From affe6062b362229e570b70d29ccf3955837330e9 Mon Sep 17 00:00:00 2001 From: Jake Lee Date: Fri, 1 Mar 2019 07:16:44 -0500 Subject: [PATCH 1/7] AP list implementation for WiFi M0 Compiles, but need sensor sample to check if it actually works --- config.cpp | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/config.cpp b/config.cpp index 589a011..33f7671 100644 --- a/config.cpp +++ b/config.cpp @@ -108,7 +108,10 @@ void print_menu() { #ifdef TRANSMITTER_WIFI Serial.println("[w] Setup wifi"); #endif - #ifdef HEATSEEK_FEATHER_WIFI_WICED + // #ifdef HEATSEEK_FEATHER_WIFI_WICED + // Serial.println("[a] List nearby access points"); + // #endif + #ifdef TRANSMITTER_WIFI Serial.println("[a] List nearby access points"); #endif Serial.println("[i] Setup Cell ID"); @@ -245,6 +248,37 @@ void enter_configuration() { break; } #endif +#ifdef HEATSEEK_FEATHER_WIFI_M0 + case 'a': { + // Derived from ScanNetworks sample of WiFi101 library + // TODO: Assuming that WiFi is available here when it totally could not be + int networkCount = 0; + networkCount = WiFi.scanNetworks(); + + Serial.println("========="); + Serial.print("Found "); Serial.print(networkCount); Serial.println(" Networks"); + + for (int i = 0; i < networkCount; i++) { + Serial.println("========="); + Serial.print("SSID: "); Serial.println(WiFi.SSID(i)); + Serial.print("RSSI: "); Serial.println(WiFi.RSSI(i)); + Serial.print("security: "); + switch (WiFi.encryptionType(i)) { + case ENC_TYPE_WEP: + Serial.println("WEP"); + case ENC_TYPE_TKIP: + Serial.println("WPA"); + case ENC_TYPE_CCMP: + Serial.println("WPA2"); + case ENC_TYPE_NONE: + Serial.println("None"); + case ENC_TYPE_AUTO: + Serial.println("Auto"); + } + } + break; + } +#endif case 'i': { char buffer[200]; int length; From 3367b3bfb97f51f584a7e62f7850f9fdf4a16b48 Mon Sep 17 00:00:00 2001 From: Jake Lee Date: Sat, 2 Mar 2019 18:33:12 -0500 Subject: [PATCH 2/7] Verified working on M0 wifi sensor --- config.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/config.cpp b/config.cpp index 33f7671..61c3fb4 100644 --- a/config.cpp +++ b/config.cpp @@ -250,9 +250,8 @@ void enter_configuration() { #endif #ifdef HEATSEEK_FEATHER_WIFI_M0 case 'a': { - // Derived from ScanNetworks sample of WiFi101 library - // TODO: Assuming that WiFi is available here when it totally could not be - int networkCount = 0; + int networkCount = -1; + WiFi.setPins(8, 7, 4, 2); networkCount = WiFi.scanNetworks(); Serial.println("========="); @@ -276,6 +275,7 @@ void enter_configuration() { Serial.println("Auto"); } } + print_menu(); break; } #endif From 5fdbbb560b2f45516fa2c3c8942206e807c8e97b Mon Sep 17 00:00:00 2001 From: Jake Lee Date: Sat, 2 Mar 2019 18:36:48 -0500 Subject: [PATCH 3/7] Combined ifdef wifi --- config.cpp | 5 ----- 1 file changed, 5 deletions(-) diff --git a/config.cpp b/config.cpp index 61c3fb4..b42b9ed 100644 --- a/config.cpp +++ b/config.cpp @@ -107,11 +107,6 @@ void print_menu() { Serial.println("[v] Calibrate temperature sensor"); #ifdef TRANSMITTER_WIFI Serial.println("[w] Setup wifi"); - #endif - // #ifdef HEATSEEK_FEATHER_WIFI_WICED - // Serial.println("[a] List nearby access points"); - // #endif - #ifdef TRANSMITTER_WIFI Serial.println("[a] List nearby access points"); #endif Serial.println("[i] Setup Cell ID"); From 4e3fd704ca7cf6454241585dc7bd4ecb0fee7ce1 Mon Sep 17 00:00:00 2001 From: Julia Guo Date: Sun, 6 Oct 2019 15:58:31 -0400 Subject: [PATCH 4/7] Updated README --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 66933c2..2c9fcfb 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,11 @@ - [Sticker Antenna](https://www.adafruit.com/product/3237) - [SIM800L GSM Breakout Module](http://www.ebay.com/itm/SIM800L-Quad-band-Network-Mini-GPRS-GSM-Breakout-Module-Ships-from-California-/172265821650?hash=item281bd7d5d2:g:97gAAOSwls5Y5qFG) +### Particle Boron (LTE) + +- Coming soon! +- All base parts +- [Particle Boron](https://docs.particle.io/boron/) ### Headseek Featherwing Board From 4b317b8ef6dc66108e5a5b1a39e5e540a25e85d3 Mon Sep 17 00:00:00 2001 From: Julia Guo Date: Fri, 22 Nov 2019 13:37:18 -0500 Subject: [PATCH 5/7] Added LTE boilerplate in transmit.cpp + user_config.h; created simple Particle project subfolder --- .vscode/c_cpp_properties.json | 17 + .vscode/settings.json | 3 + .../.vscode/c_cpp_properties.json | 18 + feather_sensor_lte/.vscode/launch.json | 92 + feather_sensor_lte/.vscode/settings.json | 11 + feather_sensor_lte/README.md | 35 + .../boron_firmware_1574447345899.bin | Bin 0 -> 5592 bytes .../Adafruit_ASFcore/Adafruit_ASFcore.h | 0 .../libraries/Adafruit_ASFcore/README.md | 33 + .../libraries/Adafruit_ASFcore/clock.h | 53 + .../Adafruit_ASFcore/clock_feature.h | 1492 +++++++++ .../libraries/Adafruit_ASFcore/compiler.h | 1157 +++++++ .../libraries/Adafruit_ASFcore/gclk.c | 522 +++ .../libraries/Adafruit_ASFcore/gclk.h | 307 ++ .../libraries/Adafruit_ASFcore/i2s.c | 750 +++++ .../libraries/Adafruit_ASFcore/i2s.h | 1404 ++++++++ .../libraries/Adafruit_ASFcore/interrupt.h | 117 + .../interrupt/interrupt_sam_nvic.c | 69 + .../interrupt/interrupt_sam_nvic.h | 172 + .../Adafruit_ASFcore/interrupt_sam_nvic.c | 86 + .../Adafruit_ASFcore/interrupt_sam_nvic.h | 189 ++ .../Adafruit_ASFcore/library.properties | 9 + .../libraries/Adafruit_ASFcore/parts.h | 1601 +++++++++ .../libraries/Adafruit_ASFcore/pinmux.c | 311 ++ .../libraries/Adafruit_ASFcore/pinmux.h | 678 ++++ .../libraries/Adafruit_ASFcore/power.h | 224 ++ .../preprocessor/mrecursion.h | 581 ++++ .../Adafruit_ASFcore/preprocessor/mrepeat.h | 321 ++ .../preprocessor/preprocessor.h | 38 + .../Adafruit_ASFcore/preprocessor/stringz.h | 67 + .../Adafruit_ASFcore/preprocessor/tpaste.h | 85 + .../libraries/Adafruit_ASFcore/reset.h | 119 + .../libraries/Adafruit_ASFcore/status_codes.h | 138 + .../libraries/Adafruit_ASFcore/system.c | 111 + .../libraries/Adafruit_ASFcore/system.h | 726 +++++ .../Adafruit_ASFcore/system_interrupt.h | 429 +++ .../system_interrupt_features.h | 195 ++ .../libraries/Adafruit_ASFcore/tc.c | 685 ++++ .../libraries/Adafruit_ASFcore/tc.h | 1783 ++++++++++ .../libraries/Adafruit_ASFcore/tc_interrupt.c | 199 ++ .../libraries/Adafruit_ASFcore/tc_interrupt.h | 179 + .../libraries/Adafruit_ASFcore/wdt.c | 264 ++ .../libraries/Adafruit_ASFcore/wdt.h | 501 +++ .../Adafruit_FONA_Library/Adafruit_FONA.cpp | 2079 ++++++++++++ .../Adafruit_FONA_Library/Adafruit_FONA.h | 263 ++ .../libraries/Adafruit_FONA_Library/README.md | 29 + .../FONA3G_setbaud/.esp8266.test.skip | 0 .../FONA3G_setbaud/FONA3G_setbaud.ino | 77 + .../FONA_SMS_Response/.esp8266.test.skip | 0 .../FONA_SMS_Response/FONA_SMS_Response.ino | 131 + .../examples/FONAtest/.esp8266.test.skip | 0 .../examples/FONAtest/FONAtest.ino | 886 +++++ .../examples/GPS/.esp8266.test.skip | 0 .../examples/GPS/GPS.ino | 112 + .../examples/IncomingCall/.esp8266.test.skip | 0 .../examples/IncomingCall/IncomingCall.ino | 62 + .../includes/FONAConfig.h | 34 + .../includes/FONAExtIncludes.h | 33 + .../includes/platform/FONAPlatStd.h | 67 + .../includes/platform/FONAPlatform.h | 62 + .../Adafruit_FONA_Library/library.properties | 9 + .../Adafruit_SleepyDog.cpp | 4 + .../Adafruit_SleepyDog.h | 28 + .../Adafruit_SleepyDog_Library/LICENSE | 22 + .../Adafruit_SleepyDog_Library/README.md | 6 + .../examples/BasicUsage/BasicUsage.ino | 62 + .../examples/Sleep/Sleep.ino | 37 + .../library.properties | 9 + .../utility/WatchdogAVR.cpp | 137 + .../utility/WatchdogAVR.h | 47 + .../utility/WatchdogKinetisK.cpp | 104 + .../utility/WatchdogKinetisK.h | 38 + .../utility/WatchdogKinetisL.cpp | 74 + .../utility/WatchdogKinetisL.h | 35 + .../utility/WatchdogSAMD.cpp | 175 + .../utility/WatchdogSAMD.h | 43 + .../libraries/ArduinoHttpClient/.gitignore | 2 + .../libraries/ArduinoHttpClient/CHANGELOG.md | 25 + .../libraries/ArduinoHttpClient/README.md | 22 + .../examples/BasicAuthGet/BasicAuthGet.ino | 69 + .../examples/BasicAuthGet/arduino_secrets.h | 3 + .../examples/CustomHeader/CustomHeader.ino | 96 + .../examples/CustomHeader/arduino_secrets.h | 3 + .../examples/DweetGet/DweetGet.ino | 107 + .../examples/DweetGet/arduino_secrets.h | 3 + .../examples/DweetPost/DweetPost.ino | 87 + .../examples/DweetPost/arduino_secrets.h | 3 + .../examples/HueBlink/HueBlink.ino | 102 + .../examples/HueBlink/arduino_secrets.h | 3 + .../PostWithHeaders/PostWithHeaders.ino | 79 + .../PostWithHeaders/arduino_secrets.h | 3 + .../examples/SimpleDelete/SimpleDelete.ino | 71 + .../examples/SimpleDelete/arduino_secrets.h | 3 + .../examples/SimpleGet/SimpleGet.ino | 66 + .../examples/SimpleGet/arduino_secrets.h | 3 + .../SimpleHttpExample/SimpleHttpExample.ino | 133 + .../SimpleHttpExample/arduino_secrets.h | 3 + .../examples/SimplePost/SimplePost.ino | 70 + .../examples/SimplePost/arduino_secrets.h | 3 + .../examples/SimplePut/SimplePut.ino | 70 + .../examples/SimplePut/arduino_secrets.h | 3 + .../SimpleWebSocket/SimpleWebSocket.ino | 80 + .../SimpleWebSocket/arduino_secrets.h | 3 + .../node_test_server/getPostPutDelete.js | 102 + .../examples/node_test_server/package.json | 13 + .../libraries/ArduinoHttpClient/keywords.txt | 64 + .../libraries/ArduinoHttpClient/library.json | 12 + .../ArduinoHttpClient/library.properties | 10 + .../ArduinoHttpClient/src/ArduinoHttpClient.h | 11 + .../ArduinoHttpClient/src/HttpClient.cpp | 862 +++++ .../ArduinoHttpClient/src/HttpClient.h | 392 +++ .../ArduinoHttpClient/src/WebSocketClient.cpp | 372 +++ .../ArduinoHttpClient/src/WebSocketClient.h | 99 + .../libraries/ArduinoHttpClient/src/b64.cpp | 72 + .../libraries/ArduinoHttpClient/src/b64.h | 6 + .../libraries/DHT/.github/ISSUE_TEMPLATE.md | 46 + .../DHT/.github/PULL_REQUEST_TEMPLATE.md | 26 + feather_sensor_lte/libraries/DHT/DHT.cpp | 259 ++ feather_sensor_lte/libraries/DHT/DHT.h | 75 + feather_sensor_lte/libraries/DHT/DHT_U.cpp | 179 + feather_sensor_lte/libraries/DHT/DHT_U.h | 78 + feather_sensor_lte/libraries/DHT/README.md | 15 + .../DHT_Unified_Sensor/DHT_Unified_Sensor.ino | 84 + .../DHT/examples/DHTtester/DHTtester.ino | 69 + feather_sensor_lte/libraries/DHT/keywords.txt | 22 + .../libraries/DHT/library.properties | 9 + .../RTClib/.github/ISSUE_TEMPLATE.md | 46 + .../RTClib/.github/PULL_REQUEST_TEMPLATE.md | 26 + feather_sensor_lte/libraries/RTClib/README.md | 42 + .../libraries/RTClib/RTClib.cpp | 506 +++ feather_sensor_lte/libraries/RTClib/RTClib.h | 135 + .../RTClib/examples/datecalc/datecalc.ino | 111 + .../RTClib/examples/ds1307/ds1307.ino | 71 + .../examples/ds1307SqwPin/ds1307SqwPin.ino | 68 + .../examples/ds1307nvram/ds1307nvram.ino | 63 + .../RTClib/examples/ds3231/ds3231.ino | 77 + .../RTClib/examples/pcf8523/pcf8523.ino | 74 + .../RTClib/examples/softrtc/softrtc.ino | 61 + .../libraries/RTClib/keywords.txt | 37 + .../libraries/RTClib/library.properties | 9 + .../libraries/WiFi101/.travis.yml | 48 + .../libraries/WiFi101/CHANGELOG | 122 + .../libraries/WiFi101/README.adoc | 27 + .../AP_SimpleWebServer/AP_SimpleWebServer.ino | 176 + .../AP_SimpleWebServer/arduino_secrets.h | 3 + .../CheckWifi101FirmwareVersion.ino | 67 + .../ConnectNoEncryption.ino | 123 + .../ConnectNoEncryption/arduino_secrets.h | 1 + .../ConnectWithWEP/ConnectWithWEP.ino | 129 + .../examples/ConnectWithWEP/arduino_secrets.h | 3 + .../ConnectWithWPA/ConnectWithWPA.ino | 119 + .../examples/ConnectWithWPA/arduino_secrets.h | 3 + .../examples/FirmwareUpdater/Endianess.ino | 62 + .../FirmwareUpdater/FirmwareUpdater.ino | 129 + .../MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino | 170 + .../MDNS_WiFiWebServer/arduino_secrets.h | 3 + .../Provisioning_WiFiWebServer.ino | 167 + .../examples/ScanNetworks/ScanNetworks.ino | 120 + .../ScanNetworksAdvanced.ino | 149 + .../SimpleWebServerWiFi.ino | 131 + .../SimpleWebServerWiFi/arduino_secrets.h | 3 + .../WiFiChatServer/WiFiChatServer.ino | 114 + .../examples/WiFiChatServer/arduino_secrets.h | 3 + .../WiFi101/examples/WiFiPing/WiFiPing.ino | 140 + .../examples/WiFiPing/arduino_secrets.h | 3 + .../examples/WiFiSSLClient/WiFiSSLClient.ino | 107 + .../examples/WiFiSSLClient/arduino_secrets.h | 3 + .../WiFiUdpNtpClient/WiFiUdpNtpClient.ino | 182 ++ .../WiFiUdpNtpClient/arduino_secrets.h | 3 + .../WiFiUdpSendReceiveString.ino | 113 + .../arduino_secrets.h | 3 + .../examples/WiFiWebClient/WiFiWebClient.ino | 121 + .../examples/WiFiWebClient/arduino_secrets.h | 3 + .../WiFiWebClientRepeating.ino | 127 + .../WiFiWebClientRepeating/arduino_secrets.h | 3 + .../examples/WiFiWebServer/WiFiWebServer.ino | 135 + .../examples/WiFiWebServer/arduino_secrets.h | 3 + .../libraries/WiFi101/keywords.txt | 61 + .../libraries/WiFi101/library.properties | 10 + .../libraries/WiFi101/src/WiFi.cpp | 1106 +++++++ .../libraries/WiFi101/src/WiFi101.h | 193 ++ .../libraries/WiFi101/src/WiFiClient.cpp | 308 ++ .../libraries/WiFi101/src/WiFiClient.h | 68 + .../WiFi101/src/WiFiMDNSResponder.cpp | 220 ++ .../libraries/WiFi101/src/WiFiMDNSResponder.h | 51 + .../libraries/WiFi101/src/WiFiSSLClient.cpp | 45 + .../libraries/WiFi101/src/WiFiSSLClient.h | 36 + .../libraries/WiFi101/src/WiFiServer.cpp | 140 + .../libraries/WiFi101/src/WiFiServer.h | 49 + .../libraries/WiFi101/src/WiFiUdp.cpp | 289 ++ .../libraries/WiFi101/src/WiFiUdp.h | 89 + .../WiFi101/src/bsp/include/nm_bsp.h | 283 ++ .../WiFi101/src/bsp/include/nm_bsp_arduino.h | 74 + .../WiFi101/src/bsp/include/nm_bsp_avr.h | 54 + .../WiFi101/src/bsp/include/nm_bsp_internal.h | 59 + .../WiFi101/src/bsp/include/nm_bsp_samd21.h | 52 + .../WiFi101/src/bsp/source/nm_bsp_arduino.c | 205 ++ .../src/bsp/source/nm_bsp_arduino_avr.c | 164 + .../src/bus_wrapper/include/nm_bus_wrapper.h | 177 + .../source/nm_bus_wrapper_samd21.cpp | 200 ++ .../WiFi101/src/common/include/nm_common.h | 153 + .../WiFi101/src/common/include/nm_debug.h | 95 + .../WiFi101/src/common/source/nm_common.c | 136 + .../WiFi101/src/driver/include/ecc_types.h | 245 ++ .../WiFi101/src/driver/include/m2m_ate_mode.h | 732 +++++ .../WiFi101/src/driver/include/m2m_crypto.h | 272 ++ .../WiFi101/src/driver/include/m2m_ota.h | 428 +++ .../WiFi101/src/driver/include/m2m_periph.h | 411 +++ .../WiFi101/src/driver/include/m2m_ssl.h | 182 ++ .../WiFi101/src/driver/include/m2m_types.h | 2383 ++++++++++++++ .../WiFi101/src/driver/include/m2m_wifi.h | 2882 +++++++++++++++++ .../WiFi101/src/driver/source/m2m_ate_mode.c | 826 +++++ .../WiFi101/src/driver/source/m2m_crypto.c | 1010 ++++++ .../WiFi101/src/driver/source/m2m_hif.c | 767 +++++ .../WiFi101/src/driver/source/m2m_hif.h | 249 ++ .../WiFi101/src/driver/source/m2m_ota.c | 417 +++ .../WiFi101/src/driver/source/m2m_periph.c | 187 ++ .../WiFi101/src/driver/source/m2m_ssl.c | 309 ++ .../WiFi101/src/driver/source/m2m_wifi.c | 1522 +++++++++ .../WiFi101/src/driver/source/nmasic.c | 688 ++++ .../WiFi101/src/driver/source/nmasic.h | 215 ++ .../WiFi101/src/driver/source/nmbus.c | 301 ++ .../WiFi101/src/driver/source/nmbus.h | 147 + .../WiFi101/src/driver/source/nmdrv.c | 402 +++ .../WiFi101/src/driver/source/nmdrv.h | 138 + .../WiFi101/src/driver/source/nmi2c.c | 269 ++ .../WiFi101/src/driver/source/nmi2c.h | 104 + .../WiFi101/src/driver/source/nmspi.c | 1401 ++++++++ .../WiFi101/src/driver/source/nmspi.h | 132 + .../WiFi101/src/driver/source/nmuart.c | 536 +++ .../WiFi101/src/driver/source/nmuart.h | 118 + .../src/socket/include/m2m_socket_host_if.h | 461 +++ .../WiFi101/src/socket/include/socket.h | 2065 ++++++++++++ .../src/socket/include/socket_buffer.h | 94 + .../WiFi101/src/socket/source/socket.c | 1445 +++++++++ .../WiFi101/src/socket/source/socket_buffer.c | 232 ++ .../src/socket/source/socket_internal.h | 71 + .../WiFi101/src/spi_flash/include/spi_flash.h | 233 ++ .../src/spi_flash/include/spi_flash_map.h | 245 ++ .../WiFi101/src/spi_flash/source/spi_flash.c | 770 +++++ feather_sensor_lte/project.properties | 1 + feather_sensor_lte/src/feather_sensor_lte.ino | 49 + transmit.cpp | 41 + user_config.h | 3 +- 244 files changed, 55871 insertions(+), 1 deletion(-) create mode 100644 .vscode/c_cpp_properties.json create mode 100644 .vscode/settings.json create mode 100644 feather_sensor_lte/.vscode/c_cpp_properties.json create mode 100644 feather_sensor_lte/.vscode/launch.json create mode 100644 feather_sensor_lte/.vscode/settings.json create mode 100644 feather_sensor_lte/README.md create mode 100644 feather_sensor_lte/boron_firmware_1574447345899.bin create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/Adafruit_ASFcore.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/README.md create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/clock.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/clock_feature.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/compiler.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/gclk.c create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/gclk.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/i2s.c create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/i2s.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/library.properties create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/parts.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/pinmux.c create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/pinmux.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/power.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/stringz.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/tpaste.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/reset.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/status_codes.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/system.c create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/system.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/system_interrupt.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/system_interrupt_features.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/tc.c create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/tc.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/tc_interrupt.c create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/tc_interrupt.h create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/wdt.c create mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/wdt.h create mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp create mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.h create mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/README.md create mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/.esp8266.test.skip create mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino create mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/.esp8266.test.skip create mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino create mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/.esp8266.test.skip create mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino create mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/GPS/.esp8266.test.skip create mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino create mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/.esp8266.test.skip create mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino create mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/FONAConfig.h create mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h create mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h create mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h create mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/library.properties create mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp create mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h create mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/LICENSE create mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/README.md create mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino create mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino create mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/library.properties create mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp create mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h create mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp create mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h create mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp create mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h create mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp create mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/.gitignore create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/CHANGELOG.md create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/README.md create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/node_test_server/package.json create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/keywords.txt create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/library.json create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/library.properties create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/src/HttpClient.cpp create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/src/HttpClient.h create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/src/WebSocketClient.cpp create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/src/WebSocketClient.h create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/src/b64.cpp create mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/src/b64.h create mode 100644 feather_sensor_lte/libraries/DHT/.github/ISSUE_TEMPLATE.md create mode 100644 feather_sensor_lte/libraries/DHT/.github/PULL_REQUEST_TEMPLATE.md create mode 100644 feather_sensor_lte/libraries/DHT/DHT.cpp create mode 100644 feather_sensor_lte/libraries/DHT/DHT.h create mode 100644 feather_sensor_lte/libraries/DHT/DHT_U.cpp create mode 100644 feather_sensor_lte/libraries/DHT/DHT_U.h create mode 100644 feather_sensor_lte/libraries/DHT/README.md create mode 100644 feather_sensor_lte/libraries/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino create mode 100644 feather_sensor_lte/libraries/DHT/examples/DHTtester/DHTtester.ino create mode 100644 feather_sensor_lte/libraries/DHT/keywords.txt create mode 100644 feather_sensor_lte/libraries/DHT/library.properties create mode 100644 feather_sensor_lte/libraries/RTClib/.github/ISSUE_TEMPLATE.md create mode 100644 feather_sensor_lte/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md create mode 100644 feather_sensor_lte/libraries/RTClib/README.md create mode 100644 feather_sensor_lte/libraries/RTClib/RTClib.cpp create mode 100644 feather_sensor_lte/libraries/RTClib/RTClib.h create mode 100644 feather_sensor_lte/libraries/RTClib/examples/datecalc/datecalc.ino create mode 100644 feather_sensor_lte/libraries/RTClib/examples/ds1307/ds1307.ino create mode 100644 feather_sensor_lte/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino create mode 100644 feather_sensor_lte/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino create mode 100644 feather_sensor_lte/libraries/RTClib/examples/ds3231/ds3231.ino create mode 100644 feather_sensor_lte/libraries/RTClib/examples/pcf8523/pcf8523.ino create mode 100644 feather_sensor_lte/libraries/RTClib/examples/softrtc/softrtc.ino create mode 100644 feather_sensor_lte/libraries/RTClib/keywords.txt create mode 100644 feather_sensor_lte/libraries/RTClib/library.properties create mode 100644 feather_sensor_lte/libraries/WiFi101/.travis.yml create mode 100644 feather_sensor_lte/libraries/WiFi101/CHANGELOG create mode 100644 feather_sensor_lte/libraries/WiFi101/README.adoc create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino create mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h create mode 100644 feather_sensor_lte/libraries/WiFi101/keywords.txt create mode 100644 feather_sensor_lte/libraries/WiFi101/library.properties create mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFi.cpp create mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFi101.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiClient.cpp create mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiClient.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiMDNSResponder.cpp create mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiMDNSResponder.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiSSLClient.cpp create mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiSSLClient.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiServer.cpp create mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiServer.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiUdp.cpp create mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiUdp.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c create mode 100644 feather_sensor_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c create mode 100644 feather_sensor_lte/libraries/WiFi101/src/bus_wrapper/include/nm_bus_wrapper.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp create mode 100644 feather_sensor_lte/libraries/WiFi101/src/common/include/nm_common.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/common/include/nm_debug.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/common/source/nm_common.c create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/include/ecc_types.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_ate_mode.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_crypto.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_ota.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_periph.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_ssl.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_types.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_wifi.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ate_mode.c create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_crypto.c create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_hif.c create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_hif.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ota.c create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_periph.c create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ssl.c create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_wifi.c create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmasic.c create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmasic.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmbus.c create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmbus.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmdrv.c create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmdrv.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmi2c.c create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmi2c.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmspi.c create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmspi.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmuart.c create mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmuart.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/socket/include/socket.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/socket/include/socket_buffer.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/socket/source/socket.c create mode 100644 feather_sensor_lte/libraries/WiFi101/src/socket/source/socket_buffer.c create mode 100644 feather_sensor_lte/libraries/WiFi101/src/socket/source/socket_internal.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/spi_flash/include/spi_flash.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h create mode 100644 feather_sensor_lte/libraries/WiFi101/src/spi_flash/source/spi_flash.c create mode 100644 feather_sensor_lte/project.properties create mode 100644 feather_sensor_lte/src/feather_sensor_lte.ino diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..1df4412 --- /dev/null +++ b/.vscode/c_cpp_properties.json @@ -0,0 +1,17 @@ +{ + "configurations": [ + { + "name": "Win32", + "includePath": [ + "${workspaceFolder}/**" + ], + "defines": [ + "_DEBUG", + "UNICODE", + "_UNICODE" + ], + "intelliSenseMode": "msvc-x64" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..3b66410 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "git.ignoreLimitWarning": true +} \ No newline at end of file diff --git a/feather_sensor_lte/.vscode/c_cpp_properties.json b/feather_sensor_lte/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..c16b552 --- /dev/null +++ b/feather_sensor_lte/.vscode/c_cpp_properties.json @@ -0,0 +1,18 @@ +{ + "configurations": [ + { + "name": "Win32", + "includePath": [ + "${workspaceFolder}/**" + ], + "defines": [ + "_DEBUG", + "UNICODE", + "_UNICODE" + ], + "intelliSenseMode": "msvc-x64", + "configurationProvider": "particle.particle-vscode-core" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/feather_sensor_lte/.vscode/launch.json b/feather_sensor_lte/.vscode/launch.json new file mode 100644 index 0000000..4532e35 --- /dev/null +++ b/feather_sensor_lte/.vscode/launch.json @@ -0,0 +1,92 @@ +{ + "version": "0.1.0", + "configurations": [ + { + "type": "cortex-debug", + "request": "attach", + "name": "Particle Debugger (photon, p1, electron)", + "servertype": "openocd", + "interface": "swd", + "device": "STM32F205RG", + "cwd": "${workspaceRoot}", + "executable": "${command:particle.getDebuggerExecutable}", + "preLaunchTask": "Particle: Flash application for debug (local)", + "armToolchainPath": "${command:particle.getDebuggerCompilerDir}", + "svdFile": "${command:particle.getDebuggerSVDFile}", + "searchDir": [ + "${command:particle.getDebuggerSearchDir}" + ], + "configFiles": [ + "interface/cmsis-dap.cfg", + "target/stm32f2x.cfg" + ], + "postAttachCommands": [ + "monitor reset halt" + ], + "windows": { + "configFiles": [ + "interface\\cmsis-dap.cfg", + "target\\stm32f2x.cfg" + ] + } + }, + { + "type": "cortex-debug", + "request": "attach", + "name": "Particle Debugger (argon, boron / bsom, xenon)", + "servertype": "openocd", + "interface": "swd", + "device": "nRF52840_xxAA", + "cwd": "${workspaceRoot}", + "executable": "${command:particle.getDebuggerExecutable}", + "preLaunchTask": "Particle: Flash application for debug (local)", + "armToolchainPath": "${command:particle.getDebuggerCompilerDir}", + "svdFile": "${command:particle.getDebuggerSVDFile}", + "searchDir": [ + "${command:particle.getDebuggerSearchDir}" + ], + "configFiles": [ + "interface/cmsis-dap.cfg", + "target/nrf52-particle.cfg" + ], + "postAttachCommands": [ + "monitor reset halt" + ], + "windows": { + "configFiles": [ + "interface\\cmsis-dap.cfg", + "target\\nrf52-particle.cfg" + ] + } + }, + { + "type": "cortex-debug", + "request": "attach", + "name": "Particle Programmer Shield v1.0 (photon, p1, electron)", + "servertype": "openocd", + "interface": "swd", + "device": "STM32F205RG", + "cwd": "${workspaceRoot}", + "executable": "${command:particle.getDebuggerExecutable}", + "preLaunchTask": "Particle: Flash application for debug (local)", + "armToolchainPath": "${command:particle.getDebuggerCompilerDir}", + "svdFile": "${command:particle.getDebuggerSVDFile}", + "searchDir": [ + "${command:particle.getDebuggerSearchDir}" + ], + "configFiles": [ + "interface/particle-ftdi.cfg", + "target/stm32f2x.cfg" + ], + "postAttachCommands": [ + "monitor reset halt" + ], + "windows": { + "configFiles": [ + "interface\\particle-ftdi.cfg", + "target\\stm32f2x.cfg" + ] + } + } + ] +} \ No newline at end of file diff --git a/feather_sensor_lte/.vscode/settings.json b/feather_sensor_lte/.vscode/settings.json new file mode 100644 index 0000000..185ece2 --- /dev/null +++ b/feather_sensor_lte/.vscode/settings.json @@ -0,0 +1,11 @@ +{ + "extensions.ignoreRecommendations": true, + "cortex-debug.openocdPath": "${command:particle.getDebuggerOpenocdPath}", + "files.associations": { + "*.ino": "cpp" + }, + "particle.targetDevice": "e00fce68ec3e4cd7fe833f2e", + "particle.firmwareVersion": "1.1.0", + "particle.targetPlatform": "boron", + "git.ignoreLimitWarning": true +} \ No newline at end of file diff --git a/feather_sensor_lte/README.md b/feather_sensor_lte/README.md new file mode 100644 index 0000000..d7c8ea2 --- /dev/null +++ b/feather_sensor_lte/README.md @@ -0,0 +1,35 @@ +# feather_sensor_lte + +A Particle project named feather_sensor_lte + +## Welcome to your project! + +Every new Particle project is composed of 3 important elements that you'll see have been created in your project directory for feather_sensor_lte. + +#### ```/src``` folder: +This is the source folder that contains the firmware files for your project. It should *not* be renamed. +Anything that is in this folder when you compile your project will be sent to our compile service and compiled into a firmware binary for the Particle device that you have targeted. + +If your application contains multiple files, they should all be included in the `src` folder. If your firmware depends on Particle libraries, those dependencies are specified in the `project.properties` file referenced below. + +#### ```.ino``` file: +This file is the firmware that will run as the primary application on your Particle device. It contains a `setup()` and `loop()` function, and can be written in Wiring or C/C++. For more information about using the Particle firmware API to create firmware for your Particle device, refer to the [Firmware Reference](https://docs.particle.io/reference/firmware/) section of the Particle documentation. + +#### ```project.properties``` file: +This is the file that specifies the name and version number of the libraries that your project depends on. Dependencies are added automatically to your `project.properties` file when you add a library to a project using the `particle library add` command in the CLI or add a library in the Desktop IDE. + +## Adding additional files to your project + +#### Projects with multiple sources +If you would like add additional files to your application, they should be added to the `/src` folder. All files in the `/src` folder will be sent to the Particle Cloud to produce a compiled binary. + +#### Projects with external libraries +If your project includes a library that has not been registered in the Particle libraries system, you should create a new folder named `/lib//src` under `/` and add the `.h`, `.cpp` & `library.properties` files for your library there. Read the [Firmware Libraries guide](https://docs.particle.io/guide/tools-and-features/libraries/) for more details on how to develop libraries. Note that all contents of the `/lib` folder and subfolders will also be sent to the Cloud for compilation. + +## Compiling your project + +When you're ready to compile your project, make sure you have the correct Particle device target selected and run `particle compile ` in the CLI or click the Compile button in the Desktop IDE. The following files in your project folder will be sent to the compile service: + +- Everything in the `/src` folder, including your `.ino` application file +- The `project.properties` file for your project +- Any libraries stored under `lib//src` diff --git a/feather_sensor_lte/boron_firmware_1574447345899.bin b/feather_sensor_lte/boron_firmware_1574447345899.bin new file mode 100644 index 0000000000000000000000000000000000000000..544964835a60d84338704d5bd1234e633fc8cef4 GIT binary patch literal 5592 zcmd5=e{d9c6@PoXm%IEpxKOBP0?ghmXAchWXj;9NIunv~6LJX@soEAh-ZeSgND{6g zv1!FINUL;er>&(UE!JrT9O{V8)t*Cu?Ku{m))u|AD0ILPwKcS~y1|xP@@xHkckdS& z$G;rMo%!7Nz3;yFzVF9(-}jqPy^BtM&P7CJ!Uh zK!cF^yzUR}Y38oi#}d%H4mwk}Vr^~yVJGAzT|MutCvA&L+6N<~T^OOk;fW!wzC6*) zNqi#FOyo?JML4f#7ioW(5lqU``Q1yD9>m(rmvCxM`<%AGF3wBZ$r;WoLOL_E{=@qc zq&+_!*hQFsWd^etkDK%A`7qXf7Cz-|kfy^YTclR0Rk+8UYMYJ6+9uz1CBJDFzjqdY zW)@%jl`HivK2Wf~$$Ver_s-(a%;IaeFndM$O|$sg?knG0@!V8c?~EB=k*_uVE%H`; zMc#_9$XoFhc`KeGZ~0&3Eqk4X_4k_Vw-oqVbNwQ3$rpJm-Xg!rjIV?@?Rg6JEd3&X z#QL z%y|`9Tw~b0L$Xh1^lF2CutWCBwDP(PExmShn_>&vG8Mt{%(8Qb$7$|0nY+8fvapJ@ zHz&k%BbZs7>F=ucaR*7OnkkbW*5`+~L&CU|_gv>uZdaDc{4bq#`x+L=*-`GfvV)F8 zqB#rFv3{i1ne9aJLH}+LHRT<%263uJ+adyJ?r&RV^ zY5sc5Uzhn?le67u+D@cy-Y&>aDr4KVdU}gLmt7BFBQl(nsgz8aNHTRT~bheg9%3HkP z{$N(Ja>~)_SZi+~%{|Gtgw^-o!F>WyfLj4plXsendwl@evpU721!^xSwo@O$nBVpH zs>NN8`$eI9+*#172W9Q`M)N(huu_H3Z2|u>nY;xY#Z4>O>$z`tj}MLTD9Lc$*Rj}k~&!4x9yACvCBEhDSP`n`m14OzbUhD zql?_B`94U(uTgU@gnQAqhq;6Jf()w;ZnF+;lhGviW3TLJF|wm(6f1Zho_A8@OmPPqmj8f+bWb&wugiX6UY@QB%++KH}p6*?Se z_BYmxoT;iv9eU912Cvk1?P;b!`B`VA12d1#v5(~Q^Uyq zY?6z3qE2-=?#Yf6N%VM)yj8o0GqTYse)vvZm?Uzf8h2F$otayL<)h^|WmhN7Hy1q3 zM)n<}>|CkV%{i^}sE-?Kd~Fg{*Un8iB3C6vnfZVYf!d}g$;-E>=iT^EN@H0ZwKgVdfGcDlU(A5M^lPdI*wMo)`IuXRa@X7(~ z4c2XNcBs6v7iUN)_0Vu7_VUB}5;wPOPrAbA8kdBhOsculLH$*Y!yG!fQVn?~DgkD+D@)oEnP*$IrYf3U(6Gw2K z<1DvwS%r1GkxQI=xqdm<{7wfi-?=KsZJvGI65odM+fB$^pFr`B|eLwW;L9@Lv7klT) zsX%i7cqMNOa;Hgjt44MhJNdU$&Lp?|(pyHhdK%}-v}zTQO6h4oUbN&HRv~T^nB2n96hf@#$6&ar$nZzM5dxdhVA)oi5*{w9kImD;u4vKB{DT7GAx$7&n%XFTr8G+Tr8Hn42vZ%!(z$H zFrU8gmd?fwiT|wHng?x)*cf`VK0zHA3uhO|7 zEt?$m)NtWM^CJB3=XT%$;6b4Dd7#Nfj{r{s`+!5h2=FUl6nG2xEARo3e}cFxdx4Ju zE`S3*y4gkV0)GZh0VjY`9oA>AVfVS*!}``C-~k{GJPbSmJPjNG^3OY<%UfKu0QdsV zrg8AoKo;OJH-_;7kbgdgJBth8ff2mV0vCWk0jGcyz{^0XZ|t7)9Iz8$YkVE!mw~Oo zKHwf82IQaSRu|m>tOo8Ne=tfOAR z?uqsFQoOHkYabTw?dqUdcXvKH7{Af(q5)tF5Cc93tOY&;Tn_{RFHl;867~No*$8VN zUxU4X{rDF4sTXyuMvYehYk+e2@gVR=;MH|5YG04{x47u{KIr~kO#?Ku+fSs8q`McqAq MGC(&!fBm2T1#!eoE&u=k literal 0 HcmV?d00001 diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/Adafruit_ASFcore.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/Adafruit_ASFcore.h new file mode 100644 index 0000000..e69de29 diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/README.md b/feather_sensor_lte/libraries/Adafruit_ASFcore/README.md new file mode 100644 index 0000000..8de73c7 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/README.md @@ -0,0 +1,33 @@ +# ASF (Atmel Software Framework) for Arduino Zero / Adafruit Feather M0 (SAMD21) + +Copy of ASF (Atmel Software Framework) excerpts for the SAMD21 processor used in the Arduino Zero / Adafruit Feather M0 boards. +You typically won't use this library directly, instead other libraries will depend on this library and use the code +within it to simplify their implementation. + +All code is taken directly from Atmel's ASF: http://www.atmel.com/tools/avrsoftwareframework.aspx?tab=overview + +The code is copyright Atmel and released by them under the following license: + + 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. The name of Atmel may not be used to endorse or promote products derived from this software without specific + prior written permission. + + 4. This software may only be redistributed and used in connection with an Atmel microcontroller product. + + THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN + NO EVENT SHALL ATMEL 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. diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/clock.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/clock.h new file mode 100644 index 0000000..549e3e9 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/clock.h @@ -0,0 +1,53 @@ +/** + * \file + * + * \brief SAM Clock Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef SYSTEM_CLOCK_H_INCLUDED +#define SYSTEM_CLOCK_H_INCLUDED + +#include "compiler.h" +#include "gclk.h" +#include "clock_feature.h" + +#endif /* SYSTEM_CLOCK_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/clock_feature.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/clock_feature.h new file mode 100644 index 0000000..be63c7c --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/clock_feature.h @@ -0,0 +1,1492 @@ +/** + * \file + * + * \brief SAM Clock Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef SYSTEM_CLOCK_FEATURE_H_INCLUDED +#define SYSTEM_CLOCK_FEATURE_H_INCLUDED + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup asfdoc_sam0_system_clock_group SAM System Clock Management Driver (SYSTEM CLOCK) + * + * This driver for Atmel® | SMART ARM®-based microcontrollers provides an interface for the configuration + * and management of the device's clocking related functions. This includes + * the various clock sources, bus clocks, and generic clocks within the device, + * with functions to manage the enabling, disabling, source selection, and + * prescaling of clocks to various internal peripherals. + * + * The following peripherals are used by this module: + * + * - GCLK (Generic Clock Management) + * - PM (Power Management) + * - SYSCTRL (Clock Source Control) + * + * The following devices can use this module: + * - Atmel | SMART SAM D20/D21 + * - Atmel | SMART SAM R21 + * - Atmel | SMART SAM D10/D11 + * - Atmel | SMART SAM DA0/DA1 + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_system_clock_prerequisites + * - \ref asfdoc_sam0_system_clock_module_overview + * - \ref asfdoc_sam0_system_clock_special_considerations + * - \ref asfdoc_sam0_system_clock_extra_info + * - \ref asfdoc_sam0_system_clock_examples + * - \ref asfdoc_sam0_system_clock_api_overview + * + * + * \section asfdoc_sam0_system_clock_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * + * \section asfdoc_sam0_system_clock_module_overview Module Overview + * The SAM devices contain a sophisticated clocking system, which is designed + * to give the maximum flexibility to the user application. This system allows + * a system designer to tune the performance and power consumption of the device + * in a dynamic manner, to achieve the best trade-off between the two for a + * particular application. + * + * This driver provides a set of functions for the configuration and management + * of the various clock related functionality within the device. + * + * \subsection asfdoc_sam0_system_clock_module_features Driver Feature Macro Definition + * + * + * + * + * + * + * + * + * + *
Driver Feature MacroSupported devices
FEATURE_SYSTEM_CLOCK_DPLLSAMD21, SAMR21, SAMD10, SAMD11, SAMDAx
+ * \note The specific features are only available in the driver when the + * selected device supports those features. + * + * \subsection asfdoc_sam0_system_clock_module_overview_clock_sources Clock Sources + * The SAM devices have a number of master clock source modules, each of + * which being capable of producing a stabilized output frequency, which can then + * be fed into the various peripherals and modules within the device. + * + * Possible clock source modules include internal R/C oscillators, internal + * DFLL modules, as well as external crystal oscillators and/or clock inputs. + * + * \subsection asfdoc_sam0_system_clock_module_overview_cpu_clock CPU / Bus Clocks + * The CPU and AHB/APBx buses are clocked by the same physical clock source + * (referred in this module as the Main Clock), however the APBx buses may + * have additional prescaler division ratios set to give each peripheral bus a + * different clock speed. + * + * The general main clock tree for the CPU and associated buses is shown in + * \ref asfdoc_sam0_system_clock_module_clock_tree "the figure below". + * + * \anchor asfdoc_sam0_system_clock_module_clock_tree + * \dot + * digraph overview { + * rankdir=LR; + * clk_src [label="Clock Sources", shape=none, height=0]; + * node [label="CPU Bus" shape=ellipse] cpu_bus; + * node [label="AHB Bus" shape=ellipse] ahb_bus; + * node [label="APBA Bus" shape=ellipse] apb_a_bus; + * node [label="APBB Bus" shape=ellipse] apb_b_bus; + * node [label="APBC Bus" shape=ellipse] apb_c_bus; + * node [label="Main Bus\nPrescaler" shape=square] main_prescaler; + * node [label="APBA Bus\nPrescaler" shape=square] apb_a_prescaler; + * node [label="APBB Bus\nPrescaler" shape=square] apb_b_prescaler; + * node [label="APBC Bus\nPrescaler" shape=square] apb_c_prescaler; + * node [label="", shape=polygon, sides=4, distortion=0.6, orientation=90, style=filled, fillcolor=black, height=0.9, width=0.2] main_clock_mux; + * + * clk_src -> main_clock_mux; + * main_clock_mux -> main_prescaler; + * main_prescaler -> cpu_bus; + * main_prescaler -> ahb_bus; + * main_prescaler -> apb_a_prescaler; + * main_prescaler -> apb_b_prescaler; + * main_prescaler -> apb_c_prescaler; + * apb_a_prescaler -> apb_a_bus; + * apb_b_prescaler -> apb_b_bus; + * apb_c_prescaler -> apb_c_bus; + * } + * \enddot + * + * \subsection asfdoc_sam0_system_clock_module_overview_clock_masking Clock Masking + * To save power, the input clock to one or more peripherals on the AHB and APBx + * buses can be masked away - when masked, no clock is passed into the module. + * Disabling of clocks of unused modules will prevent all access to the masked + * module, but will reduce the overall device power consumption. + * + * \subsection asfdoc_sam0_system_clock_module_overview_gclk Generic Clocks + * Within the SAM devices there are a number of Generic Clocks; these are used to + * provide clocks to the various peripheral clock domains in the device in a + * standardized manner. One or more master source clocks can be selected as the + * input clock to a Generic Clock Generator, which can prescale down the input + * frequency to a slower rate for use in a peripheral. + * + * Additionally, a number of individually selectable Generic Clock Channels are + * provided, which multiplex and gate the various generator outputs for one or + * more peripherals within the device. This setup allows for a single common + * generator to feed one or more channels, which can then be enabled or disabled + * individually as required. + * + * \anchor asfdoc_sam0_system_clock_module_chain_overview + * \dot + * digraph overview { + * rankdir=LR; + * node [label="Clock\nSource a" shape=square] system_clock_source; + * node [label="Generator 1" shape=square] clock_gen; + * node [label="Channel x" shape=square] clock_chan0; + * node [label="Channel y" shape=square] clock_chan1; + * node [label="Peripheral x" shape=ellipse style=filled fillcolor=lightgray] peripheral0; + * node [label="Peripheral y" shape=ellipse style=filled fillcolor=lightgray] peripheral1; + * + * system_clock_source -> clock_gen; + * clock_gen -> clock_chan0; + * clock_chan0 -> peripheral0; + * clock_gen -> clock_chan1; + * clock_chan1 -> peripheral1; + * } + * \enddot + * + * \subsubsection asfdoc_sam0_system_clock_module_chain_example Clock Chain Example + * An example setup of a complete clock chain within the device is shown in + * \ref asfdoc_sam0_system_clock_module_chain_example_fig "the figure below". + * + * \anchor asfdoc_sam0_system_clock_module_chain_example_fig + * \dot + * digraph overview { + * rankdir=LR; + * node [label="External\nOscillator" shape=square] system_clock_source0; + * node [label="Generator 0" shape=square] clock_gen0; + * node [label="Channel x" shape=square] clock_chan0; + * node [label="Core CPU" shape=ellipse style=filled fillcolor=lightgray] peripheral0; + * + * system_clock_source0 -> clock_gen0; + * clock_gen0 -> clock_chan0; + * clock_chan0 -> peripheral0; + * node [label="8MHz R/C\nOscillator (OSC8M)" shape=square fillcolor=white] system_clock_source1; + * node [label="Generator 1" shape=square] clock_gen1; + * node [label="Channel y" shape=square] clock_chan1; + * node [label="Channel z" shape=square] clock_chan2; + * node [label="SERCOM\nModule" shape=ellipse style=filled fillcolor=lightgray] peripheral1; + * node [label="Timer\nModule" shape=ellipse style=filled fillcolor=lightgray] peripheral2; + * + * system_clock_source1 -> clock_gen1; + * clock_gen1 -> clock_chan1; + * clock_gen1 -> clock_chan2; + * clock_chan1 -> peripheral1; + * clock_chan2 -> peripheral2; + * } + * \enddot + * + * \subsubsection asfdoc_sam0_system_clock_module_overview_gclk_generators Generic Clock Generators + * Each Generic Clock generator within the device can source its input clock + * from one of the provided Source Clocks, and prescale the output for one or + * more Generic Clock Channels in a one-to-many relationship. The generators + * thus allow for several clocks to be generated of different frequencies, + * power usages, and accuracies, which can be turned on and off individually to + * disable the clocks to multiple peripherals as a group. + * + * \subsubsection asfdoc_sam0_system_clock_module_overview_gclk_channels Generic Clock Channels + * To connect a Generic Clock Generator to a peripheral within the + * device, a Generic Clock Channel is used. Each peripheral or + * peripheral group has an associated Generic Clock Channel, which serves as the + * clock input for the peripheral(s). To supply a clock to the peripheral + * module(s), the associated channel must be connected to a running Generic + * Clock Generator and the channel enabled. + * + * \section asfdoc_sam0_system_clock_special_considerations Special Considerations + * + * There are no special considerations for this module. + * + * + * \section asfdoc_sam0_system_clock_extra_info Extra Information + * + * For extra information, see \ref asfdoc_sam0_system_clock_extra. This includes: + * - \ref asfdoc_sam0_system_clock_extra_acronyms + * - \ref asfdoc_sam0_system_clock_extra_dependencies + * - \ref asfdoc_sam0_system_clock_extra_errata + * - \ref asfdoc_sam0_system_clock_extra_history + * + * + * \section asfdoc_sam0_system_clock_examples Examples + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_system_clock_exqsg. + * + * + * \section asfdoc_sam0_system_clock_api_overview API Overview + * @{ + */ + +#include "compiler.h" +#include "gclk.h" + +/** + * \name Driver Feature Definition + * Define system clock features set according to different device family. + * @{ + */ +#if (SAMD21) || (SAMR21) || (SAMD11) || (SAMD10) || (SAMDA1) || defined(__DOXYGEN__) +/** Digital Phase Locked Loop (DPLL) feature support. */ +# define FEATURE_SYSTEM_CLOCK_DPLL +#endif +/*@}*/ + +/** + * \brief Available start-up times for the XOSC32K. + * + * Available external 32KHz oscillator start-up times, as a number of external + * clock cycles. + */ +enum system_xosc32k_startup { + /** Wait zero clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_0, + /** Wait 32 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_32, + /** Wait 2048 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_2048, + /** Wait 4096 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_4096, + /** Wait 16384 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_16384, + /** Wait 32768 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_32768, + /** Wait 65536 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_65536, + /** Wait 131072 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_131072, +}; + +/** + * \brief Available start-up times for the XOSC. + * + * Available external oscillator start-up times, as a number of external clock + * cycles. + */ +enum system_xosc_startup { + /** Wait one clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_1, + /** Wait two clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_2, + /** Wait four clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_4, + /** Wait eight clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_8, + /** Wait 16 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_16, + /** Wait 32 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_32, + /** Wait 64 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_64, + /** Wait 128 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_128, + /** Wait 256 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_256, + /** Wait 512 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_512, + /** Wait 1024 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_1024, + /** Wait 2048 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_2048, + /** Wait 4096 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_4096, + /** Wait 8192 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_8192, + /** Wait 16384 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_16384, + /** Wait 32768 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_32768, +}; + +/** + * \brief Available start-up times for the OSC32K. + * + * Available internal 32KHz oscillator start-up times, as a number of internal + * OSC32K clock cycles. + */ +enum system_osc32k_startup { + /** Wait three clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_3, + /** Wait four clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_4, + /** Wait six clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_6, + /** Wait ten clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_10, + /** Wait 18 clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_18, + /** Wait 34 clock cycles until the clock source is considered stable */ + SYSTEM_OSC32K_STARTUP_34, + /** Wait 66 clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_66, + /** Wait 130 clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_130, +}; + +/** + * \brief Division prescalers for the internal 8MHz system clock. + * + * Available prescalers for the internal 8MHz (nominal) system clock. + */ +enum system_osc8m_div { + /** Do not divide the 8MHz RC oscillator output. */ + SYSTEM_OSC8M_DIV_1, + /** Divide the 8MHz RC oscillator output by two. */ + SYSTEM_OSC8M_DIV_2, + /** Divide the 8MHz RC oscillator output by four. */ + SYSTEM_OSC8M_DIV_4, + /** Divide the 8MHz RC oscillator output by eight. */ + SYSTEM_OSC8M_DIV_8, +}; + +/** + * \brief Frequency range for the internal 8MHz RC oscillator. + * + * Internal 8MHz RC oscillator frequency range setting + */ +enum system_osc8m_frequency_range { + /** Frequency range 4MHz to 6MHz. */ + SYSTEM_OSC8M_FREQUENCY_RANGE_4_TO_6, + /** Frequency range 6MHz to 8MHz. */ + SYSTEM_OSC8M_FREQUENCY_RANGE_6_TO_8, + /** Frequency range 8MHz to 11MHz. */ + SYSTEM_OSC8M_FREQUENCY_RANGE_8_TO_11, + /** Frequency range 11MHz to 15MHz. */ + SYSTEM_OSC8M_FREQUENCY_RANGE_11_TO_15, +}; + +/** + * \brief Main CPU and APB/AHB bus clock source prescaler values. + * + * Available division ratios for the CPU and APB/AHB bus clocks. + */ +enum system_main_clock_div { + /** Divide Main clock by one. */ + SYSTEM_MAIN_CLOCK_DIV_1, + /** Divide Main clock by two. */ + SYSTEM_MAIN_CLOCK_DIV_2, + /** Divide Main clock by four. */ + SYSTEM_MAIN_CLOCK_DIV_4, + /** Divide Main clock by eight. */ + SYSTEM_MAIN_CLOCK_DIV_8, + /** Divide Main clock by 16. */ + SYSTEM_MAIN_CLOCK_DIV_16, + /** Divide Main clock by 32. */ + SYSTEM_MAIN_CLOCK_DIV_32, + /** Divide Main clock by 64. */ + SYSTEM_MAIN_CLOCK_DIV_64, + /** Divide Main clock by 128. */ + SYSTEM_MAIN_CLOCK_DIV_128, +}; + +/** + * \brief External clock source types. + * + * Available external clock source types. + */ +enum system_clock_external { + /** The external clock source is a crystal oscillator. */ + SYSTEM_CLOCK_EXTERNAL_CRYSTAL, + /** The connected clock source is an external logic level clock signal. */ + SYSTEM_CLOCK_EXTERNAL_CLOCK, +}; + +/** + * \brief Operating modes of the DFLL clock source. + * + * Available operating modes of the DFLL clock source module. + */ +enum system_clock_dfll_loop_mode { + /** The DFLL is operating in open loop mode with no feedback. */ + SYSTEM_CLOCK_DFLL_LOOP_MODE_OPEN, + /** The DFLL is operating in closed loop mode with frequency feedback from + * a low frequency reference clock. + */ + SYSTEM_CLOCK_DFLL_LOOP_MODE_CLOSED = SYSCTRL_DFLLCTRL_MODE, + +#ifdef SYSCTRL_DFLLCTRL_USBCRM + /** The DFLL is operating in USB recovery mode with frequency feedback + * from USB SOF. + */ + SYSTEM_CLOCK_DFLL_LOOP_MODE_USB_RECOVERY = SYSCTRL_DFLLCTRL_USBCRM, +#endif +}; + +/** + * \brief Locking behavior for the DFLL during device wake-up. + * + * DFLL lock behavior modes on device wake-up from sleep. + */ +enum system_clock_dfll_wakeup_lock { + /** Keep DFLL lock when the device wakes from sleep. */ + SYSTEM_CLOCK_DFLL_WAKEUP_LOCK_KEEP, + /** Lose DFLL lock when the devices wakes from sleep. */ + SYSTEM_CLOCK_DFLL_WAKEUP_LOCK_LOSE = SYSCTRL_DFLLCTRL_LLAW, +}; + +/** + * \brief Fine tracking behavior for the DFLL once a lock has been acquired. + * + * DFLL fine tracking behavior modes after a lock has been acquired. + */ +enum system_clock_dfll_stable_tracking { + /** Keep tracking after the DFLL has gotten a fine lock. */ + SYSTEM_CLOCK_DFLL_STABLE_TRACKING_TRACK_AFTER_LOCK, + /** Stop tracking after the DFLL has gotten a fine lock. */ + SYSTEM_CLOCK_DFLL_STABLE_TRACKING_FIX_AFTER_LOCK = SYSCTRL_DFLLCTRL_STABLE, +}; + +/** + * \brief Chill-cycle behavior of the DFLL module. + * + * DFLL chill-cycle behavior modes of the DFLL module. A chill cycle is a period + * of time when the DFLL output frequency is not measured by the unit, to allow + * the output to stabilize after a change in the input clock source. + */ +enum system_clock_dfll_chill_cycle { + /** Enable a chill cycle, where the DFLL output frequency is not measured. */ + SYSTEM_CLOCK_DFLL_CHILL_CYCLE_ENABLE, + /** Disable a chill cycle, where the DFLL output frequency is not measured. */ + SYSTEM_CLOCK_DFLL_CHILL_CYCLE_DISABLE = SYSCTRL_DFLLCTRL_CCDIS, +}; + +/** + * \brief QuickLock settings for the DFLL module. + * + * DFLL QuickLock settings for the DFLL module, to allow for a faster lock of + * the DFLL output frequency at the expense of accuracy. + */ +enum system_clock_dfll_quick_lock { + /** Enable the QuickLock feature for looser lock requirements on the DFLL. */ + SYSTEM_CLOCK_DFLL_QUICK_LOCK_ENABLE, + /** Disable the QuickLock feature for strict lock requirements on the DFLL. */ + SYSTEM_CLOCK_DFLL_QUICK_LOCK_DISABLE = SYSCTRL_DFLLCTRL_QLDIS, +}; + +/** + * \brief Available clock sources in the system. + * + * Clock sources available to the GCLK generators. + */ +enum system_clock_source { + /** Internal 8MHz RC oscillator. */ + SYSTEM_CLOCK_SOURCE_OSC8M = GCLK_SOURCE_OSC8M, + /** Internal 32KHz RC oscillator. */ + SYSTEM_CLOCK_SOURCE_OSC32K = GCLK_SOURCE_OSC32K, + /** External oscillator. */ + SYSTEM_CLOCK_SOURCE_XOSC = GCLK_SOURCE_XOSC , + /** External 32KHz oscillator. */ + SYSTEM_CLOCK_SOURCE_XOSC32K = GCLK_SOURCE_XOSC32K, + /** Digital Frequency Locked Loop (DFLL). */ + SYSTEM_CLOCK_SOURCE_DFLL = GCLK_SOURCE_DFLL48M, + /** Internal Ultra Low Power 32KHz oscillator. */ + SYSTEM_CLOCK_SOURCE_ULP32K = GCLK_SOURCE_OSCULP32K, + /** Generator input pad. */ + SYSTEM_CLOCK_SOURCE_GCLKIN = GCLK_SOURCE_GCLKIN, + /** Generic clock generator one output. */ + SYSTEM_CLOCK_SOURCE_GCLKGEN1 = GCLK_SOURCE_GCLKGEN1, +#ifdef FEATURE_SYSTEM_CLOCK_DPLL + /** Digital Phase Locked Loop (DPLL). + * Check \c FEATURE_SYSTEM_CLOCK_DPLL for which device support it. + */ + SYSTEM_CLOCK_SOURCE_DPLL = GCLK_SOURCE_FDPLL, +#endif +}; + +/** + * \brief List of APB peripheral buses. + * + * Available bus clock domains on the APB bus. + */ +enum system_clock_apb_bus { + /** Peripheral bus A on the APB bus. */ + SYSTEM_CLOCK_APB_APBA, + /** Peripheral bus B on the APB bus. */ + SYSTEM_CLOCK_APB_APBB, + /** Peripheral bus C on the APB bus. */ + SYSTEM_CLOCK_APB_APBC, +}; + +/** + * \brief Configuration structure for XOSC. + * + * External oscillator clock configuration structure. + */ +struct system_clock_source_xosc_config { + /** External clock type. */ + enum system_clock_external external_clock; + /** Crystal oscillator start-up time. */ + enum system_xosc_startup startup_time; + /** Enable automatic amplitude gain control. */ + bool auto_gain_control; + /** External clock/crystal frequency. */ + uint32_t frequency; + /** Keep the XOSC enabled in standby sleep mode. */ + bool run_in_standby; + /** Run On Demand. If this is set the XOSC won't run + * until requested by a peripheral. */ + bool on_demand; +}; + +/** + * \brief Configuration structure for XOSC32K. + * + * External 32KHz oscillator clock configuration structure. + */ +struct system_clock_source_xosc32k_config { + /** External clock type. */ + enum system_clock_external external_clock; + /** Crystal oscillator start-up time. */ + enum system_xosc32k_startup startup_time; + /** Enable automatic amplitude control. */ + bool auto_gain_control; + /** Enable 1KHz output. */ + bool enable_1khz_output; + /** Enable 32KHz output. */ + bool enable_32khz_output; + /** External clock/crystal frequency. */ + uint32_t frequency; + /** Keep the XOSC32K enabled in standby sleep mode. */ + bool run_in_standby; + /** Run On Demand. If this is set the XOSC32K won't run + * until requested by a peripheral. */ + bool on_demand; + /** Lock configuration after it has been written, + * a device reset will release the lock. */ + bool write_once; +}; + +/** + * \brief Configuration structure for OSC8M. + * + * Internal 8MHz (nominal) oscillator configuration structure. + */ +struct system_clock_source_osc8m_config { + /** Internal 8MHz RC oscillator prescaler. */ + enum system_osc8m_div prescaler; + /** Keep the OSC8M enabled in standby sleep mode. */ + bool run_in_standby; + /** Run On Demand. If this is set the OSC8M won't run + * until requested by a peripheral. */ + bool on_demand; +}; + +/** + * \brief Configuration structure for OSC32K. + * + * Internal 32KHz (nominal) oscillator configuration structure. + */ +struct system_clock_source_osc32k_config { + /** Startup time. */ + enum system_osc32k_startup startup_time; + /** Enable 1KHz output. */ + bool enable_1khz_output; + /** Enable 32KHz output. */ + bool enable_32khz_output; + /** Keep the OSC32K enabled in standby sleep mode. */ + bool run_in_standby; + /** Run On Demand. If this is set the OSC32K won't run + * until requested by a peripheral. */ + bool on_demand; + /** Lock configuration after it has been written, + * a device reset will release the lock. */ + bool write_once; +}; + +/** + * \brief Configuration structure for DFLL. + * + * DFLL oscillator configuration structure. + */ +struct system_clock_source_dfll_config { + /** Loop mode. */ + enum system_clock_dfll_loop_mode loop_mode; + /** Run On Demand. If this is set the DFLL won't run + * until requested by a peripheral. */ + bool on_demand; + /** Enable Quick Lock. */ + enum system_clock_dfll_quick_lock quick_lock; + /** Enable Chill Cycle. */ + enum system_clock_dfll_chill_cycle chill_cycle; + /** DFLL lock state on wakeup. */ + enum system_clock_dfll_wakeup_lock wakeup_lock; + /** DFLL tracking after fine lock. */ + enum system_clock_dfll_stable_tracking stable_tracking; + /** Coarse calibration value (Open loop mode). */ + uint8_t coarse_value; + /** Fine calibration value (Open loop mode). */ + uint16_t fine_value; + /** Coarse adjustment maximum step size (Closed loop mode). */ + uint8_t coarse_max_step; + /** Fine adjustment maximum step size (Closed loop mode). */ + uint16_t fine_max_step; + /** DFLL multiply factor (Closed loop mode. */ + uint16_t multiply_factor; +}; + +/** + * \name External Oscillator Management + * @{ + */ + +/** + * \brief Retrieve the default configuration for XOSC. + * + * Fills a configuration structure with the default configuration for an + * external oscillator module: + * - External Crystal + * - Start-up time of 16384 external clock cycles + * - Automatic crystal gain control mode enabled + * - Frequency of 12MHz + * - Don't run in STANDBY sleep mode + * - Run only when requested by peripheral (on demand) + * + * \param[out] config Configuration structure to fill with default values + */ +static inline void system_clock_source_xosc_get_config_defaults( + struct system_clock_source_xosc_config *const config) +{ + Assert(config); + + config->external_clock = SYSTEM_CLOCK_EXTERNAL_CRYSTAL; + config->startup_time = SYSTEM_XOSC_STARTUP_16384; + config->auto_gain_control = true; + config->frequency = 12000000UL; + config->run_in_standby = false; + config->on_demand = true; +} + +void system_clock_source_xosc_set_config( + struct system_clock_source_xosc_config *const config); + +/** + * @} + */ + + +/** + * \name External 32KHz Oscillator Management + * @{ + */ + +/** + * \brief Retrieve the default configuration for XOSC32K. + * + * Fills a configuration structure with the default configuration for an + * external 32KHz oscillator module: + * - External Crystal + * - Start-up time of 16384 external clock cycles + * - Automatic crystal gain control mode disabled + * - Frequency of 32.768KHz + * - 1KHz clock output disabled + * - 32KHz clock output enabled + * - Don't run in STANDBY sleep mode + * - Run only when requested by peripheral (on demand) + * - Don't lock registers after configuration has been written + * + * \param[out] config Configuration structure to fill with default values + */ +static inline void system_clock_source_xosc32k_get_config_defaults( + struct system_clock_source_xosc32k_config *const config) +{ + Assert(config); + + config->external_clock = SYSTEM_CLOCK_EXTERNAL_CRYSTAL; + config->startup_time = SYSTEM_XOSC32K_STARTUP_16384; + config->auto_gain_control = false; + config->frequency = 32768UL; + config->enable_1khz_output = false; + config->enable_32khz_output = true; + config->run_in_standby = false; + config->on_demand = true; + config->write_once = false; +} + +void system_clock_source_xosc32k_set_config( + struct system_clock_source_xosc32k_config *const config); +/** + * @} + */ + + +/** + * \name Internal 32KHz Oscillator Management + * @{ + */ + +/** + * \brief Retrieve the default configuration for OSC32K. + * + * Fills a configuration structure with the default configuration for an + * internal 32KHz oscillator module: + * - 1KHz clock output enabled + * - 32KHz clock output enabled + * - Don't run in STANDBY sleep mode + * - Run only when requested by peripheral (on demand) + * - Set startup time to 130 cycles + * - Don't lock registers after configuration has been written + * + * \param[out] config Configuration structure to fill with default values + */ +static inline void system_clock_source_osc32k_get_config_defaults( + struct system_clock_source_osc32k_config *const config) +{ + Assert(config); + + config->enable_1khz_output = true; + config->enable_32khz_output = true; + config->run_in_standby = false; + config->on_demand = true; + config->startup_time = SYSTEM_OSC32K_STARTUP_130; + config->write_once = false; +} + +void system_clock_source_osc32k_set_config( + struct system_clock_source_osc32k_config *const config); + +/** + * @} + */ + + +/** + * \name Internal 8MHz Oscillator Management + * @{ + */ + +/** + * \brief Retrieve the default configuration for OSC8M. + * + * Fills a configuration structure with the default configuration for an + * internal 8MHz (nominal) oscillator module: + * - Clock output frequency divided by a factor of eight + * - Don't run in STANDBY sleep mode + * - Run only when requested by peripheral (on demand) + * + * \param[out] config Configuration structure to fill with default values + */ +static inline void system_clock_source_osc8m_get_config_defaults( + struct system_clock_source_osc8m_config *const config) +{ + Assert(config); + + config->prescaler = SYSTEM_OSC8M_DIV_8; + config->run_in_standby = false; + config->on_demand = true; +} + +void system_clock_source_osc8m_set_config( + struct system_clock_source_osc8m_config *const config); + +/** + * @} + */ + + +/** + * \name Internal DFLL Management + * @{ + */ + +/** + * \brief Retrieve the default configuration for DFLL. + * + * Fills a configuration structure with the default configuration for a + * DFLL oscillator module: + * - Open loop mode + * - QuickLock mode enabled + * - Chill cycle enabled + * - Output frequency lock maintained during device wake-up + * - Continuous tracking of the output frequency + * - Default tracking values at the mid-points for both coarse and fine + * tracking parameters + * - Don't run in STANDBY sleep mode + * - Run only when requested by peripheral (on demand) + * + * \param[out] config Configuration structure to fill with default values + */ +static inline void system_clock_source_dfll_get_config_defaults( + struct system_clock_source_dfll_config *const config) +{ + Assert(config); + + config->loop_mode = SYSTEM_CLOCK_DFLL_LOOP_MODE_OPEN; + config->quick_lock = SYSTEM_CLOCK_DFLL_QUICK_LOCK_ENABLE; + config->chill_cycle = SYSTEM_CLOCK_DFLL_CHILL_CYCLE_ENABLE; + config->wakeup_lock = SYSTEM_CLOCK_DFLL_WAKEUP_LOCK_KEEP; + config->stable_tracking = SYSTEM_CLOCK_DFLL_STABLE_TRACKING_TRACK_AFTER_LOCK; + config->on_demand = true; + + /* Open loop mode calibration value */ + config->coarse_value = 0x1f / 4; /* Midpoint */ + config->fine_value = 0xff / 4; /* Midpoint */ + + /* Closed loop mode */ + config->coarse_max_step = 1; + config->fine_max_step = 1; + config->multiply_factor = 6; /* Multiply 8MHz by 6 to get 48MHz */ +} + +void system_clock_source_dfll_set_config( + struct system_clock_source_dfll_config *const config); + +/** + * @} + */ + +/** + * \name Clock Source Management + * @{ + */ +enum status_code system_clock_source_write_calibration( + const enum system_clock_source system_clock_source, + const uint16_t calibration_value, + const uint8_t freq_range); + +enum status_code system_clock_source_enable( + const enum system_clock_source system_clock_source); + +enum status_code system_clock_source_disable( + const enum system_clock_source clk_source); + +bool system_clock_source_is_ready( + const enum system_clock_source clk_source); + +uint32_t system_clock_source_get_hz( + const enum system_clock_source clk_source); + +/** + * @} + */ + +/** + * \name Main Clock Management + * @{ + */ + +/** + * \brief Set main CPU clock divider. + * + * Sets the clock divider used on the main clock to provide the CPU clock. + * + * \param[in] divider CPU clock divider to set + */ +static inline void system_cpu_clock_set_divider( + const enum system_main_clock_div divider) +{ + Assert(((uint32_t)divider & PM_CPUSEL_CPUDIV_Msk) == divider); + PM->CPUSEL.reg = (uint32_t)divider; +} + +/** + * \brief Retrieves the current frequency of the CPU core. + * + * Retrieves the operating frequency of the CPU core, obtained from the main + * generic clock and the set CPU bus divider. + * + * \return Current CPU frequency in Hz. + */ +static inline uint32_t system_cpu_clock_get_hz(void) +{ + return (system_gclk_gen_get_hz(GCLK_GENERATOR_0) >> PM->CPUSEL.reg); +} + +/** + * \brief Set APBx clock divider. + * + * Set the clock divider used on the main clock to provide the clock for the + * given APBx bus. + * + * \param[in] divider APBx bus divider to set + * \param[in] bus APBx bus to set divider + * + * \returns Status of the clock division change operation. + * + * \retval STATUS_ERR_INVALID_ARG Invalid bus ID was given + * \retval STATUS_OK The APBx clock was set successfully + */ +static inline enum status_code system_apb_clock_set_divider( + const enum system_clock_apb_bus bus, + const enum system_main_clock_div divider) +{ + switch (bus) { + case SYSTEM_CLOCK_APB_APBA: + PM->APBASEL.reg = (uint32_t)divider; + break; + case SYSTEM_CLOCK_APB_APBB: + PM->APBBSEL.reg = (uint32_t)divider; + break; + case SYSTEM_CLOCK_APB_APBC: + PM->APBCSEL.reg = (uint32_t)divider; + break; + default: + Assert(false); + return STATUS_ERR_INVALID_ARG; + } + + return STATUS_OK; +} + +/** + * \brief Retrieves the current frequency of a ABPx. + * + * Retrieves the operating frequency of an APBx bus, obtained from the main + * generic clock and the set APBx bus divider. + * + * \return Current APBx bus frequency in Hz. + */ +static inline uint32_t system_apb_clock_get_hz( + const enum system_clock_apb_bus bus) +{ + uint16_t bus_divider = 0; + + switch (bus) { + case SYSTEM_CLOCK_APB_APBA: + bus_divider = PM->APBASEL.reg; + break; + case SYSTEM_CLOCK_APB_APBB: + bus_divider = PM->APBBSEL.reg; + break; + case SYSTEM_CLOCK_APB_APBC: + bus_divider = PM->APBCSEL.reg; + break; + default: + Assert(false); + return 0; + } + + return (system_gclk_gen_get_hz(GCLK_GENERATOR_0) >> bus_divider); +} + + +/** + * @} + */ + +/** + * \name Bus Clock Masking + * @{ + */ + +/** + * \brief Set bits in the clock mask for the AHB bus. + * + * This function will set bits in the clock mask for the AHB bus. + * Any bits set to 1 will enable that clock, 0 bits in the mask + * will be ignored. + * + * \param[in] ahb_mask AHB clock mask to enable + */ +static inline void system_ahb_clock_set_mask( + const uint32_t ahb_mask) +{ + PM->AHBMASK.reg |= ahb_mask; +} + +/** + * \brief Clear bits in the clock mask for the AHB bus. + * + * This function will clear bits in the clock mask for the AHB bus. + * Any bits set to 1 will disable that clock, 0 bits in the mask + * will be ignored. + * + * \param[in] ahb_mask AHB clock mask to disable + */ +static inline void system_ahb_clock_clear_mask( + const uint32_t ahb_mask) +{ + PM->AHBMASK.reg &= ~ahb_mask; +} + +/** + * \brief Set bits in the clock mask for an APBx bus. + * + * This function will set bits in the clock mask for an APBx bus. + * Any bits set to 1 will enable the corresponding module clock, zero bits in + * the mask will be ignored. + * + * \param[in] mask APBx clock mask, a \c SYSTEM_CLOCK_APB_APBx constant from + * the device header files + * \param[in] bus Bus to set clock mask bits for, a mask of \c PM_APBxMASK_* + * constants from the device header files + * + * \returns Status indicating the result of the clock mask change operation. + * + * \retval STATUS_ERR_INVALID_ARG Invalid bus given + * \retval STATUS_OK The clock mask was set successfully + */ +static inline enum status_code system_apb_clock_set_mask( + const enum system_clock_apb_bus bus, + const uint32_t mask) +{ + switch (bus) { + case SYSTEM_CLOCK_APB_APBA: + PM->APBAMASK.reg |= mask; + break; + + case SYSTEM_CLOCK_APB_APBB: + PM->APBBMASK.reg |= mask; + break; + + case SYSTEM_CLOCK_APB_APBC: + PM->APBCMASK.reg |= mask; + break; + + default: + Assert(false); + return STATUS_ERR_INVALID_ARG; + + } + + return STATUS_OK; +} + +/** + * \brief Clear bits in the clock mask for an APBx bus. + * + * This function will clear bits in the clock mask for an APBx bus. + * Any bits set to 1 will disable the corresponding module clock, zero bits in + * the mask will be ignored. + * + * \param[in] mask APBx clock mask, a \c SYSTEM_CLOCK_APB_APBx constant from + * the device header files + * \param[in] bus Bus to clear clock mask bits + * + * \returns Status indicating the result of the clock mask change operation. + * + * \retval STATUS_ERR_INVALID_ARG Invalid bus ID was given + * \retval STATUS_OK The clock mask was changed successfully + */ +static inline enum status_code system_apb_clock_clear_mask( + const enum system_clock_apb_bus bus, + const uint32_t mask) +{ + switch (bus) { + case SYSTEM_CLOCK_APB_APBA: + PM->APBAMASK.reg &= ~mask; + break; + + case SYSTEM_CLOCK_APB_APBB: + PM->APBBMASK.reg &= ~mask; + break; + + case SYSTEM_CLOCK_APB_APBC: + PM->APBCMASK.reg &= ~mask; + break; + + default: + Assert(false); + return STATUS_ERR_INVALID_ARG; + } + + return STATUS_OK; +} + +/** + * @} + */ + +#ifdef FEATURE_SYSTEM_CLOCK_DPLL +/** + * \brief Reference clock source of the DPLL module. + */ +enum system_clock_source_dpll_reference_clock { + /** Select XOSC32K as clock reference. */ + SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_XOSC32K, + /** Select XOSC as clock reference. */ + SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_XOSC, + /** Select GCLK as clock reference. */ + SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_GCLK, +}; + +/** + * \brief Lock time-out value of the DPLL module. + */ +enum system_clock_source_dpll_lock_time { + /** Set no time-out as default. */ + SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_DEFAULT, + /** Set time-out if no lock within 8ms. */ + SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_8MS = 0x04, + /** Set time-out if no lock within 9ms. */ + SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_9MS, + /** Set time-out if no lock within 10ms. */ + SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_10MS, + /** Set time-out if no lock within 11ms. */ + SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_11MS, +}; + +/** + * \brief Filter type of the DPLL module. + */ +enum system_clock_source_dpll_filter { + /** Default filter mode. */ + SYSTEM_CLOCK_SOURCE_DPLL_FILTER_DEFAULT, + /** Low bandwidth filter. */ + SYSTEM_CLOCK_SOURCE_DPLL_FILTER_LOW_BANDWIDTH_FILTER, + /** High bandwidth filter. */ + SYSTEM_CLOCK_SOURCE_DPLL_FILTER_HIGH_BANDWIDTH_FILTER, + /** High damping filter. */ + SYSTEM_CLOCK_SOURCE_DPLL_FILTER_HIGH_DAMPING_FILTER, +}; + +/** + * \brief Configuration structure for DPLL. + * + * DPLL oscillator configuration structure. + */ +struct system_clock_source_dpll_config { + /** Run On Demand. If this is set the DPLL won't run + * until requested by a peripheral. */ + bool on_demand; + /** Keep the DPLL enabled in standby sleep mode. */ + bool run_in_standby; + /** Bypass lock signal. */ + bool lock_bypass; + /** Wake up fast. If this is set DPLL output clock is enabled after + * the startup time. */ + bool wake_up_fast; + /** Enable low power mode. */ + bool low_power_enable; + + /** Output frequency of the clock. */ + uint32_t output_frequency; + /** Reference frequency of the clock. */ + uint32_t reference_frequency; + /** Devider of reference clock. */ + uint16_t reference_divider; + + /** Filter type of the DPLL module. */ + enum system_clock_source_dpll_filter filter; + /** Lock time-out value of the DPLL module. */ + enum system_clock_source_dpll_lock_time lock_time; + /** Reference clock source of the DPLL module. */ + enum system_clock_source_dpll_reference_clock reference_clock; +}; + +/** + * \name Internal DPLL Management + * @{ + */ + +/** + * \brief Retrieve the default configuration for DPLL. + * + * Fills a configuration structure with the default configuration for a + * DPLL oscillator module: + * - Run only when requested by peripheral (on demand) + * - Don't run in STANDBY sleep mode + * - Lock bypass disabled + * - Fast wake up disabled + * - Low power mode disabled + * - Output frequency is 48MHz + * - Reference clock frequency is 32768Hz + * - Not divide reference clock + * - Select REF0 as reference clock + * - Set lock time to default mode + * - Use default filter + * + * \param[out] config Configuration structure to fill with default values + */ +static inline void system_clock_source_dpll_get_config_defaults( + struct system_clock_source_dpll_config *const config) +{ + config->on_demand = true; + config->run_in_standby = false; + config->lock_bypass = false; + config->wake_up_fast = false; + config->low_power_enable = false; + + config->output_frequency = 48000000; + config->reference_frequency = 32768; + config->reference_divider = 1; + config->reference_clock = SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_XOSC32K; + + config->lock_time = SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_DEFAULT; + config->filter = SYSTEM_CLOCK_SOURCE_DPLL_FILTER_DEFAULT; +}; + +void system_clock_source_dpll_set_config( + struct system_clock_source_dpll_config *const config); + +/* @} */ +#endif + +/** + * \name System Clock Initialization + * @{ + */ + +void system_clock_init(void); + +/** + * @} + */ + +/** + * \name System Flash Wait States + * @{ + */ + +/** + * \brief Set flash controller wait states. + * + * Will set the number of wait states that are used by the onboard + * flash memory. The number of wait states depend on both device + * supply voltage and CPU speed. The required number of wait states + * can be found in the electrical characteristics of the device. + * + * \param[in] wait_states Number of wait states to use for internal flash + */ +static inline void system_flash_set_waitstates(uint8_t wait_states) +{ + Assert(NVMCTRL_CTRLB_RWS((uint32_t)wait_states) == + ((uint32_t)wait_states << NVMCTRL_CTRLB_RWS_Pos)); + + NVMCTRL->CTRLB.bit.RWS = wait_states; +} +/** + * @} + */ + +/** + * @} + */ + +/** + * \page asfdoc_sam0_system_clock_extra Extra Information for SYSTEM CLOCK Driver + * + * \section asfdoc_sam0_system_clock_extra_acronyms Acronyms + * Below is a table listing the acronyms used in this module, along with their + * intended meanings. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
AcronymDescription
DFLLDigital Frequency Locked Loop
MUXMultiplexer
OSC32KInternal 32KHz Oscillator
OSC8MInternal 8MHz Oscillator
PLLPhase Locked Loop
OSCOscillator
XOSCExternal Oscillator
XOSC32KExternal 32KHz Oscillator
AHBAdvanced High-performance Bus
APBAdvanced Peripheral Bus
DPLLDigital Phase Locked Loop
+ * + * + * \section asfdoc_sam0_system_clock_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - None + * + * + * \section asfdoc_sam0_system_clock_extra_errata Errata + * + * - This driver implements experimental workaround for errata 9905 + * + * "The DFLL clock must be requested before being configured otherwise a + * write access to a DFLL register can freeze the device." + * This driver will enable and configure the DFLL before the ONDEMAND bit is set. + * + * + * \section asfdoc_sam0_system_clock_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Changelog
+ * \li Corrected OSC32K startup time definitions + * \li Support locking of OSC32K and XOSC32K config register (default: false) + * \li Added DPLL support, functions added: + * \c system_clock_source_dpll_get_config_defaults() and + * \c system_clock_source_dpll_set_config() + * \li Moved gclk channel locking feature out of the config struct + * functions added: + * \c system_gclk_chan_lock(), + * \c system_gclk_chan_is_locked() + * \c system_gclk_chan_is_enabled() and + * \c system_gclk_gen_is_enabled() + *
Fixed \c system_gclk_chan_disable() deadlocking if a channel is enabled + * and configured to a failed/not running clock generator
+ * \li Changed default value for CONF_CLOCK_DFLL_ON_DEMAND from \c true to \c false + * \li Fixed system_flash_set_waitstates() failing with an assertion + * if an odd number of wait states provided + *
+ * \li Updated dfll configuration function to implement workaround for + * errata 9905 in the DFLL module + * \li Updated \c system_clock_init() to reset interrupt flags before + * they are used + * \li Fixed \c system_clock_source_get_hz() to return correcy DFLL + * frequency number + *
\li Fixed \c system_clock_source_is_ready not returning the correct + * state for \c SYSTEM_CLOCK_SOURCE_OSC8M + * \li Renamed the various \c system_clock_source_*_get_default_config() + * functions to \c system_clock_source_*_get_config_defaults() to + * match the remainder of ASF + * \li Added OSC8M calibration constant loading from the device signature + * row when the oscillator is initialized + * \li Updated default configuration of the XOSC32 to disable Automatic + * Gain Control due to silicon errata + *
Initial Release
+ */ + +/** + * \page asfdoc_sam0_system_clock_exqsg Examples for System Clock Driver + * + * This is a list of the available Quick Start guides (QSGs) and example + * applications for \ref asfdoc_sam0_system_clock_group. QSGs are simple + * examples with step-by-step instructions to configure and use this driver in + * a selection of use cases. Note that QSGs can be compiled as a standalone + * application or be added to the user application. + * + * - \subpage asfdoc_sam0_system_clock_basic_use_case + * - \subpage asfdoc_sam0_system_gclk_basic_use_case + * + * \page asfdoc_sam0_system_clock_document_revision_history Document Revision History + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Doc. Rev. + * Date + * Comments + *
E04/2015Added support for SAMDAx.
D12/2014Added support for SAMR21 and SAMD10/D11.
C01/2014Added support for SAMD21.
B06/2013Corrected documentation typos. Fixed missing steps in the Basic + * Use Case Quick Start Guide.
A06/2013Initial release
+ */ + +#ifdef __cplusplus +} +#endif + +#endif /* SYSTEM_CLOCK_FEATURE_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/compiler.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/compiler.h new file mode 100644 index 0000000..2d95f97 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/compiler.h @@ -0,0 +1,1157 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef UTILS_COMPILER_H_INCLUDED +#define UTILS_COMPILER_H_INCLUDED + +/** + * \defgroup group_sam0_utils Compiler abstraction layer and code utilities + * + * Compiler abstraction layer and code utilities for Cortex-M0+ based Atmel SAM devices. + * This module provides various abstraction layers and utilities to make code compatible between different compilers. + * + * @{ + */ + +#if (defined __ICCARM__) +# include +#endif + +#include +//#include +#include "status_codes.h" +#include "preprocessor/preprocessor.h" +#include + +#ifndef __ASSEMBLY__ + +#include +#include +#include +#include + +/** + * \def UNUSED + * \brief Marking \a v as a unused parameter or value. + */ +#define UNUSED(v) (void)(v) + +/** + * \def barrier + * \brief Memory barrier + */ +#ifdef __GNUC__ +# define barrier() asm volatile("" ::: "memory") +#else +# define barrier() asm ("") +#endif + +/** + * \brief Emit the compiler pragma \a arg. + * + * \param[in] arg The pragma directive as it would appear after \e \#pragma + * (i.e. not stringified). + */ +#define COMPILER_PRAGMA(arg) _Pragma(#arg) + +/** + * \def COMPILER_PACK_SET(alignment) + * \brief Set maximum alignment for subsequent struct and union definitions to \a alignment. + */ +#define COMPILER_PACK_SET(alignment) COMPILER_PRAGMA(pack(alignment)) + +/** + * \def COMPILER_PACK_RESET() + * \brief Set default alignment for subsequent struct and union definitions. + */ +#define COMPILER_PACK_RESET() COMPILER_PRAGMA(pack()) + + +/** + * \brief Set aligned boundary. + */ +#if (defined __GNUC__) || (defined __CC_ARM) +# define COMPILER_ALIGNED(a) __attribute__((__aligned__(a))) +#elif (defined __ICCARM__) +# define COMPILER_ALIGNED(a) COMPILER_PRAGMA(data_alignment = a) +#endif + +/** + * \brief Set word-aligned boundary. + */ +#if (defined __GNUC__) || defined(__CC_ARM) +#define COMPILER_WORD_ALIGNED __attribute__((__aligned__(4))) +#elif (defined __ICCARM__) +#define COMPILER_WORD_ALIGNED COMPILER_PRAGMA(data_alignment = 4) +#endif + +/** + * \def __always_inline + * \brief The function should always be inlined. + * + * This annotation instructs the compiler to ignore its inlining + * heuristics and inline the function no matter how big it thinks it + * becomes. + */ +#if defined(__CC_ARM) +# define __always_inline __forceinline +#elif (defined __GNUC__) +# define __always_inline __attribute__((__always_inline__)) +#elif (defined __ICCARM__) +# define __always_inline _Pragma("inline=forced") +#endif + +/** + * \def __no_inline + * \brief The function should never be inlined + * + * This annotation instructs the compiler to ignore its inlining + * heuristics and not inline the function no matter how small it thinks it + * becomes. + */ +#if defined(__CC_ARM) +# define __no_inline __attribute__((noinline)) +#elif (defined __GNUC__) +# define __no_inline __attribute__((noinline)) +#elif (defined __ICCARM__) +# define __no_inline _Pragma("inline=never") +#endif + + +/** \brief This macro is used to test fatal errors. + * + * The macro tests if the expression is false. If it is, a fatal error is + * detected and the application hangs up. If \c TEST_SUITE_DEFINE_ASSERT_MACRO + * is defined, a unit test version of the macro is used, to allow execution + * of further tests after a false expression. + * + * \param[in] expr Expression to evaluate and supposed to be nonzero. + */ +#if defined(_ASSERT_ENABLE_) +# if defined(TEST_SUITE_DEFINE_ASSERT_MACRO) +# include "unit_test/suite.h" +# else +# undef TEST_SUITE_DEFINE_ASSERT_MACRO +# define Assert(expr) \ + {\ + if (!(expr)) asm("BKPT #0");\ + } +# endif +#else +# define Assert(expr) ((void) 0) +#endif + +/* Define WEAK attribute */ +#if defined ( __CC_ARM ) +# define WEAK __attribute__ ((weak)) +#elif defined ( __ICCARM__ ) +# define WEAK __weak +#elif defined ( __GNUC__ ) +# define WEAK __attribute__ ((weak)) +#endif + +/* Define NO_INIT attribute */ +#if defined ( __CC_ARM ) +# define NO_INIT __attribute__((zero_init)) +#elif defined ( __ICCARM__ ) +# define NO_INIT __no_init +#elif defined ( __GNUC__ ) +# define NO_INIT __attribute__((section(".no_init"))) +#endif + +#include "interrupt.h" + +/** \name Usual Types + * @{ */ +#ifndef __cplusplus +# if !defined(__bool_true_false_are_defined) +typedef unsigned char bool; +# endif +#endif +typedef uint16_t le16_t; +typedef uint16_t be16_t; +typedef uint32_t le32_t; +typedef uint32_t be32_t; +typedef uint32_t iram_size_t; +/** @} */ + +/** \name Aliasing Aggregate Types + * @{ */ + +/** 16-bit union. */ +typedef union +{ + int16_t s16; + uint16_t u16; + int8_t s8[2]; + uint8_t u8[2]; +} Union16; + +/** 32-bit union. */ +typedef union +{ + int32_t s32; + uint32_t u32; + int16_t s16[2]; + uint16_t u16[2]; + int8_t s8[4]; + uint8_t u8[4]; +} Union32; + +/** 64-bit union. */ +typedef union +{ + int64_t s64; + uint64_t u64; + int32_t s32[2]; + uint32_t u32[2]; + int16_t s16[4]; + uint16_t u16[4]; + int8_t s8[8]; + uint8_t u8[8]; +} Union64; + +/** Union of pointers to 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef union +{ + int64_t *s64ptr; + uint64_t *u64ptr; + int32_t *s32ptr; + uint32_t *u32ptr; + int16_t *s16ptr; + uint16_t *u16ptr; + int8_t *s8ptr; + uint8_t *u8ptr; +} UnionPtr; + +/** Union of pointers to volatile 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef union +{ + volatile int64_t *s64ptr; + volatile uint64_t *u64ptr; + volatile int32_t *s32ptr; + volatile uint32_t *u32ptr; + volatile int16_t *s16ptr; + volatile uint16_t *u16ptr; + volatile int8_t *s8ptr; + volatile uint8_t *u8ptr; +} UnionVPtr; + +/** Union of pointers to constant 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef union +{ + const int64_t *s64ptr; + const uint64_t *u64ptr; + const int32_t *s32ptr; + const uint32_t *u32ptr; + const int16_t *s16ptr; + const uint16_t *u16ptr; + const int8_t *s8ptr; + const uint8_t *u8ptr; +} UnionCPtr; + +/** Union of pointers to constant volatile 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef union +{ + const volatile int64_t *s64ptr; + const volatile uint64_t *u64ptr; + const volatile int32_t *s32ptr; + const volatile uint32_t *u32ptr; + const volatile int16_t *s16ptr; + const volatile uint16_t *u16ptr; + const volatile int8_t *s8ptr; + const volatile uint8_t *u8ptr; +} UnionCVPtr; + +/** Structure of pointers to 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef struct +{ + int64_t *s64ptr; + uint64_t *u64ptr; + int32_t *s32ptr; + uint32_t *u32ptr; + int16_t *s16ptr; + uint16_t *u16ptr; + int8_t *s8ptr; + uint8_t *u8ptr; +} StructPtr; + +/** Structure of pointers to volatile 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef struct +{ + volatile int64_t *s64ptr; + volatile uint64_t *u64ptr; + volatile int32_t *s32ptr; + volatile uint32_t *u32ptr; + volatile int16_t *s16ptr; + volatile uint16_t *u16ptr; + volatile int8_t *s8ptr; + volatile uint8_t *u8ptr; +} StructVPtr; + +/** Structure of pointers to constant 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef struct +{ + const int64_t *s64ptr; + const uint64_t *u64ptr; + const int32_t *s32ptr; + const uint32_t *u32ptr; + const int16_t *s16ptr; + const uint16_t *u16ptr; + const int8_t *s8ptr; + const uint8_t *u8ptr; +} StructCPtr; + +/** Structure of pointers to constant volatile 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef struct +{ + const volatile int64_t *s64ptr; + const volatile uint64_t *u64ptr; + const volatile int32_t *s32ptr; + const volatile uint32_t *u32ptr; + const volatile int16_t *s16ptr; + const volatile uint16_t *u16ptr; + const volatile int8_t *s8ptr; + const volatile uint8_t *u8ptr; +} StructCVPtr; + +/** @} */ + +#endif /* #ifndef __ASSEMBLY__ */ + +/** \name Usual Constants + * @{ */ +#define DISABLE 0 +//#define ENABLE 1 + +#ifndef __cplusplus +# if !defined(__bool_true_false_are_defined) +# define false 0 +# define true 1 +# endif +#endif +/** @} */ + +#ifndef __ASSEMBLY__ + +/** \name Optimization Control + * @{ */ + +/** + * \def likely(exp) + * \brief The expression \a exp is likely to be true + */ +#if !defined(likely) || defined(__DOXYGEN__) +# define likely(exp) (exp) +#endif + +/** + * \def unlikely(exp) + * \brief The expression \a exp is unlikely to be true + */ +#if !defined(unlikely) || defined(__DOXYGEN__) +# define unlikely(exp) (exp) +#endif + +/** + * \def is_constant(exp) + * \brief Determine if an expression evaluates to a constant value. + * + * \param[in] exp Any expression + * + * \return true if \a exp is constant, false otherwise. + */ +#if (defined __GNUC__) || (defined __CC_ARM) +# define is_constant(exp) __builtin_constant_p(exp) +#else +# define is_constant(exp) (0) +#endif + +/** @} */ + +/** \name Bit-Field Handling + * @{ */ + +/** \brief Reads the bits of a value specified by a given bit-mask. + * + * \param[in] value Value to read bits from. + * \param[in] mask Bit-mask indicating bits to read. + * + * \return Read bits. + */ +#define Rd_bits( value, mask) ((value) & (mask)) + +/** \brief Writes the bits of a C lvalue specified by a given bit-mask. + * + * \param[in] lvalue C lvalue to write bits to. + * \param[in] mask Bit-mask indicating bits to write. + * \param[in] bits Bits to write. + * + * \return Resulting value with written bits. + */ +#define Wr_bits(lvalue, mask, bits) ((lvalue) = ((lvalue) & ~(mask)) |\ + ((bits ) & (mask))) + +/** \brief Tests the bits of a value specified by a given bit-mask. + * + * \param[in] value Value of which to test bits. + * \param[in] mask Bit-mask indicating bits to test. + * + * \return \c 1 if at least one of the tested bits is set, else \c 0. + */ +#define Tst_bits( value, mask) (Rd_bits(value, mask) != 0) + +/** \brief Clears the bits of a C lvalue specified by a given bit-mask. + * + * \param[in] lvalue C lvalue of which to clear bits. + * \param[in] mask Bit-mask indicating bits to clear. + * + * \return Resulting value with cleared bits. + */ +#define Clr_bits(lvalue, mask) ((lvalue) &= ~(mask)) + +/** \brief Sets the bits of a C lvalue specified by a given bit-mask. + * + * \param[in] lvalue C lvalue of which to set bits. + * \param[in] mask Bit-mask indicating bits to set. + * + * \return Resulting value with set bits. + */ +#define Set_bits(lvalue, mask) ((lvalue) |= (mask)) + +/** \brief Toggles the bits of a C lvalue specified by a given bit-mask. + * + * \param[in] lvalue C lvalue of which to toggle bits. + * \param[in] mask Bit-mask indicating bits to toggle. + * + * \return Resulting value with toggled bits. + */ +#define Tgl_bits(lvalue, mask) ((lvalue) ^= (mask)) + +/** \brief Reads the bit-field of a value specified by a given bit-mask. + * + * \param[in] value Value to read a bit-field from. + * \param[in] mask Bit-mask indicating the bit-field to read. + * + * \return Read bit-field. + */ +#define Rd_bitfield( value, mask) (Rd_bits( value, mask) >> ctz(mask)) + +/** \brief Writes the bit-field of a C lvalue specified by a given bit-mask. + * + * \param[in] lvalue C lvalue to write a bit-field to. + * \param[in] mask Bit-mask indicating the bit-field to write. + * \param[in] bitfield Bit-field to write. + * + * \return Resulting value with written bit-field. + */ +#define Wr_bitfield(lvalue, mask, bitfield) (Wr_bits(lvalue, mask, (uint32_t)(bitfield) << ctz(mask))) + +/** @} */ + + +/** \name Zero-Bit Counting + * + * Under GCC, __builtin_clz and __builtin_ctz behave like macros when + * applied to constant expressions (values known at compile time), so they are + * more optimized than the use of the corresponding assembly instructions and + * they can be used as constant expressions e.g. to initialize objects having + * static storage duration, and like the corresponding assembly instructions + * when applied to non-constant expressions (values unknown at compile time), so + * they are more optimized than an assembly periphrasis. Hence, clz and ctz + * ensure a possible and optimized behavior for both constant and non-constant + * expressions. + * + * @{ */ + +/** \brief Counts the leading zero bits of the given value considered as a 32-bit integer. + * + * \param[in] u Value of which to count the leading zero bits. + * + * \return The count of leading zero bits in \a u. + */ +#if (defined __GNUC__) || (defined __CC_ARM) +# define clz(u) __builtin_clz(u) +#else +# define clz(u) (((u) == 0) ? 32 : \ + ((u) & (1ul << 31)) ? 0 : \ + ((u) & (1ul << 30)) ? 1 : \ + ((u) & (1ul << 29)) ? 2 : \ + ((u) & (1ul << 28)) ? 3 : \ + ((u) & (1ul << 27)) ? 4 : \ + ((u) & (1ul << 26)) ? 5 : \ + ((u) & (1ul << 25)) ? 6 : \ + ((u) & (1ul << 24)) ? 7 : \ + ((u) & (1ul << 23)) ? 8 : \ + ((u) & (1ul << 22)) ? 9 : \ + ((u) & (1ul << 21)) ? 10 : \ + ((u) & (1ul << 20)) ? 11 : \ + ((u) & (1ul << 19)) ? 12 : \ + ((u) & (1ul << 18)) ? 13 : \ + ((u) & (1ul << 17)) ? 14 : \ + ((u) & (1ul << 16)) ? 15 : \ + ((u) & (1ul << 15)) ? 16 : \ + ((u) & (1ul << 14)) ? 17 : \ + ((u) & (1ul << 13)) ? 18 : \ + ((u) & (1ul << 12)) ? 19 : \ + ((u) & (1ul << 11)) ? 20 : \ + ((u) & (1ul << 10)) ? 21 : \ + ((u) & (1ul << 9)) ? 22 : \ + ((u) & (1ul << 8)) ? 23 : \ + ((u) & (1ul << 7)) ? 24 : \ + ((u) & (1ul << 6)) ? 25 : \ + ((u) & (1ul << 5)) ? 26 : \ + ((u) & (1ul << 4)) ? 27 : \ + ((u) & (1ul << 3)) ? 28 : \ + ((u) & (1ul << 2)) ? 29 : \ + ((u) & (1ul << 1)) ? 30 : \ + 31) +#endif + +/** \brief Counts the trailing zero bits of the given value considered as a 32-bit integer. + * + * \param[in] u Value of which to count the trailing zero bits. + * + * \return The count of trailing zero bits in \a u. + */ +#if (defined __GNUC__) || (defined __CC_ARM) +# define ctz(u) __builtin_ctz(u) +#else +# define ctz(u) ((u) & (1ul << 0) ? 0 : \ + (u) & (1ul << 1) ? 1 : \ + (u) & (1ul << 2) ? 2 : \ + (u) & (1ul << 3) ? 3 : \ + (u) & (1ul << 4) ? 4 : \ + (u) & (1ul << 5) ? 5 : \ + (u) & (1ul << 6) ? 6 : \ + (u) & (1ul << 7) ? 7 : \ + (u) & (1ul << 8) ? 8 : \ + (u) & (1ul << 9) ? 9 : \ + (u) & (1ul << 10) ? 10 : \ + (u) & (1ul << 11) ? 11 : \ + (u) & (1ul << 12) ? 12 : \ + (u) & (1ul << 13) ? 13 : \ + (u) & (1ul << 14) ? 14 : \ + (u) & (1ul << 15) ? 15 : \ + (u) & (1ul << 16) ? 16 : \ + (u) & (1ul << 17) ? 17 : \ + (u) & (1ul << 18) ? 18 : \ + (u) & (1ul << 19) ? 19 : \ + (u) & (1ul << 20) ? 20 : \ + (u) & (1ul << 21) ? 21 : \ + (u) & (1ul << 22) ? 22 : \ + (u) & (1ul << 23) ? 23 : \ + (u) & (1ul << 24) ? 24 : \ + (u) & (1ul << 25) ? 25 : \ + (u) & (1ul << 26) ? 26 : \ + (u) & (1ul << 27) ? 27 : \ + (u) & (1ul << 28) ? 28 : \ + (u) & (1ul << 29) ? 29 : \ + (u) & (1ul << 30) ? 30 : \ + (u) & (1ul << 31) ? 31 : \ + 32) +#endif + +/** @} */ + + +/** \name Bit Reversing + * @{ */ + +/** \brief Reverses the bits of \a u8. + * + * \param[in] u8 U8 of which to reverse the bits. + * + * \return Value resulting from \a u8 with reversed bits. + */ +#define bit_reverse8(u8) ((U8)(bit_reverse32((U8)(u8)) >> 24)) + +/** \brief Reverses the bits of \a u16. + * + * \param[in] u16 U16 of which to reverse the bits. + * + * \return Value resulting from \a u16 with reversed bits. + */ +#define bit_reverse16(u16) ((uint16_t)(bit_reverse32((uint16_t)(u16)) >> 16)) + +/** \brief Reverses the bits of \a u32. + * + * \param[in] u32 U32 of which to reverse the bits. + * + * \return Value resulting from \a u32 with reversed bits. + */ +#define bit_reverse32(u32) __RBIT(u32) + +/** \brief Reverses the bits of \a u64. + * + * \param[in] u64 U64 of which to reverse the bits. + * + * \return Value resulting from \a u64 with reversed bits. + */ +#define bit_reverse64(u64) ((uint64_t)(((uint64_t)bit_reverse32((uint64_t)(u64) >> 32)) |\ + ((uint64_t)bit_reverse32((uint64_t)(u64)) << 32))) + +/** @} */ + + +/** \name Alignment + * @{ */ + +/** \brief Tests alignment of the number \a val with the \a n boundary. + * + * \param[in] val Input value. + * \param[in] n Boundary. + * + * \return \c 1 if the number \a val is aligned with the \a n boundary, else \c 0. + */ +#define Test_align(val, n) (!Tst_bits( val, (n) - 1 ) ) + +/** \brief Gets alignment of the number \a val with respect to the \a n boundary. + * + * \param[in] val Input value. + * \param[in] n Boundary. + * + * \return Alignment of the number \a val with respect to the \a n boundary. + */ +#define Get_align(val, n) ( Rd_bits( val, (n) - 1 ) ) + +/** \brief Sets alignment of the lvalue number \a lval to \a alg with respect to the \a n boundary. + * + * \param[in] lval Input/output lvalue. + * \param[in] n Boundary. + * \param[in] alg Alignment. + * + * \return New value of \a lval resulting from its alignment set to \a alg with respect to the \a n boundary. + */ +#define Set_align(lval, n, alg) ( Wr_bits(lval, (n) - 1, alg) ) + +/** \brief Aligns the number \a val with the upper \a n boundary. + * + * \param[in] val Input value. + * \param[in] n Boundary. + * + * \return Value resulting from the number \a val aligned with the upper \a n boundary. + */ +#define Align_up( val, n) (((val) + ((n) - 1)) & ~((n) - 1)) + +/** \brief Aligns the number \a val with the lower \a n boundary. + * + * \param[in] val Input value. + * \param[in] n Boundary. + * + * \return Value resulting from the number \a val aligned with the lower \a n boundary. + */ +#define Align_down(val, n) ( (val) & ~((n) - 1)) + +/** @} */ + + +/** \name Mathematics + * + * The same considerations as for clz and ctz apply here but GCC does not + * provide built-in functions to access the assembly instructions abs, min and + * max and it does not produce them by itself in most cases, so two sets of + * macros are defined here: + * - Abs, Min and Max to apply to constant expressions (values known at + * compile time); + * - abs, min and max to apply to non-constant expressions (values unknown at + * compile time), abs is found in stdlib.h. + * + * @{ */ + +/** \brief Takes the absolute value of \a a. + * + * \param[in] a Input value. + * + * \return Absolute value of \a a. + * + * \note More optimized if only used with values known at compile time. + */ +#define Abs(a) (((a) < 0 ) ? -(a) : (a)) + +/** \brief Takes the minimal value of \a a and \a b. + * + * \param[in] a Input value. + * \param[in] b Input value. + * + * \return Minimal value of \a a and \a b. + * + * \note More optimized if only used with values known at compile time. + */ +#define Min(a, b) (((a) < (b)) ? (a) : (b)) + +/** \brief Takes the maximal value of \a a and \a b. + * + * \param[in] a Input value. + * \param[in] b Input value. + * + * \return Maximal value of \a a and \a b. + * + * \note More optimized if only used with values known at compile time. + */ +#define Max(a, b) (((a) > (b)) ? (a) : (b)) + +/** \brief Takes the minimal value of \a a and \a b. + * + * \param[in] a Input value. + * \param[in] b Input value. + * + * \return Minimal value of \a a and \a b. + * + * \note More optimized if only used with values unknown at compile time. + */ +#define min(a, b) Min(a, b) + +/** \brief Takes the maximal value of \a a and \a b. + * + * \param[in] a Input value. + * \param[in] b Input value. + * + * \return Maximal value of \a a and \a b. + * + * \note More optimized if only used with values unknown at compile time. + */ +#define max(a, b) Max(a, b) + +/** @} */ + + +/** \brief Calls the routine at address \a addr. + * + * It generates a long call opcode. + * + * For example, `Long_call(0x80000000)' generates a software reset on a UC3 if + * it is invoked from the CPU supervisor mode. + * + * \param[in] addr Address of the routine to call. + * + * \note It may be used as a long jump opcode in some special cases. + */ +#define Long_call(addr) ((*(void (*)(void))(addr))()) + + +/** \name MCU Endianism Handling + * ARM is MCU little endian. + * + * @{ */ +#define BE16(x) Swap16(x) +#define LE16(x) (x) + +#define le16_to_cpu(x) (x) +#define cpu_to_le16(x) (x) +#define LE16_TO_CPU(x) (x) +#define CPU_TO_LE16(x) (x) + +#define be16_to_cpu(x) Swap16(x) +#define cpu_to_be16(x) Swap16(x) +#define BE16_TO_CPU(x) Swap16(x) +#define CPU_TO_BE16(x) Swap16(x) + +#define le32_to_cpu(x) (x) +#define cpu_to_le32(x) (x) +#define LE32_TO_CPU(x) (x) +#define CPU_TO_LE32(x) (x) + +#define be32_to_cpu(x) swap32(x) +#define cpu_to_be32(x) swap32(x) +#define BE32_TO_CPU(x) swap32(x) +#define CPU_TO_BE32(x) swap32(x) +/** @} */ + + +/** \name Endianism Conversion + * + * The same considerations as for clz and ctz apply here but GCC's + * __builtin_bswap_32 and __builtin_bswap_64 do not behave like macros when + * applied to constant expressions, so two sets of macros are defined here: + * - Swap16, Swap32 and Swap64 to apply to constant expressions (values known + * at compile time); + * - swap16, swap32 and swap64 to apply to non-constant expressions (values + * unknown at compile time). + * + * @{ */ + +/** \brief Toggles the endianism of \a u16 (by swapping its bytes). + * + * \param[in] u16 U16 of which to toggle the endianism. + * + * \return Value resulting from \a u16 with toggled endianism. + * + * \note More optimized if only used with values known at compile time. + */ +#define Swap16(u16) ((uint16_t)(((uint16_t)(u16) >> 8) |\ + ((uint16_t)(u16) << 8))) + +/** \brief Toggles the endianism of \a u32 (by swapping its bytes). + * + * \param[in] u32 U32 of which to toggle the endianism. + * + * \return Value resulting from \a u32 with toggled endianism. + * + * \note More optimized if only used with values known at compile time. + */ +#define Swap32(u32) ((uint32_t)(((uint32_t)Swap16((uint32_t)(u32) >> 16)) |\ + ((uint32_t)Swap16((uint32_t)(u32)) << 16))) + +/** \brief Toggles the endianism of \a u64 (by swapping its bytes). + * + * \param[in] u64 U64 of which to toggle the endianism. + * + * \return Value resulting from \a u64 with toggled endianism. + * + * \note More optimized if only used with values known at compile time. + */ +#define Swap64(u64) ((uint64_t)(((uint64_t)Swap32((uint64_t)(u64) >> 32)) |\ + ((uint64_t)Swap32((uint64_t)(u64)) << 32))) + +/** \brief Toggles the endianism of \a u16 (by swapping its bytes). + * + * \param[in] u16 U16 of which to toggle the endianism. + * + * \return Value resulting from \a u16 with toggled endianism. + * + * \note More optimized if only used with values unknown at compile time. + */ +#define swap16(u16) Swap16(u16) + +/** \brief Toggles the endianism of \a u32 (by swapping its bytes). + * + * \param[in] u32 U32 of which to toggle the endianism. + * + * \return Value resulting from \a u32 with toggled endianism. + * + * \note More optimized if only used with values unknown at compile time. + */ +#if (defined __GNUC__) +# define swap32(u32) ((uint32_t)__builtin_bswap32((uint32_t)(u32))) +#else +# define swap32(u32) Swap32(u32) +#endif + +/** \brief Toggles the endianism of \a u64 (by swapping its bytes). + * + * \param[in] u64 U64 of which to toggle the endianism. + * + * \return Value resulting from \a u64 with toggled endianism. + * + * \note More optimized if only used with values unknown at compile time. + */ +#if (defined __GNUC__) +# define swap64(u64) ((uint64_t)__builtin_bswap64((uint64_t)(u64))) +#else +# define swap64(u64) ((uint64_t)(((uint64_t)swap32((uint64_t)(u64) >> 32)) |\ + ((uint64_t)swap32((uint64_t)(u64)) << 32))) +#endif + +/** @} */ + + +/** \name Target Abstraction + * + * @{ */ + +#define _GLOBEXT_ extern /**< extern storage-class specifier. */ +#define _CONST_TYPE_ const /**< const type qualifier. */ +#define _MEM_TYPE_SLOW_ /**< Slow memory type. */ +#define _MEM_TYPE_MEDFAST_ /**< Fairly fast memory type. */ +#define _MEM_TYPE_FAST_ /**< Fast memory type. */ + +#define memcmp_ram2ram memcmp /**< Target-specific memcmp of RAM to RAM. */ +#define memcmp_code2ram memcmp /**< Target-specific memcmp of RAM to NVRAM. */ +#define memcpy_ram2ram memcpy /**< Target-specific memcpy from RAM to RAM. */ +#define memcpy_code2ram memcpy /**< Target-specific memcpy from NVRAM to RAM. */ + +/** @} */ + +/** + * \brief Calculate \f$ \left\lceil \frac{a}{b} \right\rceil \f$ using + * integer arithmetic. + * + * \param[in] a An integer + * \param[in] b Another integer + * + * \return (\a a / \a b) rounded up to the nearest integer. + */ +#define div_ceil(a, b) (((a) + (b) - 1) / (b)) + +#endif /* #ifndef __ASSEMBLY__ */ +#ifdef __ICCARM__ +/** \name Compiler Keywords + * + * Port of some keywords from GCC to IAR Embedded Workbench. + * + * @{ */ + +#define __asm__ asm +#define __inline__ inline +#define __volatile__ + +/** @} */ + +#endif + +#define FUNC_PTR void * +/** + * \def unused + * \brief Marking \a v as a unused parameter or value. + */ +#define unused(v) do { (void)(v); } while(0) + +/* Define RAMFUNC attribute */ +#if defined ( __CC_ARM ) /* Keil uVision 4 */ +# define RAMFUNC __attribute__ ((section(".ramfunc"))) +#elif defined ( __ICCARM__ ) /* IAR Ewarm 5.41+ */ +# define RAMFUNC __ramfunc +#elif defined ( __GNUC__ ) /* GCC CS3 2009q3-68 */ +# define RAMFUNC __attribute__ ((section(".ramfunc"))) +#endif + +/* Define OPTIMIZE_HIGH attribute */ +#if defined ( __CC_ARM ) /* Keil uVision 4 */ +# define OPTIMIZE_HIGH _Pragma("O3") +#elif defined ( __ICCARM__ ) /* IAR Ewarm 5.41+ */ +# define OPTIMIZE_HIGH _Pragma("optimize=high") +#elif defined ( __GNUC__ ) /* GCC CS3 2009q3-68 */ +# define OPTIMIZE_HIGH __attribute__((optimize(s))) +#endif +#define PASS 0 +#define FAIL 1 +#define LOW 0 +#define HIGH 1 + +typedef int8_t S8 ; //!< 8-bit signed integer. +typedef uint8_t U8 ; //!< 8-bit unsigned integer. +typedef int16_t S16; //!< 16-bit signed integer. +typedef uint16_t U16; //!< 16-bit unsigned integer. +typedef int32_t S32; //!< 32-bit signed integer. +typedef uint32_t U32; //!< 32-bit unsigned integer. +typedef int64_t S64; //!< 64-bit signed integer. +typedef uint64_t U64; //!< 64-bit unsigned integer. +typedef float F32; //!< 32-bit floating-point number. +typedef double F64; //!< 64-bit floating-point number. + +#define MSB(u16) (((U8 *)&(u16))[1]) //!< Most significant byte of \a u16. +#define LSB(u16) (((U8 *)&(u16))[0]) //!< Least significant byte of \a u16. + +#define MSH(u32) (((U16 *)&(u32))[1]) //!< Most significant half-word of \a u32. +#define LSH(u32) (((U16 *)&(u32))[0]) //!< Least significant half-word of \a u32. +#define MSB0W(u32) (((U8 *)&(u32))[3]) //!< Most significant byte of 1st rank of \a u32. +#define MSB1W(u32) (((U8 *)&(u32))[2]) //!< Most significant byte of 2nd rank of \a u32. +#define MSB2W(u32) (((U8 *)&(u32))[1]) //!< Most significant byte of 3rd rank of \a u32. +#define MSB3W(u32) (((U8 *)&(u32))[0]) //!< Most significant byte of 4th rank of \a u32. +#define LSB3W(u32) MSB0W(u32) //!< Least significant byte of 4th rank of \a u32. +#define LSB2W(u32) MSB1W(u32) //!< Least significant byte of 3rd rank of \a u32. +#define LSB1W(u32) MSB2W(u32) //!< Least significant byte of 2nd rank of \a u32. +#define LSB0W(u32) MSB3W(u32) //!< Least significant byte of 1st rank of \a u32. + +#define MSW(u64) (((U32 *)&(u64))[1]) //!< Most significant word of \a u64. +#define LSW(u64) (((U32 *)&(u64))[0]) //!< Least significant word of \a u64. +#define MSH0(u64) (((U16 *)&(u64))[3]) //!< Most significant half-word of 1st rank of \a u64. +#define MSH1(u64) (((U16 *)&(u64))[2]) //!< Most significant half-word of 2nd rank of \a u64. +#define MSH2(u64) (((U16 *)&(u64))[1]) //!< Most significant half-word of 3rd rank of \a u64. +#define MSH3(u64) (((U16 *)&(u64))[0]) //!< Most significant half-word of 4th rank of \a u64. +#define LSH3(u64) MSH0(u64) //!< Least significant half-word of 4th rank of \a u64. +#define LSH2(u64) MSH1(u64) //!< Least significant half-word of 3rd rank of \a u64. +#define LSH1(u64) MSH2(u64) //!< Least significant half-word of 2nd rank of \a u64. +#define LSH0(u64) MSH3(u64) //!< Least significant half-word of 1st rank of \a u64. +#define MSB0D(u64) (((U8 *)&(u64))[7]) //!< Most significant byte of 1st rank of \a u64. +#define MSB1D(u64) (((U8 *)&(u64))[6]) //!< Most significant byte of 2nd rank of \a u64. +#define MSB2D(u64) (((U8 *)&(u64))[5]) //!< Most significant byte of 3rd rank of \a u64. +#define MSB3D(u64) (((U8 *)&(u64))[4]) //!< Most significant byte of 4th rank of \a u64. +#define MSB4D(u64) (((U8 *)&(u64))[3]) //!< Most significant byte of 5th rank of \a u64. +#define MSB5D(u64) (((U8 *)&(u64))[2]) //!< Most significant byte of 6th rank of \a u64. +#define MSB6D(u64) (((U8 *)&(u64))[1]) //!< Most significant byte of 7th rank of \a u64. +#define MSB7D(u64) (((U8 *)&(u64))[0]) //!< Most significant byte of 8th rank of \a u64. +#define LSB7D(u64) MSB0D(u64) //!< Least significant byte of 8th rank of \a u64. +#define LSB6D(u64) MSB1D(u64) //!< Least significant byte of 7th rank of \a u64. +#define LSB5D(u64) MSB2D(u64) //!< Least significant byte of 6th rank of \a u64. +#define LSB4D(u64) MSB3D(u64) //!< Least significant byte of 5th rank of \a u64. +#define LSB3D(u64) MSB4D(u64) //!< Least significant byte of 4th rank of \a u64. +#define LSB2D(u64) MSB5D(u64) //!< Least significant byte of 3rd rank of \a u64. +#define LSB1D(u64) MSB6D(u64) //!< Least significant byte of 2nd rank of \a u64. +#define LSB0D(u64) MSB7D(u64) //!< Least significant byte of 1st rank of \a u64. + +#define LSB0(u32) LSB0W(u32) //!< Least significant byte of 1st rank of \a u32. +#define LSB1(u32) LSB1W(u32) //!< Least significant byte of 2nd rank of \a u32. +#define LSB2(u32) LSB2W(u32) //!< Least significant byte of 3rd rank of \a u32. +#define LSB3(u32) LSB3W(u32) //!< Least significant byte of 4th rank of \a u32. +#define MSB3(u32) MSB3W(u32) //!< Most significant byte of 4th rank of \a u32. +#define MSB2(u32) MSB2W(u32) //!< Most significant byte of 3rd rank of \a u32. +#define MSB1(u32) MSB1W(u32) //!< Most significant byte of 2nd rank of \a u32. +#define MSB0(u32) MSB0W(u32) //!< Most significant byte of 1st rank of \a u32. + +#if defined(__ICCARM__) +#define SHORTENUM __packed +#elif defined(__GNUC__) +#define SHORTENUM __attribute__((packed)) +#endif + +/* No operation */ +#if defined(__ICCARM__) +#define nop() __no_operation() +#elif defined(__GNUC__) +#define nop() (__NOP()) +#endif + +#define FLASH_DECLARE(x) const x +#define FLASH_EXTERN(x) extern const x +#define PGM_READ_BYTE(x) *(x) +#define PGM_READ_WORD(x) *(x) +#define MEMCPY_ENDIAN memcpy +#define PGM_READ_BLOCK(dst, src, len) memcpy((dst), (src), (len)) + +/*Defines the Flash Storage for the request and response of MAC*/ +#define CMD_ID_OCTET (0) + +/* Converting of values from CPU endian to little endian. */ +#define CPU_ENDIAN_TO_LE16(x) (x) +#define CPU_ENDIAN_TO_LE32(x) (x) +#define CPU_ENDIAN_TO_LE64(x) (x) + +/* Converting of values from little endian to CPU endian. */ +#define LE16_TO_CPU_ENDIAN(x) (x) +#define LE32_TO_CPU_ENDIAN(x) (x) +#define LE64_TO_CPU_ENDIAN(x) (x) + +/* Converting of constants from little endian to CPU endian. */ +#define CLE16_TO_CPU_ENDIAN(x) (x) +#define CLE32_TO_CPU_ENDIAN(x) (x) +#define CLE64_TO_CPU_ENDIAN(x) (x) + +/* Converting of constants from CPU endian to little endian. */ +#define CCPU_ENDIAN_TO_LE16(x) (x) +#define CCPU_ENDIAN_TO_LE32(x) (x) +#define CCPU_ENDIAN_TO_LE64(x) (x) + +#define ADDR_COPY_DST_SRC_16(dst, src) ((dst) = (src)) +#define ADDR_COPY_DST_SRC_64(dst, src) ((dst) = (src)) + +/** + * @brief Converts a 64-Bit value into a 8 Byte array + * + * @param[in] value 64-Bit value + * @param[out] data Pointer to the 8 Byte array to be updated with 64-Bit value + * @ingroup apiPalApi + */ +static inline void convert_64_bit_to_byte_array(uint64_t value, uint8_t *data) +{ + uint8_t index = 0; + + while (index < 8) + { + data[index++] = value & 0xFF; + value = value >> 8; + } +} + +/** + * @brief Converts a 16-Bit value into a 2 Byte array + * + * @param[in] value 16-Bit value + * @param[out] data Pointer to the 2 Byte array to be updated with 16-Bit value + * @ingroup apiPalApi + */ +static inline void convert_16_bit_to_byte_array(uint16_t value, uint8_t *data) +{ + data[0] = value & 0xFF; + data[1] = (value >> 8) & 0xFF; +} + +/* Converts a 16-Bit value into a 2 Byte array */ +static inline void convert_spec_16_bit_to_byte_array(uint16_t value, uint8_t *data) +{ + data[0] = value & 0xFF; + data[1] = (value >> 8) & 0xFF; +} + +/* Converts a 16-Bit value into a 2 Byte array */ +static inline void convert_16_bit_to_byte_address(uint16_t value, uint8_t *data) +{ + data[0] = value & 0xFF; + data[1] = (value >> 8) & 0xFF; +} + +/* + * @brief Converts a 2 Byte array into a 16-Bit value + * + * @param data Specifies the pointer to the 2 Byte array + * + * @return 16-Bit value + * @ingroup apiPalApi + */ +static inline uint16_t convert_byte_array_to_16_bit(uint8_t *data) +{ + return (data[0] | ((uint16_t)data[1] << 8)); +} + +/* Converts a 4 Byte array into a 32-Bit value */ +static inline uint32_t convert_byte_array_to_32_bit(uint8_t *data) +{ + union + { + uint32_t u32; + uint8_t u8[4]; + }long_addr; + uint8_t index; + for (index = 0; index < 4; index++) + { + long_addr.u8[index] = *data++; + } + return long_addr.u32; +} + +/** + * @brief Converts a 8 Byte array into a 64-Bit value + * + * @param data Specifies the pointer to the 8 Byte array + * + * @return 64-Bit value + * @ingroup apiPalApi + */ +static inline uint64_t convert_byte_array_to_64_bit(uint8_t *data) +{ + union + { + uint64_t u64; + uint8_t u8[8]; + } long_addr; + + uint8_t index; + + for (index = 0; index < 8; index++) + { + long_addr.u8[index] = *data++; + } + + return long_addr.u64; +} + +/** @} */ + +#endif /* UTILS_COMPILER_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/gclk.c b/feather_sensor_lte/libraries/Adafruit_ASFcore/gclk.c new file mode 100644 index 0000000..1199a19 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/gclk.c @@ -0,0 +1,522 @@ +/** + * \file + * + * \brief SAM D21/R21/DA0/DA1 Generic Clock Driver + * + * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#include +#include +#include + +/** + * \brief Determines if the hardware module(s) are currently synchronizing to the bus. + * + * Checks to see if the underlying hardware peripheral module(s) are currently + * synchronizing across multiple clock domains to the hardware bus, This + * function can be used to delay further operations on a module until such time + * that it is ready, to prevent blocking delays for synchronization in the + * user application. + * + * \return Synchronization status of the underlying hardware module(s). + * + * \retval false if the module has completed synchronization + * \retval true if the module synchronization is ongoing + */ +static inline bool system_gclk_is_syncing(void) +{ + if (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY){ + return true; + } + + return false; +} + +/** + * \brief Initializes the GCLK driver. + * + * Initializes the Generic Clock module, disabling and resetting all active + * Generic Clock Generators and Channels to their power-on default values. + */ +void system_gclk_init(void) +{ + /* Turn on the digital interface clock */ + system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBA, PM_APBAMASK_GCLK); + + /* Software reset the module to ensure it is re-initialized correctly */ + GCLK->CTRL.reg = GCLK_CTRL_SWRST; + while (GCLK->CTRL.reg & GCLK_CTRL_SWRST) { + /* Wait for reset to complete */ + } +} + +/** + * \brief Writes a Generic Clock Generator configuration to the hardware module. + * + * Writes out a given configuration of a Generic Clock Generator configuration + * to the hardware module. + * + * \note Changing the clock source on the fly (on a running + * generator) can take additional time if the clock source is configured + * to only run on-demand (ONDEMAND bit is set) and it is not currently + * running (no peripheral is requesting the clock source). In this case + * the GCLK will request the new clock while still keeping a request to + * the old clock source until the new clock source is ready. + * + * \note This function will not start a generator that is not already running; + * to start the generator, call \ref system_gclk_gen_enable() + * after configuring a generator. + * + * \param[in] generator Generic Clock Generator index to configure + * \param[in] config Configuration settings for the generator + */ +void system_gclk_gen_set_config( + const uint8_t generator, + struct system_gclk_gen_config *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Cache new register configurations to minimize sync requirements. */ + uint32_t new_genctrl_config = (generator << GCLK_GENCTRL_ID_Pos); + uint32_t new_gendiv_config = (generator << GCLK_GENDIV_ID_Pos); + + /* Select the requested source clock for the generator */ + new_genctrl_config |= config->source_clock << GCLK_GENCTRL_SRC_Pos; + + /* Configure the clock to be either high or low when disabled */ + if (config->high_when_disabled) { + new_genctrl_config |= GCLK_GENCTRL_OOV; + } + + /* Configure if the clock output to I/O pin should be enabled. */ + if (config->output_enable) { + new_genctrl_config |= GCLK_GENCTRL_OE; + } + + /* Set division factor */ + if (config->division_factor > 1) { + /* Check if division is a power of two */ + if (((config->division_factor & (config->division_factor - 1)) == 0)) { + /* Determine the index of the highest bit set to get the + * division factor that must be loaded into the division + * register */ + + uint32_t div2_count = 0; + + uint32_t mask; + for (mask = (1UL << 1); mask < config->division_factor; + mask <<= 1) { + div2_count++; + } + + /* Set binary divider power of 2 division factor */ + new_gendiv_config |= div2_count << GCLK_GENDIV_DIV_Pos; + new_genctrl_config |= GCLK_GENCTRL_DIVSEL; + } else { + /* Set integer division factor */ + + new_gendiv_config |= + (config->division_factor) << GCLK_GENDIV_DIV_Pos; + + /* Enable non-binary division with increased duty cycle accuracy */ + new_genctrl_config |= GCLK_GENCTRL_IDC; + } + + } + + /* Enable or disable the clock in standby mode */ + if (config->run_in_standby) { + new_genctrl_config |= GCLK_GENCTRL_RUNSTDBY; + } + + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + system_interrupt_enter_critical_section(); + + /* Select the correct generator */ + *((uint8_t*)&GCLK->GENDIV.reg) = generator; + + /* Write the new generator configuration */ + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + GCLK->GENDIV.reg = new_gendiv_config; + + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + GCLK->GENCTRL.reg = new_genctrl_config | (GCLK->GENCTRL.reg & GCLK_GENCTRL_GENEN); + + system_interrupt_leave_critical_section(); +} + +/** + * \brief Enables a Generic Clock Generator that was previously configured. + * + * Starts the clock generation of a Generic Clock Generator that was previously + * configured via a call to \ref system_gclk_gen_set_config(). + * + * \param[in] generator Generic Clock Generator index to enable + */ +void system_gclk_gen_enable( + const uint8_t generator) +{ + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + system_interrupt_enter_critical_section(); + + /* Select the requested generator */ + *((uint8_t*)&GCLK->GENCTRL.reg) = generator; + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + /* Enable generator */ + GCLK->GENCTRL.reg |= GCLK_GENCTRL_GENEN; + + system_interrupt_leave_critical_section(); +} + +/** + * \brief Disables a Generic Clock Generator that was previously enabled. + * + * Stops the clock generation of a Generic Clock Generator that was previously + * started via a call to \ref system_gclk_gen_enable(). + * + * \param[in] generator Generic Clock Generator index to disable + */ +void system_gclk_gen_disable( + const uint8_t generator) +{ + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + system_interrupt_enter_critical_section(); + + /* Select the requested generator */ + *((uint8_t*)&GCLK->GENCTRL.reg) = generator; + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + /* Disable generator */ + GCLK->GENCTRL.reg &= ~GCLK_GENCTRL_GENEN; + while (GCLK->GENCTRL.reg & GCLK_GENCTRL_GENEN) { + /* Wait for clock to become disabled */ + } + + system_interrupt_leave_critical_section(); +} + +/** + * \brief Determins if the specified Generic Clock Generator is enabled. + * + * \param[in] generator Generic Clock Generator index to check + * + * \return The enabled status. + * \retval true The Generic Clock Generator is enabled + * \retval false The Generic Clock Generator is disabled + */ +bool system_gclk_gen_is_enabled( + const uint8_t generator) +{ + bool enabled; + + system_interrupt_enter_critical_section(); + + /* Select the requested generator */ + *((uint8_t*)&GCLK->GENCTRL.reg) = generator; + /* Obtain the enabled status */ + enabled = (GCLK->GENCTRL.reg & GCLK_GENCTRL_GENEN); + + system_interrupt_leave_critical_section(); + + return enabled; +} + +/** + * \brief Retrieves the clock frequency of a Generic Clock generator. + * + * Determines the clock frequency (in Hz) of a specified Generic Clock + * generator, used as a source to a Generic Clock Channel module. + * + * \param[in] generator Generic Clock Generator index + * + * \return The frequency of the generic clock generator, in Hz. + */ +uint32_t system_gclk_gen_get_hz( + const uint8_t generator) +{ + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + system_interrupt_enter_critical_section(); + + /* Select the appropriate generator */ + *((uint8_t*)&GCLK->GENCTRL.reg) = generator; + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + /* Get the frequency of the source connected to the GCLK generator */ + uint32_t gen_input_hz = system_clock_source_get_hz( + (enum system_clock_source)GCLK->GENCTRL.bit.SRC); + + *((uint8_t*)&GCLK->GENCTRL.reg) = generator; + + uint8_t divsel = GCLK->GENCTRL.bit.DIVSEL; + + /* Select the appropriate generator division register */ + *((uint8_t*)&GCLK->GENDIV.reg) = generator; + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + uint32_t divider = GCLK->GENDIV.bit.DIV; + + system_interrupt_leave_critical_section(); + + /* Check if the generator is using fractional or binary division */ + if (!divsel && divider > 1) { + gen_input_hz /= divider; + } else if (divsel) { + gen_input_hz >>= (divider+1); + } + + return gen_input_hz; +} + +/** + * \brief Writes a Generic Clock configuration to the hardware module. + * + * Writes out a given configuration of a Generic Clock configuration to the + * hardware module. If the clock is currently running, it will be stopped. + * + * \note Once called the clock will not be running; to start the clock, + * call \ref system_gclk_chan_enable() after configuring a clock channel. + * + * \param[in] channel Generic Clock channel to configure + * \param[in] config Configuration settings for the clock + * + */ +void system_gclk_chan_set_config( + const uint8_t channel, + struct system_gclk_chan_config *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Cache the new config to reduce sync requirements */ + uint32_t new_clkctrl_config = (channel << GCLK_CLKCTRL_ID_Pos); + + /* Select the desired generic clock generator */ + new_clkctrl_config |= config->source_generator << GCLK_CLKCTRL_GEN_Pos; + + /* Disable generic clock channel */ + system_gclk_chan_disable(channel); + + /* Write the new configuration */ + GCLK->CLKCTRL.reg = new_clkctrl_config; +} + +/** + * \brief Enables a Generic Clock that was previously configured. + * + * Starts the clock generation of a Generic Clock that was previously + * configured via a call to \ref system_gclk_chan_set_config(). + * + * \param[in] channel Generic Clock channel to enable + */ +void system_gclk_chan_enable( + const uint8_t channel) +{ + system_interrupt_enter_critical_section(); + + /* Select the requested generator channel */ + *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; + + /* Enable the generic clock */ + GCLK->CLKCTRL.reg |= GCLK_CLKCTRL_CLKEN; + + system_interrupt_leave_critical_section(); +} + +/** + * \brief Disables a Generic Clock that was previously enabled. + * + * Stops the clock generation of a Generic Clock that was previously started + * via a call to \ref system_gclk_chan_enable(). + * + * \param[in] channel Generic Clock channel to disable + */ +void system_gclk_chan_disable( + const uint8_t channel) +{ + system_interrupt_enter_critical_section(); + + /* Select the requested generator channel */ + *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; + + /* Sanity check WRTLOCK */ + Assert(!GCLK->CLKCTRL.bit.WRTLOCK); + + /* Switch to known-working source so that the channel can be disabled */ + uint32_t prev_gen_id = GCLK->CLKCTRL.bit.GEN; + GCLK->CLKCTRL.bit.GEN = 0; + + /* Disable the generic clock */ + GCLK->CLKCTRL.reg &= ~GCLK_CLKCTRL_CLKEN; + while (GCLK->CLKCTRL.reg & GCLK_CLKCTRL_CLKEN) { + /* Wait for clock to become disabled */ + } + + /* Restore previous configured clock generator */ + GCLK->CLKCTRL.bit.GEN = prev_gen_id; + + system_interrupt_leave_critical_section(); +} + +/** + * \brief Determins if the specified Generic Clock channel is enabled. + * + * \param[in] channel Generic Clock Channel index + * + * \return The enabled status. + * \retval true The Generic Clock channel is enabled + * \retval false The Generic Clock channel is disabled + */ +bool system_gclk_chan_is_enabled( + const uint8_t channel) +{ + bool enabled; + + system_interrupt_enter_critical_section(); + + /* Select the requested generic clock channel */ + *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; + enabled = GCLK->CLKCTRL.bit.CLKEN; + + system_interrupt_leave_critical_section(); + + return enabled; +} + +/** + * \brief Locks a Generic Clock channel from further configuration writes. + * + * Locks a generic clock channel from further configuration writes. It is only + * possible to unlock the channel configuration through a power on reset. + * + * \param[in] channel Generic Clock channel to enable + */ +void system_gclk_chan_lock( + const uint8_t channel) +{ + system_interrupt_enter_critical_section(); + + /* Select the requested generator channel */ + *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; + + /* Lock the generic clock */ + GCLK->CLKCTRL.reg |= GCLK_CLKCTRL_WRTLOCK; + + system_interrupt_leave_critical_section(); +} + +/** + * \brief Determins if the specified Generic Clock channel is locked. + * + * \param[in] channel Generic Clock Channel index + * + * \return The lock status. + * \retval true The Generic Clock channel is locked + * \retval false The Generic Clock channel is not locked + */ +bool system_gclk_chan_is_locked( + const uint8_t channel) +{ + bool locked; + + system_interrupt_enter_critical_section(); + + /* Select the requested generic clock channel */ + *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; + locked = GCLK->CLKCTRL.bit.WRTLOCK; + + system_interrupt_leave_critical_section(); + + return locked; +} + +/** + * \brief Retrieves the clock frequency of a Generic Clock channel. + * + * Determines the clock frequency (in Hz) of a specified Generic Clock + * channel, used as a source to a device peripheral module. + * + * \param[in] channel Generic Clock Channel index + * + * \return The frequency of the generic clock channel, in Hz. + */ +uint32_t system_gclk_chan_get_hz( + const uint8_t channel) +{ + uint8_t gen_id; + + system_interrupt_enter_critical_section(); + + /* Select the requested generic clock channel */ + *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; + gen_id = GCLK->CLKCTRL.bit.GEN; + + system_interrupt_leave_critical_section(); + + /* Return the clock speed of the associated GCLK generator */ + return system_gclk_gen_get_hz(gen_id); +} diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/gclk.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/gclk.h new file mode 100644 index 0000000..1e3caf3 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/gclk.h @@ -0,0 +1,307 @@ +/** + * \file + * + * \brief SAM Generic Clock Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef SYSTEM_CLOCK_GCLK_H_INCLUDED +#define SYSTEM_CLOCK_GCLK_H_INCLUDED + +/** + * \addtogroup asfdoc_sam0_system_clock_group + * + * @{ + */ + +#include "compiler.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief List of available GCLK generators. + * + * List of Available GCLK generators. This enum is used in the peripheral + * device drivers to select the GCLK generator to be used for its operation. + * + * The number of GCLK generators available is device dependent. + */ +enum gclk_generator { + /** GCLK generator channel 0 */ + GCLK_GENERATOR_0, +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 0) + /** GCLK generator channel 1 */ + GCLK_GENERATOR_1, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 1) + /** GCLK generator channel 2 */ + GCLK_GENERATOR_2, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 2) + /** GCLK generator channel 3 */ + GCLK_GENERATOR_3, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 3) + /** GCLK generator channel 4 */ + GCLK_GENERATOR_4, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 4) + /** GCLK generator channel 5 */ + GCLK_GENERATOR_5, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 5) + /** GCLK generator channel 6 */ + GCLK_GENERATOR_6, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 6) + /** GCLK generator channel 7 */ + GCLK_GENERATOR_7, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 7) + /** GCLK generator channel 8 */ + GCLK_GENERATOR_8, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 8) + /** GCLK generator channel 9 */ + GCLK_GENERATOR_9, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 9) + /** GCLK generator channel 10 */ + GCLK_GENERATOR_10, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 10) + /** GCLK generator channel 11 */ + GCLK_GENERATOR_11, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 11) + /** GCLK generator channel 12 */ + GCLK_GENERATOR_12, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 12) + /** GCLK generator channel 13 */ + GCLK_GENERATOR_13, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 13) + /** GCLK generator channel 14 */ + GCLK_GENERATOR_14, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 14) + /** GCLK generator channel 15 */ + GCLK_GENERATOR_15, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 15) + /** GCLK generator channel 16 */ + GCLK_GENERATOR_16, +#endif +}; + +/** + * \brief Generic Clock Generator configuration structure. + * + * Configuration structure for a Generic Clock Generator channel. This + * structure should be initialized by the + * \ref system_gclk_gen_get_config_defaults() function before being modified by + * the user application. + */ +struct system_gclk_gen_config { + /** Source clock input channel index, see the \ref system_clock_source */ + uint8_t source_clock; + /** If \c true, the generator output level is high when disabled */ + bool high_when_disabled; + /** Integer division factor of the clock output compared to the input */ + uint32_t division_factor; + /** If \c true, the clock is kept enabled during device standby mode */ + bool run_in_standby; + /** If \c true, enables GCLK generator clock output to a GPIO pin */ + bool output_enable; +}; + +/** + * \brief Generic Clock configuration structure. + * + * Configuration structure for a Generic Clock channel. This structure + * should be initialized by the \ref system_gclk_chan_get_config_defaults() + * function before being modified by the user application. + */ +struct system_gclk_chan_config { + /** Generic Clock Generator source channel */ + enum gclk_generator source_generator; +}; + +/** \name Generic Clock Management + * @{ + */ +void system_gclk_init(void); + +/** @} */ + + +/** + * \name Generic Clock Management (Generators) + * @{ + */ + +/** + * \brief Initializes a Generic Clock Generator configuration structure to defaults. + * + * Initializes a given Generic Clock Generator configuration structure to + * a set of known default values. This function should be called on all + * new instances of these configuration structures before being modified + * by the user application. + * + * The default configuration is: + * \li Clock is generated undivided from the source frequency + * \li Clock generator output is low when the generator is disabled + * \li The input clock is sourced from input clock channel 0 + * \li Clock will be disabled during sleep + * \li The clock output will not be routed to a physical GPIO pin + * + * \param[out] config Configuration structure to initialize to default values + */ +static inline void system_gclk_gen_get_config_defaults( + struct system_gclk_gen_config *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Default configuration values */ + config->division_factor = 1; + config->high_when_disabled = false; +#if SAML21 || SAML22 + config->source_clock = GCLK_SOURCE_OSC16M; +#elif (SAMC20) || (SAMC21) + config->source_clock = GCLK_SOURCE_OSC48M; +#else + config->source_clock = GCLK_SOURCE_OSC8M; +#endif + config->run_in_standby = false; + config->output_enable = false; +} + +void system_gclk_gen_set_config( + const uint8_t generator, + struct system_gclk_gen_config *const config); + +void system_gclk_gen_enable( + const uint8_t generator); + +void system_gclk_gen_disable( + const uint8_t generator); + +bool system_gclk_gen_is_enabled( + const uint8_t generator); + +/** @} */ + + +/** + * \name Generic Clock Management (Channels) + * @{ + */ + +/** + * \brief Initializes a Generic Clock configuration structure to defaults. + * + * Initializes a given Generic Clock configuration structure to a set of + * known default values. This function should be called on all new + * instances of these configuration structures before being modified by the + * user application. + * + * The default configuration is as follows: + * \li Clock is sourced from the Generic Clock Generator channel 0 + * \li Clock configuration will not be write-locked when set + * + * \param[out] config Configuration structure to initialize to default values + */ +static inline void system_gclk_chan_get_config_defaults( + struct system_gclk_chan_config *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Default configuration values */ + config->source_generator = GCLK_GENERATOR_0; +} + +void system_gclk_chan_set_config( + const uint8_t channel, + struct system_gclk_chan_config *const config); + +void system_gclk_chan_enable( + const uint8_t channel); + +void system_gclk_chan_disable( + const uint8_t channel); + +bool system_gclk_chan_is_enabled( + const uint8_t channel); + +void system_gclk_chan_lock( + const uint8_t channel); + +bool system_gclk_chan_is_locked( + const uint8_t channel); + +/** @} */ + + +/** + * \name Generic Clock Frequency Retrieval + * @{ + */ + +uint32_t system_gclk_gen_get_hz( + const uint8_t generator); + +uint32_t system_gclk_chan_get_hz( + const uint8_t channel); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/i2s.c b/feather_sensor_lte/libraries/Adafruit_ASFcore/i2s.c new file mode 100644 index 0000000..31fe2d9 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/i2s.c @@ -0,0 +1,750 @@ +/** + * \file + * + * \brief SAM I2S - Inter-IC Sound Controller + * + * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#include "i2s.h" + +/** + * \brief Initializes a hardware I2S module instance + * + * Enables the clock and initialize the I2S module. + * + * \param[in,out] module_inst Pointer to the software module instance struct + * \param[in] hw Pointer to the TCC hardware module + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The module was initialized successfully + * \retval STATUS_BUSY Hardware module was busy when the + * initialization procedure was attempted + * \retval STATUS_ERR_DENIED Hardware module was already enabled + */ +enum status_code i2s_init( + struct i2s_module *const module_inst, + I2s *hw) +{ + Assert(module_inst); + Assert(hw); + + /* Enable the user interface clock in the PM */ + system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, PM_APBCMASK_I2S); + + /* Status check */ + uint32_t ctrla; + ctrla = module_inst->hw->CTRLA.reg; + if (ctrla & I2S_CTRLA_ENABLE) { + if (ctrla & (I2S_CTRLA_SEREN1 | + I2S_CTRLA_SEREN0 | I2S_CTRLA_CKEN1 | I2S_CTRLA_CKEN0)) { + return STATUS_BUSY; + } else { + return STATUS_ERR_DENIED; + } + } + + /* Initialize module */ + module_inst->hw = hw; + + /* Initialize serializers */ +#if I2S_CALLBACK_MODE == true + int i, j; + for (i = 0; i < 2; i ++) { + for (j = 0; j < I2S_SERIALIZER_CALLBACK_N; j ++) { + module_inst->serializer[i].callback[j] = NULL; + } + module_inst->serializer[i].registered_callback_mask = 0; + module_inst->serializer[i].enabled_callback_mask = 0; + + module_inst->serializer[i].job_buffer = NULL; + module_inst->serializer[i].job_status = STATUS_OK; + module_inst->serializer[i].requested_words = 0; + module_inst->serializer[i].transferred_words = 0; + + module_inst->serializer[i].mode = I2S_SERIALIZER_RECEIVE; + module_inst->serializer[i].data_size = I2S_DATA_SIZE_32BIT; + } + + _i2s_instances[0] = module_inst; + + system_interrupt_enable(SYSTEM_INTERRUPT_MODULE_I2S); +#endif + + return STATUS_OK; +} + + +/** + * \brief Configure specified I2S clock unit + * + * Enables the clock and initialize the clock unit, based on the given + * configurations. + * + * \param[in,out] module_inst Pointer to the software module instance struct + * \param[in] clock_unit I2S clock unit to initialize and configure + * \param[in] config Pointer to the I2S clock unit configuration + * options struct + * + * \return Status of the configuration procedure. + * + * \retval STATUS_OK The module was initialized successfully + * \retval STATUS_BUSY Hardware module was busy when the + * configuration procedure was attempted + * \retval STATUS_ERR_DENIED Hardware module was already enabled + * \retval STATUS_ERR_INVALID_ARG Invalid divider value or + * MCK direction setting conflict + */ +enum status_code i2s_clock_unit_set_config( + struct i2s_module *const module_inst, + const enum i2s_clock_unit clock_unit, + const struct i2s_clock_unit_config *config) +{ + Assert(module_inst); + Assert(module_inst->hw); + Assert(clock_unit < I2S_CLOCK_UNIT_N); + Assert(config); + + /* Status check */ + uint32_t ctrla, syncbusy; + syncbusy = module_inst->hw->SYNCBUSY.reg; + ctrla = module_inst->hw->CTRLA.reg; + + /* Busy ? */ + if (syncbusy & (I2S_SYNCBUSY_CKEN0 << clock_unit)) { + return STATUS_BUSY; + } + /* Already enabled ? */ + if (ctrla & (I2S_CTRLA_CKEN0 << clock_unit)) { + return STATUS_ERR_DENIED; + } + /* Parameter check */ + if (config->clock.mck_src && config->clock.mck_out_enable) { + return STATUS_ERR_INVALID_ARG; + } + + /* Initialize Clock Unit */ + uint32_t clkctrl = + (config->clock.mck_out_invert ? I2S_CLKCTRL_MCKOUTINV : 0) | + (config->clock.sck_out_invert ? I2S_CLKCTRL_SCKOUTINV : 0) | + (config->frame.frame_sync.invert_out ? I2S_CLKCTRL_FSOUTINV : 0) | + (config->clock.mck_out_enable ? I2S_CLKCTRL_MCKEN : 0) | + (config->clock.mck_src ? I2S_CLKCTRL_MCKSEL : 0) | + (config->clock.sck_src ? I2S_CLKCTRL_SCKSEL : 0) | + (config->frame.frame_sync.invert_use ? I2S_CLKCTRL_FSINV : 0) | + (config->frame.frame_sync.source ? I2S_CLKCTRL_FSSEL : 0) | + (config->frame.data_delay ? I2S_CLKCTRL_BITDELAY : 0); + + uint8_t div_val = config->clock.mck_out_div; + if ((div_val > 0x21) || (div_val == 0)) { + return STATUS_ERR_INVALID_ARG; + } else { + div_val --; + } + clkctrl |= I2S_CLKCTRL_MCKOUTDIV(div_val); + + div_val = config->clock.sck_div; + if ((div_val > 0x21) || (div_val == 0)) { + return STATUS_ERR_INVALID_ARG; + } else { + div_val --; + } + clkctrl |= I2S_CLKCTRL_MCKDIV(div_val); + + uint8_t number_slots = config->frame.number_slots; + if (number_slots > 8) { + return STATUS_ERR_INVALID_ARG; + } else if (number_slots > 0) { + number_slots --; + } + clkctrl |= + I2S_CLKCTRL_NBSLOTS(number_slots) | + I2S_CLKCTRL_FSWIDTH(config->frame.frame_sync.width) | + I2S_CLKCTRL_SLOTSIZE(config->frame.slot_size); + + /* Write clock unit configurations */ + module_inst->hw->CLKCTRL[clock_unit].reg = clkctrl; + + /* Select general clock source */ + const uint8_t i2s_gclk_ids[2] = {I2S_GCLK_ID_0, I2S_GCLK_ID_1}; + struct system_gclk_chan_config gclk_chan_config; + system_gclk_chan_get_config_defaults(&gclk_chan_config); + gclk_chan_config.source_generator = config->clock.gclk_src; + system_gclk_chan_set_config(i2s_gclk_ids[clock_unit], &gclk_chan_config); + system_gclk_chan_enable(i2s_gclk_ids[clock_unit]); + + /* Initialize pins */ + struct system_pinmux_config pin_config; + system_pinmux_get_config_defaults(&pin_config); + if (config->mck_pin.enable) { + pin_config.mux_position = config->mck_pin.mux; + system_pinmux_pin_set_config(config->mck_pin.gpio, &pin_config); + } + if (config->sck_pin.enable) { + pin_config.mux_position = config->sck_pin.mux; + system_pinmux_pin_set_config(config->sck_pin.gpio, &pin_config); + } + if (config->fs_pin.enable) { + pin_config.mux_position = config->fs_pin.mux; + system_pinmux_pin_set_config(config->fs_pin.gpio, &pin_config); + } + + return STATUS_OK; +} + + +/** + * \brief Configure specified I2S serializer + * + * Enables the clock and initialize the serializer, based on the given + * configurations. + * + * \param[in,out] module_inst Pointer to the software module instance struct + * \param[in] serializer I2S serializer to initialize and configure + * \param[in] config Pointer to the I2S serializer configuration + * options struct + * + * \return Status of the configuration procedure. + * + * \retval STATUS_OK The module was initialized successfully + * \retval STATUS_BUSY Hardware module was busy when the + * configuration procedure was attempted + * \retval STATUS_ERR_DENIED Hardware module was already enabled + */ +enum status_code i2s_serializer_set_config( + struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + const struct i2s_serializer_config *config) +{ + Assert(module_inst); + Assert(module_inst->hw); + Assert(serializer < I2S_SERIALIZER_N); + Assert(config); + + /* Status check */ + uint32_t ctrla, syncbusy; + syncbusy = module_inst->hw->SYNCBUSY.reg; + ctrla = module_inst->hw->CTRLA.reg; + + /* Busy ? */ + if (syncbusy & ((I2S_SYNCBUSY_SEREN0 | I2S_SYNCBUSY_DATA0) << serializer)) { + return STATUS_BUSY; + } + /* Already enabled ? */ + if (ctrla & (I2S_CTRLA_CKEN0 << serializer)) { + return STATUS_ERR_DENIED; + } + + /* Initialize Serializer */ + uint32_t serctrl = + (config->loop_back ? I2S_SERCTRL_RXLOOP : 0) | + (config->dma_usage ? I2S_SERCTRL_DMA : 0) | + (config->mono_mode ? I2S_SERCTRL_MONO : 0) | + (config->disable_data_slot[7] ? I2S_SERCTRL_SLOTDIS7 : 0) | + (config->disable_data_slot[6] ? I2S_SERCTRL_SLOTDIS6 : 0) | + (config->disable_data_slot[5] ? I2S_SERCTRL_SLOTDIS5 : 0) | + (config->disable_data_slot[4] ? I2S_SERCTRL_SLOTDIS4 : 0) | + (config->disable_data_slot[3] ? I2S_SERCTRL_SLOTDIS3 : 0) | + (config->disable_data_slot[2] ? I2S_SERCTRL_SLOTDIS2 : 0) | + (config->disable_data_slot[1] ? I2S_SERCTRL_SLOTDIS1 : 0) | + (config->disable_data_slot[0] ? I2S_SERCTRL_SLOTDIS0 : 0) | + (config->transfer_lsb_first ? I2S_SERCTRL_BITREV : 0) | + (config->data_adjust_left_in_word ? I2S_SERCTRL_WORDADJ : 0) | + (config->data_adjust_left_in_slot ? I2S_SERCTRL_SLOTADJ : 0) | + (config->data_padding ? I2S_SERCTRL_TXSAME : 0); + + if (config->clock_unit < I2S_CLOCK_UNIT_N) { + serctrl |= (config->clock_unit ? I2S_SERCTRL_CLKSEL : 0); + } else { + return STATUS_ERR_INVALID_ARG; + } + + serctrl |= + I2S_SERCTRL_SERMODE(config->mode) | + I2S_SERCTRL_TXDEFAULT(config->line_default_state) | + I2S_SERCTRL_DATASIZE(config->data_size) | + I2S_SERCTRL_EXTEND(config->bit_padding); + + /* Write Serializer configuration */ + module_inst->hw->SERCTRL[serializer].reg = serctrl; + + /* Initialize pins */ + struct system_pinmux_config pin_config; + system_pinmux_get_config_defaults(&pin_config); + if (config->data_pin.enable) { + pin_config.mux_position = config->data_pin.mux; + system_pinmux_pin_set_config(config->data_pin.gpio, &pin_config); + } + + /* Save configure */ + module_inst->serializer[serializer].mode = config->mode; + module_inst->serializer[serializer].data_size = config->data_size; + + return STATUS_OK; +} + + + +/** + * \brief Retrieves the current module status. + * + * Retrieves the status of the module, giving overall state information. + * + * \param[in] module_inst Pointer to the I2S software instance struct + * + * \return Bitmask of \c I2S_STATUS_* flags + * + * \retval I2S_STATUS_SYNC_BUSY Module is busy synchronization + * \retval I2S_STATUS_TRANSMIT_UNDERRUN(x) Serializer x (0~1) is underrun + * \retval I2S_STATUS_TRANSMIT_READY(x) Serializer x (0~1) is ready to + * transmit new data word + * \retval I2S_STATUS_RECEIVE_OVERRUN(x) Serializer x (0~1) is overrun + * \retval I2S_STATUS_RECEIVE_READY(x) Serializer x (0~1) has data ready to + * read + */ +uint32_t i2s_get_status( + const struct i2s_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + uint32_t intflag = module_inst->hw->INTFLAG.reg; + uint32_t status; + if (module_inst->hw->SYNCBUSY.reg) { + status = I2S_STATUS_SYNC_BUSY; + } else { + status = 0; + } + if (intflag & I2S_INTFLAG_TXUR0) { + status |= I2S_STATUS_TRANSMIT_UNDERRUN(0); + } + if (intflag & I2S_INTFLAG_TXUR1) { + status |= I2S_STATUS_TRANSMIT_UNDERRUN(1); + } + if ((intflag & I2S_INTFLAG_TXRDY0) && + !module_inst->hw->SYNCBUSY.bit.DATA0) { + status |= I2S_STATUS_TRANSMIT_READY(0); + } + if ((intflag & I2S_INTFLAG_TXRDY1) && + !module_inst->hw->SYNCBUSY.bit.DATA1) { + status |= I2S_STATUS_TRANSMIT_READY(1); + } + if (intflag & I2S_INTFLAG_RXOR0) { + status |= I2S_STATUS_RECEIVE_OVERRUN(0); + } + if (intflag & I2S_INTFLAG_RXOR1) { + status |= I2S_STATUS_RECEIVE_OVERRUN(1); + } + if (intflag & I2S_INTFLAG_RXRDY0) { + status |= I2S_STATUS_RECEIVE_READY(0); + } + if (intflag & I2S_INTFLAG_RXRDY1) { + status |= I2S_STATUS_RECEIVE_READY(1); + } + return status; +} + +/** + * \brief Clears a module status flags. + * + * Clears the given status flags of the module. + * + * \param[in] module_inst Pointer to the I2S software instance struct + * \param[in] status Bitmask of \c I2S_STATUS_* flags to clear + */ +void i2s_clear_status( + const struct i2s_module *const module_inst, + uint32_t status) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + uint32_t intflag = 0; + + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { + intflag = I2S_INTFLAG_TXUR0; + } + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { + intflag = I2S_INTFLAG_TXUR1; + } + if (status & I2S_STATUS_TRANSMIT_READY(0)) { + intflag = I2S_INTFLAG_TXRDY0; + } + if (status & I2S_STATUS_TRANSMIT_READY(1)) { + intflag = I2S_INTFLAG_TXRDY1; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { + intflag = I2S_INTFLAG_RXOR0; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { + intflag = I2S_INTFLAG_RXOR1; + } + if (status & I2S_STATUS_RECEIVE_READY(0)) { + intflag = I2S_INTFLAG_RXRDY0; + } + if (status & I2S_STATUS_RECEIVE_READY(1)) { + intflag = I2S_INTFLAG_RXRDY1; + } + module_inst->hw->INTFLAG.reg = intflag; +} + +/** + * \brief Enable interrupts on status set + * + * Enable the given status interrupt request from the I2S module. + * + * \param[in] module_inst Pointer to the I2S software instance struct + * \param[in] status Status interrupts to enable + * + * \return Status of enable procedure + * + * \retval STATUS_OK Interrupt is enabled successfully + * \retval STATUS_ERR_INVALID_ARG Status with no interrupt is passed + */ +enum status_code i2s_enable_status_interrupt( + struct i2s_module *const module_inst, + uint32_t status) +{ + /* Sanity check arguments */ + Assert(module_inst); + + /* No sync busy interrupt */ + if (status & I2S_STATUS_SYNC_BUSY) { + return STATUS_ERR_INVALID_ARG; + } + Assert(module_inst->hw); + + uint32_t intflag = 0; + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { + intflag = I2S_INTFLAG_TXUR0; + } + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { + intflag = I2S_INTFLAG_TXUR1; + } + if (status & I2S_STATUS_TRANSMIT_READY(0)) { + intflag = I2S_INTFLAG_TXRDY0; + } + if (status & I2S_STATUS_TRANSMIT_READY(1)) { + intflag = I2S_INTFLAG_TXRDY1; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { + intflag = I2S_INTFLAG_RXOR0; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { + intflag = I2S_INTFLAG_RXOR1; + } + if (status & I2S_STATUS_RECEIVE_READY(0)) { + intflag = I2S_INTFLAG_RXRDY0; + } + if (status & I2S_STATUS_RECEIVE_READY(1)) { + intflag = I2S_INTFLAG_RXRDY1; + } + module_inst->hw->INTENSET.reg = intflag; + return STATUS_OK; +} + +/** + * \brief Disable interrupts on status set + * + * Disable the given status interrupt request from the I2S module. + * + * \param[in] module_inst Pointer to the I2S software instance struct + * \param[in] status Status interrupts to disable + */ +void i2s_disable_status_interrupt( + struct i2s_module *const module_inst, + uint32_t status) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + uint32_t intflag = 0; + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { + intflag = I2S_INTFLAG_TXUR0; + } + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { + intflag = I2S_INTFLAG_TXUR1; + } + if (status & I2S_STATUS_TRANSMIT_READY(0)) { + intflag = I2S_INTFLAG_TXRDY0; + } + if (status & I2S_STATUS_TRANSMIT_READY(1)) { + intflag = I2S_INTFLAG_TXRDY1; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { + intflag = I2S_INTFLAG_RXOR0; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { + intflag = I2S_INTFLAG_RXOR1; + } + if (status & I2S_STATUS_RECEIVE_READY(0)) { + intflag = I2S_INTFLAG_RXRDY0; + } + if (status & I2S_STATUS_RECEIVE_READY(1)) { + intflag = I2S_INTFLAG_RXRDY1; + } + module_inst->hw->INTENCLR.reg = intflag; +} + + +/** + * \brief Write buffer to the specified Serializer of I2S module + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The serializer to write to + * \param[in] buffer The data buffer to write + * \param[in] size Number of data words to write + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The data was sent successfully + * \retval STATUS_ERR_DENIED The module or serializer is disabled + * \retval STATUS_ERR_INVALID_ARG An invalid buffer pointer was supplied + */ +enum status_code i2s_serializer_write_buffer_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + void *buffer, uint32_t size) +{ + Assert(module_inst); + Assert(module_inst->hw); + Assert(serializer < I2S_SERIALIZER_N); + Assert(buffer); + + if (size == 0) { + return STATUS_OK; + } + + uint8_t data_size = 1; /* number of bytes */ + struct i2s_serializer_module *data_module = (struct i2s_serializer_module *) + &module_inst->serializer[serializer]; + + /* Check buffer */ + switch(data_module->data_size) { + case I2S_DATA_SIZE_32BIT: + case I2S_DATA_SIZE_24BIT: + case I2S_DATA_SIZE_20BIT: + case I2S_DATA_SIZE_18BIT: + if ((uint32_t)buffer & 0x3) { + return STATUS_ERR_INVALID_ARG; + } + data_size = 4; + break; + case I2S_DATA_SIZE_16BIT: + case I2S_DATA_SIZE_16BIT_COMPACT: + if ((uint32_t)buffer & 0x1) { + return STATUS_ERR_INVALID_ARG; + } + data_size = 2; + break; + default: + break; + } + + /* Check status */ + if (!(module_inst->hw->CTRLA.reg & + (I2S_CTRLA_ENABLE | (I2S_CTRLA_SEREN0 << serializer)))) { + return STATUS_ERR_DENIED; + } + + /* Write */ + uint32_t i; + uint32_t sync_bit = I2S_SYNCBUSY_DATA0 << serializer; + uint32_t ready_bit = I2S_INTFLAG_TXRDY0 << serializer; + if (4 == data_size) { + uint32_t *p32 = (uint32_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Tx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + module_inst->hw->DATA[serializer].reg = p32[i]; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } else if (2 == data_size) { + uint16_t *p16 = (uint16_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Tx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + module_inst->hw->DATA[serializer].reg = p16[i]; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } else { + uint8_t *p8 = (uint8_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Tx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + module_inst->hw->DATA[serializer].reg = p8[i]; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } + + return STATUS_OK; +} + +/** + * \brief Read from the specified Serializer of I2S module to a buffer + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The serializer to write to + * \param[in] buffer The buffer to fill read data (NULL to discard) + * \param[in] size Number of data words to read + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The data was sent successfully + * \retval STATUS_ERR_DENIED The module or serializer is disabled + * \retval STATUS_ERR_INVALID_ARG An invalid buffer pointer was supplied + */ +enum status_code i2s_serializer_read_buffer_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + void *buffer, uint32_t size) +{ + Assert(module_inst); + Assert(module_inst->hw); + + if (size == 0) { + return STATUS_OK; + } + + uint8_t data_size = 1; /* number of bytes */ + struct i2s_serializer_module *data_module = (struct i2s_serializer_module *) + &module_inst->serializer[serializer]; + + /* Check buffer */ + switch(data_module->data_size) { + case I2S_DATA_SIZE_32BIT: + case I2S_DATA_SIZE_24BIT: + case I2S_DATA_SIZE_20BIT: + case I2S_DATA_SIZE_18BIT: + if ((uint32_t)buffer & 0x3) { + return STATUS_ERR_INVALID_ARG; + } + data_size = 4; + break; + case I2S_DATA_SIZE_16BIT: + case I2S_DATA_SIZE_16BIT_COMPACT: + if ((uint32_t)buffer & 0x1) { + return STATUS_ERR_INVALID_ARG; + } + data_size = 2; + break; + default: + break; + } + + /* Check status */ + if (!(module_inst->hw->CTRLA.reg & + (I2S_CTRLA_ENABLE | (I2S_CTRLA_SEREN0 << serializer)))) { + return STATUS_ERR_DENIED; + } + + /* Read */ + uint32_t i; + uint32_t sync_bit = I2S_SYNCBUSY_DATA0 << serializer; + uint32_t ready_bit = I2S_INTFLAG_RXRDY0 << serializer; + if (buffer == NULL) { + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Rx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } + else if (4 == data_size) { + uint32_t *p32 = (uint32_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Rx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + p32[i] = module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } else if (2 == data_size) { + uint16_t *p16 = (uint16_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Rx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + p16[i] = module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } else { + uint8_t *p8 = (uint8_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Tx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + p8[i] = module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } + + return STATUS_OK; +} diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/i2s.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/i2s.h new file mode 100644 index 0000000..9911e6d --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/i2s.h @@ -0,0 +1,1404 @@ +/** + * \file + * + * \brief SAM I2S - Inter-IC Sound Controller + * + * Copyright (c) 2014-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#ifndef I2S_H_INCLUDED +#define I2S_H_INCLUDED + +/** + * \defgroup asfdoc_sam0_i2s_group SAM Inter-IC Sound Controller Driver (I2S) + * + * This driver for Atmel® | SMART SAM devices provides an interface for the configuration + * and management of the device's Inter-IC Sound Controller functionality. + * + * The following driver API modes are covered by this manual: + * - Polled APIs + * \if I2S_CALLBACK_MODE + * - Callback APIs + * \endif + * + * The following peripherals are used by this module: + * - I2S (Inter-IC Sound Controller) + * + * The following devices can use this module: + * - Atmel | SMART SAM D21 + * - Atmel | SMART SAM DA1 + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_i2s_prerequisites + * - \ref asfdoc_sam0_i2s_module_overview + * - \ref asfdoc_sam0_i2s_special_considerations + * - \ref asfdoc_sam0_i2s_extra_info + * - \ref asfdoc_sam0_i2s_examples + * - \ref asfdoc_sam0_i2s_api_overview + * + * \section asfdoc_sam0_i2s_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * \section asfdoc_sam0_i2s_module_overview Module Overview + * + * The I2S provides bidirectional, synchronous, digital audio link with external + * audio devices through these signal pins: + * - Serial Data (SDm) + * - Frame Sync (FSn) + * - Serial Clock (SCKn) + * - Master Clock (MCKn) + * + * The I2S consists of 2 Clock Units and 2 Serializers, which can be separately + * configured and enabled, to provide varies functionalities as follow: + * - Communicate to Audio CODECs as Master or Slave, or provides clock and + * frame sync signals as Controller + * - Communicate to DAC or ADC through dedicated I2S serial interface + * - Communicate to multi-slot or multiple stereo DACs or ADCs, via + * Time Division Multiplexed (TDM) format + * - Reading mono or stereo MEMS microphones, using the Pulse Density + * Modulation (PDM) interface + * + * The I2S supports compact stereo data word, where left channel data bits are + * in lower half and right channel data bits are in upper half. It reduces the + * number of data words for stereo audio data and the DMA bandwidth. + * + * In master mode, the frame is configured by number of slots and slot size, and + * allows range covering 16fs to 1024fs MCK, to provide oversampling clock to an + * external audio CODEC or digital signal processor (DSP). + * + * A block diagram of the I2S can be seen in + * \ref asfdoc_sam0_i2s_module_block_diagram "the figure below". + * + * \anchor asfdoc_sam0_i2s_module_block_diagram + * \image html i2s_blocks.svg "I2S Block Diagram" + * + * This driver for I2S module provides an interface to + * - initialize and control I2S module + * - configure and control the I2S Clock Unit and Serializer + * - transmit/receive data through I2S Serializer + * + * \subsection asfdoc_sam0_i2s_module_overview_clocks Clocks + * + * To use I2S module, the I2S bus interface clock (clk_i2s) must be enabled via + * Power Manager. + * + * For each I2S Clock Unit, a generic clock (gclk_i2s_n) is connnected. When I2S + * works in master mode the generic clock is used. It should be prepared before + * clock unit is used. In master mode the input generic clock will be used as + * MCK for SCKn and FSn generation, in addition, the MCK could be devided and + * output to I2S MCKn pin, as oversampling clock to external audio device. + * + * The I2S Serializer uses clock and control signal from Clock Unit to handle + * transfer. Select different clock unit with different configurations allows + * the I2S to work as master or slave, to work on non-related clocks. + * + * When using the driver with ASF, enabling the register interface is normally + * done by the \c init function. + * The gclk source for the asynchronous domain is normally configured and set + * through the _configuration struct_ / _init_ function. + * If gclk source != 0 is used, this source has to be configured and enabled + * through invoking the system_gclk driver function when needed, or modifying + * conf_clock.h to enable it at the beginning. + * + * \subsection asfdoc_sam0_i2s_module_overview_frame Audio Frame Generation + * + * Audio sample data for all channels are sent in frames, one frame can consist + * 1 - 8 slots where each slot can be configured to a size 8-bit, 16-bit, 24-bit + * or 32-bit. The audio frame synch clock is generated by the I2S Clock unit in + * the master/controller mode. The frame rate (or frame sync frequency) is + * calculated as follow: + * + * FS = SCK / number_of_slots / number_of_bits_in_slot + * + * The serial clock (SCK) source is either an external source (slave mode) or + * generated by the I2S clock unit (controller or master mode) using the MCK as + * source. + * + * SCK = MCK / sck_div + * \note SCK generation division value is MCKDIV in register. + * + * MCK is either an external source or generated using the gclk input from a + * generic clock generator. + * + * \subsection asfdoc_sam0_i2s_module_overview_mode Master, Controller and Slave modes + * + * The i2s module has three modes: master, controller and slave. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_mode_mst Master + * In master mode the module will control the data flow on the i2s bus and can + * be responsible for clock generation. The Serializers are enabled and will + * transmit/receive data. On a bus with only master and slave the SCK and FS + * clock signal will be outputted on the SCK and FS pin on the master module. + * MCK can optionally be outputted on the MCK pin, if there is a controller + * module on the bus the SCK, FS and optionally the MCK clock is sourced from + * the same pins. Serial data will be trancieved on the SD pin in both + * scenarios. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_mode_ctl Controller + * In controller mode the module will generate the clock signals, but the + * Serializers are disabled and no data will be transmitted/received by the + * module in this mode. The clock signals is outputted on the SCK, FS and + * optionally the MCK pin. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_mode_slv Slave + * In slave mode the module will use the SCK and FS clock source from the master + * or the controller which is received on the SCK and FS pin. The MCK can + * optionally be sourced externally on the MCK pin. The Serializers are enabled + * and will tranceive data on the SD pin. All data flow is controlled by the + * master. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_mode_chg Switch modes + * The mode switching between master, controller and slave modes are actually + * done by modifying the source mode of I2S pins. + * The source mode of I2S pins are selected by writing corresponding bits in + * CLKCTRLn. + * Since source mode switching changes the direction of pin, the mode must be + * changed when the I2S Clock Unit is stopped. + * + * \subsection asfdoc_sam0_i2s_module_overview_data Data Stream Reception/Transmission + * + * The I2S module support several data stream formats: + * - I2S format + * - Time Division Multiplexed (TDM) format + * - Pulse Density Modulation (PDM) format (reception only) + * + * Basically the I2S module can send several words within each frame, it's more + * like TDM format. With adjust to the number of data words in a frame, the FS + * width, the FS to data bits delay, etc., the module is able to handle I2S + * compliant data stream. + * + * Also the Serializer can receive PDM format data stream, which allows the I2S + * module receive 1 PDM data on each SCK edge. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_data_i2s I2S Stream Reception/Transmission + * + * For 2-channel I2S compliant data stream format the i2s module uses the FS + * line as word select (WS) signal and will send left channel data word on low + * WS level and right channel data word on high WS level as specified in the I2S + * standard. The supported word sizes are 8-, 16-, 18-, 20-, 24- and 32- bit. + * + * Thus for I2S stream, the following settings should be applied to the module: + * - Data starting delay after FS transition : one SCK period + * - FS width : half of frame + * - Data bits adjust in word : left-adjusted + * - Bit transmitting order : MSB first + * + * Following is an example for I2S application connections and waveforms. See + * \ref asfdoc_sam0_i2s_module_i2s_example_diagram "the figure below". + * + * \anchor asfdoc_sam0_i2s_module_i2s_example_diagram + * \image html i2s_example.svg "I2S Example Diagram" + * + * \subsubsection asfdoc_sam0_i2s_module_overview_data_tdm TDM Stream Reception/Transmission + * In TDM format, the module sends several data words in each frame. For this + * data stream format most of the configurations could be adjusted: + * - Main Frame related settings are as follow: + * - Frame Sync (FS) options: + * - the active edge of the FS (or if FS is inverted before use) + * - the width of the FS + * - the delay between FS to first data bit + * - Data alignment in slot + * - The number of slots and slot size can be adjusted, it has been mentioned + * in \ref asfdoc_sam0_i2s_module_overview_frame + * - The data word size is controlled by Serializer, it can be chosen among + * 8, 16, 18, 20, 24 and 32 bits. + * + * The general TDM waveform generation is as follow: + * + * \anchor asfdoc_sam0_i2s_module_tdm_wave_diagram + * \image html tdm_wave.svg "TDM Waveform generation" + * + * Some other settings could also be found to set up clock, data formatting and + * pin mux. + * refer to \ref i2s_clock_unit_config "Clock Unit Configurations" + * and \ref i2s_serializer_config "Serializer Configurations" for more + * details. + * + * Following is examples for different application use cases. + * + * See \ref asfdoc_sam0_i2s_module_tdm_timeslot_example_diagram "here" for + * the Time Slot Application connection and waveform example. + * + * \anchor asfdoc_sam0_i2s_module_tdm_timeslot_example_diagram + * \image html tdm_timeslot_example.svg "Codec Example Diagram" + * + * See \ref asfdoc_sam0_i2s_module_tdm_codec_example_diagram "here" for the + * Codec Application connection and waveform example. + * + * \anchor asfdoc_sam0_i2s_module_tdm_codec_example_diagram + * \image html tdm_codec_example.svg "Time Slot Example Diagram" + * + * \subsubsection asfdoc_sam0_i2s_module_overview_data_pdm PDM Reception + * The I2S Serializer integrates PDM reception feature, to use this feature, + * simply select PDM2 mode in Serializer configuration. In PDM2 mode, it assumes + * two microphones are input for stereo stream. The left microphone bits will + * be stored in lower half and right microphone bits in upper half of the data + * word, like in compact stereo format. + * + * See \ref asfdoc_sam0_i2s_module_pdm_example_diagram "following figure" for an + * example of PDM Microphones Application with both left and right channel + * microphone connected. + * + * \anchor asfdoc_sam0_i2s_module_pdm_example_diagram + * \image html pdm_example.svg "Time PDM2 Example Diagram" + * + * \subsubsection asfdoc_sam0_i2s_module_overview_data_fmt MONO and Compact Data + * The I2S Serializer can accept some pre-defined data format and generates + * the data stream in specified way. + * + * When transmitting data, the Serializer can work in MONO mode: assum input + * is single channel mono data on left channel and copy it to right channel + * automatically. + * + * Also the I2S Serializer can support compact stereo data word. The data word + * size of the Serializer can be set to \ref I2S_DATA_SIZE_16BIT_COMPACT + * "16-bit compact" or \ref I2S_DATA_SIZE_8BIT_COMPACT "8-bit compact", with + * these option I2S Serializer will compact left channel data and right channel + * data together, the left channel data will take lower bytes and right channel + * data take higher bytes. + * + * \subsection asfdoc_sam0_i2s_module_overview_loop Loop-back Mode + * The I2S can be configured to loop back the Transmitter to Receiver. In this + * mode Serializer's input will be connected to another Serializer's output + * internally. + * + * \subsection asfdoc_sam0_i2s_module_overview_sleep Sleep Modes + * The I2S will continue to operate in any sleep mode, where the selected source + * clocks are running. + * + * \section asfdoc_sam0_i2s_special_considerations Special Considerations + * + * There is no special considerations for I2S module. + * + * \section asfdoc_sam0_i2s_extra_info Extra Information + * + * For extra information see \ref asfdoc_sam0_i2s_extra. This includes: + * - \ref asfdoc_sam0_i2s_extra_acronyms + * - \ref asfdoc_sam0_i2s_extra_dependencies + * - \ref asfdoc_sam0_i2s_extra_errata + * - \ref asfdoc_sam0_i2s_extra_history + * + * \section asfdoc_sam0_i2s_examples Examples + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_i2s_exqsg. + * + * + * \section asfdoc_sam0_i2s_api_overview API Overview + * @{ + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#if I2S_CALLBACK_MODE == true +# include + +#if !defined(__DOXYGEN__) +extern struct i2s_module *_i2s_instances[I2S_INST_NUM]; +#endif + +/** Forward definition of the device instance */ +struct i2s_module; + +/** Type of the callback functions */ +typedef void (*i2s_serializer_callback_t) + (struct i2s_module *const module); + +/** + * \brief I2S Serializer Callback enum + */ +enum i2s_serializer_callback { + /** Callback for buffer read/write finished */ + I2S_SERIALIZER_CALLBACK_BUFFER_DONE, + /** Callback for Serializer overrun/underrun */ + I2S_SERIALIZER_CALLBACK_OVER_UNDER_RUN, +# if !defined(__DOXYGEN__) + I2S_SERIALIZER_CALLBACK_N +# endif +}; + +#endif /* #if I2S_CALLBACK_MODE == true */ + +/** + * \name Module status flags + * + * I2S status flags, returned by \ref i2s_get_status() and cleared by + * \ref i2s_clear_status(). + * + * @{ + */ + +/** Module Serializer x (0~1) Transmit Underrun */ +#define I2S_STATUS_TRANSMIT_UNDERRUN(x) (1u << ((x)+0)) +/** Module Serializer x (0~1) is ready to accept new data to be transmitted */ +#define I2S_STATUS_TRANSMIT_READY(x) (1u << ((x)+2)) +/** Module Serializer x (0~1) Receive Overrun */ +#define I2S_STATUS_RECEIVE_OVERRUN(x) (1u << ((x)+4)) +/** Module Serializer x (0~1) has received a new data */ +#define I2S_STATUS_RECEIVE_READY(x) (1u << ((x)+6)) +/** Module is busy on synchronization */ +#define I2S_STATUS_SYNC_BUSY (1u << 8) + +/** @} */ + +/** + * Master Clock (MCK) source selection + */ +enum i2s_master_clock_source { + /** Master Clock (MCK) is from general clock */ + I2S_MASTER_CLOCK_SOURCE_GCLK, + /** Master Clock (MCK) is from MCK input pin */ + I2S_MASTER_CLOCK_SOURCE_MCKPIN +}; + +/** + * Serial Clock (SCK) source selection + */ +enum i2s_serial_clock_source { + /** Serial Clock (SCK) is divided from Master Clock */ + I2S_SERIAL_CLOCK_SOURCE_MCKDIV, + /** Serial Clock (SCK) is input from SCK input pin */ + I2S_SERIAL_CLOCK_SOURCE_SCKPIN +}; + +/** + * Data delay from Frame Sync (FS) + */ +enum i2s_data_delay { + /** Left Justified (no delay) */ + I2S_DATA_DELAY_0, + /** I2S data delay (1-bit delay) */ + I2S_DATA_DELAY_1, + /** Left Justified (no delay) */ + I2S_DATA_DELAY_LEFT_JUSTIFIED = I2S_DATA_DELAY_0, + /** I2S data delay (1-bit delay) */ + I2S_DATA_DELAY_I2S = I2S_DATA_DELAY_1 +}; + +/** + * Frame Sync (FS) source + */ +enum i2s_frame_sync_source { + /** Frame Sync (FS) is divided from I2S Serial Clock */ + I2S_FRAME_SYNC_SOURCE_SCKDIV, + /** Frame Sync (FS) is input from FS input pin */ + I2S_FRAME_SYNC_SOURCE_FSPIN +}; + +/** + * Frame Sync (FS) output pulse width + */ +enum i2s_frame_sync_width { + /** Frame Sync (FS) Pulse is 1 Slot width */ + I2S_FRAME_SYNC_WIDTH_SLOT, + /** Frame Sync (FS) Pulse is half a Frame width */ + I2S_FRAME_SYNC_WIDTH_HALF_FRAME, + /** Frame Sync (FS) Pulse is 1 Bit width */ + I2S_FRAME_SYNC_WIDTH_BIT, + /** 1-bit wide Frame Sync (FS) per Data sample, only used when Data transfer + * is requested */ + I2S_FRAME_SYNC_WIDTH_BURST +}; + +/** + * Time Slot Size in number of I2S serial clocks (bits) + */ +enum i2s_slot_size { + /** 8-bit slot */ + I2S_SLOT_SIZE_8_BIT, + /** 16-bit slot */ + I2S_SLOT_SIZE_16_BIT, + /** 24-bit slot */ + I2S_SLOT_SIZE_24_BIT, + /** 32-bit slot */ + I2S_SLOT_SIZE_32_BIT +}; + +/** + * DMA channels usage for I2S + */ +enum i2s_dma_usage { + /** Single DMA channel for all I2S channels */ + I2S_DMA_USE_SINGLE_CHANNEL_FOR_ALL, + /** One DMA channel per data channel */ + I2S_DMA_USE_ONE_CHANNEL_PER_DATA_CHANNEL +}; + +/** + * I2S data format, to extend mono data to 2 channels + */ +enum i2s_data_format { + /** Normal mode, keep data to its right channel */ + I2S_DATA_FORMAT_STEREO, + /** Assume input is mono data for left channel, the data is duplicated to + * right channel */ + I2S_DATA_FORMAT_MONO +}; + +/** + * I2S data bit order + */ +enum i2s_bit_order { + /** Transfer Data Most Significant Bit first (Default for I2S protocol) */ + I2S_BIT_ORDER_MSB_FIRST, + /** Transfer Data Least Significant Bit first */ + I2S_BIT_ORDER_LSB_FIRST +}; + +/** + * I2S data bit padding + */ +enum i2s_bit_padding { + /** Padding with 0 */ + I2S_BIT_PADDING_0, + /** Padding with 1 */ + I2S_BIT_PADDING_1, + /** Padding with MSBit */ + I2S_BIT_PADDING_MSB, + /** Padding with LSBit */ + I2S_BIT_PADDING_LSB, +}; + +/** + * I2S data word adjust + */ +enum i2s_data_adjust { + /** Data is right adjusted in word */ + I2S_DATA_ADJUST_RIGHT, + /** Data is left adjusted in word */ + I2S_DATA_ADJUST_LEFT +}; + +/** + * I2S data word size + */ +enum i2s_data_size { + /** 32-bit */ + I2S_DATA_SIZE_32BIT, + /** 24-bit */ + I2S_DATA_SIZE_24BIT, + /** 20-bit */ + I2S_DATA_SIZE_20BIT, + /** 18-bit */ + I2S_DATA_SIZE_18BIT, + /** 16-bit */ + I2S_DATA_SIZE_16BIT, + /** 16-bit compact stereo */ + I2S_DATA_SIZE_16BIT_COMPACT, + /** 8-bit */ + I2S_DATA_SIZE_8BIT, + /** 8-bit compact stereo */ + I2S_DATA_SIZE_8BIT_COMPACT +}; + +/** + * I2S data slot adjust + */ +enum i2s_slot_adjust { + /** Data is right adjusted in slot */ + I2S_SLOT_ADJUST_RIGHT, + /** Data is left adjusted in slot */ + I2S_SLOT_ADJUST_LEFT +}; + +/** + * I2S data padding + */ +enum i2s_data_padding { + /** Padding 0 in case of under-run */ + I2S_DATA_PADDING_0, + /** Padding last data in case of under-run */ + I2S_DATA_PADDING_SAME_AS_LAST, + /** Padding last data in case of under-run + * (abbr. \c I2S_DATA_PADDING_SAME_AS_LAST) */ + I2S_DATA_PADDING_LAST = I2S_DATA_PADDING_SAME_AS_LAST, + /** Padding last data in case of under-run + * (abbr. \c I2S_DATA_PADDING_SAME_AS_LAST) */ + I2S_DATA_PADDING_SAME = I2S_DATA_PADDING_SAME_AS_LAST +}; + +/** + * I2S line default value when slot disabled + */ +enum i2s_line_default_state { + /** Output default value is 0 */ + I2S_LINE_DEFAULT_0, + /** Output default value is 1 */ + I2S_LINE_DEFAULT_1, + /** Output default value is high impedance */ + I2S_LINE_DEFAULT_HIGH_IMPEDANCE = 3, + /** Output default value is high impedance + * (abbr. \c I2S_LINE_DEFAULT_HIGH_IMPEDANCE) */ + I2S_LINE_DEFAULT_HIZ = I2S_LINE_DEFAULT_HIGH_IMPEDANCE +}; + +/** + * I2S Serializer mode + */ +enum i2s_serializer_mode { + /** Serializer is used to receive data */ + I2S_SERIALIZER_RECEIVE, + /** Serializer is used to transmit data */ + I2S_SERIALIZER_TRANSMIT, + /** Serializer is used to receive PDM data on each clock edge */ + I2S_SERIALIZER_PDM2 +}; + +/** + * I2S clock unit selection + */ +enum i2s_clock_unit { + /** Clock Unit channel 0 */ + I2S_CLOCK_UNIT_0, + /** Clock Unit channel 1 */ + I2S_CLOCK_UNIT_1, + /** Number of Clock Unit channels */ + I2S_CLOCK_UNIT_N +}; + +/** + * I2S Serializer selection + */ +enum i2s_serializer { + /** Serializer channel 0 */ + I2S_SERIALIZER_0, + /** Serializer channel 1 */ + I2S_SERIALIZER_1, + /** Number of Serializer channels */ + I2S_SERIALIZER_N +}; + + +/** + * Configure for I2S pin + */ +struct i2s_pin_config { + /** GPIO index to access the pin */ + uint8_t gpio; + /** Pin function MUX */ + uint8_t mux; + /** Enable this pin for I2S module */ + bool enable; +}; + +/** + * Configure for I2S clock (SCK) + */ +struct i2s_clock_config { + /** Divide generic clock to master clock output (1~32, 0,1 means no div) */ + uint8_t mck_out_div; + /** Divide generic clock to serial clock (1~32, 0,1 means no div) */ + uint8_t sck_div; + /** Clock source selection */ + enum gclk_generator gclk_src; + /** Master clock source selection: generated or input from pin */ + enum i2s_master_clock_source mck_src; + /** Serial clock source selection: generated or input from pin */ + enum i2s_serial_clock_source sck_src; + /** Invert master clock output */ + bool mck_out_invert; + /** Invert serial clock output */ + bool sck_out_invert; + /** Generate MCK clock output */ + bool mck_out_enable; +}; + +/** + * Configure fir I2S frame sync (FS) + */ +struct i2s_frame_sync_config { + /** Frame Sync (FS) generated or input from pin */ + enum i2s_frame_sync_source source; + /** Frame Sync (FS) width */ + enum i2s_frame_sync_width width; + /** Invert Frame Sync (FS) signal before use */ + bool invert_use; + /** Invert Frame Sync (FS) signal before output */ + bool invert_out; +}; + +/** + * Configure fir I2S frame + */ +struct i2s_frame_config { + /** Number of slots in a frame (1~8, 0,1 means minimum 1) */ + uint8_t number_slots; + /** Size of each slot in frame */ + enum i2s_slot_size slot_size; + /** Data delay from Frame Sync (FS) to first data bit */ + enum i2s_data_delay data_delay; + /** Frame sync (FS) */ + struct i2s_frame_sync_config frame_sync; +}; + +/** + * Configure for I2S clock unit + */ +struct i2s_clock_unit_config { + /** Configure clock generation */ + struct i2s_clock_config clock; + /** Configure frame generation */ + struct i2s_frame_config frame; + + /** Configure master clock pin */ + struct i2s_pin_config mck_pin; + /** Configure serial clock pin */ + struct i2s_pin_config sck_pin; + /** Configure frame sync pin */ + struct i2s_pin_config fs_pin; +}; + +/** + * Configure for I2S Serializer + */ +struct i2s_serializer_config { + /** Configure Serializer data pin */ + struct i2s_pin_config data_pin; + + /** Set to \c true to loop-back output to input pin for test */ + bool loop_back; + + /** Set to \c true to assumes mono input and duplicate it (left channel) to + * right channel */ + bool mono_mode; + + /** Disable data slot */ + bool disable_data_slot[8]; + + /** Set to \c true to transfer LSB first, \c false to transfer MSB first */ + bool transfer_lsb_first; + /** Data Word Formatting Adjust, + * set to \c true to adjust bits in word to left */ + bool data_adjust_left_in_word; + /** Data Slot Formatting Adjust, + * set to \c true to adjust words in slot to left */ + bool data_adjust_left_in_slot; + + /** Data Word Size */ + enum i2s_data_size data_size; + /** Data Formatting Bit Extension */ + enum i2s_bit_padding bit_padding; + /** Data padding when under-run */ + enum i2s_data_padding data_padding; + + /** DMA usage */ + enum i2s_dma_usage dma_usage; + + /** Clock unit selection */ + enum i2s_clock_unit clock_unit; + + /** Line default state where slot is disabled */ + enum i2s_line_default_state line_default_state; + + /** Serializer Mode */ + enum i2s_serializer_mode mode; +}; + +/** + * \brief I2S Serializer instance struct + */ +struct i2s_serializer_module { + +#if I2S_CALLBACK_MODE == true + /** Callbacks list for Serializer */ + i2s_serializer_callback_t callback[I2S_SERIALIZER_CALLBACK_N]; + + /** Job buffer */ + void *job_buffer; + /** Requested data words to read/write */ + uint32_t requested_words; + /** Transferred data words for read/write */ + uint32_t transferred_words; + + /** Callback mask for registered callbacks */ + uint8_t registered_callback_mask; + /** Callback mask for enabled callbacks */ + uint8_t enabled_callback_mask; + + /** Status of the ongoing or last transfer job */ + enum status_code job_status; +#endif + + /** Serializer mode */ + enum i2s_serializer_mode mode; + /** Serializer data word size */ + enum i2s_data_size data_size; +}; + +/** + * \brief I2S Software Module instance struct + */ +struct i2s_module { + /** Module HW register access base */ + I2s *hw; + + /** Module Serializer used */ + struct i2s_serializer_module serializer[2]; +}; + +/** + * \brief Determines if the hardware module(s) are currently synchronizing to the bus. + * + * Checks to see if the underlying hardware peripheral module(s) are currently + * synchronizing across multiple clock domains to the hardware bus, This + * function can be used to delay further operations on a module until such time + * that it is ready, to prevent blocking delays for synchronization in the + * user application. + * + * \param[in] module_inst Pointer to the software module instance struct + * + * \return Synchronization status of the underlying hardware module(s). + * + * \retval false If the module has completed synchronization + * \retval true If the module synchronization is ongoing + */ +static inline bool i2s_is_syncing( + const struct i2s_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + return (module_inst->hw->SYNCBUSY.reg > 0); +} + +/** + * \name Driver Initialization + * @{ + */ + +enum status_code i2s_init( + struct i2s_module *const module_inst, + I2s *hw); + +/** @} */ + +/** + * \name Enable/Disable/Reset + * @{ + */ + +/** + * \brief Enable the I2S module. + * + * Enables a I2S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void i2s_enable(const struct i2s_module *const module_inst) +{ + Assert(module_inst); + Assert(module_inst->hw); + + while (module_inst->hw->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg |= I2S_SYNCBUSY_ENABLE; +} + +/** + * \brief Disables the I2S module. + * + * Disables a I2S module. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void i2s_disable(const struct i2s_module *const module_inst) +{ + Assert(module_inst); + Assert(module_inst->hw); + + while (module_inst->hw->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg &= ~I2S_SYNCBUSY_ENABLE; +} + +/** + * \brief Resets the I2S module. + * + * Resets the I2S module, restoring all hardware module registers to their + * default values and disabling the module. The I2S module will not be + * accessible while the reset is being performed. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void i2s_reset(const struct i2s_module *const module_inst) +{ + Assert(module_inst); + Assert(module_inst->hw); + + /* Disable the module if it is running */ + if (module_inst->hw->CTRLA.reg & I2S_CTRLA_ENABLE) { + i2s_disable(module_inst); + while (i2s_is_syncing(module_inst)) { + /* Sync wait */ + } + } + /* Reset the HW module */ + module_inst->hw->CTRLA.reg = I2S_CTRLA_SWRST; +} + +/** @} */ + +/** + * \name Clock Unit Initialization and Configuration + * @{ + */ + +/** + * \brief Initializes config with predefined default values for I2S clock unit. + * + * This function will initialize a given I2S Clock Unit configuration structure + * to a set of known default values. This function should be called on any new + * instance of the configuration structures before being modified by the user + * application. + * + * The default configuration is as follow: + * - The clock unit does not generate output clocks (MCK, SCK and FS) + * - The pins (MCK, SCK and FS) and Mux configurations are not set + * + * \param[out] config Pointer to a I2S module clock unit configuration struct + * to set + */ +static inline void i2s_clock_unit_get_config_defaults( + struct i2s_clock_unit_config *const config) +{ + Assert(config); + + config->clock.mck_out_enable = false; + config->clock.gclk_src = GCLK_GENERATOR_0; + + config->clock.mck_src = I2S_MASTER_CLOCK_SOURCE_GCLK; + config->clock.mck_out_div = 1; + config->clock.mck_out_invert = false; + + config->clock.sck_src = I2S_SERIAL_CLOCK_SOURCE_MCKDIV; + config->clock.sck_div = 1; + config->clock.sck_out_invert = false; + + config->frame.number_slots = 1; + config->frame.slot_size = I2S_SLOT_SIZE_32_BIT; + config->frame.data_delay = I2S_DATA_DELAY_I2S; + + config->frame.frame_sync.source = I2S_FRAME_SYNC_SOURCE_SCKDIV; + config->frame.frame_sync.width = I2S_FRAME_SYNC_WIDTH_HALF_FRAME; + config->frame.frame_sync.invert_use = false; + config->frame.frame_sync.invert_out = false; + + config->mck_pin.enable = false; + config->mck_pin.mux = 0; + config->mck_pin.gpio = 0; + + config->sck_pin.enable = false; + config->sck_pin.mux = 0; + config->sck_pin.gpio = 0; + + config->fs_pin.enable = false; + config->fs_pin.mux = 0; + config->fs_pin.gpio = 0; +} + +enum status_code i2s_clock_unit_set_config( + struct i2s_module *const module_inst, + const enum i2s_clock_unit clock_unit, + const struct i2s_clock_unit_config *config); + +/** @} */ + + +/** + * \name Clock Unit Enable/Disable + * @{ + */ + +/** + * \brief Enable the Specified Clock Unit of I2S module. + * + * Enables a Clock Unit in I2S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] clock_unit I2S Clock Unit to enable + */ +static inline void i2s_clock_unit_enable( + const struct i2s_module *const module_inst, + const enum i2s_clock_unit clock_unit) +{ + uint32_t cken_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + cken_bit = I2S_CTRLA_CKEN0 << clock_unit; + + while (module_inst->hw->SYNCBUSY.reg & cken_bit) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg |= cken_bit; +} + +/** + * \brief Disable the Specified Clock Unit of I2S module. + * + * Disables a Clock Unit in I2S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] clock_unit I2S Clock Unit to disable + */ +static inline void i2s_clock_unit_disable( + const struct i2s_module *const module_inst, + const enum i2s_clock_unit clock_unit) +{ + uint32_t cken_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + cken_bit = I2S_CTRLA_CKEN0 << clock_unit; + + while (module_inst->hw->SYNCBUSY.reg & cken_bit) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg &= ~cken_bit; +} + +/** @} */ + + +/** + * \name Serializer Initialization and Configuration + * @{ + */ + +/** + * \brief Initializes config with predefined default values for I2S Serializer. + * + * This function will initialize a given I2S Clock Unit configuration structure + * to a set of known default values. This function should be called on any new + * instance of the configuration structures before being modified by the user + * application. + * + * The default configuration is as follow: + * - Output data does not internally loopback to input line + * - Does not extend mono data (left channel) to right channel + * - None of the data slot is disabled + * - MSB of I2S data is transferred first + * - In data word data is adjusted right + * - In slot data word is adjusted left + * - The data size is 16-bit width + * - I2S will padd 0 to not defined bits + * - I2S will padd 0 to not defined words + * - I2S will use single DMA channel for all data channels + * - I2S will use clock unit 0 to serve as clock + * - The default data line state is 0, when there is no data + * - I2S will transmit data to output line + * - The data pin and Mux configuration are not set + * + * \param[out] config Pointer to a I2S module Serializer configuration struct + * to set + */ +static inline void i2s_serializer_get_config_defaults( + struct i2s_serializer_config *const config) +{ + config->loop_back = false; + + config->mono_mode = false; + + config->disable_data_slot[0] = false; + config->disable_data_slot[1] = false; + config->disable_data_slot[2] = false; + config->disable_data_slot[3] = false; + config->disable_data_slot[4] = false; + config->disable_data_slot[5] = false; + config->disable_data_slot[6] = false; + config->disable_data_slot[7] = false; + + config->transfer_lsb_first = false; + config->data_adjust_left_in_word = false; + config->data_adjust_left_in_slot = true; + + config->data_size = I2S_DATA_SIZE_16BIT; + + config->bit_padding = I2S_BIT_PADDING_0; + config->data_padding = I2S_DATA_PADDING_0; + + config->dma_usage = I2S_DMA_USE_SINGLE_CHANNEL_FOR_ALL; + + config->clock_unit = I2S_CLOCK_UNIT_0; + + config->line_default_state = I2S_LINE_DEFAULT_0; + + config->mode = I2S_SERIALIZER_TRANSMIT; + + config->data_pin.enable = false; + config->data_pin.gpio = 0; + config->data_pin.mux = 0; +} + +enum status_code i2s_serializer_set_config( + struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + const struct i2s_serializer_config *config); +/** @} */ + +/** + * \name Serializer Enable/Disable + * @{ + */ + +/** + * \brief Enable the Specified Serializer of I2S module. + * + * Enables a Serializer in I2S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer I2S Serializer to enable + */ +static inline void i2s_serializer_enable( + const struct i2s_module *const module_inst, + const enum i2s_serializer serializer) +{ + uint32_t seren_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + seren_bit = I2S_CTRLA_SEREN0 << serializer; + + while (module_inst->hw->SYNCBUSY.reg & seren_bit) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg |= seren_bit; +} + +/** + * \brief Disable the Specified Serializer of I2S module. + * + * Disables a Serializer in I2S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer I2S Serializer to disable + */ +static inline void i2s_serializer_disable( + const struct i2s_module *const module_inst, + const enum i2s_serializer serializer) +{ + uint32_t seren_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + seren_bit = I2S_CTRLA_SEREN0 << serializer; + + while (module_inst->hw->SYNCBUSY.reg & seren_bit) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg &= ~seren_bit; +} +/** @} */ + +/** + * \name Status Management + * @{ + */ + +uint32_t i2s_get_status( + const struct i2s_module *const module_inst); + +void i2s_clear_status( + const struct i2s_module *const module_inst, + uint32_t status); + + +enum status_code i2s_enable_status_interrupt( + struct i2s_module *const module_inst, + uint32_t status); + +void i2s_disable_status_interrupt( + struct i2s_module *const module_inst, + uint32_t status); + +/** @}*/ + +/** + * \name Data read/write + * @{ + */ + +/** + * \brief Write a data word to the specified Serializer of I2S module + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The Serializer to write to + * \param[in] data The data to write + * + */ +static inline void i2s_serializer_write_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + uint32_t data) +{ + uint32_t sync_bit, ready_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + ready_bit = I2S_INTFLAG_TXRDY0 << serializer; + while (!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait until ready to transmit */ + } + sync_bit = I2S_SYNCBUSY_DATA0 << serializer; + while (module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait sync */ + } + /* Write data */ + module_inst->hw->DATA[serializer].reg = data; + module_inst->hw->INTFLAG.reg = ready_bit; +} + +/** + * \brief Read a data word from the specified Serializer of I2S module + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The Serializer to read + */ +static inline uint32_t i2s_serializer_read_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer) +{ + uint32_t sync_bit, ready_bit; + uint32_t data; + + Assert(module_inst); + Assert(module_inst->hw); + + ready_bit = I2S_INTFLAG_RXRDY0 << serializer; + while (!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait until ready to transmit */ + } + sync_bit = I2S_SYNCBUSY_DATA0 << serializer; + while (module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait sync */ + } + /* Read data */ + data = module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + return data; +} + + +/** + * \brief Write buffer to the specified Serializer of I2S module + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The Serializer to write to + * \param[in] buffer The data buffer to write + * \param[in] size Number of data words to write + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The data was sent successfully + * \retval STATUS_INVALID_ARG An invalid buffer pointer was supplied + */ +enum status_code i2s_serializer_write_buffer_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + void *buffer, uint32_t size); + +/** + * \brief Read from the specified Serializer of I2S module to a buffer + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The Serializer to write to + * \param[in] buffer The buffer to fill read data + * \param[in] size Number of data words to read + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The data was sent successfully + * \retval STATUS_INVALID_ARG An invalid buffer pointer was supplied + */ +enum status_code i2s_serializer_read_buffer_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + void *buffer, uint32_t size); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +/** @} */ + + +/** + * \page asfdoc_sam0_i2s_extra Extra Information for I2S Driver + * + * \section asfdoc_sam0_i2s_extra_acronyms Acronyms + * Below is a table listing the acronyms used in this module, along with their + * intended meanings. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
AcronymDescription
I2S, IISInter-IC Sound Controller
MCKMaster Clock
SCKSerial Clock
FSFrame Sync
SDSerial Data
ADCAnalog-to-Digital Converter
DACDigital-to-Analog Converter
TDMTime Division Multiplexed
PDMPulse Density Modulation
LSBLeast Significant Bit
MSBMost Significant Bit
DSPDigital Signal Processor
+ * + * + * \section asfdoc_sam0_i2s_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - \ref asfdoc_sam0_system_pinmux_group "System Pin Multiplexer Driver" + * + * + * \section asfdoc_sam0_i2s_extra_errata Errata + * There are no errata related to this driver. + * + * + * \section asfdoc_sam0_i2s_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * + * + * + *
Changelog
Initial Release
+ */ + +/** + * \page asfdoc_sam0_i2s_exqsg Examples for I2S Driver + * + * This is a list of the available Quick Start guides (QSGs) and example + * applications for \ref asfdoc_sam0_i2s_group. QSGs are simple examples with + * step-by-step instructions to configure and use this driver in a selection of + * use cases. Note that QSGs can be compiled as a standalone application or be + * added to the user application. + * + * - \subpage asfdoc_sam0_i2s_basic_use_case + * \if I2S_CALLBACK_MODE + * - \subpage asfdoc_sam0_i2s_callback_use_case + * \endif + * - \subpage asfdoc_sam0_i2s_dma_use_case + * + * \page asfdoc_sam0_i2s_document_revision_history Document Revision History + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Doc. Rev. + * Date + * Comments + *
B04/2015Added support for SAMDA1.
A01/2014Initial release
+ */ + +#endif /* #ifndef I2S_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt.h new file mode 100644 index 0000000..fa4878e --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt.h @@ -0,0 +1,117 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ +#ifndef UTILS_INTERRUPT_H +#define UTILS_INTERRUPT_H + +//#include + +#include "interrupt/interrupt_sam_nvic.h" + +/** + * \defgroup interrupt_group Global interrupt management + * + * This is a driver for global enabling and disabling of interrupts. + * + * @{ + */ + +#if defined(__DOXYGEN__) +/** + * \def CONFIG_INTERRUPT_FORCE_INTC + * \brief Force usage of the ASF INTC driver + * + * Predefine this symbol when preprocessing to force the use of the ASF INTC driver. + * This is useful to ensure compatibility across compilers and shall be used only when required + * by the application needs. + */ +# define CONFIG_INTERRUPT_FORCE_INTC +#endif + +//! \name Global interrupt flags +//@{ +/** + * \typedef irqflags_t + * \brief Type used for holding state of interrupt flag + */ + +/** + * \def cpu_irq_enable + * \brief Enable interrupts globally + */ + +/** + * \def cpu_irq_disable + * \brief Disable interrupts globally + */ + +/** + * \fn irqflags_t cpu_irq_save(void) + * \brief Get and clear the global interrupt flags + * + * Use in conjunction with \ref cpu_irq_restore. + * + * \return Current state of interrupt flags. + * + * \note This function leaves interrupts disabled. + */ + +/** + * \fn void cpu_irq_restore(irqflags_t flags) + * \brief Restore global interrupt flags + * + * Use in conjunction with \ref cpu_irq_save. + * + * \param flags State to set interrupt flag to. + */ + +/** + * \fn bool cpu_irq_is_enabled_flags(irqflags_t flags) + * \brief Check if interrupts are globally enabled in supplied flags + * + * \param flags Currents state of interrupt flags. + * + * \return True if interrupts are enabled. + */ + +/** + * \def cpu_irq_is_enabled + * \brief Check if interrupts are globally enabled + * + * \return True if interrupts are enabled. + */ +//@} + +//! @} + +/** + * \ingroup interrupt_group + * \defgroup interrupt_deprecated_group Deprecated interrupt definitions + */ + +#endif /* UTILS_INTERRUPT_H */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c b/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c new file mode 100644 index 0000000..d813485 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c @@ -0,0 +1,69 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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 "interrupt_sam_nvic.h" + +#if !defined(__DOXYGEN__) +/* Deprecated - global flag to determine the global interrupt state. Required by + * QTouch library, however new applications should use cpu_irq_is_enabled() + * which probes the true global interrupt state from the CPU special registers. + */ +volatile bool g_interrupt_enabled = true; +#endif + +void cpu_irq_enter_critical(void) +{ + if (cpu_irq_critical_section_counter == 0) { + if (cpu_irq_is_enabled()) { + cpu_irq_disable(); + cpu_irq_prev_interrupt_state = true; + } else { + /* Make sure the to save the prev state as false */ + cpu_irq_prev_interrupt_state = false; + } + + } + + cpu_irq_critical_section_counter++; +} + +void cpu_irq_leave_critical(void) +{ + /* Check if the user is trying to leave a critical section when not in a critical section */ + Assert(cpu_irq_critical_section_counter > 0); + + cpu_irq_critical_section_counter--; + + /* Only enable global interrupts when the counter reaches 0 and the state of the global interrupt flag + was enabled when entering critical state */ + if ((cpu_irq_critical_section_counter == 0) && (cpu_irq_prev_interrupt_state)) { + cpu_irq_enable(); + } +} + diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h new file mode 100644 index 0000000..9b5645b --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h @@ -0,0 +1,172 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef UTILS_INTERRUPT_INTERRUPT_H +#define UTILS_INTERRUPT_INTERRUPT_H + +#include +//#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \weakgroup interrupt_group + * + * @{ + */ + +/** + * \name Interrupt Service Routine definition + * + * @{ + */ + +/** + * \brief Define service routine + * + * \note For NVIC devices the interrupt service routines are predefined to + * add to vector table in binary generation, so there is no service + * register at run time. The routine collections are in exceptions.h. + * + * Usage: + * \code + ISR(foo_irq_handler) + { + // Function definition + ... + } +\endcode + * + * \param func Name for the function. + */ +# define ISR(func) \ + void func (void) + +/** + * \brief Initialize interrupt vectors + * + * For NVIC the interrupt vectors are put in vector table. So nothing + * to do to initialize them, except defined the vector function with + * right name. + * + * This must be called prior to \ref irq_register_handler. + */ +# define irq_initialize_vectors() \ + do { \ + } while(0) + +/** + * \brief Register handler for interrupt + * + * For NVIC the interrupt vectors are put in vector table. So nothing + * to do to register them, except defined the vector function with + * right name. + * + * Usage: + * \code + irq_initialize_vectors(); + irq_register_handler(foo_irq_handler); +\endcode + * + * \note The function \a func must be defined with the \ref ISR macro. + * \note The functions prototypes can be found in the device exception header + * files (exceptions.h). + */ +# define irq_register_handler(int_num, int_prio) \ + NVIC_ClearPendingIRQ( (IRQn_Type)int_num); \ + NVIC_SetPriority( (IRQn_Type)int_num, int_prio); \ + NVIC_EnableIRQ( (IRQn_Type)int_num); \ + +//@} + +# define cpu_irq_enable() \ + do { \ + g_interrupt_enabled = true; \ + __DMB(); \ + __enable_irq(); \ + } while (0) +# define cpu_irq_disable() \ + do { \ + __disable_irq(); \ + __DMB(); \ + g_interrupt_enabled = false; \ + } while (0) + +typedef uint32_t irqflags_t; + +#if !defined(__DOXYGEN__) +extern volatile bool g_interrupt_enabled; +#endif + +#define cpu_irq_is_enabled() (__get_PRIMASK() == 0) + +static volatile uint32_t cpu_irq_critical_section_counter; +static volatile bool cpu_irq_prev_interrupt_state; + +static inline irqflags_t cpu_irq_save(void) +{ + irqflags_t flags = cpu_irq_is_enabled(); + cpu_irq_disable(); + return flags; +} + +static inline bool cpu_irq_is_enabled_flags(irqflags_t flags) +{ + return (flags); +} + +static inline void cpu_irq_restore(irqflags_t flags) +{ + if (cpu_irq_is_enabled_flags(flags)) + cpu_irq_enable(); +} + +void cpu_irq_enter_critical(void); +void cpu_irq_leave_critical(void); + +/** + * \weakgroup interrupt_deprecated_group + * @{ + */ + +#define Enable_global_interrupt() cpu_irq_enable() +#define Disable_global_interrupt() cpu_irq_disable() +#define Is_global_interrupt_enabled() cpu_irq_is_enabled() + +//@} + +//@} + +#ifdef __cplusplus +} +#endif + +#endif /* UTILS_INTERRUPT_INTERRUPT_H */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c b/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c new file mode 100644 index 0000000..26dcc91 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c @@ -0,0 +1,86 @@ +/** + * \file + * + * \brief Global interrupt management for SAM D20, SAM3 and SAM4 (NVIC based) + * + * Copyright (c) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#include "interrupt_sam_nvic.h" + +#if !defined(__DOXYGEN__) +/* Deprecated - global flag to determine the global interrupt state. Required by + * QTouch library, however new applications should use cpu_irq_is_enabled() + * which probes the true global interrupt state from the CPU special registers. + */ +volatile bool g_interrupt_enabled = true; +#endif + +void cpu_irq_enter_critical(void) +{ + if (cpu_irq_critical_section_counter == 0) { + if (cpu_irq_is_enabled()) { + cpu_irq_disable(); + cpu_irq_prev_interrupt_state = true; + } else { + /* Make sure the to save the prev state as false */ + cpu_irq_prev_interrupt_state = false; + } + + } + + cpu_irq_critical_section_counter++; +} + +void cpu_irq_leave_critical(void) +{ + /* Check if the user is trying to leave a critical section when not in a critical section */ + Assert(cpu_irq_critical_section_counter > 0); + + cpu_irq_critical_section_counter--; + + /* Only enable global interrupts when the counter reaches 0 and the state of the global interrupt flag + was enabled when entering critical state */ + if ((cpu_irq_critical_section_counter == 0) && (cpu_irq_prev_interrupt_state)) { + cpu_irq_enable(); + } +} + diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h new file mode 100644 index 0000000..f996e92 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h @@ -0,0 +1,189 @@ +/** + * \file + * + * \brief Global interrupt management for SAM D20, SAM3 and SAM4 (NVIC based) + * + * Copyright (c) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#ifndef UTILS_INTERRUPT_INTERRUPT_H +#define UTILS_INTERRUPT_INTERRUPT_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \weakgroup interrupt_group + * + * @{ + */ + +/** + * \name Interrupt Service Routine definition + * + * @{ + */ + +/** + * \brief Define service routine + * + * \note For NVIC devices the interrupt service routines are predefined to + * add to vector table in binary generation, so there is no service + * register at run time. The routine collections are in exceptions.h. + * + * Usage: + * \code + ISR(foo_irq_handler) + { + // Function definition + ... + } +\endcode + * + * \param func Name for the function. + */ +# define ISR(func) \ + void func (void) + +/** + * \brief Initialize interrupt vectors + * + * For NVIC the interrupt vectors are put in vector table. So nothing + * to do to initialize them, except defined the vector function with + * right name. + * + * This must be called prior to \ref irq_register_handler. + */ +# define irq_initialize_vectors() \ + do { \ + } while(0) + +/** + * \brief Register handler for interrupt + * + * For NVIC the interrupt vectors are put in vector table. So nothing + * to do to register them, except defined the vector function with + * right name. + * + * Usage: + * \code + irq_initialize_vectors(); + irq_register_handler(foo_irq_handler); +\endcode + * + * \note The function \a func must be defined with the \ref ISR macro. + * \note The functions prototypes can be found in the device exception header + * files (exceptions.h). + */ +# define irq_register_handler(int_num, int_prio) \ + NVIC_ClearPendingIRQ( (IRQn_Type)int_num); \ + NVIC_SetPriority( (IRQn_Type)int_num, int_prio); \ + NVIC_EnableIRQ( (IRQn_Type)int_num); \ + +//@} + +# define cpu_irq_enable() \ + do { \ + g_interrupt_enabled = true; \ + __DMB(); \ + __enable_irq(); \ + } while (0) +# define cpu_irq_disable() \ + do { \ + __disable_irq(); \ + __DMB(); \ + g_interrupt_enabled = false; \ + } while (0) + +typedef uint32_t irqflags_t; + +#if !defined(__DOXYGEN__) +extern volatile bool g_interrupt_enabled; +#endif + +#define cpu_irq_is_enabled() (__get_PRIMASK() == 0) + +static volatile uint32_t cpu_irq_critical_section_counter; +static volatile bool cpu_irq_prev_interrupt_state; + +static inline irqflags_t cpu_irq_save(void) +{ + irqflags_t flags = cpu_irq_is_enabled(); + cpu_irq_disable(); + return flags; +} + +static inline bool cpu_irq_is_enabled_flags(irqflags_t flags) +{ + return (flags); +} + +static inline void cpu_irq_restore(irqflags_t flags) +{ + if (cpu_irq_is_enabled_flags(flags)) + cpu_irq_enable(); +} + +void cpu_irq_enter_critical(void); +void cpu_irq_leave_critical(void); + +/** + * \weakgroup interrupt_deprecated_group + * @{ + */ + +#define Enable_global_interrupt() cpu_irq_enable() +#define Disable_global_interrupt() cpu_irq_disable() +#define Is_global_interrupt_enabled() cpu_irq_is_enabled() + +//@} + +//@} + +#ifdef __cplusplus +} +#endif + +#endif /* UTILS_INTERRUPT_INTERRUPT_H */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/library.properties b/feather_sensor_lte/libraries/Adafruit_ASFcore/library.properties new file mode 100644 index 0000000..e2af108 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/library.properties @@ -0,0 +1,9 @@ +name=Adafruit Arduino Zero ASF Core Library +version=1.0.0 +author=Adafruit +maintainer=Adafruit +sentence=ASF (Atmel Software Framework) files used by Adafruit's Arduino Zero/SAMD21 libraries. +paragraph=ASF (Atmel Software Framework) files used by Adafruit's Arduino Zero/SAMD21 libraries. This is a dependency of other libraries like Adafruit_ZeroTimer. +category=Other +url=https://github.com/adafruit/Adafruit_ASFcore +architectures=* diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/parts.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/parts.h new file mode 100644 index 0000000..40be022 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/parts.h @@ -0,0 +1,1601 @@ +/** + * \file + * + * \brief Atmel part identification macros + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#ifndef ATMEL_PARTS_H +#define ATMEL_PARTS_H + +/** + * \defgroup part_macros_group Atmel part identification macros + * + * This collection of macros identify which series and families that the various + * Atmel parts belong to. These can be used to select part-dependent sections of + * code at compile time. + * + * @{ + */ + +/** + * \name Convenience macros for part checking + * @{ + */ +/* ! Check GCC and IAR part definition for 8-bit AVR */ +#define AVR8_PART_IS_DEFINED(part) \ + (defined(__ ## part ## __) || defined(__AVR_ ## part ## __)) + +/* ! Check GCC and IAR part definition for 32-bit AVR */ +#define AVR32_PART_IS_DEFINED(part) \ + (defined(__AT32 ## part ## __) || defined(__AVR32_ ## part ## __)) + +/* ! Check GCC and IAR part definition for SAM */ +#define SAM_PART_IS_DEFINED(part) (defined(__ ## part ## __)) +/** @} */ + +/** + * \defgroup uc3_part_macros_group AVR UC3 parts + * @{ + */ + +/** + * \name AVR UC3 A series + * @{ + */ +#define UC3A0 ( \ + AVR32_PART_IS_DEFINED(UC3A0128) || \ + AVR32_PART_IS_DEFINED(UC3A0256) || \ + AVR32_PART_IS_DEFINED(UC3A0512) \ + ) + +#define UC3A1 ( \ + AVR32_PART_IS_DEFINED(UC3A1128) || \ + AVR32_PART_IS_DEFINED(UC3A1256) || \ + AVR32_PART_IS_DEFINED(UC3A1512) \ + ) + +#define UC3A3 ( \ + AVR32_PART_IS_DEFINED(UC3A364) || \ + AVR32_PART_IS_DEFINED(UC3A364S) || \ + AVR32_PART_IS_DEFINED(UC3A3128) || \ + AVR32_PART_IS_DEFINED(UC3A3128S) || \ + AVR32_PART_IS_DEFINED(UC3A3256) || \ + AVR32_PART_IS_DEFINED(UC3A3256S) \ + ) + +#define UC3A4 ( \ + AVR32_PART_IS_DEFINED(UC3A464) || \ + AVR32_PART_IS_DEFINED(UC3A464S) || \ + AVR32_PART_IS_DEFINED(UC3A4128) || \ + AVR32_PART_IS_DEFINED(UC3A4128S) || \ + AVR32_PART_IS_DEFINED(UC3A4256) || \ + AVR32_PART_IS_DEFINED(UC3A4256S) \ + ) +/** @} */ + +/** + * \name AVR UC3 B series + * @{ + */ +#define UC3B0 ( \ + AVR32_PART_IS_DEFINED(UC3B064) || \ + AVR32_PART_IS_DEFINED(UC3B0128) || \ + AVR32_PART_IS_DEFINED(UC3B0256) || \ + AVR32_PART_IS_DEFINED(UC3B0512) \ + ) + +#define UC3B1 ( \ + AVR32_PART_IS_DEFINED(UC3B164) || \ + AVR32_PART_IS_DEFINED(UC3B1128) || \ + AVR32_PART_IS_DEFINED(UC3B1256) || \ + AVR32_PART_IS_DEFINED(UC3B1512) \ + ) +/** @} */ + +/** + * \name AVR UC3 C series + * @{ + */ +#define UC3C0 ( \ + AVR32_PART_IS_DEFINED(UC3C064C) || \ + AVR32_PART_IS_DEFINED(UC3C0128C) || \ + AVR32_PART_IS_DEFINED(UC3C0256C) || \ + AVR32_PART_IS_DEFINED(UC3C0512C) \ + ) + +#define UC3C1 ( \ + AVR32_PART_IS_DEFINED(UC3C164C) || \ + AVR32_PART_IS_DEFINED(UC3C1128C) || \ + AVR32_PART_IS_DEFINED(UC3C1256C) || \ + AVR32_PART_IS_DEFINED(UC3C1512C) \ + ) + +#define UC3C2 ( \ + AVR32_PART_IS_DEFINED(UC3C264C) || \ + AVR32_PART_IS_DEFINED(UC3C2128C) || \ + AVR32_PART_IS_DEFINED(UC3C2256C) || \ + AVR32_PART_IS_DEFINED(UC3C2512C) \ + ) +/** @} */ + +/** + * \name AVR UC3 D series + * @{ + */ +#define UC3D3 ( \ + AVR32_PART_IS_DEFINED(UC64D3) || \ + AVR32_PART_IS_DEFINED(UC128D3) \ + ) + +#define UC3D4 ( \ + AVR32_PART_IS_DEFINED(UC64D4) || \ + AVR32_PART_IS_DEFINED(UC128D4) \ + ) +/** @} */ + +/** + * \name AVR UC3 L series + * @{ + */ +#define UC3L0 ( \ + AVR32_PART_IS_DEFINED(UC3L016) || \ + AVR32_PART_IS_DEFINED(UC3L032) || \ + AVR32_PART_IS_DEFINED(UC3L064) \ + ) + +#define UC3L0128 ( \ + AVR32_PART_IS_DEFINED(UC3L0128) \ + ) + +#define UC3L0256 ( \ + AVR32_PART_IS_DEFINED(UC3L0256) \ + ) + +#define UC3L3 ( \ + AVR32_PART_IS_DEFINED(UC64L3U) || \ + AVR32_PART_IS_DEFINED(UC128L3U) || \ + AVR32_PART_IS_DEFINED(UC256L3U) \ + ) + +#define UC3L4 ( \ + AVR32_PART_IS_DEFINED(UC64L4U) || \ + AVR32_PART_IS_DEFINED(UC128L4U) || \ + AVR32_PART_IS_DEFINED(UC256L4U) \ + ) + +#define UC3L3_L4 (UC3L3 || UC3L4) +/** @} */ + +/** + * \name AVR UC3 families + * @{ + */ +/** AVR UC3 A family */ +#define UC3A (UC3A0 || UC3A1 || UC3A3 || UC3A4) + +/** AVR UC3 B family */ +#define UC3B (UC3B0 || UC3B1) + +/** AVR UC3 C family */ +#define UC3C (UC3C0 || UC3C1 || UC3C2) + +/** AVR UC3 D family */ +#define UC3D (UC3D3 || UC3D4) + +/** AVR UC3 L family */ +#define UC3L (UC3L0 || UC3L0128 || UC3L0256 || UC3L3_L4) +/** @} */ + +/** AVR UC3 product line */ +#define UC3 (UC3A || UC3B || UC3C || UC3D || UC3L) + +/** @} */ + +/** + * \defgroup xmega_part_macros_group AVR XMEGA parts + * @{ + */ + +/** + * \name AVR XMEGA A series + * @{ + */ +#define XMEGA_A1 ( \ + AVR8_PART_IS_DEFINED(ATxmega64A1) || \ + AVR8_PART_IS_DEFINED(ATxmega128A1) \ + ) + +#define XMEGA_A3 ( \ + AVR8_PART_IS_DEFINED(ATxmega64A3) || \ + AVR8_PART_IS_DEFINED(ATxmega128A3) || \ + AVR8_PART_IS_DEFINED(ATxmega192A3) || \ + AVR8_PART_IS_DEFINED(ATxmega256A3) \ + ) + +#define XMEGA_A3B ( \ + AVR8_PART_IS_DEFINED(ATxmega256A3B) \ + ) + +#define XMEGA_A4 ( \ + AVR8_PART_IS_DEFINED(ATxmega16A4) || \ + AVR8_PART_IS_DEFINED(ATxmega32A4) \ + ) +/** @} */ + +/** + * \name AVR XMEGA AU series + * @{ + */ +#define XMEGA_A1U ( \ + AVR8_PART_IS_DEFINED(ATxmega64A1U) || \ + AVR8_PART_IS_DEFINED(ATxmega128A1U) \ + ) + +#define XMEGA_A3U ( \ + AVR8_PART_IS_DEFINED(ATxmega64A3U) || \ + AVR8_PART_IS_DEFINED(ATxmega128A3U) || \ + AVR8_PART_IS_DEFINED(ATxmega192A3U) || \ + AVR8_PART_IS_DEFINED(ATxmega256A3U) \ + ) + +#define XMEGA_A3BU ( \ + AVR8_PART_IS_DEFINED(ATxmega256A3BU) \ + ) + +#define XMEGA_A4U ( \ + AVR8_PART_IS_DEFINED(ATxmega16A4U) || \ + AVR8_PART_IS_DEFINED(ATxmega32A4U) || \ + AVR8_PART_IS_DEFINED(ATxmega64A4U) || \ + AVR8_PART_IS_DEFINED(ATxmega128A4U) \ + ) +/** @} */ + +/** + * \name AVR XMEGA B series + * @{ + */ +#define XMEGA_B1 ( \ + AVR8_PART_IS_DEFINED(ATxmega64B1) || \ + AVR8_PART_IS_DEFINED(ATxmega128B1) \ + ) + +#define XMEGA_B3 ( \ + AVR8_PART_IS_DEFINED(ATxmega64B3) || \ + AVR8_PART_IS_DEFINED(ATxmega128B3) \ + ) +/** @} */ + +/** + * \name AVR XMEGA C series + * @{ + */ +#define XMEGA_C3 ( \ + AVR8_PART_IS_DEFINED(ATxmega384C3) || \ + AVR8_PART_IS_DEFINED(ATxmega256C3) || \ + AVR8_PART_IS_DEFINED(ATxmega192C3) || \ + AVR8_PART_IS_DEFINED(ATxmega128C3) || \ + AVR8_PART_IS_DEFINED(ATxmega64C3) || \ + AVR8_PART_IS_DEFINED(ATxmega32C3) \ + ) + +#define XMEGA_C4 ( \ + AVR8_PART_IS_DEFINED(ATxmega32C4) || \ + AVR8_PART_IS_DEFINED(ATxmega16C4) \ + ) +/** @} */ + +/** + * \name AVR XMEGA D series + * @{ + */ +#define XMEGA_D3 ( \ + AVR8_PART_IS_DEFINED(ATxmega32D3) || \ + AVR8_PART_IS_DEFINED(ATxmega64D3) || \ + AVR8_PART_IS_DEFINED(ATxmega128D3) || \ + AVR8_PART_IS_DEFINED(ATxmega192D3) || \ + AVR8_PART_IS_DEFINED(ATxmega256D3) || \ + AVR8_PART_IS_DEFINED(ATxmega384D3) \ + ) + +#define XMEGA_D4 ( \ + AVR8_PART_IS_DEFINED(ATxmega16D4) || \ + AVR8_PART_IS_DEFINED(ATxmega32D4) || \ + AVR8_PART_IS_DEFINED(ATxmega64D4) || \ + AVR8_PART_IS_DEFINED(ATxmega128D4) \ + ) +/** @} */ + +/** + * \name AVR XMEGA E series + * @{ + */ +#define XMEGA_E5 ( \ + AVR8_PART_IS_DEFINED(ATxmega8E5) || \ + AVR8_PART_IS_DEFINED(ATxmega16E5) || \ + AVR8_PART_IS_DEFINED(ATxmega32E5) \ + ) +/** @} */ + + +/** + * \name AVR XMEGA families + * @{ + */ +/** AVR XMEGA A family */ +#define XMEGA_A (XMEGA_A1 || XMEGA_A3 || XMEGA_A3B || XMEGA_A4) + +/** AVR XMEGA AU family */ +#define XMEGA_AU (XMEGA_A1U || XMEGA_A3U || XMEGA_A3BU || XMEGA_A4U) + +/** AVR XMEGA B family */ +#define XMEGA_B (XMEGA_B1 || XMEGA_B3) + +/** AVR XMEGA C family */ +#define XMEGA_C (XMEGA_C3 || XMEGA_C4) + +/** AVR XMEGA D family */ +#define XMEGA_D (XMEGA_D3 || XMEGA_D4) + +/** AVR XMEGA E family */ +#define XMEGA_E (XMEGA_E5) +/** @} */ + + +/** AVR XMEGA product line */ +#define XMEGA (XMEGA_A || XMEGA_AU || XMEGA_B || XMEGA_C || XMEGA_D || XMEGA_E) + +/** @} */ + +/** + * \defgroup mega_part_macros_group megaAVR parts + * + * \note These megaAVR groupings are based on the groups in AVR Libc for the + * part header files. They are not names of official megaAVR device series or + * families. + * + * @{ + */ + +/** + * \name ATmegaxx0/xx1 subgroups + * @{ + */ +#define MEGA_XX0 ( \ + AVR8_PART_IS_DEFINED(ATmega640) || \ + AVR8_PART_IS_DEFINED(ATmega1280) || \ + AVR8_PART_IS_DEFINED(ATmega2560) \ + ) + +#define MEGA_XX1 ( \ + AVR8_PART_IS_DEFINED(ATmega1281) || \ + AVR8_PART_IS_DEFINED(ATmega2561) \ + ) +/** @} */ + +/** + * \name megaAVR groups + * @{ + */ +/** ATmegaxx0/xx1 group */ +#define MEGA_XX0_1 (MEGA_XX0 || MEGA_XX1) + +/** ATmegaxx4 group */ +#define MEGA_XX4 ( \ + AVR8_PART_IS_DEFINED(ATmega164A) || \ + AVR8_PART_IS_DEFINED(ATmega164PA) || \ + AVR8_PART_IS_DEFINED(ATmega324A) || \ + AVR8_PART_IS_DEFINED(ATmega324PA) || \ + AVR8_PART_IS_DEFINED(ATmega644) || \ + AVR8_PART_IS_DEFINED(ATmega644A) || \ + AVR8_PART_IS_DEFINED(ATmega644PA) || \ + AVR8_PART_IS_DEFINED(ATmega1284P) || \ + AVR8_PART_IS_DEFINED(ATmega128RFA1) \ + ) + +/** ATmegaxx4 group */ +#define MEGA_XX4_A ( \ + AVR8_PART_IS_DEFINED(ATmega164A) || \ + AVR8_PART_IS_DEFINED(ATmega164PA) || \ + AVR8_PART_IS_DEFINED(ATmega324A) || \ + AVR8_PART_IS_DEFINED(ATmega324PA) || \ + AVR8_PART_IS_DEFINED(ATmega644A) || \ + AVR8_PART_IS_DEFINED(ATmega644PA) || \ + AVR8_PART_IS_DEFINED(ATmega1284P) \ + ) + +/** ATmegaxx8 group */ +#define MEGA_XX8 ( \ + AVR8_PART_IS_DEFINED(ATmega48) || \ + AVR8_PART_IS_DEFINED(ATmega48A) || \ + AVR8_PART_IS_DEFINED(ATmega48PA) || \ + AVR8_PART_IS_DEFINED(ATmega88) || \ + AVR8_PART_IS_DEFINED(ATmega88A) || \ + AVR8_PART_IS_DEFINED(ATmega88PA) || \ + AVR8_PART_IS_DEFINED(ATmega168) || \ + AVR8_PART_IS_DEFINED(ATmega168A) || \ + AVR8_PART_IS_DEFINED(ATmega168PA) || \ + AVR8_PART_IS_DEFINED(ATmega328) || \ + AVR8_PART_IS_DEFINED(ATmega328P) \ + ) + +/** ATmegaxx8A/P/PA group */ +#define MEGA_XX8_A ( \ + AVR8_PART_IS_DEFINED(ATmega48A) || \ + AVR8_PART_IS_DEFINED(ATmega48PA) || \ + AVR8_PART_IS_DEFINED(ATmega88A) || \ + AVR8_PART_IS_DEFINED(ATmega88PA) || \ + AVR8_PART_IS_DEFINED(ATmega168A) || \ + AVR8_PART_IS_DEFINED(ATmega168PA) || \ + AVR8_PART_IS_DEFINED(ATmega328P) \ + ) + +/** ATmegaxx group */ +#define MEGA_XX ( \ + AVR8_PART_IS_DEFINED(ATmega16) || \ + AVR8_PART_IS_DEFINED(ATmega16A) || \ + AVR8_PART_IS_DEFINED(ATmega32) || \ + AVR8_PART_IS_DEFINED(ATmega32A) || \ + AVR8_PART_IS_DEFINED(ATmega64) || \ + AVR8_PART_IS_DEFINED(ATmega64A) || \ + AVR8_PART_IS_DEFINED(ATmega128) || \ + AVR8_PART_IS_DEFINED(ATmega128A) \ + ) + +/** ATmegaxxA/P/PA group */ +#define MEGA_XX_A ( \ + AVR8_PART_IS_DEFINED(ATmega16A) || \ + AVR8_PART_IS_DEFINED(ATmega32A) || \ + AVR8_PART_IS_DEFINED(ATmega64A) || \ + AVR8_PART_IS_DEFINED(ATmega128A) \ + ) +/** ATmegaxxRFA1 group */ +#define MEGA_RFA1 ( \ + AVR8_PART_IS_DEFINED(ATmega128RFA1) \ + ) + +/** ATmegaxxRFR2 group */ +#define MEGA_RFR2 ( \ + AVR8_PART_IS_DEFINED(ATmega64RFR2) || \ + AVR8_PART_IS_DEFINED(ATmega128RFR2) || \ + AVR8_PART_IS_DEFINED(ATmega256RFR2) || \ + AVR8_PART_IS_DEFINED(ATmega644RFR2) || \ + AVR8_PART_IS_DEFINED(ATmega1284RFR2) || \ + AVR8_PART_IS_DEFINED(ATmega2564RFR2) \ + ) + + +/** ATmegaxxRFxx group */ +#define MEGA_RF (MEGA_RFA1 || MEGA_RFR2) + +/** + * \name ATmegaxx_un0/un1/un2 subgroups + * @{ + */ +#define MEGA_XX_UN0 ( \ + AVR8_PART_IS_DEFINED(ATmega16) || \ + AVR8_PART_IS_DEFINED(ATmega16A) || \ + AVR8_PART_IS_DEFINED(ATmega32) || \ + AVR8_PART_IS_DEFINED(ATmega32A) \ + ) + +/** ATmegaxx group without power reduction and + * And interrupt sense register. + */ +#define MEGA_XX_UN1 ( \ + AVR8_PART_IS_DEFINED(ATmega64) || \ + AVR8_PART_IS_DEFINED(ATmega64A) || \ + AVR8_PART_IS_DEFINED(ATmega128) || \ + AVR8_PART_IS_DEFINED(ATmega128A) \ + ) + +/** ATmegaxx group without power reduction and + * And interrupt sense register. + */ +#define MEGA_XX_UN2 ( \ + AVR8_PART_IS_DEFINED(ATmega169P) || \ + AVR8_PART_IS_DEFINED(ATmega169PA) || \ + AVR8_PART_IS_DEFINED(ATmega329P) || \ + AVR8_PART_IS_DEFINED(ATmega329PA) \ + ) + +/** Devices added to complete megaAVR offering. + * Please do not use this group symbol as it is not intended + * to be permanent: the devices should be regrouped. + */ +#define MEGA_UNCATEGORIZED ( \ + AVR8_PART_IS_DEFINED(AT90CAN128) || \ + AVR8_PART_IS_DEFINED(AT90CAN32) || \ + AVR8_PART_IS_DEFINED(AT90CAN64) || \ + AVR8_PART_IS_DEFINED(AT90PWM1) || \ + AVR8_PART_IS_DEFINED(AT90PWM216) || \ + AVR8_PART_IS_DEFINED(AT90PWM2B) || \ + AVR8_PART_IS_DEFINED(AT90PWM316) || \ + AVR8_PART_IS_DEFINED(AT90PWM3B) || \ + AVR8_PART_IS_DEFINED(AT90PWM81) || \ + AVR8_PART_IS_DEFINED(AT90USB1286) || \ + AVR8_PART_IS_DEFINED(AT90USB1287) || \ + AVR8_PART_IS_DEFINED(AT90USB162) || \ + AVR8_PART_IS_DEFINED(AT90USB646) || \ + AVR8_PART_IS_DEFINED(AT90USB647) || \ + AVR8_PART_IS_DEFINED(AT90USB82) || \ + AVR8_PART_IS_DEFINED(ATmega1284) || \ + AVR8_PART_IS_DEFINED(ATmega162) || \ + AVR8_PART_IS_DEFINED(ATmega164P) || \ + AVR8_PART_IS_DEFINED(ATmega165A) || \ + AVR8_PART_IS_DEFINED(ATmega165P) || \ + AVR8_PART_IS_DEFINED(ATmega165PA) || \ + AVR8_PART_IS_DEFINED(ATmega168P) || \ + AVR8_PART_IS_DEFINED(ATmega169A) || \ + AVR8_PART_IS_DEFINED(ATmega16M1) || \ + AVR8_PART_IS_DEFINED(ATmega16U2) || \ + AVR8_PART_IS_DEFINED(ATmega16U4) || \ + AVR8_PART_IS_DEFINED(ATmega256RFA2) || \ + AVR8_PART_IS_DEFINED(ATmega324P) || \ + AVR8_PART_IS_DEFINED(ATmega325) || \ + AVR8_PART_IS_DEFINED(ATmega3250) || \ + AVR8_PART_IS_DEFINED(ATmega3250A) || \ + AVR8_PART_IS_DEFINED(ATmega3250P) || \ + AVR8_PART_IS_DEFINED(ATmega3250PA) || \ + AVR8_PART_IS_DEFINED(ATmega325A) || \ + AVR8_PART_IS_DEFINED(ATmega325P) || \ + AVR8_PART_IS_DEFINED(ATmega325PA) || \ + AVR8_PART_IS_DEFINED(ATmega329) || \ + AVR8_PART_IS_DEFINED(ATmega3290) || \ + AVR8_PART_IS_DEFINED(ATmega3290A) || \ + AVR8_PART_IS_DEFINED(ATmega3290P) || \ + AVR8_PART_IS_DEFINED(ATmega3290PA) || \ + AVR8_PART_IS_DEFINED(ATmega329A) || \ + AVR8_PART_IS_DEFINED(ATmega32M1) || \ + AVR8_PART_IS_DEFINED(ATmega32U2) || \ + AVR8_PART_IS_DEFINED(ATmega32U4) || \ + AVR8_PART_IS_DEFINED(ATmega48P) || \ + AVR8_PART_IS_DEFINED(ATmega644P) || \ + AVR8_PART_IS_DEFINED(ATmega645) || \ + AVR8_PART_IS_DEFINED(ATmega6450) || \ + AVR8_PART_IS_DEFINED(ATmega6450A) || \ + AVR8_PART_IS_DEFINED(ATmega6450P) || \ + AVR8_PART_IS_DEFINED(ATmega645A) || \ + AVR8_PART_IS_DEFINED(ATmega645P) || \ + AVR8_PART_IS_DEFINED(ATmega649) || \ + AVR8_PART_IS_DEFINED(ATmega6490) || \ + AVR8_PART_IS_DEFINED(ATmega6490A) || \ + AVR8_PART_IS_DEFINED(ATmega6490P) || \ + AVR8_PART_IS_DEFINED(ATmega649A) || \ + AVR8_PART_IS_DEFINED(ATmega649P) || \ + AVR8_PART_IS_DEFINED(ATmega64M1) || \ + AVR8_PART_IS_DEFINED(ATmega64RFA2) || \ + AVR8_PART_IS_DEFINED(ATmega8) || \ + AVR8_PART_IS_DEFINED(ATmega8515) || \ + AVR8_PART_IS_DEFINED(ATmega8535) || \ + AVR8_PART_IS_DEFINED(ATmega88P) || \ + AVR8_PART_IS_DEFINED(ATmega8A) || \ + AVR8_PART_IS_DEFINED(ATmega8U2) \ + ) + +/** Unspecified group */ +#define MEGA_UNSPECIFIED (MEGA_XX_UN0 || MEGA_XX_UN1 || MEGA_XX_UN2 || \ + MEGA_UNCATEGORIZED) + +/** @} */ + +/** megaAVR product line */ +#define MEGA (MEGA_XX0_1 || MEGA_XX4 || MEGA_XX8 || MEGA_XX || MEGA_RF || \ + MEGA_UNSPECIFIED) + +/** @} */ + +/** + * \defgroup tiny_part_macros_group tinyAVR parts + * + * @{ + */ + +/** + * \name tinyAVR groups + * @{ + */ + +/** Devices added to complete tinyAVR offering. + * Please do not use this group symbol as it is not intended + * to be permanent: the devices should be regrouped. + */ +#define TINY_UNCATEGORIZED ( \ + AVR8_PART_IS_DEFINED(ATtiny10) || \ + AVR8_PART_IS_DEFINED(ATtiny13) || \ + AVR8_PART_IS_DEFINED(ATtiny13A) || \ + AVR8_PART_IS_DEFINED(ATtiny1634) || \ + AVR8_PART_IS_DEFINED(ATtiny167) || \ + AVR8_PART_IS_DEFINED(ATtiny20) || \ + AVR8_PART_IS_DEFINED(ATtiny2313) || \ + AVR8_PART_IS_DEFINED(ATtiny2313A) || \ + AVR8_PART_IS_DEFINED(ATtiny24) || \ + AVR8_PART_IS_DEFINED(ATtiny24A) || \ + AVR8_PART_IS_DEFINED(ATtiny25) || \ + AVR8_PART_IS_DEFINED(ATtiny26) || \ + AVR8_PART_IS_DEFINED(ATtiny261) || \ + AVR8_PART_IS_DEFINED(ATtiny261A) || \ + AVR8_PART_IS_DEFINED(ATtiny4) || \ + AVR8_PART_IS_DEFINED(ATtiny40) || \ + AVR8_PART_IS_DEFINED(ATtiny4313) || \ + AVR8_PART_IS_DEFINED(ATtiny43U) || \ + AVR8_PART_IS_DEFINED(ATtiny44) || \ + AVR8_PART_IS_DEFINED(ATtiny44A) || \ + AVR8_PART_IS_DEFINED(ATtiny45) || \ + AVR8_PART_IS_DEFINED(ATtiny461) || \ + AVR8_PART_IS_DEFINED(ATtiny461A) || \ + AVR8_PART_IS_DEFINED(ATtiny48) || \ + AVR8_PART_IS_DEFINED(ATtiny5) || \ + AVR8_PART_IS_DEFINED(ATtiny828) || \ + AVR8_PART_IS_DEFINED(ATtiny84) || \ + AVR8_PART_IS_DEFINED(ATtiny84A) || \ + AVR8_PART_IS_DEFINED(ATtiny85) || \ + AVR8_PART_IS_DEFINED(ATtiny861) || \ + AVR8_PART_IS_DEFINED(ATtiny861A) || \ + AVR8_PART_IS_DEFINED(ATtiny87) || \ + AVR8_PART_IS_DEFINED(ATtiny88) || \ + AVR8_PART_IS_DEFINED(ATtiny9) \ + ) + +/** @} */ + +/** tinyAVR product line */ +#define TINY (TINY_UNCATEGORIZED) + +/** @} */ + +/** + * \defgroup sam_part_macros_group SAM parts + * @{ + */ + +/** + * \name SAM3S series + * @{ + */ +#define SAM3S1 ( \ + SAM_PART_IS_DEFINED(SAM3S1A) || \ + SAM_PART_IS_DEFINED(SAM3S1B) || \ + SAM_PART_IS_DEFINED(SAM3S1C) \ + ) + +#define SAM3S2 ( \ + SAM_PART_IS_DEFINED(SAM3S2A) || \ + SAM_PART_IS_DEFINED(SAM3S2B) || \ + SAM_PART_IS_DEFINED(SAM3S2C) \ + ) + +#define SAM3S4 ( \ + SAM_PART_IS_DEFINED(SAM3S4A) || \ + SAM_PART_IS_DEFINED(SAM3S4B) || \ + SAM_PART_IS_DEFINED(SAM3S4C) \ + ) + +#define SAM3S8 ( \ + SAM_PART_IS_DEFINED(SAM3S8B) || \ + SAM_PART_IS_DEFINED(SAM3S8C) \ + ) + +#define SAM3SD8 ( \ + SAM_PART_IS_DEFINED(SAM3SD8B) || \ + SAM_PART_IS_DEFINED(SAM3SD8C) \ + ) +/** @} */ + +/** + * \name SAM3U series + * @{ + */ +#define SAM3U1 ( \ + SAM_PART_IS_DEFINED(SAM3U1C) || \ + SAM_PART_IS_DEFINED(SAM3U1E) \ + ) + +#define SAM3U2 ( \ + SAM_PART_IS_DEFINED(SAM3U2C) || \ + SAM_PART_IS_DEFINED(SAM3U2E) \ + ) + +#define SAM3U4 ( \ + SAM_PART_IS_DEFINED(SAM3U4C) || \ + SAM_PART_IS_DEFINED(SAM3U4E) \ + ) +/** @} */ + +/** + * \name SAM3N series + * @{ + */ +#define SAM3N00 ( \ + SAM_PART_IS_DEFINED(SAM3N00A) || \ + SAM_PART_IS_DEFINED(SAM3N00B) \ + ) + +#define SAM3N0 ( \ + SAM_PART_IS_DEFINED(SAM3N0A) || \ + SAM_PART_IS_DEFINED(SAM3N0B) || \ + SAM_PART_IS_DEFINED(SAM3N0C) \ + ) + +#define SAM3N1 ( \ + SAM_PART_IS_DEFINED(SAM3N1A) || \ + SAM_PART_IS_DEFINED(SAM3N1B) || \ + SAM_PART_IS_DEFINED(SAM3N1C) \ + ) + +#define SAM3N2 ( \ + SAM_PART_IS_DEFINED(SAM3N2A) || \ + SAM_PART_IS_DEFINED(SAM3N2B) || \ + SAM_PART_IS_DEFINED(SAM3N2C) \ + ) + +#define SAM3N4 ( \ + SAM_PART_IS_DEFINED(SAM3N4A) || \ + SAM_PART_IS_DEFINED(SAM3N4B) || \ + SAM_PART_IS_DEFINED(SAM3N4C) \ + ) +/** @} */ + +/** + * \name SAM3X series + * @{ + */ +#define SAM3X4 ( \ + SAM_PART_IS_DEFINED(SAM3X4C) || \ + SAM_PART_IS_DEFINED(SAM3X4E) \ + ) + +#define SAM3X8 ( \ + SAM_PART_IS_DEFINED(SAM3X8C) || \ + SAM_PART_IS_DEFINED(SAM3X8E) || \ + SAM_PART_IS_DEFINED(SAM3X8H) \ + ) +/** @} */ + +/** + * \name SAM3A series + * @{ + */ +#define SAM3A4 ( \ + SAM_PART_IS_DEFINED(SAM3A4C) \ + ) + +#define SAM3A8 ( \ + SAM_PART_IS_DEFINED(SAM3A8C) \ + ) +/** @} */ + +/** + * \name SAM4S series + * @{ + */ +#define SAM4S2 ( \ + SAM_PART_IS_DEFINED(SAM4S2A) || \ + SAM_PART_IS_DEFINED(SAM4S2B) || \ + SAM_PART_IS_DEFINED(SAM4S2C) \ + ) + +#define SAM4S4 ( \ + SAM_PART_IS_DEFINED(SAM4S4A) || \ + SAM_PART_IS_DEFINED(SAM4S4B) || \ + SAM_PART_IS_DEFINED(SAM4S4C) \ + ) + +#define SAM4S8 ( \ + SAM_PART_IS_DEFINED(SAM4S8B) || \ + SAM_PART_IS_DEFINED(SAM4S8C) \ + ) + +#define SAM4S16 ( \ + SAM_PART_IS_DEFINED(SAM4S16B) || \ + SAM_PART_IS_DEFINED(SAM4S16C) \ + ) + +#define SAM4SA16 ( \ + SAM_PART_IS_DEFINED(SAM4SA16B) || \ + SAM_PART_IS_DEFINED(SAM4SA16C) \ + ) + +#define SAM4SD16 ( \ + SAM_PART_IS_DEFINED(SAM4SD16B) || \ + SAM_PART_IS_DEFINED(SAM4SD16C) \ + ) + +#define SAM4SD32 ( \ + SAM_PART_IS_DEFINED(SAM4SD32B) || \ + SAM_PART_IS_DEFINED(SAM4SD32C) \ + ) +/** @} */ + +/** + * \name SAM4L series + * @{ + */ +#define SAM4LS ( \ + SAM_PART_IS_DEFINED(SAM4LS2A) || \ + SAM_PART_IS_DEFINED(SAM4LS2B) || \ + SAM_PART_IS_DEFINED(SAM4LS2C) || \ + SAM_PART_IS_DEFINED(SAM4LS4A) || \ + SAM_PART_IS_DEFINED(SAM4LS4B) || \ + SAM_PART_IS_DEFINED(SAM4LS4C) || \ + SAM_PART_IS_DEFINED(SAM4LS8A) || \ + SAM_PART_IS_DEFINED(SAM4LS8B) || \ + SAM_PART_IS_DEFINED(SAM4LS8C) \ + ) + +#define SAM4LC ( \ + SAM_PART_IS_DEFINED(SAM4LC2A) || \ + SAM_PART_IS_DEFINED(SAM4LC2B) || \ + SAM_PART_IS_DEFINED(SAM4LC2C) || \ + SAM_PART_IS_DEFINED(SAM4LC4A) || \ + SAM_PART_IS_DEFINED(SAM4LC4B) || \ + SAM_PART_IS_DEFINED(SAM4LC4C) || \ + SAM_PART_IS_DEFINED(SAM4LC8A) || \ + SAM_PART_IS_DEFINED(SAM4LC8B) || \ + SAM_PART_IS_DEFINED(SAM4LC8C) \ + ) +/** @} */ + +/** + * \name SAMD20 series + * @{ + */ +#define SAMD20J ( \ + SAM_PART_IS_DEFINED(SAMD20J14) || \ + SAM_PART_IS_DEFINED(SAMD20J15) || \ + SAM_PART_IS_DEFINED(SAMD20J16) || \ + SAM_PART_IS_DEFINED(SAMD20J17) || \ + SAM_PART_IS_DEFINED(SAMD20J18) \ + ) + +#define SAMD20G ( \ + SAM_PART_IS_DEFINED(SAMD20G14) || \ + SAM_PART_IS_DEFINED(SAMD20G15) || \ + SAM_PART_IS_DEFINED(SAMD20G16) || \ + SAM_PART_IS_DEFINED(SAMD20G17) || \ + SAM_PART_IS_DEFINED(SAMD20G17U) || \ + SAM_PART_IS_DEFINED(SAMD20G18) || \ + SAM_PART_IS_DEFINED(SAMD20G18U) \ + ) + +#define SAMD20E ( \ + SAM_PART_IS_DEFINED(SAMD20E14) || \ + SAM_PART_IS_DEFINED(SAMD20E15) || \ + SAM_PART_IS_DEFINED(SAMD20E16) || \ + SAM_PART_IS_DEFINED(SAMD20E17) || \ + SAM_PART_IS_DEFINED(SAMD20E18) \ + ) +/** @} */ + +/** + * \name SAMD21 series + * @{ + */ +#define SAMD21J ( \ + SAM_PART_IS_DEFINED(SAMD21J15A) || \ + SAM_PART_IS_DEFINED(SAMD21J16A) || \ + SAM_PART_IS_DEFINED(SAMD21J17A) || \ + SAM_PART_IS_DEFINED(SAMD21J18A) || \ + SAM_PART_IS_DEFINED(SAMD21J15B) || \ + SAM_PART_IS_DEFINED(SAMD21J16B) \ + ) + +#define SAMD21G ( \ + SAM_PART_IS_DEFINED(SAMD21G15A) || \ + SAM_PART_IS_DEFINED(SAMD21G16A) || \ + SAM_PART_IS_DEFINED(SAMD21G17A) || \ + SAM_PART_IS_DEFINED(SAMD21G17AU) || \ + SAM_PART_IS_DEFINED(SAMD21G18A) || \ + SAM_PART_IS_DEFINED(SAMD21G18AU) || \ + SAM_PART_IS_DEFINED(SAMD21G15B) || \ + SAM_PART_IS_DEFINED(SAMD21G16B) || \ + SAM_PART_IS_DEFINED(SAMD21G15L) || \ + SAM_PART_IS_DEFINED(SAMD21G16L) \ + ) + +#define SAMD21GXXL ( \ + SAM_PART_IS_DEFINED(SAMD21G15L) || \ + SAM_PART_IS_DEFINED(SAMD21G16L) \ + ) + +#define SAMD21E ( \ + SAM_PART_IS_DEFINED(SAMD21E15A) || \ + SAM_PART_IS_DEFINED(SAMD21E16A) || \ + SAM_PART_IS_DEFINED(SAMD21E17A) || \ + SAM_PART_IS_DEFINED(SAMD21E18A) || \ + SAM_PART_IS_DEFINED(SAMD21E15B) || \ + SAM_PART_IS_DEFINED(SAMD21E15BU) || \ + SAM_PART_IS_DEFINED(SAMD21E16B) || \ + SAM_PART_IS_DEFINED(SAMD21E16BU) || \ + SAM_PART_IS_DEFINED(SAMD21E15L) || \ + SAM_PART_IS_DEFINED(SAMD21E16L) \ + ) + +#define SAMD21EXXL ( \ + SAM_PART_IS_DEFINED(SAMD21E15L) || \ + SAM_PART_IS_DEFINED(SAMD21E16L) \ + ) + +/** @} */ + +/** + * \name SAMR21 series + * @{ + */ +#define SAMR21G ( \ + SAM_PART_IS_DEFINED(SAMR21G16A) || \ + SAM_PART_IS_DEFINED(SAMR21G17A) || \ + SAM_PART_IS_DEFINED(SAMR21G18A) \ + ) + +#define SAMR21E ( \ + SAM_PART_IS_DEFINED(SAMR21E16A) || \ + SAM_PART_IS_DEFINED(SAMR21E17A) || \ + SAM_PART_IS_DEFINED(SAMR21E18A) || \ + SAM_PART_IS_DEFINED(SAMR21E19A) \ + ) +/** @} */ + +/** + * \name SAMD09 series + * @{ + */ +#define SAMD09C ( \ + SAM_PART_IS_DEFINED(SAMD09C13A) \ + ) + +#define SAMD09D ( \ + SAM_PART_IS_DEFINED(SAMD09D14A) \ + ) +/** @} */ + +/** + * \name SAMD10 series + * @{ + */ +#define SAMD10C ( \ + SAM_PART_IS_DEFINED(SAMD10C12A) || \ + SAM_PART_IS_DEFINED(SAMD10C13A) || \ + SAM_PART_IS_DEFINED(SAMD10C14A) \ + ) + +#define SAMD10DS ( \ + SAM_PART_IS_DEFINED(SAMD10D12AS) || \ + SAM_PART_IS_DEFINED(SAMD10D13AS) || \ + SAM_PART_IS_DEFINED(SAMD10D14AS) \ + ) + +#define SAMD10DM ( \ + SAM_PART_IS_DEFINED(SAMD10D12AM) || \ + SAM_PART_IS_DEFINED(SAMD10D13AM) || \ + SAM_PART_IS_DEFINED(SAMD10D14AM) \ + ) +/** @} */ + +/** + * \name SAMD11 series + * @{ + */ +#define SAMD11C ( \ + SAM_PART_IS_DEFINED(SAMD11C14A) \ + ) + +#define SAMD11DS ( \ + SAM_PART_IS_DEFINED(SAMD11D14AS) \ + ) + +#define SAMD11DM ( \ + SAM_PART_IS_DEFINED(SAMD11D14AM) \ + ) +/** @} */ + +/** + * \name SAML21 series + * @{ + */ +#define SAML21E ( \ + SAM_PART_IS_DEFINED(SAML21E18A) || \ + SAM_PART_IS_DEFINED(SAML21E15B) || \ + SAM_PART_IS_DEFINED(SAML21E16B) || \ + SAM_PART_IS_DEFINED(SAML21E17B) || \ + SAM_PART_IS_DEFINED(SAML21E18B) \ + ) + +#define SAML21G ( \ + SAM_PART_IS_DEFINED(SAML21G18A) || \ + SAM_PART_IS_DEFINED(SAML21G16B) || \ + SAM_PART_IS_DEFINED(SAML21G17B) || \ + SAM_PART_IS_DEFINED(SAML21G18B) \ + ) + +#define SAML21J ( \ + SAM_PART_IS_DEFINED(SAML21J18A) || \ + SAM_PART_IS_DEFINED(SAML21J16B) || \ + SAM_PART_IS_DEFINED(SAML21J17B) || \ + SAM_PART_IS_DEFINED(SAML21J18B) \ + ) + +/* Group for SAML21 A variant: SAML21[E/G/J][18]A */ +#define SAML21XXXA ( \ + SAM_PART_IS_DEFINED(SAML21E18A) || \ + SAM_PART_IS_DEFINED(SAML21G18A) || \ + SAM_PART_IS_DEFINED(SAML21J18A) \ + ) + +/* Group for SAML21 B variant: SAML21[E/G/J][15/16/1718]B */ +#define SAML21XXXB ( \ + SAM_PART_IS_DEFINED(SAML21E15B) || \ + SAM_PART_IS_DEFINED(SAML21E16B) || \ + SAM_PART_IS_DEFINED(SAML21E17B) || \ + SAM_PART_IS_DEFINED(SAML21E18B) || \ + SAM_PART_IS_DEFINED(SAML21G16B) || \ + SAM_PART_IS_DEFINED(SAML21G17B) || \ + SAM_PART_IS_DEFINED(SAML21G18B) || \ + SAM_PART_IS_DEFINED(SAML21J16B) || \ + SAM_PART_IS_DEFINED(SAML21J17B) || \ + SAM_PART_IS_DEFINED(SAML21J18B) \ + ) + +/** @} */ + +/** + * \name SAML22 series + * @{ + */ +#define SAML22N ( \ + SAM_PART_IS_DEFINED(SAML22N16A) || \ + SAM_PART_IS_DEFINED(SAML22N17A) || \ + SAM_PART_IS_DEFINED(SAML22N18A) \ + ) + +#define SAML22G ( \ + SAM_PART_IS_DEFINED(SAML22G16A) || \ + SAM_PART_IS_DEFINED(SAML22G17A) || \ + SAM_PART_IS_DEFINED(SAML22G18A) \ + ) + +#define SAML22J ( \ + SAM_PART_IS_DEFINED(SAML22J16A) || \ + SAM_PART_IS_DEFINED(SAML22J17A) || \ + SAM_PART_IS_DEFINED(SAML22J18A) \ + ) +/** @} */ + +/** + * \name SAMDA0 series + * @{ + */ +#define SAMDA0J ( \ + SAM_PART_IS_DEFINED(SAMDA0J14A) || \ + SAM_PART_IS_DEFINED(SAMDA0J15A) || \ + SAM_PART_IS_DEFINED(SAMDA0J16A) \ + ) + +#define SAMDA0G ( \ + SAM_PART_IS_DEFINED(SAMDA0G14A) || \ + SAM_PART_IS_DEFINED(SAMDA0G15A) || \ + SAM_PART_IS_DEFINED(SAMDA0G16A) \ + ) + +#define SAMDA0E ( \ + SAM_PART_IS_DEFINED(SAMDA0E14A) || \ + SAM_PART_IS_DEFINED(SAMDA0E15A) || \ + SAM_PART_IS_DEFINED(SAMDA0E16A) \ + ) +/** @} */ + +/** + * \name SAMDA1 series + * @{ + */ +#define SAMDA1J ( \ + SAM_PART_IS_DEFINED(SAMDA1J14A) || \ + SAM_PART_IS_DEFINED(SAMDA1J15A) || \ + SAM_PART_IS_DEFINED(SAMDA1J16A) \ + ) + +#define SAMDA1G ( \ + SAM_PART_IS_DEFINED(SAMDA1G14A) || \ + SAM_PART_IS_DEFINED(SAMDA1G15A) || \ + SAM_PART_IS_DEFINED(SAMDA1G16A) \ + ) + +#define SAMDA1E ( \ + SAM_PART_IS_DEFINED(SAMDA1E14A) || \ + SAM_PART_IS_DEFINED(SAMDA1E15A) || \ + SAM_PART_IS_DEFINED(SAMDA1E16A) \ + ) +/** @} */ + +/** + * \name SAMC20 series + * @{ + */ +#define SAMC20E ( \ + SAM_PART_IS_DEFINED(SAMC20E15A) || \ + SAM_PART_IS_DEFINED(SAMC20E16A) || \ + SAM_PART_IS_DEFINED(SAMC20E17A) || \ + SAM_PART_IS_DEFINED(SAMC20E18A) \ + ) + +#define SAMC20G ( \ + SAM_PART_IS_DEFINED(SAMC20G15A) || \ + SAM_PART_IS_DEFINED(SAMC20G16A) || \ + SAM_PART_IS_DEFINED(SAMC20G17A) || \ + SAM_PART_IS_DEFINED(SAMC20G18A) \ + ) + +#define SAMC20J ( \ + SAM_PART_IS_DEFINED(SAMC20J15A) || \ + SAM_PART_IS_DEFINED(SAMC20J16A) || \ + SAM_PART_IS_DEFINED(SAMC20J17A) || \ + SAM_PART_IS_DEFINED(SAMC20J18A) \ + ) +/** @} */ + +/** + * \name SAMC21 series + * @{ + */ +#define SAMC21E ( \ + SAM_PART_IS_DEFINED(SAMC21E15A) || \ + SAM_PART_IS_DEFINED(SAMC21E16A) || \ + SAM_PART_IS_DEFINED(SAMC21E17A) || \ + SAM_PART_IS_DEFINED(SAMC21E18A) \ + ) + +#define SAMC21G ( \ + SAM_PART_IS_DEFINED(SAMC21G15A) || \ + SAM_PART_IS_DEFINED(SAMC21G16A) || \ + SAM_PART_IS_DEFINED(SAMC21G17A) || \ + SAM_PART_IS_DEFINED(SAMC21G18A) \ + ) + +#define SAMC21J ( \ + SAM_PART_IS_DEFINED(SAMC21J15A) || \ + SAM_PART_IS_DEFINED(SAMC21J16A) || \ + SAM_PART_IS_DEFINED(SAMC21J17A) || \ + SAM_PART_IS_DEFINED(SAMC21J18A) \ + ) +/** @} */ + +/** + * \name SAM4E series + * @{ + */ +#define SAM4E8 ( \ + SAM_PART_IS_DEFINED(SAM4E8C) || \ + SAM_PART_IS_DEFINED(SAM4E8E) \ + ) + +#define SAM4E16 ( \ + SAM_PART_IS_DEFINED(SAM4E16C) || \ + SAM_PART_IS_DEFINED(SAM4E16E) \ + ) +/** @} */ + +/** + * \name SAM4N series + * @{ + */ +#define SAM4N8 ( \ + SAM_PART_IS_DEFINED(SAM4N8A) || \ + SAM_PART_IS_DEFINED(SAM4N8B) || \ + SAM_PART_IS_DEFINED(SAM4N8C) \ + ) + +#define SAM4N16 ( \ + SAM_PART_IS_DEFINED(SAM4N16B) || \ + SAM_PART_IS_DEFINED(SAM4N16C) \ + ) +/** @} */ + +/** + * \name SAM4C series + * @{ + */ +#define SAM4C4_0 ( \ + SAM_PART_IS_DEFINED(SAM4C4C_0) \ + ) + +#define SAM4C4_1 ( \ + SAM_PART_IS_DEFINED(SAM4C4C_1) \ + ) + +#define SAM4C4 (SAM4C4_0 || SAM4C4_1) + +#define SAM4C8_0 ( \ + SAM_PART_IS_DEFINED(SAM4C8C_0) \ + ) + +#define SAM4C8_1 ( \ + SAM_PART_IS_DEFINED(SAM4C8C_1) \ + ) + +#define SAM4C8 (SAM4C8_0 || SAM4C8_1) + +#define SAM4C16_0 ( \ + SAM_PART_IS_DEFINED(SAM4C16C_0) \ + ) + +#define SAM4C16_1 ( \ + SAM_PART_IS_DEFINED(SAM4C16C_1) \ + ) + +#define SAM4C16 (SAM4C16_0 || SAM4C16_1) + +#define SAM4C32_0 ( \ + SAM_PART_IS_DEFINED(SAM4C32C_0) ||\ + SAM_PART_IS_DEFINED(SAM4C32E_0) \ + ) + +#define SAM4C32_1 ( \ + SAM_PART_IS_DEFINED(SAM4C32C_1) ||\ + SAM_PART_IS_DEFINED(SAM4C32E_1) \ + ) + + +#define SAM4C32 (SAM4C32_0 || SAM4C32_1) + +/** @} */ + +/** + * \name SAM4CM series + * @{ + */ +#define SAM4CMP8_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMP8C_0) \ + ) + +#define SAM4CMP8_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMP8C_1) \ + ) + +#define SAM4CMP8 (SAM4CMP8_0 || SAM4CMP8_1) + +#define SAM4CMP16_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMP16C_0) \ + ) + +#define SAM4CMP16_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMP16C_1) \ + ) + +#define SAM4CMP16 (SAM4CMP16_0 || SAM4CMP16_1) + +#define SAM4CMP32_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMP32C_0) \ + ) + +#define SAM4CMP32_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMP32C_1) \ + ) + +#define SAM4CMP32 (SAM4CMP32_0 || SAM4CMP32_1) + +#define SAM4CMS4_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMS4C_0) \ + ) + +#define SAM4CMS4_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMS4C_1) \ + ) + +#define SAM4CMS4 (SAM4CMS4_0 || SAM4CMS4_1) + +#define SAM4CMS8_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMS8C_0) \ + ) + +#define SAM4CMS8_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMS8C_1) \ + ) + +#define SAM4CMS8 (SAM4CMS8_0 || SAM4CMS8_1) + +#define SAM4CMS16_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMS16C_0) \ + ) + +#define SAM4CMS16_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMS16C_1) \ + ) + +#define SAM4CMS16 (SAM4CMS16_0 || SAM4CMS16_1) + +#define SAM4CMS32_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMS32C_0) \ + ) + +#define SAM4CMS32_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMS32C_1) \ + ) + +#define SAM4CMS32 (SAM4CMS32_0 || SAM4CMS32_1) + +/** @} */ + +/** + * \name SAM4CP series + * @{ + */ +#define SAM4CP16_0 ( \ + SAM_PART_IS_DEFINED(SAM4CP16B_0) \ + ) + +#define SAM4CP16_1 ( \ + SAM_PART_IS_DEFINED(SAM4CP16B_1) \ + ) + +#define SAM4CP16 (SAM4CP16_0 || SAM4CP16_1) +/** @} */ + +/** + * \name SAMG series + * @{ + */ +#define SAMG51 ( \ + SAM_PART_IS_DEFINED(SAMG51G18) \ + ) + +#define SAMG53 ( \ + SAM_PART_IS_DEFINED(SAMG53G19) ||\ + SAM_PART_IS_DEFINED(SAMG53N19) \ + ) + +#define SAMG54 ( \ + SAM_PART_IS_DEFINED(SAMG54G19) ||\ + SAM_PART_IS_DEFINED(SAMG54J19) ||\ + SAM_PART_IS_DEFINED(SAMG54N19) \ + ) + +#define SAMG55 ( \ + SAM_PART_IS_DEFINED(SAMG55G18) ||\ + SAM_PART_IS_DEFINED(SAMG55G19) ||\ + SAM_PART_IS_DEFINED(SAMG55J18) ||\ + SAM_PART_IS_DEFINED(SAMG55J19) ||\ + SAM_PART_IS_DEFINED(SAMG55N19) \ + ) +/** @} */ + +/** + * \name SAMV71 series + * @{ + */ +#define SAMV71J ( \ + SAM_PART_IS_DEFINED(SAMV71J19) || \ + SAM_PART_IS_DEFINED(SAMV71J20) || \ + SAM_PART_IS_DEFINED(SAMV71J21) \ + ) + +#define SAMV71N ( \ + SAM_PART_IS_DEFINED(SAMV71N19) || \ + SAM_PART_IS_DEFINED(SAMV71N20) || \ + SAM_PART_IS_DEFINED(SAMV71N21) \ + ) + +#define SAMV71Q ( \ + SAM_PART_IS_DEFINED(SAMV71Q19) || \ + SAM_PART_IS_DEFINED(SAMV71Q20) || \ + SAM_PART_IS_DEFINED(SAMV71Q21) \ + ) +/** @} */ + +/** + * \name SAMV70 series + * @{ + */ +#define SAMV70J ( \ + SAM_PART_IS_DEFINED(SAMV70J19) || \ + SAM_PART_IS_DEFINED(SAMV70J20) \ + ) + +#define SAMV70N ( \ + SAM_PART_IS_DEFINED(SAMV70N19) || \ + SAM_PART_IS_DEFINED(SAMV70N20) \ + ) + +#define SAMV70Q ( \ + SAM_PART_IS_DEFINED(SAMV70Q19) || \ + SAM_PART_IS_DEFINED(SAMV70Q20) \ + ) +/** @} */ + +/** + * \name SAMS70 series + * @{ + */ +#define SAMS70J ( \ + SAM_PART_IS_DEFINED(SAMS70J19) || \ + SAM_PART_IS_DEFINED(SAMS70J20) || \ + SAM_PART_IS_DEFINED(SAMS70J21) \ + ) + +#define SAMS70N ( \ + SAM_PART_IS_DEFINED(SAMS70N19) || \ + SAM_PART_IS_DEFINED(SAMS70N20) || \ + SAM_PART_IS_DEFINED(SAMS70N21) \ + ) + +#define SAMS70Q ( \ + SAM_PART_IS_DEFINED(SAMS70Q19) || \ + SAM_PART_IS_DEFINED(SAMS70Q20) || \ + SAM_PART_IS_DEFINED(SAMS70Q21) \ + ) +/** @} */ + +/** + * \name SAME70 series + * @{ + */ +#define SAME70J ( \ + SAM_PART_IS_DEFINED(SAME70J19) || \ + SAM_PART_IS_DEFINED(SAME70J20) || \ + SAM_PART_IS_DEFINED(SAME70J21) \ + ) + +#define SAME70N ( \ + SAM_PART_IS_DEFINED(SAME70N19) || \ + SAM_PART_IS_DEFINED(SAME70N20) || \ + SAM_PART_IS_DEFINED(SAME70N21) \ + ) + +#define SAME70Q ( \ + SAM_PART_IS_DEFINED(SAME70Q19) || \ + SAM_PART_IS_DEFINED(SAME70Q20) || \ + SAM_PART_IS_DEFINED(SAME70Q21) \ + ) +/** @} */ + +/** + * \name SAM families + * @{ + */ +/** SAM3S Family */ +#define SAM3S (SAM3S1 || SAM3S2 || SAM3S4 || SAM3S8 || SAM3SD8) + +/** SAM3U Family */ +#define SAM3U (SAM3U1 || SAM3U2 || SAM3U4) + +/** SAM3N Family */ +#define SAM3N (SAM3N00 || SAM3N0 || SAM3N1 || SAM3N2 || SAM3N4) + +/** SAM3XA Family */ +#define SAM3XA (SAM3X4 || SAM3X8 || SAM3A4 || SAM3A8) + +/** SAM4S Family */ +#define SAM4S (SAM4S2 || SAM4S4 || SAM4S8 || SAM4S16 || SAM4SA16 || SAM4SD16 || SAM4SD32) + +/** SAM4L Family */ +#define SAM4L (SAM4LS || SAM4LC) + +/** SAMD20 Family */ +#define SAMD20 (SAMD20J || SAMD20G || SAMD20E) + +/** SAMD21 Family */ +#define SAMD21 (SAMD21J || SAMD21G || SAMD21E) + +/** SAMD09 Family */ +#define SAMD09 (SAMD09C || SAMD09D) + +/** SAMD10 Family */ +#define SAMD10 (SAMD10C || SAMD10DS || SAMD10DM) + +/** SAMD11 Family */ +#define SAMD11 (SAMD11C || SAMD11DS || SAMD11DM) + +/** SAMDA1 Family */ +#define SAMDA1 (SAMDA1J || SAMDA1G || SAMDA1E) + +/** SAMD Family */ +#define SAMD (SAMD20 || SAMD21 || SAMD09 || SAMD10 || SAMD11 || SAMDA1) + +/** SAMR21 Family */ +#define SAMR21 (SAMR21G || SAMR21E) + +/** SAML21 Family */ +#define SAML21 (SAML21J || SAML21G || SAML21E) + +/** SAML22 Family */ +#define SAML22 (SAML22J || SAML22G || SAML22N) +/** SAMC20 Family */ +#define SAMC20 (SAMC20J || SAMC20G || SAMC20E) + +/** SAMC21 Family */ +#define SAMC21 (SAMC21J || SAMC21G || SAMC21E) + +/** SAM4E Family */ +#define SAM4E (SAM4E8 || SAM4E16) + +/** SAM4N Family */ +#define SAM4N (SAM4N8 || SAM4N16) + +/** SAM4C Family */ +#define SAM4C_0 (SAM4C4_0 || SAM4C8_0 || SAM4C16_0 || SAM4C32_0) +#define SAM4C_1 (SAM4C4_1 || SAM4C8_1 || SAM4C16_1 || SAM4C32_1) +#define SAM4C (SAM4C4 || SAM4C8 || SAM4C16 || SAM4C32) + +/** SAM4CM Family */ +#define SAM4CM_0 (SAM4CMP8_0 || SAM4CMP16_0 || SAM4CMP32_0 || \ + SAM4CMS4_0 || SAM4CMS8_0 || SAM4CMS16_0 || SAM4CMS32_0) +#define SAM4CM_1 (SAM4CMP8_1 || SAM4CMP16_1 || SAM4CMP32_1 || \ + SAM4CMS4_1 || SAM4CMS8_1 || SAM4CMS16_1 || SAM4CMS32_1) +#define SAM4CM (SAM4CMP8 || SAM4CMP16 || SAM4CMP32 || \ + SAM4CMS4 || SAM4CMS8 || SAM4CMS16 || SAM4CMS32) + +/** SAM4CP Family */ +#define SAM4CP_0 (SAM4CP16_0) +#define SAM4CP_1 (SAM4CP16_1) +#define SAM4CP (SAM4CP16) + +/** SAMG Family */ +#define SAMG (SAMG51 || SAMG53 || SAMG54 || SAMG55) + +/** SAMV71 Family */ +#define SAMV71 (SAMV71J || SAMV71N || SAMV71Q) + +/** SAMV70 Family */ +#define SAMV70 (SAMV70J || SAMV70N || SAMV70Q) + +/** SAME70 Family */ +#define SAME70 (SAME70J || SAME70N || SAME70Q) + +/** SAMS70 Family */ +#define SAMS70 (SAMS70J || SAMS70N || SAMS70Q) + +/** SAM0 product line (cortex-m0+) */ +#define SAM0 (SAMD20 || SAMD21 || SAMR21 || SAMD10 || SAMD11 || SAML21 ||\ + SAMDA1 || SAMC20 || SAMC21 || SAML22 || SAMD09) + +/** @} */ + +/** SAM product line */ +#define SAM (SAM3S || SAM3U || SAM3N || SAM3XA || SAM4S || SAM4L || SAM4E || \ + SAM0 || SAM4N || SAM4C || SAM4CM || SAM4CP || SAMG || SAMV71 || SAMV70 || SAME70 || SAMS70) + +/** @} */ + +/** @} */ + +/** @} */ + +#endif /* ATMEL_PARTS_H */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/pinmux.c b/feather_sensor_lte/libraries/Adafruit_ASFcore/pinmux.c new file mode 100644 index 0000000..a2c9c7c --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/pinmux.c @@ -0,0 +1,311 @@ +/** + * \file + * + * \brief SAM Pin Multiplexer Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#include + +/** + * \internal + * Writes out a given configuration of a Port pin configuration to the + * hardware module. + * + * \note If the pin direction is set as an output, the pull-up/pull-down input + * configuration setting is ignored. + * + * \param[in] port Base of the PORT module to configure + * \param[in] pin_mask Mask of the port pin to configure + * \param[in] config Configuration settings for the pin + */ +static void _system_pinmux_config( + PortGroup *const port, + const uint32_t pin_mask, + const struct system_pinmux_config *const config) +{ + Assert(port); + Assert(config); + + /* Track the configuration bits into a temporary variable before writing */ + uint32_t pin_cfg = 0; + + /* Enabled powersave mode, don't create configuration */ + if (!config->powersave) { + /* Enable the pin peripheral MUX flag if non-GPIO selected (pinmux will + * be written later) and store the new MUX mask */ + if (config->mux_position != SYSTEM_PINMUX_GPIO) { + pin_cfg |= PORT_WRCONFIG_PMUXEN; + pin_cfg |= (config->mux_position << PORT_WRCONFIG_PMUX_Pos); + } + + /* Check if the user has requested that the input buffer be enabled */ + if ((config->direction == SYSTEM_PINMUX_PIN_DIR_INPUT) || + (config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK)) { + /* Enable input buffer flag */ + pin_cfg |= PORT_WRCONFIG_INEN; + + /* Enable pull-up/pull-down control flag if requested */ + if (config->input_pull != SYSTEM_PINMUX_PIN_PULL_NONE) { + pin_cfg |= PORT_WRCONFIG_PULLEN; + } + + /* Clear the port DIR bits to disable the output buffer */ + port->DIRCLR.reg = pin_mask; + } + + /* Check if the user has requested that the output buffer be enabled */ + if ((config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT) || + (config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK)) { + /* Cannot use a pull-up if the output driver is enabled, + * if requested the input buffer can only sample the current + * output state */ + pin_cfg &= ~PORT_WRCONFIG_PULLEN; + } + } else { + port->DIRCLR.reg = pin_mask; + } + + /* The Write Configuration register (WRCONFIG) requires the + * pins to to grouped into two 16-bit half-words - split them out here */ + uint32_t lower_pin_mask = (pin_mask & 0xFFFF); + uint32_t upper_pin_mask = (pin_mask >> 16); + + /* Configure the lower 16-bits of the port to the desired configuration, + * including the pin peripheral multiplexer just in case it is enabled */ + port->WRCONFIG.reg + = (lower_pin_mask << PORT_WRCONFIG_PINMASK_Pos) | + pin_cfg | PORT_WRCONFIG_WRPMUX | PORT_WRCONFIG_WRPINCFG; + + /* Configure the upper 16-bits of the port to the desired configuration, + * including the pin peripheral multiplexer just in case it is enabled */ + port->WRCONFIG.reg + = (upper_pin_mask << PORT_WRCONFIG_PINMASK_Pos) | + pin_cfg | PORT_WRCONFIG_WRPMUX | PORT_WRCONFIG_WRPINCFG | + PORT_WRCONFIG_HWSEL; + + if(!config->powersave) { + /* Set the pull-up state once the port pins are configured if one was + * requested and it does not violate the valid set of port + * configurations */ + if (pin_cfg & PORT_WRCONFIG_PULLEN) { + /* Set the OUT register bits to enable the pull-up if requested, + * clear to enable pull-down */ + if (config->input_pull == SYSTEM_PINMUX_PIN_PULL_UP) { + port->OUTSET.reg = pin_mask; + } else { + port->OUTCLR.reg = pin_mask; + } + } + + /* Check if the user has requested that the output buffer be enabled */ + if ((config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT) || + (config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK)) { + /* Set the port DIR bits to enable the output buffer */ + port->DIRSET.reg = pin_mask; + } + } +} + +/** + * \brief Writes a Port pin configuration to the hardware module. + * + * Writes out a given configuration of a Port pin configuration to the hardware + * module. + * + * \note If the pin direction is set as an output, the pull-up/pull-down input + * configuration setting is ignored. + * + * \param[in] gpio_pin Index of the GPIO pin to configure + * \param[in] config Configuration settings for the pin + */ +void system_pinmux_pin_set_config( + const uint8_t gpio_pin, + const struct system_pinmux_config *const config) +{ + PortGroup *const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); + uint32_t pin_mask = (1UL << (gpio_pin % 32)); + + _system_pinmux_config(port, pin_mask, config); +} + +/** + * \brief Writes a Port pin group configuration to the hardware module. + * + * Writes out a given configuration of a Port pin group configuration to the + * hardware module. + * + * \note If the pin direction is set as an output, the pull-up/pull-down input + * configuration setting is ignored. + * + * \param[in] port Base of the PORT module to configure + * \param[in] mask Mask of the port pin(s) to configure + * \param[in] config Configuration settings for the pin + */ +void system_pinmux_group_set_config( + PortGroup *const port, + const uint32_t mask, + const struct system_pinmux_config *const config) +{ + Assert(port); + + for (int i = 0; i < 32; i++) { + if (mask & (1UL << i)) { + _system_pinmux_config(port, (1UL << i), config); + } + } +} + +/** + * \brief Configures the input sampling mode for a group of pins. + * + * Configures the input sampling mode for a group of pins, to + * control when the physical I/O pin value is sampled and + * stored inside the microcontroller. + * + * \param[in] port Base of the PORT module to configure + * \param[in] mask Mask of the port pin(s) to configure + * \param[in] mode New pin sampling mode to configure + */ +void system_pinmux_group_set_input_sample_mode( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_sample mode) +{ + Assert(port); + + if (mode == SYSTEM_PINMUX_PIN_SAMPLE_ONDEMAND) { + port->CTRL.reg |= mask; + } else { + port->CTRL.reg &= ~mask; + } +} + +#ifdef FEATURE_SYSTEM_PINMUX_SLEWRATE_LIMITER +/** + * \brief Configures the output slew rate mode for a group of pins. + * + * Configures the output slew rate mode for a group of pins, to + * control the speed at which the physical output pin can react to + * logical changes of the I/O pin value. + * + * \param[in] port Base of the PORT module to configure + * \param[in] mask Mask of the port pin(s) to configure + * \param[in] mode New pin slew rate mode to configure + */ +void system_pinmux_group_set_output_slew_rate( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_slew_rate mode) +{ + Assert(port); + + for (int i = 0; i < 32; i++) { + if (mask & (1UL << i)) { + if (mode == SYSTEM_PINMUX_PIN_SLEW_RATE_LIMITED) { + port->PINCFG[i].reg |= PORT_PINCFG_SLEWLIM; + } else { + port->PINCFG[i].reg &= ~PORT_PINCFG_SLEWLIM; + } + } + } +} +#endif + +#ifdef FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTH +/** + * \brief Configures the output driver strength mode for a group of pins. + * + * Configures the output drive strength for a group of pins, to + * control the amount of current the pad is able to sink/source. + * + * \param[in] port Base of the PORT module to configure + * \param[in] mask Mask of the port pin(s) to configure + * \param[in] mode New output driver strength mode to configure + */ +void system_pinmux_group_set_output_strength( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_strength mode) +{ + Assert(port); + + for (int i = 0; i < 32; i++) { + if (mask & (1UL << i)) { + if (mode == SYSTEM_PINMUX_PIN_STRENGTH_HIGH) { + port->PINCFG[i].reg |= PORT_PINCFG_DRVSTR; + } else { + port->PINCFG[i].reg &= ~PORT_PINCFG_DRVSTR; + } + } + } +} +#endif + +#ifdef FEATURE_SYSTEM_PINMUX_OPEN_DRAIN +/** + * \brief Configures the output driver mode for a group of pins. + * + * Configures the output driver mode for a group of pins, to + * control the pad behavior. + * + * \param[in] port Base of the PORT module to configure + * \param[in] mask Mask of the port pin(s) to configure + * \param[in] mode New pad output driver mode to configure + */ +void system_pinmux_group_set_output_drive( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_drive mode) +{ + Assert(port); + + for (int i = 0; i < 32; i++) { + if (mask & (1UL << i)) { + if (mode == SYSTEM_PINMUX_PIN_DRIVE_OPEN_DRAIN) { + port->PINCFG[i].reg |= PORT_PINCFG_ODRAIN; + } else { + port->PINCFG[i].reg &= ~PORT_PINCFG_ODRAIN; + } + } + } +} +#endif diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/pinmux.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/pinmux.h new file mode 100644 index 0000000..7a441cc --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/pinmux.h @@ -0,0 +1,678 @@ +/** + * \file + * + * \brief SAM Pin Multiplexer Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef PINMUX_H_INCLUDED +#define PINMUX_H_INCLUDED + +/** + * \defgroup asfdoc_sam0_system_pinmux_group SAM System Pin Multiplexer (SYSTEM PINMUX) Driver + * + * This driver for Atmel® | SMART ARM®-based microcontrollers provides + * an interface for the configuration and management of the device's physical + * I/O Pins, to alter the direction and input/drive characteristics as well as + * to configure the pin peripheral multiplexer selection. + * + * The following peripheral is used by this module: + * - PORT (Port I/O Management) + * + * The following devices can use this module: + * - Atmel | SMART SAM D20/D21 + * - Atmel | SMART SAM R21 + * - Atmel | SMART SAM D09/D10/D11 + * - Atmel | SMART SAM L21/L22 + * - Atmel | SMART SAM DA1 + * - Atmel | SMART SAM C20/C21 + * + * Physically, the modules are interconnected within the device as shown in the + * following diagram: + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_system_pinmux_prerequisites + * - \ref asfdoc_sam0_system_pinmux_module_overview + * - \ref asfdoc_sam0_system_pinmux_special_considerations + * - \ref asfdoc_sam0_system_pinmux_extra_info + * - \ref asfdoc_sam0_system_pinmux_examples + * - \ref asfdoc_sam0_system_pinmux_api_overview + * + * + * \section asfdoc_sam0_system_pinmux_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * + * \section asfdoc_sam0_system_pinmux_module_overview Module Overview + * + * The SAM devices contain a number of General Purpose I/O pins, used to + * interface the user application logic and internal hardware peripherals to + * an external system. The Pin Multiplexer (PINMUX) driver provides a method + * of configuring the individual pin peripheral multiplexers to select + * alternate pin functions. + * + * \subsection asfdoc_sam0_system_pinmux_features Driver Feature Macro Definition + * + * + * + * + * + * + * + * + * + *
Driver Feature MacroSupported devices
FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTHSAM L21, SAM C20/C21
+ * \note The specific features are only available in the driver when the + * selected device supports those features. + * + * \subsection asfdoc_sam0_system_pinmux_physical_logical_pins Physical and Logical GPIO Pins + * SAM devices use two naming conventions for the I/O pins in the device; one + * physical and one logical. Each physical pin on a device package is assigned + * both a physical port and pin identifier (e.g. "PORTA.0") as well as a + * monotonically incrementing logical GPIO number (e.g. "GPIO0"). While the + * former is used to map physical pins to their physical internal device module + * counterparts, for simplicity the design of this driver uses the logical GPIO + * numbers instead. + * + * \subsection asfdoc_sam0_system_pinmux_peripheral_muxing Peripheral Multiplexing + * SAM devices contain a peripheral MUX, which is individually controllable + * for each I/O pin of the device. The peripheral MUX allows you to select the + * function of a physical package pin - whether it will be controlled as a user + * controllable GPIO pin, or whether it will be connected internally to one of + * several peripheral modules (such as an I2C module). When a pin is + * configured in GPIO mode, other peripherals connected to the same pin will be + * disabled. + * + * \subsection asfdoc_sam0_system_pinmux_pad_characteristics Special Pad Characteristics + * There are several special modes that can be selected on one or more I/O pins + * of the device, which alter the input and output characteristics of the pad. + * + * \subsubsection asfdoc_sam0_system_pinmux_drive_strength Drive Strength + * The Drive Strength configures the strength of the output driver on the + * pad. Normally, there is a fixed current limit that each I/O pin can safely + * drive, however some I/O pads offer a higher drive mode which increases this + * limit for that I/O pin at the expense of an increased power consumption. + * + * \subsubsection asfdoc_sam0_system_pinmux_slew_rate Slew Rate + * The Slew Rate configures the slew rate of the output driver, limiting the + * rate at which the pad output voltage can change with time. + * + * \subsubsection asfdoc_sam0_system_pinmux_input_sample_mode Input Sample Mode + * The Input Sample Mode configures the input sampler buffer of the pad. By + * default, the input buffer is only sampled "on-demand", i.e. when the user + * application attempts to read from the input buffer. This mode is the most + * power efficient, but increases the latency of the input sample by two clock + * cycles of the port clock. To reduce latency, the input sampler can instead + * be configured to always sample the input buffer on each port clock cycle, at + * the expense of an increased power consumption. + * + * \subsection asfdoc_sam0_system_pinmux_module_overview_physical Physical Connection + * + * \ref asfdoc_sam0_system_pinmux_intconnections "The diagram below" shows + * how this module is interconnected within the device: + * + * \anchor asfdoc_sam0_system_pinmux_intconnections + * \dot + * digraph overview { + * node [label="Port Pad" shape=square] pad; + * + * subgraph driver { + * node [label="Peripheral MUX" shape=trapezium] pinmux; + * node [label="GPIO Module" shape=ellipse shape=ellipse style=filled fillcolor=lightgray] gpio; + * node [label="Other Peripheral Modules" shape=ellipse style=filled fillcolor=lightgray] peripherals; + * } + * + * pinmux -> gpio; + * pad -> pinmux; + * pinmux -> peripherals; + * } + * \enddot + * + * \section asfdoc_sam0_system_pinmux_special_considerations Special Considerations + * + * The SAM port pin input sampling mode is set in groups of four physical + * pins; setting the sampling mode of any pin in a sub-group of eight I/O pins + * will configure the sampling mode of the entire sub-group. + * + * High Drive Strength output driver mode is not available on all device pins - + * refer to your device specific datasheet. + * + * + * \section asfdoc_sam0_system_pinmux_extra_info Extra Information + * + * For extra information, see \ref asfdoc_sam0_system_pinmux_extra. This includes: + * - \ref asfdoc_sam0_system_pinmux_extra_acronyms + * - \ref asfdoc_sam0_system_pinmux_extra_dependencies + * - \ref asfdoc_sam0_system_pinmux_extra_errata + * - \ref asfdoc_sam0_system_pinmux_extra_history + * + * + * \section asfdoc_sam0_system_pinmux_examples Examples + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_system_pinmux_exqsg. + * + * + * \section asfdoc_sam0_system_pinmux_api_overview API Overview + * @{ + */ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/*@{*/ +#if (SAML21) || (SAMC20) || (SAMC21) || defined(__DOXYGEN__) +/** Output Driver Strength Selection feature support */ +# define FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTH +#endif +/*@}*/ + +/** Peripheral multiplexer index to select GPIO mode for a pin */ +#define SYSTEM_PINMUX_GPIO (1 << 7) + +/** + * \brief Port pin direction configuration enum. + * + * Enum for the possible pin direction settings of the port pin configuration + * structure, to indicate the direction the pin should use. + */ +enum system_pinmux_pin_dir { + /** The pin's input buffer should be enabled, so that the pin state can + * be read */ + SYSTEM_PINMUX_PIN_DIR_INPUT, + /** The pin's output buffer should be enabled, so that the pin state can + * be set (but not read back) */ + SYSTEM_PINMUX_PIN_DIR_OUTPUT, + /** The pin's output and input buffers should both be enabled, so that the + * pin state can be set and read back */ + SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK, +}; + +/** + * \brief Port pin input pull configuration enum. + * + * Enum for the possible pin pull settings of the port pin configuration + * structure, to indicate the type of logic level pull the pin should use. + */ +enum system_pinmux_pin_pull { + /** No logical pull should be applied to the pin */ + SYSTEM_PINMUX_PIN_PULL_NONE, + /** Pin should be pulled up when idle */ + SYSTEM_PINMUX_PIN_PULL_UP, + /** Pin should be pulled down when idle */ + SYSTEM_PINMUX_PIN_PULL_DOWN, +}; + +/** + * \brief Port pin digital input sampling mode enum. + * + * Enum for the possible input sampling modes for the port pin configuration + * structure, to indicate the type of sampling a port pin should use. + */ +enum system_pinmux_pin_sample { + /** Pin input buffer should continuously sample the pin state */ + SYSTEM_PINMUX_PIN_SAMPLE_CONTINUOUS, + /** Pin input buffer should be enabled when the IN register is read */ + SYSTEM_PINMUX_PIN_SAMPLE_ONDEMAND, +}; + +/** + * \brief Port pin configuration structure. + * + * Configuration structure for a port pin instance. This structure should + * be initialized by the \ref system_pinmux_get_config_defaults() function + * before being modified by the user application. + */ +struct system_pinmux_config { + /** MUX index of the peripheral that should control the pin, if peripheral + * control is desired. For GPIO use, this should be set to + * \ref SYSTEM_PINMUX_GPIO. */ + uint8_t mux_position; + + /** Port buffer input/output direction */ + enum system_pinmux_pin_dir direction; + + /** Logic level pull of the input buffer */ + enum system_pinmux_pin_pull input_pull; + + /** Enable lowest possible powerstate on the pin. + * + * \note All other configurations will be ignored, the pin will be disabled. + */ + bool powersave; +}; + +/** \name Configuration and Initialization + * @{ + */ + +/** + * \brief Initializes a Port pin configuration structure to defaults. + * + * Initializes a given Port pin configuration structure to a set of + * known default values. This function should be called on all new + * instances of these configuration structures before being modified by the + * user application. + * + * The default configuration is as follows: + * \li Non peripheral (i.e. GPIO) controlled + * \li Input mode with internal pull-up enabled + * + * \param[out] config Configuration structure to initialize to default values + */ +static inline void system_pinmux_get_config_defaults( + struct system_pinmux_config *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Default configuration values */ + config->mux_position = SYSTEM_PINMUX_GPIO; + config->direction = SYSTEM_PINMUX_PIN_DIR_INPUT; + config->input_pull = SYSTEM_PINMUX_PIN_PULL_UP; + config->powersave = false; +} + +void system_pinmux_pin_set_config( + const uint8_t gpio_pin, + const struct system_pinmux_config *const config); + +void system_pinmux_group_set_config( + PortGroup *const port, + const uint32_t mask, + const struct system_pinmux_config *const config); + +/** @} */ + +/** \name Special Mode Configuration (Physical Group Orientated) + * @{ + */ + +/** + * \brief Retrieves the PORT module group instance from a given GPIO pin number. + * + * Retrieves the PORT module group instance associated with a given logical + * GPIO pin number. + * + * \param[in] gpio_pin Index of the GPIO pin to convert + * + * \return Base address of the associated PORT module. + */ +static inline PortGroup* system_pinmux_get_group_from_gpio_pin( + const uint8_t gpio_pin) +{ + uint8_t port_index = (gpio_pin / 128); + uint8_t group_index = (gpio_pin / 32); + + /* Array of available ports */ + Port *const ports[PORT_INST_NUM] = PORT_INSTS; + + if (port_index < PORT_INST_NUM) { + return &(ports[port_index]->Group[group_index]); + } else { + Assert(false); + return NULL; + } +} + +void system_pinmux_group_set_input_sample_mode( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_sample mode); + +/** @} */ + +/** \name Special Mode Configuration (Logical Pin Orientated) + * @{ + */ + +/** + * \brief Retrieves the currently selected MUX position of a logical pin. + * + * Retrieves the selected MUX peripheral on a given logical GPIO pin. + * + * \param[in] gpio_pin Index of the GPIO pin to configure + * + * \return Currently selected peripheral index on the specified pin. + */ +static inline uint8_t system_pinmux_pin_get_mux_position( + const uint8_t gpio_pin) +{ + PortGroup *const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); + uint32_t pin_index = (gpio_pin % 32); + + if (!(port->PINCFG[pin_index].reg & PORT_PINCFG_PMUXEN)) { + return SYSTEM_PINMUX_GPIO; + } + + uint32_t pmux_reg = port->PMUX[pin_index / 2].reg; + + if (pin_index & 1) { + return (pmux_reg & PORT_PMUX_PMUXO_Msk) >> PORT_PMUX_PMUXO_Pos; + } + else { + return (pmux_reg & PORT_PMUX_PMUXE_Msk) >> PORT_PMUX_PMUXE_Pos; + } +} + +/** + * \brief Configures the input sampling mode for a GPIO pin. + * + * Configures the input sampling mode for a GPIO input, to + * control when the physical I/O pin value is sampled and + * stored inside the microcontroller. + * + * \param[in] gpio_pin Index of the GPIO pin to configure + * \param[in] mode New pin sampling mode to configure + */ +static inline void system_pinmux_pin_set_input_sample_mode( + const uint8_t gpio_pin, + const enum system_pinmux_pin_sample mode) +{ + PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); + uint32_t pin_index = (gpio_pin % 32); + + if (mode == SYSTEM_PINMUX_PIN_SAMPLE_ONDEMAND) { + port->CTRL.reg |= (1 << pin_index); + } else { + port->CTRL.reg &= ~(1 << pin_index); + } +} + +/** @} */ + +#ifdef FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTH +/** + * \brief Port pin drive output strength enum. + * + * Enum for the possible output drive strengths for the port pin + * configuration structure, to indicate the driver strength the pin should + * use. + */ +enum system_pinmux_pin_strength { + /** Normal output driver strength */ + SYSTEM_PINMUX_PIN_STRENGTH_NORMAL, + /** High current output driver strength */ + SYSTEM_PINMUX_PIN_STRENGTH_HIGH, +}; + +/** + * \brief Configures the output driver strength mode for a GPIO pin. + * + * Configures the output drive strength for a GPIO output, to + * control the amount of current the pad is able to sink/source. + * + * \param[in] gpio_pin Index of the GPIO pin to configure + * \param[in] mode New output driver strength mode to configure + */ +static inline void system_pinmux_pin_set_output_strength( + const uint8_t gpio_pin, + const enum system_pinmux_pin_strength mode) +{ + PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); + uint32_t pin_index = (gpio_pin % 32); + + if (mode == SYSTEM_PINMUX_PIN_STRENGTH_HIGH) { + port->PINCFG[pin_index].reg |= PORT_PINCFG_DRVSTR; + } + else { + port->PINCFG[pin_index].reg &= ~PORT_PINCFG_DRVSTR; + } +} + +void system_pinmux_group_set_output_strength( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_strength mode); +#endif + +#ifdef FEATURE_SYSTEM_PINMUX_SLEWRATE_LIMITER +/** + * \brief Port pin output slew rate enum. + * + * Enum for the possible output drive slew rates for the port pin + * configuration structure, to indicate the driver slew rate the pin should + * use. + */ +enum system_pinmux_pin_slew_rate { + /** Normal pin output slew rate */ + SYSTEM_PINMUX_PIN_SLEW_RATE_NORMAL, + /** Enable slew rate limiter on the pin */ + SYSTEM_PINMUX_PIN_SLEW_RATE_LIMITED, +}; + +/** + * \brief Configures the output slew rate mode for a GPIO pin. + * + * Configures the output slew rate mode for a GPIO output, to + * control the speed at which the physical output pin can react to + * logical changes of the I/O pin value. + * + * \param[in] gpio_pin Index of the GPIO pin to configure + * \param[in] mode New pin slew rate mode to configure + */ +static inline void system_pinmux_pin_set_output_slew_rate( + const uint8_t gpio_pin, + const enum system_pinmux_pin_slew_rate mode) +{ + PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); + uint32_t pin_index = (gpio_pin % 32); + + if (mode == SYSTEM_PINMUX_PIN_SLEW_RATE_LIMITED) { + port->PINCFG[pin_index].reg |= PORT_PINCFG_SLEWLIM; + } + else { + port->PINCFG[pin_index].reg &= ~PORT_PINCFG_SLEWLIM; + } +} + +void system_pinmux_group_set_output_slew_rate( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_slew_rate mode); +#endif + +#ifdef FEATURE_SYSTEM_PINMUX_OPEN_DRAIN +/** + * \brief Port pin output drive mode enum. + * + * Enum for the possible output drive modes for the port pin configuration + * structure, to indicate the output mode the pin should use. + */ +enum system_pinmux_pin_drive { + /** Use totem pole output drive mode */ + SYSTEM_PINMUX_PIN_DRIVE_TOTEM, + /** Use open drain output drive mode */ + SYSTEM_PINMUX_PIN_DRIVE_OPEN_DRAIN, +}; + +/** + * \brief Configures the output driver mode for a GPIO pin. + * + * Configures the output driver mode for a GPIO output, to + * control the pad behavior. + * + * \param[in] gpio_pin Index of the GPIO pin to configure + * \param[in] mode New pad output driver mode to configure + */ +static inline void system_pinmux_pin_set_output_drive( + const uint8_t gpio_pin, + const enum system_pinmux_pin_drive mode) +{ + PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); + uint32_t pin_index = (gpio_pin % 32); + + if (mode == SYSTEM_PINMUX_PIN_DRIVE_OPEN_DRAIN) { + port->PINCFG[pin_index].reg |= PORT_PINCFG_ODRAIN; + } + else { + port->PINCFG[pin_index].reg &= ~PORT_PINCFG_ODRAIN; + } +} + +void system_pinmux_group_set_output_drive( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_drive mode); +#endif + +#ifdef __cplusplus +} +#endif + +/** @} */ + +/** + * \page asfdoc_sam0_system_pinmux_extra Extra Information for SYSTEM PINMUX Driver + * + * \section asfdoc_sam0_system_pinmux_extra_acronyms Acronyms + * The table below presents the acronyms used in this module: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
AcronymDescription
GPIOGeneral Purpose Input/Output
MUXMultiplexer
+ * + * + * \section asfdoc_sam0_system_pinmux_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - None + * + * + * \section asfdoc_sam0_system_pinmux_extra_errata Errata + * There are no errata related to this driver. + * + * + * \section asfdoc_sam0_system_pinmux_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Changelog
Removed code of open drain, slew limit and drive strength + * features
Fixed broken sampling mode function implementations, which wrote + * corrupt configuration values to the device registers
Added missing NULL pointer asserts to the PORT driver functions
Initial Release
+ */ + +/** + * \page asfdoc_sam0_system_pinmux_exqsg Examples for SYSTEM PINMUX Driver + * + * This is a list of the available Quick Start guides (QSGs) and example + * applications for \ref asfdoc_sam0_system_pinmux_group. QSGs are simple + * examples with step-by-step instructions to configure and use this driver in a + * selection of use cases. Note that a QSG can be compiled as a standalone + * application or be added to the user application. + * + * - \subpage asfdoc_sam0_system_pinmux_basic_use_case + * + * \page asfdoc_sam0_system_pinmux_document_revision_history Document Revision History + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Doc. Rev. + * Date + * Comments + *
42121F08/2015Added support for SAM L21/L22, SAM DA1, and SAM C20/C21
42121E12/2014Added support for SAM R21 and SAM D10/D11
42121D01/2014Added support for SAM D21
42121C09/2013Fixed incorrect documentation for the device pin sampling mode
42121B06/2013Corrected documentation typos
42121A06/2013Initial release
+ */ + +#endif diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/power.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/power.h new file mode 100644 index 0000000..5e90585 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/power.h @@ -0,0 +1,224 @@ +/** + * \file + * + * \brief SAM Power related functionality + * + * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef POWER_H_INCLUDED +#define POWER_H_INCLUDED + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \addtogroup asfdoc_sam0_system_group + * @{ + */ + +/** + * \brief Voltage references within the device. + * + * List of available voltage references (VREF) that may be used within the + * device. + */ +enum system_voltage_reference { + /** Temperature sensor voltage reference. */ + SYSTEM_VOLTAGE_REFERENCE_TEMPSENSE, + /** Bandgap voltage reference. */ + SYSTEM_VOLTAGE_REFERENCE_BANDGAP, +}; + +/** + * \brief Device sleep modes. + * + * List of available sleep modes in the device. A table of clocks available in + * different sleep modes can be found in \ref asfdoc_sam0_system_module_overview_sleep_mode. + */ +enum system_sleepmode { + /** IDLE 0 sleep mode. */ + SYSTEM_SLEEPMODE_IDLE_0, + /** IDLE 1 sleep mode. */ + SYSTEM_SLEEPMODE_IDLE_1, + /** IDLE 2 sleep mode. */ + SYSTEM_SLEEPMODE_IDLE_2, + /** Standby sleep mode. */ + SYSTEM_SLEEPMODE_STANDBY, +}; + + + +/** + * \name Voltage References + * @{ + */ + +/** + * \brief Enable the selected voltage reference + * + * Enables the selected voltage reference source, making the voltage reference + * available on a pin as well as an input source to the analog peripherals. + * + * \param[in] vref Voltage reference to enable + */ +static inline void system_voltage_reference_enable( + const enum system_voltage_reference vref) +{ + switch (vref) { + case SYSTEM_VOLTAGE_REFERENCE_TEMPSENSE: + SYSCTRL->VREF.reg |= SYSCTRL_VREF_TSEN; + break; + + case SYSTEM_VOLTAGE_REFERENCE_BANDGAP: + SYSCTRL->VREF.reg |= SYSCTRL_VREF_BGOUTEN; + break; + + default: + Assert(false); + return; + } +} + +/** + * \brief Disable the selected voltage reference + * + * Disables the selected voltage reference source. + * + * \param[in] vref Voltage reference to disable + */ +static inline void system_voltage_reference_disable( + const enum system_voltage_reference vref) +{ + switch (vref) { + case SYSTEM_VOLTAGE_REFERENCE_TEMPSENSE: + SYSCTRL->VREF.reg &= ~SYSCTRL_VREF_TSEN; + break; + + case SYSTEM_VOLTAGE_REFERENCE_BANDGAP: + SYSCTRL->VREF.reg &= ~SYSCTRL_VREF_BGOUTEN; + break; + + default: + Assert(false); + return; + } +} + +/** + * @} + */ + + +/** + * \name Device Sleep Control + * @{ + */ + +/** + * \brief Set the sleep mode of the device + * + * Sets the sleep mode of the device; the configured sleep mode will be entered + * upon the next call of the \ref system_sleep() function. + * + * For an overview of which systems are disabled in sleep for the different + * sleep modes, see \ref asfdoc_sam0_system_module_overview_sleep_mode. + * + * \param[in] sleep_mode Sleep mode to configure for the next sleep operation + * + * \retval STATUS_OK Operation completed successfully + * \retval STATUS_ERR_INVALID_ARG The requested sleep mode was invalid or not + * available + */ +static inline enum status_code system_set_sleepmode( + const enum system_sleepmode sleep_mode) +{ +#if (SAMD20 || SAMD21) + /* Errata: Make sure that the Flash does not power all the way down + * when in sleep mode. */ + NVMCTRL->CTRLB.bit.SLEEPPRM = NVMCTRL_CTRLB_SLEEPPRM_DISABLED_Val; +#endif + + switch (sleep_mode) { + case SYSTEM_SLEEPMODE_IDLE_0: + case SYSTEM_SLEEPMODE_IDLE_1: + case SYSTEM_SLEEPMODE_IDLE_2: + SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk; + PM->SLEEP.reg = sleep_mode; + break; + + case SYSTEM_SLEEPMODE_STANDBY: + SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; + break; + + default: + return STATUS_ERR_INVALID_ARG; + } + + return STATUS_OK; +} + +/** + * \brief Put the system to sleep waiting for interrupt + * + * Executes a device DSB (Data Synchronization Barrier) instruction to ensure + * all ongoing memory accesses have completed, then a WFI (Wait For Interrupt) + * instruction to place the device into the sleep mode specified by + * \ref system_set_sleepmode until woken by an interrupt. + */ +static inline void system_sleep(void) +{ + __DSB(); + __WFI(); +} + +/** + * @} + */ + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* POWER_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h new file mode 100644 index 0000000..4447927 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h @@ -0,0 +1,581 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef _MRECURSION_H_ +#define _MRECURSION_H_ + +/** + * \defgroup group_sam0_utils_mrecursion Preprocessor - Macro Recursion + * + * \ingroup group_sam0_utils + * + * @{ + */ + +#include "preprocessor.h" + +#define DEC_256 255 +#define DEC_255 254 +#define DEC_254 253 +#define DEC_253 252 +#define DEC_252 251 +#define DEC_251 250 +#define DEC_250 249 +#define DEC_249 248 +#define DEC_248 247 +#define DEC_247 246 +#define DEC_246 245 +#define DEC_245 244 +#define DEC_244 243 +#define DEC_243 242 +#define DEC_242 241 +#define DEC_241 240 +#define DEC_240 239 +#define DEC_239 238 +#define DEC_238 237 +#define DEC_237 236 +#define DEC_236 235 +#define DEC_235 234 +#define DEC_234 233 +#define DEC_233 232 +#define DEC_232 231 +#define DEC_231 230 +#define DEC_230 229 +#define DEC_229 228 +#define DEC_228 227 +#define DEC_227 226 +#define DEC_226 225 +#define DEC_225 224 +#define DEC_224 223 +#define DEC_223 222 +#define DEC_222 221 +#define DEC_221 220 +#define DEC_220 219 +#define DEC_219 218 +#define DEC_218 217 +#define DEC_217 216 +#define DEC_216 215 +#define DEC_215 214 +#define DEC_214 213 +#define DEC_213 212 +#define DEC_212 211 +#define DEC_211 210 +#define DEC_210 209 +#define DEC_209 208 +#define DEC_208 207 +#define DEC_207 206 +#define DEC_206 205 +#define DEC_205 204 +#define DEC_204 203 +#define DEC_203 202 +#define DEC_202 201 +#define DEC_201 200 +#define DEC_200 199 +#define DEC_199 198 +#define DEC_198 197 +#define DEC_197 196 +#define DEC_196 195 +#define DEC_195 194 +#define DEC_194 193 +#define DEC_193 192 +#define DEC_192 191 +#define DEC_191 190 +#define DEC_190 189 +#define DEC_189 188 +#define DEC_188 187 +#define DEC_187 186 +#define DEC_186 185 +#define DEC_185 184 +#define DEC_184 183 +#define DEC_183 182 +#define DEC_182 181 +#define DEC_181 180 +#define DEC_180 179 +#define DEC_179 178 +#define DEC_178 177 +#define DEC_177 176 +#define DEC_176 175 +#define DEC_175 174 +#define DEC_174 173 +#define DEC_173 172 +#define DEC_172 171 +#define DEC_171 170 +#define DEC_170 169 +#define DEC_169 168 +#define DEC_168 167 +#define DEC_167 166 +#define DEC_166 165 +#define DEC_165 164 +#define DEC_164 163 +#define DEC_163 162 +#define DEC_162 161 +#define DEC_161 160 +#define DEC_160 159 +#define DEC_159 158 +#define DEC_158 157 +#define DEC_157 156 +#define DEC_156 155 +#define DEC_155 154 +#define DEC_154 153 +#define DEC_153 152 +#define DEC_152 151 +#define DEC_151 150 +#define DEC_150 149 +#define DEC_149 148 +#define DEC_148 147 +#define DEC_147 146 +#define DEC_146 145 +#define DEC_145 144 +#define DEC_144 143 +#define DEC_143 142 +#define DEC_142 141 +#define DEC_141 140 +#define DEC_140 139 +#define DEC_139 138 +#define DEC_138 137 +#define DEC_137 136 +#define DEC_136 135 +#define DEC_135 134 +#define DEC_134 133 +#define DEC_133 132 +#define DEC_132 131 +#define DEC_131 130 +#define DEC_130 129 +#define DEC_129 128 +#define DEC_128 127 +#define DEC_127 126 +#define DEC_126 125 +#define DEC_125 124 +#define DEC_124 123 +#define DEC_123 122 +#define DEC_122 121 +#define DEC_121 120 +#define DEC_120 119 +#define DEC_119 118 +#define DEC_118 117 +#define DEC_117 116 +#define DEC_116 115 +#define DEC_115 114 +#define DEC_114 113 +#define DEC_113 112 +#define DEC_112 111 +#define DEC_111 110 +#define DEC_110 109 +#define DEC_109 108 +#define DEC_108 107 +#define DEC_107 106 +#define DEC_106 105 +#define DEC_105 104 +#define DEC_104 103 +#define DEC_103 102 +#define DEC_102 101 +#define DEC_101 100 +#define DEC_100 99 +#define DEC_99 98 +#define DEC_98 97 +#define DEC_97 96 +#define DEC_96 95 +#define DEC_95 94 +#define DEC_94 93 +#define DEC_93 92 +#define DEC_92 91 +#define DEC_91 90 +#define DEC_90 89 +#define DEC_89 88 +#define DEC_88 87 +#define DEC_87 86 +#define DEC_86 85 +#define DEC_85 84 +#define DEC_84 83 +#define DEC_83 82 +#define DEC_82 81 +#define DEC_81 80 +#define DEC_80 79 +#define DEC_79 78 +#define DEC_78 77 +#define DEC_77 76 +#define DEC_76 75 +#define DEC_75 74 +#define DEC_74 73 +#define DEC_73 72 +#define DEC_72 71 +#define DEC_71 70 +#define DEC_70 69 +#define DEC_69 68 +#define DEC_68 67 +#define DEC_67 66 +#define DEC_66 65 +#define DEC_65 64 +#define DEC_64 63 +#define DEC_63 62 +#define DEC_62 61 +#define DEC_61 60 +#define DEC_60 59 +#define DEC_59 58 +#define DEC_58 57 +#define DEC_57 56 +#define DEC_56 55 +#define DEC_55 54 +#define DEC_54 53 +#define DEC_53 52 +#define DEC_52 51 +#define DEC_51 50 +#define DEC_50 49 +#define DEC_49 48 +#define DEC_48 47 +#define DEC_47 46 +#define DEC_46 45 +#define DEC_45 44 +#define DEC_44 43 +#define DEC_43 42 +#define DEC_42 41 +#define DEC_41 40 +#define DEC_40 39 +#define DEC_39 38 +#define DEC_38 37 +#define DEC_37 36 +#define DEC_36 35 +#define DEC_35 34 +#define DEC_34 33 +#define DEC_33 32 +#define DEC_32 31 +#define DEC_31 30 +#define DEC_30 29 +#define DEC_29 28 +#define DEC_28 27 +#define DEC_27 26 +#define DEC_26 25 +#define DEC_25 24 +#define DEC_24 23 +#define DEC_23 22 +#define DEC_22 21 +#define DEC_21 20 +#define DEC_20 19 +#define DEC_19 18 +#define DEC_18 17 +#define DEC_17 16 +#define DEC_16 15 +#define DEC_15 14 +#define DEC_14 13 +#define DEC_13 12 +#define DEC_12 11 +#define DEC_11 10 +#define DEC_10 9 +#define DEC_9 8 +#define DEC_8 7 +#define DEC_7 6 +#define DEC_6 5 +#define DEC_5 4 +#define DEC_4 3 +#define DEC_3 2 +#define DEC_2 1 +#define DEC_1 0 +#define DEC_(n) DEC_##n + + +/** Maximal number of repetitions supported by MRECURSION. */ +#define MRECURSION_LIMIT 256 + +/** \brief Macro recursion. + * + * This macro represents a horizontal repetition construct. + * + * \param[in] count The number of repetitious calls to macro. Valid values + * range from 0 to MRECURSION_LIMIT. + * \param[in] macro A binary operation of the form macro(data, n). This macro + * is expanded by MRECURSION with the current repetition number + * and the auxiliary data argument. + * \param[in] data A recursive threshold, building on this to decline by times + * defined with param count. + * + * \return macro(data-count+1,0) macro(data-count+2,1)...macro(data,count-1) + */ +#define MRECURSION(count, macro, data) TPASTE2(MRECURSION, count) (macro, data) + +#define MRECURSION0( macro, data) +#define MRECURSION1( macro, data) MRECURSION0( macro, DEC_(data)) macro(data, 0) +#define MRECURSION2( macro, data) MRECURSION1( macro, DEC_(data)) macro(data, 1) +#define MRECURSION3( macro, data) MRECURSION2( macro, DEC_(data)) macro(data, 2) +#define MRECURSION4( macro, data) MRECURSION3( macro, DEC_(data)) macro(data, 3) +#define MRECURSION5( macro, data) MRECURSION4( macro, DEC_(data)) macro(data, 4) +#define MRECURSION6( macro, data) MRECURSION5( macro, DEC_(data)) macro(data, 5) +#define MRECURSION7( macro, data) MRECURSION6( macro, DEC_(data)) macro(data, 6) +#define MRECURSION8( macro, data) MRECURSION7( macro, DEC_(data)) macro(data, 7) +#define MRECURSION9( macro, data) MRECURSION8( macro, DEC_(data)) macro(data, 8) +#define MRECURSION10( macro, data) MRECURSION9( macro, DEC_(data)) macro(data, 9) +#define MRECURSION11( macro, data) MRECURSION10( macro, DEC_(data)) macro(data, 10) +#define MRECURSION12( macro, data) MRECURSION11( macro, DEC_(data)) macro(data, 11) +#define MRECURSION13( macro, data) MRECURSION12( macro, DEC_(data)) macro(data, 12) +#define MRECURSION14( macro, data) MRECURSION13( macro, DEC_(data)) macro(data, 13) +#define MRECURSION15( macro, data) MRECURSION14( macro, DEC_(data)) macro(data, 14) +#define MRECURSION16( macro, data) MRECURSION15( macro, DEC_(data)) macro(data, 15) +#define MRECURSION17( macro, data) MRECURSION16( macro, DEC_(data)) macro(data, 16) +#define MRECURSION18( macro, data) MRECURSION17( macro, DEC_(data)) macro(data, 17) +#define MRECURSION19( macro, data) MRECURSION18( macro, DEC_(data)) macro(data, 18) +#define MRECURSION20( macro, data) MRECURSION19( macro, DEC_(data)) macro(data, 19) +#define MRECURSION21( macro, data) MRECURSION20( macro, DEC_(data)) macro(data, 20) +#define MRECURSION22( macro, data) MRECURSION21( macro, DEC_(data)) macro(data, 21) +#define MRECURSION23( macro, data) MRECURSION22( macro, DEC_(data)) macro(data, 22) +#define MRECURSION24( macro, data) MRECURSION23( macro, DEC_(data)) macro(data, 23) +#define MRECURSION25( macro, data) MRECURSION24( macro, DEC_(data)) macro(data, 24) +#define MRECURSION26( macro, data) MRECURSION25( macro, DEC_(data)) macro(data, 25) +#define MRECURSION27( macro, data) MRECURSION26( macro, DEC_(data)) macro(data, 26) +#define MRECURSION28( macro, data) MRECURSION27( macro, DEC_(data)) macro(data, 27) +#define MRECURSION29( macro, data) MRECURSION28( macro, DEC_(data)) macro(data, 28) +#define MRECURSION30( macro, data) MRECURSION29( macro, DEC_(data)) macro(data, 29) +#define MRECURSION31( macro, data) MRECURSION30( macro, DEC_(data)) macro(data, 30) +#define MRECURSION32( macro, data) MRECURSION31( macro, DEC_(data)) macro(data, 31) +#define MRECURSION33( macro, data) MRECURSION32( macro, DEC_(data)) macro(data, 32) +#define MRECURSION34( macro, data) MRECURSION33( macro, DEC_(data)) macro(data, 33) +#define MRECURSION35( macro, data) MRECURSION34( macro, DEC_(data)) macro(data, 34) +#define MRECURSION36( macro, data) MRECURSION35( macro, DEC_(data)) macro(data, 35) +#define MRECURSION37( macro, data) MRECURSION36( macro, DEC_(data)) macro(data, 36) +#define MRECURSION38( macro, data) MRECURSION37( macro, DEC_(data)) macro(data, 37) +#define MRECURSION39( macro, data) MRECURSION38( macro, DEC_(data)) macro(data, 38) +#define MRECURSION40( macro, data) MRECURSION39( macro, DEC_(data)) macro(data, 39) +#define MRECURSION41( macro, data) MRECURSION40( macro, DEC_(data)) macro(data, 40) +#define MRECURSION42( macro, data) MRECURSION41( macro, DEC_(data)) macro(data, 41) +#define MRECURSION43( macro, data) MRECURSION42( macro, DEC_(data)) macro(data, 42) +#define MRECURSION44( macro, data) MRECURSION43( macro, DEC_(data)) macro(data, 43) +#define MRECURSION45( macro, data) MRECURSION44( macro, DEC_(data)) macro(data, 44) +#define MRECURSION46( macro, data) MRECURSION45( macro, DEC_(data)) macro(data, 45) +#define MRECURSION47( macro, data) MRECURSION46( macro, DEC_(data)) macro(data, 46) +#define MRECURSION48( macro, data) MRECURSION47( macro, DEC_(data)) macro(data, 47) +#define MRECURSION49( macro, data) MRECURSION48( macro, DEC_(data)) macro(data, 48) +#define MRECURSION50( macro, data) MRECURSION49( macro, DEC_(data)) macro(data, 49) +#define MRECURSION51( macro, data) MRECURSION50( macro, DEC_(data)) macro(data, 50) +#define MRECURSION52( macro, data) MRECURSION51( macro, DEC_(data)) macro(data, 51) +#define MRECURSION53( macro, data) MRECURSION52( macro, DEC_(data)) macro(data, 52) +#define MRECURSION54( macro, data) MRECURSION53( macro, DEC_(data)) macro(data, 53) +#define MRECURSION55( macro, data) MRECURSION54( macro, DEC_(data)) macro(data, 54) +#define MRECURSION56( macro, data) MRECURSION55( macro, DEC_(data)) macro(data, 55) +#define MRECURSION57( macro, data) MRECURSION56( macro, DEC_(data)) macro(data, 56) +#define MRECURSION58( macro, data) MRECURSION57( macro, DEC_(data)) macro(data, 57) +#define MRECURSION59( macro, data) MRECURSION58( macro, DEC_(data)) macro(data, 58) +#define MRECURSION60( macro, data) MRECURSION59( macro, DEC_(data)) macro(data, 59) +#define MRECURSION61( macro, data) MRECURSION60( macro, DEC_(data)) macro(data, 60) +#define MRECURSION62( macro, data) MRECURSION61( macro, DEC_(data)) macro(data, 61) +#define MRECURSION63( macro, data) MRECURSION62( macro, DEC_(data)) macro(data, 62) +#define MRECURSION64( macro, data) MRECURSION63( macro, DEC_(data)) macro(data, 63) +#define MRECURSION65( macro, data) MRECURSION64( macro, DEC_(data)) macro(data, 64) +#define MRECURSION66( macro, data) MRECURSION65( macro, DEC_(data)) macro(data, 65) +#define MRECURSION67( macro, data) MRECURSION66( macro, DEC_(data)) macro(data, 66) +#define MRECURSION68( macro, data) MRECURSION67( macro, DEC_(data)) macro(data, 67) +#define MRECURSION69( macro, data) MRECURSION68( macro, DEC_(data)) macro(data, 68) +#define MRECURSION70( macro, data) MRECURSION69( macro, DEC_(data)) macro(data, 69) +#define MRECURSION71( macro, data) MRECURSION70( macro, DEC_(data)) macro(data, 70) +#define MRECURSION72( macro, data) MRECURSION71( macro, DEC_(data)) macro(data, 71) +#define MRECURSION73( macro, data) MRECURSION72( macro, DEC_(data)) macro(data, 72) +#define MRECURSION74( macro, data) MRECURSION73( macro, DEC_(data)) macro(data, 73) +#define MRECURSION75( macro, data) MRECURSION74( macro, DEC_(data)) macro(data, 74) +#define MRECURSION76( macro, data) MRECURSION75( macro, DEC_(data)) macro(data, 75) +#define MRECURSION77( macro, data) MRECURSION76( macro, DEC_(data)) macro(data, 76) +#define MRECURSION78( macro, data) MRECURSION77( macro, DEC_(data)) macro(data, 77) +#define MRECURSION79( macro, data) MRECURSION78( macro, DEC_(data)) macro(data, 78) +#define MRECURSION80( macro, data) MRECURSION79( macro, DEC_(data)) macro(data, 79) +#define MRECURSION81( macro, data) MRECURSION80( macro, DEC_(data)) macro(data, 80) +#define MRECURSION82( macro, data) MRECURSION81( macro, DEC_(data)) macro(data, 81) +#define MRECURSION83( macro, data) MRECURSION82( macro, DEC_(data)) macro(data, 82) +#define MRECURSION84( macro, data) MRECURSION83( macro, DEC_(data)) macro(data, 83) +#define MRECURSION85( macro, data) MRECURSION84( macro, DEC_(data)) macro(data, 84) +#define MRECURSION86( macro, data) MRECURSION85( macro, DEC_(data)) macro(data, 85) +#define MRECURSION87( macro, data) MRECURSION86( macro, DEC_(data)) macro(data, 86) +#define MRECURSION88( macro, data) MRECURSION87( macro, DEC_(data)) macro(data, 87) +#define MRECURSION89( macro, data) MRECURSION88( macro, DEC_(data)) macro(data, 88) +#define MRECURSION90( macro, data) MRECURSION89( macro, DEC_(data)) macro(data, 89) +#define MRECURSION91( macro, data) MRECURSION90( macro, DEC_(data)) macro(data, 90) +#define MRECURSION92( macro, data) MRECURSION91( macro, DEC_(data)) macro(data, 91) +#define MRECURSION93( macro, data) MRECURSION92( macro, DEC_(data)) macro(data, 92) +#define MRECURSION94( macro, data) MRECURSION93( macro, DEC_(data)) macro(data, 93) +#define MRECURSION95( macro, data) MRECURSION94( macro, DEC_(data)) macro(data, 94) +#define MRECURSION96( macro, data) MRECURSION95( macro, DEC_(data)) macro(data, 95) +#define MRECURSION97( macro, data) MRECURSION96( macro, DEC_(data)) macro(data, 96) +#define MRECURSION98( macro, data) MRECURSION97( macro, DEC_(data)) macro(data, 97) +#define MRECURSION99( macro, data) MRECURSION98( macro, DEC_(data)) macro(data, 98) +#define MRECURSION100(macro, data) MRECURSION99( macro, DEC_(data)) macro(data, 99) +#define MRECURSION101(macro, data) MRECURSION100( macro, DEC_(data)) macro(data, 100) +#define MRECURSION102(macro, data) MRECURSION101( macro, DEC_(data)) macro(data, 101) +#define MRECURSION103(macro, data) MRECURSION102( macro, DEC_(data)) macro(data, 102) +#define MRECURSION104(macro, data) MRECURSION103( macro, DEC_(data)) macro(data, 103) +#define MRECURSION105(macro, data) MRECURSION104( macro, DEC_(data)) macro(data, 104) +#define MRECURSION106(macro, data) MRECURSION105( macro, DEC_(data)) macro(data, 105) +#define MRECURSION107(macro, data) MRECURSION106( macro, DEC_(data)) macro(data, 106) +#define MRECURSION108(macro, data) MRECURSION107( macro, DEC_(data)) macro(data, 107) +#define MRECURSION109(macro, data) MRECURSION108( macro, DEC_(data)) macro(data, 108) +#define MRECURSION110(macro, data) MRECURSION109( macro, DEC_(data)) macro(data, 109) +#define MRECURSION111(macro, data) MRECURSION110( macro, DEC_(data)) macro(data, 110) +#define MRECURSION112(macro, data) MRECURSION111( macro, DEC_(data)) macro(data, 111) +#define MRECURSION113(macro, data) MRECURSION112( macro, DEC_(data)) macro(data, 112) +#define MRECURSION114(macro, data) MRECURSION113( macro, DEC_(data)) macro(data, 113) +#define MRECURSION115(macro, data) MRECURSION114( macro, DEC_(data)) macro(data, 114) +#define MRECURSION116(macro, data) MRECURSION115( macro, DEC_(data)) macro(data, 115) +#define MRECURSION117(macro, data) MRECURSION116( macro, DEC_(data)) macro(data, 116) +#define MRECURSION118(macro, data) MRECURSION117( macro, DEC_(data)) macro(data, 117) +#define MRECURSION119(macro, data) MRECURSION118( macro, DEC_(data)) macro(data, 118) +#define MRECURSION120(macro, data) MRECURSION119( macro, DEC_(data)) macro(data, 119) +#define MRECURSION121(macro, data) MRECURSION120( macro, DEC_(data)) macro(data, 120) +#define MRECURSION122(macro, data) MRECURSION121( macro, DEC_(data)) macro(data, 121) +#define MRECURSION123(macro, data) MRECURSION122( macro, DEC_(data)) macro(data, 122) +#define MRECURSION124(macro, data) MRECURSION123( macro, DEC_(data)) macro(data, 123) +#define MRECURSION125(macro, data) MRECURSION124( macro, DEC_(data)) macro(data, 124) +#define MRECURSION126(macro, data) MRECURSION125( macro, DEC_(data)) macro(data, 125) +#define MRECURSION127(macro, data) MRECURSION126( macro, DEC_(data)) macro(data, 126) +#define MRECURSION128(macro, data) MRECURSION127( macro, DEC_(data)) macro(data, 127) +#define MRECURSION129(macro, data) MRECURSION128( macro, DEC_(data)) macro(data, 128) +#define MRECURSION130(macro, data) MRECURSION129( macro, DEC_(data)) macro(data, 129) +#define MRECURSION131(macro, data) MRECURSION130( macro, DEC_(data)) macro(data, 130) +#define MRECURSION132(macro, data) MRECURSION131( macro, DEC_(data)) macro(data, 131) +#define MRECURSION133(macro, data) MRECURSION132( macro, DEC_(data)) macro(data, 132) +#define MRECURSION134(macro, data) MRECURSION133( macro, DEC_(data)) macro(data, 133) +#define MRECURSION135(macro, data) MRECURSION134( macro, DEC_(data)) macro(data, 134) +#define MRECURSION136(macro, data) MRECURSION135( macro, DEC_(data)) macro(data, 135) +#define MRECURSION137(macro, data) MRECURSION136( macro, DEC_(data)) macro(data, 136) +#define MRECURSION138(macro, data) MRECURSION137( macro, DEC_(data)) macro(data, 137) +#define MRECURSION139(macro, data) MRECURSION138( macro, DEC_(data)) macro(data, 138) +#define MRECURSION140(macro, data) MRECURSION139( macro, DEC_(data)) macro(data, 139) +#define MRECURSION141(macro, data) MRECURSION140( macro, DEC_(data)) macro(data, 140) +#define MRECURSION142(macro, data) MRECURSION141( macro, DEC_(data)) macro(data, 141) +#define MRECURSION143(macro, data) MRECURSION142( macro, DEC_(data)) macro(data, 142) +#define MRECURSION144(macro, data) MRECURSION143( macro, DEC_(data)) macro(data, 143) +#define MRECURSION145(macro, data) MRECURSION144( macro, DEC_(data)) macro(data, 144) +#define MRECURSION146(macro, data) MRECURSION145( macro, DEC_(data)) macro(data, 145) +#define MRECURSION147(macro, data) MRECURSION146( macro, DEC_(data)) macro(data, 146) +#define MRECURSION148(macro, data) MRECURSION147( macro, DEC_(data)) macro(data, 147) +#define MRECURSION149(macro, data) MRECURSION148( macro, DEC_(data)) macro(data, 148) +#define MRECURSION150(macro, data) MRECURSION149( macro, DEC_(data)) macro(data, 149) +#define MRECURSION151(macro, data) MRECURSION150( macro, DEC_(data)) macro(data, 150) +#define MRECURSION152(macro, data) MRECURSION151( macro, DEC_(data)) macro(data, 151) +#define MRECURSION153(macro, data) MRECURSION152( macro, DEC_(data)) macro(data, 152) +#define MRECURSION154(macro, data) MRECURSION153( macro, DEC_(data)) macro(data, 153) +#define MRECURSION155(macro, data) MRECURSION154( macro, DEC_(data)) macro(data, 154) +#define MRECURSION156(macro, data) MRECURSION155( macro, DEC_(data)) macro(data, 155) +#define MRECURSION157(macro, data) MRECURSION156( macro, DEC_(data)) macro(data, 156) +#define MRECURSION158(macro, data) MRECURSION157( macro, DEC_(data)) macro(data, 157) +#define MRECURSION159(macro, data) MRECURSION158( macro, DEC_(data)) macro(data, 158) +#define MRECURSION160(macro, data) MRECURSION159( macro, DEC_(data)) macro(data, 159) +#define MRECURSION161(macro, data) MRECURSION160( macro, DEC_(data)) macro(data, 160) +#define MRECURSION162(macro, data) MRECURSION161( macro, DEC_(data)) macro(data, 161) +#define MRECURSION163(macro, data) MRECURSION162( macro, DEC_(data)) macro(data, 162) +#define MRECURSION164(macro, data) MRECURSION163( macro, DEC_(data)) macro(data, 163) +#define MRECURSION165(macro, data) MRECURSION164( macro, DEC_(data)) macro(data, 164) +#define MRECURSION166(macro, data) MRECURSION165( macro, DEC_(data)) macro(data, 165) +#define MRECURSION167(macro, data) MRECURSION166( macro, DEC_(data)) macro(data, 166) +#define MRECURSION168(macro, data) MRECURSION167( macro, DEC_(data)) macro(data, 167) +#define MRECURSION169(macro, data) MRECURSION168( macro, DEC_(data)) macro(data, 168) +#define MRECURSION170(macro, data) MRECURSION169( macro, DEC_(data)) macro(data, 169) +#define MRECURSION171(macro, data) MRECURSION170( macro, DEC_(data)) macro(data, 170) +#define MRECURSION172(macro, data) MRECURSION171( macro, DEC_(data)) macro(data, 171) +#define MRECURSION173(macro, data) MRECURSION172( macro, DEC_(data)) macro(data, 172) +#define MRECURSION174(macro, data) MRECURSION173( macro, DEC_(data)) macro(data, 173) +#define MRECURSION175(macro, data) MRECURSION174( macro, DEC_(data)) macro(data, 174) +#define MRECURSION176(macro, data) MRECURSION175( macro, DEC_(data)) macro(data, 175) +#define MRECURSION177(macro, data) MRECURSION176( macro, DEC_(data)) macro(data, 176) +#define MRECURSION178(macro, data) MRECURSION177( macro, DEC_(data)) macro(data, 177) +#define MRECURSION179(macro, data) MRECURSION178( macro, DEC_(data)) macro(data, 178) +#define MRECURSION180(macro, data) MRECURSION179( macro, DEC_(data)) macro(data, 179) +#define MRECURSION181(macro, data) MRECURSION180( macro, DEC_(data)) macro(data, 180) +#define MRECURSION182(macro, data) MRECURSION181( macro, DEC_(data)) macro(data, 181) +#define MRECURSION183(macro, data) MRECURSION182( macro, DEC_(data)) macro(data, 182) +#define MRECURSION184(macro, data) MRECURSION183( macro, DEC_(data)) macro(data, 183) +#define MRECURSION185(macro, data) MRECURSION184( macro, DEC_(data)) macro(data, 184) +#define MRECURSION186(macro, data) MRECURSION185( macro, DEC_(data)) macro(data, 185) +#define MRECURSION187(macro, data) MRECURSION186( macro, DEC_(data)) macro(data, 186) +#define MRECURSION188(macro, data) MRECURSION187( macro, DEC_(data)) macro(data, 187) +#define MRECURSION189(macro, data) MRECURSION188( macro, DEC_(data)) macro(data, 188) +#define MRECURSION190(macro, data) MRECURSION189( macro, DEC_(data)) macro(data, 189) +#define MRECURSION191(macro, data) MRECURSION190( macro, DEC_(data)) macro(data, 190) +#define MRECURSION192(macro, data) MRECURSION191( macro, DEC_(data)) macro(data, 191) +#define MRECURSION193(macro, data) MRECURSION192( macro, DEC_(data)) macro(data, 192) +#define MRECURSION194(macro, data) MRECURSION193( macro, DEC_(data)) macro(data, 193) +#define MRECURSION195(macro, data) MRECURSION194( macro, DEC_(data)) macro(data, 194) +#define MRECURSION196(macro, data) MRECURSION195( macro, DEC_(data)) macro(data, 195) +#define MRECURSION197(macro, data) MRECURSION196( macro, DEC_(data)) macro(data, 196) +#define MRECURSION198(macro, data) MRECURSION197( macro, DEC_(data)) macro(data, 197) +#define MRECURSION199(macro, data) MRECURSION198( macro, DEC_(data)) macro(data, 198) +#define MRECURSION200(macro, data) MRECURSION199( macro, DEC_(data)) macro(data, 199) +#define MRECURSION201(macro, data) MRECURSION200( macro, DEC_(data)) macro(data, 200) +#define MRECURSION202(macro, data) MRECURSION201( macro, DEC_(data)) macro(data, 201) +#define MRECURSION203(macro, data) MRECURSION202( macro, DEC_(data)) macro(data, 202) +#define MRECURSION204(macro, data) MRECURSION203( macro, DEC_(data)) macro(data, 203) +#define MRECURSION205(macro, data) MRECURSION204( macro, DEC_(data)) macro(data, 204) +#define MRECURSION206(macro, data) MRECURSION205( macro, DEC_(data)) macro(data, 205) +#define MRECURSION207(macro, data) MRECURSION206( macro, DEC_(data)) macro(data, 206) +#define MRECURSION208(macro, data) MRECURSION207( macro, DEC_(data)) macro(data, 207) +#define MRECURSION209(macro, data) MRECURSION208( macro, DEC_(data)) macro(data, 208) +#define MRECURSION210(macro, data) MRECURSION209( macro, DEC_(data)) macro(data, 209) +#define MRECURSION211(macro, data) MRECURSION210( macro, DEC_(data)) macro(data, 210) +#define MRECURSION212(macro, data) MRECURSION211( macro, DEC_(data)) macro(data, 211) +#define MRECURSION213(macro, data) MRECURSION212( macro, DEC_(data)) macro(data, 212) +#define MRECURSION214(macro, data) MRECURSION213( macro, DEC_(data)) macro(data, 213) +#define MRECURSION215(macro, data) MRECURSION214( macro, DEC_(data)) macro(data, 214) +#define MRECURSION216(macro, data) MRECURSION215( macro, DEC_(data)) macro(data, 215) +#define MRECURSION217(macro, data) MRECURSION216( macro, DEC_(data)) macro(data, 216) +#define MRECURSION218(macro, data) MRECURSION217( macro, DEC_(data)) macro(data, 217) +#define MRECURSION219(macro, data) MRECURSION218( macro, DEC_(data)) macro(data, 218) +#define MRECURSION220(macro, data) MRECURSION219( macro, DEC_(data)) macro(data, 219) +#define MRECURSION221(macro, data) MRECURSION220( macro, DEC_(data)) macro(data, 220) +#define MRECURSION222(macro, data) MRECURSION221( macro, DEC_(data)) macro(data, 221) +#define MRECURSION223(macro, data) MRECURSION222( macro, DEC_(data)) macro(data, 222) +#define MRECURSION224(macro, data) MRECURSION223( macro, DEC_(data)) macro(data, 223) +#define MRECURSION225(macro, data) MRECURSION224( macro, DEC_(data)) macro(data, 224) +#define MRECURSION226(macro, data) MRECURSION225( macro, DEC_(data)) macro(data, 225) +#define MRECURSION227(macro, data) MRECURSION226( macro, DEC_(data)) macro(data, 226) +#define MRECURSION228(macro, data) MRECURSION227( macro, DEC_(data)) macro(data, 227) +#define MRECURSION229(macro, data) MRECURSION228( macro, DEC_(data)) macro(data, 228) +#define MRECURSION230(macro, data) MRECURSION229( macro, DEC_(data)) macro(data, 229) +#define MRECURSION231(macro, data) MRECURSION230( macro, DEC_(data)) macro(data, 230) +#define MRECURSION232(macro, data) MRECURSION231( macro, DEC_(data)) macro(data, 231) +#define MRECURSION233(macro, data) MRECURSION232( macro, DEC_(data)) macro(data, 232) +#define MRECURSION234(macro, data) MRECURSION233( macro, DEC_(data)) macro(data, 233) +#define MRECURSION235(macro, data) MRECURSION234( macro, DEC_(data)) macro(data, 234) +#define MRECURSION236(macro, data) MRECURSION235( macro, DEC_(data)) macro(data, 235) +#define MRECURSION237(macro, data) MRECURSION236( macro, DEC_(data)) macro(data, 236) +#define MRECURSION238(macro, data) MRECURSION237( macro, DEC_(data)) macro(data, 237) +#define MRECURSION239(macro, data) MRECURSION238( macro, DEC_(data)) macro(data, 238) +#define MRECURSION240(macro, data) MRECURSION239( macro, DEC_(data)) macro(data, 239) +#define MRECURSION241(macro, data) MRECURSION240( macro, DEC_(data)) macro(data, 240) +#define MRECURSION242(macro, data) MRECURSION241( macro, DEC_(data)) macro(data, 241) +#define MRECURSION243(macro, data) MRECURSION242( macro, DEC_(data)) macro(data, 242) +#define MRECURSION244(macro, data) MRECURSION243( macro, DEC_(data)) macro(data, 243) +#define MRECURSION245(macro, data) MRECURSION244( macro, DEC_(data)) macro(data, 244) +#define MRECURSION246(macro, data) MRECURSION245( macro, DEC_(data)) macro(data, 245) +#define MRECURSION247(macro, data) MRECURSION246( macro, DEC_(data)) macro(data, 246) +#define MRECURSION248(macro, data) MRECURSION247( macro, DEC_(data)) macro(data, 247) +#define MRECURSION249(macro, data) MRECURSION248( macro, DEC_(data)) macro(data, 248) +#define MRECURSION250(macro, data) MRECURSION249( macro, DEC_(data)) macro(data, 249) +#define MRECURSION251(macro, data) MRECURSION250( macro, DEC_(data)) macro(data, 250) +#define MRECURSION252(macro, data) MRECURSION251( macro, DEC_(data)) macro(data, 251) +#define MRECURSION253(macro, data) MRECURSION252( macro, DEC_(data)) macro(data, 252) +#define MRECURSION254(macro, data) MRECURSION253( macro, DEC_(data)) macro(data, 253) +#define MRECURSION255(macro, data) MRECURSION254( macro, DEC_(data)) macro(data, 254) +#define MRECURSION256(macro, data) MRECURSION255( macro, DEC_(data)) macro(data, 255) + +/** @} */ + +#endif /* _MRECURSION_H_ */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h new file mode 100644 index 0000000..fb820d5 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h @@ -0,0 +1,321 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef _MREPEAT_H_ +#define _MREPEAT_H_ + +/** + * \defgroup group_sam0_utils_mrepeat Preprocessor - Macro Repeat + * + * \ingroup group_sam0_utils + * + * @{ + */ + +#include "preprocessor.h" + +/** Maximal number of repetitions supported by MREPEAT. */ +#define MREPEAT_LIMIT 256 + +/** \brief Macro repeat. + * + * This macro represents a horizontal repetition construct. + * + * \param[in] count The number of repetitious calls to macro. Valid values + * range from 0 to MREPEAT_LIMIT. + * \param[in] macro A binary operation of the form macro(n, data). This macro + * is expanded by MREPEAT with the current repetition number + * and the auxiliary data argument. + * \param[in] data Auxiliary data passed to macro. + * + * \return macro(0, data) macro(1, data) ... macro(count - 1, data) + */ +#define MREPEAT(count, macro, data) TPASTE2(MREPEAT, count) (macro, data) + +#define MREPEAT0( macro, data) +#define MREPEAT1( macro, data) MREPEAT0( macro, data) macro( 0, data) +#define MREPEAT2( macro, data) MREPEAT1( macro, data) macro( 1, data) +#define MREPEAT3( macro, data) MREPEAT2( macro, data) macro( 2, data) +#define MREPEAT4( macro, data) MREPEAT3( macro, data) macro( 3, data) +#define MREPEAT5( macro, data) MREPEAT4( macro, data) macro( 4, data) +#define MREPEAT6( macro, data) MREPEAT5( macro, data) macro( 5, data) +#define MREPEAT7( macro, data) MREPEAT6( macro, data) macro( 6, data) +#define MREPEAT8( macro, data) MREPEAT7( macro, data) macro( 7, data) +#define MREPEAT9( macro, data) MREPEAT8( macro, data) macro( 8, data) +#define MREPEAT10( macro, data) MREPEAT9( macro, data) macro( 9, data) +#define MREPEAT11( macro, data) MREPEAT10( macro, data) macro( 10, data) +#define MREPEAT12( macro, data) MREPEAT11( macro, data) macro( 11, data) +#define MREPEAT13( macro, data) MREPEAT12( macro, data) macro( 12, data) +#define MREPEAT14( macro, data) MREPEAT13( macro, data) macro( 13, data) +#define MREPEAT15( macro, data) MREPEAT14( macro, data) macro( 14, data) +#define MREPEAT16( macro, data) MREPEAT15( macro, data) macro( 15, data) +#define MREPEAT17( macro, data) MREPEAT16( macro, data) macro( 16, data) +#define MREPEAT18( macro, data) MREPEAT17( macro, data) macro( 17, data) +#define MREPEAT19( macro, data) MREPEAT18( macro, data) macro( 18, data) +#define MREPEAT20( macro, data) MREPEAT19( macro, data) macro( 19, data) +#define MREPEAT21( macro, data) MREPEAT20( macro, data) macro( 20, data) +#define MREPEAT22( macro, data) MREPEAT21( macro, data) macro( 21, data) +#define MREPEAT23( macro, data) MREPEAT22( macro, data) macro( 22, data) +#define MREPEAT24( macro, data) MREPEAT23( macro, data) macro( 23, data) +#define MREPEAT25( macro, data) MREPEAT24( macro, data) macro( 24, data) +#define MREPEAT26( macro, data) MREPEAT25( macro, data) macro( 25, data) +#define MREPEAT27( macro, data) MREPEAT26( macro, data) macro( 26, data) +#define MREPEAT28( macro, data) MREPEAT27( macro, data) macro( 27, data) +#define MREPEAT29( macro, data) MREPEAT28( macro, data) macro( 28, data) +#define MREPEAT30( macro, data) MREPEAT29( macro, data) macro( 29, data) +#define MREPEAT31( macro, data) MREPEAT30( macro, data) macro( 30, data) +#define MREPEAT32( macro, data) MREPEAT31( macro, data) macro( 31, data) +#define MREPEAT33( macro, data) MREPEAT32( macro, data) macro( 32, data) +#define MREPEAT34( macro, data) MREPEAT33( macro, data) macro( 33, data) +#define MREPEAT35( macro, data) MREPEAT34( macro, data) macro( 34, data) +#define MREPEAT36( macro, data) MREPEAT35( macro, data) macro( 35, data) +#define MREPEAT37( macro, data) MREPEAT36( macro, data) macro( 36, data) +#define MREPEAT38( macro, data) MREPEAT37( macro, data) macro( 37, data) +#define MREPEAT39( macro, data) MREPEAT38( macro, data) macro( 38, data) +#define MREPEAT40( macro, data) MREPEAT39( macro, data) macro( 39, data) +#define MREPEAT41( macro, data) MREPEAT40( macro, data) macro( 40, data) +#define MREPEAT42( macro, data) MREPEAT41( macro, data) macro( 41, data) +#define MREPEAT43( macro, data) MREPEAT42( macro, data) macro( 42, data) +#define MREPEAT44( macro, data) MREPEAT43( macro, data) macro( 43, data) +#define MREPEAT45( macro, data) MREPEAT44( macro, data) macro( 44, data) +#define MREPEAT46( macro, data) MREPEAT45( macro, data) macro( 45, data) +#define MREPEAT47( macro, data) MREPEAT46( macro, data) macro( 46, data) +#define MREPEAT48( macro, data) MREPEAT47( macro, data) macro( 47, data) +#define MREPEAT49( macro, data) MREPEAT48( macro, data) macro( 48, data) +#define MREPEAT50( macro, data) MREPEAT49( macro, data) macro( 49, data) +#define MREPEAT51( macro, data) MREPEAT50( macro, data) macro( 50, data) +#define MREPEAT52( macro, data) MREPEAT51( macro, data) macro( 51, data) +#define MREPEAT53( macro, data) MREPEAT52( macro, data) macro( 52, data) +#define MREPEAT54( macro, data) MREPEAT53( macro, data) macro( 53, data) +#define MREPEAT55( macro, data) MREPEAT54( macro, data) macro( 54, data) +#define MREPEAT56( macro, data) MREPEAT55( macro, data) macro( 55, data) +#define MREPEAT57( macro, data) MREPEAT56( macro, data) macro( 56, data) +#define MREPEAT58( macro, data) MREPEAT57( macro, data) macro( 57, data) +#define MREPEAT59( macro, data) MREPEAT58( macro, data) macro( 58, data) +#define MREPEAT60( macro, data) MREPEAT59( macro, data) macro( 59, data) +#define MREPEAT61( macro, data) MREPEAT60( macro, data) macro( 60, data) +#define MREPEAT62( macro, data) MREPEAT61( macro, data) macro( 61, data) +#define MREPEAT63( macro, data) MREPEAT62( macro, data) macro( 62, data) +#define MREPEAT64( macro, data) MREPEAT63( macro, data) macro( 63, data) +#define MREPEAT65( macro, data) MREPEAT64( macro, data) macro( 64, data) +#define MREPEAT66( macro, data) MREPEAT65( macro, data) macro( 65, data) +#define MREPEAT67( macro, data) MREPEAT66( macro, data) macro( 66, data) +#define MREPEAT68( macro, data) MREPEAT67( macro, data) macro( 67, data) +#define MREPEAT69( macro, data) MREPEAT68( macro, data) macro( 68, data) +#define MREPEAT70( macro, data) MREPEAT69( macro, data) macro( 69, data) +#define MREPEAT71( macro, data) MREPEAT70( macro, data) macro( 70, data) +#define MREPEAT72( macro, data) MREPEAT71( macro, data) macro( 71, data) +#define MREPEAT73( macro, data) MREPEAT72( macro, data) macro( 72, data) +#define MREPEAT74( macro, data) MREPEAT73( macro, data) macro( 73, data) +#define MREPEAT75( macro, data) MREPEAT74( macro, data) macro( 74, data) +#define MREPEAT76( macro, data) MREPEAT75( macro, data) macro( 75, data) +#define MREPEAT77( macro, data) MREPEAT76( macro, data) macro( 76, data) +#define MREPEAT78( macro, data) MREPEAT77( macro, data) macro( 77, data) +#define MREPEAT79( macro, data) MREPEAT78( macro, data) macro( 78, data) +#define MREPEAT80( macro, data) MREPEAT79( macro, data) macro( 79, data) +#define MREPEAT81( macro, data) MREPEAT80( macro, data) macro( 80, data) +#define MREPEAT82( macro, data) MREPEAT81( macro, data) macro( 81, data) +#define MREPEAT83( macro, data) MREPEAT82( macro, data) macro( 82, data) +#define MREPEAT84( macro, data) MREPEAT83( macro, data) macro( 83, data) +#define MREPEAT85( macro, data) MREPEAT84( macro, data) macro( 84, data) +#define MREPEAT86( macro, data) MREPEAT85( macro, data) macro( 85, data) +#define MREPEAT87( macro, data) MREPEAT86( macro, data) macro( 86, data) +#define MREPEAT88( macro, data) MREPEAT87( macro, data) macro( 87, data) +#define MREPEAT89( macro, data) MREPEAT88( macro, data) macro( 88, data) +#define MREPEAT90( macro, data) MREPEAT89( macro, data) macro( 89, data) +#define MREPEAT91( macro, data) MREPEAT90( macro, data) macro( 90, data) +#define MREPEAT92( macro, data) MREPEAT91( macro, data) macro( 91, data) +#define MREPEAT93( macro, data) MREPEAT92( macro, data) macro( 92, data) +#define MREPEAT94( macro, data) MREPEAT93( macro, data) macro( 93, data) +#define MREPEAT95( macro, data) MREPEAT94( macro, data) macro( 94, data) +#define MREPEAT96( macro, data) MREPEAT95( macro, data) macro( 95, data) +#define MREPEAT97( macro, data) MREPEAT96( macro, data) macro( 96, data) +#define MREPEAT98( macro, data) MREPEAT97( macro, data) macro( 97, data) +#define MREPEAT99( macro, data) MREPEAT98( macro, data) macro( 98, data) +#define MREPEAT100(macro, data) MREPEAT99( macro, data) macro( 99, data) +#define MREPEAT101(macro, data) MREPEAT100(macro, data) macro(100, data) +#define MREPEAT102(macro, data) MREPEAT101(macro, data) macro(101, data) +#define MREPEAT103(macro, data) MREPEAT102(macro, data) macro(102, data) +#define MREPEAT104(macro, data) MREPEAT103(macro, data) macro(103, data) +#define MREPEAT105(macro, data) MREPEAT104(macro, data) macro(104, data) +#define MREPEAT106(macro, data) MREPEAT105(macro, data) macro(105, data) +#define MREPEAT107(macro, data) MREPEAT106(macro, data) macro(106, data) +#define MREPEAT108(macro, data) MREPEAT107(macro, data) macro(107, data) +#define MREPEAT109(macro, data) MREPEAT108(macro, data) macro(108, data) +#define MREPEAT110(macro, data) MREPEAT109(macro, data) macro(109, data) +#define MREPEAT111(macro, data) MREPEAT110(macro, data) macro(110, data) +#define MREPEAT112(macro, data) MREPEAT111(macro, data) macro(111, data) +#define MREPEAT113(macro, data) MREPEAT112(macro, data) macro(112, data) +#define MREPEAT114(macro, data) MREPEAT113(macro, data) macro(113, data) +#define MREPEAT115(macro, data) MREPEAT114(macro, data) macro(114, data) +#define MREPEAT116(macro, data) MREPEAT115(macro, data) macro(115, data) +#define MREPEAT117(macro, data) MREPEAT116(macro, data) macro(116, data) +#define MREPEAT118(macro, data) MREPEAT117(macro, data) macro(117, data) +#define MREPEAT119(macro, data) MREPEAT118(macro, data) macro(118, data) +#define MREPEAT120(macro, data) MREPEAT119(macro, data) macro(119, data) +#define MREPEAT121(macro, data) MREPEAT120(macro, data) macro(120, data) +#define MREPEAT122(macro, data) MREPEAT121(macro, data) macro(121, data) +#define MREPEAT123(macro, data) MREPEAT122(macro, data) macro(122, data) +#define MREPEAT124(macro, data) MREPEAT123(macro, data) macro(123, data) +#define MREPEAT125(macro, data) MREPEAT124(macro, data) macro(124, data) +#define MREPEAT126(macro, data) MREPEAT125(macro, data) macro(125, data) +#define MREPEAT127(macro, data) MREPEAT126(macro, data) macro(126, data) +#define MREPEAT128(macro, data) MREPEAT127(macro, data) macro(127, data) +#define MREPEAT129(macro, data) MREPEAT128(macro, data) macro(128, data) +#define MREPEAT130(macro, data) MREPEAT129(macro, data) macro(129, data) +#define MREPEAT131(macro, data) MREPEAT130(macro, data) macro(130, data) +#define MREPEAT132(macro, data) MREPEAT131(macro, data) macro(131, data) +#define MREPEAT133(macro, data) MREPEAT132(macro, data) macro(132, data) +#define MREPEAT134(macro, data) MREPEAT133(macro, data) macro(133, data) +#define MREPEAT135(macro, data) MREPEAT134(macro, data) macro(134, data) +#define MREPEAT136(macro, data) MREPEAT135(macro, data) macro(135, data) +#define MREPEAT137(macro, data) MREPEAT136(macro, data) macro(136, data) +#define MREPEAT138(macro, data) MREPEAT137(macro, data) macro(137, data) +#define MREPEAT139(macro, data) MREPEAT138(macro, data) macro(138, data) +#define MREPEAT140(macro, data) MREPEAT139(macro, data) macro(139, data) +#define MREPEAT141(macro, data) MREPEAT140(macro, data) macro(140, data) +#define MREPEAT142(macro, data) MREPEAT141(macro, data) macro(141, data) +#define MREPEAT143(macro, data) MREPEAT142(macro, data) macro(142, data) +#define MREPEAT144(macro, data) MREPEAT143(macro, data) macro(143, data) +#define MREPEAT145(macro, data) MREPEAT144(macro, data) macro(144, data) +#define MREPEAT146(macro, data) MREPEAT145(macro, data) macro(145, data) +#define MREPEAT147(macro, data) MREPEAT146(macro, data) macro(146, data) +#define MREPEAT148(macro, data) MREPEAT147(macro, data) macro(147, data) +#define MREPEAT149(macro, data) MREPEAT148(macro, data) macro(148, data) +#define MREPEAT150(macro, data) MREPEAT149(macro, data) macro(149, data) +#define MREPEAT151(macro, data) MREPEAT150(macro, data) macro(150, data) +#define MREPEAT152(macro, data) MREPEAT151(macro, data) macro(151, data) +#define MREPEAT153(macro, data) MREPEAT152(macro, data) macro(152, data) +#define MREPEAT154(macro, data) MREPEAT153(macro, data) macro(153, data) +#define MREPEAT155(macro, data) MREPEAT154(macro, data) macro(154, data) +#define MREPEAT156(macro, data) MREPEAT155(macro, data) macro(155, data) +#define MREPEAT157(macro, data) MREPEAT156(macro, data) macro(156, data) +#define MREPEAT158(macro, data) MREPEAT157(macro, data) macro(157, data) +#define MREPEAT159(macro, data) MREPEAT158(macro, data) macro(158, data) +#define MREPEAT160(macro, data) MREPEAT159(macro, data) macro(159, data) +#define MREPEAT161(macro, data) MREPEAT160(macro, data) macro(160, data) +#define MREPEAT162(macro, data) MREPEAT161(macro, data) macro(161, data) +#define MREPEAT163(macro, data) MREPEAT162(macro, data) macro(162, data) +#define MREPEAT164(macro, data) MREPEAT163(macro, data) macro(163, data) +#define MREPEAT165(macro, data) MREPEAT164(macro, data) macro(164, data) +#define MREPEAT166(macro, data) MREPEAT165(macro, data) macro(165, data) +#define MREPEAT167(macro, data) MREPEAT166(macro, data) macro(166, data) +#define MREPEAT168(macro, data) MREPEAT167(macro, data) macro(167, data) +#define MREPEAT169(macro, data) MREPEAT168(macro, data) macro(168, data) +#define MREPEAT170(macro, data) MREPEAT169(macro, data) macro(169, data) +#define MREPEAT171(macro, data) MREPEAT170(macro, data) macro(170, data) +#define MREPEAT172(macro, data) MREPEAT171(macro, data) macro(171, data) +#define MREPEAT173(macro, data) MREPEAT172(macro, data) macro(172, data) +#define MREPEAT174(macro, data) MREPEAT173(macro, data) macro(173, data) +#define MREPEAT175(macro, data) MREPEAT174(macro, data) macro(174, data) +#define MREPEAT176(macro, data) MREPEAT175(macro, data) macro(175, data) +#define MREPEAT177(macro, data) MREPEAT176(macro, data) macro(176, data) +#define MREPEAT178(macro, data) MREPEAT177(macro, data) macro(177, data) +#define MREPEAT179(macro, data) MREPEAT178(macro, data) macro(178, data) +#define MREPEAT180(macro, data) MREPEAT179(macro, data) macro(179, data) +#define MREPEAT181(macro, data) MREPEAT180(macro, data) macro(180, data) +#define MREPEAT182(macro, data) MREPEAT181(macro, data) macro(181, data) +#define MREPEAT183(macro, data) MREPEAT182(macro, data) macro(182, data) +#define MREPEAT184(macro, data) MREPEAT183(macro, data) macro(183, data) +#define MREPEAT185(macro, data) MREPEAT184(macro, data) macro(184, data) +#define MREPEAT186(macro, data) MREPEAT185(macro, data) macro(185, data) +#define MREPEAT187(macro, data) MREPEAT186(macro, data) macro(186, data) +#define MREPEAT188(macro, data) MREPEAT187(macro, data) macro(187, data) +#define MREPEAT189(macro, data) MREPEAT188(macro, data) macro(188, data) +#define MREPEAT190(macro, data) MREPEAT189(macro, data) macro(189, data) +#define MREPEAT191(macro, data) MREPEAT190(macro, data) macro(190, data) +#define MREPEAT192(macro, data) MREPEAT191(macro, data) macro(191, data) +#define MREPEAT193(macro, data) MREPEAT192(macro, data) macro(192, data) +#define MREPEAT194(macro, data) MREPEAT193(macro, data) macro(193, data) +#define MREPEAT195(macro, data) MREPEAT194(macro, data) macro(194, data) +#define MREPEAT196(macro, data) MREPEAT195(macro, data) macro(195, data) +#define MREPEAT197(macro, data) MREPEAT196(macro, data) macro(196, data) +#define MREPEAT198(macro, data) MREPEAT197(macro, data) macro(197, data) +#define MREPEAT199(macro, data) MREPEAT198(macro, data) macro(198, data) +#define MREPEAT200(macro, data) MREPEAT199(macro, data) macro(199, data) +#define MREPEAT201(macro, data) MREPEAT200(macro, data) macro(200, data) +#define MREPEAT202(macro, data) MREPEAT201(macro, data) macro(201, data) +#define MREPEAT203(macro, data) MREPEAT202(macro, data) macro(202, data) +#define MREPEAT204(macro, data) MREPEAT203(macro, data) macro(203, data) +#define MREPEAT205(macro, data) MREPEAT204(macro, data) macro(204, data) +#define MREPEAT206(macro, data) MREPEAT205(macro, data) macro(205, data) +#define MREPEAT207(macro, data) MREPEAT206(macro, data) macro(206, data) +#define MREPEAT208(macro, data) MREPEAT207(macro, data) macro(207, data) +#define MREPEAT209(macro, data) MREPEAT208(macro, data) macro(208, data) +#define MREPEAT210(macro, data) MREPEAT209(macro, data) macro(209, data) +#define MREPEAT211(macro, data) MREPEAT210(macro, data) macro(210, data) +#define MREPEAT212(macro, data) MREPEAT211(macro, data) macro(211, data) +#define MREPEAT213(macro, data) MREPEAT212(macro, data) macro(212, data) +#define MREPEAT214(macro, data) MREPEAT213(macro, data) macro(213, data) +#define MREPEAT215(macro, data) MREPEAT214(macro, data) macro(214, data) +#define MREPEAT216(macro, data) MREPEAT215(macro, data) macro(215, data) +#define MREPEAT217(macro, data) MREPEAT216(macro, data) macro(216, data) +#define MREPEAT218(macro, data) MREPEAT217(macro, data) macro(217, data) +#define MREPEAT219(macro, data) MREPEAT218(macro, data) macro(218, data) +#define MREPEAT220(macro, data) MREPEAT219(macro, data) macro(219, data) +#define MREPEAT221(macro, data) MREPEAT220(macro, data) macro(220, data) +#define MREPEAT222(macro, data) MREPEAT221(macro, data) macro(221, data) +#define MREPEAT223(macro, data) MREPEAT222(macro, data) macro(222, data) +#define MREPEAT224(macro, data) MREPEAT223(macro, data) macro(223, data) +#define MREPEAT225(macro, data) MREPEAT224(macro, data) macro(224, data) +#define MREPEAT226(macro, data) MREPEAT225(macro, data) macro(225, data) +#define MREPEAT227(macro, data) MREPEAT226(macro, data) macro(226, data) +#define MREPEAT228(macro, data) MREPEAT227(macro, data) macro(227, data) +#define MREPEAT229(macro, data) MREPEAT228(macro, data) macro(228, data) +#define MREPEAT230(macro, data) MREPEAT229(macro, data) macro(229, data) +#define MREPEAT231(macro, data) MREPEAT230(macro, data) macro(230, data) +#define MREPEAT232(macro, data) MREPEAT231(macro, data) macro(231, data) +#define MREPEAT233(macro, data) MREPEAT232(macro, data) macro(232, data) +#define MREPEAT234(macro, data) MREPEAT233(macro, data) macro(233, data) +#define MREPEAT235(macro, data) MREPEAT234(macro, data) macro(234, data) +#define MREPEAT236(macro, data) MREPEAT235(macro, data) macro(235, data) +#define MREPEAT237(macro, data) MREPEAT236(macro, data) macro(236, data) +#define MREPEAT238(macro, data) MREPEAT237(macro, data) macro(237, data) +#define MREPEAT239(macro, data) MREPEAT238(macro, data) macro(238, data) +#define MREPEAT240(macro, data) MREPEAT239(macro, data) macro(239, data) +#define MREPEAT241(macro, data) MREPEAT240(macro, data) macro(240, data) +#define MREPEAT242(macro, data) MREPEAT241(macro, data) macro(241, data) +#define MREPEAT243(macro, data) MREPEAT242(macro, data) macro(242, data) +#define MREPEAT244(macro, data) MREPEAT243(macro, data) macro(243, data) +#define MREPEAT245(macro, data) MREPEAT244(macro, data) macro(244, data) +#define MREPEAT246(macro, data) MREPEAT245(macro, data) macro(245, data) +#define MREPEAT247(macro, data) MREPEAT246(macro, data) macro(246, data) +#define MREPEAT248(macro, data) MREPEAT247(macro, data) macro(247, data) +#define MREPEAT249(macro, data) MREPEAT248(macro, data) macro(248, data) +#define MREPEAT250(macro, data) MREPEAT249(macro, data) macro(249, data) +#define MREPEAT251(macro, data) MREPEAT250(macro, data) macro(250, data) +#define MREPEAT252(macro, data) MREPEAT251(macro, data) macro(251, data) +#define MREPEAT253(macro, data) MREPEAT252(macro, data) macro(252, data) +#define MREPEAT254(macro, data) MREPEAT253(macro, data) macro(253, data) +#define MREPEAT255(macro, data) MREPEAT254(macro, data) macro(254, data) +#define MREPEAT256(macro, data) MREPEAT255(macro, data) macro(255, data) + +/** @} */ + +#endif /* _MREPEAT_H_ */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h new file mode 100644 index 0000000..7f67d8a --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h @@ -0,0 +1,38 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef _PREPROCESSOR_H_ +#define _PREPROCESSOR_H_ + +#include "tpaste.h" +#include "stringz.h" +#include "mrepeat.h" +#include "mrecursion.h" + +#endif // _PREPROCESSOR_H_ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/stringz.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/stringz.h new file mode 100644 index 0000000..70937c4 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/stringz.h @@ -0,0 +1,67 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef _STRINGZ_H_ +#define _STRINGZ_H_ + +/** + * \defgroup group_sam0_utils_stringz Preprocessor - Stringize + * + * \ingroup group_sam0_utils + * + * @{ + */ + +/** \brief Stringize. + * + * Stringize a preprocessing token, this token being allowed to be \#defined. + * + * May be used only within macros with the token passed as an argument if the + * token is \#defined. + * + * For example, writing STRINGZ(PIN) within a macro \#defined by PIN_NAME(PIN) + * and invoked as PIN_NAME(PIN0) with PIN0 \#defined as A0 is equivalent to + * writing "A0". + */ +#define STRINGZ(x) #x + +/** \brief Absolute stringize. + * + * Stringize a preprocessing token, this token being allowed to be \#defined. + * + * No restriction of use if the token is \#defined. + * + * For example, writing ASTRINGZ(PIN0) anywhere with PIN0 \#defined as A0 is + * equivalent to writing "A0". + */ +#define ASTRINGZ(x) STRINGZ(x) + +/** @} */ + +#endif // _STRINGZ_H_ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/tpaste.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/tpaste.h new file mode 100644 index 0000000..9108183 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/tpaste.h @@ -0,0 +1,85 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ +#ifndef _TPASTE_H_ +#define _TPASTE_H_ + +/** + * \defgroup group_sam0_utils_tpaste Preprocessor - Token Paste + * + * \ingroup group_sam0_utils + * + * @{ + */ + +/** \name Token Paste + * + * Paste N preprocessing tokens together, these tokens being allowed to be \#defined. + * + * May be used only within macros with the tokens passed as arguments if the tokens are \#defined. + * + * For example, writing TPASTE2(U, WIDTH) within a macro \#defined by + * UTYPE(WIDTH) and invoked as UTYPE(UL_WIDTH) with UL_WIDTH \#defined as 32 is + * equivalent to writing U32. + * + * @{ */ +#define TPASTE2( a, b) a##b +#define TPASTE3( a, b, c) a##b##c +#define TPASTE4( a, b, c, d) a##b##c##d +#define TPASTE5( a, b, c, d, e) a##b##c##d##e +#define TPASTE6( a, b, c, d, e, f) a##b##c##d##e##f +#define TPASTE7( a, b, c, d, e, f, g) a##b##c##d##e##f##g +#define TPASTE8( a, b, c, d, e, f, g, h) a##b##c##d##e##f##g##h +#define TPASTE9( a, b, c, d, e, f, g, h, i) a##b##c##d##e##f##g##h##i +#define TPASTE10(a, b, c, d, e, f, g, h, i, j) a##b##c##d##e##f##g##h##i##j +/** @} */ + +/** \name Absolute Token Paste + * + * Paste N preprocessing tokens together, these tokens being allowed to be \#defined. + * + * No restriction of use if the tokens are \#defined. + * + * For example, writing ATPASTE2(U, UL_WIDTH) anywhere with UL_WIDTH \#defined + * as 32 is equivalent to writing U32. + * + * @{ */ +#define ATPASTE2( a, b) TPASTE2( a, b) +#define ATPASTE3( a, b, c) TPASTE3( a, b, c) +#define ATPASTE4( a, b, c, d) TPASTE4( a, b, c, d) +#define ATPASTE5( a, b, c, d, e) TPASTE5( a, b, c, d, e) +#define ATPASTE6( a, b, c, d, e, f) TPASTE6( a, b, c, d, e, f) +#define ATPASTE7( a, b, c, d, e, f, g) TPASTE7( a, b, c, d, e, f, g) +#define ATPASTE8( a, b, c, d, e, f, g, h) TPASTE8( a, b, c, d, e, f, g, h) +#define ATPASTE9( a, b, c, d, e, f, g, h, i) TPASTE9( a, b, c, d, e, f, g, h, i) +#define ATPASTE10(a, b, c, d, e, f, g, h, i, j) TPASTE10(a, b, c, d, e, f, g, h, i, j) +/** @} */ + +/** @} */ + +#endif // _TPASTE_H_ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/reset.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/reset.h new file mode 100644 index 0000000..ae1eb5a --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/reset.h @@ -0,0 +1,119 @@ +/** + * \file + * + * \brief SAM Reset related functionality + * + * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef RESET_H_INCLUDED +#define RESET_H_INCLUDED + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \addtogroup asfdoc_sam0_system_group + * @{ + */ + +/** + * \brief Reset causes of the system. + * + * List of possible reset causes of the system. + */ +enum system_reset_cause { + /** The system was last reset by a software reset. */ + SYSTEM_RESET_CAUSE_SOFTWARE = PM_RCAUSE_SYST, + /** The system was last reset by the watchdog timer. */ + SYSTEM_RESET_CAUSE_WDT = PM_RCAUSE_WDT, + /** The system was last reset because the external reset line was pulled low. */ + SYSTEM_RESET_CAUSE_EXTERNAL_RESET = PM_RCAUSE_EXT, + /** The system was last reset by the BOD33. */ + SYSTEM_RESET_CAUSE_BOD33 = PM_RCAUSE_BOD33, + /** The system was last reset by the BOD12. */ + SYSTEM_RESET_CAUSE_BOD12 = PM_RCAUSE_BOD12, + /** The system was last reset by the POR (Power on reset). */ + SYSTEM_RESET_CAUSE_POR = PM_RCAUSE_POR, +}; + + +/** + * \name Reset Control + * @{ + */ + +/** + * \brief Reset the MCU. + * + * Resets the MCU and all associated peripherals and registers, except RTC, all 32KHz sources, + * WDT (if ALWAYSON is set) and GCLK (if WRTLOCK is set). + * + */ +static inline void system_reset(void) +{ + NVIC_SystemReset(); +} + +/** + * \brief Return the reset cause. + * + * Retrieves the cause of the last system reset. + * + * \return An enum value indicating the cause of the last system reset. + */ +static inline enum system_reset_cause system_get_reset_cause(void) +{ + return (enum system_reset_cause)PM->RCAUSE.reg; +} + +/** + * @} + */ + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* RESET_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/status_codes.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/status_codes.h new file mode 100644 index 0000000..29bbf41 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/status_codes.h @@ -0,0 +1,138 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef STATUS_CODES_H_INCLUDED +#define STATUS_CODES_H_INCLUDED + +#include + +/** + * \defgroup group_sam0_utils_status_codes Status Codes + * + * \ingroup group_sam0_utils + * + * @{ + */ + +/** Mask to retrieve the error category of a status code. */ +#define STATUS_CATEGORY_MASK 0xF0 + +/** Mask to retrieve the error code within the category of a status code. */ +#define STATUS_ERROR_MASK 0x0F + +/** Status code error categories. */ +enum status_categories { + STATUS_CATEGORY_OK = 0x00, + STATUS_CATEGORY_COMMON = 0x10, + STATUS_CATEGORY_ANALOG = 0x30, + STATUS_CATEGORY_COM = 0x40, + STATUS_CATEGORY_IO = 0x50, +}; + +/** + * Status code that may be returned by shell commands and protocol + * implementations. + * + * \note Any change to these status codes and the corresponding + * message strings is strictly forbidden. New codes can be added, + * however, but make sure that any message string tables are updated + * at the same time. + */ +enum status_code { + STATUS_OK = STATUS_CATEGORY_OK | 0x00, + STATUS_VALID_DATA = STATUS_CATEGORY_OK | 0x01, + STATUS_NO_CHANGE = STATUS_CATEGORY_OK | 0x02, + STATUS_ABORTED = STATUS_CATEGORY_OK | 0x04, + STATUS_BUSY = STATUS_CATEGORY_OK | 0x05, + STATUS_SUSPEND = STATUS_CATEGORY_OK | 0x06, + + STATUS_ERR_IO = STATUS_CATEGORY_COMMON | 0x00, + STATUS_ERR_REQ_FLUSHED = STATUS_CATEGORY_COMMON | 0x01, + STATUS_ERR_TIMEOUT = STATUS_CATEGORY_COMMON | 0x02, + STATUS_ERR_BAD_DATA = STATUS_CATEGORY_COMMON | 0x03, + STATUS_ERR_NOT_FOUND = STATUS_CATEGORY_COMMON | 0x04, + STATUS_ERR_UNSUPPORTED_DEV = STATUS_CATEGORY_COMMON | 0x05, + STATUS_ERR_NO_MEMORY = STATUS_CATEGORY_COMMON | 0x06, + STATUS_ERR_INVALID_ARG = STATUS_CATEGORY_COMMON | 0x07, + STATUS_ERR_BAD_ADDRESS = STATUS_CATEGORY_COMMON | 0x08, + STATUS_ERR_BAD_FORMAT = STATUS_CATEGORY_COMMON | 0x0A, + STATUS_ERR_BAD_FRQ = STATUS_CATEGORY_COMMON | 0x0B, + STATUS_ERR_DENIED = STATUS_CATEGORY_COMMON | 0x0c, + STATUS_ERR_ALREADY_INITIALIZED = STATUS_CATEGORY_COMMON | 0x0d, + STATUS_ERR_OVERFLOW = STATUS_CATEGORY_COMMON | 0x0e, + STATUS_ERR_NOT_INITIALIZED = STATUS_CATEGORY_COMMON | 0x0f, + + STATUS_ERR_SAMPLERATE_UNAVAILABLE = STATUS_CATEGORY_ANALOG | 0x00, + STATUS_ERR_RESOLUTION_UNAVAILABLE = STATUS_CATEGORY_ANALOG | 0x01, + + STATUS_ERR_BAUDRATE_UNAVAILABLE = STATUS_CATEGORY_COM | 0x00, + STATUS_ERR_PACKET_COLLISION = STATUS_CATEGORY_COM | 0x01, + STATUS_ERR_PROTOCOL = STATUS_CATEGORY_COM | 0x02, + + STATUS_ERR_PIN_MUX_INVALID = STATUS_CATEGORY_IO | 0x00, +}; +typedef enum status_code status_code_genare_t; + +/** + Status codes used by MAC stack. + */ +enum status_code_wireless { + //STATUS_OK = 0, //!< Success + ERR_IO_ERROR = -1, //!< I/O error + ERR_FLUSHED = -2, //!< Request flushed from queue + ERR_TIMEOUT = -3, //!< Operation timed out + ERR_BAD_DATA = -4, //!< Data integrity check failed + ERR_PROTOCOL = -5, //!< Protocol error + ERR_UNSUPPORTED_DEV = -6, //!< Unsupported device + ERR_NO_MEMORY = -7, //!< Insufficient memory + ERR_INVALID_ARG = -8, //!< Invalid argument + ERR_BAD_ADDRESS = -9, //!< Bad address + ERR_BUSY = -10, //!< Resource is busy + ERR_BAD_FORMAT = -11, //!< Data format not recognized + ERR_NO_TIMER = -12, //!< No timer available + ERR_TIMER_ALREADY_RUNNING = -13, //!< Timer already running + ERR_TIMER_NOT_RUNNING = -14, //!< Timer not running + + /** + * \brief Operation in progress + * + * This status code is for driver-internal use when an operation + * is currently being performed. + * + * \note Drivers should never return this status code to any + * callers. It is strictly for internal use. + */ + OPERATION_IN_PROGRESS = -128, +}; + +typedef enum status_code_wireless status_code_t; + +/** @} */ + +#endif /* STATUS_CODES_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/system.c b/feather_sensor_lte/libraries/Adafruit_ASFcore/system.c new file mode 100644 index 0000000..0121588 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/system.c @@ -0,0 +1,111 @@ +/** + * \file + * + * \brief SAM System related functionality + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#include + +/** + * \internal + * Dummy initialization function, used as a weak alias target for the various + * init functions called by \ref system_init(). + */ +void _system_dummy_init(void); +void _system_dummy_init(void) +{ + return; +} + +#if !defined(__DOXYGEN__) +# if defined(__GNUC__) +void system_clock_init(void) WEAK __attribute__((alias("_system_dummy_init"))); +void system_board_init(void) WEAK __attribute__((alias("_system_dummy_init"))); +void _system_events_init(void) WEAK __attribute__((alias("_system_dummy_init"))); +void _system_extint_init(void) WEAK __attribute__((alias("_system_dummy_init"))); +void _system_divas_init(void) WEAK __attribute__((alias("_system_dummy_init"))); +# elif defined(__ICCARM__) +void system_clock_init(void); +void system_board_init(void); +void _system_events_init(void); +void _system_extint_init(void); +void _system_divas_init(void); +# pragma weak system_clock_init=_system_dummy_init +# pragma weak system_board_init=_system_dummy_init +# pragma weak _system_events_init=_system_dummy_init +# pragma weak _system_extint_init=_system_dummy_init +# pragma weak _system_divas_init=_system_dummy_init +# endif +#endif + +/** + * \brief Initialize system + * + * This function will call the various initialization functions within the + * system namespace. If a given optional system module is not available, the + * associated call will effectively be a NOP (No Operation). + * + * Currently the following initialization functions are supported: + * - System clock initialization (via the SYSTEM CLOCK sub-module) + * - Board hardware initialization (via the Board module) + * - Event system driver initialization (via the EVSYS module) + * - External Interrupt driver initialization (via the EXTINT module) + */ +void system_init(void) +{ + /* Configure GCLK and clock sources according to conf_clocks.h */ + system_clock_init(); + + /* Initialize board hardware */ + system_board_init(); + + /* Initialize EVSYS hardware */ + _system_events_init(); + + /* Initialize External hardware */ + _system_extint_init(); + + /* Initialize DIVAS hardware */ + _system_divas_init(); +} + diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/system.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/system.h new file mode 100644 index 0000000..7b7bc00 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/system.h @@ -0,0 +1,726 @@ +/** + * \file + * + * \brief SAM System related functionality + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef SYSTEM_H_INCLUDED +#define SYSTEM_H_INCLUDED + +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup asfdoc_sam0_system_group SAM System (SYSTEM) Driver + * + * This driver for Atmel® | SMART ARM®-based microcontrollers provides an interface for the configuration + * and management of the device's system relation functionality, necessary for + * the basic device operation. This is not limited to a single peripheral, but + * extends across multiple hardware peripherals. + * + * The following peripherals are used by this module: + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * - PM (Power Manager) + * - RSTC(Reset Controller) + * - SUPC(Supply Controller) + * \endif + * \if DEVICE_SAMC21_SYSTEM_SUPPORT + * - PM (Power Manager) + * - RSTC(Reset Controller) + * - SUPC(Supply Controller) + * \endif + * \if DEVICE_SAMD21_SYSTEM_SUPPORT + * - SYSCTRL (System Control) + * - PM (Power Manager) + * \endif + * + * The following devices can use this module: + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * - Atmel | SMART SAM L21 + * \endif + * \if DEVICE_SAMC21_SYSTEM_SUPPORT + * - Atmel | SMART SAM C20/C21 + * \endif + * \if DEVICE_SAMD21_SYSTEM_SUPPORT + * - Atmel | SMART SAM D20/D21 + * - Atmel | SMART SAM R21 + * - Atmel | SMART SAM D09/D10/D11 + * - Atmel | SMART SAM DAx + * \endif + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_system_prerequisites + * - \ref asfdoc_sam0_system_module_overview + * - \ref asfdoc_sam0_system_special_considerations + * - \ref asfdoc_sam0_system_extra_info + * - \ref asfdoc_sam0_system_examples + * - \ref asfdoc_sam0_system_api_overview + * + * + * \section asfdoc_sam0_system_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * + * \section asfdoc_sam0_system_module_overview Module Overview + * + * The System driver provides a collection of interfaces between the user + * application logic, and the core device functionality (such as clocks, reset + * cause determination, etc.) that is required for all applications. It contains + * a number of sub-modules that control one specific aspect of the device: + * + * - System Core (this module) + * - \ref asfdoc_sam0_system_clock_group "System Clock Control" (sub-module) + * - \ref asfdoc_sam0_system_interrupt_group "System Interrupt Control" (sub-module) + * - \ref asfdoc_sam0_system_pinmux_group "System Pin Multiplexer Control" (sub-module) + * + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * \subsection asfdoc_sam0_system_module_overview_vreg_l21 Voltage Regulator + * The SAM device controls the voltage regulators for the core (VDDCORE) and + * backup (VDDBU) domains. It sets the voltage regulators according to the sleep + * modes, the performance level, or the user configuration. + * + * In active mode, the voltage regulator can be chosen on the fly between a LDO + * or a Buck converter. In standby mode, the low power voltage regulator is used + * to supply VDDCORE. + * + * \subsection asfdoc_sam0_system_module_overview_bbps Battery Backup Power Switch + * The SAM device supports connection of a battery backup to the VBAT power pin. + * It includes functionality that enables automatic power switching between main + * power and battery backup power. This will ensure power to the backup domain, + * when the main battery or power source is unavailable. + * \endif + * + * \if DEVICE_SAMC21_SYSTEM_SUPPORT + * \subsection asfdoc_sam0_system_module_overview_vreg_c21 Voltage Regulator + * The SAM device controls the voltage regulators for the core (VDDCORE). It sets + * the voltage regulators according to the sleep modes. + * + * There are a selectable reference voltage and voltage dependent on the temperature + * which can be used by analog modules like the ADC. + * \endif + * + * \subsection asfdoc_sam0_system_module_overview_vref Voltage References + * The various analog modules within the SAM devices (such as AC, ADC, and + * DAC) require a voltage reference to be configured to act as a reference point + * for comparisons and conversions. + * + * The SAM devices contain multiple references, including an internal + * temperature sensor and a fixed band-gap voltage source. When enabled, the + * associated voltage reference can be selected within the desired peripheral + * where applicable. + * + * \subsection asfdoc_sam0_system_module_overview_reset_cause System Reset Cause + * In some applications there may be a need to execute a different program + * flow based on how the device was reset. For example, if the cause of reset + * was the Watchdog timer (WDT), this might indicate an error in the application, + * and a form of error handling or error logging might be needed. + * + * For this reason, an API is provided to retrieve the cause of the last system + * reset, so that appropriate action can be taken. + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * There are three groups of reset sources: + * - Power supply reset: Resets caused by an electrical issue. It covers POR and BOD reset. + * - User reset: Resets caused by the application. It covers external reset, + * system reset, and watchdog reset. + * - Backup reset: Resets caused by a backup mode exit condition. + * + * \subsection asfdoc_sam0_system_module_overview_performance_level Performance Level + * Performance level allows the user to adjust the regulator output voltage to reduce + * power consumption. The user can on the fly select the most suitable performance + * level, depending on the application demands. + * + * The SAM device can operate at two different performance levels (PL0 and PL2). + * When operating at PL0, the voltage applied on the full logic area is reduced + * by voltage scaling. This voltage scaling technique allows to reduce the active + * power consumption while decreasing the maximum frequency of the device. When + * operating at PL2, the voltage regulator supplies the highest voltage, allowing + * the device to run at higher clock speeds. + * + * Performance level transition is possible only when the device is in active + * mode. After a reset, the device starts at the lowest performance level + * (lowest power consumption and lowest max. frequency). The application can then + * switch to another performance level at any time without any stop in the code + * execution. As shown in \ref asfdoc_sam0_system_performance_level_transition_figure. + * + * \note When scaling down the performance level, the bus frequency should first be + * scaled down in order to not exceed the maximum frequency allowed for the + * low performance level. + * When scaling up the performance level (e.g. from PL0 to PL2), check the performance + * level status before increasing the bus frequency. It can be increased only + * when the performance level transition is completed. + * + * \anchor asfdoc_sam0_system_performance_level_transition_figure + * \image html performance_level_transition.svg "Performance Level Transition" + * + * \subsection asfdoc_sam0_system_module_overview_power_domain Power Domain Gating + * Power domain gating allows power saving by reducing the voltage in logic + * areas in the device to a low-power supply. The feature is available in + * Standby sleep mode and will reduce the voltage in domains where all peripherals + * are idle. Internal logic will maintain its content, meaning the corresponding + * peripherals will not need to be reconfigured when normal operating voltage + * is returned. Most power domains can be in the following three states: + * + * - Active state: The power domain is powered on. + * - Retention state: The main voltage supply for the power domain is switched off, + * while maintaining a secondary low-power supply for the sequential cells. The + * logic context is restored when waking up. + * - Off state: The power domain is entirely powered off. The logic context is lost. + * + * The SAM L21 device contains three power domains which can be controlled using + * power domain gating, namely PD0, PD1, and PD2. These power domains can be + * configured to the following cases: + * - Default with no sleepwalking peripherals: A power domain is automatically set + * to retention state in standby sleep mode if no activity require it. The application + * can force all power domains to remain in active state during standby sleep mode + * in order to accelerate wakeup time. + * - Default with sleepwalking peripherals: If one or more peripherals are enabled + * to perform sleepwalking tasks in standby sleep mode, the corresponding power + * domain (PDn) remains in active state as well as all inferior power domains (PDn) in order + * to perform a sleepwalking task. The superior power domain is then automatically + * set to active state. At the end of the sleepwalking task, the device can either + * be woken up or the superior power domain can return to retention state. + * + * Power domains can be linked to each other, it allows a power domain (PDn) to be kept + * in active state if the inferior power domain (PDn-1) is in active state too. + * + * \ref asfdoc_sam0_system_power_domain_overview_table illustrates the + * four cases to consider in standby mode. + * + * \anchor asfdoc_sam0_system_power_domain_overview_table + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Sleep Mode versus Power Domain State Overview
Sleep modePD0PD1PD2PDTOPPDBACKUP
Idleactiveactiveactiveactiveactive
Standby - Case 1activeactiveactiveactiveactive
Standby - Case 2activeactiveretentionactiveactive
Standby - Case 3activeretentionretentionactiveactive
Standby - Case 4retentionretentionretentionactiveactive
Backupoffoffoffoffactive
Offoffoffoffoffoff
+ * + * \subsection asfdoc_sam0_system_module_overview_ram_state RAMs Low Power Mode + * By default, in standby sleep mode, RAM is in low power mode (back biased) + * if its power domain is in retention state. + * \ref asfdoc_sam0_system_power_ram_state_table lists RAMs low power mode. + * + * \anchor asfdoc_sam0_system_power_ram_state_table + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
RAM Back-biasing Mode
RAM modeDescription
Retention Back-biasing modeRAM is back-biased if its power domain is in retention mode
Standby Back-biasing modeRAM is back-biased if the device is in standby mode
Standby OFF modeRAM is OFF if the device is in standby mode
Always OFF modeRAM is OFF if the device is in RET mode
+ * + * \endif + * + * \subsection asfdoc_sam0_system_module_overview_sleep_mode Sleep Modes + * The SAM devices have several sleep modes. The sleep mode controls + * which clock systems on the device will remain enabled or disabled when the + * device enters a low power sleep mode. + * \ref asfdoc_sam0_system_module_sleep_mode_table "The table below" lists the + * clock settings of the different sleep modes. + * + * \anchor asfdoc_sam0_system_module_sleep_mode_table + * + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * \else + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * \endif + *
SAM Device Sleep Modes
Sleep modeSystem clockCPU clockAHB/AHB clockGCLK clocksOscillators (ONDEMAND = 0)Oscillators (ONDEMAND = 1)Regulator modeRAM mode
IdleRunStopRun if requestedRunRunRun if requestedNormalNormal
StandbyStopStopRun if requestedRun if requestedRun if requested or RUNSTDBY = 1Run if requestedLow pwerLow pwer
BackupStopStopStopStopStopStopBackupOff
OffOffOffOffOffOffOffOffOff
Sleep modeCPU clockAHB clockAPB clocksClock sourcesSystem clock32KHzReg modeRAM mode
Idle 0StopRunRunRunRunRunNormalNormal
Idle 1StopStopRunRunRunRunNormalNormal
Idle 2StopStopStopRunRunRunNormalNormal
StandbyStopStopStopStopStopStopLow PowerSource/Drain biasing
+ * + * Before entering device sleep, one of the available sleep modes must be set. + * The device will automatically wake up in response to an interrupt being + * generated or upon any other sleep mode exit condition. + * + * Some peripheral clocks will remain enabled during sleep, depending on their + * configuration. If desired, the modules can remain clocked during sleep to allow + * them continue to operate while other parts of the system are powered down + * to save power. + * + * + * \section asfdoc_sam0_system_special_considerations Special Considerations + * + * Most of the functions in this driver have device specific restrictions and + * caveats; refer to your device datasheet. + * + * + * \section asfdoc_sam0_system_extra_info Extra Information + * + * For extra information, see \ref asfdoc_sam0_system_extra. This includes: + * - \ref asfdoc_sam0_system_extra_acronyms + * - \ref asfdoc_sam0_system_extra_dependencies + * - \ref asfdoc_sam0_system_extra_errata + * - \ref asfdoc_sam0_system_extra_history + * + * + * \section asfdoc_sam0_system_examples Examples + * + * For SYSTEM module related examples, refer to the sub-modules listed in + * the \ref asfdoc_sam0_system_module_overview "system module overview". + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_drivers_power_exqsg. + * + * + * \section asfdoc_sam0_system_api_overview API Overview + * @{ + */ + +/** + * \name System Debugger + * @{ + */ + +/** + * \brief Check if debugger is present. + * + * Check if debugger is connected to the onboard debug system (DAP). + * + * \return A bool identifying if a debugger is present. + * + * \retval true Debugger is connected to the system + * \retval false Debugger is not connected to the system + * + */ +static inline bool system_is_debugger_present(void) +{ + return DSU->STATUSB.reg & DSU_STATUSB_DBGPRES; +} + +/** + * @} + */ + +/** + * \name System Identification + * @{ + */ + +/** + * \brief Retrieve the device identification signature. + * + * Retrieves the signature of the current device. + * + * \return Device ID signature as a 32-bit integer. + */ +static inline uint32_t system_get_device_id(void) +{ + return DSU->DID.reg; +} + +/** + * @} + */ + +/** + * \name System Initialization + * @{ + */ + +void system_init(void); + +/** + * @} + */ + + +/** + * @} + */ + +/** + +* \page asfdoc_sam0_drivers_power_exqsg Examples for Power Driver + * + * This is a list of the available Quick Start Guides (QSGs) and example + * applications. QSGs are simple examples with step-by-step instructions to + * configure and use this driver in a selection of + * use cases. Note that a QSG can be compiled as a standalone application or be + * added to the user application. + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * - \subpage asfdoc_sam0_power_basic_use_case + * \endif + * + * \page asfdoc_sam0_system_extra Extra Information for SYSTEM Driver + * + * \section asfdoc_sam0_system_extra_acronyms Acronyms + * Below is a table listing the acronyms used in this module, along with their + * intended meanings. + * + * + * + * + * + * + * + * + * + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * + * + * + * + * + * + * + * + * \endif + * \if DEVICE_SAMC21_SYSTEM_SUPPORT + * + * + * + * + * + * + * + * + * \endif + * \if DEVICE_SAMD21_SYSTEM_SUPPORT + * + * + * + * + * \endif + *
AcronymDefinition
PMPower Manager
SUPCSupply Controller
RSTCReset Controller
SUPCSupply Controller
RSTCReset Controller
SYSCTRLSystem control interface
+ * + * + * \section asfdoc_sam0_system_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - None + * + * + * \section asfdoc_sam0_system_extra_errata Errata + * There are no errata related to this driver. + * + * + * \section asfdoc_sam0_system_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * + * + * + * \endif + * \if DEVICE_SAMC21_SYSTEM_SUPPORT + * + * + * + * \endif + * \if DEVICE_SAMD21_SYSTEM_SUPPORT + * + * + * + * + * + * + * + * + * + * \endif + *
Changelog
Initial Release
Initial Release
Added new \c system_reset() to reset the complete MCU with some exceptions
Added new \c system_get_device_id() function to retrieved the device + * ID.
Initial Release
+ * + * \page asfdoc_sam0_system_document_revision_history Document Revision History + * + * + * + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * + * + * + * + * + * \endif + * \if DEVICE_SAMC21_SYSTEM_SUPPORT + * + * + * + * + * + * \endif + * \if DEVICE_SAMD21_SYSTEM_SUPPORT + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * \endif + *
Doc. Rev. + * Date + * Comments + *
42449A07/2015Initial document release
42484A08/2015Initial document release.
42120E04/2015Added support for SAMDAx
42120D12/2014Added support for SAMR21 and SAMD10/D11
42120C01/2014Added support for SAMD21
42120B06/2013Corrected documentation typos
42120A06/2013Initial document release
+ */ + +#ifdef __cplusplus +} +#endif + +#endif /* SYSTEM_H_INCLUDED */ + diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/system_interrupt.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/system_interrupt.h new file mode 100644 index 0000000..93a542d --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/system_interrupt.h @@ -0,0 +1,429 @@ +/** + * \file + * + * \brief SAM System Interrupt Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef SYSTEM_INTERRUPT_H_INCLUDED +#define SYSTEM_INTERRUPT_H_INCLUDED + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup asfdoc_sam0_system_interrupt_group SAM System Interrupt (SYSTEM INTERRUPT) Driver + * + * This driver for Atmel® | SMART ARM®-based microcontrollers provides + * an interface for the configuration and management of internal software and + * hardware interrupts/exceptions. + * + * The following peripheral is used by this module: + * - NVIC (Nested Vector Interrupt Controller) + * + * The following devices can use this module: + * - Atmel | SMART SAM D20/D21 + * - Atmel | SMART SAM R21 + * - Atmel | SMART SAM D09/D10/D11 + * - Atmel | SMART SAM L21/L22 + * - Atmel | SMART SAM DA1 + * - Atmel | SMART SAM C20/C21 + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_system_interrupt_prerequisites + * - \ref asfdoc_sam0_system_interrupt_module_overview + * - \ref asfdoc_sam0_system_interrupt_special_considerations + * - \ref asfdoc_sam0_system_interrupt_extra_info + * - \ref asfdoc_sam0_system_interrupt_examples + * - \ref asfdoc_sam0_system_interrupt_api_overview + * + * + * \section asfdoc_sam0_system_interrupt_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * + * \section asfdoc_sam0_system_interrupt_module_overview Module Overview + * + * The ARM® Cortex® M0+ core contains an interrupt and exception vector table, which + * can be used to configure the device's interrupt handlers; individual + * interrupts and exceptions can be enabled and disabled, as well as configured + * with a variable priority. + * + * This driver provides a set of wrappers around the core interrupt functions, + * to expose a simple API for the management of global and individual interrupts + * within the device. + * + * \subsection asfdoc_sam0_system_interrupt_module_overview_criticalsec Critical Sections + * In some applications it is important to ensure that no interrupts may be + * executed by the system whilst a critical portion of code is being run; for + * example, a buffer may be copied from one context to another - during which + * interrupts must be disabled to avoid corruption of the source buffer contents + * until the copy has completed. This driver provides a basic API to enter and + * exit nested critical sections, so that global interrupts can be kept disabled + * for as long as necessary to complete a critical application code section. + * + * \subsection asfdoc_sam0_system_interrupt_module_overview_softints Software Interrupts + * For some applications, it may be desirable to raise a module or core + * interrupt via software. For this reason, a set of APIs to set an interrupt or + * exception as pending are provided to the user application. + * + * \section asfdoc_sam0_system_interrupt_special_considerations Special Considerations + * + * Interrupts from peripherals in the SAM devices are on a per-module basis; + * an interrupt raised from any source within a module will cause a single, + * module-common handler to execute. It is the user application or driver's + * responsibility to de-multiplex the module-common interrupt to determine the + * exact interrupt cause. + * + * \section asfdoc_sam0_system_interrupt_extra_info Extra Information + * + * For extra information, see \ref asfdoc_sam0_system_interrupt_extra. This includes: + * - \ref asfdoc_sam0_system_interrupt_extra_acronyms + * - \ref asfdoc_sam0_system_interrupt_extra_dependencies + * - \ref asfdoc_sam0_system_interrupt_extra_errata + * - \ref asfdoc_sam0_system_interrupt_extra_history + * + * + * \section asfdoc_sam0_system_interrupt_examples Examples + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_system_interrupt_exqsg. + * + * \section asfdoc_sam0_system_interrupt_api_overview API Overview + * @{ + */ + +#include "compiler.h" +#include +#include "system_interrupt_features.h" + +/** + * \brief Table of possible system interrupt/exception vector priorities. + * + * Table of all possible interrupt and exception vector priorities within the + * device. + */ +enum system_interrupt_priority_level { + /** Priority level 0, the highest possible interrupt priority */ + SYSTEM_INTERRUPT_PRIORITY_LEVEL_0 = 0, + /** Priority level 1 */ + SYSTEM_INTERRUPT_PRIORITY_LEVEL_1 = 1, + /** Priority level 2 */ + SYSTEM_INTERRUPT_PRIORITY_LEVEL_2 = 2, + /** Priority level 3, the lowest possible interrupt priority */ + SYSTEM_INTERRUPT_PRIORITY_LEVEL_3 = 3, +}; + +/** + * \name Critical Section Management + * @{ + */ + +/** + * \brief Enters a critical section. + * + * Disables global interrupts. To support nested critical sections, an internal + * count of the critical section nesting will be kept, so that global interrupts + * are only re-enabled upon leaving the outermost nested critical section. + * + */ +static inline void system_interrupt_enter_critical_section(void) +{ + cpu_irq_enter_critical(); +} + +/** + * \brief Leaves a critical section. + * + * Enables global interrupts. To support nested critical sections, an internal + * count of the critical section nesting will be kept, so that global interrupts + * are only re-enabled upon leaving the outermost nested critical section. + * + */ +static inline void system_interrupt_leave_critical_section(void) +{ + cpu_irq_leave_critical(); +} + +/** @} */ + +/** + * \name Interrupt Enabling/Disabling + * @{ + */ + +/** + * \brief Check if global interrupts are enabled. + * + * Checks if global interrupts are currently enabled. + * + * \returns A boolean that identifies if the global interrupts are enabled or not. + * + * \retval true Global interrupts are currently enabled + * \retval false Global interrupts are currently disabled + * + */ +static inline bool system_interrupt_is_global_enabled(void) +{ + return cpu_irq_is_enabled(); +} + +/** + * \brief Enables global interrupts. + * + * Enables global interrupts in the device to fire any enabled interrupt handlers. + */ +static inline void system_interrupt_enable_global(void) +{ + cpu_irq_enable(); +} + +/** + * \brief Disables global interrupts. + * + * Disabled global interrupts in the device, preventing any enabled interrupt + * handlers from executing. + */ +static inline void system_interrupt_disable_global(void) +{ + cpu_irq_disable(); +} + +/** + * \brief Checks if an interrupt vector is enabled or not. + * + * Checks if a specific interrupt vector is currently enabled. + * + * \param[in] vector Interrupt vector number to check + * + * \returns A variable identifying if the requested interrupt vector is enabled. + * + * \retval true Specified interrupt vector is currently enabled + * \retval false Specified interrupt vector is currently disabled + * + */ +static inline bool system_interrupt_is_enabled( + const enum system_interrupt_vector vector) +{ + return (bool)((NVIC->ISER[0] >> (uint32_t)vector) & 0x00000001); +} + +/** + * \brief Enable interrupt vector. + * + * Enables execution of the software handler for the requested interrupt vector. + * + * \param[in] vector Interrupt vector to enable + */ +static inline void system_interrupt_enable( + const enum system_interrupt_vector vector) +{ + NVIC->ISER[0] = (uint32_t)(1 << ((uint32_t)vector & 0x0000001f)); +} + +/** + * \brief Disable interrupt vector. + * + * Disables execution of the software handler for the requested interrupt vector. + * + * \param[in] vector Interrupt vector to disable + */ +static inline void system_interrupt_disable( + const enum system_interrupt_vector vector) +{ + NVIC->ICER[0] = (uint32_t)(1 << ((uint32_t)vector & 0x0000001f)); +} + +/** @} */ + +/** + * \name Interrupt State Management + * @{ + */ + +/** + * \brief Get active interrupt (if any). + * + * Return the vector number for the current executing software handler, if any. + * + * \return Interrupt number that is currently executing. + */ +static inline enum system_interrupt_vector system_interrupt_get_active(void) +{ + uint32_t IPSR = __get_IPSR(); + /* The IPSR returns the Exception number, which with an offset 16 to IRQ number. */ + return (enum system_interrupt_vector)((IPSR & _SYSTEM_INTERRUPT_IPSR_MASK) - 16); +} + +bool system_interrupt_is_pending( + const enum system_interrupt_vector vector); + +enum status_code system_interrupt_set_pending( + const enum system_interrupt_vector vector); + +enum status_code system_interrupt_clear_pending( + const enum system_interrupt_vector vector); + +/** @} */ + +/** + * \name Interrupt Priority Management + * @{ + */ + +enum status_code system_interrupt_set_priority( + const enum system_interrupt_vector vector, + const enum system_interrupt_priority_level priority_level); + +enum system_interrupt_priority_level system_interrupt_get_priority( + const enum system_interrupt_vector vector); + +/** @} */ + +/** @} */ + +/** + * \page asfdoc_sam0_system_interrupt_extra Extra Information for SYSTEM INTERRUPT Driver + * + * \section asfdoc_sam0_system_interrupt_extra_acronyms Acronyms + * The table below presents the acronyms used in this module: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
AcronymDescription
ISRInterrupt Service Routine
NMINon-maskable Interrupt
SERCOMSerial Communication Interface
+ * + * + * \section asfdoc_sam0_system_interrupt_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - None + * + * + * \section asfdoc_sam0_system_interrupt_extra_errata Errata + * There are no errata related to this driver. + * + * + * \section asfdoc_sam0_system_interrupt_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * + * + * + *
Changelog
Initial Release
+ */ + +/** + * \page asfdoc_sam0_system_interrupt_exqsg Examples for SYSTEM INTERRUPT Driver + * + * This is a list of the available Quick Start guides (QSGs) and example + * applications for \ref asfdoc_sam0_system_interrupt_group. QSGs are simple examples with + * step-by-step instructions to configure and use this driver in a selection of + * use cases. Note that a QSG can be compiled as a standalone application or be + * added to the user application. + * + * - \subpage asfdoc_sam0_system_interrupt_critsec_use_case + * - \subpage asfdoc_sam0_system_interrupt_enablemodint_use_case + * + * \page asfdoc_sam0_system_interrupt_document_revision_history Document Revision History + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Doc. Rev. + * Date + * Comments + *
42122E08/2015Added support for SAM L21/L22, SAM DA1, and SAM C20/C21
42122D12/2014Added support for SAM R21 and SAM D10/D11
42122C01/2014Added support for SAM D21
42122B06/2013Corrected documentation typos
42122A06/2013Initial release
+ */ + +#ifdef __cplusplus +} +#endif + +#endif // #ifndef SYSTEM_INTERRUPT_H_INCLUDED diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/system_interrupt_features.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/system_interrupt_features.h new file mode 100644 index 0000000..25dfa83 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/system_interrupt_features.h @@ -0,0 +1,195 @@ +/** + * \file + * + * \brief SAM D21 System Interrupt Driver + * + * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#ifndef SYSTEM_INTERRUPT_FEATURES_H_INCLUDED +#define SYSTEM_INTERRUPT_FEATURES_H_INCLUDED + +#if !defined(__DOXYGEN__) + +/* Generates a interrupt vector table enum list entry for a given module type + and index (e.g. "SYSTEM_INTERRUPT_MODULE_TC0 = TC0_IRQn,"). */ +# define _MODULE_IRQn(n, module) \ + SYSTEM_INTERRUPT_MODULE_##module##n = module##n##_IRQn, + +/* Generates interrupt vector table enum list entries for all instances of a + given module type on the selected device. */ +# define _SYSTEM_INTERRUPT_MODULES(name) \ + MREPEAT(name##_INST_NUM, _MODULE_IRQn, name) + +# define _SYSTEM_INTERRUPT_IPSR_MASK 0x0000003f +# define _SYSTEM_INTERRUPT_PRIORITY_MASK 0x00000003 + +# define _SYSTEM_INTERRUPT_EXTERNAL_VECTOR_START 0 + +# define _SYSTEM_INTERRUPT_SYSTICK_PRI_POS 30 +#endif + +/** + * \addtogroup asfdoc_sam0_system_interrupt_group + * @{ + */ + +/** + * \brief Table of possible system interrupt/exception vector numbers. + * + * Table of all possible interrupt and exception vector indexes within the + * SAM D21 device. Check peripherals configuration in SAM D21 datasheet for + * available vector index for specific device. + * + */ +#if defined(__DOXYGEN__) +/** \note The actual enumeration name is "system_interrupt_vector". */ +enum system_interrupt_vector_samd21 { +#else +enum system_interrupt_vector { +#endif + /** Interrupt vector index for a NMI interrupt */ + SYSTEM_INTERRUPT_NON_MASKABLE = NonMaskableInt_IRQn, + /** Interrupt vector index for a Hard Fault memory access exception */ + SYSTEM_INTERRUPT_HARD_FAULT = HardFault_IRQn, + /** Interrupt vector index for a Supervisor Call exception */ + SYSTEM_INTERRUPT_SV_CALL = SVCall_IRQn, + /** Interrupt vector index for a Pending Supervisor interrupt */ + SYSTEM_INTERRUPT_PENDING_SV = PendSV_IRQn, + /** Interrupt vector index for a System Tick interrupt */ + SYSTEM_INTERRUPT_SYSTICK = SysTick_IRQn, + + /** Interrupt vector index for a Power Manager peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_PM = PM_IRQn, + /** Interrupt vector index for a System Control peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_SYSCTRL = SYSCTRL_IRQn, + /** Interrupt vector index for a Watch Dog peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_WDT = WDT_IRQn, + /** Interrupt vector index for a Real Time Clock peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_RTC = RTC_IRQn, + /** Interrupt vector index for an External Interrupt peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_EIC = EIC_IRQn, + /** Interrupt vector index for a Non Volatile Memory Controller interrupt */ + SYSTEM_INTERRUPT_MODULE_NVMCTRL = NVMCTRL_IRQn, + /** Interrupt vector index for a Direct Memory Access interrupt */ + SYSTEM_INTERRUPT_MODULE_DMA = DMAC_IRQn, +#if defined(__DOXYGEN__) || defined(ID_USB) + /** Interrupt vector index for a Universal Serial Bus interrupt */ + SYSTEM_INTERRUPT_MODULE_USB = USB_IRQn, +#endif + /** Interrupt vector index for an Event System interrupt */ + SYSTEM_INTERRUPT_MODULE_EVSYS = EVSYS_IRQn, +#if defined(__DOXYGEN__) + /** Interrupt vector index for a SERCOM peripheral interrupt. + * + * Each specific device may contain several SERCOM peripherals; each module + * instance will have its own entry in the table, with the instance number + * substituted for "n" in the entry name (e.g. + * \c SYSTEM_INTERRUPT_MODULE_SERCOM0). + */ + SYSTEM_INTERRUPT_MODULE_SERCOMn = SERCOMn_IRQn, + + /** Interrupt vector index for a Timer/Counter Control peripheral interrupt. + * + * Each specific device may contain several TCC peripherals; each module + * instance will have its own entry in the table, with the instance number + * substituted for "n" in the entry name (e.g. + * \c SYSTEM_INTERRUPT_MODULE_TCC0). + */ + SYSTEM_INTERRUPT_MODULE_TCCn = TCCn_IRQn, + + /** Interrupt vector index for a Timer/Counter peripheral interrupt. + * + * Each specific device may contain several TC peripherals; each module + * instance will have its own entry in the table, with the instance number + * substituted for "n" in the entry name (e.g. + * \c SYSTEM_INTERRUPT_MODULE_TC3). + */ + SYSTEM_INTERRUPT_MODULE_TCn = TCn_IRQn, +#else + _SYSTEM_INTERRUPT_MODULES(SERCOM) + + _SYSTEM_INTERRUPT_MODULES(TCC) + + SYSTEM_INTERRUPT_MODULE_TC3 = TC3_IRQn, + SYSTEM_INTERRUPT_MODULE_TC4 = TC4_IRQn, + SYSTEM_INTERRUPT_MODULE_TC5 = TC5_IRQn, +# if defined(ID_TC6) + SYSTEM_INTERRUPT_MODULE_TC6 = TC6_IRQn, +# endif +# if defined(ID_TC7) + SYSTEM_INTERRUPT_MODULE_TC7 = TC7_IRQn, +# endif +#endif + +#if defined(__DOXYGEN__) || defined(ID_ADC) + /** Interrupt vector index for an Analog-to-Digital peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_ADC = ADC_IRQn, +#endif + +#if defined(__DOXYGEN__) || defined(ID_AC) + /** Interrupt vector index for an Analog Comparator peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_AC = AC_IRQn, +#endif + +#if defined(__DOXYGEN__) || defined(ID_DAC) + /** Interrupt vector index for a Digital-to-Analog peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_DAC = DAC_IRQn, +#endif +#if defined(__DOXYGEN__) || defined(ID_PTC) + /** Interrupt vector index for a Peripheral Touch Controller peripheral + * interrupt */ + SYSTEM_INTERRUPT_MODULE_PTC = PTC_IRQn, +#endif +#if defined(__DOXYGEN__) || defined(ID_I2S) + /** Interrupt vector index for a Inter-IC Sound Interface peripheral + * interrupt */ + SYSTEM_INTERRUPT_MODULE_I2S = I2S_IRQn, +#endif +#if defined(__DOXYGEN__) || defined(ID_AC1) + /** Interrupt vector index for an Analog Comparator 1 peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_AC1 = AC1_IRQn, +#endif +}; + +/** @} */ + +#endif diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/tc.c b/feather_sensor_lte/libraries/Adafruit_ASFcore/tc.c new file mode 100644 index 0000000..23e2703 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/tc.c @@ -0,0 +1,685 @@ +/** + * \file + * + * \brief SAM TC - Timer Counter Driver + * + * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#include "tc.h" + +#if TC_ASYNC == true +# include "tc_interrupt.h" +# include + +/** \internal + * Converts a given TC index to its interrupt vector index. + */ +# define _TC_INTERRUPT_VECT_NUM(n, unused) \ + SYSTEM_INTERRUPT_MODULE_TC##n, +#endif + +#if !defined(__DOXYGEN__) +# define _TC_GCLK_ID(n,unused) TPASTE3(TC,n,_GCLK_ID) , +# define _TC_PM_APBCMASK(n,unused) TPASTE2(PM_APBCMASK_TC,n) , + +# define TC_INST_GCLK_ID { MRECURSION(TC_INST_NUM, _TC_GCLK_ID, TC_INST_MAX_ID) } +# define TC_INST_PM_APBCMASK { MRECURSION(TC_INST_NUM, _TC_PM_APBCMASK, TC_INST_MAX_ID) } + +#endif + +/** + * \internal Find the index of given TC module instance. + * + * \param[in] TC module instance pointer. + * + * \return Index of the given TC module instance. + */ +uint8_t _tc_get_inst_index( + Tc *const hw) +{ + /* List of available TC modules. */ + Tc *const tc_modules[TC_INST_NUM] = TC_INSTS; + + /* Find index for TC instance. */ + for (uint32_t i = 0; i < TC_INST_NUM; i++) { + if (hw == tc_modules[i]) { + return i; + } + } + + /* Invalid data given. */ + Assert(false); + return 0; +} + + +/** + * \brief Initializes a hardware TC module instance. + * + * Enables the clock and initializes the TC module, based on the given + * configuration values. + * + * \param[in,out] module_inst Pointer to the software module instance struct + * \param[in] hw Pointer to the TC hardware module + * \param[in] config Pointer to the TC configuration options struct + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The module was initialized successfully + * \retval STATUS_BUSY Hardware module was busy when the + * initialization procedure was attempted + * \retval STATUS_INVALID_ARG An invalid configuration option or argument + * was supplied + * \retval STATUS_ERR_DENIED Hardware module was already enabled, or the + * hardware module is configured in 32-bit + * slave mode + */ +enum status_code tc_init( + struct tc_module *const module_inst, + Tc *const hw, + const struct tc_config *const config) +{ + /* Sanity check arguments */ + Assert(hw); + Assert(module_inst); + Assert(config); + + /* Temporary variable to hold all updates to the CTRLA + * register before they are written to it */ + uint16_t ctrla_tmp = 0; + /* Temporary variable to hold all updates to the CTRLBSET + * register before they are written to it */ + uint8_t ctrlbset_tmp = 0; + /* Temporary variable to hold all updates to the CTRLC + * register before they are written to it */ + uint8_t ctrlc_tmp = 0; + /* Temporary variable to hold TC instance number */ + uint8_t instance = _tc_get_inst_index(hw); + + /* Array of GLCK ID for different TC instances */ + uint8_t inst_gclk_id[] = TC_INST_GCLK_ID; + /* Array of PM APBC mask bit position for different TC instances */ + uint16_t inst_pm_apbmask[] = TC_INST_PM_APBCMASK; + + struct system_pinmux_config pin_config; + struct system_gclk_chan_config gclk_chan_config; + +#if TC_ASYNC == true + /* Initialize parameters */ + for (uint8_t i = 0; i < TC_CALLBACK_N; i++) { + module_inst->callback[i] = NULL; + } + module_inst->register_callback_mask = 0x00; + module_inst->enable_callback_mask = 0x00; + + /* Register this instance for callbacks*/ + _tc_instances[instance] = module_inst; +#endif + + /* Associate the given device instance with the hardware module */ + module_inst->hw = hw; + +#if SAMD09 || SAMD10 || SAMD11 + /* Check if even numbered TC modules are being configured in 32-bit + * counter size. Only odd numbered counters are allowed to be + * configured in 32-bit counter size. + */ + if ((config->counter_size == TC_COUNTER_SIZE_32BIT) && + !((instance + TC_INSTANCE_OFFSET) & 0x01)) { + Assert(false); + return STATUS_ERR_INVALID_ARG; + } +#else + /* Check if odd numbered TC modules are being configured in 32-bit + * counter size. Only even numbered counters are allowed to be + * configured in 32-bit counter size. + */ + if ((config->counter_size == TC_COUNTER_SIZE_32BIT) && + ((instance + TC_INSTANCE_OFFSET) & 0x01)) { + Assert(false); + return STATUS_ERR_INVALID_ARG; + } +#endif + + /* Make the counter size variable in the module_inst struct reflect + * the counter size in the module + */ + module_inst->counter_size = config->counter_size; + + if (hw->COUNT8.CTRLA.reg & TC_CTRLA_SWRST) { + /* We are in the middle of a reset. Abort. */ + return STATUS_BUSY; + } + + if (hw->COUNT8.STATUS.reg & TC_STATUS_SLAVE) { + /* Module is used as a slave */ + return STATUS_ERR_DENIED; + } + + if (hw->COUNT8.CTRLA.reg & TC_CTRLA_ENABLE) { + /* Module must be disabled before initialization. Abort. */ + return STATUS_ERR_DENIED; + } + + /* Set up the TC PWM out pin for channel 0 */ + if (config->pwm_channel[0].enabled) { + system_pinmux_get_config_defaults(&pin_config); + pin_config.mux_position = config->pwm_channel[0].pin_mux; + pin_config.direction = SYSTEM_PINMUX_PIN_DIR_OUTPUT; + system_pinmux_pin_set_config( + config->pwm_channel[0].pin_out, &pin_config); + } + + /* Set up the TC PWM out pin for channel 1 */ + if (config->pwm_channel[1].enabled) { + system_pinmux_get_config_defaults(&pin_config); + pin_config.mux_position = config->pwm_channel[1].pin_mux; + pin_config.direction = SYSTEM_PINMUX_PIN_DIR_OUTPUT; + system_pinmux_pin_set_config( + config->pwm_channel[1].pin_out, &pin_config); + } + + /* Enable the user interface clock in the PM */ + system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, + inst_pm_apbmask[instance]); + + /* Enable the slave counter if counter_size is 32-bit */ + if ((config->counter_size == TC_COUNTER_SIZE_32BIT)) + { + /* Enable the user interface clock in the PM */ + system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, + inst_pm_apbmask[instance + 1]); + } + + /* Setup clock for module */ + system_gclk_chan_get_config_defaults(&gclk_chan_config); + gclk_chan_config.source_generator = config->clock_source; + system_gclk_chan_set_config(inst_gclk_id[instance], &gclk_chan_config); + system_gclk_chan_enable(inst_gclk_id[instance]); + + /* Set ctrla register */ + ctrla_tmp = + (uint32_t)config->counter_size | + (uint32_t)config->wave_generation | + (uint32_t)config->reload_action | + (uint32_t)config->clock_prescaler; + + if (config->run_in_standby) { + ctrla_tmp |= TC_CTRLA_RUNSTDBY; + } + + /* Write configuration to register */ + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + hw->COUNT8.CTRLA.reg = ctrla_tmp; + + /* Set ctrlb register */ + if (config->oneshot) { + ctrlbset_tmp = TC_CTRLBSET_ONESHOT; + } + + if (config->count_direction) { + ctrlbset_tmp |= TC_CTRLBSET_DIR; + } + + /* Clear old ctrlb configuration */ + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + hw->COUNT8.CTRLBCLR.reg = 0xFF; + + /* Check if we actually need to go into a wait state. */ + if (ctrlbset_tmp) { + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + /* Write configuration to register */ + hw->COUNT8.CTRLBSET.reg = ctrlbset_tmp; + } + + /* Set ctrlc register*/ + ctrlc_tmp = config->waveform_invert_output; + for (uint8_t i = 0; i < NUMBER_OF_COMPARE_CAPTURE_CHANNELS; i++) { + if (config->enable_capture_on_channel[i] == true) { + ctrlc_tmp |= (TC_CTRLC_CPTEN(1) << i); + } + } + + /* Write configuration to register */ + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + hw->COUNT8.CTRLC.reg = ctrlc_tmp; + + /* Write configuration to register */ + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Switch for TC counter size */ + switch (module_inst->counter_size) { + case TC_COUNTER_SIZE_8BIT: + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT8.COUNT.reg = + config->counter_8_bit.value; + + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT8.PER.reg = + config->counter_8_bit.period; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT8.CC[0].reg = + config->counter_8_bit.compare_capture_channel[0]; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT8.CC[1].reg = + config->counter_8_bit.compare_capture_channel[1]; + + return STATUS_OK; + + case TC_COUNTER_SIZE_16BIT: + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT16.COUNT.reg + = config->counter_16_bit.value; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT16.CC[0].reg = + config->counter_16_bit.compare_capture_channel[0]; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT16.CC[1].reg = + config->counter_16_bit.compare_capture_channel[1]; + + return STATUS_OK; + + case TC_COUNTER_SIZE_32BIT: + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT32.COUNT.reg + = config->counter_32_bit.value; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT32.CC[0].reg = + config->counter_32_bit.compare_capture_channel[0]; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT32.CC[1].reg = + config->counter_32_bit.compare_capture_channel[1]; + + return STATUS_OK; + } + + Assert(false); + return STATUS_ERR_INVALID_ARG; +} + +/** + * \brief Sets TC module count value. + * + * Sets the current timer count value of a initialized TC module. The + * specified TC module may be started or stopped. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] count New timer count value to set + * + * \return Status of the count update procedure. + * + * \retval STATUS_OK The timer count was updated successfully + * \retval STATUS_ERR_INVALID_ARG An invalid timer counter size was specified + */ +enum status_code tc_set_count_value( + const struct tc_module *const module_inst, + const uint32_t count) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance*/ + Tc *const tc_module = module_inst->hw; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Write to based on the TC counter_size */ + switch (module_inst->counter_size) { + case TC_COUNTER_SIZE_8BIT: + tc_module->COUNT8.COUNT.reg = (uint8_t)count; + return STATUS_OK; + + case TC_COUNTER_SIZE_16BIT: + tc_module->COUNT16.COUNT.reg = (uint16_t)count; + return STATUS_OK; + + case TC_COUNTER_SIZE_32BIT: + tc_module->COUNT32.COUNT.reg = (uint32_t)count; + return STATUS_OK; + + default: + return STATUS_ERR_INVALID_ARG; + } +} + +/** + * \brief Get TC module count value. + * + * Retrieves the current count value of a TC module. The specified TC module + * may be started or stopped. + * + * \param[in] module_inst Pointer to the software module instance struct + * + * \return Count value of the specified TC module. + */ +uint32_t tc_get_count_value( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + Tc *const tc_module = module_inst->hw; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Read from based on the TC counter size */ + switch (module_inst->counter_size) { + case TC_COUNTER_SIZE_8BIT: + return (uint32_t)tc_module->COUNT8.COUNT.reg; + + case TC_COUNTER_SIZE_16BIT: + return (uint32_t)tc_module->COUNT16.COUNT.reg; + + case TC_COUNTER_SIZE_32BIT: + return tc_module->COUNT32.COUNT.reg; + } + + Assert(false); + return 0; +} + +/** + * \brief Gets the TC module capture value. + * + * Retrieves the capture value in the indicated TC module capture channel. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] channel_index Index of the Compare Capture channel to read + * + * \return Capture value stored in the specified timer channel. + */ +uint32_t tc_get_capture_value( + const struct tc_module *const module_inst, + const enum tc_compare_capture_channel channel_index) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + Tc *const tc_module = module_inst->hw; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Read out based on the TC counter size */ + switch (module_inst->counter_size) { + case TC_COUNTER_SIZE_8BIT: + if (channel_index < + NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { + return tc_module->COUNT8.CC[channel_index].reg; + } + + case TC_COUNTER_SIZE_16BIT: + if (channel_index < + NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { + return tc_module->COUNT16.CC[channel_index].reg; + } + + case TC_COUNTER_SIZE_32BIT: + if (channel_index < + NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { + return tc_module->COUNT32.CC[channel_index].reg; + } + } + + Assert(false); + return 0; +} + +/** + * \brief Sets a TC module compare value. + * + * Writes a compare value to the given TC module compare/capture channel. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] channel_index Index of the compare channel to write to + * \param[in] compare New compare value to set + * + * \return Status of the compare update procedure. + * + * \retval STATUS_OK The compare value was updated successfully + * \retval STATUS_ERR_INVALID_ARG An invalid channel index was supplied + */ +enum status_code tc_set_compare_value( + const struct tc_module *const module_inst, + const enum tc_compare_capture_channel channel_index, + const uint32_t compare) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + Tc *const tc_module = module_inst->hw; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Read out based on the TC counter size */ + switch (module_inst->counter_size) { + case TC_COUNTER_SIZE_8BIT: + if (channel_index < + NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { + tc_module->COUNT8.CC[channel_index].reg = + (uint8_t)compare; + return STATUS_OK; + } + + case TC_COUNTER_SIZE_16BIT: + if (channel_index < + NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { + tc_module->COUNT16.CC[channel_index].reg = + (uint16_t)compare; + return STATUS_OK; + } + + case TC_COUNTER_SIZE_32BIT: + if (channel_index < + NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { + tc_module->COUNT32.CC[channel_index].reg = + (uint32_t)compare; + return STATUS_OK; + } + } + + return STATUS_ERR_INVALID_ARG; +} + +/** + * \brief Resets the TC module. + * + * Resets the TC module, restoring all hardware module registers to their + * default values and disabling the module. The TC module will not be + * accessible while the reset is being performed. + * + * \note When resetting a 32-bit counter only the master TC module's instance + * structure should be passed to the function. + * + * \param[in] module_inst Pointer to the software module instance struct + * + * \return Status of the procedure. + * \retval STATUS_OK The module was reset successfully + * \retval STATUS_ERR_UNSUPPORTED_DEV A 32-bit slave TC module was passed to + * the function. Only use reset on master + * TC + */ +enum status_code tc_reset( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + if (tc_module->STATUS.reg & TC_STATUS_SLAVE) { + return STATUS_ERR_UNSUPPORTED_DEV; + } + + /* Disable this module if it is running */ + if (tc_module->CTRLA.reg & TC_CTRLA_ENABLE) { + tc_disable(module_inst); + while (tc_is_syncing(module_inst)) { + /* wait while module is disabling */ + } + } + + /* Reset this TC module */ + tc_module->CTRLA.reg |= TC_CTRLA_SWRST; + + return STATUS_OK; +} + +/** + * \brief Set the timer TOP/period value. + * + * For 8-bit counter size this function writes the top value to the period + * register. + * + * For 16- and 32-bit counter size this function writes the top value to + * Capture Compare register 0. The value in this register can not be used for + * any other purpose. + * + * \note This function is designed to be used in PWM or frequency + * match modes only. When the counter is set to 16- or 32-bit counter + * size. In 8-bit counter size it will always be possible to change the + * top value even in normal mode. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] top_value New timer TOP value to set + * + * \return Status of the TOP set procedure. + * + * \retval STATUS_OK The timer TOP value was updated successfully + * \retval STATUS_ERR_INVALID_ARG The configured TC module counter size in the + * module instance is invalid + */ +enum status_code tc_set_top_value ( + const struct tc_module *const module_inst, + const uint32_t top_value) +{ + Assert(module_inst); + Assert(module_inst->hw); + Assert(top_value); + + Tc *const tc_module = module_inst->hw; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + switch (module_inst->counter_size) { + case TC_COUNTER_SIZE_8BIT: + tc_module->COUNT8.PER.reg = (uint8_t)top_value; + return STATUS_OK; + + case TC_COUNTER_SIZE_16BIT: + tc_module->COUNT16.CC[0].reg = (uint16_t)top_value; + return STATUS_OK; + + case TC_COUNTER_SIZE_32BIT: + tc_module->COUNT32.CC[0].reg = (uint32_t)top_value; + return STATUS_OK; + + default: + Assert(false); + return STATUS_ERR_INVALID_ARG; + } +} diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/tc.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/tc.h new file mode 100644 index 0000000..0ee7006 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/tc.h @@ -0,0 +1,1783 @@ +/** + * \file + * + * \brief SAM TC - Timer Counter Driver + * + * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#ifndef TC_H_INCLUDED +#define TC_H_INCLUDED + +/** + * \defgroup asfdoc_sam0_tc_group SAM Timer/Counter Driver (TC) + * + * This driver for Atmel® | SMART ARM®-based microcontrollers provides an interface for the configuration + * and management of the timer modules within the device, for waveform + * generation and timing operations. The following driver API modes are covered + * by this manual: + * + * - Polled APIs + * \if TC_CALLBACK_MODE + * - Callback APIs + * \endif + * + * + * The following peripherals are used by this module: + * - TC (Timer/Counter) + * + * The following devices can use this module: + * - Atmel | SMART SAM D20/D21 + * - Atmel | SMART SAM R21 + * - Atmel | SMART SAM D09/D10/D11 + * - Atmel | SMART SAM L21/L22 + * - Atmel | SMART SAM DA1 + * - Atmel | SMART SAM C20/C21 + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_tc_prerequisites + * - \ref asfdoc_sam0_tc_module_overview + * - \ref asfdoc_sam0_tc_special_considerations + * - \ref asfdoc_sam0_tc_extra_info + * - \ref asfdoc_sam0_tc_examples + * - \ref asfdoc_sam0_tc_api_overview + * + * + * \section asfdoc_sam0_tc_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * + * \section asfdoc_sam0_tc_module_overview Module Overview + * + * The Timer/Counter (TC) module provides a set of timing and counting related + * functionality, such as the generation of periodic waveforms, the capturing + * of a periodic waveform's frequency/duty cycle, and software timekeeping for + * periodic operations. TC modules can be configured to use an 8-, 16-, or + * 32-bit counter size. + * + * This TC module for the SAM is capable of the following functions: + * + * - Generation of PWM signals + * - Generation of timestamps for events + * - General time counting + * - Waveform period capture + * - Waveform frequency capture + * + * \ref asfdoc_sam0_tc_block_diagram "The diagram below" shows the overview + * of the TC module design. + * + * \anchor asfdoc_sam0_tc_block_diagram + * \image html overview.svg "Basic Overview of the TC Module" + * + * + * \subsection asfdoc_sam0_tc_features Driver Feature Macro Definition + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Driver Feature MacroSupported devices
FEATURE_TC_DOUBLE_BUFFEREDSAM L21/L22/C20/C21
FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2SAM L21/L22/C20/C21
FEATURE_TC_STAMP_PW_CAPTURESAM L21/L22/C20/C21
FEATURE_TC_READ_SYNCSAM L21/L22/C20/C21
FEATURE_TC_IO_CAPTURESAM L21/L22/C20/C21
FEATURE_TC_GENERATE_DMA_TRIGGERSAM L21/L22
+ * \note The specific features are only available in the driver when the + * selected device supports those features. + * + * \subsection asfdoc_sam0_tc_module_overview_func_desc Functional Description + * Independent of the configured counter size, each TC module can be set up + * in one of two different modes; capture and compare. + * + * In capture mode, the counter value is stored when a configurable event + * occurs. This mode can be used to generate timestamps used in event capture, + * or it can be used for the measurement of a periodic input signal's + * frequency/duty cycle. + * + * In compare mode, the counter value is compared against one or more of the + * configured channel compare values. When the counter value coincides with a + * compare value an action can be taken automatically by the module, such as + * generating an output event or toggling a pin when used for frequency or PWM + * signal generation. + * + * \note The connection of events between modules requires the use of the + * \ref asfdoc_sam0_events_group "SAM Event System Driver (EVENTS)" + * to route output event of one module to the input event of another. + * For more information on event routing, refer to the event driver + * documentation. + * + * \subsection asfdoc_sam0_tc_module_overview_tc_size Timer/Counter Size + * Each timer module can be configured in one of three different counter + * sizes; 8-, 16-, and 32-bit. The size of the counter determines the maximum + * value it can count to before an overflow occurs and the count is reset back + * to zero. \ref asfdoc_sam0_tc_count_size_vs_top "The table below" shows the + * maximum values for each of the possible counter sizes. + * + * \anchor asfdoc_sam0_tc_count_size_vs_top + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Timer Counter Sizes and Their Maximum Count Values
Counter sizeMax. (hexadecimal)Max. (decimal)
8-bit0xFF255
16-bit0xFFFF65,535
32-bit0xFFFFFFFF4,294,967,295
+ * + * When using the counter in 16- or 32-bit count mode, Compare Capture + * register 0 (CC0) is used to store the period value when running in PWM + * generation match mode. + * + * When using 32-bit counter size, two 16-bit counters are chained together + * in a cascade formation. Except in SAM D09/D10/D11, Even numbered TC modules + * (e.g. TC0, TC2) can be configured as 32-bit counters. The odd numbered + * counters will act as slaves to the even numbered masters, and will not + * be reconfigurable until the master timer is disabled. The pairing of timer + * modules for 32-bit mode is shown in \ref asfdoc_sam0_tc_module_ms_pairs + * "the table below". + * + * \anchor asfdoc_sam0_tc_module_ms_pairs + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
TC Master and Slave Module Pairings
Master TC ModuleSlave TC Module
TC0TC1
TC2TC3
......
TCn-1TCn
+ * + * In SAM D09/D10/D11, odd numbered TC modules (e.g. TC1) can be configured as 32-bit + * counters. The even numbered(e.g. TC2) counters will act as slaves to the odd + * numbered masters. + * + * \subsection asfdoc_sam0_tc_module_overview_clock Clock Settings + * + * \subsubsection asfdoc_sam0_tc_module_overview_clock_selection Clock Selection + * Each TC peripheral is clocked asynchronously to the system clock by a GCLK + * (Generic Clock) channel. The GCLK channel connects to any of the GCLK + * generators. The GCLK generators are configured to use one of the available + * clock sources on the system such as internal oscillator, external crystals, + * etc. see the \ref asfdoc_sam0_system_clock_group "Generic Clock driver" + *for + * more information. + * + * \subsubsection asfdoc_sam0_tc_module_overview_clock_prescaler Prescaler + * Each TC module in the SAM has its own individual clock prescaler, which + * can be used to divide the input clock frequency used in the counter. This + * prescaler only scales the clock used to provide clock pulses for the counter + * to count, and does not affect the digital register interface portion of + * the module, thus the timer registers will synchronize to the raw GCLK + * frequency input to the module. + * + * As a result of this, when selecting a GCLK frequency and timer prescaler + * value the user application should consider both the timer resolution + * required and the synchronization frequency, to avoid lengthy + * synchronization times of the module if a very slow GCLK frequency is fed + * into the TC module. It is preferable to use a higher module GCLK frequency + * as the input to the timer, and prescale this down as much as possible to + * obtain a suitable counter frequency in latency-sensitive applications. + * + * \subsubsection asfdoc_sam0_tc_module_overview_clock_reloading Reloading + * Timer modules also contain a configurable reload action, used when a + * re-trigger event occurs. Examples of a re-trigger event are the counter + * reaching the maximum value when counting up, or when an event from the event + * system tells the counter to re-trigger. The reload action determines if the + * prescaler should be reset, and when this should happen. The counter will + * always be reloaded with the value it is set to start counting from. The user + * can choose between three different reload actions, described in + * \ref asfdoc_sam0_tc_module_reload_act "the table below". + * + * \anchor asfdoc_sam0_tc_module_reload_act + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
TC Module Reload Actions
Reload actionDescription
\ref TC_RELOAD_ACTION_GCLK Reload TC counter value on next GCLK cycle. Leave prescaler + * as-is.
\ref TC_RELOAD_ACTION_PRESC Reloads TC counter value on next prescaler clock. Leave prescaler + * as-is.
\ref TC_RELOAD_ACTION_RESYNC Reload TC counter value on next GCLK cycle. Clear prescaler to + * zero.
+ * + * The reload action to use will depend on the specific application being + * implemented. One example is when an external trigger for a reload occurs; if + * the TC uses the prescaler, the counter in the prescaler should not have a + * value between zero and the division factor. The TC counter and the counter + * in the prescaler should both start at zero. When the counter is set to + * re-trigger when it reaches the maximum value on the other hand, this is not the + * right option to use. In such a case it would be better if the prescaler is + * left unaltered when the re-trigger happens, letting the counter reset on the + * next GCLK cycle. + * + * \subsection asfdoc_sam0_tc_module_overview_compare_match Compare Match Operations + * In compare match operation, Compare/Capture registers are used in comparison + * with the counter value. When the timer's count value matches the value of a + * compare channel, a user defined action can be taken. + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_timer Basic Timer + * + * A Basic Timer is a simple application where compare match operations is used + * to determine when a specific period has elapsed. In Basic Timer operations, + * one or more values in the module's Compare/Capture registers are used to + * specify the time (as a number of prescaled GCLK cycles) when an action should + * be taken by the microcontroller. This can be an Interrupt Service Routine + * (ISR), event generator via the event system, or a software flag that is + * polled via the user application. + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_wg Waveform Generation + * + * Waveform generation enables the TC module to generate square waves, or if + * combined with an external passive low-pass filter; analog waveforms. + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_wg_pwm Waveform Generation - PWM + * + * Pulse width modulation is a form of waveform generation and a signalling + * technique that can be useful in many situations. When PWM mode is used, + * a digital pulse train with a configurable frequency and duty cycle can be + * generated by the TC module and output to a GPIO pin of the device. + * + * Often PWM is used to communicate a control or information parameter to an + * external circuit or component. Differing impedances of the source generator + * and sink receiver circuits is less of an issue when using PWM compared to + * using an analog voltage value, as noise will not generally affect the + * signal's integrity to a meaningful extent. + * + * \ref asfdoc_sam0_tc_module_pwm_normal_diag "The figure below" illustrates + * operations and different states of the counter and its output when running + * the counter in PWM normal mode. As can be seen, the TOP value is unchanged + * and is set to MAX. The compare match value is changed at several points to + * illustrate the resulting waveform output changes. The PWM output is set to + * normal (i.e. non-inverted) output mode. + * + * \anchor asfdoc_sam0_tc_module_pwm_normal_diag + * \image html pwm_normal_ex.svg "Example of PWM in Normal Mode, and Different Counter Operations" + * + * + * In \ref asfdoc_sam0_tc_module_pwm_match_diag "the figure below", the + * counter is set to generate PWM in Match mode. The PWM output is inverted via + * the appropriate configuration option in the TC driver configuration + * structure. In this example, the counter value is changed once, but the + * compare match value is kept unchanged. As can be seen, it is possible to + * change the TOP value when running in PWM match mode. + * + * \anchor asfdoc_sam0_tc_module_pwm_match_diag + * \image html pwm_match_ex.svg "Example of PWM in Match Mode, and Different Counter Operations" + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_wg_freq Waveform Generation - Frequency + * + * Frequency Generation mode is in many ways identical to PWM + * generation. However, in Frequency Generation a toggle only occurs + * on the output when a match on a capture channels occurs. When the + * match is made, the timer value is reset, resulting in a variable + * frequency square wave with a fixed 50% duty cycle. + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_capt Capture Operations + * + * In capture operations, any event from the event system or a pin change can + * trigger a capture of the counter value. This captured counter value can be + * used as a timestamp for the event, or it can be used in frequency and pulse + * width capture. + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_capt_event_capture Capture Operations - Event + * + * Event capture is a simple use of the capture functionality, + * designed to create timestamps for specific events. When the TC + * module's input capture pin is externally toggled, the current timer + * count value is copied into a buffered register which can then be + * read out by the user application. + * + * Note that when performing any capture operation, there is a risk that the + * counter reaches its top value (MAX) when counting up, or the bottom value + * (zero) when counting down, before the capture event occurs. This can distort + * the result, making event timestamps to appear shorter than reality; the + * user application should check for timer overflow when reading a capture + * result in order to detect this situation and perform an appropriate + * adjustment. + * + * Before checking for a new capture, \ref TC_STATUS_COUNT_OVERFLOW + * should be checked. The response to an overflow error is left to the user + * application, however it may be necessary to clear both the capture overflow + * flag and the capture flag upon each capture reading. + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_capt_pwc Capture Operations - Pulse Width + * + * Pulse Width Capture mode makes it possible to measure the pulse width and + * period of PWM signals. This mode uses two capture channels of the counter. + * This means that the counter module used for Pulse Width Capture can not be + * used for any other purpose. There are two modes for pulse width capture; + * Pulse Width Period (PWP) and Period Pulse Width (PPW). In PWP mode, capture + * channel 0 is used for storing the pulse width and capture channel 1 stores + * the observed period. While in PPW mode, the roles of the two capture channels + * is reversed. + * + * As in the above example it is necessary to poll on interrupt flags to see + * if a new capture has happened and check that a capture overflow error has + * not occurred. + * + * \subsection asfdoc_sam0_tc_module_overview_oneshot One-shot Mode + * + * TC modules can be configured into a one-shot mode. When configured in this + * manner, starting the timer will cause it to count until the next overflow + * or underflow condition before automatically halting, waiting to be manually + * triggered by the user application software or an event signal from the event + * system. + * + * \subsubsection asfdoc_sam0_tc_module_overview_inversion Wave Generation Output Inversion + * + * The output of the wave generation can be inverted by hardware if desired, + * resulting in the logically inverted value being output to the configured + * device GPIO pin. + * + * + * \section asfdoc_sam0_tc_special_considerations Special Considerations + * + * The number of capture compare registers in each TC module is dependent on + * the specific SAM device being used, and in some cases the counter size. + * + * The maximum amount of capture compare registers available in any SAM + * device is two when running in 32-bit mode and four in 8- and 16-bit modes. + * + * + * \section asfdoc_sam0_tc_extra_info Extra Information + * + * For extra information, see \ref asfdoc_sam0_tc_extra. This includes: + * - \ref asfdoc_sam0_tc_extra_acronyms + * - \ref asfdoc_sam0_tc_extra_dependencies + * - \ref asfdoc_sam0_tc_extra_errata + * - \ref asfdoc_sam0_tc_extra_history + * + * + * \section asfdoc_sam0_tc_examples Examples + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_tc_exqsg. + * + * \section asfdoc_sam0_tc_api_overview API Overview + * @{ + */ + +#include "compiler.h" +#include "clock.h" +#include "gclk.h" +#include "pinmux.h" + +// fix for Arduino zero +#if defined(__SAMD21G18A__) + #define SAMD21 1 + #define SAMD21G 1 + #define TC_ASYNC 1 +#endif + +// fix for Trinket/Gemma M0 +#if defined(__SAMD21E18A__) + #define SAMD21 1 + #define SAMD21E 1 + #define TC_ASYNC 1 +#endif + +/** + * Define port features set according to different device family + * @{ +*/ +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) || defined(__DOXYGEN__) +/** TC double buffered. */ +# define FEATURE_TC_DOUBLE_BUFFERED +/** SYNCBUSY scheme version 2. */ +# define FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2 +/** TC time stamp capture and pulse width capture. */ +# define FEATURE_TC_STAMP_PW_CAPTURE +/** Read synchronization of COUNT. */ +# define FEATURE_TC_READ_SYNC +/** IO pin edge capture. */ +# define FEATURE_TC_IO_CAPTURE +#endif + +#if (SAML21XXXB) || defined(__DOXYGEN__) +/** Generate DMA triggers*/ +# define FEATURE_TC_GENERATE_DMA_TRIGGER +#endif +/*@}*/ + +#if !defined(__DOXYGEN__) +#if SAMD20 || SAML21 || SAML22 || SAMC20 || SAMC21 +# define TC_INSTANCE_OFFSET 0 +#endif +#if SAMD21 || SAMR21 || SAMDA1 +# define TC_INSTANCE_OFFSET 3 +#endif +#if SAMD09 || SAMD10 || SAMD11 +# define TC_INSTANCE_OFFSET 1 +#endif + +#if SAMD20 +# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC0_CC8_NUM +#elif SAML21 || SAML22 || SAMC20 || SAMC21 +# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC0_CC_NUM +#elif SAMD09 || SAMD10 || SAMD11 +# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC1_CC8_NUM +#else +# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC3_CC8_NUM + /* Same number for 8-, 16- and 32-bit TC and all TC instances */ +#endif + +/** TC Instance MAX ID Number. */ +#if SAMD20E || SAMD21G || SAMD21E || SAMR21 +# if SAMD21GXXL +# define TC_INST_MAX_ID 7 +# else +# define TC_INST_MAX_ID 5 +# endif +#elif SAML21 || SAMC20 || SAMC21 +# define TC_INST_MAX_ID 4 +#elif SAML22 +# define TC_INST_MAX_ID 3 +#elif SAMD09 || SAMD10 || SAMD11 +# define TC_INST_MAX_ID 2 +#else +# define TC_INST_MAX_ID 7 +#endif + +#endif + +#if TC_ASYNC == true +# include "system_interrupt.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#if TC_ASYNC == true +/** Enum for the possible callback types for the TC module. */ +enum tc_callback { + /** Callback for TC overflow. */ + TC_CALLBACK_OVERFLOW, + /** Callback for capture overflow error. */ + TC_CALLBACK_ERROR, + /** Callback for capture compare channel 0. */ + TC_CALLBACK_CC_CHANNEL0, + /** Callback for capture compare channel 1. */ + TC_CALLBACK_CC_CHANNEL1, +# if !defined(__DOXYGEN__) + /** Number of available callbacks. */ + TC_CALLBACK_N, +# endif +}; +#endif + +/** + * \name Module Status Flags + * + * TC status flags, returned by \ref tc_get_status() and cleared by + * \ref tc_clear_status(). + * + * @{ + */ + +/** Timer channel 0 has matched against its compare value, or has captured a + * new value. + */ +#define TC_STATUS_CHANNEL_0_MATCH (1UL << 0) + +/** Timer channel 1 has matched against its compare value, or has captured a + * new value. + */ +#define TC_STATUS_CHANNEL_1_MATCH (1UL << 1) + +/** Timer register synchronization has completed, and the synchronized count + * value may be read. + */ +#define TC_STATUS_SYNC_READY (1UL << 2) + +/** A new value was captured before the previous value was read, resulting in + * lost data. + */ +#define TC_STATUS_CAPTURE_OVERFLOW (1UL << 3) + +/** The timer count value has overflowed from its maximum value to its minimum + * when counting upward, or from its minimum value to its maximum when + * counting downward. + */ +#define TC_STATUS_COUNT_OVERFLOW (1UL << 4) + +#ifdef FEATURE_TC_DOUBLE_BUFFERED +/** Channel 0 compare or capture buffer valid. */ +#define TC_STATUS_CHN0_BUFFER_VALID (1UL << 5) +/** Channel 1 compare or capture buffer valid. */ +#define TC_STATUS_CHN1_BUFFER_VALID (1UL << 6) +/** Period buffer valid. */ +#define TC_STATUS_PERIOD_BUFFER_VALID (1UL << 7) +#endif +/** @} */ + +/** + * \brief Index of the compare capture channels. + * + * This enum is used to specify which capture/compare channel to do + * operations on. + */ +enum tc_compare_capture_channel { + /** Index of compare capture channel 0. */ + TC_COMPARE_CAPTURE_CHANNEL_0, + /** Index of compare capture channel 1. */ + TC_COMPARE_CAPTURE_CHANNEL_1, +}; + +/** TC wave generation mode. */ +#if SAML21 || SAML22 || SAMC20 || SAMC21 +#define TC_WAVE_GENERATION_NORMAL_FREQ_MODE TC_WAVE_WAVEGEN_NFRQ +#define TC_WAVE_GENERATION_MATCH_FREQ_MODE TC_WAVE_WAVEGEN_MFRQ +#define TC_WAVE_GENERATION_NORMAL_PWM_MODE TC_WAVE_WAVEGEN_NPWM +#define TC_WAVE_GENERATION_MATCH_PWM_MODE TC_WAVE_WAVEGEN_MPWM +#else +#define TC_WAVE_GENERATION_NORMAL_FREQ_MODE TC_CTRLA_WAVEGEN_NFRQ +#define TC_WAVE_GENERATION_MATCH_FREQ_MODE TC_CTRLA_WAVEGEN_MFRQ +#define TC_WAVE_GENERATION_NORMAL_PWM_MODE TC_CTRLA_WAVEGEN_NPWM +#define TC_WAVE_GENERATION_MATCH_PWM_MODE TC_CTRLA_WAVEGEN_MPWM +#endif + +/** + * \brief TC wave generation mode enum. + * + * This enum is used to select which mode to run the wave + * generation in. + * + */ +enum tc_wave_generation { + /** Top is maximum, except in 8-bit counter size where it is the PER + * register. + */ + TC_WAVE_GENERATION_NORMAL_FREQ = TC_WAVE_GENERATION_NORMAL_FREQ_MODE, + + /** Top is CC0, except in 8-bit counter size where it is the PER + * register. + */ + TC_WAVE_GENERATION_MATCH_FREQ = TC_WAVE_GENERATION_MATCH_FREQ_MODE, + + /** Top is maximum, except in 8-bit counter size where it is the PER + * register. + */ + TC_WAVE_GENERATION_NORMAL_PWM = TC_WAVE_GENERATION_NORMAL_PWM_MODE, + + /** Top is CC0, except in 8-bit counter size where it is the PER + * register. + */ + TC_WAVE_GENERATION_MATCH_PWM = TC_WAVE_GENERATION_MATCH_PWM_MODE, +}; + +/** + * \brief Specifies if the counter is 8-, 16-, or 32-bit. + * + * This enum specifies the maximum value it is possible to count to. + */ +enum tc_counter_size { + /** The counter's maximum value is 0xFF, the period register is + * available to be used as top value. + */ + TC_COUNTER_SIZE_8BIT = TC_CTRLA_MODE_COUNT8, + + /** The counter's maximum value is 0xFFFF. There is no separate + * period register, to modify top one of the capture compare + * registers has to be used. This limits the amount of + * available channels. + */ + TC_COUNTER_SIZE_16BIT = TC_CTRLA_MODE_COUNT16, + + /** The counter's maximum value is 0xFFFFFFFF. There is no separate + * period register, to modify top one of the capture compare + * registers has to be used. This limits the amount of + * available channels. + */ + TC_COUNTER_SIZE_32BIT = TC_CTRLA_MODE_COUNT32, +}; + +/** + * \brief TC Counter reload action enum. + * + * This enum specify how the counter and prescaler should reload. + */ +enum tc_reload_action { + /** The counter is reloaded/reset on the next GCLK and starts + * counting on the prescaler clock. + */ + TC_RELOAD_ACTION_GCLK = TC_CTRLA_PRESCSYNC_GCLK, + + /** The counter is reloaded/reset on the next prescaler clock. + */ + TC_RELOAD_ACTION_PRESC = TC_CTRLA_PRESCSYNC_PRESC, + + /** The counter is reloaded/reset on the next GCLK, and the + * prescaler is restarted as well. + */ + TC_RELOAD_ACTION_RESYNC = TC_CTRLA_PRESCSYNC_RESYNC, +}; + +/** + * \brief TC clock prescaler values. + * + * This enum is used to choose the clock prescaler + * configuration. The prescaler divides the clock frequency of the TC + * module to make the counter count slower. + */ +enum tc_clock_prescaler { + /** Divide clock by 1. */ + TC_CLOCK_PRESCALER_DIV1 = TC_CTRLA_PRESCALER(0), + /** Divide clock by 2. */ + TC_CLOCK_PRESCALER_DIV2 = TC_CTRLA_PRESCALER(1), + /** Divide clock by 4. */ + TC_CLOCK_PRESCALER_DIV4 = TC_CTRLA_PRESCALER(2), + /** Divide clock by 8. */ + TC_CLOCK_PRESCALER_DIV8 = TC_CTRLA_PRESCALER(3), + /** Divide clock by 16. */ + TC_CLOCK_PRESCALER_DIV16 = TC_CTRLA_PRESCALER(4), + /** Divide clock by 64. */ + TC_CLOCK_PRESCALER_DIV64 = TC_CTRLA_PRESCALER(5), + /** Divide clock by 256. */ + TC_CLOCK_PRESCALER_DIV256 = TC_CTRLA_PRESCALER(6), + /** Divide clock by 1024. */ + TC_CLOCK_PRESCALER_DIV1024 = TC_CTRLA_PRESCALER(7), +}; + +/** + * \brief TC module count direction. + * + * Timer/Counter count direction. + */ +enum tc_count_direction { + /** Timer should count upward from zero to MAX. */ + TC_COUNT_DIRECTION_UP, + + /** Timer should count downward to zero from MAX. */ + TC_COUNT_DIRECTION_DOWN, +}; + +/** Waveform inversion mode. */ +#if SAML21 || SAML22 || SAMC20 || SAMC21 +#define TC_WAVEFORM_INVERT_CC0_MODE TC_DRVCTRL_INVEN(1) +#define TC_WAVEFORM_INVERT_CC1_MODE TC_DRVCTRL_INVEN(2) +#else +#define TC_WAVEFORM_INVERT_CC0_MODE TC_CTRLC_INVEN(1) +#define TC_WAVEFORM_INVERT_CC1_MODE TC_CTRLC_INVEN(2) +#endif + +/** + * \brief Waveform inversion mode. + * + * Output waveform inversion mode. + */ +enum tc_waveform_invert_output { + /** No inversion of the waveform output. */ + TC_WAVEFORM_INVERT_OUTPUT_NONE = 0, + /** Invert output from compare channel 0. */ + TC_WAVEFORM_INVERT_OUTPUT_CHANNEL_0 = TC_WAVEFORM_INVERT_CC0_MODE, + /** Invert output from compare channel 1. */ + TC_WAVEFORM_INVERT_OUTPUT_CHANNEL_1 = TC_WAVEFORM_INVERT_CC1_MODE, +}; + +/** + * \brief Action to perform when the TC module is triggered by an event. + * + * Event action to perform when the module is triggered by an event. + */ +enum tc_event_action { + /** No event action. */ + TC_EVENT_ACTION_OFF = TC_EVCTRL_EVACT_OFF, + /** Re-trigger on event. */ + TC_EVENT_ACTION_RETRIGGER = TC_EVCTRL_EVACT_RETRIGGER, + /** Increment counter on event. */ + TC_EVENT_ACTION_INCREMENT_COUNTER = TC_EVCTRL_EVACT_COUNT, + /** Start counter on event. */ + TC_EVENT_ACTION_START = TC_EVCTRL_EVACT_START, + + /** Store period in capture register 0, pulse width in capture + * register 1. + */ + TC_EVENT_ACTION_PPW = TC_EVCTRL_EVACT_PPW, + + /** Store pulse width in capture register 0, period in capture + * register 1. + */ + TC_EVENT_ACTION_PWP = TC_EVCTRL_EVACT_PWP, +#ifdef FEATURE_TC_STAMP_PW_CAPTURE + /** Time stamp capture. */ + TC_EVENT_ACTION_STAMP = TC_EVCTRL_EVACT_STAMP, + /** Pulse width capture. */ + TC_EVENT_ACTION_PW = TC_EVCTRL_EVACT_PW, +#endif +}; + +/** + * \brief TC event enable/disable structure. + * + * Event flags for the \ref tc_enable_events() and \ref tc_disable_events(). + */ +struct tc_events { + /** Generate an output event on a compare channel match. */ + bool generate_event_on_compare_channel + [NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; + /** Generate an output event on counter overflow. */ + bool generate_event_on_overflow; + /** Perform the configured event action when an incoming event is signalled. */ + bool on_event_perform_action; + /** Specifies if the input event source is inverted, when used in PWP or + * PPW event action modes. + */ + bool invert_event_input; + /** Specifies which event to trigger if an event is triggered. */ + enum tc_event_action event_action; +}; + +/** + * \brief Configuration struct for TC module in 8-bit size counter mode. + */ +struct tc_8bit_config { + /** Initial timer count value. */ + uint8_t value; + /** Where to count to or from depending on the direction on the counter. */ + uint8_t period; + /** Value to be used for compare match on each channel. */ + uint8_t compare_capture_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; +}; + +/** + * \brief Configuration struct for TC module in 16-bit size counter mode. + */ +struct tc_16bit_config { + /** Initial timer count value. */ + uint16_t value; + /** Value to be used for compare match on each channel. */ + uint16_t compare_capture_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; +}; + +/** + * \brief Configuration struct for TC module in 32-bit size counter mode. + */ +struct tc_32bit_config { + /** Initial timer count value. */ + uint32_t value; + /** Value to be used for compare match on each channel. */ + uint32_t compare_capture_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; +}; + +/** + * \brief Configuration struct for TC module in 32-bit size counter mode. + */ +struct tc_pwm_channel { + /** When \c true, PWM output for the given channel is enabled. */ + bool enabled; + /** Specifies pin output for each channel. */ + uint32_t pin_out; + /** Specifies MUX setting for each output channel pin. */ + uint32_t pin_mux; +}; + +/** + * \brief TC configuration structure. + * + * Configuration struct for a TC instance. This structure should be + * initialized by the \ref tc_get_config_defaults function before being + * modified by the user application. + */ +struct tc_config { + /** GCLK generator used to clock the peripheral. */ + enum gclk_generator clock_source; + + /** When \c true the module is enabled during standby. */ + bool run_in_standby; +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) + /** Run on demand. */ + bool on_demand; +#endif + /** Specifies either 8-, 16-, or 32-bit counter size. */ + enum tc_counter_size counter_size; + /** Specifies the prescaler value for GCLK_TC. */ + enum tc_clock_prescaler clock_prescaler; + /** Specifies which waveform generation mode to use. */ + enum tc_wave_generation wave_generation; + + /** Specifies the reload or reset time of the counter and prescaler + * resynchronization on a re-trigger event for the TC. + */ + enum tc_reload_action reload_action; + + /** Specifies which channel(s) to invert the waveform on. + For SAM L21/L22/C20/C21, it's also used to invert IO input pin. */ + uint8_t waveform_invert_output; + + /** Specifies which channel(s) to enable channel capture + * operation on. + */ + bool enable_capture_on_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; +#ifdef FEATURE_TC_IO_CAPTURE + /** Specifies which channel(s) to enable I/O capture + * operation on. + */ + bool enable_capture_on_IO[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; +#endif + + /** When \c true, one-shot will stop the TC on next hardware or software + * re-trigger event or overflow/underflow. + */ + bool oneshot; + + /** Specifies the direction for the TC to count. */ + enum tc_count_direction count_direction; + + /** Specifies the PWM channel for TC. */ + struct tc_pwm_channel pwm_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; + + /** Access the different counter size settings though this configuration member. */ + union { + /** Struct for 8-bit specific timer configuration. */ + struct tc_8bit_config counter_8_bit; + /** Struct for 16-bit specific timer configuration. */ + struct tc_16bit_config counter_16_bit; + /** Struct for 32-bit specific timer configuration. */ + struct tc_32bit_config counter_32_bit; + }; + +#ifdef FEATURE_TC_DOUBLE_BUFFERED + /** Set to \c true to enable double buffering write. When enabled any write + * through \ref tc_set_top_value(), \ref tc_set_compare_value() and + * will direct to the buffer register as buffered + * value, and the buffered value will be committed to effective register + * on UPDATE condition, if update is not locked. + */ + bool double_buffering_enabled; +#endif +}; + +#if TC_ASYNC == true +/* Forward Declaration for the device instance. */ +struct tc_module; + +/* Type of the callback functions. */ +typedef void (*tc_callback_t)(struct tc_module *const module); +#endif + +/** + * \brief TC software device instance structure. + * + * TC software instance structure, used to retain software state information + * of an associated hardware module instance. + * + * \note The fields of this structure should not be altered by the user + * application; they are reserved for module-internal use only. + */ +struct tc_module { +#if !defined(__DOXYGEN__) + /** Hardware module pointer of the associated Timer/Counter peripheral. */ + Tc *hw; + + /** Size of the initialized Timer/Counter module configuration. */ + enum tc_counter_size counter_size; +# if TC_ASYNC == true + /** Array of callbacks. */ + tc_callback_t callback[TC_CALLBACK_N]; + /** Bit mask for callbacks registered. */ + uint8_t register_callback_mask; + /** Bit mask for callbacks enabled. */ + uint8_t enable_callback_mask; +# endif +#ifdef FEATURE_TC_DOUBLE_BUFFERED + /** Set to \c true to enable double buffering write. */ + bool double_buffering_enabled; +#endif +#endif +}; + +#if !defined(__DOXYGEN__) +uint8_t _tc_get_inst_index( + Tc *const hw); +#endif + +/** + * \name Driver Initialization and Configuration + * @{ + */ + +/** + * \brief Determines if the hardware module(s) are currently synchronizing to + *the bus. + * + * Checks to see if the underlying hardware peripheral module(s) are currently + * synchronizing across multiple clock domains to the hardware bus. This + * function can be used to delay further operations on a module until such time + * that it is ready, to prevent blocking delays for synchronization in the + * user application. + * + * \param[in] module_inst Pointer to the software module instance struct + * + * \return Synchronization status of the underlying hardware module(s). + * + * \retval false If the module has completed synchronization + * \retval true If the module synchronization is ongoing + */ +static inline bool tc_is_syncing( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) + return (tc_module->SYNCBUSY.reg); +#else + return (tc_module->STATUS.reg & TC_STATUS_SYNCBUSY); +#endif +} + +/** + * \brief Initializes config with predefined default values. + * + * This function will initialize a given TC configuration structure to + * a set of known default values. This function should be called on + * any new instance of the configuration structures before being + * modified by the user application. + * + * The default configuration is as follows: + * \li GCLK generator 0 (GCLK main) clock source + * \li 16-bit counter size on the counter + * \li No prescaler + * \li Normal frequency wave generation + * \li GCLK reload action + * \li Don't run in standby + * \li Don't run on demand for SAM L21/L22/C20/C21 + * \li No inversion of waveform output + * \li No capture enabled + * \li No I/O capture enabled for SAM L21/L22/C20/C21 + * \li No event input enabled + * \li Count upward + * \li Don't perform one-shot operations + * \li No event action + * \li No channel 0 PWM output + * \li No channel 1 PWM output + * \li Counter starts on 0 + * \li Capture compare channel 0 set to 0 + * \li Capture compare channel 1 set to 0 + * \li No PWM pin output enabled + * \li Pin and MUX configuration not set + * \li Double buffer disabled (if have this feature) + * + * \param[out] config Pointer to a TC module configuration structure to set + */ +static inline void tc_get_config_defaults( + struct tc_config *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Write default config to config struct */ + config->clock_source = GCLK_GENERATOR_0; + config->counter_size = TC_COUNTER_SIZE_16BIT; + config->clock_prescaler = TC_CLOCK_PRESCALER_DIV1; + config->wave_generation = TC_WAVE_GENERATION_NORMAL_FREQ; + config->reload_action = TC_RELOAD_ACTION_GCLK; + config->run_in_standby = false; +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) + config->on_demand = false; +#endif + config->waveform_invert_output = TC_WAVEFORM_INVERT_OUTPUT_NONE; + config->enable_capture_on_channel[TC_COMPARE_CAPTURE_CHANNEL_0] = false; + config->enable_capture_on_channel[TC_COMPARE_CAPTURE_CHANNEL_1] = false; +#ifdef FEATURE_TC_IO_CAPTURE + config->enable_capture_on_IO[TC_COMPARE_CAPTURE_CHANNEL_0] = false; + config->enable_capture_on_IO[TC_COMPARE_CAPTURE_CHANNEL_1] = false; +#endif + + config->count_direction = TC_COUNT_DIRECTION_UP; + config->oneshot = false; + + config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_0].enabled = false; + config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_0].pin_out = 0; + config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_0].pin_mux = 0; + + config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_1].enabled = false; + config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_1].pin_out = 0; + config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_1].pin_mux = 0; + + config->counter_16_bit.value = 0x0000; + config->counter_16_bit.compare_capture_channel\ + [TC_COMPARE_CAPTURE_CHANNEL_0] = 0x0000; + config->counter_16_bit.compare_capture_channel\ + [TC_COMPARE_CAPTURE_CHANNEL_1] = 0x0000; +#ifdef FEATURE_TC_DOUBLE_BUFFERED + config->double_buffering_enabled = false; +#endif + +} + +enum status_code tc_init( + struct tc_module *const module_inst, + Tc *const hw, + const struct tc_config *const config); + +/** @} */ + +/** + * \name Event Management + * @{ + */ + +/** + * \brief Enables a TC module event input or output. + * + * Enables one or more input or output events to or from the TC module. + * See \ref tc_events for a list of events this module supports. + * + * \note Events cannot be altered while the module is enabled. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] events Struct containing flags of events to enable + */ +static inline void tc_enable_events( + struct tc_module *const module_inst, + struct tc_events *const events) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + Assert(events); + + Tc *const tc_module = module_inst->hw; + + uint32_t event_mask = 0; + + if (events->invert_event_input == true) { + event_mask |= TC_EVCTRL_TCINV; + } + + if (events->on_event_perform_action == true) { + event_mask |= TC_EVCTRL_TCEI; + } + + if (events->generate_event_on_overflow == true) { + event_mask |= TC_EVCTRL_OVFEO; + } + + for (uint8_t i = 0; i < NUMBER_OF_COMPARE_CAPTURE_CHANNELS; i++) { + if (events->generate_event_on_compare_channel[i] == true) { + event_mask |= (TC_EVCTRL_MCEO(1) << i); + } + } + + tc_module->COUNT8.EVCTRL.reg |= event_mask | events->event_action; +} + +/** + * \brief Disables a TC module event input or output. + * + * Disables one or more input or output events to or from the TC module. + * See \ref tc_events for a list of events this module supports. + * + * \note Events cannot be altered while the module is enabled. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] events Struct containing flags of events to disable + */ +static inline void tc_disable_events( + struct tc_module *const module_inst, + struct tc_events *const events) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + Assert(events); + + Tc *const tc_module = module_inst->hw; + + uint32_t event_mask = 0; + + if (events->invert_event_input == true) { + event_mask |= TC_EVCTRL_TCINV; + } + + if (events->on_event_perform_action == true) { + event_mask |= TC_EVCTRL_TCEI; + } + + if (events->generate_event_on_overflow == true) { + event_mask |= TC_EVCTRL_OVFEO; + } + + for (uint8_t i = 0; i < NUMBER_OF_COMPARE_CAPTURE_CHANNELS; i++) { + if (events->generate_event_on_compare_channel[i] == true) { + event_mask |= (TC_EVCTRL_MCEO(1) << i); + } + } + + tc_module->COUNT8.EVCTRL.reg &= ~event_mask; +} + +/** @} */ + +/** + * \name Enable/Disable/Reset + * @{ + */ + +enum status_code tc_reset( + const struct tc_module *const module_inst); + +/** + * \brief Enable the TC module. + * + * Enables a TC module that has been previously initialized. The counter will + * start when the counter is enabled. + * + * \note When the counter is configured to re-trigger on an event, the counter + * will not start until the start function is used. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_enable( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Enable TC module */ + tc_module->CTRLA.reg |= TC_CTRLA_ENABLE; +} + +/** + * \brief Disables the TC module. + * + * Disables a TC module and stops the counter. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_disable( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Disable TC module */ + tc_module->CTRLA.reg &= ~TC_CTRLA_ENABLE; +} + +/** @} */ + +/** + * \name Get/Set Count Value + * @{ + */ + +uint32_t tc_get_count_value( + const struct tc_module *const module_inst); + +enum status_code tc_set_count_value( + const struct tc_module *const module_inst, + const uint32_t count); + +/** @} */ + +/** + * \name Start/Stop Counter + * @{ + */ + +/** + * \brief Stops the counter. + * + * This function will stop the counter. When the counter is stopped + * the value in the count value is set to 0 if the counter was + * counting up, or maximum if the counter was counting + * down when stopped. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_stop_counter( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Write command to execute */ + tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_STOP_Val); +} + +/** + * \brief Starts the counter. + * + * Starts or restarts an initialized TC module's counter. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_start_counter( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Make certain that there are no conflicting commands in the register */ + tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Write command to execute */ + tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_RETRIGGER_Val); +} + +/** @} */ + +#ifdef FEATURE_TC_DOUBLE_BUFFERED +/** + * \name Double Buffering + * @{ + */ + +/** + * \brief Update double buffer. + * + * Update double buffer. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_update_double_buffer( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Make certain that there are no conflicting commands in the register */ + tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Write command to execute */ + tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_UPDATE_Val); +} +/** @} */ +#endif + +#ifdef FEATURE_TC_READ_SYNC +/** + * \name Count Read Synchronization + * @{ + */ + +/** + * \brief Read synchronization of COUNT. + * + * Read synchronization of COUNT. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_sync_read_count( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Make certain that there are no conflicting commands in the register */ + tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Write command to execute */ + tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_READSYNC_Val); +} +/** @} */ +#endif + +#ifdef FEATURE_TC_GENERATE_DMA_TRIGGER +/** + * \name Generate TC DMA Triggers command + * @{ + */ + +/** + * \brief TC DMA Trigger. + * + * TC DMA trigger command. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_dma_trigger_command( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Make certain that there are no conflicting commands in the register */ + tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + +#if (SAMC20) || (SAMC21) || (SAML22) || (SAML21XXXB) + /* Write command to execute */ + tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_DMAOS_Val); +#endif +} +/** @} */ +#endif + +/** + * \name Get Capture Set Compare + * @{ + */ + +uint32_t tc_get_capture_value( + const struct tc_module *const module_inst, + const enum tc_compare_capture_channel channel_index); + +enum status_code tc_set_compare_value( + const struct tc_module *const module_inst, + const enum tc_compare_capture_channel channel_index, + const uint32_t compare_value); + +/** @} */ + +/** + * \name Set Top Value + * @{ + */ + +enum status_code tc_set_top_value( + const struct tc_module *const module_inst, + const uint32_t top_value); + +/** @} */ + +/** + * \name Status Management + * @{ + */ + +/** + * \brief Retrieves the current module status. + * + * Retrieves the status of the module, giving overall state information. + * + * \param[in] module_inst Pointer to the TC software instance struct + * + * \return Bitmask of \c TC_STATUS_* flags. + * + * \retval TC_STATUS_CHANNEL_0_MATCH Timer channel 0 compare/capture match + * \retval TC_STATUS_CHANNEL_1_MATCH Timer channel 1 compare/capture match + * \retval TC_STATUS_SYNC_READY Timer read synchronization has completed + * \retval TC_STATUS_CAPTURE_OVERFLOW Timer capture data has overflowed + * \retval TC_STATUS_COUNT_OVERFLOW Timer count value has overflowed + * \retval TC_STATUS_CHN0_BUFFER_VALID Timer count channel 0 compare/capture buffer valid + * \retval TC_STATUS_CHN1_BUFFER_VALID Timer count channel 1 compare/capture buffer valid + * \retval TC_STATUS_PERIOD_BUFFER_VALID Timer count period buffer valid + */ +static inline uint32_t tc_get_status( + struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + uint32_t int_flags = tc_module->INTFLAG.reg; + + uint32_t status_flags = 0; + + /* Check for TC channel 0 match */ + if (int_flags & TC_INTFLAG_MC(1)) { + status_flags |= TC_STATUS_CHANNEL_0_MATCH; + } + + /* Check for TC channel 1 match */ + if (int_flags & TC_INTFLAG_MC(2)) { + status_flags |= TC_STATUS_CHANNEL_1_MATCH; + } + +#if !defined(FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2) + /* Check for TC read synchronization ready */ + if (int_flags & TC_INTFLAG_SYNCRDY) { + status_flags |= TC_STATUS_SYNC_READY; + } +#endif + + /* Check for TC capture overflow */ + if (int_flags & TC_INTFLAG_ERR) { + status_flags |= TC_STATUS_CAPTURE_OVERFLOW; + } + + /* Check for TC count overflow */ + if (int_flags & TC_INTFLAG_OVF) { + status_flags |= TC_STATUS_COUNT_OVERFLOW; + } +#ifdef FEATURE_TC_DOUBLE_BUFFERED + uint8_t double_buffer_valid_status = tc_module->STATUS.reg; + + /* Check channel 0 compare or capture buffer valid */ + if (double_buffer_valid_status & TC_STATUS_CCBUFV0) { + status_flags |= TC_STATUS_CHN0_BUFFER_VALID; + } + /* Check channel 0 compare or capture buffer valid */ + if (double_buffer_valid_status & TC_STATUS_CCBUFV1) { + status_flags |= TC_STATUS_CHN1_BUFFER_VALID; + } + /* Check period buffer valid */ + if (double_buffer_valid_status & TC_STATUS_PERBUFV) { + status_flags |= TC_STATUS_PERIOD_BUFFER_VALID; + } +#endif + + return status_flags; +} + +/** + * \brief Clears a module status flag. + * + * Clears the given status flag of the module. + * + * \param[in] module_inst Pointer to the TC software instance struct + * \param[in] status_flags Bitmask of \c TC_STATUS_* flags to clear + */ +static inline void tc_clear_status( + struct tc_module *const module_inst, + const uint32_t status_flags) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + uint32_t int_flags = 0; + + /* Check for TC channel 0 match */ + if (status_flags & TC_STATUS_CHANNEL_0_MATCH) { + int_flags |= TC_INTFLAG_MC(1); + } + + /* Check for TC channel 1 match */ + if (status_flags & TC_STATUS_CHANNEL_1_MATCH) { + int_flags |= TC_INTFLAG_MC(2); + } + +#if !defined(FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2) + /* Check for TC read synchronization ready */ + if (status_flags & TC_STATUS_SYNC_READY) { + int_flags |= TC_INTFLAG_SYNCRDY; + } +#endif + + /* Check for TC capture overflow */ + if (status_flags & TC_STATUS_CAPTURE_OVERFLOW) { + int_flags |= TC_INTFLAG_ERR; + } + + /* Check for TC count overflow */ + if (status_flags & TC_STATUS_COUNT_OVERFLOW) { + int_flags |= TC_INTFLAG_OVF; + } + + /* Clear interrupt flag */ + tc_module->INTFLAG.reg = int_flags; +} + +/** @} */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +/** + * \page asfdoc_sam0_tc_extra Extra Information for TC Driver + * + * \section asfdoc_sam0_tc_extra_acronyms Acronyms + * The table below presents the acronyms used in this module: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
AcronymDescription
DMADirect Memory Access
TCTimer Counter
PWMPulse Width Modulation
PWPPulse Width Period
PPWPeriod Pulse Width
+ * + * + * \section asfdoc_sam0_tc_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - \ref asfdoc_sam0_system_pinmux_group "System Pin Multiplexer Driver" + * + * + * \section asfdoc_sam0_tc_extra_errata Errata + * There are no errata related to this driver. + * + * + * \section asfdoc_sam0_tc_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Changelog
Added support for SAMD21 and do some modifications as below: + * \li Clean up in the configuration structure, the counter size + * setting specific registers is accessed through the counter_8_bit, + * counter_16_bit and counter_32_bit structures + * \li All event related settings moved into the tc_event structure
Added automatic digital clock interface enable for the slave TC + * module when a timer is initialized in 32-bit mode
Initial Release
+ */ + +/** + * \page asfdoc_sam0_tc_exqsg Examples for TC Driver + * + * This is a list of the available Quick Start guides (QSGs) and example + * applications for \ref asfdoc_sam0_tc_group. QSGs are simple examples with + * step-by-step instructions to configure and use this driver in a selection of + * use cases. Note that QSGs can be compiled as a standalone application or be + * added to the user application. + * + * - \subpage asfdoc_sam0_tc_basic_use_case + * - \subpage asfdoc_sam0_tc_macth_freq_use_case + * \if TC_CALLBACK_MODE + * - \subpage asfdoc_sam0_tc_timer_use_case + * - \subpage asfdoc_sam0_tc_callback_use_case + * \endif + * - \subpage asfdoc_sam0_tc_dma_use_case + * + * \page asfdoc_sam0_tc_document_revision_history Document Revision History + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Doc. Rev. + * Date + * Comments + *
F08/2015Added support for SAM C21 and SAM L22
E04/2015Added support for SAM L21 and SAM DA1
D12/2014Added timer use case. + * Added support for SAM R21 and SAM D10/D11
C01/2014Added support for SAM D21
B06/2013Corrected documentation typos
A06/2013Initial release
+ */ + +#endif /* TC_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/tc_interrupt.c b/feather_sensor_lte/libraries/Adafruit_ASFcore/tc_interrupt.c new file mode 100644 index 0000000..032be2f --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/tc_interrupt.c @@ -0,0 +1,199 @@ +/** + * \file + * + * \brief SAM TC - Timer Counter Callback Driver + * + * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/* + * Support and FAQ: visit Atmel Support + */ + +#include "tc_interrupt.h" + +void *_tc_instances[TC_INST_NUM]; + +void _tc_interrupt_handler(uint8_t instance); + +/** + * \brief Registers a callback. + * + * Registers a callback function which is implemented by the user. + * + * \note The callback must be enabled by \ref tc_enable_callback, + * in order for the interrupt handler to call it when the conditions for the + * callback type is met. + * + * \param[in] module Pointer to TC software instance struct + * \param[in] callback_func Pointer to callback function + * \param[in] callback_type Callback type given by an enum + */ +enum status_code tc_register_callback( + struct tc_module *const module, + tc_callback_t callback_func, + const enum tc_callback callback_type) +{ + /* Sanity check arguments */ + Assert(module); + Assert(callback_func); + + /* Register callback function */ + module->callback[callback_type] = callback_func; + + /* Set the bit corresponding to the callback_type */ + if (callback_type == TC_CALLBACK_CC_CHANNEL0) { + module->register_callback_mask |= TC_INTFLAG_MC(1); + } + else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { + module->register_callback_mask |= TC_INTFLAG_MC(2); + } + else { + module->register_callback_mask |= (1 << callback_type); + } + return STATUS_OK; +} + +/** + * \brief Unregisters a callback. + * + * Unregisters a callback function implemented by the user. The callback should be + * disabled before it is unregistered. + * + * \param[in] module Pointer to TC software instance struct + * \param[in] callback_type Callback type given by an enum + */ +enum status_code tc_unregister_callback( + struct tc_module *const module, + const enum tc_callback callback_type) +{ + /* Sanity check arguments */ + Assert(module); + + /* Unregister callback function */ + module->callback[callback_type] = NULL; + + /* Clear the bit corresponding to the callback_type */ + if (callback_type == TC_CALLBACK_CC_CHANNEL0) { + module->register_callback_mask &= ~TC_INTFLAG_MC(1); + } + else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { + module->register_callback_mask &= ~TC_INTFLAG_MC(2); + } + else { + module->register_callback_mask &= ~(1 << callback_type); + } + return STATUS_OK; +} + +/** + * \internal ISR handler for TC + * + * Auto-generate a set of interrupt handlers for each TC in the device. + */ +#define _TC_INTERRUPT_HANDLER(n, m) \ + void TC##n##_Handler(void) \ + { \ + _tc_interrupt_handler(m); \ + } + +#if (SAML21E) || (SAML21G) + _TC_INTERRUPT_HANDLER(0,0) + _TC_INTERRUPT_HANDLER(1,1) + _TC_INTERRUPT_HANDLER(4,2) +#else + MRECURSION(TC_INST_NUM, _TC_INTERRUPT_HANDLER, TC_INST_MAX_ID) +#endif + + +/** + * \internal Interrupt Handler for TC module + * + * Handles interrupts as they occur, it will run the callback functions + * that are registered and enabled. + * + * \param[in] instance ID of the TC instance calling the interrupt + * handler. + */ +void _tc_interrupt_handler( + uint8_t instance) +{ + /* Temporary variable */ + uint8_t interrupt_and_callback_status_mask; + + /* Get device instance from the look-up table */ + struct tc_module *module + = (struct tc_module *)_tc_instances[instance]; + + /* Read and mask interrupt flag register */ + interrupt_and_callback_status_mask = module->hw->COUNT8.INTFLAG.reg & + module->register_callback_mask & + module->enable_callback_mask; + + /* Check if an Overflow interrupt has occurred */ + if (interrupt_and_callback_status_mask & TC_INTFLAG_OVF) { + /* Invoke registered and enabled callback function */ + (module->callback[TC_CALLBACK_OVERFLOW])(module); + /* Clear interrupt flag */ + module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_OVF; + } + + /* Check if an Error interrupt has occurred */ + if (interrupt_and_callback_status_mask & TC_INTFLAG_ERR) { + /* Invoke registered and enabled callback function */ + (module->callback[TC_CALLBACK_ERROR])(module); + /* Clear interrupt flag */ + module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_ERR; + } + + /* Check if an Match/Capture Channel 0 interrupt has occurred */ + if (interrupt_and_callback_status_mask & TC_INTFLAG_MC(1)) { + /* Invoke registered and enabled callback function */ + (module->callback[TC_CALLBACK_CC_CHANNEL0])(module); + /* Clear interrupt flag */ + module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_MC(1); + } + + /* Check if an Match/Capture Channel 1 interrupt has occurred */ + if (interrupt_and_callback_status_mask & TC_INTFLAG_MC(2)) { + /* Invoke registered and enabled callback function */ + (module->callback[TC_CALLBACK_CC_CHANNEL1])(module); + /* Clear interrupt flag */ + module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_MC(2); + } +} diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/tc_interrupt.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/tc_interrupt.h new file mode 100644 index 0000000..4e1fd8e --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/tc_interrupt.h @@ -0,0 +1,179 @@ +/** + * \file + * + * \brief SAM TC - Timer Counter Callback Driver + * + * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/* + * Support and FAQ: visit Atmel Support + */ + +#ifndef TC_INTERRUPT_H_INCLUDED +#define TC_INTERRUPT_H_INCLUDED + +#include "tc.h" +#include "system_interrupt.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(__DOXYGEN__) +extern void *_tc_instances[TC_INST_NUM]; + +# define _TC_INTERRUPT_VECT_NUM(n, unused) \ + SYSTEM_INTERRUPT_MODULE_TC##n, +/** + * \internal Get the interrupt vector for the given device instance + * + * \param[in] TC module instance number. + * + * \return Interrupt vector for of the given TC module instance. + */ +static enum system_interrupt_vector _tc_interrupt_get_interrupt_vector( + uint32_t inst_num) +{ + static uint8_t tc_interrupt_vectors[TC_INST_NUM] = + { +#if (SAML21E) || (SAML21G) + SYSTEM_INTERRUPT_MODULE_TC0, + SYSTEM_INTERRUPT_MODULE_TC1, + SYSTEM_INTERRUPT_MODULE_TC4 +#else + MRECURSION(TC_INST_NUM, _TC_INTERRUPT_VECT_NUM, TC_INST_MAX_ID) +#endif + }; + + return (enum system_interrupt_vector)tc_interrupt_vectors[inst_num]; +} +#endif /* !defined(__DOXYGEN__) */ + +/** + * \name Callback Management + * {@ + */ + +enum status_code tc_register_callback( + struct tc_module *const module, + tc_callback_t callback_func, + const enum tc_callback callback_type); + +enum status_code tc_unregister_callback( + struct tc_module *const module, + const enum tc_callback callback_type); + +/** + * \brief Enables callback. + * + * Enables the callback function registered by the \ref + * tc_register_callback. The callback function will be called from the + * interrupt handler when the conditions for the callback type are + * met. This function will also enable the appropriate interrupts. + * + * \param[in] module Pointer to TC software instance struct + * \param[in] callback_type Callback type given by an enum + */ +static inline void tc_enable_callback( + struct tc_module *const module, + const enum tc_callback callback_type) +{ + /* Sanity check arguments */ + Assert(module); + + + /* Enable interrupts for this TC module */ + system_interrupt_enable(_tc_interrupt_get_interrupt_vector(_tc_get_inst_index(module->hw))); + + /* Enable callback */ + if (callback_type == TC_CALLBACK_CC_CHANNEL0) { + module->enable_callback_mask |= TC_INTFLAG_MC(1); + module->hw->COUNT8.INTENSET.reg = TC_INTFLAG_MC(1); + } + else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { + module->enable_callback_mask |= TC_INTFLAG_MC(2); + module->hw->COUNT8.INTENSET.reg = TC_INTFLAG_MC(2); + } + else { + module->enable_callback_mask |= (1 << callback_type); + module->hw->COUNT8.INTENSET.reg = (1 << callback_type); + } +} + +/** + * \brief Disables callback. + * + * Disables the callback function registered by the \ref + * tc_register_callback, and the callback will not be called from the + * interrupt routine. The function will also disable the appropriate + * interrupts. + * + * \param[in] module Pointer to TC software instance struct + * \param[in] callback_type Callback type given by an enum + */ +static inline void tc_disable_callback( + struct tc_module *const module, + const enum tc_callback callback_type){ + /* Sanity check arguments */ + Assert(module); + + /* Disable callback */ + if (callback_type == TC_CALLBACK_CC_CHANNEL0) { + module->hw->COUNT8.INTENCLR.reg = TC_INTFLAG_MC(1); + module->enable_callback_mask &= ~TC_INTFLAG_MC(1); + } + else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { + module->hw->COUNT8.INTENCLR.reg = TC_INTFLAG_MC(2); + module->enable_callback_mask &= ~TC_INTFLAG_MC(2); + } + else { + module->hw->COUNT8.INTENCLR.reg = (1 << callback_type); + module->enable_callback_mask &= ~(1 << callback_type); + } +} + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* TC_INTERRUPT_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/wdt.c b/feather_sensor_lte/libraries/Adafruit_ASFcore/wdt.c new file mode 100644 index 0000000..c5b0895 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/wdt.c @@ -0,0 +1,264 @@ +/** + * \file + * + * \brief SAM Watchdog Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#include "wdt.h" +#include + +/** + * \brief Sets up the WDT hardware module based on the configuration. + * + * Writes a given configuration of a WDT configuration to the + * hardware module, and initializes the internal device struct. + * + * \param[in] config Pointer to the configuration struct + * + * \return Status of the configuration procedure. + * + * \retval STATUS_OK If the module was configured correctly + * \retval STATUS_ERR_INVALID_ARG If invalid argument(s) were supplied + * \retval STATUS_ERR_IO If the Watchdog module is locked to be always on + */ +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) +enum status_code wdt_set_config( + const struct wdt_conf *const config) +{ + /* Sanity check arguments */ + Assert(config); + + Wdt *const WDT_module = WDT; + + /* Turn on the digital interface clock */ + system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBA, MCLK_APBAMASK_WDT); + + /* Check of the Watchdog has been locked to be always on, if so, abort */ + if (wdt_is_locked()) { + return STATUS_ERR_IO; + } + + /* Check for an invalid timeout period, abort if found */ + if (config->timeout_period == WDT_PERIOD_NONE) { + return STATUS_ERR_INVALID_ARG; + } + + /* Make sure the Window and Early Warning periods are not more than the + * reset period, abort if either is invalid */ + if ((config->timeout_period < config->window_period) || + (config->timeout_period < config->early_warning_period)) { + return STATUS_ERR_INVALID_ARG; + } + + /* Disable the Watchdog module */ + WDT_module->CTRLA.reg &= ~WDT_CTRLA_ENABLE; + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + if(config->enable == false) { + return STATUS_OK; + } + + uint32_t new_config = 0; + + /* Update the timeout period value with the requested period */ + new_config |= (config->timeout_period - 1) << WDT_CONFIG_PER_Pos; + + /* Check if the user has requested a reset window period */ + if (config->window_period != WDT_PERIOD_NONE) { + WDT_module->CTRLA.reg |= WDT_CTRLA_WEN; + + /* Update and enable the timeout period value */ + new_config |= (config->window_period - 1) << WDT_CONFIG_WINDOW_Pos; + } else { + /* Ensure the window enable control flag is cleared */ + WDT_module->CTRLA.reg &= ~WDT_CTRLA_WEN; + } + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + /* Write the new Watchdog configuration */ + WDT_module->CONFIG.reg = new_config; + + /* Check if the user has requested an early warning period */ + if (config->early_warning_period != WDT_PERIOD_NONE) { + /* Set the Early Warning period */ + WDT_module->EWCTRL.reg + = (config->early_warning_period - 1) << WDT_EWCTRL_EWOFFSET_Pos; + } + + /* Either enable or lock-enable the Watchdog timer depending on the user + * settings */ + if (config->always_on) { + WDT_module->CTRLA.reg |= WDT_CTRLA_ALWAYSON; + } else { + WDT_module->CTRLA.reg |= WDT_CTRLA_ENABLE; + } + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + return STATUS_OK; +} +#else +enum status_code wdt_set_config( + const struct wdt_conf *const config) +{ + /* Sanity check arguments */ + Assert(config); + + Wdt *const WDT_module = WDT; + + /* Turn on the digital interface clock */ + system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBA, PM_APBAMASK_WDT); + + /* Check of the Watchdog has been locked to be always on, if so, abort */ + if (wdt_is_locked()) { + return STATUS_ERR_IO; + } + + /* Check for an invalid timeout period, abort if found */ + if (config->timeout_period == WDT_PERIOD_NONE) { + return STATUS_ERR_INVALID_ARG; + } + + /* Make sure the Window and Early Warning periods are not more than the + * reset period, abort if either is invalid */ + if ((config->timeout_period < config->window_period) || + (config->timeout_period < config->early_warning_period)) { + return STATUS_ERR_INVALID_ARG; + } + + /* Disable the Watchdog module */ + WDT_module->CTRL.reg &= ~WDT_CTRL_ENABLE; + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + if(config->enable == false) { + return STATUS_OK; + } + + /* Configure GCLK channel and enable clock */ + struct system_gclk_chan_config gclk_chan_conf; + gclk_chan_conf.source_generator = config->clock_source; + system_gclk_chan_set_config(WDT_GCLK_ID, &gclk_chan_conf); + system_gclk_chan_enable(WDT_GCLK_ID); + if (config->always_on) { + system_gclk_chan_lock(WDT_GCLK_ID); + } + + uint32_t new_config = 0; + + /* Update the timeout period value with the requested period */ + new_config |= (config->timeout_period - 1) << WDT_CONFIG_PER_Pos; + + /* Check if the user has requested a reset window period */ + if (config->window_period != WDT_PERIOD_NONE) { + WDT_module->CTRL.reg |= WDT_CTRL_WEN; + + /* Update and enable the timeout period value */ + new_config |= (config->window_period - 1) << WDT_CONFIG_WINDOW_Pos; + } else { + /* Ensure the window enable control flag is cleared */ + WDT_module->CTRL.reg &= ~WDT_CTRL_WEN; + } + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + /* Write the new Watchdog configuration */ + WDT_module->CONFIG.reg = new_config; + + /* Check if the user has requested an early warning period */ + if (config->early_warning_period != WDT_PERIOD_NONE) { + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + /* Set the Early Warning period */ + WDT_module->EWCTRL.reg + = (config->early_warning_period - 1) << WDT_EWCTRL_EWOFFSET_Pos; + } + + /* Either enable or lock-enable the Watchdog timer depending on the user + * settings */ + if (config->always_on) { + WDT_module->CTRL.reg |= WDT_CTRL_ALWAYSON; + } else { + WDT_module->CTRL.reg |= WDT_CTRL_ENABLE; + } + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + return STATUS_OK; +} +#endif + +/** + * \brief Resets the count of the running Watchdog Timer that was previously enabled. + * + * Resets the current count of the Watchdog Timer, restarting the timeout + * period count elapsed. This function should be called after the window + * period (if one was set in the module configuration) but before the timeout + * period to prevent a reset of the system. + */ +void wdt_reset_count(void) +{ + Wdt *const WDT_module = WDT; + + /* Disable the Watchdog module */ + WDT_module->CLEAR.reg = WDT_CLEAR_CLEAR_KEY; + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } +} diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/wdt.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/wdt.h new file mode 100644 index 0000000..c4c37cf --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_ASFcore/wdt.h @@ -0,0 +1,501 @@ +/** + * \file + * + * \brief SAM Watchdog Driver + * + * Copyright (c) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef WDT_H_INCLUDED +#define WDT_H_INCLUDED + +/** + * \defgroup asfdoc_sam0_wdt_group SAM Watchdog Driver (WDT) + * + * This driver for Atmel® | SMART SAM devices provides an interface for the configuration + * and management of the device's Watchdog Timer module, including the enabling, + * disabling, and kicking within the device. The following driver API modes are + * covered by this manual: + * + * - Polled APIs + * \if WDT_CALLBACK_MODE + * - Callback APIs + * \endif + * + * The following peripherals are used by this module: + * - WDT (Watchdog Timer) + * + * The following devices can use this module: + * - Atmel | SMART SAM D20/D21 + * - Atmel | SMART SAM R21 + * - Atmel | SMART SAM D09/D10/D11 + * - Atmel | SMART SAM L21/L22 + * - Atmel | SMART SAM DA1 + * - Atmel | SMART SAM C20/C21 + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_wdt_prerequisites + * - \ref asfdoc_sam0_wdt_module_overview + * - \ref asfdoc_sam0_wdt_special_considerations + * - \ref asfdoc_sam0_wdt_extra_info + * - \ref asfdoc_sam0_wdt_examples + * - \ref asfdoc_sam0_wdt_api_overview + * + * + * \section asfdoc_sam0_wdt_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * + * \section asfdoc_sam0_wdt_module_overview Module Overview + * + * The Watchdog module (WDT) is designed to give an added level of safety in + * critical systems, to ensure a system reset is triggered in the case of a + * deadlock or other software malfunction that prevents normal device operation. + * + * At a basic level, the Watchdog is a system timer with a fixed period; once + * enabled, it will continue to count ticks of its asynchronous clock until + * it is periodically reset, or the timeout period is reached. In the event of a + * Watchdog timeout, the module will trigger a system reset identical to a pulse + * of the device's reset pin, resetting all peripherals to their power-on + * default states and restarting the application software from the reset vector. + * + * In many systems, there is an obvious upper bound to the amount of time each + * iteration of the main application loop can be expected to run, before a + * malfunction can be assumed (either due to a deadlock waiting on hardware or + * software, or due to other means). When the Watchdog is configured with a + * timeout period equal to this upper bound, a malfunction in the system will + * force a full system reset to allow for a graceful recovery. + * + * \subsection asfdoc_sam0_wdt_module_locked_mode Locked Mode + * The Watchdog configuration can be set in the device fuses and locked in + * hardware, so that no software changes can be made to the Watchdog + * configuration. Additionally, the Watchdog can be locked on in software if it + * is not already locked, so that the module configuration cannot be modified + * until a power on reset of the device. + * + * The locked configuration can be used to ensure that faulty software does not + * cause the Watchdog configuration to be changed, preserving the level of + * safety given by the module. + * + * \subsection asfdoc_sam0_wdt_module_window_mode Window Mode + * Just as there is a reasonable upper bound to the time the main program loop + * should take for each iteration, there is also in many applications a lower + * bound, i.e. a \a minimum time for which each loop iteration should run for + * under normal circumstances. To guard against a system failure resetting the + * Watchdog in a tight loop (or a failure in the system application causing the + * main loop to run faster than expected) a "Window" mode can be enabled to + * disallow resetting of the Watchdog counter before a certain period of time. + * If the Watchdog is not reset \a after the window opens but not \a before the + * Watchdog expires, the system will reset. + * + * \subsection asfdoc_sam0_wdt_module_early_warning Early Warning + * In some cases it is desirable to receive an early warning that the Watchdog is + * about to expire, so that some system action (such as saving any system + * configuration data for failure analysis purposes) can be performed before the + * system reset occurs. The Early Warning feature of the Watchdog module allows + * such a notification to be requested; after the configured early warning time + * (but before the expiry of the Watchdog counter) the Early Warning flag will + * become set, so that the user application can take an appropriate action. + * + * \note It is important to note that the purpose of the Early Warning feature + * is \a not to allow the user application to reset the Watchdog; doing + * so will defeat the safety the module gives to the user application. + * Instead, this feature should be used purely to perform any tasks that + * need to be undertaken before the system reset occurs. + * + * \subsection asfdoc_sam0_wdt_module_overview_physical Physical Connection + * + * \ref asfdoc_sam0_wdt_module_int_connections "The figure below" shows how + * this module is interconnected within the device. + * + * \anchor asfdoc_sam0_wdt_module_int_connections + * \dot + * digraph overview { + * rankdir=LR; + * node [label="GCLK*\nGeneric Clock" shape=square] wdt_clock; + * + * subgraph driver { + * node [label=" WDT | Watchdog Counter" shape=record] wdt_module; + * node [label="System Reset Logic" shape=ellipse style=filled fillcolor=lightgray] sys_reset; + * } + * + * wdt_clock -> wdt_module:f1; + * wdt_module:f1 -> sys_reset; + * } + * \enddot + * + * \note Watchdog Counter of SAM L21/L22 is \a not provided by GCLK, but it uses an + * internal 1KHz OSCULP32K output clock. + * + * \section asfdoc_sam0_wdt_special_considerations Special Considerations + * + * On some devices the Watchdog configuration can be fused to be always on in + * a particular configuration; if this mode is enabled the Watchdog is not + * software configurable and can have its count reset and early warning state + * checked/cleared only. + * + * \section asfdoc_sam0_wdt_extra_info Extra Information + * + * For extra information, see \ref asfdoc_sam0_wdt_extra. This includes: + * - \ref asfdoc_sam0_wdt_extra_acronyms + * - \ref asfdoc_sam0_wdt_extra_dependencies + * - \ref asfdoc_sam0_wdt_extra_errata + * - \ref asfdoc_sam0_wdt_extra_history + * + * + * \section asfdoc_sam0_wdt_examples Examples + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_wdt_exqsg. + * + * \section asfdoc_sam0_wdt_api_overview API Overview + * @{ + */ + +#include +#include +#include + +#if WDT_CALLBACK_MODE == true +# include "wdt_callback.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Watchdog Timer period configuration enum. + * + * Enum for the possible period settings of the Watchdog timer module, for + * values requiring a period as a number of Watchdog timer clock ticks. + */ +enum wdt_period { + /** No Watchdog period. This value can only be used when setting the + * Window and Early Warning periods; its use as the Watchdog Reset + * Period is invalid. */ + WDT_PERIOD_NONE = 0, + /** Watchdog period of 8 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_8CLK = 1, + /** Watchdog period of 16 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_16CLK = 2, + /** Watchdog period of 32 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_32CLK = 3, + /** Watchdog period of 64 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_64CLK = 4, + /** Watchdog period of 128 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_128CLK = 5, + /** Watchdog period of 256 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_256CLK = 6, + /** Watchdog period of 512 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_512CLK = 7, + /** Watchdog period of 1024 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_1024CLK = 8, + /** Watchdog period of 2048 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_2048CLK = 9, + /** Watchdog period of 4096 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_4096CLK = 10, + /** Watchdog period of 8192 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_8192CLK = 11, + /** Watchdog period of 16384 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_16384CLK = 12, +}; + +/** + * \brief Watchdog Timer configuration structure. + * + * Configuration structure for a Watchdog Timer instance. This + * structure should be initialized by the \ref wdt_get_config_defaults() + * function before being modified by the user application. + */ +struct wdt_conf { + /** If \c true, the Watchdog will be locked to the current configuration + * settings when the Watchdog is enabled. */ + bool always_on; + /** Enable/Disable the Watchdog Timer. */ + bool enable; +#if !(SAML21) && !(SAML22) && !(SAMC20) && !(SAMC21) + /** GCLK generator used to clock the peripheral except SAM L21/L22/C21/C20.*/ + enum gclk_generator clock_source; +#endif + /** Number of Watchdog timer clock ticks until the Watchdog expires. */ + enum wdt_period timeout_period; + /** Number of Watchdog timer clock ticks until the reset window opens. */ + enum wdt_period window_period; + /** Number of Watchdog timer clock ticks until the early warning flag is + * set. */ + enum wdt_period early_warning_period; +}; + +/** \name Configuration and Initialization + * @{ + */ + +/** + * \brief Determines if the hardware module(s) are currently synchronizing to the bus. + * + * Checks to see if the underlying hardware peripheral module(s) are currently + * synchronizing across multiple clock domains to the hardware bus. This + * function can be used to delay further operations on a module until such time + * that it is ready, to prevent blocking delays for synchronization in the + * user application. + * + * \return Synchronization status of the underlying hardware module(s). + * + * \retval false If the module has completed synchronization + * \retval true If the module synchronization is ongoing + */ +static inline bool wdt_is_syncing(void) +{ + Wdt *const WDT_module = WDT; + +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) + if (WDT_module->SYNCBUSY.reg) { +#else + if (WDT_module->STATUS.reg & WDT_STATUS_SYNCBUSY) { +#endif + return true; + } + + return false; +} + +/** + * \brief Initializes a Watchdog Timer configuration structure to defaults. + * + * Initializes a given Watchdog Timer configuration structure to a set of + * known default values. This function should be called on all new + * instances of these configuration structures before being modified by the + * user application. + * + * The default configuration is as follows: + * \li Not locked, to allow for further (re-)configuration + * \li Enable WDT + * \li Watchdog timer sourced from Generic Clock Channel 4 + * \li A timeout period of 16384 clocks of the Watchdog module clock + * \li No window period, so that the Watchdog count can be reset at any time + * \li No early warning period to indicate the Watchdog will soon expire + * + * \param[out] config Configuration structure to initialize to default values + */ +static inline void wdt_get_config_defaults( + struct wdt_conf *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Default configuration values */ + config->always_on = false; + config->enable = true; +#if !(SAML21) && !(SAML22) && !(SAMC20) && !(SAMC21) + config->clock_source = GCLK_GENERATOR_4; +#endif + config->timeout_period = WDT_PERIOD_16384CLK; + config->window_period = WDT_PERIOD_NONE; + config->early_warning_period = WDT_PERIOD_NONE; +} + +enum status_code wdt_set_config( + const struct wdt_conf *const config); + +/** \brief Determines if the Watchdog timer is currently locked in an enabled state. + * + * Determines if the Watchdog timer is currently enabled and locked, so that + * it cannot be disabled or otherwise reconfigured. + * + * \return Current Watchdog lock state. + */ +static inline bool wdt_is_locked(void) +{ + Wdt *const WDT_module = WDT; + +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) + return (WDT_module->CTRLA.reg & WDT_CTRLA_ALWAYSON); +#else + return (WDT_module->CTRL.reg & WDT_CTRL_ALWAYSON); +#endif +} + +/** @} */ + +/** \name Timeout and Early Warning Management + * @{ + */ + +/** \brief Clears the Watchdog timer early warning period elapsed flag. + * + * Clears the Watchdog timer early warning period elapsed flag, so that a new + * early warning period can be detected. + */ +static inline void wdt_clear_early_warning(void) +{ + Wdt *const WDT_module = WDT; + + WDT_module->INTFLAG.reg = WDT_INTFLAG_EW; +} + +/** \brief Determines if the Watchdog timer early warning period has elapsed. + * + * Determines if the Watchdog timer early warning period has elapsed. + * + * \note If no early warning period was configured, the value returned by this + * function is invalid. + * + * \return Current Watchdog Early Warning state. + */ +static inline bool wdt_is_early_warning(void) +{ + Wdt *const WDT_module = WDT; + + return (WDT_module->INTFLAG.reg & WDT_INTFLAG_EW); +} + +void wdt_reset_count(void); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +/** @} */ + +/** + * \page asfdoc_sam0_wdt_extra Extra Information for WDT Driver + * + * \section asfdoc_sam0_wdt_extra_acronyms Acronyms + * The table below presents the acronyms used in this module: + * + * + * + * + * + * + * + * + * + * + *
AcronymDescription
WDTWatchdog Timer
+ * + * + * \section asfdoc_sam0_wdt_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - \ref asfdoc_sam0_system_clock_group "System Clock Driver" + * + * + * \section asfdoc_sam0_wdt_extra_errata Errata + * There are no errata related to this driver. + * + * + * \section asfdoc_sam0_wdt_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * + * + * + * + * + * + *
Changelog
Driver updated to follow driver type convention: + * \li wdt_init, wdt_enable, wdt_disable functions removed + * \li wdt_set_config function added + * \li WDT module enable state moved inside the configuration struct
Initial Release
+ */ + +/** + * \page asfdoc_sam0_wdt_exqsg Examples for WDT Driver + * + * This is a list of the available Quick Start guides (QSGs) and example + * applications for \ref asfdoc_sam0_wdt_group. QSGs are simple examples with + * step-by-step instructions to configure and use this driver in a selection of + * use cases. Note that QSGs can be compiled as a standalone application or be + * added to the user application. + * + * - \subpage asfdoc_sam0_wdt_basic_use_case + * \if WDT_CALLBACK_MODE + * - \subpage asfdoc_sam0_wdt_callback_use_case + * \endif + * + * \page asfdoc_sam0_wdt_document_revision_history Document Revision History + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Doc. Rev. + * Date + * Comments + *
E08/2015Added support for SAM L21/L22, SAM DA1, and SAM C20/C2
D12/2014Added SAMR21 and SAMD10/D11 support
C01/2014Add SAMD21 support
B06/2013Corrected documentation typos
A06/2013Initial release
+ */ + +#endif /* WDT_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp b/feather_sensor_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp new file mode 100644 index 0000000..fe721be --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp @@ -0,0 +1,2079 @@ +/*************************************************** + This is a library for our Adafruit FONA Cellular Module + + Designed specifically to work with the Adafruit FONA + ----> http://www.adafruit.com/products/1946 + ----> http://www.adafruit.com/products/1963 + + These displays use TTL Serial to communicate, 2 pins are required to + interface + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ****************************************************/ + // next line per http://postwarrior.com/arduino-ethershield-error-prog_char-does-not-name-a-type/ + +#include "Adafruit_FONA.h" + + + + +Adafruit_FONA::Adafruit_FONA(int8_t rst) +{ + _rstpin = rst; + + apn = F("FONAnet"); + apnusername = 0; + apnpassword = 0; + mySerial = 0; + httpsredirect = false; + useragent = F("FONA"); + ok_reply = F("OK"); +} + +uint8_t Adafruit_FONA::type(void) { + return _type; +} + +boolean Adafruit_FONA::begin(Stream &port) { + mySerial = &port; + + pinMode(_rstpin, OUTPUT); + digitalWrite(_rstpin, HIGH); + delay(10); + digitalWrite(_rstpin, LOW); + delay(100); + digitalWrite(_rstpin, HIGH); + + DEBUG_PRINTLN(F("Attempting to open comm with ATs")); + // give 7 seconds to reboot + int16_t timeout = 7000; + + while (timeout > 0) { + while (mySerial->available()) mySerial->read(); + if (sendCheckReply(F("AT"), ok_reply)) + break; + while (mySerial->available()) mySerial->read(); + if (sendCheckReply(F("AT"), F("AT"))) + break; + delay(500); + timeout-=500; + } + +#ifdef ADAFRUIT_FONA_DEBUG + if (timeout <= 0) + DEBUG_PRINTLN(F("Timeout: No response to AT... last ditch attempt.")); +#endif + + sendCheckReply(F("AT"), ok_reply); + delay(100); + sendCheckReply(F("AT"), ok_reply); + delay(100); + sendCheckReply(F("AT"), ok_reply); + delay(100); + + // turn off Echo! + sendCheckReply(F("ATE0"), ok_reply); + delay(100); + + if (! sendCheckReply(F("ATE0"), ok_reply)) { + return false; + } + + // turn on hangupitude + sendCheckReply(F("AT+CVHU=0"), ok_reply); + + delay(100); + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN("ATI"); + + mySerial->println("ATI"); + readline(500, true); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + + + if (prog_char_strstr(replybuffer, (prog_char *)F("SIM808 R14")) != 0) { + _type = FONA808_V2; + } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIM808 R13")) != 0) { + _type = FONA808_V1; + } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIM800 R14")) != 0) { + _type = FONA800L; + } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIMCOM_SIM5320A")) != 0) { + _type = FONA3G_A; + } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIMCOM_SIM5320E")) != 0) { + _type = FONA3G_E; + } + + if (_type == FONA800L) { + // determine if L or H + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN("AT+GMM"); + + mySerial->println("AT+GMM"); + readline(500, true); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + + if (prog_char_strstr(replybuffer, (prog_char *)F("SIM800H")) != 0) { + _type = FONA800H; + } + } + +#if defined(FONA_PREF_SMS_STORAGE) + sendCheckReply(F("AT+CPMS=\"" FONA_PREF_SMS_STORAGE "\""), ok_reply); +#endif + + return true; +} + + +/********* Serial port ********************************************/ +boolean Adafruit_FONA::setBaudrate(uint16_t baud) { + return sendCheckReply(F("AT+IPREX="), baud, ok_reply); +} + +/********* Real Time Clock ********************************************/ + +boolean Adafruit_FONA::readRTC(uint8_t *year, uint8_t *month, uint8_t *date, uint8_t *hr, uint8_t *min, uint8_t *sec) { + uint16_t v; + sendParseReply(F("AT+CCLK?"), F("+CCLK: "), &v, '/', 0); + *year = v; + + DEBUG_PRINTLN(*year); +} + +boolean Adafruit_FONA::enableRTC(uint8_t i) { + if (! sendCheckReply(F("AT+CLTS="), i, ok_reply)) + return false; + return sendCheckReply(F("AT&W"), ok_reply); +} + + +/********* BATTERY & ADC ********************************************/ + +/* returns value in mV (uint16_t) */ +boolean Adafruit_FONA::getBattVoltage(uint16_t *v) { + return sendParseReply(F("AT+CBC"), F("+CBC: "), v, ',', 2); +} + +/* returns value in mV (uint16_t) */ +boolean Adafruit_FONA_3G::getBattVoltage(uint16_t *v) { + float f; + boolean b = sendParseReply(F("AT+CBC"), F("+CBC: "), &f, ',', 2); + *v = f*1000; + return b; +} + + +/* returns the percentage charge of battery as reported by sim800 */ +boolean Adafruit_FONA::getBattPercent(uint16_t *p) { + return sendParseReply(F("AT+CBC"), F("+CBC: "), p, ',', 1); +} + +boolean Adafruit_FONA::getADCVoltage(uint16_t *v) { + return sendParseReply(F("AT+CADC?"), F("+CADC: 1,"), v); +} + +/********* SIM ***********************************************************/ + +uint8_t Adafruit_FONA::unlockSIM(char *pin) +{ + char sendbuff[14] = "AT+CPIN="; + sendbuff[8] = pin[0]; + sendbuff[9] = pin[1]; + sendbuff[10] = pin[2]; + sendbuff[11] = pin[3]; + sendbuff[12] = '\0'; + + return sendCheckReply(sendbuff, ok_reply); +} + +uint8_t Adafruit_FONA::getSIMCCID(char *ccid) { + getReply(F("AT+CCID")); + // up to 28 chars for reply, 20 char total ccid + if (replybuffer[0] == '+') { + // fona 3g? + strncpy(ccid, replybuffer+8, 20); + } else { + // fona 800 or 800 + strncpy(ccid, replybuffer, 20); + } + ccid[20] = 0; + + readline(); // eat 'OK' + + return strlen(ccid); +} + +/********* IMEI **********************************************************/ + +uint8_t Adafruit_FONA::getIMEI(char *imei) { + getReply(F("AT+GSN")); + + // up to 15 chars + strncpy(imei, replybuffer, 15); + imei[15] = 0; + + readline(); // eat 'OK' + + return strlen(imei); +} + +/********* NETWORK *******************************************************/ + +uint8_t Adafruit_FONA::getNetworkStatus(void) { + uint16_t status; + + if (! sendParseReply(F("AT+CREG?"), F("+CREG: "), &status, ',', 1)) return 0; + + return status; +} + + +uint8_t Adafruit_FONA::getRSSI(void) { + uint16_t reply; + + if (! sendParseReply(F("AT+CSQ"), F("+CSQ: "), &reply) ) return 0; + + return reply; +} + +/********* AUDIO *******************************************************/ + +boolean Adafruit_FONA::setAudio(uint8_t a) { + // 0 is headset, 1 is external audio + if (a > 1) return false; + + return sendCheckReply(F("AT+CHFA="), a, ok_reply); +} + +uint8_t Adafruit_FONA::getVolume(void) { + uint16_t reply; + + if (! sendParseReply(F("AT+CLVL?"), F("+CLVL: "), &reply) ) return 0; + + return reply; +} + +boolean Adafruit_FONA::setVolume(uint8_t i) { + return sendCheckReply(F("AT+CLVL="), i, ok_reply); +} + + +boolean Adafruit_FONA::playDTMF(char dtmf) { + char str[4]; + str[0] = '\"'; + str[1] = dtmf; + str[2] = '\"'; + str[3] = 0; + return sendCheckReply(F("AT+CLDTMF=3,"), str, ok_reply); +} + +boolean Adafruit_FONA::playToolkitTone(uint8_t t, uint16_t len) { + return sendCheckReply(F("AT+STTONE=1,"), t, len, ok_reply); +} + +boolean Adafruit_FONA_3G::playToolkitTone(uint8_t t, uint16_t len) { + if (! sendCheckReply(F("AT+CPTONE="), t, ok_reply)) + return false; + delay(len); + return sendCheckReply(F("AT+CPTONE=0"), ok_reply); +} + +boolean Adafruit_FONA::setMicVolume(uint8_t a, uint8_t level) { + // 0 is headset, 1 is external audio + if (a > 1) return false; + + return sendCheckReply(F("AT+CMIC="), a, level, ok_reply); +} + +/********* FM RADIO *******************************************************/ + + +boolean Adafruit_FONA::FMradio(boolean onoff, uint8_t a) { + if (! onoff) { + return sendCheckReply(F("AT+FMCLOSE"), ok_reply); + } + + // 0 is headset, 1 is external audio + if (a > 1) return false; + + return sendCheckReply(F("AT+FMOPEN="), a, ok_reply); +} + +boolean Adafruit_FONA::tuneFMradio(uint16_t station) { + // Fail if FM station is outside allowed range. + if ((station < 870) || (station > 1090)) + return false; + + return sendCheckReply(F("AT+FMFREQ="), station, ok_reply); +} + +boolean Adafruit_FONA::setFMVolume(uint8_t i) { + // Fail if volume is outside allowed range (0-6). + if (i > 6) { + return false; + } + // Send FM volume command and verify response. + return sendCheckReply(F("AT+FMVOLUME="), i, ok_reply); +} + +int8_t Adafruit_FONA::getFMVolume() { + uint16_t level; + + if (! sendParseReply(F("AT+FMVOLUME?"), F("+FMVOLUME: "), &level) ) return 0; + + return level; +} + +int8_t Adafruit_FONA::getFMSignalLevel(uint16_t station) { + // Fail if FM station is outside allowed range. + if ((station < 875) || (station > 1080)) { + return -1; + } + + // Send FM signal level query command. + // Note, need to explicitly send timeout so right overload is chosen. + getReply(F("AT+FMSIGNAL="), station, FONA_DEFAULT_TIMEOUT_MS); + // Check response starts with expected value. + char *p = prog_char_strstr(replybuffer, PSTR("+FMSIGNAL: ")); + if (p == 0) return -1; + p+=11; + // Find second colon to get start of signal quality. + p = strchr(p, ':'); + if (p == 0) return -1; + p+=1; + // Parse signal quality. + int8_t level = atoi(p); + readline(); // eat the "OK" + return level; +} + +/********* PWM/BUZZER **************************************************/ + +boolean Adafruit_FONA::setPWM(uint16_t period, uint8_t duty) { + if (period > 2000) return false; + if (duty > 100) return false; + + return sendCheckReply(F("AT+SPWM=0,"), period, duty, ok_reply); +} + +/********* CALL PHONES **************************************************/ +boolean Adafruit_FONA::callPhone(char *number) { + char sendbuff[35] = "ATD"; + strncpy(sendbuff+3, number, min(30, strlen(number))); + uint8_t x = strlen(sendbuff); + sendbuff[x] = ';'; + sendbuff[x+1] = 0; + //DEBUG_PRINTLN(sendbuff); + + return sendCheckReply(sendbuff, ok_reply); +} + + +uint8_t Adafruit_FONA::getCallStatus(void) { + uint16_t phoneStatus; + + if (! sendParseReply(F("AT+CPAS"), F("+CPAS: "), &phoneStatus)) + return FONA_CALL_FAILED; // 1, since 0 is actually a known, good reply + + return phoneStatus; // 0 ready, 2 unkown, 3 ringing, 4 call in progress +} + +boolean Adafruit_FONA::hangUp(void) { + return sendCheckReply(F("ATH0"), ok_reply); +} + +boolean Adafruit_FONA_3G::hangUp(void) { + getReply(F("ATH")); + + return (prog_char_strstr(replybuffer, (prog_char *)F("VOICE CALL: END")) != 0); +} + +boolean Adafruit_FONA::pickUp(void) { + return sendCheckReply(F("ATA"), ok_reply); +} + +boolean Adafruit_FONA_3G::pickUp(void) { + return sendCheckReply(F("ATA"), F("VOICE CALL: BEGIN")); +} + + +void Adafruit_FONA::onIncomingCall() { + + DEBUG_PRINT(F("> ")); DEBUG_PRINTLN(F("Incoming call...")); + + Adafruit_FONA::_incomingCall = true; +} + +boolean Adafruit_FONA::_incomingCall = false; + +boolean Adafruit_FONA::callerIdNotification(boolean enable, uint8_t interrupt) { + if(enable){ + attachInterrupt(interrupt, onIncomingCall, FALLING); + return sendCheckReply(F("AT+CLIP=1"), ok_reply); + } + + detachInterrupt(interrupt); + return sendCheckReply(F("AT+CLIP=0"), ok_reply); +} + +boolean Adafruit_FONA::incomingCallNumber(char* phonenum) { + //+CLIP: "",145,"",0,"",0 + if(!Adafruit_FONA::_incomingCall) + return false; + + readline(); + while(!prog_char_strcmp(replybuffer, (prog_char*)F("RING")) == 0) { + flushInput(); + readline(); + } + + readline(); //reads incoming phone number line + + parseReply(F("+CLIP: \""), phonenum, '"'); + + + DEBUG_PRINT(F("Phone Number: ")); + DEBUG_PRINTLN(replybuffer); + + + Adafruit_FONA::_incomingCall = false; + return true; +} + +/********* SMS **********************************************************/ + +uint8_t Adafruit_FONA::getSMSInterrupt(void) { + uint16_t reply; + + if (! sendParseReply(F("AT+CFGRI?"), F("+CFGRI: "), &reply) ) return 0; + + return reply; +} + +boolean Adafruit_FONA::setSMSInterrupt(uint8_t i) { + return sendCheckReply(F("AT+CFGRI="), i, ok_reply); +} + +int8_t Adafruit_FONA::getNumSMS(void) { + uint16_t numsms; + + // get into text mode + if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return -1; + + // ask how many sms are stored + if (sendParseReply(F("AT+CPMS?"), F("\"SM\","), &numsms)) + return numsms; + if (sendParseReply(F("AT+CPMS?"), F("\"SM_P\","), &numsms)) + return numsms; + return -1; +} + +// Reading SMS's is a bit involved so we don't use helpers that may cause delays or debug +// printouts! +boolean Adafruit_FONA::readSMS(uint8_t i, char *smsbuff, + uint16_t maxlen, uint16_t *readlen) { + // text mode + if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return false; + + // show all text mode parameters + if (! sendCheckReply(F("AT+CSDH=1"), ok_reply)) return false; + + // parse out the SMS len + uint16_t thesmslen = 0; + + + DEBUG_PRINT(F("AT+CMGR=")); + DEBUG_PRINTLN(i); + + + //getReply(F("AT+CMGR="), i, 1000); // do not print debug! + mySerial->print(F("AT+CMGR=")); + mySerial->println(i); + readline(1000); // timeout + + //DEBUG_PRINT(F("Reply: ")); DEBUG_PRINTLN(replybuffer); + // parse it out... + + + DEBUG_PRINTLN(replybuffer); + + + if (! parseReply(F("+CMGR:"), &thesmslen, ',', 11)) { + *readlen = 0; + return false; + } + + readRaw(thesmslen); + + flushInput(); + + uint16_t thelen = min(maxlen, strlen(replybuffer)); + strncpy(smsbuff, replybuffer, thelen); + smsbuff[thelen] = 0; // end the string + + + DEBUG_PRINTLN(replybuffer); + + *readlen = thelen; + return true; +} + +// Retrieve the sender of the specified SMS message and copy it as a string to +// the sender buffer. Up to senderlen characters of the sender will be copied +// and a null terminator will be added if less than senderlen charactesr are +// copied to the result. Returns true if a result was successfully retrieved, +// otherwise false. +boolean Adafruit_FONA::getSMSSender(uint8_t i, char *sender, int senderlen) { + // Ensure text mode and all text mode parameters are sent. + if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return false; + if (! sendCheckReply(F("AT+CSDH=1"), ok_reply)) return false; + + + DEBUG_PRINT(F("AT+CMGR=")); + DEBUG_PRINTLN(i); + + + // Send command to retrieve SMS message and parse a line of response. + mySerial->print(F("AT+CMGR=")); + mySerial->println(i); + readline(1000); + + + DEBUG_PRINTLN(replybuffer); + + + // Parse the second field in the response. + boolean result = parseReplyQuoted(F("+CMGR:"), sender, senderlen, ',', 1); + // Drop any remaining data from the response. + flushInput(); + return result; +} + +boolean Adafruit_FONA::sendSMS(char *smsaddr, char *smsmsg) { + if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return -1; + + char sendcmd[30] = "AT+CMGS=\""; + strncpy(sendcmd+9, smsaddr, 30-9-2); // 9 bytes beginning, 2 bytes for close quote + null + sendcmd[strlen(sendcmd)] = '\"'; + + if (! sendCheckReply(sendcmd, F("> "))) return false; + + DEBUG_PRINT(F("> ")); DEBUG_PRINTLN(smsmsg); + + mySerial->println(smsmsg); + mySerial->println(); + mySerial->write(0x1A); + + DEBUG_PRINTLN("^Z"); + + if ( (_type == FONA3G_A) || (_type == FONA3G_E) ) { + // Eat two sets of CRLF + readline(200); + //DEBUG_PRINT("Line 1: "); DEBUG_PRINTLN(strlen(replybuffer)); + readline(200); + //DEBUG_PRINT("Line 2: "); DEBUG_PRINTLN(strlen(replybuffer)); + } + readline(10000); // read the +CMGS reply, wait up to 10 seconds!!! + //DEBUG_PRINT("Line 3: "); DEBUG_PRINTLN(strlen(replybuffer)); + if (strstr(replybuffer, "+CMGS") == 0) { + return false; + } + readline(1000); // read OK + //DEBUG_PRINT("* "); DEBUG_PRINTLN(replybuffer); + + if (strcmp(replybuffer, "OK") != 0) { + return false; + } + + return true; +} + + +boolean Adafruit_FONA::deleteSMS(uint8_t i) { + if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return -1; + // read an sms + char sendbuff[12] = "AT+CMGD=000"; + sendbuff[8] = (i / 100) + '0'; + i %= 100; + sendbuff[9] = (i / 10) + '0'; + i %= 10; + sendbuff[10] = i + '0'; + + return sendCheckReply(sendbuff, ok_reply, 2000); +} + +/********* USSD *********************************************************/ + +boolean Adafruit_FONA::sendUSSD(char *ussdmsg, char *ussdbuff, uint16_t maxlen, uint16_t *readlen) { + if (! sendCheckReply(F("AT+CUSD=1"), ok_reply)) return -1; + + char sendcmd[30] = "AT+CUSD=1,\""; + strncpy(sendcmd+11, ussdmsg, 30-11-2); // 11 bytes beginning, 2 bytes for close quote + null + sendcmd[strlen(sendcmd)] = '\"'; + + if (! sendCheckReply(sendcmd, ok_reply)) { + *readlen = 0; + return false; + } else { + readline(10000); // read the +CUSD reply, wait up to 10 seconds!!! + //DEBUG_PRINT("* "); DEBUG_PRINTLN(replybuffer); + char *p = prog_char_strstr(replybuffer, PSTR("+CUSD: ")); + if (p == 0) { + *readlen = 0; + return false; + } + p+=7; //+CUSD + // Find " to get start of ussd message. + p = strchr(p, '\"'); + if (p == 0) { + *readlen = 0; + return false; + } + p+=1; //" + // Find " to get end of ussd message. + char *strend = strchr(p, '\"'); + + uint16_t lentocopy = min(maxlen-1, strend - p); + strncpy(ussdbuff, p, lentocopy+1); + ussdbuff[lentocopy] = 0; + *readlen = lentocopy; + } + return true; +} + + +/********* TIME **********************************************************/ + +boolean Adafruit_FONA::enableNetworkTimeSync(boolean onoff) { + if (onoff) { + if (! sendCheckReply(F("AT+CLTS=1"), ok_reply)) + return false; + } else { + if (! sendCheckReply(F("AT+CLTS=0"), ok_reply)) + return false; + } + + flushInput(); // eat any 'Unsolicted Result Code' + + return true; +} + +boolean Adafruit_FONA::enableNTPTimeSync(boolean onoff, FONAFlashStringPtr ntpserver) { + if (onoff) { + if (! sendCheckReply(F("AT+CNTPCID=1"), ok_reply)) + return false; + + mySerial->print(F("AT+CNTP=\"")); + if (ntpserver != 0) { + mySerial->print(ntpserver); + } else { + mySerial->print(F("pool.ntp.org")); + } + mySerial->println(F("\",0")); + readline(FONA_DEFAULT_TIMEOUT_MS); + if (strcmp(replybuffer, "OK") != 0) + return false; + + if (! sendCheckReply(F("AT+CNTP"), ok_reply, 10000)) + return false; + + uint16_t status; + readline(10000); + if (! parseReply(F("+CNTP:"), &status)) + return false; + } else { + if (! sendCheckReply(F("AT+CNTPCID=0"), ok_reply)) + return false; + } + + return true; +} + +boolean Adafruit_FONA::getTime(char *buff, uint16_t maxlen) { + getReply(F("AT+CCLK?"), (uint16_t) 10000); + if (strncmp(replybuffer, "+CCLK: ", 7) != 0) + return false; + + char *p = replybuffer+7; + uint16_t lentocopy = min(maxlen-1, strlen(p)); + strncpy(buff, p, lentocopy+1); + buff[lentocopy] = 0; + + readline(); // eat OK + + return true; +} + +/********* GPS **********************************************************/ + + +boolean Adafruit_FONA::enableGPS(boolean onoff) { + uint16_t state; + + // first check if its already on or off + + if (_type == FONA808_V2) { + if (! sendParseReply(F("AT+CGNSPWR?"), F("+CGNSPWR: "), &state) ) + return false; + } else { + if (! sendParseReply(F("AT+CGPSPWR?"), F("+CGPSPWR: "), &state)) + return false; + } + + if (onoff && !state) { + if (_type == FONA808_V2) { + if (! sendCheckReply(F("AT+CGNSPWR=1"), ok_reply)) // try GNS command + return false; + } else { + if (! sendCheckReply(F("AT+CGPSPWR=1"), ok_reply)) + return false; + } + } else if (!onoff && state) { + if (_type == FONA808_V2) { + if (! sendCheckReply(F("AT+CGNSPWR=0"), ok_reply)) // try GNS command + return false; + } else { + if (! sendCheckReply(F("AT+CGPSPWR=0"), ok_reply)) + return false; + } + } + return true; +} + + + +boolean Adafruit_FONA_3G::enableGPS(boolean onoff) { + uint16_t state; + + // first check if its already on or off + if (! Adafruit_FONA::sendParseReply(F("AT+CGPS?"), F("+CGPS: "), &state) ) + return false; + + if (onoff && !state) { + if (! sendCheckReply(F("AT+CGPS=1"), ok_reply)) + return false; + } else if (!onoff && state) { + if (! sendCheckReply(F("AT+CGPS=0"), ok_reply)) + return false; + // this takes a little time + readline(2000); // eat '+CGPS: 0' + } + return true; +} + +int8_t Adafruit_FONA::GPSstatus(void) { + if (_type == FONA808_V2) { + // 808 V2 uses GNS commands and doesn't have an explicit 2D/3D fix status. + // Instead just look for a fix and if found assume it's a 3D fix. + getReply(F("AT+CGNSINF")); + char *p = prog_char_strstr(replybuffer, (prog_char*)F("+CGNSINF: ")); + if (p == 0) return -1; + p+=12; // Skip to second value, fix status. + readline(); // eat 'OK' + //DEBUG_PRINTLN(p); + // Assume if the fix status is '1' then we have a 3D fix, otherwise no fix. + if (p[0] == '1') return 3; + else return 0; + } + if (_type == FONA3G_A || _type == FONA3G_E) { + // FONA 3G doesn't have an explicit 2D/3D fix status. + // Instead just look for a fix and if found assume it's a 3D fix. + getReply(F("AT+CGPSINFO")); + char *p = prog_char_strstr(replybuffer, (prog_char*)F("+CGPSINFO:")); + if (p == 0) return -1; + if (p[10] != ',') return 3; // if you get anything, its 3D fix + return 0; + } + else { + // 808 V1 looks for specific 2D or 3D fix state. + getReply(F("AT+CGPSSTATUS?")); + char *p = prog_char_strstr(replybuffer, (prog_char*)F("SSTATUS: Location ")); + if (p == 0) return -1; + p+=18; + readline(); // eat 'OK' + //DEBUG_PRINTLN(p); + if (p[0] == 'U') return 0; + if (p[0] == 'N') return 1; + if (p[0] == '2') return 2; + if (p[0] == '3') return 3; + } + // else + return 0; +} + +uint8_t Adafruit_FONA::getGPS(uint8_t arg, char *buffer, uint8_t maxbuff) { + int32_t x = arg; + + if ( (_type == FONA3G_A) || (_type == FONA3G_E) ) { + getReply(F("AT+CGPSINFO")); + } else if (_type == FONA808_V1) { + getReply(F("AT+CGPSINF="), x); + } else { + getReply(F("AT+CGNSINF")); + } + + char *p = prog_char_strstr(replybuffer, (prog_char*)F("SINF")); + if (p == 0) { + buffer[0] = 0; + return 0; + } + + p+=6; + + uint8_t len = max(maxbuff-1, strlen(p)); + strncpy(buffer, p, len); + buffer[len] = 0; + + readline(); // eat 'OK' + return len; +} + +boolean Adafruit_FONA::getGPS(float *lat, float *lon, float *speed_kph, float *heading, float *altitude) { + + char gpsbuffer[120]; + + // we need at least a 2D fix + if (GPSstatus() < 2) + return false; + + // grab the mode 2^5 gps csv from the sim808 + uint8_t res_len = getGPS(32, gpsbuffer, 120); + + // make sure we have a response + if (res_len == 0) + return false; + + if (_type == FONA3G_A || _type == FONA3G_E) { + // Parse 3G respose + // +CGPSINFO:4043.000000,N,07400.000000,W,151015,203802.1,-12.0,0.0,0 + // skip beginning + char *tok; + + // grab the latitude + char *latp = strtok(gpsbuffer, ","); + if (! latp) return false; + + // grab latitude direction + char *latdir = strtok(NULL, ","); + if (! latdir) return false; + + // grab longitude + char *longp = strtok(NULL, ","); + if (! longp) return false; + + // grab longitude direction + char *longdir = strtok(NULL, ","); + if (! longdir) return false; + + // skip date & time + tok = strtok(NULL, ","); + tok = strtok(NULL, ","); + + // only grab altitude if needed + if (altitude != NULL) { + // grab altitude + char *altp = strtok(NULL, ","); + if (! altp) return false; + *altitude = atof(altp); + } + + // only grab speed if needed + if (speed_kph != NULL) { + // grab the speed in km/h + char *speedp = strtok(NULL, ","); + if (! speedp) return false; + + *speed_kph = atof(speedp); + } + + // only grab heading if needed + if (heading != NULL) { + + // grab the speed in knots + char *coursep = strtok(NULL, ","); + if (! coursep) return false; + + *heading = atof(coursep); + } + + double latitude = atof(latp); + double longitude = atof(longp); + + // convert latitude from minutes to decimal + float degrees = floor(latitude / 100); + double minutes = latitude - (100 * degrees); + minutes /= 60; + degrees += minutes; + + // turn direction into + or - + if (latdir[0] == 'S') degrees *= -1; + + *lat = degrees; + + // convert longitude from minutes to decimal + degrees = floor(longitude / 100); + minutes = longitude - (100 * degrees); + minutes /= 60; + degrees += minutes; + + // turn direction into + or - + if (longdir[0] == 'W') degrees *= -1; + + *lon = degrees; + + } else if (_type == FONA808_V2) { + // Parse 808 V2 response. See table 2-3 from here for format: + // http://www.adafruit.com/datasheets/SIM800%20Series_GNSS_Application%20Note%20V1.00.pdf + + // skip GPS run status + char *tok = strtok(gpsbuffer, ","); + if (! tok) return false; + + // skip fix status + tok = strtok(NULL, ","); + if (! tok) return false; + + // skip date + tok = strtok(NULL, ","); + if (! tok) return false; + + // grab the latitude + char *latp = strtok(NULL, ","); + if (! latp) return false; + + // grab longitude + char *longp = strtok(NULL, ","); + if (! longp) return false; + + *lat = atof(latp); + *lon = atof(longp); + + // only grab altitude if needed + if (altitude != NULL) { + // grab altitude + char *altp = strtok(NULL, ","); + if (! altp) return false; + + *altitude = atof(altp); + } + + // only grab speed if needed + if (speed_kph != NULL) { + // grab the speed in km/h + char *speedp = strtok(NULL, ","); + if (! speedp) return false; + + *speed_kph = atof(speedp); + } + + // only grab heading if needed + if (heading != NULL) { + + // grab the speed in knots + char *coursep = strtok(NULL, ","); + if (! coursep) return false; + + *heading = atof(coursep); + } + } + else { + // Parse 808 V1 response. + + // skip mode + char *tok = strtok(gpsbuffer, ","); + if (! tok) return false; + + // skip date + tok = strtok(NULL, ","); + if (! tok) return false; + + // skip fix + tok = strtok(NULL, ","); + if (! tok) return false; + + // grab the latitude + char *latp = strtok(NULL, ","); + if (! latp) return false; + + // grab latitude direction + char *latdir = strtok(NULL, ","); + if (! latdir) return false; + + // grab longitude + char *longp = strtok(NULL, ","); + if (! longp) return false; + + // grab longitude direction + char *longdir = strtok(NULL, ","); + if (! longdir) return false; + + double latitude = atof(latp); + double longitude = atof(longp); + + // convert latitude from minutes to decimal + float degrees = floor(latitude / 100); + double minutes = latitude - (100 * degrees); + minutes /= 60; + degrees += minutes; + + // turn direction into + or - + if (latdir[0] == 'S') degrees *= -1; + + *lat = degrees; + + // convert longitude from minutes to decimal + degrees = floor(longitude / 100); + minutes = longitude - (100 * degrees); + minutes /= 60; + degrees += minutes; + + // turn direction into + or - + if (longdir[0] == 'W') degrees *= -1; + + *lon = degrees; + + // only grab speed if needed + if (speed_kph != NULL) { + + // grab the speed in knots + char *speedp = strtok(NULL, ","); + if (! speedp) return false; + + // convert to kph + *speed_kph = atof(speedp) * 1.852; + + } + + // only grab heading if needed + if (heading != NULL) { + + // grab the speed in knots + char *coursep = strtok(NULL, ","); + if (! coursep) return false; + + *heading = atof(coursep); + + } + + // no need to continue + if (altitude == NULL) + return true; + + // we need at least a 3D fix for altitude + if (GPSstatus() < 3) + return false; + + // grab the mode 0 gps csv from the sim808 + res_len = getGPS(0, gpsbuffer, 120); + + // make sure we have a response + if (res_len == 0) + return false; + + // skip mode + tok = strtok(gpsbuffer, ","); + if (! tok) return false; + + // skip lat + tok = strtok(NULL, ","); + if (! tok) return false; + + // skip long + tok = strtok(NULL, ","); + if (! tok) return false; + + // grab altitude + char *altp = strtok(NULL, ","); + if (! altp) return false; + + *altitude = atof(altp); + } + + return true; + +} + +boolean Adafruit_FONA::enableGPSNMEA(uint8_t i) { + + char sendbuff[15] = "AT+CGPSOUT=000"; + sendbuff[11] = (i / 100) + '0'; + i %= 100; + sendbuff[12] = (i / 10) + '0'; + i %= 10; + sendbuff[13] = i + '0'; + + if (_type == FONA808_V2) { + if (i) + return sendCheckReply(F("AT+CGNSTST=1"), ok_reply); + else + return sendCheckReply(F("AT+CGNSTST=0"), ok_reply); + } else { + return sendCheckReply(sendbuff, ok_reply, 2000); + } +} + + +/********* GPRS **********************************************************/ + + +boolean Adafruit_FONA::enableGPRS(boolean onoff) { + + if (onoff) { + // disconnect all sockets + sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 20000); + + if (! sendCheckReply(F("AT+CGATT=1"), ok_reply, 10000)) + return false; + + // set bearer profile! connection type GPRS + if (! sendCheckReply(F("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\""), + ok_reply, 10000)) + return false; + + // set bearer profile access point name + if (apn) { + // Send command AT+SAPBR=3,1,"APN","" where is the configured APN value. + if (! sendCheckReplyQuoted(F("AT+SAPBR=3,1,\"APN\","), apn, ok_reply, 10000)) + return false; + + // send AT+CSTT,"apn","user","pass" + flushInput(); + + mySerial->print(F("AT+CSTT=\"")); + mySerial->print(apn); + if (apnusername) { + mySerial->print("\",\""); + mySerial->print(apnusername); + } + if (apnpassword) { + mySerial->print("\",\""); + mySerial->print(apnpassword); + } + mySerial->println("\""); + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(F("AT+CSTT=\"")); + DEBUG_PRINT(apn); + + if (apnusername) { + DEBUG_PRINT("\",\""); + DEBUG_PRINT(apnusername); + } + if (apnpassword) { + DEBUG_PRINT("\",\""); + DEBUG_PRINT(apnpassword); + } + DEBUG_PRINTLN("\""); + + if (! expectReply(ok_reply)) return false; + + // set username/password + if (apnusername) { + // Send command AT+SAPBR=3,1,"USER","" where is the configured APN username. + if (! sendCheckReplyQuoted(F("AT+SAPBR=3,1,\"USER\","), apnusername, ok_reply, 10000)) + return false; + } + if (apnpassword) { + // Send command AT+SAPBR=3,1,"PWD","" where is the configured APN password. + if (! sendCheckReplyQuoted(F("AT+SAPBR=3,1,\"PWD\","), apnpassword, ok_reply, 10000)) + return false; + } + } + + // open GPRS context + if (! sendCheckReply(F("AT+SAPBR=1,1"), ok_reply, 30000)) + return false; + + // bring up wireless connection + if (! sendCheckReply(F("AT+CIICR"), ok_reply, 10000)) + return false; + + } else { + // disconnect all sockets + if (! sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 20000)) + return false; + + // close GPRS context + if (! sendCheckReply(F("AT+SAPBR=0,1"), ok_reply, 10000)) + return false; + + if (! sendCheckReply(F("AT+CGATT=0"), ok_reply, 10000)) + return false; + + } + return true; +} + +boolean Adafruit_FONA_3G::enableGPRS(boolean onoff) { + + if (onoff) { + // disconnect all sockets + //sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 5000); + + if (! sendCheckReply(F("AT+CGATT=1"), ok_reply, 10000)) + return false; + + + // set bearer profile access point name + if (apn) { + // Send command AT+CGSOCKCONT=1,"IP","" where is the configured APN name. + if (! sendCheckReplyQuoted(F("AT+CGSOCKCONT=1,\"IP\","), apn, ok_reply, 10000)) + return false; + + // set username/password + if (apnusername) { + char authstring[100] = "AT+CGAUTH=1,1,\""; + char *strp = authstring + strlen(authstring); + prog_char_strcpy(strp, (prog_char *)apnusername); + strp+=prog_char_strlen((prog_char *)apnusername); + strp[0] = '\"'; + strp++; + strp[0] = 0; + + if (apnpassword) { + strp[0] = ','; strp++; + strp[0] = '\"'; strp++; + prog_char_strcpy(strp, (prog_char *)apnpassword); + strp+=prog_char_strlen((prog_char *)apnpassword); + strp[0] = '\"'; + strp++; + strp[0] = 0; + } + + if (! sendCheckReply(authstring, ok_reply, 10000)) + return false; + } + } + + // connect in transparent + if (! sendCheckReply(F("AT+CIPMODE=1"), ok_reply, 10000)) + return false; + // open network (?) + if (! sendCheckReply(F("AT+NETOPEN=,,1"), F("Network opened"), 10000)) + return false; + + readline(); // eat 'OK' + } else { + // close GPRS context + if (! sendCheckReply(F("AT+NETCLOSE"), F("Network closed"), 10000)) + return false; + + readline(); // eat 'OK' + } + + return true; +} + +uint8_t Adafruit_FONA::GPRSstate(void) { + uint16_t state; + + if (! sendParseReply(F("AT+CGATT?"), F("+CGATT: "), &state) ) + return -1; + + return state; +} + +void Adafruit_FONA::setGPRSNetworkSettings(FONAFlashStringPtr apn, + FONAFlashStringPtr username, FONAFlashStringPtr password) { + this->apn = apn; + this->apnusername = username; + this->apnpassword = password; +} + +boolean Adafruit_FONA::getGSMLoc(uint16_t *errorcode, char *buff, uint16_t maxlen) { + + getReply(F("AT+CIPGSMLOC=1,1"), (uint16_t)10000); + + if (! parseReply(F("+CIPGSMLOC: "), errorcode)) + return false; + + char *p = replybuffer+14; + uint16_t lentocopy = min(maxlen-1, strlen(p)); + strncpy(buff, p, lentocopy+1); + + readline(); // eat OK + + return true; +} + +boolean Adafruit_FONA::getGSMLoc(float *lat, float *lon) { + + uint16_t returncode; + char gpsbuffer[120]; + + // make sure we could get a response + if (! getGSMLoc(&returncode, gpsbuffer, 120)) + return false; + + // make sure we have a valid return code + if (returncode != 0) + return false; + + // +CIPGSMLOC: 0,-74.007729,40.730160,2015/10/15,19:24:55 + // tokenize the gps buffer to locate the lat & long + char *longp = strtok(gpsbuffer, ","); + if (! longp) return false; + + char *latp = strtok(NULL, ","); + if (! latp) return false; + + *lat = atof(latp); + *lon = atof(longp); + + return true; + +} +/********* TCP FUNCTIONS ************************************/ + + +boolean Adafruit_FONA::TCPconnect(char *server, uint16_t port) { + flushInput(); + + // close all old connections + if (! sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 20000) ) return false; + + // single connection at a time + if (! sendCheckReply(F("AT+CIPMUX=0"), ok_reply) ) return false; + + // manually read data + if (! sendCheckReply(F("AT+CIPRXGET=1"), ok_reply) ) return false; + + + DEBUG_PRINT(F("AT+CIPSTART=\"TCP\",\"")); + DEBUG_PRINT(server); + DEBUG_PRINT(F("\",\"")); + DEBUG_PRINT(port); + DEBUG_PRINTLN(F("\"")); + + + mySerial->print(F("AT+CIPSTART=\"TCP\",\"")); + mySerial->print(server); + mySerial->print(F("\",\"")); + mySerial->print(port); + mySerial->println(F("\"")); + + if (! expectReply(ok_reply)) return false; + if (! expectReply(F("CONNECT OK"))) return false; + + // looks like it was a success (?) + return true; +} + +boolean Adafruit_FONA::TCPclose(void) { + return sendCheckReply(F("AT+CIPCLOSE"), ok_reply); +} + +boolean Adafruit_FONA::TCPconnected(void) { + if (! sendCheckReply(F("AT+CIPSTATUS"), ok_reply, 100) ) return false; + readline(100); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return (strcmp(replybuffer, "STATE: CONNECT OK") == 0); +} + +boolean Adafruit_FONA::TCPsend(char *packet, uint8_t len) { + + DEBUG_PRINT(F("AT+CIPSEND=")); + DEBUG_PRINTLN(len); +#ifdef ADAFRUIT_FONA_DEBUG + for (uint16_t i=0; iprint(F("AT+CIPSEND=")); + mySerial->println(len); + readline(); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + if (replybuffer[0] != '>') return false; + + mySerial->write(packet, len); + readline(3000); // wait up to 3 seconds to send the data + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + + return (strcmp(replybuffer, "SEND OK") == 0); +} + +uint16_t Adafruit_FONA::TCPavailable(void) { + uint16_t avail; + + if (! sendParseReply(F("AT+CIPRXGET=4"), F("+CIPRXGET: 4,"), &avail, ',', 0) ) return false; + + + DEBUG_PRINT (avail); DEBUG_PRINTLN(F(" bytes available")); + + + return avail; +} + + +uint16_t Adafruit_FONA::TCPread(uint8_t *buff, uint8_t len) { + uint16_t avail; + + mySerial->print(F("AT+CIPRXGET=2,")); + mySerial->println(len); + readline(); + if (! parseReply(F("+CIPRXGET: 2,"), &avail, ',', 0)) return false; + + readRaw(avail); + +#ifdef ADAFRUIT_FONA_DEBUG + DEBUG_PRINT (avail); DEBUG_PRINTLN(F(" bytes read")); + for (uint8_t i=0;i ")); + DEBUG_PRINT(F("AT+HTTPPARA=\"")); + DEBUG_PRINT(parameter); + DEBUG_PRINTLN('"'); + + + mySerial->print(F("AT+HTTPPARA=\"")); + mySerial->print(parameter); + if (quoted) + mySerial->print(F("\",\"")); + else + mySerial->print(F("\",")); +} + +boolean Adafruit_FONA::HTTP_para_end(boolean quoted) { + if (quoted) + mySerial->println('"'); + else + mySerial->println(); + + return expectReply(ok_reply); +} + +boolean Adafruit_FONA::HTTP_para(FONAFlashStringPtr parameter, + const char *value) { + HTTP_para_start(parameter, true); + mySerial->print(value); + return HTTP_para_end(true); +} + +boolean Adafruit_FONA::HTTP_para(FONAFlashStringPtr parameter, + FONAFlashStringPtr value) { + HTTP_para_start(parameter, true); + mySerial->print(value); + return HTTP_para_end(true); +} + +boolean Adafruit_FONA::HTTP_para(FONAFlashStringPtr parameter, + int32_t value) { + HTTP_para_start(parameter, false); + mySerial->print(value); + return HTTP_para_end(false); +} + +boolean Adafruit_FONA::HTTP_data(uint32_t size, uint32_t maxTime) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); + DEBUG_PRINT(F("AT+HTTPDATA=")); + DEBUG_PRINT(size); + DEBUG_PRINT(','); + DEBUG_PRINTLN(maxTime); + + + mySerial->print(F("AT+HTTPDATA=")); + mySerial->print(size); + mySerial->print(","); + mySerial->println(maxTime); + + return expectReply(F("DOWNLOAD")); +} + +boolean Adafruit_FONA::HTTP_action(uint8_t method, uint16_t *status, + uint16_t *datalen, int32_t timeout) { + // Send request. + if (! sendCheckReply(F("AT+HTTPACTION="), method, ok_reply)) + return false; + + // Parse response status and size. + readline(timeout); + if (! parseReply(F("+HTTPACTION:"), status, ',', 1)) + return false; + if (! parseReply(F("+HTTPACTION:"), datalen, ',', 2)) + return false; + + return true; +} + +boolean Adafruit_FONA::HTTP_readall(uint16_t *datalen) { + getReply(F("AT+HTTPREAD")); + if (! parseReply(F("+HTTPREAD:"), datalen, ',', 0)) + return false; + + return true; +} + +boolean Adafruit_FONA::HTTP_ssl(boolean onoff) { + return sendCheckReply(F("AT+HTTPSSL="), onoff ? 1 : 0, ok_reply); +} + +/********* HTTP HIGH LEVEL FUNCTIONS ***************************/ + +boolean Adafruit_FONA::HTTP_GET_start(char *url, + uint16_t *status, uint16_t *datalen){ + if (! HTTP_setup(url)) + return false; + + // HTTP GET + if (! HTTP_action(FONA_HTTP_GET, status, datalen, 30000)) + return false; + + DEBUG_PRINT(F("Status: ")); DEBUG_PRINTLN(*status); + DEBUG_PRINT(F("Len: ")); DEBUG_PRINTLN(*datalen); + + // HTTP response data + if (! HTTP_readall(datalen)) + return false; + + return true; +} + +/* +boolean Adafruit_FONA_3G::HTTP_GET_start(char *ipaddr, char *path, uint16_t port + uint16_t *status, uint16_t *datalen){ + char send[100] = "AT+CHTTPACT=\""; + char *sendp = send + strlen(send); + memset(sendp, 0, 100 - strlen(send)); + + strcpy(sendp, ipaddr); + sendp+=strlen(ipaddr); + sendp[0] = '\"'; + sendp++; + sendp[0] = ','; + itoa(sendp, port); + getReply(send, 500); + + return; + + if (! HTTP_setup(url)) + + return false; + + // HTTP GET + if (! HTTP_action(FONA_HTTP_GET, status, datalen)) + return false; + + DEBUG_PRINT("Status: "); DEBUG_PRINTLN(*status); + DEBUG_PRINT("Len: "); DEBUG_PRINTLN(*datalen); + + // HTTP response data + if (! HTTP_readall(datalen)) + return false; + + return true; +} +*/ + +void Adafruit_FONA::HTTP_GET_end(void) { + HTTP_term(); +} + +boolean Adafruit_FONA::HTTP_POST_start(char *url, + FONAFlashStringPtr contenttype, + const uint8_t *postdata, uint16_t postdatalen, + uint16_t *status, uint16_t *datalen){ + if (! HTTP_setup(url)) + return false; + + if (! HTTP_para(F("CONTENT"), contenttype)) { + return false; + } + + // HTTP POST data + if (! HTTP_data(postdatalen, 10000)) + return false; + mySerial->write(postdata, postdatalen); + if (! expectReply(ok_reply)) + return false; + + // HTTP POST + if (! HTTP_action(FONA_HTTP_POST, status, datalen)) + return false; + + DEBUG_PRINT(F("Status: ")); DEBUG_PRINTLN(*status); + DEBUG_PRINT(F("Len: ")); DEBUG_PRINTLN(*datalen); + + // HTTP response data + if (! HTTP_readall(datalen)) + return false; + + return true; +} + +void Adafruit_FONA::HTTP_POST_end(void) { + HTTP_term(); +} + +void Adafruit_FONA::setUserAgent(FONAFlashStringPtr useragent) { + this->useragent = useragent; +} + +void Adafruit_FONA::setHTTPSRedirect(boolean onoff) { + httpsredirect = onoff; +} + +/********* HTTP HELPERS ****************************************/ + +boolean Adafruit_FONA::HTTP_setup(char *url) { + // Handle any pending + HTTP_term(); + + // Initialize and set parameters + if (! HTTP_init()) + return false; + if (! HTTP_para(F("CID"), 1)) + return false; + if (! HTTP_para(F("UA"), useragent)) + return false; + if (! HTTP_para(F("URL"), url)) + return false; + + // HTTPS redirect + if (httpsredirect) { + if (! HTTP_para(F("REDIR"),1)) + return false; + + if (! HTTP_ssl(true)) + return false; + } + + return true; +} + +/********* HELPERS *********************************************/ + +boolean Adafruit_FONA::expectReply(FONAFlashStringPtr reply, + uint16_t timeout) { + readline(timeout); + + DEBUG_PRINT(F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return (prog_char_strcmp(replybuffer, (prog_char*)reply) == 0); +} + +/********* LOW LEVEL *******************************************/ + +inline int Adafruit_FONA::available(void) { + return mySerial->available(); +} + +inline size_t Adafruit_FONA::write(uint8_t x) { + return mySerial->write(x); +} + +inline int Adafruit_FONA::read(void) { + return mySerial->read(); +} + +inline int Adafruit_FONA::peek(void) { + return mySerial->peek(); +} + +inline void Adafruit_FONA::flush() { + mySerial->flush(); +} + +void Adafruit_FONA::flushInput() { + // Read all available serial input to flush pending data. + uint16_t timeoutloop = 0; + while (timeoutloop++ < 40) { + while(available()) { + read(); + timeoutloop = 0; // If char was received reset the timer + } + delay(1); + } +} + +uint16_t Adafruit_FONA::readRaw(uint16_t b) { + uint16_t idx = 0; + + while (b && (idx < sizeof(replybuffer)-1)) { + if (mySerial->available()) { + replybuffer[idx] = mySerial->read(); + idx++; + b--; + } + } + replybuffer[idx] = 0; + + return idx; +} + +uint8_t Adafruit_FONA::readline(uint16_t timeout, boolean multiline) { + uint16_t replyidx = 0; + + while (timeout--) { + if (replyidx >= 254) { + //DEBUG_PRINTLN(F("SPACE")); + break; + } + + while(mySerial->available()) { + char c = mySerial->read(); + if (c == '\r') continue; + if (c == 0xA) { + if (replyidx == 0) // the first 0x0A is ignored + continue; + + if (!multiline) { + timeout = 0; // the second 0x0A is the end of the line + break; + } + } + replybuffer[replyidx] = c; + //DEBUG_PRINT(c, HEX); DEBUG_PRINT("#"); DEBUG_PRINTLN(c); + replyidx++; + } + + if (timeout == 0) { + //DEBUG_PRINTLN(F("TIMEOUT")); + break; + } + delay(1); + } + replybuffer[replyidx] = 0; // null term + return replyidx; +} + +uint8_t Adafruit_FONA::getReply(char *send, uint16_t timeout) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN(send); + + + mySerial->println(send); + + uint8_t l = readline(timeout); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return l; +} + +uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr send, uint16_t timeout) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN(send); + + + mySerial->println(send); + + uint8_t l = readline(timeout); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return l; +} + +// Send prefix, suffix, and newline. Return response (and also set replybuffer with response). +uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr prefix, char *suffix, uint16_t timeout) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); DEBUG_PRINTLN(suffix); + + + mySerial->print(prefix); + mySerial->println(suffix); + + uint8_t l = readline(timeout); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return l; +} + +// Send prefix, suffix, and newline. Return response (and also set replybuffer with response). +uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr prefix, int32_t suffix, uint16_t timeout) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); DEBUG_PRINTLN(suffix, DEC); + + + mySerial->print(prefix); + mySerial->println(suffix, DEC); + + uint8_t l = readline(timeout); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return l; +} + +// Send prefix, suffix, suffix2, and newline. Return response (and also set replybuffer with response). +uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr prefix, int32_t suffix1, int32_t suffix2, uint16_t timeout) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); + DEBUG_PRINT(suffix1, DEC); DEBUG_PRINT(','); DEBUG_PRINTLN(suffix2, DEC); + + + mySerial->print(prefix); + mySerial->print(suffix1); + mySerial->print(','); + mySerial->println(suffix2, DEC); + + uint8_t l = readline(timeout); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return l; +} + +// Send prefix, ", suffix, ", and newline. Return response (and also set replybuffer with response). +uint8_t Adafruit_FONA::getReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, uint16_t timeout) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); + DEBUG_PRINT('"'); DEBUG_PRINT(suffix); DEBUG_PRINTLN('"'); + + + mySerial->print(prefix); + mySerial->print('"'); + mySerial->print(suffix); + mySerial->println('"'); + + uint8_t l = readline(timeout); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return l; +} + +boolean Adafruit_FONA::sendCheckReply(char *send, char *reply, uint16_t timeout) { + if (! getReply(send, timeout) ) + return false; +/* + for (uint8_t i=0; i http://www.adafruit.com/products/1946 + ----> http://www.adafruit.com/products/1963 + + These displays use TTL Serial to communicate, 2 pins are required to + interface + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ****************************************************/ +#ifndef ADAFRUIT_FONA_H +#define ADAFRUIT_FONA_H + +#include "includes/FONAConfig.h" +#include "includes/FONAExtIncludes.h" +#include "includes/platform/FONAPlatform.h" + + + +#define FONA800L 1 +#define FONA800H 6 + +#define FONA808_V1 2 +#define FONA808_V2 3 + +#define FONA3G_A 4 +#define FONA3G_E 5 + +// Uncomment to changed the preferred SMS storage +//#define FONA_PREF_SMS_STORAGE "SM" + +#define FONA_HEADSETAUDIO 0 +#define FONA_EXTAUDIO 1 + +#define FONA_STTONE_DIALTONE 1 +#define FONA_STTONE_BUSY 2 +#define FONA_STTONE_CONGESTION 3 +#define FONA_STTONE_PATHACK 4 +#define FONA_STTONE_DROPPED 5 +#define FONA_STTONE_ERROR 6 +#define FONA_STTONE_CALLWAIT 7 +#define FONA_STTONE_RINGING 8 +#define FONA_STTONE_BEEP 16 +#define FONA_STTONE_POSTONE 17 +#define FONA_STTONE_ERRTONE 18 +#define FONA_STTONE_INDIANDIALTONE 19 +#define FONA_STTONE_USADIALTONE 20 + +#define FONA_DEFAULT_TIMEOUT_MS 500 + +#define FONA_HTTP_GET 0 +#define FONA_HTTP_POST 1 +#define FONA_HTTP_HEAD 2 + +#define FONA_CALL_READY 0 +#define FONA_CALL_FAILED 1 +#define FONA_CALL_UNKNOWN 2 +#define FONA_CALL_RINGING 3 +#define FONA_CALL_INPROGRESS 4 + +class Adafruit_FONA : public FONAStreamType { + public: + Adafruit_FONA(int8_t r); + boolean begin(FONAStreamType &port); + uint8_t type(); + + // Stream + int available(void); + size_t write(uint8_t x); + int read(void); + int peek(void); + void flush(); + + // FONA 3G requirements + boolean setBaudrate(uint16_t baud); + + // RTC + boolean enableRTC(uint8_t i); + boolean readRTC(uint8_t *year, uint8_t *month, uint8_t *date, uint8_t *hr, uint8_t *min, uint8_t *sec); + + // Battery and ADC + boolean getADCVoltage(uint16_t *v); + boolean getBattPercent(uint16_t *p); + boolean getBattVoltage(uint16_t *v); + + // SIM query + uint8_t unlockSIM(char *pin); + uint8_t getSIMCCID(char *ccid); + uint8_t getNetworkStatus(void); + uint8_t getRSSI(void); + + // IMEI + uint8_t getIMEI(char *imei); + + // set Audio output + boolean setAudio(uint8_t a); + boolean setVolume(uint8_t i); + uint8_t getVolume(void); + boolean playToolkitTone(uint8_t t, uint16_t len); + boolean setMicVolume(uint8_t a, uint8_t level); + boolean playDTMF(char tone); + + // FM radio functions. + boolean tuneFMradio(uint16_t station); + boolean FMradio(boolean onoff, uint8_t a = FONA_HEADSETAUDIO); + boolean setFMVolume(uint8_t i); + int8_t getFMVolume(); + int8_t getFMSignalLevel(uint16_t station); + + // SMS handling + boolean setSMSInterrupt(uint8_t i); + uint8_t getSMSInterrupt(void); + int8_t getNumSMS(void); + boolean readSMS(uint8_t i, char *smsbuff, uint16_t max, uint16_t *readsize); + boolean sendSMS(char *smsaddr, char *smsmsg); + boolean deleteSMS(uint8_t i); + boolean getSMSSender(uint8_t i, char *sender, int senderlen); + boolean sendUSSD(char *ussdmsg, char *ussdbuff, uint16_t maxlen, uint16_t *readlen); + + // Time + boolean enableNetworkTimeSync(boolean onoff); + boolean enableNTPTimeSync(boolean onoff, FONAFlashStringPtr ntpserver=0); + boolean getTime(char *buff, uint16_t maxlen); + + // GPRS handling + boolean enableGPRS(boolean onoff); + uint8_t GPRSstate(void); + boolean getGSMLoc(uint16_t *replycode, char *buff, uint16_t maxlen); + boolean getGSMLoc(float *lat, float *lon); + void setGPRSNetworkSettings(FONAFlashStringPtr apn, FONAFlashStringPtr username=0, FONAFlashStringPtr password=0); + + // GPS handling + boolean enableGPS(boolean onoff); + int8_t GPSstatus(void); + uint8_t getGPS(uint8_t arg, char *buffer, uint8_t maxbuff); + boolean getGPS(float *lat, float *lon, float *speed_kph=0, float *heading=0, float *altitude=0); + boolean enableGPSNMEA(uint8_t nmea); + + // TCP raw connections + boolean TCPconnect(char *server, uint16_t port); + boolean TCPclose(void); + boolean TCPconnected(void); + boolean TCPsend(char *packet, uint8_t len); + uint16_t TCPavailable(void); + uint16_t TCPread(uint8_t *buff, uint8_t len); + + // HTTP low level interface (maps directly to SIM800 commands). + boolean HTTP_init(); + boolean HTTP_term(); + void HTTP_para_start(FONAFlashStringPtr parameter, boolean quoted = true); + boolean HTTP_para_end(boolean quoted = true); + boolean HTTP_para(FONAFlashStringPtr parameter, const char *value); + boolean HTTP_para(FONAFlashStringPtr parameter, FONAFlashStringPtr value); + boolean HTTP_para(FONAFlashStringPtr parameter, int32_t value); + boolean HTTP_data(uint32_t size, uint32_t maxTime=10000); + boolean HTTP_action(uint8_t method, uint16_t *status, uint16_t *datalen, int32_t timeout = 10000); + boolean HTTP_readall(uint16_t *datalen); + boolean HTTP_ssl(boolean onoff); + + // HTTP high level interface (easier to use, less flexible). + boolean HTTP_GET_start(char *url, uint16_t *status, uint16_t *datalen); + void HTTP_GET_end(void); + boolean HTTP_POST_start(char *url, FONAFlashStringPtr contenttype, const uint8_t *postdata, uint16_t postdatalen, uint16_t *status, uint16_t *datalen); + void HTTP_POST_end(void); + void setUserAgent(FONAFlashStringPtr useragent); + + // HTTPS + void setHTTPSRedirect(boolean onoff); + + // PWM (buzzer) + boolean setPWM(uint16_t period, uint8_t duty = 50); + + // Phone calls + boolean callPhone(char *phonenum); + uint8_t getCallStatus(void); + boolean hangUp(void); + boolean pickUp(void); + boolean callerIdNotification(boolean enable, uint8_t interrupt = 0); + boolean incomingCallNumber(char* phonenum); + + // Helper functions to verify responses. + boolean expectReply(FONAFlashStringPtr reply, uint16_t timeout = 10000); + boolean sendCheckReply(char *send, char *reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + boolean sendCheckReply(FONAFlashStringPtr send, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + boolean sendCheckReply(char* send, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + + + protected: + int8_t _rstpin; + uint8_t _type; + + char replybuffer[255]; + FONAFlashStringPtr apn; + FONAFlashStringPtr apnusername; + FONAFlashStringPtr apnpassword; + boolean httpsredirect; + FONAFlashStringPtr useragent; + FONAFlashStringPtr ok_reply; + + // HTTP helpers + boolean HTTP_setup(char *url); + + void flushInput(); + uint16_t readRaw(uint16_t b); + uint8_t readline(uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS, boolean multiline = false); + uint8_t getReply(char *send, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + uint8_t getReply(FONAFlashStringPtr send, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + uint8_t getReply(FONAFlashStringPtr prefix, char *suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + uint8_t getReply(FONAFlashStringPtr prefix, int32_t suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + uint8_t getReply(FONAFlashStringPtr prefix, int32_t suffix1, int32_t suffix2, uint16_t timeout); // Don't set default value or else function call is ambiguous. + uint8_t getReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + + boolean sendCheckReply(FONAFlashStringPtr prefix, char *suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + boolean sendCheckReply(FONAFlashStringPtr prefix, int32_t suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + boolean sendCheckReply(FONAFlashStringPtr prefix, int32_t suffix, int32_t suffix2, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + boolean sendCheckReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + + + boolean parseReply(FONAFlashStringPtr toreply, + uint16_t *v, char divider = ',', uint8_t index=0); + boolean parseReply(FONAFlashStringPtr toreply, + char *v, char divider = ',', uint8_t index=0); + boolean parseReplyQuoted(FONAFlashStringPtr toreply, + char *v, int maxlen, char divider, uint8_t index); + + boolean sendParseReply(FONAFlashStringPtr tosend, + FONAFlashStringPtr toreply, + uint16_t *v, char divider = ',', uint8_t index=0); + + static boolean _incomingCall; + static void onIncomingCall(); + + FONAStreamType *mySerial; +}; + +class Adafruit_FONA_3G : public Adafruit_FONA { + + public: + Adafruit_FONA_3G (int8_t r) : Adafruit_FONA(r) { _type = FONA3G_A; } + + boolean getBattVoltage(uint16_t *v); + boolean playToolkitTone(uint8_t t, uint16_t len); + boolean hangUp(void); + boolean pickUp(void); + boolean enableGPRS(boolean onoff); + boolean enableGPS(boolean onoff); + + protected: + boolean parseReply(FONAFlashStringPtr toreply, + float *f, char divider, uint8_t index); + + boolean sendParseReply(FONAFlashStringPtr tosend, + FONAFlashStringPtr toreply, + float *f, char divider = ',', uint8_t index=0); +}; + +#endif diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/README.md b/feather_sensor_lte/libraries/Adafruit_FONA_Library/README.md new file mode 100644 index 0000000..73452ca --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_FONA_Library/README.md @@ -0,0 +1,29 @@ +# Adafruit FONA Library [![Build Status](https://secure.travis-ci.org/adafruit/Adafruit_FONA_Library.svg?branch=master)](https://travis-ci.org/adafruit/Adafruit_FONA_Library) + +**This library requires Arduino v1.0.6 or higher** + +This is a library for the Adafruit FONA Cellular GSM Breakouts etc + +Designed specifically to work with the Adafruit FONA Breakout + * https://www.adafruit.com/products/1946 + * https://www.adafruit.com/products/1963 + * http://www.adafruit.com/products/2468 + * http://www.adafruit.com/products/2542 + +These modules use TTL Serial to communicate, 2 pins are required to interface + +Adafruit invests time and resources providing this open source code, +please support Adafruit and open-source hardware by purchasing +products from Adafruit! + +Check out the links above for our tutorials and wiring diagrams + +Written by Limor Fried/Ladyada for Adafruit Industries. +BSD license, all text above must be included in any redistribution +With updates from Samy Kamkar + +To download. click the DOWNLOADS button in the top right corner, rename the uncompressed folder Adafruit_FONA +Check that the Adafruit_FONA folder contains Adafruit_FONA.cpp and Adafruit_FONA.h + +Place the Adafruit_FONA library folder your *arduinosketchfolder*/libraries/ folder. +You may need to create the libraries subfolder if its your first library. Restart the IDE. diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/.esp8266.test.skip b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/.esp8266.test.skip new file mode 100644 index 0000000..e69de29 diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino new file mode 100644 index 0000000..b0be4c5 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino @@ -0,0 +1,77 @@ +/*************************************************** + This is an example for our Adafruit FONA Cellular Module + since the FONA 3G does not do auto-baud very well, this demo + fixes the baud rate to 4800 from the default 115200 + + Designed specifically to work with the Adafruit FONA 3G + ----> http://www.adafruit.com/products/2691 + ----> http://www.adafruit.com/products/2687 + + These cellular modules use TTL Serial to communicate, 2 pins are + required to interface + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ****************************************************/ + +#include "Adafruit_FONA.h" + +#define FONA_RX 2 +#define FONA_TX 3 +#define FONA_RST 4 + +// this is a large buffer for replies +char replybuffer[255]; + +// We default to using software serial. If you want to use hardware serial +// (because softserial isnt supported) comment out the following three lines +// and uncomment the HardwareSerial line +#include +SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); +SoftwareSerial *fonaSerial = &fonaSS; + +// Hardware serial is also possible! +// HardwareSerial *fonaSerial = &Serial1; + +Adafruit_FONA fona = Adafruit_FONA(FONA_RST); + +uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); + +void setup() { + while (!Serial); + + Serial.begin(115200); + Serial.println(F("FONA set baudrate")); + + Serial.println(F("First trying 115200 baud")); + // start at 115200 baud + fonaSerial->begin(115200); + fona.begin(*fonaSerial); + + // send the command to reset the baud rate to 4800 + fona.setBaudrate(4800); + + // restart with 4800 baud + fonaSerial->begin(4800); + Serial.println(F("Initializing @ 4800 baud...")); + + if (! fona.begin(*fonaSerial)) { + Serial.println(F("Couldn't find FONA")); + while(1); + } + Serial.println(F("FONA is OK")); + + // Print module IMEI number. + char imei[15] = {0}; // MUST use a 16 character buffer for IMEI! + uint8_t imeiLen = fona.getIMEI(imei); + if (imeiLen > 0) { + Serial.print("Module IMEI: "); Serial.println(imei); + } + +} + +void loop() { +} \ No newline at end of file diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/.esp8266.test.skip b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/.esp8266.test.skip new file mode 100644 index 0000000..e69de29 diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino new file mode 100644 index 0000000..7201641 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino @@ -0,0 +1,131 @@ +/*************************************************** + This is an example for our Adafruit FONA Cellular Module + + Designed specifically to work with the Adafruit FONA + ----> http://www.adafruit.com/products/1946 + ----> http://www.adafruit.com/products/1963 + ----> http://www.adafruit.com/products/2468 + ----> http://www.adafruit.com/products/2542 + + These cellular modules use TTL Serial to communicate, 2 pins are + required to interface + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ****************************************************/ + +/* +THIS CODE IS STILL IN PROGRESS! + +Open up the serial console on the Arduino at 115200 baud to interact with FONA + + +This code will receive an SMS, identify the sender's phone number, and automatically send a response + +For use with FONA 800 & 808, not 3G +*/ + +#include "Adafruit_FONA.h" + +#define FONA_RX 2 +#define FONA_TX 3 +#define FONA_RST 4 + +// this is a large buffer for replies +char replybuffer[255]; + +// We default to using software serial. If you want to use hardware serial +// (because softserial isnt supported) comment out the following three lines +// and uncomment the HardwareSerial line +#include +SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); +SoftwareSerial *fonaSerial = &fonaSS; + +// Hardware serial is also possible! +// HardwareSerial *fonaSerial = &Serial1; + +Adafruit_FONA fona = Adafruit_FONA(FONA_RST); + +uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); + +void setup() { + while (!Serial); + + Serial.begin(115200); + Serial.println(F("FONA SMS caller ID test")); + Serial.println(F("Initializing....(May take 3 seconds)")); + + // make it slow so its easy to read! + fonaSerial->begin(4800); + if (! fona.begin(*fonaSerial)) { + Serial.println(F("Couldn't find FONA")); + while(1); + } + Serial.println(F("FONA is OK")); + + // Print SIM card IMEI number. + char imei[15] = {0}; // MUST use a 16 character buffer for IMEI! + uint8_t imeiLen = fona.getIMEI(imei); + if (imeiLen > 0) { + Serial.print("SIM card IMEI: "); Serial.println(imei); + } + + Serial.println("FONA Ready"); +} + + +char fonaInBuffer[64]; //for notifications from the FONA + +void loop() { + + char* bufPtr = fonaInBuffer; //handy buffer pointer + + if (fona.available()) //any data available from the FONA? + { + int slot = 0; //this will be the slot number of the SMS + int charCount = 0; + //Read the notification into fonaInBuffer + do { + *bufPtr = fona.read(); + Serial.write(*bufPtr); + delay(1); + } while ((*bufPtr++ != '\n') && (fona.available()) && (++charCount < (sizeof(fonaInBuffer)-1))); + + //Add a terminal NULL to the notification string + *bufPtr = 0; + + //Scan the notification string for an SMS received notification. + // If it's an SMS message, we'll get the slot number in 'slot' + if (1 == sscanf(fonaInBuffer, "+CMTI: \"SM\",%d", &slot)) { + Serial.print("slot: "); Serial.println(slot); + + char callerIDbuffer[32]; //we'll store the SMS sender number in here + + // Retrieve SMS sender address/phone number. + if (! fona.getSMSSender(slot, callerIDbuffer, 31)) { + Serial.println("Didn't find SMS message in slot!"); + } + Serial.print(F("FROM: ")); Serial.println(callerIDbuffer); + + //Send back an automatic response + Serial.println("Sending reponse..."); + if (!fona.sendSMS(callerIDbuffer, "Hey, I got your text!")) { + Serial.println(F("Failed")); + } else { + Serial.println(F("Sent!")); + } + + // delete the original msg after it is processed + // otherwise, we will fill up all the slots + // and then we won't be able to receive SMS anymore + if (fona.deleteSMS(slot)) { + Serial.println(F("OK!")); + } else { + Serial.println(F("Couldn't delete")); + } + } + } +} diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/.esp8266.test.skip b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/.esp8266.test.skip new file mode 100644 index 0000000..e69de29 diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino new file mode 100644 index 0000000..1b27732 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino @@ -0,0 +1,886 @@ +/*************************************************** + This is an example for our Adafruit FONA Cellular Module + + Designed specifically to work with the Adafruit FONA + ----> http://www.adafruit.com/products/1946 + ----> http://www.adafruit.com/products/1963 + ----> http://www.adafruit.com/products/2468 + ----> http://www.adafruit.com/products/2542 + + These cellular modules use TTL Serial to communicate, 2 pins are + required to interface + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ****************************************************/ + +/* +THIS CODE IS STILL IN PROGRESS! + +Open up the serial console on the Arduino at 115200 baud to interact with FONA + +Note that if you need to set a GPRS APN, username, and password scroll down to +the commented section below at the end of the setup() function. +*/ +#include "Adafruit_FONA.h" + +#define FONA_RX 2 +#define FONA_TX 3 +#define FONA_RST 4 + +// this is a large buffer for replies +char replybuffer[255]; + +// We default to using software serial. If you want to use hardware serial +// (because softserial isnt supported) comment out the following three lines +// and uncomment the HardwareSerial line +#include +SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); +SoftwareSerial *fonaSerial = &fonaSS; + +// Hardware serial is also possible! +// HardwareSerial *fonaSerial = &Serial1; + +// Use this for FONA 800 and 808s +Adafruit_FONA fona = Adafruit_FONA(FONA_RST); +// Use this one for FONA 3G +//Adafruit_FONA_3G fona = Adafruit_FONA_3G(FONA_RST); + +uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); + +uint8_t type; + +void setup() { + while (!Serial); + + Serial.begin(115200); + Serial.println(F("FONA basic test")); + Serial.println(F("Initializing....(May take 3 seconds)")); + + fonaSerial->begin(4800); + if (! fona.begin(*fonaSerial)) { + Serial.println(F("Couldn't find FONA")); + while (1); + } + type = fona.type(); + Serial.println(F("FONA is OK")); + Serial.print(F("Found ")); + switch (type) { + case FONA800L: + Serial.println(F("FONA 800L")); break; + case FONA800H: + Serial.println(F("FONA 800H")); break; + case FONA808_V1: + Serial.println(F("FONA 808 (v1)")); break; + case FONA808_V2: + Serial.println(F("FONA 808 (v2)")); break; + case FONA3G_A: + Serial.println(F("FONA 3G (American)")); break; + case FONA3G_E: + Serial.println(F("FONA 3G (European)")); break; + default: + Serial.println(F("???")); break; + } + + // Print module IMEI number. + char imei[15] = {0}; // MUST use a 16 character buffer for IMEI! + uint8_t imeiLen = fona.getIMEI(imei); + if (imeiLen > 0) { + Serial.print("Module IMEI: "); Serial.println(imei); + } + + // Optionally configure a GPRS APN, username, and password. + // You might need to do this to access your network's GPRS/data + // network. Contact your provider for the exact APN, username, + // and password values. Username and password are optional and + // can be removed, but APN is required. + //fona.setGPRSNetworkSettings(F("your APN"), F("your username"), F("your password")); + + // Optionally configure HTTP gets to follow redirects over SSL. + // Default is not to follow SSL redirects, however if you uncomment + // the following line then redirects over SSL will be followed. + //fona.setHTTPSRedirect(true); + + printMenu(); +} + +void printMenu(void) { + Serial.println(F("-------------------------------------")); + Serial.println(F("[?] Print this menu")); + Serial.println(F("[a] read the ADC 2.8V max (FONA800 & 808)")); + Serial.println(F("[b] read the Battery V and % charged")); + Serial.println(F("[C] read the SIM CCID")); + Serial.println(F("[U] Unlock SIM with PIN code")); + Serial.println(F("[i] read RSSI")); + Serial.println(F("[n] get Network status")); + Serial.println(F("[v] set audio Volume")); + Serial.println(F("[V] get Volume")); + Serial.println(F("[H] set Headphone audio (FONA800 & 808)")); + Serial.println(F("[e] set External audio (FONA800 & 808)")); + Serial.println(F("[T] play audio Tone")); + Serial.println(F("[P] PWM/Buzzer out (FONA800 & 808)")); + + // FM (SIM800 only!) + Serial.println(F("[f] tune FM radio (FONA800)")); + Serial.println(F("[F] turn off FM (FONA800)")); + Serial.println(F("[m] set FM volume (FONA800)")); + Serial.println(F("[M] get FM volume (FONA800)")); + Serial.println(F("[q] get FM station signal level (FONA800)")); + + // Phone + Serial.println(F("[c] make phone Call")); + Serial.println(F("[A] get call status")); + Serial.println(F("[h] Hang up phone")); + Serial.println(F("[p] Pick up phone")); + + // SMS + Serial.println(F("[N] Number of SMSs")); + Serial.println(F("[r] Read SMS #")); + Serial.println(F("[R] Read All SMS")); + Serial.println(F("[d] Delete SMS #")); + Serial.println(F("[s] Send SMS")); + Serial.println(F("[u] Send USSD")); + + // Time + Serial.println(F("[y] Enable network time sync (FONA 800 & 808)")); + Serial.println(F("[Y] Enable NTP time sync (GPRS FONA 800 & 808)")); + Serial.println(F("[t] Get network time")); + + // GPRS + Serial.println(F("[G] Enable GPRS")); + Serial.println(F("[g] Disable GPRS")); + Serial.println(F("[l] Query GSMLOC (GPRS)")); + Serial.println(F("[w] Read webpage (GPRS)")); + Serial.println(F("[W] Post to website (GPRS)")); + + // GPS + if ((type == FONA3G_A) || (type == FONA3G_E) || (type == FONA808_V1) || (type == FONA808_V2)) { + Serial.println(F("[O] Turn GPS on (FONA 808 & 3G)")); + Serial.println(F("[o] Turn GPS off (FONA 808 & 3G)")); + Serial.println(F("[L] Query GPS location (FONA 808 & 3G)")); + if (type == FONA808_V1) { + Serial.println(F("[x] GPS fix status (FONA808 v1 only)")); + } + Serial.println(F("[E] Raw NMEA out (FONA808)")); + } + + Serial.println(F("[S] create Serial passthru tunnel")); + Serial.println(F("-------------------------------------")); + Serial.println(F("")); + +} +void loop() { + Serial.print(F("FONA> ")); + while (! Serial.available() ) { + if (fona.available()) { + Serial.write(fona.read()); + } + } + + char command = Serial.read(); + Serial.println(command); + + + switch (command) { + case '?': { + printMenu(); + break; + } + + case 'a': { + // read the ADC + uint16_t adc; + if (! fona.getADCVoltage(&adc)) { + Serial.println(F("Failed to read ADC")); + } else { + Serial.print(F("ADC = ")); Serial.print(adc); Serial.println(F(" mV")); + } + break; + } + + case 'b': { + // read the battery voltage and percentage + uint16_t vbat; + if (! fona.getBattVoltage(&vbat)) { + Serial.println(F("Failed to read Batt")); + } else { + Serial.print(F("VBat = ")); Serial.print(vbat); Serial.println(F(" mV")); + } + + + if (! fona.getBattPercent(&vbat)) { + Serial.println(F("Failed to read Batt")); + } else { + Serial.print(F("VPct = ")); Serial.print(vbat); Serial.println(F("%")); + } + + break; + } + + case 'U': { + // Unlock the SIM with a PIN code + char PIN[5]; + flushSerial(); + Serial.println(F("Enter 4-digit PIN")); + readline(PIN, 3); + Serial.println(PIN); + Serial.print(F("Unlocking SIM card: ")); + if (! fona.unlockSIM(PIN)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + + case 'C': { + // read the CCID + fona.getSIMCCID(replybuffer); // make sure replybuffer is at least 21 bytes! + Serial.print(F("SIM CCID = ")); Serial.println(replybuffer); + break; + } + + case 'i': { + // read the RSSI + uint8_t n = fona.getRSSI(); + int8_t r; + + Serial.print(F("RSSI = ")); Serial.print(n); Serial.print(": "); + if (n == 0) r = -115; + if (n == 1) r = -111; + if (n == 31) r = -52; + if ((n >= 2) && (n <= 30)) { + r = map(n, 2, 30, -110, -54); + } + Serial.print(r); Serial.println(F(" dBm")); + + break; + } + + case 'n': { + // read the network/cellular status + uint8_t n = fona.getNetworkStatus(); + Serial.print(F("Network status ")); + Serial.print(n); + Serial.print(F(": ")); + if (n == 0) Serial.println(F("Not registered")); + if (n == 1) Serial.println(F("Registered (home)")); + if (n == 2) Serial.println(F("Not registered (searching)")); + if (n == 3) Serial.println(F("Denied")); + if (n == 4) Serial.println(F("Unknown")); + if (n == 5) Serial.println(F("Registered roaming")); + break; + } + + /*** Audio ***/ + case 'v': { + // set volume + flushSerial(); + if ( (type == FONA3G_A) || (type == FONA3G_E) ) { + Serial.print(F("Set Vol [0-8] ")); + } else { + Serial.print(F("Set Vol % [0-100] ")); + } + uint8_t vol = readnumber(); + Serial.println(); + if (! fona.setVolume(vol)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + + case 'V': { + uint8_t v = fona.getVolume(); + Serial.print(v); + if ( (type == FONA3G_A) || (type == FONA3G_E) ) { + Serial.println(" / 8"); + } else { + Serial.println("%"); + } + break; + } + + case 'H': { + // Set Headphone output + if (! fona.setAudio(FONA_HEADSETAUDIO)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + fona.setMicVolume(FONA_HEADSETAUDIO, 15); + break; + } + case 'e': { + // Set External output + if (! fona.setAudio(FONA_EXTAUDIO)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + + fona.setMicVolume(FONA_EXTAUDIO, 10); + break; + } + + case 'T': { + // play tone + flushSerial(); + Serial.print(F("Play tone #")); + uint8_t kittone = readnumber(); + Serial.println(); + // play for 1 second (1000 ms) + if (! fona.playToolkitTone(kittone, 1000)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + + /*** FM Radio ***/ + + case 'f': { + // get freq + flushSerial(); + Serial.print(F("FM Freq (eg 1011 == 101.1 MHz): ")); + uint16_t station = readnumber(); + Serial.println(); + // FM radio ON using headset + if (fona.FMradio(true, FONA_HEADSETAUDIO)) { + Serial.println(F("Opened")); + } + if (! fona.tuneFMradio(station)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("Tuned")); + } + break; + } + case 'F': { + // FM radio off + if (! fona.FMradio(false)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + case 'm': { + // Set FM volume. + flushSerial(); + Serial.print(F("Set FM Vol [0-6]:")); + uint8_t vol = readnumber(); + Serial.println(); + if (!fona.setFMVolume(vol)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + case 'M': { + // Get FM volume. + uint8_t fmvol = fona.getFMVolume(); + if (fmvol < 0) { + Serial.println(F("Failed")); + } else { + Serial.print(F("FM volume: ")); + Serial.println(fmvol, DEC); + } + break; + } + case 'q': { + // Get FM station signal level (in decibels). + flushSerial(); + Serial.print(F("FM Freq (eg 1011 == 101.1 MHz): ")); + uint16_t station = readnumber(); + Serial.println(); + int8_t level = fona.getFMSignalLevel(station); + if (level < 0) { + Serial.println(F("Failed! Make sure FM radio is on (tuned to station).")); + } else { + Serial.print(F("Signal level (dB): ")); + Serial.println(level, DEC); + } + break; + } + + /*** PWM ***/ + + case 'P': { + // PWM Buzzer output @ 2KHz max + flushSerial(); + Serial.print(F("PWM Freq, 0 = Off, (1-2000): ")); + uint16_t freq = readnumber(); + Serial.println(); + if (! fona.setPWM(freq)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + + /*** Call ***/ + case 'c': { + // call a phone! + char number[30]; + flushSerial(); + Serial.print(F("Call #")); + readline(number, 30); + Serial.println(); + Serial.print(F("Calling ")); Serial.println(number); + if (!fona.callPhone(number)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("Sent!")); + } + + break; + } + case 'A': { + // get call status + int8_t callstat = fona.getCallStatus(); + switch (callstat) { + case 0: Serial.println(F("Ready")); break; + case 1: Serial.println(F("Could not get status")); break; + case 3: Serial.println(F("Ringing (incoming)")); break; + case 4: Serial.println(F("Ringing/in progress (outgoing)")); break; + default: Serial.println(F("Unknown")); break; + } + break; + } + + case 'h': { + // hang up! + if (! fona.hangUp()) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + + case 'p': { + // pick up! + if (! fona.pickUp()) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + + /*** SMS ***/ + + case 'N': { + // read the number of SMS's! + int8_t smsnum = fona.getNumSMS(); + if (smsnum < 0) { + Serial.println(F("Could not read # SMS")); + } else { + Serial.print(smsnum); + Serial.println(F(" SMS's on SIM card!")); + } + break; + } + case 'r': { + // read an SMS + flushSerial(); + Serial.print(F("Read #")); + uint8_t smsn = readnumber(); + Serial.print(F("\n\rReading SMS #")); Serial.println(smsn); + + // Retrieve SMS sender address/phone number. + if (! fona.getSMSSender(smsn, replybuffer, 250)) { + Serial.println("Failed!"); + break; + } + Serial.print(F("FROM: ")); Serial.println(replybuffer); + + // Retrieve SMS value. + uint16_t smslen; + if (! fona.readSMS(smsn, replybuffer, 250, &smslen)) { // pass in buffer and max len! + Serial.println("Failed!"); + break; + } + Serial.print(F("***** SMS #")); Serial.print(smsn); + Serial.print(" ("); Serial.print(smslen); Serial.println(F(") bytes *****")); + Serial.println(replybuffer); + Serial.println(F("*****")); + + break; + } + case 'R': { + // read all SMS + int8_t smsnum = fona.getNumSMS(); + uint16_t smslen; + int8_t smsn; + + if ( (type == FONA3G_A) || (type == FONA3G_E) ) { + smsn = 0; // zero indexed + smsnum--; + } else { + smsn = 1; // 1 indexed + } + + for ( ; smsn <= smsnum; smsn++) { + Serial.print(F("\n\rReading SMS #")); Serial.println(smsn); + if (!fona.readSMS(smsn, replybuffer, 250, &smslen)) { // pass in buffer and max len! + Serial.println(F("Failed!")); + break; + } + // if the length is zero, its a special case where the index number is higher + // so increase the max we'll look at! + if (smslen == 0) { + Serial.println(F("[empty slot]")); + smsnum++; + continue; + } + + Serial.print(F("***** SMS #")); Serial.print(smsn); + Serial.print(" ("); Serial.print(smslen); Serial.println(F(") bytes *****")); + Serial.println(replybuffer); + Serial.println(F("*****")); + } + break; + } + + case 'd': { + // delete an SMS + flushSerial(); + Serial.print(F("Delete #")); + uint8_t smsn = readnumber(); + + Serial.print(F("\n\rDeleting SMS #")); Serial.println(smsn); + if (fona.deleteSMS(smsn)) { + Serial.println(F("OK!")); + } else { + Serial.println(F("Couldn't delete")); + } + break; + } + + case 's': { + // send an SMS! + char sendto[21], message[141]; + flushSerial(); + Serial.print(F("Send to #")); + readline(sendto, 20); + Serial.println(sendto); + Serial.print(F("Type out one-line message (140 char): ")); + readline(message, 140); + Serial.println(message); + if (!fona.sendSMS(sendto, message)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("Sent!")); + } + + break; + } + + case 'u': { + // send a USSD! + char message[141]; + flushSerial(); + Serial.print(F("Type out one-line message (140 char): ")); + readline(message, 140); + Serial.println(message); + + uint16_t ussdlen; + if (!fona.sendUSSD(message, replybuffer, 250, &ussdlen)) { // pass in buffer and max len! + Serial.println(F("Failed")); + } else { + Serial.println(F("Sent!")); + Serial.print(F("***** USSD Reply")); + Serial.print(" ("); Serial.print(ussdlen); Serial.println(F(") bytes *****")); + Serial.println(replybuffer); + Serial.println(F("*****")); + } + } + + /*** Time ***/ + + case 'y': { + // enable network time sync + if (!fona.enableNetworkTimeSync(true)) + Serial.println(F("Failed to enable")); + break; + } + + case 'Y': { + // enable NTP time sync + if (!fona.enableNTPTimeSync(true, F("pool.ntp.org"))) + Serial.println(F("Failed to enable")); + break; + } + + case 't': { + // read the time + char buffer[23]; + + fona.getTime(buffer, 23); // make sure replybuffer is at least 23 bytes! + Serial.print(F("Time = ")); Serial.println(buffer); + break; + } + + + /*********************************** GPS (SIM808 only) */ + + case 'o': { + // turn GPS off + if (!fona.enableGPS(false)) + Serial.println(F("Failed to turn off")); + break; + } + case 'O': { + // turn GPS on + if (!fona.enableGPS(true)) + Serial.println(F("Failed to turn on")); + break; + } + case 'x': { + int8_t stat; + // check GPS fix + stat = fona.GPSstatus(); + if (stat < 0) + Serial.println(F("Failed to query")); + if (stat == 0) Serial.println(F("GPS off")); + if (stat == 1) Serial.println(F("No fix")); + if (stat == 2) Serial.println(F("2D fix")); + if (stat == 3) Serial.println(F("3D fix")); + break; + } + + case 'L': { + // check for GPS location + char gpsdata[120]; + fona.getGPS(0, gpsdata, 120); + if (type == FONA808_V1) + Serial.println(F("Reply in format: mode,longitude,latitude,altitude,utctime(yyyymmddHHMMSS),ttff,satellites,speed,course")); + else + Serial.println(F("Reply in format: mode,fixstatus,utctime(yyyymmddHHMMSS),latitude,longitude,altitude,speed,course,fixmode,reserved1,HDOP,PDOP,VDOP,reserved2,view_satellites,used_satellites,reserved3,C/N0max,HPA,VPA")); + Serial.println(gpsdata); + + break; + } + + case 'E': { + flushSerial(); + if (type == FONA808_V1) { + Serial.print(F("GPS NMEA output sentences (0 = off, 34 = RMC+GGA, 255 = all)")); + } else { + Serial.print(F("On (1) or Off (0)? ")); + } + uint8_t nmeaout = readnumber(); + + // turn on NMEA output + fona.enableGPSNMEA(nmeaout); + + break; + } + + /*********************************** GPRS */ + + case 'g': { + // turn GPRS off + if (!fona.enableGPRS(false)) + Serial.println(F("Failed to turn off")); + break; + } + case 'G': { + // turn GPRS on + if (!fona.enableGPRS(true)) + Serial.println(F("Failed to turn on")); + break; + } + case 'l': { + // check for GSMLOC (requires GPRS) + uint16_t returncode; + + if (!fona.getGSMLoc(&returncode, replybuffer, 250)) + Serial.println(F("Failed!")); + if (returncode == 0) { + Serial.println(replybuffer); + } else { + Serial.print(F("Fail code #")); Serial.println(returncode); + } + + break; + } + case 'w': { + // read website URL + uint16_t statuscode; + int16_t length; + char url[80]; + + flushSerial(); + Serial.println(F("NOTE: in beta! Use small webpages to read!")); + Serial.println(F("URL to read (e.g. www.adafruit.com/testwifi/index.html):")); + Serial.print(F("http://")); readline(url, 79); + Serial.println(url); + + Serial.println(F("****")); + if (!fona.HTTP_GET_start(url, &statuscode, (uint16_t *)&length)) { + Serial.println("Failed!"); + break; + } + while (length > 0) { + while (fona.available()) { + char c = fona.read(); + + // Serial.write is too slow, we'll write directly to Serial register! +#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) + loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data register empty. */ + UDR0 = c; +#else + Serial.write(c); +#endif + length--; + if (! length) break; + } + } + Serial.println(F("\n****")); + fona.HTTP_GET_end(); + break; + } + + case 'W': { + // Post data to website + uint16_t statuscode; + int16_t length; + char url[80]; + char data[80]; + + flushSerial(); + Serial.println(F("NOTE: in beta! Use simple websites to post!")); + Serial.println(F("URL to post (e.g. httpbin.org/post):")); + Serial.print(F("http://")); readline(url, 79); + Serial.println(url); + Serial.println(F("Data to post (e.g. \"foo\" or \"{\"simple\":\"json\"}\"):")); + readline(data, 79); + Serial.println(data); + + Serial.println(F("****")); + if (!fona.HTTP_POST_start(url, F("text/plain"), (uint8_t *) data, strlen(data), &statuscode, (uint16_t *)&length)) { + Serial.println("Failed!"); + break; + } + while (length > 0) { + while (fona.available()) { + char c = fona.read(); + +#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) + loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data register empty. */ + UDR0 = c; +#else + Serial.write(c); +#endif + + length--; + if (! length) break; + } + } + Serial.println(F("\n****")); + fona.HTTP_POST_end(); + break; + } + /*****************************************/ + + case 'S': { + Serial.println(F("Creating SERIAL TUBE")); + while (1) { + while (Serial.available()) { + delay(1); + fona.write(Serial.read()); + } + if (fona.available()) { + Serial.write(fona.read()); + } + } + break; + } + + default: { + Serial.println(F("Unknown command")); + printMenu(); + break; + } + } + // flush input + flushSerial(); + while (fona.available()) { + Serial.write(fona.read()); + } + +} + +void flushSerial() { + while (Serial.available()) + Serial.read(); +} + +char readBlocking() { + while (!Serial.available()); + return Serial.read(); +} +uint16_t readnumber() { + uint16_t x = 0; + char c; + while (! isdigit(c = readBlocking())) { + //Serial.print(c); + } + Serial.print(c); + x = c - '0'; + while (isdigit(c = readBlocking())) { + Serial.print(c); + x *= 10; + x += c - '0'; + } + return x; +} + +uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout) { + uint16_t buffidx = 0; + boolean timeoutvalid = true; + if (timeout == 0) timeoutvalid = false; + + while (true) { + if (buffidx > maxbuff) { + //Serial.println(F("SPACE")); + break; + } + + while (Serial.available()) { + char c = Serial.read(); + + //Serial.print(c, HEX); Serial.print("#"); Serial.println(c); + + if (c == '\r') continue; + if (c == 0xA) { + if (buffidx == 0) // the first 0x0A is ignored + continue; + + timeout = 0; // the second 0x0A is the end of the line + timeoutvalid = true; + break; + } + buff[buffidx] = c; + buffidx++; + } + + if (timeoutvalid && timeout == 0) { + //Serial.println(F("TIMEOUT")); + break; + } + delay(1); + } + buff[buffidx] = 0; // null term + return buffidx; +} diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/GPS/.esp8266.test.skip b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/GPS/.esp8266.test.skip new file mode 100644 index 0000000..e69de29 diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino new file mode 100644 index 0000000..cce63d5 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino @@ -0,0 +1,112 @@ +/** + * ___ ___ _ _ _ ___ __ ___ ___ ___ ___ + * | __/ _ \| \| | /_\ ( _ )/ \( _ ) / __| _ \/ __| + * | _| (_) | .` |/ _ \ / _ \ () / _ \ | (_ | _/\__ \ + * |_| \___/|_|\_/_/ \_\ \___/\__/\___/ \___|_| |___/ + * + * This example is meant to work with the Adafruit + * FONA 808 or 3G Shield or Breakout + * + * Copyright: 2015 Adafruit + * Author: Todd Treece + * Licence: MIT + * + */ +#include "Adafruit_FONA.h" + +// standard pins for the shield, adjust as necessary +#define FONA_RX 2 +#define FONA_TX 3 +#define FONA_RST 4 + +// We default to using software serial. If you want to use hardware serial +// (because softserial isnt supported) comment out the following three lines +// and uncomment the HardwareSerial line +#include +SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); +SoftwareSerial *fonaSerial = &fonaSS; + +// Hardware serial is also possible! +// HardwareSerial *fonaSerial = &Serial1; + +Adafruit_FONA fona = Adafruit_FONA(FONA_RST); + +// Have a FONA 3G? use this object type instead +//Adafruit_FONA_3G fona = Adafruit_FONA_3G(FONA_RST); + + +void setup() { + + while (! Serial); + + Serial.begin(115200); + Serial.println(F("Adafruit FONA 808 & 3G GPS demo")); + Serial.println(F("Initializing FONA... (May take a few seconds)")); + + fonaSerial->begin(4800); + if (! fona.begin(*fonaSerial)) { + Serial.println(F("Couldn't find FONA")); + while(1); + } + Serial.println(F("FONA is OK")); + // Try to enable GPRS + + + Serial.println(F("Enabling GPS...")); + fona.enableGPS(true); +} + +void loop() { + delay(2000); + + float latitude, longitude, speed_kph, heading, speed_mph, altitude; + + // if you ask for an altitude reading, getGPS will return false if there isn't a 3D fix + boolean gps_success = fona.getGPS(&latitude, &longitude, &speed_kph, &heading, &altitude); + + if (gps_success) { + + Serial.print("GPS lat:"); + Serial.println(latitude, 6); + Serial.print("GPS long:"); + Serial.println(longitude, 6); + Serial.print("GPS speed KPH:"); + Serial.println(speed_kph); + Serial.print("GPS speed MPH:"); + speed_mph = speed_kph * 0.621371192; + Serial.println(speed_mph); + Serial.print("GPS heading:"); + Serial.println(heading); + Serial.print("GPS altitude:"); + Serial.println(altitude); + + } else { + Serial.println("Waiting for FONA GPS 3D fix..."); + } + + // Fona 3G doesnt have GPRSlocation :/ + if ((fona.type() == FONA3G_A) || (fona.type() == FONA3G_E)) + return; + // Check for network, then GPRS + Serial.println(F("Checking for Cell network...")); + if (fona.getNetworkStatus() == 1) { + // network & GPRS? Great! Print out the GSM location to compare + boolean gsmloc_success = fona.getGSMLoc(&latitude, &longitude); + + if (gsmloc_success) { + Serial.print("GSMLoc lat:"); + Serial.println(latitude, 6); + Serial.print("GSMLoc long:"); + Serial.println(longitude, 6); + } else { + Serial.println("GSM location failed..."); + Serial.println(F("Disabling GPRS")); + fona.enableGPRS(false); + Serial.println(F("Enabling GPRS")); + if (!fona.enableGPRS(true)) { + Serial.println(F("Failed to turn GPRS on")); + } + } + } +} + diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/.esp8266.test.skip b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/.esp8266.test.skip new file mode 100644 index 0000000..e69de29 diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino new file mode 100644 index 0000000..8dba308 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino @@ -0,0 +1,62 @@ +// FONA Incoming Call Number Example +// Listens for a call and displays the phone number of the caller (if available). +// Use this example to add phone call detection to your own FONA sketch. +#include "Adafruit_FONA.h" + +// Pins which are connected to the FONA. +// Note that this is different from FONAtest! +#define FONA_RX 3 +#define FONA_TX 4 +#define FONA_RST 5 + +// Note you need to map interrupt number to pin number +// for your board. On an Uno & Mega interrupt 0 is +// digital pin 2, and on a Leonardo interrupt 0 is +// digital pin 3. See this page for a complete table: +// http://arduino.cc/en/Reference/attachInterrupt +// Make sure this interrupt pin is connected to FONA RI! +#define FONA_RI_INTERRUPT 0 + +// We default to using software serial. If you want to use hardware serial +// (because softserial isnt supported) comment out the following three lines +// and uncomment the HardwareSerial line +#include +SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); +SoftwareSerial *fonaSerial = &fonaSS; + +// Hardware serial is also possible! +// HardwareSerial *fonaSerial = &Serial1; + +Adafruit_FONA fona = Adafruit_FONA(FONA_RST); + +void setup() { + Serial.begin(115200); + Serial.println(F("FONA incoming call example")); + Serial.println(F("Initializing....(May take 3 seconds)")); + + fonaSerial->begin(4800); + if (! fona.begin(*fonaSerial)) { + Serial.println(F("Couldn't find FONA")); + while(1); + } + Serial.println(F("FONA is OK")); + + // Enable incoming call notification. + if(fona.callerIdNotification(true, FONA_RI_INTERRUPT)) { + Serial.println(F("Caller id notification enabled.")); + } + else { + Serial.println(F("Caller id notification disabled")); + } +} + +void loop(){ + // Create a small string buffer to hold incoming call number. + char phone[32] = {0}; + // Check for an incoming call. Will return true if a call is incoming. + if(fona.incomingCallNumber(phone)){ + Serial.println(F("RING!")); + Serial.print(F("Phone Number: ")); + Serial.println(phone); + } +} diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/FONAConfig.h b/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/FONAConfig.h new file mode 100644 index 0000000..5fa3e13 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/FONAConfig.h @@ -0,0 +1,34 @@ +/* + * FONAConfig.h -- compile-time configuration + * This is part of the library for the Adafruit FONA Cellular Module + * + * Designed specifically to work with the Adafruit FONA + * ----> https://www.adafruit.com/products/1946 + * ----> https://www.adafruit.com/products/1963 + * ----> http://www.adafruit.com/products/2468 + * ----> http://www.adafruit.com/products/2542 + * + * Adafruit invests time and resources providing this open source code, + * please support Adafruit and open-source hardware by purchasing + * products from Adafruit! + * + * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in + * the Adafruit_FONA_Library and released under the + * BSD license, all text above must be included in any redistribution. + * + * Created on: Jan 16, 2016 + * Author: Pat Deegan + */ + +#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONACONFIG_H_ +#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONACONFIG_H_ + +/* ADAFRUIT_FONA_DEBUG + * When defined, will cause extensive debug output on the + * DebugStream set in the appropriate platform/ header. + */ + +#define ADAFRUIT_FONA_DEBUG + + +#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONACONFIG_H_ */ diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h b/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h new file mode 100644 index 0000000..f8fe878 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h @@ -0,0 +1,33 @@ +/* + * FONAExtIncludes.h -- system-wide includes + * This is part of the library for the Adafruit FONA Cellular Module + * + * Designed specifically to work with the Adafruit FONA + * ----> https://www.adafruit.com/products/1946 + * ----> https://www.adafruit.com/products/1963 + * ----> http://www.adafruit.com/products/2468 + * ----> http://www.adafruit.com/products/2542 + * + * Adafruit invests time and resources providing this open source code, + * please support Adafruit and open-source hardware by purchasing + * products from Adafruit! + * + * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in + * the Adafruit_FONA_Library and released under the + * BSD license, all text above must be included in any redistribution. + * + * Created on: Jan 16, 2016 + * Author: Pat Deegan + */ + + +#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONAEXTINCLUDES_H_ +#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONAEXTINCLUDES_H_ + + +#include "FONAConfig.h" +// include any system-wide includes required here + + + +#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONAEXTINCLUDES_H_ */ diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h b/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h new file mode 100644 index 0000000..85bc8fe --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h @@ -0,0 +1,67 @@ +/* + * FONAPlatStd.h -- standard AVR/Arduino platform. + * + * This is part of the library for the Adafruit FONA Cellular Module + * + * Designed specifically to work with the Adafruit FONA + * ----> https://www.adafruit.com/products/1946 + * ----> https://www.adafruit.com/products/1963 + * ----> http://www.adafruit.com/products/2468 + * ----> http://www.adafruit.com/products/2542 + * + * Adafruit invests time and resources providing this open source code, + * please support Adafruit and open-source hardware by purchasing + * products from Adafruit! + * + * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in + * the Adafruit_FONA_Library and released under the + * BSD license, all text above must be included in any redistribution. + * + * Created on: Jan 16, 2016 + * Author: Pat Deegan + */ + + +#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATSTD_H_ +#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATSTD_H_ + +#include "../FONAConfig.h" + + +#if (ARDUINO >= 100) + #include "Arduino.h" + #if !defined(__SAM3X8E__) && !defined(ARDUINO_ARCH_SAMD) // Arduino Due doesn't support #include + #endif +#else + #include "WProgram.h" + #include +#endif + +#include + + +// DebugStream sets the Stream output to use +// for debug (only applies when ADAFRUIT_FONA_DEBUG +// is defined in config) +#define DebugStream Serial + +#ifdef ADAFRUIT_FONA_DEBUG +// need to do some debugging... +#define DEBUG_PRINT(...) DebugStream.print(__VA_ARGS__) +#define DEBUG_PRINTLN(...) DebugStream.println(__VA_ARGS__) +#endif + +// a few typedefs to keep things portable +typedef Stream FONAStreamType; +typedef const __FlashStringHelper * FONAFlashStringPtr; + +#define prog_char char PROGMEM + +#define prog_char_strcmp(a, b) strcmp_P((a), (b)) +// define prog_char_strncmp(a, b, c) strncmp_P((a), (b), (c)) +#define prog_char_strstr(a, b) strstr_P((a), (b)) +#define prog_char_strlen(a) strlen_P((a)) +#define prog_char_strcpy(to, fromprogmem) strcpy_P((to), (fromprogmem)) +//define prog_char_strncpy(to, from, len) strncpy_P((to), (fromprogmem), (len)) + +#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATSTD_H_ */ diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h b/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h new file mode 100644 index 0000000..0bf98d0 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h @@ -0,0 +1,62 @@ +/* + * FONAPlatform.h -- platform definitions includes. + * + * This is part of the library for the Adafruit FONA Cellular Module + * + * Designed specifically to work with the Adafruit FONA + * ----> https://www.adafruit.com/products/1946 + * ----> https://www.adafruit.com/products/1963 + * ----> http://www.adafruit.com/products/2468 + * ----> http://www.adafruit.com/products/2542 + * + * Adafruit invests time and resources providing this open source code, + * please support Adafruit and open-source hardware by purchasing + * products from Adafruit! + * + * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in + * the Adafruit_FONA_Library and released under the + * BSD license, all text above must be included in any redistribution. + * + * Created on: Jan 16, 2016 + * Author: Pat Deegan + */ + + +#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATFORM_H_ +#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATFORM_H_ + +#include "../FONAConfig.h" + +// only "standard" config supported in this release -- namely AVR-based arduino type affairs +#include "FONAPlatStd.h" + + + +#ifndef DEBUG_PRINT +// debug is disabled + +#define DEBUG_PRINT(...) +#define DEBUG_PRINTLN(...) + +#endif + + +#ifndef prog_char_strcmp +#define prog_char_strcmp(a, b) strcmp((a), (b)) +#endif + +#ifndef prog_char_strstr +#define prog_char_strstr(a, b) strstr((a), (b)) +#endif + +#ifndef prog_char_strlen +#define prog_char_strlen(a) strlen((a)) +#endif + + +#ifndef prog_char_strcpy +#define prog_char_strcpy(to, fromprogmem) strcpy((to), (fromprogmem)) +#endif + + +#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATFORM_H_ */ diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/library.properties b/feather_sensor_lte/libraries/Adafruit_FONA_Library/library.properties new file mode 100644 index 0000000..bb7099c --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_FONA_Library/library.properties @@ -0,0 +1,9 @@ +name=Adafruit FONA Library +version=1.3.2 +author=Adafruit +maintainer=Adafruit +sentence=Arduino library for the Adafruit FONA +paragraph=Arduino library for the Adafruit FONA +category=Communication +url=https://github.com/adafruit/Adafruit_FONA_Library +architectures=* diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp new file mode 100644 index 0000000..9448278 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp @@ -0,0 +1,4 @@ +#include "Adafruit_SleepyDog.h" + +// Global instance of the main class for sketches to use. +WatchdogType Watchdog; diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h new file mode 100644 index 0000000..4cdf4b4 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h @@ -0,0 +1,28 @@ +#ifndef ADAFRUIT_SLEEPYDOG_H +#define ADAFRUIT_SLEEPYDOG_H + +// Platform-specific code goes below. Each #ifdef should check for the presence +// of their platform and pull in the appropriate watchdog implementation type, +// then typedef it to WatchdogType so the .cpp file can create a global instance. +#if defined(ARDUINO_ARCH_AVR) || defined(__AVR__) + #include "utility/WatchdogAVR.h" + typedef WatchdogAVR WatchdogType; +#elif defined(ARDUINO_ARCH_SAMD) + // Arduino Zero / ATSAMD series CPU watchdog support. + #include "utility/WatchdogSAMD.h" + typedef WatchdogSAMD WatchdogType; +#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) + // Teensy 3.x watchdog support. + #include "utility/WatchdogKinetisK.h" + typedef WatchdogKinetisKseries WatchdogType; +#elif defined(__MKL26Z64__) + // Teensy LC watchdog support. + #include "utility/WatchdogKinetisL.h" + typedef WatchdogKinetisLseries WatchdogType; +#else + #error Unsupported platform for the Adafruit Watchdog library! +#endif + +extern WatchdogType Watchdog; + +#endif diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/LICENSE b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/LICENSE new file mode 100644 index 0000000..04ebb92 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Adafruit Industries + +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/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/README.md b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/README.md new file mode 100644 index 0000000..3aa268a --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/README.md @@ -0,0 +1,6 @@ +# Adafruit SleepyDog Arduino Library + +Arduino library to use the watchdog timer for system reset and low power sleep. + +Currently supports the following hardware: +* Arduino Uno or compatible (ATmega328P). diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino new file mode 100644 index 0000000..8d47041 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino @@ -0,0 +1,62 @@ +// Adafruit Watchdog Library Basic Usage Example +// +// Simple example of how to use the watchdog library. +// +// Author: Tony DiCola + +#include + +void setup() { + Serial.begin(115200); + while (!Serial) ; // wait for Arduino Serial Monitor (native USB boards) + Serial.println("Adafruit Watchdog Library Demo!"); + Serial.println(); + + // First a normal example of using the watchdog timer. + // Enable the watchdog by calling Watchdog.enable() as below. This will turn + // on the watchdog timer with a ~4 second timeout before reseting the Arduino. + // The estimated actual milliseconds before reset (in milliseconds) is returned. + // Make sure to reset the watchdog before the countdown expires or the Arduino + // will reset! + int countdownMS = Watchdog.enable(4000); + Serial.print("Enabled the watchdog with max countdown of "); + Serial.print(countdownMS, DEC); + Serial.println(" milliseconds!"); + Serial.println(); + + // Now loop a few times and periodically reset the watchdog. + Serial.println("Looping ten times while resetting the watchdog..."); + for (int i = 1; i <= 10; ++i) { + Serial.print("Loop #"); Serial.println(i, DEC); + delay(1000); + // Reset the watchdog with every loop to make sure the sketch keeps running. + // If you comment out this call watch what happens after about 4 iterations! + Watchdog.reset(); + } + Serial.println(); + + // Disable the watchdog entirely by calling Watchdog.disable(); + Watchdog.disable(); + + // Finally demonstrate the watchdog resetting by enabling it for a shorter + // period of time and waiting a long time without a reset. Notice you can pass + // a _maximum_ countdown time (in milliseconds) to the enable call. The library + // will try to use that value as the countdown, but it might pick a smaller + // value if the hardware doesn't support it. The actual countdown value will + // be returned so you can see what it is. + countdownMS = Watchdog.enable(4000); + Serial.print("Get ready, the watchdog will reset in "); + Serial.print(countdownMS, DEC); + Serial.println(" milliseconds!"); + Serial.println(); + delay(countdownMS+1000); + + // Execution will never get here because the watchdog resets the Arduino! +} + +void loop() { + // We'll never actually get to the loop because the watchdog will reset in + // the setup function. + Serial.println("You shouldn't see this message."); + delay(1000); +} diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino new file mode 100644 index 0000000..d8eab80 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino @@ -0,0 +1,37 @@ +// Adafruit Watchdog Library Sleep Example +// +// Simple example of how to do low power sleep with the watchdog timer. +// +// Author: Tony DiCola + +#include + +void setup() { + Serial.begin(115200); + while (!Serial) ; // wait for Arduino Serial Monitor (native USB boards) + Serial.println("Adafruit Watchdog Library Sleep Demo!"); + Serial.println(); +} + +void loop() { + Serial.println("Going to sleep in one second..."); + delay(1000); + + // To enter low power sleep mode call Watchdog.sleep() like below + // and the watchdog will allow low power sleep for as long as possible. + // The actual amount of time spent in sleep will be returned (in + // milliseconds). + int sleepMS = Watchdog.sleep(); + + // Alternatively you can provide a millisecond value to specify + // how long you'd like the chip to sleep, but the hardware only + // supports a limited range of values so the actual sleep time might + // be smaller. The time spent in sleep will be returned (in + // milliseconds). + // int sleepMS = Watchdog.sleep(1000); // Sleep for up to 1 second. + + Serial.print("I'm awake now! I slept for "); + Serial.print(sleepMS, DEC); + Serial.println(" milliseconds."); + Serial.println(); +} diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/library.properties b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/library.properties new file mode 100644 index 0000000..c41d74b --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/library.properties @@ -0,0 +1,9 @@ +name=Adafruit SleepyDog Library +version=1.1.1 +author=Adafruit +maintainer=Adafruit +sentence=Arduino library to use the watchdog timer for system reset and low power sleep. +paragraph=Arduino library to use the watchdog timer for system reset and low power sleep. +category=Other +url=https://github.com/adafruit/Adafruit_SleepyDog +architectures=* diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp new file mode 100644 index 0000000..3355c13 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp @@ -0,0 +1,137 @@ +// Be careful to use a platform-specific conditional include to only make the +// code visible for the appropriate platform. Arduino will try to compile and +// link all .cpp files regardless of platform. +#if defined(ARDUINO_ARCH_AVR) || defined(__AVR__) + +#include +#include +#include +#include + +#include "WatchdogAVR.h" + +// Define watchdog timer interrupt. +ISR(WDT_vect) +{ + // Nothing needs to be done, however interrupt handler must be defined to + // prevent a reset. +} + +int WatchdogAVR::enable(int maxPeriodMS) { + // Pick the closest appropriate watchdog timer value. + int actualMS; + _setPeriod(maxPeriodMS, _wdto, actualMS); + // Enable the watchdog and return the actual countdown value. + wdt_enable(_wdto); + return actualMS; +} + +void WatchdogAVR::reset() { + // Reset the watchdog. + wdt_reset(); +} + +void WatchdogAVR::disable() { + // Disable the watchdog and clear any saved watchdog timer value. + wdt_disable(); + _wdto = -1; +} + +int WatchdogAVR::sleep(int maxPeriodMS) { + // Pick the closest appropriate watchdog timer value. + int sleepWDTO, actualMS; + _setPeriod(maxPeriodMS, sleepWDTO, actualMS); + + // Build watchdog prescaler register value before timing critical code. + uint8_t wdps = ((sleepWDTO & 0x08 ? 1 : 0) << WDP3) | + ((sleepWDTO & 0x04 ? 1 : 0) << WDP2) | + ((sleepWDTO & 0x02 ? 1 : 0) << WDP1) | + ((sleepWDTO & 0x01 ? 1 : 0) << WDP0); + + // The next section is timing critical so interrupts are disabled. + cli(); + // First clear any previous watchdog reset. + MCUSR &= ~(1<= 8000) || (maxMS == 0)) { + wdto = WDTO_8S; + actualMS = 8000; + } + else if (maxMS >= 4000) { + wdto = WDTO_4S; + actualMS = 4000; + } + else if (maxMS >= 2000) { + wdto = WDTO_2S; + actualMS = 2000; + } + else if (maxMS >= 1000) { + wdto = WDTO_1S; + actualMS = 1000; + } + else if (maxMS >= 500) { + wdto = WDTO_500MS; + actualMS = 500; + } + else if (maxMS >= 250) { + wdto = WDTO_250MS; + actualMS = 250; + } + else if (maxMS >= 120) { + wdto = WDTO_120MS; + actualMS = 120; + } + else if (maxMS >= 60) { + wdto = WDTO_60MS; + actualMS = 60; + } + else if (maxMS >= 30) { + wdto = WDTO_30MS; + actualMS = 30; + } + else { + wdto = WDTO_15MS; + actualMS = 15; + } +} + +#endif diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h new file mode 100644 index 0000000..9753b08 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h @@ -0,0 +1,47 @@ +#ifndef WATCHDOGAVR_H +#define WATCHDOGAVR_H + +class WatchdogAVR { +public: + WatchdogAVR(): + _wdto(-1) + {} + + // Enable the watchdog timer to reset the machine after a period of time + // without any calls to reset(). The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware does + // not support the exact desired value. + // + // The actual period (in milliseconds) before a watchdog timer reset is + // returned. + int enable(int maxPeriodMS = 0); + + // Reset or 'kick' the watchdog timer to prevent a reset of the device. + void reset(); + + // Completely disable the watchdog timer. + void disable(); + + // Enter the lowest power sleep mode (using the watchdog timer) for the + // desired period of time. The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware does + // not support the exact desired value + // + // The actual period (in milliseconds) that the hardware was asleep will be + // returned. + int sleep(int maxPeriodMS = 0); + +private: + // Pick the closest (but not higher) watchdog timer value from the provided + // maximum period. Sets wdto to the chosen period value suitable for + // passing to wdt_enable(), and actualMS to the chosen period value in + // milliseconds. A max value of 0 will pick the longest value possible. + void _setPeriod(int maxMS, int &wdto, int &actualMS); + + // Keep the last selected watchdog timer period so that the watchdog can be + // re-enabled at that rate after sleep. A value of -1 means no watchdog + // timer was enabled. + int _wdto; +}; + +#endif \ No newline at end of file diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp new file mode 100644 index 0000000..9705859 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp @@ -0,0 +1,104 @@ +// Be careful to use a platform-specific conditional include to only make the +// code visible for the appropriate platform. Arduino will try to compile and +// link all .cpp files regardless of platform. +#if defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) + +#include +#include "WatchdogKinetisK.h" + +static void one_bus_cycle(void) __attribute__((always_inline)); +static void watchdog_config(int cfg, int val); + +// Enable the watchdog timer to reset the machine after a period of time +// without any calls to reset(). The passed in period (in milliseconds) is +// just a suggestion and a lower value might be picked if the hardware does +// not support the exact desired value. +// +// The actual period (in milliseconds) before a watchdog timer reset is +// returned. +int WatchdogKinetisKseries::enable(int maxPeriodMS) +{ + if (maxPeriodMS < 4) { + maxPeriodMS = 8000; // default is 8 seconds + } + if (setting != maxPeriodMS) { + watchdog_config(WDOG_STCTRLH_WDOGEN, maxPeriodMS); + setting = maxPeriodMS; + } + return maxPeriodMS; +} + +// Reset or 'kick' the watchdog timer to prevent a reset of the device. +void WatchdogKinetisKseries::reset() +{ + __disable_irq(); + WDOG_REFRESH = 0xA602; + WDOG_REFRESH = 0xB480; + __enable_irq(); +} + +// Completely disable the watchdog timer. +void WatchdogKinetisKseries::disable() +{ + if (setting > 0) { + watchdog_config(0, 4); + setting = 0; + } +} + +// Enter the lowest power sleep mode for the desired period of time. The +// passed in period (in milliseconds) is just a suggestion and a lower value +// might be picked if the hardware does not support the exact desired value +// +// The actual period (in milliseconds) that the hardware was asleep will be +// returned. +int WatchdogKinetisKseries::sleep(int maxPeriodMS) +{ + if (maxPeriodMS <= 0) return 0; + // TODO.... + return 0; +} + +static void watchdog_config(int cfg, int val) +{ + __disable_irq(); + WDOG_UNLOCK = WDOG_UNLOCK_SEQ1; + WDOG_UNLOCK = WDOG_UNLOCK_SEQ2; + one_bus_cycle(); + WDOG_STCTRLH = cfg | WDOG_STCTRLH_ALLOWUPDATE; + WDOG_TOVALH = val >> 16; + WDOG_TOVALL = val; + WDOG_PRESC = 0; + __enable_irq(); + for (int i=0; i < 256; i++) { + one_bus_cycle(); + } +} + +static void one_bus_cycle(void) +{ + __asm__ volatile ("nop"); + #if (F_CPU / F_BUS) > 1 + __asm__ volatile ("nop"); + #endif + #if (F_CPU / F_BUS) > 2 + __asm__ volatile ("nop"); + #endif + #if (F_CPU / F_BUS) > 3 + __asm__ volatile ("nop"); + #endif + #if (F_CPU / F_BUS) > 4 + __asm__ volatile ("nop"); + #endif + #if (F_CPU / F_BUS) > 5 + __asm__ volatile ("nop"); + #endif + #if (F_CPU / F_BUS) > 6 + __asm__ volatile ("nop"); + #endif + #if (F_CPU / F_BUS) > 7 + __asm__ volatile ("nop"); + #endif +} + +#endif diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h new file mode 100644 index 0000000..e09a0c2 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h @@ -0,0 +1,38 @@ +#ifndef WATCHDOGKINETISK_H +#define WATCHDOGKINETISK_H + +class WatchdogKinetisKseries { +public: + WatchdogKinetisKseries(): setting(0) {} + + // Enable the watchdog timer to reset the machine after a period of time + // without any calls to reset(). The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware does + // not support the exact desired value. + // + // The actual period (in milliseconds) before a watchdog timer reset is + // returned. + int enable(int maxPeriodMS = 0); + + // Reset or 'kick' the watchdog timer to prevent a reset of the device. + void reset(); + + // Completely disable the watchdog timer. + void disable(); + + // Enter the lowest power sleep mode (using the watchdog timer) for the + // desired period of time. The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware does + // not support the exact desired value + // + // The actual period (in milliseconds) that the hardware was asleep will be + // returned. + // + // NOTE: This is currently not implemented on the SAMD21! + int sleep(int maxPeriodMS = 0); + +private: + int setting; +}; + +#endif diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp new file mode 100644 index 0000000..501e9c0 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp @@ -0,0 +1,74 @@ +// Be careful to use a platform-specific conditional include to only make the +// code visible for the appropriate platform. Arduino will try to compile and +// link all .cpp files regardless of platform. +#if defined(__MKL26Z64__) + +#include +#include "WatchdogKinetisL.h" + +// Normally the watchdog is disabled at startup. This removes the startup +// code. The watchdog will be active with 1024 ms timeout. Hopefully the +// user will configure the watchdog and begin resetting it before it causes +// a reboot. There is no way to start up without the watchdog and then +// enable it later... +extern "C" void startup_early_hook(void) {} + + +// Enable the watchdog timer to reset the machine after a period of time +// without any calls to reset(). The passed in period (in milliseconds) is +// just a suggestion and a lower value might be picked if the hardware does +// not support the exact desired value. +// +// The actual period (in milliseconds) before a watchdog timer reset is +// returned. +int WatchdogKinetisLseries::enable(int maxPeriodMS) +{ + // The watchdog can only be programmed once. Then it's forever + // locked to this setting (until the chip reboots). + if (maxPeriodMS <= 0 || maxPeriodMS > 256) { + SIM_COPC = 12; + } else if (maxPeriodMS > 32) { + SIM_COPC = 8; + } else { + SIM_COPC = 4; + } + // Read the actual setting. + int val = SIM_COPC & 12; + if (val == 12) return 1024; + if (val == 8) return 256; + return 32; +} + +// Reset or 'kick' the watchdog timer to prevent a reset of the device. +void WatchdogKinetisLseries::reset() +{ + __disable_irq(); + SIM_SRVCOP = 0x55; + SIM_SRVCOP = 0xAA; + __enable_irq(); +} + +// Completely disable the watchdog timer. +void WatchdogKinetisLseries::disable() +{ + // no can do.... + // The watchdog timer in this chip is write-once. + // The chip boots up with the watchdog at 1024 ms. + // You only get to configure it once. Then it + // remains locked to that setting, until a reboot. +} + +// Enter the lowest power sleep mode for the desired period of time. The +// passed in period (in milliseconds) is just a suggestion and a lower value +// might be picked if the hardware does not support the exact desired value +// +// The actual period (in milliseconds) that the hardware was asleep will be +// returned. +int WatchdogKinetisLseries::sleep(int maxPeriodMS) +{ + if (maxPeriodMS <= 0) return 0; + // TODO.... + return 0; +} + +#endif diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h new file mode 100644 index 0000000..3c68d5e --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h @@ -0,0 +1,35 @@ +#ifndef WATCHDOGKINETISL_H +#define WATCHDOGKINETISL_H + +class WatchdogKinetisLseries { +public: + WatchdogKinetisLseries() {} + + // Enable the watchdog timer to reset the machine after a period of time + // without any calls to reset(). The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware does + // not support the exact desired value. + // + // The actual period (in milliseconds) before a watchdog timer reset is + // returned. + int enable(int maxPeriodMS = 0); + + // Reset or 'kick' the watchdog timer to prevent a reset of the device. + void reset(); + + // Completely disable the watchdog timer. + void disable(); + + // Enter the lowest power sleep mode (using the watchdog timer) for the + // desired period of time. The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware does + // not support the exact desired value + // + // The actual period (in milliseconds) that the hardware was asleep will be + // returned. + // + // NOTE: This is currently not implemented on the SAMD21! + int sleep(int maxPeriodMS = 0); +}; + +#endif diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp new file mode 100644 index 0000000..d21d9a9 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp @@ -0,0 +1,175 @@ +// Requires Adafruit_ASFcore library! + +// Be careful to use a platform-specific conditional include to only make the +// code visible for the appropriate platform. Arduino will try to compile and +// link all .cpp files regardless of platform. +#if defined(ARDUINO_ARCH_SAMD) + +#include +#include +#include +#include "WatchdogSAMD.h" + +int WatchdogSAMD::enable(int maxPeriodMS, bool isForSleep) { + // Enable the watchdog with a period up to the specified max period in + // milliseconds. + + // Review the watchdog section from the SAMD21 datasheet section 17: + // http://www.atmel.com/images/atmel-42181-sam-d21_datasheet.pdf + + int cycles, actualMS; + uint8_t bits; + + if(!_initialized) _initialize_wdt(); + + WDT->CTRL.reg = 0; // Disable watchdog for config + while(WDT->STATUS.bit.SYNCBUSY); + + // You'll see some occasional conversion here compensating between + // milliseconds (1000 Hz) and WDT clock cycles (~1024 Hz). The low- + // power oscillator used by the WDT ostensibly runs at 32,768 Hz with + // a 1:32 prescale, thus 1024 Hz, though probably not super precise. + + if((maxPeriodMS >= 16000) || !maxPeriodMS) { + cycles = 16384; + bits = 0xB; + } else { + cycles = (maxPeriodMS * 1024L + 500) / 1000; // ms -> WDT cycles + if(cycles >= 8192) { + cycles = 8192; + bits = 0xA; + } else if(cycles >= 4096) { + cycles = 4096; + bits = 0x9; + } else if(cycles >= 2048) { + cycles = 2048; + bits = 0x8; + } else if(cycles >= 1024) { + cycles = 1024; + bits = 0x7; + } else if(cycles >= 512) { + cycles = 512; + bits = 0x6; + } else if(cycles >= 256) { + cycles = 256; + bits = 0x5; + } else if(cycles >= 128) { + cycles = 128; + bits = 0x4; + } else if(cycles >= 64) { + cycles = 64; + bits = 0x3; + } else if(cycles >= 32) { + cycles = 32; + bits = 0x2; + } else if(cycles >= 16) { + cycles = 16; + bits = 0x1; + } else { + cycles = 8; + bits = 0x0; + } + } + + // Watchdog timer on SAMD is a slightly different animal than on AVR. + // On AVR, the WTD timeout is configured in one register and then an + // interrupt can optionally be enabled to handle the timeout in code + // (as in waking from sleep) vs resetting the chip. Easy. + // On SAMD, when the WDT fires, that's it, the chip's getting reset. + // Instead, it has an "early warning interrupt" with a different set + // interval prior to the reset. For equivalent behavior to the AVR + // library, this requires a slightly different configuration depending + // whether we're coming from the sleep() function (which needs the + // interrupt), or just enable() (no interrupt, we want the chip reset + // unless the WDT is cleared first). In the sleep case, 'windowed' + // mode is used in order to allow access to the longest available + // sleep interval (about 16 sec); the WDT 'period' (when a reset + // occurs) follows this and is always just set to the max, since the + // interrupt will trigger first. In the enable case, windowed mode + // is not used, the WDT period is set and that's that. + // The 'isForSleep' argument determines which behavior is used; + // this isn't present in the AVR code, just here. It defaults to + // 'false' so existing Arduino code works as normal, while the sleep() + // function (later in this file) explicitly passes 'true' to get the + // alternate behavior. + + if(isForSleep) { + WDT->INTENSET.bit.EW = 1; // Enable early warning interrupt + WDT->CONFIG.bit.PER = 0xB; // Period = max + WDT->CONFIG.bit.WINDOW = bits; // Set time of interrupt + WDT->CTRL.bit.WEN = 1; // Enable window mode + while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write + } else { + WDT->INTENCLR.bit.EW = 1; // Disable early warning interrupt + WDT->CONFIG.bit.PER = bits; // Set period for chip reset + WDT->CTRL.bit.WEN = 0; // Disable window mode + while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write + } + + actualMS = (cycles * 1000L + 512) / 1024; // WDT cycles -> ms + + reset(); // Clear watchdog interval + WDT->CTRL.bit.ENABLE = 1; // Start watchdog now! + while(WDT->STATUS.bit.SYNCBUSY); + + return actualMS; +} + +void WatchdogSAMD::reset() { + // Write the watchdog clear key value (0xA5) to the watchdog + // clear register to clear the watchdog timer and reset it. + WDT->CLEAR.reg = WDT_CLEAR_CLEAR_KEY; + while(WDT->STATUS.bit.SYNCBUSY); +} + +void WatchdogSAMD::disable() { + WDT->CTRL.bit.ENABLE = 0; + while(WDT->STATUS.bit.SYNCBUSY); +} + +void WDT_Handler(void) { + // ISR for watchdog early warning, DO NOT RENAME! + WDT->CTRL.bit.ENABLE = 0; // Disable watchdog + while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write + WDT->INTFLAG.bit.EW = 1; // Clear interrupt flag +} + +int WatchdogSAMD::sleep(int maxPeriodMS) { + + int actualPeriodMS = enable(maxPeriodMS, true); // true = for sleep + + system_set_sleepmode(SYSTEM_SLEEPMODE_STANDBY); // Deepest sleep + system_sleep(); + // Code resumes here on wake (WDT early warning interrupt) + + return actualPeriodMS; +} + +void WatchdogSAMD::_initialize_wdt() { + // One-time initialization of watchdog timer. + // Insights from rickrlh and rbrucemtl in Arduino forum! + + // Generic clock generator 2, divisor = 32 (2^(DIV+1)) + GCLK->GENDIV.reg = GCLK_GENDIV_ID(2) | GCLK_GENDIV_DIV(4); + // Enable clock generator 2 using low-power 32KHz oscillator. + // With /32 divisor above, this yields 1024Hz(ish) clock. + GCLK->GENCTRL.reg = GCLK_GENCTRL_ID(2) | + GCLK_GENCTRL_GENEN | + GCLK_GENCTRL_SRC_OSCULP32K | + GCLK_GENCTRL_DIVSEL; + while(GCLK->STATUS.bit.SYNCBUSY); + // WDT clock = clock gen 2 + GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID_WDT | + GCLK_CLKCTRL_CLKEN | + GCLK_CLKCTRL_GEN_GCLK2; + + // Enable WDT early-warning interrupt + NVIC_DisableIRQ(WDT_IRQn); + NVIC_ClearPendingIRQ(WDT_IRQn); + NVIC_SetPriority(WDT_IRQn, 0); // Top priority + NVIC_EnableIRQ(WDT_IRQn); + + _initialized = true; +} + +#endif diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h new file mode 100644 index 0000000..8b03c27 --- /dev/null +++ b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h @@ -0,0 +1,43 @@ +#ifndef WATCHDOGSAMD_H +#define WATCHDOGSAMD_H + +class WatchdogSAMD { +public: + WatchdogSAMD(): + _initialized(false) + {} + + // Enable the watchdog timer to reset the machine after a period of time + // without any calls to reset(). The passed in period (in milliseconds) + // is just a suggestion and a lower value might be picked if the hardware + // does not support the exact desired value. + // User code should NOT set the 'isForSleep' argument either way -- + // it's used internally by the library, but your sketch should leave this + // out when calling enable(), just let the default have its way. + // + // The actual period (in milliseconds) before a watchdog timer reset is + // returned. + int enable(int maxPeriodMS = 0, bool isForSleep = false); + + // Reset or 'kick' the watchdog timer to prevent a reset of the device. + void reset(); + + // Completely disable the watchdog timer. + void disable(); + + // Enter the lowest power sleep mode (using the watchdog timer) for the + // desired period of time. The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware + // does not support the exact desired value + // + // The actual period (in milliseconds) that the hardware was asleep will be + // returned. + int sleep(int maxPeriodMS = 0); + +private: + void _initialize_wdt(); + + bool _initialized; +}; + +#endif diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/.gitignore b/feather_sensor_lte/libraries/ArduinoHttpClient/.gitignore new file mode 100644 index 0000000..89d225a --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/.gitignore @@ -0,0 +1,2 @@ +.development +examples/node_test_server/node_modules/ diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/CHANGELOG.md b/feather_sensor_lte/libraries/ArduinoHttpClient/CHANGELOG.md new file mode 100644 index 0000000..5645508 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/CHANGELOG.md @@ -0,0 +1,25 @@ +## ArduinoHttpClient 0.3.1 - 2017.09.25 + +* Changed examples to support Arduino Create secret tabs +* Increase WebSocket secrect-key length to 24 characters + +## ArduinoHttpClient 0.3.0 - 2017.04.20 + +* Added support for PATCH operations +* Added support for chunked response bodies +* Added new beginBody API + +## ArduinoHttpClient 0.2.0 - 2017.01.12 + +* Added PATCH method +* Added basic auth example +* Added custom header example + +## ArduinoHttpClient 0.1.1 - 2016.12.16 + +* More robust response parser + +## ArduinoHttpClient 0.1.0 - 2016.07.05 + +* Initial release + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/README.md b/feather_sensor_lte/libraries/ArduinoHttpClient/README.md new file mode 100644 index 0000000..655b618 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/README.md @@ -0,0 +1,22 @@ +# ArduinoHttpClient + +ArduinoHttpClient is a library to make it easier to interact with web servers from Arduino. + +Derived from [Adrian McEwen's HttpClient library](https://github.com/amcewen/HttpClient) + +## Dependencies + +- Requires a networking hardware and a library that provides transport specific `Client` instance, such as: + - [WiFi101](https://github.com/arduino-libraries/WiFi101) + - [Ethernet](https://github.com/arduino-libraries/Ethernet) + - [WiFi](https://github.com/arduino-libraries/WiFi) + - [GSM](https://github.com/arduino-libraries/GSM) + +## Usage + +In normal usage, handles the outgoing request and Host header. The returned status code is parsed for you, as is the Content-Length header (if present). + +Because it expects an object of type Client, you can use it with any of the networking classes that derive from that. Which means it will work with WiFiClient, EthernetClient and GSMClient. + +See the examples for more detail on how the library is used. + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino new file mode 100644 index 0000000..e793d47 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino @@ -0,0 +1,69 @@ +/* + GET client with HTTP basic authentication for ArduinoHttpClient library + Connects to server once every five seconds, sends a GET request + + + + created 14 Feb 2016 + by Tom Igoe + modified 3 Jan 2017 to add HTTP basic authentication + by Sandeep Mistry + + this example is in the public domain + */ +#include +#include +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("making GET request with HTTP basic authentication"); + client.beginRequest(); + client.get("/secure"); + client.sendBasicAuth("username", "password"); // send the username and password for authentication + client.endRequest(); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + Serial.println("Wait five seconds"); + delay(5000); +} + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino new file mode 100644 index 0000000..fa44aca --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino @@ -0,0 +1,96 @@ +/* + Custom request header example for the ArduinoHttpClient + library. This example sends a GET and a POST request with a custom header every 5 seconds. + + note: WiFi SSID and password are stored in config.h file. + If it is not present, add a new tab, call it "config.h" + and add the following variables: + char ssid[] = "ssid"; // your network SSID (name) + char pass[] = "password"; // your network password + + based on SimpleGet example by Tom Igoe + header modifications by Todd Treece + + this example is in the public domain + */ + +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + + Serial.println("making GET request"); + client.beginRequest(); + client.get("/"); + client.sendHeader("X-CUSTOM-HEADER", "custom_value"); + client.endRequest(); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("GET Status code: "); + Serial.println(statusCode); + Serial.print("GET Response: "); + Serial.println(response); + + Serial.println("Wait five seconds"); + delay(5000); + + Serial.println("making POST request"); + String postData = "name=Alice&age=12"; + client.beginRequest(); + client.post("/"); + client.sendHeader(HTTP_HEADER_CONTENT_TYPE, "application/x-www-form-urlencoded"); + client.sendHeader(HTTP_HEADER_CONTENT_LENGTH, postData.length()); + client.sendHeader("X-CUSTOM-HEADER", "custom_value"); + client.endRequest(); + client.write((const byte*)postData.c_str(), postData.length()); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("POST Status code: "); + Serial.println(statusCode); + Serial.print("POST Response: "); + Serial.println(response); + + Serial.println("Wait five seconds"); + delay(5000); +} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino new file mode 100644 index 0000000..51abd3f --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino @@ -0,0 +1,107 @@ +/* + Dweet.io GET client for ArduinoHttpClient library + Connects to dweet.io once every ten seconds, + sends a GET request and a request body. Uses SSL + + Shows how to use Strings to assemble path and parse content + from response. dweet.io expects: + https://dweet.io/get/latest/dweet/for/thingName + + For more on dweet.io, see https://dweet.io/play/ + + + + created 15 Feb 2016 + updated 16 Feb 2016 + by Tom Igoe + + this example is in the public domain +*/ +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + +const char serverAddress[] = "dweet.io"; // server address +int port = 80; +String dweetName = "scandalous-cheese-hoarder"; // use your own thing name here + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +int statusCode = 0; +String response; + +void setup() { + Serial.begin(9600); + while (!Serial); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + // assemble the path for the GET message: + String path = "/get/latest/dweet/for/" + dweetName; + + // send the GET request + Serial.println("making GET request"); + client.get(path); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + /* + Typical response is: + {"this":"succeeded", + "by":"getting", + "the":"dweets", + "with":[{"thing":"my-thing-name", + "created":"2016-02-16T05:10:36.589Z", + "content":{"sensorValue":456}}]} + + You want "content": numberValue + */ + // now parse the response looking for "content": + int labelStart = response.indexOf("content\":"); + // find the first { after "content": + int contentStart = response.indexOf("{", labelStart); + // find the following } and get what's between the braces: + int contentEnd = response.indexOf("}", labelStart); + String content = response.substring(contentStart + 1, contentEnd); + Serial.println(content); + + // now get the value after the colon, and convert to an int: + int valueStart = content.indexOf(":"); + String valueString = content.substring(valueStart + 1); + int number = valueString.toInt(); + Serial.print("Value string: "); + Serial.println(valueString); + Serial.print("Actual value: "); + Serial.println(number); + + Serial.println("Wait ten seconds\n"); + delay(10000); +} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino new file mode 100644 index 0000000..41c6f2f --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino @@ -0,0 +1,87 @@ +/* + Dweet.io POST client for ArduinoHttpClient library + Connects to dweet.io once every ten seconds, + sends a POST request and a request body. + + Shows how to use Strings to assemble path and body + + note: WiFi SSID and password are stored in config.h file. + If it is not present, add a new tab, call it "config.h" + and add the following variables: + char ssid[] = "ssid"; // your network SSID (name) + char pass[] = "password"; // your network password + + created 15 Feb 2016 + by Tom Igoe + + this example is in the public domain +*/ +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + +const char serverAddress[] = "dweet.io"; // server address +int port = 80; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +int statusCode = 0; +String response; + +void setup() { + Serial.begin(9600); + while(!Serial); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + // assemble the path for the POST message: + String dweetName = "scandalous-cheese-hoarder"; + String path = "/dweet/for/" + dweetName; + + String contentType = "application/json"; + + // assemble the body of the POST message: + int sensorValue = analogRead(A0); + String postData = "{\"sensorValue\":\""; + postData += sensorValue; + postData += "\"}"; + + Serial.println("making POST request"); + + // send the POST request + client.post(path, contentType, postData); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + Serial.println("Wait ten seconds\n"); + delay(10000); +} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino new file mode 100644 index 0000000..c18ae47 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino @@ -0,0 +1,102 @@ +/* HueBlink example for ArduinoHttpClient library + + Uses ArduinoHttpClient library to control Philips Hue + For more on Hue developer API see http://developer.meethue.com + + To control a light, the Hue expects a HTTP PUT request to: + + http://hue.hub.address/api/hueUserName/lights/lightNumber/state + + The body of the PUT request looks like this: + {"on": true} or {"on":false} + + This example shows how to concatenate Strings to assemble the + PUT request and the body of the request. + + + + modified 15 Feb 2016 + by Tom Igoe (tigoe) to match new API +*/ + +#include +#include +#include +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + +int status = WL_IDLE_STATUS; // the Wifi radio's status + +char hueHubIP[] = "192.168.0.3"; // IP address of the HUE bridge +String hueUserName = "huebridgeusername"; // hue bridge username + +// make a wifi instance and a HttpClient instance: +WiFiClient wifi; +HttpClient httpClient = HttpClient(wifi, hueHubIP); + + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial); // wait for serial port to connect. + + // attempt to connect to Wifi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to WPA SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // you're connected now, so print out the data: + Serial.print("You're connected to the network IP = "); + IPAddress ip = WiFi.localIP(); + Serial.println(ip); +} + +void loop() { + sendRequest(3, "on", "true"); // turn light on + delay(2000); // wait 2 seconds + sendRequest(3, "on", "false"); // turn light off + delay(2000); // wait 2 seconds +} + +void sendRequest(int light, String cmd, String value) { + // make a String for the HTTP request path: + String request = "/api/" + hueUserName; + request += "/lights/"; + request += light; + request += "/state/"; + + String contentType = "application/json"; + + // make a string for the JSON command: + String hueCmd = "{\"" + cmd; + hueCmd += "\":"; + hueCmd += value; + hueCmd += "}"; + // see what you assembled to send: + Serial.print("PUT request to server: "); + Serial.println(request); + Serial.print("JSON command to server: "); + + // make the PUT request to the hub: + httpClient.put(request, contentType, hueCmd); + + // read the status code and body of the response + int statusCode = httpClient.responseStatusCode(); + String response = httpClient.responseBody(); + + Serial.println(hueCmd); + Serial.print("Status code from server: "); + Serial.println(statusCode); + Serial.print("Server response: "); + Serial.println(response); + Serial.println(); +} + + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino new file mode 100644 index 0000000..835a26f --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino @@ -0,0 +1,79 @@ +/* + POST with headers client for ArduinoHttpClient library + Connects to server once every five seconds, sends a POST request + with custome headers and a request body + + + + created 14 Feb 2016 + by Tom Igoe + modified 18 Mar 2017 + by Sandeep Mistry + + this example is in the public domain + */ +#include +#include + +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("making POST request"); + String postData = "name=Alice&age=12"; + + client.beginRequest(); + client.post("/"); + client.sendHeader("Content-Type", "application/x-www-form-urlencoded"); + client.sendHeader("Content-Length", postData.length()); + client.sendHeader("X-Custom-Header", "custom-header-value"); + client.beginBody(); + client.print(postData); + client.endRequest(); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + Serial.println("Wait five seconds"); + delay(5000); +} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino new file mode 100644 index 0000000..374a145 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino @@ -0,0 +1,71 @@ +/* + Simple DELETE client for ArduinoHttpClient library + Connects to server once every five seconds, sends a DELETE request + and a request body + + + + created 14 Feb 2016 + by Tom Igoe + + this example is in the public domain + */ +#include +#include + +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("making DELETE request"); + String contentType = "application/x-www-form-urlencoded"; + String delData = "name=light&age=46"; + + client.del("/", contentType, delData); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + Serial.println("Wait five seconds"); + delay(5000); +} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino new file mode 100644 index 0000000..75db9a7 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino @@ -0,0 +1,66 @@ +/* + Simple GET client for ArduinoHttpClient library + Connects to server once every five seconds, sends a GET request + + + + created 14 Feb 2016 + by Tom Igoe + + this example is in the public domain + */ +#include +#include + +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("making GET request"); + client.get("/"); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + Serial.println("Wait five seconds"); + delay(5000); +} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino new file mode 100644 index 0000000..f64b9ba --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino @@ -0,0 +1,133 @@ +// (c) Copyright 2010-2012 MCQN Ltd. +// Released under Apache License, version 2.0 +// +// Simple example to show how to use the HttpClient library +// Get's the web page given at http:// and +// outputs the content to the serial port + +#include +#include +#include + +// This example downloads the URL "http://arduino.cc/" + +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + + + +// Name of the server we want to connect to +const char kHostname[] = "arduino.cc"; +// Path to download (this is the bit after the hostname in the URL +// that you want to download +const char kPath[] = "/"; + +// Number of milliseconds to wait without receiving any data before we give up +const int kNetworkTimeout = 30*1000; +// Number of milliseconds to wait if no data is available before trying again +const int kNetworkDelay = 1000; + +WiFiClient c; +HttpClient http(c, kHostname); + +void setup() +{ + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // attempt to connect to Wifi network: + Serial.print("Attempting to connect to WPA SSID: "); + Serial.println(ssid); + while (WiFi.begin(ssid, pass) != WL_CONNECTED) { + // unsuccessful, retry in 4 seconds + Serial.print("failed ... "); + delay(4000); + Serial.print("retrying ... "); + } + + Serial.println("connected"); +} + +void loop() +{ + int err =0; + + err = http.get(kPath); + if (err == 0) + { + Serial.println("startedRequest ok"); + + err = http.responseStatusCode(); + if (err >= 0) + { + Serial.print("Got status code: "); + Serial.println(err); + + // Usually you'd check that the response code is 200 or a + // similar "success" code (200-299) before carrying on, + // but we'll print out whatever response we get + + // If you are interesting in the response headers, you + // can read them here: + //while(http.headerAvailable()) + //{ + // String headerName = http.readHeaderName(); + // String headerValue = http.readHeaderValue(); + //} + + int bodyLen = http.contentLength(); + Serial.print("Content length is: "); + Serial.println(bodyLen); + Serial.println(); + Serial.println("Body returned follows:"); + + // Now we've got to the body, so we can print it out + unsigned long timeoutStart = millis(); + char c; + // Whilst we haven't timed out & haven't reached the end of the body + while ( (http.connected() || http.available()) && + (!http.endOfBodyReached()) && + ((millis() - timeoutStart) < kNetworkTimeout) ) + { + if (http.available()) + { + c = http.read(); + // Print out this character + Serial.print(c); + + // We read something, reset the timeout counter + timeoutStart = millis(); + } + else + { + // We haven't got any data, so let's pause to allow some to + // arrive + delay(kNetworkDelay); + } + } + } + else + { + Serial.print("Getting response failed: "); + Serial.println(err); + } + } + else + { + Serial.print("Connect failed: "); + Serial.println(err); + } + http.stop(); + + // And just stop, now that we've tried a download + while(1); +} + + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino new file mode 100644 index 0000000..6cc3517 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino @@ -0,0 +1,70 @@ +/* + Simple POST client for ArduinoHttpClient library + Connects to server once every five seconds, sends a POST request + and a request body + + + + created 14 Feb 2016 + by Tom Igoe + + this example is in the public domain + */ +#include +#include +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("making POST request"); + String contentType = "application/x-www-form-urlencoded"; + String postData = "name=Alice&age=12"; + + client.post("/", contentType, postData); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + Serial.println("Wait five seconds"); + delay(5000); +} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino new file mode 100644 index 0000000..1b06105 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino @@ -0,0 +1,70 @@ +/* + Simple PUT client for ArduinoHttpClient library + Connects to server once every five seconds, sends a PUT request + and a request body + + + + created 14 Feb 2016 + by Tom Igoe + + this example is in the public domain + */ +#include +#include +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("making PUT request"); + String contentType = "application/x-www-form-urlencoded"; + String putData = "name=light&age=46"; + + client.put("/", contentType, putData); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + Serial.println("Wait five seconds"); + delay(5000); +} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino new file mode 100644 index 0000000..baac12f --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino @@ -0,0 +1,80 @@ +/* + Simple WebSocket client for ArduinoHttpClient library + Connects to the WebSocket server, and sends a hello + message every 5 seconds + + + created 28 Jun 2016 + by Sandeep Mistry + + this example is in the public domain +*/ +#include +#include +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + +char serverAddress[] = "echo.websocket.org"; // server address +int port = 80; + +WiFiClient wifi; +WebSocketClient client = WebSocketClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +int count = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("starting WebSocket client"); + client.begin(); + + while (client.connected()) { + Serial.print("Sending hello "); + Serial.println(count); + + // send a hello # + client.beginMessage(TYPE_TEXT); + client.print("hello "); + client.print(count); + client.endMessage(); + + // increment count for next message + count++; + + // check if a message is available to be received + int messageSize = client.parseMessage(); + + if (messageSize > 0) { + Serial.println("Received a message:"); + Serial.println(client.readString()); + } + + // wait 5 seconds + delay(5000); + } + + Serial.println("disconnected"); +} + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js new file mode 100644 index 0000000..f3dd4d8 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js @@ -0,0 +1,102 @@ +/* + Express.js GET/POST example + Shows how handle GET, POST, PUT, DELETE + in Express.js 4.0 + + created 14 Feb 2016 + by Tom Igoe +*/ + +var express = require('express'); // include express.js +var app = express(); // a local instance of it +var bodyParser = require('body-parser'); // include body-parser +var WebSocketServer = require('ws').Server // include Web Socket server + +// you need a body parser: +app.use(bodyParser.urlencoded({extended: false})); // for application/x-www-form-urlencoded + +// this runs after the server successfully starts: +function serverStart() { + var port = server.address().port; + console.log('Server listening on port '+ port); +} + +app.get('/chunked', function(request, response) { + response.write('\n'); + response.write(' `:;;;,` .:;;:. \n'); + response.write(' .;;;;;;;;;;;` :;;;;;;;;;;: TM \n'); + response.write(' `;;;;;;;;;;;;;;;` :;;;;;;;;;;;;;;; \n'); + response.write(' :;;;;;;;;;;;;;;;;;; `;;;;;;;;;;;;;;;;;; \n'); + response.write(' ;;;;;;;;;;;;;;;;;;;;; .;;;;;;;;;;;;;;;;;;;; \n'); + response.write(' ;;;;;;;;:` `;;;;;;;;; ,;;;;;;;;.` .;;;;;;;; \n'); + response.write(' .;;;;;;, :;;;;;;; .;;;;;;; ;;;;;;; \n'); + response.write(' ;;;;;; ;;;;;;; ;;;;;;, ;;;;;;. \n'); + response.write(' ,;;;;; ;;;;;;.;;;;;;` ;;;;;; \n'); + response.write(' ;;;;;. ;;;;;;;;;;;` ``` ;;;;;`\n'); + response.write(' ;;;;; ;;;;;;;;;, ;;; .;;;;;\n'); + response.write('`;;;;: `;;;;;;;; ;;; ;;;;;\n'); + response.write(',;;;;` `,,,,,,,, ;;;;;;; .,,;;;,,, ;;;;;\n'); + response.write(':;;;;` .;;;;;;;; ;;;;;, :;;;;;;;; ;;;;;\n'); + response.write(':;;;;` .;;;;;;;; `;;;;;; :;;;;;;;; ;;;;;\n'); + response.write('.;;;;. ;;;;;;;. ;;; ;;;;;\n'); + response.write(' ;;;;; ;;;;;;;;; ;;; ;;;;;\n'); + response.write(' ;;;;; .;;;;;;;;;; ;;; ;;;;;,\n'); + response.write(' ;;;;;; `;;;;;;;;;;;; ;;;;; \n'); + response.write(' `;;;;;, .;;;;;; ;;;;;;; ;;;;;; \n'); + response.write(' ;;;;;;: :;;;;;;. ;;;;;;; ;;;;;; \n'); + response.write(' ;;;;;;;` .;;;;;;;, ;;;;;;;; ;;;;;;;: \n'); + response.write(' ;;;;;;;;;:,:;;;;;;;;;: ;;;;;;;;;;:,;;;;;;;;;; \n'); + response.write(' `;;;;;;;;;;;;;;;;;;;. ;;;;;;;;;;;;;;;;;;;; \n'); + response.write(' ;;;;;;;;;;;;;;;;; :;;;;;;;;;;;;;;;;: \n'); + response.write(' ,;;;;;;;;;;;;;, ;;;;;;;;;;;;;; \n'); + response.write(' .;;;;;;;;;` ,;;;;;;;;: \n'); + response.write(' \n'); + response.write(' \n'); + response.write(' \n'); + response.write(' \n'); + response.write(' ;;; ;;;;;` ;;;;: .;; ;; ,;;;;;, ;;. `;, ;;;; \n'); + response.write(' ;;; ;;:;;; ;;;;;; .;; ;; ,;;;;;: ;;; `;, ;;;:;; \n'); + response.write(' ,;:; ;; ;; ;; ;; .;; ;; ,;, ;;;,`;, ;; ;; \n'); + response.write(' ;; ;: ;; ;; ;; ;; .;; ;; ,;, ;;;;`;, ;; ;;. \n'); + response.write(' ;: ;; ;;;;;: ;; ;; .;; ;; ,;, ;;`;;;, ;; ;;` \n'); + response.write(' ,;;;;; ;;`;; ;; ;; .;; ;; ,;, ;; ;;;, ;; ;; \n'); + response.write(' ;; ,;, ;; .;; ;;;;;: ;;;;;: ,;;;;;: ;; ;;, ;;;;;; \n'); + response.write(' ;; ;; ;; ;;` ;;;;. `;;;: ,;;;;;, ;; ;;, ;;;; \n'); + response.write('\n'); + response.end(); +}); + +// this is the POST handler: +app.all('/*', function (request, response) { + console.log('Got a ' + request.method + ' request'); + // the parameters of a GET request are passed in + // request.body. Pass that to formatResponse() + // for formatting: + console.log(request.headers); + if (request.method == 'GET') { + console.log(request.query); + } else { + console.log(request.body); + } + + // send the response: + response.send('OK'); + response.end(); +}); + +// start the server: +var server = app.listen(8080, serverStart); + +// create a WebSocket server and attach it to the server +var wss = new WebSocketServer({server: server}); + +wss.on('connection', function connection(ws) { + // new connection, add message listener + ws.on('message', function incoming(message) { + // received a message + console.log('received: %s', message); + + // echo it back + ws.send(message); + }); +}); diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/node_test_server/package.json b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/node_test_server/package.json new file mode 100644 index 0000000..09f2d8b --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/node_test_server/package.json @@ -0,0 +1,13 @@ +{ + "name": "node_test_server", + "version": "0.0.1", + "author": { + "name": "Tom Igoe" + }, + "dependencies": { + "body-parser": ">=1.11.0", + "express": ">=4.0.0", + "multer": "*", + "ws": "^1.1.1" + } +} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/keywords.txt b/feather_sensor_lte/libraries/ArduinoHttpClient/keywords.txt new file mode 100644 index 0000000..27cd516 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/keywords.txt @@ -0,0 +1,64 @@ +####################################### +# Syntax Coloring Map For HttpClient +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +ArduinoHttpClient KEYWORD1 +HttpClient KEYWORD1 +WebSocketClient KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +get KEYWORD2 +post KEYWORD2 +put KEYWORD2 +patch KEYWORD2 +startRequest KEYWORD2 +beginRequest KEYWORD2 +beginBody KEYWORD2 +sendHeader KEYWORD2 +sendBasicAuth KEYWORD2 +endRequest KEYWORD2 +responseStatusCode KEYWORD2 +readHeader KEYWORD2 +skipResponseHeaders KEYWORD2 +endOfHeadersReached KEYWORD2 +endOfBodyReached KEYWORD2 +completed KEYWORD2 +contentLength KEYWORD2 +isResponseChunked KEYWORD2 +connectionKeepAlive KEYWORD2 +noDefaultRequestHeaders KEYWORD2 +headerAvailable KEYWORD2 +readHeaderName KEYWORD2 +readHeaderValue KEYWORD2 +responseBody KEYWORD2 + +beginMessage KEYWORD2 +endMessage KEYWORD2 +parseMessage KEYWORD2 +messageType KEYWORD2 +isFinal KEYWORD2 +readString KEYWORD2 +ping KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### +HTTP_SUCCESS LITERAL1 +HTTP_ERROR_CONNECTION_FAILED LITERAL1 +HTTP_ERROR_API LITERAL1 +HTTP_ERROR_TIMED_OUT LITERAL1 +HTTP_ERROR_INVALID_RESPONSE LITERAL1 + +TYPE_CONTINUATION LITERAL1 +TYPE_TEXT LITERAL1 +TYPE_BINARY LITERAL1 +TYPE_CONNECTION_CLOSE LITERAL1 +TYPE_PING LITERAL1 +TYPE_PONG LITERAL1 diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/library.json b/feather_sensor_lte/libraries/ArduinoHttpClient/library.json new file mode 100644 index 0000000..6bbda24 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/library.json @@ -0,0 +1,12 @@ +{ + "name": "ArduinoHttpClient", + "keywords": "http, web, client, ethernet, wifi, GSM", + "description": "Easily interact with web servers from Arduino, using HTTP and WebSocket's.", + "repository": + { + "type": "git", + "url": "https://github.com/arduino-libraries/ArduinoHttpClient.git" + }, + "frameworks": "arduino", + "platforms": "*" +} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/library.properties b/feather_sensor_lte/libraries/ArduinoHttpClient/library.properties new file mode 100644 index 0000000..2ac5bb5 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/library.properties @@ -0,0 +1,10 @@ +name=ArduinoHttpClient +version=0.3.1 +author=Arduino +maintainer=Arduino +sentence=[EXPERIMENTAL] Easily interact with web servers from Arduino, using HTTP and WebSocket's. +paragraph=This library can be used for HTTP (GET, POST, PUT, DELETE) requests to a web server. It also supports exchanging messages with WebSocket servers. Based on Adrian McEwen's HttpClient library. +category=Communication +url=https://github.com/arduino-libraries/ArduinoHttpClient +architectures=* +includes=ArduinoHttpClient.h diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h b/feather_sensor_lte/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h new file mode 100644 index 0000000..578733f --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h @@ -0,0 +1,11 @@ +// Library to simplify HTTP fetching on Arduino +// (c) Copyright Arduino. 2016 +// Released under Apache License, version 2.0 + +#ifndef ArduinoHttpClient_h +#define ArduinoHttpClient_h + +#include "HttpClient.h" +#include "WebSocketClient.h" + +#endif diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/src/HttpClient.cpp b/feather_sensor_lte/libraries/ArduinoHttpClient/src/HttpClient.cpp new file mode 100644 index 0000000..7517eea --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/src/HttpClient.cpp @@ -0,0 +1,862 @@ +// Class to simplify HTTP fetching on Arduino +// (c) Copyright 2010-2011 MCQN Ltd +// Released under Apache License, version 2.0 + +#include "HttpClient.h" +#include "b64.h" + +// Initialize constants +const char* HttpClient::kUserAgent = "Arduino/2.2.0"; +const char* HttpClient::kContentLengthPrefix = HTTP_HEADER_CONTENT_LENGTH ": "; +const char* HttpClient::kTransferEncodingChunked = HTTP_HEADER_TRANSFER_ENCODING ": " HTTP_HEADER_VALUE_CHUNKED; + +HttpClient::HttpClient(Client& aClient, const char* aServerName, uint16_t aServerPort) + : iClient(&aClient), iServerName(aServerName), iServerAddress(), iServerPort(aServerPort), + iConnectionClose(true), iSendDefaultRequestHeaders(true) +{ + resetState(); +} + +HttpClient::HttpClient(Client& aClient, const String& aServerName, uint16_t aServerPort) + : HttpClient(aClient, aServerName.c_str(), aServerPort) +{ +} + +HttpClient::HttpClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort) + : iClient(&aClient), iServerName(NULL), iServerAddress(aServerAddress), iServerPort(aServerPort), + iConnectionClose(true), iSendDefaultRequestHeaders(true) +{ + resetState(); +} + +void HttpClient::resetState() +{ + iState = eIdle; + iStatusCode = 0; + iContentLength = kNoContentLengthHeader; + iBodyLengthConsumed = 0; + iContentLengthPtr = kContentLengthPrefix; + iTransferEncodingChunkedPtr = kTransferEncodingChunked; + iIsChunked = false; + iChunkLength = 0; + iHttpResponseTimeout = kHttpResponseTimeout; +} + +void HttpClient::stop() +{ + iClient->stop(); + resetState(); +} + +void HttpClient::connectionKeepAlive() +{ + iConnectionClose = false; +} + +void HttpClient::noDefaultRequestHeaders() +{ + iSendDefaultRequestHeaders = false; +} + +void HttpClient::beginRequest() +{ + iState = eRequestStarted; +} + +int HttpClient::startRequest(const char* aURLPath, const char* aHttpMethod, + const char* aContentType, int aContentLength, const byte aBody[]) +{ + if (iState == eReadingBody || iState == eReadingChunkLength || iState == eReadingBodyChunk) + { + flushClientRx(); + + resetState(); + } + + tHttpState initialState = iState; + + if ((eIdle != iState) && (eRequestStarted != iState)) + { + return HTTP_ERROR_API; + } + + if (iConnectionClose || !iClient->connected()) + { + if (iServerName) + { + if (!iClient->connect(iServerName, iServerPort) > 0) + { +#ifdef LOGGING + Serial.println("Connection failed"); +#endif + return HTTP_ERROR_CONNECTION_FAILED; + } + } + else + { + if (!iClient->connect(iServerAddress, iServerPort) > 0) + { +#ifdef LOGGING + Serial.println("Connection failed"); +#endif + return HTTP_ERROR_CONNECTION_FAILED; + } + } + } + else + { +#ifdef LOGGING + Serial.println("Connection already open"); +#endif + } + + // Now we're connected, send the first part of the request + int ret = sendInitialHeaders(aURLPath, aHttpMethod); + + if (HTTP_SUCCESS == ret) + { + if (aContentType) + { + sendHeader(HTTP_HEADER_CONTENT_TYPE, aContentType); + } + + if (aContentLength > 0) + { + sendHeader(HTTP_HEADER_CONTENT_LENGTH, aContentLength); + } + + bool hasBody = (aBody && aContentLength > 0); + + if (initialState == eIdle || hasBody) + { + // This was a simple version of the API, so terminate the headers now + finishHeaders(); + } + // else we'll call it in endRequest or in the first call to print, etc. + + if (hasBody) + { + write(aBody, aContentLength); + } + } + + return ret; +} + +int HttpClient::sendInitialHeaders(const char* aURLPath, const char* aHttpMethod) +{ +#ifdef LOGGING + Serial.println("Connected"); +#endif + // Send the HTTP command, i.e. "GET /somepath/ HTTP/1.0" + iClient->print(aHttpMethod); + iClient->print(" "); + + iClient->print(aURLPath); + iClient->println(" HTTP/1.1"); + if (iSendDefaultRequestHeaders) + { + // The host header, if required + if (iServerName) + { + iClient->print("Host: "); + iClient->print(iServerName); + if (iServerPort != kHttpPort) + { + iClient->print(":"); + iClient->print(iServerPort); + } + iClient->println(); + } + // And user-agent string + sendHeader(HTTP_HEADER_USER_AGENT, kUserAgent); + } + + if (iConnectionClose) + { + // Tell the server to + // close this connection after we're done + sendHeader(HTTP_HEADER_CONNECTION, "close"); + } + + // Everything has gone well + iState = eRequestStarted; + return HTTP_SUCCESS; +} + +void HttpClient::sendHeader(const char* aHeader) +{ + iClient->println(aHeader); +} + +void HttpClient::sendHeader(const char* aHeaderName, const char* aHeaderValue) +{ + iClient->print(aHeaderName); + iClient->print(": "); + iClient->println(aHeaderValue); +} + +void HttpClient::sendHeader(const char* aHeaderName, const int aHeaderValue) +{ + iClient->print(aHeaderName); + iClient->print(": "); + iClient->println(aHeaderValue); +} + +void HttpClient::sendBasicAuth(const char* aUser, const char* aPassword) +{ + // Send the initial part of this header line + iClient->print("Authorization: Basic "); + // Now Base64 encode "aUser:aPassword" and send that + // This seems trickier than it should be but it's mostly to avoid either + // (a) some arbitrarily sized buffer which hopes to be big enough, or + // (b) allocating and freeing memory + // ...so we'll loop through 3 bytes at a time, outputting the results as we + // go. + // In Base64, each 3 bytes of unencoded data become 4 bytes of encoded data + unsigned char input[3]; + unsigned char output[5]; // Leave space for a '\0' terminator so we can easily print + int userLen = strlen(aUser); + int passwordLen = strlen(aPassword); + int inputOffset = 0; + for (int i = 0; i < (userLen+1+passwordLen); i++) + { + // Copy the relevant input byte into the input + if (i < userLen) + { + input[inputOffset++] = aUser[i]; + } + else if (i == userLen) + { + input[inputOffset++] = ':'; + } + else + { + input[inputOffset++] = aPassword[i-(userLen+1)]; + } + // See if we've got a chunk to encode + if ( (inputOffset == 3) || (i == userLen+passwordLen) ) + { + // We've either got to a 3-byte boundary, or we've reached then end + b64_encode(input, inputOffset, output, 4); + // NUL-terminate the output string + output[4] = '\0'; + // And write it out + iClient->print((char*)output); +// FIXME We might want to fill output with '=' characters if b64_encode doesn't +// FIXME do it for us when we're encoding the final chunk + inputOffset = 0; + } + } + // And end the header we've sent + iClient->println(); +} + +void HttpClient::finishHeaders() +{ + iClient->println(); + iState = eRequestSent; +} + +void HttpClient::flushClientRx() +{ + while (iClient->available()) + { + iClient->read(); + } +} + +void HttpClient::endRequest() +{ + beginBody(); +} + +void HttpClient::beginBody() +{ + if (iState < eRequestSent) + { + // We still need to finish off the headers + finishHeaders(); + } + // else the end of headers has already been sent, so nothing to do here +} + +int HttpClient::get(const char* aURLPath) +{ + return startRequest(aURLPath, HTTP_METHOD_GET); +} + +int HttpClient::get(const String& aURLPath) +{ + return get(aURLPath.c_str()); +} + +int HttpClient::post(const char* aURLPath) +{ + return startRequest(aURLPath, HTTP_METHOD_POST); +} + +int HttpClient::post(const String& aURLPath) +{ + return post(aURLPath.c_str()); +} + +int HttpClient::post(const char* aURLPath, const char* aContentType, const char* aBody) +{ + return post(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); +} + +int HttpClient::post(const String& aURLPath, const String& aContentType, const String& aBody) +{ + return post(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); +} + +int HttpClient::post(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) +{ + return startRequest(aURLPath, HTTP_METHOD_POST, aContentType, aContentLength, aBody); +} + +int HttpClient::put(const char* aURLPath) +{ + return startRequest(aURLPath, HTTP_METHOD_PUT); +} + +int HttpClient::put(const String& aURLPath) +{ + return put(aURLPath.c_str()); +} + +int HttpClient::put(const char* aURLPath, const char* aContentType, const char* aBody) +{ + return put(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); +} + +int HttpClient::put(const String& aURLPath, const String& aContentType, const String& aBody) +{ + return put(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); +} + +int HttpClient::put(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) +{ + return startRequest(aURLPath, HTTP_METHOD_PUT, aContentType, aContentLength, aBody); +} + +int HttpClient::patch(const char* aURLPath) +{ + return startRequest(aURLPath, HTTP_METHOD_PATCH); +} + +int HttpClient::patch(const String& aURLPath) +{ + return patch(aURLPath.c_str()); +} + +int HttpClient::patch(const char* aURLPath, const char* aContentType, const char* aBody) +{ + return patch(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); +} + +int HttpClient::patch(const String& aURLPath, const String& aContentType, const String& aBody) +{ + return patch(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); +} + +int HttpClient::patch(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) +{ + return startRequest(aURLPath, HTTP_METHOD_PATCH, aContentType, aContentLength, aBody); +} + +int HttpClient::del(const char* aURLPath) +{ + return startRequest(aURLPath, HTTP_METHOD_DELETE); +} + +int HttpClient::del(const String& aURLPath) +{ + return del(aURLPath.c_str()); +} + +int HttpClient::del(const char* aURLPath, const char* aContentType, const char* aBody) +{ + return del(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); +} + +int HttpClient::del(const String& aURLPath, const String& aContentType, const String& aBody) +{ + return del(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); +} + +int HttpClient::del(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) +{ + return startRequest(aURLPath, HTTP_METHOD_DELETE, aContentType, aContentLength, aBody); +} + +int HttpClient::responseStatusCode() +{ + if (iState < eRequestSent) + { + return HTTP_ERROR_API; + } + // The first line will be of the form Status-Line: + // HTTP-Version SP Status-Code SP Reason-Phrase CRLF + // Where HTTP-Version is of the form: + // HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT + + int c = '\0'; + do + { + // Make sure the status code is reset, and likewise the state. This + // lets us easily cope with 1xx informational responses by just + // ignoring them really, and reading the next line for a proper response + iStatusCode = 0; + iState = eRequestSent; + + unsigned long timeoutStart = millis(); + // Psuedo-regexp we're expecting before the status-code + const char* statusPrefix = "HTTP/*.* "; + const char* statusPtr = statusPrefix; + // Whilst we haven't timed out & haven't reached the end of the headers + while ((c != '\n') && + ( (millis() - timeoutStart) < iHttpResponseTimeout )) + { + if (available()) + { + c = read(); + if (c != -1) + { + switch(iState) + { + case eRequestSent: + // We haven't reached the status code yet + if ( (*statusPtr == '*') || (*statusPtr == c) ) + { + // This character matches, just move along + statusPtr++; + if (*statusPtr == '\0') + { + // We've reached the end of the prefix + iState = eReadingStatusCode; + } + } + else + { + return HTTP_ERROR_INVALID_RESPONSE; + } + break; + case eReadingStatusCode: + if (isdigit(c)) + { + // This assumes we won't get more than the 3 digits we + // want + iStatusCode = iStatusCode*10 + (c - '0'); + } + else + { + // We've reached the end of the status code + // We could sanity check it here or double-check for ' ' + // rather than anything else, but let's be lenient + iState = eStatusCodeRead; + } + break; + case eStatusCodeRead: + // We're just waiting for the end of the line now + break; + + default: + break; + }; + // We read something, reset the timeout counter + timeoutStart = millis(); + } + } + else + { + // We haven't got any data, so let's pause to allow some to + // arrive + delay(kHttpWaitForDataDelay); + } + } + if ( (c == '\n') && (iStatusCode < 200 && iStatusCode != 101) ) + { + // We've reached the end of an informational status line + c = '\0'; // Clear c so we'll go back into the data reading loop + } + } + // If we've read a status code successfully but it's informational (1xx) + // loop back to the start + while ( (iState == eStatusCodeRead) && (iStatusCode < 200 && iStatusCode != 101) ); + + if ( (c == '\n') && (iState == eStatusCodeRead) ) + { + // We've read the status-line successfully + return iStatusCode; + } + else if (c != '\n') + { + // We must've timed out before we reached the end of the line + return HTTP_ERROR_TIMED_OUT; + } + else + { + // This wasn't a properly formed status line, or at least not one we + // could understand + return HTTP_ERROR_INVALID_RESPONSE; + } +} + +int HttpClient::skipResponseHeaders() +{ + // Just keep reading until we finish reading the headers or time out + unsigned long timeoutStart = millis(); + // Whilst we haven't timed out & haven't reached the end of the headers + while ((!endOfHeadersReached()) && + ( (millis() - timeoutStart) < iHttpResponseTimeout )) + { + if (available()) + { + (void)readHeader(); + // We read something, reset the timeout counter + timeoutStart = millis(); + } + else + { + // We haven't got any data, so let's pause to allow some to + // arrive + delay(kHttpWaitForDataDelay); + } + } + if (endOfHeadersReached()) + { + // Success + return HTTP_SUCCESS; + } + else + { + // We must've timed out + return HTTP_ERROR_TIMED_OUT; + } +} + +bool HttpClient::endOfHeadersReached() +{ + return (iState == eReadingBody || iState == eReadingChunkLength || iState == eReadingBodyChunk); +}; + +int HttpClient::contentLength() +{ + // skip the response headers, if they haven't been read already + if (!endOfHeadersReached()) + { + skipResponseHeaders(); + } + + return iContentLength; +} + +String HttpClient::responseBody() +{ + int bodyLength = contentLength(); + String response; + + if (bodyLength > 0) + { + // try to reserve bodyLength bytes + if (response.reserve(bodyLength) == 0) { + // String reserve failed + return String((const char*)NULL); + } + } + + // keep on timedRead'ing, until: + // - we have a content length: body length equals consumed or no bytes + // available + // - no content length: no bytes are available + while (iBodyLengthConsumed != bodyLength) + { + int c = timedRead(); + + if (c == -1) { + // read timed out, done + break; + } + + if (!response.concat((char)c)) { + // adding char failed + return String((const char*)NULL); + } + } + + if (bodyLength > 0 && (unsigned int)bodyLength != response.length()) { + // failure, we did not read in reponse content length bytes + return String((const char*)NULL); + } + + return response; +} + +bool HttpClient::endOfBodyReached() +{ + if (endOfHeadersReached() && (contentLength() != kNoContentLengthHeader)) + { + // We've got to the body and we know how long it will be + return (iBodyLengthConsumed >= contentLength()); + } + return false; +} + +int HttpClient::available() +{ + if (iState == eReadingChunkLength) + { + while (iClient->available()) + { + char c = iClient->read(); + + if (c == '\n') + { + iState = eReadingBodyChunk; + break; + } + else if (c == '\r') + { + // no-op + } + else if (isHexadecimalDigit(c)) + { + char digit[2] = {c, '\0'}; + + iChunkLength = (iChunkLength * 16) + strtol(digit, NULL, 16); + } + } + } + + if (iState == eReadingBodyChunk && iChunkLength == 0) + { + iState = eReadingChunkLength; + } + + if (iState == eReadingChunkLength) + { + return 0; + } + + int clientAvailable = iClient->available(); + + if (iState == eReadingBodyChunk) + { + return min(clientAvailable, iChunkLength); + } + else + { + return clientAvailable; + } +} + + +int HttpClient::read() +{ + if (iIsChunked && !available()) + { + return -1; + } + + int ret = iClient->read(); + if (ret >= 0) + { + if (endOfHeadersReached() && iContentLength > 0) + { + // We're outputting the body now and we've seen a Content-Length header + // So keep track of how many bytes are left + iBodyLengthConsumed++; + } + + if (iState == eReadingBodyChunk) + { + iChunkLength--; + + if (iChunkLength == 0) + { + iState = eReadingChunkLength; + } + } + } + return ret; +} + +bool HttpClient::headerAvailable() +{ + // clear the currently store header line + iHeaderLine = ""; + + while (!endOfHeadersReached()) + { + // read a byte from the header + int c = readHeader(); + + if (c == '\r' || c == '\n') + { + if (iHeaderLine.length()) + { + // end of the line, all done + break; + } + else + { + // ignore any CR or LF characters + continue; + } + } + + // append byte to header line + iHeaderLine += (char)c; + } + + return (iHeaderLine.length() > 0); +} + +String HttpClient::readHeaderName() +{ + int colonIndex = iHeaderLine.indexOf(':'); + + if (colonIndex == -1) + { + return ""; + } + + return iHeaderLine.substring(0, colonIndex); +} + +String HttpClient::readHeaderValue() +{ + int colonIndex = iHeaderLine.indexOf(':'); + int startIndex = colonIndex + 1; + + if (colonIndex == -1) + { + return ""; + } + + // trim any leading whitespace + while (startIndex < (int)iHeaderLine.length() && isSpace(iHeaderLine[startIndex])) + { + startIndex++; + } + + return iHeaderLine.substring(startIndex); +} + +int HttpClient::read(uint8_t *buf, size_t size) +{ + int ret =iClient->read(buf, size); + if (endOfHeadersReached() && iContentLength > 0) + { + // We're outputting the body now and we've seen a Content-Length header + // So keep track of how many bytes are left + if (ret >= 0) + { + iBodyLengthConsumed += ret; + } + } + return ret; +} + +int HttpClient::readHeader() +{ + char c = read(); + + if (endOfHeadersReached()) + { + // We've passed the headers, but rather than return an error, we'll just + // act as a slightly less efficient version of read() + return c; + } + + // Whilst reading out the headers to whoever wants them, we'll keep an + // eye out for the "Content-Length" header + switch(iState) + { + case eStatusCodeRead: + // We're at the start of a line, or somewhere in the middle of reading + // the Content-Length prefix + if (*iContentLengthPtr == c) + { + // This character matches, just move along + iContentLengthPtr++; + if (*iContentLengthPtr == '\0') + { + // We've reached the end of the prefix + iState = eReadingContentLength; + // Just in case we get multiple Content-Length headers, this + // will ensure we just get the value of the last one + iContentLength = 0; + iBodyLengthConsumed = 0; + } + } + else if (*iTransferEncodingChunkedPtr == c) + { + // This character matches, just move along + iTransferEncodingChunkedPtr++; + if (*iTransferEncodingChunkedPtr == '\0') + { + // We've reached the end of the Transfer Encoding: chunked header + iIsChunked = true; + iState = eSkipToEndOfHeader; + } + } + else if (((iContentLengthPtr == kContentLengthPrefix) && (iTransferEncodingChunkedPtr == kTransferEncodingChunked)) && (c == '\r')) + { + // We've found a '\r' at the start of a line, so this is probably + // the end of the headers + iState = eLineStartingCRFound; + } + else + { + // This isn't the Content-Length or Transfer Encoding chunked header, skip to the end of the line + iState = eSkipToEndOfHeader; + } + break; + case eReadingContentLength: + if (isdigit(c)) + { + iContentLength = iContentLength*10 + (c - '0'); + } + else + { + // We've reached the end of the content length + // We could sanity check it here or double-check for "\r\n" + // rather than anything else, but let's be lenient + iState = eSkipToEndOfHeader; + } + break; + case eLineStartingCRFound: + if (c == '\n') + { + if (iIsChunked) + { + iState = eReadingChunkLength; + iChunkLength = 0; + } + else + { + iState = eReadingBody; + } + } + break; + default: + // We're just waiting for the end of the line now + break; + }; + + if ( (c == '\n') && !endOfHeadersReached() ) + { + // We've got to the end of this line, start processing again + iState = eStatusCodeRead; + iContentLengthPtr = kContentLengthPrefix; + iTransferEncodingChunkedPtr = kTransferEncodingChunked; + } + // And return the character read to whoever wants it + return c; +} + + + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/src/HttpClient.h b/feather_sensor_lte/libraries/ArduinoHttpClient/src/HttpClient.h new file mode 100644 index 0000000..c954872 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/src/HttpClient.h @@ -0,0 +1,392 @@ +// Class to simplify HTTP fetching on Arduino +// (c) Copyright MCQN Ltd. 2010-2012 +// Released under Apache License, version 2.0 + +#ifndef HttpClient_h +#define HttpClient_h + +#include +#include +#include "Client.h" + +static const int HTTP_SUCCESS =0; +// The end of the headers has been reached. This consumes the '\n' +// Could not connect to the server +static const int HTTP_ERROR_CONNECTION_FAILED =-1; +// This call was made when the HttpClient class wasn't expecting it +// to be called. Usually indicates your code is using the class +// incorrectly +static const int HTTP_ERROR_API =-2; +// Spent too long waiting for a reply +static const int HTTP_ERROR_TIMED_OUT =-3; +// The response from the server is invalid, is it definitely an HTTP +// server? +static const int HTTP_ERROR_INVALID_RESPONSE =-4; + +// Define some of the common methods and headers here +// That lets other code reuse them without having to declare another copy +// of them, so saves code space and RAM +#define HTTP_METHOD_GET "GET" +#define HTTP_METHOD_POST "POST" +#define HTTP_METHOD_PUT "PUT" +#define HTTP_METHOD_PATCH "PATCH" +#define HTTP_METHOD_DELETE "DELETE" +#define HTTP_HEADER_CONTENT_LENGTH "Content-Length" +#define HTTP_HEADER_CONTENT_TYPE "Content-Type" +#define HTTP_HEADER_CONNECTION "Connection" +#define HTTP_HEADER_TRANSFER_ENCODING "Transfer-Encoding" +#define HTTP_HEADER_USER_AGENT "User-Agent" +#define HTTP_HEADER_VALUE_CHUNKED "chunked" + +class HttpClient : public Client +{ +public: + static const int kNoContentLengthHeader =-1; + static const int kHttpPort =80; + static const char* kUserAgent; + +// FIXME Write longer API request, using port and user-agent, example +// FIXME Update tempToPachube example to calculate Content-Length correctly + + HttpClient(Client& aClient, const char* aServerName, uint16_t aServerPort = kHttpPort); + HttpClient(Client& aClient, const String& aServerName, uint16_t aServerPort = kHttpPort); + HttpClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort = kHttpPort); + + /** Start a more complex request. + Use this when you need to send additional headers in the request, + but you will also need to call endRequest() when you are finished. + */ + void beginRequest(); + + /** End a more complex request. + Use this when you need to have sent additional headers in the request, + but you will also need to call beginRequest() at the start. + */ + void endRequest(); + + /** Start the body of a more complex request. + Use this when you need to send the body after additional headers + in the request, but can optionally call endRequest() when + you are finished. + */ + void beginBody(); + + /** Connect to the server and start to send a GET request. + @param aURLPath Url to request + @return 0 if successful, else error + */ + int get(const char* aURLPath); + int get(const String& aURLPath); + + /** Connect to the server and start to send a POST request. + @param aURLPath Url to request + @return 0 if successful, else error + */ + int post(const char* aURLPath); + int post(const String& aURLPath); + + /** Connect to the server and send a POST request + with body and content type + @param aURLPath Url to request + @param aContentType Content type of request body + @param aBody Body of the request + @return 0 if successful, else error + */ + int post(const char* aURLPath, const char* aContentType, const char* aBody); + int post(const String& aURLPath, const String& aContentType, const String& aBody); + int post(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); + + /** Connect to the server and start to send a PUT request. + @param aURLPath Url to request + @return 0 if successful, else error + */ + int put(const char* aURLPath); + int put(const String& aURLPath); + + /** Connect to the server and send a PUT request + with body and content type + @param aURLPath Url to request + @param aContentType Content type of request body + @param aBody Body of the request + @return 0 if successful, else error + */ + int put(const char* aURLPath, const char* aContentType, const char* aBody); + int put(const String& aURLPath, const String& aContentType, const String& aBody); + int put(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); + + /** Connect to the server and start to send a PATCH request. + @param aURLPath Url to request + @return 0 if successful, else error + */ + int patch(const char* aURLPath); + int patch(const String& aURLPath); + + /** Connect to the server and send a PATCH request + with body and content type + @param aURLPath Url to request + @param aContentType Content type of request body + @param aBody Body of the request + @return 0 if successful, else error + */ + int patch(const char* aURLPath, const char* aContentType, const char* aBody); + int patch(const String& aURLPath, const String& aContentType, const String& aBody); + int patch(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); + + /** Connect to the server and start to send a DELETE request. + @param aURLPath Url to request + @return 0 if successful, else error + */ + int del(const char* aURLPath); + int del(const String& aURLPath); + + /** Connect to the server and send a DELETE request + with body and content type + @param aURLPath Url to request + @param aContentType Content type of request body + @param aBody Body of the request + @return 0 if successful, else error + */ + int del(const char* aURLPath, const char* aContentType, const char* aBody); + int del(const String& aURLPath, const String& aContentType, const String& aBody); + int del(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); + + /** Connect to the server and start to send the request. + If a body is provided, the entire request (including headers and body) will be sent + @param aURLPath Url to request + @param aHttpMethod Type of HTTP request to make, e.g. "GET", "POST", etc. + @param aContentType Content type of request body (optional) + @param aContentLength Length of request body (optional) + @param aBody Body of request (optional) + @return 0 if successful, else error + */ + int startRequest(const char* aURLPath, + const char* aHttpMethod, + const char* aContentType = NULL, + int aContentLength = -1, + const byte aBody[] = NULL); + + /** Send an additional header line. This can only be called in between the + calls to startRequest and finishRequest. + @param aHeader Header line to send, in its entirety (but without the + trailing CRLF. E.g. "Authorization: Basic YQDDCAIGES" + */ + void sendHeader(const char* aHeader); + + void sendHeader(const String& aHeader) + { sendHeader(aHeader.c_str()); } + + /** Send an additional header line. This is an alternate form of + sendHeader() which takes the header name and content as separate strings. + The call will add the ": " to separate the header, so for example, to + send a XXXXXX header call sendHeader("XXXXX", "Something") + @param aHeaderName Type of header being sent + @param aHeaderValue Value for that header + */ + void sendHeader(const char* aHeaderName, const char* aHeaderValue); + + void sendHeader(const String& aHeaderName, const String& aHeaderValue) + { sendHeader(aHeaderName.c_str(), aHeaderValue.c_str()); } + + /** Send an additional header line. This is an alternate form of + sendHeader() which takes the header name and content separately but where + the value is provided as an integer. + The call will add the ": " to separate the header, so for example, to + send a XXXXXX header call sendHeader("XXXXX", 123) + @param aHeaderName Type of header being sent + @param aHeaderValue Value for that header + */ + void sendHeader(const char* aHeaderName, const int aHeaderValue); + + void sendHeader(const String& aHeaderName, const int aHeaderValue) + { sendHeader(aHeaderName.c_str(), aHeaderValue); } + + /** Send a basic authentication header. This will encode the given username + and password, and send them in suitable header line for doing Basic + Authentication. + @param aUser Username for the authorization + @param aPassword Password for the user aUser + */ + void sendBasicAuth(const char* aUser, const char* aPassword); + + void sendBasicAuth(const String& aUser, const String& aPassword) + { sendBasicAuth(aUser.c_str(), aPassword.c_str()); } + + /** Get the HTTP status code contained in the response. + For example, 200 for successful request, 404 for file not found, etc. + */ + int responseStatusCode(); + + /** Check if a header is available to be read. + Use readHeaderName() to read header name, and readHeaderValue() to + read the header value + MUST be called after responseStatusCode() and before contentLength() + */ + bool headerAvailable(); + + /** Read the name of the current response header. + Returns empty string if a header is not available. + */ + String readHeaderName(); + + /** Read the vallue of the current response header. + Returns empty string if a header is not available. + */ + String readHeaderValue(); + + /** Read the next character of the response headers. + This functions in the same way as read() but to be used when reading + through the headers. Check whether or not the end of the headers has + been reached by calling endOfHeadersReached(), although after that point + this will still return data as read() would, but slightly less efficiently + MUST be called after responseStatusCode() and before contentLength() + @return The next character of the response headers + */ + int readHeader(); + + /** Skip any response headers to get to the body. + Use this if you don't want to do any special processing of the headers + returned in the response. You can also use it after you've found all of + the headers you're interested in, and just want to get on with processing + the body. + MUST be called after responseStatusCode() + @return HTTP_SUCCESS if successful, else an error code + */ + int skipResponseHeaders(); + + /** Test whether all of the response headers have been consumed. + @return true if we are now processing the response body, else false + */ + bool endOfHeadersReached(); + + /** Test whether the end of the body has been reached. + Only works if the Content-Length header was returned by the server + @return true if we are now at the end of the body, else false + */ + bool endOfBodyReached(); + virtual bool endOfStream() { return endOfBodyReached(); }; + virtual bool completed() { return endOfBodyReached(); }; + + /** Return the length of the body. + Also skips response headers if they have not been read already + MUST be called after responseStatusCode() + @return Length of the body, in bytes, or kNoContentLengthHeader if no + Content-Length header was returned by the server + */ + int contentLength(); + + /** Returns if the response body is chunked + @return true if response body is chunked, false otherwise + */ + int isResponseChunked() { return iIsChunked; } + + /** Return the response body as a String + Also skips response headers if they have not been read already + MUST be called after responseStatusCode() + @return response body of request as a String + */ + String responseBody(); + + /** Enables connection keep-alive mode + */ + void connectionKeepAlive(); + + /** Disables sending the default request headers (Host and User Agent) + */ + void noDefaultRequestHeaders(); + + // Inherited from Print + // Note: 1st call to these indicates the user is sending the body, so if need + // Note: be we should finish the header first + virtual size_t write(uint8_t aByte) { if (iState < eRequestSent) { finishHeaders(); }; return iClient-> write(aByte); }; + virtual size_t write(const uint8_t *aBuffer, size_t aSize) { if (iState < eRequestSent) { finishHeaders(); }; return iClient->write(aBuffer, aSize); }; + // Inherited from Stream + virtual int available(); + /** Read the next byte from the server. + @return Byte read or -1 if there are no bytes available. + */ + virtual int read(); + virtual int read(uint8_t *buf, size_t size); + virtual int peek() { return iClient->peek(); }; + virtual void flush() { return iClient->flush(); }; + + // Inherited from Client + virtual int connect(IPAddress ip, uint16_t port) { return iClient->connect(ip, port); }; + virtual int connect(const char *host, uint16_t port) { return iClient->connect(host, port); }; + virtual void stop(); + virtual uint8_t connected() { return iClient->connected(); }; + virtual operator bool() { return bool(iClient); }; + virtual uint32_t httpResponseTimeout() { return iHttpResponseTimeout; }; + virtual void setHttpResponseTimeout(uint32_t timeout) { iHttpResponseTimeout = timeout; }; +protected: + /** Reset internal state data back to the "just initialised" state + */ + void resetState(); + + /** Send the first part of the request and the initial headers. + @param aURLPath Url to request + @param aHttpMethod Type of HTTP request to make, e.g. "GET", "POST", etc. + @return 0 if successful, else error + */ + int sendInitialHeaders(const char* aURLPath, + const char* aHttpMethod); + + /* Let the server know that we've reached the end of the headers + */ + void finishHeaders(); + + /** Reading any pending data from the client (used in connection keep alive mode) + */ + void flushClientRx(); + + // Number of milliseconds that we wait each time there isn't any data + // available to be read (during status code and header processing) + static const int kHttpWaitForDataDelay = 1000; + // Number of milliseconds that we'll wait in total without receiveing any + // data before returning HTTP_ERROR_TIMED_OUT (during status code and header + // processing) + static const int kHttpResponseTimeout = 30*1000; + static const char* kContentLengthPrefix; + static const char* kTransferEncodingChunked; + typedef enum { + eIdle, + eRequestStarted, + eRequestSent, + eReadingStatusCode, + eStatusCodeRead, + eReadingContentLength, + eSkipToEndOfHeader, + eLineStartingCRFound, + eReadingBody, + eReadingChunkLength, + eReadingBodyChunk + } tHttpState; + // Client we're using + Client* iClient; + // Server we are connecting to + const char* iServerName; + IPAddress iServerAddress; + // Port of server we are connecting to + uint16_t iServerPort; + // Current state of the finite-state-machine + tHttpState iState; + // Stores the status code for the response, once known + int iStatusCode; + // Stores the value of the Content-Length header, if present + int iContentLength; + // How many bytes of the response body have been read by the user + int iBodyLengthConsumed; + // How far through a Content-Length header prefix we are + const char* iContentLengthPtr; + // How far through a Transfer-Encoding chunked header we are + const char* iTransferEncodingChunkedPtr; + // Stores if the response body is chunked + bool iIsChunked; + // Stores the value of the current chunk length, if present + int iChunkLength; + uint32_t iHttpResponseTimeout; + bool iConnectionClose; + bool iSendDefaultRequestHeaders; + String iHeaderLine; +}; + +#endif diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/src/WebSocketClient.cpp b/feather_sensor_lte/libraries/ArduinoHttpClient/src/WebSocketClient.cpp new file mode 100644 index 0000000..ab41b0a --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/src/WebSocketClient.cpp @@ -0,0 +1,372 @@ +// (c) Copyright Arduino. 2016 +// Released under Apache License, version 2.0 + +#include "b64.h" + +#include "WebSocketClient.h" + +WebSocketClient::WebSocketClient(Client& aClient, const char* aServerName, uint16_t aServerPort) + : HttpClient(aClient, aServerName, aServerPort), + iTxStarted(false), + iRxSize(0) +{ +} + +WebSocketClient::WebSocketClient(Client& aClient, const String& aServerName, uint16_t aServerPort) + : HttpClient(aClient, aServerName, aServerPort), + iTxStarted(false), + iRxSize(0) +{ +} + +WebSocketClient::WebSocketClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort) + : HttpClient(aClient, aServerAddress, aServerPort), + iTxStarted(false), + iRxSize(0) +{ +} + +int WebSocketClient::begin(const char* aPath) +{ + // start the GET request + beginRequest(); + connectionKeepAlive(); + int status = get(aPath); + + if (status == 0) + { + uint8_t randomKey[16]; + char base64RandomKey[25]; + + // create a random key for the connection upgrade + for (int i = 0; i < (int)sizeof(randomKey); i++) + { + randomKey[i] = random(0x01, 0xff); + } + memset(base64RandomKey, 0x00, sizeof(base64RandomKey)); + b64_encode(randomKey, sizeof(randomKey), (unsigned char*)base64RandomKey, sizeof(base64RandomKey)); + + // start the connection upgrade sequence + sendHeader("Upgrade", "websocket"); + sendHeader("Connection", "Upgrade"); + sendHeader("Sec-WebSocket-Key", base64RandomKey); + sendHeader("Sec-WebSocket-Version", "13"); + endRequest(); + + status = responseStatusCode(); + + if (status > 0) + { + skipResponseHeaders(); + } + } + + iRxSize = 0; + + // status code of 101 means success + return (status == 101) ? 0 : status; +} + +int WebSocketClient::begin(const String& aPath) +{ + return begin(aPath.c_str()); +} + +int WebSocketClient::beginMessage(int aType) +{ + if (iTxStarted) + { + // fail TX already started + return 1; + } + + iTxStarted = true; + iTxMessageType = (aType & 0xf); + iTxSize = 0; + + return 0; +} + +int WebSocketClient::endMessage() +{ + if (!iTxStarted) + { + // fail TX not started + return 1; + } + + // send FIN + the message type (opcode) + HttpClient::write(0x80 | iTxMessageType); + + // the message is masked (0x80) + // send the length + if (iTxSize < 126) + { + HttpClient::write(0x80 | (uint8_t)iTxSize); + } + else if (iTxSize < 0xffff) + { + HttpClient::write(0x80 | 126); + HttpClient::write((iTxSize >> 8) & 0xff); + HttpClient::write((iTxSize >> 0) & 0xff); + } + else + { + HttpClient::write(0x80 | 127); + HttpClient::write((iTxSize >> 56) & 0xff); + HttpClient::write((iTxSize >> 48) & 0xff); + HttpClient::write((iTxSize >> 40) & 0xff); + HttpClient::write((iTxSize >> 32) & 0xff); + HttpClient::write((iTxSize >> 24) & 0xff); + HttpClient::write((iTxSize >> 16) & 0xff); + HttpClient::write((iTxSize >> 8) & 0xff); + HttpClient::write((iTxSize >> 0) & 0xff); + } + + uint8_t maskKey[4]; + + // create a random mask for the data and send + for (int i = 0; i < (int)sizeof(maskKey); i++) + { + maskKey[i] = random(0xff); + } + HttpClient::write(maskKey, sizeof(maskKey)); + + // mask the data and send + for (int i = 0; i < (int)iTxSize; i++) { + iTxBuffer[i] ^= maskKey[i % sizeof(maskKey)]; + } + + size_t txSize = iTxSize; + + iTxStarted = false; + iTxSize = 0; + + return (HttpClient::write(iTxBuffer, txSize) == txSize) ? 0 : 1; +} + +size_t WebSocketClient::write(uint8_t aByte) +{ + return write(&aByte, sizeof(aByte)); +} + +size_t WebSocketClient::write(const uint8_t *aBuffer, size_t aSize) +{ + if (iState < eReadingBody) + { + // have not upgraded the connection yet + return HttpClient::write(aBuffer, aSize); + } + + if (!iTxStarted) + { + // fail TX not started + return 0; + } + + // check if the write size, fits in the buffer + if ((iTxSize + aSize) > sizeof(iTxBuffer)) + { + aSize = sizeof(iTxSize) - iTxSize; + } + + // copy data into the buffer + memcpy(iTxBuffer + iTxSize, aBuffer, aSize); + + iTxSize += aSize; + + return aSize; +} + +int WebSocketClient::parseMessage() +{ + flushRx(); + + // make sure 2 bytes (opcode + length) + // are available + if (HttpClient::available() < 2) + { + return 0; + } + + // read open code and length + uint8_t opcode = HttpClient::read(); + int length = HttpClient::read(); + + if ((opcode & 0x0f) == 0) + { + // continuation, use previous opcode and update flags + iRxOpCode |= opcode; + } + else + { + iRxOpCode = opcode; + } + + iRxMasked = (length & 0x80); + length &= 0x7f; + + // read the RX size + if (length < 126) + { + iRxSize = length; + } + else if (length == 126) + { + iRxSize = (HttpClient::read() << 8) | HttpClient::read(); + } + else + { + iRxSize = ((uint64_t)HttpClient::read() << 56) | + ((uint64_t)HttpClient::read() << 48) | + ((uint64_t)HttpClient::read() << 40) | + ((uint64_t)HttpClient::read() << 32) | + ((uint64_t)HttpClient::read() << 24) | + ((uint64_t)HttpClient::read() << 16) | + ((uint64_t)HttpClient::read() << 8) | + (uint64_t)HttpClient::read(); + } + + // read in the mask, if present + if (iRxMasked) + { + for (int i = 0; i < (int)sizeof(iRxMaskKey); i++) + { + iRxMaskKey[i] = HttpClient::read(); + } + } + + iRxMaskIndex = 0; + + if (TYPE_CONNECTION_CLOSE == messageType()) + { + flushRx(); + stop(); + iRxSize = 0; + } + else if (TYPE_PING == messageType()) + { + beginMessage(TYPE_PONG); + while(available()) + { + write(read()); + } + endMessage(); + + iRxSize = 0; + } + else if (TYPE_PONG == messageType()) + { + flushRx(); + iRxSize = 0; + } + + return iRxSize; +} + +int WebSocketClient::messageType() +{ + return (iRxOpCode & 0x0f); +} + +bool WebSocketClient::isFinal() +{ + return ((iRxOpCode & 0x80) != 0); +} + +String WebSocketClient::readString() +{ + int avail = available(); + String s; + + if (avail > 0) + { + s.reserve(avail); + + for (int i = 0; i < avail; i++) + { + s += (char)read(); + } + } + + return s; +} + +int WebSocketClient::ping() +{ + uint8_t pingData[16]; + + // create random data for the ping + for (int i = 0; i < (int)sizeof(pingData); i++) + { + pingData[i] = random(0xff); + } + + beginMessage(TYPE_PING); + write(pingData, sizeof(pingData)); + return endMessage(); +} + +int WebSocketClient::available() +{ + if (iState < eReadingBody) + { + return HttpClient::available(); + } + + return iRxSize; +} + +int WebSocketClient::read() +{ + byte b; + + if (read(&b, sizeof(b))) + { + return b; + } + + return -1; +} + +int WebSocketClient::read(uint8_t *aBuffer, size_t aSize) +{ + int readCount = HttpClient::read(aBuffer, aSize); + + if (readCount > 0) + { + iRxSize -= readCount; + + // unmask the RX data if needed + if (iRxMasked) + { + for (int i = 0; i < (int)aSize; i++, iRxMaskIndex++) + { + aBuffer[i] ^= iRxMaskKey[iRxMaskIndex % sizeof(iRxMaskKey)]; + } + } + } + + return readCount; +} + +int WebSocketClient::peek() +{ + int p = HttpClient::peek(); + + if (p != -1 && iRxMasked) + { + // unmask the RX data if needed + p = (uint8_t)p ^ iRxMaskKey[iRxMaskIndex % sizeof(iRxMaskKey)]; + } + + return p; +} + +void WebSocketClient::flushRx() +{ + while(available()) + { + read(); + } +} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/src/WebSocketClient.h b/feather_sensor_lte/libraries/ArduinoHttpClient/src/WebSocketClient.h new file mode 100644 index 0000000..4b009e6 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/src/WebSocketClient.h @@ -0,0 +1,99 @@ +// (c) Copyright Arduino. 2016 +// Released under Apache License, version 2.0 + +#ifndef WebSocketClient_h +#define WebSocketClient_h + +#include + +#include "HttpClient.h" + +static const int TYPE_CONTINUATION = 0x0; +static const int TYPE_TEXT = 0x1; +static const int TYPE_BINARY = 0x2; +static const int TYPE_CONNECTION_CLOSE = 0x8; +static const int TYPE_PING = 0x9; +static const int TYPE_PONG = 0xa; + +class WebSocketClient : public HttpClient +{ +public: + WebSocketClient(Client& aClient, const char* aServerName, uint16_t aServerPort = HttpClient::kHttpPort); + WebSocketClient(Client& aClient, const String& aServerName, uint16_t aServerPort = HttpClient::kHttpPort); + WebSocketClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort = HttpClient::kHttpPort); + + /** Start the Web Socket connection to the specified path + @param aURLPath Path to use in request (optional, "/" is used by default) + @return 0 if successful, else error + */ + int begin(const char* aPath = "/"); + int begin(const String& aPath); + + /** Begin to send a message of type (TYPE_TEXT or TYPE_BINARY) + Use the write or Stream API's to set message content, followed by endMessage + to complete the message. + @param aURLPath Path to use in request + @return 0 if successful, else error + */ + int beginMessage(int aType); + + /** Completes sending of a message started by beginMessage + @return 0 if successful, else error + */ + int endMessage(); + + /** Try to parse an incoming messages + @return 0 if no message available, else size of parsed message + */ + int parseMessage(); + + /** Returns type of current parsed message + @return type of current parsedMessage (TYPE_TEXT or TYPE_BINARY) + */ + int messageType(); + + /** Returns if the current message is the final chunk of a split + message + @return true for final message, false otherwise + */ + bool isFinal(); + + /** Read the current messages as a string + @return current message as a string + */ + String readString(); + + /** Send a ping + @return 0 if successful, else error + */ + int ping(); + + // Inherited from Print + virtual size_t write(uint8_t aByte); + virtual size_t write(const uint8_t *aBuffer, size_t aSize); + // Inherited from Stream + virtual int available(); + /** Read the next byte from the server. + @return Byte read or -1 if there are no bytes available. + */ + virtual int read(); + virtual int read(uint8_t *buf, size_t size); + virtual int peek(); + +private: + void flushRx(); + +private: + bool iTxStarted; + uint8_t iTxMessageType; + uint8_t iTxBuffer[128]; + uint64_t iTxSize; + + uint8_t iRxOpCode; + uint64_t iRxSize; + bool iRxMasked; + int iRxMaskIndex; + uint8_t iRxMaskKey[4]; +}; + +#endif diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/src/b64.cpp b/feather_sensor_lte/libraries/ArduinoHttpClient/src/b64.cpp new file mode 100644 index 0000000..683d60a --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/src/b64.cpp @@ -0,0 +1,72 @@ +// Simple Base64 code +// (c) Copyright 2010 MCQN Ltd. +// Released under Apache License, version 2.0 + +#include "b64.h" + +/* Simple test program +#include +void main() +{ + char* in = "amcewen"; + char out[22]; + + b64_encode(in, 15, out, 22); + out[21] = '\0'; + + printf(out); +} +*/ + +int b64_encode(const unsigned char* aInput, int aInputLen, unsigned char* aOutput, int aOutputLen) +{ + // Work out if we've got enough space to encode the input + // Every 6 bits of input becomes a byte of output + if (aOutputLen < (aInputLen*8)/6) + { + // FIXME Should we return an error here, or just the length + return (aInputLen*8)/6; + } + + // If we get here we've got enough space to do the encoding + + const char* b64_dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + if (aInputLen == 3) + { + aOutput[0] = b64_dictionary[aInput[0] >> 2]; + aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4|(aInput[1]>>4)]; + aOutput[2] = b64_dictionary[(aInput[1]&0x0F)<<2|(aInput[2]>>6)]; + aOutput[3] = b64_dictionary[aInput[2]&0x3F]; + } + else if (aInputLen == 2) + { + aOutput[0] = b64_dictionary[aInput[0] >> 2]; + aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4|(aInput[1]>>4)]; + aOutput[2] = b64_dictionary[(aInput[1]&0x0F)<<2]; + aOutput[3] = '='; + } + else if (aInputLen == 1) + { + aOutput[0] = b64_dictionary[aInput[0] >> 2]; + aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4]; + aOutput[2] = '='; + aOutput[3] = '='; + } + else + { + // Break the input into 3-byte chunks and process each of them + int i; + for (i = 0; i < aInputLen/3; i++) + { + b64_encode(&aInput[i*3], 3, &aOutput[i*4], 4); + } + if (aInputLen % 3 > 0) + { + // It doesn't fit neatly into a 3-byte chunk, so process what's left + b64_encode(&aInput[i*3], aInputLen % 3, &aOutput[i*4], aOutputLen - (i*4)); + } + } + + return ((aInputLen+2)/3)*4; +} + diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/src/b64.h b/feather_sensor_lte/libraries/ArduinoHttpClient/src/b64.h new file mode 100644 index 0000000..cdb1226 --- /dev/null +++ b/feather_sensor_lte/libraries/ArduinoHttpClient/src/b64.h @@ -0,0 +1,6 @@ +#ifndef b64_h +#define b64_h + +int b64_encode(const unsigned char* aInput, int aInputLen, unsigned char* aOutput, int aOutputLen); + +#endif diff --git a/feather_sensor_lte/libraries/DHT/.github/ISSUE_TEMPLATE.md b/feather_sensor_lte/libraries/DHT/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..f0e2614 --- /dev/null +++ b/feather_sensor_lte/libraries/DHT/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,46 @@ +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/feather_sensor_lte/libraries/DHT/.github/PULL_REQUEST_TEMPLATE.md b/feather_sensor_lte/libraries/DHT/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..7b641eb --- /dev/null +++ b/feather_sensor_lte/libraries/DHT/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,26 @@ +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/feather_sensor_lte/libraries/DHT/DHT.cpp b/feather_sensor_lte/libraries/DHT/DHT.cpp new file mode 100644 index 0000000..86ad91c --- /dev/null +++ b/feather_sensor_lte/libraries/DHT/DHT.cpp @@ -0,0 +1,259 @@ +/* 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/feather_sensor_lte/libraries/DHT/DHT.h b/feather_sensor_lte/libraries/DHT/DHT.h new file mode 100644 index 0000000..d81f6db --- /dev/null +++ b/feather_sensor_lte/libraries/DHT/DHT.h @@ -0,0 +1,75 @@ +/* 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/feather_sensor_lte/libraries/DHT/DHT_U.cpp b/feather_sensor_lte/libraries/DHT/DHT_U.cpp new file mode 100644 index 0000000..efc7963 --- /dev/null +++ b/feather_sensor_lte/libraries/DHT/DHT_U.cpp @@ -0,0 +1,179 @@ +// 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/feather_sensor_lte/libraries/DHT/DHT_U.h b/feather_sensor_lte/libraries/DHT/DHT_U.h new file mode 100644 index 0000000..d9ee709 --- /dev/null +++ b/feather_sensor_lte/libraries/DHT/DHT_U.h @@ -0,0 +1,78 @@ +// 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/feather_sensor_lte/libraries/DHT/README.md b/feather_sensor_lte/libraries/DHT/README.md new file mode 100644 index 0000000..d32afdc --- /dev/null +++ b/feather_sensor_lte/libraries/DHT/README.md @@ -0,0 +1,15 @@ +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/feather_sensor_lte/libraries/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino b/feather_sensor_lte/libraries/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino new file mode 100644 index 0000000..4820f2e --- /dev/null +++ b/feather_sensor_lte/libraries/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino @@ -0,0 +1,84 @@ +// 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/feather_sensor_lte/libraries/DHT/examples/DHTtester/DHTtester.ino b/feather_sensor_lte/libraries/DHT/examples/DHTtester/DHTtester.ino new file mode 100644 index 0000000..ae6c41a --- /dev/null +++ b/feather_sensor_lte/libraries/DHT/examples/DHTtester/DHTtester.ino @@ -0,0 +1,69 @@ +// 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/feather_sensor_lte/libraries/DHT/keywords.txt b/feather_sensor_lte/libraries/DHT/keywords.txt new file mode 100644 index 0000000..146d4fa --- /dev/null +++ b/feather_sensor_lte/libraries/DHT/keywords.txt @@ -0,0 +1,22 @@ +########################################### +# 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/feather_sensor_lte/libraries/DHT/library.properties b/feather_sensor_lte/libraries/DHT/library.properties new file mode 100644 index 0000000..a54c1dc --- /dev/null +++ b/feather_sensor_lte/libraries/DHT/library.properties @@ -0,0 +1,9 @@ +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/feather_sensor_lte/libraries/RTClib/.github/ISSUE_TEMPLATE.md b/feather_sensor_lte/libraries/RTClib/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..f0e2614 --- /dev/null +++ b/feather_sensor_lte/libraries/RTClib/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,46 @@ +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/feather_sensor_lte/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md b/feather_sensor_lte/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..7b641eb --- /dev/null +++ b/feather_sensor_lte/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,26 @@ +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/feather_sensor_lte/libraries/RTClib/README.md b/feather_sensor_lte/libraries/RTClib/README.md new file mode 100644 index 0000000..661e18d --- /dev/null +++ b/feather_sensor_lte/libraries/RTClib/README.md @@ -0,0 +1,42 @@ +This is a fork of JeeLab's fantastic real time clock library for Arduino. + +For details on using this library with an RTC module like the DS1307, PCF8523, or DS3231, see the guide at: https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/overview + +To download. click the DOWNLOADS button to the right, and rename the uncompressed folder RTClib. + +Place the RTClib folder in your *arduinosketchfolder*/libraries/ folder. +You may need to create the libraries subfolder if its your first library. Restart the IDE. + +Please note that dayOfTheWeek() ranges from 0 to 6 inclusive with 0 being 'Sunday' + + + +## Compatibility + +MCU | Tested Works | Doesn't Work | Not Tested | Notes +------------------ | :----------: | :----------: | :---------: | ----- +Atmega328 @ 16MHz | X | | | +Atmega328 @ 12MHz | X | | | +Atmega32u4 @ 16MHz | X | | | Use SDA/SCL on pins D3 & D2 +Atmega32u4 @ 8MHz | X | | | Use SDA/SCL on pins D3 & D2 +ESP8266 | X | | | SDA/SCL default to pins 4 & 5 but any two pins can be assigned as SDA/SCL using Wire.begin(SDA,SCL) +Atmega2560 @ 16MHz | X | | | Use SDA/SCL on Pins 20 & 21 +ATSAM3X8E | X | | | Use SDA1 and SCL1 +ATSAM21D | X | | | +ATtiny85 @ 16MHz | X | | | +ATtiny85 @ 8MHz | X | | | +Intel Curie @ 32MHz | | | X | +STM32F2 | | | X | + + * ATmega328 @ 16MHz : Arduino UNO, Adafruit Pro Trinket 5V, Adafruit Metro 328, Adafruit Metro Mini + * ATmega328 @ 12MHz : Adafruit Pro Trinket 3V + * ATmega32u4 @ 16MHz : Arduino Leonardo, Arduino Micro, Arduino Yun, Teensy 2.0 + * ATmega32u4 @ 8MHz : Adafruit Flora, Bluefruit Micro + * ESP8266 : Adafruit Huzzah + * ATmega2560 @ 16MHz : Arduino Mega + * ATSAM3X8E : Arduino Due + * ATSAM21D : Arduino Zero, M0 Pro + * ATtiny85 @ 16MHz : Adafruit Trinket 5V + * ATtiny85 @ 8MHz : Adafruit Gemma, Arduino Gemma, Adafruit Trinket 3V + + diff --git a/feather_sensor_lte/libraries/RTClib/RTClib.cpp b/feather_sensor_lte/libraries/RTClib/RTClib.cpp new file mode 100644 index 0000000..a08dfe9 --- /dev/null +++ b/feather_sensor_lte/libraries/RTClib/RTClib.cpp @@ -0,0 +1,506 @@ +// Code by JeeLabs http://news.jeelabs.org/code/ +// Released to the public domain! Enjoy! + +#include +#include "RTClib.h" +#ifdef __AVR__ + #include +#elif defined(ESP8266) + #include +#elif defined(ARDUINO_ARCH_SAMD) +// nothing special needed +#elif defined(ARDUINO_SAM_DUE) + #define PROGMEM + #define pgm_read_byte(addr) (*(const unsigned char *)(addr)) + #define Wire Wire1 +#endif + + + +#if (ARDUINO >= 100) + #include // capital A so it is error prone on case-sensitive filesystems + // Macro to deal with the difference in I2C write functions from old and new Arduino versions. + #define _I2C_WRITE write + #define _I2C_READ read +#else + #include + #define _I2C_WRITE send + #define _I2C_READ receive +#endif + + +static uint8_t read_i2c_register(uint8_t addr, uint8_t reg) { + Wire.beginTransmission(addr); + Wire._I2C_WRITE((byte)reg); + Wire.endTransmission(); + + Wire.requestFrom(addr, (byte)1); + return Wire._I2C_READ(); +} + +static void write_i2c_register(uint8_t addr, uint8_t reg, uint8_t val) { + Wire.beginTransmission(addr); + Wire._I2C_WRITE((byte)reg); + Wire._I2C_WRITE((byte)val); + Wire.endTransmission(); +} + + +//////////////////////////////////////////////////////////////////////////////// +// utility code, some of this could be exposed in the DateTime API if needed + +const uint8_t daysInMonth [] PROGMEM = { 31,28,31,30,31,30,31,31,30,31,30,31 }; + +// number of days since 2000/01/01, valid for 2001..2099 +static uint16_t date2days(uint16_t y, uint8_t m, uint8_t d) { + if (y >= 2000) + y -= 2000; + uint16_t days = d; + for (uint8_t i = 1; i < m; ++i) + days += pgm_read_byte(daysInMonth + i - 1); + if (m > 2 && y % 4 == 0) + ++days; + return days + 365 * y + (y + 3) / 4 - 1; +} + +static long time2long(uint16_t days, uint8_t h, uint8_t m, uint8_t s) { + return ((days * 24L + h) * 60 + m) * 60 + s; +} + +//////////////////////////////////////////////////////////////////////////////// +// DateTime implementation - ignores time zones and DST changes +// NOTE: also ignores leap seconds, see http://en.wikipedia.org/wiki/Leap_second + +DateTime::DateTime (uint32_t t) { + t -= SECONDS_FROM_1970_TO_2000; // bring to 2000 timestamp from 1970 + + ss = t % 60; + t /= 60; + mm = t % 60; + t /= 60; + hh = t % 24; + uint16_t days = t / 24; + uint8_t leap; + for (yOff = 0; ; ++yOff) { + leap = yOff % 4 == 0; + if (days < 365 + leap) + break; + days -= 365 + leap; + } + for (m = 1; ; ++m) { + uint8_t daysPerMonth = pgm_read_byte(daysInMonth + m - 1); + if (leap && m == 2) + ++daysPerMonth; + if (days < daysPerMonth) + break; + days -= daysPerMonth; + } + d = days + 1; +} + +DateTime::DateTime (uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t min, uint8_t sec) { + if (year >= 2000) + year -= 2000; + yOff = year; + m = month; + d = day; + hh = hour; + mm = min; + ss = sec; +} + +DateTime::DateTime (const DateTime& copy): + yOff(copy.yOff), + m(copy.m), + d(copy.d), + hh(copy.hh), + mm(copy.mm), + ss(copy.ss) +{} + +static uint8_t conv2d(const char* p) { + uint8_t v = 0; + if ('0' <= *p && *p <= '9') + v = *p - '0'; + return 10 * v + *++p - '0'; +} + +// A convenient constructor for using "the compiler's time": +// DateTime now (__DATE__, __TIME__); +// NOTE: using F() would further reduce the RAM footprint, see below. +DateTime::DateTime (const char* date, const char* time) { + // sample input: date = "Dec 26 2009", time = "12:34:56" + yOff = conv2d(date + 9); + // Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec + switch (date[0]) { + case 'J': m = (date[1] == 'a') ? 1 : ((date[2] == 'n') ? 6 : 7); break; + case 'F': m = 2; break; + case 'A': m = date[2] == 'r' ? 4 : 8; break; + case 'M': m = date[2] == 'r' ? 3 : 5; break; + case 'S': m = 9; break; + case 'O': m = 10; break; + case 'N': m = 11; break; + case 'D': m = 12; break; + } + d = conv2d(date + 4); + hh = conv2d(time); + mm = conv2d(time + 3); + ss = conv2d(time + 6); +} + +// A convenient constructor for using "the compiler's time": +// This version will save RAM by using PROGMEM to store it by using the F macro. +// DateTime now (F(__DATE__), F(__TIME__)); +DateTime::DateTime (const __FlashStringHelper* date, const __FlashStringHelper* time) { + // sample input: date = "Dec 26 2009", time = "12:34:56" + char buff[11]; + memcpy_P(buff, date, 11); + yOff = conv2d(buff + 9); + // Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec + switch (buff[0]) { + case 'J': m = (buff[1] == 'a') ? 1 : ((buff[2] == 'n') ? 6 : 7); break; + case 'F': m = 2; break; + case 'A': m = buff[2] == 'r' ? 4 : 8; break; + case 'M': m = buff[2] == 'r' ? 3 : 5; break; + case 'S': m = 9; break; + case 'O': m = 10; break; + case 'N': m = 11; break; + case 'D': m = 12; break; + } + d = conv2d(buff + 4); + memcpy_P(buff, time, 8); + hh = conv2d(buff); + mm = conv2d(buff + 3); + ss = conv2d(buff + 6); +} + +uint8_t DateTime::dayOfTheWeek() const { + uint16_t day = date2days(yOff, m, d); + return (day + 6) % 7; // Jan 1, 2000 is a Saturday, i.e. returns 6 +} + +uint32_t DateTime::unixtime(void) const { + uint32_t t; + uint16_t days = date2days(yOff, m, d); + t = time2long(days, hh, mm, ss); + t += SECONDS_FROM_1970_TO_2000; // seconds from 1970 to 2000 + + return t; +} + +long DateTime::secondstime(void) const { + long t; + uint16_t days = date2days(yOff, m, d); + t = time2long(days, hh, mm, ss); + return t; +} + +DateTime DateTime::operator+(const TimeSpan& span) { + return DateTime(unixtime()+span.totalseconds()); +} + +DateTime DateTime::operator-(const TimeSpan& span) { + return DateTime(unixtime()-span.totalseconds()); +} + +TimeSpan DateTime::operator-(const DateTime& right) { + return TimeSpan(unixtime()-right.unixtime()); +} + +//////////////////////////////////////////////////////////////////////////////// +// TimeSpan implementation + +TimeSpan::TimeSpan (int32_t seconds): + _seconds(seconds) +{} + +TimeSpan::TimeSpan (int16_t days, int8_t hours, int8_t minutes, int8_t seconds): + _seconds((int32_t)days*86400L + (int32_t)hours*3600 + (int32_t)minutes*60 + seconds) +{} + +TimeSpan::TimeSpan (const TimeSpan& copy): + _seconds(copy._seconds) +{} + +TimeSpan TimeSpan::operator+(const TimeSpan& right) { + return TimeSpan(_seconds+right._seconds); +} + +TimeSpan TimeSpan::operator-(const TimeSpan& right) { + return TimeSpan(_seconds-right._seconds); +} + +//////////////////////////////////////////////////////////////////////////////// +// RTC_DS1307 implementation + +static uint8_t bcd2bin (uint8_t val) { return val - 6 * (val >> 4); } +static uint8_t bin2bcd (uint8_t val) { return val + 6 * (val / 10); } + +boolean RTC_DS1307::begin(void) { + Wire.begin(); + return true; +} + +uint8_t RTC_DS1307::isrunning(void) { + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE((byte)0); + Wire.endTransmission(); + + Wire.requestFrom(DS1307_ADDRESS, 1); + uint8_t ss = Wire._I2C_READ(); + return !(ss>>7); +} + +void RTC_DS1307::adjust(const DateTime& dt) { + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE((byte)0); // start at location 0 + Wire._I2C_WRITE(bin2bcd(dt.second())); + Wire._I2C_WRITE(bin2bcd(dt.minute())); + Wire._I2C_WRITE(bin2bcd(dt.hour())); + Wire._I2C_WRITE(bin2bcd(0)); + Wire._I2C_WRITE(bin2bcd(dt.day())); + Wire._I2C_WRITE(bin2bcd(dt.month())); + Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); + Wire.endTransmission(); +} + +DateTime RTC_DS1307::now() { + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE((byte)0); + Wire.endTransmission(); + + Wire.requestFrom(DS1307_ADDRESS, 7); + uint8_t ss = bcd2bin(Wire._I2C_READ() & 0x7F); + uint8_t mm = bcd2bin(Wire._I2C_READ()); + uint8_t hh = bcd2bin(Wire._I2C_READ()); + Wire._I2C_READ(); + uint8_t d = bcd2bin(Wire._I2C_READ()); + uint8_t m = bcd2bin(Wire._I2C_READ()); + uint16_t y = bcd2bin(Wire._I2C_READ()) + 2000; + + return DateTime (y, m, d, hh, mm, ss); +} + +Ds1307SqwPinMode RTC_DS1307::readSqwPinMode() { + int mode; + + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE(DS1307_CONTROL); + Wire.endTransmission(); + + Wire.requestFrom((uint8_t)DS1307_ADDRESS, (uint8_t)1); + mode = Wire._I2C_READ(); + + mode &= 0x93; + return static_cast(mode); +} + +void RTC_DS1307::writeSqwPinMode(Ds1307SqwPinMode mode) { + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE(DS1307_CONTROL); + Wire._I2C_WRITE(mode); + Wire.endTransmission(); +} + +void RTC_DS1307::readnvram(uint8_t* buf, uint8_t size, uint8_t address) { + int addrByte = DS1307_NVRAM + address; + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE(addrByte); + Wire.endTransmission(); + + Wire.requestFrom((uint8_t) DS1307_ADDRESS, size); + for (uint8_t pos = 0; pos < size; ++pos) { + buf[pos] = Wire._I2C_READ(); + } +} + +void RTC_DS1307::writenvram(uint8_t address, uint8_t* buf, uint8_t size) { + int addrByte = DS1307_NVRAM + address; + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE(addrByte); + for (uint8_t pos = 0; pos < size; ++pos) { + Wire._I2C_WRITE(buf[pos]); + } + Wire.endTransmission(); +} + +uint8_t RTC_DS1307::readnvram(uint8_t address) { + uint8_t data; + readnvram(&data, 1, address); + return data; +} + +void RTC_DS1307::writenvram(uint8_t address, uint8_t data) { + writenvram(address, &data, 1); +} + +//////////////////////////////////////////////////////////////////////////////// +// RTC_Millis implementation + +long RTC_Millis::offset = 0; + +void RTC_Millis::adjust(const DateTime& dt) { + offset = dt.unixtime() - millis() / 1000; +} + +DateTime RTC_Millis::now() { + return (uint32_t)(offset + millis() / 1000); +} + +//////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////////////// +// RTC_PCF8563 implementation + +boolean RTC_PCF8523::begin(void) { + Wire.begin(); + return true; +} + +boolean RTC_PCF8523::initialized(void) { + Wire.beginTransmission(PCF8523_ADDRESS); + Wire._I2C_WRITE((byte)PCF8523_CONTROL_3); + Wire.endTransmission(); + + Wire.requestFrom(PCF8523_ADDRESS, 1); + uint8_t ss = Wire._I2C_READ(); + return ((ss & 0xE0) != 0xE0); +} + +void RTC_PCF8523::adjust(const DateTime& dt) { + Wire.beginTransmission(PCF8523_ADDRESS); + Wire._I2C_WRITE((byte)3); // start at location 3 + Wire._I2C_WRITE(bin2bcd(dt.second())); + Wire._I2C_WRITE(bin2bcd(dt.minute())); + Wire._I2C_WRITE(bin2bcd(dt.hour())); + Wire._I2C_WRITE(bin2bcd(dt.day())); + Wire._I2C_WRITE(bin2bcd(0)); // skip weekdays + Wire._I2C_WRITE(bin2bcd(dt.month())); + Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); + Wire.endTransmission(); + + // set to battery switchover mode + Wire.beginTransmission(PCF8523_ADDRESS); + Wire._I2C_WRITE((byte)PCF8523_CONTROL_3); + Wire._I2C_WRITE((byte)0x00); + Wire.endTransmission(); +} + +DateTime RTC_PCF8523::now() { + Wire.beginTransmission(PCF8523_ADDRESS); + Wire._I2C_WRITE((byte)3); + Wire.endTransmission(); + + Wire.requestFrom(PCF8523_ADDRESS, 7); + uint8_t ss = bcd2bin(Wire._I2C_READ() & 0x7F); + uint8_t mm = bcd2bin(Wire._I2C_READ()); + uint8_t hh = bcd2bin(Wire._I2C_READ()); + uint8_t d = bcd2bin(Wire._I2C_READ()); + Wire._I2C_READ(); // skip 'weekdays' + uint8_t m = bcd2bin(Wire._I2C_READ()); + uint16_t y = bcd2bin(Wire._I2C_READ()) + 2000; + + return DateTime (y, m, d, hh, mm, ss); +} + +Pcf8523SqwPinMode RTC_PCF8523::readSqwPinMode() { + int mode; + + Wire.beginTransmission(PCF8523_ADDRESS); + Wire._I2C_WRITE(PCF8523_CLKOUTCONTROL); + Wire.endTransmission(); + + Wire.requestFrom((uint8_t)PCF8523_ADDRESS, (uint8_t)1); + mode = Wire._I2C_READ(); + + mode >>= 3; + mode &= 0x7; + return static_cast(mode); +} + +void RTC_PCF8523::writeSqwPinMode(Pcf8523SqwPinMode mode) { + Wire.beginTransmission(PCF8523_ADDRESS); + Wire._I2C_WRITE(PCF8523_CLKOUTCONTROL); + Wire._I2C_WRITE(mode << 3); + Wire.endTransmission(); +} + + + + +//////////////////////////////////////////////////////////////////////////////// +// RTC_DS3231 implementation + +boolean RTC_DS3231::begin(void) { + Wire.begin(); + return true; +} + +bool RTC_DS3231::lostPower(void) { + return (read_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG) >> 7); +} + +void RTC_DS3231::adjust(const DateTime& dt) { + Wire.beginTransmission(DS3231_ADDRESS); + Wire._I2C_WRITE((byte)0); // start at location 0 + Wire._I2C_WRITE(bin2bcd(dt.second())); + Wire._I2C_WRITE(bin2bcd(dt.minute())); + Wire._I2C_WRITE(bin2bcd(dt.hour())); + Wire._I2C_WRITE(bin2bcd(0)); + Wire._I2C_WRITE(bin2bcd(dt.day())); + Wire._I2C_WRITE(bin2bcd(dt.month())); + Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); + Wire.endTransmission(); + + uint8_t statreg = read_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG); + statreg &= ~0x80; // flip OSF bit + write_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG, statreg); +} + +DateTime RTC_DS3231::now() { + Wire.beginTransmission(DS3231_ADDRESS); + Wire._I2C_WRITE((byte)0); + Wire.endTransmission(); + + Wire.requestFrom(DS3231_ADDRESS, 7); + uint8_t ss = bcd2bin(Wire._I2C_READ() & 0x7F); + uint8_t mm = bcd2bin(Wire._I2C_READ()); + uint8_t hh = bcd2bin(Wire._I2C_READ()); + Wire._I2C_READ(); + uint8_t d = bcd2bin(Wire._I2C_READ()); + uint8_t m = bcd2bin(Wire._I2C_READ()); + uint16_t y = bcd2bin(Wire._I2C_READ()) + 2000; + + return DateTime (y, m, d, hh, mm, ss); +} + +Ds3231SqwPinMode RTC_DS3231::readSqwPinMode() { + int mode; + + Wire.beginTransmission(DS3231_ADDRESS); + Wire._I2C_WRITE(DS3231_CONTROL); + Wire.endTransmission(); + + Wire.requestFrom((uint8_t)DS3231_ADDRESS, (uint8_t)1); + mode = Wire._I2C_READ(); + + mode &= 0x93; + return static_cast(mode); +} + +void RTC_DS3231::writeSqwPinMode(Ds3231SqwPinMode mode) { + uint8_t ctrl; + ctrl = read_i2c_register(DS3231_ADDRESS, DS3231_CONTROL); + + ctrl &= ~0x04; // turn off INTCON + ctrl &= ~0x18; // set freq bits to 0 + + if (mode == DS3231_OFF) { + ctrl |= 0x04; // turn on INTCN + } else { + ctrl |= mode; + } + write_i2c_register(DS3231_ADDRESS, DS3231_CONTROL, ctrl); + + //Serial.println( read_i2c_register(DS3231_ADDRESS, DS3231_CONTROL), HEX); +} diff --git a/feather_sensor_lte/libraries/RTClib/RTClib.h b/feather_sensor_lte/libraries/RTClib/RTClib.h new file mode 100644 index 0000000..abf5d9b --- /dev/null +++ b/feather_sensor_lte/libraries/RTClib/RTClib.h @@ -0,0 +1,135 @@ +// Code by JeeLabs http://news.jeelabs.org/code/ +// Released to the public domain! Enjoy! + +#ifndef _RTCLIB_H_ +#define _RTCLIB_H_ + +#include +class TimeSpan; + + +#define PCF8523_ADDRESS 0x68 +#define PCF8523_CLKOUTCONTROL 0x0F +#define PCF8523_CONTROL_3 0x02 + +#define DS1307_ADDRESS 0x68 +#define DS1307_CONTROL 0x07 +#define DS1307_NVRAM 0x08 + +#define DS3231_ADDRESS 0x68 +#define DS3231_CONTROL 0x0E +#define DS3231_STATUSREG 0x0F + +#define SECONDS_PER_DAY 86400L + +#define SECONDS_FROM_1970_TO_2000 946684800 + + + +// Simple general-purpose date/time class (no TZ / DST / leap second handling!) +class DateTime { +public: + DateTime (uint32_t t =0); + DateTime (uint16_t year, uint8_t month, uint8_t day, + uint8_t hour =0, uint8_t min =0, uint8_t sec =0); + DateTime (const DateTime& copy); + DateTime (const char* date, const char* time); + DateTime (const __FlashStringHelper* date, const __FlashStringHelper* time); + uint16_t year() const { return 2000 + yOff; } + uint8_t month() const { return m; } + uint8_t day() const { return d; } + uint8_t hour() const { return hh; } + uint8_t minute() const { return mm; } + uint8_t second() const { return ss; } + uint8_t dayOfTheWeek() const; + + // 32-bit times as seconds since 1/1/2000 + long secondstime() const; + // 32-bit times as seconds since 1/1/1970 + uint32_t unixtime(void) const; + + DateTime operator+(const TimeSpan& span); + DateTime operator-(const TimeSpan& span); + TimeSpan operator-(const DateTime& right); + +protected: + uint8_t yOff, m, d, hh, mm, ss; +}; + +// Timespan which can represent changes in time with seconds accuracy. +class TimeSpan { +public: + TimeSpan (int32_t seconds = 0); + TimeSpan (int16_t days, int8_t hours, int8_t minutes, int8_t seconds); + TimeSpan (const TimeSpan& copy); + int16_t days() const { return _seconds / 86400L; } + int8_t hours() const { return _seconds / 3600 % 24; } + int8_t minutes() const { return _seconds / 60 % 60; } + int8_t seconds() const { return _seconds % 60; } + int32_t totalseconds() const { return _seconds; } + + TimeSpan operator+(const TimeSpan& right); + TimeSpan operator-(const TimeSpan& right); + +protected: + int32_t _seconds; +}; + +// RTC based on the DS1307 chip connected via I2C and the Wire library +enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 }; + +class RTC_DS1307 { +public: + boolean begin(void); + static void adjust(const DateTime& dt); + uint8_t isrunning(void); + static DateTime now(); + static Ds1307SqwPinMode readSqwPinMode(); + static void writeSqwPinMode(Ds1307SqwPinMode mode); + uint8_t readnvram(uint8_t address); + void readnvram(uint8_t* buf, uint8_t size, uint8_t address); + void writenvram(uint8_t address, uint8_t data); + void writenvram(uint8_t address, uint8_t* buf, uint8_t size); +}; + +// RTC based on the DS3231 chip connected via I2C and the Wire library +enum Ds3231SqwPinMode { DS3231_OFF = 0x01, DS3231_SquareWave1Hz = 0x00, DS3231_SquareWave1kHz = 0x08, DS3231_SquareWave4kHz = 0x10, DS3231_SquareWave8kHz = 0x18 }; + +class RTC_DS3231 { +public: + boolean begin(void); + static void adjust(const DateTime& dt); + bool lostPower(void); + static DateTime now(); + static Ds3231SqwPinMode readSqwPinMode(); + static void writeSqwPinMode(Ds3231SqwPinMode mode); +}; + + +// RTC based on the PCF8523 chip connected via I2C and the Wire library +enum Pcf8523SqwPinMode { PCF8523_OFF = 7, PCF8523_SquareWave1HZ = 6, PCF8523_SquareWave32HZ = 5, PCF8523_SquareWave1kHz = 4, PCF8523_SquareWave4kHz = 3, PCF8523_SquareWave8kHz = 2, PCF8523_SquareWave16kHz = 1, PCF8523_SquareWave32kHz = 0 }; + +class RTC_PCF8523 { +public: + boolean begin(void); + void adjust(const DateTime& dt); + boolean initialized(void); + static DateTime now(); + + Pcf8523SqwPinMode readSqwPinMode(); + void writeSqwPinMode(Pcf8523SqwPinMode mode); +}; + +// RTC using the internal millis() clock, has to be initialized before use +// NOTE: this clock won't be correct once the millis() timer rolls over (>49d?) +class RTC_Millis { +public: + static void begin(const DateTime& dt) { adjust(dt); } + static void adjust(const DateTime& dt); + static DateTime now(); + +protected: + static long offset; +}; + +#endif // _RTCLIB_H_ diff --git a/feather_sensor_lte/libraries/RTClib/examples/datecalc/datecalc.ino b/feather_sensor_lte/libraries/RTClib/examples/datecalc/datecalc.ino new file mode 100644 index 0000000..771dacd --- /dev/null +++ b/feather_sensor_lte/libraries/RTClib/examples/datecalc/datecalc.ino @@ -0,0 +1,111 @@ +// Simple date conversions and calculations + +#include +#include "RTClib.h" + +#if defined(ARDUINO_ARCH_SAMD) +// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! + #define Serial SerialUSB +#endif + +void showDate(const char* txt, const DateTime& dt) { + Serial.print(txt); + Serial.print(' '); + Serial.print(dt.year(), DEC); + Serial.print('/'); + Serial.print(dt.month(), DEC); + Serial.print('/'); + Serial.print(dt.day(), DEC); + Serial.print(' '); + Serial.print(dt.hour(), DEC); + Serial.print(':'); + Serial.print(dt.minute(), DEC); + Serial.print(':'); + Serial.print(dt.second(), DEC); + + Serial.print(" = "); + Serial.print(dt.unixtime()); + Serial.print("s / "); + Serial.print(dt.unixtime() / 86400L); + Serial.print("d since 1970"); + + Serial.println(); +} + +void showTimeSpan(const char* txt, const TimeSpan& ts) { + Serial.print(txt); + Serial.print(" "); + Serial.print(ts.days(), DEC); + Serial.print(" days "); + Serial.print(ts.hours(), DEC); + Serial.print(" hours "); + Serial.print(ts.minutes(), DEC); + Serial.print(" minutes "); + Serial.print(ts.seconds(), DEC); + Serial.print(" seconds ("); + Serial.print(ts.totalseconds(), DEC); + Serial.print(" total seconds)"); + Serial.println(); +} + +void setup () { + +#ifndef ESP8266 + while (!Serial); // for Leonardo/Micro/Zero +#endif + Serial.begin(57600); + + DateTime dt0 (0, 1, 1, 0, 0, 0); + showDate("dt0", dt0); + + DateTime dt1 (1, 1, 1, 0, 0, 0); + showDate("dt1", dt1); + + DateTime dt2 (2009, 1, 1, 0, 0, 0); + showDate("dt2", dt2); + + DateTime dt3 (2009, 1, 2, 0, 0, 0); + showDate("dt3", dt3); + + DateTime dt4 (2009, 1, 27, 0, 0, 0); + showDate("dt4", dt4); + + DateTime dt5 (2009, 2, 27, 0, 0, 0); + showDate("dt5", dt5); + + DateTime dt6 (2009, 12, 27, 0, 0, 0); + showDate("dt6", dt6); + + DateTime dt7 (dt6.unixtime() + 3600); // One hour later. + showDate("dt7", dt7); + + DateTime dt75 = dt6 + TimeSpan(0, 1, 0, 0); // One hour later with TimeSpan addition. + showDate("dt7.5", dt75); + + DateTime dt8 (dt6.unixtime() + 86400L); // One day later. + showDate("dt8", dt8); + + DateTime dt85 = dt6 + TimeSpan(1, 0, 0, 0); // One day later with TimeSpan addition. + showDate("dt8.5", dt85); + + DateTime dt9 (dt6.unixtime() + 7 * 86400L); // One week later. + showDate("dt9", dt9); + + DateTime dt95 = dt6 + TimeSpan(7, 0, 0, 0); // One week later with TimeSpan addition. + showDate("dt9.5", dt95); + + DateTime dt10 = dt6 + TimeSpan(0, 0, 42, 42); // Fourty two minutes and fourty two seconds later. + showDate("dt10", dt10); + + DateTime dt11 = dt6 - TimeSpan(7, 0, 0, 0); // One week ago. + showDate("dt11", dt11); + + TimeSpan ts1 = dt6 - dt5; + showTimeSpan("dt6-dt5", ts1); + + TimeSpan ts2 = dt10 - dt6; + showTimeSpan("dt10-dt6", ts2); +} + +void loop () { +} diff --git a/feather_sensor_lte/libraries/RTClib/examples/ds1307/ds1307.ino b/feather_sensor_lte/libraries/RTClib/examples/ds1307/ds1307.ino new file mode 100644 index 0000000..7d9162f --- /dev/null +++ b/feather_sensor_lte/libraries/RTClib/examples/ds1307/ds1307.ino @@ -0,0 +1,71 @@ +// Date and time functions using a DS1307 RTC connected via I2C and Wire lib +#include +#include "RTClib.h" + +RTC_DS1307 rtc; + +char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; + +void setup () { + while (!Serial); // for Leonardo/Micro/Zero + + Serial.begin(57600); + if (! rtc.begin()) { + Serial.println("Couldn't find RTC"); + while (1); + } + + if (! rtc.isrunning()) { + Serial.println("RTC is NOT running!"); + // following line sets the RTC to the date & time this sketch was compiled + // rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); + // This line sets the RTC with an explicit date & time, for example to set + // January 21, 2014 at 3am you would call: + // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); + } +} + +void loop () { + DateTime now = rtc.now(); + + Serial.print(now.year(), DEC); + Serial.print('/'); + Serial.print(now.month(), DEC); + Serial.print('/'); + Serial.print(now.day(), DEC); + Serial.print(" ("); + Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); + Serial.print(") "); + Serial.print(now.hour(), DEC); + Serial.print(':'); + Serial.print(now.minute(), DEC); + Serial.print(':'); + Serial.print(now.second(), DEC); + Serial.println(); + + Serial.print(" since midnight 1/1/1970 = "); + Serial.print(now.unixtime()); + Serial.print("s = "); + Serial.print(now.unixtime() / 86400L); + Serial.println("d"); + + // calculate a date which is 7 days and 30 seconds into the future + DateTime future (now + TimeSpan(7,12,30,6)); + + Serial.print(" now + 7d + 30s: "); + Serial.print(future.year(), DEC); + Serial.print('/'); + Serial.print(future.month(), DEC); + Serial.print('/'); + Serial.print(future.day(), DEC); + Serial.print(' '); + Serial.print(future.hour(), DEC); + Serial.print(':'); + Serial.print(future.minute(), DEC); + Serial.print(':'); + Serial.print(future.second(), DEC); + Serial.println(); + + Serial.println(); + delay(3000); +} \ No newline at end of file diff --git a/feather_sensor_lte/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino b/feather_sensor_lte/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino new file mode 100644 index 0000000..c12c26c --- /dev/null +++ b/feather_sensor_lte/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino @@ -0,0 +1,68 @@ +// SQW/OUT pin mode using a DS1307 RTC connected via I2C. +// +// According to the data sheet (http://datasheets.maxim-ic.com/en/ds/DS1307.pdf), the +// DS1307's SQW/OUT pin can be set to low, high, 1Hz, 4.096kHz, 8.192kHz, or 32.768kHz. +// +// This sketch reads the state of the pin, then iterates through the possible values at +// 5 second intervals. +// + +// NOTE: +// You must connect a pull up resistor (~10kohm) from the SQW pin up to VCC. Without +// this pull up the wave output will not work! + +#include +#include "RTClib.h" + +#if defined(ARDUINO_ARCH_SAMD) +// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! + #define Serial SerialUSB +#endif + +RTC_DS1307 rtc; + +int mode_index = 0; + +Ds1307SqwPinMode modes[] = {OFF, ON, SquareWave1HZ, SquareWave4kHz, SquareWave8kHz, SquareWave32kHz}; + + +void print_mode() { + Ds1307SqwPinMode mode = rtc.readSqwPinMode(); + + Serial.print("Sqw Pin Mode: "); + switch(mode) { + case OFF: Serial.println("OFF"); break; + case ON: Serial.println("ON"); break; + case SquareWave1HZ: Serial.println("1Hz"); break; + case SquareWave4kHz: Serial.println("4.096kHz"); break; + case SquareWave8kHz: Serial.println("8.192kHz"); break; + case SquareWave32kHz: Serial.println("32.768kHz"); break; + default: Serial.println("UNKNOWN"); break; + } +} + +void setup () { + +#ifndef ESP8266 + while (!Serial); // for Leonardo/Micro/Zero +#endif + + Serial.begin(57600); + if (! rtc.begin()) { + Serial.println("Couldn't find RTC"); + while (1); + } + + print_mode(); +} + +void loop () { + rtc.writeSqwPinMode(modes[mode_index++]); + print_mode(); + + if (mode_index > 5) { + mode_index = 0; + } + + delay(5000); +} diff --git a/feather_sensor_lte/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino b/feather_sensor_lte/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino new file mode 100644 index 0000000..0acd0cf --- /dev/null +++ b/feather_sensor_lte/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino @@ -0,0 +1,63 @@ +// Example of using the non-volatile RAM storage on the DS1307. +// You can write up to 56 bytes from address 0 to 55. +// Data will be persisted as long as the DS1307 has battery power. + +#include +#include "RTClib.h" + +#if defined(ARDUINO_ARCH_SAMD) +// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! + #define Serial SerialUSB +#endif + +RTC_DS1307 rtc; + +void printnvram(uint8_t address) { + Serial.print("Address 0x"); + Serial.print(address, HEX); + Serial.print(" = 0x"); + Serial.println(rtc.readnvram(address), HEX); +} + +void setup () { + +#ifndef ESP8266 + while (!Serial); // for Leonardo/Micro/Zero +#endif + Serial.begin(57600); + rtc.begin(); + + // Print old RAM contents on startup. + Serial.println("Current NVRAM values:"); + for (int i = 0; i < 6; ++i) { + printnvram(i); + } + + // Write some bytes to non-volatile RAM storage. + // NOTE: You can only read and write from addresses 0 to 55 (i.e. 56 byte values). + Serial.println("Writing NVRAM values."); + // Example writing one byte at a time: + rtc.writenvram(0, 0xFE); + rtc.writenvram(1, 0xED); + // Example writing multiple bytes: + uint8_t writeData[4] = { 0xBE, 0xEF, 0x01, 0x02 }; + rtc.writenvram(2, writeData, 4); + + // Read bytes from non-volatile RAM storage. + Serial.println("Reading NVRAM values:"); + // Example reading one byte at a time. + Serial.println(rtc.readnvram(0), HEX); + Serial.println(rtc.readnvram(1), HEX); + // Example reading multiple bytes: + uint8_t readData[4] = {0}; + rtc.readnvram(readData, 4, 2); + Serial.println(readData[0], HEX); + Serial.println(readData[1], HEX); + Serial.println(readData[2], HEX); + Serial.println(readData[3], HEX); + +} + +void loop () { + // Do nothing in the loop. +} diff --git a/feather_sensor_lte/libraries/RTClib/examples/ds3231/ds3231.ino b/feather_sensor_lte/libraries/RTClib/examples/ds3231/ds3231.ino new file mode 100644 index 0000000..b62d510 --- /dev/null +++ b/feather_sensor_lte/libraries/RTClib/examples/ds3231/ds3231.ino @@ -0,0 +1,77 @@ +// Date and time functions using a DS3231 RTC connected via I2C and Wire lib +#include +#include "RTClib.h" + +RTC_DS3231 rtc; + +char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; + +void setup () { + +#ifndef ESP8266 + while (!Serial); // for Leonardo/Micro/Zero +#endif + + Serial.begin(9600); + + delay(3000); // wait for console opening + + if (! rtc.begin()) { + Serial.println("Couldn't find RTC"); + while (1); + } + + if (rtc.lostPower()) { + Serial.println("RTC lost power, lets set the time!"); + // following line sets the RTC to the date & time this sketch was compiled + rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); + // This line sets the RTC with an explicit date & time, for example to set + // January 21, 2014 at 3am you would call: + // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); + } +} + +void loop () { + DateTime now = rtc.now(); + + Serial.print(now.year(), DEC); + Serial.print('/'); + Serial.print(now.month(), DEC); + Serial.print('/'); + Serial.print(now.day(), DEC); + Serial.print(" ("); + Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); + Serial.print(") "); + Serial.print(now.hour(), DEC); + Serial.print(':'); + Serial.print(now.minute(), DEC); + Serial.print(':'); + Serial.print(now.second(), DEC); + Serial.println(); + + Serial.print(" since midnight 1/1/1970 = "); + Serial.print(now.unixtime()); + Serial.print("s = "); + Serial.print(now.unixtime() / 86400L); + Serial.println("d"); + + // calculate a date which is 7 days and 30 seconds into the future + DateTime future (now + TimeSpan(7,12,30,6)); + + Serial.print(" now + 7d + 30s: "); + Serial.print(future.year(), DEC); + Serial.print('/'); + Serial.print(future.month(), DEC); + Serial.print('/'); + Serial.print(future.day(), DEC); + Serial.print(' '); + Serial.print(future.hour(), DEC); + Serial.print(':'); + Serial.print(future.minute(), DEC); + Serial.print(':'); + Serial.print(future.second(), DEC); + Serial.println(); + + Serial.println(); + delay(3000); +} diff --git a/feather_sensor_lte/libraries/RTClib/examples/pcf8523/pcf8523.ino b/feather_sensor_lte/libraries/RTClib/examples/pcf8523/pcf8523.ino new file mode 100644 index 0000000..fc7dfe8 --- /dev/null +++ b/feather_sensor_lte/libraries/RTClib/examples/pcf8523/pcf8523.ino @@ -0,0 +1,74 @@ +// Date and time functions using a DS1307 RTC connected via I2C and Wire lib +#include +#include "RTClib.h" + +RTC_PCF8523 rtc; + +char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; + +void setup () { + + while (!Serial) { + delay(1); // for Leonardo/Micro/Zero + } + + Serial.begin(57600); + if (! rtc.begin()) { + Serial.println("Couldn't find RTC"); + while (1); + } + + if (! rtc.initialized()) { + Serial.println("RTC is NOT running!"); + // following line sets the RTC to the date & time this sketch was compiled + // rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); + // This line sets the RTC with an explicit date & time, for example to set + // January 21, 2014 at 3am you would call: + // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); + } +} + +void loop () { + DateTime now = rtc.now(); + + Serial.print(now.year(), DEC); + Serial.print('/'); + Serial.print(now.month(), DEC); + Serial.print('/'); + Serial.print(now.day(), DEC); + Serial.print(" ("); + Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); + Serial.print(") "); + Serial.print(now.hour(), DEC); + Serial.print(':'); + Serial.print(now.minute(), DEC); + Serial.print(':'); + Serial.print(now.second(), DEC); + Serial.println(); + + Serial.print(" since midnight 1/1/1970 = "); + Serial.print(now.unixtime()); + Serial.print("s = "); + Serial.print(now.unixtime() / 86400L); + Serial.println("d"); + + // calculate a date which is 7 days and 30 seconds into the future + DateTime future (now + TimeSpan(7,12,30,6)); + + Serial.print(" now + 7d + 30s: "); + Serial.print(future.year(), DEC); + Serial.print('/'); + Serial.print(future.month(), DEC); + Serial.print('/'); + Serial.print(future.day(), DEC); + Serial.print(' '); + Serial.print(future.hour(), DEC); + Serial.print(':'); + Serial.print(future.minute(), DEC); + Serial.print(':'); + Serial.print(future.second(), DEC); + Serial.println(); + + Serial.println(); + delay(3000); +} \ No newline at end of file diff --git a/feather_sensor_lte/libraries/RTClib/examples/softrtc/softrtc.ino b/feather_sensor_lte/libraries/RTClib/examples/softrtc/softrtc.ino new file mode 100644 index 0000000..80f1886 --- /dev/null +++ b/feather_sensor_lte/libraries/RTClib/examples/softrtc/softrtc.ino @@ -0,0 +1,61 @@ +// Date and time functions using just software, based on millis() & timer + +#include +#include // this #include still required because the RTClib depends on it +#include "RTClib.h" + +#if defined(ARDUINO_ARCH_SAMD) +// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! + #define Serial SerialUSB +#endif + +RTC_Millis rtc; + +void setup () { + Serial.begin(57600); + // following line sets the RTC to the date & time this sketch was compiled + rtc.begin(DateTime(F(__DATE__), F(__TIME__))); + // This line sets the RTC with an explicit date & time, for example to set + // January 21, 2014 at 3am you would call: + // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); +} + +void loop () { + DateTime now = rtc.now(); + + Serial.print(now.year(), DEC); + Serial.print('/'); + Serial.print(now.month(), DEC); + Serial.print('/'); + Serial.print(now.day(), DEC); + Serial.print(' '); + Serial.print(now.hour(), DEC); + Serial.print(':'); + Serial.print(now.minute(), DEC); + Serial.print(':'); + Serial.print(now.second(), DEC); + Serial.println(); + + Serial.print(" seconds since 1970: "); + Serial.println(now.unixtime()); + + // calculate a date which is 7 days and 30 seconds into the future + DateTime future (now.unixtime() + 7 * 86400L + 30); + + Serial.print(" now + 7d + 30s: "); + Serial.print(future.year(), DEC); + Serial.print('/'); + Serial.print(future.month(), DEC); + Serial.print('/'); + Serial.print(future.day(), DEC); + Serial.print(' '); + Serial.print(future.hour(), DEC); + Serial.print(':'); + Serial.print(future.minute(), DEC); + Serial.print(':'); + Serial.print(future.second(), DEC); + Serial.println(); + + Serial.println(); + delay(3000); +} diff --git a/feather_sensor_lte/libraries/RTClib/keywords.txt b/feather_sensor_lte/libraries/RTClib/keywords.txt new file mode 100644 index 0000000..26cdc1e --- /dev/null +++ b/feather_sensor_lte/libraries/RTClib/keywords.txt @@ -0,0 +1,37 @@ +####################################### +# Syntax Coloring Map For RTC +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +DateTime KEYWORD1 +RTC_DS1307 KEYWORD1 +RTC_Millis KEYWORD1 +Ds1307SqwPinMode KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +year KEYWORD2 +month KEYWORD2 +day KEYWORD2 +hour KEYWORD2 +minute KEYWORD2 +second KEYWORD2 +dayOfWeek KEYWORD2 +secondstime KEYWORD2 +unixtime KEYWORD2 +begin KEYWORD2 +adjust KEYWORD2 +isrunning KEYWORD2 +now KEYWORD2 +readSqwPinMode KEYWORD2 +writeSqwPinMode KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + diff --git a/feather_sensor_lte/libraries/RTClib/library.properties b/feather_sensor_lte/libraries/RTClib/library.properties new file mode 100644 index 0000000..13d6177 --- /dev/null +++ b/feather_sensor_lte/libraries/RTClib/library.properties @@ -0,0 +1,9 @@ +name=RTClib +version=1.2.1 +author=Adafruit +maintainer=Adafruit +sentence=A fork of Jeelab's fantastic RTC library +paragraph=A fork of Jeelab's fantastic RTC library +category=Timing +url=https://github.com/adafruit/RTClib +architectures=* diff --git a/feather_sensor_lte/libraries/WiFi101/.travis.yml b/feather_sensor_lte/libraries/WiFi101/.travis.yml new file mode 100644 index 0000000..465c761 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/.travis.yml @@ -0,0 +1,48 @@ +language: generic +env: + global: + - IDE_VERSION=1.8.2 + matrix: + - BOARD="arduino:avr:uno" + - BOARD="arduino:avr:mega:cpu=atmega2560" + - BOARD="arduino:sam:arduino_due_x_dbg" + - BOARD="arduino:samd:arduino_zero_edbg" + - BOARD="arduino:samd:mkr1000" + - BOARD="Intel:arc32:arduino_101" +before_install: + - wget http://downloads.arduino.cc/arduino-$IDE_VERSION-linux64.tar.xz + - tar xf arduino-$IDE_VERSION-linux64.tar.xz + - mv arduino-$IDE_VERSION $HOME/arduino-ide + - export PATH=$PATH:$HOME/arduino-ide + - if [[ "$BOARD" =~ "arduino:sam:" ]]; then + arduino --install-boards arduino:sam; + fi + - if [[ "$BOARD" =~ "arduino:samd:" ]]; then + arduino --install-boards arduino:samd; + fi + - if [[ "$BOARD" =~ "Intel:arc32" ]]; then + arduino --install-boards Intel:arc32; + fi + - buildExampleSketch() { arduino --verbose-build --verify --board $BOARD $PWD/examples/$1/$1.ino; } +install: + - mkdir -p $HOME/Arduino/libraries + - ln -s $PWD $HOME/Arduino/libraries/. +script: + - buildExampleSketch AP_SimpleWebServer + - buildExampleSketch CheckWifi101FirmwareVersion + - buildExampleSketch ConnectNoEncryption + - buildExampleSketch ConnectWithWEP + - buildExampleSketch ConnectWithWPA + - buildExampleSketch FirmwareUpdater + - buildExampleSketch MDNS_WiFiWebServer + - buildExampleSketch ScanNetworks + - buildExampleSketch SimpleWebServerWiFi + - buildExampleSketch WiFiChatServer + - buildExampleSketch WiFiPing + - buildExampleSketch WiFiSSLClient + - buildExampleSketch WiFiUdpNtpClient + - buildExampleSketch WiFiUdpSendReceiveString + - buildExampleSketch WiFiWebClient + - buildExampleSketch WiFiWebClientRepeating + - buildExampleSketch WiFiWebServer + diff --git a/feather_sensor_lte/libraries/WiFi101/CHANGELOG b/feather_sensor_lte/libraries/WiFi101/CHANGELOG new file mode 100644 index 0000000..fbe1643 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/CHANGELOG @@ -0,0 +1,122 @@ +WiFi101 ?.?.? - ????.??.?? + +WiFi101 0.14.3 - 2017.06.01 + +* Fixed issues with WiFiMDNSResponder and large request packets +* Fixed issues with WiFiClient and sending data after the socket is closed + +WiFi101 0.14.2 - 2017.05.08 + +* Fixed issues with WiFiServer::write not working + +WiFi101 0.14.1 - 2017.04.20 + +* Fixed issues with WiFiMDNSResponder and Windows using Bonjour +* Correct cast of buffer size when processing received data + +WiFi101 0.14.0 - 2017.03.22 + +* Added support for firmware 19.5.2 +* Add ability to create Access Point with WPA security (f/w 19.5.2 or higher) +* Add WiFi.hostname(name) method to set custom host name for DHCP (f/w 19.5.2 or higher) +* Enables support for AES-256 Ciphers (f/w 19.5.2 or higher) +* Make provisioning mode backwards compatible with f/w 19.4.4 and older + +WiFi101 0.13.0 - 2017.03.01 + +* Added WiFi.channel() and WiFi.BSSID() + +WiFi101 0.12.1 - 2017.01.19 + +* Fixed tomorrow day issue in WiFi.getTime() + +WiFi101 0.12.0 - 2017.01.05 + +* Made provisioning mode easier and added example sketch +* Fixed WiFi.getTime() not returning 0, if time has not been synced via NTP +* Fixed crashing when connecting after scanning +* Fixed WiFiServer::available() returning valid client on outbound client connection +* Added WiFiUdp::beginMulticast(port) function for compatiblity with EthernetUdp, as beginMulti was inconsistent + +WiFi101 0.11.2 - 2016.12.15 + +* Fixed value of WiFi.getTime() being off by one day +* Fixed calling WiFi.RSSI() causing lockups + +WiFi101 0.11.1 - 2016.11.29 + +* Fixed regression for non-AVR boards that resulted in corrupt with data over than 1400 bytes was received + +WiFi101 0.11.0 - 2016.11.14 + +* Changed WiFi.ping(...) to return round trip time on success, negative value on error. Thanks @PKGeorgiev +* WiFi.end() now powers down the WiFi module +* WiFi.config(ip) can now be used to set a static IP for WiFi.begin(...) +* Fixed WiFi.BSSID(bssid) returning reversed MAC address +* Added WiFi.APClientMacAddress() API to get MAC address of AP client in AP mode +* Added WiFi.getTime() API to get epoch from NTP + +WiFi101 0.10.0 - 2016.09.08 + +* Added WiFi.end() to disconnect from the AP or end AP mode +* Added new WiFi.ping(...) functionality. Thanks @PKGeorgiev +* Added WiFi.setPins(...) to customize the CS, INTN, RESET and CHIPEN pins +* Add new WL_AP_LISTENING, WL_AP_CONNECTED, and WL_AP_FAILED status types for AP mode +* Fixed return value of WiFiUDP::beginPacket(host, port) when host is successfully resolved +* Added power management methods: WiFi.lowPowerMode(), WiFi.maxLowPowerMode(), WiFi.noLowPowerMode() +* Close TCP sockets when physical link is disconnected +* Fixed WiFi.RSSI() returning 0 when there was pending socket data + +WiFi101 0.9.1 - 2016.04.19 + +* Increased compatibility with 3rd party boards and architectures. +* Rename WiFiMdnsResponder.h/cpp to WiFiMDNSResponder.h/cpp +* Fixed buffering of UDP packet + +WiFi101 0.9.0 - 2016.03.21 + +* Fixed WiFi.status() hanging when shield is not present +* Fixed MAC address returning 00:00:00:00:00:00 with firmware version 19.3.0 +* Fixed SSL write functionality with firmware version 19.3.0 +* Fixed previous version of the library not working on the Uno and other boards that used PCINT's +* Added beginAP(...) API's to create access point with WEP passwords +* Fixed beginAP(...) channel off by one error +* Fixed WiFi.status() always returning WL_CONNECTED once connected, even if access point is disconnected later +* Added beginMulti API for Multicast UDP support +* Added WiFiMDNSResponder class and MDNS Web server example + +WiFi101 0.8.0 - 2016.02.15 + +* Added example for Access Point web server (thanks @ladyada) +* Fixed MAC Address printed in reverse order +* Allow another library to override PCINT ISR (fix issues when using the WiFi101 + library with other libraries like SoftwareSerial) + +WiFi101 0.7.0 - 2015.01.11 + +* Added support for WiFi Firmware 19.4.4 +* WiFi.hostByName(...) will not try resolve the domain name if it's already a numeric IP +* Fixed manual IP configuration (no DHCP) +* Fixed WiFiServer.available(), now follows API specification +* Fixed WEP key connection +* Fixed WiFiClient copy constructor and assignment operator. This improves stability when + Client objects are assigned or returned from functions. +* Control pins are now configurable through defines from variant. + +WiFi101 0.6.0 - 2015.11.27 + +* Fixed bug with AVR boards when Web Server is used +* Fixed UDP read bug on AVR Boards +* Added missing inlcude for SSL Client +* Fixed peek() function +* Fixed some examples + +WiFi101 0.5.1 - 2015.10.06 + +* Improved support for AVR Boards (Uno, Mega, Leonardo, etc.) and + ARM based boards (Due and Zero). + +WiFi101 0.5.0 - 2015.10.01 + +* Initial release + diff --git a/feather_sensor_lte/libraries/WiFi101/README.adoc b/feather_sensor_lte/libraries/WiFi101/README.adoc new file mode 100644 index 0000000..8eb6924 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/README.adoc @@ -0,0 +1,27 @@ += WiFi library for the Arduino WiFi Shield 101 and MKR1000 board = + +image:https://travis-ci.org/arduino-libraries/WiFi101.svg?branch=master["Build Status", link="https://travis-ci.org/arduino-libraries/WiFi101"] + +This library implements a network driver for devices based +on the ATMEL WINC1500 WiFi module. + +For more information about this library please visit us at +https://www.arduino.cc/en/Reference/WiFi101 + +== License == + +Copyright (c) Arduino LLC. All right reserved. + +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 2.1 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 Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA diff --git a/feather_sensor_lte/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino b/feather_sensor_lte/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino new file mode 100644 index 0000000..b5caf7a --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino @@ -0,0 +1,176 @@ +/* + WiFi Web Server LED Blink + + A simple web server that lets you blink an LED via the web. + This sketch will create a new access point (with no password). + It will then launch a new server and print out the IP address + to the Serial monitor. From there, you can open that address in a web browser + to turn on and off the LED on pin 13. + + If the IP address of your shield is yourAddress: + http://yourAddress/H turns the LED on + http://yourAddress/L turns it off + + created 25 Nov 2012 + by Tom Igoe + adapted to WiFi AP by Adafruit + */ + +#include +#include +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int led = LED_BUILTIN; +int status = WL_IDLE_STATUS; +WiFiServer server(80); + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + Serial.println("Access Point Web Server"); + + pinMode(led, OUTPUT); // set the LED pin mode + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue + while (true); + } + + // by default the local IP address of will be 192.168.1.1 + // you can override it with the following: + // WiFi.config(IPAddress(10, 0, 0, 1)); + + // print the network name (SSID); + Serial.print("Creating access point named: "); + Serial.println(ssid); + + // Create open network. Change this line if you want to create an WEP network: + status = WiFi.beginAP(ssid); + if (status != WL_AP_LISTENING) { + Serial.println("Creating access point failed"); + // don't continue + while (true); + } + + // wait 10 seconds for connection: + delay(10000); + + // start the web server on port 80 + server.begin(); + + // you're connected now, so print out the status + printWiFiStatus(); +} + + +void loop() { + // compare the previous status to the current status + if (status != WiFi.status()) { + // it has changed update the variable + status = WiFi.status(); + + if (status == WL_AP_CONNECTED) { + byte remoteMac[6]; + + // a device has connected to the AP + Serial.print("Device connected to AP, MAC address: "); + WiFi.APClientMacAddress(remoteMac); + Serial.print(remoteMac[5], HEX); + Serial.print(":"); + Serial.print(remoteMac[4], HEX); + Serial.print(":"); + Serial.print(remoteMac[3], HEX); + Serial.print(":"); + Serial.print(remoteMac[2], HEX); + Serial.print(":"); + Serial.print(remoteMac[1], HEX); + Serial.print(":"); + Serial.println(remoteMac[0], HEX); + } else { + // a device has disconnected from the AP, and we are back in listening mode + Serial.println("Device disconnected from AP"); + } + } + + WiFiClient client = server.available(); // listen for incoming clients + + if (client) { // if you get a client, + Serial.println("new client"); // print a message out the serial port + String currentLine = ""; // make a String to hold incoming data from the client + while (client.connected()) { // loop while the client's connected + if (client.available()) { // if there's bytes to read from the client, + char c = client.read(); // read a byte, then + Serial.write(c); // print it out the serial monitor + if (c == '\n') { // if the byte is a newline character + + // if the current line is blank, you got two newline characters in a row. + // that's the end of the client HTTP request, so send a response: + if (currentLine.length() == 0) { + // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) + // and a content-type so the client knows what's coming, then a blank line: + client.println("HTTP/1.1 200 OK"); + client.println("Content-type:text/html"); + client.println(); + + // the content of the HTTP response follows the header: + client.print("Click here turn the LED on
"); + client.print("Click here turn the LED off
"); + + // The HTTP response ends with another blank line: + client.println(); + // break out of the while loop: + break; + } + else { // if you got a newline, then clear currentLine: + currentLine = ""; + } + } + else if (c != '\r') { // if you got anything else but a carriage return character, + currentLine += c; // add it to the end of the currentLine + } + + // Check to see if the client request was "GET /H" or "GET /L": + if (currentLine.endsWith("GET /H")) { + digitalWrite(led, HIGH); // GET /H turns the LED on + } + if (currentLine.endsWith("GET /L")) { + digitalWrite(led, LOW); // GET /L turns the LED off + } + } + } + // close the connection: + client.stop(); + Serial.println("client disconnected"); + } +} + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); + // print where to go in a browser: + Serial.print("To see this page in action, open a browser to http://"); + Serial.println(ip); + +} diff --git a/feather_sensor_lte/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino b/feather_sensor_lte/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino new file mode 100644 index 0000000..8cd312e --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino @@ -0,0 +1,67 @@ +/* + * This example check if the firmware loaded on the WiFi101 + * shield is updated. + * + * Circuit: + * - WiFi101 Shield attached + * + * Created 29 July 2015 by Cristian Maglie + * This code is in the public domain. + */ +#include +#include +#include + +void setup() { + // Initialize serial + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // Print a welcome message + Serial.println("WiFi101 firmware check."); + Serial.println(); + + // Check for the presence of the shield + Serial.print("WiFi101 shield: "); + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("NOT PRESENT"); + return; // don't continue + } + Serial.println("DETECTED"); + + // Print firmware version on the shield + String fv = WiFi.firmwareVersion(); + String latestFv; + Serial.print("Firmware version installed: "); + Serial.println(fv); + + if (REV(GET_CHIPID()) >= REV_3A0) { + // model B + latestFv = WIFI_FIRMWARE_LATEST_MODEL_B; + } else { + // model A + latestFv = WIFI_FIRMWARE_LATEST_MODEL_A; + } + + // Print required firmware version + Serial.print("Latest firmware version available : "); + Serial.println(latestFv); + + // Check if the latest version is installed + Serial.println(); + if (fv == latestFv) { + Serial.println("Check result: PASSED"); + } else { + Serial.println("Check result: NOT PASSED"); + Serial.println(" - The firmware version on the shield do not match the"); + Serial.println(" version required by the library, you may experience"); + Serial.println(" issues or failures."); + } +} + +void loop() { + // do nothing +} + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino b/feather_sensor_lte/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino new file mode 100644 index 0000000..f43a232 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino @@ -0,0 +1,123 @@ +/* + + This example connects to an unencrypted WiFi network. + Then it prints the MAC address of the WiFi shield, + the IP address obtained, and other network details. + + Circuit: + * WiFi shield attached + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + */ +#include +#include +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +int status = WL_IDLE_STATUS; // the WiFi radio's status + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to open SSID: "); + Serial.println(ssid); + status = WiFi.begin(ssid); + + // wait 10 seconds for connection: + delay(10000); + } + + // you're connected now, so print out the data: + Serial.print("You're connected to the network"); + printCurrentNet(); + printWiFiData(); +} + +void loop() { + // check the network connection once every 10 seconds: + delay(10000); + printCurrentNet(); +} + +void printWiFiData() { + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + Serial.println(ip); + + // print your MAC address: + byte mac[6]; + WiFi.macAddress(mac); + Serial.print("MAC address: "); + Serial.print(mac[5], HEX); + Serial.print(":"); + Serial.print(mac[4], HEX); + Serial.print(":"); + Serial.print(mac[3], HEX); + Serial.print(":"); + Serial.print(mac[2], HEX); + Serial.print(":"); + Serial.print(mac[1], HEX); + Serial.print(":"); + Serial.println(mac[0], HEX); + + // print your subnet mask: + IPAddress subnet = WiFi.subnetMask(); + Serial.print("NetMask: "); + Serial.println(subnet); + + // print your gateway address: + IPAddress gateway = WiFi.gatewayIP(); + Serial.print("Gateway: "); + Serial.println(gateway); +} + +void printCurrentNet() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print the MAC address of the router you're attached to: + byte bssid[6]; + WiFi.BSSID(bssid); + Serial.print("BSSID: "); + Serial.print(bssid[5], HEX); + Serial.print(":"); + Serial.print(bssid[4], HEX); + Serial.print(":"); + Serial.print(bssid[3], HEX); + Serial.print(":"); + Serial.print(bssid[2], HEX); + Serial.print(":"); + Serial.print(bssid[1], HEX); + Serial.print(":"); + Serial.println(bssid[0], HEX); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.println(rssi); + + // print the encryption type: + byte encryption = WiFi.encryptionType(); + Serial.print("Encryption Type:"); + Serial.println(encryption, HEX); +} + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h new file mode 100644 index 0000000..07c1148 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h @@ -0,0 +1 @@ +#define SECRET_SSID "" diff --git a/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino b/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino new file mode 100644 index 0000000..c226fa7 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino @@ -0,0 +1,129 @@ +/* + + This example connects to a WEP-encrypted WiFi network. + Then it prints the MAC address of the WiFi shield, + the IP address obtained, and other network details. + + If you use 40-bit WEP, you need a key that is 10 characters long, + and the characters must be hexadecimal (0-9 or A-F). + e.g. for 40-bit, ABBADEAF01 will work, but ABBADEAF won't work + (too short) and ABBAISDEAF won't work (I and S are not + hexadecimal characters). + + For 128-bit, you need a string that is 26 characters long. + D0D0DEADF00DABBADEAFBEADED will work because it's 26 characters, + all in the 0-9, A-F range. + + Circuit: + * WiFi shield attached + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + */ +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char key[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number +int status = WL_IDLE_STATUS; // the WiFi radio's status + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to WEP network, SSID: "); + Serial.println(ssid); + status = WiFi.begin(ssid, keyIndex, key); + + // wait 10 seconds for connection: + delay(10000); + } + + // once you are connected : + Serial.print("You're connected to the network"); + printCurrentNet(); + printWiFiData(); +} + +void loop() { + // check the network connection once every 10 seconds: + delay(10000); + printCurrentNet(); +} + +void printWiFiData() { + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + Serial.println(ip); + + // print your MAC address: + byte mac[6]; + WiFi.macAddress(mac); + Serial.print("MAC address: "); + Serial.print(mac[5], HEX); + Serial.print(":"); + Serial.print(mac[4], HEX); + Serial.print(":"); + Serial.print(mac[3], HEX); + Serial.print(":"); + Serial.print(mac[2], HEX); + Serial.print(":"); + Serial.print(mac[1], HEX); + Serial.print(":"); + Serial.println(mac[0], HEX); +} + +void printCurrentNet() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print the MAC address of the router you're attached to: + byte bssid[6]; + WiFi.BSSID(bssid); + Serial.print("BSSID: "); + Serial.print(bssid[5], HEX); + Serial.print(":"); + Serial.print(bssid[4], HEX); + Serial.print(":"); + Serial.print(bssid[3], HEX); + Serial.print(":"); + Serial.print(bssid[2], HEX); + Serial.print(":"); + Serial.print(bssid[1], HEX); + Serial.print(":"); + Serial.println(bssid[0], HEX); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.println(rssi); + + // print the encryption type: + byte encryption = WiFi.encryptionType(); + Serial.print("Encryption Type:"); + Serial.println(encryption, HEX); + Serial.println(); +} + + + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino b/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino new file mode 100644 index 0000000..b98af65 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino @@ -0,0 +1,119 @@ +/* + + This example connects to an unencrypted WiFi network. + Then it prints the MAC address of the WiFi shield, + the IP address obtained, and other network details. + + Circuit: + * WiFi shield attached + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + */ +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int status = WL_IDLE_STATUS; // the WiFi radio's status + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to WPA SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + + // you're connected now, so print out the data: + Serial.print("You're connected to the network"); + printCurrentNet(); + printWiFiData(); + +} + +void loop() { + // check the network connection once every 10 seconds: + delay(10000); + printCurrentNet(); +} + +void printWiFiData() { + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + Serial.println(ip); + + // print your MAC address: + byte mac[6]; + WiFi.macAddress(mac); + Serial.print("MAC address: "); + Serial.print(mac[5], HEX); + Serial.print(":"); + Serial.print(mac[4], HEX); + Serial.print(":"); + Serial.print(mac[3], HEX); + Serial.print(":"); + Serial.print(mac[2], HEX); + Serial.print(":"); + Serial.print(mac[1], HEX); + Serial.print(":"); + Serial.println(mac[0], HEX); + +} + +void printCurrentNet() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print the MAC address of the router you're attached to: + byte bssid[6]; + WiFi.BSSID(bssid); + Serial.print("BSSID: "); + Serial.print(bssid[5], HEX); + Serial.print(":"); + Serial.print(bssid[4], HEX); + Serial.print(":"); + Serial.print(bssid[3], HEX); + Serial.print(":"); + Serial.print(bssid[2], HEX); + Serial.print(":"); + Serial.print(bssid[1], HEX); + Serial.print(":"); + Serial.println(bssid[0], HEX); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.println(rssi); + + // print the encryption type: + byte encryption = WiFi.encryptionType(); + Serial.print("Encryption Type:"); + Serial.println(encryption, HEX); + Serial.println(); +} + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino b/feather_sensor_lte/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino new file mode 100644 index 0000000..897c770 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino @@ -0,0 +1,62 @@ +/* + Endianess.ino - Network byte order conversion functions. + Copyright (c) 2015 Arduino LLC. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + + +bool isBigEndian() { + uint32_t test = 0x11223344; + uint8_t *pTest = reinterpret_cast(&test); + return pTest[0] == 0x11; +} + +uint32_t fromNetwork32(uint32_t from) { + static const bool be = isBigEndian(); + if (be) { + return from; + } else { + uint8_t *pFrom = reinterpret_cast(&from); + uint32_t to; + to = pFrom[0]; to <<= 8; + to |= pFrom[1]; to <<= 8; + to |= pFrom[2]; to <<= 8; + to |= pFrom[3]; + return to; + } +} + +uint16_t fromNetwork16(uint16_t from) { + static bool be = isBigEndian(); + if (be) { + return from; + } else { + uint8_t *pFrom = reinterpret_cast(&from); + uint16_t to; + to = pFrom[0]; to <<= 8; + to |= pFrom[1]; + return to; + } +} + +uint32_t toNetwork32(uint32_t to) { + return fromNetwork32(to); +} + +uint16_t toNetwork16(uint16_t to) { + return fromNetwork16(to); +} + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino b/feather_sensor_lte/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino new file mode 100644 index 0000000..1bbd6b9 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino @@ -0,0 +1,129 @@ +/* + FirmwareUpdate.h - Firmware Updater for WiFi101 / WINC1500. + Copyright (c) 2015 Arduino LLC. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include +#include + +typedef struct __attribute__((__packed__)) { + uint8_t command; + uint32_t address; + uint32_t arg1; + uint16_t payloadLength; + + // payloadLenght bytes of data follows... +} UartPacket; + +static const int MAX_PAYLOAD_SIZE = 1024; + +#define CMD_READ_FLASH 0x01 +#define CMD_WRITE_FLASH 0x02 +#define CMD_ERASE_FLASH 0x03 +#define CMD_MAX_PAYLOAD_SIZE 0x50 +#define CMD_HELLO 0x99 + +void setup() { + Serial.begin(115200); + + nm_bsp_init(); + if (m2m_wifi_download_mode() != M2M_SUCCESS) { + Serial.println(F("Failed to put the WiFi module in download mode")); + while (true) + ; + } +} + +void receivePacket(UartPacket *pkt, uint8_t *payload) { + // Read command + uint8_t *p = reinterpret_cast(pkt); + uint16_t l = sizeof(UartPacket); + while (l > 0) { + int c = Serial.read(); + if (c == -1) + continue; + *p++ = c; + l--; + } + + // Convert parameters from network byte order to cpu byte order + pkt->address = fromNetwork32(pkt->address); + pkt->arg1 = fromNetwork32(pkt->arg1); + pkt->payloadLength = fromNetwork16(pkt->payloadLength); + + // Read payload + l = pkt->payloadLength; + while (l > 0) { + int c = Serial.read(); + if (c == -1) + continue; + *payload++ = c; + l--; + } +} + +// Allocated statically so the compiler can tell us +// about the amount of used RAM +static UartPacket pkt; +static uint8_t payload[MAX_PAYLOAD_SIZE]; + +void loop() { + receivePacket(&pkt, payload); + + if (pkt.command == CMD_HELLO) { + if (pkt.address == 0x11223344 && pkt.arg1 == 0x55667788) + Serial.print("v10000"); + } + + if (pkt.command == CMD_MAX_PAYLOAD_SIZE) { + uint16_t res = toNetwork16(MAX_PAYLOAD_SIZE); + Serial.write(reinterpret_cast(&res), sizeof(res)); + } + + if (pkt.command == CMD_READ_FLASH) { + uint32_t address = pkt.address; + uint32_t len = pkt.arg1; + if (spi_flash_read(payload, address, len) != M2M_SUCCESS) { + Serial.println("ER"); + } else { + Serial.write(payload, len); + Serial.print("OK"); + } + } + + if (pkt.command == CMD_WRITE_FLASH) { + uint32_t address = pkt.address; + uint32_t len = pkt.payloadLength; + if (spi_flash_write(payload, address, len) != M2M_SUCCESS) { + Serial.print("ER"); + } else { + Serial.print("OK"); + } + } + + if (pkt.command == CMD_ERASE_FLASH) { + uint32_t address = pkt.address; + uint32_t len = pkt.arg1; + if (spi_flash_erase(address, len) != M2M_SUCCESS) { + Serial.print("ER"); + } else { + Serial.print("OK"); + } + } +} + + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino b/feather_sensor_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino new file mode 100644 index 0000000..f62ac62 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino @@ -0,0 +1,170 @@ +/* + MDNS WiFi Web Server + + A simple web server that shows the value of the analog input pins, + and exposes itself on the MDNS name 'wifi101.local'. + + On Linux (like Ubuntu 15.04) or OSX you can access the web page + on the device in a browser at 'http://wifi101.local/'. + + On Windows you'll first need to install the Bonjour Printer Services + from: + https://support.apple.com/kb/dl999?locale=en_US + Then you can access the device in a browser at 'http://wifi101.local/'. + + This example is written for a network using WPA encryption. For + WEP or WPA, change the WiFi.begin() call accordingly. + + Circuit: + * WiFi shield attached + * Analog inputs attached to pins A0 through A5 (optional) + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + modified 27 January 2016 + by Tony DiCola + +*/ + +#include +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +char mdnsName[] = "wifi101"; // the MDNS name that the board will respond to +// Note that the actual MDNS name will have '.local' after +// the name above, so "wifi101" will be accessible on +// the MDNS name "wifi101.local". + +int status = WL_IDLE_STATUS; + +// Create a MDNS responder to listen and respond to MDNS name requests. +WiFiMDNSResponder mdnsResponder; + +WiFiServer server(80); + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + // you're connected now, so print out the status: + printWiFiStatus(); + + server.begin(); + + // Setup the MDNS responder to listen to the configured name. + // NOTE: You _must_ call this _after_ connecting to the WiFi network and + // being assigned an IP address. + if (!mdnsResponder.begin(mdnsName)) { + Serial.println("Failed to start MDNS responder!"); + while(1); + } + + Serial.print("Server listening at http://"); + Serial.print(mdnsName); + Serial.println(".local/"); +} + + +void loop() { + // Call the update() function on the MDNS responder every loop iteration to + // make sure it can detect and respond to name requests. + mdnsResponder.poll(); + + // listen for incoming clients + WiFiClient client = server.available(); + if (client) { + Serial.println("new client"); + // an http request ends with a blank line + boolean currentLineIsBlank = true; + while (client.connected()) { + if (client.available()) { + char c = client.read(); + Serial.write(c); + // if you've gotten to the end of the line (received a newline + // character) and the line is blank, the http request has ended, + // so you can send a reply + if (c == '\n' && currentLineIsBlank) { + // send a standard http response header + client.println("HTTP/1.1 200 OK"); + client.println("Content-Type: text/html"); + client.println("Connection: close"); // the connection will be closed after completion of the response + client.println("Refresh: 5"); // refresh the page automatically every 5 sec + client.println(); + client.println(""); + client.println(""); + // output the value of each analog input pin + for (int analogChannel = 0; analogChannel < 6; analogChannel++) { + int sensorReading = analogRead(analogChannel); + client.print("analog input "); + client.print(analogChannel); + client.print(" is "); + client.print(sensorReading); + client.println("
"); + } + client.println(""); + break; + } + if (c == '\n') { + // you're starting a new line + currentLineIsBlank = true; + } + else if (c != '\r') { + // you've gotten a character on the current line + currentLineIsBlank = false; + } + } + } + // give the web browser time to receive the data + delay(1); + + // close the connection: + client.stop(); + Serial.println("client disconnected"); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} diff --git a/feather_sensor_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino b/feather_sensor_lte/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino new file mode 100644 index 0000000..0297707 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino @@ -0,0 +1,167 @@ +/* + WiFi Web Server + + A simple web server that shows the value of the analog input pins. + using a WiFi shield. + + This example is written to configure the WiFi settings using provisioning mode. + It also sets up an mDNS server so the IP address of the board doesn't have to + be obtained via the serial monitor. + + Circuit: + WiFi shield attached + Analog inputs attached to pins A0 through A5 (optional) + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + +*/ + +#include +#include +#include + +const int ledPin = 6; // LED pin for connectivity status indicator + +char mdnsName[] = "wifi101"; // the MDNS name that the board will respond to + // after WiFi settings have been provisioned +// Note that the actual MDNS name will have '.local' after +// the name above, so "wifi101" will be accessible on +// the MDNS name "wifi101.local". + +WiFiServer server(80); + +// Create a MDNS responder to listen and respond to MDNS name requests. +WiFiMDNSResponder mdnsResponder; + +void setup() { + //Initialize serial: + Serial.begin(9600); + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // configure the LED pin for output mode + pinMode(ledPin, OUTPUT); + + // Start in provisioning mode: + // 1) This will try to connect to a previously associated access point. + // 2) If this fails, an access point named "wifi101-XXXX" will be created, where XXXX + // is the last 4 digits of the boards MAC address. Once you are connected to the access point, + // you can configure an SSID and password by visiting http://wifi101/ + WiFi.beginProvision(); + + while (WiFi.status() != WL_CONNECTED) { + // wait while not connected + + // blink the led to show an unconnected status + digitalWrite(ledPin, HIGH); + delay(500); + digitalWrite(ledPin, LOW); + delay(500); + } + + // connected, make the LED stay on + digitalWrite(ledPin, HIGH); + + server.begin(); + + // Setup the MDNS responder to listen to the configured name. + // NOTE: You _must_ call this _after_ connecting to the WiFi network and + // being assigned an IP address. + if (!mdnsResponder.begin(mdnsName)) { + Serial.println("Failed to start MDNS responder!"); + while(1); + } + + Serial.print("Server listening at http://"); + Serial.print(mdnsName); + Serial.println(".local/"); + + // you're connected now, so print out the status: + printWiFiStatus(); +} + + +void loop() { + // Call the update() function on the MDNS responder every loop iteration to + // make sure it can detect and respond to name requests. + mdnsResponder.poll(); + + // listen for incoming clients + WiFiClient client = server.available(); + if (client) { + Serial.println("new client"); + // an http request ends with a blank line + boolean currentLineIsBlank = true; + while (client.connected()) { + if (client.available()) { + char c = client.read(); + Serial.write(c); + // if you've gotten to the end of the line (received a newline + // character) and the line is blank, the http request has ended, + // so you can send a reply + if (c == '\n' && currentLineIsBlank) { + // send a standard http response header + client.println("HTTP/1.1 200 OK"); + client.println("Content-Type: text/html"); + client.println("Connection: close"); // the connection will be closed after completion of the response + client.println("Refresh: 5"); // refresh the page automatically every 5 sec + client.println(); + client.println(""); + client.println(""); + // output the value of each analog input pin + for (int analogChannel = 0; analogChannel < 6; analogChannel++) { + int sensorReading = analogRead(analogChannel); + client.print("analog input "); + client.print(analogChannel); + client.print(" is "); + client.print(sensorReading); + client.println("
"); + } + client.println(""); + break; + } + if (c == '\n') { + // you're starting a new line + currentLineIsBlank = true; + } + else if (c != '\r') { + // you've gotten a character on the current line + currentLineIsBlank = false; + } + } + } + // give the web browser time to receive the data + delay(1); + + // close the connection: + client.stop(); + Serial.println("client disonnected"); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino b/feather_sensor_lte/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino new file mode 100644 index 0000000..45b908e --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino @@ -0,0 +1,120 @@ +/* + + This example prints the WiFi shield's MAC address, and + scans for available WiFi networks using the WiFi shield. + Every ten seconds, it scans again. It doesn't actually + connect to any network, so no encryption scheme is specified. + + Circuit: + * WiFi shield attached + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 21 Junn 2012 + by Tom Igoe and Jaymes Dec + */ + + +#include +#include + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // Print WiFi MAC address: + printMacAddress(); + + // scan for existing networks: + Serial.println("Scanning available networks..."); + listNetworks(); +} + +void loop() { + delay(10000); + // scan for existing networks: + Serial.println("Scanning available networks..."); + listNetworks(); +} + +void printMacAddress() { + // the MAC address of your WiFi shield + byte mac[6]; + + // print your MAC address: + WiFi.macAddress(mac); + Serial.print("MAC: "); + Serial.print(mac[5], HEX); + Serial.print(":"); + Serial.print(mac[4], HEX); + Serial.print(":"); + Serial.print(mac[3], HEX); + Serial.print(":"); + Serial.print(mac[2], HEX); + Serial.print(":"); + Serial.print(mac[1], HEX); + Serial.print(":"); + Serial.println(mac[0], HEX); +} + +void listNetworks() { + // scan for nearby networks: + Serial.println("** Scan Networks **"); + int numSsid = WiFi.scanNetworks(); + if (numSsid == -1) + { + Serial.println("Couldn't get a wifi connection"); + while (true); + } + + // print the list of networks seen: + Serial.print("number of available networks:"); + Serial.println(numSsid); + + // print the network number and name for each network found: + for (int thisNet = 0; thisNet < numSsid; thisNet++) { + Serial.print(thisNet); + Serial.print(") "); + Serial.print(WiFi.SSID(thisNet)); + Serial.print("\tSignal: "); + Serial.print(WiFi.RSSI(thisNet)); + Serial.print(" dBm"); + Serial.print("\tEncryption: "); + printEncryptionType(WiFi.encryptionType(thisNet)); + Serial.flush(); + } +} + +void printEncryptionType(int thisType) { + // read the encryption type and print out the name: + switch (thisType) { + case ENC_TYPE_WEP: + Serial.println("WEP"); + break; + case ENC_TYPE_TKIP: + Serial.println("WPA"); + break; + case ENC_TYPE_CCMP: + Serial.println("WPA2"); + break; + case ENC_TYPE_NONE: + Serial.println("None"); + break; + case ENC_TYPE_AUTO: + Serial.println("Auto"); + break; + } +} + + + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino b/feather_sensor_lte/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino new file mode 100644 index 0000000..2afb544 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino @@ -0,0 +1,149 @@ +/* + + This example prints the WiFi 101 shield or MKR1000 MAC address, and + scans for available WiFi networks using the WiFi 101 shield or MKR1000 board. + Every ten seconds, it scans again. It doesn't actually + connect to any network, so no encryption scheme is specified. + BSSID and WiFi channel are printed + + Circuit: + WiFi 101 shield attached or MKR1000 board + + This example is based on ScanNetworks + + created 1 Mar 2017 + by Arturo Guadalupi +*/ + + +#include +#include + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // Print WiFi MAC address: + printMacAddress(); + + // scan for existing networks: + Serial.println(); + Serial.println("Scanning available networks..."); + listNetworks(); +} + +void loop() { + delay(10000); + // scan for existing networks: + Serial.println("Scanning available networks..."); + listNetworks(); +} + +void printMacAddress() { + // the MAC address of your WiFi shield + byte mac[6]; + + // print your MAC address: + WiFi.macAddress(mac); + Serial.print("MAC: "); + print2Digits(mac[5]); + Serial.print(":"); + print2Digits(mac[4]); + Serial.print(":"); + print2Digits(mac[3]); + Serial.print(":"); + print2Digits(mac[2]); + Serial.print(":"); + print2Digits(mac[1]); + Serial.print(":"); + print2Digits(mac[0]); +} + +void listNetworks() { + // scan for nearby networks: + Serial.println("** Scan Networks **"); + int numSsid = WiFi.scanNetworks(); + if (numSsid == -1) + { + Serial.println("Couldn't get a WiFi connection"); + while (true); + } + + // print the list of networks seen: + Serial.print("number of available networks: "); + Serial.println(numSsid); + + // print the network number and name for each network found: + for (int thisNet = 0; thisNet < numSsid; thisNet++) { + Serial.print(thisNet + 1); + Serial.print(") "); + Serial.print("Signal: "); + Serial.print(WiFi.RSSI(thisNet)); + Serial.print(" dBm"); + Serial.print("\tChannel: "); + Serial.print(WiFi.channel(thisNet)); + byte bssid[6]; + Serial.print("\t\tBSSID: "); + printBSSID(WiFi.BSSID(thisNet, bssid)); + Serial.print("\tEncryption: "); + printEncryptionType(WiFi.encryptionType(thisNet)); + Serial.print("\t\tSSID: "); + Serial.println(WiFi.SSID(thisNet)); + Serial.flush(); + } + Serial.println(); +} + +void printBSSID(byte bssid[]) { + print2Digits(bssid[5]); + Serial.print(":"); + print2Digits(bssid[4]); + Serial.print(":"); + print2Digits(bssid[3]); + Serial.print(":"); + print2Digits(bssid[2]); + Serial.print(":"); + print2Digits(bssid[1]); + Serial.print(":"); + print2Digits(bssid[0]); +} + +void printEncryptionType(int thisType) { + // read the encryption type and print out the name: + switch (thisType) { + case ENC_TYPE_WEP: + Serial.print("WEP"); + break; + case ENC_TYPE_TKIP: + Serial.print("WPA"); + break; + case ENC_TYPE_CCMP: + Serial.print("WPA2"); + break; + case ENC_TYPE_NONE: + Serial.print("None"); + break; + case ENC_TYPE_AUTO: + Serial.print("Auto"); + break; + } +} + +void print2Digits(byte thisByte) { + if (thisByte < 0xF) { + Serial.print("0"); + } + Serial.print(thisByte, HEX); +} + + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino b/feather_sensor_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino new file mode 100644 index 0000000..aeaf0c6 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino @@ -0,0 +1,131 @@ +/* + WiFi Web Server LED Blink + + A simple web server that lets you blink an LED via the web. + This sketch will print the IP address of your WiFi Shield (once connected) + to the Serial monitor. From there, you can open that address in a web browser + to turn on and off the LED on pin 9. + + If the IP address of your shield is yourAddress: + http://yourAddress/H turns the LED on + http://yourAddress/L turns it off + + This example is written for a network using WPA encryption. For + WEP or WPA, change the WiFi.begin() call accordingly. + + Circuit: + * WiFi shield attached + * LED attached to pin 9 + + created 25 Nov 2012 + by Tom Igoe + */ +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int status = WL_IDLE_STATUS; +WiFiServer server(80); + +void setup() { + Serial.begin(9600); // initialize serial communication + pinMode(9, OUTPUT); // set the LED pin mode + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + while (true); // don't continue + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + // wait 10 seconds for connection: + delay(10000); + } + server.begin(); // start the web server on port 80 + printWiFiStatus(); // you're connected now, so print out the status +} + + +void loop() { + WiFiClient client = server.available(); // listen for incoming clients + + if (client) { // if you get a client, + Serial.println("new client"); // print a message out the serial port + String currentLine = ""; // make a String to hold incoming data from the client + while (client.connected()) { // loop while the client's connected + if (client.available()) { // if there's bytes to read from the client, + char c = client.read(); // read a byte, then + Serial.write(c); // print it out the serial monitor + if (c == '\n') { // if the byte is a newline character + + // if the current line is blank, you got two newline characters in a row. + // that's the end of the client HTTP request, so send a response: + if (currentLine.length() == 0) { + // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) + // and a content-type so the client knows what's coming, then a blank line: + client.println("HTTP/1.1 200 OK"); + client.println("Content-type:text/html"); + client.println(); + + // the content of the HTTP response follows the header: + client.print("Click here turn the LED on pin 9 on
"); + client.print("Click here turn the LED on pin 9 off
"); + + // The HTTP response ends with another blank line: + client.println(); + // break out of the while loop: + break; + } + else { // if you got a newline, then clear currentLine: + currentLine = ""; + } + } + else if (c != '\r') { // if you got anything else but a carriage return character, + currentLine += c; // add it to the end of the currentLine + } + + // Check to see if the client request was "GET /H" or "GET /L": + if (currentLine.endsWith("GET /H")) { + digitalWrite(9, HIGH); // GET /H turns the LED on + } + if (currentLine.endsWith("GET /L")) { + digitalWrite(9, LOW); // GET /L turns the LED off + } + } + } + // close the connection: + client.stop(); + Serial.println("client disonnected"); + } +} + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); + // print where to go in a browser: + Serial.print("To see this page in action, open a browser to http://"); + Serial.println(ip); +} diff --git a/feather_sensor_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino b/feather_sensor_lte/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino new file mode 100644 index 0000000..ac7bd76 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino @@ -0,0 +1,114 @@ +/* + Chat Server + + A simple server that distributes any incoming messages to all + connected clients. To use telnet to your device's IP address and type. + You can see the client's input in the serial monitor as well. + + This example is written for a network using WPA encryption. For + WEP or WPA, change the WiFi.begin() call accordingly. + + + Circuit: + * WiFi shield attached + + created 18 Dec 2009 + by David A. Mellis + modified 31 May 2012 + by Tom Igoe + + */ + +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) + +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int status = WL_IDLE_STATUS; + +WiFiServer server(23); + +boolean alreadyConnected = false; // whether or not the client was connected previously + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + + // start the server: + server.begin(); + // you're connected now, so print out the status: + printWiFiStatus(); +} + + +void loop() { + // wait for a new client: + WiFiClient client = server.available(); + + + // when the client sends the first byte, say hello: + if (client) { + if (!alreadyConnected) { + // clead out the input buffer: + client.flush(); + Serial.println("We have a new client"); + client.println("Hello, client!"); + alreadyConnected = true; + } + + if (client.available() > 0) { + // read the bytes incoming from the client: + char thisChar = client.read(); + // echo the bytes back to the client: + server.write(thisChar); + // echo the bytes to the server as well: + Serial.write(thisChar); + } + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} + + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino b/feather_sensor_lte/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino new file mode 100644 index 0000000..9a51c19 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino @@ -0,0 +1,140 @@ +/* + + This example connects to a encrypted WiFi network (WPA/WPA2). + Then it prints the MAC address of the WiFi shield, + the IP address obtained, and other network details. + Then it continuously pings given host specified by IP Address or name. + + Circuit: + WiFi shield attached / MKR1000 + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 09 June 2016 + by Petar Georgiev +*/ +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int status = WL_IDLE_STATUS; // the WiFi radio's status + +// Specify IP address or hostname +String hostName = "www.google.com"; +int pingResult; + +void setup() { + // Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to WPA SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + + // wait 5 seconds for connection: + delay(5000); + } + + // you're connected now, so print out the data: + Serial.println("You're connected to the network"); + printCurrentNet(); + printWiFiData(); +} + +void loop() { + Serial.print("Pinging "); + Serial.print(hostName); + Serial.print(": "); + + pingResult = WiFi.ping(hostName); + + if (pingResult >= 0) { + Serial.print("SUCCESS! RTT = "); + Serial.print(pingResult); + Serial.println(" ms"); + } else { + Serial.print("FAILED! Error code: "); + Serial.println(pingResult); + } + + delay(5000); +} + +void printWiFiData() { + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP address : "); + Serial.println(ip); + + Serial.print("Subnet mask: "); + Serial.println((IPAddress)WiFi.subnetMask()); + + Serial.print("Gateway IP : "); + Serial.println((IPAddress)WiFi.gatewayIP()); + + // print your MAC address: + byte mac[6]; + WiFi.macAddress(mac); + Serial.print("MAC address: "); + Serial.print(mac[5], HEX); + Serial.print(":"); + Serial.print(mac[4], HEX); + Serial.print(":"); + Serial.print(mac[3], HEX); + Serial.print(":"); + Serial.print(mac[2], HEX); + Serial.print(":"); + Serial.print(mac[1], HEX); + Serial.print(":"); + Serial.println(mac[0], HEX); + Serial.println(); +} + +void printCurrentNet() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print the MAC address of the router you're attached to: + byte bssid[6]; + WiFi.BSSID(bssid); + Serial.print("BSSID: "); + Serial.print(bssid[5], HEX); + Serial.print(":"); + Serial.print(bssid[4], HEX); + Serial.print(":"); + Serial.print(bssid[3], HEX); + Serial.print(":"); + Serial.print(bssid[2], HEX); + Serial.print(":"); + Serial.print(bssid[1], HEX); + Serial.print(":"); + Serial.println(bssid[0], HEX); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI): "); + Serial.println(rssi); + + // print the encryption type: + byte encryption = WiFi.encryptionType(); + Serial.print("Encryption Type: "); + Serial.println(encryption, HEX); + Serial.println(); +} diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino b/feather_sensor_lte/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino new file mode 100644 index 0000000..a436902 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino @@ -0,0 +1,107 @@ +/* +This example creates a client object that connects and transfers +data using always SSL. + +It is compatible with the methods normally related to plain +connections, like client.connect(host, port). + +Written by Arturo Guadalupi +last revision November 2015 + +*/ + +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int status = WL_IDLE_STATUS; +// if you don't want to use DNS (and reduce your sketch size) +// use the numeric IP instead of the name for the server: +//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) +char server[] = "www.google.com"; // name address for Google (using DNS) + +// Initialize the Ethernet client library +// with the IP address and port of the server +// that you want to connect to (port 80 is default for HTTP): +WiFiSSLClient client; + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while (status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + Serial.println("Connected to wifi"); + printWiFiStatus(); + + Serial.println("\nStarting connection to server..."); + // if you get a connection, report back via serial: + if (client.connect(server, 443)) { + Serial.println("connected to server"); + // Make a HTTP request: + client.println("GET /search?q=arduino HTTP/1.1"); + client.println("Host: www.google.com"); + client.println("Connection: close"); + client.println(); + } +} + +void loop() { + // if there are incoming bytes available + // from the server, read them and print them: + while (client.available()) { + char c = client.read(); + Serial.write(c); + } + + // if the server's disconnected, stop the client: + if (!client.connected()) { + Serial.println(); + Serial.println("disconnecting from server."); + client.stop(); + + // do nothing forevermore: + while (true); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino b/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino new file mode 100644 index 0000000..e82fbaa --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino @@ -0,0 +1,182 @@ +/* + + Udp NTP Client + + Get the time from a Network Time Protocol (NTP) time server + Demonstrates use of UDP sendPacket and ReceivePacket + For more on NTP time servers and the messages needed to communicate with them, + see http://en.wikipedia.org/wiki/Network_Time_Protocol + + created 4 Sep 2010 + by Michael Margolis + modified 9 Apr 2012 + by Tom Igoe + + This code is in the public domain. + + */ + +#include +#include +#include + +int status = WL_IDLE_STATUS; +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +unsigned int localPort = 2390; // local port to listen for UDP packets + +IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server + +const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message + +byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets + +// A UDP instance to let us send and receive packets over UDP +WiFiUDP Udp; + +void setup() +{ + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + + Serial.println("Connected to wifi"); + printWiFiStatus(); + + Serial.println("\nStarting connection to server..."); + Udp.begin(localPort); +} + +void loop() +{ + sendNTPpacket(timeServer); // send an NTP packet to a time server + // wait to see if a reply is available + delay(1000); + if ( Udp.parsePacket() ) { + Serial.println("packet received"); + // We've received a packet, read the data from it + Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer + + //the timestamp starts at byte 40 of the received packet and is four bytes, + // or two words, long. First, esxtract the two words: + + unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); + unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); + // combine the four bytes (two words) into a long integer + // this is NTP time (seconds since Jan 1 1900): + unsigned long secsSince1900 = highWord << 16 | lowWord; + Serial.print("Seconds since Jan 1 1900 = " ); + Serial.println(secsSince1900); + + // now convert NTP time into everyday time: + Serial.print("Unix time = "); + // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: + const unsigned long seventyYears = 2208988800UL; + // subtract seventy years: + unsigned long epoch = secsSince1900 - seventyYears; + // print Unix time: + Serial.println(epoch); + + + // print the hour, minute and second: + Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) + Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) + Serial.print(':'); + if ( ((epoch % 3600) / 60) < 10 ) { + // In the first 10 minutes of each hour, we'll want a leading '0' + Serial.print('0'); + } + Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) + Serial.print(':'); + if ( (epoch % 60) < 10 ) { + // In the first 10 seconds of each minute, we'll want a leading '0' + Serial.print('0'); + } + Serial.println(epoch % 60); // print the second + } + // wait ten seconds before asking for the time again + delay(10000); +} + +// send an NTP request to the time server at the given address +unsigned long sendNTPpacket(IPAddress& address) +{ + //Serial.println("1"); + // set all bytes in the buffer to 0 + memset(packetBuffer, 0, NTP_PACKET_SIZE); + // Initialize values needed to form NTP request + // (see URL above for details on the packets) + //Serial.println("2"); + packetBuffer[0] = 0b11100011; // LI, Version, Mode + packetBuffer[1] = 0; // Stratum, or type of clock + packetBuffer[2] = 6; // Polling Interval + packetBuffer[3] = 0xEC; // Peer Clock Precision + // 8 bytes of zero for Root Delay & Root Dispersion + packetBuffer[12] = 49; + packetBuffer[13] = 0x4E; + packetBuffer[14] = 49; + packetBuffer[15] = 52; + + //Serial.println("3"); + + // all NTP fields have been given values, now + // you can send a packet requesting a timestamp: + Udp.beginPacket(address, 123); //NTP requests are to port 123 + //Serial.println("4"); + Udp.write(packetBuffer, NTP_PACKET_SIZE); + //Serial.println("5"); + Udp.endPacket(); + //Serial.println("6"); +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} + + + + + + + + + + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino b/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino new file mode 100644 index 0000000..cbc9f7f --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino @@ -0,0 +1,113 @@ +/* + WiFi UDP Send and Receive String + + This sketch wait an UDP packet on localPort using a WiFi shield. + When a packet is received an Acknowledge packet is sent to the client on port remotePort + + Circuit: + * WiFi shield attached + + created 30 December 2012 + by dlf (Metodo2 srl) + + */ + + +#include +#include +#include + +int status = WL_IDLE_STATUS; +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +unsigned int localPort = 2390; // local port to listen on + +char packetBuffer[255]; //buffer to hold incoming packet +char ReplyBuffer[] = "acknowledged"; // a string to send back + +WiFiUDP Udp; + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + Serial.println("Connected to wifi"); + printWiFiStatus(); + + Serial.println("\nStarting connection to server..."); + // if you get a connection, report back via serial: + Udp.begin(localPort); +} + +void loop() { + + // if there's data available, read a packet + int packetSize = Udp.parsePacket(); + if (packetSize) + { + Serial.print("Received packet of size "); + Serial.println(packetSize); + Serial.print("From "); + IPAddress remoteIp = Udp.remoteIP(); + Serial.print(remoteIp); + Serial.print(", port "); + Serial.println(Udp.remotePort()); + + // read the packet into packetBufffer + int len = Udp.read(packetBuffer, 255); + if (len > 0) packetBuffer[len] = 0; + Serial.println("Contents:"); + Serial.println(packetBuffer); + + // send a reply, to the IP address and port that sent us the packet we received + Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); + Udp.write(ReplyBuffer); + Udp.endPacket(); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} + + + + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino b/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino new file mode 100644 index 0000000..5faa779 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino @@ -0,0 +1,121 @@ +/* + Web client + + This sketch connects to a website (http://www.google.com) + using a WiFi shield. + + This example is written for a network using WPA encryption. For + WEP or WPA, change the WiFi.begin() call accordingly. + + This example is written for a network using WPA encryption. For + WEP or WPA, change the WiFi.begin() call accordingly. + + Circuit: + * WiFi shield attached + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + */ + + +#include +#include +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int status = WL_IDLE_STATUS; +// if you don't want to use DNS (and reduce your sketch size) +// use the numeric IP instead of the name for the server: +//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) +char server[] = "www.google.com"; // name address for Google (using DNS) + +// Initialize the Ethernet client library +// with the IP address and port of the server +// that you want to connect to (port 80 is default for HTTP): +WiFiClient client; + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while (status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + Serial.println("Connected to wifi"); + printWiFiStatus(); + + Serial.println("\nStarting connection to server..."); + // if you get a connection, report back via serial: + if (client.connect(server, 80)) { + Serial.println("connected to server"); + // Make a HTTP request: + client.println("GET /search?q=arduino HTTP/1.1"); + client.println("Host: www.google.com"); + client.println("Connection: close"); + client.println(); + } +} + +void loop() { + // if there are incoming bytes available + // from the server, read them and print them: + while (client.available()) { + char c = client.read(); + Serial.write(c); + } + + // if the server's disconnected, stop the client: + if (!client.connected()) { + Serial.println(); + Serial.println("disconnecting from server."); + client.stop(); + + // do nothing forevermore: + while (true); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} + + + + + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino b/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino new file mode 100644 index 0000000..ac8b4e5 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino @@ -0,0 +1,127 @@ +/* + Repeating WiFi Web Client + + This sketch connects to a a web server and makes a request + using an Arduino WiFi shield. + + Circuit: + * WiFi shield attached to pins SPI pins and pin 7 + + created 23 April 2012 + modified 31 May 2012 + by Tom Igoe + modified 13 Jan 2014 + by Federico Vanzati + + http://arduino.cc/en/Tutorial/WiFiWebClientRepeating + This code is in the public domain. + */ + +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int status = WL_IDLE_STATUS; + +// Initialize the WiFi client library +WiFiClient client; + +// server address: +char server[] = "www.arduino.cc"; +//IPAddress server(64,131,82,241); + +unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds +const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + // you're connected now, so print out the status: + printWiFiStatus(); +} + +void loop() { + // if there's incoming data from the net connection. + // send it out the serial port. This is for debugging + // purposes only: + while (client.available()) { + char c = client.read(); + Serial.write(c); + } + + // if ten seconds have passed since your last connection, + // then connect again and send data: + if (millis() - lastConnectionTime > postingInterval) { + httpRequest(); + } + +} + +// this method makes a HTTP connection to the server: +void httpRequest() { + // close any connection before send a new request. + // This will free the socket on the WiFi shield + client.stop(); + + // if there's a successful connection: + if (client.connect(server, 80)) { + Serial.println("connecting..."); + // send the HTTP PUT request: + client.println("GET /latest.txt HTTP/1.1"); + client.println("Host: www.arduino.cc"); + client.println("User-Agent: ArduinoWiFi/1.1"); + client.println("Connection: close"); + client.println(); + + // note the time that the connection was made: + lastConnectionTime = millis(); + } + else { + // if you couldn't make a connection: + Serial.println("connection failed"); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino b/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino new file mode 100644 index 0000000..24d0083 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino @@ -0,0 +1,135 @@ +/* + WiFi Web Server + + A simple web server that shows the value of the analog input pins. + using a WiFi shield. + + This example is written for a network using WPA encryption. For + WEP or WPA, change the WiFi.begin() call accordingly. + + Circuit: + * WiFi shield attached + * Analog inputs attached to pins A0 through A5 (optional) + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + + */ + +#include +#include + + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int status = WL_IDLE_STATUS; + +WiFiServer server(80); + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while (status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + server.begin(); + // you're connected now, so print out the status: + printWiFiStatus(); +} + + +void loop() { + // listen for incoming clients + WiFiClient client = server.available(); + if (client) { + Serial.println("new client"); + // an http request ends with a blank line + boolean currentLineIsBlank = true; + while (client.connected()) { + if (client.available()) { + char c = client.read(); + Serial.write(c); + // if you've gotten to the end of the line (received a newline + // character) and the line is blank, the http request has ended, + // so you can send a reply + if (c == '\n' && currentLineIsBlank) { + // send a standard http response header + client.println("HTTP/1.1 200 OK"); + client.println("Content-Type: text/html"); + client.println("Connection: close"); // the connection will be closed after completion of the response + client.println("Refresh: 5"); // refresh the page automatically every 5 sec + client.println(); + client.println(""); + client.println(""); + // output the value of each analog input pin + for (int analogChannel = 0; analogChannel < 6; analogChannel++) { + int sensorReading = analogRead(analogChannel); + client.print("analog input "); + client.print(analogChannel); + client.print(" is "); + client.print(sensorReading); + client.println("
"); + } + client.println(""); + break; + } + if (c == '\n') { + // you're starting a new line + currentLineIsBlank = true; + } + else if (c != '\r') { + // you've gotten a character on the current line + currentLineIsBlank = false; + } + } + } + // give the web browser time to receive the data + delay(1); + + // close the connection: + client.stop(); + Serial.println("client disconnected"); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_lte/libraries/WiFi101/keywords.txt b/feather_sensor_lte/libraries/WiFi101/keywords.txt new file mode 100644 index 0000000..498954d --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/keywords.txt @@ -0,0 +1,61 @@ +####################################### +# Syntax Coloring Map For WiFi +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +WiFi KEYWORD1 +WiFi101 KEYWORD1 +Client KEYWORD1 +Server KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +setPins KEYWORD2 +status KEYWORD2 +connect KEYWORD2 +connectSSL KEYWORD2 +write KEYWORD2 +available KEYWORD2 +read KEYWORD2 +flush KEYWORD2 +stop KEYWORD2 +connected KEYWORD2 +begin KEYWORD2 +beginProvision KEYWORD2 +beginOrProvision KEYWORD2 +beginMulticast KEYWORD2 +disconnect KEYWORD2 +macAddress KEYWORD2 +localIP KEYWORD2 +subnetMask KEYWORD2 +gatewayIP KEYWORD2 +SSID KEYWORD2 +BSSID KEYWORD2 +APClientMacAddress KEYWORD2 +RSSI KEYWORD2 +encryptionType KEYWORD2 +channel KEYWORD2 +provisioned KEYWORD2 +getResult KEYWORD2 +getSocket KEYWORD2 +poll KEYWORD2 +getTime KEYWORD2 +hostname KEYWORD2 +WiFiClient KEYWORD2 +WiFiServer KEYWORD2 +WiFiSSLClient KEYWORD2 +WiFiMDNSResponder KEYWORD2 + +lowPowerMode KEYWORD2 +maxLowPowerMode KEYWORD2 +noLowPowerMode KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + diff --git a/feather_sensor_lte/libraries/WiFi101/library.properties b/feather_sensor_lte/libraries/WiFi101/library.properties new file mode 100644 index 0000000..f6d0b6d --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/library.properties @@ -0,0 +1,10 @@ +name=WiFi101 +version=0.14.4 +author=Arduino +maintainer=Arduino +sentence=Network driver for ATMEL WINC1500 module (used on Arduino/Genuino Wifi Shield 101 and MKR1000 boards) +paragraph=This library implements a network driver for devices based on the ATMEL WINC1500 wifi module +category=Communication +url=http://www.arduino.cc/en/Reference/WiFi101 +architectures=* +includes=WiFi101.h diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFi.cpp b/feather_sensor_lte/libraries/WiFi101/src/WiFi.cpp new file mode 100644 index 0000000..0c71ffc --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/WiFi.cpp @@ -0,0 +1,1106 @@ +/* + WiFi.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifdef ARDUINO_ARCH_AVR +#include +#if (__AVR_LIBC_MAJOR__ < 2) +#define WIFI_101_NO_TIME_H +#endif +#endif + +#ifndef WIFI_101_NO_TIME_H +#include +#endif + +#if !defined(_TIME_H_) && !defined(TIME_H) +// another library overrided the time.h header +#define WIFI_101_NO_TIME_H +#endif + +#include "WiFi101.h" + +extern "C" { + #include "bsp/include/nm_bsp.h" + #include "bsp/include/nm_bsp_arduino.h" + #include "socket/include/socket_buffer.h" + #include "socket/include/m2m_socket_host_if.h" + #include "driver/source/nmasic.h" + #include "driver/include/m2m_periph.h" + #include "driver/include/m2m_ssl.h" +} + +static void wifi_cb(uint8_t u8MsgType, void *pvMsg) +{ + switch (u8MsgType) { + case M2M_WIFI_RESP_DEFAULT_CONNECT: + { + tstrM2MDefaultConnResp *pstrDefaultConnResp = (tstrM2MDefaultConnResp *)pvMsg; + if (pstrDefaultConnResp->s8ErrorCode) { + WiFi._status = WL_DISCONNECTED; + } + } + break; + + case M2M_WIFI_RESP_CON_STATE_CHANGED: + { + tstrM2mWifiStateChanged *pstrWifiState = (tstrM2mWifiStateChanged *)pvMsg; + if (pstrWifiState->u8CurrState == M2M_WIFI_CONNECTED) { + //SERIAL_PORT_MONITOR.println("wifi_cb: M2M_WIFI_RESP_CON_STATE_CHANGED: CONNECTED"); + if (WiFi._mode == WL_STA_MODE && !WiFi._dhcp) { + WiFi._status = WL_CONNECTED; + + // WiFi led ON. + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); + } else if (WiFi._mode == WL_AP_MODE) { + WiFi._status = WL_AP_CONNECTED; + } + } else if (pstrWifiState->u8CurrState == M2M_WIFI_DISCONNECTED) { + //SERIAL_PORT_MONITOR.println("wifi_cb: M2M_WIFI_RESP_CON_STATE_CHANGED: DISCONNECTED"); + if (WiFi._mode == WL_STA_MODE) { + WiFi._status = WL_DISCONNECTED; + if (WiFi._dhcp) { + WiFi._localip = 0; + WiFi._submask = 0; + WiFi._gateway = 0; + } + // Close sockets to clean state + // Clients will need to reconnect once the physical link will be re-established + for (int i=0; i < TCP_SOCK_MAX; i++) { + if (WiFi._client[i]) + WiFi._client[i]->stop(); + } + } else if (WiFi._mode == WL_AP_MODE) { + WiFi._status = WL_AP_LISTENING; + } + // WiFi led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); + } + } + break; + + case M2M_WIFI_REQ_DHCP_CONF: + { + if (WiFi._mode == WL_STA_MODE) { + tstrM2MIPConfig *pstrIPCfg = (tstrM2MIPConfig *)pvMsg; + WiFi._localip = pstrIPCfg->u32StaticIP; + WiFi._submask = pstrIPCfg->u32SubnetMask; + WiFi._gateway = pstrIPCfg->u32Gateway; + + WiFi._status = WL_CONNECTED; + + // WiFi led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0); + } + /*uint8_t *pu8IPAddress = (uint8_t *)pvMsg; + SERIAL_PORT_MONITOR.print("wifi_cb: M2M_WIFI_REQ_DHCP_CONF: IP is "); + SERIAL_PORT_MONITOR.print(pu8IPAddress[0], 10); + SERIAL_PORT_MONITOR.print("."); + SERIAL_PORT_MONITOR.print(pu8IPAddress[1], 10); + SERIAL_PORT_MONITOR.print("."); + SERIAL_PORT_MONITOR.print(pu8IPAddress[2], 10); + SERIAL_PORT_MONITOR.print("."); + SERIAL_PORT_MONITOR.print(pu8IPAddress[3], 10); + SERIAL_PORT_MONITOR.println("");*/ + } + break; + + case M2M_WIFI_RESP_CURRENT_RSSI: + { + WiFi._resolve = *((int8_t *)pvMsg); + } + break; + + case M2M_WIFI_RESP_PROVISION_INFO: + { + tstrM2MProvisionInfo *pstrProvInfo = (tstrM2MProvisionInfo *)pvMsg; + //SERIAL_PORT_MONITOR.println("wifi_cb: M2M_WIFI_RESP_PROVISION_INFO"); + + if (pstrProvInfo->u8Status == M2M_SUCCESS) { + memset(WiFi._ssid, 0, M2M_MAX_SSID_LEN); + memcpy(WiFi._ssid, (char *)pstrProvInfo->au8SSID, strlen((char *)pstrProvInfo->au8SSID)); + WiFi._mode = WL_STA_MODE; + WiFi._localip = 0; + WiFi._submask = 0; + WiFi._gateway = 0; + m2m_wifi_connect((char *)pstrProvInfo->au8SSID, strlen((char *)pstrProvInfo->au8SSID), + pstrProvInfo->u8SecType, pstrProvInfo->au8Password, M2M_WIFI_CH_ALL); + } else { + WiFi._status = WL_PROVISIONING_FAILED; + //SERIAL_PORT_MONITOR.println("wifi_cb: Provision failed.\r\n"); + WiFi.beginProvision(); + } + } + break; + + case M2M_WIFI_RESP_SCAN_DONE: + { + tstrM2mScanDone *pstrInfo = (tstrM2mScanDone *)pvMsg; + if (pstrInfo->u8NumofCh >= 1) { + WiFi._status = WL_SCAN_COMPLETED; + } + } + break; + + case M2M_WIFI_RESP_SCAN_RESULT: + { + tstrM2mWifiscanResult *pstrScanResult = (tstrM2mWifiscanResult *)pvMsg; + uint16_t scan_ssid_len = strlen((const char *)pstrScanResult->au8SSID); + memset(WiFi._scan_ssid, 0, M2M_MAX_SSID_LEN); + if (scan_ssid_len) { + memcpy(WiFi._scan_ssid, (const char *)pstrScanResult->au8SSID, scan_ssid_len); + } + if (WiFi._remoteMacAddress) { + // reverse copy the remote MAC + for(int i = 0; i < 6; i++) { + WiFi._remoteMacAddress[i] = pstrScanResult->au8BSSID[5-i]; + } + } + WiFi._resolve = pstrScanResult->s8rssi; + WiFi._scan_auth = pstrScanResult->u8AuthType; + WiFi._scan_channel = pstrScanResult->u8ch; + WiFi._status = WL_SCAN_COMPLETED; + } + break; + + case M2M_WIFI_RESP_CONN_INFO: + { + tstrM2MConnInfo *pstrConnInfo = (tstrM2MConnInfo*)pvMsg; + + if (WiFi._remoteMacAddress) { + // reverse copy the remote MAC + for(int i = 0; i < 6; i++) { + WiFi._remoteMacAddress[i] = pstrConnInfo->au8MACAddress[5-i]; + } + WiFi._remoteMacAddress = 0; + } + + strcpy((char *)WiFi._ssid, pstrConnInfo->acSSID); + } + break; + + case M2M_WIFI_RESP_GET_SYS_TIME: + { + if (WiFi._resolve != 0) { + memcpy((tstrSystemTime *)WiFi._resolve, pvMsg, sizeof(tstrSystemTime)); + + WiFi._resolve = 0; + } + } + break; + + default: + break; + } +} + +static void resolve_cb(uint8_t * /* hostName */, uint32_t hostIp) +{ + WiFi._resolve = hostIp; +} + +static void ping_cb(uint32 u32IPAddr, uint32 u32RTT, uint8 u8ErrorCode) +{ + if (PING_ERR_SUCCESS == u8ErrorCode) { + // Ensure this ICMP reply comes from requested IP address + if (WiFi._resolve == u32IPAddr) { + WiFi._resolve = (uint32_t)u32RTT; + } else { + // Another network device replied to the our ICMP request + WiFi._resolve = (uint32_t)WL_PING_DEST_UNREACHABLE; + } + } else if (PING_ERR_DEST_UNREACH == u8ErrorCode) { + WiFi._resolve = (uint32_t)WL_PING_DEST_UNREACHABLE; + } else if (PING_ERR_TIMEOUT == u8ErrorCode) { + WiFi._resolve = (uint32_t)WL_PING_TIMEOUT; + } else { + WiFi._resolve = (uint32_t)WL_PING_ERROR; + } +} + +WiFiClass::WiFiClass() +{ + _mode = WL_RESET_MODE; + _status = WL_NO_SHIELD; + _init = 0; +} + +void WiFiClass::setPins(int8_t cs, int8_t irq, int8_t rst, int8_t en) +{ + gi8Winc1501CsPin = cs; + gi8Winc1501IntnPin = irq; + gi8Winc1501ResetPin = rst; + gi8Winc1501ChipEnPin = en; +} + +int WiFiClass::init() +{ + tstrWifiInitParam param; + int8_t ret; + + // Initialize the WiFi BSP: + nm_bsp_init(); + + // Initialize WiFi module and register status callback: + param.pfAppWifiCb = wifi_cb; + ret = m2m_wifi_init(¶m); + if (M2M_SUCCESS != ret && M2M_ERR_FW_VER_MISMATCH != ret) { + // Error led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO18, 0); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO6, 1); + return ret; + } + + // Initialize socket API and register socket callback: + socketInit(); + socketBufferInit(); + registerSocketCallback(socketBufferCb, resolve_cb); + _init = 1; + _status = WL_IDLE_STATUS; + _localip = 0; + _submask = 0; + _gateway = 0; + _dhcp = 1; + _resolve = 0; + _remoteMacAddress = 0; + memset(_client, 0, sizeof(WiFiClient *) * TCP_SOCK_MAX); + + extern uint32 nmdrv_firm_ver; + + if (nmdrv_firm_ver >= M2M_MAKE_VERSION(19, 5, 0)) { + // enable AES-128 and AES-256 Ciphers, if firmware is 19.5.0 or higher + m2m_ssl_set_active_ciphersuites(SSL_NON_ECC_CIPHERS_AES_128 | SSL_NON_ECC_CIPHERS_AES_256); + } + + // Initialize IO expander LED control (rev A then rev B).. + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO18, 1); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO15, 1); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO18, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO6, 1); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO4, 1); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO5, 1); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO6, 1); + + return ret; +} + +extern "C" { + sint8 nm_get_firmware_info(tstrM2mRev* M2mRev); +} + +char* WiFiClass::firmwareVersion() +{ + tstrM2mRev rev; + + if (!_init) { + init(); + } + nm_get_firmware_info(&rev); + memset(_version, 0, 9); + if (rev.u8FirmwareMajor != rev.u8DriverMajor && rev.u8FirmwareMinor != rev.u8DriverMinor) { + sprintf(_version, "-Err-"); + } + else { + sprintf(_version, "%d.%d.%d", rev.u8FirmwareMajor, rev.u8FirmwareMinor, rev.u8FirmwarePatch); + } + return _version; +} + +uint8_t WiFiClass::begin() +{ + if (!_init) { + init(); + } + + // Connect to router: + if (_dhcp) { + _localip = 0; + _submask = 0; + _gateway = 0; + } + if (m2m_wifi_default_connect() < 0) { + _status = WL_CONNECT_FAILED; + return _status; + } + _status = WL_IDLE_STATUS; + _mode = WL_STA_MODE; + + // Wait for connection or timeout: + unsigned long start = millis(); + while (!(_status & WL_CONNECTED) && + !(_status & WL_DISCONNECTED) && + millis() - start < 60000) { + m2m_wifi_handle_events(NULL); + } + + memset(_ssid, 0, M2M_MAX_SSID_LEN); + + if (!(_status & WL_CONNECTED)) { + _mode = WL_RESET_MODE; + } else { + m2m_wifi_get_connection_info(); + + m2m_wifi_handle_events(NULL); + } + + return _status; +} + +uint8_t WiFiClass::begin(const char *ssid) +{ + return startConnect(ssid, M2M_WIFI_SEC_OPEN, (void *)0); +} + +uint8_t WiFiClass::begin(const char *ssid, uint8_t key_idx, const char* key) +{ + tstrM2mWifiWepParams wep_params; + + memset(&wep_params, 0, sizeof(tstrM2mWifiWepParams)); + wep_params.u8KeyIndx = key_idx; + wep_params.u8KeySz = strlen(key); + strcpy((char *)&wep_params.au8WepKey[0], key); + return startConnect(ssid, M2M_WIFI_SEC_WEP, &wep_params); +} + +uint8_t WiFiClass::begin(const char *ssid, const char *key) +{ + return startConnect(ssid, M2M_WIFI_SEC_WPA_PSK, key); +} + +uint8_t WiFiClass::startConnect(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo) +{ + if (!_init) { + init(); + } + + // Connect to router: + if (_dhcp) { + _localip = 0; + _submask = 0; + _gateway = 0; + } + if (m2m_wifi_connect((char*)ssid, strlen(ssid), u8SecType, (void*)pvAuthInfo, M2M_WIFI_CH_ALL) < 0) { + _status = WL_CONNECT_FAILED; + return _status; + } + _status = WL_IDLE_STATUS; + _mode = WL_STA_MODE; + + // Wait for connection or timeout: + unsigned long start = millis(); + while (!(_status & WL_CONNECTED) && + !(_status & WL_DISCONNECTED) && + millis() - start < 60000) { + m2m_wifi_handle_events(NULL); + } + if (!(_status & WL_CONNECTED)) { + _mode = WL_RESET_MODE; + } + + memset(_ssid, 0, M2M_MAX_SSID_LEN); + memcpy(_ssid, ssid, strlen(ssid)); + return _status; +} + +uint8_t WiFiClass::beginAP(const char *ssid) +{ + return beginAP(ssid, 1); +} + +uint8_t WiFiClass::beginAP(const char *ssid, uint8_t channel) +{ + return startAP(ssid, M2M_WIFI_SEC_OPEN, NULL, channel); +} + +uint8_t WiFiClass::beginAP(const char *ssid, uint8_t key_idx, const char* key) +{ + return beginAP(ssid, key_idx, key, 1); +} + +uint8_t WiFiClass::beginAP(const char *ssid, uint8_t key_idx, const char* key, uint8_t channel) +{ + tstrM2mWifiWepParams wep_params; + + if (key_idx == 0) { + key_idx = 1; // 1 is the minimum key index + } + + memset(&wep_params, 0, sizeof(tstrM2mWifiWepParams)); + wep_params.u8KeyIndx = key_idx; + wep_params.u8KeySz = strlen(key); + strcpy((char *)&wep_params.au8WepKey[0], key); + + return startAP(ssid, M2M_WIFI_SEC_WEP, &wep_params, channel); +} + +uint8_t WiFiClass::beginAP(const char *ssid, const char* key) +{ + return beginAP(ssid, key, 1); +} + +uint8_t WiFiClass::beginAP(const char *ssid, const char* key, uint8_t channel) +{ + return startAP(ssid, M2M_WIFI_SEC_WPA_PSK, key, channel); +} + +uint8_t WiFiClass::startAP(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo, uint8_t channel) +{ + tstrM2MAPConfig strM2MAPConfig; + + if (!_init) { + init(); + } + + if (channel == 0) { + channel = 1; // channel 1 is the minium channel + } + + // Enter Access Point mode: + memset(&strM2MAPConfig, 0x00, sizeof(tstrM2MAPConfig)); + strcpy((char *)&strM2MAPConfig.au8SSID, ssid); + strM2MAPConfig.u8ListenChannel = channel; + strM2MAPConfig.u8SecType = u8SecType; + if (_localip == 0) { + strM2MAPConfig.au8DHCPServerIP[0] = 192; + strM2MAPConfig.au8DHCPServerIP[1] = 168; + strM2MAPConfig.au8DHCPServerIP[2] = 1; + strM2MAPConfig.au8DHCPServerIP[3] = 1; + } else { + memcpy(strM2MAPConfig.au8DHCPServerIP, &_localip, sizeof(_localip)); + if (strM2MAPConfig.au8DHCPServerIP[3] == 100) { + // limitation of WINC1500 firmware, IP address of client is always x.x.x.100 + _status = WL_AP_FAILED; + return _status; + } + } + + if (u8SecType == M2M_WIFI_SEC_WEP) { + tstrM2mWifiWepParams* wep_params = (tstrM2mWifiWepParams*)pvAuthInfo; + + strM2MAPConfig.u8KeyIndx = wep_params->u8KeyIndx; + strM2MAPConfig.u8KeySz = wep_params->u8KeySz; + strcpy((char*)strM2MAPConfig.au8WepKey, (char *)wep_params->au8WepKey); + } + + if (u8SecType == M2M_WIFI_SEC_WPA_PSK) { + strM2MAPConfig.u8KeySz = strlen((char*)pvAuthInfo); + strcpy((char*)strM2MAPConfig.au8Key, (char *)pvAuthInfo); + } + + if (m2m_wifi_enable_ap(&strM2MAPConfig) < 0) { + _status = WL_AP_FAILED; + return _status; + } + _status = WL_AP_LISTENING; + _mode = WL_AP_MODE; + + memset(_ssid, 0, M2M_MAX_SSID_LEN); + memcpy(_ssid, ssid, strlen(ssid)); + m2m_memcpy((uint8 *)&_localip, (uint8 *)&strM2MAPConfig.au8DHCPServerIP[0], 4); + _submask = 0x00FFFFFF; + _gateway = _localip; + + // WiFi led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0); + + return _status; +} + +uint8_t WiFiClass::beginProvision() +{ + return beginProvision(1); +} + +uint8_t WiFiClass::beginProvision(uint8_t channel) +{ + // try to connect using begin + if (begin() != WL_CONNECTED) { + // failed, enter provisioning mode + + uint8_t mac[6]; + char provSsid[13]; + + // get MAC address for provisioning SSID + macAddress(mac); + sprintf(provSsid, "wifi101-%.2X%2X", mac[1], mac[0]); + + // start provisioning mode + startProvision(provSsid, "wifi101", channel); + } + + return status(); +} + +uint8_t WiFiClass::startProvision(const char *ssid, const char *url, uint8_t channel) +{ + tstrM2MAPConfig strM2MAPConfig; + + if (!_init) { + init(); + } + + // Enter Provision mode: + memset(&strM2MAPConfig, 0x00, sizeof(tstrM2MAPConfig)); + strcpy((char *)&strM2MAPConfig.au8SSID, ssid); + strM2MAPConfig.u8ListenChannel = channel; + strM2MAPConfig.u8SecType = M2M_WIFI_SEC_OPEN; + strM2MAPConfig.u8SsidHide = SSID_MODE_VISIBLE; + strM2MAPConfig.au8DHCPServerIP[0] = 192; + strM2MAPConfig.au8DHCPServerIP[1] = 168; + strM2MAPConfig.au8DHCPServerIP[2] = 1; + strM2MAPConfig.au8DHCPServerIP[3] = 1; + + if (m2m_wifi_start_provision_mode((tstrM2MAPConfig *)&strM2MAPConfig, (char*)url, 1) < 0) { + _status = WL_PROVISIONING_FAILED; + return _status; + } + _status = WL_PROVISIONING; + _mode = WL_PROV_MODE; + + memset(_ssid, 0, M2M_MAX_SSID_LEN); + memcpy(_ssid, ssid, strlen(ssid)); + m2m_memcpy((uint8 *)&_localip, (uint8 *)&strM2MAPConfig.au8DHCPServerIP[0], 4); + _submask = 0x00FFFFFF; + _gateway = _localip; + + // WiFi led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0); + + return _status; +} + +uint32_t WiFiClass::provisioned() +{ + m2m_wifi_handle_events(NULL); + + if (_mode == WL_STA_MODE) { + return 1; + } + else { + return 0; + } +} + +void WiFiClass::config(IPAddress local_ip) +{ + config(local_ip, (uint32_t)0); +} + +void WiFiClass::config(IPAddress local_ip, IPAddress dns_server) +{ + config(local_ip, dns_server, (uint32_t)0); +} + +void WiFiClass::config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway) +{ + config(local_ip, dns_server, gateway, (uint32_t)0); +} + +void WiFiClass::config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet) +{ + tstrM2MIPConfig conf; + + if (!_init) { + init(); + } + + conf.u32DNS = (uint32_t)dns_server; + conf.u32Gateway = (uint32_t)gateway; + conf.u32StaticIP = (uint32_t)local_ip; + conf.u32SubnetMask = (uint32_t)subnet; + _dhcp = 0; + m2m_wifi_enable_dhcp(0); // disable DHCP + m2m_wifi_set_static_ip(&conf); + _localip = conf.u32StaticIP; + _submask = conf.u32SubnetMask; + _gateway = conf.u32Gateway; +} + +void WiFiClass::hostname(const char* name) +{ + if (!_init) { + init(); + } + + m2m_wifi_set_device_name((uint8 *)name, strlen(name)); +} + +void WiFiClass::disconnect() +{ + m2m_wifi_disconnect(); + + // WiFi led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); +} + +void WiFiClass::end() +{ + if (_mode == WL_AP_MODE) { + m2m_wifi_disable_ap(); + } else { + if (_mode == WL_PROV_MODE) { + m2m_wifi_stop_provision_mode(); + } + + m2m_wifi_disconnect(); + } + + // WiFi led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); + + socketDeinit(); + + m2m_wifi_deinit(NULL); + + nm_bsp_deinit(); + + _mode = WL_RESET_MODE; + _status = WL_NO_SHIELD; + _init = 0; +} + +uint8_t *WiFiClass::macAddress(uint8_t *mac) +{ + m2m_wifi_get_mac_address(mac); + byte tmpMac[6], i; + + m2m_wifi_get_mac_address(tmpMac); + + for(i = 0; i < 6; i++) + mac[i] = tmpMac[5-i]; + + return mac; +} + +uint32_t WiFiClass::localIP() +{ + return _localip; +} + +uint32_t WiFiClass::subnetMask() +{ + return _submask; +} + +uint32_t WiFiClass::gatewayIP() +{ + return _gateway; +} + +char* WiFiClass::SSID() +{ + if (_status == WL_CONNECTED || _status == WL_AP_LISTENING || _status == WL_AP_CONNECTED) { + return _ssid; + } + else { + return 0; + } +} + +uint8_t* WiFiClass::BSSID(uint8_t* bssid) +{ + if (_mode == WL_AP_MODE) { + return macAddress(bssid); + } else { + return remoteMacAddress(bssid); + } +} + +uint8_t* WiFiClass::APClientMacAddress(uint8_t* mac) +{ + if (_mode == WL_AP_MODE) { + return remoteMacAddress(mac); + } else { + memset(mac, 0, 6); + return mac; + } +} + +uint8_t* WiFiClass::remoteMacAddress(uint8_t* remoteMacAddress) +{ + _remoteMacAddress = remoteMacAddress; + memset(remoteMacAddress, 0, 6); + + m2m_wifi_get_connection_info(); + + // Wait for connection or timeout: + unsigned long start = millis(); + while (_remoteMacAddress != 0 && millis() - start < 1000) { + m2m_wifi_handle_events(NULL); + } + + _remoteMacAddress = 0; + return remoteMacAddress; +} + +int32_t WiFiClass::RSSI() +{ + // Clear pending events: + m2m_wifi_handle_events(NULL); + + // Send RSSI request: + _resolve = 0; + if (m2m_wifi_req_curr_rssi() < 0) { + return 0; + } + + // Wait for connection or timeout: + unsigned long start = millis(); + while (_resolve == 0 && millis() - start < 1000) { + m2m_wifi_handle_events(NULL); + } + + int32_t rssi = _resolve; + + _resolve = 0; + + return rssi; +} + +int8_t WiFiClass::scanNetworks() +{ + wl_status_t tmp = _status; + + if (!_init) { + init(); + } + + // Start scan: + if (m2m_wifi_request_scan(M2M_WIFI_CH_ALL) < 0) { + return 0; + } + + // Wait for scan result or timeout: + _status = WL_IDLE_STATUS; + unsigned long start = millis(); + while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 5000) { + m2m_wifi_handle_events(NULL); + } + _status = tmp; + return m2m_wifi_get_num_ap_found(); +} + +char* WiFiClass::SSID(uint8_t pos) +{ + wl_status_t tmp = _status; + + // Get scan SSID result: + memset(_scan_ssid, 0, M2M_MAX_SSID_LEN); + if (m2m_wifi_req_scan_result(pos) < 0) { + return 0; + } + + // Wait for connection or timeout: + _status = WL_IDLE_STATUS; + unsigned long start = millis(); + while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + + _status = tmp; + _resolve = 0; + + return _scan_ssid; +} + +int32_t WiFiClass::RSSI(uint8_t pos) +{ + wl_status_t tmp = _status; + + // Get scan RSSI result: + if (m2m_wifi_req_scan_result(pos) < 0) { + return 0; + } + + // Wait for connection or timeout: + _status = WL_IDLE_STATUS; + unsigned long start = millis(); + while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + + _status = tmp; + + int32_t rssi = _resolve; + + _resolve = 0; + + return rssi; +} + +uint8_t WiFiClass::encryptionType() +{ + int8_t net = scanNetworks(); + + for (uint8_t i = 0; i < net; ++i) { + SSID(i); + if (strcmp(_scan_ssid, _ssid) == 0) { + break; + } + } + + return _scan_auth; +} + +uint8_t WiFiClass::encryptionType(uint8_t pos) +{ + wl_status_t tmp = _status; + + // Get scan auth result: + if (m2m_wifi_req_scan_result(pos) < 0) { + return 0; + } + + // Wait for connection or timeout: + _status = WL_IDLE_STATUS; + unsigned long start = millis(); + while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + + _status = tmp; + _resolve = 0; + + return _scan_auth; +} + +uint8_t* WiFiClass::BSSID(uint8_t pos, uint8_t* bssid) +{ + wl_status_t tmp = _status; + + _remoteMacAddress = bssid; + + // Get scan auth result: + if (m2m_wifi_req_scan_result(pos) < 0) { + return 0; + } + + // Wait for connection or timeout: + _status = WL_IDLE_STATUS; + unsigned long start = millis(); + while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + + _status = tmp; + _resolve = 0; + _remoteMacAddress = 0; + + return bssid; +} + +uint8_t WiFiClass::channel(uint8_t pos) +{ + wl_status_t tmp = _status; + + // Get scan auth result: + if (m2m_wifi_req_scan_result(pos) < 0) { + return 0; + } + + // Wait for connection or timeout: + _status = WL_IDLE_STATUS; + unsigned long start = millis(); + while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + + _status = tmp; + _resolve = 0; + + return _scan_channel; +} + +uint8_t WiFiClass::status() +{ + if (!_init) { + init(); + } + + m2m_wifi_handle_events(NULL); + + return _status; +} + +int WiFiClass::hostByName(const char* aHostname, IPAddress& aResult) +{ + + // check if aHostname is already an ipaddress + if (aResult.fromString(aHostname)) { + // if fromString returns true we have an IP address ready + return 1; + + } else { + // Network led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); + + // Send DNS request: + _resolve = 0; + if (gethostbyname((uint8 *)aHostname) < 0) { + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + return 0; + } + + // Wait for connection or timeout: + unsigned long start = millis(); + while (_resolve == 0 && millis() - start < 20000) { + m2m_wifi_handle_events(NULL); + } + + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + + if (_resolve == 0) { + return 0; + } + + aResult = _resolve; + _resolve = 0; + return 1; + } +} + +void WiFiClass::refresh(void) +{ + // Update state machine: + m2m_wifi_handle_events(NULL); +} + +void WiFiClass::lowPowerMode(void) +{ + m2m_wifi_set_sleep_mode(M2M_PS_H_AUTOMATIC, true); +} + +void WiFiClass::maxLowPowerMode(void) +{ + m2m_wifi_set_sleep_mode(M2M_PS_DEEP_AUTOMATIC, true); +} + +void WiFiClass::noLowPowerMode(void) +{ + m2m_wifi_set_sleep_mode(M2M_NO_PS, false); +} + +int WiFiClass::ping(const char* hostname, uint8_t ttl) +{ + IPAddress ip; + + if (hostByName(hostname, ip) > 0) { + return ping(ip, ttl); + } else { + return WL_PING_UNKNOWN_HOST; + } +} + +int WiFiClass::ping(const String &hostname, uint8_t ttl) +{ + return ping(hostname.c_str(), ttl); +} + +int WiFiClass::ping(IPAddress host, uint8_t ttl) +{ + // Network led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); + + uint32_t dstHost = (uint32_t)host; + _resolve = dstHost; + + if (m2m_ping_req((uint32_t)host, ttl, &ping_cb) < 0) { + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + // Error sending ping request + return WL_PING_ERROR; + } + + // Wait for success or timeout: + unsigned long start = millis(); + while (_resolve == dstHost && millis() - start < 5000) { + m2m_wifi_handle_events(NULL); + } + + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + + if (_resolve == dstHost) { + _resolve = 0; + return WL_PING_TIMEOUT; + } else { + int rtt = (int)_resolve; + _resolve = 0; + return rtt; + } +} + +uint32_t WiFiClass::getTime() +{ +#ifdef WIFI_101_NO_TIME_H + #warning "No system header included, WiFi.getTime() will always return 0" + return 0; +#else + tstrSystemTime systemTime; + + _resolve = (uint32_t)&systemTime; + + m2m_wifi_get_sytem_time(); + + unsigned long start = millis(); + while (_resolve != 0 && millis() - start < 5000) { + m2m_wifi_handle_events(NULL); + } + + time_t t = 0; + + if (_resolve == 0 && systemTime.u16Year > 0) { + struct tm tm; + + tm.tm_year = systemTime.u16Year - 1900; + tm.tm_mon = systemTime.u8Month - 1; + tm.tm_mday = systemTime.u8Day; + tm.tm_hour = systemTime.u8Hour; + tm.tm_min = systemTime.u8Minute; + tm.tm_sec = systemTime.u8Second; + tm.tm_isdst = -1; + + t = mktime(&tm); + } + + _resolve = 0; + + return t; +#endif +} + +WiFiClass WiFi; diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFi101.h b/feather_sensor_lte/libraries/WiFi101/src/WiFi101.h new file mode 100644 index 0000000..6e46fab --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/WiFi101.h @@ -0,0 +1,193 @@ +/* + WiFi.h - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef WIFI_H +#define WIFI_H + +#define WIFI_FIRMWARE_LATEST_MODEL_A "19.4.4" +#define WIFI_FIRMWARE_LATEST_MODEL_B "19.5.2" + +// for backwards compatibility +#define WIFI_FIRMWARE_REQUIRED WIFI_FIRMWARE_LATEST_MODEL_B + +#include + +extern "C" { + #include "driver/include/m2m_wifi.h" + #include "socket/include/socket.h" +} + +#include "WiFiClient.h" +#include "WiFiSSLClient.h" +#include "WiFiServer.h" + +typedef enum { + WL_NO_SHIELD = 255, + WL_IDLE_STATUS = 0, + WL_NO_SSID_AVAIL, + WL_SCAN_COMPLETED, + WL_CONNECTED, + WL_CONNECT_FAILED, + WL_CONNECTION_LOST, + WL_DISCONNECTED, + WL_AP_LISTENING, + WL_AP_CONNECTED, + WL_AP_FAILED, + WL_PROVISIONING, + WL_PROVISIONING_FAILED +} wl_status_t; + +/* Encryption modes */ +enum wl_enc_type { /* Values map to 802.11 encryption suites... */ + ENC_TYPE_WEP = M2M_WIFI_SEC_WEP, + ENC_TYPE_TKIP = M2M_WIFI_SEC_WPA_PSK, + ENC_TYPE_CCMP = M2M_WIFI_SEC_802_1X, + /* ... except these two, 7 and 8 are reserved in 802.11-2007 */ + ENC_TYPE_NONE = M2M_WIFI_SEC_OPEN, + ENC_TYPE_AUTO = M2M_WIFI_SEC_INVALID +}; + +typedef enum { + WL_RESET_MODE = 0, + WL_STA_MODE, + WL_PROV_MODE, + WL_AP_MODE +} wl_mode_t; + +typedef enum { + WL_PING_DEST_UNREACHABLE = -1, + WL_PING_TIMEOUT = -2, + WL_PING_UNKNOWN_HOST = -3, + WL_PING_ERROR = -4 +} wl_ping_result_t; + +class WiFiClass +{ +public: + uint32_t _localip; + uint32_t _submask; + uint32_t _gateway; + int _dhcp; + uint32_t _resolve; + byte *_remoteMacAddress; + wl_mode_t _mode; + wl_status_t _status; + char _scan_ssid[M2M_MAX_SSID_LEN]; + uint8_t _scan_auth; + uint8_t _scan_channel; + char _ssid[M2M_MAX_SSID_LEN]; + WiFiClient *_client[TCP_SOCK_MAX]; + + WiFiClass(); + + void setPins(int8_t cs, int8_t irq, int8_t rst, int8_t en = -1); + + int init(); + + char* firmwareVersion(); + + /* Start Wifi connection with WPA/WPA2 encryption. + * + * param ssid: Pointer to the SSID string. + * param key: Key input buffer. + */ + uint8_t begin(); + uint8_t begin(const char *ssid); + uint8_t begin(const char *ssid, uint8_t key_idx, const char* key); + uint8_t begin(const char *ssid, const char *key); + uint8_t begin(const String &ssid) { return begin(ssid.c_str()); } + uint8_t begin(const String &ssid, uint8_t key_idx, const String &key) { return begin(ssid.c_str(), key_idx, key.c_str()); } + uint8_t begin(const String &ssid, const String &key) { return begin(ssid.c_str(), key.c_str()); } + + /* Start Wifi in Access Point, with open security. + * Only one client can connect to the AP at a time. + * + * param ssid: Pointer to the SSID string. + * param channel: Wifi channel to use. Valid values are 1-12. + */ + uint8_t beginAP(const char *ssid); + uint8_t beginAP(const char *ssid, uint8_t channel); + uint8_t beginAP(const char *ssid, uint8_t key_idx, const char* key); + uint8_t beginAP(const char *ssid, uint8_t key_idx, const char* key, uint8_t channel); + uint8_t beginAP(const char *ssid, const char* key); + uint8_t beginAP(const char *ssid, const char* key, uint8_t channel); + + uint8_t beginProvision(); + uint8_t beginProvision(uint8_t channel); + + uint32_t provisioned(); + + void config(IPAddress local_ip); + void config(IPAddress local_ip, IPAddress dns_server); + void config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway); + void config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet); + + void hostname(const char* name); + + void disconnect(); + void end(); + + uint8_t *macAddress(uint8_t *mac); + + uint32_t localIP(); + uint32_t subnetMask(); + uint32_t gatewayIP(); + char* SSID(); + int32_t RSSI(); + uint8_t encryptionType(); + uint8_t* BSSID(uint8_t* bssid); + uint8_t* APClientMacAddress(uint8_t* mac); + int8_t scanNetworks(); + char* SSID(uint8_t pos); + int32_t RSSI(uint8_t pos); + uint8_t encryptionType(uint8_t pos); + uint8_t* BSSID(uint8_t pos, uint8_t* bssid); + uint8_t channel(uint8_t pos); + + uint8_t status(); + + int hostByName(const char* hostname, IPAddress& result); + int hostByName(const String &hostname, IPAddress& result) { return hostByName(hostname.c_str(), result); } + + int ping(const char* hostname, uint8_t ttl = 128); + int ping(const String &hostname, uint8_t ttl = 128); + int ping(IPAddress host, uint8_t ttl = 128); + + unsigned long getTime(); + + void refresh(void); + + void lowPowerMode(void); + void maxLowPowerMode(void); + void noLowPowerMode(void); + +private: + int _init; + char _version[9]; + + uint8_t startConnect(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo); + uint8_t startAP(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo, uint8_t channel); + uint8_t* remoteMacAddress(uint8_t* remoteMacAddress); + + uint8_t startProvision(const char *ssid, const char *url, uint8_t channel); +}; + +extern WiFiClass WiFi; + +#endif /* WIFI_H */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiClient.cpp b/feather_sensor_lte/libraries/WiFi101/src/WiFiClient.cpp new file mode 100644 index 0000000..8298618 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/WiFiClient.cpp @@ -0,0 +1,308 @@ +/* + WiFiClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +extern "C" { + #include "socket/include/socket.h" + #include "driver/include/m2m_periph.h" +} + +#include "WiFi101.h" +#include "WiFiClient.h" + +#define IS_CONNECTED (_flag & SOCKET_BUFFER_FLAG_CONNECTED) + +WiFiClient::WiFiClient() +{ + _socket = -1; + _flag = 0; + _head = 0; + _tail = 0; +} + +WiFiClient::WiFiClient(uint8_t sock, uint8_t parentsock) +{ + // Spawn connected TCP client from TCP server socket: + _socket = sock; + _flag = SOCKET_BUFFER_FLAG_CONNECTED; + if (parentsock) { + _flag |= ((uint32_t)parentsock) << SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS; + } + _head = 0; + _tail = 0; + for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { + if (WiFi._client[sock] == this) + WiFi._client[sock] = 0; + } + WiFi._client[_socket] = this; + + // Add socket buffer handler: + socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_buffer); + + // Enable receive buffer: + recv(_socket, _buffer, SOCKET_BUFFER_MTU, 0); + + m2m_wifi_handle_events(NULL); +} + +WiFiClient::WiFiClient(const WiFiClient& other) +{ + copyFrom(other); +} + +void WiFiClient::copyFrom(const WiFiClient& other) +{ + _socket = other._socket; + _flag = other._flag; + _head = other._head; + _tail = other._tail; + if (_head > _tail) { + memcpy(_buffer + _tail, other._buffer + _tail, (_head - _tail)); + } + + for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { + if (WiFi._client[sock] == this) + WiFi._client[sock] = 0; + } + + if (_socket > -1) { + WiFi._client[_socket] = this; + + // Add socket buffer handler: + socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_buffer); + + // Enable receive buffer: + recv(_socket, _buffer, SOCKET_BUFFER_MTU, 0); + } + + m2m_wifi_handle_events(NULL); +} + +int WiFiClient::connectSSL(const char* host, uint16_t port) +{ + return connect(host, port, SOCKET_FLAGS_SSL); +} + +int WiFiClient::connectSSL(IPAddress ip, uint16_t port) +{ + return connect(ip, port, SOCKET_FLAGS_SSL, 0); +} + +int WiFiClient::connect(const char* host, uint16_t port) +{ + return connect(host, port, 0); +} + +int WiFiClient::connect(IPAddress ip, uint16_t port) +{ + return connect(ip, port, 0, 0); +} + +int WiFiClient::connect(const char* host, uint16_t port, uint8_t opt) +{ + IPAddress remote_addr; + if (WiFi.hostByName(host, remote_addr)) { + return connect(remote_addr, port, opt, (const uint8_t *)host); + } + return 0; +} + +int WiFiClient::connect(IPAddress ip, uint16_t port, uint8_t opt, const uint8_t *hostname) +{ + struct sockaddr_in addr; + + // Initialize socket address structure: + addr.sin_family = AF_INET; + addr.sin_port = _htons(port); + addr.sin_addr.s_addr = ip; + + // Create TCP socket: + _flag = 0; + _head = 0; + _tail = 0; + if ((_socket = socket(AF_INET, SOCK_STREAM, opt)) < 0) { + return 0; + } + + if (opt & SOCKET_FLAGS_SSL && hostname) { + setsockopt(_socket, SOL_SSL_SOCKET, SO_SSL_SNI, hostname, m2m_strlen((uint8_t *)hostname)); + } + + // Add socket buffer handler: + socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_buffer); + + // Connect to remote host: + if (connectSocket(_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { + close(_socket); + _socket = -1; + return 0; + } + + // Wait for connection or timeout: + unsigned long start = millis(); + while (!IS_CONNECTED && millis() - start < 20000) { + m2m_wifi_handle_events(NULL); + } + if (!IS_CONNECTED) { + close(_socket); + _socket = -1; + return 0; + } + + WiFi._client[_socket] = this; + + return 1; +} + +size_t WiFiClient::write(uint8_t b) +{ + return write(&b, 1); +} + +size_t WiFiClient::write(const uint8_t *buf, size_t size) +{ + sint16 err; + + if (_socket < 0 || size == 0 || !IS_CONNECTED) { + setWriteError(); + return 0; + } + + // Network led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); + + m2m_wifi_handle_events(NULL); + + while ((err = send(_socket, (void *)buf, size, 0)) < 0) { + // Exit on fatal error, retry if buffer not ready. + if (err != SOCK_ERR_BUFFER_FULL) { + setWriteError(); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + return 0; + } + m2m_wifi_handle_events(NULL); + } + + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + + return size; +} + +int WiFiClient::available() +{ + m2m_wifi_handle_events(NULL); + + if (_socket != -1) { + return _head - _tail; + } + return 0; +} + +int WiFiClient::read() +{ + uint8_t b; + + if (read(&b, sizeof(b)) == -1) { + return -1; + } + + return b; +} + +int WiFiClient::read(uint8_t* buf, size_t size) +{ + // sizeof(size_t) is architecture dependent + // but we need a 16 bit data type here + uint16_t size_tmp = available(); + + if (size_tmp == 0) { + return -1; + } + + if (size < size_tmp) { + size_tmp = size; + } + + for (uint32_t i = 0; i < size_tmp; ++i) { + buf[i] = _buffer[_tail++]; + } + + if (_tail == _head) { + _tail = _head = 0; + _flag &= ~SOCKET_BUFFER_FLAG_FULL; + recv(_socket, _buffer, SOCKET_BUFFER_MTU, 0); + m2m_wifi_handle_events(NULL); + } + + return size_tmp; +} + +int WiFiClient::peek() +{ + if (!available()) + return -1; + + return _buffer[_tail]; +} + +void WiFiClient::flush() +{ + while (available()) + read(); +} + +void WiFiClient::stop() +{ + if (_socket < 0) + return; + + socketBufferUnregister(_socket); + close(_socket); + _socket = -1; + _flag = 0; +} + +uint8_t WiFiClient::connected() +{ + m2m_wifi_handle_events(NULL); + if (available()) + return 1; + return IS_CONNECTED; +} + +uint8_t WiFiClient::status() +{ + // Deprecated. + return 0; +} + +WiFiClient::operator bool() +{ + return _socket != -1; +} + +WiFiClient& WiFiClient::operator =(const WiFiClient& other) +{ + copyFrom(other); + + return *this; +} diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiClient.h b/feather_sensor_lte/libraries/WiFi101/src/WiFiClient.h new file mode 100644 index 0000000..bef171d --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/WiFiClient.h @@ -0,0 +1,68 @@ +/* + WiFiClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef WIFICLIENT_H +#define WIFICLIENT_H + +#include +#include +#include +#include "socket/include/socket_buffer.h" + +class WiFiClient : public Client { + +public: + WiFiClient(); + WiFiClient(uint8_t sock, uint8_t parentsock = 0); + WiFiClient(const WiFiClient& other); + + uint8_t status(); + + int connectSSL(IPAddress ip, uint16_t port); + int connectSSL(const char* host, uint16_t port); + virtual int connect(IPAddress ip, uint16_t port); + virtual int connect(const char* host, uint16_t port); + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + virtual int available(); + virtual int read(); + virtual int read(uint8_t *buf, size_t size); + virtual int peek(); + virtual void flush(); + virtual void stop(); + virtual uint8_t connected(); + virtual operator bool(); + virtual WiFiClient& operator =(const WiFiClient& other); + + using Print::write; + + uint32_t _flag; + +private: + SOCKET _socket; + uint32_t _head; + uint32_t _tail; + uint8_t _buffer[SOCKET_BUFFER_TCP_SIZE]; + int connect(const char* host, uint16_t port, uint8_t opt); + int connect(IPAddress ip, uint16_t port, uint8_t opt, const uint8_t *hostname); + void copyFrom(const WiFiClient& other); + +}; + +#endif /* WIFICLIENT_H */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiMDNSResponder.cpp b/feather_sensor_lte/libraries/WiFi101/src/WiFiMDNSResponder.cpp new file mode 100644 index 0000000..a192113 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/WiFiMDNSResponder.cpp @@ -0,0 +1,220 @@ +// Port of CC3000 MDNS Responder to WINC1500. +// Author: Tony DiCola +// +// This MDNSResponder class implements just enough MDNS functionality to respond +// to name requests, for example 'foo.local'. This does not implement any other +// MDNS or Bonjour functionality like services, etc. +// +// Copyright (c) 2016 Adafruit Industries. All right reserved. +// +// 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 2.1 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 Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +#include +#ifndef ARDUINO_ARCH_AVR +#include +#endif + +#include "Arduino.h" +#include "WiFiMDNSResponder.h" + +// Important RFC's for reference: +// - DNS request and response: http://www.ietf.org/rfc/rfc1035.txt +// - Multicast DNS: http://www.ietf.org/rfc/rfc6762.txt + +#define HEADER_SIZE 12 +#define TTL_OFFSET 4 +#define IP_OFFSET 10 + +const uint8_t expectedRequestHeader[HEADER_SIZE] PROGMEM = { + 0x00, 0x00, + 0x00, 0x00, + 0x00, 0x01, // questions (these 2 bytes are ignored) + 0x00, 0x00, + 0x00, 0x00, + 0x00, 0x00 +}; + +const uint8_t responseHeader[] PROGMEM = { + 0x00, 0x00, // ID = 0 + 0x84, 0x00, // Flags = response + authoritative answer + 0x00, 0x00, // Question count = 0 + 0x00, 0x01, // Answer count = 1 + 0x00, 0x00, // Name server records = 0 + 0x00, 0x01 // Additional records = 1 +}; + +// Generate positive response for IPV4 address +const uint8_t aRecord[] PROGMEM = { + 0x00, 0x01, // Type = 1, A record/IPV4 address + 0x80, 0x01, // Class = Internet, with cache flush bit + 0x00, 0x00, 0x00, 0x00, // TTL in seconds, to be filled in later + 0x00, 0x04, // Length of record + 0x00, 0x00, 0x00, 0x00 // IP address, to be filled in later +}; + +// Generate negative response for IPV6 address (CC3000 doesn't support IPV6) +const uint8_t nsecRecord[] PROGMEM = { + 0xC0, 0x0C, // Name offset + 0x00, 0x2F, // Type = 47, NSEC (overloaded by MDNS) + 0x80, 0x01, // Class = Internet, with cache flush bit + 0x00, 0x00, 0x00, 0x00, // TTL in seconds, to be filled in later + 0x00, 0x08, // Length of record + 0xC0, 0x0C, // Next domain = offset to FQDN + 0x00, // Block number = 0 + 0x04, // Length of bitmap = 4 bytes + 0x40, 0x00, 0x00, 0x00 // Bitmap value = Only first bit (A record/IPV4) is set +}; + +const uint8_t domain[] PROGMEM = { 'l', 'o', 'c', 'a', 'l' }; + +WiFiMDNSResponder::WiFiMDNSResponder() : + minimumExpectedRequestLength(0) +{ +} + +WiFiMDNSResponder::~WiFiMDNSResponder() +{ +} + +bool WiFiMDNSResponder::begin(const char* _name, uint32_t _ttlSeconds) +{ + int nameLength = strlen(_name); + + if (nameLength > 255) { + // Can only handle domains that are upto 255 chars in length. + minimumExpectedRequestLength = 0; + return false; + } + + name = _name; + ttlSeconds = _ttlSeconds; + + name.toLowerCase(); + minimumExpectedRequestLength = HEADER_SIZE + 1 + nameLength + 1 + sizeof(domain) + 5; + + // Open the MDNS UDP listening socket on port 5353 with multicast address + // 224.0.0.251 (0xE00000FB) + if (!udpSocket.beginMulticast(IPAddress(224, 0, 0, 251), 5353)) { + return false; + } + + return true; +} + +void WiFiMDNSResponder::poll() +{ + if (parseRequest()) { + replyToRequest(); + } +} + +bool WiFiMDNSResponder::parseRequest() +{ + int packetLength = udpSocket.parsePacket(); + + if (packetLength) { + // check if parsed packet matches expected request length + if (packetLength < minimumExpectedRequestLength) { + // it does not, read the full packet in and drop data + while(udpSocket.available()) { + udpSocket.read(); + } + + return false; + } + + // read up to the min expect request length + uint8_t request[minimumExpectedRequestLength]; + udpSocket.read(request, minimumExpectedRequestLength); + + // discard the rest + while(udpSocket.available()) { + udpSocket.read(); + } + + // parse request + uint8_t requestNameLength = request[HEADER_SIZE]; + uint8_t* requestName = &request[HEADER_SIZE + 1]; + uint8_t requestDomainLength = request[HEADER_SIZE + 1 + requestNameLength]; + uint8_t* requestDomain = &request[HEADER_SIZE + 1 + requestNameLength + 1]; + uint16_t requestQtype; + uint16_t requestQclass; + + memcpy(&requestQtype, &request[minimumExpectedRequestLength - 4], sizeof(requestQtype)); + memcpy(&requestQclass, &request[minimumExpectedRequestLength - 2], sizeof(requestQclass)); + + requestQtype = _ntohs(requestQtype); + requestQclass = _ntohs(requestQclass); + + // compare request + if (memcmp_P(request, expectedRequestHeader, 4) == 0 && // request header start match + memcmp_P(&request[6], &expectedRequestHeader[6], 6) == 0 && // request header end match + requestNameLength == name.length() && // name length match + strncasecmp(name.c_str(), (char*)requestName, requestNameLength) == 0 && // name match + requestDomainLength == sizeof(domain) && // domain length match + memcmp_P(requestDomain, domain, requestDomainLength) == 0 && // suffix match + requestQtype == 0x0001 && // request QType match + requestQclass == 0x0001) { // request QClass match + + return true; + } + } + + return false; +} + +void WiFiMDNSResponder::replyToRequest() +{ + int nameLength = name.length(); + int domainLength = sizeof(domain); + uint32_t ipAddress = WiFi.localIP(); + uint32_t ttl = _htonl(ttlSeconds); + + int responseSize = sizeof(responseHeader) + 1 + nameLength + 1 + domainLength + 1 + sizeof(aRecord) + sizeof(nsecRecord); + uint8_t response[responseSize]; + uint8_t* r = response; + + // copy header + memcpy_P(r, responseHeader, sizeof(responseHeader)); + r += sizeof(responseHeader); + + // copy name + *r = nameLength; + memcpy(r + 1, name.c_str(), nameLength); + r += (1 + nameLength); + + // copy domain + *r = domainLength; + memcpy_P(r + 1, domain, domainLength); + r += (1 + domainLength); + + // terminator + *r = 0x00; + r++; + + // copy A record + memcpy_P(r, aRecord, sizeof(aRecord)); + memcpy(r + TTL_OFFSET, &ttl, sizeof(ttl)); // replace TTL value + memcpy(r + IP_OFFSET, &ipAddress, sizeof(ipAddress)); // replace IP address value + r += sizeof(aRecord); + + // copy NSEC record + memcpy_P(r, nsecRecord, sizeof(nsecRecord)); + r += sizeof(nsecRecord); + + udpSocket.beginPacket(IPAddress(224, 0, 0, 251), 5353); + udpSocket.write(response, responseSize); + udpSocket.endPacket(); +} diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiMDNSResponder.h b/feather_sensor_lte/libraries/WiFi101/src/WiFiMDNSResponder.h new file mode 100644 index 0000000..d7e3d43 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/WiFiMDNSResponder.h @@ -0,0 +1,51 @@ +// Port of CC3000 MDNS Responder to WINC1500. +// Author: Tony DiCola +// +// This MDNSResponder class implements just enough MDNS functionality to respond +// to name requests, for example 'foo.local'. This does not implement any other +// MDNS or Bonjour functionality like services, etc. +// +// Copyright (c) 2016 Adafruit Industries. All right reserved. +// +// 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 2.1 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 Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +#ifndef WIFIMDNSRESPONDER_H +#define WIFIMDNSRESPONDER_H + +#include "WiFi101.h" +#include "WiFiUdp.h" + +class WiFiMDNSResponder { +public: + WiFiMDNSResponder(); + ~WiFiMDNSResponder(); + bool begin(const char* _name, uint32_t _ttlSeconds = 3600); + void poll(); + +private: + bool parseRequest(); + void replyToRequest(); + +private: + String name; + uint32_t ttlSeconds; + + int minimumExpectedRequestLength; + + // UDP socket for receiving/sending MDNS data. + WiFiUDP udpSocket; +}; + +#endif diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiSSLClient.cpp b/feather_sensor_lte/libraries/WiFi101/src/WiFiSSLClient.cpp new file mode 100644 index 0000000..e7be43c --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/WiFiSSLClient.cpp @@ -0,0 +1,45 @@ +/* + WiFiSSLClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "WiFiSSLClient.h" + +WiFiSSLClient::WiFiSSLClient() : + WiFiClient() +{ +} + +WiFiSSLClient::WiFiSSLClient(uint8_t sock, uint8_t parentsock) : + WiFiClient(sock, parentsock) +{ +} + +WiFiSSLClient::WiFiSSLClient(const WiFiSSLClient& other) : + WiFiClient(other) +{ +} + +int WiFiSSLClient::connect(IPAddress ip, uint16_t port) +{ + return WiFiClient::connectSSL(ip, port); +} + +int WiFiSSLClient::connect(const char* host, uint16_t port) +{ + return WiFiClient::connectSSL(host, port); +} diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiSSLClient.h b/feather_sensor_lte/libraries/WiFi101/src/WiFiSSLClient.h new file mode 100644 index 0000000..c5851e5 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/WiFiSSLClient.h @@ -0,0 +1,36 @@ +/* + WiFiSSLClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef WIFISSLCLIENT_H +#define WIFISSLCLIENT_H + +#include "WiFiClient.h" + +class WiFiSSLClient : public WiFiClient { + +public: + WiFiSSLClient(); + WiFiSSLClient(uint8_t sock, uint8_t parentsock = 0); + WiFiSSLClient(const WiFiSSLClient& other); + + virtual int connect(IPAddress ip, uint16_t port); + virtual int connect(const char* host, uint16_t port); +}; + +#endif /* WIFISSLCLIENT_H */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiServer.cpp b/feather_sensor_lte/libraries/WiFi101/src/WiFiServer.cpp new file mode 100644 index 0000000..5f330ba --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/WiFiServer.cpp @@ -0,0 +1,140 @@ +/* + WiFiClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +extern "C" { + #include "socket/include/socket.h" +} + +#include "WiFi101.h" +#include "WiFiClient.h" +#include "WiFiServer.h" + +#define READY (_flag & SOCKET_BUFFER_FLAG_BIND) + +WiFiServer::WiFiServer(uint16_t port) +{ + _port = port; + _flag = 0; +} + +void WiFiServer::begin() +{ + begin(0); +} + +uint8_t WiFiServer::beginSSL() +{ + return begin(SOCKET_FLAGS_SSL); +} + +uint8_t WiFiServer::begin(uint8_t opt) +{ + struct sockaddr_in addr; + + _flag = 0; + + // Initialize socket address structure. + addr.sin_family = AF_INET; + addr.sin_port = _htons(_port); + addr.sin_addr.s_addr = 0; + + // Open TCP server socket. + if ((_socket = socket(AF_INET, SOCK_STREAM, opt)) < 0) { + return 0; + } + + // Add socket buffer handler: + socketBufferRegister(_socket, &_flag, 0, 0, 0); + + // Bind socket: + if (bind(_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { + close(_socket); + _socket = -1; + return 0; + } + + // Wait for connection or timeout: + unsigned long start = millis(); + while (!READY && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + if (!READY) { + close(_socket); + _socket = -1; + return 0; + } + _flag &= ~SOCKET_BUFFER_FLAG_BIND; + + return 1; +} + +WiFiClient WiFiServer::available(uint8_t* status) +{ + uint32_t flag; + + m2m_wifi_handle_events(NULL); + if (_flag & SOCKET_BUFFER_FLAG_SPAWN) { + flag = _flag; + _flag &= ~SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK; + _flag &= ~SOCKET_BUFFER_FLAG_SPAWN; + if (status != NULL) { + *status = 0; + } + return WiFiClient(((flag & SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK) >> SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS), _socket + 1); + } else { + WiFiClient *client; + + for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { + client = WiFi._client[sock]; + if (client && client->_flag & SOCKET_BUFFER_FLAG_CONNECTED) { + if (((client->_flag >> SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS) & 0xff) == (uint8)(_socket + 1)) { + return *client; + } + } + } + } + + return WiFiClient(); +} + +uint8_t WiFiServer::status() { + // Deprecated. + return 0; +} + +size_t WiFiServer::write(uint8_t b) +{ + return write(&b, 1); +} + +size_t WiFiServer::write(const uint8_t *buffer, size_t size) +{ + size_t n = 0; + WiFiClient *client; + + for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { + client = WiFi._client[sock]; + if (client && client->_flag & SOCKET_BUFFER_FLAG_CONNECTED) { + if (((client->_flag >> SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS) & 0xff) == (uint8)(_socket + 1)) { + n += client->write(buffer, size); + } + } + } + return n; +} diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiServer.h b/feather_sensor_lte/libraries/WiFi101/src/WiFiServer.h new file mode 100644 index 0000000..d658b2f --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/WiFiServer.h @@ -0,0 +1,49 @@ +/* + WiFiClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef WIFISERVER_H +#define WIFISERVER_H + +#include +#include + +class WiFiClient; + +class WiFiServer : public Server { + +private: + SOCKET _socket; + uint32_t _flag; + uint16_t _port; + uint8_t begin(uint8_t opt); + +public: + WiFiServer(uint16_t); + WiFiClient available(uint8_t* status = NULL); + void begin(); + uint8_t beginSSL(); + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + uint8_t status(); + + using Print::write; + +}; + +#endif /* WIFISERVER_H */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiUdp.cpp b/feather_sensor_lte/libraries/WiFi101/src/WiFiUdp.cpp new file mode 100644 index 0000000..e55c965 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/WiFiUdp.cpp @@ -0,0 +1,289 @@ +/* + WiFiUdp.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +extern "C" { + #include "socket/include/socket.h" + #include "driver/include/m2m_periph.h" + extern uint8 hif_small_xfer; +} + +#include +#include "WiFi101.h" +#include "WiFiUdp.h" +#include "WiFiClient.h" +#include "WiFiServer.h" + +#define READY (_flag & SOCKET_BUFFER_FLAG_BIND) + +/* Constructor. */ +WiFiUDP::WiFiUDP() +{ + _socket = -1; + _flag = 0; + _head = 0; + _tail = 0; + _rcvSize = 0; + _rcvPort = 0; + _rcvIP = 0; + _sndSize = 0; +} + +/* Start WiFiUDP socket, listening at local port PORT */ +uint8_t WiFiUDP::begin(uint16_t port) +{ + struct sockaddr_in addr; + uint32 u32EnableCallbacks = 0; + + _flag = 0; + _head = 0; + _tail = 0; + _rcvSize = 0; + _rcvPort = 0; + _rcvIP = 0; + _sndSize = 0; + + // Initialize socket address structure. + addr.sin_family = AF_INET; + addr.sin_port = _htons(port); + addr.sin_addr.s_addr = 0; + + // Open TCP server socket. + if ((_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { + return 0; + } + + // Add socket buffer handler: + socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_recvBuffer); + setsockopt(_socket, SOL_SOCKET, SO_SET_UDP_SEND_CALLBACK, &u32EnableCallbacks, 0); + + // Bind socket: + if (bind(_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { + close(_socket); + _socket = -1; + return 0; + } + + // Wait for connection or timeout: + unsigned long start = millis(); + while (!READY && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + if (!READY) { + close(_socket); + _socket = -1; + return 0; + } + _flag &= ~SOCKET_BUFFER_FLAG_BIND; + + return 1; +} + +uint8_t WiFiUDP::beginMulticast(IPAddress ip, uint16_t port) +{ + uint32_t multiIp = ip; + + if (!begin(port)) { + return 0; + } + + setsockopt(_socket, SOL_SOCKET, IP_ADD_MEMBERSHIP, &multiIp, sizeof(multiIp)); + + return 1; +} + +/* return number of bytes available in the current packet, + will return zero if parsePacket hasn't been called yet */ +int WiFiUDP::available() +{ + m2m_wifi_handle_events(NULL); + + if (_socket != -1) { + return _rcvSize; + } + return 0; + } + +/* Release any resources being used by this WiFiUDP instance */ +void WiFiUDP::stop() +{ + if (_socket < 0) + return; + + socketBufferUnregister(_socket); + close(_socket); + _socket = -1; +} + +int WiFiUDP::beginPacket(const char *host, uint16_t port) +{ + IPAddress ip; + if (WiFi.hostByName(host, ip)) { + return beginPacket(ip, port); + } + + return 0; +} + +int WiFiUDP::beginPacket(IPAddress ip, uint16_t port) +{ + _sndIP = ip; + _sndPort = port; + _sndSize = 0; + + return 1; +} + +int WiFiUDP::endPacket() +{ + struct sockaddr_in addr; + + // Network led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); + + addr.sin_family = AF_INET; + addr.sin_port = _htons(_sndPort); + addr.sin_addr.s_addr = _sndIP; + + if (sendto(_socket, (void *)_sndBuffer, _sndSize, 0, + (struct sockaddr *)&addr, sizeof(addr)) < 0) { + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + return 0; + } + + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + + return 1; +} + +size_t WiFiUDP::write(uint8_t byte) +{ + return write(&byte, 1); +} + +size_t WiFiUDP::write(const uint8_t *buffer, size_t size) +{ + if ((size + _sndSize) > sizeof(_sndBuffer)) { + size = sizeof(_sndBuffer) - _sndSize; + } + + memcpy(_sndBuffer + _sndSize, buffer, size); + + _sndSize += size; + + return size; +} + +int WiFiUDP::parsePacket() +{ + m2m_wifi_handle_events(NULL); + + if (_socket != -1) { + if (_rcvSize != 0) { + return _rcvSize; + } + if (_head != _tail) { + _rcvSize = ((uint16_t)_recvBuffer[_tail] << 8) + (uint16_t)_recvBuffer[_tail + 1]; + _rcvPort = ((uint16_t)_recvBuffer[_tail + 2] << 8) + (uint16_t)_recvBuffer[_tail + 3]; + _rcvIP = ((uint32_t)_recvBuffer[_tail + 4] << 24) + ((uint32_t)_recvBuffer[_tail + 5] << 16) + + ((uint32_t)_recvBuffer[_tail + 6] << 8) + (uint32_t)_recvBuffer[_tail + 7]; + _tail += SOCKET_BUFFER_UDP_HEADER_SIZE; + return _rcvSize; + } + } + return 0; +} + +int WiFiUDP::read() +{ + uint8_t b; + + if (read(&b, sizeof(b)) == -1) { + return -1; + } + + return b; +} + +int WiFiUDP::read(unsigned char* buf, size_t size) +{ + // sizeof(size_t) is architecture dependent + // but we need a 16 bit data type here + uint16_t size_tmp = available(); + + if (size_tmp == 0) { + return -1; + } + + if (size < size_tmp) { + size_tmp = size; + } + + for (uint32_t i = 0; i < size_tmp; ++i) { + buf[i] = _recvBuffer[_tail++]; + _rcvSize--; + + if (_tail == _head) { + // the full buffered data has been read, reset head and tail for next transfer + _tail = _head = 0; + + // clear the buffer full flag + _flag &= ~SOCKET_BUFFER_FLAG_FULL; + + // setup buffer and buffer size to transfer the remainder of the current packet + // or next received packet + if (hif_small_xfer) { + recvfrom(_socket, _recvBuffer, SOCKET_BUFFER_MTU, 0); + } else { + recvfrom(_socket, _recvBuffer + SOCKET_BUFFER_UDP_HEADER_SIZE, SOCKET_BUFFER_MTU, 0); + } + m2m_wifi_handle_events(NULL); + } + } + + return size_tmp; +} + +int WiFiUDP::peek() +{ + if (!available()) + return -1; + + return _recvBuffer[_tail]; +} + +void WiFiUDP::flush() +{ + while (available()) + read(); +} + +IPAddress WiFiUDP::remoteIP() +{ + return _rcvIP; +} + +uint16_t WiFiUDP::remotePort() +{ + return _rcvPort; +} diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiUdp.h b/feather_sensor_lte/libraries/WiFi101/src/WiFiUdp.h new file mode 100644 index 0000000..d961682 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/WiFiUdp.h @@ -0,0 +1,89 @@ +/* + WiFiUdp.h - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef WIFIUDP_H +#define WIFIUDP_H + +#include + +class WiFiUDP : public UDP { +private: + SOCKET _socket; + uint32_t _flag; + uint32_t _head; + uint32_t _tail; + uint8_t _recvBuffer[SOCKET_BUFFER_UDP_SIZE]; + uint16_t _rcvSize; + uint16_t _rcvPort; + uint32_t _rcvIP; + uint8_t _sndBuffer[SOCKET_BUFFER_UDP_SIZE]; + uint16_t _sndSize; + uint16_t _sndPort; + uint32_t _sndIP; + +public: + WiFiUDP(); // Constructor + virtual uint8_t begin(uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use + virtual uint8_t beginMulticast(IPAddress, uint16_t); // initialize, start listening on specified multicast IP address and port. Returns 1 if successful, 0 if there are no sockets available to use + virtual uint8_t beginMulti(IPAddress ip, uint16_t port) { return beginMulticast(ip, port); } + virtual void stop(); // Finish with the UDP socket + + // Sending UDP packets + + // Start building up a packet to send to the remote host specific in ip and port + // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port + virtual int beginPacket(IPAddress ip, uint16_t port); + // Start building up a packet to send to the remote host specific in host and port + // Returns 1 if successful, 0 if there was a problem resolving the hostname or port + virtual int beginPacket(const char *host, uint16_t port); + // Finish off this packet and send it + // Returns 1 if the packet was sent successfully, 0 if there was an error + virtual int endPacket(); + // Write a single byte into the packet + virtual size_t write(uint8_t); + // Write size bytes from buffer into the packet + virtual size_t write(const uint8_t *buffer, size_t size); + + using Print::write; + + // Start processing the next available incoming packet + // Returns the size of the packet in bytes, or 0 if no packets are available + virtual int parsePacket(); + // Number of bytes remaining in the current packet + virtual int available(); + // Read a single byte from the current packet + virtual int read(); + // Read up to len bytes from the current packet and place them into buffer + // Returns the number of bytes read, or 0 if none are available + virtual int read(unsigned char* buffer, size_t len); + // Read up to len characters from the current packet and place them into buffer + // Returns the number of characters read, or 0 if none are available + virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; + // Return the next byte from the current packet without moving on to the next byte + virtual int peek(); + virtual void flush(); // Finish reading the current packet + + // Return the IP address of the host who sent the current incoming packet + virtual IPAddress remoteIP(); + // Return the port of the host who sent the current incoming packet + virtual uint16_t remotePort(); + +}; + +#endif /* WIFIUDP_H */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp.h b/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp.h new file mode 100644 index 0000000..5527bab --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp.h @@ -0,0 +1,283 @@ +/** + * + * \file + * + * \brief WINC BSP API Declarations. + * + * Copyright (c) 2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/** \defgroup nm_bsp BSP + */ +/**@defgroup BSPDefine Defines + * @ingroup nm_bsp + * @{ + */ +#ifndef _NM_BSP_H_ +#define _NM_BSP_H_ + +#define NMI_API +/*!< +* Attribute used to define memory section to map Functions in host memory. +*/ +#define CONST const + +/*!< +* Used for code portability. +*/ + +/*! + * @typedef void (*tpfNmBspIsr) (void); + * @brief Pointer to function.\n + * Used as a data type of ISR function registered by \ref nm_bsp_register_isr + * @return None + */ +typedef void (*tpfNmBspIsr)(void); + + + +#ifndef NULL +#define NULL ((void*)0) +#endif +/*!< +* Void Pointer to '0' in case of NULL is not defined. +*/ + + +#define BSP_MIN(x,y) ((x)>(y)?(y):(x)) +/*!< +* Computes the minimum of \b x and \b y. +*/ + + //@} + +/**@defgroup DataT DataTypes + * @ingroup nm_bsp + * @{ + */ + + /*! + * @ingroup DataTypes + * @typedef unsigned char uint8; + * @brief Range of values between 0 to 255 + */ +typedef unsigned char uint8; + + /*! + * @ingroup DataTypes + * @typedef unsigned short uint16; + * @brief Range of values between 0 to 65535 + */ +typedef unsigned short uint16; + + /*! + * @ingroup Data Types + * @typedef unsigned long uint32; + * @brief Range of values between 0 to 4294967295 + */ +typedef unsigned long uint32; + + + /*! + * @ingroup Data Types + * @typedef signed char sint8; + * @brief Range of values between -128 to 127 + */ +typedef signed char sint8; + + /*! + * @ingroup DataTypes + * @typedef signed short sint16; + * @brief Range of values between -32768 to 32767 + */ +typedef signed short sint16; + + /*! + * @ingroup DataTypes + * @typedef signed long sint32; + * @brief Range of values between -2147483648 to 2147483647 + */ + +typedef signed long sint32; + //@} + +#ifndef CORTUS_APP + + +#ifdef __cplusplus +extern "C"{ +#endif + +/** \defgroup BSPAPI Function + * @ingroup nm_bsp + */ + + +/** @defgroup NmBspInitFn nm_bsp_init + * @ingroup BSPAPI + * Initialization for BSP such as Reset and Chip Enable Pins for WINC, delays, register ISR, enable/disable IRQ for WINC, ...etc. You must use this function in the head of your application to + * enable WINC and Host Driver communicate each other. + */ + /**@{*/ +/*! + * @fn sint8 nm_bsp_init(void); + * @note Implementation of this function is host dependent. + * @warning Missing use will lead to unavailability of host communication.\n + * + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + + */ +sint8 nm_bsp_init(void); + /**@}*/ + + + /** @defgroup NmBspDeinitFn nm_bsp_deinit + * @ingroup BSPAPI + * De-initialization for BSP (\e Board \e Support \e Package) + */ + /**@{*/ +/*! + * @fn sint8 nm_bsp_deinit(void); + * @pre Initialize \ref nm_bsp_init first + * @note Implementation of this function is host dependent. + * @warning Missing use may lead to unknown behavior in case of soft reset.\n + * @see nm_bsp_init + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + + */ +sint8 nm_bsp_deinit(void); + /**@}*/ + + +/** @defgroup NmBspResetFn nm_bsp_reset +* @ingroup BSPAPI +* Resetting NMC1500 SoC by setting CHIP_EN and RESET_N signals low, then after specific delay the function will put CHIP_EN high then RESET_N high, +* for the timing between signals please review the WINC data-sheet +*/ +/**@{*/ + /*! + * @fn void nm_bsp_reset(void); + * @param [in] None + * @pre Initialize \ref nm_bsp_init first + * @note Implementation of this function is host dependent and called by HIF layer. + * @see nm_bsp_init + * @return None + + */ +void nm_bsp_reset(void); + /**@}*/ + + +/** @defgroup NmBspSleepFn nm_bsp_sleep +* @ingroup BSPAPI +* Sleep in units of milliseconds.\n +* This function used by HIF Layer according to different situations. +*/ +/**@{*/ +/*! + * @fn void nm_bsp_sleep(uint32); + * @brief + * @param [in] u32TimeMsec + * Time unit in milliseconds + * @pre Initialize \ref nm_bsp_init first + * @warning Maximum value must nor exceed 4294967295 milliseconds which is equal to 4294967.295 seconds.\n + * @note Implementation of this function is host dependent. + * @see nm_bsp_init + * @return None + */ +void nm_bsp_sleep(uint32 u32TimeMsec); +/**@}*/ + + +/** @defgroup NmBspRegisterFn nm_bsp_register_isr +* @ingroup BSPAPI +* Register ISR (Interrupt Service Routine) in the initialization of HIF (Host Interface) Layer. +* When the interrupt trigger the BSP layer should call the pfisr function once inside the interrupt. +*/ +/**@{*/ +/*! + * @fn void nm_bsp_register_isr(tpfNmBspIsr); + * @param [in] tpfNmBspIsr pfIsr + * Pointer to ISR handler in HIF + * @warning Make sure that ISR for IRQ pin for WINC is disabled by default in your implementation. + * @note Implementation of this function is host dependent and called by HIF layer. + * @see tpfNmBspIsr + * @return None + + */ +void nm_bsp_register_isr(tpfNmBspIsr pfIsr); +/**@}*/ + + +/** @defgroup NmBspInterruptCtrl nm_bsp_interrupt_ctrl +* @ingroup BSPAPI +* Synchronous enable/disable interrupts function +*/ +/**@{*/ +/*! + * @fn void nm_bsp_interrupt_ctrl(uint8); + * @brief Enable/Disable interrupts + * @param [in] u8Enable + * '0' disable interrupts. '1' enable interrupts + * @see tpfNmBspIsr + * @note Implementation of this function is host dependent and called by HIF layer. + * @return None + + */ +void nm_bsp_interrupt_ctrl(uint8 u8Enable); + /**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif + +#ifdef _NM_BSP_BIG_END +#define NM_BSP_B_L_32(x) \ +((((x) & 0x000000FF) << 24) + \ +(((x) & 0x0000FF00) << 8) + \ +(((x) & 0x00FF0000) >> 8) + \ +(((x) & 0xFF000000) >> 24)) +#define NM_BSP_B_L_16(x) \ +((((x) & 0x00FF) << 8) + \ +(((x) & 0xFF00) >> 8)) +#else +#define NM_BSP_B_L_32(x) (x) +#define NM_BSP_B_L_16(x) (x) +#endif + + +#endif /*_NM_BSP_H_*/ diff --git a/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h b/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h new file mode 100644 index 0000000..77417e8 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h @@ -0,0 +1,74 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 BSP APIs definitions. + * + * Copyright (c) 2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NM_BSP_ARDUINO_H_ +#define _NM_BSP_ARDUINO_H_ + +#include + +#include + +/* + * Arduino variants may redefine those pins. + * If no pins are specified the following defaults are used: + * WINC1501_RESET_PIN - pin 5 + * WINC1501_INTN_PIN - pin 7 + * WINC1501_CHIP_EN_PIN - not connected (tied to VCC) + */ +#if !defined(WINC1501_RESET_PIN) + #define WINC1501_RESET_PIN 5 +#endif +#if !defined(WINC1501_INTN_PIN) + #define WINC1501_INTN_PIN 7 +#endif +#if !defined(WINC1501_SPI_CS_PIN) + #define WINC1501_SPI_CS_PIN 10 +#endif +#if !defined(WINC1501_CHIP_EN_PIN) + #define WINC1501_CHIP_EN_PIN -1 +#endif + +extern int8_t gi8Winc1501CsPin; +extern int8_t gi8Winc1501ResetPin; +extern int8_t gi8Winc1501IntnPin; +extern int8_t gi8Winc1501ChipEnPin; + +#endif /* _NM_BSP_ARDUINO_H_ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h b/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h new file mode 100644 index 0000000..c5991f2 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h @@ -0,0 +1,54 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 BSP APIs definitions. + * + * Copyright (c) 2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NM_BSP_AVR_H_ +#define _NM_BSP_AVR_H_ + +#pragma once + +#define NM_DEBUG 0 +#define NM_BSP_PRINTF + +#define CONF_WINC_USE_SPI 1 + +#define NM_EDGE_INTERRUPT 1 + +#endif /* _NM_BSP_AVR_H_ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h b/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h new file mode 100644 index 0000000..45d3ff2 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h @@ -0,0 +1,59 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 BSP APIs declarations. + * + * Copyright (c) 2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/**@defgroup BSPDefine Defines + * @ingroup nm_bsp + * @{ + */ +#ifndef _NM_BSP_INTERNAL_H_ +#define _NM_BSP_INTERNAL_H_ + +#ifdef ARDUINO_ARCH_AVR +#define LIMITED_RAM_DEVICE +#include "bsp/include/nm_bsp_avr.h" +#else +#include "bsp/include/nm_bsp_samd21.h" +#endif + +#ifdef ARDUINO +#define CONF_PERIPH +#endif + +#endif //_NM_BSP_INTERNAL_H_ \ No newline at end of file diff --git a/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h b/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h new file mode 100644 index 0000000..296cd20 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h @@ -0,0 +1,52 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 BSP APIs definitions. + * + * Copyright (c) 2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NM_BSP_SAMD21_H_ +#define _NM_BSP_SAMD21_H_ + +#define NM_DEBUG 0 +#define NM_BSP_PRINTF + +#define CONF_WINC_USE_SPI 1 + +#define NM_EDGE_INTERRUPT 1 + +#endif /* _NM_BSP_SAMD21_H_ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c b/feather_sensor_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c new file mode 100644 index 0000000..e27be14 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c @@ -0,0 +1,205 @@ +/** + * + * \file + * + * \brief This module contains SAMD21 BSP APIs implementation. + * + * Copyright (c) 2014 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "bsp/include/nm_bsp.h" +#include "bsp/include/nm_bsp_arduino.h" +#include "common/include/nm_common.h" + +int8_t gi8Winc1501CsPin = WINC1501_SPI_CS_PIN; +int8_t gi8Winc1501ResetPin = WINC1501_RESET_PIN; +int8_t gi8Winc1501IntnPin = WINC1501_INTN_PIN; +int8_t gi8Winc1501ChipEnPin = WINC1501_CHIP_EN_PIN; + +static tpfNmBspIsr gpfIsr; + +void __attribute__((weak)) attachInterruptMultiArch(uint32_t pin, void *chip_isr, uint32_t mode) +{ + attachInterrupt(pin, chip_isr, mode); +} + +void __attribute__((weak)) detachInterruptMultiArch(uint32_t pin) +{ + detachInterrupt(pin); +} + +static void chip_isr(void) +{ + if (gpfIsr) { + gpfIsr(); + } +} + +/* + * @fn init_chip_pins + * @brief Initialize reset, chip enable and wake pin + * @author M.S.M + * @date 11 July 2012 + * @version 1.0 + */ +static void init_chip_pins(void) +{ + /* Configure RESETN pin as output. */ + pinMode(gi8Winc1501ResetPin, OUTPUT); + digitalWrite(gi8Winc1501ResetPin, HIGH); + + /* Configure INTN pins as input. */ + pinMode(gi8Winc1501IntnPin, INPUT); + + if (gi8Winc1501ChipEnPin > -1) + { + /* Configure CHIP_EN as pull-up */ + pinMode(gi8Winc1501ChipEnPin, INPUT_PULLUP); + } +} + +static void deinit_chip_pins(void) +{ + digitalWrite(gi8Winc1501ResetPin, LOW); + pinMode(gi8Winc1501ResetPin, INPUT); + + if (gi8Winc1501ChipEnPin > -1) + { + pinMode(gi8Winc1501ChipEnPin, INPUT); + } +} + +/* + * @fn nm_bsp_init + * @brief Initialize BSP + * @return 0 in case of success and -1 in case of failure + * @author M.S.M + * @date 11 July 2012 + * @version 1.0 + */ +sint8 nm_bsp_init(void) +{ + gpfIsr = NULL; + + init_chip_pins(); + + nm_bsp_reset(); + + return M2M_SUCCESS; +} + +/** + * @fn nm_bsp_deinit + * @brief De-iInitialize BSP + * @return 0 in case of success and -1 in case of failure + * @author M. Abdelmawla + * @date 11 July 2012 + * @version 1.0 + */ +sint8 nm_bsp_deinit(void) +{ + deinit_chip_pins(); + + return M2M_SUCCESS; +} + +/** + * @fn nm_bsp_reset + * @brief Reset NMC1500 SoC by setting CHIP_EN and RESET_N signals low, + * CHIP_EN high then RESET_N high + * @author M. Abdelmawla + * @date 11 July 2012 + * @version 1.0 + */ +void nm_bsp_reset(void) +{ + digitalWrite(gi8Winc1501ResetPin, LOW); + nm_bsp_sleep(100); + digitalWrite(gi8Winc1501ResetPin, HIGH); + nm_bsp_sleep(100); +} + +/* + * @fn nm_bsp_sleep + * @brief Sleep in units of mSec + * @param[IN] u32TimeMsec + * Time in milliseconds + * @author M.S.M + * @date 28 OCT 2013 + * @version 1.0 + */ +void nm_bsp_sleep(uint32 u32TimeMsec) +{ + while (u32TimeMsec--) { + delay(1); + } +} + +/* + * @fn nm_bsp_register_isr + * @brief Register interrupt service routine + * @param[IN] pfIsr + * Pointer to ISR handler + * @author M.S.M + * @date 28 OCT 2013 + * @sa tpfNmBspIsr + * @version 1.0 + */ +void nm_bsp_register_isr(tpfNmBspIsr pfIsr) +{ + gpfIsr = pfIsr; + attachInterruptMultiArch(gi8Winc1501IntnPin, chip_isr, FALLING); +} + +/* + * @fn nm_bsp_interrupt_ctrl + * @brief Enable/Disable interrupts + * @param[IN] u8Enable + * '0' disable interrupts. '1' enable interrupts + * @author M.S.M + * @date 28 OCT 2013 + * @version 1.0 + */ +void nm_bsp_interrupt_ctrl(uint8 u8Enable) +{ + if (u8Enable) { + attachInterruptMultiArch(gi8Winc1501IntnPin, chip_isr, FALLING); + } else { + detachInterruptMultiArch(gi8Winc1501IntnPin); + } +} diff --git a/feather_sensor_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c b/feather_sensor_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c new file mode 100644 index 0000000..050d5d5 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c @@ -0,0 +1,164 @@ +/** + * + * \file + * + * \brief This module contains SAMD21 BSP APIs implementation. + * + * Copyright (c) 2014 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifdef ARDUINO_ARCH_AVR + +#include "bsp/include/nm_bsp.h" +#include "bsp/include/nm_bsp_arduino.h" +#include "common/include/nm_common.h" + +#define IS_MEGA (defined(ARDUINO_AVR_MEGA) || defined(ARDUINO_AVR_MEGA2560)) + +static tpfNmBspIsr gpfIsr; + +volatile uint8_t *_receivePortRegister; +volatile uint8_t *_pcint_maskreg; +uint8_t _receiveBitMask; +volatile uint8_t prev_pin_read = 1; + +uint8_t rx_pin_read() +{ + return *_receivePortRegister & _receiveBitMask; +} + +#if !IS_MEGA + +#if defined(PCINT0_vect) +ISR(PCINT0_vect) +{ + if (!rx_pin_read() && gpfIsr) + { + gpfIsr(); + } +} +#endif + +#if defined(PCINT1_vect) +ISR(PCINT1_vect, ISR_ALIASOF(PCINT0_vect)); +#endif + +#if defined(PCINT2_vect) +ISR(PCINT2_vect, ISR_ALIASOF(PCINT0_vect)); +#endif + +#if defined(PCINT3_vect) +ISR(PCINT3_vect, ISR_ALIASOF(PCINT0_vect)); +#endif + +#endif // !IS_MEGA + +#if defined(TIMER4_OVF_vect) +ISR(TIMER4_OVF_vect) { + uint8_t curr_pin_read = rx_pin_read(); + if ((curr_pin_read != prev_pin_read) && !curr_pin_read && gpfIsr) + { + gpfIsr(); + } + prev_pin_read = curr_pin_read; +} + +// stategy 3 - start a timer and perform a sort of polling +void attachFakeInterruptToTimer(void) { + TCCR4B = (1< I2C/UART. Parameter:tstrNmI2cDefault/tstrNmUartDefault */ +#define NM_BUS_IOCTL_W ((uint8)1) /*!< Write only ==> I2C/UART. Parameter type tstrNmI2cDefault/tstrNmUartDefault*/ +#define NM_BUS_IOCTL_W_SPECIAL ((uint8)2) /*!< Write two buffers within the same transaction + (same start/stop conditions) ==> I2C only. Parameter:tstrNmI2cSpecial */ +#define NM_BUS_IOCTL_RW ((uint8)3) /*!< Read/Write at the same time ==> SPI only. Parameter:tstrNmSpiRw */ + +#define NM_BUS_IOCTL_WR_RESTART ((uint8)4) /*!< Write buffer then made restart condition then read ==> I2C only. parameter:tstrNmI2cSpecial */ +/** +* @struct tstrNmBusCapabilities +* @brief Structure holding bus capabilities information +* @sa NM_BUS_TYPE_I2C, NM_BUS_TYPE_SPI +*/ +typedef struct +{ + uint16 u16MaxTrxSz; /*!< Maximum transfer size. Must be >= 16 bytes*/ +} tstrNmBusCapabilities; + +/** +* @struct tstrNmI2cDefault +* @brief Structure holding I2C default operation parameters +* @sa NM_BUS_IOCTL_R, NM_BUS_IOCTL_W +*/ +typedef struct +{ + uint8 u8SlaveAdr; + uint8 *pu8Buf; /*!< Operation buffer */ + uint16 u16Sz; /*!< Operation size */ +} tstrNmI2cDefault; + +/** +* @struct tstrNmI2cSpecial +* @brief Structure holding I2C special operation parameters +* @sa NM_BUS_IOCTL_W_SPECIAL +*/ +typedef struct +{ + uint8 u8SlaveAdr; + uint8 *pu8Buf1; /*!< pointer to the 1st buffer */ + uint8 *pu8Buf2; /*!< pointer to the 2nd buffer */ + uint16 u16Sz1; /*!< 1st buffer size */ + uint16 u16Sz2; /*!< 2nd buffer size */ +} tstrNmI2cSpecial; + +/** +* @struct tstrNmSpiRw +* @brief Structure holding SPI R/W parameters +* @sa NM_BUS_IOCTL_RW +*/ +typedef struct +{ + uint8 *pu8InBuf; /*!< pointer to input buffer. + Can be set to null and in this case zeros should be sent at MOSI */ + uint8 *pu8OutBuf; /*!< pointer to output buffer. + Can be set to null and in this case data from MISO can be ignored */ + uint16 u16Sz; /*!< Transfere size */ +} tstrNmSpiRw; + + +/** +* @struct tstrNmUartDefault +* @brief Structure holding UART default operation parameters +* @sa NM_BUS_IOCTL_R, NM_BUS_IOCTL_W +*/ +typedef struct +{ + uint8 *pu8Buf; /*!< Operation buffer */ + uint16 u16Sz; /*!< Operation size */ +} tstrNmUartDefault; +/*!< Bus capabilities. This structure must be declared at platform specific bus wrapper */ +extern tstrNmBusCapabilities egstrNmBusCapabilities; + + +#ifdef __cplusplus + extern "C" { + #endif +/** +* @fn nm_bus_init +* @brief Initialize the bus wrapper +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_bus_init(void *); + +/** +* @fn nm_bus_ioctl +* @brief send/receive from the bus +* @param [in] u8Cmd +* IOCTL command for the operation +* @param [in] pvParameter +* Arbitrary parameter depending on IOCTL +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +* @note For SPI only, it's important to be able to send/receive at the same time +*/ +sint8 nm_bus_ioctl(uint8 u8Cmd, void* pvParameter); + +/** +* @fn nm_bus_deinit +* @brief De-initialize the bus wrapper +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_bus_deinit(void); + +/* +* @fn nm_bus_reinit +* @brief re-initialize the bus wrapper +* @param [in] void *config +* re-init configuration data +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_bus_reinit(void *); +/* +* @fn nm_bus_get_chip_type +* @brief get chip type +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +#ifdef CONF_WINC_USE_UART +uint8 nm_bus_get_chip_type(void); +#endif +#ifdef __cplusplus + } + #endif + +#endif /*_NM_BUS_WRAPPER_H_*/ diff --git a/feather_sensor_lte/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp b/feather_sensor_lte/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp new file mode 100644 index 0000000..22a7473 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp @@ -0,0 +1,200 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 bus wrapper APIs implementation. + * + * Copyright (c) 2014 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include +#include + +/* + * Variants may define an alternative SPI instace to use for WiFi101. + * If not defined the following defaults are used: + * WINC1501_SPI - SPI + */ +#if !defined(WINC1501_SPI) + #define WINC1501_SPI SPI +#endif + +extern "C" { + +#include "bsp/include/nm_bsp.h" +#include "bsp/include/nm_bsp_arduino.h" +#include "common/include/nm_common.h" +#include "bus_wrapper/include/nm_bus_wrapper.h" + +} + +#define NM_BUS_MAX_TRX_SZ 256 + +tstrNmBusCapabilities egstrNmBusCapabilities = +{ + NM_BUS_MAX_TRX_SZ +}; + +static const SPISettings wifi_SPISettings(12000000L, MSBFIRST, SPI_MODE0); + +static sint8 spi_rw(uint8* pu8Mosi, uint8* pu8Miso, uint16 u16Sz) +{ + uint8 u8Dummy = 0; + uint8 u8SkipMosi = 0, u8SkipMiso = 0; + + if (!pu8Mosi) { + pu8Mosi = &u8Dummy; + u8SkipMosi = 1; + } + else if(!pu8Miso) { + pu8Miso = &u8Dummy; + u8SkipMiso = 1; + } + else { + return M2M_ERR_BUS_FAIL; + } + + WINC1501_SPI.beginTransaction(wifi_SPISettings); + digitalWrite(gi8Winc1501CsPin, LOW); + + while (u16Sz) { + *pu8Miso = WINC1501_SPI.transfer(*pu8Mosi); + + u16Sz--; + if (!u8SkipMiso) + pu8Miso++; + if (!u8SkipMosi) + pu8Mosi++; + } + + digitalWrite(gi8Winc1501CsPin, HIGH); + WINC1501_SPI.endTransaction(); + + return M2M_SUCCESS; +} + +extern "C" { + +/* +* @fn nm_bus_init +* @brief Initialize the bus wrapper +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M.S.M +* @date 28 oct 2013 +* @version 1.0 +*/ +sint8 nm_bus_init(void * /* pvInitValue */) +{ + sint8 result = M2M_SUCCESS; + + /* Configure SPI peripheral. */ + WINC1501_SPI.begin(); + + /* Configure CS PIN. */ + pinMode(gi8Winc1501CsPin, OUTPUT); + digitalWrite(gi8Winc1501CsPin, HIGH); + + /* Reset WINC1500. */ + nm_bsp_reset(); + nm_bsp_sleep(1); + + return result; +} + +/* +* @fn nm_bus_ioctl +* @brief send/receive from the bus +* @param[IN] u8Cmd +* IOCTL command for the operation +* @param[IN] pvParameter +* Arbitrary parameter depenging on IOCTL +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M.S.M +* @date 28 oct 2013 +* @note For SPI only, it's important to be able to send/receive at the same time +* @version 1.0 +*/ +sint8 nm_bus_ioctl(uint8 u8Cmd, void* pvParameter) +{ + sint8 s8Ret = 0; + switch(u8Cmd) + { + case NM_BUS_IOCTL_RW: { + tstrNmSpiRw *pstrParam = (tstrNmSpiRw *)pvParameter; + s8Ret = spi_rw(pstrParam->pu8InBuf, pstrParam->pu8OutBuf, pstrParam->u16Sz); + } + break; + default: + s8Ret = -1; + M2M_ERR("invalide ioclt cmd\n"); + break; + } + + return s8Ret; +} + +/* +* @fn nm_bus_deinit +* @brief De-initialize the bus wrapper +* @author M.S.M +* @date 28 oct 2013 +* @version 1.0 +*/ +sint8 nm_bus_deinit(void) +{ + WINC1501_SPI.end(); + return 0; +} + +/* +* @fn nm_bus_reinit +* @brief re-initialize the bus wrapper +* @param [in] void *config +* re-init configuration data +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Dina El Sissy +* @date 19 Sept 2012 +* @version 1.0 +*/ +sint8 nm_bus_reinit(void* /* config */) +{ + return M2M_SUCCESS; +} + +} // extern "C" + diff --git a/feather_sensor_lte/libraries/WiFi101/src/common/include/nm_common.h b/feather_sensor_lte/libraries/WiFi101/src/common/include/nm_common.h new file mode 100644 index 0000000..d66fbdb --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/common/include/nm_common.h @@ -0,0 +1,153 @@ +/** + * + * \file + * + * \brief WINC Driver Common API Declarations. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NM_COMMON_H_ +#define _NM_COMMON_H_ + +#include "bsp/include/nm_bsp.h" +#include "common/include/nm_debug.h" + +/**@defgroup CommonDefines CommonDefines + * @ingroup WlanDefines + */ +/**@{*/ +#define M2M_TIME_OUT_DELAY 10000 + +/*states*/ +#define M2M_SUCCESS ((sint8)0) +#define M2M_ERR_SEND ((sint8)-1) +#define M2M_ERR_RCV ((sint8)-2) +#define M2M_ERR_MEM_ALLOC ((sint8)-3) +#define M2M_ERR_TIME_OUT ((sint8)-4) +#define M2M_ERR_INIT ((sint8)-5) +#define M2M_ERR_BUS_FAIL ((sint8)-6) +#define M2M_NOT_YET ((sint8)-7) +#define M2M_ERR_FIRMWARE ((sint8)-8) +#define M2M_SPI_FAIL ((sint8)-9) +#define M2M_ERR_FIRMWARE_bURN ((sint8)-10) +#define M2M_ACK ((sint8)-11) +#define M2M_ERR_FAIL ((sint8)-12) +#define M2M_ERR_FW_VER_MISMATCH ((sint8)-13) +#define M2M_ERR_SCAN_IN_PROGRESS ((sint8)-14) +#define M2M_ERR_INVALID_ARG ((sint8)-15) +#define M2M_ERR_INVALID ((sint8)-16) + +/*i2c MAASTER ERR*/ +#define I2C_ERR_LARGE_ADDRESS 0xE1UL /*the address exceed the max addressing mode in i2c flash*/ +#define I2C_ERR_TX_ABRT 0xE2UL /*NO ACK from slave*/ +#define I2C_ERR_OVER_SIZE 0xE3UL /**/ +#define ERR_PREFIX_NMIS 0xE4UL /*wrong first four byte in flash NMIS*/ +#define ERR_FIRMEWARE_EXCEED_SIZE 0xE5UL /*Total size of firmware exceed the max size 256k*/ +/**/ +#define PROGRAM_START 0x26961735UL +#define BOOT_SUCCESS 0x10add09eUL +#define BOOT_START 0x12345678UL + + +#define NBIT31 (0x80000000) +#define NBIT30 (0x40000000) +#define NBIT29 (0x20000000) +#define NBIT28 (0x10000000) +#define NBIT27 (0x08000000) +#define NBIT26 (0x04000000) +#define NBIT25 (0x02000000) +#define NBIT24 (0x01000000) +#define NBIT23 (0x00800000) +#define NBIT22 (0x00400000) +#define NBIT21 (0x00200000) +#define NBIT20 (0x00100000) +#define NBIT19 (0x00080000) +#define NBIT18 (0x00040000) +#define NBIT17 (0x00020000) +#define NBIT16 (0x00010000) +#define NBIT15 (0x00008000) +#define NBIT14 (0x00004000) +#define NBIT13 (0x00002000) +#define NBIT12 (0x00001000) +#define NBIT11 (0x00000800) +#define NBIT10 (0x00000400) +#define NBIT9 (0x00000200) +#define NBIT8 (0x00000100) +#define NBIT7 (0x00000080) +#define NBIT6 (0x00000040) +#define NBIT5 (0x00000020) +#define NBIT4 (0x00000010) +#define NBIT3 (0x00000008) +#define NBIT2 (0x00000004) +#define NBIT1 (0x00000002) +#define NBIT0 (0x00000001) + +#define M2M_MAX(A,B) ((A) > (B) ? (A) : (B)) +#define M2M_SEL(x,m1,m2,m3) ((x>1)?((x>2)?(m3):(m2)):(m1)) +#define WORD_ALIGN(val) (((val) & 0x03) ? ((val) + 4 - ((val) & 0x03)) : (val)) + + + +#define DATA_PKT_OFFSET 4 + +#ifndef BIG_ENDIAN +#define BYTE_0(word) ((uint8)(((word) >> 0 ) & 0x000000FFUL)) +#define BYTE_1(word) ((uint8)(((word) >> 8 ) & 0x000000FFUL)) +#define BYTE_2(word) ((uint8)(((word) >> 16) & 0x000000FFUL)) +#define BYTE_3(word) ((uint8)(((word) >> 24) & 0x000000FFUL)) +#else +#define BYTE_0(word) ((uint8)(((word) >> 24) & 0x000000FFUL)) +#define BYTE_1(word) ((uint8)(((word) >> 16) & 0x000000FFUL)) +#define BYTE_2(word) ((uint8)(((word) >> 8 ) & 0x000000FFUL)) +#define BYTE_3(word) ((uint8)(((word) >> 0 ) & 0x000000FFUL)) +#endif + +/**@}*/ +#ifdef __cplusplus + extern "C" { + #endif +NMI_API void m2m_memcpy(uint8* pDst,uint8* pSrc,uint32 sz); +NMI_API void m2m_memset(uint8* pBuf,uint8 val,uint32 sz); +NMI_API uint16 m2m_strlen(uint8 * pcStr); +NMI_API sint8 m2m_memcmp(uint8 *pu8Buff1,uint8 *pu8Buff2 ,uint32 u32Size); +NMI_API uint8 m2m_strncmp(uint8 *pcS1, uint8 *pcS2, uint16 u16Len); +NMI_API uint8 * m2m_strstr(uint8 *pcIn, uint8 *pcStr); +NMI_API uint8 m2m_checksum(uint8* buf, int sz); + +#ifdef __cplusplus +} + #endif +#endif /*_NM_COMMON_H_*/ diff --git a/feather_sensor_lte/libraries/WiFi101/src/common/include/nm_debug.h b/feather_sensor_lte/libraries/WiFi101/src/common/include/nm_debug.h new file mode 100644 index 0000000..a710f6c --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/common/include/nm_debug.h @@ -0,0 +1,95 @@ +/** + * + * \file + * + * \brief This module contains debug APIs declarations. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NM_DEBUG_H_ +#define _NM_DEBUG_H_ + +#include "bsp/include/nm_bsp.h" +#include "bsp/include/nm_bsp_internal.h" + +/**@defgroup DebugDefines DebugDefines + * @ingroup WlanDefines + */ +/**@{*/ + + +#define M2M_LOG_NONE 0 +#define M2M_LOG_ERROR 1 +#define M2M_LOG_INFO 2 +#define M2M_LOG_REQ 3 +#define M2M_LOG_DBG 4 + +#if (defined __APS3_CORTUS__) +#define M2M_LOG_LEVEL M2M_LOG_INFO +#else +#define M2M_LOG_LEVEL M2M_LOG_REQ +#endif + + +#define M2M_ERR(...) +#define M2M_INFO(...) +#define M2M_REQ(...) +#define M2M_DBG(...) +#define M2M_PRINT(...) + +#if (CONF_WINC_DEBUG == 1) +#undef M2M_PRINT +#define M2M_PRINT(...) do{CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) +#if (M2M_LOG_LEVEL >= M2M_LOG_ERROR) +#undef M2M_ERR +#define M2M_ERR(...) do{CONF_WINC_PRINTF("(APP)(ERR)[%s][%d]",__FUNCTION__,__LINE__); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) +#if (M2M_LOG_LEVEL >= M2M_LOG_INFO) +#undef M2M_INFO +#define M2M_INFO(...) do{CONF_WINC_PRINTF("(APP)(INFO)"); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) +#if (M2M_LOG_LEVEL >= M2M_LOG_REQ) +#undef M2M_REQ +#define M2M_REQ(...) do{CONF_WINC_PRINTF("(APP)(R)"); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) +#if (M2M_LOG_LEVEL >= M2M_LOG_DBG) +#undef M2M_DBG +#define M2M_DBG(...) do{CONF_WINC_PRINTF("(APP)(DBG)[%s][%d]",__FUNCTION__,__LINE__); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) +#endif /*M2M_LOG_DBG*/ +#endif /*M2M_LOG_REQ*/ +#endif /*M2M_LOG_INFO*/ +#endif /*M2M_LOG_ERROR*/ +#endif /*CONF_WINC_DEBUG */ + +/**@}*/ +#endif /* _NM_DEBUG_H_ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/common/source/nm_common.c b/feather_sensor_lte/libraries/WiFi101/src/common/source/nm_common.c new file mode 100644 index 0000000..8b3c941 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/common/source/nm_common.c @@ -0,0 +1,136 @@ +/** + * + * \file + * + * \brief This module contains common APIs declarations. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +#include "common/include/nm_common.h" + +void m2m_memcpy(uint8* pDst,uint8* pSrc,uint32 sz) +{ + if(sz == 0) return; + do + { + *pDst = *pSrc; + pDst++; + pSrc++; + }while(--sz); +} +uint8 m2m_checksum(uint8* buf, int sz) +{ + uint8 cs = 0; + while(--sz) + { + cs ^= *buf; + buf++; + } + + return cs; +} + +void m2m_memset(uint8* pBuf,uint8 val,uint32 sz) +{ + if(sz == 0) return; + do + { + *pBuf = val; + pBuf++; + }while(--sz); +} + +uint16 m2m_strlen(uint8 * pcStr) +{ + uint16 u16StrLen = 0; + while(*pcStr) + { + u16StrLen ++; + pcStr++; + } + return u16StrLen; +} + +uint8 m2m_strncmp(uint8 *pcS1, uint8 *pcS2, uint16 u16Len) +{ + for ( ; u16Len > 0; pcS1++, pcS2++, --u16Len) + if (*pcS1 != *pcS2) + return ((*(uint8 *)pcS1 < *(uint8 *)pcS2) ? -1 : +1); + else if (*pcS1 == '\0') + return 0; + return 0; +} + +/* Finds the occurance of pcStr in pcIn. +If pcStr is part of pcIn it returns a valid pointer to the start of pcStr within pcIn. +Otherwise a NULL Pointer is returned. +*/ +uint8 * m2m_strstr(uint8 *pcIn, uint8 *pcStr) +{ + uint8 u8c; + uint16 u16StrLen; + + u8c = *pcStr++; + if (!u8c) + return (uint8 *) pcIn; // Trivial empty string case + + u16StrLen = m2m_strlen(pcStr); + do { + uint8 u8Sc; + + do { + u8Sc = *pcIn++; + if (!u8Sc) + return (uint8 *) 0; + } while (u8Sc != u8c); + } while (m2m_strncmp(pcIn, pcStr, u16StrLen) != 0); + + return (uint8 *) (pcIn - 1); +} + +sint8 m2m_memcmp(uint8 *pu8Buff1,uint8 *pu8Buff2 ,uint32 u32Size) +{ + uint32 i; + sint8 s8Result = 0; + for(i = 0 ; i < u32Size ; i++) + { + if(pu8Buff1[i] != pu8Buff2[i]) + { + s8Result = 1; + break; + } + } + return s8Result; +} diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/include/ecc_types.h b/feather_sensor_lte/libraries/WiFi101/src/driver/include/ecc_types.h new file mode 100644 index 0000000..764c3b9 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/include/ecc_types.h @@ -0,0 +1,245 @@ +/** + * + * \file + * + * \brief WINC Application Interface Internal Types. + * + * Copyright (c) 2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef __ECC_TYPES_H__ +#define __ECC_TYPES_H__ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "m2m_types.h" + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + + +#define ECC_LARGEST_CURVE_SIZE (32) +/*!< + The size of the the largest supported EC. For now, assuming + the 256-bit EC is the largest supported curve type. +*/ + + +#define ECC_POINT_MAX_SIZE ECC_LARGEST_CURVE_SIZE +/*!< + Maximum size of one coordinate of an EC point. +*/ + + +#define ECC_POINT_MAX_SIZE_WORDS (ECC_POINT_MAX_SIZE / 4) +/*!< + SIZE in 32-bit words. +*/ + +#if 0 +#define ECC_NUM_SUPP_CURVES ((sizeof(gastrECCSuppList)) / (sizeof(tstrEllipticCurve))) +#endif +/*!< +*/ + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +/*! +@enum \ + tenuEcNamedCurve + +@brief EC Named Curves + + Defines a list of supported ECC named curves. +*/ +typedef enum EcNamedCurve{ + EC_SECP192R1 = 19, + /*!< + It is defined by NIST as P192 and by the SEC Group as secp192r1. + */ + EC_SECP256R1 = 23, + /*!< + It is defined by NIST as P256 and by the SEC Group as secp256r1. + */ + EC_SECP384R1 = 24, + /*!< + It is defined by NIST as P384 and by the SEC Group as secp384r1. + */ + EC_SECP521R1 = 25, + /*!< + It is defined by NIST as P521 and by the SEC Group as secp521r1. + */ + EC_UNKNOWN = 255 +}tenuEcNamedCurve; + + +/*! +@struct \ + tstrECPoint + +@brief Elliptic Curve point representation +*/ +typedef struct EcPoint{ + uint8 X[ECC_POINT_MAX_SIZE]; + /*!< + The X-coordinate of the ec point. + */ + uint8 Y[ECC_POINT_MAX_SIZE]; + /*!< + The Y-coordinate of the ec point. + */ + uint16 u16Size; + /*!< + Point size in bytes (for each of the coordinates). + */ + uint16 u16PrivKeyID; + /*!< + ID for the corresponding private key. + */ +}tstrECPoint; + + +/*! +@struct \ + tstrECDomainParam + +@brief ECC Curve Domain Parameters + + The structure defines the ECC domain parameters for curves defined over prime finite fields. +*/ +typedef struct EcDomainParam{ + uint32 p[ECC_POINT_MAX_SIZE_WORDS]; + uint32 a[ECC_POINT_MAX_SIZE_WORDS]; + uint32 b[ECC_POINT_MAX_SIZE_WORDS]; + tstrECPoint G; +}tstrECDomainParam; + + +/*! +@struct \ + tstrEllipticCurve + +@brief + Definition of an elliptic curve +*/ +typedef struct{ + tenuEcNamedCurve enuType; + tstrECDomainParam strParam; +}tstrEllipticCurve; + + +typedef enum{ + ECC_REQ_NONE, + ECC_REQ_CLIENT_ECDH, + ECC_REQ_SERVER_ECDH, + ECC_REQ_GEN_KEY, + ECC_REQ_SIGN_GEN, + ECC_REQ_SIGN_VERIFY +}tenuEccREQ; + + +typedef struct{ + tstrECPoint strPubKey; + uint8 au8Key[ECC_POINT_MAX_SIZE]; +}tstrEcdhReqInfo; + + +typedef struct{ + uint32 u32nSig; +}tstrEcdsaVerifyReqInfo; + + +typedef struct{ + uint16 u16CurveType; + uint16 u16HashSz; +}tstrEcdsaSignReqInfo; + + +typedef struct{ + uint16 u16REQ; + uint16 u16Status; + uint32 u32UserData; + uint32 u32SeqNo; + union{ + tstrEcdhReqInfo strEcdhREQ; + tstrEcdsaSignReqInfo strEcdsaSignREQ; + tstrEcdsaVerifyReqInfo strEcdsaVerifyREQ; + }; +}tstrEccReqInfo; + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +GLOBALS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#if 0 +static tstrEllipticCurve gastrECCSuppList[] = { + { + EC_SECP256R1, + { + {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF}, + {0xFFFFFFFC, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF}, + {0x27D2604B, 0x3BCE3C3E, 0xCC53B0F6, 0x651D06B0, 0x769886BC, 0xB3EBBD55, 0xAA3A93E7, 0x5AC635D8}, + { + { + 0x6B, 0x17, 0xD1, 0xF2, 0xE1, 0x2C, 0x42, 0x47, 0xF8, 0xBC, 0xE6, 0xE5, 0x63, 0xA4, 0x40, 0xF2, + 0x77, 0x03, 0x7D, 0x81, 0x2D, 0xEB, 0x33, 0xA0, 0xF4, 0xA1, 0x39, 0x45, 0xD8, 0x98, 0xC2, 0x96 + }, + { + 0x4F, 0xE3, 0x42, 0xE2, 0xFE, 0x1A, 0x7F, 0x9B, 0x8E, 0xE7, 0xEB, 0x4A, 0x7C, 0x0F, 0x9E, 0x16, + 0x2B, 0xCE, 0x33, 0x57, 0x6B, 0x31, 0x5E, 0xCE, 0xCB, 0xB6, 0x40, 0x68, 0x37, 0xBF, 0x51, 0xF5 + }, + 32 + } + } + } +}; +#endif + +/*!< + List of supported Elliptic Curves ordered by security level (most secure curve is at index ZERO). +*/ + + + +#endif /* __ECC_TYPES_H__ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_ate_mode.h b/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_ate_mode.h new file mode 100644 index 0000000..a17d298 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_ate_mode.h @@ -0,0 +1,732 @@ +/** + * + * \file + * + * \brief WINC ATE Test Driver Interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifdef _M2M_ATE_FW_ + +#ifndef _M2M_ATE_MODE_H_ +#define _M2M_ATE_MODE_H_ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#include "common/include/nm_common.h" +#include "driver/include/m2m_types.h" + +/** \defgroup m2m_ate ATE +*/ +/**@defgroup ATEDefine Defines + * @ingroup m2m_ate + * @{ + */ +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#define M2M_ATE_MAX_NUM_OF_RATES (20) +/*!< +Maximum number of all rates (b,g and n) + */ +#define M2M_ATE_MAX_FRAME_LENGTH (1024) +/*!< Maximum number of length for each frame + */ +#define M2M_ATE_MIN_FRAME_LENGTH (1) +/*!< Minimum number of length for each frame + */ +#define M2M_ATE_SUCCESS (M2M_SUCCESS) +/*!< No Error and operation has been completed successfully. +*/ +#define M2M_ATE_ERR_VALIDATE (M2M_ERR_FAIL) +/*!< Error in parameters passed to functions. + */ +#define M2M_ATE_ERR_TX_ALREADY_RUNNING (-1) +/*!< Error in starting a transmission test. Another test is already running and its not allowed to start another ATE test. + */ +#define M2M_ATE_ERR_RX_ALREADY_RUNNING (-2) +/*!< Error in starting a reception test. Another test is already running and its not allowed to start another ATE test. + */ +#define M2M_ATE_ERR_UNHANDLED_CASE (-3) +/*!< Invalid case. + */ +#define M2M_ATE_RX_DISABLE_DA 0x0 +/*!< Filter selection for received frames: Disable filtering received frames by the destination address. + */ +#define M2M_ATE_RX_ENABLE_DA 0x1 +/*!< Filter selection for received frames: Enable filtering received frames by the destination address. + */ +#define M2M_ATE_RX_DISABLE_SA 0x0 +/*!< Filter selection for received frames: Disable filtering received frames by the source address. + */ +#define M2M_ATE_RX_ENABLE_SA 0x1 +/*!< Filter selection for received frames: Enable filtering received frames by the source address. + */ +#define M2M_ATE_DISABLE_SELF_MACADDR 0x0 +/*!\n",ret); + while(1); + } + //Initialize the OTA module + m2m_ota_init(OtaUpdateCb,NULL); + //connect to AP that provide connection to the OTA server + m2m_wifi_default_connect(); + + while(1) + { + + //Handle the app state machine plus the WINC event handler + while(m2m_wifi_handle_events(NULL) != M2M_SUCCESS) { + + } + + } +} +@endcode + +*/ +NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl); + /**@}*/ +/** @defgroup OtaStartUpdatefn m2m_ota_start_update_crt +* @ingroup WLANAPI +* Request OTA start for cortus application image using the downloaded URL, the OTA module will download the OTA image and ensure integrity of the image, +* and update the validity of the image in control structure. Switching to that image requires calling @ref m2m_ota_switch_crt API. +* As a prerequisite @ref m2m_ota_init should be called before using @ref m2m_ota_start_update_crt(). +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl); + +@param [in] u8DownloadUrl + The cortus application image url. +@warning + Calling this API does not guarantee cortus application image update, It depends on the connection with the download server and the validity of the image. + If the API response is failure this may invalidate the roll-back image if it was previously valid, since the WINC does not have any internal memory + except the flash roll-back image location to validate the downloaded image from + +@see + m2m_ota_init + tpfOtaUpdateCb + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl); + /**@}*/ +/** @defgroup OtaRollbackfn m2m_ota_rollback +* @ingroup WLANAPI + Request OTA Roll-back to the old (other) WINC image, the WINC firmware will check the validation of the Roll-back image + and switch to it if it is valid. + If the API response is success, system restart is required (re-initialize the driver with hardware rest) update the host driver version may + be required if it is did not match the minimum version supported by the WINC firmware. + +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ota_rollback(void); + +@sa + m2m_ota_init + m2m_ota_start_update + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_rollback(void); + /**@}*/ +/** @defgroup OtaRollbackfn m2m_ota_rollback_crt +* @ingroup WLANAPI + Request Cortus application OTA Roll-back to the old (other) cortus application image, the WINC firmware will check the validation of the Roll-back image + and switch to it if it is valid. + If the API response is success, system restart is required (re-initialize the driver with hardware rest) update the host driver version may + be required. + +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ota_rollback_crt(void); + +@sa + m2m_ota_init + m2m_ota_start_update_crt + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_rollback_crt(void); + /**@}*/ +/** @defgroup OtaAbortfn m2m_ota_abort +* @ingroup WLANAPI + Request abort of current OTA download. + The WINC firmware will terminate the OTA download if one is in progress. + If no download is in progress, the API will respond with failure. +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ota_abort(void); + +@return + The function returns @ref M2M_SUCCESS for successful operation and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_abort(void); + /**@}*/ + /**@}*/ +/** @defgroup OtaSwitchFirmware m2m_ota_switch_firmware +* @ingroup WLANAPI +* Switch to the upgraded Firmware, that API will update the control structure working image to the upgraded image + take effect will be on the next system restart +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ota_switch_firmware(void); + +@warning + It is important to note that if the API succeeds, system restart is required (re-initializing the driver with hardware reset) updating the host driver version may be required + if it does not match the minimum driver version supported by the WINC's firmware. +@sa + m2m_ota_init + m2m_ota_start_update + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_switch_firmware(void); + /**@}*/ + /**@}*/ +/** @defgroup OtaSwitchFirmware m2m_ota_switch_crt +* @ingroup WLANAPI +* Switch to the upgraded cortus application, that API will update the control structure working image to the upgraded image + take effect will be on the next system restart +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ota_switch_firmware(void); + +@warning + It is important to note that if the API succeeds, system restart is required (re-initializing the driver with hardware reset) updating the host driver version may be required + if it does not match the minimum driver version supported by the WINC's firmware. +@sa + m2m_ota_init + m2m_ota_start_update_crt + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_switch_crt(void); +/*! +@fn \ + NMI_API sint8 m2m_ota_get_firmware_version(void); + +@brief + Get the OTA Firmware version. + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_get_firmware_version(tstrM2mRev *pstrRev); + /**@}*/ +NMI_API sint8 m2m_ota_test(void); + +#ifdef __cplusplus +} +#endif +#endif /* __M2M_OTA_H__ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_periph.h b/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_periph.h new file mode 100644 index 0000000..1012882 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_periph.h @@ -0,0 +1,411 @@ +/** + * + * \file + * + * \brief WINC Peripherals Application Interface. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _M2M_PERIPH_H_ +#define _M2M_PERIPH_H_ + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +#include "common/include/nm_common.h" +#include "driver/include/m2m_types.h" + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*! +@struct \ + tstrPerphInitParam + +@brief + Peripheral module initialization parameters. +*/ +typedef struct { + void * arg; +} tstrPerphInitParam; + + +/*! +@enum \ + tenuGpioNum + +@brief + A list of GPIO numbers configurable through the m2m_periph module. +*/ +typedef enum { + M2M_PERIPH_GPIO3, /*!< GPIO15 pad */ + M2M_PERIPH_GPIO4, /*!< GPIO16 pad */ + M2M_PERIPH_GPIO5, /*!< GPIO18 pad */ + M2M_PERIPH_GPIO6, /*!< GPIO18 pad */ + M2M_PERIPH_GPIO15, /*!< GPIO15 pad */ + M2M_PERIPH_GPIO16, /*!< GPIO16 pad */ + M2M_PERIPH_GPIO18, /*!< GPIO18 pad */ + M2M_PERIPH_GPIO_MAX +} tenuGpioNum; + + +/*! +@enum \ + tenuI2cMasterSclMuxOpt + +@brief + Allowed pin multiplexing options for I2C master SCL signal. +*/ +typedef enum { + M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_HOST_WAKEUP, /*!< I2C master SCL is avaiable on HOST_WAKEUP. */ + M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_SD_DAT3, /*!< I2C master SCL is avaiable on SD_DAT3 (GPIO 7). */ + M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_GPIO13, /*!< I2C master SCL is avaiable on GPIO 13. */ + M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_GPIO4, /*!< I2C master SCL is avaiable on GPIO 4.*/ + M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_I2C_SCL, /*!< I2C master SCL is avaiable on I2C slave SCL. */ + M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_NUM +} tenuI2cMasterSclMuxOpt; + +/*! +@enum \ + tenuI2cMasterSdaMuxOpt + +@brief + Allowed pin multiplexing options for I2C master SDA signal. +*/ +typedef enum { + M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_RTC_CLK , /*!< I2C master SDA is avaiable on RTC_CLK. */ + M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_SD_CLK, /*!< I2C master SDA is avaiable on SD_CLK (GPIO 8). */ + M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_GPIO14, /*!< I2C master SDA is avaiable on GPIO 14. */ + M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_GPIO6, /*!< I2C master SDA is avaiable on GPIO 6.*/ + M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_I2C_SDA, /*!< I2C master SDA is avaiable on I2C slave SDA. */ + M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_NUM +} tenuI2cMasterSdaMuxOpt; + + +/*! +@struct \ + tstrI2cMasterInitParam + +@brief + I2C master configuration parameters. +@sa + tenuI2cMasterSclMuxOpt + tenuI2cMasterSdaMuxOpt +*/ +typedef struct { + uint8 enuSclMuxOpt; /*!< SCL multiplexing option. Allowed value are defined in tenuI2cMasterSclMuxOpt */ + uint8 enuSdaMuxOpt; /*!< SDA multiplexing option. Allowed value are defined in tenuI2cMasterSdaMuxOpt */ + uint8 u8ClkSpeedKHz; /*!< I2C master clock speed in KHz. */ +} tstrI2cMasterInitParam; + +/*! +@enum \ + tenuI2cMasterFlags + +@brief + Bitwise-ORed flags for use in m2m_periph_i2c_master_write and m2m_periph_i2c_master_read +@sa + m2m_periph_i2c_master_write + m2m_periph_i2c_master_read +*/ +typedef enum { + I2C_MASTER_NO_FLAGS = 0x00, + /*!< No flags. */ + I2C_MASTER_NO_STOP = 0x01, + /*!< No stop bit after this transaction. Useful for scattered buffer read/write operations. */ + I2C_MASTER_NO_START = 0x02, + /*!< No start bit at the beginning of this transaction. Useful for scattered buffer read/write operations.*/ +} tenuI2cMasterFlags; + +/*! +@enum \ + tenuPullupMask + +@brief + Bitwise-ORed flags for use in m2m_perph_pullup_ctrl. +@sa + m2m_periph_pullup_ctrl + +*/ +typedef enum { + M2M_PERIPH_PULLUP_DIS_HOST_WAKEUP = (1ul << 0), + M2M_PERIPH_PULLUP_DIS_RTC_CLK = (1ul << 1), + M2M_PERIPH_PULLUP_DIS_IRQN = (1ul << 2), + M2M_PERIPH_PULLUP_DIS_GPIO_3 = (1ul << 3), + M2M_PERIPH_PULLUP_DIS_GPIO_4 = (1ul << 4), + M2M_PERIPH_PULLUP_DIS_GPIO_5 = (1ul << 5), + M2M_PERIPH_PULLUP_DIS_SD_DAT3 = (1ul << 6), + M2M_PERIPH_PULLUP_DIS_SD_DAT2_SPI_RXD = (1ul << 7), + M2M_PERIPH_PULLUP_DIS_SD_DAT1_SPI_SSN = (1ul << 9), + M2M_PERIPH_PULLUP_DIS_SD_CMD_SPI_SCK = (1ul << 10), + M2M_PERIPH_PULLUP_DIS_SD_DAT0_SPI_TXD = (1ul << 11), + M2M_PERIPH_PULLUP_DIS_GPIO_6 = (1ul << 12), + M2M_PERIPH_PULLUP_DIS_SD_CLK = (1ul << 13), + M2M_PERIPH_PULLUP_DIS_I2C_SCL = (1ul << 14), + M2M_PERIPH_PULLUP_DIS_I2C_SDA = (1ul << 15), + M2M_PERIPH_PULLUP_DIS_GPIO_11 = (1ul << 16), + M2M_PERIPH_PULLUP_DIS_GPIO_12 = (1ul << 17), + M2M_PERIPH_PULLUP_DIS_GPIO_13 = (1ul << 18), + M2M_PERIPH_PULLUP_DIS_GPIO_14 = (1ul << 19), + M2M_PERIPH_PULLUP_DIS_GPIO_15 = (1ul << 20), + M2M_PERIPH_PULLUP_DIS_GPIO_16 = (1ul << 21), + M2M_PERIPH_PULLUP_DIS_GPIO_17 = (1ul << 22), + M2M_PERIPH_PULLUP_DIS_GPIO_18 = (1ul << 23), + M2M_PERIPH_PULLUP_DIS_GPIO_19 = (1ul << 24), + M2M_PERIPH_PULLUP_DIS_GPIO_20 = (1ul << 25), + M2M_PERIPH_PULLUP_DIS_GPIO_21 = (1ul << 26), + M2M_PERIPH_PULLUP_DIS_GPIO_22 = (1ul << 27), + M2M_PERIPH_PULLUP_DIS_GPIO_23 = (1ul << 28), + M2M_PERIPH_PULLUP_DIS_GPIO_24 = (1ul << 29), +} tenuPullupMask; + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +#ifdef __cplusplus + extern "C" { +#endif + +/*! +@fn \ + NMI_API sint8 m2m_periph_init(tstrPerphInitParam * param); + +@brief + Initialize the NMC1500 peripheral driver module. + +@param [in] param + Peripheral module initialization structure. See members of tstrPerphInitParam. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tstrPerphInitParam +*/ +NMI_API sint8 m2m_periph_init(tstrPerphInitParam * param); + +/*! +@fn \ + NMI_API sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir); + +@brief + Configure a specific NMC1500 pad as a GPIO and sets its direction (input or output). + +@param [in] u8GpioNum + GPIO number. Allowed values are defined in tenuGpioNum. + +@param [in] u8GpioDir + GPIO direction: Zero = input. Non-zero = output. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuGpioNum +*/ +NMI_API sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir); + +/*! +@fn \ + NMI_API sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal); + +@brief + Set an NMC1500 GPIO output level high or low. + +@param [in] u8GpioNum + GPIO number. Allowed values are defined in tenuGpioNum. + +@param [in] u8GpioVal + GPIO output value. Zero = low, non-zero = high. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuGpioNum +*/ +NMI_API sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal); + +/*! +@fn \ + NMI_API sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal); + +@brief + Read an NMC1500 GPIO input level. + +@param [in] u8GpioNum + GPIO number. Allowed values are defined in tenuGpioNum. + +@param [out] pu8GpioVal + GPIO input value. Zero = low, non-zero = high. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuGpioNum +*/ +NMI_API sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal); + +/*! +@fn \ + NMI_API sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn); + +@brief + Set an NMC1500 GPIO pullup resisitor enable or disable. + +@param [in] u8GpioNum + GPIO number. Allowed values are defined in tenuGpioNum. + +@param [in] u8PullupEn + Zero: pullup disabled. Non-zero: pullup enabled. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuGpioNum +*/ +NMI_API sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn); + +/*! +@fn \ + NMI_API sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param); + +@brief + Initialize and configure the NMC1500 I2C master peripheral. + +@param [in] param + I2C master initialization structure. See members of tstrI2cMasterInitParam. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tstrI2cMasterInitParam +*/ +NMI_API sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param); + +/*! +@fn \ + NMI_API sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags); + +@brief + Write a stream of bytes to the I2C slave device. + +@param [in] u8SlaveAddr + 7-bit I2C slave address. +@param [in] pu8Buf + A pointer to an input buffer which contains a stream of bytes. +@param [in] u16BufLen + Input buffer length in bytes. +@param [in] flags + Write operation bitwise-ORed flags. See tenuI2cMasterFlags. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuI2cMasterFlags +*/ +NMI_API sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags); + + +/*! +@fn \ + NMI_API sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags); + +@brief + Write a stream of bytes to the I2C slave device. + +@param [in] u8SlaveAddr + 7-bit I2C slave address. +@param [out] pu8Buf + A pointer to an output buffer in which a stream of bytes are received. +@param [in] u16BufLen + Max output buffer length in bytes. +@param [out] pu16ReadLen + Actual number of bytes received. +@param [in] flags + Write operation bitwise-ORed flags. See tenuI2cMasterFlags. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuI2cMasterFlags +*/ +NMI_API sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags); + + +/*! +@fn \ + NMI_API sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable); + +@brief + Control the programmable pull-up resistor on the chip pads . + + +@param [in] pinmask + Write operation bitwise-ORed mask for which pads to control. Allowed values are defined in tenuPullupMask. + +@param [in] enable + Set to 0 to disable pull-up resistor. Non-zero will enable the pull-up. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuPullupMask +*/ +NMI_API sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable); + +#ifdef __cplusplus +} +#endif + + +#endif /* _M2M_PERIPH_H_ */ \ No newline at end of file diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_ssl.h b/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_ssl.h new file mode 100644 index 0000000..f5271f0 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_ssl.h @@ -0,0 +1,182 @@ +/** + * + * \file + * + * \brief WINC Application Interface Internal Types. + * + * Copyright (c) 2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/**@defgroup SSLAPI SSL +*/ + +#ifndef __M2M_SSL_H__ +#define __M2M_SSL_H__ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "common/include/nm_common.h" +#include "driver/include/m2m_types.h" +#include "driver/source/nmdrv.h" +#include "ecc_types.h" +#include "socket/include/socket.h" + +/**@defgroup SSLEnums Enumeration/Typedefs + * @ingroup SSLAPI + * @{*/ + +/*! +@typedef \ + void (*tpfAppSslCb) (uint8 u8MsgType, void * pvMsg); + +@brief A callback to get SSL notifications. + +@param[in] u8MsgType +@param[in] pvMsg A structure to provide notification payload. +*/ +typedef void (*tpfAppSSLCb) (uint8 u8MsgType, void * pvMsg); + +/**@} +*/ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/** \defgroup SSLFUNCTIONS Functions +* @ingroup SSLAPI +*/ + +/**@{*/ +/*! + @fn \ m2m_ssl_init(tpfAppSslCb pfAppSslCb); + @brief Initializes the SSL layer. + @param [in] pfAppSslCb + Application SSL callback function. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_init(tpfAppSSLCb pfAppSSLCb); + +/*! + @fn \ NMI_API sint8 m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz) + @brief Sends ECC responses to the WINC + @param [in] strECCResp + ECC Response struct. + @param [in] pu8RspDataBuffe + Pointer of the response data to be sent. + @param [in] u16RspDataSz + Response data size. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz); + +/*! + @fn \ NMI_API sint8 m2m_ssl_send_certs_to_winc(uint8* pu8Buffer, uint32 u32BufferSz) + @brief Sends certificates to the WINC + @param [in] pu8Buffer + Pointer to the certificates. + @param [in] u32BufferSz + Size of the certificates. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_send_certs_to_winc(uint8* pu8Buffer, uint32 u32BufferSz); + +/*! + @fn \ NMI_API sint8 m2m_ssl_retrieve_cert(uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key) + @brief Retrieve the certificate to be verified from the WINC + @param [in] pu16CurveType + Pointer to the certificate curve type. + @param [in] pu8Hash + Pointer to the certificate hash. + @param [in] pu8Sig + Pointer to the certificate signature. + @param [in] pu8Key + Pointer to the certificate Key. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_retrieve_cert(uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key); + +/*! + @fn \ NMI_API sint8 m2m_ssl_retrieve_hash(uint8* pu8Hash, uint16 u16HashSz) + @brief Retrieve the certificate hash + @param [in] pu8Hash + Pointer to the certificate hash. + @param [in] u16HashSz + Hash size. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_retrieve_hash(uint8* pu8Hash, uint16 u16HashSz); + +/*! + @fn \ NMI_API void m2m_ssl_stop_processing_certs(void) + @brief Allow ssl driver to tidy up in case application does not read all available certificates. + @warning This API must only be called if some certificates are left unread. + @return None. +*/ +NMI_API void m2m_ssl_stop_processing_certs(void); + +/*! + @fn \ NMI_API void m2m_ssl_ecc_process_done(void) + @brief Allow ssl driver to tidy up after application has finished processing ecc message. + @warning This API must be called after receiving a SSL callback with type @ref M2M_SSL_REQ_ECC + @return None. +*/ +NMI_API void m2m_ssl_ecc_process_done(void); + +/*! +@fn \ + NMI_API sint8 m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP); + Override the default Active SSL ciphers in the SSL module with a certain combination selected by the caller in the form of + a bitmap containing the required ciphers to be on. + There is no need to call this function if the application will not change the default ciphersuites. + +@param [in] u32SslCsBMP + Bitmap containing the desired ciphers to be enabled for the SSL module. The ciphersuites are defined in + @ref SSLCipherSuiteID. + The default ciphersuites are all ciphersuites supported by the firmware with the exception of ECC ciphersuites. + The caller can override the default with any desired combination, except for combinations involving both RSA + and ECC; if any RSA ciphersuite is enabled, then firmware will disable all ECC ciphersuites. + If u32SslCsBMP does not contain any ciphersuites supported by firmware, then the current active list will not + be changed. + +@return + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) +*/ +sint8 m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP); + + /**@}*/ +#endif /* __M2M_SSL_H__ */ \ No newline at end of file diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_types.h b/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_types.h new file mode 100644 index 0000000..a847f3f --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_types.h @@ -0,0 +1,2383 @@ +/** + * + * \file + * + * \brief WINC Application Interface Internal Types. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef __M2M_WIFI_TYPES_H__ +#define __M2M_WIFI_TYPES_H__ + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#ifndef _BOOT_ +#ifndef _FIRMWARE_ +#include "common/include/nm_common.h" +#else +#include "m2m_common.h" +#endif +#endif + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/**@defgroup WlanDefines Defines + * @ingroup m2m_wifi + */ +/**@{*/ +#define M2M_MAJOR_SHIFT (8) +#define M2M_MINOR_SHIFT (4) +#define M2M_PATCH_SHIFT (0) + +#define M2M_DRV_VERSION_SHIFT (16) +#define M2M_FW_VERSION_SHIFT (0) + +#define M2M_GET_MAJOR(ver_info_hword) ((uint8)((ver_info_hword) >> M2M_MAJOR_SHIFT) & 0xff) +#define M2M_GET_MINOR(ver_info_hword) ((uint8)((ver_info_hword) >> M2M_MINOR_SHIFT) & 0x0f) +#define M2M_GET_PATCH(ver_info_hword) ((uint8)((ver_info_hword) >> M2M_PATCH_SHIFT) & 0x0f) + +#define M2M_GET_FW_VER(ver_info_word) ((uint16) ((ver_info_word) >> M2M_FW_VERSION_SHIFT)) +#define M2M_GET_DRV_VER(ver_info_word) ((uint16) ((ver_info_word) >> M2M_DRV_VERSION_SHIFT)) + +#define M2M_GET_DRV_MAJOR(ver_info_word) M2M_GET_MAJOR(M2M_GET_DRV_VER(ver_info_word)) +#define M2M_GET_DRV_MINOR(ver_info_word) M2M_GET_MINOR(M2M_GET_DRV_VER(ver_info_word)) +#define M2M_GET_DRV_PATCH(ver_info_word) M2M_GET_PATCH(M2M_GET_DRV_VER(ver_info_word)) + +#define M2M_GET_FW_MAJOR(ver_info_word) M2M_GET_MAJOR(M2M_GET_FW_VER(ver_info_word)) +#define M2M_GET_FW_MINOR(ver_info_word) M2M_GET_MINOR(M2M_GET_FW_VER(ver_info_word)) +#define M2M_GET_FW_PATCH(ver_info_word) M2M_GET_PATCH(M2M_GET_FW_VER(ver_info_word)) + +#define M2M_MAKE_VERSION(major, minor, patch) ( \ + ((uint16)((major) & 0xff) << M2M_MAJOR_SHIFT) | \ + ((uint16)((minor) & 0x0f) << M2M_MINOR_SHIFT) | \ + ((uint16)((patch) & 0x0f) << M2M_PATCH_SHIFT)) + +#define M2M_MAKE_VERSION_INFO(fw_major, fw_minor, fw_patch, drv_major, drv_minor, drv_patch) \ + ( \ + ( ((uint32)M2M_MAKE_VERSION((fw_major), (fw_minor), (fw_patch))) << M2M_FW_VERSION_SHIFT) | \ + ( ((uint32)M2M_MAKE_VERSION((drv_major), (drv_minor), (drv_patch))) << M2M_DRV_VERSION_SHIFT)) + +#define REL_19_5_2_VER M2M_MAKE_VERSION_INFO(19,5,2,19,3,0) +#define REL_19_5_1_VER M2M_MAKE_VERSION_INFO(19,5,1,19,3,0) +#define REL_19_5_0_VER M2M_MAKE_VERSION_INFO(19,5,0,19,3,0) +#define REL_19_4_6_VER M2M_MAKE_VERSION_INFO(19,4,6,19,3,0) +#define REL_19_4_5_VER M2M_MAKE_VERSION_INFO(19,4,5,19,3,0) +#define REL_19_4_4_VER M2M_MAKE_VERSION_INFO(19,4,4,19,3,0) +#define REL_19_4_3_VER M2M_MAKE_VERSION_INFO(19,4,3,19,3,0) +#define REL_19_4_2_VER M2M_MAKE_VERSION_INFO(19,4,2,19,3,0) +#define REL_19_4_1_VER M2M_MAKE_VERSION_INFO(19,4,1,19,3,0) +#define REL_19_4_0_VER M2M_MAKE_VERSION_INFO(19,4,0,19,3,0) +#define REL_19_3_1_VER M2M_MAKE_VERSION_INFO(19,3,1,19,3,0) +#define REL_19_3_0_VER M2M_MAKE_VERSION_INFO(19,3,0,19,3,0) +#define REL_19_2_2_VER M2M_MAKE_VERSION_INFO(19,2,2,19,2,0) +#define REL_19_2_1_VER M2M_MAKE_VERSION_INFO(19,2,1,19,2,0) +#define REL_19_2_0_VER M2M_MAKE_VERSION_INFO(19,2,0,19,2,0) +#define REL_19_1_0_VER M2M_MAKE_VERSION_INFO(19,1,0,18,2,0) +#define REL_19_0_0_VER M2M_MAKE_VERSION_INFO(19,0,0,18,1,1) + +/*======*======*======*======* + FIRMWARE VERSION NO INFO + *======*======*======*======*/ + +#define M2M_RELEASE_VERSION_MAJOR_NO (19) +/*!< Firmware Major release version number. +*/ + + +#define M2M_RELEASE_VERSION_MINOR_NO (5) +/*!< Firmware Minor release version number. +*/ + +#define M2M_RELEASE_VERSION_PATCH_NO (2) +/*!< Firmware patch release version number. +*/ + +/*======*======*======*======* + SUPPORTED DRIVER VERSION NO INFO + *======*======*======*======*/ + +#define M2M_MIN_REQ_DRV_VERSION_MAJOR_NO (19) +/*!< Driver Major release version number. +*/ + + +#define M2M_MIN_REQ_DRV_VERSION_MINOR_NO (3) +/*!< Driver Minor release version number. +*/ + +#define M2M_MIN_REQ_DRV_VERSION_PATCH_NO (0) +/*!< Driver patch release version number. +*/ + +#define M2M_MIN_REQ_DRV_SVN_VERSION (0) +/*!< Driver svn version. +*/ + + + +#if !defined(M2M_RELEASE_VERSION_MAJOR_NO) || !defined(M2M_RELEASE_VERSION_MINOR_NO) +#error Undefined version number +#endif + +#define M2M_BUFFER_MAX_SIZE (1600UL - 4) +/*!< Maximum size for the shared packet buffer. + */ + + +#define M2M_MAC_ADDRES_LEN 6 +/*!< The size fo 802 MAC address. + */ + +#define M2M_ETHERNET_HDR_OFFSET 34 +/*!< The offset of the Ethernet header within the WLAN Tx Buffer. + */ + + +#define M2M_ETHERNET_HDR_LEN 14 +/*!< Length of the Etherenet header in bytes. +*/ + + +#define M2M_MAX_SSID_LEN 33 +/*!< Maximum size for the Wi-Fi SSID including the NULL termination. + */ + + +#define M2M_MAX_PSK_LEN 65 +/*!< Maximum size for the WPA PSK including the NULL termination. + */ + +#define M2M_MIN_PSK_LEN 9 +/*!< Maximum size for the WPA PSK including the NULL termination. + */ + +#define M2M_DEVICE_NAME_MAX 48 +/*!< Maximum Size for the device name including the NULL termination. + */ + + +#define M2M_LISTEN_INTERVAL 1 +/*!< The STA uses the Listen Interval parameter to indicate to the AP how + many beacon intervals it shall sleep before it retrieves the queued frames + from the AP. +*/ + +#define MAX_HIDDEN_SITES 4 +/*!< + max number of hidden SSID suuported by scan request +*/ + + +#define M2M_1X_USR_NAME_MAX 21 +/*!< The maximum size of the user name including the NULL termination. + It is used for RADIUS authentication in case of connecting the device to + an AP secured with WPA-Enterprise. +*/ + + +#define M2M_1X_PWD_MAX 41 +/*!< The maximum size of the password including the NULL termination. + It is used for RADIUS authentication in case of connecting the device to + an AP secured with WPA-Enterprise. +*/ + +#define M2M_CUST_IE_LEN_MAX 252 +/*!< The maximum size of IE (Information Element). +*/ + +#define PWR_DEFAULT PWR_HIGH +/********************* + * + * WIFI GROUP requests + */ + +#define M2M_CONFIG_CMD_BASE 1 +/*!< The base value of all the host configuration commands opcodes. +*/ +#define M2M_STA_CMD_BASE 40 +/*!< The base value of all the station mode host commands opcodes. +*/ +#define M2M_AP_CMD_BASE 70 +/*!< The base value of all the Access Point mode host commands opcodes. +*/ +#define M2M_P2P_CMD_BASE 90 +/*!< The base value of all the P2P mode host commands opcodes. +*/ +#define M2M_SERVER_CMD_BASE 100 +/*!< The base value of all the power save mode host commands codes. +*/ +/********************** + * OTA GROUP requests + */ +#define M2M_OTA_CMD_BASE 100 +/*!< The base value of all the OTA mode host commands opcodes. + * The OTA Have special group so can extended from 1-M2M_MAX_GRP_NUM_REQ +*/ +/*********************** + * + * CRYPTO group requests + */ +#define M2M_CRYPTO_CMD_BASE 1 +/*!< The base value of all the crypto mode host commands opcodes. + * The crypto Have special group so can extended from 1-M2M_MAX_GRP_NUM_REQ +*/ + +#define M2M_MAX_GRP_NUM_REQ (127) +/*!< max number of request in one group equal to 127 as the last bit reserved for config or data pkt +*/ + +#define WEP_40_KEY_STRING_SIZE ((uint8)10) +/*!< Indicate the wep key size in bytes for 40 bit string passphrase. +*/ + +#define WEP_104_KEY_STRING_SIZE ((uint8)26) +/*!< Indicate the wep key size in bytes for 104 bit string passphrase. +*/ +#define WEP_KEY_MAX_INDEX ((uint8)4) +/*!< Indicate the max key index value for WEP authentication +*/ +#define M2M_SHA256_CONTEXT_BUFF_LEN (128) +/*!< sha256 context size +*/ +#define M2M_SCAN_DEFAULT_NUM_SLOTS (2) +/*!< The default. number of scan slots performed by the WINC board. +*/ +#define M2M_SCAN_DEFAULT_SLOT_TIME (30) +/*!< The default. duration in miliseconds of a scan slots performed by the WINC board. +*/ +#define M2M_SCAN_DEFAULT_NUM_PROBE (2) +/*!< The default. number of scan slots performed by the WINC board. +*/ + + +/*======*======*======*======* + CONNECTION ERROR DEFINITIONS + *======*======*======*======*/ +typedef enum { + M2M_DEFAULT_CONN_INPROGRESS = ((sint8)-23), + /*!< + A failure that indicates that a default connection or forced connection is in progress + */ + M2M_DEFAULT_CONN_FAIL, + /*!< + A failure response that indicates that the winc failed to connect to the cached network + */ + M2M_DEFAULT_CONN_SCAN_MISMATCH, + /*!< + A failure response that indicates that no one of the cached networks + was found in the scan results, as a result to the function call m2m_default_connect. + */ + M2M_DEFAULT_CONN_EMPTY_LIST + /*!< + A failure response that indicates an empty network list as + a result to the function call m2m_default_connect. + */ + +}tenuM2mDefaultConnErrcode; + + + +/*======*======*======*======* + TLS DEFINITIONS + *======*======*======*======*/ +#define TLS_FILE_NAME_MAX 48 +/*!< Maximum length for each TLS certificate file name including null terminator. +*/ +#define TLS_SRV_SEC_MAX_FILES 8 +/*!< Maximum number of certificates allowed in TLS_SRV section. +*/ +#define TLS_SRV_SEC_START_PATTERN_LEN 8 +/*!< Length of certificate struct start pattern. +*/ +/*======*======*======*======* + OTA DEFINITIONS + *======*======*======*======*/ + +#define OTA_STATUS_VALID (0x12526285) +/*!< + Magic value updated in the Control structure in case of ROLLACK image Valid +*/ +#define OTA_STATUS_INVALID (0x23987718) +/*!< + Magic value updated in the Control structure in case of ROLLACK image InValid +*/ +#define OTA_MAGIC_VALUE (0x1ABCDEF9) +/*!< + Magic value set at the beginning of the OTA image header +*/ +#define M2M_MAGIC_APP (0xef522f61UL) +/*!< + Magic value set at the beginning of the Cortus OTA image header +*/ + +#define OTA_FORMAT_VER_0 (0) /*Till 19.2.2 format*/ +#define OTA_FORMAT_VER_1 (1) /*starting from 19.3.0 CRC is used and sequence number is used*/ +/*!< + Control structure format version +*/ +#define OTA_SHA256_DIGEST_SIZE (32) +/*!< + Sha256 digest size in the OTA image, + the sha256 digest is set at the beginning of image before the OTA header + */ + +/*======*======*======*======* + SSL DEFINITIONS + *======*======*======*======*/ + +#define TLS_CRL_DATA_MAX_LEN 64 +/* Every bit have 3dB gain control each. + for example: + 1 ->3db + 3 ->6db + 7 ->9db + */ + uint16 u8PPAGFor11GN; + /*!< PPA gain for 11GN (as the RF document represented) + PPA_AGC<0:2> Every bit have 3dB gain control each. + for example: + 1 ->3db + 3 ->6db + 7 ->9db + */ +}tstrM2mWifiGainsParams; + +/*! +@struct \ + tstrM2mWifiWepParams + +@brief + WEP security key parameters. +*/ +typedef struct{ + uint8 u8KeyIndx; + /*!< Wep key Index. + */ + uint8 u8KeySz; + /*!< Wep key Size. + */ + uint8 au8WepKey[WEP_104_KEY_STRING_SIZE + 1]; + /*!< WEP Key represented as a NULL terminated ASCII string. + */ + uint8 __PAD24__[3]; + /*!< Padding bytes to keep the structure word alligned. + */ +}tstrM2mWifiWepParams; + + +/*! +@struct \ + tstr1xAuthCredentials + +@brief + Credentials for the user to authenticate with the AAA server (WPA-Enterprise Mode IEEE802.1x). +*/ +typedef struct{ + uint8 au8UserName[M2M_1X_USR_NAME_MAX]; + /*!< User Name. It must be Null terminated string. + */ + uint8 au8Passwd[M2M_1X_PWD_MAX]; + /*!< Password corresponding to the user name. It must be Null terminated string. + */ +}tstr1xAuthCredentials; + + +/*! +@union \ + tuniM2MWifiAuth + +@brief + Wi-Fi Security Parameters for all supported security modes. +*/ +typedef union{ + uint8 au8PSK[M2M_MAX_PSK_LEN]; + /*!< Pre-Shared Key in case of WPA-Personal security. + */ + tstr1xAuthCredentials strCred1x; + /*!< Credentials for RADIUS server authentication in case of WPA-Enterprise security. + */ + tstrM2mWifiWepParams strWepInfo; + /*!< WEP key parameters in case of WEP security. + */ +}tuniM2MWifiAuth; + + +/*! +@struct \ + tstrM2MWifiSecInfo + +@brief + Authentication credentials to connect to a Wi-Fi network. +*/ +typedef struct{ + tuniM2MWifiAuth uniAuth; + /*!< Union holding all possible authentication parameters corresponding the current security types. + */ + uint8 u8SecType; + /*!< Wi-Fi network security type. See tenuM2mSecType for supported security types. + */ +#define __PADDING__ (4 - ((sizeof(tuniM2MWifiAuth) + 1) % 4)) + uint8 __PAD__[__PADDING__]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2MWifiSecInfo; + + +/*! +@struct \ + tstrM2mWifiConnect + +@brief + Wi-Fi Connect Request +*/ +typedef struct{ + tstrM2MWifiSecInfo strSec; + /*!< Security parameters for authenticating with the AP. + */ + uint16 u16Ch; + /*!< RF Channel for the target SSID. + */ + uint8 au8SSID[M2M_MAX_SSID_LEN]; + /*!< SSID of the desired AP. It must be NULL terminated string. + */ + uint8 u8NoSaveCred; +#define __CONN_PAD_SIZE__ (4 - ((sizeof(tstrM2MWifiSecInfo) + M2M_MAX_SSID_LEN + 3) % 4)) + uint8 __PAD__[__CONN_PAD_SIZE__]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mWifiConnect; + + +/*! +@struct \ + tstrM2MWPSConnect + +@brief + WPS Configuration parameters + +@sa + tenuWPSTrigger +*/ +typedef struct { + uint8 u8TriggerType; + /*!< WPS triggering method (Push button or PIN) + */ + char acPinNumber[8]; + /*!< WPS PIN No (for PIN method) + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2MWPSConnect; + + +/*! +@struct \ + tstrM2MWPSInfo + +@brief WPS Result + + This structure is passed to the application in response to a WPS request. If the WPS session is completed successfully, the + structure will have Non-ZERO authentication type. If the WPS Session fails (due to error or timeout) the authentication type + is set to ZERO. + +@sa + tenuM2mSecType +*/ +typedef struct{ + uint8 u8AuthType; + /*!< Network authentication type. + */ + uint8 u8Ch; + /*!< RF Channel for the AP. + */ + uint8 au8SSID[M2M_MAX_SSID_LEN]; + /*!< SSID obtained from WPS. + */ + uint8 au8PSK[M2M_MAX_PSK_LEN]; + /*!< PSK for the network obtained from WPS. + */ +}tstrM2MWPSInfo; + + +/*! +@struct \ + tstrM2MDefaultConnResp + +@brief + Response error of the m2m_default_connect + +@sa + M2M_DEFAULT_CONN_SCAN_MISMATCH + M2M_DEFAULT_CONN_EMPTY_LIST +*/ +typedef struct{ + sint8 s8ErrorCode; + /*!< + Default connect error code. possible values are: + - M2M_DEFAULT_CONN_EMPTY_LIST + - M2M_DEFAULT_CONN_SCAN_MISMATCH + */ + uint8 __PAD24__[3]; +}tstrM2MDefaultConnResp; + +/*! +@struct \ + tstrM2MScanOption + +@brief + Scan options and configurations. + +@sa + tenuM2mScanCh + tstrM2MScan +*/ +typedef struct { + uint8 u8NumOfSlot; + /*|< The min number of slots is 2 for every channel, + every slot the soc will send Probe Request on air, and wait/listen for PROBE RESP/BEACONS for the u16slotTime + */ + uint8 u8SlotTime; + /*|< the time that the Soc will wait on every channel listening to the frames on air + when that time increaseed number of AP will increased in the scan results + min time is 10 ms and the max is 250 ms + */ + uint8 u8ProbesPerSlot; + /*!< Number of probe requests to be sent per channel scan slot. + */ + sint8 s8RssiThresh; + /*! < The RSSI threshold of the AP which will be connected to directly. + */ + +}tstrM2MScanOption; + +/*! +@struct \ + tstrM2MScanRegion + +@brief + Wi-Fi channel regulation region information. + +@sa + tenuM2mScanRegion +*/ +typedef struct { + uint16 u16ScanRegion; + /*|< Specifies the number of channels allowed in the region (e.g. North America = 11 ... etc.). + */ + uint8 __PAD16__[2]; + +}tstrM2MScanRegion; + +/*! +@struct \ + tstrM2MScan + +@brief + Wi-Fi Scan Request + +@sa + tenuM2mScanCh + tstrM2MScanOption +*/ +typedef struct { + uint8 u8ChNum; + /*!< The Wi-Fi RF Channel number + */ + uint8 __RSVD8__[1]; + /*!< Reserved for future use. + */ + uint16 u16PassiveScanTime; + /*!< Passive Scan Timeout in ms. The field is ignored for active scan. + */ +}tstrM2MScan; + +/*! +@struct \ + tstrCyptoResp + +@brief + crypto response +*/ +typedef struct { + sint8 s8Resp; + /***/ + uint8 __PAD24__[3]; + /* + */ +}tstrCyptoResp; + + +/*! +@struct \ + tstrM2mScanDone + +@brief + Wi-Fi Scan Result +*/ +typedef struct{ + uint8 u8NumofCh; + /*!< Number of found APs + */ + sint8 s8ScanState; + /*!< Scan status + */ + uint8 __PAD16__[2]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mScanDone; + + +/*! +@struct \ + tstrM2mReqScanResult + +@brief Scan Result Request + + The Wi-Fi Scan results list is stored in Firmware. The application can request a certain scan result by its index. +*/ +typedef struct { + uint8 u8Index; + /*!< Index of the desired scan result + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mReqScanResult; + + +/*! +@struct \ + tstrM2mWifiscanResult + +@brief Wi-Fi Scan Result + + Information corresponding to an AP in the Scan Result list identified by its order (index) in the list. +*/ +typedef struct { + uint8 u8index; + /*!< AP index in the scan result list. + */ + sint8 s8rssi; + /*!< AP signal strength. + */ + uint8 u8AuthType; + /*!< AP authentication type. + */ + uint8 u8ch; + /*!< AP RF channel. + */ + uint8 au8BSSID[6]; + /*!< BSSID of the AP. + */ + uint8 au8SSID[M2M_MAX_SSID_LEN]; + /*!< AP ssid. + */ + uint8 _PAD8_; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mWifiscanResult; + + +/*! +@struct \ + tstrM2mWifiStateChanged + +@brief + Wi-Fi Connection State + +@sa + M2M_WIFI_DISCONNECTED, M2M_WIFI_CONNECTED, M2M_WIFI_REQ_CON_STATE_CHANGED,tenuM2mConnChangedErrcode +*/ +typedef struct { + uint8 u8CurrState; + /*!< Current Wi-Fi connection state + */ + uint8 u8ErrCode; + /*!< Error type review tenuM2mConnChangedErrcode + */ + uint8 __PAD16__[2]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mWifiStateChanged; + + +/*! +@struct \ + tstrM2mPsType + +@brief + Power Save Configuration + +@sa + tenuPowerSaveModes +*/ +typedef struct{ + uint8 u8PsType; + /*!< Power save operating mode + */ + uint8 u8BcastEn; + /*!< + */ + uint8 __PAD16__[2]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mPsType; + +/*! +@struct \ + tstrM2mSlpReqTime + +@brief + Manual power save request sleep time + +*/ +typedef struct { + /*!< Sleep time in ms + */ + uint32 u32SleepTime; + +} tstrM2mSlpReqTime; + +/*! +@struct \ + tstrM2mLsnInt + +@brief Listen interval + + It is the value of the Wi-Fi STA listen interval for power saving. It is given in units of Beacon period. + Periodically after the listen interval fires, the WINC is wakeup and listen to the beacon and check for any buffered frames for it from the AP. +*/ +typedef struct { + uint16 u16LsnInt; + /*!< Listen interval in Beacon period count. + */ + uint8 __PAD16__[2]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mLsnInt; + + +/*! +@struct \ + tstrM2MWifiMonitorModeCtrl + +@brief Wi-Fi Monitor Mode Filter + + This structure sets the filtering criteria for WLAN packets when monitoring mode is enable. + The received packets matching the filtering parameters, are passed directly to the application. +*/ +typedef struct{ + uint8 u8ChannelID; + /* !< RF Channel ID. It must use values from tenuM2mScanCh + */ + uint8 u8FrameType; + /*!< It must use values from tenuWifiFrameType. + */ + uint8 u8FrameSubtype; + /*!< It must use values from tenuSubTypes. + */ + uint8 au8SrcMacAddress[6]; + /* ZERO means DO NOT FILTER Source address. + */ + uint8 au8DstMacAddress[6]; + /* ZERO means DO NOT FILTER Destination address. + */ + uint8 au8BSSID[6]; + /* ZERO means DO NOT FILTER BSSID. + */ + uint8 u8EnRecvHdr; + /* + Enable recv the full hder before the payload + */ + uint8 __PAD16__[2]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2MWifiMonitorModeCtrl; + + +/*! +@struct \ + tstrM2MWifiRxPacketInfo + +@brief Wi-Fi RX Frame Header + + The M2M application has the ability to allow Wi-Fi monitoring mode for receiving all Wi-Fi Raw frames matching a well defined filtering criteria. + When a target Wi-Fi packet is received, the header information are extracted and assigned in this structure. +*/ +typedef struct{ + uint8 u8FrameType; + /*!< It must use values from tenuWifiFrameType. + */ + uint8 u8FrameSubtype; + /*!< It must use values from tenuSubTypes. + */ + uint8 u8ServiceClass; + /*!< Service class from Wi-Fi header. + */ + uint8 u8Priority; + /*!< Priority from Wi-Fi header. + */ + uint8 u8HeaderLength; + /*!< Frame Header length. + */ + uint8 u8CipherType; + /*!< Encryption type for the rx packet. + */ + uint8 au8SrcMacAddress[6]; + /* ZERO means DO NOT FILTER Source address. + */ + uint8 au8DstMacAddress[6]; + /* ZERO means DO NOT FILTER Destination address. + */ + uint8 au8BSSID[6]; + /* ZERO means DO NOT FILTER BSSID. + */ + uint16 u16DataLength; + /*!< Data payload length (Header excluded). + */ + uint16 u16FrameLength; + /*!< Total frame length (Header + Data). + */ + uint32 u32DataRateKbps; + /*!< Data Rate in Kbps. + */ + sint8 s8RSSI; + /*!< RSSI. + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2MWifiRxPacketInfo; + + +/*! +@struct \ + tstrM2MWifiTxPacketInfo + +@brief Wi-Fi TX Packet Info + + The M2M Application has the ability to compose a RAW Wi-Fi frames (under the application responsibility). + When transmitting a Wi-Fi packet, the application must supply the firmware with this structure for sending the target frame. +*/ +typedef struct{ + uint16 u16PacketSize; + /*!< Wlan frame length. + */ + uint16 u16HeaderLength; + /*!< Wlan frame header length. + */ +}tstrM2MWifiTxPacketInfo; + + +/*! + @struct \ + tstrM2MP2PConnect + + @brief + Set the device to operate in the Wi-Fi Direct (P2P) mode. +*/ +typedef struct { + uint8 u8ListenChannel; + /*!< P2P Listen Channel (1, 6 or 11) + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2MP2PConnect; + +/*! +@struct \ + tstrM2MAPConfig + +@brief AP Configuration + + This structure holds the configuration parameters for the M2M AP mode. It should be set by the application when + it requests to enable the M2M AP operation mode. The M2M AP mode currently supports only WEP security (with + the NO Security option available of course). +*/ +typedef struct { + /*!< + Configuration parameters for the WiFi AP. + */ + uint8 au8SSID[M2M_MAX_SSID_LEN]; + /*!< AP SSID + */ + uint8 u8ListenChannel; + /*!< Wi-Fi RF Channel which the AP will operate on + */ + uint8 u8KeyIndx; + /*!< Wep key Index + */ + uint8 u8KeySz; + /*!< Wep/WPA key Size + */ + uint8 au8WepKey[WEP_104_KEY_STRING_SIZE + 1]; + /*!< Wep key + */ + uint8 u8SecType; + /*!< Security type: Open or WEP or WPA in the current implementation + */ + uint8 u8SsidHide; + /*!< SSID Status "Hidden(1)/Visible(0)" + */ + uint8 au8DHCPServerIP[4]; + /*!< Ap IP server address + */ + uint8 au8Key[M2M_MAX_PSK_LEN]; + /*!< WPA key + */ + uint8 __PAD24__[2]; + /*!< Padding bytes for forcing alignment + */ +}tstrM2MAPConfig; + + +/*! +@struct \ + tstrM2mServerInit + +@brief + PS Server initialization. +*/ +typedef struct { + uint8 u8Channel; + /*!< Server Listen channel + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mServerInit; + + +/*! +@struct \ + tstrM2mClientState + +@brief + PS Client State. +*/ +typedef struct { + uint8 u8State; + /*!< PS Client State + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mClientState; + + +/*! +@struct \ + tstrM2Mservercmd + +@brief + PS Server CMD +*/ +typedef struct { + uint8 u8cmd; + /*!< PS Server Cmd + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2Mservercmd; + + +/*! +@struct \ + tstrM2mSetMacAddress + +@brief + Sets the MAC address from application. The WINC load the mac address from the effuse by default to the WINC configuration memory, + but that function is used to let the application overwrite the configuration memory with the mac address from the host. + +@note + It's recommended to call this only once before calling connect request and after the m2m_wifi_init +*/ +typedef struct { + uint8 au8Mac[6]; + /*!< MAC address array + */ + uint8 __PAD16__[2]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mSetMacAddress; + + +/*! +@struct \ + tstrM2MDeviceNameConfig + +@brief Device name + + It is assigned by the application. It is used mainly for Wi-Fi Direct device + discovery and WPS device information. +*/ +typedef struct { + uint8 au8DeviceName[M2M_DEVICE_NAME_MAX]; + /*!< NULL terminated device name + */ +}tstrM2MDeviceNameConfig; + + +/*! +@struct \ + tstrM2MIPConfig + +@brief + Static IP configuration. + +@note + All member IP addresses are expressed in Network Byte Order (eg. "192.168.10.1" will be expressed as 0x010AA8C0). + */ +typedef struct { + uint32 u32StaticIP; + /*!< The static IP assigned to the device. + */ + uint32 u32Gateway; + /*!< IP of the Default internet gateway. + */ + uint32 u32DNS; + /*!< IP for the DNS server. + */ + uint32 u32SubnetMask; + /*!< Subnet mask for the local area network. + */ + uint32 u32DhcpLeaseTime; + /*!< Dhcp Lease Time in sec + */ +} tstrM2MIPConfig; + +/*! +@struct \ + tstrM2mIpRsvdPkt + +@brief + Received Packet Size and Data Offset + + */ +typedef struct{ + uint16 u16PktSz; + uint16 u16PktOffset; +} tstrM2mIpRsvdPkt; + + +/*! +@struct \ + tstrM2MProvisionModeConfig + +@brief + M2M Provisioning Mode Configuration + */ + +typedef struct { + tstrM2MAPConfig strApConfig; + /*!< + Configuration parameters for the WiFi AP. + */ + char acHttpServerDomainName[64]; + /*!< + The device domain name for HTTP provisioning. + */ + uint8 u8EnableRedirect; + /*!< + A flag to enable/disable HTTP redirect feature for the HTTP Provisioning server. If the Redirect is enabled, + all HTTP traffic (http://URL) from the device associated with WINC AP will be redirected to the HTTP Provisioning Web page. + - 0 : Disable HTTP Redirect. + - 1 : Enable HTTP Redirect. + */ + uint8 __PAD24__[3]; +}tstrM2MProvisionModeConfig; + + +/*! +@struct \ + tstrM2MProvisionInfo + +@brief + M2M Provisioning Information obtained from the HTTP Provisioning server. + */ +typedef struct{ + uint8 au8SSID[M2M_MAX_SSID_LEN]; + /*!< + Provisioned SSID. + */ + uint8 au8Password[M2M_MAX_PSK_LEN]; + /*!< + Provisioned Password. + */ + uint8 u8SecType; + /*!< + Wifi Security type. + */ + uint8 u8Status; + /*!< + Provisioning status. It must be checked before reading the provisioning information. It may be + - M2M_SUCCESS : Provision successful. + - M2M_FAIL : Provision Failed. + */ +}tstrM2MProvisionInfo; + + +/*! +@struct \ + tstrM2MConnInfo + +@brief + M2M Provisioning Information obtained from the HTTP Provisioning server. + */ +typedef struct{ + char acSSID[M2M_MAX_SSID_LEN]; + /*!< AP connection SSID name */ + uint8 u8SecType; + /*!< Security type */ + uint8 au8IPAddr[4]; + /*!< Connection IP address */ + uint8 au8MACAddress[6]; + /*!< MAC address of the peer Wi-Fi station */ + sint8 s8RSSI; + /*!< Connection RSSI signal */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment */ +}tstrM2MConnInfo; + +/*! +@struct \ + tstrOtaInitHdr + +@brief + OTA Image Header + */ + +typedef struct{ + uint32 u32OtaMagicValue; + /*!< Magic value kept in the OTA image after the + sha256 Digest buffer to define the Start of OTA Header */ + uint32 u32OtaPayloadSzie; + /*!< + The Total OTA image payload size, include the sha256 key size + */ + +}tstrOtaInitHdr; + + +/*! +@struct \ + tstrOtaControlSec + +@brief + Control section structure is used to define the working image and + the validity of the roll-back image and its offset, also both firmware versions is kept in that structure. + */ + +typedef struct { + uint32 u32OtaMagicValue; +/*!< + Magic value used to ensure the structure is valid or not +*/ + uint32 u32OtaFormatVersion; +/*!< + NA NA NA Flash version cs struct version + 00 00 00 00 00 + Control structure format version, the value will be incremented in case of structure changed or updated +*/ + uint32 u32OtaSequenceNumber; +/*!< + Sequence number is used while update the control structure to keep track of how many times that section updated +*/ + uint32 u32OtaLastCheckTime; +/*!< + Last time OTA check for update +*/ + uint32 u32OtaCurrentworkingImagOffset; +/*!< + Current working offset in flash +*/ + uint32 u32OtaCurrentworkingImagFirmwareVer; +/*!< + current working image version ex 18.0.1 +*/ + uint32 u32OtaRollbackImageOffset; +/*!< + Roll-back image offset in flash +*/ + uint32 u32OtaRollbackImageValidStatus; +/*!< + roll-back image valid status +*/ + uint32 u32OtaRollbackImagFirmwareVer; +/*!< + Roll-back image version (ex 18.0.3) +*/ + uint32 u32OtaCortusAppWorkingOffset; +/*!< + cortus app working offset in flash +*/ + uint32 u32OtaCortusAppWorkingValidSts; +/*!< + Working Cortus app valid status +*/ + uint32 u32OtaCortusAppWorkingVer; +/*!< + Working cortus app version (ex 18.0.3) +*/ + uint32 u32OtaCortusAppRollbackOffset; +/*!< + cortus app rollback offset in flash +*/ + uint32 u32OtaCortusAppRollbackValidSts; +/*!< + roll-back cortus app valid status +*/ + uint32 u32OtaCortusAppRollbackVer; +/*!< + Roll-back cortus app version (ex 18.0.3) +*/ + uint32 u32OtaControlSecCrc; +/*!< + CRC for the control structure to ensure validity +*/ +} tstrOtaControlSec; + +/*! +@enum \ + tenuOtaUpdateStatus + +@brief + OTA return status +*/ +typedef enum { + OTA_STATUS_SUCSESS = 0, + /*!< OTA Success with not errors. */ + OTA_STATUS_FAIL = 1, + /*!< OTA generic fail. */ + OTA_STATUS_INVAILD_ARG = 2, + /*!< Invalid or malformed download URL. */ + OTA_STATUS_INVAILD_RB_IMAGE = 3, + /*!< Invalid rollback image. */ + OTA_STATUS_INVAILD_FLASH_SIZE = 4, + /*!< Flash size on device is not enough for OTA. */ + OTA_STATUS_AlREADY_ENABLED = 5, + /*!< An OTA operation is already enabled. */ + OTA_STATUS_UPDATE_INPROGRESS = 6, + /*!< An OTA operation update is in progress */ + OTA_STATUS_IMAGE_VERIF_FAILED = 7, + /*!< OTA Verfication failed */ + OTA_STATUS_CONNECTION_ERROR = 8, + /*!< OTA connection error */ + OTA_STATUS_SERVER_ERROR = 9, + /*!< OTA server Error (file not found or else ...) */ + OTA_STATUS_ABORTED = 10 + /*!< OTA download has been aborted by the application. */ +} tenuOtaUpdateStatus; +/*! +@enum \ + tenuOtaUpdateStatusType + +@brief + OTA update Status type +*/ +typedef enum { + + DL_STATUS = 1, + /*!< Download OTA file status + */ + SW_STATUS = 2, + /*!< Switching to the upgrade firmware status + */ + RB_STATUS = 3, + /*!< Roll-back status + */ + AB_STATUS = 4 + /*!< Abort status + */ +}tenuOtaUpdateStatusType; + + +/*! +@struct \ + tstrOtaUpdateStatusResp + +@brief + OTA Update Information + +@sa + tenuWPSTrigger +*/ +typedef struct { + uint8 u8OtaUpdateStatusType; + /*!< + Status type tenuOtaUpdateStatusType + */ + uint8 u8OtaUpdateStatus; + /*!< + OTA_SUCCESS + OTA_ERR_WORKING_IMAGE_LOAD_FAIL + OTA_ERR_INVAILD_CONTROL_SEC + M2M_ERR_OTA_SWITCH_FAIL + M2M_ERR_OTA_START_UPDATE_FAIL + M2M_ERR_OTA_ROLLBACK_FAIL + M2M_ERR_OTA_INVAILD_FLASH_SIZE + M2M_ERR_OTA_INVAILD_ARG + */ + uint8 _PAD16_[2]; +}tstrOtaUpdateStatusResp; + +/*! +@struct \ + tstrOtaUpdateInfo + +@brief + OTA Update Information + +@sa + tenuWPSTrigger +*/ +typedef struct { + uint32 u8NcfUpgradeVersion; + /*!< NCF OTA Upgrade Version + */ + uint32 u8NcfCurrentVersion; + /*!< NCF OTA Current firmware version + */ + uint32 u8NcdUpgradeVersion; + /*!< NCD (host) upgraded version (if the u8NcdRequiredUpgrade == true) + */ + uint8 u8NcdRequiredUpgrade; + /*!< NCD Required upgrade to the above version + */ + uint8 u8DownloadUrlOffset; + /*!< Download URL offset in the received packet + */ + uint8 u8DownloadUrlSize; + /*!< Download URL size in the received packet + */ + uint8 __PAD8__; + /*!< Padding bytes for forcing 4-byte alignment + */ +} tstrOtaUpdateInfo; + +/*! +@struct \ + tstrSystemTime + +@brief + Used for time storage. +*/ +typedef struct{ + uint16 u16Year; + uint8 u8Month; + uint8 u8Day; + uint8 u8Hour; + uint8 u8Minute; + uint8 u8Second; + uint8 __PAD8__; +}tstrSystemTime; + +/*! +@struct \ + tstrM2MMulticastMac + +@brief + M2M add/remove multi-cast mac address + */ + typedef struct { + uint8 au8macaddress[M2M_MAC_ADDRES_LEN]; + /*!< + Mac address needed to be added or removed from filter. + */ + uint8 u8AddRemove; + /*!< + set by 1 to add or 0 to remove from filter. + */ + uint8 __PAD8__; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2MMulticastMac; + +/*! +@struct \ + tstrPrng + +@brief + M2M Request PRNG + */ + typedef struct { + /*!< + return buffer address + */ + uint8 *pu8RngBuff; + /*!< + PRNG size requested + */ + uint16 u16PrngSize; + /*!< + PRNG pads + */ + uint8 __PAD16__[2]; +}tstrPrng; + +/* + * TLS certificate revocation list + * Typedefs common between fw and host + */ + +/*! +@struct \ + tstrTlsCrlEntry + +@brief + Certificate data for inclusion in a revocation list (CRL) +*/ +typedef struct { + uint8 u8DataLen; + /*!< + Length of certificate data (maximum possible is @ref TLS_CRL_DATA_MAX_LEN) + */ + uint8 au8Data[TLS_CRL_DATA_MAX_LEN]; + /*!< + Certificate data + */ + uint8 __PAD24__[3]; + /*!< + Padding bytes for forcing 4-byte alignment + */ +}tstrTlsCrlEntry; + +/*! +@struct \ + tstrTlsCrlInfo + +@brief + Certificate revocation list details +*/ +typedef struct { + uint8 u8CrlType; + /*!< + Type of certificate data contained in list + */ + uint8 u8Rsv1; + /*!< + Reserved for future use + */ + uint8 u8Rsv2; + /*!< + Reserved for future use + */ + uint8 u8Rsv3; + /*!< + Reserved for future use + */ + tstrTlsCrlEntry astrTlsCrl[TLS_CRL_MAX_ENTRIES]; + /*!< + List entries + */ +}tstrTlsCrlInfo; + + /*! +@enum\ + tenuSslCertExpSettings + +@brief SSL Certificate Expiry Validation Options +*/ +typedef enum{ + SSL_CERT_EXP_CHECK_DISABLE, + /*!< + ALWAYS OFF. + Ignore certificate expiration date validation. If a certificate is + expired or there is no configured system time, the SSL connection SUCCEEDs. + */ + SSL_CERT_EXP_CHECK_ENABLE, + /*!< + ALWAYS ON. + Validate certificate expiration date. If a certificate is expired or + there is no configured system time, the SSL connection FAILs. + */ + SSL_CERT_EXP_CHECK_EN_IF_SYS_TIME + /*!< + CONDITIONAL VALIDATION (Default setting at startup). + Validate the certificate expiration date only if there is a configured system time. + If there is no configured system time, the certificate expiration is bypassed and the + SSL connection SUCCEEDs. + */ +}tenuSslCertExpSettings; + + +/*! +@struct \ + tstrTlsSrvSecFileEntry + +@brief + This struct contains a TLS certificate. + */ +typedef struct{ + char acFileName[TLS_FILE_NAME_MAX]; + /*!< Name of the certificate. */ + uint32 u32FileSize; + /*!< Size of the certificate. */ + uint32 u32FileAddr; + /*!< Error Code. */ +}tstrTlsSrvSecFileEntry; + +/*! +@struct \ + tstrTlsSrvSecHdr + +@brief + This struct contains a set of TLS certificates. + */ +typedef struct{ + uint8 au8SecStartPattern[TLS_SRV_SEC_START_PATTERN_LEN]; + /*!< Start pattern. */ + uint32 u32nEntries; + /*!< Number of certificates stored in the struct. */ + uint32 u32NextWriteAddr; + /*!< TLS Certificates. */ + tstrTlsSrvSecFileEntry astrEntries[TLS_SRV_SEC_MAX_FILES]; +}tstrTlsSrvSecHdr; + +typedef struct{ + uint32 u32CsBMP; +}tstrSslSetActiveCsList; + + + /**@}*/ + +#endif diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_wifi.h b/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_wifi.h new file mode 100644 index 0000000..3477196 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_wifi.h @@ -0,0 +1,2882 @@ +/** + * + * \file + * + * \brief WINC WLAN Application Interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef __M2M_WIFI_H__ +#define __M2M_WIFI_H__ + +/** \defgroup m2m_wifi WLAN + * + */ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "common/include/nm_common.h" +#include "driver/include/m2m_types.h" +#include "driver/source/nmdrv.h" + +#ifdef CONF_MGMT + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/**@defgroup WlanEnums DataTypes + * @ingroup m2m_wifi + * @{*/ +/*! +@enum \ + tenuWifiFrameType + +@brief + Enumeration for Wi-Fi MAC frame type codes (2-bit) + The following types are used to identify the type of frame sent or received. + Each frame type constitutes a number of frame subtypes as defined in @ref tenuSubTypes to specify the exact type of frame. + Values are defined as per the IEEE 802.11 standard. + +@remarks + The following frame types are useful for advanced user usage when monitoring mode is used (defining @ref CONF_MGMT) + and the user application requires to monitor the frame transmission and reception. +@see + tenuSubTypes +*/ +typedef enum { + MANAGEMENT = 0x00, + /*!< Wi-Fi Management frame (Probe Req/Resp, Beacon, Association Req/Resp ...etc). + */ + CONTROL = 0x04, + /*!< Wi-Fi Control frame (eg. ACK frame). + */ + DATA_BASICTYPE = 0x08, + /*!< Wi-Fi Data frame. + */ + RESERVED = 0x0C, + + M2M_WIFI_FRAME_TYPE_ANY = 0xFF +/*!< Set monitor mode to receive any of the frames types +*/ +}tenuWifiFrameType; + + +/*! +@enum \ + tenuSubTypes + +@brief + Enumeration for Wi-Fi MAC Frame subtype code (6-bit). + The frame subtypes fall into one of the three frame type groups as defined in @ref tenuWifiFrameType + (MANAGEMENT, CONTROL & DATA). + Values are defined as per the IEEE 802.11 standard. +@remarks + The following sub-frame types are useful for advanced user usage when @ref CONF_MGMT is defined + and the application developer requires to monitor the frame transmission and reception. +@see + tenuWifiFrameType + tstrM2MWifiMonitorModeCtrl +*/ +typedef enum { + /*!< Sub-Types related to Management Sub-Types */ + ASSOC_REQ = 0x00, + ASSOC_RSP = 0x10, + REASSOC_REQ = 0x20, + REASSOC_RSP = 0x30, + PROBE_REQ = 0x40, + PROBE_RSP = 0x50, + BEACON = 0x80, + ATIM = 0x90, + DISASOC = 0xA0, + AUTH = 0xB0, + DEAUTH = 0xC0, + ACTION = 0xD0, +/**@{*/ + /* Sub-Types related to Control */ + PS_POLL = 0xA4, + RTS = 0xB4, + CTS = 0xC4, + ACK = 0xD4, + CFEND = 0xE4, + CFEND_ACK = 0xF4, + BLOCKACK_REQ = 0x84, + BLOCKACK = 0x94, +/**@{*/ + /* Sub-Types related to Data */ + DATA = 0x08, + DATA_ACK = 0x18, + DATA_POLL = 0x28, + DATA_POLL_ACK = 0x38, + NULL_FRAME = 0x48, + CFACK = 0x58, + CFPOLL = 0x68, + CFPOLL_ACK = 0x78, + QOS_DATA = 0x88, + QOS_DATA_ACK = 0x98, + QOS_DATA_POLL = 0xA8, + QOS_DATA_POLL_ACK = 0xB8, + QOS_NULL_FRAME = 0xC8, + QOS_CFPOLL = 0xE8, + QOS_CFPOLL_ACK = 0xF8, + M2M_WIFI_FRAME_SUB_TYPE_ANY = 0xFF + /*!< Set monitor mode to receive any of the frames types + */ +}tenuSubTypes; + + +/*! +@enum \ + tenuInfoElementId + +@brief + Enumeration for the Wi-Fi Information Element(IE) IDs, which indicates the specific type of IEs. + IEs are management frame information included in management frames. + Values are defined as per the IEEE 802.11 standard. + +*/ +typedef enum { + ISSID = 0, + /*!< Service Set Identifier (SSID) + */ + ISUPRATES = 1, + /*!< Supported Rates + */ + IFHPARMS = 2, + /*!< FH parameter set + */ + IDSPARMS = 3, + /*!< DS parameter set + */ + ICFPARMS = 4, + /*!< CF parameter set + */ + ITIM = 5, + /*!< Traffic Information Map + */ + IIBPARMS = 6, + /*!< IBSS parameter set + */ + ICOUNTRY = 7, + /*!< Country element. + */ + IEDCAPARAMS = 12, + /*!< EDCA parameter set + */ + ITSPEC = 13, + /*!< Traffic Specification + */ + ITCLAS = 14, + /*!< Traffic Classification + */ + ISCHED = 15, + /*!< Schedule. + */ + ICTEXT = 16, + /*!< Challenge Text + */ + IPOWERCONSTRAINT = 32, + /*!< Power Constraint. + */ + IPOWERCAPABILITY = 33, + /*!< Power Capability + */ + ITPCREQUEST = 34, + /*!< TPC Request + */ + ITPCREPORT = 35, + /*!< TPC Report + */ + ISUPCHANNEL = 36, + /* Supported channel list + */ + ICHSWANNOUNC = 37, + /*!< Channel Switch Announcement + */ + IMEASUREMENTREQUEST = 38, + /*!< Measurement request + */ + IMEASUREMENTREPORT = 39, + /*!< Measurement report + */ + IQUIET = 40, + /*!< Quiet element Info + */ + IIBSSDFS = 41, + /*!< IBSS DFS + */ + IERPINFO = 42, + /*!< ERP Information + */ + ITSDELAY = 43, + /*!< TS Delay + */ + ITCLASPROCESS = 44, + /*!< TCLAS Processing + */ + IHTCAP = 45, + /*!< HT Capabilities + */ + IQOSCAP = 46, + /*!< QoS Capability + */ + IRSNELEMENT = 48, + /*!< RSN Information Element + */ + IEXSUPRATES = 50, + /*!< Extended Supported Rates + */ + IEXCHSWANNOUNC = 60, + /*!< Extended Ch Switch Announcement + */ + IHTOPERATION = 61, + /*!< HT Information + */ + ISECCHOFF = 62, + /*!< Secondary Channel Offset + */ + I2040COEX = 72, + /*!< 20/40 Coexistence IE + */ + I2040INTOLCHREPORT = 73, + /*!< 20/40 Intolerant channel report + */ + IOBSSSCAN = 74, + /*!< OBSS Scan parameters + */ + IEXTCAP = 127, + /*!< Extended capability + */ + IWMM = 221, + /*!< WMM parameters + */ + IWPAELEMENT = 221 + /*!< WPA Information Element + */ +}tenuInfoElementId; + + +/*! +@struct \ + tenuWifiCapability + +@brief + Enumeration for capability Information field bit. + The value of the capability information field from the 802.11 management frames received by the wireless LAN interface. + Defining the capabilities of the Wi-Fi system. Values are defined as per the IEEE 802.11 standard. + +@details + Capabilities:- + ESS/IBSS : Defines whether a frame is coming from an AP or not. + POLLABLE : CF Poll-able + POLLREQ : Request to be polled + PRIVACY : WEP encryption supported + SHORTPREAMBLE : Short Preamble is supported + SHORTSLOT : Short Slot is supported + PBCC :PBCC + CHANNELAGILITY :Channel Agility + SPECTRUM_MGMT :Spectrum Management + DSSS_OFDM : DSSS-OFDM +*/ +typedef enum{ + ESS = 0x01, + /*!< ESS capability + */ + IBSS = 0x02, + /*!< IBSS mode + */ + POLLABLE = 0x04, + /*!< CF Pollable + */ + POLLREQ = 0x08, + /*!< Request to be polled + */ + PRIVACY = 0x10, + /*!< WEP encryption supported + */ + SHORTPREAMBLE = 0x20, + /*!< Short Preamble is supported + */ + SHORTSLOT = 0x400, + /*!< Short Slot is supported + */ + PBCC = 0x40, + /*!< PBCC + */ + CHANNELAGILITY = 0x80, + /*!< Channel Agility + */ + SPECTRUM_MGMT = 0x100, + /*!< Spectrum Management + */ + DSSS_OFDM = 0x2000 + /*!< DSSS-OFDM + */ +}tenuWifiCapability; + + +#endif + +/*! +@typedef \ + tpfAppWifiCb + +@brief + Wi-Fi's main callback function handler, for handling the M2M_WIFI events received on the Wi-Fi interface. + Such notifications are received in response to Wi-Fi/P2P operations such as @ref m2m_wifi_request_scan, + @ref m2m_wifi_connect. + Wi-Fi/P2P operations are implemented in an asynchronous mode, and all incoming information/status + are to be handled through this callback function when the corresponding notification is received. + Applications are expected to assign this wi-fi callback function by calling @ref m2m_wifi_init +@param [in] u8MsgType + Type of notifications. Possible types are: + /ref M2M_WIFI_RESP_CON_STATE_CHANGED + /ref M2M_WIFI_RESP_CONN_INFO + /ref M2M_WIFI_REQ_DHCP_CONF + /ref M2M_WIFI_REQ_WPS + /ref M2M_WIFI_RESP_IP_CONFLICT + /ref M2M_WIFI_RESP_SCAN_DONE + /ref M2M_WIFI_RESP_SCAN_RESULT + /ref M2M_WIFI_RESP_CURRENT_RSSI + /ref M2M_WIFI_RESP_CLIENT_INFO + /ref M2M_WIFI_RESP_PROVISION_INFO + /ref M2M_WIFI_RESP_DEFAULT_CONNECT + + In case Ethernet/Bypass mode is defined : + @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET + + In case monitoring mode is used: + @ref M2M_WIFI_RESP_WIFI_RX_PACKET + +@param [in] pvMsg + A pointer to a buffer containing the notification parameters (if any). It should be + casted to the correct data type corresponding to the notification type. + +@see + tstrM2mWifiStateChanged + tstrM2MWPSInfo + tstrM2mScanDone + tstrM2mWifiscanResult +*/ +typedef void (*tpfAppWifiCb) (uint8 u8MsgType, void * pvMsg); + +/*! +@typedef \ + tpfAppEthCb + +@brief + ETHERNET (bypass mode) notification callback function receiving Bypass mode events as defined in + the Wi-Fi responses enumeration @ref tenuM2mStaCmd. + +@param [in] u8MsgType + Type of notification. Possible types are: + - [M2M_WIFI_RESP_ETHERNET_RX_PACKET](@ref M2M_WIFI_RESP_ETHERNET_RX_PACKET) + +@param [in] pvMsg + A pointer to a buffer containing the notification parameters (if any). It should be + casted to the correct data type corresponding to the notification type. + For example, it could be a pointer to the buffer holding the received frame in case of @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET + event. + +@param [in] pvControlBuf + A pointer to control buffer describing the accompanied message. + To be casted to @ref tstrM2mIpCtrlBuf in case of @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET event. + +@warning + Make sure that the application defines @ref ETH_MODE. + +@see + m2m_wifi_init + +*/ +typedef void (*tpfAppEthCb) (uint8 u8MsgType, void * pvMsg,void * pvCtrlBuf); + +/*! +@typedef \ + tpfAppMonCb + +@brief + Wi-Fi monitoring mode callback function. This function delivers all received wi-Fi packets through the Wi-Fi interface. + Applications requiring to operate in the monitoring should call the asynchronous function m2m_wifi_enable_monitoring_mode + and expect to receive the Wi-Fi packets through this callback function, when the event is received. + To disable the monitoring mode a call to @ref m2m_wifi_disable_monitoring_mode should be made. +@param [in] pstrWifiRxPacket + Pointer to a structure holding the Wi-Fi packet header parameters. + +@param [in] pu8Payload + Pointer to the buffer holding the Wi-Fi packet payload information required by the application starting from the + defined OFFSET by the application (when calling m2m_wifi_enable_monitoring_mode). + Could hold a value of NULL, if the application does not need any data from the payload. + +@param [in] u16PayloadSize + The size of the payload in bytes. + +@see + m2m_wifi_enable_monitoring_mode,m2m_wifi_init + +@warning + u16PayloadSize should not exceed the buffer size given through m2m_wifi_enable_monitoring_mode. + +*/ +typedef void (*tpfAppMonCb) (tstrM2MWifiRxPacketInfo *pstrWifiRxPacket, uint8 * pu8Payload, uint16 u16PayloadSize); + +/** +@struct \ + tstrEthInitParam + +@brief + Structure to hold Ethernet interface parameters. + Structure is to be defined and have its attributes set,based on the application's functionality before + a call is made to initialize the Wi-Fi operations by calling the @ref m2m_wifi_init function. + This structure is part of the Wi-Fi configuration structure @ref tstrWifiInitParam. + Applications shouldn't need to define this structure, if the bypass mode is not defined. + +@see + tpfAppEthCb + tpfAppWifiCb + m2m_wifi_init + +@warning + Make sure that application defines @ref ETH_MODE before using @ref tstrEthInitParam. + +*/ +typedef struct { + tpfAppWifiCb pfAppWifiCb; + /*!< + Callback for wifi notifications. + */ + tpfAppEthCb pfAppEthCb; + /*!< + Callback for Ethernet interface. + */ + uint8 * au8ethRcvBuf; + /*!< + Pointer to Receive Buffer of Ethernet Packet + */ + uint16 u16ethRcvBufSize; + /*!< + Size of Receive Buffer for Ethernet Packet + */ + uint8 u8EthernetEnable; + /*!< + Enable Ethernet mode flag + */ + uint8 __PAD8__; + /*!< + Padding + */ +} tstrEthInitParam; +/*! +@struct \ + tstrM2mIpCtrlBuf + +@brief + Structure holding the incoming buffer's data size information, indicating the data size of the buffer and the remaining buffer's data size . + The data of the buffer which holds the packet sent to the host when in the bypass mode, is placed in the @ref tstrEthInitParam structure in the + @ref au8ethRcvBuf attribute. This following information is retrieved in the host when an event @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET is received in + the Wi-Fi callback function @ref tpfAppWifiCb. + + The application is expected to use this structure's information to determine if there is still incoming data to be received from the firmware. + + @see + tpfAppEthCb + tstrEthInitParam + + @warning + Make sure that ETHERNET/bypass mode is defined before using @ref tstrM2mIpCtrlBuf + + */ +typedef struct{ + uint16 u16DataSize; + /*!< + Size of the received data in bytes. + */ + uint16 u16RemainigDataSize; + /*!< + Size of the remaining data bytes to be delivered to host. + */ +} tstrM2mIpCtrlBuf; + + +/** +@struct \ + tstrWifiInitParam + +@brief + Structure, holding the Wi-fi configuration attributes such as the wi-fi callback , monitoring mode callback and Ethernet parameter initialization structure. + Such configuration parameters are required to be set before calling the wi-fi initialization function @ref m2m_wifi_init. + @ref pfAppWifiCb attribute must be set to handle the wi-fi callback operations. + @ref pfAppMonCb attribute, is optional based on whether the application requires the monitoring mode configuration, and can there not + be set before the initialization. + @ref strEthInitParam structure, is another optional configuration based on whether the bypass mode is set. + + @see + tpfAppEthCb + tpfAppMonCb + tstrEthInitParam + +*/ +typedef struct { + tpfAppWifiCb pfAppWifiCb; + /*!< + Callback for Wi-Fi notifications. + */ + tpfAppMonCb pfAppMonCb; + /*!< + Callback for monitoring interface. + */ + tstrEthInitParam strEthInitParam ; + /*!< + Structure to hold Ethernet interface parameters. + */ + +} tstrWifiInitParam; + //@} +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/** \defgroup WLANAPI Function + * @ingroup m2m_wifi + */ +#ifdef __cplusplus + extern "C" { +#endif + /** @defgroup WiFiDownloadFn m2m_wifi_download_mode + * @ingroup WLANAPI + * Synchronous download mode entry function that prepares the WINC board to enter the download mode, ready for the firmware or certificate download. +* The WINC board is prepared for download, through initializations for the WINC driver including bus initializations and interrupt enabling, it also halts the chip, to allow for the firmware downloads. +* Firmware can be downloaded through a number of interfaces, UART, I2C and SPI. + */ + /**@{*/ +/*! +@fn \ + NMI_API void m2m_wifi_download_mode(void); +@brief Prepares the WINC broard before downloading any data (Firmware, Certificates .. etc) + + This function should called before starting to download any data to the WINC board. The WINC board is prepared for download, through initializations for the WINC driver including bus initializations + and interrupt enabling, it also halts the chip, to allow for the firmware downloads Firmware can be downloaded through a number of interfaces, UART, I2C and SPI. + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_download_mode(void); + + /**@}*/ + /** @defgroup WifiInitFn m2m_wifi_init + * @ingroup WLANAPI + * Synchronous initialization function for the WINC driver. This function initializes the driver by, registering the call back function for M2M_WIFI layer(also the call back function for bypass mode/monitoring mode if defined), + * initializing the host interface layer and the bus interfaces. + * Wi-Fi callback registering is essential to allow the handling of the events received, in response to the asynchronous Wi-Fi operations. + +Following are the possible Wi-Fi events that are expected to be received through the call back function(provided by the application) to the M2M_WIFI layer are : + + @ref M2M_WIFI_RESP_CON_STATE_CHANGED \n + @ref M2M_WIFI_RESP_CONN_INFO \n + @ref M2M_WIFI_REQ_DHCP_CONF \n + @ref M2M_WIFI_REQ_WPS \n + @ref M2M_WIFI_RESP_IP_CONFLICT \n + @ref M2M_WIFI_RESP_SCAN_DONE \n + @ref M2M_WIFI_RESP_SCAN_RESULT \n + @ref M2M_WIFI_RESP_CURRENT_RSSI \n + @ref M2M_WIFI_RESP_CLIENT_INFO \n + @ref M2M_WIFI_RESP_PROVISION_INFO \n + @ref M2M_WIFI_RESP_DEFAULT_CONNECT \n + Example: \n + In case Bypass mode is defined : \n + @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET + + In case Monitoring mode is used: \n + @ref M2M_WIFI_RESP_WIFI_RX_PACKET + + Any application using the WINC driver must call this function at the start of its main function. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_init(tstrWifiInitParam * pWifiInitParam); + +@param [in] pWifiInitParam + This is a pointer to the @ref tstrWifiInitParam structure which holds the pointer to the application WIFI layer call back function, + monitoring mode call back and @ref tstrEthInitParam structure containing bypass mode parameters. + +@brief Initialize the WINC host driver. + This function initializes the driver by, registering the call back function for M2M_WIFI layer(also the call back function for bypass mode/monitoring mode if defined), + initializing the host interface layer and the bus interfaces. + +@pre + Prior to this function call, The application should initialize the BSP using "nm_bsp_init". + Also,application users must provide a call back function responsible for receiving all the WI-FI events that are received on the M2M_WIFI layer. + +@warning + Failure to successfully complete function indicates that the driver couldn't be initialized and a fatal error will prevent the application from proceeding. + +@see + nm_bsp_init + m2m_wifi_deinit + tenuM2mStaCmd + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_init(tstrWifiInitParam * pWifiInitParam); + /**@}*/ + /** @defgroup WifiDeinitFn m2m_wifi_deinit + * @ingroup WLANAPI + * Synchronous de-initialization function to the WINC1500 driver. De-initializes the host interface and frees any resources used by the M2M_WIFI layer. + * This function must be called in the application closing phase to ensure that all resources have been correctly released. No arguments are expected to be passed in. + */ +/**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_deinit(void * arg); + +@param [in] arg + Generic argument. Not used in the current implementation. +@brief Deinitilize the WINC driver and host enterface. + This function must be called at the De-initilization stage of the application. Generally This function should be the last function before switching off the chip + and it should be followed only by "nm_bsp_deinit" function call. Every function call of "nm_wifi_init" should be matched with a call to nm_wifi_deinit. +@see + nm_bsp_deinit + nm_wifi_init + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_deinit(void * arg); + + /**@}*/ +/** @defgroup WifiHandleEventsFn m2m_wifi_handle_events +* @ingroup WLANAPI +* Synchronous M2M event handler function, responsible for handling interrupts received from the WINC firmware. +* Application developers should call this function periodically in-order to receive the events that are to be handled by the +* callback functions implemented by the application. + + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_handle_events(void * arg); + +@pre + Prior to receiving events, the WINC driver should have been successfully initialized by calling the @ref m2m_wifi_init function. + +@brief Handle the varios events received from the WINC board. + Whenever an event happen in the WINC board (e.g. Connection, Disconnection , DHCP .. etc), WINC will interrupt the host to let it know that a new + event has occured. The host driver will attempt to handle these events whenever the host driver decides to do that by calling the "m2m_wifi_handle_events" function. + It's mandatory to call this function periodically and independantly of any other condition. It's ideal to include this function in the main and the most frequent loop of the + host application. +@warning + Failure to successfully complete this function indicates bus errors and hence a fatal error that will prevent the application from proceeding. + +@return + The function returns @ref M2M_SUCCESS for successful interrupt handling and a negative value otherwise. +*/ + +NMI_API sint8 m2m_wifi_handle_events(void * arg); + + /**@}*/ +/** @defgroup WifiSendCRLFn m2m_wifi_send_crl +* @ingroup WLANAPI +* Asynchronous API that notifies the WINC with the Certificate Revocation List to be used for TLS. + + */ + /**@{*/ +/*! +@fn \ + sint8 m2m_wifi_send_crl(tstrTlsCrlInfo* pCRL); + +@brief + Asynchronous API that notifies the WINC with the Certificate Revocation List. + +@param [in] pCRL + Pointer to the structure containing certificate revocation list details. + +@return + The function returns @ref M2M_SUCCESS if the command has been successfully queued to the WINC, + and a negative value otherwise. +*/ + +sint8 m2m_wifi_send_crl(tstrTlsCrlInfo* pCRL); + + /**@}*/ +/** @defgroup WifiDefaultConnectFn m2m_wifi_default_connect + * @ingroup WLANAPI + * Asynchronous Wi-Fi connection function. An application calling this function will cause the firmware to correspondingly connect to the last successfully connected AP from the cached connections. + * A failure to connect will result in a response of @ref M2M_WIFI_RESP_DEFAULT_CONNECT indicating the connection error as defined in the structure @ref tstrM2MDefaultConnResp. + * Possible errors are: + * The connection list is empty @ref M2M_DEFAULT_CONN_EMPTY_LIST or a mismatch for the saved AP name @ref M2M_DEFAULT_CONN_SCAN_MISMATCH. + * only difference between this function and @ref m2m_wifi_connect, is the connection parameters. + * Connection using this function is expected to connect using cached connection parameters. + + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_default_connect(void); + +@pre + Prior to connecting, the WINC driver should have been successfully initialized by calling the @ref m2m_wifi_init function. + +@brief Connect to the last successfully connected AP from the cached connections. + +@warning + This function must be called in station mode only. + It's important to note that successful completion of a call to m2m_wifi_default_connect() does not guarantee success of the WIFI connection, + and a negative return value indicates only locally-detected errors. + +@see + m2m_wifi_connect + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_default_connect(void); + /**@}*/ +/** @defgroup WifiConnectFn m2m_wifi_connect + * @ingroup WLANAPI + * Asynchronous wi-fi connection function to a specific AP. Prior to a successful connection, the application must define the SSID of the AP, the security type, + * the authentication information parameters and the channel number to which the connection will be established. + * The connection status is known when a response of @ref M2M_WIFI_RESP_CON_STATE_CHANGED is received based on the states defined in @ref tenuM2mConnState, + * successful connection is defined by @ref M2M_WIFI_CONNECTED +* + * The only difference between this function and @ref m2m_wifi_default_connect, is the connection parameters. + * Connection using this function is expected to be made to a specific AP and to a specified channel. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_connect(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch); + +@param [in] pcSsid + A buffer holding the SSID corresponding to the requested AP. + +@param [in] u8SsidLen + Length of the given SSID (not including the NULL termination). + A length less than ZERO or greater than the maximum defined SSID @ref M2M_MAX_SSID_LEN will result in a negative error + @ref M2M_ERR_FAIL. + +@param [in] u8SecType + Wi-Fi security type security for the network. It can be one of the following types: + -@ref M2M_WIFI_SEC_OPEN + -@ref M2M_WIFI_SEC_WEP + -@ref M2M_WIFI_SEC_WPA_PSK + -@ref M2M_WIFI_SEC_802_1X + A value outside these possible values will result in a negative return error @ref M2M_ERR_FAIL. + +@param [in] pvAuthInfo + Authentication parameters required for completing the connection. It is type is based on the Security type. + If the authentication parameters are NULL or are greater than the maximum length of the authentication parameters length as defined by + @ref M2M_MAX_PSK_LEN a negative error will return @ref M2M_ERR_FAIL(-12) indicating connection failure. + +@param [in] u16Ch + Wi-Fi channel number as defined in @ref tenuM2mScanCh enumeration. + Channel number greater than @ref M2M_WIFI_CH_14 returns a negative error @ref M2M_ERR_FAIL(-12). + Except if the value is M2M_WIFI_CH_ALL(255), since this indicates that the firmware should scan all channels to find the SSID requested to connect to. + Failure to find the connection match will return a negative error @ref M2M_DEFAULT_CONN_SCAN_MISMATCH. +@pre + Prior to a successful connection request, the Wi-Fi driver must have been successfully initialized through the call of the @ref @m2m_wifi_init function +@see + tuniM2MWifiAuth + tstr1xAuthCredentials + tstrM2mWifiWepParams + +@warning + -This function must be called in station mode only. + -Successful completion of this function does not guarantee success of the WIFI connection, and + a negative return value indicates only locally-detected errors. + +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_connect(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch); + /**@}*/ +/** @defgroup WifiConnectFn m2m_wifi_connect_sc + * @ingroup WLANAPI + * Asynchronous wi-fi connection function to a specific AP. Prior to a successful connection, the application developers must know the SSID of the AP, the security type, + * the authentication information parameters and the channel number to which the connection will be established.this API allows the user to choose + * whether to + * The connection status is known when a response of @ref M2M_WIFI_RESP_CON_STATE_CHANGED is received based on the states defined in @ref tenuM2mConnState, + * successful connection is defined by @ref M2M_WIFI_CONNECTED + * The only difference between this function and @ref m2m_wifi_connect, is the option to save the acess point info ( SSID, password...etc) or not. + * Connection using this function is expected to be made to a specific AP and to a specified channel. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_connect_sc(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch,uint8 u8SaveCred); + +@param [in] pcSsid + A buffer holding the SSID corresponding to the requested AP. + +@param [in] u8SsidLen + Length of the given SSID (not including the NULL termination). + A length less than ZERO or greater than the maximum defined SSID @ref M2M_MAX_SSID_LEN will result in a negative error + @ref M2M_ERR_FAIL. + +@param [in] u8SecType + Wi-Fi security type security for the network. It can be one of the following types: + -@ref M2M_WIFI_SEC_OPEN + -@ref M2M_WIFI_SEC_WEP + -@ref M2M_WIFI_SEC_WPA_PSK + -@ref M2M_WIFI_SEC_802_1X + A value outside these possible values will result in a negative return error @ref M2M_ERR_FAIL. + +@param [in] pvAuthInfo + Authentication parameters required for completing the connection. It is type is based on the Security type. + If the authentication parameters are NULL or are greater than the maximum length of the authentication parameters length as defined by + @ref M2M_MAX_PSK_LEN a negative error will return @ref M2M_ERR_FAIL(-12) indicating connection failure. + +@param [in] u16Ch + Wi-Fi channel number as defined in @ref tenuM2mScanCh enumeration. + Channel number greater than @ref M2M_WIFI_CH_14 returns a negative error @ref M2M_ERR_FAIL(-12). + Except if the value is M2M_WIFI_CH_ALL(255), since this indicates that the firmware should scan all channels to find the SSID requested to connect to. + Failure to find the connection match will return a negative error @ref M2M_DEFAULT_CONN_SCAN_MISMATCH. + +@param [in] u8NoSaveCred + Option to store the acess point SSID and password into the WINC flash memory or not. + +@pre + Prior to a successful connection request, the wi-fi driver must have been successfully initialized through the call of the @ref @m2m_wifi_init function +@see + tuniM2MWifiAuth + tstr1xAuthCredentials + tstrM2mWifiWepParams + +@warning + -This function must be called in station mode only. + -Successful completion of this function does not guarantee success of the WIFI connection, and + a negative return value indicates only locally-detected errors. + +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ + NMI_API sint8 m2m_wifi_connect_sc(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch, uint8 u8SaveCred); + /**@}*/ +/** @defgroup WifiDisconnectFn m2m_wifi_disconnect + * @ingroup WLANAPI + * Synchronous wi-fi disconnection function, requesting a Wi-Fi disconnection from the currently connected AP. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_disconnect(void); + +@pre + Disconnection request must be made to a successfully connected AP. If the WINC is not in the connected state, a call to this function will hold insignificant. + +@brief Request a Wi-Fi disconnect from the currently connected AP. + After the Disconnect is complete the driver should recieve a response of @ref M2M_WIFI_RESP_CON_STATE_CHANGED based on the states defined + in @ref tenuM2mConnState, successful disconnection is defined by @ref M2M_WIFI_DISCONNECTED . +@warning + This function must be called in station mode only. + +@see + m2m_wifi_connect + m2m_wifi_default_connect + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_disconnect(void); + + /**@}*/ +/** @defgroup StartProvisionModeFn m2m_wifi_start_provision_mode + * @ingroup WLANAPI + * Asynchronous Wi-Fi provisioning function, which starts the WINC HTTP PROVISIONING mode. + The function triggers the WINC to activate the Wi-Fi AP (HOTSPOT) mode with the passed configuration parameters and then starts the + HTTP Provision WEB Server. + The provisioning status is returned in an event @ref M2M_WIFI_RESP_PROVISION_INFO + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_start_provision_mode(tstrM2MAPConfig *pstrAPConfig, char *pcHttpServerDomainName, uint8 bEnableHttpRedirect); + +@param [in] pstrAPConfig + AP configuration parameters as defined in @ref tstrM2MAPConfig configuration structure. + A NULL value passed in, will result in a negative error @ref M2M_ERR_FAIL. + +@param [in] pcHttpServerDomainName + Domain name of the HTTP Provision WEB server which others will use to load the provisioning Home page. + The domain name can have one of the following 3 forms: + 1- "wincprov.com" + 2- "http://wincprov.com" + 3- "https://wincprov.com" + The forms 1 and 2 are equivalent, they both will start a plain http server, while form 3 + will start a secure HTTP provisioning Session (HTTP over SSL connection). + +@param [in] bEnableHttpRedirect + A flag to enable/disable the HTTP redirect feature. If Secure provisioning is enabled (i.e. the server + domain name uses "https" prefix) this flag is ignored (no meaning for redirect in HTTPS). + Possible values are: + - ZERO DO NOT Use HTTP Redirect. In this case the associated device could open the provisioning page ONLY when + the HTTP Provision URL of the WINC HTTP Server is correctly written on the browser. + - Non-Zero value Use HTTP Redirect. In this case, all http traffic (http://URL) from the associated + device (Phone, PC, ...etc) will be redirected to the WINC HTTP Provisioning Home page. + +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback + is done through passing it to the initialization @ref m2m_wifi_init function. + - The event @ref M2M_WIFI_RESP_CONN_INFO must be handled in the callback to receive the requested connection info. + +@see + tpfAppWifiCb + m2m_wifi_init + M2M_WIFI_RESP_PROVISION_INFO + m2m_wifi_stop_provision_mode + tstrM2MAPConfig + +@warning + DO Not use ".local" in the pcHttpServerDomainName. + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +\section Example + The example demonstrates a code snippet for how provisioning is triggered and the response event received accordingly. +@code + #include "m2m_wifi.h" + #include "m2m_types.h" + + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_PROVISION_INFO: + { + tstrM2MProvisionInfo *pstrProvInfo = (tstrM2MProvisionInfo*)pvMsg; + if(pstrProvInfo->u8Status == M2M_SUCCESS) + { + m2m_wifi_connect((char*)pstrProvInfo->au8SSID, (uint8)strlen(pstrProvInfo->au8SSID), pstrProvInfo->u8SecType, + pstrProvInfo->au8Password, M2M_WIFI_CH_ALL); + + printf("PROV SSID : %s\n",pstrProvInfo->au8SSID); + printf("PROV PSK : %s\n",pstrProvInfo->au8Password); + } + else + { + printf("(ERR) Provisioning Failed\n"); + } + } + break; + + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + tstrM2MAPConfig apConfig; + uint8 bEnableRedirect = 1; + + strcpy(apConfig.au8SSID, "WINC_SSID"); + apConfig.u8ListenChannel = 1; + apConfig.u8SecType = M2M_WIFI_SEC_OPEN; + apConfig.u8SsidHide = 0; + + // IP Address + apConfig.au8DHCPServerIP[0] = 192; + apConfig.au8DHCPServerIP[1] = 168; + apConfig.au8DHCPServerIP[2] = 1; + apConfig.au8DHCPServerIP[0] = 1; + + m2m_wifi_start_provision_mode(&apConfig, "atmelwincconf.com", bEnableRedirect); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API sint8 m2m_wifi_start_provision_mode(tstrM2MAPConfig *pstrAPConfig, char *pcHttpServerDomainName, uint8 bEnableHttpRedirect); + /**@}*/ +/** @defgroup StopProvisioningModeFn m2m_wifi_stop_provision_mode + * @ingroup WLANAPI + * Synchronous provision termination function which stops the provision mode if it is active. + */ + /**@{*/ +/*! +@fn \ + sint8 m2m_wifi_stop_provision_mode(void); + +@pre + An active provisioning session must be active before it is terminated through this function. +@see + m2m_wifi_start_provision_mode + +@return + The function returns ZERO for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_stop_provision_mode(void); + /**@}*/ +/** @defgroup GetConnectionInfoFn m2m_wifi_get_connection_info + * @ingroup WLANAPI + * Asynchronous connection status retrieval function, retrieves the status information of the currently connected AP. The result is passed to the Wi-Fi notification callback +* through the event @ref M2M_WIFI_RESP_CONN_INFO. Connection information is retrieved from the structure @ref tstrM2MConnInfo. + */ + /**@{*/ +/*! +@fn \ + sint8 m2m_wifi_get_connection_info(void); + +@brief + Retrieve the current Connection information. The result is passed to the Wi-Fi notification callback + with [M2M_WIFI_RESP_CONN_INFO](@ref M2M_WIFI_RESP_CONN_INFO). +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback + is done through passing it to the initialization @ref m2m_wifi_init function. + - The event @ref M2M_WIFI_RESP_CONN_INFO must be handled in the callback to receive the requested connection info. + + Connection Information retrieved: + + + -Connection Security + -Connection RSSI + -Remote MAC address + -Remote IP address + + and in case of WINC station mode the SSID of the AP is also retrieved. +@warning + -In case of WINC AP mode or P2P mode, ignore the SSID field (NULL string). +@sa + M2M_WIFI_RESP_CONN_INFO, + tstrM2MConnInfo +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet shows an example of how wi-fi connection information is retrieved . +@code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_CONN_INFO: + { + tstrM2MConnInfo *pstrConnInfo = (tstrM2MConnInfo*)pvMsg; + + printf("CONNECTED AP INFO\n"); + printf("SSID : %s\n",pstrConnInfo->acSSID); + printf("SEC TYPE : %d\n",pstrConnInfo->u8SecType); + printf("Signal Strength : %d\n", pstrConnInfo->s8RSSI); + printf("Local IP Address : %d.%d.%d.%d\n", + pstrConnInfo->au8IPAddr[0] , pstrConnInfo->au8IPAddr[1], pstrConnInfo->au8IPAddr[2], pstrConnInfo->au8IPAddr[3]); + } + break; + + case M2M_WIFI_REQ_DHCP_CONF: + { + // Get the current AP information. + m2m_wifi_get_connection_info(); + } + break; + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // connect to the default AP + m2m_wifi_default_connect(); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API sint8 m2m_wifi_get_connection_info(void); + /**@}*/ +/** @defgroup WifiSetMacAddFn m2m_wifi_set_mac_address + * @ingroup WLANAPI + * Synchronous MAC address assigning to the NMC1500. It is used for non-production SW. Assign MAC address to the WINC device. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_set_mac_address(uint8 au8MacAddress[6]); + +@brief Assign a MAC address to the WINC board. + This function override the already assigned MAC address of the WINC board with a user provided one. This is for experimental + use only and should never be used in the production SW. + +@param [in] au8MacAddress + MAC Address to be set to the WINC. + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_set_mac_address(uint8 au8MacAddress[6]); + + /**@}*/ +/** @defgroup WifiWpsFn m2m_wifi_wps + * @ingroup WLANAPI + * Asynchronous WPS triggering function. + * This function is called for the WINC to enter the WPS (Wi-Fi Protected Setup) mode. The result is passed to the Wi-Fi notification callback +* with the event @ref M2M_WIFI_REQ_WPS. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_wps(uint8 u8TriggerType,const char * pcPinNumber); + +@param [in] u8TriggerType + WPS Trigger method. Could be: + - [WPS_PIN_TRIGGER](@ref WPS_PIN_TRIGGER) Push button method + - [WPS_PBC_TRIGGER](@ref WPS_PBC_TRIGGER) Pin method + +@param [in] pcPinNumber + PIN number for WPS PIN method. It is not used if the trigger type is WPS_PBC_TRIGGER. It must follow the rules + stated by the WPS standard. + +@warning + This function is not allowed in AP or P2P modes. + +@pre + - A Wi-Fi notification callback of type (@ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback + is done through passing it to the [m2m_wifi_init](@ref m2m_wifi_init). + - The event [M2M_WIFI_REQ_WPS](@ref M2M_WIFI_REQ_WPS) must be handled in the callback to receive the WPS status. + - The WINC device MUST be in IDLE or STA mode. If AP or P2P mode is active, the WPS will not be performed. + - The [m2m_wifi_handle_events](@ref m2m_wifi_handle_events) MUST be called periodically to receive the responses in the callback. +@see + tpfAppWifiCb + m2m_wifi_init + M2M_WIFI_REQ_WPS + tenuWPSTrigger + tstrM2MWPSInfo + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet shows an example of how Wi-Fi WPS is triggered . +@code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + switch(u8WiFiEvent) + { + case M2M_WIFI_REQ_WPS: + { + tstrM2MWPSInfo *pstrWPS = (tstrM2MWPSInfo*)pvMsg; + if(pstrWPS->u8AuthType != 0) + { + printf("WPS SSID : %s\n",pstrWPS->au8SSID); + printf("WPS PSK : %s\n",pstrWPS->au8PSK); + printf("WPS SSID Auth Type : %s\n",pstrWPS->u8AuthType == M2M_WIFI_SEC_OPEN ? "OPEN" : "WPA/WPA2"); + printf("WPS Channel : %d\n",pstrWPS->u8Ch + 1); + + // establish Wi-Fi connection + m2m_wifi_connect((char*)pstrWPS->au8SSID, (uint8)m2m_strlen(pstrWPS->au8SSID), + pstrWPS->u8AuthType, pstrWPS->au8PSK, pstrWPS->u8Ch); + } + else + { + printf("(ERR) WPS Is not enabled OR Timed out\n"); + } + } + break; + + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // Trigger WPS in Push button mode. + m2m_wifi_wps(WPS_PBC_TRIGGER, NULL); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API sint8 m2m_wifi_wps(uint8 u8TriggerType,const char *pcPinNumber); + /**@}*/ +/** @defgroup WifiWpsDisableFn m2m_wifi_wps_disable + * @ingroup WLANAPI + * Disable the WINC1500 WPS operation. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_wps_disable(void); + +@pre WINC should be already in WPS mode using @ref m2m_wifi_wps + +@brief Stops the WPS ongoing session. + +@see + m2m_wifi_wps + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_wps_disable(void); + + /**@}*/ +/** @defgroup WifiP2PFn m2m_wifi_p2p + * @ingroup WLANAPI + * Asynchronous Wi-Fi direct (P2P) enabling mode function. + The WINC supports P2P in device listening mode ONLY (intent is ZERO). + The WINC P2P implementation does not support P2P GO (Group Owner) mode. + Active P2P devices (e.g. phones) could find the WINC in the search list. When a device is connected to WINC, a Wi-Fi notification event + @ref M2M_WIFI_RESP_CON_STATE_CHANGED is triggered. After a short while, the DHCP IP Address is obtained + and an event @ref M2M_WIFI_REQ_DHCP_CONF is triggered. Refer to the code examples for a more illustrative example. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_p2p(uint8 u8Channel); + +@param [in] u8Channel + P2P Listen RF channel. According to the P2P standard It must hold only one of the following values 1, 6 or 11. + +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback + is done through passing it to the @ref m2m_wifi_init. + - The events @ref M2M_WIFI_RESP_CON_STATE_CHANGED and @ref M2M_WIFI_REQ_DHCP_CONF + must be handled in the callback. + - The @ref m2m_wifi_handle_events MUST be called to receive the responses in the callback. + +@warning + This function is not allowed in AP or STA modes. + +@see + tpfAppWifiCb + m2m_wifi_init + M2M_WIFI_RESP_CON_STATE_CHANGED + M2M_WIFI_REQ_DHCP_CONF + tstrM2mWifiStateChanged + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet shown an example of how the p2p mode operates. +@code + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_CON_STATE_CHANGED: + { + tstrM2mWifiStateChanged *pstrWifiState = (tstrM2mWifiStateChanged*)pvMsg; + M2M_INFO("Wifi State :: %s :: ErrCode %d\n", pstrWifiState->u8CurrState? "CONNECTED":"DISCONNECTED",pstrWifiState->u8ErrCode); + + // Do something + } + break; + + case M2M_WIFI_REQ_DHCP_CONF: + { + uint8 *pu8IPAddress = (uint8*)pvMsg; + + printf("P2P IP Address \"%u.%u.%u.%u\"\n",pu8IPAddress[0],pu8IPAddress[1],pu8IPAddress[2],pu8IPAddress[3]); + } + break; + + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // Trigger P2P + m2m_wifi_p2p(M2M_WIFI_CH_1); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode + +*/ +NMI_API sint8 m2m_wifi_p2p(uint8 u8Channel); + /**@}*/ +/** @defgroup WifiP2PDisconnectFn m2m_wifi_p2p_disconnect + * @ingroup WLANAPI + * Disable the WINC1500 device Wi-Fi direct mode (P2P). + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_p2p_disconnect(void); +@pre + The p2p mode must have be enabled and active before a disconnect can be called. + +@see + m2m_wifi_p2p +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_p2p_disconnect(void); + /**@}*/ +/** @defgroup WifiEnableApFn m2m_wifi_enable_ap + * @ingroup WLANAPI + * Asynchronous Wi-FI hot-spot enabling function. + * The WINC supports AP mode operation with the following limitations: + - Only 1 STA could be associated at a time. + - Open and WEP are the only supported security types + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_enable_ap(CONST tstrM2MAPConfig* pstrM2MAPConfig); + +@param [in] pstrM2MAPConfig + A structure holding the AP configurations. + +@warning + This function is not allowed in P2P or STA modes. + +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback + is done through passing it to the [m2m_wifi_init](@ref m2m_wifi_init). + - The event @ref M2M_WIFI_REQ_DHCP_CONF must be handled in the callback. + - The @ref m2m_wifi_handle_events MUST be called to receive the responses in the callback. + +@see + tpfAppWifiCb + tenuM2mSecType + m2m_wifi_init + M2M_WIFI_REQ_DHCP_CONF + tstrM2mWifiStateChanged + tstrM2MAPConfig + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet demonstrates how the AP mode is enabled after the driver is initialized in the application's main function and the handling + of the event @ref M2M_WIFI_REQ_DHCP_CONF, to indicate successful connection. +@code + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + switch(u8WiFiEvent) + { + case M2M_WIFI_REQ_DHCP_CONF: + { + uint8 *pu8IPAddress = (uint8*)pvMsg; + + printf("Associated STA has IP Address \"%u.%u.%u.%u\"\n",pu8IPAddress[0],pu8IPAddress[1],pu8IPAddress[2],pu8IPAddress[3]); + } + break; + + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + tstrM2MAPConfig apConfig; + + strcpy(apConfig.au8SSID, "WINC_SSID"); + apConfig.u8ListenChannel = 1; + apConfig.u8SecType = M2M_WIFI_SEC_OPEN; + apConfig.u8SsidHide = 0; + + // IP Address + apConfig.au8DHCPServerIP[0] = 192; + apConfig.au8DHCPServerIP[1] = 168; + apConfig.au8DHCPServerIP[2] = 1; + apConfig.au8DHCPServerIP[0] = 1; + + // Trigger AP + m2m_wifi_enable_ap(&apConfig); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode + +*/ +NMI_API sint8 m2m_wifi_enable_ap(CONST tstrM2MAPConfig* pstrM2MAPConfig); + /**@}*/ +/** @defgroup WifiDisableApFn m2m_wifi_disable_ap + * @ingroup WLANAPI + * Synchronous Wi-Fi hot-spot disabling function. Must be called only when the AP is enabled through the @ref m2m_wifi_enable_ap + * function. Otherwise the call to this function will not be useful. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_disable_ap(void); +@see + m2m_wifi_enable_ap +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_disable_ap(void); + /**@}*/ +/** @defgroup SetStaticIPFn m2m_wifi_set_static_ip + * @ingroup WLANAPI + * Synchronous static IP Address configuration function. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_set_static_ip(tstrM2MIPConfig * pstrStaticIPConf); + +@param [in] pstrStaticIPConf + Pointer to a structure holding the static IP Configurations (IP, + Gateway, subnet mask and DNS address). + +@pre The application must disable auto DHCP using @ref m2m_wifi_enable_dhcp before assigning a static IP address. + +@brief Assign a static IP address to the WINC board. + This function assigns a static IP address in case the AP doesn't have a DHCP server or in case the application wants to assign + a predefined known IP address. The user must take in mind that assigning a static IP address might result in an IP address + conflict. In case of an IP address conflict observed by the WINC board the user will get a response of @ref M2M_WIFI_RESP_IP_CONFLICT + in the wifi callback. The application is then responsible to either solve the conflict or assign another IP address. +@warning + Normally this function normally should not be used. DHCP configuration is requested automatically after successful Wi-Fi connection is established. + +@see + tstrM2MIPConfig + + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_set_static_ip(tstrM2MIPConfig * pstrStaticIPConf); + + /**@}*/ +/** @defgroup RequestDHCPClientFn m2m_wifi_request_dhcp_client + * @ingroup WLANAPI + * Starts the DHCP client operation(DHCP requested by the firmware automatically in STA/AP/P2P mode). + * + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_request_dhcp_client(void); + +@warning + This function is legacy and exists only for compatability with older applications. DHCP configuration is requested automatically after successful Wi-Fi connection is established. + +@return + The function returns @ref M2M_SUCCESS always. +*/ +NMI_API sint8 m2m_wifi_request_dhcp_client(void); + /**@}*/ +/** @defgroup RequestDHCPServerFn m2m_wifi_request_dhcp_server + * @ingroup WLANAPI + * Dhcp requested by the firmware automatically in STA/AP/P2P mode). + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_request_dhcp_server(uint8* addr); + +@warning + This function is legacy and exists only for compatability with older applications. DHCP server is started automatically when enabling the AP mode. + + +@return + The function returns @ref M2M_SUCCESS always. +*/ +NMI_API sint8 m2m_wifi_request_dhcp_server(uint8* addr); + /**@}*/ +/** @defgroup WifiDHCPEnableFn m2m_wifi_enable_dhcp + * @ingroup WLANAPI + * Synchronous Wi-Fi DHCP enable function. This function Enable/Disable DHCP protocol. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_enable_dhcp(uint8 u8DhcpEn ); + +@brief + Enable/Disable the DHCP client after connection. + +@param [in] u8DhcpEn + Possible values: + 1: Enable DHCP client after connection. + 0: Disable DHCP client after connection. +@warnings + -DHCP client is enabled by default + -This Function should be called before using m2m_wifi_set_static_ip() + + +@sa + m2m_wifi_set_static_ip() + +@return + The function SHALL return @ref M2M_SUCCESS for successful operation and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_enable_dhcp(uint8 u8DhcpEn ); + /**@}*/ +/** @defgroup WifiSetScanOptionFn m2m_wifi_set_scan_options + * @ingroup WLANAPI + * Synchronous Wi-Fi scan settings function. This function sets the time configuration parameters for the scan operation. + */ + +/*! +@fn \ + sint8 m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption) + +@param [in] ptstrM2MScanOption; + Pointer to the structure holding the Scan Parameters. + +@see + tenuM2mScanCh + m2m_wifi_request_scan + tstrM2MScanOption + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption); + /**@}*/ +/** @defgroup WifiSetScanRegionFn m2m_wifi_set_scan_region + * @ingroup WLANAPI + * Synchronous wi-fi scan region setting function. + * This function sets the scan region, which will affect the range of possible scan channels. + * For 2.5GHz supported in the current release, the requested scan region can't exceed the maximum number of channels (14). + *@{*/ +/*! +@fn \ + sint8 m2m_wifi_set_scan_region(uint16 ScanRegion) + +@param [in] ScanRegion; + ASIA + NORTH_AMERICA +@see + tenuM2mScanCh + m2m_wifi_request_scan + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_set_scan_region(uint16 ScanRegion); + /**@}*/ +/** @defgroup WifiRequestScanFn m2m_wifi_request_scan +* @ingroup WLANAPI +* Asynchronous Wi-FI scan request on the given channel. The scan status is delivered in the wifi event callback and then the application +* is supposed to read the scan results sequentially. +* The number of APs found (N) is returned in event @ref M2M_WIFI_RESP_SCAN_DONE with the number of found +* APs. +* The application reads the list of APs by calling the function @ref m2m_wifi_req_scan_result N times. +* +*@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_request_scan(uint8 ch); + +@param [in] ch + RF Channel ID for SCAN operation. It should be set according to tenuM2mScanCh. + With a value of M2M_WIFI_CH_ALL(255)), means to scan all channels. + +@warning + This function is not allowed in P2P or AP modes. It works only for STA mode (both connected or disconnected states). + +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback + is done through passing it to the @ref m2m_wifi_init. + - The events @ref M2M_WIFI_RESP_SCAN_DONE and @ref M2M_WIFI_RESP_SCAN_RESULT. + must be handled in the callback. + - The @ref m2m_wifi_handle_events function MUST be called to receive the responses in the callback. + +@see + M2M_WIFI_RESP_SCAN_DONE + M2M_WIFI_RESP_SCAN_RESULT + tpfAppWifiCb + tstrM2mWifiscanResult + tenuM2mScanCh + m2m_wifi_init + m2m_wifi_handle_events + m2m_wifi_req_scan_result + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of + the events received in response. +@code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + static uint8 u8ScanResultIdx = 0; + + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_SCAN_DONE: + { + tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; + + printf("Num of AP found %d\n",pstrInfo->u8NumofCh); + if(pstrInfo->s8ScanState == M2M_SUCCESS) + { + u8ScanResultIdx = 0; + if(pstrInfo->u8NumofCh >= 1) + { + m2m_wifi_req_scan_result(u8ScanResultIdx); + u8ScanResultIdx ++; + } + else + { + printf("No AP Found Rescan\n"); + m2m_wifi_request_scan(M2M_WIFI_CH_ALL); + } + } + else + { + printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); + } + } + break; + + case M2M_WIFI_RESP_SCAN_RESULT: + { + tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; + uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); + + printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", + pstrScanResult->u8index,pstrScanResult->s8rssi, + pstrScanResult->u8AuthType, + pstrScanResult->u8ch, + pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], + pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], + pstrScanResult->au8SSID); + + if(u8ScanResultIdx < u8NumFoundAPs) + { + // Read the next scan result + m2m_wifi_req_scan_result(index); + u8ScanResultIdx ++; + } + } + break; + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // Scan all channels + m2m_wifi_request_scan(M2M_WIFI_CH_ALL); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API sint8 m2m_wifi_request_scan(uint8 ch); + + /**@}*/ +/** @defgroup WifiRequestScanFn m2m_wifi_request_scan_passive +* @ingroup WLANAPI +* Same as m2m_wifi_request_scan but perform passive scanning while the other one perform active scanning. + +* +*@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_request_scan_passive(uint8 ch, uint16 scan_time); + +@param [in] ch + RF Channel ID for SCAN operation. It should be set according to tenuM2mScanCh. + With a value of M2M_WIFI_CH_ALL(255)), means to scan all channels. + +@param [in] scan_time + The time in ms that passive scan is listening to beacons on each channel per one slot, enter 0 for deafult setting. + +@warning + This function is not allowed in P2P or AP modes. It works only for STA mode (both connected or disconnected states). + +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback + is done through passing it to the @ref m2m_wifi_init. + - The events @ref M2M_WIFI_RESP_SCAN_DONE and @ref M2M_WIFI_RESP_SCAN_RESULT. + must be handled in the callback. + - The @ref m2m_wifi_handle_events function MUST be called to receive the responses in the callback. + +@see + m2m_wifi_request_scan + M2M_WIFI_RESP_SCAN_DONE + M2M_WIFI_RESP_SCAN_RESULT + tpfAppWifiCb + tstrM2mWifiscanResult + tenuM2mScanCh + m2m_wifi_init + m2m_wifi_handle_events + m2m_wifi_req_scan_result + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_request_scan_passive(uint8 ch, uint16 scan_time); + + + /**@}*/ +/** @defgroup WifiRequestScanFn m2m_wifi_request_scan_ssid_list +* @ingroup WLANAPI +* Asynchronous wi-fi scan request on the given channel and the hidden scan list. The scan status is delivered in the wi-fi event callback and then the application +* is to read the scan results sequentially. +* The number of APs found (N) is returned in event @ref M2M_WIFI_RESP_SCAN_DONE with the number of found +* APs. +* The application could read the list of APs by calling the function @ref m2m_wifi_req_scan_result N times. +* +*@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_request_scan_ssid_list(uint8 ch,uint8 * u8SsidList); + +@param [in] ch + RF Channel ID for SCAN operation. It should be set according to tenuM2mScanCh. + With a value of M2M_WIFI_CH_ALL(255)), means to scan all channels. +@param [in] u8SsidList + u8SsidList is a buffer containing a list of hidden SSIDs to + include during the scan. The first byte in the buffer, u8SsidList[0], + is the number of SSIDs encoded in the string. The number of hidden SSIDs + cannot exceed MAX_HIDDEN_SITES. All SSIDs are concatenated in the following + bytes and each SSID is prefixed with a one-byte header containing its length. + The total number of bytes in u8SsidList buffer, including length byte, cannot + exceed 133 bytes (MAX_HIDDEN_SITES SSIDs x 32 bytes each, which is max SSID length). + For instance, encoding the two hidden SSIDs "DEMO_AP" and "TEST" + results in the following buffer content: +@code + uint8 u8SsidList[14]; + u8SsidList[0] = 2; // Number of SSIDs is 2 + u8SsidList[1] = 7; // Length of the string "DEMO_AP" without NULL termination + memcpy(&u8SsidList[2], "DEMO_AP", 7); // Bytes index 2-9 containing the string DEMO_AP + u8SsidList[9] = 4; // Length of the string "TEST" without NULL termination + memcpy(&u8SsidList[10], "TEST", 4); // Bytes index 10-13 containing the string TEST +@endcode + +@warning + This function is not allowed in P2P. It works only for STA/AP mode (connected or disconnected). + +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback + is done through passing it to the @ref m2m_wifi_init. + - The events @ref M2M_WIFI_RESP_SCAN_DONE and @ref M2M_WIFI_RESP_SCAN_RESULT. + must be handled in the callback. + - The @ref m2m_wifi_handle_events function MUST be called to receive the responses in the callback. + +@see + M2M_WIFI_RESP_SCAN_DONE + M2M_WIFI_RESP_SCAN_RESULT + tpfAppWifiCb + tstrM2mWifiscanResult + tenuM2mScanCh + m2m_wifi_init + m2m_wifi_handle_events + m2m_wifi_req_scan_result + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of + the events received in response. +@code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + static void request_scan_hidden_demo_ap(void); + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + static uint8 u8ScanResultIdx = 0; + + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_SCAN_DONE: + { + tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; + + printf("Num of AP found %d\n",pstrInfo->u8NumofCh); + if(pstrInfo->s8ScanState == M2M_SUCCESS) + { + u8ScanResultIdx = 0; + if(pstrInfo->u8NumofCh >= 1) + { + m2m_wifi_req_scan_result(u8ScanResultIdx); + u8ScanResultIdx ++; + } + else + { + printf("No AP Found Rescan\n"); + request_scan_hidden_demo_ap(); + } + } + else + { + printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); + } + } + break; + + case M2M_WIFI_RESP_SCAN_RESULT: + { + tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; + uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); + + printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", + pstrScanResult->u8index,pstrScanResult->s8rssi, + pstrScanResult->u8AuthType, + pstrScanResult->u8ch, + pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], + pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], + pstrScanResult->au8SSID); + + if(u8ScanResultIdx < u8NumFoundAPs) + { + // Read the next scan result + m2m_wifi_req_scan_result(index); + u8ScanResultIdx ++; + } + } + break; + default: + break; + } + } + + static void request_scan_hidden_demo_ap(void) + { + uint8 list[9]; + char ssid[] = "DEMO_AP"; + uint8 len = (uint8)(sizeof(ssid)-1); + + list[0] = 1; + list[1] = len; + memcpy(&list[2], ssid, len); // copy 7 bytes + // Scan all channels + m2m_wifi_request_scan_ssid_list(M2M_WIFI_CH_ALL, list); + } + + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + request_scan_hidden_demo_ap(); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API sint8 m2m_wifi_request_scan_ssid_list(uint8 ch,uint8 * u8Ssidlist); + +/**@}*/ +/** @defgroup WifiGetNumAPFoundFn m2m_wifi_get_num_ap_found + * @ingroup WLANAPI +* Synchronous function to retrieve the number of AP's found in the last scan request, The function reads the number of APs from global variable which was updated in the Wi-Fi callback function through the M2M_WIFI_RESP_SCAN_DONE event. +* Function used only in STA mode only. + */ + /**@{*/ +/*! +@fn NMI_API uint8 m2m_wifi_get_num_ap_found(void); + +@see m2m_wifi_request_scan + M2M_WIFI_RESP_SCAN_DONE + M2M_WIFI_RESP_SCAN_RESULT +@pre m2m_wifi_request_scan need to be called first + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback + is done through passing it to the @ref m2m_wifi_init. + - The event @ref M2M_WIFI_RESP_SCAN_DONE must be handled in the callback to receive the requested scan information. +@warning This function must be called only in the wi-fi callback function when the events @ref M2M_WIFI_RESP_SCAN_DONE or @ref M2M_WIFI_RESP_SCAN_RESULT + are received. + Calling this function in any other place will result in undefined/outdated numbers. +@return Return the number of AP's found in the last Scan Request. + +\section Example + The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of + the events received in response. +@code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + static uint8 u8ScanResultIdx = 0; + + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_SCAN_DONE: + { + tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; + + printf("Num of AP found %d\n",pstrInfo->u8NumofCh); + if(pstrInfo->s8ScanState == M2M_SUCCESS) + { + u8ScanResultIdx = 0; + if(pstrInfo->u8NumofCh >= 1) + { + m2m_wifi_req_scan_result(u8ScanResultIdx); + u8ScanResultIdx ++; + } + else + { + printf("No AP Found Rescan\n"); + m2m_wifi_request_scan(M2M_WIFI_CH_ALL); + } + } + else + { + printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); + } + } + break; + + case M2M_WIFI_RESP_SCAN_RESULT: + { + tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; + uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); + + printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", + pstrScanResult->u8index,pstrScanResult->s8rssi, + pstrScanResult->u8AuthType, + pstrScanResult->u8ch, + pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], + pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], + pstrScanResult->au8SSID); + + if(u8ScanResultIdx < u8NumFoundAPs) + { + // Read the next scan result + m2m_wifi_req_scan_result(index); + u8ScanResultIdx ++; + } + } + break; + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // Scan all channels + m2m_wifi_request_scan(M2M_WIFI_CH_ALL); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API uint8 m2m_wifi_get_num_ap_found(void); +/**@}*/ +/** @defgroup WifiReqScanResult m2m_wifi_req_scan_result +* @ingroup WLANAPI +* Synchronous call to read the AP information from the SCAN Result list with the given index. +* This function is expected to be called when the response events M2M_WIFI_RESP_SCAN_RESULT or +* M2M_WIFI_RESP_SCAN_DONE are received in the wi-fi callback function. +* The response information received can be obtained through the casting to the @ref tstrM2mWifiscanResult structure + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_req_scan_result(uint8 index); +@param [in] index + Index for the requested result, the index range start from 0 till number of AP's found + +@see tstrM2mWifiscanResult + m2m_wifi_get_num_ap_found + m2m_wifi_request_scan + +@pre @ref m2m_wifi_request_scan needs to be called first, then m2m_wifi_get_num_ap_found + to get the number of AP's found + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback + is done through passing it to the @ref m2m_wifi_init function. + - The event @ref M2M_WIFI_RESP_SCAN_RESULT must be handled in the callback to receive the requested scan information. +@warning Function used in STA mode only. the scan results are updated only if the scan request is called. + Calling this function only without a scan request will lead to firmware errors. + Refrain from introducing a large delay between the scan request and the scan result request, to prevent + errors occurring. + +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of + the events received in response. +@code + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + static uint8 u8ScanResultIdx = 0; + + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_SCAN_DONE: + { + tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; + + printf("Num of AP found %d\n",pstrInfo->u8NumofCh); + if(pstrInfo->s8ScanState == M2M_SUCCESS) + { + u8ScanResultIdx = 0; + if(pstrInfo->u8NumofCh >= 1) + { + m2m_wifi_req_scan_result(u8ScanResultIdx); + u8ScanResultIdx ++; + } + else + { + printf("No AP Found Rescan\n"); + m2m_wifi_request_scan(M2M_WIFI_CH_ALL); + } + } + else + { + printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); + } + } + break; + + case M2M_WIFI_RESP_SCAN_RESULT: + { + tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; + uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); + + printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", + pstrScanResult->u8index,pstrScanResult->s8rssi, + pstrScanResult->u8AuthType, + pstrScanResult->u8ch, + pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], + pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], + pstrScanResult->au8SSID); + + if(u8ScanResultIdx < u8NumFoundAPs) + { + // Read the next scan result + m2m_wifi_req_scan_result(index); + u8ScanResultIdx ++; + } + } + break; + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // Scan all channels + m2m_wifi_request_scan(M2M_WIFI_CH_ALL); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API sint8 m2m_wifi_req_scan_result(uint8 index); +/**@}*/ +/** @defgroup WifiReqCurrentRssiFn m2m_wifi_req_curr_rssi + * @ingroup WLANAPI + * Asynchronous request for the current RSSI of the connected AP. + * The response received in through the @ref M2M_WIFI_RESP_CURRENT_RSSI event. + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_req_curr_rssi(void); +@pre - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered before initialization. Registering the callback + is done through passing it to the [m2m_wifi_init](@ref m2m_wifi_init) through the @ref tstrWifiInitParam initialization structure. + - The event @ref M2M_WIFI_RESP_CURRENT_RSSI must be handled in the callback to receive the requested Rssi information. +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet demonstrates how the RSSI request is called in the application's main function and the handling of the event received in the callback. +@code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + static uint8 u8ScanResultIdx = 0; + + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_CURRENT_RSSI: + { + sint8 *rssi = (sint8*)pvMsg; + M2M_INFO("ch rssi %d\n",*rssi); + } + break; + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // Scan all channels + m2m_wifi_req_curr_rssi(); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode + +*/ +NMI_API sint8 m2m_wifi_req_curr_rssi(void); +/**@}*/ +/** @defgroup WifiGetOtpMacAddFn m2m_wifi_get_otp_mac_address +* @ingroup WLANAPI +* Request the MAC address stored on the One Time Programmable(OTP) memory of the device. +* The function is blocking until the response is received. +*/ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); + +@param [out] pu8MacAddr + Output MAC address buffer of 6 bytes size. Valid only if *pu8Valid=1. +@param [out] pu8IsValid + Output boolean value to indicate the validity of pu8MacAddr in OTP. + Output zero if the OTP memory is not programmed, non-zero otherwise. +@pre m2m_wifi_init required to be called before any WIFI/socket function +@see m2m_wifi_get_mac_address + +@return The function returns @ref M2M_SUCCESS for success and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); +/**@}*/ +/** @defgroup WifiGetMacAddFn m2m_wifi_get_mac_address +* @ingroup WLANAPI +* Function to retrieve the current MAC address. The function is blocking until the response is received. +*/ +/**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr) +@param [out] pu8MacAddr + Output MAC address buffer of 6 bytes size. +@pre m2m_wifi_init required to be called before any WIFI/socket function +@see m2m_wifi_get_otp_mac_address +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr); +/**@}*/ +/** @defgroup SetSleepModeFn m2m_wifi_set_sleep_mode + * @ingroup WLANAPI + * This is one of the two synchronous power-save setting functions that + * allow the host MCU application to tweak the system power consumption. Such tweaking can be done through one of two ways: +* 1) Changing the power save mode, to one of the allowed power save modes @ref tenuPowerSaveModes. This is done by setting the first parameter +* 2) Configuring DTIM monitoring: Configuring beacon monitoring parameters by enabling or disabling the reception of broadcast/multicast data. +* this is done by setting the second parameter. + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn); +@param [in] PsTyp + Desired power saving mode. Supported types are enumerated in @ref tenuPowerSaveModes. +@param [in] BcastEn + Broadcast reception enable flag. + If it is 1, the WINC1500 will be awake each DTIM beacon for receiving broadcast traffic. + If it is 0, the WINC1500: disable broadcast traffic. Through this flag the WINC1500 will not wakeup at the DTIM beacon, but it will wakeup depends only + on the the configured Listen Interval. + +@warning The function called once after initialization. + +@see tenuPowerSaveModes + m2m_wifi_get_sleep_mode + m2m_wifi_set_lsn_int + +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn); +/**@}*/ +/** @defgroup WifiRequestSleepFn m2m_wifi_request_sleep + * @ingroup WLANAPI + * Synchronous power-save sleep request function, which requests from the WINC1500 device to sleep in the currenlty configured power save mode as defined + * by the @ref m2m_wifi_set_sleep_mode, for a specific time as defined by the passed in parameter. + * This function should be used in the @ref M2M_PS_MANUAL power save mode only. + * A wake up request is automatically performed by the WINC1500 device when any host driver API function, e.g. Wi-Fi or socket operation is called. + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_request_sleep(uint32 u32SlpReqTime); +@param [in] u32SlpReqTime + Request sleep time in ms + The best recommended sleep duration is left to be determined by the application. Taking into account that if the application sends notifications very rarely, + sleeping for a long time can be a power-efficient decision. In contrast applications that are senstive for long periods of absence can experience + performance degradation in the connection if long sleeping times are used. +@warning The function should be called in @ref M2M_PS_MANUAL power save mode only. As enumerated in @ref tenuPowerSaveModes + It's also important to note that during the sleeping time while in the M2M_PS_MANUAL mode, AP beacon monitoring is bypassed and the wifi-connection may drop if + the sleep period is enlongated. +@see tenuPowerSaveModes + m2m_wifi_set_sleep_mode + +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_request_sleep(uint32 u32SlpReqTime); +/**@}*/ +/** @defgroup GetSleepModeFn m2m_wifi_get_sleep_mode + * @ingroup WLANAPI + * Synchronous power save mode retrieval function. + */ + /**@{*/ +/*! +@fn NMI_API uint8 m2m_wifi_get_sleep_mode(void); +@see tenuPowerSaveModes + m2m_wifi_set_sleep_mode +@return The current operating power saving mode based on the enumerated sleep modes @ref tenuPowerSaveModes. +*/ +NMI_API uint8 m2m_wifi_get_sleep_mode(void); +/**@}*/ +/** @defgroup WifiReqClientCtrlFn m2m_wifi_req_client_ctrl + * @ingroup WLANAPI + * Asynchronous command sending function to the PS Client (An WINC1500 board running the ps_firmware) +* if the PS client send any command it will be received through the @ref M2M_WIFI_RESP_CLIENT_INFO event + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_req_client_ctrl(uint8 cmd); +@brief +@param [in] cmd + Control command sent from PS Server to PS Client (command values defined by the application) +@pre @ref m2m_wifi_req_server_init should be called first +@warning This mode is not supported in the current release. +@see m2m_wifi_req_server_init + M2M_WIFI_RESP_CLIENT_INFO +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_req_client_ctrl(uint8 cmd); +/**@}*/ +/** @defgroup WifiReqServerInit m2m_wifi_req_server_init + * @ingroup WLANAPI + * Synchronous function to initialize the PS Server. + * The WINC1500 supports non secure communication with another WINC1500, +* (SERVER/CLIENT) through one byte command (probe request and probe response) without any connection setup. +* The server mode can't be used with any other modes (STA/P2P/AP) +*/ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_req_server_init(uint8 ch); +@param [in] ch + Server listening channel +@see m2m_wifi_req_client_ctrl +@warning This mode is not supported in the current release. +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_req_server_init(uint8 ch); +/**@}*/ +/** @defgroup WifiSetDeviceNameFn m2m_wifi_set_device_name + * @ingroup WLANAPI + * Sets the WINC device name. The name string is used as a device name in both (P2P) WiFi-Direct mode as well as DHCP hostname (option 12). + * For P2P devices to communicate a device name must be present. If it is not set through this function a default name is assigned. + * The default name is WINC-XX-YY, where XX and YY are the last 2 octets of the OTP MAC address. If OTP (eFuse) is programmed, + * then the default name is WINC-00-00. + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength); +@param [in] pu8DeviceName + A Buffer holding the device name. Device name is a null terminated C string. +@param [in] u8DeviceNameLength + The length of the device name. Should not exceed the maximum device name's length @ref M2M_DEVICE_NAME_MAX (including null character). +@warning The function called once after initialization. + Used for the Wi-Fi Direct (P2P) as well as DHCP client hostname option (12). +@warning Device name shall contain only characters allowed in valid internet host name as defined in RFC 952 and 1123. +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength); +/**@}*/ +/** @defgroup WifiSetLsnIntFn m2m_wifi_set_lsn_int + * @ingroup WLANAPI +* This is one of the two synchronous power-save setting functions that +* allow the host MCU application to tweak the system power consumption. Such tweaking can be done by modifying the +* the Wi-Fi listen interval. The listen interval is how many beacon periods the station can sleep before it wakes up to receive data buffer in AP. +* It is represented in units of AP beacon periods(100ms). +*/ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt * pstrM2mLsnInt); + +@param [in] pstrM2mLsnInt + Structure holding the listen interval configurations. +@pre Function @m2m_wifi_set_sleep_mode shall be called first, to set the power saving mode required. +@warning The function should be called once after initialization. +@see tstrM2mLsnInt + m2m_wifi_set_sleep_mode +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt *pstrM2mLsnInt); +/**@}*/ +/** @defgroup WifiEnableMonitorModeFn m2m_wifi_enable_monitoring_mode + * @ingroup WLANAPI + * Asynchronous Wi-Fi monitoring mode (Promiscuous mode) enabling function. This function enables the monitoring mode, thus allowing two operations to be performed: + * 1) Transmission of manually configured frames, through using the @ref m2m_wifi_send_wlan_pkt function. + * 2) Reception of frames based on a defined filtering criteria + * When the monitoring mode is enabled, reception of all frames that satisfy the filter criteria passed in as a parameter is allowed, on the current wireless channel \n. + * All packets that meet the filtering criteria are passed to the application layer, to be handled by the assigned monitoring callback function \n. + * The monitoring callback function must be implemented before starting the monitoring mode, in-order to handle the packets received \n. + * Registering of the implemented callback function is through the callback pointer @ref tpfAppMonCb in the @ref tstrWifiInitParam structure\n. + * passed to @ref m2m_wifi_init function at initialization. + * + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_enable_monitoring_mode(tstrM2MWifiMonitorModeCtrl *, uint8 *, uint16 , uint16); + * @param [in] pstrMtrCtrl + * Pointer to @ref tstrM2MWifiMonitorModeCtrl structure holding the filtering parameters. + * @param [in] pu8PayloadBuffer + * Pointer to a buffer allocated by the application. The buffer SHALL hold the Data field of + * the WIFI RX Packet (Or a part from it). If it is set to NULL, the WIFI data payload will + * be discarded by the monitoring driver. + * @param [in] u16BufferSize + * The total size of the pu8PayloadBuffer in bytes. + * @param [in] u16DataOffset + * Starting offset in the DATA FIELD of the received WIFI packet. The application may be interested + * in reading specific information from the received packet. It must assign the offset to the starting + * position of it relative to the DATA payload start.\n + * \e Example, \e if \e the \e SSID \e is \e needed \e to \e be \e read \e from \e a \e PROBE \e REQ \e packet, \e the \e u16Offset \e MUST \e be \e set \e to \e 0. + * @warning When This mode is enabled, you can not be connected in any mode (Station, Access Point, or P2P).\n + * @see tstrM2MWifiMonitorModeCtrl + tstrM2MWifiRxPacketInfo + tstrWifiInitParam + tenuM2mScanCh + m2m_wifi_disable_monitoring_mode + m2m_wifi_send_wlan_pkt + m2m_wifi_send_ethernet_pkt + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*\section Example +* The example demonstrates the main function where-by the monitoring enable function is called after the initialization of the driver and the packets are +* handled in the callback function. +* @code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + //Declare receive buffer + uint8 gmgmt[1600]; + + //Callback functions + void wifi_cb(uint8 u8WiFiEvent, void * pvMsg) + { + ; + } + void wifi_monitoring_cb(tstrM2MWifiRxPacketInfo *pstrWifiRxPacket, uint8 *pu8Payload, uint16 u16PayloadSize) + { + if((NULL != pstrWifiRxPacket) && (0 != u16PayloadSize)) { + if(MANAGEMENT == pstrWifiRxPacket->u8FrameType) { + M2M_INFO("***# MGMT PACKET #***\n"); + } else if(DATA_BASICTYPE == pstrWifiRxPacket->u8FrameType) { + M2M_INFO("***# DATA PACKET #***\n"); + } else if(CONTROL == pstrWifiRxPacket->u8FrameType) { + M2M_INFO("***# CONTROL PACKET #***\n"); + } + } + } + + int main() + { + //Register wifi_monitoring_cb + tstrWifiInitParam param; + param.pfAppWifiCb = wifi_cb; + param.pfAppMonCb = wifi_monitoring_cb; + + nm_bsp_init(); + + if(!m2m_wifi_init(¶m)) { + //Enable Monitor Mode with filter to receive all data frames on channel 1 + tstrM2MWifiMonitorModeCtrl strMonitorCtrl = {0}; + strMonitorCtrl.u8ChannelID = M2M_WIFI_CH_1; + strMonitorCtrl.u8FrameType = DATA_BASICTYPE; + strMonitorCtrl.u8FrameSubtype = M2M_WIFI_FRAME_SUB_TYPE_ANY; //Receive any subtype of data frame + m2m_wifi_enable_monitoring_mode(&strMonitorCtrl, gmgmt, sizeof(gmgmt), 0); + + while(1) { + m2m_wifi_handle_events(NULL); + } + } + return 0; + } + * @endcode + */ +NMI_API sint8 m2m_wifi_enable_monitoring_mode(tstrM2MWifiMonitorModeCtrl *pstrMtrCtrl, uint8 *pu8PayloadBuffer, + uint16 u16BufferSize, uint16 u16DataOffset); +/**@}*/ +/** @defgroup WifiDisableMonitorModeFn m2m_wifi_disable_monitoring_mode + * @ingroup WLANAPI + * Synchronous function to disable Wi-Fi monitoring mode (Promiscuous mode). Expected to be called, if the enable monitoring mode is set, but if it was called without enabling + * no negative impact will reside. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_disable_monitoring_mode(void); + * @see m2m_wifi_enable_monitoring_mode + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_disable_monitoring_mode(void); + /**@}*/ + /** @defgroup SendWlanPktFn m2m_wifi_send_wlan_pkt + * @ingroup WLANAPI + * Synchronous function to transmit a WIFI RAW packet while the implementation of this packet is left to the application developer. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_send_wlan_pkt(uint8 *, uint16, uint16); + + * @param [in] pu8WlanPacket + * Pointer to a buffer holding the whole WIFI frame. + * @param [in] u16WlanHeaderLength + * The size of the WIFI packet header ONLY. + * @param [in] u16WlanPktSize + * The size of the whole bytes in packet. + * @see m2m_wifi_enable_monitoring_mode + m2m_wifi_disable_monitoring_mode + * @pre Enable Monitoring mode first using @ref m2m_wifi_enable_monitoring_mode + * @warning This function available in monitoring mode ONLY.\n + * @note Packets are user's responsibility. + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_send_wlan_pkt(uint8 *pu8WlanPacket, uint16 u16WlanHeaderLength, uint16 u16WlanPktSize); +/**@}*/ +/** @defgroup WifiSendEthernetPktFn m2m_wifi_send_ethernet_pkt + * @ingroup WLANAPI + * Synchronous function to transmit an Ethernet packet. Transmit a packet directly in ETHERNET/bypass mode where the TCP/IP stack is disabled and the implementation of this packet is left to the application developer. + * The Ethernet packet composition is left to the application developer. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_send_ethernet_pkt(uint8* pu8Packet,uint16 u16PacketSize) + * @param [in] pu8Packet + * Pointer to a buffer holding the whole Ethernet frame. + * @param [in] u16PacketSize + * The size of the whole bytes in packet. + * @warning This function available in ETHERNET/Bypass mode ONLY. Make sure that application defines @ref ETH_MODE.\n + * @note Packets are the user's responsibility. + * @sa m2m_wifi_enable_mac_mcast,m2m_wifi_set_receive_buffer + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + + */ +NMI_API sint8 m2m_wifi_send_ethernet_pkt(uint8* pu8Packet,uint16 u16PacketSize); +/**@}*/ +/** @defgroup WifiEnableSntpFn m2m_wifi_enable_sntp + * @ingroup WLANAPI + * Synchronous function to enable/disable the native Simple Network Time Protocol(SNTP) client in the WINC1500 firmware.\n + * The SNTP is enabled by default at start-up.The SNTP client at firmware is used to synchronize the system clock to the UTC time from the well known time + * servers (e.g. "time-c.nist.gov"). The SNTP client uses a default update cycle of 1 day. + * The UTC is important for checking the expiration date of X509 certificates used while establishing + * TLS (Transport Layer Security) connections. + * It is highly recommended to use it if there is no other means to get the UTC time. If there is a RTC + * on the host MCU, the SNTP could be disabled and the host should set the system time to the firmware + * using the @ref m2m_wifi_set_system_time function. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_enable_sntp(uint8); + * @param [in] bEnable +* Enabling/Disabling flag + * '0' :disable SNTP + * '1' :enable SNTP + * @see m2m_wifi_set_sytem_time + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_enable_sntp(uint8 bEnable); +/**@}*/ +/** @defgroup WifiSetSystemTime m2m_wifi_set_sytem_time + * @ingroup WLANAPI + * Synchronous function for setting the system time in time/date format (@ref uint32).\n + * The @ref tstrSystemTime structure can be used as a reference to the time values that should be set and pass its value as @ref uint32 + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_set_sytem_time(uint32); + * @param [in] u32UTCSeconds + * Seconds elapsed since January 1, 1900 (NTP Timestamp). + * @see m2m_wifi_enable_sntp + * tstrSystemTime + * @note If there is an RTC on the host MCU, the SNTP could be disabled and the host should set the system time to the firmware + * using the API @ref m2m_wifi_set_sytem_time. + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_set_sytem_time(uint32 u32UTCSeconds); +/**@}*/ +/** @defgroup WifiGetSystemTime m2m_wifi_get_sytem_time + * @ingroup WLANAPI + * Asynchronous function used to retrieve the system time through the use of the response @ref M2M_WIFI_RESP_GET_SYS_TIME. + * Response time retrieved is parsed into the members defined in the structure @ref tstrSystemTime. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_get_sytem_time(void); + * @see m2m_wifi_enable_sntp + tstrSystemTime + * @note Get the system time from the SNTP client + * using the API @ref m2m_wifi_get_sytem_time. + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_get_sytem_time(void); +/**@}*/ +/** @defgroup WifiSetCustInfoElementFn m2m_wifi_set_cust_InfoElement + * @ingroup WLANAPI + * Synchronous function to Add/Remove user-defined Information Element to the WIFIBeacon and Probe Response frames while chip mode is Access Point Mode.\n + * According to the information element layout shown bellow, if it is required to set new data for the information elements, pass in the buffer with the + * information according to the sizes and ordering defined bellow. However, if it's required to delete these IEs, fill the buffer with zeros. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_set_cust_InfoElement(uint8*); + * @param [in] pau8M2mCustInfoElement + * Pointer to Buffer containing the IE to be sent. It is the application developer's responsibility to ensure on the correctness of the information element's ordering passed in. + * @warning - Size of All elements combined must not exceed 255 byte.\n + * - Used in Access Point Mode \n + * @note IEs Format will be follow the following layout:\n + * @verbatim + --------------- ---------- ---------- ------------------- -------- -------- ----------- ---------------------- + | Byte[0] | Byte[1] | Byte[2] | Byte[3:length1+2] | ..... | Byte[n] | Byte[n+1] | Byte[n+2:lengthx+2] | + |---------------|----------|----------|-------------------|-------- --------|-----------|------------------| + | #of all Bytes | IE1 ID | Length1 | Data1(Hex Coded) | ..... | IEx ID | Lengthx | Datax(Hex Coded) | + --------------- ---------- ---------- ------------------- -------- -------- ----------- ---------------------- + * @endverbatim + * @see m2m_wifi_enable_sntp + * tstrSystemTime + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + \section Example + The example demonstrates how the information elements are set using this function. + *@code + * + char elementData[21]; + static char state = 0; // To Add, Append, and Delete + if(0 == state) { //Add 3 IEs + state = 1; + //Total Number of Bytes + elementData[0]=12; + //First IE + elementData[1]=200; elementData[2]=1; elementData[3]='A'; + //Second IE + elementData[4]=201; elementData[5]=2; elementData[6]='B'; elementData[7]='C'; + //Third IE + elementData[8]=202; elementData[9]=3; elementData[10]='D'; elementData[11]=0; elementData[12]='F'; + } else if(1 == state) { + //Append 2 IEs to others, Notice that we keep old data in array starting with\n + //element 13 and total number of bytes increased to 20 + state = 2; + //Total Number of Bytes + elementData[0]=20; + //Fourth IE + elementData[13]=203; elementData[14]=1; elementData[15]='G'; + //Fifth IE + elementData[16]=204; elementData[17]=3; elementData[18]='X'; elementData[19]=5; elementData[20]='Z'; + } else if(2 == state) { //Delete All IEs + state = 0; + //Total Number of Bytes + elementData[0]=0; + } + m2m_wifi_set_cust_InfoElement(elementData); + * @endcode + */ +NMI_API sint8 m2m_wifi_set_cust_InfoElement(uint8* pau8M2mCustInfoElement); + /**@}*/ +/** @defgroup WifiSetPowerProfile m2m_wifi_set_power_profile + * @ingroup WLANAPI + * Change the power profile mode + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode); +@brief +@param [in] u8PwrMode + Change the WINC1500 power profile to different mode based on the enumeration + @ref tenuM2mPwrMode +@pre Must be called after the initializations and before any connection request and can't be changed in run time. +@sa tenuM2mPwrMode + m2m_wifi_init +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode); + /**@}*/ + /** @defgroup WifiSetTxPower m2m_wifi_set_tx_power + * @ingroup WLANAPI + * Set the TX power tenuM2mTxPwrLevel + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel); +@param [in] u8TxPwrLevel + change the TX power based on the enumeration tenuM2mTxPwrLevel +@pre Must be called after the initialization and before any connection request and can't be changed in runtime. +@sa tenuM2mTxPwrLevel + m2m_wifi_init +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel); + /**@}*/ +/** @defgroup WifiEnableFirmware m2m_wifi_enable_firmware_logs +* @ingroup WLANAPI +* Enable or Disable logs in run time (Disabling Firmware logs will +* enhance the firmware start-up time and performance) +*/ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable); +@param [in] u8Enable + Set 1 to enable the logs, 0 for disable +@pre Must be called after intialization through the following function @ref m2m_wifi_init +@sa __DISABLE_FIRMWARE_LOGS__ (build option to disable logs from initializations) + m2m_wifi_init +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable); + /**@}*/ + /** @defgroup WifiSetBatteryVoltage m2m_wifi_set_battery_voltage +* @ingroup WLANAPI +* Set the battery voltage to update the firmware calculations +*/ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_set_battery_voltage(uint8 u8BattVolt) +@brief Set the battery voltage to update the firmware calculations +@param [in] dbBattVolt + Battery Volt in double +@pre Must be called after intialization through the following function @ref m2m_wifi_init +@sa m2m_wifi_init +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +sint8 m2m_wifi_set_battery_voltage(uint16 u16BattVoltx100); + /**@}*/ + /** @defgroup WifiSetGains m2m_wifi_set_gains +* @ingroup WLANAPI +* Set the chip gains mainly (PPA for 11b/11gn) +*/ + /**@{*/ +/*! +@fn sint8 m2m_wifi_set_gains(tstrM2mWifiGainsParams* pstrM2mGain); +@brief Set the chip PPA gain for 11b/11gn +@param [in] pstrM2mGain + tstrM2mWifiGainsParams contain gain parmaters as implemnted in rf document +@pre Must be called after intialization through the following function @ref m2m_wifi_init +@sa m2m_wifi_init +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +sint8 m2m_wifi_set_gains(tstrM2mWifiGainsParams* pstrM2mGain); + /**@}*/ +/** @defgroup WifiGetFirmwareVersion m2m_wifi_get_firmware_version +* @ingroup WLANAPI +* Get Firmware version info as defined in the structure @ref tstrM2mRev. +*/ + /**@{*/ +/*! +@fn m2m_wifi_get_firmware_version(tstrM2mRev* pstrRev) +@param [out] M2mRev + Pointer to the structure @ref tstrM2mRev that contains the firmware version parameters +@pre Must be called after intialization through the following function @ref m2m_wifi_init +@sa m2m_wifi_init +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +sint8 m2m_wifi_get_firmware_version(tstrM2mRev *pstrRev); +/**@}*/ +#ifdef ETH_MODE +/** @defgroup WifiEnableMacMcastFn m2m_wifi_enable_mac_mcast + * @ingroup WLANAPI + * Synchronous function for filtering received MAC addresses from certain MAC address groups. + * This function allows the addtion/removal of certain MAC addresses, used in the multicast filter. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8 *, uint8); + * @brief + * @param [in] pu8MulticastMacAddress + * Pointer to MAC address + * @param [in] u8AddRemove + * A flag to add or remove the MAC ADDRESS, based on the following values: + * - 0 : remove MAC address + * - 1 : add MAC address + * @warning This function is available in ETHERNET/bypass mode ONLY. Make sure that the application defines @ref ETH_MODE.\n + * @note Maximum number of MAC addresses that could be added is 8. + * @sa m2m_wifi_set_receive_buffer, m2m_wifi_send_ethernet_pkt + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8* pu8MulticastMacAddress, uint8 u8AddRemove); +/**@}*/ +/** @defgroup SetReceiveBufferFn m2m_wifi_set_receive_buffer + * @ingroup WLANAPI + * Synchronous function for setting or modifying the receiver buffer's length. + * In the ETHERNET/bypass mode the application should define a callback of type @ref tpfAppEthCb, through which the application handles the received + * ethernet frames. It is through this callback function that the user can dynamically modify the length of the currently used receiver buffer. + *@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_set_receive_buffer(void *, uint16); + + * @param [in] pvBuffer + * Pointer to Buffer to receive data. + * NULL pointer causes a negative error @ref M2M_ERR_FAIL. + * + * @param [in] u16BufferLen + * Length of data to be received. Maximum length of data should not exceed the size defined by TCP/IP + * defined as @ref SOCKET_BUFFER_MAX_LENGTH + * + * @warning This function is available in the Ethernet/bypass mode ONLY. Make sure that the application defines @ref ETH_MODE.\n + * @sa m2m_wifi_enable_mac_mcast,m2m_wifi_send_ethernet_pkt + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_set_receive_buffer(void* pvBuffer,uint16 u16BufferLen); +/**@}*/ +#endif /* ETH_MODE */ +/** @defgroup GetPrngBytes m2m_wifi_prng_get_random_bytes + * @ingroup WLANAPI + * Asynchronous function for retrieving from the firmware a pseudo-random set of bytes as specifed in the size passed in as a parameter. + * The registered wifi-cb function retrieves the random bytes through the response @ref M2M_WIFI_RESP_GET_PRNG + *@{*/ +/*! + * @fn sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PRNGBuff,uint16 u16PRNGSize) + * @param [out] pu8PrngBuff + * Pointer to a buffer to receive data. + * @param [in] u16PrngSize + * Request size in bytes + *@warning Size greater than the maximum specified (@ref M2M_BUFFER_MAX_SIZE - sizeof(tstrPrng)) + * causes a negative error @ref M2M_ERR_FAIL. + *@see tstrPrng + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PrngBuff,uint16 u16PrngSize); +/**@}*/ +#ifdef __cplusplus +} +#endif +#endif /* __M2M_WIFI_H__ */ + diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ate_mode.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ate_mode.c new file mode 100644 index 0000000..beb1af8 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ate_mode.c @@ -0,0 +1,826 @@ +/** + * + * \file + * + * \brief NMC1500 Peripherials Application Interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifdef _M2M_ATE_FW_ +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#include "driver/include/m2m_ate_mode.h" +#include "driver/source/nmasic.h" +#include "driver/source/nmdrv.h" +#include "m2m_hif.h" +#include "driver/source/nmbus.h" +#include "bsp/include/nm_bsp.h" + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#define rInterrupt_CORTUS_0 (0x10a8) +#define rInterrupt_CORTUS_1 (0x10ac) +#define rInterrupt_CORTUS_2 (0x10b0) + +#define rBurstTx_NMI_TX_RATE (0x161d00) +#define rBurstTx_NMI_NUM_TX_FRAMES (0x161d04) +#define rBurstTx_NMI_TX_FRAME_LEN (0x161d08) +#define rBurstTx_NMI_TX_CW_PARAM (0x161d0c) +#define rBurstTx_NMI_TX_GAIN (0x161d10) +#define rBurstTx_NMI_TX_DPD_CTRL (0x161d14) +#define rBurstTx_NMI_USE_PMU (0x161d18) +#define rBurstTx_NMI_TEST_CH (0x161d1c) +#define rBurstTx_NMI_TX_PHY_CONT (0x161d20) +#define rBurstTx_NMI_TX_CW_MODE (0x161d24) +#define rBurstTx_NMI_TEST_XO_OFF (0x161d28) +#define rBurstTx_NMI_USE_EFUSE_XO_OFF (0x161d2c) + +#define rBurstTx_NMI_MAC_FILTER_ENABLE_DA (0x161d30) +#define rBurstTx_NMI_MAC_ADDR_LO_PEER (0x161d34) +#define rBurstTx_NMI_MAC_ADDR_LO_SELF (0x161d38) +#define rBurstTx_NMI_MAC_ADDR_HI_PEER (0x161d3c) +#define rBurstTx_NMI_MAC_ADDR_HI_SELF (0x161d40) +#define rBurstTx_NMI_RX_PKT_CNT_SUCCESS (0x161d44) +#define rBurstTx_NMI_RX_PKT_CNT_FAIL (0x161d48) +#define rBurstTx_NMI_SET_SELF_MAC_ADDR (0x161d4c) +#define rBurstTx_NMI_MAC_ADDR_LO_SA (0x161d50) +#define rBurstTx_NMI_MAC_ADDR_HI_SA (0x161d54) +#define rBurstTx_NMI_MAC_FILTER_ENABLE_SA (0x161d58) + +#define rBurstRx_NMI_RX_ALL_PKTS_CONT (0x9898) +#define rBurstRx_NMI_RX_ERR_PKTS_CONT (0x988c) + +#define TX_DGAIN_MAX_NUM_REGS (4) +#define TX_DGAIN_REG_BASE_ADDRESS (0x1240) +#define TX_GAIN_CODE_MAX_NUM_REGS (3) +#define TX_GAIN_CODE_BASE_ADDRESS (0x1250) +#define TX_PA_MAX_NUM_REGS (3) +#define TX_PA_BASE_ADDRESS (0x1e58) +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +VARIABLES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +volatile static uint8 gu8AteIsRunning = 0; /*!< ATE firmware status, 1 means ATE is running otherwise stopped */ +volatile static uint8 gu8RxState = 0; /*!< RX status, 1 means Rx is running otherwise stopped */ +volatile static uint8 gu8TxState = 0; /*!< TX status, 1 means Tx is running otherwise stopped */ +volatile static uint32 gaAteFwTxRates[M2M_ATE_MAX_NUM_OF_RATES] = +{ + 0x01, 0x02, 0x05, 0x0B, /*B-Rats*/ + 0x06, 0x09, 0x0C, 0x12, 0x18, 0x24, 0x30, 0x36, /*G-Rats*/ + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87 /*N-Rats*/ +}; + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +STATIC FUNCTIONS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +static void m2m_ate_set_rx_status(uint8 u8Value) +{ + gu8RxState = u8Value; +} + +static void m2m_ate_set_tx_status(uint8 u8Value) +{ + gu8TxState = u8Value; +} + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION IMPLEMENTATION +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/*! +@fn \ + sint8 m2m_ate_init(void); + +@brief + This function used to download ATE firmware from flash and start it + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_init(void) +{ + sint8 s8Ret = M2M_SUCCESS; + uint8 u8WifiMode = M2M_WIFI_MODE_ATE_HIGH; + + s8Ret = nm_drv_init(&u8WifiMode); + + return s8Ret; +} + +/*! +@fn \ + sint8 m2m_ate_init(tstrM2mAteInit *pstrInit); + +@brief + This function used to download ATE firmware from flash and start it + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_init_param(tstrM2mAteInit *pstrInit) +{ + sint8 s8Ret = M2M_SUCCESS; + + s8Ret = nm_drv_init((void*)&pstrInit->u8RxPwrMode); + + return s8Ret; +} + +/*! +@fn \ + sint8 m2m_ate_deinit(void); + +@brief + De-Initialization of ATE firmware mode + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_deinit(void) +{ + return nm_drv_deinit(NULL); +} + +/*! +@fn \ + sint8 m2m_ate_set_fw_state(uint8); + +@brief + This function used to change ATE firmware status from running to stopped or vice versa. + +@param [in] u8State + Required state of ATE firmware, one of \ref tenuM2mAteFwState enumeration values. +@return + The function SHALL return 0 for success and a negative value otherwise. +\sa + m2m_ate_init +*/ +sint8 m2m_ate_set_fw_state(uint8 u8State) +{ + sint8 s8Ret = M2M_SUCCESS; + uint32_t u32Val = 0; + + if((M2M_ATE_FW_STATE_STOP == u8State) && (M2M_ATE_FW_STATE_STOP != gu8AteIsRunning)) + { + u32Val = nm_read_reg(rNMI_GLB_RESET); + u32Val &= ~(1 << 10); + s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val); + gu8AteIsRunning = M2M_ATE_FW_STATE_STOP; + } + else if((M2M_ATE_FW_STATE_RUN == u8State) && (M2M_ATE_FW_STATE_RUN != gu8AteIsRunning)) + { + /* 0x1118[0]=0 at power-on-reset: pad-based control. */ + /* Switch cortus reset register to register control. 0x1118[0]=1. */ + u32Val = nm_read_reg(rNMI_BOOT_RESET_MUX); + u32Val |= (1 << 0); + s8Ret = nm_write_reg(rNMI_BOOT_RESET_MUX, u32Val); + if(M2M_SUCCESS != s8Ret) + { + goto __EXIT; + } + /** + Write the firmware download complete magic value 0x10ADD09E at + location 0xFFFF000C (Cortus map) or C000C (AHB map). + This will let the boot-rom code execute from RAM. + **/ + s8Ret = nm_write_reg(0xc0000, 0x71); + if(M2M_SUCCESS != s8Ret) + { + goto __EXIT; + } + + u32Val = nm_read_reg(rNMI_GLB_RESET); + if((u32Val & (1ul << 10)) == (1ul << 10)) + { + u32Val &= ~(1ul << 10); + s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val); + if(M2M_SUCCESS != s8Ret) + { + goto __EXIT; + } + } + + u32Val |= (1ul << 10); + s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val); + if(M2M_SUCCESS != s8Ret) + { + goto __EXIT; + } + gu8AteIsRunning = M2M_ATE_FW_STATE_RUN; + } + else + { + s8Ret = M2M_ATE_ERR_UNHANDLED_CASE; + } + +__EXIT: + if((M2M_SUCCESS == s8Ret) && (M2M_ATE_FW_STATE_RUN == gu8AteIsRunning)) + { + nm_bsp_sleep(500); /*wait for ATE firmware start up*/ + } + return s8Ret; +} + +/*! +@fn \ + sint8 m2m_ate_get_fw_state(uint8); + +@brief + This function used to return status of ATE firmware. + +@return + The function SHALL return status of ATE firmware, one of \ref tenuM2mAteFwState enumeration values. +\sa + m2m_ate_init, m2m_ate_set_fw_state +*/ +sint8 m2m_ate_get_fw_state(void) +{ + return gu8AteIsRunning; +} + +/*! +@fn \ + uint32 m2m_ate_get_tx_rate(uint8); + +@brief + This function used to return value of TX rate required by application developer. + +@param [in] u8Index + Index of required rate , one of \ref tenuM2mAteTxIndexOfRates enumeration values. +@return + The function SHALL return 0 for in case of failure otherwise selected rate value. +\sa + tenuM2mAteTxIndexOfRates +*/ +uint32 m2m_ate_get_tx_rate(uint8 u8Index) +{ + if(M2M_ATE_MAX_NUM_OF_RATES <= u8Index) + { + return 0; + } + return gaAteFwTxRates[u8Index]; +} + +/*! +@fn \ + sint8 m2m_ate_get_tx_status(void); + +@brief + This function used to return status of TX test case either running or stopped. + +@return + The function SHALL return status of ATE firmware, 1 if TX is running otherwise 0. +\sa + m2m_ate_start_tx, m2m_ate_stop_tx +*/ +sint8 m2m_ate_get_tx_status(void) +{ + return gu8TxState; +} + +/*! +@fn \ + sint8 m2m_ate_start_tx(tstrM2mAteTx *) + +@brief + This function used to start TX test case. + +@param [in] strM2mAteTx + Type of \ref tstrM2mAteTx, with the values required to enable TX test case. You must use \ref m2m_ate_init first. +@return + The function SHALL return 0 for success and a negative value otherwise. +\sa + m2m_ate_init, m2m_ate_stop_tx, m2m_ate_get_tx_status +*/ +sint8 m2m_ate_start_tx(tstrM2mAteTx * strM2mAteTx) +{ + sint8 s8Ret = M2M_SUCCESS; + uint8 u8LoopCntr = 0; + uint32_t val32; + + + if(NULL == strM2mAteTx) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + if(0 != m2m_ate_get_tx_status()) + { + s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING; + goto __EXIT; + } + + if(0 != m2m_ate_get_rx_status()) + { + s8Ret = M2M_ATE_ERR_RX_ALREADY_RUNNING; + goto __EXIT; + } + + if( (strM2mAteTx->channel_num < M2M_ATE_CHANNEL_1) || + (strM2mAteTx->channel_num > M2M_ATE_CHANNEL_14) || + (strM2mAteTx->tx_gain_sel < M2M_ATE_TX_GAIN_DYNAMIC) || + (strM2mAteTx->tx_gain_sel > M2M_ATE_TX_GAIN_TELEC) || + (strM2mAteTx->frame_len > M2M_ATE_MAX_FRAME_LENGTH) || + (strM2mAteTx->frame_len < M2M_ATE_MIN_FRAME_LENGTH) + ) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + if( (strM2mAteTx->duty_cycle < M2M_ATE_TX_DUTY_MAX_VALUE /*1*/) || + (strM2mAteTx->duty_cycle > M2M_ATE_TX_DUTY_MIN_VALUE /*10*/ ) || + (strM2mAteTx->dpd_ctrl < M2M_ATE_TX_DPD_DYNAMIC) || + (strM2mAteTx->dpd_ctrl > M2M_ATE_TX_DPD_ENABLED) || + (strM2mAteTx->use_pmu > M2M_ATE_PMU_ENABLE) || + (strM2mAteTx->phy_burst_tx < M2M_ATE_TX_SRC_MAC) || + (strM2mAteTx->phy_burst_tx > M2M_ATE_TX_SRC_PHY) || + (strM2mAteTx->cw_tx < M2M_ATE_TX_MODE_NORM) || + (strM2mAteTx->cw_tx > M2M_ATE_TX_MODE_CW) + ) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + for(u8LoopCntr=0; u8LoopCntrdata_rate) + { + break; + } + } + + if(M2M_ATE_MAX_NUM_OF_RATES == u8LoopCntr) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + + + s8Ret += nm_write_reg(rBurstTx_NMI_USE_PMU, strM2mAteTx->use_pmu); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_PHY_CONT, strM2mAteTx->phy_burst_tx); + s8Ret += nm_write_reg(rBurstTx_NMI_NUM_TX_FRAMES, strM2mAteTx->num_frames); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_GAIN, strM2mAteTx->tx_gain_sel); + s8Ret += nm_write_reg(rBurstTx_NMI_TEST_CH, strM2mAteTx->channel_num); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_FRAME_LEN, strM2mAteTx->frame_len); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_CW_PARAM, strM2mAteTx->duty_cycle); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_DPD_CTRL, strM2mAteTx->dpd_ctrl); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_RATE, strM2mAteTx->data_rate); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_CW_MODE, strM2mAteTx->cw_tx); + s8Ret += nm_write_reg(rBurstTx_NMI_TEST_XO_OFF, strM2mAteTx->xo_offset_x1000); + s8Ret += nm_write_reg(rBurstTx_NMI_USE_EFUSE_XO_OFF, strM2mAteTx->use_efuse_xo_offset); + + val32 = strM2mAteTx->peer_mac_addr[5] << 0; + val32 |= strM2mAteTx->peer_mac_addr[4] << 8; + val32 |= strM2mAteTx->peer_mac_addr[3] << 16; + nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_PEER, val32 ); + + val32 = strM2mAteTx->peer_mac_addr[2] << 0; + val32 |= strM2mAteTx->peer_mac_addr[1] << 8; + val32 |= strM2mAteTx->peer_mac_addr[0] << 16; + nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_PEER, val32 ); + + if(M2M_SUCCESS == s8Ret) + { + s8Ret += nm_write_reg(rInterrupt_CORTUS_0, 1); /*Interrupt Cortus*/ + m2m_ate_set_tx_status(1); + nm_bsp_sleep(200); /*Recommended*/ + } + +__EXIT: + return s8Ret; +} + +/*! +@fn \ + sint8 m2m_ate_stop_tx(void) + +@brief + This function used to stop TX test case. + +@return + The function SHALL return 0 for success and a negative value otherwise. +\sa + m2m_ate_init, m2m_ate_start_tx, m2m_ate_get_tx_status +*/ +sint8 m2m_ate_stop_tx(void) +{ + sint8 s8Ret = M2M_SUCCESS; + + s8Ret = nm_write_reg(rInterrupt_CORTUS_1, 1); + if(M2M_SUCCESS == s8Ret) + { + m2m_ate_set_tx_status(0); + } + + return s8Ret; +} + +/*! +@fn \ + sint8 m2m_ate_get_rx_status(uint8); + +@brief + This function used to return status of RX test case either running or stopped. + +@return + The function SHALL return status of ATE firmware, 1 if RX is running otherwise 0. +\sa + m2m_ate_start_rx, m2m_ate_stop_rx +*/ +sint8 m2m_ate_get_rx_status(void) +{ + return gu8RxState; +} + +/*! +@fn \ + sint8 m2m_ate_start_rx(tstrM2mAteRx *) + +@brief + This function used to start RX test case. + +@param [in] strM2mAteRx + Type of \ref tstrM2mAteRx, with the values required to enable RX test case. You must use \ref m2m_ate_init first. +@return + The function SHALL return 0 for success and a negative value otherwise. +\sa + m2m_ate_init, m2m_ate_stop_rx, m2m_ate_get_rx_status +*/ +sint8 m2m_ate_start_rx(tstrM2mAteRx * strM2mAteRxStr) +{ + sint8 s8Ret = M2M_SUCCESS; + uint32 val32; + if(NULL == strM2mAteRxStr) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + if(0 != m2m_ate_get_tx_status()) + { + s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING; + goto __EXIT; + } + + if(0 != m2m_ate_get_rx_status()) + { + s8Ret = M2M_ATE_ERR_RX_ALREADY_RUNNING; + goto __EXIT; + } + + if( (strM2mAteRxStr->channel_num < M2M_ATE_CHANNEL_1) || + (strM2mAteRxStr->channel_num > M2M_ATE_CHANNEL_14)|| + (strM2mAteRxStr->use_pmu > M2M_ATE_PMU_ENABLE) + ) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + s8Ret += nm_write_reg(rBurstTx_NMI_TEST_CH, strM2mAteRxStr->channel_num); + s8Ret += nm_write_reg(rBurstTx_NMI_USE_PMU, strM2mAteRxStr->use_pmu); + s8Ret += nm_write_reg(rBurstTx_NMI_TEST_XO_OFF, strM2mAteRxStr->xo_offset_x1000); + s8Ret += nm_write_reg(rBurstTx_NMI_USE_EFUSE_XO_OFF, strM2mAteRxStr->use_efuse_xo_offset); + + if(strM2mAteRxStr->override_self_mac_addr) + { + val32 = strM2mAteRxStr->self_mac_addr[5] << 0; + val32 |= strM2mAteRxStr->self_mac_addr[4] << 8; + val32 |= strM2mAteRxStr->self_mac_addr[3] << 16; + nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_SELF, val32 ); + + val32 = strM2mAteRxStr->self_mac_addr[2] << 0; + val32 |= strM2mAteRxStr->self_mac_addr[1] << 8; + val32 |= strM2mAteRxStr->self_mac_addr[0] << 16; + nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_SELF, val32 ); + } + + if(strM2mAteRxStr->mac_filter_en_sa) + { + val32 = strM2mAteRxStr->peer_mac_addr[5] << 0; + val32 |= strM2mAteRxStr->peer_mac_addr[4] << 8; + val32 |= strM2mAteRxStr->peer_mac_addr[3] << 16; + nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_SA, val32 ); + + val32 = strM2mAteRxStr->peer_mac_addr[2] << 0; + val32 |= strM2mAteRxStr->peer_mac_addr[1] << 8; + val32 |= strM2mAteRxStr->peer_mac_addr[0] << 16; + nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_SA, val32 ); + } + + nm_write_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_DA, strM2mAteRxStr->mac_filter_en_da); + nm_write_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_SA, strM2mAteRxStr->mac_filter_en_sa); + nm_write_reg(rBurstTx_NMI_SET_SELF_MAC_ADDR, strM2mAteRxStr->override_self_mac_addr); + + if(M2M_SUCCESS == s8Ret) + { + s8Ret += nm_write_reg(rInterrupt_CORTUS_2, 1); /*Interrupt Cortus*/ + m2m_ate_set_rx_status(1); + nm_bsp_sleep(10); /*Recommended*/ + } + +__EXIT: + return s8Ret; +} + +/*! +@fn \ + sint8 m2m_ate_stop_rx(void) + +@brief + This function used to stop RX test case. + +@return + The function SHALL return 0 for success and a negative value otherwise. +\sa + m2m_ate_init, m2m_ate_start_rx, m2m_ate_get_rx_status +*/ +sint8 m2m_ate_stop_rx(void) +{ + m2m_ate_set_rx_status(0); + nm_bsp_sleep(200); /*Recommended*/ + return M2M_SUCCESS; +} + +/*! +@fn \ + sint8 m2m_ate_read_rx_status(tstrM2mAteRxStatus *) + +@brief + This function used to read RX statistics from ATE firmware. + +@param [out] strM2mAteRxStatus + Type of \ref tstrM2mAteRxStatus used to save statistics of RX test case. You must use \ref m2m_ate_start_rx first. +@return + The function SHALL return 0 for success and a negative value otherwise. +\sa + m2m_ate_init, m2m_ate_start_rx +*/ +sint8 m2m_ate_read_rx_status(tstrM2mAteRxStatus *strM2mAteRxStatus) +{ + sint8 s8Ret = M2M_SUCCESS; + + if(NULL == strM2mAteRxStatus) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + if(0 != m2m_ate_get_tx_status()) + { + s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING; + goto __EXIT; + } + + if (nm_read_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_DA) || nm_read_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_SA)) + { + strM2mAteRxStatus->num_rx_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_SUCCESS) + nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_FAIL); + strM2mAteRxStatus->num_good_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_SUCCESS); + strM2mAteRxStatus->num_err_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_FAIL); + } + else + { + strM2mAteRxStatus->num_rx_pkts = nm_read_reg(rBurstRx_NMI_RX_ALL_PKTS_CONT) + nm_read_reg(0x989c); + strM2mAteRxStatus->num_err_pkts = nm_read_reg(rBurstRx_NMI_RX_ERR_PKTS_CONT); + strM2mAteRxStatus->num_good_pkts = strM2mAteRxStatus->num_rx_pkts - strM2mAteRxStatus->num_err_pkts; + } + +__EXIT: + return s8Ret; +} +/*! +@fn \ + sint8 m2m_ate_set_dig_gain(double dGaindB) + +@brief + This function is used to set the digital gain + +@param [in] double dGaindB + The digital gain value required to be set. +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_set_dig_gain(double dGaindB) +{ + uint32_t dGain, val32; + dGain = (uint32_t)(pow(10, dGaindB/20.0) * 1024.0); + + val32 = nm_read_reg(0x160cd0); + val32 &= ~(0x1ffful << 0); + val32 |= (((uint32_t)dGain) << 0); + nm_write_reg(0x160cd0, val32); + return M2M_SUCCESS; +} +/*! +@fn \ + sint8 m2m_ate_get_dig_gain(double * dGaindB) + +@brief + This function is used to get the digital gain + +@param [out] double * dGaindB + The retrieved digital gain value obtained from HW registers in dB. +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_get_dig_gain(double * dGaindB) +{ + uint32 dGain, val32; + + if(!dGaindB) return M2M_ERR_INVALID_ARG; + + val32 = nm_read_reg(0x160cd0); + + dGain = (val32 >> 0) & 0x1ffful; + *dGaindB = 20.0*log10((double)dGain / 1024.0); + + return M2M_SUCCESS; +} +/*! +@fn \ + void m2m_ate_set_pa_gain(uint8 gain_db) + +@brief + This function is used to set the PA gain (18/15/12/9/6/3/0 only) + +@param [in] uint8 gain_db + PA gain level allowed (18/15/12/9/6/3/0 only) + +*/ +void m2m_ate_set_pa_gain(uint8 gain_db) +{ + uint32 PA_1e9c; + uint8 aGain[] = { + /* "0 dB" */ 0x00, + /* "3 dB" */ 0x01, + /* "6 dB" */ 0x03, + /* "9 dB" */ 0x07, + /* "12 dB" */ 0x0f, + /* "15 dB" */ 0x1f, + /* "18 dB" */ 0x3f }; + /* The variable PA gain is valid only for High power mode */ + PA_1e9c = nm_read_reg(0x1e9c); + /* TX bank 0. */ + PA_1e9c &= ~(0x3ful << 8); + PA_1e9c |= (((uint32)aGain[gain_db/3] & 0x3f) << 8); + nm_write_reg(0x1e9c, PA_1e9c); +} +/*! +@fn \ + sint8 m2m_ate_get_pa_gain(double *paGaindB) + +@brief + This function is used to get the PA gain + +@param [out] double *paGaindB + The retrieved PA gain value obtained from HW registers in dB. +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_get_pa_gain(double *paGaindB) +{ + uint32 val32, paGain; + uint32 m_cmbPAGainStep; + + if(!paGaindB) + return M2M_ERR_INVALID_ARG; + + val32 = nm_read_reg(0x1e9c); + + paGain = (val32 >> 8) & 0x3f; + + switch(paGain){ + case 0x1: + m_cmbPAGainStep = 5; + break; + case 0x3: + m_cmbPAGainStep = 4; + break; + case 0x7: + m_cmbPAGainStep = 3; + break; + case 0xf: + m_cmbPAGainStep = 2; + break; + case 0x1f: + m_cmbPAGainStep = 1; + break; + case 0x3f: + m_cmbPAGainStep = 0; + break; + default: + m_cmbPAGainStep = 0; + break; + } + + *paGaindB = 18 - m_cmbPAGainStep*3; + + return M2M_SUCCESS; +} +/*! +@fn \ + sint8 m2m_ate_get_ppa_gain(double * ppaGaindB) + +@brief + This function is used to get the PPA gain + +@param [out] uint32 * ppaGaindB + The retrieved PPA gain value obtained from HW registers in dB. +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_get_ppa_gain(double * ppaGaindB) +{ + uint32 val32, ppaGain, m_cmbPPAGainStep; + + if(!ppaGaindB) return M2M_ERR_INVALID_ARG; + + val32 = nm_read_reg(0x1ea0); + + ppaGain = (val32 >> 5) & 0x7; + + switch(ppaGain){ + case 0x1: + m_cmbPPAGainStep = 2; + break; + case 0x3: + m_cmbPPAGainStep = 1; + break; + case 0x7: + m_cmbPPAGainStep = 0; + break; + default: + m_cmbPPAGainStep = 3; + break; + } + + *ppaGaindB = 9 - m_cmbPPAGainStep*3; + + + return M2M_SUCCESS; +} +/*! +@fn \ + sint8 m2m_ate_get_tot_gain(double * totGaindB) + +@brief + This function is used to calculate the total gain + +@param [out] double * totGaindB + The retrieved total gain value obtained from calculations made based on the digital gain, PA and PPA gain values. +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_get_tot_gain(double * totGaindB) +{ + double dGaindB, paGaindB, ppaGaindB; + + if(!totGaindB) return M2M_ERR_INVALID_ARG; + + m2m_ate_get_pa_gain(&paGaindB); + m2m_ate_get_ppa_gain(&ppaGaindB); + m2m_ate_get_dig_gain(&dGaindB); + + *totGaindB = dGaindB + paGaindB + ppaGaindB; + + return M2M_SUCCESS; +} + +#endif //_M2M_ATE_FW_ \ No newline at end of file diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_crypto.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_crypto.c new file mode 100644 index 0000000..9ac7711 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_crypto.c @@ -0,0 +1,1010 @@ +/** + * + * \file + * + * \brief WINC Crypto module. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "driver/include/m2m_crypto.h" +#include "driver/source/nmbus.h" +#include "driver/source/nmasic.h" + +#ifdef CONF_CRYPTO_HW + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*======*======*======*======*======*=======* +* WINC SHA256 HW Engine Register Definition * +*======*======*======*======*======*========*/ + +#define SHA_BLOCK_SIZE (64) + +#define SHARED_MEM_BASE (0xd0000) + + +#define SHA256_MEM_BASE (0x180000UL) +#define SHA256_ENGINE_ADDR (0x180000ul) + +/* SHA256 Registers */ +#define SHA256_CTRL (SHA256_MEM_BASE+0x00) +#define SHA256_CTRL_START_CALC_MASK (NBIT0) +#define SHA256_CTRL_START_CALC_SHIFT (0) +#define SHA256_CTRL_PREPROCESS_MASK (NBIT1) +#define SHA256_CTRL_PREPROCESS_SHIFT (1) +#define SHA256_CTRL_HASH_HASH_MASK (NBIT2) +#define SHA256_CTRL_HASH_HASH_SHIFT (2) +#define SHA256_CTRL_INIT_SHA256_STATE_MASK (NBIT3) +#define SHA256_CTRL_INIT_SHA256_STATE_SHIFT (3) +#define SHA256_CTRL_WR_BACK_HASH_VALUE_MASK (NBIT4) +#define SHA256_CTRL_WR_BACK_HASH_VALUE_SHIFT (4) +#define SHA256_CTRL_FORCE_SHA256_QUIT_MASK (NBIT5) +#define SHA256_CTRL_FORCE_SHA256_QUIT_SHIFT (5) + +#define SHA256_REGS_SHA256_CTRL_AHB_BYTE_REV_EN (NBIT6) +#define SHA256_REGS_SHA256_CTRL_RESERVED (NBIT7) +#define SHA256_REGS_SHA256_CTRL_CORE_TO_AHB_CLK_RATIO (NBIT8+ NBIT9+ NBIT10) +#define SHA256_REGS_SHA256_CTRL_CORE_TO_AHB_CLK_RATIO_MASK (NBIT2+ NBIT1+ NBIT0) +#define SHA256_REGS_SHA256_CTRL_CORE_TO_AHB_CLK_RATIO_SHIFT (8) +#define SHA256_REGS_SHA256_CTRL_RESERVED_11 (NBIT11) +#define SHA256_REGS_SHA256_CTRL_SHA1_CALC (NBIT12) +#define SHA256_REGS_SHA256_CTRL_PBKDF2_SHA1_CALC (NBIT13) + + +#define SHA256_START_RD_ADDR (SHA256_MEM_BASE+0x04UL) +#define SHA256_DATA_LENGTH (SHA256_MEM_BASE+0x08UL) +#define SHA256_START_WR_ADDR (SHA256_MEM_BASE+0x0cUL) +#define SHA256_COND_CHK_CTRL (SHA256_MEM_BASE+0x10) +#define SHA256_COND_CHK_CTRL_HASH_VAL_COND_CHK_MASK (NBIT1 | NBIT0) +#define SHA256_COND_CHK_CTRL_HASH_VAL_COND_CHK_SHIFT (0) +#define SHA256_COND_CHK_CTRL_STEP_VAL_MASK (NBIT6 | NBIT5 | NBIT4 | NBIT3 | NBIT2) +#define SHA256_COND_CHK_CTRL_STEP_VAL_SHIFT (2) +#define SHA256_COND_CHK_CTRL_COND_CHK_RESULT_MASK (NBIT7) +#define SHA256_COND_CHK_CTRL_COND_CHK_RESULT_SHIFT (7) + +#define SHA256_MOD_DATA_RANGE (SHA256_MEM_BASE+0x14) +#define SHA256_MOD_DATA_RANGE_ST_BYTE_2_ADD_STP_MASK (NBIT24-1) +#define SHA256_MOD_DATA_RANGE_ST_BYTE_2_ADD_STP_SHIFT (0) +#define SHA256_MOD_DATA_RANGE_MOD_DATA_LEN_MASK (NBIT24 | NBIT25| NBIT26) +#define SHA256_MOD_DATA_RANGE_MOD_DATA_LEN_SHIFT (24) + + +#define SHA256_COND_CHK_STS_1 (SHA256_MEM_BASE+0x18) +#define SHA256_COND_CHK_STS_2 (SHA256_MEM_BASE+0x1c) +#define SHA256_DONE_INTR_ENABLE (SHA256_MEM_BASE+0x20) +#define SHA256_DONE_INTR_STS (SHA256_MEM_BASE+0x24) +#define SHA256_TARGET_HASH_H1 (SHA256_MEM_BASE+0x28) +#define SHA256_TARGET_HASH_H2 (SHA256_MEM_BASE+0x2c) +#define SHA256_TARGET_HASH_H3 (SHA256_MEM_BASE+0x30) +#define SHA256_TARGET_HASH_H4 (SHA256_MEM_BASE+0x34) +#define SHA256_TARGET_HASH_H5 (SHA256_MEM_BASE+0x38) +#define SHA256_TARGET_HASH_H6 (SHA256_MEM_BASE+0x3c) +#define SHA256_TARGET_HASH_H7 (SHA256_MEM_BASE+0x40) +#define SHA256_TARGET_HASH_H8 (SHA256_MEM_BASE+0x44) + +/*======*======*======*======*======*=======* +* WINC BIGINT HW Engine Register Definition * +*======*======*======*======*======*========*/ + + +#define BIGINT_ENGINE_ADDR (0x180080ul) +#define BIGINT_VERSION (BIGINT_ENGINE_ADDR + 0x00) + +#define BIGINT_MISC_CTRL (BIGINT_ENGINE_ADDR + 0x04) +#define BIGINT_MISC_CTRL_CTL_START (NBIT0) +#define BIGINT_MISC_CTRL_CTL_RESET (NBIT1) +#define BIGINT_MISC_CTRL_CTL_MSW_FIRST (NBIT2) +#define BIGINT_MISC_CTRL_CTL_SWAP_BYTE_ORDER (NBIT3) +#define BIGINT_MISC_CTRL_CTL_FORCE_BARRETT (NBIT4) +#define BIGINT_MISC_CTRL_CTL_M_PRIME_VALID (NBIT5) + +#define BIGINT_M_PRIME (BIGINT_ENGINE_ADDR + 0x08) + +#define BIGINT_STATUS (BIGINT_ENGINE_ADDR + 0x0C) +#define BIGINT_STATUS_STS_DONE (NBIT0) + +#define BIGINT_CLK_COUNT (BIGINT_ENGINE_ADDR + 0x10) +#define BIGINT_ADDR_X (BIGINT_ENGINE_ADDR + 0x14) +#define BIGINT_ADDR_E (BIGINT_ENGINE_ADDR + 0x18) +#define BIGINT_ADDR_M (BIGINT_ENGINE_ADDR + 0x1C) +#define BIGINT_ADDR_R (BIGINT_ENGINE_ADDR + 0x20) +#define BIGINT_LENGTH (BIGINT_ENGINE_ADDR + 0x24) + +#define BIGINT_IRQ_STS (BIGINT_ENGINE_ADDR + 0x28) +#define BIGINT_IRQ_STS_DONE (NBIT0) +#define BIGINT_IRQ_STS_CHOOSE_MONT (NBIT1) +#define BIGINT_IRQ_STS_M_READ (NBIT2) +#define BIGINT_IRQ_STS_X_READ (NBIT3) +#define BIGINT_IRQ_STS_START (NBIT4) +#define BIGINT_IRQ_STS_PRECOMP_FINISH (NBIT5) + +#define BIGINT_IRQ_MASK (BIGINT_ENGINE_ADDR + 0x2C) +#define BIGINT_IRQ_MASK_CTL_IRQ_MASK_START (NBIT4) + +#define ENABLE_FLIPPING 1 + + + + +#define GET_UINT32(BUF,OFFSET) (((uint32)((BUF)[OFFSET])) | ((uint32)(((BUF)[OFFSET + 1]) << 8)) | \ +((uint32)(((BUF)[OFFSET + 2]) << 16)) | ((uint32)(((BUF)[OFFSET + 3]) << 24))) + +#define PUTU32(VAL32,BUF,OFFSET) \ +do \ +{ \ + (BUF)[OFFSET ] = BYTE_3((VAL32)); \ + (BUF)[OFFSET +1 ] = BYTE_2((VAL32)); \ + (BUF)[OFFSET +2 ] = BYTE_1((VAL32)); \ + (BUF)[OFFSET +3 ] = BYTE_0((VAL32)); \ +}while(0) + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*! +@struct \ + tstrHashContext + +@brief +*/ +typedef struct{ + uint32 au32HashState[M2M_SHA256_DIGEST_LEN/4]; + uint8 au8CurrentBlock[64]; + uint32 u32TotalLength; + uint8 u8InitHashFlag; +}tstrSHA256HashCtxt; + + + +/*======*======*======*======*======*=======* +* SHA256 IMPLEMENTATION * +*======*======*======*======*======*========*/ + +sint8 m2m_crypto_sha256_hash_init(tstrM2mSha256Ctxt *pstrSha256Ctxt) +{ + tstrSHA256HashCtxt *pstrSHA256 = (tstrSHA256HashCtxt*)pstrSha256Ctxt; + if(pstrSHA256 != NULL) + { + m2m_memset((uint8*)pstrSha256Ctxt, 0, sizeof(tstrM2mSha256Ctxt)); + pstrSHA256->u8InitHashFlag = 1; + } + return 0; +} + +sint8 m2m_crypto_sha256_hash_update(tstrM2mSha256Ctxt *pstrSha256Ctxt, uint8 *pu8Data, uint16 u16DataLength) +{ + sint8 s8Ret = M2M_ERR_FAIL; + tstrSHA256HashCtxt *pstrSHA256 = (tstrSHA256HashCtxt*)pstrSha256Ctxt; + if(pstrSHA256 != NULL) + { + uint32 u32ReadAddr; + uint32 u32WriteAddr = SHARED_MEM_BASE; + uint32 u32Addr = u32WriteAddr; + uint32 u32ResidualBytes; + uint32 u32NBlocks; + uint32 u32Offset; + uint32 u32CurrentBlock = 0; + uint8 u8IsDone = 0; + + /* Get the remaining bytes from the previous update (if the length is not block aligned). */ + u32ResidualBytes = pstrSHA256->u32TotalLength % SHA_BLOCK_SIZE; + + /* Update the total data length. */ + pstrSHA256->u32TotalLength += u16DataLength; + + if(u32ResidualBytes != 0) + { + if((u32ResidualBytes + u16DataLength) >= SHA_BLOCK_SIZE) + { + u32Offset = SHA_BLOCK_SIZE - u32ResidualBytes; + m2m_memcpy(&pstrSHA256->au8CurrentBlock[u32ResidualBytes], pu8Data, u32Offset); + pu8Data += u32Offset; + u16DataLength -= u32Offset; + + nm_write_block(u32Addr, pstrSHA256->au8CurrentBlock, SHA_BLOCK_SIZE); + u32Addr += SHA_BLOCK_SIZE; + u32CurrentBlock = 1; + } + else + { + m2m_memcpy(&pstrSHA256->au8CurrentBlock[u32ResidualBytes], pu8Data, u16DataLength); + u16DataLength = 0; + } + } + + /* Get the number of HASH BLOCKs and the residual bytes. */ + u32NBlocks = u16DataLength / SHA_BLOCK_SIZE; + u32ResidualBytes = u16DataLength % SHA_BLOCK_SIZE; + + if(u32NBlocks != 0) + { + nm_write_block(u32Addr, pu8Data, (uint16)(u32NBlocks * SHA_BLOCK_SIZE)); + pu8Data += (u32NBlocks * SHA_BLOCK_SIZE); + } + + u32NBlocks += u32CurrentBlock; + if(u32NBlocks != 0) + { + uint32 u32RegVal = 0; + + nm_write_reg(SHA256_CTRL, u32RegVal); + u32RegVal |= SHA256_CTRL_FORCE_SHA256_QUIT_MASK; + nm_write_reg(SHA256_CTRL, u32RegVal); + + if(pstrSHA256->u8InitHashFlag) + { + pstrSHA256->u8InitHashFlag = 0; + u32RegVal |= SHA256_CTRL_INIT_SHA256_STATE_MASK; + } + + u32ReadAddr = u32WriteAddr + (u32NBlocks * SHA_BLOCK_SIZE); + nm_write_reg(SHA256_DATA_LENGTH, (u32NBlocks * SHA_BLOCK_SIZE)); + nm_write_reg(SHA256_START_RD_ADDR, u32WriteAddr); + nm_write_reg(SHA256_START_WR_ADDR, u32ReadAddr); + + u32RegVal |= SHA256_CTRL_START_CALC_MASK; + + u32RegVal &= ~(0x7 << 8); + u32RegVal |= (2 << 8); + + nm_write_reg(SHA256_CTRL, u32RegVal); + + /* 5. Wait for done_intr */ + while(!u8IsDone) + { + u32RegVal = nm_read_reg(SHA256_DONE_INTR_STS); + u8IsDone = u32RegVal & NBIT0; + } + } + if(u32ResidualBytes != 0) + { + m2m_memcpy(pstrSHA256->au8CurrentBlock, pu8Data, u32ResidualBytes); + } + s8Ret = M2M_SUCCESS; + } + return s8Ret; +} + + +sint8 m2m_crypto_sha256_hash_finish(tstrM2mSha256Ctxt *pstrSha256Ctxt, uint8 *pu8Sha256Digest) +{ + sint8 s8Ret = M2M_ERR_FAIL; + tstrSHA256HashCtxt *pstrSHA256 = (tstrSHA256HashCtxt*)pstrSha256Ctxt; + if(pstrSHA256 != NULL) + { + uint32 u32ReadAddr; + uint32 u32WriteAddr = SHARED_MEM_BASE; + uint32 u32Addr = u32WriteAddr; + uint16 u16Offset; + uint16 u16PaddingLength; + uint16 u16NBlocks = 1; + uint32 u32RegVal = 0; + uint32 u32Idx,u32ByteIdx; + uint32 au32Digest[M2M_SHA256_DIGEST_LEN / 4]; + uint8 u8IsDone = 0; + + nm_write_reg(SHA256_CTRL,u32RegVal); + u32RegVal |= SHA256_CTRL_FORCE_SHA256_QUIT_MASK; + nm_write_reg(SHA256_CTRL,u32RegVal); + + if(pstrSHA256->u8InitHashFlag) + { + pstrSHA256->u8InitHashFlag = 0; + u32RegVal |= SHA256_CTRL_INIT_SHA256_STATE_MASK; + } + + /* Calculate the offset of the last data byte in the current block. */ + u16Offset = (uint16)(pstrSHA256->u32TotalLength % SHA_BLOCK_SIZE); + + /* Add the padding byte 0x80. */ + pstrSHA256->au8CurrentBlock[u16Offset ++] = 0x80; + + /* Calculate the required padding to complete + one Hash Block Size. + */ + u16PaddingLength = SHA_BLOCK_SIZE - u16Offset; + m2m_memset(&pstrSHA256->au8CurrentBlock[u16Offset], 0, u16PaddingLength); + + /* If the padding count is not enough to hold 64-bit representation of + the total input message length, one padding block is required. + */ + if(u16PaddingLength < 8) + { + nm_write_block(u32Addr, pstrSHA256->au8CurrentBlock, SHA_BLOCK_SIZE); + u32Addr += SHA_BLOCK_SIZE; + m2m_memset(pstrSHA256->au8CurrentBlock, 0, SHA_BLOCK_SIZE); + u16NBlocks ++; + } + + /* pack the length at the end of the padding block */ + PUTU32(pstrSHA256->u32TotalLength << 3, pstrSHA256->au8CurrentBlock, (SHA_BLOCK_SIZE - 4)); + + u32ReadAddr = u32WriteAddr + (u16NBlocks * SHA_BLOCK_SIZE); + nm_write_block(u32Addr, pstrSHA256->au8CurrentBlock, SHA_BLOCK_SIZE); + nm_write_reg(SHA256_DATA_LENGTH, (u16NBlocks * SHA_BLOCK_SIZE)); + nm_write_reg(SHA256_START_RD_ADDR, u32WriteAddr); + nm_write_reg(SHA256_START_WR_ADDR, u32ReadAddr); + + u32RegVal |= SHA256_CTRL_START_CALC_MASK; + u32RegVal |= SHA256_CTRL_WR_BACK_HASH_VALUE_MASK; + u32RegVal &= ~(0x7UL << 8); + u32RegVal |= (0x2UL << 8); + + nm_write_reg(SHA256_CTRL,u32RegVal); + + + /* 5. Wait for done_intr */ + while(!u8IsDone) + { + u32RegVal = nm_read_reg(SHA256_DONE_INTR_STS); + u8IsDone = u32RegVal & NBIT0; + } + nm_read_block(u32ReadAddr, (uint8*)au32Digest, 32); + + /* Convert the output words to an array of bytes. + */ + u32ByteIdx = 0; + for(u32Idx = 0; u32Idx < (M2M_SHA256_DIGEST_LEN / 4); u32Idx ++) + { + pu8Sha256Digest[u32ByteIdx ++] = BYTE_3(au32Digest[u32Idx]); + pu8Sha256Digest[u32ByteIdx ++] = BYTE_2(au32Digest[u32Idx]); + pu8Sha256Digest[u32ByteIdx ++] = BYTE_1(au32Digest[u32Idx]); + pu8Sha256Digest[u32ByteIdx ++] = BYTE_0(au32Digest[u32Idx]); + } + s8Ret = M2M_SUCCESS; + } + return s8Ret; +} + + +/*======*======*======*======*======*=======* +* RSA IMPLEMENTATION * +*======*======*======*======*======*========*/ + +static void FlipBuffer(uint8 *pu8InBuffer, uint8 *pu8OutBuffer, uint16 u16BufferSize) +{ + uint16 u16Idx; + for(u16Idx = 0; u16Idx < u16BufferSize; u16Idx ++) + { +#if ENABLE_FLIPPING == 1 + pu8OutBuffer[u16Idx] = pu8InBuffer[u16BufferSize - u16Idx - 1]; +#else + pu8OutBuffer[u16Idx] = pu8InBuffer[u16Idx]; +#endif + } +} + +void BigInt_ModExp +( + uint8 *pu8X, uint16 u16XSize, + uint8 *pu8E, uint16 u16ESize, + uint8 *pu8M, uint16 u16MSize, + uint8 *pu8R, uint16 u16RSize + ) +{ + uint32 u32Reg; + uint8 au8Tmp[780] = {0}; + uint32 u32XAddr = SHARED_MEM_BASE; + uint32 u32MAddr; + uint32 u32EAddr; + uint32 u32RAddr; + uint8 u8EMswBits = 32; + uint32 u32Mprime = 0x7F; + uint16 u16XSizeWords,u16ESizeWords; + uint32 u32Exponent; + + u16XSizeWords = (u16XSize + 3) / 4; + u16ESizeWords = (u16ESize + 3) / 4; + + u32MAddr = u32XAddr + (u16XSizeWords * 4); + u32EAddr = u32MAddr + (u16XSizeWords * 4); + u32RAddr = u32EAddr + (u16ESizeWords * 4); + + /* Reset the core. + */ + u32Reg = 0; + u32Reg |= BIGINT_MISC_CTRL_CTL_RESET; + u32Reg = nm_read_reg(BIGINT_MISC_CTRL); + u32Reg &= ~BIGINT_MISC_CTRL_CTL_RESET; + u32Reg = nm_read_reg(BIGINT_MISC_CTRL); + + nm_write_block(u32RAddr,au8Tmp, u16RSize); + + /* Write Input Operands to Chip Memory. + */ + /*------- X -------*/ + FlipBuffer(pu8X,au8Tmp,u16XSize); + nm_write_block(u32XAddr,au8Tmp,u16XSizeWords * 4); + + /*------- E -------*/ + m2m_memset(au8Tmp, 0, sizeof(au8Tmp)); + FlipBuffer(pu8E, au8Tmp, u16ESize); + nm_write_block(u32EAddr, au8Tmp, u16ESizeWords * 4); + u32Exponent = GET_UINT32(au8Tmp, (u16ESizeWords * 4) - 4); + while((u32Exponent & NBIT31)== 0) + { + u32Exponent <<= 1; + u8EMswBits --; + } + + /*------- M -------*/ + m2m_memset(au8Tmp, 0, sizeof(au8Tmp)); + FlipBuffer(pu8M, au8Tmp, u16XSize); + nm_write_block(u32MAddr, au8Tmp, u16XSizeWords * 4); + + /* Program the addresses of the input operands. + */ + nm_write_reg(BIGINT_ADDR_X, u32XAddr); + nm_write_reg(BIGINT_ADDR_E, u32EAddr); + nm_write_reg(BIGINT_ADDR_M, u32MAddr); + nm_write_reg(BIGINT_ADDR_R, u32RAddr); + + /* Mprime. + */ + nm_write_reg(BIGINT_M_PRIME,u32Mprime); + + /* Length. + */ + u32Reg = (u16XSizeWords & 0xFF); + u32Reg += ((u16ESizeWords & 0xFF) << 8); + u32Reg += (u8EMswBits << 16); + nm_write_reg(BIGINT_LENGTH,u32Reg); + + /* CTRL Register. + */ + u32Reg = nm_read_reg(BIGINT_MISC_CTRL); + u32Reg ^= BIGINT_MISC_CTRL_CTL_START; + u32Reg |= BIGINT_MISC_CTRL_CTL_FORCE_BARRETT; + //u32Reg |= BIGINT_MISC_CTRL_CTL_M_PRIME_VALID; +#if ENABLE_FLIPPING == 0 + u32Reg |= BIGINT_MISC_CTRL_CTL_MSW_FIRST; +#endif + nm_write_reg(BIGINT_MISC_CTRL,u32Reg); + + /* Wait for computation to complete. */ + while(1) + { + u32Reg = nm_read_reg(BIGINT_IRQ_STS); + if(u32Reg & BIGINT_IRQ_STS_DONE) + { + break; + } + } + nm_write_reg(BIGINT_IRQ_STS,0); + m2m_memset(au8Tmp, 0, sizeof(au8Tmp)); + nm_read_block(u32RAddr, au8Tmp, u16RSize); + FlipBuffer(au8Tmp, pu8R, u16RSize); +} + + + +#define MD5_DIGEST_SIZE (16) +#define SHA1_DIGEST_SIZE (20) + +static const uint8 au8TEncodingMD5[] = +{ + 0x30, 0x20, 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86, + 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05, 0x05, 0x00, + 0x04 +}; +/*!< Fixed part of the Encoding T for the MD5 hash algorithm. +*/ + + +static const uint8 au8TEncodingSHA1[] = +{ + 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, + 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04 +}; +/*!< Fixed part of the Encoding T for the SHA-1 hash algorithm. +*/ + + +static const uint8 au8TEncodingSHA2[] = +{ + 0x30, 0x31, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, + 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, + 0x00, 0x04 +}; +/*!< Fixed part of the Encoding T for the SHA-2 hash algorithm. +*/ + + +sint8 m2m_crypto_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash, + uint16 u16HashLength, uint8 *pu8RsaSignature) +{ + sint8 s8Ret = M2M_RSA_SIGN_FAIL; + + if((pu8N != NULL) && (pu8E != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL)) + { + uint16 u16TLength, u16TEncodingLength; + uint8 *pu8T; + uint8 au8EM[512]; + + /* Selection of correct T Encoding based on the hash size. + */ + if(u16HashLength == MD5_DIGEST_SIZE) + { + pu8T = (uint8*)au8TEncodingMD5; + u16TEncodingLength = sizeof(au8TEncodingMD5); + } + else if(u16HashLength == SHA1_DIGEST_SIZE) + { + pu8T = (uint8*)au8TEncodingSHA1; + u16TEncodingLength = sizeof(au8TEncodingSHA1); + } + else + { + pu8T = (uint8*)au8TEncodingSHA2; + u16TEncodingLength = sizeof(au8TEncodingSHA2); + } + u16TLength = u16TEncodingLength + 1 + u16HashLength; + + /* If emLen < tLen + 11. + */ + if(u16NSize >= (u16TLength + 11)) + { + uint32 u32PSLength,u32Idx = 0; + + /* + RSA verification + */ + BigInt_ModExp(pu8RsaSignature, u16NSize, pu8E, u16ESize, pu8N, u16NSize, au8EM, u16NSize); + + u32PSLength = u16NSize - u16TLength - 3; + + /* + The calculated EM must match the following pattern. + *======*======*======*======*======* + * 0x00 || 0x01 || PS || 0x00 || T * + *======*======*======*======*======* + Where PS is all 0xFF + T is defined based on the hash algorithm. + */ + if((au8EM[0] == 0x00) && (au8EM[1] == 0x01)) + { + for(u32Idx = 2; au8EM[u32Idx] == 0xFF; u32Idx ++); + if(u32Idx == (u32PSLength + 2)) + { + if(au8EM[u32Idx ++] == 0x00) + { + if(!m2m_memcmp(&au8EM[u32Idx], pu8T, u16TEncodingLength)) + { + u32Idx += u16TEncodingLength; + if(au8EM[u32Idx ++] == u16HashLength) + s8Ret = m2m_memcmp(&au8EM[u32Idx], pu8SignedMsgHash, u16HashLength); + } + } + } + } + } + } + return s8Ret; +} + + +sint8 m2m_crypto_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash, + uint16 u16HashLength, uint8 *pu8RsaSignature) +{ + sint8 s8Ret = M2M_RSA_SIGN_FAIL; + + if((pu8N != NULL) && (pu8d != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL)) + { + uint16 u16TLength, u16TEncodingLength; + uint8 *pu8T; + uint8 au8EM[512]; + + /* Selection of correct T Encoding based on the hash size. + */ + if(u16HashLength == MD5_DIGEST_SIZE) + { + pu8T = (uint8*)au8TEncodingMD5; + u16TEncodingLength = sizeof(au8TEncodingMD5); + } + else if(u16HashLength == SHA1_DIGEST_SIZE) + { + pu8T = (uint8*)au8TEncodingSHA1; + u16TEncodingLength = sizeof(au8TEncodingSHA1); + } + else + { + pu8T = (uint8*)au8TEncodingSHA2; + u16TEncodingLength = sizeof(au8TEncodingSHA2); + } + u16TLength = u16TEncodingLength + 1 + u16HashLength; + + /* If emLen < tLen + 11. + */ + if(u16NSize >= (u16TLength + 11)) + { + uint16 u16PSLength = 0; + uint16 u16Offset = 0; + + /* + The calculated EM must match the following pattern. + *======*======*======*======*======* + * 0x00 || 0x01 || PS || 0x00 || T * + *======*======*======*======*======* + Where PS is all 0xFF + T is defined based on the hash algorithm. + */ + au8EM[u16Offset ++] = 0; + au8EM[u16Offset ++] = 1; + u16PSLength = u16NSize - u16TLength - 3; + m2m_memset(&au8EM[u16Offset], 0xFF, u16PSLength); + u16Offset += u16PSLength; + au8EM[u16Offset ++] = 0; + m2m_memcpy(&au8EM[u16Offset], pu8T, u16TEncodingLength); + u16Offset += u16TEncodingLength; + au8EM[u16Offset ++] = u16HashLength; + m2m_memcpy(&au8EM[u16Offset], pu8SignedMsgHash, u16HashLength); + + /* + RSA Signature Generation + */ + BigInt_ModExp(au8EM, u16NSize, pu8d, u16dSize, pu8N, u16NSize, pu8RsaSignature, u16NSize); + s8Ret = M2M_RSA_SIGN_OK; + } + } + return s8Ret; +} + +#endif /* CONF_CRYPTO */ + +#ifdef CONF_CRYPTO_SOFT + +typedef struct { + tpfAppCryproCb pfAppCryptoCb; + uint8 * pu8Digest; + uint8 * pu8Rsa; + uint8 u8CryptoBusy; +}tstrCryptoCtxt; + +typedef struct { + uint8 au8N[M2M_MAX_RSA_LEN]; + uint8 au8E[M2M_MAX_RSA_LEN]; + uint8 au8Hash[M2M_SHA256_DIGEST_LEN]; + uint16 u16Nsz; + uint16 u16Esz; + uint16 u16Hsz; + uint8 _pad16_[2]; +}tstrRsaPayload; + +static tstrCryptoCtxt gstrCryptoCtxt; + + +/** +* @fn m2m_crypto_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +* @brief WiFi call back function +* @param [in] u8OpCode +* HIF Opcode type. +* @param [in] u16DataSize +* HIF data length. +* @param [in] u32Addr +* HIF address. +* @author +* @date +* @version 1.0 +*/ +static void m2m_crypto_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +{ + sint8 ret = M2M_SUCCESS; + gstrCryptoCtxt.u8CryptoBusy = 0; + if(u8OpCode == M2M_CRYPTO_RESP_SHA256_INIT) + { + tstrM2mSha256Ctxt strCtxt; + if (hif_receive(u32Addr, (uint8*) &strCtxt,sizeof(tstrM2mSha256Ctxt), 0) == M2M_SUCCESS) + { + tstrCyptoResp strResp; + if(hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt), (uint8*) &strResp,sizeof(tstrCyptoResp), 1) == M2M_SUCCESS) + { + if (gstrCryptoCtxt.pfAppCryptoCb) + gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,&strCtxt); + } + } + } + else if(u8OpCode == M2M_CRYPTO_RESP_SHA256_UPDATE) + { + tstrM2mSha256Ctxt strCtxt; + if (hif_receive(u32Addr, (uint8*) &strCtxt,sizeof(tstrM2mSha256Ctxt), 0) == M2M_SUCCESS) + { + tstrCyptoResp strResp; + if (hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt), (uint8*) &strResp,sizeof(tstrCyptoResp), 1) == M2M_SUCCESS) + { + if (gstrCryptoCtxt.pfAppCryptoCb) + gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,&strCtxt); + } + } + + } + else if(u8OpCode == M2M_CRYPTO_RESP_SHA256_FINSIH) + { + tstrCyptoResp strResp; + if (hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt), (uint8*) &strResp,sizeof(tstrCyptoResp), 0) == M2M_SUCCESS) + { + if (hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt) + sizeof(tstrCyptoResp), (uint8*)gstrCryptoCtxt.pu8Digest,M2M_SHA256_DIGEST_LEN, 1) == M2M_SUCCESS) + { + if (gstrCryptoCtxt.pfAppCryptoCb) + gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,gstrCryptoCtxt.pu8Digest); + + } + } + } + else if(u8OpCode == M2M_CRYPTO_RESP_RSA_SIGN_GEN) + { + tstrCyptoResp strResp; + if (hif_receive(u32Addr + sizeof(tstrRsaPayload), (uint8*)&strResp,sizeof(tstrCyptoResp), 0) == M2M_SUCCESS) + { + if (hif_receive(u32Addr + sizeof(tstrRsaPayload) + sizeof(tstrCyptoResp), (uint8*)gstrCryptoCtxt.pu8Rsa,M2M_MAX_RSA_LEN, 0) == M2M_SUCCESS) + { + if (gstrCryptoCtxt.pfAppCryptoCb) + gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,gstrCryptoCtxt.pu8Rsa); + } + } + } + else if(u8OpCode == M2M_CRYPTO_RESP_RSA_SIGN_VERIFY) + { + tstrCyptoResp strResp; + if (hif_receive(u32Addr + sizeof(tstrRsaPayload), (uint8*)&strResp,sizeof(tstrCyptoResp), 1) == M2M_SUCCESS) + { + if (gstrCryptoCtxt.pfAppCryptoCb) + gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,NULL); + } + } + else + { + M2M_ERR("u8Code %d ??\n",u8OpCode); + } + +} +/*! +@fn \ + sint8 m2m_crypto_init(); + +@brief crypto initialization + +@param[in] pfAppCryproCb + +*/ +sint8 m2m_crypto_init(tpfAppCryproCb pfAppCryproCb) +{ + sint8 ret = M2M_ERR_FAIL; + m2m_memset((uint8*)&gstrCryptoCtxt,0,sizeof(tstrCryptoCtxt)); + if(pfAppCryproCb != NULL) + { + gstrCryptoCtxt.pfAppCryptoCb = pfAppCryproCb; + ret = hif_register_cb(M2M_REQ_GROUP_CRYPTO,m2m_crypto_cb); + } + return ret; +} +/*! +@fn \ + sint8 m2m_sha256_hash_init(tstrM2mSha256Ctxt *psha256Ctxt); + +@brief SHA256 hash initialization + +@param[in] psha256Ctxt + Pointer to a sha256 context allocated by the caller. +*/ +sint8 m2m_crypto_sha256_hash_init(tstrM2mSha256Ctxt *psha256Ctxt) +{ + sint8 ret = M2M_ERR_FAIL; + if((psha256Ctxt != NULL)&&(!gstrCryptoCtxt.u8CryptoBusy)) + { + ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_SHA256_INIT|M2M_REQ_DATA_PKT,(uint8*)psha256Ctxt,sizeof(tstrM2mSha256Ctxt),NULL,0,0); + } + return ret; +} + + +/*! +@fn \ + sint8 m2m_sha256_hash_update(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Data, uint16 u16DataLength); + +@brief SHA256 hash update + +@param [in] psha256Ctxt + Pointer to the sha256 context. + +@param [in] pu8Data + Buffer holding the data submitted to the hash. + +@param [in] u16DataLength + Size of the data bufefr in bytes. +*/ +sint8 m2m_crypto_sha256_hash_update(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Data, uint16 u16DataLength) +{ + sint8 ret = M2M_ERR_FAIL; + if((!gstrCryptoCtxt.u8CryptoBusy) && (psha256Ctxt != NULL) && (pu8Data != NULL) && (u16DataLength < M2M_SHA256_MAX_DATA)) + { + ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_SHA256_UPDATE|M2M_REQ_DATA_PKT,(uint8*)psha256Ctxt,sizeof(tstrM2mSha256Ctxt),pu8Data,u16DataLength,sizeof(tstrM2mSha256Ctxt) + sizeof(tstrCyptoResp)); + } + return ret; + +} + + +/*! +@fn \ + sint8 m2m_sha256_hash_finish(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Sha256Digest); + +@brief SHA256 hash finalization + +@param[in] psha256Ctxt + Pointer to a sha256 context allocated by the caller. + +@param [in] pu8Sha256Digest + Buffer allocated by the caller which will hold the resultant SHA256 Digest. It must be allocated no less than M2M_SHA256_DIGEST_LEN. +*/ +sint8 m2m_crypto_sha256_hash_finish(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Sha256Digest) +{ + sint8 ret = M2M_ERR_FAIL; + if((!gstrCryptoCtxt.u8CryptoBusy) && (psha256Ctxt != NULL) && (pu8Sha256Digest != NULL)) + { + gstrCryptoCtxt.pu8Digest = pu8Sha256Digest; + ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_SHA256_FINSIH|M2M_REQ_DATA_PKT,(uint8*)psha256Ctxt,sizeof(tstrM2mSha256Ctxt),NULL,0,0); + } + return ret; +} + + + + +/*! +@fn \ + sint8 m2m_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash, \ + uint16 u16HashLength, uint8 *pu8RsaSignature); + +@brief RSA Signature Verification + + The function shall request the RSA Signature verification from the WINC Firmware for the given message. The signed message shall be + compressed to the corresponding hash algorithm before calling this function. + The hash type is identified by the given hash length. For example, if the hash length is 32 bytes, then it is SHA256. + +@param[in] pu8N + RSA Key modulus n. + +@param[in] u16NSize + Size of the RSA modulus n in bytes. + +@param[in] pu8E + RSA public exponent. + +@param[in] u16ESize + Size of the RSA public exponent in bytes. + +@param[in] pu8SignedMsgHash + The hash digest of the signed message. + +@param[in] u16HashLength + The length of the hash digest. + +@param[out] pu8RsaSignature + Signature value to be verified. +*/ + + +sint8 m2m_crypto_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash, + uint16 u16HashLength, uint8 *pu8RsaSignature) +{ + sint8 ret = M2M_ERR_FAIL; + if((!gstrCryptoCtxt.u8CryptoBusy) && (pu8N != NULL) && (pu8E != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL) + && (u16NSize != 0) && (u16ESize != 0) && (u16HashLength != 0) && (pu8RsaSignature != NULL) ) + + { + tstrRsaPayload strRsa = {0}; + + m2m_memcpy(strRsa.au8N,pu8N,u16NSize); + m2m_memcpy(strRsa.au8E,pu8E,u16ESize); + m2m_memcpy(strRsa.au8Hash,pu8SignedMsgHash,u16HashLength); + + strRsa.u16Esz = u16ESize; + strRsa.u16Hsz = u16HashLength; + strRsa.u16Nsz = u16NSize; + + ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_RSA_SIGN_VERIFY|M2M_REQ_DATA_PKT,(uint8*)&strRsa,sizeof(tstrRsaPayload),NULL,0,0); + + } + return ret; +} + + +/*! +@fn \ + sint8 m2m_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash, \ + uint16 u16HashLength, uint8 *pu8RsaSignature); + +@brief RSA Signature Generation + + The function shall request the RSA Signature generation from the WINC Firmware for the given message. The signed message shall be + compressed to the corresponding hash algorithm before calling this function. + The hash type is identified by the given hash length. For example, if the hash length is 32 bytes, then it is SHA256. + +@param[in] pu8N + RSA Key modulus n. + +@param[in] u16NSize + Size of the RSA modulus n in bytes. + +@param[in] pu8d + RSA private exponent. + +@param[in] u16dSize + Size of the RSA private exponent in bytes. + +@param[in] pu8SignedMsgHash + The hash digest of the signed message. + +@param[in] u16HashLength + The length of the hash digest. + +@param[out] pu8RsaSignature + Pointer to a user buffer allocated by teh caller shall hold the generated signature. +*/ +sint8 m2m_crypto_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash, + uint16 u16HashLength, uint8 *pu8RsaSignature) +{ + sint8 ret = M2M_ERR_FAIL; + if((!gstrCryptoCtxt.u8CryptoBusy) && (pu8N != NULL) && (pu8d != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL) + && (u16NSize != 0) && (u16dSize != 0) && (u16HashLength != 0) && (pu8RsaSignature != NULL)) + + { + tstrRsaPayload strRsa = {0}; + + m2m_memcpy(strRsa.au8N,pu8N,u16NSize); + m2m_memcpy(strRsa.au8E,pu8d,u16dSize); + m2m_memcpy(strRsa.au8Hash,pu8SignedMsgHash,u16HashLength); + + strRsa.u16Esz = u16dSize; + strRsa.u16Hsz = u16HashLength; + strRsa.u16Nsz = u16NSize; + + gstrCryptoCtxt.pu8Rsa = pu8RsaSignature; + ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_RSA_SIGN_GEN|M2M_REQ_DATA_PKT,(uint8*)&strRsa,sizeof(tstrRsaPayload),NULL,0,0); + + } + return ret; +} + +#endif \ No newline at end of file diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_hif.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_hif.c new file mode 100644 index 0000000..f0ed93a --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_hif.c @@ -0,0 +1,767 @@ +/** + * + * \file + * + * \brief This module contains M2M host interface APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "common/include/nm_common.h" +#include "driver/source/nmbus.h" +#include "bsp/include/nm_bsp.h" +#include "m2m_hif.h" +#include "driver/include/m2m_types.h" +#include "driver/source/nmasic.h" +#include "driver/include/m2m_periph.h" + +#if (defined NM_EDGE_INTERRUPT)&&(defined NM_LEVEL_INTERRUPT) +#error "only one type of interrupt NM_EDGE_INTERRUPT,NM_LEVEL_INTERRUPT" +#endif + +#if !((defined NM_EDGE_INTERRUPT)||(defined NM_LEVEL_INTERRUPT)) +#error "define interrupt type NM_EDGE_INTERRUPT,NM_LEVEL_INTERRUPT" +#endif + +#ifndef CORTUS_APP +#define NMI_AHB_DATA_MEM_BASE 0x30000 +#define NMI_AHB_SHARE_MEM_BASE 0xd0000 + +#define WIFI_HOST_RCV_CTRL_0 (0x1070) +#define WIFI_HOST_RCV_CTRL_1 (0x1084) +#define WIFI_HOST_RCV_CTRL_2 (0x1078) +#define WIFI_HOST_RCV_CTRL_3 (0x106c) +#define WIFI_HOST_RCV_CTRL_4 (0x150400) +#define WIFI_HOST_RCV_CTRL_5 (0x1088) + +typedef struct { + uint8 u8ChipMode; + uint8 u8ChipSleep; + uint8 u8HifRXDone; + uint8 u8Interrupt; + uint32 u32RxAddr; + uint32 u32RxSize; + tpfHifCallBack pfWifiCb; + tpfHifCallBack pfIpCb; + tpfHifCallBack pfOtaCb; + tpfHifCallBack pfSigmaCb; + tpfHifCallBack pfHifCb; + tpfHifCallBack pfCryptoCb; + tpfHifCallBack pfSslCb; +}tstrHifContext; + +volatile tstrHifContext gstrHifCxt; + +static void isr(void) +{ + gstrHifCxt.u8Interrupt++; +#ifdef NM_LEVEL_INTERRUPT + nm_bsp_interrupt_ctrl(0); +#endif +} +static sint8 hif_set_rx_done(void) +{ + uint32 reg; + sint8 ret = M2M_SUCCESS; + + gstrHifCxt.u8HifRXDone = 0; +#ifdef NM_EDGE_INTERRUPT + nm_bsp_interrupt_ctrl(1); +#endif + ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0,®); + if(ret != M2M_SUCCESS)goto ERR1; + /* Set RX Done */ + reg |= NBIT1; + ret = nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg); + if(ret != M2M_SUCCESS)goto ERR1; +#ifdef NM_LEVEL_INTERRUPT + nm_bsp_interrupt_ctrl(1); +#endif +ERR1: + return ret; + +} +/** +* @fn static void m2m_hif_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +* @brief WiFi call back function +* @param [in] u8OpCode +* HIF Opcode type. +* @param [in] u16DataSize +* HIF data length. +* @param [in] u32Addr +* HIF address. +* @param [in] grp +* HIF group type. +* @author +* @date +* @version 1.0 +*/ +static void m2m_hif_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)u8OpCode; + (void)u16DataSize; + (void)u32Addr; +#endif +} +/** +* @fn NMI_API sint8 hif_chip_wake(void); +* @brief To Wakeup the chip. +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +sint8 hif_chip_wake(void) +{ + sint8 ret = M2M_SUCCESS; + if(gstrHifCxt.u8HifRXDone) + { + /*chip already wake for the rx not done no need to send wake request*/ + return ret; + } + if(gstrHifCxt.u8ChipSleep == 0) + { + if(gstrHifCxt.u8ChipMode != M2M_NO_PS) + { + ret = chip_wake(); + if(ret != M2M_SUCCESS)goto ERR1; + } + else + { + } + } + gstrHifCxt.u8ChipSleep++; +ERR1: + return ret; +} +/*! +@fn \ + NMI_API void hif_set_sleep_mode(uint8 u8Pstype); + +@brief + Set the sleep mode of the HIF layer. + +@param [in] u8Pstype + Sleep mode. + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ + +void hif_set_sleep_mode(uint8 u8Pstype) +{ + gstrHifCxt.u8ChipMode = u8Pstype; +} +/*! +@fn \ + NMI_API uint8 hif_get_sleep_mode(void); + +@brief + Get the sleep mode of the HIF layer. + +@return + The function SHALL return the sleep mode of the HIF layer. +*/ + +uint8 hif_get_sleep_mode(void) +{ + return gstrHifCxt.u8ChipMode; +} + +/** +* @fn NMI_API sint8 hif_chip_sleep_sc(void); +* @brief To clear the chip sleep but keep the chip sleep +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +sint8 hif_chip_sleep_sc(void) +{ + if(gstrHifCxt.u8ChipSleep >= 1) + { + gstrHifCxt.u8ChipSleep--; + } + return M2M_SUCCESS; +} +/** +* @fn NMI_API sint8 hif_chip_sleep(void); +* @brief To make the chip sleep. +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +sint8 hif_chip_sleep(void) +{ + sint8 ret = M2M_SUCCESS; + + if(gstrHifCxt.u8ChipSleep >= 1) + { + gstrHifCxt.u8ChipSleep--; + } + + if(gstrHifCxt.u8ChipSleep == 0) + { + if(gstrHifCxt.u8ChipMode != M2M_NO_PS) + { + ret = chip_sleep(); + if(ret != M2M_SUCCESS)goto ERR1; + + } + else + { + } + } +ERR1: + return ret; +} +/** +* @fn NMI_API sint8 hif_init(void * arg); +* @brief To initialize HIF layer. +* @param [in] arg +* Pointer to the arguments. +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +sint8 hif_init(void * arg) +{ +#ifdef ARDUINO + (void)arg; // Silence "unused" warning +#endif + m2m_memset((uint8*)&gstrHifCxt,0,sizeof(tstrHifContext)); + nm_bsp_register_isr(isr); + hif_register_cb(M2M_REQ_GROUP_HIF,m2m_hif_cb); + return M2M_SUCCESS; +} +/** +* @fn NMI_API sint8 hif_deinit(void * arg); +* @brief To De-initialize HIF layer. +* @param [in] arg +* Pointer to the arguments. +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ +sint8 hif_deinit(void * arg) +{ +#ifdef ARDUINO + (void)arg; // Silence "unused" warning +#endif + sint8 ret = M2M_SUCCESS; + ret = hif_chip_wake(); + m2m_memset((uint8*)&gstrHifCxt,0,sizeof(tstrHifContext)); + return ret; +} +/** +* @fn NMI_API sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, + uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) +* @brief Send packet using host interface. + +* @param [in] u8Gid +* Group ID. +* @param [in] u8Opcode +* Operation ID. +* @param [in] pu8CtrlBuf +* Pointer to the Control buffer. +* @param [in] u16CtrlBufSize + Control buffer size. +* @param [in] u16DataOffset + Packet Data offset. +* @param [in] pu8DataBuf +* Packet buffer Allocated by the caller. +* @param [in] u16DataSize + Packet buffer size (including the HIF header). +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, + uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) +{ + sint8 ret = M2M_ERR_SEND; + volatile tstrHifHdr strHif; + + strHif.u8Opcode = u8Opcode&(~NBIT7); + strHif.u8Gid = u8Gid; + strHif.u16Length = M2M_HIF_HDR_OFFSET; + if(pu8DataBuf != NULL) + { + strHif.u16Length += u16DataOffset + u16DataSize; + } + else + { + strHif.u16Length += u16CtrlBufSize; + } + ret = hif_chip_wake(); + if(ret == M2M_SUCCESS) + { + volatile uint32 reg, dma_addr = 0; + volatile uint16 cnt = 0; +//#define OPTIMIZE_BUS +/*please define in firmware also*/ +#ifndef OPTIMIZE_BUS + reg = 0UL; + reg |= (uint32)u8Gid; + reg |= ((uint32)u8Opcode<<8); + reg |= ((uint32)strHif.u16Length<<16); + ret = nm_write_reg(NMI_STATE_REG,reg); + if(M2M_SUCCESS != ret) goto ERR1; + + reg = 0UL; + reg |= NBIT1; + ret = nm_write_reg(WIFI_HOST_RCV_CTRL_2, reg); + if(M2M_SUCCESS != ret) goto ERR1; +#else + reg = 0UL; + reg |= NBIT1; + reg |= ((u8Opcode & NBIT7) ? (NBIT2):(0)); /*Data = 1 or config*/ + reg |= (u8Gid == M2M_REQ_GROUP_IP) ? (NBIT3):(0); /*IP = 1 or non IP*/ + reg |= ((uint32)strHif.u16Length << 4); /*length of pkt max = 4096*/ + ret = nm_write_reg(WIFI_HOST_RCV_CTRL_2, reg); + if(M2M_SUCCESS != ret) goto ERR1; +#endif + dma_addr = 0; + + for(cnt = 0; cnt < 1000; cnt ++) + { + ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_2,(uint32 *)®); + if(ret != M2M_SUCCESS) break; + /* + * If it takes too long to get a response, the slow down to + * avoid back-to-back register read operations. + */ + if(cnt >= 500) { + if(cnt < 501) { + M2M_INFO("Slowing down...\n"); + } + nm_bsp_sleep(1); + } + if (!(reg & NBIT1)) + { + ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_4,(uint32 *)&dma_addr); + if(ret != M2M_SUCCESS) { + /*in case of read error clear the DMA address and return error*/ + dma_addr = 0; + goto ERR1; + } + /*in case of success break */ + break; + } + } + + if (dma_addr != 0) + { + volatile uint32 u32CurrAddr; + u32CurrAddr = dma_addr; + strHif.u16Length=NM_BSP_B_L_16(strHif.u16Length); + ret = nm_write_block(u32CurrAddr, (uint8*)&strHif, M2M_HIF_HDR_OFFSET); + if(M2M_SUCCESS != ret) goto ERR1; + u32CurrAddr += M2M_HIF_HDR_OFFSET; + if(pu8CtrlBuf != NULL) + { + ret = nm_write_block(u32CurrAddr, pu8CtrlBuf, u16CtrlBufSize); + if(M2M_SUCCESS != ret) goto ERR1; + u32CurrAddr += u16CtrlBufSize; + } + if(pu8DataBuf != NULL) + { + u32CurrAddr += (u16DataOffset - u16CtrlBufSize); + ret = nm_write_block(u32CurrAddr, pu8DataBuf, u16DataSize); + if(M2M_SUCCESS != ret) goto ERR1; + u32CurrAddr += u16DataSize; + } + + reg = dma_addr << 2; + reg |= NBIT1; + ret = nm_write_reg(WIFI_HOST_RCV_CTRL_3, reg); + if(M2M_SUCCESS != ret) goto ERR1; + } + else + { + ret = hif_chip_sleep(); + M2M_DBG("Failed to alloc rx size %d\r",ret); + ret = M2M_ERR_MEM_ALLOC; + goto ERR2; + } + + } + else + { + M2M_ERR("(HIF)Fail to wakup the chip\n"); + goto ERR2; + } + /*actual sleep ret = M2M_SUCCESS*/ + ret = hif_chip_sleep(); + return ret; +ERR1: + /*reset the count but no actual sleep as it already bus error*/ + hif_chip_sleep_sc(); +ERR2: + /*logical error*/ + return ret; +} + +#ifdef ARDUINO +volatile uint8 hif_small_xfer = 0; +#endif + +/** +* @fn hif_isr +* @brief Host interface interrupt service routine +* @author M. Abdelmawla +* @date 15 July 2012 +* @return 1 in case of interrupt received else 0 will be returned +* @version 1.0 +*/ +static sint8 hif_isr(void) +{ + sint8 ret = M2M_SUCCESS; + volatile uint32 reg; + volatile tstrHifHdr strHif; + +#ifdef ARDUINO + ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, (uint32*)®); +#else + ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, ®); +#endif + if(M2M_SUCCESS == ret) + { + if(reg & 0x1) /* New interrupt has been received */ + { + uint16 size; + + nm_bsp_interrupt_ctrl(0); + /*Clearing RX interrupt*/ + reg &= ~NBIT0; + ret = nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg); + if(ret != M2M_SUCCESS)goto ERR1; + gstrHifCxt.u8HifRXDone = 1; + size = (uint16)((reg >> 2) & 0xfff); + if (size > 0) { + uint32 address = 0; + /** + start bus transfer + **/ + ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_1, &address); + if(M2M_SUCCESS != ret) + { + M2M_ERR("(hif) WIFI_HOST_RCV_CTRL_1 bus fail\n"); + nm_bsp_interrupt_ctrl(1); + goto ERR1; + } + gstrHifCxt.u32RxAddr = address; + gstrHifCxt.u32RxSize = size; + ret = nm_read_block(address, (uint8*)&strHif, sizeof(tstrHifHdr)); + strHif.u16Length = NM_BSP_B_L_16(strHif.u16Length); + if(M2M_SUCCESS != ret) + { + M2M_ERR("(hif) address bus fail\n"); + nm_bsp_interrupt_ctrl(1); + goto ERR1; + } + if(strHif.u16Length != size) + { + if((size - strHif.u16Length) > 4) + { + M2M_ERR("(hif) Corrupted packet Size = %u \n", + size, strHif.u16Length, strHif.u8Gid, strHif.u8Opcode); + nm_bsp_interrupt_ctrl(1); + ret = M2M_ERR_BUS_FAIL; + goto ERR1; + } + } + + if(M2M_REQ_GROUP_WIFI == strHif.u8Gid) + { + if(gstrHifCxt.pfWifiCb) + gstrHifCxt.pfWifiCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); + else +#ifdef ARDUINO + { +#endif + M2M_ERR("WIFI callback is not registered\n"); +#ifdef ARDUINO + } +#endif + } + else if(M2M_REQ_GROUP_IP == strHif.u8Gid) + { + if(gstrHifCxt.pfIpCb) + gstrHifCxt.pfIpCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); + else +#ifdef ARDUINO + { +#endif + M2M_ERR("Scoket callback is not registered\n"); +#ifdef ARDUINO + } +#endif + } + else if(M2M_REQ_GROUP_OTA == strHif.u8Gid) + { + if(gstrHifCxt.pfOtaCb) + gstrHifCxt.pfOtaCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); + else +#ifdef ARDUINO + { +#endif + M2M_ERR("Ota callback is not registered\n"); +#ifdef ARDUINO + } +#endif + } + else if(M2M_REQ_GROUP_CRYPTO == strHif.u8Gid) + { + if(gstrHifCxt.pfCryptoCb) + gstrHifCxt.pfCryptoCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); + + else +#ifdef ARDUINO + { +#endif + M2M_ERR("Crypto callback is not registered\n"); +#ifdef ARDUINO + } +#endif + } + else if(M2M_REQ_GROUP_SIGMA == strHif.u8Gid) + { + if(gstrHifCxt.pfSigmaCb) + gstrHifCxt.pfSigmaCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); + else +#ifdef ARDUINO + { +#endif + M2M_ERR("Sigma callback is not registered\n"); +#ifdef ARDUINO + } +#endif + } + else if(M2M_REQ_GROUP_SSL == strHif.u8Gid) + { + if(gstrHifCxt.pfSslCb) + gstrHifCxt.pfSslCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); + } + else + { + M2M_ERR("(hif) invalid group ID\n"); + ret = M2M_ERR_BUS_FAIL; + goto ERR1; + } +#ifdef ARDUINO + if(hif_small_xfer) + { + /*Pause SPI transfer*/ + return ret; + } +#endif + if(gstrHifCxt.u8HifRXDone) + { + M2M_ERR("(hif) host app didn't set RX Done <%u><%X>\n", strHif.u8Gid, strHif.u8Opcode); + ret = hif_set_rx_done(); + if(ret != M2M_SUCCESS) goto ERR1; + } + } + else + { + M2M_ERR("(hif) Wrong Size\n"); + ret = M2M_ERR_RCV; + goto ERR1; + } + } + else + { +#ifndef WIN32 + M2M_ERR("(hif) False interrupt %lx",reg); + ret = M2M_ERR_FAIL; + goto ERR1; +#else +#endif + } + } + else + { + M2M_ERR("(hif) Fail to Read interrupt reg\n"); + goto ERR1; + } + +ERR1: + return ret; +} + +#ifdef ARDUINO +void Socket_ReadSocketData_Small(void); +#endif + +/** +* @fn hif_handle_isr(void) +* @brief Handle interrupt received from NMC1500 firmware. +* @return The function SHALL return 0 for success and a negative value otherwise. +*/ + +sint8 hif_handle_isr(void) +{ + sint8 ret = M2M_SUCCESS; + +#ifdef ARDUINO + if(hif_small_xfer) { + /*SPI protocol paused to allow small transfer*/ + Socket_ReadSocketData_Small(); + return ret; + } +#endif + + while (gstrHifCxt.u8Interrupt) { + /*must be at that place because of the race of interrupt increment and that decrement*/ + /*when the interrupt enabled*/ + gstrHifCxt.u8Interrupt--; + while(1) + { + ret = hif_isr(); +#ifdef ARDUINO + if(hif_small_xfer) { + return ret; + } +#endif + if(ret == M2M_SUCCESS) { + /*we will try forever untill we get that interrupt*/ + /*Fail return errors here due to bus errors (reading expected values)*/ + break; + } else { + M2M_ERR("(HIF) Fail to handle interrupt %d try Again..\n",ret); + } + } + } + + return ret; +} +/* +* @fn hif_receive +* @brief Host interface interrupt serviece routine +* @param [in] u32Addr +* Receive start address +* @param [out] pu8Buf +* Pointer to receive buffer. Allocated by the caller +* @param [in] u16Sz +* Receive buffer size +* @param [in] isDone +* If you don't need any more packets send True otherwise send false +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ +sint8 hif_receive(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz, uint8 isDone) +{ + sint8 ret = M2M_SUCCESS; + if((u32Addr == 0)||(pu8Buf == NULL) || (u16Sz == 0)) + { + if(isDone) + { + /* set RX done */ + ret = hif_set_rx_done(); + } + else + { + ret = M2M_ERR_FAIL; + M2M_ERR(" hif_receive: Invalid argument\n"); + } + goto ERR1; + } + + if(u16Sz > gstrHifCxt.u32RxSize) + { + ret = M2M_ERR_FAIL; + M2M_ERR("APP Requested Size is larger than the recived buffer size <%u><%lu>\n",u16Sz, gstrHifCxt.u32RxSize); + goto ERR1; + } + if((u32Addr < gstrHifCxt.u32RxAddr)||((u32Addr + u16Sz)>(gstrHifCxt.u32RxAddr + gstrHifCxt.u32RxSize))) + { + ret = M2M_ERR_FAIL; + M2M_ERR("APP Requested Address beyond the recived buffer address and length\n"); + goto ERR1; + } + + /* Receive the payload */ + ret = nm_read_block(u32Addr, pu8Buf, u16Sz); + if(ret != M2M_SUCCESS)goto ERR1; + + /* check if this is the last packet */ + if((((gstrHifCxt.u32RxAddr + gstrHifCxt.u32RxSize) - (u32Addr + u16Sz)) <= 0) || isDone) + { + /* set RX done */ + ret = hif_set_rx_done(); + } + +ERR1: + return ret; +} + +/** +* @fn hif_register_cb +* @brief To set Callback function for every compantent Component +* @param [in] u8Grp +* Group to which the Callback function should be set. +* @param [in] fn +* function to be set +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +sint8 hif_register_cb(uint8 u8Grp,tpfHifCallBack fn) +{ + sint8 ret = M2M_SUCCESS; + switch(u8Grp) + { + case M2M_REQ_GROUP_IP: + gstrHifCxt.pfIpCb = fn; + break; + case M2M_REQ_GROUP_WIFI: + gstrHifCxt.pfWifiCb = fn; + break; + case M2M_REQ_GROUP_OTA: + gstrHifCxt.pfOtaCb = fn; + break; + case M2M_REQ_GROUP_HIF: + gstrHifCxt.pfHifCb = fn; + break; + case M2M_REQ_GROUP_CRYPTO: + gstrHifCxt.pfCryptoCb = fn; + break; + case M2M_REQ_GROUP_SIGMA: + gstrHifCxt.pfSigmaCb = fn; + break; + case M2M_REQ_GROUP_SSL: + gstrHifCxt.pfSslCb = fn; + break; + default: + M2M_ERR("GRp ? %d\n",u8Grp); + ret = M2M_ERR_FAIL; + break; + } + return ret; +} + +#endif diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_hif.h b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_hif.h new file mode 100644 index 0000000..1187183 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_hif.h @@ -0,0 +1,249 @@ +/** + * + * \file + * + * \brief This module contains M2M host interface APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _M2M_HIF_ +#define _M2M_HIF_ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "common/include/nm_common.h" +/*!< Include depends on UNO Board is used or not*/ +#ifdef ENABLE_UNO_BOARD +#include "m2m_uno_hif.h" +#endif + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#define M2M_HIF_MAX_PACKET_SIZE (1600 - 4) +/*!< Maximum size of the buffer could be transferred between Host and Firmware. +*/ + +#define M2M_HIF_HDR_OFFSET (sizeof(tstrHifHdr) + 4) + +/** +* @struct tstrHifHdr +* @brief Structure to hold HIF header +*/ +typedef struct +{ + uint8 u8Gid; /*!< Group ID */ + uint8 u8Opcode; /*!< OP code */ + uint16 u16Length; /*!< Payload length */ +}tstrHifHdr; + +#ifdef __cplusplus + extern "C" { +#endif + +/*! +@typedef typedef void (*tpfHifCallBack)(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr); +@brief used to point to Wi-Fi call back function depend on Arduino project or other projects. +@param [in] u8OpCode + HIF Opcode type. +@param [in] u16DataSize + HIF data length. +@param [in] u32Addr + HIF address. +@param [in] grp + HIF group type. +*/ +typedef void (*tpfHifCallBack)(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr); +/** +* @fn NMI_API sint8 hif_init(void * arg); +* @brief + To initialize HIF layer. +* @param [in] arg +* Pointer to the arguments. +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 hif_init(void * arg); +/** +* @fn NMI_API sint8 hif_deinit(void * arg); +* @brief + To Deinitialize HIF layer. +* @param [in] arg +* Pointer to the arguments. +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 hif_deinit(void * arg); +/** +* @fn NMI_API sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, + uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) +* @brief Send packet using host interface. + +* @param [in] u8Gid +* Group ID. +* @param [in] u8Opcode +* Operation ID. +* @param [in] pu8CtrlBuf +* Pointer to the Control buffer. +* @param [in] u16CtrlBufSize + Control buffer size. +* @param [in] u16DataOffset + Packet Data offset. +* @param [in] pu8DataBuf +* Packet buffer Allocated by the caller. +* @param [in] u16DataSize + Packet buffer size (including the HIF header). +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, + uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset); +/* +* @fn hif_receive +* @brief Host interface interrupt serviece routine +* @param [in] u32Addr +* Receive start address +* @param [out] pu8Buf +* Pointer to receive buffer. Allocated by the caller +* @param [in] u16Sz +* Receive buffer size +* @param [in] isDone +* If you don't need any more packets send True otherwise send false +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +NMI_API sint8 hif_receive(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz, uint8 isDone); +/** +* @fn hif_register_cb +* @brief + To set Callback function for every Component. + +* @param [in] u8Grp +* Group to which the Callback function should be set. + +* @param [in] fn +* function to be set to the specified group. +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 hif_register_cb(uint8 u8Grp,tpfHifCallBack fn); +/** +* @fn NMI_API sint8 hif_chip_sleep(void); +* @brief + To make the chip sleep. +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 hif_chip_sleep(void); +/** +* @fn NMI_API sint8 hif_chip_sleep_sc(void); +* @brief + To clear the chip count only but keep the chip awake +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 hif_chip_sleep_sc(void); +/** +* @fn NMI_API sint8 hif_chip_wake(void); +* @brief + To Wakeup the chip. +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +NMI_API sint8 hif_chip_wake(void); +/*! +@fn \ + NMI_API void hif_set_sleep_mode(uint8 u8Pstype); + +@brief + Set the sleep mode of the HIF layer. + +@param [in] u8Pstype + Sleep mode. + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ + +NMI_API void hif_set_sleep_mode(uint8 u8Pstype); +/*! +@fn \ + NMI_API uint8 hif_get_sleep_mode(void); + +@brief + Get the sleep mode of the HIF layer. + +@return + The function SHALL return the sleep mode of the HIF layer. +*/ + +NMI_API uint8 hif_get_sleep_mode(void); + +#ifdef CORTUS_APP +/** +* @fn hif_Resp_handler(uint8 *pu8Buffer, uint16 u16BufferSize) +* @brief + Response handler for HIF layer. + +* @param [in] pu8Buffer + Pointer to the buffer. + +* @param [in] u16BufferSize + Buffer size. + +* @return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 hif_Resp_handler(uint8 *pu8Buffer, uint16 u16BufferSize); +#endif + +/** +* @fn hif_handle_isr(void) +* @brief + Handle interrupt received from NMC1500 firmware. +* @return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 hif_handle_isr(void); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ota.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ota.c new file mode 100644 index 0000000..cf4a30f --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ota.c @@ -0,0 +1,417 @@ +/** + * + * \file + * + * \brief NMC1500 IoT OTA Interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#include "common/include/nm_common.h" +#include "driver/include/m2m_types.h" +#include "driver/include/m2m_ota.h" +#include "driver/source/m2m_hif.h" +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +static tpfOtaUpdateCb gpfOtaUpdateCb = NULL; +static tpfOtaNotifCb gpfOtaNotifCb = NULL; + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/** +* @fn m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr, uint8 grp) +* @brief WiFi call back function +* @param [in] u8OpCode +* HIF Opcode type. +* @param [in] u16DataSize +* HIF data length. +* @param [in] u32Addr +* HIF address. +* @param [in] grp +* HIF group type. +* @author +* @date +* @version 1.0 +*/ +static void m2m_ota_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +{ +#ifdef ARDUINO + (void)u16DataSize; // Silence "unused" warning +#endif + sint8 ret = M2M_SUCCESS; + if(u8OpCode == M2M_OTA_RESP_NOTIF_UPDATE_INFO) + { + tstrOtaUpdateInfo strOtaUpdateInfo; + m2m_memset((uint8*)&strOtaUpdateInfo,0,sizeof(tstrOtaUpdateInfo)); + ret = hif_receive(u32Addr,(uint8*)&strOtaUpdateInfo,sizeof(tstrOtaUpdateInfo),0); + if(ret == M2M_SUCCESS) + { + if(gpfOtaNotifCb) + gpfOtaNotifCb(&strOtaUpdateInfo); + } + } + else if (u8OpCode == M2M_OTA_RESP_UPDATE_STATUS) + { + tstrOtaUpdateStatusResp strOtaUpdateStatusResp; + m2m_memset((uint8*)&strOtaUpdateStatusResp,0,sizeof(tstrOtaUpdateStatusResp)); + ret = hif_receive(u32Addr, (uint8*) &strOtaUpdateStatusResp,sizeof(tstrOtaUpdateStatusResp), 0); + if(ret == M2M_SUCCESS) + { + if(gpfOtaUpdateCb) + gpfOtaUpdateCb(strOtaUpdateStatusResp.u8OtaUpdateStatusType,strOtaUpdateStatusResp.u8OtaUpdateStatus); + } + } + else + { + M2M_ERR("Invaild OTA resp %d ?\n",u8OpCode); + } + +} +/*! +@fn \ + NMI_API sint8 m2m_ota_init(tpfOtaUpdateCb pfOtaUpdateCb, tpfOtaNotifCb pfOtaNotifCb); + +@brief + Initialize the OTA layer. + +@param [in] pfOtaUpdateCb + OTA Update callback function + +@param [in] pfOtaNotifCb + OTA notify callback function + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_init(tpfOtaUpdateCb pfOtaUpdateCb, tpfOtaNotifCb pfOtaNotifCb) +{ + sint8 ret = M2M_SUCCESS; + + if(pfOtaUpdateCb){ + gpfOtaUpdateCb = pfOtaUpdateCb; + }else{ + M2M_ERR("Invaild Ota update cb\n"); + } + if(pfOtaNotifCb){ + gpfOtaNotifCb = pfOtaNotifCb; + }else{ + M2M_ERR("Invaild Ota notify cb\n"); + } + + hif_register_cb(M2M_REQ_GROUP_OTA,m2m_ota_cb); + + return ret; +} +/*! +@fn \ + NMI_API sint8 m2m_ota_notif_set_url(uint8 * u8Url); + +@brief + Set the OTA url + +@param [in] u8Url + The url server address + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_notif_set_url(uint8 * u8Url) +{ + sint8 ret = M2M_SUCCESS; + uint16 u16UrlSize = m2m_strlen(u8Url) + 1; + /*Todo: we may change it to data pkt but we need to give it higer priority + but the priorty is not implemnted yet in data pkt + */ + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_NOTIF_SET_URL,u8Url,u16UrlSize,NULL,0,0); + return ret; + +} + +/*! +@fn \ + NMI_API sint8 m2m_ota_notif_check_for_update(void); + +@brief + check for ota update + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_notif_check_for_update(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_NOTIF_CHECK_FOR_UPDATE,NULL,0,NULL,0,0); + return ret; +} + +/*! +@fn \ + NMI_API sint8 m2m_ota_notif_sched(uint32 u32Period); + +@brief + Schedule OTA update + +@param [in] u32Period + Period in days + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_notif_sched(uint32 u32Period) +{ +#ifdef ARDUINO + (void)u32Period; // Silence "unused" warning +#endif + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_NOTIF_CHECK_FOR_UPDATE,NULL,0,NULL,0,0); + return ret; +} + +/*! +@fn \ + NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl); + +@brief + Request OTA start update using the downloaded url + +@param [in] u8DownloadUrl + The download firmware url, you get it from device info + +@return + The function SHALL return 0 for success and a negative value otherwise. + +*/ +NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl) +{ + sint8 ret = M2M_SUCCESS; + uint16 u16DurlSize = m2m_strlen(u8DownloadUrl) + 1; + /*Todo: we may change it to data pkt but we need to give it higer priority + but the priorty is not implemnted yet in data pkt + */ + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_START_FW_UPDATE,u8DownloadUrl,u16DurlSize,NULL,0,0); + return ret; +} +/*! +@fn \ + NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl); + +@brief + Request OTA start for the Cortus app image. + +@param [in] u8DownloadUrl + The cortus application image url. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +*/ +NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl) +{ + sint8 ret = M2M_SUCCESS; + uint16 u16DurlSize = m2m_strlen(u8DownloadUrl) + 1; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_START_CRT_UPDATE,u8DownloadUrl,u16DurlSize,NULL,0,0); + return ret; +} + + +/*! +@fn \ + NMI_API sint8 m2m_ota_rollback(void); + +@brief + Request OTA Rollback image + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_rollback(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_ROLLBACK_FW,NULL,0,NULL,0,0); + return ret; +} +/*! +@fn \ + NMI_API sint8 m2m_ota_rollback_crt(void); + +@brief + Request Cortus application OTA Rollback image + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_rollback_crt(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_ROLLBACK_CRT,NULL,0,NULL,0,0); + return ret; +} + +/*! +@fn \ + NMI_API sint8 m2m_ota_abort(void); + +@brief + Request OTA Abort + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_abort(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_ABORT,NULL,0,NULL,0,0); + return ret; +} + + +/*! +@fn \ + NMI_API sint8 m2m_ota_switch_firmware(void); + +@brief + Switch to the upgraded Firmware + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_switch_firmware(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_SWITCH_FIRMWARE,NULL,0,NULL,0,0); + return ret; +} +/*! +@fn \ + NMI_API sint8 m2m_ota_switch_crt(void); + +@brief + Switch to the upgraded cortus application. + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_switch_crt(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_SWITCH_CRT_IMG,NULL,0,NULL,0,0); + return ret; +} + +/*! +@fn \ + NMI_API sint8 m2m_ota_get_firmware_version(tstrM2mRev * pstrRev); + +@brief + Get the OTA Firmware version. + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_get_firmware_version(tstrM2mRev * pstrRev) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_chip_wake(); + if(ret == M2M_SUCCESS) + { + ret = nm_get_ota_firmware_info(pstrRev); + hif_chip_sleep(); + } + return ret; +} +#if 0 +#define M2M_OTA_FILE "../../../m2m_ota.dat" +NMI_API sint8 m2m_ota_test(void) +{ + uint32 page = 0; + uint8 buffer[1500]; + uint32 u32Sz = 0; + sint8 ret = M2M_SUCCESS; + FILE *fp =NULL; + fp = fopen(M2M_OTA_FILE,"rb"); + if(fp) + { + fseek(fp, 0L, SEEK_END); + u32Sz = ftell(fp); + fseek(fp, 0L, SEEK_SET); + + while(u32Sz > 0) + { + { + page = (rand()%1400); + + if((page<100)||(page>1400)) page = 1400; + } + + if(u32Sz>page) + { + u32Sz-=page; + } + else + { + page = u32Sz; + u32Sz = 0; + } + printf("page %d\n", (int)page); + fread(buffer,page,1,fp); + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_TEST|M2M_REQ_DATA_PKT,NULL,0,(uint8*)&buffer,page,0); + if(ret != M2M_SUCCESS) + { + M2M_ERR("\n"); + } + nm_bsp_sleep(1); + } + + } + else + { + M2M_ERR("nO err\n"); + } + return ret; +} +#endif + diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_periph.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_periph.c new file mode 100644 index 0000000..0f8890b --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_periph.c @@ -0,0 +1,187 @@ +/** + * + * \file + * + * \brief NMC1500 Peripherials Application Interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "driver/include/m2m_periph.h" +#include "driver/source/nmasic.h" +#include "m2m_hif.h" + +#ifdef CONF_PERIPH + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#define GPIO_OP_DIR 0 +#define GPIO_OP_SET 1 +#define GPIO_OP_GET 2 +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +STATIC FUNCTIONS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +static sint8 get_gpio_idx(uint8 u8GpioNum) +{ + if(u8GpioNum >= M2M_PERIPH_GPIO_MAX) return -1; + if(u8GpioNum == M2M_PERIPH_GPIO15) { return 15; + } else if(u8GpioNum == M2M_PERIPH_GPIO16) { return 16; + } else if(u8GpioNum == M2M_PERIPH_GPIO18) { return 18; + } else if(u8GpioNum == M2M_PERIPH_GPIO3) { return 3; + } else if(u8GpioNum == M2M_PERIPH_GPIO4) { return 4; + } else if(u8GpioNum == M2M_PERIPH_GPIO5) { return 5; + } else if(u8GpioNum == M2M_PERIPH_GPIO6) { return 6; + } else { + return -2; + } +} +/* + * GPIO read/write skeleton with wakeup/sleep capability. + */ +static sint8 gpio_ioctl(uint8 op, uint8 u8GpioNum, uint8 u8InVal, uint8 * pu8OutVal) +{ + sint8 ret, gpio; + + ret = hif_chip_wake(); + if(ret != M2M_SUCCESS) goto _EXIT; + + gpio = get_gpio_idx(u8GpioNum); + if(gpio < 0) goto _EXIT1; + + if(op == GPIO_OP_DIR) { + ret = set_gpio_dir((uint8)gpio, u8InVal); + } else if(op == GPIO_OP_SET) { + ret = set_gpio_val((uint8)gpio, u8InVal); + } else if(op == GPIO_OP_GET) { + ret = get_gpio_val((uint8)gpio, pu8OutVal); + } + if(ret != M2M_SUCCESS) goto _EXIT1; + +_EXIT1: + ret = hif_chip_sleep(); +_EXIT: + return ret; +} +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION IMPLEMENTATION +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +sint8 m2m_periph_init(tstrPerphInitParam * param) +{ +#ifdef ARDUINO + (void)param; // Silence "unused" warning +#endif + return M2M_SUCCESS; +} + +sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir) +{ + return gpio_ioctl(GPIO_OP_DIR, u8GpioNum, u8GpioDir, NULL); +} + +sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal) +{ + return gpio_ioctl(GPIO_OP_SET, u8GpioNum, u8GpioVal, NULL); +} + +sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal) +{ + return gpio_ioctl(GPIO_OP_GET, u8GpioNum, 0, pu8GpioVal); +} + +sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn) +{ +#ifdef ARDUINO + (void)u8GpioNum; // Silence "unused" warning + (void)u8PullupEn; +#endif + /* TBD */ + return M2M_SUCCESS; +} + +sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)param; +#endif + /* TBD */ + return M2M_SUCCESS; +} + +sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)u8SlaveAddr; + (void)pu8Buf; + (void)u16BufLen; + (void)flags; +#endif + /* TBD */ + return M2M_SUCCESS; +} + +sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)u8SlaveAddr; + (void)pu8Buf; + (void)u16BufLen; + (void)pu16ReadLen; + (void)flags; +#endif + /* TBD */ + return M2M_SUCCESS; +} + + +sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable) +{ + return pullup_ctrl(pinmask, enable); +} +#endif /* CONF_PERIPH */ \ No newline at end of file diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ssl.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ssl.c new file mode 100644 index 0000000..07513f7 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ssl.c @@ -0,0 +1,309 @@ +/** + * + * \file + * + * \brief This module contains M2M Wi-Fi APIs implementation. + * + * Copyright (c) 2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "driver/include/m2m_ssl.h" +#include "driver/source/m2m_hif.h" +#include "driver/source/nmasic.h" + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +static tpfAppSSLCb gpfAppSSLCb = NULL; +static uint32 gu32HIFAddr = 0; + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*! + @fn \ m2m_ssl_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) + @brief SSL callback function + @param [in] u8OpCode + HIF Opcode type. + @param [in] u16DataSize + HIF data length. + @param [in] u32Addr + HIF address. +*/ +static void m2m_ssl_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +{ +#ifdef ARDUINO + (void)u16DataSize; // Silence "unused" warning +#endif + sint8 s8tmp = M2M_SUCCESS; + switch(u8OpCode) + { + case M2M_SSL_REQ_ECC: + { + tstrEccReqInfo strEccREQ; + s8tmp = hif_receive(u32Addr, (uint8*)&strEccREQ, sizeof(tstrEccReqInfo), 0); + if(s8tmp == M2M_SUCCESS) + { + if (gpfAppSSLCb) + { + gu32HIFAddr = u32Addr + sizeof(tstrEccReqInfo); + gpfAppSSLCb(M2M_SSL_REQ_ECC, &strEccREQ); + } + } + } + break; + case M2M_SSL_RESP_SET_CS_LIST: + { + tstrSslSetActiveCsList strCsList; + s8tmp = hif_receive(u32Addr, (uint8*)&strCsList, sizeof(tstrSslSetActiveCsList), 0); + if(s8tmp == M2M_SUCCESS) + { + if (gpfAppSSLCb) + gpfAppSSLCb(M2M_SSL_RESP_SET_CS_LIST, &strCsList); + } + } + break; + } + if(s8tmp != M2M_SUCCESS) + { + M2M_ERR("Error receiving SSL from the HIF\n"); + } +} + + +/*! + @fn \ m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz) + @brief Sends ECC responses to the WINC + @param [in] strECCResp + ECC Response struct. + @param [in] pu8RspDataBuffe + Pointer of the response data to be sent. + @param [in] u16RspDataSz + Response data size. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz) +{ + sint8 s8Ret = M2M_SUCCESS; + + s8Ret = hif_send(M2M_REQ_GROUP_SSL, (M2M_SSL_RESP_ECC | M2M_REQ_DATA_PKT), (uint8*)strECCResp, sizeof(tstrEccReqInfo), pu8RspDataBuff, u16RspDataSz, sizeof(tstrEccReqInfo)); + + return s8Ret; +} + +/*! + @fn \ m2m_ssl_send_certs_to_winc(uint8* sector_buffer, uint32 sector_size) + @brief Sends certificates to the WINC + @param [in] pu8Buffer + Pointer to the certificates. + @param [in] u32BufferSz + Size of the certificates. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_send_certs_to_winc(uint8* pu8Buffer, uint32 u32BufferSz) +{ + sint8 s8Ret = M2M_SUCCESS; + + s8Ret = hif_send(M2M_REQ_GROUP_SSL, (M2M_SSL_IND_CERTS_ECC | M2M_REQ_DATA_PKT), NULL, 0, pu8Buffer, u32BufferSz, 0); + + return s8Ret; +} + +/*! + @fn \ m2m_ssl_retrieve_cert(uint32 u32ReadAddr, uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key) + @brief Retrieve the certificate to be verified from the WINC + @param [in] pu16CurveType + Pointer to the certificate curve type. + @param [in] pu8Hash + Pointer to the certificate hash. + @param [in] pu8Sig + Pointer to the certificate signature. + @param [in] pu8Key + Pointer to the certificate Key. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_retrieve_cert(uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key) +{ + uint8 bSetRxDone = 1; + uint16 u16HashSz, u16SigSz, u16KeySz; + sint8 s8Ret = M2M_SUCCESS; + + if(gu32HIFAddr == 0) return M2M_ERR_FAIL; + + if(hif_receive(gu32HIFAddr, (uint8*)pu16CurveType, 2, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += 2; + + if(hif_receive(gu32HIFAddr, (uint8*)&u16KeySz, 2, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += 2; + + if(hif_receive(gu32HIFAddr, (uint8*)&u16HashSz, 2, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += 2; + + if(hif_receive(gu32HIFAddr, (uint8*)&u16SigSz, 2, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += 2; + + (*pu16CurveType)= _htons((*pu16CurveType)); + pu8Key->u16Size = _htons(u16KeySz); + u16HashSz = _htons(u16HashSz); + u16SigSz = _htons(u16SigSz); + + if(hif_receive(gu32HIFAddr, pu8Key->X, pu8Key->u16Size * 2, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += (pu8Key->u16Size * 2); + + if(hif_receive(gu32HIFAddr, pu8Hash, u16HashSz, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += u16HashSz; + + if(hif_receive(gu32HIFAddr, pu8Sig, u16SigSz, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += u16SigSz; + + bSetRxDone = 0; + +__ERR: + if(bSetRxDone) + { + s8Ret = M2M_ERR_FAIL; + hif_receive(0, NULL, 0, 1); + } + return s8Ret; +} + +/*! + @fn \ m2m_ssl_retrieve_hash(uint32 u32ReadAddr, uint8* pu8Hash, uint16 u16HashSz) + @brief Retrieve the certificate hash + @param [in] pu8Hash + Pointer to the certificate hash. + @param [in] u16HashSz + Hash size. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_retrieve_hash(uint8* pu8Hash, uint16 u16HashSz) +{ + uint8 bSetRxDone = 1; + sint8 s8Ret = M2M_SUCCESS; + + if(gu32HIFAddr == 0) return M2M_ERR_FAIL; + + if(hif_receive(gu32HIFAddr, pu8Hash, u16HashSz, 0) != M2M_SUCCESS) goto __ERR; + + bSetRxDone = 0; + +__ERR: + if(bSetRxDone) + { + s8Ret = M2M_ERR_FAIL; + hif_receive(0, NULL, 0, 1); + } + return s8Ret; +} + +/*! + @fn \ m2m_ssl_stop_processing_certs(void) + @brief Stops receiving from the HIF +*/ +NMI_API void m2m_ssl_stop_processing_certs(void) +{ + hif_receive(0, NULL, 0, 1); +} + +/*! + @fn \ m2m_ssl_ecc_process_done(void) + @brief Stops receiving from the HIF +*/ +NMI_API void m2m_ssl_ecc_process_done(void) +{ + gu32HIFAddr = 0; +} + +/*! +@fn \ + m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP); + Override the default Active SSL ciphers in the SSL module with a certain combination selected by the caller in the form of + a bitmap containing the required ciphers to be on. + There is no need to call this function if the application will not change the default ciphersuites. + +@param [in] u32SslCsBMP + Bitmap containing the desired ciphers to be enabled for the SSL module. The ciphersuites are defined in + @ref SSLCipherSuiteID. + The default ciphersuites are all ciphersuites supported by the firmware with the exception of ECC ciphersuites. + The caller can override the default with any desired combination, except for combinations involving both RSA + and ECC; if any RSA ciphersuite is enabled, then firmware will disable all ECC ciphersuites. + If u32SslCsBMP does not contain any ciphersuites supported by firmware, then the current active list will not + be changed. + +@return + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) +*/ +sint8 m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP) +{ + sint8 s8Ret = M2M_SUCCESS; + tstrSslSetActiveCsList strCsList; + + strCsList.u32CsBMP = u32SslCsBMP; + s8Ret = hif_send(M2M_REQ_GROUP_SSL, M2M_SSL_REQ_SET_CS_LIST, (uint8*)&strCsList, sizeof(tstrSslSetActiveCsList), NULL, 0, 0); + + return s8Ret; +} + +/*! + @fn \ m2m_ssl_init(tpfAppSslCb pfAppSslCb); + @brief Initializes the SSL layer. + @param [in] pfAppSslCb + Application SSL callback function. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_init(tpfAppSSLCb pfAppSSLCb) +{ + sint8 s8Ret = M2M_SUCCESS; + + gpfAppSSLCb = pfAppSSLCb; + gu32HIFAddr = 0; + + s8Ret = hif_register_cb(M2M_REQ_GROUP_SSL,m2m_ssl_cb); + if (s8Ret != M2M_SUCCESS) + { + M2M_ERR("hif_register_cb() failed with ret=%d", s8Ret); + } + return s8Ret; +} \ No newline at end of file diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_wifi.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_wifi.c new file mode 100644 index 0000000..7998623 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_wifi.c @@ -0,0 +1,1522 @@ +/** + * + * \file + * + * \brief This module contains M2M Wi-Fi APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "driver/include/m2m_wifi.h" +#include "driver/source/m2m_hif.h" +#include "driver/source/nmasic.h" + +static volatile uint8 gu8ChNum; +static volatile uint8 gu8scanInProgress = 0; +static tpfAppWifiCb gpfAppWifiCb = NULL; + + +#ifdef ETH_MODE +static tpfAppEthCb gpfAppEthCb = NULL; +static uint8* gau8ethRcvBuf=NULL; +static uint16 gu16ethRcvBufSize ; +#endif + + +//#define CONF_MGMT +#ifdef CONF_MGMT +static tpfAppMonCb gpfAppMonCb = NULL; +static struct _tstrMgmtCtrl +{ + uint8* pu8Buf; + uint16 u16Offset; + uint16 u16Sz; +} +gstrMgmtCtrl = {NULL, 0 , 0}; +#endif +/** +* @fn m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr, uint8 grp) +* @brief WiFi call back function +* @param [in] u8OpCode +* HIF Opcode type. +* @param [in] u16DataSize +* HIF data length. +* @param [in] u32Addr +* HIF address. +* @param [in] grp +* HIF group type. +* @author +* @date +* @version 1.0 +*/ +static void m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +{ +#ifdef ARDUINO + (void)u16DataSize; // Silence "unused" warning +#endif + uint8 rx_buf[8]; + if (u8OpCode == M2M_WIFI_RESP_CON_STATE_CHANGED) + { + tstrM2mWifiStateChanged strState; + if (hif_receive(u32Addr, (uint8*) &strState,sizeof(tstrM2mWifiStateChanged), 0) == M2M_SUCCESS) + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_CON_STATE_CHANGED, &strState); + } + } + else if (u8OpCode == M2M_WIFI_RESP_GET_SYS_TIME) + { + tstrSystemTime strSysTime; + if (hif_receive(u32Addr, (uint8*) &strSysTime,sizeof(tstrSystemTime), 0) == M2M_SUCCESS) + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_GET_SYS_TIME, &strSysTime); + } + } + else if(u8OpCode == M2M_WIFI_RESP_CONN_INFO) + { + tstrM2MConnInfo strConnInfo; + if(hif_receive(u32Addr, (uint8*)&strConnInfo, sizeof(tstrM2MConnInfo), 1) == M2M_SUCCESS) + { + if(gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_CONN_INFO, &strConnInfo); + } + } + else if (u8OpCode == M2M_WIFI_RESP_MEMORY_RECOVER) + { +#if 0 + if (hif_receive(u32Addr, rx_buf, 4, 1) == M2M_SUCCESS) + { + tstrM2mWifiStateChanged strState; + m2m_memcpy((uint8*) &strState, rx_buf,sizeof(tstrM2mWifiStateChanged)); + if (app_wifi_recover_cb) + app_wifi_recover_cb(strState.u8CurrState); + } +#endif + } + else if (u8OpCode == M2M_WIFI_REQ_DHCP_CONF) + { + tstrM2MIPConfig strIpConfig; +#ifdef ARDUINO + extern uint32 nmdrv_firm_ver; + uint16 rxSize = sizeof(tstrM2MIPConfig); + + if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 5, 0)) { + // for backwards compatibility with firmware 19.4.4 and older, + // the old tstrM2MIPConfig does not contain the u32DhcpLeaseTime field + rxSize -= sizeof(strIpConfig.u32DhcpLeaseTime); + } + + if (hif_receive(u32Addr, (uint8 *)&strIpConfig, rxSize, 0) == M2M_SUCCESS) +#else + if (hif_receive(u32Addr, (uint8 *)&strIpConfig, sizeof(tstrM2MIPConfig), 0) == M2M_SUCCESS) +#endif + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_REQ_DHCP_CONF, (uint8 *)&strIpConfig); + } + } + else if (u8OpCode == M2M_WIFI_REQ_WPS) + { + tstrM2MWPSInfo strWps; + m2m_memset((uint8*)&strWps,0,sizeof(tstrM2MWPSInfo)); + if(hif_receive(u32Addr, (uint8*)&strWps, sizeof(tstrM2MWPSInfo), 0) == M2M_SUCCESS) + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_REQ_WPS, &strWps); + } + } + else if (u8OpCode == M2M_WIFI_RESP_IP_CONFLICT) + { + uint32 u32ConflictedIP; + if(hif_receive(u32Addr, (uint8 *)&u32ConflictedIP, sizeof(u32ConflictedIP), 0) == M2M_SUCCESS) + { + M2M_INFO("Conflicted IP \" %u.%u.%u.%u \" \n", + BYTE_0(u32ConflictedIP),BYTE_1(u32ConflictedIP),BYTE_2(u32ConflictedIP),BYTE_3(u32ConflictedIP)); + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_IP_CONFLICT, NULL); + + } + } + else if (u8OpCode == M2M_WIFI_RESP_SCAN_DONE) + { + tstrM2mScanDone strState; + gu8scanInProgress = 0; + if(hif_receive(u32Addr, (uint8*)&strState, sizeof(tstrM2mScanDone), 0) == M2M_SUCCESS) + { + gu8ChNum = strState.u8NumofCh; + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_SCAN_DONE, &strState); + } + } + else if (u8OpCode == M2M_WIFI_RESP_SCAN_RESULT) + { + tstrM2mWifiscanResult strScanResult; + if(hif_receive(u32Addr, (uint8*)&strScanResult, sizeof(tstrM2mWifiscanResult), 0) == M2M_SUCCESS) + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_SCAN_RESULT, &strScanResult); + } + } + else if (u8OpCode == M2M_WIFI_RESP_CURRENT_RSSI) + { + if (hif_receive(u32Addr, rx_buf, 4, 0) == M2M_SUCCESS) + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_CURRENT_RSSI, rx_buf); + } + } + else if (u8OpCode == M2M_WIFI_RESP_CLIENT_INFO) + { + if (hif_receive(u32Addr, rx_buf, 4, 0) == M2M_SUCCESS) + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_CLIENT_INFO, rx_buf); + } + } + else if(u8OpCode == M2M_WIFI_RESP_PROVISION_INFO) + { + tstrM2MProvisionInfo strProvInfo; + if(hif_receive(u32Addr, (uint8*)&strProvInfo, sizeof(tstrM2MProvisionInfo), 1) == M2M_SUCCESS) + { + if(gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_PROVISION_INFO, &strProvInfo); + } + } + else if(u8OpCode == M2M_WIFI_RESP_DEFAULT_CONNECT) + { + tstrM2MDefaultConnResp strResp; + if(hif_receive(u32Addr, (uint8*)&strResp, sizeof(tstrM2MDefaultConnResp), 1) == M2M_SUCCESS) + { + if(gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_DEFAULT_CONNECT, &strResp); + } + } + + else if(u8OpCode == M2M_WIFI_RESP_GET_PRNG) + { + tstrPrng strPrng; + if(hif_receive(u32Addr, (uint8*)&strPrng,sizeof(tstrPrng), 0) == M2M_SUCCESS) + { + if(hif_receive(u32Addr + sizeof(tstrPrng),strPrng.pu8RngBuff,strPrng.u16PrngSize, 1) == M2M_SUCCESS) + { + if(gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_GET_PRNG,&strPrng); + } + } + } +#ifdef ETH_MODE + else if(u8OpCode == M2M_WIFI_RESP_ETHERNET_RX_PACKET) + { + uint8 u8SetRxDone; + tstrM2mIpRsvdPkt strM2mRsvd; + if(hif_receive(u32Addr, &strM2mRsvd ,sizeof(tstrM2mIpRsvdPkt), 0) == M2M_SUCCESS) + { + tstrM2mIpCtrlBuf strM2mIpCtrlBuf; + uint16 u16Offset = strM2mRsvd.u16PktOffset; + strM2mIpCtrlBuf.u16RemainigDataSize = strM2mRsvd.u16PktSz; + if((gpfAppEthCb) && (gau8ethRcvBuf) && (gu16ethRcvBufSize > 0)) + { + do + { + u8SetRxDone = 1; + if(strM2mIpCtrlBuf.u16RemainigDataSize > gu16ethRcvBufSize) + { + u8SetRxDone = 0; + strM2mIpCtrlBuf.u16DataSize = gu16ethRcvBufSize; + } + else + { + strM2mIpCtrlBuf.u16DataSize = strM2mIpCtrlBuf.u16RemainigDataSize; + } + + if(hif_receive(u32Addr + u16Offset, gau8ethRcvBuf, strM2mIpCtrlBuf.u16DataSize, u8SetRxDone) == M2M_SUCCESS) + { + strM2mIpCtrlBuf.u16RemainigDataSize -= strM2mIpCtrlBuf.u16DataSize; + u16Offset += strM2mIpCtrlBuf.u16DataSize; + gpfAppEthCb(M2M_WIFI_RESP_ETHERNET_RX_PACKET, gau8ethRcvBuf, &(strM2mIpCtrlBuf)); + } + else + { + break; + } + }while (strM2mIpCtrlBuf.u16RemainigDataSize > 0); + } + } + } +#endif /* ETH_MODE */ +#ifdef CONF_MGMT + else if(u8OpCode == M2M_WIFI_RESP_WIFI_RX_PACKET) + { + + tstrM2MWifiRxPacketInfo strRxPacketInfo; + if(u16DataSize >= sizeof(tstrM2MWifiRxPacketInfo)) { + if(hif_receive(u32Addr, (uint8*)&strRxPacketInfo, sizeof(tstrM2MWifiRxPacketInfo), 0) == M2M_SUCCESS) + { + u16DataSize -= sizeof(tstrM2MWifiRxPacketInfo); + if(u16DataSize > 0 && gstrMgmtCtrl.pu8Buf != NULL) + { + if(u16DataSize > (gstrMgmtCtrl.u16Sz + gstrMgmtCtrl.u16Offset)) + { + u16DataSize = gstrMgmtCtrl.u16Sz; + } + u32Addr += sizeof(tstrM2MWifiRxPacketInfo) + gstrMgmtCtrl.u16Offset; + if(hif_receive(u32Addr , gstrMgmtCtrl.pu8Buf, u16DataSize, 1) != M2M_SUCCESS) return; + } + if(gpfAppMonCb) + gpfAppMonCb(&strRxPacketInfo, gstrMgmtCtrl.pu8Buf,u16DataSize); + } + } else { + M2M_ERR("Incorrect mon data size %u\n", u16DataSize); + } + } +#endif + else + { + M2M_ERR("REQ Not defined %d\n",u8OpCode); + } +} + +sint8 m2m_wifi_download_mode() +{ + sint8 ret = M2M_SUCCESS; + /* Apply device specific initialization. */ + ret = nm_drv_init_download_mode(); + if(ret != M2M_SUCCESS) goto _EXIT0; + + + + enable_interrupts(); + +_EXIT0: + return ret; +} + +static sint8 m2m_validate_ap_parameters(CONST tstrM2MAPConfig* pstrM2MAPConfig) +{ + sint8 s8Ret = M2M_SUCCESS; + /* Check for incoming pointer */ + if(pstrM2MAPConfig == NULL) + { + M2M_ERR("INVALID POINTER\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + /* Check for SSID */ + if((m2m_strlen((uint8 *)pstrM2MAPConfig->au8SSID) <= 0) || (m2m_strlen((uint8 *)pstrM2MAPConfig->au8SSID) >= M2M_MAX_SSID_LEN)) + { + M2M_ERR("INVALID SSID\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + /* Check for Channel */ + if(pstrM2MAPConfig->u8ListenChannel > M2M_WIFI_CH_14 || pstrM2MAPConfig->u8ListenChannel < M2M_WIFI_CH_1) + { + M2M_ERR("INVALID CH\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + /* Check for DHCP Server IP address */ + if(!(pstrM2MAPConfig->au8DHCPServerIP[0] || pstrM2MAPConfig->au8DHCPServerIP[1])) + { + if(!(pstrM2MAPConfig->au8DHCPServerIP[2])) + { + M2M_ERR("INVALID DHCP SERVER IP\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + } + /* Check for Security */ + if(pstrM2MAPConfig->u8SecType == M2M_WIFI_SEC_OPEN) + { + goto ERR1; + } + else if(pstrM2MAPConfig->u8SecType == M2M_WIFI_SEC_WEP) + { + /* Check for WEP Key index */ + if((pstrM2MAPConfig->u8KeyIndx <= 0) || (pstrM2MAPConfig->u8KeyIndx > WEP_KEY_MAX_INDEX)) + { + M2M_ERR("INVALID KEY INDEX\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + /* Check for WEP Key size */ + if( (pstrM2MAPConfig->u8KeySz != WEP_40_KEY_STRING_SIZE) && + (pstrM2MAPConfig->u8KeySz != WEP_104_KEY_STRING_SIZE) + ) + { + M2M_ERR("INVALID KEY STRING SIZE\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + + if((m2m_strlen((uint8 *)pstrM2MAPConfig->au8WepKey) <= 0) || (m2m_strlen((uint8 *)pstrM2MAPConfig->au8WepKey) > WEP_104_KEY_STRING_SIZE)) + { + M2M_ERR("INVALID KEY SIZE\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + } + else if(pstrM2MAPConfig->u8SecType == M2M_WIFI_SEC_WPA_PSK) + { + /* Check for WPA Key size */ + if( ((pstrM2MAPConfig->u8KeySz + 1) < M2M_MIN_PSK_LEN) || ((pstrM2MAPConfig->u8KeySz + 1) > M2M_MAX_PSK_LEN)) + { + M2M_ERR("INVALID WPA KEY SIZE\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + } + else + { + M2M_ERR("INVALID AUTHENTICATION MODE\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + +ERR1: + return s8Ret; +} +static sint8 m2m_validate_scan_options(tstrM2MScanOption* ptstrM2MScanOption) +{ + sint8 s8Ret = M2M_SUCCESS; + /* Check for incoming pointer */ + if(ptstrM2MScanOption == NULL) + { + M2M_ERR("INVALID POINTER\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR; + } + /* Check for valid No of slots */ + if(ptstrM2MScanOption->u8NumOfSlot == 0) + { + M2M_ERR("INVALID No of scan slots! %d\n",ptstrM2MScanOption->u8NumOfSlot); + s8Ret = M2M_ERR_FAIL; + goto ERR; + } + /* Check for valid time of slots */ + if(ptstrM2MScanOption->u8SlotTime < 10 || ptstrM2MScanOption->u8SlotTime > 250) + { + M2M_ERR("INVALID scan slot time! %d\n",ptstrM2MScanOption->u8SlotTime); + s8Ret = M2M_ERR_FAIL; + goto ERR; + } + /* Check for valid No of probe requests per slot */ + if((ptstrM2MScanOption->u8ProbesPerSlot == 0)||(ptstrM2MScanOption->u8ProbesPerSlot > M2M_SCAN_DEFAULT_NUM_PROBE)) + { + M2M_ERR("INVALID No of probe requests per scan slot %d\n",ptstrM2MScanOption->u8ProbesPerSlot); + s8Ret = M2M_ERR_FAIL; + goto ERR; + } + /* Check for valid RSSI threshold */ + if((ptstrM2MScanOption->s8RssiThresh < -99) || (ptstrM2MScanOption->s8RssiThresh >= 0)) + { + M2M_ERR("INVALID RSSI threshold %d \n",ptstrM2MScanOption->s8RssiThresh); + s8Ret = M2M_ERR_FAIL; + } + +ERR: + return s8Ret; +} + +sint8 m2m_wifi_send_crl(tstrTlsCrlInfo* pCRL) +{ + sint8 s8Ret = M2M_ERR_FAIL; + s8Ret = hif_send(M2M_REQ_GROUP_SSL, M2M_SSL_IND_CRL|M2M_REQ_DATA_PKT, NULL, 0, (uint8*)pCRL, sizeof(tstrTlsCrlInfo), 0); + return s8Ret; +} + +sint8 m2m_wifi_init(tstrWifiInitParam * param) +{ + tstrM2mRev strtmp; + sint8 ret = M2M_SUCCESS; + uint8 u8WifiMode = M2M_WIFI_MODE_NORMAL; + + if(param == NULL) { + ret = M2M_ERR_FAIL; + goto _EXIT0; + } + + gpfAppWifiCb = param->pfAppWifiCb; + +#ifdef ETH_MODE + gpfAppEthCb = param->strEthInitParam.pfAppEthCb; + gau8ethRcvBuf = param->strEthInitParam.au8ethRcvBuf; + gu16ethRcvBufSize = param->strEthInitParam.u16ethRcvBufSize; + u8WifiMode = param->strEthInitParam.u8EthernetEnable; +#endif /* ETH_MODE */ + +#ifdef CONF_MGMT + gpfAppMonCb = param->pfAppMonCb; +#endif + gu8scanInProgress = 0; + /* Apply device specific initialization. */ + ret = nm_drv_init(&u8WifiMode); + if(ret != M2M_SUCCESS) goto _EXIT0; + /* Initialize host interface module */ + ret = hif_init(NULL); + if(ret != M2M_SUCCESS) goto _EXIT1; + + hif_register_cb(M2M_REQ_GROUP_WIFI,m2m_wifi_cb); + + ret = nm_get_firmware_full_info(&strtmp); + +#ifdef ARDUINO + if (M2M_ERR_FAIL == ret) + { + // for compatibility with firmware version 19.3.0 + ret = nm_get_firmware_info(&strtmp); + } +#endif + M2M_INFO("Firmware ver : %u.%u.%u Svnrev %u\n", strtmp.u8FirmwareMajor, strtmp.u8FirmwareMinor, strtmp.u8FirmwarePatch,strtmp.u16FirmwareSvnNum); + M2M_INFO("Firmware Build %s Time %s\n",strtmp.BuildDate,strtmp.BuildTime); + M2M_INFO("Firmware Min driver ver : %u.%u.%u\n", strtmp.u8DriverMajor, strtmp.u8DriverMinor, strtmp.u8DriverPatch); + M2M_INFO("Driver ver: %u.%u.%u\n", M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); + M2M_INFO("Driver built at %s\t%s\n",__DATE__,__TIME__); + if(M2M_ERR_FW_VER_MISMATCH == ret) + { + M2M_ERR("Mismatch Firmawre Version\n"); + } + + goto _EXIT0; + +_EXIT1: + nm_drv_deinit(NULL); +_EXIT0: + return ret; +} + +sint8 m2m_wifi_deinit(void * arg) +{ +#ifdef ARDUINO + (void)arg; // Silence "unused" warning +#endif + hif_deinit(NULL); + + nm_drv_deinit(NULL); + + return M2M_SUCCESS; +} + + +#ifdef ARDUINO +#include "socket/include/socket_buffer.h" +extern tstrSocketBuffer gastrSocketBuffer[]; +#endif + +sint8 m2m_wifi_handle_events(void * arg) +{ +#ifdef ARDUINO + (void)arg; // Silence "unused" warning + + uint8 i; + + /* Arduino API LIMITATION: */ + /* To be compliant with the standard Arduino WiFi API socket must be buffered. */ + /* WiFi101 shield does not have this ability and automatically pushes incoming */ + /* data to the Arduino MCU. Function m2m_wifi_handle_events() is taking care of */ + /* this transfer. Hence by ensuring that all the MCU socket buffers are available */ + /* we can perform the transfer. */ + /* However, if one socket buffer is full, we have to delay this transfer by */ + /* returning an error value, as we have no way of knowing which socket is about */ + /* to be used. */ + /* Consequently, the Arduino sketch must NOT block on reading only one socket if */ + /* several sockets are to be used. Instead, application must carefully read for */ + /* all sockets, anytime. */ + for (i = 0; i < MAX_SOCKET; ++i) { + if (gastrSocketBuffer[i].flag && (*(gastrSocketBuffer[i].flag) & SOCKET_BUFFER_FLAG_FULL)) { + return M2M_ERR_FAIL; + } + } +#endif + return hif_handle_isr(); +} + +sint8 m2m_wifi_default_connect(void) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DEFAULT_CONNECT, NULL, 0,NULL, 0,0); +} + +sint8 m2m_wifi_connect(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch) +{ + return m2m_wifi_connect_sc(pcSsid, u8SsidLen, u8SecType, pvAuthInfo, u16Ch,0); +} +sint8 m2m_wifi_connect_sc(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch, uint8 u8NoSaveCred) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mWifiConnect strConnect; + tstrM2MWifiSecInfo *pstrAuthInfo; + + if(u8SecType != M2M_WIFI_SEC_OPEN) + { + if(pvAuthInfo == NULL) + { + M2M_ERR("Key is not valid\n"); + ret = M2M_ERR_FAIL; + goto ERR1; + } + if((u8SecType == M2M_WIFI_SEC_WPA_PSK) && (m2m_strlen(pvAuthInfo) == (M2M_MAX_PSK_LEN-1))) + { + uint8 i = 0; + uint8* pu8Psk = (uint8*)pvAuthInfo; + while(i < (M2M_MAX_PSK_LEN-1)) + { + if(pu8Psk[i]<'0' || (pu8Psk[i]>'9' && pu8Psk[i] < 'A')|| (pu8Psk[i]>'F' && pu8Psk[i] < 'a') || pu8Psk[i] > 'f') + { + M2M_ERR("Invalid Key\n"); + ret = M2M_ERR_FAIL; + goto ERR1; + } + i++; + } + } + } + if((u8SsidLen<=0)||(u8SsidLen>=M2M_MAX_SSID_LEN)) + { + M2M_ERR("SSID LEN INVALID\n"); + ret = M2M_ERR_FAIL; + goto ERR1; + } + + if(u16Ch < M2M_WIFI_CH_1|| u16Ch > M2M_WIFI_CH_14) + { + if(u16Ch!=M2M_WIFI_CH_ALL) + { + M2M_ERR("CH INVALID\n"); + ret = M2M_ERR_FAIL; + goto ERR1; + } + } + + + m2m_memcpy(strConnect.au8SSID, (uint8*)pcSsid, u8SsidLen); + strConnect.au8SSID[u8SsidLen] = 0; + strConnect.u16Ch = NM_BSP_B_L_16(u16Ch); + /* Credentials will be Not be saved if u8NoSaveCred is set */ + strConnect.u8NoSaveCred = u8NoSaveCred ? 1:0; + pstrAuthInfo = &strConnect.strSec; + pstrAuthInfo->u8SecType = u8SecType; + + if(u8SecType == M2M_WIFI_SEC_WEP) + { + tstrM2mWifiWepParams * pstrWepParams = (tstrM2mWifiWepParams*)pvAuthInfo; + tstrM2mWifiWepParams *pstrWep = &pstrAuthInfo->uniAuth.strWepInfo; +#ifdef ARDUINO + pstrWep->u8KeyIndx =pstrWepParams->u8KeyIndx; +#else + pstrWep->u8KeyIndx =pstrWepParams->u8KeyIndx-1; +#endif + + if(pstrWep->u8KeyIndx >= WEP_KEY_MAX_INDEX) + { + M2M_ERR("Invalid Wep key index %d\n", pstrWep->u8KeyIndx); + ret = M2M_ERR_FAIL; + goto ERR1; + } +#ifdef ARDUINO + pstrWep->u8KeySz = pstrWepParams->u8KeySz; +#else + pstrWep->u8KeySz = pstrWepParams->u8KeySz-1; +#endif + if ((pstrWep->u8KeySz != WEP_40_KEY_STRING_SIZE)&& (pstrWep->u8KeySz != WEP_104_KEY_STRING_SIZE)) + { + M2M_ERR("Invalid Wep key length %d\n", pstrWep->u8KeySz); + ret = M2M_ERR_FAIL; + goto ERR1; + } + m2m_memcpy((uint8*)pstrWep->au8WepKey,(uint8*)pstrWepParams->au8WepKey, pstrWepParams->u8KeySz); + pstrWep->au8WepKey[pstrWepParams->u8KeySz] = 0; + + } + + + else if(u8SecType == M2M_WIFI_SEC_WPA_PSK) + { + uint16 u16KeyLen = m2m_strlen((uint8*)pvAuthInfo); + if((u16KeyLen <= 0)||(u16KeyLen >= M2M_MAX_PSK_LEN)) + { + M2M_ERR("Incorrect PSK key length\n"); + ret = M2M_ERR_FAIL; + goto ERR1; + } + m2m_memcpy(pstrAuthInfo->uniAuth.au8PSK, (uint8*)pvAuthInfo, u16KeyLen + 1); + } + else if(u8SecType == M2M_WIFI_SEC_802_1X) + { + m2m_memcpy((uint8*)&pstrAuthInfo->uniAuth.strCred1x, (uint8*)pvAuthInfo, sizeof(tstr1xAuthCredentials)); + } + else if(u8SecType == M2M_WIFI_SEC_OPEN) + { + + } + else + { + M2M_ERR("undefined sec type\n"); + ret = M2M_ERR_FAIL; + goto ERR1; + } + + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CONNECT, (uint8*)&strConnect, sizeof(tstrM2mWifiConnect),NULL, 0,0); + +ERR1: + return ret; +} + +sint8 m2m_wifi_disconnect(void) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISCONNECT, NULL, 0, NULL, 0,0); +} +sint8 m2m_wifi_set_mac_address(uint8 au8MacAddress[6]) +{ + tstrM2mSetMacAddress strTmp; + m2m_memcpy((uint8*) strTmp.au8Mac, (uint8*) au8MacAddress, 6); + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_MAC_ADDRESS, + (uint8*) &strTmp, sizeof(tstrM2mSetMacAddress), NULL, 0,0); +} + +sint8 m2m_wifi_set_static_ip(tstrM2MIPConfig * pstrStaticIPConf) +{ + pstrStaticIPConf->u32DNS = NM_BSP_B_L_32(pstrStaticIPConf->u32DNS); + pstrStaticIPConf->u32Gateway = NM_BSP_B_L_32(pstrStaticIPConf->u32Gateway); + pstrStaticIPConf->u32StaticIP = NM_BSP_B_L_32( + pstrStaticIPConf->u32StaticIP); + pstrStaticIPConf->u32SubnetMask = NM_BSP_B_L_32( + pstrStaticIPConf->u32SubnetMask); + return hif_send(M2M_REQ_GROUP_IP, M2M_IP_REQ_STATIC_IP_CONF, + (uint8*) pstrStaticIPConf, sizeof(tstrM2MIPConfig), NULL, 0,0); +} + +sint8 m2m_wifi_request_dhcp_client(void) +{ + /*legacy API should be removed */ + return 0; +} +sint8 m2m_wifi_request_dhcp_server(uint8* addr) +{ +#ifdef ARDUINO + (void)addr; // Silence "unused" warning +#endif + /*legacy API should be removed */ + return 0; +} +/*! +@fn NMI_API sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt * pstrM2mLsnInt); +@brief Set the Wi-Fi listen interval for power save operation. It is represented in units + of AP Beacon periods. +@param [in] pstrM2mLsnInt + Structure holding the listen interval configurations. +@return The function SHALL return 0 for success and a negative value otherwise. +@sa tstrM2mLsnInt , m2m_wifi_set_sleep_mode +@pre m2m_wifi_set_sleep_mode shall be called first +@warning The Function called once after initialization. +*/ +sint8 m2m_wifi_enable_dhcp(uint8 u8DhcpEn ) +{ + + uint8 u8Req; + u8Req = u8DhcpEn ? M2M_IP_REQ_ENABLE_DHCP : M2M_IP_REQ_DISABLE_DHCP; + return hif_send(M2M_REQ_GROUP_IP, u8Req, NULL, 0, NULL, 0, 0); + + +} + +sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt* pstrM2mLsnInt) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_LSN_INT, (uint8*)pstrM2mLsnInt, sizeof(tstrM2mLsnInt), NULL, 0, 0); +} + +sint8 m2m_wifi_set_cust_InfoElement(uint8* pau8M2mCustInfoElement) +{ + + sint8 ret = M2M_ERR_FAIL; + if(pau8M2mCustInfoElement != NULL) + { + if((pau8M2mCustInfoElement[0] + 1) < M2M_CUST_IE_LEN_MAX) + { + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CUST_INFO_ELEMENT|M2M_REQ_DATA_PKT, (uint8*)pau8M2mCustInfoElement, pau8M2mCustInfoElement[0]+1, NULL, 0, 0); + } + } + return ret; +} + +sint8 m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption) +{ + sint8 s8Ret = M2M_ERR_FAIL; + if(m2m_validate_scan_options (ptstrM2MScanOption) == M2M_SUCCESS) + { + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_SCAN_OPTION, (uint8*)ptstrM2MScanOption, sizeof(tstrM2MScanOption),NULL, 0,0); + } + return s8Ret; +} +sint8 m2m_wifi_set_scan_region(uint16 ScanRegion) +{ + sint8 s8Ret = M2M_ERR_FAIL; + tstrM2MScanRegion strScanRegion; + strScanRegion.u16ScanRegion = ScanRegion; + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_SCAN_REGION, (uint8*)&strScanRegion, sizeof(tstrM2MScanRegion),NULL, 0,0); + return s8Ret; +} +sint8 m2m_wifi_request_scan(uint8 ch) +{ + sint8 s8Ret = M2M_SUCCESS; + + if(!gu8scanInProgress) + { + if(((ch >= M2M_WIFI_CH_1) && (ch <= M2M_WIFI_CH_14)) || (ch == M2M_WIFI_CH_ALL)) + { + tstrM2MScan strtmp; + strtmp.u8ChNum = ch; + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SCAN, (uint8*)&strtmp, sizeof(tstrM2MScan),NULL, 0,0); + if(s8Ret == M2M_SUCCESS) + { + gu8scanInProgress = 1; + } + } + else + { + s8Ret = M2M_ERR_INVALID_ARG; + } + } + else + { + s8Ret = M2M_ERR_SCAN_IN_PROGRESS; + } + return s8Ret; +} + +sint8 m2m_wifi_request_scan_passive(uint8 ch, uint16 scan_time) +{ + sint8 s8Ret = M2M_SUCCESS; + + if(!gu8scanInProgress) + { + if(((ch >= M2M_WIFI_CH_1) && (ch <= M2M_WIFI_CH_14)) || (ch == M2M_WIFI_CH_ALL)) + { + tstrM2MScan strtmp; + strtmp.u8ChNum = ch; + + strtmp.u16PassiveScanTime = scan_time; + + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_PASSIVE_SCAN, (uint8*)&strtmp, sizeof(tstrM2MScan),NULL, 0,0); + if(s8Ret == M2M_SUCCESS) + { + gu8scanInProgress = 1; + } + } + else + { + s8Ret = M2M_ERR_INVALID_ARG; + } + } + else + { + s8Ret = M2M_ERR_SCAN_IN_PROGRESS; + } + return s8Ret; +} + +sint8 m2m_wifi_request_scan_ssid_list(uint8 ch,uint8 * u8Ssidlist) +{ + sint8 s8Ret = M2M_ERR_INVALID_ARG; + + if(!gu8scanInProgress) + { + if((((ch >= M2M_WIFI_CH_1) && (ch <= M2M_WIFI_CH_14)) || (ch == M2M_WIFI_CH_ALL))&&(u8Ssidlist != NULL)) + { + tstrM2MScan strtmp; + uint16 u16Lsize = 0; + uint8 u8Apnum = u8Ssidlist[u16Lsize]; + if(u8Apnum <= MAX_HIDDEN_SITES) + { + u16Lsize++; + while(u8Apnum) + { + if(u8Ssidlist[u16Lsize] >= M2M_MAX_SSID_LEN){ + goto EXIT; + }else { + u16Lsize += u8Ssidlist[u16Lsize] + 1; + u8Apnum--; + } + } + strtmp.u8ChNum = ch; + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SCAN_SSID_LIST|M2M_REQ_DATA_PKT, (uint8*)&strtmp, sizeof(tstrM2MScan),u8Ssidlist, u16Lsize,sizeof(tstrM2MScan)); + if(s8Ret == M2M_SUCCESS) + { + gu8scanInProgress = 1; + } + } + } + } + else + { + s8Ret = M2M_ERR_SCAN_IN_PROGRESS; + } +EXIT: + return s8Ret; +} +sint8 m2m_wifi_wps(uint8 u8TriggerType,const char *pcPinNumber) +{ + tstrM2MWPSConnect strtmp; + + /* Stop Scan if it is ongoing. + */ + gu8scanInProgress = 0; + strtmp.u8TriggerType = u8TriggerType; + /*If WPS is using PIN METHOD*/ + if (u8TriggerType == WPS_PIN_TRIGGER) + m2m_memcpy ((uint8*)strtmp.acPinNumber,(uint8*) pcPinNumber,8); + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_WPS, (uint8*)&strtmp,sizeof(tstrM2MWPSConnect), NULL, 0,0); +} +sint8 m2m_wifi_wps_disable(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_WPS, NULL,0, NULL, 0, 0); + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_req_client_ctrl(uint8 cmd); +@brief Send a command to the PS Client (An WINC1500 board running the ps_firmware), + if the PS client send any commands it will be received in wifi_cb M2M_WIFI_RESP_CLIENT_INFO +@param [in] cmd + Control command sent from PS Server to PS Client (command values defined by the application) +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. +@sa m2m_wifi_req_server_init, M2M_WIFI_RESP_CLIENT_INFO +@pre m2m_wifi_req_server_init should be called first +@warning +*/ +sint8 m2m_wifi_req_client_ctrl(uint8 u8Cmd) +{ + + sint8 ret = M2M_SUCCESS; +#ifdef _PS_SERVER_ + tstrM2Mservercmd strCmd; + strCmd.u8cmd = u8Cmd; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CLIENT_CTRL, (uint8*)&strCmd, sizeof(tstrM2Mservercmd), NULL, 0, 0); +#else +#ifdef ARDUINO + (void)u8Cmd; // Silence "unused" warning +#endif + M2M_ERR("_PS_SERVER_ is not defined\n"); +#endif + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_req_server_init(uint8 ch); +@brief Initialize the PS Server, The WINC1500 support Non secure communication with another WINC1500, + (SERVER/CLIENT) through one byte command (probe request and probe response) without any connection setup +@param [in] ch + Server listening channel +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise +@sa m2m_wifi_req_client_ctrl +@warning The server mode can't be used with any other modes (STA/P2P/AP) +*/ +sint8 m2m_wifi_req_server_init(uint8 ch) +{ + sint8 ret = M2M_SUCCESS; +#ifdef _PS_SERVER_ + tstrM2mServerInit strServer; + strServer.u8Channel = ch; + ret = hif_send(M2M_REQ_GROUP_WIFI,M2M_WIFI_REQ_SERVER_INIT, (uint8*)&strServer, sizeof(tstrM2mServerInit), NULL, 0, 0); +#else +#ifdef ARDUINO + (void)ch; // Silence "unused" warning +#endif + M2M_ERR("_PS_SERVER_ is not defined\n"); +#endif + return ret; +} +sint8 m2m_wifi_p2p(uint8 u8Channel) +{ + sint8 ret = M2M_SUCCESS; + if((u8Channel == M2M_WIFI_CH_1) || (u8Channel == M2M_WIFI_CH_6) || (u8Channel == M2M_WIFI_CH_11)) + { + tstrM2MP2PConnect strtmp; + strtmp.u8ListenChannel = u8Channel; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_P2P, (uint8*)&strtmp, sizeof(tstrM2MP2PConnect), NULL, 0,0); + } + else + { + M2M_ERR("Listen channel should only be M2M_WIFI_CH_1/6/11 \n"); + ret = M2M_ERR_FAIL; + } + return ret; +} +sint8 m2m_wifi_p2p_disconnect(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_P2P, NULL, 0, NULL, 0, 0); + return ret; +} +sint8 m2m_wifi_enable_ap(CONST tstrM2MAPConfig* pstrM2MAPConfig) +{ + sint8 ret = M2M_ERR_FAIL; + if(M2M_SUCCESS == m2m_validate_ap_parameters(pstrM2MAPConfig)) + { +#ifdef ARDUINO + extern uint32 nmdrv_firm_ver; + uint16 txSize = sizeof(tstrM2MAPConfig); + + if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 5, 0)) { + // for backwards compat with firmwware 19.4.x and older + // (listen channel is 0 based, there is no au8Key field) + ((tstrM2MAPConfig*)pstrM2MAPConfig)->u8ListenChannel--; + txSize -= sizeof(pstrM2MAPConfig->au8Key) + 1; + } + + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_AP, (uint8 *)pstrM2MAPConfig, txSize, NULL, 0, 0); +#else + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_AP, (uint8 *)pstrM2MAPConfig, sizeof(tstrM2MAPConfig), NULL, 0, 0); +#endif + } + return ret; +} + +sint8 m2m_wifi_set_gains(tstrM2mWifiGainsParams* pstrM2mGain) +{ + sint8 ret = M2M_ERR_FAIL; + if(pstrM2mGain != NULL) + { + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_GAINS, (uint8 *)pstrM2mGain, sizeof(tstrM2mWifiGainsParams), NULL, 0, 0); + } + return ret; +} +sint8 m2m_wifi_disable_ap(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_AP, NULL, 0, NULL, 0, 0); + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_req_curr_rssi(void); +@brief Request the current RSSI for the current connected AP, + the response received in wifi_cb M2M_WIFI_RESP_CURRENT_RSSI +@sa M2M_WIFI_RESP_CURRENT_RSSI +@return The function shall return M2M_SUCCESS for success and a negative value otherwise. +*/ +sint8 m2m_wifi_req_curr_rssi(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CURRENT_RSSI, NULL, 0, NULL,0, 0); + return ret; +} +sint8 m2m_wifi_send_ethernet_pkt(uint8* pu8Packet,uint16 u16PacketSize) +{ + sint8 s8Ret = -1; + if((pu8Packet != NULL)&&(u16PacketSize>0)) + { + tstrM2MWifiTxPacketInfo strTxPkt; + + strTxPkt.u16PacketSize = u16PacketSize; + strTxPkt.u16HeaderLength = M2M_ETHERNET_HDR_LEN; + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SEND_ETHERNET_PACKET | M2M_REQ_DATA_PKT, + (uint8*)&strTxPkt, sizeof(tstrM2MWifiTxPacketInfo), pu8Packet, u16PacketSize, M2M_ETHERNET_HDR_OFFSET - M2M_HIF_HDR_OFFSET); + } + return s8Ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); +@brief Request the MAC address stored on the OTP (one time programmable) memory of the device. + (the function is Blocking until response received) +@param [out] pu8MacAddr + Output MAC address buffer of 6 bytes size. Valid only if *pu8Valid=1. +@param [out] pu8IsValid + A output boolean value to indicate the validity of pu8MacAddr in OTP. + Output zero if the OTP memory is not programmed, non-zero otherwise. +@return The function shall return M2M_SUCCESS for success and a negative value otherwise. +@sa m2m_wifi_get_mac_address +@pre m2m_wifi_init required to call any WIFI/socket function +*/ +sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8* pu8IsValid) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_chip_wake(); + if(ret == M2M_SUCCESS) + { + ret = nmi_get_otp_mac_address(pu8MacAddr, pu8IsValid); + if(ret == M2M_SUCCESS) + { + ret = hif_chip_sleep(); + } + } + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr) +@brief Request the current MAC address of the device (the working mac address). + (the function is Blocking until response received) +@param [out] pu8MacAddr + Output MAC address buffer of 6 bytes size. +@return The function shall return M2M_SUCCESS for success and a negative value otherwise. +@sa m2m_wifi_get_otp_mac_address +@pre m2m_wifi_init required to call any WIFI/socket function +*/ +sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_chip_wake(); + if(ret == M2M_SUCCESS) + { + ret = nmi_get_mac_address(pu8MacAddr); + if(ret == M2M_SUCCESS) + { + ret = hif_chip_sleep(); + } + } + + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_req_scan_result(uint8 index); +@brief Reads the AP information from the Scan Result list with the given index, + the response received in wifi_cb M2M_WIFI_RESP_SCAN_RESULT, + the response pointer should be casted with tstrM2mWifiscanResult structure +@param [in] index + Index for the requested result, the index range start from 0 till number of AP's found +@sa tstrM2mWifiscanResult,m2m_wifi_get_num_ap_found,m2m_wifi_request_scan +@return The function shall return M2M_SUCCESE for success and a negative value otherwise +@pre m2m_wifi_request_scan need to be called first, then m2m_wifi_get_num_ap_found + to get the number of AP's found +@warning Function used only in STA mode only. the scan result updated only if scan request called, + else it will be cashed in firmware for the host scan request result, + which mean if large delay occur between the scan request and the scan result request, + the result will not be up-to-date +*/ + +sint8 m2m_wifi_req_scan_result(uint8 index) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mReqScanResult strReqScanRlt; + strReqScanRlt.u8Index = index; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SCAN_RESULT, (uint8*) &strReqScanRlt, sizeof(tstrM2mReqScanResult), NULL, 0, 0); + return ret; +} +/*! +@fn NMI_API uint8 m2m_wifi_get_num_ap_found(void); +@brief Reads the number of AP's found in the last Scan Request, + The function read the number of AP's from global variable which updated in the + wifi_cb in M2M_WIFI_RESP_SCAN_DONE. +@sa m2m_wifi_request_scan +@return Return the number of AP's found in the last Scan Request. +@pre m2m_wifi_request_scan need to be called first +@warning That function need to be called in the wifi_cb in M2M_WIFI_RESP_SCAN_DONE, + calling that function in any other place will return undefined/undated numbers. + Function used only in STA mode only. +*/ +uint8 m2m_wifi_get_num_ap_found(void) +{ + return gu8ChNum; +} +/*! +@fn NMI_API uint8 m2m_wifi_get_sleep_mode(void); +@brief Get the current Power save mode. +@return The current operating power saving mode. +@sa tenuPowerSaveModes , m2m_wifi_set_sleep_mode +*/ +uint8 m2m_wifi_get_sleep_mode(void) +{ + return hif_get_sleep_mode(); +} +/*! +@fn NMI_API sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn); +@brief Set the power saving mode for the WINC1500. +@param [in] PsTyp + Desired power saving mode. Supported types are defined in tenuPowerSaveModes. +@param [in] BcastEn + Broadcast reception enable flag. + If it is 1, the WINC1500 must be awake each DTIM Beacon for receiving Broadcast traffic. + If it is 0, the WINC1500 will not wakeup at the DTIM Beacon, but its wakeup depends only + on the the configured Listen Interval. +@return The function SHALL return 0 for success and a negative value otherwise. +@sa tenuPowerSaveModes +@warning The function called once after initialization. +*/ +sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mPsType strPs; + strPs.u8PsType = PsTyp; + strPs.u8BcastEn = BcastEn; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SLEEP, (uint8*) &strPs,sizeof(tstrM2mPsType), NULL, 0, 0); + M2M_INFO("POWER SAVE %d\n",PsTyp); + hif_set_sleep_mode(PsTyp); + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_request_sleep(void) +@brief Request from WINC1500 device to Sleep for specific time in the M2M_PS_MANUAL Power save mode (only). +@param [in] u32SlpReqTime + Request Sleep in ms +@return The function SHALL return M2M_SUCCESS for success and a negative value otherwise. +@sa tenuPowerSaveModes , m2m_wifi_set_sleep_mode +@warning the Function should be called in M2M_PS_MANUAL power save only +*/ +sint8 m2m_wifi_request_sleep(uint32 u32SlpReqTime) +{ + sint8 ret = M2M_SUCCESS; + uint8 psType; + psType = hif_get_sleep_mode(); + if(psType == M2M_PS_MANUAL) + { + tstrM2mSlpReqTime strPs; + strPs.u32SleepTime = u32SlpReqTime; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DOZE, (uint8*) &strPs,sizeof(tstrM2mSlpReqTime), NULL, 0, 0); + } + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength); +@brief Set the WINC1500 device name which is used as P2P device name. +@param [in] pu8DeviceName + Buffer holding the device name. +@param [in] u8DeviceNameLength + Length of the device name. +@return The function SHALL return M2M_SUCCESS for success and a negative value otherwise. +@warning The Function called once after initialization. +*/ +sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength) +{ + tstrM2MDeviceNameConfig strDeviceName; + if(u8DeviceNameLength >= M2M_DEVICE_NAME_MAX) + { + u8DeviceNameLength = M2M_DEVICE_NAME_MAX; + } + //pu8DeviceName[u8DeviceNameLength] = '\0'; + u8DeviceNameLength ++; + m2m_memcpy(strDeviceName.au8DeviceName, pu8DeviceName, u8DeviceNameLength); + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_DEVICE_NAME, + (uint8*)&strDeviceName, sizeof(tstrM2MDeviceNameConfig), NULL, 0,0); +} +sint8 m2m_wifi_get_firmware_version(tstrM2mRev *pstrRev) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_chip_wake(); + if(ret == M2M_SUCCESS) + { + ret = nm_get_firmware_full_info(pstrRev); + hif_chip_sleep(); + } + return ret; +} +#ifdef CONF_MGMT +sint8 m2m_wifi_enable_monitoring_mode(tstrM2MWifiMonitorModeCtrl *pstrMtrCtrl, uint8 *pu8PayloadBuffer, + uint16 u16BufferSize, uint16 u16DataOffset) +{ + sint8 s8Ret = -1; + if((pstrMtrCtrl->u8ChannelID >= M2M_WIFI_CH_1) && (pstrMtrCtrl->u8ChannelID <= M2M_WIFI_CH_14)) + { + gstrMgmtCtrl.pu8Buf = pu8PayloadBuffer; + gstrMgmtCtrl.u16Sz = u16BufferSize; + gstrMgmtCtrl.u16Offset = u16DataOffset; + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_MONITORING, + (uint8*)pstrMtrCtrl, sizeof(tstrM2MWifiMonitorModeCtrl), NULL, 0,0); + } + return s8Ret; +} + +sint8 m2m_wifi_disable_monitoring_mode(void) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_MONITORING, NULL, 0, NULL, 0,0); +} + +sint8 m2m_wifi_send_wlan_pkt(uint8 *pu8WlanPacket, uint16 u16WlanHeaderLength, uint16 u16WlanPktSize) +{ + sint8 s8Ret = -1; + if(pu8WlanPacket != NULL) + { + tstrM2MWifiTxPacketInfo strTxPkt; + + strTxPkt.u16PacketSize = u16WlanPktSize; + strTxPkt.u16HeaderLength = u16WlanHeaderLength; + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SEND_WIFI_PACKET | M2M_REQ_DATA_PKT, + (uint8*)&strTxPkt, sizeof(tstrM2MWifiTxPacketInfo), pu8WlanPacket, u16WlanPktSize, sizeof(tstrM2MWifiTxPacketInfo)); + } + return s8Ret; +} +#endif + +sint8 m2m_wifi_start_provision_mode(tstrM2MAPConfig *pstrAPConfig, char *pcHttpServerDomainName, uint8 bEnableHttpRedirect) +{ + sint8 s8Ret = M2M_ERR_FAIL; + + if((pstrAPConfig != NULL)) + { + tstrM2MProvisionModeConfig strProvConfig; + if(M2M_SUCCESS == m2m_validate_ap_parameters(pstrAPConfig)) + { + m2m_memcpy((uint8*)&strProvConfig.strApConfig, (uint8*)pstrAPConfig, sizeof(tstrM2MAPConfig)); + if((m2m_strlen((uint8 *)pcHttpServerDomainName) <= 0) || (NULL == pcHttpServerDomainName)) + { + M2M_ERR("INVALID DOMAIN NAME\n"); + goto ERR1; + } + m2m_memcpy((uint8*)strProvConfig.acHttpServerDomainName, (uint8*)pcHttpServerDomainName, 64); + strProvConfig.u8EnableRedirect = bEnableHttpRedirect; + + /* Stop Scan if it is ongoing. + */ + gu8scanInProgress = 0; +#ifdef ARDUINO + extern uint32 nmdrv_firm_ver; + uint16 txSize = sizeof(tstrM2MProvisionModeConfig); + + if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 5, 0)) { + // for backwards compat with firmwware 19.4.x and older + // (listen channel is 0 based, there is no au8Key field) + strProvConfig.strApConfig.u8ListenChannel--; + txSize -= sizeof(strProvConfig.strApConfig.au8Key) + 1; + m2m_memcpy((uint8*)&strProvConfig.strApConfig.au8Key[3], (uint8*)pcHttpServerDomainName, 64); + uint8* pu8EnableRedirect = (uint8*)strProvConfig.strApConfig.au8Key; + pu8EnableRedirect[3 + 64] = bEnableHttpRedirect; + } + + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_START_PROVISION_MODE | M2M_REQ_DATA_PKT, + (uint8*)&strProvConfig, txSize, NULL, 0, 0); +#else + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_START_PROVISION_MODE | M2M_REQ_DATA_PKT, + (uint8*)&strProvConfig, sizeof(tstrM2MProvisionModeConfig), NULL, 0, 0); +#endif + } + else + { + /*goto ERR1;*/ + } + } +ERR1: + return s8Ret; +} + +sint8 m2m_wifi_stop_provision_mode(void) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_STOP_PROVISION_MODE, NULL, 0, NULL, 0, 0); +} + +sint8 m2m_wifi_get_connection_info(void) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_GET_CONN_INFO, NULL, 0, NULL, 0, 0); +} + +sint8 m2m_wifi_set_sytem_time(uint32 u32UTCSeconds) +{ + /* + The firmware accepts timestamps relative to 1900 like NTP Timestamp. + */ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_SYS_TIME, (uint8*)&u32UTCSeconds, sizeof(tstrSystemTime), NULL, 0, 0); +} +/*! + * @fn NMI_API sint8 m2m_wifi_get_sytem_time(void); + * @see m2m_wifi_enable_sntp + tstrSystemTime + * @note get the system time from the sntp client + * using the API \ref m2m_wifi_get_sytem_time. + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +sint8 m2m_wifi_get_sytem_time(void) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_GET_SYS_TIME, NULL,0, NULL, 0, 0); +} + +sint8 m2m_wifi_enable_sntp(uint8 bEnable) +{ + uint8 u8Req; + + u8Req = bEnable ? M2M_WIFI_REQ_ENABLE_SNTP_CLIENT : M2M_WIFI_REQ_DISABLE_SNTP_CLIENT; + return hif_send(M2M_REQ_GROUP_WIFI, u8Req, NULL, 0, NULL, 0, 0); +} +/*! +@fn NMI_API sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode); +@brief Change the power profile mode +@param [in] u8PwrMode + Change the WINC power profile to different mode + PWR_LOW1/PWR_LOW2/PWR_HIGH/PWR_AUTO (tenuM2mPwrMode) +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. +@sa tenuM2mPwrMode +@pre m2m_wifi_init +@warning must be called after the initializations and before any connection request and can't be changed in run time, +*/ +sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mPwrMode strM2mPwrMode; + strM2mPwrMode.u8PwrMode = u8PwrMode; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_POWER_PROFILE, (uint8*)&strM2mPwrMode,sizeof(tstrM2mPwrMode), NULL, 0, 0); + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel); +@brief set the TX power tenuM2mTxPwrLevel +@param [in] u8TxPwrLevel + change the TX power tenuM2mTxPwrLevel +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. +@sa tenuM2mTxPwrLevel +@pre m2m_wifi_init +@warning +*/ +sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mTxPwrLevel strM2mTxPwrLevel; + strM2mTxPwrLevel.u8TxPwrLevel = u8TxPwrLevel; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_TX_POWER, (uint8*)&strM2mTxPwrLevel,sizeof(tstrM2mTxPwrLevel), NULL, 0, 0); + return ret; +} + +/*! +@fn NMI_API sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable); +@brief Enable or Disable logs in run time (Disable Firmware logs will + enhance the firmware start-up time and performance) +@param [in] u8Enable + Set 1 to enable the logs 0 for disable +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. +@sa __DISABLE_FIRMWARE_LOGS__ (build option to disable logs from initializations) +@pre m2m_wifi_init +@warning +*/ +sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mEnableLogs strM2mEnableLogs; + strM2mEnableLogs.u8Enable = u8Enable; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_ENABLE_LOGS, (uint8*)&strM2mEnableLogs,sizeof(tstrM2mEnableLogs), NULL, 0, 0); + return ret; +} + +/*! +@fn NMI_API sint8 m2m_wifi_set_battery_voltage(uint16 u16BattVoltx100); +@brief Enable or Disable logs in run time (Disable Firmware logs will + enhance the firmware start-up time and performance) +@param [in] u16BattVoltx100 + battery voltage multiplied by 100 +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. +@sa __DISABLE_FIRMWARE_LOGS__ (build option to disable logs from initializations) +@pre m2m_wifi_init +@warning +*/ +sint8 m2m_wifi_set_battery_voltage(uint16 u16BattVoltx100) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mBatteryVoltage strM2mBattVol = {0}; + strM2mBattVol.u16BattVolt = u16BattVoltx100; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_BATTERY_VOLTAGE, (uint8*)&strM2mBattVol,sizeof(tstrM2mBatteryVoltage), NULL, 0, 0); + return ret; +} +/*! +@fn sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PrngBuff,uint16 u16PrngSize) +@brief Get random bytes using the PRNG bytes. +@param [in] u16PrngSize + Size of the required random bytes to be generated. +@param [in] pu8PrngBuff + Pointer to user allocated buffer. +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. +*/ +sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PrngBuff,uint16 u16PrngSize) +{ + sint8 ret = M2M_ERR_FAIL; + tstrPrng strRng = {0}; + if((u16PrngSize < (M2M_BUFFER_MAX_SIZE - sizeof(tstrPrng)))&&(pu8PrngBuff != NULL)) + { + strRng.u16PrngSize = u16PrngSize; + strRng.pu8RngBuff = pu8PrngBuff; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_GET_PRNG|M2M_REQ_DATA_PKT,(uint8 *)&strRng, sizeof(tstrPrng),NULL,0, 0); + } + else + { + M2M_ERR("PRNG Buffer exceeded maximum size %d or NULL Buffer\n",u16PrngSize); + } + return ret; +} +#ifdef ETH_MODE +/*! +@fn \ + NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8* pu8MulticastMacAddress, uint8 u8AddRemove) + +@brief + Add MAC filter to receive Multicast packets. + +@param [in] pu8MulticastMacAddress + Pointer to the MAC address. +@param [in] u8AddRemove + Flag to Add/Remove MAC address. +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ + +NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8* pu8MulticastMacAddress, uint8 u8AddRemove) +{ + sint8 s8ret = M2M_ERR_FAIL; + tstrM2MMulticastMac strMulticastMac; + + if(pu8MulticastMacAddress != NULL ) + { + strMulticastMac.u8AddRemove = u8AddRemove; + m2m_memcpy(strMulticastMac.au8macaddress,pu8MulticastMacAddress,M2M_MAC_ADDRES_LEN); + M2M_DBG("mac multicast: %x:%x:%x:%x:%x:%x\r\n",strMulticastMac.au8macaddress[0],strMulticastMac.au8macaddress[1],strMulticastMac.au8macaddress[2],strMulticastMac.au8macaddress[3],strMulticastMac.au8macaddress[4],strMulticastMac.au8macaddress[5]); + s8ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_MAC_MCAST, (uint8 *)&strMulticastMac,sizeof(tstrM2MMulticastMac),NULL,0,0); + } + + return s8ret; + +} + +/*! +@fn \ + NMI_API sint8 m2m_wifi_set_receive_buffer(void* pvBuffer,uint16 u16BufferLen); + +@brief + set the ethernet receive buffer, should be called in the receive call back. + +@param [in] pvBuffer + Pointer to the ethernet receive buffer. +@param [in] u16BufferLen + Length of the buffer. + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_set_receive_buffer(void* pvBuffer,uint16 u16BufferLen) +{ + sint8 s8ret = M2M_SUCCESS; + if(pvBuffer != NULL) + { + gau8ethRcvBuf = pvBuffer; + gu16ethRcvBufSize= u16BufferLen; + } + else + { + s8ret = M2M_ERR_FAIL; + M2M_ERR("Buffer NULL pointer\r\n"); + } + return s8ret; +} +#endif /* ETH_MODE */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmasic.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmasic.c new file mode 100644 index 0000000..91c0e5a --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmasic.c @@ -0,0 +1,688 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 ASIC specific internal APIs. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "common/include/nm_common.h" +#include "driver/source/nmbus.h" +#include "bsp/include/nm_bsp.h" +#include "driver/source/nmasic.h" +#include "driver/include/m2m_types.h" + +#define NMI_GLB_RESET_0 (NMI_PERIPH_REG_BASE + 0x400) +#define NMI_INTR_REG_BASE (NMI_PERIPH_REG_BASE + 0xa00) +#define NMI_PIN_MUX_0 (NMI_PERIPH_REG_BASE + 0x408) +#define NMI_INTR_ENABLE (NMI_INTR_REG_BASE) +#define GET_UINT32(X,Y) (X[0+Y] + ((uint32)X[1+Y]<<8) + ((uint32)X[2+Y]<<16) +((uint32)X[3+Y]<<24)) + +/*SPI and I2C only*/ +#define CORT_HOST_COMM (0x10) +#define HOST_CORT_COMM (0x0b) +#define WAKE_CLK_REG (0x1) +#define CLOCKS_EN_REG (0xf) + + + +#ifdef ARDUINO +#define TIMEOUT (2000) +#else +#define TIMEOUT (0xfffffffful) +#endif +#define WAKUP_TRAILS_TIMEOUT (4) + +sint8 chip_apply_conf(uint32 u32Conf) +{ + sint8 ret = M2M_SUCCESS; + uint32 val32 = u32Conf; + +#if (defined __ENABLE_PMU__) || (defined CONF_WINC_INT_PMU) + val32 |= rHAVE_USE_PMU_BIT; +#endif +#ifdef __ENABLE_SLEEP_CLK_SRC_RTC__ + val32 |= rHAVE_SLEEP_CLK_SRC_RTC_BIT; +#elif defined __ENABLE_SLEEP_CLK_SRC_XO__ + val32 |= rHAVE_SLEEP_CLK_SRC_XO_BIT; +#endif +#ifdef __ENABLE_EXT_PA_INV_TX_RX__ + val32 |= rHAVE_EXT_PA_INV_TX_RX; +#endif +#ifdef __ENABLE_LEGACY_RF_SETTINGS__ + val32 |= rHAVE_LEGACY_RF_SETTINGS; +#endif +#ifdef __DISABLE_FIRMWARE_LOGS__ + val32 |= rHAVE_LOGS_DISABLED_BIT; +#endif + + val32 |= rHAVE_RESERVED1_BIT; + do { + nm_write_reg(rNMI_GP_REG_1, val32); + if(val32 != 0) { + uint32 reg = 0; + ret = nm_read_reg_with_ret(rNMI_GP_REG_1, ®); + if(ret == M2M_SUCCESS) { + if(reg == val32) + break; + } + } else { + break; + } + } while(1); + + return M2M_SUCCESS; +} +void chip_idle(void) +{ + uint32 reg = 0; + nm_read_reg_with_ret(WAKE_CLK_REG, ®); + if(reg & NBIT1) + { + reg &=~ NBIT1; + nm_write_reg(WAKE_CLK_REG, reg); + } +} + +sint8 enable_interrupts(void) +{ + uint32 reg = 0; + sint8 ret = M2M_SUCCESS; + /** + interrupt pin mux select + **/ + ret = nm_read_reg_with_ret(NMI_PIN_MUX_0, ®); + if (M2M_SUCCESS != ret) goto ERR1; + + reg |= ((uint32) 1 << 8); + ret = nm_write_reg(NMI_PIN_MUX_0, reg); + if (M2M_SUCCESS != ret) goto ERR1; + + /** + interrupt enable + **/ + ret = nm_read_reg_with_ret(NMI_INTR_ENABLE, ®); + if (M2M_SUCCESS != ret) goto ERR1; + + reg |= ((uint32) 1 << 16); + ret = nm_write_reg(NMI_INTR_ENABLE, reg); + if (M2M_SUCCESS != ret) goto ERR1; +ERR1: + return ret; +} + +sint8 cpu_start(void) { + uint32 reg = 0; + sint8 ret; + + /** + reset regs + */ + ret = nm_write_reg(BOOTROM_REG,0); + ret += nm_write_reg(NMI_STATE_REG,0); + ret += nm_write_reg(NMI_REV_REG,0); + /** + Go... + **/ + ret += nm_read_reg_with_ret(0x1118, ®); + reg |= (1 << 0); + ret += nm_write_reg(0x1118, reg); + ret += nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); + if ((reg & (1ul << 10)) == (1ul << 10)) { + reg &= ~(1ul << 10); + ret += nm_write_reg(NMI_GLB_RESET_0, reg); + } + reg |= (1ul << 10); + ret += nm_write_reg(NMI_GLB_RESET_0, reg); + nm_bsp_sleep(1); + return ret; +} + +uint32 nmi_get_chipid(void) +{ + static uint32 chipid = 0; + + if (chipid == 0) { + uint32 rfrevid; + + if((nm_read_reg_with_ret(0x1000, &chipid)) != M2M_SUCCESS) { + chipid = 0; + return 0; + } + //if((ret = nm_read_reg_with_ret(0x11fc, &revid)) != M2M_SUCCESS) { + // return 0; + //} + if((nm_read_reg_with_ret(0x13f4, &rfrevid)) != M2M_SUCCESS) { + chipid = 0; + return 0; + } + + if (chipid == 0x1002a0) { + if (rfrevid == 0x1) { /* 1002A0 */ + } else /* if (rfrevid == 0x2) */ { /* 1002A1 */ + chipid = 0x1002a1; + } + } else if(chipid == 0x1002b0) { + if(rfrevid == 3) { /* 1002B0 */ + } else if(rfrevid == 4) { /* 1002B1 */ + chipid = 0x1002b1; + } else /* if(rfrevid == 5) */ { /* 1002B2 */ + chipid = 0x1002b2; + } + }else if(chipid == 0x1000F0) { + if((nm_read_reg_with_ret(0x3B0000, &chipid)) != M2M_SUCCESS) { + chipid = 0; + return 0; + } + }else { + + } +//#define PROBE_FLASH +#ifdef PROBE_FLASH + if(chipid) { + UWORD32 flashid; + + flashid = probe_spi_flash(); + if(flashid == 0x1230ef) { + chipid &= ~(0x0f0000); + chipid |= 0x050000; + } + if(flashid == 0xc21320c2) { + chipid &= ~(0x0f0000); + chipid |= 0x050000; + } + } +#else + /*M2M is by default have SPI flash*/ + chipid &= ~(0x0f0000); + chipid |= 0x050000; +#endif /* PROBE_FLASH */ + } + return chipid; +} + +uint32 nmi_get_rfrevid(void) +{ + uint32 rfrevid; + if((nm_read_reg_with_ret(0x13f4, &rfrevid)) != M2M_SUCCESS) { + rfrevid = 0; + return 0; + } + return rfrevid; +} + +void restore_pmu_settings_after_global_reset(void) +{ + /* + * Must restore PMU register value after + * global reset if PMU toggle is done at + * least once since the last hard reset. + */ + if(REV(nmi_get_chipid()) >= REV_2B0) { + nm_write_reg(0x1e48, 0xb78469ce); + } +} + +void nmi_update_pll(void) +{ + uint32 pll; + + pll = nm_read_reg(0x1428); + pll &= ~0x1ul; + nm_write_reg(0x1428, pll); + pll |= 0x1ul; + nm_write_reg(0x1428, pll); + +} +void nmi_set_sys_clk_src_to_xo(void) +{ + uint32 val32; + + /* Switch system clock source to XO. This will take effect after nmi_update_pll(). */ + val32 = nm_read_reg(0x141c); + val32 |= (1 << 2); + nm_write_reg(0x141c, val32); + + /* Do PLL update */ + nmi_update_pll(); +} +sint8 chip_sleep(void) +{ + uint32 reg; + sint8 ret = M2M_SUCCESS; + + while(1) + { + ret = nm_read_reg_with_ret(CORT_HOST_COMM,®); + if(ret != M2M_SUCCESS) goto ERR1; + if((reg & NBIT0) == 0) break; + } + + /* Clear bit 1 */ + ret = nm_read_reg_with_ret(WAKE_CLK_REG, ®); + if(ret != M2M_SUCCESS)goto ERR1; + if(reg & NBIT1) + { + reg &=~NBIT1; + ret = nm_write_reg(WAKE_CLK_REG, reg); + if(ret != M2M_SUCCESS)goto ERR1; + } + + ret = nm_read_reg_with_ret(HOST_CORT_COMM, ®); + if(ret != M2M_SUCCESS)goto ERR1; + if(reg & NBIT0) + { + reg &= ~NBIT0; + ret = nm_write_reg(HOST_CORT_COMM, reg); + if(ret != M2M_SUCCESS)goto ERR1; + } + +ERR1: + return ret; +} +sint8 chip_wake(void) +{ + sint8 ret = M2M_SUCCESS; + uint32 reg = 0, clk_status_reg = 0,trials = 0; + + ret = nm_read_reg_with_ret(HOST_CORT_COMM, ®); + if(ret != M2M_SUCCESS)goto _WAKE_EXIT; + + if(!(reg & NBIT0)) + { + /*USE bit 0 to indicate host wakeup*/ + ret = nm_write_reg(HOST_CORT_COMM, reg|NBIT0); + if(ret != M2M_SUCCESS)goto _WAKE_EXIT; + } + + ret = nm_read_reg_with_ret(WAKE_CLK_REG, ®); + if(ret != M2M_SUCCESS)goto _WAKE_EXIT; + /* Set bit 1 */ + if(!(reg & NBIT1)) + { + ret = nm_write_reg(WAKE_CLK_REG, reg | NBIT1); + if(ret != M2M_SUCCESS) goto _WAKE_EXIT; + } + + do + { + ret = nm_read_reg_with_ret(CLOCKS_EN_REG, &clk_status_reg); + if(ret != M2M_SUCCESS) { + M2M_ERR("Bus error (5).%d %lx\n",ret,clk_status_reg); + goto _WAKE_EXIT; + } + if(clk_status_reg & NBIT2) { + break; + } + nm_bsp_sleep(2); + trials++; + if(trials > WAKUP_TRAILS_TIMEOUT) + { + M2M_ERR("Failed to wakup the chip\n"); + ret = M2M_ERR_TIME_OUT; + goto _WAKE_EXIT; + } + }while(1); + + /*workaround sometimes spi fail to read clock regs after reading/writing clockless registers*/ + nm_bus_reset(); + +_WAKE_EXIT: + return ret; +} +sint8 cpu_halt(void) +{ + sint8 ret; + uint32 reg = 0; + ret = nm_read_reg_with_ret(0x1118, ®); + reg |= (1 << 0); + ret += nm_write_reg(0x1118, reg); + ret += nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); + if ((reg & (1ul << 10)) == (1ul << 10)) { + reg &= ~(1ul << 10); + ret += nm_write_reg(NMI_GLB_RESET_0, reg); + ret += nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); + } + return ret; +} +sint8 chip_reset_and_cpu_halt(void) +{ + sint8 ret = M2M_SUCCESS; + + /*Wakeup needed only for I2C interface*/ + ret = chip_wake(); + if(ret != M2M_SUCCESS) goto ERR1; + /*Reset and CPU halt need for no wait board only*/ + ret = chip_reset(); + if(ret != M2M_SUCCESS) goto ERR1; + ret = cpu_halt(); + if(ret != M2M_SUCCESS) goto ERR1; +ERR1: + return ret; +} +sint8 chip_reset(void) +{ + sint8 ret = M2M_SUCCESS; + ret = nm_write_reg(NMI_GLB_RESET_0, 0); + nm_bsp_sleep(50); + return ret; +} + +sint8 wait_for_bootrom(uint8 arg) +{ + sint8 ret = M2M_SUCCESS; + uint32 reg = 0, cnt = 0; + uint32 u32GpReg1 = 0; + uint32 u32DriverVerInfo = M2M_MAKE_VERSION_INFO(M2M_RELEASE_VERSION_MAJOR_NO,\ + M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO,\ + M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO,\ + M2M_RELEASE_VERSION_PATCH_NO); + + + reg = 0; + while(1) { + reg = nm_read_reg(0x1014); /* wait for efuse loading done */ + if (reg & 0x80000000) { + break; + } + nm_bsp_sleep(1); /* TODO: Why bus error if this delay is not here. */ + } + reg = nm_read_reg(M2M_WAIT_FOR_HOST_REG); + reg &= 0x1; + + /* check if waiting for the host will be skipped or not */ + if(reg == 0) + { + reg = 0; + while(reg != M2M_FINISH_BOOT_ROM) + { + nm_bsp_sleep(1); + reg = nm_read_reg(BOOTROM_REG); + + if(++cnt > TIMEOUT) + { + M2M_DBG("failed to load firmware from flash.\n"); + ret = M2M_ERR_INIT; + goto ERR2; + } + } + } + + if(M2M_WIFI_MODE_ATE_HIGH == arg) { + nm_write_reg(NMI_REV_REG, M2M_ATE_FW_START_VALUE); + nm_write_reg(NMI_STATE_REG, NBIT20); + }else if(M2M_WIFI_MODE_ATE_LOW == arg) { + nm_write_reg(NMI_REV_REG, M2M_ATE_FW_START_VALUE); + nm_write_reg(NMI_STATE_REG, 0); + }else if(M2M_WIFI_MODE_ETHERNET == arg){ + u32GpReg1 = rHAVE_ETHERNET_MODE_BIT; + nm_write_reg(NMI_STATE_REG, u32DriverVerInfo); + } else { + /*bypass this step*/ + nm_write_reg(NMI_STATE_REG, u32DriverVerInfo); + } + + if(REV(nmi_get_chipid()) >= REV_3A0){ + chip_apply_conf(u32GpReg1 | rHAVE_USE_PMU_BIT); + } else { + chip_apply_conf(u32GpReg1); + } + M2M_INFO("DriverVerInfo: 0x%08lx\n",u32DriverVerInfo); + + nm_write_reg(BOOTROM_REG,M2M_START_FIRMWARE); + +#ifdef __ROM_TEST__ + rom_test(); +#endif /* __ROM_TEST__ */ + +ERR2: + return ret; +} + +sint8 wait_for_firmware_start(uint8 arg) +{ + sint8 ret = M2M_SUCCESS; + uint32 reg = 0, cnt = 0; + uint32 u32Timeout = TIMEOUT; + volatile uint32 regAddress = NMI_STATE_REG; + volatile uint32 checkValue = M2M_FINISH_INIT_STATE; + + if((M2M_WIFI_MODE_ATE_HIGH == arg)||(M2M_WIFI_MODE_ATE_LOW == arg)) { + regAddress = NMI_REV_REG; + checkValue = M2M_ATE_FW_IS_UP_VALUE; + } else { + /*bypass this step*/ + } + + + while (checkValue != reg) + { + nm_bsp_sleep(2); /* TODO: Why bus error if this delay is not here. */ + M2M_DBG("%x %x %x\n",(unsigned int)nm_read_reg(0x108c),(unsigned int)nm_read_reg(0x108c),(unsigned int)nm_read_reg(0x14A0)); + reg = nm_read_reg(regAddress); + if(++cnt >= u32Timeout) + { + M2M_DBG("Time out for wait firmware Run\n"); + ret = M2M_ERR_INIT; + goto ERR; + } + } + if(M2M_FINISH_INIT_STATE == checkValue) + { + nm_write_reg(NMI_STATE_REG, 0); + } +ERR: + return ret; +} + +sint8 chip_deinit(void) +{ + uint32 reg = 0; + sint8 ret; + + /** + stop the firmware, need a re-download + **/ + ret = nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); + if (ret != M2M_SUCCESS) { + M2M_ERR("failed to de-initialize\n"); + goto ERR1; + } + reg &= ~(1 << 10); + ret = nm_write_reg(NMI_GLB_RESET_0, reg); + if (ret != M2M_SUCCESS) { + M2M_ERR("failed to de-initialize\n"); + goto ERR1; + } + +ERR1: + return ret; +} + +#ifdef CONF_PERIPH + +sint8 set_gpio_dir(uint8 gpio, uint8 dir) +{ + uint32 val32; + sint8 ret; + + ret = nm_read_reg_with_ret(0x20108, &val32); + if(ret != M2M_SUCCESS) goto _EXIT; + + if(dir) { + val32 |= (1ul << gpio); + } else { + val32 &= ~(1ul << gpio); + } + + ret = nm_write_reg(0x20108, val32); + +_EXIT: + return ret; +} +sint8 set_gpio_val(uint8 gpio, uint8 val) +{ + uint32 val32; + sint8 ret; + + ret = nm_read_reg_with_ret(0x20100, &val32); + if(ret != M2M_SUCCESS) goto _EXIT; + + if(val) { + val32 |= (1ul << gpio); + } else { + val32 &= ~(1ul << gpio); + } + + ret = nm_write_reg(0x20100, val32); + +_EXIT: + return ret; +} + +sint8 get_gpio_val(uint8 gpio, uint8* val) +{ + uint32 val32; + sint8 ret; + + ret = nm_read_reg_with_ret(0x20104, &val32); + if(ret != M2M_SUCCESS) goto _EXIT; + + *val = (uint8)((val32 >> gpio) & 0x01); + +_EXIT: + return ret; +} + +sint8 pullup_ctrl(uint32 pinmask, uint8 enable) +{ + sint8 s8Ret; + uint32 val32; + s8Ret = nm_read_reg_with_ret(0x142c, &val32); + if(s8Ret != M2M_SUCCESS) { + M2M_ERR("[pullup_ctrl]: failed to read\n"); + goto _EXIT; + } + if(enable) { + val32 &= ~pinmask; + } else { + val32 |= pinmask; + } + s8Ret = nm_write_reg(0x142c, val32); + if(s8Ret != M2M_SUCCESS) { + M2M_ERR("[pullup_ctrl]: failed to write\n"); + goto _EXIT; + } +_EXIT: + return s8Ret; +} +#endif /* CONF_PERIPH */ + +sint8 nmi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid) +{ + sint8 ret; + uint32 u32RegValue; + uint8 mac[6]; + tstrGpRegs strgp = {0}; + + ret = nm_read_reg_with_ret(rNMI_GP_REG_2, &u32RegValue); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; +#ifdef ARDUINO + if (u32RegValue) { + ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; + u32RegValue = strgp.u32Mac_efuse_mib; + } else { + // firmware version 19.3.0 + ret = nm_read_reg_with_ret(rNMI_GP_REG_0, &u32RegValue); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; + } +#else + ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; + u32RegValue = strgp.u32Mac_efuse_mib; +#endif + if(!EFUSED_MAC(u32RegValue)) { + M2M_DBG("Default MAC\n"); + m2m_memset(pu8MacAddr, 0, 6); + goto _EXIT_ERR; + } + + M2M_DBG("OTP MAC\n"); + u32RegValue >>=16; + ret = nm_read_block(u32RegValue|0x30000, mac, 6); + m2m_memcpy(pu8MacAddr,mac,6); + if(pu8IsValid) *pu8IsValid = 1; + return ret; + +_EXIT_ERR: + if(pu8IsValid) *pu8IsValid = 0; + return ret; +} + +sint8 nmi_get_mac_address(uint8 *pu8MacAddr) +{ + sint8 ret; + uint32 u32RegValue; + uint8 mac[6]; + tstrGpRegs strgp = {0}; + + ret = nm_read_reg_with_ret(rNMI_GP_REG_2, &u32RegValue); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; +#ifdef ARDUINO + if (u32RegValue) { + ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; + u32RegValue = strgp.u32Mac_efuse_mib; + } else { + // firmware version 19.3.0 + ret = nm_read_reg_with_ret(rNMI_GP_REG_0, &u32RegValue); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; + } +#else + ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; + u32RegValue = strgp.u32Mac_efuse_mib; +#endif + u32RegValue &=0x0000ffff; + ret = nm_read_block(u32RegValue|0x30000, mac, 6); + m2m_memcpy(pu8MacAddr, mac, 6); + + return ret; + +_EXIT_ERR: + return ret; +} diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmasic.h b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmasic.h new file mode 100644 index 0000000..84a395b --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmasic.h @@ -0,0 +1,215 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 ASIC specific internal APIs. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +#ifndef _NMASIC_H_ +#define _NMASIC_H_ + +#include "common/include/nm_common.h" + +#define NMI_PERIPH_REG_BASE 0x1000 +#define NMI_CHIPID (NMI_PERIPH_REG_BASE) +#define rNMI_GP_REG_0 (0x149c) +#define rNMI_GP_REG_1 (0x14A0) +#define rNMI_GP_REG_2 (0xc0008) +#define rNMI_GLB_RESET (0x1400) +#define rNMI_BOOT_RESET_MUX (0x1118) +#define NMI_STATE_REG (0x108c) +#define BOOTROM_REG (0xc000c) +#define NMI_REV_REG (0x207ac) /*Also, Used to load ATE firmware from SPI Flash and to ensure that it is running too*/ +#define NMI_REV_REG_ATE (0x1048) /*Revision info register in case of ATE FW*/ +#define M2M_WAIT_FOR_HOST_REG (0x207bc) +#define M2M_FINISH_INIT_STATE 0x02532636UL +#define M2M_FINISH_BOOT_ROM 0x10add09eUL +#define M2M_START_FIRMWARE 0xef522f61UL +#define M2M_START_PS_FIRMWARE 0x94992610UL + +#define M2M_ATE_FW_START_VALUE (0x3C1CD57D) /*Also, Change this value in boot_firmware if it will be changed here*/ +#define M2M_ATE_FW_IS_UP_VALUE (0xD75DC1C3) /*Also, Change this value in ATE (Burst) firmware if it will be changed here*/ + +#define REV_2B0 (0x2B0) +#define REV_B0 (0x2B0) +#define REV_3A0 (0x3A0) +#define GET_CHIPID() nmi_get_chipid() +#define ISNMC1000(id) ((((id) & 0xfffff000) == 0x100000) ? 1 : 0) +#define ISNMC1500(id) ((((id) & 0xfffff000) == 0x150000) ? 1 : 0) +#define ISNMC3000(id) ((((id) & 0xfff00000) == 0x300000) ? 1 : 0) +#define REV(id) (((id) & 0x00000fff )) +#define EFUSED_MAC(value) (value & 0xffff0000) + +#define rHAVE_SDIO_IRQ_GPIO_BIT (NBIT0) +#define rHAVE_USE_PMU_BIT (NBIT1) +#define rHAVE_SLEEP_CLK_SRC_RTC_BIT (NBIT2) +#define rHAVE_SLEEP_CLK_SRC_XO_BIT (NBIT3) +#define rHAVE_EXT_PA_INV_TX_RX (NBIT4) +#define rHAVE_LEGACY_RF_SETTINGS (NBIT5) +#define rHAVE_LOGS_DISABLED_BIT (NBIT6) +#define rHAVE_ETHERNET_MODE_BIT (NBIT7) +#define rHAVE_RESERVED1_BIT (NBIT8) + +typedef struct{ + uint32 u32Mac_efuse_mib; + uint32 u32Firmware_Ota_rev; +}tstrGpRegs; + +#ifdef __cplusplus + extern "C" { +#endif + +/* +* @fn cpu_halt +* @brief +*/ +sint8 cpu_halt(void); +/* +* @fn chip_sleep +* @brief +*/ +sint8 chip_sleep(void); +/* +* @fn chip_wake +* @brief +*/ +sint8 chip_wake(void); +/* +* @fn chip_idle +* @brief +*/ +void chip_idle(void); +/* +* @fn enable_interrupts +* @brief +*/ +sint8 enable_interrupts(void); +/* +* @fn cpu_start +* @brief +*/ +sint8 cpu_start(void); +/* +* @fn nmi_get_chipid +* @brief +*/ +uint32 nmi_get_chipid(void); +/* +* @fn nmi_get_rfrevid +* @brief +*/ +uint32 nmi_get_rfrevid(void); +/* +* @fn restore_pmu_settings_after_global_reset +* @brief +*/ +void restore_pmu_settings_after_global_reset(void); +/* +* @fn nmi_update_pll +* @brief +*/ +void nmi_update_pll(void); +/* +* @fn nmi_set_sys_clk_src_to_xo +* @brief +*/ +void nmi_set_sys_clk_src_to_xo(void); +/* +* @fn chip_reset +* @brief +*/ +sint8 chip_reset(void); +/* +* @fn wait_for_bootrom +* @brief +*/ +sint8 wait_for_bootrom(uint8); +/* +* @fn wait_for_firmware_start +* @brief +*/ +sint8 wait_for_firmware_start(uint8); +/* +* @fn chip_deinit +* @brief +*/ +sint8 chip_deinit(void); +/* +* @fn chip_reset_and_cpu_halt +* @brief +*/ +sint8 chip_reset_and_cpu_halt(void); +/* +* @fn set_gpio_dir +* @brief +*/ +sint8 set_gpio_dir(uint8 gpio, uint8 dir); +/* +* @fn set_gpio_val +* @brief +*/ +sint8 set_gpio_val(uint8 gpio, uint8 val); +/* +* @fn get_gpio_val +* @brief +*/ +sint8 get_gpio_val(uint8 gpio, uint8* val); +/* +* @fn pullup_ctrl +* @brief +*/ +sint8 pullup_ctrl(uint32 pinmask, uint8 enable); +/* +* @fn nmi_get_otp_mac_address +* @brief +*/ +sint8 nmi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); +/* +* @fn nmi_get_mac_address +* @brief +*/ +sint8 nmi_get_mac_address(uint8 *pu8MacAddr); +/* +* @fn chip_apply_conf +* @brief +*/ +sint8 chip_apply_conf(uint32 u32conf); + +#ifdef __cplusplus + } +#endif + +#endif /*_NMASIC_H_*/ diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmbus.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmbus.c new file mode 100644 index 0000000..d001d72 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmbus.c @@ -0,0 +1,301 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 bus APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +#ifndef CORTUS_APP + +#include "nmbus.h" +#include "nmi2c.h" +#include "nmspi.h" +#include "nmuart.h" + +#define MAX_TRX_CFG_SZ 8 + +/** +* @fn nm_bus_iface_init +* @brief Initialize bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_bus_iface_init(void *pvInitVal) +{ + sint8 ret = M2M_SUCCESS; + ret = nm_bus_init(pvInitVal); + return ret; +} + +/** +* @fn nm_bus_iface_deinit +* @brief Deinitialize bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Samer Sarhan +* @date 07 April 2014 +* @version 1.0 +*/ +sint8 nm_bus_iface_deinit(void) +{ + sint8 ret = M2M_SUCCESS; + ret = nm_bus_deinit(); + + return ret; +} + +/** +* @fn nm_bus_reset +* @brief reset bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @version 1.0 +*/ +sint8 nm_bus_reset(void) +{ + sint8 ret = M2M_SUCCESS; +#ifdef CONF_WINC_USE_UART +#elif defined (CONF_WINC_USE_SPI) + return nm_spi_reset(); +#elif defined (CONF_WINC_USE_I2C) +#else +#error "Plesae define bus usage" +#endif + + return ret; +} + +/** +* @fn nm_bus_iface_reconfigure +* @brief reconfigure bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Viswanathan Murugesan +* @date 22 Oct 2014 +* @version 1.0 +*/ +sint8 nm_bus_iface_reconfigure(void *ptr) +{ +#ifdef ARDUINO + (void)ptr; // Silence "unused" warning +#endif + sint8 ret = M2M_SUCCESS; +#ifdef CONF_WINC_USE_UART + ret = nm_uart_reconfigure(ptr); +#endif + return ret; +} +/* +* @fn nm_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +uint32 nm_read_reg(uint32 u32Addr) +{ +#ifdef CONF_WINC_USE_UART + return nm_uart_read_reg(u32Addr); +#elif defined (CONF_WINC_USE_SPI) + return nm_spi_read_reg(u32Addr); +#elif defined (CONF_WINC_USE_I2C) + return nm_i2c_read_reg(u32Addr); +#else +#error "Plesae define bus usage" +#endif + +} + +/* +* @fn nm_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) +{ +#ifdef CONF_WINC_USE_UART + return nm_uart_read_reg_with_ret(u32Addr,pu32RetVal); +#elif defined (CONF_WINC_USE_SPI) + return nm_spi_read_reg_with_ret(u32Addr,pu32RetVal); +#elif defined (CONF_WINC_USE_I2C) + return nm_i2c_read_reg_with_ret(u32Addr,pu32RetVal); +#else +#error "Plesae define bus usage" +#endif +} + +/* +* @fn nm_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_write_reg(uint32 u32Addr, uint32 u32Val) +{ +#ifdef CONF_WINC_USE_UART + return nm_uart_write_reg(u32Addr,u32Val); +#elif defined (CONF_WINC_USE_SPI) + return nm_spi_write_reg(u32Addr,u32Val); +#elif defined (CONF_WINC_USE_I2C) + return nm_i2c_write_reg(u32Addr,u32Val); +#else +#error "Plesae define bus usage" +#endif +} + +static sint8 p_nm_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) +{ +#ifdef CONF_WINC_USE_UART + return nm_uart_read_block(u32Addr,puBuf,u16Sz); +#elif defined (CONF_WINC_USE_SPI) + return nm_spi_read_block(u32Addr,puBuf,u16Sz); +#elif defined (CONF_WINC_USE_I2C) + return nm_i2c_read_block(u32Addr,puBuf,u16Sz); +#else +#error "Plesae define bus usage" +#endif + +} +/* +* @fn nm_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u32Sz +* Number of bytes to read. The buffer size must be >= u32Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_read_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz) +{ + uint16 u16MaxTrxSz = egstrNmBusCapabilities.u16MaxTrxSz - MAX_TRX_CFG_SZ; + uint32 off = 0; + sint8 s8Ret = M2M_SUCCESS; + + for(;;) + { + if(u32Sz <= u16MaxTrxSz) + { + s8Ret += p_nm_read_block(u32Addr, &puBuf[off], (uint16)u32Sz); + break; + } + else + { + s8Ret += p_nm_read_block(u32Addr, &puBuf[off], u16MaxTrxSz); + if(M2M_SUCCESS != s8Ret) break; + u32Sz -= u16MaxTrxSz; + off += u16MaxTrxSz; + u32Addr += u16MaxTrxSz; + } + } + + return s8Ret; +} + +static sint8 p_nm_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) +{ +#ifdef CONF_WINC_USE_UART + return nm_uart_write_block(u32Addr,puBuf,u16Sz); +#elif defined (CONF_WINC_USE_SPI) + return nm_spi_write_block(u32Addr,puBuf,u16Sz); +#elif defined (CONF_WINC_USE_I2C) + return nm_i2c_write_block(u32Addr,puBuf,u16Sz); +#else +#error "Plesae define bus usage" +#endif + +} +/** +* @fn nm_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u32Sz +* Number of bytes to write. The buffer size must be >= u32Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_write_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz) +{ + uint16 u16MaxTrxSz = egstrNmBusCapabilities.u16MaxTrxSz - MAX_TRX_CFG_SZ; + uint32 off = 0; + sint8 s8Ret = M2M_SUCCESS; + + for(;;) + { + if(u32Sz <= u16MaxTrxSz) + { + s8Ret += p_nm_write_block(u32Addr, &puBuf[off], (uint16)u32Sz); + break; + } + else + { + s8Ret += p_nm_write_block(u32Addr, &puBuf[off], u16MaxTrxSz); + if(M2M_SUCCESS != s8Ret) break; + u32Sz -= u16MaxTrxSz; + off += u16MaxTrxSz; + u32Addr += u16MaxTrxSz; + } + } + + return s8Ret; +} + +#endif + diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmbus.h b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmbus.h new file mode 100644 index 0000000..2ea7838 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmbus.h @@ -0,0 +1,147 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 bus APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NMBUS_H_ +#define _NMBUS_H_ + +#include "common/include/nm_common.h" +#include "bus_wrapper/include/nm_bus_wrapper.h" + + + +#ifdef __cplusplus +extern "C"{ +#endif +/** +* @fn nm_bus_iface_init +* @brief Initialize bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_bus_iface_init(void *); + + +/** +* @fn nm_bus_iface_deinit +* @brief Deinitialize bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_bus_iface_deinit(void); + +/** +* @fn nm_bus_reset +* @brief reset bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @version 1.0 +*/ +sint8 nm_bus_reset(void); + +/** +* @fn nm_bus_iface_reconfigure +* @brief reconfigure bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_bus_iface_reconfigure(void *ptr); + +/** +* @fn nm_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +*/ +uint32 nm_read_reg(uint32 u32Addr); + +/** +* @fn nm_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); + +/** +* @fn nm_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_write_reg(uint32 u32Addr, uint32 u32Val); + +/** +* @fn nm_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u32Sz +* Number of bytes to read. The buffer size must be >= u32Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_read_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz); + +/** +* @fn nm_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u32Sz +* Number of bytes to write. The buffer size must be >= u32Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_write_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz); + + + + +#ifdef __cplusplus +} +#endif + +#endif /* _NMBUS_H_ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmdrv.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmdrv.c new file mode 100644 index 0000000..b3f2a8a --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmdrv.c @@ -0,0 +1,402 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 M2M driver APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "common/include/nm_common.h" +#include "driver/source/nmbus.h" +#include "bsp/include/nm_bsp.h" +#include "driver/source/nmdrv.h" +#include "driver/source/nmasic.h" +#include "driver/include/m2m_types.h" +#include "spi_flash/include/spi_flash.h" + +#ifdef CONF_WINC_USE_SPI +#include "driver/source/nmspi.h" +#endif + +#ifdef ARDUINO + uint32 nmdrv_firm_ver = 0; +#endif + +/** +* @fn nm_get_firmware_info(tstrM2mRev* M2mRev) +* @brief Get Firmware version info +* @param [out] M2mRev +* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters +* @version 1.0 +*/ +sint8 nm_get_firmware_info(tstrM2mRev* M2mRev) +{ + uint16 curr_drv_ver, min_req_drv_ver,curr_firm_ver; + uint32 reg = 0; + sint8 ret = M2M_SUCCESS; + + ret = nm_read_reg_with_ret(NMI_REV_REG, ®); + //In case the Firmware running is ATE fw + if(M2M_ATE_FW_IS_UP_VALUE == reg) + { + //Read FW info again from the register specified for ATE + ret = nm_read_reg_with_ret(NMI_REV_REG_ATE, ®); + } + M2mRev->u8DriverMajor = M2M_GET_DRV_MAJOR(reg); + M2mRev->u8DriverMinor = M2M_GET_DRV_MINOR(reg); + M2mRev->u8DriverPatch = M2M_GET_DRV_PATCH(reg); + M2mRev->u8FirmwareMajor = M2M_GET_FW_MAJOR(reg); + M2mRev->u8FirmwareMinor = M2M_GET_FW_MINOR(reg); + M2mRev->u8FirmwarePatch = M2M_GET_FW_PATCH(reg); + M2mRev->u32Chipid = nmi_get_chipid(); + M2mRev->u16FirmwareSvnNum = 0; + + curr_firm_ver = M2M_MAKE_VERSION(M2mRev->u8FirmwareMajor, M2mRev->u8FirmwareMinor,M2mRev->u8FirmwarePatch); +#ifdef ARDUINO + nmdrv_firm_ver = curr_firm_ver; +#endif + curr_drv_ver = M2M_MAKE_VERSION(M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); + min_req_drv_ver = M2M_MAKE_VERSION(M2mRev->u8DriverMajor, M2mRev->u8DriverMinor,M2mRev->u8DriverPatch); + if(curr_drv_ver < min_req_drv_ver) { + /*The current driver version should be larger or equal + than the min driver that the current firmware support */ + ret = M2M_ERR_FW_VER_MISMATCH; + } + if(curr_drv_ver > curr_firm_ver) { + /*The current driver should be equal or less than the firmware version*/ + ret = M2M_ERR_FW_VER_MISMATCH; + } + return ret; +} +/** +* @fn nm_get_firmware_info(tstrM2mRev* M2mRev) +* @brief Get Firmware version info +* @param [out] M2mRev +* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters +* @version 1.0 +*/ +sint8 nm_get_firmware_full_info(tstrM2mRev* pstrRev) +{ + uint16 curr_drv_ver, min_req_drv_ver,curr_firm_ver; + uint32 reg = 0; + sint8 ret = M2M_SUCCESS; + tstrGpRegs strgp = {0}; + if (pstrRev != NULL) + { + m2m_memset((uint8*)pstrRev,0,sizeof(tstrM2mRev)); + ret = nm_read_reg_with_ret(rNMI_GP_REG_2, ®); + if(ret == M2M_SUCCESS) + { + if(reg != 0) + { + ret = nm_read_block(reg|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); + if(ret == M2M_SUCCESS) + { + reg = strgp.u32Firmware_Ota_rev; + reg &= 0x0000ffff; + if(reg != 0) + { + ret = nm_read_block(reg|0x30000,(uint8*)pstrRev,sizeof(tstrM2mRev)); + if(ret == M2M_SUCCESS) + { + curr_firm_ver = M2M_MAKE_VERSION(pstrRev->u8FirmwareMajor, pstrRev->u8FirmwareMinor,pstrRev->u8FirmwarePatch); +#ifdef ARDUINO + nmdrv_firm_ver = curr_firm_ver; +#endif + curr_drv_ver = M2M_MAKE_VERSION(M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); + min_req_drv_ver = M2M_MAKE_VERSION(pstrRev->u8DriverMajor, pstrRev->u8DriverMinor,pstrRev->u8DriverPatch); + if((curr_firm_ver == 0)||(min_req_drv_ver == 0)||(min_req_drv_ver == 0)){ + ret = M2M_ERR_FAIL; + goto EXIT; + } + if(curr_drv_ver < min_req_drv_ver) { + /*The current driver version should be larger or equal + than the min driver that the current firmware support */ + ret = M2M_ERR_FW_VER_MISMATCH; + goto EXIT; + } + if(curr_drv_ver > curr_firm_ver) { + /*The current driver should be equal or less than the firmware version*/ + ret = M2M_ERR_FW_VER_MISMATCH; + goto EXIT; + } + } + }else { + ret = M2M_ERR_FAIL; + } + } + }else{ + ret = M2M_ERR_FAIL; + } + } + } +EXIT: + return ret; +} +/** +* @fn nm_get_ota_firmware_info(tstrM2mRev* pstrRev) +* @brief Get Firmware version info +* @param [out] M2mRev +* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters + +* @version 1.0 +*/ +sint8 nm_get_ota_firmware_info(tstrM2mRev* pstrRev) +{ + uint16 curr_drv_ver, min_req_drv_ver,curr_firm_ver; + uint32 reg = 0; + sint8 ret; + tstrGpRegs strgp = {0}; + + if (pstrRev != NULL) + { + m2m_memset((uint8*)pstrRev,0,sizeof(tstrM2mRev)); + ret = nm_read_reg_with_ret(rNMI_GP_REG_2, ®); + if(ret == M2M_SUCCESS) + { + if(reg != 0) + { + ret = nm_read_block(reg|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); + if(ret == M2M_SUCCESS) + { + reg = strgp.u32Firmware_Ota_rev; + reg >>= 16; + if(reg != 0) + { + ret = nm_read_block(reg|0x30000,(uint8*)pstrRev,sizeof(tstrM2mRev)); + if(ret == M2M_SUCCESS) + { + curr_firm_ver = M2M_MAKE_VERSION(pstrRev->u8FirmwareMajor, pstrRev->u8FirmwareMinor,pstrRev->u8FirmwarePatch); + curr_drv_ver = M2M_MAKE_VERSION(M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); + min_req_drv_ver = M2M_MAKE_VERSION(pstrRev->u8DriverMajor, pstrRev->u8DriverMinor,pstrRev->u8DriverPatch); + if((curr_firm_ver == 0)||(min_req_drv_ver == 0)||(min_req_drv_ver == 0)){ + ret = M2M_ERR_FAIL; + goto EXIT; + } + if(curr_drv_ver < min_req_drv_ver) { + /*The current driver version should be larger or equal + than the min driver that the current firmware support */ + ret = M2M_ERR_FW_VER_MISMATCH; + } + if(curr_drv_ver > curr_firm_ver) { + /*The current driver should be equal or less than the firmware version*/ + ret = M2M_ERR_FW_VER_MISMATCH; + } + } + }else{ + ret = M2M_ERR_INVALID; + } + } + }else{ + ret = M2M_ERR_FAIL; + } + } + } else { + ret = M2M_ERR_INVALID_ARG; + } +EXIT: + return ret; +} + + + +/* +* @fn nm_drv_init_download_mode +* @brief Initialize NMC1000 driver +* @return M2M_SUCCESS in case of success and Negative error code in case of failure +* @param [in] arg +* Generic argument +* @author Viswanathan Murugesan +* @date 10 Oct 2014 +* @version 1.0 +*/ +sint8 nm_drv_init_download_mode() +{ + sint8 ret = M2M_SUCCESS; + + ret = nm_bus_iface_init(NULL); + if (M2M_SUCCESS != ret) { + M2M_ERR("[nmi start]: fail init bus\n"); + goto ERR1; + } + + /** + TODO:reset the chip and halt the cpu in case of no wait efuse is set (add the no wait effuse check) + */ + if(!ISNMC3000(GET_CHIPID())) + { + /*Execuate that function only for 1500A/B, no room in 3000, but it may be needed in 3400 no wait*/ + chip_reset_and_cpu_halt(); + } + +#ifdef CONF_WINC_USE_SPI + /* Must do this after global reset to set SPI data packet size. */ + nm_spi_init(); +#endif + + M2M_INFO("Chip ID %lx\n", nmi_get_chipid()); + + /*disable all interrupt in ROM (to disable uart) in 2b0 chip*/ + nm_write_reg(0x20300,0); + +ERR1: + return ret; +} + +/* +* @fn nm_drv_init +* @brief Initialize NMC1000 driver +* @return M2M_SUCCESS in case of success and Negative error code in case of failure +* @param [in] arg +* Generic argument +* @author M. Abdelmawla +* @date 15 July 2012 +* @version 1.0 +*/ +sint8 nm_drv_init(void * arg) +{ + sint8 ret = M2M_SUCCESS; + uint8 u8Mode; + + if(NULL != arg) { + u8Mode = *((uint8 *)arg); + if((u8Mode < M2M_WIFI_MODE_NORMAL)||(u8Mode >= M2M_WIFI_MODE_MAX)) { + u8Mode = M2M_WIFI_MODE_NORMAL; + } + } else { + u8Mode = M2M_WIFI_MODE_NORMAL; + } + + ret = nm_bus_iface_init(NULL); + if (M2M_SUCCESS != ret) { + M2M_ERR("[nmi start]: fail init bus\n"); + goto ERR1; + } + +#ifdef BUS_ONLY + return; +#endif + + +#ifdef NO_HW_CHIP_EN + ret = chip_wake(); + if (M2M_SUCCESS != ret) { + M2M_ERR("[nmi start]: fail chip_wakeup\n"); + goto ERR2; + } + /** + Go... + **/ + ret = chip_reset(); + if (M2M_SUCCESS != ret) { + goto ERR2; + } +#endif + M2M_INFO("Chip ID %lx\n", nmi_get_chipid()); +#ifdef CONF_WINC_USE_SPI + /* Must do this after global reset to set SPI data packet size. */ + nm_spi_init(); +#endif + ret = wait_for_bootrom(u8Mode); + if (M2M_SUCCESS != ret) { + goto ERR2; + } + + ret = wait_for_firmware_start(u8Mode); + if (M2M_SUCCESS != ret) { + goto ERR2; + } + + if((M2M_WIFI_MODE_ATE_HIGH == u8Mode)||(M2M_WIFI_MODE_ATE_LOW == u8Mode)) { + goto ERR1; + } else { + /*continue running*/ + } + + ret = enable_interrupts(); + if (M2M_SUCCESS != ret) { + M2M_ERR("failed to enable interrupts..\n"); + goto ERR2; + } + return ret; +ERR2: + nm_bus_iface_deinit(); +ERR1: + return ret; +} + +/* +* @fn nm_drv_deinit +* @brief Deinitialize NMC1000 driver +* @author M. Abdelmawla +* @date 17 July 2012 +* @version 1.0 +*/ +sint8 nm_drv_deinit(void * arg) +{ +#ifdef ARDUINO + (void)arg; // Silence "unused" warning +#endif + sint8 ret; + + ret = chip_deinit(); + if (M2M_SUCCESS != ret) { + M2M_ERR("[nmi stop]: chip_deinit fail\n"); + goto ERR1; + } + + /* Disable SPI flash to save power when the chip is off */ + ret = spi_flash_enable(0); + if (M2M_SUCCESS != ret) { + M2M_ERR("[nmi stop]: SPI flash disable fail\n"); + goto ERR1; + } + + ret = nm_bus_iface_deinit(); + if (M2M_SUCCESS != ret) { + M2M_ERR("[nmi stop]: fail init bus\n"); + goto ERR1; + } +#ifdef CONF_WINC_USE_SPI + /* Must do this after global reset to set SPI data packet size. */ + nm_spi_deinit(); +#endif + +ERR1: + return ret; +} + + diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmdrv.h b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmdrv.h new file mode 100644 index 0000000..6a416b2 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmdrv.h @@ -0,0 +1,138 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 M2M driver APIs declarations. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NMDRV_H_ +#define _NMDRV_H_ + +#include "common/include/nm_common.h" + +/** +* @struct tstrM2mRev +* @brief Structure holding firmware version parameters and build date/time +*/ +typedef struct { + uint32 u32Chipid; /* HW revision which will be basically the chip ID */ + uint8 u8FirmwareMajor; /* Version Major Number which represents the official release base */ + uint8 u8FirmwareMinor; /* Version Minor Number which represents the engineering release base */ + uint8 u8FirmwarePatch; /* Version pathc Number which represents the pathces release base */ + uint8 u8DriverMajor; /* Version Major Number which represents the official release base */ + uint8 u8DriverMinor; /* Version Minor Number which represents the engineering release base */ + uint8 u8DriverPatch; /* Version Patch Number which represents the pathces release base */ + uint8 BuildDate[sizeof(__DATE__)]; + uint8 BuildTime[sizeof(__TIME__)]; + uint8 _PAD8_; + uint16 u16FirmwareSvnNum; + uint16 _PAD16_[2]; +} tstrM2mRev; + +/** +* @struct tstrM2mBinaryHeader +* @brief Structure holding compatibility version info for firmware binaries +*/ +typedef struct { + tstrM2mRev binVerInfo; + uint32 flashOffset; + uint32 payloadSize; +} tstrM2mBinaryHeader; + +#ifdef __cplusplus + extern "C" { + #endif +/** +* @fn nm_get_firmware_info(tstrM2mRev* M2mRev) +* @brief Get Firmware version info +* @param [out] M2mRev +* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters +* @version 1.0 +*/ +sint8 nm_get_firmware_info(tstrM2mRev* M2mRev); +/** +* @fn nm_get_firmware_full_info(tstrM2mRev* pstrRev) +* @brief Get Firmware version info +* @param [out] M2mRev +* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters +* @version 1.0 +*/ +sint8 nm_get_firmware_full_info(tstrM2mRev* pstrRev); +/** +* @fn nm_get_ota_firmware_info(tstrM2mRev* pstrRev) +* @brief Get Firmware version info +* @param [out] M2mRev +* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters + +* @version 1.0 +*/ +sint8 nm_get_ota_firmware_info(tstrM2mRev* pstrRev); +/* +* @fn nm_drv_init +* @brief Initialize NMC1000 driver +* @return ZERO in case of success and Negative error code in case of failure +*/ +sint8 nm_drv_init_download_mode(void); + +/* +* @fn nm_drv_init +* @brief Initialize NMC1000 driver +* @return M2M_SUCCESS in case of success and Negative error code in case of failure +* @param [in] arg +* Generic argument TBD +* @return ZERO in case of success and Negative error code in case of failure + +*/ +sint8 nm_drv_init(void * arg); + +/** +* @fn nm_drv_deinit +* @brief Deinitialize NMC1000 driver +* @author M. Abdelmawla +* @param [in] arg +* Generic argument TBD +* @return ZERO in case of success and Negative error code in case of failure +*/ +sint8 nm_drv_deinit(void * arg); + +#ifdef __cplusplus + } + #endif + +#endif /*_NMDRV_H_*/ + + diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmi2c.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmi2c.c new file mode 100644 index 0000000..e11d2f7 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmi2c.c @@ -0,0 +1,269 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 I2C protocol bus APIs implementation. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "common/include/nm_common.h" + +#ifdef CONF_WINC_USE_I2C + +#include "nmi2c.h" +#include "bus_wrapper/include/nm_bus_wrapper.h" + + +/* +* @fn nm_i2c_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ + sint8 nm_i2c_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) +{ + uint8 b[6]; + uint8 rsz; + tstrNmI2cDefault strI2c; + sint8 s8Ret = M2M_SUCCESS; + + if(u32Addr < 0xff) { /* clockless i2c */ + b[0] = 0x09; + b[1] = (uint8)(u32Addr); + rsz = 1; + strI2c.u16Sz = 2; + } else { + b[0] = 0x80; + b[1] = (uint8)(u32Addr >> 24); + b[2] = (uint8)(u32Addr >> 16); + b[3] = (uint8)(u32Addr >> 8); + b[4] = (uint8)(u32Addr); + b[5] = 0x04; + rsz = 4; + strI2c.u16Sz = 6; + } + + strI2c.pu8Buf = b; + + if(M2M_SUCCESS == nm_bus_ioctl(NM_BUS_IOCTL_W, &strI2c)) + { + strI2c.u16Sz = rsz; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strI2c)) + { + //M2M_ERR("read error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + M2M_ERR("failed to send cfg bytes\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + + if (rsz == 1) { + *pu32RetVal = b[0]; + } else { + *pu32RetVal = b[0] | ((uint32)b[1] << 8) | ((uint32)b[2] << 16) | ((uint32)b[3] << 24); + } + return s8Ret; +} + +/* +* @fn nm_i2c_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +uint32 nm_i2c_read_reg(uint32 u32Addr) +{ + uint32 val; + nm_i2c_read_reg_with_ret(u32Addr, &val); + return val; +} + +/* +* @fn nm_i2c_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_i2c_write_reg(uint32 u32Addr, uint32 u32Val) +{ + tstrNmI2cDefault strI2c; + uint8 b[16]; + sint8 s8Ret = M2M_SUCCESS; + + if(u32Addr < 0xff) { /* clockless i2c */ + b[0] = 0x19; + b[1] = (uint8)(u32Addr); + b[2] = (uint8)(u32Val); + strI2c.u16Sz = 3; + } else { + b[0] = 0x90; + b[1] = (uint8)(u32Addr >> 24); + b[2] = (uint8)(u32Addr >> 16); + b[3] = (uint8)(u32Addr >> 8); + b[4] = (uint8)u32Addr; + b[5] = 0x04; + b[6] = (uint8)u32Val; + b[7] = (uint8)(u32Val >> 8); + b[8] = (uint8)(u32Val >> 16); + b[9] = (uint8)(u32Val >> 24); + strI2c.u16Sz = 10; + } + + strI2c.pu8Buf = b; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strI2c)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + + return s8Ret; +} + +/* +* @fn nm_i2c_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u16Sz +* Number of bytes to read. The buffer size must be >= u16Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_i2c_read_block(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz) +{ + tstrNmI2cDefault strI2c; + uint8 au8Buf[7]; + sint8 s8Ret = M2M_SUCCESS; + + au8Buf[0] = 0x02; + au8Buf[1] = (uint8)(u32Addr >> 24); + au8Buf[2] = (uint8)(u32Addr >> 16); + au8Buf[3] = (uint8)(u32Addr >> 8); + au8Buf[4] = (uint8)(u32Addr >> 0); + au8Buf[5] = (uint8)(u16Sz >> 8); + au8Buf[6] = (uint8)(u16Sz); + + strI2c.pu8Buf = au8Buf; + strI2c.u16Sz = sizeof(au8Buf); + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strI2c)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + else + { + strI2c.pu8Buf = pu8Buf; + strI2c.u16Sz = u16Sz; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strI2c)) + { + M2M_ERR("read error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + + return s8Ret; +} + +/* +* @fn nm_i2c_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u16Sz +* Number of bytes to write. The buffer size must be >= u16Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_i2c_write_block(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz) +{ + uint8 au8Buf[7]; + tstrNmI2cSpecial strI2c; + sint8 s8Ret = M2M_SUCCESS; + + au8Buf[0] = 0x12; + au8Buf[1] = (uint8)(u32Addr >> 24); + au8Buf[2] = (uint8)(u32Addr >> 16); + au8Buf[3] = (uint8)(u32Addr >> 8); + au8Buf[4] = (uint8)(u32Addr); + au8Buf[5] = (uint8)(u16Sz >> 8); + au8Buf[6] = (uint8)(u16Sz); + + strI2c.pu8Buf1 = au8Buf; + strI2c.pu8Buf2 = pu8Buf; + strI2c.u16Sz1 = sizeof(au8Buf); + strI2c.u16Sz2 = u16Sz; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W_SPECIAL, &strI2c)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + + return s8Ret; +} + +#endif +/* EOF */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmi2c.h b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmi2c.h new file mode 100644 index 0000000..fea85e6 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmi2c.h @@ -0,0 +1,104 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 I2C protocol bus APIs implementation. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NMI2C_H_ +#define _NMI2C_H_ + +#include "common/include/nm_common.h" + +/** +* @fn nm_i2c_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +*/ +uint32 nm_i2c_read_reg(uint32 u32Addr); + +/** +* @fn nm_i2c_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_i2c_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); + +/** +* @fn nm_i2c_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_i2c_write_reg(uint32 u32Addr, uint32 u32Val); + +/** +* @fn nm_i2c_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u16Sz +* Number of bytes to read. The buffer size must be >= u16Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_i2c_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); + +/** +* @fn nm_i2c_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u16Sz +* Number of bytes to write. The buffer size must be >= u16Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_i2c_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); + +#endif /* _NMI2C_H_ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmspi.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmspi.c new file mode 100644 index 0000000..9483ab7 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmspi.c @@ -0,0 +1,1401 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 SPI protocol bus APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +#include "common/include/nm_common.h" + +#ifdef CONF_WINC_USE_SPI + +#define USE_OLD_SPI_SW + +#include "bus_wrapper/include/nm_bus_wrapper.h" +#include "nmspi.h" + +#define NMI_PERIPH_REG_BASE 0x1000 +#define NMI_INTR_REG_BASE (NMI_PERIPH_REG_BASE+0xa00) +#define NMI_CHIPID (NMI_PERIPH_REG_BASE) +#define NMI_PIN_MUX_0 (NMI_PERIPH_REG_BASE + 0x408) +#define NMI_INTR_ENABLE (NMI_INTR_REG_BASE) + +#define NMI_SPI_REG_BASE 0xe800 +#define NMI_SPI_CTL (NMI_SPI_REG_BASE) +#define NMI_SPI_MASTER_DMA_ADDR (NMI_SPI_REG_BASE+0x4) +#define NMI_SPI_MASTER_DMA_COUNT (NMI_SPI_REG_BASE+0x8) +#define NMI_SPI_SLAVE_DMA_ADDR (NMI_SPI_REG_BASE+0xc) +#define NMI_SPI_SLAVE_DMA_COUNT (NMI_SPI_REG_BASE+0x10) +#define NMI_SPI_TX_MODE (NMI_SPI_REG_BASE+0x20) +#define NMI_SPI_PROTOCOL_CONFIG (NMI_SPI_REG_BASE+0x24) +#define NMI_SPI_INTR_CTL (NMI_SPI_REG_BASE+0x2c) +#define NMI_SPI_MISC_CTRL (NMI_SPI_REG_BASE+0x48) + +#define NMI_SPI_PROTOCOL_OFFSET (NMI_SPI_PROTOCOL_CONFIG-NMI_SPI_REG_BASE) + +#define SPI_BASE NMI_SPI_REG_BASE + +#define CMD_DMA_WRITE 0xc1 +#define CMD_DMA_READ 0xc2 +#define CMD_INTERNAL_WRITE 0xc3 +#define CMD_INTERNAL_READ 0xc4 +#define CMD_TERMINATE 0xc5 +#define CMD_REPEAT 0xc6 +#define CMD_DMA_EXT_WRITE 0xc7 +#define CMD_DMA_EXT_READ 0xc8 +#define CMD_SINGLE_WRITE 0xc9 +#define CMD_SINGLE_READ 0xca +#define CMD_RESET 0xcf + +#define N_OK 1 +#define N_FAIL 0 +#define N_RESET -1 +#define N_RETRY -2 + +#define SPI_RESP_RETRY_COUNT (10) +#define SPI_RETRY_COUNT (10) +#define DATA_PKT_SZ_256 256 +#define DATA_PKT_SZ_512 512 +#define DATA_PKT_SZ_1K 1024 +#define DATA_PKT_SZ_4K (4 * 1024) +#define DATA_PKT_SZ_8K (8 * 1024) +#define DATA_PKT_SZ DATA_PKT_SZ_8K + +static uint8 gu8Crc_off = 0; + +static sint8 nmi_spi_read(uint8* b, uint16 sz) +{ + tstrNmSpiRw spi; + spi.pu8InBuf = NULL; + spi.pu8OutBuf = b; + spi.u16Sz = sz; + return nm_bus_ioctl(NM_BUS_IOCTL_RW, &spi); +} + +static sint8 nmi_spi_write(uint8* b, uint16 sz) +{ + tstrNmSpiRw spi; + spi.pu8InBuf = b; + spi.pu8OutBuf = NULL; + spi.u16Sz = sz; + return nm_bus_ioctl(NM_BUS_IOCTL_RW, &spi); +} +#ifndef USE_OLD_SPI_SW +static sint8 nmi_spi_rw(uint8 *bin,uint8* bout,uint16 sz) +{ + tstrNmSpiRw spi; + spi.pu8InBuf = bin; + spi.pu8OutBuf = bout; + spi.u16Sz = sz; + return nm_bus_ioctl(NM_BUS_IOCTL_RW, &spi); +} +#endif +/******************************************** + + Crc7 + +********************************************/ +#if (defined ARDUINO_ARCH_AVR) +#include +static PROGMEM const uint8 crc7_syndrome_table[256] = { +#else +static const uint8 crc7_syndrome_table[256] = { +#endif + 0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f, + 0x48, 0x41, 0x5a, 0x53, 0x6c, 0x65, 0x7e, 0x77, + 0x19, 0x10, 0x0b, 0x02, 0x3d, 0x34, 0x2f, 0x26, + 0x51, 0x58, 0x43, 0x4a, 0x75, 0x7c, 0x67, 0x6e, + 0x32, 0x3b, 0x20, 0x29, 0x16, 0x1f, 0x04, 0x0d, + 0x7a, 0x73, 0x68, 0x61, 0x5e, 0x57, 0x4c, 0x45, + 0x2b, 0x22, 0x39, 0x30, 0x0f, 0x06, 0x1d, 0x14, + 0x63, 0x6a, 0x71, 0x78, 0x47, 0x4e, 0x55, 0x5c, + 0x64, 0x6d, 0x76, 0x7f, 0x40, 0x49, 0x52, 0x5b, + 0x2c, 0x25, 0x3e, 0x37, 0x08, 0x01, 0x1a, 0x13, + 0x7d, 0x74, 0x6f, 0x66, 0x59, 0x50, 0x4b, 0x42, + 0x35, 0x3c, 0x27, 0x2e, 0x11, 0x18, 0x03, 0x0a, + 0x56, 0x5f, 0x44, 0x4d, 0x72, 0x7b, 0x60, 0x69, + 0x1e, 0x17, 0x0c, 0x05, 0x3a, 0x33, 0x28, 0x21, + 0x4f, 0x46, 0x5d, 0x54, 0x6b, 0x62, 0x79, 0x70, + 0x07, 0x0e, 0x15, 0x1c, 0x23, 0x2a, 0x31, 0x38, + 0x41, 0x48, 0x53, 0x5a, 0x65, 0x6c, 0x77, 0x7e, + 0x09, 0x00, 0x1b, 0x12, 0x2d, 0x24, 0x3f, 0x36, + 0x58, 0x51, 0x4a, 0x43, 0x7c, 0x75, 0x6e, 0x67, + 0x10, 0x19, 0x02, 0x0b, 0x34, 0x3d, 0x26, 0x2f, + 0x73, 0x7a, 0x61, 0x68, 0x57, 0x5e, 0x45, 0x4c, + 0x3b, 0x32, 0x29, 0x20, 0x1f, 0x16, 0x0d, 0x04, + 0x6a, 0x63, 0x78, 0x71, 0x4e, 0x47, 0x5c, 0x55, + 0x22, 0x2b, 0x30, 0x39, 0x06, 0x0f, 0x14, 0x1d, + 0x25, 0x2c, 0x37, 0x3e, 0x01, 0x08, 0x13, 0x1a, + 0x6d, 0x64, 0x7f, 0x76, 0x49, 0x40, 0x5b, 0x52, + 0x3c, 0x35, 0x2e, 0x27, 0x18, 0x11, 0x0a, 0x03, + 0x74, 0x7d, 0x66, 0x6f, 0x50, 0x59, 0x42, 0x4b, + 0x17, 0x1e, 0x05, 0x0c, 0x33, 0x3a, 0x21, 0x28, + 0x5f, 0x56, 0x4d, 0x44, 0x7b, 0x72, 0x69, 0x60, + 0x0e, 0x07, 0x1c, 0x15, 0x2a, 0x23, 0x38, 0x31, + 0x46, 0x4f, 0x54, 0x5d, 0x62, 0x6b, 0x70, 0x79 +}; + + +static uint8 crc7_byte(uint8 crc, uint8 data) +{ +#if (defined ARDUINO_ARCH_AVR) + return pgm_read_byte_near(crc7_syndrome_table + ((crc << 1) ^ data)); +#else + return crc7_syndrome_table[(crc << 1) ^ data]; +#endif +} + +static uint8 crc7(uint8 crc, const uint8 *buffer, uint32 len) +{ + while (len--) + crc = crc7_byte(crc, *buffer++); + return crc; +} + +/******************************************** + + Spi protocol Function + +********************************************/ + +#define CMD_DMA_WRITE 0xc1 +#define CMD_DMA_READ 0xc2 +#define CMD_INTERNAL_WRITE 0xc3 +#define CMD_INTERNAL_READ 0xc4 +#define CMD_TERMINATE 0xc5 +#define CMD_REPEAT 0xc6 +#define CMD_DMA_EXT_WRITE 0xc7 +#define CMD_DMA_EXT_READ 0xc8 +#define CMD_SINGLE_WRITE 0xc9 +#define CMD_SINGLE_READ 0xca +#define CMD_RESET 0xcf + +#define DATA_PKT_SZ_256 256 +#define DATA_PKT_SZ_512 512 +#define DATA_PKT_SZ_1K 1024 +#define DATA_PKT_SZ_4K (4 * 1024) +#define DATA_PKT_SZ_8K (8 * 1024) +#define DATA_PKT_SZ DATA_PKT_SZ_8K + +static sint8 spi_cmd(uint8 cmd, uint32 adr, uint32 u32data, uint32 sz,uint8 clockless) +{ + uint8 bc[9]; + uint8 len = 5; + sint8 result = N_OK; + + bc[0] = cmd; + switch (cmd) { + case CMD_SINGLE_READ: /* single word (4 bytes) read */ + bc[1] = (uint8)(adr >> 16); + bc[2] = (uint8)(adr >> 8); + bc[3] = (uint8)adr; + len = 5; + break; + case CMD_INTERNAL_READ: /* internal register read */ + bc[1] = (uint8)(adr >> 8); + if(clockless) bc[1] |= (1 << 7); + bc[2] = (uint8)adr; + bc[3] = 0x00; + len = 5; + break; + case CMD_TERMINATE: /* termination */ + bc[1] = 0x00; + bc[2] = 0x00; + bc[3] = 0x00; + len = 5; + break; + case CMD_REPEAT: /* repeat */ + bc[1] = 0x00; + bc[2] = 0x00; + bc[3] = 0x00; + len = 5; + break; + case CMD_RESET: /* reset */ + bc[1] = 0xff; + bc[2] = 0xff; + bc[3] = 0xff; + len = 5; + break; + case CMD_DMA_WRITE: /* dma write */ + case CMD_DMA_READ: /* dma read */ + bc[1] = (uint8)(adr >> 16); + bc[2] = (uint8)(adr >> 8); + bc[3] = (uint8)adr; + bc[4] = (uint8)(sz >> 8); + bc[5] = (uint8)(sz); + len = 7; + break; + case CMD_DMA_EXT_WRITE: /* dma extended write */ + case CMD_DMA_EXT_READ: /* dma extended read */ + bc[1] = (uint8)(adr >> 16); + bc[2] = (uint8)(adr >> 8); + bc[3] = (uint8)adr; + bc[4] = (uint8)(sz >> 16); + bc[5] = (uint8)(sz >> 8); + bc[6] = (uint8)(sz); + len = 8; + break; + case CMD_INTERNAL_WRITE: /* internal register write */ + bc[1] = (uint8)(adr >> 8); + if(clockless) bc[1] |= (1 << 7); + bc[2] = (uint8)(adr); + bc[3] = (uint8)(u32data >> 24); + bc[4] = (uint8)(u32data >> 16); + bc[5] = (uint8)(u32data >> 8); + bc[6] = (uint8)(u32data); + len = 8; + break; + case CMD_SINGLE_WRITE: /* single word write */ + bc[1] = (uint8)(adr >> 16); + bc[2] = (uint8)(adr >> 8); + bc[3] = (uint8)(adr); + bc[4] = (uint8)(u32data >> 24); + bc[5] = (uint8)(u32data >> 16); + bc[6] = (uint8)(u32data >> 8); + bc[7] = (uint8)(u32data); + len = 9; + break; + default: + result = N_FAIL; + break; + } + + if (result) { + if (!gu8Crc_off) + bc[len-1] = (crc7(0x7f, (const uint8 *)&bc[0], len-1)) << 1; + else + len-=1; + + if (M2M_SUCCESS != nmi_spi_write(bc, len)) { + M2M_ERR("[nmi spi]: Failed cmd write, bus error...\n"); + result = N_FAIL; + } + } + + return result; +} + +static sint8 spi_data_rsp(uint8 cmd) +{ +#ifdef ARDUINO + (void)cmd; // Silence "unused" warning +#endif + uint8 len; + uint8 rsp[3]; + sint8 result = N_OK; + + if (!gu8Crc_off) + len = 2; + else + len = 3; + + if (M2M_SUCCESS != nmi_spi_read(&rsp[0], len)) { + M2M_ERR("[nmi spi]: Failed bus error...\n"); + result = N_FAIL; + goto _fail_; + } + + if((rsp[len-1] != 0)||(rsp[len-2] != 0xC3)) + { + M2M_ERR("[nmi spi]: Failed data response read, %x %x %x\n",rsp[0],rsp[1],rsp[2]); + result = N_FAIL; + goto _fail_; + } +_fail_: + + return result; +} + +static sint8 spi_cmd_rsp(uint8 cmd) +{ + uint8 rsp; + sint8 result = N_OK; + sint8 s8RetryCnt; + + /** + Command/Control response + **/ + if ((cmd == CMD_RESET) || + (cmd == CMD_TERMINATE) || + (cmd == CMD_REPEAT)) { + if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { + result = N_FAIL; + goto _fail_; + } + } + + /* wait for response */ + s8RetryCnt = SPI_RESP_RETRY_COUNT; + do + { + if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { + M2M_ERR("[nmi spi]: Failed cmd response read, bus error...\n"); + result = N_FAIL; + goto _fail_; + } + } while((rsp != cmd) && (s8RetryCnt-- >0)); + + /** + State response + **/ + /* wait for response */ + s8RetryCnt = SPI_RESP_RETRY_COUNT; + do + { + if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { + M2M_ERR("[nmi spi]: Failed cmd response read, bus error...\n"); + result = N_FAIL; + goto _fail_; + } + } while((rsp != 0x00) && (s8RetryCnt-- >0)); + +_fail_: + + return result; +} +#ifndef USE_OLD_SPI_SW +static int spi_cmd_complete(uint8_t cmd, uint32_t adr, uint8_t *b, uint32_t sz, uint8_t clockless) +{ + uint8_t wb[32], rb[32]; + uint8_t wix, rix; + uint32_t len2; + uint8_t rsp; + int len = 0; + int result = N_OK; + + wb[0] = cmd; + switch (cmd) { + case CMD_SINGLE_READ: /* single word (4 bytes) read */ + wb[1] = (uint8_t)(adr >> 16); + wb[2] = (uint8_t)(adr >> 8); + wb[3] = (uint8_t)adr; + len = 5; + break; + case CMD_INTERNAL_READ: /* internal register read */ + wb[1] = (uint8_t)(adr >> 8); + if(clockless == 1) wb[1] |= (1 << 7); + wb[2] = (uint8_t)adr; + wb[3] = 0x00; + len = 5; + break; + case CMD_TERMINATE: /* termination */ + wb[1] = 0x00; + wb[2] = 0x00; + wb[3] = 0x00; + len = 5; + break; + case CMD_REPEAT: /* repeat */ + wb[1] = 0x00; + wb[2] = 0x00; + wb[3] = 0x00; + len = 5; + break; + case CMD_RESET: /* reset */ + wb[1] = 0xff; + wb[2] = 0xff; + wb[3] = 0xff; + len = 5; + break; + case CMD_DMA_WRITE: /* dma write */ + case CMD_DMA_READ: /* dma read */ + wb[1] = (uint8_t)(adr >> 16); + wb[2] = (uint8_t)(adr >> 8); + wb[3] = (uint8_t)adr; + wb[4] = (uint8_t)(sz >> 8); + wb[5] = (uint8_t)(sz); + len = 7; + break; + case CMD_DMA_EXT_WRITE: /* dma extended write */ + case CMD_DMA_EXT_READ: /* dma extended read */ + wb[1] = (uint8_t)(adr >> 16); + wb[2] = (uint8_t)(adr >> 8); + wb[3] = (uint8_t)adr; + wb[4] = (uint8_t)(sz >> 16); + wb[5] = (uint8_t)(sz >> 8); + wb[6] = (uint8_t)(sz); + len = 8; + break; + case CMD_INTERNAL_WRITE: /* internal register write */ + wb[1] = (uint8_t)(adr >> 8); + if(clockless == 1) wb[1] |= (1 << 7); + wb[2] = (uint8_t)(adr); + wb[3] = b[3]; + wb[4] = b[2]; + wb[5] = b[1]; + wb[6] = b[0]; + len = 8; + break; + case CMD_SINGLE_WRITE: /* single word write */ + wb[1] = (uint8_t)(adr >> 16); + wb[2] = (uint8_t)(adr >> 8); + wb[3] = (uint8_t)(adr); + wb[4] = b[3]; + wb[5] = b[2]; + wb[6] = b[1]; + wb[7] = b[0]; + len = 9; + break; + default: + result = N_FAIL; + break; + } + + if (result != N_OK) { + return result; + } + + if (!gu8Crc_off) { + wb[len-1] = (crc7(0x7f, (const uint8_t *)&wb[0], len-1)) << 1; + } else { + len -=1; + } + +#define NUM_SKIP_BYTES (1) +#define NUM_RSP_BYTES (2) +#define NUM_DATA_HDR_BYTES (1) +#define NUM_DATA_BYTES (4) +#define NUM_CRC_BYTES (2) +#define NUM_DUMMY_BYTES (3) + + if ((cmd == CMD_RESET) || + (cmd == CMD_TERMINATE) || + (cmd == CMD_REPEAT)) { + len2 = len + (NUM_SKIP_BYTES + NUM_RSP_BYTES + NUM_DUMMY_BYTES); + } else if ((cmd == CMD_INTERNAL_READ) || (cmd == CMD_SINGLE_READ)) { + if (!gu8Crc_off) { + len2 = len + (NUM_RSP_BYTES + NUM_DATA_HDR_BYTES + NUM_DATA_BYTES + + NUM_CRC_BYTES + NUM_DUMMY_BYTES); + } else { + len2 = len + (NUM_RSP_BYTES + NUM_DATA_HDR_BYTES + NUM_DATA_BYTES + + NUM_DUMMY_BYTES); + } + } else { + len2 = len + (NUM_RSP_BYTES + NUM_DUMMY_BYTES); + } +#undef NUM_DUMMY_BYTES + + if(len2 > (sizeof(wb)/sizeof(wb[0]))) { + M2M_ERR("[nmi spi]: spi buffer size too small (%d) (%d)\n", + len2, (sizeof(wb)/sizeof(wb[0]))); + result = N_FAIL; + return result; + } + /* zero spi write buffers. */ + for(wix = len; wix< len2; wix++) { + wb[wix] = 0; + } + rix = len; + + if (nmi_spi_rw(wb, rb, len2) != M2M_SUCCESS) { + M2M_ERR("[nmi spi]: Failed cmd write, bus error...\n"); + result = N_FAIL; + return result; + } + +#if 0 + { + int jj; + printk("--- cnd = %x, len=%d, len2=%d\n", cmd, len, len2); + for(jj=0; jj= len2) break; + if(((jj+1)%16) != 0) { + if((jj%16) == 0) { + printk("wb[%02x]: %02x ", jj, wb[jj]); + } else { + printk("%02x ", wb[jj]); + } + } else { + printk("%02x\n", wb[jj]); + } + } + printk("\n"); + + for(jj=0; jj= len2) break; + if(((jj+1)%16) != 0) { + if((jj%16) == 0) { + printk("rb[%02x]: %02x ", jj, rb[jj]); + } else { + printk("%02x ", rb[jj]); + } + } else { + printk("%02x\n", rb[jj]); + } + } + printk("\n"); + } +#endif + + /** + Command/Control response + **/ + if ((cmd == CMD_RESET) || + (cmd == CMD_TERMINATE) || + (cmd == CMD_REPEAT)) { + rix++; /* skip 1 byte */ + } + + rsp = rb[rix++]; + + + if (rsp != cmd) { + M2M_ERR("[nmi spi]: Failed cmd response, cmd (%02x), resp (%02x)\n", cmd, rsp); + result = N_FAIL; + return result; + } + + /** + State response + **/ + rsp = rb[rix++]; + if (rsp != 0x00) { + M2M_ERR("[nmi spi]: Failed cmd state response state (%02x)\n", rsp); + result = N_FAIL; + return result; + } + + if ((cmd == CMD_INTERNAL_READ) || (cmd == CMD_SINGLE_READ) + || (cmd == CMD_DMA_READ) || (cmd == CMD_DMA_EXT_READ)) { + int retry; + //uint16_t crc1, crc2; + uint8_t crc[2]; + /** + Data Respnose header + **/ + retry = SPI_RESP_RETRY_COUNT; + do { + /* ensure there is room in buffer later to read data and crc */ + if(rix < len2) { + rsp = rb[rix++]; + } else { + retry = 0; + break; + } + if (((rsp >> 4) & 0xf) == 0xf) + break; + } while (retry--); + + if (retry <= 0) { + M2M_ERR("[nmi spi]: Error, data read response (%02x)\n", rsp); + result = N_RESET; + return result; + } + + if ((cmd == CMD_INTERNAL_READ) || (cmd == CMD_SINGLE_READ)) { + /** + Read bytes + **/ + if((rix+3) < len2) { + b[0] = rb[rix++]; + b[1] = rb[rix++]; + b[2] = rb[rix++]; + b[3] = rb[rix++]; + } else { + M2M_ERR("[nmi spi]: buffer overrun when reading data.\n"); + result = N_FAIL; + return result; + } + + if (!gu8Crc_off) { + /** + Read Crc + **/ + if((rix+1) < len2) { + crc[0] = rb[rix++]; + crc[1] = rb[rix++]; + } else { + M2M_ERR("[nmi spi]: buffer overrun when reading crc.\n"); + result = N_FAIL; + return result; + } + } + } else if((cmd == CMD_DMA_READ) || (cmd == CMD_DMA_EXT_READ)) { + int ix; + + /* some data may be read in response to dummy bytes. */ + for(ix=0; (rix < len2) && (ix < sz);) { + b[ix++] = rb[rix++]; + } +#if 0 + if(ix) M2M_INFO("ttt %d %d\n", sz, ix); +#endif + sz -= ix; + + if(sz > 0) { + int nbytes; + + if (sz <= (DATA_PKT_SZ-ix)) { + nbytes = sz; + } else { + nbytes = DATA_PKT_SZ-ix; + } + + /** + Read bytes + **/ + if (nmi_spi_read(&b[ix], nbytes) != M2M_SUCCESS) { + M2M_ERR("[nmi spi]: Failed data block read, bus error...\n"); + result = N_FAIL; + goto _error_; + } + + /** + Read Crc + **/ + if (!gu8Crc_off) { + if (nmi_spi_read(crc, 2) != M2M_SUCCESS) { + M2M_ERR("[nmi spi]: Failed data block crc read, bus error...\n"); + result = N_FAIL; + goto _error_; + } + } + + + ix += nbytes; + sz -= nbytes; + } + + /* if any data in left unread, then read the rest using normal DMA code.*/ + while(sz > 0) { + int nbytes; + + if (sz <= DATA_PKT_SZ) { + nbytes = sz; + } else { + nbytes = DATA_PKT_SZ; + } + + /** + read data response only on the next DMA cycles not + the first DMA since data response header is already + handled above for the first DMA. + **/ + /** + Data Respnose header + **/ + retry = SPI_RESP_RETRY_COUNT; + do { + if (nmi_spi_read(&rsp, 1) != M2M_SUCCESS) { + M2M_ERR("[nmi spi]: Failed data response read, bus error...\n"); + result = N_FAIL; + break; + } + if (((rsp >> 4) & 0xf) == 0xf) + break; + } while (retry--); + + if (result == N_FAIL) + break; + + + /** + Read bytes + **/ + if (nmi_spi_read(&b[ix], nbytes) != M2M_SUCCESS) { + M2M_ERR("[nmi spi]: Failed data block read, bus error...\n"); + result = N_FAIL; + break; + } + + /** + Read Crc + **/ + if (!gu8Crc_off) { + if (nmi_spi_read(crc, 2) != M2M_SUCCESS) { + M2M_ERR("[nmi spi]: Failed data block crc read, bus error...\n"); + result = N_FAIL; + break; + } + } + + ix += nbytes; + sz -= nbytes; + } + } + } +_error_: + return result; +} +#endif +static sint8 spi_data_read(uint8 *b, uint16 sz,uint8 clockless) +{ + sint16 retry, ix, nbytes; + sint8 result = N_OK; + uint8 crc[2]; + uint8 rsp; + + /** + Data + **/ + ix = 0; + do { + if (sz <= DATA_PKT_SZ) + nbytes = sz; + else + nbytes = DATA_PKT_SZ; + + /** + Data Respnose header + **/ + retry = SPI_RESP_RETRY_COUNT; + do { + if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { + M2M_ERR("[nmi spi]: Failed data response read, bus error...\n"); + result = N_FAIL; + break; + } + if (((rsp >> 4) & 0xf) == 0xf) + break; + } while (retry--); + + if (result == N_FAIL) + break; + + if (retry <= 0) { + M2M_ERR("[nmi spi]: Failed data response read...(%02x)\n", rsp); + result = N_FAIL; + break; + } + + /** + Read bytes + **/ + if (M2M_SUCCESS != nmi_spi_read(&b[ix], nbytes)) { + M2M_ERR("[nmi spi]: Failed data block read, bus error...\n"); + result = N_FAIL; + break; + } + if(!clockless) + { + /** + Read Crc + **/ + if (!gu8Crc_off) { + if (M2M_SUCCESS != nmi_spi_read(crc, 2)) { + M2M_ERR("[nmi spi]: Failed data block crc read, bus error...\n"); + result = N_FAIL; + break; + } + } + } + ix += nbytes; + sz -= nbytes; + + } while (sz); + + return result; +} + +static sint8 spi_data_write(uint8 *b, uint16 sz) +{ + sint16 ix; + uint16 nbytes; + sint8 result = 1; + uint8 cmd, order, crc[2] = {0}; + //uint8 rsp; + + /** + Data + **/ + ix = 0; + do { + if (sz <= DATA_PKT_SZ) + nbytes = sz; + else + nbytes = DATA_PKT_SZ; + + /** + Write command + **/ + cmd = 0xf0; + if (ix == 0) { + if (sz <= DATA_PKT_SZ) + order = 0x3; + else + order = 0x1; + } else { + if (sz <= DATA_PKT_SZ) + order = 0x3; + else + order = 0x2; + } + cmd |= order; + if (M2M_SUCCESS != nmi_spi_write(&cmd, 1)) { + M2M_ERR("[nmi spi]: Failed data block cmd write, bus error...\n"); + result = N_FAIL; + break; + } + + /** + Write data + **/ + if (M2M_SUCCESS != nmi_spi_write(&b[ix], nbytes)) { + M2M_ERR("[nmi spi]: Failed data block write, bus error...\n"); + result = N_FAIL; + break; + } + + /** + Write Crc + **/ + if (!gu8Crc_off) { + if (M2M_SUCCESS != nmi_spi_write(crc, 2)) { + M2M_ERR("[nmi spi]: Failed data block crc write, bus error...\n"); + result = N_FAIL; + break; + } + } + + ix += nbytes; + sz -= nbytes; + } while (sz); + + + return result; +} + +/******************************************** + + Spi Internal Read/Write Function + +********************************************/ + +/******************************************** + + Spi interfaces + +********************************************/ + +static sint8 spi_write_reg(uint32 addr, uint32 u32data) +{ + uint8 retry = SPI_RETRY_COUNT; + sint8 result = N_OK; + uint8 cmd = CMD_SINGLE_WRITE; + uint8 clockless = 0; + +_RETRY_: + if (addr <= 0x30) + { + /** + NMC1000 clockless registers. + **/ + cmd = CMD_INTERNAL_WRITE; + clockless = 1; + } + else + { + cmd = CMD_SINGLE_WRITE; + clockless = 0; + } + +#if defined USE_OLD_SPI_SW + result = spi_cmd(cmd, addr, u32data, 4, clockless); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd, write reg (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + + result = spi_cmd_rsp(cmd); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd response, write reg (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + +#else + + result = spi_cmd_complete(cmd, addr, (uint8*)&u32data, 4, clockless); + if (result != N_OK) { + M2M_ERR( "[nmi spi]: Failed cmd, write reg (%08x)...\n", addr); + goto _FAIL_; + } + +#endif +_FAIL_: + if(result != N_OK) + { + nm_bsp_sleep(1); + spi_cmd(CMD_RESET, 0, 0, 0, 0); + spi_cmd_rsp(CMD_RESET); + M2M_ERR("Reset and retry %d %lx %lx\n",retry,addr,u32data); + nm_bsp_sleep(1); + retry--; + if(retry) goto _RETRY_; + } + + return result; +} + +static sint8 nm_spi_write(uint32 addr, uint8 *buf, uint16 size) +{ + sint8 result; + uint8 retry = SPI_RETRY_COUNT; + uint8 cmd = CMD_DMA_EXT_WRITE; + + +_RETRY_: + /** + Command + **/ +#if defined USE_OLD_SPI_SW + //Workaround hardware problem with single byte transfers over SPI bus + if (size == 1) + size = 2; + + result = spi_cmd(cmd, addr, 0, size,0); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd, write block (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + + result = spi_cmd_rsp(cmd); + if (result != N_OK) { + M2M_ERR("[nmi spi ]: Failed cmd response, write block (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } +#else + result = spi_cmd_complete(cmd, addr, NULL, size, 0); + if (result != N_OK) { + M2M_ERR( "[nmi spi]: Failed cmd, write block (%08x)...\n", addr); + goto _FAIL_; + } +#endif + + /** + Data + **/ + result = spi_data_write(buf, size); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed block data write...\n"); + goto _FAIL_; + } + /** + Data RESP + **/ + result = spi_data_rsp(cmd); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed block data write...\n"); + goto _FAIL_; + } + +_FAIL_: + if(result != N_OK) + { + nm_bsp_sleep(1); + spi_cmd(CMD_RESET, 0, 0, 0, 0); + spi_cmd_rsp(CMD_RESET); + M2M_ERR("Reset and retry %d %lx %d\n",retry,addr,size); + nm_bsp_sleep(1); + retry--; + if(retry) goto _RETRY_; + } + + + return result; +} + +static sint8 spi_read_reg(uint32 addr, uint32 *u32data) +{ + uint8 retry = SPI_RETRY_COUNT; + sint8 result = N_OK; + uint8 cmd = CMD_SINGLE_READ; + uint8 tmp[4]; + uint8 clockless = 0; + +_RETRY_: + + if (addr <= 0xff) + { + /** + NMC1000 clockless registers. + **/ + cmd = CMD_INTERNAL_READ; + clockless = 1; + } + else + { + cmd = CMD_SINGLE_READ; + clockless = 0; + } + +#if defined USE_OLD_SPI_SW + result = spi_cmd(cmd, addr, 0, 4, clockless); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd, read reg (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + + result = spi_cmd_rsp(cmd); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd response, read reg (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + + /* to avoid endianess issues */ + result = spi_data_read(&tmp[0], 4, clockless); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed data read...\n"); + goto _FAIL_; + } +#else + result = spi_cmd_complete(cmd, addr, (uint8*)&tmp[0], 4, clockless); + if (result != N_OK) { + M2M_ERR( "[nmi spi]: Failed cmd, read reg (%08x)...\n", addr); + goto _FAIL_; + } + +#endif + + *u32data = tmp[0] | + ((uint32)tmp[1] << 8) | + ((uint32)tmp[2] << 16) | + ((uint32)tmp[3] << 24); + +_FAIL_: + if(result != N_OK) + { + + nm_bsp_sleep(1); + spi_cmd(CMD_RESET, 0, 0, 0, 0); + spi_cmd_rsp(CMD_RESET); + M2M_ERR("Reset and retry %d %lx\n",retry,addr); + nm_bsp_sleep(1); + retry--; + if(retry) goto _RETRY_; + } + + return result; +} + +static sint8 nm_spi_read(uint32 addr, uint8 *buf, uint16 size) +{ + uint8 cmd = CMD_DMA_EXT_READ; + sint8 result; + uint8 retry = SPI_RETRY_COUNT; +#if defined USE_OLD_SPI_SW + uint8 tmp[2]; + uint8 single_byte_workaround = 0; +#endif + +_RETRY_: + + /** + Command + **/ +#if defined USE_OLD_SPI_SW + if (size == 1) + { + //Workaround hardware problem with single byte transfers over SPI bus + size = 2; + single_byte_workaround = 1; + } + result = spi_cmd(cmd, addr, 0, size,0); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd, read block (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + + result = spi_cmd_rsp(cmd); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd response, read block (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + + /** + Data + **/ + if (single_byte_workaround) + { + result = spi_data_read(tmp, size,0); + buf[0] = tmp[0]; + } + else + result = spi_data_read(buf, size,0); + + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed block data read...\n"); + goto _FAIL_; + } +#else + result = spi_cmd_complete(cmd, addr, buf, size, 0); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd, read block (%08x)...\n", addr); + goto _FAIL_; + } +#endif + +_FAIL_: + if(result != N_OK) + { + nm_bsp_sleep(1); + spi_cmd(CMD_RESET, 0, 0, 0, 0); + spi_cmd_rsp(CMD_RESET); + M2M_ERR("Reset and retry %d %lx %d\n",retry,addr,size); + nm_bsp_sleep(1); + retry--; + if(retry) goto _RETRY_; + } + + return result; +} + +/******************************************** + + Bus interfaces + +********************************************/ + +static void spi_init_pkt_sz(void) +{ + uint32 val32; + + /* Make sure SPI max. packet size fits the defined DATA_PKT_SZ. */ + val32 = nm_spi_read_reg(SPI_BASE+0x24); + val32 &= ~(0x7 << 4); + switch(DATA_PKT_SZ) + { + case 256: val32 |= (0 << 4); break; + case 512: val32 |= (1 << 4); break; + case 1024: val32 |= (2 << 4); break; + case 2048: val32 |= (3 << 4); break; + case 4096: val32 |= (4 << 4); break; + case 8192: val32 |= (5 << 4); break; + + } + nm_spi_write_reg(SPI_BASE+0x24, val32); +} + +sint8 nm_spi_reset(void) +{ + spi_cmd(CMD_RESET, 0, 0, 0, 0); + spi_cmd_rsp(CMD_RESET); + return M2M_SUCCESS; +} + +/* +* @fn nm_spi_init +* @brief Initialize the SPI +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_spi_init(void) +{ + uint32 chipid; + uint32 reg = 0; + + + /** + configure protocol + **/ + gu8Crc_off = 0; + + // TODO: We can remove the CRC trials if there is a definite way to reset + // the SPI to it's initial value. + if (!spi_read_reg(NMI_SPI_PROTOCOL_CONFIG, ®)) { + /* Read failed. Try with CRC off. This might happen when module + is removed but chip isn't reset*/ + gu8Crc_off = 1; + M2M_ERR("[nmi spi]: Failed internal read protocol with CRC on, retyring with CRC off...\n"); + if (!spi_read_reg(NMI_SPI_PROTOCOL_CONFIG, ®)){ + // Reaad failed with both CRC on and off, something went bad + M2M_ERR( "[nmi spi]: Failed internal read protocol...\n"); + return 0; + } + } + if(gu8Crc_off == 0) + { + reg &= ~0xc; /* disable crc checking */ + reg &= ~0x70; + reg |= (0x5 << 4); + if (!spi_write_reg(NMI_SPI_PROTOCOL_CONFIG, reg)) { + M2M_ERR( "[nmi spi]: Failed internal write protocol reg...\n"); + return 0; + } + gu8Crc_off = 1; + } + + /** + make sure can read back chip id correctly + **/ + if (!spi_read_reg(0x1000, &chipid)) { + M2M_ERR("[nmi spi]: Fail cmd read chip id...\n"); + return M2M_ERR_BUS_FAIL; + } + + M2M_DBG("[nmi spi]: chipid (%08x)\n", (unsigned int)chipid); + spi_init_pkt_sz(); + + + return M2M_SUCCESS; +} + +/* +* @fn nm_spi_init +* @brief DeInitialize the SPI +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Samer Sarhan +* @date 27 Feb 2015 +* @version 1.0 +*/ +sint8 nm_spi_deinit(void) +{ + gu8Crc_off = 0; + return M2M_SUCCESS; +} + +/* +* @fn nm_spi_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +uint32 nm_spi_read_reg(uint32 u32Addr) +{ + uint32 u32Val; + + spi_read_reg(u32Addr, &u32Val); + + return u32Val; +} + +/* +* @fn nm_spi_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_spi_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) +{ + sint8 s8Ret; + + s8Ret = spi_read_reg(u32Addr,pu32RetVal); + + if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; + else s8Ret = M2M_ERR_BUS_FAIL; + + return s8Ret; +} + +/* +* @fn nm_spi_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_spi_write_reg(uint32 u32Addr, uint32 u32Val) +{ + sint8 s8Ret; + + s8Ret = spi_write_reg(u32Addr, u32Val); + + if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; + else s8Ret = M2M_ERR_BUS_FAIL; + + return s8Ret; +} + +/* +* @fn nm_spi_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u16Sz +* Number of bytes to read. The buffer size must be >= u16Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_spi_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) +{ + sint8 s8Ret; + + s8Ret = nm_spi_read(u32Addr, puBuf, u16Sz); + + if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; + else s8Ret = M2M_ERR_BUS_FAIL; + + return s8Ret; +} + +/* +* @fn nm_spi_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u16Sz +* Number of bytes to write. The buffer size must be >= u16Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_spi_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) +{ + sint8 s8Ret; + + s8Ret = nm_spi_write(u32Addr, puBuf, u16Sz); + + if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; + else s8Ret = M2M_ERR_BUS_FAIL; + + return s8Ret; +} + +#endif diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmspi.h b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmspi.h new file mode 100644 index 0000000..a1bd4a9 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmspi.h @@ -0,0 +1,132 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 SPI protocol bus APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NMSPI_H_ +#define _NMSPI_H_ + +#include "common/include/nm_common.h" + +#ifdef __cplusplus + extern "C" { +#endif + +/** +* @fn nm_spi_init +* @brief Initialize the SPI +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_init(void); +/** +* @fn nm_spi_reset +* @brief reset the SPI +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_reset(void); + +/** +* @fn nm_spi_deinit +* @brief DeInitialize the SPI +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_deinit(void); + +/** +* @fn nm_spi_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +*/ +uint32 nm_spi_read_reg(uint32 u32Addr); + +/** +* @fn nm_spi_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); + +/** +* @fn nm_spi_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_write_reg(uint32 u32Addr, uint32 u32Val); + +/** +* @fn nm_spi_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u16Sz +* Number of bytes to read. The buffer size must be >= u16Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); + +/** +* @fn nm_spi_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u16Sz +* Number of bytes to write. The buffer size must be >= u16Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); + +#ifdef __cplusplus + } +#endif + +#endif /* _NMSPI_H_ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmuart.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmuart.c new file mode 100644 index 0000000..63541cf --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmuart.c @@ -0,0 +1,536 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 UART protocol bus APIs implementation. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "common/include/nm_common.h" + +#ifdef CONF_WINC_USE_UART + +#include "driver/source/nmuart.h" +#include "bus_wrapper/include/nm_bus_wrapper.h" + +#define HDR_SZ 12 + +static uint8 get_cs(uint8* b, uint8 sz){ + int i; + uint8 cs = 0; + for(i = 0; i < sz; i++) + cs ^= b[i]; + return cs; +} + +/* +* @fn nm_uart_sync_cmd +* @brief Check COM Port +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Dina El Sissy +* @date 13 AUG 2012 +* @version 1.0 +*/ +sint8 nm_uart_sync_cmd(void) +{ + tstrNmUartDefault strUart; + sint8 s8Ret = -1; + uint8 b [HDR_SZ+1]; + uint8 rsz; + uint8 onchip = 0; + + /*read reg*/ + b[0] = 0x12; + + rsz = 1; + strUart.pu8Buf = b; + strUart.u16Sz = 1; + + if(M2M_SUCCESS == nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + strUart.u16Sz = rsz; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + M2M_ERR("failed to send cfg bytes\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + if (b[0] == 0x5a) + { + s8Ret = 0; + onchip = 1; + M2M_INFO("Built-in WINC1500 UART Found\n"); + } + else if(b[0] == 0x5b) + { + s8Ret = 0; + onchip = 0; + M2M_INFO("WINC1500 Serial Bridge Found\n"); + } + /*TODO: this should be the way we read the register since the cortus is little endian*/ + /**pu32RetVal = b[0] | ((uint32)b[1] << 8) | ((uint32)b[2] << 16) | ((uint32)b[3] << 24);*/ + if(s8Ret == M2M_SUCCESS) + s8Ret = (sint8)onchip; + return s8Ret; +} + sint8 nm_uart_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) +{ + tstrNmUartDefault strUart; + sint8 s8Ret = M2M_SUCCESS; + uint8 b [HDR_SZ+1]; + uint8 rsz; + + /*read reg*/ + b[0] = 0xa5; + b[1] = 0; + b[2] = 0; + b[3] = 0; + b[4] = 0; + b[5] = (uint8)(u32Addr & 0x000000ff); + b[6] = (uint8)((u32Addr & 0x0000ff00)>>8); + b[7] = (uint8)((u32Addr & 0x00ff0000)>>16); + b[8] = (uint8)((u32Addr & 0xff000000)>>24); + b[9] = 0; + b[10] = 0; + b[11] = 0; + b[12] = 0; + + b[2] = get_cs(&b[1],HDR_SZ); + + rsz = 4; + strUart.pu8Buf = b; + strUart.u16Sz = sizeof(b); + + if(M2M_SUCCESS == nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + if(!nm_bus_get_chip_type()) + { + strUart.u16Sz = 1; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + if(b[0] == 0xAC) + { + M2M_DBG("Successfully sent the command\n"); + strUart.u16Sz = rsz; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + strUart.u16Sz = rsz; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + } + } + else + { + M2M_ERR("failed to send cfg bytes\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + /*TODO: this should be the way we read the register since the cortus is little endian*/ + /**pu32RetVal = b[0] | ((uint32)b[1] << 8) | ((uint32)b[2] << 16) | ((uint32)b[3] << 24);*/ + + *pu32RetVal = ((uint32)b[0] << 24) | ((uint32)b[1] << 16) | ((uint32)b[2] << 8) | b[3]; + + return s8Ret; +} + +/* +* @fn nm_uart_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +* @author Dina El Sissy +* @date 13 AUG 2012 +* @version 1.0 +*/ +uint32 nm_uart_read_reg(uint32 u32Addr) +{ + uint32 val; + nm_uart_read_reg_with_ret(u32Addr , &val); + return val; +} + +/* +* @fn nm_uart_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Dina El Sissy +* @date 13 AUG 2012 +* @version 1.0 +*/ +sint8 nm_uart_write_reg(uint32 u32Addr, uint32 u32Val) +{ + tstrNmUartDefault strUart; + sint8 s8Ret = M2M_SUCCESS; + uint8 b[HDR_SZ+1]; + + /*write reg*/ + b[0] = 0xa5; + b[1] = 1; + b[2] = 0; + b[3] = 0; + b[4] = 0; + b[5] = (uint8)(u32Addr & 0x000000ff); + b[6] = (uint8)((u32Addr & 0x0000ff00)>>8); + b[7] = (uint8)((u32Addr & 0x00ff0000)>>16); + b[8] = (uint8)((u32Addr & 0xff000000)>>24); + b[9] = (uint8)(u32Val & 0x000000ff); + b[10] = (uint8)((u32Val & 0x0000ff00)>>8); + b[11] = (uint8)((u32Val & 0x00ff0000)>>16); + b[12] = (uint8)((u32Val & 0xff000000)>>24); + + b[2] = get_cs(&b[1],HDR_SZ); + + get_cs(&b[1],HDR_SZ); + + strUart.pu8Buf = b; + strUart.u16Sz = sizeof(b); + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + else + { + if(!nm_bus_get_chip_type()) + { + //check for the ack from the SAMD21 for the packet reception. + strUart.u16Sz = 1; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + if(b[0] == 0xAC) + { + M2M_DBG("Successfully sent the reg write command\n"); + } + else + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + } + + return s8Ret; +} + + +/** +* @fn nm_uart_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u16Sz +* Number of bytes to read. The buffer size must be >= u16Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Dina El Sissy +* @date 13 AUG 2012 +* @version 1.0 +*/ +sint8 nm_uart_read_block(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz) +{ + tstrNmUartDefault strUart; + sint8 s8Ret = M2M_SUCCESS; + uint8 au8Buf[HDR_SZ+1]; + + au8Buf[0] = 0xa5; + au8Buf[1] = 2; + au8Buf[2] = 0; + au8Buf[3] = (uint8)(u16Sz & 0x00ff); + au8Buf[4] = (uint8)((u16Sz & 0xff00)>>8); + au8Buf[5] = (uint8)(u32Addr & 0x000000ff); + au8Buf[6] = (uint8)((u32Addr & 0x0000ff00)>>8); + au8Buf[7] = (uint8)((u32Addr & 0x00ff0000)>>16); + au8Buf[8] = (uint8)((u32Addr & 0xff000000)>>24); + au8Buf[9] = 0; + au8Buf[10] = 0; + au8Buf[11] = 0; + au8Buf[12] = 0; + + au8Buf[2] = get_cs(&au8Buf[1],HDR_SZ); + + strUart.pu8Buf = au8Buf; + strUart.u16Sz = sizeof(au8Buf); + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + else + { + if(!nm_bus_get_chip_type()) + { + //check for the ack from the SAMD21 for the packet reception. + strUart.u16Sz = 1; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + if(au8Buf[0] == 0xAC) + { + M2M_DBG("Successfully sent the block read command\n"); + strUart.pu8Buf = pu8Buf; + strUart.u16Sz = u16Sz; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + M2M_ERR("read error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + M2M_ERR("write error (Error sending the block read command)\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + strUart.pu8Buf = pu8Buf; + strUart.u16Sz = u16Sz; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + M2M_ERR("read error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + } + + return s8Ret; +} + +/** +* @fn nm_uart_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u16Sz +* Number of bytes to write. The buffer size must be >= u16Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Dina El Sissy +* @date 13 AUG 2012 +* @version 1.0 +*/ +sint8 nm_uart_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) +{ + tstrNmUartDefault strUart; + sint8 s8Ret = M2M_SUCCESS; + static uint8 au8Buf[HDR_SZ+1]; + + au8Buf[0] = 0xa5; + au8Buf[1] = 3; + au8Buf[2] = 0; + au8Buf[3] = (uint8)(u16Sz & 0x00ff); + au8Buf[4] = (uint8)((u16Sz & 0xff00)>>8); + au8Buf[5] = (uint8)(u32Addr & 0x000000ff); + au8Buf[6] = (uint8)((u32Addr & 0x0000ff00)>>8); + au8Buf[7] = (uint8)((u32Addr & 0x00ff0000)>>16); + au8Buf[8] = (uint8)((u32Addr & 0xff000000)>>24); + au8Buf[9] = 0; + au8Buf[10] = 0; + au8Buf[11] = 0; + au8Buf[12] = 0; + + au8Buf[2] = get_cs(&au8Buf[1],HDR_SZ); + + strUart.pu8Buf = au8Buf; + strUart.u16Sz = sizeof(au8Buf); + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + else + { + if(!nm_bus_get_chip_type()) + { + //check for the ack from the SAMD21 for the packet reception. + strUart.u16Sz = 1; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + if(au8Buf[0] == 0xAC) + { + M2M_DBG("Successfully sent the block Write command\n"); + strUart.pu8Buf = puBuf; + strUart.u16Sz = u16Sz; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + else + { + //check for the ack from the SAMD21 for the payload reception. + strUart.pu8Buf = au8Buf; + strUart.u16Sz = 1; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + if(au8Buf[0] == 0xAC) + { + M2M_DBG("Successfully sent the data payload\n"); + } + else + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + } + else + { + M2M_ERR("write error (Error sending the block write command)\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + strUart.pu8Buf = puBuf; + strUart.u16Sz = u16Sz; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + } + return s8Ret; +} + +/** +* @fn nm_uart_reconfigure +* @brief Reconfigures the UART interface +* @param [in] ptr +* Pointer to a DWORD containing baudrate at this moment. +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Viswanathan Murugesan +* @date 22 OCT 2014 +* @version 1.0 +*/ +sint8 nm_uart_reconfigure(void *ptr) +{ + tstrNmUartDefault strUart; + sint8 s8Ret = M2M_SUCCESS; + uint8 b[HDR_SZ+1]; + + /*write reg*/ + b[0] = 0xa5; + b[1] = 5; + b[2] = 0; + b[3] = 0; + b[4] = 0; + b[5] = 0; + b[6] = 0; + b[7] = 0; + b[8] = 0; + b[9] = (uint8)((*(unsigned long *)ptr) & 0x000000ff); + b[10] = (uint8)(((*(unsigned long *)ptr) & 0x0000ff00)>>8); + b[11] = (uint8)(((*(unsigned long *)ptr) & 0x00ff0000)>>16); + b[12] = (uint8)(((*(unsigned long *)ptr) & 0xff000000)>>24); + + b[2] = get_cs(&b[1],HDR_SZ); + + get_cs(&b[1],HDR_SZ); + + strUart.pu8Buf = b; + strUart.u16Sz = sizeof(b); + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + else + { + if(!nm_bus_get_chip_type()) + { + //check for the ack from the SAMD21 for the packet reception. + strUart.u16Sz = 1; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + if(b[0] == 0xAC) + { + M2M_DBG("Successfully sent the UART reconfigure command\n"); + } + else + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + } + + return s8Ret; +} +#endif +/* EOF */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmuart.h b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmuart.h new file mode 100644 index 0000000..8f07d39 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmuart.h @@ -0,0 +1,118 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 UART protocol bus APIs implementation. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NMUART_H_ +#define _NMUART_H_ + +#include "common/include/nm_common.h" + +/* +* @fn nm_uart_sync_cmd +* @brief Check COM Port +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_uart_sync_cmd(void); +/** +* @fn nm_uart_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +*/ +uint32 nm_uart_read_reg(uint32 u32Addr); + +/** +* @fn nm_uart_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_uart_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); + +/** +* @fn nm_uart_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_uart_write_reg(uint32 u32Addr, uint32 u32Val); + +/** +* @fn nm_uart_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u16Sz +* Number of bytes to read. The buffer size must be >= u16Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_uart_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); + +/** +* @fn nm_uart_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u16Sz +* Number of bytes to write. The buffer size must be >= u16Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_uart_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); + +/** +* @fn nm_uart_reconfigure +* @brief Reconfigures the UART interface +* @param [in] ptr +* Pointer to a DWORD containing baudrate at this moment. +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_uart_reconfigure(void *ptr); +#endif /* _NMI2C_H_ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h b/feather_sensor_lte/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h new file mode 100644 index 0000000..933ad67 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h @@ -0,0 +1,461 @@ +/** + * + * \file + * + * \brief BSD compatible socket interface internal types. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +#ifndef __M2M_SOCKET_HOST_IF_H__ +#define __M2M_SOCKET_HOST_IF_H__ + + +#ifdef __cplusplus +extern "C" { +#endif + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#ifndef _BOOT_ +#ifndef _FIRMWARE_ +#include "socket/include/socket.h" +#else +#include "m2m_types.h" +#endif +#endif + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/* + * HOSTNAME_MAX_SIZE is defined here and also in host_drv/socket/include/socket.h + * The two definitions must match. +*/ +#ifdef _FIRMWARE_ +#define HOSTNAME_MAX_SIZE (64) +#endif + +#define SSL_MAX_OPT_LEN HOSTNAME_MAX_SIZE + + + +#define SOCKET_CMD_INVALID 0x00 +/*!< + Invlaid Socket command value. +*/ + + +#define SOCKET_CMD_BIND 0x41 +/*!< + Socket Binding command value. +*/ + + +#define SOCKET_CMD_LISTEN 0x42 +/*!< + Socket Listening command value. +*/ + + +#define SOCKET_CMD_ACCEPT 0x43 +/*!< + Socket Accepting command value. +*/ + + +#define SOCKET_CMD_CONNECT 0x44 +/*!< + Socket Connecting command value. +*/ + + +#define SOCKET_CMD_SEND 0x45 +/*!< + Socket send command value. +*/ + + +#define SOCKET_CMD_RECV 0x46 +/*!< + Socket Recieve command value. +*/ + + +#define SOCKET_CMD_SENDTO 0x47 +/*!< + Socket sendTo command value. +*/ + + +#define SOCKET_CMD_RECVFROM 0x48 +/*!< + Socket RecieveFrom command value. +*/ + + +#define SOCKET_CMD_CLOSE 0x49 +/*!< + Socket Close command value. +*/ + + +#define SOCKET_CMD_DNS_RESOLVE 0x4A +/*!< + Socket DNS Resolve command value. +*/ + + +#define SOCKET_CMD_SSL_CONNECT 0x4B +/*!< + SSL-Socket Connect command value. +*/ + + +#define SOCKET_CMD_SSL_SEND 0x4C +/*!< + SSL-Socket Send command value. +*/ + + +#define SOCKET_CMD_SSL_RECV 0x4D +/*!< + SSL-Socket Recieve command value. +*/ + + +#define SOCKET_CMD_SSL_CLOSE 0x4E +/*!< + SSL-Socket Close command value. +*/ + + +#define SOCKET_CMD_SET_SOCKET_OPTION 0x4F +/*!< + Set Socket Option command value. +*/ + + +#define SOCKET_CMD_SSL_CREATE 0x50 +/*!< +*/ + + +#define SOCKET_CMD_SSL_SET_SOCK_OPT 0x51 +/*!< +*/ + + +#define SOCKET_CMD_PING 0x52 +/*!< +*/ + + +#define SOCKET_CMD_SSL_SET_CS_LIST 0x53 +/*!< + Recommend instead using @ref M2M_SSL_REQ_SET_CS_LIST and + associated response @ref M2M_SSL_RESP_SET_CS_LIST +*/ + + +#define SOCKET_CMD_SSL_BIND 0x54 +/*!< +*/ + + +#define SOCKET_CMD_SSL_EXP_CHECK 0x55 +/*!< +*/ + + + +#define PING_ERR_SUCCESS 0 +#define PING_ERR_DEST_UNREACH 1 +#define PING_ERR_TIMEOUT 2 + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +/*! +* @brief +*/ +typedef struct{ + uint16 u16Family; + uint16 u16Port; + uint32 u32IPAddr; +}tstrSockAddr; + + +typedef sint8 SOCKET; +typedef tstrSockAddr tstrUIPSockAddr; + + + +/*! +@struct \ + tstrDnsReply + +@brief + DNS Reply, contains hostName and HostIP. +*/ +typedef struct{ + char acHostName[HOSTNAME_MAX_SIZE]; + uint32 u32HostIP; +}tstrDnsReply; + + +/*! +@brief +*/ +typedef struct{ + tstrSockAddr strAddr; + SOCKET sock; + uint8 u8Void; + uint16 u16SessionID; +}tstrBindCmd; + + +/*! +@brief +*/ +typedef struct{ + SOCKET sock; + sint8 s8Status; + uint16 u16SessionID; +}tstrBindReply; + + +/*! +* @brief +*/ +typedef struct{ + SOCKET sock; + uint8 u8BackLog; + uint16 u16SessionID; +}tstrListenCmd; + + +/*! +@struct \ + tstrSocketRecvMsg + +@brief Socket recv status. + + It is passed to the APPSocketEventHandler with SOCKET_MSG_RECV or SOCKET_MSG_RECVFROM message type + in a response to a user call to the recv or recvfrom. + If the received data from the remote peer is larger than the USER Buffer size (given at recv call), the data is + delivered to the user in a number of consecutive chunks according to the USER Buffer size. +*/ +typedef struct{ + SOCKET sock; + sint8 s8Status; + uint16 u16SessionID; +}tstrListenReply; + + +/*! +* @brief +*/ +typedef struct{ + tstrSockAddr strAddr; + SOCKET sListenSock; + SOCKET sConnectedSock; + uint16 u16AppDataOffset; + /*!< + In further packet send requests the host interface should put the user application + data at this offset in the allocated shared data packet. + */ +}tstrAcceptReply; + + +/*! +* @brief +*/ +typedef struct{ + tstrSockAddr strAddr; + SOCKET sock; + uint8 u8SslFlags; + uint16 u16SessionID; +}tstrConnectCmd; + + +/*! +@struct \ + tstrConnectReply + +@brief + Connect Reply, contains sock number and error value +*/ +typedef struct{ + SOCKET sock; + sint8 s8Error; + uint16 u16AppDataOffset; + /*!< + In further packet send requests the host interface should put the user application + data at this offset in the allocated shared data packet. + */ +}tstrConnectReply; + + +/*! +@brief +*/ +typedef struct{ + SOCKET sock; + uint8 u8Void; + uint16 u16DataSize; + tstrSockAddr strAddr; + uint16 u16SessionID; + uint16 u16Void; +}tstrSendCmd; + + +/*! +@struct \ + tstrSendReply + +@brief + Send Reply, contains socket number and number of sent bytes. +*/ +typedef struct{ + SOCKET sock; + uint8 u8Void; + sint16 s16SentBytes; + uint16 u16SessionID; + uint16 u16Void; +}tstrSendReply; + + +/*! +* @brief +*/ +typedef struct{ + uint32 u32Timeoutmsec; + SOCKET sock; + uint8 u8Void; + uint16 u16SessionID; +}tstrRecvCmd; + + +/*! +@struct +@brief +*/ +typedef struct{ + tstrSockAddr strRemoteAddr; + sint16 s16RecvStatus; + uint16 u16DataOffset; + SOCKET sock; + uint8 u8Void; + uint16 u16SessionID; +}tstrRecvReply; + + +/*! +* @brief +*/ +typedef struct{ + uint32 u32OptionValue; + SOCKET sock; + uint8 u8Option; + uint16 u16SessionID; +}tstrSetSocketOptCmd; + + +typedef struct{ + SOCKET sslSock; + uint8 __PAD24__[3]; +}tstrSSLSocketCreateCmd; + + +/*! +* @brief +*/ +typedef struct{ + SOCKET sock; + uint8 u8Option; + uint16 u16SessionID; + uint32 u32OptLen; + uint8 au8OptVal[SSL_MAX_OPT_LEN]; +}tstrSSLSetSockOptCmd; + + +/*! +*/ +typedef struct{ + uint32 u32DestIPAddr; + uint32 u32CmdPrivate; + uint16 u16PingCount; + uint8 u8TTL; + uint8 __PAD8__; +}tstrPingCmd; + + +typedef struct{ + uint32 u32IPAddr; + uint32 u32CmdPrivate; + uint32 u32RTT; + uint16 u16Success; + uint16 u16Fail; + uint8 u8ErrorCode; + uint8 __PAD24__[3]; +}tstrPingReply; + + +/*! +@struct\ + tstrSslCertExpSettings + +@brief SSL Certificate Expiry Validation Settings + +@sa tenuSslCertExpSettings +*/ +typedef struct{ + uint32 u32CertExpValidationOpt; + /*!< + See @tenuSslCertExpSettings for possible values. + */ +}tstrSslCertExpSettings; + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* __M2M_SOCKET_HOST_IF_H__ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/socket/include/socket.h b/feather_sensor_lte/libraries/WiFi101/src/socket/include/socket.h new file mode 100644 index 0000000..837959a --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/socket/include/socket.h @@ -0,0 +1,2065 @@ +/** + * + * \file + * + * \brief WINC BSD compatible Socket Interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef __SOCKET_H__ +#define __SOCKET_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup SocketHeader Socket + * BSD compatible socket interface beftween the host layer and the network + * protocol stacks in the firmware. + * These functions are used by the host application to send or receive + * packets and to do other socket operations. + */ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "common/include/nm_common.h" +#include "driver/include/m2m_types.h" + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/** + * @defgroup SocketDefines Defines + * @ingroup SocketHeader + */ + +/** @defgroup IPDefines TCP/IP Defines + * @ingroup SocketDefines + * The following list of macros are used to define constants used throughout the socket layer. + * @{ + */ + +/* + * HOSTNAME_MAX_SIZE is defined here and also in host_drv/socket/include/m2m_socket_host_if.h + * The two definitions must match. +*/ +#define HOSTNAME_MAX_SIZE 64 +/*!< + Maximum allowed size for a host domain name passed to the function gethostbyname @ref gethostbyname. + command value. Used with the setsockopt function. + +*/ + +#define SOCKET_BUFFER_MAX_LENGTH 1400 +/*!< + Maximum allowed size for a socket data buffer. Used with @ref send socket + function to ensure that the buffer sent is within the allowed range. +*/ + +#define AF_INET 2 +/*!< + The AF_INET is the address family used for IPv4. An IPv4 transport address is specified with the @ref sockaddr_in structure. + (It is the only supported type for the current implementation.) +*/ + + +#define SOCK_STREAM 1 +/*!< + One of the IPv4 supported socket types for reliable connection-oriented stream connection. + Passed to the @ref socket function for the socket creation operation. +*/ + +#define SOCK_DGRAM 2 +/*!< + One of the IPv4 supported socket types for unreliable connectionless datagram connection. + Passed to the @ref socket function for the socket creation operation. +*/ + + +#define SOCKET_FLAGS_SSL 0x01 +/*!< + This flag shall be passed to the socket API for SSL session. +*/ + +#define TCP_SOCK_MAX (7) +/*!< + Maximum number of simultaneous TCP sockets. +*/ + +#define UDP_SOCK_MAX 4 +/*!< + Maximum number of simultaneous UDP sockets. +*/ + +#define MAX_SOCKET (TCP_SOCK_MAX + UDP_SOCK_MAX) +/*!< + Maximum number of Sockets. +*/ + +#define SOL_SOCKET 1 +/*!< + Socket option. + Used with the @ref setsockopt function +*/ + +#define SOL_SSL_SOCKET 2 +/*!< + SSL Socket option level. + Used with the @ref setsockopt function +*/ + +#define SO_SET_UDP_SEND_CALLBACK 0x00 +/*!< + Socket option used by the application to enable/disable + the use of UDP send callbacks. + Used with the @ref setsockopt function. +*/ + +#define IP_ADD_MEMBERSHIP 0x01 +/*!< + Set Socket Option Add Membership command value (to join a multicast group). + Used with the @ref setsockopt function. +*/ + + +#define IP_DROP_MEMBERSHIP 0x02 +/*!< + Set Socket Option Drop Membership command value (to leave a multicast group). + Used with the @ref setsockopt function. +*/ + //@} + + + +/** + * @defgroup TLSDefines TLS Defines + * @ingroup SocketDefines + */ + + + +/** @defgroup SSLSocketOptions TLS Socket Options + * @ingroup TLSDefines + * The following list of macros are used to define SSL Socket options. + * @{ + * @sa setsockopt + */ + +#define SO_SSL_BYPASS_X509_VERIF 0x01 +/*!< + Allow an opened SSL socket to bypass the X509 certificate + verification process. + It is highly required NOT to use this socket option in production + software applications. It is supported for debugging and testing + purposes. + The option value should be casted to int type and it is handled + as a boolean flag. +*/ + + +#define SO_SSL_SNI 0x02 +/*!< + Set the Server Name Indicator (SNI) for an SSL socket. The + SNI is a NULL terminated string containing the server name + associated with the connection. It must not exceed the size + of HOSTNAME_MAX_SIZE. +*/ + + +#define SO_SSL_ENABLE_SESSION_CACHING 0x03 +/*!< + This option allow the TLS to cache the session information for fast + TLS session establishment in future connections using the + TLS Protocol session resume features. +*/ + + +#define SO_SSL_ENABLE_SNI_VALIDATION 0x04 +/*!< + Enable SNI validation against the server's certificate subject + common name. If there is no SNI provided (via the SO_SSL_SNI + option), setting this option does nothing. +*/ + + +//@} + + + +/** @defgroup LegacySSLCipherSuite Legacy names for TLS Cipher Suite IDs + * @ingroup TLSDefines + * The following list of macros MUST NOT be used. Instead use the new names under SSLCipherSuiteID + * @sa sslSetActiveCipherSuites + * @{ + */ + +#define SSL_ENABLE_RSA_SHA_SUITES 0x01 +/*!< + Enable RSA Hmac_SHA based Cipher suites. For example, + TLS_RSA_WITH_AES_128_CBC_SHA +*/ + + +#define SSL_ENABLE_RSA_SHA256_SUITES 0x02 +/*!< + Enable RSA Hmac_SHA256 based Cipher suites. For example, + TLS_RSA_WITH_AES_128_CBC_SHA256 +*/ + + +#define SSL_ENABLE_DHE_SHA_SUITES 0x04 +/*!< + Enable DHE Hmac_SHA based Cipher suites. For example, + TLS_DHE_RSA_WITH_AES_128_CBC_SHA +*/ + + +#define SSL_ENABLE_DHE_SHA256_SUITES 0x08 +/*!< + Enable DHE Hmac_SHA256 based Cipher suites. For example, + TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 +*/ + + +#define SSL_ENABLE_RSA_GCM_SUITES 0x10 +/*!< + Enable RSA AEAD based Cipher suites. For example, + TLS_RSA_WITH_AES_128_GCM_SHA256 +*/ + + +#define SSL_ENABLE_DHE_GCM_SUITES 0x20 +/*!< + Enable DHE AEAD based Cipher suites. For example, + TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 +*/ + + +#define SSL_ENABLE_ALL_SUITES 0x0000003F +/*!< + Enable all possible supported cipher suites. +*/ + +//@} + + + +/** @defgroup SSLCipherSuiteID TLS Cipher Suite IDs + * @ingroup TLSDefines + * The following list of macros defined the list of supported TLS Cipher suites. + * Each MACRO defines a single Cipher suite. + * @sa m2m_ssl_set_active_ciphersuites + * @{ + */ + +#define SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA NBIT0 +#define SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 NBIT1 +#define SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA NBIT2 +#define SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 NBIT3 +#define SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 NBIT4 +#define SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 NBIT5 +#define SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA NBIT6 +#define SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 NBIT7 +#define SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA NBIT8 +#define SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 NBIT9 +#define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA NBIT10 +#define SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA NBIT11 +#define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 NBIT12 +#define SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 NBIT13 +#define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 NBIT14 +#define SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 NBIT15 + + + +#define SSL_ECC_ONLY_CIPHERS \ +(\ + SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 \ +) +/*!< + All ciphers that use ECC crypto only. This execuldes ciphers that use RSA. They use ECDSA instead. + These ciphers are turned off by default at startup. + The application may enable them if it has an ECC math engine (like ATECC508). +*/ +#define SSL_ECC_ALL_CIPHERS \ +(\ + SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA | \ + SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 | \ + SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 \ +) +/*!< + All supported ECC Ciphers including those ciphers that depend on RSA and ECC. + These ciphers are turned off by default at startup. + The application may enable them if it has an ECC math engine (like ATECC508). +*/ + +#define SSL_NON_ECC_CIPHERS_AES_128 \ +(\ + SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA | \ + SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA | \ + SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 | \ + SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 \ +) +/*!< + All supported AES-128 Ciphers (ECC ciphers are not counted). This is the default active group after startup. +*/ + + +#define SSL_ECC_CIPHERS_AES_256 \ +(\ + SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA \ +) +/*!< + ECC AES-256 supported ciphers. +*/ + + +#define SSL_NON_ECC_CIPHERS_AES_256 \ +(\ + SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA | \ + SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 | \ + SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA | \ + SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 \ +) +/*!< + AES-256 Ciphers. + This group is disabled by default at startup because the WINC1500 HW Accelerator + supports only AES-128. If the application needs to force AES-256 cipher support, + it could enable them (or any of them) explicitly by calling sslSetActiveCipherSuites. +*/ + + +#define SSL_CIPHER_ALL \ +(\ + SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA | \ + SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA | \ + SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 | \ + SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 | \ + SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA | \ + SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 | \ + SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA | \ + SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 | \ + SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA | \ + SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 | \ + SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 | \ + SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA \ +) +/*!< + Turn On All TLS Ciphers. +*/ + + + //@} + + + + +/************** +Socket Errors +**************/ +/**@defgroup SocketErrorCode Error Codes + * @ingroup SocketHeader + * The following list of macros are used to define the possible error codes returned as a result of a call to a socket function. + * Errors are listed in numerical order with the error macro name. + * @{ + */ +#define SOCK_ERR_NO_ERROR 0 +/*!< + Successful socket operation +*/ + + +#define SOCK_ERR_INVALID_ADDRESS -1 +/*!< + Socket address is invalid. The socket operation cannot be completed successfully without specifying a specific address + For example: bind is called without specifying a port number +*/ + + +#define SOCK_ERR_ADDR_ALREADY_IN_USE -2 +/*!< + Socket operation cannot bind on the given address. With socket operations, only one IP address per socket is permitted. + Any attempt for a new socket to bind with an IP address already bound to another open socket, + will return the following error code. States that bind operation failed. +*/ + + +#define SOCK_ERR_MAX_TCP_SOCK -3 +/*!< + Exceeded the maximum number of TCP sockets. A maximum number of TCP sockets opened simultaneously is defined through TCP_SOCK_MAX. + It is not permitted to exceed that number at socket creation. Identifies that @ref socket operation failed. +*/ + + +#define SOCK_ERR_MAX_UDP_SOCK -4 +/*!< + Exceeded the maximum number of UDP sockets. A maximum number of UDP sockets opened simultaneously is defined through UDP_SOCK_MAX. + It is not permitted to exceed that number at socket creation. Identifies that @ref socket operation failed +*/ + + +#define SOCK_ERR_INVALID_ARG -6 +/*!< + An invalid argument is passed to a function. +*/ + + +#define SOCK_ERR_MAX_LISTEN_SOCK -7 +/*!< + Exceeded the maximum number of TCP passive listening sockets. + Identifies Identifies that @ref listen operation failed. +*/ + + +#define SOCK_ERR_INVALID -9 +/*!< + The requested socket operation is not valid in the + current socket state. + For example: @ref accept is called on a TCP socket before @ref bind or @ref listen. +*/ + + +#define SOCK_ERR_ADDR_IS_REQUIRED -11 +/*!< + Destination address is required. Failure to provide the socket address required for the socket operation to be completed. + It is generated as an error to the @ref sendto function when the address required to send the data to is not known. +*/ + + +#define SOCK_ERR_CONN_ABORTED -12 +/*!< + The socket is closed by the peer. The local socket is + closed also. +*/ + + +#define SOCK_ERR_TIMEOUT -13 +/*!< + The socket pending operation has Timedout. +*/ + + +#define SOCK_ERR_BUFFER_FULL -14 +/*!< + No buffer space available to be used for the requested socket operation. +*/ + +#ifdef _NM_BSP_BIG_END + +#define _htonl(m) (m) +#define _htons(A) (A) + +#else + +#define _htonl(m) \ + (uint32)(((uint32)(m << 24)) | ((uint32)((m & 0x0000FF00) << 8)) | ((uint32)((m & 0x00FF0000) >> 8)) | ((uint32)(m >> 24))) +/*!< + Convert a 4-byte integer from the host representation to the Network byte order representation. +*/ + + +#define _htons(A) (uint16)((((uint16) (A)) << 8) | (((uint16) (A)) >> 8)) +/*!< + Convert a 2-byte integer (short) from the host representation to the Network byte order representation. +*/ + + +#endif + + +#define _ntohl _htonl +/*!< + Convert a 4-byte integer from the Network byte order representation to the host representation . +*/ + + +#define _ntohs _htons +/*!< + Convert a 2-byte integer from the Network byte order representation to the host representation . +*/ + //@} + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/** @defgroup SocketEnums DataTypes + * @ingroup SocketHeader + * Specific Enumeration-typedefs used for socket operations + * @{ */ + +/*! +@typedef \ + SOCKET + +@brief + Definition for socket handler data type. + Socket ID,used with all socket operations to uniquely identify the socket handler. + Such an ID is uniquely assigned at socket creation when calling @ref socket operation. +*/ +typedef sint8 SOCKET; + + + +/*! +@struct \ + in_addr + +@brief + IPv4 address representation. + + This structure is used as a placeholder for IPV4 address in other structures. +@see + sockaddr_in +*/ +typedef struct{ + uint32 s_addr; + /*!< + Network Byte Order representation of the IPv4 address. For example, + the address "192.168.0.10" is represented as 0x0A00A8C0. + */ +}in_addr; + + +/*! +@struct \ + sockaddr + +@brief + Generic socket address structure. + +@see + sockaddr_in +*/ +struct sockaddr{ + uint16 sa_family; + /*!< +Socket address family. + */ + uint8 sa_data[14]; + /*!< + Maximum size of all the different socket address structures. + */ +}; + + +/*! +@struct \ + sockaddr_in + +@brief + Socket address structure for IPV4 addresses. Used to specify socket address information to which to connect to. + Can be cast to @ref sockaddr structure. +*/ +struct sockaddr_in{ + uint16 sin_family; + /*!< + Specifies the address family(AF). + Members of AF_INET address family are IPv4 addresses. + Hence,the only supported value for this is AF_INET. + */ + uint16 sin_port; + /*!< + Port number of the socket. + Network sockets are identified by a pair of IP addresses and port number. + It must be set in the Network Byte Order format , @ref _htons (e.g. _htons(80)). + Can NOT have zero value. + */ + in_addr sin_addr; + /*!< + IP Address of the socket. + The IP address is of type @ref in_addr structure. + Can be set to "0" to accept any IP address for server operation. non zero otherwise. + */ + uint8 sin_zero[8]; + /*!< + Padding to make structure the same size as @ref sockaddr. + */ +}; + //@} +/**@defgroup AsyncCalback Asynchronous Events + * @ingroup SocketEnums + * Specific Enumeration used for asynchronous operations + * @{ */ +/*! +@enum \ + tenuSocketCallbackMsgType + +@brief + Asynchronous APIs, make use of callback functions, in-order to return back the results once the corresponding socket operation is completed. + Hence resuming the normal execution of the application code while the socket operation returns the results. + Callback functions expect event messages to be passed in, in-order to identify the operation they're returning the results for. + The following enum identifies the type of events that are received in the callback function. + + Application Use: + In order for application developers to handle the pending events from the network controller through the callback functions. + A function call must be made to the function @ref m2m_wifi_handle_events at least once for each socket operation. + +@see + bind + listen + accept + connect + send + recv + +*/ +typedef enum{ + SOCKET_MSG_BIND = 1, + /*!< + Bind socket event. + */ + SOCKET_MSG_LISTEN, + /*!< + Listen socket event. + */ + SOCKET_MSG_DNS_RESOLVE, + /*!< + DNS Resolution event. + */ + SOCKET_MSG_ACCEPT, + /*!< + Accept socket event. + */ + SOCKET_MSG_CONNECT, + /*!< + Connect socket event. + */ + SOCKET_MSG_RECV, + /*!< + Receive socket event. + */ + SOCKET_MSG_SEND, + /*!< + Send socket event. + */ + SOCKET_MSG_SENDTO, + /*!< + sendto socket event. + */ + SOCKET_MSG_RECVFROM + /*!< + Recvfrom socket event. + */ +}tenuSocketCallbackMsgType; + + +/*! +@struct \ + tstrSocketBindMsg + +@brief Socket bind status. + + An asynchronous call to the @ref bind socket operation, returns information through this structure in response. + This structure together with the event @ref SOCKET_MSG_BIND are passed in paramters to the callback function. +@see + bind + +*/ +typedef struct{ + sint8 status; + /*!< + The result of the bind operation. + Holding a value of ZERO for a successful bind or otherwise a negative + error code corresponding to the type of error. + */ +}tstrSocketBindMsg; + + +/*! +@struct \ + tstrSocketListenMsg + +@brief Socket listen status. + + Socket listen information is returned through this structure in response to the asynchronous call to the @ref listen function. + This structure together with the event @ref SOCKET_MSG_LISTEN are passed-in parameters to the callback function. +@see + listen +*/ +typedef struct{ + sint8 status; + /*!< + Holding a value of ZERO for a successful listen or otherwise a negative + error code corresponding to the type of error. + */ +}tstrSocketListenMsg; + + + +/*! +@struct \ + tstrSocketAcceptMsg + +@brief Socket accept status. + + Socket accept information is returned through this structure in response to the asynchronous call to the @ref accept function. + This structure together with the event @ref SOCKET_MSG_ACCEPT are passed-in parameters to the callback function. +*/ +typedef struct{ + SOCKET sock; + /*!< + On a successful @ref accept operation, the return information is the socket ID for the accepted connection with the remote peer. + Otherwise a negative error code is returned to indicate failure of the accept operation. + */ + struct sockaddr_in strAddr; + /*!< + Socket address structure for the remote peer. + */ +}tstrSocketAcceptMsg; + + +/*! +@struct \ + tstrSocketConnectMsg + +@brief Socket connect status. + + Socket connect information is returned through this structure in response to the asynchronous call to the @ref connect socket function. + This structure together with the event @ref SOCKET_MSG_CONNECT are passed-in parameters to the callback function. +*/ +typedef struct{ + SOCKET sock; + /*!< + Socket ID referring to the socket passed to the connect function call. + */ + sint8 s8Error; + /*!< + Connect error code. + Holding a value of ZERO for a successful connect or otherwise a negative + error code corresponding to the type of error. + */ +}tstrSocketConnectMsg; + + +/*! +@struct \ + tstrSocketRecvMsg + +@brief Socket recv status. + + Socket receive information is returned through this structure in response to the asynchronous call to the recv or recvfrom socket functions. + This structure together with the events @ref SOCKET_MSG_RECV or @ref SOCKET_MSG_RECVFROM are passed-in parameters to the callback function. +@remark + In case the received data from the remote peer is larger than the USER buffer size defined during the asynchronous call to the @ref recv function, the data is + delivered to the user in a number of consecutive chunks according to the USER Buffer size. + a negative or zero buffer size indicates an error with the following code: + @ref SOCK_ERR_NO_ERROR : Socket connection closed + @ref SOCK_ERR_CONN_ABORTED : Socket connection aborted + @SOCK_ERR_TIMEOUT : Socket receive timed out +*/ +typedef struct{ + uint8 *pu8Buffer; + /*!< + Pointer to the USER buffer (passed to @ref recv and @ref recvfrom function) containing the received data chunk. + */ + sint16 s16BufferSize; + /*!< + The received data chunk size. + Holds a negative value if there is a receive error or ZERO on success upon reception of close socket message. + */ + uint16 u16RemainingSize; + /*!< + The number of bytes remaining in the current @ref recv operation. + */ + struct sockaddr_in strRemoteAddr; + /*!< + Socket address structure for the remote peer. It is valid for @ref SOCKET_MSG_RECVFROM event. + */ +}tstrSocketRecvMsg; + + +/*! +@typedef \ + tpfAppSocketCb + +@brief + The main socket application callback function. Applications register their main socket application callback through this function by calling @ref registerSocketCallback. + In response to events received, the following callback function is called to handle the corresponding asynchronous function called. Example: @ref bind, @ref connect,...etc. + +@param [in] sock + Socket ID for the callback. + + The socket callback function is called whenever a new event is recived in response + to socket operations. + +@param [in] u8Msg + Socket event type. Possible values are: + - @ref SOCKET_MSG_BIND + - @ref SOCKET_MSG_LISTEN + - @ref SOCKET_MSG_ACCEPT + - @ref SOCKET_MSG_CONNECT + - @ref SOCKET_MSG_RECV + - @ref SOCKET_MSG_SEND + - @ref SOCKET_MSG_SENDTO + - @ref SOCKET_MSG_RECVFROM + +@param [in] pvMsg + Pointer to message structure. Existing types are: + - tstrSocketBindMsg + - tstrSocketListenMsg + - tstrSocketAcceptMsg + - tstrSocketConnectMsg + - tstrSocketRecvMsg + +@see + tenuSocketCallbackMsgType + tstrSocketRecvMsg + tstrSocketConnectMsg + tstrSocketAcceptMsg + tstrSocketListenMsg + tstrSocketBindMsg +*/ +typedef void (*tpfAppSocketCb) (SOCKET sock, uint8 u8Msg, void * pvMsg); + + +/*! +@typedef \ + tpfAppResolveCb + +@brief + DNS resolution callback function. + Applications requiring DNS resolution should register their callback through this function by calling @ref registerSocketCallback. + The following callback is triggered in response to asynchronous call to the @ref gethostbyname function (DNS Resolution callback). + +@param [in] pu8DomainName + Domain name of the host. + +@param [in] u32ServerIP + Server IPv4 address encoded in NW byte order format. If it is Zero, then the DNS resolution failed. +*/ +typedef void (*tpfAppResolveCb) (uint8* pu8DomainName, uint32 u32ServerIP); + +/*! +@typedef \ + tpfPingCb + +@brief PING Callback + + The function delivers the ping statistics for the sent ping triggered by calling + m2m_ping_req. + +@param [in] u32IPAddr + Destination IP. + +@param [in] u32RTT + Round Trip Time. + +@param [in] u8ErrorCode + Ping error code. It may be one of: + - PING_ERR_SUCCESS + - PING_ERR_DEST_UNREACH + - PING_ERR_TIMEOUT +*/ +typedef void (*tpfPingCb)(uint32 u32IPAddr, uint32 u32RTT, uint8 u8ErrorCode); + + /**@}*/ +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/** \defgroup SocketAPI Function + * @ingroup SocketHeader + */ + +/** @defgroup SocketInitalizationFn socketInit + * @ingroup SocketAPI + * The function performs the necessary initializations for the socket library through the following steps: + - A check made by the global variable gbSocketInit, ensuring that initialization for sockets is performed only once, + in-order to prevent reseting the socket instances already created in the global socket array (gastrSockets). + - Zero initializations to the global socket array (gastrSockets), which holds the list of TCP sockets. + - Registers the socket (Host Interface)hif callback function through the call to the hif_register_cb function. + This facilitates handling all of the socket related functions received through interrupts from the firmware. + + */ + /**@{*/ +/*! +@fn \ + NMI_API void socketInit(void); + +@param [in] void + +@return void + +@remarks + This initialization function must be invoked before any socket operation is performed. + No error codes from this initialization function since the socket array is statically allocated based in the maximum number of + sockets @ref MAX_SOCKET based on the systems capability. +\section Example +This example demonstrates the use of the socketinit for socket initialization for an mqtt chat application. + \code + tstrWifiInitParam param; + int8_t ret; + char topic[strlen(MAIN_CHAT_TOPIC) + MAIN_CHAT_USER_NAME_SIZE + 1]; + + //Initialize the board. + system_init(); + + //Initialize the UART console. + configure_console(); + + // Initialize the BSP. + nm_bsp_init(); + + ---------- + + // Initialize socket interface. + socketInit(); + registerSocketCallback(socket_event_handler, socket_resolve_handler); + + // Connect to router. + m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), + MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); + +\endcode +*/ +NMI_API void socketInit(void); + + +/*! +@fn \ + NMI_API void socketDeinit(void); + +@brief Socket Layer De-initialization + + The function performs the necessary cleanup for the socket library static data + It must be invoked as the last any socket operation is performed on any active sockets. +*/ +NMI_API void socketDeinit(void); + + +/** @} */ +/** @defgroup SocketCallbackFn registerSocketCallback + * @ingroup SocketAPI + Register two callback functions one for asynchronous socket events and the other one for DNS callback registering function. + The registered callback functions are used to retrieve information in response to the asynchronous socket functions called. + */ + /**@{*/ + + +/*! +@fn \ + NMI_API void registerSocketCallback(tpfAppSocketCb socket_cb, tpfAppResolveCb resolve_cb); + +@param [in] tpfAppSocketCb + Assignment of callback function to the global callback @ref tpfAppSocketCb gpfAppSocketCb. Delivers + socket messages to the host application. In response to the asynchronous function calls, such as @ref bind + @ref listen @ref accept @ref connect + +@param [in] tpfAppResolveCb + Assignment of callback function to the global callback @ref tpfAppResolveCb gpfAppResolveCb. + Used for DNS resolving functionalities. The DNS resolving technique is determined by the application + registering the callback. + NULL is assigned when, DNS resolution is not required. + +@return void +@remarks + If any of the socket functionalities is not to be used, NULL is passed in as a parameter. + It must be invoked after socketinit and before other socket layer operations. + +\section Example + This example demonstrates the use of the registerSocketCallback to register a socket callback function with DNS resolution CB set to null + for a simple UDP server example. + \code + tstrWifiInitParam param; + int8_t ret; + struct sockaddr_in addr; + + // Initialize the board + system_init(); + + //Initialize the UART console. + configure_console(); + + // Initialize the BSP. + nm_bsp_init(); + + // Initialize socket address structure. + addr.sin_family = AF_INET; + addr.sin_port = _htons(MAIN_WIFI_M2M_SERVER_PORT); + addr.sin_addr.s_addr = _htonl(MAIN_WIFI_M2M_SERVER_IP); + + // Initialize Wi-Fi parameters structure. + memset((uint8_t *)¶m, 0, sizeof(tstrWifiInitParam)); + + // Initialize Wi-Fi driver with data and status callbacks. + param.pfAppWifiCb = wifi_cb; + ret = m2m_wifi_init(¶m); + if (M2M_SUCCESS != ret) { + printf("main: m2m_wifi_init call error!(%d)\r\n", ret); + while (1) { + } + } + + // Initialize socket module + socketInit(); + registerSocketCallback(socket_cb, NULL); + + // Connect to router. + m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); + \endcode +*/ +NMI_API void registerSocketCallback(tpfAppSocketCb socket_cb, tpfAppResolveCb resolve_cb); + + +/** @} */ + +/** @defgroup SocketFn socket + * @ingroup SocketAPI + * Synchronous socket allocation function based on the specified socket type. Created sockets are non-blocking and their possible types are either TCP or a UDP sockets. + * The maximum allowed number of TCP sockets is @ref TCP_SOCK_MAX sockets while the maximum number of UDP sockets that can be created simultaneously is @ref UDP_SOCK_MAX sockets. + * +*/ + /**@{*/ +/*! +@fn \ + NMI_API SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags); + + +@param [in] u16Domain + Socket family. The only allowed value is AF_INET (IPv4.0) for TCP/UDP sockets. + +@param [in] u8Type + Socket type. Allowed values are: + - [SOCK_STREAM](@ref SOCK_STREAM) + - [SOCK_DGRAM](@ref SOCK_DGRAM) + +@param [in] u8Flags + Used to specify the socket creation flags. It shall be set to zero for normal TCP/UDP sockets. + It could be @ref SOCKET_FLAGS_SSL if the socket is used for SSL session. The use of the flag + @ref SOCKET_FLAGS_SSL has no meaning in case of UDP sockets. + +@pre + The @ref socketInit function must be called once at the beginning of the application to initialize the socket handler. + before any call to the socket function can be made. + +@see + connect + bind + listen + accept + recv + recvfrom + send + sendto + close + setsockopt + getsockopt + +@return + On successful socket creation, a non-blocking socket type is created and a socket ID is returned + In case of failure the function returns a negative value, identifying one of the socket error codes defined. + For example: @ref SOCK_ERR_INVALID for invalid argument or + @ref SOCK_ERR_MAX_TCP_SOCK if the number of TCP allocated sockets exceeds the number of available sockets. + +@remarks + The socket function must be called a priori to any other related socket functions "e.g. send, recv, close ..etc" +\section Example + This example demonstrates the use of the socket function to allocate the socket, returning the socket handler to be used for other +socket operations. Socket creation is dependent on the socket type. +\subsection sub1 UDP example +@code + SOCKET UdpServerSocket = -1; + + UdpServerSocket = socket(AF_INET, SOCK_DGRAM, 0); + +@endcode +\subsection sub2 TCP example +@code + static SOCKET tcp_client_socket = -1; + + tcp_client_socket = socket(AF_INET, SOCK_STREAM, 0)); +@endcode +\subsection sub3 SSL example +@code +static SOCKET ssl_socket = -1; + +ssl_socket = socket(AF_INET, SOCK_STREAM, SOCK_FLAGS_SSL)); +@endcode +*/ +NMI_API SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags); + + +/** @} */ +/** @defgroup BindFn bind + * @ingroup SocketAPI +* Asynchronous bind function associates the provided address and local port to the socket. +* The function can be used with both TCP and UDP sockets it's mandatory to call the @ref bind function before starting any UDP or TCP server operation. +* Upon socket bind completion, the application will receive a @ref SOCKET_MSG_BIND message in the socket callback. +*/ + /**@{*/ +/*! +\fn \ + NMI_API sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); + + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] pstrAddr + Pointer to socket address structure "sockaddr_in" + [sockaddr_in](@ref sockaddr_in) + + +@param [in] u8AddrLen + Size of the given socket address structure in bytes. + +@pre + The socket function must be called to allocate a socket before passing the socket ID to the bind function. + +@see + socket + connect + listen + accept + recv + recvfrom + send + sendto + +@return + The function returns ZERO for successful operations and a negative value otherwise. + The possible error values are: + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + Indicating that the operation was successful. + + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) + Indicating passing invalid arguments such as negative socket ID or NULL socket address structure. + + - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID) + Indicate socket bind failure. +\section Example + This example demonstrates the call of the bind socket operation after a successful socket operation. +@code + struct sockaddr_in addr; + SOCKET udpServerSocket =-1; + int ret = -1; + + if(udpServerSocket == -1) + { + udpServerSocket = socket(AF_INET, SOCK_DGRAM, 0); + if(udpServerSocket >= 0) + { + addr.sin_family = AF_INET; + addr.sin_port = _htons(1234); + addr.sin_addr.s_addr = 0; + ret = bind(udpServerSocket,(struct sockaddr*)&addr,sizeof(addr)); + + if(ret != 0) + { + printf("Bind Failed. Error code = %d\n",ret); + close(udpServerSocket); + } + } + else + { + printf("UDP Server Socket Creation Failed\n"); + return; + } + } +@endcode +*/ +NMI_API sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); + + +/** @} */ + +/** @defgroup ListenFn listen + * @ingroup SocketAPI + * After successful socket binding to an IP address and port on the system, start listening on a passive socket for incoming connections. + The socket must be bound on a local port or the listen operation fails. + Upon the call to the asynchronous listen function, response is received through the event [SOCKET_MSG_BIND](@ref SOCKET_MSG_BIND) + in the socket callback. + A successful listen means the TCP server operation is active. If a connection is accepted, then the application socket callback function is + notified with the new connected socket through the event @ref SOCKET_MSG_ACCEPT. Hence there is no need to call the @ref accept function + after calling @ref listen. + + After a connection is accepted, the user is then required to call the @ref recv to receive any packets transmitted by the remote host or to receive notification of socket connection + termination. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 listen(SOCKET sock, uint8 backlog); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] backlog + Not used by the current implementation. + +@pre + The bind function must be called to assign the port number and IP address to the socket before the listen operation. + +@see + bind + accept + recv + recvfrom + send + sendto + +@return + The function returns ZERO for successful operations and a negative value otherwise. + The possible error values are: + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + Indicating that the operation was successful. + + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) + Indicating passing invalid arguments such as negative socket ID. + + - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID) + Indicate socket listen failure. +\section Example +This example demonstrates the call of the listen socket operation after a successful socket operation. +@code + static void TCP_Socketcallback(SOCKET sock, uint8 u8Msg, void * pvMsg) + { + int ret =-1; + + switch(u8Msg) + { + case SOCKET_MSG_BIND: + { + tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg; + if(pstrBind != NULL) + { + if(pstrBind->status == 0) + { + ret = listen(sock, 0); + + if(ret <0) + printf("Listen failure! Error = %d\n",ret); + } + else + { + M2M_ERR("bind Failure!\n"); + close(sock); + } + } + } + break; + + case SOCKET_MSG_LISTEN: + { + + tstrSocketListenMsg *pstrListen = (tstrSocketListenMsg*)pvMsg; + if(pstrListen != NULL) + { + if(pstrListen->status == 0) + { + ret = accept(sock,NULL,0); + } + else + { + M2M_ERR("listen Failure!\n"); + close(sock); + } + } + } + break; + + case SOCKET_MSG_ACCEPT: + { + tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg*)pvMsg; + + if(pstrAccept->sock >= 0) + { + TcpNotificationSocket = pstrAccept->sock; + recv(pstrAccept->sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT); + } + else + { + M2M_ERR("accept failure\n"); + } + } + break; + + default: + break; + } + } + +@endcode +*/ +NMI_API sint8 listen(SOCKET sock, uint8 backlog); +/** @} */ +/** @defgroup AcceptFn accept + * @ingroup SocketAPI + * The function has no current implementation. An empty deceleration is used to prevent errors when legacy application code is used. + * For recent application use, the accept function can be safer as it has no effect and could be safely removed from any application using it. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. +@param [in] addr + Not used in the current implementation. + +@param [in] addrlen + Not used in the current implementation. + +@return + The function returns ZERO for successful operations and a negative value otherwise. + The possible error values are: + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + Indicating that the operation was successful. + + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) + Indicating passing invalid arguments such as negative socket ID. +*/ +NMI_API sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen); +/** @} */ +/** @defgroup ConnectFn connect + * @ingroup SocketAPI + * Establishes a TCP connection with a remote server. + The asynchronous connect function must be called after receiving a valid socket ID from the @ref socket function. + The application socket callback function is notified of a successful new socket connection through the event @ref SOCKET_MSG_CONNECT. + A successful connect means the TCP session is active. The application is then required to make a call to the @ref recv + to receive any packets transmitted by the remote server, unless the application is interrupted by a notification of socket connection + termination. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] pstrAddr + Address of the remote server. +@param [in] pstrAddr + Pointer to socket address structure "sockaddr_in" + [sockaddr_in](@ref sockaddr_in) + +@param [in] u8AddrLen + Size of the given socket address structure in bytes. + Not currently used, implemented for BSD compatibility only. +@pre + The socket function must be called to allocate a TCP socket before passing the socket ID to the bind function. + If the socket is not bound, you do NOT have to call bind before the "connect" function. + +@see + socket + recv + send + close + +@return + The function returns ZERO for successful operations and a negative value otherwise. + The possible error values are: + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + Indicating that the operation was successful. + + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) + Indicating passing invalid arguments such as negative socket ID or NULL socket address structure. + + - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID) + Indicate socket connect failure. +\section Example + The example demonstrates a TCP application, showing how the asynchronous call to the connect function is made through the main function and how the + callback function handles the @ref SOCKET_MSG_CONNECT event. +\subsection sub1 Main Function +@code + struct sockaddr_in Serv_Addr; + SOCKET TcpClientSocket =-1; + int ret = -1 + + TcpClientSocket = socket(AF_INET,SOCK_STREAM,0); + Serv_Addr.sin_family = AF_INET; + Serv_Addr.sin_port = _htons(1234); + Serv_Addr.sin_addr.s_addr = inet_addr(SERVER); + printf("Connected to server via socket %u\n",TcpClientSocket); + + do + { + ret = connect(TcpClientSocket,(sockaddr_in*)&Serv_Addr,sizeof(Serv_Addr)); + if(ret != 0) + { + printf("Connection Error\n"); + } + else + { + printf("Connection successful.\n"); + break; + } + }while(1) +@endcode +\subsection sub2 Socket Callback +@code + if(u8Msg == SOCKET_MSG_CONNECT) + { + tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg*)pvMsg; + if(pstrConnect->s8Error == 0) + { + uint8 acBuffer[GROWL_MSG_SIZE]; + uint16 u16MsgSize; + + printf("Connect success!\n"); + + u16MsgSize = FormatMsg(u8ClientID, acBuffer); + send(sock, acBuffer, u16MsgSize, 0); + recv(pstrNotification->Socket, (void*)au8Msg,GROWL_DESCRIPTION_MAX_LENGTH, GROWL_RX_TIMEOUT); + u8Retry = GROWL_CONNECT_RETRY; + } + else + { + M2M_DBG("Connection Failed, Error: %d\n",pstrConnect->s8Error"); + close(pstrNotification->Socket); + } + } +@endcode +*/ +#ifdef ARDUINO +NMI_API sint8 connectSocket(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); +#else +NMI_API sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); +#endif +/** @} */ +/** @defgroup ReceiveFn recv + * @ingroup SocketAPI + * An asynchronous receive function, used to retrieve data from a TCP stream. + Before calling the recv function, a successful socket connection status must have been received through any of the two socket events + [SOCKET_MSG_CONNECT] or [SOCKET_MSG_ACCEPT], from the socket callback. Hence, indicating that the socket is already connected to a remote + host. + The application receives the required data in response to this asynchronous call through the reception of the event @ref SOCKET_MSG_RECV in the + socket callback. + + Receiving the SOCKET_MSG_RECV message in the callback with zero or negative buffer length indicates the following: + - SOCK_ERR_NO_ERROR : Socket connection closed + - SOCK_ERR_CONN_ABORTED : Socket connection aborted + - SOCK_ERR_TIMEOUT : Socket receive timed out + The application code is expected to close the socket through the call to the @ref close function upon the appearance of the above mentioned errors. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + + +@param [in] pvRecvBuf + Pointer to a buffer that will hold the received data. The buffer is used + in the recv callback to deliver the received data to the caller. The buffer must + be resident in memory (heap or global buffer). + +@param [in] u16BufLen + The buffer size in bytes. + +@param [in] u32Timeoutmsec + Timeout for the recv function in milli-seconds. If the value is set to ZERO, the timeout + will be set to infinite (the recv function waits forever). If the timeout period is + elapsed with no data received, the socket will get a timeout error. +@pre + - The socket function must be called to allocate a TCP socket before passing the socket ID to the recv function. + - The socket in a connected state is expected to receive data through the socket interface. + +@see + socket + connect + bind + listen + recvfrom + close + + +@return + The function returns ZERO for successful operations and a negative value otherwise. + The possible error values are: + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + Indicating that the operation was successful. + + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) + Indicating passing invalid arguments such as negative socket ID or NULL Recieve buffer. + + - [SOCK_ERR_BUFFER_FULL](@ref SOCK_ERR_BUFFER_FULL) + Indicate socket receive failure. +\section Example + The example demonstrates a code snippet for the calling of the recv function in the socket callback upon notification of the accept or connect events, and the parsing of the + received data when the SOCKET_MSG_RECV event is received. +@code + + switch(u8Msg) + { + + case SOCKET_MSG_ACCEPT: + { + tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg*)pvMsg; + + if(pstrAccept->sock >= 0) + { + recv(pstrAccept->sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT); + } + else + { + M2M_ERR("accept\n"); + } + } + break; + + + case SOCKET_MSG_RECV: + { + tstrSocketRecvMsg *pstrRx = (tstrSocketRecvMsg*)pvMsg; + + if(pstrRx->s16BufferSize > 0) + { + + recv(sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT); + } + else + { + printf("Socet recv Error: %d\n",pstrRx->s16BufferSize); + close(sock); + } + } + break; + + default: + break; + } +} +@endcode +*/ +NMI_API sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec); +/** @} */ +/** @defgroup ReceiveFromSocketFn recvfrom + * @ingroup SocketAPI + * Receives data from a UDP Socket. +* +* The asynchronous recvfrom function is used to retrieve data from a UDP socket. The socket must already be bound to +* a local port before a call to the recvfrom function is made (i.e message @ref SOCKET_MSG_BIND is received +* with successful status in the socket callback). +* +* Upon calling the recvfrom function with a successful return code, the application is expected to receive a notification +* in the socket callback whenever a message is received through the @ref SOCKET_MSG_RECVFROM event. +* +* Receiving the SOCKET_MSG_RECVFROM message in the callback with zero, indicates that the socket is closed. +* Whereby a negative buffer length indicates one of the socket error codes such as socket timeout error @SOCK_ERR_TIMEOUT: +* +* The recvfrom callback can also be used to show the IP address of the remote host that sent the frame by +* using the "strRemoteAddr" element in the @ref tstrSocketRecvMsg structure. (refer to the code example) + */ + /**@{*/ +/*! +@fn \ + NMI_API sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32TimeoutSeconds); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] pvRecvBuf + Pointer to a buffer that will hold the received data. The buffer shall be used + in the recv callback to deliver the received data to the caller. The buffer must + be resident in memory (heap or global buffer). + +@param [in] u16BufLen + The buffer size in bytes. + +@param [in] u32TimeoutSeconds + Timeout for the recv function in milli-seconds. If the value is set to ZERO, the timeout + will be set to infinite (the recv function waits forever). + +@pre + - The socket function must be called to allocate a UDP socket before passing the socket ID to the recvfrom function. + - The socket corresponding to the socket ID must be successfully bound to a local port through the call to a @ref bind function. + +@see + socket + bind + close + +@return + The function returns ZERO for successful operations and a negative value otherwise. + The possible error values are: + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + Indicating that the operation was successful. + + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) + Indicating passing invalid arguments such as negative socket ID or NULL Receive buffer. + + - [SOCK_ERR_BUFFER_FULL](@ref SOCK_ERR_BUFFER_FULL) + Indicate socket receive failure. +\section Example + The example demonstrates a code snippet for the calling of the recvfrom function in the socket callback upon notification of a successful bind event, and the parsing of the + received data when the SOCKET_MSG_RECVFROM event is received. +@code + switch(u8Msg) + { + + case SOCKET_MSG_BIND: + { + tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg; + + if(pstrBind != NULL) + { + if(pstrBind->status == 0) + { + recvfrom(sock, gau8SocketTestBuffer, TEST_BUFFER_SIZE, 0); + } + else + { + M2M_ERR("bind\n"); + } + } + } + break; + + + case SOCKET_MSG_RECVFROM: + { + tstrSocketRecvMsg *pstrRx = (tstrSocketRecvMsg*)pvMsg; + + if(pstrRx->s16BufferSize > 0) + { + //get the remote host address and port number + uint16 u16port = pstrRx->strRemoteAddr.sin_port; + uint32 strRemoteHostAddr = pstrRx->strRemoteAddr.sin_addr.s_addr; + + printf("Recieved frame with size = %d.\tHost address=%x, Port number = %d\n\n",pstrRx->s16BufferSize,strRemoteHostAddr, u16port); + + ret = recvfrom(sock,gau8SocketTestBuffer,sizeof(gau8SocketTestBuffer),TEST_RECV_TIMEOUT); + } + else + { + printf("Socet recv Error: %d\n",pstrRx->s16BufferSize); + ret = close(sock); + } + } + break; + + default: + break; + } +} +@endcode +*/ +NMI_API sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec); +/** @} */ +/** @defgroup SendFn send + * @ingroup SocketAPI +* Asynchronous sending function, used to send data on a TCP/UDP socket. + +* Called by the application code when there is outgoing data available required to be sent on a specific socket handler. +* The only difference between this function and the similar @ref sendto function, is the type of socket the data is sent on and the parameters passed in. +* @ref send function is most commonly called for sockets in a connected state. +* After the data is sent, the socket callback function registered using registerSocketCallback(), is expected to receive an event of type +* @ref SOCKET_MSG_SEND holding information containing the number of data bytes sent. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 u16Flags); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] pvSendBuffer + Pointer to a buffer holding data to be transmitted. + +@param [in] u16SendLength + The buffer size in bytes. + +@param [in] u16Flags + Not used in the current implementation. + +@pre + Sockets must be initialized using socketInit. \n + + For TCP Socket:\n + Must use a successfully connected Socket (so that the intended recipient address is known ahead of sending the data). + Hence this function is expected to be called after a successful socket connect operation(in client case or accept in the + the server case).\n + + For UDP Socket:\n + UDP sockets most commonly use @ref sendto function, where the destination address is defined. However, in-order to send outgoing data + using the @ref send function, at least one successful call must be made to the @ref sendto function a priori the consecutive calls to the @ref send function, + to ensure that the destination address is saved in the firmware. + +@see + socketInit + recv + sendto + socket + connect + accept + sendto + +@warning + u16SendLength must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. \n + Use a valid socket identifier through the a prior call to the @ref socket function. + Must use a valid buffer pointer. + Successful completion of a call to send() does not guarantee delivery of the message, + A negative return value indicates only locally-detected errors + + +@return + The function shall return @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise. +*/ +NMI_API sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 u16Flags); +/** @} */ +/** @defgroup SendToSocketFn sendto + * @ingroup SocketAPI +* Asynchronous sending function, used to send data on a UDP socket. +* Called by the application code when there is data required to be sent on a UDP socket handler. +* The application code is expected to receive data from a successful bounded socket node. +* The only difference between this function and the similar @ref send function, is the type of socket the data is received on. This function works +* only with UDP sockets. +* After the data is sent, the socket callback function registered using registerSocketCallback(), is expected to receive an event of type +* @ref SOCKET_MSG_SENDTO. +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] pvSendBuffer + Pointer to a buffer holding data to be transmitted. + A NULL value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] u16SendLength + The buffer size in bytes. It must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. + +@param [in] flags + Not used in the current implementation + +@param [in] pstrDestAddr + The destination address. + +@param [in] u8AddrLen + Destination address length in bytes. + Not used in the current implementation, only included for BSD compatibility. +@pre + Sockets must be initialized using socketInit. + +@see + socketInit + recvfrom + sendto + socket + connect + accept + send + +@warning + u16SendLength must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. \n + Use a valid socket (returned from socket ). + A valid buffer pointer must be used (not NULL). \n + Successful completion of a call to sendto() does not guarantee delivery of the message, + A negative return value indicates only locally-detected errors + +@return + The function returns @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise. +*/ +NMI_API sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen); +/** @} */ +/** @defgroup CloseSocketFn close + * @ingroup SocketAPI + * Synchronous close function, releases all the socket assigned resources. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 close(SOCKET sock); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@pre + Sockets must be initialized through the call of the socketInit function. + @ref close is called only for valid socket identifiers created through the @ref socket function. + +@warning + If @ref close is called while there are still pending messages (sent or received ) they will be discarded. + +@see + socketInit + socket + +@return + The function returned @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise. +*/ +NMI_API sint8 close(SOCKET sock); + + +/** @} */ +/** @defgroup InetAddressFn nmi_inet_addr +* @ingroup SocketAPI +* Synchronous function which returns a BSD socket compliant Internet Protocol (IPv4) socket address. +* This IPv4 address in the input string parameter could either be specified as a host name, or as a numeric string representation like n.n.n.n known as the IPv4 dotted-decimal format +* (i.e. "192.168.10.1"). +* This function is used whenever an ip address needs to be set in the proper format +* (i.e. for the @ref tstrM2MIPConfig structure). +*/ + /**@{*/ +/*! +@fn \ + NMI_API uint32 nmi_inet_addr(char *pcIpAddr); + +@param [in] pcIpAddr + A null terminated string containing the IP address in IPv4 dotted-decimal address. + +@return + Unsigned 32-bit integer representing the IP address in Network byte order + (eg. "192.168.10.1" will be expressed as 0x010AA8C0). + +*/ +NMI_API uint32 nmi_inet_addr(char *pcIpAddr); + + +/** @} */ +/** @defgroup gethostbynameFn gethostbyname + * @ingroup SocketAPI +* Asynchronous DNS resolving function. This function use DNS to resolve a domain name into the corresponding IP address. +* A call to this function will cause a DNS request to be sent and the response will be delivered to the DNS callback function registered using registerSocketCallback() + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 gethostbyname(uint8 * pcHostName); + +@param [in] pcHostName + NULL terminated string containing the domain name for the remote host. + Its size must not exceed [HOSTNAME_MAX_SIZE](@ref HOSTNAME_MAX_SIZE). + +@see + registerSocketCallback + +@warning + Successful completion of a call to gethostbyname() does not guarantee success of the DNS request, + a negative return value indicates only locally-detected errors + +@return + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) +*/ +NMI_API sint8 gethostbyname(uint8 * pcHostName); + + +/** @} */ +/** @defgroup sslEnableCertExpirationCheckFn sslEnableCertExpirationCheck + * @ingroup SocketAPI +* Configure the behavior of the SSL Library for Certificate Expiry Validation. + */ + /**@{*/ +/*! +@fn \ +NMI_API sint8 sslEnableCertExpirationCheck(tenuSslCertExpSettings enuValidationSetting); + +@param [in] enuValidationSetting + See @ref tenuSslCertExpSettings for details. + +@return + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) for successful operation and negative error code otherwise. + +@sa tenuSslCertExpSettings +*/ +NMI_API sint8 sslEnableCertExpirationCheck(tenuSslCertExpSettings enuValidationSetting); + + +/** @} */ + +/** @defgroup SetSocketOptionFn setsockopt + * @ingroup SocketAPI +*The setsockopt() function shall set the option specified by the option_name +* argument, at the protocol level specified by the level argument, to the value +* pointed to by the option_value argument for the socket specified by the socket argument. +* +*

Possible protocol level values supported are @ref SOL_SOCKET and @ref SOL_SSL_SOCKET. +* Possible options when the protocol level is @ref SOL_SOCKET :

+* +* +* +* +* +* +* +* +* +* +* +* +* +*
@ref SO_SET_UDP_SEND_CALLBACKEnable/Disable callback messages for sendto(). +* Since UDP is unreliable by default the user maybe interested (or not) in +* receiving a message of @ref SOCKET_MSG_SENDTO for each call of sendto(). +* Enabled if option value equals @ref TRUE, disabled otherwise.
@ref IP_ADD_MEMBERSHIPValid for UDP sockets. This option is used to receive frames sent to +* a multicast group. option_value shall be a pointer to Unsigned 32-bit +* integer containing the multicast IPv4 address.
@ref IP_DROP_MEMBERSHIPValid for UDP sockets. This option is used to stop receiving frames +* sent to a multicast group. option_value shall be a pointer to Unsigned +* 32-bit integer containing the multicast IPv4 address.
+*

Possible options when the protcol leve  is @ref SOL_SSL_SOCKET

+* +* +* +* +* +* +* +* +* +* +* +* +* +*
+* @ref SO_SSL_BYPASS_X509_VERIFAllow an opened SSL socket to bypass the X509 +* certificate verification process. It is highly recommended NOT to use +* this socket option in production software applications. The option is +* supported for debugging and testing purposes. The option value should be +* casted to int type and it is handled as a boolean flag.
@ref SO_SSL_SNISet the Server Name Indicator (SNI) for an SSL socket. The SNI is a +* null terminated string containing the server name associated with the +* connection. It must not exceed the size of @ref HOSTNAME_MAX_SIZE.
@ref SO_SSL_ENABLE_SESSION_CACHINGThis option allow the TLS to cache the session information for fast +* TLS session establishment in future connections using the TLS Protocol +* session resume features.
+ */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 setsockopt(SOCKET socket, uint8 u8Level, uint8 option_name, + const void *option_value, uint16 u16OptionLen); + +@param [in] sock + Socket handler. + +@param [in] level + protocol level. See description above. + +@param [in] option_name + option to be set. See description above. + +@param [in] option_value + pointer to user provided value. + +@param [in] option_len + length of the option value in bytes. +@return + The function shall return \ref SOCK_ERR_NO_ERROR for successful operation + and a negative value (indicating the error) otherwise. +@sa SOL_SOCKET, SOL_SSL_SOCKET, IP_ADD_MEMBERSHIP, IP_DROP_MEMBERSHIP +*/ +NMI_API sint8 setsockopt(SOCKET socket, uint8 u8Level, uint8 option_name, + const void *option_value, uint16 u16OptionLen); + + +/** @} */ +/** @defgroup GetSocketOptionsFn getsockopt + * @ingroup SocketAPI + * Get socket options retrieves +* This Function isn't implemented yet but this is the form that will be released later. + */ + /**@{*/ +/*! +@fn \ + sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8 * pu8OptLen); + +@brief + +@param [in] sock + Socket Identifie. +@param [in] u8Level + The protocol level of the option. +@param [in] u8OptName + The u8OptName argument specifies a single option to get. +@param [out] pvOptValue + The pvOptValue argument contains pointer to a buffer containing the option value. +@param [out] pu8OptLen + Option value buffer length. +@return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8* pu8OptLen); +/** @} */ + +/**@}*/ +/** @defgroup PingFn m2m_ping_req + * @ingroup SocketAPI + * The function sends ping request to the given IP Address. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb); + +@param [in] u32DstIP + Target Destination IP Address for the ping request. It must be represented in Network byte order. + The function nmi_inet_addr could be used to translate the dotted decimal notation IP + to its Network bytes order integer represntative. + +@param [in] u8TTL + IP TTL value for the ping request. If set to ZERO, the dfault value SHALL be used. + +@param [in] fpPingCb + Callback will be called to deliver the ping statistics. + +@see nmi_inet_addr +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb); +/**@}*/ + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* __SOCKET_H__ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/socket/include/socket_buffer.h b/feather_sensor_lte/libraries/WiFi101/src/socket/include/socket_buffer.h new file mode 100644 index 0000000..d93a7c8 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/socket/include/socket_buffer.h @@ -0,0 +1,94 @@ +/** + * + * \file + * + * \brief BSD compatible socket interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef __SOCKET_BUFFER_H__ +#define __SOCKET_BUFFER_H__ + +#include "socket/include/socket.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define SOCKET_BUFFER_UDP_HEADER_SIZE (8) + +#if defined LIMITED_RAM_DEVICE +#define SOCKET_BUFFER_MTU (16u) +#define SOCKET_BUFFER_UDP_SIZE (SOCKET_BUFFER_UDP_HEADER_SIZE + 64u) +#define SOCKET_BUFFER_TCP_SIZE (64u) +#else +#ifdef ARDUINO +#define SOCKET_BUFFER_MTU (1446u) +#else +#define SOCKET_BUFFER_MTU (1400u) +#endif +#define SOCKET_BUFFER_UDP_SIZE (SOCKET_BUFFER_UDP_HEADER_SIZE + SOCKET_BUFFER_MTU) +#define SOCKET_BUFFER_TCP_SIZE (SOCKET_BUFFER_MTU) +#endif + +#define SOCKET_BUFFER_FLAG_CONNECTED (0x1 << 0) +#define SOCKET_BUFFER_FLAG_FULL (0x1 << 1) +#define SOCKET_BUFFER_FLAG_BIND (0x1 << 2) +#define SOCKET_BUFFER_FLAG_SPAWN (0x1 << 3) +#define SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS (16) +#define SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK (((uint32)0xFF) << SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS) +#define SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS (24) +#define SOCKET_BUFFER_FLAG_PARENT_SOCKET_MSK (((uint32)0xFF) << SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS) + +/* Parent stored as parent+1, as socket 1 ID is 0. */ + +typedef struct{ + uint8 *buffer; + uint32 *flag; + uint32 *head; + uint32 *tail; +}tstrSocketBuffer; + +void socketBufferInit(void); +void socketBufferRegister(SOCKET socket, uint32 *flag, uint32 *head, uint32 *tail, uint8 *buffer); +void socketBufferUnregister(SOCKET socket); +void socketBufferCb(SOCKET sock, uint8 u8Msg, void *pvMsg); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* __SOCKET_BUFFER_H__ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/socket/source/socket.c b/feather_sensor_lte/libraries/WiFi101/src/socket/source/socket.c new file mode 100644 index 0000000..877cc1a --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/socket/source/socket.c @@ -0,0 +1,1445 @@ +/** + * + * \file + * + * \brief BSD compatible socket interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#include + +#include "bsp/include/nm_bsp.h" +#include "socket/include/socket.h" +#include "driver/source/m2m_hif.h" +#include "socket/source/socket_internal.h" +#include "driver/include/m2m_types.h" + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +#define TLS_RECORD_HEADER_LENGTH (5) +#define ETHERNET_HEADER_OFFSET (34) +#define ETHERNET_HEADER_LENGTH (14) +#define TCP_IP_HEADER_LENGTH (40) +#define UDP_IP_HEADER_LENGTH (28) + +#define IP_PACKET_OFFSET (ETHERNET_HEADER_LENGTH + ETHERNET_HEADER_OFFSET - M2M_HIF_HDR_OFFSET) + +#define TCP_TX_PACKET_OFFSET (IP_PACKET_OFFSET + TCP_IP_HEADER_LENGTH) +#define UDP_TX_PACKET_OFFSET (IP_PACKET_OFFSET + UDP_IP_HEADER_LENGTH) +#define SSL_TX_PACKET_OFFSET (TCP_TX_PACKET_OFFSET + TLS_RECORD_HEADER_LENGTH) + +#define SOCKET_REQUEST(reqID, reqArgs, reqSize, reqPayload, reqPayloadSize, reqPayloadOffset) \ + hif_send(M2M_REQ_GROUP_IP, reqID, reqArgs, reqSize, reqPayload, reqPayloadSize, reqPayloadOffset) + + +#define SSL_FLAGS_ACTIVE NBIT0 +#define SSL_FLAGS_BYPASS_X509 NBIT1 +#define SSL_FLAGS_2_RESERVD NBIT2 +#define SSL_FLAGS_3_RESERVD NBIT3 +#define SSL_FLAGS_CACHE_SESSION NBIT4 +#define SSL_FLAGS_NO_TX_COPY NBIT5 +#define SSL_FLAGS_CHECK_SNI NBIT6 + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +PRIVATE DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +/*! +* @brief +*/ +typedef struct{ + SOCKET sock; + uint8 u8Dummy; + uint16 u16SessionID; +}tstrCloseCmd; + + +/*! +* @brief +*/ +typedef struct{ + uint8 *pu8UserBuffer; + uint16 u16UserBufferSize; + uint16 u16SessionID; + uint16 u16DataOffset; + uint8 bIsUsed; + uint8 u8SSLFlags; + uint8 bIsRecvPending; +}tstrSocket; + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +GLOBALS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +volatile sint8 gsockerrno; +volatile tstrSocket gastrSockets[MAX_SOCKET]; +volatile uint8 gu8OpCode; +volatile uint16 gu16BufferSize; +volatile uint16 gu16SessionID = 0; + +volatile tpfAppSocketCb gpfAppSocketCb; +volatile tpfAppResolveCb gpfAppResolveCb; +volatile uint8 gbSocketInit = 0; +volatile tpfPingCb gfpPingCb; + +/********************************************************************* +Function + Socket_ReadSocketData + +Description + Callback function used by the NMC1500 driver to deliver messages + for socket layer. + +Return + None. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 17 July 2012 +*********************************************************************/ +#ifdef ARDUINO +extern uint8 hif_small_xfer; +static uint32 u32Address; +static SOCKET sock_xfer; +static uint8 type_xfer; +static tstrSocketRecvMsg msg_xfer; +#endif +NMI_API void Socket_ReadSocketData(SOCKET sock, tstrSocketRecvMsg *pstrRecv,uint8 u8SocketMsg, + uint32 u32StartAddress,uint16 u16ReadCount) +{ + if((u16ReadCount > 0) && (gastrSockets[sock].pu8UserBuffer != NULL) && (gastrSockets[sock].u16UserBufferSize > 0) && (gastrSockets[sock].bIsUsed == 1)) + { +#ifdef ARDUINO + u32Address = u32StartAddress; +#else + uint32 u32Address = u32StartAddress; +#endif + uint16 u16Read; + sint16 s16Diff; + uint8 u8SetRxDone; +#ifdef ARDUINO + m2m_memcpy((uint8 *)&msg_xfer, (uint8 *)pstrRecv, sizeof(tstrSocketRecvMsg)); + msg_xfer.u16RemainingSize = u16ReadCount; +#else + pstrRecv->u16RemainingSize = u16ReadCount; +#endif + do + { + u8SetRxDone = 1; + u16Read = u16ReadCount; + s16Diff = u16Read - gastrSockets[sock].u16UserBufferSize; + if(s16Diff > 0) + { + u8SetRxDone = 0; + u16Read = gastrSockets[sock].u16UserBufferSize; +#ifdef ARDUINO + hif_small_xfer = 1; + sock_xfer = sock; + type_xfer = u8SocketMsg; +#endif + } + + if(hif_receive(u32Address, gastrSockets[sock].pu8UserBuffer, u16Read, u8SetRxDone) == M2M_SUCCESS) + { +#ifdef ARDUINO + msg_xfer.pu8Buffer = gastrSockets[sock].pu8UserBuffer; + msg_xfer.s16BufferSize = u16Read; + msg_xfer.u16RemainingSize -= u16Read; + + if (gpfAppSocketCb) + gpfAppSocketCb(sock,u8SocketMsg, &msg_xfer); + + u32Address += u16Read; +#else + pstrRecv->pu8Buffer = gastrSockets[sock].pu8UserBuffer; + pstrRecv->s16BufferSize = u16Read; + pstrRecv->u16RemainingSize -= u16Read; + + if (gpfAppSocketCb) + gpfAppSocketCb(sock,u8SocketMsg, pstrRecv); + + u16ReadCount -= u16Read; + u32Address += u16Read; + + if((!gastrSockets[sock].bIsUsed) && (u16ReadCount)) + { + M2M_DBG("Application Closed Socket While Rx Is not Complete\n"); + if(hif_receive(0, NULL, 0, 1) == M2M_SUCCESS) + M2M_DBG("hif_receive Success\n"); + else + M2M_DBG("hif_receive Fail\n"); + break; + } +#endif + } + else + { + M2M_INFO("(ERRR)Current <%d>\n", u16ReadCount); + break; + } +#ifdef ARDUINO + }while(0); +#else + }while(u16ReadCount != 0); +#endif + } +} +#ifdef ARDUINO +NMI_API void Socket_ReadSocketData_Small(void) +{ + if((msg_xfer.u16RemainingSize > 0) && (gastrSockets[sock_xfer].pu8UserBuffer != NULL) && (gastrSockets[sock_xfer].u16UserBufferSize > 0) && (gastrSockets[sock_xfer].bIsUsed == 1)) + { + uint16 u16Read; + sint16 s16Diff; + uint8 u8SetRxDone; + + //do + //{ + u8SetRxDone = 1; + u16Read = msg_xfer.u16RemainingSize; + s16Diff = u16Read - gastrSockets[sock_xfer].u16UserBufferSize; + if(s16Diff > 0) + { + /*Has to be subsequent transfer*/ + hif_small_xfer = 2; + u8SetRxDone = 0; + u16Read = gastrSockets[sock_xfer].u16UserBufferSize; + } + else + { + /*Last xfer, needed for UDP*/ + hif_small_xfer = 3; + } + if(hif_receive(u32Address, gastrSockets[sock_xfer].pu8UserBuffer, u16Read, u8SetRxDone) == M2M_SUCCESS) + { + msg_xfer.pu8Buffer = gastrSockets[sock_xfer].pu8UserBuffer; + msg_xfer.s16BufferSize = u16Read; + msg_xfer.u16RemainingSize -= u16Read; + + if (gpfAppSocketCb) + gpfAppSocketCb(sock_xfer,type_xfer, &msg_xfer); + + u32Address += u16Read; + } + else + { + M2M_INFO("(ERRR)Current <%d>\n", u16Read); + //break; + } + + if (hif_small_xfer == 3) + { + hif_small_xfer = 0; + hif_chip_sleep(); + } + + //}while(u16ReadCount != 0); + } +} +#endif +/********************************************************************* +Function + m2m_ip_cb + +Description + Callback function used by the NMC1000 driver to deliver messages + for socket layer. + +Return + None. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 17 July 2012 +*********************************************************************/ +static void m2m_ip_cb(uint8 u8OpCode, uint16 u16BufferSize,uint32 u32Address) +{ + if((u8OpCode == SOCKET_CMD_BIND) || (u8OpCode == SOCKET_CMD_SSL_BIND)) + { + tstrBindReply strBindReply; + tstrSocketBindMsg strBind; + + if(hif_receive(u32Address, (uint8*)&strBindReply, sizeof(tstrBindReply), 0) == M2M_SUCCESS) + { + strBind.status = strBindReply.s8Status; + if(gpfAppSocketCb) + gpfAppSocketCb(strBindReply.sock,SOCKET_MSG_BIND,&strBind); + } + } + else if(u8OpCode == SOCKET_CMD_LISTEN) + { + tstrListenReply strListenReply; + tstrSocketListenMsg strListen; + if(hif_receive(u32Address, (uint8*)&strListenReply, sizeof(tstrListenReply), 0) == M2M_SUCCESS) + { + strListen.status = strListenReply.s8Status; + if(gpfAppSocketCb) + gpfAppSocketCb(strListenReply.sock,SOCKET_MSG_LISTEN, &strListen); + } + } + else if(u8OpCode == SOCKET_CMD_ACCEPT) + { + tstrAcceptReply strAcceptReply; + tstrSocketAcceptMsg strAccept; + if(hif_receive(u32Address, (uint8*)&strAcceptReply, sizeof(tstrAcceptReply), 0) == M2M_SUCCESS) + { + if(strAcceptReply.sConnectedSock >= 0) + { + gastrSockets[strAcceptReply.sConnectedSock].u8SSLFlags = gastrSockets[strAcceptReply.sListenSock].u8SSLFlags; + gastrSockets[strAcceptReply.sConnectedSock].bIsUsed = 1; + gastrSockets[strAcceptReply.sConnectedSock].u16DataOffset = strAcceptReply.u16AppDataOffset - M2M_HIF_HDR_OFFSET; + + /* The session ID is used to distinguish different socket connections + by comparing the assigned session ID to the one reported by the firmware*/ + ++gu16SessionID; + if(gu16SessionID == 0) + ++gu16SessionID; + + gastrSockets[strAcceptReply.sConnectedSock].u16SessionID = gu16SessionID; + M2M_DBG("Socket %d session ID = %d\r\n",strAcceptReply.sConnectedSock , gu16SessionID ); + } + strAccept.sock = strAcceptReply.sConnectedSock; + strAccept.strAddr.sin_family = AF_INET; + strAccept.strAddr.sin_port = strAcceptReply.strAddr.u16Port; + strAccept.strAddr.sin_addr.s_addr = strAcceptReply.strAddr.u32IPAddr; + if(gpfAppSocketCb) + gpfAppSocketCb(strAcceptReply.sListenSock, SOCKET_MSG_ACCEPT, &strAccept); + } + } + else if((u8OpCode == SOCKET_CMD_CONNECT) || (u8OpCode == SOCKET_CMD_SSL_CONNECT)) + { + tstrConnectReply strConnectReply; + tstrSocketConnectMsg strConnMsg; + if(hif_receive(u32Address, (uint8*)&strConnectReply, sizeof(tstrConnectReply), 0) == M2M_SUCCESS) + { + strConnMsg.sock = strConnectReply.sock; + strConnMsg.s8Error = strConnectReply.s8Error; + if(strConnectReply.s8Error == SOCK_ERR_NO_ERROR) + { + gastrSockets[strConnectReply.sock].u16DataOffset = strConnectReply.u16AppDataOffset - M2M_HIF_HDR_OFFSET; + } + if(gpfAppSocketCb) + gpfAppSocketCb(strConnectReply.sock,SOCKET_MSG_CONNECT, &strConnMsg); + } + } + else if(u8OpCode == SOCKET_CMD_DNS_RESOLVE) + { + tstrDnsReply strDnsReply; + if(hif_receive(u32Address, (uint8*)&strDnsReply, sizeof(tstrDnsReply), 0) == M2M_SUCCESS) + { + if(gpfAppResolveCb) + gpfAppResolveCb((uint8*)strDnsReply.acHostName, strDnsReply.u32HostIP); + } + } + else if((u8OpCode == SOCKET_CMD_RECV) || (u8OpCode == SOCKET_CMD_RECVFROM) || (u8OpCode == SOCKET_CMD_SSL_RECV)) + { + SOCKET sock; + sint16 s16RecvStatus; + tstrRecvReply strRecvReply; + uint16 u16ReadSize; + tstrSocketRecvMsg strRecvMsg; + uint8 u8CallbackMsgID = SOCKET_MSG_RECV; + uint16 u16DataOffset; + + if(u8OpCode == SOCKET_CMD_RECVFROM) + u8CallbackMsgID = SOCKET_MSG_RECVFROM; + + /* Read RECV REPLY data structure. + */ + u16ReadSize = sizeof(tstrRecvReply); + if(hif_receive(u32Address, (uint8*)&strRecvReply, u16ReadSize, 0) == M2M_SUCCESS) + { + uint16 u16SessionID = 0; + + sock = strRecvReply.sock; + u16SessionID = strRecvReply.u16SessionID; + M2M_DBG("recv callback session ID = %d\r\n",u16SessionID); + + /* Reset the Socket RX Pending Flag. + */ + gastrSockets[sock].bIsRecvPending = 0; + + s16RecvStatus = NM_BSP_B_L_16(strRecvReply.s16RecvStatus); + u16DataOffset = NM_BSP_B_L_16(strRecvReply.u16DataOffset); + strRecvMsg.strRemoteAddr.sin_port = strRecvReply.strRemoteAddr.u16Port; + strRecvMsg.strRemoteAddr.sin_addr.s_addr = strRecvReply.strRemoteAddr.u32IPAddr; + + if(u16SessionID == gastrSockets[sock].u16SessionID) + { +#ifdef ARDUINO + if((s16RecvStatus > 0) && (s16RecvStatus < (sint32)u16BufferSize)) +#else + if((s16RecvStatus > 0) && (s16RecvStatus < u16BufferSize)) +#endif + { + /* Skip incoming bytes until reaching the Start of Application Data. + */ + u32Address += u16DataOffset; + + /* Read the Application data and deliver it to the application callback in + the given application buffer. If the buffer is smaller than the received data, + the data is passed to the application in chunks according to its buffer size. + */ + u16ReadSize = (uint16)s16RecvStatus; + Socket_ReadSocketData(sock, &strRecvMsg, u8CallbackMsgID, u32Address, u16ReadSize); + } + else + { + strRecvMsg.s16BufferSize = s16RecvStatus; + strRecvMsg.pu8Buffer = NULL; + if(gpfAppSocketCb) + gpfAppSocketCb(sock,u8CallbackMsgID, &strRecvMsg); + } + } + else + { + M2M_DBG("Discard recv callback %d %d \r\n",u16SessionID , gastrSockets[sock].u16SessionID); + if(u16ReadSize < u16BufferSize) + { + if(hif_receive(0, NULL, 0, 1) == M2M_SUCCESS) + M2M_DBG("hif_receive Success\n"); + else +#ifdef ARDUINO + { +#endif + M2M_DBG("hif_receive Fail\n"); +#ifdef ARDUINO + } +#endif + } + } + } + } + else if((u8OpCode == SOCKET_CMD_SEND) || (u8OpCode == SOCKET_CMD_SENDTO) || (u8OpCode == SOCKET_CMD_SSL_SEND)) + { + SOCKET sock; + sint16 s16Rcvd; + tstrSendReply strReply; + uint8 u8CallbackMsgID = SOCKET_MSG_SEND; + + if(u8OpCode == SOCKET_CMD_SENDTO) + u8CallbackMsgID = SOCKET_MSG_SENDTO; + + if(hif_receive(u32Address, (uint8*)&strReply, sizeof(tstrSendReply), 0) == M2M_SUCCESS) + { + uint16 u16SessionID = 0; + + sock = strReply.sock; + u16SessionID = strReply.u16SessionID; + M2M_DBG("send callback session ID = %d\r\n",u16SessionID); + + s16Rcvd = NM_BSP_B_L_16(strReply.s16SentBytes); + + if(u16SessionID == gastrSockets[sock].u16SessionID) + { + if(gpfAppSocketCb) + gpfAppSocketCb(sock,u8CallbackMsgID, &s16Rcvd); + } + else + { + M2M_DBG("Discard send callback %d %d \r\n",u16SessionID , gastrSockets[sock].u16SessionID); + } + } + } + else if(u8OpCode == SOCKET_CMD_PING) + { + tstrPingReply strPingReply; + if(hif_receive(u32Address, (uint8*)&strPingReply, sizeof(tstrPingReply), 1) == M2M_SUCCESS) + { + gfpPingCb = (void (*)(uint32 , uint32 , uint8))(uintptr_t)strPingReply.u32CmdPrivate; + if(gfpPingCb != NULL) + { + gfpPingCb(strPingReply.u32IPAddr, strPingReply.u32RTT, strPingReply.u8ErrorCode); + } + } + } +} +/********************************************************************* +Function + socketInit + +Description + +Return + None. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +void socketInit(void) +{ + if(gbSocketInit == 0) + { + m2m_memset((uint8*)gastrSockets, 0, MAX_SOCKET * sizeof(tstrSocket)); + hif_register_cb(M2M_REQ_GROUP_IP,m2m_ip_cb); + gbSocketInit = 1; + gu16SessionID = 0; + } +} +/********************************************************************* +Function + socketDeinit + +Description + +Return + None. + +Author + Samer Sarhan + +Version + 1.0 + +Date + 27 Feb 2015 +*********************************************************************/ +void socketDeinit(void) +{ + m2m_memset((uint8*)gastrSockets, 0, MAX_SOCKET * sizeof(tstrSocket)); + hif_register_cb(M2M_REQ_GROUP_IP, NULL); + gpfAppSocketCb = NULL; + gpfAppResolveCb = NULL; + gbSocketInit = 0; +} +/********************************************************************* +Function + registerSocketCallback + +Description + +Return + None. + +Author + Ahmed Ezzat + +Versio + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +void registerSocketCallback(tpfAppSocketCb pfAppSocketCb, tpfAppResolveCb pfAppResolveCb) +{ + gpfAppSocketCb = pfAppSocketCb; + gpfAppResolveCb = pfAppResolveCb; +} + +/********************************************************************* +Function + socket + +Description + Creates a socket. + +Return + - Negative value for error. + - ZERO or positive value as a socket ID if successful. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags) +{ + SOCKET sock = -1; + uint8 u8SockID; + uint8 u8Count; + volatile tstrSocket *pstrSock; + static volatile uint8 u8NextTcpSock = 0; + static volatile uint8 u8NextUdpSock = 0; + + /* The only supported family is the AF_INET for UDP and TCP transport layer protocols. */ + if(u16Domain == AF_INET) + { + if(u8Type == SOCK_STREAM) + { + for(u8Count = 0; u8Count < TCP_SOCK_MAX; u8Count ++) + { + u8SockID = u8NextTcpSock; + pstrSock = &gastrSockets[u8NextTcpSock]; + u8NextTcpSock = (u8NextTcpSock + 1) % TCP_SOCK_MAX; + if(!pstrSock->bIsUsed) + { + sock = (SOCKET)u8SockID; + break; + } + } + } + else if(u8Type == SOCK_DGRAM) + { + volatile tstrSocket *pastrUDPSockets = &gastrSockets[TCP_SOCK_MAX]; + for(u8Count = 0; u8Count < UDP_SOCK_MAX; u8Count ++) + { + u8SockID = u8NextUdpSock; + pstrSock = &pastrUDPSockets[u8NextUdpSock]; + u8NextUdpSock = (u8NextUdpSock + 1) % UDP_SOCK_MAX; + if(!pstrSock->bIsUsed) + { + sock = (SOCKET)(u8SockID + TCP_SOCK_MAX); + break; + } + } + } + + if(sock >= 0) + { + m2m_memset((uint8*)pstrSock, 0, sizeof(tstrSocket)); + pstrSock->bIsUsed = 1; + + /* The session ID is used to distinguish different socket connections + by comparing the assigned session ID to the one reported by the firmware*/ + ++gu16SessionID; + if(gu16SessionID == 0) + ++gu16SessionID; + + pstrSock->u16SessionID = gu16SessionID; + M2M_INFO("Socket %d session ID = %d\r\n",sock, gu16SessionID ); + + if(u8Flags & SOCKET_FLAGS_SSL) + { + tstrSSLSocketCreateCmd strSSLCreate; + strSSLCreate.sslSock = sock; + pstrSock->u8SSLFlags = SSL_FLAGS_ACTIVE | SSL_FLAGS_NO_TX_COPY; + SOCKET_REQUEST(SOCKET_CMD_SSL_CREATE, (uint8*)&strSSLCreate, sizeof(tstrSSLSocketCreateCmd), 0, 0, 0); + } + } + } + return sock; +} +/********************************************************************* +Function + bind + +Description + Request to bind a socket on a local address. + +Return + + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 5 June 2012 +*********************************************************************/ +sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen) +{ + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + if((pstrAddr != NULL) && (sock >= 0) && (gastrSockets[sock].bIsUsed == 1) && (u8AddrLen != 0)) + { + tstrBindCmd strBind; + uint8 u8CMD = SOCKET_CMD_BIND; + if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) + { + u8CMD = SOCKET_CMD_SSL_BIND; + } + + /* Build the bind request. */ + strBind.sock = sock; + m2m_memcpy((uint8 *)&strBind.strAddr, (uint8 *)pstrAddr, sizeof(tstrSockAddr)); + strBind.u16SessionID = gastrSockets[sock].u16SessionID; + + /* Send the request. */ + s8Ret = SOCKET_REQUEST(u8CMD, (uint8*)&strBind,sizeof(tstrBindCmd) , NULL , 0, 0); + if(s8Ret != SOCK_ERR_NO_ERROR) + { + s8Ret = SOCK_ERR_INVALID; + } + } + return s8Ret; +} +/********************************************************************* +Function + listen + +Description + + +Return + + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 5 June 2012 +*********************************************************************/ +sint8 listen(SOCKET sock, uint8 backlog) +{ + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + + if(sock >= 0 && (gastrSockets[sock].bIsUsed == 1)) + { + tstrListenCmd strListen; + + strListen.sock = sock; + strListen.u8BackLog = backlog; + strListen.u16SessionID = gastrSockets[sock].u16SessionID; + + s8Ret = SOCKET_REQUEST(SOCKET_CMD_LISTEN, (uint8*)&strListen, sizeof(tstrListenCmd), NULL, 0, 0); + if(s8Ret != SOCK_ERR_NO_ERROR) + { + s8Ret = SOCK_ERR_INVALID; + } + } + return s8Ret; +} +/********************************************************************* +Function + accept + +Description + +Return + + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 5 June 2012 +*********************************************************************/ +sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)addr; + (void)addrlen; +#endif + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + + if(sock >= 0 && (gastrSockets[sock].bIsUsed == 1) ) + { + s8Ret = SOCK_ERR_NO_ERROR; + } + return s8Ret; +} +/********************************************************************* +Function + connect + +Description + Connect to a remote TCP Server. + +Return + + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 5 June 2012 +*********************************************************************/ +#ifdef ARDUINO +sint8 connectSocket(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen) +#else +sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen) +#endif +{ + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + if((sock >= 0) && (pstrAddr != NULL) && (gastrSockets[sock].bIsUsed == 1) && (u8AddrLen != 0)) + { + tstrConnectCmd strConnect; + uint8 u8Cmd = SOCKET_CMD_CONNECT; + if((gastrSockets[sock].u8SSLFlags) & SSL_FLAGS_ACTIVE) + { + u8Cmd = SOCKET_CMD_SSL_CONNECT; + strConnect.u8SslFlags = gastrSockets[sock].u8SSLFlags; + } + strConnect.sock = sock; + m2m_memcpy((uint8 *)&strConnect.strAddr, (uint8 *)pstrAddr, sizeof(tstrSockAddr)); + + strConnect.u16SessionID = gastrSockets[sock].u16SessionID; + s8Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strConnect,sizeof(tstrConnectCmd), NULL, 0, 0); + if(s8Ret != SOCK_ERR_NO_ERROR) + { + s8Ret = SOCK_ERR_INVALID; + } + } + return s8Ret; +} +/********************************************************************* +Function + send + +Description + +Return + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 5 June 2012 +*********************************************************************/ +sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags) +{ +#ifdef ARDUINO + (void)flags; // Silence "unused" warning +#endif + sint16 s16Ret = SOCK_ERR_INVALID_ARG; + + if((sock >= 0) && (pvSendBuffer != NULL) && (u16SendLength <= SOCKET_BUFFER_MAX_LENGTH) && (gastrSockets[sock].bIsUsed == 1)) + { + uint16 u16DataOffset; + tstrSendCmd strSend; + uint8 u8Cmd; + + u8Cmd = SOCKET_CMD_SEND; + u16DataOffset = TCP_TX_PACKET_OFFSET; + + strSend.sock = sock; + strSend.u16DataSize = NM_BSP_B_L_16(u16SendLength); + strSend.u16SessionID = gastrSockets[sock].u16SessionID; + + if(sock >= TCP_SOCK_MAX) + { + u16DataOffset = UDP_TX_PACKET_OFFSET; + } + if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) + { + u8Cmd = SOCKET_CMD_SSL_SEND; + u16DataOffset = gastrSockets[sock].u16DataOffset; +#ifdef ARDUINO + extern uint32 nmdrv_firm_ver; + + if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 4, 0)) { + // firmware 19.3.0 and older only works with this specific offset + u16DataOffset = SSL_TX_PACKET_OFFSET; + } +#endif + } + + s16Ret = SOCKET_REQUEST(u8Cmd|M2M_REQ_DATA_PKT, (uint8*)&strSend, sizeof(tstrSendCmd), pvSendBuffer, u16SendLength, u16DataOffset); + if(s16Ret != SOCK_ERR_NO_ERROR) + { + s16Ret = SOCK_ERR_BUFFER_FULL; + } + } + return s16Ret; +} +/********************************************************************* +Function + sendto + +Description + +Return + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)flags; + (void)u8AddrLen; +#endif + sint16 s16Ret = SOCK_ERR_INVALID_ARG; + + if((sock >= 0) && (pvSendBuffer != NULL) && (u16SendLength <= SOCKET_BUFFER_MAX_LENGTH) && (gastrSockets[sock].bIsUsed == 1)) + { + if(gastrSockets[sock].bIsUsed) + { + tstrSendCmd strSendTo; + + m2m_memset((uint8*)&strSendTo, 0, sizeof(tstrSendCmd)); + + strSendTo.sock = sock; + strSendTo.u16DataSize = NM_BSP_B_L_16(u16SendLength); + strSendTo.u16SessionID = gastrSockets[sock].u16SessionID; + + if(pstrDestAddr != NULL) + { + struct sockaddr_in *pstrAddr; + pstrAddr = (void*)pstrDestAddr; + + strSendTo.strAddr.u16Family = pstrAddr->sin_family; + strSendTo.strAddr.u16Port = pstrAddr->sin_port; + strSendTo.strAddr.u32IPAddr = pstrAddr->sin_addr.s_addr; + } + s16Ret = SOCKET_REQUEST(SOCKET_CMD_SENDTO|M2M_REQ_DATA_PKT, (uint8*)&strSendTo, sizeof(tstrSendCmd), + pvSendBuffer, u16SendLength, UDP_TX_PACKET_OFFSET); + + if(s16Ret != SOCK_ERR_NO_ERROR) + { + s16Ret = SOCK_ERR_BUFFER_FULL; + } + } + } + return s16Ret; +} +/********************************************************************* +Function + recv + +Description + +Return + + +Author + Ahmed Ezzat + +Version + 1.0 + 2.0 9 April 2013 --> Add timeout for recv operation. + +Date + 5 June 2012 +*********************************************************************/ +sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec) +{ + sint16 s16Ret = SOCK_ERR_INVALID_ARG; + + if((sock >= 0) && (pvRecvBuf != NULL) && (u16BufLen != 0) && (gastrSockets[sock].bIsUsed == 1)) + { + s16Ret = SOCK_ERR_NO_ERROR; + gastrSockets[sock].pu8UserBuffer = (uint8*)pvRecvBuf; + gastrSockets[sock].u16UserBufferSize = u16BufLen; + + if(!gastrSockets[sock].bIsRecvPending) + { + tstrRecvCmd strRecv; + uint8 u8Cmd = SOCKET_CMD_RECV; + + gastrSockets[sock].bIsRecvPending = 1; + if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) + { + u8Cmd = SOCKET_CMD_SSL_RECV; + } + + /* Check the timeout value. */ + if(u32Timeoutmsec == 0) + strRecv.u32Timeoutmsec = 0xFFFFFFFF; + else + strRecv.u32Timeoutmsec = NM_BSP_B_L_32(u32Timeoutmsec); + strRecv.sock = sock; + strRecv.u16SessionID = gastrSockets[sock].u16SessionID; + + s16Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strRecv, sizeof(tstrRecvCmd), NULL , 0, 0); + if(s16Ret != SOCK_ERR_NO_ERROR) + { + s16Ret = SOCK_ERR_BUFFER_FULL; + } + } + } + return s16Ret; +} +/********************************************************************* +Function + close + +Description + +Return + None. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +sint8 close(SOCKET sock) +{ + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + M2M_INFO("Sock to delete <%d>\n", sock); + if(sock >= 0 && (gastrSockets[sock].bIsUsed == 1)) + { + uint8 u8Cmd = SOCKET_CMD_CLOSE; + tstrCloseCmd strclose; + strclose.sock = sock; + strclose.u16SessionID = gastrSockets[sock].u16SessionID; + + gastrSockets[sock].bIsUsed = 0; + gastrSockets[sock].u16SessionID =0; + + if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) + { + u8Cmd = SOCKET_CMD_SSL_CLOSE; + } + s8Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strclose, sizeof(tstrCloseCmd), NULL,0, 0); + if(s8Ret != SOCK_ERR_NO_ERROR) + { + s8Ret = SOCK_ERR_INVALID; + } + m2m_memset((uint8*)&gastrSockets[sock], 0, sizeof(tstrSocket)); + } + return s8Ret; +} +/********************************************************************* +Function + recvfrom + +Description + +Return + + +Author + Ahmed Ezzat + +Version + 1.0 + 2.0 9 April 2013 --> Add timeout for recv operation. + +Date + 5 June 2012 +*********************************************************************/ +sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec) +{ + sint16 s16Ret = SOCK_ERR_NO_ERROR; + if((sock >= 0) && (pvRecvBuf != NULL) && (u16BufLen != 0) && (gastrSockets[sock].bIsUsed == 1)) + { + if(gastrSockets[sock].bIsUsed) + { + s16Ret = SOCK_ERR_NO_ERROR; + gastrSockets[sock].pu8UserBuffer = (uint8*)pvRecvBuf; + gastrSockets[sock].u16UserBufferSize = u16BufLen; + + if(!gastrSockets[sock].bIsRecvPending) + { + tstrRecvCmd strRecv; + + gastrSockets[sock].bIsRecvPending = 1; + + /* Check the timeout value. */ + if(u32Timeoutmsec == 0) + strRecv.u32Timeoutmsec = 0xFFFFFFFF; + else + strRecv.u32Timeoutmsec = NM_BSP_B_L_32(u32Timeoutmsec); + strRecv.sock = sock; + strRecv.u16SessionID = gastrSockets[sock].u16SessionID; + + s16Ret = SOCKET_REQUEST(SOCKET_CMD_RECVFROM, (uint8*)&strRecv, sizeof(tstrRecvCmd), NULL , 0, 0); + if(s16Ret != SOCK_ERR_NO_ERROR) + { + s16Ret = SOCK_ERR_BUFFER_FULL; + } + } + } + } + else + { + s16Ret = SOCK_ERR_INVALID_ARG; + } + return s16Ret; +} +/********************************************************************* +Function + nmi_inet_addr + +Description + +Return + Unsigned 32-bit integer representing the IP address in Network + byte order. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +uint32 nmi_inet_addr(char *pcIpAddr) +{ + uint8 tmp; + uint32 u32IP = 0; + uint8 au8IP[4]; + uint8 c; + uint8 i, j; + + tmp = 0; + + for(i = 0; i < 4; ++i) + { + j = 0; + do + { + c = *pcIpAddr; + ++j; + if(j > 4) + { + return 0; + } + if(c == '.' || c == 0) + { + au8IP[i] = tmp; + tmp = 0; + } + else if(c >= '0' && c <= '9') + { + tmp = (tmp * 10) + (c - '0'); + } + else + { + return 0; + } + ++pcIpAddr; + } while(c != '.' && c != 0); + } + m2m_memcpy((uint8*)&u32IP, au8IP, 4); + return u32IP; +} +/********************************************************************* +Function + gethostbyname + +Description + +Return + None. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +sint8 gethostbyname(uint8 * pcHostName) +{ + sint8 s8Err = SOCK_ERR_INVALID_ARG; + uint8 u8HostNameSize = (uint8)m2m_strlen(pcHostName); + if(u8HostNameSize <= HOSTNAME_MAX_SIZE) + { + s8Err = SOCKET_REQUEST(SOCKET_CMD_DNS_RESOLVE, (uint8*)pcHostName, u8HostNameSize + 1, NULL,0, 0); + } + return s8Err; +} +/********************************************************************* +Function + setsockopt + +Description + +Return + None. + +Author + Abdelrahman Diab + +Version + 1.0 + +Date + 9 September 2014 +*********************************************************************/ +static sint8 sslSetSockOpt(SOCKET sock, uint8 u8Opt, const void *pvOptVal, uint16 u16OptLen) +{ + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + if(sock < TCP_SOCK_MAX) + { + if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) + { + if(u8Opt == SO_SSL_BYPASS_X509_VERIF) + { + int optVal = *((int*)pvOptVal); + if(optVal) + { + gastrSockets[sock].u8SSLFlags |= SSL_FLAGS_BYPASS_X509; + } + else + { + gastrSockets[sock].u8SSLFlags &= ~SSL_FLAGS_BYPASS_X509; + } + s8Ret = SOCK_ERR_NO_ERROR; + } + else if(u8Opt == SO_SSL_ENABLE_SESSION_CACHING) + { + int optVal = *((int*)pvOptVal); + if(optVal) + { + gastrSockets[sock].u8SSLFlags |= SSL_FLAGS_CACHE_SESSION; + } + else + { + gastrSockets[sock].u8SSLFlags &= ~SSL_FLAGS_CACHE_SESSION; + } + s8Ret = SOCK_ERR_NO_ERROR; + } + else if(u8Opt == SO_SSL_ENABLE_SNI_VALIDATION) + { + int optVal = *((int*)pvOptVal); + if(optVal) + { + gastrSockets[sock].u8SSLFlags |= SSL_FLAGS_CHECK_SNI; + } + else + { + gastrSockets[sock].u8SSLFlags &= ~SSL_FLAGS_CHECK_SNI; + } + s8Ret = SOCK_ERR_NO_ERROR; + } + else if(u8Opt == SO_SSL_SNI) + { + if(u16OptLen < HOSTNAME_MAX_SIZE) + { + uint8 *pu8SNI = (uint8*)pvOptVal; + tstrSSLSetSockOptCmd strCmd; + + strCmd.sock = sock; + strCmd.u16SessionID = gastrSockets[sock].u16SessionID; + strCmd.u8Option = u8Opt; + strCmd.u32OptLen = u16OptLen; + m2m_memcpy(strCmd.au8OptVal, pu8SNI, HOSTNAME_MAX_SIZE); + + if(SOCKET_REQUEST(SOCKET_CMD_SSL_SET_SOCK_OPT, (uint8*)&strCmd, sizeof(tstrSSLSetSockOptCmd), + 0, 0, 0) == M2M_ERR_MEM_ALLOC) + { + s8Ret = SOCKET_REQUEST(SOCKET_CMD_SSL_SET_SOCK_OPT | M2M_REQ_DATA_PKT, + (uint8*)&strCmd, sizeof(tstrSSLSetSockOptCmd), 0, 0, 0); + } + s8Ret = SOCK_ERR_NO_ERROR; + } + else + { + M2M_ERR("SNI Exceeds Max Length\n"); + } + } + else + { + M2M_ERR("Unknown SSL Socket Option %d\n",u8Opt); + } + } + else + { + M2M_ERR("Not SSL Socket\n"); + } + } + return s8Ret; +} +/********************************************************************* +Function + setsockopt + +Description + +Return + None. + +Author + Abdelrahman Diab + +Version + 1.0 + +Date + 9 September 2014 +*********************************************************************/ +sint8 setsockopt(SOCKET sock, uint8 u8Level, uint8 option_name, + const void *option_value, uint16 u16OptionLen) +{ + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + if((sock >= 0) && (option_value != NULL) && (gastrSockets[sock].bIsUsed == 1)) + { + if(u8Level == SOL_SSL_SOCKET) + { + s8Ret = sslSetSockOpt(sock, option_name, option_value, u16OptionLen); + } + else + { + uint8 u8Cmd = SOCKET_CMD_SET_SOCKET_OPTION; + tstrSetSocketOptCmd strSetSockOpt; + strSetSockOpt.u8Option=option_name; + strSetSockOpt.sock = sock; + strSetSockOpt.u32OptionValue = *(uint32*)option_value; + strSetSockOpt.u16SessionID = gastrSockets[sock].u16SessionID; + + s8Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strSetSockOpt, sizeof(tstrSetSocketOptCmd), NULL,0, 0); + if(s8Ret != SOCK_ERR_NO_ERROR) + { + s8Ret = SOCK_ERR_INVALID; + } + } + } + return s8Ret; +} +/********************************************************************* +Function + getsockopt + +Description + +Return + None. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 24 August 2014 +*********************************************************************/ +sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8* pu8OptLen) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)sock; + (void)u8Level; + (void)u8OptName; + (void)pvOptValue; + (void)pu8OptLen; +#endif + /* TBD */ + return M2M_SUCCESS; +} +/********************************************************************* +Function + m2m_ping_req + +Description + Send Ping request. + +Return + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2015 +*********************************************************************/ +sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb) +{ + sint8 s8Ret = M2M_ERR_INVALID_ARG; + + if((u32DstIP != 0) && (fpPingCb != NULL)) + { + tstrPingCmd strPingCmd; + + strPingCmd.u16PingCount = 1; + strPingCmd.u32DestIPAddr = u32DstIP; +#ifdef ARDUINO + strPingCmd.u32CmdPrivate = (uint32)(uintptr_t)(fpPingCb); +#else + strPingCmd.u32CmdPrivate = (uint32)(fpPingCb); +#endif + strPingCmd.u8TTL = u8TTL; + + s8Ret = SOCKET_REQUEST(SOCKET_CMD_PING, (uint8*)&strPingCmd, sizeof(tstrPingCmd), NULL, 0, 0); + } + return s8Ret; +} +/********************************************************************* +Function + sslEnableCertExpirationCheck + +Description + Enable/Disable TLS Certificate Expiration Check. + +Return + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + +*********************************************************************/ +sint8 sslEnableCertExpirationCheck(tenuSslCertExpSettings enuValidationSetting) +{ + tstrSslCertExpSettings strSettings; + strSettings.u32CertExpValidationOpt = (uint32)enuValidationSetting; + return SOCKET_REQUEST(SOCKET_CMD_SSL_EXP_CHECK, (uint8*)&strSettings, sizeof(tstrSslCertExpSettings), NULL, 0, 0); +} \ No newline at end of file diff --git a/feather_sensor_lte/libraries/WiFi101/src/socket/source/socket_buffer.c b/feather_sensor_lte/libraries/WiFi101/src/socket/source/socket_buffer.c new file mode 100644 index 0000000..d100558 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/socket/source/socket_buffer.c @@ -0,0 +1,232 @@ +/** + * + * \file + * + * \brief BSD compatible socket interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include +#include "socket/include/socket.h" +#include "driver/source/m2m_hif.h" +#include "socket/source/socket_internal.h" +#include "socket/include/socket_buffer.h" +#include "driver/include/m2m_periph.h" + +tstrSocketBuffer gastrSocketBuffer[MAX_SOCKET]; + +extern uint8 hif_small_xfer; + +void socketBufferInit(void) +{ + memset(gastrSocketBuffer, 0, sizeof(gastrSocketBuffer)); +} + +void socketBufferRegister(SOCKET socket, uint32 *flag, uint32 *head, uint32 *tail, uint8 *buffer) +{ + gastrSocketBuffer[socket].flag = flag; + gastrSocketBuffer[socket].head = head; + gastrSocketBuffer[socket].tail = tail; + gastrSocketBuffer[socket].buffer = buffer; +} + +void socketBufferUnregister(SOCKET socket) +{ + gastrSocketBuffer[socket].flag = 0; + gastrSocketBuffer[socket].head = 0; + gastrSocketBuffer[socket].tail = 0; + gastrSocketBuffer[socket].buffer = 0; +} + +void socketBufferCb(SOCKET sock, uint8 u8Msg, void *pvMsg) +{ + switch (u8Msg) { + /* Socket connected. */ + case SOCKET_MSG_CONNECT: + { + tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg *)pvMsg; + if (pstrConnect && pstrConnect->s8Error >= 0) { + recv(sock, gastrSocketBuffer[sock].buffer, SOCKET_BUFFER_MTU, 0); + *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_CONNECTED; + } else { + close(sock); + } + } + break; + + /* TCP Data receive. */ + case SOCKET_MSG_RECV: + { + // Network led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); + + tstrSocketRecvMsg *pstrRecv = (tstrSocketRecvMsg *)pvMsg; + if (pstrRecv && pstrRecv->s16BufferSize > 0) { + /* Protect against overflow. */ + if (*(gastrSocketBuffer[sock].head) + pstrRecv->s16BufferSize > SOCKET_BUFFER_TCP_SIZE) { + *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_FULL; + break; + } + + /* Add data size. */ + *(gastrSocketBuffer[sock].head) += pstrRecv->s16BufferSize; + + /* Buffer full, stop reception. */ + if (SOCKET_BUFFER_TCP_SIZE - *(gastrSocketBuffer[sock].head) < SOCKET_BUFFER_MTU) { + if (pstrRecv->u16RemainingSize != 0) { + *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_FULL; + } + } + else { + recv(sock, gastrSocketBuffer[sock].buffer + *(gastrSocketBuffer[sock].head), + SOCKET_BUFFER_MTU, 0); + } + } + /* Test EOF (Socket closed) condition for TCP socket. */ + else { + *(gastrSocketBuffer[sock].flag) &= ~SOCKET_BUFFER_FLAG_CONNECTED; + close(sock); + } + + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + } + break; + + /* UDP Data receive. */ + case SOCKET_MSG_RECVFROM: + { + // Network led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); + + tstrSocketRecvMsg *pstrRecv = (tstrSocketRecvMsg *)pvMsg; + if (pstrRecv && pstrRecv->s16BufferSize > 0) { + + if (hif_small_xfer < 2) { + uint32 h = *(gastrSocketBuffer[sock].head); + uint8 *buf = gastrSocketBuffer[sock].buffer; + uint16 sz = pstrRecv->s16BufferSize + pstrRecv->u16RemainingSize; + + /* Store packet size. */ + buf[h++] = sz >> 8; + buf[h++] = sz; + + /* Store remote host port. */ + buf[h++] = pstrRecv->strRemoteAddr.sin_port; + buf[h++] = pstrRecv->strRemoteAddr.sin_port >> 8; + + /* Store remote host IP. */ + buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr >> 24; + buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr >> 16; + buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr >> 8; + buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr; + + /* Data received. */ + *(gastrSocketBuffer[sock].head) = h + pstrRecv->s16BufferSize; + } + else { + /* Data received. */ + *(gastrSocketBuffer[sock].head) += pstrRecv->s16BufferSize; + } + + /* Buffer full, stop reception. */ + if (SOCKET_BUFFER_UDP_SIZE - *(gastrSocketBuffer[sock].head) < SOCKET_BUFFER_MTU + SOCKET_BUFFER_UDP_HEADER_SIZE) { + if (pstrRecv->u16RemainingSize != 0) { + *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_FULL; + } + } + else { + if (hif_small_xfer && hif_small_xfer != 3) { + recvfrom(sock, gastrSocketBuffer[sock].buffer + *(gastrSocketBuffer[sock].head), + SOCKET_BUFFER_MTU, 0); + } + else { + recvfrom(sock, gastrSocketBuffer[sock].buffer + *(gastrSocketBuffer[sock].head) + SOCKET_BUFFER_UDP_HEADER_SIZE, + SOCKET_BUFFER_MTU, 0); + } + } + } + + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + } + break; + + /* Socket bind. */ + case SOCKET_MSG_BIND: + { + tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg *)pvMsg; + if (pstrBind && pstrBind->status == 0) { + *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_BIND; + /* TCP socket needs to enter Listen state. */ + if (sock < TCP_SOCK_MAX) { + listen(sock, 0); + } + /* UDP socket only needs to supply the receive buffer. */ + /* +8 is used to store size, port and IP of incoming data. */ + else { + recvfrom(sock, gastrSocketBuffer[sock].buffer + SOCKET_BUFFER_UDP_HEADER_SIZE, + SOCKET_BUFFER_MTU, 0); + } + } + } + break; + + /* Connect accept. */ + case SOCKET_MSG_ACCEPT: + { + tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg *)pvMsg; + if (pstrAccept && pstrAccept->sock >= 0) { + if (*(gastrSocketBuffer[sock].flag) & SOCKET_BUFFER_FLAG_SPAWN) { + /* One spawn connection already waiting, discard current one. */ + close(pstrAccept->sock); + } + else { + /* Use flag to store spawn TCP descriptor. */ + *(gastrSocketBuffer[sock].flag) &= ~SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK; + *(gastrSocketBuffer[sock].flag) |= (((uint32)pstrAccept->sock) << SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS); + *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_SPAWN; + } + } + } + break; + + } +} diff --git a/feather_sensor_lte/libraries/WiFi101/src/socket/source/socket_internal.h b/feather_sensor_lte/libraries/WiFi101/src/socket/source/socket_internal.h new file mode 100644 index 0000000..1904c23 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/socket/source/socket_internal.h @@ -0,0 +1,71 @@ +/** + * + * \file + * + * \brief BSD compatible socket interface internal types. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +#ifndef __SOCKET_INTERNAL_H__ +#define __SOCKET_INTERNAL_H__ + + +#ifdef __cplusplus +extern "C" { +#endif + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "socket/include/socket.h" +#include "socket/include/m2m_socket_host_if.h" + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +NMI_API void Socket_ReadSocketData(SOCKET sock, tstrSocketRecvMsg *pstrRecv,uint8 u8SocketMsg, + uint32 u32StartAddress,uint16 u16ReadCount); +#ifdef ARDUINO +NMI_API void Socket_ReadSocketData_Small(void); +#endif + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* __SOCKET_H__ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/spi_flash/include/spi_flash.h b/feather_sensor_lte/libraries/WiFi101/src/spi_flash/include/spi_flash.h new file mode 100644 index 0000000..a85aa72 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/spi_flash/include/spi_flash.h @@ -0,0 +1,233 @@ +/** + * + * \file + * + * \brief WINC1500 SPI Flash. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/** \defgroup SPIFLASH Spi Flash + * @file spi_flash.h + * @brief This file describe SPI flash APIs, how to use it and limitations with each one. + * @section Example + * This example illustrates a complete guide of how to use these APIs. + * @code{.c} + #include "spi_flash.h" + + #define DATA_TO_REPLACE "THIS IS A NEW SECTOR IN FLASH" + + int main() + { + uint8 au8FlashContent[FLASH_SECTOR_SZ] = {0}; + uint32 u32FlashTotalSize = 0; + uint32 u32FlashOffset = 0; + + ret = m2m_wifi_download_mode(); + if(M2M_SUCCESS != ret) + { + printf("Unable to enter download mode\r\n"); + } + else + { + u32FlashTotalSize = spi_flash_get_size(); + } + + while((u32FlashTotalSize > u32FlashOffset) && (M2M_SUCCESS == ret)) + { + ret = spi_flash_read(au8FlashContent, u32FlashOffset, FLASH_SECTOR_SZ); + if(M2M_SUCCESS != ret) + { + printf("Unable to read SPI sector\r\n"); + break; + } + memcpy(au8FlashContent, DATA_TO_REPLACE, strlen(DATA_TO_REPLACE)); + + ret = spi_flash_erase(u32FlashOffset, FLASH_SECTOR_SZ); + if(M2M_SUCCESS != ret) + { + printf("Unable to erase SPI sector\r\n"); + break; + } + + ret = spi_flash_write(au8FlashContent, u32FlashOffset, FLASH_SECTOR_SZ); + if(M2M_SUCCESS != ret) + { + printf("Unable to write SPI sector\r\n"); + break; + } + u32FlashOffset += FLASH_SECTOR_SZ; + } + + if(M2M_SUCCESS == ret) + { + printf("Successful operations\r\n"); + } + else + { + printf("Failed operations\r\n"); + } + + while(1); + return M2M_SUCCESS; + } + * @endcode + */ + +#ifndef __SPI_FLASH_H__ +#define __SPI_FLASH_H__ +#include "common/include/nm_common.h" +#include "bus_wrapper/include/nm_bus_wrapper.h" +#include "driver/source/nmbus.h" +#include "driver/source/nmasic.h" + +#ifdef ARDUINO +#ifdef __cplusplus +extern "C" { +#endif +#endif + +/** + * @fn spi_flash_enable + * @brief Enable spi flash operations + * @version 1.0 + */ +sint8 spi_flash_enable(uint8 enable); +/** \defgroup SPIFLASHAPI Function + * @ingroup SPIFLASH + */ + + /** @defgroup SPiFlashGetFn spi_flash_get_size + * @ingroup SPIFLASHAPI + */ + /**@{*/ +/*! + * @fn uint32 spi_flash_get_size(void); + * @brief Returns with \ref uint32 value which is total flash size\n + * @note Returned value in Mb (Mega Bit). + * @return SPI flash size in case of success and a ZERO value in case of failure. + */ +uint32 spi_flash_get_size(void); + /**@}*/ + + /** @defgroup SPiFlashRead spi_flash_read + * @ingroup SPIFLASHAPI + */ + /**@{*/ +/*! + * @fn sint8 spi_flash_read(uint8 *, uint32, uint32); + * @brief Read a specified portion of data from SPI Flash.\n + * @param [out] pu8Buf + * Pointer to data buffer which will fill in with data in case of successful operation. + * @param [in] u32Addr + * Address (Offset) to read from at the SPI flash. + * @param [in] u32Sz + * Total size of data to be read in bytes + * @warning + * - Address (offset) plus size of data must not exceed flash size.\n + * - No firmware is required for reading from SPI flash.\n + * - In case of there is a running firmware, it is required to pause your firmware first + * before any trial to access SPI flash to avoid any racing between host and running firmware on bus using + * @ref m2m_wifi_download_mode + * @note + * - It is blocking function\n + * @sa m2m_wifi_download_mode, spi_flash_get_size + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +sint8 spi_flash_read(uint8 *pu8Buf, uint32 u32Addr, uint32 u32Sz); + /**@}*/ + + /** @defgroup SPiFlashWrite spi_flash_write + * @ingroup SPIFLASHAPI + */ + /**@{*/ +/*! + * @fn sint8 spi_flash_write(uint8 *, uint32, uint32); + * @brief Write a specified portion of data to SPI Flash.\n + * @param [in] pu8Buf + * Pointer to data buffer which contains the required to be written. + * @param [in] u32Offset + * Address (Offset) to write at the SPI flash. + * @param [in] u32Sz + * Total number of size of data bytes + * @note + * - It is blocking function\n + * - It is user's responsibility to verify that data has been written successfully + * by reading data again and compare it with the original. + * @warning + * - Address (offset) plus size of data must not exceed flash size.\n + * - No firmware is required for writing to SPI flash.\n + * - In case of there is a running firmware, it is required to pause your firmware first + * before any trial to access SPI flash to avoid any racing between host and running firmware on bus using + * @ref m2m_wifi_download_mode. + * - Before writing to any section, it is required to erase it first. + * @sa m2m_wifi_download_mode, spi_flash_get_size, spi_flash_erase + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + + */ +sint8 spi_flash_write(uint8* pu8Buf, uint32 u32Offset, uint32 u32Sz); + /**@}*/ + + /** @defgroup SPiFlashErase spi_flash_erase + * @ingroup SPIFLASHAPI + */ + /**@{*/ +/*! + * @fn sint8 spi_flash_erase(uint32, uint32); + * @brief Erase a specified portion of SPI Flash.\n + * @param [in] u32Offset + * Address (Offset) to erase from the SPI flash. + * @param [in] u32Sz + * Size of SPI flash required to be erased. + * @note It is blocking function \n +* @warning +* - Address (offset) plus size of data must not exceed flash size.\n +* - No firmware is required for writing to SPI flash.\n + * - In case of there is a running firmware, it is required to pause your firmware first + * before any trial to access SPI flash to avoid any racing between host and running firmware on bus using + * @ref m2m_wifi_download_mode + * - It is blocking function\n + * @sa m2m_wifi_download_mode, spi_flash_get_size + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + + */ +sint8 spi_flash_erase(uint32 u32Offset, uint32 u32Sz); + /**@}*/ +#ifdef ARDUINO +#ifdef __cplusplus +} +#endif +#endif +#endif //__SPI_FLASH_H__ diff --git a/feather_sensor_lte/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h b/feather_sensor_lte/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h new file mode 100644 index 0000000..3b0da53 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h @@ -0,0 +1,245 @@ +/** + * + * \file + * + * \brief WINC1500 SPI Flash. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/** +* @file spi_flash_map.h +* @brief This module contains spi flash CONTENT +* @author M.S.M +* @date 17 SEPT 2013 +* @version 1.0 +*/ +#ifndef __SPI_FLASH_MAP_H__ +#define __SPI_FLASH_MAP_H__ + +#define FLASH_MAP_VER_0 (0) +#define FLASH_MAP_VER_1 (1) +#define FLASH_MAP_VER_2 (2) +#define FLASH_MAP_VER_3 (3) + +#define FLASH_MAP_VERSION FLASH_MAP_VER_3 + +//#define DOWNLOAD_ROLLBACK +//#define OTA_GEN +#define _PROGRAM_POWER_SAVE_ + +/* =======*=======*=======*=======*======= + * General Sizes for Flash Memory + * =======*=======*=======*=======*======= + */ + +#define FLASH_START_ADDR (0UL) +/*! location :xxxK + * "S:xxxK" -means-> Size is :xxxK + */ + +/* + * Boot Firmware: which used to select which firmware to run + * + */ +#define M2M_BOOT_FIRMWARE_STARTING_ADDR (FLASH_START_ADDR) +#define M2M_BOOT_FIRMWARE_FLASH_SZ (FLASH_SECTOR_SZ) + +/* + * Control Section: which used by Boot firmware + * + */ +#define M2M_CONTROL_FLASH_OFFSET (M2M_BOOT_FIRMWARE_STARTING_ADDR + M2M_BOOT_FIRMWARE_FLASH_SZ) +#define M2M_CONTROL_FLASH_BKP_OFFSET (M2M_CONTROL_FLASH_OFFSET + FLASH_SECTOR_SZ) +#define M2M_CONTROL_FLASH_SEC_SZ (FLASH_SECTOR_SZ) +#define M2M_CONTROL_FLASH_TOTAL_SZ (FLASH_SECTOR_SZ * 2) + +/* + * LUT for PLL and TX Gain settings: + * + */ +#define M2M_PLL_FLASH_OFFSET (M2M_CONTROL_FLASH_OFFSET + M2M_CONTROL_FLASH_TOTAL_SZ) +#define M2M_PLL_FLASH_SZ (1024 * 1) +#define M2M_GAIN_FLASH_OFFSET (M2M_PLL_FLASH_OFFSET + M2M_PLL_FLASH_SZ) +#define M2M_GAIN_FLASH_SZ (M2M_CONFIG_SECT_TOTAL_SZ - M2M_PLL_FLASH_SZ) +#define M2M_CONFIG_SECT_TOTAL_SZ (FLASH_SECTOR_SZ) + +/* + * Certificate: + * + */ +#define M2M_TLS_ROOTCER_FLASH_OFFSET (M2M_PLL_FLASH_OFFSET + M2M_CONFIG_SECT_TOTAL_SZ) +#define M2M_TLS_ROOTCER_FLASH_SIZE (FLASH_SECTOR_SZ * 1) + +/* + * TLS Server Key Files + * + */ +#define M2M_TLS_SERVER_FLASH_OFFSET (M2M_TLS_ROOTCER_FLASH_OFFSET + M2M_TLS_ROOTCER_FLASH_SIZE) +#define M2M_TLS_SERVER_FLASH_SIZE (FLASH_SECTOR_SZ * 2) + +/* + * HTTP Files + * + */ +#define M2M_HTTP_MEM_FLASH_OFFSET (M2M_TLS_SERVER_FLASH_OFFSET + M2M_TLS_SERVER_FLASH_SIZE) +#define M2M_HTTP_MEM_FLASH_SZ (FLASH_SECTOR_SZ * 2) + +/* + * Saved Connection Parameters: + * + */ +#define M2M_CACHED_CONNS_FLASH_OFFSET (M2M_HTTP_MEM_FLASH_OFFSET + M2M_HTTP_MEM_FLASH_SZ) +#define M2M_CACHED_CONNS_FLASH_SZ (FLASH_SECTOR_SZ * 1) + +/* + * + * Common section size + */ + +#define M2M_COMMON_DATA_SEC \ + (\ + M2M_BOOT_FIRMWARE_FLASH_SZ + \ + M2M_CONTROL_FLASH_TOTAL_SZ + \ + M2M_CONFIG_SECT_TOTAL_SZ + \ + M2M_TLS_ROOTCER_FLASH_SIZE + \ + M2M_TLS_SERVER_FLASH_SIZE + \ + M2M_HTTP_MEM_FLASH_SZ + \ + M2M_CACHED_CONNS_FLASH_SZ \ + ) + +/* + * + * OTA image1 Offset + */ + +#define M2M_OTA_IMAGE1_OFFSET (M2M_CACHED_CONNS_FLASH_OFFSET + M2M_CACHED_CONNS_FLASH_SZ) +/* + * Firmware Offset + * + */ +#if (defined _FIRMWARE_)||(defined OTA_GEN) +#define M2M_FIRMWARE_FLASH_OFFSET (0UL) +#else +#if (defined DOWNLOAD_ROLLBACK) +#define M2M_FIRMWARE_FLASH_OFFSET (M2M_OTA_IMAGE2_OFFSET) +#else +#define M2M_FIRMWARE_FLASH_OFFSET (M2M_OTA_IMAGE1_OFFSET) +#endif +#endif +/* + * + * Firmware + */ +#define M2M_FIRMWARE_FLASH_SZ (236 * 1024UL) +/** + * + * OTA image Size + */ +#define OTA_IMAGE_SIZE (M2M_FIRMWARE_FLASH_SZ) +/** + * + * Flash Total size + */ +#define FLASH_IMAGE1_CONTENT_SZ (M2M_COMMON_DATA_SEC + OTA_IMAGE_SIZE) + +/** + * + * OTA image 2 offset + */ +#define M2M_OTA_IMAGE2_OFFSET (FLASH_IMAGE1_CONTENT_SZ) + +/* + * App(Cortus App 4M): App. which runs over firmware + * + */ +#define M2M_APP_4M_MEM_FLASH_SZ (FLASH_SECTOR_SZ * 16) +#define M2M_APP_4M_MEM_FLASH_OFFSET (FLASH_4M_TOTAL_SZ - M2M_APP_4M_MEM_FLASH_SZ) +#define M2M_APP_8M_MEM_FLASH_OFFSET (M2M_OTA_IMAGE2_OFFSET + OTA_IMAGE_SIZE) +#define M2M_APP_8M_MEM_FLASH_SZ (FLASH_SECTOR_SZ * 32) +#define M2M_APP_OTA_MEM_FLASH_OFFSET (M2M_APP_8M_MEM_FLASH_OFFSET + M2M_APP_8M_MEM_FLASH_SZ) + +/* Check if total size of content + * don't exceed total size of memory allowed + **/ +#if (M2M_COMMON_DATA_SEC + (OTA_IMAGE_SIZE *2)> FLASH_4M_TOTAL_SZ) +#error "Excced 4M Flash Size" +#endif /* (FLASH_CONTENT_SZ > FLASH_TOTAL_SZ) */ + + +#endif /* __SPI_FLASH_MAP_H__ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/spi_flash/source/spi_flash.c b/feather_sensor_lte/libraries/WiFi101/src/spi_flash/source/spi_flash.c new file mode 100644 index 0000000..12eff59 --- /dev/null +++ b/feather_sensor_lte/libraries/WiFi101/src/spi_flash/source/spi_flash.c @@ -0,0 +1,770 @@ +/** + * + * \file + * + * \brief WINC1500 SPI Flash. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifdef PROFILING +#include "windows.h" +#endif +#include "spi_flash/include/spi_flash.h" +#define DUMMY_REGISTER (0x1084) + +#ifdef ARDUINO +#define u32(x) ((uint32)x) +#endif + +#define TIMEOUT (-1) /*MS*/ + +//#define DISABLE_UNSED_FLASH_FUNCTIONS + +#define FLASH_BLOCK_SIZE (32UL * 1024) +/*!> 16); + cmd[2] = (uint8)(u32FlashAdr >> 8); + cmd[3] = (uint8)(u32FlashAdr); + cmd[4] = 0xA5; + + ret += nm_write_reg(SPI_FLASH_DATA_CNT, u32Sz); +#ifdef ARDUINO + ret += nm_write_reg(SPI_FLASH_BUF1, u32(cmd[0])|u32(cmd[1]<<8)|u32(cmd[2]<<16)|u32(cmd[3]<<24)); +#else + ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]|(cmd[1]<<8)|(cmd[2]<<16)|(cmd[3]<<24)); +#endif + ret += nm_write_reg(SPI_FLASH_BUF2, cmd[4]); + ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x1f); + ret += nm_write_reg(SPI_FLASH_DMA_ADDR, u32MemAdr); + ret += nm_write_reg(SPI_FLASH_CMD_CNT, 5 | (1<<7)); + do + { + ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); + if(M2M_SUCCESS != ret) break; + } + while(val != 1); + + return ret; +} + +/** +* @fn spi_flash_sector_erase +* @brief Erase sector (4KB) +* @param[IN] u32FlashAdr +* Any memory address within the sector +* @return Status of execution +* @note Compatible with MX25L6465E and should be working with other types +* @author M. Abdelmawla +* @version 1.0 +*/ +static sint8 spi_flash_sector_erase(uint32 u32FlashAdr) +{ + uint8 cmd[4]; + uint32 val = 0; + sint8 ret = M2M_SUCCESS; + + cmd[0] = 0x20; + cmd[1] = (uint8)(u32FlashAdr >> 16); + cmd[2] = (uint8)(u32FlashAdr >> 8); + cmd[3] = (uint8)(u32FlashAdr); + + ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); +#ifdef ARDUINO + ret += nm_write_reg(SPI_FLASH_BUF1, u32(cmd[0])|u32(cmd[1]<<8)|u32(cmd[2]<<16)|u32(cmd[3]<<24)); +#else + ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]|(cmd[1]<<8)|(cmd[2]<<16)|(cmd[3]<<24)); +#endif + ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x0f); + ret += nm_write_reg(SPI_FLASH_DMA_ADDR, 0); + ret += nm_write_reg(SPI_FLASH_CMD_CNT, 4 | (1<<7)); + do + { + ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); + if(M2M_SUCCESS != ret) break; + } + while(val != 1); + + return ret; +} + +/** +* @fn spi_flash_write_enable +* @brief Send write enable command to SPI flash +* @return Status of execution +* @note Compatible with MX25L6465E and should be working with other types +* @author M. Abdelmawla +* @version 1.0 +*/ +static sint8 spi_flash_write_enable(void) +{ + uint8 cmd[1]; + uint32 val = 0; + sint8 ret = M2M_SUCCESS; + + cmd[0] = 0x06; + + ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); + ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]); + ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x01); + ret += nm_write_reg(SPI_FLASH_DMA_ADDR, 0); + ret += nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1<<7)); + do + { + ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); + if(M2M_SUCCESS != ret) break; + } + while(val != 1); + + return ret; +} + +/** +* @fn spi_flash_write_disable +* @brief Send write disable command to SPI flash +* @note Compatible with MX25L6465E and should be working with other types +* @author M. Abdelmawla +* @version 1.0 +*/ +static sint8 spi_flash_write_disable(void) +{ + uint8 cmd[1]; + uint32 val = 0; + sint8 ret = M2M_SUCCESS; + cmd[0] = 0x04; + + ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); + ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]); + ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x01); + ret += nm_write_reg(SPI_FLASH_DMA_ADDR, 0); + ret += nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1<<7)); + do + { + ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); + if(M2M_SUCCESS != ret) break; + } + while(val != 1); + + return ret; +} + +/** +* @fn spi_flash_page_program +* @brief Write data (less than page size) from cortus memory to SPI flash +* @param[IN] u32MemAdr +* Cortus data address. It must be set to its AHB access address +* @param[IN] u32FlashAdr +* Address to write to at the SPI flash +* @param[IN] u32Sz +* Data size +* @note Compatible with MX25L6465E and should be working with other types +* @author M. Abdelmawla +* @version 1.0 +*/ +static sint8 spi_flash_page_program(uint32 u32MemAdr, uint32 u32FlashAdr, uint32 u32Sz) +{ + uint8 cmd[4]; + uint32 val = 0; + sint8 ret = M2M_SUCCESS; + + cmd[0] = 0x02; + cmd[1] = (uint8)(u32FlashAdr >> 16); + cmd[2] = (uint8)(u32FlashAdr >> 8); + cmd[3] = (uint8)(u32FlashAdr); + + ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); +#ifdef ARDUINO + ret += nm_write_reg(SPI_FLASH_BUF1, u32(cmd[0])|u32(cmd[1]<<8)|u32(cmd[2]<<16)|u32(cmd[3]<<24)); +#else + ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]|(cmd[1]<<8)|(cmd[2]<<16)|(cmd[3]<<24)); +#endif + ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x0f); + ret += nm_write_reg(SPI_FLASH_DMA_ADDR, u32MemAdr); + ret += nm_write_reg(SPI_FLASH_CMD_CNT, 4 | (1<<7) | ((u32Sz & 0xfffff) << 8)); + do + { + ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); + if(M2M_SUCCESS != ret) break; + } + while(val != 1); + + return ret; +} + +/** +* @fn spi_flash_read_internal +* @brief Read from data from SPI flash +* @param[OUT] pu8Buf +* Pointer to data buffer +* @param[IN] u32Addr +* Address to read from at the SPI flash +* @param[IN] u32Sz +* Data size +* @note Data size must be < 64KB (limitation imposed by the bus wrapper) +* @author M. Abdelmawla +* @version 1.0 +*/ +static sint8 spi_flash_read_internal(uint8 *pu8Buf, uint32 u32Addr, uint32 u32Sz) +{ + sint8 ret = M2M_SUCCESS; + /* read size must be < 64KB */ + ret = spi_flash_load_to_cortus_mem(HOST_SHARE_MEM_BASE, u32Addr, u32Sz); + if(M2M_SUCCESS != ret) goto ERR; + ret = nm_read_block(HOST_SHARE_MEM_BASE, pu8Buf, u32Sz); +ERR: + return ret; +} + +/** +* @fn spi_flash_pp +* @brief Program data of size less than a page (256 bytes) at the SPI flash +* @param[IN] u32Offset +* Address to write to at the SPI flash +* @param[IN] pu8Buf +* Pointer to data buffer +* @param[IN] u32Sz +* Data size +* @return Status of execution +* @author M. Abdelmawla +* @version 1.0 +*/ +static sint8 spi_flash_pp(uint32 u32Offset, uint8 *pu8Buf, uint16 u16Sz) +{ + sint8 ret = M2M_SUCCESS; + uint8 tmp; + spi_flash_write_enable(); + /* use shared packet memory as temp mem */ + ret += nm_write_block(HOST_SHARE_MEM_BASE, pu8Buf, u16Sz); + ret += spi_flash_page_program(HOST_SHARE_MEM_BASE, u32Offset, u16Sz); + ret += spi_flash_read_status_reg(&tmp); + do + { + if(ret != M2M_SUCCESS) goto ERR; + ret += spi_flash_read_status_reg(&tmp); + }while(tmp & 0x01); + ret += spi_flash_write_disable(); +ERR: + return ret; +} + +/** +* @fn spi_flash_rdid +* @brief Read SPI Flash ID +* @return SPI FLash ID +* @author M.S.M +* @version 1.0 +*/ +static uint32 spi_flash_rdid(void) +{ + unsigned char cmd[1]; + uint32 reg = 0; + uint32 cnt = 0; + sint8 ret = M2M_SUCCESS; + + cmd[0] = 0x9f; + + ret += nm_write_reg(SPI_FLASH_DATA_CNT, 4); + ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]); + ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x1); + ret += nm_write_reg(SPI_FLASH_DMA_ADDR, DUMMY_REGISTER); + ret += nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1<<7)); + do + { + ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)®); + if(M2M_SUCCESS != ret) break; + if(++cnt > 500) + { + ret = M2M_ERR_INIT; + break; + } + } + while(reg != 1); + reg = (M2M_SUCCESS == ret)?(nm_read_reg(DUMMY_REGISTER)):(0); + M2M_PRINT("Flash ID %x \n",(unsigned int)reg); + return reg; +} + +/** +* @fn spi_flash_unlock +* @brief Unlock SPI Flash +* @author M.S.M +* @version 1.0 +*/ +#if 0 +static void spi_flash_unlock(void) +{ + uint8 tmp; + tmp = spi_flash_read_security_reg(); + spi_flash_clear_security_flags(); + if(tmp & 0x80) + { + spi_flash_write_enable(); + spi_flash_gang_unblock(); + } +} +#endif +static void spi_flash_enter_low_power_mode(void) { + volatile unsigned long tmp; + unsigned char* cmd = (unsigned char*) &tmp; + + cmd[0] = 0xb9; + + nm_write_reg(SPI_FLASH_DATA_CNT, 0); + nm_write_reg(SPI_FLASH_BUF1, cmd[0]); + nm_write_reg(SPI_FLASH_BUF_DIR, 0x1); + nm_write_reg(SPI_FLASH_DMA_ADDR, 0); + nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1 << 7)); + while(nm_read_reg(SPI_FLASH_TR_DONE) != 1); +} + + +static void spi_flash_leave_low_power_mode(void) { + volatile unsigned long tmp; + unsigned char* cmd = (unsigned char*) &tmp; + + cmd[0] = 0xab; + + nm_write_reg(SPI_FLASH_DATA_CNT, 0); + nm_write_reg(SPI_FLASH_BUF1, cmd[0]); + nm_write_reg(SPI_FLASH_BUF_DIR, 0x1); + nm_write_reg(SPI_FLASH_DMA_ADDR, 0); + nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1 << 7)); + while(nm_read_reg(SPI_FLASH_TR_DONE) != 1); +} +/*********************************************/ +/* GLOBAL FUNCTIONS */ +/*********************************************/ +/** + * @fn spi_flash_enable + * @brief Enable spi flash operations + * @author M. Abdelmawla + * @version 1.0 + */ +sint8 spi_flash_enable(uint8 enable) +{ + sint8 s8Ret = M2M_SUCCESS; + if(REV(nmi_get_chipid()) >= REV_3A0) { + uint32 u32Val; + + /* Enable pinmux to SPI flash. */ + s8Ret = nm_read_reg_with_ret(0x1410, &u32Val); + if(s8Ret != M2M_SUCCESS) { + goto ERR1; + } + /* GPIO15/16/17/18 */ + u32Val &= ~((0x7777ul) << 12); + u32Val |= ((0x1111ul) << 12); + nm_write_reg(0x1410, u32Val); + if(enable) { + spi_flash_leave_low_power_mode(); + } else { + spi_flash_enter_low_power_mode(); + } + /* Disable pinmux to SPI flash to minimize leakage. */ + u32Val &= ~((0x7777ul) << 12); + u32Val |= ((0x0010ul) << 12); + nm_write_reg(0x1410, u32Val); + } +ERR1: + return s8Ret; +} +/** +* @fn spi_flash_read +* @brief Read from data from SPI flash +* @param[OUT] pu8Buf +* Pointer to data buffer +* @param[IN] u32offset +* Address to read from at the SPI flash +* @param[IN] u32Sz +* Data size +* @return Status of execution +* @note Data size is limited by the SPI flash size only +* @author M. Abdelmawla +* @version 1.0 +*/ +sint8 spi_flash_read(uint8 *pu8Buf, uint32 u32offset, uint32 u32Sz) +{ + sint8 ret = M2M_SUCCESS; + if(u32Sz > FLASH_BLOCK_SIZE) + { + do + { + ret = spi_flash_read_internal(pu8Buf, u32offset, FLASH_BLOCK_SIZE); + if(M2M_SUCCESS != ret) goto ERR; + u32Sz -= FLASH_BLOCK_SIZE; + u32offset += FLASH_BLOCK_SIZE; + pu8Buf += FLASH_BLOCK_SIZE; + } while(u32Sz > FLASH_BLOCK_SIZE); + } + + ret = spi_flash_read_internal(pu8Buf, u32offset, u32Sz); + +ERR: + return ret; +} + +/** +* @fn spi_flash_write +* @brief Proram SPI flash +* @param[IN] pu8Buf +* Pointer to data buffer +* @param[IN] u32Offset +* Address to write to at the SPI flash +* @param[IN] u32Sz +* Data size +* @return Status of execution +* @author M. Abdelmawla +* @version 1.0 +*/ +sint8 spi_flash_write(uint8* pu8Buf, uint32 u32Offset, uint32 u32Sz) +{ +#ifdef PROFILING + uint32 t1 = 0; + uint32 percent =0; + uint32 tpercent =0; +#endif + sint8 ret = M2M_SUCCESS; + uint32 u32wsz; + uint32 u32off; + uint32 u32Blksz; + u32Blksz = FLASH_PAGE_SZ; + u32off = u32Offset % u32Blksz; +#ifdef PROFILING + tpercent = (u32Sz/u32Blksz)+((u32Sz%u32Blksz)>0); + t1 = GetTickCount(); + M2M_PRINT(">Start programming...\r\n"); +#endif + if(u32Sz<=0) + { + M2M_ERR("Data size = %d",(int)u32Sz); + ret = M2M_ERR_FAIL; + goto ERR; + } + + if (u32off)/*first part of data in the address page*/ + { + u32wsz = u32Blksz - u32off; + if(spi_flash_pp(u32Offset, pu8Buf, (uint16)BSP_MIN(u32Sz, u32wsz))!=M2M_SUCCESS) + { + ret = M2M_ERR_FAIL; + goto ERR; + } + if (u32Sz < u32wsz) goto EXIT; + pu8Buf += u32wsz; + u32Offset += u32wsz; + u32Sz -= u32wsz; + } + while (u32Sz > 0) + { + u32wsz = BSP_MIN(u32Sz, u32Blksz); + + /*write complete page or the remaining data*/ + if(spi_flash_pp(u32Offset, pu8Buf, (uint16)u32wsz)!=M2M_SUCCESS) + { + ret = M2M_ERR_FAIL; + goto ERR; + } + pu8Buf += u32wsz; + u32Offset += u32wsz; + u32Sz -= u32wsz; +#ifdef PROFILING + percent++; + printf("\r>Complete Percentage = %d%%.\r",((percent*100)/tpercent)); +#endif + } +EXIT: +#ifdef PROFILING + M2M_PRINT("\rDone\t\t\t\t\t\t"); + M2M_PRINT("\n#Programming time = %f sec\n\r",(GetTickCount() - t1)/1000.0); +#endif +ERR: + return ret; +} + +/** +* @fn spi_flash_erase +* @brief Erase from data from SPI flash +* @param[IN] u32Offset +* Address to write to at the SPI flash +* @param[IN] u32Sz +* Data size +* @return Status of execution +* @note Data size is limited by the SPI flash size only +* @author M. Abdelmawla +* @version 1.0 +*/ +sint8 spi_flash_erase(uint32 u32Offset, uint32 u32Sz) +{ + uint32 i = 0; + sint8 ret = M2M_SUCCESS; + uint8 tmp = 0; +#ifdef PROFILING + uint32 t; + t = GetTickCount(); +#endif + M2M_PRINT("\r\n>Start erasing...\r\n"); + for(i = u32Offset; i < (u32Sz +u32Offset); i += (16*FLASH_PAGE_SZ)) + { + ret += spi_flash_write_enable(); + ret += spi_flash_read_status_reg(&tmp); + ret += spi_flash_sector_erase(i + 10); + ret += spi_flash_read_status_reg(&tmp); + do + { + if(ret != M2M_SUCCESS) goto ERR; + ret += spi_flash_read_status_reg(&tmp); + }while(tmp & 0x01); + + } + M2M_PRINT("Done\r\n"); +#ifdef PROFILING + M2M_PRINT("#Erase time = %f sec\n", (GetTickCount()-t)/1000.0); +#endif +ERR: + return ret; +} + +/** +* @fn spi_flash_get_size +* @brief Get size of SPI Flash +* @return Size of Flash +* @author M.S.M +* @version 1.0 +*/ +uint32 spi_flash_get_size(void) +{ + uint32 u32FlashId = 0, u32FlashPwr = 0; + static uint32 gu32InernalFlashSize= 0; + + if(!gu32InernalFlashSize) + { + u32FlashId = spi_flash_rdid();//spi_flash_probe(); + if(u32FlashId != 0xffffffff) + { + /*flash size is the third byte from the FLASH RDID*/ + u32FlashPwr = ((u32FlashId>>16)&0xff) - 0x11; /*2MBIT is the min*/ + /*That number power 2 to get the flash size*/ + gu32InernalFlashSize = 1< + +// First, we're going to make some variables. +// This is our "shorthand" that we'll use throughout the program: + +int led1 = D0; // Instead of writing D0 over and over again, we'll write led1 +// You'll need to wire an LED to this one to see it blink. + +int led2 = D7; // Instead of writing D7 over and over again, we'll write led2 +// This one is the little blue LED on your board. On the Photon it is next to D7, and on the Core it is next to the USB jack. + +// Having declared these variables, let's move on to the setup function. +// The setup function is a standard part of any microcontroller program. +// It runs only once when the device boots up or is reset. + +void setup() { + + // We are going to tell our device that D0 and D7 (which we named led1 and led2 respectively) are going to be output + // (That means that we will be sending voltage to them, rather than monitoring voltage that comes from them) + + // It's important you do this here, inside the setup() function rather than outside it or in the loop function. + + pinMode(led1, OUTPUT); + pinMode(led2, OUTPUT); + +} + +// Next we have the loop function, the other essential part of a microcontroller program. +// This routine gets repeated over and over, as quickly as possible and as many times as possible, after the setup function is called. +// Note: Code that blocks for too long (like more than 5 seconds), can make weird things happen (like dropping the network connection). The built-in delay function shown below safely interleaves required background activity, so arbitrarily long delays can safely be done if you need them. + +void loop() { + // To blink the LED, first we'll turn it on... + digitalWrite(led1, HIGH); + digitalWrite(led2, HIGH); + + // We'll leave it on for 1 second... + delay(1000); + + // Then we'll turn it off... + digitalWrite(led1, LOW); + digitalWrite(led2, LOW); + + // Wait 1 second... + delay(1000); + + // And repeat! +} + diff --git a/transmit.cpp b/transmit.cpp index 5990b49..3fdd5f5 100644 --- a/transmit.cpp +++ b/transmit.cpp @@ -3,6 +3,11 @@ #include "watchdog.h" #include +#ifdef HEATSEEK_BORON_LTE + TCPClient tcpClient; + Bool lteConnected = false; +#endif + #ifdef HEATSEEK_FEATHER_WIFI_WICED AdafruitHTTP http; bool wifiConnected = false; @@ -290,6 +295,42 @@ } #endif +#ifdef HEATSEEK_BORON_LTE + // Function to reconnect to LTE? + void force_lte_reconnect(void); + + // Function to connect to Particle Cloud + void connect_to_lte(){ + // Configure the connection here. + Serial.println(“Establishing connection...”); + // Connect to LTE network here. + Serial.println(“Connected to LTE”); + watchdog_feed(); + } + + // Function to transmit + bool _transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time){ + // If cell / API endpoint not configured, indicate error + if (!CONFIG.data.cell_configured || !CONFIG.data.endpoint_configured) { + Serial.println("cannot send data - not configured"); + return false; + } + + // If not connected, connect + if(!lteConnected){ + connect_to_lte(); + } + + // Set up TCPClient + // Do some error checking + client.connect(CONFIG.data.endpoint_domain, 80); + // Load contenttype + // Load data + // Post data via TCPClient + // Done. +} +#endif + typedef struct { float temperature_f; float humidity; diff --git a/user_config.h b/user_config.h index 57fbb6a..6011268 100644 --- a/user_config.h +++ b/user_config.h @@ -1,3 +1,4 @@ //#define HEATSEEK_FEATHER_CELL_M0 -#define HEATSEEK_FEATHER_WIFI_M0 +//#define HEATSEEK_FEATHER_WIFI_M0 +#define HEATSEEK_BORON_LTE //#define HEATSEEK_FEATHER_WIFI_WICED From c7e9e5004def435c92b9c9d3af710d15ca02d973 Mon Sep 17 00:00:00 2001 From: ShrutiVerma17 Date: Fri, 6 Dec 2019 12:56:29 -0500 Subject: [PATCH 6/7] Transmit Code Added, Not compiling --- boron | 1 + feather_sensor_lte/.vscode/settings.json | 2 +- .../boron_firmware_1574729317031.bin | Bin 0 -> 5592 bytes feather_sensor_lte/src/feather_sensor_lte.ino | 1 + .../.vscode/c_cpp_properties.json | 18 + feather_sensor_transmit/.vscode/launch.json | 92 + feather_sensor_transmit/.vscode/settings.json | 11 + .../boron_firmware_1574447345899.bin | Bin 0 -> 5592 bytes .../boron_firmware_1574729317031.bin | Bin 0 -> 5592 bytes .../Adafruit_ASFcore/Adafruit_ASFcore.h | 0 .../libraries/Adafruit_ASFcore/README.md | 33 + .../libraries/Adafruit_ASFcore/clock.h | 53 + .../Adafruit_ASFcore/clock_feature.h | 1492 +++++++++ .../libraries/Adafruit_ASFcore/compiler.h | 1157 +++++++ .../libraries/Adafruit_ASFcore/gclk.c | 522 +++ .../libraries/Adafruit_ASFcore/gclk.h | 307 ++ .../libraries/Adafruit_ASFcore/i2s.c | 750 +++++ .../libraries/Adafruit_ASFcore/i2s.h | 1404 ++++++++ .../libraries/Adafruit_ASFcore/interrupt.h | 117 + .../interrupt/interrupt_sam_nvic.c | 69 + .../interrupt/interrupt_sam_nvic.h | 172 + .../Adafruit_ASFcore/interrupt_sam_nvic.c | 86 + .../Adafruit_ASFcore/interrupt_sam_nvic.h | 189 ++ .../Adafruit_ASFcore/library.properties | 9 + .../libraries/Adafruit_ASFcore/parts.h | 1601 +++++++++ .../libraries/Adafruit_ASFcore/pinmux.c | 311 ++ .../libraries/Adafruit_ASFcore/pinmux.h | 678 ++++ .../libraries/Adafruit_ASFcore/power.h | 224 ++ .../preprocessor/mrecursion.h | 581 ++++ .../Adafruit_ASFcore/preprocessor/mrepeat.h | 321 ++ .../preprocessor/preprocessor.h | 38 + .../Adafruit_ASFcore/preprocessor/stringz.h | 67 + .../Adafruit_ASFcore/preprocessor/tpaste.h | 85 + .../libraries/Adafruit_ASFcore/reset.h | 119 + .../libraries/Adafruit_ASFcore/status_codes.h | 138 + .../libraries/Adafruit_ASFcore/system.c | 111 + .../libraries/Adafruit_ASFcore/system.h | 726 +++++ .../Adafruit_ASFcore/system_interrupt.h | 429 +++ .../system_interrupt_features.h | 195 ++ .../libraries/Adafruit_ASFcore/tc.c | 685 ++++ .../libraries/Adafruit_ASFcore/tc.h | 1783 ++++++++++ .../libraries/Adafruit_ASFcore/tc_interrupt.c | 199 ++ .../libraries/Adafruit_ASFcore/tc_interrupt.h | 179 + .../libraries/Adafruit_ASFcore/wdt.c | 264 ++ .../libraries/Adafruit_ASFcore/wdt.h | 501 +++ .../Adafruit_FONA_Library/Adafruit_FONA.cpp | 2079 ++++++++++++ .../Adafruit_FONA_Library/Adafruit_FONA.h | 263 ++ .../libraries/Adafruit_FONA_Library/README.md | 29 + .../FONA3G_setbaud/.esp8266.test.skip | 0 .../FONA3G_setbaud/FONA3G_setbaud.ino | 77 + .../FONA_SMS_Response/.esp8266.test.skip | 0 .../FONA_SMS_Response/FONA_SMS_Response.ino | 131 + .../examples/FONAtest/.esp8266.test.skip | 0 .../examples/FONAtest/FONAtest.ino | 886 +++++ .../examples/GPS/.esp8266.test.skip | 0 .../examples/GPS/GPS.ino | 112 + .../examples/IncomingCall/.esp8266.test.skip | 0 .../examples/IncomingCall/IncomingCall.ino | 62 + .../includes/FONAConfig.h | 34 + .../includes/FONAExtIncludes.h | 33 + .../includes/platform/FONAPlatStd.h | 67 + .../includes/platform/FONAPlatform.h | 62 + .../Adafruit_FONA_Library/library.properties | 9 + .../Adafruit_SleepyDog.cpp | 4 + .../Adafruit_SleepyDog.h | 28 + .../Adafruit_SleepyDog_Library/LICENSE | 22 + .../Adafruit_SleepyDog_Library/README.md | 6 + .../examples/BasicUsage/BasicUsage.ino | 62 + .../examples/Sleep/Sleep.ino | 37 + .../library.properties | 9 + .../utility/WatchdogAVR.cpp | 137 + .../utility/WatchdogAVR.h | 47 + .../utility/WatchdogKinetisK.cpp | 104 + .../utility/WatchdogKinetisK.h | 38 + .../utility/WatchdogKinetisL.cpp | 74 + .../utility/WatchdogKinetisL.h | 35 + .../utility/WatchdogSAMD.cpp | 175 + .../utility/WatchdogSAMD.h | 43 + .../libraries/ArduinoHttpClient/.gitignore | 2 + .../libraries/ArduinoHttpClient/CHANGELOG.md | 25 + .../libraries/ArduinoHttpClient/README.md | 22 + .../examples/BasicAuthGet/BasicAuthGet.ino | 69 + .../examples/BasicAuthGet/arduino_secrets.h | 3 + .../examples/CustomHeader/CustomHeader.ino | 96 + .../examples/CustomHeader/arduino_secrets.h | 3 + .../examples/DweetGet/DweetGet.ino | 107 + .../examples/DweetGet/arduino_secrets.h | 3 + .../examples/DweetPost/DweetPost.ino | 87 + .../examples/DweetPost/arduino_secrets.h | 3 + .../examples/HueBlink/HueBlink.ino | 102 + .../examples/HueBlink/arduino_secrets.h | 3 + .../PostWithHeaders/PostWithHeaders.ino | 79 + .../PostWithHeaders/arduino_secrets.h | 3 + .../examples/SimpleDelete/SimpleDelete.ino | 71 + .../examples/SimpleDelete/arduino_secrets.h | 3 + .../examples/SimpleGet/SimpleGet.ino | 66 + .../examples/SimpleGet/arduino_secrets.h | 3 + .../SimpleHttpExample/SimpleHttpExample.ino | 133 + .../SimpleHttpExample/arduino_secrets.h | 3 + .../examples/SimplePost/SimplePost.ino | 70 + .../examples/SimplePost/arduino_secrets.h | 3 + .../examples/SimplePut/SimplePut.ino | 70 + .../examples/SimplePut/arduino_secrets.h | 3 + .../SimpleWebSocket/SimpleWebSocket.ino | 80 + .../SimpleWebSocket/arduino_secrets.h | 3 + .../node_test_server/getPostPutDelete.js | 102 + .../examples/node_test_server/package.json | 13 + .../libraries/ArduinoHttpClient/keywords.txt | 64 + .../libraries/ArduinoHttpClient/library.json | 12 + .../ArduinoHttpClient/library.properties | 10 + .../ArduinoHttpClient/src/ArduinoHttpClient.h | 11 + .../ArduinoHttpClient/src/HttpClient.cpp | 862 +++++ .../ArduinoHttpClient/src/HttpClient.h | 392 +++ .../ArduinoHttpClient/src/WebSocketClient.cpp | 372 +++ .../ArduinoHttpClient/src/WebSocketClient.h | 99 + .../libraries/ArduinoHttpClient/src/b64.cpp | 72 + .../libraries/ArduinoHttpClient/src/b64.h | 6 + .../libraries/DHT/.github/ISSUE_TEMPLATE.md | 46 + .../DHT/.github/PULL_REQUEST_TEMPLATE.md | 26 + feather_sensor_transmit/libraries/DHT/DHT.cpp | 259 ++ feather_sensor_transmit/libraries/DHT/DHT.h | 75 + .../libraries/DHT/DHT_U.cpp | 179 + feather_sensor_transmit/libraries/DHT/DHT_U.h | 78 + .../libraries/DHT/README.md | 15 + .../DHT_Unified_Sensor/DHT_Unified_Sensor.ino | 84 + .../DHT/examples/DHTtester/DHTtester.ino | 69 + .../libraries/DHT/keywords.txt | 22 + .../libraries/DHT/library.properties | 9 + .../RTClib/.github/ISSUE_TEMPLATE.md | 46 + .../RTClib/.github/PULL_REQUEST_TEMPLATE.md | 26 + .../libraries/RTClib/README.md | 42 + .../libraries/RTClib/RTClib.cpp | 506 +++ .../libraries/RTClib/RTClib.h | 135 + .../RTClib/examples/datecalc/datecalc.ino | 111 + .../RTClib/examples/ds1307/ds1307.ino | 71 + .../examples/ds1307SqwPin/ds1307SqwPin.ino | 68 + .../examples/ds1307nvram/ds1307nvram.ino | 63 + .../RTClib/examples/ds3231/ds3231.ino | 77 + .../RTClib/examples/pcf8523/pcf8523.ino | 74 + .../RTClib/examples/softrtc/softrtc.ino | 61 + .../libraries/RTClib/keywords.txt | 37 + .../libraries/RTClib/library.properties | 9 + .../libraries/WiFi101/.travis.yml | 48 + .../libraries/WiFi101/CHANGELOG | 122 + .../libraries/WiFi101/README.adoc | 27 + .../AP_SimpleWebServer/AP_SimpleWebServer.ino | 176 + .../AP_SimpleWebServer/arduino_secrets.h | 3 + .../CheckWifi101FirmwareVersion.ino | 67 + .../ConnectNoEncryption.ino | 123 + .../ConnectNoEncryption/arduino_secrets.h | 1 + .../ConnectWithWEP/ConnectWithWEP.ino | 129 + .../examples/ConnectWithWEP/arduino_secrets.h | 3 + .../ConnectWithWPA/ConnectWithWPA.ino | 119 + .../examples/ConnectWithWPA/arduino_secrets.h | 3 + .../examples/FirmwareUpdater/Endianess.ino | 62 + .../FirmwareUpdater/FirmwareUpdater.ino | 129 + .../MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino | 170 + .../MDNS_WiFiWebServer/arduino_secrets.h | 3 + .../Provisioning_WiFiWebServer.ino | 167 + .../examples/ScanNetworks/ScanNetworks.ino | 120 + .../ScanNetworksAdvanced.ino | 149 + .../SimpleWebServerWiFi.ino | 131 + .../SimpleWebServerWiFi/arduino_secrets.h | 3 + .../WiFiChatServer/WiFiChatServer.ino | 114 + .../examples/WiFiChatServer/arduino_secrets.h | 3 + .../WiFi101/examples/WiFiPing/WiFiPing.ino | 140 + .../examples/WiFiPing/arduino_secrets.h | 3 + .../examples/WiFiSSLClient/WiFiSSLClient.ino | 107 + .../examples/WiFiSSLClient/arduino_secrets.h | 3 + .../WiFiUdpNtpClient/WiFiUdpNtpClient.ino | 182 ++ .../WiFiUdpNtpClient/arduino_secrets.h | 3 + .../WiFiUdpSendReceiveString.ino | 113 + .../arduino_secrets.h | 3 + .../examples/WiFiWebClient/WiFiWebClient.ino | 121 + .../examples/WiFiWebClient/arduino_secrets.h | 3 + .../WiFiWebClientRepeating.ino | 127 + .../WiFiWebClientRepeating/arduino_secrets.h | 3 + .../examples/WiFiWebServer/WiFiWebServer.ino | 135 + .../examples/WiFiWebServer/arduino_secrets.h | 3 + .../libraries/WiFi101/keywords.txt | 61 + .../libraries/WiFi101/library.properties | 10 + .../libraries/WiFi101/src/WiFi.cpp | 1106 +++++++ .../libraries/WiFi101/src/WiFi101.h | 193 ++ .../libraries/WiFi101/src/WiFiClient.cpp | 308 ++ .../libraries/WiFi101/src/WiFiClient.h | 68 + .../WiFi101/src/WiFiMDNSResponder.cpp | 220 ++ .../libraries/WiFi101/src/WiFiMDNSResponder.h | 51 + .../libraries/WiFi101/src/WiFiSSLClient.cpp | 45 + .../libraries/WiFi101/src/WiFiSSLClient.h | 36 + .../libraries/WiFi101/src/WiFiServer.cpp | 140 + .../libraries/WiFi101/src/WiFiServer.h | 49 + .../libraries/WiFi101/src/WiFiUdp.cpp | 289 ++ .../libraries/WiFi101/src/WiFiUdp.h | 89 + .../WiFi101/src/bsp/include/nm_bsp.h | 283 ++ .../WiFi101/src/bsp/include/nm_bsp_arduino.h | 74 + .../WiFi101/src/bsp/include/nm_bsp_avr.h | 54 + .../WiFi101/src/bsp/include/nm_bsp_internal.h | 59 + .../WiFi101/src/bsp/include/nm_bsp_samd21.h | 52 + .../WiFi101/src/bsp/source/nm_bsp_arduino.c | 205 ++ .../src/bsp/source/nm_bsp_arduino_avr.c | 164 + .../src/bus_wrapper/include/nm_bus_wrapper.h | 177 + .../source/nm_bus_wrapper_samd21.cpp | 200 ++ .../WiFi101/src/common/include/nm_common.h | 153 + .../WiFi101/src/common/include/nm_debug.h | 95 + .../WiFi101/src/common/source/nm_common.c | 136 + .../WiFi101/src/driver/include/ecc_types.h | 245 ++ .../WiFi101/src/driver/include/m2m_ate_mode.h | 732 +++++ .../WiFi101/src/driver/include/m2m_crypto.h | 272 ++ .../WiFi101/src/driver/include/m2m_ota.h | 428 +++ .../WiFi101/src/driver/include/m2m_periph.h | 411 +++ .../WiFi101/src/driver/include/m2m_ssl.h | 182 ++ .../WiFi101/src/driver/include/m2m_types.h | 2383 ++++++++++++++ .../WiFi101/src/driver/include/m2m_wifi.h | 2882 +++++++++++++++++ .../WiFi101/src/driver/source/m2m_ate_mode.c | 826 +++++ .../WiFi101/src/driver/source/m2m_crypto.c | 1010 ++++++ .../WiFi101/src/driver/source/m2m_hif.c | 767 +++++ .../WiFi101/src/driver/source/m2m_hif.h | 249 ++ .../WiFi101/src/driver/source/m2m_ota.c | 417 +++ .../WiFi101/src/driver/source/m2m_periph.c | 187 ++ .../WiFi101/src/driver/source/m2m_ssl.c | 309 ++ .../WiFi101/src/driver/source/m2m_wifi.c | 1522 +++++++++ .../WiFi101/src/driver/source/nmasic.c | 688 ++++ .../WiFi101/src/driver/source/nmasic.h | 215 ++ .../WiFi101/src/driver/source/nmbus.c | 301 ++ .../WiFi101/src/driver/source/nmbus.h | 147 + .../WiFi101/src/driver/source/nmdrv.c | 402 +++ .../WiFi101/src/driver/source/nmdrv.h | 138 + .../WiFi101/src/driver/source/nmi2c.c | 269 ++ .../WiFi101/src/driver/source/nmi2c.h | 104 + .../WiFi101/src/driver/source/nmspi.c | 1401 ++++++++ .../WiFi101/src/driver/source/nmspi.h | 132 + .../WiFi101/src/driver/source/nmuart.c | 536 +++ .../WiFi101/src/driver/source/nmuart.h | 118 + .../src/socket/include/m2m_socket_host_if.h | 461 +++ .../WiFi101/src/socket/include/socket.h | 2065 ++++++++++++ .../src/socket/include/socket_buffer.h | 94 + .../WiFi101/src/socket/source/socket.c | 1445 +++++++++ .../WiFi101/src/socket/source/socket_buffer.c | 232 ++ .../src/socket/source/socket_internal.h | 71 + .../WiFi101/src/spi_flash/include/spi_flash.h | 233 ++ .../src/spi_flash/include/spi_flash_map.h | 245 ++ .../WiFi101/src/spi_flash/source/spi_flash.c | 770 +++++ feather_sensor_transmit/project.properties | 1 + feather_sensor_transmit/src/LICENSE.txt | 22 + feather_sensor_transmit/src/README.md | 67 + feather_sensor_transmit/src/config.cpp | 453 +++ feather_sensor_transmit/src/config.h | 39 + .../src/heatseek_sensor.ino | 166 + feather_sensor_transmit/src/rtc.cpp | 58 + feather_sensor_transmit/src/rtc.h | 11 + feather_sensor_transmit/src/transmit.cpp | 513 +++ feather_sensor_transmit/src/transmit.h | 58 + feather_sensor_transmit/src/user_config.h | 4 + feather_sensor_transmit/src/watchdog.cpp | 25 + feather_sensor_transmit/src/watchdog.h | 9 + .../.vscode/c_cpp_properties.json | 18 + .../.vscode/launch.json | 92 + .../.vscode/settings.json | 11 + .../feather_sensor_transmit_lte/README.md | 35 + .../boron_firmware_1574447345899.bin | Bin 0 -> 5592 bytes .../boron_firmware_1574729317031.bin | Bin 0 -> 5592 bytes .../lib/DHT/LICENSE.txt | 0 .../lib/DHT/README.md | 15 + .../DHT_Unified_Sensor/DHT_Unified_Sensor.ino | 84 + .../lib/DHT/examples/DHTtester/DHTtester.ino | 69 + .../lib/DHT/keywords.txt | 22 + .../lib/DHT/library.properties | 9 + .../lib/DHT/src/DHT.cpp | 259 ++ .../lib/DHT/src/DHT.h | 75 + .../lib/DHT/src/DHT_U.cpp | 179 + .../lib/DHT/src/DHT_U.h | 78 + .../lib/SdFat/LICENSE.md | 21 + .../lib/SdFat/README.md | 42 + .../#attic/AnalogLogger/AnalogLogger.ino | 197 ++ .../BaseExtCaseTest/BaseExtCaseTest.ino | 46 + .../examples/#attic/HelloWorld/HelloWorld.ino | 20 + .../examples/#attic/MiniSerial/MiniSerial.ino | 29 + .../PrintBenchmarkSD/PrintBenchmarkSD.ino | 125 + .../SdFat/examples/#attic/SD_Size/SD_Size.ino | 30 + .../examples/#attic/SdFatSize/SdFatSize.ino | 33 + .../#attic/StreamParseInt/StreamParseInt.ino | 44 + .../SdFat/examples/#attic/append/append.ino | 77 + .../SdFat/examples/#attic/average/average.ino | 82 + .../SdFat/examples/#attic/benchSD/benchSD.ino | 149 + .../examples/#attic/bufstream/bufstream.ino | 39 + .../examples/#attic/cin_cout/cin_cout.ino | 39 + .../examples/#attic/eventlog/eventlog.ino | 62 + .../#attic/fgetsRewrite/fgetsRewrite.ino | 111 + .../SdFat/examples/#attic/readlog/readlog.ino | 51 + .../lib/SdFat/examples/#attic/readme.txt | 34 + .../AnalogBinLogger/AnalogBinLogger.h | 39 + .../AnalogBinLogger/AnalogBinLogger.ino | 826 +++++ .../DirectoryFunctions/DirectoryFunctions.ino | 129 + .../examples/LongFileName/LongFileName.ino | 102 + .../A long name can be 255 characters.txt | 4 + .../LongFileName/testFiles/LFN,NAME.TXT | 1 + .../LongFileName/testFiles/MIXCASE.txt | 5 + .../LongFileName/testFiles/Not_8_3.txt | 2 + .../examples/LongFileName/testFiles/OK%83.TXT | 1 + .../LongFileName/testFiles/STD_8_3.TXT | 1 + .../LongFileName/testFiles/With Blank.txt | 2 + .../LongFileName/testFiles/With.Two dots.txt | 2 + .../examples/LongFileName/testFiles/lower.txt | 5 + .../examples/LongFileName/testFiles/mixed.TXT | 5 + .../LowLatencyLogger/LowLatencyLogger.ino | 655 ++++ .../LowLatencyLogger/UserFunctions.cpp | 41 + .../examples/LowLatencyLogger/UserTypes.h | 15 + .../LowLatencyLogger.ino | 655 ++++ .../LowLatencyLoggerADXL345.ino | 1 + .../LowLatencyLoggerADXL345/UserFunctions.cpp | 70 + .../LowLatencyLoggerADXL345/UserTypes.h | 17 + .../LowLatencyLoggerADXL345/readme.txt | 1 + .../LowLatencyLogger.ino | 655 ++++ .../LowLatencyLoggerMPU6050.ino | 2 + .../LowLatencyLoggerMPU6050/UserFunctions.cpp | 51 + .../LowLatencyLoggerMPU6050/UserTypes.h | 18 + .../lib/SdFat/examples/OpenNext/OpenNext.ino | 60 + .../PrintBenchmark/PrintBenchmark.ino | 152 + .../SdFat/examples/QuickStart/QuickStart.ino | 161 + .../lib/SdFat/examples/RawWrite/RawWrite.ino | 180 + .../lib/SdFat/examples/ReadCsv/ReadCsv.ino | 212 ++ .../examples/ReadCsvArray/ReadCsvArray.ino | 139 + .../examples/ReadCsvStream/ReadCsvStream.ino | 121 + .../SdFat/examples/ReadWrite/ReadWrite.ino | 81 + .../SdFat/examples/STM32Test/STM32Test.ino | 175 + .../examples/SdFormatter/SdFormatter.ino | 552 ++++ .../lib/SdFat/examples/SdInfo/SdInfo.ino | 248 ++ .../examples/SoftwareSpi/SoftwareSpi.ino | 58 + .../SdFat/examples/StdioBench/StdioBench.ino | 214 ++ .../TeensySdioDemo/TeensySdioDemo.ino | 169 + .../SdFat/examples/Timestamp/Timestamp.ino | 176 + .../lib/SdFat/examples/TwoCards/TwoCards.ino | 170 + .../VolumeFreeSpace/VolumeFreeSpace.ino | 82 + .../lib/SdFat/examples/bench/bench.ino | 222 ++ .../SdFat/examples/dataLogger/dataLogger.ino | 150 + .../lib/SdFat/examples/fgets/fgets.ino | 88 + .../SdFat/examples/formatting/formatting.ino | 73 + .../lib/SdFat/examples/getline/getline.ino | 84 + .../lib/SdFat/examples/rename/rename.ino | 107 + .../lib/SdFat/examples/wipe/wipe.ino | 42 + .../AnalogBinLoggerExtras/AdcErrorStudy.txt | 98 + .../AnalogBinLoggerExtras/RateTable.txt | 21 + .../bintocsv/AnalogBinLogger.h | 39 + .../bintocsv/bintocsv.cpp | 82 + .../extras/AnalogBinLoggerExtras/readme.txt | 95 + .../lib/SdFat/extras/MainPage/SdFatmainpage.h | 403 +++ .../extras/SdFatTestSuite/SdFatTestSuite.cpp | 87 + .../extras/SdFatTestSuite/SdFatTestSuite.h | 50 + .../examples/ATS_SD_File/ATS_SD_File.ino | 105 + .../examples/ATS_SD_Files/ATS_SD_Files.ino | 75 + .../examples/ATS_SD_Seek/ATS_SD_Seek.ino | 108 + .../examples/StressTest/StressTest.ino | 76 + .../examples/TestMkdir/TestMkdir.ino | 138 + .../examples/TestRmdir/TestRmdir.ino | 98 + .../examples/fstreamTest/fstreamTest.ino | 94 + .../examples/istreamTest/istreamTest.ino | 261 ++ .../examples/lfnSize/lfnSize.ino | 36 + .../examples/lfnTest/lfnTest.ino | 234 ++ .../examples/lfnTestCout/lfnTestCout.ino | 218 ++ .../examples/ostreamTest/ostreamTest.ino | 172 + .../lib/SdFat/extras/changes.txt | 569 ++++ .../lib/SdFat/extras/cpplint.txt | 1 + .../lib/SdFat/library.properties | 11 + .../lib/SdFat/src/BlockDriver.h | 40 + .../lib/SdFat/src/FatLib/ArduinoFiles.h | 249 ++ .../lib/SdFat/src/FatLib/ArduinoStream.h | 153 + .../lib/SdFat/src/FatLib/BaseBlockDriver.h | 80 + .../lib/SdFat/src/FatLib/FatApiConstants.h | 87 + .../lib/SdFat/src/FatLib/FatFile.cpp | 1530 +++++++++ .../lib/SdFat/src/FatLib/FatFile.h | 1029 ++++++ .../lib/SdFat/src/FatLib/FatFileLFN.cpp | 688 ++++ .../lib/SdFat/src/FatLib/FatFilePrint.cpp | 267 ++ .../lib/SdFat/src/FatLib/FatFileSFN.cpp | 278 ++ .../lib/SdFat/src/FatLib/FatFileSystem.h | 332 ++ .../lib/SdFat/src/FatLib/FatLib.h | 36 + .../lib/SdFat/src/FatLib/FatLibConfig.h | 146 + .../lib/SdFat/src/FatLib/FatStructs.h | 882 +++++ .../lib/SdFat/src/FatLib/FatVolume.cpp | 614 ++++ .../lib/SdFat/src/FatLib/FatVolume.h | 375 +++ .../lib/SdFat/src/FatLib/FmtNumber.cpp | 460 +++ .../lib/SdFat/src/FatLib/FmtNumber.h | 43 + .../lib/SdFat/src/FatLib/StdioStream.cpp | 508 +++ .../lib/SdFat/src/FatLib/StdioStream.h | 667 ++++ .../lib/SdFat/src/FatLib/bufstream.h | 172 + .../lib/SdFat/src/FatLib/fstream.cpp | 172 + .../lib/SdFat/src/FatLib/fstream.h | 320 ++ .../lib/SdFat/src/FatLib/ios.h | 423 +++ .../lib/SdFat/src/FatLib/iostream.h | 158 + .../lib/SdFat/src/FatLib/istream.cpp | 396 +++ .../lib/SdFat/src/FatLib/istream.h | 384 +++ .../lib/SdFat/src/FatLib/ostream.cpp | 196 ++ .../lib/SdFat/src/FatLib/ostream.h | 276 ++ .../lib/SdFat/src/FreeStack.h | 61 + .../lib/SdFat/src/MinimumSerial.cpp | 71 + .../lib/SdFat/src/MinimumSerial.h | 67 + .../lib/SdFat/src/SdCard/SdInfo.h | 485 +++ .../lib/SdFat/src/SdCard/SdSpiCard.cpp | 802 +++++ .../lib/SdFat/src/SdCard/SdSpiCard.h | 377 +++ .../lib/SdFat/src/SdCard/SdSpiCardEX.cpp | 94 + .../lib/SdFat/src/SdCard/SdioCard.h | 301 ++ .../lib/SdFat/src/SdCard/SdioCardEX.cpp | 108 + .../lib/SdFat/src/SdCard/SdioTeensy.cpp | 800 +++++ .../lib/SdFat/src/SdFat.h | 512 +++ .../lib/SdFat/src/SdFatConfig.h | 233 ++ .../lib/SdFat/src/SpiDriver/DigitalPin.h | 386 +++ .../lib/SdFat/src/SpiDriver/SdSpiBaseDriver.h | 79 + .../lib/SdFat/src/SpiDriver/SdSpiDriver.h | 438 +++ .../lib/SdFat/src/SpiDriver/SdSpiESP8266.cpp | 93 + .../lib/SdFat/src/SpiDriver/SdSpiParticle.cpp | 102 + .../lib/SdFat/src/SpiDriver/SdSpiSAM3X.cpp | 218 ++ .../lib/SdFat/src/SpiDriver/SdSpiSTM32.cpp | 105 + .../lib/SdFat/src/SpiDriver/SdSpiTeensy3.cpp | 233 ++ .../lib/SdFat/src/SpiDriver/SoftSPI.h | 167 + .../boards/AvrDevelopersGpioPinMap.h | 37 + .../src/SpiDriver/boards/BobuinoGpioPinMap.h | 37 + .../SdFat/src/SpiDriver/boards/GpioPinMap.h | 45 + .../src/SpiDriver/boards/LeonardoGpioPinMap.h | 35 + .../src/SpiDriver/boards/MegaGpioPinMap.h | 75 + .../boards/SleepingBeautyGpioPinMap.h | 37 + .../SpiDriver/boards/Standard1284GpioPinMap.h | 37 + .../src/SpiDriver/boards/Teensy2GpioPinMap.h | 30 + .../SpiDriver/boards/Teensy2ppGpioPinMap.h | 51 + .../src/SpiDriver/boards/UnoGpioPinMap.h | 25 + .../lib/SdFat/src/SysCall.h | 88 + .../lib/SdFat/src/sdios.h | 33 + .../Adafruit_ASFcore/Adafruit_ASFcore.h | 0 .../libraries/Adafruit_ASFcore/README.md | 33 + .../libraries/Adafruit_ASFcore/clock.h | 53 + .../Adafruit_ASFcore/clock_feature.h | 1492 +++++++++ .../libraries/Adafruit_ASFcore/compiler.h | 1157 +++++++ .../libraries/Adafruit_ASFcore/gclk.c | 522 +++ .../libraries/Adafruit_ASFcore/gclk.h | 307 ++ .../libraries/Adafruit_ASFcore/i2s.c | 750 +++++ .../libraries/Adafruit_ASFcore/i2s.h | 1404 ++++++++ .../libraries/Adafruit_ASFcore/interrupt.h | 117 + .../interrupt/interrupt_sam_nvic.c | 69 + .../interrupt/interrupt_sam_nvic.h | 172 + .../Adafruit_ASFcore/interrupt_sam_nvic.c | 86 + .../Adafruit_ASFcore/interrupt_sam_nvic.h | 189 ++ .../Adafruit_ASFcore/library.properties | 9 + .../libraries/Adafruit_ASFcore/parts.h | 1601 +++++++++ .../libraries/Adafruit_ASFcore/pinmux.c | 311 ++ .../libraries/Adafruit_ASFcore/pinmux.h | 678 ++++ .../libraries/Adafruit_ASFcore/power.h | 224 ++ .../preprocessor/mrecursion.h | 581 ++++ .../Adafruit_ASFcore/preprocessor/mrepeat.h | 321 ++ .../preprocessor/preprocessor.h | 38 + .../Adafruit_ASFcore/preprocessor/stringz.h | 67 + .../Adafruit_ASFcore/preprocessor/tpaste.h | 85 + .../libraries/Adafruit_ASFcore/reset.h | 119 + .../libraries/Adafruit_ASFcore/status_codes.h | 138 + .../libraries/Adafruit_ASFcore/system.c | 111 + .../libraries/Adafruit_ASFcore/system.h | 726 +++++ .../Adafruit_ASFcore/system_interrupt.h | 429 +++ .../system_interrupt_features.h | 195 ++ .../libraries/Adafruit_ASFcore/tc.c | 685 ++++ .../libraries/Adafruit_ASFcore/tc.h | 1783 ++++++++++ .../libraries/Adafruit_ASFcore/tc_interrupt.c | 199 ++ .../libraries/Adafruit_ASFcore/tc_interrupt.h | 179 + .../libraries/Adafruit_ASFcore/wdt.c | 264 ++ .../libraries/Adafruit_ASFcore/wdt.h | 501 +++ .../Adafruit_FONA_Library/Adafruit_FONA.cpp | 2079 ++++++++++++ .../Adafruit_FONA_Library/Adafruit_FONA.h | 263 ++ .../libraries/Adafruit_FONA_Library/README.md | 29 + .../FONA3G_setbaud/.esp8266.test.skip | 0 .../FONA3G_setbaud/FONA3G_setbaud.ino | 77 + .../FONA_SMS_Response/.esp8266.test.skip | 0 .../FONA_SMS_Response/FONA_SMS_Response.ino | 131 + .../examples/FONAtest/.esp8266.test.skip | 0 .../examples/FONAtest/FONAtest.ino | 886 +++++ .../examples/GPS/.esp8266.test.skip | 0 .../examples/GPS/GPS.ino | 112 + .../examples/IncomingCall/.esp8266.test.skip | 0 .../examples/IncomingCall/IncomingCall.ino | 62 + .../includes/FONAConfig.h | 34 + .../includes/FONAExtIncludes.h | 33 + .../includes/platform/FONAPlatStd.h | 67 + .../includes/platform/FONAPlatform.h | 62 + .../Adafruit_FONA_Library/library.properties | 9 + .../Adafruit_SleepyDog.cpp | 4 + .../Adafruit_SleepyDog.h | 28 + .../Adafruit_SleepyDog_Library/LICENSE | 22 + .../Adafruit_SleepyDog_Library/README.md | 6 + .../examples/BasicUsage/BasicUsage.ino | 62 + .../examples/Sleep/Sleep.ino | 37 + .../library.properties | 9 + .../utility/WatchdogAVR.cpp | 137 + .../utility/WatchdogAVR.h | 47 + .../utility/WatchdogKinetisK.cpp | 104 + .../utility/WatchdogKinetisK.h | 38 + .../utility/WatchdogKinetisL.cpp | 74 + .../utility/WatchdogKinetisL.h | 35 + .../utility/WatchdogSAMD.cpp | 175 + .../utility/WatchdogSAMD.h | 43 + .../libraries/ArduinoHttpClient/.gitignore | 2 + .../libraries/ArduinoHttpClient/CHANGELOG.md | 25 + .../libraries/ArduinoHttpClient/README.md | 22 + .../examples/BasicAuthGet/BasicAuthGet.ino | 69 + .../examples/BasicAuthGet/arduino_secrets.h | 3 + .../examples/CustomHeader/CustomHeader.ino | 96 + .../examples/CustomHeader/arduino_secrets.h | 3 + .../examples/DweetGet/DweetGet.ino | 107 + .../examples/DweetGet/arduino_secrets.h | 3 + .../examples/DweetPost/DweetPost.ino | 87 + .../examples/DweetPost/arduino_secrets.h | 3 + .../examples/HueBlink/HueBlink.ino | 102 + .../examples/HueBlink/arduino_secrets.h | 3 + .../PostWithHeaders/PostWithHeaders.ino | 79 + .../PostWithHeaders/arduino_secrets.h | 3 + .../examples/SimpleDelete/SimpleDelete.ino | 71 + .../examples/SimpleDelete/arduino_secrets.h | 3 + .../examples/SimpleGet/SimpleGet.ino | 66 + .../examples/SimpleGet/arduino_secrets.h | 3 + .../SimpleHttpExample/SimpleHttpExample.ino | 133 + .../SimpleHttpExample/arduino_secrets.h | 3 + .../examples/SimplePost/SimplePost.ino | 70 + .../examples/SimplePost/arduino_secrets.h | 3 + .../examples/SimplePut/SimplePut.ino | 70 + .../examples/SimplePut/arduino_secrets.h | 3 + .../SimpleWebSocket/SimpleWebSocket.ino | 80 + .../SimpleWebSocket/arduino_secrets.h | 3 + .../node_test_server/getPostPutDelete.js | 102 + .../examples/node_test_server/package.json | 13 + .../libraries/ArduinoHttpClient/keywords.txt | 64 + .../libraries/ArduinoHttpClient/library.json | 12 + .../ArduinoHttpClient/library.properties | 10 + .../ArduinoHttpClient/src/ArduinoHttpClient.h | 11 + .../ArduinoHttpClient/src/HttpClient.cpp | 862 +++++ .../ArduinoHttpClient/src/HttpClient.h | 392 +++ .../ArduinoHttpClient/src/WebSocketClient.cpp | 372 +++ .../ArduinoHttpClient/src/WebSocketClient.h | 99 + .../libraries/ArduinoHttpClient/src/b64.cpp | 72 + .../libraries/ArduinoHttpClient/src/b64.h | 6 + .../RTClib/.github/ISSUE_TEMPLATE.md | 46 + .../RTClib/.github/PULL_REQUEST_TEMPLATE.md | 26 + .../libraries/RTClib/README.md | 42 + .../libraries/RTClib/RTClib.cpp | 506 +++ .../libraries/RTClib/RTClib.h | 135 + .../RTClib/examples/datecalc/datecalc.ino | 111 + .../RTClib/examples/ds1307/ds1307.ino | 71 + .../examples/ds1307SqwPin/ds1307SqwPin.ino | 68 + .../examples/ds1307nvram/ds1307nvram.ino | 63 + .../RTClib/examples/ds3231/ds3231.ino | 77 + .../RTClib/examples/pcf8523/pcf8523.ino | 74 + .../RTClib/examples/softrtc/softrtc.ino | 61 + .../libraries/RTClib/keywords.txt | 37 + .../libraries/RTClib/library.properties | 9 + .../libraries/SD/File.cpp | 168 + .../libraries/SD/README.txt | 13 + .../libraries/SD/SD.cpp | 637 ++++ .../libraries/SD/SD.h | 138 + .../libraries/SD/utility/FatStructs.h | 418 +++ .../libraries/SD/utility/Sd2Card.cpp | 777 +++++ .../libraries/SD/utility/Sd2Card.h | 273 ++ .../libraries/SD/utility/Sd2PinMap.h | 525 +++ .../libraries/SD/utility/SdFat.h | 641 ++++ .../libraries/SD/utility/SdFatUtil.h | 77 + .../libraries/SD/utility/SdFatmainpage.h | 202 ++ .../libraries/SD/utility/SdFile.cpp | 1527 +++++++++ .../libraries/SD/utility/SdInfo.h | 232 ++ .../libraries/SD/utility/SdVolume.cpp | 351 ++ .../libraries/WiFi101/.travis.yml | 48 + .../libraries/WiFi101/CHANGELOG | 122 + .../libraries/WiFi101/README.adoc | 27 + .../AP_SimpleWebServer/AP_SimpleWebServer.ino | 176 + .../AP_SimpleWebServer/arduino_secrets.h | 3 + .../CheckWifi101FirmwareVersion.ino | 67 + .../ConnectNoEncryption.ino | 123 + .../ConnectNoEncryption/arduino_secrets.h | 1 + .../ConnectWithWEP/ConnectWithWEP.ino | 129 + .../examples/ConnectWithWEP/arduino_secrets.h | 3 + .../ConnectWithWPA/ConnectWithWPA.ino | 119 + .../examples/ConnectWithWPA/arduino_secrets.h | 3 + .../examples/FirmwareUpdater/Endianess.ino | 62 + .../FirmwareUpdater/FirmwareUpdater.ino | 129 + .../MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino | 170 + .../MDNS_WiFiWebServer/arduino_secrets.h | 3 + .../Provisioning_WiFiWebServer.ino | 167 + .../examples/ScanNetworks/ScanNetworks.ino | 120 + .../ScanNetworksAdvanced.ino | 149 + .../SimpleWebServerWiFi.ino | 131 + .../SimpleWebServerWiFi/arduino_secrets.h | 3 + .../WiFiChatServer/WiFiChatServer.ino | 114 + .../examples/WiFiChatServer/arduino_secrets.h | 3 + .../WiFi101/examples/WiFiPing/WiFiPing.ino | 140 + .../examples/WiFiPing/arduino_secrets.h | 3 + .../examples/WiFiSSLClient/WiFiSSLClient.ino | 107 + .../examples/WiFiSSLClient/arduino_secrets.h | 3 + .../WiFiUdpNtpClient/WiFiUdpNtpClient.ino | 182 ++ .../WiFiUdpNtpClient/arduino_secrets.h | 3 + .../WiFiUdpSendReceiveString.ino | 113 + .../arduino_secrets.h | 3 + .../examples/WiFiWebClient/WiFiWebClient.ino | 121 + .../examples/WiFiWebClient/arduino_secrets.h | 3 + .../WiFiWebClientRepeating.ino | 127 + .../WiFiWebClientRepeating/arduino_secrets.h | 3 + .../examples/WiFiWebServer/WiFiWebServer.ino | 135 + .../examples/WiFiWebServer/arduino_secrets.h | 3 + .../libraries/WiFi101/keywords.txt | 61 + .../libraries/WiFi101/library.properties | 10 + .../libraries/WiFi101/src/WiFi.cpp | 1106 +++++++ .../libraries/WiFi101/src/WiFi101.h | 193 ++ .../libraries/WiFi101/src/WiFiClient.cpp | 308 ++ .../libraries/WiFi101/src/WiFiClient.h | 68 + .../WiFi101/src/WiFiMDNSResponder.cpp | 220 ++ .../libraries/WiFi101/src/WiFiMDNSResponder.h | 51 + .../libraries/WiFi101/src/WiFiSSLClient.cpp | 45 + .../libraries/WiFi101/src/WiFiSSLClient.h | 36 + .../libraries/WiFi101/src/WiFiServer.cpp | 140 + .../libraries/WiFi101/src/WiFiServer.h | 49 + .../libraries/WiFi101/src/WiFiUdp.cpp | 289 ++ .../libraries/WiFi101/src/WiFiUdp.h | 89 + .../WiFi101/src/bsp/include/nm_bsp.h | 283 ++ .../WiFi101/src/bsp/include/nm_bsp_arduino.h | 74 + .../WiFi101/src/bsp/include/nm_bsp_avr.h | 54 + .../WiFi101/src/bsp/include/nm_bsp_internal.h | 59 + .../WiFi101/src/bsp/include/nm_bsp_samd21.h | 52 + .../WiFi101/src/bsp/source/nm_bsp_arduino.c | 205 ++ .../src/bsp/source/nm_bsp_arduino_avr.c | 164 + .../src/bus_wrapper/include/nm_bus_wrapper.h | 177 + .../source/nm_bus_wrapper_samd21.cpp | 200 ++ .../WiFi101/src/common/include/nm_common.h | 153 + .../WiFi101/src/common/include/nm_debug.h | 95 + .../WiFi101/src/common/source/nm_common.c | 136 + .../WiFi101/src/driver/include/ecc_types.h | 245 ++ .../WiFi101/src/driver/include/m2m_ate_mode.h | 732 +++++ .../WiFi101/src/driver/include/m2m_crypto.h | 272 ++ .../WiFi101/src/driver/include/m2m_ota.h | 428 +++ .../WiFi101/src/driver/include/m2m_periph.h | 411 +++ .../WiFi101/src/driver/include/m2m_ssl.h | 182 ++ .../WiFi101/src/driver/include/m2m_types.h | 2383 ++++++++++++++ .../WiFi101/src/driver/include/m2m_wifi.h | 2882 +++++++++++++++++ .../WiFi101/src/driver/source/m2m_ate_mode.c | 826 +++++ .../WiFi101/src/driver/source/m2m_crypto.c | 1010 ++++++ .../WiFi101/src/driver/source/m2m_hif.c | 767 +++++ .../WiFi101/src/driver/source/m2m_hif.h | 249 ++ .../WiFi101/src/driver/source/m2m_ota.c | 417 +++ .../WiFi101/src/driver/source/m2m_periph.c | 187 ++ .../WiFi101/src/driver/source/m2m_ssl.c | 309 ++ .../WiFi101/src/driver/source/m2m_wifi.c | 1522 +++++++++ .../WiFi101/src/driver/source/nmasic.c | 688 ++++ .../WiFi101/src/driver/source/nmasic.h | 215 ++ .../WiFi101/src/driver/source/nmbus.c | 301 ++ .../WiFi101/src/driver/source/nmbus.h | 147 + .../WiFi101/src/driver/source/nmdrv.c | 402 +++ .../WiFi101/src/driver/source/nmdrv.h | 138 + .../WiFi101/src/driver/source/nmi2c.c | 269 ++ .../WiFi101/src/driver/source/nmi2c.h | 104 + .../WiFi101/src/driver/source/nmspi.c | 1401 ++++++++ .../WiFi101/src/driver/source/nmspi.h | 132 + .../WiFi101/src/driver/source/nmuart.c | 536 +++ .../WiFi101/src/driver/source/nmuart.h | 118 + .../src/socket/include/m2m_socket_host_if.h | 461 +++ .../WiFi101/src/socket/include/socket.h | 2065 ++++++++++++ .../src/socket/include/socket_buffer.h | 94 + .../WiFi101/src/socket/source/socket.c | 1445 +++++++++ .../WiFi101/src/socket/source/socket_buffer.c | 232 ++ .../src/socket/source/socket_internal.h | 71 + .../WiFi101/src/spi_flash/include/spi_flash.h | 233 ++ .../src/spi_flash/include/spi_flash_map.h | 245 ++ .../WiFi101/src/spi_flash/source/spi_flash.c | 770 +++++ .../project.properties | 3 + .../src/config.cpp | 453 +++ .../feather_sensor_transmit_lte/src/config.h | 39 + .../src/feather_sensor_transmit_lte.cpp | 178 + .../src/feather_sensor_transmit_lte.ino | 166 + .../feather_sensor_transmit_lte/src/rtc.cpp | 58 + .../feather_sensor_transmit_lte/src/rtc.h | 11 + .../src/transmit.cpp | 513 +++ .../src/transmit.h | 58 + .../src/user_config.h | 4 + .../src/watchdog.cpp | 25 + .../src/watchdog.h | 9 + .../target/1.1.0/boron/module_user_memory.ld | 4 + 674 files changed, 148884 insertions(+), 1 deletion(-) create mode 160000 boron create mode 100644 feather_sensor_lte/boron_firmware_1574729317031.bin create mode 100644 feather_sensor_transmit/.vscode/c_cpp_properties.json create mode 100644 feather_sensor_transmit/.vscode/launch.json create mode 100644 feather_sensor_transmit/.vscode/settings.json create mode 100644 feather_sensor_transmit/boron_firmware_1574447345899.bin create mode 100644 feather_sensor_transmit/boron_firmware_1574729317031.bin create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/Adafruit_ASFcore.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/README.md create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/clock.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/clock_feature.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/compiler.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/gclk.c create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/gclk.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/i2s.c create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/i2s.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/library.properties create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/parts.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/pinmux.c create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/pinmux.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/power.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/stringz.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/tpaste.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/reset.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/status_codes.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/system.c create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/system.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/system_interrupt.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/system_interrupt_features.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/tc.c create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/tc.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/tc_interrupt.c create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/tc_interrupt.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/wdt.c create mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/wdt.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp create mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/Adafruit_FONA.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/README.md create mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/.esp8266.test.skip create mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino create mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/.esp8266.test.skip create mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino create mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONAtest/.esp8266.test.skip create mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino create mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/GPS/.esp8266.test.skip create mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino create mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/IncomingCall/.esp8266.test.skip create mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino create mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/FONAConfig.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/library.properties create mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp create mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/LICENSE create mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/README.md create mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino create mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino create mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/library.properties create mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp create mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp create mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp create mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h create mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp create mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/.gitignore create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/CHANGELOG.md create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/README.md create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/node_test_server/package.json create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/keywords.txt create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/library.json create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/library.properties create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/src/HttpClient.cpp create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/src/HttpClient.h create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/src/WebSocketClient.cpp create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/src/WebSocketClient.h create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/src/b64.cpp create mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/src/b64.h create mode 100644 feather_sensor_transmit/libraries/DHT/.github/ISSUE_TEMPLATE.md create mode 100644 feather_sensor_transmit/libraries/DHT/.github/PULL_REQUEST_TEMPLATE.md create mode 100644 feather_sensor_transmit/libraries/DHT/DHT.cpp create mode 100644 feather_sensor_transmit/libraries/DHT/DHT.h create mode 100644 feather_sensor_transmit/libraries/DHT/DHT_U.cpp create mode 100644 feather_sensor_transmit/libraries/DHT/DHT_U.h create mode 100644 feather_sensor_transmit/libraries/DHT/README.md create mode 100644 feather_sensor_transmit/libraries/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino create mode 100644 feather_sensor_transmit/libraries/DHT/examples/DHTtester/DHTtester.ino create mode 100644 feather_sensor_transmit/libraries/DHT/keywords.txt create mode 100644 feather_sensor_transmit/libraries/DHT/library.properties create mode 100644 feather_sensor_transmit/libraries/RTClib/.github/ISSUE_TEMPLATE.md create mode 100644 feather_sensor_transmit/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md create mode 100644 feather_sensor_transmit/libraries/RTClib/README.md create mode 100644 feather_sensor_transmit/libraries/RTClib/RTClib.cpp create mode 100644 feather_sensor_transmit/libraries/RTClib/RTClib.h create mode 100644 feather_sensor_transmit/libraries/RTClib/examples/datecalc/datecalc.ino create mode 100644 feather_sensor_transmit/libraries/RTClib/examples/ds1307/ds1307.ino create mode 100644 feather_sensor_transmit/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino create mode 100644 feather_sensor_transmit/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino create mode 100644 feather_sensor_transmit/libraries/RTClib/examples/ds3231/ds3231.ino create mode 100644 feather_sensor_transmit/libraries/RTClib/examples/pcf8523/pcf8523.ino create mode 100644 feather_sensor_transmit/libraries/RTClib/examples/softrtc/softrtc.ino create mode 100644 feather_sensor_transmit/libraries/RTClib/keywords.txt create mode 100644 feather_sensor_transmit/libraries/RTClib/library.properties create mode 100644 feather_sensor_transmit/libraries/WiFi101/.travis.yml create mode 100644 feather_sensor_transmit/libraries/WiFi101/CHANGELOG create mode 100644 feather_sensor_transmit/libraries/WiFi101/README.adoc create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino create mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/keywords.txt create mode 100644 feather_sensor_transmit/libraries/WiFi101/library.properties create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFi.cpp create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFi101.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiClient.cpp create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiClient.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiMDNSResponder.cpp create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiMDNSResponder.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiSSLClient.cpp create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiSSLClient.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiServer.cpp create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiServer.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiUdp.cpp create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiUdp.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/bus_wrapper/include/nm_bus_wrapper.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/common/include/nm_common.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/common/include/nm_debug.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/common/source/nm_common.c create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/include/ecc_types.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_ate_mode.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_crypto.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_ota.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_periph.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_ssl.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_types.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_wifi.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ate_mode.c create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_crypto.c create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_hif.c create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_hif.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ota.c create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_periph.c create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ssl.c create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_wifi.c create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmasic.c create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmasic.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmbus.c create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmbus.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmdrv.c create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmdrv.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmi2c.c create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmi2c.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmspi.c create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmspi.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmuart.c create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmuart.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/socket/include/socket.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/socket/include/socket_buffer.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket.c create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket_buffer.c create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket_internal.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/spi_flash/include/spi_flash.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h create mode 100644 feather_sensor_transmit/libraries/WiFi101/src/spi_flash/source/spi_flash.c create mode 100644 feather_sensor_transmit/project.properties create mode 100644 feather_sensor_transmit/src/LICENSE.txt create mode 100644 feather_sensor_transmit/src/README.md create mode 100644 feather_sensor_transmit/src/config.cpp create mode 100644 feather_sensor_transmit/src/config.h create mode 100644 feather_sensor_transmit/src/heatseek_sensor.ino create mode 100644 feather_sensor_transmit/src/rtc.cpp create mode 100644 feather_sensor_transmit/src/rtc.h create mode 100644 feather_sensor_transmit/src/transmit.cpp create mode 100644 feather_sensor_transmit/src/transmit.h create mode 100644 feather_sensor_transmit/src/user_config.h create mode 100644 feather_sensor_transmit/src/watchdog.cpp create mode 100644 feather_sensor_transmit/src/watchdog.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/c_cpp_properties.json create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/launch.json create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/settings.json create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/README.md create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/boron_firmware_1574447345899.bin create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/boron_firmware_1574729317031.bin create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/LICENSE.txt create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/README.md create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/examples/DHTtester/DHTtester.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/keywords.txt create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/library.properties create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT_U.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT_U.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/LICENSE.md create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/README.md create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/AnalogLogger/AnalogLogger.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/BaseExtCaseTest/BaseExtCaseTest.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/HelloWorld/HelloWorld.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/MiniSerial/MiniSerial.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/PrintBenchmarkSD/PrintBenchmarkSD.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/SD_Size/SD_Size.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/SdFatSize/SdFatSize.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/StreamParseInt/StreamParseInt.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/append/append.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/average/average.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/benchSD/benchSD.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/bufstream/bufstream.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/cin_cout/cin_cout.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/eventlog/eventlog.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/fgetsRewrite/fgetsRewrite.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/readlog/readlog.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/readme.txt create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/AnalogBinLogger/AnalogBinLogger.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/AnalogBinLogger/AnalogBinLogger.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/DirectoryFunctions/DirectoryFunctions.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/LongFileName.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/A long name can be 255 characters.txt create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/LFN,NAME.TXT create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/MIXCASE.txt create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/Not_8_3.txt create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/OK%83.TXT create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/STD_8_3.TXT create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/With Blank.txt create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/With.Two dots.txt create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/lower.txt create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/mixed.TXT create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/LowLatencyLogger.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/UserFunctions.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/UserTypes.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/LowLatencyLogger.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/LowLatencyLoggerADXL345.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/UserFunctions.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/UserTypes.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/readme.txt create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/LowLatencyLogger.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/LowLatencyLoggerMPU6050.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/UserFunctions.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/UserTypes.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/OpenNext/OpenNext.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/PrintBenchmark/PrintBenchmark.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/QuickStart/QuickStart.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/RawWrite/RawWrite.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsv/ReadCsv.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsvArray/ReadCsvArray.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsvStream/ReadCsvStream.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadWrite/ReadWrite.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/STM32Test/STM32Test.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SdFormatter/SdFormatter.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SdInfo/SdInfo.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SoftwareSpi/SoftwareSpi.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/StdioBench/StdioBench.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/TeensySdioDemo/TeensySdioDemo.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/Timestamp/Timestamp.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/TwoCards/TwoCards.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/VolumeFreeSpace/VolumeFreeSpace.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/bench/bench.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/dataLogger/dataLogger.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/fgets/fgets.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/formatting/formatting.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/getline/getline.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/rename/rename.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/wipe/wipe.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/AdcErrorStudy.txt create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/RateTable.txt create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/bintocsv/AnalogBinLogger.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/bintocsv/bintocsv.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/readme.txt create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/MainPage/SdFatmainpage.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/SdFatTestSuite.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/SdFatTestSuite.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_File/ATS_SD_File.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_Files/ATS_SD_Files.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_Seek/ATS_SD_Seek.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/StressTest/StressTest.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/TestMkdir/TestMkdir.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/TestRmdir/TestRmdir.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/fstreamTest/fstreamTest.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/istreamTest/istreamTest.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnSize/lfnSize.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnTest/lfnTest.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnTestCout/lfnTestCout.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ostreamTest/ostreamTest.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/changes.txt create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/cpplint.txt create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/library.properties create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/BlockDriver.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ArduinoFiles.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ArduinoStream.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/BaseBlockDriver.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatApiConstants.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFile.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFile.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileLFN.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFilePrint.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileSFN.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileSystem.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatLib.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatLibConfig.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatStructs.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatVolume.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatVolume.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FmtNumber.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FmtNumber.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/StdioStream.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/StdioStream.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/bufstream.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/fstream.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/fstream.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ios.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/iostream.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/istream.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/istream.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ostream.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ostream.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FreeStack.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/MinimumSerial.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/MinimumSerial.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdInfo.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCard.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCard.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCardEX.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioCard.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioCardEX.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioTeensy.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdFat.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdFatConfig.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/DigitalPin.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiBaseDriver.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiDriver.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiESP8266.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiParticle.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiSAM3X.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiSTM32.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiTeensy3.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SoftSPI.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/AvrDevelopersGpioPinMap.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/BobuinoGpioPinMap.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/GpioPinMap.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/LeonardoGpioPinMap.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/MegaGpioPinMap.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/SleepingBeautyGpioPinMap.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Standard1284GpioPinMap.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Teensy2GpioPinMap.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Teensy2ppGpioPinMap.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/UnoGpioPinMap.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SysCall.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/sdios.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/Adafruit_ASFcore.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/README.md create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/clock.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/clock_feature.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/compiler.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/gclk.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/gclk.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/i2s.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/i2s.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/library.properties create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/parts.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/pinmux.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/pinmux.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/power.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/stringz.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/tpaste.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/reset.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/status_codes.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system_interrupt.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system_interrupt_features.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc_interrupt.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc_interrupt.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/wdt.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/wdt.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/README.md create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/.esp8266.test.skip create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/.esp8266.test.skip create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/.esp8266.test.skip create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/GPS/.esp8266.test.skip create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/.esp8266.test.skip create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/FONAConfig.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/library.properties create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/LICENSE create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/README.md create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/library.properties create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/.gitignore create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/CHANGELOG.md create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/README.md create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/node_test_server/package.json create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/keywords.txt create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/library.json create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/library.properties create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/HttpClient.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/HttpClient.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/WebSocketClient.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/WebSocketClient.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/b64.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/b64.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/.github/ISSUE_TEMPLATE.md create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/README.md create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/RTClib.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/RTClib.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/datecalc/datecalc.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307/ds1307.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds3231/ds3231.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/pcf8523/pcf8523.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/softrtc/softrtc.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/keywords.txt create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/library.properties create mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/File.cpp create mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/README.txt create mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/SD.cpp create mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/SD.h create mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/FatStructs.h create mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2Card.cpp create mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2Card.h create mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2PinMap.h create mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFat.h create mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFatUtil.h create mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFatmainpage.h create mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFile.cpp create mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdInfo.h create mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdVolume.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/.travis.yml create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/CHANGELOG create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/README.adoc create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/keywords.txt create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/library.properties create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFi.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFi101.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiClient.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiClient.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiMDNSResponder.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiMDNSResponder.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiSSLClient.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiSSLClient.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiServer.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiServer.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiUdp.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiUdp.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bus_wrapper/include/nm_bus_wrapper.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/include/nm_common.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/include/nm_debug.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/source/nm_common.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/ecc_types.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_ate_mode.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_crypto.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_ota.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_periph.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_ssl.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_types.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_wifi.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ate_mode.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_crypto.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_hif.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_hif.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ota.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_periph.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ssl.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_wifi.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmasic.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmasic.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmbus.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmbus.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmdrv.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmdrv.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmi2c.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmi2c.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmspi.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmspi.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmuart.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmuart.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/socket.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/socket_buffer.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket_buffer.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket_internal.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/include/spi_flash.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/source/spi_flash.c create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/project.properties create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/config.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/config.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.ino create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/rtc.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/rtc.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/transmit.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/transmit.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/user_config.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/watchdog.cpp create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/watchdog.h create mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/target/1.1.0/boron/module_user_memory.ld diff --git a/boron b/boron new file mode 160000 index 0000000..bc0e560 --- /dev/null +++ b/boron @@ -0,0 +1 @@ +Subproject commit bc0e56015aaea350d627b8f199ba69fc7943cad1 diff --git a/feather_sensor_lte/.vscode/settings.json b/feather_sensor_lte/.vscode/settings.json index 185ece2..5d5f015 100644 --- a/feather_sensor_lte/.vscode/settings.json +++ b/feather_sensor_lte/.vscode/settings.json @@ -4,7 +4,7 @@ "files.associations": { "*.ino": "cpp" }, - "particle.targetDevice": "e00fce68ec3e4cd7fe833f2e", + "particle.targetDevice": "e00fce684c6a4946ca9fecd1", "particle.firmwareVersion": "1.1.0", "particle.targetPlatform": "boron", "git.ignoreLimitWarning": true diff --git a/feather_sensor_lte/boron_firmware_1574729317031.bin b/feather_sensor_lte/boron_firmware_1574729317031.bin new file mode 100644 index 0000000000000000000000000000000000000000..544964835a60d84338704d5bd1234e633fc8cef4 GIT binary patch literal 5592 zcmd5=e{d9c6@PoXm%IEpxKOBP0?ghmXAchWXj;9NIunv~6LJX@soEAh-ZeSgND{6g zv1!FINUL;er>&(UE!JrT9O{V8)t*Cu?Ku{m))u|AD0ILPwKcS~y1|xP@@xHkckdS& z$G;rMo%!7Nz3;yFzVF9(-}jqPy^BtM&P7CJ!Uh zK!cF^yzUR}Y38oi#}d%H4mwk}Vr^~yVJGAzT|MutCvA&L+6N<~T^OOk;fW!wzC6*) zNqi#FOyo?JML4f#7ioW(5lqU``Q1yD9>m(rmvCxM`<%AGF3wBZ$r;WoLOL_E{=@qc zq&+_!*hQFsWd^etkDK%A`7qXf7Cz-|kfy^YTclR0Rk+8UYMYJ6+9uz1CBJDFzjqdY zW)@%jl`HivK2Wf~$$Ver_s-(a%;IaeFndM$O|$sg?knG0@!V8c?~EB=k*_uVE%H`; zMc#_9$XoFhc`KeGZ~0&3Eqk4X_4k_Vw-oqVbNwQ3$rpJm-Xg!rjIV?@?Rg6JEd3&X z#QL z%y|`9Tw~b0L$Xh1^lF2CutWCBwDP(PExmShn_>&vG8Mt{%(8Qb$7$|0nY+8fvapJ@ zHz&k%BbZs7>F=ucaR*7OnkkbW*5`+~L&CU|_gv>uZdaDc{4bq#`x+L=*-`GfvV)F8 zqB#rFv3{i1ne9aJLH}+LHRT<%263uJ+adyJ?r&RV^ zY5sc5Uzhn?le67u+D@cy-Y&>aDr4KVdU}gLmt7BFBQl(nsgz8aNHTRT~bheg9%3HkP z{$N(Ja>~)_SZi+~%{|Gtgw^-o!F>WyfLj4plXsendwl@evpU721!^xSwo@O$nBVpH zs>NN8`$eI9+*#172W9Q`M)N(huu_H3Z2|u>nY;xY#Z4>O>$z`tj}MLTD9Lc$*Rj}k~&!4x9yACvCBEhDSP`n`m14OzbUhD zql?_B`94U(uTgU@gnQAqhq;6Jf()w;ZnF+;lhGviW3TLJF|wm(6f1Zho_A8@OmPPqmj8f+bWb&wugiX6UY@QB%++KH}p6*?Se z_BYmxoT;iv9eU912Cvk1?P;b!`B`VA12d1#v5(~Q^Uyq zY?6z3qE2-=?#Yf6N%VM)yj8o0GqTYse)vvZm?Uzf8h2F$otayL<)h^|WmhN7Hy1q3 zM)n<}>|CkV%{i^}sE-?Kd~Fg{*Un8iB3C6vnfZVYf!d}g$;-E>=iT^EN@H0ZwKgVdfGcDlU(A5M^lPdI*wMo)`IuXRa@X7(~ z4c2XNcBs6v7iUN)_0Vu7_VUB}5;wPOPrAbA8kdBhOsculLH$*Y!yG!fQVn?~DgkD+D@)oEnP*$IrYf3U(6Gw2K z<1DvwS%r1GkxQI=xqdm<{7wfi-?=KsZJvGI65odM+fB$^pFr`B|eLwW;L9@Lv7klT) zsX%i7cqMNOa;Hgjt44MhJNdU$&Lp?|(pyHhdK%}-v}zTQO6h4oUbN&HRv~T^nB2n96hf@#$6&ar$nZzM5dxdhVA)oi5*{w9kImD;u4vKB{DT7GAx$7&n%XFTr8G+Tr8Hn42vZ%!(z$H zFrU8gmd?fwiT|wHng?x)*cf`VK0zHA3uhO|7 zEt?$m)NtWM^CJB3=XT%$;6b4Dd7#Nfj{r{s`+!5h2=FUl6nG2xEARo3e}cFxdx4Ju zE`S3*y4gkV0)GZh0VjY`9oA>AVfVS*!}``C-~k{GJPbSmJPjNG^3OY<%UfKu0QdsV zrg8AoKo;OJH-_;7kbgdgJBth8ff2mV0vCWk0jGcyz{^0XZ|t7)9Iz8$YkVE!mw~Oo zKHwf82IQaSRu|m>tOo8Ne=tfOAR z?uqsFQoOHkYabTw?dqUdcXvKH7{Af(q5)tF5Cc93tOY&;Tn_{RFHl;867~No*$8VN zUxU4X{rDF4sTXyuMvYehYk+e2@gVR=;MH|5YG04{x47u{KIr~kO#?Ku+fSs8q`McqAq MGC(&!fBm2T1#!eoE&u=k literal 0 HcmV?d00001 diff --git a/feather_sensor_lte/src/feather_sensor_lte.ino b/feather_sensor_lte/src/feather_sensor_lte.ino index 5e5c1a3..e6af00e 100644 --- a/feather_sensor_lte/src/feather_sensor_lte.ino +++ b/feather_sensor_lte/src/feather_sensor_lte.ino @@ -5,6 +5,7 @@ int led1 = D0; // Instead of writing D0 over and over again, we'll write led1 // You'll need to wire an LED to this one to see it blink. +// You'll need to wire an LED to this one to see it blink. int led2 = D7; // Instead of writing D7 over and over again, we'll write led2 // This one is the little blue LED on your board. On the Photon it is next to D7, and on the Core it is next to the USB jack. diff --git a/feather_sensor_transmit/.vscode/c_cpp_properties.json b/feather_sensor_transmit/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..c16b552 --- /dev/null +++ b/feather_sensor_transmit/.vscode/c_cpp_properties.json @@ -0,0 +1,18 @@ +{ + "configurations": [ + { + "name": "Win32", + "includePath": [ + "${workspaceFolder}/**" + ], + "defines": [ + "_DEBUG", + "UNICODE", + "_UNICODE" + ], + "intelliSenseMode": "msvc-x64", + "configurationProvider": "particle.particle-vscode-core" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/feather_sensor_transmit/.vscode/launch.json b/feather_sensor_transmit/.vscode/launch.json new file mode 100644 index 0000000..4532e35 --- /dev/null +++ b/feather_sensor_transmit/.vscode/launch.json @@ -0,0 +1,92 @@ +{ + "version": "0.1.0", + "configurations": [ + { + "type": "cortex-debug", + "request": "attach", + "name": "Particle Debugger (photon, p1, electron)", + "servertype": "openocd", + "interface": "swd", + "device": "STM32F205RG", + "cwd": "${workspaceRoot}", + "executable": "${command:particle.getDebuggerExecutable}", + "preLaunchTask": "Particle: Flash application for debug (local)", + "armToolchainPath": "${command:particle.getDebuggerCompilerDir}", + "svdFile": "${command:particle.getDebuggerSVDFile}", + "searchDir": [ + "${command:particle.getDebuggerSearchDir}" + ], + "configFiles": [ + "interface/cmsis-dap.cfg", + "target/stm32f2x.cfg" + ], + "postAttachCommands": [ + "monitor reset halt" + ], + "windows": { + "configFiles": [ + "interface\\cmsis-dap.cfg", + "target\\stm32f2x.cfg" + ] + } + }, + { + "type": "cortex-debug", + "request": "attach", + "name": "Particle Debugger (argon, boron / bsom, xenon)", + "servertype": "openocd", + "interface": "swd", + "device": "nRF52840_xxAA", + "cwd": "${workspaceRoot}", + "executable": "${command:particle.getDebuggerExecutable}", + "preLaunchTask": "Particle: Flash application for debug (local)", + "armToolchainPath": "${command:particle.getDebuggerCompilerDir}", + "svdFile": "${command:particle.getDebuggerSVDFile}", + "searchDir": [ + "${command:particle.getDebuggerSearchDir}" + ], + "configFiles": [ + "interface/cmsis-dap.cfg", + "target/nrf52-particle.cfg" + ], + "postAttachCommands": [ + "monitor reset halt" + ], + "windows": { + "configFiles": [ + "interface\\cmsis-dap.cfg", + "target\\nrf52-particle.cfg" + ] + } + }, + { + "type": "cortex-debug", + "request": "attach", + "name": "Particle Programmer Shield v1.0 (photon, p1, electron)", + "servertype": "openocd", + "interface": "swd", + "device": "STM32F205RG", + "cwd": "${workspaceRoot}", + "executable": "${command:particle.getDebuggerExecutable}", + "preLaunchTask": "Particle: Flash application for debug (local)", + "armToolchainPath": "${command:particle.getDebuggerCompilerDir}", + "svdFile": "${command:particle.getDebuggerSVDFile}", + "searchDir": [ + "${command:particle.getDebuggerSearchDir}" + ], + "configFiles": [ + "interface/particle-ftdi.cfg", + "target/stm32f2x.cfg" + ], + "postAttachCommands": [ + "monitor reset halt" + ], + "windows": { + "configFiles": [ + "interface\\particle-ftdi.cfg", + "target\\stm32f2x.cfg" + ] + } + } + ] +} \ No newline at end of file diff --git a/feather_sensor_transmit/.vscode/settings.json b/feather_sensor_transmit/.vscode/settings.json new file mode 100644 index 0000000..5d5f015 --- /dev/null +++ b/feather_sensor_transmit/.vscode/settings.json @@ -0,0 +1,11 @@ +{ + "extensions.ignoreRecommendations": true, + "cortex-debug.openocdPath": "${command:particle.getDebuggerOpenocdPath}", + "files.associations": { + "*.ino": "cpp" + }, + "particle.targetDevice": "e00fce684c6a4946ca9fecd1", + "particle.firmwareVersion": "1.1.0", + "particle.targetPlatform": "boron", + "git.ignoreLimitWarning": true +} \ No newline at end of file diff --git a/feather_sensor_transmit/boron_firmware_1574447345899.bin b/feather_sensor_transmit/boron_firmware_1574447345899.bin new file mode 100644 index 0000000000000000000000000000000000000000..544964835a60d84338704d5bd1234e633fc8cef4 GIT binary patch literal 5592 zcmd5=e{d9c6@PoXm%IEpxKOBP0?ghmXAchWXj;9NIunv~6LJX@soEAh-ZeSgND{6g zv1!FINUL;er>&(UE!JrT9O{V8)t*Cu?Ku{m))u|AD0ILPwKcS~y1|xP@@xHkckdS& z$G;rMo%!7Nz3;yFzVF9(-}jqPy^BtM&P7CJ!Uh zK!cF^yzUR}Y38oi#}d%H4mwk}Vr^~yVJGAzT|MutCvA&L+6N<~T^OOk;fW!wzC6*) zNqi#FOyo?JML4f#7ioW(5lqU``Q1yD9>m(rmvCxM`<%AGF3wBZ$r;WoLOL_E{=@qc zq&+_!*hQFsWd^etkDK%A`7qXf7Cz-|kfy^YTclR0Rk+8UYMYJ6+9uz1CBJDFzjqdY zW)@%jl`HivK2Wf~$$Ver_s-(a%;IaeFndM$O|$sg?knG0@!V8c?~EB=k*_uVE%H`; zMc#_9$XoFhc`KeGZ~0&3Eqk4X_4k_Vw-oqVbNwQ3$rpJm-Xg!rjIV?@?Rg6JEd3&X z#QL z%y|`9Tw~b0L$Xh1^lF2CutWCBwDP(PExmShn_>&vG8Mt{%(8Qb$7$|0nY+8fvapJ@ zHz&k%BbZs7>F=ucaR*7OnkkbW*5`+~L&CU|_gv>uZdaDc{4bq#`x+L=*-`GfvV)F8 zqB#rFv3{i1ne9aJLH}+LHRT<%263uJ+adyJ?r&RV^ zY5sc5Uzhn?le67u+D@cy-Y&>aDr4KVdU}gLmt7BFBQl(nsgz8aNHTRT~bheg9%3HkP z{$N(Ja>~)_SZi+~%{|Gtgw^-o!F>WyfLj4plXsendwl@evpU721!^xSwo@O$nBVpH zs>NN8`$eI9+*#172W9Q`M)N(huu_H3Z2|u>nY;xY#Z4>O>$z`tj}MLTD9Lc$*Rj}k~&!4x9yACvCBEhDSP`n`m14OzbUhD zql?_B`94U(uTgU@gnQAqhq;6Jf()w;ZnF+;lhGviW3TLJF|wm(6f1Zho_A8@OmPPqmj8f+bWb&wugiX6UY@QB%++KH}p6*?Se z_BYmxoT;iv9eU912Cvk1?P;b!`B`VA12d1#v5(~Q^Uyq zY?6z3qE2-=?#Yf6N%VM)yj8o0GqTYse)vvZm?Uzf8h2F$otayL<)h^|WmhN7Hy1q3 zM)n<}>|CkV%{i^}sE-?Kd~Fg{*Un8iB3C6vnfZVYf!d}g$;-E>=iT^EN@H0ZwKgVdfGcDlU(A5M^lPdI*wMo)`IuXRa@X7(~ z4c2XNcBs6v7iUN)_0Vu7_VUB}5;wPOPrAbA8kdBhOsculLH$*Y!yG!fQVn?~DgkD+D@)oEnP*$IrYf3U(6Gw2K z<1DvwS%r1GkxQI=xqdm<{7wfi-?=KsZJvGI65odM+fB$^pFr`B|eLwW;L9@Lv7klT) zsX%i7cqMNOa;Hgjt44MhJNdU$&Lp?|(pyHhdK%}-v}zTQO6h4oUbN&HRv~T^nB2n96hf@#$6&ar$nZzM5dxdhVA)oi5*{w9kImD;u4vKB{DT7GAx$7&n%XFTr8G+Tr8Hn42vZ%!(z$H zFrU8gmd?fwiT|wHng?x)*cf`VK0zHA3uhO|7 zEt?$m)NtWM^CJB3=XT%$;6b4Dd7#Nfj{r{s`+!5h2=FUl6nG2xEARo3e}cFxdx4Ju zE`S3*y4gkV0)GZh0VjY`9oA>AVfVS*!}``C-~k{GJPbSmJPjNG^3OY<%UfKu0QdsV zrg8AoKo;OJH-_;7kbgdgJBth8ff2mV0vCWk0jGcyz{^0XZ|t7)9Iz8$YkVE!mw~Oo zKHwf82IQaSRu|m>tOo8Ne=tfOAR z?uqsFQoOHkYabTw?dqUdcXvKH7{Af(q5)tF5Cc93tOY&;Tn_{RFHl;867~No*$8VN zUxU4X{rDF4sTXyuMvYehYk+e2@gVR=;MH|5YG04{x47u{KIr~kO#?Ku+fSs8q`McqAq MGC(&!fBm2T1#!eoE&u=k literal 0 HcmV?d00001 diff --git a/feather_sensor_transmit/boron_firmware_1574729317031.bin b/feather_sensor_transmit/boron_firmware_1574729317031.bin new file mode 100644 index 0000000000000000000000000000000000000000..544964835a60d84338704d5bd1234e633fc8cef4 GIT binary patch literal 5592 zcmd5=e{d9c6@PoXm%IEpxKOBP0?ghmXAchWXj;9NIunv~6LJX@soEAh-ZeSgND{6g zv1!FINUL;er>&(UE!JrT9O{V8)t*Cu?Ku{m))u|AD0ILPwKcS~y1|xP@@xHkckdS& z$G;rMo%!7Nz3;yFzVF9(-}jqPy^BtM&P7CJ!Uh zK!cF^yzUR}Y38oi#}d%H4mwk}Vr^~yVJGAzT|MutCvA&L+6N<~T^OOk;fW!wzC6*) zNqi#FOyo?JML4f#7ioW(5lqU``Q1yD9>m(rmvCxM`<%AGF3wBZ$r;WoLOL_E{=@qc zq&+_!*hQFsWd^etkDK%A`7qXf7Cz-|kfy^YTclR0Rk+8UYMYJ6+9uz1CBJDFzjqdY zW)@%jl`HivK2Wf~$$Ver_s-(a%;IaeFndM$O|$sg?knG0@!V8c?~EB=k*_uVE%H`; zMc#_9$XoFhc`KeGZ~0&3Eqk4X_4k_Vw-oqVbNwQ3$rpJm-Xg!rjIV?@?Rg6JEd3&X z#QL z%y|`9Tw~b0L$Xh1^lF2CutWCBwDP(PExmShn_>&vG8Mt{%(8Qb$7$|0nY+8fvapJ@ zHz&k%BbZs7>F=ucaR*7OnkkbW*5`+~L&CU|_gv>uZdaDc{4bq#`x+L=*-`GfvV)F8 zqB#rFv3{i1ne9aJLH}+LHRT<%263uJ+adyJ?r&RV^ zY5sc5Uzhn?le67u+D@cy-Y&>aDr4KVdU}gLmt7BFBQl(nsgz8aNHTRT~bheg9%3HkP z{$N(Ja>~)_SZi+~%{|Gtgw^-o!F>WyfLj4plXsendwl@evpU721!^xSwo@O$nBVpH zs>NN8`$eI9+*#172W9Q`M)N(huu_H3Z2|u>nY;xY#Z4>O>$z`tj}MLTD9Lc$*Rj}k~&!4x9yACvCBEhDSP`n`m14OzbUhD zql?_B`94U(uTgU@gnQAqhq;6Jf()w;ZnF+;lhGviW3TLJF|wm(6f1Zho_A8@OmPPqmj8f+bWb&wugiX6UY@QB%++KH}p6*?Se z_BYmxoT;iv9eU912Cvk1?P;b!`B`VA12d1#v5(~Q^Uyq zY?6z3qE2-=?#Yf6N%VM)yj8o0GqTYse)vvZm?Uzf8h2F$otayL<)h^|WmhN7Hy1q3 zM)n<}>|CkV%{i^}sE-?Kd~Fg{*Un8iB3C6vnfZVYf!d}g$;-E>=iT^EN@H0ZwKgVdfGcDlU(A5M^lPdI*wMo)`IuXRa@X7(~ z4c2XNcBs6v7iUN)_0Vu7_VUB}5;wPOPrAbA8kdBhOsculLH$*Y!yG!fQVn?~DgkD+D@)oEnP*$IrYf3U(6Gw2K z<1DvwS%r1GkxQI=xqdm<{7wfi-?=KsZJvGI65odM+fB$^pFr`B|eLwW;L9@Lv7klT) zsX%i7cqMNOa;Hgjt44MhJNdU$&Lp?|(pyHhdK%}-v}zTQO6h4oUbN&HRv~T^nB2n96hf@#$6&ar$nZzM5dxdhVA)oi5*{w9kImD;u4vKB{DT7GAx$7&n%XFTr8G+Tr8Hn42vZ%!(z$H zFrU8gmd?fwiT|wHng?x)*cf`VK0zHA3uhO|7 zEt?$m)NtWM^CJB3=XT%$;6b4Dd7#Nfj{r{s`+!5h2=FUl6nG2xEARo3e}cFxdx4Ju zE`S3*y4gkV0)GZh0VjY`9oA>AVfVS*!}``C-~k{GJPbSmJPjNG^3OY<%UfKu0QdsV zrg8AoKo;OJH-_;7kbgdgJBth8ff2mV0vCWk0jGcyz{^0XZ|t7)9Iz8$YkVE!mw~Oo zKHwf82IQaSRu|m>tOo8Ne=tfOAR z?uqsFQoOHkYabTw?dqUdcXvKH7{Af(q5)tF5Cc93tOY&;Tn_{RFHl;867~No*$8VN zUxU4X{rDF4sTXyuMvYehYk+e2@gVR=;MH|5YG04{x47u{KIr~kO#?Ku+fSs8q`McqAq MGC(&!fBm2T1#!eoE&u=k literal 0 HcmV?d00001 diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/Adafruit_ASFcore.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/Adafruit_ASFcore.h new file mode 100644 index 0000000..e69de29 diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/README.md b/feather_sensor_transmit/libraries/Adafruit_ASFcore/README.md new file mode 100644 index 0000000..8de73c7 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/README.md @@ -0,0 +1,33 @@ +# ASF (Atmel Software Framework) for Arduino Zero / Adafruit Feather M0 (SAMD21) + +Copy of ASF (Atmel Software Framework) excerpts for the SAMD21 processor used in the Arduino Zero / Adafruit Feather M0 boards. +You typically won't use this library directly, instead other libraries will depend on this library and use the code +within it to simplify their implementation. + +All code is taken directly from Atmel's ASF: http://www.atmel.com/tools/avrsoftwareframework.aspx?tab=overview + +The code is copyright Atmel and released by them under the following license: + + 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. The name of Atmel may not be used to endorse or promote products derived from this software without specific + prior written permission. + + 4. This software may only be redistributed and used in connection with an Atmel microcontroller product. + + THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN + NO EVENT SHALL ATMEL 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. diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/clock.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/clock.h new file mode 100644 index 0000000..549e3e9 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/clock.h @@ -0,0 +1,53 @@ +/** + * \file + * + * \brief SAM Clock Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef SYSTEM_CLOCK_H_INCLUDED +#define SYSTEM_CLOCK_H_INCLUDED + +#include "compiler.h" +#include "gclk.h" +#include "clock_feature.h" + +#endif /* SYSTEM_CLOCK_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/clock_feature.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/clock_feature.h new file mode 100644 index 0000000..be63c7c --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/clock_feature.h @@ -0,0 +1,1492 @@ +/** + * \file + * + * \brief SAM Clock Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef SYSTEM_CLOCK_FEATURE_H_INCLUDED +#define SYSTEM_CLOCK_FEATURE_H_INCLUDED + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup asfdoc_sam0_system_clock_group SAM System Clock Management Driver (SYSTEM CLOCK) + * + * This driver for Atmel® | SMART ARM®-based microcontrollers provides an interface for the configuration + * and management of the device's clocking related functions. This includes + * the various clock sources, bus clocks, and generic clocks within the device, + * with functions to manage the enabling, disabling, source selection, and + * prescaling of clocks to various internal peripherals. + * + * The following peripherals are used by this module: + * + * - GCLK (Generic Clock Management) + * - PM (Power Management) + * - SYSCTRL (Clock Source Control) + * + * The following devices can use this module: + * - Atmel | SMART SAM D20/D21 + * - Atmel | SMART SAM R21 + * - Atmel | SMART SAM D10/D11 + * - Atmel | SMART SAM DA0/DA1 + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_system_clock_prerequisites + * - \ref asfdoc_sam0_system_clock_module_overview + * - \ref asfdoc_sam0_system_clock_special_considerations + * - \ref asfdoc_sam0_system_clock_extra_info + * - \ref asfdoc_sam0_system_clock_examples + * - \ref asfdoc_sam0_system_clock_api_overview + * + * + * \section asfdoc_sam0_system_clock_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * + * \section asfdoc_sam0_system_clock_module_overview Module Overview + * The SAM devices contain a sophisticated clocking system, which is designed + * to give the maximum flexibility to the user application. This system allows + * a system designer to tune the performance and power consumption of the device + * in a dynamic manner, to achieve the best trade-off between the two for a + * particular application. + * + * This driver provides a set of functions for the configuration and management + * of the various clock related functionality within the device. + * + * \subsection asfdoc_sam0_system_clock_module_features Driver Feature Macro Definition + * + * + * + * + * + * + * + * + * + *
Driver Feature MacroSupported devices
FEATURE_SYSTEM_CLOCK_DPLLSAMD21, SAMR21, SAMD10, SAMD11, SAMDAx
+ * \note The specific features are only available in the driver when the + * selected device supports those features. + * + * \subsection asfdoc_sam0_system_clock_module_overview_clock_sources Clock Sources + * The SAM devices have a number of master clock source modules, each of + * which being capable of producing a stabilized output frequency, which can then + * be fed into the various peripherals and modules within the device. + * + * Possible clock source modules include internal R/C oscillators, internal + * DFLL modules, as well as external crystal oscillators and/or clock inputs. + * + * \subsection asfdoc_sam0_system_clock_module_overview_cpu_clock CPU / Bus Clocks + * The CPU and AHB/APBx buses are clocked by the same physical clock source + * (referred in this module as the Main Clock), however the APBx buses may + * have additional prescaler division ratios set to give each peripheral bus a + * different clock speed. + * + * The general main clock tree for the CPU and associated buses is shown in + * \ref asfdoc_sam0_system_clock_module_clock_tree "the figure below". + * + * \anchor asfdoc_sam0_system_clock_module_clock_tree + * \dot + * digraph overview { + * rankdir=LR; + * clk_src [label="Clock Sources", shape=none, height=0]; + * node [label="CPU Bus" shape=ellipse] cpu_bus; + * node [label="AHB Bus" shape=ellipse] ahb_bus; + * node [label="APBA Bus" shape=ellipse] apb_a_bus; + * node [label="APBB Bus" shape=ellipse] apb_b_bus; + * node [label="APBC Bus" shape=ellipse] apb_c_bus; + * node [label="Main Bus\nPrescaler" shape=square] main_prescaler; + * node [label="APBA Bus\nPrescaler" shape=square] apb_a_prescaler; + * node [label="APBB Bus\nPrescaler" shape=square] apb_b_prescaler; + * node [label="APBC Bus\nPrescaler" shape=square] apb_c_prescaler; + * node [label="", shape=polygon, sides=4, distortion=0.6, orientation=90, style=filled, fillcolor=black, height=0.9, width=0.2] main_clock_mux; + * + * clk_src -> main_clock_mux; + * main_clock_mux -> main_prescaler; + * main_prescaler -> cpu_bus; + * main_prescaler -> ahb_bus; + * main_prescaler -> apb_a_prescaler; + * main_prescaler -> apb_b_prescaler; + * main_prescaler -> apb_c_prescaler; + * apb_a_prescaler -> apb_a_bus; + * apb_b_prescaler -> apb_b_bus; + * apb_c_prescaler -> apb_c_bus; + * } + * \enddot + * + * \subsection asfdoc_sam0_system_clock_module_overview_clock_masking Clock Masking + * To save power, the input clock to one or more peripherals on the AHB and APBx + * buses can be masked away - when masked, no clock is passed into the module. + * Disabling of clocks of unused modules will prevent all access to the masked + * module, but will reduce the overall device power consumption. + * + * \subsection asfdoc_sam0_system_clock_module_overview_gclk Generic Clocks + * Within the SAM devices there are a number of Generic Clocks; these are used to + * provide clocks to the various peripheral clock domains in the device in a + * standardized manner. One or more master source clocks can be selected as the + * input clock to a Generic Clock Generator, which can prescale down the input + * frequency to a slower rate for use in a peripheral. + * + * Additionally, a number of individually selectable Generic Clock Channels are + * provided, which multiplex and gate the various generator outputs for one or + * more peripherals within the device. This setup allows for a single common + * generator to feed one or more channels, which can then be enabled or disabled + * individually as required. + * + * \anchor asfdoc_sam0_system_clock_module_chain_overview + * \dot + * digraph overview { + * rankdir=LR; + * node [label="Clock\nSource a" shape=square] system_clock_source; + * node [label="Generator 1" shape=square] clock_gen; + * node [label="Channel x" shape=square] clock_chan0; + * node [label="Channel y" shape=square] clock_chan1; + * node [label="Peripheral x" shape=ellipse style=filled fillcolor=lightgray] peripheral0; + * node [label="Peripheral y" shape=ellipse style=filled fillcolor=lightgray] peripheral1; + * + * system_clock_source -> clock_gen; + * clock_gen -> clock_chan0; + * clock_chan0 -> peripheral0; + * clock_gen -> clock_chan1; + * clock_chan1 -> peripheral1; + * } + * \enddot + * + * \subsubsection asfdoc_sam0_system_clock_module_chain_example Clock Chain Example + * An example setup of a complete clock chain within the device is shown in + * \ref asfdoc_sam0_system_clock_module_chain_example_fig "the figure below". + * + * \anchor asfdoc_sam0_system_clock_module_chain_example_fig + * \dot + * digraph overview { + * rankdir=LR; + * node [label="External\nOscillator" shape=square] system_clock_source0; + * node [label="Generator 0" shape=square] clock_gen0; + * node [label="Channel x" shape=square] clock_chan0; + * node [label="Core CPU" shape=ellipse style=filled fillcolor=lightgray] peripheral0; + * + * system_clock_source0 -> clock_gen0; + * clock_gen0 -> clock_chan0; + * clock_chan0 -> peripheral0; + * node [label="8MHz R/C\nOscillator (OSC8M)" shape=square fillcolor=white] system_clock_source1; + * node [label="Generator 1" shape=square] clock_gen1; + * node [label="Channel y" shape=square] clock_chan1; + * node [label="Channel z" shape=square] clock_chan2; + * node [label="SERCOM\nModule" shape=ellipse style=filled fillcolor=lightgray] peripheral1; + * node [label="Timer\nModule" shape=ellipse style=filled fillcolor=lightgray] peripheral2; + * + * system_clock_source1 -> clock_gen1; + * clock_gen1 -> clock_chan1; + * clock_gen1 -> clock_chan2; + * clock_chan1 -> peripheral1; + * clock_chan2 -> peripheral2; + * } + * \enddot + * + * \subsubsection asfdoc_sam0_system_clock_module_overview_gclk_generators Generic Clock Generators + * Each Generic Clock generator within the device can source its input clock + * from one of the provided Source Clocks, and prescale the output for one or + * more Generic Clock Channels in a one-to-many relationship. The generators + * thus allow for several clocks to be generated of different frequencies, + * power usages, and accuracies, which can be turned on and off individually to + * disable the clocks to multiple peripherals as a group. + * + * \subsubsection asfdoc_sam0_system_clock_module_overview_gclk_channels Generic Clock Channels + * To connect a Generic Clock Generator to a peripheral within the + * device, a Generic Clock Channel is used. Each peripheral or + * peripheral group has an associated Generic Clock Channel, which serves as the + * clock input for the peripheral(s). To supply a clock to the peripheral + * module(s), the associated channel must be connected to a running Generic + * Clock Generator and the channel enabled. + * + * \section asfdoc_sam0_system_clock_special_considerations Special Considerations + * + * There are no special considerations for this module. + * + * + * \section asfdoc_sam0_system_clock_extra_info Extra Information + * + * For extra information, see \ref asfdoc_sam0_system_clock_extra. This includes: + * - \ref asfdoc_sam0_system_clock_extra_acronyms + * - \ref asfdoc_sam0_system_clock_extra_dependencies + * - \ref asfdoc_sam0_system_clock_extra_errata + * - \ref asfdoc_sam0_system_clock_extra_history + * + * + * \section asfdoc_sam0_system_clock_examples Examples + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_system_clock_exqsg. + * + * + * \section asfdoc_sam0_system_clock_api_overview API Overview + * @{ + */ + +#include "compiler.h" +#include "gclk.h" + +/** + * \name Driver Feature Definition + * Define system clock features set according to different device family. + * @{ + */ +#if (SAMD21) || (SAMR21) || (SAMD11) || (SAMD10) || (SAMDA1) || defined(__DOXYGEN__) +/** Digital Phase Locked Loop (DPLL) feature support. */ +# define FEATURE_SYSTEM_CLOCK_DPLL +#endif +/*@}*/ + +/** + * \brief Available start-up times for the XOSC32K. + * + * Available external 32KHz oscillator start-up times, as a number of external + * clock cycles. + */ +enum system_xosc32k_startup { + /** Wait zero clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_0, + /** Wait 32 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_32, + /** Wait 2048 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_2048, + /** Wait 4096 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_4096, + /** Wait 16384 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_16384, + /** Wait 32768 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_32768, + /** Wait 65536 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_65536, + /** Wait 131072 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_131072, +}; + +/** + * \brief Available start-up times for the XOSC. + * + * Available external oscillator start-up times, as a number of external clock + * cycles. + */ +enum system_xosc_startup { + /** Wait one clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_1, + /** Wait two clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_2, + /** Wait four clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_4, + /** Wait eight clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_8, + /** Wait 16 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_16, + /** Wait 32 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_32, + /** Wait 64 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_64, + /** Wait 128 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_128, + /** Wait 256 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_256, + /** Wait 512 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_512, + /** Wait 1024 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_1024, + /** Wait 2048 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_2048, + /** Wait 4096 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_4096, + /** Wait 8192 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_8192, + /** Wait 16384 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_16384, + /** Wait 32768 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_32768, +}; + +/** + * \brief Available start-up times for the OSC32K. + * + * Available internal 32KHz oscillator start-up times, as a number of internal + * OSC32K clock cycles. + */ +enum system_osc32k_startup { + /** Wait three clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_3, + /** Wait four clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_4, + /** Wait six clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_6, + /** Wait ten clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_10, + /** Wait 18 clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_18, + /** Wait 34 clock cycles until the clock source is considered stable */ + SYSTEM_OSC32K_STARTUP_34, + /** Wait 66 clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_66, + /** Wait 130 clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_130, +}; + +/** + * \brief Division prescalers for the internal 8MHz system clock. + * + * Available prescalers for the internal 8MHz (nominal) system clock. + */ +enum system_osc8m_div { + /** Do not divide the 8MHz RC oscillator output. */ + SYSTEM_OSC8M_DIV_1, + /** Divide the 8MHz RC oscillator output by two. */ + SYSTEM_OSC8M_DIV_2, + /** Divide the 8MHz RC oscillator output by four. */ + SYSTEM_OSC8M_DIV_4, + /** Divide the 8MHz RC oscillator output by eight. */ + SYSTEM_OSC8M_DIV_8, +}; + +/** + * \brief Frequency range for the internal 8MHz RC oscillator. + * + * Internal 8MHz RC oscillator frequency range setting + */ +enum system_osc8m_frequency_range { + /** Frequency range 4MHz to 6MHz. */ + SYSTEM_OSC8M_FREQUENCY_RANGE_4_TO_6, + /** Frequency range 6MHz to 8MHz. */ + SYSTEM_OSC8M_FREQUENCY_RANGE_6_TO_8, + /** Frequency range 8MHz to 11MHz. */ + SYSTEM_OSC8M_FREQUENCY_RANGE_8_TO_11, + /** Frequency range 11MHz to 15MHz. */ + SYSTEM_OSC8M_FREQUENCY_RANGE_11_TO_15, +}; + +/** + * \brief Main CPU and APB/AHB bus clock source prescaler values. + * + * Available division ratios for the CPU and APB/AHB bus clocks. + */ +enum system_main_clock_div { + /** Divide Main clock by one. */ + SYSTEM_MAIN_CLOCK_DIV_1, + /** Divide Main clock by two. */ + SYSTEM_MAIN_CLOCK_DIV_2, + /** Divide Main clock by four. */ + SYSTEM_MAIN_CLOCK_DIV_4, + /** Divide Main clock by eight. */ + SYSTEM_MAIN_CLOCK_DIV_8, + /** Divide Main clock by 16. */ + SYSTEM_MAIN_CLOCK_DIV_16, + /** Divide Main clock by 32. */ + SYSTEM_MAIN_CLOCK_DIV_32, + /** Divide Main clock by 64. */ + SYSTEM_MAIN_CLOCK_DIV_64, + /** Divide Main clock by 128. */ + SYSTEM_MAIN_CLOCK_DIV_128, +}; + +/** + * \brief External clock source types. + * + * Available external clock source types. + */ +enum system_clock_external { + /** The external clock source is a crystal oscillator. */ + SYSTEM_CLOCK_EXTERNAL_CRYSTAL, + /** The connected clock source is an external logic level clock signal. */ + SYSTEM_CLOCK_EXTERNAL_CLOCK, +}; + +/** + * \brief Operating modes of the DFLL clock source. + * + * Available operating modes of the DFLL clock source module. + */ +enum system_clock_dfll_loop_mode { + /** The DFLL is operating in open loop mode with no feedback. */ + SYSTEM_CLOCK_DFLL_LOOP_MODE_OPEN, + /** The DFLL is operating in closed loop mode with frequency feedback from + * a low frequency reference clock. + */ + SYSTEM_CLOCK_DFLL_LOOP_MODE_CLOSED = SYSCTRL_DFLLCTRL_MODE, + +#ifdef SYSCTRL_DFLLCTRL_USBCRM + /** The DFLL is operating in USB recovery mode with frequency feedback + * from USB SOF. + */ + SYSTEM_CLOCK_DFLL_LOOP_MODE_USB_RECOVERY = SYSCTRL_DFLLCTRL_USBCRM, +#endif +}; + +/** + * \brief Locking behavior for the DFLL during device wake-up. + * + * DFLL lock behavior modes on device wake-up from sleep. + */ +enum system_clock_dfll_wakeup_lock { + /** Keep DFLL lock when the device wakes from sleep. */ + SYSTEM_CLOCK_DFLL_WAKEUP_LOCK_KEEP, + /** Lose DFLL lock when the devices wakes from sleep. */ + SYSTEM_CLOCK_DFLL_WAKEUP_LOCK_LOSE = SYSCTRL_DFLLCTRL_LLAW, +}; + +/** + * \brief Fine tracking behavior for the DFLL once a lock has been acquired. + * + * DFLL fine tracking behavior modes after a lock has been acquired. + */ +enum system_clock_dfll_stable_tracking { + /** Keep tracking after the DFLL has gotten a fine lock. */ + SYSTEM_CLOCK_DFLL_STABLE_TRACKING_TRACK_AFTER_LOCK, + /** Stop tracking after the DFLL has gotten a fine lock. */ + SYSTEM_CLOCK_DFLL_STABLE_TRACKING_FIX_AFTER_LOCK = SYSCTRL_DFLLCTRL_STABLE, +}; + +/** + * \brief Chill-cycle behavior of the DFLL module. + * + * DFLL chill-cycle behavior modes of the DFLL module. A chill cycle is a period + * of time when the DFLL output frequency is not measured by the unit, to allow + * the output to stabilize after a change in the input clock source. + */ +enum system_clock_dfll_chill_cycle { + /** Enable a chill cycle, where the DFLL output frequency is not measured. */ + SYSTEM_CLOCK_DFLL_CHILL_CYCLE_ENABLE, + /** Disable a chill cycle, where the DFLL output frequency is not measured. */ + SYSTEM_CLOCK_DFLL_CHILL_CYCLE_DISABLE = SYSCTRL_DFLLCTRL_CCDIS, +}; + +/** + * \brief QuickLock settings for the DFLL module. + * + * DFLL QuickLock settings for the DFLL module, to allow for a faster lock of + * the DFLL output frequency at the expense of accuracy. + */ +enum system_clock_dfll_quick_lock { + /** Enable the QuickLock feature for looser lock requirements on the DFLL. */ + SYSTEM_CLOCK_DFLL_QUICK_LOCK_ENABLE, + /** Disable the QuickLock feature for strict lock requirements on the DFLL. */ + SYSTEM_CLOCK_DFLL_QUICK_LOCK_DISABLE = SYSCTRL_DFLLCTRL_QLDIS, +}; + +/** + * \brief Available clock sources in the system. + * + * Clock sources available to the GCLK generators. + */ +enum system_clock_source { + /** Internal 8MHz RC oscillator. */ + SYSTEM_CLOCK_SOURCE_OSC8M = GCLK_SOURCE_OSC8M, + /** Internal 32KHz RC oscillator. */ + SYSTEM_CLOCK_SOURCE_OSC32K = GCLK_SOURCE_OSC32K, + /** External oscillator. */ + SYSTEM_CLOCK_SOURCE_XOSC = GCLK_SOURCE_XOSC , + /** External 32KHz oscillator. */ + SYSTEM_CLOCK_SOURCE_XOSC32K = GCLK_SOURCE_XOSC32K, + /** Digital Frequency Locked Loop (DFLL). */ + SYSTEM_CLOCK_SOURCE_DFLL = GCLK_SOURCE_DFLL48M, + /** Internal Ultra Low Power 32KHz oscillator. */ + SYSTEM_CLOCK_SOURCE_ULP32K = GCLK_SOURCE_OSCULP32K, + /** Generator input pad. */ + SYSTEM_CLOCK_SOURCE_GCLKIN = GCLK_SOURCE_GCLKIN, + /** Generic clock generator one output. */ + SYSTEM_CLOCK_SOURCE_GCLKGEN1 = GCLK_SOURCE_GCLKGEN1, +#ifdef FEATURE_SYSTEM_CLOCK_DPLL + /** Digital Phase Locked Loop (DPLL). + * Check \c FEATURE_SYSTEM_CLOCK_DPLL for which device support it. + */ + SYSTEM_CLOCK_SOURCE_DPLL = GCLK_SOURCE_FDPLL, +#endif +}; + +/** + * \brief List of APB peripheral buses. + * + * Available bus clock domains on the APB bus. + */ +enum system_clock_apb_bus { + /** Peripheral bus A on the APB bus. */ + SYSTEM_CLOCK_APB_APBA, + /** Peripheral bus B on the APB bus. */ + SYSTEM_CLOCK_APB_APBB, + /** Peripheral bus C on the APB bus. */ + SYSTEM_CLOCK_APB_APBC, +}; + +/** + * \brief Configuration structure for XOSC. + * + * External oscillator clock configuration structure. + */ +struct system_clock_source_xosc_config { + /** External clock type. */ + enum system_clock_external external_clock; + /** Crystal oscillator start-up time. */ + enum system_xosc_startup startup_time; + /** Enable automatic amplitude gain control. */ + bool auto_gain_control; + /** External clock/crystal frequency. */ + uint32_t frequency; + /** Keep the XOSC enabled in standby sleep mode. */ + bool run_in_standby; + /** Run On Demand. If this is set the XOSC won't run + * until requested by a peripheral. */ + bool on_demand; +}; + +/** + * \brief Configuration structure for XOSC32K. + * + * External 32KHz oscillator clock configuration structure. + */ +struct system_clock_source_xosc32k_config { + /** External clock type. */ + enum system_clock_external external_clock; + /** Crystal oscillator start-up time. */ + enum system_xosc32k_startup startup_time; + /** Enable automatic amplitude control. */ + bool auto_gain_control; + /** Enable 1KHz output. */ + bool enable_1khz_output; + /** Enable 32KHz output. */ + bool enable_32khz_output; + /** External clock/crystal frequency. */ + uint32_t frequency; + /** Keep the XOSC32K enabled in standby sleep mode. */ + bool run_in_standby; + /** Run On Demand. If this is set the XOSC32K won't run + * until requested by a peripheral. */ + bool on_demand; + /** Lock configuration after it has been written, + * a device reset will release the lock. */ + bool write_once; +}; + +/** + * \brief Configuration structure for OSC8M. + * + * Internal 8MHz (nominal) oscillator configuration structure. + */ +struct system_clock_source_osc8m_config { + /** Internal 8MHz RC oscillator prescaler. */ + enum system_osc8m_div prescaler; + /** Keep the OSC8M enabled in standby sleep mode. */ + bool run_in_standby; + /** Run On Demand. If this is set the OSC8M won't run + * until requested by a peripheral. */ + bool on_demand; +}; + +/** + * \brief Configuration structure for OSC32K. + * + * Internal 32KHz (nominal) oscillator configuration structure. + */ +struct system_clock_source_osc32k_config { + /** Startup time. */ + enum system_osc32k_startup startup_time; + /** Enable 1KHz output. */ + bool enable_1khz_output; + /** Enable 32KHz output. */ + bool enable_32khz_output; + /** Keep the OSC32K enabled in standby sleep mode. */ + bool run_in_standby; + /** Run On Demand. If this is set the OSC32K won't run + * until requested by a peripheral. */ + bool on_demand; + /** Lock configuration after it has been written, + * a device reset will release the lock. */ + bool write_once; +}; + +/** + * \brief Configuration structure for DFLL. + * + * DFLL oscillator configuration structure. + */ +struct system_clock_source_dfll_config { + /** Loop mode. */ + enum system_clock_dfll_loop_mode loop_mode; + /** Run On Demand. If this is set the DFLL won't run + * until requested by a peripheral. */ + bool on_demand; + /** Enable Quick Lock. */ + enum system_clock_dfll_quick_lock quick_lock; + /** Enable Chill Cycle. */ + enum system_clock_dfll_chill_cycle chill_cycle; + /** DFLL lock state on wakeup. */ + enum system_clock_dfll_wakeup_lock wakeup_lock; + /** DFLL tracking after fine lock. */ + enum system_clock_dfll_stable_tracking stable_tracking; + /** Coarse calibration value (Open loop mode). */ + uint8_t coarse_value; + /** Fine calibration value (Open loop mode). */ + uint16_t fine_value; + /** Coarse adjustment maximum step size (Closed loop mode). */ + uint8_t coarse_max_step; + /** Fine adjustment maximum step size (Closed loop mode). */ + uint16_t fine_max_step; + /** DFLL multiply factor (Closed loop mode. */ + uint16_t multiply_factor; +}; + +/** + * \name External Oscillator Management + * @{ + */ + +/** + * \brief Retrieve the default configuration for XOSC. + * + * Fills a configuration structure with the default configuration for an + * external oscillator module: + * - External Crystal + * - Start-up time of 16384 external clock cycles + * - Automatic crystal gain control mode enabled + * - Frequency of 12MHz + * - Don't run in STANDBY sleep mode + * - Run only when requested by peripheral (on demand) + * + * \param[out] config Configuration structure to fill with default values + */ +static inline void system_clock_source_xosc_get_config_defaults( + struct system_clock_source_xosc_config *const config) +{ + Assert(config); + + config->external_clock = SYSTEM_CLOCK_EXTERNAL_CRYSTAL; + config->startup_time = SYSTEM_XOSC_STARTUP_16384; + config->auto_gain_control = true; + config->frequency = 12000000UL; + config->run_in_standby = false; + config->on_demand = true; +} + +void system_clock_source_xosc_set_config( + struct system_clock_source_xosc_config *const config); + +/** + * @} + */ + + +/** + * \name External 32KHz Oscillator Management + * @{ + */ + +/** + * \brief Retrieve the default configuration for XOSC32K. + * + * Fills a configuration structure with the default configuration for an + * external 32KHz oscillator module: + * - External Crystal + * - Start-up time of 16384 external clock cycles + * - Automatic crystal gain control mode disabled + * - Frequency of 32.768KHz + * - 1KHz clock output disabled + * - 32KHz clock output enabled + * - Don't run in STANDBY sleep mode + * - Run only when requested by peripheral (on demand) + * - Don't lock registers after configuration has been written + * + * \param[out] config Configuration structure to fill with default values + */ +static inline void system_clock_source_xosc32k_get_config_defaults( + struct system_clock_source_xosc32k_config *const config) +{ + Assert(config); + + config->external_clock = SYSTEM_CLOCK_EXTERNAL_CRYSTAL; + config->startup_time = SYSTEM_XOSC32K_STARTUP_16384; + config->auto_gain_control = false; + config->frequency = 32768UL; + config->enable_1khz_output = false; + config->enable_32khz_output = true; + config->run_in_standby = false; + config->on_demand = true; + config->write_once = false; +} + +void system_clock_source_xosc32k_set_config( + struct system_clock_source_xosc32k_config *const config); +/** + * @} + */ + + +/** + * \name Internal 32KHz Oscillator Management + * @{ + */ + +/** + * \brief Retrieve the default configuration for OSC32K. + * + * Fills a configuration structure with the default configuration for an + * internal 32KHz oscillator module: + * - 1KHz clock output enabled + * - 32KHz clock output enabled + * - Don't run in STANDBY sleep mode + * - Run only when requested by peripheral (on demand) + * - Set startup time to 130 cycles + * - Don't lock registers after configuration has been written + * + * \param[out] config Configuration structure to fill with default values + */ +static inline void system_clock_source_osc32k_get_config_defaults( + struct system_clock_source_osc32k_config *const config) +{ + Assert(config); + + config->enable_1khz_output = true; + config->enable_32khz_output = true; + config->run_in_standby = false; + config->on_demand = true; + config->startup_time = SYSTEM_OSC32K_STARTUP_130; + config->write_once = false; +} + +void system_clock_source_osc32k_set_config( + struct system_clock_source_osc32k_config *const config); + +/** + * @} + */ + + +/** + * \name Internal 8MHz Oscillator Management + * @{ + */ + +/** + * \brief Retrieve the default configuration for OSC8M. + * + * Fills a configuration structure with the default configuration for an + * internal 8MHz (nominal) oscillator module: + * - Clock output frequency divided by a factor of eight + * - Don't run in STANDBY sleep mode + * - Run only when requested by peripheral (on demand) + * + * \param[out] config Configuration structure to fill with default values + */ +static inline void system_clock_source_osc8m_get_config_defaults( + struct system_clock_source_osc8m_config *const config) +{ + Assert(config); + + config->prescaler = SYSTEM_OSC8M_DIV_8; + config->run_in_standby = false; + config->on_demand = true; +} + +void system_clock_source_osc8m_set_config( + struct system_clock_source_osc8m_config *const config); + +/** + * @} + */ + + +/** + * \name Internal DFLL Management + * @{ + */ + +/** + * \brief Retrieve the default configuration for DFLL. + * + * Fills a configuration structure with the default configuration for a + * DFLL oscillator module: + * - Open loop mode + * - QuickLock mode enabled + * - Chill cycle enabled + * - Output frequency lock maintained during device wake-up + * - Continuous tracking of the output frequency + * - Default tracking values at the mid-points for both coarse and fine + * tracking parameters + * - Don't run in STANDBY sleep mode + * - Run only when requested by peripheral (on demand) + * + * \param[out] config Configuration structure to fill with default values + */ +static inline void system_clock_source_dfll_get_config_defaults( + struct system_clock_source_dfll_config *const config) +{ + Assert(config); + + config->loop_mode = SYSTEM_CLOCK_DFLL_LOOP_MODE_OPEN; + config->quick_lock = SYSTEM_CLOCK_DFLL_QUICK_LOCK_ENABLE; + config->chill_cycle = SYSTEM_CLOCK_DFLL_CHILL_CYCLE_ENABLE; + config->wakeup_lock = SYSTEM_CLOCK_DFLL_WAKEUP_LOCK_KEEP; + config->stable_tracking = SYSTEM_CLOCK_DFLL_STABLE_TRACKING_TRACK_AFTER_LOCK; + config->on_demand = true; + + /* Open loop mode calibration value */ + config->coarse_value = 0x1f / 4; /* Midpoint */ + config->fine_value = 0xff / 4; /* Midpoint */ + + /* Closed loop mode */ + config->coarse_max_step = 1; + config->fine_max_step = 1; + config->multiply_factor = 6; /* Multiply 8MHz by 6 to get 48MHz */ +} + +void system_clock_source_dfll_set_config( + struct system_clock_source_dfll_config *const config); + +/** + * @} + */ + +/** + * \name Clock Source Management + * @{ + */ +enum status_code system_clock_source_write_calibration( + const enum system_clock_source system_clock_source, + const uint16_t calibration_value, + const uint8_t freq_range); + +enum status_code system_clock_source_enable( + const enum system_clock_source system_clock_source); + +enum status_code system_clock_source_disable( + const enum system_clock_source clk_source); + +bool system_clock_source_is_ready( + const enum system_clock_source clk_source); + +uint32_t system_clock_source_get_hz( + const enum system_clock_source clk_source); + +/** + * @} + */ + +/** + * \name Main Clock Management + * @{ + */ + +/** + * \brief Set main CPU clock divider. + * + * Sets the clock divider used on the main clock to provide the CPU clock. + * + * \param[in] divider CPU clock divider to set + */ +static inline void system_cpu_clock_set_divider( + const enum system_main_clock_div divider) +{ + Assert(((uint32_t)divider & PM_CPUSEL_CPUDIV_Msk) == divider); + PM->CPUSEL.reg = (uint32_t)divider; +} + +/** + * \brief Retrieves the current frequency of the CPU core. + * + * Retrieves the operating frequency of the CPU core, obtained from the main + * generic clock and the set CPU bus divider. + * + * \return Current CPU frequency in Hz. + */ +static inline uint32_t system_cpu_clock_get_hz(void) +{ + return (system_gclk_gen_get_hz(GCLK_GENERATOR_0) >> PM->CPUSEL.reg); +} + +/** + * \brief Set APBx clock divider. + * + * Set the clock divider used on the main clock to provide the clock for the + * given APBx bus. + * + * \param[in] divider APBx bus divider to set + * \param[in] bus APBx bus to set divider + * + * \returns Status of the clock division change operation. + * + * \retval STATUS_ERR_INVALID_ARG Invalid bus ID was given + * \retval STATUS_OK The APBx clock was set successfully + */ +static inline enum status_code system_apb_clock_set_divider( + const enum system_clock_apb_bus bus, + const enum system_main_clock_div divider) +{ + switch (bus) { + case SYSTEM_CLOCK_APB_APBA: + PM->APBASEL.reg = (uint32_t)divider; + break; + case SYSTEM_CLOCK_APB_APBB: + PM->APBBSEL.reg = (uint32_t)divider; + break; + case SYSTEM_CLOCK_APB_APBC: + PM->APBCSEL.reg = (uint32_t)divider; + break; + default: + Assert(false); + return STATUS_ERR_INVALID_ARG; + } + + return STATUS_OK; +} + +/** + * \brief Retrieves the current frequency of a ABPx. + * + * Retrieves the operating frequency of an APBx bus, obtained from the main + * generic clock and the set APBx bus divider. + * + * \return Current APBx bus frequency in Hz. + */ +static inline uint32_t system_apb_clock_get_hz( + const enum system_clock_apb_bus bus) +{ + uint16_t bus_divider = 0; + + switch (bus) { + case SYSTEM_CLOCK_APB_APBA: + bus_divider = PM->APBASEL.reg; + break; + case SYSTEM_CLOCK_APB_APBB: + bus_divider = PM->APBBSEL.reg; + break; + case SYSTEM_CLOCK_APB_APBC: + bus_divider = PM->APBCSEL.reg; + break; + default: + Assert(false); + return 0; + } + + return (system_gclk_gen_get_hz(GCLK_GENERATOR_0) >> bus_divider); +} + + +/** + * @} + */ + +/** + * \name Bus Clock Masking + * @{ + */ + +/** + * \brief Set bits in the clock mask for the AHB bus. + * + * This function will set bits in the clock mask for the AHB bus. + * Any bits set to 1 will enable that clock, 0 bits in the mask + * will be ignored. + * + * \param[in] ahb_mask AHB clock mask to enable + */ +static inline void system_ahb_clock_set_mask( + const uint32_t ahb_mask) +{ + PM->AHBMASK.reg |= ahb_mask; +} + +/** + * \brief Clear bits in the clock mask for the AHB bus. + * + * This function will clear bits in the clock mask for the AHB bus. + * Any bits set to 1 will disable that clock, 0 bits in the mask + * will be ignored. + * + * \param[in] ahb_mask AHB clock mask to disable + */ +static inline void system_ahb_clock_clear_mask( + const uint32_t ahb_mask) +{ + PM->AHBMASK.reg &= ~ahb_mask; +} + +/** + * \brief Set bits in the clock mask for an APBx bus. + * + * This function will set bits in the clock mask for an APBx bus. + * Any bits set to 1 will enable the corresponding module clock, zero bits in + * the mask will be ignored. + * + * \param[in] mask APBx clock mask, a \c SYSTEM_CLOCK_APB_APBx constant from + * the device header files + * \param[in] bus Bus to set clock mask bits for, a mask of \c PM_APBxMASK_* + * constants from the device header files + * + * \returns Status indicating the result of the clock mask change operation. + * + * \retval STATUS_ERR_INVALID_ARG Invalid bus given + * \retval STATUS_OK The clock mask was set successfully + */ +static inline enum status_code system_apb_clock_set_mask( + const enum system_clock_apb_bus bus, + const uint32_t mask) +{ + switch (bus) { + case SYSTEM_CLOCK_APB_APBA: + PM->APBAMASK.reg |= mask; + break; + + case SYSTEM_CLOCK_APB_APBB: + PM->APBBMASK.reg |= mask; + break; + + case SYSTEM_CLOCK_APB_APBC: + PM->APBCMASK.reg |= mask; + break; + + default: + Assert(false); + return STATUS_ERR_INVALID_ARG; + + } + + return STATUS_OK; +} + +/** + * \brief Clear bits in the clock mask for an APBx bus. + * + * This function will clear bits in the clock mask for an APBx bus. + * Any bits set to 1 will disable the corresponding module clock, zero bits in + * the mask will be ignored. + * + * \param[in] mask APBx clock mask, a \c SYSTEM_CLOCK_APB_APBx constant from + * the device header files + * \param[in] bus Bus to clear clock mask bits + * + * \returns Status indicating the result of the clock mask change operation. + * + * \retval STATUS_ERR_INVALID_ARG Invalid bus ID was given + * \retval STATUS_OK The clock mask was changed successfully + */ +static inline enum status_code system_apb_clock_clear_mask( + const enum system_clock_apb_bus bus, + const uint32_t mask) +{ + switch (bus) { + case SYSTEM_CLOCK_APB_APBA: + PM->APBAMASK.reg &= ~mask; + break; + + case SYSTEM_CLOCK_APB_APBB: + PM->APBBMASK.reg &= ~mask; + break; + + case SYSTEM_CLOCK_APB_APBC: + PM->APBCMASK.reg &= ~mask; + break; + + default: + Assert(false); + return STATUS_ERR_INVALID_ARG; + } + + return STATUS_OK; +} + +/** + * @} + */ + +#ifdef FEATURE_SYSTEM_CLOCK_DPLL +/** + * \brief Reference clock source of the DPLL module. + */ +enum system_clock_source_dpll_reference_clock { + /** Select XOSC32K as clock reference. */ + SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_XOSC32K, + /** Select XOSC as clock reference. */ + SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_XOSC, + /** Select GCLK as clock reference. */ + SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_GCLK, +}; + +/** + * \brief Lock time-out value of the DPLL module. + */ +enum system_clock_source_dpll_lock_time { + /** Set no time-out as default. */ + SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_DEFAULT, + /** Set time-out if no lock within 8ms. */ + SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_8MS = 0x04, + /** Set time-out if no lock within 9ms. */ + SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_9MS, + /** Set time-out if no lock within 10ms. */ + SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_10MS, + /** Set time-out if no lock within 11ms. */ + SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_11MS, +}; + +/** + * \brief Filter type of the DPLL module. + */ +enum system_clock_source_dpll_filter { + /** Default filter mode. */ + SYSTEM_CLOCK_SOURCE_DPLL_FILTER_DEFAULT, + /** Low bandwidth filter. */ + SYSTEM_CLOCK_SOURCE_DPLL_FILTER_LOW_BANDWIDTH_FILTER, + /** High bandwidth filter. */ + SYSTEM_CLOCK_SOURCE_DPLL_FILTER_HIGH_BANDWIDTH_FILTER, + /** High damping filter. */ + SYSTEM_CLOCK_SOURCE_DPLL_FILTER_HIGH_DAMPING_FILTER, +}; + +/** + * \brief Configuration structure for DPLL. + * + * DPLL oscillator configuration structure. + */ +struct system_clock_source_dpll_config { + /** Run On Demand. If this is set the DPLL won't run + * until requested by a peripheral. */ + bool on_demand; + /** Keep the DPLL enabled in standby sleep mode. */ + bool run_in_standby; + /** Bypass lock signal. */ + bool lock_bypass; + /** Wake up fast. If this is set DPLL output clock is enabled after + * the startup time. */ + bool wake_up_fast; + /** Enable low power mode. */ + bool low_power_enable; + + /** Output frequency of the clock. */ + uint32_t output_frequency; + /** Reference frequency of the clock. */ + uint32_t reference_frequency; + /** Devider of reference clock. */ + uint16_t reference_divider; + + /** Filter type of the DPLL module. */ + enum system_clock_source_dpll_filter filter; + /** Lock time-out value of the DPLL module. */ + enum system_clock_source_dpll_lock_time lock_time; + /** Reference clock source of the DPLL module. */ + enum system_clock_source_dpll_reference_clock reference_clock; +}; + +/** + * \name Internal DPLL Management + * @{ + */ + +/** + * \brief Retrieve the default configuration for DPLL. + * + * Fills a configuration structure with the default configuration for a + * DPLL oscillator module: + * - Run only when requested by peripheral (on demand) + * - Don't run in STANDBY sleep mode + * - Lock bypass disabled + * - Fast wake up disabled + * - Low power mode disabled + * - Output frequency is 48MHz + * - Reference clock frequency is 32768Hz + * - Not divide reference clock + * - Select REF0 as reference clock + * - Set lock time to default mode + * - Use default filter + * + * \param[out] config Configuration structure to fill with default values + */ +static inline void system_clock_source_dpll_get_config_defaults( + struct system_clock_source_dpll_config *const config) +{ + config->on_demand = true; + config->run_in_standby = false; + config->lock_bypass = false; + config->wake_up_fast = false; + config->low_power_enable = false; + + config->output_frequency = 48000000; + config->reference_frequency = 32768; + config->reference_divider = 1; + config->reference_clock = SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_XOSC32K; + + config->lock_time = SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_DEFAULT; + config->filter = SYSTEM_CLOCK_SOURCE_DPLL_FILTER_DEFAULT; +}; + +void system_clock_source_dpll_set_config( + struct system_clock_source_dpll_config *const config); + +/* @} */ +#endif + +/** + * \name System Clock Initialization + * @{ + */ + +void system_clock_init(void); + +/** + * @} + */ + +/** + * \name System Flash Wait States + * @{ + */ + +/** + * \brief Set flash controller wait states. + * + * Will set the number of wait states that are used by the onboard + * flash memory. The number of wait states depend on both device + * supply voltage and CPU speed. The required number of wait states + * can be found in the electrical characteristics of the device. + * + * \param[in] wait_states Number of wait states to use for internal flash + */ +static inline void system_flash_set_waitstates(uint8_t wait_states) +{ + Assert(NVMCTRL_CTRLB_RWS((uint32_t)wait_states) == + ((uint32_t)wait_states << NVMCTRL_CTRLB_RWS_Pos)); + + NVMCTRL->CTRLB.bit.RWS = wait_states; +} +/** + * @} + */ + +/** + * @} + */ + +/** + * \page asfdoc_sam0_system_clock_extra Extra Information for SYSTEM CLOCK Driver + * + * \section asfdoc_sam0_system_clock_extra_acronyms Acronyms + * Below is a table listing the acronyms used in this module, along with their + * intended meanings. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
AcronymDescription
DFLLDigital Frequency Locked Loop
MUXMultiplexer
OSC32KInternal 32KHz Oscillator
OSC8MInternal 8MHz Oscillator
PLLPhase Locked Loop
OSCOscillator
XOSCExternal Oscillator
XOSC32KExternal 32KHz Oscillator
AHBAdvanced High-performance Bus
APBAdvanced Peripheral Bus
DPLLDigital Phase Locked Loop
+ * + * + * \section asfdoc_sam0_system_clock_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - None + * + * + * \section asfdoc_sam0_system_clock_extra_errata Errata + * + * - This driver implements experimental workaround for errata 9905 + * + * "The DFLL clock must be requested before being configured otherwise a + * write access to a DFLL register can freeze the device." + * This driver will enable and configure the DFLL before the ONDEMAND bit is set. + * + * + * \section asfdoc_sam0_system_clock_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Changelog
+ * \li Corrected OSC32K startup time definitions + * \li Support locking of OSC32K and XOSC32K config register (default: false) + * \li Added DPLL support, functions added: + * \c system_clock_source_dpll_get_config_defaults() and + * \c system_clock_source_dpll_set_config() + * \li Moved gclk channel locking feature out of the config struct + * functions added: + * \c system_gclk_chan_lock(), + * \c system_gclk_chan_is_locked() + * \c system_gclk_chan_is_enabled() and + * \c system_gclk_gen_is_enabled() + *
Fixed \c system_gclk_chan_disable() deadlocking if a channel is enabled + * and configured to a failed/not running clock generator
+ * \li Changed default value for CONF_CLOCK_DFLL_ON_DEMAND from \c true to \c false + * \li Fixed system_flash_set_waitstates() failing with an assertion + * if an odd number of wait states provided + *
+ * \li Updated dfll configuration function to implement workaround for + * errata 9905 in the DFLL module + * \li Updated \c system_clock_init() to reset interrupt flags before + * they are used + * \li Fixed \c system_clock_source_get_hz() to return correcy DFLL + * frequency number + *
\li Fixed \c system_clock_source_is_ready not returning the correct + * state for \c SYSTEM_CLOCK_SOURCE_OSC8M + * \li Renamed the various \c system_clock_source_*_get_default_config() + * functions to \c system_clock_source_*_get_config_defaults() to + * match the remainder of ASF + * \li Added OSC8M calibration constant loading from the device signature + * row when the oscillator is initialized + * \li Updated default configuration of the XOSC32 to disable Automatic + * Gain Control due to silicon errata + *
Initial Release
+ */ + +/** + * \page asfdoc_sam0_system_clock_exqsg Examples for System Clock Driver + * + * This is a list of the available Quick Start guides (QSGs) and example + * applications for \ref asfdoc_sam0_system_clock_group. QSGs are simple + * examples with step-by-step instructions to configure and use this driver in + * a selection of use cases. Note that QSGs can be compiled as a standalone + * application or be added to the user application. + * + * - \subpage asfdoc_sam0_system_clock_basic_use_case + * - \subpage asfdoc_sam0_system_gclk_basic_use_case + * + * \page asfdoc_sam0_system_clock_document_revision_history Document Revision History + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Doc. Rev. + * Date + * Comments + *
E04/2015Added support for SAMDAx.
D12/2014Added support for SAMR21 and SAMD10/D11.
C01/2014Added support for SAMD21.
B06/2013Corrected documentation typos. Fixed missing steps in the Basic + * Use Case Quick Start Guide.
A06/2013Initial release
+ */ + +#ifdef __cplusplus +} +#endif + +#endif /* SYSTEM_CLOCK_FEATURE_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/compiler.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/compiler.h new file mode 100644 index 0000000..2d95f97 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/compiler.h @@ -0,0 +1,1157 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef UTILS_COMPILER_H_INCLUDED +#define UTILS_COMPILER_H_INCLUDED + +/** + * \defgroup group_sam0_utils Compiler abstraction layer and code utilities + * + * Compiler abstraction layer and code utilities for Cortex-M0+ based Atmel SAM devices. + * This module provides various abstraction layers and utilities to make code compatible between different compilers. + * + * @{ + */ + +#if (defined __ICCARM__) +# include +#endif + +#include +//#include +#include "status_codes.h" +#include "preprocessor/preprocessor.h" +#include + +#ifndef __ASSEMBLY__ + +#include +#include +#include +#include + +/** + * \def UNUSED + * \brief Marking \a v as a unused parameter or value. + */ +#define UNUSED(v) (void)(v) + +/** + * \def barrier + * \brief Memory barrier + */ +#ifdef __GNUC__ +# define barrier() asm volatile("" ::: "memory") +#else +# define barrier() asm ("") +#endif + +/** + * \brief Emit the compiler pragma \a arg. + * + * \param[in] arg The pragma directive as it would appear after \e \#pragma + * (i.e. not stringified). + */ +#define COMPILER_PRAGMA(arg) _Pragma(#arg) + +/** + * \def COMPILER_PACK_SET(alignment) + * \brief Set maximum alignment for subsequent struct and union definitions to \a alignment. + */ +#define COMPILER_PACK_SET(alignment) COMPILER_PRAGMA(pack(alignment)) + +/** + * \def COMPILER_PACK_RESET() + * \brief Set default alignment for subsequent struct and union definitions. + */ +#define COMPILER_PACK_RESET() COMPILER_PRAGMA(pack()) + + +/** + * \brief Set aligned boundary. + */ +#if (defined __GNUC__) || (defined __CC_ARM) +# define COMPILER_ALIGNED(a) __attribute__((__aligned__(a))) +#elif (defined __ICCARM__) +# define COMPILER_ALIGNED(a) COMPILER_PRAGMA(data_alignment = a) +#endif + +/** + * \brief Set word-aligned boundary. + */ +#if (defined __GNUC__) || defined(__CC_ARM) +#define COMPILER_WORD_ALIGNED __attribute__((__aligned__(4))) +#elif (defined __ICCARM__) +#define COMPILER_WORD_ALIGNED COMPILER_PRAGMA(data_alignment = 4) +#endif + +/** + * \def __always_inline + * \brief The function should always be inlined. + * + * This annotation instructs the compiler to ignore its inlining + * heuristics and inline the function no matter how big it thinks it + * becomes. + */ +#if defined(__CC_ARM) +# define __always_inline __forceinline +#elif (defined __GNUC__) +# define __always_inline __attribute__((__always_inline__)) +#elif (defined __ICCARM__) +# define __always_inline _Pragma("inline=forced") +#endif + +/** + * \def __no_inline + * \brief The function should never be inlined + * + * This annotation instructs the compiler to ignore its inlining + * heuristics and not inline the function no matter how small it thinks it + * becomes. + */ +#if defined(__CC_ARM) +# define __no_inline __attribute__((noinline)) +#elif (defined __GNUC__) +# define __no_inline __attribute__((noinline)) +#elif (defined __ICCARM__) +# define __no_inline _Pragma("inline=never") +#endif + + +/** \brief This macro is used to test fatal errors. + * + * The macro tests if the expression is false. If it is, a fatal error is + * detected and the application hangs up. If \c TEST_SUITE_DEFINE_ASSERT_MACRO + * is defined, a unit test version of the macro is used, to allow execution + * of further tests after a false expression. + * + * \param[in] expr Expression to evaluate and supposed to be nonzero. + */ +#if defined(_ASSERT_ENABLE_) +# if defined(TEST_SUITE_DEFINE_ASSERT_MACRO) +# include "unit_test/suite.h" +# else +# undef TEST_SUITE_DEFINE_ASSERT_MACRO +# define Assert(expr) \ + {\ + if (!(expr)) asm("BKPT #0");\ + } +# endif +#else +# define Assert(expr) ((void) 0) +#endif + +/* Define WEAK attribute */ +#if defined ( __CC_ARM ) +# define WEAK __attribute__ ((weak)) +#elif defined ( __ICCARM__ ) +# define WEAK __weak +#elif defined ( __GNUC__ ) +# define WEAK __attribute__ ((weak)) +#endif + +/* Define NO_INIT attribute */ +#if defined ( __CC_ARM ) +# define NO_INIT __attribute__((zero_init)) +#elif defined ( __ICCARM__ ) +# define NO_INIT __no_init +#elif defined ( __GNUC__ ) +# define NO_INIT __attribute__((section(".no_init"))) +#endif + +#include "interrupt.h" + +/** \name Usual Types + * @{ */ +#ifndef __cplusplus +# if !defined(__bool_true_false_are_defined) +typedef unsigned char bool; +# endif +#endif +typedef uint16_t le16_t; +typedef uint16_t be16_t; +typedef uint32_t le32_t; +typedef uint32_t be32_t; +typedef uint32_t iram_size_t; +/** @} */ + +/** \name Aliasing Aggregate Types + * @{ */ + +/** 16-bit union. */ +typedef union +{ + int16_t s16; + uint16_t u16; + int8_t s8[2]; + uint8_t u8[2]; +} Union16; + +/** 32-bit union. */ +typedef union +{ + int32_t s32; + uint32_t u32; + int16_t s16[2]; + uint16_t u16[2]; + int8_t s8[4]; + uint8_t u8[4]; +} Union32; + +/** 64-bit union. */ +typedef union +{ + int64_t s64; + uint64_t u64; + int32_t s32[2]; + uint32_t u32[2]; + int16_t s16[4]; + uint16_t u16[4]; + int8_t s8[8]; + uint8_t u8[8]; +} Union64; + +/** Union of pointers to 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef union +{ + int64_t *s64ptr; + uint64_t *u64ptr; + int32_t *s32ptr; + uint32_t *u32ptr; + int16_t *s16ptr; + uint16_t *u16ptr; + int8_t *s8ptr; + uint8_t *u8ptr; +} UnionPtr; + +/** Union of pointers to volatile 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef union +{ + volatile int64_t *s64ptr; + volatile uint64_t *u64ptr; + volatile int32_t *s32ptr; + volatile uint32_t *u32ptr; + volatile int16_t *s16ptr; + volatile uint16_t *u16ptr; + volatile int8_t *s8ptr; + volatile uint8_t *u8ptr; +} UnionVPtr; + +/** Union of pointers to constant 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef union +{ + const int64_t *s64ptr; + const uint64_t *u64ptr; + const int32_t *s32ptr; + const uint32_t *u32ptr; + const int16_t *s16ptr; + const uint16_t *u16ptr; + const int8_t *s8ptr; + const uint8_t *u8ptr; +} UnionCPtr; + +/** Union of pointers to constant volatile 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef union +{ + const volatile int64_t *s64ptr; + const volatile uint64_t *u64ptr; + const volatile int32_t *s32ptr; + const volatile uint32_t *u32ptr; + const volatile int16_t *s16ptr; + const volatile uint16_t *u16ptr; + const volatile int8_t *s8ptr; + const volatile uint8_t *u8ptr; +} UnionCVPtr; + +/** Structure of pointers to 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef struct +{ + int64_t *s64ptr; + uint64_t *u64ptr; + int32_t *s32ptr; + uint32_t *u32ptr; + int16_t *s16ptr; + uint16_t *u16ptr; + int8_t *s8ptr; + uint8_t *u8ptr; +} StructPtr; + +/** Structure of pointers to volatile 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef struct +{ + volatile int64_t *s64ptr; + volatile uint64_t *u64ptr; + volatile int32_t *s32ptr; + volatile uint32_t *u32ptr; + volatile int16_t *s16ptr; + volatile uint16_t *u16ptr; + volatile int8_t *s8ptr; + volatile uint8_t *u8ptr; +} StructVPtr; + +/** Structure of pointers to constant 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef struct +{ + const int64_t *s64ptr; + const uint64_t *u64ptr; + const int32_t *s32ptr; + const uint32_t *u32ptr; + const int16_t *s16ptr; + const uint16_t *u16ptr; + const int8_t *s8ptr; + const uint8_t *u8ptr; +} StructCPtr; + +/** Structure of pointers to constant volatile 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef struct +{ + const volatile int64_t *s64ptr; + const volatile uint64_t *u64ptr; + const volatile int32_t *s32ptr; + const volatile uint32_t *u32ptr; + const volatile int16_t *s16ptr; + const volatile uint16_t *u16ptr; + const volatile int8_t *s8ptr; + const volatile uint8_t *u8ptr; +} StructCVPtr; + +/** @} */ + +#endif /* #ifndef __ASSEMBLY__ */ + +/** \name Usual Constants + * @{ */ +#define DISABLE 0 +//#define ENABLE 1 + +#ifndef __cplusplus +# if !defined(__bool_true_false_are_defined) +# define false 0 +# define true 1 +# endif +#endif +/** @} */ + +#ifndef __ASSEMBLY__ + +/** \name Optimization Control + * @{ */ + +/** + * \def likely(exp) + * \brief The expression \a exp is likely to be true + */ +#if !defined(likely) || defined(__DOXYGEN__) +# define likely(exp) (exp) +#endif + +/** + * \def unlikely(exp) + * \brief The expression \a exp is unlikely to be true + */ +#if !defined(unlikely) || defined(__DOXYGEN__) +# define unlikely(exp) (exp) +#endif + +/** + * \def is_constant(exp) + * \brief Determine if an expression evaluates to a constant value. + * + * \param[in] exp Any expression + * + * \return true if \a exp is constant, false otherwise. + */ +#if (defined __GNUC__) || (defined __CC_ARM) +# define is_constant(exp) __builtin_constant_p(exp) +#else +# define is_constant(exp) (0) +#endif + +/** @} */ + +/** \name Bit-Field Handling + * @{ */ + +/** \brief Reads the bits of a value specified by a given bit-mask. + * + * \param[in] value Value to read bits from. + * \param[in] mask Bit-mask indicating bits to read. + * + * \return Read bits. + */ +#define Rd_bits( value, mask) ((value) & (mask)) + +/** \brief Writes the bits of a C lvalue specified by a given bit-mask. + * + * \param[in] lvalue C lvalue to write bits to. + * \param[in] mask Bit-mask indicating bits to write. + * \param[in] bits Bits to write. + * + * \return Resulting value with written bits. + */ +#define Wr_bits(lvalue, mask, bits) ((lvalue) = ((lvalue) & ~(mask)) |\ + ((bits ) & (mask))) + +/** \brief Tests the bits of a value specified by a given bit-mask. + * + * \param[in] value Value of which to test bits. + * \param[in] mask Bit-mask indicating bits to test. + * + * \return \c 1 if at least one of the tested bits is set, else \c 0. + */ +#define Tst_bits( value, mask) (Rd_bits(value, mask) != 0) + +/** \brief Clears the bits of a C lvalue specified by a given bit-mask. + * + * \param[in] lvalue C lvalue of which to clear bits. + * \param[in] mask Bit-mask indicating bits to clear. + * + * \return Resulting value with cleared bits. + */ +#define Clr_bits(lvalue, mask) ((lvalue) &= ~(mask)) + +/** \brief Sets the bits of a C lvalue specified by a given bit-mask. + * + * \param[in] lvalue C lvalue of which to set bits. + * \param[in] mask Bit-mask indicating bits to set. + * + * \return Resulting value with set bits. + */ +#define Set_bits(lvalue, mask) ((lvalue) |= (mask)) + +/** \brief Toggles the bits of a C lvalue specified by a given bit-mask. + * + * \param[in] lvalue C lvalue of which to toggle bits. + * \param[in] mask Bit-mask indicating bits to toggle. + * + * \return Resulting value with toggled bits. + */ +#define Tgl_bits(lvalue, mask) ((lvalue) ^= (mask)) + +/** \brief Reads the bit-field of a value specified by a given bit-mask. + * + * \param[in] value Value to read a bit-field from. + * \param[in] mask Bit-mask indicating the bit-field to read. + * + * \return Read bit-field. + */ +#define Rd_bitfield( value, mask) (Rd_bits( value, mask) >> ctz(mask)) + +/** \brief Writes the bit-field of a C lvalue specified by a given bit-mask. + * + * \param[in] lvalue C lvalue to write a bit-field to. + * \param[in] mask Bit-mask indicating the bit-field to write. + * \param[in] bitfield Bit-field to write. + * + * \return Resulting value with written bit-field. + */ +#define Wr_bitfield(lvalue, mask, bitfield) (Wr_bits(lvalue, mask, (uint32_t)(bitfield) << ctz(mask))) + +/** @} */ + + +/** \name Zero-Bit Counting + * + * Under GCC, __builtin_clz and __builtin_ctz behave like macros when + * applied to constant expressions (values known at compile time), so they are + * more optimized than the use of the corresponding assembly instructions and + * they can be used as constant expressions e.g. to initialize objects having + * static storage duration, and like the corresponding assembly instructions + * when applied to non-constant expressions (values unknown at compile time), so + * they are more optimized than an assembly periphrasis. Hence, clz and ctz + * ensure a possible and optimized behavior for both constant and non-constant + * expressions. + * + * @{ */ + +/** \brief Counts the leading zero bits of the given value considered as a 32-bit integer. + * + * \param[in] u Value of which to count the leading zero bits. + * + * \return The count of leading zero bits in \a u. + */ +#if (defined __GNUC__) || (defined __CC_ARM) +# define clz(u) __builtin_clz(u) +#else +# define clz(u) (((u) == 0) ? 32 : \ + ((u) & (1ul << 31)) ? 0 : \ + ((u) & (1ul << 30)) ? 1 : \ + ((u) & (1ul << 29)) ? 2 : \ + ((u) & (1ul << 28)) ? 3 : \ + ((u) & (1ul << 27)) ? 4 : \ + ((u) & (1ul << 26)) ? 5 : \ + ((u) & (1ul << 25)) ? 6 : \ + ((u) & (1ul << 24)) ? 7 : \ + ((u) & (1ul << 23)) ? 8 : \ + ((u) & (1ul << 22)) ? 9 : \ + ((u) & (1ul << 21)) ? 10 : \ + ((u) & (1ul << 20)) ? 11 : \ + ((u) & (1ul << 19)) ? 12 : \ + ((u) & (1ul << 18)) ? 13 : \ + ((u) & (1ul << 17)) ? 14 : \ + ((u) & (1ul << 16)) ? 15 : \ + ((u) & (1ul << 15)) ? 16 : \ + ((u) & (1ul << 14)) ? 17 : \ + ((u) & (1ul << 13)) ? 18 : \ + ((u) & (1ul << 12)) ? 19 : \ + ((u) & (1ul << 11)) ? 20 : \ + ((u) & (1ul << 10)) ? 21 : \ + ((u) & (1ul << 9)) ? 22 : \ + ((u) & (1ul << 8)) ? 23 : \ + ((u) & (1ul << 7)) ? 24 : \ + ((u) & (1ul << 6)) ? 25 : \ + ((u) & (1ul << 5)) ? 26 : \ + ((u) & (1ul << 4)) ? 27 : \ + ((u) & (1ul << 3)) ? 28 : \ + ((u) & (1ul << 2)) ? 29 : \ + ((u) & (1ul << 1)) ? 30 : \ + 31) +#endif + +/** \brief Counts the trailing zero bits of the given value considered as a 32-bit integer. + * + * \param[in] u Value of which to count the trailing zero bits. + * + * \return The count of trailing zero bits in \a u. + */ +#if (defined __GNUC__) || (defined __CC_ARM) +# define ctz(u) __builtin_ctz(u) +#else +# define ctz(u) ((u) & (1ul << 0) ? 0 : \ + (u) & (1ul << 1) ? 1 : \ + (u) & (1ul << 2) ? 2 : \ + (u) & (1ul << 3) ? 3 : \ + (u) & (1ul << 4) ? 4 : \ + (u) & (1ul << 5) ? 5 : \ + (u) & (1ul << 6) ? 6 : \ + (u) & (1ul << 7) ? 7 : \ + (u) & (1ul << 8) ? 8 : \ + (u) & (1ul << 9) ? 9 : \ + (u) & (1ul << 10) ? 10 : \ + (u) & (1ul << 11) ? 11 : \ + (u) & (1ul << 12) ? 12 : \ + (u) & (1ul << 13) ? 13 : \ + (u) & (1ul << 14) ? 14 : \ + (u) & (1ul << 15) ? 15 : \ + (u) & (1ul << 16) ? 16 : \ + (u) & (1ul << 17) ? 17 : \ + (u) & (1ul << 18) ? 18 : \ + (u) & (1ul << 19) ? 19 : \ + (u) & (1ul << 20) ? 20 : \ + (u) & (1ul << 21) ? 21 : \ + (u) & (1ul << 22) ? 22 : \ + (u) & (1ul << 23) ? 23 : \ + (u) & (1ul << 24) ? 24 : \ + (u) & (1ul << 25) ? 25 : \ + (u) & (1ul << 26) ? 26 : \ + (u) & (1ul << 27) ? 27 : \ + (u) & (1ul << 28) ? 28 : \ + (u) & (1ul << 29) ? 29 : \ + (u) & (1ul << 30) ? 30 : \ + (u) & (1ul << 31) ? 31 : \ + 32) +#endif + +/** @} */ + + +/** \name Bit Reversing + * @{ */ + +/** \brief Reverses the bits of \a u8. + * + * \param[in] u8 U8 of which to reverse the bits. + * + * \return Value resulting from \a u8 with reversed bits. + */ +#define bit_reverse8(u8) ((U8)(bit_reverse32((U8)(u8)) >> 24)) + +/** \brief Reverses the bits of \a u16. + * + * \param[in] u16 U16 of which to reverse the bits. + * + * \return Value resulting from \a u16 with reversed bits. + */ +#define bit_reverse16(u16) ((uint16_t)(bit_reverse32((uint16_t)(u16)) >> 16)) + +/** \brief Reverses the bits of \a u32. + * + * \param[in] u32 U32 of which to reverse the bits. + * + * \return Value resulting from \a u32 with reversed bits. + */ +#define bit_reverse32(u32) __RBIT(u32) + +/** \brief Reverses the bits of \a u64. + * + * \param[in] u64 U64 of which to reverse the bits. + * + * \return Value resulting from \a u64 with reversed bits. + */ +#define bit_reverse64(u64) ((uint64_t)(((uint64_t)bit_reverse32((uint64_t)(u64) >> 32)) |\ + ((uint64_t)bit_reverse32((uint64_t)(u64)) << 32))) + +/** @} */ + + +/** \name Alignment + * @{ */ + +/** \brief Tests alignment of the number \a val with the \a n boundary. + * + * \param[in] val Input value. + * \param[in] n Boundary. + * + * \return \c 1 if the number \a val is aligned with the \a n boundary, else \c 0. + */ +#define Test_align(val, n) (!Tst_bits( val, (n) - 1 ) ) + +/** \brief Gets alignment of the number \a val with respect to the \a n boundary. + * + * \param[in] val Input value. + * \param[in] n Boundary. + * + * \return Alignment of the number \a val with respect to the \a n boundary. + */ +#define Get_align(val, n) ( Rd_bits( val, (n) - 1 ) ) + +/** \brief Sets alignment of the lvalue number \a lval to \a alg with respect to the \a n boundary. + * + * \param[in] lval Input/output lvalue. + * \param[in] n Boundary. + * \param[in] alg Alignment. + * + * \return New value of \a lval resulting from its alignment set to \a alg with respect to the \a n boundary. + */ +#define Set_align(lval, n, alg) ( Wr_bits(lval, (n) - 1, alg) ) + +/** \brief Aligns the number \a val with the upper \a n boundary. + * + * \param[in] val Input value. + * \param[in] n Boundary. + * + * \return Value resulting from the number \a val aligned with the upper \a n boundary. + */ +#define Align_up( val, n) (((val) + ((n) - 1)) & ~((n) - 1)) + +/** \brief Aligns the number \a val with the lower \a n boundary. + * + * \param[in] val Input value. + * \param[in] n Boundary. + * + * \return Value resulting from the number \a val aligned with the lower \a n boundary. + */ +#define Align_down(val, n) ( (val) & ~((n) - 1)) + +/** @} */ + + +/** \name Mathematics + * + * The same considerations as for clz and ctz apply here but GCC does not + * provide built-in functions to access the assembly instructions abs, min and + * max and it does not produce them by itself in most cases, so two sets of + * macros are defined here: + * - Abs, Min and Max to apply to constant expressions (values known at + * compile time); + * - abs, min and max to apply to non-constant expressions (values unknown at + * compile time), abs is found in stdlib.h. + * + * @{ */ + +/** \brief Takes the absolute value of \a a. + * + * \param[in] a Input value. + * + * \return Absolute value of \a a. + * + * \note More optimized if only used with values known at compile time. + */ +#define Abs(a) (((a) < 0 ) ? -(a) : (a)) + +/** \brief Takes the minimal value of \a a and \a b. + * + * \param[in] a Input value. + * \param[in] b Input value. + * + * \return Minimal value of \a a and \a b. + * + * \note More optimized if only used with values known at compile time. + */ +#define Min(a, b) (((a) < (b)) ? (a) : (b)) + +/** \brief Takes the maximal value of \a a and \a b. + * + * \param[in] a Input value. + * \param[in] b Input value. + * + * \return Maximal value of \a a and \a b. + * + * \note More optimized if only used with values known at compile time. + */ +#define Max(a, b) (((a) > (b)) ? (a) : (b)) + +/** \brief Takes the minimal value of \a a and \a b. + * + * \param[in] a Input value. + * \param[in] b Input value. + * + * \return Minimal value of \a a and \a b. + * + * \note More optimized if only used with values unknown at compile time. + */ +#define min(a, b) Min(a, b) + +/** \brief Takes the maximal value of \a a and \a b. + * + * \param[in] a Input value. + * \param[in] b Input value. + * + * \return Maximal value of \a a and \a b. + * + * \note More optimized if only used with values unknown at compile time. + */ +#define max(a, b) Max(a, b) + +/** @} */ + + +/** \brief Calls the routine at address \a addr. + * + * It generates a long call opcode. + * + * For example, `Long_call(0x80000000)' generates a software reset on a UC3 if + * it is invoked from the CPU supervisor mode. + * + * \param[in] addr Address of the routine to call. + * + * \note It may be used as a long jump opcode in some special cases. + */ +#define Long_call(addr) ((*(void (*)(void))(addr))()) + + +/** \name MCU Endianism Handling + * ARM is MCU little endian. + * + * @{ */ +#define BE16(x) Swap16(x) +#define LE16(x) (x) + +#define le16_to_cpu(x) (x) +#define cpu_to_le16(x) (x) +#define LE16_TO_CPU(x) (x) +#define CPU_TO_LE16(x) (x) + +#define be16_to_cpu(x) Swap16(x) +#define cpu_to_be16(x) Swap16(x) +#define BE16_TO_CPU(x) Swap16(x) +#define CPU_TO_BE16(x) Swap16(x) + +#define le32_to_cpu(x) (x) +#define cpu_to_le32(x) (x) +#define LE32_TO_CPU(x) (x) +#define CPU_TO_LE32(x) (x) + +#define be32_to_cpu(x) swap32(x) +#define cpu_to_be32(x) swap32(x) +#define BE32_TO_CPU(x) swap32(x) +#define CPU_TO_BE32(x) swap32(x) +/** @} */ + + +/** \name Endianism Conversion + * + * The same considerations as for clz and ctz apply here but GCC's + * __builtin_bswap_32 and __builtin_bswap_64 do not behave like macros when + * applied to constant expressions, so two sets of macros are defined here: + * - Swap16, Swap32 and Swap64 to apply to constant expressions (values known + * at compile time); + * - swap16, swap32 and swap64 to apply to non-constant expressions (values + * unknown at compile time). + * + * @{ */ + +/** \brief Toggles the endianism of \a u16 (by swapping its bytes). + * + * \param[in] u16 U16 of which to toggle the endianism. + * + * \return Value resulting from \a u16 with toggled endianism. + * + * \note More optimized if only used with values known at compile time. + */ +#define Swap16(u16) ((uint16_t)(((uint16_t)(u16) >> 8) |\ + ((uint16_t)(u16) << 8))) + +/** \brief Toggles the endianism of \a u32 (by swapping its bytes). + * + * \param[in] u32 U32 of which to toggle the endianism. + * + * \return Value resulting from \a u32 with toggled endianism. + * + * \note More optimized if only used with values known at compile time. + */ +#define Swap32(u32) ((uint32_t)(((uint32_t)Swap16((uint32_t)(u32) >> 16)) |\ + ((uint32_t)Swap16((uint32_t)(u32)) << 16))) + +/** \brief Toggles the endianism of \a u64 (by swapping its bytes). + * + * \param[in] u64 U64 of which to toggle the endianism. + * + * \return Value resulting from \a u64 with toggled endianism. + * + * \note More optimized if only used with values known at compile time. + */ +#define Swap64(u64) ((uint64_t)(((uint64_t)Swap32((uint64_t)(u64) >> 32)) |\ + ((uint64_t)Swap32((uint64_t)(u64)) << 32))) + +/** \brief Toggles the endianism of \a u16 (by swapping its bytes). + * + * \param[in] u16 U16 of which to toggle the endianism. + * + * \return Value resulting from \a u16 with toggled endianism. + * + * \note More optimized if only used with values unknown at compile time. + */ +#define swap16(u16) Swap16(u16) + +/** \brief Toggles the endianism of \a u32 (by swapping its bytes). + * + * \param[in] u32 U32 of which to toggle the endianism. + * + * \return Value resulting from \a u32 with toggled endianism. + * + * \note More optimized if only used with values unknown at compile time. + */ +#if (defined __GNUC__) +# define swap32(u32) ((uint32_t)__builtin_bswap32((uint32_t)(u32))) +#else +# define swap32(u32) Swap32(u32) +#endif + +/** \brief Toggles the endianism of \a u64 (by swapping its bytes). + * + * \param[in] u64 U64 of which to toggle the endianism. + * + * \return Value resulting from \a u64 with toggled endianism. + * + * \note More optimized if only used with values unknown at compile time. + */ +#if (defined __GNUC__) +# define swap64(u64) ((uint64_t)__builtin_bswap64((uint64_t)(u64))) +#else +# define swap64(u64) ((uint64_t)(((uint64_t)swap32((uint64_t)(u64) >> 32)) |\ + ((uint64_t)swap32((uint64_t)(u64)) << 32))) +#endif + +/** @} */ + + +/** \name Target Abstraction + * + * @{ */ + +#define _GLOBEXT_ extern /**< extern storage-class specifier. */ +#define _CONST_TYPE_ const /**< const type qualifier. */ +#define _MEM_TYPE_SLOW_ /**< Slow memory type. */ +#define _MEM_TYPE_MEDFAST_ /**< Fairly fast memory type. */ +#define _MEM_TYPE_FAST_ /**< Fast memory type. */ + +#define memcmp_ram2ram memcmp /**< Target-specific memcmp of RAM to RAM. */ +#define memcmp_code2ram memcmp /**< Target-specific memcmp of RAM to NVRAM. */ +#define memcpy_ram2ram memcpy /**< Target-specific memcpy from RAM to RAM. */ +#define memcpy_code2ram memcpy /**< Target-specific memcpy from NVRAM to RAM. */ + +/** @} */ + +/** + * \brief Calculate \f$ \left\lceil \frac{a}{b} \right\rceil \f$ using + * integer arithmetic. + * + * \param[in] a An integer + * \param[in] b Another integer + * + * \return (\a a / \a b) rounded up to the nearest integer. + */ +#define div_ceil(a, b) (((a) + (b) - 1) / (b)) + +#endif /* #ifndef __ASSEMBLY__ */ +#ifdef __ICCARM__ +/** \name Compiler Keywords + * + * Port of some keywords from GCC to IAR Embedded Workbench. + * + * @{ */ + +#define __asm__ asm +#define __inline__ inline +#define __volatile__ + +/** @} */ + +#endif + +#define FUNC_PTR void * +/** + * \def unused + * \brief Marking \a v as a unused parameter or value. + */ +#define unused(v) do { (void)(v); } while(0) + +/* Define RAMFUNC attribute */ +#if defined ( __CC_ARM ) /* Keil uVision 4 */ +# define RAMFUNC __attribute__ ((section(".ramfunc"))) +#elif defined ( __ICCARM__ ) /* IAR Ewarm 5.41+ */ +# define RAMFUNC __ramfunc +#elif defined ( __GNUC__ ) /* GCC CS3 2009q3-68 */ +# define RAMFUNC __attribute__ ((section(".ramfunc"))) +#endif + +/* Define OPTIMIZE_HIGH attribute */ +#if defined ( __CC_ARM ) /* Keil uVision 4 */ +# define OPTIMIZE_HIGH _Pragma("O3") +#elif defined ( __ICCARM__ ) /* IAR Ewarm 5.41+ */ +# define OPTIMIZE_HIGH _Pragma("optimize=high") +#elif defined ( __GNUC__ ) /* GCC CS3 2009q3-68 */ +# define OPTIMIZE_HIGH __attribute__((optimize(s))) +#endif +#define PASS 0 +#define FAIL 1 +#define LOW 0 +#define HIGH 1 + +typedef int8_t S8 ; //!< 8-bit signed integer. +typedef uint8_t U8 ; //!< 8-bit unsigned integer. +typedef int16_t S16; //!< 16-bit signed integer. +typedef uint16_t U16; //!< 16-bit unsigned integer. +typedef int32_t S32; //!< 32-bit signed integer. +typedef uint32_t U32; //!< 32-bit unsigned integer. +typedef int64_t S64; //!< 64-bit signed integer. +typedef uint64_t U64; //!< 64-bit unsigned integer. +typedef float F32; //!< 32-bit floating-point number. +typedef double F64; //!< 64-bit floating-point number. + +#define MSB(u16) (((U8 *)&(u16))[1]) //!< Most significant byte of \a u16. +#define LSB(u16) (((U8 *)&(u16))[0]) //!< Least significant byte of \a u16. + +#define MSH(u32) (((U16 *)&(u32))[1]) //!< Most significant half-word of \a u32. +#define LSH(u32) (((U16 *)&(u32))[0]) //!< Least significant half-word of \a u32. +#define MSB0W(u32) (((U8 *)&(u32))[3]) //!< Most significant byte of 1st rank of \a u32. +#define MSB1W(u32) (((U8 *)&(u32))[2]) //!< Most significant byte of 2nd rank of \a u32. +#define MSB2W(u32) (((U8 *)&(u32))[1]) //!< Most significant byte of 3rd rank of \a u32. +#define MSB3W(u32) (((U8 *)&(u32))[0]) //!< Most significant byte of 4th rank of \a u32. +#define LSB3W(u32) MSB0W(u32) //!< Least significant byte of 4th rank of \a u32. +#define LSB2W(u32) MSB1W(u32) //!< Least significant byte of 3rd rank of \a u32. +#define LSB1W(u32) MSB2W(u32) //!< Least significant byte of 2nd rank of \a u32. +#define LSB0W(u32) MSB3W(u32) //!< Least significant byte of 1st rank of \a u32. + +#define MSW(u64) (((U32 *)&(u64))[1]) //!< Most significant word of \a u64. +#define LSW(u64) (((U32 *)&(u64))[0]) //!< Least significant word of \a u64. +#define MSH0(u64) (((U16 *)&(u64))[3]) //!< Most significant half-word of 1st rank of \a u64. +#define MSH1(u64) (((U16 *)&(u64))[2]) //!< Most significant half-word of 2nd rank of \a u64. +#define MSH2(u64) (((U16 *)&(u64))[1]) //!< Most significant half-word of 3rd rank of \a u64. +#define MSH3(u64) (((U16 *)&(u64))[0]) //!< Most significant half-word of 4th rank of \a u64. +#define LSH3(u64) MSH0(u64) //!< Least significant half-word of 4th rank of \a u64. +#define LSH2(u64) MSH1(u64) //!< Least significant half-word of 3rd rank of \a u64. +#define LSH1(u64) MSH2(u64) //!< Least significant half-word of 2nd rank of \a u64. +#define LSH0(u64) MSH3(u64) //!< Least significant half-word of 1st rank of \a u64. +#define MSB0D(u64) (((U8 *)&(u64))[7]) //!< Most significant byte of 1st rank of \a u64. +#define MSB1D(u64) (((U8 *)&(u64))[6]) //!< Most significant byte of 2nd rank of \a u64. +#define MSB2D(u64) (((U8 *)&(u64))[5]) //!< Most significant byte of 3rd rank of \a u64. +#define MSB3D(u64) (((U8 *)&(u64))[4]) //!< Most significant byte of 4th rank of \a u64. +#define MSB4D(u64) (((U8 *)&(u64))[3]) //!< Most significant byte of 5th rank of \a u64. +#define MSB5D(u64) (((U8 *)&(u64))[2]) //!< Most significant byte of 6th rank of \a u64. +#define MSB6D(u64) (((U8 *)&(u64))[1]) //!< Most significant byte of 7th rank of \a u64. +#define MSB7D(u64) (((U8 *)&(u64))[0]) //!< Most significant byte of 8th rank of \a u64. +#define LSB7D(u64) MSB0D(u64) //!< Least significant byte of 8th rank of \a u64. +#define LSB6D(u64) MSB1D(u64) //!< Least significant byte of 7th rank of \a u64. +#define LSB5D(u64) MSB2D(u64) //!< Least significant byte of 6th rank of \a u64. +#define LSB4D(u64) MSB3D(u64) //!< Least significant byte of 5th rank of \a u64. +#define LSB3D(u64) MSB4D(u64) //!< Least significant byte of 4th rank of \a u64. +#define LSB2D(u64) MSB5D(u64) //!< Least significant byte of 3rd rank of \a u64. +#define LSB1D(u64) MSB6D(u64) //!< Least significant byte of 2nd rank of \a u64. +#define LSB0D(u64) MSB7D(u64) //!< Least significant byte of 1st rank of \a u64. + +#define LSB0(u32) LSB0W(u32) //!< Least significant byte of 1st rank of \a u32. +#define LSB1(u32) LSB1W(u32) //!< Least significant byte of 2nd rank of \a u32. +#define LSB2(u32) LSB2W(u32) //!< Least significant byte of 3rd rank of \a u32. +#define LSB3(u32) LSB3W(u32) //!< Least significant byte of 4th rank of \a u32. +#define MSB3(u32) MSB3W(u32) //!< Most significant byte of 4th rank of \a u32. +#define MSB2(u32) MSB2W(u32) //!< Most significant byte of 3rd rank of \a u32. +#define MSB1(u32) MSB1W(u32) //!< Most significant byte of 2nd rank of \a u32. +#define MSB0(u32) MSB0W(u32) //!< Most significant byte of 1st rank of \a u32. + +#if defined(__ICCARM__) +#define SHORTENUM __packed +#elif defined(__GNUC__) +#define SHORTENUM __attribute__((packed)) +#endif + +/* No operation */ +#if defined(__ICCARM__) +#define nop() __no_operation() +#elif defined(__GNUC__) +#define nop() (__NOP()) +#endif + +#define FLASH_DECLARE(x) const x +#define FLASH_EXTERN(x) extern const x +#define PGM_READ_BYTE(x) *(x) +#define PGM_READ_WORD(x) *(x) +#define MEMCPY_ENDIAN memcpy +#define PGM_READ_BLOCK(dst, src, len) memcpy((dst), (src), (len)) + +/*Defines the Flash Storage for the request and response of MAC*/ +#define CMD_ID_OCTET (0) + +/* Converting of values from CPU endian to little endian. */ +#define CPU_ENDIAN_TO_LE16(x) (x) +#define CPU_ENDIAN_TO_LE32(x) (x) +#define CPU_ENDIAN_TO_LE64(x) (x) + +/* Converting of values from little endian to CPU endian. */ +#define LE16_TO_CPU_ENDIAN(x) (x) +#define LE32_TO_CPU_ENDIAN(x) (x) +#define LE64_TO_CPU_ENDIAN(x) (x) + +/* Converting of constants from little endian to CPU endian. */ +#define CLE16_TO_CPU_ENDIAN(x) (x) +#define CLE32_TO_CPU_ENDIAN(x) (x) +#define CLE64_TO_CPU_ENDIAN(x) (x) + +/* Converting of constants from CPU endian to little endian. */ +#define CCPU_ENDIAN_TO_LE16(x) (x) +#define CCPU_ENDIAN_TO_LE32(x) (x) +#define CCPU_ENDIAN_TO_LE64(x) (x) + +#define ADDR_COPY_DST_SRC_16(dst, src) ((dst) = (src)) +#define ADDR_COPY_DST_SRC_64(dst, src) ((dst) = (src)) + +/** + * @brief Converts a 64-Bit value into a 8 Byte array + * + * @param[in] value 64-Bit value + * @param[out] data Pointer to the 8 Byte array to be updated with 64-Bit value + * @ingroup apiPalApi + */ +static inline void convert_64_bit_to_byte_array(uint64_t value, uint8_t *data) +{ + uint8_t index = 0; + + while (index < 8) + { + data[index++] = value & 0xFF; + value = value >> 8; + } +} + +/** + * @brief Converts a 16-Bit value into a 2 Byte array + * + * @param[in] value 16-Bit value + * @param[out] data Pointer to the 2 Byte array to be updated with 16-Bit value + * @ingroup apiPalApi + */ +static inline void convert_16_bit_to_byte_array(uint16_t value, uint8_t *data) +{ + data[0] = value & 0xFF; + data[1] = (value >> 8) & 0xFF; +} + +/* Converts a 16-Bit value into a 2 Byte array */ +static inline void convert_spec_16_bit_to_byte_array(uint16_t value, uint8_t *data) +{ + data[0] = value & 0xFF; + data[1] = (value >> 8) & 0xFF; +} + +/* Converts a 16-Bit value into a 2 Byte array */ +static inline void convert_16_bit_to_byte_address(uint16_t value, uint8_t *data) +{ + data[0] = value & 0xFF; + data[1] = (value >> 8) & 0xFF; +} + +/* + * @brief Converts a 2 Byte array into a 16-Bit value + * + * @param data Specifies the pointer to the 2 Byte array + * + * @return 16-Bit value + * @ingroup apiPalApi + */ +static inline uint16_t convert_byte_array_to_16_bit(uint8_t *data) +{ + return (data[0] | ((uint16_t)data[1] << 8)); +} + +/* Converts a 4 Byte array into a 32-Bit value */ +static inline uint32_t convert_byte_array_to_32_bit(uint8_t *data) +{ + union + { + uint32_t u32; + uint8_t u8[4]; + }long_addr; + uint8_t index; + for (index = 0; index < 4; index++) + { + long_addr.u8[index] = *data++; + } + return long_addr.u32; +} + +/** + * @brief Converts a 8 Byte array into a 64-Bit value + * + * @param data Specifies the pointer to the 8 Byte array + * + * @return 64-Bit value + * @ingroup apiPalApi + */ +static inline uint64_t convert_byte_array_to_64_bit(uint8_t *data) +{ + union + { + uint64_t u64; + uint8_t u8[8]; + } long_addr; + + uint8_t index; + + for (index = 0; index < 8; index++) + { + long_addr.u8[index] = *data++; + } + + return long_addr.u64; +} + +/** @} */ + +#endif /* UTILS_COMPILER_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/gclk.c b/feather_sensor_transmit/libraries/Adafruit_ASFcore/gclk.c new file mode 100644 index 0000000..1199a19 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/gclk.c @@ -0,0 +1,522 @@ +/** + * \file + * + * \brief SAM D21/R21/DA0/DA1 Generic Clock Driver + * + * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#include +#include +#include + +/** + * \brief Determines if the hardware module(s) are currently synchronizing to the bus. + * + * Checks to see if the underlying hardware peripheral module(s) are currently + * synchronizing across multiple clock domains to the hardware bus, This + * function can be used to delay further operations on a module until such time + * that it is ready, to prevent blocking delays for synchronization in the + * user application. + * + * \return Synchronization status of the underlying hardware module(s). + * + * \retval false if the module has completed synchronization + * \retval true if the module synchronization is ongoing + */ +static inline bool system_gclk_is_syncing(void) +{ + if (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY){ + return true; + } + + return false; +} + +/** + * \brief Initializes the GCLK driver. + * + * Initializes the Generic Clock module, disabling and resetting all active + * Generic Clock Generators and Channels to their power-on default values. + */ +void system_gclk_init(void) +{ + /* Turn on the digital interface clock */ + system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBA, PM_APBAMASK_GCLK); + + /* Software reset the module to ensure it is re-initialized correctly */ + GCLK->CTRL.reg = GCLK_CTRL_SWRST; + while (GCLK->CTRL.reg & GCLK_CTRL_SWRST) { + /* Wait for reset to complete */ + } +} + +/** + * \brief Writes a Generic Clock Generator configuration to the hardware module. + * + * Writes out a given configuration of a Generic Clock Generator configuration + * to the hardware module. + * + * \note Changing the clock source on the fly (on a running + * generator) can take additional time if the clock source is configured + * to only run on-demand (ONDEMAND bit is set) and it is not currently + * running (no peripheral is requesting the clock source). In this case + * the GCLK will request the new clock while still keeping a request to + * the old clock source until the new clock source is ready. + * + * \note This function will not start a generator that is not already running; + * to start the generator, call \ref system_gclk_gen_enable() + * after configuring a generator. + * + * \param[in] generator Generic Clock Generator index to configure + * \param[in] config Configuration settings for the generator + */ +void system_gclk_gen_set_config( + const uint8_t generator, + struct system_gclk_gen_config *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Cache new register configurations to minimize sync requirements. */ + uint32_t new_genctrl_config = (generator << GCLK_GENCTRL_ID_Pos); + uint32_t new_gendiv_config = (generator << GCLK_GENDIV_ID_Pos); + + /* Select the requested source clock for the generator */ + new_genctrl_config |= config->source_clock << GCLK_GENCTRL_SRC_Pos; + + /* Configure the clock to be either high or low when disabled */ + if (config->high_when_disabled) { + new_genctrl_config |= GCLK_GENCTRL_OOV; + } + + /* Configure if the clock output to I/O pin should be enabled. */ + if (config->output_enable) { + new_genctrl_config |= GCLK_GENCTRL_OE; + } + + /* Set division factor */ + if (config->division_factor > 1) { + /* Check if division is a power of two */ + if (((config->division_factor & (config->division_factor - 1)) == 0)) { + /* Determine the index of the highest bit set to get the + * division factor that must be loaded into the division + * register */ + + uint32_t div2_count = 0; + + uint32_t mask; + for (mask = (1UL << 1); mask < config->division_factor; + mask <<= 1) { + div2_count++; + } + + /* Set binary divider power of 2 division factor */ + new_gendiv_config |= div2_count << GCLK_GENDIV_DIV_Pos; + new_genctrl_config |= GCLK_GENCTRL_DIVSEL; + } else { + /* Set integer division factor */ + + new_gendiv_config |= + (config->division_factor) << GCLK_GENDIV_DIV_Pos; + + /* Enable non-binary division with increased duty cycle accuracy */ + new_genctrl_config |= GCLK_GENCTRL_IDC; + } + + } + + /* Enable or disable the clock in standby mode */ + if (config->run_in_standby) { + new_genctrl_config |= GCLK_GENCTRL_RUNSTDBY; + } + + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + system_interrupt_enter_critical_section(); + + /* Select the correct generator */ + *((uint8_t*)&GCLK->GENDIV.reg) = generator; + + /* Write the new generator configuration */ + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + GCLK->GENDIV.reg = new_gendiv_config; + + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + GCLK->GENCTRL.reg = new_genctrl_config | (GCLK->GENCTRL.reg & GCLK_GENCTRL_GENEN); + + system_interrupt_leave_critical_section(); +} + +/** + * \brief Enables a Generic Clock Generator that was previously configured. + * + * Starts the clock generation of a Generic Clock Generator that was previously + * configured via a call to \ref system_gclk_gen_set_config(). + * + * \param[in] generator Generic Clock Generator index to enable + */ +void system_gclk_gen_enable( + const uint8_t generator) +{ + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + system_interrupt_enter_critical_section(); + + /* Select the requested generator */ + *((uint8_t*)&GCLK->GENCTRL.reg) = generator; + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + /* Enable generator */ + GCLK->GENCTRL.reg |= GCLK_GENCTRL_GENEN; + + system_interrupt_leave_critical_section(); +} + +/** + * \brief Disables a Generic Clock Generator that was previously enabled. + * + * Stops the clock generation of a Generic Clock Generator that was previously + * started via a call to \ref system_gclk_gen_enable(). + * + * \param[in] generator Generic Clock Generator index to disable + */ +void system_gclk_gen_disable( + const uint8_t generator) +{ + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + system_interrupt_enter_critical_section(); + + /* Select the requested generator */ + *((uint8_t*)&GCLK->GENCTRL.reg) = generator; + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + /* Disable generator */ + GCLK->GENCTRL.reg &= ~GCLK_GENCTRL_GENEN; + while (GCLK->GENCTRL.reg & GCLK_GENCTRL_GENEN) { + /* Wait for clock to become disabled */ + } + + system_interrupt_leave_critical_section(); +} + +/** + * \brief Determins if the specified Generic Clock Generator is enabled. + * + * \param[in] generator Generic Clock Generator index to check + * + * \return The enabled status. + * \retval true The Generic Clock Generator is enabled + * \retval false The Generic Clock Generator is disabled + */ +bool system_gclk_gen_is_enabled( + const uint8_t generator) +{ + bool enabled; + + system_interrupt_enter_critical_section(); + + /* Select the requested generator */ + *((uint8_t*)&GCLK->GENCTRL.reg) = generator; + /* Obtain the enabled status */ + enabled = (GCLK->GENCTRL.reg & GCLK_GENCTRL_GENEN); + + system_interrupt_leave_critical_section(); + + return enabled; +} + +/** + * \brief Retrieves the clock frequency of a Generic Clock generator. + * + * Determines the clock frequency (in Hz) of a specified Generic Clock + * generator, used as a source to a Generic Clock Channel module. + * + * \param[in] generator Generic Clock Generator index + * + * \return The frequency of the generic clock generator, in Hz. + */ +uint32_t system_gclk_gen_get_hz( + const uint8_t generator) +{ + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + system_interrupt_enter_critical_section(); + + /* Select the appropriate generator */ + *((uint8_t*)&GCLK->GENCTRL.reg) = generator; + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + /* Get the frequency of the source connected to the GCLK generator */ + uint32_t gen_input_hz = system_clock_source_get_hz( + (enum system_clock_source)GCLK->GENCTRL.bit.SRC); + + *((uint8_t*)&GCLK->GENCTRL.reg) = generator; + + uint8_t divsel = GCLK->GENCTRL.bit.DIVSEL; + + /* Select the appropriate generator division register */ + *((uint8_t*)&GCLK->GENDIV.reg) = generator; + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + uint32_t divider = GCLK->GENDIV.bit.DIV; + + system_interrupt_leave_critical_section(); + + /* Check if the generator is using fractional or binary division */ + if (!divsel && divider > 1) { + gen_input_hz /= divider; + } else if (divsel) { + gen_input_hz >>= (divider+1); + } + + return gen_input_hz; +} + +/** + * \brief Writes a Generic Clock configuration to the hardware module. + * + * Writes out a given configuration of a Generic Clock configuration to the + * hardware module. If the clock is currently running, it will be stopped. + * + * \note Once called the clock will not be running; to start the clock, + * call \ref system_gclk_chan_enable() after configuring a clock channel. + * + * \param[in] channel Generic Clock channel to configure + * \param[in] config Configuration settings for the clock + * + */ +void system_gclk_chan_set_config( + const uint8_t channel, + struct system_gclk_chan_config *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Cache the new config to reduce sync requirements */ + uint32_t new_clkctrl_config = (channel << GCLK_CLKCTRL_ID_Pos); + + /* Select the desired generic clock generator */ + new_clkctrl_config |= config->source_generator << GCLK_CLKCTRL_GEN_Pos; + + /* Disable generic clock channel */ + system_gclk_chan_disable(channel); + + /* Write the new configuration */ + GCLK->CLKCTRL.reg = new_clkctrl_config; +} + +/** + * \brief Enables a Generic Clock that was previously configured. + * + * Starts the clock generation of a Generic Clock that was previously + * configured via a call to \ref system_gclk_chan_set_config(). + * + * \param[in] channel Generic Clock channel to enable + */ +void system_gclk_chan_enable( + const uint8_t channel) +{ + system_interrupt_enter_critical_section(); + + /* Select the requested generator channel */ + *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; + + /* Enable the generic clock */ + GCLK->CLKCTRL.reg |= GCLK_CLKCTRL_CLKEN; + + system_interrupt_leave_critical_section(); +} + +/** + * \brief Disables a Generic Clock that was previously enabled. + * + * Stops the clock generation of a Generic Clock that was previously started + * via a call to \ref system_gclk_chan_enable(). + * + * \param[in] channel Generic Clock channel to disable + */ +void system_gclk_chan_disable( + const uint8_t channel) +{ + system_interrupt_enter_critical_section(); + + /* Select the requested generator channel */ + *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; + + /* Sanity check WRTLOCK */ + Assert(!GCLK->CLKCTRL.bit.WRTLOCK); + + /* Switch to known-working source so that the channel can be disabled */ + uint32_t prev_gen_id = GCLK->CLKCTRL.bit.GEN; + GCLK->CLKCTRL.bit.GEN = 0; + + /* Disable the generic clock */ + GCLK->CLKCTRL.reg &= ~GCLK_CLKCTRL_CLKEN; + while (GCLK->CLKCTRL.reg & GCLK_CLKCTRL_CLKEN) { + /* Wait for clock to become disabled */ + } + + /* Restore previous configured clock generator */ + GCLK->CLKCTRL.bit.GEN = prev_gen_id; + + system_interrupt_leave_critical_section(); +} + +/** + * \brief Determins if the specified Generic Clock channel is enabled. + * + * \param[in] channel Generic Clock Channel index + * + * \return The enabled status. + * \retval true The Generic Clock channel is enabled + * \retval false The Generic Clock channel is disabled + */ +bool system_gclk_chan_is_enabled( + const uint8_t channel) +{ + bool enabled; + + system_interrupt_enter_critical_section(); + + /* Select the requested generic clock channel */ + *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; + enabled = GCLK->CLKCTRL.bit.CLKEN; + + system_interrupt_leave_critical_section(); + + return enabled; +} + +/** + * \brief Locks a Generic Clock channel from further configuration writes. + * + * Locks a generic clock channel from further configuration writes. It is only + * possible to unlock the channel configuration through a power on reset. + * + * \param[in] channel Generic Clock channel to enable + */ +void system_gclk_chan_lock( + const uint8_t channel) +{ + system_interrupt_enter_critical_section(); + + /* Select the requested generator channel */ + *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; + + /* Lock the generic clock */ + GCLK->CLKCTRL.reg |= GCLK_CLKCTRL_WRTLOCK; + + system_interrupt_leave_critical_section(); +} + +/** + * \brief Determins if the specified Generic Clock channel is locked. + * + * \param[in] channel Generic Clock Channel index + * + * \return The lock status. + * \retval true The Generic Clock channel is locked + * \retval false The Generic Clock channel is not locked + */ +bool system_gclk_chan_is_locked( + const uint8_t channel) +{ + bool locked; + + system_interrupt_enter_critical_section(); + + /* Select the requested generic clock channel */ + *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; + locked = GCLK->CLKCTRL.bit.WRTLOCK; + + system_interrupt_leave_critical_section(); + + return locked; +} + +/** + * \brief Retrieves the clock frequency of a Generic Clock channel. + * + * Determines the clock frequency (in Hz) of a specified Generic Clock + * channel, used as a source to a device peripheral module. + * + * \param[in] channel Generic Clock Channel index + * + * \return The frequency of the generic clock channel, in Hz. + */ +uint32_t system_gclk_chan_get_hz( + const uint8_t channel) +{ + uint8_t gen_id; + + system_interrupt_enter_critical_section(); + + /* Select the requested generic clock channel */ + *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; + gen_id = GCLK->CLKCTRL.bit.GEN; + + system_interrupt_leave_critical_section(); + + /* Return the clock speed of the associated GCLK generator */ + return system_gclk_gen_get_hz(gen_id); +} diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/gclk.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/gclk.h new file mode 100644 index 0000000..1e3caf3 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/gclk.h @@ -0,0 +1,307 @@ +/** + * \file + * + * \brief SAM Generic Clock Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef SYSTEM_CLOCK_GCLK_H_INCLUDED +#define SYSTEM_CLOCK_GCLK_H_INCLUDED + +/** + * \addtogroup asfdoc_sam0_system_clock_group + * + * @{ + */ + +#include "compiler.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief List of available GCLK generators. + * + * List of Available GCLK generators. This enum is used in the peripheral + * device drivers to select the GCLK generator to be used for its operation. + * + * The number of GCLK generators available is device dependent. + */ +enum gclk_generator { + /** GCLK generator channel 0 */ + GCLK_GENERATOR_0, +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 0) + /** GCLK generator channel 1 */ + GCLK_GENERATOR_1, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 1) + /** GCLK generator channel 2 */ + GCLK_GENERATOR_2, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 2) + /** GCLK generator channel 3 */ + GCLK_GENERATOR_3, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 3) + /** GCLK generator channel 4 */ + GCLK_GENERATOR_4, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 4) + /** GCLK generator channel 5 */ + GCLK_GENERATOR_5, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 5) + /** GCLK generator channel 6 */ + GCLK_GENERATOR_6, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 6) + /** GCLK generator channel 7 */ + GCLK_GENERATOR_7, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 7) + /** GCLK generator channel 8 */ + GCLK_GENERATOR_8, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 8) + /** GCLK generator channel 9 */ + GCLK_GENERATOR_9, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 9) + /** GCLK generator channel 10 */ + GCLK_GENERATOR_10, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 10) + /** GCLK generator channel 11 */ + GCLK_GENERATOR_11, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 11) + /** GCLK generator channel 12 */ + GCLK_GENERATOR_12, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 12) + /** GCLK generator channel 13 */ + GCLK_GENERATOR_13, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 13) + /** GCLK generator channel 14 */ + GCLK_GENERATOR_14, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 14) + /** GCLK generator channel 15 */ + GCLK_GENERATOR_15, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 15) + /** GCLK generator channel 16 */ + GCLK_GENERATOR_16, +#endif +}; + +/** + * \brief Generic Clock Generator configuration structure. + * + * Configuration structure for a Generic Clock Generator channel. This + * structure should be initialized by the + * \ref system_gclk_gen_get_config_defaults() function before being modified by + * the user application. + */ +struct system_gclk_gen_config { + /** Source clock input channel index, see the \ref system_clock_source */ + uint8_t source_clock; + /** If \c true, the generator output level is high when disabled */ + bool high_when_disabled; + /** Integer division factor of the clock output compared to the input */ + uint32_t division_factor; + /** If \c true, the clock is kept enabled during device standby mode */ + bool run_in_standby; + /** If \c true, enables GCLK generator clock output to a GPIO pin */ + bool output_enable; +}; + +/** + * \brief Generic Clock configuration structure. + * + * Configuration structure for a Generic Clock channel. This structure + * should be initialized by the \ref system_gclk_chan_get_config_defaults() + * function before being modified by the user application. + */ +struct system_gclk_chan_config { + /** Generic Clock Generator source channel */ + enum gclk_generator source_generator; +}; + +/** \name Generic Clock Management + * @{ + */ +void system_gclk_init(void); + +/** @} */ + + +/** + * \name Generic Clock Management (Generators) + * @{ + */ + +/** + * \brief Initializes a Generic Clock Generator configuration structure to defaults. + * + * Initializes a given Generic Clock Generator configuration structure to + * a set of known default values. This function should be called on all + * new instances of these configuration structures before being modified + * by the user application. + * + * The default configuration is: + * \li Clock is generated undivided from the source frequency + * \li Clock generator output is low when the generator is disabled + * \li The input clock is sourced from input clock channel 0 + * \li Clock will be disabled during sleep + * \li The clock output will not be routed to a physical GPIO pin + * + * \param[out] config Configuration structure to initialize to default values + */ +static inline void system_gclk_gen_get_config_defaults( + struct system_gclk_gen_config *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Default configuration values */ + config->division_factor = 1; + config->high_when_disabled = false; +#if SAML21 || SAML22 + config->source_clock = GCLK_SOURCE_OSC16M; +#elif (SAMC20) || (SAMC21) + config->source_clock = GCLK_SOURCE_OSC48M; +#else + config->source_clock = GCLK_SOURCE_OSC8M; +#endif + config->run_in_standby = false; + config->output_enable = false; +} + +void system_gclk_gen_set_config( + const uint8_t generator, + struct system_gclk_gen_config *const config); + +void system_gclk_gen_enable( + const uint8_t generator); + +void system_gclk_gen_disable( + const uint8_t generator); + +bool system_gclk_gen_is_enabled( + const uint8_t generator); + +/** @} */ + + +/** + * \name Generic Clock Management (Channels) + * @{ + */ + +/** + * \brief Initializes a Generic Clock configuration structure to defaults. + * + * Initializes a given Generic Clock configuration structure to a set of + * known default values. This function should be called on all new + * instances of these configuration structures before being modified by the + * user application. + * + * The default configuration is as follows: + * \li Clock is sourced from the Generic Clock Generator channel 0 + * \li Clock configuration will not be write-locked when set + * + * \param[out] config Configuration structure to initialize to default values + */ +static inline void system_gclk_chan_get_config_defaults( + struct system_gclk_chan_config *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Default configuration values */ + config->source_generator = GCLK_GENERATOR_0; +} + +void system_gclk_chan_set_config( + const uint8_t channel, + struct system_gclk_chan_config *const config); + +void system_gclk_chan_enable( + const uint8_t channel); + +void system_gclk_chan_disable( + const uint8_t channel); + +bool system_gclk_chan_is_enabled( + const uint8_t channel); + +void system_gclk_chan_lock( + const uint8_t channel); + +bool system_gclk_chan_is_locked( + const uint8_t channel); + +/** @} */ + + +/** + * \name Generic Clock Frequency Retrieval + * @{ + */ + +uint32_t system_gclk_gen_get_hz( + const uint8_t generator); + +uint32_t system_gclk_chan_get_hz( + const uint8_t channel); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/i2s.c b/feather_sensor_transmit/libraries/Adafruit_ASFcore/i2s.c new file mode 100644 index 0000000..31fe2d9 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/i2s.c @@ -0,0 +1,750 @@ +/** + * \file + * + * \brief SAM I2S - Inter-IC Sound Controller + * + * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#include "i2s.h" + +/** + * \brief Initializes a hardware I2S module instance + * + * Enables the clock and initialize the I2S module. + * + * \param[in,out] module_inst Pointer to the software module instance struct + * \param[in] hw Pointer to the TCC hardware module + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The module was initialized successfully + * \retval STATUS_BUSY Hardware module was busy when the + * initialization procedure was attempted + * \retval STATUS_ERR_DENIED Hardware module was already enabled + */ +enum status_code i2s_init( + struct i2s_module *const module_inst, + I2s *hw) +{ + Assert(module_inst); + Assert(hw); + + /* Enable the user interface clock in the PM */ + system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, PM_APBCMASK_I2S); + + /* Status check */ + uint32_t ctrla; + ctrla = module_inst->hw->CTRLA.reg; + if (ctrla & I2S_CTRLA_ENABLE) { + if (ctrla & (I2S_CTRLA_SEREN1 | + I2S_CTRLA_SEREN0 | I2S_CTRLA_CKEN1 | I2S_CTRLA_CKEN0)) { + return STATUS_BUSY; + } else { + return STATUS_ERR_DENIED; + } + } + + /* Initialize module */ + module_inst->hw = hw; + + /* Initialize serializers */ +#if I2S_CALLBACK_MODE == true + int i, j; + for (i = 0; i < 2; i ++) { + for (j = 0; j < I2S_SERIALIZER_CALLBACK_N; j ++) { + module_inst->serializer[i].callback[j] = NULL; + } + module_inst->serializer[i].registered_callback_mask = 0; + module_inst->serializer[i].enabled_callback_mask = 0; + + module_inst->serializer[i].job_buffer = NULL; + module_inst->serializer[i].job_status = STATUS_OK; + module_inst->serializer[i].requested_words = 0; + module_inst->serializer[i].transferred_words = 0; + + module_inst->serializer[i].mode = I2S_SERIALIZER_RECEIVE; + module_inst->serializer[i].data_size = I2S_DATA_SIZE_32BIT; + } + + _i2s_instances[0] = module_inst; + + system_interrupt_enable(SYSTEM_INTERRUPT_MODULE_I2S); +#endif + + return STATUS_OK; +} + + +/** + * \brief Configure specified I2S clock unit + * + * Enables the clock and initialize the clock unit, based on the given + * configurations. + * + * \param[in,out] module_inst Pointer to the software module instance struct + * \param[in] clock_unit I2S clock unit to initialize and configure + * \param[in] config Pointer to the I2S clock unit configuration + * options struct + * + * \return Status of the configuration procedure. + * + * \retval STATUS_OK The module was initialized successfully + * \retval STATUS_BUSY Hardware module was busy when the + * configuration procedure was attempted + * \retval STATUS_ERR_DENIED Hardware module was already enabled + * \retval STATUS_ERR_INVALID_ARG Invalid divider value or + * MCK direction setting conflict + */ +enum status_code i2s_clock_unit_set_config( + struct i2s_module *const module_inst, + const enum i2s_clock_unit clock_unit, + const struct i2s_clock_unit_config *config) +{ + Assert(module_inst); + Assert(module_inst->hw); + Assert(clock_unit < I2S_CLOCK_UNIT_N); + Assert(config); + + /* Status check */ + uint32_t ctrla, syncbusy; + syncbusy = module_inst->hw->SYNCBUSY.reg; + ctrla = module_inst->hw->CTRLA.reg; + + /* Busy ? */ + if (syncbusy & (I2S_SYNCBUSY_CKEN0 << clock_unit)) { + return STATUS_BUSY; + } + /* Already enabled ? */ + if (ctrla & (I2S_CTRLA_CKEN0 << clock_unit)) { + return STATUS_ERR_DENIED; + } + /* Parameter check */ + if (config->clock.mck_src && config->clock.mck_out_enable) { + return STATUS_ERR_INVALID_ARG; + } + + /* Initialize Clock Unit */ + uint32_t clkctrl = + (config->clock.mck_out_invert ? I2S_CLKCTRL_MCKOUTINV : 0) | + (config->clock.sck_out_invert ? I2S_CLKCTRL_SCKOUTINV : 0) | + (config->frame.frame_sync.invert_out ? I2S_CLKCTRL_FSOUTINV : 0) | + (config->clock.mck_out_enable ? I2S_CLKCTRL_MCKEN : 0) | + (config->clock.mck_src ? I2S_CLKCTRL_MCKSEL : 0) | + (config->clock.sck_src ? I2S_CLKCTRL_SCKSEL : 0) | + (config->frame.frame_sync.invert_use ? I2S_CLKCTRL_FSINV : 0) | + (config->frame.frame_sync.source ? I2S_CLKCTRL_FSSEL : 0) | + (config->frame.data_delay ? I2S_CLKCTRL_BITDELAY : 0); + + uint8_t div_val = config->clock.mck_out_div; + if ((div_val > 0x21) || (div_val == 0)) { + return STATUS_ERR_INVALID_ARG; + } else { + div_val --; + } + clkctrl |= I2S_CLKCTRL_MCKOUTDIV(div_val); + + div_val = config->clock.sck_div; + if ((div_val > 0x21) || (div_val == 0)) { + return STATUS_ERR_INVALID_ARG; + } else { + div_val --; + } + clkctrl |= I2S_CLKCTRL_MCKDIV(div_val); + + uint8_t number_slots = config->frame.number_slots; + if (number_slots > 8) { + return STATUS_ERR_INVALID_ARG; + } else if (number_slots > 0) { + number_slots --; + } + clkctrl |= + I2S_CLKCTRL_NBSLOTS(number_slots) | + I2S_CLKCTRL_FSWIDTH(config->frame.frame_sync.width) | + I2S_CLKCTRL_SLOTSIZE(config->frame.slot_size); + + /* Write clock unit configurations */ + module_inst->hw->CLKCTRL[clock_unit].reg = clkctrl; + + /* Select general clock source */ + const uint8_t i2s_gclk_ids[2] = {I2S_GCLK_ID_0, I2S_GCLK_ID_1}; + struct system_gclk_chan_config gclk_chan_config; + system_gclk_chan_get_config_defaults(&gclk_chan_config); + gclk_chan_config.source_generator = config->clock.gclk_src; + system_gclk_chan_set_config(i2s_gclk_ids[clock_unit], &gclk_chan_config); + system_gclk_chan_enable(i2s_gclk_ids[clock_unit]); + + /* Initialize pins */ + struct system_pinmux_config pin_config; + system_pinmux_get_config_defaults(&pin_config); + if (config->mck_pin.enable) { + pin_config.mux_position = config->mck_pin.mux; + system_pinmux_pin_set_config(config->mck_pin.gpio, &pin_config); + } + if (config->sck_pin.enable) { + pin_config.mux_position = config->sck_pin.mux; + system_pinmux_pin_set_config(config->sck_pin.gpio, &pin_config); + } + if (config->fs_pin.enable) { + pin_config.mux_position = config->fs_pin.mux; + system_pinmux_pin_set_config(config->fs_pin.gpio, &pin_config); + } + + return STATUS_OK; +} + + +/** + * \brief Configure specified I2S serializer + * + * Enables the clock and initialize the serializer, based on the given + * configurations. + * + * \param[in,out] module_inst Pointer to the software module instance struct + * \param[in] serializer I2S serializer to initialize and configure + * \param[in] config Pointer to the I2S serializer configuration + * options struct + * + * \return Status of the configuration procedure. + * + * \retval STATUS_OK The module was initialized successfully + * \retval STATUS_BUSY Hardware module was busy when the + * configuration procedure was attempted + * \retval STATUS_ERR_DENIED Hardware module was already enabled + */ +enum status_code i2s_serializer_set_config( + struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + const struct i2s_serializer_config *config) +{ + Assert(module_inst); + Assert(module_inst->hw); + Assert(serializer < I2S_SERIALIZER_N); + Assert(config); + + /* Status check */ + uint32_t ctrla, syncbusy; + syncbusy = module_inst->hw->SYNCBUSY.reg; + ctrla = module_inst->hw->CTRLA.reg; + + /* Busy ? */ + if (syncbusy & ((I2S_SYNCBUSY_SEREN0 | I2S_SYNCBUSY_DATA0) << serializer)) { + return STATUS_BUSY; + } + /* Already enabled ? */ + if (ctrla & (I2S_CTRLA_CKEN0 << serializer)) { + return STATUS_ERR_DENIED; + } + + /* Initialize Serializer */ + uint32_t serctrl = + (config->loop_back ? I2S_SERCTRL_RXLOOP : 0) | + (config->dma_usage ? I2S_SERCTRL_DMA : 0) | + (config->mono_mode ? I2S_SERCTRL_MONO : 0) | + (config->disable_data_slot[7] ? I2S_SERCTRL_SLOTDIS7 : 0) | + (config->disable_data_slot[6] ? I2S_SERCTRL_SLOTDIS6 : 0) | + (config->disable_data_slot[5] ? I2S_SERCTRL_SLOTDIS5 : 0) | + (config->disable_data_slot[4] ? I2S_SERCTRL_SLOTDIS4 : 0) | + (config->disable_data_slot[3] ? I2S_SERCTRL_SLOTDIS3 : 0) | + (config->disable_data_slot[2] ? I2S_SERCTRL_SLOTDIS2 : 0) | + (config->disable_data_slot[1] ? I2S_SERCTRL_SLOTDIS1 : 0) | + (config->disable_data_slot[0] ? I2S_SERCTRL_SLOTDIS0 : 0) | + (config->transfer_lsb_first ? I2S_SERCTRL_BITREV : 0) | + (config->data_adjust_left_in_word ? I2S_SERCTRL_WORDADJ : 0) | + (config->data_adjust_left_in_slot ? I2S_SERCTRL_SLOTADJ : 0) | + (config->data_padding ? I2S_SERCTRL_TXSAME : 0); + + if (config->clock_unit < I2S_CLOCK_UNIT_N) { + serctrl |= (config->clock_unit ? I2S_SERCTRL_CLKSEL : 0); + } else { + return STATUS_ERR_INVALID_ARG; + } + + serctrl |= + I2S_SERCTRL_SERMODE(config->mode) | + I2S_SERCTRL_TXDEFAULT(config->line_default_state) | + I2S_SERCTRL_DATASIZE(config->data_size) | + I2S_SERCTRL_EXTEND(config->bit_padding); + + /* Write Serializer configuration */ + module_inst->hw->SERCTRL[serializer].reg = serctrl; + + /* Initialize pins */ + struct system_pinmux_config pin_config; + system_pinmux_get_config_defaults(&pin_config); + if (config->data_pin.enable) { + pin_config.mux_position = config->data_pin.mux; + system_pinmux_pin_set_config(config->data_pin.gpio, &pin_config); + } + + /* Save configure */ + module_inst->serializer[serializer].mode = config->mode; + module_inst->serializer[serializer].data_size = config->data_size; + + return STATUS_OK; +} + + + +/** + * \brief Retrieves the current module status. + * + * Retrieves the status of the module, giving overall state information. + * + * \param[in] module_inst Pointer to the I2S software instance struct + * + * \return Bitmask of \c I2S_STATUS_* flags + * + * \retval I2S_STATUS_SYNC_BUSY Module is busy synchronization + * \retval I2S_STATUS_TRANSMIT_UNDERRUN(x) Serializer x (0~1) is underrun + * \retval I2S_STATUS_TRANSMIT_READY(x) Serializer x (0~1) is ready to + * transmit new data word + * \retval I2S_STATUS_RECEIVE_OVERRUN(x) Serializer x (0~1) is overrun + * \retval I2S_STATUS_RECEIVE_READY(x) Serializer x (0~1) has data ready to + * read + */ +uint32_t i2s_get_status( + const struct i2s_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + uint32_t intflag = module_inst->hw->INTFLAG.reg; + uint32_t status; + if (module_inst->hw->SYNCBUSY.reg) { + status = I2S_STATUS_SYNC_BUSY; + } else { + status = 0; + } + if (intflag & I2S_INTFLAG_TXUR0) { + status |= I2S_STATUS_TRANSMIT_UNDERRUN(0); + } + if (intflag & I2S_INTFLAG_TXUR1) { + status |= I2S_STATUS_TRANSMIT_UNDERRUN(1); + } + if ((intflag & I2S_INTFLAG_TXRDY0) && + !module_inst->hw->SYNCBUSY.bit.DATA0) { + status |= I2S_STATUS_TRANSMIT_READY(0); + } + if ((intflag & I2S_INTFLAG_TXRDY1) && + !module_inst->hw->SYNCBUSY.bit.DATA1) { + status |= I2S_STATUS_TRANSMIT_READY(1); + } + if (intflag & I2S_INTFLAG_RXOR0) { + status |= I2S_STATUS_RECEIVE_OVERRUN(0); + } + if (intflag & I2S_INTFLAG_RXOR1) { + status |= I2S_STATUS_RECEIVE_OVERRUN(1); + } + if (intflag & I2S_INTFLAG_RXRDY0) { + status |= I2S_STATUS_RECEIVE_READY(0); + } + if (intflag & I2S_INTFLAG_RXRDY1) { + status |= I2S_STATUS_RECEIVE_READY(1); + } + return status; +} + +/** + * \brief Clears a module status flags. + * + * Clears the given status flags of the module. + * + * \param[in] module_inst Pointer to the I2S software instance struct + * \param[in] status Bitmask of \c I2S_STATUS_* flags to clear + */ +void i2s_clear_status( + const struct i2s_module *const module_inst, + uint32_t status) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + uint32_t intflag = 0; + + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { + intflag = I2S_INTFLAG_TXUR0; + } + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { + intflag = I2S_INTFLAG_TXUR1; + } + if (status & I2S_STATUS_TRANSMIT_READY(0)) { + intflag = I2S_INTFLAG_TXRDY0; + } + if (status & I2S_STATUS_TRANSMIT_READY(1)) { + intflag = I2S_INTFLAG_TXRDY1; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { + intflag = I2S_INTFLAG_RXOR0; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { + intflag = I2S_INTFLAG_RXOR1; + } + if (status & I2S_STATUS_RECEIVE_READY(0)) { + intflag = I2S_INTFLAG_RXRDY0; + } + if (status & I2S_STATUS_RECEIVE_READY(1)) { + intflag = I2S_INTFLAG_RXRDY1; + } + module_inst->hw->INTFLAG.reg = intflag; +} + +/** + * \brief Enable interrupts on status set + * + * Enable the given status interrupt request from the I2S module. + * + * \param[in] module_inst Pointer to the I2S software instance struct + * \param[in] status Status interrupts to enable + * + * \return Status of enable procedure + * + * \retval STATUS_OK Interrupt is enabled successfully + * \retval STATUS_ERR_INVALID_ARG Status with no interrupt is passed + */ +enum status_code i2s_enable_status_interrupt( + struct i2s_module *const module_inst, + uint32_t status) +{ + /* Sanity check arguments */ + Assert(module_inst); + + /* No sync busy interrupt */ + if (status & I2S_STATUS_SYNC_BUSY) { + return STATUS_ERR_INVALID_ARG; + } + Assert(module_inst->hw); + + uint32_t intflag = 0; + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { + intflag = I2S_INTFLAG_TXUR0; + } + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { + intflag = I2S_INTFLAG_TXUR1; + } + if (status & I2S_STATUS_TRANSMIT_READY(0)) { + intflag = I2S_INTFLAG_TXRDY0; + } + if (status & I2S_STATUS_TRANSMIT_READY(1)) { + intflag = I2S_INTFLAG_TXRDY1; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { + intflag = I2S_INTFLAG_RXOR0; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { + intflag = I2S_INTFLAG_RXOR1; + } + if (status & I2S_STATUS_RECEIVE_READY(0)) { + intflag = I2S_INTFLAG_RXRDY0; + } + if (status & I2S_STATUS_RECEIVE_READY(1)) { + intflag = I2S_INTFLAG_RXRDY1; + } + module_inst->hw->INTENSET.reg = intflag; + return STATUS_OK; +} + +/** + * \brief Disable interrupts on status set + * + * Disable the given status interrupt request from the I2S module. + * + * \param[in] module_inst Pointer to the I2S software instance struct + * \param[in] status Status interrupts to disable + */ +void i2s_disable_status_interrupt( + struct i2s_module *const module_inst, + uint32_t status) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + uint32_t intflag = 0; + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { + intflag = I2S_INTFLAG_TXUR0; + } + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { + intflag = I2S_INTFLAG_TXUR1; + } + if (status & I2S_STATUS_TRANSMIT_READY(0)) { + intflag = I2S_INTFLAG_TXRDY0; + } + if (status & I2S_STATUS_TRANSMIT_READY(1)) { + intflag = I2S_INTFLAG_TXRDY1; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { + intflag = I2S_INTFLAG_RXOR0; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { + intflag = I2S_INTFLAG_RXOR1; + } + if (status & I2S_STATUS_RECEIVE_READY(0)) { + intflag = I2S_INTFLAG_RXRDY0; + } + if (status & I2S_STATUS_RECEIVE_READY(1)) { + intflag = I2S_INTFLAG_RXRDY1; + } + module_inst->hw->INTENCLR.reg = intflag; +} + + +/** + * \brief Write buffer to the specified Serializer of I2S module + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The serializer to write to + * \param[in] buffer The data buffer to write + * \param[in] size Number of data words to write + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The data was sent successfully + * \retval STATUS_ERR_DENIED The module or serializer is disabled + * \retval STATUS_ERR_INVALID_ARG An invalid buffer pointer was supplied + */ +enum status_code i2s_serializer_write_buffer_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + void *buffer, uint32_t size) +{ + Assert(module_inst); + Assert(module_inst->hw); + Assert(serializer < I2S_SERIALIZER_N); + Assert(buffer); + + if (size == 0) { + return STATUS_OK; + } + + uint8_t data_size = 1; /* number of bytes */ + struct i2s_serializer_module *data_module = (struct i2s_serializer_module *) + &module_inst->serializer[serializer]; + + /* Check buffer */ + switch(data_module->data_size) { + case I2S_DATA_SIZE_32BIT: + case I2S_DATA_SIZE_24BIT: + case I2S_DATA_SIZE_20BIT: + case I2S_DATA_SIZE_18BIT: + if ((uint32_t)buffer & 0x3) { + return STATUS_ERR_INVALID_ARG; + } + data_size = 4; + break; + case I2S_DATA_SIZE_16BIT: + case I2S_DATA_SIZE_16BIT_COMPACT: + if ((uint32_t)buffer & 0x1) { + return STATUS_ERR_INVALID_ARG; + } + data_size = 2; + break; + default: + break; + } + + /* Check status */ + if (!(module_inst->hw->CTRLA.reg & + (I2S_CTRLA_ENABLE | (I2S_CTRLA_SEREN0 << serializer)))) { + return STATUS_ERR_DENIED; + } + + /* Write */ + uint32_t i; + uint32_t sync_bit = I2S_SYNCBUSY_DATA0 << serializer; + uint32_t ready_bit = I2S_INTFLAG_TXRDY0 << serializer; + if (4 == data_size) { + uint32_t *p32 = (uint32_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Tx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + module_inst->hw->DATA[serializer].reg = p32[i]; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } else if (2 == data_size) { + uint16_t *p16 = (uint16_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Tx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + module_inst->hw->DATA[serializer].reg = p16[i]; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } else { + uint8_t *p8 = (uint8_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Tx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + module_inst->hw->DATA[serializer].reg = p8[i]; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } + + return STATUS_OK; +} + +/** + * \brief Read from the specified Serializer of I2S module to a buffer + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The serializer to write to + * \param[in] buffer The buffer to fill read data (NULL to discard) + * \param[in] size Number of data words to read + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The data was sent successfully + * \retval STATUS_ERR_DENIED The module or serializer is disabled + * \retval STATUS_ERR_INVALID_ARG An invalid buffer pointer was supplied + */ +enum status_code i2s_serializer_read_buffer_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + void *buffer, uint32_t size) +{ + Assert(module_inst); + Assert(module_inst->hw); + + if (size == 0) { + return STATUS_OK; + } + + uint8_t data_size = 1; /* number of bytes */ + struct i2s_serializer_module *data_module = (struct i2s_serializer_module *) + &module_inst->serializer[serializer]; + + /* Check buffer */ + switch(data_module->data_size) { + case I2S_DATA_SIZE_32BIT: + case I2S_DATA_SIZE_24BIT: + case I2S_DATA_SIZE_20BIT: + case I2S_DATA_SIZE_18BIT: + if ((uint32_t)buffer & 0x3) { + return STATUS_ERR_INVALID_ARG; + } + data_size = 4; + break; + case I2S_DATA_SIZE_16BIT: + case I2S_DATA_SIZE_16BIT_COMPACT: + if ((uint32_t)buffer & 0x1) { + return STATUS_ERR_INVALID_ARG; + } + data_size = 2; + break; + default: + break; + } + + /* Check status */ + if (!(module_inst->hw->CTRLA.reg & + (I2S_CTRLA_ENABLE | (I2S_CTRLA_SEREN0 << serializer)))) { + return STATUS_ERR_DENIED; + } + + /* Read */ + uint32_t i; + uint32_t sync_bit = I2S_SYNCBUSY_DATA0 << serializer; + uint32_t ready_bit = I2S_INTFLAG_RXRDY0 << serializer; + if (buffer == NULL) { + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Rx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } + else if (4 == data_size) { + uint32_t *p32 = (uint32_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Rx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + p32[i] = module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } else if (2 == data_size) { + uint16_t *p16 = (uint16_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Rx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + p16[i] = module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } else { + uint8_t *p8 = (uint8_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Tx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + p8[i] = module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } + + return STATUS_OK; +} diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/i2s.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/i2s.h new file mode 100644 index 0000000..9911e6d --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/i2s.h @@ -0,0 +1,1404 @@ +/** + * \file + * + * \brief SAM I2S - Inter-IC Sound Controller + * + * Copyright (c) 2014-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#ifndef I2S_H_INCLUDED +#define I2S_H_INCLUDED + +/** + * \defgroup asfdoc_sam0_i2s_group SAM Inter-IC Sound Controller Driver (I2S) + * + * This driver for Atmel® | SMART SAM devices provides an interface for the configuration + * and management of the device's Inter-IC Sound Controller functionality. + * + * The following driver API modes are covered by this manual: + * - Polled APIs + * \if I2S_CALLBACK_MODE + * - Callback APIs + * \endif + * + * The following peripherals are used by this module: + * - I2S (Inter-IC Sound Controller) + * + * The following devices can use this module: + * - Atmel | SMART SAM D21 + * - Atmel | SMART SAM DA1 + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_i2s_prerequisites + * - \ref asfdoc_sam0_i2s_module_overview + * - \ref asfdoc_sam0_i2s_special_considerations + * - \ref asfdoc_sam0_i2s_extra_info + * - \ref asfdoc_sam0_i2s_examples + * - \ref asfdoc_sam0_i2s_api_overview + * + * \section asfdoc_sam0_i2s_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * \section asfdoc_sam0_i2s_module_overview Module Overview + * + * The I2S provides bidirectional, synchronous, digital audio link with external + * audio devices through these signal pins: + * - Serial Data (SDm) + * - Frame Sync (FSn) + * - Serial Clock (SCKn) + * - Master Clock (MCKn) + * + * The I2S consists of 2 Clock Units and 2 Serializers, which can be separately + * configured and enabled, to provide varies functionalities as follow: + * - Communicate to Audio CODECs as Master or Slave, or provides clock and + * frame sync signals as Controller + * - Communicate to DAC or ADC through dedicated I2S serial interface + * - Communicate to multi-slot or multiple stereo DACs or ADCs, via + * Time Division Multiplexed (TDM) format + * - Reading mono or stereo MEMS microphones, using the Pulse Density + * Modulation (PDM) interface + * + * The I2S supports compact stereo data word, where left channel data bits are + * in lower half and right channel data bits are in upper half. It reduces the + * number of data words for stereo audio data and the DMA bandwidth. + * + * In master mode, the frame is configured by number of slots and slot size, and + * allows range covering 16fs to 1024fs MCK, to provide oversampling clock to an + * external audio CODEC or digital signal processor (DSP). + * + * A block diagram of the I2S can be seen in + * \ref asfdoc_sam0_i2s_module_block_diagram "the figure below". + * + * \anchor asfdoc_sam0_i2s_module_block_diagram + * \image html i2s_blocks.svg "I2S Block Diagram" + * + * This driver for I2S module provides an interface to + * - initialize and control I2S module + * - configure and control the I2S Clock Unit and Serializer + * - transmit/receive data through I2S Serializer + * + * \subsection asfdoc_sam0_i2s_module_overview_clocks Clocks + * + * To use I2S module, the I2S bus interface clock (clk_i2s) must be enabled via + * Power Manager. + * + * For each I2S Clock Unit, a generic clock (gclk_i2s_n) is connnected. When I2S + * works in master mode the generic clock is used. It should be prepared before + * clock unit is used. In master mode the input generic clock will be used as + * MCK for SCKn and FSn generation, in addition, the MCK could be devided and + * output to I2S MCKn pin, as oversampling clock to external audio device. + * + * The I2S Serializer uses clock and control signal from Clock Unit to handle + * transfer. Select different clock unit with different configurations allows + * the I2S to work as master or slave, to work on non-related clocks. + * + * When using the driver with ASF, enabling the register interface is normally + * done by the \c init function. + * The gclk source for the asynchronous domain is normally configured and set + * through the _configuration struct_ / _init_ function. + * If gclk source != 0 is used, this source has to be configured and enabled + * through invoking the system_gclk driver function when needed, or modifying + * conf_clock.h to enable it at the beginning. + * + * \subsection asfdoc_sam0_i2s_module_overview_frame Audio Frame Generation + * + * Audio sample data for all channels are sent in frames, one frame can consist + * 1 - 8 slots where each slot can be configured to a size 8-bit, 16-bit, 24-bit + * or 32-bit. The audio frame synch clock is generated by the I2S Clock unit in + * the master/controller mode. The frame rate (or frame sync frequency) is + * calculated as follow: + * + * FS = SCK / number_of_slots / number_of_bits_in_slot + * + * The serial clock (SCK) source is either an external source (slave mode) or + * generated by the I2S clock unit (controller or master mode) using the MCK as + * source. + * + * SCK = MCK / sck_div + * \note SCK generation division value is MCKDIV in register. + * + * MCK is either an external source or generated using the gclk input from a + * generic clock generator. + * + * \subsection asfdoc_sam0_i2s_module_overview_mode Master, Controller and Slave modes + * + * The i2s module has three modes: master, controller and slave. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_mode_mst Master + * In master mode the module will control the data flow on the i2s bus and can + * be responsible for clock generation. The Serializers are enabled and will + * transmit/receive data. On a bus with only master and slave the SCK and FS + * clock signal will be outputted on the SCK and FS pin on the master module. + * MCK can optionally be outputted on the MCK pin, if there is a controller + * module on the bus the SCK, FS and optionally the MCK clock is sourced from + * the same pins. Serial data will be trancieved on the SD pin in both + * scenarios. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_mode_ctl Controller + * In controller mode the module will generate the clock signals, but the + * Serializers are disabled and no data will be transmitted/received by the + * module in this mode. The clock signals is outputted on the SCK, FS and + * optionally the MCK pin. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_mode_slv Slave + * In slave mode the module will use the SCK and FS clock source from the master + * or the controller which is received on the SCK and FS pin. The MCK can + * optionally be sourced externally on the MCK pin. The Serializers are enabled + * and will tranceive data on the SD pin. All data flow is controlled by the + * master. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_mode_chg Switch modes + * The mode switching between master, controller and slave modes are actually + * done by modifying the source mode of I2S pins. + * The source mode of I2S pins are selected by writing corresponding bits in + * CLKCTRLn. + * Since source mode switching changes the direction of pin, the mode must be + * changed when the I2S Clock Unit is stopped. + * + * \subsection asfdoc_sam0_i2s_module_overview_data Data Stream Reception/Transmission + * + * The I2S module support several data stream formats: + * - I2S format + * - Time Division Multiplexed (TDM) format + * - Pulse Density Modulation (PDM) format (reception only) + * + * Basically the I2S module can send several words within each frame, it's more + * like TDM format. With adjust to the number of data words in a frame, the FS + * width, the FS to data bits delay, etc., the module is able to handle I2S + * compliant data stream. + * + * Also the Serializer can receive PDM format data stream, which allows the I2S + * module receive 1 PDM data on each SCK edge. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_data_i2s I2S Stream Reception/Transmission + * + * For 2-channel I2S compliant data stream format the i2s module uses the FS + * line as word select (WS) signal and will send left channel data word on low + * WS level and right channel data word on high WS level as specified in the I2S + * standard. The supported word sizes are 8-, 16-, 18-, 20-, 24- and 32- bit. + * + * Thus for I2S stream, the following settings should be applied to the module: + * - Data starting delay after FS transition : one SCK period + * - FS width : half of frame + * - Data bits adjust in word : left-adjusted + * - Bit transmitting order : MSB first + * + * Following is an example for I2S application connections and waveforms. See + * \ref asfdoc_sam0_i2s_module_i2s_example_diagram "the figure below". + * + * \anchor asfdoc_sam0_i2s_module_i2s_example_diagram + * \image html i2s_example.svg "I2S Example Diagram" + * + * \subsubsection asfdoc_sam0_i2s_module_overview_data_tdm TDM Stream Reception/Transmission + * In TDM format, the module sends several data words in each frame. For this + * data stream format most of the configurations could be adjusted: + * - Main Frame related settings are as follow: + * - Frame Sync (FS) options: + * - the active edge of the FS (or if FS is inverted before use) + * - the width of the FS + * - the delay between FS to first data bit + * - Data alignment in slot + * - The number of slots and slot size can be adjusted, it has been mentioned + * in \ref asfdoc_sam0_i2s_module_overview_frame + * - The data word size is controlled by Serializer, it can be chosen among + * 8, 16, 18, 20, 24 and 32 bits. + * + * The general TDM waveform generation is as follow: + * + * \anchor asfdoc_sam0_i2s_module_tdm_wave_diagram + * \image html tdm_wave.svg "TDM Waveform generation" + * + * Some other settings could also be found to set up clock, data formatting and + * pin mux. + * refer to \ref i2s_clock_unit_config "Clock Unit Configurations" + * and \ref i2s_serializer_config "Serializer Configurations" for more + * details. + * + * Following is examples for different application use cases. + * + * See \ref asfdoc_sam0_i2s_module_tdm_timeslot_example_diagram "here" for + * the Time Slot Application connection and waveform example. + * + * \anchor asfdoc_sam0_i2s_module_tdm_timeslot_example_diagram + * \image html tdm_timeslot_example.svg "Codec Example Diagram" + * + * See \ref asfdoc_sam0_i2s_module_tdm_codec_example_diagram "here" for the + * Codec Application connection and waveform example. + * + * \anchor asfdoc_sam0_i2s_module_tdm_codec_example_diagram + * \image html tdm_codec_example.svg "Time Slot Example Diagram" + * + * \subsubsection asfdoc_sam0_i2s_module_overview_data_pdm PDM Reception + * The I2S Serializer integrates PDM reception feature, to use this feature, + * simply select PDM2 mode in Serializer configuration. In PDM2 mode, it assumes + * two microphones are input for stereo stream. The left microphone bits will + * be stored in lower half and right microphone bits in upper half of the data + * word, like in compact stereo format. + * + * See \ref asfdoc_sam0_i2s_module_pdm_example_diagram "following figure" for an + * example of PDM Microphones Application with both left and right channel + * microphone connected. + * + * \anchor asfdoc_sam0_i2s_module_pdm_example_diagram + * \image html pdm_example.svg "Time PDM2 Example Diagram" + * + * \subsubsection asfdoc_sam0_i2s_module_overview_data_fmt MONO and Compact Data + * The I2S Serializer can accept some pre-defined data format and generates + * the data stream in specified way. + * + * When transmitting data, the Serializer can work in MONO mode: assum input + * is single channel mono data on left channel and copy it to right channel + * automatically. + * + * Also the I2S Serializer can support compact stereo data word. The data word + * size of the Serializer can be set to \ref I2S_DATA_SIZE_16BIT_COMPACT + * "16-bit compact" or \ref I2S_DATA_SIZE_8BIT_COMPACT "8-bit compact", with + * these option I2S Serializer will compact left channel data and right channel + * data together, the left channel data will take lower bytes and right channel + * data take higher bytes. + * + * \subsection asfdoc_sam0_i2s_module_overview_loop Loop-back Mode + * The I2S can be configured to loop back the Transmitter to Receiver. In this + * mode Serializer's input will be connected to another Serializer's output + * internally. + * + * \subsection asfdoc_sam0_i2s_module_overview_sleep Sleep Modes + * The I2S will continue to operate in any sleep mode, where the selected source + * clocks are running. + * + * \section asfdoc_sam0_i2s_special_considerations Special Considerations + * + * There is no special considerations for I2S module. + * + * \section asfdoc_sam0_i2s_extra_info Extra Information + * + * For extra information see \ref asfdoc_sam0_i2s_extra. This includes: + * - \ref asfdoc_sam0_i2s_extra_acronyms + * - \ref asfdoc_sam0_i2s_extra_dependencies + * - \ref asfdoc_sam0_i2s_extra_errata + * - \ref asfdoc_sam0_i2s_extra_history + * + * \section asfdoc_sam0_i2s_examples Examples + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_i2s_exqsg. + * + * + * \section asfdoc_sam0_i2s_api_overview API Overview + * @{ + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#if I2S_CALLBACK_MODE == true +# include + +#if !defined(__DOXYGEN__) +extern struct i2s_module *_i2s_instances[I2S_INST_NUM]; +#endif + +/** Forward definition of the device instance */ +struct i2s_module; + +/** Type of the callback functions */ +typedef void (*i2s_serializer_callback_t) + (struct i2s_module *const module); + +/** + * \brief I2S Serializer Callback enum + */ +enum i2s_serializer_callback { + /** Callback for buffer read/write finished */ + I2S_SERIALIZER_CALLBACK_BUFFER_DONE, + /** Callback for Serializer overrun/underrun */ + I2S_SERIALIZER_CALLBACK_OVER_UNDER_RUN, +# if !defined(__DOXYGEN__) + I2S_SERIALIZER_CALLBACK_N +# endif +}; + +#endif /* #if I2S_CALLBACK_MODE == true */ + +/** + * \name Module status flags + * + * I2S status flags, returned by \ref i2s_get_status() and cleared by + * \ref i2s_clear_status(). + * + * @{ + */ + +/** Module Serializer x (0~1) Transmit Underrun */ +#define I2S_STATUS_TRANSMIT_UNDERRUN(x) (1u << ((x)+0)) +/** Module Serializer x (0~1) is ready to accept new data to be transmitted */ +#define I2S_STATUS_TRANSMIT_READY(x) (1u << ((x)+2)) +/** Module Serializer x (0~1) Receive Overrun */ +#define I2S_STATUS_RECEIVE_OVERRUN(x) (1u << ((x)+4)) +/** Module Serializer x (0~1) has received a new data */ +#define I2S_STATUS_RECEIVE_READY(x) (1u << ((x)+6)) +/** Module is busy on synchronization */ +#define I2S_STATUS_SYNC_BUSY (1u << 8) + +/** @} */ + +/** + * Master Clock (MCK) source selection + */ +enum i2s_master_clock_source { + /** Master Clock (MCK) is from general clock */ + I2S_MASTER_CLOCK_SOURCE_GCLK, + /** Master Clock (MCK) is from MCK input pin */ + I2S_MASTER_CLOCK_SOURCE_MCKPIN +}; + +/** + * Serial Clock (SCK) source selection + */ +enum i2s_serial_clock_source { + /** Serial Clock (SCK) is divided from Master Clock */ + I2S_SERIAL_CLOCK_SOURCE_MCKDIV, + /** Serial Clock (SCK) is input from SCK input pin */ + I2S_SERIAL_CLOCK_SOURCE_SCKPIN +}; + +/** + * Data delay from Frame Sync (FS) + */ +enum i2s_data_delay { + /** Left Justified (no delay) */ + I2S_DATA_DELAY_0, + /** I2S data delay (1-bit delay) */ + I2S_DATA_DELAY_1, + /** Left Justified (no delay) */ + I2S_DATA_DELAY_LEFT_JUSTIFIED = I2S_DATA_DELAY_0, + /** I2S data delay (1-bit delay) */ + I2S_DATA_DELAY_I2S = I2S_DATA_DELAY_1 +}; + +/** + * Frame Sync (FS) source + */ +enum i2s_frame_sync_source { + /** Frame Sync (FS) is divided from I2S Serial Clock */ + I2S_FRAME_SYNC_SOURCE_SCKDIV, + /** Frame Sync (FS) is input from FS input pin */ + I2S_FRAME_SYNC_SOURCE_FSPIN +}; + +/** + * Frame Sync (FS) output pulse width + */ +enum i2s_frame_sync_width { + /** Frame Sync (FS) Pulse is 1 Slot width */ + I2S_FRAME_SYNC_WIDTH_SLOT, + /** Frame Sync (FS) Pulse is half a Frame width */ + I2S_FRAME_SYNC_WIDTH_HALF_FRAME, + /** Frame Sync (FS) Pulse is 1 Bit width */ + I2S_FRAME_SYNC_WIDTH_BIT, + /** 1-bit wide Frame Sync (FS) per Data sample, only used when Data transfer + * is requested */ + I2S_FRAME_SYNC_WIDTH_BURST +}; + +/** + * Time Slot Size in number of I2S serial clocks (bits) + */ +enum i2s_slot_size { + /** 8-bit slot */ + I2S_SLOT_SIZE_8_BIT, + /** 16-bit slot */ + I2S_SLOT_SIZE_16_BIT, + /** 24-bit slot */ + I2S_SLOT_SIZE_24_BIT, + /** 32-bit slot */ + I2S_SLOT_SIZE_32_BIT +}; + +/** + * DMA channels usage for I2S + */ +enum i2s_dma_usage { + /** Single DMA channel for all I2S channels */ + I2S_DMA_USE_SINGLE_CHANNEL_FOR_ALL, + /** One DMA channel per data channel */ + I2S_DMA_USE_ONE_CHANNEL_PER_DATA_CHANNEL +}; + +/** + * I2S data format, to extend mono data to 2 channels + */ +enum i2s_data_format { + /** Normal mode, keep data to its right channel */ + I2S_DATA_FORMAT_STEREO, + /** Assume input is mono data for left channel, the data is duplicated to + * right channel */ + I2S_DATA_FORMAT_MONO +}; + +/** + * I2S data bit order + */ +enum i2s_bit_order { + /** Transfer Data Most Significant Bit first (Default for I2S protocol) */ + I2S_BIT_ORDER_MSB_FIRST, + /** Transfer Data Least Significant Bit first */ + I2S_BIT_ORDER_LSB_FIRST +}; + +/** + * I2S data bit padding + */ +enum i2s_bit_padding { + /** Padding with 0 */ + I2S_BIT_PADDING_0, + /** Padding with 1 */ + I2S_BIT_PADDING_1, + /** Padding with MSBit */ + I2S_BIT_PADDING_MSB, + /** Padding with LSBit */ + I2S_BIT_PADDING_LSB, +}; + +/** + * I2S data word adjust + */ +enum i2s_data_adjust { + /** Data is right adjusted in word */ + I2S_DATA_ADJUST_RIGHT, + /** Data is left adjusted in word */ + I2S_DATA_ADJUST_LEFT +}; + +/** + * I2S data word size + */ +enum i2s_data_size { + /** 32-bit */ + I2S_DATA_SIZE_32BIT, + /** 24-bit */ + I2S_DATA_SIZE_24BIT, + /** 20-bit */ + I2S_DATA_SIZE_20BIT, + /** 18-bit */ + I2S_DATA_SIZE_18BIT, + /** 16-bit */ + I2S_DATA_SIZE_16BIT, + /** 16-bit compact stereo */ + I2S_DATA_SIZE_16BIT_COMPACT, + /** 8-bit */ + I2S_DATA_SIZE_8BIT, + /** 8-bit compact stereo */ + I2S_DATA_SIZE_8BIT_COMPACT +}; + +/** + * I2S data slot adjust + */ +enum i2s_slot_adjust { + /** Data is right adjusted in slot */ + I2S_SLOT_ADJUST_RIGHT, + /** Data is left adjusted in slot */ + I2S_SLOT_ADJUST_LEFT +}; + +/** + * I2S data padding + */ +enum i2s_data_padding { + /** Padding 0 in case of under-run */ + I2S_DATA_PADDING_0, + /** Padding last data in case of under-run */ + I2S_DATA_PADDING_SAME_AS_LAST, + /** Padding last data in case of under-run + * (abbr. \c I2S_DATA_PADDING_SAME_AS_LAST) */ + I2S_DATA_PADDING_LAST = I2S_DATA_PADDING_SAME_AS_LAST, + /** Padding last data in case of under-run + * (abbr. \c I2S_DATA_PADDING_SAME_AS_LAST) */ + I2S_DATA_PADDING_SAME = I2S_DATA_PADDING_SAME_AS_LAST +}; + +/** + * I2S line default value when slot disabled + */ +enum i2s_line_default_state { + /** Output default value is 0 */ + I2S_LINE_DEFAULT_0, + /** Output default value is 1 */ + I2S_LINE_DEFAULT_1, + /** Output default value is high impedance */ + I2S_LINE_DEFAULT_HIGH_IMPEDANCE = 3, + /** Output default value is high impedance + * (abbr. \c I2S_LINE_DEFAULT_HIGH_IMPEDANCE) */ + I2S_LINE_DEFAULT_HIZ = I2S_LINE_DEFAULT_HIGH_IMPEDANCE +}; + +/** + * I2S Serializer mode + */ +enum i2s_serializer_mode { + /** Serializer is used to receive data */ + I2S_SERIALIZER_RECEIVE, + /** Serializer is used to transmit data */ + I2S_SERIALIZER_TRANSMIT, + /** Serializer is used to receive PDM data on each clock edge */ + I2S_SERIALIZER_PDM2 +}; + +/** + * I2S clock unit selection + */ +enum i2s_clock_unit { + /** Clock Unit channel 0 */ + I2S_CLOCK_UNIT_0, + /** Clock Unit channel 1 */ + I2S_CLOCK_UNIT_1, + /** Number of Clock Unit channels */ + I2S_CLOCK_UNIT_N +}; + +/** + * I2S Serializer selection + */ +enum i2s_serializer { + /** Serializer channel 0 */ + I2S_SERIALIZER_0, + /** Serializer channel 1 */ + I2S_SERIALIZER_1, + /** Number of Serializer channels */ + I2S_SERIALIZER_N +}; + + +/** + * Configure for I2S pin + */ +struct i2s_pin_config { + /** GPIO index to access the pin */ + uint8_t gpio; + /** Pin function MUX */ + uint8_t mux; + /** Enable this pin for I2S module */ + bool enable; +}; + +/** + * Configure for I2S clock (SCK) + */ +struct i2s_clock_config { + /** Divide generic clock to master clock output (1~32, 0,1 means no div) */ + uint8_t mck_out_div; + /** Divide generic clock to serial clock (1~32, 0,1 means no div) */ + uint8_t sck_div; + /** Clock source selection */ + enum gclk_generator gclk_src; + /** Master clock source selection: generated or input from pin */ + enum i2s_master_clock_source mck_src; + /** Serial clock source selection: generated or input from pin */ + enum i2s_serial_clock_source sck_src; + /** Invert master clock output */ + bool mck_out_invert; + /** Invert serial clock output */ + bool sck_out_invert; + /** Generate MCK clock output */ + bool mck_out_enable; +}; + +/** + * Configure fir I2S frame sync (FS) + */ +struct i2s_frame_sync_config { + /** Frame Sync (FS) generated or input from pin */ + enum i2s_frame_sync_source source; + /** Frame Sync (FS) width */ + enum i2s_frame_sync_width width; + /** Invert Frame Sync (FS) signal before use */ + bool invert_use; + /** Invert Frame Sync (FS) signal before output */ + bool invert_out; +}; + +/** + * Configure fir I2S frame + */ +struct i2s_frame_config { + /** Number of slots in a frame (1~8, 0,1 means minimum 1) */ + uint8_t number_slots; + /** Size of each slot in frame */ + enum i2s_slot_size slot_size; + /** Data delay from Frame Sync (FS) to first data bit */ + enum i2s_data_delay data_delay; + /** Frame sync (FS) */ + struct i2s_frame_sync_config frame_sync; +}; + +/** + * Configure for I2S clock unit + */ +struct i2s_clock_unit_config { + /** Configure clock generation */ + struct i2s_clock_config clock; + /** Configure frame generation */ + struct i2s_frame_config frame; + + /** Configure master clock pin */ + struct i2s_pin_config mck_pin; + /** Configure serial clock pin */ + struct i2s_pin_config sck_pin; + /** Configure frame sync pin */ + struct i2s_pin_config fs_pin; +}; + +/** + * Configure for I2S Serializer + */ +struct i2s_serializer_config { + /** Configure Serializer data pin */ + struct i2s_pin_config data_pin; + + /** Set to \c true to loop-back output to input pin for test */ + bool loop_back; + + /** Set to \c true to assumes mono input and duplicate it (left channel) to + * right channel */ + bool mono_mode; + + /** Disable data slot */ + bool disable_data_slot[8]; + + /** Set to \c true to transfer LSB first, \c false to transfer MSB first */ + bool transfer_lsb_first; + /** Data Word Formatting Adjust, + * set to \c true to adjust bits in word to left */ + bool data_adjust_left_in_word; + /** Data Slot Formatting Adjust, + * set to \c true to adjust words in slot to left */ + bool data_adjust_left_in_slot; + + /** Data Word Size */ + enum i2s_data_size data_size; + /** Data Formatting Bit Extension */ + enum i2s_bit_padding bit_padding; + /** Data padding when under-run */ + enum i2s_data_padding data_padding; + + /** DMA usage */ + enum i2s_dma_usage dma_usage; + + /** Clock unit selection */ + enum i2s_clock_unit clock_unit; + + /** Line default state where slot is disabled */ + enum i2s_line_default_state line_default_state; + + /** Serializer Mode */ + enum i2s_serializer_mode mode; +}; + +/** + * \brief I2S Serializer instance struct + */ +struct i2s_serializer_module { + +#if I2S_CALLBACK_MODE == true + /** Callbacks list for Serializer */ + i2s_serializer_callback_t callback[I2S_SERIALIZER_CALLBACK_N]; + + /** Job buffer */ + void *job_buffer; + /** Requested data words to read/write */ + uint32_t requested_words; + /** Transferred data words for read/write */ + uint32_t transferred_words; + + /** Callback mask for registered callbacks */ + uint8_t registered_callback_mask; + /** Callback mask for enabled callbacks */ + uint8_t enabled_callback_mask; + + /** Status of the ongoing or last transfer job */ + enum status_code job_status; +#endif + + /** Serializer mode */ + enum i2s_serializer_mode mode; + /** Serializer data word size */ + enum i2s_data_size data_size; +}; + +/** + * \brief I2S Software Module instance struct + */ +struct i2s_module { + /** Module HW register access base */ + I2s *hw; + + /** Module Serializer used */ + struct i2s_serializer_module serializer[2]; +}; + +/** + * \brief Determines if the hardware module(s) are currently synchronizing to the bus. + * + * Checks to see if the underlying hardware peripheral module(s) are currently + * synchronizing across multiple clock domains to the hardware bus, This + * function can be used to delay further operations on a module until such time + * that it is ready, to prevent blocking delays for synchronization in the + * user application. + * + * \param[in] module_inst Pointer to the software module instance struct + * + * \return Synchronization status of the underlying hardware module(s). + * + * \retval false If the module has completed synchronization + * \retval true If the module synchronization is ongoing + */ +static inline bool i2s_is_syncing( + const struct i2s_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + return (module_inst->hw->SYNCBUSY.reg > 0); +} + +/** + * \name Driver Initialization + * @{ + */ + +enum status_code i2s_init( + struct i2s_module *const module_inst, + I2s *hw); + +/** @} */ + +/** + * \name Enable/Disable/Reset + * @{ + */ + +/** + * \brief Enable the I2S module. + * + * Enables a I2S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void i2s_enable(const struct i2s_module *const module_inst) +{ + Assert(module_inst); + Assert(module_inst->hw); + + while (module_inst->hw->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg |= I2S_SYNCBUSY_ENABLE; +} + +/** + * \brief Disables the I2S module. + * + * Disables a I2S module. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void i2s_disable(const struct i2s_module *const module_inst) +{ + Assert(module_inst); + Assert(module_inst->hw); + + while (module_inst->hw->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg &= ~I2S_SYNCBUSY_ENABLE; +} + +/** + * \brief Resets the I2S module. + * + * Resets the I2S module, restoring all hardware module registers to their + * default values and disabling the module. The I2S module will not be + * accessible while the reset is being performed. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void i2s_reset(const struct i2s_module *const module_inst) +{ + Assert(module_inst); + Assert(module_inst->hw); + + /* Disable the module if it is running */ + if (module_inst->hw->CTRLA.reg & I2S_CTRLA_ENABLE) { + i2s_disable(module_inst); + while (i2s_is_syncing(module_inst)) { + /* Sync wait */ + } + } + /* Reset the HW module */ + module_inst->hw->CTRLA.reg = I2S_CTRLA_SWRST; +} + +/** @} */ + +/** + * \name Clock Unit Initialization and Configuration + * @{ + */ + +/** + * \brief Initializes config with predefined default values for I2S clock unit. + * + * This function will initialize a given I2S Clock Unit configuration structure + * to a set of known default values. This function should be called on any new + * instance of the configuration structures before being modified by the user + * application. + * + * The default configuration is as follow: + * - The clock unit does not generate output clocks (MCK, SCK and FS) + * - The pins (MCK, SCK and FS) and Mux configurations are not set + * + * \param[out] config Pointer to a I2S module clock unit configuration struct + * to set + */ +static inline void i2s_clock_unit_get_config_defaults( + struct i2s_clock_unit_config *const config) +{ + Assert(config); + + config->clock.mck_out_enable = false; + config->clock.gclk_src = GCLK_GENERATOR_0; + + config->clock.mck_src = I2S_MASTER_CLOCK_SOURCE_GCLK; + config->clock.mck_out_div = 1; + config->clock.mck_out_invert = false; + + config->clock.sck_src = I2S_SERIAL_CLOCK_SOURCE_MCKDIV; + config->clock.sck_div = 1; + config->clock.sck_out_invert = false; + + config->frame.number_slots = 1; + config->frame.slot_size = I2S_SLOT_SIZE_32_BIT; + config->frame.data_delay = I2S_DATA_DELAY_I2S; + + config->frame.frame_sync.source = I2S_FRAME_SYNC_SOURCE_SCKDIV; + config->frame.frame_sync.width = I2S_FRAME_SYNC_WIDTH_HALF_FRAME; + config->frame.frame_sync.invert_use = false; + config->frame.frame_sync.invert_out = false; + + config->mck_pin.enable = false; + config->mck_pin.mux = 0; + config->mck_pin.gpio = 0; + + config->sck_pin.enable = false; + config->sck_pin.mux = 0; + config->sck_pin.gpio = 0; + + config->fs_pin.enable = false; + config->fs_pin.mux = 0; + config->fs_pin.gpio = 0; +} + +enum status_code i2s_clock_unit_set_config( + struct i2s_module *const module_inst, + const enum i2s_clock_unit clock_unit, + const struct i2s_clock_unit_config *config); + +/** @} */ + + +/** + * \name Clock Unit Enable/Disable + * @{ + */ + +/** + * \brief Enable the Specified Clock Unit of I2S module. + * + * Enables a Clock Unit in I2S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] clock_unit I2S Clock Unit to enable + */ +static inline void i2s_clock_unit_enable( + const struct i2s_module *const module_inst, + const enum i2s_clock_unit clock_unit) +{ + uint32_t cken_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + cken_bit = I2S_CTRLA_CKEN0 << clock_unit; + + while (module_inst->hw->SYNCBUSY.reg & cken_bit) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg |= cken_bit; +} + +/** + * \brief Disable the Specified Clock Unit of I2S module. + * + * Disables a Clock Unit in I2S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] clock_unit I2S Clock Unit to disable + */ +static inline void i2s_clock_unit_disable( + const struct i2s_module *const module_inst, + const enum i2s_clock_unit clock_unit) +{ + uint32_t cken_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + cken_bit = I2S_CTRLA_CKEN0 << clock_unit; + + while (module_inst->hw->SYNCBUSY.reg & cken_bit) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg &= ~cken_bit; +} + +/** @} */ + + +/** + * \name Serializer Initialization and Configuration + * @{ + */ + +/** + * \brief Initializes config with predefined default values for I2S Serializer. + * + * This function will initialize a given I2S Clock Unit configuration structure + * to a set of known default values. This function should be called on any new + * instance of the configuration structures before being modified by the user + * application. + * + * The default configuration is as follow: + * - Output data does not internally loopback to input line + * - Does not extend mono data (left channel) to right channel + * - None of the data slot is disabled + * - MSB of I2S data is transferred first + * - In data word data is adjusted right + * - In slot data word is adjusted left + * - The data size is 16-bit width + * - I2S will padd 0 to not defined bits + * - I2S will padd 0 to not defined words + * - I2S will use single DMA channel for all data channels + * - I2S will use clock unit 0 to serve as clock + * - The default data line state is 0, when there is no data + * - I2S will transmit data to output line + * - The data pin and Mux configuration are not set + * + * \param[out] config Pointer to a I2S module Serializer configuration struct + * to set + */ +static inline void i2s_serializer_get_config_defaults( + struct i2s_serializer_config *const config) +{ + config->loop_back = false; + + config->mono_mode = false; + + config->disable_data_slot[0] = false; + config->disable_data_slot[1] = false; + config->disable_data_slot[2] = false; + config->disable_data_slot[3] = false; + config->disable_data_slot[4] = false; + config->disable_data_slot[5] = false; + config->disable_data_slot[6] = false; + config->disable_data_slot[7] = false; + + config->transfer_lsb_first = false; + config->data_adjust_left_in_word = false; + config->data_adjust_left_in_slot = true; + + config->data_size = I2S_DATA_SIZE_16BIT; + + config->bit_padding = I2S_BIT_PADDING_0; + config->data_padding = I2S_DATA_PADDING_0; + + config->dma_usage = I2S_DMA_USE_SINGLE_CHANNEL_FOR_ALL; + + config->clock_unit = I2S_CLOCK_UNIT_0; + + config->line_default_state = I2S_LINE_DEFAULT_0; + + config->mode = I2S_SERIALIZER_TRANSMIT; + + config->data_pin.enable = false; + config->data_pin.gpio = 0; + config->data_pin.mux = 0; +} + +enum status_code i2s_serializer_set_config( + struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + const struct i2s_serializer_config *config); +/** @} */ + +/** + * \name Serializer Enable/Disable + * @{ + */ + +/** + * \brief Enable the Specified Serializer of I2S module. + * + * Enables a Serializer in I2S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer I2S Serializer to enable + */ +static inline void i2s_serializer_enable( + const struct i2s_module *const module_inst, + const enum i2s_serializer serializer) +{ + uint32_t seren_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + seren_bit = I2S_CTRLA_SEREN0 << serializer; + + while (module_inst->hw->SYNCBUSY.reg & seren_bit) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg |= seren_bit; +} + +/** + * \brief Disable the Specified Serializer of I2S module. + * + * Disables a Serializer in I2S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer I2S Serializer to disable + */ +static inline void i2s_serializer_disable( + const struct i2s_module *const module_inst, + const enum i2s_serializer serializer) +{ + uint32_t seren_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + seren_bit = I2S_CTRLA_SEREN0 << serializer; + + while (module_inst->hw->SYNCBUSY.reg & seren_bit) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg &= ~seren_bit; +} +/** @} */ + +/** + * \name Status Management + * @{ + */ + +uint32_t i2s_get_status( + const struct i2s_module *const module_inst); + +void i2s_clear_status( + const struct i2s_module *const module_inst, + uint32_t status); + + +enum status_code i2s_enable_status_interrupt( + struct i2s_module *const module_inst, + uint32_t status); + +void i2s_disable_status_interrupt( + struct i2s_module *const module_inst, + uint32_t status); + +/** @}*/ + +/** + * \name Data read/write + * @{ + */ + +/** + * \brief Write a data word to the specified Serializer of I2S module + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The Serializer to write to + * \param[in] data The data to write + * + */ +static inline void i2s_serializer_write_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + uint32_t data) +{ + uint32_t sync_bit, ready_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + ready_bit = I2S_INTFLAG_TXRDY0 << serializer; + while (!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait until ready to transmit */ + } + sync_bit = I2S_SYNCBUSY_DATA0 << serializer; + while (module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait sync */ + } + /* Write data */ + module_inst->hw->DATA[serializer].reg = data; + module_inst->hw->INTFLAG.reg = ready_bit; +} + +/** + * \brief Read a data word from the specified Serializer of I2S module + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The Serializer to read + */ +static inline uint32_t i2s_serializer_read_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer) +{ + uint32_t sync_bit, ready_bit; + uint32_t data; + + Assert(module_inst); + Assert(module_inst->hw); + + ready_bit = I2S_INTFLAG_RXRDY0 << serializer; + while (!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait until ready to transmit */ + } + sync_bit = I2S_SYNCBUSY_DATA0 << serializer; + while (module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait sync */ + } + /* Read data */ + data = module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + return data; +} + + +/** + * \brief Write buffer to the specified Serializer of I2S module + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The Serializer to write to + * \param[in] buffer The data buffer to write + * \param[in] size Number of data words to write + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The data was sent successfully + * \retval STATUS_INVALID_ARG An invalid buffer pointer was supplied + */ +enum status_code i2s_serializer_write_buffer_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + void *buffer, uint32_t size); + +/** + * \brief Read from the specified Serializer of I2S module to a buffer + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The Serializer to write to + * \param[in] buffer The buffer to fill read data + * \param[in] size Number of data words to read + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The data was sent successfully + * \retval STATUS_INVALID_ARG An invalid buffer pointer was supplied + */ +enum status_code i2s_serializer_read_buffer_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + void *buffer, uint32_t size); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +/** @} */ + + +/** + * \page asfdoc_sam0_i2s_extra Extra Information for I2S Driver + * + * \section asfdoc_sam0_i2s_extra_acronyms Acronyms + * Below is a table listing the acronyms used in this module, along with their + * intended meanings. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
AcronymDescription
I2S, IISInter-IC Sound Controller
MCKMaster Clock
SCKSerial Clock
FSFrame Sync
SDSerial Data
ADCAnalog-to-Digital Converter
DACDigital-to-Analog Converter
TDMTime Division Multiplexed
PDMPulse Density Modulation
LSBLeast Significant Bit
MSBMost Significant Bit
DSPDigital Signal Processor
+ * + * + * \section asfdoc_sam0_i2s_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - \ref asfdoc_sam0_system_pinmux_group "System Pin Multiplexer Driver" + * + * + * \section asfdoc_sam0_i2s_extra_errata Errata + * There are no errata related to this driver. + * + * + * \section asfdoc_sam0_i2s_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * + * + * + *
Changelog
Initial Release
+ */ + +/** + * \page asfdoc_sam0_i2s_exqsg Examples for I2S Driver + * + * This is a list of the available Quick Start guides (QSGs) and example + * applications for \ref asfdoc_sam0_i2s_group. QSGs are simple examples with + * step-by-step instructions to configure and use this driver in a selection of + * use cases. Note that QSGs can be compiled as a standalone application or be + * added to the user application. + * + * - \subpage asfdoc_sam0_i2s_basic_use_case + * \if I2S_CALLBACK_MODE + * - \subpage asfdoc_sam0_i2s_callback_use_case + * \endif + * - \subpage asfdoc_sam0_i2s_dma_use_case + * + * \page asfdoc_sam0_i2s_document_revision_history Document Revision History + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Doc. Rev. + * Date + * Comments + *
B04/2015Added support for SAMDA1.
A01/2014Initial release
+ */ + +#endif /* #ifndef I2S_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt.h new file mode 100644 index 0000000..fa4878e --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt.h @@ -0,0 +1,117 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ +#ifndef UTILS_INTERRUPT_H +#define UTILS_INTERRUPT_H + +//#include + +#include "interrupt/interrupt_sam_nvic.h" + +/** + * \defgroup interrupt_group Global interrupt management + * + * This is a driver for global enabling and disabling of interrupts. + * + * @{ + */ + +#if defined(__DOXYGEN__) +/** + * \def CONFIG_INTERRUPT_FORCE_INTC + * \brief Force usage of the ASF INTC driver + * + * Predefine this symbol when preprocessing to force the use of the ASF INTC driver. + * This is useful to ensure compatibility across compilers and shall be used only when required + * by the application needs. + */ +# define CONFIG_INTERRUPT_FORCE_INTC +#endif + +//! \name Global interrupt flags +//@{ +/** + * \typedef irqflags_t + * \brief Type used for holding state of interrupt flag + */ + +/** + * \def cpu_irq_enable + * \brief Enable interrupts globally + */ + +/** + * \def cpu_irq_disable + * \brief Disable interrupts globally + */ + +/** + * \fn irqflags_t cpu_irq_save(void) + * \brief Get and clear the global interrupt flags + * + * Use in conjunction with \ref cpu_irq_restore. + * + * \return Current state of interrupt flags. + * + * \note This function leaves interrupts disabled. + */ + +/** + * \fn void cpu_irq_restore(irqflags_t flags) + * \brief Restore global interrupt flags + * + * Use in conjunction with \ref cpu_irq_save. + * + * \param flags State to set interrupt flag to. + */ + +/** + * \fn bool cpu_irq_is_enabled_flags(irqflags_t flags) + * \brief Check if interrupts are globally enabled in supplied flags + * + * \param flags Currents state of interrupt flags. + * + * \return True if interrupts are enabled. + */ + +/** + * \def cpu_irq_is_enabled + * \brief Check if interrupts are globally enabled + * + * \return True if interrupts are enabled. + */ +//@} + +//! @} + +/** + * \ingroup interrupt_group + * \defgroup interrupt_deprecated_group Deprecated interrupt definitions + */ + +#endif /* UTILS_INTERRUPT_H */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c b/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c new file mode 100644 index 0000000..d813485 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c @@ -0,0 +1,69 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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 "interrupt_sam_nvic.h" + +#if !defined(__DOXYGEN__) +/* Deprecated - global flag to determine the global interrupt state. Required by + * QTouch library, however new applications should use cpu_irq_is_enabled() + * which probes the true global interrupt state from the CPU special registers. + */ +volatile bool g_interrupt_enabled = true; +#endif + +void cpu_irq_enter_critical(void) +{ + if (cpu_irq_critical_section_counter == 0) { + if (cpu_irq_is_enabled()) { + cpu_irq_disable(); + cpu_irq_prev_interrupt_state = true; + } else { + /* Make sure the to save the prev state as false */ + cpu_irq_prev_interrupt_state = false; + } + + } + + cpu_irq_critical_section_counter++; +} + +void cpu_irq_leave_critical(void) +{ + /* Check if the user is trying to leave a critical section when not in a critical section */ + Assert(cpu_irq_critical_section_counter > 0); + + cpu_irq_critical_section_counter--; + + /* Only enable global interrupts when the counter reaches 0 and the state of the global interrupt flag + was enabled when entering critical state */ + if ((cpu_irq_critical_section_counter == 0) && (cpu_irq_prev_interrupt_state)) { + cpu_irq_enable(); + } +} + diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h new file mode 100644 index 0000000..9b5645b --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h @@ -0,0 +1,172 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef UTILS_INTERRUPT_INTERRUPT_H +#define UTILS_INTERRUPT_INTERRUPT_H + +#include +//#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \weakgroup interrupt_group + * + * @{ + */ + +/** + * \name Interrupt Service Routine definition + * + * @{ + */ + +/** + * \brief Define service routine + * + * \note For NVIC devices the interrupt service routines are predefined to + * add to vector table in binary generation, so there is no service + * register at run time. The routine collections are in exceptions.h. + * + * Usage: + * \code + ISR(foo_irq_handler) + { + // Function definition + ... + } +\endcode + * + * \param func Name for the function. + */ +# define ISR(func) \ + void func (void) + +/** + * \brief Initialize interrupt vectors + * + * For NVIC the interrupt vectors are put in vector table. So nothing + * to do to initialize them, except defined the vector function with + * right name. + * + * This must be called prior to \ref irq_register_handler. + */ +# define irq_initialize_vectors() \ + do { \ + } while(0) + +/** + * \brief Register handler for interrupt + * + * For NVIC the interrupt vectors are put in vector table. So nothing + * to do to register them, except defined the vector function with + * right name. + * + * Usage: + * \code + irq_initialize_vectors(); + irq_register_handler(foo_irq_handler); +\endcode + * + * \note The function \a func must be defined with the \ref ISR macro. + * \note The functions prototypes can be found in the device exception header + * files (exceptions.h). + */ +# define irq_register_handler(int_num, int_prio) \ + NVIC_ClearPendingIRQ( (IRQn_Type)int_num); \ + NVIC_SetPriority( (IRQn_Type)int_num, int_prio); \ + NVIC_EnableIRQ( (IRQn_Type)int_num); \ + +//@} + +# define cpu_irq_enable() \ + do { \ + g_interrupt_enabled = true; \ + __DMB(); \ + __enable_irq(); \ + } while (0) +# define cpu_irq_disable() \ + do { \ + __disable_irq(); \ + __DMB(); \ + g_interrupt_enabled = false; \ + } while (0) + +typedef uint32_t irqflags_t; + +#if !defined(__DOXYGEN__) +extern volatile bool g_interrupt_enabled; +#endif + +#define cpu_irq_is_enabled() (__get_PRIMASK() == 0) + +static volatile uint32_t cpu_irq_critical_section_counter; +static volatile bool cpu_irq_prev_interrupt_state; + +static inline irqflags_t cpu_irq_save(void) +{ + irqflags_t flags = cpu_irq_is_enabled(); + cpu_irq_disable(); + return flags; +} + +static inline bool cpu_irq_is_enabled_flags(irqflags_t flags) +{ + return (flags); +} + +static inline void cpu_irq_restore(irqflags_t flags) +{ + if (cpu_irq_is_enabled_flags(flags)) + cpu_irq_enable(); +} + +void cpu_irq_enter_critical(void); +void cpu_irq_leave_critical(void); + +/** + * \weakgroup interrupt_deprecated_group + * @{ + */ + +#define Enable_global_interrupt() cpu_irq_enable() +#define Disable_global_interrupt() cpu_irq_disable() +#define Is_global_interrupt_enabled() cpu_irq_is_enabled() + +//@} + +//@} + +#ifdef __cplusplus +} +#endif + +#endif /* UTILS_INTERRUPT_INTERRUPT_H */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c b/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c new file mode 100644 index 0000000..26dcc91 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c @@ -0,0 +1,86 @@ +/** + * \file + * + * \brief Global interrupt management for SAM D20, SAM3 and SAM4 (NVIC based) + * + * Copyright (c) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#include "interrupt_sam_nvic.h" + +#if !defined(__DOXYGEN__) +/* Deprecated - global flag to determine the global interrupt state. Required by + * QTouch library, however new applications should use cpu_irq_is_enabled() + * which probes the true global interrupt state from the CPU special registers. + */ +volatile bool g_interrupt_enabled = true; +#endif + +void cpu_irq_enter_critical(void) +{ + if (cpu_irq_critical_section_counter == 0) { + if (cpu_irq_is_enabled()) { + cpu_irq_disable(); + cpu_irq_prev_interrupt_state = true; + } else { + /* Make sure the to save the prev state as false */ + cpu_irq_prev_interrupt_state = false; + } + + } + + cpu_irq_critical_section_counter++; +} + +void cpu_irq_leave_critical(void) +{ + /* Check if the user is trying to leave a critical section when not in a critical section */ + Assert(cpu_irq_critical_section_counter > 0); + + cpu_irq_critical_section_counter--; + + /* Only enable global interrupts when the counter reaches 0 and the state of the global interrupt flag + was enabled when entering critical state */ + if ((cpu_irq_critical_section_counter == 0) && (cpu_irq_prev_interrupt_state)) { + cpu_irq_enable(); + } +} + diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h new file mode 100644 index 0000000..f996e92 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h @@ -0,0 +1,189 @@ +/** + * \file + * + * \brief Global interrupt management for SAM D20, SAM3 and SAM4 (NVIC based) + * + * Copyright (c) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#ifndef UTILS_INTERRUPT_INTERRUPT_H +#define UTILS_INTERRUPT_INTERRUPT_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \weakgroup interrupt_group + * + * @{ + */ + +/** + * \name Interrupt Service Routine definition + * + * @{ + */ + +/** + * \brief Define service routine + * + * \note For NVIC devices the interrupt service routines are predefined to + * add to vector table in binary generation, so there is no service + * register at run time. The routine collections are in exceptions.h. + * + * Usage: + * \code + ISR(foo_irq_handler) + { + // Function definition + ... + } +\endcode + * + * \param func Name for the function. + */ +# define ISR(func) \ + void func (void) + +/** + * \brief Initialize interrupt vectors + * + * For NVIC the interrupt vectors are put in vector table. So nothing + * to do to initialize them, except defined the vector function with + * right name. + * + * This must be called prior to \ref irq_register_handler. + */ +# define irq_initialize_vectors() \ + do { \ + } while(0) + +/** + * \brief Register handler for interrupt + * + * For NVIC the interrupt vectors are put in vector table. So nothing + * to do to register them, except defined the vector function with + * right name. + * + * Usage: + * \code + irq_initialize_vectors(); + irq_register_handler(foo_irq_handler); +\endcode + * + * \note The function \a func must be defined with the \ref ISR macro. + * \note The functions prototypes can be found in the device exception header + * files (exceptions.h). + */ +# define irq_register_handler(int_num, int_prio) \ + NVIC_ClearPendingIRQ( (IRQn_Type)int_num); \ + NVIC_SetPriority( (IRQn_Type)int_num, int_prio); \ + NVIC_EnableIRQ( (IRQn_Type)int_num); \ + +//@} + +# define cpu_irq_enable() \ + do { \ + g_interrupt_enabled = true; \ + __DMB(); \ + __enable_irq(); \ + } while (0) +# define cpu_irq_disable() \ + do { \ + __disable_irq(); \ + __DMB(); \ + g_interrupt_enabled = false; \ + } while (0) + +typedef uint32_t irqflags_t; + +#if !defined(__DOXYGEN__) +extern volatile bool g_interrupt_enabled; +#endif + +#define cpu_irq_is_enabled() (__get_PRIMASK() == 0) + +static volatile uint32_t cpu_irq_critical_section_counter; +static volatile bool cpu_irq_prev_interrupt_state; + +static inline irqflags_t cpu_irq_save(void) +{ + irqflags_t flags = cpu_irq_is_enabled(); + cpu_irq_disable(); + return flags; +} + +static inline bool cpu_irq_is_enabled_flags(irqflags_t flags) +{ + return (flags); +} + +static inline void cpu_irq_restore(irqflags_t flags) +{ + if (cpu_irq_is_enabled_flags(flags)) + cpu_irq_enable(); +} + +void cpu_irq_enter_critical(void); +void cpu_irq_leave_critical(void); + +/** + * \weakgroup interrupt_deprecated_group + * @{ + */ + +#define Enable_global_interrupt() cpu_irq_enable() +#define Disable_global_interrupt() cpu_irq_disable() +#define Is_global_interrupt_enabled() cpu_irq_is_enabled() + +//@} + +//@} + +#ifdef __cplusplus +} +#endif + +#endif /* UTILS_INTERRUPT_INTERRUPT_H */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/library.properties b/feather_sensor_transmit/libraries/Adafruit_ASFcore/library.properties new file mode 100644 index 0000000..e2af108 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/library.properties @@ -0,0 +1,9 @@ +name=Adafruit Arduino Zero ASF Core Library +version=1.0.0 +author=Adafruit +maintainer=Adafruit +sentence=ASF (Atmel Software Framework) files used by Adafruit's Arduino Zero/SAMD21 libraries. +paragraph=ASF (Atmel Software Framework) files used by Adafruit's Arduino Zero/SAMD21 libraries. This is a dependency of other libraries like Adafruit_ZeroTimer. +category=Other +url=https://github.com/adafruit/Adafruit_ASFcore +architectures=* diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/parts.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/parts.h new file mode 100644 index 0000000..40be022 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/parts.h @@ -0,0 +1,1601 @@ +/** + * \file + * + * \brief Atmel part identification macros + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#ifndef ATMEL_PARTS_H +#define ATMEL_PARTS_H + +/** + * \defgroup part_macros_group Atmel part identification macros + * + * This collection of macros identify which series and families that the various + * Atmel parts belong to. These can be used to select part-dependent sections of + * code at compile time. + * + * @{ + */ + +/** + * \name Convenience macros for part checking + * @{ + */ +/* ! Check GCC and IAR part definition for 8-bit AVR */ +#define AVR8_PART_IS_DEFINED(part) \ + (defined(__ ## part ## __) || defined(__AVR_ ## part ## __)) + +/* ! Check GCC and IAR part definition for 32-bit AVR */ +#define AVR32_PART_IS_DEFINED(part) \ + (defined(__AT32 ## part ## __) || defined(__AVR32_ ## part ## __)) + +/* ! Check GCC and IAR part definition for SAM */ +#define SAM_PART_IS_DEFINED(part) (defined(__ ## part ## __)) +/** @} */ + +/** + * \defgroup uc3_part_macros_group AVR UC3 parts + * @{ + */ + +/** + * \name AVR UC3 A series + * @{ + */ +#define UC3A0 ( \ + AVR32_PART_IS_DEFINED(UC3A0128) || \ + AVR32_PART_IS_DEFINED(UC3A0256) || \ + AVR32_PART_IS_DEFINED(UC3A0512) \ + ) + +#define UC3A1 ( \ + AVR32_PART_IS_DEFINED(UC3A1128) || \ + AVR32_PART_IS_DEFINED(UC3A1256) || \ + AVR32_PART_IS_DEFINED(UC3A1512) \ + ) + +#define UC3A3 ( \ + AVR32_PART_IS_DEFINED(UC3A364) || \ + AVR32_PART_IS_DEFINED(UC3A364S) || \ + AVR32_PART_IS_DEFINED(UC3A3128) || \ + AVR32_PART_IS_DEFINED(UC3A3128S) || \ + AVR32_PART_IS_DEFINED(UC3A3256) || \ + AVR32_PART_IS_DEFINED(UC3A3256S) \ + ) + +#define UC3A4 ( \ + AVR32_PART_IS_DEFINED(UC3A464) || \ + AVR32_PART_IS_DEFINED(UC3A464S) || \ + AVR32_PART_IS_DEFINED(UC3A4128) || \ + AVR32_PART_IS_DEFINED(UC3A4128S) || \ + AVR32_PART_IS_DEFINED(UC3A4256) || \ + AVR32_PART_IS_DEFINED(UC3A4256S) \ + ) +/** @} */ + +/** + * \name AVR UC3 B series + * @{ + */ +#define UC3B0 ( \ + AVR32_PART_IS_DEFINED(UC3B064) || \ + AVR32_PART_IS_DEFINED(UC3B0128) || \ + AVR32_PART_IS_DEFINED(UC3B0256) || \ + AVR32_PART_IS_DEFINED(UC3B0512) \ + ) + +#define UC3B1 ( \ + AVR32_PART_IS_DEFINED(UC3B164) || \ + AVR32_PART_IS_DEFINED(UC3B1128) || \ + AVR32_PART_IS_DEFINED(UC3B1256) || \ + AVR32_PART_IS_DEFINED(UC3B1512) \ + ) +/** @} */ + +/** + * \name AVR UC3 C series + * @{ + */ +#define UC3C0 ( \ + AVR32_PART_IS_DEFINED(UC3C064C) || \ + AVR32_PART_IS_DEFINED(UC3C0128C) || \ + AVR32_PART_IS_DEFINED(UC3C0256C) || \ + AVR32_PART_IS_DEFINED(UC3C0512C) \ + ) + +#define UC3C1 ( \ + AVR32_PART_IS_DEFINED(UC3C164C) || \ + AVR32_PART_IS_DEFINED(UC3C1128C) || \ + AVR32_PART_IS_DEFINED(UC3C1256C) || \ + AVR32_PART_IS_DEFINED(UC3C1512C) \ + ) + +#define UC3C2 ( \ + AVR32_PART_IS_DEFINED(UC3C264C) || \ + AVR32_PART_IS_DEFINED(UC3C2128C) || \ + AVR32_PART_IS_DEFINED(UC3C2256C) || \ + AVR32_PART_IS_DEFINED(UC3C2512C) \ + ) +/** @} */ + +/** + * \name AVR UC3 D series + * @{ + */ +#define UC3D3 ( \ + AVR32_PART_IS_DEFINED(UC64D3) || \ + AVR32_PART_IS_DEFINED(UC128D3) \ + ) + +#define UC3D4 ( \ + AVR32_PART_IS_DEFINED(UC64D4) || \ + AVR32_PART_IS_DEFINED(UC128D4) \ + ) +/** @} */ + +/** + * \name AVR UC3 L series + * @{ + */ +#define UC3L0 ( \ + AVR32_PART_IS_DEFINED(UC3L016) || \ + AVR32_PART_IS_DEFINED(UC3L032) || \ + AVR32_PART_IS_DEFINED(UC3L064) \ + ) + +#define UC3L0128 ( \ + AVR32_PART_IS_DEFINED(UC3L0128) \ + ) + +#define UC3L0256 ( \ + AVR32_PART_IS_DEFINED(UC3L0256) \ + ) + +#define UC3L3 ( \ + AVR32_PART_IS_DEFINED(UC64L3U) || \ + AVR32_PART_IS_DEFINED(UC128L3U) || \ + AVR32_PART_IS_DEFINED(UC256L3U) \ + ) + +#define UC3L4 ( \ + AVR32_PART_IS_DEFINED(UC64L4U) || \ + AVR32_PART_IS_DEFINED(UC128L4U) || \ + AVR32_PART_IS_DEFINED(UC256L4U) \ + ) + +#define UC3L3_L4 (UC3L3 || UC3L4) +/** @} */ + +/** + * \name AVR UC3 families + * @{ + */ +/** AVR UC3 A family */ +#define UC3A (UC3A0 || UC3A1 || UC3A3 || UC3A4) + +/** AVR UC3 B family */ +#define UC3B (UC3B0 || UC3B1) + +/** AVR UC3 C family */ +#define UC3C (UC3C0 || UC3C1 || UC3C2) + +/** AVR UC3 D family */ +#define UC3D (UC3D3 || UC3D4) + +/** AVR UC3 L family */ +#define UC3L (UC3L0 || UC3L0128 || UC3L0256 || UC3L3_L4) +/** @} */ + +/** AVR UC3 product line */ +#define UC3 (UC3A || UC3B || UC3C || UC3D || UC3L) + +/** @} */ + +/** + * \defgroup xmega_part_macros_group AVR XMEGA parts + * @{ + */ + +/** + * \name AVR XMEGA A series + * @{ + */ +#define XMEGA_A1 ( \ + AVR8_PART_IS_DEFINED(ATxmega64A1) || \ + AVR8_PART_IS_DEFINED(ATxmega128A1) \ + ) + +#define XMEGA_A3 ( \ + AVR8_PART_IS_DEFINED(ATxmega64A3) || \ + AVR8_PART_IS_DEFINED(ATxmega128A3) || \ + AVR8_PART_IS_DEFINED(ATxmega192A3) || \ + AVR8_PART_IS_DEFINED(ATxmega256A3) \ + ) + +#define XMEGA_A3B ( \ + AVR8_PART_IS_DEFINED(ATxmega256A3B) \ + ) + +#define XMEGA_A4 ( \ + AVR8_PART_IS_DEFINED(ATxmega16A4) || \ + AVR8_PART_IS_DEFINED(ATxmega32A4) \ + ) +/** @} */ + +/** + * \name AVR XMEGA AU series + * @{ + */ +#define XMEGA_A1U ( \ + AVR8_PART_IS_DEFINED(ATxmega64A1U) || \ + AVR8_PART_IS_DEFINED(ATxmega128A1U) \ + ) + +#define XMEGA_A3U ( \ + AVR8_PART_IS_DEFINED(ATxmega64A3U) || \ + AVR8_PART_IS_DEFINED(ATxmega128A3U) || \ + AVR8_PART_IS_DEFINED(ATxmega192A3U) || \ + AVR8_PART_IS_DEFINED(ATxmega256A3U) \ + ) + +#define XMEGA_A3BU ( \ + AVR8_PART_IS_DEFINED(ATxmega256A3BU) \ + ) + +#define XMEGA_A4U ( \ + AVR8_PART_IS_DEFINED(ATxmega16A4U) || \ + AVR8_PART_IS_DEFINED(ATxmega32A4U) || \ + AVR8_PART_IS_DEFINED(ATxmega64A4U) || \ + AVR8_PART_IS_DEFINED(ATxmega128A4U) \ + ) +/** @} */ + +/** + * \name AVR XMEGA B series + * @{ + */ +#define XMEGA_B1 ( \ + AVR8_PART_IS_DEFINED(ATxmega64B1) || \ + AVR8_PART_IS_DEFINED(ATxmega128B1) \ + ) + +#define XMEGA_B3 ( \ + AVR8_PART_IS_DEFINED(ATxmega64B3) || \ + AVR8_PART_IS_DEFINED(ATxmega128B3) \ + ) +/** @} */ + +/** + * \name AVR XMEGA C series + * @{ + */ +#define XMEGA_C3 ( \ + AVR8_PART_IS_DEFINED(ATxmega384C3) || \ + AVR8_PART_IS_DEFINED(ATxmega256C3) || \ + AVR8_PART_IS_DEFINED(ATxmega192C3) || \ + AVR8_PART_IS_DEFINED(ATxmega128C3) || \ + AVR8_PART_IS_DEFINED(ATxmega64C3) || \ + AVR8_PART_IS_DEFINED(ATxmega32C3) \ + ) + +#define XMEGA_C4 ( \ + AVR8_PART_IS_DEFINED(ATxmega32C4) || \ + AVR8_PART_IS_DEFINED(ATxmega16C4) \ + ) +/** @} */ + +/** + * \name AVR XMEGA D series + * @{ + */ +#define XMEGA_D3 ( \ + AVR8_PART_IS_DEFINED(ATxmega32D3) || \ + AVR8_PART_IS_DEFINED(ATxmega64D3) || \ + AVR8_PART_IS_DEFINED(ATxmega128D3) || \ + AVR8_PART_IS_DEFINED(ATxmega192D3) || \ + AVR8_PART_IS_DEFINED(ATxmega256D3) || \ + AVR8_PART_IS_DEFINED(ATxmega384D3) \ + ) + +#define XMEGA_D4 ( \ + AVR8_PART_IS_DEFINED(ATxmega16D4) || \ + AVR8_PART_IS_DEFINED(ATxmega32D4) || \ + AVR8_PART_IS_DEFINED(ATxmega64D4) || \ + AVR8_PART_IS_DEFINED(ATxmega128D4) \ + ) +/** @} */ + +/** + * \name AVR XMEGA E series + * @{ + */ +#define XMEGA_E5 ( \ + AVR8_PART_IS_DEFINED(ATxmega8E5) || \ + AVR8_PART_IS_DEFINED(ATxmega16E5) || \ + AVR8_PART_IS_DEFINED(ATxmega32E5) \ + ) +/** @} */ + + +/** + * \name AVR XMEGA families + * @{ + */ +/** AVR XMEGA A family */ +#define XMEGA_A (XMEGA_A1 || XMEGA_A3 || XMEGA_A3B || XMEGA_A4) + +/** AVR XMEGA AU family */ +#define XMEGA_AU (XMEGA_A1U || XMEGA_A3U || XMEGA_A3BU || XMEGA_A4U) + +/** AVR XMEGA B family */ +#define XMEGA_B (XMEGA_B1 || XMEGA_B3) + +/** AVR XMEGA C family */ +#define XMEGA_C (XMEGA_C3 || XMEGA_C4) + +/** AVR XMEGA D family */ +#define XMEGA_D (XMEGA_D3 || XMEGA_D4) + +/** AVR XMEGA E family */ +#define XMEGA_E (XMEGA_E5) +/** @} */ + + +/** AVR XMEGA product line */ +#define XMEGA (XMEGA_A || XMEGA_AU || XMEGA_B || XMEGA_C || XMEGA_D || XMEGA_E) + +/** @} */ + +/** + * \defgroup mega_part_macros_group megaAVR parts + * + * \note These megaAVR groupings are based on the groups in AVR Libc for the + * part header files. They are not names of official megaAVR device series or + * families. + * + * @{ + */ + +/** + * \name ATmegaxx0/xx1 subgroups + * @{ + */ +#define MEGA_XX0 ( \ + AVR8_PART_IS_DEFINED(ATmega640) || \ + AVR8_PART_IS_DEFINED(ATmega1280) || \ + AVR8_PART_IS_DEFINED(ATmega2560) \ + ) + +#define MEGA_XX1 ( \ + AVR8_PART_IS_DEFINED(ATmega1281) || \ + AVR8_PART_IS_DEFINED(ATmega2561) \ + ) +/** @} */ + +/** + * \name megaAVR groups + * @{ + */ +/** ATmegaxx0/xx1 group */ +#define MEGA_XX0_1 (MEGA_XX0 || MEGA_XX1) + +/** ATmegaxx4 group */ +#define MEGA_XX4 ( \ + AVR8_PART_IS_DEFINED(ATmega164A) || \ + AVR8_PART_IS_DEFINED(ATmega164PA) || \ + AVR8_PART_IS_DEFINED(ATmega324A) || \ + AVR8_PART_IS_DEFINED(ATmega324PA) || \ + AVR8_PART_IS_DEFINED(ATmega644) || \ + AVR8_PART_IS_DEFINED(ATmega644A) || \ + AVR8_PART_IS_DEFINED(ATmega644PA) || \ + AVR8_PART_IS_DEFINED(ATmega1284P) || \ + AVR8_PART_IS_DEFINED(ATmega128RFA1) \ + ) + +/** ATmegaxx4 group */ +#define MEGA_XX4_A ( \ + AVR8_PART_IS_DEFINED(ATmega164A) || \ + AVR8_PART_IS_DEFINED(ATmega164PA) || \ + AVR8_PART_IS_DEFINED(ATmega324A) || \ + AVR8_PART_IS_DEFINED(ATmega324PA) || \ + AVR8_PART_IS_DEFINED(ATmega644A) || \ + AVR8_PART_IS_DEFINED(ATmega644PA) || \ + AVR8_PART_IS_DEFINED(ATmega1284P) \ + ) + +/** ATmegaxx8 group */ +#define MEGA_XX8 ( \ + AVR8_PART_IS_DEFINED(ATmega48) || \ + AVR8_PART_IS_DEFINED(ATmega48A) || \ + AVR8_PART_IS_DEFINED(ATmega48PA) || \ + AVR8_PART_IS_DEFINED(ATmega88) || \ + AVR8_PART_IS_DEFINED(ATmega88A) || \ + AVR8_PART_IS_DEFINED(ATmega88PA) || \ + AVR8_PART_IS_DEFINED(ATmega168) || \ + AVR8_PART_IS_DEFINED(ATmega168A) || \ + AVR8_PART_IS_DEFINED(ATmega168PA) || \ + AVR8_PART_IS_DEFINED(ATmega328) || \ + AVR8_PART_IS_DEFINED(ATmega328P) \ + ) + +/** ATmegaxx8A/P/PA group */ +#define MEGA_XX8_A ( \ + AVR8_PART_IS_DEFINED(ATmega48A) || \ + AVR8_PART_IS_DEFINED(ATmega48PA) || \ + AVR8_PART_IS_DEFINED(ATmega88A) || \ + AVR8_PART_IS_DEFINED(ATmega88PA) || \ + AVR8_PART_IS_DEFINED(ATmega168A) || \ + AVR8_PART_IS_DEFINED(ATmega168PA) || \ + AVR8_PART_IS_DEFINED(ATmega328P) \ + ) + +/** ATmegaxx group */ +#define MEGA_XX ( \ + AVR8_PART_IS_DEFINED(ATmega16) || \ + AVR8_PART_IS_DEFINED(ATmega16A) || \ + AVR8_PART_IS_DEFINED(ATmega32) || \ + AVR8_PART_IS_DEFINED(ATmega32A) || \ + AVR8_PART_IS_DEFINED(ATmega64) || \ + AVR8_PART_IS_DEFINED(ATmega64A) || \ + AVR8_PART_IS_DEFINED(ATmega128) || \ + AVR8_PART_IS_DEFINED(ATmega128A) \ + ) + +/** ATmegaxxA/P/PA group */ +#define MEGA_XX_A ( \ + AVR8_PART_IS_DEFINED(ATmega16A) || \ + AVR8_PART_IS_DEFINED(ATmega32A) || \ + AVR8_PART_IS_DEFINED(ATmega64A) || \ + AVR8_PART_IS_DEFINED(ATmega128A) \ + ) +/** ATmegaxxRFA1 group */ +#define MEGA_RFA1 ( \ + AVR8_PART_IS_DEFINED(ATmega128RFA1) \ + ) + +/** ATmegaxxRFR2 group */ +#define MEGA_RFR2 ( \ + AVR8_PART_IS_DEFINED(ATmega64RFR2) || \ + AVR8_PART_IS_DEFINED(ATmega128RFR2) || \ + AVR8_PART_IS_DEFINED(ATmega256RFR2) || \ + AVR8_PART_IS_DEFINED(ATmega644RFR2) || \ + AVR8_PART_IS_DEFINED(ATmega1284RFR2) || \ + AVR8_PART_IS_DEFINED(ATmega2564RFR2) \ + ) + + +/** ATmegaxxRFxx group */ +#define MEGA_RF (MEGA_RFA1 || MEGA_RFR2) + +/** + * \name ATmegaxx_un0/un1/un2 subgroups + * @{ + */ +#define MEGA_XX_UN0 ( \ + AVR8_PART_IS_DEFINED(ATmega16) || \ + AVR8_PART_IS_DEFINED(ATmega16A) || \ + AVR8_PART_IS_DEFINED(ATmega32) || \ + AVR8_PART_IS_DEFINED(ATmega32A) \ + ) + +/** ATmegaxx group without power reduction and + * And interrupt sense register. + */ +#define MEGA_XX_UN1 ( \ + AVR8_PART_IS_DEFINED(ATmega64) || \ + AVR8_PART_IS_DEFINED(ATmega64A) || \ + AVR8_PART_IS_DEFINED(ATmega128) || \ + AVR8_PART_IS_DEFINED(ATmega128A) \ + ) + +/** ATmegaxx group without power reduction and + * And interrupt sense register. + */ +#define MEGA_XX_UN2 ( \ + AVR8_PART_IS_DEFINED(ATmega169P) || \ + AVR8_PART_IS_DEFINED(ATmega169PA) || \ + AVR8_PART_IS_DEFINED(ATmega329P) || \ + AVR8_PART_IS_DEFINED(ATmega329PA) \ + ) + +/** Devices added to complete megaAVR offering. + * Please do not use this group symbol as it is not intended + * to be permanent: the devices should be regrouped. + */ +#define MEGA_UNCATEGORIZED ( \ + AVR8_PART_IS_DEFINED(AT90CAN128) || \ + AVR8_PART_IS_DEFINED(AT90CAN32) || \ + AVR8_PART_IS_DEFINED(AT90CAN64) || \ + AVR8_PART_IS_DEFINED(AT90PWM1) || \ + AVR8_PART_IS_DEFINED(AT90PWM216) || \ + AVR8_PART_IS_DEFINED(AT90PWM2B) || \ + AVR8_PART_IS_DEFINED(AT90PWM316) || \ + AVR8_PART_IS_DEFINED(AT90PWM3B) || \ + AVR8_PART_IS_DEFINED(AT90PWM81) || \ + AVR8_PART_IS_DEFINED(AT90USB1286) || \ + AVR8_PART_IS_DEFINED(AT90USB1287) || \ + AVR8_PART_IS_DEFINED(AT90USB162) || \ + AVR8_PART_IS_DEFINED(AT90USB646) || \ + AVR8_PART_IS_DEFINED(AT90USB647) || \ + AVR8_PART_IS_DEFINED(AT90USB82) || \ + AVR8_PART_IS_DEFINED(ATmega1284) || \ + AVR8_PART_IS_DEFINED(ATmega162) || \ + AVR8_PART_IS_DEFINED(ATmega164P) || \ + AVR8_PART_IS_DEFINED(ATmega165A) || \ + AVR8_PART_IS_DEFINED(ATmega165P) || \ + AVR8_PART_IS_DEFINED(ATmega165PA) || \ + AVR8_PART_IS_DEFINED(ATmega168P) || \ + AVR8_PART_IS_DEFINED(ATmega169A) || \ + AVR8_PART_IS_DEFINED(ATmega16M1) || \ + AVR8_PART_IS_DEFINED(ATmega16U2) || \ + AVR8_PART_IS_DEFINED(ATmega16U4) || \ + AVR8_PART_IS_DEFINED(ATmega256RFA2) || \ + AVR8_PART_IS_DEFINED(ATmega324P) || \ + AVR8_PART_IS_DEFINED(ATmega325) || \ + AVR8_PART_IS_DEFINED(ATmega3250) || \ + AVR8_PART_IS_DEFINED(ATmega3250A) || \ + AVR8_PART_IS_DEFINED(ATmega3250P) || \ + AVR8_PART_IS_DEFINED(ATmega3250PA) || \ + AVR8_PART_IS_DEFINED(ATmega325A) || \ + AVR8_PART_IS_DEFINED(ATmega325P) || \ + AVR8_PART_IS_DEFINED(ATmega325PA) || \ + AVR8_PART_IS_DEFINED(ATmega329) || \ + AVR8_PART_IS_DEFINED(ATmega3290) || \ + AVR8_PART_IS_DEFINED(ATmega3290A) || \ + AVR8_PART_IS_DEFINED(ATmega3290P) || \ + AVR8_PART_IS_DEFINED(ATmega3290PA) || \ + AVR8_PART_IS_DEFINED(ATmega329A) || \ + AVR8_PART_IS_DEFINED(ATmega32M1) || \ + AVR8_PART_IS_DEFINED(ATmega32U2) || \ + AVR8_PART_IS_DEFINED(ATmega32U4) || \ + AVR8_PART_IS_DEFINED(ATmega48P) || \ + AVR8_PART_IS_DEFINED(ATmega644P) || \ + AVR8_PART_IS_DEFINED(ATmega645) || \ + AVR8_PART_IS_DEFINED(ATmega6450) || \ + AVR8_PART_IS_DEFINED(ATmega6450A) || \ + AVR8_PART_IS_DEFINED(ATmega6450P) || \ + AVR8_PART_IS_DEFINED(ATmega645A) || \ + AVR8_PART_IS_DEFINED(ATmega645P) || \ + AVR8_PART_IS_DEFINED(ATmega649) || \ + AVR8_PART_IS_DEFINED(ATmega6490) || \ + AVR8_PART_IS_DEFINED(ATmega6490A) || \ + AVR8_PART_IS_DEFINED(ATmega6490P) || \ + AVR8_PART_IS_DEFINED(ATmega649A) || \ + AVR8_PART_IS_DEFINED(ATmega649P) || \ + AVR8_PART_IS_DEFINED(ATmega64M1) || \ + AVR8_PART_IS_DEFINED(ATmega64RFA2) || \ + AVR8_PART_IS_DEFINED(ATmega8) || \ + AVR8_PART_IS_DEFINED(ATmega8515) || \ + AVR8_PART_IS_DEFINED(ATmega8535) || \ + AVR8_PART_IS_DEFINED(ATmega88P) || \ + AVR8_PART_IS_DEFINED(ATmega8A) || \ + AVR8_PART_IS_DEFINED(ATmega8U2) \ + ) + +/** Unspecified group */ +#define MEGA_UNSPECIFIED (MEGA_XX_UN0 || MEGA_XX_UN1 || MEGA_XX_UN2 || \ + MEGA_UNCATEGORIZED) + +/** @} */ + +/** megaAVR product line */ +#define MEGA (MEGA_XX0_1 || MEGA_XX4 || MEGA_XX8 || MEGA_XX || MEGA_RF || \ + MEGA_UNSPECIFIED) + +/** @} */ + +/** + * \defgroup tiny_part_macros_group tinyAVR parts + * + * @{ + */ + +/** + * \name tinyAVR groups + * @{ + */ + +/** Devices added to complete tinyAVR offering. + * Please do not use this group symbol as it is not intended + * to be permanent: the devices should be regrouped. + */ +#define TINY_UNCATEGORIZED ( \ + AVR8_PART_IS_DEFINED(ATtiny10) || \ + AVR8_PART_IS_DEFINED(ATtiny13) || \ + AVR8_PART_IS_DEFINED(ATtiny13A) || \ + AVR8_PART_IS_DEFINED(ATtiny1634) || \ + AVR8_PART_IS_DEFINED(ATtiny167) || \ + AVR8_PART_IS_DEFINED(ATtiny20) || \ + AVR8_PART_IS_DEFINED(ATtiny2313) || \ + AVR8_PART_IS_DEFINED(ATtiny2313A) || \ + AVR8_PART_IS_DEFINED(ATtiny24) || \ + AVR8_PART_IS_DEFINED(ATtiny24A) || \ + AVR8_PART_IS_DEFINED(ATtiny25) || \ + AVR8_PART_IS_DEFINED(ATtiny26) || \ + AVR8_PART_IS_DEFINED(ATtiny261) || \ + AVR8_PART_IS_DEFINED(ATtiny261A) || \ + AVR8_PART_IS_DEFINED(ATtiny4) || \ + AVR8_PART_IS_DEFINED(ATtiny40) || \ + AVR8_PART_IS_DEFINED(ATtiny4313) || \ + AVR8_PART_IS_DEFINED(ATtiny43U) || \ + AVR8_PART_IS_DEFINED(ATtiny44) || \ + AVR8_PART_IS_DEFINED(ATtiny44A) || \ + AVR8_PART_IS_DEFINED(ATtiny45) || \ + AVR8_PART_IS_DEFINED(ATtiny461) || \ + AVR8_PART_IS_DEFINED(ATtiny461A) || \ + AVR8_PART_IS_DEFINED(ATtiny48) || \ + AVR8_PART_IS_DEFINED(ATtiny5) || \ + AVR8_PART_IS_DEFINED(ATtiny828) || \ + AVR8_PART_IS_DEFINED(ATtiny84) || \ + AVR8_PART_IS_DEFINED(ATtiny84A) || \ + AVR8_PART_IS_DEFINED(ATtiny85) || \ + AVR8_PART_IS_DEFINED(ATtiny861) || \ + AVR8_PART_IS_DEFINED(ATtiny861A) || \ + AVR8_PART_IS_DEFINED(ATtiny87) || \ + AVR8_PART_IS_DEFINED(ATtiny88) || \ + AVR8_PART_IS_DEFINED(ATtiny9) \ + ) + +/** @} */ + +/** tinyAVR product line */ +#define TINY (TINY_UNCATEGORIZED) + +/** @} */ + +/** + * \defgroup sam_part_macros_group SAM parts + * @{ + */ + +/** + * \name SAM3S series + * @{ + */ +#define SAM3S1 ( \ + SAM_PART_IS_DEFINED(SAM3S1A) || \ + SAM_PART_IS_DEFINED(SAM3S1B) || \ + SAM_PART_IS_DEFINED(SAM3S1C) \ + ) + +#define SAM3S2 ( \ + SAM_PART_IS_DEFINED(SAM3S2A) || \ + SAM_PART_IS_DEFINED(SAM3S2B) || \ + SAM_PART_IS_DEFINED(SAM3S2C) \ + ) + +#define SAM3S4 ( \ + SAM_PART_IS_DEFINED(SAM3S4A) || \ + SAM_PART_IS_DEFINED(SAM3S4B) || \ + SAM_PART_IS_DEFINED(SAM3S4C) \ + ) + +#define SAM3S8 ( \ + SAM_PART_IS_DEFINED(SAM3S8B) || \ + SAM_PART_IS_DEFINED(SAM3S8C) \ + ) + +#define SAM3SD8 ( \ + SAM_PART_IS_DEFINED(SAM3SD8B) || \ + SAM_PART_IS_DEFINED(SAM3SD8C) \ + ) +/** @} */ + +/** + * \name SAM3U series + * @{ + */ +#define SAM3U1 ( \ + SAM_PART_IS_DEFINED(SAM3U1C) || \ + SAM_PART_IS_DEFINED(SAM3U1E) \ + ) + +#define SAM3U2 ( \ + SAM_PART_IS_DEFINED(SAM3U2C) || \ + SAM_PART_IS_DEFINED(SAM3U2E) \ + ) + +#define SAM3U4 ( \ + SAM_PART_IS_DEFINED(SAM3U4C) || \ + SAM_PART_IS_DEFINED(SAM3U4E) \ + ) +/** @} */ + +/** + * \name SAM3N series + * @{ + */ +#define SAM3N00 ( \ + SAM_PART_IS_DEFINED(SAM3N00A) || \ + SAM_PART_IS_DEFINED(SAM3N00B) \ + ) + +#define SAM3N0 ( \ + SAM_PART_IS_DEFINED(SAM3N0A) || \ + SAM_PART_IS_DEFINED(SAM3N0B) || \ + SAM_PART_IS_DEFINED(SAM3N0C) \ + ) + +#define SAM3N1 ( \ + SAM_PART_IS_DEFINED(SAM3N1A) || \ + SAM_PART_IS_DEFINED(SAM3N1B) || \ + SAM_PART_IS_DEFINED(SAM3N1C) \ + ) + +#define SAM3N2 ( \ + SAM_PART_IS_DEFINED(SAM3N2A) || \ + SAM_PART_IS_DEFINED(SAM3N2B) || \ + SAM_PART_IS_DEFINED(SAM3N2C) \ + ) + +#define SAM3N4 ( \ + SAM_PART_IS_DEFINED(SAM3N4A) || \ + SAM_PART_IS_DEFINED(SAM3N4B) || \ + SAM_PART_IS_DEFINED(SAM3N4C) \ + ) +/** @} */ + +/** + * \name SAM3X series + * @{ + */ +#define SAM3X4 ( \ + SAM_PART_IS_DEFINED(SAM3X4C) || \ + SAM_PART_IS_DEFINED(SAM3X4E) \ + ) + +#define SAM3X8 ( \ + SAM_PART_IS_DEFINED(SAM3X8C) || \ + SAM_PART_IS_DEFINED(SAM3X8E) || \ + SAM_PART_IS_DEFINED(SAM3X8H) \ + ) +/** @} */ + +/** + * \name SAM3A series + * @{ + */ +#define SAM3A4 ( \ + SAM_PART_IS_DEFINED(SAM3A4C) \ + ) + +#define SAM3A8 ( \ + SAM_PART_IS_DEFINED(SAM3A8C) \ + ) +/** @} */ + +/** + * \name SAM4S series + * @{ + */ +#define SAM4S2 ( \ + SAM_PART_IS_DEFINED(SAM4S2A) || \ + SAM_PART_IS_DEFINED(SAM4S2B) || \ + SAM_PART_IS_DEFINED(SAM4S2C) \ + ) + +#define SAM4S4 ( \ + SAM_PART_IS_DEFINED(SAM4S4A) || \ + SAM_PART_IS_DEFINED(SAM4S4B) || \ + SAM_PART_IS_DEFINED(SAM4S4C) \ + ) + +#define SAM4S8 ( \ + SAM_PART_IS_DEFINED(SAM4S8B) || \ + SAM_PART_IS_DEFINED(SAM4S8C) \ + ) + +#define SAM4S16 ( \ + SAM_PART_IS_DEFINED(SAM4S16B) || \ + SAM_PART_IS_DEFINED(SAM4S16C) \ + ) + +#define SAM4SA16 ( \ + SAM_PART_IS_DEFINED(SAM4SA16B) || \ + SAM_PART_IS_DEFINED(SAM4SA16C) \ + ) + +#define SAM4SD16 ( \ + SAM_PART_IS_DEFINED(SAM4SD16B) || \ + SAM_PART_IS_DEFINED(SAM4SD16C) \ + ) + +#define SAM4SD32 ( \ + SAM_PART_IS_DEFINED(SAM4SD32B) || \ + SAM_PART_IS_DEFINED(SAM4SD32C) \ + ) +/** @} */ + +/** + * \name SAM4L series + * @{ + */ +#define SAM4LS ( \ + SAM_PART_IS_DEFINED(SAM4LS2A) || \ + SAM_PART_IS_DEFINED(SAM4LS2B) || \ + SAM_PART_IS_DEFINED(SAM4LS2C) || \ + SAM_PART_IS_DEFINED(SAM4LS4A) || \ + SAM_PART_IS_DEFINED(SAM4LS4B) || \ + SAM_PART_IS_DEFINED(SAM4LS4C) || \ + SAM_PART_IS_DEFINED(SAM4LS8A) || \ + SAM_PART_IS_DEFINED(SAM4LS8B) || \ + SAM_PART_IS_DEFINED(SAM4LS8C) \ + ) + +#define SAM4LC ( \ + SAM_PART_IS_DEFINED(SAM4LC2A) || \ + SAM_PART_IS_DEFINED(SAM4LC2B) || \ + SAM_PART_IS_DEFINED(SAM4LC2C) || \ + SAM_PART_IS_DEFINED(SAM4LC4A) || \ + SAM_PART_IS_DEFINED(SAM4LC4B) || \ + SAM_PART_IS_DEFINED(SAM4LC4C) || \ + SAM_PART_IS_DEFINED(SAM4LC8A) || \ + SAM_PART_IS_DEFINED(SAM4LC8B) || \ + SAM_PART_IS_DEFINED(SAM4LC8C) \ + ) +/** @} */ + +/** + * \name SAMD20 series + * @{ + */ +#define SAMD20J ( \ + SAM_PART_IS_DEFINED(SAMD20J14) || \ + SAM_PART_IS_DEFINED(SAMD20J15) || \ + SAM_PART_IS_DEFINED(SAMD20J16) || \ + SAM_PART_IS_DEFINED(SAMD20J17) || \ + SAM_PART_IS_DEFINED(SAMD20J18) \ + ) + +#define SAMD20G ( \ + SAM_PART_IS_DEFINED(SAMD20G14) || \ + SAM_PART_IS_DEFINED(SAMD20G15) || \ + SAM_PART_IS_DEFINED(SAMD20G16) || \ + SAM_PART_IS_DEFINED(SAMD20G17) || \ + SAM_PART_IS_DEFINED(SAMD20G17U) || \ + SAM_PART_IS_DEFINED(SAMD20G18) || \ + SAM_PART_IS_DEFINED(SAMD20G18U) \ + ) + +#define SAMD20E ( \ + SAM_PART_IS_DEFINED(SAMD20E14) || \ + SAM_PART_IS_DEFINED(SAMD20E15) || \ + SAM_PART_IS_DEFINED(SAMD20E16) || \ + SAM_PART_IS_DEFINED(SAMD20E17) || \ + SAM_PART_IS_DEFINED(SAMD20E18) \ + ) +/** @} */ + +/** + * \name SAMD21 series + * @{ + */ +#define SAMD21J ( \ + SAM_PART_IS_DEFINED(SAMD21J15A) || \ + SAM_PART_IS_DEFINED(SAMD21J16A) || \ + SAM_PART_IS_DEFINED(SAMD21J17A) || \ + SAM_PART_IS_DEFINED(SAMD21J18A) || \ + SAM_PART_IS_DEFINED(SAMD21J15B) || \ + SAM_PART_IS_DEFINED(SAMD21J16B) \ + ) + +#define SAMD21G ( \ + SAM_PART_IS_DEFINED(SAMD21G15A) || \ + SAM_PART_IS_DEFINED(SAMD21G16A) || \ + SAM_PART_IS_DEFINED(SAMD21G17A) || \ + SAM_PART_IS_DEFINED(SAMD21G17AU) || \ + SAM_PART_IS_DEFINED(SAMD21G18A) || \ + SAM_PART_IS_DEFINED(SAMD21G18AU) || \ + SAM_PART_IS_DEFINED(SAMD21G15B) || \ + SAM_PART_IS_DEFINED(SAMD21G16B) || \ + SAM_PART_IS_DEFINED(SAMD21G15L) || \ + SAM_PART_IS_DEFINED(SAMD21G16L) \ + ) + +#define SAMD21GXXL ( \ + SAM_PART_IS_DEFINED(SAMD21G15L) || \ + SAM_PART_IS_DEFINED(SAMD21G16L) \ + ) + +#define SAMD21E ( \ + SAM_PART_IS_DEFINED(SAMD21E15A) || \ + SAM_PART_IS_DEFINED(SAMD21E16A) || \ + SAM_PART_IS_DEFINED(SAMD21E17A) || \ + SAM_PART_IS_DEFINED(SAMD21E18A) || \ + SAM_PART_IS_DEFINED(SAMD21E15B) || \ + SAM_PART_IS_DEFINED(SAMD21E15BU) || \ + SAM_PART_IS_DEFINED(SAMD21E16B) || \ + SAM_PART_IS_DEFINED(SAMD21E16BU) || \ + SAM_PART_IS_DEFINED(SAMD21E15L) || \ + SAM_PART_IS_DEFINED(SAMD21E16L) \ + ) + +#define SAMD21EXXL ( \ + SAM_PART_IS_DEFINED(SAMD21E15L) || \ + SAM_PART_IS_DEFINED(SAMD21E16L) \ + ) + +/** @} */ + +/** + * \name SAMR21 series + * @{ + */ +#define SAMR21G ( \ + SAM_PART_IS_DEFINED(SAMR21G16A) || \ + SAM_PART_IS_DEFINED(SAMR21G17A) || \ + SAM_PART_IS_DEFINED(SAMR21G18A) \ + ) + +#define SAMR21E ( \ + SAM_PART_IS_DEFINED(SAMR21E16A) || \ + SAM_PART_IS_DEFINED(SAMR21E17A) || \ + SAM_PART_IS_DEFINED(SAMR21E18A) || \ + SAM_PART_IS_DEFINED(SAMR21E19A) \ + ) +/** @} */ + +/** + * \name SAMD09 series + * @{ + */ +#define SAMD09C ( \ + SAM_PART_IS_DEFINED(SAMD09C13A) \ + ) + +#define SAMD09D ( \ + SAM_PART_IS_DEFINED(SAMD09D14A) \ + ) +/** @} */ + +/** + * \name SAMD10 series + * @{ + */ +#define SAMD10C ( \ + SAM_PART_IS_DEFINED(SAMD10C12A) || \ + SAM_PART_IS_DEFINED(SAMD10C13A) || \ + SAM_PART_IS_DEFINED(SAMD10C14A) \ + ) + +#define SAMD10DS ( \ + SAM_PART_IS_DEFINED(SAMD10D12AS) || \ + SAM_PART_IS_DEFINED(SAMD10D13AS) || \ + SAM_PART_IS_DEFINED(SAMD10D14AS) \ + ) + +#define SAMD10DM ( \ + SAM_PART_IS_DEFINED(SAMD10D12AM) || \ + SAM_PART_IS_DEFINED(SAMD10D13AM) || \ + SAM_PART_IS_DEFINED(SAMD10D14AM) \ + ) +/** @} */ + +/** + * \name SAMD11 series + * @{ + */ +#define SAMD11C ( \ + SAM_PART_IS_DEFINED(SAMD11C14A) \ + ) + +#define SAMD11DS ( \ + SAM_PART_IS_DEFINED(SAMD11D14AS) \ + ) + +#define SAMD11DM ( \ + SAM_PART_IS_DEFINED(SAMD11D14AM) \ + ) +/** @} */ + +/** + * \name SAML21 series + * @{ + */ +#define SAML21E ( \ + SAM_PART_IS_DEFINED(SAML21E18A) || \ + SAM_PART_IS_DEFINED(SAML21E15B) || \ + SAM_PART_IS_DEFINED(SAML21E16B) || \ + SAM_PART_IS_DEFINED(SAML21E17B) || \ + SAM_PART_IS_DEFINED(SAML21E18B) \ + ) + +#define SAML21G ( \ + SAM_PART_IS_DEFINED(SAML21G18A) || \ + SAM_PART_IS_DEFINED(SAML21G16B) || \ + SAM_PART_IS_DEFINED(SAML21G17B) || \ + SAM_PART_IS_DEFINED(SAML21G18B) \ + ) + +#define SAML21J ( \ + SAM_PART_IS_DEFINED(SAML21J18A) || \ + SAM_PART_IS_DEFINED(SAML21J16B) || \ + SAM_PART_IS_DEFINED(SAML21J17B) || \ + SAM_PART_IS_DEFINED(SAML21J18B) \ + ) + +/* Group for SAML21 A variant: SAML21[E/G/J][18]A */ +#define SAML21XXXA ( \ + SAM_PART_IS_DEFINED(SAML21E18A) || \ + SAM_PART_IS_DEFINED(SAML21G18A) || \ + SAM_PART_IS_DEFINED(SAML21J18A) \ + ) + +/* Group for SAML21 B variant: SAML21[E/G/J][15/16/1718]B */ +#define SAML21XXXB ( \ + SAM_PART_IS_DEFINED(SAML21E15B) || \ + SAM_PART_IS_DEFINED(SAML21E16B) || \ + SAM_PART_IS_DEFINED(SAML21E17B) || \ + SAM_PART_IS_DEFINED(SAML21E18B) || \ + SAM_PART_IS_DEFINED(SAML21G16B) || \ + SAM_PART_IS_DEFINED(SAML21G17B) || \ + SAM_PART_IS_DEFINED(SAML21G18B) || \ + SAM_PART_IS_DEFINED(SAML21J16B) || \ + SAM_PART_IS_DEFINED(SAML21J17B) || \ + SAM_PART_IS_DEFINED(SAML21J18B) \ + ) + +/** @} */ + +/** + * \name SAML22 series + * @{ + */ +#define SAML22N ( \ + SAM_PART_IS_DEFINED(SAML22N16A) || \ + SAM_PART_IS_DEFINED(SAML22N17A) || \ + SAM_PART_IS_DEFINED(SAML22N18A) \ + ) + +#define SAML22G ( \ + SAM_PART_IS_DEFINED(SAML22G16A) || \ + SAM_PART_IS_DEFINED(SAML22G17A) || \ + SAM_PART_IS_DEFINED(SAML22G18A) \ + ) + +#define SAML22J ( \ + SAM_PART_IS_DEFINED(SAML22J16A) || \ + SAM_PART_IS_DEFINED(SAML22J17A) || \ + SAM_PART_IS_DEFINED(SAML22J18A) \ + ) +/** @} */ + +/** + * \name SAMDA0 series + * @{ + */ +#define SAMDA0J ( \ + SAM_PART_IS_DEFINED(SAMDA0J14A) || \ + SAM_PART_IS_DEFINED(SAMDA0J15A) || \ + SAM_PART_IS_DEFINED(SAMDA0J16A) \ + ) + +#define SAMDA0G ( \ + SAM_PART_IS_DEFINED(SAMDA0G14A) || \ + SAM_PART_IS_DEFINED(SAMDA0G15A) || \ + SAM_PART_IS_DEFINED(SAMDA0G16A) \ + ) + +#define SAMDA0E ( \ + SAM_PART_IS_DEFINED(SAMDA0E14A) || \ + SAM_PART_IS_DEFINED(SAMDA0E15A) || \ + SAM_PART_IS_DEFINED(SAMDA0E16A) \ + ) +/** @} */ + +/** + * \name SAMDA1 series + * @{ + */ +#define SAMDA1J ( \ + SAM_PART_IS_DEFINED(SAMDA1J14A) || \ + SAM_PART_IS_DEFINED(SAMDA1J15A) || \ + SAM_PART_IS_DEFINED(SAMDA1J16A) \ + ) + +#define SAMDA1G ( \ + SAM_PART_IS_DEFINED(SAMDA1G14A) || \ + SAM_PART_IS_DEFINED(SAMDA1G15A) || \ + SAM_PART_IS_DEFINED(SAMDA1G16A) \ + ) + +#define SAMDA1E ( \ + SAM_PART_IS_DEFINED(SAMDA1E14A) || \ + SAM_PART_IS_DEFINED(SAMDA1E15A) || \ + SAM_PART_IS_DEFINED(SAMDA1E16A) \ + ) +/** @} */ + +/** + * \name SAMC20 series + * @{ + */ +#define SAMC20E ( \ + SAM_PART_IS_DEFINED(SAMC20E15A) || \ + SAM_PART_IS_DEFINED(SAMC20E16A) || \ + SAM_PART_IS_DEFINED(SAMC20E17A) || \ + SAM_PART_IS_DEFINED(SAMC20E18A) \ + ) + +#define SAMC20G ( \ + SAM_PART_IS_DEFINED(SAMC20G15A) || \ + SAM_PART_IS_DEFINED(SAMC20G16A) || \ + SAM_PART_IS_DEFINED(SAMC20G17A) || \ + SAM_PART_IS_DEFINED(SAMC20G18A) \ + ) + +#define SAMC20J ( \ + SAM_PART_IS_DEFINED(SAMC20J15A) || \ + SAM_PART_IS_DEFINED(SAMC20J16A) || \ + SAM_PART_IS_DEFINED(SAMC20J17A) || \ + SAM_PART_IS_DEFINED(SAMC20J18A) \ + ) +/** @} */ + +/** + * \name SAMC21 series + * @{ + */ +#define SAMC21E ( \ + SAM_PART_IS_DEFINED(SAMC21E15A) || \ + SAM_PART_IS_DEFINED(SAMC21E16A) || \ + SAM_PART_IS_DEFINED(SAMC21E17A) || \ + SAM_PART_IS_DEFINED(SAMC21E18A) \ + ) + +#define SAMC21G ( \ + SAM_PART_IS_DEFINED(SAMC21G15A) || \ + SAM_PART_IS_DEFINED(SAMC21G16A) || \ + SAM_PART_IS_DEFINED(SAMC21G17A) || \ + SAM_PART_IS_DEFINED(SAMC21G18A) \ + ) + +#define SAMC21J ( \ + SAM_PART_IS_DEFINED(SAMC21J15A) || \ + SAM_PART_IS_DEFINED(SAMC21J16A) || \ + SAM_PART_IS_DEFINED(SAMC21J17A) || \ + SAM_PART_IS_DEFINED(SAMC21J18A) \ + ) +/** @} */ + +/** + * \name SAM4E series + * @{ + */ +#define SAM4E8 ( \ + SAM_PART_IS_DEFINED(SAM4E8C) || \ + SAM_PART_IS_DEFINED(SAM4E8E) \ + ) + +#define SAM4E16 ( \ + SAM_PART_IS_DEFINED(SAM4E16C) || \ + SAM_PART_IS_DEFINED(SAM4E16E) \ + ) +/** @} */ + +/** + * \name SAM4N series + * @{ + */ +#define SAM4N8 ( \ + SAM_PART_IS_DEFINED(SAM4N8A) || \ + SAM_PART_IS_DEFINED(SAM4N8B) || \ + SAM_PART_IS_DEFINED(SAM4N8C) \ + ) + +#define SAM4N16 ( \ + SAM_PART_IS_DEFINED(SAM4N16B) || \ + SAM_PART_IS_DEFINED(SAM4N16C) \ + ) +/** @} */ + +/** + * \name SAM4C series + * @{ + */ +#define SAM4C4_0 ( \ + SAM_PART_IS_DEFINED(SAM4C4C_0) \ + ) + +#define SAM4C4_1 ( \ + SAM_PART_IS_DEFINED(SAM4C4C_1) \ + ) + +#define SAM4C4 (SAM4C4_0 || SAM4C4_1) + +#define SAM4C8_0 ( \ + SAM_PART_IS_DEFINED(SAM4C8C_0) \ + ) + +#define SAM4C8_1 ( \ + SAM_PART_IS_DEFINED(SAM4C8C_1) \ + ) + +#define SAM4C8 (SAM4C8_0 || SAM4C8_1) + +#define SAM4C16_0 ( \ + SAM_PART_IS_DEFINED(SAM4C16C_0) \ + ) + +#define SAM4C16_1 ( \ + SAM_PART_IS_DEFINED(SAM4C16C_1) \ + ) + +#define SAM4C16 (SAM4C16_0 || SAM4C16_1) + +#define SAM4C32_0 ( \ + SAM_PART_IS_DEFINED(SAM4C32C_0) ||\ + SAM_PART_IS_DEFINED(SAM4C32E_0) \ + ) + +#define SAM4C32_1 ( \ + SAM_PART_IS_DEFINED(SAM4C32C_1) ||\ + SAM_PART_IS_DEFINED(SAM4C32E_1) \ + ) + + +#define SAM4C32 (SAM4C32_0 || SAM4C32_1) + +/** @} */ + +/** + * \name SAM4CM series + * @{ + */ +#define SAM4CMP8_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMP8C_0) \ + ) + +#define SAM4CMP8_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMP8C_1) \ + ) + +#define SAM4CMP8 (SAM4CMP8_0 || SAM4CMP8_1) + +#define SAM4CMP16_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMP16C_0) \ + ) + +#define SAM4CMP16_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMP16C_1) \ + ) + +#define SAM4CMP16 (SAM4CMP16_0 || SAM4CMP16_1) + +#define SAM4CMP32_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMP32C_0) \ + ) + +#define SAM4CMP32_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMP32C_1) \ + ) + +#define SAM4CMP32 (SAM4CMP32_0 || SAM4CMP32_1) + +#define SAM4CMS4_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMS4C_0) \ + ) + +#define SAM4CMS4_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMS4C_1) \ + ) + +#define SAM4CMS4 (SAM4CMS4_0 || SAM4CMS4_1) + +#define SAM4CMS8_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMS8C_0) \ + ) + +#define SAM4CMS8_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMS8C_1) \ + ) + +#define SAM4CMS8 (SAM4CMS8_0 || SAM4CMS8_1) + +#define SAM4CMS16_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMS16C_0) \ + ) + +#define SAM4CMS16_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMS16C_1) \ + ) + +#define SAM4CMS16 (SAM4CMS16_0 || SAM4CMS16_1) + +#define SAM4CMS32_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMS32C_0) \ + ) + +#define SAM4CMS32_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMS32C_1) \ + ) + +#define SAM4CMS32 (SAM4CMS32_0 || SAM4CMS32_1) + +/** @} */ + +/** + * \name SAM4CP series + * @{ + */ +#define SAM4CP16_0 ( \ + SAM_PART_IS_DEFINED(SAM4CP16B_0) \ + ) + +#define SAM4CP16_1 ( \ + SAM_PART_IS_DEFINED(SAM4CP16B_1) \ + ) + +#define SAM4CP16 (SAM4CP16_0 || SAM4CP16_1) +/** @} */ + +/** + * \name SAMG series + * @{ + */ +#define SAMG51 ( \ + SAM_PART_IS_DEFINED(SAMG51G18) \ + ) + +#define SAMG53 ( \ + SAM_PART_IS_DEFINED(SAMG53G19) ||\ + SAM_PART_IS_DEFINED(SAMG53N19) \ + ) + +#define SAMG54 ( \ + SAM_PART_IS_DEFINED(SAMG54G19) ||\ + SAM_PART_IS_DEFINED(SAMG54J19) ||\ + SAM_PART_IS_DEFINED(SAMG54N19) \ + ) + +#define SAMG55 ( \ + SAM_PART_IS_DEFINED(SAMG55G18) ||\ + SAM_PART_IS_DEFINED(SAMG55G19) ||\ + SAM_PART_IS_DEFINED(SAMG55J18) ||\ + SAM_PART_IS_DEFINED(SAMG55J19) ||\ + SAM_PART_IS_DEFINED(SAMG55N19) \ + ) +/** @} */ + +/** + * \name SAMV71 series + * @{ + */ +#define SAMV71J ( \ + SAM_PART_IS_DEFINED(SAMV71J19) || \ + SAM_PART_IS_DEFINED(SAMV71J20) || \ + SAM_PART_IS_DEFINED(SAMV71J21) \ + ) + +#define SAMV71N ( \ + SAM_PART_IS_DEFINED(SAMV71N19) || \ + SAM_PART_IS_DEFINED(SAMV71N20) || \ + SAM_PART_IS_DEFINED(SAMV71N21) \ + ) + +#define SAMV71Q ( \ + SAM_PART_IS_DEFINED(SAMV71Q19) || \ + SAM_PART_IS_DEFINED(SAMV71Q20) || \ + SAM_PART_IS_DEFINED(SAMV71Q21) \ + ) +/** @} */ + +/** + * \name SAMV70 series + * @{ + */ +#define SAMV70J ( \ + SAM_PART_IS_DEFINED(SAMV70J19) || \ + SAM_PART_IS_DEFINED(SAMV70J20) \ + ) + +#define SAMV70N ( \ + SAM_PART_IS_DEFINED(SAMV70N19) || \ + SAM_PART_IS_DEFINED(SAMV70N20) \ + ) + +#define SAMV70Q ( \ + SAM_PART_IS_DEFINED(SAMV70Q19) || \ + SAM_PART_IS_DEFINED(SAMV70Q20) \ + ) +/** @} */ + +/** + * \name SAMS70 series + * @{ + */ +#define SAMS70J ( \ + SAM_PART_IS_DEFINED(SAMS70J19) || \ + SAM_PART_IS_DEFINED(SAMS70J20) || \ + SAM_PART_IS_DEFINED(SAMS70J21) \ + ) + +#define SAMS70N ( \ + SAM_PART_IS_DEFINED(SAMS70N19) || \ + SAM_PART_IS_DEFINED(SAMS70N20) || \ + SAM_PART_IS_DEFINED(SAMS70N21) \ + ) + +#define SAMS70Q ( \ + SAM_PART_IS_DEFINED(SAMS70Q19) || \ + SAM_PART_IS_DEFINED(SAMS70Q20) || \ + SAM_PART_IS_DEFINED(SAMS70Q21) \ + ) +/** @} */ + +/** + * \name SAME70 series + * @{ + */ +#define SAME70J ( \ + SAM_PART_IS_DEFINED(SAME70J19) || \ + SAM_PART_IS_DEFINED(SAME70J20) || \ + SAM_PART_IS_DEFINED(SAME70J21) \ + ) + +#define SAME70N ( \ + SAM_PART_IS_DEFINED(SAME70N19) || \ + SAM_PART_IS_DEFINED(SAME70N20) || \ + SAM_PART_IS_DEFINED(SAME70N21) \ + ) + +#define SAME70Q ( \ + SAM_PART_IS_DEFINED(SAME70Q19) || \ + SAM_PART_IS_DEFINED(SAME70Q20) || \ + SAM_PART_IS_DEFINED(SAME70Q21) \ + ) +/** @} */ + +/** + * \name SAM families + * @{ + */ +/** SAM3S Family */ +#define SAM3S (SAM3S1 || SAM3S2 || SAM3S4 || SAM3S8 || SAM3SD8) + +/** SAM3U Family */ +#define SAM3U (SAM3U1 || SAM3U2 || SAM3U4) + +/** SAM3N Family */ +#define SAM3N (SAM3N00 || SAM3N0 || SAM3N1 || SAM3N2 || SAM3N4) + +/** SAM3XA Family */ +#define SAM3XA (SAM3X4 || SAM3X8 || SAM3A4 || SAM3A8) + +/** SAM4S Family */ +#define SAM4S (SAM4S2 || SAM4S4 || SAM4S8 || SAM4S16 || SAM4SA16 || SAM4SD16 || SAM4SD32) + +/** SAM4L Family */ +#define SAM4L (SAM4LS || SAM4LC) + +/** SAMD20 Family */ +#define SAMD20 (SAMD20J || SAMD20G || SAMD20E) + +/** SAMD21 Family */ +#define SAMD21 (SAMD21J || SAMD21G || SAMD21E) + +/** SAMD09 Family */ +#define SAMD09 (SAMD09C || SAMD09D) + +/** SAMD10 Family */ +#define SAMD10 (SAMD10C || SAMD10DS || SAMD10DM) + +/** SAMD11 Family */ +#define SAMD11 (SAMD11C || SAMD11DS || SAMD11DM) + +/** SAMDA1 Family */ +#define SAMDA1 (SAMDA1J || SAMDA1G || SAMDA1E) + +/** SAMD Family */ +#define SAMD (SAMD20 || SAMD21 || SAMD09 || SAMD10 || SAMD11 || SAMDA1) + +/** SAMR21 Family */ +#define SAMR21 (SAMR21G || SAMR21E) + +/** SAML21 Family */ +#define SAML21 (SAML21J || SAML21G || SAML21E) + +/** SAML22 Family */ +#define SAML22 (SAML22J || SAML22G || SAML22N) +/** SAMC20 Family */ +#define SAMC20 (SAMC20J || SAMC20G || SAMC20E) + +/** SAMC21 Family */ +#define SAMC21 (SAMC21J || SAMC21G || SAMC21E) + +/** SAM4E Family */ +#define SAM4E (SAM4E8 || SAM4E16) + +/** SAM4N Family */ +#define SAM4N (SAM4N8 || SAM4N16) + +/** SAM4C Family */ +#define SAM4C_0 (SAM4C4_0 || SAM4C8_0 || SAM4C16_0 || SAM4C32_0) +#define SAM4C_1 (SAM4C4_1 || SAM4C8_1 || SAM4C16_1 || SAM4C32_1) +#define SAM4C (SAM4C4 || SAM4C8 || SAM4C16 || SAM4C32) + +/** SAM4CM Family */ +#define SAM4CM_0 (SAM4CMP8_0 || SAM4CMP16_0 || SAM4CMP32_0 || \ + SAM4CMS4_0 || SAM4CMS8_0 || SAM4CMS16_0 || SAM4CMS32_0) +#define SAM4CM_1 (SAM4CMP8_1 || SAM4CMP16_1 || SAM4CMP32_1 || \ + SAM4CMS4_1 || SAM4CMS8_1 || SAM4CMS16_1 || SAM4CMS32_1) +#define SAM4CM (SAM4CMP8 || SAM4CMP16 || SAM4CMP32 || \ + SAM4CMS4 || SAM4CMS8 || SAM4CMS16 || SAM4CMS32) + +/** SAM4CP Family */ +#define SAM4CP_0 (SAM4CP16_0) +#define SAM4CP_1 (SAM4CP16_1) +#define SAM4CP (SAM4CP16) + +/** SAMG Family */ +#define SAMG (SAMG51 || SAMG53 || SAMG54 || SAMG55) + +/** SAMV71 Family */ +#define SAMV71 (SAMV71J || SAMV71N || SAMV71Q) + +/** SAMV70 Family */ +#define SAMV70 (SAMV70J || SAMV70N || SAMV70Q) + +/** SAME70 Family */ +#define SAME70 (SAME70J || SAME70N || SAME70Q) + +/** SAMS70 Family */ +#define SAMS70 (SAMS70J || SAMS70N || SAMS70Q) + +/** SAM0 product line (cortex-m0+) */ +#define SAM0 (SAMD20 || SAMD21 || SAMR21 || SAMD10 || SAMD11 || SAML21 ||\ + SAMDA1 || SAMC20 || SAMC21 || SAML22 || SAMD09) + +/** @} */ + +/** SAM product line */ +#define SAM (SAM3S || SAM3U || SAM3N || SAM3XA || SAM4S || SAM4L || SAM4E || \ + SAM0 || SAM4N || SAM4C || SAM4CM || SAM4CP || SAMG || SAMV71 || SAMV70 || SAME70 || SAMS70) + +/** @} */ + +/** @} */ + +/** @} */ + +#endif /* ATMEL_PARTS_H */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/pinmux.c b/feather_sensor_transmit/libraries/Adafruit_ASFcore/pinmux.c new file mode 100644 index 0000000..a2c9c7c --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/pinmux.c @@ -0,0 +1,311 @@ +/** + * \file + * + * \brief SAM Pin Multiplexer Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#include + +/** + * \internal + * Writes out a given configuration of a Port pin configuration to the + * hardware module. + * + * \note If the pin direction is set as an output, the pull-up/pull-down input + * configuration setting is ignored. + * + * \param[in] port Base of the PORT module to configure + * \param[in] pin_mask Mask of the port pin to configure + * \param[in] config Configuration settings for the pin + */ +static void _system_pinmux_config( + PortGroup *const port, + const uint32_t pin_mask, + const struct system_pinmux_config *const config) +{ + Assert(port); + Assert(config); + + /* Track the configuration bits into a temporary variable before writing */ + uint32_t pin_cfg = 0; + + /* Enabled powersave mode, don't create configuration */ + if (!config->powersave) { + /* Enable the pin peripheral MUX flag if non-GPIO selected (pinmux will + * be written later) and store the new MUX mask */ + if (config->mux_position != SYSTEM_PINMUX_GPIO) { + pin_cfg |= PORT_WRCONFIG_PMUXEN; + pin_cfg |= (config->mux_position << PORT_WRCONFIG_PMUX_Pos); + } + + /* Check if the user has requested that the input buffer be enabled */ + if ((config->direction == SYSTEM_PINMUX_PIN_DIR_INPUT) || + (config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK)) { + /* Enable input buffer flag */ + pin_cfg |= PORT_WRCONFIG_INEN; + + /* Enable pull-up/pull-down control flag if requested */ + if (config->input_pull != SYSTEM_PINMUX_PIN_PULL_NONE) { + pin_cfg |= PORT_WRCONFIG_PULLEN; + } + + /* Clear the port DIR bits to disable the output buffer */ + port->DIRCLR.reg = pin_mask; + } + + /* Check if the user has requested that the output buffer be enabled */ + if ((config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT) || + (config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK)) { + /* Cannot use a pull-up if the output driver is enabled, + * if requested the input buffer can only sample the current + * output state */ + pin_cfg &= ~PORT_WRCONFIG_PULLEN; + } + } else { + port->DIRCLR.reg = pin_mask; + } + + /* The Write Configuration register (WRCONFIG) requires the + * pins to to grouped into two 16-bit half-words - split them out here */ + uint32_t lower_pin_mask = (pin_mask & 0xFFFF); + uint32_t upper_pin_mask = (pin_mask >> 16); + + /* Configure the lower 16-bits of the port to the desired configuration, + * including the pin peripheral multiplexer just in case it is enabled */ + port->WRCONFIG.reg + = (lower_pin_mask << PORT_WRCONFIG_PINMASK_Pos) | + pin_cfg | PORT_WRCONFIG_WRPMUX | PORT_WRCONFIG_WRPINCFG; + + /* Configure the upper 16-bits of the port to the desired configuration, + * including the pin peripheral multiplexer just in case it is enabled */ + port->WRCONFIG.reg + = (upper_pin_mask << PORT_WRCONFIG_PINMASK_Pos) | + pin_cfg | PORT_WRCONFIG_WRPMUX | PORT_WRCONFIG_WRPINCFG | + PORT_WRCONFIG_HWSEL; + + if(!config->powersave) { + /* Set the pull-up state once the port pins are configured if one was + * requested and it does not violate the valid set of port + * configurations */ + if (pin_cfg & PORT_WRCONFIG_PULLEN) { + /* Set the OUT register bits to enable the pull-up if requested, + * clear to enable pull-down */ + if (config->input_pull == SYSTEM_PINMUX_PIN_PULL_UP) { + port->OUTSET.reg = pin_mask; + } else { + port->OUTCLR.reg = pin_mask; + } + } + + /* Check if the user has requested that the output buffer be enabled */ + if ((config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT) || + (config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK)) { + /* Set the port DIR bits to enable the output buffer */ + port->DIRSET.reg = pin_mask; + } + } +} + +/** + * \brief Writes a Port pin configuration to the hardware module. + * + * Writes out a given configuration of a Port pin configuration to the hardware + * module. + * + * \note If the pin direction is set as an output, the pull-up/pull-down input + * configuration setting is ignored. + * + * \param[in] gpio_pin Index of the GPIO pin to configure + * \param[in] config Configuration settings for the pin + */ +void system_pinmux_pin_set_config( + const uint8_t gpio_pin, + const struct system_pinmux_config *const config) +{ + PortGroup *const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); + uint32_t pin_mask = (1UL << (gpio_pin % 32)); + + _system_pinmux_config(port, pin_mask, config); +} + +/** + * \brief Writes a Port pin group configuration to the hardware module. + * + * Writes out a given configuration of a Port pin group configuration to the + * hardware module. + * + * \note If the pin direction is set as an output, the pull-up/pull-down input + * configuration setting is ignored. + * + * \param[in] port Base of the PORT module to configure + * \param[in] mask Mask of the port pin(s) to configure + * \param[in] config Configuration settings for the pin + */ +void system_pinmux_group_set_config( + PortGroup *const port, + const uint32_t mask, + const struct system_pinmux_config *const config) +{ + Assert(port); + + for (int i = 0; i < 32; i++) { + if (mask & (1UL << i)) { + _system_pinmux_config(port, (1UL << i), config); + } + } +} + +/** + * \brief Configures the input sampling mode for a group of pins. + * + * Configures the input sampling mode for a group of pins, to + * control when the physical I/O pin value is sampled and + * stored inside the microcontroller. + * + * \param[in] port Base of the PORT module to configure + * \param[in] mask Mask of the port pin(s) to configure + * \param[in] mode New pin sampling mode to configure + */ +void system_pinmux_group_set_input_sample_mode( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_sample mode) +{ + Assert(port); + + if (mode == SYSTEM_PINMUX_PIN_SAMPLE_ONDEMAND) { + port->CTRL.reg |= mask; + } else { + port->CTRL.reg &= ~mask; + } +} + +#ifdef FEATURE_SYSTEM_PINMUX_SLEWRATE_LIMITER +/** + * \brief Configures the output slew rate mode for a group of pins. + * + * Configures the output slew rate mode for a group of pins, to + * control the speed at which the physical output pin can react to + * logical changes of the I/O pin value. + * + * \param[in] port Base of the PORT module to configure + * \param[in] mask Mask of the port pin(s) to configure + * \param[in] mode New pin slew rate mode to configure + */ +void system_pinmux_group_set_output_slew_rate( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_slew_rate mode) +{ + Assert(port); + + for (int i = 0; i < 32; i++) { + if (mask & (1UL << i)) { + if (mode == SYSTEM_PINMUX_PIN_SLEW_RATE_LIMITED) { + port->PINCFG[i].reg |= PORT_PINCFG_SLEWLIM; + } else { + port->PINCFG[i].reg &= ~PORT_PINCFG_SLEWLIM; + } + } + } +} +#endif + +#ifdef FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTH +/** + * \brief Configures the output driver strength mode for a group of pins. + * + * Configures the output drive strength for a group of pins, to + * control the amount of current the pad is able to sink/source. + * + * \param[in] port Base of the PORT module to configure + * \param[in] mask Mask of the port pin(s) to configure + * \param[in] mode New output driver strength mode to configure + */ +void system_pinmux_group_set_output_strength( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_strength mode) +{ + Assert(port); + + for (int i = 0; i < 32; i++) { + if (mask & (1UL << i)) { + if (mode == SYSTEM_PINMUX_PIN_STRENGTH_HIGH) { + port->PINCFG[i].reg |= PORT_PINCFG_DRVSTR; + } else { + port->PINCFG[i].reg &= ~PORT_PINCFG_DRVSTR; + } + } + } +} +#endif + +#ifdef FEATURE_SYSTEM_PINMUX_OPEN_DRAIN +/** + * \brief Configures the output driver mode for a group of pins. + * + * Configures the output driver mode for a group of pins, to + * control the pad behavior. + * + * \param[in] port Base of the PORT module to configure + * \param[in] mask Mask of the port pin(s) to configure + * \param[in] mode New pad output driver mode to configure + */ +void system_pinmux_group_set_output_drive( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_drive mode) +{ + Assert(port); + + for (int i = 0; i < 32; i++) { + if (mask & (1UL << i)) { + if (mode == SYSTEM_PINMUX_PIN_DRIVE_OPEN_DRAIN) { + port->PINCFG[i].reg |= PORT_PINCFG_ODRAIN; + } else { + port->PINCFG[i].reg &= ~PORT_PINCFG_ODRAIN; + } + } + } +} +#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/pinmux.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/pinmux.h new file mode 100644 index 0000000..7a441cc --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/pinmux.h @@ -0,0 +1,678 @@ +/** + * \file + * + * \brief SAM Pin Multiplexer Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef PINMUX_H_INCLUDED +#define PINMUX_H_INCLUDED + +/** + * \defgroup asfdoc_sam0_system_pinmux_group SAM System Pin Multiplexer (SYSTEM PINMUX) Driver + * + * This driver for Atmel® | SMART ARM®-based microcontrollers provides + * an interface for the configuration and management of the device's physical + * I/O Pins, to alter the direction and input/drive characteristics as well as + * to configure the pin peripheral multiplexer selection. + * + * The following peripheral is used by this module: + * - PORT (Port I/O Management) + * + * The following devices can use this module: + * - Atmel | SMART SAM D20/D21 + * - Atmel | SMART SAM R21 + * - Atmel | SMART SAM D09/D10/D11 + * - Atmel | SMART SAM L21/L22 + * - Atmel | SMART SAM DA1 + * - Atmel | SMART SAM C20/C21 + * + * Physically, the modules are interconnected within the device as shown in the + * following diagram: + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_system_pinmux_prerequisites + * - \ref asfdoc_sam0_system_pinmux_module_overview + * - \ref asfdoc_sam0_system_pinmux_special_considerations + * - \ref asfdoc_sam0_system_pinmux_extra_info + * - \ref asfdoc_sam0_system_pinmux_examples + * - \ref asfdoc_sam0_system_pinmux_api_overview + * + * + * \section asfdoc_sam0_system_pinmux_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * + * \section asfdoc_sam0_system_pinmux_module_overview Module Overview + * + * The SAM devices contain a number of General Purpose I/O pins, used to + * interface the user application logic and internal hardware peripherals to + * an external system. The Pin Multiplexer (PINMUX) driver provides a method + * of configuring the individual pin peripheral multiplexers to select + * alternate pin functions. + * + * \subsection asfdoc_sam0_system_pinmux_features Driver Feature Macro Definition + * + * + * + * + * + * + * + * + * + *
Driver Feature MacroSupported devices
FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTHSAM L21, SAM C20/C21
+ * \note The specific features are only available in the driver when the + * selected device supports those features. + * + * \subsection asfdoc_sam0_system_pinmux_physical_logical_pins Physical and Logical GPIO Pins + * SAM devices use two naming conventions for the I/O pins in the device; one + * physical and one logical. Each physical pin on a device package is assigned + * both a physical port and pin identifier (e.g. "PORTA.0") as well as a + * monotonically incrementing logical GPIO number (e.g. "GPIO0"). While the + * former is used to map physical pins to their physical internal device module + * counterparts, for simplicity the design of this driver uses the logical GPIO + * numbers instead. + * + * \subsection asfdoc_sam0_system_pinmux_peripheral_muxing Peripheral Multiplexing + * SAM devices contain a peripheral MUX, which is individually controllable + * for each I/O pin of the device. The peripheral MUX allows you to select the + * function of a physical package pin - whether it will be controlled as a user + * controllable GPIO pin, or whether it will be connected internally to one of + * several peripheral modules (such as an I2C module). When a pin is + * configured in GPIO mode, other peripherals connected to the same pin will be + * disabled. + * + * \subsection asfdoc_sam0_system_pinmux_pad_characteristics Special Pad Characteristics + * There are several special modes that can be selected on one or more I/O pins + * of the device, which alter the input and output characteristics of the pad. + * + * \subsubsection asfdoc_sam0_system_pinmux_drive_strength Drive Strength + * The Drive Strength configures the strength of the output driver on the + * pad. Normally, there is a fixed current limit that each I/O pin can safely + * drive, however some I/O pads offer a higher drive mode which increases this + * limit for that I/O pin at the expense of an increased power consumption. + * + * \subsubsection asfdoc_sam0_system_pinmux_slew_rate Slew Rate + * The Slew Rate configures the slew rate of the output driver, limiting the + * rate at which the pad output voltage can change with time. + * + * \subsubsection asfdoc_sam0_system_pinmux_input_sample_mode Input Sample Mode + * The Input Sample Mode configures the input sampler buffer of the pad. By + * default, the input buffer is only sampled "on-demand", i.e. when the user + * application attempts to read from the input buffer. This mode is the most + * power efficient, but increases the latency of the input sample by two clock + * cycles of the port clock. To reduce latency, the input sampler can instead + * be configured to always sample the input buffer on each port clock cycle, at + * the expense of an increased power consumption. + * + * \subsection asfdoc_sam0_system_pinmux_module_overview_physical Physical Connection + * + * \ref asfdoc_sam0_system_pinmux_intconnections "The diagram below" shows + * how this module is interconnected within the device: + * + * \anchor asfdoc_sam0_system_pinmux_intconnections + * \dot + * digraph overview { + * node [label="Port Pad" shape=square] pad; + * + * subgraph driver { + * node [label="Peripheral MUX" shape=trapezium] pinmux; + * node [label="GPIO Module" shape=ellipse shape=ellipse style=filled fillcolor=lightgray] gpio; + * node [label="Other Peripheral Modules" shape=ellipse style=filled fillcolor=lightgray] peripherals; + * } + * + * pinmux -> gpio; + * pad -> pinmux; + * pinmux -> peripherals; + * } + * \enddot + * + * \section asfdoc_sam0_system_pinmux_special_considerations Special Considerations + * + * The SAM port pin input sampling mode is set in groups of four physical + * pins; setting the sampling mode of any pin in a sub-group of eight I/O pins + * will configure the sampling mode of the entire sub-group. + * + * High Drive Strength output driver mode is not available on all device pins - + * refer to your device specific datasheet. + * + * + * \section asfdoc_sam0_system_pinmux_extra_info Extra Information + * + * For extra information, see \ref asfdoc_sam0_system_pinmux_extra. This includes: + * - \ref asfdoc_sam0_system_pinmux_extra_acronyms + * - \ref asfdoc_sam0_system_pinmux_extra_dependencies + * - \ref asfdoc_sam0_system_pinmux_extra_errata + * - \ref asfdoc_sam0_system_pinmux_extra_history + * + * + * \section asfdoc_sam0_system_pinmux_examples Examples + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_system_pinmux_exqsg. + * + * + * \section asfdoc_sam0_system_pinmux_api_overview API Overview + * @{ + */ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/*@{*/ +#if (SAML21) || (SAMC20) || (SAMC21) || defined(__DOXYGEN__) +/** Output Driver Strength Selection feature support */ +# define FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTH +#endif +/*@}*/ + +/** Peripheral multiplexer index to select GPIO mode for a pin */ +#define SYSTEM_PINMUX_GPIO (1 << 7) + +/** + * \brief Port pin direction configuration enum. + * + * Enum for the possible pin direction settings of the port pin configuration + * structure, to indicate the direction the pin should use. + */ +enum system_pinmux_pin_dir { + /** The pin's input buffer should be enabled, so that the pin state can + * be read */ + SYSTEM_PINMUX_PIN_DIR_INPUT, + /** The pin's output buffer should be enabled, so that the pin state can + * be set (but not read back) */ + SYSTEM_PINMUX_PIN_DIR_OUTPUT, + /** The pin's output and input buffers should both be enabled, so that the + * pin state can be set and read back */ + SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK, +}; + +/** + * \brief Port pin input pull configuration enum. + * + * Enum for the possible pin pull settings of the port pin configuration + * structure, to indicate the type of logic level pull the pin should use. + */ +enum system_pinmux_pin_pull { + /** No logical pull should be applied to the pin */ + SYSTEM_PINMUX_PIN_PULL_NONE, + /** Pin should be pulled up when idle */ + SYSTEM_PINMUX_PIN_PULL_UP, + /** Pin should be pulled down when idle */ + SYSTEM_PINMUX_PIN_PULL_DOWN, +}; + +/** + * \brief Port pin digital input sampling mode enum. + * + * Enum for the possible input sampling modes for the port pin configuration + * structure, to indicate the type of sampling a port pin should use. + */ +enum system_pinmux_pin_sample { + /** Pin input buffer should continuously sample the pin state */ + SYSTEM_PINMUX_PIN_SAMPLE_CONTINUOUS, + /** Pin input buffer should be enabled when the IN register is read */ + SYSTEM_PINMUX_PIN_SAMPLE_ONDEMAND, +}; + +/** + * \brief Port pin configuration structure. + * + * Configuration structure for a port pin instance. This structure should + * be initialized by the \ref system_pinmux_get_config_defaults() function + * before being modified by the user application. + */ +struct system_pinmux_config { + /** MUX index of the peripheral that should control the pin, if peripheral + * control is desired. For GPIO use, this should be set to + * \ref SYSTEM_PINMUX_GPIO. */ + uint8_t mux_position; + + /** Port buffer input/output direction */ + enum system_pinmux_pin_dir direction; + + /** Logic level pull of the input buffer */ + enum system_pinmux_pin_pull input_pull; + + /** Enable lowest possible powerstate on the pin. + * + * \note All other configurations will be ignored, the pin will be disabled. + */ + bool powersave; +}; + +/** \name Configuration and Initialization + * @{ + */ + +/** + * \brief Initializes a Port pin configuration structure to defaults. + * + * Initializes a given Port pin configuration structure to a set of + * known default values. This function should be called on all new + * instances of these configuration structures before being modified by the + * user application. + * + * The default configuration is as follows: + * \li Non peripheral (i.e. GPIO) controlled + * \li Input mode with internal pull-up enabled + * + * \param[out] config Configuration structure to initialize to default values + */ +static inline void system_pinmux_get_config_defaults( + struct system_pinmux_config *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Default configuration values */ + config->mux_position = SYSTEM_PINMUX_GPIO; + config->direction = SYSTEM_PINMUX_PIN_DIR_INPUT; + config->input_pull = SYSTEM_PINMUX_PIN_PULL_UP; + config->powersave = false; +} + +void system_pinmux_pin_set_config( + const uint8_t gpio_pin, + const struct system_pinmux_config *const config); + +void system_pinmux_group_set_config( + PortGroup *const port, + const uint32_t mask, + const struct system_pinmux_config *const config); + +/** @} */ + +/** \name Special Mode Configuration (Physical Group Orientated) + * @{ + */ + +/** + * \brief Retrieves the PORT module group instance from a given GPIO pin number. + * + * Retrieves the PORT module group instance associated with a given logical + * GPIO pin number. + * + * \param[in] gpio_pin Index of the GPIO pin to convert + * + * \return Base address of the associated PORT module. + */ +static inline PortGroup* system_pinmux_get_group_from_gpio_pin( + const uint8_t gpio_pin) +{ + uint8_t port_index = (gpio_pin / 128); + uint8_t group_index = (gpio_pin / 32); + + /* Array of available ports */ + Port *const ports[PORT_INST_NUM] = PORT_INSTS; + + if (port_index < PORT_INST_NUM) { + return &(ports[port_index]->Group[group_index]); + } else { + Assert(false); + return NULL; + } +} + +void system_pinmux_group_set_input_sample_mode( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_sample mode); + +/** @} */ + +/** \name Special Mode Configuration (Logical Pin Orientated) + * @{ + */ + +/** + * \brief Retrieves the currently selected MUX position of a logical pin. + * + * Retrieves the selected MUX peripheral on a given logical GPIO pin. + * + * \param[in] gpio_pin Index of the GPIO pin to configure + * + * \return Currently selected peripheral index on the specified pin. + */ +static inline uint8_t system_pinmux_pin_get_mux_position( + const uint8_t gpio_pin) +{ + PortGroup *const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); + uint32_t pin_index = (gpio_pin % 32); + + if (!(port->PINCFG[pin_index].reg & PORT_PINCFG_PMUXEN)) { + return SYSTEM_PINMUX_GPIO; + } + + uint32_t pmux_reg = port->PMUX[pin_index / 2].reg; + + if (pin_index & 1) { + return (pmux_reg & PORT_PMUX_PMUXO_Msk) >> PORT_PMUX_PMUXO_Pos; + } + else { + return (pmux_reg & PORT_PMUX_PMUXE_Msk) >> PORT_PMUX_PMUXE_Pos; + } +} + +/** + * \brief Configures the input sampling mode for a GPIO pin. + * + * Configures the input sampling mode for a GPIO input, to + * control when the physical I/O pin value is sampled and + * stored inside the microcontroller. + * + * \param[in] gpio_pin Index of the GPIO pin to configure + * \param[in] mode New pin sampling mode to configure + */ +static inline void system_pinmux_pin_set_input_sample_mode( + const uint8_t gpio_pin, + const enum system_pinmux_pin_sample mode) +{ + PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); + uint32_t pin_index = (gpio_pin % 32); + + if (mode == SYSTEM_PINMUX_PIN_SAMPLE_ONDEMAND) { + port->CTRL.reg |= (1 << pin_index); + } else { + port->CTRL.reg &= ~(1 << pin_index); + } +} + +/** @} */ + +#ifdef FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTH +/** + * \brief Port pin drive output strength enum. + * + * Enum for the possible output drive strengths for the port pin + * configuration structure, to indicate the driver strength the pin should + * use. + */ +enum system_pinmux_pin_strength { + /** Normal output driver strength */ + SYSTEM_PINMUX_PIN_STRENGTH_NORMAL, + /** High current output driver strength */ + SYSTEM_PINMUX_PIN_STRENGTH_HIGH, +}; + +/** + * \brief Configures the output driver strength mode for a GPIO pin. + * + * Configures the output drive strength for a GPIO output, to + * control the amount of current the pad is able to sink/source. + * + * \param[in] gpio_pin Index of the GPIO pin to configure + * \param[in] mode New output driver strength mode to configure + */ +static inline void system_pinmux_pin_set_output_strength( + const uint8_t gpio_pin, + const enum system_pinmux_pin_strength mode) +{ + PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); + uint32_t pin_index = (gpio_pin % 32); + + if (mode == SYSTEM_PINMUX_PIN_STRENGTH_HIGH) { + port->PINCFG[pin_index].reg |= PORT_PINCFG_DRVSTR; + } + else { + port->PINCFG[pin_index].reg &= ~PORT_PINCFG_DRVSTR; + } +} + +void system_pinmux_group_set_output_strength( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_strength mode); +#endif + +#ifdef FEATURE_SYSTEM_PINMUX_SLEWRATE_LIMITER +/** + * \brief Port pin output slew rate enum. + * + * Enum for the possible output drive slew rates for the port pin + * configuration structure, to indicate the driver slew rate the pin should + * use. + */ +enum system_pinmux_pin_slew_rate { + /** Normal pin output slew rate */ + SYSTEM_PINMUX_PIN_SLEW_RATE_NORMAL, + /** Enable slew rate limiter on the pin */ + SYSTEM_PINMUX_PIN_SLEW_RATE_LIMITED, +}; + +/** + * \brief Configures the output slew rate mode for a GPIO pin. + * + * Configures the output slew rate mode for a GPIO output, to + * control the speed at which the physical output pin can react to + * logical changes of the I/O pin value. + * + * \param[in] gpio_pin Index of the GPIO pin to configure + * \param[in] mode New pin slew rate mode to configure + */ +static inline void system_pinmux_pin_set_output_slew_rate( + const uint8_t gpio_pin, + const enum system_pinmux_pin_slew_rate mode) +{ + PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); + uint32_t pin_index = (gpio_pin % 32); + + if (mode == SYSTEM_PINMUX_PIN_SLEW_RATE_LIMITED) { + port->PINCFG[pin_index].reg |= PORT_PINCFG_SLEWLIM; + } + else { + port->PINCFG[pin_index].reg &= ~PORT_PINCFG_SLEWLIM; + } +} + +void system_pinmux_group_set_output_slew_rate( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_slew_rate mode); +#endif + +#ifdef FEATURE_SYSTEM_PINMUX_OPEN_DRAIN +/** + * \brief Port pin output drive mode enum. + * + * Enum for the possible output drive modes for the port pin configuration + * structure, to indicate the output mode the pin should use. + */ +enum system_pinmux_pin_drive { + /** Use totem pole output drive mode */ + SYSTEM_PINMUX_PIN_DRIVE_TOTEM, + /** Use open drain output drive mode */ + SYSTEM_PINMUX_PIN_DRIVE_OPEN_DRAIN, +}; + +/** + * \brief Configures the output driver mode for a GPIO pin. + * + * Configures the output driver mode for a GPIO output, to + * control the pad behavior. + * + * \param[in] gpio_pin Index of the GPIO pin to configure + * \param[in] mode New pad output driver mode to configure + */ +static inline void system_pinmux_pin_set_output_drive( + const uint8_t gpio_pin, + const enum system_pinmux_pin_drive mode) +{ + PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); + uint32_t pin_index = (gpio_pin % 32); + + if (mode == SYSTEM_PINMUX_PIN_DRIVE_OPEN_DRAIN) { + port->PINCFG[pin_index].reg |= PORT_PINCFG_ODRAIN; + } + else { + port->PINCFG[pin_index].reg &= ~PORT_PINCFG_ODRAIN; + } +} + +void system_pinmux_group_set_output_drive( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_drive mode); +#endif + +#ifdef __cplusplus +} +#endif + +/** @} */ + +/** + * \page asfdoc_sam0_system_pinmux_extra Extra Information for SYSTEM PINMUX Driver + * + * \section asfdoc_sam0_system_pinmux_extra_acronyms Acronyms + * The table below presents the acronyms used in this module: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
AcronymDescription
GPIOGeneral Purpose Input/Output
MUXMultiplexer
+ * + * + * \section asfdoc_sam0_system_pinmux_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - None + * + * + * \section asfdoc_sam0_system_pinmux_extra_errata Errata + * There are no errata related to this driver. + * + * + * \section asfdoc_sam0_system_pinmux_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Changelog
Removed code of open drain, slew limit and drive strength + * features
Fixed broken sampling mode function implementations, which wrote + * corrupt configuration values to the device registers
Added missing NULL pointer asserts to the PORT driver functions
Initial Release
+ */ + +/** + * \page asfdoc_sam0_system_pinmux_exqsg Examples for SYSTEM PINMUX Driver + * + * This is a list of the available Quick Start guides (QSGs) and example + * applications for \ref asfdoc_sam0_system_pinmux_group. QSGs are simple + * examples with step-by-step instructions to configure and use this driver in a + * selection of use cases. Note that a QSG can be compiled as a standalone + * application or be added to the user application. + * + * - \subpage asfdoc_sam0_system_pinmux_basic_use_case + * + * \page asfdoc_sam0_system_pinmux_document_revision_history Document Revision History + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Doc. Rev. + * Date + * Comments + *
42121F08/2015Added support for SAM L21/L22, SAM DA1, and SAM C20/C21
42121E12/2014Added support for SAM R21 and SAM D10/D11
42121D01/2014Added support for SAM D21
42121C09/2013Fixed incorrect documentation for the device pin sampling mode
42121B06/2013Corrected documentation typos
42121A06/2013Initial release
+ */ + +#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/power.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/power.h new file mode 100644 index 0000000..5e90585 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/power.h @@ -0,0 +1,224 @@ +/** + * \file + * + * \brief SAM Power related functionality + * + * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef POWER_H_INCLUDED +#define POWER_H_INCLUDED + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \addtogroup asfdoc_sam0_system_group + * @{ + */ + +/** + * \brief Voltage references within the device. + * + * List of available voltage references (VREF) that may be used within the + * device. + */ +enum system_voltage_reference { + /** Temperature sensor voltage reference. */ + SYSTEM_VOLTAGE_REFERENCE_TEMPSENSE, + /** Bandgap voltage reference. */ + SYSTEM_VOLTAGE_REFERENCE_BANDGAP, +}; + +/** + * \brief Device sleep modes. + * + * List of available sleep modes in the device. A table of clocks available in + * different sleep modes can be found in \ref asfdoc_sam0_system_module_overview_sleep_mode. + */ +enum system_sleepmode { + /** IDLE 0 sleep mode. */ + SYSTEM_SLEEPMODE_IDLE_0, + /** IDLE 1 sleep mode. */ + SYSTEM_SLEEPMODE_IDLE_1, + /** IDLE 2 sleep mode. */ + SYSTEM_SLEEPMODE_IDLE_2, + /** Standby sleep mode. */ + SYSTEM_SLEEPMODE_STANDBY, +}; + + + +/** + * \name Voltage References + * @{ + */ + +/** + * \brief Enable the selected voltage reference + * + * Enables the selected voltage reference source, making the voltage reference + * available on a pin as well as an input source to the analog peripherals. + * + * \param[in] vref Voltage reference to enable + */ +static inline void system_voltage_reference_enable( + const enum system_voltage_reference vref) +{ + switch (vref) { + case SYSTEM_VOLTAGE_REFERENCE_TEMPSENSE: + SYSCTRL->VREF.reg |= SYSCTRL_VREF_TSEN; + break; + + case SYSTEM_VOLTAGE_REFERENCE_BANDGAP: + SYSCTRL->VREF.reg |= SYSCTRL_VREF_BGOUTEN; + break; + + default: + Assert(false); + return; + } +} + +/** + * \brief Disable the selected voltage reference + * + * Disables the selected voltage reference source. + * + * \param[in] vref Voltage reference to disable + */ +static inline void system_voltage_reference_disable( + const enum system_voltage_reference vref) +{ + switch (vref) { + case SYSTEM_VOLTAGE_REFERENCE_TEMPSENSE: + SYSCTRL->VREF.reg &= ~SYSCTRL_VREF_TSEN; + break; + + case SYSTEM_VOLTAGE_REFERENCE_BANDGAP: + SYSCTRL->VREF.reg &= ~SYSCTRL_VREF_BGOUTEN; + break; + + default: + Assert(false); + return; + } +} + +/** + * @} + */ + + +/** + * \name Device Sleep Control + * @{ + */ + +/** + * \brief Set the sleep mode of the device + * + * Sets the sleep mode of the device; the configured sleep mode will be entered + * upon the next call of the \ref system_sleep() function. + * + * For an overview of which systems are disabled in sleep for the different + * sleep modes, see \ref asfdoc_sam0_system_module_overview_sleep_mode. + * + * \param[in] sleep_mode Sleep mode to configure for the next sleep operation + * + * \retval STATUS_OK Operation completed successfully + * \retval STATUS_ERR_INVALID_ARG The requested sleep mode was invalid or not + * available + */ +static inline enum status_code system_set_sleepmode( + const enum system_sleepmode sleep_mode) +{ +#if (SAMD20 || SAMD21) + /* Errata: Make sure that the Flash does not power all the way down + * when in sleep mode. */ + NVMCTRL->CTRLB.bit.SLEEPPRM = NVMCTRL_CTRLB_SLEEPPRM_DISABLED_Val; +#endif + + switch (sleep_mode) { + case SYSTEM_SLEEPMODE_IDLE_0: + case SYSTEM_SLEEPMODE_IDLE_1: + case SYSTEM_SLEEPMODE_IDLE_2: + SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk; + PM->SLEEP.reg = sleep_mode; + break; + + case SYSTEM_SLEEPMODE_STANDBY: + SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; + break; + + default: + return STATUS_ERR_INVALID_ARG; + } + + return STATUS_OK; +} + +/** + * \brief Put the system to sleep waiting for interrupt + * + * Executes a device DSB (Data Synchronization Barrier) instruction to ensure + * all ongoing memory accesses have completed, then a WFI (Wait For Interrupt) + * instruction to place the device into the sleep mode specified by + * \ref system_set_sleepmode until woken by an interrupt. + */ +static inline void system_sleep(void) +{ + __DSB(); + __WFI(); +} + +/** + * @} + */ + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* POWER_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h new file mode 100644 index 0000000..4447927 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h @@ -0,0 +1,581 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef _MRECURSION_H_ +#define _MRECURSION_H_ + +/** + * \defgroup group_sam0_utils_mrecursion Preprocessor - Macro Recursion + * + * \ingroup group_sam0_utils + * + * @{ + */ + +#include "preprocessor.h" + +#define DEC_256 255 +#define DEC_255 254 +#define DEC_254 253 +#define DEC_253 252 +#define DEC_252 251 +#define DEC_251 250 +#define DEC_250 249 +#define DEC_249 248 +#define DEC_248 247 +#define DEC_247 246 +#define DEC_246 245 +#define DEC_245 244 +#define DEC_244 243 +#define DEC_243 242 +#define DEC_242 241 +#define DEC_241 240 +#define DEC_240 239 +#define DEC_239 238 +#define DEC_238 237 +#define DEC_237 236 +#define DEC_236 235 +#define DEC_235 234 +#define DEC_234 233 +#define DEC_233 232 +#define DEC_232 231 +#define DEC_231 230 +#define DEC_230 229 +#define DEC_229 228 +#define DEC_228 227 +#define DEC_227 226 +#define DEC_226 225 +#define DEC_225 224 +#define DEC_224 223 +#define DEC_223 222 +#define DEC_222 221 +#define DEC_221 220 +#define DEC_220 219 +#define DEC_219 218 +#define DEC_218 217 +#define DEC_217 216 +#define DEC_216 215 +#define DEC_215 214 +#define DEC_214 213 +#define DEC_213 212 +#define DEC_212 211 +#define DEC_211 210 +#define DEC_210 209 +#define DEC_209 208 +#define DEC_208 207 +#define DEC_207 206 +#define DEC_206 205 +#define DEC_205 204 +#define DEC_204 203 +#define DEC_203 202 +#define DEC_202 201 +#define DEC_201 200 +#define DEC_200 199 +#define DEC_199 198 +#define DEC_198 197 +#define DEC_197 196 +#define DEC_196 195 +#define DEC_195 194 +#define DEC_194 193 +#define DEC_193 192 +#define DEC_192 191 +#define DEC_191 190 +#define DEC_190 189 +#define DEC_189 188 +#define DEC_188 187 +#define DEC_187 186 +#define DEC_186 185 +#define DEC_185 184 +#define DEC_184 183 +#define DEC_183 182 +#define DEC_182 181 +#define DEC_181 180 +#define DEC_180 179 +#define DEC_179 178 +#define DEC_178 177 +#define DEC_177 176 +#define DEC_176 175 +#define DEC_175 174 +#define DEC_174 173 +#define DEC_173 172 +#define DEC_172 171 +#define DEC_171 170 +#define DEC_170 169 +#define DEC_169 168 +#define DEC_168 167 +#define DEC_167 166 +#define DEC_166 165 +#define DEC_165 164 +#define DEC_164 163 +#define DEC_163 162 +#define DEC_162 161 +#define DEC_161 160 +#define DEC_160 159 +#define DEC_159 158 +#define DEC_158 157 +#define DEC_157 156 +#define DEC_156 155 +#define DEC_155 154 +#define DEC_154 153 +#define DEC_153 152 +#define DEC_152 151 +#define DEC_151 150 +#define DEC_150 149 +#define DEC_149 148 +#define DEC_148 147 +#define DEC_147 146 +#define DEC_146 145 +#define DEC_145 144 +#define DEC_144 143 +#define DEC_143 142 +#define DEC_142 141 +#define DEC_141 140 +#define DEC_140 139 +#define DEC_139 138 +#define DEC_138 137 +#define DEC_137 136 +#define DEC_136 135 +#define DEC_135 134 +#define DEC_134 133 +#define DEC_133 132 +#define DEC_132 131 +#define DEC_131 130 +#define DEC_130 129 +#define DEC_129 128 +#define DEC_128 127 +#define DEC_127 126 +#define DEC_126 125 +#define DEC_125 124 +#define DEC_124 123 +#define DEC_123 122 +#define DEC_122 121 +#define DEC_121 120 +#define DEC_120 119 +#define DEC_119 118 +#define DEC_118 117 +#define DEC_117 116 +#define DEC_116 115 +#define DEC_115 114 +#define DEC_114 113 +#define DEC_113 112 +#define DEC_112 111 +#define DEC_111 110 +#define DEC_110 109 +#define DEC_109 108 +#define DEC_108 107 +#define DEC_107 106 +#define DEC_106 105 +#define DEC_105 104 +#define DEC_104 103 +#define DEC_103 102 +#define DEC_102 101 +#define DEC_101 100 +#define DEC_100 99 +#define DEC_99 98 +#define DEC_98 97 +#define DEC_97 96 +#define DEC_96 95 +#define DEC_95 94 +#define DEC_94 93 +#define DEC_93 92 +#define DEC_92 91 +#define DEC_91 90 +#define DEC_90 89 +#define DEC_89 88 +#define DEC_88 87 +#define DEC_87 86 +#define DEC_86 85 +#define DEC_85 84 +#define DEC_84 83 +#define DEC_83 82 +#define DEC_82 81 +#define DEC_81 80 +#define DEC_80 79 +#define DEC_79 78 +#define DEC_78 77 +#define DEC_77 76 +#define DEC_76 75 +#define DEC_75 74 +#define DEC_74 73 +#define DEC_73 72 +#define DEC_72 71 +#define DEC_71 70 +#define DEC_70 69 +#define DEC_69 68 +#define DEC_68 67 +#define DEC_67 66 +#define DEC_66 65 +#define DEC_65 64 +#define DEC_64 63 +#define DEC_63 62 +#define DEC_62 61 +#define DEC_61 60 +#define DEC_60 59 +#define DEC_59 58 +#define DEC_58 57 +#define DEC_57 56 +#define DEC_56 55 +#define DEC_55 54 +#define DEC_54 53 +#define DEC_53 52 +#define DEC_52 51 +#define DEC_51 50 +#define DEC_50 49 +#define DEC_49 48 +#define DEC_48 47 +#define DEC_47 46 +#define DEC_46 45 +#define DEC_45 44 +#define DEC_44 43 +#define DEC_43 42 +#define DEC_42 41 +#define DEC_41 40 +#define DEC_40 39 +#define DEC_39 38 +#define DEC_38 37 +#define DEC_37 36 +#define DEC_36 35 +#define DEC_35 34 +#define DEC_34 33 +#define DEC_33 32 +#define DEC_32 31 +#define DEC_31 30 +#define DEC_30 29 +#define DEC_29 28 +#define DEC_28 27 +#define DEC_27 26 +#define DEC_26 25 +#define DEC_25 24 +#define DEC_24 23 +#define DEC_23 22 +#define DEC_22 21 +#define DEC_21 20 +#define DEC_20 19 +#define DEC_19 18 +#define DEC_18 17 +#define DEC_17 16 +#define DEC_16 15 +#define DEC_15 14 +#define DEC_14 13 +#define DEC_13 12 +#define DEC_12 11 +#define DEC_11 10 +#define DEC_10 9 +#define DEC_9 8 +#define DEC_8 7 +#define DEC_7 6 +#define DEC_6 5 +#define DEC_5 4 +#define DEC_4 3 +#define DEC_3 2 +#define DEC_2 1 +#define DEC_1 0 +#define DEC_(n) DEC_##n + + +/** Maximal number of repetitions supported by MRECURSION. */ +#define MRECURSION_LIMIT 256 + +/** \brief Macro recursion. + * + * This macro represents a horizontal repetition construct. + * + * \param[in] count The number of repetitious calls to macro. Valid values + * range from 0 to MRECURSION_LIMIT. + * \param[in] macro A binary operation of the form macro(data, n). This macro + * is expanded by MRECURSION with the current repetition number + * and the auxiliary data argument. + * \param[in] data A recursive threshold, building on this to decline by times + * defined with param count. + * + * \return macro(data-count+1,0) macro(data-count+2,1)...macro(data,count-1) + */ +#define MRECURSION(count, macro, data) TPASTE2(MRECURSION, count) (macro, data) + +#define MRECURSION0( macro, data) +#define MRECURSION1( macro, data) MRECURSION0( macro, DEC_(data)) macro(data, 0) +#define MRECURSION2( macro, data) MRECURSION1( macro, DEC_(data)) macro(data, 1) +#define MRECURSION3( macro, data) MRECURSION2( macro, DEC_(data)) macro(data, 2) +#define MRECURSION4( macro, data) MRECURSION3( macro, DEC_(data)) macro(data, 3) +#define MRECURSION5( macro, data) MRECURSION4( macro, DEC_(data)) macro(data, 4) +#define MRECURSION6( macro, data) MRECURSION5( macro, DEC_(data)) macro(data, 5) +#define MRECURSION7( macro, data) MRECURSION6( macro, DEC_(data)) macro(data, 6) +#define MRECURSION8( macro, data) MRECURSION7( macro, DEC_(data)) macro(data, 7) +#define MRECURSION9( macro, data) MRECURSION8( macro, DEC_(data)) macro(data, 8) +#define MRECURSION10( macro, data) MRECURSION9( macro, DEC_(data)) macro(data, 9) +#define MRECURSION11( macro, data) MRECURSION10( macro, DEC_(data)) macro(data, 10) +#define MRECURSION12( macro, data) MRECURSION11( macro, DEC_(data)) macro(data, 11) +#define MRECURSION13( macro, data) MRECURSION12( macro, DEC_(data)) macro(data, 12) +#define MRECURSION14( macro, data) MRECURSION13( macro, DEC_(data)) macro(data, 13) +#define MRECURSION15( macro, data) MRECURSION14( macro, DEC_(data)) macro(data, 14) +#define MRECURSION16( macro, data) MRECURSION15( macro, DEC_(data)) macro(data, 15) +#define MRECURSION17( macro, data) MRECURSION16( macro, DEC_(data)) macro(data, 16) +#define MRECURSION18( macro, data) MRECURSION17( macro, DEC_(data)) macro(data, 17) +#define MRECURSION19( macro, data) MRECURSION18( macro, DEC_(data)) macro(data, 18) +#define MRECURSION20( macro, data) MRECURSION19( macro, DEC_(data)) macro(data, 19) +#define MRECURSION21( macro, data) MRECURSION20( macro, DEC_(data)) macro(data, 20) +#define MRECURSION22( macro, data) MRECURSION21( macro, DEC_(data)) macro(data, 21) +#define MRECURSION23( macro, data) MRECURSION22( macro, DEC_(data)) macro(data, 22) +#define MRECURSION24( macro, data) MRECURSION23( macro, DEC_(data)) macro(data, 23) +#define MRECURSION25( macro, data) MRECURSION24( macro, DEC_(data)) macro(data, 24) +#define MRECURSION26( macro, data) MRECURSION25( macro, DEC_(data)) macro(data, 25) +#define MRECURSION27( macro, data) MRECURSION26( macro, DEC_(data)) macro(data, 26) +#define MRECURSION28( macro, data) MRECURSION27( macro, DEC_(data)) macro(data, 27) +#define MRECURSION29( macro, data) MRECURSION28( macro, DEC_(data)) macro(data, 28) +#define MRECURSION30( macro, data) MRECURSION29( macro, DEC_(data)) macro(data, 29) +#define MRECURSION31( macro, data) MRECURSION30( macro, DEC_(data)) macro(data, 30) +#define MRECURSION32( macro, data) MRECURSION31( macro, DEC_(data)) macro(data, 31) +#define MRECURSION33( macro, data) MRECURSION32( macro, DEC_(data)) macro(data, 32) +#define MRECURSION34( macro, data) MRECURSION33( macro, DEC_(data)) macro(data, 33) +#define MRECURSION35( macro, data) MRECURSION34( macro, DEC_(data)) macro(data, 34) +#define MRECURSION36( macro, data) MRECURSION35( macro, DEC_(data)) macro(data, 35) +#define MRECURSION37( macro, data) MRECURSION36( macro, DEC_(data)) macro(data, 36) +#define MRECURSION38( macro, data) MRECURSION37( macro, DEC_(data)) macro(data, 37) +#define MRECURSION39( macro, data) MRECURSION38( macro, DEC_(data)) macro(data, 38) +#define MRECURSION40( macro, data) MRECURSION39( macro, DEC_(data)) macro(data, 39) +#define MRECURSION41( macro, data) MRECURSION40( macro, DEC_(data)) macro(data, 40) +#define MRECURSION42( macro, data) MRECURSION41( macro, DEC_(data)) macro(data, 41) +#define MRECURSION43( macro, data) MRECURSION42( macro, DEC_(data)) macro(data, 42) +#define MRECURSION44( macro, data) MRECURSION43( macro, DEC_(data)) macro(data, 43) +#define MRECURSION45( macro, data) MRECURSION44( macro, DEC_(data)) macro(data, 44) +#define MRECURSION46( macro, data) MRECURSION45( macro, DEC_(data)) macro(data, 45) +#define MRECURSION47( macro, data) MRECURSION46( macro, DEC_(data)) macro(data, 46) +#define MRECURSION48( macro, data) MRECURSION47( macro, DEC_(data)) macro(data, 47) +#define MRECURSION49( macro, data) MRECURSION48( macro, DEC_(data)) macro(data, 48) +#define MRECURSION50( macro, data) MRECURSION49( macro, DEC_(data)) macro(data, 49) +#define MRECURSION51( macro, data) MRECURSION50( macro, DEC_(data)) macro(data, 50) +#define MRECURSION52( macro, data) MRECURSION51( macro, DEC_(data)) macro(data, 51) +#define MRECURSION53( macro, data) MRECURSION52( macro, DEC_(data)) macro(data, 52) +#define MRECURSION54( macro, data) MRECURSION53( macro, DEC_(data)) macro(data, 53) +#define MRECURSION55( macro, data) MRECURSION54( macro, DEC_(data)) macro(data, 54) +#define MRECURSION56( macro, data) MRECURSION55( macro, DEC_(data)) macro(data, 55) +#define MRECURSION57( macro, data) MRECURSION56( macro, DEC_(data)) macro(data, 56) +#define MRECURSION58( macro, data) MRECURSION57( macro, DEC_(data)) macro(data, 57) +#define MRECURSION59( macro, data) MRECURSION58( macro, DEC_(data)) macro(data, 58) +#define MRECURSION60( macro, data) MRECURSION59( macro, DEC_(data)) macro(data, 59) +#define MRECURSION61( macro, data) MRECURSION60( macro, DEC_(data)) macro(data, 60) +#define MRECURSION62( macro, data) MRECURSION61( macro, DEC_(data)) macro(data, 61) +#define MRECURSION63( macro, data) MRECURSION62( macro, DEC_(data)) macro(data, 62) +#define MRECURSION64( macro, data) MRECURSION63( macro, DEC_(data)) macro(data, 63) +#define MRECURSION65( macro, data) MRECURSION64( macro, DEC_(data)) macro(data, 64) +#define MRECURSION66( macro, data) MRECURSION65( macro, DEC_(data)) macro(data, 65) +#define MRECURSION67( macro, data) MRECURSION66( macro, DEC_(data)) macro(data, 66) +#define MRECURSION68( macro, data) MRECURSION67( macro, DEC_(data)) macro(data, 67) +#define MRECURSION69( macro, data) MRECURSION68( macro, DEC_(data)) macro(data, 68) +#define MRECURSION70( macro, data) MRECURSION69( macro, DEC_(data)) macro(data, 69) +#define MRECURSION71( macro, data) MRECURSION70( macro, DEC_(data)) macro(data, 70) +#define MRECURSION72( macro, data) MRECURSION71( macro, DEC_(data)) macro(data, 71) +#define MRECURSION73( macro, data) MRECURSION72( macro, DEC_(data)) macro(data, 72) +#define MRECURSION74( macro, data) MRECURSION73( macro, DEC_(data)) macro(data, 73) +#define MRECURSION75( macro, data) MRECURSION74( macro, DEC_(data)) macro(data, 74) +#define MRECURSION76( macro, data) MRECURSION75( macro, DEC_(data)) macro(data, 75) +#define MRECURSION77( macro, data) MRECURSION76( macro, DEC_(data)) macro(data, 76) +#define MRECURSION78( macro, data) MRECURSION77( macro, DEC_(data)) macro(data, 77) +#define MRECURSION79( macro, data) MRECURSION78( macro, DEC_(data)) macro(data, 78) +#define MRECURSION80( macro, data) MRECURSION79( macro, DEC_(data)) macro(data, 79) +#define MRECURSION81( macro, data) MRECURSION80( macro, DEC_(data)) macro(data, 80) +#define MRECURSION82( macro, data) MRECURSION81( macro, DEC_(data)) macro(data, 81) +#define MRECURSION83( macro, data) MRECURSION82( macro, DEC_(data)) macro(data, 82) +#define MRECURSION84( macro, data) MRECURSION83( macro, DEC_(data)) macro(data, 83) +#define MRECURSION85( macro, data) MRECURSION84( macro, DEC_(data)) macro(data, 84) +#define MRECURSION86( macro, data) MRECURSION85( macro, DEC_(data)) macro(data, 85) +#define MRECURSION87( macro, data) MRECURSION86( macro, DEC_(data)) macro(data, 86) +#define MRECURSION88( macro, data) MRECURSION87( macro, DEC_(data)) macro(data, 87) +#define MRECURSION89( macro, data) MRECURSION88( macro, DEC_(data)) macro(data, 88) +#define MRECURSION90( macro, data) MRECURSION89( macro, DEC_(data)) macro(data, 89) +#define MRECURSION91( macro, data) MRECURSION90( macro, DEC_(data)) macro(data, 90) +#define MRECURSION92( macro, data) MRECURSION91( macro, DEC_(data)) macro(data, 91) +#define MRECURSION93( macro, data) MRECURSION92( macro, DEC_(data)) macro(data, 92) +#define MRECURSION94( macro, data) MRECURSION93( macro, DEC_(data)) macro(data, 93) +#define MRECURSION95( macro, data) MRECURSION94( macro, DEC_(data)) macro(data, 94) +#define MRECURSION96( macro, data) MRECURSION95( macro, DEC_(data)) macro(data, 95) +#define MRECURSION97( macro, data) MRECURSION96( macro, DEC_(data)) macro(data, 96) +#define MRECURSION98( macro, data) MRECURSION97( macro, DEC_(data)) macro(data, 97) +#define MRECURSION99( macro, data) MRECURSION98( macro, DEC_(data)) macro(data, 98) +#define MRECURSION100(macro, data) MRECURSION99( macro, DEC_(data)) macro(data, 99) +#define MRECURSION101(macro, data) MRECURSION100( macro, DEC_(data)) macro(data, 100) +#define MRECURSION102(macro, data) MRECURSION101( macro, DEC_(data)) macro(data, 101) +#define MRECURSION103(macro, data) MRECURSION102( macro, DEC_(data)) macro(data, 102) +#define MRECURSION104(macro, data) MRECURSION103( macro, DEC_(data)) macro(data, 103) +#define MRECURSION105(macro, data) MRECURSION104( macro, DEC_(data)) macro(data, 104) +#define MRECURSION106(macro, data) MRECURSION105( macro, DEC_(data)) macro(data, 105) +#define MRECURSION107(macro, data) MRECURSION106( macro, DEC_(data)) macro(data, 106) +#define MRECURSION108(macro, data) MRECURSION107( macro, DEC_(data)) macro(data, 107) +#define MRECURSION109(macro, data) MRECURSION108( macro, DEC_(data)) macro(data, 108) +#define MRECURSION110(macro, data) MRECURSION109( macro, DEC_(data)) macro(data, 109) +#define MRECURSION111(macro, data) MRECURSION110( macro, DEC_(data)) macro(data, 110) +#define MRECURSION112(macro, data) MRECURSION111( macro, DEC_(data)) macro(data, 111) +#define MRECURSION113(macro, data) MRECURSION112( macro, DEC_(data)) macro(data, 112) +#define MRECURSION114(macro, data) MRECURSION113( macro, DEC_(data)) macro(data, 113) +#define MRECURSION115(macro, data) MRECURSION114( macro, DEC_(data)) macro(data, 114) +#define MRECURSION116(macro, data) MRECURSION115( macro, DEC_(data)) macro(data, 115) +#define MRECURSION117(macro, data) MRECURSION116( macro, DEC_(data)) macro(data, 116) +#define MRECURSION118(macro, data) MRECURSION117( macro, DEC_(data)) macro(data, 117) +#define MRECURSION119(macro, data) MRECURSION118( macro, DEC_(data)) macro(data, 118) +#define MRECURSION120(macro, data) MRECURSION119( macro, DEC_(data)) macro(data, 119) +#define MRECURSION121(macro, data) MRECURSION120( macro, DEC_(data)) macro(data, 120) +#define MRECURSION122(macro, data) MRECURSION121( macro, DEC_(data)) macro(data, 121) +#define MRECURSION123(macro, data) MRECURSION122( macro, DEC_(data)) macro(data, 122) +#define MRECURSION124(macro, data) MRECURSION123( macro, DEC_(data)) macro(data, 123) +#define MRECURSION125(macro, data) MRECURSION124( macro, DEC_(data)) macro(data, 124) +#define MRECURSION126(macro, data) MRECURSION125( macro, DEC_(data)) macro(data, 125) +#define MRECURSION127(macro, data) MRECURSION126( macro, DEC_(data)) macro(data, 126) +#define MRECURSION128(macro, data) MRECURSION127( macro, DEC_(data)) macro(data, 127) +#define MRECURSION129(macro, data) MRECURSION128( macro, DEC_(data)) macro(data, 128) +#define MRECURSION130(macro, data) MRECURSION129( macro, DEC_(data)) macro(data, 129) +#define MRECURSION131(macro, data) MRECURSION130( macro, DEC_(data)) macro(data, 130) +#define MRECURSION132(macro, data) MRECURSION131( macro, DEC_(data)) macro(data, 131) +#define MRECURSION133(macro, data) MRECURSION132( macro, DEC_(data)) macro(data, 132) +#define MRECURSION134(macro, data) MRECURSION133( macro, DEC_(data)) macro(data, 133) +#define MRECURSION135(macro, data) MRECURSION134( macro, DEC_(data)) macro(data, 134) +#define MRECURSION136(macro, data) MRECURSION135( macro, DEC_(data)) macro(data, 135) +#define MRECURSION137(macro, data) MRECURSION136( macro, DEC_(data)) macro(data, 136) +#define MRECURSION138(macro, data) MRECURSION137( macro, DEC_(data)) macro(data, 137) +#define MRECURSION139(macro, data) MRECURSION138( macro, DEC_(data)) macro(data, 138) +#define MRECURSION140(macro, data) MRECURSION139( macro, DEC_(data)) macro(data, 139) +#define MRECURSION141(macro, data) MRECURSION140( macro, DEC_(data)) macro(data, 140) +#define MRECURSION142(macro, data) MRECURSION141( macro, DEC_(data)) macro(data, 141) +#define MRECURSION143(macro, data) MRECURSION142( macro, DEC_(data)) macro(data, 142) +#define MRECURSION144(macro, data) MRECURSION143( macro, DEC_(data)) macro(data, 143) +#define MRECURSION145(macro, data) MRECURSION144( macro, DEC_(data)) macro(data, 144) +#define MRECURSION146(macro, data) MRECURSION145( macro, DEC_(data)) macro(data, 145) +#define MRECURSION147(macro, data) MRECURSION146( macro, DEC_(data)) macro(data, 146) +#define MRECURSION148(macro, data) MRECURSION147( macro, DEC_(data)) macro(data, 147) +#define MRECURSION149(macro, data) MRECURSION148( macro, DEC_(data)) macro(data, 148) +#define MRECURSION150(macro, data) MRECURSION149( macro, DEC_(data)) macro(data, 149) +#define MRECURSION151(macro, data) MRECURSION150( macro, DEC_(data)) macro(data, 150) +#define MRECURSION152(macro, data) MRECURSION151( macro, DEC_(data)) macro(data, 151) +#define MRECURSION153(macro, data) MRECURSION152( macro, DEC_(data)) macro(data, 152) +#define MRECURSION154(macro, data) MRECURSION153( macro, DEC_(data)) macro(data, 153) +#define MRECURSION155(macro, data) MRECURSION154( macro, DEC_(data)) macro(data, 154) +#define MRECURSION156(macro, data) MRECURSION155( macro, DEC_(data)) macro(data, 155) +#define MRECURSION157(macro, data) MRECURSION156( macro, DEC_(data)) macro(data, 156) +#define MRECURSION158(macro, data) MRECURSION157( macro, DEC_(data)) macro(data, 157) +#define MRECURSION159(macro, data) MRECURSION158( macro, DEC_(data)) macro(data, 158) +#define MRECURSION160(macro, data) MRECURSION159( macro, DEC_(data)) macro(data, 159) +#define MRECURSION161(macro, data) MRECURSION160( macro, DEC_(data)) macro(data, 160) +#define MRECURSION162(macro, data) MRECURSION161( macro, DEC_(data)) macro(data, 161) +#define MRECURSION163(macro, data) MRECURSION162( macro, DEC_(data)) macro(data, 162) +#define MRECURSION164(macro, data) MRECURSION163( macro, DEC_(data)) macro(data, 163) +#define MRECURSION165(macro, data) MRECURSION164( macro, DEC_(data)) macro(data, 164) +#define MRECURSION166(macro, data) MRECURSION165( macro, DEC_(data)) macro(data, 165) +#define MRECURSION167(macro, data) MRECURSION166( macro, DEC_(data)) macro(data, 166) +#define MRECURSION168(macro, data) MRECURSION167( macro, DEC_(data)) macro(data, 167) +#define MRECURSION169(macro, data) MRECURSION168( macro, DEC_(data)) macro(data, 168) +#define MRECURSION170(macro, data) MRECURSION169( macro, DEC_(data)) macro(data, 169) +#define MRECURSION171(macro, data) MRECURSION170( macro, DEC_(data)) macro(data, 170) +#define MRECURSION172(macro, data) MRECURSION171( macro, DEC_(data)) macro(data, 171) +#define MRECURSION173(macro, data) MRECURSION172( macro, DEC_(data)) macro(data, 172) +#define MRECURSION174(macro, data) MRECURSION173( macro, DEC_(data)) macro(data, 173) +#define MRECURSION175(macro, data) MRECURSION174( macro, DEC_(data)) macro(data, 174) +#define MRECURSION176(macro, data) MRECURSION175( macro, DEC_(data)) macro(data, 175) +#define MRECURSION177(macro, data) MRECURSION176( macro, DEC_(data)) macro(data, 176) +#define MRECURSION178(macro, data) MRECURSION177( macro, DEC_(data)) macro(data, 177) +#define MRECURSION179(macro, data) MRECURSION178( macro, DEC_(data)) macro(data, 178) +#define MRECURSION180(macro, data) MRECURSION179( macro, DEC_(data)) macro(data, 179) +#define MRECURSION181(macro, data) MRECURSION180( macro, DEC_(data)) macro(data, 180) +#define MRECURSION182(macro, data) MRECURSION181( macro, DEC_(data)) macro(data, 181) +#define MRECURSION183(macro, data) MRECURSION182( macro, DEC_(data)) macro(data, 182) +#define MRECURSION184(macro, data) MRECURSION183( macro, DEC_(data)) macro(data, 183) +#define MRECURSION185(macro, data) MRECURSION184( macro, DEC_(data)) macro(data, 184) +#define MRECURSION186(macro, data) MRECURSION185( macro, DEC_(data)) macro(data, 185) +#define MRECURSION187(macro, data) MRECURSION186( macro, DEC_(data)) macro(data, 186) +#define MRECURSION188(macro, data) MRECURSION187( macro, DEC_(data)) macro(data, 187) +#define MRECURSION189(macro, data) MRECURSION188( macro, DEC_(data)) macro(data, 188) +#define MRECURSION190(macro, data) MRECURSION189( macro, DEC_(data)) macro(data, 189) +#define MRECURSION191(macro, data) MRECURSION190( macro, DEC_(data)) macro(data, 190) +#define MRECURSION192(macro, data) MRECURSION191( macro, DEC_(data)) macro(data, 191) +#define MRECURSION193(macro, data) MRECURSION192( macro, DEC_(data)) macro(data, 192) +#define MRECURSION194(macro, data) MRECURSION193( macro, DEC_(data)) macro(data, 193) +#define MRECURSION195(macro, data) MRECURSION194( macro, DEC_(data)) macro(data, 194) +#define MRECURSION196(macro, data) MRECURSION195( macro, DEC_(data)) macro(data, 195) +#define MRECURSION197(macro, data) MRECURSION196( macro, DEC_(data)) macro(data, 196) +#define MRECURSION198(macro, data) MRECURSION197( macro, DEC_(data)) macro(data, 197) +#define MRECURSION199(macro, data) MRECURSION198( macro, DEC_(data)) macro(data, 198) +#define MRECURSION200(macro, data) MRECURSION199( macro, DEC_(data)) macro(data, 199) +#define MRECURSION201(macro, data) MRECURSION200( macro, DEC_(data)) macro(data, 200) +#define MRECURSION202(macro, data) MRECURSION201( macro, DEC_(data)) macro(data, 201) +#define MRECURSION203(macro, data) MRECURSION202( macro, DEC_(data)) macro(data, 202) +#define MRECURSION204(macro, data) MRECURSION203( macro, DEC_(data)) macro(data, 203) +#define MRECURSION205(macro, data) MRECURSION204( macro, DEC_(data)) macro(data, 204) +#define MRECURSION206(macro, data) MRECURSION205( macro, DEC_(data)) macro(data, 205) +#define MRECURSION207(macro, data) MRECURSION206( macro, DEC_(data)) macro(data, 206) +#define MRECURSION208(macro, data) MRECURSION207( macro, DEC_(data)) macro(data, 207) +#define MRECURSION209(macro, data) MRECURSION208( macro, DEC_(data)) macro(data, 208) +#define MRECURSION210(macro, data) MRECURSION209( macro, DEC_(data)) macro(data, 209) +#define MRECURSION211(macro, data) MRECURSION210( macro, DEC_(data)) macro(data, 210) +#define MRECURSION212(macro, data) MRECURSION211( macro, DEC_(data)) macro(data, 211) +#define MRECURSION213(macro, data) MRECURSION212( macro, DEC_(data)) macro(data, 212) +#define MRECURSION214(macro, data) MRECURSION213( macro, DEC_(data)) macro(data, 213) +#define MRECURSION215(macro, data) MRECURSION214( macro, DEC_(data)) macro(data, 214) +#define MRECURSION216(macro, data) MRECURSION215( macro, DEC_(data)) macro(data, 215) +#define MRECURSION217(macro, data) MRECURSION216( macro, DEC_(data)) macro(data, 216) +#define MRECURSION218(macro, data) MRECURSION217( macro, DEC_(data)) macro(data, 217) +#define MRECURSION219(macro, data) MRECURSION218( macro, DEC_(data)) macro(data, 218) +#define MRECURSION220(macro, data) MRECURSION219( macro, DEC_(data)) macro(data, 219) +#define MRECURSION221(macro, data) MRECURSION220( macro, DEC_(data)) macro(data, 220) +#define MRECURSION222(macro, data) MRECURSION221( macro, DEC_(data)) macro(data, 221) +#define MRECURSION223(macro, data) MRECURSION222( macro, DEC_(data)) macro(data, 222) +#define MRECURSION224(macro, data) MRECURSION223( macro, DEC_(data)) macro(data, 223) +#define MRECURSION225(macro, data) MRECURSION224( macro, DEC_(data)) macro(data, 224) +#define MRECURSION226(macro, data) MRECURSION225( macro, DEC_(data)) macro(data, 225) +#define MRECURSION227(macro, data) MRECURSION226( macro, DEC_(data)) macro(data, 226) +#define MRECURSION228(macro, data) MRECURSION227( macro, DEC_(data)) macro(data, 227) +#define MRECURSION229(macro, data) MRECURSION228( macro, DEC_(data)) macro(data, 228) +#define MRECURSION230(macro, data) MRECURSION229( macro, DEC_(data)) macro(data, 229) +#define MRECURSION231(macro, data) MRECURSION230( macro, DEC_(data)) macro(data, 230) +#define MRECURSION232(macro, data) MRECURSION231( macro, DEC_(data)) macro(data, 231) +#define MRECURSION233(macro, data) MRECURSION232( macro, DEC_(data)) macro(data, 232) +#define MRECURSION234(macro, data) MRECURSION233( macro, DEC_(data)) macro(data, 233) +#define MRECURSION235(macro, data) MRECURSION234( macro, DEC_(data)) macro(data, 234) +#define MRECURSION236(macro, data) MRECURSION235( macro, DEC_(data)) macro(data, 235) +#define MRECURSION237(macro, data) MRECURSION236( macro, DEC_(data)) macro(data, 236) +#define MRECURSION238(macro, data) MRECURSION237( macro, DEC_(data)) macro(data, 237) +#define MRECURSION239(macro, data) MRECURSION238( macro, DEC_(data)) macro(data, 238) +#define MRECURSION240(macro, data) MRECURSION239( macro, DEC_(data)) macro(data, 239) +#define MRECURSION241(macro, data) MRECURSION240( macro, DEC_(data)) macro(data, 240) +#define MRECURSION242(macro, data) MRECURSION241( macro, DEC_(data)) macro(data, 241) +#define MRECURSION243(macro, data) MRECURSION242( macro, DEC_(data)) macro(data, 242) +#define MRECURSION244(macro, data) MRECURSION243( macro, DEC_(data)) macro(data, 243) +#define MRECURSION245(macro, data) MRECURSION244( macro, DEC_(data)) macro(data, 244) +#define MRECURSION246(macro, data) MRECURSION245( macro, DEC_(data)) macro(data, 245) +#define MRECURSION247(macro, data) MRECURSION246( macro, DEC_(data)) macro(data, 246) +#define MRECURSION248(macro, data) MRECURSION247( macro, DEC_(data)) macro(data, 247) +#define MRECURSION249(macro, data) MRECURSION248( macro, DEC_(data)) macro(data, 248) +#define MRECURSION250(macro, data) MRECURSION249( macro, DEC_(data)) macro(data, 249) +#define MRECURSION251(macro, data) MRECURSION250( macro, DEC_(data)) macro(data, 250) +#define MRECURSION252(macro, data) MRECURSION251( macro, DEC_(data)) macro(data, 251) +#define MRECURSION253(macro, data) MRECURSION252( macro, DEC_(data)) macro(data, 252) +#define MRECURSION254(macro, data) MRECURSION253( macro, DEC_(data)) macro(data, 253) +#define MRECURSION255(macro, data) MRECURSION254( macro, DEC_(data)) macro(data, 254) +#define MRECURSION256(macro, data) MRECURSION255( macro, DEC_(data)) macro(data, 255) + +/** @} */ + +#endif /* _MRECURSION_H_ */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h new file mode 100644 index 0000000..fb820d5 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h @@ -0,0 +1,321 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef _MREPEAT_H_ +#define _MREPEAT_H_ + +/** + * \defgroup group_sam0_utils_mrepeat Preprocessor - Macro Repeat + * + * \ingroup group_sam0_utils + * + * @{ + */ + +#include "preprocessor.h" + +/** Maximal number of repetitions supported by MREPEAT. */ +#define MREPEAT_LIMIT 256 + +/** \brief Macro repeat. + * + * This macro represents a horizontal repetition construct. + * + * \param[in] count The number of repetitious calls to macro. Valid values + * range from 0 to MREPEAT_LIMIT. + * \param[in] macro A binary operation of the form macro(n, data). This macro + * is expanded by MREPEAT with the current repetition number + * and the auxiliary data argument. + * \param[in] data Auxiliary data passed to macro. + * + * \return macro(0, data) macro(1, data) ... macro(count - 1, data) + */ +#define MREPEAT(count, macro, data) TPASTE2(MREPEAT, count) (macro, data) + +#define MREPEAT0( macro, data) +#define MREPEAT1( macro, data) MREPEAT0( macro, data) macro( 0, data) +#define MREPEAT2( macro, data) MREPEAT1( macro, data) macro( 1, data) +#define MREPEAT3( macro, data) MREPEAT2( macro, data) macro( 2, data) +#define MREPEAT4( macro, data) MREPEAT3( macro, data) macro( 3, data) +#define MREPEAT5( macro, data) MREPEAT4( macro, data) macro( 4, data) +#define MREPEAT6( macro, data) MREPEAT5( macro, data) macro( 5, data) +#define MREPEAT7( macro, data) MREPEAT6( macro, data) macro( 6, data) +#define MREPEAT8( macro, data) MREPEAT7( macro, data) macro( 7, data) +#define MREPEAT9( macro, data) MREPEAT8( macro, data) macro( 8, data) +#define MREPEAT10( macro, data) MREPEAT9( macro, data) macro( 9, data) +#define MREPEAT11( macro, data) MREPEAT10( macro, data) macro( 10, data) +#define MREPEAT12( macro, data) MREPEAT11( macro, data) macro( 11, data) +#define MREPEAT13( macro, data) MREPEAT12( macro, data) macro( 12, data) +#define MREPEAT14( macro, data) MREPEAT13( macro, data) macro( 13, data) +#define MREPEAT15( macro, data) MREPEAT14( macro, data) macro( 14, data) +#define MREPEAT16( macro, data) MREPEAT15( macro, data) macro( 15, data) +#define MREPEAT17( macro, data) MREPEAT16( macro, data) macro( 16, data) +#define MREPEAT18( macro, data) MREPEAT17( macro, data) macro( 17, data) +#define MREPEAT19( macro, data) MREPEAT18( macro, data) macro( 18, data) +#define MREPEAT20( macro, data) MREPEAT19( macro, data) macro( 19, data) +#define MREPEAT21( macro, data) MREPEAT20( macro, data) macro( 20, data) +#define MREPEAT22( macro, data) MREPEAT21( macro, data) macro( 21, data) +#define MREPEAT23( macro, data) MREPEAT22( macro, data) macro( 22, data) +#define MREPEAT24( macro, data) MREPEAT23( macro, data) macro( 23, data) +#define MREPEAT25( macro, data) MREPEAT24( macro, data) macro( 24, data) +#define MREPEAT26( macro, data) MREPEAT25( macro, data) macro( 25, data) +#define MREPEAT27( macro, data) MREPEAT26( macro, data) macro( 26, data) +#define MREPEAT28( macro, data) MREPEAT27( macro, data) macro( 27, data) +#define MREPEAT29( macro, data) MREPEAT28( macro, data) macro( 28, data) +#define MREPEAT30( macro, data) MREPEAT29( macro, data) macro( 29, data) +#define MREPEAT31( macro, data) MREPEAT30( macro, data) macro( 30, data) +#define MREPEAT32( macro, data) MREPEAT31( macro, data) macro( 31, data) +#define MREPEAT33( macro, data) MREPEAT32( macro, data) macro( 32, data) +#define MREPEAT34( macro, data) MREPEAT33( macro, data) macro( 33, data) +#define MREPEAT35( macro, data) MREPEAT34( macro, data) macro( 34, data) +#define MREPEAT36( macro, data) MREPEAT35( macro, data) macro( 35, data) +#define MREPEAT37( macro, data) MREPEAT36( macro, data) macro( 36, data) +#define MREPEAT38( macro, data) MREPEAT37( macro, data) macro( 37, data) +#define MREPEAT39( macro, data) MREPEAT38( macro, data) macro( 38, data) +#define MREPEAT40( macro, data) MREPEAT39( macro, data) macro( 39, data) +#define MREPEAT41( macro, data) MREPEAT40( macro, data) macro( 40, data) +#define MREPEAT42( macro, data) MREPEAT41( macro, data) macro( 41, data) +#define MREPEAT43( macro, data) MREPEAT42( macro, data) macro( 42, data) +#define MREPEAT44( macro, data) MREPEAT43( macro, data) macro( 43, data) +#define MREPEAT45( macro, data) MREPEAT44( macro, data) macro( 44, data) +#define MREPEAT46( macro, data) MREPEAT45( macro, data) macro( 45, data) +#define MREPEAT47( macro, data) MREPEAT46( macro, data) macro( 46, data) +#define MREPEAT48( macro, data) MREPEAT47( macro, data) macro( 47, data) +#define MREPEAT49( macro, data) MREPEAT48( macro, data) macro( 48, data) +#define MREPEAT50( macro, data) MREPEAT49( macro, data) macro( 49, data) +#define MREPEAT51( macro, data) MREPEAT50( macro, data) macro( 50, data) +#define MREPEAT52( macro, data) MREPEAT51( macro, data) macro( 51, data) +#define MREPEAT53( macro, data) MREPEAT52( macro, data) macro( 52, data) +#define MREPEAT54( macro, data) MREPEAT53( macro, data) macro( 53, data) +#define MREPEAT55( macro, data) MREPEAT54( macro, data) macro( 54, data) +#define MREPEAT56( macro, data) MREPEAT55( macro, data) macro( 55, data) +#define MREPEAT57( macro, data) MREPEAT56( macro, data) macro( 56, data) +#define MREPEAT58( macro, data) MREPEAT57( macro, data) macro( 57, data) +#define MREPEAT59( macro, data) MREPEAT58( macro, data) macro( 58, data) +#define MREPEAT60( macro, data) MREPEAT59( macro, data) macro( 59, data) +#define MREPEAT61( macro, data) MREPEAT60( macro, data) macro( 60, data) +#define MREPEAT62( macro, data) MREPEAT61( macro, data) macro( 61, data) +#define MREPEAT63( macro, data) MREPEAT62( macro, data) macro( 62, data) +#define MREPEAT64( macro, data) MREPEAT63( macro, data) macro( 63, data) +#define MREPEAT65( macro, data) MREPEAT64( macro, data) macro( 64, data) +#define MREPEAT66( macro, data) MREPEAT65( macro, data) macro( 65, data) +#define MREPEAT67( macro, data) MREPEAT66( macro, data) macro( 66, data) +#define MREPEAT68( macro, data) MREPEAT67( macro, data) macro( 67, data) +#define MREPEAT69( macro, data) MREPEAT68( macro, data) macro( 68, data) +#define MREPEAT70( macro, data) MREPEAT69( macro, data) macro( 69, data) +#define MREPEAT71( macro, data) MREPEAT70( macro, data) macro( 70, data) +#define MREPEAT72( macro, data) MREPEAT71( macro, data) macro( 71, data) +#define MREPEAT73( macro, data) MREPEAT72( macro, data) macro( 72, data) +#define MREPEAT74( macro, data) MREPEAT73( macro, data) macro( 73, data) +#define MREPEAT75( macro, data) MREPEAT74( macro, data) macro( 74, data) +#define MREPEAT76( macro, data) MREPEAT75( macro, data) macro( 75, data) +#define MREPEAT77( macro, data) MREPEAT76( macro, data) macro( 76, data) +#define MREPEAT78( macro, data) MREPEAT77( macro, data) macro( 77, data) +#define MREPEAT79( macro, data) MREPEAT78( macro, data) macro( 78, data) +#define MREPEAT80( macro, data) MREPEAT79( macro, data) macro( 79, data) +#define MREPEAT81( macro, data) MREPEAT80( macro, data) macro( 80, data) +#define MREPEAT82( macro, data) MREPEAT81( macro, data) macro( 81, data) +#define MREPEAT83( macro, data) MREPEAT82( macro, data) macro( 82, data) +#define MREPEAT84( macro, data) MREPEAT83( macro, data) macro( 83, data) +#define MREPEAT85( macro, data) MREPEAT84( macro, data) macro( 84, data) +#define MREPEAT86( macro, data) MREPEAT85( macro, data) macro( 85, data) +#define MREPEAT87( macro, data) MREPEAT86( macro, data) macro( 86, data) +#define MREPEAT88( macro, data) MREPEAT87( macro, data) macro( 87, data) +#define MREPEAT89( macro, data) MREPEAT88( macro, data) macro( 88, data) +#define MREPEAT90( macro, data) MREPEAT89( macro, data) macro( 89, data) +#define MREPEAT91( macro, data) MREPEAT90( macro, data) macro( 90, data) +#define MREPEAT92( macro, data) MREPEAT91( macro, data) macro( 91, data) +#define MREPEAT93( macro, data) MREPEAT92( macro, data) macro( 92, data) +#define MREPEAT94( macro, data) MREPEAT93( macro, data) macro( 93, data) +#define MREPEAT95( macro, data) MREPEAT94( macro, data) macro( 94, data) +#define MREPEAT96( macro, data) MREPEAT95( macro, data) macro( 95, data) +#define MREPEAT97( macro, data) MREPEAT96( macro, data) macro( 96, data) +#define MREPEAT98( macro, data) MREPEAT97( macro, data) macro( 97, data) +#define MREPEAT99( macro, data) MREPEAT98( macro, data) macro( 98, data) +#define MREPEAT100(macro, data) MREPEAT99( macro, data) macro( 99, data) +#define MREPEAT101(macro, data) MREPEAT100(macro, data) macro(100, data) +#define MREPEAT102(macro, data) MREPEAT101(macro, data) macro(101, data) +#define MREPEAT103(macro, data) MREPEAT102(macro, data) macro(102, data) +#define MREPEAT104(macro, data) MREPEAT103(macro, data) macro(103, data) +#define MREPEAT105(macro, data) MREPEAT104(macro, data) macro(104, data) +#define MREPEAT106(macro, data) MREPEAT105(macro, data) macro(105, data) +#define MREPEAT107(macro, data) MREPEAT106(macro, data) macro(106, data) +#define MREPEAT108(macro, data) MREPEAT107(macro, data) macro(107, data) +#define MREPEAT109(macro, data) MREPEAT108(macro, data) macro(108, data) +#define MREPEAT110(macro, data) MREPEAT109(macro, data) macro(109, data) +#define MREPEAT111(macro, data) MREPEAT110(macro, data) macro(110, data) +#define MREPEAT112(macro, data) MREPEAT111(macro, data) macro(111, data) +#define MREPEAT113(macro, data) MREPEAT112(macro, data) macro(112, data) +#define MREPEAT114(macro, data) MREPEAT113(macro, data) macro(113, data) +#define MREPEAT115(macro, data) MREPEAT114(macro, data) macro(114, data) +#define MREPEAT116(macro, data) MREPEAT115(macro, data) macro(115, data) +#define MREPEAT117(macro, data) MREPEAT116(macro, data) macro(116, data) +#define MREPEAT118(macro, data) MREPEAT117(macro, data) macro(117, data) +#define MREPEAT119(macro, data) MREPEAT118(macro, data) macro(118, data) +#define MREPEAT120(macro, data) MREPEAT119(macro, data) macro(119, data) +#define MREPEAT121(macro, data) MREPEAT120(macro, data) macro(120, data) +#define MREPEAT122(macro, data) MREPEAT121(macro, data) macro(121, data) +#define MREPEAT123(macro, data) MREPEAT122(macro, data) macro(122, data) +#define MREPEAT124(macro, data) MREPEAT123(macro, data) macro(123, data) +#define MREPEAT125(macro, data) MREPEAT124(macro, data) macro(124, data) +#define MREPEAT126(macro, data) MREPEAT125(macro, data) macro(125, data) +#define MREPEAT127(macro, data) MREPEAT126(macro, data) macro(126, data) +#define MREPEAT128(macro, data) MREPEAT127(macro, data) macro(127, data) +#define MREPEAT129(macro, data) MREPEAT128(macro, data) macro(128, data) +#define MREPEAT130(macro, data) MREPEAT129(macro, data) macro(129, data) +#define MREPEAT131(macro, data) MREPEAT130(macro, data) macro(130, data) +#define MREPEAT132(macro, data) MREPEAT131(macro, data) macro(131, data) +#define MREPEAT133(macro, data) MREPEAT132(macro, data) macro(132, data) +#define MREPEAT134(macro, data) MREPEAT133(macro, data) macro(133, data) +#define MREPEAT135(macro, data) MREPEAT134(macro, data) macro(134, data) +#define MREPEAT136(macro, data) MREPEAT135(macro, data) macro(135, data) +#define MREPEAT137(macro, data) MREPEAT136(macro, data) macro(136, data) +#define MREPEAT138(macro, data) MREPEAT137(macro, data) macro(137, data) +#define MREPEAT139(macro, data) MREPEAT138(macro, data) macro(138, data) +#define MREPEAT140(macro, data) MREPEAT139(macro, data) macro(139, data) +#define MREPEAT141(macro, data) MREPEAT140(macro, data) macro(140, data) +#define MREPEAT142(macro, data) MREPEAT141(macro, data) macro(141, data) +#define MREPEAT143(macro, data) MREPEAT142(macro, data) macro(142, data) +#define MREPEAT144(macro, data) MREPEAT143(macro, data) macro(143, data) +#define MREPEAT145(macro, data) MREPEAT144(macro, data) macro(144, data) +#define MREPEAT146(macro, data) MREPEAT145(macro, data) macro(145, data) +#define MREPEAT147(macro, data) MREPEAT146(macro, data) macro(146, data) +#define MREPEAT148(macro, data) MREPEAT147(macro, data) macro(147, data) +#define MREPEAT149(macro, data) MREPEAT148(macro, data) macro(148, data) +#define MREPEAT150(macro, data) MREPEAT149(macro, data) macro(149, data) +#define MREPEAT151(macro, data) MREPEAT150(macro, data) macro(150, data) +#define MREPEAT152(macro, data) MREPEAT151(macro, data) macro(151, data) +#define MREPEAT153(macro, data) MREPEAT152(macro, data) macro(152, data) +#define MREPEAT154(macro, data) MREPEAT153(macro, data) macro(153, data) +#define MREPEAT155(macro, data) MREPEAT154(macro, data) macro(154, data) +#define MREPEAT156(macro, data) MREPEAT155(macro, data) macro(155, data) +#define MREPEAT157(macro, data) MREPEAT156(macro, data) macro(156, data) +#define MREPEAT158(macro, data) MREPEAT157(macro, data) macro(157, data) +#define MREPEAT159(macro, data) MREPEAT158(macro, data) macro(158, data) +#define MREPEAT160(macro, data) MREPEAT159(macro, data) macro(159, data) +#define MREPEAT161(macro, data) MREPEAT160(macro, data) macro(160, data) +#define MREPEAT162(macro, data) MREPEAT161(macro, data) macro(161, data) +#define MREPEAT163(macro, data) MREPEAT162(macro, data) macro(162, data) +#define MREPEAT164(macro, data) MREPEAT163(macro, data) macro(163, data) +#define MREPEAT165(macro, data) MREPEAT164(macro, data) macro(164, data) +#define MREPEAT166(macro, data) MREPEAT165(macro, data) macro(165, data) +#define MREPEAT167(macro, data) MREPEAT166(macro, data) macro(166, data) +#define MREPEAT168(macro, data) MREPEAT167(macro, data) macro(167, data) +#define MREPEAT169(macro, data) MREPEAT168(macro, data) macro(168, data) +#define MREPEAT170(macro, data) MREPEAT169(macro, data) macro(169, data) +#define MREPEAT171(macro, data) MREPEAT170(macro, data) macro(170, data) +#define MREPEAT172(macro, data) MREPEAT171(macro, data) macro(171, data) +#define MREPEAT173(macro, data) MREPEAT172(macro, data) macro(172, data) +#define MREPEAT174(macro, data) MREPEAT173(macro, data) macro(173, data) +#define MREPEAT175(macro, data) MREPEAT174(macro, data) macro(174, data) +#define MREPEAT176(macro, data) MREPEAT175(macro, data) macro(175, data) +#define MREPEAT177(macro, data) MREPEAT176(macro, data) macro(176, data) +#define MREPEAT178(macro, data) MREPEAT177(macro, data) macro(177, data) +#define MREPEAT179(macro, data) MREPEAT178(macro, data) macro(178, data) +#define MREPEAT180(macro, data) MREPEAT179(macro, data) macro(179, data) +#define MREPEAT181(macro, data) MREPEAT180(macro, data) macro(180, data) +#define MREPEAT182(macro, data) MREPEAT181(macro, data) macro(181, data) +#define MREPEAT183(macro, data) MREPEAT182(macro, data) macro(182, data) +#define MREPEAT184(macro, data) MREPEAT183(macro, data) macro(183, data) +#define MREPEAT185(macro, data) MREPEAT184(macro, data) macro(184, data) +#define MREPEAT186(macro, data) MREPEAT185(macro, data) macro(185, data) +#define MREPEAT187(macro, data) MREPEAT186(macro, data) macro(186, data) +#define MREPEAT188(macro, data) MREPEAT187(macro, data) macro(187, data) +#define MREPEAT189(macro, data) MREPEAT188(macro, data) macro(188, data) +#define MREPEAT190(macro, data) MREPEAT189(macro, data) macro(189, data) +#define MREPEAT191(macro, data) MREPEAT190(macro, data) macro(190, data) +#define MREPEAT192(macro, data) MREPEAT191(macro, data) macro(191, data) +#define MREPEAT193(macro, data) MREPEAT192(macro, data) macro(192, data) +#define MREPEAT194(macro, data) MREPEAT193(macro, data) macro(193, data) +#define MREPEAT195(macro, data) MREPEAT194(macro, data) macro(194, data) +#define MREPEAT196(macro, data) MREPEAT195(macro, data) macro(195, data) +#define MREPEAT197(macro, data) MREPEAT196(macro, data) macro(196, data) +#define MREPEAT198(macro, data) MREPEAT197(macro, data) macro(197, data) +#define MREPEAT199(macro, data) MREPEAT198(macro, data) macro(198, data) +#define MREPEAT200(macro, data) MREPEAT199(macro, data) macro(199, data) +#define MREPEAT201(macro, data) MREPEAT200(macro, data) macro(200, data) +#define MREPEAT202(macro, data) MREPEAT201(macro, data) macro(201, data) +#define MREPEAT203(macro, data) MREPEAT202(macro, data) macro(202, data) +#define MREPEAT204(macro, data) MREPEAT203(macro, data) macro(203, data) +#define MREPEAT205(macro, data) MREPEAT204(macro, data) macro(204, data) +#define MREPEAT206(macro, data) MREPEAT205(macro, data) macro(205, data) +#define MREPEAT207(macro, data) MREPEAT206(macro, data) macro(206, data) +#define MREPEAT208(macro, data) MREPEAT207(macro, data) macro(207, data) +#define MREPEAT209(macro, data) MREPEAT208(macro, data) macro(208, data) +#define MREPEAT210(macro, data) MREPEAT209(macro, data) macro(209, data) +#define MREPEAT211(macro, data) MREPEAT210(macro, data) macro(210, data) +#define MREPEAT212(macro, data) MREPEAT211(macro, data) macro(211, data) +#define MREPEAT213(macro, data) MREPEAT212(macro, data) macro(212, data) +#define MREPEAT214(macro, data) MREPEAT213(macro, data) macro(213, data) +#define MREPEAT215(macro, data) MREPEAT214(macro, data) macro(214, data) +#define MREPEAT216(macro, data) MREPEAT215(macro, data) macro(215, data) +#define MREPEAT217(macro, data) MREPEAT216(macro, data) macro(216, data) +#define MREPEAT218(macro, data) MREPEAT217(macro, data) macro(217, data) +#define MREPEAT219(macro, data) MREPEAT218(macro, data) macro(218, data) +#define MREPEAT220(macro, data) MREPEAT219(macro, data) macro(219, data) +#define MREPEAT221(macro, data) MREPEAT220(macro, data) macro(220, data) +#define MREPEAT222(macro, data) MREPEAT221(macro, data) macro(221, data) +#define MREPEAT223(macro, data) MREPEAT222(macro, data) macro(222, data) +#define MREPEAT224(macro, data) MREPEAT223(macro, data) macro(223, data) +#define MREPEAT225(macro, data) MREPEAT224(macro, data) macro(224, data) +#define MREPEAT226(macro, data) MREPEAT225(macro, data) macro(225, data) +#define MREPEAT227(macro, data) MREPEAT226(macro, data) macro(226, data) +#define MREPEAT228(macro, data) MREPEAT227(macro, data) macro(227, data) +#define MREPEAT229(macro, data) MREPEAT228(macro, data) macro(228, data) +#define MREPEAT230(macro, data) MREPEAT229(macro, data) macro(229, data) +#define MREPEAT231(macro, data) MREPEAT230(macro, data) macro(230, data) +#define MREPEAT232(macro, data) MREPEAT231(macro, data) macro(231, data) +#define MREPEAT233(macro, data) MREPEAT232(macro, data) macro(232, data) +#define MREPEAT234(macro, data) MREPEAT233(macro, data) macro(233, data) +#define MREPEAT235(macro, data) MREPEAT234(macro, data) macro(234, data) +#define MREPEAT236(macro, data) MREPEAT235(macro, data) macro(235, data) +#define MREPEAT237(macro, data) MREPEAT236(macro, data) macro(236, data) +#define MREPEAT238(macro, data) MREPEAT237(macro, data) macro(237, data) +#define MREPEAT239(macro, data) MREPEAT238(macro, data) macro(238, data) +#define MREPEAT240(macro, data) MREPEAT239(macro, data) macro(239, data) +#define MREPEAT241(macro, data) MREPEAT240(macro, data) macro(240, data) +#define MREPEAT242(macro, data) MREPEAT241(macro, data) macro(241, data) +#define MREPEAT243(macro, data) MREPEAT242(macro, data) macro(242, data) +#define MREPEAT244(macro, data) MREPEAT243(macro, data) macro(243, data) +#define MREPEAT245(macro, data) MREPEAT244(macro, data) macro(244, data) +#define MREPEAT246(macro, data) MREPEAT245(macro, data) macro(245, data) +#define MREPEAT247(macro, data) MREPEAT246(macro, data) macro(246, data) +#define MREPEAT248(macro, data) MREPEAT247(macro, data) macro(247, data) +#define MREPEAT249(macro, data) MREPEAT248(macro, data) macro(248, data) +#define MREPEAT250(macro, data) MREPEAT249(macro, data) macro(249, data) +#define MREPEAT251(macro, data) MREPEAT250(macro, data) macro(250, data) +#define MREPEAT252(macro, data) MREPEAT251(macro, data) macro(251, data) +#define MREPEAT253(macro, data) MREPEAT252(macro, data) macro(252, data) +#define MREPEAT254(macro, data) MREPEAT253(macro, data) macro(253, data) +#define MREPEAT255(macro, data) MREPEAT254(macro, data) macro(254, data) +#define MREPEAT256(macro, data) MREPEAT255(macro, data) macro(255, data) + +/** @} */ + +#endif /* _MREPEAT_H_ */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h new file mode 100644 index 0000000..7f67d8a --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h @@ -0,0 +1,38 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef _PREPROCESSOR_H_ +#define _PREPROCESSOR_H_ + +#include "tpaste.h" +#include "stringz.h" +#include "mrepeat.h" +#include "mrecursion.h" + +#endif // _PREPROCESSOR_H_ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/stringz.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/stringz.h new file mode 100644 index 0000000..70937c4 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/stringz.h @@ -0,0 +1,67 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef _STRINGZ_H_ +#define _STRINGZ_H_ + +/** + * \defgroup group_sam0_utils_stringz Preprocessor - Stringize + * + * \ingroup group_sam0_utils + * + * @{ + */ + +/** \brief Stringize. + * + * Stringize a preprocessing token, this token being allowed to be \#defined. + * + * May be used only within macros with the token passed as an argument if the + * token is \#defined. + * + * For example, writing STRINGZ(PIN) within a macro \#defined by PIN_NAME(PIN) + * and invoked as PIN_NAME(PIN0) with PIN0 \#defined as A0 is equivalent to + * writing "A0". + */ +#define STRINGZ(x) #x + +/** \brief Absolute stringize. + * + * Stringize a preprocessing token, this token being allowed to be \#defined. + * + * No restriction of use if the token is \#defined. + * + * For example, writing ASTRINGZ(PIN0) anywhere with PIN0 \#defined as A0 is + * equivalent to writing "A0". + */ +#define ASTRINGZ(x) STRINGZ(x) + +/** @} */ + +#endif // _STRINGZ_H_ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/tpaste.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/tpaste.h new file mode 100644 index 0000000..9108183 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/tpaste.h @@ -0,0 +1,85 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ +#ifndef _TPASTE_H_ +#define _TPASTE_H_ + +/** + * \defgroup group_sam0_utils_tpaste Preprocessor - Token Paste + * + * \ingroup group_sam0_utils + * + * @{ + */ + +/** \name Token Paste + * + * Paste N preprocessing tokens together, these tokens being allowed to be \#defined. + * + * May be used only within macros with the tokens passed as arguments if the tokens are \#defined. + * + * For example, writing TPASTE2(U, WIDTH) within a macro \#defined by + * UTYPE(WIDTH) and invoked as UTYPE(UL_WIDTH) with UL_WIDTH \#defined as 32 is + * equivalent to writing U32. + * + * @{ */ +#define TPASTE2( a, b) a##b +#define TPASTE3( a, b, c) a##b##c +#define TPASTE4( a, b, c, d) a##b##c##d +#define TPASTE5( a, b, c, d, e) a##b##c##d##e +#define TPASTE6( a, b, c, d, e, f) a##b##c##d##e##f +#define TPASTE7( a, b, c, d, e, f, g) a##b##c##d##e##f##g +#define TPASTE8( a, b, c, d, e, f, g, h) a##b##c##d##e##f##g##h +#define TPASTE9( a, b, c, d, e, f, g, h, i) a##b##c##d##e##f##g##h##i +#define TPASTE10(a, b, c, d, e, f, g, h, i, j) a##b##c##d##e##f##g##h##i##j +/** @} */ + +/** \name Absolute Token Paste + * + * Paste N preprocessing tokens together, these tokens being allowed to be \#defined. + * + * No restriction of use if the tokens are \#defined. + * + * For example, writing ATPASTE2(U, UL_WIDTH) anywhere with UL_WIDTH \#defined + * as 32 is equivalent to writing U32. + * + * @{ */ +#define ATPASTE2( a, b) TPASTE2( a, b) +#define ATPASTE3( a, b, c) TPASTE3( a, b, c) +#define ATPASTE4( a, b, c, d) TPASTE4( a, b, c, d) +#define ATPASTE5( a, b, c, d, e) TPASTE5( a, b, c, d, e) +#define ATPASTE6( a, b, c, d, e, f) TPASTE6( a, b, c, d, e, f) +#define ATPASTE7( a, b, c, d, e, f, g) TPASTE7( a, b, c, d, e, f, g) +#define ATPASTE8( a, b, c, d, e, f, g, h) TPASTE8( a, b, c, d, e, f, g, h) +#define ATPASTE9( a, b, c, d, e, f, g, h, i) TPASTE9( a, b, c, d, e, f, g, h, i) +#define ATPASTE10(a, b, c, d, e, f, g, h, i, j) TPASTE10(a, b, c, d, e, f, g, h, i, j) +/** @} */ + +/** @} */ + +#endif // _TPASTE_H_ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/reset.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/reset.h new file mode 100644 index 0000000..ae1eb5a --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/reset.h @@ -0,0 +1,119 @@ +/** + * \file + * + * \brief SAM Reset related functionality + * + * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef RESET_H_INCLUDED +#define RESET_H_INCLUDED + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \addtogroup asfdoc_sam0_system_group + * @{ + */ + +/** + * \brief Reset causes of the system. + * + * List of possible reset causes of the system. + */ +enum system_reset_cause { + /** The system was last reset by a software reset. */ + SYSTEM_RESET_CAUSE_SOFTWARE = PM_RCAUSE_SYST, + /** The system was last reset by the watchdog timer. */ + SYSTEM_RESET_CAUSE_WDT = PM_RCAUSE_WDT, + /** The system was last reset because the external reset line was pulled low. */ + SYSTEM_RESET_CAUSE_EXTERNAL_RESET = PM_RCAUSE_EXT, + /** The system was last reset by the BOD33. */ + SYSTEM_RESET_CAUSE_BOD33 = PM_RCAUSE_BOD33, + /** The system was last reset by the BOD12. */ + SYSTEM_RESET_CAUSE_BOD12 = PM_RCAUSE_BOD12, + /** The system was last reset by the POR (Power on reset). */ + SYSTEM_RESET_CAUSE_POR = PM_RCAUSE_POR, +}; + + +/** + * \name Reset Control + * @{ + */ + +/** + * \brief Reset the MCU. + * + * Resets the MCU and all associated peripherals and registers, except RTC, all 32KHz sources, + * WDT (if ALWAYSON is set) and GCLK (if WRTLOCK is set). + * + */ +static inline void system_reset(void) +{ + NVIC_SystemReset(); +} + +/** + * \brief Return the reset cause. + * + * Retrieves the cause of the last system reset. + * + * \return An enum value indicating the cause of the last system reset. + */ +static inline enum system_reset_cause system_get_reset_cause(void) +{ + return (enum system_reset_cause)PM->RCAUSE.reg; +} + +/** + * @} + */ + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* RESET_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/status_codes.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/status_codes.h new file mode 100644 index 0000000..29bbf41 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/status_codes.h @@ -0,0 +1,138 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef STATUS_CODES_H_INCLUDED +#define STATUS_CODES_H_INCLUDED + +#include + +/** + * \defgroup group_sam0_utils_status_codes Status Codes + * + * \ingroup group_sam0_utils + * + * @{ + */ + +/** Mask to retrieve the error category of a status code. */ +#define STATUS_CATEGORY_MASK 0xF0 + +/** Mask to retrieve the error code within the category of a status code. */ +#define STATUS_ERROR_MASK 0x0F + +/** Status code error categories. */ +enum status_categories { + STATUS_CATEGORY_OK = 0x00, + STATUS_CATEGORY_COMMON = 0x10, + STATUS_CATEGORY_ANALOG = 0x30, + STATUS_CATEGORY_COM = 0x40, + STATUS_CATEGORY_IO = 0x50, +}; + +/** + * Status code that may be returned by shell commands and protocol + * implementations. + * + * \note Any change to these status codes and the corresponding + * message strings is strictly forbidden. New codes can be added, + * however, but make sure that any message string tables are updated + * at the same time. + */ +enum status_code { + STATUS_OK = STATUS_CATEGORY_OK | 0x00, + STATUS_VALID_DATA = STATUS_CATEGORY_OK | 0x01, + STATUS_NO_CHANGE = STATUS_CATEGORY_OK | 0x02, + STATUS_ABORTED = STATUS_CATEGORY_OK | 0x04, + STATUS_BUSY = STATUS_CATEGORY_OK | 0x05, + STATUS_SUSPEND = STATUS_CATEGORY_OK | 0x06, + + STATUS_ERR_IO = STATUS_CATEGORY_COMMON | 0x00, + STATUS_ERR_REQ_FLUSHED = STATUS_CATEGORY_COMMON | 0x01, + STATUS_ERR_TIMEOUT = STATUS_CATEGORY_COMMON | 0x02, + STATUS_ERR_BAD_DATA = STATUS_CATEGORY_COMMON | 0x03, + STATUS_ERR_NOT_FOUND = STATUS_CATEGORY_COMMON | 0x04, + STATUS_ERR_UNSUPPORTED_DEV = STATUS_CATEGORY_COMMON | 0x05, + STATUS_ERR_NO_MEMORY = STATUS_CATEGORY_COMMON | 0x06, + STATUS_ERR_INVALID_ARG = STATUS_CATEGORY_COMMON | 0x07, + STATUS_ERR_BAD_ADDRESS = STATUS_CATEGORY_COMMON | 0x08, + STATUS_ERR_BAD_FORMAT = STATUS_CATEGORY_COMMON | 0x0A, + STATUS_ERR_BAD_FRQ = STATUS_CATEGORY_COMMON | 0x0B, + STATUS_ERR_DENIED = STATUS_CATEGORY_COMMON | 0x0c, + STATUS_ERR_ALREADY_INITIALIZED = STATUS_CATEGORY_COMMON | 0x0d, + STATUS_ERR_OVERFLOW = STATUS_CATEGORY_COMMON | 0x0e, + STATUS_ERR_NOT_INITIALIZED = STATUS_CATEGORY_COMMON | 0x0f, + + STATUS_ERR_SAMPLERATE_UNAVAILABLE = STATUS_CATEGORY_ANALOG | 0x00, + STATUS_ERR_RESOLUTION_UNAVAILABLE = STATUS_CATEGORY_ANALOG | 0x01, + + STATUS_ERR_BAUDRATE_UNAVAILABLE = STATUS_CATEGORY_COM | 0x00, + STATUS_ERR_PACKET_COLLISION = STATUS_CATEGORY_COM | 0x01, + STATUS_ERR_PROTOCOL = STATUS_CATEGORY_COM | 0x02, + + STATUS_ERR_PIN_MUX_INVALID = STATUS_CATEGORY_IO | 0x00, +}; +typedef enum status_code status_code_genare_t; + +/** + Status codes used by MAC stack. + */ +enum status_code_wireless { + //STATUS_OK = 0, //!< Success + ERR_IO_ERROR = -1, //!< I/O error + ERR_FLUSHED = -2, //!< Request flushed from queue + ERR_TIMEOUT = -3, //!< Operation timed out + ERR_BAD_DATA = -4, //!< Data integrity check failed + ERR_PROTOCOL = -5, //!< Protocol error + ERR_UNSUPPORTED_DEV = -6, //!< Unsupported device + ERR_NO_MEMORY = -7, //!< Insufficient memory + ERR_INVALID_ARG = -8, //!< Invalid argument + ERR_BAD_ADDRESS = -9, //!< Bad address + ERR_BUSY = -10, //!< Resource is busy + ERR_BAD_FORMAT = -11, //!< Data format not recognized + ERR_NO_TIMER = -12, //!< No timer available + ERR_TIMER_ALREADY_RUNNING = -13, //!< Timer already running + ERR_TIMER_NOT_RUNNING = -14, //!< Timer not running + + /** + * \brief Operation in progress + * + * This status code is for driver-internal use when an operation + * is currently being performed. + * + * \note Drivers should never return this status code to any + * callers. It is strictly for internal use. + */ + OPERATION_IN_PROGRESS = -128, +}; + +typedef enum status_code_wireless status_code_t; + +/** @} */ + +#endif /* STATUS_CODES_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/system.c b/feather_sensor_transmit/libraries/Adafruit_ASFcore/system.c new file mode 100644 index 0000000..0121588 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/system.c @@ -0,0 +1,111 @@ +/** + * \file + * + * \brief SAM System related functionality + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#include + +/** + * \internal + * Dummy initialization function, used as a weak alias target for the various + * init functions called by \ref system_init(). + */ +void _system_dummy_init(void); +void _system_dummy_init(void) +{ + return; +} + +#if !defined(__DOXYGEN__) +# if defined(__GNUC__) +void system_clock_init(void) WEAK __attribute__((alias("_system_dummy_init"))); +void system_board_init(void) WEAK __attribute__((alias("_system_dummy_init"))); +void _system_events_init(void) WEAK __attribute__((alias("_system_dummy_init"))); +void _system_extint_init(void) WEAK __attribute__((alias("_system_dummy_init"))); +void _system_divas_init(void) WEAK __attribute__((alias("_system_dummy_init"))); +# elif defined(__ICCARM__) +void system_clock_init(void); +void system_board_init(void); +void _system_events_init(void); +void _system_extint_init(void); +void _system_divas_init(void); +# pragma weak system_clock_init=_system_dummy_init +# pragma weak system_board_init=_system_dummy_init +# pragma weak _system_events_init=_system_dummy_init +# pragma weak _system_extint_init=_system_dummy_init +# pragma weak _system_divas_init=_system_dummy_init +# endif +#endif + +/** + * \brief Initialize system + * + * This function will call the various initialization functions within the + * system namespace. If a given optional system module is not available, the + * associated call will effectively be a NOP (No Operation). + * + * Currently the following initialization functions are supported: + * - System clock initialization (via the SYSTEM CLOCK sub-module) + * - Board hardware initialization (via the Board module) + * - Event system driver initialization (via the EVSYS module) + * - External Interrupt driver initialization (via the EXTINT module) + */ +void system_init(void) +{ + /* Configure GCLK and clock sources according to conf_clocks.h */ + system_clock_init(); + + /* Initialize board hardware */ + system_board_init(); + + /* Initialize EVSYS hardware */ + _system_events_init(); + + /* Initialize External hardware */ + _system_extint_init(); + + /* Initialize DIVAS hardware */ + _system_divas_init(); +} + diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/system.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/system.h new file mode 100644 index 0000000..7b7bc00 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/system.h @@ -0,0 +1,726 @@ +/** + * \file + * + * \brief SAM System related functionality + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef SYSTEM_H_INCLUDED +#define SYSTEM_H_INCLUDED + +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup asfdoc_sam0_system_group SAM System (SYSTEM) Driver + * + * This driver for Atmel® | SMART ARM®-based microcontrollers provides an interface for the configuration + * and management of the device's system relation functionality, necessary for + * the basic device operation. This is not limited to a single peripheral, but + * extends across multiple hardware peripherals. + * + * The following peripherals are used by this module: + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * - PM (Power Manager) + * - RSTC(Reset Controller) + * - SUPC(Supply Controller) + * \endif + * \if DEVICE_SAMC21_SYSTEM_SUPPORT + * - PM (Power Manager) + * - RSTC(Reset Controller) + * - SUPC(Supply Controller) + * \endif + * \if DEVICE_SAMD21_SYSTEM_SUPPORT + * - SYSCTRL (System Control) + * - PM (Power Manager) + * \endif + * + * The following devices can use this module: + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * - Atmel | SMART SAM L21 + * \endif + * \if DEVICE_SAMC21_SYSTEM_SUPPORT + * - Atmel | SMART SAM C20/C21 + * \endif + * \if DEVICE_SAMD21_SYSTEM_SUPPORT + * - Atmel | SMART SAM D20/D21 + * - Atmel | SMART SAM R21 + * - Atmel | SMART SAM D09/D10/D11 + * - Atmel | SMART SAM DAx + * \endif + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_system_prerequisites + * - \ref asfdoc_sam0_system_module_overview + * - \ref asfdoc_sam0_system_special_considerations + * - \ref asfdoc_sam0_system_extra_info + * - \ref asfdoc_sam0_system_examples + * - \ref asfdoc_sam0_system_api_overview + * + * + * \section asfdoc_sam0_system_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * + * \section asfdoc_sam0_system_module_overview Module Overview + * + * The System driver provides a collection of interfaces between the user + * application logic, and the core device functionality (such as clocks, reset + * cause determination, etc.) that is required for all applications. It contains + * a number of sub-modules that control one specific aspect of the device: + * + * - System Core (this module) + * - \ref asfdoc_sam0_system_clock_group "System Clock Control" (sub-module) + * - \ref asfdoc_sam0_system_interrupt_group "System Interrupt Control" (sub-module) + * - \ref asfdoc_sam0_system_pinmux_group "System Pin Multiplexer Control" (sub-module) + * + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * \subsection asfdoc_sam0_system_module_overview_vreg_l21 Voltage Regulator + * The SAM device controls the voltage regulators for the core (VDDCORE) and + * backup (VDDBU) domains. It sets the voltage regulators according to the sleep + * modes, the performance level, or the user configuration. + * + * In active mode, the voltage regulator can be chosen on the fly between a LDO + * or a Buck converter. In standby mode, the low power voltage regulator is used + * to supply VDDCORE. + * + * \subsection asfdoc_sam0_system_module_overview_bbps Battery Backup Power Switch + * The SAM device supports connection of a battery backup to the VBAT power pin. + * It includes functionality that enables automatic power switching between main + * power and battery backup power. This will ensure power to the backup domain, + * when the main battery or power source is unavailable. + * \endif + * + * \if DEVICE_SAMC21_SYSTEM_SUPPORT + * \subsection asfdoc_sam0_system_module_overview_vreg_c21 Voltage Regulator + * The SAM device controls the voltage regulators for the core (VDDCORE). It sets + * the voltage regulators according to the sleep modes. + * + * There are a selectable reference voltage and voltage dependent on the temperature + * which can be used by analog modules like the ADC. + * \endif + * + * \subsection asfdoc_sam0_system_module_overview_vref Voltage References + * The various analog modules within the SAM devices (such as AC, ADC, and + * DAC) require a voltage reference to be configured to act as a reference point + * for comparisons and conversions. + * + * The SAM devices contain multiple references, including an internal + * temperature sensor and a fixed band-gap voltage source. When enabled, the + * associated voltage reference can be selected within the desired peripheral + * where applicable. + * + * \subsection asfdoc_sam0_system_module_overview_reset_cause System Reset Cause + * In some applications there may be a need to execute a different program + * flow based on how the device was reset. For example, if the cause of reset + * was the Watchdog timer (WDT), this might indicate an error in the application, + * and a form of error handling or error logging might be needed. + * + * For this reason, an API is provided to retrieve the cause of the last system + * reset, so that appropriate action can be taken. + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * There are three groups of reset sources: + * - Power supply reset: Resets caused by an electrical issue. It covers POR and BOD reset. + * - User reset: Resets caused by the application. It covers external reset, + * system reset, and watchdog reset. + * - Backup reset: Resets caused by a backup mode exit condition. + * + * \subsection asfdoc_sam0_system_module_overview_performance_level Performance Level + * Performance level allows the user to adjust the regulator output voltage to reduce + * power consumption. The user can on the fly select the most suitable performance + * level, depending on the application demands. + * + * The SAM device can operate at two different performance levels (PL0 and PL2). + * When operating at PL0, the voltage applied on the full logic area is reduced + * by voltage scaling. This voltage scaling technique allows to reduce the active + * power consumption while decreasing the maximum frequency of the device. When + * operating at PL2, the voltage regulator supplies the highest voltage, allowing + * the device to run at higher clock speeds. + * + * Performance level transition is possible only when the device is in active + * mode. After a reset, the device starts at the lowest performance level + * (lowest power consumption and lowest max. frequency). The application can then + * switch to another performance level at any time without any stop in the code + * execution. As shown in \ref asfdoc_sam0_system_performance_level_transition_figure. + * + * \note When scaling down the performance level, the bus frequency should first be + * scaled down in order to not exceed the maximum frequency allowed for the + * low performance level. + * When scaling up the performance level (e.g. from PL0 to PL2), check the performance + * level status before increasing the bus frequency. It can be increased only + * when the performance level transition is completed. + * + * \anchor asfdoc_sam0_system_performance_level_transition_figure + * \image html performance_level_transition.svg "Performance Level Transition" + * + * \subsection asfdoc_sam0_system_module_overview_power_domain Power Domain Gating + * Power domain gating allows power saving by reducing the voltage in logic + * areas in the device to a low-power supply. The feature is available in + * Standby sleep mode and will reduce the voltage in domains where all peripherals + * are idle. Internal logic will maintain its content, meaning the corresponding + * peripherals will not need to be reconfigured when normal operating voltage + * is returned. Most power domains can be in the following three states: + * + * - Active state: The power domain is powered on. + * - Retention state: The main voltage supply for the power domain is switched off, + * while maintaining a secondary low-power supply for the sequential cells. The + * logic context is restored when waking up. + * - Off state: The power domain is entirely powered off. The logic context is lost. + * + * The SAM L21 device contains three power domains which can be controlled using + * power domain gating, namely PD0, PD1, and PD2. These power domains can be + * configured to the following cases: + * - Default with no sleepwalking peripherals: A power domain is automatically set + * to retention state in standby sleep mode if no activity require it. The application + * can force all power domains to remain in active state during standby sleep mode + * in order to accelerate wakeup time. + * - Default with sleepwalking peripherals: If one or more peripherals are enabled + * to perform sleepwalking tasks in standby sleep mode, the corresponding power + * domain (PDn) remains in active state as well as all inferior power domains (PDn) in order + * to perform a sleepwalking task. The superior power domain is then automatically + * set to active state. At the end of the sleepwalking task, the device can either + * be woken up or the superior power domain can return to retention state. + * + * Power domains can be linked to each other, it allows a power domain (PDn) to be kept + * in active state if the inferior power domain (PDn-1) is in active state too. + * + * \ref asfdoc_sam0_system_power_domain_overview_table illustrates the + * four cases to consider in standby mode. + * + * \anchor asfdoc_sam0_system_power_domain_overview_table + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Sleep Mode versus Power Domain State Overview
Sleep modePD0PD1PD2PDTOPPDBACKUP
Idleactiveactiveactiveactiveactive
Standby - Case 1activeactiveactiveactiveactive
Standby - Case 2activeactiveretentionactiveactive
Standby - Case 3activeretentionretentionactiveactive
Standby - Case 4retentionretentionretentionactiveactive
Backupoffoffoffoffactive
Offoffoffoffoffoff
+ * + * \subsection asfdoc_sam0_system_module_overview_ram_state RAMs Low Power Mode + * By default, in standby sleep mode, RAM is in low power mode (back biased) + * if its power domain is in retention state. + * \ref asfdoc_sam0_system_power_ram_state_table lists RAMs low power mode. + * + * \anchor asfdoc_sam0_system_power_ram_state_table + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
RAM Back-biasing Mode
RAM modeDescription
Retention Back-biasing modeRAM is back-biased if its power domain is in retention mode
Standby Back-biasing modeRAM is back-biased if the device is in standby mode
Standby OFF modeRAM is OFF if the device is in standby mode
Always OFF modeRAM is OFF if the device is in RET mode
+ * + * \endif + * + * \subsection asfdoc_sam0_system_module_overview_sleep_mode Sleep Modes + * The SAM devices have several sleep modes. The sleep mode controls + * which clock systems on the device will remain enabled or disabled when the + * device enters a low power sleep mode. + * \ref asfdoc_sam0_system_module_sleep_mode_table "The table below" lists the + * clock settings of the different sleep modes. + * + * \anchor asfdoc_sam0_system_module_sleep_mode_table + * + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * \else + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * \endif + *
SAM Device Sleep Modes
Sleep modeSystem clockCPU clockAHB/AHB clockGCLK clocksOscillators (ONDEMAND = 0)Oscillators (ONDEMAND = 1)Regulator modeRAM mode
IdleRunStopRun if requestedRunRunRun if requestedNormalNormal
StandbyStopStopRun if requestedRun if requestedRun if requested or RUNSTDBY = 1Run if requestedLow pwerLow pwer
BackupStopStopStopStopStopStopBackupOff
OffOffOffOffOffOffOffOffOff
Sleep modeCPU clockAHB clockAPB clocksClock sourcesSystem clock32KHzReg modeRAM mode
Idle 0StopRunRunRunRunRunNormalNormal
Idle 1StopStopRunRunRunRunNormalNormal
Idle 2StopStopStopRunRunRunNormalNormal
StandbyStopStopStopStopStopStopLow PowerSource/Drain biasing
+ * + * Before entering device sleep, one of the available sleep modes must be set. + * The device will automatically wake up in response to an interrupt being + * generated or upon any other sleep mode exit condition. + * + * Some peripheral clocks will remain enabled during sleep, depending on their + * configuration. If desired, the modules can remain clocked during sleep to allow + * them continue to operate while other parts of the system are powered down + * to save power. + * + * + * \section asfdoc_sam0_system_special_considerations Special Considerations + * + * Most of the functions in this driver have device specific restrictions and + * caveats; refer to your device datasheet. + * + * + * \section asfdoc_sam0_system_extra_info Extra Information + * + * For extra information, see \ref asfdoc_sam0_system_extra. This includes: + * - \ref asfdoc_sam0_system_extra_acronyms + * - \ref asfdoc_sam0_system_extra_dependencies + * - \ref asfdoc_sam0_system_extra_errata + * - \ref asfdoc_sam0_system_extra_history + * + * + * \section asfdoc_sam0_system_examples Examples + * + * For SYSTEM module related examples, refer to the sub-modules listed in + * the \ref asfdoc_sam0_system_module_overview "system module overview". + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_drivers_power_exqsg. + * + * + * \section asfdoc_sam0_system_api_overview API Overview + * @{ + */ + +/** + * \name System Debugger + * @{ + */ + +/** + * \brief Check if debugger is present. + * + * Check if debugger is connected to the onboard debug system (DAP). + * + * \return A bool identifying if a debugger is present. + * + * \retval true Debugger is connected to the system + * \retval false Debugger is not connected to the system + * + */ +static inline bool system_is_debugger_present(void) +{ + return DSU->STATUSB.reg & DSU_STATUSB_DBGPRES; +} + +/** + * @} + */ + +/** + * \name System Identification + * @{ + */ + +/** + * \brief Retrieve the device identification signature. + * + * Retrieves the signature of the current device. + * + * \return Device ID signature as a 32-bit integer. + */ +static inline uint32_t system_get_device_id(void) +{ + return DSU->DID.reg; +} + +/** + * @} + */ + +/** + * \name System Initialization + * @{ + */ + +void system_init(void); + +/** + * @} + */ + + +/** + * @} + */ + +/** + +* \page asfdoc_sam0_drivers_power_exqsg Examples for Power Driver + * + * This is a list of the available Quick Start Guides (QSGs) and example + * applications. QSGs are simple examples with step-by-step instructions to + * configure and use this driver in a selection of + * use cases. Note that a QSG can be compiled as a standalone application or be + * added to the user application. + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * - \subpage asfdoc_sam0_power_basic_use_case + * \endif + * + * \page asfdoc_sam0_system_extra Extra Information for SYSTEM Driver + * + * \section asfdoc_sam0_system_extra_acronyms Acronyms + * Below is a table listing the acronyms used in this module, along with their + * intended meanings. + * + * + * + * + * + * + * + * + * + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * + * + * + * + * + * + * + * + * \endif + * \if DEVICE_SAMC21_SYSTEM_SUPPORT + * + * + * + * + * + * + * + * + * \endif + * \if DEVICE_SAMD21_SYSTEM_SUPPORT + * + * + * + * + * \endif + *
AcronymDefinition
PMPower Manager
SUPCSupply Controller
RSTCReset Controller
SUPCSupply Controller
RSTCReset Controller
SYSCTRLSystem control interface
+ * + * + * \section asfdoc_sam0_system_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - None + * + * + * \section asfdoc_sam0_system_extra_errata Errata + * There are no errata related to this driver. + * + * + * \section asfdoc_sam0_system_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * + * + * + * \endif + * \if DEVICE_SAMC21_SYSTEM_SUPPORT + * + * + * + * \endif + * \if DEVICE_SAMD21_SYSTEM_SUPPORT + * + * + * + * + * + * + * + * + * + * \endif + *
Changelog
Initial Release
Initial Release
Added new \c system_reset() to reset the complete MCU with some exceptions
Added new \c system_get_device_id() function to retrieved the device + * ID.
Initial Release
+ * + * \page asfdoc_sam0_system_document_revision_history Document Revision History + * + * + * + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * + * + * + * + * + * \endif + * \if DEVICE_SAMC21_SYSTEM_SUPPORT + * + * + * + * + * + * \endif + * \if DEVICE_SAMD21_SYSTEM_SUPPORT + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * \endif + *
Doc. Rev. + * Date + * Comments + *
42449A07/2015Initial document release
42484A08/2015Initial document release.
42120E04/2015Added support for SAMDAx
42120D12/2014Added support for SAMR21 and SAMD10/D11
42120C01/2014Added support for SAMD21
42120B06/2013Corrected documentation typos
42120A06/2013Initial document release
+ */ + +#ifdef __cplusplus +} +#endif + +#endif /* SYSTEM_H_INCLUDED */ + diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/system_interrupt.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/system_interrupt.h new file mode 100644 index 0000000..93a542d --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/system_interrupt.h @@ -0,0 +1,429 @@ +/** + * \file + * + * \brief SAM System Interrupt Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef SYSTEM_INTERRUPT_H_INCLUDED +#define SYSTEM_INTERRUPT_H_INCLUDED + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup asfdoc_sam0_system_interrupt_group SAM System Interrupt (SYSTEM INTERRUPT) Driver + * + * This driver for Atmel® | SMART ARM®-based microcontrollers provides + * an interface for the configuration and management of internal software and + * hardware interrupts/exceptions. + * + * The following peripheral is used by this module: + * - NVIC (Nested Vector Interrupt Controller) + * + * The following devices can use this module: + * - Atmel | SMART SAM D20/D21 + * - Atmel | SMART SAM R21 + * - Atmel | SMART SAM D09/D10/D11 + * - Atmel | SMART SAM L21/L22 + * - Atmel | SMART SAM DA1 + * - Atmel | SMART SAM C20/C21 + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_system_interrupt_prerequisites + * - \ref asfdoc_sam0_system_interrupt_module_overview + * - \ref asfdoc_sam0_system_interrupt_special_considerations + * - \ref asfdoc_sam0_system_interrupt_extra_info + * - \ref asfdoc_sam0_system_interrupt_examples + * - \ref asfdoc_sam0_system_interrupt_api_overview + * + * + * \section asfdoc_sam0_system_interrupt_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * + * \section asfdoc_sam0_system_interrupt_module_overview Module Overview + * + * The ARM® Cortex® M0+ core contains an interrupt and exception vector table, which + * can be used to configure the device's interrupt handlers; individual + * interrupts and exceptions can be enabled and disabled, as well as configured + * with a variable priority. + * + * This driver provides a set of wrappers around the core interrupt functions, + * to expose a simple API for the management of global and individual interrupts + * within the device. + * + * \subsection asfdoc_sam0_system_interrupt_module_overview_criticalsec Critical Sections + * In some applications it is important to ensure that no interrupts may be + * executed by the system whilst a critical portion of code is being run; for + * example, a buffer may be copied from one context to another - during which + * interrupts must be disabled to avoid corruption of the source buffer contents + * until the copy has completed. This driver provides a basic API to enter and + * exit nested critical sections, so that global interrupts can be kept disabled + * for as long as necessary to complete a critical application code section. + * + * \subsection asfdoc_sam0_system_interrupt_module_overview_softints Software Interrupts + * For some applications, it may be desirable to raise a module or core + * interrupt via software. For this reason, a set of APIs to set an interrupt or + * exception as pending are provided to the user application. + * + * \section asfdoc_sam0_system_interrupt_special_considerations Special Considerations + * + * Interrupts from peripherals in the SAM devices are on a per-module basis; + * an interrupt raised from any source within a module will cause a single, + * module-common handler to execute. It is the user application or driver's + * responsibility to de-multiplex the module-common interrupt to determine the + * exact interrupt cause. + * + * \section asfdoc_sam0_system_interrupt_extra_info Extra Information + * + * For extra information, see \ref asfdoc_sam0_system_interrupt_extra. This includes: + * - \ref asfdoc_sam0_system_interrupt_extra_acronyms + * - \ref asfdoc_sam0_system_interrupt_extra_dependencies + * - \ref asfdoc_sam0_system_interrupt_extra_errata + * - \ref asfdoc_sam0_system_interrupt_extra_history + * + * + * \section asfdoc_sam0_system_interrupt_examples Examples + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_system_interrupt_exqsg. + * + * \section asfdoc_sam0_system_interrupt_api_overview API Overview + * @{ + */ + +#include "compiler.h" +#include +#include "system_interrupt_features.h" + +/** + * \brief Table of possible system interrupt/exception vector priorities. + * + * Table of all possible interrupt and exception vector priorities within the + * device. + */ +enum system_interrupt_priority_level { + /** Priority level 0, the highest possible interrupt priority */ + SYSTEM_INTERRUPT_PRIORITY_LEVEL_0 = 0, + /** Priority level 1 */ + SYSTEM_INTERRUPT_PRIORITY_LEVEL_1 = 1, + /** Priority level 2 */ + SYSTEM_INTERRUPT_PRIORITY_LEVEL_2 = 2, + /** Priority level 3, the lowest possible interrupt priority */ + SYSTEM_INTERRUPT_PRIORITY_LEVEL_3 = 3, +}; + +/** + * \name Critical Section Management + * @{ + */ + +/** + * \brief Enters a critical section. + * + * Disables global interrupts. To support nested critical sections, an internal + * count of the critical section nesting will be kept, so that global interrupts + * are only re-enabled upon leaving the outermost nested critical section. + * + */ +static inline void system_interrupt_enter_critical_section(void) +{ + cpu_irq_enter_critical(); +} + +/** + * \brief Leaves a critical section. + * + * Enables global interrupts. To support nested critical sections, an internal + * count of the critical section nesting will be kept, so that global interrupts + * are only re-enabled upon leaving the outermost nested critical section. + * + */ +static inline void system_interrupt_leave_critical_section(void) +{ + cpu_irq_leave_critical(); +} + +/** @} */ + +/** + * \name Interrupt Enabling/Disabling + * @{ + */ + +/** + * \brief Check if global interrupts are enabled. + * + * Checks if global interrupts are currently enabled. + * + * \returns A boolean that identifies if the global interrupts are enabled or not. + * + * \retval true Global interrupts are currently enabled + * \retval false Global interrupts are currently disabled + * + */ +static inline bool system_interrupt_is_global_enabled(void) +{ + return cpu_irq_is_enabled(); +} + +/** + * \brief Enables global interrupts. + * + * Enables global interrupts in the device to fire any enabled interrupt handlers. + */ +static inline void system_interrupt_enable_global(void) +{ + cpu_irq_enable(); +} + +/** + * \brief Disables global interrupts. + * + * Disabled global interrupts in the device, preventing any enabled interrupt + * handlers from executing. + */ +static inline void system_interrupt_disable_global(void) +{ + cpu_irq_disable(); +} + +/** + * \brief Checks if an interrupt vector is enabled or not. + * + * Checks if a specific interrupt vector is currently enabled. + * + * \param[in] vector Interrupt vector number to check + * + * \returns A variable identifying if the requested interrupt vector is enabled. + * + * \retval true Specified interrupt vector is currently enabled + * \retval false Specified interrupt vector is currently disabled + * + */ +static inline bool system_interrupt_is_enabled( + const enum system_interrupt_vector vector) +{ + return (bool)((NVIC->ISER[0] >> (uint32_t)vector) & 0x00000001); +} + +/** + * \brief Enable interrupt vector. + * + * Enables execution of the software handler for the requested interrupt vector. + * + * \param[in] vector Interrupt vector to enable + */ +static inline void system_interrupt_enable( + const enum system_interrupt_vector vector) +{ + NVIC->ISER[0] = (uint32_t)(1 << ((uint32_t)vector & 0x0000001f)); +} + +/** + * \brief Disable interrupt vector. + * + * Disables execution of the software handler for the requested interrupt vector. + * + * \param[in] vector Interrupt vector to disable + */ +static inline void system_interrupt_disable( + const enum system_interrupt_vector vector) +{ + NVIC->ICER[0] = (uint32_t)(1 << ((uint32_t)vector & 0x0000001f)); +} + +/** @} */ + +/** + * \name Interrupt State Management + * @{ + */ + +/** + * \brief Get active interrupt (if any). + * + * Return the vector number for the current executing software handler, if any. + * + * \return Interrupt number that is currently executing. + */ +static inline enum system_interrupt_vector system_interrupt_get_active(void) +{ + uint32_t IPSR = __get_IPSR(); + /* The IPSR returns the Exception number, which with an offset 16 to IRQ number. */ + return (enum system_interrupt_vector)((IPSR & _SYSTEM_INTERRUPT_IPSR_MASK) - 16); +} + +bool system_interrupt_is_pending( + const enum system_interrupt_vector vector); + +enum status_code system_interrupt_set_pending( + const enum system_interrupt_vector vector); + +enum status_code system_interrupt_clear_pending( + const enum system_interrupt_vector vector); + +/** @} */ + +/** + * \name Interrupt Priority Management + * @{ + */ + +enum status_code system_interrupt_set_priority( + const enum system_interrupt_vector vector, + const enum system_interrupt_priority_level priority_level); + +enum system_interrupt_priority_level system_interrupt_get_priority( + const enum system_interrupt_vector vector); + +/** @} */ + +/** @} */ + +/** + * \page asfdoc_sam0_system_interrupt_extra Extra Information for SYSTEM INTERRUPT Driver + * + * \section asfdoc_sam0_system_interrupt_extra_acronyms Acronyms + * The table below presents the acronyms used in this module: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
AcronymDescription
ISRInterrupt Service Routine
NMINon-maskable Interrupt
SERCOMSerial Communication Interface
+ * + * + * \section asfdoc_sam0_system_interrupt_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - None + * + * + * \section asfdoc_sam0_system_interrupt_extra_errata Errata + * There are no errata related to this driver. + * + * + * \section asfdoc_sam0_system_interrupt_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * + * + * + *
Changelog
Initial Release
+ */ + +/** + * \page asfdoc_sam0_system_interrupt_exqsg Examples for SYSTEM INTERRUPT Driver + * + * This is a list of the available Quick Start guides (QSGs) and example + * applications for \ref asfdoc_sam0_system_interrupt_group. QSGs are simple examples with + * step-by-step instructions to configure and use this driver in a selection of + * use cases. Note that a QSG can be compiled as a standalone application or be + * added to the user application. + * + * - \subpage asfdoc_sam0_system_interrupt_critsec_use_case + * - \subpage asfdoc_sam0_system_interrupt_enablemodint_use_case + * + * \page asfdoc_sam0_system_interrupt_document_revision_history Document Revision History + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Doc. Rev. + * Date + * Comments + *
42122E08/2015Added support for SAM L21/L22, SAM DA1, and SAM C20/C21
42122D12/2014Added support for SAM R21 and SAM D10/D11
42122C01/2014Added support for SAM D21
42122B06/2013Corrected documentation typos
42122A06/2013Initial release
+ */ + +#ifdef __cplusplus +} +#endif + +#endif // #ifndef SYSTEM_INTERRUPT_H_INCLUDED diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/system_interrupt_features.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/system_interrupt_features.h new file mode 100644 index 0000000..25dfa83 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/system_interrupt_features.h @@ -0,0 +1,195 @@ +/** + * \file + * + * \brief SAM D21 System Interrupt Driver + * + * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#ifndef SYSTEM_INTERRUPT_FEATURES_H_INCLUDED +#define SYSTEM_INTERRUPT_FEATURES_H_INCLUDED + +#if !defined(__DOXYGEN__) + +/* Generates a interrupt vector table enum list entry for a given module type + and index (e.g. "SYSTEM_INTERRUPT_MODULE_TC0 = TC0_IRQn,"). */ +# define _MODULE_IRQn(n, module) \ + SYSTEM_INTERRUPT_MODULE_##module##n = module##n##_IRQn, + +/* Generates interrupt vector table enum list entries for all instances of a + given module type on the selected device. */ +# define _SYSTEM_INTERRUPT_MODULES(name) \ + MREPEAT(name##_INST_NUM, _MODULE_IRQn, name) + +# define _SYSTEM_INTERRUPT_IPSR_MASK 0x0000003f +# define _SYSTEM_INTERRUPT_PRIORITY_MASK 0x00000003 + +# define _SYSTEM_INTERRUPT_EXTERNAL_VECTOR_START 0 + +# define _SYSTEM_INTERRUPT_SYSTICK_PRI_POS 30 +#endif + +/** + * \addtogroup asfdoc_sam0_system_interrupt_group + * @{ + */ + +/** + * \brief Table of possible system interrupt/exception vector numbers. + * + * Table of all possible interrupt and exception vector indexes within the + * SAM D21 device. Check peripherals configuration in SAM D21 datasheet for + * available vector index for specific device. + * + */ +#if defined(__DOXYGEN__) +/** \note The actual enumeration name is "system_interrupt_vector". */ +enum system_interrupt_vector_samd21 { +#else +enum system_interrupt_vector { +#endif + /** Interrupt vector index for a NMI interrupt */ + SYSTEM_INTERRUPT_NON_MASKABLE = NonMaskableInt_IRQn, + /** Interrupt vector index for a Hard Fault memory access exception */ + SYSTEM_INTERRUPT_HARD_FAULT = HardFault_IRQn, + /** Interrupt vector index for a Supervisor Call exception */ + SYSTEM_INTERRUPT_SV_CALL = SVCall_IRQn, + /** Interrupt vector index for a Pending Supervisor interrupt */ + SYSTEM_INTERRUPT_PENDING_SV = PendSV_IRQn, + /** Interrupt vector index for a System Tick interrupt */ + SYSTEM_INTERRUPT_SYSTICK = SysTick_IRQn, + + /** Interrupt vector index for a Power Manager peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_PM = PM_IRQn, + /** Interrupt vector index for a System Control peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_SYSCTRL = SYSCTRL_IRQn, + /** Interrupt vector index for a Watch Dog peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_WDT = WDT_IRQn, + /** Interrupt vector index for a Real Time Clock peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_RTC = RTC_IRQn, + /** Interrupt vector index for an External Interrupt peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_EIC = EIC_IRQn, + /** Interrupt vector index for a Non Volatile Memory Controller interrupt */ + SYSTEM_INTERRUPT_MODULE_NVMCTRL = NVMCTRL_IRQn, + /** Interrupt vector index for a Direct Memory Access interrupt */ + SYSTEM_INTERRUPT_MODULE_DMA = DMAC_IRQn, +#if defined(__DOXYGEN__) || defined(ID_USB) + /** Interrupt vector index for a Universal Serial Bus interrupt */ + SYSTEM_INTERRUPT_MODULE_USB = USB_IRQn, +#endif + /** Interrupt vector index for an Event System interrupt */ + SYSTEM_INTERRUPT_MODULE_EVSYS = EVSYS_IRQn, +#if defined(__DOXYGEN__) + /** Interrupt vector index for a SERCOM peripheral interrupt. + * + * Each specific device may contain several SERCOM peripherals; each module + * instance will have its own entry in the table, with the instance number + * substituted for "n" in the entry name (e.g. + * \c SYSTEM_INTERRUPT_MODULE_SERCOM0). + */ + SYSTEM_INTERRUPT_MODULE_SERCOMn = SERCOMn_IRQn, + + /** Interrupt vector index for a Timer/Counter Control peripheral interrupt. + * + * Each specific device may contain several TCC peripherals; each module + * instance will have its own entry in the table, with the instance number + * substituted for "n" in the entry name (e.g. + * \c SYSTEM_INTERRUPT_MODULE_TCC0). + */ + SYSTEM_INTERRUPT_MODULE_TCCn = TCCn_IRQn, + + /** Interrupt vector index for a Timer/Counter peripheral interrupt. + * + * Each specific device may contain several TC peripherals; each module + * instance will have its own entry in the table, with the instance number + * substituted for "n" in the entry name (e.g. + * \c SYSTEM_INTERRUPT_MODULE_TC3). + */ + SYSTEM_INTERRUPT_MODULE_TCn = TCn_IRQn, +#else + _SYSTEM_INTERRUPT_MODULES(SERCOM) + + _SYSTEM_INTERRUPT_MODULES(TCC) + + SYSTEM_INTERRUPT_MODULE_TC3 = TC3_IRQn, + SYSTEM_INTERRUPT_MODULE_TC4 = TC4_IRQn, + SYSTEM_INTERRUPT_MODULE_TC5 = TC5_IRQn, +# if defined(ID_TC6) + SYSTEM_INTERRUPT_MODULE_TC6 = TC6_IRQn, +# endif +# if defined(ID_TC7) + SYSTEM_INTERRUPT_MODULE_TC7 = TC7_IRQn, +# endif +#endif + +#if defined(__DOXYGEN__) || defined(ID_ADC) + /** Interrupt vector index for an Analog-to-Digital peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_ADC = ADC_IRQn, +#endif + +#if defined(__DOXYGEN__) || defined(ID_AC) + /** Interrupt vector index for an Analog Comparator peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_AC = AC_IRQn, +#endif + +#if defined(__DOXYGEN__) || defined(ID_DAC) + /** Interrupt vector index for a Digital-to-Analog peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_DAC = DAC_IRQn, +#endif +#if defined(__DOXYGEN__) || defined(ID_PTC) + /** Interrupt vector index for a Peripheral Touch Controller peripheral + * interrupt */ + SYSTEM_INTERRUPT_MODULE_PTC = PTC_IRQn, +#endif +#if defined(__DOXYGEN__) || defined(ID_I2S) + /** Interrupt vector index for a Inter-IC Sound Interface peripheral + * interrupt */ + SYSTEM_INTERRUPT_MODULE_I2S = I2S_IRQn, +#endif +#if defined(__DOXYGEN__) || defined(ID_AC1) + /** Interrupt vector index for an Analog Comparator 1 peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_AC1 = AC1_IRQn, +#endif +}; + +/** @} */ + +#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc.c b/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc.c new file mode 100644 index 0000000..23e2703 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc.c @@ -0,0 +1,685 @@ +/** + * \file + * + * \brief SAM TC - Timer Counter Driver + * + * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#include "tc.h" + +#if TC_ASYNC == true +# include "tc_interrupt.h" +# include + +/** \internal + * Converts a given TC index to its interrupt vector index. + */ +# define _TC_INTERRUPT_VECT_NUM(n, unused) \ + SYSTEM_INTERRUPT_MODULE_TC##n, +#endif + +#if !defined(__DOXYGEN__) +# define _TC_GCLK_ID(n,unused) TPASTE3(TC,n,_GCLK_ID) , +# define _TC_PM_APBCMASK(n,unused) TPASTE2(PM_APBCMASK_TC,n) , + +# define TC_INST_GCLK_ID { MRECURSION(TC_INST_NUM, _TC_GCLK_ID, TC_INST_MAX_ID) } +# define TC_INST_PM_APBCMASK { MRECURSION(TC_INST_NUM, _TC_PM_APBCMASK, TC_INST_MAX_ID) } + +#endif + +/** + * \internal Find the index of given TC module instance. + * + * \param[in] TC module instance pointer. + * + * \return Index of the given TC module instance. + */ +uint8_t _tc_get_inst_index( + Tc *const hw) +{ + /* List of available TC modules. */ + Tc *const tc_modules[TC_INST_NUM] = TC_INSTS; + + /* Find index for TC instance. */ + for (uint32_t i = 0; i < TC_INST_NUM; i++) { + if (hw == tc_modules[i]) { + return i; + } + } + + /* Invalid data given. */ + Assert(false); + return 0; +} + + +/** + * \brief Initializes a hardware TC module instance. + * + * Enables the clock and initializes the TC module, based on the given + * configuration values. + * + * \param[in,out] module_inst Pointer to the software module instance struct + * \param[in] hw Pointer to the TC hardware module + * \param[in] config Pointer to the TC configuration options struct + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The module was initialized successfully + * \retval STATUS_BUSY Hardware module was busy when the + * initialization procedure was attempted + * \retval STATUS_INVALID_ARG An invalid configuration option or argument + * was supplied + * \retval STATUS_ERR_DENIED Hardware module was already enabled, or the + * hardware module is configured in 32-bit + * slave mode + */ +enum status_code tc_init( + struct tc_module *const module_inst, + Tc *const hw, + const struct tc_config *const config) +{ + /* Sanity check arguments */ + Assert(hw); + Assert(module_inst); + Assert(config); + + /* Temporary variable to hold all updates to the CTRLA + * register before they are written to it */ + uint16_t ctrla_tmp = 0; + /* Temporary variable to hold all updates to the CTRLBSET + * register before they are written to it */ + uint8_t ctrlbset_tmp = 0; + /* Temporary variable to hold all updates to the CTRLC + * register before they are written to it */ + uint8_t ctrlc_tmp = 0; + /* Temporary variable to hold TC instance number */ + uint8_t instance = _tc_get_inst_index(hw); + + /* Array of GLCK ID for different TC instances */ + uint8_t inst_gclk_id[] = TC_INST_GCLK_ID; + /* Array of PM APBC mask bit position for different TC instances */ + uint16_t inst_pm_apbmask[] = TC_INST_PM_APBCMASK; + + struct system_pinmux_config pin_config; + struct system_gclk_chan_config gclk_chan_config; + +#if TC_ASYNC == true + /* Initialize parameters */ + for (uint8_t i = 0; i < TC_CALLBACK_N; i++) { + module_inst->callback[i] = NULL; + } + module_inst->register_callback_mask = 0x00; + module_inst->enable_callback_mask = 0x00; + + /* Register this instance for callbacks*/ + _tc_instances[instance] = module_inst; +#endif + + /* Associate the given device instance with the hardware module */ + module_inst->hw = hw; + +#if SAMD09 || SAMD10 || SAMD11 + /* Check if even numbered TC modules are being configured in 32-bit + * counter size. Only odd numbered counters are allowed to be + * configured in 32-bit counter size. + */ + if ((config->counter_size == TC_COUNTER_SIZE_32BIT) && + !((instance + TC_INSTANCE_OFFSET) & 0x01)) { + Assert(false); + return STATUS_ERR_INVALID_ARG; + } +#else + /* Check if odd numbered TC modules are being configured in 32-bit + * counter size. Only even numbered counters are allowed to be + * configured in 32-bit counter size. + */ + if ((config->counter_size == TC_COUNTER_SIZE_32BIT) && + ((instance + TC_INSTANCE_OFFSET) & 0x01)) { + Assert(false); + return STATUS_ERR_INVALID_ARG; + } +#endif + + /* Make the counter size variable in the module_inst struct reflect + * the counter size in the module + */ + module_inst->counter_size = config->counter_size; + + if (hw->COUNT8.CTRLA.reg & TC_CTRLA_SWRST) { + /* We are in the middle of a reset. Abort. */ + return STATUS_BUSY; + } + + if (hw->COUNT8.STATUS.reg & TC_STATUS_SLAVE) { + /* Module is used as a slave */ + return STATUS_ERR_DENIED; + } + + if (hw->COUNT8.CTRLA.reg & TC_CTRLA_ENABLE) { + /* Module must be disabled before initialization. Abort. */ + return STATUS_ERR_DENIED; + } + + /* Set up the TC PWM out pin for channel 0 */ + if (config->pwm_channel[0].enabled) { + system_pinmux_get_config_defaults(&pin_config); + pin_config.mux_position = config->pwm_channel[0].pin_mux; + pin_config.direction = SYSTEM_PINMUX_PIN_DIR_OUTPUT; + system_pinmux_pin_set_config( + config->pwm_channel[0].pin_out, &pin_config); + } + + /* Set up the TC PWM out pin for channel 1 */ + if (config->pwm_channel[1].enabled) { + system_pinmux_get_config_defaults(&pin_config); + pin_config.mux_position = config->pwm_channel[1].pin_mux; + pin_config.direction = SYSTEM_PINMUX_PIN_DIR_OUTPUT; + system_pinmux_pin_set_config( + config->pwm_channel[1].pin_out, &pin_config); + } + + /* Enable the user interface clock in the PM */ + system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, + inst_pm_apbmask[instance]); + + /* Enable the slave counter if counter_size is 32-bit */ + if ((config->counter_size == TC_COUNTER_SIZE_32BIT)) + { + /* Enable the user interface clock in the PM */ + system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, + inst_pm_apbmask[instance + 1]); + } + + /* Setup clock for module */ + system_gclk_chan_get_config_defaults(&gclk_chan_config); + gclk_chan_config.source_generator = config->clock_source; + system_gclk_chan_set_config(inst_gclk_id[instance], &gclk_chan_config); + system_gclk_chan_enable(inst_gclk_id[instance]); + + /* Set ctrla register */ + ctrla_tmp = + (uint32_t)config->counter_size | + (uint32_t)config->wave_generation | + (uint32_t)config->reload_action | + (uint32_t)config->clock_prescaler; + + if (config->run_in_standby) { + ctrla_tmp |= TC_CTRLA_RUNSTDBY; + } + + /* Write configuration to register */ + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + hw->COUNT8.CTRLA.reg = ctrla_tmp; + + /* Set ctrlb register */ + if (config->oneshot) { + ctrlbset_tmp = TC_CTRLBSET_ONESHOT; + } + + if (config->count_direction) { + ctrlbset_tmp |= TC_CTRLBSET_DIR; + } + + /* Clear old ctrlb configuration */ + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + hw->COUNT8.CTRLBCLR.reg = 0xFF; + + /* Check if we actually need to go into a wait state. */ + if (ctrlbset_tmp) { + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + /* Write configuration to register */ + hw->COUNT8.CTRLBSET.reg = ctrlbset_tmp; + } + + /* Set ctrlc register*/ + ctrlc_tmp = config->waveform_invert_output; + for (uint8_t i = 0; i < NUMBER_OF_COMPARE_CAPTURE_CHANNELS; i++) { + if (config->enable_capture_on_channel[i] == true) { + ctrlc_tmp |= (TC_CTRLC_CPTEN(1) << i); + } + } + + /* Write configuration to register */ + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + hw->COUNT8.CTRLC.reg = ctrlc_tmp; + + /* Write configuration to register */ + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Switch for TC counter size */ + switch (module_inst->counter_size) { + case TC_COUNTER_SIZE_8BIT: + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT8.COUNT.reg = + config->counter_8_bit.value; + + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT8.PER.reg = + config->counter_8_bit.period; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT8.CC[0].reg = + config->counter_8_bit.compare_capture_channel[0]; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT8.CC[1].reg = + config->counter_8_bit.compare_capture_channel[1]; + + return STATUS_OK; + + case TC_COUNTER_SIZE_16BIT: + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT16.COUNT.reg + = config->counter_16_bit.value; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT16.CC[0].reg = + config->counter_16_bit.compare_capture_channel[0]; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT16.CC[1].reg = + config->counter_16_bit.compare_capture_channel[1]; + + return STATUS_OK; + + case TC_COUNTER_SIZE_32BIT: + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT32.COUNT.reg + = config->counter_32_bit.value; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT32.CC[0].reg = + config->counter_32_bit.compare_capture_channel[0]; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT32.CC[1].reg = + config->counter_32_bit.compare_capture_channel[1]; + + return STATUS_OK; + } + + Assert(false); + return STATUS_ERR_INVALID_ARG; +} + +/** + * \brief Sets TC module count value. + * + * Sets the current timer count value of a initialized TC module. The + * specified TC module may be started or stopped. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] count New timer count value to set + * + * \return Status of the count update procedure. + * + * \retval STATUS_OK The timer count was updated successfully + * \retval STATUS_ERR_INVALID_ARG An invalid timer counter size was specified + */ +enum status_code tc_set_count_value( + const struct tc_module *const module_inst, + const uint32_t count) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance*/ + Tc *const tc_module = module_inst->hw; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Write to based on the TC counter_size */ + switch (module_inst->counter_size) { + case TC_COUNTER_SIZE_8BIT: + tc_module->COUNT8.COUNT.reg = (uint8_t)count; + return STATUS_OK; + + case TC_COUNTER_SIZE_16BIT: + tc_module->COUNT16.COUNT.reg = (uint16_t)count; + return STATUS_OK; + + case TC_COUNTER_SIZE_32BIT: + tc_module->COUNT32.COUNT.reg = (uint32_t)count; + return STATUS_OK; + + default: + return STATUS_ERR_INVALID_ARG; + } +} + +/** + * \brief Get TC module count value. + * + * Retrieves the current count value of a TC module. The specified TC module + * may be started or stopped. + * + * \param[in] module_inst Pointer to the software module instance struct + * + * \return Count value of the specified TC module. + */ +uint32_t tc_get_count_value( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + Tc *const tc_module = module_inst->hw; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Read from based on the TC counter size */ + switch (module_inst->counter_size) { + case TC_COUNTER_SIZE_8BIT: + return (uint32_t)tc_module->COUNT8.COUNT.reg; + + case TC_COUNTER_SIZE_16BIT: + return (uint32_t)tc_module->COUNT16.COUNT.reg; + + case TC_COUNTER_SIZE_32BIT: + return tc_module->COUNT32.COUNT.reg; + } + + Assert(false); + return 0; +} + +/** + * \brief Gets the TC module capture value. + * + * Retrieves the capture value in the indicated TC module capture channel. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] channel_index Index of the Compare Capture channel to read + * + * \return Capture value stored in the specified timer channel. + */ +uint32_t tc_get_capture_value( + const struct tc_module *const module_inst, + const enum tc_compare_capture_channel channel_index) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + Tc *const tc_module = module_inst->hw; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Read out based on the TC counter size */ + switch (module_inst->counter_size) { + case TC_COUNTER_SIZE_8BIT: + if (channel_index < + NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { + return tc_module->COUNT8.CC[channel_index].reg; + } + + case TC_COUNTER_SIZE_16BIT: + if (channel_index < + NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { + return tc_module->COUNT16.CC[channel_index].reg; + } + + case TC_COUNTER_SIZE_32BIT: + if (channel_index < + NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { + return tc_module->COUNT32.CC[channel_index].reg; + } + } + + Assert(false); + return 0; +} + +/** + * \brief Sets a TC module compare value. + * + * Writes a compare value to the given TC module compare/capture channel. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] channel_index Index of the compare channel to write to + * \param[in] compare New compare value to set + * + * \return Status of the compare update procedure. + * + * \retval STATUS_OK The compare value was updated successfully + * \retval STATUS_ERR_INVALID_ARG An invalid channel index was supplied + */ +enum status_code tc_set_compare_value( + const struct tc_module *const module_inst, + const enum tc_compare_capture_channel channel_index, + const uint32_t compare) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + Tc *const tc_module = module_inst->hw; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Read out based on the TC counter size */ + switch (module_inst->counter_size) { + case TC_COUNTER_SIZE_8BIT: + if (channel_index < + NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { + tc_module->COUNT8.CC[channel_index].reg = + (uint8_t)compare; + return STATUS_OK; + } + + case TC_COUNTER_SIZE_16BIT: + if (channel_index < + NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { + tc_module->COUNT16.CC[channel_index].reg = + (uint16_t)compare; + return STATUS_OK; + } + + case TC_COUNTER_SIZE_32BIT: + if (channel_index < + NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { + tc_module->COUNT32.CC[channel_index].reg = + (uint32_t)compare; + return STATUS_OK; + } + } + + return STATUS_ERR_INVALID_ARG; +} + +/** + * \brief Resets the TC module. + * + * Resets the TC module, restoring all hardware module registers to their + * default values and disabling the module. The TC module will not be + * accessible while the reset is being performed. + * + * \note When resetting a 32-bit counter only the master TC module's instance + * structure should be passed to the function. + * + * \param[in] module_inst Pointer to the software module instance struct + * + * \return Status of the procedure. + * \retval STATUS_OK The module was reset successfully + * \retval STATUS_ERR_UNSUPPORTED_DEV A 32-bit slave TC module was passed to + * the function. Only use reset on master + * TC + */ +enum status_code tc_reset( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + if (tc_module->STATUS.reg & TC_STATUS_SLAVE) { + return STATUS_ERR_UNSUPPORTED_DEV; + } + + /* Disable this module if it is running */ + if (tc_module->CTRLA.reg & TC_CTRLA_ENABLE) { + tc_disable(module_inst); + while (tc_is_syncing(module_inst)) { + /* wait while module is disabling */ + } + } + + /* Reset this TC module */ + tc_module->CTRLA.reg |= TC_CTRLA_SWRST; + + return STATUS_OK; +} + +/** + * \brief Set the timer TOP/period value. + * + * For 8-bit counter size this function writes the top value to the period + * register. + * + * For 16- and 32-bit counter size this function writes the top value to + * Capture Compare register 0. The value in this register can not be used for + * any other purpose. + * + * \note This function is designed to be used in PWM or frequency + * match modes only. When the counter is set to 16- or 32-bit counter + * size. In 8-bit counter size it will always be possible to change the + * top value even in normal mode. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] top_value New timer TOP value to set + * + * \return Status of the TOP set procedure. + * + * \retval STATUS_OK The timer TOP value was updated successfully + * \retval STATUS_ERR_INVALID_ARG The configured TC module counter size in the + * module instance is invalid + */ +enum status_code tc_set_top_value ( + const struct tc_module *const module_inst, + const uint32_t top_value) +{ + Assert(module_inst); + Assert(module_inst->hw); + Assert(top_value); + + Tc *const tc_module = module_inst->hw; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + switch (module_inst->counter_size) { + case TC_COUNTER_SIZE_8BIT: + tc_module->COUNT8.PER.reg = (uint8_t)top_value; + return STATUS_OK; + + case TC_COUNTER_SIZE_16BIT: + tc_module->COUNT16.CC[0].reg = (uint16_t)top_value; + return STATUS_OK; + + case TC_COUNTER_SIZE_32BIT: + tc_module->COUNT32.CC[0].reg = (uint32_t)top_value; + return STATUS_OK; + + default: + Assert(false); + return STATUS_ERR_INVALID_ARG; + } +} diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc.h new file mode 100644 index 0000000..0ee7006 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc.h @@ -0,0 +1,1783 @@ +/** + * \file + * + * \brief SAM TC - Timer Counter Driver + * + * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#ifndef TC_H_INCLUDED +#define TC_H_INCLUDED + +/** + * \defgroup asfdoc_sam0_tc_group SAM Timer/Counter Driver (TC) + * + * This driver for Atmel® | SMART ARM®-based microcontrollers provides an interface for the configuration + * and management of the timer modules within the device, for waveform + * generation and timing operations. The following driver API modes are covered + * by this manual: + * + * - Polled APIs + * \if TC_CALLBACK_MODE + * - Callback APIs + * \endif + * + * + * The following peripherals are used by this module: + * - TC (Timer/Counter) + * + * The following devices can use this module: + * - Atmel | SMART SAM D20/D21 + * - Atmel | SMART SAM R21 + * - Atmel | SMART SAM D09/D10/D11 + * - Atmel | SMART SAM L21/L22 + * - Atmel | SMART SAM DA1 + * - Atmel | SMART SAM C20/C21 + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_tc_prerequisites + * - \ref asfdoc_sam0_tc_module_overview + * - \ref asfdoc_sam0_tc_special_considerations + * - \ref asfdoc_sam0_tc_extra_info + * - \ref asfdoc_sam0_tc_examples + * - \ref asfdoc_sam0_tc_api_overview + * + * + * \section asfdoc_sam0_tc_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * + * \section asfdoc_sam0_tc_module_overview Module Overview + * + * The Timer/Counter (TC) module provides a set of timing and counting related + * functionality, such as the generation of periodic waveforms, the capturing + * of a periodic waveform's frequency/duty cycle, and software timekeeping for + * periodic operations. TC modules can be configured to use an 8-, 16-, or + * 32-bit counter size. + * + * This TC module for the SAM is capable of the following functions: + * + * - Generation of PWM signals + * - Generation of timestamps for events + * - General time counting + * - Waveform period capture + * - Waveform frequency capture + * + * \ref asfdoc_sam0_tc_block_diagram "The diagram below" shows the overview + * of the TC module design. + * + * \anchor asfdoc_sam0_tc_block_diagram + * \image html overview.svg "Basic Overview of the TC Module" + * + * + * \subsection asfdoc_sam0_tc_features Driver Feature Macro Definition + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Driver Feature MacroSupported devices
FEATURE_TC_DOUBLE_BUFFEREDSAM L21/L22/C20/C21
FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2SAM L21/L22/C20/C21
FEATURE_TC_STAMP_PW_CAPTURESAM L21/L22/C20/C21
FEATURE_TC_READ_SYNCSAM L21/L22/C20/C21
FEATURE_TC_IO_CAPTURESAM L21/L22/C20/C21
FEATURE_TC_GENERATE_DMA_TRIGGERSAM L21/L22
+ * \note The specific features are only available in the driver when the + * selected device supports those features. + * + * \subsection asfdoc_sam0_tc_module_overview_func_desc Functional Description + * Independent of the configured counter size, each TC module can be set up + * in one of two different modes; capture and compare. + * + * In capture mode, the counter value is stored when a configurable event + * occurs. This mode can be used to generate timestamps used in event capture, + * or it can be used for the measurement of a periodic input signal's + * frequency/duty cycle. + * + * In compare mode, the counter value is compared against one or more of the + * configured channel compare values. When the counter value coincides with a + * compare value an action can be taken automatically by the module, such as + * generating an output event or toggling a pin when used for frequency or PWM + * signal generation. + * + * \note The connection of events between modules requires the use of the + * \ref asfdoc_sam0_events_group "SAM Event System Driver (EVENTS)" + * to route output event of one module to the input event of another. + * For more information on event routing, refer to the event driver + * documentation. + * + * \subsection asfdoc_sam0_tc_module_overview_tc_size Timer/Counter Size + * Each timer module can be configured in one of three different counter + * sizes; 8-, 16-, and 32-bit. The size of the counter determines the maximum + * value it can count to before an overflow occurs and the count is reset back + * to zero. \ref asfdoc_sam0_tc_count_size_vs_top "The table below" shows the + * maximum values for each of the possible counter sizes. + * + * \anchor asfdoc_sam0_tc_count_size_vs_top + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Timer Counter Sizes and Their Maximum Count Values
Counter sizeMax. (hexadecimal)Max. (decimal)
8-bit0xFF255
16-bit0xFFFF65,535
32-bit0xFFFFFFFF4,294,967,295
+ * + * When using the counter in 16- or 32-bit count mode, Compare Capture + * register 0 (CC0) is used to store the period value when running in PWM + * generation match mode. + * + * When using 32-bit counter size, two 16-bit counters are chained together + * in a cascade formation. Except in SAM D09/D10/D11, Even numbered TC modules + * (e.g. TC0, TC2) can be configured as 32-bit counters. The odd numbered + * counters will act as slaves to the even numbered masters, and will not + * be reconfigurable until the master timer is disabled. The pairing of timer + * modules for 32-bit mode is shown in \ref asfdoc_sam0_tc_module_ms_pairs + * "the table below". + * + * \anchor asfdoc_sam0_tc_module_ms_pairs + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
TC Master and Slave Module Pairings
Master TC ModuleSlave TC Module
TC0TC1
TC2TC3
......
TCn-1TCn
+ * + * In SAM D09/D10/D11, odd numbered TC modules (e.g. TC1) can be configured as 32-bit + * counters. The even numbered(e.g. TC2) counters will act as slaves to the odd + * numbered masters. + * + * \subsection asfdoc_sam0_tc_module_overview_clock Clock Settings + * + * \subsubsection asfdoc_sam0_tc_module_overview_clock_selection Clock Selection + * Each TC peripheral is clocked asynchronously to the system clock by a GCLK + * (Generic Clock) channel. The GCLK channel connects to any of the GCLK + * generators. The GCLK generators are configured to use one of the available + * clock sources on the system such as internal oscillator, external crystals, + * etc. see the \ref asfdoc_sam0_system_clock_group "Generic Clock driver" + *for + * more information. + * + * \subsubsection asfdoc_sam0_tc_module_overview_clock_prescaler Prescaler + * Each TC module in the SAM has its own individual clock prescaler, which + * can be used to divide the input clock frequency used in the counter. This + * prescaler only scales the clock used to provide clock pulses for the counter + * to count, and does not affect the digital register interface portion of + * the module, thus the timer registers will synchronize to the raw GCLK + * frequency input to the module. + * + * As a result of this, when selecting a GCLK frequency and timer prescaler + * value the user application should consider both the timer resolution + * required and the synchronization frequency, to avoid lengthy + * synchronization times of the module if a very slow GCLK frequency is fed + * into the TC module. It is preferable to use a higher module GCLK frequency + * as the input to the timer, and prescale this down as much as possible to + * obtain a suitable counter frequency in latency-sensitive applications. + * + * \subsubsection asfdoc_sam0_tc_module_overview_clock_reloading Reloading + * Timer modules also contain a configurable reload action, used when a + * re-trigger event occurs. Examples of a re-trigger event are the counter + * reaching the maximum value when counting up, or when an event from the event + * system tells the counter to re-trigger. The reload action determines if the + * prescaler should be reset, and when this should happen. The counter will + * always be reloaded with the value it is set to start counting from. The user + * can choose between three different reload actions, described in + * \ref asfdoc_sam0_tc_module_reload_act "the table below". + * + * \anchor asfdoc_sam0_tc_module_reload_act + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
TC Module Reload Actions
Reload actionDescription
\ref TC_RELOAD_ACTION_GCLK Reload TC counter value on next GCLK cycle. Leave prescaler + * as-is.
\ref TC_RELOAD_ACTION_PRESC Reloads TC counter value on next prescaler clock. Leave prescaler + * as-is.
\ref TC_RELOAD_ACTION_RESYNC Reload TC counter value on next GCLK cycle. Clear prescaler to + * zero.
+ * + * The reload action to use will depend on the specific application being + * implemented. One example is when an external trigger for a reload occurs; if + * the TC uses the prescaler, the counter in the prescaler should not have a + * value between zero and the division factor. The TC counter and the counter + * in the prescaler should both start at zero. When the counter is set to + * re-trigger when it reaches the maximum value on the other hand, this is not the + * right option to use. In such a case it would be better if the prescaler is + * left unaltered when the re-trigger happens, letting the counter reset on the + * next GCLK cycle. + * + * \subsection asfdoc_sam0_tc_module_overview_compare_match Compare Match Operations + * In compare match operation, Compare/Capture registers are used in comparison + * with the counter value. When the timer's count value matches the value of a + * compare channel, a user defined action can be taken. + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_timer Basic Timer + * + * A Basic Timer is a simple application where compare match operations is used + * to determine when a specific period has elapsed. In Basic Timer operations, + * one or more values in the module's Compare/Capture registers are used to + * specify the time (as a number of prescaled GCLK cycles) when an action should + * be taken by the microcontroller. This can be an Interrupt Service Routine + * (ISR), event generator via the event system, or a software flag that is + * polled via the user application. + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_wg Waveform Generation + * + * Waveform generation enables the TC module to generate square waves, or if + * combined with an external passive low-pass filter; analog waveforms. + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_wg_pwm Waveform Generation - PWM + * + * Pulse width modulation is a form of waveform generation and a signalling + * technique that can be useful in many situations. When PWM mode is used, + * a digital pulse train with a configurable frequency and duty cycle can be + * generated by the TC module and output to a GPIO pin of the device. + * + * Often PWM is used to communicate a control or information parameter to an + * external circuit or component. Differing impedances of the source generator + * and sink receiver circuits is less of an issue when using PWM compared to + * using an analog voltage value, as noise will not generally affect the + * signal's integrity to a meaningful extent. + * + * \ref asfdoc_sam0_tc_module_pwm_normal_diag "The figure below" illustrates + * operations and different states of the counter and its output when running + * the counter in PWM normal mode. As can be seen, the TOP value is unchanged + * and is set to MAX. The compare match value is changed at several points to + * illustrate the resulting waveform output changes. The PWM output is set to + * normal (i.e. non-inverted) output mode. + * + * \anchor asfdoc_sam0_tc_module_pwm_normal_diag + * \image html pwm_normal_ex.svg "Example of PWM in Normal Mode, and Different Counter Operations" + * + * + * In \ref asfdoc_sam0_tc_module_pwm_match_diag "the figure below", the + * counter is set to generate PWM in Match mode. The PWM output is inverted via + * the appropriate configuration option in the TC driver configuration + * structure. In this example, the counter value is changed once, but the + * compare match value is kept unchanged. As can be seen, it is possible to + * change the TOP value when running in PWM match mode. + * + * \anchor asfdoc_sam0_tc_module_pwm_match_diag + * \image html pwm_match_ex.svg "Example of PWM in Match Mode, and Different Counter Operations" + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_wg_freq Waveform Generation - Frequency + * + * Frequency Generation mode is in many ways identical to PWM + * generation. However, in Frequency Generation a toggle only occurs + * on the output when a match on a capture channels occurs. When the + * match is made, the timer value is reset, resulting in a variable + * frequency square wave with a fixed 50% duty cycle. + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_capt Capture Operations + * + * In capture operations, any event from the event system or a pin change can + * trigger a capture of the counter value. This captured counter value can be + * used as a timestamp for the event, or it can be used in frequency and pulse + * width capture. + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_capt_event_capture Capture Operations - Event + * + * Event capture is a simple use of the capture functionality, + * designed to create timestamps for specific events. When the TC + * module's input capture pin is externally toggled, the current timer + * count value is copied into a buffered register which can then be + * read out by the user application. + * + * Note that when performing any capture operation, there is a risk that the + * counter reaches its top value (MAX) when counting up, or the bottom value + * (zero) when counting down, before the capture event occurs. This can distort + * the result, making event timestamps to appear shorter than reality; the + * user application should check for timer overflow when reading a capture + * result in order to detect this situation and perform an appropriate + * adjustment. + * + * Before checking for a new capture, \ref TC_STATUS_COUNT_OVERFLOW + * should be checked. The response to an overflow error is left to the user + * application, however it may be necessary to clear both the capture overflow + * flag and the capture flag upon each capture reading. + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_capt_pwc Capture Operations - Pulse Width + * + * Pulse Width Capture mode makes it possible to measure the pulse width and + * period of PWM signals. This mode uses two capture channels of the counter. + * This means that the counter module used for Pulse Width Capture can not be + * used for any other purpose. There are two modes for pulse width capture; + * Pulse Width Period (PWP) and Period Pulse Width (PPW). In PWP mode, capture + * channel 0 is used for storing the pulse width and capture channel 1 stores + * the observed period. While in PPW mode, the roles of the two capture channels + * is reversed. + * + * As in the above example it is necessary to poll on interrupt flags to see + * if a new capture has happened and check that a capture overflow error has + * not occurred. + * + * \subsection asfdoc_sam0_tc_module_overview_oneshot One-shot Mode + * + * TC modules can be configured into a one-shot mode. When configured in this + * manner, starting the timer will cause it to count until the next overflow + * or underflow condition before automatically halting, waiting to be manually + * triggered by the user application software or an event signal from the event + * system. + * + * \subsubsection asfdoc_sam0_tc_module_overview_inversion Wave Generation Output Inversion + * + * The output of the wave generation can be inverted by hardware if desired, + * resulting in the logically inverted value being output to the configured + * device GPIO pin. + * + * + * \section asfdoc_sam0_tc_special_considerations Special Considerations + * + * The number of capture compare registers in each TC module is dependent on + * the specific SAM device being used, and in some cases the counter size. + * + * The maximum amount of capture compare registers available in any SAM + * device is two when running in 32-bit mode and four in 8- and 16-bit modes. + * + * + * \section asfdoc_sam0_tc_extra_info Extra Information + * + * For extra information, see \ref asfdoc_sam0_tc_extra. This includes: + * - \ref asfdoc_sam0_tc_extra_acronyms + * - \ref asfdoc_sam0_tc_extra_dependencies + * - \ref asfdoc_sam0_tc_extra_errata + * - \ref asfdoc_sam0_tc_extra_history + * + * + * \section asfdoc_sam0_tc_examples Examples + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_tc_exqsg. + * + * \section asfdoc_sam0_tc_api_overview API Overview + * @{ + */ + +#include "compiler.h" +#include "clock.h" +#include "gclk.h" +#include "pinmux.h" + +// fix for Arduino zero +#if defined(__SAMD21G18A__) + #define SAMD21 1 + #define SAMD21G 1 + #define TC_ASYNC 1 +#endif + +// fix for Trinket/Gemma M0 +#if defined(__SAMD21E18A__) + #define SAMD21 1 + #define SAMD21E 1 + #define TC_ASYNC 1 +#endif + +/** + * Define port features set according to different device family + * @{ +*/ +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) || defined(__DOXYGEN__) +/** TC double buffered. */ +# define FEATURE_TC_DOUBLE_BUFFERED +/** SYNCBUSY scheme version 2. */ +# define FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2 +/** TC time stamp capture and pulse width capture. */ +# define FEATURE_TC_STAMP_PW_CAPTURE +/** Read synchronization of COUNT. */ +# define FEATURE_TC_READ_SYNC +/** IO pin edge capture. */ +# define FEATURE_TC_IO_CAPTURE +#endif + +#if (SAML21XXXB) || defined(__DOXYGEN__) +/** Generate DMA triggers*/ +# define FEATURE_TC_GENERATE_DMA_TRIGGER +#endif +/*@}*/ + +#if !defined(__DOXYGEN__) +#if SAMD20 || SAML21 || SAML22 || SAMC20 || SAMC21 +# define TC_INSTANCE_OFFSET 0 +#endif +#if SAMD21 || SAMR21 || SAMDA1 +# define TC_INSTANCE_OFFSET 3 +#endif +#if SAMD09 || SAMD10 || SAMD11 +# define TC_INSTANCE_OFFSET 1 +#endif + +#if SAMD20 +# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC0_CC8_NUM +#elif SAML21 || SAML22 || SAMC20 || SAMC21 +# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC0_CC_NUM +#elif SAMD09 || SAMD10 || SAMD11 +# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC1_CC8_NUM +#else +# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC3_CC8_NUM + /* Same number for 8-, 16- and 32-bit TC and all TC instances */ +#endif + +/** TC Instance MAX ID Number. */ +#if SAMD20E || SAMD21G || SAMD21E || SAMR21 +# if SAMD21GXXL +# define TC_INST_MAX_ID 7 +# else +# define TC_INST_MAX_ID 5 +# endif +#elif SAML21 || SAMC20 || SAMC21 +# define TC_INST_MAX_ID 4 +#elif SAML22 +# define TC_INST_MAX_ID 3 +#elif SAMD09 || SAMD10 || SAMD11 +# define TC_INST_MAX_ID 2 +#else +# define TC_INST_MAX_ID 7 +#endif + +#endif + +#if TC_ASYNC == true +# include "system_interrupt.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#if TC_ASYNC == true +/** Enum for the possible callback types for the TC module. */ +enum tc_callback { + /** Callback for TC overflow. */ + TC_CALLBACK_OVERFLOW, + /** Callback for capture overflow error. */ + TC_CALLBACK_ERROR, + /** Callback for capture compare channel 0. */ + TC_CALLBACK_CC_CHANNEL0, + /** Callback for capture compare channel 1. */ + TC_CALLBACK_CC_CHANNEL1, +# if !defined(__DOXYGEN__) + /** Number of available callbacks. */ + TC_CALLBACK_N, +# endif +}; +#endif + +/** + * \name Module Status Flags + * + * TC status flags, returned by \ref tc_get_status() and cleared by + * \ref tc_clear_status(). + * + * @{ + */ + +/** Timer channel 0 has matched against its compare value, or has captured a + * new value. + */ +#define TC_STATUS_CHANNEL_0_MATCH (1UL << 0) + +/** Timer channel 1 has matched against its compare value, or has captured a + * new value. + */ +#define TC_STATUS_CHANNEL_1_MATCH (1UL << 1) + +/** Timer register synchronization has completed, and the synchronized count + * value may be read. + */ +#define TC_STATUS_SYNC_READY (1UL << 2) + +/** A new value was captured before the previous value was read, resulting in + * lost data. + */ +#define TC_STATUS_CAPTURE_OVERFLOW (1UL << 3) + +/** The timer count value has overflowed from its maximum value to its minimum + * when counting upward, or from its minimum value to its maximum when + * counting downward. + */ +#define TC_STATUS_COUNT_OVERFLOW (1UL << 4) + +#ifdef FEATURE_TC_DOUBLE_BUFFERED +/** Channel 0 compare or capture buffer valid. */ +#define TC_STATUS_CHN0_BUFFER_VALID (1UL << 5) +/** Channel 1 compare or capture buffer valid. */ +#define TC_STATUS_CHN1_BUFFER_VALID (1UL << 6) +/** Period buffer valid. */ +#define TC_STATUS_PERIOD_BUFFER_VALID (1UL << 7) +#endif +/** @} */ + +/** + * \brief Index of the compare capture channels. + * + * This enum is used to specify which capture/compare channel to do + * operations on. + */ +enum tc_compare_capture_channel { + /** Index of compare capture channel 0. */ + TC_COMPARE_CAPTURE_CHANNEL_0, + /** Index of compare capture channel 1. */ + TC_COMPARE_CAPTURE_CHANNEL_1, +}; + +/** TC wave generation mode. */ +#if SAML21 || SAML22 || SAMC20 || SAMC21 +#define TC_WAVE_GENERATION_NORMAL_FREQ_MODE TC_WAVE_WAVEGEN_NFRQ +#define TC_WAVE_GENERATION_MATCH_FREQ_MODE TC_WAVE_WAVEGEN_MFRQ +#define TC_WAVE_GENERATION_NORMAL_PWM_MODE TC_WAVE_WAVEGEN_NPWM +#define TC_WAVE_GENERATION_MATCH_PWM_MODE TC_WAVE_WAVEGEN_MPWM +#else +#define TC_WAVE_GENERATION_NORMAL_FREQ_MODE TC_CTRLA_WAVEGEN_NFRQ +#define TC_WAVE_GENERATION_MATCH_FREQ_MODE TC_CTRLA_WAVEGEN_MFRQ +#define TC_WAVE_GENERATION_NORMAL_PWM_MODE TC_CTRLA_WAVEGEN_NPWM +#define TC_WAVE_GENERATION_MATCH_PWM_MODE TC_CTRLA_WAVEGEN_MPWM +#endif + +/** + * \brief TC wave generation mode enum. + * + * This enum is used to select which mode to run the wave + * generation in. + * + */ +enum tc_wave_generation { + /** Top is maximum, except in 8-bit counter size where it is the PER + * register. + */ + TC_WAVE_GENERATION_NORMAL_FREQ = TC_WAVE_GENERATION_NORMAL_FREQ_MODE, + + /** Top is CC0, except in 8-bit counter size where it is the PER + * register. + */ + TC_WAVE_GENERATION_MATCH_FREQ = TC_WAVE_GENERATION_MATCH_FREQ_MODE, + + /** Top is maximum, except in 8-bit counter size where it is the PER + * register. + */ + TC_WAVE_GENERATION_NORMAL_PWM = TC_WAVE_GENERATION_NORMAL_PWM_MODE, + + /** Top is CC0, except in 8-bit counter size where it is the PER + * register. + */ + TC_WAVE_GENERATION_MATCH_PWM = TC_WAVE_GENERATION_MATCH_PWM_MODE, +}; + +/** + * \brief Specifies if the counter is 8-, 16-, or 32-bit. + * + * This enum specifies the maximum value it is possible to count to. + */ +enum tc_counter_size { + /** The counter's maximum value is 0xFF, the period register is + * available to be used as top value. + */ + TC_COUNTER_SIZE_8BIT = TC_CTRLA_MODE_COUNT8, + + /** The counter's maximum value is 0xFFFF. There is no separate + * period register, to modify top one of the capture compare + * registers has to be used. This limits the amount of + * available channels. + */ + TC_COUNTER_SIZE_16BIT = TC_CTRLA_MODE_COUNT16, + + /** The counter's maximum value is 0xFFFFFFFF. There is no separate + * period register, to modify top one of the capture compare + * registers has to be used. This limits the amount of + * available channels. + */ + TC_COUNTER_SIZE_32BIT = TC_CTRLA_MODE_COUNT32, +}; + +/** + * \brief TC Counter reload action enum. + * + * This enum specify how the counter and prescaler should reload. + */ +enum tc_reload_action { + /** The counter is reloaded/reset on the next GCLK and starts + * counting on the prescaler clock. + */ + TC_RELOAD_ACTION_GCLK = TC_CTRLA_PRESCSYNC_GCLK, + + /** The counter is reloaded/reset on the next prescaler clock. + */ + TC_RELOAD_ACTION_PRESC = TC_CTRLA_PRESCSYNC_PRESC, + + /** The counter is reloaded/reset on the next GCLK, and the + * prescaler is restarted as well. + */ + TC_RELOAD_ACTION_RESYNC = TC_CTRLA_PRESCSYNC_RESYNC, +}; + +/** + * \brief TC clock prescaler values. + * + * This enum is used to choose the clock prescaler + * configuration. The prescaler divides the clock frequency of the TC + * module to make the counter count slower. + */ +enum tc_clock_prescaler { + /** Divide clock by 1. */ + TC_CLOCK_PRESCALER_DIV1 = TC_CTRLA_PRESCALER(0), + /** Divide clock by 2. */ + TC_CLOCK_PRESCALER_DIV2 = TC_CTRLA_PRESCALER(1), + /** Divide clock by 4. */ + TC_CLOCK_PRESCALER_DIV4 = TC_CTRLA_PRESCALER(2), + /** Divide clock by 8. */ + TC_CLOCK_PRESCALER_DIV8 = TC_CTRLA_PRESCALER(3), + /** Divide clock by 16. */ + TC_CLOCK_PRESCALER_DIV16 = TC_CTRLA_PRESCALER(4), + /** Divide clock by 64. */ + TC_CLOCK_PRESCALER_DIV64 = TC_CTRLA_PRESCALER(5), + /** Divide clock by 256. */ + TC_CLOCK_PRESCALER_DIV256 = TC_CTRLA_PRESCALER(6), + /** Divide clock by 1024. */ + TC_CLOCK_PRESCALER_DIV1024 = TC_CTRLA_PRESCALER(7), +}; + +/** + * \brief TC module count direction. + * + * Timer/Counter count direction. + */ +enum tc_count_direction { + /** Timer should count upward from zero to MAX. */ + TC_COUNT_DIRECTION_UP, + + /** Timer should count downward to zero from MAX. */ + TC_COUNT_DIRECTION_DOWN, +}; + +/** Waveform inversion mode. */ +#if SAML21 || SAML22 || SAMC20 || SAMC21 +#define TC_WAVEFORM_INVERT_CC0_MODE TC_DRVCTRL_INVEN(1) +#define TC_WAVEFORM_INVERT_CC1_MODE TC_DRVCTRL_INVEN(2) +#else +#define TC_WAVEFORM_INVERT_CC0_MODE TC_CTRLC_INVEN(1) +#define TC_WAVEFORM_INVERT_CC1_MODE TC_CTRLC_INVEN(2) +#endif + +/** + * \brief Waveform inversion mode. + * + * Output waveform inversion mode. + */ +enum tc_waveform_invert_output { + /** No inversion of the waveform output. */ + TC_WAVEFORM_INVERT_OUTPUT_NONE = 0, + /** Invert output from compare channel 0. */ + TC_WAVEFORM_INVERT_OUTPUT_CHANNEL_0 = TC_WAVEFORM_INVERT_CC0_MODE, + /** Invert output from compare channel 1. */ + TC_WAVEFORM_INVERT_OUTPUT_CHANNEL_1 = TC_WAVEFORM_INVERT_CC1_MODE, +}; + +/** + * \brief Action to perform when the TC module is triggered by an event. + * + * Event action to perform when the module is triggered by an event. + */ +enum tc_event_action { + /** No event action. */ + TC_EVENT_ACTION_OFF = TC_EVCTRL_EVACT_OFF, + /** Re-trigger on event. */ + TC_EVENT_ACTION_RETRIGGER = TC_EVCTRL_EVACT_RETRIGGER, + /** Increment counter on event. */ + TC_EVENT_ACTION_INCREMENT_COUNTER = TC_EVCTRL_EVACT_COUNT, + /** Start counter on event. */ + TC_EVENT_ACTION_START = TC_EVCTRL_EVACT_START, + + /** Store period in capture register 0, pulse width in capture + * register 1. + */ + TC_EVENT_ACTION_PPW = TC_EVCTRL_EVACT_PPW, + + /** Store pulse width in capture register 0, period in capture + * register 1. + */ + TC_EVENT_ACTION_PWP = TC_EVCTRL_EVACT_PWP, +#ifdef FEATURE_TC_STAMP_PW_CAPTURE + /** Time stamp capture. */ + TC_EVENT_ACTION_STAMP = TC_EVCTRL_EVACT_STAMP, + /** Pulse width capture. */ + TC_EVENT_ACTION_PW = TC_EVCTRL_EVACT_PW, +#endif +}; + +/** + * \brief TC event enable/disable structure. + * + * Event flags for the \ref tc_enable_events() and \ref tc_disable_events(). + */ +struct tc_events { + /** Generate an output event on a compare channel match. */ + bool generate_event_on_compare_channel + [NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; + /** Generate an output event on counter overflow. */ + bool generate_event_on_overflow; + /** Perform the configured event action when an incoming event is signalled. */ + bool on_event_perform_action; + /** Specifies if the input event source is inverted, when used in PWP or + * PPW event action modes. + */ + bool invert_event_input; + /** Specifies which event to trigger if an event is triggered. */ + enum tc_event_action event_action; +}; + +/** + * \brief Configuration struct for TC module in 8-bit size counter mode. + */ +struct tc_8bit_config { + /** Initial timer count value. */ + uint8_t value; + /** Where to count to or from depending on the direction on the counter. */ + uint8_t period; + /** Value to be used for compare match on each channel. */ + uint8_t compare_capture_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; +}; + +/** + * \brief Configuration struct for TC module in 16-bit size counter mode. + */ +struct tc_16bit_config { + /** Initial timer count value. */ + uint16_t value; + /** Value to be used for compare match on each channel. */ + uint16_t compare_capture_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; +}; + +/** + * \brief Configuration struct for TC module in 32-bit size counter mode. + */ +struct tc_32bit_config { + /** Initial timer count value. */ + uint32_t value; + /** Value to be used for compare match on each channel. */ + uint32_t compare_capture_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; +}; + +/** + * \brief Configuration struct for TC module in 32-bit size counter mode. + */ +struct tc_pwm_channel { + /** When \c true, PWM output for the given channel is enabled. */ + bool enabled; + /** Specifies pin output for each channel. */ + uint32_t pin_out; + /** Specifies MUX setting for each output channel pin. */ + uint32_t pin_mux; +}; + +/** + * \brief TC configuration structure. + * + * Configuration struct for a TC instance. This structure should be + * initialized by the \ref tc_get_config_defaults function before being + * modified by the user application. + */ +struct tc_config { + /** GCLK generator used to clock the peripheral. */ + enum gclk_generator clock_source; + + /** When \c true the module is enabled during standby. */ + bool run_in_standby; +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) + /** Run on demand. */ + bool on_demand; +#endif + /** Specifies either 8-, 16-, or 32-bit counter size. */ + enum tc_counter_size counter_size; + /** Specifies the prescaler value for GCLK_TC. */ + enum tc_clock_prescaler clock_prescaler; + /** Specifies which waveform generation mode to use. */ + enum tc_wave_generation wave_generation; + + /** Specifies the reload or reset time of the counter and prescaler + * resynchronization on a re-trigger event for the TC. + */ + enum tc_reload_action reload_action; + + /** Specifies which channel(s) to invert the waveform on. + For SAM L21/L22/C20/C21, it's also used to invert IO input pin. */ + uint8_t waveform_invert_output; + + /** Specifies which channel(s) to enable channel capture + * operation on. + */ + bool enable_capture_on_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; +#ifdef FEATURE_TC_IO_CAPTURE + /** Specifies which channel(s) to enable I/O capture + * operation on. + */ + bool enable_capture_on_IO[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; +#endif + + /** When \c true, one-shot will stop the TC on next hardware or software + * re-trigger event or overflow/underflow. + */ + bool oneshot; + + /** Specifies the direction for the TC to count. */ + enum tc_count_direction count_direction; + + /** Specifies the PWM channel for TC. */ + struct tc_pwm_channel pwm_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; + + /** Access the different counter size settings though this configuration member. */ + union { + /** Struct for 8-bit specific timer configuration. */ + struct tc_8bit_config counter_8_bit; + /** Struct for 16-bit specific timer configuration. */ + struct tc_16bit_config counter_16_bit; + /** Struct for 32-bit specific timer configuration. */ + struct tc_32bit_config counter_32_bit; + }; + +#ifdef FEATURE_TC_DOUBLE_BUFFERED + /** Set to \c true to enable double buffering write. When enabled any write + * through \ref tc_set_top_value(), \ref tc_set_compare_value() and + * will direct to the buffer register as buffered + * value, and the buffered value will be committed to effective register + * on UPDATE condition, if update is not locked. + */ + bool double_buffering_enabled; +#endif +}; + +#if TC_ASYNC == true +/* Forward Declaration for the device instance. */ +struct tc_module; + +/* Type of the callback functions. */ +typedef void (*tc_callback_t)(struct tc_module *const module); +#endif + +/** + * \brief TC software device instance structure. + * + * TC software instance structure, used to retain software state information + * of an associated hardware module instance. + * + * \note The fields of this structure should not be altered by the user + * application; they are reserved for module-internal use only. + */ +struct tc_module { +#if !defined(__DOXYGEN__) + /** Hardware module pointer of the associated Timer/Counter peripheral. */ + Tc *hw; + + /** Size of the initialized Timer/Counter module configuration. */ + enum tc_counter_size counter_size; +# if TC_ASYNC == true + /** Array of callbacks. */ + tc_callback_t callback[TC_CALLBACK_N]; + /** Bit mask for callbacks registered. */ + uint8_t register_callback_mask; + /** Bit mask for callbacks enabled. */ + uint8_t enable_callback_mask; +# endif +#ifdef FEATURE_TC_DOUBLE_BUFFERED + /** Set to \c true to enable double buffering write. */ + bool double_buffering_enabled; +#endif +#endif +}; + +#if !defined(__DOXYGEN__) +uint8_t _tc_get_inst_index( + Tc *const hw); +#endif + +/** + * \name Driver Initialization and Configuration + * @{ + */ + +/** + * \brief Determines if the hardware module(s) are currently synchronizing to + *the bus. + * + * Checks to see if the underlying hardware peripheral module(s) are currently + * synchronizing across multiple clock domains to the hardware bus. This + * function can be used to delay further operations on a module until such time + * that it is ready, to prevent blocking delays for synchronization in the + * user application. + * + * \param[in] module_inst Pointer to the software module instance struct + * + * \return Synchronization status of the underlying hardware module(s). + * + * \retval false If the module has completed synchronization + * \retval true If the module synchronization is ongoing + */ +static inline bool tc_is_syncing( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) + return (tc_module->SYNCBUSY.reg); +#else + return (tc_module->STATUS.reg & TC_STATUS_SYNCBUSY); +#endif +} + +/** + * \brief Initializes config with predefined default values. + * + * This function will initialize a given TC configuration structure to + * a set of known default values. This function should be called on + * any new instance of the configuration structures before being + * modified by the user application. + * + * The default configuration is as follows: + * \li GCLK generator 0 (GCLK main) clock source + * \li 16-bit counter size on the counter + * \li No prescaler + * \li Normal frequency wave generation + * \li GCLK reload action + * \li Don't run in standby + * \li Don't run on demand for SAM L21/L22/C20/C21 + * \li No inversion of waveform output + * \li No capture enabled + * \li No I/O capture enabled for SAM L21/L22/C20/C21 + * \li No event input enabled + * \li Count upward + * \li Don't perform one-shot operations + * \li No event action + * \li No channel 0 PWM output + * \li No channel 1 PWM output + * \li Counter starts on 0 + * \li Capture compare channel 0 set to 0 + * \li Capture compare channel 1 set to 0 + * \li No PWM pin output enabled + * \li Pin and MUX configuration not set + * \li Double buffer disabled (if have this feature) + * + * \param[out] config Pointer to a TC module configuration structure to set + */ +static inline void tc_get_config_defaults( + struct tc_config *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Write default config to config struct */ + config->clock_source = GCLK_GENERATOR_0; + config->counter_size = TC_COUNTER_SIZE_16BIT; + config->clock_prescaler = TC_CLOCK_PRESCALER_DIV1; + config->wave_generation = TC_WAVE_GENERATION_NORMAL_FREQ; + config->reload_action = TC_RELOAD_ACTION_GCLK; + config->run_in_standby = false; +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) + config->on_demand = false; +#endif + config->waveform_invert_output = TC_WAVEFORM_INVERT_OUTPUT_NONE; + config->enable_capture_on_channel[TC_COMPARE_CAPTURE_CHANNEL_0] = false; + config->enable_capture_on_channel[TC_COMPARE_CAPTURE_CHANNEL_1] = false; +#ifdef FEATURE_TC_IO_CAPTURE + config->enable_capture_on_IO[TC_COMPARE_CAPTURE_CHANNEL_0] = false; + config->enable_capture_on_IO[TC_COMPARE_CAPTURE_CHANNEL_1] = false; +#endif + + config->count_direction = TC_COUNT_DIRECTION_UP; + config->oneshot = false; + + config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_0].enabled = false; + config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_0].pin_out = 0; + config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_0].pin_mux = 0; + + config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_1].enabled = false; + config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_1].pin_out = 0; + config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_1].pin_mux = 0; + + config->counter_16_bit.value = 0x0000; + config->counter_16_bit.compare_capture_channel\ + [TC_COMPARE_CAPTURE_CHANNEL_0] = 0x0000; + config->counter_16_bit.compare_capture_channel\ + [TC_COMPARE_CAPTURE_CHANNEL_1] = 0x0000; +#ifdef FEATURE_TC_DOUBLE_BUFFERED + config->double_buffering_enabled = false; +#endif + +} + +enum status_code tc_init( + struct tc_module *const module_inst, + Tc *const hw, + const struct tc_config *const config); + +/** @} */ + +/** + * \name Event Management + * @{ + */ + +/** + * \brief Enables a TC module event input or output. + * + * Enables one or more input or output events to or from the TC module. + * See \ref tc_events for a list of events this module supports. + * + * \note Events cannot be altered while the module is enabled. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] events Struct containing flags of events to enable + */ +static inline void tc_enable_events( + struct tc_module *const module_inst, + struct tc_events *const events) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + Assert(events); + + Tc *const tc_module = module_inst->hw; + + uint32_t event_mask = 0; + + if (events->invert_event_input == true) { + event_mask |= TC_EVCTRL_TCINV; + } + + if (events->on_event_perform_action == true) { + event_mask |= TC_EVCTRL_TCEI; + } + + if (events->generate_event_on_overflow == true) { + event_mask |= TC_EVCTRL_OVFEO; + } + + for (uint8_t i = 0; i < NUMBER_OF_COMPARE_CAPTURE_CHANNELS; i++) { + if (events->generate_event_on_compare_channel[i] == true) { + event_mask |= (TC_EVCTRL_MCEO(1) << i); + } + } + + tc_module->COUNT8.EVCTRL.reg |= event_mask | events->event_action; +} + +/** + * \brief Disables a TC module event input or output. + * + * Disables one or more input or output events to or from the TC module. + * See \ref tc_events for a list of events this module supports. + * + * \note Events cannot be altered while the module is enabled. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] events Struct containing flags of events to disable + */ +static inline void tc_disable_events( + struct tc_module *const module_inst, + struct tc_events *const events) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + Assert(events); + + Tc *const tc_module = module_inst->hw; + + uint32_t event_mask = 0; + + if (events->invert_event_input == true) { + event_mask |= TC_EVCTRL_TCINV; + } + + if (events->on_event_perform_action == true) { + event_mask |= TC_EVCTRL_TCEI; + } + + if (events->generate_event_on_overflow == true) { + event_mask |= TC_EVCTRL_OVFEO; + } + + for (uint8_t i = 0; i < NUMBER_OF_COMPARE_CAPTURE_CHANNELS; i++) { + if (events->generate_event_on_compare_channel[i] == true) { + event_mask |= (TC_EVCTRL_MCEO(1) << i); + } + } + + tc_module->COUNT8.EVCTRL.reg &= ~event_mask; +} + +/** @} */ + +/** + * \name Enable/Disable/Reset + * @{ + */ + +enum status_code tc_reset( + const struct tc_module *const module_inst); + +/** + * \brief Enable the TC module. + * + * Enables a TC module that has been previously initialized. The counter will + * start when the counter is enabled. + * + * \note When the counter is configured to re-trigger on an event, the counter + * will not start until the start function is used. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_enable( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Enable TC module */ + tc_module->CTRLA.reg |= TC_CTRLA_ENABLE; +} + +/** + * \brief Disables the TC module. + * + * Disables a TC module and stops the counter. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_disable( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Disable TC module */ + tc_module->CTRLA.reg &= ~TC_CTRLA_ENABLE; +} + +/** @} */ + +/** + * \name Get/Set Count Value + * @{ + */ + +uint32_t tc_get_count_value( + const struct tc_module *const module_inst); + +enum status_code tc_set_count_value( + const struct tc_module *const module_inst, + const uint32_t count); + +/** @} */ + +/** + * \name Start/Stop Counter + * @{ + */ + +/** + * \brief Stops the counter. + * + * This function will stop the counter. When the counter is stopped + * the value in the count value is set to 0 if the counter was + * counting up, or maximum if the counter was counting + * down when stopped. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_stop_counter( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Write command to execute */ + tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_STOP_Val); +} + +/** + * \brief Starts the counter. + * + * Starts or restarts an initialized TC module's counter. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_start_counter( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Make certain that there are no conflicting commands in the register */ + tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Write command to execute */ + tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_RETRIGGER_Val); +} + +/** @} */ + +#ifdef FEATURE_TC_DOUBLE_BUFFERED +/** + * \name Double Buffering + * @{ + */ + +/** + * \brief Update double buffer. + * + * Update double buffer. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_update_double_buffer( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Make certain that there are no conflicting commands in the register */ + tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Write command to execute */ + tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_UPDATE_Val); +} +/** @} */ +#endif + +#ifdef FEATURE_TC_READ_SYNC +/** + * \name Count Read Synchronization + * @{ + */ + +/** + * \brief Read synchronization of COUNT. + * + * Read synchronization of COUNT. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_sync_read_count( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Make certain that there are no conflicting commands in the register */ + tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Write command to execute */ + tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_READSYNC_Val); +} +/** @} */ +#endif + +#ifdef FEATURE_TC_GENERATE_DMA_TRIGGER +/** + * \name Generate TC DMA Triggers command + * @{ + */ + +/** + * \brief TC DMA Trigger. + * + * TC DMA trigger command. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_dma_trigger_command( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Make certain that there are no conflicting commands in the register */ + tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + +#if (SAMC20) || (SAMC21) || (SAML22) || (SAML21XXXB) + /* Write command to execute */ + tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_DMAOS_Val); +#endif +} +/** @} */ +#endif + +/** + * \name Get Capture Set Compare + * @{ + */ + +uint32_t tc_get_capture_value( + const struct tc_module *const module_inst, + const enum tc_compare_capture_channel channel_index); + +enum status_code tc_set_compare_value( + const struct tc_module *const module_inst, + const enum tc_compare_capture_channel channel_index, + const uint32_t compare_value); + +/** @} */ + +/** + * \name Set Top Value + * @{ + */ + +enum status_code tc_set_top_value( + const struct tc_module *const module_inst, + const uint32_t top_value); + +/** @} */ + +/** + * \name Status Management + * @{ + */ + +/** + * \brief Retrieves the current module status. + * + * Retrieves the status of the module, giving overall state information. + * + * \param[in] module_inst Pointer to the TC software instance struct + * + * \return Bitmask of \c TC_STATUS_* flags. + * + * \retval TC_STATUS_CHANNEL_0_MATCH Timer channel 0 compare/capture match + * \retval TC_STATUS_CHANNEL_1_MATCH Timer channel 1 compare/capture match + * \retval TC_STATUS_SYNC_READY Timer read synchronization has completed + * \retval TC_STATUS_CAPTURE_OVERFLOW Timer capture data has overflowed + * \retval TC_STATUS_COUNT_OVERFLOW Timer count value has overflowed + * \retval TC_STATUS_CHN0_BUFFER_VALID Timer count channel 0 compare/capture buffer valid + * \retval TC_STATUS_CHN1_BUFFER_VALID Timer count channel 1 compare/capture buffer valid + * \retval TC_STATUS_PERIOD_BUFFER_VALID Timer count period buffer valid + */ +static inline uint32_t tc_get_status( + struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + uint32_t int_flags = tc_module->INTFLAG.reg; + + uint32_t status_flags = 0; + + /* Check for TC channel 0 match */ + if (int_flags & TC_INTFLAG_MC(1)) { + status_flags |= TC_STATUS_CHANNEL_0_MATCH; + } + + /* Check for TC channel 1 match */ + if (int_flags & TC_INTFLAG_MC(2)) { + status_flags |= TC_STATUS_CHANNEL_1_MATCH; + } + +#if !defined(FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2) + /* Check for TC read synchronization ready */ + if (int_flags & TC_INTFLAG_SYNCRDY) { + status_flags |= TC_STATUS_SYNC_READY; + } +#endif + + /* Check for TC capture overflow */ + if (int_flags & TC_INTFLAG_ERR) { + status_flags |= TC_STATUS_CAPTURE_OVERFLOW; + } + + /* Check for TC count overflow */ + if (int_flags & TC_INTFLAG_OVF) { + status_flags |= TC_STATUS_COUNT_OVERFLOW; + } +#ifdef FEATURE_TC_DOUBLE_BUFFERED + uint8_t double_buffer_valid_status = tc_module->STATUS.reg; + + /* Check channel 0 compare or capture buffer valid */ + if (double_buffer_valid_status & TC_STATUS_CCBUFV0) { + status_flags |= TC_STATUS_CHN0_BUFFER_VALID; + } + /* Check channel 0 compare or capture buffer valid */ + if (double_buffer_valid_status & TC_STATUS_CCBUFV1) { + status_flags |= TC_STATUS_CHN1_BUFFER_VALID; + } + /* Check period buffer valid */ + if (double_buffer_valid_status & TC_STATUS_PERBUFV) { + status_flags |= TC_STATUS_PERIOD_BUFFER_VALID; + } +#endif + + return status_flags; +} + +/** + * \brief Clears a module status flag. + * + * Clears the given status flag of the module. + * + * \param[in] module_inst Pointer to the TC software instance struct + * \param[in] status_flags Bitmask of \c TC_STATUS_* flags to clear + */ +static inline void tc_clear_status( + struct tc_module *const module_inst, + const uint32_t status_flags) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + uint32_t int_flags = 0; + + /* Check for TC channel 0 match */ + if (status_flags & TC_STATUS_CHANNEL_0_MATCH) { + int_flags |= TC_INTFLAG_MC(1); + } + + /* Check for TC channel 1 match */ + if (status_flags & TC_STATUS_CHANNEL_1_MATCH) { + int_flags |= TC_INTFLAG_MC(2); + } + +#if !defined(FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2) + /* Check for TC read synchronization ready */ + if (status_flags & TC_STATUS_SYNC_READY) { + int_flags |= TC_INTFLAG_SYNCRDY; + } +#endif + + /* Check for TC capture overflow */ + if (status_flags & TC_STATUS_CAPTURE_OVERFLOW) { + int_flags |= TC_INTFLAG_ERR; + } + + /* Check for TC count overflow */ + if (status_flags & TC_STATUS_COUNT_OVERFLOW) { + int_flags |= TC_INTFLAG_OVF; + } + + /* Clear interrupt flag */ + tc_module->INTFLAG.reg = int_flags; +} + +/** @} */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +/** + * \page asfdoc_sam0_tc_extra Extra Information for TC Driver + * + * \section asfdoc_sam0_tc_extra_acronyms Acronyms + * The table below presents the acronyms used in this module: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
AcronymDescription
DMADirect Memory Access
TCTimer Counter
PWMPulse Width Modulation
PWPPulse Width Period
PPWPeriod Pulse Width
+ * + * + * \section asfdoc_sam0_tc_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - \ref asfdoc_sam0_system_pinmux_group "System Pin Multiplexer Driver" + * + * + * \section asfdoc_sam0_tc_extra_errata Errata + * There are no errata related to this driver. + * + * + * \section asfdoc_sam0_tc_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Changelog
Added support for SAMD21 and do some modifications as below: + * \li Clean up in the configuration structure, the counter size + * setting specific registers is accessed through the counter_8_bit, + * counter_16_bit and counter_32_bit structures + * \li All event related settings moved into the tc_event structure
Added automatic digital clock interface enable for the slave TC + * module when a timer is initialized in 32-bit mode
Initial Release
+ */ + +/** + * \page asfdoc_sam0_tc_exqsg Examples for TC Driver + * + * This is a list of the available Quick Start guides (QSGs) and example + * applications for \ref asfdoc_sam0_tc_group. QSGs are simple examples with + * step-by-step instructions to configure and use this driver in a selection of + * use cases. Note that QSGs can be compiled as a standalone application or be + * added to the user application. + * + * - \subpage asfdoc_sam0_tc_basic_use_case + * - \subpage asfdoc_sam0_tc_macth_freq_use_case + * \if TC_CALLBACK_MODE + * - \subpage asfdoc_sam0_tc_timer_use_case + * - \subpage asfdoc_sam0_tc_callback_use_case + * \endif + * - \subpage asfdoc_sam0_tc_dma_use_case + * + * \page asfdoc_sam0_tc_document_revision_history Document Revision History + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Doc. Rev. + * Date + * Comments + *
F08/2015Added support for SAM C21 and SAM L22
E04/2015Added support for SAM L21 and SAM DA1
D12/2014Added timer use case. + * Added support for SAM R21 and SAM D10/D11
C01/2014Added support for SAM D21
B06/2013Corrected documentation typos
A06/2013Initial release
+ */ + +#endif /* TC_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc_interrupt.c b/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc_interrupt.c new file mode 100644 index 0000000..032be2f --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc_interrupt.c @@ -0,0 +1,199 @@ +/** + * \file + * + * \brief SAM TC - Timer Counter Callback Driver + * + * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/* + * Support and FAQ: visit Atmel Support + */ + +#include "tc_interrupt.h" + +void *_tc_instances[TC_INST_NUM]; + +void _tc_interrupt_handler(uint8_t instance); + +/** + * \brief Registers a callback. + * + * Registers a callback function which is implemented by the user. + * + * \note The callback must be enabled by \ref tc_enable_callback, + * in order for the interrupt handler to call it when the conditions for the + * callback type is met. + * + * \param[in] module Pointer to TC software instance struct + * \param[in] callback_func Pointer to callback function + * \param[in] callback_type Callback type given by an enum + */ +enum status_code tc_register_callback( + struct tc_module *const module, + tc_callback_t callback_func, + const enum tc_callback callback_type) +{ + /* Sanity check arguments */ + Assert(module); + Assert(callback_func); + + /* Register callback function */ + module->callback[callback_type] = callback_func; + + /* Set the bit corresponding to the callback_type */ + if (callback_type == TC_CALLBACK_CC_CHANNEL0) { + module->register_callback_mask |= TC_INTFLAG_MC(1); + } + else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { + module->register_callback_mask |= TC_INTFLAG_MC(2); + } + else { + module->register_callback_mask |= (1 << callback_type); + } + return STATUS_OK; +} + +/** + * \brief Unregisters a callback. + * + * Unregisters a callback function implemented by the user. The callback should be + * disabled before it is unregistered. + * + * \param[in] module Pointer to TC software instance struct + * \param[in] callback_type Callback type given by an enum + */ +enum status_code tc_unregister_callback( + struct tc_module *const module, + const enum tc_callback callback_type) +{ + /* Sanity check arguments */ + Assert(module); + + /* Unregister callback function */ + module->callback[callback_type] = NULL; + + /* Clear the bit corresponding to the callback_type */ + if (callback_type == TC_CALLBACK_CC_CHANNEL0) { + module->register_callback_mask &= ~TC_INTFLAG_MC(1); + } + else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { + module->register_callback_mask &= ~TC_INTFLAG_MC(2); + } + else { + module->register_callback_mask &= ~(1 << callback_type); + } + return STATUS_OK; +} + +/** + * \internal ISR handler for TC + * + * Auto-generate a set of interrupt handlers for each TC in the device. + */ +#define _TC_INTERRUPT_HANDLER(n, m) \ + void TC##n##_Handler(void) \ + { \ + _tc_interrupt_handler(m); \ + } + +#if (SAML21E) || (SAML21G) + _TC_INTERRUPT_HANDLER(0,0) + _TC_INTERRUPT_HANDLER(1,1) + _TC_INTERRUPT_HANDLER(4,2) +#else + MRECURSION(TC_INST_NUM, _TC_INTERRUPT_HANDLER, TC_INST_MAX_ID) +#endif + + +/** + * \internal Interrupt Handler for TC module + * + * Handles interrupts as they occur, it will run the callback functions + * that are registered and enabled. + * + * \param[in] instance ID of the TC instance calling the interrupt + * handler. + */ +void _tc_interrupt_handler( + uint8_t instance) +{ + /* Temporary variable */ + uint8_t interrupt_and_callback_status_mask; + + /* Get device instance from the look-up table */ + struct tc_module *module + = (struct tc_module *)_tc_instances[instance]; + + /* Read and mask interrupt flag register */ + interrupt_and_callback_status_mask = module->hw->COUNT8.INTFLAG.reg & + module->register_callback_mask & + module->enable_callback_mask; + + /* Check if an Overflow interrupt has occurred */ + if (interrupt_and_callback_status_mask & TC_INTFLAG_OVF) { + /* Invoke registered and enabled callback function */ + (module->callback[TC_CALLBACK_OVERFLOW])(module); + /* Clear interrupt flag */ + module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_OVF; + } + + /* Check if an Error interrupt has occurred */ + if (interrupt_and_callback_status_mask & TC_INTFLAG_ERR) { + /* Invoke registered and enabled callback function */ + (module->callback[TC_CALLBACK_ERROR])(module); + /* Clear interrupt flag */ + module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_ERR; + } + + /* Check if an Match/Capture Channel 0 interrupt has occurred */ + if (interrupt_and_callback_status_mask & TC_INTFLAG_MC(1)) { + /* Invoke registered and enabled callback function */ + (module->callback[TC_CALLBACK_CC_CHANNEL0])(module); + /* Clear interrupt flag */ + module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_MC(1); + } + + /* Check if an Match/Capture Channel 1 interrupt has occurred */ + if (interrupt_and_callback_status_mask & TC_INTFLAG_MC(2)) { + /* Invoke registered and enabled callback function */ + (module->callback[TC_CALLBACK_CC_CHANNEL1])(module); + /* Clear interrupt flag */ + module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_MC(2); + } +} diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc_interrupt.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc_interrupt.h new file mode 100644 index 0000000..4e1fd8e --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc_interrupt.h @@ -0,0 +1,179 @@ +/** + * \file + * + * \brief SAM TC - Timer Counter Callback Driver + * + * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/* + * Support and FAQ: visit Atmel Support + */ + +#ifndef TC_INTERRUPT_H_INCLUDED +#define TC_INTERRUPT_H_INCLUDED + +#include "tc.h" +#include "system_interrupt.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(__DOXYGEN__) +extern void *_tc_instances[TC_INST_NUM]; + +# define _TC_INTERRUPT_VECT_NUM(n, unused) \ + SYSTEM_INTERRUPT_MODULE_TC##n, +/** + * \internal Get the interrupt vector for the given device instance + * + * \param[in] TC module instance number. + * + * \return Interrupt vector for of the given TC module instance. + */ +static enum system_interrupt_vector _tc_interrupt_get_interrupt_vector( + uint32_t inst_num) +{ + static uint8_t tc_interrupt_vectors[TC_INST_NUM] = + { +#if (SAML21E) || (SAML21G) + SYSTEM_INTERRUPT_MODULE_TC0, + SYSTEM_INTERRUPT_MODULE_TC1, + SYSTEM_INTERRUPT_MODULE_TC4 +#else + MRECURSION(TC_INST_NUM, _TC_INTERRUPT_VECT_NUM, TC_INST_MAX_ID) +#endif + }; + + return (enum system_interrupt_vector)tc_interrupt_vectors[inst_num]; +} +#endif /* !defined(__DOXYGEN__) */ + +/** + * \name Callback Management + * {@ + */ + +enum status_code tc_register_callback( + struct tc_module *const module, + tc_callback_t callback_func, + const enum tc_callback callback_type); + +enum status_code tc_unregister_callback( + struct tc_module *const module, + const enum tc_callback callback_type); + +/** + * \brief Enables callback. + * + * Enables the callback function registered by the \ref + * tc_register_callback. The callback function will be called from the + * interrupt handler when the conditions for the callback type are + * met. This function will also enable the appropriate interrupts. + * + * \param[in] module Pointer to TC software instance struct + * \param[in] callback_type Callback type given by an enum + */ +static inline void tc_enable_callback( + struct tc_module *const module, + const enum tc_callback callback_type) +{ + /* Sanity check arguments */ + Assert(module); + + + /* Enable interrupts for this TC module */ + system_interrupt_enable(_tc_interrupt_get_interrupt_vector(_tc_get_inst_index(module->hw))); + + /* Enable callback */ + if (callback_type == TC_CALLBACK_CC_CHANNEL0) { + module->enable_callback_mask |= TC_INTFLAG_MC(1); + module->hw->COUNT8.INTENSET.reg = TC_INTFLAG_MC(1); + } + else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { + module->enable_callback_mask |= TC_INTFLAG_MC(2); + module->hw->COUNT8.INTENSET.reg = TC_INTFLAG_MC(2); + } + else { + module->enable_callback_mask |= (1 << callback_type); + module->hw->COUNT8.INTENSET.reg = (1 << callback_type); + } +} + +/** + * \brief Disables callback. + * + * Disables the callback function registered by the \ref + * tc_register_callback, and the callback will not be called from the + * interrupt routine. The function will also disable the appropriate + * interrupts. + * + * \param[in] module Pointer to TC software instance struct + * \param[in] callback_type Callback type given by an enum + */ +static inline void tc_disable_callback( + struct tc_module *const module, + const enum tc_callback callback_type){ + /* Sanity check arguments */ + Assert(module); + + /* Disable callback */ + if (callback_type == TC_CALLBACK_CC_CHANNEL0) { + module->hw->COUNT8.INTENCLR.reg = TC_INTFLAG_MC(1); + module->enable_callback_mask &= ~TC_INTFLAG_MC(1); + } + else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { + module->hw->COUNT8.INTENCLR.reg = TC_INTFLAG_MC(2); + module->enable_callback_mask &= ~TC_INTFLAG_MC(2); + } + else { + module->hw->COUNT8.INTENCLR.reg = (1 << callback_type); + module->enable_callback_mask &= ~(1 << callback_type); + } +} + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* TC_INTERRUPT_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/wdt.c b/feather_sensor_transmit/libraries/Adafruit_ASFcore/wdt.c new file mode 100644 index 0000000..c5b0895 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/wdt.c @@ -0,0 +1,264 @@ +/** + * \file + * + * \brief SAM Watchdog Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#include "wdt.h" +#include + +/** + * \brief Sets up the WDT hardware module based on the configuration. + * + * Writes a given configuration of a WDT configuration to the + * hardware module, and initializes the internal device struct. + * + * \param[in] config Pointer to the configuration struct + * + * \return Status of the configuration procedure. + * + * \retval STATUS_OK If the module was configured correctly + * \retval STATUS_ERR_INVALID_ARG If invalid argument(s) were supplied + * \retval STATUS_ERR_IO If the Watchdog module is locked to be always on + */ +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) +enum status_code wdt_set_config( + const struct wdt_conf *const config) +{ + /* Sanity check arguments */ + Assert(config); + + Wdt *const WDT_module = WDT; + + /* Turn on the digital interface clock */ + system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBA, MCLK_APBAMASK_WDT); + + /* Check of the Watchdog has been locked to be always on, if so, abort */ + if (wdt_is_locked()) { + return STATUS_ERR_IO; + } + + /* Check for an invalid timeout period, abort if found */ + if (config->timeout_period == WDT_PERIOD_NONE) { + return STATUS_ERR_INVALID_ARG; + } + + /* Make sure the Window and Early Warning periods are not more than the + * reset period, abort if either is invalid */ + if ((config->timeout_period < config->window_period) || + (config->timeout_period < config->early_warning_period)) { + return STATUS_ERR_INVALID_ARG; + } + + /* Disable the Watchdog module */ + WDT_module->CTRLA.reg &= ~WDT_CTRLA_ENABLE; + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + if(config->enable == false) { + return STATUS_OK; + } + + uint32_t new_config = 0; + + /* Update the timeout period value with the requested period */ + new_config |= (config->timeout_period - 1) << WDT_CONFIG_PER_Pos; + + /* Check if the user has requested a reset window period */ + if (config->window_period != WDT_PERIOD_NONE) { + WDT_module->CTRLA.reg |= WDT_CTRLA_WEN; + + /* Update and enable the timeout period value */ + new_config |= (config->window_period - 1) << WDT_CONFIG_WINDOW_Pos; + } else { + /* Ensure the window enable control flag is cleared */ + WDT_module->CTRLA.reg &= ~WDT_CTRLA_WEN; + } + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + /* Write the new Watchdog configuration */ + WDT_module->CONFIG.reg = new_config; + + /* Check if the user has requested an early warning period */ + if (config->early_warning_period != WDT_PERIOD_NONE) { + /* Set the Early Warning period */ + WDT_module->EWCTRL.reg + = (config->early_warning_period - 1) << WDT_EWCTRL_EWOFFSET_Pos; + } + + /* Either enable or lock-enable the Watchdog timer depending on the user + * settings */ + if (config->always_on) { + WDT_module->CTRLA.reg |= WDT_CTRLA_ALWAYSON; + } else { + WDT_module->CTRLA.reg |= WDT_CTRLA_ENABLE; + } + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + return STATUS_OK; +} +#else +enum status_code wdt_set_config( + const struct wdt_conf *const config) +{ + /* Sanity check arguments */ + Assert(config); + + Wdt *const WDT_module = WDT; + + /* Turn on the digital interface clock */ + system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBA, PM_APBAMASK_WDT); + + /* Check of the Watchdog has been locked to be always on, if so, abort */ + if (wdt_is_locked()) { + return STATUS_ERR_IO; + } + + /* Check for an invalid timeout period, abort if found */ + if (config->timeout_period == WDT_PERIOD_NONE) { + return STATUS_ERR_INVALID_ARG; + } + + /* Make sure the Window and Early Warning periods are not more than the + * reset period, abort if either is invalid */ + if ((config->timeout_period < config->window_period) || + (config->timeout_period < config->early_warning_period)) { + return STATUS_ERR_INVALID_ARG; + } + + /* Disable the Watchdog module */ + WDT_module->CTRL.reg &= ~WDT_CTRL_ENABLE; + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + if(config->enable == false) { + return STATUS_OK; + } + + /* Configure GCLK channel and enable clock */ + struct system_gclk_chan_config gclk_chan_conf; + gclk_chan_conf.source_generator = config->clock_source; + system_gclk_chan_set_config(WDT_GCLK_ID, &gclk_chan_conf); + system_gclk_chan_enable(WDT_GCLK_ID); + if (config->always_on) { + system_gclk_chan_lock(WDT_GCLK_ID); + } + + uint32_t new_config = 0; + + /* Update the timeout period value with the requested period */ + new_config |= (config->timeout_period - 1) << WDT_CONFIG_PER_Pos; + + /* Check if the user has requested a reset window period */ + if (config->window_period != WDT_PERIOD_NONE) { + WDT_module->CTRL.reg |= WDT_CTRL_WEN; + + /* Update and enable the timeout period value */ + new_config |= (config->window_period - 1) << WDT_CONFIG_WINDOW_Pos; + } else { + /* Ensure the window enable control flag is cleared */ + WDT_module->CTRL.reg &= ~WDT_CTRL_WEN; + } + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + /* Write the new Watchdog configuration */ + WDT_module->CONFIG.reg = new_config; + + /* Check if the user has requested an early warning period */ + if (config->early_warning_period != WDT_PERIOD_NONE) { + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + /* Set the Early Warning period */ + WDT_module->EWCTRL.reg + = (config->early_warning_period - 1) << WDT_EWCTRL_EWOFFSET_Pos; + } + + /* Either enable or lock-enable the Watchdog timer depending on the user + * settings */ + if (config->always_on) { + WDT_module->CTRL.reg |= WDT_CTRL_ALWAYSON; + } else { + WDT_module->CTRL.reg |= WDT_CTRL_ENABLE; + } + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + return STATUS_OK; +} +#endif + +/** + * \brief Resets the count of the running Watchdog Timer that was previously enabled. + * + * Resets the current count of the Watchdog Timer, restarting the timeout + * period count elapsed. This function should be called after the window + * period (if one was set in the module configuration) but before the timeout + * period to prevent a reset of the system. + */ +void wdt_reset_count(void) +{ + Wdt *const WDT_module = WDT; + + /* Disable the Watchdog module */ + WDT_module->CLEAR.reg = WDT_CLEAR_CLEAR_KEY; + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } +} diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/wdt.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/wdt.h new file mode 100644 index 0000000..c4c37cf --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_ASFcore/wdt.h @@ -0,0 +1,501 @@ +/** + * \file + * + * \brief SAM Watchdog Driver + * + * Copyright (c) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef WDT_H_INCLUDED +#define WDT_H_INCLUDED + +/** + * \defgroup asfdoc_sam0_wdt_group SAM Watchdog Driver (WDT) + * + * This driver for Atmel® | SMART SAM devices provides an interface for the configuration + * and management of the device's Watchdog Timer module, including the enabling, + * disabling, and kicking within the device. The following driver API modes are + * covered by this manual: + * + * - Polled APIs + * \if WDT_CALLBACK_MODE + * - Callback APIs + * \endif + * + * The following peripherals are used by this module: + * - WDT (Watchdog Timer) + * + * The following devices can use this module: + * - Atmel | SMART SAM D20/D21 + * - Atmel | SMART SAM R21 + * - Atmel | SMART SAM D09/D10/D11 + * - Atmel | SMART SAM L21/L22 + * - Atmel | SMART SAM DA1 + * - Atmel | SMART SAM C20/C21 + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_wdt_prerequisites + * - \ref asfdoc_sam0_wdt_module_overview + * - \ref asfdoc_sam0_wdt_special_considerations + * - \ref asfdoc_sam0_wdt_extra_info + * - \ref asfdoc_sam0_wdt_examples + * - \ref asfdoc_sam0_wdt_api_overview + * + * + * \section asfdoc_sam0_wdt_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * + * \section asfdoc_sam0_wdt_module_overview Module Overview + * + * The Watchdog module (WDT) is designed to give an added level of safety in + * critical systems, to ensure a system reset is triggered in the case of a + * deadlock or other software malfunction that prevents normal device operation. + * + * At a basic level, the Watchdog is a system timer with a fixed period; once + * enabled, it will continue to count ticks of its asynchronous clock until + * it is periodically reset, or the timeout period is reached. In the event of a + * Watchdog timeout, the module will trigger a system reset identical to a pulse + * of the device's reset pin, resetting all peripherals to their power-on + * default states and restarting the application software from the reset vector. + * + * In many systems, there is an obvious upper bound to the amount of time each + * iteration of the main application loop can be expected to run, before a + * malfunction can be assumed (either due to a deadlock waiting on hardware or + * software, or due to other means). When the Watchdog is configured with a + * timeout period equal to this upper bound, a malfunction in the system will + * force a full system reset to allow for a graceful recovery. + * + * \subsection asfdoc_sam0_wdt_module_locked_mode Locked Mode + * The Watchdog configuration can be set in the device fuses and locked in + * hardware, so that no software changes can be made to the Watchdog + * configuration. Additionally, the Watchdog can be locked on in software if it + * is not already locked, so that the module configuration cannot be modified + * until a power on reset of the device. + * + * The locked configuration can be used to ensure that faulty software does not + * cause the Watchdog configuration to be changed, preserving the level of + * safety given by the module. + * + * \subsection asfdoc_sam0_wdt_module_window_mode Window Mode + * Just as there is a reasonable upper bound to the time the main program loop + * should take for each iteration, there is also in many applications a lower + * bound, i.e. a \a minimum time for which each loop iteration should run for + * under normal circumstances. To guard against a system failure resetting the + * Watchdog in a tight loop (or a failure in the system application causing the + * main loop to run faster than expected) a "Window" mode can be enabled to + * disallow resetting of the Watchdog counter before a certain period of time. + * If the Watchdog is not reset \a after the window opens but not \a before the + * Watchdog expires, the system will reset. + * + * \subsection asfdoc_sam0_wdt_module_early_warning Early Warning + * In some cases it is desirable to receive an early warning that the Watchdog is + * about to expire, so that some system action (such as saving any system + * configuration data for failure analysis purposes) can be performed before the + * system reset occurs. The Early Warning feature of the Watchdog module allows + * such a notification to be requested; after the configured early warning time + * (but before the expiry of the Watchdog counter) the Early Warning flag will + * become set, so that the user application can take an appropriate action. + * + * \note It is important to note that the purpose of the Early Warning feature + * is \a not to allow the user application to reset the Watchdog; doing + * so will defeat the safety the module gives to the user application. + * Instead, this feature should be used purely to perform any tasks that + * need to be undertaken before the system reset occurs. + * + * \subsection asfdoc_sam0_wdt_module_overview_physical Physical Connection + * + * \ref asfdoc_sam0_wdt_module_int_connections "The figure below" shows how + * this module is interconnected within the device. + * + * \anchor asfdoc_sam0_wdt_module_int_connections + * \dot + * digraph overview { + * rankdir=LR; + * node [label="GCLK*\nGeneric Clock" shape=square] wdt_clock; + * + * subgraph driver { + * node [label=" WDT | Watchdog Counter" shape=record] wdt_module; + * node [label="System Reset Logic" shape=ellipse style=filled fillcolor=lightgray] sys_reset; + * } + * + * wdt_clock -> wdt_module:f1; + * wdt_module:f1 -> sys_reset; + * } + * \enddot + * + * \note Watchdog Counter of SAM L21/L22 is \a not provided by GCLK, but it uses an + * internal 1KHz OSCULP32K output clock. + * + * \section asfdoc_sam0_wdt_special_considerations Special Considerations + * + * On some devices the Watchdog configuration can be fused to be always on in + * a particular configuration; if this mode is enabled the Watchdog is not + * software configurable and can have its count reset and early warning state + * checked/cleared only. + * + * \section asfdoc_sam0_wdt_extra_info Extra Information + * + * For extra information, see \ref asfdoc_sam0_wdt_extra. This includes: + * - \ref asfdoc_sam0_wdt_extra_acronyms + * - \ref asfdoc_sam0_wdt_extra_dependencies + * - \ref asfdoc_sam0_wdt_extra_errata + * - \ref asfdoc_sam0_wdt_extra_history + * + * + * \section asfdoc_sam0_wdt_examples Examples + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_wdt_exqsg. + * + * \section asfdoc_sam0_wdt_api_overview API Overview + * @{ + */ + +#include +#include +#include + +#if WDT_CALLBACK_MODE == true +# include "wdt_callback.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Watchdog Timer period configuration enum. + * + * Enum for the possible period settings of the Watchdog timer module, for + * values requiring a period as a number of Watchdog timer clock ticks. + */ +enum wdt_period { + /** No Watchdog period. This value can only be used when setting the + * Window and Early Warning periods; its use as the Watchdog Reset + * Period is invalid. */ + WDT_PERIOD_NONE = 0, + /** Watchdog period of 8 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_8CLK = 1, + /** Watchdog period of 16 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_16CLK = 2, + /** Watchdog period of 32 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_32CLK = 3, + /** Watchdog period of 64 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_64CLK = 4, + /** Watchdog period of 128 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_128CLK = 5, + /** Watchdog period of 256 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_256CLK = 6, + /** Watchdog period of 512 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_512CLK = 7, + /** Watchdog period of 1024 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_1024CLK = 8, + /** Watchdog period of 2048 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_2048CLK = 9, + /** Watchdog period of 4096 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_4096CLK = 10, + /** Watchdog period of 8192 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_8192CLK = 11, + /** Watchdog period of 16384 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_16384CLK = 12, +}; + +/** + * \brief Watchdog Timer configuration structure. + * + * Configuration structure for a Watchdog Timer instance. This + * structure should be initialized by the \ref wdt_get_config_defaults() + * function before being modified by the user application. + */ +struct wdt_conf { + /** If \c true, the Watchdog will be locked to the current configuration + * settings when the Watchdog is enabled. */ + bool always_on; + /** Enable/Disable the Watchdog Timer. */ + bool enable; +#if !(SAML21) && !(SAML22) && !(SAMC20) && !(SAMC21) + /** GCLK generator used to clock the peripheral except SAM L21/L22/C21/C20.*/ + enum gclk_generator clock_source; +#endif + /** Number of Watchdog timer clock ticks until the Watchdog expires. */ + enum wdt_period timeout_period; + /** Number of Watchdog timer clock ticks until the reset window opens. */ + enum wdt_period window_period; + /** Number of Watchdog timer clock ticks until the early warning flag is + * set. */ + enum wdt_period early_warning_period; +}; + +/** \name Configuration and Initialization + * @{ + */ + +/** + * \brief Determines if the hardware module(s) are currently synchronizing to the bus. + * + * Checks to see if the underlying hardware peripheral module(s) are currently + * synchronizing across multiple clock domains to the hardware bus. This + * function can be used to delay further operations on a module until such time + * that it is ready, to prevent blocking delays for synchronization in the + * user application. + * + * \return Synchronization status of the underlying hardware module(s). + * + * \retval false If the module has completed synchronization + * \retval true If the module synchronization is ongoing + */ +static inline bool wdt_is_syncing(void) +{ + Wdt *const WDT_module = WDT; + +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) + if (WDT_module->SYNCBUSY.reg) { +#else + if (WDT_module->STATUS.reg & WDT_STATUS_SYNCBUSY) { +#endif + return true; + } + + return false; +} + +/** + * \brief Initializes a Watchdog Timer configuration structure to defaults. + * + * Initializes a given Watchdog Timer configuration structure to a set of + * known default values. This function should be called on all new + * instances of these configuration structures before being modified by the + * user application. + * + * The default configuration is as follows: + * \li Not locked, to allow for further (re-)configuration + * \li Enable WDT + * \li Watchdog timer sourced from Generic Clock Channel 4 + * \li A timeout period of 16384 clocks of the Watchdog module clock + * \li No window period, so that the Watchdog count can be reset at any time + * \li No early warning period to indicate the Watchdog will soon expire + * + * \param[out] config Configuration structure to initialize to default values + */ +static inline void wdt_get_config_defaults( + struct wdt_conf *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Default configuration values */ + config->always_on = false; + config->enable = true; +#if !(SAML21) && !(SAML22) && !(SAMC20) && !(SAMC21) + config->clock_source = GCLK_GENERATOR_4; +#endif + config->timeout_period = WDT_PERIOD_16384CLK; + config->window_period = WDT_PERIOD_NONE; + config->early_warning_period = WDT_PERIOD_NONE; +} + +enum status_code wdt_set_config( + const struct wdt_conf *const config); + +/** \brief Determines if the Watchdog timer is currently locked in an enabled state. + * + * Determines if the Watchdog timer is currently enabled and locked, so that + * it cannot be disabled or otherwise reconfigured. + * + * \return Current Watchdog lock state. + */ +static inline bool wdt_is_locked(void) +{ + Wdt *const WDT_module = WDT; + +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) + return (WDT_module->CTRLA.reg & WDT_CTRLA_ALWAYSON); +#else + return (WDT_module->CTRL.reg & WDT_CTRL_ALWAYSON); +#endif +} + +/** @} */ + +/** \name Timeout and Early Warning Management + * @{ + */ + +/** \brief Clears the Watchdog timer early warning period elapsed flag. + * + * Clears the Watchdog timer early warning period elapsed flag, so that a new + * early warning period can be detected. + */ +static inline void wdt_clear_early_warning(void) +{ + Wdt *const WDT_module = WDT; + + WDT_module->INTFLAG.reg = WDT_INTFLAG_EW; +} + +/** \brief Determines if the Watchdog timer early warning period has elapsed. + * + * Determines if the Watchdog timer early warning period has elapsed. + * + * \note If no early warning period was configured, the value returned by this + * function is invalid. + * + * \return Current Watchdog Early Warning state. + */ +static inline bool wdt_is_early_warning(void) +{ + Wdt *const WDT_module = WDT; + + return (WDT_module->INTFLAG.reg & WDT_INTFLAG_EW); +} + +void wdt_reset_count(void); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +/** @} */ + +/** + * \page asfdoc_sam0_wdt_extra Extra Information for WDT Driver + * + * \section asfdoc_sam0_wdt_extra_acronyms Acronyms + * The table below presents the acronyms used in this module: + * + * + * + * + * + * + * + * + * + * + *
AcronymDescription
WDTWatchdog Timer
+ * + * + * \section asfdoc_sam0_wdt_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - \ref asfdoc_sam0_system_clock_group "System Clock Driver" + * + * + * \section asfdoc_sam0_wdt_extra_errata Errata + * There are no errata related to this driver. + * + * + * \section asfdoc_sam0_wdt_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * + * + * + * + * + * + *
Changelog
Driver updated to follow driver type convention: + * \li wdt_init, wdt_enable, wdt_disable functions removed + * \li wdt_set_config function added + * \li WDT module enable state moved inside the configuration struct
Initial Release
+ */ + +/** + * \page asfdoc_sam0_wdt_exqsg Examples for WDT Driver + * + * This is a list of the available Quick Start guides (QSGs) and example + * applications for \ref asfdoc_sam0_wdt_group. QSGs are simple examples with + * step-by-step instructions to configure and use this driver in a selection of + * use cases. Note that QSGs can be compiled as a standalone application or be + * added to the user application. + * + * - \subpage asfdoc_sam0_wdt_basic_use_case + * \if WDT_CALLBACK_MODE + * - \subpage asfdoc_sam0_wdt_callback_use_case + * \endif + * + * \page asfdoc_sam0_wdt_document_revision_history Document Revision History + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Doc. Rev. + * Date + * Comments + *
E08/2015Added support for SAM L21/L22, SAM DA1, and SAM C20/C2
D12/2014Added SAMR21 and SAMD10/D11 support
C01/2014Add SAMD21 support
B06/2013Corrected documentation typos
A06/2013Initial release
+ */ + +#endif /* WDT_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp new file mode 100644 index 0000000..fe721be --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp @@ -0,0 +1,2079 @@ +/*************************************************** + This is a library for our Adafruit FONA Cellular Module + + Designed specifically to work with the Adafruit FONA + ----> http://www.adafruit.com/products/1946 + ----> http://www.adafruit.com/products/1963 + + These displays use TTL Serial to communicate, 2 pins are required to + interface + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ****************************************************/ + // next line per http://postwarrior.com/arduino-ethershield-error-prog_char-does-not-name-a-type/ + +#include "Adafruit_FONA.h" + + + + +Adafruit_FONA::Adafruit_FONA(int8_t rst) +{ + _rstpin = rst; + + apn = F("FONAnet"); + apnusername = 0; + apnpassword = 0; + mySerial = 0; + httpsredirect = false; + useragent = F("FONA"); + ok_reply = F("OK"); +} + +uint8_t Adafruit_FONA::type(void) { + return _type; +} + +boolean Adafruit_FONA::begin(Stream &port) { + mySerial = &port; + + pinMode(_rstpin, OUTPUT); + digitalWrite(_rstpin, HIGH); + delay(10); + digitalWrite(_rstpin, LOW); + delay(100); + digitalWrite(_rstpin, HIGH); + + DEBUG_PRINTLN(F("Attempting to open comm with ATs")); + // give 7 seconds to reboot + int16_t timeout = 7000; + + while (timeout > 0) { + while (mySerial->available()) mySerial->read(); + if (sendCheckReply(F("AT"), ok_reply)) + break; + while (mySerial->available()) mySerial->read(); + if (sendCheckReply(F("AT"), F("AT"))) + break; + delay(500); + timeout-=500; + } + +#ifdef ADAFRUIT_FONA_DEBUG + if (timeout <= 0) + DEBUG_PRINTLN(F("Timeout: No response to AT... last ditch attempt.")); +#endif + + sendCheckReply(F("AT"), ok_reply); + delay(100); + sendCheckReply(F("AT"), ok_reply); + delay(100); + sendCheckReply(F("AT"), ok_reply); + delay(100); + + // turn off Echo! + sendCheckReply(F("ATE0"), ok_reply); + delay(100); + + if (! sendCheckReply(F("ATE0"), ok_reply)) { + return false; + } + + // turn on hangupitude + sendCheckReply(F("AT+CVHU=0"), ok_reply); + + delay(100); + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN("ATI"); + + mySerial->println("ATI"); + readline(500, true); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + + + if (prog_char_strstr(replybuffer, (prog_char *)F("SIM808 R14")) != 0) { + _type = FONA808_V2; + } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIM808 R13")) != 0) { + _type = FONA808_V1; + } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIM800 R14")) != 0) { + _type = FONA800L; + } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIMCOM_SIM5320A")) != 0) { + _type = FONA3G_A; + } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIMCOM_SIM5320E")) != 0) { + _type = FONA3G_E; + } + + if (_type == FONA800L) { + // determine if L or H + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN("AT+GMM"); + + mySerial->println("AT+GMM"); + readline(500, true); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + + if (prog_char_strstr(replybuffer, (prog_char *)F("SIM800H")) != 0) { + _type = FONA800H; + } + } + +#if defined(FONA_PREF_SMS_STORAGE) + sendCheckReply(F("AT+CPMS=\"" FONA_PREF_SMS_STORAGE "\""), ok_reply); +#endif + + return true; +} + + +/********* Serial port ********************************************/ +boolean Adafruit_FONA::setBaudrate(uint16_t baud) { + return sendCheckReply(F("AT+IPREX="), baud, ok_reply); +} + +/********* Real Time Clock ********************************************/ + +boolean Adafruit_FONA::readRTC(uint8_t *year, uint8_t *month, uint8_t *date, uint8_t *hr, uint8_t *min, uint8_t *sec) { + uint16_t v; + sendParseReply(F("AT+CCLK?"), F("+CCLK: "), &v, '/', 0); + *year = v; + + DEBUG_PRINTLN(*year); +} + +boolean Adafruit_FONA::enableRTC(uint8_t i) { + if (! sendCheckReply(F("AT+CLTS="), i, ok_reply)) + return false; + return sendCheckReply(F("AT&W"), ok_reply); +} + + +/********* BATTERY & ADC ********************************************/ + +/* returns value in mV (uint16_t) */ +boolean Adafruit_FONA::getBattVoltage(uint16_t *v) { + return sendParseReply(F("AT+CBC"), F("+CBC: "), v, ',', 2); +} + +/* returns value in mV (uint16_t) */ +boolean Adafruit_FONA_3G::getBattVoltage(uint16_t *v) { + float f; + boolean b = sendParseReply(F("AT+CBC"), F("+CBC: "), &f, ',', 2); + *v = f*1000; + return b; +} + + +/* returns the percentage charge of battery as reported by sim800 */ +boolean Adafruit_FONA::getBattPercent(uint16_t *p) { + return sendParseReply(F("AT+CBC"), F("+CBC: "), p, ',', 1); +} + +boolean Adafruit_FONA::getADCVoltage(uint16_t *v) { + return sendParseReply(F("AT+CADC?"), F("+CADC: 1,"), v); +} + +/********* SIM ***********************************************************/ + +uint8_t Adafruit_FONA::unlockSIM(char *pin) +{ + char sendbuff[14] = "AT+CPIN="; + sendbuff[8] = pin[0]; + sendbuff[9] = pin[1]; + sendbuff[10] = pin[2]; + sendbuff[11] = pin[3]; + sendbuff[12] = '\0'; + + return sendCheckReply(sendbuff, ok_reply); +} + +uint8_t Adafruit_FONA::getSIMCCID(char *ccid) { + getReply(F("AT+CCID")); + // up to 28 chars for reply, 20 char total ccid + if (replybuffer[0] == '+') { + // fona 3g? + strncpy(ccid, replybuffer+8, 20); + } else { + // fona 800 or 800 + strncpy(ccid, replybuffer, 20); + } + ccid[20] = 0; + + readline(); // eat 'OK' + + return strlen(ccid); +} + +/********* IMEI **********************************************************/ + +uint8_t Adafruit_FONA::getIMEI(char *imei) { + getReply(F("AT+GSN")); + + // up to 15 chars + strncpy(imei, replybuffer, 15); + imei[15] = 0; + + readline(); // eat 'OK' + + return strlen(imei); +} + +/********* NETWORK *******************************************************/ + +uint8_t Adafruit_FONA::getNetworkStatus(void) { + uint16_t status; + + if (! sendParseReply(F("AT+CREG?"), F("+CREG: "), &status, ',', 1)) return 0; + + return status; +} + + +uint8_t Adafruit_FONA::getRSSI(void) { + uint16_t reply; + + if (! sendParseReply(F("AT+CSQ"), F("+CSQ: "), &reply) ) return 0; + + return reply; +} + +/********* AUDIO *******************************************************/ + +boolean Adafruit_FONA::setAudio(uint8_t a) { + // 0 is headset, 1 is external audio + if (a > 1) return false; + + return sendCheckReply(F("AT+CHFA="), a, ok_reply); +} + +uint8_t Adafruit_FONA::getVolume(void) { + uint16_t reply; + + if (! sendParseReply(F("AT+CLVL?"), F("+CLVL: "), &reply) ) return 0; + + return reply; +} + +boolean Adafruit_FONA::setVolume(uint8_t i) { + return sendCheckReply(F("AT+CLVL="), i, ok_reply); +} + + +boolean Adafruit_FONA::playDTMF(char dtmf) { + char str[4]; + str[0] = '\"'; + str[1] = dtmf; + str[2] = '\"'; + str[3] = 0; + return sendCheckReply(F("AT+CLDTMF=3,"), str, ok_reply); +} + +boolean Adafruit_FONA::playToolkitTone(uint8_t t, uint16_t len) { + return sendCheckReply(F("AT+STTONE=1,"), t, len, ok_reply); +} + +boolean Adafruit_FONA_3G::playToolkitTone(uint8_t t, uint16_t len) { + if (! sendCheckReply(F("AT+CPTONE="), t, ok_reply)) + return false; + delay(len); + return sendCheckReply(F("AT+CPTONE=0"), ok_reply); +} + +boolean Adafruit_FONA::setMicVolume(uint8_t a, uint8_t level) { + // 0 is headset, 1 is external audio + if (a > 1) return false; + + return sendCheckReply(F("AT+CMIC="), a, level, ok_reply); +} + +/********* FM RADIO *******************************************************/ + + +boolean Adafruit_FONA::FMradio(boolean onoff, uint8_t a) { + if (! onoff) { + return sendCheckReply(F("AT+FMCLOSE"), ok_reply); + } + + // 0 is headset, 1 is external audio + if (a > 1) return false; + + return sendCheckReply(F("AT+FMOPEN="), a, ok_reply); +} + +boolean Adafruit_FONA::tuneFMradio(uint16_t station) { + // Fail if FM station is outside allowed range. + if ((station < 870) || (station > 1090)) + return false; + + return sendCheckReply(F("AT+FMFREQ="), station, ok_reply); +} + +boolean Adafruit_FONA::setFMVolume(uint8_t i) { + // Fail if volume is outside allowed range (0-6). + if (i > 6) { + return false; + } + // Send FM volume command and verify response. + return sendCheckReply(F("AT+FMVOLUME="), i, ok_reply); +} + +int8_t Adafruit_FONA::getFMVolume() { + uint16_t level; + + if (! sendParseReply(F("AT+FMVOLUME?"), F("+FMVOLUME: "), &level) ) return 0; + + return level; +} + +int8_t Adafruit_FONA::getFMSignalLevel(uint16_t station) { + // Fail if FM station is outside allowed range. + if ((station < 875) || (station > 1080)) { + return -1; + } + + // Send FM signal level query command. + // Note, need to explicitly send timeout so right overload is chosen. + getReply(F("AT+FMSIGNAL="), station, FONA_DEFAULT_TIMEOUT_MS); + // Check response starts with expected value. + char *p = prog_char_strstr(replybuffer, PSTR("+FMSIGNAL: ")); + if (p == 0) return -1; + p+=11; + // Find second colon to get start of signal quality. + p = strchr(p, ':'); + if (p == 0) return -1; + p+=1; + // Parse signal quality. + int8_t level = atoi(p); + readline(); // eat the "OK" + return level; +} + +/********* PWM/BUZZER **************************************************/ + +boolean Adafruit_FONA::setPWM(uint16_t period, uint8_t duty) { + if (period > 2000) return false; + if (duty > 100) return false; + + return sendCheckReply(F("AT+SPWM=0,"), period, duty, ok_reply); +} + +/********* CALL PHONES **************************************************/ +boolean Adafruit_FONA::callPhone(char *number) { + char sendbuff[35] = "ATD"; + strncpy(sendbuff+3, number, min(30, strlen(number))); + uint8_t x = strlen(sendbuff); + sendbuff[x] = ';'; + sendbuff[x+1] = 0; + //DEBUG_PRINTLN(sendbuff); + + return sendCheckReply(sendbuff, ok_reply); +} + + +uint8_t Adafruit_FONA::getCallStatus(void) { + uint16_t phoneStatus; + + if (! sendParseReply(F("AT+CPAS"), F("+CPAS: "), &phoneStatus)) + return FONA_CALL_FAILED; // 1, since 0 is actually a known, good reply + + return phoneStatus; // 0 ready, 2 unkown, 3 ringing, 4 call in progress +} + +boolean Adafruit_FONA::hangUp(void) { + return sendCheckReply(F("ATH0"), ok_reply); +} + +boolean Adafruit_FONA_3G::hangUp(void) { + getReply(F("ATH")); + + return (prog_char_strstr(replybuffer, (prog_char *)F("VOICE CALL: END")) != 0); +} + +boolean Adafruit_FONA::pickUp(void) { + return sendCheckReply(F("ATA"), ok_reply); +} + +boolean Adafruit_FONA_3G::pickUp(void) { + return sendCheckReply(F("ATA"), F("VOICE CALL: BEGIN")); +} + + +void Adafruit_FONA::onIncomingCall() { + + DEBUG_PRINT(F("> ")); DEBUG_PRINTLN(F("Incoming call...")); + + Adafruit_FONA::_incomingCall = true; +} + +boolean Adafruit_FONA::_incomingCall = false; + +boolean Adafruit_FONA::callerIdNotification(boolean enable, uint8_t interrupt) { + if(enable){ + attachInterrupt(interrupt, onIncomingCall, FALLING); + return sendCheckReply(F("AT+CLIP=1"), ok_reply); + } + + detachInterrupt(interrupt); + return sendCheckReply(F("AT+CLIP=0"), ok_reply); +} + +boolean Adafruit_FONA::incomingCallNumber(char* phonenum) { + //+CLIP: "",145,"",0,"",0 + if(!Adafruit_FONA::_incomingCall) + return false; + + readline(); + while(!prog_char_strcmp(replybuffer, (prog_char*)F("RING")) == 0) { + flushInput(); + readline(); + } + + readline(); //reads incoming phone number line + + parseReply(F("+CLIP: \""), phonenum, '"'); + + + DEBUG_PRINT(F("Phone Number: ")); + DEBUG_PRINTLN(replybuffer); + + + Adafruit_FONA::_incomingCall = false; + return true; +} + +/********* SMS **********************************************************/ + +uint8_t Adafruit_FONA::getSMSInterrupt(void) { + uint16_t reply; + + if (! sendParseReply(F("AT+CFGRI?"), F("+CFGRI: "), &reply) ) return 0; + + return reply; +} + +boolean Adafruit_FONA::setSMSInterrupt(uint8_t i) { + return sendCheckReply(F("AT+CFGRI="), i, ok_reply); +} + +int8_t Adafruit_FONA::getNumSMS(void) { + uint16_t numsms; + + // get into text mode + if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return -1; + + // ask how many sms are stored + if (sendParseReply(F("AT+CPMS?"), F("\"SM\","), &numsms)) + return numsms; + if (sendParseReply(F("AT+CPMS?"), F("\"SM_P\","), &numsms)) + return numsms; + return -1; +} + +// Reading SMS's is a bit involved so we don't use helpers that may cause delays or debug +// printouts! +boolean Adafruit_FONA::readSMS(uint8_t i, char *smsbuff, + uint16_t maxlen, uint16_t *readlen) { + // text mode + if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return false; + + // show all text mode parameters + if (! sendCheckReply(F("AT+CSDH=1"), ok_reply)) return false; + + // parse out the SMS len + uint16_t thesmslen = 0; + + + DEBUG_PRINT(F("AT+CMGR=")); + DEBUG_PRINTLN(i); + + + //getReply(F("AT+CMGR="), i, 1000); // do not print debug! + mySerial->print(F("AT+CMGR=")); + mySerial->println(i); + readline(1000); // timeout + + //DEBUG_PRINT(F("Reply: ")); DEBUG_PRINTLN(replybuffer); + // parse it out... + + + DEBUG_PRINTLN(replybuffer); + + + if (! parseReply(F("+CMGR:"), &thesmslen, ',', 11)) { + *readlen = 0; + return false; + } + + readRaw(thesmslen); + + flushInput(); + + uint16_t thelen = min(maxlen, strlen(replybuffer)); + strncpy(smsbuff, replybuffer, thelen); + smsbuff[thelen] = 0; // end the string + + + DEBUG_PRINTLN(replybuffer); + + *readlen = thelen; + return true; +} + +// Retrieve the sender of the specified SMS message and copy it as a string to +// the sender buffer. Up to senderlen characters of the sender will be copied +// and a null terminator will be added if less than senderlen charactesr are +// copied to the result. Returns true if a result was successfully retrieved, +// otherwise false. +boolean Adafruit_FONA::getSMSSender(uint8_t i, char *sender, int senderlen) { + // Ensure text mode and all text mode parameters are sent. + if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return false; + if (! sendCheckReply(F("AT+CSDH=1"), ok_reply)) return false; + + + DEBUG_PRINT(F("AT+CMGR=")); + DEBUG_PRINTLN(i); + + + // Send command to retrieve SMS message and parse a line of response. + mySerial->print(F("AT+CMGR=")); + mySerial->println(i); + readline(1000); + + + DEBUG_PRINTLN(replybuffer); + + + // Parse the second field in the response. + boolean result = parseReplyQuoted(F("+CMGR:"), sender, senderlen, ',', 1); + // Drop any remaining data from the response. + flushInput(); + return result; +} + +boolean Adafruit_FONA::sendSMS(char *smsaddr, char *smsmsg) { + if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return -1; + + char sendcmd[30] = "AT+CMGS=\""; + strncpy(sendcmd+9, smsaddr, 30-9-2); // 9 bytes beginning, 2 bytes for close quote + null + sendcmd[strlen(sendcmd)] = '\"'; + + if (! sendCheckReply(sendcmd, F("> "))) return false; + + DEBUG_PRINT(F("> ")); DEBUG_PRINTLN(smsmsg); + + mySerial->println(smsmsg); + mySerial->println(); + mySerial->write(0x1A); + + DEBUG_PRINTLN("^Z"); + + if ( (_type == FONA3G_A) || (_type == FONA3G_E) ) { + // Eat two sets of CRLF + readline(200); + //DEBUG_PRINT("Line 1: "); DEBUG_PRINTLN(strlen(replybuffer)); + readline(200); + //DEBUG_PRINT("Line 2: "); DEBUG_PRINTLN(strlen(replybuffer)); + } + readline(10000); // read the +CMGS reply, wait up to 10 seconds!!! + //DEBUG_PRINT("Line 3: "); DEBUG_PRINTLN(strlen(replybuffer)); + if (strstr(replybuffer, "+CMGS") == 0) { + return false; + } + readline(1000); // read OK + //DEBUG_PRINT("* "); DEBUG_PRINTLN(replybuffer); + + if (strcmp(replybuffer, "OK") != 0) { + return false; + } + + return true; +} + + +boolean Adafruit_FONA::deleteSMS(uint8_t i) { + if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return -1; + // read an sms + char sendbuff[12] = "AT+CMGD=000"; + sendbuff[8] = (i / 100) + '0'; + i %= 100; + sendbuff[9] = (i / 10) + '0'; + i %= 10; + sendbuff[10] = i + '0'; + + return sendCheckReply(sendbuff, ok_reply, 2000); +} + +/********* USSD *********************************************************/ + +boolean Adafruit_FONA::sendUSSD(char *ussdmsg, char *ussdbuff, uint16_t maxlen, uint16_t *readlen) { + if (! sendCheckReply(F("AT+CUSD=1"), ok_reply)) return -1; + + char sendcmd[30] = "AT+CUSD=1,\""; + strncpy(sendcmd+11, ussdmsg, 30-11-2); // 11 bytes beginning, 2 bytes for close quote + null + sendcmd[strlen(sendcmd)] = '\"'; + + if (! sendCheckReply(sendcmd, ok_reply)) { + *readlen = 0; + return false; + } else { + readline(10000); // read the +CUSD reply, wait up to 10 seconds!!! + //DEBUG_PRINT("* "); DEBUG_PRINTLN(replybuffer); + char *p = prog_char_strstr(replybuffer, PSTR("+CUSD: ")); + if (p == 0) { + *readlen = 0; + return false; + } + p+=7; //+CUSD + // Find " to get start of ussd message. + p = strchr(p, '\"'); + if (p == 0) { + *readlen = 0; + return false; + } + p+=1; //" + // Find " to get end of ussd message. + char *strend = strchr(p, '\"'); + + uint16_t lentocopy = min(maxlen-1, strend - p); + strncpy(ussdbuff, p, lentocopy+1); + ussdbuff[lentocopy] = 0; + *readlen = lentocopy; + } + return true; +} + + +/********* TIME **********************************************************/ + +boolean Adafruit_FONA::enableNetworkTimeSync(boolean onoff) { + if (onoff) { + if (! sendCheckReply(F("AT+CLTS=1"), ok_reply)) + return false; + } else { + if (! sendCheckReply(F("AT+CLTS=0"), ok_reply)) + return false; + } + + flushInput(); // eat any 'Unsolicted Result Code' + + return true; +} + +boolean Adafruit_FONA::enableNTPTimeSync(boolean onoff, FONAFlashStringPtr ntpserver) { + if (onoff) { + if (! sendCheckReply(F("AT+CNTPCID=1"), ok_reply)) + return false; + + mySerial->print(F("AT+CNTP=\"")); + if (ntpserver != 0) { + mySerial->print(ntpserver); + } else { + mySerial->print(F("pool.ntp.org")); + } + mySerial->println(F("\",0")); + readline(FONA_DEFAULT_TIMEOUT_MS); + if (strcmp(replybuffer, "OK") != 0) + return false; + + if (! sendCheckReply(F("AT+CNTP"), ok_reply, 10000)) + return false; + + uint16_t status; + readline(10000); + if (! parseReply(F("+CNTP:"), &status)) + return false; + } else { + if (! sendCheckReply(F("AT+CNTPCID=0"), ok_reply)) + return false; + } + + return true; +} + +boolean Adafruit_FONA::getTime(char *buff, uint16_t maxlen) { + getReply(F("AT+CCLK?"), (uint16_t) 10000); + if (strncmp(replybuffer, "+CCLK: ", 7) != 0) + return false; + + char *p = replybuffer+7; + uint16_t lentocopy = min(maxlen-1, strlen(p)); + strncpy(buff, p, lentocopy+1); + buff[lentocopy] = 0; + + readline(); // eat OK + + return true; +} + +/********* GPS **********************************************************/ + + +boolean Adafruit_FONA::enableGPS(boolean onoff) { + uint16_t state; + + // first check if its already on or off + + if (_type == FONA808_V2) { + if (! sendParseReply(F("AT+CGNSPWR?"), F("+CGNSPWR: "), &state) ) + return false; + } else { + if (! sendParseReply(F("AT+CGPSPWR?"), F("+CGPSPWR: "), &state)) + return false; + } + + if (onoff && !state) { + if (_type == FONA808_V2) { + if (! sendCheckReply(F("AT+CGNSPWR=1"), ok_reply)) // try GNS command + return false; + } else { + if (! sendCheckReply(F("AT+CGPSPWR=1"), ok_reply)) + return false; + } + } else if (!onoff && state) { + if (_type == FONA808_V2) { + if (! sendCheckReply(F("AT+CGNSPWR=0"), ok_reply)) // try GNS command + return false; + } else { + if (! sendCheckReply(F("AT+CGPSPWR=0"), ok_reply)) + return false; + } + } + return true; +} + + + +boolean Adafruit_FONA_3G::enableGPS(boolean onoff) { + uint16_t state; + + // first check if its already on or off + if (! Adafruit_FONA::sendParseReply(F("AT+CGPS?"), F("+CGPS: "), &state) ) + return false; + + if (onoff && !state) { + if (! sendCheckReply(F("AT+CGPS=1"), ok_reply)) + return false; + } else if (!onoff && state) { + if (! sendCheckReply(F("AT+CGPS=0"), ok_reply)) + return false; + // this takes a little time + readline(2000); // eat '+CGPS: 0' + } + return true; +} + +int8_t Adafruit_FONA::GPSstatus(void) { + if (_type == FONA808_V2) { + // 808 V2 uses GNS commands and doesn't have an explicit 2D/3D fix status. + // Instead just look for a fix and if found assume it's a 3D fix. + getReply(F("AT+CGNSINF")); + char *p = prog_char_strstr(replybuffer, (prog_char*)F("+CGNSINF: ")); + if (p == 0) return -1; + p+=12; // Skip to second value, fix status. + readline(); // eat 'OK' + //DEBUG_PRINTLN(p); + // Assume if the fix status is '1' then we have a 3D fix, otherwise no fix. + if (p[0] == '1') return 3; + else return 0; + } + if (_type == FONA3G_A || _type == FONA3G_E) { + // FONA 3G doesn't have an explicit 2D/3D fix status. + // Instead just look for a fix and if found assume it's a 3D fix. + getReply(F("AT+CGPSINFO")); + char *p = prog_char_strstr(replybuffer, (prog_char*)F("+CGPSINFO:")); + if (p == 0) return -1; + if (p[10] != ',') return 3; // if you get anything, its 3D fix + return 0; + } + else { + // 808 V1 looks for specific 2D or 3D fix state. + getReply(F("AT+CGPSSTATUS?")); + char *p = prog_char_strstr(replybuffer, (prog_char*)F("SSTATUS: Location ")); + if (p == 0) return -1; + p+=18; + readline(); // eat 'OK' + //DEBUG_PRINTLN(p); + if (p[0] == 'U') return 0; + if (p[0] == 'N') return 1; + if (p[0] == '2') return 2; + if (p[0] == '3') return 3; + } + // else + return 0; +} + +uint8_t Adafruit_FONA::getGPS(uint8_t arg, char *buffer, uint8_t maxbuff) { + int32_t x = arg; + + if ( (_type == FONA3G_A) || (_type == FONA3G_E) ) { + getReply(F("AT+CGPSINFO")); + } else if (_type == FONA808_V1) { + getReply(F("AT+CGPSINF="), x); + } else { + getReply(F("AT+CGNSINF")); + } + + char *p = prog_char_strstr(replybuffer, (prog_char*)F("SINF")); + if (p == 0) { + buffer[0] = 0; + return 0; + } + + p+=6; + + uint8_t len = max(maxbuff-1, strlen(p)); + strncpy(buffer, p, len); + buffer[len] = 0; + + readline(); // eat 'OK' + return len; +} + +boolean Adafruit_FONA::getGPS(float *lat, float *lon, float *speed_kph, float *heading, float *altitude) { + + char gpsbuffer[120]; + + // we need at least a 2D fix + if (GPSstatus() < 2) + return false; + + // grab the mode 2^5 gps csv from the sim808 + uint8_t res_len = getGPS(32, gpsbuffer, 120); + + // make sure we have a response + if (res_len == 0) + return false; + + if (_type == FONA3G_A || _type == FONA3G_E) { + // Parse 3G respose + // +CGPSINFO:4043.000000,N,07400.000000,W,151015,203802.1,-12.0,0.0,0 + // skip beginning + char *tok; + + // grab the latitude + char *latp = strtok(gpsbuffer, ","); + if (! latp) return false; + + // grab latitude direction + char *latdir = strtok(NULL, ","); + if (! latdir) return false; + + // grab longitude + char *longp = strtok(NULL, ","); + if (! longp) return false; + + // grab longitude direction + char *longdir = strtok(NULL, ","); + if (! longdir) return false; + + // skip date & time + tok = strtok(NULL, ","); + tok = strtok(NULL, ","); + + // only grab altitude if needed + if (altitude != NULL) { + // grab altitude + char *altp = strtok(NULL, ","); + if (! altp) return false; + *altitude = atof(altp); + } + + // only grab speed if needed + if (speed_kph != NULL) { + // grab the speed in km/h + char *speedp = strtok(NULL, ","); + if (! speedp) return false; + + *speed_kph = atof(speedp); + } + + // only grab heading if needed + if (heading != NULL) { + + // grab the speed in knots + char *coursep = strtok(NULL, ","); + if (! coursep) return false; + + *heading = atof(coursep); + } + + double latitude = atof(latp); + double longitude = atof(longp); + + // convert latitude from minutes to decimal + float degrees = floor(latitude / 100); + double minutes = latitude - (100 * degrees); + minutes /= 60; + degrees += minutes; + + // turn direction into + or - + if (latdir[0] == 'S') degrees *= -1; + + *lat = degrees; + + // convert longitude from minutes to decimal + degrees = floor(longitude / 100); + minutes = longitude - (100 * degrees); + minutes /= 60; + degrees += minutes; + + // turn direction into + or - + if (longdir[0] == 'W') degrees *= -1; + + *lon = degrees; + + } else if (_type == FONA808_V2) { + // Parse 808 V2 response. See table 2-3 from here for format: + // http://www.adafruit.com/datasheets/SIM800%20Series_GNSS_Application%20Note%20V1.00.pdf + + // skip GPS run status + char *tok = strtok(gpsbuffer, ","); + if (! tok) return false; + + // skip fix status + tok = strtok(NULL, ","); + if (! tok) return false; + + // skip date + tok = strtok(NULL, ","); + if (! tok) return false; + + // grab the latitude + char *latp = strtok(NULL, ","); + if (! latp) return false; + + // grab longitude + char *longp = strtok(NULL, ","); + if (! longp) return false; + + *lat = atof(latp); + *lon = atof(longp); + + // only grab altitude if needed + if (altitude != NULL) { + // grab altitude + char *altp = strtok(NULL, ","); + if (! altp) return false; + + *altitude = atof(altp); + } + + // only grab speed if needed + if (speed_kph != NULL) { + // grab the speed in km/h + char *speedp = strtok(NULL, ","); + if (! speedp) return false; + + *speed_kph = atof(speedp); + } + + // only grab heading if needed + if (heading != NULL) { + + // grab the speed in knots + char *coursep = strtok(NULL, ","); + if (! coursep) return false; + + *heading = atof(coursep); + } + } + else { + // Parse 808 V1 response. + + // skip mode + char *tok = strtok(gpsbuffer, ","); + if (! tok) return false; + + // skip date + tok = strtok(NULL, ","); + if (! tok) return false; + + // skip fix + tok = strtok(NULL, ","); + if (! tok) return false; + + // grab the latitude + char *latp = strtok(NULL, ","); + if (! latp) return false; + + // grab latitude direction + char *latdir = strtok(NULL, ","); + if (! latdir) return false; + + // grab longitude + char *longp = strtok(NULL, ","); + if (! longp) return false; + + // grab longitude direction + char *longdir = strtok(NULL, ","); + if (! longdir) return false; + + double latitude = atof(latp); + double longitude = atof(longp); + + // convert latitude from minutes to decimal + float degrees = floor(latitude / 100); + double minutes = latitude - (100 * degrees); + minutes /= 60; + degrees += minutes; + + // turn direction into + or - + if (latdir[0] == 'S') degrees *= -1; + + *lat = degrees; + + // convert longitude from minutes to decimal + degrees = floor(longitude / 100); + minutes = longitude - (100 * degrees); + minutes /= 60; + degrees += minutes; + + // turn direction into + or - + if (longdir[0] == 'W') degrees *= -1; + + *lon = degrees; + + // only grab speed if needed + if (speed_kph != NULL) { + + // grab the speed in knots + char *speedp = strtok(NULL, ","); + if (! speedp) return false; + + // convert to kph + *speed_kph = atof(speedp) * 1.852; + + } + + // only grab heading if needed + if (heading != NULL) { + + // grab the speed in knots + char *coursep = strtok(NULL, ","); + if (! coursep) return false; + + *heading = atof(coursep); + + } + + // no need to continue + if (altitude == NULL) + return true; + + // we need at least a 3D fix for altitude + if (GPSstatus() < 3) + return false; + + // grab the mode 0 gps csv from the sim808 + res_len = getGPS(0, gpsbuffer, 120); + + // make sure we have a response + if (res_len == 0) + return false; + + // skip mode + tok = strtok(gpsbuffer, ","); + if (! tok) return false; + + // skip lat + tok = strtok(NULL, ","); + if (! tok) return false; + + // skip long + tok = strtok(NULL, ","); + if (! tok) return false; + + // grab altitude + char *altp = strtok(NULL, ","); + if (! altp) return false; + + *altitude = atof(altp); + } + + return true; + +} + +boolean Adafruit_FONA::enableGPSNMEA(uint8_t i) { + + char sendbuff[15] = "AT+CGPSOUT=000"; + sendbuff[11] = (i / 100) + '0'; + i %= 100; + sendbuff[12] = (i / 10) + '0'; + i %= 10; + sendbuff[13] = i + '0'; + + if (_type == FONA808_V2) { + if (i) + return sendCheckReply(F("AT+CGNSTST=1"), ok_reply); + else + return sendCheckReply(F("AT+CGNSTST=0"), ok_reply); + } else { + return sendCheckReply(sendbuff, ok_reply, 2000); + } +} + + +/********* GPRS **********************************************************/ + + +boolean Adafruit_FONA::enableGPRS(boolean onoff) { + + if (onoff) { + // disconnect all sockets + sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 20000); + + if (! sendCheckReply(F("AT+CGATT=1"), ok_reply, 10000)) + return false; + + // set bearer profile! connection type GPRS + if (! sendCheckReply(F("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\""), + ok_reply, 10000)) + return false; + + // set bearer profile access point name + if (apn) { + // Send command AT+SAPBR=3,1,"APN","" where is the configured APN value. + if (! sendCheckReplyQuoted(F("AT+SAPBR=3,1,\"APN\","), apn, ok_reply, 10000)) + return false; + + // send AT+CSTT,"apn","user","pass" + flushInput(); + + mySerial->print(F("AT+CSTT=\"")); + mySerial->print(apn); + if (apnusername) { + mySerial->print("\",\""); + mySerial->print(apnusername); + } + if (apnpassword) { + mySerial->print("\",\""); + mySerial->print(apnpassword); + } + mySerial->println("\""); + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(F("AT+CSTT=\"")); + DEBUG_PRINT(apn); + + if (apnusername) { + DEBUG_PRINT("\",\""); + DEBUG_PRINT(apnusername); + } + if (apnpassword) { + DEBUG_PRINT("\",\""); + DEBUG_PRINT(apnpassword); + } + DEBUG_PRINTLN("\""); + + if (! expectReply(ok_reply)) return false; + + // set username/password + if (apnusername) { + // Send command AT+SAPBR=3,1,"USER","" where is the configured APN username. + if (! sendCheckReplyQuoted(F("AT+SAPBR=3,1,\"USER\","), apnusername, ok_reply, 10000)) + return false; + } + if (apnpassword) { + // Send command AT+SAPBR=3,1,"PWD","" where is the configured APN password. + if (! sendCheckReplyQuoted(F("AT+SAPBR=3,1,\"PWD\","), apnpassword, ok_reply, 10000)) + return false; + } + } + + // open GPRS context + if (! sendCheckReply(F("AT+SAPBR=1,1"), ok_reply, 30000)) + return false; + + // bring up wireless connection + if (! sendCheckReply(F("AT+CIICR"), ok_reply, 10000)) + return false; + + } else { + // disconnect all sockets + if (! sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 20000)) + return false; + + // close GPRS context + if (! sendCheckReply(F("AT+SAPBR=0,1"), ok_reply, 10000)) + return false; + + if (! sendCheckReply(F("AT+CGATT=0"), ok_reply, 10000)) + return false; + + } + return true; +} + +boolean Adafruit_FONA_3G::enableGPRS(boolean onoff) { + + if (onoff) { + // disconnect all sockets + //sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 5000); + + if (! sendCheckReply(F("AT+CGATT=1"), ok_reply, 10000)) + return false; + + + // set bearer profile access point name + if (apn) { + // Send command AT+CGSOCKCONT=1,"IP","" where is the configured APN name. + if (! sendCheckReplyQuoted(F("AT+CGSOCKCONT=1,\"IP\","), apn, ok_reply, 10000)) + return false; + + // set username/password + if (apnusername) { + char authstring[100] = "AT+CGAUTH=1,1,\""; + char *strp = authstring + strlen(authstring); + prog_char_strcpy(strp, (prog_char *)apnusername); + strp+=prog_char_strlen((prog_char *)apnusername); + strp[0] = '\"'; + strp++; + strp[0] = 0; + + if (apnpassword) { + strp[0] = ','; strp++; + strp[0] = '\"'; strp++; + prog_char_strcpy(strp, (prog_char *)apnpassword); + strp+=prog_char_strlen((prog_char *)apnpassword); + strp[0] = '\"'; + strp++; + strp[0] = 0; + } + + if (! sendCheckReply(authstring, ok_reply, 10000)) + return false; + } + } + + // connect in transparent + if (! sendCheckReply(F("AT+CIPMODE=1"), ok_reply, 10000)) + return false; + // open network (?) + if (! sendCheckReply(F("AT+NETOPEN=,,1"), F("Network opened"), 10000)) + return false; + + readline(); // eat 'OK' + } else { + // close GPRS context + if (! sendCheckReply(F("AT+NETCLOSE"), F("Network closed"), 10000)) + return false; + + readline(); // eat 'OK' + } + + return true; +} + +uint8_t Adafruit_FONA::GPRSstate(void) { + uint16_t state; + + if (! sendParseReply(F("AT+CGATT?"), F("+CGATT: "), &state) ) + return -1; + + return state; +} + +void Adafruit_FONA::setGPRSNetworkSettings(FONAFlashStringPtr apn, + FONAFlashStringPtr username, FONAFlashStringPtr password) { + this->apn = apn; + this->apnusername = username; + this->apnpassword = password; +} + +boolean Adafruit_FONA::getGSMLoc(uint16_t *errorcode, char *buff, uint16_t maxlen) { + + getReply(F("AT+CIPGSMLOC=1,1"), (uint16_t)10000); + + if (! parseReply(F("+CIPGSMLOC: "), errorcode)) + return false; + + char *p = replybuffer+14; + uint16_t lentocopy = min(maxlen-1, strlen(p)); + strncpy(buff, p, lentocopy+1); + + readline(); // eat OK + + return true; +} + +boolean Adafruit_FONA::getGSMLoc(float *lat, float *lon) { + + uint16_t returncode; + char gpsbuffer[120]; + + // make sure we could get a response + if (! getGSMLoc(&returncode, gpsbuffer, 120)) + return false; + + // make sure we have a valid return code + if (returncode != 0) + return false; + + // +CIPGSMLOC: 0,-74.007729,40.730160,2015/10/15,19:24:55 + // tokenize the gps buffer to locate the lat & long + char *longp = strtok(gpsbuffer, ","); + if (! longp) return false; + + char *latp = strtok(NULL, ","); + if (! latp) return false; + + *lat = atof(latp); + *lon = atof(longp); + + return true; + +} +/********* TCP FUNCTIONS ************************************/ + + +boolean Adafruit_FONA::TCPconnect(char *server, uint16_t port) { + flushInput(); + + // close all old connections + if (! sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 20000) ) return false; + + // single connection at a time + if (! sendCheckReply(F("AT+CIPMUX=0"), ok_reply) ) return false; + + // manually read data + if (! sendCheckReply(F("AT+CIPRXGET=1"), ok_reply) ) return false; + + + DEBUG_PRINT(F("AT+CIPSTART=\"TCP\",\"")); + DEBUG_PRINT(server); + DEBUG_PRINT(F("\",\"")); + DEBUG_PRINT(port); + DEBUG_PRINTLN(F("\"")); + + + mySerial->print(F("AT+CIPSTART=\"TCP\",\"")); + mySerial->print(server); + mySerial->print(F("\",\"")); + mySerial->print(port); + mySerial->println(F("\"")); + + if (! expectReply(ok_reply)) return false; + if (! expectReply(F("CONNECT OK"))) return false; + + // looks like it was a success (?) + return true; +} + +boolean Adafruit_FONA::TCPclose(void) { + return sendCheckReply(F("AT+CIPCLOSE"), ok_reply); +} + +boolean Adafruit_FONA::TCPconnected(void) { + if (! sendCheckReply(F("AT+CIPSTATUS"), ok_reply, 100) ) return false; + readline(100); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return (strcmp(replybuffer, "STATE: CONNECT OK") == 0); +} + +boolean Adafruit_FONA::TCPsend(char *packet, uint8_t len) { + + DEBUG_PRINT(F("AT+CIPSEND=")); + DEBUG_PRINTLN(len); +#ifdef ADAFRUIT_FONA_DEBUG + for (uint16_t i=0; iprint(F("AT+CIPSEND=")); + mySerial->println(len); + readline(); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + if (replybuffer[0] != '>') return false; + + mySerial->write(packet, len); + readline(3000); // wait up to 3 seconds to send the data + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + + return (strcmp(replybuffer, "SEND OK") == 0); +} + +uint16_t Adafruit_FONA::TCPavailable(void) { + uint16_t avail; + + if (! sendParseReply(F("AT+CIPRXGET=4"), F("+CIPRXGET: 4,"), &avail, ',', 0) ) return false; + + + DEBUG_PRINT (avail); DEBUG_PRINTLN(F(" bytes available")); + + + return avail; +} + + +uint16_t Adafruit_FONA::TCPread(uint8_t *buff, uint8_t len) { + uint16_t avail; + + mySerial->print(F("AT+CIPRXGET=2,")); + mySerial->println(len); + readline(); + if (! parseReply(F("+CIPRXGET: 2,"), &avail, ',', 0)) return false; + + readRaw(avail); + +#ifdef ADAFRUIT_FONA_DEBUG + DEBUG_PRINT (avail); DEBUG_PRINTLN(F(" bytes read")); + for (uint8_t i=0;i ")); + DEBUG_PRINT(F("AT+HTTPPARA=\"")); + DEBUG_PRINT(parameter); + DEBUG_PRINTLN('"'); + + + mySerial->print(F("AT+HTTPPARA=\"")); + mySerial->print(parameter); + if (quoted) + mySerial->print(F("\",\"")); + else + mySerial->print(F("\",")); +} + +boolean Adafruit_FONA::HTTP_para_end(boolean quoted) { + if (quoted) + mySerial->println('"'); + else + mySerial->println(); + + return expectReply(ok_reply); +} + +boolean Adafruit_FONA::HTTP_para(FONAFlashStringPtr parameter, + const char *value) { + HTTP_para_start(parameter, true); + mySerial->print(value); + return HTTP_para_end(true); +} + +boolean Adafruit_FONA::HTTP_para(FONAFlashStringPtr parameter, + FONAFlashStringPtr value) { + HTTP_para_start(parameter, true); + mySerial->print(value); + return HTTP_para_end(true); +} + +boolean Adafruit_FONA::HTTP_para(FONAFlashStringPtr parameter, + int32_t value) { + HTTP_para_start(parameter, false); + mySerial->print(value); + return HTTP_para_end(false); +} + +boolean Adafruit_FONA::HTTP_data(uint32_t size, uint32_t maxTime) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); + DEBUG_PRINT(F("AT+HTTPDATA=")); + DEBUG_PRINT(size); + DEBUG_PRINT(','); + DEBUG_PRINTLN(maxTime); + + + mySerial->print(F("AT+HTTPDATA=")); + mySerial->print(size); + mySerial->print(","); + mySerial->println(maxTime); + + return expectReply(F("DOWNLOAD")); +} + +boolean Adafruit_FONA::HTTP_action(uint8_t method, uint16_t *status, + uint16_t *datalen, int32_t timeout) { + // Send request. + if (! sendCheckReply(F("AT+HTTPACTION="), method, ok_reply)) + return false; + + // Parse response status and size. + readline(timeout); + if (! parseReply(F("+HTTPACTION:"), status, ',', 1)) + return false; + if (! parseReply(F("+HTTPACTION:"), datalen, ',', 2)) + return false; + + return true; +} + +boolean Adafruit_FONA::HTTP_readall(uint16_t *datalen) { + getReply(F("AT+HTTPREAD")); + if (! parseReply(F("+HTTPREAD:"), datalen, ',', 0)) + return false; + + return true; +} + +boolean Adafruit_FONA::HTTP_ssl(boolean onoff) { + return sendCheckReply(F("AT+HTTPSSL="), onoff ? 1 : 0, ok_reply); +} + +/********* HTTP HIGH LEVEL FUNCTIONS ***************************/ + +boolean Adafruit_FONA::HTTP_GET_start(char *url, + uint16_t *status, uint16_t *datalen){ + if (! HTTP_setup(url)) + return false; + + // HTTP GET + if (! HTTP_action(FONA_HTTP_GET, status, datalen, 30000)) + return false; + + DEBUG_PRINT(F("Status: ")); DEBUG_PRINTLN(*status); + DEBUG_PRINT(F("Len: ")); DEBUG_PRINTLN(*datalen); + + // HTTP response data + if (! HTTP_readall(datalen)) + return false; + + return true; +} + +/* +boolean Adafruit_FONA_3G::HTTP_GET_start(char *ipaddr, char *path, uint16_t port + uint16_t *status, uint16_t *datalen){ + char send[100] = "AT+CHTTPACT=\""; + char *sendp = send + strlen(send); + memset(sendp, 0, 100 - strlen(send)); + + strcpy(sendp, ipaddr); + sendp+=strlen(ipaddr); + sendp[0] = '\"'; + sendp++; + sendp[0] = ','; + itoa(sendp, port); + getReply(send, 500); + + return; + + if (! HTTP_setup(url)) + + return false; + + // HTTP GET + if (! HTTP_action(FONA_HTTP_GET, status, datalen)) + return false; + + DEBUG_PRINT("Status: "); DEBUG_PRINTLN(*status); + DEBUG_PRINT("Len: "); DEBUG_PRINTLN(*datalen); + + // HTTP response data + if (! HTTP_readall(datalen)) + return false; + + return true; +} +*/ + +void Adafruit_FONA::HTTP_GET_end(void) { + HTTP_term(); +} + +boolean Adafruit_FONA::HTTP_POST_start(char *url, + FONAFlashStringPtr contenttype, + const uint8_t *postdata, uint16_t postdatalen, + uint16_t *status, uint16_t *datalen){ + if (! HTTP_setup(url)) + return false; + + if (! HTTP_para(F("CONTENT"), contenttype)) { + return false; + } + + // HTTP POST data + if (! HTTP_data(postdatalen, 10000)) + return false; + mySerial->write(postdata, postdatalen); + if (! expectReply(ok_reply)) + return false; + + // HTTP POST + if (! HTTP_action(FONA_HTTP_POST, status, datalen)) + return false; + + DEBUG_PRINT(F("Status: ")); DEBUG_PRINTLN(*status); + DEBUG_PRINT(F("Len: ")); DEBUG_PRINTLN(*datalen); + + // HTTP response data + if (! HTTP_readall(datalen)) + return false; + + return true; +} + +void Adafruit_FONA::HTTP_POST_end(void) { + HTTP_term(); +} + +void Adafruit_FONA::setUserAgent(FONAFlashStringPtr useragent) { + this->useragent = useragent; +} + +void Adafruit_FONA::setHTTPSRedirect(boolean onoff) { + httpsredirect = onoff; +} + +/********* HTTP HELPERS ****************************************/ + +boolean Adafruit_FONA::HTTP_setup(char *url) { + // Handle any pending + HTTP_term(); + + // Initialize and set parameters + if (! HTTP_init()) + return false; + if (! HTTP_para(F("CID"), 1)) + return false; + if (! HTTP_para(F("UA"), useragent)) + return false; + if (! HTTP_para(F("URL"), url)) + return false; + + // HTTPS redirect + if (httpsredirect) { + if (! HTTP_para(F("REDIR"),1)) + return false; + + if (! HTTP_ssl(true)) + return false; + } + + return true; +} + +/********* HELPERS *********************************************/ + +boolean Adafruit_FONA::expectReply(FONAFlashStringPtr reply, + uint16_t timeout) { + readline(timeout); + + DEBUG_PRINT(F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return (prog_char_strcmp(replybuffer, (prog_char*)reply) == 0); +} + +/********* LOW LEVEL *******************************************/ + +inline int Adafruit_FONA::available(void) { + return mySerial->available(); +} + +inline size_t Adafruit_FONA::write(uint8_t x) { + return mySerial->write(x); +} + +inline int Adafruit_FONA::read(void) { + return mySerial->read(); +} + +inline int Adafruit_FONA::peek(void) { + return mySerial->peek(); +} + +inline void Adafruit_FONA::flush() { + mySerial->flush(); +} + +void Adafruit_FONA::flushInput() { + // Read all available serial input to flush pending data. + uint16_t timeoutloop = 0; + while (timeoutloop++ < 40) { + while(available()) { + read(); + timeoutloop = 0; // If char was received reset the timer + } + delay(1); + } +} + +uint16_t Adafruit_FONA::readRaw(uint16_t b) { + uint16_t idx = 0; + + while (b && (idx < sizeof(replybuffer)-1)) { + if (mySerial->available()) { + replybuffer[idx] = mySerial->read(); + idx++; + b--; + } + } + replybuffer[idx] = 0; + + return idx; +} + +uint8_t Adafruit_FONA::readline(uint16_t timeout, boolean multiline) { + uint16_t replyidx = 0; + + while (timeout--) { + if (replyidx >= 254) { + //DEBUG_PRINTLN(F("SPACE")); + break; + } + + while(mySerial->available()) { + char c = mySerial->read(); + if (c == '\r') continue; + if (c == 0xA) { + if (replyidx == 0) // the first 0x0A is ignored + continue; + + if (!multiline) { + timeout = 0; // the second 0x0A is the end of the line + break; + } + } + replybuffer[replyidx] = c; + //DEBUG_PRINT(c, HEX); DEBUG_PRINT("#"); DEBUG_PRINTLN(c); + replyidx++; + } + + if (timeout == 0) { + //DEBUG_PRINTLN(F("TIMEOUT")); + break; + } + delay(1); + } + replybuffer[replyidx] = 0; // null term + return replyidx; +} + +uint8_t Adafruit_FONA::getReply(char *send, uint16_t timeout) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN(send); + + + mySerial->println(send); + + uint8_t l = readline(timeout); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return l; +} + +uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr send, uint16_t timeout) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN(send); + + + mySerial->println(send); + + uint8_t l = readline(timeout); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return l; +} + +// Send prefix, suffix, and newline. Return response (and also set replybuffer with response). +uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr prefix, char *suffix, uint16_t timeout) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); DEBUG_PRINTLN(suffix); + + + mySerial->print(prefix); + mySerial->println(suffix); + + uint8_t l = readline(timeout); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return l; +} + +// Send prefix, suffix, and newline. Return response (and also set replybuffer with response). +uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr prefix, int32_t suffix, uint16_t timeout) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); DEBUG_PRINTLN(suffix, DEC); + + + mySerial->print(prefix); + mySerial->println(suffix, DEC); + + uint8_t l = readline(timeout); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return l; +} + +// Send prefix, suffix, suffix2, and newline. Return response (and also set replybuffer with response). +uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr prefix, int32_t suffix1, int32_t suffix2, uint16_t timeout) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); + DEBUG_PRINT(suffix1, DEC); DEBUG_PRINT(','); DEBUG_PRINTLN(suffix2, DEC); + + + mySerial->print(prefix); + mySerial->print(suffix1); + mySerial->print(','); + mySerial->println(suffix2, DEC); + + uint8_t l = readline(timeout); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return l; +} + +// Send prefix, ", suffix, ", and newline. Return response (and also set replybuffer with response). +uint8_t Adafruit_FONA::getReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, uint16_t timeout) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); + DEBUG_PRINT('"'); DEBUG_PRINT(suffix); DEBUG_PRINTLN('"'); + + + mySerial->print(prefix); + mySerial->print('"'); + mySerial->print(suffix); + mySerial->println('"'); + + uint8_t l = readline(timeout); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return l; +} + +boolean Adafruit_FONA::sendCheckReply(char *send, char *reply, uint16_t timeout) { + if (! getReply(send, timeout) ) + return false; +/* + for (uint8_t i=0; i http://www.adafruit.com/products/1946 + ----> http://www.adafruit.com/products/1963 + + These displays use TTL Serial to communicate, 2 pins are required to + interface + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ****************************************************/ +#ifndef ADAFRUIT_FONA_H +#define ADAFRUIT_FONA_H + +#include "includes/FONAConfig.h" +#include "includes/FONAExtIncludes.h" +#include "includes/platform/FONAPlatform.h" + + + +#define FONA800L 1 +#define FONA800H 6 + +#define FONA808_V1 2 +#define FONA808_V2 3 + +#define FONA3G_A 4 +#define FONA3G_E 5 + +// Uncomment to changed the preferred SMS storage +//#define FONA_PREF_SMS_STORAGE "SM" + +#define FONA_HEADSETAUDIO 0 +#define FONA_EXTAUDIO 1 + +#define FONA_STTONE_DIALTONE 1 +#define FONA_STTONE_BUSY 2 +#define FONA_STTONE_CONGESTION 3 +#define FONA_STTONE_PATHACK 4 +#define FONA_STTONE_DROPPED 5 +#define FONA_STTONE_ERROR 6 +#define FONA_STTONE_CALLWAIT 7 +#define FONA_STTONE_RINGING 8 +#define FONA_STTONE_BEEP 16 +#define FONA_STTONE_POSTONE 17 +#define FONA_STTONE_ERRTONE 18 +#define FONA_STTONE_INDIANDIALTONE 19 +#define FONA_STTONE_USADIALTONE 20 + +#define FONA_DEFAULT_TIMEOUT_MS 500 + +#define FONA_HTTP_GET 0 +#define FONA_HTTP_POST 1 +#define FONA_HTTP_HEAD 2 + +#define FONA_CALL_READY 0 +#define FONA_CALL_FAILED 1 +#define FONA_CALL_UNKNOWN 2 +#define FONA_CALL_RINGING 3 +#define FONA_CALL_INPROGRESS 4 + +class Adafruit_FONA : public FONAStreamType { + public: + Adafruit_FONA(int8_t r); + boolean begin(FONAStreamType &port); + uint8_t type(); + + // Stream + int available(void); + size_t write(uint8_t x); + int read(void); + int peek(void); + void flush(); + + // FONA 3G requirements + boolean setBaudrate(uint16_t baud); + + // RTC + boolean enableRTC(uint8_t i); + boolean readRTC(uint8_t *year, uint8_t *month, uint8_t *date, uint8_t *hr, uint8_t *min, uint8_t *sec); + + // Battery and ADC + boolean getADCVoltage(uint16_t *v); + boolean getBattPercent(uint16_t *p); + boolean getBattVoltage(uint16_t *v); + + // SIM query + uint8_t unlockSIM(char *pin); + uint8_t getSIMCCID(char *ccid); + uint8_t getNetworkStatus(void); + uint8_t getRSSI(void); + + // IMEI + uint8_t getIMEI(char *imei); + + // set Audio output + boolean setAudio(uint8_t a); + boolean setVolume(uint8_t i); + uint8_t getVolume(void); + boolean playToolkitTone(uint8_t t, uint16_t len); + boolean setMicVolume(uint8_t a, uint8_t level); + boolean playDTMF(char tone); + + // FM radio functions. + boolean tuneFMradio(uint16_t station); + boolean FMradio(boolean onoff, uint8_t a = FONA_HEADSETAUDIO); + boolean setFMVolume(uint8_t i); + int8_t getFMVolume(); + int8_t getFMSignalLevel(uint16_t station); + + // SMS handling + boolean setSMSInterrupt(uint8_t i); + uint8_t getSMSInterrupt(void); + int8_t getNumSMS(void); + boolean readSMS(uint8_t i, char *smsbuff, uint16_t max, uint16_t *readsize); + boolean sendSMS(char *smsaddr, char *smsmsg); + boolean deleteSMS(uint8_t i); + boolean getSMSSender(uint8_t i, char *sender, int senderlen); + boolean sendUSSD(char *ussdmsg, char *ussdbuff, uint16_t maxlen, uint16_t *readlen); + + // Time + boolean enableNetworkTimeSync(boolean onoff); + boolean enableNTPTimeSync(boolean onoff, FONAFlashStringPtr ntpserver=0); + boolean getTime(char *buff, uint16_t maxlen); + + // GPRS handling + boolean enableGPRS(boolean onoff); + uint8_t GPRSstate(void); + boolean getGSMLoc(uint16_t *replycode, char *buff, uint16_t maxlen); + boolean getGSMLoc(float *lat, float *lon); + void setGPRSNetworkSettings(FONAFlashStringPtr apn, FONAFlashStringPtr username=0, FONAFlashStringPtr password=0); + + // GPS handling + boolean enableGPS(boolean onoff); + int8_t GPSstatus(void); + uint8_t getGPS(uint8_t arg, char *buffer, uint8_t maxbuff); + boolean getGPS(float *lat, float *lon, float *speed_kph=0, float *heading=0, float *altitude=0); + boolean enableGPSNMEA(uint8_t nmea); + + // TCP raw connections + boolean TCPconnect(char *server, uint16_t port); + boolean TCPclose(void); + boolean TCPconnected(void); + boolean TCPsend(char *packet, uint8_t len); + uint16_t TCPavailable(void); + uint16_t TCPread(uint8_t *buff, uint8_t len); + + // HTTP low level interface (maps directly to SIM800 commands). + boolean HTTP_init(); + boolean HTTP_term(); + void HTTP_para_start(FONAFlashStringPtr parameter, boolean quoted = true); + boolean HTTP_para_end(boolean quoted = true); + boolean HTTP_para(FONAFlashStringPtr parameter, const char *value); + boolean HTTP_para(FONAFlashStringPtr parameter, FONAFlashStringPtr value); + boolean HTTP_para(FONAFlashStringPtr parameter, int32_t value); + boolean HTTP_data(uint32_t size, uint32_t maxTime=10000); + boolean HTTP_action(uint8_t method, uint16_t *status, uint16_t *datalen, int32_t timeout = 10000); + boolean HTTP_readall(uint16_t *datalen); + boolean HTTP_ssl(boolean onoff); + + // HTTP high level interface (easier to use, less flexible). + boolean HTTP_GET_start(char *url, uint16_t *status, uint16_t *datalen); + void HTTP_GET_end(void); + boolean HTTP_POST_start(char *url, FONAFlashStringPtr contenttype, const uint8_t *postdata, uint16_t postdatalen, uint16_t *status, uint16_t *datalen); + void HTTP_POST_end(void); + void setUserAgent(FONAFlashStringPtr useragent); + + // HTTPS + void setHTTPSRedirect(boolean onoff); + + // PWM (buzzer) + boolean setPWM(uint16_t period, uint8_t duty = 50); + + // Phone calls + boolean callPhone(char *phonenum); + uint8_t getCallStatus(void); + boolean hangUp(void); + boolean pickUp(void); + boolean callerIdNotification(boolean enable, uint8_t interrupt = 0); + boolean incomingCallNumber(char* phonenum); + + // Helper functions to verify responses. + boolean expectReply(FONAFlashStringPtr reply, uint16_t timeout = 10000); + boolean sendCheckReply(char *send, char *reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + boolean sendCheckReply(FONAFlashStringPtr send, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + boolean sendCheckReply(char* send, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + + + protected: + int8_t _rstpin; + uint8_t _type; + + char replybuffer[255]; + FONAFlashStringPtr apn; + FONAFlashStringPtr apnusername; + FONAFlashStringPtr apnpassword; + boolean httpsredirect; + FONAFlashStringPtr useragent; + FONAFlashStringPtr ok_reply; + + // HTTP helpers + boolean HTTP_setup(char *url); + + void flushInput(); + uint16_t readRaw(uint16_t b); + uint8_t readline(uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS, boolean multiline = false); + uint8_t getReply(char *send, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + uint8_t getReply(FONAFlashStringPtr send, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + uint8_t getReply(FONAFlashStringPtr prefix, char *suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + uint8_t getReply(FONAFlashStringPtr prefix, int32_t suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + uint8_t getReply(FONAFlashStringPtr prefix, int32_t suffix1, int32_t suffix2, uint16_t timeout); // Don't set default value or else function call is ambiguous. + uint8_t getReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + + boolean sendCheckReply(FONAFlashStringPtr prefix, char *suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + boolean sendCheckReply(FONAFlashStringPtr prefix, int32_t suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + boolean sendCheckReply(FONAFlashStringPtr prefix, int32_t suffix, int32_t suffix2, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + boolean sendCheckReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + + + boolean parseReply(FONAFlashStringPtr toreply, + uint16_t *v, char divider = ',', uint8_t index=0); + boolean parseReply(FONAFlashStringPtr toreply, + char *v, char divider = ',', uint8_t index=0); + boolean parseReplyQuoted(FONAFlashStringPtr toreply, + char *v, int maxlen, char divider, uint8_t index); + + boolean sendParseReply(FONAFlashStringPtr tosend, + FONAFlashStringPtr toreply, + uint16_t *v, char divider = ',', uint8_t index=0); + + static boolean _incomingCall; + static void onIncomingCall(); + + FONAStreamType *mySerial; +}; + +class Adafruit_FONA_3G : public Adafruit_FONA { + + public: + Adafruit_FONA_3G (int8_t r) : Adafruit_FONA(r) { _type = FONA3G_A; } + + boolean getBattVoltage(uint16_t *v); + boolean playToolkitTone(uint8_t t, uint16_t len); + boolean hangUp(void); + boolean pickUp(void); + boolean enableGPRS(boolean onoff); + boolean enableGPS(boolean onoff); + + protected: + boolean parseReply(FONAFlashStringPtr toreply, + float *f, char divider, uint8_t index); + + boolean sendParseReply(FONAFlashStringPtr tosend, + FONAFlashStringPtr toreply, + float *f, char divider = ',', uint8_t index=0); +}; + +#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/README.md b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/README.md new file mode 100644 index 0000000..73452ca --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/README.md @@ -0,0 +1,29 @@ +# Adafruit FONA Library [![Build Status](https://secure.travis-ci.org/adafruit/Adafruit_FONA_Library.svg?branch=master)](https://travis-ci.org/adafruit/Adafruit_FONA_Library) + +**This library requires Arduino v1.0.6 or higher** + +This is a library for the Adafruit FONA Cellular GSM Breakouts etc + +Designed specifically to work with the Adafruit FONA Breakout + * https://www.adafruit.com/products/1946 + * https://www.adafruit.com/products/1963 + * http://www.adafruit.com/products/2468 + * http://www.adafruit.com/products/2542 + +These modules use TTL Serial to communicate, 2 pins are required to interface + +Adafruit invests time and resources providing this open source code, +please support Adafruit and open-source hardware by purchasing +products from Adafruit! + +Check out the links above for our tutorials and wiring diagrams + +Written by Limor Fried/Ladyada for Adafruit Industries. +BSD license, all text above must be included in any redistribution +With updates from Samy Kamkar + +To download. click the DOWNLOADS button in the top right corner, rename the uncompressed folder Adafruit_FONA +Check that the Adafruit_FONA folder contains Adafruit_FONA.cpp and Adafruit_FONA.h + +Place the Adafruit_FONA library folder your *arduinosketchfolder*/libraries/ folder. +You may need to create the libraries subfolder if its your first library. Restart the IDE. diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/.esp8266.test.skip b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/.esp8266.test.skip new file mode 100644 index 0000000..e69de29 diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino new file mode 100644 index 0000000..b0be4c5 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino @@ -0,0 +1,77 @@ +/*************************************************** + This is an example for our Adafruit FONA Cellular Module + since the FONA 3G does not do auto-baud very well, this demo + fixes the baud rate to 4800 from the default 115200 + + Designed specifically to work with the Adafruit FONA 3G + ----> http://www.adafruit.com/products/2691 + ----> http://www.adafruit.com/products/2687 + + These cellular modules use TTL Serial to communicate, 2 pins are + required to interface + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ****************************************************/ + +#include "Adafruit_FONA.h" + +#define FONA_RX 2 +#define FONA_TX 3 +#define FONA_RST 4 + +// this is a large buffer for replies +char replybuffer[255]; + +// We default to using software serial. If you want to use hardware serial +// (because softserial isnt supported) comment out the following three lines +// and uncomment the HardwareSerial line +#include +SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); +SoftwareSerial *fonaSerial = &fonaSS; + +// Hardware serial is also possible! +// HardwareSerial *fonaSerial = &Serial1; + +Adafruit_FONA fona = Adafruit_FONA(FONA_RST); + +uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); + +void setup() { + while (!Serial); + + Serial.begin(115200); + Serial.println(F("FONA set baudrate")); + + Serial.println(F("First trying 115200 baud")); + // start at 115200 baud + fonaSerial->begin(115200); + fona.begin(*fonaSerial); + + // send the command to reset the baud rate to 4800 + fona.setBaudrate(4800); + + // restart with 4800 baud + fonaSerial->begin(4800); + Serial.println(F("Initializing @ 4800 baud...")); + + if (! fona.begin(*fonaSerial)) { + Serial.println(F("Couldn't find FONA")); + while(1); + } + Serial.println(F("FONA is OK")); + + // Print module IMEI number. + char imei[15] = {0}; // MUST use a 16 character buffer for IMEI! + uint8_t imeiLen = fona.getIMEI(imei); + if (imeiLen > 0) { + Serial.print("Module IMEI: "); Serial.println(imei); + } + +} + +void loop() { +} \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/.esp8266.test.skip b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/.esp8266.test.skip new file mode 100644 index 0000000..e69de29 diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino new file mode 100644 index 0000000..7201641 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino @@ -0,0 +1,131 @@ +/*************************************************** + This is an example for our Adafruit FONA Cellular Module + + Designed specifically to work with the Adafruit FONA + ----> http://www.adafruit.com/products/1946 + ----> http://www.adafruit.com/products/1963 + ----> http://www.adafruit.com/products/2468 + ----> http://www.adafruit.com/products/2542 + + These cellular modules use TTL Serial to communicate, 2 pins are + required to interface + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ****************************************************/ + +/* +THIS CODE IS STILL IN PROGRESS! + +Open up the serial console on the Arduino at 115200 baud to interact with FONA + + +This code will receive an SMS, identify the sender's phone number, and automatically send a response + +For use with FONA 800 & 808, not 3G +*/ + +#include "Adafruit_FONA.h" + +#define FONA_RX 2 +#define FONA_TX 3 +#define FONA_RST 4 + +// this is a large buffer for replies +char replybuffer[255]; + +// We default to using software serial. If you want to use hardware serial +// (because softserial isnt supported) comment out the following three lines +// and uncomment the HardwareSerial line +#include +SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); +SoftwareSerial *fonaSerial = &fonaSS; + +// Hardware serial is also possible! +// HardwareSerial *fonaSerial = &Serial1; + +Adafruit_FONA fona = Adafruit_FONA(FONA_RST); + +uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); + +void setup() { + while (!Serial); + + Serial.begin(115200); + Serial.println(F("FONA SMS caller ID test")); + Serial.println(F("Initializing....(May take 3 seconds)")); + + // make it slow so its easy to read! + fonaSerial->begin(4800); + if (! fona.begin(*fonaSerial)) { + Serial.println(F("Couldn't find FONA")); + while(1); + } + Serial.println(F("FONA is OK")); + + // Print SIM card IMEI number. + char imei[15] = {0}; // MUST use a 16 character buffer for IMEI! + uint8_t imeiLen = fona.getIMEI(imei); + if (imeiLen > 0) { + Serial.print("SIM card IMEI: "); Serial.println(imei); + } + + Serial.println("FONA Ready"); +} + + +char fonaInBuffer[64]; //for notifications from the FONA + +void loop() { + + char* bufPtr = fonaInBuffer; //handy buffer pointer + + if (fona.available()) //any data available from the FONA? + { + int slot = 0; //this will be the slot number of the SMS + int charCount = 0; + //Read the notification into fonaInBuffer + do { + *bufPtr = fona.read(); + Serial.write(*bufPtr); + delay(1); + } while ((*bufPtr++ != '\n') && (fona.available()) && (++charCount < (sizeof(fonaInBuffer)-1))); + + //Add a terminal NULL to the notification string + *bufPtr = 0; + + //Scan the notification string for an SMS received notification. + // If it's an SMS message, we'll get the slot number in 'slot' + if (1 == sscanf(fonaInBuffer, "+CMTI: \"SM\",%d", &slot)) { + Serial.print("slot: "); Serial.println(slot); + + char callerIDbuffer[32]; //we'll store the SMS sender number in here + + // Retrieve SMS sender address/phone number. + if (! fona.getSMSSender(slot, callerIDbuffer, 31)) { + Serial.println("Didn't find SMS message in slot!"); + } + Serial.print(F("FROM: ")); Serial.println(callerIDbuffer); + + //Send back an automatic response + Serial.println("Sending reponse..."); + if (!fona.sendSMS(callerIDbuffer, "Hey, I got your text!")) { + Serial.println(F("Failed")); + } else { + Serial.println(F("Sent!")); + } + + // delete the original msg after it is processed + // otherwise, we will fill up all the slots + // and then we won't be able to receive SMS anymore + if (fona.deleteSMS(slot)) { + Serial.println(F("OK!")); + } else { + Serial.println(F("Couldn't delete")); + } + } + } +} diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONAtest/.esp8266.test.skip b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONAtest/.esp8266.test.skip new file mode 100644 index 0000000..e69de29 diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino new file mode 100644 index 0000000..1b27732 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino @@ -0,0 +1,886 @@ +/*************************************************** + This is an example for our Adafruit FONA Cellular Module + + Designed specifically to work with the Adafruit FONA + ----> http://www.adafruit.com/products/1946 + ----> http://www.adafruit.com/products/1963 + ----> http://www.adafruit.com/products/2468 + ----> http://www.adafruit.com/products/2542 + + These cellular modules use TTL Serial to communicate, 2 pins are + required to interface + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ****************************************************/ + +/* +THIS CODE IS STILL IN PROGRESS! + +Open up the serial console on the Arduino at 115200 baud to interact with FONA + +Note that if you need to set a GPRS APN, username, and password scroll down to +the commented section below at the end of the setup() function. +*/ +#include "Adafruit_FONA.h" + +#define FONA_RX 2 +#define FONA_TX 3 +#define FONA_RST 4 + +// this is a large buffer for replies +char replybuffer[255]; + +// We default to using software serial. If you want to use hardware serial +// (because softserial isnt supported) comment out the following three lines +// and uncomment the HardwareSerial line +#include +SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); +SoftwareSerial *fonaSerial = &fonaSS; + +// Hardware serial is also possible! +// HardwareSerial *fonaSerial = &Serial1; + +// Use this for FONA 800 and 808s +Adafruit_FONA fona = Adafruit_FONA(FONA_RST); +// Use this one for FONA 3G +//Adafruit_FONA_3G fona = Adafruit_FONA_3G(FONA_RST); + +uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); + +uint8_t type; + +void setup() { + while (!Serial); + + Serial.begin(115200); + Serial.println(F("FONA basic test")); + Serial.println(F("Initializing....(May take 3 seconds)")); + + fonaSerial->begin(4800); + if (! fona.begin(*fonaSerial)) { + Serial.println(F("Couldn't find FONA")); + while (1); + } + type = fona.type(); + Serial.println(F("FONA is OK")); + Serial.print(F("Found ")); + switch (type) { + case FONA800L: + Serial.println(F("FONA 800L")); break; + case FONA800H: + Serial.println(F("FONA 800H")); break; + case FONA808_V1: + Serial.println(F("FONA 808 (v1)")); break; + case FONA808_V2: + Serial.println(F("FONA 808 (v2)")); break; + case FONA3G_A: + Serial.println(F("FONA 3G (American)")); break; + case FONA3G_E: + Serial.println(F("FONA 3G (European)")); break; + default: + Serial.println(F("???")); break; + } + + // Print module IMEI number. + char imei[15] = {0}; // MUST use a 16 character buffer for IMEI! + uint8_t imeiLen = fona.getIMEI(imei); + if (imeiLen > 0) { + Serial.print("Module IMEI: "); Serial.println(imei); + } + + // Optionally configure a GPRS APN, username, and password. + // You might need to do this to access your network's GPRS/data + // network. Contact your provider for the exact APN, username, + // and password values. Username and password are optional and + // can be removed, but APN is required. + //fona.setGPRSNetworkSettings(F("your APN"), F("your username"), F("your password")); + + // Optionally configure HTTP gets to follow redirects over SSL. + // Default is not to follow SSL redirects, however if you uncomment + // the following line then redirects over SSL will be followed. + //fona.setHTTPSRedirect(true); + + printMenu(); +} + +void printMenu(void) { + Serial.println(F("-------------------------------------")); + Serial.println(F("[?] Print this menu")); + Serial.println(F("[a] read the ADC 2.8V max (FONA800 & 808)")); + Serial.println(F("[b] read the Battery V and % charged")); + Serial.println(F("[C] read the SIM CCID")); + Serial.println(F("[U] Unlock SIM with PIN code")); + Serial.println(F("[i] read RSSI")); + Serial.println(F("[n] get Network status")); + Serial.println(F("[v] set audio Volume")); + Serial.println(F("[V] get Volume")); + Serial.println(F("[H] set Headphone audio (FONA800 & 808)")); + Serial.println(F("[e] set External audio (FONA800 & 808)")); + Serial.println(F("[T] play audio Tone")); + Serial.println(F("[P] PWM/Buzzer out (FONA800 & 808)")); + + // FM (SIM800 only!) + Serial.println(F("[f] tune FM radio (FONA800)")); + Serial.println(F("[F] turn off FM (FONA800)")); + Serial.println(F("[m] set FM volume (FONA800)")); + Serial.println(F("[M] get FM volume (FONA800)")); + Serial.println(F("[q] get FM station signal level (FONA800)")); + + // Phone + Serial.println(F("[c] make phone Call")); + Serial.println(F("[A] get call status")); + Serial.println(F("[h] Hang up phone")); + Serial.println(F("[p] Pick up phone")); + + // SMS + Serial.println(F("[N] Number of SMSs")); + Serial.println(F("[r] Read SMS #")); + Serial.println(F("[R] Read All SMS")); + Serial.println(F("[d] Delete SMS #")); + Serial.println(F("[s] Send SMS")); + Serial.println(F("[u] Send USSD")); + + // Time + Serial.println(F("[y] Enable network time sync (FONA 800 & 808)")); + Serial.println(F("[Y] Enable NTP time sync (GPRS FONA 800 & 808)")); + Serial.println(F("[t] Get network time")); + + // GPRS + Serial.println(F("[G] Enable GPRS")); + Serial.println(F("[g] Disable GPRS")); + Serial.println(F("[l] Query GSMLOC (GPRS)")); + Serial.println(F("[w] Read webpage (GPRS)")); + Serial.println(F("[W] Post to website (GPRS)")); + + // GPS + if ((type == FONA3G_A) || (type == FONA3G_E) || (type == FONA808_V1) || (type == FONA808_V2)) { + Serial.println(F("[O] Turn GPS on (FONA 808 & 3G)")); + Serial.println(F("[o] Turn GPS off (FONA 808 & 3G)")); + Serial.println(F("[L] Query GPS location (FONA 808 & 3G)")); + if (type == FONA808_V1) { + Serial.println(F("[x] GPS fix status (FONA808 v1 only)")); + } + Serial.println(F("[E] Raw NMEA out (FONA808)")); + } + + Serial.println(F("[S] create Serial passthru tunnel")); + Serial.println(F("-------------------------------------")); + Serial.println(F("")); + +} +void loop() { + Serial.print(F("FONA> ")); + while (! Serial.available() ) { + if (fona.available()) { + Serial.write(fona.read()); + } + } + + char command = Serial.read(); + Serial.println(command); + + + switch (command) { + case '?': { + printMenu(); + break; + } + + case 'a': { + // read the ADC + uint16_t adc; + if (! fona.getADCVoltage(&adc)) { + Serial.println(F("Failed to read ADC")); + } else { + Serial.print(F("ADC = ")); Serial.print(adc); Serial.println(F(" mV")); + } + break; + } + + case 'b': { + // read the battery voltage and percentage + uint16_t vbat; + if (! fona.getBattVoltage(&vbat)) { + Serial.println(F("Failed to read Batt")); + } else { + Serial.print(F("VBat = ")); Serial.print(vbat); Serial.println(F(" mV")); + } + + + if (! fona.getBattPercent(&vbat)) { + Serial.println(F("Failed to read Batt")); + } else { + Serial.print(F("VPct = ")); Serial.print(vbat); Serial.println(F("%")); + } + + break; + } + + case 'U': { + // Unlock the SIM with a PIN code + char PIN[5]; + flushSerial(); + Serial.println(F("Enter 4-digit PIN")); + readline(PIN, 3); + Serial.println(PIN); + Serial.print(F("Unlocking SIM card: ")); + if (! fona.unlockSIM(PIN)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + + case 'C': { + // read the CCID + fona.getSIMCCID(replybuffer); // make sure replybuffer is at least 21 bytes! + Serial.print(F("SIM CCID = ")); Serial.println(replybuffer); + break; + } + + case 'i': { + // read the RSSI + uint8_t n = fona.getRSSI(); + int8_t r; + + Serial.print(F("RSSI = ")); Serial.print(n); Serial.print(": "); + if (n == 0) r = -115; + if (n == 1) r = -111; + if (n == 31) r = -52; + if ((n >= 2) && (n <= 30)) { + r = map(n, 2, 30, -110, -54); + } + Serial.print(r); Serial.println(F(" dBm")); + + break; + } + + case 'n': { + // read the network/cellular status + uint8_t n = fona.getNetworkStatus(); + Serial.print(F("Network status ")); + Serial.print(n); + Serial.print(F(": ")); + if (n == 0) Serial.println(F("Not registered")); + if (n == 1) Serial.println(F("Registered (home)")); + if (n == 2) Serial.println(F("Not registered (searching)")); + if (n == 3) Serial.println(F("Denied")); + if (n == 4) Serial.println(F("Unknown")); + if (n == 5) Serial.println(F("Registered roaming")); + break; + } + + /*** Audio ***/ + case 'v': { + // set volume + flushSerial(); + if ( (type == FONA3G_A) || (type == FONA3G_E) ) { + Serial.print(F("Set Vol [0-8] ")); + } else { + Serial.print(F("Set Vol % [0-100] ")); + } + uint8_t vol = readnumber(); + Serial.println(); + if (! fona.setVolume(vol)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + + case 'V': { + uint8_t v = fona.getVolume(); + Serial.print(v); + if ( (type == FONA3G_A) || (type == FONA3G_E) ) { + Serial.println(" / 8"); + } else { + Serial.println("%"); + } + break; + } + + case 'H': { + // Set Headphone output + if (! fona.setAudio(FONA_HEADSETAUDIO)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + fona.setMicVolume(FONA_HEADSETAUDIO, 15); + break; + } + case 'e': { + // Set External output + if (! fona.setAudio(FONA_EXTAUDIO)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + + fona.setMicVolume(FONA_EXTAUDIO, 10); + break; + } + + case 'T': { + // play tone + flushSerial(); + Serial.print(F("Play tone #")); + uint8_t kittone = readnumber(); + Serial.println(); + // play for 1 second (1000 ms) + if (! fona.playToolkitTone(kittone, 1000)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + + /*** FM Radio ***/ + + case 'f': { + // get freq + flushSerial(); + Serial.print(F("FM Freq (eg 1011 == 101.1 MHz): ")); + uint16_t station = readnumber(); + Serial.println(); + // FM radio ON using headset + if (fona.FMradio(true, FONA_HEADSETAUDIO)) { + Serial.println(F("Opened")); + } + if (! fona.tuneFMradio(station)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("Tuned")); + } + break; + } + case 'F': { + // FM radio off + if (! fona.FMradio(false)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + case 'm': { + // Set FM volume. + flushSerial(); + Serial.print(F("Set FM Vol [0-6]:")); + uint8_t vol = readnumber(); + Serial.println(); + if (!fona.setFMVolume(vol)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + case 'M': { + // Get FM volume. + uint8_t fmvol = fona.getFMVolume(); + if (fmvol < 0) { + Serial.println(F("Failed")); + } else { + Serial.print(F("FM volume: ")); + Serial.println(fmvol, DEC); + } + break; + } + case 'q': { + // Get FM station signal level (in decibels). + flushSerial(); + Serial.print(F("FM Freq (eg 1011 == 101.1 MHz): ")); + uint16_t station = readnumber(); + Serial.println(); + int8_t level = fona.getFMSignalLevel(station); + if (level < 0) { + Serial.println(F("Failed! Make sure FM radio is on (tuned to station).")); + } else { + Serial.print(F("Signal level (dB): ")); + Serial.println(level, DEC); + } + break; + } + + /*** PWM ***/ + + case 'P': { + // PWM Buzzer output @ 2KHz max + flushSerial(); + Serial.print(F("PWM Freq, 0 = Off, (1-2000): ")); + uint16_t freq = readnumber(); + Serial.println(); + if (! fona.setPWM(freq)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + + /*** Call ***/ + case 'c': { + // call a phone! + char number[30]; + flushSerial(); + Serial.print(F("Call #")); + readline(number, 30); + Serial.println(); + Serial.print(F("Calling ")); Serial.println(number); + if (!fona.callPhone(number)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("Sent!")); + } + + break; + } + case 'A': { + // get call status + int8_t callstat = fona.getCallStatus(); + switch (callstat) { + case 0: Serial.println(F("Ready")); break; + case 1: Serial.println(F("Could not get status")); break; + case 3: Serial.println(F("Ringing (incoming)")); break; + case 4: Serial.println(F("Ringing/in progress (outgoing)")); break; + default: Serial.println(F("Unknown")); break; + } + break; + } + + case 'h': { + // hang up! + if (! fona.hangUp()) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + + case 'p': { + // pick up! + if (! fona.pickUp()) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + + /*** SMS ***/ + + case 'N': { + // read the number of SMS's! + int8_t smsnum = fona.getNumSMS(); + if (smsnum < 0) { + Serial.println(F("Could not read # SMS")); + } else { + Serial.print(smsnum); + Serial.println(F(" SMS's on SIM card!")); + } + break; + } + case 'r': { + // read an SMS + flushSerial(); + Serial.print(F("Read #")); + uint8_t smsn = readnumber(); + Serial.print(F("\n\rReading SMS #")); Serial.println(smsn); + + // Retrieve SMS sender address/phone number. + if (! fona.getSMSSender(smsn, replybuffer, 250)) { + Serial.println("Failed!"); + break; + } + Serial.print(F("FROM: ")); Serial.println(replybuffer); + + // Retrieve SMS value. + uint16_t smslen; + if (! fona.readSMS(smsn, replybuffer, 250, &smslen)) { // pass in buffer and max len! + Serial.println("Failed!"); + break; + } + Serial.print(F("***** SMS #")); Serial.print(smsn); + Serial.print(" ("); Serial.print(smslen); Serial.println(F(") bytes *****")); + Serial.println(replybuffer); + Serial.println(F("*****")); + + break; + } + case 'R': { + // read all SMS + int8_t smsnum = fona.getNumSMS(); + uint16_t smslen; + int8_t smsn; + + if ( (type == FONA3G_A) || (type == FONA3G_E) ) { + smsn = 0; // zero indexed + smsnum--; + } else { + smsn = 1; // 1 indexed + } + + for ( ; smsn <= smsnum; smsn++) { + Serial.print(F("\n\rReading SMS #")); Serial.println(smsn); + if (!fona.readSMS(smsn, replybuffer, 250, &smslen)) { // pass in buffer and max len! + Serial.println(F("Failed!")); + break; + } + // if the length is zero, its a special case where the index number is higher + // so increase the max we'll look at! + if (smslen == 0) { + Serial.println(F("[empty slot]")); + smsnum++; + continue; + } + + Serial.print(F("***** SMS #")); Serial.print(smsn); + Serial.print(" ("); Serial.print(smslen); Serial.println(F(") bytes *****")); + Serial.println(replybuffer); + Serial.println(F("*****")); + } + break; + } + + case 'd': { + // delete an SMS + flushSerial(); + Serial.print(F("Delete #")); + uint8_t smsn = readnumber(); + + Serial.print(F("\n\rDeleting SMS #")); Serial.println(smsn); + if (fona.deleteSMS(smsn)) { + Serial.println(F("OK!")); + } else { + Serial.println(F("Couldn't delete")); + } + break; + } + + case 's': { + // send an SMS! + char sendto[21], message[141]; + flushSerial(); + Serial.print(F("Send to #")); + readline(sendto, 20); + Serial.println(sendto); + Serial.print(F("Type out one-line message (140 char): ")); + readline(message, 140); + Serial.println(message); + if (!fona.sendSMS(sendto, message)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("Sent!")); + } + + break; + } + + case 'u': { + // send a USSD! + char message[141]; + flushSerial(); + Serial.print(F("Type out one-line message (140 char): ")); + readline(message, 140); + Serial.println(message); + + uint16_t ussdlen; + if (!fona.sendUSSD(message, replybuffer, 250, &ussdlen)) { // pass in buffer and max len! + Serial.println(F("Failed")); + } else { + Serial.println(F("Sent!")); + Serial.print(F("***** USSD Reply")); + Serial.print(" ("); Serial.print(ussdlen); Serial.println(F(") bytes *****")); + Serial.println(replybuffer); + Serial.println(F("*****")); + } + } + + /*** Time ***/ + + case 'y': { + // enable network time sync + if (!fona.enableNetworkTimeSync(true)) + Serial.println(F("Failed to enable")); + break; + } + + case 'Y': { + // enable NTP time sync + if (!fona.enableNTPTimeSync(true, F("pool.ntp.org"))) + Serial.println(F("Failed to enable")); + break; + } + + case 't': { + // read the time + char buffer[23]; + + fona.getTime(buffer, 23); // make sure replybuffer is at least 23 bytes! + Serial.print(F("Time = ")); Serial.println(buffer); + break; + } + + + /*********************************** GPS (SIM808 only) */ + + case 'o': { + // turn GPS off + if (!fona.enableGPS(false)) + Serial.println(F("Failed to turn off")); + break; + } + case 'O': { + // turn GPS on + if (!fona.enableGPS(true)) + Serial.println(F("Failed to turn on")); + break; + } + case 'x': { + int8_t stat; + // check GPS fix + stat = fona.GPSstatus(); + if (stat < 0) + Serial.println(F("Failed to query")); + if (stat == 0) Serial.println(F("GPS off")); + if (stat == 1) Serial.println(F("No fix")); + if (stat == 2) Serial.println(F("2D fix")); + if (stat == 3) Serial.println(F("3D fix")); + break; + } + + case 'L': { + // check for GPS location + char gpsdata[120]; + fona.getGPS(0, gpsdata, 120); + if (type == FONA808_V1) + Serial.println(F("Reply in format: mode,longitude,latitude,altitude,utctime(yyyymmddHHMMSS),ttff,satellites,speed,course")); + else + Serial.println(F("Reply in format: mode,fixstatus,utctime(yyyymmddHHMMSS),latitude,longitude,altitude,speed,course,fixmode,reserved1,HDOP,PDOP,VDOP,reserved2,view_satellites,used_satellites,reserved3,C/N0max,HPA,VPA")); + Serial.println(gpsdata); + + break; + } + + case 'E': { + flushSerial(); + if (type == FONA808_V1) { + Serial.print(F("GPS NMEA output sentences (0 = off, 34 = RMC+GGA, 255 = all)")); + } else { + Serial.print(F("On (1) or Off (0)? ")); + } + uint8_t nmeaout = readnumber(); + + // turn on NMEA output + fona.enableGPSNMEA(nmeaout); + + break; + } + + /*********************************** GPRS */ + + case 'g': { + // turn GPRS off + if (!fona.enableGPRS(false)) + Serial.println(F("Failed to turn off")); + break; + } + case 'G': { + // turn GPRS on + if (!fona.enableGPRS(true)) + Serial.println(F("Failed to turn on")); + break; + } + case 'l': { + // check for GSMLOC (requires GPRS) + uint16_t returncode; + + if (!fona.getGSMLoc(&returncode, replybuffer, 250)) + Serial.println(F("Failed!")); + if (returncode == 0) { + Serial.println(replybuffer); + } else { + Serial.print(F("Fail code #")); Serial.println(returncode); + } + + break; + } + case 'w': { + // read website URL + uint16_t statuscode; + int16_t length; + char url[80]; + + flushSerial(); + Serial.println(F("NOTE: in beta! Use small webpages to read!")); + Serial.println(F("URL to read (e.g. www.adafruit.com/testwifi/index.html):")); + Serial.print(F("http://")); readline(url, 79); + Serial.println(url); + + Serial.println(F("****")); + if (!fona.HTTP_GET_start(url, &statuscode, (uint16_t *)&length)) { + Serial.println("Failed!"); + break; + } + while (length > 0) { + while (fona.available()) { + char c = fona.read(); + + // Serial.write is too slow, we'll write directly to Serial register! +#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) + loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data register empty. */ + UDR0 = c; +#else + Serial.write(c); +#endif + length--; + if (! length) break; + } + } + Serial.println(F("\n****")); + fona.HTTP_GET_end(); + break; + } + + case 'W': { + // Post data to website + uint16_t statuscode; + int16_t length; + char url[80]; + char data[80]; + + flushSerial(); + Serial.println(F("NOTE: in beta! Use simple websites to post!")); + Serial.println(F("URL to post (e.g. httpbin.org/post):")); + Serial.print(F("http://")); readline(url, 79); + Serial.println(url); + Serial.println(F("Data to post (e.g. \"foo\" or \"{\"simple\":\"json\"}\"):")); + readline(data, 79); + Serial.println(data); + + Serial.println(F("****")); + if (!fona.HTTP_POST_start(url, F("text/plain"), (uint8_t *) data, strlen(data), &statuscode, (uint16_t *)&length)) { + Serial.println("Failed!"); + break; + } + while (length > 0) { + while (fona.available()) { + char c = fona.read(); + +#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) + loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data register empty. */ + UDR0 = c; +#else + Serial.write(c); +#endif + + length--; + if (! length) break; + } + } + Serial.println(F("\n****")); + fona.HTTP_POST_end(); + break; + } + /*****************************************/ + + case 'S': { + Serial.println(F("Creating SERIAL TUBE")); + while (1) { + while (Serial.available()) { + delay(1); + fona.write(Serial.read()); + } + if (fona.available()) { + Serial.write(fona.read()); + } + } + break; + } + + default: { + Serial.println(F("Unknown command")); + printMenu(); + break; + } + } + // flush input + flushSerial(); + while (fona.available()) { + Serial.write(fona.read()); + } + +} + +void flushSerial() { + while (Serial.available()) + Serial.read(); +} + +char readBlocking() { + while (!Serial.available()); + return Serial.read(); +} +uint16_t readnumber() { + uint16_t x = 0; + char c; + while (! isdigit(c = readBlocking())) { + //Serial.print(c); + } + Serial.print(c); + x = c - '0'; + while (isdigit(c = readBlocking())) { + Serial.print(c); + x *= 10; + x += c - '0'; + } + return x; +} + +uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout) { + uint16_t buffidx = 0; + boolean timeoutvalid = true; + if (timeout == 0) timeoutvalid = false; + + while (true) { + if (buffidx > maxbuff) { + //Serial.println(F("SPACE")); + break; + } + + while (Serial.available()) { + char c = Serial.read(); + + //Serial.print(c, HEX); Serial.print("#"); Serial.println(c); + + if (c == '\r') continue; + if (c == 0xA) { + if (buffidx == 0) // the first 0x0A is ignored + continue; + + timeout = 0; // the second 0x0A is the end of the line + timeoutvalid = true; + break; + } + buff[buffidx] = c; + buffidx++; + } + + if (timeoutvalid && timeout == 0) { + //Serial.println(F("TIMEOUT")); + break; + } + delay(1); + } + buff[buffidx] = 0; // null term + return buffidx; +} diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/GPS/.esp8266.test.skip b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/GPS/.esp8266.test.skip new file mode 100644 index 0000000..e69de29 diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino new file mode 100644 index 0000000..cce63d5 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino @@ -0,0 +1,112 @@ +/** + * ___ ___ _ _ _ ___ __ ___ ___ ___ ___ + * | __/ _ \| \| | /_\ ( _ )/ \( _ ) / __| _ \/ __| + * | _| (_) | .` |/ _ \ / _ \ () / _ \ | (_ | _/\__ \ + * |_| \___/|_|\_/_/ \_\ \___/\__/\___/ \___|_| |___/ + * + * This example is meant to work with the Adafruit + * FONA 808 or 3G Shield or Breakout + * + * Copyright: 2015 Adafruit + * Author: Todd Treece + * Licence: MIT + * + */ +#include "Adafruit_FONA.h" + +// standard pins for the shield, adjust as necessary +#define FONA_RX 2 +#define FONA_TX 3 +#define FONA_RST 4 + +// We default to using software serial. If you want to use hardware serial +// (because softserial isnt supported) comment out the following three lines +// and uncomment the HardwareSerial line +#include +SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); +SoftwareSerial *fonaSerial = &fonaSS; + +// Hardware serial is also possible! +// HardwareSerial *fonaSerial = &Serial1; + +Adafruit_FONA fona = Adafruit_FONA(FONA_RST); + +// Have a FONA 3G? use this object type instead +//Adafruit_FONA_3G fona = Adafruit_FONA_3G(FONA_RST); + + +void setup() { + + while (! Serial); + + Serial.begin(115200); + Serial.println(F("Adafruit FONA 808 & 3G GPS demo")); + Serial.println(F("Initializing FONA... (May take a few seconds)")); + + fonaSerial->begin(4800); + if (! fona.begin(*fonaSerial)) { + Serial.println(F("Couldn't find FONA")); + while(1); + } + Serial.println(F("FONA is OK")); + // Try to enable GPRS + + + Serial.println(F("Enabling GPS...")); + fona.enableGPS(true); +} + +void loop() { + delay(2000); + + float latitude, longitude, speed_kph, heading, speed_mph, altitude; + + // if you ask for an altitude reading, getGPS will return false if there isn't a 3D fix + boolean gps_success = fona.getGPS(&latitude, &longitude, &speed_kph, &heading, &altitude); + + if (gps_success) { + + Serial.print("GPS lat:"); + Serial.println(latitude, 6); + Serial.print("GPS long:"); + Serial.println(longitude, 6); + Serial.print("GPS speed KPH:"); + Serial.println(speed_kph); + Serial.print("GPS speed MPH:"); + speed_mph = speed_kph * 0.621371192; + Serial.println(speed_mph); + Serial.print("GPS heading:"); + Serial.println(heading); + Serial.print("GPS altitude:"); + Serial.println(altitude); + + } else { + Serial.println("Waiting for FONA GPS 3D fix..."); + } + + // Fona 3G doesnt have GPRSlocation :/ + if ((fona.type() == FONA3G_A) || (fona.type() == FONA3G_E)) + return; + // Check for network, then GPRS + Serial.println(F("Checking for Cell network...")); + if (fona.getNetworkStatus() == 1) { + // network & GPRS? Great! Print out the GSM location to compare + boolean gsmloc_success = fona.getGSMLoc(&latitude, &longitude); + + if (gsmloc_success) { + Serial.print("GSMLoc lat:"); + Serial.println(latitude, 6); + Serial.print("GSMLoc long:"); + Serial.println(longitude, 6); + } else { + Serial.println("GSM location failed..."); + Serial.println(F("Disabling GPRS")); + fona.enableGPRS(false); + Serial.println(F("Enabling GPRS")); + if (!fona.enableGPRS(true)) { + Serial.println(F("Failed to turn GPRS on")); + } + } + } +} + diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/IncomingCall/.esp8266.test.skip b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/IncomingCall/.esp8266.test.skip new file mode 100644 index 0000000..e69de29 diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino new file mode 100644 index 0000000..8dba308 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino @@ -0,0 +1,62 @@ +// FONA Incoming Call Number Example +// Listens for a call and displays the phone number of the caller (if available). +// Use this example to add phone call detection to your own FONA sketch. +#include "Adafruit_FONA.h" + +// Pins which are connected to the FONA. +// Note that this is different from FONAtest! +#define FONA_RX 3 +#define FONA_TX 4 +#define FONA_RST 5 + +// Note you need to map interrupt number to pin number +// for your board. On an Uno & Mega interrupt 0 is +// digital pin 2, and on a Leonardo interrupt 0 is +// digital pin 3. See this page for a complete table: +// http://arduino.cc/en/Reference/attachInterrupt +// Make sure this interrupt pin is connected to FONA RI! +#define FONA_RI_INTERRUPT 0 + +// We default to using software serial. If you want to use hardware serial +// (because softserial isnt supported) comment out the following three lines +// and uncomment the HardwareSerial line +#include +SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); +SoftwareSerial *fonaSerial = &fonaSS; + +// Hardware serial is also possible! +// HardwareSerial *fonaSerial = &Serial1; + +Adafruit_FONA fona = Adafruit_FONA(FONA_RST); + +void setup() { + Serial.begin(115200); + Serial.println(F("FONA incoming call example")); + Serial.println(F("Initializing....(May take 3 seconds)")); + + fonaSerial->begin(4800); + if (! fona.begin(*fonaSerial)) { + Serial.println(F("Couldn't find FONA")); + while(1); + } + Serial.println(F("FONA is OK")); + + // Enable incoming call notification. + if(fona.callerIdNotification(true, FONA_RI_INTERRUPT)) { + Serial.println(F("Caller id notification enabled.")); + } + else { + Serial.println(F("Caller id notification disabled")); + } +} + +void loop(){ + // Create a small string buffer to hold incoming call number. + char phone[32] = {0}; + // Check for an incoming call. Will return true if a call is incoming. + if(fona.incomingCallNumber(phone)){ + Serial.println(F("RING!")); + Serial.print(F("Phone Number: ")); + Serial.println(phone); + } +} diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/FONAConfig.h b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/FONAConfig.h new file mode 100644 index 0000000..5fa3e13 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/FONAConfig.h @@ -0,0 +1,34 @@ +/* + * FONAConfig.h -- compile-time configuration + * This is part of the library for the Adafruit FONA Cellular Module + * + * Designed specifically to work with the Adafruit FONA + * ----> https://www.adafruit.com/products/1946 + * ----> https://www.adafruit.com/products/1963 + * ----> http://www.adafruit.com/products/2468 + * ----> http://www.adafruit.com/products/2542 + * + * Adafruit invests time and resources providing this open source code, + * please support Adafruit and open-source hardware by purchasing + * products from Adafruit! + * + * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in + * the Adafruit_FONA_Library and released under the + * BSD license, all text above must be included in any redistribution. + * + * Created on: Jan 16, 2016 + * Author: Pat Deegan + */ + +#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONACONFIG_H_ +#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONACONFIG_H_ + +/* ADAFRUIT_FONA_DEBUG + * When defined, will cause extensive debug output on the + * DebugStream set in the appropriate platform/ header. + */ + +#define ADAFRUIT_FONA_DEBUG + + +#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONACONFIG_H_ */ diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h new file mode 100644 index 0000000..f8fe878 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h @@ -0,0 +1,33 @@ +/* + * FONAExtIncludes.h -- system-wide includes + * This is part of the library for the Adafruit FONA Cellular Module + * + * Designed specifically to work with the Adafruit FONA + * ----> https://www.adafruit.com/products/1946 + * ----> https://www.adafruit.com/products/1963 + * ----> http://www.adafruit.com/products/2468 + * ----> http://www.adafruit.com/products/2542 + * + * Adafruit invests time and resources providing this open source code, + * please support Adafruit and open-source hardware by purchasing + * products from Adafruit! + * + * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in + * the Adafruit_FONA_Library and released under the + * BSD license, all text above must be included in any redistribution. + * + * Created on: Jan 16, 2016 + * Author: Pat Deegan + */ + + +#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONAEXTINCLUDES_H_ +#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONAEXTINCLUDES_H_ + + +#include "FONAConfig.h" +// include any system-wide includes required here + + + +#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONAEXTINCLUDES_H_ */ diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h new file mode 100644 index 0000000..85bc8fe --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h @@ -0,0 +1,67 @@ +/* + * FONAPlatStd.h -- standard AVR/Arduino platform. + * + * This is part of the library for the Adafruit FONA Cellular Module + * + * Designed specifically to work with the Adafruit FONA + * ----> https://www.adafruit.com/products/1946 + * ----> https://www.adafruit.com/products/1963 + * ----> http://www.adafruit.com/products/2468 + * ----> http://www.adafruit.com/products/2542 + * + * Adafruit invests time and resources providing this open source code, + * please support Adafruit and open-source hardware by purchasing + * products from Adafruit! + * + * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in + * the Adafruit_FONA_Library and released under the + * BSD license, all text above must be included in any redistribution. + * + * Created on: Jan 16, 2016 + * Author: Pat Deegan + */ + + +#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATSTD_H_ +#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATSTD_H_ + +#include "../FONAConfig.h" + + +#if (ARDUINO >= 100) + #include "Arduino.h" + #if !defined(__SAM3X8E__) && !defined(ARDUINO_ARCH_SAMD) // Arduino Due doesn't support #include + #endif +#else + #include "WProgram.h" + #include +#endif + +#include + + +// DebugStream sets the Stream output to use +// for debug (only applies when ADAFRUIT_FONA_DEBUG +// is defined in config) +#define DebugStream Serial + +#ifdef ADAFRUIT_FONA_DEBUG +// need to do some debugging... +#define DEBUG_PRINT(...) DebugStream.print(__VA_ARGS__) +#define DEBUG_PRINTLN(...) DebugStream.println(__VA_ARGS__) +#endif + +// a few typedefs to keep things portable +typedef Stream FONAStreamType; +typedef const __FlashStringHelper * FONAFlashStringPtr; + +#define prog_char char PROGMEM + +#define prog_char_strcmp(a, b) strcmp_P((a), (b)) +// define prog_char_strncmp(a, b, c) strncmp_P((a), (b), (c)) +#define prog_char_strstr(a, b) strstr_P((a), (b)) +#define prog_char_strlen(a) strlen_P((a)) +#define prog_char_strcpy(to, fromprogmem) strcpy_P((to), (fromprogmem)) +//define prog_char_strncpy(to, from, len) strncpy_P((to), (fromprogmem), (len)) + +#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATSTD_H_ */ diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h new file mode 100644 index 0000000..0bf98d0 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h @@ -0,0 +1,62 @@ +/* + * FONAPlatform.h -- platform definitions includes. + * + * This is part of the library for the Adafruit FONA Cellular Module + * + * Designed specifically to work with the Adafruit FONA + * ----> https://www.adafruit.com/products/1946 + * ----> https://www.adafruit.com/products/1963 + * ----> http://www.adafruit.com/products/2468 + * ----> http://www.adafruit.com/products/2542 + * + * Adafruit invests time and resources providing this open source code, + * please support Adafruit and open-source hardware by purchasing + * products from Adafruit! + * + * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in + * the Adafruit_FONA_Library and released under the + * BSD license, all text above must be included in any redistribution. + * + * Created on: Jan 16, 2016 + * Author: Pat Deegan + */ + + +#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATFORM_H_ +#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATFORM_H_ + +#include "../FONAConfig.h" + +// only "standard" config supported in this release -- namely AVR-based arduino type affairs +#include "FONAPlatStd.h" + + + +#ifndef DEBUG_PRINT +// debug is disabled + +#define DEBUG_PRINT(...) +#define DEBUG_PRINTLN(...) + +#endif + + +#ifndef prog_char_strcmp +#define prog_char_strcmp(a, b) strcmp((a), (b)) +#endif + +#ifndef prog_char_strstr +#define prog_char_strstr(a, b) strstr((a), (b)) +#endif + +#ifndef prog_char_strlen +#define prog_char_strlen(a) strlen((a)) +#endif + + +#ifndef prog_char_strcpy +#define prog_char_strcpy(to, fromprogmem) strcpy((to), (fromprogmem)) +#endif + + +#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATFORM_H_ */ diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/library.properties b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/library.properties new file mode 100644 index 0000000..bb7099c --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/library.properties @@ -0,0 +1,9 @@ +name=Adafruit FONA Library +version=1.3.2 +author=Adafruit +maintainer=Adafruit +sentence=Arduino library for the Adafruit FONA +paragraph=Arduino library for the Adafruit FONA +category=Communication +url=https://github.com/adafruit/Adafruit_FONA_Library +architectures=* diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp new file mode 100644 index 0000000..9448278 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp @@ -0,0 +1,4 @@ +#include "Adafruit_SleepyDog.h" + +// Global instance of the main class for sketches to use. +WatchdogType Watchdog; diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h new file mode 100644 index 0000000..4cdf4b4 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h @@ -0,0 +1,28 @@ +#ifndef ADAFRUIT_SLEEPYDOG_H +#define ADAFRUIT_SLEEPYDOG_H + +// Platform-specific code goes below. Each #ifdef should check for the presence +// of their platform and pull in the appropriate watchdog implementation type, +// then typedef it to WatchdogType so the .cpp file can create a global instance. +#if defined(ARDUINO_ARCH_AVR) || defined(__AVR__) + #include "utility/WatchdogAVR.h" + typedef WatchdogAVR WatchdogType; +#elif defined(ARDUINO_ARCH_SAMD) + // Arduino Zero / ATSAMD series CPU watchdog support. + #include "utility/WatchdogSAMD.h" + typedef WatchdogSAMD WatchdogType; +#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) + // Teensy 3.x watchdog support. + #include "utility/WatchdogKinetisK.h" + typedef WatchdogKinetisKseries WatchdogType; +#elif defined(__MKL26Z64__) + // Teensy LC watchdog support. + #include "utility/WatchdogKinetisL.h" + typedef WatchdogKinetisLseries WatchdogType; +#else + #error Unsupported platform for the Adafruit Watchdog library! +#endif + +extern WatchdogType Watchdog; + +#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/LICENSE b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/LICENSE new file mode 100644 index 0000000..04ebb92 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Adafruit Industries + +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/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/README.md b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/README.md new file mode 100644 index 0000000..3aa268a --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/README.md @@ -0,0 +1,6 @@ +# Adafruit SleepyDog Arduino Library + +Arduino library to use the watchdog timer for system reset and low power sleep. + +Currently supports the following hardware: +* Arduino Uno or compatible (ATmega328P). diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino new file mode 100644 index 0000000..8d47041 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino @@ -0,0 +1,62 @@ +// Adafruit Watchdog Library Basic Usage Example +// +// Simple example of how to use the watchdog library. +// +// Author: Tony DiCola + +#include + +void setup() { + Serial.begin(115200); + while (!Serial) ; // wait for Arduino Serial Monitor (native USB boards) + Serial.println("Adafruit Watchdog Library Demo!"); + Serial.println(); + + // First a normal example of using the watchdog timer. + // Enable the watchdog by calling Watchdog.enable() as below. This will turn + // on the watchdog timer with a ~4 second timeout before reseting the Arduino. + // The estimated actual milliseconds before reset (in milliseconds) is returned. + // Make sure to reset the watchdog before the countdown expires or the Arduino + // will reset! + int countdownMS = Watchdog.enable(4000); + Serial.print("Enabled the watchdog with max countdown of "); + Serial.print(countdownMS, DEC); + Serial.println(" milliseconds!"); + Serial.println(); + + // Now loop a few times and periodically reset the watchdog. + Serial.println("Looping ten times while resetting the watchdog..."); + for (int i = 1; i <= 10; ++i) { + Serial.print("Loop #"); Serial.println(i, DEC); + delay(1000); + // Reset the watchdog with every loop to make sure the sketch keeps running. + // If you comment out this call watch what happens after about 4 iterations! + Watchdog.reset(); + } + Serial.println(); + + // Disable the watchdog entirely by calling Watchdog.disable(); + Watchdog.disable(); + + // Finally demonstrate the watchdog resetting by enabling it for a shorter + // period of time and waiting a long time without a reset. Notice you can pass + // a _maximum_ countdown time (in milliseconds) to the enable call. The library + // will try to use that value as the countdown, but it might pick a smaller + // value if the hardware doesn't support it. The actual countdown value will + // be returned so you can see what it is. + countdownMS = Watchdog.enable(4000); + Serial.print("Get ready, the watchdog will reset in "); + Serial.print(countdownMS, DEC); + Serial.println(" milliseconds!"); + Serial.println(); + delay(countdownMS+1000); + + // Execution will never get here because the watchdog resets the Arduino! +} + +void loop() { + // We'll never actually get to the loop because the watchdog will reset in + // the setup function. + Serial.println("You shouldn't see this message."); + delay(1000); +} diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino new file mode 100644 index 0000000..d8eab80 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino @@ -0,0 +1,37 @@ +// Adafruit Watchdog Library Sleep Example +// +// Simple example of how to do low power sleep with the watchdog timer. +// +// Author: Tony DiCola + +#include + +void setup() { + Serial.begin(115200); + while (!Serial) ; // wait for Arduino Serial Monitor (native USB boards) + Serial.println("Adafruit Watchdog Library Sleep Demo!"); + Serial.println(); +} + +void loop() { + Serial.println("Going to sleep in one second..."); + delay(1000); + + // To enter low power sleep mode call Watchdog.sleep() like below + // and the watchdog will allow low power sleep for as long as possible. + // The actual amount of time spent in sleep will be returned (in + // milliseconds). + int sleepMS = Watchdog.sleep(); + + // Alternatively you can provide a millisecond value to specify + // how long you'd like the chip to sleep, but the hardware only + // supports a limited range of values so the actual sleep time might + // be smaller. The time spent in sleep will be returned (in + // milliseconds). + // int sleepMS = Watchdog.sleep(1000); // Sleep for up to 1 second. + + Serial.print("I'm awake now! I slept for "); + Serial.print(sleepMS, DEC); + Serial.println(" milliseconds."); + Serial.println(); +} diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/library.properties b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/library.properties new file mode 100644 index 0000000..c41d74b --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/library.properties @@ -0,0 +1,9 @@ +name=Adafruit SleepyDog Library +version=1.1.1 +author=Adafruit +maintainer=Adafruit +sentence=Arduino library to use the watchdog timer for system reset and low power sleep. +paragraph=Arduino library to use the watchdog timer for system reset and low power sleep. +category=Other +url=https://github.com/adafruit/Adafruit_SleepyDog +architectures=* diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp new file mode 100644 index 0000000..3355c13 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp @@ -0,0 +1,137 @@ +// Be careful to use a platform-specific conditional include to only make the +// code visible for the appropriate platform. Arduino will try to compile and +// link all .cpp files regardless of platform. +#if defined(ARDUINO_ARCH_AVR) || defined(__AVR__) + +#include +#include +#include +#include + +#include "WatchdogAVR.h" + +// Define watchdog timer interrupt. +ISR(WDT_vect) +{ + // Nothing needs to be done, however interrupt handler must be defined to + // prevent a reset. +} + +int WatchdogAVR::enable(int maxPeriodMS) { + // Pick the closest appropriate watchdog timer value. + int actualMS; + _setPeriod(maxPeriodMS, _wdto, actualMS); + // Enable the watchdog and return the actual countdown value. + wdt_enable(_wdto); + return actualMS; +} + +void WatchdogAVR::reset() { + // Reset the watchdog. + wdt_reset(); +} + +void WatchdogAVR::disable() { + // Disable the watchdog and clear any saved watchdog timer value. + wdt_disable(); + _wdto = -1; +} + +int WatchdogAVR::sleep(int maxPeriodMS) { + // Pick the closest appropriate watchdog timer value. + int sleepWDTO, actualMS; + _setPeriod(maxPeriodMS, sleepWDTO, actualMS); + + // Build watchdog prescaler register value before timing critical code. + uint8_t wdps = ((sleepWDTO & 0x08 ? 1 : 0) << WDP3) | + ((sleepWDTO & 0x04 ? 1 : 0) << WDP2) | + ((sleepWDTO & 0x02 ? 1 : 0) << WDP1) | + ((sleepWDTO & 0x01 ? 1 : 0) << WDP0); + + // The next section is timing critical so interrupts are disabled. + cli(); + // First clear any previous watchdog reset. + MCUSR &= ~(1<= 8000) || (maxMS == 0)) { + wdto = WDTO_8S; + actualMS = 8000; + } + else if (maxMS >= 4000) { + wdto = WDTO_4S; + actualMS = 4000; + } + else if (maxMS >= 2000) { + wdto = WDTO_2S; + actualMS = 2000; + } + else if (maxMS >= 1000) { + wdto = WDTO_1S; + actualMS = 1000; + } + else if (maxMS >= 500) { + wdto = WDTO_500MS; + actualMS = 500; + } + else if (maxMS >= 250) { + wdto = WDTO_250MS; + actualMS = 250; + } + else if (maxMS >= 120) { + wdto = WDTO_120MS; + actualMS = 120; + } + else if (maxMS >= 60) { + wdto = WDTO_60MS; + actualMS = 60; + } + else if (maxMS >= 30) { + wdto = WDTO_30MS; + actualMS = 30; + } + else { + wdto = WDTO_15MS; + actualMS = 15; + } +} + +#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h new file mode 100644 index 0000000..9753b08 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h @@ -0,0 +1,47 @@ +#ifndef WATCHDOGAVR_H +#define WATCHDOGAVR_H + +class WatchdogAVR { +public: + WatchdogAVR(): + _wdto(-1) + {} + + // Enable the watchdog timer to reset the machine after a period of time + // without any calls to reset(). The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware does + // not support the exact desired value. + // + // The actual period (in milliseconds) before a watchdog timer reset is + // returned. + int enable(int maxPeriodMS = 0); + + // Reset or 'kick' the watchdog timer to prevent a reset of the device. + void reset(); + + // Completely disable the watchdog timer. + void disable(); + + // Enter the lowest power sleep mode (using the watchdog timer) for the + // desired period of time. The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware does + // not support the exact desired value + // + // The actual period (in milliseconds) that the hardware was asleep will be + // returned. + int sleep(int maxPeriodMS = 0); + +private: + // Pick the closest (but not higher) watchdog timer value from the provided + // maximum period. Sets wdto to the chosen period value suitable for + // passing to wdt_enable(), and actualMS to the chosen period value in + // milliseconds. A max value of 0 will pick the longest value possible. + void _setPeriod(int maxMS, int &wdto, int &actualMS); + + // Keep the last selected watchdog timer period so that the watchdog can be + // re-enabled at that rate after sleep. A value of -1 means no watchdog + // timer was enabled. + int _wdto; +}; + +#endif \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp new file mode 100644 index 0000000..9705859 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp @@ -0,0 +1,104 @@ +// Be careful to use a platform-specific conditional include to only make the +// code visible for the appropriate platform. Arduino will try to compile and +// link all .cpp files regardless of platform. +#if defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) + +#include +#include "WatchdogKinetisK.h" + +static void one_bus_cycle(void) __attribute__((always_inline)); +static void watchdog_config(int cfg, int val); + +// Enable the watchdog timer to reset the machine after a period of time +// without any calls to reset(). The passed in period (in milliseconds) is +// just a suggestion and a lower value might be picked if the hardware does +// not support the exact desired value. +// +// The actual period (in milliseconds) before a watchdog timer reset is +// returned. +int WatchdogKinetisKseries::enable(int maxPeriodMS) +{ + if (maxPeriodMS < 4) { + maxPeriodMS = 8000; // default is 8 seconds + } + if (setting != maxPeriodMS) { + watchdog_config(WDOG_STCTRLH_WDOGEN, maxPeriodMS); + setting = maxPeriodMS; + } + return maxPeriodMS; +} + +// Reset or 'kick' the watchdog timer to prevent a reset of the device. +void WatchdogKinetisKseries::reset() +{ + __disable_irq(); + WDOG_REFRESH = 0xA602; + WDOG_REFRESH = 0xB480; + __enable_irq(); +} + +// Completely disable the watchdog timer. +void WatchdogKinetisKseries::disable() +{ + if (setting > 0) { + watchdog_config(0, 4); + setting = 0; + } +} + +// Enter the lowest power sleep mode for the desired period of time. The +// passed in period (in milliseconds) is just a suggestion and a lower value +// might be picked if the hardware does not support the exact desired value +// +// The actual period (in milliseconds) that the hardware was asleep will be +// returned. +int WatchdogKinetisKseries::sleep(int maxPeriodMS) +{ + if (maxPeriodMS <= 0) return 0; + // TODO.... + return 0; +} + +static void watchdog_config(int cfg, int val) +{ + __disable_irq(); + WDOG_UNLOCK = WDOG_UNLOCK_SEQ1; + WDOG_UNLOCK = WDOG_UNLOCK_SEQ2; + one_bus_cycle(); + WDOG_STCTRLH = cfg | WDOG_STCTRLH_ALLOWUPDATE; + WDOG_TOVALH = val >> 16; + WDOG_TOVALL = val; + WDOG_PRESC = 0; + __enable_irq(); + for (int i=0; i < 256; i++) { + one_bus_cycle(); + } +} + +static void one_bus_cycle(void) +{ + __asm__ volatile ("nop"); + #if (F_CPU / F_BUS) > 1 + __asm__ volatile ("nop"); + #endif + #if (F_CPU / F_BUS) > 2 + __asm__ volatile ("nop"); + #endif + #if (F_CPU / F_BUS) > 3 + __asm__ volatile ("nop"); + #endif + #if (F_CPU / F_BUS) > 4 + __asm__ volatile ("nop"); + #endif + #if (F_CPU / F_BUS) > 5 + __asm__ volatile ("nop"); + #endif + #if (F_CPU / F_BUS) > 6 + __asm__ volatile ("nop"); + #endif + #if (F_CPU / F_BUS) > 7 + __asm__ volatile ("nop"); + #endif +} + +#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h new file mode 100644 index 0000000..e09a0c2 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h @@ -0,0 +1,38 @@ +#ifndef WATCHDOGKINETISK_H +#define WATCHDOGKINETISK_H + +class WatchdogKinetisKseries { +public: + WatchdogKinetisKseries(): setting(0) {} + + // Enable the watchdog timer to reset the machine after a period of time + // without any calls to reset(). The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware does + // not support the exact desired value. + // + // The actual period (in milliseconds) before a watchdog timer reset is + // returned. + int enable(int maxPeriodMS = 0); + + // Reset or 'kick' the watchdog timer to prevent a reset of the device. + void reset(); + + // Completely disable the watchdog timer. + void disable(); + + // Enter the lowest power sleep mode (using the watchdog timer) for the + // desired period of time. The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware does + // not support the exact desired value + // + // The actual period (in milliseconds) that the hardware was asleep will be + // returned. + // + // NOTE: This is currently not implemented on the SAMD21! + int sleep(int maxPeriodMS = 0); + +private: + int setting; +}; + +#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp new file mode 100644 index 0000000..501e9c0 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp @@ -0,0 +1,74 @@ +// Be careful to use a platform-specific conditional include to only make the +// code visible for the appropriate platform. Arduino will try to compile and +// link all .cpp files regardless of platform. +#if defined(__MKL26Z64__) + +#include +#include "WatchdogKinetisL.h" + +// Normally the watchdog is disabled at startup. This removes the startup +// code. The watchdog will be active with 1024 ms timeout. Hopefully the +// user will configure the watchdog and begin resetting it before it causes +// a reboot. There is no way to start up without the watchdog and then +// enable it later... +extern "C" void startup_early_hook(void) {} + + +// Enable the watchdog timer to reset the machine after a period of time +// without any calls to reset(). The passed in period (in milliseconds) is +// just a suggestion and a lower value might be picked if the hardware does +// not support the exact desired value. +// +// The actual period (in milliseconds) before a watchdog timer reset is +// returned. +int WatchdogKinetisLseries::enable(int maxPeriodMS) +{ + // The watchdog can only be programmed once. Then it's forever + // locked to this setting (until the chip reboots). + if (maxPeriodMS <= 0 || maxPeriodMS > 256) { + SIM_COPC = 12; + } else if (maxPeriodMS > 32) { + SIM_COPC = 8; + } else { + SIM_COPC = 4; + } + // Read the actual setting. + int val = SIM_COPC & 12; + if (val == 12) return 1024; + if (val == 8) return 256; + return 32; +} + +// Reset or 'kick' the watchdog timer to prevent a reset of the device. +void WatchdogKinetisLseries::reset() +{ + __disable_irq(); + SIM_SRVCOP = 0x55; + SIM_SRVCOP = 0xAA; + __enable_irq(); +} + +// Completely disable the watchdog timer. +void WatchdogKinetisLseries::disable() +{ + // no can do.... + // The watchdog timer in this chip is write-once. + // The chip boots up with the watchdog at 1024 ms. + // You only get to configure it once. Then it + // remains locked to that setting, until a reboot. +} + +// Enter the lowest power sleep mode for the desired period of time. The +// passed in period (in milliseconds) is just a suggestion and a lower value +// might be picked if the hardware does not support the exact desired value +// +// The actual period (in milliseconds) that the hardware was asleep will be +// returned. +int WatchdogKinetisLseries::sleep(int maxPeriodMS) +{ + if (maxPeriodMS <= 0) return 0; + // TODO.... + return 0; +} + +#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h new file mode 100644 index 0000000..3c68d5e --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h @@ -0,0 +1,35 @@ +#ifndef WATCHDOGKINETISL_H +#define WATCHDOGKINETISL_H + +class WatchdogKinetisLseries { +public: + WatchdogKinetisLseries() {} + + // Enable the watchdog timer to reset the machine after a period of time + // without any calls to reset(). The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware does + // not support the exact desired value. + // + // The actual period (in milliseconds) before a watchdog timer reset is + // returned. + int enable(int maxPeriodMS = 0); + + // Reset or 'kick' the watchdog timer to prevent a reset of the device. + void reset(); + + // Completely disable the watchdog timer. + void disable(); + + // Enter the lowest power sleep mode (using the watchdog timer) for the + // desired period of time. The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware does + // not support the exact desired value + // + // The actual period (in milliseconds) that the hardware was asleep will be + // returned. + // + // NOTE: This is currently not implemented on the SAMD21! + int sleep(int maxPeriodMS = 0); +}; + +#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp new file mode 100644 index 0000000..d21d9a9 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp @@ -0,0 +1,175 @@ +// Requires Adafruit_ASFcore library! + +// Be careful to use a platform-specific conditional include to only make the +// code visible for the appropriate platform. Arduino will try to compile and +// link all .cpp files regardless of platform. +#if defined(ARDUINO_ARCH_SAMD) + +#include +#include +#include +#include "WatchdogSAMD.h" + +int WatchdogSAMD::enable(int maxPeriodMS, bool isForSleep) { + // Enable the watchdog with a period up to the specified max period in + // milliseconds. + + // Review the watchdog section from the SAMD21 datasheet section 17: + // http://www.atmel.com/images/atmel-42181-sam-d21_datasheet.pdf + + int cycles, actualMS; + uint8_t bits; + + if(!_initialized) _initialize_wdt(); + + WDT->CTRL.reg = 0; // Disable watchdog for config + while(WDT->STATUS.bit.SYNCBUSY); + + // You'll see some occasional conversion here compensating between + // milliseconds (1000 Hz) and WDT clock cycles (~1024 Hz). The low- + // power oscillator used by the WDT ostensibly runs at 32,768 Hz with + // a 1:32 prescale, thus 1024 Hz, though probably not super precise. + + if((maxPeriodMS >= 16000) || !maxPeriodMS) { + cycles = 16384; + bits = 0xB; + } else { + cycles = (maxPeriodMS * 1024L + 500) / 1000; // ms -> WDT cycles + if(cycles >= 8192) { + cycles = 8192; + bits = 0xA; + } else if(cycles >= 4096) { + cycles = 4096; + bits = 0x9; + } else if(cycles >= 2048) { + cycles = 2048; + bits = 0x8; + } else if(cycles >= 1024) { + cycles = 1024; + bits = 0x7; + } else if(cycles >= 512) { + cycles = 512; + bits = 0x6; + } else if(cycles >= 256) { + cycles = 256; + bits = 0x5; + } else if(cycles >= 128) { + cycles = 128; + bits = 0x4; + } else if(cycles >= 64) { + cycles = 64; + bits = 0x3; + } else if(cycles >= 32) { + cycles = 32; + bits = 0x2; + } else if(cycles >= 16) { + cycles = 16; + bits = 0x1; + } else { + cycles = 8; + bits = 0x0; + } + } + + // Watchdog timer on SAMD is a slightly different animal than on AVR. + // On AVR, the WTD timeout is configured in one register and then an + // interrupt can optionally be enabled to handle the timeout in code + // (as in waking from sleep) vs resetting the chip. Easy. + // On SAMD, when the WDT fires, that's it, the chip's getting reset. + // Instead, it has an "early warning interrupt" with a different set + // interval prior to the reset. For equivalent behavior to the AVR + // library, this requires a slightly different configuration depending + // whether we're coming from the sleep() function (which needs the + // interrupt), or just enable() (no interrupt, we want the chip reset + // unless the WDT is cleared first). In the sleep case, 'windowed' + // mode is used in order to allow access to the longest available + // sleep interval (about 16 sec); the WDT 'period' (when a reset + // occurs) follows this and is always just set to the max, since the + // interrupt will trigger first. In the enable case, windowed mode + // is not used, the WDT period is set and that's that. + // The 'isForSleep' argument determines which behavior is used; + // this isn't present in the AVR code, just here. It defaults to + // 'false' so existing Arduino code works as normal, while the sleep() + // function (later in this file) explicitly passes 'true' to get the + // alternate behavior. + + if(isForSleep) { + WDT->INTENSET.bit.EW = 1; // Enable early warning interrupt + WDT->CONFIG.bit.PER = 0xB; // Period = max + WDT->CONFIG.bit.WINDOW = bits; // Set time of interrupt + WDT->CTRL.bit.WEN = 1; // Enable window mode + while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write + } else { + WDT->INTENCLR.bit.EW = 1; // Disable early warning interrupt + WDT->CONFIG.bit.PER = bits; // Set period for chip reset + WDT->CTRL.bit.WEN = 0; // Disable window mode + while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write + } + + actualMS = (cycles * 1000L + 512) / 1024; // WDT cycles -> ms + + reset(); // Clear watchdog interval + WDT->CTRL.bit.ENABLE = 1; // Start watchdog now! + while(WDT->STATUS.bit.SYNCBUSY); + + return actualMS; +} + +void WatchdogSAMD::reset() { + // Write the watchdog clear key value (0xA5) to the watchdog + // clear register to clear the watchdog timer and reset it. + WDT->CLEAR.reg = WDT_CLEAR_CLEAR_KEY; + while(WDT->STATUS.bit.SYNCBUSY); +} + +void WatchdogSAMD::disable() { + WDT->CTRL.bit.ENABLE = 0; + while(WDT->STATUS.bit.SYNCBUSY); +} + +void WDT_Handler(void) { + // ISR for watchdog early warning, DO NOT RENAME! + WDT->CTRL.bit.ENABLE = 0; // Disable watchdog + while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write + WDT->INTFLAG.bit.EW = 1; // Clear interrupt flag +} + +int WatchdogSAMD::sleep(int maxPeriodMS) { + + int actualPeriodMS = enable(maxPeriodMS, true); // true = for sleep + + system_set_sleepmode(SYSTEM_SLEEPMODE_STANDBY); // Deepest sleep + system_sleep(); + // Code resumes here on wake (WDT early warning interrupt) + + return actualPeriodMS; +} + +void WatchdogSAMD::_initialize_wdt() { + // One-time initialization of watchdog timer. + // Insights from rickrlh and rbrucemtl in Arduino forum! + + // Generic clock generator 2, divisor = 32 (2^(DIV+1)) + GCLK->GENDIV.reg = GCLK_GENDIV_ID(2) | GCLK_GENDIV_DIV(4); + // Enable clock generator 2 using low-power 32KHz oscillator. + // With /32 divisor above, this yields 1024Hz(ish) clock. + GCLK->GENCTRL.reg = GCLK_GENCTRL_ID(2) | + GCLK_GENCTRL_GENEN | + GCLK_GENCTRL_SRC_OSCULP32K | + GCLK_GENCTRL_DIVSEL; + while(GCLK->STATUS.bit.SYNCBUSY); + // WDT clock = clock gen 2 + GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID_WDT | + GCLK_CLKCTRL_CLKEN | + GCLK_CLKCTRL_GEN_GCLK2; + + // Enable WDT early-warning interrupt + NVIC_DisableIRQ(WDT_IRQn); + NVIC_ClearPendingIRQ(WDT_IRQn); + NVIC_SetPriority(WDT_IRQn, 0); // Top priority + NVIC_EnableIRQ(WDT_IRQn); + + _initialized = true; +} + +#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h new file mode 100644 index 0000000..8b03c27 --- /dev/null +++ b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h @@ -0,0 +1,43 @@ +#ifndef WATCHDOGSAMD_H +#define WATCHDOGSAMD_H + +class WatchdogSAMD { +public: + WatchdogSAMD(): + _initialized(false) + {} + + // Enable the watchdog timer to reset the machine after a period of time + // without any calls to reset(). The passed in period (in milliseconds) + // is just a suggestion and a lower value might be picked if the hardware + // does not support the exact desired value. + // User code should NOT set the 'isForSleep' argument either way -- + // it's used internally by the library, but your sketch should leave this + // out when calling enable(), just let the default have its way. + // + // The actual period (in milliseconds) before a watchdog timer reset is + // returned. + int enable(int maxPeriodMS = 0, bool isForSleep = false); + + // Reset or 'kick' the watchdog timer to prevent a reset of the device. + void reset(); + + // Completely disable the watchdog timer. + void disable(); + + // Enter the lowest power sleep mode (using the watchdog timer) for the + // desired period of time. The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware + // does not support the exact desired value + // + // The actual period (in milliseconds) that the hardware was asleep will be + // returned. + int sleep(int maxPeriodMS = 0); + +private: + void _initialize_wdt(); + + bool _initialized; +}; + +#endif diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/.gitignore b/feather_sensor_transmit/libraries/ArduinoHttpClient/.gitignore new file mode 100644 index 0000000..89d225a --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/.gitignore @@ -0,0 +1,2 @@ +.development +examples/node_test_server/node_modules/ diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/CHANGELOG.md b/feather_sensor_transmit/libraries/ArduinoHttpClient/CHANGELOG.md new file mode 100644 index 0000000..5645508 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/CHANGELOG.md @@ -0,0 +1,25 @@ +## ArduinoHttpClient 0.3.1 - 2017.09.25 + +* Changed examples to support Arduino Create secret tabs +* Increase WebSocket secrect-key length to 24 characters + +## ArduinoHttpClient 0.3.0 - 2017.04.20 + +* Added support for PATCH operations +* Added support for chunked response bodies +* Added new beginBody API + +## ArduinoHttpClient 0.2.0 - 2017.01.12 + +* Added PATCH method +* Added basic auth example +* Added custom header example + +## ArduinoHttpClient 0.1.1 - 2016.12.16 + +* More robust response parser + +## ArduinoHttpClient 0.1.0 - 2016.07.05 + +* Initial release + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/README.md b/feather_sensor_transmit/libraries/ArduinoHttpClient/README.md new file mode 100644 index 0000000..655b618 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/README.md @@ -0,0 +1,22 @@ +# ArduinoHttpClient + +ArduinoHttpClient is a library to make it easier to interact with web servers from Arduino. + +Derived from [Adrian McEwen's HttpClient library](https://github.com/amcewen/HttpClient) + +## Dependencies + +- Requires a networking hardware and a library that provides transport specific `Client` instance, such as: + - [WiFi101](https://github.com/arduino-libraries/WiFi101) + - [Ethernet](https://github.com/arduino-libraries/Ethernet) + - [WiFi](https://github.com/arduino-libraries/WiFi) + - [GSM](https://github.com/arduino-libraries/GSM) + +## Usage + +In normal usage, handles the outgoing request and Host header. The returned status code is parsed for you, as is the Content-Length header (if present). + +Because it expects an object of type Client, you can use it with any of the networking classes that derive from that. Which means it will work with WiFiClient, EthernetClient and GSMClient. + +See the examples for more detail on how the library is used. + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino new file mode 100644 index 0000000..e793d47 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino @@ -0,0 +1,69 @@ +/* + GET client with HTTP basic authentication for ArduinoHttpClient library + Connects to server once every five seconds, sends a GET request + + + + created 14 Feb 2016 + by Tom Igoe + modified 3 Jan 2017 to add HTTP basic authentication + by Sandeep Mistry + + this example is in the public domain + */ +#include +#include +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("making GET request with HTTP basic authentication"); + client.beginRequest(); + client.get("/secure"); + client.sendBasicAuth("username", "password"); // send the username and password for authentication + client.endRequest(); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + Serial.println("Wait five seconds"); + delay(5000); +} + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino new file mode 100644 index 0000000..fa44aca --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino @@ -0,0 +1,96 @@ +/* + Custom request header example for the ArduinoHttpClient + library. This example sends a GET and a POST request with a custom header every 5 seconds. + + note: WiFi SSID and password are stored in config.h file. + If it is not present, add a new tab, call it "config.h" + and add the following variables: + char ssid[] = "ssid"; // your network SSID (name) + char pass[] = "password"; // your network password + + based on SimpleGet example by Tom Igoe + header modifications by Todd Treece + + this example is in the public domain + */ + +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + + Serial.println("making GET request"); + client.beginRequest(); + client.get("/"); + client.sendHeader("X-CUSTOM-HEADER", "custom_value"); + client.endRequest(); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("GET Status code: "); + Serial.println(statusCode); + Serial.print("GET Response: "); + Serial.println(response); + + Serial.println("Wait five seconds"); + delay(5000); + + Serial.println("making POST request"); + String postData = "name=Alice&age=12"; + client.beginRequest(); + client.post("/"); + client.sendHeader(HTTP_HEADER_CONTENT_TYPE, "application/x-www-form-urlencoded"); + client.sendHeader(HTTP_HEADER_CONTENT_LENGTH, postData.length()); + client.sendHeader("X-CUSTOM-HEADER", "custom_value"); + client.endRequest(); + client.write((const byte*)postData.c_str(), postData.length()); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("POST Status code: "); + Serial.println(statusCode); + Serial.print("POST Response: "); + Serial.println(response); + + Serial.println("Wait five seconds"); + delay(5000); +} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino new file mode 100644 index 0000000..51abd3f --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino @@ -0,0 +1,107 @@ +/* + Dweet.io GET client for ArduinoHttpClient library + Connects to dweet.io once every ten seconds, + sends a GET request and a request body. Uses SSL + + Shows how to use Strings to assemble path and parse content + from response. dweet.io expects: + https://dweet.io/get/latest/dweet/for/thingName + + For more on dweet.io, see https://dweet.io/play/ + + + + created 15 Feb 2016 + updated 16 Feb 2016 + by Tom Igoe + + this example is in the public domain +*/ +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + +const char serverAddress[] = "dweet.io"; // server address +int port = 80; +String dweetName = "scandalous-cheese-hoarder"; // use your own thing name here + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +int statusCode = 0; +String response; + +void setup() { + Serial.begin(9600); + while (!Serial); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + // assemble the path for the GET message: + String path = "/get/latest/dweet/for/" + dweetName; + + // send the GET request + Serial.println("making GET request"); + client.get(path); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + /* + Typical response is: + {"this":"succeeded", + "by":"getting", + "the":"dweets", + "with":[{"thing":"my-thing-name", + "created":"2016-02-16T05:10:36.589Z", + "content":{"sensorValue":456}}]} + + You want "content": numberValue + */ + // now parse the response looking for "content": + int labelStart = response.indexOf("content\":"); + // find the first { after "content": + int contentStart = response.indexOf("{", labelStart); + // find the following } and get what's between the braces: + int contentEnd = response.indexOf("}", labelStart); + String content = response.substring(contentStart + 1, contentEnd); + Serial.println(content); + + // now get the value after the colon, and convert to an int: + int valueStart = content.indexOf(":"); + String valueString = content.substring(valueStart + 1); + int number = valueString.toInt(); + Serial.print("Value string: "); + Serial.println(valueString); + Serial.print("Actual value: "); + Serial.println(number); + + Serial.println("Wait ten seconds\n"); + delay(10000); +} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino new file mode 100644 index 0000000..41c6f2f --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino @@ -0,0 +1,87 @@ +/* + Dweet.io POST client for ArduinoHttpClient library + Connects to dweet.io once every ten seconds, + sends a POST request and a request body. + + Shows how to use Strings to assemble path and body + + note: WiFi SSID and password are stored in config.h file. + If it is not present, add a new tab, call it "config.h" + and add the following variables: + char ssid[] = "ssid"; // your network SSID (name) + char pass[] = "password"; // your network password + + created 15 Feb 2016 + by Tom Igoe + + this example is in the public domain +*/ +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + +const char serverAddress[] = "dweet.io"; // server address +int port = 80; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +int statusCode = 0; +String response; + +void setup() { + Serial.begin(9600); + while(!Serial); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + // assemble the path for the POST message: + String dweetName = "scandalous-cheese-hoarder"; + String path = "/dweet/for/" + dweetName; + + String contentType = "application/json"; + + // assemble the body of the POST message: + int sensorValue = analogRead(A0); + String postData = "{\"sensorValue\":\""; + postData += sensorValue; + postData += "\"}"; + + Serial.println("making POST request"); + + // send the POST request + client.post(path, contentType, postData); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + Serial.println("Wait ten seconds\n"); + delay(10000); +} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino new file mode 100644 index 0000000..c18ae47 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino @@ -0,0 +1,102 @@ +/* HueBlink example for ArduinoHttpClient library + + Uses ArduinoHttpClient library to control Philips Hue + For more on Hue developer API see http://developer.meethue.com + + To control a light, the Hue expects a HTTP PUT request to: + + http://hue.hub.address/api/hueUserName/lights/lightNumber/state + + The body of the PUT request looks like this: + {"on": true} or {"on":false} + + This example shows how to concatenate Strings to assemble the + PUT request and the body of the request. + + + + modified 15 Feb 2016 + by Tom Igoe (tigoe) to match new API +*/ + +#include +#include +#include +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + +int status = WL_IDLE_STATUS; // the Wifi radio's status + +char hueHubIP[] = "192.168.0.3"; // IP address of the HUE bridge +String hueUserName = "huebridgeusername"; // hue bridge username + +// make a wifi instance and a HttpClient instance: +WiFiClient wifi; +HttpClient httpClient = HttpClient(wifi, hueHubIP); + + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial); // wait for serial port to connect. + + // attempt to connect to Wifi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to WPA SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // you're connected now, so print out the data: + Serial.print("You're connected to the network IP = "); + IPAddress ip = WiFi.localIP(); + Serial.println(ip); +} + +void loop() { + sendRequest(3, "on", "true"); // turn light on + delay(2000); // wait 2 seconds + sendRequest(3, "on", "false"); // turn light off + delay(2000); // wait 2 seconds +} + +void sendRequest(int light, String cmd, String value) { + // make a String for the HTTP request path: + String request = "/api/" + hueUserName; + request += "/lights/"; + request += light; + request += "/state/"; + + String contentType = "application/json"; + + // make a string for the JSON command: + String hueCmd = "{\"" + cmd; + hueCmd += "\":"; + hueCmd += value; + hueCmd += "}"; + // see what you assembled to send: + Serial.print("PUT request to server: "); + Serial.println(request); + Serial.print("JSON command to server: "); + + // make the PUT request to the hub: + httpClient.put(request, contentType, hueCmd); + + // read the status code and body of the response + int statusCode = httpClient.responseStatusCode(); + String response = httpClient.responseBody(); + + Serial.println(hueCmd); + Serial.print("Status code from server: "); + Serial.println(statusCode); + Serial.print("Server response: "); + Serial.println(response); + Serial.println(); +} + + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino new file mode 100644 index 0000000..835a26f --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino @@ -0,0 +1,79 @@ +/* + POST with headers client for ArduinoHttpClient library + Connects to server once every five seconds, sends a POST request + with custome headers and a request body + + + + created 14 Feb 2016 + by Tom Igoe + modified 18 Mar 2017 + by Sandeep Mistry + + this example is in the public domain + */ +#include +#include + +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("making POST request"); + String postData = "name=Alice&age=12"; + + client.beginRequest(); + client.post("/"); + client.sendHeader("Content-Type", "application/x-www-form-urlencoded"); + client.sendHeader("Content-Length", postData.length()); + client.sendHeader("X-Custom-Header", "custom-header-value"); + client.beginBody(); + client.print(postData); + client.endRequest(); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + Serial.println("Wait five seconds"); + delay(5000); +} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino new file mode 100644 index 0000000..374a145 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino @@ -0,0 +1,71 @@ +/* + Simple DELETE client for ArduinoHttpClient library + Connects to server once every five seconds, sends a DELETE request + and a request body + + + + created 14 Feb 2016 + by Tom Igoe + + this example is in the public domain + */ +#include +#include + +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("making DELETE request"); + String contentType = "application/x-www-form-urlencoded"; + String delData = "name=light&age=46"; + + client.del("/", contentType, delData); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + Serial.println("Wait five seconds"); + delay(5000); +} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino new file mode 100644 index 0000000..75db9a7 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino @@ -0,0 +1,66 @@ +/* + Simple GET client for ArduinoHttpClient library + Connects to server once every five seconds, sends a GET request + + + + created 14 Feb 2016 + by Tom Igoe + + this example is in the public domain + */ +#include +#include + +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("making GET request"); + client.get("/"); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + Serial.println("Wait five seconds"); + delay(5000); +} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino new file mode 100644 index 0000000..f64b9ba --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino @@ -0,0 +1,133 @@ +// (c) Copyright 2010-2012 MCQN Ltd. +// Released under Apache License, version 2.0 +// +// Simple example to show how to use the HttpClient library +// Get's the web page given at http:// and +// outputs the content to the serial port + +#include +#include +#include + +// This example downloads the URL "http://arduino.cc/" + +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + + + +// Name of the server we want to connect to +const char kHostname[] = "arduino.cc"; +// Path to download (this is the bit after the hostname in the URL +// that you want to download +const char kPath[] = "/"; + +// Number of milliseconds to wait without receiving any data before we give up +const int kNetworkTimeout = 30*1000; +// Number of milliseconds to wait if no data is available before trying again +const int kNetworkDelay = 1000; + +WiFiClient c; +HttpClient http(c, kHostname); + +void setup() +{ + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // attempt to connect to Wifi network: + Serial.print("Attempting to connect to WPA SSID: "); + Serial.println(ssid); + while (WiFi.begin(ssid, pass) != WL_CONNECTED) { + // unsuccessful, retry in 4 seconds + Serial.print("failed ... "); + delay(4000); + Serial.print("retrying ... "); + } + + Serial.println("connected"); +} + +void loop() +{ + int err =0; + + err = http.get(kPath); + if (err == 0) + { + Serial.println("startedRequest ok"); + + err = http.responseStatusCode(); + if (err >= 0) + { + Serial.print("Got status code: "); + Serial.println(err); + + // Usually you'd check that the response code is 200 or a + // similar "success" code (200-299) before carrying on, + // but we'll print out whatever response we get + + // If you are interesting in the response headers, you + // can read them here: + //while(http.headerAvailable()) + //{ + // String headerName = http.readHeaderName(); + // String headerValue = http.readHeaderValue(); + //} + + int bodyLen = http.contentLength(); + Serial.print("Content length is: "); + Serial.println(bodyLen); + Serial.println(); + Serial.println("Body returned follows:"); + + // Now we've got to the body, so we can print it out + unsigned long timeoutStart = millis(); + char c; + // Whilst we haven't timed out & haven't reached the end of the body + while ( (http.connected() || http.available()) && + (!http.endOfBodyReached()) && + ((millis() - timeoutStart) < kNetworkTimeout) ) + { + if (http.available()) + { + c = http.read(); + // Print out this character + Serial.print(c); + + // We read something, reset the timeout counter + timeoutStart = millis(); + } + else + { + // We haven't got any data, so let's pause to allow some to + // arrive + delay(kNetworkDelay); + } + } + } + else + { + Serial.print("Getting response failed: "); + Serial.println(err); + } + } + else + { + Serial.print("Connect failed: "); + Serial.println(err); + } + http.stop(); + + // And just stop, now that we've tried a download + while(1); +} + + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino new file mode 100644 index 0000000..6cc3517 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino @@ -0,0 +1,70 @@ +/* + Simple POST client for ArduinoHttpClient library + Connects to server once every five seconds, sends a POST request + and a request body + + + + created 14 Feb 2016 + by Tom Igoe + + this example is in the public domain + */ +#include +#include +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("making POST request"); + String contentType = "application/x-www-form-urlencoded"; + String postData = "name=Alice&age=12"; + + client.post("/", contentType, postData); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + Serial.println("Wait five seconds"); + delay(5000); +} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino new file mode 100644 index 0000000..1b06105 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino @@ -0,0 +1,70 @@ +/* + Simple PUT client for ArduinoHttpClient library + Connects to server once every five seconds, sends a PUT request + and a request body + + + + created 14 Feb 2016 + by Tom Igoe + + this example is in the public domain + */ +#include +#include +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("making PUT request"); + String contentType = "application/x-www-form-urlencoded"; + String putData = "name=light&age=46"; + + client.put("/", contentType, putData); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + Serial.println("Wait five seconds"); + delay(5000); +} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino new file mode 100644 index 0000000..baac12f --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino @@ -0,0 +1,80 @@ +/* + Simple WebSocket client for ArduinoHttpClient library + Connects to the WebSocket server, and sends a hello + message every 5 seconds + + + created 28 Jun 2016 + by Sandeep Mistry + + this example is in the public domain +*/ +#include +#include +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + +char serverAddress[] = "echo.websocket.org"; // server address +int port = 80; + +WiFiClient wifi; +WebSocketClient client = WebSocketClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +int count = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("starting WebSocket client"); + client.begin(); + + while (client.connected()) { + Serial.print("Sending hello "); + Serial.println(count); + + // send a hello # + client.beginMessage(TYPE_TEXT); + client.print("hello "); + client.print(count); + client.endMessage(); + + // increment count for next message + count++; + + // check if a message is available to be received + int messageSize = client.parseMessage(); + + if (messageSize > 0) { + Serial.println("Received a message:"); + Serial.println(client.readString()); + } + + // wait 5 seconds + delay(5000); + } + + Serial.println("disconnected"); +} + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js new file mode 100644 index 0000000..f3dd4d8 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js @@ -0,0 +1,102 @@ +/* + Express.js GET/POST example + Shows how handle GET, POST, PUT, DELETE + in Express.js 4.0 + + created 14 Feb 2016 + by Tom Igoe +*/ + +var express = require('express'); // include express.js +var app = express(); // a local instance of it +var bodyParser = require('body-parser'); // include body-parser +var WebSocketServer = require('ws').Server // include Web Socket server + +// you need a body parser: +app.use(bodyParser.urlencoded({extended: false})); // for application/x-www-form-urlencoded + +// this runs after the server successfully starts: +function serverStart() { + var port = server.address().port; + console.log('Server listening on port '+ port); +} + +app.get('/chunked', function(request, response) { + response.write('\n'); + response.write(' `:;;;,` .:;;:. \n'); + response.write(' .;;;;;;;;;;;` :;;;;;;;;;;: TM \n'); + response.write(' `;;;;;;;;;;;;;;;` :;;;;;;;;;;;;;;; \n'); + response.write(' :;;;;;;;;;;;;;;;;;; `;;;;;;;;;;;;;;;;;; \n'); + response.write(' ;;;;;;;;;;;;;;;;;;;;; .;;;;;;;;;;;;;;;;;;;; \n'); + response.write(' ;;;;;;;;:` `;;;;;;;;; ,;;;;;;;;.` .;;;;;;;; \n'); + response.write(' .;;;;;;, :;;;;;;; .;;;;;;; ;;;;;;; \n'); + response.write(' ;;;;;; ;;;;;;; ;;;;;;, ;;;;;;. \n'); + response.write(' ,;;;;; ;;;;;;.;;;;;;` ;;;;;; \n'); + response.write(' ;;;;;. ;;;;;;;;;;;` ``` ;;;;;`\n'); + response.write(' ;;;;; ;;;;;;;;;, ;;; .;;;;;\n'); + response.write('`;;;;: `;;;;;;;; ;;; ;;;;;\n'); + response.write(',;;;;` `,,,,,,,, ;;;;;;; .,,;;;,,, ;;;;;\n'); + response.write(':;;;;` .;;;;;;;; ;;;;;, :;;;;;;;; ;;;;;\n'); + response.write(':;;;;` .;;;;;;;; `;;;;;; :;;;;;;;; ;;;;;\n'); + response.write('.;;;;. ;;;;;;;. ;;; ;;;;;\n'); + response.write(' ;;;;; ;;;;;;;;; ;;; ;;;;;\n'); + response.write(' ;;;;; .;;;;;;;;;; ;;; ;;;;;,\n'); + response.write(' ;;;;;; `;;;;;;;;;;;; ;;;;; \n'); + response.write(' `;;;;;, .;;;;;; ;;;;;;; ;;;;;; \n'); + response.write(' ;;;;;;: :;;;;;;. ;;;;;;; ;;;;;; \n'); + response.write(' ;;;;;;;` .;;;;;;;, ;;;;;;;; ;;;;;;;: \n'); + response.write(' ;;;;;;;;;:,:;;;;;;;;;: ;;;;;;;;;;:,;;;;;;;;;; \n'); + response.write(' `;;;;;;;;;;;;;;;;;;;. ;;;;;;;;;;;;;;;;;;;; \n'); + response.write(' ;;;;;;;;;;;;;;;;; :;;;;;;;;;;;;;;;;: \n'); + response.write(' ,;;;;;;;;;;;;;, ;;;;;;;;;;;;;; \n'); + response.write(' .;;;;;;;;;` ,;;;;;;;;: \n'); + response.write(' \n'); + response.write(' \n'); + response.write(' \n'); + response.write(' \n'); + response.write(' ;;; ;;;;;` ;;;;: .;; ;; ,;;;;;, ;;. `;, ;;;; \n'); + response.write(' ;;; ;;:;;; ;;;;;; .;; ;; ,;;;;;: ;;; `;, ;;;:;; \n'); + response.write(' ,;:; ;; ;; ;; ;; .;; ;; ,;, ;;;,`;, ;; ;; \n'); + response.write(' ;; ;: ;; ;; ;; ;; .;; ;; ,;, ;;;;`;, ;; ;;. \n'); + response.write(' ;: ;; ;;;;;: ;; ;; .;; ;; ,;, ;;`;;;, ;; ;;` \n'); + response.write(' ,;;;;; ;;`;; ;; ;; .;; ;; ,;, ;; ;;;, ;; ;; \n'); + response.write(' ;; ,;, ;; .;; ;;;;;: ;;;;;: ,;;;;;: ;; ;;, ;;;;;; \n'); + response.write(' ;; ;; ;; ;;` ;;;;. `;;;: ,;;;;;, ;; ;;, ;;;; \n'); + response.write('\n'); + response.end(); +}); + +// this is the POST handler: +app.all('/*', function (request, response) { + console.log('Got a ' + request.method + ' request'); + // the parameters of a GET request are passed in + // request.body. Pass that to formatResponse() + // for formatting: + console.log(request.headers); + if (request.method == 'GET') { + console.log(request.query); + } else { + console.log(request.body); + } + + // send the response: + response.send('OK'); + response.end(); +}); + +// start the server: +var server = app.listen(8080, serverStart); + +// create a WebSocket server and attach it to the server +var wss = new WebSocketServer({server: server}); + +wss.on('connection', function connection(ws) { + // new connection, add message listener + ws.on('message', function incoming(message) { + // received a message + console.log('received: %s', message); + + // echo it back + ws.send(message); + }); +}); diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/node_test_server/package.json b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/node_test_server/package.json new file mode 100644 index 0000000..09f2d8b --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/node_test_server/package.json @@ -0,0 +1,13 @@ +{ + "name": "node_test_server", + "version": "0.0.1", + "author": { + "name": "Tom Igoe" + }, + "dependencies": { + "body-parser": ">=1.11.0", + "express": ">=4.0.0", + "multer": "*", + "ws": "^1.1.1" + } +} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/keywords.txt b/feather_sensor_transmit/libraries/ArduinoHttpClient/keywords.txt new file mode 100644 index 0000000..27cd516 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/keywords.txt @@ -0,0 +1,64 @@ +####################################### +# Syntax Coloring Map For HttpClient +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +ArduinoHttpClient KEYWORD1 +HttpClient KEYWORD1 +WebSocketClient KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +get KEYWORD2 +post KEYWORD2 +put KEYWORD2 +patch KEYWORD2 +startRequest KEYWORD2 +beginRequest KEYWORD2 +beginBody KEYWORD2 +sendHeader KEYWORD2 +sendBasicAuth KEYWORD2 +endRequest KEYWORD2 +responseStatusCode KEYWORD2 +readHeader KEYWORD2 +skipResponseHeaders KEYWORD2 +endOfHeadersReached KEYWORD2 +endOfBodyReached KEYWORD2 +completed KEYWORD2 +contentLength KEYWORD2 +isResponseChunked KEYWORD2 +connectionKeepAlive KEYWORD2 +noDefaultRequestHeaders KEYWORD2 +headerAvailable KEYWORD2 +readHeaderName KEYWORD2 +readHeaderValue KEYWORD2 +responseBody KEYWORD2 + +beginMessage KEYWORD2 +endMessage KEYWORD2 +parseMessage KEYWORD2 +messageType KEYWORD2 +isFinal KEYWORD2 +readString KEYWORD2 +ping KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### +HTTP_SUCCESS LITERAL1 +HTTP_ERROR_CONNECTION_FAILED LITERAL1 +HTTP_ERROR_API LITERAL1 +HTTP_ERROR_TIMED_OUT LITERAL1 +HTTP_ERROR_INVALID_RESPONSE LITERAL1 + +TYPE_CONTINUATION LITERAL1 +TYPE_TEXT LITERAL1 +TYPE_BINARY LITERAL1 +TYPE_CONNECTION_CLOSE LITERAL1 +TYPE_PING LITERAL1 +TYPE_PONG LITERAL1 diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/library.json b/feather_sensor_transmit/libraries/ArduinoHttpClient/library.json new file mode 100644 index 0000000..6bbda24 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/library.json @@ -0,0 +1,12 @@ +{ + "name": "ArduinoHttpClient", + "keywords": "http, web, client, ethernet, wifi, GSM", + "description": "Easily interact with web servers from Arduino, using HTTP and WebSocket's.", + "repository": + { + "type": "git", + "url": "https://github.com/arduino-libraries/ArduinoHttpClient.git" + }, + "frameworks": "arduino", + "platforms": "*" +} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/library.properties b/feather_sensor_transmit/libraries/ArduinoHttpClient/library.properties new file mode 100644 index 0000000..2ac5bb5 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/library.properties @@ -0,0 +1,10 @@ +name=ArduinoHttpClient +version=0.3.1 +author=Arduino +maintainer=Arduino +sentence=[EXPERIMENTAL] Easily interact with web servers from Arduino, using HTTP and WebSocket's. +paragraph=This library can be used for HTTP (GET, POST, PUT, DELETE) requests to a web server. It also supports exchanging messages with WebSocket servers. Based on Adrian McEwen's HttpClient library. +category=Communication +url=https://github.com/arduino-libraries/ArduinoHttpClient +architectures=* +includes=ArduinoHttpClient.h diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h new file mode 100644 index 0000000..578733f --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h @@ -0,0 +1,11 @@ +// Library to simplify HTTP fetching on Arduino +// (c) Copyright Arduino. 2016 +// Released under Apache License, version 2.0 + +#ifndef ArduinoHttpClient_h +#define ArduinoHttpClient_h + +#include "HttpClient.h" +#include "WebSocketClient.h" + +#endif diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/HttpClient.cpp b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/HttpClient.cpp new file mode 100644 index 0000000..7517eea --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/HttpClient.cpp @@ -0,0 +1,862 @@ +// Class to simplify HTTP fetching on Arduino +// (c) Copyright 2010-2011 MCQN Ltd +// Released under Apache License, version 2.0 + +#include "HttpClient.h" +#include "b64.h" + +// Initialize constants +const char* HttpClient::kUserAgent = "Arduino/2.2.0"; +const char* HttpClient::kContentLengthPrefix = HTTP_HEADER_CONTENT_LENGTH ": "; +const char* HttpClient::kTransferEncodingChunked = HTTP_HEADER_TRANSFER_ENCODING ": " HTTP_HEADER_VALUE_CHUNKED; + +HttpClient::HttpClient(Client& aClient, const char* aServerName, uint16_t aServerPort) + : iClient(&aClient), iServerName(aServerName), iServerAddress(), iServerPort(aServerPort), + iConnectionClose(true), iSendDefaultRequestHeaders(true) +{ + resetState(); +} + +HttpClient::HttpClient(Client& aClient, const String& aServerName, uint16_t aServerPort) + : HttpClient(aClient, aServerName.c_str(), aServerPort) +{ +} + +HttpClient::HttpClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort) + : iClient(&aClient), iServerName(NULL), iServerAddress(aServerAddress), iServerPort(aServerPort), + iConnectionClose(true), iSendDefaultRequestHeaders(true) +{ + resetState(); +} + +void HttpClient::resetState() +{ + iState = eIdle; + iStatusCode = 0; + iContentLength = kNoContentLengthHeader; + iBodyLengthConsumed = 0; + iContentLengthPtr = kContentLengthPrefix; + iTransferEncodingChunkedPtr = kTransferEncodingChunked; + iIsChunked = false; + iChunkLength = 0; + iHttpResponseTimeout = kHttpResponseTimeout; +} + +void HttpClient::stop() +{ + iClient->stop(); + resetState(); +} + +void HttpClient::connectionKeepAlive() +{ + iConnectionClose = false; +} + +void HttpClient::noDefaultRequestHeaders() +{ + iSendDefaultRequestHeaders = false; +} + +void HttpClient::beginRequest() +{ + iState = eRequestStarted; +} + +int HttpClient::startRequest(const char* aURLPath, const char* aHttpMethod, + const char* aContentType, int aContentLength, const byte aBody[]) +{ + if (iState == eReadingBody || iState == eReadingChunkLength || iState == eReadingBodyChunk) + { + flushClientRx(); + + resetState(); + } + + tHttpState initialState = iState; + + if ((eIdle != iState) && (eRequestStarted != iState)) + { + return HTTP_ERROR_API; + } + + if (iConnectionClose || !iClient->connected()) + { + if (iServerName) + { + if (!iClient->connect(iServerName, iServerPort) > 0) + { +#ifdef LOGGING + Serial.println("Connection failed"); +#endif + return HTTP_ERROR_CONNECTION_FAILED; + } + } + else + { + if (!iClient->connect(iServerAddress, iServerPort) > 0) + { +#ifdef LOGGING + Serial.println("Connection failed"); +#endif + return HTTP_ERROR_CONNECTION_FAILED; + } + } + } + else + { +#ifdef LOGGING + Serial.println("Connection already open"); +#endif + } + + // Now we're connected, send the first part of the request + int ret = sendInitialHeaders(aURLPath, aHttpMethod); + + if (HTTP_SUCCESS == ret) + { + if (aContentType) + { + sendHeader(HTTP_HEADER_CONTENT_TYPE, aContentType); + } + + if (aContentLength > 0) + { + sendHeader(HTTP_HEADER_CONTENT_LENGTH, aContentLength); + } + + bool hasBody = (aBody && aContentLength > 0); + + if (initialState == eIdle || hasBody) + { + // This was a simple version of the API, so terminate the headers now + finishHeaders(); + } + // else we'll call it in endRequest or in the first call to print, etc. + + if (hasBody) + { + write(aBody, aContentLength); + } + } + + return ret; +} + +int HttpClient::sendInitialHeaders(const char* aURLPath, const char* aHttpMethod) +{ +#ifdef LOGGING + Serial.println("Connected"); +#endif + // Send the HTTP command, i.e. "GET /somepath/ HTTP/1.0" + iClient->print(aHttpMethod); + iClient->print(" "); + + iClient->print(aURLPath); + iClient->println(" HTTP/1.1"); + if (iSendDefaultRequestHeaders) + { + // The host header, if required + if (iServerName) + { + iClient->print("Host: "); + iClient->print(iServerName); + if (iServerPort != kHttpPort) + { + iClient->print(":"); + iClient->print(iServerPort); + } + iClient->println(); + } + // And user-agent string + sendHeader(HTTP_HEADER_USER_AGENT, kUserAgent); + } + + if (iConnectionClose) + { + // Tell the server to + // close this connection after we're done + sendHeader(HTTP_HEADER_CONNECTION, "close"); + } + + // Everything has gone well + iState = eRequestStarted; + return HTTP_SUCCESS; +} + +void HttpClient::sendHeader(const char* aHeader) +{ + iClient->println(aHeader); +} + +void HttpClient::sendHeader(const char* aHeaderName, const char* aHeaderValue) +{ + iClient->print(aHeaderName); + iClient->print(": "); + iClient->println(aHeaderValue); +} + +void HttpClient::sendHeader(const char* aHeaderName, const int aHeaderValue) +{ + iClient->print(aHeaderName); + iClient->print(": "); + iClient->println(aHeaderValue); +} + +void HttpClient::sendBasicAuth(const char* aUser, const char* aPassword) +{ + // Send the initial part of this header line + iClient->print("Authorization: Basic "); + // Now Base64 encode "aUser:aPassword" and send that + // This seems trickier than it should be but it's mostly to avoid either + // (a) some arbitrarily sized buffer which hopes to be big enough, or + // (b) allocating and freeing memory + // ...so we'll loop through 3 bytes at a time, outputting the results as we + // go. + // In Base64, each 3 bytes of unencoded data become 4 bytes of encoded data + unsigned char input[3]; + unsigned char output[5]; // Leave space for a '\0' terminator so we can easily print + int userLen = strlen(aUser); + int passwordLen = strlen(aPassword); + int inputOffset = 0; + for (int i = 0; i < (userLen+1+passwordLen); i++) + { + // Copy the relevant input byte into the input + if (i < userLen) + { + input[inputOffset++] = aUser[i]; + } + else if (i == userLen) + { + input[inputOffset++] = ':'; + } + else + { + input[inputOffset++] = aPassword[i-(userLen+1)]; + } + // See if we've got a chunk to encode + if ( (inputOffset == 3) || (i == userLen+passwordLen) ) + { + // We've either got to a 3-byte boundary, or we've reached then end + b64_encode(input, inputOffset, output, 4); + // NUL-terminate the output string + output[4] = '\0'; + // And write it out + iClient->print((char*)output); +// FIXME We might want to fill output with '=' characters if b64_encode doesn't +// FIXME do it for us when we're encoding the final chunk + inputOffset = 0; + } + } + // And end the header we've sent + iClient->println(); +} + +void HttpClient::finishHeaders() +{ + iClient->println(); + iState = eRequestSent; +} + +void HttpClient::flushClientRx() +{ + while (iClient->available()) + { + iClient->read(); + } +} + +void HttpClient::endRequest() +{ + beginBody(); +} + +void HttpClient::beginBody() +{ + if (iState < eRequestSent) + { + // We still need to finish off the headers + finishHeaders(); + } + // else the end of headers has already been sent, so nothing to do here +} + +int HttpClient::get(const char* aURLPath) +{ + return startRequest(aURLPath, HTTP_METHOD_GET); +} + +int HttpClient::get(const String& aURLPath) +{ + return get(aURLPath.c_str()); +} + +int HttpClient::post(const char* aURLPath) +{ + return startRequest(aURLPath, HTTP_METHOD_POST); +} + +int HttpClient::post(const String& aURLPath) +{ + return post(aURLPath.c_str()); +} + +int HttpClient::post(const char* aURLPath, const char* aContentType, const char* aBody) +{ + return post(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); +} + +int HttpClient::post(const String& aURLPath, const String& aContentType, const String& aBody) +{ + return post(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); +} + +int HttpClient::post(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) +{ + return startRequest(aURLPath, HTTP_METHOD_POST, aContentType, aContentLength, aBody); +} + +int HttpClient::put(const char* aURLPath) +{ + return startRequest(aURLPath, HTTP_METHOD_PUT); +} + +int HttpClient::put(const String& aURLPath) +{ + return put(aURLPath.c_str()); +} + +int HttpClient::put(const char* aURLPath, const char* aContentType, const char* aBody) +{ + return put(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); +} + +int HttpClient::put(const String& aURLPath, const String& aContentType, const String& aBody) +{ + return put(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); +} + +int HttpClient::put(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) +{ + return startRequest(aURLPath, HTTP_METHOD_PUT, aContentType, aContentLength, aBody); +} + +int HttpClient::patch(const char* aURLPath) +{ + return startRequest(aURLPath, HTTP_METHOD_PATCH); +} + +int HttpClient::patch(const String& aURLPath) +{ + return patch(aURLPath.c_str()); +} + +int HttpClient::patch(const char* aURLPath, const char* aContentType, const char* aBody) +{ + return patch(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); +} + +int HttpClient::patch(const String& aURLPath, const String& aContentType, const String& aBody) +{ + return patch(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); +} + +int HttpClient::patch(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) +{ + return startRequest(aURLPath, HTTP_METHOD_PATCH, aContentType, aContentLength, aBody); +} + +int HttpClient::del(const char* aURLPath) +{ + return startRequest(aURLPath, HTTP_METHOD_DELETE); +} + +int HttpClient::del(const String& aURLPath) +{ + return del(aURLPath.c_str()); +} + +int HttpClient::del(const char* aURLPath, const char* aContentType, const char* aBody) +{ + return del(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); +} + +int HttpClient::del(const String& aURLPath, const String& aContentType, const String& aBody) +{ + return del(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); +} + +int HttpClient::del(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) +{ + return startRequest(aURLPath, HTTP_METHOD_DELETE, aContentType, aContentLength, aBody); +} + +int HttpClient::responseStatusCode() +{ + if (iState < eRequestSent) + { + return HTTP_ERROR_API; + } + // The first line will be of the form Status-Line: + // HTTP-Version SP Status-Code SP Reason-Phrase CRLF + // Where HTTP-Version is of the form: + // HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT + + int c = '\0'; + do + { + // Make sure the status code is reset, and likewise the state. This + // lets us easily cope with 1xx informational responses by just + // ignoring them really, and reading the next line for a proper response + iStatusCode = 0; + iState = eRequestSent; + + unsigned long timeoutStart = millis(); + // Psuedo-regexp we're expecting before the status-code + const char* statusPrefix = "HTTP/*.* "; + const char* statusPtr = statusPrefix; + // Whilst we haven't timed out & haven't reached the end of the headers + while ((c != '\n') && + ( (millis() - timeoutStart) < iHttpResponseTimeout )) + { + if (available()) + { + c = read(); + if (c != -1) + { + switch(iState) + { + case eRequestSent: + // We haven't reached the status code yet + if ( (*statusPtr == '*') || (*statusPtr == c) ) + { + // This character matches, just move along + statusPtr++; + if (*statusPtr == '\0') + { + // We've reached the end of the prefix + iState = eReadingStatusCode; + } + } + else + { + return HTTP_ERROR_INVALID_RESPONSE; + } + break; + case eReadingStatusCode: + if (isdigit(c)) + { + // This assumes we won't get more than the 3 digits we + // want + iStatusCode = iStatusCode*10 + (c - '0'); + } + else + { + // We've reached the end of the status code + // We could sanity check it here or double-check for ' ' + // rather than anything else, but let's be lenient + iState = eStatusCodeRead; + } + break; + case eStatusCodeRead: + // We're just waiting for the end of the line now + break; + + default: + break; + }; + // We read something, reset the timeout counter + timeoutStart = millis(); + } + } + else + { + // We haven't got any data, so let's pause to allow some to + // arrive + delay(kHttpWaitForDataDelay); + } + } + if ( (c == '\n') && (iStatusCode < 200 && iStatusCode != 101) ) + { + // We've reached the end of an informational status line + c = '\0'; // Clear c so we'll go back into the data reading loop + } + } + // If we've read a status code successfully but it's informational (1xx) + // loop back to the start + while ( (iState == eStatusCodeRead) && (iStatusCode < 200 && iStatusCode != 101) ); + + if ( (c == '\n') && (iState == eStatusCodeRead) ) + { + // We've read the status-line successfully + return iStatusCode; + } + else if (c != '\n') + { + // We must've timed out before we reached the end of the line + return HTTP_ERROR_TIMED_OUT; + } + else + { + // This wasn't a properly formed status line, or at least not one we + // could understand + return HTTP_ERROR_INVALID_RESPONSE; + } +} + +int HttpClient::skipResponseHeaders() +{ + // Just keep reading until we finish reading the headers or time out + unsigned long timeoutStart = millis(); + // Whilst we haven't timed out & haven't reached the end of the headers + while ((!endOfHeadersReached()) && + ( (millis() - timeoutStart) < iHttpResponseTimeout )) + { + if (available()) + { + (void)readHeader(); + // We read something, reset the timeout counter + timeoutStart = millis(); + } + else + { + // We haven't got any data, so let's pause to allow some to + // arrive + delay(kHttpWaitForDataDelay); + } + } + if (endOfHeadersReached()) + { + // Success + return HTTP_SUCCESS; + } + else + { + // We must've timed out + return HTTP_ERROR_TIMED_OUT; + } +} + +bool HttpClient::endOfHeadersReached() +{ + return (iState == eReadingBody || iState == eReadingChunkLength || iState == eReadingBodyChunk); +}; + +int HttpClient::contentLength() +{ + // skip the response headers, if they haven't been read already + if (!endOfHeadersReached()) + { + skipResponseHeaders(); + } + + return iContentLength; +} + +String HttpClient::responseBody() +{ + int bodyLength = contentLength(); + String response; + + if (bodyLength > 0) + { + // try to reserve bodyLength bytes + if (response.reserve(bodyLength) == 0) { + // String reserve failed + return String((const char*)NULL); + } + } + + // keep on timedRead'ing, until: + // - we have a content length: body length equals consumed or no bytes + // available + // - no content length: no bytes are available + while (iBodyLengthConsumed != bodyLength) + { + int c = timedRead(); + + if (c == -1) { + // read timed out, done + break; + } + + if (!response.concat((char)c)) { + // adding char failed + return String((const char*)NULL); + } + } + + if (bodyLength > 0 && (unsigned int)bodyLength != response.length()) { + // failure, we did not read in reponse content length bytes + return String((const char*)NULL); + } + + return response; +} + +bool HttpClient::endOfBodyReached() +{ + if (endOfHeadersReached() && (contentLength() != kNoContentLengthHeader)) + { + // We've got to the body and we know how long it will be + return (iBodyLengthConsumed >= contentLength()); + } + return false; +} + +int HttpClient::available() +{ + if (iState == eReadingChunkLength) + { + while (iClient->available()) + { + char c = iClient->read(); + + if (c == '\n') + { + iState = eReadingBodyChunk; + break; + } + else if (c == '\r') + { + // no-op + } + else if (isHexadecimalDigit(c)) + { + char digit[2] = {c, '\0'}; + + iChunkLength = (iChunkLength * 16) + strtol(digit, NULL, 16); + } + } + } + + if (iState == eReadingBodyChunk && iChunkLength == 0) + { + iState = eReadingChunkLength; + } + + if (iState == eReadingChunkLength) + { + return 0; + } + + int clientAvailable = iClient->available(); + + if (iState == eReadingBodyChunk) + { + return min(clientAvailable, iChunkLength); + } + else + { + return clientAvailable; + } +} + + +int HttpClient::read() +{ + if (iIsChunked && !available()) + { + return -1; + } + + int ret = iClient->read(); + if (ret >= 0) + { + if (endOfHeadersReached() && iContentLength > 0) + { + // We're outputting the body now and we've seen a Content-Length header + // So keep track of how many bytes are left + iBodyLengthConsumed++; + } + + if (iState == eReadingBodyChunk) + { + iChunkLength--; + + if (iChunkLength == 0) + { + iState = eReadingChunkLength; + } + } + } + return ret; +} + +bool HttpClient::headerAvailable() +{ + // clear the currently store header line + iHeaderLine = ""; + + while (!endOfHeadersReached()) + { + // read a byte from the header + int c = readHeader(); + + if (c == '\r' || c == '\n') + { + if (iHeaderLine.length()) + { + // end of the line, all done + break; + } + else + { + // ignore any CR or LF characters + continue; + } + } + + // append byte to header line + iHeaderLine += (char)c; + } + + return (iHeaderLine.length() > 0); +} + +String HttpClient::readHeaderName() +{ + int colonIndex = iHeaderLine.indexOf(':'); + + if (colonIndex == -1) + { + return ""; + } + + return iHeaderLine.substring(0, colonIndex); +} + +String HttpClient::readHeaderValue() +{ + int colonIndex = iHeaderLine.indexOf(':'); + int startIndex = colonIndex + 1; + + if (colonIndex == -1) + { + return ""; + } + + // trim any leading whitespace + while (startIndex < (int)iHeaderLine.length() && isSpace(iHeaderLine[startIndex])) + { + startIndex++; + } + + return iHeaderLine.substring(startIndex); +} + +int HttpClient::read(uint8_t *buf, size_t size) +{ + int ret =iClient->read(buf, size); + if (endOfHeadersReached() && iContentLength > 0) + { + // We're outputting the body now and we've seen a Content-Length header + // So keep track of how many bytes are left + if (ret >= 0) + { + iBodyLengthConsumed += ret; + } + } + return ret; +} + +int HttpClient::readHeader() +{ + char c = read(); + + if (endOfHeadersReached()) + { + // We've passed the headers, but rather than return an error, we'll just + // act as a slightly less efficient version of read() + return c; + } + + // Whilst reading out the headers to whoever wants them, we'll keep an + // eye out for the "Content-Length" header + switch(iState) + { + case eStatusCodeRead: + // We're at the start of a line, or somewhere in the middle of reading + // the Content-Length prefix + if (*iContentLengthPtr == c) + { + // This character matches, just move along + iContentLengthPtr++; + if (*iContentLengthPtr == '\0') + { + // We've reached the end of the prefix + iState = eReadingContentLength; + // Just in case we get multiple Content-Length headers, this + // will ensure we just get the value of the last one + iContentLength = 0; + iBodyLengthConsumed = 0; + } + } + else if (*iTransferEncodingChunkedPtr == c) + { + // This character matches, just move along + iTransferEncodingChunkedPtr++; + if (*iTransferEncodingChunkedPtr == '\0') + { + // We've reached the end of the Transfer Encoding: chunked header + iIsChunked = true; + iState = eSkipToEndOfHeader; + } + } + else if (((iContentLengthPtr == kContentLengthPrefix) && (iTransferEncodingChunkedPtr == kTransferEncodingChunked)) && (c == '\r')) + { + // We've found a '\r' at the start of a line, so this is probably + // the end of the headers + iState = eLineStartingCRFound; + } + else + { + // This isn't the Content-Length or Transfer Encoding chunked header, skip to the end of the line + iState = eSkipToEndOfHeader; + } + break; + case eReadingContentLength: + if (isdigit(c)) + { + iContentLength = iContentLength*10 + (c - '0'); + } + else + { + // We've reached the end of the content length + // We could sanity check it here or double-check for "\r\n" + // rather than anything else, but let's be lenient + iState = eSkipToEndOfHeader; + } + break; + case eLineStartingCRFound: + if (c == '\n') + { + if (iIsChunked) + { + iState = eReadingChunkLength; + iChunkLength = 0; + } + else + { + iState = eReadingBody; + } + } + break; + default: + // We're just waiting for the end of the line now + break; + }; + + if ( (c == '\n') && !endOfHeadersReached() ) + { + // We've got to the end of this line, start processing again + iState = eStatusCodeRead; + iContentLengthPtr = kContentLengthPrefix; + iTransferEncodingChunkedPtr = kTransferEncodingChunked; + } + // And return the character read to whoever wants it + return c; +} + + + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/HttpClient.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/HttpClient.h new file mode 100644 index 0000000..c954872 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/HttpClient.h @@ -0,0 +1,392 @@ +// Class to simplify HTTP fetching on Arduino +// (c) Copyright MCQN Ltd. 2010-2012 +// Released under Apache License, version 2.0 + +#ifndef HttpClient_h +#define HttpClient_h + +#include +#include +#include "Client.h" + +static const int HTTP_SUCCESS =0; +// The end of the headers has been reached. This consumes the '\n' +// Could not connect to the server +static const int HTTP_ERROR_CONNECTION_FAILED =-1; +// This call was made when the HttpClient class wasn't expecting it +// to be called. Usually indicates your code is using the class +// incorrectly +static const int HTTP_ERROR_API =-2; +// Spent too long waiting for a reply +static const int HTTP_ERROR_TIMED_OUT =-3; +// The response from the server is invalid, is it definitely an HTTP +// server? +static const int HTTP_ERROR_INVALID_RESPONSE =-4; + +// Define some of the common methods and headers here +// That lets other code reuse them without having to declare another copy +// of them, so saves code space and RAM +#define HTTP_METHOD_GET "GET" +#define HTTP_METHOD_POST "POST" +#define HTTP_METHOD_PUT "PUT" +#define HTTP_METHOD_PATCH "PATCH" +#define HTTP_METHOD_DELETE "DELETE" +#define HTTP_HEADER_CONTENT_LENGTH "Content-Length" +#define HTTP_HEADER_CONTENT_TYPE "Content-Type" +#define HTTP_HEADER_CONNECTION "Connection" +#define HTTP_HEADER_TRANSFER_ENCODING "Transfer-Encoding" +#define HTTP_HEADER_USER_AGENT "User-Agent" +#define HTTP_HEADER_VALUE_CHUNKED "chunked" + +class HttpClient : public Client +{ +public: + static const int kNoContentLengthHeader =-1; + static const int kHttpPort =80; + static const char* kUserAgent; + +// FIXME Write longer API request, using port and user-agent, example +// FIXME Update tempToPachube example to calculate Content-Length correctly + + HttpClient(Client& aClient, const char* aServerName, uint16_t aServerPort = kHttpPort); + HttpClient(Client& aClient, const String& aServerName, uint16_t aServerPort = kHttpPort); + HttpClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort = kHttpPort); + + /** Start a more complex request. + Use this when you need to send additional headers in the request, + but you will also need to call endRequest() when you are finished. + */ + void beginRequest(); + + /** End a more complex request. + Use this when you need to have sent additional headers in the request, + but you will also need to call beginRequest() at the start. + */ + void endRequest(); + + /** Start the body of a more complex request. + Use this when you need to send the body after additional headers + in the request, but can optionally call endRequest() when + you are finished. + */ + void beginBody(); + + /** Connect to the server and start to send a GET request. + @param aURLPath Url to request + @return 0 if successful, else error + */ + int get(const char* aURLPath); + int get(const String& aURLPath); + + /** Connect to the server and start to send a POST request. + @param aURLPath Url to request + @return 0 if successful, else error + */ + int post(const char* aURLPath); + int post(const String& aURLPath); + + /** Connect to the server and send a POST request + with body and content type + @param aURLPath Url to request + @param aContentType Content type of request body + @param aBody Body of the request + @return 0 if successful, else error + */ + int post(const char* aURLPath, const char* aContentType, const char* aBody); + int post(const String& aURLPath, const String& aContentType, const String& aBody); + int post(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); + + /** Connect to the server and start to send a PUT request. + @param aURLPath Url to request + @return 0 if successful, else error + */ + int put(const char* aURLPath); + int put(const String& aURLPath); + + /** Connect to the server and send a PUT request + with body and content type + @param aURLPath Url to request + @param aContentType Content type of request body + @param aBody Body of the request + @return 0 if successful, else error + */ + int put(const char* aURLPath, const char* aContentType, const char* aBody); + int put(const String& aURLPath, const String& aContentType, const String& aBody); + int put(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); + + /** Connect to the server and start to send a PATCH request. + @param aURLPath Url to request + @return 0 if successful, else error + */ + int patch(const char* aURLPath); + int patch(const String& aURLPath); + + /** Connect to the server and send a PATCH request + with body and content type + @param aURLPath Url to request + @param aContentType Content type of request body + @param aBody Body of the request + @return 0 if successful, else error + */ + int patch(const char* aURLPath, const char* aContentType, const char* aBody); + int patch(const String& aURLPath, const String& aContentType, const String& aBody); + int patch(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); + + /** Connect to the server and start to send a DELETE request. + @param aURLPath Url to request + @return 0 if successful, else error + */ + int del(const char* aURLPath); + int del(const String& aURLPath); + + /** Connect to the server and send a DELETE request + with body and content type + @param aURLPath Url to request + @param aContentType Content type of request body + @param aBody Body of the request + @return 0 if successful, else error + */ + int del(const char* aURLPath, const char* aContentType, const char* aBody); + int del(const String& aURLPath, const String& aContentType, const String& aBody); + int del(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); + + /** Connect to the server and start to send the request. + If a body is provided, the entire request (including headers and body) will be sent + @param aURLPath Url to request + @param aHttpMethod Type of HTTP request to make, e.g. "GET", "POST", etc. + @param aContentType Content type of request body (optional) + @param aContentLength Length of request body (optional) + @param aBody Body of request (optional) + @return 0 if successful, else error + */ + int startRequest(const char* aURLPath, + const char* aHttpMethod, + const char* aContentType = NULL, + int aContentLength = -1, + const byte aBody[] = NULL); + + /** Send an additional header line. This can only be called in between the + calls to startRequest and finishRequest. + @param aHeader Header line to send, in its entirety (but without the + trailing CRLF. E.g. "Authorization: Basic YQDDCAIGES" + */ + void sendHeader(const char* aHeader); + + void sendHeader(const String& aHeader) + { sendHeader(aHeader.c_str()); } + + /** Send an additional header line. This is an alternate form of + sendHeader() which takes the header name and content as separate strings. + The call will add the ": " to separate the header, so for example, to + send a XXXXXX header call sendHeader("XXXXX", "Something") + @param aHeaderName Type of header being sent + @param aHeaderValue Value for that header + */ + void sendHeader(const char* aHeaderName, const char* aHeaderValue); + + void sendHeader(const String& aHeaderName, const String& aHeaderValue) + { sendHeader(aHeaderName.c_str(), aHeaderValue.c_str()); } + + /** Send an additional header line. This is an alternate form of + sendHeader() which takes the header name and content separately but where + the value is provided as an integer. + The call will add the ": " to separate the header, so for example, to + send a XXXXXX header call sendHeader("XXXXX", 123) + @param aHeaderName Type of header being sent + @param aHeaderValue Value for that header + */ + void sendHeader(const char* aHeaderName, const int aHeaderValue); + + void sendHeader(const String& aHeaderName, const int aHeaderValue) + { sendHeader(aHeaderName.c_str(), aHeaderValue); } + + /** Send a basic authentication header. This will encode the given username + and password, and send them in suitable header line for doing Basic + Authentication. + @param aUser Username for the authorization + @param aPassword Password for the user aUser + */ + void sendBasicAuth(const char* aUser, const char* aPassword); + + void sendBasicAuth(const String& aUser, const String& aPassword) + { sendBasicAuth(aUser.c_str(), aPassword.c_str()); } + + /** Get the HTTP status code contained in the response. + For example, 200 for successful request, 404 for file not found, etc. + */ + int responseStatusCode(); + + /** Check if a header is available to be read. + Use readHeaderName() to read header name, and readHeaderValue() to + read the header value + MUST be called after responseStatusCode() and before contentLength() + */ + bool headerAvailable(); + + /** Read the name of the current response header. + Returns empty string if a header is not available. + */ + String readHeaderName(); + + /** Read the vallue of the current response header. + Returns empty string if a header is not available. + */ + String readHeaderValue(); + + /** Read the next character of the response headers. + This functions in the same way as read() but to be used when reading + through the headers. Check whether or not the end of the headers has + been reached by calling endOfHeadersReached(), although after that point + this will still return data as read() would, but slightly less efficiently + MUST be called after responseStatusCode() and before contentLength() + @return The next character of the response headers + */ + int readHeader(); + + /** Skip any response headers to get to the body. + Use this if you don't want to do any special processing of the headers + returned in the response. You can also use it after you've found all of + the headers you're interested in, and just want to get on with processing + the body. + MUST be called after responseStatusCode() + @return HTTP_SUCCESS if successful, else an error code + */ + int skipResponseHeaders(); + + /** Test whether all of the response headers have been consumed. + @return true if we are now processing the response body, else false + */ + bool endOfHeadersReached(); + + /** Test whether the end of the body has been reached. + Only works if the Content-Length header was returned by the server + @return true if we are now at the end of the body, else false + */ + bool endOfBodyReached(); + virtual bool endOfStream() { return endOfBodyReached(); }; + virtual bool completed() { return endOfBodyReached(); }; + + /** Return the length of the body. + Also skips response headers if they have not been read already + MUST be called after responseStatusCode() + @return Length of the body, in bytes, or kNoContentLengthHeader if no + Content-Length header was returned by the server + */ + int contentLength(); + + /** Returns if the response body is chunked + @return true if response body is chunked, false otherwise + */ + int isResponseChunked() { return iIsChunked; } + + /** Return the response body as a String + Also skips response headers if they have not been read already + MUST be called after responseStatusCode() + @return response body of request as a String + */ + String responseBody(); + + /** Enables connection keep-alive mode + */ + void connectionKeepAlive(); + + /** Disables sending the default request headers (Host and User Agent) + */ + void noDefaultRequestHeaders(); + + // Inherited from Print + // Note: 1st call to these indicates the user is sending the body, so if need + // Note: be we should finish the header first + virtual size_t write(uint8_t aByte) { if (iState < eRequestSent) { finishHeaders(); }; return iClient-> write(aByte); }; + virtual size_t write(const uint8_t *aBuffer, size_t aSize) { if (iState < eRequestSent) { finishHeaders(); }; return iClient->write(aBuffer, aSize); }; + // Inherited from Stream + virtual int available(); + /** Read the next byte from the server. + @return Byte read or -1 if there are no bytes available. + */ + virtual int read(); + virtual int read(uint8_t *buf, size_t size); + virtual int peek() { return iClient->peek(); }; + virtual void flush() { return iClient->flush(); }; + + // Inherited from Client + virtual int connect(IPAddress ip, uint16_t port) { return iClient->connect(ip, port); }; + virtual int connect(const char *host, uint16_t port) { return iClient->connect(host, port); }; + virtual void stop(); + virtual uint8_t connected() { return iClient->connected(); }; + virtual operator bool() { return bool(iClient); }; + virtual uint32_t httpResponseTimeout() { return iHttpResponseTimeout; }; + virtual void setHttpResponseTimeout(uint32_t timeout) { iHttpResponseTimeout = timeout; }; +protected: + /** Reset internal state data back to the "just initialised" state + */ + void resetState(); + + /** Send the first part of the request and the initial headers. + @param aURLPath Url to request + @param aHttpMethod Type of HTTP request to make, e.g. "GET", "POST", etc. + @return 0 if successful, else error + */ + int sendInitialHeaders(const char* aURLPath, + const char* aHttpMethod); + + /* Let the server know that we've reached the end of the headers + */ + void finishHeaders(); + + /** Reading any pending data from the client (used in connection keep alive mode) + */ + void flushClientRx(); + + // Number of milliseconds that we wait each time there isn't any data + // available to be read (during status code and header processing) + static const int kHttpWaitForDataDelay = 1000; + // Number of milliseconds that we'll wait in total without receiveing any + // data before returning HTTP_ERROR_TIMED_OUT (during status code and header + // processing) + static const int kHttpResponseTimeout = 30*1000; + static const char* kContentLengthPrefix; + static const char* kTransferEncodingChunked; + typedef enum { + eIdle, + eRequestStarted, + eRequestSent, + eReadingStatusCode, + eStatusCodeRead, + eReadingContentLength, + eSkipToEndOfHeader, + eLineStartingCRFound, + eReadingBody, + eReadingChunkLength, + eReadingBodyChunk + } tHttpState; + // Client we're using + Client* iClient; + // Server we are connecting to + const char* iServerName; + IPAddress iServerAddress; + // Port of server we are connecting to + uint16_t iServerPort; + // Current state of the finite-state-machine + tHttpState iState; + // Stores the status code for the response, once known + int iStatusCode; + // Stores the value of the Content-Length header, if present + int iContentLength; + // How many bytes of the response body have been read by the user + int iBodyLengthConsumed; + // How far through a Content-Length header prefix we are + const char* iContentLengthPtr; + // How far through a Transfer-Encoding chunked header we are + const char* iTransferEncodingChunkedPtr; + // Stores if the response body is chunked + bool iIsChunked; + // Stores the value of the current chunk length, if present + int iChunkLength; + uint32_t iHttpResponseTimeout; + bool iConnectionClose; + bool iSendDefaultRequestHeaders; + String iHeaderLine; +}; + +#endif diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/WebSocketClient.cpp b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/WebSocketClient.cpp new file mode 100644 index 0000000..ab41b0a --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/WebSocketClient.cpp @@ -0,0 +1,372 @@ +// (c) Copyright Arduino. 2016 +// Released under Apache License, version 2.0 + +#include "b64.h" + +#include "WebSocketClient.h" + +WebSocketClient::WebSocketClient(Client& aClient, const char* aServerName, uint16_t aServerPort) + : HttpClient(aClient, aServerName, aServerPort), + iTxStarted(false), + iRxSize(0) +{ +} + +WebSocketClient::WebSocketClient(Client& aClient, const String& aServerName, uint16_t aServerPort) + : HttpClient(aClient, aServerName, aServerPort), + iTxStarted(false), + iRxSize(0) +{ +} + +WebSocketClient::WebSocketClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort) + : HttpClient(aClient, aServerAddress, aServerPort), + iTxStarted(false), + iRxSize(0) +{ +} + +int WebSocketClient::begin(const char* aPath) +{ + // start the GET request + beginRequest(); + connectionKeepAlive(); + int status = get(aPath); + + if (status == 0) + { + uint8_t randomKey[16]; + char base64RandomKey[25]; + + // create a random key for the connection upgrade + for (int i = 0; i < (int)sizeof(randomKey); i++) + { + randomKey[i] = random(0x01, 0xff); + } + memset(base64RandomKey, 0x00, sizeof(base64RandomKey)); + b64_encode(randomKey, sizeof(randomKey), (unsigned char*)base64RandomKey, sizeof(base64RandomKey)); + + // start the connection upgrade sequence + sendHeader("Upgrade", "websocket"); + sendHeader("Connection", "Upgrade"); + sendHeader("Sec-WebSocket-Key", base64RandomKey); + sendHeader("Sec-WebSocket-Version", "13"); + endRequest(); + + status = responseStatusCode(); + + if (status > 0) + { + skipResponseHeaders(); + } + } + + iRxSize = 0; + + // status code of 101 means success + return (status == 101) ? 0 : status; +} + +int WebSocketClient::begin(const String& aPath) +{ + return begin(aPath.c_str()); +} + +int WebSocketClient::beginMessage(int aType) +{ + if (iTxStarted) + { + // fail TX already started + return 1; + } + + iTxStarted = true; + iTxMessageType = (aType & 0xf); + iTxSize = 0; + + return 0; +} + +int WebSocketClient::endMessage() +{ + if (!iTxStarted) + { + // fail TX not started + return 1; + } + + // send FIN + the message type (opcode) + HttpClient::write(0x80 | iTxMessageType); + + // the message is masked (0x80) + // send the length + if (iTxSize < 126) + { + HttpClient::write(0x80 | (uint8_t)iTxSize); + } + else if (iTxSize < 0xffff) + { + HttpClient::write(0x80 | 126); + HttpClient::write((iTxSize >> 8) & 0xff); + HttpClient::write((iTxSize >> 0) & 0xff); + } + else + { + HttpClient::write(0x80 | 127); + HttpClient::write((iTxSize >> 56) & 0xff); + HttpClient::write((iTxSize >> 48) & 0xff); + HttpClient::write((iTxSize >> 40) & 0xff); + HttpClient::write((iTxSize >> 32) & 0xff); + HttpClient::write((iTxSize >> 24) & 0xff); + HttpClient::write((iTxSize >> 16) & 0xff); + HttpClient::write((iTxSize >> 8) & 0xff); + HttpClient::write((iTxSize >> 0) & 0xff); + } + + uint8_t maskKey[4]; + + // create a random mask for the data and send + for (int i = 0; i < (int)sizeof(maskKey); i++) + { + maskKey[i] = random(0xff); + } + HttpClient::write(maskKey, sizeof(maskKey)); + + // mask the data and send + for (int i = 0; i < (int)iTxSize; i++) { + iTxBuffer[i] ^= maskKey[i % sizeof(maskKey)]; + } + + size_t txSize = iTxSize; + + iTxStarted = false; + iTxSize = 0; + + return (HttpClient::write(iTxBuffer, txSize) == txSize) ? 0 : 1; +} + +size_t WebSocketClient::write(uint8_t aByte) +{ + return write(&aByte, sizeof(aByte)); +} + +size_t WebSocketClient::write(const uint8_t *aBuffer, size_t aSize) +{ + if (iState < eReadingBody) + { + // have not upgraded the connection yet + return HttpClient::write(aBuffer, aSize); + } + + if (!iTxStarted) + { + // fail TX not started + return 0; + } + + // check if the write size, fits in the buffer + if ((iTxSize + aSize) > sizeof(iTxBuffer)) + { + aSize = sizeof(iTxSize) - iTxSize; + } + + // copy data into the buffer + memcpy(iTxBuffer + iTxSize, aBuffer, aSize); + + iTxSize += aSize; + + return aSize; +} + +int WebSocketClient::parseMessage() +{ + flushRx(); + + // make sure 2 bytes (opcode + length) + // are available + if (HttpClient::available() < 2) + { + return 0; + } + + // read open code and length + uint8_t opcode = HttpClient::read(); + int length = HttpClient::read(); + + if ((opcode & 0x0f) == 0) + { + // continuation, use previous opcode and update flags + iRxOpCode |= opcode; + } + else + { + iRxOpCode = opcode; + } + + iRxMasked = (length & 0x80); + length &= 0x7f; + + // read the RX size + if (length < 126) + { + iRxSize = length; + } + else if (length == 126) + { + iRxSize = (HttpClient::read() << 8) | HttpClient::read(); + } + else + { + iRxSize = ((uint64_t)HttpClient::read() << 56) | + ((uint64_t)HttpClient::read() << 48) | + ((uint64_t)HttpClient::read() << 40) | + ((uint64_t)HttpClient::read() << 32) | + ((uint64_t)HttpClient::read() << 24) | + ((uint64_t)HttpClient::read() << 16) | + ((uint64_t)HttpClient::read() << 8) | + (uint64_t)HttpClient::read(); + } + + // read in the mask, if present + if (iRxMasked) + { + for (int i = 0; i < (int)sizeof(iRxMaskKey); i++) + { + iRxMaskKey[i] = HttpClient::read(); + } + } + + iRxMaskIndex = 0; + + if (TYPE_CONNECTION_CLOSE == messageType()) + { + flushRx(); + stop(); + iRxSize = 0; + } + else if (TYPE_PING == messageType()) + { + beginMessage(TYPE_PONG); + while(available()) + { + write(read()); + } + endMessage(); + + iRxSize = 0; + } + else if (TYPE_PONG == messageType()) + { + flushRx(); + iRxSize = 0; + } + + return iRxSize; +} + +int WebSocketClient::messageType() +{ + return (iRxOpCode & 0x0f); +} + +bool WebSocketClient::isFinal() +{ + return ((iRxOpCode & 0x80) != 0); +} + +String WebSocketClient::readString() +{ + int avail = available(); + String s; + + if (avail > 0) + { + s.reserve(avail); + + for (int i = 0; i < avail; i++) + { + s += (char)read(); + } + } + + return s; +} + +int WebSocketClient::ping() +{ + uint8_t pingData[16]; + + // create random data for the ping + for (int i = 0; i < (int)sizeof(pingData); i++) + { + pingData[i] = random(0xff); + } + + beginMessage(TYPE_PING); + write(pingData, sizeof(pingData)); + return endMessage(); +} + +int WebSocketClient::available() +{ + if (iState < eReadingBody) + { + return HttpClient::available(); + } + + return iRxSize; +} + +int WebSocketClient::read() +{ + byte b; + + if (read(&b, sizeof(b))) + { + return b; + } + + return -1; +} + +int WebSocketClient::read(uint8_t *aBuffer, size_t aSize) +{ + int readCount = HttpClient::read(aBuffer, aSize); + + if (readCount > 0) + { + iRxSize -= readCount; + + // unmask the RX data if needed + if (iRxMasked) + { + for (int i = 0; i < (int)aSize; i++, iRxMaskIndex++) + { + aBuffer[i] ^= iRxMaskKey[iRxMaskIndex % sizeof(iRxMaskKey)]; + } + } + } + + return readCount; +} + +int WebSocketClient::peek() +{ + int p = HttpClient::peek(); + + if (p != -1 && iRxMasked) + { + // unmask the RX data if needed + p = (uint8_t)p ^ iRxMaskKey[iRxMaskIndex % sizeof(iRxMaskKey)]; + } + + return p; +} + +void WebSocketClient::flushRx() +{ + while(available()) + { + read(); + } +} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/WebSocketClient.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/WebSocketClient.h new file mode 100644 index 0000000..4b009e6 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/WebSocketClient.h @@ -0,0 +1,99 @@ +// (c) Copyright Arduino. 2016 +// Released under Apache License, version 2.0 + +#ifndef WebSocketClient_h +#define WebSocketClient_h + +#include + +#include "HttpClient.h" + +static const int TYPE_CONTINUATION = 0x0; +static const int TYPE_TEXT = 0x1; +static const int TYPE_BINARY = 0x2; +static const int TYPE_CONNECTION_CLOSE = 0x8; +static const int TYPE_PING = 0x9; +static const int TYPE_PONG = 0xa; + +class WebSocketClient : public HttpClient +{ +public: + WebSocketClient(Client& aClient, const char* aServerName, uint16_t aServerPort = HttpClient::kHttpPort); + WebSocketClient(Client& aClient, const String& aServerName, uint16_t aServerPort = HttpClient::kHttpPort); + WebSocketClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort = HttpClient::kHttpPort); + + /** Start the Web Socket connection to the specified path + @param aURLPath Path to use in request (optional, "/" is used by default) + @return 0 if successful, else error + */ + int begin(const char* aPath = "/"); + int begin(const String& aPath); + + /** Begin to send a message of type (TYPE_TEXT or TYPE_BINARY) + Use the write or Stream API's to set message content, followed by endMessage + to complete the message. + @param aURLPath Path to use in request + @return 0 if successful, else error + */ + int beginMessage(int aType); + + /** Completes sending of a message started by beginMessage + @return 0 if successful, else error + */ + int endMessage(); + + /** Try to parse an incoming messages + @return 0 if no message available, else size of parsed message + */ + int parseMessage(); + + /** Returns type of current parsed message + @return type of current parsedMessage (TYPE_TEXT or TYPE_BINARY) + */ + int messageType(); + + /** Returns if the current message is the final chunk of a split + message + @return true for final message, false otherwise + */ + bool isFinal(); + + /** Read the current messages as a string + @return current message as a string + */ + String readString(); + + /** Send a ping + @return 0 if successful, else error + */ + int ping(); + + // Inherited from Print + virtual size_t write(uint8_t aByte); + virtual size_t write(const uint8_t *aBuffer, size_t aSize); + // Inherited from Stream + virtual int available(); + /** Read the next byte from the server. + @return Byte read or -1 if there are no bytes available. + */ + virtual int read(); + virtual int read(uint8_t *buf, size_t size); + virtual int peek(); + +private: + void flushRx(); + +private: + bool iTxStarted; + uint8_t iTxMessageType; + uint8_t iTxBuffer[128]; + uint64_t iTxSize; + + uint8_t iRxOpCode; + uint64_t iRxSize; + bool iRxMasked; + int iRxMaskIndex; + uint8_t iRxMaskKey[4]; +}; + +#endif diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/b64.cpp b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/b64.cpp new file mode 100644 index 0000000..683d60a --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/b64.cpp @@ -0,0 +1,72 @@ +// Simple Base64 code +// (c) Copyright 2010 MCQN Ltd. +// Released under Apache License, version 2.0 + +#include "b64.h" + +/* Simple test program +#include +void main() +{ + char* in = "amcewen"; + char out[22]; + + b64_encode(in, 15, out, 22); + out[21] = '\0'; + + printf(out); +} +*/ + +int b64_encode(const unsigned char* aInput, int aInputLen, unsigned char* aOutput, int aOutputLen) +{ + // Work out if we've got enough space to encode the input + // Every 6 bits of input becomes a byte of output + if (aOutputLen < (aInputLen*8)/6) + { + // FIXME Should we return an error here, or just the length + return (aInputLen*8)/6; + } + + // If we get here we've got enough space to do the encoding + + const char* b64_dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + if (aInputLen == 3) + { + aOutput[0] = b64_dictionary[aInput[0] >> 2]; + aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4|(aInput[1]>>4)]; + aOutput[2] = b64_dictionary[(aInput[1]&0x0F)<<2|(aInput[2]>>6)]; + aOutput[3] = b64_dictionary[aInput[2]&0x3F]; + } + else if (aInputLen == 2) + { + aOutput[0] = b64_dictionary[aInput[0] >> 2]; + aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4|(aInput[1]>>4)]; + aOutput[2] = b64_dictionary[(aInput[1]&0x0F)<<2]; + aOutput[3] = '='; + } + else if (aInputLen == 1) + { + aOutput[0] = b64_dictionary[aInput[0] >> 2]; + aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4]; + aOutput[2] = '='; + aOutput[3] = '='; + } + else + { + // Break the input into 3-byte chunks and process each of them + int i; + for (i = 0; i < aInputLen/3; i++) + { + b64_encode(&aInput[i*3], 3, &aOutput[i*4], 4); + } + if (aInputLen % 3 > 0) + { + // It doesn't fit neatly into a 3-byte chunk, so process what's left + b64_encode(&aInput[i*3], aInputLen % 3, &aOutput[i*4], aOutputLen - (i*4)); + } + } + + return ((aInputLen+2)/3)*4; +} + diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/b64.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/b64.h new file mode 100644 index 0000000..cdb1226 --- /dev/null +++ b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/b64.h @@ -0,0 +1,6 @@ +#ifndef b64_h +#define b64_h + +int b64_encode(const unsigned char* aInput, int aInputLen, unsigned char* aOutput, int aOutputLen); + +#endif diff --git a/feather_sensor_transmit/libraries/DHT/.github/ISSUE_TEMPLATE.md b/feather_sensor_transmit/libraries/DHT/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..f0e2614 --- /dev/null +++ b/feather_sensor_transmit/libraries/DHT/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,46 @@ +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/feather_sensor_transmit/libraries/DHT/.github/PULL_REQUEST_TEMPLATE.md b/feather_sensor_transmit/libraries/DHT/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..7b641eb --- /dev/null +++ b/feather_sensor_transmit/libraries/DHT/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,26 @@ +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/feather_sensor_transmit/libraries/DHT/DHT.cpp b/feather_sensor_transmit/libraries/DHT/DHT.cpp new file mode 100644 index 0000000..86ad91c --- /dev/null +++ b/feather_sensor_transmit/libraries/DHT/DHT.cpp @@ -0,0 +1,259 @@ +/* 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/feather_sensor_transmit/libraries/DHT/DHT.h b/feather_sensor_transmit/libraries/DHT/DHT.h new file mode 100644 index 0000000..d81f6db --- /dev/null +++ b/feather_sensor_transmit/libraries/DHT/DHT.h @@ -0,0 +1,75 @@ +/* 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/feather_sensor_transmit/libraries/DHT/DHT_U.cpp b/feather_sensor_transmit/libraries/DHT/DHT_U.cpp new file mode 100644 index 0000000..efc7963 --- /dev/null +++ b/feather_sensor_transmit/libraries/DHT/DHT_U.cpp @@ -0,0 +1,179 @@ +// 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/feather_sensor_transmit/libraries/DHT/DHT_U.h b/feather_sensor_transmit/libraries/DHT/DHT_U.h new file mode 100644 index 0000000..d9ee709 --- /dev/null +++ b/feather_sensor_transmit/libraries/DHT/DHT_U.h @@ -0,0 +1,78 @@ +// 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/feather_sensor_transmit/libraries/DHT/README.md b/feather_sensor_transmit/libraries/DHT/README.md new file mode 100644 index 0000000..d32afdc --- /dev/null +++ b/feather_sensor_transmit/libraries/DHT/README.md @@ -0,0 +1,15 @@ +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/feather_sensor_transmit/libraries/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino b/feather_sensor_transmit/libraries/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino new file mode 100644 index 0000000..4820f2e --- /dev/null +++ b/feather_sensor_transmit/libraries/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino @@ -0,0 +1,84 @@ +// 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/feather_sensor_transmit/libraries/DHT/examples/DHTtester/DHTtester.ino b/feather_sensor_transmit/libraries/DHT/examples/DHTtester/DHTtester.ino new file mode 100644 index 0000000..ae6c41a --- /dev/null +++ b/feather_sensor_transmit/libraries/DHT/examples/DHTtester/DHTtester.ino @@ -0,0 +1,69 @@ +// 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/feather_sensor_transmit/libraries/DHT/keywords.txt b/feather_sensor_transmit/libraries/DHT/keywords.txt new file mode 100644 index 0000000..146d4fa --- /dev/null +++ b/feather_sensor_transmit/libraries/DHT/keywords.txt @@ -0,0 +1,22 @@ +########################################### +# 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/feather_sensor_transmit/libraries/DHT/library.properties b/feather_sensor_transmit/libraries/DHT/library.properties new file mode 100644 index 0000000..a54c1dc --- /dev/null +++ b/feather_sensor_transmit/libraries/DHT/library.properties @@ -0,0 +1,9 @@ +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/feather_sensor_transmit/libraries/RTClib/.github/ISSUE_TEMPLATE.md b/feather_sensor_transmit/libraries/RTClib/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..f0e2614 --- /dev/null +++ b/feather_sensor_transmit/libraries/RTClib/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,46 @@ +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/feather_sensor_transmit/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md b/feather_sensor_transmit/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..7b641eb --- /dev/null +++ b/feather_sensor_transmit/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,26 @@ +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/feather_sensor_transmit/libraries/RTClib/README.md b/feather_sensor_transmit/libraries/RTClib/README.md new file mode 100644 index 0000000..661e18d --- /dev/null +++ b/feather_sensor_transmit/libraries/RTClib/README.md @@ -0,0 +1,42 @@ +This is a fork of JeeLab's fantastic real time clock library for Arduino. + +For details on using this library with an RTC module like the DS1307, PCF8523, or DS3231, see the guide at: https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/overview + +To download. click the DOWNLOADS button to the right, and rename the uncompressed folder RTClib. + +Place the RTClib folder in your *arduinosketchfolder*/libraries/ folder. +You may need to create the libraries subfolder if its your first library. Restart the IDE. + +Please note that dayOfTheWeek() ranges from 0 to 6 inclusive with 0 being 'Sunday' + + + +## Compatibility + +MCU | Tested Works | Doesn't Work | Not Tested | Notes +------------------ | :----------: | :----------: | :---------: | ----- +Atmega328 @ 16MHz | X | | | +Atmega328 @ 12MHz | X | | | +Atmega32u4 @ 16MHz | X | | | Use SDA/SCL on pins D3 & D2 +Atmega32u4 @ 8MHz | X | | | Use SDA/SCL on pins D3 & D2 +ESP8266 | X | | | SDA/SCL default to pins 4 & 5 but any two pins can be assigned as SDA/SCL using Wire.begin(SDA,SCL) +Atmega2560 @ 16MHz | X | | | Use SDA/SCL on Pins 20 & 21 +ATSAM3X8E | X | | | Use SDA1 and SCL1 +ATSAM21D | X | | | +ATtiny85 @ 16MHz | X | | | +ATtiny85 @ 8MHz | X | | | +Intel Curie @ 32MHz | | | X | +STM32F2 | | | X | + + * ATmega328 @ 16MHz : Arduino UNO, Adafruit Pro Trinket 5V, Adafruit Metro 328, Adafruit Metro Mini + * ATmega328 @ 12MHz : Adafruit Pro Trinket 3V + * ATmega32u4 @ 16MHz : Arduino Leonardo, Arduino Micro, Arduino Yun, Teensy 2.0 + * ATmega32u4 @ 8MHz : Adafruit Flora, Bluefruit Micro + * ESP8266 : Adafruit Huzzah + * ATmega2560 @ 16MHz : Arduino Mega + * ATSAM3X8E : Arduino Due + * ATSAM21D : Arduino Zero, M0 Pro + * ATtiny85 @ 16MHz : Adafruit Trinket 5V + * ATtiny85 @ 8MHz : Adafruit Gemma, Arduino Gemma, Adafruit Trinket 3V + + diff --git a/feather_sensor_transmit/libraries/RTClib/RTClib.cpp b/feather_sensor_transmit/libraries/RTClib/RTClib.cpp new file mode 100644 index 0000000..a08dfe9 --- /dev/null +++ b/feather_sensor_transmit/libraries/RTClib/RTClib.cpp @@ -0,0 +1,506 @@ +// Code by JeeLabs http://news.jeelabs.org/code/ +// Released to the public domain! Enjoy! + +#include +#include "RTClib.h" +#ifdef __AVR__ + #include +#elif defined(ESP8266) + #include +#elif defined(ARDUINO_ARCH_SAMD) +// nothing special needed +#elif defined(ARDUINO_SAM_DUE) + #define PROGMEM + #define pgm_read_byte(addr) (*(const unsigned char *)(addr)) + #define Wire Wire1 +#endif + + + +#if (ARDUINO >= 100) + #include // capital A so it is error prone on case-sensitive filesystems + // Macro to deal with the difference in I2C write functions from old and new Arduino versions. + #define _I2C_WRITE write + #define _I2C_READ read +#else + #include + #define _I2C_WRITE send + #define _I2C_READ receive +#endif + + +static uint8_t read_i2c_register(uint8_t addr, uint8_t reg) { + Wire.beginTransmission(addr); + Wire._I2C_WRITE((byte)reg); + Wire.endTransmission(); + + Wire.requestFrom(addr, (byte)1); + return Wire._I2C_READ(); +} + +static void write_i2c_register(uint8_t addr, uint8_t reg, uint8_t val) { + Wire.beginTransmission(addr); + Wire._I2C_WRITE((byte)reg); + Wire._I2C_WRITE((byte)val); + Wire.endTransmission(); +} + + +//////////////////////////////////////////////////////////////////////////////// +// utility code, some of this could be exposed in the DateTime API if needed + +const uint8_t daysInMonth [] PROGMEM = { 31,28,31,30,31,30,31,31,30,31,30,31 }; + +// number of days since 2000/01/01, valid for 2001..2099 +static uint16_t date2days(uint16_t y, uint8_t m, uint8_t d) { + if (y >= 2000) + y -= 2000; + uint16_t days = d; + for (uint8_t i = 1; i < m; ++i) + days += pgm_read_byte(daysInMonth + i - 1); + if (m > 2 && y % 4 == 0) + ++days; + return days + 365 * y + (y + 3) / 4 - 1; +} + +static long time2long(uint16_t days, uint8_t h, uint8_t m, uint8_t s) { + return ((days * 24L + h) * 60 + m) * 60 + s; +} + +//////////////////////////////////////////////////////////////////////////////// +// DateTime implementation - ignores time zones and DST changes +// NOTE: also ignores leap seconds, see http://en.wikipedia.org/wiki/Leap_second + +DateTime::DateTime (uint32_t t) { + t -= SECONDS_FROM_1970_TO_2000; // bring to 2000 timestamp from 1970 + + ss = t % 60; + t /= 60; + mm = t % 60; + t /= 60; + hh = t % 24; + uint16_t days = t / 24; + uint8_t leap; + for (yOff = 0; ; ++yOff) { + leap = yOff % 4 == 0; + if (days < 365 + leap) + break; + days -= 365 + leap; + } + for (m = 1; ; ++m) { + uint8_t daysPerMonth = pgm_read_byte(daysInMonth + m - 1); + if (leap && m == 2) + ++daysPerMonth; + if (days < daysPerMonth) + break; + days -= daysPerMonth; + } + d = days + 1; +} + +DateTime::DateTime (uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t min, uint8_t sec) { + if (year >= 2000) + year -= 2000; + yOff = year; + m = month; + d = day; + hh = hour; + mm = min; + ss = sec; +} + +DateTime::DateTime (const DateTime& copy): + yOff(copy.yOff), + m(copy.m), + d(copy.d), + hh(copy.hh), + mm(copy.mm), + ss(copy.ss) +{} + +static uint8_t conv2d(const char* p) { + uint8_t v = 0; + if ('0' <= *p && *p <= '9') + v = *p - '0'; + return 10 * v + *++p - '0'; +} + +// A convenient constructor for using "the compiler's time": +// DateTime now (__DATE__, __TIME__); +// NOTE: using F() would further reduce the RAM footprint, see below. +DateTime::DateTime (const char* date, const char* time) { + // sample input: date = "Dec 26 2009", time = "12:34:56" + yOff = conv2d(date + 9); + // Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec + switch (date[0]) { + case 'J': m = (date[1] == 'a') ? 1 : ((date[2] == 'n') ? 6 : 7); break; + case 'F': m = 2; break; + case 'A': m = date[2] == 'r' ? 4 : 8; break; + case 'M': m = date[2] == 'r' ? 3 : 5; break; + case 'S': m = 9; break; + case 'O': m = 10; break; + case 'N': m = 11; break; + case 'D': m = 12; break; + } + d = conv2d(date + 4); + hh = conv2d(time); + mm = conv2d(time + 3); + ss = conv2d(time + 6); +} + +// A convenient constructor for using "the compiler's time": +// This version will save RAM by using PROGMEM to store it by using the F macro. +// DateTime now (F(__DATE__), F(__TIME__)); +DateTime::DateTime (const __FlashStringHelper* date, const __FlashStringHelper* time) { + // sample input: date = "Dec 26 2009", time = "12:34:56" + char buff[11]; + memcpy_P(buff, date, 11); + yOff = conv2d(buff + 9); + // Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec + switch (buff[0]) { + case 'J': m = (buff[1] == 'a') ? 1 : ((buff[2] == 'n') ? 6 : 7); break; + case 'F': m = 2; break; + case 'A': m = buff[2] == 'r' ? 4 : 8; break; + case 'M': m = buff[2] == 'r' ? 3 : 5; break; + case 'S': m = 9; break; + case 'O': m = 10; break; + case 'N': m = 11; break; + case 'D': m = 12; break; + } + d = conv2d(buff + 4); + memcpy_P(buff, time, 8); + hh = conv2d(buff); + mm = conv2d(buff + 3); + ss = conv2d(buff + 6); +} + +uint8_t DateTime::dayOfTheWeek() const { + uint16_t day = date2days(yOff, m, d); + return (day + 6) % 7; // Jan 1, 2000 is a Saturday, i.e. returns 6 +} + +uint32_t DateTime::unixtime(void) const { + uint32_t t; + uint16_t days = date2days(yOff, m, d); + t = time2long(days, hh, mm, ss); + t += SECONDS_FROM_1970_TO_2000; // seconds from 1970 to 2000 + + return t; +} + +long DateTime::secondstime(void) const { + long t; + uint16_t days = date2days(yOff, m, d); + t = time2long(days, hh, mm, ss); + return t; +} + +DateTime DateTime::operator+(const TimeSpan& span) { + return DateTime(unixtime()+span.totalseconds()); +} + +DateTime DateTime::operator-(const TimeSpan& span) { + return DateTime(unixtime()-span.totalseconds()); +} + +TimeSpan DateTime::operator-(const DateTime& right) { + return TimeSpan(unixtime()-right.unixtime()); +} + +//////////////////////////////////////////////////////////////////////////////// +// TimeSpan implementation + +TimeSpan::TimeSpan (int32_t seconds): + _seconds(seconds) +{} + +TimeSpan::TimeSpan (int16_t days, int8_t hours, int8_t minutes, int8_t seconds): + _seconds((int32_t)days*86400L + (int32_t)hours*3600 + (int32_t)minutes*60 + seconds) +{} + +TimeSpan::TimeSpan (const TimeSpan& copy): + _seconds(copy._seconds) +{} + +TimeSpan TimeSpan::operator+(const TimeSpan& right) { + return TimeSpan(_seconds+right._seconds); +} + +TimeSpan TimeSpan::operator-(const TimeSpan& right) { + return TimeSpan(_seconds-right._seconds); +} + +//////////////////////////////////////////////////////////////////////////////// +// RTC_DS1307 implementation + +static uint8_t bcd2bin (uint8_t val) { return val - 6 * (val >> 4); } +static uint8_t bin2bcd (uint8_t val) { return val + 6 * (val / 10); } + +boolean RTC_DS1307::begin(void) { + Wire.begin(); + return true; +} + +uint8_t RTC_DS1307::isrunning(void) { + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE((byte)0); + Wire.endTransmission(); + + Wire.requestFrom(DS1307_ADDRESS, 1); + uint8_t ss = Wire._I2C_READ(); + return !(ss>>7); +} + +void RTC_DS1307::adjust(const DateTime& dt) { + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE((byte)0); // start at location 0 + Wire._I2C_WRITE(bin2bcd(dt.second())); + Wire._I2C_WRITE(bin2bcd(dt.minute())); + Wire._I2C_WRITE(bin2bcd(dt.hour())); + Wire._I2C_WRITE(bin2bcd(0)); + Wire._I2C_WRITE(bin2bcd(dt.day())); + Wire._I2C_WRITE(bin2bcd(dt.month())); + Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); + Wire.endTransmission(); +} + +DateTime RTC_DS1307::now() { + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE((byte)0); + Wire.endTransmission(); + + Wire.requestFrom(DS1307_ADDRESS, 7); + uint8_t ss = bcd2bin(Wire._I2C_READ() & 0x7F); + uint8_t mm = bcd2bin(Wire._I2C_READ()); + uint8_t hh = bcd2bin(Wire._I2C_READ()); + Wire._I2C_READ(); + uint8_t d = bcd2bin(Wire._I2C_READ()); + uint8_t m = bcd2bin(Wire._I2C_READ()); + uint16_t y = bcd2bin(Wire._I2C_READ()) + 2000; + + return DateTime (y, m, d, hh, mm, ss); +} + +Ds1307SqwPinMode RTC_DS1307::readSqwPinMode() { + int mode; + + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE(DS1307_CONTROL); + Wire.endTransmission(); + + Wire.requestFrom((uint8_t)DS1307_ADDRESS, (uint8_t)1); + mode = Wire._I2C_READ(); + + mode &= 0x93; + return static_cast(mode); +} + +void RTC_DS1307::writeSqwPinMode(Ds1307SqwPinMode mode) { + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE(DS1307_CONTROL); + Wire._I2C_WRITE(mode); + Wire.endTransmission(); +} + +void RTC_DS1307::readnvram(uint8_t* buf, uint8_t size, uint8_t address) { + int addrByte = DS1307_NVRAM + address; + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE(addrByte); + Wire.endTransmission(); + + Wire.requestFrom((uint8_t) DS1307_ADDRESS, size); + for (uint8_t pos = 0; pos < size; ++pos) { + buf[pos] = Wire._I2C_READ(); + } +} + +void RTC_DS1307::writenvram(uint8_t address, uint8_t* buf, uint8_t size) { + int addrByte = DS1307_NVRAM + address; + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE(addrByte); + for (uint8_t pos = 0; pos < size; ++pos) { + Wire._I2C_WRITE(buf[pos]); + } + Wire.endTransmission(); +} + +uint8_t RTC_DS1307::readnvram(uint8_t address) { + uint8_t data; + readnvram(&data, 1, address); + return data; +} + +void RTC_DS1307::writenvram(uint8_t address, uint8_t data) { + writenvram(address, &data, 1); +} + +//////////////////////////////////////////////////////////////////////////////// +// RTC_Millis implementation + +long RTC_Millis::offset = 0; + +void RTC_Millis::adjust(const DateTime& dt) { + offset = dt.unixtime() - millis() / 1000; +} + +DateTime RTC_Millis::now() { + return (uint32_t)(offset + millis() / 1000); +} + +//////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////////////// +// RTC_PCF8563 implementation + +boolean RTC_PCF8523::begin(void) { + Wire.begin(); + return true; +} + +boolean RTC_PCF8523::initialized(void) { + Wire.beginTransmission(PCF8523_ADDRESS); + Wire._I2C_WRITE((byte)PCF8523_CONTROL_3); + Wire.endTransmission(); + + Wire.requestFrom(PCF8523_ADDRESS, 1); + uint8_t ss = Wire._I2C_READ(); + return ((ss & 0xE0) != 0xE0); +} + +void RTC_PCF8523::adjust(const DateTime& dt) { + Wire.beginTransmission(PCF8523_ADDRESS); + Wire._I2C_WRITE((byte)3); // start at location 3 + Wire._I2C_WRITE(bin2bcd(dt.second())); + Wire._I2C_WRITE(bin2bcd(dt.minute())); + Wire._I2C_WRITE(bin2bcd(dt.hour())); + Wire._I2C_WRITE(bin2bcd(dt.day())); + Wire._I2C_WRITE(bin2bcd(0)); // skip weekdays + Wire._I2C_WRITE(bin2bcd(dt.month())); + Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); + Wire.endTransmission(); + + // set to battery switchover mode + Wire.beginTransmission(PCF8523_ADDRESS); + Wire._I2C_WRITE((byte)PCF8523_CONTROL_3); + Wire._I2C_WRITE((byte)0x00); + Wire.endTransmission(); +} + +DateTime RTC_PCF8523::now() { + Wire.beginTransmission(PCF8523_ADDRESS); + Wire._I2C_WRITE((byte)3); + Wire.endTransmission(); + + Wire.requestFrom(PCF8523_ADDRESS, 7); + uint8_t ss = bcd2bin(Wire._I2C_READ() & 0x7F); + uint8_t mm = bcd2bin(Wire._I2C_READ()); + uint8_t hh = bcd2bin(Wire._I2C_READ()); + uint8_t d = bcd2bin(Wire._I2C_READ()); + Wire._I2C_READ(); // skip 'weekdays' + uint8_t m = bcd2bin(Wire._I2C_READ()); + uint16_t y = bcd2bin(Wire._I2C_READ()) + 2000; + + return DateTime (y, m, d, hh, mm, ss); +} + +Pcf8523SqwPinMode RTC_PCF8523::readSqwPinMode() { + int mode; + + Wire.beginTransmission(PCF8523_ADDRESS); + Wire._I2C_WRITE(PCF8523_CLKOUTCONTROL); + Wire.endTransmission(); + + Wire.requestFrom((uint8_t)PCF8523_ADDRESS, (uint8_t)1); + mode = Wire._I2C_READ(); + + mode >>= 3; + mode &= 0x7; + return static_cast(mode); +} + +void RTC_PCF8523::writeSqwPinMode(Pcf8523SqwPinMode mode) { + Wire.beginTransmission(PCF8523_ADDRESS); + Wire._I2C_WRITE(PCF8523_CLKOUTCONTROL); + Wire._I2C_WRITE(mode << 3); + Wire.endTransmission(); +} + + + + +//////////////////////////////////////////////////////////////////////////////// +// RTC_DS3231 implementation + +boolean RTC_DS3231::begin(void) { + Wire.begin(); + return true; +} + +bool RTC_DS3231::lostPower(void) { + return (read_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG) >> 7); +} + +void RTC_DS3231::adjust(const DateTime& dt) { + Wire.beginTransmission(DS3231_ADDRESS); + Wire._I2C_WRITE((byte)0); // start at location 0 + Wire._I2C_WRITE(bin2bcd(dt.second())); + Wire._I2C_WRITE(bin2bcd(dt.minute())); + Wire._I2C_WRITE(bin2bcd(dt.hour())); + Wire._I2C_WRITE(bin2bcd(0)); + Wire._I2C_WRITE(bin2bcd(dt.day())); + Wire._I2C_WRITE(bin2bcd(dt.month())); + Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); + Wire.endTransmission(); + + uint8_t statreg = read_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG); + statreg &= ~0x80; // flip OSF bit + write_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG, statreg); +} + +DateTime RTC_DS3231::now() { + Wire.beginTransmission(DS3231_ADDRESS); + Wire._I2C_WRITE((byte)0); + Wire.endTransmission(); + + Wire.requestFrom(DS3231_ADDRESS, 7); + uint8_t ss = bcd2bin(Wire._I2C_READ() & 0x7F); + uint8_t mm = bcd2bin(Wire._I2C_READ()); + uint8_t hh = bcd2bin(Wire._I2C_READ()); + Wire._I2C_READ(); + uint8_t d = bcd2bin(Wire._I2C_READ()); + uint8_t m = bcd2bin(Wire._I2C_READ()); + uint16_t y = bcd2bin(Wire._I2C_READ()) + 2000; + + return DateTime (y, m, d, hh, mm, ss); +} + +Ds3231SqwPinMode RTC_DS3231::readSqwPinMode() { + int mode; + + Wire.beginTransmission(DS3231_ADDRESS); + Wire._I2C_WRITE(DS3231_CONTROL); + Wire.endTransmission(); + + Wire.requestFrom((uint8_t)DS3231_ADDRESS, (uint8_t)1); + mode = Wire._I2C_READ(); + + mode &= 0x93; + return static_cast(mode); +} + +void RTC_DS3231::writeSqwPinMode(Ds3231SqwPinMode mode) { + uint8_t ctrl; + ctrl = read_i2c_register(DS3231_ADDRESS, DS3231_CONTROL); + + ctrl &= ~0x04; // turn off INTCON + ctrl &= ~0x18; // set freq bits to 0 + + if (mode == DS3231_OFF) { + ctrl |= 0x04; // turn on INTCN + } else { + ctrl |= mode; + } + write_i2c_register(DS3231_ADDRESS, DS3231_CONTROL, ctrl); + + //Serial.println( read_i2c_register(DS3231_ADDRESS, DS3231_CONTROL), HEX); +} diff --git a/feather_sensor_transmit/libraries/RTClib/RTClib.h b/feather_sensor_transmit/libraries/RTClib/RTClib.h new file mode 100644 index 0000000..abf5d9b --- /dev/null +++ b/feather_sensor_transmit/libraries/RTClib/RTClib.h @@ -0,0 +1,135 @@ +// Code by JeeLabs http://news.jeelabs.org/code/ +// Released to the public domain! Enjoy! + +#ifndef _RTCLIB_H_ +#define _RTCLIB_H_ + +#include +class TimeSpan; + + +#define PCF8523_ADDRESS 0x68 +#define PCF8523_CLKOUTCONTROL 0x0F +#define PCF8523_CONTROL_3 0x02 + +#define DS1307_ADDRESS 0x68 +#define DS1307_CONTROL 0x07 +#define DS1307_NVRAM 0x08 + +#define DS3231_ADDRESS 0x68 +#define DS3231_CONTROL 0x0E +#define DS3231_STATUSREG 0x0F + +#define SECONDS_PER_DAY 86400L + +#define SECONDS_FROM_1970_TO_2000 946684800 + + + +// Simple general-purpose date/time class (no TZ / DST / leap second handling!) +class DateTime { +public: + DateTime (uint32_t t =0); + DateTime (uint16_t year, uint8_t month, uint8_t day, + uint8_t hour =0, uint8_t min =0, uint8_t sec =0); + DateTime (const DateTime& copy); + DateTime (const char* date, const char* time); + DateTime (const __FlashStringHelper* date, const __FlashStringHelper* time); + uint16_t year() const { return 2000 + yOff; } + uint8_t month() const { return m; } + uint8_t day() const { return d; } + uint8_t hour() const { return hh; } + uint8_t minute() const { return mm; } + uint8_t second() const { return ss; } + uint8_t dayOfTheWeek() const; + + // 32-bit times as seconds since 1/1/2000 + long secondstime() const; + // 32-bit times as seconds since 1/1/1970 + uint32_t unixtime(void) const; + + DateTime operator+(const TimeSpan& span); + DateTime operator-(const TimeSpan& span); + TimeSpan operator-(const DateTime& right); + +protected: + uint8_t yOff, m, d, hh, mm, ss; +}; + +// Timespan which can represent changes in time with seconds accuracy. +class TimeSpan { +public: + TimeSpan (int32_t seconds = 0); + TimeSpan (int16_t days, int8_t hours, int8_t minutes, int8_t seconds); + TimeSpan (const TimeSpan& copy); + int16_t days() const { return _seconds / 86400L; } + int8_t hours() const { return _seconds / 3600 % 24; } + int8_t minutes() const { return _seconds / 60 % 60; } + int8_t seconds() const { return _seconds % 60; } + int32_t totalseconds() const { return _seconds; } + + TimeSpan operator+(const TimeSpan& right); + TimeSpan operator-(const TimeSpan& right); + +protected: + int32_t _seconds; +}; + +// RTC based on the DS1307 chip connected via I2C and the Wire library +enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 }; + +class RTC_DS1307 { +public: + boolean begin(void); + static void adjust(const DateTime& dt); + uint8_t isrunning(void); + static DateTime now(); + static Ds1307SqwPinMode readSqwPinMode(); + static void writeSqwPinMode(Ds1307SqwPinMode mode); + uint8_t readnvram(uint8_t address); + void readnvram(uint8_t* buf, uint8_t size, uint8_t address); + void writenvram(uint8_t address, uint8_t data); + void writenvram(uint8_t address, uint8_t* buf, uint8_t size); +}; + +// RTC based on the DS3231 chip connected via I2C and the Wire library +enum Ds3231SqwPinMode { DS3231_OFF = 0x01, DS3231_SquareWave1Hz = 0x00, DS3231_SquareWave1kHz = 0x08, DS3231_SquareWave4kHz = 0x10, DS3231_SquareWave8kHz = 0x18 }; + +class RTC_DS3231 { +public: + boolean begin(void); + static void adjust(const DateTime& dt); + bool lostPower(void); + static DateTime now(); + static Ds3231SqwPinMode readSqwPinMode(); + static void writeSqwPinMode(Ds3231SqwPinMode mode); +}; + + +// RTC based on the PCF8523 chip connected via I2C and the Wire library +enum Pcf8523SqwPinMode { PCF8523_OFF = 7, PCF8523_SquareWave1HZ = 6, PCF8523_SquareWave32HZ = 5, PCF8523_SquareWave1kHz = 4, PCF8523_SquareWave4kHz = 3, PCF8523_SquareWave8kHz = 2, PCF8523_SquareWave16kHz = 1, PCF8523_SquareWave32kHz = 0 }; + +class RTC_PCF8523 { +public: + boolean begin(void); + void adjust(const DateTime& dt); + boolean initialized(void); + static DateTime now(); + + Pcf8523SqwPinMode readSqwPinMode(); + void writeSqwPinMode(Pcf8523SqwPinMode mode); +}; + +// RTC using the internal millis() clock, has to be initialized before use +// NOTE: this clock won't be correct once the millis() timer rolls over (>49d?) +class RTC_Millis { +public: + static void begin(const DateTime& dt) { adjust(dt); } + static void adjust(const DateTime& dt); + static DateTime now(); + +protected: + static long offset; +}; + +#endif // _RTCLIB_H_ diff --git a/feather_sensor_transmit/libraries/RTClib/examples/datecalc/datecalc.ino b/feather_sensor_transmit/libraries/RTClib/examples/datecalc/datecalc.ino new file mode 100644 index 0000000..771dacd --- /dev/null +++ b/feather_sensor_transmit/libraries/RTClib/examples/datecalc/datecalc.ino @@ -0,0 +1,111 @@ +// Simple date conversions and calculations + +#include +#include "RTClib.h" + +#if defined(ARDUINO_ARCH_SAMD) +// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! + #define Serial SerialUSB +#endif + +void showDate(const char* txt, const DateTime& dt) { + Serial.print(txt); + Serial.print(' '); + Serial.print(dt.year(), DEC); + Serial.print('/'); + Serial.print(dt.month(), DEC); + Serial.print('/'); + Serial.print(dt.day(), DEC); + Serial.print(' '); + Serial.print(dt.hour(), DEC); + Serial.print(':'); + Serial.print(dt.minute(), DEC); + Serial.print(':'); + Serial.print(dt.second(), DEC); + + Serial.print(" = "); + Serial.print(dt.unixtime()); + Serial.print("s / "); + Serial.print(dt.unixtime() / 86400L); + Serial.print("d since 1970"); + + Serial.println(); +} + +void showTimeSpan(const char* txt, const TimeSpan& ts) { + Serial.print(txt); + Serial.print(" "); + Serial.print(ts.days(), DEC); + Serial.print(" days "); + Serial.print(ts.hours(), DEC); + Serial.print(" hours "); + Serial.print(ts.minutes(), DEC); + Serial.print(" minutes "); + Serial.print(ts.seconds(), DEC); + Serial.print(" seconds ("); + Serial.print(ts.totalseconds(), DEC); + Serial.print(" total seconds)"); + Serial.println(); +} + +void setup () { + +#ifndef ESP8266 + while (!Serial); // for Leonardo/Micro/Zero +#endif + Serial.begin(57600); + + DateTime dt0 (0, 1, 1, 0, 0, 0); + showDate("dt0", dt0); + + DateTime dt1 (1, 1, 1, 0, 0, 0); + showDate("dt1", dt1); + + DateTime dt2 (2009, 1, 1, 0, 0, 0); + showDate("dt2", dt2); + + DateTime dt3 (2009, 1, 2, 0, 0, 0); + showDate("dt3", dt3); + + DateTime dt4 (2009, 1, 27, 0, 0, 0); + showDate("dt4", dt4); + + DateTime dt5 (2009, 2, 27, 0, 0, 0); + showDate("dt5", dt5); + + DateTime dt6 (2009, 12, 27, 0, 0, 0); + showDate("dt6", dt6); + + DateTime dt7 (dt6.unixtime() + 3600); // One hour later. + showDate("dt7", dt7); + + DateTime dt75 = dt6 + TimeSpan(0, 1, 0, 0); // One hour later with TimeSpan addition. + showDate("dt7.5", dt75); + + DateTime dt8 (dt6.unixtime() + 86400L); // One day later. + showDate("dt8", dt8); + + DateTime dt85 = dt6 + TimeSpan(1, 0, 0, 0); // One day later with TimeSpan addition. + showDate("dt8.5", dt85); + + DateTime dt9 (dt6.unixtime() + 7 * 86400L); // One week later. + showDate("dt9", dt9); + + DateTime dt95 = dt6 + TimeSpan(7, 0, 0, 0); // One week later with TimeSpan addition. + showDate("dt9.5", dt95); + + DateTime dt10 = dt6 + TimeSpan(0, 0, 42, 42); // Fourty two minutes and fourty two seconds later. + showDate("dt10", dt10); + + DateTime dt11 = dt6 - TimeSpan(7, 0, 0, 0); // One week ago. + showDate("dt11", dt11); + + TimeSpan ts1 = dt6 - dt5; + showTimeSpan("dt6-dt5", ts1); + + TimeSpan ts2 = dt10 - dt6; + showTimeSpan("dt10-dt6", ts2); +} + +void loop () { +} diff --git a/feather_sensor_transmit/libraries/RTClib/examples/ds1307/ds1307.ino b/feather_sensor_transmit/libraries/RTClib/examples/ds1307/ds1307.ino new file mode 100644 index 0000000..7d9162f --- /dev/null +++ b/feather_sensor_transmit/libraries/RTClib/examples/ds1307/ds1307.ino @@ -0,0 +1,71 @@ +// Date and time functions using a DS1307 RTC connected via I2C and Wire lib +#include +#include "RTClib.h" + +RTC_DS1307 rtc; + +char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; + +void setup () { + while (!Serial); // for Leonardo/Micro/Zero + + Serial.begin(57600); + if (! rtc.begin()) { + Serial.println("Couldn't find RTC"); + while (1); + } + + if (! rtc.isrunning()) { + Serial.println("RTC is NOT running!"); + // following line sets the RTC to the date & time this sketch was compiled + // rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); + // This line sets the RTC with an explicit date & time, for example to set + // January 21, 2014 at 3am you would call: + // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); + } +} + +void loop () { + DateTime now = rtc.now(); + + Serial.print(now.year(), DEC); + Serial.print('/'); + Serial.print(now.month(), DEC); + Serial.print('/'); + Serial.print(now.day(), DEC); + Serial.print(" ("); + Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); + Serial.print(") "); + Serial.print(now.hour(), DEC); + Serial.print(':'); + Serial.print(now.minute(), DEC); + Serial.print(':'); + Serial.print(now.second(), DEC); + Serial.println(); + + Serial.print(" since midnight 1/1/1970 = "); + Serial.print(now.unixtime()); + Serial.print("s = "); + Serial.print(now.unixtime() / 86400L); + Serial.println("d"); + + // calculate a date which is 7 days and 30 seconds into the future + DateTime future (now + TimeSpan(7,12,30,6)); + + Serial.print(" now + 7d + 30s: "); + Serial.print(future.year(), DEC); + Serial.print('/'); + Serial.print(future.month(), DEC); + Serial.print('/'); + Serial.print(future.day(), DEC); + Serial.print(' '); + Serial.print(future.hour(), DEC); + Serial.print(':'); + Serial.print(future.minute(), DEC); + Serial.print(':'); + Serial.print(future.second(), DEC); + Serial.println(); + + Serial.println(); + delay(3000); +} \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino b/feather_sensor_transmit/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino new file mode 100644 index 0000000..c12c26c --- /dev/null +++ b/feather_sensor_transmit/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino @@ -0,0 +1,68 @@ +// SQW/OUT pin mode using a DS1307 RTC connected via I2C. +// +// According to the data sheet (http://datasheets.maxim-ic.com/en/ds/DS1307.pdf), the +// DS1307's SQW/OUT pin can be set to low, high, 1Hz, 4.096kHz, 8.192kHz, or 32.768kHz. +// +// This sketch reads the state of the pin, then iterates through the possible values at +// 5 second intervals. +// + +// NOTE: +// You must connect a pull up resistor (~10kohm) from the SQW pin up to VCC. Without +// this pull up the wave output will not work! + +#include +#include "RTClib.h" + +#if defined(ARDUINO_ARCH_SAMD) +// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! + #define Serial SerialUSB +#endif + +RTC_DS1307 rtc; + +int mode_index = 0; + +Ds1307SqwPinMode modes[] = {OFF, ON, SquareWave1HZ, SquareWave4kHz, SquareWave8kHz, SquareWave32kHz}; + + +void print_mode() { + Ds1307SqwPinMode mode = rtc.readSqwPinMode(); + + Serial.print("Sqw Pin Mode: "); + switch(mode) { + case OFF: Serial.println("OFF"); break; + case ON: Serial.println("ON"); break; + case SquareWave1HZ: Serial.println("1Hz"); break; + case SquareWave4kHz: Serial.println("4.096kHz"); break; + case SquareWave8kHz: Serial.println("8.192kHz"); break; + case SquareWave32kHz: Serial.println("32.768kHz"); break; + default: Serial.println("UNKNOWN"); break; + } +} + +void setup () { + +#ifndef ESP8266 + while (!Serial); // for Leonardo/Micro/Zero +#endif + + Serial.begin(57600); + if (! rtc.begin()) { + Serial.println("Couldn't find RTC"); + while (1); + } + + print_mode(); +} + +void loop () { + rtc.writeSqwPinMode(modes[mode_index++]); + print_mode(); + + if (mode_index > 5) { + mode_index = 0; + } + + delay(5000); +} diff --git a/feather_sensor_transmit/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino b/feather_sensor_transmit/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino new file mode 100644 index 0000000..0acd0cf --- /dev/null +++ b/feather_sensor_transmit/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino @@ -0,0 +1,63 @@ +// Example of using the non-volatile RAM storage on the DS1307. +// You can write up to 56 bytes from address 0 to 55. +// Data will be persisted as long as the DS1307 has battery power. + +#include +#include "RTClib.h" + +#if defined(ARDUINO_ARCH_SAMD) +// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! + #define Serial SerialUSB +#endif + +RTC_DS1307 rtc; + +void printnvram(uint8_t address) { + Serial.print("Address 0x"); + Serial.print(address, HEX); + Serial.print(" = 0x"); + Serial.println(rtc.readnvram(address), HEX); +} + +void setup () { + +#ifndef ESP8266 + while (!Serial); // for Leonardo/Micro/Zero +#endif + Serial.begin(57600); + rtc.begin(); + + // Print old RAM contents on startup. + Serial.println("Current NVRAM values:"); + for (int i = 0; i < 6; ++i) { + printnvram(i); + } + + // Write some bytes to non-volatile RAM storage. + // NOTE: You can only read and write from addresses 0 to 55 (i.e. 56 byte values). + Serial.println("Writing NVRAM values."); + // Example writing one byte at a time: + rtc.writenvram(0, 0xFE); + rtc.writenvram(1, 0xED); + // Example writing multiple bytes: + uint8_t writeData[4] = { 0xBE, 0xEF, 0x01, 0x02 }; + rtc.writenvram(2, writeData, 4); + + // Read bytes from non-volatile RAM storage. + Serial.println("Reading NVRAM values:"); + // Example reading one byte at a time. + Serial.println(rtc.readnvram(0), HEX); + Serial.println(rtc.readnvram(1), HEX); + // Example reading multiple bytes: + uint8_t readData[4] = {0}; + rtc.readnvram(readData, 4, 2); + Serial.println(readData[0], HEX); + Serial.println(readData[1], HEX); + Serial.println(readData[2], HEX); + Serial.println(readData[3], HEX); + +} + +void loop () { + // Do nothing in the loop. +} diff --git a/feather_sensor_transmit/libraries/RTClib/examples/ds3231/ds3231.ino b/feather_sensor_transmit/libraries/RTClib/examples/ds3231/ds3231.ino new file mode 100644 index 0000000..b62d510 --- /dev/null +++ b/feather_sensor_transmit/libraries/RTClib/examples/ds3231/ds3231.ino @@ -0,0 +1,77 @@ +// Date and time functions using a DS3231 RTC connected via I2C and Wire lib +#include +#include "RTClib.h" + +RTC_DS3231 rtc; + +char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; + +void setup () { + +#ifndef ESP8266 + while (!Serial); // for Leonardo/Micro/Zero +#endif + + Serial.begin(9600); + + delay(3000); // wait for console opening + + if (! rtc.begin()) { + Serial.println("Couldn't find RTC"); + while (1); + } + + if (rtc.lostPower()) { + Serial.println("RTC lost power, lets set the time!"); + // following line sets the RTC to the date & time this sketch was compiled + rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); + // This line sets the RTC with an explicit date & time, for example to set + // January 21, 2014 at 3am you would call: + // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); + } +} + +void loop () { + DateTime now = rtc.now(); + + Serial.print(now.year(), DEC); + Serial.print('/'); + Serial.print(now.month(), DEC); + Serial.print('/'); + Serial.print(now.day(), DEC); + Serial.print(" ("); + Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); + Serial.print(") "); + Serial.print(now.hour(), DEC); + Serial.print(':'); + Serial.print(now.minute(), DEC); + Serial.print(':'); + Serial.print(now.second(), DEC); + Serial.println(); + + Serial.print(" since midnight 1/1/1970 = "); + Serial.print(now.unixtime()); + Serial.print("s = "); + Serial.print(now.unixtime() / 86400L); + Serial.println("d"); + + // calculate a date which is 7 days and 30 seconds into the future + DateTime future (now + TimeSpan(7,12,30,6)); + + Serial.print(" now + 7d + 30s: "); + Serial.print(future.year(), DEC); + Serial.print('/'); + Serial.print(future.month(), DEC); + Serial.print('/'); + Serial.print(future.day(), DEC); + Serial.print(' '); + Serial.print(future.hour(), DEC); + Serial.print(':'); + Serial.print(future.minute(), DEC); + Serial.print(':'); + Serial.print(future.second(), DEC); + Serial.println(); + + Serial.println(); + delay(3000); +} diff --git a/feather_sensor_transmit/libraries/RTClib/examples/pcf8523/pcf8523.ino b/feather_sensor_transmit/libraries/RTClib/examples/pcf8523/pcf8523.ino new file mode 100644 index 0000000..fc7dfe8 --- /dev/null +++ b/feather_sensor_transmit/libraries/RTClib/examples/pcf8523/pcf8523.ino @@ -0,0 +1,74 @@ +// Date and time functions using a DS1307 RTC connected via I2C and Wire lib +#include +#include "RTClib.h" + +RTC_PCF8523 rtc; + +char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; + +void setup () { + + while (!Serial) { + delay(1); // for Leonardo/Micro/Zero + } + + Serial.begin(57600); + if (! rtc.begin()) { + Serial.println("Couldn't find RTC"); + while (1); + } + + if (! rtc.initialized()) { + Serial.println("RTC is NOT running!"); + // following line sets the RTC to the date & time this sketch was compiled + // rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); + // This line sets the RTC with an explicit date & time, for example to set + // January 21, 2014 at 3am you would call: + // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); + } +} + +void loop () { + DateTime now = rtc.now(); + + Serial.print(now.year(), DEC); + Serial.print('/'); + Serial.print(now.month(), DEC); + Serial.print('/'); + Serial.print(now.day(), DEC); + Serial.print(" ("); + Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); + Serial.print(") "); + Serial.print(now.hour(), DEC); + Serial.print(':'); + Serial.print(now.minute(), DEC); + Serial.print(':'); + Serial.print(now.second(), DEC); + Serial.println(); + + Serial.print(" since midnight 1/1/1970 = "); + Serial.print(now.unixtime()); + Serial.print("s = "); + Serial.print(now.unixtime() / 86400L); + Serial.println("d"); + + // calculate a date which is 7 days and 30 seconds into the future + DateTime future (now + TimeSpan(7,12,30,6)); + + Serial.print(" now + 7d + 30s: "); + Serial.print(future.year(), DEC); + Serial.print('/'); + Serial.print(future.month(), DEC); + Serial.print('/'); + Serial.print(future.day(), DEC); + Serial.print(' '); + Serial.print(future.hour(), DEC); + Serial.print(':'); + Serial.print(future.minute(), DEC); + Serial.print(':'); + Serial.print(future.second(), DEC); + Serial.println(); + + Serial.println(); + delay(3000); +} \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/RTClib/examples/softrtc/softrtc.ino b/feather_sensor_transmit/libraries/RTClib/examples/softrtc/softrtc.ino new file mode 100644 index 0000000..80f1886 --- /dev/null +++ b/feather_sensor_transmit/libraries/RTClib/examples/softrtc/softrtc.ino @@ -0,0 +1,61 @@ +// Date and time functions using just software, based on millis() & timer + +#include +#include // this #include still required because the RTClib depends on it +#include "RTClib.h" + +#if defined(ARDUINO_ARCH_SAMD) +// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! + #define Serial SerialUSB +#endif + +RTC_Millis rtc; + +void setup () { + Serial.begin(57600); + // following line sets the RTC to the date & time this sketch was compiled + rtc.begin(DateTime(F(__DATE__), F(__TIME__))); + // This line sets the RTC with an explicit date & time, for example to set + // January 21, 2014 at 3am you would call: + // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); +} + +void loop () { + DateTime now = rtc.now(); + + Serial.print(now.year(), DEC); + Serial.print('/'); + Serial.print(now.month(), DEC); + Serial.print('/'); + Serial.print(now.day(), DEC); + Serial.print(' '); + Serial.print(now.hour(), DEC); + Serial.print(':'); + Serial.print(now.minute(), DEC); + Serial.print(':'); + Serial.print(now.second(), DEC); + Serial.println(); + + Serial.print(" seconds since 1970: "); + Serial.println(now.unixtime()); + + // calculate a date which is 7 days and 30 seconds into the future + DateTime future (now.unixtime() + 7 * 86400L + 30); + + Serial.print(" now + 7d + 30s: "); + Serial.print(future.year(), DEC); + Serial.print('/'); + Serial.print(future.month(), DEC); + Serial.print('/'); + Serial.print(future.day(), DEC); + Serial.print(' '); + Serial.print(future.hour(), DEC); + Serial.print(':'); + Serial.print(future.minute(), DEC); + Serial.print(':'); + Serial.print(future.second(), DEC); + Serial.println(); + + Serial.println(); + delay(3000); +} diff --git a/feather_sensor_transmit/libraries/RTClib/keywords.txt b/feather_sensor_transmit/libraries/RTClib/keywords.txt new file mode 100644 index 0000000..26cdc1e --- /dev/null +++ b/feather_sensor_transmit/libraries/RTClib/keywords.txt @@ -0,0 +1,37 @@ +####################################### +# Syntax Coloring Map For RTC +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +DateTime KEYWORD1 +RTC_DS1307 KEYWORD1 +RTC_Millis KEYWORD1 +Ds1307SqwPinMode KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +year KEYWORD2 +month KEYWORD2 +day KEYWORD2 +hour KEYWORD2 +minute KEYWORD2 +second KEYWORD2 +dayOfWeek KEYWORD2 +secondstime KEYWORD2 +unixtime KEYWORD2 +begin KEYWORD2 +adjust KEYWORD2 +isrunning KEYWORD2 +now KEYWORD2 +readSqwPinMode KEYWORD2 +writeSqwPinMode KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + diff --git a/feather_sensor_transmit/libraries/RTClib/library.properties b/feather_sensor_transmit/libraries/RTClib/library.properties new file mode 100644 index 0000000..13d6177 --- /dev/null +++ b/feather_sensor_transmit/libraries/RTClib/library.properties @@ -0,0 +1,9 @@ +name=RTClib +version=1.2.1 +author=Adafruit +maintainer=Adafruit +sentence=A fork of Jeelab's fantastic RTC library +paragraph=A fork of Jeelab's fantastic RTC library +category=Timing +url=https://github.com/adafruit/RTClib +architectures=* diff --git a/feather_sensor_transmit/libraries/WiFi101/.travis.yml b/feather_sensor_transmit/libraries/WiFi101/.travis.yml new file mode 100644 index 0000000..465c761 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/.travis.yml @@ -0,0 +1,48 @@ +language: generic +env: + global: + - IDE_VERSION=1.8.2 + matrix: + - BOARD="arduino:avr:uno" + - BOARD="arduino:avr:mega:cpu=atmega2560" + - BOARD="arduino:sam:arduino_due_x_dbg" + - BOARD="arduino:samd:arduino_zero_edbg" + - BOARD="arduino:samd:mkr1000" + - BOARD="Intel:arc32:arduino_101" +before_install: + - wget http://downloads.arduino.cc/arduino-$IDE_VERSION-linux64.tar.xz + - tar xf arduino-$IDE_VERSION-linux64.tar.xz + - mv arduino-$IDE_VERSION $HOME/arduino-ide + - export PATH=$PATH:$HOME/arduino-ide + - if [[ "$BOARD" =~ "arduino:sam:" ]]; then + arduino --install-boards arduino:sam; + fi + - if [[ "$BOARD" =~ "arduino:samd:" ]]; then + arduino --install-boards arduino:samd; + fi + - if [[ "$BOARD" =~ "Intel:arc32" ]]; then + arduino --install-boards Intel:arc32; + fi + - buildExampleSketch() { arduino --verbose-build --verify --board $BOARD $PWD/examples/$1/$1.ino; } +install: + - mkdir -p $HOME/Arduino/libraries + - ln -s $PWD $HOME/Arduino/libraries/. +script: + - buildExampleSketch AP_SimpleWebServer + - buildExampleSketch CheckWifi101FirmwareVersion + - buildExampleSketch ConnectNoEncryption + - buildExampleSketch ConnectWithWEP + - buildExampleSketch ConnectWithWPA + - buildExampleSketch FirmwareUpdater + - buildExampleSketch MDNS_WiFiWebServer + - buildExampleSketch ScanNetworks + - buildExampleSketch SimpleWebServerWiFi + - buildExampleSketch WiFiChatServer + - buildExampleSketch WiFiPing + - buildExampleSketch WiFiSSLClient + - buildExampleSketch WiFiUdpNtpClient + - buildExampleSketch WiFiUdpSendReceiveString + - buildExampleSketch WiFiWebClient + - buildExampleSketch WiFiWebClientRepeating + - buildExampleSketch WiFiWebServer + diff --git a/feather_sensor_transmit/libraries/WiFi101/CHANGELOG b/feather_sensor_transmit/libraries/WiFi101/CHANGELOG new file mode 100644 index 0000000..fbe1643 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/CHANGELOG @@ -0,0 +1,122 @@ +WiFi101 ?.?.? - ????.??.?? + +WiFi101 0.14.3 - 2017.06.01 + +* Fixed issues with WiFiMDNSResponder and large request packets +* Fixed issues with WiFiClient and sending data after the socket is closed + +WiFi101 0.14.2 - 2017.05.08 + +* Fixed issues with WiFiServer::write not working + +WiFi101 0.14.1 - 2017.04.20 + +* Fixed issues with WiFiMDNSResponder and Windows using Bonjour +* Correct cast of buffer size when processing received data + +WiFi101 0.14.0 - 2017.03.22 + +* Added support for firmware 19.5.2 +* Add ability to create Access Point with WPA security (f/w 19.5.2 or higher) +* Add WiFi.hostname(name) method to set custom host name for DHCP (f/w 19.5.2 or higher) +* Enables support for AES-256 Ciphers (f/w 19.5.2 or higher) +* Make provisioning mode backwards compatible with f/w 19.4.4 and older + +WiFi101 0.13.0 - 2017.03.01 + +* Added WiFi.channel() and WiFi.BSSID() + +WiFi101 0.12.1 - 2017.01.19 + +* Fixed tomorrow day issue in WiFi.getTime() + +WiFi101 0.12.0 - 2017.01.05 + +* Made provisioning mode easier and added example sketch +* Fixed WiFi.getTime() not returning 0, if time has not been synced via NTP +* Fixed crashing when connecting after scanning +* Fixed WiFiServer::available() returning valid client on outbound client connection +* Added WiFiUdp::beginMulticast(port) function for compatiblity with EthernetUdp, as beginMulti was inconsistent + +WiFi101 0.11.2 - 2016.12.15 + +* Fixed value of WiFi.getTime() being off by one day +* Fixed calling WiFi.RSSI() causing lockups + +WiFi101 0.11.1 - 2016.11.29 + +* Fixed regression for non-AVR boards that resulted in corrupt with data over than 1400 bytes was received + +WiFi101 0.11.0 - 2016.11.14 + +* Changed WiFi.ping(...) to return round trip time on success, negative value on error. Thanks @PKGeorgiev +* WiFi.end() now powers down the WiFi module +* WiFi.config(ip) can now be used to set a static IP for WiFi.begin(...) +* Fixed WiFi.BSSID(bssid) returning reversed MAC address +* Added WiFi.APClientMacAddress() API to get MAC address of AP client in AP mode +* Added WiFi.getTime() API to get epoch from NTP + +WiFi101 0.10.0 - 2016.09.08 + +* Added WiFi.end() to disconnect from the AP or end AP mode +* Added new WiFi.ping(...) functionality. Thanks @PKGeorgiev +* Added WiFi.setPins(...) to customize the CS, INTN, RESET and CHIPEN pins +* Add new WL_AP_LISTENING, WL_AP_CONNECTED, and WL_AP_FAILED status types for AP mode +* Fixed return value of WiFiUDP::beginPacket(host, port) when host is successfully resolved +* Added power management methods: WiFi.lowPowerMode(), WiFi.maxLowPowerMode(), WiFi.noLowPowerMode() +* Close TCP sockets when physical link is disconnected +* Fixed WiFi.RSSI() returning 0 when there was pending socket data + +WiFi101 0.9.1 - 2016.04.19 + +* Increased compatibility with 3rd party boards and architectures. +* Rename WiFiMdnsResponder.h/cpp to WiFiMDNSResponder.h/cpp +* Fixed buffering of UDP packet + +WiFi101 0.9.0 - 2016.03.21 + +* Fixed WiFi.status() hanging when shield is not present +* Fixed MAC address returning 00:00:00:00:00:00 with firmware version 19.3.0 +* Fixed SSL write functionality with firmware version 19.3.0 +* Fixed previous version of the library not working on the Uno and other boards that used PCINT's +* Added beginAP(...) API's to create access point with WEP passwords +* Fixed beginAP(...) channel off by one error +* Fixed WiFi.status() always returning WL_CONNECTED once connected, even if access point is disconnected later +* Added beginMulti API for Multicast UDP support +* Added WiFiMDNSResponder class and MDNS Web server example + +WiFi101 0.8.0 - 2016.02.15 + +* Added example for Access Point web server (thanks @ladyada) +* Fixed MAC Address printed in reverse order +* Allow another library to override PCINT ISR (fix issues when using the WiFi101 + library with other libraries like SoftwareSerial) + +WiFi101 0.7.0 - 2015.01.11 + +* Added support for WiFi Firmware 19.4.4 +* WiFi.hostByName(...) will not try resolve the domain name if it's already a numeric IP +* Fixed manual IP configuration (no DHCP) +* Fixed WiFiServer.available(), now follows API specification +* Fixed WEP key connection +* Fixed WiFiClient copy constructor and assignment operator. This improves stability when + Client objects are assigned or returned from functions. +* Control pins are now configurable through defines from variant. + +WiFi101 0.6.0 - 2015.11.27 + +* Fixed bug with AVR boards when Web Server is used +* Fixed UDP read bug on AVR Boards +* Added missing inlcude for SSL Client +* Fixed peek() function +* Fixed some examples + +WiFi101 0.5.1 - 2015.10.06 + +* Improved support for AVR Boards (Uno, Mega, Leonardo, etc.) and + ARM based boards (Due and Zero). + +WiFi101 0.5.0 - 2015.10.01 + +* Initial release + diff --git a/feather_sensor_transmit/libraries/WiFi101/README.adoc b/feather_sensor_transmit/libraries/WiFi101/README.adoc new file mode 100644 index 0000000..8eb6924 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/README.adoc @@ -0,0 +1,27 @@ += WiFi library for the Arduino WiFi Shield 101 and MKR1000 board = + +image:https://travis-ci.org/arduino-libraries/WiFi101.svg?branch=master["Build Status", link="https://travis-ci.org/arduino-libraries/WiFi101"] + +This library implements a network driver for devices based +on the ATMEL WINC1500 WiFi module. + +For more information about this library please visit us at +https://www.arduino.cc/en/Reference/WiFi101 + +== License == + +Copyright (c) Arduino LLC. All right reserved. + +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 2.1 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 Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino b/feather_sensor_transmit/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino new file mode 100644 index 0000000..b5caf7a --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino @@ -0,0 +1,176 @@ +/* + WiFi Web Server LED Blink + + A simple web server that lets you blink an LED via the web. + This sketch will create a new access point (with no password). + It will then launch a new server and print out the IP address + to the Serial monitor. From there, you can open that address in a web browser + to turn on and off the LED on pin 13. + + If the IP address of your shield is yourAddress: + http://yourAddress/H turns the LED on + http://yourAddress/L turns it off + + created 25 Nov 2012 + by Tom Igoe + adapted to WiFi AP by Adafruit + */ + +#include +#include +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int led = LED_BUILTIN; +int status = WL_IDLE_STATUS; +WiFiServer server(80); + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + Serial.println("Access Point Web Server"); + + pinMode(led, OUTPUT); // set the LED pin mode + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue + while (true); + } + + // by default the local IP address of will be 192.168.1.1 + // you can override it with the following: + // WiFi.config(IPAddress(10, 0, 0, 1)); + + // print the network name (SSID); + Serial.print("Creating access point named: "); + Serial.println(ssid); + + // Create open network. Change this line if you want to create an WEP network: + status = WiFi.beginAP(ssid); + if (status != WL_AP_LISTENING) { + Serial.println("Creating access point failed"); + // don't continue + while (true); + } + + // wait 10 seconds for connection: + delay(10000); + + // start the web server on port 80 + server.begin(); + + // you're connected now, so print out the status + printWiFiStatus(); +} + + +void loop() { + // compare the previous status to the current status + if (status != WiFi.status()) { + // it has changed update the variable + status = WiFi.status(); + + if (status == WL_AP_CONNECTED) { + byte remoteMac[6]; + + // a device has connected to the AP + Serial.print("Device connected to AP, MAC address: "); + WiFi.APClientMacAddress(remoteMac); + Serial.print(remoteMac[5], HEX); + Serial.print(":"); + Serial.print(remoteMac[4], HEX); + Serial.print(":"); + Serial.print(remoteMac[3], HEX); + Serial.print(":"); + Serial.print(remoteMac[2], HEX); + Serial.print(":"); + Serial.print(remoteMac[1], HEX); + Serial.print(":"); + Serial.println(remoteMac[0], HEX); + } else { + // a device has disconnected from the AP, and we are back in listening mode + Serial.println("Device disconnected from AP"); + } + } + + WiFiClient client = server.available(); // listen for incoming clients + + if (client) { // if you get a client, + Serial.println("new client"); // print a message out the serial port + String currentLine = ""; // make a String to hold incoming data from the client + while (client.connected()) { // loop while the client's connected + if (client.available()) { // if there's bytes to read from the client, + char c = client.read(); // read a byte, then + Serial.write(c); // print it out the serial monitor + if (c == '\n') { // if the byte is a newline character + + // if the current line is blank, you got two newline characters in a row. + // that's the end of the client HTTP request, so send a response: + if (currentLine.length() == 0) { + // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) + // and a content-type so the client knows what's coming, then a blank line: + client.println("HTTP/1.1 200 OK"); + client.println("Content-type:text/html"); + client.println(); + + // the content of the HTTP response follows the header: + client.print("Click here turn the LED on
"); + client.print("Click here turn the LED off
"); + + // The HTTP response ends with another blank line: + client.println(); + // break out of the while loop: + break; + } + else { // if you got a newline, then clear currentLine: + currentLine = ""; + } + } + else if (c != '\r') { // if you got anything else but a carriage return character, + currentLine += c; // add it to the end of the currentLine + } + + // Check to see if the client request was "GET /H" or "GET /L": + if (currentLine.endsWith("GET /H")) { + digitalWrite(led, HIGH); // GET /H turns the LED on + } + if (currentLine.endsWith("GET /L")) { + digitalWrite(led, LOW); // GET /L turns the LED off + } + } + } + // close the connection: + client.stop(); + Serial.println("client disconnected"); + } +} + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); + // print where to go in a browser: + Serial.print("To see this page in action, open a browser to http://"); + Serial.println(ip); + +} diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino b/feather_sensor_transmit/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino new file mode 100644 index 0000000..8cd312e --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino @@ -0,0 +1,67 @@ +/* + * This example check if the firmware loaded on the WiFi101 + * shield is updated. + * + * Circuit: + * - WiFi101 Shield attached + * + * Created 29 July 2015 by Cristian Maglie + * This code is in the public domain. + */ +#include +#include +#include + +void setup() { + // Initialize serial + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // Print a welcome message + Serial.println("WiFi101 firmware check."); + Serial.println(); + + // Check for the presence of the shield + Serial.print("WiFi101 shield: "); + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("NOT PRESENT"); + return; // don't continue + } + Serial.println("DETECTED"); + + // Print firmware version on the shield + String fv = WiFi.firmwareVersion(); + String latestFv; + Serial.print("Firmware version installed: "); + Serial.println(fv); + + if (REV(GET_CHIPID()) >= REV_3A0) { + // model B + latestFv = WIFI_FIRMWARE_LATEST_MODEL_B; + } else { + // model A + latestFv = WIFI_FIRMWARE_LATEST_MODEL_A; + } + + // Print required firmware version + Serial.print("Latest firmware version available : "); + Serial.println(latestFv); + + // Check if the latest version is installed + Serial.println(); + if (fv == latestFv) { + Serial.println("Check result: PASSED"); + } else { + Serial.println("Check result: NOT PASSED"); + Serial.println(" - The firmware version on the shield do not match the"); + Serial.println(" version required by the library, you may experience"); + Serial.println(" issues or failures."); + } +} + +void loop() { + // do nothing +} + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino b/feather_sensor_transmit/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino new file mode 100644 index 0000000..f43a232 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino @@ -0,0 +1,123 @@ +/* + + This example connects to an unencrypted WiFi network. + Then it prints the MAC address of the WiFi shield, + the IP address obtained, and other network details. + + Circuit: + * WiFi shield attached + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + */ +#include +#include +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +int status = WL_IDLE_STATUS; // the WiFi radio's status + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to open SSID: "); + Serial.println(ssid); + status = WiFi.begin(ssid); + + // wait 10 seconds for connection: + delay(10000); + } + + // you're connected now, so print out the data: + Serial.print("You're connected to the network"); + printCurrentNet(); + printWiFiData(); +} + +void loop() { + // check the network connection once every 10 seconds: + delay(10000); + printCurrentNet(); +} + +void printWiFiData() { + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + Serial.println(ip); + + // print your MAC address: + byte mac[6]; + WiFi.macAddress(mac); + Serial.print("MAC address: "); + Serial.print(mac[5], HEX); + Serial.print(":"); + Serial.print(mac[4], HEX); + Serial.print(":"); + Serial.print(mac[3], HEX); + Serial.print(":"); + Serial.print(mac[2], HEX); + Serial.print(":"); + Serial.print(mac[1], HEX); + Serial.print(":"); + Serial.println(mac[0], HEX); + + // print your subnet mask: + IPAddress subnet = WiFi.subnetMask(); + Serial.print("NetMask: "); + Serial.println(subnet); + + // print your gateway address: + IPAddress gateway = WiFi.gatewayIP(); + Serial.print("Gateway: "); + Serial.println(gateway); +} + +void printCurrentNet() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print the MAC address of the router you're attached to: + byte bssid[6]; + WiFi.BSSID(bssid); + Serial.print("BSSID: "); + Serial.print(bssid[5], HEX); + Serial.print(":"); + Serial.print(bssid[4], HEX); + Serial.print(":"); + Serial.print(bssid[3], HEX); + Serial.print(":"); + Serial.print(bssid[2], HEX); + Serial.print(":"); + Serial.print(bssid[1], HEX); + Serial.print(":"); + Serial.println(bssid[0], HEX); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.println(rssi); + + // print the encryption type: + byte encryption = WiFi.encryptionType(); + Serial.print("Encryption Type:"); + Serial.println(encryption, HEX); +} + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h new file mode 100644 index 0000000..07c1148 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h @@ -0,0 +1 @@ +#define SECRET_SSID "" diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino b/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino new file mode 100644 index 0000000..c226fa7 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino @@ -0,0 +1,129 @@ +/* + + This example connects to a WEP-encrypted WiFi network. + Then it prints the MAC address of the WiFi shield, + the IP address obtained, and other network details. + + If you use 40-bit WEP, you need a key that is 10 characters long, + and the characters must be hexadecimal (0-9 or A-F). + e.g. for 40-bit, ABBADEAF01 will work, but ABBADEAF won't work + (too short) and ABBAISDEAF won't work (I and S are not + hexadecimal characters). + + For 128-bit, you need a string that is 26 characters long. + D0D0DEADF00DABBADEAFBEADED will work because it's 26 characters, + all in the 0-9, A-F range. + + Circuit: + * WiFi shield attached + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + */ +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char key[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number +int status = WL_IDLE_STATUS; // the WiFi radio's status + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to WEP network, SSID: "); + Serial.println(ssid); + status = WiFi.begin(ssid, keyIndex, key); + + // wait 10 seconds for connection: + delay(10000); + } + + // once you are connected : + Serial.print("You're connected to the network"); + printCurrentNet(); + printWiFiData(); +} + +void loop() { + // check the network connection once every 10 seconds: + delay(10000); + printCurrentNet(); +} + +void printWiFiData() { + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + Serial.println(ip); + + // print your MAC address: + byte mac[6]; + WiFi.macAddress(mac); + Serial.print("MAC address: "); + Serial.print(mac[5], HEX); + Serial.print(":"); + Serial.print(mac[4], HEX); + Serial.print(":"); + Serial.print(mac[3], HEX); + Serial.print(":"); + Serial.print(mac[2], HEX); + Serial.print(":"); + Serial.print(mac[1], HEX); + Serial.print(":"); + Serial.println(mac[0], HEX); +} + +void printCurrentNet() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print the MAC address of the router you're attached to: + byte bssid[6]; + WiFi.BSSID(bssid); + Serial.print("BSSID: "); + Serial.print(bssid[5], HEX); + Serial.print(":"); + Serial.print(bssid[4], HEX); + Serial.print(":"); + Serial.print(bssid[3], HEX); + Serial.print(":"); + Serial.print(bssid[2], HEX); + Serial.print(":"); + Serial.print(bssid[1], HEX); + Serial.print(":"); + Serial.println(bssid[0], HEX); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.println(rssi); + + // print the encryption type: + byte encryption = WiFi.encryptionType(); + Serial.print("Encryption Type:"); + Serial.println(encryption, HEX); + Serial.println(); +} + + + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino b/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino new file mode 100644 index 0000000..b98af65 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino @@ -0,0 +1,119 @@ +/* + + This example connects to an unencrypted WiFi network. + Then it prints the MAC address of the WiFi shield, + the IP address obtained, and other network details. + + Circuit: + * WiFi shield attached + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + */ +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int status = WL_IDLE_STATUS; // the WiFi radio's status + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to WPA SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + + // you're connected now, so print out the data: + Serial.print("You're connected to the network"); + printCurrentNet(); + printWiFiData(); + +} + +void loop() { + // check the network connection once every 10 seconds: + delay(10000); + printCurrentNet(); +} + +void printWiFiData() { + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + Serial.println(ip); + + // print your MAC address: + byte mac[6]; + WiFi.macAddress(mac); + Serial.print("MAC address: "); + Serial.print(mac[5], HEX); + Serial.print(":"); + Serial.print(mac[4], HEX); + Serial.print(":"); + Serial.print(mac[3], HEX); + Serial.print(":"); + Serial.print(mac[2], HEX); + Serial.print(":"); + Serial.print(mac[1], HEX); + Serial.print(":"); + Serial.println(mac[0], HEX); + +} + +void printCurrentNet() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print the MAC address of the router you're attached to: + byte bssid[6]; + WiFi.BSSID(bssid); + Serial.print("BSSID: "); + Serial.print(bssid[5], HEX); + Serial.print(":"); + Serial.print(bssid[4], HEX); + Serial.print(":"); + Serial.print(bssid[3], HEX); + Serial.print(":"); + Serial.print(bssid[2], HEX); + Serial.print(":"); + Serial.print(bssid[1], HEX); + Serial.print(":"); + Serial.println(bssid[0], HEX); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.println(rssi); + + // print the encryption type: + byte encryption = WiFi.encryptionType(); + Serial.print("Encryption Type:"); + Serial.println(encryption, HEX); + Serial.println(); +} + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino b/feather_sensor_transmit/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino new file mode 100644 index 0000000..897c770 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino @@ -0,0 +1,62 @@ +/* + Endianess.ino - Network byte order conversion functions. + Copyright (c) 2015 Arduino LLC. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + + +bool isBigEndian() { + uint32_t test = 0x11223344; + uint8_t *pTest = reinterpret_cast(&test); + return pTest[0] == 0x11; +} + +uint32_t fromNetwork32(uint32_t from) { + static const bool be = isBigEndian(); + if (be) { + return from; + } else { + uint8_t *pFrom = reinterpret_cast(&from); + uint32_t to; + to = pFrom[0]; to <<= 8; + to |= pFrom[1]; to <<= 8; + to |= pFrom[2]; to <<= 8; + to |= pFrom[3]; + return to; + } +} + +uint16_t fromNetwork16(uint16_t from) { + static bool be = isBigEndian(); + if (be) { + return from; + } else { + uint8_t *pFrom = reinterpret_cast(&from); + uint16_t to; + to = pFrom[0]; to <<= 8; + to |= pFrom[1]; + return to; + } +} + +uint32_t toNetwork32(uint32_t to) { + return fromNetwork32(to); +} + +uint16_t toNetwork16(uint16_t to) { + return fromNetwork16(to); +} + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino b/feather_sensor_transmit/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino new file mode 100644 index 0000000..1bbd6b9 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino @@ -0,0 +1,129 @@ +/* + FirmwareUpdate.h - Firmware Updater for WiFi101 / WINC1500. + Copyright (c) 2015 Arduino LLC. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include +#include + +typedef struct __attribute__((__packed__)) { + uint8_t command; + uint32_t address; + uint32_t arg1; + uint16_t payloadLength; + + // payloadLenght bytes of data follows... +} UartPacket; + +static const int MAX_PAYLOAD_SIZE = 1024; + +#define CMD_READ_FLASH 0x01 +#define CMD_WRITE_FLASH 0x02 +#define CMD_ERASE_FLASH 0x03 +#define CMD_MAX_PAYLOAD_SIZE 0x50 +#define CMD_HELLO 0x99 + +void setup() { + Serial.begin(115200); + + nm_bsp_init(); + if (m2m_wifi_download_mode() != M2M_SUCCESS) { + Serial.println(F("Failed to put the WiFi module in download mode")); + while (true) + ; + } +} + +void receivePacket(UartPacket *pkt, uint8_t *payload) { + // Read command + uint8_t *p = reinterpret_cast(pkt); + uint16_t l = sizeof(UartPacket); + while (l > 0) { + int c = Serial.read(); + if (c == -1) + continue; + *p++ = c; + l--; + } + + // Convert parameters from network byte order to cpu byte order + pkt->address = fromNetwork32(pkt->address); + pkt->arg1 = fromNetwork32(pkt->arg1); + pkt->payloadLength = fromNetwork16(pkt->payloadLength); + + // Read payload + l = pkt->payloadLength; + while (l > 0) { + int c = Serial.read(); + if (c == -1) + continue; + *payload++ = c; + l--; + } +} + +// Allocated statically so the compiler can tell us +// about the amount of used RAM +static UartPacket pkt; +static uint8_t payload[MAX_PAYLOAD_SIZE]; + +void loop() { + receivePacket(&pkt, payload); + + if (pkt.command == CMD_HELLO) { + if (pkt.address == 0x11223344 && pkt.arg1 == 0x55667788) + Serial.print("v10000"); + } + + if (pkt.command == CMD_MAX_PAYLOAD_SIZE) { + uint16_t res = toNetwork16(MAX_PAYLOAD_SIZE); + Serial.write(reinterpret_cast(&res), sizeof(res)); + } + + if (pkt.command == CMD_READ_FLASH) { + uint32_t address = pkt.address; + uint32_t len = pkt.arg1; + if (spi_flash_read(payload, address, len) != M2M_SUCCESS) { + Serial.println("ER"); + } else { + Serial.write(payload, len); + Serial.print("OK"); + } + } + + if (pkt.command == CMD_WRITE_FLASH) { + uint32_t address = pkt.address; + uint32_t len = pkt.payloadLength; + if (spi_flash_write(payload, address, len) != M2M_SUCCESS) { + Serial.print("ER"); + } else { + Serial.print("OK"); + } + } + + if (pkt.command == CMD_ERASE_FLASH) { + uint32_t address = pkt.address; + uint32_t len = pkt.arg1; + if (spi_flash_erase(address, len) != M2M_SUCCESS) { + Serial.print("ER"); + } else { + Serial.print("OK"); + } + } +} + + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino b/feather_sensor_transmit/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino new file mode 100644 index 0000000..f62ac62 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino @@ -0,0 +1,170 @@ +/* + MDNS WiFi Web Server + + A simple web server that shows the value of the analog input pins, + and exposes itself on the MDNS name 'wifi101.local'. + + On Linux (like Ubuntu 15.04) or OSX you can access the web page + on the device in a browser at 'http://wifi101.local/'. + + On Windows you'll first need to install the Bonjour Printer Services + from: + https://support.apple.com/kb/dl999?locale=en_US + Then you can access the device in a browser at 'http://wifi101.local/'. + + This example is written for a network using WPA encryption. For + WEP or WPA, change the WiFi.begin() call accordingly. + + Circuit: + * WiFi shield attached + * Analog inputs attached to pins A0 through A5 (optional) + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + modified 27 January 2016 + by Tony DiCola + +*/ + +#include +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +char mdnsName[] = "wifi101"; // the MDNS name that the board will respond to +// Note that the actual MDNS name will have '.local' after +// the name above, so "wifi101" will be accessible on +// the MDNS name "wifi101.local". + +int status = WL_IDLE_STATUS; + +// Create a MDNS responder to listen and respond to MDNS name requests. +WiFiMDNSResponder mdnsResponder; + +WiFiServer server(80); + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + // you're connected now, so print out the status: + printWiFiStatus(); + + server.begin(); + + // Setup the MDNS responder to listen to the configured name. + // NOTE: You _must_ call this _after_ connecting to the WiFi network and + // being assigned an IP address. + if (!mdnsResponder.begin(mdnsName)) { + Serial.println("Failed to start MDNS responder!"); + while(1); + } + + Serial.print("Server listening at http://"); + Serial.print(mdnsName); + Serial.println(".local/"); +} + + +void loop() { + // Call the update() function on the MDNS responder every loop iteration to + // make sure it can detect and respond to name requests. + mdnsResponder.poll(); + + // listen for incoming clients + WiFiClient client = server.available(); + if (client) { + Serial.println("new client"); + // an http request ends with a blank line + boolean currentLineIsBlank = true; + while (client.connected()) { + if (client.available()) { + char c = client.read(); + Serial.write(c); + // if you've gotten to the end of the line (received a newline + // character) and the line is blank, the http request has ended, + // so you can send a reply + if (c == '\n' && currentLineIsBlank) { + // send a standard http response header + client.println("HTTP/1.1 200 OK"); + client.println("Content-Type: text/html"); + client.println("Connection: close"); // the connection will be closed after completion of the response + client.println("Refresh: 5"); // refresh the page automatically every 5 sec + client.println(); + client.println(""); + client.println(""); + // output the value of each analog input pin + for (int analogChannel = 0; analogChannel < 6; analogChannel++) { + int sensorReading = analogRead(analogChannel); + client.print("analog input "); + client.print(analogChannel); + client.print(" is "); + client.print(sensorReading); + client.println("
"); + } + client.println(""); + break; + } + if (c == '\n') { + // you're starting a new line + currentLineIsBlank = true; + } + else if (c != '\r') { + // you've gotten a character on the current line + currentLineIsBlank = false; + } + } + } + // give the web browser time to receive the data + delay(1); + + // close the connection: + client.stop(); + Serial.println("client disconnected"); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino b/feather_sensor_transmit/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino new file mode 100644 index 0000000..0297707 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino @@ -0,0 +1,167 @@ +/* + WiFi Web Server + + A simple web server that shows the value of the analog input pins. + using a WiFi shield. + + This example is written to configure the WiFi settings using provisioning mode. + It also sets up an mDNS server so the IP address of the board doesn't have to + be obtained via the serial monitor. + + Circuit: + WiFi shield attached + Analog inputs attached to pins A0 through A5 (optional) + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + +*/ + +#include +#include +#include + +const int ledPin = 6; // LED pin for connectivity status indicator + +char mdnsName[] = "wifi101"; // the MDNS name that the board will respond to + // after WiFi settings have been provisioned +// Note that the actual MDNS name will have '.local' after +// the name above, so "wifi101" will be accessible on +// the MDNS name "wifi101.local". + +WiFiServer server(80); + +// Create a MDNS responder to listen and respond to MDNS name requests. +WiFiMDNSResponder mdnsResponder; + +void setup() { + //Initialize serial: + Serial.begin(9600); + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // configure the LED pin for output mode + pinMode(ledPin, OUTPUT); + + // Start in provisioning mode: + // 1) This will try to connect to a previously associated access point. + // 2) If this fails, an access point named "wifi101-XXXX" will be created, where XXXX + // is the last 4 digits of the boards MAC address. Once you are connected to the access point, + // you can configure an SSID and password by visiting http://wifi101/ + WiFi.beginProvision(); + + while (WiFi.status() != WL_CONNECTED) { + // wait while not connected + + // blink the led to show an unconnected status + digitalWrite(ledPin, HIGH); + delay(500); + digitalWrite(ledPin, LOW); + delay(500); + } + + // connected, make the LED stay on + digitalWrite(ledPin, HIGH); + + server.begin(); + + // Setup the MDNS responder to listen to the configured name. + // NOTE: You _must_ call this _after_ connecting to the WiFi network and + // being assigned an IP address. + if (!mdnsResponder.begin(mdnsName)) { + Serial.println("Failed to start MDNS responder!"); + while(1); + } + + Serial.print("Server listening at http://"); + Serial.print(mdnsName); + Serial.println(".local/"); + + // you're connected now, so print out the status: + printWiFiStatus(); +} + + +void loop() { + // Call the update() function on the MDNS responder every loop iteration to + // make sure it can detect and respond to name requests. + mdnsResponder.poll(); + + // listen for incoming clients + WiFiClient client = server.available(); + if (client) { + Serial.println("new client"); + // an http request ends with a blank line + boolean currentLineIsBlank = true; + while (client.connected()) { + if (client.available()) { + char c = client.read(); + Serial.write(c); + // if you've gotten to the end of the line (received a newline + // character) and the line is blank, the http request has ended, + // so you can send a reply + if (c == '\n' && currentLineIsBlank) { + // send a standard http response header + client.println("HTTP/1.1 200 OK"); + client.println("Content-Type: text/html"); + client.println("Connection: close"); // the connection will be closed after completion of the response + client.println("Refresh: 5"); // refresh the page automatically every 5 sec + client.println(); + client.println(""); + client.println(""); + // output the value of each analog input pin + for (int analogChannel = 0; analogChannel < 6; analogChannel++) { + int sensorReading = analogRead(analogChannel); + client.print("analog input "); + client.print(analogChannel); + client.print(" is "); + client.print(sensorReading); + client.println("
"); + } + client.println(""); + break; + } + if (c == '\n') { + // you're starting a new line + currentLineIsBlank = true; + } + else if (c != '\r') { + // you've gotten a character on the current line + currentLineIsBlank = false; + } + } + } + // give the web browser time to receive the data + delay(1); + + // close the connection: + client.stop(); + Serial.println("client disonnected"); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino b/feather_sensor_transmit/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino new file mode 100644 index 0000000..45b908e --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino @@ -0,0 +1,120 @@ +/* + + This example prints the WiFi shield's MAC address, and + scans for available WiFi networks using the WiFi shield. + Every ten seconds, it scans again. It doesn't actually + connect to any network, so no encryption scheme is specified. + + Circuit: + * WiFi shield attached + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 21 Junn 2012 + by Tom Igoe and Jaymes Dec + */ + + +#include +#include + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // Print WiFi MAC address: + printMacAddress(); + + // scan for existing networks: + Serial.println("Scanning available networks..."); + listNetworks(); +} + +void loop() { + delay(10000); + // scan for existing networks: + Serial.println("Scanning available networks..."); + listNetworks(); +} + +void printMacAddress() { + // the MAC address of your WiFi shield + byte mac[6]; + + // print your MAC address: + WiFi.macAddress(mac); + Serial.print("MAC: "); + Serial.print(mac[5], HEX); + Serial.print(":"); + Serial.print(mac[4], HEX); + Serial.print(":"); + Serial.print(mac[3], HEX); + Serial.print(":"); + Serial.print(mac[2], HEX); + Serial.print(":"); + Serial.print(mac[1], HEX); + Serial.print(":"); + Serial.println(mac[0], HEX); +} + +void listNetworks() { + // scan for nearby networks: + Serial.println("** Scan Networks **"); + int numSsid = WiFi.scanNetworks(); + if (numSsid == -1) + { + Serial.println("Couldn't get a wifi connection"); + while (true); + } + + // print the list of networks seen: + Serial.print("number of available networks:"); + Serial.println(numSsid); + + // print the network number and name for each network found: + for (int thisNet = 0; thisNet < numSsid; thisNet++) { + Serial.print(thisNet); + Serial.print(") "); + Serial.print(WiFi.SSID(thisNet)); + Serial.print("\tSignal: "); + Serial.print(WiFi.RSSI(thisNet)); + Serial.print(" dBm"); + Serial.print("\tEncryption: "); + printEncryptionType(WiFi.encryptionType(thisNet)); + Serial.flush(); + } +} + +void printEncryptionType(int thisType) { + // read the encryption type and print out the name: + switch (thisType) { + case ENC_TYPE_WEP: + Serial.println("WEP"); + break; + case ENC_TYPE_TKIP: + Serial.println("WPA"); + break; + case ENC_TYPE_CCMP: + Serial.println("WPA2"); + break; + case ENC_TYPE_NONE: + Serial.println("None"); + break; + case ENC_TYPE_AUTO: + Serial.println("Auto"); + break; + } +} + + + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino b/feather_sensor_transmit/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino new file mode 100644 index 0000000..2afb544 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino @@ -0,0 +1,149 @@ +/* + + This example prints the WiFi 101 shield or MKR1000 MAC address, and + scans for available WiFi networks using the WiFi 101 shield or MKR1000 board. + Every ten seconds, it scans again. It doesn't actually + connect to any network, so no encryption scheme is specified. + BSSID and WiFi channel are printed + + Circuit: + WiFi 101 shield attached or MKR1000 board + + This example is based on ScanNetworks + + created 1 Mar 2017 + by Arturo Guadalupi +*/ + + +#include +#include + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // Print WiFi MAC address: + printMacAddress(); + + // scan for existing networks: + Serial.println(); + Serial.println("Scanning available networks..."); + listNetworks(); +} + +void loop() { + delay(10000); + // scan for existing networks: + Serial.println("Scanning available networks..."); + listNetworks(); +} + +void printMacAddress() { + // the MAC address of your WiFi shield + byte mac[6]; + + // print your MAC address: + WiFi.macAddress(mac); + Serial.print("MAC: "); + print2Digits(mac[5]); + Serial.print(":"); + print2Digits(mac[4]); + Serial.print(":"); + print2Digits(mac[3]); + Serial.print(":"); + print2Digits(mac[2]); + Serial.print(":"); + print2Digits(mac[1]); + Serial.print(":"); + print2Digits(mac[0]); +} + +void listNetworks() { + // scan for nearby networks: + Serial.println("** Scan Networks **"); + int numSsid = WiFi.scanNetworks(); + if (numSsid == -1) + { + Serial.println("Couldn't get a WiFi connection"); + while (true); + } + + // print the list of networks seen: + Serial.print("number of available networks: "); + Serial.println(numSsid); + + // print the network number and name for each network found: + for (int thisNet = 0; thisNet < numSsid; thisNet++) { + Serial.print(thisNet + 1); + Serial.print(") "); + Serial.print("Signal: "); + Serial.print(WiFi.RSSI(thisNet)); + Serial.print(" dBm"); + Serial.print("\tChannel: "); + Serial.print(WiFi.channel(thisNet)); + byte bssid[6]; + Serial.print("\t\tBSSID: "); + printBSSID(WiFi.BSSID(thisNet, bssid)); + Serial.print("\tEncryption: "); + printEncryptionType(WiFi.encryptionType(thisNet)); + Serial.print("\t\tSSID: "); + Serial.println(WiFi.SSID(thisNet)); + Serial.flush(); + } + Serial.println(); +} + +void printBSSID(byte bssid[]) { + print2Digits(bssid[5]); + Serial.print(":"); + print2Digits(bssid[4]); + Serial.print(":"); + print2Digits(bssid[3]); + Serial.print(":"); + print2Digits(bssid[2]); + Serial.print(":"); + print2Digits(bssid[1]); + Serial.print(":"); + print2Digits(bssid[0]); +} + +void printEncryptionType(int thisType) { + // read the encryption type and print out the name: + switch (thisType) { + case ENC_TYPE_WEP: + Serial.print("WEP"); + break; + case ENC_TYPE_TKIP: + Serial.print("WPA"); + break; + case ENC_TYPE_CCMP: + Serial.print("WPA2"); + break; + case ENC_TYPE_NONE: + Serial.print("None"); + break; + case ENC_TYPE_AUTO: + Serial.print("Auto"); + break; + } +} + +void print2Digits(byte thisByte) { + if (thisByte < 0xF) { + Serial.print("0"); + } + Serial.print(thisByte, HEX); +} + + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino b/feather_sensor_transmit/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino new file mode 100644 index 0000000..aeaf0c6 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino @@ -0,0 +1,131 @@ +/* + WiFi Web Server LED Blink + + A simple web server that lets you blink an LED via the web. + This sketch will print the IP address of your WiFi Shield (once connected) + to the Serial monitor. From there, you can open that address in a web browser + to turn on and off the LED on pin 9. + + If the IP address of your shield is yourAddress: + http://yourAddress/H turns the LED on + http://yourAddress/L turns it off + + This example is written for a network using WPA encryption. For + WEP or WPA, change the WiFi.begin() call accordingly. + + Circuit: + * WiFi shield attached + * LED attached to pin 9 + + created 25 Nov 2012 + by Tom Igoe + */ +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int status = WL_IDLE_STATUS; +WiFiServer server(80); + +void setup() { + Serial.begin(9600); // initialize serial communication + pinMode(9, OUTPUT); // set the LED pin mode + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + while (true); // don't continue + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + // wait 10 seconds for connection: + delay(10000); + } + server.begin(); // start the web server on port 80 + printWiFiStatus(); // you're connected now, so print out the status +} + + +void loop() { + WiFiClient client = server.available(); // listen for incoming clients + + if (client) { // if you get a client, + Serial.println("new client"); // print a message out the serial port + String currentLine = ""; // make a String to hold incoming data from the client + while (client.connected()) { // loop while the client's connected + if (client.available()) { // if there's bytes to read from the client, + char c = client.read(); // read a byte, then + Serial.write(c); // print it out the serial monitor + if (c == '\n') { // if the byte is a newline character + + // if the current line is blank, you got two newline characters in a row. + // that's the end of the client HTTP request, so send a response: + if (currentLine.length() == 0) { + // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) + // and a content-type so the client knows what's coming, then a blank line: + client.println("HTTP/1.1 200 OK"); + client.println("Content-type:text/html"); + client.println(); + + // the content of the HTTP response follows the header: + client.print("Click here turn the LED on pin 9 on
"); + client.print("Click here turn the LED on pin 9 off
"); + + // The HTTP response ends with another blank line: + client.println(); + // break out of the while loop: + break; + } + else { // if you got a newline, then clear currentLine: + currentLine = ""; + } + } + else if (c != '\r') { // if you got anything else but a carriage return character, + currentLine += c; // add it to the end of the currentLine + } + + // Check to see if the client request was "GET /H" or "GET /L": + if (currentLine.endsWith("GET /H")) { + digitalWrite(9, HIGH); // GET /H turns the LED on + } + if (currentLine.endsWith("GET /L")) { + digitalWrite(9, LOW); // GET /L turns the LED off + } + } + } + // close the connection: + client.stop(); + Serial.println("client disonnected"); + } +} + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); + // print where to go in a browser: + Serial.print("To see this page in action, open a browser to http://"); + Serial.println(ip); +} diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino new file mode 100644 index 0000000..ac7bd76 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino @@ -0,0 +1,114 @@ +/* + Chat Server + + A simple server that distributes any incoming messages to all + connected clients. To use telnet to your device's IP address and type. + You can see the client's input in the serial monitor as well. + + This example is written for a network using WPA encryption. For + WEP or WPA, change the WiFi.begin() call accordingly. + + + Circuit: + * WiFi shield attached + + created 18 Dec 2009 + by David A. Mellis + modified 31 May 2012 + by Tom Igoe + + */ + +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) + +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int status = WL_IDLE_STATUS; + +WiFiServer server(23); + +boolean alreadyConnected = false; // whether or not the client was connected previously + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + + // start the server: + server.begin(); + // you're connected now, so print out the status: + printWiFiStatus(); +} + + +void loop() { + // wait for a new client: + WiFiClient client = server.available(); + + + // when the client sends the first byte, say hello: + if (client) { + if (!alreadyConnected) { + // clead out the input buffer: + client.flush(); + Serial.println("We have a new client"); + client.println("Hello, client!"); + alreadyConnected = true; + } + + if (client.available() > 0) { + // read the bytes incoming from the client: + char thisChar = client.read(); + // echo the bytes back to the client: + server.write(thisChar); + // echo the bytes to the server as well: + Serial.write(thisChar); + } + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} + + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino new file mode 100644 index 0000000..9a51c19 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino @@ -0,0 +1,140 @@ +/* + + This example connects to a encrypted WiFi network (WPA/WPA2). + Then it prints the MAC address of the WiFi shield, + the IP address obtained, and other network details. + Then it continuously pings given host specified by IP Address or name. + + Circuit: + WiFi shield attached / MKR1000 + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 09 June 2016 + by Petar Georgiev +*/ +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int status = WL_IDLE_STATUS; // the WiFi radio's status + +// Specify IP address or hostname +String hostName = "www.google.com"; +int pingResult; + +void setup() { + // Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to WPA SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + + // wait 5 seconds for connection: + delay(5000); + } + + // you're connected now, so print out the data: + Serial.println("You're connected to the network"); + printCurrentNet(); + printWiFiData(); +} + +void loop() { + Serial.print("Pinging "); + Serial.print(hostName); + Serial.print(": "); + + pingResult = WiFi.ping(hostName); + + if (pingResult >= 0) { + Serial.print("SUCCESS! RTT = "); + Serial.print(pingResult); + Serial.println(" ms"); + } else { + Serial.print("FAILED! Error code: "); + Serial.println(pingResult); + } + + delay(5000); +} + +void printWiFiData() { + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP address : "); + Serial.println(ip); + + Serial.print("Subnet mask: "); + Serial.println((IPAddress)WiFi.subnetMask()); + + Serial.print("Gateway IP : "); + Serial.println((IPAddress)WiFi.gatewayIP()); + + // print your MAC address: + byte mac[6]; + WiFi.macAddress(mac); + Serial.print("MAC address: "); + Serial.print(mac[5], HEX); + Serial.print(":"); + Serial.print(mac[4], HEX); + Serial.print(":"); + Serial.print(mac[3], HEX); + Serial.print(":"); + Serial.print(mac[2], HEX); + Serial.print(":"); + Serial.print(mac[1], HEX); + Serial.print(":"); + Serial.println(mac[0], HEX); + Serial.println(); +} + +void printCurrentNet() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print the MAC address of the router you're attached to: + byte bssid[6]; + WiFi.BSSID(bssid); + Serial.print("BSSID: "); + Serial.print(bssid[5], HEX); + Serial.print(":"); + Serial.print(bssid[4], HEX); + Serial.print(":"); + Serial.print(bssid[3], HEX); + Serial.print(":"); + Serial.print(bssid[2], HEX); + Serial.print(":"); + Serial.print(bssid[1], HEX); + Serial.print(":"); + Serial.println(bssid[0], HEX); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI): "); + Serial.println(rssi); + + // print the encryption type: + byte encryption = WiFi.encryptionType(); + Serial.print("Encryption Type: "); + Serial.println(encryption, HEX); + Serial.println(); +} diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino new file mode 100644 index 0000000..a436902 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino @@ -0,0 +1,107 @@ +/* +This example creates a client object that connects and transfers +data using always SSL. + +It is compatible with the methods normally related to plain +connections, like client.connect(host, port). + +Written by Arturo Guadalupi +last revision November 2015 + +*/ + +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int status = WL_IDLE_STATUS; +// if you don't want to use DNS (and reduce your sketch size) +// use the numeric IP instead of the name for the server: +//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) +char server[] = "www.google.com"; // name address for Google (using DNS) + +// Initialize the Ethernet client library +// with the IP address and port of the server +// that you want to connect to (port 80 is default for HTTP): +WiFiSSLClient client; + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while (status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + Serial.println("Connected to wifi"); + printWiFiStatus(); + + Serial.println("\nStarting connection to server..."); + // if you get a connection, report back via serial: + if (client.connect(server, 443)) { + Serial.println("connected to server"); + // Make a HTTP request: + client.println("GET /search?q=arduino HTTP/1.1"); + client.println("Host: www.google.com"); + client.println("Connection: close"); + client.println(); + } +} + +void loop() { + // if there are incoming bytes available + // from the server, read them and print them: + while (client.available()) { + char c = client.read(); + Serial.write(c); + } + + // if the server's disconnected, stop the client: + if (!client.connected()) { + Serial.println(); + Serial.println("disconnecting from server."); + client.stop(); + + // do nothing forevermore: + while (true); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino new file mode 100644 index 0000000..e82fbaa --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino @@ -0,0 +1,182 @@ +/* + + Udp NTP Client + + Get the time from a Network Time Protocol (NTP) time server + Demonstrates use of UDP sendPacket and ReceivePacket + For more on NTP time servers and the messages needed to communicate with them, + see http://en.wikipedia.org/wiki/Network_Time_Protocol + + created 4 Sep 2010 + by Michael Margolis + modified 9 Apr 2012 + by Tom Igoe + + This code is in the public domain. + + */ + +#include +#include +#include + +int status = WL_IDLE_STATUS; +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +unsigned int localPort = 2390; // local port to listen for UDP packets + +IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server + +const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message + +byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets + +// A UDP instance to let us send and receive packets over UDP +WiFiUDP Udp; + +void setup() +{ + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + + Serial.println("Connected to wifi"); + printWiFiStatus(); + + Serial.println("\nStarting connection to server..."); + Udp.begin(localPort); +} + +void loop() +{ + sendNTPpacket(timeServer); // send an NTP packet to a time server + // wait to see if a reply is available + delay(1000); + if ( Udp.parsePacket() ) { + Serial.println("packet received"); + // We've received a packet, read the data from it + Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer + + //the timestamp starts at byte 40 of the received packet and is four bytes, + // or two words, long. First, esxtract the two words: + + unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); + unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); + // combine the four bytes (two words) into a long integer + // this is NTP time (seconds since Jan 1 1900): + unsigned long secsSince1900 = highWord << 16 | lowWord; + Serial.print("Seconds since Jan 1 1900 = " ); + Serial.println(secsSince1900); + + // now convert NTP time into everyday time: + Serial.print("Unix time = "); + // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: + const unsigned long seventyYears = 2208988800UL; + // subtract seventy years: + unsigned long epoch = secsSince1900 - seventyYears; + // print Unix time: + Serial.println(epoch); + + + // print the hour, minute and second: + Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) + Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) + Serial.print(':'); + if ( ((epoch % 3600) / 60) < 10 ) { + // In the first 10 minutes of each hour, we'll want a leading '0' + Serial.print('0'); + } + Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) + Serial.print(':'); + if ( (epoch % 60) < 10 ) { + // In the first 10 seconds of each minute, we'll want a leading '0' + Serial.print('0'); + } + Serial.println(epoch % 60); // print the second + } + // wait ten seconds before asking for the time again + delay(10000); +} + +// send an NTP request to the time server at the given address +unsigned long sendNTPpacket(IPAddress& address) +{ + //Serial.println("1"); + // set all bytes in the buffer to 0 + memset(packetBuffer, 0, NTP_PACKET_SIZE); + // Initialize values needed to form NTP request + // (see URL above for details on the packets) + //Serial.println("2"); + packetBuffer[0] = 0b11100011; // LI, Version, Mode + packetBuffer[1] = 0; // Stratum, or type of clock + packetBuffer[2] = 6; // Polling Interval + packetBuffer[3] = 0xEC; // Peer Clock Precision + // 8 bytes of zero for Root Delay & Root Dispersion + packetBuffer[12] = 49; + packetBuffer[13] = 0x4E; + packetBuffer[14] = 49; + packetBuffer[15] = 52; + + //Serial.println("3"); + + // all NTP fields have been given values, now + // you can send a packet requesting a timestamp: + Udp.beginPacket(address, 123); //NTP requests are to port 123 + //Serial.println("4"); + Udp.write(packetBuffer, NTP_PACKET_SIZE); + //Serial.println("5"); + Udp.endPacket(); + //Serial.println("6"); +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} + + + + + + + + + + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino new file mode 100644 index 0000000..cbc9f7f --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino @@ -0,0 +1,113 @@ +/* + WiFi UDP Send and Receive String + + This sketch wait an UDP packet on localPort using a WiFi shield. + When a packet is received an Acknowledge packet is sent to the client on port remotePort + + Circuit: + * WiFi shield attached + + created 30 December 2012 + by dlf (Metodo2 srl) + + */ + + +#include +#include +#include + +int status = WL_IDLE_STATUS; +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +unsigned int localPort = 2390; // local port to listen on + +char packetBuffer[255]; //buffer to hold incoming packet +char ReplyBuffer[] = "acknowledged"; // a string to send back + +WiFiUDP Udp; + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + Serial.println("Connected to wifi"); + printWiFiStatus(); + + Serial.println("\nStarting connection to server..."); + // if you get a connection, report back via serial: + Udp.begin(localPort); +} + +void loop() { + + // if there's data available, read a packet + int packetSize = Udp.parsePacket(); + if (packetSize) + { + Serial.print("Received packet of size "); + Serial.println(packetSize); + Serial.print("From "); + IPAddress remoteIp = Udp.remoteIP(); + Serial.print(remoteIp); + Serial.print(", port "); + Serial.println(Udp.remotePort()); + + // read the packet into packetBufffer + int len = Udp.read(packetBuffer, 255); + if (len > 0) packetBuffer[len] = 0; + Serial.println("Contents:"); + Serial.println(packetBuffer); + + // send a reply, to the IP address and port that sent us the packet we received + Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); + Udp.write(ReplyBuffer); + Udp.endPacket(); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} + + + + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino new file mode 100644 index 0000000..5faa779 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino @@ -0,0 +1,121 @@ +/* + Web client + + This sketch connects to a website (http://www.google.com) + using a WiFi shield. + + This example is written for a network using WPA encryption. For + WEP or WPA, change the WiFi.begin() call accordingly. + + This example is written for a network using WPA encryption. For + WEP or WPA, change the WiFi.begin() call accordingly. + + Circuit: + * WiFi shield attached + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + */ + + +#include +#include +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int status = WL_IDLE_STATUS; +// if you don't want to use DNS (and reduce your sketch size) +// use the numeric IP instead of the name for the server: +//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) +char server[] = "www.google.com"; // name address for Google (using DNS) + +// Initialize the Ethernet client library +// with the IP address and port of the server +// that you want to connect to (port 80 is default for HTTP): +WiFiClient client; + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while (status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + Serial.println("Connected to wifi"); + printWiFiStatus(); + + Serial.println("\nStarting connection to server..."); + // if you get a connection, report back via serial: + if (client.connect(server, 80)) { + Serial.println("connected to server"); + // Make a HTTP request: + client.println("GET /search?q=arduino HTTP/1.1"); + client.println("Host: www.google.com"); + client.println("Connection: close"); + client.println(); + } +} + +void loop() { + // if there are incoming bytes available + // from the server, read them and print them: + while (client.available()) { + char c = client.read(); + Serial.write(c); + } + + // if the server's disconnected, stop the client: + if (!client.connected()) { + Serial.println(); + Serial.println("disconnecting from server."); + client.stop(); + + // do nothing forevermore: + while (true); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} + + + + + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino new file mode 100644 index 0000000..ac8b4e5 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino @@ -0,0 +1,127 @@ +/* + Repeating WiFi Web Client + + This sketch connects to a a web server and makes a request + using an Arduino WiFi shield. + + Circuit: + * WiFi shield attached to pins SPI pins and pin 7 + + created 23 April 2012 + modified 31 May 2012 + by Tom Igoe + modified 13 Jan 2014 + by Federico Vanzati + + http://arduino.cc/en/Tutorial/WiFiWebClientRepeating + This code is in the public domain. + */ + +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int status = WL_IDLE_STATUS; + +// Initialize the WiFi client library +WiFiClient client; + +// server address: +char server[] = "www.arduino.cc"; +//IPAddress server(64,131,82,241); + +unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds +const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + // you're connected now, so print out the status: + printWiFiStatus(); +} + +void loop() { + // if there's incoming data from the net connection. + // send it out the serial port. This is for debugging + // purposes only: + while (client.available()) { + char c = client.read(); + Serial.write(c); + } + + // if ten seconds have passed since your last connection, + // then connect again and send data: + if (millis() - lastConnectionTime > postingInterval) { + httpRequest(); + } + +} + +// this method makes a HTTP connection to the server: +void httpRequest() { + // close any connection before send a new request. + // This will free the socket on the WiFi shield + client.stop(); + + // if there's a successful connection: + if (client.connect(server, 80)) { + Serial.println("connecting..."); + // send the HTTP PUT request: + client.println("GET /latest.txt HTTP/1.1"); + client.println("Host: www.arduino.cc"); + client.println("User-Agent: ArduinoWiFi/1.1"); + client.println("Connection: close"); + client.println(); + + // note the time that the connection was made: + lastConnectionTime = millis(); + } + else { + // if you couldn't make a connection: + Serial.println("connection failed"); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino new file mode 100644 index 0000000..24d0083 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino @@ -0,0 +1,135 @@ +/* + WiFi Web Server + + A simple web server that shows the value of the analog input pins. + using a WiFi shield. + + This example is written for a network using WPA encryption. For + WEP or WPA, change the WiFi.begin() call accordingly. + + Circuit: + * WiFi shield attached + * Analog inputs attached to pins A0 through A5 (optional) + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + + */ + +#include +#include + + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int status = WL_IDLE_STATUS; + +WiFiServer server(80); + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while (status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + server.begin(); + // you're connected now, so print out the status: + printWiFiStatus(); +} + + +void loop() { + // listen for incoming clients + WiFiClient client = server.available(); + if (client) { + Serial.println("new client"); + // an http request ends with a blank line + boolean currentLineIsBlank = true; + while (client.connected()) { + if (client.available()) { + char c = client.read(); + Serial.write(c); + // if you've gotten to the end of the line (received a newline + // character) and the line is blank, the http request has ended, + // so you can send a reply + if (c == '\n' && currentLineIsBlank) { + // send a standard http response header + client.println("HTTP/1.1 200 OK"); + client.println("Content-Type: text/html"); + client.println("Connection: close"); // the connection will be closed after completion of the response + client.println("Refresh: 5"); // refresh the page automatically every 5 sec + client.println(); + client.println(""); + client.println(""); + // output the value of each analog input pin + for (int analogChannel = 0; analogChannel < 6; analogChannel++) { + int sensorReading = analogRead(analogChannel); + client.print("analog input "); + client.print(analogChannel); + client.print(" is "); + client.print(sensorReading); + client.println("
"); + } + client.println(""); + break; + } + if (c == '\n') { + // you're starting a new line + currentLineIsBlank = true; + } + else if (c != '\r') { + // you've gotten a character on the current line + currentLineIsBlank = false; + } + } + } + // give the web browser time to receive the data + delay(1); + + // close the connection: + client.stop(); + Serial.println("client disconnected"); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit/libraries/WiFi101/keywords.txt b/feather_sensor_transmit/libraries/WiFi101/keywords.txt new file mode 100644 index 0000000..498954d --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/keywords.txt @@ -0,0 +1,61 @@ +####################################### +# Syntax Coloring Map For WiFi +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +WiFi KEYWORD1 +WiFi101 KEYWORD1 +Client KEYWORD1 +Server KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +setPins KEYWORD2 +status KEYWORD2 +connect KEYWORD2 +connectSSL KEYWORD2 +write KEYWORD2 +available KEYWORD2 +read KEYWORD2 +flush KEYWORD2 +stop KEYWORD2 +connected KEYWORD2 +begin KEYWORD2 +beginProvision KEYWORD2 +beginOrProvision KEYWORD2 +beginMulticast KEYWORD2 +disconnect KEYWORD2 +macAddress KEYWORD2 +localIP KEYWORD2 +subnetMask KEYWORD2 +gatewayIP KEYWORD2 +SSID KEYWORD2 +BSSID KEYWORD2 +APClientMacAddress KEYWORD2 +RSSI KEYWORD2 +encryptionType KEYWORD2 +channel KEYWORD2 +provisioned KEYWORD2 +getResult KEYWORD2 +getSocket KEYWORD2 +poll KEYWORD2 +getTime KEYWORD2 +hostname KEYWORD2 +WiFiClient KEYWORD2 +WiFiServer KEYWORD2 +WiFiSSLClient KEYWORD2 +WiFiMDNSResponder KEYWORD2 + +lowPowerMode KEYWORD2 +maxLowPowerMode KEYWORD2 +noLowPowerMode KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + diff --git a/feather_sensor_transmit/libraries/WiFi101/library.properties b/feather_sensor_transmit/libraries/WiFi101/library.properties new file mode 100644 index 0000000..f6d0b6d --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/library.properties @@ -0,0 +1,10 @@ +name=WiFi101 +version=0.14.4 +author=Arduino +maintainer=Arduino +sentence=Network driver for ATMEL WINC1500 module (used on Arduino/Genuino Wifi Shield 101 and MKR1000 boards) +paragraph=This library implements a network driver for devices based on the ATMEL WINC1500 wifi module +category=Communication +url=http://www.arduino.cc/en/Reference/WiFi101 +architectures=* +includes=WiFi101.h diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFi.cpp b/feather_sensor_transmit/libraries/WiFi101/src/WiFi.cpp new file mode 100644 index 0000000..0c71ffc --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/WiFi.cpp @@ -0,0 +1,1106 @@ +/* + WiFi.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifdef ARDUINO_ARCH_AVR +#include +#if (__AVR_LIBC_MAJOR__ < 2) +#define WIFI_101_NO_TIME_H +#endif +#endif + +#ifndef WIFI_101_NO_TIME_H +#include +#endif + +#if !defined(_TIME_H_) && !defined(TIME_H) +// another library overrided the time.h header +#define WIFI_101_NO_TIME_H +#endif + +#include "WiFi101.h" + +extern "C" { + #include "bsp/include/nm_bsp.h" + #include "bsp/include/nm_bsp_arduino.h" + #include "socket/include/socket_buffer.h" + #include "socket/include/m2m_socket_host_if.h" + #include "driver/source/nmasic.h" + #include "driver/include/m2m_periph.h" + #include "driver/include/m2m_ssl.h" +} + +static void wifi_cb(uint8_t u8MsgType, void *pvMsg) +{ + switch (u8MsgType) { + case M2M_WIFI_RESP_DEFAULT_CONNECT: + { + tstrM2MDefaultConnResp *pstrDefaultConnResp = (tstrM2MDefaultConnResp *)pvMsg; + if (pstrDefaultConnResp->s8ErrorCode) { + WiFi._status = WL_DISCONNECTED; + } + } + break; + + case M2M_WIFI_RESP_CON_STATE_CHANGED: + { + tstrM2mWifiStateChanged *pstrWifiState = (tstrM2mWifiStateChanged *)pvMsg; + if (pstrWifiState->u8CurrState == M2M_WIFI_CONNECTED) { + //SERIAL_PORT_MONITOR.println("wifi_cb: M2M_WIFI_RESP_CON_STATE_CHANGED: CONNECTED"); + if (WiFi._mode == WL_STA_MODE && !WiFi._dhcp) { + WiFi._status = WL_CONNECTED; + + // WiFi led ON. + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); + } else if (WiFi._mode == WL_AP_MODE) { + WiFi._status = WL_AP_CONNECTED; + } + } else if (pstrWifiState->u8CurrState == M2M_WIFI_DISCONNECTED) { + //SERIAL_PORT_MONITOR.println("wifi_cb: M2M_WIFI_RESP_CON_STATE_CHANGED: DISCONNECTED"); + if (WiFi._mode == WL_STA_MODE) { + WiFi._status = WL_DISCONNECTED; + if (WiFi._dhcp) { + WiFi._localip = 0; + WiFi._submask = 0; + WiFi._gateway = 0; + } + // Close sockets to clean state + // Clients will need to reconnect once the physical link will be re-established + for (int i=0; i < TCP_SOCK_MAX; i++) { + if (WiFi._client[i]) + WiFi._client[i]->stop(); + } + } else if (WiFi._mode == WL_AP_MODE) { + WiFi._status = WL_AP_LISTENING; + } + // WiFi led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); + } + } + break; + + case M2M_WIFI_REQ_DHCP_CONF: + { + if (WiFi._mode == WL_STA_MODE) { + tstrM2MIPConfig *pstrIPCfg = (tstrM2MIPConfig *)pvMsg; + WiFi._localip = pstrIPCfg->u32StaticIP; + WiFi._submask = pstrIPCfg->u32SubnetMask; + WiFi._gateway = pstrIPCfg->u32Gateway; + + WiFi._status = WL_CONNECTED; + + // WiFi led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0); + } + /*uint8_t *pu8IPAddress = (uint8_t *)pvMsg; + SERIAL_PORT_MONITOR.print("wifi_cb: M2M_WIFI_REQ_DHCP_CONF: IP is "); + SERIAL_PORT_MONITOR.print(pu8IPAddress[0], 10); + SERIAL_PORT_MONITOR.print("."); + SERIAL_PORT_MONITOR.print(pu8IPAddress[1], 10); + SERIAL_PORT_MONITOR.print("."); + SERIAL_PORT_MONITOR.print(pu8IPAddress[2], 10); + SERIAL_PORT_MONITOR.print("."); + SERIAL_PORT_MONITOR.print(pu8IPAddress[3], 10); + SERIAL_PORT_MONITOR.println("");*/ + } + break; + + case M2M_WIFI_RESP_CURRENT_RSSI: + { + WiFi._resolve = *((int8_t *)pvMsg); + } + break; + + case M2M_WIFI_RESP_PROVISION_INFO: + { + tstrM2MProvisionInfo *pstrProvInfo = (tstrM2MProvisionInfo *)pvMsg; + //SERIAL_PORT_MONITOR.println("wifi_cb: M2M_WIFI_RESP_PROVISION_INFO"); + + if (pstrProvInfo->u8Status == M2M_SUCCESS) { + memset(WiFi._ssid, 0, M2M_MAX_SSID_LEN); + memcpy(WiFi._ssid, (char *)pstrProvInfo->au8SSID, strlen((char *)pstrProvInfo->au8SSID)); + WiFi._mode = WL_STA_MODE; + WiFi._localip = 0; + WiFi._submask = 0; + WiFi._gateway = 0; + m2m_wifi_connect((char *)pstrProvInfo->au8SSID, strlen((char *)pstrProvInfo->au8SSID), + pstrProvInfo->u8SecType, pstrProvInfo->au8Password, M2M_WIFI_CH_ALL); + } else { + WiFi._status = WL_PROVISIONING_FAILED; + //SERIAL_PORT_MONITOR.println("wifi_cb: Provision failed.\r\n"); + WiFi.beginProvision(); + } + } + break; + + case M2M_WIFI_RESP_SCAN_DONE: + { + tstrM2mScanDone *pstrInfo = (tstrM2mScanDone *)pvMsg; + if (pstrInfo->u8NumofCh >= 1) { + WiFi._status = WL_SCAN_COMPLETED; + } + } + break; + + case M2M_WIFI_RESP_SCAN_RESULT: + { + tstrM2mWifiscanResult *pstrScanResult = (tstrM2mWifiscanResult *)pvMsg; + uint16_t scan_ssid_len = strlen((const char *)pstrScanResult->au8SSID); + memset(WiFi._scan_ssid, 0, M2M_MAX_SSID_LEN); + if (scan_ssid_len) { + memcpy(WiFi._scan_ssid, (const char *)pstrScanResult->au8SSID, scan_ssid_len); + } + if (WiFi._remoteMacAddress) { + // reverse copy the remote MAC + for(int i = 0; i < 6; i++) { + WiFi._remoteMacAddress[i] = pstrScanResult->au8BSSID[5-i]; + } + } + WiFi._resolve = pstrScanResult->s8rssi; + WiFi._scan_auth = pstrScanResult->u8AuthType; + WiFi._scan_channel = pstrScanResult->u8ch; + WiFi._status = WL_SCAN_COMPLETED; + } + break; + + case M2M_WIFI_RESP_CONN_INFO: + { + tstrM2MConnInfo *pstrConnInfo = (tstrM2MConnInfo*)pvMsg; + + if (WiFi._remoteMacAddress) { + // reverse copy the remote MAC + for(int i = 0; i < 6; i++) { + WiFi._remoteMacAddress[i] = pstrConnInfo->au8MACAddress[5-i]; + } + WiFi._remoteMacAddress = 0; + } + + strcpy((char *)WiFi._ssid, pstrConnInfo->acSSID); + } + break; + + case M2M_WIFI_RESP_GET_SYS_TIME: + { + if (WiFi._resolve != 0) { + memcpy((tstrSystemTime *)WiFi._resolve, pvMsg, sizeof(tstrSystemTime)); + + WiFi._resolve = 0; + } + } + break; + + default: + break; + } +} + +static void resolve_cb(uint8_t * /* hostName */, uint32_t hostIp) +{ + WiFi._resolve = hostIp; +} + +static void ping_cb(uint32 u32IPAddr, uint32 u32RTT, uint8 u8ErrorCode) +{ + if (PING_ERR_SUCCESS == u8ErrorCode) { + // Ensure this ICMP reply comes from requested IP address + if (WiFi._resolve == u32IPAddr) { + WiFi._resolve = (uint32_t)u32RTT; + } else { + // Another network device replied to the our ICMP request + WiFi._resolve = (uint32_t)WL_PING_DEST_UNREACHABLE; + } + } else if (PING_ERR_DEST_UNREACH == u8ErrorCode) { + WiFi._resolve = (uint32_t)WL_PING_DEST_UNREACHABLE; + } else if (PING_ERR_TIMEOUT == u8ErrorCode) { + WiFi._resolve = (uint32_t)WL_PING_TIMEOUT; + } else { + WiFi._resolve = (uint32_t)WL_PING_ERROR; + } +} + +WiFiClass::WiFiClass() +{ + _mode = WL_RESET_MODE; + _status = WL_NO_SHIELD; + _init = 0; +} + +void WiFiClass::setPins(int8_t cs, int8_t irq, int8_t rst, int8_t en) +{ + gi8Winc1501CsPin = cs; + gi8Winc1501IntnPin = irq; + gi8Winc1501ResetPin = rst; + gi8Winc1501ChipEnPin = en; +} + +int WiFiClass::init() +{ + tstrWifiInitParam param; + int8_t ret; + + // Initialize the WiFi BSP: + nm_bsp_init(); + + // Initialize WiFi module and register status callback: + param.pfAppWifiCb = wifi_cb; + ret = m2m_wifi_init(¶m); + if (M2M_SUCCESS != ret && M2M_ERR_FW_VER_MISMATCH != ret) { + // Error led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO18, 0); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO6, 1); + return ret; + } + + // Initialize socket API and register socket callback: + socketInit(); + socketBufferInit(); + registerSocketCallback(socketBufferCb, resolve_cb); + _init = 1; + _status = WL_IDLE_STATUS; + _localip = 0; + _submask = 0; + _gateway = 0; + _dhcp = 1; + _resolve = 0; + _remoteMacAddress = 0; + memset(_client, 0, sizeof(WiFiClient *) * TCP_SOCK_MAX); + + extern uint32 nmdrv_firm_ver; + + if (nmdrv_firm_ver >= M2M_MAKE_VERSION(19, 5, 0)) { + // enable AES-128 and AES-256 Ciphers, if firmware is 19.5.0 or higher + m2m_ssl_set_active_ciphersuites(SSL_NON_ECC_CIPHERS_AES_128 | SSL_NON_ECC_CIPHERS_AES_256); + } + + // Initialize IO expander LED control (rev A then rev B).. + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO18, 1); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO15, 1); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO18, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO6, 1); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO4, 1); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO5, 1); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO6, 1); + + return ret; +} + +extern "C" { + sint8 nm_get_firmware_info(tstrM2mRev* M2mRev); +} + +char* WiFiClass::firmwareVersion() +{ + tstrM2mRev rev; + + if (!_init) { + init(); + } + nm_get_firmware_info(&rev); + memset(_version, 0, 9); + if (rev.u8FirmwareMajor != rev.u8DriverMajor && rev.u8FirmwareMinor != rev.u8DriverMinor) { + sprintf(_version, "-Err-"); + } + else { + sprintf(_version, "%d.%d.%d", rev.u8FirmwareMajor, rev.u8FirmwareMinor, rev.u8FirmwarePatch); + } + return _version; +} + +uint8_t WiFiClass::begin() +{ + if (!_init) { + init(); + } + + // Connect to router: + if (_dhcp) { + _localip = 0; + _submask = 0; + _gateway = 0; + } + if (m2m_wifi_default_connect() < 0) { + _status = WL_CONNECT_FAILED; + return _status; + } + _status = WL_IDLE_STATUS; + _mode = WL_STA_MODE; + + // Wait for connection or timeout: + unsigned long start = millis(); + while (!(_status & WL_CONNECTED) && + !(_status & WL_DISCONNECTED) && + millis() - start < 60000) { + m2m_wifi_handle_events(NULL); + } + + memset(_ssid, 0, M2M_MAX_SSID_LEN); + + if (!(_status & WL_CONNECTED)) { + _mode = WL_RESET_MODE; + } else { + m2m_wifi_get_connection_info(); + + m2m_wifi_handle_events(NULL); + } + + return _status; +} + +uint8_t WiFiClass::begin(const char *ssid) +{ + return startConnect(ssid, M2M_WIFI_SEC_OPEN, (void *)0); +} + +uint8_t WiFiClass::begin(const char *ssid, uint8_t key_idx, const char* key) +{ + tstrM2mWifiWepParams wep_params; + + memset(&wep_params, 0, sizeof(tstrM2mWifiWepParams)); + wep_params.u8KeyIndx = key_idx; + wep_params.u8KeySz = strlen(key); + strcpy((char *)&wep_params.au8WepKey[0], key); + return startConnect(ssid, M2M_WIFI_SEC_WEP, &wep_params); +} + +uint8_t WiFiClass::begin(const char *ssid, const char *key) +{ + return startConnect(ssid, M2M_WIFI_SEC_WPA_PSK, key); +} + +uint8_t WiFiClass::startConnect(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo) +{ + if (!_init) { + init(); + } + + // Connect to router: + if (_dhcp) { + _localip = 0; + _submask = 0; + _gateway = 0; + } + if (m2m_wifi_connect((char*)ssid, strlen(ssid), u8SecType, (void*)pvAuthInfo, M2M_WIFI_CH_ALL) < 0) { + _status = WL_CONNECT_FAILED; + return _status; + } + _status = WL_IDLE_STATUS; + _mode = WL_STA_MODE; + + // Wait for connection or timeout: + unsigned long start = millis(); + while (!(_status & WL_CONNECTED) && + !(_status & WL_DISCONNECTED) && + millis() - start < 60000) { + m2m_wifi_handle_events(NULL); + } + if (!(_status & WL_CONNECTED)) { + _mode = WL_RESET_MODE; + } + + memset(_ssid, 0, M2M_MAX_SSID_LEN); + memcpy(_ssid, ssid, strlen(ssid)); + return _status; +} + +uint8_t WiFiClass::beginAP(const char *ssid) +{ + return beginAP(ssid, 1); +} + +uint8_t WiFiClass::beginAP(const char *ssid, uint8_t channel) +{ + return startAP(ssid, M2M_WIFI_SEC_OPEN, NULL, channel); +} + +uint8_t WiFiClass::beginAP(const char *ssid, uint8_t key_idx, const char* key) +{ + return beginAP(ssid, key_idx, key, 1); +} + +uint8_t WiFiClass::beginAP(const char *ssid, uint8_t key_idx, const char* key, uint8_t channel) +{ + tstrM2mWifiWepParams wep_params; + + if (key_idx == 0) { + key_idx = 1; // 1 is the minimum key index + } + + memset(&wep_params, 0, sizeof(tstrM2mWifiWepParams)); + wep_params.u8KeyIndx = key_idx; + wep_params.u8KeySz = strlen(key); + strcpy((char *)&wep_params.au8WepKey[0], key); + + return startAP(ssid, M2M_WIFI_SEC_WEP, &wep_params, channel); +} + +uint8_t WiFiClass::beginAP(const char *ssid, const char* key) +{ + return beginAP(ssid, key, 1); +} + +uint8_t WiFiClass::beginAP(const char *ssid, const char* key, uint8_t channel) +{ + return startAP(ssid, M2M_WIFI_SEC_WPA_PSK, key, channel); +} + +uint8_t WiFiClass::startAP(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo, uint8_t channel) +{ + tstrM2MAPConfig strM2MAPConfig; + + if (!_init) { + init(); + } + + if (channel == 0) { + channel = 1; // channel 1 is the minium channel + } + + // Enter Access Point mode: + memset(&strM2MAPConfig, 0x00, sizeof(tstrM2MAPConfig)); + strcpy((char *)&strM2MAPConfig.au8SSID, ssid); + strM2MAPConfig.u8ListenChannel = channel; + strM2MAPConfig.u8SecType = u8SecType; + if (_localip == 0) { + strM2MAPConfig.au8DHCPServerIP[0] = 192; + strM2MAPConfig.au8DHCPServerIP[1] = 168; + strM2MAPConfig.au8DHCPServerIP[2] = 1; + strM2MAPConfig.au8DHCPServerIP[3] = 1; + } else { + memcpy(strM2MAPConfig.au8DHCPServerIP, &_localip, sizeof(_localip)); + if (strM2MAPConfig.au8DHCPServerIP[3] == 100) { + // limitation of WINC1500 firmware, IP address of client is always x.x.x.100 + _status = WL_AP_FAILED; + return _status; + } + } + + if (u8SecType == M2M_WIFI_SEC_WEP) { + tstrM2mWifiWepParams* wep_params = (tstrM2mWifiWepParams*)pvAuthInfo; + + strM2MAPConfig.u8KeyIndx = wep_params->u8KeyIndx; + strM2MAPConfig.u8KeySz = wep_params->u8KeySz; + strcpy((char*)strM2MAPConfig.au8WepKey, (char *)wep_params->au8WepKey); + } + + if (u8SecType == M2M_WIFI_SEC_WPA_PSK) { + strM2MAPConfig.u8KeySz = strlen((char*)pvAuthInfo); + strcpy((char*)strM2MAPConfig.au8Key, (char *)pvAuthInfo); + } + + if (m2m_wifi_enable_ap(&strM2MAPConfig) < 0) { + _status = WL_AP_FAILED; + return _status; + } + _status = WL_AP_LISTENING; + _mode = WL_AP_MODE; + + memset(_ssid, 0, M2M_MAX_SSID_LEN); + memcpy(_ssid, ssid, strlen(ssid)); + m2m_memcpy((uint8 *)&_localip, (uint8 *)&strM2MAPConfig.au8DHCPServerIP[0], 4); + _submask = 0x00FFFFFF; + _gateway = _localip; + + // WiFi led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0); + + return _status; +} + +uint8_t WiFiClass::beginProvision() +{ + return beginProvision(1); +} + +uint8_t WiFiClass::beginProvision(uint8_t channel) +{ + // try to connect using begin + if (begin() != WL_CONNECTED) { + // failed, enter provisioning mode + + uint8_t mac[6]; + char provSsid[13]; + + // get MAC address for provisioning SSID + macAddress(mac); + sprintf(provSsid, "wifi101-%.2X%2X", mac[1], mac[0]); + + // start provisioning mode + startProvision(provSsid, "wifi101", channel); + } + + return status(); +} + +uint8_t WiFiClass::startProvision(const char *ssid, const char *url, uint8_t channel) +{ + tstrM2MAPConfig strM2MAPConfig; + + if (!_init) { + init(); + } + + // Enter Provision mode: + memset(&strM2MAPConfig, 0x00, sizeof(tstrM2MAPConfig)); + strcpy((char *)&strM2MAPConfig.au8SSID, ssid); + strM2MAPConfig.u8ListenChannel = channel; + strM2MAPConfig.u8SecType = M2M_WIFI_SEC_OPEN; + strM2MAPConfig.u8SsidHide = SSID_MODE_VISIBLE; + strM2MAPConfig.au8DHCPServerIP[0] = 192; + strM2MAPConfig.au8DHCPServerIP[1] = 168; + strM2MAPConfig.au8DHCPServerIP[2] = 1; + strM2MAPConfig.au8DHCPServerIP[3] = 1; + + if (m2m_wifi_start_provision_mode((tstrM2MAPConfig *)&strM2MAPConfig, (char*)url, 1) < 0) { + _status = WL_PROVISIONING_FAILED; + return _status; + } + _status = WL_PROVISIONING; + _mode = WL_PROV_MODE; + + memset(_ssid, 0, M2M_MAX_SSID_LEN); + memcpy(_ssid, ssid, strlen(ssid)); + m2m_memcpy((uint8 *)&_localip, (uint8 *)&strM2MAPConfig.au8DHCPServerIP[0], 4); + _submask = 0x00FFFFFF; + _gateway = _localip; + + // WiFi led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0); + + return _status; +} + +uint32_t WiFiClass::provisioned() +{ + m2m_wifi_handle_events(NULL); + + if (_mode == WL_STA_MODE) { + return 1; + } + else { + return 0; + } +} + +void WiFiClass::config(IPAddress local_ip) +{ + config(local_ip, (uint32_t)0); +} + +void WiFiClass::config(IPAddress local_ip, IPAddress dns_server) +{ + config(local_ip, dns_server, (uint32_t)0); +} + +void WiFiClass::config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway) +{ + config(local_ip, dns_server, gateway, (uint32_t)0); +} + +void WiFiClass::config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet) +{ + tstrM2MIPConfig conf; + + if (!_init) { + init(); + } + + conf.u32DNS = (uint32_t)dns_server; + conf.u32Gateway = (uint32_t)gateway; + conf.u32StaticIP = (uint32_t)local_ip; + conf.u32SubnetMask = (uint32_t)subnet; + _dhcp = 0; + m2m_wifi_enable_dhcp(0); // disable DHCP + m2m_wifi_set_static_ip(&conf); + _localip = conf.u32StaticIP; + _submask = conf.u32SubnetMask; + _gateway = conf.u32Gateway; +} + +void WiFiClass::hostname(const char* name) +{ + if (!_init) { + init(); + } + + m2m_wifi_set_device_name((uint8 *)name, strlen(name)); +} + +void WiFiClass::disconnect() +{ + m2m_wifi_disconnect(); + + // WiFi led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); +} + +void WiFiClass::end() +{ + if (_mode == WL_AP_MODE) { + m2m_wifi_disable_ap(); + } else { + if (_mode == WL_PROV_MODE) { + m2m_wifi_stop_provision_mode(); + } + + m2m_wifi_disconnect(); + } + + // WiFi led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); + + socketDeinit(); + + m2m_wifi_deinit(NULL); + + nm_bsp_deinit(); + + _mode = WL_RESET_MODE; + _status = WL_NO_SHIELD; + _init = 0; +} + +uint8_t *WiFiClass::macAddress(uint8_t *mac) +{ + m2m_wifi_get_mac_address(mac); + byte tmpMac[6], i; + + m2m_wifi_get_mac_address(tmpMac); + + for(i = 0; i < 6; i++) + mac[i] = tmpMac[5-i]; + + return mac; +} + +uint32_t WiFiClass::localIP() +{ + return _localip; +} + +uint32_t WiFiClass::subnetMask() +{ + return _submask; +} + +uint32_t WiFiClass::gatewayIP() +{ + return _gateway; +} + +char* WiFiClass::SSID() +{ + if (_status == WL_CONNECTED || _status == WL_AP_LISTENING || _status == WL_AP_CONNECTED) { + return _ssid; + } + else { + return 0; + } +} + +uint8_t* WiFiClass::BSSID(uint8_t* bssid) +{ + if (_mode == WL_AP_MODE) { + return macAddress(bssid); + } else { + return remoteMacAddress(bssid); + } +} + +uint8_t* WiFiClass::APClientMacAddress(uint8_t* mac) +{ + if (_mode == WL_AP_MODE) { + return remoteMacAddress(mac); + } else { + memset(mac, 0, 6); + return mac; + } +} + +uint8_t* WiFiClass::remoteMacAddress(uint8_t* remoteMacAddress) +{ + _remoteMacAddress = remoteMacAddress; + memset(remoteMacAddress, 0, 6); + + m2m_wifi_get_connection_info(); + + // Wait for connection or timeout: + unsigned long start = millis(); + while (_remoteMacAddress != 0 && millis() - start < 1000) { + m2m_wifi_handle_events(NULL); + } + + _remoteMacAddress = 0; + return remoteMacAddress; +} + +int32_t WiFiClass::RSSI() +{ + // Clear pending events: + m2m_wifi_handle_events(NULL); + + // Send RSSI request: + _resolve = 0; + if (m2m_wifi_req_curr_rssi() < 0) { + return 0; + } + + // Wait for connection or timeout: + unsigned long start = millis(); + while (_resolve == 0 && millis() - start < 1000) { + m2m_wifi_handle_events(NULL); + } + + int32_t rssi = _resolve; + + _resolve = 0; + + return rssi; +} + +int8_t WiFiClass::scanNetworks() +{ + wl_status_t tmp = _status; + + if (!_init) { + init(); + } + + // Start scan: + if (m2m_wifi_request_scan(M2M_WIFI_CH_ALL) < 0) { + return 0; + } + + // Wait for scan result or timeout: + _status = WL_IDLE_STATUS; + unsigned long start = millis(); + while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 5000) { + m2m_wifi_handle_events(NULL); + } + _status = tmp; + return m2m_wifi_get_num_ap_found(); +} + +char* WiFiClass::SSID(uint8_t pos) +{ + wl_status_t tmp = _status; + + // Get scan SSID result: + memset(_scan_ssid, 0, M2M_MAX_SSID_LEN); + if (m2m_wifi_req_scan_result(pos) < 0) { + return 0; + } + + // Wait for connection or timeout: + _status = WL_IDLE_STATUS; + unsigned long start = millis(); + while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + + _status = tmp; + _resolve = 0; + + return _scan_ssid; +} + +int32_t WiFiClass::RSSI(uint8_t pos) +{ + wl_status_t tmp = _status; + + // Get scan RSSI result: + if (m2m_wifi_req_scan_result(pos) < 0) { + return 0; + } + + // Wait for connection or timeout: + _status = WL_IDLE_STATUS; + unsigned long start = millis(); + while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + + _status = tmp; + + int32_t rssi = _resolve; + + _resolve = 0; + + return rssi; +} + +uint8_t WiFiClass::encryptionType() +{ + int8_t net = scanNetworks(); + + for (uint8_t i = 0; i < net; ++i) { + SSID(i); + if (strcmp(_scan_ssid, _ssid) == 0) { + break; + } + } + + return _scan_auth; +} + +uint8_t WiFiClass::encryptionType(uint8_t pos) +{ + wl_status_t tmp = _status; + + // Get scan auth result: + if (m2m_wifi_req_scan_result(pos) < 0) { + return 0; + } + + // Wait for connection or timeout: + _status = WL_IDLE_STATUS; + unsigned long start = millis(); + while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + + _status = tmp; + _resolve = 0; + + return _scan_auth; +} + +uint8_t* WiFiClass::BSSID(uint8_t pos, uint8_t* bssid) +{ + wl_status_t tmp = _status; + + _remoteMacAddress = bssid; + + // Get scan auth result: + if (m2m_wifi_req_scan_result(pos) < 0) { + return 0; + } + + // Wait for connection or timeout: + _status = WL_IDLE_STATUS; + unsigned long start = millis(); + while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + + _status = tmp; + _resolve = 0; + _remoteMacAddress = 0; + + return bssid; +} + +uint8_t WiFiClass::channel(uint8_t pos) +{ + wl_status_t tmp = _status; + + // Get scan auth result: + if (m2m_wifi_req_scan_result(pos) < 0) { + return 0; + } + + // Wait for connection or timeout: + _status = WL_IDLE_STATUS; + unsigned long start = millis(); + while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + + _status = tmp; + _resolve = 0; + + return _scan_channel; +} + +uint8_t WiFiClass::status() +{ + if (!_init) { + init(); + } + + m2m_wifi_handle_events(NULL); + + return _status; +} + +int WiFiClass::hostByName(const char* aHostname, IPAddress& aResult) +{ + + // check if aHostname is already an ipaddress + if (aResult.fromString(aHostname)) { + // if fromString returns true we have an IP address ready + return 1; + + } else { + // Network led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); + + // Send DNS request: + _resolve = 0; + if (gethostbyname((uint8 *)aHostname) < 0) { + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + return 0; + } + + // Wait for connection or timeout: + unsigned long start = millis(); + while (_resolve == 0 && millis() - start < 20000) { + m2m_wifi_handle_events(NULL); + } + + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + + if (_resolve == 0) { + return 0; + } + + aResult = _resolve; + _resolve = 0; + return 1; + } +} + +void WiFiClass::refresh(void) +{ + // Update state machine: + m2m_wifi_handle_events(NULL); +} + +void WiFiClass::lowPowerMode(void) +{ + m2m_wifi_set_sleep_mode(M2M_PS_H_AUTOMATIC, true); +} + +void WiFiClass::maxLowPowerMode(void) +{ + m2m_wifi_set_sleep_mode(M2M_PS_DEEP_AUTOMATIC, true); +} + +void WiFiClass::noLowPowerMode(void) +{ + m2m_wifi_set_sleep_mode(M2M_NO_PS, false); +} + +int WiFiClass::ping(const char* hostname, uint8_t ttl) +{ + IPAddress ip; + + if (hostByName(hostname, ip) > 0) { + return ping(ip, ttl); + } else { + return WL_PING_UNKNOWN_HOST; + } +} + +int WiFiClass::ping(const String &hostname, uint8_t ttl) +{ + return ping(hostname.c_str(), ttl); +} + +int WiFiClass::ping(IPAddress host, uint8_t ttl) +{ + // Network led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); + + uint32_t dstHost = (uint32_t)host; + _resolve = dstHost; + + if (m2m_ping_req((uint32_t)host, ttl, &ping_cb) < 0) { + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + // Error sending ping request + return WL_PING_ERROR; + } + + // Wait for success or timeout: + unsigned long start = millis(); + while (_resolve == dstHost && millis() - start < 5000) { + m2m_wifi_handle_events(NULL); + } + + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + + if (_resolve == dstHost) { + _resolve = 0; + return WL_PING_TIMEOUT; + } else { + int rtt = (int)_resolve; + _resolve = 0; + return rtt; + } +} + +uint32_t WiFiClass::getTime() +{ +#ifdef WIFI_101_NO_TIME_H + #warning "No system header included, WiFi.getTime() will always return 0" + return 0; +#else + tstrSystemTime systemTime; + + _resolve = (uint32_t)&systemTime; + + m2m_wifi_get_sytem_time(); + + unsigned long start = millis(); + while (_resolve != 0 && millis() - start < 5000) { + m2m_wifi_handle_events(NULL); + } + + time_t t = 0; + + if (_resolve == 0 && systemTime.u16Year > 0) { + struct tm tm; + + tm.tm_year = systemTime.u16Year - 1900; + tm.tm_mon = systemTime.u8Month - 1; + tm.tm_mday = systemTime.u8Day; + tm.tm_hour = systemTime.u8Hour; + tm.tm_min = systemTime.u8Minute; + tm.tm_sec = systemTime.u8Second; + tm.tm_isdst = -1; + + t = mktime(&tm); + } + + _resolve = 0; + + return t; +#endif +} + +WiFiClass WiFi; diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFi101.h b/feather_sensor_transmit/libraries/WiFi101/src/WiFi101.h new file mode 100644 index 0000000..6e46fab --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/WiFi101.h @@ -0,0 +1,193 @@ +/* + WiFi.h - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef WIFI_H +#define WIFI_H + +#define WIFI_FIRMWARE_LATEST_MODEL_A "19.4.4" +#define WIFI_FIRMWARE_LATEST_MODEL_B "19.5.2" + +// for backwards compatibility +#define WIFI_FIRMWARE_REQUIRED WIFI_FIRMWARE_LATEST_MODEL_B + +#include + +extern "C" { + #include "driver/include/m2m_wifi.h" + #include "socket/include/socket.h" +} + +#include "WiFiClient.h" +#include "WiFiSSLClient.h" +#include "WiFiServer.h" + +typedef enum { + WL_NO_SHIELD = 255, + WL_IDLE_STATUS = 0, + WL_NO_SSID_AVAIL, + WL_SCAN_COMPLETED, + WL_CONNECTED, + WL_CONNECT_FAILED, + WL_CONNECTION_LOST, + WL_DISCONNECTED, + WL_AP_LISTENING, + WL_AP_CONNECTED, + WL_AP_FAILED, + WL_PROVISIONING, + WL_PROVISIONING_FAILED +} wl_status_t; + +/* Encryption modes */ +enum wl_enc_type { /* Values map to 802.11 encryption suites... */ + ENC_TYPE_WEP = M2M_WIFI_SEC_WEP, + ENC_TYPE_TKIP = M2M_WIFI_SEC_WPA_PSK, + ENC_TYPE_CCMP = M2M_WIFI_SEC_802_1X, + /* ... except these two, 7 and 8 are reserved in 802.11-2007 */ + ENC_TYPE_NONE = M2M_WIFI_SEC_OPEN, + ENC_TYPE_AUTO = M2M_WIFI_SEC_INVALID +}; + +typedef enum { + WL_RESET_MODE = 0, + WL_STA_MODE, + WL_PROV_MODE, + WL_AP_MODE +} wl_mode_t; + +typedef enum { + WL_PING_DEST_UNREACHABLE = -1, + WL_PING_TIMEOUT = -2, + WL_PING_UNKNOWN_HOST = -3, + WL_PING_ERROR = -4 +} wl_ping_result_t; + +class WiFiClass +{ +public: + uint32_t _localip; + uint32_t _submask; + uint32_t _gateway; + int _dhcp; + uint32_t _resolve; + byte *_remoteMacAddress; + wl_mode_t _mode; + wl_status_t _status; + char _scan_ssid[M2M_MAX_SSID_LEN]; + uint8_t _scan_auth; + uint8_t _scan_channel; + char _ssid[M2M_MAX_SSID_LEN]; + WiFiClient *_client[TCP_SOCK_MAX]; + + WiFiClass(); + + void setPins(int8_t cs, int8_t irq, int8_t rst, int8_t en = -1); + + int init(); + + char* firmwareVersion(); + + /* Start Wifi connection with WPA/WPA2 encryption. + * + * param ssid: Pointer to the SSID string. + * param key: Key input buffer. + */ + uint8_t begin(); + uint8_t begin(const char *ssid); + uint8_t begin(const char *ssid, uint8_t key_idx, const char* key); + uint8_t begin(const char *ssid, const char *key); + uint8_t begin(const String &ssid) { return begin(ssid.c_str()); } + uint8_t begin(const String &ssid, uint8_t key_idx, const String &key) { return begin(ssid.c_str(), key_idx, key.c_str()); } + uint8_t begin(const String &ssid, const String &key) { return begin(ssid.c_str(), key.c_str()); } + + /* Start Wifi in Access Point, with open security. + * Only one client can connect to the AP at a time. + * + * param ssid: Pointer to the SSID string. + * param channel: Wifi channel to use. Valid values are 1-12. + */ + uint8_t beginAP(const char *ssid); + uint8_t beginAP(const char *ssid, uint8_t channel); + uint8_t beginAP(const char *ssid, uint8_t key_idx, const char* key); + uint8_t beginAP(const char *ssid, uint8_t key_idx, const char* key, uint8_t channel); + uint8_t beginAP(const char *ssid, const char* key); + uint8_t beginAP(const char *ssid, const char* key, uint8_t channel); + + uint8_t beginProvision(); + uint8_t beginProvision(uint8_t channel); + + uint32_t provisioned(); + + void config(IPAddress local_ip); + void config(IPAddress local_ip, IPAddress dns_server); + void config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway); + void config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet); + + void hostname(const char* name); + + void disconnect(); + void end(); + + uint8_t *macAddress(uint8_t *mac); + + uint32_t localIP(); + uint32_t subnetMask(); + uint32_t gatewayIP(); + char* SSID(); + int32_t RSSI(); + uint8_t encryptionType(); + uint8_t* BSSID(uint8_t* bssid); + uint8_t* APClientMacAddress(uint8_t* mac); + int8_t scanNetworks(); + char* SSID(uint8_t pos); + int32_t RSSI(uint8_t pos); + uint8_t encryptionType(uint8_t pos); + uint8_t* BSSID(uint8_t pos, uint8_t* bssid); + uint8_t channel(uint8_t pos); + + uint8_t status(); + + int hostByName(const char* hostname, IPAddress& result); + int hostByName(const String &hostname, IPAddress& result) { return hostByName(hostname.c_str(), result); } + + int ping(const char* hostname, uint8_t ttl = 128); + int ping(const String &hostname, uint8_t ttl = 128); + int ping(IPAddress host, uint8_t ttl = 128); + + unsigned long getTime(); + + void refresh(void); + + void lowPowerMode(void); + void maxLowPowerMode(void); + void noLowPowerMode(void); + +private: + int _init; + char _version[9]; + + uint8_t startConnect(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo); + uint8_t startAP(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo, uint8_t channel); + uint8_t* remoteMacAddress(uint8_t* remoteMacAddress); + + uint8_t startProvision(const char *ssid, const char *url, uint8_t channel); +}; + +extern WiFiClass WiFi; + +#endif /* WIFI_H */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiClient.cpp b/feather_sensor_transmit/libraries/WiFi101/src/WiFiClient.cpp new file mode 100644 index 0000000..8298618 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/WiFiClient.cpp @@ -0,0 +1,308 @@ +/* + WiFiClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +extern "C" { + #include "socket/include/socket.h" + #include "driver/include/m2m_periph.h" +} + +#include "WiFi101.h" +#include "WiFiClient.h" + +#define IS_CONNECTED (_flag & SOCKET_BUFFER_FLAG_CONNECTED) + +WiFiClient::WiFiClient() +{ + _socket = -1; + _flag = 0; + _head = 0; + _tail = 0; +} + +WiFiClient::WiFiClient(uint8_t sock, uint8_t parentsock) +{ + // Spawn connected TCP client from TCP server socket: + _socket = sock; + _flag = SOCKET_BUFFER_FLAG_CONNECTED; + if (parentsock) { + _flag |= ((uint32_t)parentsock) << SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS; + } + _head = 0; + _tail = 0; + for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { + if (WiFi._client[sock] == this) + WiFi._client[sock] = 0; + } + WiFi._client[_socket] = this; + + // Add socket buffer handler: + socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_buffer); + + // Enable receive buffer: + recv(_socket, _buffer, SOCKET_BUFFER_MTU, 0); + + m2m_wifi_handle_events(NULL); +} + +WiFiClient::WiFiClient(const WiFiClient& other) +{ + copyFrom(other); +} + +void WiFiClient::copyFrom(const WiFiClient& other) +{ + _socket = other._socket; + _flag = other._flag; + _head = other._head; + _tail = other._tail; + if (_head > _tail) { + memcpy(_buffer + _tail, other._buffer + _tail, (_head - _tail)); + } + + for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { + if (WiFi._client[sock] == this) + WiFi._client[sock] = 0; + } + + if (_socket > -1) { + WiFi._client[_socket] = this; + + // Add socket buffer handler: + socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_buffer); + + // Enable receive buffer: + recv(_socket, _buffer, SOCKET_BUFFER_MTU, 0); + } + + m2m_wifi_handle_events(NULL); +} + +int WiFiClient::connectSSL(const char* host, uint16_t port) +{ + return connect(host, port, SOCKET_FLAGS_SSL); +} + +int WiFiClient::connectSSL(IPAddress ip, uint16_t port) +{ + return connect(ip, port, SOCKET_FLAGS_SSL, 0); +} + +int WiFiClient::connect(const char* host, uint16_t port) +{ + return connect(host, port, 0); +} + +int WiFiClient::connect(IPAddress ip, uint16_t port) +{ + return connect(ip, port, 0, 0); +} + +int WiFiClient::connect(const char* host, uint16_t port, uint8_t opt) +{ + IPAddress remote_addr; + if (WiFi.hostByName(host, remote_addr)) { + return connect(remote_addr, port, opt, (const uint8_t *)host); + } + return 0; +} + +int WiFiClient::connect(IPAddress ip, uint16_t port, uint8_t opt, const uint8_t *hostname) +{ + struct sockaddr_in addr; + + // Initialize socket address structure: + addr.sin_family = AF_INET; + addr.sin_port = _htons(port); + addr.sin_addr.s_addr = ip; + + // Create TCP socket: + _flag = 0; + _head = 0; + _tail = 0; + if ((_socket = socket(AF_INET, SOCK_STREAM, opt)) < 0) { + return 0; + } + + if (opt & SOCKET_FLAGS_SSL && hostname) { + setsockopt(_socket, SOL_SSL_SOCKET, SO_SSL_SNI, hostname, m2m_strlen((uint8_t *)hostname)); + } + + // Add socket buffer handler: + socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_buffer); + + // Connect to remote host: + if (connectSocket(_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { + close(_socket); + _socket = -1; + return 0; + } + + // Wait for connection or timeout: + unsigned long start = millis(); + while (!IS_CONNECTED && millis() - start < 20000) { + m2m_wifi_handle_events(NULL); + } + if (!IS_CONNECTED) { + close(_socket); + _socket = -1; + return 0; + } + + WiFi._client[_socket] = this; + + return 1; +} + +size_t WiFiClient::write(uint8_t b) +{ + return write(&b, 1); +} + +size_t WiFiClient::write(const uint8_t *buf, size_t size) +{ + sint16 err; + + if (_socket < 0 || size == 0 || !IS_CONNECTED) { + setWriteError(); + return 0; + } + + // Network led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); + + m2m_wifi_handle_events(NULL); + + while ((err = send(_socket, (void *)buf, size, 0)) < 0) { + // Exit on fatal error, retry if buffer not ready. + if (err != SOCK_ERR_BUFFER_FULL) { + setWriteError(); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + return 0; + } + m2m_wifi_handle_events(NULL); + } + + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + + return size; +} + +int WiFiClient::available() +{ + m2m_wifi_handle_events(NULL); + + if (_socket != -1) { + return _head - _tail; + } + return 0; +} + +int WiFiClient::read() +{ + uint8_t b; + + if (read(&b, sizeof(b)) == -1) { + return -1; + } + + return b; +} + +int WiFiClient::read(uint8_t* buf, size_t size) +{ + // sizeof(size_t) is architecture dependent + // but we need a 16 bit data type here + uint16_t size_tmp = available(); + + if (size_tmp == 0) { + return -1; + } + + if (size < size_tmp) { + size_tmp = size; + } + + for (uint32_t i = 0; i < size_tmp; ++i) { + buf[i] = _buffer[_tail++]; + } + + if (_tail == _head) { + _tail = _head = 0; + _flag &= ~SOCKET_BUFFER_FLAG_FULL; + recv(_socket, _buffer, SOCKET_BUFFER_MTU, 0); + m2m_wifi_handle_events(NULL); + } + + return size_tmp; +} + +int WiFiClient::peek() +{ + if (!available()) + return -1; + + return _buffer[_tail]; +} + +void WiFiClient::flush() +{ + while (available()) + read(); +} + +void WiFiClient::stop() +{ + if (_socket < 0) + return; + + socketBufferUnregister(_socket); + close(_socket); + _socket = -1; + _flag = 0; +} + +uint8_t WiFiClient::connected() +{ + m2m_wifi_handle_events(NULL); + if (available()) + return 1; + return IS_CONNECTED; +} + +uint8_t WiFiClient::status() +{ + // Deprecated. + return 0; +} + +WiFiClient::operator bool() +{ + return _socket != -1; +} + +WiFiClient& WiFiClient::operator =(const WiFiClient& other) +{ + copyFrom(other); + + return *this; +} diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiClient.h b/feather_sensor_transmit/libraries/WiFi101/src/WiFiClient.h new file mode 100644 index 0000000..bef171d --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/WiFiClient.h @@ -0,0 +1,68 @@ +/* + WiFiClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef WIFICLIENT_H +#define WIFICLIENT_H + +#include +#include +#include +#include "socket/include/socket_buffer.h" + +class WiFiClient : public Client { + +public: + WiFiClient(); + WiFiClient(uint8_t sock, uint8_t parentsock = 0); + WiFiClient(const WiFiClient& other); + + uint8_t status(); + + int connectSSL(IPAddress ip, uint16_t port); + int connectSSL(const char* host, uint16_t port); + virtual int connect(IPAddress ip, uint16_t port); + virtual int connect(const char* host, uint16_t port); + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + virtual int available(); + virtual int read(); + virtual int read(uint8_t *buf, size_t size); + virtual int peek(); + virtual void flush(); + virtual void stop(); + virtual uint8_t connected(); + virtual operator bool(); + virtual WiFiClient& operator =(const WiFiClient& other); + + using Print::write; + + uint32_t _flag; + +private: + SOCKET _socket; + uint32_t _head; + uint32_t _tail; + uint8_t _buffer[SOCKET_BUFFER_TCP_SIZE]; + int connect(const char* host, uint16_t port, uint8_t opt); + int connect(IPAddress ip, uint16_t port, uint8_t opt, const uint8_t *hostname); + void copyFrom(const WiFiClient& other); + +}; + +#endif /* WIFICLIENT_H */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiMDNSResponder.cpp b/feather_sensor_transmit/libraries/WiFi101/src/WiFiMDNSResponder.cpp new file mode 100644 index 0000000..a192113 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/WiFiMDNSResponder.cpp @@ -0,0 +1,220 @@ +// Port of CC3000 MDNS Responder to WINC1500. +// Author: Tony DiCola +// +// This MDNSResponder class implements just enough MDNS functionality to respond +// to name requests, for example 'foo.local'. This does not implement any other +// MDNS or Bonjour functionality like services, etc. +// +// Copyright (c) 2016 Adafruit Industries. All right reserved. +// +// 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 2.1 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 Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +#include +#ifndef ARDUINO_ARCH_AVR +#include +#endif + +#include "Arduino.h" +#include "WiFiMDNSResponder.h" + +// Important RFC's for reference: +// - DNS request and response: http://www.ietf.org/rfc/rfc1035.txt +// - Multicast DNS: http://www.ietf.org/rfc/rfc6762.txt + +#define HEADER_SIZE 12 +#define TTL_OFFSET 4 +#define IP_OFFSET 10 + +const uint8_t expectedRequestHeader[HEADER_SIZE] PROGMEM = { + 0x00, 0x00, + 0x00, 0x00, + 0x00, 0x01, // questions (these 2 bytes are ignored) + 0x00, 0x00, + 0x00, 0x00, + 0x00, 0x00 +}; + +const uint8_t responseHeader[] PROGMEM = { + 0x00, 0x00, // ID = 0 + 0x84, 0x00, // Flags = response + authoritative answer + 0x00, 0x00, // Question count = 0 + 0x00, 0x01, // Answer count = 1 + 0x00, 0x00, // Name server records = 0 + 0x00, 0x01 // Additional records = 1 +}; + +// Generate positive response for IPV4 address +const uint8_t aRecord[] PROGMEM = { + 0x00, 0x01, // Type = 1, A record/IPV4 address + 0x80, 0x01, // Class = Internet, with cache flush bit + 0x00, 0x00, 0x00, 0x00, // TTL in seconds, to be filled in later + 0x00, 0x04, // Length of record + 0x00, 0x00, 0x00, 0x00 // IP address, to be filled in later +}; + +// Generate negative response for IPV6 address (CC3000 doesn't support IPV6) +const uint8_t nsecRecord[] PROGMEM = { + 0xC0, 0x0C, // Name offset + 0x00, 0x2F, // Type = 47, NSEC (overloaded by MDNS) + 0x80, 0x01, // Class = Internet, with cache flush bit + 0x00, 0x00, 0x00, 0x00, // TTL in seconds, to be filled in later + 0x00, 0x08, // Length of record + 0xC0, 0x0C, // Next domain = offset to FQDN + 0x00, // Block number = 0 + 0x04, // Length of bitmap = 4 bytes + 0x40, 0x00, 0x00, 0x00 // Bitmap value = Only first bit (A record/IPV4) is set +}; + +const uint8_t domain[] PROGMEM = { 'l', 'o', 'c', 'a', 'l' }; + +WiFiMDNSResponder::WiFiMDNSResponder() : + minimumExpectedRequestLength(0) +{ +} + +WiFiMDNSResponder::~WiFiMDNSResponder() +{ +} + +bool WiFiMDNSResponder::begin(const char* _name, uint32_t _ttlSeconds) +{ + int nameLength = strlen(_name); + + if (nameLength > 255) { + // Can only handle domains that are upto 255 chars in length. + minimumExpectedRequestLength = 0; + return false; + } + + name = _name; + ttlSeconds = _ttlSeconds; + + name.toLowerCase(); + minimumExpectedRequestLength = HEADER_SIZE + 1 + nameLength + 1 + sizeof(domain) + 5; + + // Open the MDNS UDP listening socket on port 5353 with multicast address + // 224.0.0.251 (0xE00000FB) + if (!udpSocket.beginMulticast(IPAddress(224, 0, 0, 251), 5353)) { + return false; + } + + return true; +} + +void WiFiMDNSResponder::poll() +{ + if (parseRequest()) { + replyToRequest(); + } +} + +bool WiFiMDNSResponder::parseRequest() +{ + int packetLength = udpSocket.parsePacket(); + + if (packetLength) { + // check if parsed packet matches expected request length + if (packetLength < minimumExpectedRequestLength) { + // it does not, read the full packet in and drop data + while(udpSocket.available()) { + udpSocket.read(); + } + + return false; + } + + // read up to the min expect request length + uint8_t request[minimumExpectedRequestLength]; + udpSocket.read(request, minimumExpectedRequestLength); + + // discard the rest + while(udpSocket.available()) { + udpSocket.read(); + } + + // parse request + uint8_t requestNameLength = request[HEADER_SIZE]; + uint8_t* requestName = &request[HEADER_SIZE + 1]; + uint8_t requestDomainLength = request[HEADER_SIZE + 1 + requestNameLength]; + uint8_t* requestDomain = &request[HEADER_SIZE + 1 + requestNameLength + 1]; + uint16_t requestQtype; + uint16_t requestQclass; + + memcpy(&requestQtype, &request[minimumExpectedRequestLength - 4], sizeof(requestQtype)); + memcpy(&requestQclass, &request[minimumExpectedRequestLength - 2], sizeof(requestQclass)); + + requestQtype = _ntohs(requestQtype); + requestQclass = _ntohs(requestQclass); + + // compare request + if (memcmp_P(request, expectedRequestHeader, 4) == 0 && // request header start match + memcmp_P(&request[6], &expectedRequestHeader[6], 6) == 0 && // request header end match + requestNameLength == name.length() && // name length match + strncasecmp(name.c_str(), (char*)requestName, requestNameLength) == 0 && // name match + requestDomainLength == sizeof(domain) && // domain length match + memcmp_P(requestDomain, domain, requestDomainLength) == 0 && // suffix match + requestQtype == 0x0001 && // request QType match + requestQclass == 0x0001) { // request QClass match + + return true; + } + } + + return false; +} + +void WiFiMDNSResponder::replyToRequest() +{ + int nameLength = name.length(); + int domainLength = sizeof(domain); + uint32_t ipAddress = WiFi.localIP(); + uint32_t ttl = _htonl(ttlSeconds); + + int responseSize = sizeof(responseHeader) + 1 + nameLength + 1 + domainLength + 1 + sizeof(aRecord) + sizeof(nsecRecord); + uint8_t response[responseSize]; + uint8_t* r = response; + + // copy header + memcpy_P(r, responseHeader, sizeof(responseHeader)); + r += sizeof(responseHeader); + + // copy name + *r = nameLength; + memcpy(r + 1, name.c_str(), nameLength); + r += (1 + nameLength); + + // copy domain + *r = domainLength; + memcpy_P(r + 1, domain, domainLength); + r += (1 + domainLength); + + // terminator + *r = 0x00; + r++; + + // copy A record + memcpy_P(r, aRecord, sizeof(aRecord)); + memcpy(r + TTL_OFFSET, &ttl, sizeof(ttl)); // replace TTL value + memcpy(r + IP_OFFSET, &ipAddress, sizeof(ipAddress)); // replace IP address value + r += sizeof(aRecord); + + // copy NSEC record + memcpy_P(r, nsecRecord, sizeof(nsecRecord)); + r += sizeof(nsecRecord); + + udpSocket.beginPacket(IPAddress(224, 0, 0, 251), 5353); + udpSocket.write(response, responseSize); + udpSocket.endPacket(); +} diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiMDNSResponder.h b/feather_sensor_transmit/libraries/WiFi101/src/WiFiMDNSResponder.h new file mode 100644 index 0000000..d7e3d43 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/WiFiMDNSResponder.h @@ -0,0 +1,51 @@ +// Port of CC3000 MDNS Responder to WINC1500. +// Author: Tony DiCola +// +// This MDNSResponder class implements just enough MDNS functionality to respond +// to name requests, for example 'foo.local'. This does not implement any other +// MDNS or Bonjour functionality like services, etc. +// +// Copyright (c) 2016 Adafruit Industries. All right reserved. +// +// 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 2.1 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 Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +#ifndef WIFIMDNSRESPONDER_H +#define WIFIMDNSRESPONDER_H + +#include "WiFi101.h" +#include "WiFiUdp.h" + +class WiFiMDNSResponder { +public: + WiFiMDNSResponder(); + ~WiFiMDNSResponder(); + bool begin(const char* _name, uint32_t _ttlSeconds = 3600); + void poll(); + +private: + bool parseRequest(); + void replyToRequest(); + +private: + String name; + uint32_t ttlSeconds; + + int minimumExpectedRequestLength; + + // UDP socket for receiving/sending MDNS data. + WiFiUDP udpSocket; +}; + +#endif diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiSSLClient.cpp b/feather_sensor_transmit/libraries/WiFi101/src/WiFiSSLClient.cpp new file mode 100644 index 0000000..e7be43c --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/WiFiSSLClient.cpp @@ -0,0 +1,45 @@ +/* + WiFiSSLClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "WiFiSSLClient.h" + +WiFiSSLClient::WiFiSSLClient() : + WiFiClient() +{ +} + +WiFiSSLClient::WiFiSSLClient(uint8_t sock, uint8_t parentsock) : + WiFiClient(sock, parentsock) +{ +} + +WiFiSSLClient::WiFiSSLClient(const WiFiSSLClient& other) : + WiFiClient(other) +{ +} + +int WiFiSSLClient::connect(IPAddress ip, uint16_t port) +{ + return WiFiClient::connectSSL(ip, port); +} + +int WiFiSSLClient::connect(const char* host, uint16_t port) +{ + return WiFiClient::connectSSL(host, port); +} diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiSSLClient.h b/feather_sensor_transmit/libraries/WiFi101/src/WiFiSSLClient.h new file mode 100644 index 0000000..c5851e5 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/WiFiSSLClient.h @@ -0,0 +1,36 @@ +/* + WiFiSSLClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef WIFISSLCLIENT_H +#define WIFISSLCLIENT_H + +#include "WiFiClient.h" + +class WiFiSSLClient : public WiFiClient { + +public: + WiFiSSLClient(); + WiFiSSLClient(uint8_t sock, uint8_t parentsock = 0); + WiFiSSLClient(const WiFiSSLClient& other); + + virtual int connect(IPAddress ip, uint16_t port); + virtual int connect(const char* host, uint16_t port); +}; + +#endif /* WIFISSLCLIENT_H */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiServer.cpp b/feather_sensor_transmit/libraries/WiFi101/src/WiFiServer.cpp new file mode 100644 index 0000000..5f330ba --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/WiFiServer.cpp @@ -0,0 +1,140 @@ +/* + WiFiClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +extern "C" { + #include "socket/include/socket.h" +} + +#include "WiFi101.h" +#include "WiFiClient.h" +#include "WiFiServer.h" + +#define READY (_flag & SOCKET_BUFFER_FLAG_BIND) + +WiFiServer::WiFiServer(uint16_t port) +{ + _port = port; + _flag = 0; +} + +void WiFiServer::begin() +{ + begin(0); +} + +uint8_t WiFiServer::beginSSL() +{ + return begin(SOCKET_FLAGS_SSL); +} + +uint8_t WiFiServer::begin(uint8_t opt) +{ + struct sockaddr_in addr; + + _flag = 0; + + // Initialize socket address structure. + addr.sin_family = AF_INET; + addr.sin_port = _htons(_port); + addr.sin_addr.s_addr = 0; + + // Open TCP server socket. + if ((_socket = socket(AF_INET, SOCK_STREAM, opt)) < 0) { + return 0; + } + + // Add socket buffer handler: + socketBufferRegister(_socket, &_flag, 0, 0, 0); + + // Bind socket: + if (bind(_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { + close(_socket); + _socket = -1; + return 0; + } + + // Wait for connection or timeout: + unsigned long start = millis(); + while (!READY && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + if (!READY) { + close(_socket); + _socket = -1; + return 0; + } + _flag &= ~SOCKET_BUFFER_FLAG_BIND; + + return 1; +} + +WiFiClient WiFiServer::available(uint8_t* status) +{ + uint32_t flag; + + m2m_wifi_handle_events(NULL); + if (_flag & SOCKET_BUFFER_FLAG_SPAWN) { + flag = _flag; + _flag &= ~SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK; + _flag &= ~SOCKET_BUFFER_FLAG_SPAWN; + if (status != NULL) { + *status = 0; + } + return WiFiClient(((flag & SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK) >> SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS), _socket + 1); + } else { + WiFiClient *client; + + for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { + client = WiFi._client[sock]; + if (client && client->_flag & SOCKET_BUFFER_FLAG_CONNECTED) { + if (((client->_flag >> SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS) & 0xff) == (uint8)(_socket + 1)) { + return *client; + } + } + } + } + + return WiFiClient(); +} + +uint8_t WiFiServer::status() { + // Deprecated. + return 0; +} + +size_t WiFiServer::write(uint8_t b) +{ + return write(&b, 1); +} + +size_t WiFiServer::write(const uint8_t *buffer, size_t size) +{ + size_t n = 0; + WiFiClient *client; + + for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { + client = WiFi._client[sock]; + if (client && client->_flag & SOCKET_BUFFER_FLAG_CONNECTED) { + if (((client->_flag >> SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS) & 0xff) == (uint8)(_socket + 1)) { + n += client->write(buffer, size); + } + } + } + return n; +} diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiServer.h b/feather_sensor_transmit/libraries/WiFi101/src/WiFiServer.h new file mode 100644 index 0000000..d658b2f --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/WiFiServer.h @@ -0,0 +1,49 @@ +/* + WiFiClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef WIFISERVER_H +#define WIFISERVER_H + +#include +#include + +class WiFiClient; + +class WiFiServer : public Server { + +private: + SOCKET _socket; + uint32_t _flag; + uint16_t _port; + uint8_t begin(uint8_t opt); + +public: + WiFiServer(uint16_t); + WiFiClient available(uint8_t* status = NULL); + void begin(); + uint8_t beginSSL(); + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + uint8_t status(); + + using Print::write; + +}; + +#endif /* WIFISERVER_H */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiUdp.cpp b/feather_sensor_transmit/libraries/WiFi101/src/WiFiUdp.cpp new file mode 100644 index 0000000..e55c965 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/WiFiUdp.cpp @@ -0,0 +1,289 @@ +/* + WiFiUdp.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +extern "C" { + #include "socket/include/socket.h" + #include "driver/include/m2m_periph.h" + extern uint8 hif_small_xfer; +} + +#include +#include "WiFi101.h" +#include "WiFiUdp.h" +#include "WiFiClient.h" +#include "WiFiServer.h" + +#define READY (_flag & SOCKET_BUFFER_FLAG_BIND) + +/* Constructor. */ +WiFiUDP::WiFiUDP() +{ + _socket = -1; + _flag = 0; + _head = 0; + _tail = 0; + _rcvSize = 0; + _rcvPort = 0; + _rcvIP = 0; + _sndSize = 0; +} + +/* Start WiFiUDP socket, listening at local port PORT */ +uint8_t WiFiUDP::begin(uint16_t port) +{ + struct sockaddr_in addr; + uint32 u32EnableCallbacks = 0; + + _flag = 0; + _head = 0; + _tail = 0; + _rcvSize = 0; + _rcvPort = 0; + _rcvIP = 0; + _sndSize = 0; + + // Initialize socket address structure. + addr.sin_family = AF_INET; + addr.sin_port = _htons(port); + addr.sin_addr.s_addr = 0; + + // Open TCP server socket. + if ((_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { + return 0; + } + + // Add socket buffer handler: + socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_recvBuffer); + setsockopt(_socket, SOL_SOCKET, SO_SET_UDP_SEND_CALLBACK, &u32EnableCallbacks, 0); + + // Bind socket: + if (bind(_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { + close(_socket); + _socket = -1; + return 0; + } + + // Wait for connection or timeout: + unsigned long start = millis(); + while (!READY && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + if (!READY) { + close(_socket); + _socket = -1; + return 0; + } + _flag &= ~SOCKET_BUFFER_FLAG_BIND; + + return 1; +} + +uint8_t WiFiUDP::beginMulticast(IPAddress ip, uint16_t port) +{ + uint32_t multiIp = ip; + + if (!begin(port)) { + return 0; + } + + setsockopt(_socket, SOL_SOCKET, IP_ADD_MEMBERSHIP, &multiIp, sizeof(multiIp)); + + return 1; +} + +/* return number of bytes available in the current packet, + will return zero if parsePacket hasn't been called yet */ +int WiFiUDP::available() +{ + m2m_wifi_handle_events(NULL); + + if (_socket != -1) { + return _rcvSize; + } + return 0; + } + +/* Release any resources being used by this WiFiUDP instance */ +void WiFiUDP::stop() +{ + if (_socket < 0) + return; + + socketBufferUnregister(_socket); + close(_socket); + _socket = -1; +} + +int WiFiUDP::beginPacket(const char *host, uint16_t port) +{ + IPAddress ip; + if (WiFi.hostByName(host, ip)) { + return beginPacket(ip, port); + } + + return 0; +} + +int WiFiUDP::beginPacket(IPAddress ip, uint16_t port) +{ + _sndIP = ip; + _sndPort = port; + _sndSize = 0; + + return 1; +} + +int WiFiUDP::endPacket() +{ + struct sockaddr_in addr; + + // Network led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); + + addr.sin_family = AF_INET; + addr.sin_port = _htons(_sndPort); + addr.sin_addr.s_addr = _sndIP; + + if (sendto(_socket, (void *)_sndBuffer, _sndSize, 0, + (struct sockaddr *)&addr, sizeof(addr)) < 0) { + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + return 0; + } + + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + + return 1; +} + +size_t WiFiUDP::write(uint8_t byte) +{ + return write(&byte, 1); +} + +size_t WiFiUDP::write(const uint8_t *buffer, size_t size) +{ + if ((size + _sndSize) > sizeof(_sndBuffer)) { + size = sizeof(_sndBuffer) - _sndSize; + } + + memcpy(_sndBuffer + _sndSize, buffer, size); + + _sndSize += size; + + return size; +} + +int WiFiUDP::parsePacket() +{ + m2m_wifi_handle_events(NULL); + + if (_socket != -1) { + if (_rcvSize != 0) { + return _rcvSize; + } + if (_head != _tail) { + _rcvSize = ((uint16_t)_recvBuffer[_tail] << 8) + (uint16_t)_recvBuffer[_tail + 1]; + _rcvPort = ((uint16_t)_recvBuffer[_tail + 2] << 8) + (uint16_t)_recvBuffer[_tail + 3]; + _rcvIP = ((uint32_t)_recvBuffer[_tail + 4] << 24) + ((uint32_t)_recvBuffer[_tail + 5] << 16) + + ((uint32_t)_recvBuffer[_tail + 6] << 8) + (uint32_t)_recvBuffer[_tail + 7]; + _tail += SOCKET_BUFFER_UDP_HEADER_SIZE; + return _rcvSize; + } + } + return 0; +} + +int WiFiUDP::read() +{ + uint8_t b; + + if (read(&b, sizeof(b)) == -1) { + return -1; + } + + return b; +} + +int WiFiUDP::read(unsigned char* buf, size_t size) +{ + // sizeof(size_t) is architecture dependent + // but we need a 16 bit data type here + uint16_t size_tmp = available(); + + if (size_tmp == 0) { + return -1; + } + + if (size < size_tmp) { + size_tmp = size; + } + + for (uint32_t i = 0; i < size_tmp; ++i) { + buf[i] = _recvBuffer[_tail++]; + _rcvSize--; + + if (_tail == _head) { + // the full buffered data has been read, reset head and tail for next transfer + _tail = _head = 0; + + // clear the buffer full flag + _flag &= ~SOCKET_BUFFER_FLAG_FULL; + + // setup buffer and buffer size to transfer the remainder of the current packet + // or next received packet + if (hif_small_xfer) { + recvfrom(_socket, _recvBuffer, SOCKET_BUFFER_MTU, 0); + } else { + recvfrom(_socket, _recvBuffer + SOCKET_BUFFER_UDP_HEADER_SIZE, SOCKET_BUFFER_MTU, 0); + } + m2m_wifi_handle_events(NULL); + } + } + + return size_tmp; +} + +int WiFiUDP::peek() +{ + if (!available()) + return -1; + + return _recvBuffer[_tail]; +} + +void WiFiUDP::flush() +{ + while (available()) + read(); +} + +IPAddress WiFiUDP::remoteIP() +{ + return _rcvIP; +} + +uint16_t WiFiUDP::remotePort() +{ + return _rcvPort; +} diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiUdp.h b/feather_sensor_transmit/libraries/WiFi101/src/WiFiUdp.h new file mode 100644 index 0000000..d961682 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/WiFiUdp.h @@ -0,0 +1,89 @@ +/* + WiFiUdp.h - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef WIFIUDP_H +#define WIFIUDP_H + +#include + +class WiFiUDP : public UDP { +private: + SOCKET _socket; + uint32_t _flag; + uint32_t _head; + uint32_t _tail; + uint8_t _recvBuffer[SOCKET_BUFFER_UDP_SIZE]; + uint16_t _rcvSize; + uint16_t _rcvPort; + uint32_t _rcvIP; + uint8_t _sndBuffer[SOCKET_BUFFER_UDP_SIZE]; + uint16_t _sndSize; + uint16_t _sndPort; + uint32_t _sndIP; + +public: + WiFiUDP(); // Constructor + virtual uint8_t begin(uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use + virtual uint8_t beginMulticast(IPAddress, uint16_t); // initialize, start listening on specified multicast IP address and port. Returns 1 if successful, 0 if there are no sockets available to use + virtual uint8_t beginMulti(IPAddress ip, uint16_t port) { return beginMulticast(ip, port); } + virtual void stop(); // Finish with the UDP socket + + // Sending UDP packets + + // Start building up a packet to send to the remote host specific in ip and port + // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port + virtual int beginPacket(IPAddress ip, uint16_t port); + // Start building up a packet to send to the remote host specific in host and port + // Returns 1 if successful, 0 if there was a problem resolving the hostname or port + virtual int beginPacket(const char *host, uint16_t port); + // Finish off this packet and send it + // Returns 1 if the packet was sent successfully, 0 if there was an error + virtual int endPacket(); + // Write a single byte into the packet + virtual size_t write(uint8_t); + // Write size bytes from buffer into the packet + virtual size_t write(const uint8_t *buffer, size_t size); + + using Print::write; + + // Start processing the next available incoming packet + // Returns the size of the packet in bytes, or 0 if no packets are available + virtual int parsePacket(); + // Number of bytes remaining in the current packet + virtual int available(); + // Read a single byte from the current packet + virtual int read(); + // Read up to len bytes from the current packet and place them into buffer + // Returns the number of bytes read, or 0 if none are available + virtual int read(unsigned char* buffer, size_t len); + // Read up to len characters from the current packet and place them into buffer + // Returns the number of characters read, or 0 if none are available + virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; + // Return the next byte from the current packet without moving on to the next byte + virtual int peek(); + virtual void flush(); // Finish reading the current packet + + // Return the IP address of the host who sent the current incoming packet + virtual IPAddress remoteIP(); + // Return the port of the host who sent the current incoming packet + virtual uint16_t remotePort(); + +}; + +#endif /* WIFIUDP_H */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp.h b/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp.h new file mode 100644 index 0000000..5527bab --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp.h @@ -0,0 +1,283 @@ +/** + * + * \file + * + * \brief WINC BSP API Declarations. + * + * Copyright (c) 2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/** \defgroup nm_bsp BSP + */ +/**@defgroup BSPDefine Defines + * @ingroup nm_bsp + * @{ + */ +#ifndef _NM_BSP_H_ +#define _NM_BSP_H_ + +#define NMI_API +/*!< +* Attribute used to define memory section to map Functions in host memory. +*/ +#define CONST const + +/*!< +* Used for code portability. +*/ + +/*! + * @typedef void (*tpfNmBspIsr) (void); + * @brief Pointer to function.\n + * Used as a data type of ISR function registered by \ref nm_bsp_register_isr + * @return None + */ +typedef void (*tpfNmBspIsr)(void); + + + +#ifndef NULL +#define NULL ((void*)0) +#endif +/*!< +* Void Pointer to '0' in case of NULL is not defined. +*/ + + +#define BSP_MIN(x,y) ((x)>(y)?(y):(x)) +/*!< +* Computes the minimum of \b x and \b y. +*/ + + //@} + +/**@defgroup DataT DataTypes + * @ingroup nm_bsp + * @{ + */ + + /*! + * @ingroup DataTypes + * @typedef unsigned char uint8; + * @brief Range of values between 0 to 255 + */ +typedef unsigned char uint8; + + /*! + * @ingroup DataTypes + * @typedef unsigned short uint16; + * @brief Range of values between 0 to 65535 + */ +typedef unsigned short uint16; + + /*! + * @ingroup Data Types + * @typedef unsigned long uint32; + * @brief Range of values between 0 to 4294967295 + */ +typedef unsigned long uint32; + + + /*! + * @ingroup Data Types + * @typedef signed char sint8; + * @brief Range of values between -128 to 127 + */ +typedef signed char sint8; + + /*! + * @ingroup DataTypes + * @typedef signed short sint16; + * @brief Range of values between -32768 to 32767 + */ +typedef signed short sint16; + + /*! + * @ingroup DataTypes + * @typedef signed long sint32; + * @brief Range of values between -2147483648 to 2147483647 + */ + +typedef signed long sint32; + //@} + +#ifndef CORTUS_APP + + +#ifdef __cplusplus +extern "C"{ +#endif + +/** \defgroup BSPAPI Function + * @ingroup nm_bsp + */ + + +/** @defgroup NmBspInitFn nm_bsp_init + * @ingroup BSPAPI + * Initialization for BSP such as Reset and Chip Enable Pins for WINC, delays, register ISR, enable/disable IRQ for WINC, ...etc. You must use this function in the head of your application to + * enable WINC and Host Driver communicate each other. + */ + /**@{*/ +/*! + * @fn sint8 nm_bsp_init(void); + * @note Implementation of this function is host dependent. + * @warning Missing use will lead to unavailability of host communication.\n + * + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + + */ +sint8 nm_bsp_init(void); + /**@}*/ + + + /** @defgroup NmBspDeinitFn nm_bsp_deinit + * @ingroup BSPAPI + * De-initialization for BSP (\e Board \e Support \e Package) + */ + /**@{*/ +/*! + * @fn sint8 nm_bsp_deinit(void); + * @pre Initialize \ref nm_bsp_init first + * @note Implementation of this function is host dependent. + * @warning Missing use may lead to unknown behavior in case of soft reset.\n + * @see nm_bsp_init + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + + */ +sint8 nm_bsp_deinit(void); + /**@}*/ + + +/** @defgroup NmBspResetFn nm_bsp_reset +* @ingroup BSPAPI +* Resetting NMC1500 SoC by setting CHIP_EN and RESET_N signals low, then after specific delay the function will put CHIP_EN high then RESET_N high, +* for the timing between signals please review the WINC data-sheet +*/ +/**@{*/ + /*! + * @fn void nm_bsp_reset(void); + * @param [in] None + * @pre Initialize \ref nm_bsp_init first + * @note Implementation of this function is host dependent and called by HIF layer. + * @see nm_bsp_init + * @return None + + */ +void nm_bsp_reset(void); + /**@}*/ + + +/** @defgroup NmBspSleepFn nm_bsp_sleep +* @ingroup BSPAPI +* Sleep in units of milliseconds.\n +* This function used by HIF Layer according to different situations. +*/ +/**@{*/ +/*! + * @fn void nm_bsp_sleep(uint32); + * @brief + * @param [in] u32TimeMsec + * Time unit in milliseconds + * @pre Initialize \ref nm_bsp_init first + * @warning Maximum value must nor exceed 4294967295 milliseconds which is equal to 4294967.295 seconds.\n + * @note Implementation of this function is host dependent. + * @see nm_bsp_init + * @return None + */ +void nm_bsp_sleep(uint32 u32TimeMsec); +/**@}*/ + + +/** @defgroup NmBspRegisterFn nm_bsp_register_isr +* @ingroup BSPAPI +* Register ISR (Interrupt Service Routine) in the initialization of HIF (Host Interface) Layer. +* When the interrupt trigger the BSP layer should call the pfisr function once inside the interrupt. +*/ +/**@{*/ +/*! + * @fn void nm_bsp_register_isr(tpfNmBspIsr); + * @param [in] tpfNmBspIsr pfIsr + * Pointer to ISR handler in HIF + * @warning Make sure that ISR for IRQ pin for WINC is disabled by default in your implementation. + * @note Implementation of this function is host dependent and called by HIF layer. + * @see tpfNmBspIsr + * @return None + + */ +void nm_bsp_register_isr(tpfNmBspIsr pfIsr); +/**@}*/ + + +/** @defgroup NmBspInterruptCtrl nm_bsp_interrupt_ctrl +* @ingroup BSPAPI +* Synchronous enable/disable interrupts function +*/ +/**@{*/ +/*! + * @fn void nm_bsp_interrupt_ctrl(uint8); + * @brief Enable/Disable interrupts + * @param [in] u8Enable + * '0' disable interrupts. '1' enable interrupts + * @see tpfNmBspIsr + * @note Implementation of this function is host dependent and called by HIF layer. + * @return None + + */ +void nm_bsp_interrupt_ctrl(uint8 u8Enable); + /**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif + +#ifdef _NM_BSP_BIG_END +#define NM_BSP_B_L_32(x) \ +((((x) & 0x000000FF) << 24) + \ +(((x) & 0x0000FF00) << 8) + \ +(((x) & 0x00FF0000) >> 8) + \ +(((x) & 0xFF000000) >> 24)) +#define NM_BSP_B_L_16(x) \ +((((x) & 0x00FF) << 8) + \ +(((x) & 0xFF00) >> 8)) +#else +#define NM_BSP_B_L_32(x) (x) +#define NM_BSP_B_L_16(x) (x) +#endif + + +#endif /*_NM_BSP_H_*/ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h b/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h new file mode 100644 index 0000000..77417e8 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h @@ -0,0 +1,74 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 BSP APIs definitions. + * + * Copyright (c) 2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NM_BSP_ARDUINO_H_ +#define _NM_BSP_ARDUINO_H_ + +#include + +#include + +/* + * Arduino variants may redefine those pins. + * If no pins are specified the following defaults are used: + * WINC1501_RESET_PIN - pin 5 + * WINC1501_INTN_PIN - pin 7 + * WINC1501_CHIP_EN_PIN - not connected (tied to VCC) + */ +#if !defined(WINC1501_RESET_PIN) + #define WINC1501_RESET_PIN 5 +#endif +#if !defined(WINC1501_INTN_PIN) + #define WINC1501_INTN_PIN 7 +#endif +#if !defined(WINC1501_SPI_CS_PIN) + #define WINC1501_SPI_CS_PIN 10 +#endif +#if !defined(WINC1501_CHIP_EN_PIN) + #define WINC1501_CHIP_EN_PIN -1 +#endif + +extern int8_t gi8Winc1501CsPin; +extern int8_t gi8Winc1501ResetPin; +extern int8_t gi8Winc1501IntnPin; +extern int8_t gi8Winc1501ChipEnPin; + +#endif /* _NM_BSP_ARDUINO_H_ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h b/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h new file mode 100644 index 0000000..c5991f2 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h @@ -0,0 +1,54 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 BSP APIs definitions. + * + * Copyright (c) 2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NM_BSP_AVR_H_ +#define _NM_BSP_AVR_H_ + +#pragma once + +#define NM_DEBUG 0 +#define NM_BSP_PRINTF + +#define CONF_WINC_USE_SPI 1 + +#define NM_EDGE_INTERRUPT 1 + +#endif /* _NM_BSP_AVR_H_ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h b/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h new file mode 100644 index 0000000..45d3ff2 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h @@ -0,0 +1,59 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 BSP APIs declarations. + * + * Copyright (c) 2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/**@defgroup BSPDefine Defines + * @ingroup nm_bsp + * @{ + */ +#ifndef _NM_BSP_INTERNAL_H_ +#define _NM_BSP_INTERNAL_H_ + +#ifdef ARDUINO_ARCH_AVR +#define LIMITED_RAM_DEVICE +#include "bsp/include/nm_bsp_avr.h" +#else +#include "bsp/include/nm_bsp_samd21.h" +#endif + +#ifdef ARDUINO +#define CONF_PERIPH +#endif + +#endif //_NM_BSP_INTERNAL_H_ \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h b/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h new file mode 100644 index 0000000..296cd20 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h @@ -0,0 +1,52 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 BSP APIs definitions. + * + * Copyright (c) 2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NM_BSP_SAMD21_H_ +#define _NM_BSP_SAMD21_H_ + +#define NM_DEBUG 0 +#define NM_BSP_PRINTF + +#define CONF_WINC_USE_SPI 1 + +#define NM_EDGE_INTERRUPT 1 + +#endif /* _NM_BSP_SAMD21_H_ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c b/feather_sensor_transmit/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c new file mode 100644 index 0000000..e27be14 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c @@ -0,0 +1,205 @@ +/** + * + * \file + * + * \brief This module contains SAMD21 BSP APIs implementation. + * + * Copyright (c) 2014 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "bsp/include/nm_bsp.h" +#include "bsp/include/nm_bsp_arduino.h" +#include "common/include/nm_common.h" + +int8_t gi8Winc1501CsPin = WINC1501_SPI_CS_PIN; +int8_t gi8Winc1501ResetPin = WINC1501_RESET_PIN; +int8_t gi8Winc1501IntnPin = WINC1501_INTN_PIN; +int8_t gi8Winc1501ChipEnPin = WINC1501_CHIP_EN_PIN; + +static tpfNmBspIsr gpfIsr; + +void __attribute__((weak)) attachInterruptMultiArch(uint32_t pin, void *chip_isr, uint32_t mode) +{ + attachInterrupt(pin, chip_isr, mode); +} + +void __attribute__((weak)) detachInterruptMultiArch(uint32_t pin) +{ + detachInterrupt(pin); +} + +static void chip_isr(void) +{ + if (gpfIsr) { + gpfIsr(); + } +} + +/* + * @fn init_chip_pins + * @brief Initialize reset, chip enable and wake pin + * @author M.S.M + * @date 11 July 2012 + * @version 1.0 + */ +static void init_chip_pins(void) +{ + /* Configure RESETN pin as output. */ + pinMode(gi8Winc1501ResetPin, OUTPUT); + digitalWrite(gi8Winc1501ResetPin, HIGH); + + /* Configure INTN pins as input. */ + pinMode(gi8Winc1501IntnPin, INPUT); + + if (gi8Winc1501ChipEnPin > -1) + { + /* Configure CHIP_EN as pull-up */ + pinMode(gi8Winc1501ChipEnPin, INPUT_PULLUP); + } +} + +static void deinit_chip_pins(void) +{ + digitalWrite(gi8Winc1501ResetPin, LOW); + pinMode(gi8Winc1501ResetPin, INPUT); + + if (gi8Winc1501ChipEnPin > -1) + { + pinMode(gi8Winc1501ChipEnPin, INPUT); + } +} + +/* + * @fn nm_bsp_init + * @brief Initialize BSP + * @return 0 in case of success and -1 in case of failure + * @author M.S.M + * @date 11 July 2012 + * @version 1.0 + */ +sint8 nm_bsp_init(void) +{ + gpfIsr = NULL; + + init_chip_pins(); + + nm_bsp_reset(); + + return M2M_SUCCESS; +} + +/** + * @fn nm_bsp_deinit + * @brief De-iInitialize BSP + * @return 0 in case of success and -1 in case of failure + * @author M. Abdelmawla + * @date 11 July 2012 + * @version 1.0 + */ +sint8 nm_bsp_deinit(void) +{ + deinit_chip_pins(); + + return M2M_SUCCESS; +} + +/** + * @fn nm_bsp_reset + * @brief Reset NMC1500 SoC by setting CHIP_EN and RESET_N signals low, + * CHIP_EN high then RESET_N high + * @author M. Abdelmawla + * @date 11 July 2012 + * @version 1.0 + */ +void nm_bsp_reset(void) +{ + digitalWrite(gi8Winc1501ResetPin, LOW); + nm_bsp_sleep(100); + digitalWrite(gi8Winc1501ResetPin, HIGH); + nm_bsp_sleep(100); +} + +/* + * @fn nm_bsp_sleep + * @brief Sleep in units of mSec + * @param[IN] u32TimeMsec + * Time in milliseconds + * @author M.S.M + * @date 28 OCT 2013 + * @version 1.0 + */ +void nm_bsp_sleep(uint32 u32TimeMsec) +{ + while (u32TimeMsec--) { + delay(1); + } +} + +/* + * @fn nm_bsp_register_isr + * @brief Register interrupt service routine + * @param[IN] pfIsr + * Pointer to ISR handler + * @author M.S.M + * @date 28 OCT 2013 + * @sa tpfNmBspIsr + * @version 1.0 + */ +void nm_bsp_register_isr(tpfNmBspIsr pfIsr) +{ + gpfIsr = pfIsr; + attachInterruptMultiArch(gi8Winc1501IntnPin, chip_isr, FALLING); +} + +/* + * @fn nm_bsp_interrupt_ctrl + * @brief Enable/Disable interrupts + * @param[IN] u8Enable + * '0' disable interrupts. '1' enable interrupts + * @author M.S.M + * @date 28 OCT 2013 + * @version 1.0 + */ +void nm_bsp_interrupt_ctrl(uint8 u8Enable) +{ + if (u8Enable) { + attachInterruptMultiArch(gi8Winc1501IntnPin, chip_isr, FALLING); + } else { + detachInterruptMultiArch(gi8Winc1501IntnPin); + } +} diff --git a/feather_sensor_transmit/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c b/feather_sensor_transmit/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c new file mode 100644 index 0000000..050d5d5 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c @@ -0,0 +1,164 @@ +/** + * + * \file + * + * \brief This module contains SAMD21 BSP APIs implementation. + * + * Copyright (c) 2014 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifdef ARDUINO_ARCH_AVR + +#include "bsp/include/nm_bsp.h" +#include "bsp/include/nm_bsp_arduino.h" +#include "common/include/nm_common.h" + +#define IS_MEGA (defined(ARDUINO_AVR_MEGA) || defined(ARDUINO_AVR_MEGA2560)) + +static tpfNmBspIsr gpfIsr; + +volatile uint8_t *_receivePortRegister; +volatile uint8_t *_pcint_maskreg; +uint8_t _receiveBitMask; +volatile uint8_t prev_pin_read = 1; + +uint8_t rx_pin_read() +{ + return *_receivePortRegister & _receiveBitMask; +} + +#if !IS_MEGA + +#if defined(PCINT0_vect) +ISR(PCINT0_vect) +{ + if (!rx_pin_read() && gpfIsr) + { + gpfIsr(); + } +} +#endif + +#if defined(PCINT1_vect) +ISR(PCINT1_vect, ISR_ALIASOF(PCINT0_vect)); +#endif + +#if defined(PCINT2_vect) +ISR(PCINT2_vect, ISR_ALIASOF(PCINT0_vect)); +#endif + +#if defined(PCINT3_vect) +ISR(PCINT3_vect, ISR_ALIASOF(PCINT0_vect)); +#endif + +#endif // !IS_MEGA + +#if defined(TIMER4_OVF_vect) +ISR(TIMER4_OVF_vect) { + uint8_t curr_pin_read = rx_pin_read(); + if ((curr_pin_read != prev_pin_read) && !curr_pin_read && gpfIsr) + { + gpfIsr(); + } + prev_pin_read = curr_pin_read; +} + +// stategy 3 - start a timer and perform a sort of polling +void attachFakeInterruptToTimer(void) { + TCCR4B = (1< I2C/UART. Parameter:tstrNmI2cDefault/tstrNmUartDefault */ +#define NM_BUS_IOCTL_W ((uint8)1) /*!< Write only ==> I2C/UART. Parameter type tstrNmI2cDefault/tstrNmUartDefault*/ +#define NM_BUS_IOCTL_W_SPECIAL ((uint8)2) /*!< Write two buffers within the same transaction + (same start/stop conditions) ==> I2C only. Parameter:tstrNmI2cSpecial */ +#define NM_BUS_IOCTL_RW ((uint8)3) /*!< Read/Write at the same time ==> SPI only. Parameter:tstrNmSpiRw */ + +#define NM_BUS_IOCTL_WR_RESTART ((uint8)4) /*!< Write buffer then made restart condition then read ==> I2C only. parameter:tstrNmI2cSpecial */ +/** +* @struct tstrNmBusCapabilities +* @brief Structure holding bus capabilities information +* @sa NM_BUS_TYPE_I2C, NM_BUS_TYPE_SPI +*/ +typedef struct +{ + uint16 u16MaxTrxSz; /*!< Maximum transfer size. Must be >= 16 bytes*/ +} tstrNmBusCapabilities; + +/** +* @struct tstrNmI2cDefault +* @brief Structure holding I2C default operation parameters +* @sa NM_BUS_IOCTL_R, NM_BUS_IOCTL_W +*/ +typedef struct +{ + uint8 u8SlaveAdr; + uint8 *pu8Buf; /*!< Operation buffer */ + uint16 u16Sz; /*!< Operation size */ +} tstrNmI2cDefault; + +/** +* @struct tstrNmI2cSpecial +* @brief Structure holding I2C special operation parameters +* @sa NM_BUS_IOCTL_W_SPECIAL +*/ +typedef struct +{ + uint8 u8SlaveAdr; + uint8 *pu8Buf1; /*!< pointer to the 1st buffer */ + uint8 *pu8Buf2; /*!< pointer to the 2nd buffer */ + uint16 u16Sz1; /*!< 1st buffer size */ + uint16 u16Sz2; /*!< 2nd buffer size */ +} tstrNmI2cSpecial; + +/** +* @struct tstrNmSpiRw +* @brief Structure holding SPI R/W parameters +* @sa NM_BUS_IOCTL_RW +*/ +typedef struct +{ + uint8 *pu8InBuf; /*!< pointer to input buffer. + Can be set to null and in this case zeros should be sent at MOSI */ + uint8 *pu8OutBuf; /*!< pointer to output buffer. + Can be set to null and in this case data from MISO can be ignored */ + uint16 u16Sz; /*!< Transfere size */ +} tstrNmSpiRw; + + +/** +* @struct tstrNmUartDefault +* @brief Structure holding UART default operation parameters +* @sa NM_BUS_IOCTL_R, NM_BUS_IOCTL_W +*/ +typedef struct +{ + uint8 *pu8Buf; /*!< Operation buffer */ + uint16 u16Sz; /*!< Operation size */ +} tstrNmUartDefault; +/*!< Bus capabilities. This structure must be declared at platform specific bus wrapper */ +extern tstrNmBusCapabilities egstrNmBusCapabilities; + + +#ifdef __cplusplus + extern "C" { + #endif +/** +* @fn nm_bus_init +* @brief Initialize the bus wrapper +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_bus_init(void *); + +/** +* @fn nm_bus_ioctl +* @brief send/receive from the bus +* @param [in] u8Cmd +* IOCTL command for the operation +* @param [in] pvParameter +* Arbitrary parameter depending on IOCTL +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +* @note For SPI only, it's important to be able to send/receive at the same time +*/ +sint8 nm_bus_ioctl(uint8 u8Cmd, void* pvParameter); + +/** +* @fn nm_bus_deinit +* @brief De-initialize the bus wrapper +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_bus_deinit(void); + +/* +* @fn nm_bus_reinit +* @brief re-initialize the bus wrapper +* @param [in] void *config +* re-init configuration data +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_bus_reinit(void *); +/* +* @fn nm_bus_get_chip_type +* @brief get chip type +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +#ifdef CONF_WINC_USE_UART +uint8 nm_bus_get_chip_type(void); +#endif +#ifdef __cplusplus + } + #endif + +#endif /*_NM_BUS_WRAPPER_H_*/ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp b/feather_sensor_transmit/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp new file mode 100644 index 0000000..22a7473 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp @@ -0,0 +1,200 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 bus wrapper APIs implementation. + * + * Copyright (c) 2014 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include +#include + +/* + * Variants may define an alternative SPI instace to use for WiFi101. + * If not defined the following defaults are used: + * WINC1501_SPI - SPI + */ +#if !defined(WINC1501_SPI) + #define WINC1501_SPI SPI +#endif + +extern "C" { + +#include "bsp/include/nm_bsp.h" +#include "bsp/include/nm_bsp_arduino.h" +#include "common/include/nm_common.h" +#include "bus_wrapper/include/nm_bus_wrapper.h" + +} + +#define NM_BUS_MAX_TRX_SZ 256 + +tstrNmBusCapabilities egstrNmBusCapabilities = +{ + NM_BUS_MAX_TRX_SZ +}; + +static const SPISettings wifi_SPISettings(12000000L, MSBFIRST, SPI_MODE0); + +static sint8 spi_rw(uint8* pu8Mosi, uint8* pu8Miso, uint16 u16Sz) +{ + uint8 u8Dummy = 0; + uint8 u8SkipMosi = 0, u8SkipMiso = 0; + + if (!pu8Mosi) { + pu8Mosi = &u8Dummy; + u8SkipMosi = 1; + } + else if(!pu8Miso) { + pu8Miso = &u8Dummy; + u8SkipMiso = 1; + } + else { + return M2M_ERR_BUS_FAIL; + } + + WINC1501_SPI.beginTransaction(wifi_SPISettings); + digitalWrite(gi8Winc1501CsPin, LOW); + + while (u16Sz) { + *pu8Miso = WINC1501_SPI.transfer(*pu8Mosi); + + u16Sz--; + if (!u8SkipMiso) + pu8Miso++; + if (!u8SkipMosi) + pu8Mosi++; + } + + digitalWrite(gi8Winc1501CsPin, HIGH); + WINC1501_SPI.endTransaction(); + + return M2M_SUCCESS; +} + +extern "C" { + +/* +* @fn nm_bus_init +* @brief Initialize the bus wrapper +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M.S.M +* @date 28 oct 2013 +* @version 1.0 +*/ +sint8 nm_bus_init(void * /* pvInitValue */) +{ + sint8 result = M2M_SUCCESS; + + /* Configure SPI peripheral. */ + WINC1501_SPI.begin(); + + /* Configure CS PIN. */ + pinMode(gi8Winc1501CsPin, OUTPUT); + digitalWrite(gi8Winc1501CsPin, HIGH); + + /* Reset WINC1500. */ + nm_bsp_reset(); + nm_bsp_sleep(1); + + return result; +} + +/* +* @fn nm_bus_ioctl +* @brief send/receive from the bus +* @param[IN] u8Cmd +* IOCTL command for the operation +* @param[IN] pvParameter +* Arbitrary parameter depenging on IOCTL +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M.S.M +* @date 28 oct 2013 +* @note For SPI only, it's important to be able to send/receive at the same time +* @version 1.0 +*/ +sint8 nm_bus_ioctl(uint8 u8Cmd, void* pvParameter) +{ + sint8 s8Ret = 0; + switch(u8Cmd) + { + case NM_BUS_IOCTL_RW: { + tstrNmSpiRw *pstrParam = (tstrNmSpiRw *)pvParameter; + s8Ret = spi_rw(pstrParam->pu8InBuf, pstrParam->pu8OutBuf, pstrParam->u16Sz); + } + break; + default: + s8Ret = -1; + M2M_ERR("invalide ioclt cmd\n"); + break; + } + + return s8Ret; +} + +/* +* @fn nm_bus_deinit +* @brief De-initialize the bus wrapper +* @author M.S.M +* @date 28 oct 2013 +* @version 1.0 +*/ +sint8 nm_bus_deinit(void) +{ + WINC1501_SPI.end(); + return 0; +} + +/* +* @fn nm_bus_reinit +* @brief re-initialize the bus wrapper +* @param [in] void *config +* re-init configuration data +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Dina El Sissy +* @date 19 Sept 2012 +* @version 1.0 +*/ +sint8 nm_bus_reinit(void* /* config */) +{ + return M2M_SUCCESS; +} + +} // extern "C" + diff --git a/feather_sensor_transmit/libraries/WiFi101/src/common/include/nm_common.h b/feather_sensor_transmit/libraries/WiFi101/src/common/include/nm_common.h new file mode 100644 index 0000000..d66fbdb --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/common/include/nm_common.h @@ -0,0 +1,153 @@ +/** + * + * \file + * + * \brief WINC Driver Common API Declarations. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NM_COMMON_H_ +#define _NM_COMMON_H_ + +#include "bsp/include/nm_bsp.h" +#include "common/include/nm_debug.h" + +/**@defgroup CommonDefines CommonDefines + * @ingroup WlanDefines + */ +/**@{*/ +#define M2M_TIME_OUT_DELAY 10000 + +/*states*/ +#define M2M_SUCCESS ((sint8)0) +#define M2M_ERR_SEND ((sint8)-1) +#define M2M_ERR_RCV ((sint8)-2) +#define M2M_ERR_MEM_ALLOC ((sint8)-3) +#define M2M_ERR_TIME_OUT ((sint8)-4) +#define M2M_ERR_INIT ((sint8)-5) +#define M2M_ERR_BUS_FAIL ((sint8)-6) +#define M2M_NOT_YET ((sint8)-7) +#define M2M_ERR_FIRMWARE ((sint8)-8) +#define M2M_SPI_FAIL ((sint8)-9) +#define M2M_ERR_FIRMWARE_bURN ((sint8)-10) +#define M2M_ACK ((sint8)-11) +#define M2M_ERR_FAIL ((sint8)-12) +#define M2M_ERR_FW_VER_MISMATCH ((sint8)-13) +#define M2M_ERR_SCAN_IN_PROGRESS ((sint8)-14) +#define M2M_ERR_INVALID_ARG ((sint8)-15) +#define M2M_ERR_INVALID ((sint8)-16) + +/*i2c MAASTER ERR*/ +#define I2C_ERR_LARGE_ADDRESS 0xE1UL /*the address exceed the max addressing mode in i2c flash*/ +#define I2C_ERR_TX_ABRT 0xE2UL /*NO ACK from slave*/ +#define I2C_ERR_OVER_SIZE 0xE3UL /**/ +#define ERR_PREFIX_NMIS 0xE4UL /*wrong first four byte in flash NMIS*/ +#define ERR_FIRMEWARE_EXCEED_SIZE 0xE5UL /*Total size of firmware exceed the max size 256k*/ +/**/ +#define PROGRAM_START 0x26961735UL +#define BOOT_SUCCESS 0x10add09eUL +#define BOOT_START 0x12345678UL + + +#define NBIT31 (0x80000000) +#define NBIT30 (0x40000000) +#define NBIT29 (0x20000000) +#define NBIT28 (0x10000000) +#define NBIT27 (0x08000000) +#define NBIT26 (0x04000000) +#define NBIT25 (0x02000000) +#define NBIT24 (0x01000000) +#define NBIT23 (0x00800000) +#define NBIT22 (0x00400000) +#define NBIT21 (0x00200000) +#define NBIT20 (0x00100000) +#define NBIT19 (0x00080000) +#define NBIT18 (0x00040000) +#define NBIT17 (0x00020000) +#define NBIT16 (0x00010000) +#define NBIT15 (0x00008000) +#define NBIT14 (0x00004000) +#define NBIT13 (0x00002000) +#define NBIT12 (0x00001000) +#define NBIT11 (0x00000800) +#define NBIT10 (0x00000400) +#define NBIT9 (0x00000200) +#define NBIT8 (0x00000100) +#define NBIT7 (0x00000080) +#define NBIT6 (0x00000040) +#define NBIT5 (0x00000020) +#define NBIT4 (0x00000010) +#define NBIT3 (0x00000008) +#define NBIT2 (0x00000004) +#define NBIT1 (0x00000002) +#define NBIT0 (0x00000001) + +#define M2M_MAX(A,B) ((A) > (B) ? (A) : (B)) +#define M2M_SEL(x,m1,m2,m3) ((x>1)?((x>2)?(m3):(m2)):(m1)) +#define WORD_ALIGN(val) (((val) & 0x03) ? ((val) + 4 - ((val) & 0x03)) : (val)) + + + +#define DATA_PKT_OFFSET 4 + +#ifndef BIG_ENDIAN +#define BYTE_0(word) ((uint8)(((word) >> 0 ) & 0x000000FFUL)) +#define BYTE_1(word) ((uint8)(((word) >> 8 ) & 0x000000FFUL)) +#define BYTE_2(word) ((uint8)(((word) >> 16) & 0x000000FFUL)) +#define BYTE_3(word) ((uint8)(((word) >> 24) & 0x000000FFUL)) +#else +#define BYTE_0(word) ((uint8)(((word) >> 24) & 0x000000FFUL)) +#define BYTE_1(word) ((uint8)(((word) >> 16) & 0x000000FFUL)) +#define BYTE_2(word) ((uint8)(((word) >> 8 ) & 0x000000FFUL)) +#define BYTE_3(word) ((uint8)(((word) >> 0 ) & 0x000000FFUL)) +#endif + +/**@}*/ +#ifdef __cplusplus + extern "C" { + #endif +NMI_API void m2m_memcpy(uint8* pDst,uint8* pSrc,uint32 sz); +NMI_API void m2m_memset(uint8* pBuf,uint8 val,uint32 sz); +NMI_API uint16 m2m_strlen(uint8 * pcStr); +NMI_API sint8 m2m_memcmp(uint8 *pu8Buff1,uint8 *pu8Buff2 ,uint32 u32Size); +NMI_API uint8 m2m_strncmp(uint8 *pcS1, uint8 *pcS2, uint16 u16Len); +NMI_API uint8 * m2m_strstr(uint8 *pcIn, uint8 *pcStr); +NMI_API uint8 m2m_checksum(uint8* buf, int sz); + +#ifdef __cplusplus +} + #endif +#endif /*_NM_COMMON_H_*/ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/common/include/nm_debug.h b/feather_sensor_transmit/libraries/WiFi101/src/common/include/nm_debug.h new file mode 100644 index 0000000..a710f6c --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/common/include/nm_debug.h @@ -0,0 +1,95 @@ +/** + * + * \file + * + * \brief This module contains debug APIs declarations. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NM_DEBUG_H_ +#define _NM_DEBUG_H_ + +#include "bsp/include/nm_bsp.h" +#include "bsp/include/nm_bsp_internal.h" + +/**@defgroup DebugDefines DebugDefines + * @ingroup WlanDefines + */ +/**@{*/ + + +#define M2M_LOG_NONE 0 +#define M2M_LOG_ERROR 1 +#define M2M_LOG_INFO 2 +#define M2M_LOG_REQ 3 +#define M2M_LOG_DBG 4 + +#if (defined __APS3_CORTUS__) +#define M2M_LOG_LEVEL M2M_LOG_INFO +#else +#define M2M_LOG_LEVEL M2M_LOG_REQ +#endif + + +#define M2M_ERR(...) +#define M2M_INFO(...) +#define M2M_REQ(...) +#define M2M_DBG(...) +#define M2M_PRINT(...) + +#if (CONF_WINC_DEBUG == 1) +#undef M2M_PRINT +#define M2M_PRINT(...) do{CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) +#if (M2M_LOG_LEVEL >= M2M_LOG_ERROR) +#undef M2M_ERR +#define M2M_ERR(...) do{CONF_WINC_PRINTF("(APP)(ERR)[%s][%d]",__FUNCTION__,__LINE__); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) +#if (M2M_LOG_LEVEL >= M2M_LOG_INFO) +#undef M2M_INFO +#define M2M_INFO(...) do{CONF_WINC_PRINTF("(APP)(INFO)"); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) +#if (M2M_LOG_LEVEL >= M2M_LOG_REQ) +#undef M2M_REQ +#define M2M_REQ(...) do{CONF_WINC_PRINTF("(APP)(R)"); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) +#if (M2M_LOG_LEVEL >= M2M_LOG_DBG) +#undef M2M_DBG +#define M2M_DBG(...) do{CONF_WINC_PRINTF("(APP)(DBG)[%s][%d]",__FUNCTION__,__LINE__); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) +#endif /*M2M_LOG_DBG*/ +#endif /*M2M_LOG_REQ*/ +#endif /*M2M_LOG_INFO*/ +#endif /*M2M_LOG_ERROR*/ +#endif /*CONF_WINC_DEBUG */ + +/**@}*/ +#endif /* _NM_DEBUG_H_ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/common/source/nm_common.c b/feather_sensor_transmit/libraries/WiFi101/src/common/source/nm_common.c new file mode 100644 index 0000000..8b3c941 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/common/source/nm_common.c @@ -0,0 +1,136 @@ +/** + * + * \file + * + * \brief This module contains common APIs declarations. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +#include "common/include/nm_common.h" + +void m2m_memcpy(uint8* pDst,uint8* pSrc,uint32 sz) +{ + if(sz == 0) return; + do + { + *pDst = *pSrc; + pDst++; + pSrc++; + }while(--sz); +} +uint8 m2m_checksum(uint8* buf, int sz) +{ + uint8 cs = 0; + while(--sz) + { + cs ^= *buf; + buf++; + } + + return cs; +} + +void m2m_memset(uint8* pBuf,uint8 val,uint32 sz) +{ + if(sz == 0) return; + do + { + *pBuf = val; + pBuf++; + }while(--sz); +} + +uint16 m2m_strlen(uint8 * pcStr) +{ + uint16 u16StrLen = 0; + while(*pcStr) + { + u16StrLen ++; + pcStr++; + } + return u16StrLen; +} + +uint8 m2m_strncmp(uint8 *pcS1, uint8 *pcS2, uint16 u16Len) +{ + for ( ; u16Len > 0; pcS1++, pcS2++, --u16Len) + if (*pcS1 != *pcS2) + return ((*(uint8 *)pcS1 < *(uint8 *)pcS2) ? -1 : +1); + else if (*pcS1 == '\0') + return 0; + return 0; +} + +/* Finds the occurance of pcStr in pcIn. +If pcStr is part of pcIn it returns a valid pointer to the start of pcStr within pcIn. +Otherwise a NULL Pointer is returned. +*/ +uint8 * m2m_strstr(uint8 *pcIn, uint8 *pcStr) +{ + uint8 u8c; + uint16 u16StrLen; + + u8c = *pcStr++; + if (!u8c) + return (uint8 *) pcIn; // Trivial empty string case + + u16StrLen = m2m_strlen(pcStr); + do { + uint8 u8Sc; + + do { + u8Sc = *pcIn++; + if (!u8Sc) + return (uint8 *) 0; + } while (u8Sc != u8c); + } while (m2m_strncmp(pcIn, pcStr, u16StrLen) != 0); + + return (uint8 *) (pcIn - 1); +} + +sint8 m2m_memcmp(uint8 *pu8Buff1,uint8 *pu8Buff2 ,uint32 u32Size) +{ + uint32 i; + sint8 s8Result = 0; + for(i = 0 ; i < u32Size ; i++) + { + if(pu8Buff1[i] != pu8Buff2[i]) + { + s8Result = 1; + break; + } + } + return s8Result; +} diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/include/ecc_types.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/include/ecc_types.h new file mode 100644 index 0000000..764c3b9 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/include/ecc_types.h @@ -0,0 +1,245 @@ +/** + * + * \file + * + * \brief WINC Application Interface Internal Types. + * + * Copyright (c) 2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef __ECC_TYPES_H__ +#define __ECC_TYPES_H__ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "m2m_types.h" + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + + +#define ECC_LARGEST_CURVE_SIZE (32) +/*!< + The size of the the largest supported EC. For now, assuming + the 256-bit EC is the largest supported curve type. +*/ + + +#define ECC_POINT_MAX_SIZE ECC_LARGEST_CURVE_SIZE +/*!< + Maximum size of one coordinate of an EC point. +*/ + + +#define ECC_POINT_MAX_SIZE_WORDS (ECC_POINT_MAX_SIZE / 4) +/*!< + SIZE in 32-bit words. +*/ + +#if 0 +#define ECC_NUM_SUPP_CURVES ((sizeof(gastrECCSuppList)) / (sizeof(tstrEllipticCurve))) +#endif +/*!< +*/ + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +/*! +@enum \ + tenuEcNamedCurve + +@brief EC Named Curves + + Defines a list of supported ECC named curves. +*/ +typedef enum EcNamedCurve{ + EC_SECP192R1 = 19, + /*!< + It is defined by NIST as P192 and by the SEC Group as secp192r1. + */ + EC_SECP256R1 = 23, + /*!< + It is defined by NIST as P256 and by the SEC Group as secp256r1. + */ + EC_SECP384R1 = 24, + /*!< + It is defined by NIST as P384 and by the SEC Group as secp384r1. + */ + EC_SECP521R1 = 25, + /*!< + It is defined by NIST as P521 and by the SEC Group as secp521r1. + */ + EC_UNKNOWN = 255 +}tenuEcNamedCurve; + + +/*! +@struct \ + tstrECPoint + +@brief Elliptic Curve point representation +*/ +typedef struct EcPoint{ + uint8 X[ECC_POINT_MAX_SIZE]; + /*!< + The X-coordinate of the ec point. + */ + uint8 Y[ECC_POINT_MAX_SIZE]; + /*!< + The Y-coordinate of the ec point. + */ + uint16 u16Size; + /*!< + Point size in bytes (for each of the coordinates). + */ + uint16 u16PrivKeyID; + /*!< + ID for the corresponding private key. + */ +}tstrECPoint; + + +/*! +@struct \ + tstrECDomainParam + +@brief ECC Curve Domain Parameters + + The structure defines the ECC domain parameters for curves defined over prime finite fields. +*/ +typedef struct EcDomainParam{ + uint32 p[ECC_POINT_MAX_SIZE_WORDS]; + uint32 a[ECC_POINT_MAX_SIZE_WORDS]; + uint32 b[ECC_POINT_MAX_SIZE_WORDS]; + tstrECPoint G; +}tstrECDomainParam; + + +/*! +@struct \ + tstrEllipticCurve + +@brief + Definition of an elliptic curve +*/ +typedef struct{ + tenuEcNamedCurve enuType; + tstrECDomainParam strParam; +}tstrEllipticCurve; + + +typedef enum{ + ECC_REQ_NONE, + ECC_REQ_CLIENT_ECDH, + ECC_REQ_SERVER_ECDH, + ECC_REQ_GEN_KEY, + ECC_REQ_SIGN_GEN, + ECC_REQ_SIGN_VERIFY +}tenuEccREQ; + + +typedef struct{ + tstrECPoint strPubKey; + uint8 au8Key[ECC_POINT_MAX_SIZE]; +}tstrEcdhReqInfo; + + +typedef struct{ + uint32 u32nSig; +}tstrEcdsaVerifyReqInfo; + + +typedef struct{ + uint16 u16CurveType; + uint16 u16HashSz; +}tstrEcdsaSignReqInfo; + + +typedef struct{ + uint16 u16REQ; + uint16 u16Status; + uint32 u32UserData; + uint32 u32SeqNo; + union{ + tstrEcdhReqInfo strEcdhREQ; + tstrEcdsaSignReqInfo strEcdsaSignREQ; + tstrEcdsaVerifyReqInfo strEcdsaVerifyREQ; + }; +}tstrEccReqInfo; + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +GLOBALS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#if 0 +static tstrEllipticCurve gastrECCSuppList[] = { + { + EC_SECP256R1, + { + {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF}, + {0xFFFFFFFC, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF}, + {0x27D2604B, 0x3BCE3C3E, 0xCC53B0F6, 0x651D06B0, 0x769886BC, 0xB3EBBD55, 0xAA3A93E7, 0x5AC635D8}, + { + { + 0x6B, 0x17, 0xD1, 0xF2, 0xE1, 0x2C, 0x42, 0x47, 0xF8, 0xBC, 0xE6, 0xE5, 0x63, 0xA4, 0x40, 0xF2, + 0x77, 0x03, 0x7D, 0x81, 0x2D, 0xEB, 0x33, 0xA0, 0xF4, 0xA1, 0x39, 0x45, 0xD8, 0x98, 0xC2, 0x96 + }, + { + 0x4F, 0xE3, 0x42, 0xE2, 0xFE, 0x1A, 0x7F, 0x9B, 0x8E, 0xE7, 0xEB, 0x4A, 0x7C, 0x0F, 0x9E, 0x16, + 0x2B, 0xCE, 0x33, 0x57, 0x6B, 0x31, 0x5E, 0xCE, 0xCB, 0xB6, 0x40, 0x68, 0x37, 0xBF, 0x51, 0xF5 + }, + 32 + } + } + } +}; +#endif + +/*!< + List of supported Elliptic Curves ordered by security level (most secure curve is at index ZERO). +*/ + + + +#endif /* __ECC_TYPES_H__ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_ate_mode.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_ate_mode.h new file mode 100644 index 0000000..a17d298 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_ate_mode.h @@ -0,0 +1,732 @@ +/** + * + * \file + * + * \brief WINC ATE Test Driver Interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifdef _M2M_ATE_FW_ + +#ifndef _M2M_ATE_MODE_H_ +#define _M2M_ATE_MODE_H_ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#include "common/include/nm_common.h" +#include "driver/include/m2m_types.h" + +/** \defgroup m2m_ate ATE +*/ +/**@defgroup ATEDefine Defines + * @ingroup m2m_ate + * @{ + */ +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#define M2M_ATE_MAX_NUM_OF_RATES (20) +/*!< +Maximum number of all rates (b,g and n) + */ +#define M2M_ATE_MAX_FRAME_LENGTH (1024) +/*!< Maximum number of length for each frame + */ +#define M2M_ATE_MIN_FRAME_LENGTH (1) +/*!< Minimum number of length for each frame + */ +#define M2M_ATE_SUCCESS (M2M_SUCCESS) +/*!< No Error and operation has been completed successfully. +*/ +#define M2M_ATE_ERR_VALIDATE (M2M_ERR_FAIL) +/*!< Error in parameters passed to functions. + */ +#define M2M_ATE_ERR_TX_ALREADY_RUNNING (-1) +/*!< Error in starting a transmission test. Another test is already running and its not allowed to start another ATE test. + */ +#define M2M_ATE_ERR_RX_ALREADY_RUNNING (-2) +/*!< Error in starting a reception test. Another test is already running and its not allowed to start another ATE test. + */ +#define M2M_ATE_ERR_UNHANDLED_CASE (-3) +/*!< Invalid case. + */ +#define M2M_ATE_RX_DISABLE_DA 0x0 +/*!< Filter selection for received frames: Disable filtering received frames by the destination address. + */ +#define M2M_ATE_RX_ENABLE_DA 0x1 +/*!< Filter selection for received frames: Enable filtering received frames by the destination address. + */ +#define M2M_ATE_RX_DISABLE_SA 0x0 +/*!< Filter selection for received frames: Disable filtering received frames by the source address. + */ +#define M2M_ATE_RX_ENABLE_SA 0x1 +/*!< Filter selection for received frames: Enable filtering received frames by the source address. + */ +#define M2M_ATE_DISABLE_SELF_MACADDR 0x0 +/*!\n",ret); + while(1); + } + //Initialize the OTA module + m2m_ota_init(OtaUpdateCb,NULL); + //connect to AP that provide connection to the OTA server + m2m_wifi_default_connect(); + + while(1) + { + + //Handle the app state machine plus the WINC event handler + while(m2m_wifi_handle_events(NULL) != M2M_SUCCESS) { + + } + + } +} +@endcode + +*/ +NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl); + /**@}*/ +/** @defgroup OtaStartUpdatefn m2m_ota_start_update_crt +* @ingroup WLANAPI +* Request OTA start for cortus application image using the downloaded URL, the OTA module will download the OTA image and ensure integrity of the image, +* and update the validity of the image in control structure. Switching to that image requires calling @ref m2m_ota_switch_crt API. +* As a prerequisite @ref m2m_ota_init should be called before using @ref m2m_ota_start_update_crt(). +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl); + +@param [in] u8DownloadUrl + The cortus application image url. +@warning + Calling this API does not guarantee cortus application image update, It depends on the connection with the download server and the validity of the image. + If the API response is failure this may invalidate the roll-back image if it was previously valid, since the WINC does not have any internal memory + except the flash roll-back image location to validate the downloaded image from + +@see + m2m_ota_init + tpfOtaUpdateCb + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl); + /**@}*/ +/** @defgroup OtaRollbackfn m2m_ota_rollback +* @ingroup WLANAPI + Request OTA Roll-back to the old (other) WINC image, the WINC firmware will check the validation of the Roll-back image + and switch to it if it is valid. + If the API response is success, system restart is required (re-initialize the driver with hardware rest) update the host driver version may + be required if it is did not match the minimum version supported by the WINC firmware. + +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ota_rollback(void); + +@sa + m2m_ota_init + m2m_ota_start_update + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_rollback(void); + /**@}*/ +/** @defgroup OtaRollbackfn m2m_ota_rollback_crt +* @ingroup WLANAPI + Request Cortus application OTA Roll-back to the old (other) cortus application image, the WINC firmware will check the validation of the Roll-back image + and switch to it if it is valid. + If the API response is success, system restart is required (re-initialize the driver with hardware rest) update the host driver version may + be required. + +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ota_rollback_crt(void); + +@sa + m2m_ota_init + m2m_ota_start_update_crt + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_rollback_crt(void); + /**@}*/ +/** @defgroup OtaAbortfn m2m_ota_abort +* @ingroup WLANAPI + Request abort of current OTA download. + The WINC firmware will terminate the OTA download if one is in progress. + If no download is in progress, the API will respond with failure. +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ota_abort(void); + +@return + The function returns @ref M2M_SUCCESS for successful operation and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_abort(void); + /**@}*/ + /**@}*/ +/** @defgroup OtaSwitchFirmware m2m_ota_switch_firmware +* @ingroup WLANAPI +* Switch to the upgraded Firmware, that API will update the control structure working image to the upgraded image + take effect will be on the next system restart +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ota_switch_firmware(void); + +@warning + It is important to note that if the API succeeds, system restart is required (re-initializing the driver with hardware reset) updating the host driver version may be required + if it does not match the minimum driver version supported by the WINC's firmware. +@sa + m2m_ota_init + m2m_ota_start_update + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_switch_firmware(void); + /**@}*/ + /**@}*/ +/** @defgroup OtaSwitchFirmware m2m_ota_switch_crt +* @ingroup WLANAPI +* Switch to the upgraded cortus application, that API will update the control structure working image to the upgraded image + take effect will be on the next system restart +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ota_switch_firmware(void); + +@warning + It is important to note that if the API succeeds, system restart is required (re-initializing the driver with hardware reset) updating the host driver version may be required + if it does not match the minimum driver version supported by the WINC's firmware. +@sa + m2m_ota_init + m2m_ota_start_update_crt + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_switch_crt(void); +/*! +@fn \ + NMI_API sint8 m2m_ota_get_firmware_version(void); + +@brief + Get the OTA Firmware version. + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_get_firmware_version(tstrM2mRev *pstrRev); + /**@}*/ +NMI_API sint8 m2m_ota_test(void); + +#ifdef __cplusplus +} +#endif +#endif /* __M2M_OTA_H__ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_periph.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_periph.h new file mode 100644 index 0000000..1012882 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_periph.h @@ -0,0 +1,411 @@ +/** + * + * \file + * + * \brief WINC Peripherals Application Interface. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _M2M_PERIPH_H_ +#define _M2M_PERIPH_H_ + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +#include "common/include/nm_common.h" +#include "driver/include/m2m_types.h" + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*! +@struct \ + tstrPerphInitParam + +@brief + Peripheral module initialization parameters. +*/ +typedef struct { + void * arg; +} tstrPerphInitParam; + + +/*! +@enum \ + tenuGpioNum + +@brief + A list of GPIO numbers configurable through the m2m_periph module. +*/ +typedef enum { + M2M_PERIPH_GPIO3, /*!< GPIO15 pad */ + M2M_PERIPH_GPIO4, /*!< GPIO16 pad */ + M2M_PERIPH_GPIO5, /*!< GPIO18 pad */ + M2M_PERIPH_GPIO6, /*!< GPIO18 pad */ + M2M_PERIPH_GPIO15, /*!< GPIO15 pad */ + M2M_PERIPH_GPIO16, /*!< GPIO16 pad */ + M2M_PERIPH_GPIO18, /*!< GPIO18 pad */ + M2M_PERIPH_GPIO_MAX +} tenuGpioNum; + + +/*! +@enum \ + tenuI2cMasterSclMuxOpt + +@brief + Allowed pin multiplexing options for I2C master SCL signal. +*/ +typedef enum { + M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_HOST_WAKEUP, /*!< I2C master SCL is avaiable on HOST_WAKEUP. */ + M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_SD_DAT3, /*!< I2C master SCL is avaiable on SD_DAT3 (GPIO 7). */ + M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_GPIO13, /*!< I2C master SCL is avaiable on GPIO 13. */ + M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_GPIO4, /*!< I2C master SCL is avaiable on GPIO 4.*/ + M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_I2C_SCL, /*!< I2C master SCL is avaiable on I2C slave SCL. */ + M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_NUM +} tenuI2cMasterSclMuxOpt; + +/*! +@enum \ + tenuI2cMasterSdaMuxOpt + +@brief + Allowed pin multiplexing options for I2C master SDA signal. +*/ +typedef enum { + M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_RTC_CLK , /*!< I2C master SDA is avaiable on RTC_CLK. */ + M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_SD_CLK, /*!< I2C master SDA is avaiable on SD_CLK (GPIO 8). */ + M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_GPIO14, /*!< I2C master SDA is avaiable on GPIO 14. */ + M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_GPIO6, /*!< I2C master SDA is avaiable on GPIO 6.*/ + M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_I2C_SDA, /*!< I2C master SDA is avaiable on I2C slave SDA. */ + M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_NUM +} tenuI2cMasterSdaMuxOpt; + + +/*! +@struct \ + tstrI2cMasterInitParam + +@brief + I2C master configuration parameters. +@sa + tenuI2cMasterSclMuxOpt + tenuI2cMasterSdaMuxOpt +*/ +typedef struct { + uint8 enuSclMuxOpt; /*!< SCL multiplexing option. Allowed value are defined in tenuI2cMasterSclMuxOpt */ + uint8 enuSdaMuxOpt; /*!< SDA multiplexing option. Allowed value are defined in tenuI2cMasterSdaMuxOpt */ + uint8 u8ClkSpeedKHz; /*!< I2C master clock speed in KHz. */ +} tstrI2cMasterInitParam; + +/*! +@enum \ + tenuI2cMasterFlags + +@brief + Bitwise-ORed flags for use in m2m_periph_i2c_master_write and m2m_periph_i2c_master_read +@sa + m2m_periph_i2c_master_write + m2m_periph_i2c_master_read +*/ +typedef enum { + I2C_MASTER_NO_FLAGS = 0x00, + /*!< No flags. */ + I2C_MASTER_NO_STOP = 0x01, + /*!< No stop bit after this transaction. Useful for scattered buffer read/write operations. */ + I2C_MASTER_NO_START = 0x02, + /*!< No start bit at the beginning of this transaction. Useful for scattered buffer read/write operations.*/ +} tenuI2cMasterFlags; + +/*! +@enum \ + tenuPullupMask + +@brief + Bitwise-ORed flags for use in m2m_perph_pullup_ctrl. +@sa + m2m_periph_pullup_ctrl + +*/ +typedef enum { + M2M_PERIPH_PULLUP_DIS_HOST_WAKEUP = (1ul << 0), + M2M_PERIPH_PULLUP_DIS_RTC_CLK = (1ul << 1), + M2M_PERIPH_PULLUP_DIS_IRQN = (1ul << 2), + M2M_PERIPH_PULLUP_DIS_GPIO_3 = (1ul << 3), + M2M_PERIPH_PULLUP_DIS_GPIO_4 = (1ul << 4), + M2M_PERIPH_PULLUP_DIS_GPIO_5 = (1ul << 5), + M2M_PERIPH_PULLUP_DIS_SD_DAT3 = (1ul << 6), + M2M_PERIPH_PULLUP_DIS_SD_DAT2_SPI_RXD = (1ul << 7), + M2M_PERIPH_PULLUP_DIS_SD_DAT1_SPI_SSN = (1ul << 9), + M2M_PERIPH_PULLUP_DIS_SD_CMD_SPI_SCK = (1ul << 10), + M2M_PERIPH_PULLUP_DIS_SD_DAT0_SPI_TXD = (1ul << 11), + M2M_PERIPH_PULLUP_DIS_GPIO_6 = (1ul << 12), + M2M_PERIPH_PULLUP_DIS_SD_CLK = (1ul << 13), + M2M_PERIPH_PULLUP_DIS_I2C_SCL = (1ul << 14), + M2M_PERIPH_PULLUP_DIS_I2C_SDA = (1ul << 15), + M2M_PERIPH_PULLUP_DIS_GPIO_11 = (1ul << 16), + M2M_PERIPH_PULLUP_DIS_GPIO_12 = (1ul << 17), + M2M_PERIPH_PULLUP_DIS_GPIO_13 = (1ul << 18), + M2M_PERIPH_PULLUP_DIS_GPIO_14 = (1ul << 19), + M2M_PERIPH_PULLUP_DIS_GPIO_15 = (1ul << 20), + M2M_PERIPH_PULLUP_DIS_GPIO_16 = (1ul << 21), + M2M_PERIPH_PULLUP_DIS_GPIO_17 = (1ul << 22), + M2M_PERIPH_PULLUP_DIS_GPIO_18 = (1ul << 23), + M2M_PERIPH_PULLUP_DIS_GPIO_19 = (1ul << 24), + M2M_PERIPH_PULLUP_DIS_GPIO_20 = (1ul << 25), + M2M_PERIPH_PULLUP_DIS_GPIO_21 = (1ul << 26), + M2M_PERIPH_PULLUP_DIS_GPIO_22 = (1ul << 27), + M2M_PERIPH_PULLUP_DIS_GPIO_23 = (1ul << 28), + M2M_PERIPH_PULLUP_DIS_GPIO_24 = (1ul << 29), +} tenuPullupMask; + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +#ifdef __cplusplus + extern "C" { +#endif + +/*! +@fn \ + NMI_API sint8 m2m_periph_init(tstrPerphInitParam * param); + +@brief + Initialize the NMC1500 peripheral driver module. + +@param [in] param + Peripheral module initialization structure. See members of tstrPerphInitParam. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tstrPerphInitParam +*/ +NMI_API sint8 m2m_periph_init(tstrPerphInitParam * param); + +/*! +@fn \ + NMI_API sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir); + +@brief + Configure a specific NMC1500 pad as a GPIO and sets its direction (input or output). + +@param [in] u8GpioNum + GPIO number. Allowed values are defined in tenuGpioNum. + +@param [in] u8GpioDir + GPIO direction: Zero = input. Non-zero = output. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuGpioNum +*/ +NMI_API sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir); + +/*! +@fn \ + NMI_API sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal); + +@brief + Set an NMC1500 GPIO output level high or low. + +@param [in] u8GpioNum + GPIO number. Allowed values are defined in tenuGpioNum. + +@param [in] u8GpioVal + GPIO output value. Zero = low, non-zero = high. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuGpioNum +*/ +NMI_API sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal); + +/*! +@fn \ + NMI_API sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal); + +@brief + Read an NMC1500 GPIO input level. + +@param [in] u8GpioNum + GPIO number. Allowed values are defined in tenuGpioNum. + +@param [out] pu8GpioVal + GPIO input value. Zero = low, non-zero = high. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuGpioNum +*/ +NMI_API sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal); + +/*! +@fn \ + NMI_API sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn); + +@brief + Set an NMC1500 GPIO pullup resisitor enable or disable. + +@param [in] u8GpioNum + GPIO number. Allowed values are defined in tenuGpioNum. + +@param [in] u8PullupEn + Zero: pullup disabled. Non-zero: pullup enabled. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuGpioNum +*/ +NMI_API sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn); + +/*! +@fn \ + NMI_API sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param); + +@brief + Initialize and configure the NMC1500 I2C master peripheral. + +@param [in] param + I2C master initialization structure. See members of tstrI2cMasterInitParam. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tstrI2cMasterInitParam +*/ +NMI_API sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param); + +/*! +@fn \ + NMI_API sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags); + +@brief + Write a stream of bytes to the I2C slave device. + +@param [in] u8SlaveAddr + 7-bit I2C slave address. +@param [in] pu8Buf + A pointer to an input buffer which contains a stream of bytes. +@param [in] u16BufLen + Input buffer length in bytes. +@param [in] flags + Write operation bitwise-ORed flags. See tenuI2cMasterFlags. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuI2cMasterFlags +*/ +NMI_API sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags); + + +/*! +@fn \ + NMI_API sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags); + +@brief + Write a stream of bytes to the I2C slave device. + +@param [in] u8SlaveAddr + 7-bit I2C slave address. +@param [out] pu8Buf + A pointer to an output buffer in which a stream of bytes are received. +@param [in] u16BufLen + Max output buffer length in bytes. +@param [out] pu16ReadLen + Actual number of bytes received. +@param [in] flags + Write operation bitwise-ORed flags. See tenuI2cMasterFlags. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuI2cMasterFlags +*/ +NMI_API sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags); + + +/*! +@fn \ + NMI_API sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable); + +@brief + Control the programmable pull-up resistor on the chip pads . + + +@param [in] pinmask + Write operation bitwise-ORed mask for which pads to control. Allowed values are defined in tenuPullupMask. + +@param [in] enable + Set to 0 to disable pull-up resistor. Non-zero will enable the pull-up. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuPullupMask +*/ +NMI_API sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable); + +#ifdef __cplusplus +} +#endif + + +#endif /* _M2M_PERIPH_H_ */ \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_ssl.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_ssl.h new file mode 100644 index 0000000..f5271f0 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_ssl.h @@ -0,0 +1,182 @@ +/** + * + * \file + * + * \brief WINC Application Interface Internal Types. + * + * Copyright (c) 2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/**@defgroup SSLAPI SSL +*/ + +#ifndef __M2M_SSL_H__ +#define __M2M_SSL_H__ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "common/include/nm_common.h" +#include "driver/include/m2m_types.h" +#include "driver/source/nmdrv.h" +#include "ecc_types.h" +#include "socket/include/socket.h" + +/**@defgroup SSLEnums Enumeration/Typedefs + * @ingroup SSLAPI + * @{*/ + +/*! +@typedef \ + void (*tpfAppSslCb) (uint8 u8MsgType, void * pvMsg); + +@brief A callback to get SSL notifications. + +@param[in] u8MsgType +@param[in] pvMsg A structure to provide notification payload. +*/ +typedef void (*tpfAppSSLCb) (uint8 u8MsgType, void * pvMsg); + +/**@} +*/ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/** \defgroup SSLFUNCTIONS Functions +* @ingroup SSLAPI +*/ + +/**@{*/ +/*! + @fn \ m2m_ssl_init(tpfAppSslCb pfAppSslCb); + @brief Initializes the SSL layer. + @param [in] pfAppSslCb + Application SSL callback function. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_init(tpfAppSSLCb pfAppSSLCb); + +/*! + @fn \ NMI_API sint8 m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz) + @brief Sends ECC responses to the WINC + @param [in] strECCResp + ECC Response struct. + @param [in] pu8RspDataBuffe + Pointer of the response data to be sent. + @param [in] u16RspDataSz + Response data size. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz); + +/*! + @fn \ NMI_API sint8 m2m_ssl_send_certs_to_winc(uint8* pu8Buffer, uint32 u32BufferSz) + @brief Sends certificates to the WINC + @param [in] pu8Buffer + Pointer to the certificates. + @param [in] u32BufferSz + Size of the certificates. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_send_certs_to_winc(uint8* pu8Buffer, uint32 u32BufferSz); + +/*! + @fn \ NMI_API sint8 m2m_ssl_retrieve_cert(uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key) + @brief Retrieve the certificate to be verified from the WINC + @param [in] pu16CurveType + Pointer to the certificate curve type. + @param [in] pu8Hash + Pointer to the certificate hash. + @param [in] pu8Sig + Pointer to the certificate signature. + @param [in] pu8Key + Pointer to the certificate Key. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_retrieve_cert(uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key); + +/*! + @fn \ NMI_API sint8 m2m_ssl_retrieve_hash(uint8* pu8Hash, uint16 u16HashSz) + @brief Retrieve the certificate hash + @param [in] pu8Hash + Pointer to the certificate hash. + @param [in] u16HashSz + Hash size. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_retrieve_hash(uint8* pu8Hash, uint16 u16HashSz); + +/*! + @fn \ NMI_API void m2m_ssl_stop_processing_certs(void) + @brief Allow ssl driver to tidy up in case application does not read all available certificates. + @warning This API must only be called if some certificates are left unread. + @return None. +*/ +NMI_API void m2m_ssl_stop_processing_certs(void); + +/*! + @fn \ NMI_API void m2m_ssl_ecc_process_done(void) + @brief Allow ssl driver to tidy up after application has finished processing ecc message. + @warning This API must be called after receiving a SSL callback with type @ref M2M_SSL_REQ_ECC + @return None. +*/ +NMI_API void m2m_ssl_ecc_process_done(void); + +/*! +@fn \ + NMI_API sint8 m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP); + Override the default Active SSL ciphers in the SSL module with a certain combination selected by the caller in the form of + a bitmap containing the required ciphers to be on. + There is no need to call this function if the application will not change the default ciphersuites. + +@param [in] u32SslCsBMP + Bitmap containing the desired ciphers to be enabled for the SSL module. The ciphersuites are defined in + @ref SSLCipherSuiteID. + The default ciphersuites are all ciphersuites supported by the firmware with the exception of ECC ciphersuites. + The caller can override the default with any desired combination, except for combinations involving both RSA + and ECC; if any RSA ciphersuite is enabled, then firmware will disable all ECC ciphersuites. + If u32SslCsBMP does not contain any ciphersuites supported by firmware, then the current active list will not + be changed. + +@return + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) +*/ +sint8 m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP); + + /**@}*/ +#endif /* __M2M_SSL_H__ */ \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_types.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_types.h new file mode 100644 index 0000000..a847f3f --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_types.h @@ -0,0 +1,2383 @@ +/** + * + * \file + * + * \brief WINC Application Interface Internal Types. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef __M2M_WIFI_TYPES_H__ +#define __M2M_WIFI_TYPES_H__ + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#ifndef _BOOT_ +#ifndef _FIRMWARE_ +#include "common/include/nm_common.h" +#else +#include "m2m_common.h" +#endif +#endif + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/**@defgroup WlanDefines Defines + * @ingroup m2m_wifi + */ +/**@{*/ +#define M2M_MAJOR_SHIFT (8) +#define M2M_MINOR_SHIFT (4) +#define M2M_PATCH_SHIFT (0) + +#define M2M_DRV_VERSION_SHIFT (16) +#define M2M_FW_VERSION_SHIFT (0) + +#define M2M_GET_MAJOR(ver_info_hword) ((uint8)((ver_info_hword) >> M2M_MAJOR_SHIFT) & 0xff) +#define M2M_GET_MINOR(ver_info_hword) ((uint8)((ver_info_hword) >> M2M_MINOR_SHIFT) & 0x0f) +#define M2M_GET_PATCH(ver_info_hword) ((uint8)((ver_info_hword) >> M2M_PATCH_SHIFT) & 0x0f) + +#define M2M_GET_FW_VER(ver_info_word) ((uint16) ((ver_info_word) >> M2M_FW_VERSION_SHIFT)) +#define M2M_GET_DRV_VER(ver_info_word) ((uint16) ((ver_info_word) >> M2M_DRV_VERSION_SHIFT)) + +#define M2M_GET_DRV_MAJOR(ver_info_word) M2M_GET_MAJOR(M2M_GET_DRV_VER(ver_info_word)) +#define M2M_GET_DRV_MINOR(ver_info_word) M2M_GET_MINOR(M2M_GET_DRV_VER(ver_info_word)) +#define M2M_GET_DRV_PATCH(ver_info_word) M2M_GET_PATCH(M2M_GET_DRV_VER(ver_info_word)) + +#define M2M_GET_FW_MAJOR(ver_info_word) M2M_GET_MAJOR(M2M_GET_FW_VER(ver_info_word)) +#define M2M_GET_FW_MINOR(ver_info_word) M2M_GET_MINOR(M2M_GET_FW_VER(ver_info_word)) +#define M2M_GET_FW_PATCH(ver_info_word) M2M_GET_PATCH(M2M_GET_FW_VER(ver_info_word)) + +#define M2M_MAKE_VERSION(major, minor, patch) ( \ + ((uint16)((major) & 0xff) << M2M_MAJOR_SHIFT) | \ + ((uint16)((minor) & 0x0f) << M2M_MINOR_SHIFT) | \ + ((uint16)((patch) & 0x0f) << M2M_PATCH_SHIFT)) + +#define M2M_MAKE_VERSION_INFO(fw_major, fw_minor, fw_patch, drv_major, drv_minor, drv_patch) \ + ( \ + ( ((uint32)M2M_MAKE_VERSION((fw_major), (fw_minor), (fw_patch))) << M2M_FW_VERSION_SHIFT) | \ + ( ((uint32)M2M_MAKE_VERSION((drv_major), (drv_minor), (drv_patch))) << M2M_DRV_VERSION_SHIFT)) + +#define REL_19_5_2_VER M2M_MAKE_VERSION_INFO(19,5,2,19,3,0) +#define REL_19_5_1_VER M2M_MAKE_VERSION_INFO(19,5,1,19,3,0) +#define REL_19_5_0_VER M2M_MAKE_VERSION_INFO(19,5,0,19,3,0) +#define REL_19_4_6_VER M2M_MAKE_VERSION_INFO(19,4,6,19,3,0) +#define REL_19_4_5_VER M2M_MAKE_VERSION_INFO(19,4,5,19,3,0) +#define REL_19_4_4_VER M2M_MAKE_VERSION_INFO(19,4,4,19,3,0) +#define REL_19_4_3_VER M2M_MAKE_VERSION_INFO(19,4,3,19,3,0) +#define REL_19_4_2_VER M2M_MAKE_VERSION_INFO(19,4,2,19,3,0) +#define REL_19_4_1_VER M2M_MAKE_VERSION_INFO(19,4,1,19,3,0) +#define REL_19_4_0_VER M2M_MAKE_VERSION_INFO(19,4,0,19,3,0) +#define REL_19_3_1_VER M2M_MAKE_VERSION_INFO(19,3,1,19,3,0) +#define REL_19_3_0_VER M2M_MAKE_VERSION_INFO(19,3,0,19,3,0) +#define REL_19_2_2_VER M2M_MAKE_VERSION_INFO(19,2,2,19,2,0) +#define REL_19_2_1_VER M2M_MAKE_VERSION_INFO(19,2,1,19,2,0) +#define REL_19_2_0_VER M2M_MAKE_VERSION_INFO(19,2,0,19,2,0) +#define REL_19_1_0_VER M2M_MAKE_VERSION_INFO(19,1,0,18,2,0) +#define REL_19_0_0_VER M2M_MAKE_VERSION_INFO(19,0,0,18,1,1) + +/*======*======*======*======* + FIRMWARE VERSION NO INFO + *======*======*======*======*/ + +#define M2M_RELEASE_VERSION_MAJOR_NO (19) +/*!< Firmware Major release version number. +*/ + + +#define M2M_RELEASE_VERSION_MINOR_NO (5) +/*!< Firmware Minor release version number. +*/ + +#define M2M_RELEASE_VERSION_PATCH_NO (2) +/*!< Firmware patch release version number. +*/ + +/*======*======*======*======* + SUPPORTED DRIVER VERSION NO INFO + *======*======*======*======*/ + +#define M2M_MIN_REQ_DRV_VERSION_MAJOR_NO (19) +/*!< Driver Major release version number. +*/ + + +#define M2M_MIN_REQ_DRV_VERSION_MINOR_NO (3) +/*!< Driver Minor release version number. +*/ + +#define M2M_MIN_REQ_DRV_VERSION_PATCH_NO (0) +/*!< Driver patch release version number. +*/ + +#define M2M_MIN_REQ_DRV_SVN_VERSION (0) +/*!< Driver svn version. +*/ + + + +#if !defined(M2M_RELEASE_VERSION_MAJOR_NO) || !defined(M2M_RELEASE_VERSION_MINOR_NO) +#error Undefined version number +#endif + +#define M2M_BUFFER_MAX_SIZE (1600UL - 4) +/*!< Maximum size for the shared packet buffer. + */ + + +#define M2M_MAC_ADDRES_LEN 6 +/*!< The size fo 802 MAC address. + */ + +#define M2M_ETHERNET_HDR_OFFSET 34 +/*!< The offset of the Ethernet header within the WLAN Tx Buffer. + */ + + +#define M2M_ETHERNET_HDR_LEN 14 +/*!< Length of the Etherenet header in bytes. +*/ + + +#define M2M_MAX_SSID_LEN 33 +/*!< Maximum size for the Wi-Fi SSID including the NULL termination. + */ + + +#define M2M_MAX_PSK_LEN 65 +/*!< Maximum size for the WPA PSK including the NULL termination. + */ + +#define M2M_MIN_PSK_LEN 9 +/*!< Maximum size for the WPA PSK including the NULL termination. + */ + +#define M2M_DEVICE_NAME_MAX 48 +/*!< Maximum Size for the device name including the NULL termination. + */ + + +#define M2M_LISTEN_INTERVAL 1 +/*!< The STA uses the Listen Interval parameter to indicate to the AP how + many beacon intervals it shall sleep before it retrieves the queued frames + from the AP. +*/ + +#define MAX_HIDDEN_SITES 4 +/*!< + max number of hidden SSID suuported by scan request +*/ + + +#define M2M_1X_USR_NAME_MAX 21 +/*!< The maximum size of the user name including the NULL termination. + It is used for RADIUS authentication in case of connecting the device to + an AP secured with WPA-Enterprise. +*/ + + +#define M2M_1X_PWD_MAX 41 +/*!< The maximum size of the password including the NULL termination. + It is used for RADIUS authentication in case of connecting the device to + an AP secured with WPA-Enterprise. +*/ + +#define M2M_CUST_IE_LEN_MAX 252 +/*!< The maximum size of IE (Information Element). +*/ + +#define PWR_DEFAULT PWR_HIGH +/********************* + * + * WIFI GROUP requests + */ + +#define M2M_CONFIG_CMD_BASE 1 +/*!< The base value of all the host configuration commands opcodes. +*/ +#define M2M_STA_CMD_BASE 40 +/*!< The base value of all the station mode host commands opcodes. +*/ +#define M2M_AP_CMD_BASE 70 +/*!< The base value of all the Access Point mode host commands opcodes. +*/ +#define M2M_P2P_CMD_BASE 90 +/*!< The base value of all the P2P mode host commands opcodes. +*/ +#define M2M_SERVER_CMD_BASE 100 +/*!< The base value of all the power save mode host commands codes. +*/ +/********************** + * OTA GROUP requests + */ +#define M2M_OTA_CMD_BASE 100 +/*!< The base value of all the OTA mode host commands opcodes. + * The OTA Have special group so can extended from 1-M2M_MAX_GRP_NUM_REQ +*/ +/*********************** + * + * CRYPTO group requests + */ +#define M2M_CRYPTO_CMD_BASE 1 +/*!< The base value of all the crypto mode host commands opcodes. + * The crypto Have special group so can extended from 1-M2M_MAX_GRP_NUM_REQ +*/ + +#define M2M_MAX_GRP_NUM_REQ (127) +/*!< max number of request in one group equal to 127 as the last bit reserved for config or data pkt +*/ + +#define WEP_40_KEY_STRING_SIZE ((uint8)10) +/*!< Indicate the wep key size in bytes for 40 bit string passphrase. +*/ + +#define WEP_104_KEY_STRING_SIZE ((uint8)26) +/*!< Indicate the wep key size in bytes for 104 bit string passphrase. +*/ +#define WEP_KEY_MAX_INDEX ((uint8)4) +/*!< Indicate the max key index value for WEP authentication +*/ +#define M2M_SHA256_CONTEXT_BUFF_LEN (128) +/*!< sha256 context size +*/ +#define M2M_SCAN_DEFAULT_NUM_SLOTS (2) +/*!< The default. number of scan slots performed by the WINC board. +*/ +#define M2M_SCAN_DEFAULT_SLOT_TIME (30) +/*!< The default. duration in miliseconds of a scan slots performed by the WINC board. +*/ +#define M2M_SCAN_DEFAULT_NUM_PROBE (2) +/*!< The default. number of scan slots performed by the WINC board. +*/ + + +/*======*======*======*======* + CONNECTION ERROR DEFINITIONS + *======*======*======*======*/ +typedef enum { + M2M_DEFAULT_CONN_INPROGRESS = ((sint8)-23), + /*!< + A failure that indicates that a default connection or forced connection is in progress + */ + M2M_DEFAULT_CONN_FAIL, + /*!< + A failure response that indicates that the winc failed to connect to the cached network + */ + M2M_DEFAULT_CONN_SCAN_MISMATCH, + /*!< + A failure response that indicates that no one of the cached networks + was found in the scan results, as a result to the function call m2m_default_connect. + */ + M2M_DEFAULT_CONN_EMPTY_LIST + /*!< + A failure response that indicates an empty network list as + a result to the function call m2m_default_connect. + */ + +}tenuM2mDefaultConnErrcode; + + + +/*======*======*======*======* + TLS DEFINITIONS + *======*======*======*======*/ +#define TLS_FILE_NAME_MAX 48 +/*!< Maximum length for each TLS certificate file name including null terminator. +*/ +#define TLS_SRV_SEC_MAX_FILES 8 +/*!< Maximum number of certificates allowed in TLS_SRV section. +*/ +#define TLS_SRV_SEC_START_PATTERN_LEN 8 +/*!< Length of certificate struct start pattern. +*/ +/*======*======*======*======* + OTA DEFINITIONS + *======*======*======*======*/ + +#define OTA_STATUS_VALID (0x12526285) +/*!< + Magic value updated in the Control structure in case of ROLLACK image Valid +*/ +#define OTA_STATUS_INVALID (0x23987718) +/*!< + Magic value updated in the Control structure in case of ROLLACK image InValid +*/ +#define OTA_MAGIC_VALUE (0x1ABCDEF9) +/*!< + Magic value set at the beginning of the OTA image header +*/ +#define M2M_MAGIC_APP (0xef522f61UL) +/*!< + Magic value set at the beginning of the Cortus OTA image header +*/ + +#define OTA_FORMAT_VER_0 (0) /*Till 19.2.2 format*/ +#define OTA_FORMAT_VER_1 (1) /*starting from 19.3.0 CRC is used and sequence number is used*/ +/*!< + Control structure format version +*/ +#define OTA_SHA256_DIGEST_SIZE (32) +/*!< + Sha256 digest size in the OTA image, + the sha256 digest is set at the beginning of image before the OTA header + */ + +/*======*======*======*======* + SSL DEFINITIONS + *======*======*======*======*/ + +#define TLS_CRL_DATA_MAX_LEN 64 +/* Every bit have 3dB gain control each. + for example: + 1 ->3db + 3 ->6db + 7 ->9db + */ + uint16 u8PPAGFor11GN; + /*!< PPA gain for 11GN (as the RF document represented) + PPA_AGC<0:2> Every bit have 3dB gain control each. + for example: + 1 ->3db + 3 ->6db + 7 ->9db + */ +}tstrM2mWifiGainsParams; + +/*! +@struct \ + tstrM2mWifiWepParams + +@brief + WEP security key parameters. +*/ +typedef struct{ + uint8 u8KeyIndx; + /*!< Wep key Index. + */ + uint8 u8KeySz; + /*!< Wep key Size. + */ + uint8 au8WepKey[WEP_104_KEY_STRING_SIZE + 1]; + /*!< WEP Key represented as a NULL terminated ASCII string. + */ + uint8 __PAD24__[3]; + /*!< Padding bytes to keep the structure word alligned. + */ +}tstrM2mWifiWepParams; + + +/*! +@struct \ + tstr1xAuthCredentials + +@brief + Credentials for the user to authenticate with the AAA server (WPA-Enterprise Mode IEEE802.1x). +*/ +typedef struct{ + uint8 au8UserName[M2M_1X_USR_NAME_MAX]; + /*!< User Name. It must be Null terminated string. + */ + uint8 au8Passwd[M2M_1X_PWD_MAX]; + /*!< Password corresponding to the user name. It must be Null terminated string. + */ +}tstr1xAuthCredentials; + + +/*! +@union \ + tuniM2MWifiAuth + +@brief + Wi-Fi Security Parameters for all supported security modes. +*/ +typedef union{ + uint8 au8PSK[M2M_MAX_PSK_LEN]; + /*!< Pre-Shared Key in case of WPA-Personal security. + */ + tstr1xAuthCredentials strCred1x; + /*!< Credentials for RADIUS server authentication in case of WPA-Enterprise security. + */ + tstrM2mWifiWepParams strWepInfo; + /*!< WEP key parameters in case of WEP security. + */ +}tuniM2MWifiAuth; + + +/*! +@struct \ + tstrM2MWifiSecInfo + +@brief + Authentication credentials to connect to a Wi-Fi network. +*/ +typedef struct{ + tuniM2MWifiAuth uniAuth; + /*!< Union holding all possible authentication parameters corresponding the current security types. + */ + uint8 u8SecType; + /*!< Wi-Fi network security type. See tenuM2mSecType for supported security types. + */ +#define __PADDING__ (4 - ((sizeof(tuniM2MWifiAuth) + 1) % 4)) + uint8 __PAD__[__PADDING__]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2MWifiSecInfo; + + +/*! +@struct \ + tstrM2mWifiConnect + +@brief + Wi-Fi Connect Request +*/ +typedef struct{ + tstrM2MWifiSecInfo strSec; + /*!< Security parameters for authenticating with the AP. + */ + uint16 u16Ch; + /*!< RF Channel for the target SSID. + */ + uint8 au8SSID[M2M_MAX_SSID_LEN]; + /*!< SSID of the desired AP. It must be NULL terminated string. + */ + uint8 u8NoSaveCred; +#define __CONN_PAD_SIZE__ (4 - ((sizeof(tstrM2MWifiSecInfo) + M2M_MAX_SSID_LEN + 3) % 4)) + uint8 __PAD__[__CONN_PAD_SIZE__]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mWifiConnect; + + +/*! +@struct \ + tstrM2MWPSConnect + +@brief + WPS Configuration parameters + +@sa + tenuWPSTrigger +*/ +typedef struct { + uint8 u8TriggerType; + /*!< WPS triggering method (Push button or PIN) + */ + char acPinNumber[8]; + /*!< WPS PIN No (for PIN method) + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2MWPSConnect; + + +/*! +@struct \ + tstrM2MWPSInfo + +@brief WPS Result + + This structure is passed to the application in response to a WPS request. If the WPS session is completed successfully, the + structure will have Non-ZERO authentication type. If the WPS Session fails (due to error or timeout) the authentication type + is set to ZERO. + +@sa + tenuM2mSecType +*/ +typedef struct{ + uint8 u8AuthType; + /*!< Network authentication type. + */ + uint8 u8Ch; + /*!< RF Channel for the AP. + */ + uint8 au8SSID[M2M_MAX_SSID_LEN]; + /*!< SSID obtained from WPS. + */ + uint8 au8PSK[M2M_MAX_PSK_LEN]; + /*!< PSK for the network obtained from WPS. + */ +}tstrM2MWPSInfo; + + +/*! +@struct \ + tstrM2MDefaultConnResp + +@brief + Response error of the m2m_default_connect + +@sa + M2M_DEFAULT_CONN_SCAN_MISMATCH + M2M_DEFAULT_CONN_EMPTY_LIST +*/ +typedef struct{ + sint8 s8ErrorCode; + /*!< + Default connect error code. possible values are: + - M2M_DEFAULT_CONN_EMPTY_LIST + - M2M_DEFAULT_CONN_SCAN_MISMATCH + */ + uint8 __PAD24__[3]; +}tstrM2MDefaultConnResp; + +/*! +@struct \ + tstrM2MScanOption + +@brief + Scan options and configurations. + +@sa + tenuM2mScanCh + tstrM2MScan +*/ +typedef struct { + uint8 u8NumOfSlot; + /*|< The min number of slots is 2 for every channel, + every slot the soc will send Probe Request on air, and wait/listen for PROBE RESP/BEACONS for the u16slotTime + */ + uint8 u8SlotTime; + /*|< the time that the Soc will wait on every channel listening to the frames on air + when that time increaseed number of AP will increased in the scan results + min time is 10 ms and the max is 250 ms + */ + uint8 u8ProbesPerSlot; + /*!< Number of probe requests to be sent per channel scan slot. + */ + sint8 s8RssiThresh; + /*! < The RSSI threshold of the AP which will be connected to directly. + */ + +}tstrM2MScanOption; + +/*! +@struct \ + tstrM2MScanRegion + +@brief + Wi-Fi channel regulation region information. + +@sa + tenuM2mScanRegion +*/ +typedef struct { + uint16 u16ScanRegion; + /*|< Specifies the number of channels allowed in the region (e.g. North America = 11 ... etc.). + */ + uint8 __PAD16__[2]; + +}tstrM2MScanRegion; + +/*! +@struct \ + tstrM2MScan + +@brief + Wi-Fi Scan Request + +@sa + tenuM2mScanCh + tstrM2MScanOption +*/ +typedef struct { + uint8 u8ChNum; + /*!< The Wi-Fi RF Channel number + */ + uint8 __RSVD8__[1]; + /*!< Reserved for future use. + */ + uint16 u16PassiveScanTime; + /*!< Passive Scan Timeout in ms. The field is ignored for active scan. + */ +}tstrM2MScan; + +/*! +@struct \ + tstrCyptoResp + +@brief + crypto response +*/ +typedef struct { + sint8 s8Resp; + /***/ + uint8 __PAD24__[3]; + /* + */ +}tstrCyptoResp; + + +/*! +@struct \ + tstrM2mScanDone + +@brief + Wi-Fi Scan Result +*/ +typedef struct{ + uint8 u8NumofCh; + /*!< Number of found APs + */ + sint8 s8ScanState; + /*!< Scan status + */ + uint8 __PAD16__[2]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mScanDone; + + +/*! +@struct \ + tstrM2mReqScanResult + +@brief Scan Result Request + + The Wi-Fi Scan results list is stored in Firmware. The application can request a certain scan result by its index. +*/ +typedef struct { + uint8 u8Index; + /*!< Index of the desired scan result + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mReqScanResult; + + +/*! +@struct \ + tstrM2mWifiscanResult + +@brief Wi-Fi Scan Result + + Information corresponding to an AP in the Scan Result list identified by its order (index) in the list. +*/ +typedef struct { + uint8 u8index; + /*!< AP index in the scan result list. + */ + sint8 s8rssi; + /*!< AP signal strength. + */ + uint8 u8AuthType; + /*!< AP authentication type. + */ + uint8 u8ch; + /*!< AP RF channel. + */ + uint8 au8BSSID[6]; + /*!< BSSID of the AP. + */ + uint8 au8SSID[M2M_MAX_SSID_LEN]; + /*!< AP ssid. + */ + uint8 _PAD8_; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mWifiscanResult; + + +/*! +@struct \ + tstrM2mWifiStateChanged + +@brief + Wi-Fi Connection State + +@sa + M2M_WIFI_DISCONNECTED, M2M_WIFI_CONNECTED, M2M_WIFI_REQ_CON_STATE_CHANGED,tenuM2mConnChangedErrcode +*/ +typedef struct { + uint8 u8CurrState; + /*!< Current Wi-Fi connection state + */ + uint8 u8ErrCode; + /*!< Error type review tenuM2mConnChangedErrcode + */ + uint8 __PAD16__[2]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mWifiStateChanged; + + +/*! +@struct \ + tstrM2mPsType + +@brief + Power Save Configuration + +@sa + tenuPowerSaveModes +*/ +typedef struct{ + uint8 u8PsType; + /*!< Power save operating mode + */ + uint8 u8BcastEn; + /*!< + */ + uint8 __PAD16__[2]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mPsType; + +/*! +@struct \ + tstrM2mSlpReqTime + +@brief + Manual power save request sleep time + +*/ +typedef struct { + /*!< Sleep time in ms + */ + uint32 u32SleepTime; + +} tstrM2mSlpReqTime; + +/*! +@struct \ + tstrM2mLsnInt + +@brief Listen interval + + It is the value of the Wi-Fi STA listen interval for power saving. It is given in units of Beacon period. + Periodically after the listen interval fires, the WINC is wakeup and listen to the beacon and check for any buffered frames for it from the AP. +*/ +typedef struct { + uint16 u16LsnInt; + /*!< Listen interval in Beacon period count. + */ + uint8 __PAD16__[2]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mLsnInt; + + +/*! +@struct \ + tstrM2MWifiMonitorModeCtrl + +@brief Wi-Fi Monitor Mode Filter + + This structure sets the filtering criteria for WLAN packets when monitoring mode is enable. + The received packets matching the filtering parameters, are passed directly to the application. +*/ +typedef struct{ + uint8 u8ChannelID; + /* !< RF Channel ID. It must use values from tenuM2mScanCh + */ + uint8 u8FrameType; + /*!< It must use values from tenuWifiFrameType. + */ + uint8 u8FrameSubtype; + /*!< It must use values from tenuSubTypes. + */ + uint8 au8SrcMacAddress[6]; + /* ZERO means DO NOT FILTER Source address. + */ + uint8 au8DstMacAddress[6]; + /* ZERO means DO NOT FILTER Destination address. + */ + uint8 au8BSSID[6]; + /* ZERO means DO NOT FILTER BSSID. + */ + uint8 u8EnRecvHdr; + /* + Enable recv the full hder before the payload + */ + uint8 __PAD16__[2]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2MWifiMonitorModeCtrl; + + +/*! +@struct \ + tstrM2MWifiRxPacketInfo + +@brief Wi-Fi RX Frame Header + + The M2M application has the ability to allow Wi-Fi monitoring mode for receiving all Wi-Fi Raw frames matching a well defined filtering criteria. + When a target Wi-Fi packet is received, the header information are extracted and assigned in this structure. +*/ +typedef struct{ + uint8 u8FrameType; + /*!< It must use values from tenuWifiFrameType. + */ + uint8 u8FrameSubtype; + /*!< It must use values from tenuSubTypes. + */ + uint8 u8ServiceClass; + /*!< Service class from Wi-Fi header. + */ + uint8 u8Priority; + /*!< Priority from Wi-Fi header. + */ + uint8 u8HeaderLength; + /*!< Frame Header length. + */ + uint8 u8CipherType; + /*!< Encryption type for the rx packet. + */ + uint8 au8SrcMacAddress[6]; + /* ZERO means DO NOT FILTER Source address. + */ + uint8 au8DstMacAddress[6]; + /* ZERO means DO NOT FILTER Destination address. + */ + uint8 au8BSSID[6]; + /* ZERO means DO NOT FILTER BSSID. + */ + uint16 u16DataLength; + /*!< Data payload length (Header excluded). + */ + uint16 u16FrameLength; + /*!< Total frame length (Header + Data). + */ + uint32 u32DataRateKbps; + /*!< Data Rate in Kbps. + */ + sint8 s8RSSI; + /*!< RSSI. + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2MWifiRxPacketInfo; + + +/*! +@struct \ + tstrM2MWifiTxPacketInfo + +@brief Wi-Fi TX Packet Info + + The M2M Application has the ability to compose a RAW Wi-Fi frames (under the application responsibility). + When transmitting a Wi-Fi packet, the application must supply the firmware with this structure for sending the target frame. +*/ +typedef struct{ + uint16 u16PacketSize; + /*!< Wlan frame length. + */ + uint16 u16HeaderLength; + /*!< Wlan frame header length. + */ +}tstrM2MWifiTxPacketInfo; + + +/*! + @struct \ + tstrM2MP2PConnect + + @brief + Set the device to operate in the Wi-Fi Direct (P2P) mode. +*/ +typedef struct { + uint8 u8ListenChannel; + /*!< P2P Listen Channel (1, 6 or 11) + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2MP2PConnect; + +/*! +@struct \ + tstrM2MAPConfig + +@brief AP Configuration + + This structure holds the configuration parameters for the M2M AP mode. It should be set by the application when + it requests to enable the M2M AP operation mode. The M2M AP mode currently supports only WEP security (with + the NO Security option available of course). +*/ +typedef struct { + /*!< + Configuration parameters for the WiFi AP. + */ + uint8 au8SSID[M2M_MAX_SSID_LEN]; + /*!< AP SSID + */ + uint8 u8ListenChannel; + /*!< Wi-Fi RF Channel which the AP will operate on + */ + uint8 u8KeyIndx; + /*!< Wep key Index + */ + uint8 u8KeySz; + /*!< Wep/WPA key Size + */ + uint8 au8WepKey[WEP_104_KEY_STRING_SIZE + 1]; + /*!< Wep key + */ + uint8 u8SecType; + /*!< Security type: Open or WEP or WPA in the current implementation + */ + uint8 u8SsidHide; + /*!< SSID Status "Hidden(1)/Visible(0)" + */ + uint8 au8DHCPServerIP[4]; + /*!< Ap IP server address + */ + uint8 au8Key[M2M_MAX_PSK_LEN]; + /*!< WPA key + */ + uint8 __PAD24__[2]; + /*!< Padding bytes for forcing alignment + */ +}tstrM2MAPConfig; + + +/*! +@struct \ + tstrM2mServerInit + +@brief + PS Server initialization. +*/ +typedef struct { + uint8 u8Channel; + /*!< Server Listen channel + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mServerInit; + + +/*! +@struct \ + tstrM2mClientState + +@brief + PS Client State. +*/ +typedef struct { + uint8 u8State; + /*!< PS Client State + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mClientState; + + +/*! +@struct \ + tstrM2Mservercmd + +@brief + PS Server CMD +*/ +typedef struct { + uint8 u8cmd; + /*!< PS Server Cmd + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2Mservercmd; + + +/*! +@struct \ + tstrM2mSetMacAddress + +@brief + Sets the MAC address from application. The WINC load the mac address from the effuse by default to the WINC configuration memory, + but that function is used to let the application overwrite the configuration memory with the mac address from the host. + +@note + It's recommended to call this only once before calling connect request and after the m2m_wifi_init +*/ +typedef struct { + uint8 au8Mac[6]; + /*!< MAC address array + */ + uint8 __PAD16__[2]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mSetMacAddress; + + +/*! +@struct \ + tstrM2MDeviceNameConfig + +@brief Device name + + It is assigned by the application. It is used mainly for Wi-Fi Direct device + discovery and WPS device information. +*/ +typedef struct { + uint8 au8DeviceName[M2M_DEVICE_NAME_MAX]; + /*!< NULL terminated device name + */ +}tstrM2MDeviceNameConfig; + + +/*! +@struct \ + tstrM2MIPConfig + +@brief + Static IP configuration. + +@note + All member IP addresses are expressed in Network Byte Order (eg. "192.168.10.1" will be expressed as 0x010AA8C0). + */ +typedef struct { + uint32 u32StaticIP; + /*!< The static IP assigned to the device. + */ + uint32 u32Gateway; + /*!< IP of the Default internet gateway. + */ + uint32 u32DNS; + /*!< IP for the DNS server. + */ + uint32 u32SubnetMask; + /*!< Subnet mask for the local area network. + */ + uint32 u32DhcpLeaseTime; + /*!< Dhcp Lease Time in sec + */ +} tstrM2MIPConfig; + +/*! +@struct \ + tstrM2mIpRsvdPkt + +@brief + Received Packet Size and Data Offset + + */ +typedef struct{ + uint16 u16PktSz; + uint16 u16PktOffset; +} tstrM2mIpRsvdPkt; + + +/*! +@struct \ + tstrM2MProvisionModeConfig + +@brief + M2M Provisioning Mode Configuration + */ + +typedef struct { + tstrM2MAPConfig strApConfig; + /*!< + Configuration parameters for the WiFi AP. + */ + char acHttpServerDomainName[64]; + /*!< + The device domain name for HTTP provisioning. + */ + uint8 u8EnableRedirect; + /*!< + A flag to enable/disable HTTP redirect feature for the HTTP Provisioning server. If the Redirect is enabled, + all HTTP traffic (http://URL) from the device associated with WINC AP will be redirected to the HTTP Provisioning Web page. + - 0 : Disable HTTP Redirect. + - 1 : Enable HTTP Redirect. + */ + uint8 __PAD24__[3]; +}tstrM2MProvisionModeConfig; + + +/*! +@struct \ + tstrM2MProvisionInfo + +@brief + M2M Provisioning Information obtained from the HTTP Provisioning server. + */ +typedef struct{ + uint8 au8SSID[M2M_MAX_SSID_LEN]; + /*!< + Provisioned SSID. + */ + uint8 au8Password[M2M_MAX_PSK_LEN]; + /*!< + Provisioned Password. + */ + uint8 u8SecType; + /*!< + Wifi Security type. + */ + uint8 u8Status; + /*!< + Provisioning status. It must be checked before reading the provisioning information. It may be + - M2M_SUCCESS : Provision successful. + - M2M_FAIL : Provision Failed. + */ +}tstrM2MProvisionInfo; + + +/*! +@struct \ + tstrM2MConnInfo + +@brief + M2M Provisioning Information obtained from the HTTP Provisioning server. + */ +typedef struct{ + char acSSID[M2M_MAX_SSID_LEN]; + /*!< AP connection SSID name */ + uint8 u8SecType; + /*!< Security type */ + uint8 au8IPAddr[4]; + /*!< Connection IP address */ + uint8 au8MACAddress[6]; + /*!< MAC address of the peer Wi-Fi station */ + sint8 s8RSSI; + /*!< Connection RSSI signal */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment */ +}tstrM2MConnInfo; + +/*! +@struct \ + tstrOtaInitHdr + +@brief + OTA Image Header + */ + +typedef struct{ + uint32 u32OtaMagicValue; + /*!< Magic value kept in the OTA image after the + sha256 Digest buffer to define the Start of OTA Header */ + uint32 u32OtaPayloadSzie; + /*!< + The Total OTA image payload size, include the sha256 key size + */ + +}tstrOtaInitHdr; + + +/*! +@struct \ + tstrOtaControlSec + +@brief + Control section structure is used to define the working image and + the validity of the roll-back image and its offset, also both firmware versions is kept in that structure. + */ + +typedef struct { + uint32 u32OtaMagicValue; +/*!< + Magic value used to ensure the structure is valid or not +*/ + uint32 u32OtaFormatVersion; +/*!< + NA NA NA Flash version cs struct version + 00 00 00 00 00 + Control structure format version, the value will be incremented in case of structure changed or updated +*/ + uint32 u32OtaSequenceNumber; +/*!< + Sequence number is used while update the control structure to keep track of how many times that section updated +*/ + uint32 u32OtaLastCheckTime; +/*!< + Last time OTA check for update +*/ + uint32 u32OtaCurrentworkingImagOffset; +/*!< + Current working offset in flash +*/ + uint32 u32OtaCurrentworkingImagFirmwareVer; +/*!< + current working image version ex 18.0.1 +*/ + uint32 u32OtaRollbackImageOffset; +/*!< + Roll-back image offset in flash +*/ + uint32 u32OtaRollbackImageValidStatus; +/*!< + roll-back image valid status +*/ + uint32 u32OtaRollbackImagFirmwareVer; +/*!< + Roll-back image version (ex 18.0.3) +*/ + uint32 u32OtaCortusAppWorkingOffset; +/*!< + cortus app working offset in flash +*/ + uint32 u32OtaCortusAppWorkingValidSts; +/*!< + Working Cortus app valid status +*/ + uint32 u32OtaCortusAppWorkingVer; +/*!< + Working cortus app version (ex 18.0.3) +*/ + uint32 u32OtaCortusAppRollbackOffset; +/*!< + cortus app rollback offset in flash +*/ + uint32 u32OtaCortusAppRollbackValidSts; +/*!< + roll-back cortus app valid status +*/ + uint32 u32OtaCortusAppRollbackVer; +/*!< + Roll-back cortus app version (ex 18.0.3) +*/ + uint32 u32OtaControlSecCrc; +/*!< + CRC for the control structure to ensure validity +*/ +} tstrOtaControlSec; + +/*! +@enum \ + tenuOtaUpdateStatus + +@brief + OTA return status +*/ +typedef enum { + OTA_STATUS_SUCSESS = 0, + /*!< OTA Success with not errors. */ + OTA_STATUS_FAIL = 1, + /*!< OTA generic fail. */ + OTA_STATUS_INVAILD_ARG = 2, + /*!< Invalid or malformed download URL. */ + OTA_STATUS_INVAILD_RB_IMAGE = 3, + /*!< Invalid rollback image. */ + OTA_STATUS_INVAILD_FLASH_SIZE = 4, + /*!< Flash size on device is not enough for OTA. */ + OTA_STATUS_AlREADY_ENABLED = 5, + /*!< An OTA operation is already enabled. */ + OTA_STATUS_UPDATE_INPROGRESS = 6, + /*!< An OTA operation update is in progress */ + OTA_STATUS_IMAGE_VERIF_FAILED = 7, + /*!< OTA Verfication failed */ + OTA_STATUS_CONNECTION_ERROR = 8, + /*!< OTA connection error */ + OTA_STATUS_SERVER_ERROR = 9, + /*!< OTA server Error (file not found or else ...) */ + OTA_STATUS_ABORTED = 10 + /*!< OTA download has been aborted by the application. */ +} tenuOtaUpdateStatus; +/*! +@enum \ + tenuOtaUpdateStatusType + +@brief + OTA update Status type +*/ +typedef enum { + + DL_STATUS = 1, + /*!< Download OTA file status + */ + SW_STATUS = 2, + /*!< Switching to the upgrade firmware status + */ + RB_STATUS = 3, + /*!< Roll-back status + */ + AB_STATUS = 4 + /*!< Abort status + */ +}tenuOtaUpdateStatusType; + + +/*! +@struct \ + tstrOtaUpdateStatusResp + +@brief + OTA Update Information + +@sa + tenuWPSTrigger +*/ +typedef struct { + uint8 u8OtaUpdateStatusType; + /*!< + Status type tenuOtaUpdateStatusType + */ + uint8 u8OtaUpdateStatus; + /*!< + OTA_SUCCESS + OTA_ERR_WORKING_IMAGE_LOAD_FAIL + OTA_ERR_INVAILD_CONTROL_SEC + M2M_ERR_OTA_SWITCH_FAIL + M2M_ERR_OTA_START_UPDATE_FAIL + M2M_ERR_OTA_ROLLBACK_FAIL + M2M_ERR_OTA_INVAILD_FLASH_SIZE + M2M_ERR_OTA_INVAILD_ARG + */ + uint8 _PAD16_[2]; +}tstrOtaUpdateStatusResp; + +/*! +@struct \ + tstrOtaUpdateInfo + +@brief + OTA Update Information + +@sa + tenuWPSTrigger +*/ +typedef struct { + uint32 u8NcfUpgradeVersion; + /*!< NCF OTA Upgrade Version + */ + uint32 u8NcfCurrentVersion; + /*!< NCF OTA Current firmware version + */ + uint32 u8NcdUpgradeVersion; + /*!< NCD (host) upgraded version (if the u8NcdRequiredUpgrade == true) + */ + uint8 u8NcdRequiredUpgrade; + /*!< NCD Required upgrade to the above version + */ + uint8 u8DownloadUrlOffset; + /*!< Download URL offset in the received packet + */ + uint8 u8DownloadUrlSize; + /*!< Download URL size in the received packet + */ + uint8 __PAD8__; + /*!< Padding bytes for forcing 4-byte alignment + */ +} tstrOtaUpdateInfo; + +/*! +@struct \ + tstrSystemTime + +@brief + Used for time storage. +*/ +typedef struct{ + uint16 u16Year; + uint8 u8Month; + uint8 u8Day; + uint8 u8Hour; + uint8 u8Minute; + uint8 u8Second; + uint8 __PAD8__; +}tstrSystemTime; + +/*! +@struct \ + tstrM2MMulticastMac + +@brief + M2M add/remove multi-cast mac address + */ + typedef struct { + uint8 au8macaddress[M2M_MAC_ADDRES_LEN]; + /*!< + Mac address needed to be added or removed from filter. + */ + uint8 u8AddRemove; + /*!< + set by 1 to add or 0 to remove from filter. + */ + uint8 __PAD8__; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2MMulticastMac; + +/*! +@struct \ + tstrPrng + +@brief + M2M Request PRNG + */ + typedef struct { + /*!< + return buffer address + */ + uint8 *pu8RngBuff; + /*!< + PRNG size requested + */ + uint16 u16PrngSize; + /*!< + PRNG pads + */ + uint8 __PAD16__[2]; +}tstrPrng; + +/* + * TLS certificate revocation list + * Typedefs common between fw and host + */ + +/*! +@struct \ + tstrTlsCrlEntry + +@brief + Certificate data for inclusion in a revocation list (CRL) +*/ +typedef struct { + uint8 u8DataLen; + /*!< + Length of certificate data (maximum possible is @ref TLS_CRL_DATA_MAX_LEN) + */ + uint8 au8Data[TLS_CRL_DATA_MAX_LEN]; + /*!< + Certificate data + */ + uint8 __PAD24__[3]; + /*!< + Padding bytes for forcing 4-byte alignment + */ +}tstrTlsCrlEntry; + +/*! +@struct \ + tstrTlsCrlInfo + +@brief + Certificate revocation list details +*/ +typedef struct { + uint8 u8CrlType; + /*!< + Type of certificate data contained in list + */ + uint8 u8Rsv1; + /*!< + Reserved for future use + */ + uint8 u8Rsv2; + /*!< + Reserved for future use + */ + uint8 u8Rsv3; + /*!< + Reserved for future use + */ + tstrTlsCrlEntry astrTlsCrl[TLS_CRL_MAX_ENTRIES]; + /*!< + List entries + */ +}tstrTlsCrlInfo; + + /*! +@enum\ + tenuSslCertExpSettings + +@brief SSL Certificate Expiry Validation Options +*/ +typedef enum{ + SSL_CERT_EXP_CHECK_DISABLE, + /*!< + ALWAYS OFF. + Ignore certificate expiration date validation. If a certificate is + expired or there is no configured system time, the SSL connection SUCCEEDs. + */ + SSL_CERT_EXP_CHECK_ENABLE, + /*!< + ALWAYS ON. + Validate certificate expiration date. If a certificate is expired or + there is no configured system time, the SSL connection FAILs. + */ + SSL_CERT_EXP_CHECK_EN_IF_SYS_TIME + /*!< + CONDITIONAL VALIDATION (Default setting at startup). + Validate the certificate expiration date only if there is a configured system time. + If there is no configured system time, the certificate expiration is bypassed and the + SSL connection SUCCEEDs. + */ +}tenuSslCertExpSettings; + + +/*! +@struct \ + tstrTlsSrvSecFileEntry + +@brief + This struct contains a TLS certificate. + */ +typedef struct{ + char acFileName[TLS_FILE_NAME_MAX]; + /*!< Name of the certificate. */ + uint32 u32FileSize; + /*!< Size of the certificate. */ + uint32 u32FileAddr; + /*!< Error Code. */ +}tstrTlsSrvSecFileEntry; + +/*! +@struct \ + tstrTlsSrvSecHdr + +@brief + This struct contains a set of TLS certificates. + */ +typedef struct{ + uint8 au8SecStartPattern[TLS_SRV_SEC_START_PATTERN_LEN]; + /*!< Start pattern. */ + uint32 u32nEntries; + /*!< Number of certificates stored in the struct. */ + uint32 u32NextWriteAddr; + /*!< TLS Certificates. */ + tstrTlsSrvSecFileEntry astrEntries[TLS_SRV_SEC_MAX_FILES]; +}tstrTlsSrvSecHdr; + +typedef struct{ + uint32 u32CsBMP; +}tstrSslSetActiveCsList; + + + /**@}*/ + +#endif diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_wifi.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_wifi.h new file mode 100644 index 0000000..3477196 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_wifi.h @@ -0,0 +1,2882 @@ +/** + * + * \file + * + * \brief WINC WLAN Application Interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef __M2M_WIFI_H__ +#define __M2M_WIFI_H__ + +/** \defgroup m2m_wifi WLAN + * + */ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "common/include/nm_common.h" +#include "driver/include/m2m_types.h" +#include "driver/source/nmdrv.h" + +#ifdef CONF_MGMT + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/**@defgroup WlanEnums DataTypes + * @ingroup m2m_wifi + * @{*/ +/*! +@enum \ + tenuWifiFrameType + +@brief + Enumeration for Wi-Fi MAC frame type codes (2-bit) + The following types are used to identify the type of frame sent or received. + Each frame type constitutes a number of frame subtypes as defined in @ref tenuSubTypes to specify the exact type of frame. + Values are defined as per the IEEE 802.11 standard. + +@remarks + The following frame types are useful for advanced user usage when monitoring mode is used (defining @ref CONF_MGMT) + and the user application requires to monitor the frame transmission and reception. +@see + tenuSubTypes +*/ +typedef enum { + MANAGEMENT = 0x00, + /*!< Wi-Fi Management frame (Probe Req/Resp, Beacon, Association Req/Resp ...etc). + */ + CONTROL = 0x04, + /*!< Wi-Fi Control frame (eg. ACK frame). + */ + DATA_BASICTYPE = 0x08, + /*!< Wi-Fi Data frame. + */ + RESERVED = 0x0C, + + M2M_WIFI_FRAME_TYPE_ANY = 0xFF +/*!< Set monitor mode to receive any of the frames types +*/ +}tenuWifiFrameType; + + +/*! +@enum \ + tenuSubTypes + +@brief + Enumeration for Wi-Fi MAC Frame subtype code (6-bit). + The frame subtypes fall into one of the three frame type groups as defined in @ref tenuWifiFrameType + (MANAGEMENT, CONTROL & DATA). + Values are defined as per the IEEE 802.11 standard. +@remarks + The following sub-frame types are useful for advanced user usage when @ref CONF_MGMT is defined + and the application developer requires to monitor the frame transmission and reception. +@see + tenuWifiFrameType + tstrM2MWifiMonitorModeCtrl +*/ +typedef enum { + /*!< Sub-Types related to Management Sub-Types */ + ASSOC_REQ = 0x00, + ASSOC_RSP = 0x10, + REASSOC_REQ = 0x20, + REASSOC_RSP = 0x30, + PROBE_REQ = 0x40, + PROBE_RSP = 0x50, + BEACON = 0x80, + ATIM = 0x90, + DISASOC = 0xA0, + AUTH = 0xB0, + DEAUTH = 0xC0, + ACTION = 0xD0, +/**@{*/ + /* Sub-Types related to Control */ + PS_POLL = 0xA4, + RTS = 0xB4, + CTS = 0xC4, + ACK = 0xD4, + CFEND = 0xE4, + CFEND_ACK = 0xF4, + BLOCKACK_REQ = 0x84, + BLOCKACK = 0x94, +/**@{*/ + /* Sub-Types related to Data */ + DATA = 0x08, + DATA_ACK = 0x18, + DATA_POLL = 0x28, + DATA_POLL_ACK = 0x38, + NULL_FRAME = 0x48, + CFACK = 0x58, + CFPOLL = 0x68, + CFPOLL_ACK = 0x78, + QOS_DATA = 0x88, + QOS_DATA_ACK = 0x98, + QOS_DATA_POLL = 0xA8, + QOS_DATA_POLL_ACK = 0xB8, + QOS_NULL_FRAME = 0xC8, + QOS_CFPOLL = 0xE8, + QOS_CFPOLL_ACK = 0xF8, + M2M_WIFI_FRAME_SUB_TYPE_ANY = 0xFF + /*!< Set monitor mode to receive any of the frames types + */ +}tenuSubTypes; + + +/*! +@enum \ + tenuInfoElementId + +@brief + Enumeration for the Wi-Fi Information Element(IE) IDs, which indicates the specific type of IEs. + IEs are management frame information included in management frames. + Values are defined as per the IEEE 802.11 standard. + +*/ +typedef enum { + ISSID = 0, + /*!< Service Set Identifier (SSID) + */ + ISUPRATES = 1, + /*!< Supported Rates + */ + IFHPARMS = 2, + /*!< FH parameter set + */ + IDSPARMS = 3, + /*!< DS parameter set + */ + ICFPARMS = 4, + /*!< CF parameter set + */ + ITIM = 5, + /*!< Traffic Information Map + */ + IIBPARMS = 6, + /*!< IBSS parameter set + */ + ICOUNTRY = 7, + /*!< Country element. + */ + IEDCAPARAMS = 12, + /*!< EDCA parameter set + */ + ITSPEC = 13, + /*!< Traffic Specification + */ + ITCLAS = 14, + /*!< Traffic Classification + */ + ISCHED = 15, + /*!< Schedule. + */ + ICTEXT = 16, + /*!< Challenge Text + */ + IPOWERCONSTRAINT = 32, + /*!< Power Constraint. + */ + IPOWERCAPABILITY = 33, + /*!< Power Capability + */ + ITPCREQUEST = 34, + /*!< TPC Request + */ + ITPCREPORT = 35, + /*!< TPC Report + */ + ISUPCHANNEL = 36, + /* Supported channel list + */ + ICHSWANNOUNC = 37, + /*!< Channel Switch Announcement + */ + IMEASUREMENTREQUEST = 38, + /*!< Measurement request + */ + IMEASUREMENTREPORT = 39, + /*!< Measurement report + */ + IQUIET = 40, + /*!< Quiet element Info + */ + IIBSSDFS = 41, + /*!< IBSS DFS + */ + IERPINFO = 42, + /*!< ERP Information + */ + ITSDELAY = 43, + /*!< TS Delay + */ + ITCLASPROCESS = 44, + /*!< TCLAS Processing + */ + IHTCAP = 45, + /*!< HT Capabilities + */ + IQOSCAP = 46, + /*!< QoS Capability + */ + IRSNELEMENT = 48, + /*!< RSN Information Element + */ + IEXSUPRATES = 50, + /*!< Extended Supported Rates + */ + IEXCHSWANNOUNC = 60, + /*!< Extended Ch Switch Announcement + */ + IHTOPERATION = 61, + /*!< HT Information + */ + ISECCHOFF = 62, + /*!< Secondary Channel Offset + */ + I2040COEX = 72, + /*!< 20/40 Coexistence IE + */ + I2040INTOLCHREPORT = 73, + /*!< 20/40 Intolerant channel report + */ + IOBSSSCAN = 74, + /*!< OBSS Scan parameters + */ + IEXTCAP = 127, + /*!< Extended capability + */ + IWMM = 221, + /*!< WMM parameters + */ + IWPAELEMENT = 221 + /*!< WPA Information Element + */ +}tenuInfoElementId; + + +/*! +@struct \ + tenuWifiCapability + +@brief + Enumeration for capability Information field bit. + The value of the capability information field from the 802.11 management frames received by the wireless LAN interface. + Defining the capabilities of the Wi-Fi system. Values are defined as per the IEEE 802.11 standard. + +@details + Capabilities:- + ESS/IBSS : Defines whether a frame is coming from an AP or not. + POLLABLE : CF Poll-able + POLLREQ : Request to be polled + PRIVACY : WEP encryption supported + SHORTPREAMBLE : Short Preamble is supported + SHORTSLOT : Short Slot is supported + PBCC :PBCC + CHANNELAGILITY :Channel Agility + SPECTRUM_MGMT :Spectrum Management + DSSS_OFDM : DSSS-OFDM +*/ +typedef enum{ + ESS = 0x01, + /*!< ESS capability + */ + IBSS = 0x02, + /*!< IBSS mode + */ + POLLABLE = 0x04, + /*!< CF Pollable + */ + POLLREQ = 0x08, + /*!< Request to be polled + */ + PRIVACY = 0x10, + /*!< WEP encryption supported + */ + SHORTPREAMBLE = 0x20, + /*!< Short Preamble is supported + */ + SHORTSLOT = 0x400, + /*!< Short Slot is supported + */ + PBCC = 0x40, + /*!< PBCC + */ + CHANNELAGILITY = 0x80, + /*!< Channel Agility + */ + SPECTRUM_MGMT = 0x100, + /*!< Spectrum Management + */ + DSSS_OFDM = 0x2000 + /*!< DSSS-OFDM + */ +}tenuWifiCapability; + + +#endif + +/*! +@typedef \ + tpfAppWifiCb + +@brief + Wi-Fi's main callback function handler, for handling the M2M_WIFI events received on the Wi-Fi interface. + Such notifications are received in response to Wi-Fi/P2P operations such as @ref m2m_wifi_request_scan, + @ref m2m_wifi_connect. + Wi-Fi/P2P operations are implemented in an asynchronous mode, and all incoming information/status + are to be handled through this callback function when the corresponding notification is received. + Applications are expected to assign this wi-fi callback function by calling @ref m2m_wifi_init +@param [in] u8MsgType + Type of notifications. Possible types are: + /ref M2M_WIFI_RESP_CON_STATE_CHANGED + /ref M2M_WIFI_RESP_CONN_INFO + /ref M2M_WIFI_REQ_DHCP_CONF + /ref M2M_WIFI_REQ_WPS + /ref M2M_WIFI_RESP_IP_CONFLICT + /ref M2M_WIFI_RESP_SCAN_DONE + /ref M2M_WIFI_RESP_SCAN_RESULT + /ref M2M_WIFI_RESP_CURRENT_RSSI + /ref M2M_WIFI_RESP_CLIENT_INFO + /ref M2M_WIFI_RESP_PROVISION_INFO + /ref M2M_WIFI_RESP_DEFAULT_CONNECT + + In case Ethernet/Bypass mode is defined : + @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET + + In case monitoring mode is used: + @ref M2M_WIFI_RESP_WIFI_RX_PACKET + +@param [in] pvMsg + A pointer to a buffer containing the notification parameters (if any). It should be + casted to the correct data type corresponding to the notification type. + +@see + tstrM2mWifiStateChanged + tstrM2MWPSInfo + tstrM2mScanDone + tstrM2mWifiscanResult +*/ +typedef void (*tpfAppWifiCb) (uint8 u8MsgType, void * pvMsg); + +/*! +@typedef \ + tpfAppEthCb + +@brief + ETHERNET (bypass mode) notification callback function receiving Bypass mode events as defined in + the Wi-Fi responses enumeration @ref tenuM2mStaCmd. + +@param [in] u8MsgType + Type of notification. Possible types are: + - [M2M_WIFI_RESP_ETHERNET_RX_PACKET](@ref M2M_WIFI_RESP_ETHERNET_RX_PACKET) + +@param [in] pvMsg + A pointer to a buffer containing the notification parameters (if any). It should be + casted to the correct data type corresponding to the notification type. + For example, it could be a pointer to the buffer holding the received frame in case of @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET + event. + +@param [in] pvControlBuf + A pointer to control buffer describing the accompanied message. + To be casted to @ref tstrM2mIpCtrlBuf in case of @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET event. + +@warning + Make sure that the application defines @ref ETH_MODE. + +@see + m2m_wifi_init + +*/ +typedef void (*tpfAppEthCb) (uint8 u8MsgType, void * pvMsg,void * pvCtrlBuf); + +/*! +@typedef \ + tpfAppMonCb + +@brief + Wi-Fi monitoring mode callback function. This function delivers all received wi-Fi packets through the Wi-Fi interface. + Applications requiring to operate in the monitoring should call the asynchronous function m2m_wifi_enable_monitoring_mode + and expect to receive the Wi-Fi packets through this callback function, when the event is received. + To disable the monitoring mode a call to @ref m2m_wifi_disable_monitoring_mode should be made. +@param [in] pstrWifiRxPacket + Pointer to a structure holding the Wi-Fi packet header parameters. + +@param [in] pu8Payload + Pointer to the buffer holding the Wi-Fi packet payload information required by the application starting from the + defined OFFSET by the application (when calling m2m_wifi_enable_monitoring_mode). + Could hold a value of NULL, if the application does not need any data from the payload. + +@param [in] u16PayloadSize + The size of the payload in bytes. + +@see + m2m_wifi_enable_monitoring_mode,m2m_wifi_init + +@warning + u16PayloadSize should not exceed the buffer size given through m2m_wifi_enable_monitoring_mode. + +*/ +typedef void (*tpfAppMonCb) (tstrM2MWifiRxPacketInfo *pstrWifiRxPacket, uint8 * pu8Payload, uint16 u16PayloadSize); + +/** +@struct \ + tstrEthInitParam + +@brief + Structure to hold Ethernet interface parameters. + Structure is to be defined and have its attributes set,based on the application's functionality before + a call is made to initialize the Wi-Fi operations by calling the @ref m2m_wifi_init function. + This structure is part of the Wi-Fi configuration structure @ref tstrWifiInitParam. + Applications shouldn't need to define this structure, if the bypass mode is not defined. + +@see + tpfAppEthCb + tpfAppWifiCb + m2m_wifi_init + +@warning + Make sure that application defines @ref ETH_MODE before using @ref tstrEthInitParam. + +*/ +typedef struct { + tpfAppWifiCb pfAppWifiCb; + /*!< + Callback for wifi notifications. + */ + tpfAppEthCb pfAppEthCb; + /*!< + Callback for Ethernet interface. + */ + uint8 * au8ethRcvBuf; + /*!< + Pointer to Receive Buffer of Ethernet Packet + */ + uint16 u16ethRcvBufSize; + /*!< + Size of Receive Buffer for Ethernet Packet + */ + uint8 u8EthernetEnable; + /*!< + Enable Ethernet mode flag + */ + uint8 __PAD8__; + /*!< + Padding + */ +} tstrEthInitParam; +/*! +@struct \ + tstrM2mIpCtrlBuf + +@brief + Structure holding the incoming buffer's data size information, indicating the data size of the buffer and the remaining buffer's data size . + The data of the buffer which holds the packet sent to the host when in the bypass mode, is placed in the @ref tstrEthInitParam structure in the + @ref au8ethRcvBuf attribute. This following information is retrieved in the host when an event @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET is received in + the Wi-Fi callback function @ref tpfAppWifiCb. + + The application is expected to use this structure's information to determine if there is still incoming data to be received from the firmware. + + @see + tpfAppEthCb + tstrEthInitParam + + @warning + Make sure that ETHERNET/bypass mode is defined before using @ref tstrM2mIpCtrlBuf + + */ +typedef struct{ + uint16 u16DataSize; + /*!< + Size of the received data in bytes. + */ + uint16 u16RemainigDataSize; + /*!< + Size of the remaining data bytes to be delivered to host. + */ +} tstrM2mIpCtrlBuf; + + +/** +@struct \ + tstrWifiInitParam + +@brief + Structure, holding the Wi-fi configuration attributes such as the wi-fi callback , monitoring mode callback and Ethernet parameter initialization structure. + Such configuration parameters are required to be set before calling the wi-fi initialization function @ref m2m_wifi_init. + @ref pfAppWifiCb attribute must be set to handle the wi-fi callback operations. + @ref pfAppMonCb attribute, is optional based on whether the application requires the monitoring mode configuration, and can there not + be set before the initialization. + @ref strEthInitParam structure, is another optional configuration based on whether the bypass mode is set. + + @see + tpfAppEthCb + tpfAppMonCb + tstrEthInitParam + +*/ +typedef struct { + tpfAppWifiCb pfAppWifiCb; + /*!< + Callback for Wi-Fi notifications. + */ + tpfAppMonCb pfAppMonCb; + /*!< + Callback for monitoring interface. + */ + tstrEthInitParam strEthInitParam ; + /*!< + Structure to hold Ethernet interface parameters. + */ + +} tstrWifiInitParam; + //@} +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/** \defgroup WLANAPI Function + * @ingroup m2m_wifi + */ +#ifdef __cplusplus + extern "C" { +#endif + /** @defgroup WiFiDownloadFn m2m_wifi_download_mode + * @ingroup WLANAPI + * Synchronous download mode entry function that prepares the WINC board to enter the download mode, ready for the firmware or certificate download. +* The WINC board is prepared for download, through initializations for the WINC driver including bus initializations and interrupt enabling, it also halts the chip, to allow for the firmware downloads. +* Firmware can be downloaded through a number of interfaces, UART, I2C and SPI. + */ + /**@{*/ +/*! +@fn \ + NMI_API void m2m_wifi_download_mode(void); +@brief Prepares the WINC broard before downloading any data (Firmware, Certificates .. etc) + + This function should called before starting to download any data to the WINC board. The WINC board is prepared for download, through initializations for the WINC driver including bus initializations + and interrupt enabling, it also halts the chip, to allow for the firmware downloads Firmware can be downloaded through a number of interfaces, UART, I2C and SPI. + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_download_mode(void); + + /**@}*/ + /** @defgroup WifiInitFn m2m_wifi_init + * @ingroup WLANAPI + * Synchronous initialization function for the WINC driver. This function initializes the driver by, registering the call back function for M2M_WIFI layer(also the call back function for bypass mode/monitoring mode if defined), + * initializing the host interface layer and the bus interfaces. + * Wi-Fi callback registering is essential to allow the handling of the events received, in response to the asynchronous Wi-Fi operations. + +Following are the possible Wi-Fi events that are expected to be received through the call back function(provided by the application) to the M2M_WIFI layer are : + + @ref M2M_WIFI_RESP_CON_STATE_CHANGED \n + @ref M2M_WIFI_RESP_CONN_INFO \n + @ref M2M_WIFI_REQ_DHCP_CONF \n + @ref M2M_WIFI_REQ_WPS \n + @ref M2M_WIFI_RESP_IP_CONFLICT \n + @ref M2M_WIFI_RESP_SCAN_DONE \n + @ref M2M_WIFI_RESP_SCAN_RESULT \n + @ref M2M_WIFI_RESP_CURRENT_RSSI \n + @ref M2M_WIFI_RESP_CLIENT_INFO \n + @ref M2M_WIFI_RESP_PROVISION_INFO \n + @ref M2M_WIFI_RESP_DEFAULT_CONNECT \n + Example: \n + In case Bypass mode is defined : \n + @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET + + In case Monitoring mode is used: \n + @ref M2M_WIFI_RESP_WIFI_RX_PACKET + + Any application using the WINC driver must call this function at the start of its main function. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_init(tstrWifiInitParam * pWifiInitParam); + +@param [in] pWifiInitParam + This is a pointer to the @ref tstrWifiInitParam structure which holds the pointer to the application WIFI layer call back function, + monitoring mode call back and @ref tstrEthInitParam structure containing bypass mode parameters. + +@brief Initialize the WINC host driver. + This function initializes the driver by, registering the call back function for M2M_WIFI layer(also the call back function for bypass mode/monitoring mode if defined), + initializing the host interface layer and the bus interfaces. + +@pre + Prior to this function call, The application should initialize the BSP using "nm_bsp_init". + Also,application users must provide a call back function responsible for receiving all the WI-FI events that are received on the M2M_WIFI layer. + +@warning + Failure to successfully complete function indicates that the driver couldn't be initialized and a fatal error will prevent the application from proceeding. + +@see + nm_bsp_init + m2m_wifi_deinit + tenuM2mStaCmd + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_init(tstrWifiInitParam * pWifiInitParam); + /**@}*/ + /** @defgroup WifiDeinitFn m2m_wifi_deinit + * @ingroup WLANAPI + * Synchronous de-initialization function to the WINC1500 driver. De-initializes the host interface and frees any resources used by the M2M_WIFI layer. + * This function must be called in the application closing phase to ensure that all resources have been correctly released. No arguments are expected to be passed in. + */ +/**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_deinit(void * arg); + +@param [in] arg + Generic argument. Not used in the current implementation. +@brief Deinitilize the WINC driver and host enterface. + This function must be called at the De-initilization stage of the application. Generally This function should be the last function before switching off the chip + and it should be followed only by "nm_bsp_deinit" function call. Every function call of "nm_wifi_init" should be matched with a call to nm_wifi_deinit. +@see + nm_bsp_deinit + nm_wifi_init + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_deinit(void * arg); + + /**@}*/ +/** @defgroup WifiHandleEventsFn m2m_wifi_handle_events +* @ingroup WLANAPI +* Synchronous M2M event handler function, responsible for handling interrupts received from the WINC firmware. +* Application developers should call this function periodically in-order to receive the events that are to be handled by the +* callback functions implemented by the application. + + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_handle_events(void * arg); + +@pre + Prior to receiving events, the WINC driver should have been successfully initialized by calling the @ref m2m_wifi_init function. + +@brief Handle the varios events received from the WINC board. + Whenever an event happen in the WINC board (e.g. Connection, Disconnection , DHCP .. etc), WINC will interrupt the host to let it know that a new + event has occured. The host driver will attempt to handle these events whenever the host driver decides to do that by calling the "m2m_wifi_handle_events" function. + It's mandatory to call this function periodically and independantly of any other condition. It's ideal to include this function in the main and the most frequent loop of the + host application. +@warning + Failure to successfully complete this function indicates bus errors and hence a fatal error that will prevent the application from proceeding. + +@return + The function returns @ref M2M_SUCCESS for successful interrupt handling and a negative value otherwise. +*/ + +NMI_API sint8 m2m_wifi_handle_events(void * arg); + + /**@}*/ +/** @defgroup WifiSendCRLFn m2m_wifi_send_crl +* @ingroup WLANAPI +* Asynchronous API that notifies the WINC with the Certificate Revocation List to be used for TLS. + + */ + /**@{*/ +/*! +@fn \ + sint8 m2m_wifi_send_crl(tstrTlsCrlInfo* pCRL); + +@brief + Asynchronous API that notifies the WINC with the Certificate Revocation List. + +@param [in] pCRL + Pointer to the structure containing certificate revocation list details. + +@return + The function returns @ref M2M_SUCCESS if the command has been successfully queued to the WINC, + and a negative value otherwise. +*/ + +sint8 m2m_wifi_send_crl(tstrTlsCrlInfo* pCRL); + + /**@}*/ +/** @defgroup WifiDefaultConnectFn m2m_wifi_default_connect + * @ingroup WLANAPI + * Asynchronous Wi-Fi connection function. An application calling this function will cause the firmware to correspondingly connect to the last successfully connected AP from the cached connections. + * A failure to connect will result in a response of @ref M2M_WIFI_RESP_DEFAULT_CONNECT indicating the connection error as defined in the structure @ref tstrM2MDefaultConnResp. + * Possible errors are: + * The connection list is empty @ref M2M_DEFAULT_CONN_EMPTY_LIST or a mismatch for the saved AP name @ref M2M_DEFAULT_CONN_SCAN_MISMATCH. + * only difference between this function and @ref m2m_wifi_connect, is the connection parameters. + * Connection using this function is expected to connect using cached connection parameters. + + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_default_connect(void); + +@pre + Prior to connecting, the WINC driver should have been successfully initialized by calling the @ref m2m_wifi_init function. + +@brief Connect to the last successfully connected AP from the cached connections. + +@warning + This function must be called in station mode only. + It's important to note that successful completion of a call to m2m_wifi_default_connect() does not guarantee success of the WIFI connection, + and a negative return value indicates only locally-detected errors. + +@see + m2m_wifi_connect + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_default_connect(void); + /**@}*/ +/** @defgroup WifiConnectFn m2m_wifi_connect + * @ingroup WLANAPI + * Asynchronous wi-fi connection function to a specific AP. Prior to a successful connection, the application must define the SSID of the AP, the security type, + * the authentication information parameters and the channel number to which the connection will be established. + * The connection status is known when a response of @ref M2M_WIFI_RESP_CON_STATE_CHANGED is received based on the states defined in @ref tenuM2mConnState, + * successful connection is defined by @ref M2M_WIFI_CONNECTED +* + * The only difference between this function and @ref m2m_wifi_default_connect, is the connection parameters. + * Connection using this function is expected to be made to a specific AP and to a specified channel. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_connect(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch); + +@param [in] pcSsid + A buffer holding the SSID corresponding to the requested AP. + +@param [in] u8SsidLen + Length of the given SSID (not including the NULL termination). + A length less than ZERO or greater than the maximum defined SSID @ref M2M_MAX_SSID_LEN will result in a negative error + @ref M2M_ERR_FAIL. + +@param [in] u8SecType + Wi-Fi security type security for the network. It can be one of the following types: + -@ref M2M_WIFI_SEC_OPEN + -@ref M2M_WIFI_SEC_WEP + -@ref M2M_WIFI_SEC_WPA_PSK + -@ref M2M_WIFI_SEC_802_1X + A value outside these possible values will result in a negative return error @ref M2M_ERR_FAIL. + +@param [in] pvAuthInfo + Authentication parameters required for completing the connection. It is type is based on the Security type. + If the authentication parameters are NULL or are greater than the maximum length of the authentication parameters length as defined by + @ref M2M_MAX_PSK_LEN a negative error will return @ref M2M_ERR_FAIL(-12) indicating connection failure. + +@param [in] u16Ch + Wi-Fi channel number as defined in @ref tenuM2mScanCh enumeration. + Channel number greater than @ref M2M_WIFI_CH_14 returns a negative error @ref M2M_ERR_FAIL(-12). + Except if the value is M2M_WIFI_CH_ALL(255), since this indicates that the firmware should scan all channels to find the SSID requested to connect to. + Failure to find the connection match will return a negative error @ref M2M_DEFAULT_CONN_SCAN_MISMATCH. +@pre + Prior to a successful connection request, the Wi-Fi driver must have been successfully initialized through the call of the @ref @m2m_wifi_init function +@see + tuniM2MWifiAuth + tstr1xAuthCredentials + tstrM2mWifiWepParams + +@warning + -This function must be called in station mode only. + -Successful completion of this function does not guarantee success of the WIFI connection, and + a negative return value indicates only locally-detected errors. + +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_connect(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch); + /**@}*/ +/** @defgroup WifiConnectFn m2m_wifi_connect_sc + * @ingroup WLANAPI + * Asynchronous wi-fi connection function to a specific AP. Prior to a successful connection, the application developers must know the SSID of the AP, the security type, + * the authentication information parameters and the channel number to which the connection will be established.this API allows the user to choose + * whether to + * The connection status is known when a response of @ref M2M_WIFI_RESP_CON_STATE_CHANGED is received based on the states defined in @ref tenuM2mConnState, + * successful connection is defined by @ref M2M_WIFI_CONNECTED + * The only difference between this function and @ref m2m_wifi_connect, is the option to save the acess point info ( SSID, password...etc) or not. + * Connection using this function is expected to be made to a specific AP and to a specified channel. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_connect_sc(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch,uint8 u8SaveCred); + +@param [in] pcSsid + A buffer holding the SSID corresponding to the requested AP. + +@param [in] u8SsidLen + Length of the given SSID (not including the NULL termination). + A length less than ZERO or greater than the maximum defined SSID @ref M2M_MAX_SSID_LEN will result in a negative error + @ref M2M_ERR_FAIL. + +@param [in] u8SecType + Wi-Fi security type security for the network. It can be one of the following types: + -@ref M2M_WIFI_SEC_OPEN + -@ref M2M_WIFI_SEC_WEP + -@ref M2M_WIFI_SEC_WPA_PSK + -@ref M2M_WIFI_SEC_802_1X + A value outside these possible values will result in a negative return error @ref M2M_ERR_FAIL. + +@param [in] pvAuthInfo + Authentication parameters required for completing the connection. It is type is based on the Security type. + If the authentication parameters are NULL or are greater than the maximum length of the authentication parameters length as defined by + @ref M2M_MAX_PSK_LEN a negative error will return @ref M2M_ERR_FAIL(-12) indicating connection failure. + +@param [in] u16Ch + Wi-Fi channel number as defined in @ref tenuM2mScanCh enumeration. + Channel number greater than @ref M2M_WIFI_CH_14 returns a negative error @ref M2M_ERR_FAIL(-12). + Except if the value is M2M_WIFI_CH_ALL(255), since this indicates that the firmware should scan all channels to find the SSID requested to connect to. + Failure to find the connection match will return a negative error @ref M2M_DEFAULT_CONN_SCAN_MISMATCH. + +@param [in] u8NoSaveCred + Option to store the acess point SSID and password into the WINC flash memory or not. + +@pre + Prior to a successful connection request, the wi-fi driver must have been successfully initialized through the call of the @ref @m2m_wifi_init function +@see + tuniM2MWifiAuth + tstr1xAuthCredentials + tstrM2mWifiWepParams + +@warning + -This function must be called in station mode only. + -Successful completion of this function does not guarantee success of the WIFI connection, and + a negative return value indicates only locally-detected errors. + +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ + NMI_API sint8 m2m_wifi_connect_sc(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch, uint8 u8SaveCred); + /**@}*/ +/** @defgroup WifiDisconnectFn m2m_wifi_disconnect + * @ingroup WLANAPI + * Synchronous wi-fi disconnection function, requesting a Wi-Fi disconnection from the currently connected AP. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_disconnect(void); + +@pre + Disconnection request must be made to a successfully connected AP. If the WINC is not in the connected state, a call to this function will hold insignificant. + +@brief Request a Wi-Fi disconnect from the currently connected AP. + After the Disconnect is complete the driver should recieve a response of @ref M2M_WIFI_RESP_CON_STATE_CHANGED based on the states defined + in @ref tenuM2mConnState, successful disconnection is defined by @ref M2M_WIFI_DISCONNECTED . +@warning + This function must be called in station mode only. + +@see + m2m_wifi_connect + m2m_wifi_default_connect + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_disconnect(void); + + /**@}*/ +/** @defgroup StartProvisionModeFn m2m_wifi_start_provision_mode + * @ingroup WLANAPI + * Asynchronous Wi-Fi provisioning function, which starts the WINC HTTP PROVISIONING mode. + The function triggers the WINC to activate the Wi-Fi AP (HOTSPOT) mode with the passed configuration parameters and then starts the + HTTP Provision WEB Server. + The provisioning status is returned in an event @ref M2M_WIFI_RESP_PROVISION_INFO + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_start_provision_mode(tstrM2MAPConfig *pstrAPConfig, char *pcHttpServerDomainName, uint8 bEnableHttpRedirect); + +@param [in] pstrAPConfig + AP configuration parameters as defined in @ref tstrM2MAPConfig configuration structure. + A NULL value passed in, will result in a negative error @ref M2M_ERR_FAIL. + +@param [in] pcHttpServerDomainName + Domain name of the HTTP Provision WEB server which others will use to load the provisioning Home page. + The domain name can have one of the following 3 forms: + 1- "wincprov.com" + 2- "http://wincprov.com" + 3- "https://wincprov.com" + The forms 1 and 2 are equivalent, they both will start a plain http server, while form 3 + will start a secure HTTP provisioning Session (HTTP over SSL connection). + +@param [in] bEnableHttpRedirect + A flag to enable/disable the HTTP redirect feature. If Secure provisioning is enabled (i.e. the server + domain name uses "https" prefix) this flag is ignored (no meaning for redirect in HTTPS). + Possible values are: + - ZERO DO NOT Use HTTP Redirect. In this case the associated device could open the provisioning page ONLY when + the HTTP Provision URL of the WINC HTTP Server is correctly written on the browser. + - Non-Zero value Use HTTP Redirect. In this case, all http traffic (http://URL) from the associated + device (Phone, PC, ...etc) will be redirected to the WINC HTTP Provisioning Home page. + +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback + is done through passing it to the initialization @ref m2m_wifi_init function. + - The event @ref M2M_WIFI_RESP_CONN_INFO must be handled in the callback to receive the requested connection info. + +@see + tpfAppWifiCb + m2m_wifi_init + M2M_WIFI_RESP_PROVISION_INFO + m2m_wifi_stop_provision_mode + tstrM2MAPConfig + +@warning + DO Not use ".local" in the pcHttpServerDomainName. + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +\section Example + The example demonstrates a code snippet for how provisioning is triggered and the response event received accordingly. +@code + #include "m2m_wifi.h" + #include "m2m_types.h" + + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_PROVISION_INFO: + { + tstrM2MProvisionInfo *pstrProvInfo = (tstrM2MProvisionInfo*)pvMsg; + if(pstrProvInfo->u8Status == M2M_SUCCESS) + { + m2m_wifi_connect((char*)pstrProvInfo->au8SSID, (uint8)strlen(pstrProvInfo->au8SSID), pstrProvInfo->u8SecType, + pstrProvInfo->au8Password, M2M_WIFI_CH_ALL); + + printf("PROV SSID : %s\n",pstrProvInfo->au8SSID); + printf("PROV PSK : %s\n",pstrProvInfo->au8Password); + } + else + { + printf("(ERR) Provisioning Failed\n"); + } + } + break; + + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + tstrM2MAPConfig apConfig; + uint8 bEnableRedirect = 1; + + strcpy(apConfig.au8SSID, "WINC_SSID"); + apConfig.u8ListenChannel = 1; + apConfig.u8SecType = M2M_WIFI_SEC_OPEN; + apConfig.u8SsidHide = 0; + + // IP Address + apConfig.au8DHCPServerIP[0] = 192; + apConfig.au8DHCPServerIP[1] = 168; + apConfig.au8DHCPServerIP[2] = 1; + apConfig.au8DHCPServerIP[0] = 1; + + m2m_wifi_start_provision_mode(&apConfig, "atmelwincconf.com", bEnableRedirect); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API sint8 m2m_wifi_start_provision_mode(tstrM2MAPConfig *pstrAPConfig, char *pcHttpServerDomainName, uint8 bEnableHttpRedirect); + /**@}*/ +/** @defgroup StopProvisioningModeFn m2m_wifi_stop_provision_mode + * @ingroup WLANAPI + * Synchronous provision termination function which stops the provision mode if it is active. + */ + /**@{*/ +/*! +@fn \ + sint8 m2m_wifi_stop_provision_mode(void); + +@pre + An active provisioning session must be active before it is terminated through this function. +@see + m2m_wifi_start_provision_mode + +@return + The function returns ZERO for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_stop_provision_mode(void); + /**@}*/ +/** @defgroup GetConnectionInfoFn m2m_wifi_get_connection_info + * @ingroup WLANAPI + * Asynchronous connection status retrieval function, retrieves the status information of the currently connected AP. The result is passed to the Wi-Fi notification callback +* through the event @ref M2M_WIFI_RESP_CONN_INFO. Connection information is retrieved from the structure @ref tstrM2MConnInfo. + */ + /**@{*/ +/*! +@fn \ + sint8 m2m_wifi_get_connection_info(void); + +@brief + Retrieve the current Connection information. The result is passed to the Wi-Fi notification callback + with [M2M_WIFI_RESP_CONN_INFO](@ref M2M_WIFI_RESP_CONN_INFO). +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback + is done through passing it to the initialization @ref m2m_wifi_init function. + - The event @ref M2M_WIFI_RESP_CONN_INFO must be handled in the callback to receive the requested connection info. + + Connection Information retrieved: + + + -Connection Security + -Connection RSSI + -Remote MAC address + -Remote IP address + + and in case of WINC station mode the SSID of the AP is also retrieved. +@warning + -In case of WINC AP mode or P2P mode, ignore the SSID field (NULL string). +@sa + M2M_WIFI_RESP_CONN_INFO, + tstrM2MConnInfo +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet shows an example of how wi-fi connection information is retrieved . +@code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_CONN_INFO: + { + tstrM2MConnInfo *pstrConnInfo = (tstrM2MConnInfo*)pvMsg; + + printf("CONNECTED AP INFO\n"); + printf("SSID : %s\n",pstrConnInfo->acSSID); + printf("SEC TYPE : %d\n",pstrConnInfo->u8SecType); + printf("Signal Strength : %d\n", pstrConnInfo->s8RSSI); + printf("Local IP Address : %d.%d.%d.%d\n", + pstrConnInfo->au8IPAddr[0] , pstrConnInfo->au8IPAddr[1], pstrConnInfo->au8IPAddr[2], pstrConnInfo->au8IPAddr[3]); + } + break; + + case M2M_WIFI_REQ_DHCP_CONF: + { + // Get the current AP information. + m2m_wifi_get_connection_info(); + } + break; + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // connect to the default AP + m2m_wifi_default_connect(); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API sint8 m2m_wifi_get_connection_info(void); + /**@}*/ +/** @defgroup WifiSetMacAddFn m2m_wifi_set_mac_address + * @ingroup WLANAPI + * Synchronous MAC address assigning to the NMC1500. It is used for non-production SW. Assign MAC address to the WINC device. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_set_mac_address(uint8 au8MacAddress[6]); + +@brief Assign a MAC address to the WINC board. + This function override the already assigned MAC address of the WINC board with a user provided one. This is for experimental + use only and should never be used in the production SW. + +@param [in] au8MacAddress + MAC Address to be set to the WINC. + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_set_mac_address(uint8 au8MacAddress[6]); + + /**@}*/ +/** @defgroup WifiWpsFn m2m_wifi_wps + * @ingroup WLANAPI + * Asynchronous WPS triggering function. + * This function is called for the WINC to enter the WPS (Wi-Fi Protected Setup) mode. The result is passed to the Wi-Fi notification callback +* with the event @ref M2M_WIFI_REQ_WPS. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_wps(uint8 u8TriggerType,const char * pcPinNumber); + +@param [in] u8TriggerType + WPS Trigger method. Could be: + - [WPS_PIN_TRIGGER](@ref WPS_PIN_TRIGGER) Push button method + - [WPS_PBC_TRIGGER](@ref WPS_PBC_TRIGGER) Pin method + +@param [in] pcPinNumber + PIN number for WPS PIN method. It is not used if the trigger type is WPS_PBC_TRIGGER. It must follow the rules + stated by the WPS standard. + +@warning + This function is not allowed in AP or P2P modes. + +@pre + - A Wi-Fi notification callback of type (@ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback + is done through passing it to the [m2m_wifi_init](@ref m2m_wifi_init). + - The event [M2M_WIFI_REQ_WPS](@ref M2M_WIFI_REQ_WPS) must be handled in the callback to receive the WPS status. + - The WINC device MUST be in IDLE or STA mode. If AP or P2P mode is active, the WPS will not be performed. + - The [m2m_wifi_handle_events](@ref m2m_wifi_handle_events) MUST be called periodically to receive the responses in the callback. +@see + tpfAppWifiCb + m2m_wifi_init + M2M_WIFI_REQ_WPS + tenuWPSTrigger + tstrM2MWPSInfo + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet shows an example of how Wi-Fi WPS is triggered . +@code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + switch(u8WiFiEvent) + { + case M2M_WIFI_REQ_WPS: + { + tstrM2MWPSInfo *pstrWPS = (tstrM2MWPSInfo*)pvMsg; + if(pstrWPS->u8AuthType != 0) + { + printf("WPS SSID : %s\n",pstrWPS->au8SSID); + printf("WPS PSK : %s\n",pstrWPS->au8PSK); + printf("WPS SSID Auth Type : %s\n",pstrWPS->u8AuthType == M2M_WIFI_SEC_OPEN ? "OPEN" : "WPA/WPA2"); + printf("WPS Channel : %d\n",pstrWPS->u8Ch + 1); + + // establish Wi-Fi connection + m2m_wifi_connect((char*)pstrWPS->au8SSID, (uint8)m2m_strlen(pstrWPS->au8SSID), + pstrWPS->u8AuthType, pstrWPS->au8PSK, pstrWPS->u8Ch); + } + else + { + printf("(ERR) WPS Is not enabled OR Timed out\n"); + } + } + break; + + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // Trigger WPS in Push button mode. + m2m_wifi_wps(WPS_PBC_TRIGGER, NULL); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API sint8 m2m_wifi_wps(uint8 u8TriggerType,const char *pcPinNumber); + /**@}*/ +/** @defgroup WifiWpsDisableFn m2m_wifi_wps_disable + * @ingroup WLANAPI + * Disable the WINC1500 WPS operation. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_wps_disable(void); + +@pre WINC should be already in WPS mode using @ref m2m_wifi_wps + +@brief Stops the WPS ongoing session. + +@see + m2m_wifi_wps + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_wps_disable(void); + + /**@}*/ +/** @defgroup WifiP2PFn m2m_wifi_p2p + * @ingroup WLANAPI + * Asynchronous Wi-Fi direct (P2P) enabling mode function. + The WINC supports P2P in device listening mode ONLY (intent is ZERO). + The WINC P2P implementation does not support P2P GO (Group Owner) mode. + Active P2P devices (e.g. phones) could find the WINC in the search list. When a device is connected to WINC, a Wi-Fi notification event + @ref M2M_WIFI_RESP_CON_STATE_CHANGED is triggered. After a short while, the DHCP IP Address is obtained + and an event @ref M2M_WIFI_REQ_DHCP_CONF is triggered. Refer to the code examples for a more illustrative example. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_p2p(uint8 u8Channel); + +@param [in] u8Channel + P2P Listen RF channel. According to the P2P standard It must hold only one of the following values 1, 6 or 11. + +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback + is done through passing it to the @ref m2m_wifi_init. + - The events @ref M2M_WIFI_RESP_CON_STATE_CHANGED and @ref M2M_WIFI_REQ_DHCP_CONF + must be handled in the callback. + - The @ref m2m_wifi_handle_events MUST be called to receive the responses in the callback. + +@warning + This function is not allowed in AP or STA modes. + +@see + tpfAppWifiCb + m2m_wifi_init + M2M_WIFI_RESP_CON_STATE_CHANGED + M2M_WIFI_REQ_DHCP_CONF + tstrM2mWifiStateChanged + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet shown an example of how the p2p mode operates. +@code + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_CON_STATE_CHANGED: + { + tstrM2mWifiStateChanged *pstrWifiState = (tstrM2mWifiStateChanged*)pvMsg; + M2M_INFO("Wifi State :: %s :: ErrCode %d\n", pstrWifiState->u8CurrState? "CONNECTED":"DISCONNECTED",pstrWifiState->u8ErrCode); + + // Do something + } + break; + + case M2M_WIFI_REQ_DHCP_CONF: + { + uint8 *pu8IPAddress = (uint8*)pvMsg; + + printf("P2P IP Address \"%u.%u.%u.%u\"\n",pu8IPAddress[0],pu8IPAddress[1],pu8IPAddress[2],pu8IPAddress[3]); + } + break; + + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // Trigger P2P + m2m_wifi_p2p(M2M_WIFI_CH_1); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode + +*/ +NMI_API sint8 m2m_wifi_p2p(uint8 u8Channel); + /**@}*/ +/** @defgroup WifiP2PDisconnectFn m2m_wifi_p2p_disconnect + * @ingroup WLANAPI + * Disable the WINC1500 device Wi-Fi direct mode (P2P). + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_p2p_disconnect(void); +@pre + The p2p mode must have be enabled and active before a disconnect can be called. + +@see + m2m_wifi_p2p +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_p2p_disconnect(void); + /**@}*/ +/** @defgroup WifiEnableApFn m2m_wifi_enable_ap + * @ingroup WLANAPI + * Asynchronous Wi-FI hot-spot enabling function. + * The WINC supports AP mode operation with the following limitations: + - Only 1 STA could be associated at a time. + - Open and WEP are the only supported security types + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_enable_ap(CONST tstrM2MAPConfig* pstrM2MAPConfig); + +@param [in] pstrM2MAPConfig + A structure holding the AP configurations. + +@warning + This function is not allowed in P2P or STA modes. + +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback + is done through passing it to the [m2m_wifi_init](@ref m2m_wifi_init). + - The event @ref M2M_WIFI_REQ_DHCP_CONF must be handled in the callback. + - The @ref m2m_wifi_handle_events MUST be called to receive the responses in the callback. + +@see + tpfAppWifiCb + tenuM2mSecType + m2m_wifi_init + M2M_WIFI_REQ_DHCP_CONF + tstrM2mWifiStateChanged + tstrM2MAPConfig + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet demonstrates how the AP mode is enabled after the driver is initialized in the application's main function and the handling + of the event @ref M2M_WIFI_REQ_DHCP_CONF, to indicate successful connection. +@code + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + switch(u8WiFiEvent) + { + case M2M_WIFI_REQ_DHCP_CONF: + { + uint8 *pu8IPAddress = (uint8*)pvMsg; + + printf("Associated STA has IP Address \"%u.%u.%u.%u\"\n",pu8IPAddress[0],pu8IPAddress[1],pu8IPAddress[2],pu8IPAddress[3]); + } + break; + + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + tstrM2MAPConfig apConfig; + + strcpy(apConfig.au8SSID, "WINC_SSID"); + apConfig.u8ListenChannel = 1; + apConfig.u8SecType = M2M_WIFI_SEC_OPEN; + apConfig.u8SsidHide = 0; + + // IP Address + apConfig.au8DHCPServerIP[0] = 192; + apConfig.au8DHCPServerIP[1] = 168; + apConfig.au8DHCPServerIP[2] = 1; + apConfig.au8DHCPServerIP[0] = 1; + + // Trigger AP + m2m_wifi_enable_ap(&apConfig); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode + +*/ +NMI_API sint8 m2m_wifi_enable_ap(CONST tstrM2MAPConfig* pstrM2MAPConfig); + /**@}*/ +/** @defgroup WifiDisableApFn m2m_wifi_disable_ap + * @ingroup WLANAPI + * Synchronous Wi-Fi hot-spot disabling function. Must be called only when the AP is enabled through the @ref m2m_wifi_enable_ap + * function. Otherwise the call to this function will not be useful. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_disable_ap(void); +@see + m2m_wifi_enable_ap +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_disable_ap(void); + /**@}*/ +/** @defgroup SetStaticIPFn m2m_wifi_set_static_ip + * @ingroup WLANAPI + * Synchronous static IP Address configuration function. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_set_static_ip(tstrM2MIPConfig * pstrStaticIPConf); + +@param [in] pstrStaticIPConf + Pointer to a structure holding the static IP Configurations (IP, + Gateway, subnet mask and DNS address). + +@pre The application must disable auto DHCP using @ref m2m_wifi_enable_dhcp before assigning a static IP address. + +@brief Assign a static IP address to the WINC board. + This function assigns a static IP address in case the AP doesn't have a DHCP server or in case the application wants to assign + a predefined known IP address. The user must take in mind that assigning a static IP address might result in an IP address + conflict. In case of an IP address conflict observed by the WINC board the user will get a response of @ref M2M_WIFI_RESP_IP_CONFLICT + in the wifi callback. The application is then responsible to either solve the conflict or assign another IP address. +@warning + Normally this function normally should not be used. DHCP configuration is requested automatically after successful Wi-Fi connection is established. + +@see + tstrM2MIPConfig + + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_set_static_ip(tstrM2MIPConfig * pstrStaticIPConf); + + /**@}*/ +/** @defgroup RequestDHCPClientFn m2m_wifi_request_dhcp_client + * @ingroup WLANAPI + * Starts the DHCP client operation(DHCP requested by the firmware automatically in STA/AP/P2P mode). + * + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_request_dhcp_client(void); + +@warning + This function is legacy and exists only for compatability with older applications. DHCP configuration is requested automatically after successful Wi-Fi connection is established. + +@return + The function returns @ref M2M_SUCCESS always. +*/ +NMI_API sint8 m2m_wifi_request_dhcp_client(void); + /**@}*/ +/** @defgroup RequestDHCPServerFn m2m_wifi_request_dhcp_server + * @ingroup WLANAPI + * Dhcp requested by the firmware automatically in STA/AP/P2P mode). + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_request_dhcp_server(uint8* addr); + +@warning + This function is legacy and exists only for compatability with older applications. DHCP server is started automatically when enabling the AP mode. + + +@return + The function returns @ref M2M_SUCCESS always. +*/ +NMI_API sint8 m2m_wifi_request_dhcp_server(uint8* addr); + /**@}*/ +/** @defgroup WifiDHCPEnableFn m2m_wifi_enable_dhcp + * @ingroup WLANAPI + * Synchronous Wi-Fi DHCP enable function. This function Enable/Disable DHCP protocol. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_enable_dhcp(uint8 u8DhcpEn ); + +@brief + Enable/Disable the DHCP client after connection. + +@param [in] u8DhcpEn + Possible values: + 1: Enable DHCP client after connection. + 0: Disable DHCP client after connection. +@warnings + -DHCP client is enabled by default + -This Function should be called before using m2m_wifi_set_static_ip() + + +@sa + m2m_wifi_set_static_ip() + +@return + The function SHALL return @ref M2M_SUCCESS for successful operation and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_enable_dhcp(uint8 u8DhcpEn ); + /**@}*/ +/** @defgroup WifiSetScanOptionFn m2m_wifi_set_scan_options + * @ingroup WLANAPI + * Synchronous Wi-Fi scan settings function. This function sets the time configuration parameters for the scan operation. + */ + +/*! +@fn \ + sint8 m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption) + +@param [in] ptstrM2MScanOption; + Pointer to the structure holding the Scan Parameters. + +@see + tenuM2mScanCh + m2m_wifi_request_scan + tstrM2MScanOption + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption); + /**@}*/ +/** @defgroup WifiSetScanRegionFn m2m_wifi_set_scan_region + * @ingroup WLANAPI + * Synchronous wi-fi scan region setting function. + * This function sets the scan region, which will affect the range of possible scan channels. + * For 2.5GHz supported in the current release, the requested scan region can't exceed the maximum number of channels (14). + *@{*/ +/*! +@fn \ + sint8 m2m_wifi_set_scan_region(uint16 ScanRegion) + +@param [in] ScanRegion; + ASIA + NORTH_AMERICA +@see + tenuM2mScanCh + m2m_wifi_request_scan + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_set_scan_region(uint16 ScanRegion); + /**@}*/ +/** @defgroup WifiRequestScanFn m2m_wifi_request_scan +* @ingroup WLANAPI +* Asynchronous Wi-FI scan request on the given channel. The scan status is delivered in the wifi event callback and then the application +* is supposed to read the scan results sequentially. +* The number of APs found (N) is returned in event @ref M2M_WIFI_RESP_SCAN_DONE with the number of found +* APs. +* The application reads the list of APs by calling the function @ref m2m_wifi_req_scan_result N times. +* +*@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_request_scan(uint8 ch); + +@param [in] ch + RF Channel ID for SCAN operation. It should be set according to tenuM2mScanCh. + With a value of M2M_WIFI_CH_ALL(255)), means to scan all channels. + +@warning + This function is not allowed in P2P or AP modes. It works only for STA mode (both connected or disconnected states). + +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback + is done through passing it to the @ref m2m_wifi_init. + - The events @ref M2M_WIFI_RESP_SCAN_DONE and @ref M2M_WIFI_RESP_SCAN_RESULT. + must be handled in the callback. + - The @ref m2m_wifi_handle_events function MUST be called to receive the responses in the callback. + +@see + M2M_WIFI_RESP_SCAN_DONE + M2M_WIFI_RESP_SCAN_RESULT + tpfAppWifiCb + tstrM2mWifiscanResult + tenuM2mScanCh + m2m_wifi_init + m2m_wifi_handle_events + m2m_wifi_req_scan_result + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of + the events received in response. +@code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + static uint8 u8ScanResultIdx = 0; + + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_SCAN_DONE: + { + tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; + + printf("Num of AP found %d\n",pstrInfo->u8NumofCh); + if(pstrInfo->s8ScanState == M2M_SUCCESS) + { + u8ScanResultIdx = 0; + if(pstrInfo->u8NumofCh >= 1) + { + m2m_wifi_req_scan_result(u8ScanResultIdx); + u8ScanResultIdx ++; + } + else + { + printf("No AP Found Rescan\n"); + m2m_wifi_request_scan(M2M_WIFI_CH_ALL); + } + } + else + { + printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); + } + } + break; + + case M2M_WIFI_RESP_SCAN_RESULT: + { + tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; + uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); + + printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", + pstrScanResult->u8index,pstrScanResult->s8rssi, + pstrScanResult->u8AuthType, + pstrScanResult->u8ch, + pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], + pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], + pstrScanResult->au8SSID); + + if(u8ScanResultIdx < u8NumFoundAPs) + { + // Read the next scan result + m2m_wifi_req_scan_result(index); + u8ScanResultIdx ++; + } + } + break; + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // Scan all channels + m2m_wifi_request_scan(M2M_WIFI_CH_ALL); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API sint8 m2m_wifi_request_scan(uint8 ch); + + /**@}*/ +/** @defgroup WifiRequestScanFn m2m_wifi_request_scan_passive +* @ingroup WLANAPI +* Same as m2m_wifi_request_scan but perform passive scanning while the other one perform active scanning. + +* +*@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_request_scan_passive(uint8 ch, uint16 scan_time); + +@param [in] ch + RF Channel ID for SCAN operation. It should be set according to tenuM2mScanCh. + With a value of M2M_WIFI_CH_ALL(255)), means to scan all channels. + +@param [in] scan_time + The time in ms that passive scan is listening to beacons on each channel per one slot, enter 0 for deafult setting. + +@warning + This function is not allowed in P2P or AP modes. It works only for STA mode (both connected or disconnected states). + +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback + is done through passing it to the @ref m2m_wifi_init. + - The events @ref M2M_WIFI_RESP_SCAN_DONE and @ref M2M_WIFI_RESP_SCAN_RESULT. + must be handled in the callback. + - The @ref m2m_wifi_handle_events function MUST be called to receive the responses in the callback. + +@see + m2m_wifi_request_scan + M2M_WIFI_RESP_SCAN_DONE + M2M_WIFI_RESP_SCAN_RESULT + tpfAppWifiCb + tstrM2mWifiscanResult + tenuM2mScanCh + m2m_wifi_init + m2m_wifi_handle_events + m2m_wifi_req_scan_result + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_request_scan_passive(uint8 ch, uint16 scan_time); + + + /**@}*/ +/** @defgroup WifiRequestScanFn m2m_wifi_request_scan_ssid_list +* @ingroup WLANAPI +* Asynchronous wi-fi scan request on the given channel and the hidden scan list. The scan status is delivered in the wi-fi event callback and then the application +* is to read the scan results sequentially. +* The number of APs found (N) is returned in event @ref M2M_WIFI_RESP_SCAN_DONE with the number of found +* APs. +* The application could read the list of APs by calling the function @ref m2m_wifi_req_scan_result N times. +* +*@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_request_scan_ssid_list(uint8 ch,uint8 * u8SsidList); + +@param [in] ch + RF Channel ID for SCAN operation. It should be set according to tenuM2mScanCh. + With a value of M2M_WIFI_CH_ALL(255)), means to scan all channels. +@param [in] u8SsidList + u8SsidList is a buffer containing a list of hidden SSIDs to + include during the scan. The first byte in the buffer, u8SsidList[0], + is the number of SSIDs encoded in the string. The number of hidden SSIDs + cannot exceed MAX_HIDDEN_SITES. All SSIDs are concatenated in the following + bytes and each SSID is prefixed with a one-byte header containing its length. + The total number of bytes in u8SsidList buffer, including length byte, cannot + exceed 133 bytes (MAX_HIDDEN_SITES SSIDs x 32 bytes each, which is max SSID length). + For instance, encoding the two hidden SSIDs "DEMO_AP" and "TEST" + results in the following buffer content: +@code + uint8 u8SsidList[14]; + u8SsidList[0] = 2; // Number of SSIDs is 2 + u8SsidList[1] = 7; // Length of the string "DEMO_AP" without NULL termination + memcpy(&u8SsidList[2], "DEMO_AP", 7); // Bytes index 2-9 containing the string DEMO_AP + u8SsidList[9] = 4; // Length of the string "TEST" without NULL termination + memcpy(&u8SsidList[10], "TEST", 4); // Bytes index 10-13 containing the string TEST +@endcode + +@warning + This function is not allowed in P2P. It works only for STA/AP mode (connected or disconnected). + +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback + is done through passing it to the @ref m2m_wifi_init. + - The events @ref M2M_WIFI_RESP_SCAN_DONE and @ref M2M_WIFI_RESP_SCAN_RESULT. + must be handled in the callback. + - The @ref m2m_wifi_handle_events function MUST be called to receive the responses in the callback. + +@see + M2M_WIFI_RESP_SCAN_DONE + M2M_WIFI_RESP_SCAN_RESULT + tpfAppWifiCb + tstrM2mWifiscanResult + tenuM2mScanCh + m2m_wifi_init + m2m_wifi_handle_events + m2m_wifi_req_scan_result + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of + the events received in response. +@code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + static void request_scan_hidden_demo_ap(void); + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + static uint8 u8ScanResultIdx = 0; + + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_SCAN_DONE: + { + tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; + + printf("Num of AP found %d\n",pstrInfo->u8NumofCh); + if(pstrInfo->s8ScanState == M2M_SUCCESS) + { + u8ScanResultIdx = 0; + if(pstrInfo->u8NumofCh >= 1) + { + m2m_wifi_req_scan_result(u8ScanResultIdx); + u8ScanResultIdx ++; + } + else + { + printf("No AP Found Rescan\n"); + request_scan_hidden_demo_ap(); + } + } + else + { + printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); + } + } + break; + + case M2M_WIFI_RESP_SCAN_RESULT: + { + tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; + uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); + + printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", + pstrScanResult->u8index,pstrScanResult->s8rssi, + pstrScanResult->u8AuthType, + pstrScanResult->u8ch, + pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], + pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], + pstrScanResult->au8SSID); + + if(u8ScanResultIdx < u8NumFoundAPs) + { + // Read the next scan result + m2m_wifi_req_scan_result(index); + u8ScanResultIdx ++; + } + } + break; + default: + break; + } + } + + static void request_scan_hidden_demo_ap(void) + { + uint8 list[9]; + char ssid[] = "DEMO_AP"; + uint8 len = (uint8)(sizeof(ssid)-1); + + list[0] = 1; + list[1] = len; + memcpy(&list[2], ssid, len); // copy 7 bytes + // Scan all channels + m2m_wifi_request_scan_ssid_list(M2M_WIFI_CH_ALL, list); + } + + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + request_scan_hidden_demo_ap(); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API sint8 m2m_wifi_request_scan_ssid_list(uint8 ch,uint8 * u8Ssidlist); + +/**@}*/ +/** @defgroup WifiGetNumAPFoundFn m2m_wifi_get_num_ap_found + * @ingroup WLANAPI +* Synchronous function to retrieve the number of AP's found in the last scan request, The function reads the number of APs from global variable which was updated in the Wi-Fi callback function through the M2M_WIFI_RESP_SCAN_DONE event. +* Function used only in STA mode only. + */ + /**@{*/ +/*! +@fn NMI_API uint8 m2m_wifi_get_num_ap_found(void); + +@see m2m_wifi_request_scan + M2M_WIFI_RESP_SCAN_DONE + M2M_WIFI_RESP_SCAN_RESULT +@pre m2m_wifi_request_scan need to be called first + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback + is done through passing it to the @ref m2m_wifi_init. + - The event @ref M2M_WIFI_RESP_SCAN_DONE must be handled in the callback to receive the requested scan information. +@warning This function must be called only in the wi-fi callback function when the events @ref M2M_WIFI_RESP_SCAN_DONE or @ref M2M_WIFI_RESP_SCAN_RESULT + are received. + Calling this function in any other place will result in undefined/outdated numbers. +@return Return the number of AP's found in the last Scan Request. + +\section Example + The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of + the events received in response. +@code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + static uint8 u8ScanResultIdx = 0; + + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_SCAN_DONE: + { + tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; + + printf("Num of AP found %d\n",pstrInfo->u8NumofCh); + if(pstrInfo->s8ScanState == M2M_SUCCESS) + { + u8ScanResultIdx = 0; + if(pstrInfo->u8NumofCh >= 1) + { + m2m_wifi_req_scan_result(u8ScanResultIdx); + u8ScanResultIdx ++; + } + else + { + printf("No AP Found Rescan\n"); + m2m_wifi_request_scan(M2M_WIFI_CH_ALL); + } + } + else + { + printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); + } + } + break; + + case M2M_WIFI_RESP_SCAN_RESULT: + { + tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; + uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); + + printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", + pstrScanResult->u8index,pstrScanResult->s8rssi, + pstrScanResult->u8AuthType, + pstrScanResult->u8ch, + pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], + pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], + pstrScanResult->au8SSID); + + if(u8ScanResultIdx < u8NumFoundAPs) + { + // Read the next scan result + m2m_wifi_req_scan_result(index); + u8ScanResultIdx ++; + } + } + break; + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // Scan all channels + m2m_wifi_request_scan(M2M_WIFI_CH_ALL); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API uint8 m2m_wifi_get_num_ap_found(void); +/**@}*/ +/** @defgroup WifiReqScanResult m2m_wifi_req_scan_result +* @ingroup WLANAPI +* Synchronous call to read the AP information from the SCAN Result list with the given index. +* This function is expected to be called when the response events M2M_WIFI_RESP_SCAN_RESULT or +* M2M_WIFI_RESP_SCAN_DONE are received in the wi-fi callback function. +* The response information received can be obtained through the casting to the @ref tstrM2mWifiscanResult structure + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_req_scan_result(uint8 index); +@param [in] index + Index for the requested result, the index range start from 0 till number of AP's found + +@see tstrM2mWifiscanResult + m2m_wifi_get_num_ap_found + m2m_wifi_request_scan + +@pre @ref m2m_wifi_request_scan needs to be called first, then m2m_wifi_get_num_ap_found + to get the number of AP's found + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback + is done through passing it to the @ref m2m_wifi_init function. + - The event @ref M2M_WIFI_RESP_SCAN_RESULT must be handled in the callback to receive the requested scan information. +@warning Function used in STA mode only. the scan results are updated only if the scan request is called. + Calling this function only without a scan request will lead to firmware errors. + Refrain from introducing a large delay between the scan request and the scan result request, to prevent + errors occurring. + +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of + the events received in response. +@code + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + static uint8 u8ScanResultIdx = 0; + + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_SCAN_DONE: + { + tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; + + printf("Num of AP found %d\n",pstrInfo->u8NumofCh); + if(pstrInfo->s8ScanState == M2M_SUCCESS) + { + u8ScanResultIdx = 0; + if(pstrInfo->u8NumofCh >= 1) + { + m2m_wifi_req_scan_result(u8ScanResultIdx); + u8ScanResultIdx ++; + } + else + { + printf("No AP Found Rescan\n"); + m2m_wifi_request_scan(M2M_WIFI_CH_ALL); + } + } + else + { + printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); + } + } + break; + + case M2M_WIFI_RESP_SCAN_RESULT: + { + tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; + uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); + + printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", + pstrScanResult->u8index,pstrScanResult->s8rssi, + pstrScanResult->u8AuthType, + pstrScanResult->u8ch, + pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], + pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], + pstrScanResult->au8SSID); + + if(u8ScanResultIdx < u8NumFoundAPs) + { + // Read the next scan result + m2m_wifi_req_scan_result(index); + u8ScanResultIdx ++; + } + } + break; + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // Scan all channels + m2m_wifi_request_scan(M2M_WIFI_CH_ALL); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API sint8 m2m_wifi_req_scan_result(uint8 index); +/**@}*/ +/** @defgroup WifiReqCurrentRssiFn m2m_wifi_req_curr_rssi + * @ingroup WLANAPI + * Asynchronous request for the current RSSI of the connected AP. + * The response received in through the @ref M2M_WIFI_RESP_CURRENT_RSSI event. + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_req_curr_rssi(void); +@pre - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered before initialization. Registering the callback + is done through passing it to the [m2m_wifi_init](@ref m2m_wifi_init) through the @ref tstrWifiInitParam initialization structure. + - The event @ref M2M_WIFI_RESP_CURRENT_RSSI must be handled in the callback to receive the requested Rssi information. +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet demonstrates how the RSSI request is called in the application's main function and the handling of the event received in the callback. +@code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + static uint8 u8ScanResultIdx = 0; + + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_CURRENT_RSSI: + { + sint8 *rssi = (sint8*)pvMsg; + M2M_INFO("ch rssi %d\n",*rssi); + } + break; + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // Scan all channels + m2m_wifi_req_curr_rssi(); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode + +*/ +NMI_API sint8 m2m_wifi_req_curr_rssi(void); +/**@}*/ +/** @defgroup WifiGetOtpMacAddFn m2m_wifi_get_otp_mac_address +* @ingroup WLANAPI +* Request the MAC address stored on the One Time Programmable(OTP) memory of the device. +* The function is blocking until the response is received. +*/ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); + +@param [out] pu8MacAddr + Output MAC address buffer of 6 bytes size. Valid only if *pu8Valid=1. +@param [out] pu8IsValid + Output boolean value to indicate the validity of pu8MacAddr in OTP. + Output zero if the OTP memory is not programmed, non-zero otherwise. +@pre m2m_wifi_init required to be called before any WIFI/socket function +@see m2m_wifi_get_mac_address + +@return The function returns @ref M2M_SUCCESS for success and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); +/**@}*/ +/** @defgroup WifiGetMacAddFn m2m_wifi_get_mac_address +* @ingroup WLANAPI +* Function to retrieve the current MAC address. The function is blocking until the response is received. +*/ +/**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr) +@param [out] pu8MacAddr + Output MAC address buffer of 6 bytes size. +@pre m2m_wifi_init required to be called before any WIFI/socket function +@see m2m_wifi_get_otp_mac_address +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr); +/**@}*/ +/** @defgroup SetSleepModeFn m2m_wifi_set_sleep_mode + * @ingroup WLANAPI + * This is one of the two synchronous power-save setting functions that + * allow the host MCU application to tweak the system power consumption. Such tweaking can be done through one of two ways: +* 1) Changing the power save mode, to one of the allowed power save modes @ref tenuPowerSaveModes. This is done by setting the first parameter +* 2) Configuring DTIM monitoring: Configuring beacon monitoring parameters by enabling or disabling the reception of broadcast/multicast data. +* this is done by setting the second parameter. + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn); +@param [in] PsTyp + Desired power saving mode. Supported types are enumerated in @ref tenuPowerSaveModes. +@param [in] BcastEn + Broadcast reception enable flag. + If it is 1, the WINC1500 will be awake each DTIM beacon for receiving broadcast traffic. + If it is 0, the WINC1500: disable broadcast traffic. Through this flag the WINC1500 will not wakeup at the DTIM beacon, but it will wakeup depends only + on the the configured Listen Interval. + +@warning The function called once after initialization. + +@see tenuPowerSaveModes + m2m_wifi_get_sleep_mode + m2m_wifi_set_lsn_int + +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn); +/**@}*/ +/** @defgroup WifiRequestSleepFn m2m_wifi_request_sleep + * @ingroup WLANAPI + * Synchronous power-save sleep request function, which requests from the WINC1500 device to sleep in the currenlty configured power save mode as defined + * by the @ref m2m_wifi_set_sleep_mode, for a specific time as defined by the passed in parameter. + * This function should be used in the @ref M2M_PS_MANUAL power save mode only. + * A wake up request is automatically performed by the WINC1500 device when any host driver API function, e.g. Wi-Fi or socket operation is called. + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_request_sleep(uint32 u32SlpReqTime); +@param [in] u32SlpReqTime + Request sleep time in ms + The best recommended sleep duration is left to be determined by the application. Taking into account that if the application sends notifications very rarely, + sleeping for a long time can be a power-efficient decision. In contrast applications that are senstive for long periods of absence can experience + performance degradation in the connection if long sleeping times are used. +@warning The function should be called in @ref M2M_PS_MANUAL power save mode only. As enumerated in @ref tenuPowerSaveModes + It's also important to note that during the sleeping time while in the M2M_PS_MANUAL mode, AP beacon monitoring is bypassed and the wifi-connection may drop if + the sleep period is enlongated. +@see tenuPowerSaveModes + m2m_wifi_set_sleep_mode + +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_request_sleep(uint32 u32SlpReqTime); +/**@}*/ +/** @defgroup GetSleepModeFn m2m_wifi_get_sleep_mode + * @ingroup WLANAPI + * Synchronous power save mode retrieval function. + */ + /**@{*/ +/*! +@fn NMI_API uint8 m2m_wifi_get_sleep_mode(void); +@see tenuPowerSaveModes + m2m_wifi_set_sleep_mode +@return The current operating power saving mode based on the enumerated sleep modes @ref tenuPowerSaveModes. +*/ +NMI_API uint8 m2m_wifi_get_sleep_mode(void); +/**@}*/ +/** @defgroup WifiReqClientCtrlFn m2m_wifi_req_client_ctrl + * @ingroup WLANAPI + * Asynchronous command sending function to the PS Client (An WINC1500 board running the ps_firmware) +* if the PS client send any command it will be received through the @ref M2M_WIFI_RESP_CLIENT_INFO event + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_req_client_ctrl(uint8 cmd); +@brief +@param [in] cmd + Control command sent from PS Server to PS Client (command values defined by the application) +@pre @ref m2m_wifi_req_server_init should be called first +@warning This mode is not supported in the current release. +@see m2m_wifi_req_server_init + M2M_WIFI_RESP_CLIENT_INFO +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_req_client_ctrl(uint8 cmd); +/**@}*/ +/** @defgroup WifiReqServerInit m2m_wifi_req_server_init + * @ingroup WLANAPI + * Synchronous function to initialize the PS Server. + * The WINC1500 supports non secure communication with another WINC1500, +* (SERVER/CLIENT) through one byte command (probe request and probe response) without any connection setup. +* The server mode can't be used with any other modes (STA/P2P/AP) +*/ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_req_server_init(uint8 ch); +@param [in] ch + Server listening channel +@see m2m_wifi_req_client_ctrl +@warning This mode is not supported in the current release. +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_req_server_init(uint8 ch); +/**@}*/ +/** @defgroup WifiSetDeviceNameFn m2m_wifi_set_device_name + * @ingroup WLANAPI + * Sets the WINC device name. The name string is used as a device name in both (P2P) WiFi-Direct mode as well as DHCP hostname (option 12). + * For P2P devices to communicate a device name must be present. If it is not set through this function a default name is assigned. + * The default name is WINC-XX-YY, where XX and YY are the last 2 octets of the OTP MAC address. If OTP (eFuse) is programmed, + * then the default name is WINC-00-00. + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength); +@param [in] pu8DeviceName + A Buffer holding the device name. Device name is a null terminated C string. +@param [in] u8DeviceNameLength + The length of the device name. Should not exceed the maximum device name's length @ref M2M_DEVICE_NAME_MAX (including null character). +@warning The function called once after initialization. + Used for the Wi-Fi Direct (P2P) as well as DHCP client hostname option (12). +@warning Device name shall contain only characters allowed in valid internet host name as defined in RFC 952 and 1123. +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength); +/**@}*/ +/** @defgroup WifiSetLsnIntFn m2m_wifi_set_lsn_int + * @ingroup WLANAPI +* This is one of the two synchronous power-save setting functions that +* allow the host MCU application to tweak the system power consumption. Such tweaking can be done by modifying the +* the Wi-Fi listen interval. The listen interval is how many beacon periods the station can sleep before it wakes up to receive data buffer in AP. +* It is represented in units of AP beacon periods(100ms). +*/ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt * pstrM2mLsnInt); + +@param [in] pstrM2mLsnInt + Structure holding the listen interval configurations. +@pre Function @m2m_wifi_set_sleep_mode shall be called first, to set the power saving mode required. +@warning The function should be called once after initialization. +@see tstrM2mLsnInt + m2m_wifi_set_sleep_mode +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt *pstrM2mLsnInt); +/**@}*/ +/** @defgroup WifiEnableMonitorModeFn m2m_wifi_enable_monitoring_mode + * @ingroup WLANAPI + * Asynchronous Wi-Fi monitoring mode (Promiscuous mode) enabling function. This function enables the monitoring mode, thus allowing two operations to be performed: + * 1) Transmission of manually configured frames, through using the @ref m2m_wifi_send_wlan_pkt function. + * 2) Reception of frames based on a defined filtering criteria + * When the monitoring mode is enabled, reception of all frames that satisfy the filter criteria passed in as a parameter is allowed, on the current wireless channel \n. + * All packets that meet the filtering criteria are passed to the application layer, to be handled by the assigned monitoring callback function \n. + * The monitoring callback function must be implemented before starting the monitoring mode, in-order to handle the packets received \n. + * Registering of the implemented callback function is through the callback pointer @ref tpfAppMonCb in the @ref tstrWifiInitParam structure\n. + * passed to @ref m2m_wifi_init function at initialization. + * + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_enable_monitoring_mode(tstrM2MWifiMonitorModeCtrl *, uint8 *, uint16 , uint16); + * @param [in] pstrMtrCtrl + * Pointer to @ref tstrM2MWifiMonitorModeCtrl structure holding the filtering parameters. + * @param [in] pu8PayloadBuffer + * Pointer to a buffer allocated by the application. The buffer SHALL hold the Data field of + * the WIFI RX Packet (Or a part from it). If it is set to NULL, the WIFI data payload will + * be discarded by the monitoring driver. + * @param [in] u16BufferSize + * The total size of the pu8PayloadBuffer in bytes. + * @param [in] u16DataOffset + * Starting offset in the DATA FIELD of the received WIFI packet. The application may be interested + * in reading specific information from the received packet. It must assign the offset to the starting + * position of it relative to the DATA payload start.\n + * \e Example, \e if \e the \e SSID \e is \e needed \e to \e be \e read \e from \e a \e PROBE \e REQ \e packet, \e the \e u16Offset \e MUST \e be \e set \e to \e 0. + * @warning When This mode is enabled, you can not be connected in any mode (Station, Access Point, or P2P).\n + * @see tstrM2MWifiMonitorModeCtrl + tstrM2MWifiRxPacketInfo + tstrWifiInitParam + tenuM2mScanCh + m2m_wifi_disable_monitoring_mode + m2m_wifi_send_wlan_pkt + m2m_wifi_send_ethernet_pkt + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*\section Example +* The example demonstrates the main function where-by the monitoring enable function is called after the initialization of the driver and the packets are +* handled in the callback function. +* @code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + //Declare receive buffer + uint8 gmgmt[1600]; + + //Callback functions + void wifi_cb(uint8 u8WiFiEvent, void * pvMsg) + { + ; + } + void wifi_monitoring_cb(tstrM2MWifiRxPacketInfo *pstrWifiRxPacket, uint8 *pu8Payload, uint16 u16PayloadSize) + { + if((NULL != pstrWifiRxPacket) && (0 != u16PayloadSize)) { + if(MANAGEMENT == pstrWifiRxPacket->u8FrameType) { + M2M_INFO("***# MGMT PACKET #***\n"); + } else if(DATA_BASICTYPE == pstrWifiRxPacket->u8FrameType) { + M2M_INFO("***# DATA PACKET #***\n"); + } else if(CONTROL == pstrWifiRxPacket->u8FrameType) { + M2M_INFO("***# CONTROL PACKET #***\n"); + } + } + } + + int main() + { + //Register wifi_monitoring_cb + tstrWifiInitParam param; + param.pfAppWifiCb = wifi_cb; + param.pfAppMonCb = wifi_monitoring_cb; + + nm_bsp_init(); + + if(!m2m_wifi_init(¶m)) { + //Enable Monitor Mode with filter to receive all data frames on channel 1 + tstrM2MWifiMonitorModeCtrl strMonitorCtrl = {0}; + strMonitorCtrl.u8ChannelID = M2M_WIFI_CH_1; + strMonitorCtrl.u8FrameType = DATA_BASICTYPE; + strMonitorCtrl.u8FrameSubtype = M2M_WIFI_FRAME_SUB_TYPE_ANY; //Receive any subtype of data frame + m2m_wifi_enable_monitoring_mode(&strMonitorCtrl, gmgmt, sizeof(gmgmt), 0); + + while(1) { + m2m_wifi_handle_events(NULL); + } + } + return 0; + } + * @endcode + */ +NMI_API sint8 m2m_wifi_enable_monitoring_mode(tstrM2MWifiMonitorModeCtrl *pstrMtrCtrl, uint8 *pu8PayloadBuffer, + uint16 u16BufferSize, uint16 u16DataOffset); +/**@}*/ +/** @defgroup WifiDisableMonitorModeFn m2m_wifi_disable_monitoring_mode + * @ingroup WLANAPI + * Synchronous function to disable Wi-Fi monitoring mode (Promiscuous mode). Expected to be called, if the enable monitoring mode is set, but if it was called without enabling + * no negative impact will reside. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_disable_monitoring_mode(void); + * @see m2m_wifi_enable_monitoring_mode + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_disable_monitoring_mode(void); + /**@}*/ + /** @defgroup SendWlanPktFn m2m_wifi_send_wlan_pkt + * @ingroup WLANAPI + * Synchronous function to transmit a WIFI RAW packet while the implementation of this packet is left to the application developer. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_send_wlan_pkt(uint8 *, uint16, uint16); + + * @param [in] pu8WlanPacket + * Pointer to a buffer holding the whole WIFI frame. + * @param [in] u16WlanHeaderLength + * The size of the WIFI packet header ONLY. + * @param [in] u16WlanPktSize + * The size of the whole bytes in packet. + * @see m2m_wifi_enable_monitoring_mode + m2m_wifi_disable_monitoring_mode + * @pre Enable Monitoring mode first using @ref m2m_wifi_enable_monitoring_mode + * @warning This function available in monitoring mode ONLY.\n + * @note Packets are user's responsibility. + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_send_wlan_pkt(uint8 *pu8WlanPacket, uint16 u16WlanHeaderLength, uint16 u16WlanPktSize); +/**@}*/ +/** @defgroup WifiSendEthernetPktFn m2m_wifi_send_ethernet_pkt + * @ingroup WLANAPI + * Synchronous function to transmit an Ethernet packet. Transmit a packet directly in ETHERNET/bypass mode where the TCP/IP stack is disabled and the implementation of this packet is left to the application developer. + * The Ethernet packet composition is left to the application developer. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_send_ethernet_pkt(uint8* pu8Packet,uint16 u16PacketSize) + * @param [in] pu8Packet + * Pointer to a buffer holding the whole Ethernet frame. + * @param [in] u16PacketSize + * The size of the whole bytes in packet. + * @warning This function available in ETHERNET/Bypass mode ONLY. Make sure that application defines @ref ETH_MODE.\n + * @note Packets are the user's responsibility. + * @sa m2m_wifi_enable_mac_mcast,m2m_wifi_set_receive_buffer + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + + */ +NMI_API sint8 m2m_wifi_send_ethernet_pkt(uint8* pu8Packet,uint16 u16PacketSize); +/**@}*/ +/** @defgroup WifiEnableSntpFn m2m_wifi_enable_sntp + * @ingroup WLANAPI + * Synchronous function to enable/disable the native Simple Network Time Protocol(SNTP) client in the WINC1500 firmware.\n + * The SNTP is enabled by default at start-up.The SNTP client at firmware is used to synchronize the system clock to the UTC time from the well known time + * servers (e.g. "time-c.nist.gov"). The SNTP client uses a default update cycle of 1 day. + * The UTC is important for checking the expiration date of X509 certificates used while establishing + * TLS (Transport Layer Security) connections. + * It is highly recommended to use it if there is no other means to get the UTC time. If there is a RTC + * on the host MCU, the SNTP could be disabled and the host should set the system time to the firmware + * using the @ref m2m_wifi_set_system_time function. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_enable_sntp(uint8); + * @param [in] bEnable +* Enabling/Disabling flag + * '0' :disable SNTP + * '1' :enable SNTP + * @see m2m_wifi_set_sytem_time + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_enable_sntp(uint8 bEnable); +/**@}*/ +/** @defgroup WifiSetSystemTime m2m_wifi_set_sytem_time + * @ingroup WLANAPI + * Synchronous function for setting the system time in time/date format (@ref uint32).\n + * The @ref tstrSystemTime structure can be used as a reference to the time values that should be set and pass its value as @ref uint32 + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_set_sytem_time(uint32); + * @param [in] u32UTCSeconds + * Seconds elapsed since January 1, 1900 (NTP Timestamp). + * @see m2m_wifi_enable_sntp + * tstrSystemTime + * @note If there is an RTC on the host MCU, the SNTP could be disabled and the host should set the system time to the firmware + * using the API @ref m2m_wifi_set_sytem_time. + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_set_sytem_time(uint32 u32UTCSeconds); +/**@}*/ +/** @defgroup WifiGetSystemTime m2m_wifi_get_sytem_time + * @ingroup WLANAPI + * Asynchronous function used to retrieve the system time through the use of the response @ref M2M_WIFI_RESP_GET_SYS_TIME. + * Response time retrieved is parsed into the members defined in the structure @ref tstrSystemTime. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_get_sytem_time(void); + * @see m2m_wifi_enable_sntp + tstrSystemTime + * @note Get the system time from the SNTP client + * using the API @ref m2m_wifi_get_sytem_time. + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_get_sytem_time(void); +/**@}*/ +/** @defgroup WifiSetCustInfoElementFn m2m_wifi_set_cust_InfoElement + * @ingroup WLANAPI + * Synchronous function to Add/Remove user-defined Information Element to the WIFIBeacon and Probe Response frames while chip mode is Access Point Mode.\n + * According to the information element layout shown bellow, if it is required to set new data for the information elements, pass in the buffer with the + * information according to the sizes and ordering defined bellow. However, if it's required to delete these IEs, fill the buffer with zeros. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_set_cust_InfoElement(uint8*); + * @param [in] pau8M2mCustInfoElement + * Pointer to Buffer containing the IE to be sent. It is the application developer's responsibility to ensure on the correctness of the information element's ordering passed in. + * @warning - Size of All elements combined must not exceed 255 byte.\n + * - Used in Access Point Mode \n + * @note IEs Format will be follow the following layout:\n + * @verbatim + --------------- ---------- ---------- ------------------- -------- -------- ----------- ---------------------- + | Byte[0] | Byte[1] | Byte[2] | Byte[3:length1+2] | ..... | Byte[n] | Byte[n+1] | Byte[n+2:lengthx+2] | + |---------------|----------|----------|-------------------|-------- --------|-----------|------------------| + | #of all Bytes | IE1 ID | Length1 | Data1(Hex Coded) | ..... | IEx ID | Lengthx | Datax(Hex Coded) | + --------------- ---------- ---------- ------------------- -------- -------- ----------- ---------------------- + * @endverbatim + * @see m2m_wifi_enable_sntp + * tstrSystemTime + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + \section Example + The example demonstrates how the information elements are set using this function. + *@code + * + char elementData[21]; + static char state = 0; // To Add, Append, and Delete + if(0 == state) { //Add 3 IEs + state = 1; + //Total Number of Bytes + elementData[0]=12; + //First IE + elementData[1]=200; elementData[2]=1; elementData[3]='A'; + //Second IE + elementData[4]=201; elementData[5]=2; elementData[6]='B'; elementData[7]='C'; + //Third IE + elementData[8]=202; elementData[9]=3; elementData[10]='D'; elementData[11]=0; elementData[12]='F'; + } else if(1 == state) { + //Append 2 IEs to others, Notice that we keep old data in array starting with\n + //element 13 and total number of bytes increased to 20 + state = 2; + //Total Number of Bytes + elementData[0]=20; + //Fourth IE + elementData[13]=203; elementData[14]=1; elementData[15]='G'; + //Fifth IE + elementData[16]=204; elementData[17]=3; elementData[18]='X'; elementData[19]=5; elementData[20]='Z'; + } else if(2 == state) { //Delete All IEs + state = 0; + //Total Number of Bytes + elementData[0]=0; + } + m2m_wifi_set_cust_InfoElement(elementData); + * @endcode + */ +NMI_API sint8 m2m_wifi_set_cust_InfoElement(uint8* pau8M2mCustInfoElement); + /**@}*/ +/** @defgroup WifiSetPowerProfile m2m_wifi_set_power_profile + * @ingroup WLANAPI + * Change the power profile mode + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode); +@brief +@param [in] u8PwrMode + Change the WINC1500 power profile to different mode based on the enumeration + @ref tenuM2mPwrMode +@pre Must be called after the initializations and before any connection request and can't be changed in run time. +@sa tenuM2mPwrMode + m2m_wifi_init +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode); + /**@}*/ + /** @defgroup WifiSetTxPower m2m_wifi_set_tx_power + * @ingroup WLANAPI + * Set the TX power tenuM2mTxPwrLevel + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel); +@param [in] u8TxPwrLevel + change the TX power based on the enumeration tenuM2mTxPwrLevel +@pre Must be called after the initialization and before any connection request and can't be changed in runtime. +@sa tenuM2mTxPwrLevel + m2m_wifi_init +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel); + /**@}*/ +/** @defgroup WifiEnableFirmware m2m_wifi_enable_firmware_logs +* @ingroup WLANAPI +* Enable or Disable logs in run time (Disabling Firmware logs will +* enhance the firmware start-up time and performance) +*/ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable); +@param [in] u8Enable + Set 1 to enable the logs, 0 for disable +@pre Must be called after intialization through the following function @ref m2m_wifi_init +@sa __DISABLE_FIRMWARE_LOGS__ (build option to disable logs from initializations) + m2m_wifi_init +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable); + /**@}*/ + /** @defgroup WifiSetBatteryVoltage m2m_wifi_set_battery_voltage +* @ingroup WLANAPI +* Set the battery voltage to update the firmware calculations +*/ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_set_battery_voltage(uint8 u8BattVolt) +@brief Set the battery voltage to update the firmware calculations +@param [in] dbBattVolt + Battery Volt in double +@pre Must be called after intialization through the following function @ref m2m_wifi_init +@sa m2m_wifi_init +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +sint8 m2m_wifi_set_battery_voltage(uint16 u16BattVoltx100); + /**@}*/ + /** @defgroup WifiSetGains m2m_wifi_set_gains +* @ingroup WLANAPI +* Set the chip gains mainly (PPA for 11b/11gn) +*/ + /**@{*/ +/*! +@fn sint8 m2m_wifi_set_gains(tstrM2mWifiGainsParams* pstrM2mGain); +@brief Set the chip PPA gain for 11b/11gn +@param [in] pstrM2mGain + tstrM2mWifiGainsParams contain gain parmaters as implemnted in rf document +@pre Must be called after intialization through the following function @ref m2m_wifi_init +@sa m2m_wifi_init +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +sint8 m2m_wifi_set_gains(tstrM2mWifiGainsParams* pstrM2mGain); + /**@}*/ +/** @defgroup WifiGetFirmwareVersion m2m_wifi_get_firmware_version +* @ingroup WLANAPI +* Get Firmware version info as defined in the structure @ref tstrM2mRev. +*/ + /**@{*/ +/*! +@fn m2m_wifi_get_firmware_version(tstrM2mRev* pstrRev) +@param [out] M2mRev + Pointer to the structure @ref tstrM2mRev that contains the firmware version parameters +@pre Must be called after intialization through the following function @ref m2m_wifi_init +@sa m2m_wifi_init +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +sint8 m2m_wifi_get_firmware_version(tstrM2mRev *pstrRev); +/**@}*/ +#ifdef ETH_MODE +/** @defgroup WifiEnableMacMcastFn m2m_wifi_enable_mac_mcast + * @ingroup WLANAPI + * Synchronous function for filtering received MAC addresses from certain MAC address groups. + * This function allows the addtion/removal of certain MAC addresses, used in the multicast filter. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8 *, uint8); + * @brief + * @param [in] pu8MulticastMacAddress + * Pointer to MAC address + * @param [in] u8AddRemove + * A flag to add or remove the MAC ADDRESS, based on the following values: + * - 0 : remove MAC address + * - 1 : add MAC address + * @warning This function is available in ETHERNET/bypass mode ONLY. Make sure that the application defines @ref ETH_MODE.\n + * @note Maximum number of MAC addresses that could be added is 8. + * @sa m2m_wifi_set_receive_buffer, m2m_wifi_send_ethernet_pkt + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8* pu8MulticastMacAddress, uint8 u8AddRemove); +/**@}*/ +/** @defgroup SetReceiveBufferFn m2m_wifi_set_receive_buffer + * @ingroup WLANAPI + * Synchronous function for setting or modifying the receiver buffer's length. + * In the ETHERNET/bypass mode the application should define a callback of type @ref tpfAppEthCb, through which the application handles the received + * ethernet frames. It is through this callback function that the user can dynamically modify the length of the currently used receiver buffer. + *@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_set_receive_buffer(void *, uint16); + + * @param [in] pvBuffer + * Pointer to Buffer to receive data. + * NULL pointer causes a negative error @ref M2M_ERR_FAIL. + * + * @param [in] u16BufferLen + * Length of data to be received. Maximum length of data should not exceed the size defined by TCP/IP + * defined as @ref SOCKET_BUFFER_MAX_LENGTH + * + * @warning This function is available in the Ethernet/bypass mode ONLY. Make sure that the application defines @ref ETH_MODE.\n + * @sa m2m_wifi_enable_mac_mcast,m2m_wifi_send_ethernet_pkt + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_set_receive_buffer(void* pvBuffer,uint16 u16BufferLen); +/**@}*/ +#endif /* ETH_MODE */ +/** @defgroup GetPrngBytes m2m_wifi_prng_get_random_bytes + * @ingroup WLANAPI + * Asynchronous function for retrieving from the firmware a pseudo-random set of bytes as specifed in the size passed in as a parameter. + * The registered wifi-cb function retrieves the random bytes through the response @ref M2M_WIFI_RESP_GET_PRNG + *@{*/ +/*! + * @fn sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PRNGBuff,uint16 u16PRNGSize) + * @param [out] pu8PrngBuff + * Pointer to a buffer to receive data. + * @param [in] u16PrngSize + * Request size in bytes + *@warning Size greater than the maximum specified (@ref M2M_BUFFER_MAX_SIZE - sizeof(tstrPrng)) + * causes a negative error @ref M2M_ERR_FAIL. + *@see tstrPrng + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PrngBuff,uint16 u16PrngSize); +/**@}*/ +#ifdef __cplusplus +} +#endif +#endif /* __M2M_WIFI_H__ */ + diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ate_mode.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ate_mode.c new file mode 100644 index 0000000..beb1af8 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ate_mode.c @@ -0,0 +1,826 @@ +/** + * + * \file + * + * \brief NMC1500 Peripherials Application Interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifdef _M2M_ATE_FW_ +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#include "driver/include/m2m_ate_mode.h" +#include "driver/source/nmasic.h" +#include "driver/source/nmdrv.h" +#include "m2m_hif.h" +#include "driver/source/nmbus.h" +#include "bsp/include/nm_bsp.h" + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#define rInterrupt_CORTUS_0 (0x10a8) +#define rInterrupt_CORTUS_1 (0x10ac) +#define rInterrupt_CORTUS_2 (0x10b0) + +#define rBurstTx_NMI_TX_RATE (0x161d00) +#define rBurstTx_NMI_NUM_TX_FRAMES (0x161d04) +#define rBurstTx_NMI_TX_FRAME_LEN (0x161d08) +#define rBurstTx_NMI_TX_CW_PARAM (0x161d0c) +#define rBurstTx_NMI_TX_GAIN (0x161d10) +#define rBurstTx_NMI_TX_DPD_CTRL (0x161d14) +#define rBurstTx_NMI_USE_PMU (0x161d18) +#define rBurstTx_NMI_TEST_CH (0x161d1c) +#define rBurstTx_NMI_TX_PHY_CONT (0x161d20) +#define rBurstTx_NMI_TX_CW_MODE (0x161d24) +#define rBurstTx_NMI_TEST_XO_OFF (0x161d28) +#define rBurstTx_NMI_USE_EFUSE_XO_OFF (0x161d2c) + +#define rBurstTx_NMI_MAC_FILTER_ENABLE_DA (0x161d30) +#define rBurstTx_NMI_MAC_ADDR_LO_PEER (0x161d34) +#define rBurstTx_NMI_MAC_ADDR_LO_SELF (0x161d38) +#define rBurstTx_NMI_MAC_ADDR_HI_PEER (0x161d3c) +#define rBurstTx_NMI_MAC_ADDR_HI_SELF (0x161d40) +#define rBurstTx_NMI_RX_PKT_CNT_SUCCESS (0x161d44) +#define rBurstTx_NMI_RX_PKT_CNT_FAIL (0x161d48) +#define rBurstTx_NMI_SET_SELF_MAC_ADDR (0x161d4c) +#define rBurstTx_NMI_MAC_ADDR_LO_SA (0x161d50) +#define rBurstTx_NMI_MAC_ADDR_HI_SA (0x161d54) +#define rBurstTx_NMI_MAC_FILTER_ENABLE_SA (0x161d58) + +#define rBurstRx_NMI_RX_ALL_PKTS_CONT (0x9898) +#define rBurstRx_NMI_RX_ERR_PKTS_CONT (0x988c) + +#define TX_DGAIN_MAX_NUM_REGS (4) +#define TX_DGAIN_REG_BASE_ADDRESS (0x1240) +#define TX_GAIN_CODE_MAX_NUM_REGS (3) +#define TX_GAIN_CODE_BASE_ADDRESS (0x1250) +#define TX_PA_MAX_NUM_REGS (3) +#define TX_PA_BASE_ADDRESS (0x1e58) +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +VARIABLES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +volatile static uint8 gu8AteIsRunning = 0; /*!< ATE firmware status, 1 means ATE is running otherwise stopped */ +volatile static uint8 gu8RxState = 0; /*!< RX status, 1 means Rx is running otherwise stopped */ +volatile static uint8 gu8TxState = 0; /*!< TX status, 1 means Tx is running otherwise stopped */ +volatile static uint32 gaAteFwTxRates[M2M_ATE_MAX_NUM_OF_RATES] = +{ + 0x01, 0x02, 0x05, 0x0B, /*B-Rats*/ + 0x06, 0x09, 0x0C, 0x12, 0x18, 0x24, 0x30, 0x36, /*G-Rats*/ + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87 /*N-Rats*/ +}; + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +STATIC FUNCTIONS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +static void m2m_ate_set_rx_status(uint8 u8Value) +{ + gu8RxState = u8Value; +} + +static void m2m_ate_set_tx_status(uint8 u8Value) +{ + gu8TxState = u8Value; +} + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION IMPLEMENTATION +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/*! +@fn \ + sint8 m2m_ate_init(void); + +@brief + This function used to download ATE firmware from flash and start it + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_init(void) +{ + sint8 s8Ret = M2M_SUCCESS; + uint8 u8WifiMode = M2M_WIFI_MODE_ATE_HIGH; + + s8Ret = nm_drv_init(&u8WifiMode); + + return s8Ret; +} + +/*! +@fn \ + sint8 m2m_ate_init(tstrM2mAteInit *pstrInit); + +@brief + This function used to download ATE firmware from flash and start it + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_init_param(tstrM2mAteInit *pstrInit) +{ + sint8 s8Ret = M2M_SUCCESS; + + s8Ret = nm_drv_init((void*)&pstrInit->u8RxPwrMode); + + return s8Ret; +} + +/*! +@fn \ + sint8 m2m_ate_deinit(void); + +@brief + De-Initialization of ATE firmware mode + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_deinit(void) +{ + return nm_drv_deinit(NULL); +} + +/*! +@fn \ + sint8 m2m_ate_set_fw_state(uint8); + +@brief + This function used to change ATE firmware status from running to stopped or vice versa. + +@param [in] u8State + Required state of ATE firmware, one of \ref tenuM2mAteFwState enumeration values. +@return + The function SHALL return 0 for success and a negative value otherwise. +\sa + m2m_ate_init +*/ +sint8 m2m_ate_set_fw_state(uint8 u8State) +{ + sint8 s8Ret = M2M_SUCCESS; + uint32_t u32Val = 0; + + if((M2M_ATE_FW_STATE_STOP == u8State) && (M2M_ATE_FW_STATE_STOP != gu8AteIsRunning)) + { + u32Val = nm_read_reg(rNMI_GLB_RESET); + u32Val &= ~(1 << 10); + s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val); + gu8AteIsRunning = M2M_ATE_FW_STATE_STOP; + } + else if((M2M_ATE_FW_STATE_RUN == u8State) && (M2M_ATE_FW_STATE_RUN != gu8AteIsRunning)) + { + /* 0x1118[0]=0 at power-on-reset: pad-based control. */ + /* Switch cortus reset register to register control. 0x1118[0]=1. */ + u32Val = nm_read_reg(rNMI_BOOT_RESET_MUX); + u32Val |= (1 << 0); + s8Ret = nm_write_reg(rNMI_BOOT_RESET_MUX, u32Val); + if(M2M_SUCCESS != s8Ret) + { + goto __EXIT; + } + /** + Write the firmware download complete magic value 0x10ADD09E at + location 0xFFFF000C (Cortus map) or C000C (AHB map). + This will let the boot-rom code execute from RAM. + **/ + s8Ret = nm_write_reg(0xc0000, 0x71); + if(M2M_SUCCESS != s8Ret) + { + goto __EXIT; + } + + u32Val = nm_read_reg(rNMI_GLB_RESET); + if((u32Val & (1ul << 10)) == (1ul << 10)) + { + u32Val &= ~(1ul << 10); + s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val); + if(M2M_SUCCESS != s8Ret) + { + goto __EXIT; + } + } + + u32Val |= (1ul << 10); + s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val); + if(M2M_SUCCESS != s8Ret) + { + goto __EXIT; + } + gu8AteIsRunning = M2M_ATE_FW_STATE_RUN; + } + else + { + s8Ret = M2M_ATE_ERR_UNHANDLED_CASE; + } + +__EXIT: + if((M2M_SUCCESS == s8Ret) && (M2M_ATE_FW_STATE_RUN == gu8AteIsRunning)) + { + nm_bsp_sleep(500); /*wait for ATE firmware start up*/ + } + return s8Ret; +} + +/*! +@fn \ + sint8 m2m_ate_get_fw_state(uint8); + +@brief + This function used to return status of ATE firmware. + +@return + The function SHALL return status of ATE firmware, one of \ref tenuM2mAteFwState enumeration values. +\sa + m2m_ate_init, m2m_ate_set_fw_state +*/ +sint8 m2m_ate_get_fw_state(void) +{ + return gu8AteIsRunning; +} + +/*! +@fn \ + uint32 m2m_ate_get_tx_rate(uint8); + +@brief + This function used to return value of TX rate required by application developer. + +@param [in] u8Index + Index of required rate , one of \ref tenuM2mAteTxIndexOfRates enumeration values. +@return + The function SHALL return 0 for in case of failure otherwise selected rate value. +\sa + tenuM2mAteTxIndexOfRates +*/ +uint32 m2m_ate_get_tx_rate(uint8 u8Index) +{ + if(M2M_ATE_MAX_NUM_OF_RATES <= u8Index) + { + return 0; + } + return gaAteFwTxRates[u8Index]; +} + +/*! +@fn \ + sint8 m2m_ate_get_tx_status(void); + +@brief + This function used to return status of TX test case either running or stopped. + +@return + The function SHALL return status of ATE firmware, 1 if TX is running otherwise 0. +\sa + m2m_ate_start_tx, m2m_ate_stop_tx +*/ +sint8 m2m_ate_get_tx_status(void) +{ + return gu8TxState; +} + +/*! +@fn \ + sint8 m2m_ate_start_tx(tstrM2mAteTx *) + +@brief + This function used to start TX test case. + +@param [in] strM2mAteTx + Type of \ref tstrM2mAteTx, with the values required to enable TX test case. You must use \ref m2m_ate_init first. +@return + The function SHALL return 0 for success and a negative value otherwise. +\sa + m2m_ate_init, m2m_ate_stop_tx, m2m_ate_get_tx_status +*/ +sint8 m2m_ate_start_tx(tstrM2mAteTx * strM2mAteTx) +{ + sint8 s8Ret = M2M_SUCCESS; + uint8 u8LoopCntr = 0; + uint32_t val32; + + + if(NULL == strM2mAteTx) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + if(0 != m2m_ate_get_tx_status()) + { + s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING; + goto __EXIT; + } + + if(0 != m2m_ate_get_rx_status()) + { + s8Ret = M2M_ATE_ERR_RX_ALREADY_RUNNING; + goto __EXIT; + } + + if( (strM2mAteTx->channel_num < M2M_ATE_CHANNEL_1) || + (strM2mAteTx->channel_num > M2M_ATE_CHANNEL_14) || + (strM2mAteTx->tx_gain_sel < M2M_ATE_TX_GAIN_DYNAMIC) || + (strM2mAteTx->tx_gain_sel > M2M_ATE_TX_GAIN_TELEC) || + (strM2mAteTx->frame_len > M2M_ATE_MAX_FRAME_LENGTH) || + (strM2mAteTx->frame_len < M2M_ATE_MIN_FRAME_LENGTH) + ) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + if( (strM2mAteTx->duty_cycle < M2M_ATE_TX_DUTY_MAX_VALUE /*1*/) || + (strM2mAteTx->duty_cycle > M2M_ATE_TX_DUTY_MIN_VALUE /*10*/ ) || + (strM2mAteTx->dpd_ctrl < M2M_ATE_TX_DPD_DYNAMIC) || + (strM2mAteTx->dpd_ctrl > M2M_ATE_TX_DPD_ENABLED) || + (strM2mAteTx->use_pmu > M2M_ATE_PMU_ENABLE) || + (strM2mAteTx->phy_burst_tx < M2M_ATE_TX_SRC_MAC) || + (strM2mAteTx->phy_burst_tx > M2M_ATE_TX_SRC_PHY) || + (strM2mAteTx->cw_tx < M2M_ATE_TX_MODE_NORM) || + (strM2mAteTx->cw_tx > M2M_ATE_TX_MODE_CW) + ) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + for(u8LoopCntr=0; u8LoopCntrdata_rate) + { + break; + } + } + + if(M2M_ATE_MAX_NUM_OF_RATES == u8LoopCntr) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + + + s8Ret += nm_write_reg(rBurstTx_NMI_USE_PMU, strM2mAteTx->use_pmu); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_PHY_CONT, strM2mAteTx->phy_burst_tx); + s8Ret += nm_write_reg(rBurstTx_NMI_NUM_TX_FRAMES, strM2mAteTx->num_frames); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_GAIN, strM2mAteTx->tx_gain_sel); + s8Ret += nm_write_reg(rBurstTx_NMI_TEST_CH, strM2mAteTx->channel_num); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_FRAME_LEN, strM2mAteTx->frame_len); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_CW_PARAM, strM2mAteTx->duty_cycle); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_DPD_CTRL, strM2mAteTx->dpd_ctrl); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_RATE, strM2mAteTx->data_rate); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_CW_MODE, strM2mAteTx->cw_tx); + s8Ret += nm_write_reg(rBurstTx_NMI_TEST_XO_OFF, strM2mAteTx->xo_offset_x1000); + s8Ret += nm_write_reg(rBurstTx_NMI_USE_EFUSE_XO_OFF, strM2mAteTx->use_efuse_xo_offset); + + val32 = strM2mAteTx->peer_mac_addr[5] << 0; + val32 |= strM2mAteTx->peer_mac_addr[4] << 8; + val32 |= strM2mAteTx->peer_mac_addr[3] << 16; + nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_PEER, val32 ); + + val32 = strM2mAteTx->peer_mac_addr[2] << 0; + val32 |= strM2mAteTx->peer_mac_addr[1] << 8; + val32 |= strM2mAteTx->peer_mac_addr[0] << 16; + nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_PEER, val32 ); + + if(M2M_SUCCESS == s8Ret) + { + s8Ret += nm_write_reg(rInterrupt_CORTUS_0, 1); /*Interrupt Cortus*/ + m2m_ate_set_tx_status(1); + nm_bsp_sleep(200); /*Recommended*/ + } + +__EXIT: + return s8Ret; +} + +/*! +@fn \ + sint8 m2m_ate_stop_tx(void) + +@brief + This function used to stop TX test case. + +@return + The function SHALL return 0 for success and a negative value otherwise. +\sa + m2m_ate_init, m2m_ate_start_tx, m2m_ate_get_tx_status +*/ +sint8 m2m_ate_stop_tx(void) +{ + sint8 s8Ret = M2M_SUCCESS; + + s8Ret = nm_write_reg(rInterrupt_CORTUS_1, 1); + if(M2M_SUCCESS == s8Ret) + { + m2m_ate_set_tx_status(0); + } + + return s8Ret; +} + +/*! +@fn \ + sint8 m2m_ate_get_rx_status(uint8); + +@brief + This function used to return status of RX test case either running or stopped. + +@return + The function SHALL return status of ATE firmware, 1 if RX is running otherwise 0. +\sa + m2m_ate_start_rx, m2m_ate_stop_rx +*/ +sint8 m2m_ate_get_rx_status(void) +{ + return gu8RxState; +} + +/*! +@fn \ + sint8 m2m_ate_start_rx(tstrM2mAteRx *) + +@brief + This function used to start RX test case. + +@param [in] strM2mAteRx + Type of \ref tstrM2mAteRx, with the values required to enable RX test case. You must use \ref m2m_ate_init first. +@return + The function SHALL return 0 for success and a negative value otherwise. +\sa + m2m_ate_init, m2m_ate_stop_rx, m2m_ate_get_rx_status +*/ +sint8 m2m_ate_start_rx(tstrM2mAteRx * strM2mAteRxStr) +{ + sint8 s8Ret = M2M_SUCCESS; + uint32 val32; + if(NULL == strM2mAteRxStr) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + if(0 != m2m_ate_get_tx_status()) + { + s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING; + goto __EXIT; + } + + if(0 != m2m_ate_get_rx_status()) + { + s8Ret = M2M_ATE_ERR_RX_ALREADY_RUNNING; + goto __EXIT; + } + + if( (strM2mAteRxStr->channel_num < M2M_ATE_CHANNEL_1) || + (strM2mAteRxStr->channel_num > M2M_ATE_CHANNEL_14)|| + (strM2mAteRxStr->use_pmu > M2M_ATE_PMU_ENABLE) + ) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + s8Ret += nm_write_reg(rBurstTx_NMI_TEST_CH, strM2mAteRxStr->channel_num); + s8Ret += nm_write_reg(rBurstTx_NMI_USE_PMU, strM2mAteRxStr->use_pmu); + s8Ret += nm_write_reg(rBurstTx_NMI_TEST_XO_OFF, strM2mAteRxStr->xo_offset_x1000); + s8Ret += nm_write_reg(rBurstTx_NMI_USE_EFUSE_XO_OFF, strM2mAteRxStr->use_efuse_xo_offset); + + if(strM2mAteRxStr->override_self_mac_addr) + { + val32 = strM2mAteRxStr->self_mac_addr[5] << 0; + val32 |= strM2mAteRxStr->self_mac_addr[4] << 8; + val32 |= strM2mAteRxStr->self_mac_addr[3] << 16; + nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_SELF, val32 ); + + val32 = strM2mAteRxStr->self_mac_addr[2] << 0; + val32 |= strM2mAteRxStr->self_mac_addr[1] << 8; + val32 |= strM2mAteRxStr->self_mac_addr[0] << 16; + nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_SELF, val32 ); + } + + if(strM2mAteRxStr->mac_filter_en_sa) + { + val32 = strM2mAteRxStr->peer_mac_addr[5] << 0; + val32 |= strM2mAteRxStr->peer_mac_addr[4] << 8; + val32 |= strM2mAteRxStr->peer_mac_addr[3] << 16; + nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_SA, val32 ); + + val32 = strM2mAteRxStr->peer_mac_addr[2] << 0; + val32 |= strM2mAteRxStr->peer_mac_addr[1] << 8; + val32 |= strM2mAteRxStr->peer_mac_addr[0] << 16; + nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_SA, val32 ); + } + + nm_write_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_DA, strM2mAteRxStr->mac_filter_en_da); + nm_write_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_SA, strM2mAteRxStr->mac_filter_en_sa); + nm_write_reg(rBurstTx_NMI_SET_SELF_MAC_ADDR, strM2mAteRxStr->override_self_mac_addr); + + if(M2M_SUCCESS == s8Ret) + { + s8Ret += nm_write_reg(rInterrupt_CORTUS_2, 1); /*Interrupt Cortus*/ + m2m_ate_set_rx_status(1); + nm_bsp_sleep(10); /*Recommended*/ + } + +__EXIT: + return s8Ret; +} + +/*! +@fn \ + sint8 m2m_ate_stop_rx(void) + +@brief + This function used to stop RX test case. + +@return + The function SHALL return 0 for success and a negative value otherwise. +\sa + m2m_ate_init, m2m_ate_start_rx, m2m_ate_get_rx_status +*/ +sint8 m2m_ate_stop_rx(void) +{ + m2m_ate_set_rx_status(0); + nm_bsp_sleep(200); /*Recommended*/ + return M2M_SUCCESS; +} + +/*! +@fn \ + sint8 m2m_ate_read_rx_status(tstrM2mAteRxStatus *) + +@brief + This function used to read RX statistics from ATE firmware. + +@param [out] strM2mAteRxStatus + Type of \ref tstrM2mAteRxStatus used to save statistics of RX test case. You must use \ref m2m_ate_start_rx first. +@return + The function SHALL return 0 for success and a negative value otherwise. +\sa + m2m_ate_init, m2m_ate_start_rx +*/ +sint8 m2m_ate_read_rx_status(tstrM2mAteRxStatus *strM2mAteRxStatus) +{ + sint8 s8Ret = M2M_SUCCESS; + + if(NULL == strM2mAteRxStatus) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + if(0 != m2m_ate_get_tx_status()) + { + s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING; + goto __EXIT; + } + + if (nm_read_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_DA) || nm_read_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_SA)) + { + strM2mAteRxStatus->num_rx_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_SUCCESS) + nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_FAIL); + strM2mAteRxStatus->num_good_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_SUCCESS); + strM2mAteRxStatus->num_err_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_FAIL); + } + else + { + strM2mAteRxStatus->num_rx_pkts = nm_read_reg(rBurstRx_NMI_RX_ALL_PKTS_CONT) + nm_read_reg(0x989c); + strM2mAteRxStatus->num_err_pkts = nm_read_reg(rBurstRx_NMI_RX_ERR_PKTS_CONT); + strM2mAteRxStatus->num_good_pkts = strM2mAteRxStatus->num_rx_pkts - strM2mAteRxStatus->num_err_pkts; + } + +__EXIT: + return s8Ret; +} +/*! +@fn \ + sint8 m2m_ate_set_dig_gain(double dGaindB) + +@brief + This function is used to set the digital gain + +@param [in] double dGaindB + The digital gain value required to be set. +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_set_dig_gain(double dGaindB) +{ + uint32_t dGain, val32; + dGain = (uint32_t)(pow(10, dGaindB/20.0) * 1024.0); + + val32 = nm_read_reg(0x160cd0); + val32 &= ~(0x1ffful << 0); + val32 |= (((uint32_t)dGain) << 0); + nm_write_reg(0x160cd0, val32); + return M2M_SUCCESS; +} +/*! +@fn \ + sint8 m2m_ate_get_dig_gain(double * dGaindB) + +@brief + This function is used to get the digital gain + +@param [out] double * dGaindB + The retrieved digital gain value obtained from HW registers in dB. +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_get_dig_gain(double * dGaindB) +{ + uint32 dGain, val32; + + if(!dGaindB) return M2M_ERR_INVALID_ARG; + + val32 = nm_read_reg(0x160cd0); + + dGain = (val32 >> 0) & 0x1ffful; + *dGaindB = 20.0*log10((double)dGain / 1024.0); + + return M2M_SUCCESS; +} +/*! +@fn \ + void m2m_ate_set_pa_gain(uint8 gain_db) + +@brief + This function is used to set the PA gain (18/15/12/9/6/3/0 only) + +@param [in] uint8 gain_db + PA gain level allowed (18/15/12/9/6/3/0 only) + +*/ +void m2m_ate_set_pa_gain(uint8 gain_db) +{ + uint32 PA_1e9c; + uint8 aGain[] = { + /* "0 dB" */ 0x00, + /* "3 dB" */ 0x01, + /* "6 dB" */ 0x03, + /* "9 dB" */ 0x07, + /* "12 dB" */ 0x0f, + /* "15 dB" */ 0x1f, + /* "18 dB" */ 0x3f }; + /* The variable PA gain is valid only for High power mode */ + PA_1e9c = nm_read_reg(0x1e9c); + /* TX bank 0. */ + PA_1e9c &= ~(0x3ful << 8); + PA_1e9c |= (((uint32)aGain[gain_db/3] & 0x3f) << 8); + nm_write_reg(0x1e9c, PA_1e9c); +} +/*! +@fn \ + sint8 m2m_ate_get_pa_gain(double *paGaindB) + +@brief + This function is used to get the PA gain + +@param [out] double *paGaindB + The retrieved PA gain value obtained from HW registers in dB. +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_get_pa_gain(double *paGaindB) +{ + uint32 val32, paGain; + uint32 m_cmbPAGainStep; + + if(!paGaindB) + return M2M_ERR_INVALID_ARG; + + val32 = nm_read_reg(0x1e9c); + + paGain = (val32 >> 8) & 0x3f; + + switch(paGain){ + case 0x1: + m_cmbPAGainStep = 5; + break; + case 0x3: + m_cmbPAGainStep = 4; + break; + case 0x7: + m_cmbPAGainStep = 3; + break; + case 0xf: + m_cmbPAGainStep = 2; + break; + case 0x1f: + m_cmbPAGainStep = 1; + break; + case 0x3f: + m_cmbPAGainStep = 0; + break; + default: + m_cmbPAGainStep = 0; + break; + } + + *paGaindB = 18 - m_cmbPAGainStep*3; + + return M2M_SUCCESS; +} +/*! +@fn \ + sint8 m2m_ate_get_ppa_gain(double * ppaGaindB) + +@brief + This function is used to get the PPA gain + +@param [out] uint32 * ppaGaindB + The retrieved PPA gain value obtained from HW registers in dB. +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_get_ppa_gain(double * ppaGaindB) +{ + uint32 val32, ppaGain, m_cmbPPAGainStep; + + if(!ppaGaindB) return M2M_ERR_INVALID_ARG; + + val32 = nm_read_reg(0x1ea0); + + ppaGain = (val32 >> 5) & 0x7; + + switch(ppaGain){ + case 0x1: + m_cmbPPAGainStep = 2; + break; + case 0x3: + m_cmbPPAGainStep = 1; + break; + case 0x7: + m_cmbPPAGainStep = 0; + break; + default: + m_cmbPPAGainStep = 3; + break; + } + + *ppaGaindB = 9 - m_cmbPPAGainStep*3; + + + return M2M_SUCCESS; +} +/*! +@fn \ + sint8 m2m_ate_get_tot_gain(double * totGaindB) + +@brief + This function is used to calculate the total gain + +@param [out] double * totGaindB + The retrieved total gain value obtained from calculations made based on the digital gain, PA and PPA gain values. +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_get_tot_gain(double * totGaindB) +{ + double dGaindB, paGaindB, ppaGaindB; + + if(!totGaindB) return M2M_ERR_INVALID_ARG; + + m2m_ate_get_pa_gain(&paGaindB); + m2m_ate_get_ppa_gain(&ppaGaindB); + m2m_ate_get_dig_gain(&dGaindB); + + *totGaindB = dGaindB + paGaindB + ppaGaindB; + + return M2M_SUCCESS; +} + +#endif //_M2M_ATE_FW_ \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_crypto.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_crypto.c new file mode 100644 index 0000000..9ac7711 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_crypto.c @@ -0,0 +1,1010 @@ +/** + * + * \file + * + * \brief WINC Crypto module. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "driver/include/m2m_crypto.h" +#include "driver/source/nmbus.h" +#include "driver/source/nmasic.h" + +#ifdef CONF_CRYPTO_HW + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*======*======*======*======*======*=======* +* WINC SHA256 HW Engine Register Definition * +*======*======*======*======*======*========*/ + +#define SHA_BLOCK_SIZE (64) + +#define SHARED_MEM_BASE (0xd0000) + + +#define SHA256_MEM_BASE (0x180000UL) +#define SHA256_ENGINE_ADDR (0x180000ul) + +/* SHA256 Registers */ +#define SHA256_CTRL (SHA256_MEM_BASE+0x00) +#define SHA256_CTRL_START_CALC_MASK (NBIT0) +#define SHA256_CTRL_START_CALC_SHIFT (0) +#define SHA256_CTRL_PREPROCESS_MASK (NBIT1) +#define SHA256_CTRL_PREPROCESS_SHIFT (1) +#define SHA256_CTRL_HASH_HASH_MASK (NBIT2) +#define SHA256_CTRL_HASH_HASH_SHIFT (2) +#define SHA256_CTRL_INIT_SHA256_STATE_MASK (NBIT3) +#define SHA256_CTRL_INIT_SHA256_STATE_SHIFT (3) +#define SHA256_CTRL_WR_BACK_HASH_VALUE_MASK (NBIT4) +#define SHA256_CTRL_WR_BACK_HASH_VALUE_SHIFT (4) +#define SHA256_CTRL_FORCE_SHA256_QUIT_MASK (NBIT5) +#define SHA256_CTRL_FORCE_SHA256_QUIT_SHIFT (5) + +#define SHA256_REGS_SHA256_CTRL_AHB_BYTE_REV_EN (NBIT6) +#define SHA256_REGS_SHA256_CTRL_RESERVED (NBIT7) +#define SHA256_REGS_SHA256_CTRL_CORE_TO_AHB_CLK_RATIO (NBIT8+ NBIT9+ NBIT10) +#define SHA256_REGS_SHA256_CTRL_CORE_TO_AHB_CLK_RATIO_MASK (NBIT2+ NBIT1+ NBIT0) +#define SHA256_REGS_SHA256_CTRL_CORE_TO_AHB_CLK_RATIO_SHIFT (8) +#define SHA256_REGS_SHA256_CTRL_RESERVED_11 (NBIT11) +#define SHA256_REGS_SHA256_CTRL_SHA1_CALC (NBIT12) +#define SHA256_REGS_SHA256_CTRL_PBKDF2_SHA1_CALC (NBIT13) + + +#define SHA256_START_RD_ADDR (SHA256_MEM_BASE+0x04UL) +#define SHA256_DATA_LENGTH (SHA256_MEM_BASE+0x08UL) +#define SHA256_START_WR_ADDR (SHA256_MEM_BASE+0x0cUL) +#define SHA256_COND_CHK_CTRL (SHA256_MEM_BASE+0x10) +#define SHA256_COND_CHK_CTRL_HASH_VAL_COND_CHK_MASK (NBIT1 | NBIT0) +#define SHA256_COND_CHK_CTRL_HASH_VAL_COND_CHK_SHIFT (0) +#define SHA256_COND_CHK_CTRL_STEP_VAL_MASK (NBIT6 | NBIT5 | NBIT4 | NBIT3 | NBIT2) +#define SHA256_COND_CHK_CTRL_STEP_VAL_SHIFT (2) +#define SHA256_COND_CHK_CTRL_COND_CHK_RESULT_MASK (NBIT7) +#define SHA256_COND_CHK_CTRL_COND_CHK_RESULT_SHIFT (7) + +#define SHA256_MOD_DATA_RANGE (SHA256_MEM_BASE+0x14) +#define SHA256_MOD_DATA_RANGE_ST_BYTE_2_ADD_STP_MASK (NBIT24-1) +#define SHA256_MOD_DATA_RANGE_ST_BYTE_2_ADD_STP_SHIFT (0) +#define SHA256_MOD_DATA_RANGE_MOD_DATA_LEN_MASK (NBIT24 | NBIT25| NBIT26) +#define SHA256_MOD_DATA_RANGE_MOD_DATA_LEN_SHIFT (24) + + +#define SHA256_COND_CHK_STS_1 (SHA256_MEM_BASE+0x18) +#define SHA256_COND_CHK_STS_2 (SHA256_MEM_BASE+0x1c) +#define SHA256_DONE_INTR_ENABLE (SHA256_MEM_BASE+0x20) +#define SHA256_DONE_INTR_STS (SHA256_MEM_BASE+0x24) +#define SHA256_TARGET_HASH_H1 (SHA256_MEM_BASE+0x28) +#define SHA256_TARGET_HASH_H2 (SHA256_MEM_BASE+0x2c) +#define SHA256_TARGET_HASH_H3 (SHA256_MEM_BASE+0x30) +#define SHA256_TARGET_HASH_H4 (SHA256_MEM_BASE+0x34) +#define SHA256_TARGET_HASH_H5 (SHA256_MEM_BASE+0x38) +#define SHA256_TARGET_HASH_H6 (SHA256_MEM_BASE+0x3c) +#define SHA256_TARGET_HASH_H7 (SHA256_MEM_BASE+0x40) +#define SHA256_TARGET_HASH_H8 (SHA256_MEM_BASE+0x44) + +/*======*======*======*======*======*=======* +* WINC BIGINT HW Engine Register Definition * +*======*======*======*======*======*========*/ + + +#define BIGINT_ENGINE_ADDR (0x180080ul) +#define BIGINT_VERSION (BIGINT_ENGINE_ADDR + 0x00) + +#define BIGINT_MISC_CTRL (BIGINT_ENGINE_ADDR + 0x04) +#define BIGINT_MISC_CTRL_CTL_START (NBIT0) +#define BIGINT_MISC_CTRL_CTL_RESET (NBIT1) +#define BIGINT_MISC_CTRL_CTL_MSW_FIRST (NBIT2) +#define BIGINT_MISC_CTRL_CTL_SWAP_BYTE_ORDER (NBIT3) +#define BIGINT_MISC_CTRL_CTL_FORCE_BARRETT (NBIT4) +#define BIGINT_MISC_CTRL_CTL_M_PRIME_VALID (NBIT5) + +#define BIGINT_M_PRIME (BIGINT_ENGINE_ADDR + 0x08) + +#define BIGINT_STATUS (BIGINT_ENGINE_ADDR + 0x0C) +#define BIGINT_STATUS_STS_DONE (NBIT0) + +#define BIGINT_CLK_COUNT (BIGINT_ENGINE_ADDR + 0x10) +#define BIGINT_ADDR_X (BIGINT_ENGINE_ADDR + 0x14) +#define BIGINT_ADDR_E (BIGINT_ENGINE_ADDR + 0x18) +#define BIGINT_ADDR_M (BIGINT_ENGINE_ADDR + 0x1C) +#define BIGINT_ADDR_R (BIGINT_ENGINE_ADDR + 0x20) +#define BIGINT_LENGTH (BIGINT_ENGINE_ADDR + 0x24) + +#define BIGINT_IRQ_STS (BIGINT_ENGINE_ADDR + 0x28) +#define BIGINT_IRQ_STS_DONE (NBIT0) +#define BIGINT_IRQ_STS_CHOOSE_MONT (NBIT1) +#define BIGINT_IRQ_STS_M_READ (NBIT2) +#define BIGINT_IRQ_STS_X_READ (NBIT3) +#define BIGINT_IRQ_STS_START (NBIT4) +#define BIGINT_IRQ_STS_PRECOMP_FINISH (NBIT5) + +#define BIGINT_IRQ_MASK (BIGINT_ENGINE_ADDR + 0x2C) +#define BIGINT_IRQ_MASK_CTL_IRQ_MASK_START (NBIT4) + +#define ENABLE_FLIPPING 1 + + + + +#define GET_UINT32(BUF,OFFSET) (((uint32)((BUF)[OFFSET])) | ((uint32)(((BUF)[OFFSET + 1]) << 8)) | \ +((uint32)(((BUF)[OFFSET + 2]) << 16)) | ((uint32)(((BUF)[OFFSET + 3]) << 24))) + +#define PUTU32(VAL32,BUF,OFFSET) \ +do \ +{ \ + (BUF)[OFFSET ] = BYTE_3((VAL32)); \ + (BUF)[OFFSET +1 ] = BYTE_2((VAL32)); \ + (BUF)[OFFSET +2 ] = BYTE_1((VAL32)); \ + (BUF)[OFFSET +3 ] = BYTE_0((VAL32)); \ +}while(0) + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*! +@struct \ + tstrHashContext + +@brief +*/ +typedef struct{ + uint32 au32HashState[M2M_SHA256_DIGEST_LEN/4]; + uint8 au8CurrentBlock[64]; + uint32 u32TotalLength; + uint8 u8InitHashFlag; +}tstrSHA256HashCtxt; + + + +/*======*======*======*======*======*=======* +* SHA256 IMPLEMENTATION * +*======*======*======*======*======*========*/ + +sint8 m2m_crypto_sha256_hash_init(tstrM2mSha256Ctxt *pstrSha256Ctxt) +{ + tstrSHA256HashCtxt *pstrSHA256 = (tstrSHA256HashCtxt*)pstrSha256Ctxt; + if(pstrSHA256 != NULL) + { + m2m_memset((uint8*)pstrSha256Ctxt, 0, sizeof(tstrM2mSha256Ctxt)); + pstrSHA256->u8InitHashFlag = 1; + } + return 0; +} + +sint8 m2m_crypto_sha256_hash_update(tstrM2mSha256Ctxt *pstrSha256Ctxt, uint8 *pu8Data, uint16 u16DataLength) +{ + sint8 s8Ret = M2M_ERR_FAIL; + tstrSHA256HashCtxt *pstrSHA256 = (tstrSHA256HashCtxt*)pstrSha256Ctxt; + if(pstrSHA256 != NULL) + { + uint32 u32ReadAddr; + uint32 u32WriteAddr = SHARED_MEM_BASE; + uint32 u32Addr = u32WriteAddr; + uint32 u32ResidualBytes; + uint32 u32NBlocks; + uint32 u32Offset; + uint32 u32CurrentBlock = 0; + uint8 u8IsDone = 0; + + /* Get the remaining bytes from the previous update (if the length is not block aligned). */ + u32ResidualBytes = pstrSHA256->u32TotalLength % SHA_BLOCK_SIZE; + + /* Update the total data length. */ + pstrSHA256->u32TotalLength += u16DataLength; + + if(u32ResidualBytes != 0) + { + if((u32ResidualBytes + u16DataLength) >= SHA_BLOCK_SIZE) + { + u32Offset = SHA_BLOCK_SIZE - u32ResidualBytes; + m2m_memcpy(&pstrSHA256->au8CurrentBlock[u32ResidualBytes], pu8Data, u32Offset); + pu8Data += u32Offset; + u16DataLength -= u32Offset; + + nm_write_block(u32Addr, pstrSHA256->au8CurrentBlock, SHA_BLOCK_SIZE); + u32Addr += SHA_BLOCK_SIZE; + u32CurrentBlock = 1; + } + else + { + m2m_memcpy(&pstrSHA256->au8CurrentBlock[u32ResidualBytes], pu8Data, u16DataLength); + u16DataLength = 0; + } + } + + /* Get the number of HASH BLOCKs and the residual bytes. */ + u32NBlocks = u16DataLength / SHA_BLOCK_SIZE; + u32ResidualBytes = u16DataLength % SHA_BLOCK_SIZE; + + if(u32NBlocks != 0) + { + nm_write_block(u32Addr, pu8Data, (uint16)(u32NBlocks * SHA_BLOCK_SIZE)); + pu8Data += (u32NBlocks * SHA_BLOCK_SIZE); + } + + u32NBlocks += u32CurrentBlock; + if(u32NBlocks != 0) + { + uint32 u32RegVal = 0; + + nm_write_reg(SHA256_CTRL, u32RegVal); + u32RegVal |= SHA256_CTRL_FORCE_SHA256_QUIT_MASK; + nm_write_reg(SHA256_CTRL, u32RegVal); + + if(pstrSHA256->u8InitHashFlag) + { + pstrSHA256->u8InitHashFlag = 0; + u32RegVal |= SHA256_CTRL_INIT_SHA256_STATE_MASK; + } + + u32ReadAddr = u32WriteAddr + (u32NBlocks * SHA_BLOCK_SIZE); + nm_write_reg(SHA256_DATA_LENGTH, (u32NBlocks * SHA_BLOCK_SIZE)); + nm_write_reg(SHA256_START_RD_ADDR, u32WriteAddr); + nm_write_reg(SHA256_START_WR_ADDR, u32ReadAddr); + + u32RegVal |= SHA256_CTRL_START_CALC_MASK; + + u32RegVal &= ~(0x7 << 8); + u32RegVal |= (2 << 8); + + nm_write_reg(SHA256_CTRL, u32RegVal); + + /* 5. Wait for done_intr */ + while(!u8IsDone) + { + u32RegVal = nm_read_reg(SHA256_DONE_INTR_STS); + u8IsDone = u32RegVal & NBIT0; + } + } + if(u32ResidualBytes != 0) + { + m2m_memcpy(pstrSHA256->au8CurrentBlock, pu8Data, u32ResidualBytes); + } + s8Ret = M2M_SUCCESS; + } + return s8Ret; +} + + +sint8 m2m_crypto_sha256_hash_finish(tstrM2mSha256Ctxt *pstrSha256Ctxt, uint8 *pu8Sha256Digest) +{ + sint8 s8Ret = M2M_ERR_FAIL; + tstrSHA256HashCtxt *pstrSHA256 = (tstrSHA256HashCtxt*)pstrSha256Ctxt; + if(pstrSHA256 != NULL) + { + uint32 u32ReadAddr; + uint32 u32WriteAddr = SHARED_MEM_BASE; + uint32 u32Addr = u32WriteAddr; + uint16 u16Offset; + uint16 u16PaddingLength; + uint16 u16NBlocks = 1; + uint32 u32RegVal = 0; + uint32 u32Idx,u32ByteIdx; + uint32 au32Digest[M2M_SHA256_DIGEST_LEN / 4]; + uint8 u8IsDone = 0; + + nm_write_reg(SHA256_CTRL,u32RegVal); + u32RegVal |= SHA256_CTRL_FORCE_SHA256_QUIT_MASK; + nm_write_reg(SHA256_CTRL,u32RegVal); + + if(pstrSHA256->u8InitHashFlag) + { + pstrSHA256->u8InitHashFlag = 0; + u32RegVal |= SHA256_CTRL_INIT_SHA256_STATE_MASK; + } + + /* Calculate the offset of the last data byte in the current block. */ + u16Offset = (uint16)(pstrSHA256->u32TotalLength % SHA_BLOCK_SIZE); + + /* Add the padding byte 0x80. */ + pstrSHA256->au8CurrentBlock[u16Offset ++] = 0x80; + + /* Calculate the required padding to complete + one Hash Block Size. + */ + u16PaddingLength = SHA_BLOCK_SIZE - u16Offset; + m2m_memset(&pstrSHA256->au8CurrentBlock[u16Offset], 0, u16PaddingLength); + + /* If the padding count is not enough to hold 64-bit representation of + the total input message length, one padding block is required. + */ + if(u16PaddingLength < 8) + { + nm_write_block(u32Addr, pstrSHA256->au8CurrentBlock, SHA_BLOCK_SIZE); + u32Addr += SHA_BLOCK_SIZE; + m2m_memset(pstrSHA256->au8CurrentBlock, 0, SHA_BLOCK_SIZE); + u16NBlocks ++; + } + + /* pack the length at the end of the padding block */ + PUTU32(pstrSHA256->u32TotalLength << 3, pstrSHA256->au8CurrentBlock, (SHA_BLOCK_SIZE - 4)); + + u32ReadAddr = u32WriteAddr + (u16NBlocks * SHA_BLOCK_SIZE); + nm_write_block(u32Addr, pstrSHA256->au8CurrentBlock, SHA_BLOCK_SIZE); + nm_write_reg(SHA256_DATA_LENGTH, (u16NBlocks * SHA_BLOCK_SIZE)); + nm_write_reg(SHA256_START_RD_ADDR, u32WriteAddr); + nm_write_reg(SHA256_START_WR_ADDR, u32ReadAddr); + + u32RegVal |= SHA256_CTRL_START_CALC_MASK; + u32RegVal |= SHA256_CTRL_WR_BACK_HASH_VALUE_MASK; + u32RegVal &= ~(0x7UL << 8); + u32RegVal |= (0x2UL << 8); + + nm_write_reg(SHA256_CTRL,u32RegVal); + + + /* 5. Wait for done_intr */ + while(!u8IsDone) + { + u32RegVal = nm_read_reg(SHA256_DONE_INTR_STS); + u8IsDone = u32RegVal & NBIT0; + } + nm_read_block(u32ReadAddr, (uint8*)au32Digest, 32); + + /* Convert the output words to an array of bytes. + */ + u32ByteIdx = 0; + for(u32Idx = 0; u32Idx < (M2M_SHA256_DIGEST_LEN / 4); u32Idx ++) + { + pu8Sha256Digest[u32ByteIdx ++] = BYTE_3(au32Digest[u32Idx]); + pu8Sha256Digest[u32ByteIdx ++] = BYTE_2(au32Digest[u32Idx]); + pu8Sha256Digest[u32ByteIdx ++] = BYTE_1(au32Digest[u32Idx]); + pu8Sha256Digest[u32ByteIdx ++] = BYTE_0(au32Digest[u32Idx]); + } + s8Ret = M2M_SUCCESS; + } + return s8Ret; +} + + +/*======*======*======*======*======*=======* +* RSA IMPLEMENTATION * +*======*======*======*======*======*========*/ + +static void FlipBuffer(uint8 *pu8InBuffer, uint8 *pu8OutBuffer, uint16 u16BufferSize) +{ + uint16 u16Idx; + for(u16Idx = 0; u16Idx < u16BufferSize; u16Idx ++) + { +#if ENABLE_FLIPPING == 1 + pu8OutBuffer[u16Idx] = pu8InBuffer[u16BufferSize - u16Idx - 1]; +#else + pu8OutBuffer[u16Idx] = pu8InBuffer[u16Idx]; +#endif + } +} + +void BigInt_ModExp +( + uint8 *pu8X, uint16 u16XSize, + uint8 *pu8E, uint16 u16ESize, + uint8 *pu8M, uint16 u16MSize, + uint8 *pu8R, uint16 u16RSize + ) +{ + uint32 u32Reg; + uint8 au8Tmp[780] = {0}; + uint32 u32XAddr = SHARED_MEM_BASE; + uint32 u32MAddr; + uint32 u32EAddr; + uint32 u32RAddr; + uint8 u8EMswBits = 32; + uint32 u32Mprime = 0x7F; + uint16 u16XSizeWords,u16ESizeWords; + uint32 u32Exponent; + + u16XSizeWords = (u16XSize + 3) / 4; + u16ESizeWords = (u16ESize + 3) / 4; + + u32MAddr = u32XAddr + (u16XSizeWords * 4); + u32EAddr = u32MAddr + (u16XSizeWords * 4); + u32RAddr = u32EAddr + (u16ESizeWords * 4); + + /* Reset the core. + */ + u32Reg = 0; + u32Reg |= BIGINT_MISC_CTRL_CTL_RESET; + u32Reg = nm_read_reg(BIGINT_MISC_CTRL); + u32Reg &= ~BIGINT_MISC_CTRL_CTL_RESET; + u32Reg = nm_read_reg(BIGINT_MISC_CTRL); + + nm_write_block(u32RAddr,au8Tmp, u16RSize); + + /* Write Input Operands to Chip Memory. + */ + /*------- X -------*/ + FlipBuffer(pu8X,au8Tmp,u16XSize); + nm_write_block(u32XAddr,au8Tmp,u16XSizeWords * 4); + + /*------- E -------*/ + m2m_memset(au8Tmp, 0, sizeof(au8Tmp)); + FlipBuffer(pu8E, au8Tmp, u16ESize); + nm_write_block(u32EAddr, au8Tmp, u16ESizeWords * 4); + u32Exponent = GET_UINT32(au8Tmp, (u16ESizeWords * 4) - 4); + while((u32Exponent & NBIT31)== 0) + { + u32Exponent <<= 1; + u8EMswBits --; + } + + /*------- M -------*/ + m2m_memset(au8Tmp, 0, sizeof(au8Tmp)); + FlipBuffer(pu8M, au8Tmp, u16XSize); + nm_write_block(u32MAddr, au8Tmp, u16XSizeWords * 4); + + /* Program the addresses of the input operands. + */ + nm_write_reg(BIGINT_ADDR_X, u32XAddr); + nm_write_reg(BIGINT_ADDR_E, u32EAddr); + nm_write_reg(BIGINT_ADDR_M, u32MAddr); + nm_write_reg(BIGINT_ADDR_R, u32RAddr); + + /* Mprime. + */ + nm_write_reg(BIGINT_M_PRIME,u32Mprime); + + /* Length. + */ + u32Reg = (u16XSizeWords & 0xFF); + u32Reg += ((u16ESizeWords & 0xFF) << 8); + u32Reg += (u8EMswBits << 16); + nm_write_reg(BIGINT_LENGTH,u32Reg); + + /* CTRL Register. + */ + u32Reg = nm_read_reg(BIGINT_MISC_CTRL); + u32Reg ^= BIGINT_MISC_CTRL_CTL_START; + u32Reg |= BIGINT_MISC_CTRL_CTL_FORCE_BARRETT; + //u32Reg |= BIGINT_MISC_CTRL_CTL_M_PRIME_VALID; +#if ENABLE_FLIPPING == 0 + u32Reg |= BIGINT_MISC_CTRL_CTL_MSW_FIRST; +#endif + nm_write_reg(BIGINT_MISC_CTRL,u32Reg); + + /* Wait for computation to complete. */ + while(1) + { + u32Reg = nm_read_reg(BIGINT_IRQ_STS); + if(u32Reg & BIGINT_IRQ_STS_DONE) + { + break; + } + } + nm_write_reg(BIGINT_IRQ_STS,0); + m2m_memset(au8Tmp, 0, sizeof(au8Tmp)); + nm_read_block(u32RAddr, au8Tmp, u16RSize); + FlipBuffer(au8Tmp, pu8R, u16RSize); +} + + + +#define MD5_DIGEST_SIZE (16) +#define SHA1_DIGEST_SIZE (20) + +static const uint8 au8TEncodingMD5[] = +{ + 0x30, 0x20, 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86, + 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05, 0x05, 0x00, + 0x04 +}; +/*!< Fixed part of the Encoding T for the MD5 hash algorithm. +*/ + + +static const uint8 au8TEncodingSHA1[] = +{ + 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, + 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04 +}; +/*!< Fixed part of the Encoding T for the SHA-1 hash algorithm. +*/ + + +static const uint8 au8TEncodingSHA2[] = +{ + 0x30, 0x31, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, + 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, + 0x00, 0x04 +}; +/*!< Fixed part of the Encoding T for the SHA-2 hash algorithm. +*/ + + +sint8 m2m_crypto_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash, + uint16 u16HashLength, uint8 *pu8RsaSignature) +{ + sint8 s8Ret = M2M_RSA_SIGN_FAIL; + + if((pu8N != NULL) && (pu8E != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL)) + { + uint16 u16TLength, u16TEncodingLength; + uint8 *pu8T; + uint8 au8EM[512]; + + /* Selection of correct T Encoding based on the hash size. + */ + if(u16HashLength == MD5_DIGEST_SIZE) + { + pu8T = (uint8*)au8TEncodingMD5; + u16TEncodingLength = sizeof(au8TEncodingMD5); + } + else if(u16HashLength == SHA1_DIGEST_SIZE) + { + pu8T = (uint8*)au8TEncodingSHA1; + u16TEncodingLength = sizeof(au8TEncodingSHA1); + } + else + { + pu8T = (uint8*)au8TEncodingSHA2; + u16TEncodingLength = sizeof(au8TEncodingSHA2); + } + u16TLength = u16TEncodingLength + 1 + u16HashLength; + + /* If emLen < tLen + 11. + */ + if(u16NSize >= (u16TLength + 11)) + { + uint32 u32PSLength,u32Idx = 0; + + /* + RSA verification + */ + BigInt_ModExp(pu8RsaSignature, u16NSize, pu8E, u16ESize, pu8N, u16NSize, au8EM, u16NSize); + + u32PSLength = u16NSize - u16TLength - 3; + + /* + The calculated EM must match the following pattern. + *======*======*======*======*======* + * 0x00 || 0x01 || PS || 0x00 || T * + *======*======*======*======*======* + Where PS is all 0xFF + T is defined based on the hash algorithm. + */ + if((au8EM[0] == 0x00) && (au8EM[1] == 0x01)) + { + for(u32Idx = 2; au8EM[u32Idx] == 0xFF; u32Idx ++); + if(u32Idx == (u32PSLength + 2)) + { + if(au8EM[u32Idx ++] == 0x00) + { + if(!m2m_memcmp(&au8EM[u32Idx], pu8T, u16TEncodingLength)) + { + u32Idx += u16TEncodingLength; + if(au8EM[u32Idx ++] == u16HashLength) + s8Ret = m2m_memcmp(&au8EM[u32Idx], pu8SignedMsgHash, u16HashLength); + } + } + } + } + } + } + return s8Ret; +} + + +sint8 m2m_crypto_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash, + uint16 u16HashLength, uint8 *pu8RsaSignature) +{ + sint8 s8Ret = M2M_RSA_SIGN_FAIL; + + if((pu8N != NULL) && (pu8d != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL)) + { + uint16 u16TLength, u16TEncodingLength; + uint8 *pu8T; + uint8 au8EM[512]; + + /* Selection of correct T Encoding based on the hash size. + */ + if(u16HashLength == MD5_DIGEST_SIZE) + { + pu8T = (uint8*)au8TEncodingMD5; + u16TEncodingLength = sizeof(au8TEncodingMD5); + } + else if(u16HashLength == SHA1_DIGEST_SIZE) + { + pu8T = (uint8*)au8TEncodingSHA1; + u16TEncodingLength = sizeof(au8TEncodingSHA1); + } + else + { + pu8T = (uint8*)au8TEncodingSHA2; + u16TEncodingLength = sizeof(au8TEncodingSHA2); + } + u16TLength = u16TEncodingLength + 1 + u16HashLength; + + /* If emLen < tLen + 11. + */ + if(u16NSize >= (u16TLength + 11)) + { + uint16 u16PSLength = 0; + uint16 u16Offset = 0; + + /* + The calculated EM must match the following pattern. + *======*======*======*======*======* + * 0x00 || 0x01 || PS || 0x00 || T * + *======*======*======*======*======* + Where PS is all 0xFF + T is defined based on the hash algorithm. + */ + au8EM[u16Offset ++] = 0; + au8EM[u16Offset ++] = 1; + u16PSLength = u16NSize - u16TLength - 3; + m2m_memset(&au8EM[u16Offset], 0xFF, u16PSLength); + u16Offset += u16PSLength; + au8EM[u16Offset ++] = 0; + m2m_memcpy(&au8EM[u16Offset], pu8T, u16TEncodingLength); + u16Offset += u16TEncodingLength; + au8EM[u16Offset ++] = u16HashLength; + m2m_memcpy(&au8EM[u16Offset], pu8SignedMsgHash, u16HashLength); + + /* + RSA Signature Generation + */ + BigInt_ModExp(au8EM, u16NSize, pu8d, u16dSize, pu8N, u16NSize, pu8RsaSignature, u16NSize); + s8Ret = M2M_RSA_SIGN_OK; + } + } + return s8Ret; +} + +#endif /* CONF_CRYPTO */ + +#ifdef CONF_CRYPTO_SOFT + +typedef struct { + tpfAppCryproCb pfAppCryptoCb; + uint8 * pu8Digest; + uint8 * pu8Rsa; + uint8 u8CryptoBusy; +}tstrCryptoCtxt; + +typedef struct { + uint8 au8N[M2M_MAX_RSA_LEN]; + uint8 au8E[M2M_MAX_RSA_LEN]; + uint8 au8Hash[M2M_SHA256_DIGEST_LEN]; + uint16 u16Nsz; + uint16 u16Esz; + uint16 u16Hsz; + uint8 _pad16_[2]; +}tstrRsaPayload; + +static tstrCryptoCtxt gstrCryptoCtxt; + + +/** +* @fn m2m_crypto_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +* @brief WiFi call back function +* @param [in] u8OpCode +* HIF Opcode type. +* @param [in] u16DataSize +* HIF data length. +* @param [in] u32Addr +* HIF address. +* @author +* @date +* @version 1.0 +*/ +static void m2m_crypto_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +{ + sint8 ret = M2M_SUCCESS; + gstrCryptoCtxt.u8CryptoBusy = 0; + if(u8OpCode == M2M_CRYPTO_RESP_SHA256_INIT) + { + tstrM2mSha256Ctxt strCtxt; + if (hif_receive(u32Addr, (uint8*) &strCtxt,sizeof(tstrM2mSha256Ctxt), 0) == M2M_SUCCESS) + { + tstrCyptoResp strResp; + if(hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt), (uint8*) &strResp,sizeof(tstrCyptoResp), 1) == M2M_SUCCESS) + { + if (gstrCryptoCtxt.pfAppCryptoCb) + gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,&strCtxt); + } + } + } + else if(u8OpCode == M2M_CRYPTO_RESP_SHA256_UPDATE) + { + tstrM2mSha256Ctxt strCtxt; + if (hif_receive(u32Addr, (uint8*) &strCtxt,sizeof(tstrM2mSha256Ctxt), 0) == M2M_SUCCESS) + { + tstrCyptoResp strResp; + if (hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt), (uint8*) &strResp,sizeof(tstrCyptoResp), 1) == M2M_SUCCESS) + { + if (gstrCryptoCtxt.pfAppCryptoCb) + gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,&strCtxt); + } + } + + } + else if(u8OpCode == M2M_CRYPTO_RESP_SHA256_FINSIH) + { + tstrCyptoResp strResp; + if (hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt), (uint8*) &strResp,sizeof(tstrCyptoResp), 0) == M2M_SUCCESS) + { + if (hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt) + sizeof(tstrCyptoResp), (uint8*)gstrCryptoCtxt.pu8Digest,M2M_SHA256_DIGEST_LEN, 1) == M2M_SUCCESS) + { + if (gstrCryptoCtxt.pfAppCryptoCb) + gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,gstrCryptoCtxt.pu8Digest); + + } + } + } + else if(u8OpCode == M2M_CRYPTO_RESP_RSA_SIGN_GEN) + { + tstrCyptoResp strResp; + if (hif_receive(u32Addr + sizeof(tstrRsaPayload), (uint8*)&strResp,sizeof(tstrCyptoResp), 0) == M2M_SUCCESS) + { + if (hif_receive(u32Addr + sizeof(tstrRsaPayload) + sizeof(tstrCyptoResp), (uint8*)gstrCryptoCtxt.pu8Rsa,M2M_MAX_RSA_LEN, 0) == M2M_SUCCESS) + { + if (gstrCryptoCtxt.pfAppCryptoCb) + gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,gstrCryptoCtxt.pu8Rsa); + } + } + } + else if(u8OpCode == M2M_CRYPTO_RESP_RSA_SIGN_VERIFY) + { + tstrCyptoResp strResp; + if (hif_receive(u32Addr + sizeof(tstrRsaPayload), (uint8*)&strResp,sizeof(tstrCyptoResp), 1) == M2M_SUCCESS) + { + if (gstrCryptoCtxt.pfAppCryptoCb) + gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,NULL); + } + } + else + { + M2M_ERR("u8Code %d ??\n",u8OpCode); + } + +} +/*! +@fn \ + sint8 m2m_crypto_init(); + +@brief crypto initialization + +@param[in] pfAppCryproCb + +*/ +sint8 m2m_crypto_init(tpfAppCryproCb pfAppCryproCb) +{ + sint8 ret = M2M_ERR_FAIL; + m2m_memset((uint8*)&gstrCryptoCtxt,0,sizeof(tstrCryptoCtxt)); + if(pfAppCryproCb != NULL) + { + gstrCryptoCtxt.pfAppCryptoCb = pfAppCryproCb; + ret = hif_register_cb(M2M_REQ_GROUP_CRYPTO,m2m_crypto_cb); + } + return ret; +} +/*! +@fn \ + sint8 m2m_sha256_hash_init(tstrM2mSha256Ctxt *psha256Ctxt); + +@brief SHA256 hash initialization + +@param[in] psha256Ctxt + Pointer to a sha256 context allocated by the caller. +*/ +sint8 m2m_crypto_sha256_hash_init(tstrM2mSha256Ctxt *psha256Ctxt) +{ + sint8 ret = M2M_ERR_FAIL; + if((psha256Ctxt != NULL)&&(!gstrCryptoCtxt.u8CryptoBusy)) + { + ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_SHA256_INIT|M2M_REQ_DATA_PKT,(uint8*)psha256Ctxt,sizeof(tstrM2mSha256Ctxt),NULL,0,0); + } + return ret; +} + + +/*! +@fn \ + sint8 m2m_sha256_hash_update(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Data, uint16 u16DataLength); + +@brief SHA256 hash update + +@param [in] psha256Ctxt + Pointer to the sha256 context. + +@param [in] pu8Data + Buffer holding the data submitted to the hash. + +@param [in] u16DataLength + Size of the data bufefr in bytes. +*/ +sint8 m2m_crypto_sha256_hash_update(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Data, uint16 u16DataLength) +{ + sint8 ret = M2M_ERR_FAIL; + if((!gstrCryptoCtxt.u8CryptoBusy) && (psha256Ctxt != NULL) && (pu8Data != NULL) && (u16DataLength < M2M_SHA256_MAX_DATA)) + { + ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_SHA256_UPDATE|M2M_REQ_DATA_PKT,(uint8*)psha256Ctxt,sizeof(tstrM2mSha256Ctxt),pu8Data,u16DataLength,sizeof(tstrM2mSha256Ctxt) + sizeof(tstrCyptoResp)); + } + return ret; + +} + + +/*! +@fn \ + sint8 m2m_sha256_hash_finish(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Sha256Digest); + +@brief SHA256 hash finalization + +@param[in] psha256Ctxt + Pointer to a sha256 context allocated by the caller. + +@param [in] pu8Sha256Digest + Buffer allocated by the caller which will hold the resultant SHA256 Digest. It must be allocated no less than M2M_SHA256_DIGEST_LEN. +*/ +sint8 m2m_crypto_sha256_hash_finish(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Sha256Digest) +{ + sint8 ret = M2M_ERR_FAIL; + if((!gstrCryptoCtxt.u8CryptoBusy) && (psha256Ctxt != NULL) && (pu8Sha256Digest != NULL)) + { + gstrCryptoCtxt.pu8Digest = pu8Sha256Digest; + ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_SHA256_FINSIH|M2M_REQ_DATA_PKT,(uint8*)psha256Ctxt,sizeof(tstrM2mSha256Ctxt),NULL,0,0); + } + return ret; +} + + + + +/*! +@fn \ + sint8 m2m_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash, \ + uint16 u16HashLength, uint8 *pu8RsaSignature); + +@brief RSA Signature Verification + + The function shall request the RSA Signature verification from the WINC Firmware for the given message. The signed message shall be + compressed to the corresponding hash algorithm before calling this function. + The hash type is identified by the given hash length. For example, if the hash length is 32 bytes, then it is SHA256. + +@param[in] pu8N + RSA Key modulus n. + +@param[in] u16NSize + Size of the RSA modulus n in bytes. + +@param[in] pu8E + RSA public exponent. + +@param[in] u16ESize + Size of the RSA public exponent in bytes. + +@param[in] pu8SignedMsgHash + The hash digest of the signed message. + +@param[in] u16HashLength + The length of the hash digest. + +@param[out] pu8RsaSignature + Signature value to be verified. +*/ + + +sint8 m2m_crypto_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash, + uint16 u16HashLength, uint8 *pu8RsaSignature) +{ + sint8 ret = M2M_ERR_FAIL; + if((!gstrCryptoCtxt.u8CryptoBusy) && (pu8N != NULL) && (pu8E != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL) + && (u16NSize != 0) && (u16ESize != 0) && (u16HashLength != 0) && (pu8RsaSignature != NULL) ) + + { + tstrRsaPayload strRsa = {0}; + + m2m_memcpy(strRsa.au8N,pu8N,u16NSize); + m2m_memcpy(strRsa.au8E,pu8E,u16ESize); + m2m_memcpy(strRsa.au8Hash,pu8SignedMsgHash,u16HashLength); + + strRsa.u16Esz = u16ESize; + strRsa.u16Hsz = u16HashLength; + strRsa.u16Nsz = u16NSize; + + ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_RSA_SIGN_VERIFY|M2M_REQ_DATA_PKT,(uint8*)&strRsa,sizeof(tstrRsaPayload),NULL,0,0); + + } + return ret; +} + + +/*! +@fn \ + sint8 m2m_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash, \ + uint16 u16HashLength, uint8 *pu8RsaSignature); + +@brief RSA Signature Generation + + The function shall request the RSA Signature generation from the WINC Firmware for the given message. The signed message shall be + compressed to the corresponding hash algorithm before calling this function. + The hash type is identified by the given hash length. For example, if the hash length is 32 bytes, then it is SHA256. + +@param[in] pu8N + RSA Key modulus n. + +@param[in] u16NSize + Size of the RSA modulus n in bytes. + +@param[in] pu8d + RSA private exponent. + +@param[in] u16dSize + Size of the RSA private exponent in bytes. + +@param[in] pu8SignedMsgHash + The hash digest of the signed message. + +@param[in] u16HashLength + The length of the hash digest. + +@param[out] pu8RsaSignature + Pointer to a user buffer allocated by teh caller shall hold the generated signature. +*/ +sint8 m2m_crypto_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash, + uint16 u16HashLength, uint8 *pu8RsaSignature) +{ + sint8 ret = M2M_ERR_FAIL; + if((!gstrCryptoCtxt.u8CryptoBusy) && (pu8N != NULL) && (pu8d != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL) + && (u16NSize != 0) && (u16dSize != 0) && (u16HashLength != 0) && (pu8RsaSignature != NULL)) + + { + tstrRsaPayload strRsa = {0}; + + m2m_memcpy(strRsa.au8N,pu8N,u16NSize); + m2m_memcpy(strRsa.au8E,pu8d,u16dSize); + m2m_memcpy(strRsa.au8Hash,pu8SignedMsgHash,u16HashLength); + + strRsa.u16Esz = u16dSize; + strRsa.u16Hsz = u16HashLength; + strRsa.u16Nsz = u16NSize; + + gstrCryptoCtxt.pu8Rsa = pu8RsaSignature; + ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_RSA_SIGN_GEN|M2M_REQ_DATA_PKT,(uint8*)&strRsa,sizeof(tstrRsaPayload),NULL,0,0); + + } + return ret; +} + +#endif \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_hif.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_hif.c new file mode 100644 index 0000000..f0ed93a --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_hif.c @@ -0,0 +1,767 @@ +/** + * + * \file + * + * \brief This module contains M2M host interface APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "common/include/nm_common.h" +#include "driver/source/nmbus.h" +#include "bsp/include/nm_bsp.h" +#include "m2m_hif.h" +#include "driver/include/m2m_types.h" +#include "driver/source/nmasic.h" +#include "driver/include/m2m_periph.h" + +#if (defined NM_EDGE_INTERRUPT)&&(defined NM_LEVEL_INTERRUPT) +#error "only one type of interrupt NM_EDGE_INTERRUPT,NM_LEVEL_INTERRUPT" +#endif + +#if !((defined NM_EDGE_INTERRUPT)||(defined NM_LEVEL_INTERRUPT)) +#error "define interrupt type NM_EDGE_INTERRUPT,NM_LEVEL_INTERRUPT" +#endif + +#ifndef CORTUS_APP +#define NMI_AHB_DATA_MEM_BASE 0x30000 +#define NMI_AHB_SHARE_MEM_BASE 0xd0000 + +#define WIFI_HOST_RCV_CTRL_0 (0x1070) +#define WIFI_HOST_RCV_CTRL_1 (0x1084) +#define WIFI_HOST_RCV_CTRL_2 (0x1078) +#define WIFI_HOST_RCV_CTRL_3 (0x106c) +#define WIFI_HOST_RCV_CTRL_4 (0x150400) +#define WIFI_HOST_RCV_CTRL_5 (0x1088) + +typedef struct { + uint8 u8ChipMode; + uint8 u8ChipSleep; + uint8 u8HifRXDone; + uint8 u8Interrupt; + uint32 u32RxAddr; + uint32 u32RxSize; + tpfHifCallBack pfWifiCb; + tpfHifCallBack pfIpCb; + tpfHifCallBack pfOtaCb; + tpfHifCallBack pfSigmaCb; + tpfHifCallBack pfHifCb; + tpfHifCallBack pfCryptoCb; + tpfHifCallBack pfSslCb; +}tstrHifContext; + +volatile tstrHifContext gstrHifCxt; + +static void isr(void) +{ + gstrHifCxt.u8Interrupt++; +#ifdef NM_LEVEL_INTERRUPT + nm_bsp_interrupt_ctrl(0); +#endif +} +static sint8 hif_set_rx_done(void) +{ + uint32 reg; + sint8 ret = M2M_SUCCESS; + + gstrHifCxt.u8HifRXDone = 0; +#ifdef NM_EDGE_INTERRUPT + nm_bsp_interrupt_ctrl(1); +#endif + ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0,®); + if(ret != M2M_SUCCESS)goto ERR1; + /* Set RX Done */ + reg |= NBIT1; + ret = nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg); + if(ret != M2M_SUCCESS)goto ERR1; +#ifdef NM_LEVEL_INTERRUPT + nm_bsp_interrupt_ctrl(1); +#endif +ERR1: + return ret; + +} +/** +* @fn static void m2m_hif_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +* @brief WiFi call back function +* @param [in] u8OpCode +* HIF Opcode type. +* @param [in] u16DataSize +* HIF data length. +* @param [in] u32Addr +* HIF address. +* @param [in] grp +* HIF group type. +* @author +* @date +* @version 1.0 +*/ +static void m2m_hif_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)u8OpCode; + (void)u16DataSize; + (void)u32Addr; +#endif +} +/** +* @fn NMI_API sint8 hif_chip_wake(void); +* @brief To Wakeup the chip. +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +sint8 hif_chip_wake(void) +{ + sint8 ret = M2M_SUCCESS; + if(gstrHifCxt.u8HifRXDone) + { + /*chip already wake for the rx not done no need to send wake request*/ + return ret; + } + if(gstrHifCxt.u8ChipSleep == 0) + { + if(gstrHifCxt.u8ChipMode != M2M_NO_PS) + { + ret = chip_wake(); + if(ret != M2M_SUCCESS)goto ERR1; + } + else + { + } + } + gstrHifCxt.u8ChipSleep++; +ERR1: + return ret; +} +/*! +@fn \ + NMI_API void hif_set_sleep_mode(uint8 u8Pstype); + +@brief + Set the sleep mode of the HIF layer. + +@param [in] u8Pstype + Sleep mode. + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ + +void hif_set_sleep_mode(uint8 u8Pstype) +{ + gstrHifCxt.u8ChipMode = u8Pstype; +} +/*! +@fn \ + NMI_API uint8 hif_get_sleep_mode(void); + +@brief + Get the sleep mode of the HIF layer. + +@return + The function SHALL return the sleep mode of the HIF layer. +*/ + +uint8 hif_get_sleep_mode(void) +{ + return gstrHifCxt.u8ChipMode; +} + +/** +* @fn NMI_API sint8 hif_chip_sleep_sc(void); +* @brief To clear the chip sleep but keep the chip sleep +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +sint8 hif_chip_sleep_sc(void) +{ + if(gstrHifCxt.u8ChipSleep >= 1) + { + gstrHifCxt.u8ChipSleep--; + } + return M2M_SUCCESS; +} +/** +* @fn NMI_API sint8 hif_chip_sleep(void); +* @brief To make the chip sleep. +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +sint8 hif_chip_sleep(void) +{ + sint8 ret = M2M_SUCCESS; + + if(gstrHifCxt.u8ChipSleep >= 1) + { + gstrHifCxt.u8ChipSleep--; + } + + if(gstrHifCxt.u8ChipSleep == 0) + { + if(gstrHifCxt.u8ChipMode != M2M_NO_PS) + { + ret = chip_sleep(); + if(ret != M2M_SUCCESS)goto ERR1; + + } + else + { + } + } +ERR1: + return ret; +} +/** +* @fn NMI_API sint8 hif_init(void * arg); +* @brief To initialize HIF layer. +* @param [in] arg +* Pointer to the arguments. +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +sint8 hif_init(void * arg) +{ +#ifdef ARDUINO + (void)arg; // Silence "unused" warning +#endif + m2m_memset((uint8*)&gstrHifCxt,0,sizeof(tstrHifContext)); + nm_bsp_register_isr(isr); + hif_register_cb(M2M_REQ_GROUP_HIF,m2m_hif_cb); + return M2M_SUCCESS; +} +/** +* @fn NMI_API sint8 hif_deinit(void * arg); +* @brief To De-initialize HIF layer. +* @param [in] arg +* Pointer to the arguments. +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ +sint8 hif_deinit(void * arg) +{ +#ifdef ARDUINO + (void)arg; // Silence "unused" warning +#endif + sint8 ret = M2M_SUCCESS; + ret = hif_chip_wake(); + m2m_memset((uint8*)&gstrHifCxt,0,sizeof(tstrHifContext)); + return ret; +} +/** +* @fn NMI_API sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, + uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) +* @brief Send packet using host interface. + +* @param [in] u8Gid +* Group ID. +* @param [in] u8Opcode +* Operation ID. +* @param [in] pu8CtrlBuf +* Pointer to the Control buffer. +* @param [in] u16CtrlBufSize + Control buffer size. +* @param [in] u16DataOffset + Packet Data offset. +* @param [in] pu8DataBuf +* Packet buffer Allocated by the caller. +* @param [in] u16DataSize + Packet buffer size (including the HIF header). +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, + uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) +{ + sint8 ret = M2M_ERR_SEND; + volatile tstrHifHdr strHif; + + strHif.u8Opcode = u8Opcode&(~NBIT7); + strHif.u8Gid = u8Gid; + strHif.u16Length = M2M_HIF_HDR_OFFSET; + if(pu8DataBuf != NULL) + { + strHif.u16Length += u16DataOffset + u16DataSize; + } + else + { + strHif.u16Length += u16CtrlBufSize; + } + ret = hif_chip_wake(); + if(ret == M2M_SUCCESS) + { + volatile uint32 reg, dma_addr = 0; + volatile uint16 cnt = 0; +//#define OPTIMIZE_BUS +/*please define in firmware also*/ +#ifndef OPTIMIZE_BUS + reg = 0UL; + reg |= (uint32)u8Gid; + reg |= ((uint32)u8Opcode<<8); + reg |= ((uint32)strHif.u16Length<<16); + ret = nm_write_reg(NMI_STATE_REG,reg); + if(M2M_SUCCESS != ret) goto ERR1; + + reg = 0UL; + reg |= NBIT1; + ret = nm_write_reg(WIFI_HOST_RCV_CTRL_2, reg); + if(M2M_SUCCESS != ret) goto ERR1; +#else + reg = 0UL; + reg |= NBIT1; + reg |= ((u8Opcode & NBIT7) ? (NBIT2):(0)); /*Data = 1 or config*/ + reg |= (u8Gid == M2M_REQ_GROUP_IP) ? (NBIT3):(0); /*IP = 1 or non IP*/ + reg |= ((uint32)strHif.u16Length << 4); /*length of pkt max = 4096*/ + ret = nm_write_reg(WIFI_HOST_RCV_CTRL_2, reg); + if(M2M_SUCCESS != ret) goto ERR1; +#endif + dma_addr = 0; + + for(cnt = 0; cnt < 1000; cnt ++) + { + ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_2,(uint32 *)®); + if(ret != M2M_SUCCESS) break; + /* + * If it takes too long to get a response, the slow down to + * avoid back-to-back register read operations. + */ + if(cnt >= 500) { + if(cnt < 501) { + M2M_INFO("Slowing down...\n"); + } + nm_bsp_sleep(1); + } + if (!(reg & NBIT1)) + { + ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_4,(uint32 *)&dma_addr); + if(ret != M2M_SUCCESS) { + /*in case of read error clear the DMA address and return error*/ + dma_addr = 0; + goto ERR1; + } + /*in case of success break */ + break; + } + } + + if (dma_addr != 0) + { + volatile uint32 u32CurrAddr; + u32CurrAddr = dma_addr; + strHif.u16Length=NM_BSP_B_L_16(strHif.u16Length); + ret = nm_write_block(u32CurrAddr, (uint8*)&strHif, M2M_HIF_HDR_OFFSET); + if(M2M_SUCCESS != ret) goto ERR1; + u32CurrAddr += M2M_HIF_HDR_OFFSET; + if(pu8CtrlBuf != NULL) + { + ret = nm_write_block(u32CurrAddr, pu8CtrlBuf, u16CtrlBufSize); + if(M2M_SUCCESS != ret) goto ERR1; + u32CurrAddr += u16CtrlBufSize; + } + if(pu8DataBuf != NULL) + { + u32CurrAddr += (u16DataOffset - u16CtrlBufSize); + ret = nm_write_block(u32CurrAddr, pu8DataBuf, u16DataSize); + if(M2M_SUCCESS != ret) goto ERR1; + u32CurrAddr += u16DataSize; + } + + reg = dma_addr << 2; + reg |= NBIT1; + ret = nm_write_reg(WIFI_HOST_RCV_CTRL_3, reg); + if(M2M_SUCCESS != ret) goto ERR1; + } + else + { + ret = hif_chip_sleep(); + M2M_DBG("Failed to alloc rx size %d\r",ret); + ret = M2M_ERR_MEM_ALLOC; + goto ERR2; + } + + } + else + { + M2M_ERR("(HIF)Fail to wakup the chip\n"); + goto ERR2; + } + /*actual sleep ret = M2M_SUCCESS*/ + ret = hif_chip_sleep(); + return ret; +ERR1: + /*reset the count but no actual sleep as it already bus error*/ + hif_chip_sleep_sc(); +ERR2: + /*logical error*/ + return ret; +} + +#ifdef ARDUINO +volatile uint8 hif_small_xfer = 0; +#endif + +/** +* @fn hif_isr +* @brief Host interface interrupt service routine +* @author M. Abdelmawla +* @date 15 July 2012 +* @return 1 in case of interrupt received else 0 will be returned +* @version 1.0 +*/ +static sint8 hif_isr(void) +{ + sint8 ret = M2M_SUCCESS; + volatile uint32 reg; + volatile tstrHifHdr strHif; + +#ifdef ARDUINO + ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, (uint32*)®); +#else + ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, ®); +#endif + if(M2M_SUCCESS == ret) + { + if(reg & 0x1) /* New interrupt has been received */ + { + uint16 size; + + nm_bsp_interrupt_ctrl(0); + /*Clearing RX interrupt*/ + reg &= ~NBIT0; + ret = nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg); + if(ret != M2M_SUCCESS)goto ERR1; + gstrHifCxt.u8HifRXDone = 1; + size = (uint16)((reg >> 2) & 0xfff); + if (size > 0) { + uint32 address = 0; + /** + start bus transfer + **/ + ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_1, &address); + if(M2M_SUCCESS != ret) + { + M2M_ERR("(hif) WIFI_HOST_RCV_CTRL_1 bus fail\n"); + nm_bsp_interrupt_ctrl(1); + goto ERR1; + } + gstrHifCxt.u32RxAddr = address; + gstrHifCxt.u32RxSize = size; + ret = nm_read_block(address, (uint8*)&strHif, sizeof(tstrHifHdr)); + strHif.u16Length = NM_BSP_B_L_16(strHif.u16Length); + if(M2M_SUCCESS != ret) + { + M2M_ERR("(hif) address bus fail\n"); + nm_bsp_interrupt_ctrl(1); + goto ERR1; + } + if(strHif.u16Length != size) + { + if((size - strHif.u16Length) > 4) + { + M2M_ERR("(hif) Corrupted packet Size = %u \n", + size, strHif.u16Length, strHif.u8Gid, strHif.u8Opcode); + nm_bsp_interrupt_ctrl(1); + ret = M2M_ERR_BUS_FAIL; + goto ERR1; + } + } + + if(M2M_REQ_GROUP_WIFI == strHif.u8Gid) + { + if(gstrHifCxt.pfWifiCb) + gstrHifCxt.pfWifiCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); + else +#ifdef ARDUINO + { +#endif + M2M_ERR("WIFI callback is not registered\n"); +#ifdef ARDUINO + } +#endif + } + else if(M2M_REQ_GROUP_IP == strHif.u8Gid) + { + if(gstrHifCxt.pfIpCb) + gstrHifCxt.pfIpCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); + else +#ifdef ARDUINO + { +#endif + M2M_ERR("Scoket callback is not registered\n"); +#ifdef ARDUINO + } +#endif + } + else if(M2M_REQ_GROUP_OTA == strHif.u8Gid) + { + if(gstrHifCxt.pfOtaCb) + gstrHifCxt.pfOtaCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); + else +#ifdef ARDUINO + { +#endif + M2M_ERR("Ota callback is not registered\n"); +#ifdef ARDUINO + } +#endif + } + else if(M2M_REQ_GROUP_CRYPTO == strHif.u8Gid) + { + if(gstrHifCxt.pfCryptoCb) + gstrHifCxt.pfCryptoCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); + + else +#ifdef ARDUINO + { +#endif + M2M_ERR("Crypto callback is not registered\n"); +#ifdef ARDUINO + } +#endif + } + else if(M2M_REQ_GROUP_SIGMA == strHif.u8Gid) + { + if(gstrHifCxt.pfSigmaCb) + gstrHifCxt.pfSigmaCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); + else +#ifdef ARDUINO + { +#endif + M2M_ERR("Sigma callback is not registered\n"); +#ifdef ARDUINO + } +#endif + } + else if(M2M_REQ_GROUP_SSL == strHif.u8Gid) + { + if(gstrHifCxt.pfSslCb) + gstrHifCxt.pfSslCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); + } + else + { + M2M_ERR("(hif) invalid group ID\n"); + ret = M2M_ERR_BUS_FAIL; + goto ERR1; + } +#ifdef ARDUINO + if(hif_small_xfer) + { + /*Pause SPI transfer*/ + return ret; + } +#endif + if(gstrHifCxt.u8HifRXDone) + { + M2M_ERR("(hif) host app didn't set RX Done <%u><%X>\n", strHif.u8Gid, strHif.u8Opcode); + ret = hif_set_rx_done(); + if(ret != M2M_SUCCESS) goto ERR1; + } + } + else + { + M2M_ERR("(hif) Wrong Size\n"); + ret = M2M_ERR_RCV; + goto ERR1; + } + } + else + { +#ifndef WIN32 + M2M_ERR("(hif) False interrupt %lx",reg); + ret = M2M_ERR_FAIL; + goto ERR1; +#else +#endif + } + } + else + { + M2M_ERR("(hif) Fail to Read interrupt reg\n"); + goto ERR1; + } + +ERR1: + return ret; +} + +#ifdef ARDUINO +void Socket_ReadSocketData_Small(void); +#endif + +/** +* @fn hif_handle_isr(void) +* @brief Handle interrupt received from NMC1500 firmware. +* @return The function SHALL return 0 for success and a negative value otherwise. +*/ + +sint8 hif_handle_isr(void) +{ + sint8 ret = M2M_SUCCESS; + +#ifdef ARDUINO + if(hif_small_xfer) { + /*SPI protocol paused to allow small transfer*/ + Socket_ReadSocketData_Small(); + return ret; + } +#endif + + while (gstrHifCxt.u8Interrupt) { + /*must be at that place because of the race of interrupt increment and that decrement*/ + /*when the interrupt enabled*/ + gstrHifCxt.u8Interrupt--; + while(1) + { + ret = hif_isr(); +#ifdef ARDUINO + if(hif_small_xfer) { + return ret; + } +#endif + if(ret == M2M_SUCCESS) { + /*we will try forever untill we get that interrupt*/ + /*Fail return errors here due to bus errors (reading expected values)*/ + break; + } else { + M2M_ERR("(HIF) Fail to handle interrupt %d try Again..\n",ret); + } + } + } + + return ret; +} +/* +* @fn hif_receive +* @brief Host interface interrupt serviece routine +* @param [in] u32Addr +* Receive start address +* @param [out] pu8Buf +* Pointer to receive buffer. Allocated by the caller +* @param [in] u16Sz +* Receive buffer size +* @param [in] isDone +* If you don't need any more packets send True otherwise send false +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ +sint8 hif_receive(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz, uint8 isDone) +{ + sint8 ret = M2M_SUCCESS; + if((u32Addr == 0)||(pu8Buf == NULL) || (u16Sz == 0)) + { + if(isDone) + { + /* set RX done */ + ret = hif_set_rx_done(); + } + else + { + ret = M2M_ERR_FAIL; + M2M_ERR(" hif_receive: Invalid argument\n"); + } + goto ERR1; + } + + if(u16Sz > gstrHifCxt.u32RxSize) + { + ret = M2M_ERR_FAIL; + M2M_ERR("APP Requested Size is larger than the recived buffer size <%u><%lu>\n",u16Sz, gstrHifCxt.u32RxSize); + goto ERR1; + } + if((u32Addr < gstrHifCxt.u32RxAddr)||((u32Addr + u16Sz)>(gstrHifCxt.u32RxAddr + gstrHifCxt.u32RxSize))) + { + ret = M2M_ERR_FAIL; + M2M_ERR("APP Requested Address beyond the recived buffer address and length\n"); + goto ERR1; + } + + /* Receive the payload */ + ret = nm_read_block(u32Addr, pu8Buf, u16Sz); + if(ret != M2M_SUCCESS)goto ERR1; + + /* check if this is the last packet */ + if((((gstrHifCxt.u32RxAddr + gstrHifCxt.u32RxSize) - (u32Addr + u16Sz)) <= 0) || isDone) + { + /* set RX done */ + ret = hif_set_rx_done(); + } + +ERR1: + return ret; +} + +/** +* @fn hif_register_cb +* @brief To set Callback function for every compantent Component +* @param [in] u8Grp +* Group to which the Callback function should be set. +* @param [in] fn +* function to be set +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +sint8 hif_register_cb(uint8 u8Grp,tpfHifCallBack fn) +{ + sint8 ret = M2M_SUCCESS; + switch(u8Grp) + { + case M2M_REQ_GROUP_IP: + gstrHifCxt.pfIpCb = fn; + break; + case M2M_REQ_GROUP_WIFI: + gstrHifCxt.pfWifiCb = fn; + break; + case M2M_REQ_GROUP_OTA: + gstrHifCxt.pfOtaCb = fn; + break; + case M2M_REQ_GROUP_HIF: + gstrHifCxt.pfHifCb = fn; + break; + case M2M_REQ_GROUP_CRYPTO: + gstrHifCxt.pfCryptoCb = fn; + break; + case M2M_REQ_GROUP_SIGMA: + gstrHifCxt.pfSigmaCb = fn; + break; + case M2M_REQ_GROUP_SSL: + gstrHifCxt.pfSslCb = fn; + break; + default: + M2M_ERR("GRp ? %d\n",u8Grp); + ret = M2M_ERR_FAIL; + break; + } + return ret; +} + +#endif diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_hif.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_hif.h new file mode 100644 index 0000000..1187183 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_hif.h @@ -0,0 +1,249 @@ +/** + * + * \file + * + * \brief This module contains M2M host interface APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _M2M_HIF_ +#define _M2M_HIF_ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "common/include/nm_common.h" +/*!< Include depends on UNO Board is used or not*/ +#ifdef ENABLE_UNO_BOARD +#include "m2m_uno_hif.h" +#endif + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#define M2M_HIF_MAX_PACKET_SIZE (1600 - 4) +/*!< Maximum size of the buffer could be transferred between Host and Firmware. +*/ + +#define M2M_HIF_HDR_OFFSET (sizeof(tstrHifHdr) + 4) + +/** +* @struct tstrHifHdr +* @brief Structure to hold HIF header +*/ +typedef struct +{ + uint8 u8Gid; /*!< Group ID */ + uint8 u8Opcode; /*!< OP code */ + uint16 u16Length; /*!< Payload length */ +}tstrHifHdr; + +#ifdef __cplusplus + extern "C" { +#endif + +/*! +@typedef typedef void (*tpfHifCallBack)(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr); +@brief used to point to Wi-Fi call back function depend on Arduino project or other projects. +@param [in] u8OpCode + HIF Opcode type. +@param [in] u16DataSize + HIF data length. +@param [in] u32Addr + HIF address. +@param [in] grp + HIF group type. +*/ +typedef void (*tpfHifCallBack)(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr); +/** +* @fn NMI_API sint8 hif_init(void * arg); +* @brief + To initialize HIF layer. +* @param [in] arg +* Pointer to the arguments. +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 hif_init(void * arg); +/** +* @fn NMI_API sint8 hif_deinit(void * arg); +* @brief + To Deinitialize HIF layer. +* @param [in] arg +* Pointer to the arguments. +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 hif_deinit(void * arg); +/** +* @fn NMI_API sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, + uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) +* @brief Send packet using host interface. + +* @param [in] u8Gid +* Group ID. +* @param [in] u8Opcode +* Operation ID. +* @param [in] pu8CtrlBuf +* Pointer to the Control buffer. +* @param [in] u16CtrlBufSize + Control buffer size. +* @param [in] u16DataOffset + Packet Data offset. +* @param [in] pu8DataBuf +* Packet buffer Allocated by the caller. +* @param [in] u16DataSize + Packet buffer size (including the HIF header). +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, + uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset); +/* +* @fn hif_receive +* @brief Host interface interrupt serviece routine +* @param [in] u32Addr +* Receive start address +* @param [out] pu8Buf +* Pointer to receive buffer. Allocated by the caller +* @param [in] u16Sz +* Receive buffer size +* @param [in] isDone +* If you don't need any more packets send True otherwise send false +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +NMI_API sint8 hif_receive(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz, uint8 isDone); +/** +* @fn hif_register_cb +* @brief + To set Callback function for every Component. + +* @param [in] u8Grp +* Group to which the Callback function should be set. + +* @param [in] fn +* function to be set to the specified group. +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 hif_register_cb(uint8 u8Grp,tpfHifCallBack fn); +/** +* @fn NMI_API sint8 hif_chip_sleep(void); +* @brief + To make the chip sleep. +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 hif_chip_sleep(void); +/** +* @fn NMI_API sint8 hif_chip_sleep_sc(void); +* @brief + To clear the chip count only but keep the chip awake +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 hif_chip_sleep_sc(void); +/** +* @fn NMI_API sint8 hif_chip_wake(void); +* @brief + To Wakeup the chip. +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +NMI_API sint8 hif_chip_wake(void); +/*! +@fn \ + NMI_API void hif_set_sleep_mode(uint8 u8Pstype); + +@brief + Set the sleep mode of the HIF layer. + +@param [in] u8Pstype + Sleep mode. + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ + +NMI_API void hif_set_sleep_mode(uint8 u8Pstype); +/*! +@fn \ + NMI_API uint8 hif_get_sleep_mode(void); + +@brief + Get the sleep mode of the HIF layer. + +@return + The function SHALL return the sleep mode of the HIF layer. +*/ + +NMI_API uint8 hif_get_sleep_mode(void); + +#ifdef CORTUS_APP +/** +* @fn hif_Resp_handler(uint8 *pu8Buffer, uint16 u16BufferSize) +* @brief + Response handler for HIF layer. + +* @param [in] pu8Buffer + Pointer to the buffer. + +* @param [in] u16BufferSize + Buffer size. + +* @return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 hif_Resp_handler(uint8 *pu8Buffer, uint16 u16BufferSize); +#endif + +/** +* @fn hif_handle_isr(void) +* @brief + Handle interrupt received from NMC1500 firmware. +* @return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 hif_handle_isr(void); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ota.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ota.c new file mode 100644 index 0000000..cf4a30f --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ota.c @@ -0,0 +1,417 @@ +/** + * + * \file + * + * \brief NMC1500 IoT OTA Interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#include "common/include/nm_common.h" +#include "driver/include/m2m_types.h" +#include "driver/include/m2m_ota.h" +#include "driver/source/m2m_hif.h" +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +static tpfOtaUpdateCb gpfOtaUpdateCb = NULL; +static tpfOtaNotifCb gpfOtaNotifCb = NULL; + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/** +* @fn m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr, uint8 grp) +* @brief WiFi call back function +* @param [in] u8OpCode +* HIF Opcode type. +* @param [in] u16DataSize +* HIF data length. +* @param [in] u32Addr +* HIF address. +* @param [in] grp +* HIF group type. +* @author +* @date +* @version 1.0 +*/ +static void m2m_ota_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +{ +#ifdef ARDUINO + (void)u16DataSize; // Silence "unused" warning +#endif + sint8 ret = M2M_SUCCESS; + if(u8OpCode == M2M_OTA_RESP_NOTIF_UPDATE_INFO) + { + tstrOtaUpdateInfo strOtaUpdateInfo; + m2m_memset((uint8*)&strOtaUpdateInfo,0,sizeof(tstrOtaUpdateInfo)); + ret = hif_receive(u32Addr,(uint8*)&strOtaUpdateInfo,sizeof(tstrOtaUpdateInfo),0); + if(ret == M2M_SUCCESS) + { + if(gpfOtaNotifCb) + gpfOtaNotifCb(&strOtaUpdateInfo); + } + } + else if (u8OpCode == M2M_OTA_RESP_UPDATE_STATUS) + { + tstrOtaUpdateStatusResp strOtaUpdateStatusResp; + m2m_memset((uint8*)&strOtaUpdateStatusResp,0,sizeof(tstrOtaUpdateStatusResp)); + ret = hif_receive(u32Addr, (uint8*) &strOtaUpdateStatusResp,sizeof(tstrOtaUpdateStatusResp), 0); + if(ret == M2M_SUCCESS) + { + if(gpfOtaUpdateCb) + gpfOtaUpdateCb(strOtaUpdateStatusResp.u8OtaUpdateStatusType,strOtaUpdateStatusResp.u8OtaUpdateStatus); + } + } + else + { + M2M_ERR("Invaild OTA resp %d ?\n",u8OpCode); + } + +} +/*! +@fn \ + NMI_API sint8 m2m_ota_init(tpfOtaUpdateCb pfOtaUpdateCb, tpfOtaNotifCb pfOtaNotifCb); + +@brief + Initialize the OTA layer. + +@param [in] pfOtaUpdateCb + OTA Update callback function + +@param [in] pfOtaNotifCb + OTA notify callback function + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_init(tpfOtaUpdateCb pfOtaUpdateCb, tpfOtaNotifCb pfOtaNotifCb) +{ + sint8 ret = M2M_SUCCESS; + + if(pfOtaUpdateCb){ + gpfOtaUpdateCb = pfOtaUpdateCb; + }else{ + M2M_ERR("Invaild Ota update cb\n"); + } + if(pfOtaNotifCb){ + gpfOtaNotifCb = pfOtaNotifCb; + }else{ + M2M_ERR("Invaild Ota notify cb\n"); + } + + hif_register_cb(M2M_REQ_GROUP_OTA,m2m_ota_cb); + + return ret; +} +/*! +@fn \ + NMI_API sint8 m2m_ota_notif_set_url(uint8 * u8Url); + +@brief + Set the OTA url + +@param [in] u8Url + The url server address + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_notif_set_url(uint8 * u8Url) +{ + sint8 ret = M2M_SUCCESS; + uint16 u16UrlSize = m2m_strlen(u8Url) + 1; + /*Todo: we may change it to data pkt but we need to give it higer priority + but the priorty is not implemnted yet in data pkt + */ + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_NOTIF_SET_URL,u8Url,u16UrlSize,NULL,0,0); + return ret; + +} + +/*! +@fn \ + NMI_API sint8 m2m_ota_notif_check_for_update(void); + +@brief + check for ota update + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_notif_check_for_update(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_NOTIF_CHECK_FOR_UPDATE,NULL,0,NULL,0,0); + return ret; +} + +/*! +@fn \ + NMI_API sint8 m2m_ota_notif_sched(uint32 u32Period); + +@brief + Schedule OTA update + +@param [in] u32Period + Period in days + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_notif_sched(uint32 u32Period) +{ +#ifdef ARDUINO + (void)u32Period; // Silence "unused" warning +#endif + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_NOTIF_CHECK_FOR_UPDATE,NULL,0,NULL,0,0); + return ret; +} + +/*! +@fn \ + NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl); + +@brief + Request OTA start update using the downloaded url + +@param [in] u8DownloadUrl + The download firmware url, you get it from device info + +@return + The function SHALL return 0 for success and a negative value otherwise. + +*/ +NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl) +{ + sint8 ret = M2M_SUCCESS; + uint16 u16DurlSize = m2m_strlen(u8DownloadUrl) + 1; + /*Todo: we may change it to data pkt but we need to give it higer priority + but the priorty is not implemnted yet in data pkt + */ + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_START_FW_UPDATE,u8DownloadUrl,u16DurlSize,NULL,0,0); + return ret; +} +/*! +@fn \ + NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl); + +@brief + Request OTA start for the Cortus app image. + +@param [in] u8DownloadUrl + The cortus application image url. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +*/ +NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl) +{ + sint8 ret = M2M_SUCCESS; + uint16 u16DurlSize = m2m_strlen(u8DownloadUrl) + 1; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_START_CRT_UPDATE,u8DownloadUrl,u16DurlSize,NULL,0,0); + return ret; +} + + +/*! +@fn \ + NMI_API sint8 m2m_ota_rollback(void); + +@brief + Request OTA Rollback image + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_rollback(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_ROLLBACK_FW,NULL,0,NULL,0,0); + return ret; +} +/*! +@fn \ + NMI_API sint8 m2m_ota_rollback_crt(void); + +@brief + Request Cortus application OTA Rollback image + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_rollback_crt(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_ROLLBACK_CRT,NULL,0,NULL,0,0); + return ret; +} + +/*! +@fn \ + NMI_API sint8 m2m_ota_abort(void); + +@brief + Request OTA Abort + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_abort(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_ABORT,NULL,0,NULL,0,0); + return ret; +} + + +/*! +@fn \ + NMI_API sint8 m2m_ota_switch_firmware(void); + +@brief + Switch to the upgraded Firmware + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_switch_firmware(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_SWITCH_FIRMWARE,NULL,0,NULL,0,0); + return ret; +} +/*! +@fn \ + NMI_API sint8 m2m_ota_switch_crt(void); + +@brief + Switch to the upgraded cortus application. + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_switch_crt(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_SWITCH_CRT_IMG,NULL,0,NULL,0,0); + return ret; +} + +/*! +@fn \ + NMI_API sint8 m2m_ota_get_firmware_version(tstrM2mRev * pstrRev); + +@brief + Get the OTA Firmware version. + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_get_firmware_version(tstrM2mRev * pstrRev) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_chip_wake(); + if(ret == M2M_SUCCESS) + { + ret = nm_get_ota_firmware_info(pstrRev); + hif_chip_sleep(); + } + return ret; +} +#if 0 +#define M2M_OTA_FILE "../../../m2m_ota.dat" +NMI_API sint8 m2m_ota_test(void) +{ + uint32 page = 0; + uint8 buffer[1500]; + uint32 u32Sz = 0; + sint8 ret = M2M_SUCCESS; + FILE *fp =NULL; + fp = fopen(M2M_OTA_FILE,"rb"); + if(fp) + { + fseek(fp, 0L, SEEK_END); + u32Sz = ftell(fp); + fseek(fp, 0L, SEEK_SET); + + while(u32Sz > 0) + { + { + page = (rand()%1400); + + if((page<100)||(page>1400)) page = 1400; + } + + if(u32Sz>page) + { + u32Sz-=page; + } + else + { + page = u32Sz; + u32Sz = 0; + } + printf("page %d\n", (int)page); + fread(buffer,page,1,fp); + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_TEST|M2M_REQ_DATA_PKT,NULL,0,(uint8*)&buffer,page,0); + if(ret != M2M_SUCCESS) + { + M2M_ERR("\n"); + } + nm_bsp_sleep(1); + } + + } + else + { + M2M_ERR("nO err\n"); + } + return ret; +} +#endif + diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_periph.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_periph.c new file mode 100644 index 0000000..0f8890b --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_periph.c @@ -0,0 +1,187 @@ +/** + * + * \file + * + * \brief NMC1500 Peripherials Application Interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "driver/include/m2m_periph.h" +#include "driver/source/nmasic.h" +#include "m2m_hif.h" + +#ifdef CONF_PERIPH + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#define GPIO_OP_DIR 0 +#define GPIO_OP_SET 1 +#define GPIO_OP_GET 2 +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +STATIC FUNCTIONS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +static sint8 get_gpio_idx(uint8 u8GpioNum) +{ + if(u8GpioNum >= M2M_PERIPH_GPIO_MAX) return -1; + if(u8GpioNum == M2M_PERIPH_GPIO15) { return 15; + } else if(u8GpioNum == M2M_PERIPH_GPIO16) { return 16; + } else if(u8GpioNum == M2M_PERIPH_GPIO18) { return 18; + } else if(u8GpioNum == M2M_PERIPH_GPIO3) { return 3; + } else if(u8GpioNum == M2M_PERIPH_GPIO4) { return 4; + } else if(u8GpioNum == M2M_PERIPH_GPIO5) { return 5; + } else if(u8GpioNum == M2M_PERIPH_GPIO6) { return 6; + } else { + return -2; + } +} +/* + * GPIO read/write skeleton with wakeup/sleep capability. + */ +static sint8 gpio_ioctl(uint8 op, uint8 u8GpioNum, uint8 u8InVal, uint8 * pu8OutVal) +{ + sint8 ret, gpio; + + ret = hif_chip_wake(); + if(ret != M2M_SUCCESS) goto _EXIT; + + gpio = get_gpio_idx(u8GpioNum); + if(gpio < 0) goto _EXIT1; + + if(op == GPIO_OP_DIR) { + ret = set_gpio_dir((uint8)gpio, u8InVal); + } else if(op == GPIO_OP_SET) { + ret = set_gpio_val((uint8)gpio, u8InVal); + } else if(op == GPIO_OP_GET) { + ret = get_gpio_val((uint8)gpio, pu8OutVal); + } + if(ret != M2M_SUCCESS) goto _EXIT1; + +_EXIT1: + ret = hif_chip_sleep(); +_EXIT: + return ret; +} +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION IMPLEMENTATION +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +sint8 m2m_periph_init(tstrPerphInitParam * param) +{ +#ifdef ARDUINO + (void)param; // Silence "unused" warning +#endif + return M2M_SUCCESS; +} + +sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir) +{ + return gpio_ioctl(GPIO_OP_DIR, u8GpioNum, u8GpioDir, NULL); +} + +sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal) +{ + return gpio_ioctl(GPIO_OP_SET, u8GpioNum, u8GpioVal, NULL); +} + +sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal) +{ + return gpio_ioctl(GPIO_OP_GET, u8GpioNum, 0, pu8GpioVal); +} + +sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn) +{ +#ifdef ARDUINO + (void)u8GpioNum; // Silence "unused" warning + (void)u8PullupEn; +#endif + /* TBD */ + return M2M_SUCCESS; +} + +sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)param; +#endif + /* TBD */ + return M2M_SUCCESS; +} + +sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)u8SlaveAddr; + (void)pu8Buf; + (void)u16BufLen; + (void)flags; +#endif + /* TBD */ + return M2M_SUCCESS; +} + +sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)u8SlaveAddr; + (void)pu8Buf; + (void)u16BufLen; + (void)pu16ReadLen; + (void)flags; +#endif + /* TBD */ + return M2M_SUCCESS; +} + + +sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable) +{ + return pullup_ctrl(pinmask, enable); +} +#endif /* CONF_PERIPH */ \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ssl.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ssl.c new file mode 100644 index 0000000..07513f7 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ssl.c @@ -0,0 +1,309 @@ +/** + * + * \file + * + * \brief This module contains M2M Wi-Fi APIs implementation. + * + * Copyright (c) 2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "driver/include/m2m_ssl.h" +#include "driver/source/m2m_hif.h" +#include "driver/source/nmasic.h" + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +static tpfAppSSLCb gpfAppSSLCb = NULL; +static uint32 gu32HIFAddr = 0; + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*! + @fn \ m2m_ssl_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) + @brief SSL callback function + @param [in] u8OpCode + HIF Opcode type. + @param [in] u16DataSize + HIF data length. + @param [in] u32Addr + HIF address. +*/ +static void m2m_ssl_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +{ +#ifdef ARDUINO + (void)u16DataSize; // Silence "unused" warning +#endif + sint8 s8tmp = M2M_SUCCESS; + switch(u8OpCode) + { + case M2M_SSL_REQ_ECC: + { + tstrEccReqInfo strEccREQ; + s8tmp = hif_receive(u32Addr, (uint8*)&strEccREQ, sizeof(tstrEccReqInfo), 0); + if(s8tmp == M2M_SUCCESS) + { + if (gpfAppSSLCb) + { + gu32HIFAddr = u32Addr + sizeof(tstrEccReqInfo); + gpfAppSSLCb(M2M_SSL_REQ_ECC, &strEccREQ); + } + } + } + break; + case M2M_SSL_RESP_SET_CS_LIST: + { + tstrSslSetActiveCsList strCsList; + s8tmp = hif_receive(u32Addr, (uint8*)&strCsList, sizeof(tstrSslSetActiveCsList), 0); + if(s8tmp == M2M_SUCCESS) + { + if (gpfAppSSLCb) + gpfAppSSLCb(M2M_SSL_RESP_SET_CS_LIST, &strCsList); + } + } + break; + } + if(s8tmp != M2M_SUCCESS) + { + M2M_ERR("Error receiving SSL from the HIF\n"); + } +} + + +/*! + @fn \ m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz) + @brief Sends ECC responses to the WINC + @param [in] strECCResp + ECC Response struct. + @param [in] pu8RspDataBuffe + Pointer of the response data to be sent. + @param [in] u16RspDataSz + Response data size. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz) +{ + sint8 s8Ret = M2M_SUCCESS; + + s8Ret = hif_send(M2M_REQ_GROUP_SSL, (M2M_SSL_RESP_ECC | M2M_REQ_DATA_PKT), (uint8*)strECCResp, sizeof(tstrEccReqInfo), pu8RspDataBuff, u16RspDataSz, sizeof(tstrEccReqInfo)); + + return s8Ret; +} + +/*! + @fn \ m2m_ssl_send_certs_to_winc(uint8* sector_buffer, uint32 sector_size) + @brief Sends certificates to the WINC + @param [in] pu8Buffer + Pointer to the certificates. + @param [in] u32BufferSz + Size of the certificates. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_send_certs_to_winc(uint8* pu8Buffer, uint32 u32BufferSz) +{ + sint8 s8Ret = M2M_SUCCESS; + + s8Ret = hif_send(M2M_REQ_GROUP_SSL, (M2M_SSL_IND_CERTS_ECC | M2M_REQ_DATA_PKT), NULL, 0, pu8Buffer, u32BufferSz, 0); + + return s8Ret; +} + +/*! + @fn \ m2m_ssl_retrieve_cert(uint32 u32ReadAddr, uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key) + @brief Retrieve the certificate to be verified from the WINC + @param [in] pu16CurveType + Pointer to the certificate curve type. + @param [in] pu8Hash + Pointer to the certificate hash. + @param [in] pu8Sig + Pointer to the certificate signature. + @param [in] pu8Key + Pointer to the certificate Key. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_retrieve_cert(uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key) +{ + uint8 bSetRxDone = 1; + uint16 u16HashSz, u16SigSz, u16KeySz; + sint8 s8Ret = M2M_SUCCESS; + + if(gu32HIFAddr == 0) return M2M_ERR_FAIL; + + if(hif_receive(gu32HIFAddr, (uint8*)pu16CurveType, 2, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += 2; + + if(hif_receive(gu32HIFAddr, (uint8*)&u16KeySz, 2, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += 2; + + if(hif_receive(gu32HIFAddr, (uint8*)&u16HashSz, 2, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += 2; + + if(hif_receive(gu32HIFAddr, (uint8*)&u16SigSz, 2, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += 2; + + (*pu16CurveType)= _htons((*pu16CurveType)); + pu8Key->u16Size = _htons(u16KeySz); + u16HashSz = _htons(u16HashSz); + u16SigSz = _htons(u16SigSz); + + if(hif_receive(gu32HIFAddr, pu8Key->X, pu8Key->u16Size * 2, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += (pu8Key->u16Size * 2); + + if(hif_receive(gu32HIFAddr, pu8Hash, u16HashSz, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += u16HashSz; + + if(hif_receive(gu32HIFAddr, pu8Sig, u16SigSz, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += u16SigSz; + + bSetRxDone = 0; + +__ERR: + if(bSetRxDone) + { + s8Ret = M2M_ERR_FAIL; + hif_receive(0, NULL, 0, 1); + } + return s8Ret; +} + +/*! + @fn \ m2m_ssl_retrieve_hash(uint32 u32ReadAddr, uint8* pu8Hash, uint16 u16HashSz) + @brief Retrieve the certificate hash + @param [in] pu8Hash + Pointer to the certificate hash. + @param [in] u16HashSz + Hash size. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_retrieve_hash(uint8* pu8Hash, uint16 u16HashSz) +{ + uint8 bSetRxDone = 1; + sint8 s8Ret = M2M_SUCCESS; + + if(gu32HIFAddr == 0) return M2M_ERR_FAIL; + + if(hif_receive(gu32HIFAddr, pu8Hash, u16HashSz, 0) != M2M_SUCCESS) goto __ERR; + + bSetRxDone = 0; + +__ERR: + if(bSetRxDone) + { + s8Ret = M2M_ERR_FAIL; + hif_receive(0, NULL, 0, 1); + } + return s8Ret; +} + +/*! + @fn \ m2m_ssl_stop_processing_certs(void) + @brief Stops receiving from the HIF +*/ +NMI_API void m2m_ssl_stop_processing_certs(void) +{ + hif_receive(0, NULL, 0, 1); +} + +/*! + @fn \ m2m_ssl_ecc_process_done(void) + @brief Stops receiving from the HIF +*/ +NMI_API void m2m_ssl_ecc_process_done(void) +{ + gu32HIFAddr = 0; +} + +/*! +@fn \ + m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP); + Override the default Active SSL ciphers in the SSL module with a certain combination selected by the caller in the form of + a bitmap containing the required ciphers to be on. + There is no need to call this function if the application will not change the default ciphersuites. + +@param [in] u32SslCsBMP + Bitmap containing the desired ciphers to be enabled for the SSL module. The ciphersuites are defined in + @ref SSLCipherSuiteID. + The default ciphersuites are all ciphersuites supported by the firmware with the exception of ECC ciphersuites. + The caller can override the default with any desired combination, except for combinations involving both RSA + and ECC; if any RSA ciphersuite is enabled, then firmware will disable all ECC ciphersuites. + If u32SslCsBMP does not contain any ciphersuites supported by firmware, then the current active list will not + be changed. + +@return + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) +*/ +sint8 m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP) +{ + sint8 s8Ret = M2M_SUCCESS; + tstrSslSetActiveCsList strCsList; + + strCsList.u32CsBMP = u32SslCsBMP; + s8Ret = hif_send(M2M_REQ_GROUP_SSL, M2M_SSL_REQ_SET_CS_LIST, (uint8*)&strCsList, sizeof(tstrSslSetActiveCsList), NULL, 0, 0); + + return s8Ret; +} + +/*! + @fn \ m2m_ssl_init(tpfAppSslCb pfAppSslCb); + @brief Initializes the SSL layer. + @param [in] pfAppSslCb + Application SSL callback function. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_init(tpfAppSSLCb pfAppSSLCb) +{ + sint8 s8Ret = M2M_SUCCESS; + + gpfAppSSLCb = pfAppSSLCb; + gu32HIFAddr = 0; + + s8Ret = hif_register_cb(M2M_REQ_GROUP_SSL,m2m_ssl_cb); + if (s8Ret != M2M_SUCCESS) + { + M2M_ERR("hif_register_cb() failed with ret=%d", s8Ret); + } + return s8Ret; +} \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_wifi.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_wifi.c new file mode 100644 index 0000000..7998623 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_wifi.c @@ -0,0 +1,1522 @@ +/** + * + * \file + * + * \brief This module contains M2M Wi-Fi APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "driver/include/m2m_wifi.h" +#include "driver/source/m2m_hif.h" +#include "driver/source/nmasic.h" + +static volatile uint8 gu8ChNum; +static volatile uint8 gu8scanInProgress = 0; +static tpfAppWifiCb gpfAppWifiCb = NULL; + + +#ifdef ETH_MODE +static tpfAppEthCb gpfAppEthCb = NULL; +static uint8* gau8ethRcvBuf=NULL; +static uint16 gu16ethRcvBufSize ; +#endif + + +//#define CONF_MGMT +#ifdef CONF_MGMT +static tpfAppMonCb gpfAppMonCb = NULL; +static struct _tstrMgmtCtrl +{ + uint8* pu8Buf; + uint16 u16Offset; + uint16 u16Sz; +} +gstrMgmtCtrl = {NULL, 0 , 0}; +#endif +/** +* @fn m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr, uint8 grp) +* @brief WiFi call back function +* @param [in] u8OpCode +* HIF Opcode type. +* @param [in] u16DataSize +* HIF data length. +* @param [in] u32Addr +* HIF address. +* @param [in] grp +* HIF group type. +* @author +* @date +* @version 1.0 +*/ +static void m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +{ +#ifdef ARDUINO + (void)u16DataSize; // Silence "unused" warning +#endif + uint8 rx_buf[8]; + if (u8OpCode == M2M_WIFI_RESP_CON_STATE_CHANGED) + { + tstrM2mWifiStateChanged strState; + if (hif_receive(u32Addr, (uint8*) &strState,sizeof(tstrM2mWifiStateChanged), 0) == M2M_SUCCESS) + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_CON_STATE_CHANGED, &strState); + } + } + else if (u8OpCode == M2M_WIFI_RESP_GET_SYS_TIME) + { + tstrSystemTime strSysTime; + if (hif_receive(u32Addr, (uint8*) &strSysTime,sizeof(tstrSystemTime), 0) == M2M_SUCCESS) + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_GET_SYS_TIME, &strSysTime); + } + } + else if(u8OpCode == M2M_WIFI_RESP_CONN_INFO) + { + tstrM2MConnInfo strConnInfo; + if(hif_receive(u32Addr, (uint8*)&strConnInfo, sizeof(tstrM2MConnInfo), 1) == M2M_SUCCESS) + { + if(gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_CONN_INFO, &strConnInfo); + } + } + else if (u8OpCode == M2M_WIFI_RESP_MEMORY_RECOVER) + { +#if 0 + if (hif_receive(u32Addr, rx_buf, 4, 1) == M2M_SUCCESS) + { + tstrM2mWifiStateChanged strState; + m2m_memcpy((uint8*) &strState, rx_buf,sizeof(tstrM2mWifiStateChanged)); + if (app_wifi_recover_cb) + app_wifi_recover_cb(strState.u8CurrState); + } +#endif + } + else if (u8OpCode == M2M_WIFI_REQ_DHCP_CONF) + { + tstrM2MIPConfig strIpConfig; +#ifdef ARDUINO + extern uint32 nmdrv_firm_ver; + uint16 rxSize = sizeof(tstrM2MIPConfig); + + if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 5, 0)) { + // for backwards compatibility with firmware 19.4.4 and older, + // the old tstrM2MIPConfig does not contain the u32DhcpLeaseTime field + rxSize -= sizeof(strIpConfig.u32DhcpLeaseTime); + } + + if (hif_receive(u32Addr, (uint8 *)&strIpConfig, rxSize, 0) == M2M_SUCCESS) +#else + if (hif_receive(u32Addr, (uint8 *)&strIpConfig, sizeof(tstrM2MIPConfig), 0) == M2M_SUCCESS) +#endif + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_REQ_DHCP_CONF, (uint8 *)&strIpConfig); + } + } + else if (u8OpCode == M2M_WIFI_REQ_WPS) + { + tstrM2MWPSInfo strWps; + m2m_memset((uint8*)&strWps,0,sizeof(tstrM2MWPSInfo)); + if(hif_receive(u32Addr, (uint8*)&strWps, sizeof(tstrM2MWPSInfo), 0) == M2M_SUCCESS) + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_REQ_WPS, &strWps); + } + } + else if (u8OpCode == M2M_WIFI_RESP_IP_CONFLICT) + { + uint32 u32ConflictedIP; + if(hif_receive(u32Addr, (uint8 *)&u32ConflictedIP, sizeof(u32ConflictedIP), 0) == M2M_SUCCESS) + { + M2M_INFO("Conflicted IP \" %u.%u.%u.%u \" \n", + BYTE_0(u32ConflictedIP),BYTE_1(u32ConflictedIP),BYTE_2(u32ConflictedIP),BYTE_3(u32ConflictedIP)); + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_IP_CONFLICT, NULL); + + } + } + else if (u8OpCode == M2M_WIFI_RESP_SCAN_DONE) + { + tstrM2mScanDone strState; + gu8scanInProgress = 0; + if(hif_receive(u32Addr, (uint8*)&strState, sizeof(tstrM2mScanDone), 0) == M2M_SUCCESS) + { + gu8ChNum = strState.u8NumofCh; + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_SCAN_DONE, &strState); + } + } + else if (u8OpCode == M2M_WIFI_RESP_SCAN_RESULT) + { + tstrM2mWifiscanResult strScanResult; + if(hif_receive(u32Addr, (uint8*)&strScanResult, sizeof(tstrM2mWifiscanResult), 0) == M2M_SUCCESS) + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_SCAN_RESULT, &strScanResult); + } + } + else if (u8OpCode == M2M_WIFI_RESP_CURRENT_RSSI) + { + if (hif_receive(u32Addr, rx_buf, 4, 0) == M2M_SUCCESS) + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_CURRENT_RSSI, rx_buf); + } + } + else if (u8OpCode == M2M_WIFI_RESP_CLIENT_INFO) + { + if (hif_receive(u32Addr, rx_buf, 4, 0) == M2M_SUCCESS) + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_CLIENT_INFO, rx_buf); + } + } + else if(u8OpCode == M2M_WIFI_RESP_PROVISION_INFO) + { + tstrM2MProvisionInfo strProvInfo; + if(hif_receive(u32Addr, (uint8*)&strProvInfo, sizeof(tstrM2MProvisionInfo), 1) == M2M_SUCCESS) + { + if(gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_PROVISION_INFO, &strProvInfo); + } + } + else if(u8OpCode == M2M_WIFI_RESP_DEFAULT_CONNECT) + { + tstrM2MDefaultConnResp strResp; + if(hif_receive(u32Addr, (uint8*)&strResp, sizeof(tstrM2MDefaultConnResp), 1) == M2M_SUCCESS) + { + if(gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_DEFAULT_CONNECT, &strResp); + } + } + + else if(u8OpCode == M2M_WIFI_RESP_GET_PRNG) + { + tstrPrng strPrng; + if(hif_receive(u32Addr, (uint8*)&strPrng,sizeof(tstrPrng), 0) == M2M_SUCCESS) + { + if(hif_receive(u32Addr + sizeof(tstrPrng),strPrng.pu8RngBuff,strPrng.u16PrngSize, 1) == M2M_SUCCESS) + { + if(gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_GET_PRNG,&strPrng); + } + } + } +#ifdef ETH_MODE + else if(u8OpCode == M2M_WIFI_RESP_ETHERNET_RX_PACKET) + { + uint8 u8SetRxDone; + tstrM2mIpRsvdPkt strM2mRsvd; + if(hif_receive(u32Addr, &strM2mRsvd ,sizeof(tstrM2mIpRsvdPkt), 0) == M2M_SUCCESS) + { + tstrM2mIpCtrlBuf strM2mIpCtrlBuf; + uint16 u16Offset = strM2mRsvd.u16PktOffset; + strM2mIpCtrlBuf.u16RemainigDataSize = strM2mRsvd.u16PktSz; + if((gpfAppEthCb) && (gau8ethRcvBuf) && (gu16ethRcvBufSize > 0)) + { + do + { + u8SetRxDone = 1; + if(strM2mIpCtrlBuf.u16RemainigDataSize > gu16ethRcvBufSize) + { + u8SetRxDone = 0; + strM2mIpCtrlBuf.u16DataSize = gu16ethRcvBufSize; + } + else + { + strM2mIpCtrlBuf.u16DataSize = strM2mIpCtrlBuf.u16RemainigDataSize; + } + + if(hif_receive(u32Addr + u16Offset, gau8ethRcvBuf, strM2mIpCtrlBuf.u16DataSize, u8SetRxDone) == M2M_SUCCESS) + { + strM2mIpCtrlBuf.u16RemainigDataSize -= strM2mIpCtrlBuf.u16DataSize; + u16Offset += strM2mIpCtrlBuf.u16DataSize; + gpfAppEthCb(M2M_WIFI_RESP_ETHERNET_RX_PACKET, gau8ethRcvBuf, &(strM2mIpCtrlBuf)); + } + else + { + break; + } + }while (strM2mIpCtrlBuf.u16RemainigDataSize > 0); + } + } + } +#endif /* ETH_MODE */ +#ifdef CONF_MGMT + else if(u8OpCode == M2M_WIFI_RESP_WIFI_RX_PACKET) + { + + tstrM2MWifiRxPacketInfo strRxPacketInfo; + if(u16DataSize >= sizeof(tstrM2MWifiRxPacketInfo)) { + if(hif_receive(u32Addr, (uint8*)&strRxPacketInfo, sizeof(tstrM2MWifiRxPacketInfo), 0) == M2M_SUCCESS) + { + u16DataSize -= sizeof(tstrM2MWifiRxPacketInfo); + if(u16DataSize > 0 && gstrMgmtCtrl.pu8Buf != NULL) + { + if(u16DataSize > (gstrMgmtCtrl.u16Sz + gstrMgmtCtrl.u16Offset)) + { + u16DataSize = gstrMgmtCtrl.u16Sz; + } + u32Addr += sizeof(tstrM2MWifiRxPacketInfo) + gstrMgmtCtrl.u16Offset; + if(hif_receive(u32Addr , gstrMgmtCtrl.pu8Buf, u16DataSize, 1) != M2M_SUCCESS) return; + } + if(gpfAppMonCb) + gpfAppMonCb(&strRxPacketInfo, gstrMgmtCtrl.pu8Buf,u16DataSize); + } + } else { + M2M_ERR("Incorrect mon data size %u\n", u16DataSize); + } + } +#endif + else + { + M2M_ERR("REQ Not defined %d\n",u8OpCode); + } +} + +sint8 m2m_wifi_download_mode() +{ + sint8 ret = M2M_SUCCESS; + /* Apply device specific initialization. */ + ret = nm_drv_init_download_mode(); + if(ret != M2M_SUCCESS) goto _EXIT0; + + + + enable_interrupts(); + +_EXIT0: + return ret; +} + +static sint8 m2m_validate_ap_parameters(CONST tstrM2MAPConfig* pstrM2MAPConfig) +{ + sint8 s8Ret = M2M_SUCCESS; + /* Check for incoming pointer */ + if(pstrM2MAPConfig == NULL) + { + M2M_ERR("INVALID POINTER\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + /* Check for SSID */ + if((m2m_strlen((uint8 *)pstrM2MAPConfig->au8SSID) <= 0) || (m2m_strlen((uint8 *)pstrM2MAPConfig->au8SSID) >= M2M_MAX_SSID_LEN)) + { + M2M_ERR("INVALID SSID\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + /* Check for Channel */ + if(pstrM2MAPConfig->u8ListenChannel > M2M_WIFI_CH_14 || pstrM2MAPConfig->u8ListenChannel < M2M_WIFI_CH_1) + { + M2M_ERR("INVALID CH\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + /* Check for DHCP Server IP address */ + if(!(pstrM2MAPConfig->au8DHCPServerIP[0] || pstrM2MAPConfig->au8DHCPServerIP[1])) + { + if(!(pstrM2MAPConfig->au8DHCPServerIP[2])) + { + M2M_ERR("INVALID DHCP SERVER IP\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + } + /* Check for Security */ + if(pstrM2MAPConfig->u8SecType == M2M_WIFI_SEC_OPEN) + { + goto ERR1; + } + else if(pstrM2MAPConfig->u8SecType == M2M_WIFI_SEC_WEP) + { + /* Check for WEP Key index */ + if((pstrM2MAPConfig->u8KeyIndx <= 0) || (pstrM2MAPConfig->u8KeyIndx > WEP_KEY_MAX_INDEX)) + { + M2M_ERR("INVALID KEY INDEX\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + /* Check for WEP Key size */ + if( (pstrM2MAPConfig->u8KeySz != WEP_40_KEY_STRING_SIZE) && + (pstrM2MAPConfig->u8KeySz != WEP_104_KEY_STRING_SIZE) + ) + { + M2M_ERR("INVALID KEY STRING SIZE\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + + if((m2m_strlen((uint8 *)pstrM2MAPConfig->au8WepKey) <= 0) || (m2m_strlen((uint8 *)pstrM2MAPConfig->au8WepKey) > WEP_104_KEY_STRING_SIZE)) + { + M2M_ERR("INVALID KEY SIZE\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + } + else if(pstrM2MAPConfig->u8SecType == M2M_WIFI_SEC_WPA_PSK) + { + /* Check for WPA Key size */ + if( ((pstrM2MAPConfig->u8KeySz + 1) < M2M_MIN_PSK_LEN) || ((pstrM2MAPConfig->u8KeySz + 1) > M2M_MAX_PSK_LEN)) + { + M2M_ERR("INVALID WPA KEY SIZE\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + } + else + { + M2M_ERR("INVALID AUTHENTICATION MODE\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + +ERR1: + return s8Ret; +} +static sint8 m2m_validate_scan_options(tstrM2MScanOption* ptstrM2MScanOption) +{ + sint8 s8Ret = M2M_SUCCESS; + /* Check for incoming pointer */ + if(ptstrM2MScanOption == NULL) + { + M2M_ERR("INVALID POINTER\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR; + } + /* Check for valid No of slots */ + if(ptstrM2MScanOption->u8NumOfSlot == 0) + { + M2M_ERR("INVALID No of scan slots! %d\n",ptstrM2MScanOption->u8NumOfSlot); + s8Ret = M2M_ERR_FAIL; + goto ERR; + } + /* Check for valid time of slots */ + if(ptstrM2MScanOption->u8SlotTime < 10 || ptstrM2MScanOption->u8SlotTime > 250) + { + M2M_ERR("INVALID scan slot time! %d\n",ptstrM2MScanOption->u8SlotTime); + s8Ret = M2M_ERR_FAIL; + goto ERR; + } + /* Check for valid No of probe requests per slot */ + if((ptstrM2MScanOption->u8ProbesPerSlot == 0)||(ptstrM2MScanOption->u8ProbesPerSlot > M2M_SCAN_DEFAULT_NUM_PROBE)) + { + M2M_ERR("INVALID No of probe requests per scan slot %d\n",ptstrM2MScanOption->u8ProbesPerSlot); + s8Ret = M2M_ERR_FAIL; + goto ERR; + } + /* Check for valid RSSI threshold */ + if((ptstrM2MScanOption->s8RssiThresh < -99) || (ptstrM2MScanOption->s8RssiThresh >= 0)) + { + M2M_ERR("INVALID RSSI threshold %d \n",ptstrM2MScanOption->s8RssiThresh); + s8Ret = M2M_ERR_FAIL; + } + +ERR: + return s8Ret; +} + +sint8 m2m_wifi_send_crl(tstrTlsCrlInfo* pCRL) +{ + sint8 s8Ret = M2M_ERR_FAIL; + s8Ret = hif_send(M2M_REQ_GROUP_SSL, M2M_SSL_IND_CRL|M2M_REQ_DATA_PKT, NULL, 0, (uint8*)pCRL, sizeof(tstrTlsCrlInfo), 0); + return s8Ret; +} + +sint8 m2m_wifi_init(tstrWifiInitParam * param) +{ + tstrM2mRev strtmp; + sint8 ret = M2M_SUCCESS; + uint8 u8WifiMode = M2M_WIFI_MODE_NORMAL; + + if(param == NULL) { + ret = M2M_ERR_FAIL; + goto _EXIT0; + } + + gpfAppWifiCb = param->pfAppWifiCb; + +#ifdef ETH_MODE + gpfAppEthCb = param->strEthInitParam.pfAppEthCb; + gau8ethRcvBuf = param->strEthInitParam.au8ethRcvBuf; + gu16ethRcvBufSize = param->strEthInitParam.u16ethRcvBufSize; + u8WifiMode = param->strEthInitParam.u8EthernetEnable; +#endif /* ETH_MODE */ + +#ifdef CONF_MGMT + gpfAppMonCb = param->pfAppMonCb; +#endif + gu8scanInProgress = 0; + /* Apply device specific initialization. */ + ret = nm_drv_init(&u8WifiMode); + if(ret != M2M_SUCCESS) goto _EXIT0; + /* Initialize host interface module */ + ret = hif_init(NULL); + if(ret != M2M_SUCCESS) goto _EXIT1; + + hif_register_cb(M2M_REQ_GROUP_WIFI,m2m_wifi_cb); + + ret = nm_get_firmware_full_info(&strtmp); + +#ifdef ARDUINO + if (M2M_ERR_FAIL == ret) + { + // for compatibility with firmware version 19.3.0 + ret = nm_get_firmware_info(&strtmp); + } +#endif + M2M_INFO("Firmware ver : %u.%u.%u Svnrev %u\n", strtmp.u8FirmwareMajor, strtmp.u8FirmwareMinor, strtmp.u8FirmwarePatch,strtmp.u16FirmwareSvnNum); + M2M_INFO("Firmware Build %s Time %s\n",strtmp.BuildDate,strtmp.BuildTime); + M2M_INFO("Firmware Min driver ver : %u.%u.%u\n", strtmp.u8DriverMajor, strtmp.u8DriverMinor, strtmp.u8DriverPatch); + M2M_INFO("Driver ver: %u.%u.%u\n", M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); + M2M_INFO("Driver built at %s\t%s\n",__DATE__,__TIME__); + if(M2M_ERR_FW_VER_MISMATCH == ret) + { + M2M_ERR("Mismatch Firmawre Version\n"); + } + + goto _EXIT0; + +_EXIT1: + nm_drv_deinit(NULL); +_EXIT0: + return ret; +} + +sint8 m2m_wifi_deinit(void * arg) +{ +#ifdef ARDUINO + (void)arg; // Silence "unused" warning +#endif + hif_deinit(NULL); + + nm_drv_deinit(NULL); + + return M2M_SUCCESS; +} + + +#ifdef ARDUINO +#include "socket/include/socket_buffer.h" +extern tstrSocketBuffer gastrSocketBuffer[]; +#endif + +sint8 m2m_wifi_handle_events(void * arg) +{ +#ifdef ARDUINO + (void)arg; // Silence "unused" warning + + uint8 i; + + /* Arduino API LIMITATION: */ + /* To be compliant with the standard Arduino WiFi API socket must be buffered. */ + /* WiFi101 shield does not have this ability and automatically pushes incoming */ + /* data to the Arduino MCU. Function m2m_wifi_handle_events() is taking care of */ + /* this transfer. Hence by ensuring that all the MCU socket buffers are available */ + /* we can perform the transfer. */ + /* However, if one socket buffer is full, we have to delay this transfer by */ + /* returning an error value, as we have no way of knowing which socket is about */ + /* to be used. */ + /* Consequently, the Arduino sketch must NOT block on reading only one socket if */ + /* several sockets are to be used. Instead, application must carefully read for */ + /* all sockets, anytime. */ + for (i = 0; i < MAX_SOCKET; ++i) { + if (gastrSocketBuffer[i].flag && (*(gastrSocketBuffer[i].flag) & SOCKET_BUFFER_FLAG_FULL)) { + return M2M_ERR_FAIL; + } + } +#endif + return hif_handle_isr(); +} + +sint8 m2m_wifi_default_connect(void) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DEFAULT_CONNECT, NULL, 0,NULL, 0,0); +} + +sint8 m2m_wifi_connect(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch) +{ + return m2m_wifi_connect_sc(pcSsid, u8SsidLen, u8SecType, pvAuthInfo, u16Ch,0); +} +sint8 m2m_wifi_connect_sc(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch, uint8 u8NoSaveCred) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mWifiConnect strConnect; + tstrM2MWifiSecInfo *pstrAuthInfo; + + if(u8SecType != M2M_WIFI_SEC_OPEN) + { + if(pvAuthInfo == NULL) + { + M2M_ERR("Key is not valid\n"); + ret = M2M_ERR_FAIL; + goto ERR1; + } + if((u8SecType == M2M_WIFI_SEC_WPA_PSK) && (m2m_strlen(pvAuthInfo) == (M2M_MAX_PSK_LEN-1))) + { + uint8 i = 0; + uint8* pu8Psk = (uint8*)pvAuthInfo; + while(i < (M2M_MAX_PSK_LEN-1)) + { + if(pu8Psk[i]<'0' || (pu8Psk[i]>'9' && pu8Psk[i] < 'A')|| (pu8Psk[i]>'F' && pu8Psk[i] < 'a') || pu8Psk[i] > 'f') + { + M2M_ERR("Invalid Key\n"); + ret = M2M_ERR_FAIL; + goto ERR1; + } + i++; + } + } + } + if((u8SsidLen<=0)||(u8SsidLen>=M2M_MAX_SSID_LEN)) + { + M2M_ERR("SSID LEN INVALID\n"); + ret = M2M_ERR_FAIL; + goto ERR1; + } + + if(u16Ch < M2M_WIFI_CH_1|| u16Ch > M2M_WIFI_CH_14) + { + if(u16Ch!=M2M_WIFI_CH_ALL) + { + M2M_ERR("CH INVALID\n"); + ret = M2M_ERR_FAIL; + goto ERR1; + } + } + + + m2m_memcpy(strConnect.au8SSID, (uint8*)pcSsid, u8SsidLen); + strConnect.au8SSID[u8SsidLen] = 0; + strConnect.u16Ch = NM_BSP_B_L_16(u16Ch); + /* Credentials will be Not be saved if u8NoSaveCred is set */ + strConnect.u8NoSaveCred = u8NoSaveCred ? 1:0; + pstrAuthInfo = &strConnect.strSec; + pstrAuthInfo->u8SecType = u8SecType; + + if(u8SecType == M2M_WIFI_SEC_WEP) + { + tstrM2mWifiWepParams * pstrWepParams = (tstrM2mWifiWepParams*)pvAuthInfo; + tstrM2mWifiWepParams *pstrWep = &pstrAuthInfo->uniAuth.strWepInfo; +#ifdef ARDUINO + pstrWep->u8KeyIndx =pstrWepParams->u8KeyIndx; +#else + pstrWep->u8KeyIndx =pstrWepParams->u8KeyIndx-1; +#endif + + if(pstrWep->u8KeyIndx >= WEP_KEY_MAX_INDEX) + { + M2M_ERR("Invalid Wep key index %d\n", pstrWep->u8KeyIndx); + ret = M2M_ERR_FAIL; + goto ERR1; + } +#ifdef ARDUINO + pstrWep->u8KeySz = pstrWepParams->u8KeySz; +#else + pstrWep->u8KeySz = pstrWepParams->u8KeySz-1; +#endif + if ((pstrWep->u8KeySz != WEP_40_KEY_STRING_SIZE)&& (pstrWep->u8KeySz != WEP_104_KEY_STRING_SIZE)) + { + M2M_ERR("Invalid Wep key length %d\n", pstrWep->u8KeySz); + ret = M2M_ERR_FAIL; + goto ERR1; + } + m2m_memcpy((uint8*)pstrWep->au8WepKey,(uint8*)pstrWepParams->au8WepKey, pstrWepParams->u8KeySz); + pstrWep->au8WepKey[pstrWepParams->u8KeySz] = 0; + + } + + + else if(u8SecType == M2M_WIFI_SEC_WPA_PSK) + { + uint16 u16KeyLen = m2m_strlen((uint8*)pvAuthInfo); + if((u16KeyLen <= 0)||(u16KeyLen >= M2M_MAX_PSK_LEN)) + { + M2M_ERR("Incorrect PSK key length\n"); + ret = M2M_ERR_FAIL; + goto ERR1; + } + m2m_memcpy(pstrAuthInfo->uniAuth.au8PSK, (uint8*)pvAuthInfo, u16KeyLen + 1); + } + else if(u8SecType == M2M_WIFI_SEC_802_1X) + { + m2m_memcpy((uint8*)&pstrAuthInfo->uniAuth.strCred1x, (uint8*)pvAuthInfo, sizeof(tstr1xAuthCredentials)); + } + else if(u8SecType == M2M_WIFI_SEC_OPEN) + { + + } + else + { + M2M_ERR("undefined sec type\n"); + ret = M2M_ERR_FAIL; + goto ERR1; + } + + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CONNECT, (uint8*)&strConnect, sizeof(tstrM2mWifiConnect),NULL, 0,0); + +ERR1: + return ret; +} + +sint8 m2m_wifi_disconnect(void) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISCONNECT, NULL, 0, NULL, 0,0); +} +sint8 m2m_wifi_set_mac_address(uint8 au8MacAddress[6]) +{ + tstrM2mSetMacAddress strTmp; + m2m_memcpy((uint8*) strTmp.au8Mac, (uint8*) au8MacAddress, 6); + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_MAC_ADDRESS, + (uint8*) &strTmp, sizeof(tstrM2mSetMacAddress), NULL, 0,0); +} + +sint8 m2m_wifi_set_static_ip(tstrM2MIPConfig * pstrStaticIPConf) +{ + pstrStaticIPConf->u32DNS = NM_BSP_B_L_32(pstrStaticIPConf->u32DNS); + pstrStaticIPConf->u32Gateway = NM_BSP_B_L_32(pstrStaticIPConf->u32Gateway); + pstrStaticIPConf->u32StaticIP = NM_BSP_B_L_32( + pstrStaticIPConf->u32StaticIP); + pstrStaticIPConf->u32SubnetMask = NM_BSP_B_L_32( + pstrStaticIPConf->u32SubnetMask); + return hif_send(M2M_REQ_GROUP_IP, M2M_IP_REQ_STATIC_IP_CONF, + (uint8*) pstrStaticIPConf, sizeof(tstrM2MIPConfig), NULL, 0,0); +} + +sint8 m2m_wifi_request_dhcp_client(void) +{ + /*legacy API should be removed */ + return 0; +} +sint8 m2m_wifi_request_dhcp_server(uint8* addr) +{ +#ifdef ARDUINO + (void)addr; // Silence "unused" warning +#endif + /*legacy API should be removed */ + return 0; +} +/*! +@fn NMI_API sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt * pstrM2mLsnInt); +@brief Set the Wi-Fi listen interval for power save operation. It is represented in units + of AP Beacon periods. +@param [in] pstrM2mLsnInt + Structure holding the listen interval configurations. +@return The function SHALL return 0 for success and a negative value otherwise. +@sa tstrM2mLsnInt , m2m_wifi_set_sleep_mode +@pre m2m_wifi_set_sleep_mode shall be called first +@warning The Function called once after initialization. +*/ +sint8 m2m_wifi_enable_dhcp(uint8 u8DhcpEn ) +{ + + uint8 u8Req; + u8Req = u8DhcpEn ? M2M_IP_REQ_ENABLE_DHCP : M2M_IP_REQ_DISABLE_DHCP; + return hif_send(M2M_REQ_GROUP_IP, u8Req, NULL, 0, NULL, 0, 0); + + +} + +sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt* pstrM2mLsnInt) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_LSN_INT, (uint8*)pstrM2mLsnInt, sizeof(tstrM2mLsnInt), NULL, 0, 0); +} + +sint8 m2m_wifi_set_cust_InfoElement(uint8* pau8M2mCustInfoElement) +{ + + sint8 ret = M2M_ERR_FAIL; + if(pau8M2mCustInfoElement != NULL) + { + if((pau8M2mCustInfoElement[0] + 1) < M2M_CUST_IE_LEN_MAX) + { + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CUST_INFO_ELEMENT|M2M_REQ_DATA_PKT, (uint8*)pau8M2mCustInfoElement, pau8M2mCustInfoElement[0]+1, NULL, 0, 0); + } + } + return ret; +} + +sint8 m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption) +{ + sint8 s8Ret = M2M_ERR_FAIL; + if(m2m_validate_scan_options (ptstrM2MScanOption) == M2M_SUCCESS) + { + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_SCAN_OPTION, (uint8*)ptstrM2MScanOption, sizeof(tstrM2MScanOption),NULL, 0,0); + } + return s8Ret; +} +sint8 m2m_wifi_set_scan_region(uint16 ScanRegion) +{ + sint8 s8Ret = M2M_ERR_FAIL; + tstrM2MScanRegion strScanRegion; + strScanRegion.u16ScanRegion = ScanRegion; + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_SCAN_REGION, (uint8*)&strScanRegion, sizeof(tstrM2MScanRegion),NULL, 0,0); + return s8Ret; +} +sint8 m2m_wifi_request_scan(uint8 ch) +{ + sint8 s8Ret = M2M_SUCCESS; + + if(!gu8scanInProgress) + { + if(((ch >= M2M_WIFI_CH_1) && (ch <= M2M_WIFI_CH_14)) || (ch == M2M_WIFI_CH_ALL)) + { + tstrM2MScan strtmp; + strtmp.u8ChNum = ch; + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SCAN, (uint8*)&strtmp, sizeof(tstrM2MScan),NULL, 0,0); + if(s8Ret == M2M_SUCCESS) + { + gu8scanInProgress = 1; + } + } + else + { + s8Ret = M2M_ERR_INVALID_ARG; + } + } + else + { + s8Ret = M2M_ERR_SCAN_IN_PROGRESS; + } + return s8Ret; +} + +sint8 m2m_wifi_request_scan_passive(uint8 ch, uint16 scan_time) +{ + sint8 s8Ret = M2M_SUCCESS; + + if(!gu8scanInProgress) + { + if(((ch >= M2M_WIFI_CH_1) && (ch <= M2M_WIFI_CH_14)) || (ch == M2M_WIFI_CH_ALL)) + { + tstrM2MScan strtmp; + strtmp.u8ChNum = ch; + + strtmp.u16PassiveScanTime = scan_time; + + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_PASSIVE_SCAN, (uint8*)&strtmp, sizeof(tstrM2MScan),NULL, 0,0); + if(s8Ret == M2M_SUCCESS) + { + gu8scanInProgress = 1; + } + } + else + { + s8Ret = M2M_ERR_INVALID_ARG; + } + } + else + { + s8Ret = M2M_ERR_SCAN_IN_PROGRESS; + } + return s8Ret; +} + +sint8 m2m_wifi_request_scan_ssid_list(uint8 ch,uint8 * u8Ssidlist) +{ + sint8 s8Ret = M2M_ERR_INVALID_ARG; + + if(!gu8scanInProgress) + { + if((((ch >= M2M_WIFI_CH_1) && (ch <= M2M_WIFI_CH_14)) || (ch == M2M_WIFI_CH_ALL))&&(u8Ssidlist != NULL)) + { + tstrM2MScan strtmp; + uint16 u16Lsize = 0; + uint8 u8Apnum = u8Ssidlist[u16Lsize]; + if(u8Apnum <= MAX_HIDDEN_SITES) + { + u16Lsize++; + while(u8Apnum) + { + if(u8Ssidlist[u16Lsize] >= M2M_MAX_SSID_LEN){ + goto EXIT; + }else { + u16Lsize += u8Ssidlist[u16Lsize] + 1; + u8Apnum--; + } + } + strtmp.u8ChNum = ch; + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SCAN_SSID_LIST|M2M_REQ_DATA_PKT, (uint8*)&strtmp, sizeof(tstrM2MScan),u8Ssidlist, u16Lsize,sizeof(tstrM2MScan)); + if(s8Ret == M2M_SUCCESS) + { + gu8scanInProgress = 1; + } + } + } + } + else + { + s8Ret = M2M_ERR_SCAN_IN_PROGRESS; + } +EXIT: + return s8Ret; +} +sint8 m2m_wifi_wps(uint8 u8TriggerType,const char *pcPinNumber) +{ + tstrM2MWPSConnect strtmp; + + /* Stop Scan if it is ongoing. + */ + gu8scanInProgress = 0; + strtmp.u8TriggerType = u8TriggerType; + /*If WPS is using PIN METHOD*/ + if (u8TriggerType == WPS_PIN_TRIGGER) + m2m_memcpy ((uint8*)strtmp.acPinNumber,(uint8*) pcPinNumber,8); + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_WPS, (uint8*)&strtmp,sizeof(tstrM2MWPSConnect), NULL, 0,0); +} +sint8 m2m_wifi_wps_disable(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_WPS, NULL,0, NULL, 0, 0); + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_req_client_ctrl(uint8 cmd); +@brief Send a command to the PS Client (An WINC1500 board running the ps_firmware), + if the PS client send any commands it will be received in wifi_cb M2M_WIFI_RESP_CLIENT_INFO +@param [in] cmd + Control command sent from PS Server to PS Client (command values defined by the application) +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. +@sa m2m_wifi_req_server_init, M2M_WIFI_RESP_CLIENT_INFO +@pre m2m_wifi_req_server_init should be called first +@warning +*/ +sint8 m2m_wifi_req_client_ctrl(uint8 u8Cmd) +{ + + sint8 ret = M2M_SUCCESS; +#ifdef _PS_SERVER_ + tstrM2Mservercmd strCmd; + strCmd.u8cmd = u8Cmd; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CLIENT_CTRL, (uint8*)&strCmd, sizeof(tstrM2Mservercmd), NULL, 0, 0); +#else +#ifdef ARDUINO + (void)u8Cmd; // Silence "unused" warning +#endif + M2M_ERR("_PS_SERVER_ is not defined\n"); +#endif + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_req_server_init(uint8 ch); +@brief Initialize the PS Server, The WINC1500 support Non secure communication with another WINC1500, + (SERVER/CLIENT) through one byte command (probe request and probe response) without any connection setup +@param [in] ch + Server listening channel +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise +@sa m2m_wifi_req_client_ctrl +@warning The server mode can't be used with any other modes (STA/P2P/AP) +*/ +sint8 m2m_wifi_req_server_init(uint8 ch) +{ + sint8 ret = M2M_SUCCESS; +#ifdef _PS_SERVER_ + tstrM2mServerInit strServer; + strServer.u8Channel = ch; + ret = hif_send(M2M_REQ_GROUP_WIFI,M2M_WIFI_REQ_SERVER_INIT, (uint8*)&strServer, sizeof(tstrM2mServerInit), NULL, 0, 0); +#else +#ifdef ARDUINO + (void)ch; // Silence "unused" warning +#endif + M2M_ERR("_PS_SERVER_ is not defined\n"); +#endif + return ret; +} +sint8 m2m_wifi_p2p(uint8 u8Channel) +{ + sint8 ret = M2M_SUCCESS; + if((u8Channel == M2M_WIFI_CH_1) || (u8Channel == M2M_WIFI_CH_6) || (u8Channel == M2M_WIFI_CH_11)) + { + tstrM2MP2PConnect strtmp; + strtmp.u8ListenChannel = u8Channel; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_P2P, (uint8*)&strtmp, sizeof(tstrM2MP2PConnect), NULL, 0,0); + } + else + { + M2M_ERR("Listen channel should only be M2M_WIFI_CH_1/6/11 \n"); + ret = M2M_ERR_FAIL; + } + return ret; +} +sint8 m2m_wifi_p2p_disconnect(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_P2P, NULL, 0, NULL, 0, 0); + return ret; +} +sint8 m2m_wifi_enable_ap(CONST tstrM2MAPConfig* pstrM2MAPConfig) +{ + sint8 ret = M2M_ERR_FAIL; + if(M2M_SUCCESS == m2m_validate_ap_parameters(pstrM2MAPConfig)) + { +#ifdef ARDUINO + extern uint32 nmdrv_firm_ver; + uint16 txSize = sizeof(tstrM2MAPConfig); + + if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 5, 0)) { + // for backwards compat with firmwware 19.4.x and older + // (listen channel is 0 based, there is no au8Key field) + ((tstrM2MAPConfig*)pstrM2MAPConfig)->u8ListenChannel--; + txSize -= sizeof(pstrM2MAPConfig->au8Key) + 1; + } + + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_AP, (uint8 *)pstrM2MAPConfig, txSize, NULL, 0, 0); +#else + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_AP, (uint8 *)pstrM2MAPConfig, sizeof(tstrM2MAPConfig), NULL, 0, 0); +#endif + } + return ret; +} + +sint8 m2m_wifi_set_gains(tstrM2mWifiGainsParams* pstrM2mGain) +{ + sint8 ret = M2M_ERR_FAIL; + if(pstrM2mGain != NULL) + { + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_GAINS, (uint8 *)pstrM2mGain, sizeof(tstrM2mWifiGainsParams), NULL, 0, 0); + } + return ret; +} +sint8 m2m_wifi_disable_ap(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_AP, NULL, 0, NULL, 0, 0); + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_req_curr_rssi(void); +@brief Request the current RSSI for the current connected AP, + the response received in wifi_cb M2M_WIFI_RESP_CURRENT_RSSI +@sa M2M_WIFI_RESP_CURRENT_RSSI +@return The function shall return M2M_SUCCESS for success and a negative value otherwise. +*/ +sint8 m2m_wifi_req_curr_rssi(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CURRENT_RSSI, NULL, 0, NULL,0, 0); + return ret; +} +sint8 m2m_wifi_send_ethernet_pkt(uint8* pu8Packet,uint16 u16PacketSize) +{ + sint8 s8Ret = -1; + if((pu8Packet != NULL)&&(u16PacketSize>0)) + { + tstrM2MWifiTxPacketInfo strTxPkt; + + strTxPkt.u16PacketSize = u16PacketSize; + strTxPkt.u16HeaderLength = M2M_ETHERNET_HDR_LEN; + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SEND_ETHERNET_PACKET | M2M_REQ_DATA_PKT, + (uint8*)&strTxPkt, sizeof(tstrM2MWifiTxPacketInfo), pu8Packet, u16PacketSize, M2M_ETHERNET_HDR_OFFSET - M2M_HIF_HDR_OFFSET); + } + return s8Ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); +@brief Request the MAC address stored on the OTP (one time programmable) memory of the device. + (the function is Blocking until response received) +@param [out] pu8MacAddr + Output MAC address buffer of 6 bytes size. Valid only if *pu8Valid=1. +@param [out] pu8IsValid + A output boolean value to indicate the validity of pu8MacAddr in OTP. + Output zero if the OTP memory is not programmed, non-zero otherwise. +@return The function shall return M2M_SUCCESS for success and a negative value otherwise. +@sa m2m_wifi_get_mac_address +@pre m2m_wifi_init required to call any WIFI/socket function +*/ +sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8* pu8IsValid) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_chip_wake(); + if(ret == M2M_SUCCESS) + { + ret = nmi_get_otp_mac_address(pu8MacAddr, pu8IsValid); + if(ret == M2M_SUCCESS) + { + ret = hif_chip_sleep(); + } + } + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr) +@brief Request the current MAC address of the device (the working mac address). + (the function is Blocking until response received) +@param [out] pu8MacAddr + Output MAC address buffer of 6 bytes size. +@return The function shall return M2M_SUCCESS for success and a negative value otherwise. +@sa m2m_wifi_get_otp_mac_address +@pre m2m_wifi_init required to call any WIFI/socket function +*/ +sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_chip_wake(); + if(ret == M2M_SUCCESS) + { + ret = nmi_get_mac_address(pu8MacAddr); + if(ret == M2M_SUCCESS) + { + ret = hif_chip_sleep(); + } + } + + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_req_scan_result(uint8 index); +@brief Reads the AP information from the Scan Result list with the given index, + the response received in wifi_cb M2M_WIFI_RESP_SCAN_RESULT, + the response pointer should be casted with tstrM2mWifiscanResult structure +@param [in] index + Index for the requested result, the index range start from 0 till number of AP's found +@sa tstrM2mWifiscanResult,m2m_wifi_get_num_ap_found,m2m_wifi_request_scan +@return The function shall return M2M_SUCCESE for success and a negative value otherwise +@pre m2m_wifi_request_scan need to be called first, then m2m_wifi_get_num_ap_found + to get the number of AP's found +@warning Function used only in STA mode only. the scan result updated only if scan request called, + else it will be cashed in firmware for the host scan request result, + which mean if large delay occur between the scan request and the scan result request, + the result will not be up-to-date +*/ + +sint8 m2m_wifi_req_scan_result(uint8 index) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mReqScanResult strReqScanRlt; + strReqScanRlt.u8Index = index; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SCAN_RESULT, (uint8*) &strReqScanRlt, sizeof(tstrM2mReqScanResult), NULL, 0, 0); + return ret; +} +/*! +@fn NMI_API uint8 m2m_wifi_get_num_ap_found(void); +@brief Reads the number of AP's found in the last Scan Request, + The function read the number of AP's from global variable which updated in the + wifi_cb in M2M_WIFI_RESP_SCAN_DONE. +@sa m2m_wifi_request_scan +@return Return the number of AP's found in the last Scan Request. +@pre m2m_wifi_request_scan need to be called first +@warning That function need to be called in the wifi_cb in M2M_WIFI_RESP_SCAN_DONE, + calling that function in any other place will return undefined/undated numbers. + Function used only in STA mode only. +*/ +uint8 m2m_wifi_get_num_ap_found(void) +{ + return gu8ChNum; +} +/*! +@fn NMI_API uint8 m2m_wifi_get_sleep_mode(void); +@brief Get the current Power save mode. +@return The current operating power saving mode. +@sa tenuPowerSaveModes , m2m_wifi_set_sleep_mode +*/ +uint8 m2m_wifi_get_sleep_mode(void) +{ + return hif_get_sleep_mode(); +} +/*! +@fn NMI_API sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn); +@brief Set the power saving mode for the WINC1500. +@param [in] PsTyp + Desired power saving mode. Supported types are defined in tenuPowerSaveModes. +@param [in] BcastEn + Broadcast reception enable flag. + If it is 1, the WINC1500 must be awake each DTIM Beacon for receiving Broadcast traffic. + If it is 0, the WINC1500 will not wakeup at the DTIM Beacon, but its wakeup depends only + on the the configured Listen Interval. +@return The function SHALL return 0 for success and a negative value otherwise. +@sa tenuPowerSaveModes +@warning The function called once after initialization. +*/ +sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mPsType strPs; + strPs.u8PsType = PsTyp; + strPs.u8BcastEn = BcastEn; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SLEEP, (uint8*) &strPs,sizeof(tstrM2mPsType), NULL, 0, 0); + M2M_INFO("POWER SAVE %d\n",PsTyp); + hif_set_sleep_mode(PsTyp); + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_request_sleep(void) +@brief Request from WINC1500 device to Sleep for specific time in the M2M_PS_MANUAL Power save mode (only). +@param [in] u32SlpReqTime + Request Sleep in ms +@return The function SHALL return M2M_SUCCESS for success and a negative value otherwise. +@sa tenuPowerSaveModes , m2m_wifi_set_sleep_mode +@warning the Function should be called in M2M_PS_MANUAL power save only +*/ +sint8 m2m_wifi_request_sleep(uint32 u32SlpReqTime) +{ + sint8 ret = M2M_SUCCESS; + uint8 psType; + psType = hif_get_sleep_mode(); + if(psType == M2M_PS_MANUAL) + { + tstrM2mSlpReqTime strPs; + strPs.u32SleepTime = u32SlpReqTime; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DOZE, (uint8*) &strPs,sizeof(tstrM2mSlpReqTime), NULL, 0, 0); + } + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength); +@brief Set the WINC1500 device name which is used as P2P device name. +@param [in] pu8DeviceName + Buffer holding the device name. +@param [in] u8DeviceNameLength + Length of the device name. +@return The function SHALL return M2M_SUCCESS for success and a negative value otherwise. +@warning The Function called once after initialization. +*/ +sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength) +{ + tstrM2MDeviceNameConfig strDeviceName; + if(u8DeviceNameLength >= M2M_DEVICE_NAME_MAX) + { + u8DeviceNameLength = M2M_DEVICE_NAME_MAX; + } + //pu8DeviceName[u8DeviceNameLength] = '\0'; + u8DeviceNameLength ++; + m2m_memcpy(strDeviceName.au8DeviceName, pu8DeviceName, u8DeviceNameLength); + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_DEVICE_NAME, + (uint8*)&strDeviceName, sizeof(tstrM2MDeviceNameConfig), NULL, 0,0); +} +sint8 m2m_wifi_get_firmware_version(tstrM2mRev *pstrRev) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_chip_wake(); + if(ret == M2M_SUCCESS) + { + ret = nm_get_firmware_full_info(pstrRev); + hif_chip_sleep(); + } + return ret; +} +#ifdef CONF_MGMT +sint8 m2m_wifi_enable_monitoring_mode(tstrM2MWifiMonitorModeCtrl *pstrMtrCtrl, uint8 *pu8PayloadBuffer, + uint16 u16BufferSize, uint16 u16DataOffset) +{ + sint8 s8Ret = -1; + if((pstrMtrCtrl->u8ChannelID >= M2M_WIFI_CH_1) && (pstrMtrCtrl->u8ChannelID <= M2M_WIFI_CH_14)) + { + gstrMgmtCtrl.pu8Buf = pu8PayloadBuffer; + gstrMgmtCtrl.u16Sz = u16BufferSize; + gstrMgmtCtrl.u16Offset = u16DataOffset; + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_MONITORING, + (uint8*)pstrMtrCtrl, sizeof(tstrM2MWifiMonitorModeCtrl), NULL, 0,0); + } + return s8Ret; +} + +sint8 m2m_wifi_disable_monitoring_mode(void) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_MONITORING, NULL, 0, NULL, 0,0); +} + +sint8 m2m_wifi_send_wlan_pkt(uint8 *pu8WlanPacket, uint16 u16WlanHeaderLength, uint16 u16WlanPktSize) +{ + sint8 s8Ret = -1; + if(pu8WlanPacket != NULL) + { + tstrM2MWifiTxPacketInfo strTxPkt; + + strTxPkt.u16PacketSize = u16WlanPktSize; + strTxPkt.u16HeaderLength = u16WlanHeaderLength; + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SEND_WIFI_PACKET | M2M_REQ_DATA_PKT, + (uint8*)&strTxPkt, sizeof(tstrM2MWifiTxPacketInfo), pu8WlanPacket, u16WlanPktSize, sizeof(tstrM2MWifiTxPacketInfo)); + } + return s8Ret; +} +#endif + +sint8 m2m_wifi_start_provision_mode(tstrM2MAPConfig *pstrAPConfig, char *pcHttpServerDomainName, uint8 bEnableHttpRedirect) +{ + sint8 s8Ret = M2M_ERR_FAIL; + + if((pstrAPConfig != NULL)) + { + tstrM2MProvisionModeConfig strProvConfig; + if(M2M_SUCCESS == m2m_validate_ap_parameters(pstrAPConfig)) + { + m2m_memcpy((uint8*)&strProvConfig.strApConfig, (uint8*)pstrAPConfig, sizeof(tstrM2MAPConfig)); + if((m2m_strlen((uint8 *)pcHttpServerDomainName) <= 0) || (NULL == pcHttpServerDomainName)) + { + M2M_ERR("INVALID DOMAIN NAME\n"); + goto ERR1; + } + m2m_memcpy((uint8*)strProvConfig.acHttpServerDomainName, (uint8*)pcHttpServerDomainName, 64); + strProvConfig.u8EnableRedirect = bEnableHttpRedirect; + + /* Stop Scan if it is ongoing. + */ + gu8scanInProgress = 0; +#ifdef ARDUINO + extern uint32 nmdrv_firm_ver; + uint16 txSize = sizeof(tstrM2MProvisionModeConfig); + + if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 5, 0)) { + // for backwards compat with firmwware 19.4.x and older + // (listen channel is 0 based, there is no au8Key field) + strProvConfig.strApConfig.u8ListenChannel--; + txSize -= sizeof(strProvConfig.strApConfig.au8Key) + 1; + m2m_memcpy((uint8*)&strProvConfig.strApConfig.au8Key[3], (uint8*)pcHttpServerDomainName, 64); + uint8* pu8EnableRedirect = (uint8*)strProvConfig.strApConfig.au8Key; + pu8EnableRedirect[3 + 64] = bEnableHttpRedirect; + } + + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_START_PROVISION_MODE | M2M_REQ_DATA_PKT, + (uint8*)&strProvConfig, txSize, NULL, 0, 0); +#else + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_START_PROVISION_MODE | M2M_REQ_DATA_PKT, + (uint8*)&strProvConfig, sizeof(tstrM2MProvisionModeConfig), NULL, 0, 0); +#endif + } + else + { + /*goto ERR1;*/ + } + } +ERR1: + return s8Ret; +} + +sint8 m2m_wifi_stop_provision_mode(void) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_STOP_PROVISION_MODE, NULL, 0, NULL, 0, 0); +} + +sint8 m2m_wifi_get_connection_info(void) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_GET_CONN_INFO, NULL, 0, NULL, 0, 0); +} + +sint8 m2m_wifi_set_sytem_time(uint32 u32UTCSeconds) +{ + /* + The firmware accepts timestamps relative to 1900 like NTP Timestamp. + */ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_SYS_TIME, (uint8*)&u32UTCSeconds, sizeof(tstrSystemTime), NULL, 0, 0); +} +/*! + * @fn NMI_API sint8 m2m_wifi_get_sytem_time(void); + * @see m2m_wifi_enable_sntp + tstrSystemTime + * @note get the system time from the sntp client + * using the API \ref m2m_wifi_get_sytem_time. + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +sint8 m2m_wifi_get_sytem_time(void) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_GET_SYS_TIME, NULL,0, NULL, 0, 0); +} + +sint8 m2m_wifi_enable_sntp(uint8 bEnable) +{ + uint8 u8Req; + + u8Req = bEnable ? M2M_WIFI_REQ_ENABLE_SNTP_CLIENT : M2M_WIFI_REQ_DISABLE_SNTP_CLIENT; + return hif_send(M2M_REQ_GROUP_WIFI, u8Req, NULL, 0, NULL, 0, 0); +} +/*! +@fn NMI_API sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode); +@brief Change the power profile mode +@param [in] u8PwrMode + Change the WINC power profile to different mode + PWR_LOW1/PWR_LOW2/PWR_HIGH/PWR_AUTO (tenuM2mPwrMode) +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. +@sa tenuM2mPwrMode +@pre m2m_wifi_init +@warning must be called after the initializations and before any connection request and can't be changed in run time, +*/ +sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mPwrMode strM2mPwrMode; + strM2mPwrMode.u8PwrMode = u8PwrMode; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_POWER_PROFILE, (uint8*)&strM2mPwrMode,sizeof(tstrM2mPwrMode), NULL, 0, 0); + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel); +@brief set the TX power tenuM2mTxPwrLevel +@param [in] u8TxPwrLevel + change the TX power tenuM2mTxPwrLevel +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. +@sa tenuM2mTxPwrLevel +@pre m2m_wifi_init +@warning +*/ +sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mTxPwrLevel strM2mTxPwrLevel; + strM2mTxPwrLevel.u8TxPwrLevel = u8TxPwrLevel; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_TX_POWER, (uint8*)&strM2mTxPwrLevel,sizeof(tstrM2mTxPwrLevel), NULL, 0, 0); + return ret; +} + +/*! +@fn NMI_API sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable); +@brief Enable or Disable logs in run time (Disable Firmware logs will + enhance the firmware start-up time and performance) +@param [in] u8Enable + Set 1 to enable the logs 0 for disable +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. +@sa __DISABLE_FIRMWARE_LOGS__ (build option to disable logs from initializations) +@pre m2m_wifi_init +@warning +*/ +sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mEnableLogs strM2mEnableLogs; + strM2mEnableLogs.u8Enable = u8Enable; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_ENABLE_LOGS, (uint8*)&strM2mEnableLogs,sizeof(tstrM2mEnableLogs), NULL, 0, 0); + return ret; +} + +/*! +@fn NMI_API sint8 m2m_wifi_set_battery_voltage(uint16 u16BattVoltx100); +@brief Enable or Disable logs in run time (Disable Firmware logs will + enhance the firmware start-up time and performance) +@param [in] u16BattVoltx100 + battery voltage multiplied by 100 +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. +@sa __DISABLE_FIRMWARE_LOGS__ (build option to disable logs from initializations) +@pre m2m_wifi_init +@warning +*/ +sint8 m2m_wifi_set_battery_voltage(uint16 u16BattVoltx100) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mBatteryVoltage strM2mBattVol = {0}; + strM2mBattVol.u16BattVolt = u16BattVoltx100; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_BATTERY_VOLTAGE, (uint8*)&strM2mBattVol,sizeof(tstrM2mBatteryVoltage), NULL, 0, 0); + return ret; +} +/*! +@fn sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PrngBuff,uint16 u16PrngSize) +@brief Get random bytes using the PRNG bytes. +@param [in] u16PrngSize + Size of the required random bytes to be generated. +@param [in] pu8PrngBuff + Pointer to user allocated buffer. +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. +*/ +sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PrngBuff,uint16 u16PrngSize) +{ + sint8 ret = M2M_ERR_FAIL; + tstrPrng strRng = {0}; + if((u16PrngSize < (M2M_BUFFER_MAX_SIZE - sizeof(tstrPrng)))&&(pu8PrngBuff != NULL)) + { + strRng.u16PrngSize = u16PrngSize; + strRng.pu8RngBuff = pu8PrngBuff; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_GET_PRNG|M2M_REQ_DATA_PKT,(uint8 *)&strRng, sizeof(tstrPrng),NULL,0, 0); + } + else + { + M2M_ERR("PRNG Buffer exceeded maximum size %d or NULL Buffer\n",u16PrngSize); + } + return ret; +} +#ifdef ETH_MODE +/*! +@fn \ + NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8* pu8MulticastMacAddress, uint8 u8AddRemove) + +@brief + Add MAC filter to receive Multicast packets. + +@param [in] pu8MulticastMacAddress + Pointer to the MAC address. +@param [in] u8AddRemove + Flag to Add/Remove MAC address. +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ + +NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8* pu8MulticastMacAddress, uint8 u8AddRemove) +{ + sint8 s8ret = M2M_ERR_FAIL; + tstrM2MMulticastMac strMulticastMac; + + if(pu8MulticastMacAddress != NULL ) + { + strMulticastMac.u8AddRemove = u8AddRemove; + m2m_memcpy(strMulticastMac.au8macaddress,pu8MulticastMacAddress,M2M_MAC_ADDRES_LEN); + M2M_DBG("mac multicast: %x:%x:%x:%x:%x:%x\r\n",strMulticastMac.au8macaddress[0],strMulticastMac.au8macaddress[1],strMulticastMac.au8macaddress[2],strMulticastMac.au8macaddress[3],strMulticastMac.au8macaddress[4],strMulticastMac.au8macaddress[5]); + s8ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_MAC_MCAST, (uint8 *)&strMulticastMac,sizeof(tstrM2MMulticastMac),NULL,0,0); + } + + return s8ret; + +} + +/*! +@fn \ + NMI_API sint8 m2m_wifi_set_receive_buffer(void* pvBuffer,uint16 u16BufferLen); + +@brief + set the ethernet receive buffer, should be called in the receive call back. + +@param [in] pvBuffer + Pointer to the ethernet receive buffer. +@param [in] u16BufferLen + Length of the buffer. + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_set_receive_buffer(void* pvBuffer,uint16 u16BufferLen) +{ + sint8 s8ret = M2M_SUCCESS; + if(pvBuffer != NULL) + { + gau8ethRcvBuf = pvBuffer; + gu16ethRcvBufSize= u16BufferLen; + } + else + { + s8ret = M2M_ERR_FAIL; + M2M_ERR("Buffer NULL pointer\r\n"); + } + return s8ret; +} +#endif /* ETH_MODE */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmasic.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmasic.c new file mode 100644 index 0000000..91c0e5a --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmasic.c @@ -0,0 +1,688 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 ASIC specific internal APIs. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "common/include/nm_common.h" +#include "driver/source/nmbus.h" +#include "bsp/include/nm_bsp.h" +#include "driver/source/nmasic.h" +#include "driver/include/m2m_types.h" + +#define NMI_GLB_RESET_0 (NMI_PERIPH_REG_BASE + 0x400) +#define NMI_INTR_REG_BASE (NMI_PERIPH_REG_BASE + 0xa00) +#define NMI_PIN_MUX_0 (NMI_PERIPH_REG_BASE + 0x408) +#define NMI_INTR_ENABLE (NMI_INTR_REG_BASE) +#define GET_UINT32(X,Y) (X[0+Y] + ((uint32)X[1+Y]<<8) + ((uint32)X[2+Y]<<16) +((uint32)X[3+Y]<<24)) + +/*SPI and I2C only*/ +#define CORT_HOST_COMM (0x10) +#define HOST_CORT_COMM (0x0b) +#define WAKE_CLK_REG (0x1) +#define CLOCKS_EN_REG (0xf) + + + +#ifdef ARDUINO +#define TIMEOUT (2000) +#else +#define TIMEOUT (0xfffffffful) +#endif +#define WAKUP_TRAILS_TIMEOUT (4) + +sint8 chip_apply_conf(uint32 u32Conf) +{ + sint8 ret = M2M_SUCCESS; + uint32 val32 = u32Conf; + +#if (defined __ENABLE_PMU__) || (defined CONF_WINC_INT_PMU) + val32 |= rHAVE_USE_PMU_BIT; +#endif +#ifdef __ENABLE_SLEEP_CLK_SRC_RTC__ + val32 |= rHAVE_SLEEP_CLK_SRC_RTC_BIT; +#elif defined __ENABLE_SLEEP_CLK_SRC_XO__ + val32 |= rHAVE_SLEEP_CLK_SRC_XO_BIT; +#endif +#ifdef __ENABLE_EXT_PA_INV_TX_RX__ + val32 |= rHAVE_EXT_PA_INV_TX_RX; +#endif +#ifdef __ENABLE_LEGACY_RF_SETTINGS__ + val32 |= rHAVE_LEGACY_RF_SETTINGS; +#endif +#ifdef __DISABLE_FIRMWARE_LOGS__ + val32 |= rHAVE_LOGS_DISABLED_BIT; +#endif + + val32 |= rHAVE_RESERVED1_BIT; + do { + nm_write_reg(rNMI_GP_REG_1, val32); + if(val32 != 0) { + uint32 reg = 0; + ret = nm_read_reg_with_ret(rNMI_GP_REG_1, ®); + if(ret == M2M_SUCCESS) { + if(reg == val32) + break; + } + } else { + break; + } + } while(1); + + return M2M_SUCCESS; +} +void chip_idle(void) +{ + uint32 reg = 0; + nm_read_reg_with_ret(WAKE_CLK_REG, ®); + if(reg & NBIT1) + { + reg &=~ NBIT1; + nm_write_reg(WAKE_CLK_REG, reg); + } +} + +sint8 enable_interrupts(void) +{ + uint32 reg = 0; + sint8 ret = M2M_SUCCESS; + /** + interrupt pin mux select + **/ + ret = nm_read_reg_with_ret(NMI_PIN_MUX_0, ®); + if (M2M_SUCCESS != ret) goto ERR1; + + reg |= ((uint32) 1 << 8); + ret = nm_write_reg(NMI_PIN_MUX_0, reg); + if (M2M_SUCCESS != ret) goto ERR1; + + /** + interrupt enable + **/ + ret = nm_read_reg_with_ret(NMI_INTR_ENABLE, ®); + if (M2M_SUCCESS != ret) goto ERR1; + + reg |= ((uint32) 1 << 16); + ret = nm_write_reg(NMI_INTR_ENABLE, reg); + if (M2M_SUCCESS != ret) goto ERR1; +ERR1: + return ret; +} + +sint8 cpu_start(void) { + uint32 reg = 0; + sint8 ret; + + /** + reset regs + */ + ret = nm_write_reg(BOOTROM_REG,0); + ret += nm_write_reg(NMI_STATE_REG,0); + ret += nm_write_reg(NMI_REV_REG,0); + /** + Go... + **/ + ret += nm_read_reg_with_ret(0x1118, ®); + reg |= (1 << 0); + ret += nm_write_reg(0x1118, reg); + ret += nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); + if ((reg & (1ul << 10)) == (1ul << 10)) { + reg &= ~(1ul << 10); + ret += nm_write_reg(NMI_GLB_RESET_0, reg); + } + reg |= (1ul << 10); + ret += nm_write_reg(NMI_GLB_RESET_0, reg); + nm_bsp_sleep(1); + return ret; +} + +uint32 nmi_get_chipid(void) +{ + static uint32 chipid = 0; + + if (chipid == 0) { + uint32 rfrevid; + + if((nm_read_reg_with_ret(0x1000, &chipid)) != M2M_SUCCESS) { + chipid = 0; + return 0; + } + //if((ret = nm_read_reg_with_ret(0x11fc, &revid)) != M2M_SUCCESS) { + // return 0; + //} + if((nm_read_reg_with_ret(0x13f4, &rfrevid)) != M2M_SUCCESS) { + chipid = 0; + return 0; + } + + if (chipid == 0x1002a0) { + if (rfrevid == 0x1) { /* 1002A0 */ + } else /* if (rfrevid == 0x2) */ { /* 1002A1 */ + chipid = 0x1002a1; + } + } else if(chipid == 0x1002b0) { + if(rfrevid == 3) { /* 1002B0 */ + } else if(rfrevid == 4) { /* 1002B1 */ + chipid = 0x1002b1; + } else /* if(rfrevid == 5) */ { /* 1002B2 */ + chipid = 0x1002b2; + } + }else if(chipid == 0x1000F0) { + if((nm_read_reg_with_ret(0x3B0000, &chipid)) != M2M_SUCCESS) { + chipid = 0; + return 0; + } + }else { + + } +//#define PROBE_FLASH +#ifdef PROBE_FLASH + if(chipid) { + UWORD32 flashid; + + flashid = probe_spi_flash(); + if(flashid == 0x1230ef) { + chipid &= ~(0x0f0000); + chipid |= 0x050000; + } + if(flashid == 0xc21320c2) { + chipid &= ~(0x0f0000); + chipid |= 0x050000; + } + } +#else + /*M2M is by default have SPI flash*/ + chipid &= ~(0x0f0000); + chipid |= 0x050000; +#endif /* PROBE_FLASH */ + } + return chipid; +} + +uint32 nmi_get_rfrevid(void) +{ + uint32 rfrevid; + if((nm_read_reg_with_ret(0x13f4, &rfrevid)) != M2M_SUCCESS) { + rfrevid = 0; + return 0; + } + return rfrevid; +} + +void restore_pmu_settings_after_global_reset(void) +{ + /* + * Must restore PMU register value after + * global reset if PMU toggle is done at + * least once since the last hard reset. + */ + if(REV(nmi_get_chipid()) >= REV_2B0) { + nm_write_reg(0x1e48, 0xb78469ce); + } +} + +void nmi_update_pll(void) +{ + uint32 pll; + + pll = nm_read_reg(0x1428); + pll &= ~0x1ul; + nm_write_reg(0x1428, pll); + pll |= 0x1ul; + nm_write_reg(0x1428, pll); + +} +void nmi_set_sys_clk_src_to_xo(void) +{ + uint32 val32; + + /* Switch system clock source to XO. This will take effect after nmi_update_pll(). */ + val32 = nm_read_reg(0x141c); + val32 |= (1 << 2); + nm_write_reg(0x141c, val32); + + /* Do PLL update */ + nmi_update_pll(); +} +sint8 chip_sleep(void) +{ + uint32 reg; + sint8 ret = M2M_SUCCESS; + + while(1) + { + ret = nm_read_reg_with_ret(CORT_HOST_COMM,®); + if(ret != M2M_SUCCESS) goto ERR1; + if((reg & NBIT0) == 0) break; + } + + /* Clear bit 1 */ + ret = nm_read_reg_with_ret(WAKE_CLK_REG, ®); + if(ret != M2M_SUCCESS)goto ERR1; + if(reg & NBIT1) + { + reg &=~NBIT1; + ret = nm_write_reg(WAKE_CLK_REG, reg); + if(ret != M2M_SUCCESS)goto ERR1; + } + + ret = nm_read_reg_with_ret(HOST_CORT_COMM, ®); + if(ret != M2M_SUCCESS)goto ERR1; + if(reg & NBIT0) + { + reg &= ~NBIT0; + ret = nm_write_reg(HOST_CORT_COMM, reg); + if(ret != M2M_SUCCESS)goto ERR1; + } + +ERR1: + return ret; +} +sint8 chip_wake(void) +{ + sint8 ret = M2M_SUCCESS; + uint32 reg = 0, clk_status_reg = 0,trials = 0; + + ret = nm_read_reg_with_ret(HOST_CORT_COMM, ®); + if(ret != M2M_SUCCESS)goto _WAKE_EXIT; + + if(!(reg & NBIT0)) + { + /*USE bit 0 to indicate host wakeup*/ + ret = nm_write_reg(HOST_CORT_COMM, reg|NBIT0); + if(ret != M2M_SUCCESS)goto _WAKE_EXIT; + } + + ret = nm_read_reg_with_ret(WAKE_CLK_REG, ®); + if(ret != M2M_SUCCESS)goto _WAKE_EXIT; + /* Set bit 1 */ + if(!(reg & NBIT1)) + { + ret = nm_write_reg(WAKE_CLK_REG, reg | NBIT1); + if(ret != M2M_SUCCESS) goto _WAKE_EXIT; + } + + do + { + ret = nm_read_reg_with_ret(CLOCKS_EN_REG, &clk_status_reg); + if(ret != M2M_SUCCESS) { + M2M_ERR("Bus error (5).%d %lx\n",ret,clk_status_reg); + goto _WAKE_EXIT; + } + if(clk_status_reg & NBIT2) { + break; + } + nm_bsp_sleep(2); + trials++; + if(trials > WAKUP_TRAILS_TIMEOUT) + { + M2M_ERR("Failed to wakup the chip\n"); + ret = M2M_ERR_TIME_OUT; + goto _WAKE_EXIT; + } + }while(1); + + /*workaround sometimes spi fail to read clock regs after reading/writing clockless registers*/ + nm_bus_reset(); + +_WAKE_EXIT: + return ret; +} +sint8 cpu_halt(void) +{ + sint8 ret; + uint32 reg = 0; + ret = nm_read_reg_with_ret(0x1118, ®); + reg |= (1 << 0); + ret += nm_write_reg(0x1118, reg); + ret += nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); + if ((reg & (1ul << 10)) == (1ul << 10)) { + reg &= ~(1ul << 10); + ret += nm_write_reg(NMI_GLB_RESET_0, reg); + ret += nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); + } + return ret; +} +sint8 chip_reset_and_cpu_halt(void) +{ + sint8 ret = M2M_SUCCESS; + + /*Wakeup needed only for I2C interface*/ + ret = chip_wake(); + if(ret != M2M_SUCCESS) goto ERR1; + /*Reset and CPU halt need for no wait board only*/ + ret = chip_reset(); + if(ret != M2M_SUCCESS) goto ERR1; + ret = cpu_halt(); + if(ret != M2M_SUCCESS) goto ERR1; +ERR1: + return ret; +} +sint8 chip_reset(void) +{ + sint8 ret = M2M_SUCCESS; + ret = nm_write_reg(NMI_GLB_RESET_0, 0); + nm_bsp_sleep(50); + return ret; +} + +sint8 wait_for_bootrom(uint8 arg) +{ + sint8 ret = M2M_SUCCESS; + uint32 reg = 0, cnt = 0; + uint32 u32GpReg1 = 0; + uint32 u32DriverVerInfo = M2M_MAKE_VERSION_INFO(M2M_RELEASE_VERSION_MAJOR_NO,\ + M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO,\ + M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO,\ + M2M_RELEASE_VERSION_PATCH_NO); + + + reg = 0; + while(1) { + reg = nm_read_reg(0x1014); /* wait for efuse loading done */ + if (reg & 0x80000000) { + break; + } + nm_bsp_sleep(1); /* TODO: Why bus error if this delay is not here. */ + } + reg = nm_read_reg(M2M_WAIT_FOR_HOST_REG); + reg &= 0x1; + + /* check if waiting for the host will be skipped or not */ + if(reg == 0) + { + reg = 0; + while(reg != M2M_FINISH_BOOT_ROM) + { + nm_bsp_sleep(1); + reg = nm_read_reg(BOOTROM_REG); + + if(++cnt > TIMEOUT) + { + M2M_DBG("failed to load firmware from flash.\n"); + ret = M2M_ERR_INIT; + goto ERR2; + } + } + } + + if(M2M_WIFI_MODE_ATE_HIGH == arg) { + nm_write_reg(NMI_REV_REG, M2M_ATE_FW_START_VALUE); + nm_write_reg(NMI_STATE_REG, NBIT20); + }else if(M2M_WIFI_MODE_ATE_LOW == arg) { + nm_write_reg(NMI_REV_REG, M2M_ATE_FW_START_VALUE); + nm_write_reg(NMI_STATE_REG, 0); + }else if(M2M_WIFI_MODE_ETHERNET == arg){ + u32GpReg1 = rHAVE_ETHERNET_MODE_BIT; + nm_write_reg(NMI_STATE_REG, u32DriverVerInfo); + } else { + /*bypass this step*/ + nm_write_reg(NMI_STATE_REG, u32DriverVerInfo); + } + + if(REV(nmi_get_chipid()) >= REV_3A0){ + chip_apply_conf(u32GpReg1 | rHAVE_USE_PMU_BIT); + } else { + chip_apply_conf(u32GpReg1); + } + M2M_INFO("DriverVerInfo: 0x%08lx\n",u32DriverVerInfo); + + nm_write_reg(BOOTROM_REG,M2M_START_FIRMWARE); + +#ifdef __ROM_TEST__ + rom_test(); +#endif /* __ROM_TEST__ */ + +ERR2: + return ret; +} + +sint8 wait_for_firmware_start(uint8 arg) +{ + sint8 ret = M2M_SUCCESS; + uint32 reg = 0, cnt = 0; + uint32 u32Timeout = TIMEOUT; + volatile uint32 regAddress = NMI_STATE_REG; + volatile uint32 checkValue = M2M_FINISH_INIT_STATE; + + if((M2M_WIFI_MODE_ATE_HIGH == arg)||(M2M_WIFI_MODE_ATE_LOW == arg)) { + regAddress = NMI_REV_REG; + checkValue = M2M_ATE_FW_IS_UP_VALUE; + } else { + /*bypass this step*/ + } + + + while (checkValue != reg) + { + nm_bsp_sleep(2); /* TODO: Why bus error if this delay is not here. */ + M2M_DBG("%x %x %x\n",(unsigned int)nm_read_reg(0x108c),(unsigned int)nm_read_reg(0x108c),(unsigned int)nm_read_reg(0x14A0)); + reg = nm_read_reg(regAddress); + if(++cnt >= u32Timeout) + { + M2M_DBG("Time out for wait firmware Run\n"); + ret = M2M_ERR_INIT; + goto ERR; + } + } + if(M2M_FINISH_INIT_STATE == checkValue) + { + nm_write_reg(NMI_STATE_REG, 0); + } +ERR: + return ret; +} + +sint8 chip_deinit(void) +{ + uint32 reg = 0; + sint8 ret; + + /** + stop the firmware, need a re-download + **/ + ret = nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); + if (ret != M2M_SUCCESS) { + M2M_ERR("failed to de-initialize\n"); + goto ERR1; + } + reg &= ~(1 << 10); + ret = nm_write_reg(NMI_GLB_RESET_0, reg); + if (ret != M2M_SUCCESS) { + M2M_ERR("failed to de-initialize\n"); + goto ERR1; + } + +ERR1: + return ret; +} + +#ifdef CONF_PERIPH + +sint8 set_gpio_dir(uint8 gpio, uint8 dir) +{ + uint32 val32; + sint8 ret; + + ret = nm_read_reg_with_ret(0x20108, &val32); + if(ret != M2M_SUCCESS) goto _EXIT; + + if(dir) { + val32 |= (1ul << gpio); + } else { + val32 &= ~(1ul << gpio); + } + + ret = nm_write_reg(0x20108, val32); + +_EXIT: + return ret; +} +sint8 set_gpio_val(uint8 gpio, uint8 val) +{ + uint32 val32; + sint8 ret; + + ret = nm_read_reg_with_ret(0x20100, &val32); + if(ret != M2M_SUCCESS) goto _EXIT; + + if(val) { + val32 |= (1ul << gpio); + } else { + val32 &= ~(1ul << gpio); + } + + ret = nm_write_reg(0x20100, val32); + +_EXIT: + return ret; +} + +sint8 get_gpio_val(uint8 gpio, uint8* val) +{ + uint32 val32; + sint8 ret; + + ret = nm_read_reg_with_ret(0x20104, &val32); + if(ret != M2M_SUCCESS) goto _EXIT; + + *val = (uint8)((val32 >> gpio) & 0x01); + +_EXIT: + return ret; +} + +sint8 pullup_ctrl(uint32 pinmask, uint8 enable) +{ + sint8 s8Ret; + uint32 val32; + s8Ret = nm_read_reg_with_ret(0x142c, &val32); + if(s8Ret != M2M_SUCCESS) { + M2M_ERR("[pullup_ctrl]: failed to read\n"); + goto _EXIT; + } + if(enable) { + val32 &= ~pinmask; + } else { + val32 |= pinmask; + } + s8Ret = nm_write_reg(0x142c, val32); + if(s8Ret != M2M_SUCCESS) { + M2M_ERR("[pullup_ctrl]: failed to write\n"); + goto _EXIT; + } +_EXIT: + return s8Ret; +} +#endif /* CONF_PERIPH */ + +sint8 nmi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid) +{ + sint8 ret; + uint32 u32RegValue; + uint8 mac[6]; + tstrGpRegs strgp = {0}; + + ret = nm_read_reg_with_ret(rNMI_GP_REG_2, &u32RegValue); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; +#ifdef ARDUINO + if (u32RegValue) { + ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; + u32RegValue = strgp.u32Mac_efuse_mib; + } else { + // firmware version 19.3.0 + ret = nm_read_reg_with_ret(rNMI_GP_REG_0, &u32RegValue); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; + } +#else + ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; + u32RegValue = strgp.u32Mac_efuse_mib; +#endif + if(!EFUSED_MAC(u32RegValue)) { + M2M_DBG("Default MAC\n"); + m2m_memset(pu8MacAddr, 0, 6); + goto _EXIT_ERR; + } + + M2M_DBG("OTP MAC\n"); + u32RegValue >>=16; + ret = nm_read_block(u32RegValue|0x30000, mac, 6); + m2m_memcpy(pu8MacAddr,mac,6); + if(pu8IsValid) *pu8IsValid = 1; + return ret; + +_EXIT_ERR: + if(pu8IsValid) *pu8IsValid = 0; + return ret; +} + +sint8 nmi_get_mac_address(uint8 *pu8MacAddr) +{ + sint8 ret; + uint32 u32RegValue; + uint8 mac[6]; + tstrGpRegs strgp = {0}; + + ret = nm_read_reg_with_ret(rNMI_GP_REG_2, &u32RegValue); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; +#ifdef ARDUINO + if (u32RegValue) { + ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; + u32RegValue = strgp.u32Mac_efuse_mib; + } else { + // firmware version 19.3.0 + ret = nm_read_reg_with_ret(rNMI_GP_REG_0, &u32RegValue); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; + } +#else + ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; + u32RegValue = strgp.u32Mac_efuse_mib; +#endif + u32RegValue &=0x0000ffff; + ret = nm_read_block(u32RegValue|0x30000, mac, 6); + m2m_memcpy(pu8MacAddr, mac, 6); + + return ret; + +_EXIT_ERR: + return ret; +} diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmasic.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmasic.h new file mode 100644 index 0000000..84a395b --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmasic.h @@ -0,0 +1,215 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 ASIC specific internal APIs. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +#ifndef _NMASIC_H_ +#define _NMASIC_H_ + +#include "common/include/nm_common.h" + +#define NMI_PERIPH_REG_BASE 0x1000 +#define NMI_CHIPID (NMI_PERIPH_REG_BASE) +#define rNMI_GP_REG_0 (0x149c) +#define rNMI_GP_REG_1 (0x14A0) +#define rNMI_GP_REG_2 (0xc0008) +#define rNMI_GLB_RESET (0x1400) +#define rNMI_BOOT_RESET_MUX (0x1118) +#define NMI_STATE_REG (0x108c) +#define BOOTROM_REG (0xc000c) +#define NMI_REV_REG (0x207ac) /*Also, Used to load ATE firmware from SPI Flash and to ensure that it is running too*/ +#define NMI_REV_REG_ATE (0x1048) /*Revision info register in case of ATE FW*/ +#define M2M_WAIT_FOR_HOST_REG (0x207bc) +#define M2M_FINISH_INIT_STATE 0x02532636UL +#define M2M_FINISH_BOOT_ROM 0x10add09eUL +#define M2M_START_FIRMWARE 0xef522f61UL +#define M2M_START_PS_FIRMWARE 0x94992610UL + +#define M2M_ATE_FW_START_VALUE (0x3C1CD57D) /*Also, Change this value in boot_firmware if it will be changed here*/ +#define M2M_ATE_FW_IS_UP_VALUE (0xD75DC1C3) /*Also, Change this value in ATE (Burst) firmware if it will be changed here*/ + +#define REV_2B0 (0x2B0) +#define REV_B0 (0x2B0) +#define REV_3A0 (0x3A0) +#define GET_CHIPID() nmi_get_chipid() +#define ISNMC1000(id) ((((id) & 0xfffff000) == 0x100000) ? 1 : 0) +#define ISNMC1500(id) ((((id) & 0xfffff000) == 0x150000) ? 1 : 0) +#define ISNMC3000(id) ((((id) & 0xfff00000) == 0x300000) ? 1 : 0) +#define REV(id) (((id) & 0x00000fff )) +#define EFUSED_MAC(value) (value & 0xffff0000) + +#define rHAVE_SDIO_IRQ_GPIO_BIT (NBIT0) +#define rHAVE_USE_PMU_BIT (NBIT1) +#define rHAVE_SLEEP_CLK_SRC_RTC_BIT (NBIT2) +#define rHAVE_SLEEP_CLK_SRC_XO_BIT (NBIT3) +#define rHAVE_EXT_PA_INV_TX_RX (NBIT4) +#define rHAVE_LEGACY_RF_SETTINGS (NBIT5) +#define rHAVE_LOGS_DISABLED_BIT (NBIT6) +#define rHAVE_ETHERNET_MODE_BIT (NBIT7) +#define rHAVE_RESERVED1_BIT (NBIT8) + +typedef struct{ + uint32 u32Mac_efuse_mib; + uint32 u32Firmware_Ota_rev; +}tstrGpRegs; + +#ifdef __cplusplus + extern "C" { +#endif + +/* +* @fn cpu_halt +* @brief +*/ +sint8 cpu_halt(void); +/* +* @fn chip_sleep +* @brief +*/ +sint8 chip_sleep(void); +/* +* @fn chip_wake +* @brief +*/ +sint8 chip_wake(void); +/* +* @fn chip_idle +* @brief +*/ +void chip_idle(void); +/* +* @fn enable_interrupts +* @brief +*/ +sint8 enable_interrupts(void); +/* +* @fn cpu_start +* @brief +*/ +sint8 cpu_start(void); +/* +* @fn nmi_get_chipid +* @brief +*/ +uint32 nmi_get_chipid(void); +/* +* @fn nmi_get_rfrevid +* @brief +*/ +uint32 nmi_get_rfrevid(void); +/* +* @fn restore_pmu_settings_after_global_reset +* @brief +*/ +void restore_pmu_settings_after_global_reset(void); +/* +* @fn nmi_update_pll +* @brief +*/ +void nmi_update_pll(void); +/* +* @fn nmi_set_sys_clk_src_to_xo +* @brief +*/ +void nmi_set_sys_clk_src_to_xo(void); +/* +* @fn chip_reset +* @brief +*/ +sint8 chip_reset(void); +/* +* @fn wait_for_bootrom +* @brief +*/ +sint8 wait_for_bootrom(uint8); +/* +* @fn wait_for_firmware_start +* @brief +*/ +sint8 wait_for_firmware_start(uint8); +/* +* @fn chip_deinit +* @brief +*/ +sint8 chip_deinit(void); +/* +* @fn chip_reset_and_cpu_halt +* @brief +*/ +sint8 chip_reset_and_cpu_halt(void); +/* +* @fn set_gpio_dir +* @brief +*/ +sint8 set_gpio_dir(uint8 gpio, uint8 dir); +/* +* @fn set_gpio_val +* @brief +*/ +sint8 set_gpio_val(uint8 gpio, uint8 val); +/* +* @fn get_gpio_val +* @brief +*/ +sint8 get_gpio_val(uint8 gpio, uint8* val); +/* +* @fn pullup_ctrl +* @brief +*/ +sint8 pullup_ctrl(uint32 pinmask, uint8 enable); +/* +* @fn nmi_get_otp_mac_address +* @brief +*/ +sint8 nmi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); +/* +* @fn nmi_get_mac_address +* @brief +*/ +sint8 nmi_get_mac_address(uint8 *pu8MacAddr); +/* +* @fn chip_apply_conf +* @brief +*/ +sint8 chip_apply_conf(uint32 u32conf); + +#ifdef __cplusplus + } +#endif + +#endif /*_NMASIC_H_*/ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmbus.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmbus.c new file mode 100644 index 0000000..d001d72 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmbus.c @@ -0,0 +1,301 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 bus APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +#ifndef CORTUS_APP + +#include "nmbus.h" +#include "nmi2c.h" +#include "nmspi.h" +#include "nmuart.h" + +#define MAX_TRX_CFG_SZ 8 + +/** +* @fn nm_bus_iface_init +* @brief Initialize bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_bus_iface_init(void *pvInitVal) +{ + sint8 ret = M2M_SUCCESS; + ret = nm_bus_init(pvInitVal); + return ret; +} + +/** +* @fn nm_bus_iface_deinit +* @brief Deinitialize bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Samer Sarhan +* @date 07 April 2014 +* @version 1.0 +*/ +sint8 nm_bus_iface_deinit(void) +{ + sint8 ret = M2M_SUCCESS; + ret = nm_bus_deinit(); + + return ret; +} + +/** +* @fn nm_bus_reset +* @brief reset bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @version 1.0 +*/ +sint8 nm_bus_reset(void) +{ + sint8 ret = M2M_SUCCESS; +#ifdef CONF_WINC_USE_UART +#elif defined (CONF_WINC_USE_SPI) + return nm_spi_reset(); +#elif defined (CONF_WINC_USE_I2C) +#else +#error "Plesae define bus usage" +#endif + + return ret; +} + +/** +* @fn nm_bus_iface_reconfigure +* @brief reconfigure bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Viswanathan Murugesan +* @date 22 Oct 2014 +* @version 1.0 +*/ +sint8 nm_bus_iface_reconfigure(void *ptr) +{ +#ifdef ARDUINO + (void)ptr; // Silence "unused" warning +#endif + sint8 ret = M2M_SUCCESS; +#ifdef CONF_WINC_USE_UART + ret = nm_uart_reconfigure(ptr); +#endif + return ret; +} +/* +* @fn nm_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +uint32 nm_read_reg(uint32 u32Addr) +{ +#ifdef CONF_WINC_USE_UART + return nm_uart_read_reg(u32Addr); +#elif defined (CONF_WINC_USE_SPI) + return nm_spi_read_reg(u32Addr); +#elif defined (CONF_WINC_USE_I2C) + return nm_i2c_read_reg(u32Addr); +#else +#error "Plesae define bus usage" +#endif + +} + +/* +* @fn nm_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) +{ +#ifdef CONF_WINC_USE_UART + return nm_uart_read_reg_with_ret(u32Addr,pu32RetVal); +#elif defined (CONF_WINC_USE_SPI) + return nm_spi_read_reg_with_ret(u32Addr,pu32RetVal); +#elif defined (CONF_WINC_USE_I2C) + return nm_i2c_read_reg_with_ret(u32Addr,pu32RetVal); +#else +#error "Plesae define bus usage" +#endif +} + +/* +* @fn nm_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_write_reg(uint32 u32Addr, uint32 u32Val) +{ +#ifdef CONF_WINC_USE_UART + return nm_uart_write_reg(u32Addr,u32Val); +#elif defined (CONF_WINC_USE_SPI) + return nm_spi_write_reg(u32Addr,u32Val); +#elif defined (CONF_WINC_USE_I2C) + return nm_i2c_write_reg(u32Addr,u32Val); +#else +#error "Plesae define bus usage" +#endif +} + +static sint8 p_nm_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) +{ +#ifdef CONF_WINC_USE_UART + return nm_uart_read_block(u32Addr,puBuf,u16Sz); +#elif defined (CONF_WINC_USE_SPI) + return nm_spi_read_block(u32Addr,puBuf,u16Sz); +#elif defined (CONF_WINC_USE_I2C) + return nm_i2c_read_block(u32Addr,puBuf,u16Sz); +#else +#error "Plesae define bus usage" +#endif + +} +/* +* @fn nm_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u32Sz +* Number of bytes to read. The buffer size must be >= u32Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_read_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz) +{ + uint16 u16MaxTrxSz = egstrNmBusCapabilities.u16MaxTrxSz - MAX_TRX_CFG_SZ; + uint32 off = 0; + sint8 s8Ret = M2M_SUCCESS; + + for(;;) + { + if(u32Sz <= u16MaxTrxSz) + { + s8Ret += p_nm_read_block(u32Addr, &puBuf[off], (uint16)u32Sz); + break; + } + else + { + s8Ret += p_nm_read_block(u32Addr, &puBuf[off], u16MaxTrxSz); + if(M2M_SUCCESS != s8Ret) break; + u32Sz -= u16MaxTrxSz; + off += u16MaxTrxSz; + u32Addr += u16MaxTrxSz; + } + } + + return s8Ret; +} + +static sint8 p_nm_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) +{ +#ifdef CONF_WINC_USE_UART + return nm_uart_write_block(u32Addr,puBuf,u16Sz); +#elif defined (CONF_WINC_USE_SPI) + return nm_spi_write_block(u32Addr,puBuf,u16Sz); +#elif defined (CONF_WINC_USE_I2C) + return nm_i2c_write_block(u32Addr,puBuf,u16Sz); +#else +#error "Plesae define bus usage" +#endif + +} +/** +* @fn nm_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u32Sz +* Number of bytes to write. The buffer size must be >= u32Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_write_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz) +{ + uint16 u16MaxTrxSz = egstrNmBusCapabilities.u16MaxTrxSz - MAX_TRX_CFG_SZ; + uint32 off = 0; + sint8 s8Ret = M2M_SUCCESS; + + for(;;) + { + if(u32Sz <= u16MaxTrxSz) + { + s8Ret += p_nm_write_block(u32Addr, &puBuf[off], (uint16)u32Sz); + break; + } + else + { + s8Ret += p_nm_write_block(u32Addr, &puBuf[off], u16MaxTrxSz); + if(M2M_SUCCESS != s8Ret) break; + u32Sz -= u16MaxTrxSz; + off += u16MaxTrxSz; + u32Addr += u16MaxTrxSz; + } + } + + return s8Ret; +} + +#endif + diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmbus.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmbus.h new file mode 100644 index 0000000..2ea7838 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmbus.h @@ -0,0 +1,147 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 bus APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NMBUS_H_ +#define _NMBUS_H_ + +#include "common/include/nm_common.h" +#include "bus_wrapper/include/nm_bus_wrapper.h" + + + +#ifdef __cplusplus +extern "C"{ +#endif +/** +* @fn nm_bus_iface_init +* @brief Initialize bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_bus_iface_init(void *); + + +/** +* @fn nm_bus_iface_deinit +* @brief Deinitialize bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_bus_iface_deinit(void); + +/** +* @fn nm_bus_reset +* @brief reset bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @version 1.0 +*/ +sint8 nm_bus_reset(void); + +/** +* @fn nm_bus_iface_reconfigure +* @brief reconfigure bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_bus_iface_reconfigure(void *ptr); + +/** +* @fn nm_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +*/ +uint32 nm_read_reg(uint32 u32Addr); + +/** +* @fn nm_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); + +/** +* @fn nm_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_write_reg(uint32 u32Addr, uint32 u32Val); + +/** +* @fn nm_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u32Sz +* Number of bytes to read. The buffer size must be >= u32Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_read_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz); + +/** +* @fn nm_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u32Sz +* Number of bytes to write. The buffer size must be >= u32Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_write_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz); + + + + +#ifdef __cplusplus +} +#endif + +#endif /* _NMBUS_H_ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmdrv.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmdrv.c new file mode 100644 index 0000000..b3f2a8a --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmdrv.c @@ -0,0 +1,402 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 M2M driver APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "common/include/nm_common.h" +#include "driver/source/nmbus.h" +#include "bsp/include/nm_bsp.h" +#include "driver/source/nmdrv.h" +#include "driver/source/nmasic.h" +#include "driver/include/m2m_types.h" +#include "spi_flash/include/spi_flash.h" + +#ifdef CONF_WINC_USE_SPI +#include "driver/source/nmspi.h" +#endif + +#ifdef ARDUINO + uint32 nmdrv_firm_ver = 0; +#endif + +/** +* @fn nm_get_firmware_info(tstrM2mRev* M2mRev) +* @brief Get Firmware version info +* @param [out] M2mRev +* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters +* @version 1.0 +*/ +sint8 nm_get_firmware_info(tstrM2mRev* M2mRev) +{ + uint16 curr_drv_ver, min_req_drv_ver,curr_firm_ver; + uint32 reg = 0; + sint8 ret = M2M_SUCCESS; + + ret = nm_read_reg_with_ret(NMI_REV_REG, ®); + //In case the Firmware running is ATE fw + if(M2M_ATE_FW_IS_UP_VALUE == reg) + { + //Read FW info again from the register specified for ATE + ret = nm_read_reg_with_ret(NMI_REV_REG_ATE, ®); + } + M2mRev->u8DriverMajor = M2M_GET_DRV_MAJOR(reg); + M2mRev->u8DriverMinor = M2M_GET_DRV_MINOR(reg); + M2mRev->u8DriverPatch = M2M_GET_DRV_PATCH(reg); + M2mRev->u8FirmwareMajor = M2M_GET_FW_MAJOR(reg); + M2mRev->u8FirmwareMinor = M2M_GET_FW_MINOR(reg); + M2mRev->u8FirmwarePatch = M2M_GET_FW_PATCH(reg); + M2mRev->u32Chipid = nmi_get_chipid(); + M2mRev->u16FirmwareSvnNum = 0; + + curr_firm_ver = M2M_MAKE_VERSION(M2mRev->u8FirmwareMajor, M2mRev->u8FirmwareMinor,M2mRev->u8FirmwarePatch); +#ifdef ARDUINO + nmdrv_firm_ver = curr_firm_ver; +#endif + curr_drv_ver = M2M_MAKE_VERSION(M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); + min_req_drv_ver = M2M_MAKE_VERSION(M2mRev->u8DriverMajor, M2mRev->u8DriverMinor,M2mRev->u8DriverPatch); + if(curr_drv_ver < min_req_drv_ver) { + /*The current driver version should be larger or equal + than the min driver that the current firmware support */ + ret = M2M_ERR_FW_VER_MISMATCH; + } + if(curr_drv_ver > curr_firm_ver) { + /*The current driver should be equal or less than the firmware version*/ + ret = M2M_ERR_FW_VER_MISMATCH; + } + return ret; +} +/** +* @fn nm_get_firmware_info(tstrM2mRev* M2mRev) +* @brief Get Firmware version info +* @param [out] M2mRev +* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters +* @version 1.0 +*/ +sint8 nm_get_firmware_full_info(tstrM2mRev* pstrRev) +{ + uint16 curr_drv_ver, min_req_drv_ver,curr_firm_ver; + uint32 reg = 0; + sint8 ret = M2M_SUCCESS; + tstrGpRegs strgp = {0}; + if (pstrRev != NULL) + { + m2m_memset((uint8*)pstrRev,0,sizeof(tstrM2mRev)); + ret = nm_read_reg_with_ret(rNMI_GP_REG_2, ®); + if(ret == M2M_SUCCESS) + { + if(reg != 0) + { + ret = nm_read_block(reg|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); + if(ret == M2M_SUCCESS) + { + reg = strgp.u32Firmware_Ota_rev; + reg &= 0x0000ffff; + if(reg != 0) + { + ret = nm_read_block(reg|0x30000,(uint8*)pstrRev,sizeof(tstrM2mRev)); + if(ret == M2M_SUCCESS) + { + curr_firm_ver = M2M_MAKE_VERSION(pstrRev->u8FirmwareMajor, pstrRev->u8FirmwareMinor,pstrRev->u8FirmwarePatch); +#ifdef ARDUINO + nmdrv_firm_ver = curr_firm_ver; +#endif + curr_drv_ver = M2M_MAKE_VERSION(M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); + min_req_drv_ver = M2M_MAKE_VERSION(pstrRev->u8DriverMajor, pstrRev->u8DriverMinor,pstrRev->u8DriverPatch); + if((curr_firm_ver == 0)||(min_req_drv_ver == 0)||(min_req_drv_ver == 0)){ + ret = M2M_ERR_FAIL; + goto EXIT; + } + if(curr_drv_ver < min_req_drv_ver) { + /*The current driver version should be larger or equal + than the min driver that the current firmware support */ + ret = M2M_ERR_FW_VER_MISMATCH; + goto EXIT; + } + if(curr_drv_ver > curr_firm_ver) { + /*The current driver should be equal or less than the firmware version*/ + ret = M2M_ERR_FW_VER_MISMATCH; + goto EXIT; + } + } + }else { + ret = M2M_ERR_FAIL; + } + } + }else{ + ret = M2M_ERR_FAIL; + } + } + } +EXIT: + return ret; +} +/** +* @fn nm_get_ota_firmware_info(tstrM2mRev* pstrRev) +* @brief Get Firmware version info +* @param [out] M2mRev +* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters + +* @version 1.0 +*/ +sint8 nm_get_ota_firmware_info(tstrM2mRev* pstrRev) +{ + uint16 curr_drv_ver, min_req_drv_ver,curr_firm_ver; + uint32 reg = 0; + sint8 ret; + tstrGpRegs strgp = {0}; + + if (pstrRev != NULL) + { + m2m_memset((uint8*)pstrRev,0,sizeof(tstrM2mRev)); + ret = nm_read_reg_with_ret(rNMI_GP_REG_2, ®); + if(ret == M2M_SUCCESS) + { + if(reg != 0) + { + ret = nm_read_block(reg|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); + if(ret == M2M_SUCCESS) + { + reg = strgp.u32Firmware_Ota_rev; + reg >>= 16; + if(reg != 0) + { + ret = nm_read_block(reg|0x30000,(uint8*)pstrRev,sizeof(tstrM2mRev)); + if(ret == M2M_SUCCESS) + { + curr_firm_ver = M2M_MAKE_VERSION(pstrRev->u8FirmwareMajor, pstrRev->u8FirmwareMinor,pstrRev->u8FirmwarePatch); + curr_drv_ver = M2M_MAKE_VERSION(M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); + min_req_drv_ver = M2M_MAKE_VERSION(pstrRev->u8DriverMajor, pstrRev->u8DriverMinor,pstrRev->u8DriverPatch); + if((curr_firm_ver == 0)||(min_req_drv_ver == 0)||(min_req_drv_ver == 0)){ + ret = M2M_ERR_FAIL; + goto EXIT; + } + if(curr_drv_ver < min_req_drv_ver) { + /*The current driver version should be larger or equal + than the min driver that the current firmware support */ + ret = M2M_ERR_FW_VER_MISMATCH; + } + if(curr_drv_ver > curr_firm_ver) { + /*The current driver should be equal or less than the firmware version*/ + ret = M2M_ERR_FW_VER_MISMATCH; + } + } + }else{ + ret = M2M_ERR_INVALID; + } + } + }else{ + ret = M2M_ERR_FAIL; + } + } + } else { + ret = M2M_ERR_INVALID_ARG; + } +EXIT: + return ret; +} + + + +/* +* @fn nm_drv_init_download_mode +* @brief Initialize NMC1000 driver +* @return M2M_SUCCESS in case of success and Negative error code in case of failure +* @param [in] arg +* Generic argument +* @author Viswanathan Murugesan +* @date 10 Oct 2014 +* @version 1.0 +*/ +sint8 nm_drv_init_download_mode() +{ + sint8 ret = M2M_SUCCESS; + + ret = nm_bus_iface_init(NULL); + if (M2M_SUCCESS != ret) { + M2M_ERR("[nmi start]: fail init bus\n"); + goto ERR1; + } + + /** + TODO:reset the chip and halt the cpu in case of no wait efuse is set (add the no wait effuse check) + */ + if(!ISNMC3000(GET_CHIPID())) + { + /*Execuate that function only for 1500A/B, no room in 3000, but it may be needed in 3400 no wait*/ + chip_reset_and_cpu_halt(); + } + +#ifdef CONF_WINC_USE_SPI + /* Must do this after global reset to set SPI data packet size. */ + nm_spi_init(); +#endif + + M2M_INFO("Chip ID %lx\n", nmi_get_chipid()); + + /*disable all interrupt in ROM (to disable uart) in 2b0 chip*/ + nm_write_reg(0x20300,0); + +ERR1: + return ret; +} + +/* +* @fn nm_drv_init +* @brief Initialize NMC1000 driver +* @return M2M_SUCCESS in case of success and Negative error code in case of failure +* @param [in] arg +* Generic argument +* @author M. Abdelmawla +* @date 15 July 2012 +* @version 1.0 +*/ +sint8 nm_drv_init(void * arg) +{ + sint8 ret = M2M_SUCCESS; + uint8 u8Mode; + + if(NULL != arg) { + u8Mode = *((uint8 *)arg); + if((u8Mode < M2M_WIFI_MODE_NORMAL)||(u8Mode >= M2M_WIFI_MODE_MAX)) { + u8Mode = M2M_WIFI_MODE_NORMAL; + } + } else { + u8Mode = M2M_WIFI_MODE_NORMAL; + } + + ret = nm_bus_iface_init(NULL); + if (M2M_SUCCESS != ret) { + M2M_ERR("[nmi start]: fail init bus\n"); + goto ERR1; + } + +#ifdef BUS_ONLY + return; +#endif + + +#ifdef NO_HW_CHIP_EN + ret = chip_wake(); + if (M2M_SUCCESS != ret) { + M2M_ERR("[nmi start]: fail chip_wakeup\n"); + goto ERR2; + } + /** + Go... + **/ + ret = chip_reset(); + if (M2M_SUCCESS != ret) { + goto ERR2; + } +#endif + M2M_INFO("Chip ID %lx\n", nmi_get_chipid()); +#ifdef CONF_WINC_USE_SPI + /* Must do this after global reset to set SPI data packet size. */ + nm_spi_init(); +#endif + ret = wait_for_bootrom(u8Mode); + if (M2M_SUCCESS != ret) { + goto ERR2; + } + + ret = wait_for_firmware_start(u8Mode); + if (M2M_SUCCESS != ret) { + goto ERR2; + } + + if((M2M_WIFI_MODE_ATE_HIGH == u8Mode)||(M2M_WIFI_MODE_ATE_LOW == u8Mode)) { + goto ERR1; + } else { + /*continue running*/ + } + + ret = enable_interrupts(); + if (M2M_SUCCESS != ret) { + M2M_ERR("failed to enable interrupts..\n"); + goto ERR2; + } + return ret; +ERR2: + nm_bus_iface_deinit(); +ERR1: + return ret; +} + +/* +* @fn nm_drv_deinit +* @brief Deinitialize NMC1000 driver +* @author M. Abdelmawla +* @date 17 July 2012 +* @version 1.0 +*/ +sint8 nm_drv_deinit(void * arg) +{ +#ifdef ARDUINO + (void)arg; // Silence "unused" warning +#endif + sint8 ret; + + ret = chip_deinit(); + if (M2M_SUCCESS != ret) { + M2M_ERR("[nmi stop]: chip_deinit fail\n"); + goto ERR1; + } + + /* Disable SPI flash to save power when the chip is off */ + ret = spi_flash_enable(0); + if (M2M_SUCCESS != ret) { + M2M_ERR("[nmi stop]: SPI flash disable fail\n"); + goto ERR1; + } + + ret = nm_bus_iface_deinit(); + if (M2M_SUCCESS != ret) { + M2M_ERR("[nmi stop]: fail init bus\n"); + goto ERR1; + } +#ifdef CONF_WINC_USE_SPI + /* Must do this after global reset to set SPI data packet size. */ + nm_spi_deinit(); +#endif + +ERR1: + return ret; +} + + diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmdrv.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmdrv.h new file mode 100644 index 0000000..6a416b2 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmdrv.h @@ -0,0 +1,138 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 M2M driver APIs declarations. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NMDRV_H_ +#define _NMDRV_H_ + +#include "common/include/nm_common.h" + +/** +* @struct tstrM2mRev +* @brief Structure holding firmware version parameters and build date/time +*/ +typedef struct { + uint32 u32Chipid; /* HW revision which will be basically the chip ID */ + uint8 u8FirmwareMajor; /* Version Major Number which represents the official release base */ + uint8 u8FirmwareMinor; /* Version Minor Number which represents the engineering release base */ + uint8 u8FirmwarePatch; /* Version pathc Number which represents the pathces release base */ + uint8 u8DriverMajor; /* Version Major Number which represents the official release base */ + uint8 u8DriverMinor; /* Version Minor Number which represents the engineering release base */ + uint8 u8DriverPatch; /* Version Patch Number which represents the pathces release base */ + uint8 BuildDate[sizeof(__DATE__)]; + uint8 BuildTime[sizeof(__TIME__)]; + uint8 _PAD8_; + uint16 u16FirmwareSvnNum; + uint16 _PAD16_[2]; +} tstrM2mRev; + +/** +* @struct tstrM2mBinaryHeader +* @brief Structure holding compatibility version info for firmware binaries +*/ +typedef struct { + tstrM2mRev binVerInfo; + uint32 flashOffset; + uint32 payloadSize; +} tstrM2mBinaryHeader; + +#ifdef __cplusplus + extern "C" { + #endif +/** +* @fn nm_get_firmware_info(tstrM2mRev* M2mRev) +* @brief Get Firmware version info +* @param [out] M2mRev +* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters +* @version 1.0 +*/ +sint8 nm_get_firmware_info(tstrM2mRev* M2mRev); +/** +* @fn nm_get_firmware_full_info(tstrM2mRev* pstrRev) +* @brief Get Firmware version info +* @param [out] M2mRev +* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters +* @version 1.0 +*/ +sint8 nm_get_firmware_full_info(tstrM2mRev* pstrRev); +/** +* @fn nm_get_ota_firmware_info(tstrM2mRev* pstrRev) +* @brief Get Firmware version info +* @param [out] M2mRev +* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters + +* @version 1.0 +*/ +sint8 nm_get_ota_firmware_info(tstrM2mRev* pstrRev); +/* +* @fn nm_drv_init +* @brief Initialize NMC1000 driver +* @return ZERO in case of success and Negative error code in case of failure +*/ +sint8 nm_drv_init_download_mode(void); + +/* +* @fn nm_drv_init +* @brief Initialize NMC1000 driver +* @return M2M_SUCCESS in case of success and Negative error code in case of failure +* @param [in] arg +* Generic argument TBD +* @return ZERO in case of success and Negative error code in case of failure + +*/ +sint8 nm_drv_init(void * arg); + +/** +* @fn nm_drv_deinit +* @brief Deinitialize NMC1000 driver +* @author M. Abdelmawla +* @param [in] arg +* Generic argument TBD +* @return ZERO in case of success and Negative error code in case of failure +*/ +sint8 nm_drv_deinit(void * arg); + +#ifdef __cplusplus + } + #endif + +#endif /*_NMDRV_H_*/ + + diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmi2c.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmi2c.c new file mode 100644 index 0000000..e11d2f7 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmi2c.c @@ -0,0 +1,269 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 I2C protocol bus APIs implementation. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "common/include/nm_common.h" + +#ifdef CONF_WINC_USE_I2C + +#include "nmi2c.h" +#include "bus_wrapper/include/nm_bus_wrapper.h" + + +/* +* @fn nm_i2c_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ + sint8 nm_i2c_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) +{ + uint8 b[6]; + uint8 rsz; + tstrNmI2cDefault strI2c; + sint8 s8Ret = M2M_SUCCESS; + + if(u32Addr < 0xff) { /* clockless i2c */ + b[0] = 0x09; + b[1] = (uint8)(u32Addr); + rsz = 1; + strI2c.u16Sz = 2; + } else { + b[0] = 0x80; + b[1] = (uint8)(u32Addr >> 24); + b[2] = (uint8)(u32Addr >> 16); + b[3] = (uint8)(u32Addr >> 8); + b[4] = (uint8)(u32Addr); + b[5] = 0x04; + rsz = 4; + strI2c.u16Sz = 6; + } + + strI2c.pu8Buf = b; + + if(M2M_SUCCESS == nm_bus_ioctl(NM_BUS_IOCTL_W, &strI2c)) + { + strI2c.u16Sz = rsz; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strI2c)) + { + //M2M_ERR("read error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + M2M_ERR("failed to send cfg bytes\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + + if (rsz == 1) { + *pu32RetVal = b[0]; + } else { + *pu32RetVal = b[0] | ((uint32)b[1] << 8) | ((uint32)b[2] << 16) | ((uint32)b[3] << 24); + } + return s8Ret; +} + +/* +* @fn nm_i2c_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +uint32 nm_i2c_read_reg(uint32 u32Addr) +{ + uint32 val; + nm_i2c_read_reg_with_ret(u32Addr, &val); + return val; +} + +/* +* @fn nm_i2c_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_i2c_write_reg(uint32 u32Addr, uint32 u32Val) +{ + tstrNmI2cDefault strI2c; + uint8 b[16]; + sint8 s8Ret = M2M_SUCCESS; + + if(u32Addr < 0xff) { /* clockless i2c */ + b[0] = 0x19; + b[1] = (uint8)(u32Addr); + b[2] = (uint8)(u32Val); + strI2c.u16Sz = 3; + } else { + b[0] = 0x90; + b[1] = (uint8)(u32Addr >> 24); + b[2] = (uint8)(u32Addr >> 16); + b[3] = (uint8)(u32Addr >> 8); + b[4] = (uint8)u32Addr; + b[5] = 0x04; + b[6] = (uint8)u32Val; + b[7] = (uint8)(u32Val >> 8); + b[8] = (uint8)(u32Val >> 16); + b[9] = (uint8)(u32Val >> 24); + strI2c.u16Sz = 10; + } + + strI2c.pu8Buf = b; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strI2c)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + + return s8Ret; +} + +/* +* @fn nm_i2c_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u16Sz +* Number of bytes to read. The buffer size must be >= u16Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_i2c_read_block(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz) +{ + tstrNmI2cDefault strI2c; + uint8 au8Buf[7]; + sint8 s8Ret = M2M_SUCCESS; + + au8Buf[0] = 0x02; + au8Buf[1] = (uint8)(u32Addr >> 24); + au8Buf[2] = (uint8)(u32Addr >> 16); + au8Buf[3] = (uint8)(u32Addr >> 8); + au8Buf[4] = (uint8)(u32Addr >> 0); + au8Buf[5] = (uint8)(u16Sz >> 8); + au8Buf[6] = (uint8)(u16Sz); + + strI2c.pu8Buf = au8Buf; + strI2c.u16Sz = sizeof(au8Buf); + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strI2c)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + else + { + strI2c.pu8Buf = pu8Buf; + strI2c.u16Sz = u16Sz; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strI2c)) + { + M2M_ERR("read error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + + return s8Ret; +} + +/* +* @fn nm_i2c_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u16Sz +* Number of bytes to write. The buffer size must be >= u16Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_i2c_write_block(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz) +{ + uint8 au8Buf[7]; + tstrNmI2cSpecial strI2c; + sint8 s8Ret = M2M_SUCCESS; + + au8Buf[0] = 0x12; + au8Buf[1] = (uint8)(u32Addr >> 24); + au8Buf[2] = (uint8)(u32Addr >> 16); + au8Buf[3] = (uint8)(u32Addr >> 8); + au8Buf[4] = (uint8)(u32Addr); + au8Buf[5] = (uint8)(u16Sz >> 8); + au8Buf[6] = (uint8)(u16Sz); + + strI2c.pu8Buf1 = au8Buf; + strI2c.pu8Buf2 = pu8Buf; + strI2c.u16Sz1 = sizeof(au8Buf); + strI2c.u16Sz2 = u16Sz; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W_SPECIAL, &strI2c)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + + return s8Ret; +} + +#endif +/* EOF */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmi2c.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmi2c.h new file mode 100644 index 0000000..fea85e6 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmi2c.h @@ -0,0 +1,104 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 I2C protocol bus APIs implementation. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NMI2C_H_ +#define _NMI2C_H_ + +#include "common/include/nm_common.h" + +/** +* @fn nm_i2c_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +*/ +uint32 nm_i2c_read_reg(uint32 u32Addr); + +/** +* @fn nm_i2c_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_i2c_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); + +/** +* @fn nm_i2c_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_i2c_write_reg(uint32 u32Addr, uint32 u32Val); + +/** +* @fn nm_i2c_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u16Sz +* Number of bytes to read. The buffer size must be >= u16Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_i2c_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); + +/** +* @fn nm_i2c_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u16Sz +* Number of bytes to write. The buffer size must be >= u16Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_i2c_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); + +#endif /* _NMI2C_H_ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmspi.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmspi.c new file mode 100644 index 0000000..9483ab7 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmspi.c @@ -0,0 +1,1401 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 SPI protocol bus APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +#include "common/include/nm_common.h" + +#ifdef CONF_WINC_USE_SPI + +#define USE_OLD_SPI_SW + +#include "bus_wrapper/include/nm_bus_wrapper.h" +#include "nmspi.h" + +#define NMI_PERIPH_REG_BASE 0x1000 +#define NMI_INTR_REG_BASE (NMI_PERIPH_REG_BASE+0xa00) +#define NMI_CHIPID (NMI_PERIPH_REG_BASE) +#define NMI_PIN_MUX_0 (NMI_PERIPH_REG_BASE + 0x408) +#define NMI_INTR_ENABLE (NMI_INTR_REG_BASE) + +#define NMI_SPI_REG_BASE 0xe800 +#define NMI_SPI_CTL (NMI_SPI_REG_BASE) +#define NMI_SPI_MASTER_DMA_ADDR (NMI_SPI_REG_BASE+0x4) +#define NMI_SPI_MASTER_DMA_COUNT (NMI_SPI_REG_BASE+0x8) +#define NMI_SPI_SLAVE_DMA_ADDR (NMI_SPI_REG_BASE+0xc) +#define NMI_SPI_SLAVE_DMA_COUNT (NMI_SPI_REG_BASE+0x10) +#define NMI_SPI_TX_MODE (NMI_SPI_REG_BASE+0x20) +#define NMI_SPI_PROTOCOL_CONFIG (NMI_SPI_REG_BASE+0x24) +#define NMI_SPI_INTR_CTL (NMI_SPI_REG_BASE+0x2c) +#define NMI_SPI_MISC_CTRL (NMI_SPI_REG_BASE+0x48) + +#define NMI_SPI_PROTOCOL_OFFSET (NMI_SPI_PROTOCOL_CONFIG-NMI_SPI_REG_BASE) + +#define SPI_BASE NMI_SPI_REG_BASE + +#define CMD_DMA_WRITE 0xc1 +#define CMD_DMA_READ 0xc2 +#define CMD_INTERNAL_WRITE 0xc3 +#define CMD_INTERNAL_READ 0xc4 +#define CMD_TERMINATE 0xc5 +#define CMD_REPEAT 0xc6 +#define CMD_DMA_EXT_WRITE 0xc7 +#define CMD_DMA_EXT_READ 0xc8 +#define CMD_SINGLE_WRITE 0xc9 +#define CMD_SINGLE_READ 0xca +#define CMD_RESET 0xcf + +#define N_OK 1 +#define N_FAIL 0 +#define N_RESET -1 +#define N_RETRY -2 + +#define SPI_RESP_RETRY_COUNT (10) +#define SPI_RETRY_COUNT (10) +#define DATA_PKT_SZ_256 256 +#define DATA_PKT_SZ_512 512 +#define DATA_PKT_SZ_1K 1024 +#define DATA_PKT_SZ_4K (4 * 1024) +#define DATA_PKT_SZ_8K (8 * 1024) +#define DATA_PKT_SZ DATA_PKT_SZ_8K + +static uint8 gu8Crc_off = 0; + +static sint8 nmi_spi_read(uint8* b, uint16 sz) +{ + tstrNmSpiRw spi; + spi.pu8InBuf = NULL; + spi.pu8OutBuf = b; + spi.u16Sz = sz; + return nm_bus_ioctl(NM_BUS_IOCTL_RW, &spi); +} + +static sint8 nmi_spi_write(uint8* b, uint16 sz) +{ + tstrNmSpiRw spi; + spi.pu8InBuf = b; + spi.pu8OutBuf = NULL; + spi.u16Sz = sz; + return nm_bus_ioctl(NM_BUS_IOCTL_RW, &spi); +} +#ifndef USE_OLD_SPI_SW +static sint8 nmi_spi_rw(uint8 *bin,uint8* bout,uint16 sz) +{ + tstrNmSpiRw spi; + spi.pu8InBuf = bin; + spi.pu8OutBuf = bout; + spi.u16Sz = sz; + return nm_bus_ioctl(NM_BUS_IOCTL_RW, &spi); +} +#endif +/******************************************** + + Crc7 + +********************************************/ +#if (defined ARDUINO_ARCH_AVR) +#include +static PROGMEM const uint8 crc7_syndrome_table[256] = { +#else +static const uint8 crc7_syndrome_table[256] = { +#endif + 0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f, + 0x48, 0x41, 0x5a, 0x53, 0x6c, 0x65, 0x7e, 0x77, + 0x19, 0x10, 0x0b, 0x02, 0x3d, 0x34, 0x2f, 0x26, + 0x51, 0x58, 0x43, 0x4a, 0x75, 0x7c, 0x67, 0x6e, + 0x32, 0x3b, 0x20, 0x29, 0x16, 0x1f, 0x04, 0x0d, + 0x7a, 0x73, 0x68, 0x61, 0x5e, 0x57, 0x4c, 0x45, + 0x2b, 0x22, 0x39, 0x30, 0x0f, 0x06, 0x1d, 0x14, + 0x63, 0x6a, 0x71, 0x78, 0x47, 0x4e, 0x55, 0x5c, + 0x64, 0x6d, 0x76, 0x7f, 0x40, 0x49, 0x52, 0x5b, + 0x2c, 0x25, 0x3e, 0x37, 0x08, 0x01, 0x1a, 0x13, + 0x7d, 0x74, 0x6f, 0x66, 0x59, 0x50, 0x4b, 0x42, + 0x35, 0x3c, 0x27, 0x2e, 0x11, 0x18, 0x03, 0x0a, + 0x56, 0x5f, 0x44, 0x4d, 0x72, 0x7b, 0x60, 0x69, + 0x1e, 0x17, 0x0c, 0x05, 0x3a, 0x33, 0x28, 0x21, + 0x4f, 0x46, 0x5d, 0x54, 0x6b, 0x62, 0x79, 0x70, + 0x07, 0x0e, 0x15, 0x1c, 0x23, 0x2a, 0x31, 0x38, + 0x41, 0x48, 0x53, 0x5a, 0x65, 0x6c, 0x77, 0x7e, + 0x09, 0x00, 0x1b, 0x12, 0x2d, 0x24, 0x3f, 0x36, + 0x58, 0x51, 0x4a, 0x43, 0x7c, 0x75, 0x6e, 0x67, + 0x10, 0x19, 0x02, 0x0b, 0x34, 0x3d, 0x26, 0x2f, + 0x73, 0x7a, 0x61, 0x68, 0x57, 0x5e, 0x45, 0x4c, + 0x3b, 0x32, 0x29, 0x20, 0x1f, 0x16, 0x0d, 0x04, + 0x6a, 0x63, 0x78, 0x71, 0x4e, 0x47, 0x5c, 0x55, + 0x22, 0x2b, 0x30, 0x39, 0x06, 0x0f, 0x14, 0x1d, + 0x25, 0x2c, 0x37, 0x3e, 0x01, 0x08, 0x13, 0x1a, + 0x6d, 0x64, 0x7f, 0x76, 0x49, 0x40, 0x5b, 0x52, + 0x3c, 0x35, 0x2e, 0x27, 0x18, 0x11, 0x0a, 0x03, + 0x74, 0x7d, 0x66, 0x6f, 0x50, 0x59, 0x42, 0x4b, + 0x17, 0x1e, 0x05, 0x0c, 0x33, 0x3a, 0x21, 0x28, + 0x5f, 0x56, 0x4d, 0x44, 0x7b, 0x72, 0x69, 0x60, + 0x0e, 0x07, 0x1c, 0x15, 0x2a, 0x23, 0x38, 0x31, + 0x46, 0x4f, 0x54, 0x5d, 0x62, 0x6b, 0x70, 0x79 +}; + + +static uint8 crc7_byte(uint8 crc, uint8 data) +{ +#if (defined ARDUINO_ARCH_AVR) + return pgm_read_byte_near(crc7_syndrome_table + ((crc << 1) ^ data)); +#else + return crc7_syndrome_table[(crc << 1) ^ data]; +#endif +} + +static uint8 crc7(uint8 crc, const uint8 *buffer, uint32 len) +{ + while (len--) + crc = crc7_byte(crc, *buffer++); + return crc; +} + +/******************************************** + + Spi protocol Function + +********************************************/ + +#define CMD_DMA_WRITE 0xc1 +#define CMD_DMA_READ 0xc2 +#define CMD_INTERNAL_WRITE 0xc3 +#define CMD_INTERNAL_READ 0xc4 +#define CMD_TERMINATE 0xc5 +#define CMD_REPEAT 0xc6 +#define CMD_DMA_EXT_WRITE 0xc7 +#define CMD_DMA_EXT_READ 0xc8 +#define CMD_SINGLE_WRITE 0xc9 +#define CMD_SINGLE_READ 0xca +#define CMD_RESET 0xcf + +#define DATA_PKT_SZ_256 256 +#define DATA_PKT_SZ_512 512 +#define DATA_PKT_SZ_1K 1024 +#define DATA_PKT_SZ_4K (4 * 1024) +#define DATA_PKT_SZ_8K (8 * 1024) +#define DATA_PKT_SZ DATA_PKT_SZ_8K + +static sint8 spi_cmd(uint8 cmd, uint32 adr, uint32 u32data, uint32 sz,uint8 clockless) +{ + uint8 bc[9]; + uint8 len = 5; + sint8 result = N_OK; + + bc[0] = cmd; + switch (cmd) { + case CMD_SINGLE_READ: /* single word (4 bytes) read */ + bc[1] = (uint8)(adr >> 16); + bc[2] = (uint8)(adr >> 8); + bc[3] = (uint8)adr; + len = 5; + break; + case CMD_INTERNAL_READ: /* internal register read */ + bc[1] = (uint8)(adr >> 8); + if(clockless) bc[1] |= (1 << 7); + bc[2] = (uint8)adr; + bc[3] = 0x00; + len = 5; + break; + case CMD_TERMINATE: /* termination */ + bc[1] = 0x00; + bc[2] = 0x00; + bc[3] = 0x00; + len = 5; + break; + case CMD_REPEAT: /* repeat */ + bc[1] = 0x00; + bc[2] = 0x00; + bc[3] = 0x00; + len = 5; + break; + case CMD_RESET: /* reset */ + bc[1] = 0xff; + bc[2] = 0xff; + bc[3] = 0xff; + len = 5; + break; + case CMD_DMA_WRITE: /* dma write */ + case CMD_DMA_READ: /* dma read */ + bc[1] = (uint8)(adr >> 16); + bc[2] = (uint8)(adr >> 8); + bc[3] = (uint8)adr; + bc[4] = (uint8)(sz >> 8); + bc[5] = (uint8)(sz); + len = 7; + break; + case CMD_DMA_EXT_WRITE: /* dma extended write */ + case CMD_DMA_EXT_READ: /* dma extended read */ + bc[1] = (uint8)(adr >> 16); + bc[2] = (uint8)(adr >> 8); + bc[3] = (uint8)adr; + bc[4] = (uint8)(sz >> 16); + bc[5] = (uint8)(sz >> 8); + bc[6] = (uint8)(sz); + len = 8; + break; + case CMD_INTERNAL_WRITE: /* internal register write */ + bc[1] = (uint8)(adr >> 8); + if(clockless) bc[1] |= (1 << 7); + bc[2] = (uint8)(adr); + bc[3] = (uint8)(u32data >> 24); + bc[4] = (uint8)(u32data >> 16); + bc[5] = (uint8)(u32data >> 8); + bc[6] = (uint8)(u32data); + len = 8; + break; + case CMD_SINGLE_WRITE: /* single word write */ + bc[1] = (uint8)(adr >> 16); + bc[2] = (uint8)(adr >> 8); + bc[3] = (uint8)(adr); + bc[4] = (uint8)(u32data >> 24); + bc[5] = (uint8)(u32data >> 16); + bc[6] = (uint8)(u32data >> 8); + bc[7] = (uint8)(u32data); + len = 9; + break; + default: + result = N_FAIL; + break; + } + + if (result) { + if (!gu8Crc_off) + bc[len-1] = (crc7(0x7f, (const uint8 *)&bc[0], len-1)) << 1; + else + len-=1; + + if (M2M_SUCCESS != nmi_spi_write(bc, len)) { + M2M_ERR("[nmi spi]: Failed cmd write, bus error...\n"); + result = N_FAIL; + } + } + + return result; +} + +static sint8 spi_data_rsp(uint8 cmd) +{ +#ifdef ARDUINO + (void)cmd; // Silence "unused" warning +#endif + uint8 len; + uint8 rsp[3]; + sint8 result = N_OK; + + if (!gu8Crc_off) + len = 2; + else + len = 3; + + if (M2M_SUCCESS != nmi_spi_read(&rsp[0], len)) { + M2M_ERR("[nmi spi]: Failed bus error...\n"); + result = N_FAIL; + goto _fail_; + } + + if((rsp[len-1] != 0)||(rsp[len-2] != 0xC3)) + { + M2M_ERR("[nmi spi]: Failed data response read, %x %x %x\n",rsp[0],rsp[1],rsp[2]); + result = N_FAIL; + goto _fail_; + } +_fail_: + + return result; +} + +static sint8 spi_cmd_rsp(uint8 cmd) +{ + uint8 rsp; + sint8 result = N_OK; + sint8 s8RetryCnt; + + /** + Command/Control response + **/ + if ((cmd == CMD_RESET) || + (cmd == CMD_TERMINATE) || + (cmd == CMD_REPEAT)) { + if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { + result = N_FAIL; + goto _fail_; + } + } + + /* wait for response */ + s8RetryCnt = SPI_RESP_RETRY_COUNT; + do + { + if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { + M2M_ERR("[nmi spi]: Failed cmd response read, bus error...\n"); + result = N_FAIL; + goto _fail_; + } + } while((rsp != cmd) && (s8RetryCnt-- >0)); + + /** + State response + **/ + /* wait for response */ + s8RetryCnt = SPI_RESP_RETRY_COUNT; + do + { + if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { + M2M_ERR("[nmi spi]: Failed cmd response read, bus error...\n"); + result = N_FAIL; + goto _fail_; + } + } while((rsp != 0x00) && (s8RetryCnt-- >0)); + +_fail_: + + return result; +} +#ifndef USE_OLD_SPI_SW +static int spi_cmd_complete(uint8_t cmd, uint32_t adr, uint8_t *b, uint32_t sz, uint8_t clockless) +{ + uint8_t wb[32], rb[32]; + uint8_t wix, rix; + uint32_t len2; + uint8_t rsp; + int len = 0; + int result = N_OK; + + wb[0] = cmd; + switch (cmd) { + case CMD_SINGLE_READ: /* single word (4 bytes) read */ + wb[1] = (uint8_t)(adr >> 16); + wb[2] = (uint8_t)(adr >> 8); + wb[3] = (uint8_t)adr; + len = 5; + break; + case CMD_INTERNAL_READ: /* internal register read */ + wb[1] = (uint8_t)(adr >> 8); + if(clockless == 1) wb[1] |= (1 << 7); + wb[2] = (uint8_t)adr; + wb[3] = 0x00; + len = 5; + break; + case CMD_TERMINATE: /* termination */ + wb[1] = 0x00; + wb[2] = 0x00; + wb[3] = 0x00; + len = 5; + break; + case CMD_REPEAT: /* repeat */ + wb[1] = 0x00; + wb[2] = 0x00; + wb[3] = 0x00; + len = 5; + break; + case CMD_RESET: /* reset */ + wb[1] = 0xff; + wb[2] = 0xff; + wb[3] = 0xff; + len = 5; + break; + case CMD_DMA_WRITE: /* dma write */ + case CMD_DMA_READ: /* dma read */ + wb[1] = (uint8_t)(adr >> 16); + wb[2] = (uint8_t)(adr >> 8); + wb[3] = (uint8_t)adr; + wb[4] = (uint8_t)(sz >> 8); + wb[5] = (uint8_t)(sz); + len = 7; + break; + case CMD_DMA_EXT_WRITE: /* dma extended write */ + case CMD_DMA_EXT_READ: /* dma extended read */ + wb[1] = (uint8_t)(adr >> 16); + wb[2] = (uint8_t)(adr >> 8); + wb[3] = (uint8_t)adr; + wb[4] = (uint8_t)(sz >> 16); + wb[5] = (uint8_t)(sz >> 8); + wb[6] = (uint8_t)(sz); + len = 8; + break; + case CMD_INTERNAL_WRITE: /* internal register write */ + wb[1] = (uint8_t)(adr >> 8); + if(clockless == 1) wb[1] |= (1 << 7); + wb[2] = (uint8_t)(adr); + wb[3] = b[3]; + wb[4] = b[2]; + wb[5] = b[1]; + wb[6] = b[0]; + len = 8; + break; + case CMD_SINGLE_WRITE: /* single word write */ + wb[1] = (uint8_t)(adr >> 16); + wb[2] = (uint8_t)(adr >> 8); + wb[3] = (uint8_t)(adr); + wb[4] = b[3]; + wb[5] = b[2]; + wb[6] = b[1]; + wb[7] = b[0]; + len = 9; + break; + default: + result = N_FAIL; + break; + } + + if (result != N_OK) { + return result; + } + + if (!gu8Crc_off) { + wb[len-1] = (crc7(0x7f, (const uint8_t *)&wb[0], len-1)) << 1; + } else { + len -=1; + } + +#define NUM_SKIP_BYTES (1) +#define NUM_RSP_BYTES (2) +#define NUM_DATA_HDR_BYTES (1) +#define NUM_DATA_BYTES (4) +#define NUM_CRC_BYTES (2) +#define NUM_DUMMY_BYTES (3) + + if ((cmd == CMD_RESET) || + (cmd == CMD_TERMINATE) || + (cmd == CMD_REPEAT)) { + len2 = len + (NUM_SKIP_BYTES + NUM_RSP_BYTES + NUM_DUMMY_BYTES); + } else if ((cmd == CMD_INTERNAL_READ) || (cmd == CMD_SINGLE_READ)) { + if (!gu8Crc_off) { + len2 = len + (NUM_RSP_BYTES + NUM_DATA_HDR_BYTES + NUM_DATA_BYTES + + NUM_CRC_BYTES + NUM_DUMMY_BYTES); + } else { + len2 = len + (NUM_RSP_BYTES + NUM_DATA_HDR_BYTES + NUM_DATA_BYTES + + NUM_DUMMY_BYTES); + } + } else { + len2 = len + (NUM_RSP_BYTES + NUM_DUMMY_BYTES); + } +#undef NUM_DUMMY_BYTES + + if(len2 > (sizeof(wb)/sizeof(wb[0]))) { + M2M_ERR("[nmi spi]: spi buffer size too small (%d) (%d)\n", + len2, (sizeof(wb)/sizeof(wb[0]))); + result = N_FAIL; + return result; + } + /* zero spi write buffers. */ + for(wix = len; wix< len2; wix++) { + wb[wix] = 0; + } + rix = len; + + if (nmi_spi_rw(wb, rb, len2) != M2M_SUCCESS) { + M2M_ERR("[nmi spi]: Failed cmd write, bus error...\n"); + result = N_FAIL; + return result; + } + +#if 0 + { + int jj; + printk("--- cnd = %x, len=%d, len2=%d\n", cmd, len, len2); + for(jj=0; jj= len2) break; + if(((jj+1)%16) != 0) { + if((jj%16) == 0) { + printk("wb[%02x]: %02x ", jj, wb[jj]); + } else { + printk("%02x ", wb[jj]); + } + } else { + printk("%02x\n", wb[jj]); + } + } + printk("\n"); + + for(jj=0; jj= len2) break; + if(((jj+1)%16) != 0) { + if((jj%16) == 0) { + printk("rb[%02x]: %02x ", jj, rb[jj]); + } else { + printk("%02x ", rb[jj]); + } + } else { + printk("%02x\n", rb[jj]); + } + } + printk("\n"); + } +#endif + + /** + Command/Control response + **/ + if ((cmd == CMD_RESET) || + (cmd == CMD_TERMINATE) || + (cmd == CMD_REPEAT)) { + rix++; /* skip 1 byte */ + } + + rsp = rb[rix++]; + + + if (rsp != cmd) { + M2M_ERR("[nmi spi]: Failed cmd response, cmd (%02x), resp (%02x)\n", cmd, rsp); + result = N_FAIL; + return result; + } + + /** + State response + **/ + rsp = rb[rix++]; + if (rsp != 0x00) { + M2M_ERR("[nmi spi]: Failed cmd state response state (%02x)\n", rsp); + result = N_FAIL; + return result; + } + + if ((cmd == CMD_INTERNAL_READ) || (cmd == CMD_SINGLE_READ) + || (cmd == CMD_DMA_READ) || (cmd == CMD_DMA_EXT_READ)) { + int retry; + //uint16_t crc1, crc2; + uint8_t crc[2]; + /** + Data Respnose header + **/ + retry = SPI_RESP_RETRY_COUNT; + do { + /* ensure there is room in buffer later to read data and crc */ + if(rix < len2) { + rsp = rb[rix++]; + } else { + retry = 0; + break; + } + if (((rsp >> 4) & 0xf) == 0xf) + break; + } while (retry--); + + if (retry <= 0) { + M2M_ERR("[nmi spi]: Error, data read response (%02x)\n", rsp); + result = N_RESET; + return result; + } + + if ((cmd == CMD_INTERNAL_READ) || (cmd == CMD_SINGLE_READ)) { + /** + Read bytes + **/ + if((rix+3) < len2) { + b[0] = rb[rix++]; + b[1] = rb[rix++]; + b[2] = rb[rix++]; + b[3] = rb[rix++]; + } else { + M2M_ERR("[nmi spi]: buffer overrun when reading data.\n"); + result = N_FAIL; + return result; + } + + if (!gu8Crc_off) { + /** + Read Crc + **/ + if((rix+1) < len2) { + crc[0] = rb[rix++]; + crc[1] = rb[rix++]; + } else { + M2M_ERR("[nmi spi]: buffer overrun when reading crc.\n"); + result = N_FAIL; + return result; + } + } + } else if((cmd == CMD_DMA_READ) || (cmd == CMD_DMA_EXT_READ)) { + int ix; + + /* some data may be read in response to dummy bytes. */ + for(ix=0; (rix < len2) && (ix < sz);) { + b[ix++] = rb[rix++]; + } +#if 0 + if(ix) M2M_INFO("ttt %d %d\n", sz, ix); +#endif + sz -= ix; + + if(sz > 0) { + int nbytes; + + if (sz <= (DATA_PKT_SZ-ix)) { + nbytes = sz; + } else { + nbytes = DATA_PKT_SZ-ix; + } + + /** + Read bytes + **/ + if (nmi_spi_read(&b[ix], nbytes) != M2M_SUCCESS) { + M2M_ERR("[nmi spi]: Failed data block read, bus error...\n"); + result = N_FAIL; + goto _error_; + } + + /** + Read Crc + **/ + if (!gu8Crc_off) { + if (nmi_spi_read(crc, 2) != M2M_SUCCESS) { + M2M_ERR("[nmi spi]: Failed data block crc read, bus error...\n"); + result = N_FAIL; + goto _error_; + } + } + + + ix += nbytes; + sz -= nbytes; + } + + /* if any data in left unread, then read the rest using normal DMA code.*/ + while(sz > 0) { + int nbytes; + + if (sz <= DATA_PKT_SZ) { + nbytes = sz; + } else { + nbytes = DATA_PKT_SZ; + } + + /** + read data response only on the next DMA cycles not + the first DMA since data response header is already + handled above for the first DMA. + **/ + /** + Data Respnose header + **/ + retry = SPI_RESP_RETRY_COUNT; + do { + if (nmi_spi_read(&rsp, 1) != M2M_SUCCESS) { + M2M_ERR("[nmi spi]: Failed data response read, bus error...\n"); + result = N_FAIL; + break; + } + if (((rsp >> 4) & 0xf) == 0xf) + break; + } while (retry--); + + if (result == N_FAIL) + break; + + + /** + Read bytes + **/ + if (nmi_spi_read(&b[ix], nbytes) != M2M_SUCCESS) { + M2M_ERR("[nmi spi]: Failed data block read, bus error...\n"); + result = N_FAIL; + break; + } + + /** + Read Crc + **/ + if (!gu8Crc_off) { + if (nmi_spi_read(crc, 2) != M2M_SUCCESS) { + M2M_ERR("[nmi spi]: Failed data block crc read, bus error...\n"); + result = N_FAIL; + break; + } + } + + ix += nbytes; + sz -= nbytes; + } + } + } +_error_: + return result; +} +#endif +static sint8 spi_data_read(uint8 *b, uint16 sz,uint8 clockless) +{ + sint16 retry, ix, nbytes; + sint8 result = N_OK; + uint8 crc[2]; + uint8 rsp; + + /** + Data + **/ + ix = 0; + do { + if (sz <= DATA_PKT_SZ) + nbytes = sz; + else + nbytes = DATA_PKT_SZ; + + /** + Data Respnose header + **/ + retry = SPI_RESP_RETRY_COUNT; + do { + if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { + M2M_ERR("[nmi spi]: Failed data response read, bus error...\n"); + result = N_FAIL; + break; + } + if (((rsp >> 4) & 0xf) == 0xf) + break; + } while (retry--); + + if (result == N_FAIL) + break; + + if (retry <= 0) { + M2M_ERR("[nmi spi]: Failed data response read...(%02x)\n", rsp); + result = N_FAIL; + break; + } + + /** + Read bytes + **/ + if (M2M_SUCCESS != nmi_spi_read(&b[ix], nbytes)) { + M2M_ERR("[nmi spi]: Failed data block read, bus error...\n"); + result = N_FAIL; + break; + } + if(!clockless) + { + /** + Read Crc + **/ + if (!gu8Crc_off) { + if (M2M_SUCCESS != nmi_spi_read(crc, 2)) { + M2M_ERR("[nmi spi]: Failed data block crc read, bus error...\n"); + result = N_FAIL; + break; + } + } + } + ix += nbytes; + sz -= nbytes; + + } while (sz); + + return result; +} + +static sint8 spi_data_write(uint8 *b, uint16 sz) +{ + sint16 ix; + uint16 nbytes; + sint8 result = 1; + uint8 cmd, order, crc[2] = {0}; + //uint8 rsp; + + /** + Data + **/ + ix = 0; + do { + if (sz <= DATA_PKT_SZ) + nbytes = sz; + else + nbytes = DATA_PKT_SZ; + + /** + Write command + **/ + cmd = 0xf0; + if (ix == 0) { + if (sz <= DATA_PKT_SZ) + order = 0x3; + else + order = 0x1; + } else { + if (sz <= DATA_PKT_SZ) + order = 0x3; + else + order = 0x2; + } + cmd |= order; + if (M2M_SUCCESS != nmi_spi_write(&cmd, 1)) { + M2M_ERR("[nmi spi]: Failed data block cmd write, bus error...\n"); + result = N_FAIL; + break; + } + + /** + Write data + **/ + if (M2M_SUCCESS != nmi_spi_write(&b[ix], nbytes)) { + M2M_ERR("[nmi spi]: Failed data block write, bus error...\n"); + result = N_FAIL; + break; + } + + /** + Write Crc + **/ + if (!gu8Crc_off) { + if (M2M_SUCCESS != nmi_spi_write(crc, 2)) { + M2M_ERR("[nmi spi]: Failed data block crc write, bus error...\n"); + result = N_FAIL; + break; + } + } + + ix += nbytes; + sz -= nbytes; + } while (sz); + + + return result; +} + +/******************************************** + + Spi Internal Read/Write Function + +********************************************/ + +/******************************************** + + Spi interfaces + +********************************************/ + +static sint8 spi_write_reg(uint32 addr, uint32 u32data) +{ + uint8 retry = SPI_RETRY_COUNT; + sint8 result = N_OK; + uint8 cmd = CMD_SINGLE_WRITE; + uint8 clockless = 0; + +_RETRY_: + if (addr <= 0x30) + { + /** + NMC1000 clockless registers. + **/ + cmd = CMD_INTERNAL_WRITE; + clockless = 1; + } + else + { + cmd = CMD_SINGLE_WRITE; + clockless = 0; + } + +#if defined USE_OLD_SPI_SW + result = spi_cmd(cmd, addr, u32data, 4, clockless); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd, write reg (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + + result = spi_cmd_rsp(cmd); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd response, write reg (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + +#else + + result = spi_cmd_complete(cmd, addr, (uint8*)&u32data, 4, clockless); + if (result != N_OK) { + M2M_ERR( "[nmi spi]: Failed cmd, write reg (%08x)...\n", addr); + goto _FAIL_; + } + +#endif +_FAIL_: + if(result != N_OK) + { + nm_bsp_sleep(1); + spi_cmd(CMD_RESET, 0, 0, 0, 0); + spi_cmd_rsp(CMD_RESET); + M2M_ERR("Reset and retry %d %lx %lx\n",retry,addr,u32data); + nm_bsp_sleep(1); + retry--; + if(retry) goto _RETRY_; + } + + return result; +} + +static sint8 nm_spi_write(uint32 addr, uint8 *buf, uint16 size) +{ + sint8 result; + uint8 retry = SPI_RETRY_COUNT; + uint8 cmd = CMD_DMA_EXT_WRITE; + + +_RETRY_: + /** + Command + **/ +#if defined USE_OLD_SPI_SW + //Workaround hardware problem with single byte transfers over SPI bus + if (size == 1) + size = 2; + + result = spi_cmd(cmd, addr, 0, size,0); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd, write block (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + + result = spi_cmd_rsp(cmd); + if (result != N_OK) { + M2M_ERR("[nmi spi ]: Failed cmd response, write block (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } +#else + result = spi_cmd_complete(cmd, addr, NULL, size, 0); + if (result != N_OK) { + M2M_ERR( "[nmi spi]: Failed cmd, write block (%08x)...\n", addr); + goto _FAIL_; + } +#endif + + /** + Data + **/ + result = spi_data_write(buf, size); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed block data write...\n"); + goto _FAIL_; + } + /** + Data RESP + **/ + result = spi_data_rsp(cmd); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed block data write...\n"); + goto _FAIL_; + } + +_FAIL_: + if(result != N_OK) + { + nm_bsp_sleep(1); + spi_cmd(CMD_RESET, 0, 0, 0, 0); + spi_cmd_rsp(CMD_RESET); + M2M_ERR("Reset and retry %d %lx %d\n",retry,addr,size); + nm_bsp_sleep(1); + retry--; + if(retry) goto _RETRY_; + } + + + return result; +} + +static sint8 spi_read_reg(uint32 addr, uint32 *u32data) +{ + uint8 retry = SPI_RETRY_COUNT; + sint8 result = N_OK; + uint8 cmd = CMD_SINGLE_READ; + uint8 tmp[4]; + uint8 clockless = 0; + +_RETRY_: + + if (addr <= 0xff) + { + /** + NMC1000 clockless registers. + **/ + cmd = CMD_INTERNAL_READ; + clockless = 1; + } + else + { + cmd = CMD_SINGLE_READ; + clockless = 0; + } + +#if defined USE_OLD_SPI_SW + result = spi_cmd(cmd, addr, 0, 4, clockless); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd, read reg (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + + result = spi_cmd_rsp(cmd); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd response, read reg (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + + /* to avoid endianess issues */ + result = spi_data_read(&tmp[0], 4, clockless); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed data read...\n"); + goto _FAIL_; + } +#else + result = spi_cmd_complete(cmd, addr, (uint8*)&tmp[0], 4, clockless); + if (result != N_OK) { + M2M_ERR( "[nmi spi]: Failed cmd, read reg (%08x)...\n", addr); + goto _FAIL_; + } + +#endif + + *u32data = tmp[0] | + ((uint32)tmp[1] << 8) | + ((uint32)tmp[2] << 16) | + ((uint32)tmp[3] << 24); + +_FAIL_: + if(result != N_OK) + { + + nm_bsp_sleep(1); + spi_cmd(CMD_RESET, 0, 0, 0, 0); + spi_cmd_rsp(CMD_RESET); + M2M_ERR("Reset and retry %d %lx\n",retry,addr); + nm_bsp_sleep(1); + retry--; + if(retry) goto _RETRY_; + } + + return result; +} + +static sint8 nm_spi_read(uint32 addr, uint8 *buf, uint16 size) +{ + uint8 cmd = CMD_DMA_EXT_READ; + sint8 result; + uint8 retry = SPI_RETRY_COUNT; +#if defined USE_OLD_SPI_SW + uint8 tmp[2]; + uint8 single_byte_workaround = 0; +#endif + +_RETRY_: + + /** + Command + **/ +#if defined USE_OLD_SPI_SW + if (size == 1) + { + //Workaround hardware problem with single byte transfers over SPI bus + size = 2; + single_byte_workaround = 1; + } + result = spi_cmd(cmd, addr, 0, size,0); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd, read block (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + + result = spi_cmd_rsp(cmd); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd response, read block (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + + /** + Data + **/ + if (single_byte_workaround) + { + result = spi_data_read(tmp, size,0); + buf[0] = tmp[0]; + } + else + result = spi_data_read(buf, size,0); + + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed block data read...\n"); + goto _FAIL_; + } +#else + result = spi_cmd_complete(cmd, addr, buf, size, 0); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd, read block (%08x)...\n", addr); + goto _FAIL_; + } +#endif + +_FAIL_: + if(result != N_OK) + { + nm_bsp_sleep(1); + spi_cmd(CMD_RESET, 0, 0, 0, 0); + spi_cmd_rsp(CMD_RESET); + M2M_ERR("Reset and retry %d %lx %d\n",retry,addr,size); + nm_bsp_sleep(1); + retry--; + if(retry) goto _RETRY_; + } + + return result; +} + +/******************************************** + + Bus interfaces + +********************************************/ + +static void spi_init_pkt_sz(void) +{ + uint32 val32; + + /* Make sure SPI max. packet size fits the defined DATA_PKT_SZ. */ + val32 = nm_spi_read_reg(SPI_BASE+0x24); + val32 &= ~(0x7 << 4); + switch(DATA_PKT_SZ) + { + case 256: val32 |= (0 << 4); break; + case 512: val32 |= (1 << 4); break; + case 1024: val32 |= (2 << 4); break; + case 2048: val32 |= (3 << 4); break; + case 4096: val32 |= (4 << 4); break; + case 8192: val32 |= (5 << 4); break; + + } + nm_spi_write_reg(SPI_BASE+0x24, val32); +} + +sint8 nm_spi_reset(void) +{ + spi_cmd(CMD_RESET, 0, 0, 0, 0); + spi_cmd_rsp(CMD_RESET); + return M2M_SUCCESS; +} + +/* +* @fn nm_spi_init +* @brief Initialize the SPI +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_spi_init(void) +{ + uint32 chipid; + uint32 reg = 0; + + + /** + configure protocol + **/ + gu8Crc_off = 0; + + // TODO: We can remove the CRC trials if there is a definite way to reset + // the SPI to it's initial value. + if (!spi_read_reg(NMI_SPI_PROTOCOL_CONFIG, ®)) { + /* Read failed. Try with CRC off. This might happen when module + is removed but chip isn't reset*/ + gu8Crc_off = 1; + M2M_ERR("[nmi spi]: Failed internal read protocol with CRC on, retyring with CRC off...\n"); + if (!spi_read_reg(NMI_SPI_PROTOCOL_CONFIG, ®)){ + // Reaad failed with both CRC on and off, something went bad + M2M_ERR( "[nmi spi]: Failed internal read protocol...\n"); + return 0; + } + } + if(gu8Crc_off == 0) + { + reg &= ~0xc; /* disable crc checking */ + reg &= ~0x70; + reg |= (0x5 << 4); + if (!spi_write_reg(NMI_SPI_PROTOCOL_CONFIG, reg)) { + M2M_ERR( "[nmi spi]: Failed internal write protocol reg...\n"); + return 0; + } + gu8Crc_off = 1; + } + + /** + make sure can read back chip id correctly + **/ + if (!spi_read_reg(0x1000, &chipid)) { + M2M_ERR("[nmi spi]: Fail cmd read chip id...\n"); + return M2M_ERR_BUS_FAIL; + } + + M2M_DBG("[nmi spi]: chipid (%08x)\n", (unsigned int)chipid); + spi_init_pkt_sz(); + + + return M2M_SUCCESS; +} + +/* +* @fn nm_spi_init +* @brief DeInitialize the SPI +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Samer Sarhan +* @date 27 Feb 2015 +* @version 1.0 +*/ +sint8 nm_spi_deinit(void) +{ + gu8Crc_off = 0; + return M2M_SUCCESS; +} + +/* +* @fn nm_spi_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +uint32 nm_spi_read_reg(uint32 u32Addr) +{ + uint32 u32Val; + + spi_read_reg(u32Addr, &u32Val); + + return u32Val; +} + +/* +* @fn nm_spi_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_spi_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) +{ + sint8 s8Ret; + + s8Ret = spi_read_reg(u32Addr,pu32RetVal); + + if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; + else s8Ret = M2M_ERR_BUS_FAIL; + + return s8Ret; +} + +/* +* @fn nm_spi_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_spi_write_reg(uint32 u32Addr, uint32 u32Val) +{ + sint8 s8Ret; + + s8Ret = spi_write_reg(u32Addr, u32Val); + + if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; + else s8Ret = M2M_ERR_BUS_FAIL; + + return s8Ret; +} + +/* +* @fn nm_spi_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u16Sz +* Number of bytes to read. The buffer size must be >= u16Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_spi_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) +{ + sint8 s8Ret; + + s8Ret = nm_spi_read(u32Addr, puBuf, u16Sz); + + if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; + else s8Ret = M2M_ERR_BUS_FAIL; + + return s8Ret; +} + +/* +* @fn nm_spi_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u16Sz +* Number of bytes to write. The buffer size must be >= u16Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_spi_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) +{ + sint8 s8Ret; + + s8Ret = nm_spi_write(u32Addr, puBuf, u16Sz); + + if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; + else s8Ret = M2M_ERR_BUS_FAIL; + + return s8Ret; +} + +#endif diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmspi.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmspi.h new file mode 100644 index 0000000..a1bd4a9 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmspi.h @@ -0,0 +1,132 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 SPI protocol bus APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NMSPI_H_ +#define _NMSPI_H_ + +#include "common/include/nm_common.h" + +#ifdef __cplusplus + extern "C" { +#endif + +/** +* @fn nm_spi_init +* @brief Initialize the SPI +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_init(void); +/** +* @fn nm_spi_reset +* @brief reset the SPI +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_reset(void); + +/** +* @fn nm_spi_deinit +* @brief DeInitialize the SPI +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_deinit(void); + +/** +* @fn nm_spi_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +*/ +uint32 nm_spi_read_reg(uint32 u32Addr); + +/** +* @fn nm_spi_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); + +/** +* @fn nm_spi_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_write_reg(uint32 u32Addr, uint32 u32Val); + +/** +* @fn nm_spi_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u16Sz +* Number of bytes to read. The buffer size must be >= u16Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); + +/** +* @fn nm_spi_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u16Sz +* Number of bytes to write. The buffer size must be >= u16Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); + +#ifdef __cplusplus + } +#endif + +#endif /* _NMSPI_H_ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmuart.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmuart.c new file mode 100644 index 0000000..63541cf --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmuart.c @@ -0,0 +1,536 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 UART protocol bus APIs implementation. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "common/include/nm_common.h" + +#ifdef CONF_WINC_USE_UART + +#include "driver/source/nmuart.h" +#include "bus_wrapper/include/nm_bus_wrapper.h" + +#define HDR_SZ 12 + +static uint8 get_cs(uint8* b, uint8 sz){ + int i; + uint8 cs = 0; + for(i = 0; i < sz; i++) + cs ^= b[i]; + return cs; +} + +/* +* @fn nm_uart_sync_cmd +* @brief Check COM Port +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Dina El Sissy +* @date 13 AUG 2012 +* @version 1.0 +*/ +sint8 nm_uart_sync_cmd(void) +{ + tstrNmUartDefault strUart; + sint8 s8Ret = -1; + uint8 b [HDR_SZ+1]; + uint8 rsz; + uint8 onchip = 0; + + /*read reg*/ + b[0] = 0x12; + + rsz = 1; + strUart.pu8Buf = b; + strUart.u16Sz = 1; + + if(M2M_SUCCESS == nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + strUart.u16Sz = rsz; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + M2M_ERR("failed to send cfg bytes\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + if (b[0] == 0x5a) + { + s8Ret = 0; + onchip = 1; + M2M_INFO("Built-in WINC1500 UART Found\n"); + } + else if(b[0] == 0x5b) + { + s8Ret = 0; + onchip = 0; + M2M_INFO("WINC1500 Serial Bridge Found\n"); + } + /*TODO: this should be the way we read the register since the cortus is little endian*/ + /**pu32RetVal = b[0] | ((uint32)b[1] << 8) | ((uint32)b[2] << 16) | ((uint32)b[3] << 24);*/ + if(s8Ret == M2M_SUCCESS) + s8Ret = (sint8)onchip; + return s8Ret; +} + sint8 nm_uart_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) +{ + tstrNmUartDefault strUart; + sint8 s8Ret = M2M_SUCCESS; + uint8 b [HDR_SZ+1]; + uint8 rsz; + + /*read reg*/ + b[0] = 0xa5; + b[1] = 0; + b[2] = 0; + b[3] = 0; + b[4] = 0; + b[5] = (uint8)(u32Addr & 0x000000ff); + b[6] = (uint8)((u32Addr & 0x0000ff00)>>8); + b[7] = (uint8)((u32Addr & 0x00ff0000)>>16); + b[8] = (uint8)((u32Addr & 0xff000000)>>24); + b[9] = 0; + b[10] = 0; + b[11] = 0; + b[12] = 0; + + b[2] = get_cs(&b[1],HDR_SZ); + + rsz = 4; + strUart.pu8Buf = b; + strUart.u16Sz = sizeof(b); + + if(M2M_SUCCESS == nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + if(!nm_bus_get_chip_type()) + { + strUart.u16Sz = 1; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + if(b[0] == 0xAC) + { + M2M_DBG("Successfully sent the command\n"); + strUart.u16Sz = rsz; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + strUart.u16Sz = rsz; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + } + } + else + { + M2M_ERR("failed to send cfg bytes\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + /*TODO: this should be the way we read the register since the cortus is little endian*/ + /**pu32RetVal = b[0] | ((uint32)b[1] << 8) | ((uint32)b[2] << 16) | ((uint32)b[3] << 24);*/ + + *pu32RetVal = ((uint32)b[0] << 24) | ((uint32)b[1] << 16) | ((uint32)b[2] << 8) | b[3]; + + return s8Ret; +} + +/* +* @fn nm_uart_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +* @author Dina El Sissy +* @date 13 AUG 2012 +* @version 1.0 +*/ +uint32 nm_uart_read_reg(uint32 u32Addr) +{ + uint32 val; + nm_uart_read_reg_with_ret(u32Addr , &val); + return val; +} + +/* +* @fn nm_uart_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Dina El Sissy +* @date 13 AUG 2012 +* @version 1.0 +*/ +sint8 nm_uart_write_reg(uint32 u32Addr, uint32 u32Val) +{ + tstrNmUartDefault strUart; + sint8 s8Ret = M2M_SUCCESS; + uint8 b[HDR_SZ+1]; + + /*write reg*/ + b[0] = 0xa5; + b[1] = 1; + b[2] = 0; + b[3] = 0; + b[4] = 0; + b[5] = (uint8)(u32Addr & 0x000000ff); + b[6] = (uint8)((u32Addr & 0x0000ff00)>>8); + b[7] = (uint8)((u32Addr & 0x00ff0000)>>16); + b[8] = (uint8)((u32Addr & 0xff000000)>>24); + b[9] = (uint8)(u32Val & 0x000000ff); + b[10] = (uint8)((u32Val & 0x0000ff00)>>8); + b[11] = (uint8)((u32Val & 0x00ff0000)>>16); + b[12] = (uint8)((u32Val & 0xff000000)>>24); + + b[2] = get_cs(&b[1],HDR_SZ); + + get_cs(&b[1],HDR_SZ); + + strUart.pu8Buf = b; + strUart.u16Sz = sizeof(b); + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + else + { + if(!nm_bus_get_chip_type()) + { + //check for the ack from the SAMD21 for the packet reception. + strUart.u16Sz = 1; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + if(b[0] == 0xAC) + { + M2M_DBG("Successfully sent the reg write command\n"); + } + else + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + } + + return s8Ret; +} + + +/** +* @fn nm_uart_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u16Sz +* Number of bytes to read. The buffer size must be >= u16Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Dina El Sissy +* @date 13 AUG 2012 +* @version 1.0 +*/ +sint8 nm_uart_read_block(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz) +{ + tstrNmUartDefault strUart; + sint8 s8Ret = M2M_SUCCESS; + uint8 au8Buf[HDR_SZ+1]; + + au8Buf[0] = 0xa5; + au8Buf[1] = 2; + au8Buf[2] = 0; + au8Buf[3] = (uint8)(u16Sz & 0x00ff); + au8Buf[4] = (uint8)((u16Sz & 0xff00)>>8); + au8Buf[5] = (uint8)(u32Addr & 0x000000ff); + au8Buf[6] = (uint8)((u32Addr & 0x0000ff00)>>8); + au8Buf[7] = (uint8)((u32Addr & 0x00ff0000)>>16); + au8Buf[8] = (uint8)((u32Addr & 0xff000000)>>24); + au8Buf[9] = 0; + au8Buf[10] = 0; + au8Buf[11] = 0; + au8Buf[12] = 0; + + au8Buf[2] = get_cs(&au8Buf[1],HDR_SZ); + + strUart.pu8Buf = au8Buf; + strUart.u16Sz = sizeof(au8Buf); + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + else + { + if(!nm_bus_get_chip_type()) + { + //check for the ack from the SAMD21 for the packet reception. + strUart.u16Sz = 1; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + if(au8Buf[0] == 0xAC) + { + M2M_DBG("Successfully sent the block read command\n"); + strUart.pu8Buf = pu8Buf; + strUart.u16Sz = u16Sz; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + M2M_ERR("read error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + M2M_ERR("write error (Error sending the block read command)\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + strUart.pu8Buf = pu8Buf; + strUart.u16Sz = u16Sz; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + M2M_ERR("read error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + } + + return s8Ret; +} + +/** +* @fn nm_uart_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u16Sz +* Number of bytes to write. The buffer size must be >= u16Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Dina El Sissy +* @date 13 AUG 2012 +* @version 1.0 +*/ +sint8 nm_uart_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) +{ + tstrNmUartDefault strUart; + sint8 s8Ret = M2M_SUCCESS; + static uint8 au8Buf[HDR_SZ+1]; + + au8Buf[0] = 0xa5; + au8Buf[1] = 3; + au8Buf[2] = 0; + au8Buf[3] = (uint8)(u16Sz & 0x00ff); + au8Buf[4] = (uint8)((u16Sz & 0xff00)>>8); + au8Buf[5] = (uint8)(u32Addr & 0x000000ff); + au8Buf[6] = (uint8)((u32Addr & 0x0000ff00)>>8); + au8Buf[7] = (uint8)((u32Addr & 0x00ff0000)>>16); + au8Buf[8] = (uint8)((u32Addr & 0xff000000)>>24); + au8Buf[9] = 0; + au8Buf[10] = 0; + au8Buf[11] = 0; + au8Buf[12] = 0; + + au8Buf[2] = get_cs(&au8Buf[1],HDR_SZ); + + strUart.pu8Buf = au8Buf; + strUart.u16Sz = sizeof(au8Buf); + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + else + { + if(!nm_bus_get_chip_type()) + { + //check for the ack from the SAMD21 for the packet reception. + strUart.u16Sz = 1; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + if(au8Buf[0] == 0xAC) + { + M2M_DBG("Successfully sent the block Write command\n"); + strUart.pu8Buf = puBuf; + strUart.u16Sz = u16Sz; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + else + { + //check for the ack from the SAMD21 for the payload reception. + strUart.pu8Buf = au8Buf; + strUart.u16Sz = 1; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + if(au8Buf[0] == 0xAC) + { + M2M_DBG("Successfully sent the data payload\n"); + } + else + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + } + else + { + M2M_ERR("write error (Error sending the block write command)\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + strUart.pu8Buf = puBuf; + strUart.u16Sz = u16Sz; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + } + return s8Ret; +} + +/** +* @fn nm_uart_reconfigure +* @brief Reconfigures the UART interface +* @param [in] ptr +* Pointer to a DWORD containing baudrate at this moment. +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Viswanathan Murugesan +* @date 22 OCT 2014 +* @version 1.0 +*/ +sint8 nm_uart_reconfigure(void *ptr) +{ + tstrNmUartDefault strUart; + sint8 s8Ret = M2M_SUCCESS; + uint8 b[HDR_SZ+1]; + + /*write reg*/ + b[0] = 0xa5; + b[1] = 5; + b[2] = 0; + b[3] = 0; + b[4] = 0; + b[5] = 0; + b[6] = 0; + b[7] = 0; + b[8] = 0; + b[9] = (uint8)((*(unsigned long *)ptr) & 0x000000ff); + b[10] = (uint8)(((*(unsigned long *)ptr) & 0x0000ff00)>>8); + b[11] = (uint8)(((*(unsigned long *)ptr) & 0x00ff0000)>>16); + b[12] = (uint8)(((*(unsigned long *)ptr) & 0xff000000)>>24); + + b[2] = get_cs(&b[1],HDR_SZ); + + get_cs(&b[1],HDR_SZ); + + strUart.pu8Buf = b; + strUart.u16Sz = sizeof(b); + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + else + { + if(!nm_bus_get_chip_type()) + { + //check for the ack from the SAMD21 for the packet reception. + strUart.u16Sz = 1; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + if(b[0] == 0xAC) + { + M2M_DBG("Successfully sent the UART reconfigure command\n"); + } + else + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + } + + return s8Ret; +} +#endif +/* EOF */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmuart.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmuart.h new file mode 100644 index 0000000..8f07d39 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmuart.h @@ -0,0 +1,118 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 UART protocol bus APIs implementation. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NMUART_H_ +#define _NMUART_H_ + +#include "common/include/nm_common.h" + +/* +* @fn nm_uart_sync_cmd +* @brief Check COM Port +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_uart_sync_cmd(void); +/** +* @fn nm_uart_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +*/ +uint32 nm_uart_read_reg(uint32 u32Addr); + +/** +* @fn nm_uart_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_uart_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); + +/** +* @fn nm_uart_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_uart_write_reg(uint32 u32Addr, uint32 u32Val); + +/** +* @fn nm_uart_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u16Sz +* Number of bytes to read. The buffer size must be >= u16Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_uart_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); + +/** +* @fn nm_uart_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u16Sz +* Number of bytes to write. The buffer size must be >= u16Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_uart_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); + +/** +* @fn nm_uart_reconfigure +* @brief Reconfigures the UART interface +* @param [in] ptr +* Pointer to a DWORD containing baudrate at this moment. +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_uart_reconfigure(void *ptr); +#endif /* _NMI2C_H_ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h b/feather_sensor_transmit/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h new file mode 100644 index 0000000..933ad67 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h @@ -0,0 +1,461 @@ +/** + * + * \file + * + * \brief BSD compatible socket interface internal types. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +#ifndef __M2M_SOCKET_HOST_IF_H__ +#define __M2M_SOCKET_HOST_IF_H__ + + +#ifdef __cplusplus +extern "C" { +#endif + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#ifndef _BOOT_ +#ifndef _FIRMWARE_ +#include "socket/include/socket.h" +#else +#include "m2m_types.h" +#endif +#endif + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/* + * HOSTNAME_MAX_SIZE is defined here and also in host_drv/socket/include/socket.h + * The two definitions must match. +*/ +#ifdef _FIRMWARE_ +#define HOSTNAME_MAX_SIZE (64) +#endif + +#define SSL_MAX_OPT_LEN HOSTNAME_MAX_SIZE + + + +#define SOCKET_CMD_INVALID 0x00 +/*!< + Invlaid Socket command value. +*/ + + +#define SOCKET_CMD_BIND 0x41 +/*!< + Socket Binding command value. +*/ + + +#define SOCKET_CMD_LISTEN 0x42 +/*!< + Socket Listening command value. +*/ + + +#define SOCKET_CMD_ACCEPT 0x43 +/*!< + Socket Accepting command value. +*/ + + +#define SOCKET_CMD_CONNECT 0x44 +/*!< + Socket Connecting command value. +*/ + + +#define SOCKET_CMD_SEND 0x45 +/*!< + Socket send command value. +*/ + + +#define SOCKET_CMD_RECV 0x46 +/*!< + Socket Recieve command value. +*/ + + +#define SOCKET_CMD_SENDTO 0x47 +/*!< + Socket sendTo command value. +*/ + + +#define SOCKET_CMD_RECVFROM 0x48 +/*!< + Socket RecieveFrom command value. +*/ + + +#define SOCKET_CMD_CLOSE 0x49 +/*!< + Socket Close command value. +*/ + + +#define SOCKET_CMD_DNS_RESOLVE 0x4A +/*!< + Socket DNS Resolve command value. +*/ + + +#define SOCKET_CMD_SSL_CONNECT 0x4B +/*!< + SSL-Socket Connect command value. +*/ + + +#define SOCKET_CMD_SSL_SEND 0x4C +/*!< + SSL-Socket Send command value. +*/ + + +#define SOCKET_CMD_SSL_RECV 0x4D +/*!< + SSL-Socket Recieve command value. +*/ + + +#define SOCKET_CMD_SSL_CLOSE 0x4E +/*!< + SSL-Socket Close command value. +*/ + + +#define SOCKET_CMD_SET_SOCKET_OPTION 0x4F +/*!< + Set Socket Option command value. +*/ + + +#define SOCKET_CMD_SSL_CREATE 0x50 +/*!< +*/ + + +#define SOCKET_CMD_SSL_SET_SOCK_OPT 0x51 +/*!< +*/ + + +#define SOCKET_CMD_PING 0x52 +/*!< +*/ + + +#define SOCKET_CMD_SSL_SET_CS_LIST 0x53 +/*!< + Recommend instead using @ref M2M_SSL_REQ_SET_CS_LIST and + associated response @ref M2M_SSL_RESP_SET_CS_LIST +*/ + + +#define SOCKET_CMD_SSL_BIND 0x54 +/*!< +*/ + + +#define SOCKET_CMD_SSL_EXP_CHECK 0x55 +/*!< +*/ + + + +#define PING_ERR_SUCCESS 0 +#define PING_ERR_DEST_UNREACH 1 +#define PING_ERR_TIMEOUT 2 + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +/*! +* @brief +*/ +typedef struct{ + uint16 u16Family; + uint16 u16Port; + uint32 u32IPAddr; +}tstrSockAddr; + + +typedef sint8 SOCKET; +typedef tstrSockAddr tstrUIPSockAddr; + + + +/*! +@struct \ + tstrDnsReply + +@brief + DNS Reply, contains hostName and HostIP. +*/ +typedef struct{ + char acHostName[HOSTNAME_MAX_SIZE]; + uint32 u32HostIP; +}tstrDnsReply; + + +/*! +@brief +*/ +typedef struct{ + tstrSockAddr strAddr; + SOCKET sock; + uint8 u8Void; + uint16 u16SessionID; +}tstrBindCmd; + + +/*! +@brief +*/ +typedef struct{ + SOCKET sock; + sint8 s8Status; + uint16 u16SessionID; +}tstrBindReply; + + +/*! +* @brief +*/ +typedef struct{ + SOCKET sock; + uint8 u8BackLog; + uint16 u16SessionID; +}tstrListenCmd; + + +/*! +@struct \ + tstrSocketRecvMsg + +@brief Socket recv status. + + It is passed to the APPSocketEventHandler with SOCKET_MSG_RECV or SOCKET_MSG_RECVFROM message type + in a response to a user call to the recv or recvfrom. + If the received data from the remote peer is larger than the USER Buffer size (given at recv call), the data is + delivered to the user in a number of consecutive chunks according to the USER Buffer size. +*/ +typedef struct{ + SOCKET sock; + sint8 s8Status; + uint16 u16SessionID; +}tstrListenReply; + + +/*! +* @brief +*/ +typedef struct{ + tstrSockAddr strAddr; + SOCKET sListenSock; + SOCKET sConnectedSock; + uint16 u16AppDataOffset; + /*!< + In further packet send requests the host interface should put the user application + data at this offset in the allocated shared data packet. + */ +}tstrAcceptReply; + + +/*! +* @brief +*/ +typedef struct{ + tstrSockAddr strAddr; + SOCKET sock; + uint8 u8SslFlags; + uint16 u16SessionID; +}tstrConnectCmd; + + +/*! +@struct \ + tstrConnectReply + +@brief + Connect Reply, contains sock number and error value +*/ +typedef struct{ + SOCKET sock; + sint8 s8Error; + uint16 u16AppDataOffset; + /*!< + In further packet send requests the host interface should put the user application + data at this offset in the allocated shared data packet. + */ +}tstrConnectReply; + + +/*! +@brief +*/ +typedef struct{ + SOCKET sock; + uint8 u8Void; + uint16 u16DataSize; + tstrSockAddr strAddr; + uint16 u16SessionID; + uint16 u16Void; +}tstrSendCmd; + + +/*! +@struct \ + tstrSendReply + +@brief + Send Reply, contains socket number and number of sent bytes. +*/ +typedef struct{ + SOCKET sock; + uint8 u8Void; + sint16 s16SentBytes; + uint16 u16SessionID; + uint16 u16Void; +}tstrSendReply; + + +/*! +* @brief +*/ +typedef struct{ + uint32 u32Timeoutmsec; + SOCKET sock; + uint8 u8Void; + uint16 u16SessionID; +}tstrRecvCmd; + + +/*! +@struct +@brief +*/ +typedef struct{ + tstrSockAddr strRemoteAddr; + sint16 s16RecvStatus; + uint16 u16DataOffset; + SOCKET sock; + uint8 u8Void; + uint16 u16SessionID; +}tstrRecvReply; + + +/*! +* @brief +*/ +typedef struct{ + uint32 u32OptionValue; + SOCKET sock; + uint8 u8Option; + uint16 u16SessionID; +}tstrSetSocketOptCmd; + + +typedef struct{ + SOCKET sslSock; + uint8 __PAD24__[3]; +}tstrSSLSocketCreateCmd; + + +/*! +* @brief +*/ +typedef struct{ + SOCKET sock; + uint8 u8Option; + uint16 u16SessionID; + uint32 u32OptLen; + uint8 au8OptVal[SSL_MAX_OPT_LEN]; +}tstrSSLSetSockOptCmd; + + +/*! +*/ +typedef struct{ + uint32 u32DestIPAddr; + uint32 u32CmdPrivate; + uint16 u16PingCount; + uint8 u8TTL; + uint8 __PAD8__; +}tstrPingCmd; + + +typedef struct{ + uint32 u32IPAddr; + uint32 u32CmdPrivate; + uint32 u32RTT; + uint16 u16Success; + uint16 u16Fail; + uint8 u8ErrorCode; + uint8 __PAD24__[3]; +}tstrPingReply; + + +/*! +@struct\ + tstrSslCertExpSettings + +@brief SSL Certificate Expiry Validation Settings + +@sa tenuSslCertExpSettings +*/ +typedef struct{ + uint32 u32CertExpValidationOpt; + /*!< + See @tenuSslCertExpSettings for possible values. + */ +}tstrSslCertExpSettings; + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* __M2M_SOCKET_HOST_IF_H__ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/socket/include/socket.h b/feather_sensor_transmit/libraries/WiFi101/src/socket/include/socket.h new file mode 100644 index 0000000..837959a --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/socket/include/socket.h @@ -0,0 +1,2065 @@ +/** + * + * \file + * + * \brief WINC BSD compatible Socket Interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef __SOCKET_H__ +#define __SOCKET_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup SocketHeader Socket + * BSD compatible socket interface beftween the host layer and the network + * protocol stacks in the firmware. + * These functions are used by the host application to send or receive + * packets and to do other socket operations. + */ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "common/include/nm_common.h" +#include "driver/include/m2m_types.h" + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/** + * @defgroup SocketDefines Defines + * @ingroup SocketHeader + */ + +/** @defgroup IPDefines TCP/IP Defines + * @ingroup SocketDefines + * The following list of macros are used to define constants used throughout the socket layer. + * @{ + */ + +/* + * HOSTNAME_MAX_SIZE is defined here and also in host_drv/socket/include/m2m_socket_host_if.h + * The two definitions must match. +*/ +#define HOSTNAME_MAX_SIZE 64 +/*!< + Maximum allowed size for a host domain name passed to the function gethostbyname @ref gethostbyname. + command value. Used with the setsockopt function. + +*/ + +#define SOCKET_BUFFER_MAX_LENGTH 1400 +/*!< + Maximum allowed size for a socket data buffer. Used with @ref send socket + function to ensure that the buffer sent is within the allowed range. +*/ + +#define AF_INET 2 +/*!< + The AF_INET is the address family used for IPv4. An IPv4 transport address is specified with the @ref sockaddr_in structure. + (It is the only supported type for the current implementation.) +*/ + + +#define SOCK_STREAM 1 +/*!< + One of the IPv4 supported socket types for reliable connection-oriented stream connection. + Passed to the @ref socket function for the socket creation operation. +*/ + +#define SOCK_DGRAM 2 +/*!< + One of the IPv4 supported socket types for unreliable connectionless datagram connection. + Passed to the @ref socket function for the socket creation operation. +*/ + + +#define SOCKET_FLAGS_SSL 0x01 +/*!< + This flag shall be passed to the socket API for SSL session. +*/ + +#define TCP_SOCK_MAX (7) +/*!< + Maximum number of simultaneous TCP sockets. +*/ + +#define UDP_SOCK_MAX 4 +/*!< + Maximum number of simultaneous UDP sockets. +*/ + +#define MAX_SOCKET (TCP_SOCK_MAX + UDP_SOCK_MAX) +/*!< + Maximum number of Sockets. +*/ + +#define SOL_SOCKET 1 +/*!< + Socket option. + Used with the @ref setsockopt function +*/ + +#define SOL_SSL_SOCKET 2 +/*!< + SSL Socket option level. + Used with the @ref setsockopt function +*/ + +#define SO_SET_UDP_SEND_CALLBACK 0x00 +/*!< + Socket option used by the application to enable/disable + the use of UDP send callbacks. + Used with the @ref setsockopt function. +*/ + +#define IP_ADD_MEMBERSHIP 0x01 +/*!< + Set Socket Option Add Membership command value (to join a multicast group). + Used with the @ref setsockopt function. +*/ + + +#define IP_DROP_MEMBERSHIP 0x02 +/*!< + Set Socket Option Drop Membership command value (to leave a multicast group). + Used with the @ref setsockopt function. +*/ + //@} + + + +/** + * @defgroup TLSDefines TLS Defines + * @ingroup SocketDefines + */ + + + +/** @defgroup SSLSocketOptions TLS Socket Options + * @ingroup TLSDefines + * The following list of macros are used to define SSL Socket options. + * @{ + * @sa setsockopt + */ + +#define SO_SSL_BYPASS_X509_VERIF 0x01 +/*!< + Allow an opened SSL socket to bypass the X509 certificate + verification process. + It is highly required NOT to use this socket option in production + software applications. It is supported for debugging and testing + purposes. + The option value should be casted to int type and it is handled + as a boolean flag. +*/ + + +#define SO_SSL_SNI 0x02 +/*!< + Set the Server Name Indicator (SNI) for an SSL socket. The + SNI is a NULL terminated string containing the server name + associated with the connection. It must not exceed the size + of HOSTNAME_MAX_SIZE. +*/ + + +#define SO_SSL_ENABLE_SESSION_CACHING 0x03 +/*!< + This option allow the TLS to cache the session information for fast + TLS session establishment in future connections using the + TLS Protocol session resume features. +*/ + + +#define SO_SSL_ENABLE_SNI_VALIDATION 0x04 +/*!< + Enable SNI validation against the server's certificate subject + common name. If there is no SNI provided (via the SO_SSL_SNI + option), setting this option does nothing. +*/ + + +//@} + + + +/** @defgroup LegacySSLCipherSuite Legacy names for TLS Cipher Suite IDs + * @ingroup TLSDefines + * The following list of macros MUST NOT be used. Instead use the new names under SSLCipherSuiteID + * @sa sslSetActiveCipherSuites + * @{ + */ + +#define SSL_ENABLE_RSA_SHA_SUITES 0x01 +/*!< + Enable RSA Hmac_SHA based Cipher suites. For example, + TLS_RSA_WITH_AES_128_CBC_SHA +*/ + + +#define SSL_ENABLE_RSA_SHA256_SUITES 0x02 +/*!< + Enable RSA Hmac_SHA256 based Cipher suites. For example, + TLS_RSA_WITH_AES_128_CBC_SHA256 +*/ + + +#define SSL_ENABLE_DHE_SHA_SUITES 0x04 +/*!< + Enable DHE Hmac_SHA based Cipher suites. For example, + TLS_DHE_RSA_WITH_AES_128_CBC_SHA +*/ + + +#define SSL_ENABLE_DHE_SHA256_SUITES 0x08 +/*!< + Enable DHE Hmac_SHA256 based Cipher suites. For example, + TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 +*/ + + +#define SSL_ENABLE_RSA_GCM_SUITES 0x10 +/*!< + Enable RSA AEAD based Cipher suites. For example, + TLS_RSA_WITH_AES_128_GCM_SHA256 +*/ + + +#define SSL_ENABLE_DHE_GCM_SUITES 0x20 +/*!< + Enable DHE AEAD based Cipher suites. For example, + TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 +*/ + + +#define SSL_ENABLE_ALL_SUITES 0x0000003F +/*!< + Enable all possible supported cipher suites. +*/ + +//@} + + + +/** @defgroup SSLCipherSuiteID TLS Cipher Suite IDs + * @ingroup TLSDefines + * The following list of macros defined the list of supported TLS Cipher suites. + * Each MACRO defines a single Cipher suite. + * @sa m2m_ssl_set_active_ciphersuites + * @{ + */ + +#define SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA NBIT0 +#define SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 NBIT1 +#define SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA NBIT2 +#define SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 NBIT3 +#define SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 NBIT4 +#define SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 NBIT5 +#define SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA NBIT6 +#define SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 NBIT7 +#define SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA NBIT8 +#define SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 NBIT9 +#define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA NBIT10 +#define SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA NBIT11 +#define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 NBIT12 +#define SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 NBIT13 +#define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 NBIT14 +#define SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 NBIT15 + + + +#define SSL_ECC_ONLY_CIPHERS \ +(\ + SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 \ +) +/*!< + All ciphers that use ECC crypto only. This execuldes ciphers that use RSA. They use ECDSA instead. + These ciphers are turned off by default at startup. + The application may enable them if it has an ECC math engine (like ATECC508). +*/ +#define SSL_ECC_ALL_CIPHERS \ +(\ + SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA | \ + SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 | \ + SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 \ +) +/*!< + All supported ECC Ciphers including those ciphers that depend on RSA and ECC. + These ciphers are turned off by default at startup. + The application may enable them if it has an ECC math engine (like ATECC508). +*/ + +#define SSL_NON_ECC_CIPHERS_AES_128 \ +(\ + SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA | \ + SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA | \ + SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 | \ + SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 \ +) +/*!< + All supported AES-128 Ciphers (ECC ciphers are not counted). This is the default active group after startup. +*/ + + +#define SSL_ECC_CIPHERS_AES_256 \ +(\ + SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA \ +) +/*!< + ECC AES-256 supported ciphers. +*/ + + +#define SSL_NON_ECC_CIPHERS_AES_256 \ +(\ + SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA | \ + SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 | \ + SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA | \ + SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 \ +) +/*!< + AES-256 Ciphers. + This group is disabled by default at startup because the WINC1500 HW Accelerator + supports only AES-128. If the application needs to force AES-256 cipher support, + it could enable them (or any of them) explicitly by calling sslSetActiveCipherSuites. +*/ + + +#define SSL_CIPHER_ALL \ +(\ + SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA | \ + SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA | \ + SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 | \ + SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 | \ + SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA | \ + SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 | \ + SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA | \ + SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 | \ + SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA | \ + SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 | \ + SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 | \ + SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA \ +) +/*!< + Turn On All TLS Ciphers. +*/ + + + //@} + + + + +/************** +Socket Errors +**************/ +/**@defgroup SocketErrorCode Error Codes + * @ingroup SocketHeader + * The following list of macros are used to define the possible error codes returned as a result of a call to a socket function. + * Errors are listed in numerical order with the error macro name. + * @{ + */ +#define SOCK_ERR_NO_ERROR 0 +/*!< + Successful socket operation +*/ + + +#define SOCK_ERR_INVALID_ADDRESS -1 +/*!< + Socket address is invalid. The socket operation cannot be completed successfully without specifying a specific address + For example: bind is called without specifying a port number +*/ + + +#define SOCK_ERR_ADDR_ALREADY_IN_USE -2 +/*!< + Socket operation cannot bind on the given address. With socket operations, only one IP address per socket is permitted. + Any attempt for a new socket to bind with an IP address already bound to another open socket, + will return the following error code. States that bind operation failed. +*/ + + +#define SOCK_ERR_MAX_TCP_SOCK -3 +/*!< + Exceeded the maximum number of TCP sockets. A maximum number of TCP sockets opened simultaneously is defined through TCP_SOCK_MAX. + It is not permitted to exceed that number at socket creation. Identifies that @ref socket operation failed. +*/ + + +#define SOCK_ERR_MAX_UDP_SOCK -4 +/*!< + Exceeded the maximum number of UDP sockets. A maximum number of UDP sockets opened simultaneously is defined through UDP_SOCK_MAX. + It is not permitted to exceed that number at socket creation. Identifies that @ref socket operation failed +*/ + + +#define SOCK_ERR_INVALID_ARG -6 +/*!< + An invalid argument is passed to a function. +*/ + + +#define SOCK_ERR_MAX_LISTEN_SOCK -7 +/*!< + Exceeded the maximum number of TCP passive listening sockets. + Identifies Identifies that @ref listen operation failed. +*/ + + +#define SOCK_ERR_INVALID -9 +/*!< + The requested socket operation is not valid in the + current socket state. + For example: @ref accept is called on a TCP socket before @ref bind or @ref listen. +*/ + + +#define SOCK_ERR_ADDR_IS_REQUIRED -11 +/*!< + Destination address is required. Failure to provide the socket address required for the socket operation to be completed. + It is generated as an error to the @ref sendto function when the address required to send the data to is not known. +*/ + + +#define SOCK_ERR_CONN_ABORTED -12 +/*!< + The socket is closed by the peer. The local socket is + closed also. +*/ + + +#define SOCK_ERR_TIMEOUT -13 +/*!< + The socket pending operation has Timedout. +*/ + + +#define SOCK_ERR_BUFFER_FULL -14 +/*!< + No buffer space available to be used for the requested socket operation. +*/ + +#ifdef _NM_BSP_BIG_END + +#define _htonl(m) (m) +#define _htons(A) (A) + +#else + +#define _htonl(m) \ + (uint32)(((uint32)(m << 24)) | ((uint32)((m & 0x0000FF00) << 8)) | ((uint32)((m & 0x00FF0000) >> 8)) | ((uint32)(m >> 24))) +/*!< + Convert a 4-byte integer from the host representation to the Network byte order representation. +*/ + + +#define _htons(A) (uint16)((((uint16) (A)) << 8) | (((uint16) (A)) >> 8)) +/*!< + Convert a 2-byte integer (short) from the host representation to the Network byte order representation. +*/ + + +#endif + + +#define _ntohl _htonl +/*!< + Convert a 4-byte integer from the Network byte order representation to the host representation . +*/ + + +#define _ntohs _htons +/*!< + Convert a 2-byte integer from the Network byte order representation to the host representation . +*/ + //@} + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/** @defgroup SocketEnums DataTypes + * @ingroup SocketHeader + * Specific Enumeration-typedefs used for socket operations + * @{ */ + +/*! +@typedef \ + SOCKET + +@brief + Definition for socket handler data type. + Socket ID,used with all socket operations to uniquely identify the socket handler. + Such an ID is uniquely assigned at socket creation when calling @ref socket operation. +*/ +typedef sint8 SOCKET; + + + +/*! +@struct \ + in_addr + +@brief + IPv4 address representation. + + This structure is used as a placeholder for IPV4 address in other structures. +@see + sockaddr_in +*/ +typedef struct{ + uint32 s_addr; + /*!< + Network Byte Order representation of the IPv4 address. For example, + the address "192.168.0.10" is represented as 0x0A00A8C0. + */ +}in_addr; + + +/*! +@struct \ + sockaddr + +@brief + Generic socket address structure. + +@see + sockaddr_in +*/ +struct sockaddr{ + uint16 sa_family; + /*!< +Socket address family. + */ + uint8 sa_data[14]; + /*!< + Maximum size of all the different socket address structures. + */ +}; + + +/*! +@struct \ + sockaddr_in + +@brief + Socket address structure for IPV4 addresses. Used to specify socket address information to which to connect to. + Can be cast to @ref sockaddr structure. +*/ +struct sockaddr_in{ + uint16 sin_family; + /*!< + Specifies the address family(AF). + Members of AF_INET address family are IPv4 addresses. + Hence,the only supported value for this is AF_INET. + */ + uint16 sin_port; + /*!< + Port number of the socket. + Network sockets are identified by a pair of IP addresses and port number. + It must be set in the Network Byte Order format , @ref _htons (e.g. _htons(80)). + Can NOT have zero value. + */ + in_addr sin_addr; + /*!< + IP Address of the socket. + The IP address is of type @ref in_addr structure. + Can be set to "0" to accept any IP address for server operation. non zero otherwise. + */ + uint8 sin_zero[8]; + /*!< + Padding to make structure the same size as @ref sockaddr. + */ +}; + //@} +/**@defgroup AsyncCalback Asynchronous Events + * @ingroup SocketEnums + * Specific Enumeration used for asynchronous operations + * @{ */ +/*! +@enum \ + tenuSocketCallbackMsgType + +@brief + Asynchronous APIs, make use of callback functions, in-order to return back the results once the corresponding socket operation is completed. + Hence resuming the normal execution of the application code while the socket operation returns the results. + Callback functions expect event messages to be passed in, in-order to identify the operation they're returning the results for. + The following enum identifies the type of events that are received in the callback function. + + Application Use: + In order for application developers to handle the pending events from the network controller through the callback functions. + A function call must be made to the function @ref m2m_wifi_handle_events at least once for each socket operation. + +@see + bind + listen + accept + connect + send + recv + +*/ +typedef enum{ + SOCKET_MSG_BIND = 1, + /*!< + Bind socket event. + */ + SOCKET_MSG_LISTEN, + /*!< + Listen socket event. + */ + SOCKET_MSG_DNS_RESOLVE, + /*!< + DNS Resolution event. + */ + SOCKET_MSG_ACCEPT, + /*!< + Accept socket event. + */ + SOCKET_MSG_CONNECT, + /*!< + Connect socket event. + */ + SOCKET_MSG_RECV, + /*!< + Receive socket event. + */ + SOCKET_MSG_SEND, + /*!< + Send socket event. + */ + SOCKET_MSG_SENDTO, + /*!< + sendto socket event. + */ + SOCKET_MSG_RECVFROM + /*!< + Recvfrom socket event. + */ +}tenuSocketCallbackMsgType; + + +/*! +@struct \ + tstrSocketBindMsg + +@brief Socket bind status. + + An asynchronous call to the @ref bind socket operation, returns information through this structure in response. + This structure together with the event @ref SOCKET_MSG_BIND are passed in paramters to the callback function. +@see + bind + +*/ +typedef struct{ + sint8 status; + /*!< + The result of the bind operation. + Holding a value of ZERO for a successful bind or otherwise a negative + error code corresponding to the type of error. + */ +}tstrSocketBindMsg; + + +/*! +@struct \ + tstrSocketListenMsg + +@brief Socket listen status. + + Socket listen information is returned through this structure in response to the asynchronous call to the @ref listen function. + This structure together with the event @ref SOCKET_MSG_LISTEN are passed-in parameters to the callback function. +@see + listen +*/ +typedef struct{ + sint8 status; + /*!< + Holding a value of ZERO for a successful listen or otherwise a negative + error code corresponding to the type of error. + */ +}tstrSocketListenMsg; + + + +/*! +@struct \ + tstrSocketAcceptMsg + +@brief Socket accept status. + + Socket accept information is returned through this structure in response to the asynchronous call to the @ref accept function. + This structure together with the event @ref SOCKET_MSG_ACCEPT are passed-in parameters to the callback function. +*/ +typedef struct{ + SOCKET sock; + /*!< + On a successful @ref accept operation, the return information is the socket ID for the accepted connection with the remote peer. + Otherwise a negative error code is returned to indicate failure of the accept operation. + */ + struct sockaddr_in strAddr; + /*!< + Socket address structure for the remote peer. + */ +}tstrSocketAcceptMsg; + + +/*! +@struct \ + tstrSocketConnectMsg + +@brief Socket connect status. + + Socket connect information is returned through this structure in response to the asynchronous call to the @ref connect socket function. + This structure together with the event @ref SOCKET_MSG_CONNECT are passed-in parameters to the callback function. +*/ +typedef struct{ + SOCKET sock; + /*!< + Socket ID referring to the socket passed to the connect function call. + */ + sint8 s8Error; + /*!< + Connect error code. + Holding a value of ZERO for a successful connect or otherwise a negative + error code corresponding to the type of error. + */ +}tstrSocketConnectMsg; + + +/*! +@struct \ + tstrSocketRecvMsg + +@brief Socket recv status. + + Socket receive information is returned through this structure in response to the asynchronous call to the recv or recvfrom socket functions. + This structure together with the events @ref SOCKET_MSG_RECV or @ref SOCKET_MSG_RECVFROM are passed-in parameters to the callback function. +@remark + In case the received data from the remote peer is larger than the USER buffer size defined during the asynchronous call to the @ref recv function, the data is + delivered to the user in a number of consecutive chunks according to the USER Buffer size. + a negative or zero buffer size indicates an error with the following code: + @ref SOCK_ERR_NO_ERROR : Socket connection closed + @ref SOCK_ERR_CONN_ABORTED : Socket connection aborted + @SOCK_ERR_TIMEOUT : Socket receive timed out +*/ +typedef struct{ + uint8 *pu8Buffer; + /*!< + Pointer to the USER buffer (passed to @ref recv and @ref recvfrom function) containing the received data chunk. + */ + sint16 s16BufferSize; + /*!< + The received data chunk size. + Holds a negative value if there is a receive error or ZERO on success upon reception of close socket message. + */ + uint16 u16RemainingSize; + /*!< + The number of bytes remaining in the current @ref recv operation. + */ + struct sockaddr_in strRemoteAddr; + /*!< + Socket address structure for the remote peer. It is valid for @ref SOCKET_MSG_RECVFROM event. + */ +}tstrSocketRecvMsg; + + +/*! +@typedef \ + tpfAppSocketCb + +@brief + The main socket application callback function. Applications register their main socket application callback through this function by calling @ref registerSocketCallback. + In response to events received, the following callback function is called to handle the corresponding asynchronous function called. Example: @ref bind, @ref connect,...etc. + +@param [in] sock + Socket ID for the callback. + + The socket callback function is called whenever a new event is recived in response + to socket operations. + +@param [in] u8Msg + Socket event type. Possible values are: + - @ref SOCKET_MSG_BIND + - @ref SOCKET_MSG_LISTEN + - @ref SOCKET_MSG_ACCEPT + - @ref SOCKET_MSG_CONNECT + - @ref SOCKET_MSG_RECV + - @ref SOCKET_MSG_SEND + - @ref SOCKET_MSG_SENDTO + - @ref SOCKET_MSG_RECVFROM + +@param [in] pvMsg + Pointer to message structure. Existing types are: + - tstrSocketBindMsg + - tstrSocketListenMsg + - tstrSocketAcceptMsg + - tstrSocketConnectMsg + - tstrSocketRecvMsg + +@see + tenuSocketCallbackMsgType + tstrSocketRecvMsg + tstrSocketConnectMsg + tstrSocketAcceptMsg + tstrSocketListenMsg + tstrSocketBindMsg +*/ +typedef void (*tpfAppSocketCb) (SOCKET sock, uint8 u8Msg, void * pvMsg); + + +/*! +@typedef \ + tpfAppResolveCb + +@brief + DNS resolution callback function. + Applications requiring DNS resolution should register their callback through this function by calling @ref registerSocketCallback. + The following callback is triggered in response to asynchronous call to the @ref gethostbyname function (DNS Resolution callback). + +@param [in] pu8DomainName + Domain name of the host. + +@param [in] u32ServerIP + Server IPv4 address encoded in NW byte order format. If it is Zero, then the DNS resolution failed. +*/ +typedef void (*tpfAppResolveCb) (uint8* pu8DomainName, uint32 u32ServerIP); + +/*! +@typedef \ + tpfPingCb + +@brief PING Callback + + The function delivers the ping statistics for the sent ping triggered by calling + m2m_ping_req. + +@param [in] u32IPAddr + Destination IP. + +@param [in] u32RTT + Round Trip Time. + +@param [in] u8ErrorCode + Ping error code. It may be one of: + - PING_ERR_SUCCESS + - PING_ERR_DEST_UNREACH + - PING_ERR_TIMEOUT +*/ +typedef void (*tpfPingCb)(uint32 u32IPAddr, uint32 u32RTT, uint8 u8ErrorCode); + + /**@}*/ +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/** \defgroup SocketAPI Function + * @ingroup SocketHeader + */ + +/** @defgroup SocketInitalizationFn socketInit + * @ingroup SocketAPI + * The function performs the necessary initializations for the socket library through the following steps: + - A check made by the global variable gbSocketInit, ensuring that initialization for sockets is performed only once, + in-order to prevent reseting the socket instances already created in the global socket array (gastrSockets). + - Zero initializations to the global socket array (gastrSockets), which holds the list of TCP sockets. + - Registers the socket (Host Interface)hif callback function through the call to the hif_register_cb function. + This facilitates handling all of the socket related functions received through interrupts from the firmware. + + */ + /**@{*/ +/*! +@fn \ + NMI_API void socketInit(void); + +@param [in] void + +@return void + +@remarks + This initialization function must be invoked before any socket operation is performed. + No error codes from this initialization function since the socket array is statically allocated based in the maximum number of + sockets @ref MAX_SOCKET based on the systems capability. +\section Example +This example demonstrates the use of the socketinit for socket initialization for an mqtt chat application. + \code + tstrWifiInitParam param; + int8_t ret; + char topic[strlen(MAIN_CHAT_TOPIC) + MAIN_CHAT_USER_NAME_SIZE + 1]; + + //Initialize the board. + system_init(); + + //Initialize the UART console. + configure_console(); + + // Initialize the BSP. + nm_bsp_init(); + + ---------- + + // Initialize socket interface. + socketInit(); + registerSocketCallback(socket_event_handler, socket_resolve_handler); + + // Connect to router. + m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), + MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); + +\endcode +*/ +NMI_API void socketInit(void); + + +/*! +@fn \ + NMI_API void socketDeinit(void); + +@brief Socket Layer De-initialization + + The function performs the necessary cleanup for the socket library static data + It must be invoked as the last any socket operation is performed on any active sockets. +*/ +NMI_API void socketDeinit(void); + + +/** @} */ +/** @defgroup SocketCallbackFn registerSocketCallback + * @ingroup SocketAPI + Register two callback functions one for asynchronous socket events and the other one for DNS callback registering function. + The registered callback functions are used to retrieve information in response to the asynchronous socket functions called. + */ + /**@{*/ + + +/*! +@fn \ + NMI_API void registerSocketCallback(tpfAppSocketCb socket_cb, tpfAppResolveCb resolve_cb); + +@param [in] tpfAppSocketCb + Assignment of callback function to the global callback @ref tpfAppSocketCb gpfAppSocketCb. Delivers + socket messages to the host application. In response to the asynchronous function calls, such as @ref bind + @ref listen @ref accept @ref connect + +@param [in] tpfAppResolveCb + Assignment of callback function to the global callback @ref tpfAppResolveCb gpfAppResolveCb. + Used for DNS resolving functionalities. The DNS resolving technique is determined by the application + registering the callback. + NULL is assigned when, DNS resolution is not required. + +@return void +@remarks + If any of the socket functionalities is not to be used, NULL is passed in as a parameter. + It must be invoked after socketinit and before other socket layer operations. + +\section Example + This example demonstrates the use of the registerSocketCallback to register a socket callback function with DNS resolution CB set to null + for a simple UDP server example. + \code + tstrWifiInitParam param; + int8_t ret; + struct sockaddr_in addr; + + // Initialize the board + system_init(); + + //Initialize the UART console. + configure_console(); + + // Initialize the BSP. + nm_bsp_init(); + + // Initialize socket address structure. + addr.sin_family = AF_INET; + addr.sin_port = _htons(MAIN_WIFI_M2M_SERVER_PORT); + addr.sin_addr.s_addr = _htonl(MAIN_WIFI_M2M_SERVER_IP); + + // Initialize Wi-Fi parameters structure. + memset((uint8_t *)¶m, 0, sizeof(tstrWifiInitParam)); + + // Initialize Wi-Fi driver with data and status callbacks. + param.pfAppWifiCb = wifi_cb; + ret = m2m_wifi_init(¶m); + if (M2M_SUCCESS != ret) { + printf("main: m2m_wifi_init call error!(%d)\r\n", ret); + while (1) { + } + } + + // Initialize socket module + socketInit(); + registerSocketCallback(socket_cb, NULL); + + // Connect to router. + m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); + \endcode +*/ +NMI_API void registerSocketCallback(tpfAppSocketCb socket_cb, tpfAppResolveCb resolve_cb); + + +/** @} */ + +/** @defgroup SocketFn socket + * @ingroup SocketAPI + * Synchronous socket allocation function based on the specified socket type. Created sockets are non-blocking and their possible types are either TCP or a UDP sockets. + * The maximum allowed number of TCP sockets is @ref TCP_SOCK_MAX sockets while the maximum number of UDP sockets that can be created simultaneously is @ref UDP_SOCK_MAX sockets. + * +*/ + /**@{*/ +/*! +@fn \ + NMI_API SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags); + + +@param [in] u16Domain + Socket family. The only allowed value is AF_INET (IPv4.0) for TCP/UDP sockets. + +@param [in] u8Type + Socket type. Allowed values are: + - [SOCK_STREAM](@ref SOCK_STREAM) + - [SOCK_DGRAM](@ref SOCK_DGRAM) + +@param [in] u8Flags + Used to specify the socket creation flags. It shall be set to zero for normal TCP/UDP sockets. + It could be @ref SOCKET_FLAGS_SSL if the socket is used for SSL session. The use of the flag + @ref SOCKET_FLAGS_SSL has no meaning in case of UDP sockets. + +@pre + The @ref socketInit function must be called once at the beginning of the application to initialize the socket handler. + before any call to the socket function can be made. + +@see + connect + bind + listen + accept + recv + recvfrom + send + sendto + close + setsockopt + getsockopt + +@return + On successful socket creation, a non-blocking socket type is created and a socket ID is returned + In case of failure the function returns a negative value, identifying one of the socket error codes defined. + For example: @ref SOCK_ERR_INVALID for invalid argument or + @ref SOCK_ERR_MAX_TCP_SOCK if the number of TCP allocated sockets exceeds the number of available sockets. + +@remarks + The socket function must be called a priori to any other related socket functions "e.g. send, recv, close ..etc" +\section Example + This example demonstrates the use of the socket function to allocate the socket, returning the socket handler to be used for other +socket operations. Socket creation is dependent on the socket type. +\subsection sub1 UDP example +@code + SOCKET UdpServerSocket = -1; + + UdpServerSocket = socket(AF_INET, SOCK_DGRAM, 0); + +@endcode +\subsection sub2 TCP example +@code + static SOCKET tcp_client_socket = -1; + + tcp_client_socket = socket(AF_INET, SOCK_STREAM, 0)); +@endcode +\subsection sub3 SSL example +@code +static SOCKET ssl_socket = -1; + +ssl_socket = socket(AF_INET, SOCK_STREAM, SOCK_FLAGS_SSL)); +@endcode +*/ +NMI_API SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags); + + +/** @} */ +/** @defgroup BindFn bind + * @ingroup SocketAPI +* Asynchronous bind function associates the provided address and local port to the socket. +* The function can be used with both TCP and UDP sockets it's mandatory to call the @ref bind function before starting any UDP or TCP server operation. +* Upon socket bind completion, the application will receive a @ref SOCKET_MSG_BIND message in the socket callback. +*/ + /**@{*/ +/*! +\fn \ + NMI_API sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); + + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] pstrAddr + Pointer to socket address structure "sockaddr_in" + [sockaddr_in](@ref sockaddr_in) + + +@param [in] u8AddrLen + Size of the given socket address structure in bytes. + +@pre + The socket function must be called to allocate a socket before passing the socket ID to the bind function. + +@see + socket + connect + listen + accept + recv + recvfrom + send + sendto + +@return + The function returns ZERO for successful operations and a negative value otherwise. + The possible error values are: + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + Indicating that the operation was successful. + + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) + Indicating passing invalid arguments such as negative socket ID or NULL socket address structure. + + - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID) + Indicate socket bind failure. +\section Example + This example demonstrates the call of the bind socket operation after a successful socket operation. +@code + struct sockaddr_in addr; + SOCKET udpServerSocket =-1; + int ret = -1; + + if(udpServerSocket == -1) + { + udpServerSocket = socket(AF_INET, SOCK_DGRAM, 0); + if(udpServerSocket >= 0) + { + addr.sin_family = AF_INET; + addr.sin_port = _htons(1234); + addr.sin_addr.s_addr = 0; + ret = bind(udpServerSocket,(struct sockaddr*)&addr,sizeof(addr)); + + if(ret != 0) + { + printf("Bind Failed. Error code = %d\n",ret); + close(udpServerSocket); + } + } + else + { + printf("UDP Server Socket Creation Failed\n"); + return; + } + } +@endcode +*/ +NMI_API sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); + + +/** @} */ + +/** @defgroup ListenFn listen + * @ingroup SocketAPI + * After successful socket binding to an IP address and port on the system, start listening on a passive socket for incoming connections. + The socket must be bound on a local port or the listen operation fails. + Upon the call to the asynchronous listen function, response is received through the event [SOCKET_MSG_BIND](@ref SOCKET_MSG_BIND) + in the socket callback. + A successful listen means the TCP server operation is active. If a connection is accepted, then the application socket callback function is + notified with the new connected socket through the event @ref SOCKET_MSG_ACCEPT. Hence there is no need to call the @ref accept function + after calling @ref listen. + + After a connection is accepted, the user is then required to call the @ref recv to receive any packets transmitted by the remote host or to receive notification of socket connection + termination. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 listen(SOCKET sock, uint8 backlog); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] backlog + Not used by the current implementation. + +@pre + The bind function must be called to assign the port number and IP address to the socket before the listen operation. + +@see + bind + accept + recv + recvfrom + send + sendto + +@return + The function returns ZERO for successful operations and a negative value otherwise. + The possible error values are: + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + Indicating that the operation was successful. + + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) + Indicating passing invalid arguments such as negative socket ID. + + - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID) + Indicate socket listen failure. +\section Example +This example demonstrates the call of the listen socket operation after a successful socket operation. +@code + static void TCP_Socketcallback(SOCKET sock, uint8 u8Msg, void * pvMsg) + { + int ret =-1; + + switch(u8Msg) + { + case SOCKET_MSG_BIND: + { + tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg; + if(pstrBind != NULL) + { + if(pstrBind->status == 0) + { + ret = listen(sock, 0); + + if(ret <0) + printf("Listen failure! Error = %d\n",ret); + } + else + { + M2M_ERR("bind Failure!\n"); + close(sock); + } + } + } + break; + + case SOCKET_MSG_LISTEN: + { + + tstrSocketListenMsg *pstrListen = (tstrSocketListenMsg*)pvMsg; + if(pstrListen != NULL) + { + if(pstrListen->status == 0) + { + ret = accept(sock,NULL,0); + } + else + { + M2M_ERR("listen Failure!\n"); + close(sock); + } + } + } + break; + + case SOCKET_MSG_ACCEPT: + { + tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg*)pvMsg; + + if(pstrAccept->sock >= 0) + { + TcpNotificationSocket = pstrAccept->sock; + recv(pstrAccept->sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT); + } + else + { + M2M_ERR("accept failure\n"); + } + } + break; + + default: + break; + } + } + +@endcode +*/ +NMI_API sint8 listen(SOCKET sock, uint8 backlog); +/** @} */ +/** @defgroup AcceptFn accept + * @ingroup SocketAPI + * The function has no current implementation. An empty deceleration is used to prevent errors when legacy application code is used. + * For recent application use, the accept function can be safer as it has no effect and could be safely removed from any application using it. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. +@param [in] addr + Not used in the current implementation. + +@param [in] addrlen + Not used in the current implementation. + +@return + The function returns ZERO for successful operations and a negative value otherwise. + The possible error values are: + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + Indicating that the operation was successful. + + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) + Indicating passing invalid arguments such as negative socket ID. +*/ +NMI_API sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen); +/** @} */ +/** @defgroup ConnectFn connect + * @ingroup SocketAPI + * Establishes a TCP connection with a remote server. + The asynchronous connect function must be called after receiving a valid socket ID from the @ref socket function. + The application socket callback function is notified of a successful new socket connection through the event @ref SOCKET_MSG_CONNECT. + A successful connect means the TCP session is active. The application is then required to make a call to the @ref recv + to receive any packets transmitted by the remote server, unless the application is interrupted by a notification of socket connection + termination. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] pstrAddr + Address of the remote server. +@param [in] pstrAddr + Pointer to socket address structure "sockaddr_in" + [sockaddr_in](@ref sockaddr_in) + +@param [in] u8AddrLen + Size of the given socket address structure in bytes. + Not currently used, implemented for BSD compatibility only. +@pre + The socket function must be called to allocate a TCP socket before passing the socket ID to the bind function. + If the socket is not bound, you do NOT have to call bind before the "connect" function. + +@see + socket + recv + send + close + +@return + The function returns ZERO for successful operations and a negative value otherwise. + The possible error values are: + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + Indicating that the operation was successful. + + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) + Indicating passing invalid arguments such as negative socket ID or NULL socket address structure. + + - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID) + Indicate socket connect failure. +\section Example + The example demonstrates a TCP application, showing how the asynchronous call to the connect function is made through the main function and how the + callback function handles the @ref SOCKET_MSG_CONNECT event. +\subsection sub1 Main Function +@code + struct sockaddr_in Serv_Addr; + SOCKET TcpClientSocket =-1; + int ret = -1 + + TcpClientSocket = socket(AF_INET,SOCK_STREAM,0); + Serv_Addr.sin_family = AF_INET; + Serv_Addr.sin_port = _htons(1234); + Serv_Addr.sin_addr.s_addr = inet_addr(SERVER); + printf("Connected to server via socket %u\n",TcpClientSocket); + + do + { + ret = connect(TcpClientSocket,(sockaddr_in*)&Serv_Addr,sizeof(Serv_Addr)); + if(ret != 0) + { + printf("Connection Error\n"); + } + else + { + printf("Connection successful.\n"); + break; + } + }while(1) +@endcode +\subsection sub2 Socket Callback +@code + if(u8Msg == SOCKET_MSG_CONNECT) + { + tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg*)pvMsg; + if(pstrConnect->s8Error == 0) + { + uint8 acBuffer[GROWL_MSG_SIZE]; + uint16 u16MsgSize; + + printf("Connect success!\n"); + + u16MsgSize = FormatMsg(u8ClientID, acBuffer); + send(sock, acBuffer, u16MsgSize, 0); + recv(pstrNotification->Socket, (void*)au8Msg,GROWL_DESCRIPTION_MAX_LENGTH, GROWL_RX_TIMEOUT); + u8Retry = GROWL_CONNECT_RETRY; + } + else + { + M2M_DBG("Connection Failed, Error: %d\n",pstrConnect->s8Error"); + close(pstrNotification->Socket); + } + } +@endcode +*/ +#ifdef ARDUINO +NMI_API sint8 connectSocket(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); +#else +NMI_API sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); +#endif +/** @} */ +/** @defgroup ReceiveFn recv + * @ingroup SocketAPI + * An asynchronous receive function, used to retrieve data from a TCP stream. + Before calling the recv function, a successful socket connection status must have been received through any of the two socket events + [SOCKET_MSG_CONNECT] or [SOCKET_MSG_ACCEPT], from the socket callback. Hence, indicating that the socket is already connected to a remote + host. + The application receives the required data in response to this asynchronous call through the reception of the event @ref SOCKET_MSG_RECV in the + socket callback. + + Receiving the SOCKET_MSG_RECV message in the callback with zero or negative buffer length indicates the following: + - SOCK_ERR_NO_ERROR : Socket connection closed + - SOCK_ERR_CONN_ABORTED : Socket connection aborted + - SOCK_ERR_TIMEOUT : Socket receive timed out + The application code is expected to close the socket through the call to the @ref close function upon the appearance of the above mentioned errors. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + + +@param [in] pvRecvBuf + Pointer to a buffer that will hold the received data. The buffer is used + in the recv callback to deliver the received data to the caller. The buffer must + be resident in memory (heap or global buffer). + +@param [in] u16BufLen + The buffer size in bytes. + +@param [in] u32Timeoutmsec + Timeout for the recv function in milli-seconds. If the value is set to ZERO, the timeout + will be set to infinite (the recv function waits forever). If the timeout period is + elapsed with no data received, the socket will get a timeout error. +@pre + - The socket function must be called to allocate a TCP socket before passing the socket ID to the recv function. + - The socket in a connected state is expected to receive data through the socket interface. + +@see + socket + connect + bind + listen + recvfrom + close + + +@return + The function returns ZERO for successful operations and a negative value otherwise. + The possible error values are: + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + Indicating that the operation was successful. + + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) + Indicating passing invalid arguments such as negative socket ID or NULL Recieve buffer. + + - [SOCK_ERR_BUFFER_FULL](@ref SOCK_ERR_BUFFER_FULL) + Indicate socket receive failure. +\section Example + The example demonstrates a code snippet for the calling of the recv function in the socket callback upon notification of the accept or connect events, and the parsing of the + received data when the SOCKET_MSG_RECV event is received. +@code + + switch(u8Msg) + { + + case SOCKET_MSG_ACCEPT: + { + tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg*)pvMsg; + + if(pstrAccept->sock >= 0) + { + recv(pstrAccept->sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT); + } + else + { + M2M_ERR("accept\n"); + } + } + break; + + + case SOCKET_MSG_RECV: + { + tstrSocketRecvMsg *pstrRx = (tstrSocketRecvMsg*)pvMsg; + + if(pstrRx->s16BufferSize > 0) + { + + recv(sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT); + } + else + { + printf("Socet recv Error: %d\n",pstrRx->s16BufferSize); + close(sock); + } + } + break; + + default: + break; + } +} +@endcode +*/ +NMI_API sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec); +/** @} */ +/** @defgroup ReceiveFromSocketFn recvfrom + * @ingroup SocketAPI + * Receives data from a UDP Socket. +* +* The asynchronous recvfrom function is used to retrieve data from a UDP socket. The socket must already be bound to +* a local port before a call to the recvfrom function is made (i.e message @ref SOCKET_MSG_BIND is received +* with successful status in the socket callback). +* +* Upon calling the recvfrom function with a successful return code, the application is expected to receive a notification +* in the socket callback whenever a message is received through the @ref SOCKET_MSG_RECVFROM event. +* +* Receiving the SOCKET_MSG_RECVFROM message in the callback with zero, indicates that the socket is closed. +* Whereby a negative buffer length indicates one of the socket error codes such as socket timeout error @SOCK_ERR_TIMEOUT: +* +* The recvfrom callback can also be used to show the IP address of the remote host that sent the frame by +* using the "strRemoteAddr" element in the @ref tstrSocketRecvMsg structure. (refer to the code example) + */ + /**@{*/ +/*! +@fn \ + NMI_API sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32TimeoutSeconds); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] pvRecvBuf + Pointer to a buffer that will hold the received data. The buffer shall be used + in the recv callback to deliver the received data to the caller. The buffer must + be resident in memory (heap or global buffer). + +@param [in] u16BufLen + The buffer size in bytes. + +@param [in] u32TimeoutSeconds + Timeout for the recv function in milli-seconds. If the value is set to ZERO, the timeout + will be set to infinite (the recv function waits forever). + +@pre + - The socket function must be called to allocate a UDP socket before passing the socket ID to the recvfrom function. + - The socket corresponding to the socket ID must be successfully bound to a local port through the call to a @ref bind function. + +@see + socket + bind + close + +@return + The function returns ZERO for successful operations and a negative value otherwise. + The possible error values are: + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + Indicating that the operation was successful. + + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) + Indicating passing invalid arguments such as negative socket ID or NULL Receive buffer. + + - [SOCK_ERR_BUFFER_FULL](@ref SOCK_ERR_BUFFER_FULL) + Indicate socket receive failure. +\section Example + The example demonstrates a code snippet for the calling of the recvfrom function in the socket callback upon notification of a successful bind event, and the parsing of the + received data when the SOCKET_MSG_RECVFROM event is received. +@code + switch(u8Msg) + { + + case SOCKET_MSG_BIND: + { + tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg; + + if(pstrBind != NULL) + { + if(pstrBind->status == 0) + { + recvfrom(sock, gau8SocketTestBuffer, TEST_BUFFER_SIZE, 0); + } + else + { + M2M_ERR("bind\n"); + } + } + } + break; + + + case SOCKET_MSG_RECVFROM: + { + tstrSocketRecvMsg *pstrRx = (tstrSocketRecvMsg*)pvMsg; + + if(pstrRx->s16BufferSize > 0) + { + //get the remote host address and port number + uint16 u16port = pstrRx->strRemoteAddr.sin_port; + uint32 strRemoteHostAddr = pstrRx->strRemoteAddr.sin_addr.s_addr; + + printf("Recieved frame with size = %d.\tHost address=%x, Port number = %d\n\n",pstrRx->s16BufferSize,strRemoteHostAddr, u16port); + + ret = recvfrom(sock,gau8SocketTestBuffer,sizeof(gau8SocketTestBuffer),TEST_RECV_TIMEOUT); + } + else + { + printf("Socet recv Error: %d\n",pstrRx->s16BufferSize); + ret = close(sock); + } + } + break; + + default: + break; + } +} +@endcode +*/ +NMI_API sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec); +/** @} */ +/** @defgroup SendFn send + * @ingroup SocketAPI +* Asynchronous sending function, used to send data on a TCP/UDP socket. + +* Called by the application code when there is outgoing data available required to be sent on a specific socket handler. +* The only difference between this function and the similar @ref sendto function, is the type of socket the data is sent on and the parameters passed in. +* @ref send function is most commonly called for sockets in a connected state. +* After the data is sent, the socket callback function registered using registerSocketCallback(), is expected to receive an event of type +* @ref SOCKET_MSG_SEND holding information containing the number of data bytes sent. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 u16Flags); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] pvSendBuffer + Pointer to a buffer holding data to be transmitted. + +@param [in] u16SendLength + The buffer size in bytes. + +@param [in] u16Flags + Not used in the current implementation. + +@pre + Sockets must be initialized using socketInit. \n + + For TCP Socket:\n + Must use a successfully connected Socket (so that the intended recipient address is known ahead of sending the data). + Hence this function is expected to be called after a successful socket connect operation(in client case or accept in the + the server case).\n + + For UDP Socket:\n + UDP sockets most commonly use @ref sendto function, where the destination address is defined. However, in-order to send outgoing data + using the @ref send function, at least one successful call must be made to the @ref sendto function a priori the consecutive calls to the @ref send function, + to ensure that the destination address is saved in the firmware. + +@see + socketInit + recv + sendto + socket + connect + accept + sendto + +@warning + u16SendLength must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. \n + Use a valid socket identifier through the a prior call to the @ref socket function. + Must use a valid buffer pointer. + Successful completion of a call to send() does not guarantee delivery of the message, + A negative return value indicates only locally-detected errors + + +@return + The function shall return @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise. +*/ +NMI_API sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 u16Flags); +/** @} */ +/** @defgroup SendToSocketFn sendto + * @ingroup SocketAPI +* Asynchronous sending function, used to send data on a UDP socket. +* Called by the application code when there is data required to be sent on a UDP socket handler. +* The application code is expected to receive data from a successful bounded socket node. +* The only difference between this function and the similar @ref send function, is the type of socket the data is received on. This function works +* only with UDP sockets. +* After the data is sent, the socket callback function registered using registerSocketCallback(), is expected to receive an event of type +* @ref SOCKET_MSG_SENDTO. +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] pvSendBuffer + Pointer to a buffer holding data to be transmitted. + A NULL value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] u16SendLength + The buffer size in bytes. It must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. + +@param [in] flags + Not used in the current implementation + +@param [in] pstrDestAddr + The destination address. + +@param [in] u8AddrLen + Destination address length in bytes. + Not used in the current implementation, only included for BSD compatibility. +@pre + Sockets must be initialized using socketInit. + +@see + socketInit + recvfrom + sendto + socket + connect + accept + send + +@warning + u16SendLength must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. \n + Use a valid socket (returned from socket ). + A valid buffer pointer must be used (not NULL). \n + Successful completion of a call to sendto() does not guarantee delivery of the message, + A negative return value indicates only locally-detected errors + +@return + The function returns @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise. +*/ +NMI_API sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen); +/** @} */ +/** @defgroup CloseSocketFn close + * @ingroup SocketAPI + * Synchronous close function, releases all the socket assigned resources. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 close(SOCKET sock); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@pre + Sockets must be initialized through the call of the socketInit function. + @ref close is called only for valid socket identifiers created through the @ref socket function. + +@warning + If @ref close is called while there are still pending messages (sent or received ) they will be discarded. + +@see + socketInit + socket + +@return + The function returned @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise. +*/ +NMI_API sint8 close(SOCKET sock); + + +/** @} */ +/** @defgroup InetAddressFn nmi_inet_addr +* @ingroup SocketAPI +* Synchronous function which returns a BSD socket compliant Internet Protocol (IPv4) socket address. +* This IPv4 address in the input string parameter could either be specified as a host name, or as a numeric string representation like n.n.n.n known as the IPv4 dotted-decimal format +* (i.e. "192.168.10.1"). +* This function is used whenever an ip address needs to be set in the proper format +* (i.e. for the @ref tstrM2MIPConfig structure). +*/ + /**@{*/ +/*! +@fn \ + NMI_API uint32 nmi_inet_addr(char *pcIpAddr); + +@param [in] pcIpAddr + A null terminated string containing the IP address in IPv4 dotted-decimal address. + +@return + Unsigned 32-bit integer representing the IP address in Network byte order + (eg. "192.168.10.1" will be expressed as 0x010AA8C0). + +*/ +NMI_API uint32 nmi_inet_addr(char *pcIpAddr); + + +/** @} */ +/** @defgroup gethostbynameFn gethostbyname + * @ingroup SocketAPI +* Asynchronous DNS resolving function. This function use DNS to resolve a domain name into the corresponding IP address. +* A call to this function will cause a DNS request to be sent and the response will be delivered to the DNS callback function registered using registerSocketCallback() + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 gethostbyname(uint8 * pcHostName); + +@param [in] pcHostName + NULL terminated string containing the domain name for the remote host. + Its size must not exceed [HOSTNAME_MAX_SIZE](@ref HOSTNAME_MAX_SIZE). + +@see + registerSocketCallback + +@warning + Successful completion of a call to gethostbyname() does not guarantee success of the DNS request, + a negative return value indicates only locally-detected errors + +@return + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) +*/ +NMI_API sint8 gethostbyname(uint8 * pcHostName); + + +/** @} */ +/** @defgroup sslEnableCertExpirationCheckFn sslEnableCertExpirationCheck + * @ingroup SocketAPI +* Configure the behavior of the SSL Library for Certificate Expiry Validation. + */ + /**@{*/ +/*! +@fn \ +NMI_API sint8 sslEnableCertExpirationCheck(tenuSslCertExpSettings enuValidationSetting); + +@param [in] enuValidationSetting + See @ref tenuSslCertExpSettings for details. + +@return + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) for successful operation and negative error code otherwise. + +@sa tenuSslCertExpSettings +*/ +NMI_API sint8 sslEnableCertExpirationCheck(tenuSslCertExpSettings enuValidationSetting); + + +/** @} */ + +/** @defgroup SetSocketOptionFn setsockopt + * @ingroup SocketAPI +*The setsockopt() function shall set the option specified by the option_name +* argument, at the protocol level specified by the level argument, to the value +* pointed to by the option_value argument for the socket specified by the socket argument. +* +*

Possible protocol level values supported are @ref SOL_SOCKET and @ref SOL_SSL_SOCKET. +* Possible options when the protocol level is @ref SOL_SOCKET :

+* +* +* +* +* +* +* +* +* +* +* +* +* +*
@ref SO_SET_UDP_SEND_CALLBACKEnable/Disable callback messages for sendto(). +* Since UDP is unreliable by default the user maybe interested (or not) in +* receiving a message of @ref SOCKET_MSG_SENDTO for each call of sendto(). +* Enabled if option value equals @ref TRUE, disabled otherwise.
@ref IP_ADD_MEMBERSHIPValid for UDP sockets. This option is used to receive frames sent to +* a multicast group. option_value shall be a pointer to Unsigned 32-bit +* integer containing the multicast IPv4 address.
@ref IP_DROP_MEMBERSHIPValid for UDP sockets. This option is used to stop receiving frames +* sent to a multicast group. option_value shall be a pointer to Unsigned +* 32-bit integer containing the multicast IPv4 address.
+*

Possible options when the protcol leve  is @ref SOL_SSL_SOCKET

+* +* +* +* +* +* +* +* +* +* +* +* +* +*
+* @ref SO_SSL_BYPASS_X509_VERIFAllow an opened SSL socket to bypass the X509 +* certificate verification process. It is highly recommended NOT to use +* this socket option in production software applications. The option is +* supported for debugging and testing purposes. The option value should be +* casted to int type and it is handled as a boolean flag.
@ref SO_SSL_SNISet the Server Name Indicator (SNI) for an SSL socket. The SNI is a +* null terminated string containing the server name associated with the +* connection. It must not exceed the size of @ref HOSTNAME_MAX_SIZE.
@ref SO_SSL_ENABLE_SESSION_CACHINGThis option allow the TLS to cache the session information for fast +* TLS session establishment in future connections using the TLS Protocol +* session resume features.
+ */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 setsockopt(SOCKET socket, uint8 u8Level, uint8 option_name, + const void *option_value, uint16 u16OptionLen); + +@param [in] sock + Socket handler. + +@param [in] level + protocol level. See description above. + +@param [in] option_name + option to be set. See description above. + +@param [in] option_value + pointer to user provided value. + +@param [in] option_len + length of the option value in bytes. +@return + The function shall return \ref SOCK_ERR_NO_ERROR for successful operation + and a negative value (indicating the error) otherwise. +@sa SOL_SOCKET, SOL_SSL_SOCKET, IP_ADD_MEMBERSHIP, IP_DROP_MEMBERSHIP +*/ +NMI_API sint8 setsockopt(SOCKET socket, uint8 u8Level, uint8 option_name, + const void *option_value, uint16 u16OptionLen); + + +/** @} */ +/** @defgroup GetSocketOptionsFn getsockopt + * @ingroup SocketAPI + * Get socket options retrieves +* This Function isn't implemented yet but this is the form that will be released later. + */ + /**@{*/ +/*! +@fn \ + sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8 * pu8OptLen); + +@brief + +@param [in] sock + Socket Identifie. +@param [in] u8Level + The protocol level of the option. +@param [in] u8OptName + The u8OptName argument specifies a single option to get. +@param [out] pvOptValue + The pvOptValue argument contains pointer to a buffer containing the option value. +@param [out] pu8OptLen + Option value buffer length. +@return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8* pu8OptLen); +/** @} */ + +/**@}*/ +/** @defgroup PingFn m2m_ping_req + * @ingroup SocketAPI + * The function sends ping request to the given IP Address. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb); + +@param [in] u32DstIP + Target Destination IP Address for the ping request. It must be represented in Network byte order. + The function nmi_inet_addr could be used to translate the dotted decimal notation IP + to its Network bytes order integer represntative. + +@param [in] u8TTL + IP TTL value for the ping request. If set to ZERO, the dfault value SHALL be used. + +@param [in] fpPingCb + Callback will be called to deliver the ping statistics. + +@see nmi_inet_addr +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb); +/**@}*/ + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* __SOCKET_H__ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/socket/include/socket_buffer.h b/feather_sensor_transmit/libraries/WiFi101/src/socket/include/socket_buffer.h new file mode 100644 index 0000000..d93a7c8 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/socket/include/socket_buffer.h @@ -0,0 +1,94 @@ +/** + * + * \file + * + * \brief BSD compatible socket interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef __SOCKET_BUFFER_H__ +#define __SOCKET_BUFFER_H__ + +#include "socket/include/socket.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define SOCKET_BUFFER_UDP_HEADER_SIZE (8) + +#if defined LIMITED_RAM_DEVICE +#define SOCKET_BUFFER_MTU (16u) +#define SOCKET_BUFFER_UDP_SIZE (SOCKET_BUFFER_UDP_HEADER_SIZE + 64u) +#define SOCKET_BUFFER_TCP_SIZE (64u) +#else +#ifdef ARDUINO +#define SOCKET_BUFFER_MTU (1446u) +#else +#define SOCKET_BUFFER_MTU (1400u) +#endif +#define SOCKET_BUFFER_UDP_SIZE (SOCKET_BUFFER_UDP_HEADER_SIZE + SOCKET_BUFFER_MTU) +#define SOCKET_BUFFER_TCP_SIZE (SOCKET_BUFFER_MTU) +#endif + +#define SOCKET_BUFFER_FLAG_CONNECTED (0x1 << 0) +#define SOCKET_BUFFER_FLAG_FULL (0x1 << 1) +#define SOCKET_BUFFER_FLAG_BIND (0x1 << 2) +#define SOCKET_BUFFER_FLAG_SPAWN (0x1 << 3) +#define SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS (16) +#define SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK (((uint32)0xFF) << SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS) +#define SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS (24) +#define SOCKET_BUFFER_FLAG_PARENT_SOCKET_MSK (((uint32)0xFF) << SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS) + +/* Parent stored as parent+1, as socket 1 ID is 0. */ + +typedef struct{ + uint8 *buffer; + uint32 *flag; + uint32 *head; + uint32 *tail; +}tstrSocketBuffer; + +void socketBufferInit(void); +void socketBufferRegister(SOCKET socket, uint32 *flag, uint32 *head, uint32 *tail, uint8 *buffer); +void socketBufferUnregister(SOCKET socket); +void socketBufferCb(SOCKET sock, uint8 u8Msg, void *pvMsg); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* __SOCKET_BUFFER_H__ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket.c b/feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket.c new file mode 100644 index 0000000..877cc1a --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket.c @@ -0,0 +1,1445 @@ +/** + * + * \file + * + * \brief BSD compatible socket interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#include + +#include "bsp/include/nm_bsp.h" +#include "socket/include/socket.h" +#include "driver/source/m2m_hif.h" +#include "socket/source/socket_internal.h" +#include "driver/include/m2m_types.h" + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +#define TLS_RECORD_HEADER_LENGTH (5) +#define ETHERNET_HEADER_OFFSET (34) +#define ETHERNET_HEADER_LENGTH (14) +#define TCP_IP_HEADER_LENGTH (40) +#define UDP_IP_HEADER_LENGTH (28) + +#define IP_PACKET_OFFSET (ETHERNET_HEADER_LENGTH + ETHERNET_HEADER_OFFSET - M2M_HIF_HDR_OFFSET) + +#define TCP_TX_PACKET_OFFSET (IP_PACKET_OFFSET + TCP_IP_HEADER_LENGTH) +#define UDP_TX_PACKET_OFFSET (IP_PACKET_OFFSET + UDP_IP_HEADER_LENGTH) +#define SSL_TX_PACKET_OFFSET (TCP_TX_PACKET_OFFSET + TLS_RECORD_HEADER_LENGTH) + +#define SOCKET_REQUEST(reqID, reqArgs, reqSize, reqPayload, reqPayloadSize, reqPayloadOffset) \ + hif_send(M2M_REQ_GROUP_IP, reqID, reqArgs, reqSize, reqPayload, reqPayloadSize, reqPayloadOffset) + + +#define SSL_FLAGS_ACTIVE NBIT0 +#define SSL_FLAGS_BYPASS_X509 NBIT1 +#define SSL_FLAGS_2_RESERVD NBIT2 +#define SSL_FLAGS_3_RESERVD NBIT3 +#define SSL_FLAGS_CACHE_SESSION NBIT4 +#define SSL_FLAGS_NO_TX_COPY NBIT5 +#define SSL_FLAGS_CHECK_SNI NBIT6 + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +PRIVATE DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +/*! +* @brief +*/ +typedef struct{ + SOCKET sock; + uint8 u8Dummy; + uint16 u16SessionID; +}tstrCloseCmd; + + +/*! +* @brief +*/ +typedef struct{ + uint8 *pu8UserBuffer; + uint16 u16UserBufferSize; + uint16 u16SessionID; + uint16 u16DataOffset; + uint8 bIsUsed; + uint8 u8SSLFlags; + uint8 bIsRecvPending; +}tstrSocket; + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +GLOBALS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +volatile sint8 gsockerrno; +volatile tstrSocket gastrSockets[MAX_SOCKET]; +volatile uint8 gu8OpCode; +volatile uint16 gu16BufferSize; +volatile uint16 gu16SessionID = 0; + +volatile tpfAppSocketCb gpfAppSocketCb; +volatile tpfAppResolveCb gpfAppResolveCb; +volatile uint8 gbSocketInit = 0; +volatile tpfPingCb gfpPingCb; + +/********************************************************************* +Function + Socket_ReadSocketData + +Description + Callback function used by the NMC1500 driver to deliver messages + for socket layer. + +Return + None. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 17 July 2012 +*********************************************************************/ +#ifdef ARDUINO +extern uint8 hif_small_xfer; +static uint32 u32Address; +static SOCKET sock_xfer; +static uint8 type_xfer; +static tstrSocketRecvMsg msg_xfer; +#endif +NMI_API void Socket_ReadSocketData(SOCKET sock, tstrSocketRecvMsg *pstrRecv,uint8 u8SocketMsg, + uint32 u32StartAddress,uint16 u16ReadCount) +{ + if((u16ReadCount > 0) && (gastrSockets[sock].pu8UserBuffer != NULL) && (gastrSockets[sock].u16UserBufferSize > 0) && (gastrSockets[sock].bIsUsed == 1)) + { +#ifdef ARDUINO + u32Address = u32StartAddress; +#else + uint32 u32Address = u32StartAddress; +#endif + uint16 u16Read; + sint16 s16Diff; + uint8 u8SetRxDone; +#ifdef ARDUINO + m2m_memcpy((uint8 *)&msg_xfer, (uint8 *)pstrRecv, sizeof(tstrSocketRecvMsg)); + msg_xfer.u16RemainingSize = u16ReadCount; +#else + pstrRecv->u16RemainingSize = u16ReadCount; +#endif + do + { + u8SetRxDone = 1; + u16Read = u16ReadCount; + s16Diff = u16Read - gastrSockets[sock].u16UserBufferSize; + if(s16Diff > 0) + { + u8SetRxDone = 0; + u16Read = gastrSockets[sock].u16UserBufferSize; +#ifdef ARDUINO + hif_small_xfer = 1; + sock_xfer = sock; + type_xfer = u8SocketMsg; +#endif + } + + if(hif_receive(u32Address, gastrSockets[sock].pu8UserBuffer, u16Read, u8SetRxDone) == M2M_SUCCESS) + { +#ifdef ARDUINO + msg_xfer.pu8Buffer = gastrSockets[sock].pu8UserBuffer; + msg_xfer.s16BufferSize = u16Read; + msg_xfer.u16RemainingSize -= u16Read; + + if (gpfAppSocketCb) + gpfAppSocketCb(sock,u8SocketMsg, &msg_xfer); + + u32Address += u16Read; +#else + pstrRecv->pu8Buffer = gastrSockets[sock].pu8UserBuffer; + pstrRecv->s16BufferSize = u16Read; + pstrRecv->u16RemainingSize -= u16Read; + + if (gpfAppSocketCb) + gpfAppSocketCb(sock,u8SocketMsg, pstrRecv); + + u16ReadCount -= u16Read; + u32Address += u16Read; + + if((!gastrSockets[sock].bIsUsed) && (u16ReadCount)) + { + M2M_DBG("Application Closed Socket While Rx Is not Complete\n"); + if(hif_receive(0, NULL, 0, 1) == M2M_SUCCESS) + M2M_DBG("hif_receive Success\n"); + else + M2M_DBG("hif_receive Fail\n"); + break; + } +#endif + } + else + { + M2M_INFO("(ERRR)Current <%d>\n", u16ReadCount); + break; + } +#ifdef ARDUINO + }while(0); +#else + }while(u16ReadCount != 0); +#endif + } +} +#ifdef ARDUINO +NMI_API void Socket_ReadSocketData_Small(void) +{ + if((msg_xfer.u16RemainingSize > 0) && (gastrSockets[sock_xfer].pu8UserBuffer != NULL) && (gastrSockets[sock_xfer].u16UserBufferSize > 0) && (gastrSockets[sock_xfer].bIsUsed == 1)) + { + uint16 u16Read; + sint16 s16Diff; + uint8 u8SetRxDone; + + //do + //{ + u8SetRxDone = 1; + u16Read = msg_xfer.u16RemainingSize; + s16Diff = u16Read - gastrSockets[sock_xfer].u16UserBufferSize; + if(s16Diff > 0) + { + /*Has to be subsequent transfer*/ + hif_small_xfer = 2; + u8SetRxDone = 0; + u16Read = gastrSockets[sock_xfer].u16UserBufferSize; + } + else + { + /*Last xfer, needed for UDP*/ + hif_small_xfer = 3; + } + if(hif_receive(u32Address, gastrSockets[sock_xfer].pu8UserBuffer, u16Read, u8SetRxDone) == M2M_SUCCESS) + { + msg_xfer.pu8Buffer = gastrSockets[sock_xfer].pu8UserBuffer; + msg_xfer.s16BufferSize = u16Read; + msg_xfer.u16RemainingSize -= u16Read; + + if (gpfAppSocketCb) + gpfAppSocketCb(sock_xfer,type_xfer, &msg_xfer); + + u32Address += u16Read; + } + else + { + M2M_INFO("(ERRR)Current <%d>\n", u16Read); + //break; + } + + if (hif_small_xfer == 3) + { + hif_small_xfer = 0; + hif_chip_sleep(); + } + + //}while(u16ReadCount != 0); + } +} +#endif +/********************************************************************* +Function + m2m_ip_cb + +Description + Callback function used by the NMC1000 driver to deliver messages + for socket layer. + +Return + None. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 17 July 2012 +*********************************************************************/ +static void m2m_ip_cb(uint8 u8OpCode, uint16 u16BufferSize,uint32 u32Address) +{ + if((u8OpCode == SOCKET_CMD_BIND) || (u8OpCode == SOCKET_CMD_SSL_BIND)) + { + tstrBindReply strBindReply; + tstrSocketBindMsg strBind; + + if(hif_receive(u32Address, (uint8*)&strBindReply, sizeof(tstrBindReply), 0) == M2M_SUCCESS) + { + strBind.status = strBindReply.s8Status; + if(gpfAppSocketCb) + gpfAppSocketCb(strBindReply.sock,SOCKET_MSG_BIND,&strBind); + } + } + else if(u8OpCode == SOCKET_CMD_LISTEN) + { + tstrListenReply strListenReply; + tstrSocketListenMsg strListen; + if(hif_receive(u32Address, (uint8*)&strListenReply, sizeof(tstrListenReply), 0) == M2M_SUCCESS) + { + strListen.status = strListenReply.s8Status; + if(gpfAppSocketCb) + gpfAppSocketCb(strListenReply.sock,SOCKET_MSG_LISTEN, &strListen); + } + } + else if(u8OpCode == SOCKET_CMD_ACCEPT) + { + tstrAcceptReply strAcceptReply; + tstrSocketAcceptMsg strAccept; + if(hif_receive(u32Address, (uint8*)&strAcceptReply, sizeof(tstrAcceptReply), 0) == M2M_SUCCESS) + { + if(strAcceptReply.sConnectedSock >= 0) + { + gastrSockets[strAcceptReply.sConnectedSock].u8SSLFlags = gastrSockets[strAcceptReply.sListenSock].u8SSLFlags; + gastrSockets[strAcceptReply.sConnectedSock].bIsUsed = 1; + gastrSockets[strAcceptReply.sConnectedSock].u16DataOffset = strAcceptReply.u16AppDataOffset - M2M_HIF_HDR_OFFSET; + + /* The session ID is used to distinguish different socket connections + by comparing the assigned session ID to the one reported by the firmware*/ + ++gu16SessionID; + if(gu16SessionID == 0) + ++gu16SessionID; + + gastrSockets[strAcceptReply.sConnectedSock].u16SessionID = gu16SessionID; + M2M_DBG("Socket %d session ID = %d\r\n",strAcceptReply.sConnectedSock , gu16SessionID ); + } + strAccept.sock = strAcceptReply.sConnectedSock; + strAccept.strAddr.sin_family = AF_INET; + strAccept.strAddr.sin_port = strAcceptReply.strAddr.u16Port; + strAccept.strAddr.sin_addr.s_addr = strAcceptReply.strAddr.u32IPAddr; + if(gpfAppSocketCb) + gpfAppSocketCb(strAcceptReply.sListenSock, SOCKET_MSG_ACCEPT, &strAccept); + } + } + else if((u8OpCode == SOCKET_CMD_CONNECT) || (u8OpCode == SOCKET_CMD_SSL_CONNECT)) + { + tstrConnectReply strConnectReply; + tstrSocketConnectMsg strConnMsg; + if(hif_receive(u32Address, (uint8*)&strConnectReply, sizeof(tstrConnectReply), 0) == M2M_SUCCESS) + { + strConnMsg.sock = strConnectReply.sock; + strConnMsg.s8Error = strConnectReply.s8Error; + if(strConnectReply.s8Error == SOCK_ERR_NO_ERROR) + { + gastrSockets[strConnectReply.sock].u16DataOffset = strConnectReply.u16AppDataOffset - M2M_HIF_HDR_OFFSET; + } + if(gpfAppSocketCb) + gpfAppSocketCb(strConnectReply.sock,SOCKET_MSG_CONNECT, &strConnMsg); + } + } + else if(u8OpCode == SOCKET_CMD_DNS_RESOLVE) + { + tstrDnsReply strDnsReply; + if(hif_receive(u32Address, (uint8*)&strDnsReply, sizeof(tstrDnsReply), 0) == M2M_SUCCESS) + { + if(gpfAppResolveCb) + gpfAppResolveCb((uint8*)strDnsReply.acHostName, strDnsReply.u32HostIP); + } + } + else if((u8OpCode == SOCKET_CMD_RECV) || (u8OpCode == SOCKET_CMD_RECVFROM) || (u8OpCode == SOCKET_CMD_SSL_RECV)) + { + SOCKET sock; + sint16 s16RecvStatus; + tstrRecvReply strRecvReply; + uint16 u16ReadSize; + tstrSocketRecvMsg strRecvMsg; + uint8 u8CallbackMsgID = SOCKET_MSG_RECV; + uint16 u16DataOffset; + + if(u8OpCode == SOCKET_CMD_RECVFROM) + u8CallbackMsgID = SOCKET_MSG_RECVFROM; + + /* Read RECV REPLY data structure. + */ + u16ReadSize = sizeof(tstrRecvReply); + if(hif_receive(u32Address, (uint8*)&strRecvReply, u16ReadSize, 0) == M2M_SUCCESS) + { + uint16 u16SessionID = 0; + + sock = strRecvReply.sock; + u16SessionID = strRecvReply.u16SessionID; + M2M_DBG("recv callback session ID = %d\r\n",u16SessionID); + + /* Reset the Socket RX Pending Flag. + */ + gastrSockets[sock].bIsRecvPending = 0; + + s16RecvStatus = NM_BSP_B_L_16(strRecvReply.s16RecvStatus); + u16DataOffset = NM_BSP_B_L_16(strRecvReply.u16DataOffset); + strRecvMsg.strRemoteAddr.sin_port = strRecvReply.strRemoteAddr.u16Port; + strRecvMsg.strRemoteAddr.sin_addr.s_addr = strRecvReply.strRemoteAddr.u32IPAddr; + + if(u16SessionID == gastrSockets[sock].u16SessionID) + { +#ifdef ARDUINO + if((s16RecvStatus > 0) && (s16RecvStatus < (sint32)u16BufferSize)) +#else + if((s16RecvStatus > 0) && (s16RecvStatus < u16BufferSize)) +#endif + { + /* Skip incoming bytes until reaching the Start of Application Data. + */ + u32Address += u16DataOffset; + + /* Read the Application data and deliver it to the application callback in + the given application buffer. If the buffer is smaller than the received data, + the data is passed to the application in chunks according to its buffer size. + */ + u16ReadSize = (uint16)s16RecvStatus; + Socket_ReadSocketData(sock, &strRecvMsg, u8CallbackMsgID, u32Address, u16ReadSize); + } + else + { + strRecvMsg.s16BufferSize = s16RecvStatus; + strRecvMsg.pu8Buffer = NULL; + if(gpfAppSocketCb) + gpfAppSocketCb(sock,u8CallbackMsgID, &strRecvMsg); + } + } + else + { + M2M_DBG("Discard recv callback %d %d \r\n",u16SessionID , gastrSockets[sock].u16SessionID); + if(u16ReadSize < u16BufferSize) + { + if(hif_receive(0, NULL, 0, 1) == M2M_SUCCESS) + M2M_DBG("hif_receive Success\n"); + else +#ifdef ARDUINO + { +#endif + M2M_DBG("hif_receive Fail\n"); +#ifdef ARDUINO + } +#endif + } + } + } + } + else if((u8OpCode == SOCKET_CMD_SEND) || (u8OpCode == SOCKET_CMD_SENDTO) || (u8OpCode == SOCKET_CMD_SSL_SEND)) + { + SOCKET sock; + sint16 s16Rcvd; + tstrSendReply strReply; + uint8 u8CallbackMsgID = SOCKET_MSG_SEND; + + if(u8OpCode == SOCKET_CMD_SENDTO) + u8CallbackMsgID = SOCKET_MSG_SENDTO; + + if(hif_receive(u32Address, (uint8*)&strReply, sizeof(tstrSendReply), 0) == M2M_SUCCESS) + { + uint16 u16SessionID = 0; + + sock = strReply.sock; + u16SessionID = strReply.u16SessionID; + M2M_DBG("send callback session ID = %d\r\n",u16SessionID); + + s16Rcvd = NM_BSP_B_L_16(strReply.s16SentBytes); + + if(u16SessionID == gastrSockets[sock].u16SessionID) + { + if(gpfAppSocketCb) + gpfAppSocketCb(sock,u8CallbackMsgID, &s16Rcvd); + } + else + { + M2M_DBG("Discard send callback %d %d \r\n",u16SessionID , gastrSockets[sock].u16SessionID); + } + } + } + else if(u8OpCode == SOCKET_CMD_PING) + { + tstrPingReply strPingReply; + if(hif_receive(u32Address, (uint8*)&strPingReply, sizeof(tstrPingReply), 1) == M2M_SUCCESS) + { + gfpPingCb = (void (*)(uint32 , uint32 , uint8))(uintptr_t)strPingReply.u32CmdPrivate; + if(gfpPingCb != NULL) + { + gfpPingCb(strPingReply.u32IPAddr, strPingReply.u32RTT, strPingReply.u8ErrorCode); + } + } + } +} +/********************************************************************* +Function + socketInit + +Description + +Return + None. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +void socketInit(void) +{ + if(gbSocketInit == 0) + { + m2m_memset((uint8*)gastrSockets, 0, MAX_SOCKET * sizeof(tstrSocket)); + hif_register_cb(M2M_REQ_GROUP_IP,m2m_ip_cb); + gbSocketInit = 1; + gu16SessionID = 0; + } +} +/********************************************************************* +Function + socketDeinit + +Description + +Return + None. + +Author + Samer Sarhan + +Version + 1.0 + +Date + 27 Feb 2015 +*********************************************************************/ +void socketDeinit(void) +{ + m2m_memset((uint8*)gastrSockets, 0, MAX_SOCKET * sizeof(tstrSocket)); + hif_register_cb(M2M_REQ_GROUP_IP, NULL); + gpfAppSocketCb = NULL; + gpfAppResolveCb = NULL; + gbSocketInit = 0; +} +/********************************************************************* +Function + registerSocketCallback + +Description + +Return + None. + +Author + Ahmed Ezzat + +Versio + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +void registerSocketCallback(tpfAppSocketCb pfAppSocketCb, tpfAppResolveCb pfAppResolveCb) +{ + gpfAppSocketCb = pfAppSocketCb; + gpfAppResolveCb = pfAppResolveCb; +} + +/********************************************************************* +Function + socket + +Description + Creates a socket. + +Return + - Negative value for error. + - ZERO or positive value as a socket ID if successful. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags) +{ + SOCKET sock = -1; + uint8 u8SockID; + uint8 u8Count; + volatile tstrSocket *pstrSock; + static volatile uint8 u8NextTcpSock = 0; + static volatile uint8 u8NextUdpSock = 0; + + /* The only supported family is the AF_INET for UDP and TCP transport layer protocols. */ + if(u16Domain == AF_INET) + { + if(u8Type == SOCK_STREAM) + { + for(u8Count = 0; u8Count < TCP_SOCK_MAX; u8Count ++) + { + u8SockID = u8NextTcpSock; + pstrSock = &gastrSockets[u8NextTcpSock]; + u8NextTcpSock = (u8NextTcpSock + 1) % TCP_SOCK_MAX; + if(!pstrSock->bIsUsed) + { + sock = (SOCKET)u8SockID; + break; + } + } + } + else if(u8Type == SOCK_DGRAM) + { + volatile tstrSocket *pastrUDPSockets = &gastrSockets[TCP_SOCK_MAX]; + for(u8Count = 0; u8Count < UDP_SOCK_MAX; u8Count ++) + { + u8SockID = u8NextUdpSock; + pstrSock = &pastrUDPSockets[u8NextUdpSock]; + u8NextUdpSock = (u8NextUdpSock + 1) % UDP_SOCK_MAX; + if(!pstrSock->bIsUsed) + { + sock = (SOCKET)(u8SockID + TCP_SOCK_MAX); + break; + } + } + } + + if(sock >= 0) + { + m2m_memset((uint8*)pstrSock, 0, sizeof(tstrSocket)); + pstrSock->bIsUsed = 1; + + /* The session ID is used to distinguish different socket connections + by comparing the assigned session ID to the one reported by the firmware*/ + ++gu16SessionID; + if(gu16SessionID == 0) + ++gu16SessionID; + + pstrSock->u16SessionID = gu16SessionID; + M2M_INFO("Socket %d session ID = %d\r\n",sock, gu16SessionID ); + + if(u8Flags & SOCKET_FLAGS_SSL) + { + tstrSSLSocketCreateCmd strSSLCreate; + strSSLCreate.sslSock = sock; + pstrSock->u8SSLFlags = SSL_FLAGS_ACTIVE | SSL_FLAGS_NO_TX_COPY; + SOCKET_REQUEST(SOCKET_CMD_SSL_CREATE, (uint8*)&strSSLCreate, sizeof(tstrSSLSocketCreateCmd), 0, 0, 0); + } + } + } + return sock; +} +/********************************************************************* +Function + bind + +Description + Request to bind a socket on a local address. + +Return + + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 5 June 2012 +*********************************************************************/ +sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen) +{ + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + if((pstrAddr != NULL) && (sock >= 0) && (gastrSockets[sock].bIsUsed == 1) && (u8AddrLen != 0)) + { + tstrBindCmd strBind; + uint8 u8CMD = SOCKET_CMD_BIND; + if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) + { + u8CMD = SOCKET_CMD_SSL_BIND; + } + + /* Build the bind request. */ + strBind.sock = sock; + m2m_memcpy((uint8 *)&strBind.strAddr, (uint8 *)pstrAddr, sizeof(tstrSockAddr)); + strBind.u16SessionID = gastrSockets[sock].u16SessionID; + + /* Send the request. */ + s8Ret = SOCKET_REQUEST(u8CMD, (uint8*)&strBind,sizeof(tstrBindCmd) , NULL , 0, 0); + if(s8Ret != SOCK_ERR_NO_ERROR) + { + s8Ret = SOCK_ERR_INVALID; + } + } + return s8Ret; +} +/********************************************************************* +Function + listen + +Description + + +Return + + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 5 June 2012 +*********************************************************************/ +sint8 listen(SOCKET sock, uint8 backlog) +{ + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + + if(sock >= 0 && (gastrSockets[sock].bIsUsed == 1)) + { + tstrListenCmd strListen; + + strListen.sock = sock; + strListen.u8BackLog = backlog; + strListen.u16SessionID = gastrSockets[sock].u16SessionID; + + s8Ret = SOCKET_REQUEST(SOCKET_CMD_LISTEN, (uint8*)&strListen, sizeof(tstrListenCmd), NULL, 0, 0); + if(s8Ret != SOCK_ERR_NO_ERROR) + { + s8Ret = SOCK_ERR_INVALID; + } + } + return s8Ret; +} +/********************************************************************* +Function + accept + +Description + +Return + + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 5 June 2012 +*********************************************************************/ +sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)addr; + (void)addrlen; +#endif + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + + if(sock >= 0 && (gastrSockets[sock].bIsUsed == 1) ) + { + s8Ret = SOCK_ERR_NO_ERROR; + } + return s8Ret; +} +/********************************************************************* +Function + connect + +Description + Connect to a remote TCP Server. + +Return + + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 5 June 2012 +*********************************************************************/ +#ifdef ARDUINO +sint8 connectSocket(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen) +#else +sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen) +#endif +{ + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + if((sock >= 0) && (pstrAddr != NULL) && (gastrSockets[sock].bIsUsed == 1) && (u8AddrLen != 0)) + { + tstrConnectCmd strConnect; + uint8 u8Cmd = SOCKET_CMD_CONNECT; + if((gastrSockets[sock].u8SSLFlags) & SSL_FLAGS_ACTIVE) + { + u8Cmd = SOCKET_CMD_SSL_CONNECT; + strConnect.u8SslFlags = gastrSockets[sock].u8SSLFlags; + } + strConnect.sock = sock; + m2m_memcpy((uint8 *)&strConnect.strAddr, (uint8 *)pstrAddr, sizeof(tstrSockAddr)); + + strConnect.u16SessionID = gastrSockets[sock].u16SessionID; + s8Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strConnect,sizeof(tstrConnectCmd), NULL, 0, 0); + if(s8Ret != SOCK_ERR_NO_ERROR) + { + s8Ret = SOCK_ERR_INVALID; + } + } + return s8Ret; +} +/********************************************************************* +Function + send + +Description + +Return + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 5 June 2012 +*********************************************************************/ +sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags) +{ +#ifdef ARDUINO + (void)flags; // Silence "unused" warning +#endif + sint16 s16Ret = SOCK_ERR_INVALID_ARG; + + if((sock >= 0) && (pvSendBuffer != NULL) && (u16SendLength <= SOCKET_BUFFER_MAX_LENGTH) && (gastrSockets[sock].bIsUsed == 1)) + { + uint16 u16DataOffset; + tstrSendCmd strSend; + uint8 u8Cmd; + + u8Cmd = SOCKET_CMD_SEND; + u16DataOffset = TCP_TX_PACKET_OFFSET; + + strSend.sock = sock; + strSend.u16DataSize = NM_BSP_B_L_16(u16SendLength); + strSend.u16SessionID = gastrSockets[sock].u16SessionID; + + if(sock >= TCP_SOCK_MAX) + { + u16DataOffset = UDP_TX_PACKET_OFFSET; + } + if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) + { + u8Cmd = SOCKET_CMD_SSL_SEND; + u16DataOffset = gastrSockets[sock].u16DataOffset; +#ifdef ARDUINO + extern uint32 nmdrv_firm_ver; + + if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 4, 0)) { + // firmware 19.3.0 and older only works with this specific offset + u16DataOffset = SSL_TX_PACKET_OFFSET; + } +#endif + } + + s16Ret = SOCKET_REQUEST(u8Cmd|M2M_REQ_DATA_PKT, (uint8*)&strSend, sizeof(tstrSendCmd), pvSendBuffer, u16SendLength, u16DataOffset); + if(s16Ret != SOCK_ERR_NO_ERROR) + { + s16Ret = SOCK_ERR_BUFFER_FULL; + } + } + return s16Ret; +} +/********************************************************************* +Function + sendto + +Description + +Return + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)flags; + (void)u8AddrLen; +#endif + sint16 s16Ret = SOCK_ERR_INVALID_ARG; + + if((sock >= 0) && (pvSendBuffer != NULL) && (u16SendLength <= SOCKET_BUFFER_MAX_LENGTH) && (gastrSockets[sock].bIsUsed == 1)) + { + if(gastrSockets[sock].bIsUsed) + { + tstrSendCmd strSendTo; + + m2m_memset((uint8*)&strSendTo, 0, sizeof(tstrSendCmd)); + + strSendTo.sock = sock; + strSendTo.u16DataSize = NM_BSP_B_L_16(u16SendLength); + strSendTo.u16SessionID = gastrSockets[sock].u16SessionID; + + if(pstrDestAddr != NULL) + { + struct sockaddr_in *pstrAddr; + pstrAddr = (void*)pstrDestAddr; + + strSendTo.strAddr.u16Family = pstrAddr->sin_family; + strSendTo.strAddr.u16Port = pstrAddr->sin_port; + strSendTo.strAddr.u32IPAddr = pstrAddr->sin_addr.s_addr; + } + s16Ret = SOCKET_REQUEST(SOCKET_CMD_SENDTO|M2M_REQ_DATA_PKT, (uint8*)&strSendTo, sizeof(tstrSendCmd), + pvSendBuffer, u16SendLength, UDP_TX_PACKET_OFFSET); + + if(s16Ret != SOCK_ERR_NO_ERROR) + { + s16Ret = SOCK_ERR_BUFFER_FULL; + } + } + } + return s16Ret; +} +/********************************************************************* +Function + recv + +Description + +Return + + +Author + Ahmed Ezzat + +Version + 1.0 + 2.0 9 April 2013 --> Add timeout for recv operation. + +Date + 5 June 2012 +*********************************************************************/ +sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec) +{ + sint16 s16Ret = SOCK_ERR_INVALID_ARG; + + if((sock >= 0) && (pvRecvBuf != NULL) && (u16BufLen != 0) && (gastrSockets[sock].bIsUsed == 1)) + { + s16Ret = SOCK_ERR_NO_ERROR; + gastrSockets[sock].pu8UserBuffer = (uint8*)pvRecvBuf; + gastrSockets[sock].u16UserBufferSize = u16BufLen; + + if(!gastrSockets[sock].bIsRecvPending) + { + tstrRecvCmd strRecv; + uint8 u8Cmd = SOCKET_CMD_RECV; + + gastrSockets[sock].bIsRecvPending = 1; + if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) + { + u8Cmd = SOCKET_CMD_SSL_RECV; + } + + /* Check the timeout value. */ + if(u32Timeoutmsec == 0) + strRecv.u32Timeoutmsec = 0xFFFFFFFF; + else + strRecv.u32Timeoutmsec = NM_BSP_B_L_32(u32Timeoutmsec); + strRecv.sock = sock; + strRecv.u16SessionID = gastrSockets[sock].u16SessionID; + + s16Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strRecv, sizeof(tstrRecvCmd), NULL , 0, 0); + if(s16Ret != SOCK_ERR_NO_ERROR) + { + s16Ret = SOCK_ERR_BUFFER_FULL; + } + } + } + return s16Ret; +} +/********************************************************************* +Function + close + +Description + +Return + None. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +sint8 close(SOCKET sock) +{ + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + M2M_INFO("Sock to delete <%d>\n", sock); + if(sock >= 0 && (gastrSockets[sock].bIsUsed == 1)) + { + uint8 u8Cmd = SOCKET_CMD_CLOSE; + tstrCloseCmd strclose; + strclose.sock = sock; + strclose.u16SessionID = gastrSockets[sock].u16SessionID; + + gastrSockets[sock].bIsUsed = 0; + gastrSockets[sock].u16SessionID =0; + + if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) + { + u8Cmd = SOCKET_CMD_SSL_CLOSE; + } + s8Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strclose, sizeof(tstrCloseCmd), NULL,0, 0); + if(s8Ret != SOCK_ERR_NO_ERROR) + { + s8Ret = SOCK_ERR_INVALID; + } + m2m_memset((uint8*)&gastrSockets[sock], 0, sizeof(tstrSocket)); + } + return s8Ret; +} +/********************************************************************* +Function + recvfrom + +Description + +Return + + +Author + Ahmed Ezzat + +Version + 1.0 + 2.0 9 April 2013 --> Add timeout for recv operation. + +Date + 5 June 2012 +*********************************************************************/ +sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec) +{ + sint16 s16Ret = SOCK_ERR_NO_ERROR; + if((sock >= 0) && (pvRecvBuf != NULL) && (u16BufLen != 0) && (gastrSockets[sock].bIsUsed == 1)) + { + if(gastrSockets[sock].bIsUsed) + { + s16Ret = SOCK_ERR_NO_ERROR; + gastrSockets[sock].pu8UserBuffer = (uint8*)pvRecvBuf; + gastrSockets[sock].u16UserBufferSize = u16BufLen; + + if(!gastrSockets[sock].bIsRecvPending) + { + tstrRecvCmd strRecv; + + gastrSockets[sock].bIsRecvPending = 1; + + /* Check the timeout value. */ + if(u32Timeoutmsec == 0) + strRecv.u32Timeoutmsec = 0xFFFFFFFF; + else + strRecv.u32Timeoutmsec = NM_BSP_B_L_32(u32Timeoutmsec); + strRecv.sock = sock; + strRecv.u16SessionID = gastrSockets[sock].u16SessionID; + + s16Ret = SOCKET_REQUEST(SOCKET_CMD_RECVFROM, (uint8*)&strRecv, sizeof(tstrRecvCmd), NULL , 0, 0); + if(s16Ret != SOCK_ERR_NO_ERROR) + { + s16Ret = SOCK_ERR_BUFFER_FULL; + } + } + } + } + else + { + s16Ret = SOCK_ERR_INVALID_ARG; + } + return s16Ret; +} +/********************************************************************* +Function + nmi_inet_addr + +Description + +Return + Unsigned 32-bit integer representing the IP address in Network + byte order. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +uint32 nmi_inet_addr(char *pcIpAddr) +{ + uint8 tmp; + uint32 u32IP = 0; + uint8 au8IP[4]; + uint8 c; + uint8 i, j; + + tmp = 0; + + for(i = 0; i < 4; ++i) + { + j = 0; + do + { + c = *pcIpAddr; + ++j; + if(j > 4) + { + return 0; + } + if(c == '.' || c == 0) + { + au8IP[i] = tmp; + tmp = 0; + } + else if(c >= '0' && c <= '9') + { + tmp = (tmp * 10) + (c - '0'); + } + else + { + return 0; + } + ++pcIpAddr; + } while(c != '.' && c != 0); + } + m2m_memcpy((uint8*)&u32IP, au8IP, 4); + return u32IP; +} +/********************************************************************* +Function + gethostbyname + +Description + +Return + None. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +sint8 gethostbyname(uint8 * pcHostName) +{ + sint8 s8Err = SOCK_ERR_INVALID_ARG; + uint8 u8HostNameSize = (uint8)m2m_strlen(pcHostName); + if(u8HostNameSize <= HOSTNAME_MAX_SIZE) + { + s8Err = SOCKET_REQUEST(SOCKET_CMD_DNS_RESOLVE, (uint8*)pcHostName, u8HostNameSize + 1, NULL,0, 0); + } + return s8Err; +} +/********************************************************************* +Function + setsockopt + +Description + +Return + None. + +Author + Abdelrahman Diab + +Version + 1.0 + +Date + 9 September 2014 +*********************************************************************/ +static sint8 sslSetSockOpt(SOCKET sock, uint8 u8Opt, const void *pvOptVal, uint16 u16OptLen) +{ + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + if(sock < TCP_SOCK_MAX) + { + if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) + { + if(u8Opt == SO_SSL_BYPASS_X509_VERIF) + { + int optVal = *((int*)pvOptVal); + if(optVal) + { + gastrSockets[sock].u8SSLFlags |= SSL_FLAGS_BYPASS_X509; + } + else + { + gastrSockets[sock].u8SSLFlags &= ~SSL_FLAGS_BYPASS_X509; + } + s8Ret = SOCK_ERR_NO_ERROR; + } + else if(u8Opt == SO_SSL_ENABLE_SESSION_CACHING) + { + int optVal = *((int*)pvOptVal); + if(optVal) + { + gastrSockets[sock].u8SSLFlags |= SSL_FLAGS_CACHE_SESSION; + } + else + { + gastrSockets[sock].u8SSLFlags &= ~SSL_FLAGS_CACHE_SESSION; + } + s8Ret = SOCK_ERR_NO_ERROR; + } + else if(u8Opt == SO_SSL_ENABLE_SNI_VALIDATION) + { + int optVal = *((int*)pvOptVal); + if(optVal) + { + gastrSockets[sock].u8SSLFlags |= SSL_FLAGS_CHECK_SNI; + } + else + { + gastrSockets[sock].u8SSLFlags &= ~SSL_FLAGS_CHECK_SNI; + } + s8Ret = SOCK_ERR_NO_ERROR; + } + else if(u8Opt == SO_SSL_SNI) + { + if(u16OptLen < HOSTNAME_MAX_SIZE) + { + uint8 *pu8SNI = (uint8*)pvOptVal; + tstrSSLSetSockOptCmd strCmd; + + strCmd.sock = sock; + strCmd.u16SessionID = gastrSockets[sock].u16SessionID; + strCmd.u8Option = u8Opt; + strCmd.u32OptLen = u16OptLen; + m2m_memcpy(strCmd.au8OptVal, pu8SNI, HOSTNAME_MAX_SIZE); + + if(SOCKET_REQUEST(SOCKET_CMD_SSL_SET_SOCK_OPT, (uint8*)&strCmd, sizeof(tstrSSLSetSockOptCmd), + 0, 0, 0) == M2M_ERR_MEM_ALLOC) + { + s8Ret = SOCKET_REQUEST(SOCKET_CMD_SSL_SET_SOCK_OPT | M2M_REQ_DATA_PKT, + (uint8*)&strCmd, sizeof(tstrSSLSetSockOptCmd), 0, 0, 0); + } + s8Ret = SOCK_ERR_NO_ERROR; + } + else + { + M2M_ERR("SNI Exceeds Max Length\n"); + } + } + else + { + M2M_ERR("Unknown SSL Socket Option %d\n",u8Opt); + } + } + else + { + M2M_ERR("Not SSL Socket\n"); + } + } + return s8Ret; +} +/********************************************************************* +Function + setsockopt + +Description + +Return + None. + +Author + Abdelrahman Diab + +Version + 1.0 + +Date + 9 September 2014 +*********************************************************************/ +sint8 setsockopt(SOCKET sock, uint8 u8Level, uint8 option_name, + const void *option_value, uint16 u16OptionLen) +{ + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + if((sock >= 0) && (option_value != NULL) && (gastrSockets[sock].bIsUsed == 1)) + { + if(u8Level == SOL_SSL_SOCKET) + { + s8Ret = sslSetSockOpt(sock, option_name, option_value, u16OptionLen); + } + else + { + uint8 u8Cmd = SOCKET_CMD_SET_SOCKET_OPTION; + tstrSetSocketOptCmd strSetSockOpt; + strSetSockOpt.u8Option=option_name; + strSetSockOpt.sock = sock; + strSetSockOpt.u32OptionValue = *(uint32*)option_value; + strSetSockOpt.u16SessionID = gastrSockets[sock].u16SessionID; + + s8Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strSetSockOpt, sizeof(tstrSetSocketOptCmd), NULL,0, 0); + if(s8Ret != SOCK_ERR_NO_ERROR) + { + s8Ret = SOCK_ERR_INVALID; + } + } + } + return s8Ret; +} +/********************************************************************* +Function + getsockopt + +Description + +Return + None. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 24 August 2014 +*********************************************************************/ +sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8* pu8OptLen) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)sock; + (void)u8Level; + (void)u8OptName; + (void)pvOptValue; + (void)pu8OptLen; +#endif + /* TBD */ + return M2M_SUCCESS; +} +/********************************************************************* +Function + m2m_ping_req + +Description + Send Ping request. + +Return + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2015 +*********************************************************************/ +sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb) +{ + sint8 s8Ret = M2M_ERR_INVALID_ARG; + + if((u32DstIP != 0) && (fpPingCb != NULL)) + { + tstrPingCmd strPingCmd; + + strPingCmd.u16PingCount = 1; + strPingCmd.u32DestIPAddr = u32DstIP; +#ifdef ARDUINO + strPingCmd.u32CmdPrivate = (uint32)(uintptr_t)(fpPingCb); +#else + strPingCmd.u32CmdPrivate = (uint32)(fpPingCb); +#endif + strPingCmd.u8TTL = u8TTL; + + s8Ret = SOCKET_REQUEST(SOCKET_CMD_PING, (uint8*)&strPingCmd, sizeof(tstrPingCmd), NULL, 0, 0); + } + return s8Ret; +} +/********************************************************************* +Function + sslEnableCertExpirationCheck + +Description + Enable/Disable TLS Certificate Expiration Check. + +Return + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + +*********************************************************************/ +sint8 sslEnableCertExpirationCheck(tenuSslCertExpSettings enuValidationSetting) +{ + tstrSslCertExpSettings strSettings; + strSettings.u32CertExpValidationOpt = (uint32)enuValidationSetting; + return SOCKET_REQUEST(SOCKET_CMD_SSL_EXP_CHECK, (uint8*)&strSettings, sizeof(tstrSslCertExpSettings), NULL, 0, 0); +} \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket_buffer.c b/feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket_buffer.c new file mode 100644 index 0000000..d100558 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket_buffer.c @@ -0,0 +1,232 @@ +/** + * + * \file + * + * \brief BSD compatible socket interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include +#include "socket/include/socket.h" +#include "driver/source/m2m_hif.h" +#include "socket/source/socket_internal.h" +#include "socket/include/socket_buffer.h" +#include "driver/include/m2m_periph.h" + +tstrSocketBuffer gastrSocketBuffer[MAX_SOCKET]; + +extern uint8 hif_small_xfer; + +void socketBufferInit(void) +{ + memset(gastrSocketBuffer, 0, sizeof(gastrSocketBuffer)); +} + +void socketBufferRegister(SOCKET socket, uint32 *flag, uint32 *head, uint32 *tail, uint8 *buffer) +{ + gastrSocketBuffer[socket].flag = flag; + gastrSocketBuffer[socket].head = head; + gastrSocketBuffer[socket].tail = tail; + gastrSocketBuffer[socket].buffer = buffer; +} + +void socketBufferUnregister(SOCKET socket) +{ + gastrSocketBuffer[socket].flag = 0; + gastrSocketBuffer[socket].head = 0; + gastrSocketBuffer[socket].tail = 0; + gastrSocketBuffer[socket].buffer = 0; +} + +void socketBufferCb(SOCKET sock, uint8 u8Msg, void *pvMsg) +{ + switch (u8Msg) { + /* Socket connected. */ + case SOCKET_MSG_CONNECT: + { + tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg *)pvMsg; + if (pstrConnect && pstrConnect->s8Error >= 0) { + recv(sock, gastrSocketBuffer[sock].buffer, SOCKET_BUFFER_MTU, 0); + *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_CONNECTED; + } else { + close(sock); + } + } + break; + + /* TCP Data receive. */ + case SOCKET_MSG_RECV: + { + // Network led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); + + tstrSocketRecvMsg *pstrRecv = (tstrSocketRecvMsg *)pvMsg; + if (pstrRecv && pstrRecv->s16BufferSize > 0) { + /* Protect against overflow. */ + if (*(gastrSocketBuffer[sock].head) + pstrRecv->s16BufferSize > SOCKET_BUFFER_TCP_SIZE) { + *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_FULL; + break; + } + + /* Add data size. */ + *(gastrSocketBuffer[sock].head) += pstrRecv->s16BufferSize; + + /* Buffer full, stop reception. */ + if (SOCKET_BUFFER_TCP_SIZE - *(gastrSocketBuffer[sock].head) < SOCKET_BUFFER_MTU) { + if (pstrRecv->u16RemainingSize != 0) { + *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_FULL; + } + } + else { + recv(sock, gastrSocketBuffer[sock].buffer + *(gastrSocketBuffer[sock].head), + SOCKET_BUFFER_MTU, 0); + } + } + /* Test EOF (Socket closed) condition for TCP socket. */ + else { + *(gastrSocketBuffer[sock].flag) &= ~SOCKET_BUFFER_FLAG_CONNECTED; + close(sock); + } + + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + } + break; + + /* UDP Data receive. */ + case SOCKET_MSG_RECVFROM: + { + // Network led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); + + tstrSocketRecvMsg *pstrRecv = (tstrSocketRecvMsg *)pvMsg; + if (pstrRecv && pstrRecv->s16BufferSize > 0) { + + if (hif_small_xfer < 2) { + uint32 h = *(gastrSocketBuffer[sock].head); + uint8 *buf = gastrSocketBuffer[sock].buffer; + uint16 sz = pstrRecv->s16BufferSize + pstrRecv->u16RemainingSize; + + /* Store packet size. */ + buf[h++] = sz >> 8; + buf[h++] = sz; + + /* Store remote host port. */ + buf[h++] = pstrRecv->strRemoteAddr.sin_port; + buf[h++] = pstrRecv->strRemoteAddr.sin_port >> 8; + + /* Store remote host IP. */ + buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr >> 24; + buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr >> 16; + buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr >> 8; + buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr; + + /* Data received. */ + *(gastrSocketBuffer[sock].head) = h + pstrRecv->s16BufferSize; + } + else { + /* Data received. */ + *(gastrSocketBuffer[sock].head) += pstrRecv->s16BufferSize; + } + + /* Buffer full, stop reception. */ + if (SOCKET_BUFFER_UDP_SIZE - *(gastrSocketBuffer[sock].head) < SOCKET_BUFFER_MTU + SOCKET_BUFFER_UDP_HEADER_SIZE) { + if (pstrRecv->u16RemainingSize != 0) { + *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_FULL; + } + } + else { + if (hif_small_xfer && hif_small_xfer != 3) { + recvfrom(sock, gastrSocketBuffer[sock].buffer + *(gastrSocketBuffer[sock].head), + SOCKET_BUFFER_MTU, 0); + } + else { + recvfrom(sock, gastrSocketBuffer[sock].buffer + *(gastrSocketBuffer[sock].head) + SOCKET_BUFFER_UDP_HEADER_SIZE, + SOCKET_BUFFER_MTU, 0); + } + } + } + + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + } + break; + + /* Socket bind. */ + case SOCKET_MSG_BIND: + { + tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg *)pvMsg; + if (pstrBind && pstrBind->status == 0) { + *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_BIND; + /* TCP socket needs to enter Listen state. */ + if (sock < TCP_SOCK_MAX) { + listen(sock, 0); + } + /* UDP socket only needs to supply the receive buffer. */ + /* +8 is used to store size, port and IP of incoming data. */ + else { + recvfrom(sock, gastrSocketBuffer[sock].buffer + SOCKET_BUFFER_UDP_HEADER_SIZE, + SOCKET_BUFFER_MTU, 0); + } + } + } + break; + + /* Connect accept. */ + case SOCKET_MSG_ACCEPT: + { + tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg *)pvMsg; + if (pstrAccept && pstrAccept->sock >= 0) { + if (*(gastrSocketBuffer[sock].flag) & SOCKET_BUFFER_FLAG_SPAWN) { + /* One spawn connection already waiting, discard current one. */ + close(pstrAccept->sock); + } + else { + /* Use flag to store spawn TCP descriptor. */ + *(gastrSocketBuffer[sock].flag) &= ~SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK; + *(gastrSocketBuffer[sock].flag) |= (((uint32)pstrAccept->sock) << SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS); + *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_SPAWN; + } + } + } + break; + + } +} diff --git a/feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket_internal.h b/feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket_internal.h new file mode 100644 index 0000000..1904c23 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket_internal.h @@ -0,0 +1,71 @@ +/** + * + * \file + * + * \brief BSD compatible socket interface internal types. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +#ifndef __SOCKET_INTERNAL_H__ +#define __SOCKET_INTERNAL_H__ + + +#ifdef __cplusplus +extern "C" { +#endif + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "socket/include/socket.h" +#include "socket/include/m2m_socket_host_if.h" + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +NMI_API void Socket_ReadSocketData(SOCKET sock, tstrSocketRecvMsg *pstrRecv,uint8 u8SocketMsg, + uint32 u32StartAddress,uint16 u16ReadCount); +#ifdef ARDUINO +NMI_API void Socket_ReadSocketData_Small(void); +#endif + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* __SOCKET_H__ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/spi_flash/include/spi_flash.h b/feather_sensor_transmit/libraries/WiFi101/src/spi_flash/include/spi_flash.h new file mode 100644 index 0000000..a85aa72 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/spi_flash/include/spi_flash.h @@ -0,0 +1,233 @@ +/** + * + * \file + * + * \brief WINC1500 SPI Flash. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/** \defgroup SPIFLASH Spi Flash + * @file spi_flash.h + * @brief This file describe SPI flash APIs, how to use it and limitations with each one. + * @section Example + * This example illustrates a complete guide of how to use these APIs. + * @code{.c} + #include "spi_flash.h" + + #define DATA_TO_REPLACE "THIS IS A NEW SECTOR IN FLASH" + + int main() + { + uint8 au8FlashContent[FLASH_SECTOR_SZ] = {0}; + uint32 u32FlashTotalSize = 0; + uint32 u32FlashOffset = 0; + + ret = m2m_wifi_download_mode(); + if(M2M_SUCCESS != ret) + { + printf("Unable to enter download mode\r\n"); + } + else + { + u32FlashTotalSize = spi_flash_get_size(); + } + + while((u32FlashTotalSize > u32FlashOffset) && (M2M_SUCCESS == ret)) + { + ret = spi_flash_read(au8FlashContent, u32FlashOffset, FLASH_SECTOR_SZ); + if(M2M_SUCCESS != ret) + { + printf("Unable to read SPI sector\r\n"); + break; + } + memcpy(au8FlashContent, DATA_TO_REPLACE, strlen(DATA_TO_REPLACE)); + + ret = spi_flash_erase(u32FlashOffset, FLASH_SECTOR_SZ); + if(M2M_SUCCESS != ret) + { + printf("Unable to erase SPI sector\r\n"); + break; + } + + ret = spi_flash_write(au8FlashContent, u32FlashOffset, FLASH_SECTOR_SZ); + if(M2M_SUCCESS != ret) + { + printf("Unable to write SPI sector\r\n"); + break; + } + u32FlashOffset += FLASH_SECTOR_SZ; + } + + if(M2M_SUCCESS == ret) + { + printf("Successful operations\r\n"); + } + else + { + printf("Failed operations\r\n"); + } + + while(1); + return M2M_SUCCESS; + } + * @endcode + */ + +#ifndef __SPI_FLASH_H__ +#define __SPI_FLASH_H__ +#include "common/include/nm_common.h" +#include "bus_wrapper/include/nm_bus_wrapper.h" +#include "driver/source/nmbus.h" +#include "driver/source/nmasic.h" + +#ifdef ARDUINO +#ifdef __cplusplus +extern "C" { +#endif +#endif + +/** + * @fn spi_flash_enable + * @brief Enable spi flash operations + * @version 1.0 + */ +sint8 spi_flash_enable(uint8 enable); +/** \defgroup SPIFLASHAPI Function + * @ingroup SPIFLASH + */ + + /** @defgroup SPiFlashGetFn spi_flash_get_size + * @ingroup SPIFLASHAPI + */ + /**@{*/ +/*! + * @fn uint32 spi_flash_get_size(void); + * @brief Returns with \ref uint32 value which is total flash size\n + * @note Returned value in Mb (Mega Bit). + * @return SPI flash size in case of success and a ZERO value in case of failure. + */ +uint32 spi_flash_get_size(void); + /**@}*/ + + /** @defgroup SPiFlashRead spi_flash_read + * @ingroup SPIFLASHAPI + */ + /**@{*/ +/*! + * @fn sint8 spi_flash_read(uint8 *, uint32, uint32); + * @brief Read a specified portion of data from SPI Flash.\n + * @param [out] pu8Buf + * Pointer to data buffer which will fill in with data in case of successful operation. + * @param [in] u32Addr + * Address (Offset) to read from at the SPI flash. + * @param [in] u32Sz + * Total size of data to be read in bytes + * @warning + * - Address (offset) plus size of data must not exceed flash size.\n + * - No firmware is required for reading from SPI flash.\n + * - In case of there is a running firmware, it is required to pause your firmware first + * before any trial to access SPI flash to avoid any racing between host and running firmware on bus using + * @ref m2m_wifi_download_mode + * @note + * - It is blocking function\n + * @sa m2m_wifi_download_mode, spi_flash_get_size + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +sint8 spi_flash_read(uint8 *pu8Buf, uint32 u32Addr, uint32 u32Sz); + /**@}*/ + + /** @defgroup SPiFlashWrite spi_flash_write + * @ingroup SPIFLASHAPI + */ + /**@{*/ +/*! + * @fn sint8 spi_flash_write(uint8 *, uint32, uint32); + * @brief Write a specified portion of data to SPI Flash.\n + * @param [in] pu8Buf + * Pointer to data buffer which contains the required to be written. + * @param [in] u32Offset + * Address (Offset) to write at the SPI flash. + * @param [in] u32Sz + * Total number of size of data bytes + * @note + * - It is blocking function\n + * - It is user's responsibility to verify that data has been written successfully + * by reading data again and compare it with the original. + * @warning + * - Address (offset) plus size of data must not exceed flash size.\n + * - No firmware is required for writing to SPI flash.\n + * - In case of there is a running firmware, it is required to pause your firmware first + * before any trial to access SPI flash to avoid any racing between host and running firmware on bus using + * @ref m2m_wifi_download_mode. + * - Before writing to any section, it is required to erase it first. + * @sa m2m_wifi_download_mode, spi_flash_get_size, spi_flash_erase + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + + */ +sint8 spi_flash_write(uint8* pu8Buf, uint32 u32Offset, uint32 u32Sz); + /**@}*/ + + /** @defgroup SPiFlashErase spi_flash_erase + * @ingroup SPIFLASHAPI + */ + /**@{*/ +/*! + * @fn sint8 spi_flash_erase(uint32, uint32); + * @brief Erase a specified portion of SPI Flash.\n + * @param [in] u32Offset + * Address (Offset) to erase from the SPI flash. + * @param [in] u32Sz + * Size of SPI flash required to be erased. + * @note It is blocking function \n +* @warning +* - Address (offset) plus size of data must not exceed flash size.\n +* - No firmware is required for writing to SPI flash.\n + * - In case of there is a running firmware, it is required to pause your firmware first + * before any trial to access SPI flash to avoid any racing between host and running firmware on bus using + * @ref m2m_wifi_download_mode + * - It is blocking function\n + * @sa m2m_wifi_download_mode, spi_flash_get_size + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + + */ +sint8 spi_flash_erase(uint32 u32Offset, uint32 u32Sz); + /**@}*/ +#ifdef ARDUINO +#ifdef __cplusplus +} +#endif +#endif +#endif //__SPI_FLASH_H__ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h b/feather_sensor_transmit/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h new file mode 100644 index 0000000..3b0da53 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h @@ -0,0 +1,245 @@ +/** + * + * \file + * + * \brief WINC1500 SPI Flash. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/** +* @file spi_flash_map.h +* @brief This module contains spi flash CONTENT +* @author M.S.M +* @date 17 SEPT 2013 +* @version 1.0 +*/ +#ifndef __SPI_FLASH_MAP_H__ +#define __SPI_FLASH_MAP_H__ + +#define FLASH_MAP_VER_0 (0) +#define FLASH_MAP_VER_1 (1) +#define FLASH_MAP_VER_2 (2) +#define FLASH_MAP_VER_3 (3) + +#define FLASH_MAP_VERSION FLASH_MAP_VER_3 + +//#define DOWNLOAD_ROLLBACK +//#define OTA_GEN +#define _PROGRAM_POWER_SAVE_ + +/* =======*=======*=======*=======*======= + * General Sizes for Flash Memory + * =======*=======*=======*=======*======= + */ + +#define FLASH_START_ADDR (0UL) +/*! location :xxxK + * "S:xxxK" -means-> Size is :xxxK + */ + +/* + * Boot Firmware: which used to select which firmware to run + * + */ +#define M2M_BOOT_FIRMWARE_STARTING_ADDR (FLASH_START_ADDR) +#define M2M_BOOT_FIRMWARE_FLASH_SZ (FLASH_SECTOR_SZ) + +/* + * Control Section: which used by Boot firmware + * + */ +#define M2M_CONTROL_FLASH_OFFSET (M2M_BOOT_FIRMWARE_STARTING_ADDR + M2M_BOOT_FIRMWARE_FLASH_SZ) +#define M2M_CONTROL_FLASH_BKP_OFFSET (M2M_CONTROL_FLASH_OFFSET + FLASH_SECTOR_SZ) +#define M2M_CONTROL_FLASH_SEC_SZ (FLASH_SECTOR_SZ) +#define M2M_CONTROL_FLASH_TOTAL_SZ (FLASH_SECTOR_SZ * 2) + +/* + * LUT for PLL and TX Gain settings: + * + */ +#define M2M_PLL_FLASH_OFFSET (M2M_CONTROL_FLASH_OFFSET + M2M_CONTROL_FLASH_TOTAL_SZ) +#define M2M_PLL_FLASH_SZ (1024 * 1) +#define M2M_GAIN_FLASH_OFFSET (M2M_PLL_FLASH_OFFSET + M2M_PLL_FLASH_SZ) +#define M2M_GAIN_FLASH_SZ (M2M_CONFIG_SECT_TOTAL_SZ - M2M_PLL_FLASH_SZ) +#define M2M_CONFIG_SECT_TOTAL_SZ (FLASH_SECTOR_SZ) + +/* + * Certificate: + * + */ +#define M2M_TLS_ROOTCER_FLASH_OFFSET (M2M_PLL_FLASH_OFFSET + M2M_CONFIG_SECT_TOTAL_SZ) +#define M2M_TLS_ROOTCER_FLASH_SIZE (FLASH_SECTOR_SZ * 1) + +/* + * TLS Server Key Files + * + */ +#define M2M_TLS_SERVER_FLASH_OFFSET (M2M_TLS_ROOTCER_FLASH_OFFSET + M2M_TLS_ROOTCER_FLASH_SIZE) +#define M2M_TLS_SERVER_FLASH_SIZE (FLASH_SECTOR_SZ * 2) + +/* + * HTTP Files + * + */ +#define M2M_HTTP_MEM_FLASH_OFFSET (M2M_TLS_SERVER_FLASH_OFFSET + M2M_TLS_SERVER_FLASH_SIZE) +#define M2M_HTTP_MEM_FLASH_SZ (FLASH_SECTOR_SZ * 2) + +/* + * Saved Connection Parameters: + * + */ +#define M2M_CACHED_CONNS_FLASH_OFFSET (M2M_HTTP_MEM_FLASH_OFFSET + M2M_HTTP_MEM_FLASH_SZ) +#define M2M_CACHED_CONNS_FLASH_SZ (FLASH_SECTOR_SZ * 1) + +/* + * + * Common section size + */ + +#define M2M_COMMON_DATA_SEC \ + (\ + M2M_BOOT_FIRMWARE_FLASH_SZ + \ + M2M_CONTROL_FLASH_TOTAL_SZ + \ + M2M_CONFIG_SECT_TOTAL_SZ + \ + M2M_TLS_ROOTCER_FLASH_SIZE + \ + M2M_TLS_SERVER_FLASH_SIZE + \ + M2M_HTTP_MEM_FLASH_SZ + \ + M2M_CACHED_CONNS_FLASH_SZ \ + ) + +/* + * + * OTA image1 Offset + */ + +#define M2M_OTA_IMAGE1_OFFSET (M2M_CACHED_CONNS_FLASH_OFFSET + M2M_CACHED_CONNS_FLASH_SZ) +/* + * Firmware Offset + * + */ +#if (defined _FIRMWARE_)||(defined OTA_GEN) +#define M2M_FIRMWARE_FLASH_OFFSET (0UL) +#else +#if (defined DOWNLOAD_ROLLBACK) +#define M2M_FIRMWARE_FLASH_OFFSET (M2M_OTA_IMAGE2_OFFSET) +#else +#define M2M_FIRMWARE_FLASH_OFFSET (M2M_OTA_IMAGE1_OFFSET) +#endif +#endif +/* + * + * Firmware + */ +#define M2M_FIRMWARE_FLASH_SZ (236 * 1024UL) +/** + * + * OTA image Size + */ +#define OTA_IMAGE_SIZE (M2M_FIRMWARE_FLASH_SZ) +/** + * + * Flash Total size + */ +#define FLASH_IMAGE1_CONTENT_SZ (M2M_COMMON_DATA_SEC + OTA_IMAGE_SIZE) + +/** + * + * OTA image 2 offset + */ +#define M2M_OTA_IMAGE2_OFFSET (FLASH_IMAGE1_CONTENT_SZ) + +/* + * App(Cortus App 4M): App. which runs over firmware + * + */ +#define M2M_APP_4M_MEM_FLASH_SZ (FLASH_SECTOR_SZ * 16) +#define M2M_APP_4M_MEM_FLASH_OFFSET (FLASH_4M_TOTAL_SZ - M2M_APP_4M_MEM_FLASH_SZ) +#define M2M_APP_8M_MEM_FLASH_OFFSET (M2M_OTA_IMAGE2_OFFSET + OTA_IMAGE_SIZE) +#define M2M_APP_8M_MEM_FLASH_SZ (FLASH_SECTOR_SZ * 32) +#define M2M_APP_OTA_MEM_FLASH_OFFSET (M2M_APP_8M_MEM_FLASH_OFFSET + M2M_APP_8M_MEM_FLASH_SZ) + +/* Check if total size of content + * don't exceed total size of memory allowed + **/ +#if (M2M_COMMON_DATA_SEC + (OTA_IMAGE_SIZE *2)> FLASH_4M_TOTAL_SZ) +#error "Excced 4M Flash Size" +#endif /* (FLASH_CONTENT_SZ > FLASH_TOTAL_SZ) */ + + +#endif /* __SPI_FLASH_MAP_H__ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/spi_flash/source/spi_flash.c b/feather_sensor_transmit/libraries/WiFi101/src/spi_flash/source/spi_flash.c new file mode 100644 index 0000000..12eff59 --- /dev/null +++ b/feather_sensor_transmit/libraries/WiFi101/src/spi_flash/source/spi_flash.c @@ -0,0 +1,770 @@ +/** + * + * \file + * + * \brief WINC1500 SPI Flash. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifdef PROFILING +#include "windows.h" +#endif +#include "spi_flash/include/spi_flash.h" +#define DUMMY_REGISTER (0x1084) + +#ifdef ARDUINO +#define u32(x) ((uint32)x) +#endif + +#define TIMEOUT (-1) /*MS*/ + +//#define DISABLE_UNSED_FLASH_FUNCTIONS + +#define FLASH_BLOCK_SIZE (32UL * 1024) +/*!> 16); + cmd[2] = (uint8)(u32FlashAdr >> 8); + cmd[3] = (uint8)(u32FlashAdr); + cmd[4] = 0xA5; + + ret += nm_write_reg(SPI_FLASH_DATA_CNT, u32Sz); +#ifdef ARDUINO + ret += nm_write_reg(SPI_FLASH_BUF1, u32(cmd[0])|u32(cmd[1]<<8)|u32(cmd[2]<<16)|u32(cmd[3]<<24)); +#else + ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]|(cmd[1]<<8)|(cmd[2]<<16)|(cmd[3]<<24)); +#endif + ret += nm_write_reg(SPI_FLASH_BUF2, cmd[4]); + ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x1f); + ret += nm_write_reg(SPI_FLASH_DMA_ADDR, u32MemAdr); + ret += nm_write_reg(SPI_FLASH_CMD_CNT, 5 | (1<<7)); + do + { + ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); + if(M2M_SUCCESS != ret) break; + } + while(val != 1); + + return ret; +} + +/** +* @fn spi_flash_sector_erase +* @brief Erase sector (4KB) +* @param[IN] u32FlashAdr +* Any memory address within the sector +* @return Status of execution +* @note Compatible with MX25L6465E and should be working with other types +* @author M. Abdelmawla +* @version 1.0 +*/ +static sint8 spi_flash_sector_erase(uint32 u32FlashAdr) +{ + uint8 cmd[4]; + uint32 val = 0; + sint8 ret = M2M_SUCCESS; + + cmd[0] = 0x20; + cmd[1] = (uint8)(u32FlashAdr >> 16); + cmd[2] = (uint8)(u32FlashAdr >> 8); + cmd[3] = (uint8)(u32FlashAdr); + + ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); +#ifdef ARDUINO + ret += nm_write_reg(SPI_FLASH_BUF1, u32(cmd[0])|u32(cmd[1]<<8)|u32(cmd[2]<<16)|u32(cmd[3]<<24)); +#else + ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]|(cmd[1]<<8)|(cmd[2]<<16)|(cmd[3]<<24)); +#endif + ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x0f); + ret += nm_write_reg(SPI_FLASH_DMA_ADDR, 0); + ret += nm_write_reg(SPI_FLASH_CMD_CNT, 4 | (1<<7)); + do + { + ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); + if(M2M_SUCCESS != ret) break; + } + while(val != 1); + + return ret; +} + +/** +* @fn spi_flash_write_enable +* @brief Send write enable command to SPI flash +* @return Status of execution +* @note Compatible with MX25L6465E and should be working with other types +* @author M. Abdelmawla +* @version 1.0 +*/ +static sint8 spi_flash_write_enable(void) +{ + uint8 cmd[1]; + uint32 val = 0; + sint8 ret = M2M_SUCCESS; + + cmd[0] = 0x06; + + ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); + ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]); + ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x01); + ret += nm_write_reg(SPI_FLASH_DMA_ADDR, 0); + ret += nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1<<7)); + do + { + ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); + if(M2M_SUCCESS != ret) break; + } + while(val != 1); + + return ret; +} + +/** +* @fn spi_flash_write_disable +* @brief Send write disable command to SPI flash +* @note Compatible with MX25L6465E and should be working with other types +* @author M. Abdelmawla +* @version 1.0 +*/ +static sint8 spi_flash_write_disable(void) +{ + uint8 cmd[1]; + uint32 val = 0; + sint8 ret = M2M_SUCCESS; + cmd[0] = 0x04; + + ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); + ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]); + ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x01); + ret += nm_write_reg(SPI_FLASH_DMA_ADDR, 0); + ret += nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1<<7)); + do + { + ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); + if(M2M_SUCCESS != ret) break; + } + while(val != 1); + + return ret; +} + +/** +* @fn spi_flash_page_program +* @brief Write data (less than page size) from cortus memory to SPI flash +* @param[IN] u32MemAdr +* Cortus data address. It must be set to its AHB access address +* @param[IN] u32FlashAdr +* Address to write to at the SPI flash +* @param[IN] u32Sz +* Data size +* @note Compatible with MX25L6465E and should be working with other types +* @author M. Abdelmawla +* @version 1.0 +*/ +static sint8 spi_flash_page_program(uint32 u32MemAdr, uint32 u32FlashAdr, uint32 u32Sz) +{ + uint8 cmd[4]; + uint32 val = 0; + sint8 ret = M2M_SUCCESS; + + cmd[0] = 0x02; + cmd[1] = (uint8)(u32FlashAdr >> 16); + cmd[2] = (uint8)(u32FlashAdr >> 8); + cmd[3] = (uint8)(u32FlashAdr); + + ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); +#ifdef ARDUINO + ret += nm_write_reg(SPI_FLASH_BUF1, u32(cmd[0])|u32(cmd[1]<<8)|u32(cmd[2]<<16)|u32(cmd[3]<<24)); +#else + ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]|(cmd[1]<<8)|(cmd[2]<<16)|(cmd[3]<<24)); +#endif + ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x0f); + ret += nm_write_reg(SPI_FLASH_DMA_ADDR, u32MemAdr); + ret += nm_write_reg(SPI_FLASH_CMD_CNT, 4 | (1<<7) | ((u32Sz & 0xfffff) << 8)); + do + { + ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); + if(M2M_SUCCESS != ret) break; + } + while(val != 1); + + return ret; +} + +/** +* @fn spi_flash_read_internal +* @brief Read from data from SPI flash +* @param[OUT] pu8Buf +* Pointer to data buffer +* @param[IN] u32Addr +* Address to read from at the SPI flash +* @param[IN] u32Sz +* Data size +* @note Data size must be < 64KB (limitation imposed by the bus wrapper) +* @author M. Abdelmawla +* @version 1.0 +*/ +static sint8 spi_flash_read_internal(uint8 *pu8Buf, uint32 u32Addr, uint32 u32Sz) +{ + sint8 ret = M2M_SUCCESS; + /* read size must be < 64KB */ + ret = spi_flash_load_to_cortus_mem(HOST_SHARE_MEM_BASE, u32Addr, u32Sz); + if(M2M_SUCCESS != ret) goto ERR; + ret = nm_read_block(HOST_SHARE_MEM_BASE, pu8Buf, u32Sz); +ERR: + return ret; +} + +/** +* @fn spi_flash_pp +* @brief Program data of size less than a page (256 bytes) at the SPI flash +* @param[IN] u32Offset +* Address to write to at the SPI flash +* @param[IN] pu8Buf +* Pointer to data buffer +* @param[IN] u32Sz +* Data size +* @return Status of execution +* @author M. Abdelmawla +* @version 1.0 +*/ +static sint8 spi_flash_pp(uint32 u32Offset, uint8 *pu8Buf, uint16 u16Sz) +{ + sint8 ret = M2M_SUCCESS; + uint8 tmp; + spi_flash_write_enable(); + /* use shared packet memory as temp mem */ + ret += nm_write_block(HOST_SHARE_MEM_BASE, pu8Buf, u16Sz); + ret += spi_flash_page_program(HOST_SHARE_MEM_BASE, u32Offset, u16Sz); + ret += spi_flash_read_status_reg(&tmp); + do + { + if(ret != M2M_SUCCESS) goto ERR; + ret += spi_flash_read_status_reg(&tmp); + }while(tmp & 0x01); + ret += spi_flash_write_disable(); +ERR: + return ret; +} + +/** +* @fn spi_flash_rdid +* @brief Read SPI Flash ID +* @return SPI FLash ID +* @author M.S.M +* @version 1.0 +*/ +static uint32 spi_flash_rdid(void) +{ + unsigned char cmd[1]; + uint32 reg = 0; + uint32 cnt = 0; + sint8 ret = M2M_SUCCESS; + + cmd[0] = 0x9f; + + ret += nm_write_reg(SPI_FLASH_DATA_CNT, 4); + ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]); + ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x1); + ret += nm_write_reg(SPI_FLASH_DMA_ADDR, DUMMY_REGISTER); + ret += nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1<<7)); + do + { + ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)®); + if(M2M_SUCCESS != ret) break; + if(++cnt > 500) + { + ret = M2M_ERR_INIT; + break; + } + } + while(reg != 1); + reg = (M2M_SUCCESS == ret)?(nm_read_reg(DUMMY_REGISTER)):(0); + M2M_PRINT("Flash ID %x \n",(unsigned int)reg); + return reg; +} + +/** +* @fn spi_flash_unlock +* @brief Unlock SPI Flash +* @author M.S.M +* @version 1.0 +*/ +#if 0 +static void spi_flash_unlock(void) +{ + uint8 tmp; + tmp = spi_flash_read_security_reg(); + spi_flash_clear_security_flags(); + if(tmp & 0x80) + { + spi_flash_write_enable(); + spi_flash_gang_unblock(); + } +} +#endif +static void spi_flash_enter_low_power_mode(void) { + volatile unsigned long tmp; + unsigned char* cmd = (unsigned char*) &tmp; + + cmd[0] = 0xb9; + + nm_write_reg(SPI_FLASH_DATA_CNT, 0); + nm_write_reg(SPI_FLASH_BUF1, cmd[0]); + nm_write_reg(SPI_FLASH_BUF_DIR, 0x1); + nm_write_reg(SPI_FLASH_DMA_ADDR, 0); + nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1 << 7)); + while(nm_read_reg(SPI_FLASH_TR_DONE) != 1); +} + + +static void spi_flash_leave_low_power_mode(void) { + volatile unsigned long tmp; + unsigned char* cmd = (unsigned char*) &tmp; + + cmd[0] = 0xab; + + nm_write_reg(SPI_FLASH_DATA_CNT, 0); + nm_write_reg(SPI_FLASH_BUF1, cmd[0]); + nm_write_reg(SPI_FLASH_BUF_DIR, 0x1); + nm_write_reg(SPI_FLASH_DMA_ADDR, 0); + nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1 << 7)); + while(nm_read_reg(SPI_FLASH_TR_DONE) != 1); +} +/*********************************************/ +/* GLOBAL FUNCTIONS */ +/*********************************************/ +/** + * @fn spi_flash_enable + * @brief Enable spi flash operations + * @author M. Abdelmawla + * @version 1.0 + */ +sint8 spi_flash_enable(uint8 enable) +{ + sint8 s8Ret = M2M_SUCCESS; + if(REV(nmi_get_chipid()) >= REV_3A0) { + uint32 u32Val; + + /* Enable pinmux to SPI flash. */ + s8Ret = nm_read_reg_with_ret(0x1410, &u32Val); + if(s8Ret != M2M_SUCCESS) { + goto ERR1; + } + /* GPIO15/16/17/18 */ + u32Val &= ~((0x7777ul) << 12); + u32Val |= ((0x1111ul) << 12); + nm_write_reg(0x1410, u32Val); + if(enable) { + spi_flash_leave_low_power_mode(); + } else { + spi_flash_enter_low_power_mode(); + } + /* Disable pinmux to SPI flash to minimize leakage. */ + u32Val &= ~((0x7777ul) << 12); + u32Val |= ((0x0010ul) << 12); + nm_write_reg(0x1410, u32Val); + } +ERR1: + return s8Ret; +} +/** +* @fn spi_flash_read +* @brief Read from data from SPI flash +* @param[OUT] pu8Buf +* Pointer to data buffer +* @param[IN] u32offset +* Address to read from at the SPI flash +* @param[IN] u32Sz +* Data size +* @return Status of execution +* @note Data size is limited by the SPI flash size only +* @author M. Abdelmawla +* @version 1.0 +*/ +sint8 spi_flash_read(uint8 *pu8Buf, uint32 u32offset, uint32 u32Sz) +{ + sint8 ret = M2M_SUCCESS; + if(u32Sz > FLASH_BLOCK_SIZE) + { + do + { + ret = spi_flash_read_internal(pu8Buf, u32offset, FLASH_BLOCK_SIZE); + if(M2M_SUCCESS != ret) goto ERR; + u32Sz -= FLASH_BLOCK_SIZE; + u32offset += FLASH_BLOCK_SIZE; + pu8Buf += FLASH_BLOCK_SIZE; + } while(u32Sz > FLASH_BLOCK_SIZE); + } + + ret = spi_flash_read_internal(pu8Buf, u32offset, u32Sz); + +ERR: + return ret; +} + +/** +* @fn spi_flash_write +* @brief Proram SPI flash +* @param[IN] pu8Buf +* Pointer to data buffer +* @param[IN] u32Offset +* Address to write to at the SPI flash +* @param[IN] u32Sz +* Data size +* @return Status of execution +* @author M. Abdelmawla +* @version 1.0 +*/ +sint8 spi_flash_write(uint8* pu8Buf, uint32 u32Offset, uint32 u32Sz) +{ +#ifdef PROFILING + uint32 t1 = 0; + uint32 percent =0; + uint32 tpercent =0; +#endif + sint8 ret = M2M_SUCCESS; + uint32 u32wsz; + uint32 u32off; + uint32 u32Blksz; + u32Blksz = FLASH_PAGE_SZ; + u32off = u32Offset % u32Blksz; +#ifdef PROFILING + tpercent = (u32Sz/u32Blksz)+((u32Sz%u32Blksz)>0); + t1 = GetTickCount(); + M2M_PRINT(">Start programming...\r\n"); +#endif + if(u32Sz<=0) + { + M2M_ERR("Data size = %d",(int)u32Sz); + ret = M2M_ERR_FAIL; + goto ERR; + } + + if (u32off)/*first part of data in the address page*/ + { + u32wsz = u32Blksz - u32off; + if(spi_flash_pp(u32Offset, pu8Buf, (uint16)BSP_MIN(u32Sz, u32wsz))!=M2M_SUCCESS) + { + ret = M2M_ERR_FAIL; + goto ERR; + } + if (u32Sz < u32wsz) goto EXIT; + pu8Buf += u32wsz; + u32Offset += u32wsz; + u32Sz -= u32wsz; + } + while (u32Sz > 0) + { + u32wsz = BSP_MIN(u32Sz, u32Blksz); + + /*write complete page or the remaining data*/ + if(spi_flash_pp(u32Offset, pu8Buf, (uint16)u32wsz)!=M2M_SUCCESS) + { + ret = M2M_ERR_FAIL; + goto ERR; + } + pu8Buf += u32wsz; + u32Offset += u32wsz; + u32Sz -= u32wsz; +#ifdef PROFILING + percent++; + printf("\r>Complete Percentage = %d%%.\r",((percent*100)/tpercent)); +#endif + } +EXIT: +#ifdef PROFILING + M2M_PRINT("\rDone\t\t\t\t\t\t"); + M2M_PRINT("\n#Programming time = %f sec\n\r",(GetTickCount() - t1)/1000.0); +#endif +ERR: + return ret; +} + +/** +* @fn spi_flash_erase +* @brief Erase from data from SPI flash +* @param[IN] u32Offset +* Address to write to at the SPI flash +* @param[IN] u32Sz +* Data size +* @return Status of execution +* @note Data size is limited by the SPI flash size only +* @author M. Abdelmawla +* @version 1.0 +*/ +sint8 spi_flash_erase(uint32 u32Offset, uint32 u32Sz) +{ + uint32 i = 0; + sint8 ret = M2M_SUCCESS; + uint8 tmp = 0; +#ifdef PROFILING + uint32 t; + t = GetTickCount(); +#endif + M2M_PRINT("\r\n>Start erasing...\r\n"); + for(i = u32Offset; i < (u32Sz +u32Offset); i += (16*FLASH_PAGE_SZ)) + { + ret += spi_flash_write_enable(); + ret += spi_flash_read_status_reg(&tmp); + ret += spi_flash_sector_erase(i + 10); + ret += spi_flash_read_status_reg(&tmp); + do + { + if(ret != M2M_SUCCESS) goto ERR; + ret += spi_flash_read_status_reg(&tmp); + }while(tmp & 0x01); + + } + M2M_PRINT("Done\r\n"); +#ifdef PROFILING + M2M_PRINT("#Erase time = %f sec\n", (GetTickCount()-t)/1000.0); +#endif +ERR: + return ret; +} + +/** +* @fn spi_flash_get_size +* @brief Get size of SPI Flash +* @return Size of Flash +* @author M.S.M +* @version 1.0 +*/ +uint32 spi_flash_get_size(void) +{ + uint32 u32FlashId = 0, u32FlashPwr = 0; + static uint32 gu32InernalFlashSize= 0; + + if(!gu32InernalFlashSize) + { + u32FlashId = spi_flash_rdid();//spi_flash_probe(); + if(u32FlashId != 0xffffffff) + { + /*flash size is the third byte from the FLASH RDID*/ + u32FlashPwr = ((u32FlashId>>16)&0xff) - 0x11; /*2MBIT is the min*/ + /*That number power 2 to get the flash size*/ + gu32InernalFlashSize = 1< +#include +#include "config.h" +#include +#include "watchdog.h" +#include "rtc.h" +#include "transmit.h" + +#ifdef HEATSEEK_FEATHER_WIFI_WICED +char const* get_encryption_str(int32_t enc_type); +#endif + +CONFIG_union CONFIG; +static DHT dht(DHT_DATA, DHT22); + +void write_config() { + File config_file; + + if (config_file = SD.open("config.bin", FILE_WRITE | O_TRUNC)) { + config_file.write(CONFIG.raw, sizeof(CONFIG)); + config_file.close(); + } else { + Serial.println("unable to update config"); + while(true); // watchdog will reboot + } +} + +bool read_config() { + File config_file; + bool success = false; + + if (config_file = SD.open("config.bin", FILE_READ)) { + int read_size = config_file.read(CONFIG.raw, sizeof(CONFIG)); + + if (sizeof(CONFIG) == read_size) { + Serial.print("Version from file: "); + Serial.print(CONFIG.data.version); + Serial.print("; expected version: "); + Serial.println(CONFIG_VERSION); + if (CONFIG.data.version == CONFIG_VERSION) { + Serial.println("config loaded"); + success = true; + } else { + Serial.println("incorrect config version"); + } + } else { + Serial.print("config incorrect size - expected: "); + Serial.print(sizeof(CONFIG)); + Serial.print(", got: "); + Serial.println(read_size); + } + + config_file.close(); + } else { + Serial.println("unable to read config"); + } + + return success; +} + +void set_default_config() { + CONFIG.data.version = CONFIG_VERSION; + CONFIG.data.reading_interval_s = 5 * 60; + CONFIG.data.cell_configured = 0; + CONFIG.data.wifi_configured = 0; + CONFIG.data.temperature_offset_f = 0.0; + + strcpy(CONFIG.data.hub_id, "featherhub"); + + strcpy(CONFIG.data.endpoint_domain, "relay.heatseek.org"); + strcpy(CONFIG.data.endpoint_path, "/temperatures"); + CONFIG.data.endpoint_configured = 1; +} + +int read_input_until_newline(char *message, char *buffer) { + int i = 0; + bool reached_newline = false; + + while (true) { + Serial.println(message); + + while (Serial.available()) { + char c = Serial.read(); + if (c == '\n') { +// Serial.println("done setting"); + reached_newline = true; + break; + } else { + buffer[i++] = c; + } + } + if (reached_newline) break; + + watchdog_feed(); + delay(2000); + } + + return i; +} + +void print_menu() { + Serial.println("-------------------------------------"); + Serial.println("[?] Print this menu"); + Serial.println("[t] Set RTC"); + Serial.println("[r] Set reading interval"); + Serial.println("[q] Clear reading transmission queue"); + Serial.println("[v] Calibrate temperature sensor"); + #ifdef TRANSMITTER_WIFI + Serial.println("[w] Setup wifi"); + Serial.println("[a] List nearby access points"); + #endif + Serial.println("[i] Setup Cell ID"); + Serial.println("[e] Setup API Endpoint"); + Serial.println("[p] Print config"); + Serial.println("[d] Reset config"); + Serial.println("[s] Exit config"); +} + +void print_config_info() { + Serial.println("-------------------------------------"); + Serial.println("Current config:"); + + #ifdef TRANSMITTER_WIFI + if (CONFIG.data.wifi_configured) { + Serial.print("wifi ssid: "); + Serial.print(CONFIG.data.wifi_ssid); + Serial.print(", wifi pass: "); + Serial.print(CONFIG.data.wifi_pass); + } else { + Serial.print("Wifi not configured"); + } + + Serial.println(); + #endif + + if (CONFIG.data.cell_configured) { + Serial.print("hub id: "); + Serial.print(CONFIG.data.hub_id); + Serial.print(", cell id: "); + Serial.print(CONFIG.data.cell_id); + } else { + Serial.print("cell id not configured"); + } + Serial.println(); + + if (CONFIG.data.endpoint_configured) { + Serial.print("endpoint: "); + Serial.print(CONFIG.data.endpoint_domain); + Serial.print(CONFIG.data.endpoint_path); + } else { + Serial.print("endpoint not configured"); + } + Serial.println(); + + Serial.print("reading_interval (seconds): "); + Serial.println(CONFIG.data.reading_interval_s); +} + +void enter_configuration() { + print_menu(); + + while(true) { + char command = Serial.read(); + while(Serial.available()) { Serial.read(); } + + switch (command) { + case '?': { + print_menu(); + break; + } + case 't': { + rtc_set(); + print_menu(); + break; + } + case 'q': { + clear_queued_transmissions(); + print_menu(); + break; + } + case 'r': { + char buffer[200]; + int length; + + length = read_input_until_newline("Enter Reading interval in seconds", buffer); + buffer[length] = '\0'; + CONFIG.data.reading_interval_s = strtol(buffer, NULL, 0); + + write_config(); + + update_last_reading_time(0); // take initial reading after configuration + clear_queued_transmissions(); // clear transmission queue + + Serial.println("Reading interval Configured"); + print_config_info(); + print_menu(); + break; + } +#ifdef TRANSMITTER_WIFI + case 'w': { + char buffer[200]; + int length; + + length = read_input_until_newline("Enter WiFi SSID", buffer); + buffer[length] = '\0'; + strcpy(CONFIG.data.wifi_ssid, buffer); + + length = read_input_until_newline("Enter WiFi password", buffer); + buffer[length] = '\0'; + strcpy(CONFIG.data.wifi_pass, buffer); + + CONFIG.data.wifi_configured = 1; + write_config(); + force_wifi_reconnect(); + + Serial.println("Wifi Configured"); + print_config_info(); + print_menu(); + break; + } +#endif +#ifdef HEATSEEK_FEATHER_WIFI_WICED + case 'a': { + wl_ap_info_t ap_list[20]; + int networkCount = 0; + networkCount = Feather.scanNetworks(ap_list, 20); + + Serial.println("========="); + Serial.print("Found "); Serial.print(networkCount); Serial.println(" Networks"); + + for (int i = 0; i < networkCount; i++) { + Serial.println("========="); + wl_ap_info_t ap = ap_list[i]; + Serial.print("SSID: "); Serial.println(ap.ssid); + Serial.print("RSSI: "); Serial.println(ap.rssi); + Serial.print("max data rate: "); Serial.println(ap.max_data_rate); + Serial.print("network type: "); Serial.println(ap.network_type); + Serial.print("security: "); Serial.print(ap.security); Serial.print(" - "); Serial.println(get_encryption_str(ap.security)); + Serial.print("channel: "); Serial.println(ap.channel); + Serial.print("band_2_4ghz: "); Serial.println(ap.band_2_4ghz); + } + + break; + } +#endif +#ifdef HEATSEEK_FEATHER_WIFI_M0 + case 'a': { + int networkCount = -1; + WiFi.setPins(8, 7, 4, 2); + networkCount = WiFi.scanNetworks(); + + Serial.println("========="); + Serial.print("Found "); Serial.print(networkCount); Serial.println(" Networks"); + + for (int i = 0; i < networkCount; i++) { + Serial.println("========="); + Serial.print("SSID: "); Serial.println(WiFi.SSID(i)); + Serial.print("RSSI: "); Serial.println(WiFi.RSSI(i)); + Serial.print("security: "); + switch (WiFi.encryptionType(i)) { + case ENC_TYPE_WEP: + Serial.println("WEP"); + case ENC_TYPE_TKIP: + Serial.println("WPA"); + case ENC_TYPE_CCMP: + Serial.println("WPA2"); + case ENC_TYPE_NONE: + Serial.println("None"); + case ENC_TYPE_AUTO: + Serial.println("Auto"); + } + } + print_menu(); + break; + } +#endif + case 'i': { + char buffer[200]; + int length; + +// hub is now always set to 'featherhub' +// length = read_input_until_newline("Enter HUB ID", buffer); +// buffer[length] = '\0'; +// strcpy(CONFIG.data.hub_id, buffer); + + length = read_input_until_newline("Enter CELL ID", buffer); + buffer[length] = '\0'; + strcpy(CONFIG.data.cell_id, buffer); + + CONFIG.data.cell_configured = 1; + write_config(); + + Serial.println("Cell ID Configured"); + print_config_info(); + print_menu(); + break; + } + case 'e': { + char buffer[200]; + int length; + + length = read_input_until_newline("Enter domain of API endpoint (Example: 'heatseek.org')", buffer); + buffer[length] = '\0'; + strcpy(CONFIG.data.endpoint_domain, buffer); + + length = read_input_until_newline("Enter path of API endpoint (Example: '/readings/create')", buffer); + buffer[length] = '\0'; + strcpy(CONFIG.data.endpoint_path, buffer); + + CONFIG.data.endpoint_configured = 1; + write_config(); + + Serial.println("API Endpoint configured"); + print_config_info(); + print_menu(); + break; + } + case 'd': { + Serial.println("reseting config"); + set_default_config(); + write_config(); + + print_config_info(); + print_menu(); + break; + } + case 'p': { + Serial.println("print config info"); + print_config_info(); + break; + } + case 's': { + Serial.println("exiting config"); + return; + } + case 'v': { + char buffer[200]; + int length; + float current_temp; + int readings_taken = 0; + float temperature_f; + float average_temperature_f = 0.0; + + length = read_input_until_newline("Enter current temperature, in fahrenheit, with one decimal place. For example: '41.0'. PLEASE ENSURE THAT SENSOR IS ON FOR APPROX. 5 MINUTES BEFORE CALIBRATING!", buffer); + buffer[length] = '\0'; + current_temp = strtof(buffer, NULL); + + while (readings_taken < 5) { + watchdog_feed(); + Serial.println("Calibrating, please wait..."); + temperature_f = dht.readTemperature(true); + + if (!isnan(temperature_f)) { + if (average_temperature_f == 0.0) { + average_temperature_f = temperature_f; + } else { + average_temperature_f = (average_temperature_f + temperature_f) / 2; + } + } else { + Serial.println("Failed to read temperature sensor; reboot device and try again."); + while(true); + } + + watchdog_feed(); + readings_taken++; + delay(2000); + } + + watchdog_feed(); + + float temperature_offset = current_temp - average_temperature_f; + CONFIG.data.temperature_offset_f = temperature_offset; + write_config(); + + Serial.print("Temperature offset set to: "); + Serial.println(temperature_offset); + + print_config_info(); + print_menu(); + break; + } + } + + watchdog_feed(); + delay(50); + } +} + +uint32_t get_last_reading_time() { + File reading_time_file; + uint8_t data[4]; + + if (reading_time_file = SD.open("time.bin", FILE_READ)) { + reading_time_file.read(data, sizeof(data)); + reading_time_file.close(); + } else { + Serial.println("unable to read last reading time"); + return 0; + } + + return data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); +} + +void update_last_reading_time(uint32_t timestamp) { + uint8_t data[4]; + + data[0] = (timestamp & 0x000000ff); + data[1] = (timestamp & 0x0000ff00) >> 8; + data[2] = (timestamp & 0x00ff0000) >> 16; + data[3] = (timestamp & 0xff000000) >> 24; + + File reading_time_file; + + if (reading_time_file = SD.open("time.bin", FILE_WRITE | O_TRUNC)) { + reading_time_file.write(data, sizeof(data)); + reading_time_file.close(); + } else { + Serial.println("unable to update last reading time"); + while(true); // watchdog will reboot + } + + Serial.println("updated last reading time"); +} + +#ifdef HEATSEEK_FEATHER_WIFI_WICED +char const* get_encryption_str(int32_t enc_type) +{ + // read the encryption type and print out the name: + switch (enc_type) + { + case ENC_TYPE_AUTO: return "ENC_TYPE_AUTO"; + case ENC_TYPE_OPEN: return "ENC_TYPE_OPEN"; + case ENC_TYPE_WEP: return "ENC_TYPE_WEP"; + case ENC_TYPE_WEP_SHARED: return "ENC_TYPE_WEP_SHARED"; + case ENC_TYPE_WPA_TKIP: return "ENC_TYPE_WPA_TKIP"; + case ENC_TYPE_WPA_AES: return "ENC_TYPE_WPA_AES"; + case ENC_TYPE_WPA_MIXED: return "ENC_TYPE_WPA_MIXED"; + case ENC_TYPE_WPA2_AES: return "ENC_TYPE_WPA2_AES"; + case ENC_TYPE_WPA2_TKIP: return "ENC_TYPE_WPA2_TKIP"; + case ENC_TYPE_WPA2_MIXED: return "ENC_TYPE_WPA2_MIXED"; + case ENC_TYPE_WPA_TKIP_ENT: return "ENC_TYPE_WPA_TKIP_ENT"; + case ENC_TYPE_WPA_AES_ENT: return "ENC_TYPE_WPA_AES_ENT"; + case ENC_TYPE_WPA_MIXED_ENT: return "ENC_TYPE_WPA_MIXED_ENT"; + case ENC_TYPE_WPA2_TKIP_ENT: return "ENC_TYPE_WPA2_TKIP_ENT"; + case ENC_TYPE_WPA2_AES_ENT: return "ENC_TYPE_WPA2_AES_ENT"; + case ENC_TYPE_WPA2_MIXED_ENT: return "ENC_TYPE_WPA2_MIXED_ENT"; + case ENC_TYPE_WPS_OPEN: return "ENC_TYPE_WPS_OPEN"; + case ENC_TYPE_WPS_SECURE: return "ENC_TYPE_WPS_SECURE"; + case ENC_TYPE_IBSS_OPEN: return "ENC_TYPE_IBSS_OPEN"; + default: return "UNKNOWN"; + } +} +#endif diff --git a/feather_sensor_transmit/src/config.h b/feather_sensor_transmit/src/config.h new file mode 100644 index 0000000..1a10ad2 --- /dev/null +++ b/feather_sensor_transmit/src/config.h @@ -0,0 +1,39 @@ +#ifndef CONFIG_H +#define CONFIG_H + +#define CONFIG_VERSION 6 + +typedef struct { + uint16_t version; + int32_t reading_interval_s; + + float temperature_offset_f; + + uint8_t cell_configured; + char hub_id[50]; + char cell_id[50]; + + uint8_t wifi_configured; + char wifi_ssid[50]; + char wifi_pass[200]; + + uint8_t endpoint_configured; + char endpoint_domain[100]; + char endpoint_path[100]; +} CONFIG_struct; + +typedef union { + CONFIG_struct data; + uint8_t raw[sizeof(CONFIG_struct)]; +} CONFIG_union; + +extern CONFIG_union CONFIG; + +void write_config(); +bool read_config(); +void set_default_config(); +void enter_configuration(); +uint32_t get_last_reading_time(); +void update_last_reading_time(uint32_t timestamp); + +#endif diff --git a/feather_sensor_transmit/src/heatseek_sensor.ino b/feather_sensor_transmit/src/heatseek_sensor.ino new file mode 100644 index 0000000..4f28524 --- /dev/null +++ b/feather_sensor_transmit/src/heatseek_sensor.ino @@ -0,0 +1,166 @@ +#include +#include +#include +#include +#include "user_config.h" +#include "transmit.h" +#include "config.h" +#include "watchdog.h" +#include "rtc.h" + +static DHT dht(DHT_DATA, DHT22); +uint32_t startup_millis = 0; + +void setup() { + watchdog_init(); + + Serial.begin(9600); + delay(2000); + + Serial.print("initializing heatseek data logger: "); + #ifdef TRANSMITTER_WIFI + Serial.println("WIFI"); + #else + Serial.println("cellular"); + #endif + + initialize_sd(); + rtc_initialize(); + + dht.begin(); + + if (!read_config()) set_default_config(); + + watchdog_feed(); + + startup_millis = millis(); +} + +void loop() { + float temperature_f; + float humidity; + float heat_index; + + int32_t current_time = rtc.now().unixtime(); + int32_t last_reading_time = get_last_reading_time(); + int32_t time_since_last_reading = current_time - last_reading_time; + + char command = Serial.read(); + if (command == 'C') { + enter_configuration(); + } + + Serial.print("Time since last reading: "); + Serial.print(time_since_last_reading); + Serial.print(", reading_interval: "); + Serial.print(CONFIG.data.reading_interval_s); + Serial.print(". Code version: "); + Serial.print(CODE_VERSION); + Serial.println(". Press 'C' to enter config."); + + if (millis() - startup_millis < 15000) { + Serial.println("Allowing 15 seconds to enter config mode [C] before taking first reading."); + watchdog_feed(); + delay(2000); + return; + } + + if (CONFIG.data.reading_interval_s - time_since_last_reading > SEND_SAVED_READINGS_THRESHOLD) { + Serial.println("Checking for queued temperature readings"); + watchdog_feed(); + transmit_queued_temps(); + delay(2000); + watchdog_feed(); + return; + } else if (time_since_last_reading < CONFIG.data.reading_interval_s) { + delay(2000); + watchdog_feed(); + return; + } + + watchdog_feed(); + + read_temperatures(&temperature_f, &humidity, &heat_index); + log_to_sd(temperature_f, humidity, heat_index, current_time); + + watchdog_feed(); + + update_last_reading_time(current_time); + watchdog_feed(); + + transmit(temperature_f, humidity, heat_index, current_time); + + watchdog_feed(); + + delay(2000); +} + +void read_temperatures(float *temperature_f, float *humidity, float *heat_index) { + while (true) { + bool success = true; + + *temperature_f = dht.readTemperature(true); + *humidity = dht.readHumidity(); + + if (!isnan(*temperature_f) && !isnan(*humidity)) { + Serial.print("Temperature (actual reading): "); + Serial.print(*temperature_f); + Serial.println(" *F"); + + *temperature_f = *temperature_f + CONFIG.data.temperature_offset_f; + Serial.print("Temperature (after calibration): "); + Serial.print(*temperature_f); + Serial.println(" *F"); + + Serial.print("Humidity: "); + Serial.print(*humidity); + Serial.println("%"); + + *heat_index = dht.computeHeatIndex(*temperature_f, *humidity); + + Serial.print("Heat index: "); + Serial.println(*heat_index); + + return; + + } else { + Serial.println("Error reading temperatures!"); + } + + delay(2000); + + // if we continue to fail to read a temperature, the watchdog will + // eventually cause a reboot + } +} + +void log_to_sd(float temperature_f, float humidity, float heat_index, uint32_t current_time) { + Serial.println("writing to SD card..."); + + File data_file; + + if (data_file = SD.open("data.csv", FILE_WRITE)) { + data_file.print(current_time); data_file.print(","); + data_file.print(temperature_f); data_file.print(","); + data_file.print(humidity); data_file.print(","); + data_file.print(heat_index); data_file.println(); + Serial.println("wrote to SD"); + data_file.close(); + } else { + Serial.println("unable to open data.csv"); + while(true); // watchdog will reboot + } +} + +void initialize_sd() { + // Stop LORA module from interfering with SPI + #ifdef TRANSMITTER_GSM + pinMode(LORA_CS, OUTPUT); + digitalWrite(LORA_CS, HIGH); + #endif + + while (!SD.begin(SD_CS)) { + Serial.println("failed to initialize SD card"); + delay(1000); // watchdog will reboot + } +} diff --git a/feather_sensor_transmit/src/rtc.cpp b/feather_sensor_transmit/src/rtc.cpp new file mode 100644 index 0000000..108127e --- /dev/null +++ b/feather_sensor_transmit/src/rtc.cpp @@ -0,0 +1,58 @@ +#include "rtc.h" +#include "watchdog.h" +#include "config.h" + +RTC_PCF8523 rtc; + +void rtc_initialize() { + if (!rtc.begin()) { + Serial.println("Couldn't find RTC"); + while (true); // watchdog will reboot + } + + if (!rtc.initialized()) { + Serial.print("RTC is NOT running! "); + Serial.println(rtc.now().unixtime()); + // TODO - this could make a web request to set and continually update the RTC + rtc_set(); + } +} + +void rtc_set() { + char timestamp[50]; + int i = 0; + bool timestamp_input = false; + uint32_t value = 0; + + while (true) { + Serial.println("Setting RTC, enter the current unix timestamp"); + + while (Serial.available()) { + char c = Serial.read(); + timestamp[i++] = c; + if (c == '\n') { timestamp_input = true; } + } + + if (timestamp_input) { + value = strtoul(timestamp, NULL, 0); + + // sanity check + if (value < 1810148331 && value > 1494614996) { + Serial.println("done setting"); + break; + } else { + Serial.println("The value you entered looks wrong - please try again"); + timestamp_input = false; + i = 0; + } + } + watchdog_feed(); + delay(2000); + } + + Serial.print("setting timestamp to: "); + Serial.println(value); + + rtc.adjust(DateTime(value)); + update_last_reading_time(0); +} diff --git a/feather_sensor_transmit/src/rtc.h b/feather_sensor_transmit/src/rtc.h new file mode 100644 index 0000000..21befff --- /dev/null +++ b/feather_sensor_transmit/src/rtc.h @@ -0,0 +1,11 @@ +#ifndef RTC_H +#define RTC_H + +#include + +extern RTC_PCF8523 rtc; + +void rtc_initialize(); +void rtc_set(); + +#endif diff --git a/feather_sensor_transmit/src/transmit.cpp b/feather_sensor_transmit/src/transmit.cpp new file mode 100644 index 0000000..69bd38f --- /dev/null +++ b/feather_sensor_transmit/src/transmit.cpp @@ -0,0 +1,513 @@ +#include "transmit.h" +#include "config.h" +#include "watchdog.h" +#include + +#ifdef HEATSEEK_BORON_LTE + TCPClient tcpClient; + Bool lteConnected = false; +#endif + +#ifdef HEATSEEK_FEATHER_WIFI_WICED + AdafruitHTTP http; + bool wifiConnected = false; + volatile bool response_received = false; + volatile bool transmit_success = false; +#endif + +#ifdef HEATSEEK_FEATHER_WIFI_M0 + WiFiClient wifiClient; + bool wifiConnected = false; +#endif + +#ifdef TRANSMITTER_GSM + #include + + HardwareSerial *fonaSerial = &Serial1; + + Adafruit_FONA fona = Adafruit_FONA(FONA_RST); + bool gsmConnected = false; +#endif + +#ifdef TRANSMITTER_GSM + bool fona_post(float temperature_f, float humidity, float heat_index, uint32_t current_time) { + fona.HTTP_POST_end(); + + uint16_t statuscode; + int16_t length; + + char url[200]; + strcpy(url, CONFIG.data.endpoint_domain); + strcat(url, CONFIG.data.endpoint_path); + + char data[200]; + + char temperature_buffer[10]; + char humidity_buffer[10]; + char heat_index_buffer[10]; + + dtostrf(temperature_f, 4, 3, temperature_buffer); + dtostrf(humidity, 4, 3, humidity_buffer); + dtostrf(heat_index, 4, 3, heat_index_buffer); + + sprintf(data, "temp=%s&humidity=%s&heat_index=%s&hub=%s&cell=%s&time=%d&sp=%d&cell_version=%s", temperature_buffer, humidity_buffer, heat_index_buffer, CONFIG.data.hub_id, CONFIG.data.cell_id, current_time, CONFIG.data.reading_interval_s, CODE_VERSION); + + Serial.print("posting to: "); Serial.println(url); + Serial.print("with data: "); Serial.println(data); + + if (!fona.HTTP_POST_start(url, F("application/x-www-form-urlencoded"), (uint8_t *) data, strlen(data), &statuscode, (uint16_t *)&length)) { + return false; + } + + Serial.println("reading status"); + + if (statuscode != 200) { + Serial.print("status not 200: "); + Serial.println(statuscode); + return false; + } + + fona.HTTP_POST_end(); + return true; + } + + void connect_to_fona() { + Serial.println('starting fona serial'); + fonaSerial->begin(4800); + + Serial.println('starting fona serial 2'); + if (!fona.begin(*fonaSerial)) { + Serial.println("Couldn't find FONA"); + while(true); // watchdog will reboot + } + + watchdog_feed(); + delay(2000); + + Serial.println('enabling FONA GPRS'); + + uint32_t start = millis(); + + while (!fona.enableGPRS(true)) { + delay(1000); + watchdog_feed(); + + if (millis() - start > 60000) { + Serial.println("failed to start FONA GPRS after 60 sec"); + while (true); + } + } + + Serial.println("Enabled FONA GRPS"); + + gsmConnected = true; + } + + bool _transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time) { + if (!CONFIG.data.cell_configured || !CONFIG.data.endpoint_configured) { + Serial.println("cannot send data - not configured"); + return false; + } + + if (!gsmConnected) connect_to_fona(); + watchdog_feed(); + + int transmit_attempts = 1; + + while (!fona_post(temperature_f, humidity, heat_index, current_time)) { + Serial.print("failed to POST, trying again... attempt #"); + Serial.println(transmit_attempts); + + if (transmit_attempts < 4) { + transmit_attempts++; + watchdog_feed(); + delay(500); + } else { + while (true); + } + } + + return true; + } +#endif + +#ifdef HEATSEEK_FEATHER_WIFI_WICED + void force_wifi_reconnect(void) { + wifiConnected = false; + } + + void receive_callback(void) { + http.respParseHeader(); + int status_received = http.respStatus(); + + Serial.printf("transmitted - received status: (%d) \n", status_received); + + http.stop(); + response_received = true; + transmit_success = (status_received == 200); + } + + void connect_to_wifi() { + Serial.print("Please wait while connecting to:"); + Serial.print(CONFIG.data.wifi_ssid); + Serial.println("... "); + + if (Feather.connect(CONFIG.data.wifi_ssid, CONFIG.data.wifi_pass)) { + Serial.println("Connected!"); + wifiConnected = true; + } else { + Serial.printf("Failed! %s (%d) \n", Feather.errstr()); + } + Serial.println(); + + if (!Feather.connected()) { return; } + + // Connected: Print network info + Feather.printNetwork(); + + // Tell the HTTP client to auto print error codes and halt on errors + http.err_actions(true, true); + + // Set HTTP client verbose + http.verbose(true); + + // Set the callback handlers + http.setReceivedCallback(receive_callback); + } + + bool _transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time) { + if (!CONFIG.data.cell_configured || !CONFIG.data.wifi_configured || !CONFIG.data.endpoint_configured) { + Serial.println("cannot send data - not configured"); + return false; + } + + while (!wifiConnected) { connect_to_wifi(); } + + http.connect(CONFIG.data.endpoint_domain, PORT); // Will halt if an error occurs + + http.addHeader("User-Agent", USER_AGENT_HEADER); + http.addHeader("Connection", "close"); + http.addHeader("Content-Type", "application/x-www-form-urlencoded"); + + char time_buffer[30]; + char temperature_buffer[30]; + char humidity_buffer[30]; + char heat_index_buffer[30]; + char reading_interval_buffer[30]; + + sprintf(time_buffer, "%d", current_time); + sprintf(reading_interval_buffer, "%d", CONFIG.data.reading_interval_s); + sprintf(temperature_buffer, "%.3f", temperature_f); + sprintf(humidity_buffer, "%.3f", humidity); + sprintf(heat_index_buffer, "%.3f", heat_index); + + const char* post_data[][2] = + { + {"hub", CONFIG.data.hub_id}, + {"cell", CONFIG.data.cell_id}, + {"time", time_buffer}, + {"temp", temperature_buffer}, + {"humidity", humidity_buffer}, + {"sp", reading_interval_buffer}, + {"heat_index", heat_index_buffer}, + {"cell_version", CODE_VERSION}, + }; + int param_count = 8; + + response_received = false; + transmit_success = false; + + http.post(CONFIG.data.endpoint_domain, CONFIG.data.endpoint_path, post_data, param_count); // Will halt if an error occurs + + while (!response_received || !transmit_success); // Hang if transmit doesn't complete or fails + + return true; + } +#endif + +#ifdef HEATSEEK_FEATHER_WIFI_M0 + void force_wifi_reconnect(void) { + if (wifiConnected) { + wifiConnected = false; + WiFi.end(); + } + } + + void connect_to_wifi() { + WiFi.setPins(8, 7, 4, 2); + + Serial.print("Please wait while connecting to:"); + Serial.print(CONFIG.data.wifi_ssid); + Serial.println("... "); + + int status = WL_IDLE_STATUS; + + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(CONFIG.data.wifi_ssid, CONFIG.data.wifi_pass); + + while (status != WL_CONNECTED) { + delay(1000); + Serial.println("Establishing connection..."); + } + + wifiConnected = true; + Serial.println("Connected to WiFi"); + + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); + + watchdog_feed(); + } + + bool _transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time) { + if (!CONFIG.data.cell_configured || !CONFIG.data.wifi_configured || !CONFIG.data.endpoint_configured) { + Serial.println("cannot send data - not configured"); + return false; + } + + if (!wifiConnected) { connect_to_wifi(); } + + HttpClient client = HttpClient(wifiClient, CONFIG.data.endpoint_domain, 80); + + String contentType = "application/x-www-form-urlencoded"; + String data = "temp=" + String(temperature_f, 3) + "&humidity=" + String(humidity, 3) + "&heat_index=" + String(heat_index, 3) + "&hub=" + CONFIG.data.hub_id + "&cell=" + CONFIG.data.cell_id + "&time=" + current_time + "&sp=" + CONFIG.data.reading_interval_s + "&cell_version=" + CODE_VERSION; + + Serial.print("Posting data: "); + Serial.println(data); + + client.post(CONFIG.data.endpoint_path, contentType, data); + + int statusCode = client.responseStatusCode(); + String response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + return statusCode == 200; + } +#endif + +#ifdef HEATSEEK_BORON_LTE + // Function to reconnect to LTE? + void force_lte_reconnect(void); + + // Function to connect to Particle Cloud + void connect_to_lte(){ + // Configure the connection here. + Serial.println(“Establishing connection...”); + // Connect to LTE network here. + Serial.println(“Connected to LTE”); + watchdog_feed(); + } + + // Function to transmit + bool _transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time){ + // If cell / API endpoint not configured, indicate error + if (!CONFIG.data.cell_configured || !CONFIG.data.endpoint_configured) { + Serial.println("cannot send data - not configured"); + return false; + } + + // If not connected, connect + if(!lteConnected){ + connect_to_lte(); + } + + // Set up TCPClient + // Do some error checking + client.connect(CONFIG.data.endpoint_domain, 80); + String contentType = "application/x-www-form-urlencoded"; + String data = "temp=" + String(temperature_f, 3) + "&humidity=" + String(humidity, 3) + "&heat_index=" + String(heat_index, 3) + "&hub=" + CONFIG.data.hub_id + "&cell=" + CONFIG.data.cell_id + "&time=" + current_time + "&sp=" + CONFIG.data.reading_interval_s + "&cell_version=" + CODE_VERSION; + Serial.print("Posting data: "); + Serial.println(data); + client.write(CONFIG.data.endpoint_path, contentType, data); + int statusCode = client.status(); + int numCharacters = client.available(); + string response = ""; + for (int i = 0; i < numCharacters; i++) + { + response.append(client.read()); + } + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + return statusCode == 200; + // Load data + // Post data via TCPClient + // Done. +} +#endif + +typedef struct { + float temperature_f; + float humidity; + float heat_index; +} temp_data_struct; + +typedef union { + temp_data_struct data; + uint8_t raw[sizeof(temp_data_struct)]; +} temp_data; + +// Create a file on the SD card representing a temperature reading +// The file name is the unix timestamp, however, due to FAT naming conventions, +// we have to place a period in it. e.g. 1500985299 -> 1500985.299 +// The content of the file is the binary reading data struct. +void queue_transmission(char *filename, temp_data temp, uint32_t current_time) { + char file_path[50]; + char timestamp[50]; + char timestamp_first_half[50]; + char timestamp_last_half[50]; + + // FAT only allows 8 character names, so we make the last 3 digits of the + // timestamp the file "extension" + sprintf(timestamp, "%d", current_time); + strncpy(timestamp_first_half, timestamp, 7); + timestamp_first_half[7] = '\0'; + strncpy(timestamp_last_half, timestamp+7, 3); + timestamp_last_half[3] = '\0'; + + sprintf(filename, "%s.%s", timestamp_first_half, timestamp_last_half); + sprintf(file_path, "pending/%s", filename); + + File temperature_file; + SD.mkdir("pending"); + if (temperature_file = SD.open(file_path, FILE_WRITE | O_TRUNC)) { + temperature_file.write(temp.raw, sizeof(temp)); + temperature_file.close(); + } else { + Serial.println("unable to write temperature"); + while(true); // watchdog will reboot + } +} + +// Take a filename for a reading, read the temperature data and +// transmit it. Then delete the file when the transfer is successful. +void transmit_queued_temp(char *filename) { + watchdog_feed(); + + File temperature_file; + temp_data temperature; + char read_time_buffer[100]; + char file_path[100]; + sprintf(file_path, "pending/%s", filename); + + Serial.print("transfering: "); + Serial.println(filename); + + strncpy(read_time_buffer, filename, 7); + strncpy(read_time_buffer+7, filename+8, 3); + read_time_buffer[10] = '\0'; + + uint32_t read_time = strtoul(read_time_buffer, NULL, 0); + + if (temperature_file = SD.open(file_path, FILE_READ)) { + int read_size = temperature_file.read(temperature.raw, sizeof(temperature)); + + if (sizeof(temperature) == read_size) { + bool transmit_success = _transmit(temperature.data.temperature_f, temperature.data.humidity, temperature.data.heat_index, read_time); + + temperature_file.close(); + delay(100); + + if (transmit_success) { + Serial.println("transferred."); + + if (SD.remove(file_path)) { + Serial.println("removed."); + } else { + Serial.println("failed to remove file"); + } + } else { + Serial.println("failed to transfer"); + } + } else { + Serial.print("file incorrect size - expected: "); + Serial.print(sizeof(temperature)); + Serial.print(", got: "); + Serial.println(read_size); + } + } else { + Serial.print("failed to open: "); + Serial.println(filename); + } + + watchdog_feed(); +} + +void transmit_queued_temps() { + char filename[100]; + File pending_dir = SD.open("pending"); + int temps_transfered_count = 0; + + while (temps_transfered_count < TRANSMITS_PER_LOOP) { + File entry = pending_dir.openNextFile(); + if (!entry) { break; } // No more files + + strcpy(filename, entry.name()); + entry.close(); + + transmit_queued_temp(filename); + temps_transfered_count += 1; + } + + pending_dir.close(); +} + +void clear_queued_transmissions() { + File pending_dir = SD.open("pending"); + + Serial.println("==== Removing queued temperature files"); + while (true) { + watchdog_feed(); + + File entry = pending_dir.openNextFile(); + if (!entry) { break; } // No more files + + char filename[100]; + strcpy(filename, entry.name()); + entry.close(); + + char file_path[100]; + sprintf(file_path, "pending/%s", filename); + + if (SD.remove(file_path)) { + Serial.println("removed queued temperature file."); + } else { + Serial.println("failed to remove queued temperature file."); + } + } + + Serial.println("===="); + + pending_dir.close(); +} + +void transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time) { + watchdog_feed(); + + temp_data temp; + temp.data.temperature_f = temperature_f; + temp.data.humidity = humidity; + temp.data.heat_index = heat_index; + + char filename[100]; + queue_transmission(filename, temp, current_time); + watchdog_feed(); + delay(1000); + + Serial.print("created file: "); + Serial.println(filename); + + transmit_queued_temp(filename); + transmit_queued_temps(); +} diff --git a/feather_sensor_transmit/src/transmit.h b/feather_sensor_transmit/src/transmit.h new file mode 100644 index 0000000..a817d47 --- /dev/null +++ b/feather_sensor_transmit/src/transmit.h @@ -0,0 +1,58 @@ +#ifndef TRANSMIT_H +#define TRANSMIT_H + +#define CODE_VERSION "F-1.2.0" + +#include "user_config.h" + +#ifdef HEATSEEK_FEATHER_CELL_M0 + #define TRANSMITTER_GSM +#else + #define TRANSMITTER_WIFI +#endif + +#ifdef HEATSEEK_FEATHER_WIFI_WICED + #include + #include + #include + + #define DHT_DATA PC2 + #define SD_CS PB4 + + #define TRANSMITS_PER_LOOP 20 +#endif + +#ifdef HEATSEEK_FEATHER_WIFI_M0 + #include + #include + + #define DHT_DATA A2 + #define SD_CS 10 + + #define TRANSMITS_PER_LOOP 20 +#endif + +#ifdef TRANSMITTER_GSM + #include "Adafruit_FONA.h" + #include + + #define DHT_DATA A2 + #define SD_CS 10 + #define FONA_RST A4 + #define LORA_CS 8 + + #define TRANSMITS_PER_LOOP 5 +#endif + +#define SEND_SAVED_READINGS_THRESHOLD (10 * 60) +#define USER_AGENT_HEADER "curl/7.45.0" +#define PORT 80 + +void transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time); +void transmit_queued_temps(); +void clear_queued_transmissions(); +#ifdef TRANSMITTER_WIFI +void force_wifi_reconnect(); +#endif + +#endif diff --git a/feather_sensor_transmit/src/user_config.h b/feather_sensor_transmit/src/user_config.h new file mode 100644 index 0000000..6011268 --- /dev/null +++ b/feather_sensor_transmit/src/user_config.h @@ -0,0 +1,4 @@ +//#define HEATSEEK_FEATHER_CELL_M0 +//#define HEATSEEK_FEATHER_WIFI_M0 +#define HEATSEEK_BORON_LTE +//#define HEATSEEK_FEATHER_WIFI_WICED diff --git a/feather_sensor_transmit/src/watchdog.cpp b/feather_sensor_transmit/src/watchdog.cpp new file mode 100644 index 0000000..090b286 --- /dev/null +++ b/feather_sensor_transmit/src/watchdog.cpp @@ -0,0 +1,25 @@ +#include "watchdog.h" + +#if defined(HEATSEEK_FEATHER_WIFI_M0) || defined(TRANSMITTER_GSM) + #include +#endif + +void watchdog_init() { + #ifdef HEATSEEK_FEATHER_WIFI_WICED + iwdg_init(IWDG_PRE_256, 3500); // 30 second watchdog, 40kHz processor + #endif + + #if defined(HEATSEEK_FEATHER_WIFI_M0) || defined(TRANSMITTER_GSM) + Watchdog.enable(16000); // 16 seconds (this is the max supported) + #endif +} + +void watchdog_feed() { + #ifdef HEATSEEK_FEATHER_WIFI_WICED + iwdg_feed(); + #endif + + #if defined(HEATSEEK_FEATHER_WIFI_M0) || defined(TRANSMITTER_GSM) + Watchdog.reset(); + #endif +} diff --git a/feather_sensor_transmit/src/watchdog.h b/feather_sensor_transmit/src/watchdog.h new file mode 100644 index 0000000..7acb4e3 --- /dev/null +++ b/feather_sensor_transmit/src/watchdog.h @@ -0,0 +1,9 @@ +#ifndef WATCHDOG_H +#define WATCHDOG_H + +#include "transmit.h" + +void watchdog_init(); +void watchdog_feed(); + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/c_cpp_properties.json b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..97a3fc5 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/c_cpp_properties.json @@ -0,0 +1,18 @@ +{ + "configurations": [ + { + "name": "Win32", + "includePath": [ + "{$workspaceFolder}/**" + ], + "defines": [ + "_DEBUG", + "UNICODE", + "_UNICODE" + ], + "intelliSenseMode": "gcc-x64", + "configurationProvider": "particle.particle-vscode-core" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/launch.json b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/launch.json new file mode 100644 index 0000000..4532e35 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/launch.json @@ -0,0 +1,92 @@ +{ + "version": "0.1.0", + "configurations": [ + { + "type": "cortex-debug", + "request": "attach", + "name": "Particle Debugger (photon, p1, electron)", + "servertype": "openocd", + "interface": "swd", + "device": "STM32F205RG", + "cwd": "${workspaceRoot}", + "executable": "${command:particle.getDebuggerExecutable}", + "preLaunchTask": "Particle: Flash application for debug (local)", + "armToolchainPath": "${command:particle.getDebuggerCompilerDir}", + "svdFile": "${command:particle.getDebuggerSVDFile}", + "searchDir": [ + "${command:particle.getDebuggerSearchDir}" + ], + "configFiles": [ + "interface/cmsis-dap.cfg", + "target/stm32f2x.cfg" + ], + "postAttachCommands": [ + "monitor reset halt" + ], + "windows": { + "configFiles": [ + "interface\\cmsis-dap.cfg", + "target\\stm32f2x.cfg" + ] + } + }, + { + "type": "cortex-debug", + "request": "attach", + "name": "Particle Debugger (argon, boron / bsom, xenon)", + "servertype": "openocd", + "interface": "swd", + "device": "nRF52840_xxAA", + "cwd": "${workspaceRoot}", + "executable": "${command:particle.getDebuggerExecutable}", + "preLaunchTask": "Particle: Flash application for debug (local)", + "armToolchainPath": "${command:particle.getDebuggerCompilerDir}", + "svdFile": "${command:particle.getDebuggerSVDFile}", + "searchDir": [ + "${command:particle.getDebuggerSearchDir}" + ], + "configFiles": [ + "interface/cmsis-dap.cfg", + "target/nrf52-particle.cfg" + ], + "postAttachCommands": [ + "monitor reset halt" + ], + "windows": { + "configFiles": [ + "interface\\cmsis-dap.cfg", + "target\\nrf52-particle.cfg" + ] + } + }, + { + "type": "cortex-debug", + "request": "attach", + "name": "Particle Programmer Shield v1.0 (photon, p1, electron)", + "servertype": "openocd", + "interface": "swd", + "device": "STM32F205RG", + "cwd": "${workspaceRoot}", + "executable": "${command:particle.getDebuggerExecutable}", + "preLaunchTask": "Particle: Flash application for debug (local)", + "armToolchainPath": "${command:particle.getDebuggerCompilerDir}", + "svdFile": "${command:particle.getDebuggerSVDFile}", + "searchDir": [ + "${command:particle.getDebuggerSearchDir}" + ], + "configFiles": [ + "interface/particle-ftdi.cfg", + "target/stm32f2x.cfg" + ], + "postAttachCommands": [ + "monitor reset halt" + ], + "windows": { + "configFiles": [ + "interface\\particle-ftdi.cfg", + "target\\stm32f2x.cfg" + ] + } + } + ] +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/settings.json b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/settings.json new file mode 100644 index 0000000..52250e9 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/settings.json @@ -0,0 +1,11 @@ +{ + "extensions.ignoreRecommendations": true, + "C_Cpp.default.configurationProvider": "particle.particle-vscode-core", + "cortex-debug.openocdPath": "${command:particle.getDebuggerOpenocdPath}", + "files.associations": { + "*.ino": "cpp" + }, + "particle.targetDevice": "e00fce684c6a4946ca9fecd1", + "particle.firmwareVersion": "1.1.0", + "particle.targetPlatform": "boron" +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/README.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/README.md new file mode 100644 index 0000000..2e3b0f4 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/README.md @@ -0,0 +1,35 @@ +# feather_sensor_transmit_lte + +A Particle project named feather_sensor_transmit_lte + +## Welcome to your project! + +Every new Particle project is composed of 3 important elements that you'll see have been created in your project directory for feather_sensor_transmit_lte. + +#### ```/src``` folder: +This is the source folder that contains the firmware files for your project. It should *not* be renamed. +Anything that is in this folder when you compile your project will be sent to our compile service and compiled into a firmware binary for the Particle device that you have targeted. + +If your application contains multiple files, they should all be included in the `src` folder. If your firmware depends on Particle libraries, those dependencies are specified in the `project.properties` file referenced below. + +#### ```.ino``` file: +This file is the firmware that will run as the primary application on your Particle device. It contains a `setup()` and `loop()` function, and can be written in Wiring or C/C++. For more information about using the Particle firmware API to create firmware for your Particle device, refer to the [Firmware Reference](https://docs.particle.io/reference/firmware/) section of the Particle documentation. + +#### ```project.properties``` file: +This is the file that specifies the name and version number of the libraries that your project depends on. Dependencies are added automatically to your `project.properties` file when you add a library to a project using the `particle library add` command in the CLI or add a library in the Desktop IDE. + +## Adding additional files to your project + +#### Projects with multiple sources +If you would like add additional files to your application, they should be added to the `/src` folder. All files in the `/src` folder will be sent to the Particle Cloud to produce a compiled binary. + +#### Projects with external libraries +If your project includes a library that has not been registered in the Particle libraries system, you should create a new folder named `/lib//src` under `/` and add the `.h`, `.cpp` & `library.properties` files for your library there. Read the [Firmware Libraries guide](https://docs.particle.io/guide/tools-and-features/libraries/) for more details on how to develop libraries. Note that all contents of the `/lib` folder and subfolders will also be sent to the Cloud for compilation. + +## Compiling your project + +When you're ready to compile your project, make sure you have the correct Particle device target selected and run `particle compile ` in the CLI or click the Compile button in the Desktop IDE. The following files in your project folder will be sent to the compile service: + +- Everything in the `/src` folder, including your `.ino` application file +- The `project.properties` file for your project +- Any libraries stored under `lib//src` diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/boron_firmware_1574447345899.bin b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/boron_firmware_1574447345899.bin new file mode 100644 index 0000000000000000000000000000000000000000..544964835a60d84338704d5bd1234e633fc8cef4 GIT binary patch literal 5592 zcmd5=e{d9c6@PoXm%IEpxKOBP0?ghmXAchWXj;9NIunv~6LJX@soEAh-ZeSgND{6g zv1!FINUL;er>&(UE!JrT9O{V8)t*Cu?Ku{m))u|AD0ILPwKcS~y1|xP@@xHkckdS& z$G;rMo%!7Nz3;yFzVF9(-}jqPy^BtM&P7CJ!Uh zK!cF^yzUR}Y38oi#}d%H4mwk}Vr^~yVJGAzT|MutCvA&L+6N<~T^OOk;fW!wzC6*) zNqi#FOyo?JML4f#7ioW(5lqU``Q1yD9>m(rmvCxM`<%AGF3wBZ$r;WoLOL_E{=@qc zq&+_!*hQFsWd^etkDK%A`7qXf7Cz-|kfy^YTclR0Rk+8UYMYJ6+9uz1CBJDFzjqdY zW)@%jl`HivK2Wf~$$Ver_s-(a%;IaeFndM$O|$sg?knG0@!V8c?~EB=k*_uVE%H`; zMc#_9$XoFhc`KeGZ~0&3Eqk4X_4k_Vw-oqVbNwQ3$rpJm-Xg!rjIV?@?Rg6JEd3&X z#QL z%y|`9Tw~b0L$Xh1^lF2CutWCBwDP(PExmShn_>&vG8Mt{%(8Qb$7$|0nY+8fvapJ@ zHz&k%BbZs7>F=ucaR*7OnkkbW*5`+~L&CU|_gv>uZdaDc{4bq#`x+L=*-`GfvV)F8 zqB#rFv3{i1ne9aJLH}+LHRT<%263uJ+adyJ?r&RV^ zY5sc5Uzhn?le67u+D@cy-Y&>aDr4KVdU}gLmt7BFBQl(nsgz8aNHTRT~bheg9%3HkP z{$N(Ja>~)_SZi+~%{|Gtgw^-o!F>WyfLj4plXsendwl@evpU721!^xSwo@O$nBVpH zs>NN8`$eI9+*#172W9Q`M)N(huu_H3Z2|u>nY;xY#Z4>O>$z`tj}MLTD9Lc$*Rj}k~&!4x9yACvCBEhDSP`n`m14OzbUhD zql?_B`94U(uTgU@gnQAqhq;6Jf()w;ZnF+;lhGviW3TLJF|wm(6f1Zho_A8@OmPPqmj8f+bWb&wugiX6UY@QB%++KH}p6*?Se z_BYmxoT;iv9eU912Cvk1?P;b!`B`VA12d1#v5(~Q^Uyq zY?6z3qE2-=?#Yf6N%VM)yj8o0GqTYse)vvZm?Uzf8h2F$otayL<)h^|WmhN7Hy1q3 zM)n<}>|CkV%{i^}sE-?Kd~Fg{*Un8iB3C6vnfZVYf!d}g$;-E>=iT^EN@H0ZwKgVdfGcDlU(A5M^lPdI*wMo)`IuXRa@X7(~ z4c2XNcBs6v7iUN)_0Vu7_VUB}5;wPOPrAbA8kdBhOsculLH$*Y!yG!fQVn?~DgkD+D@)oEnP*$IrYf3U(6Gw2K z<1DvwS%r1GkxQI=xqdm<{7wfi-?=KsZJvGI65odM+fB$^pFr`B|eLwW;L9@Lv7klT) zsX%i7cqMNOa;Hgjt44MhJNdU$&Lp?|(pyHhdK%}-v}zTQO6h4oUbN&HRv~T^nB2n96hf@#$6&ar$nZzM5dxdhVA)oi5*{w9kImD;u4vKB{DT7GAx$7&n%XFTr8G+Tr8Hn42vZ%!(z$H zFrU8gmd?fwiT|wHng?x)*cf`VK0zHA3uhO|7 zEt?$m)NtWM^CJB3=XT%$;6b4Dd7#Nfj{r{s`+!5h2=FUl6nG2xEARo3e}cFxdx4Ju zE`S3*y4gkV0)GZh0VjY`9oA>AVfVS*!}``C-~k{GJPbSmJPjNG^3OY<%UfKu0QdsV zrg8AoKo;OJH-_;7kbgdgJBth8ff2mV0vCWk0jGcyz{^0XZ|t7)9Iz8$YkVE!mw~Oo zKHwf82IQaSRu|m>tOo8Ne=tfOAR z?uqsFQoOHkYabTw?dqUdcXvKH7{Af(q5)tF5Cc93tOY&;Tn_{RFHl;867~No*$8VN zUxU4X{rDF4sTXyuMvYehYk+e2@gVR=;MH|5YG04{x47u{KIr~kO#?Ku+fSs8q`McqAq MGC(&!fBm2T1#!eoE&u=k literal 0 HcmV?d00001 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/boron_firmware_1574729317031.bin b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/boron_firmware_1574729317031.bin new file mode 100644 index 0000000000000000000000000000000000000000..544964835a60d84338704d5bd1234e633fc8cef4 GIT binary patch literal 5592 zcmd5=e{d9c6@PoXm%IEpxKOBP0?ghmXAchWXj;9NIunv~6LJX@soEAh-ZeSgND{6g zv1!FINUL;er>&(UE!JrT9O{V8)t*Cu?Ku{m))u|AD0ILPwKcS~y1|xP@@xHkckdS& z$G;rMo%!7Nz3;yFzVF9(-}jqPy^BtM&P7CJ!Uh zK!cF^yzUR}Y38oi#}d%H4mwk}Vr^~yVJGAzT|MutCvA&L+6N<~T^OOk;fW!wzC6*) zNqi#FOyo?JML4f#7ioW(5lqU``Q1yD9>m(rmvCxM`<%AGF3wBZ$r;WoLOL_E{=@qc zq&+_!*hQFsWd^etkDK%A`7qXf7Cz-|kfy^YTclR0Rk+8UYMYJ6+9uz1CBJDFzjqdY zW)@%jl`HivK2Wf~$$Ver_s-(a%;IaeFndM$O|$sg?knG0@!V8c?~EB=k*_uVE%H`; zMc#_9$XoFhc`KeGZ~0&3Eqk4X_4k_Vw-oqVbNwQ3$rpJm-Xg!rjIV?@?Rg6JEd3&X z#QL z%y|`9Tw~b0L$Xh1^lF2CutWCBwDP(PExmShn_>&vG8Mt{%(8Qb$7$|0nY+8fvapJ@ zHz&k%BbZs7>F=ucaR*7OnkkbW*5`+~L&CU|_gv>uZdaDc{4bq#`x+L=*-`GfvV)F8 zqB#rFv3{i1ne9aJLH}+LHRT<%263uJ+adyJ?r&RV^ zY5sc5Uzhn?le67u+D@cy-Y&>aDr4KVdU}gLmt7BFBQl(nsgz8aNHTRT~bheg9%3HkP z{$N(Ja>~)_SZi+~%{|Gtgw^-o!F>WyfLj4plXsendwl@evpU721!^xSwo@O$nBVpH zs>NN8`$eI9+*#172W9Q`M)N(huu_H3Z2|u>nY;xY#Z4>O>$z`tj}MLTD9Lc$*Rj}k~&!4x9yACvCBEhDSP`n`m14OzbUhD zql?_B`94U(uTgU@gnQAqhq;6Jf()w;ZnF+;lhGviW3TLJF|wm(6f1Zho_A8@OmPPqmj8f+bWb&wugiX6UY@QB%++KH}p6*?Se z_BYmxoT;iv9eU912Cvk1?P;b!`B`VA12d1#v5(~Q^Uyq zY?6z3qE2-=?#Yf6N%VM)yj8o0GqTYse)vvZm?Uzf8h2F$otayL<)h^|WmhN7Hy1q3 zM)n<}>|CkV%{i^}sE-?Kd~Fg{*Un8iB3C6vnfZVYf!d}g$;-E>=iT^EN@H0ZwKgVdfGcDlU(A5M^lPdI*wMo)`IuXRa@X7(~ z4c2XNcBs6v7iUN)_0Vu7_VUB}5;wPOPrAbA8kdBhOsculLH$*Y!yG!fQVn?~DgkD+D@)oEnP*$IrYf3U(6Gw2K z<1DvwS%r1GkxQI=xqdm<{7wfi-?=KsZJvGI65odM+fB$^pFr`B|eLwW;L9@Lv7klT) zsX%i7cqMNOa;Hgjt44MhJNdU$&Lp?|(pyHhdK%}-v}zTQO6h4oUbN&HRv~T^nB2n96hf@#$6&ar$nZzM5dxdhVA)oi5*{w9kImD;u4vKB{DT7GAx$7&n%XFTr8G+Tr8Hn42vZ%!(z$H zFrU8gmd?fwiT|wHng?x)*cf`VK0zHA3uhO|7 zEt?$m)NtWM^CJB3=XT%$;6b4Dd7#Nfj{r{s`+!5h2=FUl6nG2xEARo3e}cFxdx4Ju zE`S3*y4gkV0)GZh0VjY`9oA>AVfVS*!}``C-~k{GJPbSmJPjNG^3OY<%UfKu0QdsV zrg8AoKo;OJH-_;7kbgdgJBth8ff2mV0vCWk0jGcyz{^0XZ|t7)9Iz8$YkVE!mw~Oo zKHwf82IQaSRu|m>tOo8Ne=tfOAR z?uqsFQoOHkYabTw?dqUdcXvKH7{Af(q5)tF5Cc93tOY&;Tn_{RFHl;867~No*$8VN zUxU4X{rDF4sTXyuMvYehYk+e2@gVR=;MH|5YG04{x47u{KIr~kO#?Ku+fSs8q`McqAq MGC(&!fBm2T1#!eoE&u=k literal 0 HcmV?d00001 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/LICENSE.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/LICENSE.txt new file mode 100644 index 0000000..e69de29 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/README.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/README.md new file mode 100644 index 0000000..d32afdc --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/README.md @@ -0,0 +1,15 @@ +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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino new file mode 100644 index 0000000..4820f2e --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino @@ -0,0 +1,84 @@ +// 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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/examples/DHTtester/DHTtester.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/examples/DHTtester/DHTtester.ino new file mode 100644 index 0000000..ae6c41a --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/examples/DHTtester/DHTtester.ino @@ -0,0 +1,69 @@ +// 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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/keywords.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/keywords.txt new file mode 100644 index 0000000..146d4fa --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/keywords.txt @@ -0,0 +1,22 @@ +########################################### +# 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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/library.properties b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/library.properties new file mode 100644 index 0000000..8c247f5 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/library.properties @@ -0,0 +1,9 @@ +name=DHT +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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT.cpp new file mode 100644 index 0000000..86ad91c --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT.cpp @@ -0,0 +1,259 @@ +/* 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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT.h new file mode 100644 index 0000000..d81f6db --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT.h @@ -0,0 +1,75 @@ +/* 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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT_U.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT_U.cpp new file mode 100644 index 0000000..efc7963 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT_U.cpp @@ -0,0 +1,179 @@ +// 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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT_U.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT_U.h new file mode 100644 index 0000000..fcf66ad --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT_U.h @@ -0,0 +1,78 @@ +// 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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/LICENSE.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/LICENSE.md new file mode 100644 index 0000000..557757f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2011..2017 Bill Greiman + +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. \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/README.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/README.md new file mode 100644 index 0000000..606fd97 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/README.md @@ -0,0 +1,42 @@ +The Arduino SdFat library provides read/write access to FAT16/FAT32 +file systems on SD/SDHC flash cards. + +SdFat requires Arduino 1.6x or greater. + +Key changes: + +Support for multiple SPI ports now uses a pointer to a SPIClass object. + +See the STM32Test example. +``` +explicit SdFat(SPIClass* spiPort); +\\ or +explicit SdFatEX(SPIClass* spiPort); +``` + +Open flags now follow POSIX conventions. O_RDONLY is the same as O_READ and O_WRONLY is the +same as O_WRITE. One and only one of of the mode flags, O_RDONLY, O_RDWR, or +O_WRONLY is required. + +Open flags for Particle Gen3 and ARM boards are now defined by fcntl.h. +See SdFatConfig.h for options. + +Support for particle Gen3 devices. + +New cluster allocation algorithm. + +Please read changes.txt and the html documentation in the extras folder for more information. + +Please report problems as issues. + +A number of configuration options can be set by editing SdFatConfig.h +define macros. See the html documentation for details + +Please read the html documentation for this library. Start with +html/index.html and read the Main Page. Next go to the Classes tab and +read the documentation for the classes SdFat, SdFatEX, SdBaseFile, +SdFile, File, StdioStream, ifstream, ofstream, and others. + +Please continue by reading the html documentation in SdFat/extras/html + +Updated 28 Dec 2018 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/AnalogLogger/AnalogLogger.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/AnalogLogger/AnalogLogger.ino new file mode 100644 index 0000000..b65c5ab --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/AnalogLogger/AnalogLogger.ino @@ -0,0 +1,197 @@ +// A simple data logger for the Arduino analog pins with optional DS1307 +// uses RTClib from https://github.com/adafruit/RTClib +#include +#include "SdFat.h" +#include "sdios.h" +#include "FreeStack.h" + +#define SD_CHIP_SELECT SS // SD chip select pin +#define USE_DS1307 0 // set nonzero to use DS1307 RTC +#define LOG_INTERVAL 1000 // mills between entries +#define SENSOR_COUNT 3 // number of analog pins to log +#define ECHO_TO_SERIAL 1 // echo data to serial port if nonzero +#define WAIT_TO_START 1 // Wait for serial input in setup() +#define ADC_DELAY 10 // ADC delay for high impedence sensors + +// file system object +SdFat sd; + +// text file for logging +ofstream logfile; + +// Serial print stream +ArduinoOutStream cout(Serial); + +// buffer to format data - makes it eaiser to echo to Serial +char buf[80]; +//------------------------------------------------------------------------------ +#if SENSOR_COUNT > 6 +#error SENSOR_COUNT too large +#endif // SENSOR_COUNT +//------------------------------------------------------------------------------ +// store error strings in flash to save RAM +#define error(s) sd.errorHalt(F(s)) +//------------------------------------------------------------------------------ +#if USE_DS1307 +// use RTClib from Adafruit +// https://github.com/adafruit/RTClib + +// The Arduino IDE has a bug that causes Wire and RTClib to be loaded even +// if USE_DS1307 is false. + +#error remove this line and uncomment the next two lines. +//#include +//#include +RTC_DS1307 RTC; // define the Real Time Clock object +//------------------------------------------------------------------------------ +// call back for file timestamps +void dateTime(uint16_t* date, uint16_t* time) { + DateTime now = RTC.now(); + + // return date using FAT_DATE macro to format fields + *date = FAT_DATE(now.year(), now.month(), now.day()); + + // return time using FAT_TIME macro to format fields + *time = FAT_TIME(now.hour(), now.minute(), now.second()); +} +//------------------------------------------------------------------------------ +// format date/time +ostream& operator << (ostream& os, DateTime& dt) { + os << dt.year() << '/' << int(dt.month()) << '/' << int(dt.day()) << ','; + os << int(dt.hour()) << ':' << setfill('0') << setw(2) << int(dt.minute()); + os << ':' << setw(2) << int(dt.second()) << setfill(' '); + return os; +} +#endif // USE_DS1307 +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + + // Wait for USB Serial. + while (!Serial) { + SysCall::yield(); + } + // F() stores strings in flash to save RAM + cout << endl << F("FreeStack: ") << FreeStack() << endl; + +#if WAIT_TO_START + cout << F("Type any character to start\n"); + while (!Serial.available()) { + SysCall::yield(); + } + // Discard input. + do { + delay(10); + } while(Serial.available() && Serial.read() >= 0); +#endif // WAIT_TO_START + +#if USE_DS1307 + // connect to RTC + Wire.begin(); + if (!RTC.begin()) { + error("RTC failed"); + } + + // set date time callback function + SdFile::dateTimeCallback(dateTime); + DateTime now = RTC.now(); + cout << now << endl; +#endif // USE_DS1307 + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(SD_CHIP_SELECT, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } + + // create a new file in root, the current working directory + char name[] = "logger00.csv"; + + for (uint8_t i = 0; i < 100; i++) { + name[6] = i/10 + '0'; + name[7] = i%10 + '0'; + if (sd.exists(name)) { + continue; + } + logfile.open(name); + break; + } + if (!logfile.is_open()) { + error("file.open"); + } + + cout << F("Logging to: ") << name << endl; + cout << F("Type any character to stop\n\n"); + + // format header in buffer + obufstream bout(buf, sizeof(buf)); + + bout << F("millis"); + +#if USE_DS1307 + bout << F(",date,time"); +#endif // USE_DS1307 + + for (uint8_t i = 0; i < SENSOR_COUNT; i++) { + bout << F(",sens") << int(i); + } + logfile << buf << endl; + +#if ECHO_TO_SERIAL + cout << buf << endl; +#endif // ECHO_TO_SERIAL +} +//------------------------------------------------------------------------------ +void loop() { + uint32_t m; + + // wait for time to be a multiple of interval + do { + m = millis(); + } while (m % LOG_INTERVAL); + + // use buffer stream to format line + obufstream bout(buf, sizeof(buf)); + + // start with time in millis + bout << m; + +#if USE_DS1307 + DateTime now = RTC.now(); + bout << ',' << now; +#endif // USE_DS1307 + + // read analog pins and format data + for (uint8_t ia = 0; ia < SENSOR_COUNT; ia++) { +#if ADC_DELAY + analogRead(ia); + delay(ADC_DELAY); +#endif // ADC_DELAY + bout << ',' << analogRead(ia); + } + bout << endl; + + // log data and flush to SD + logfile << buf << flush; + + // check for error + if (!logfile) { + error("write data failed"); + } + +#if ECHO_TO_SERIAL + cout << buf; +#endif // ECHO_TO_SERIAL + + // don't log two points in the same millis + if (m == millis()) { + delay(1); + } + + if (!Serial.available()) { + return; + } + logfile.close(); + cout << F("Done!"); + SysCall::halt(); +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/BaseExtCaseTest/BaseExtCaseTest.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/BaseExtCaseTest/BaseExtCaseTest.ino new file mode 100644 index 0000000..0212d3b --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/BaseExtCaseTest/BaseExtCaseTest.ino @@ -0,0 +1,46 @@ +/* + * Program to test Short File Name character case flags. + */ +#include +#include "SdFat.h" + +const uint8_t chipSelect = SS; + +SdFat sd; + +SdFile file; +const char* name[] = { + "low.low", "low.Mix", "low.UP", + "Mix.low", "Mix.Mix", "Mix.UP", + "UP.low", "UP.Mix", "UP.UP" +}; +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + Serial.println("type any character to start"); + while (!Serial.available()) { + SysCall::yield(); + } + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + Serial.println("begin failed"); + return; + } + for (uint8_t i = 0; i < 9; i++) { + sd.remove(name[i]); + if (!file.open(name[i], O_RDWR | O_CREAT | O_EXCL)) { + sd.errorHalt(name[i]); + } + file.println(name[i]); + + file.close(); + } + sd.ls(LS_DATE|LS_SIZE); + Serial.println("Done"); +} +//------------------------------------------------------------------------------ +void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/HelloWorld/HelloWorld.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/HelloWorld/HelloWorld.ino new file mode 100644 index 0000000..2540b06 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/HelloWorld/HelloWorld.ino @@ -0,0 +1,20 @@ +#include +#include "SdFat.h" +#include "sdios.h" + +// create a serial output stream +ArduinoOutStream cout(Serial); + +void setup() { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + delay(2000); + + cout << "Hello, World!\n"; +} + +void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/MiniSerial/MiniSerial.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/MiniSerial/MiniSerial.ino new file mode 100644 index 0000000..f8270b6 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/MiniSerial/MiniSerial.ino @@ -0,0 +1,29 @@ +// This example illustrates use of SdFat's +// minimal unbuffered AVR Serial support. +// +// This is useful for debug and saves RAM +// Will not work on Due, Leonardo, or Teensy + +#include +#include "SdFat.h" +#include "FreeStack.h" +#ifdef UDR0 // Must be AVR with serial port zero. +#include "MinimumSerial.h" + +MinimumSerial MiniSerial; + +void setup() { + MiniSerial.begin(9600); + MiniSerial.println(FreeStack()); +} +void loop() { + int c; + MiniSerial.println(F("Type any Character")); + while ((c = MiniSerial.read()) < 0) {} + MiniSerial.print(F("Read: ")); + MiniSerial.println((char)c); + while (MiniSerial.read() >= 0) {} +} +#else // UDR0 +#error no AVR serial port 0 +#endif // UDR0 \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/PrintBenchmarkSD/PrintBenchmarkSD.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/PrintBenchmarkSD/PrintBenchmarkSD.ino new file mode 100644 index 0000000..650caeb --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/PrintBenchmarkSD/PrintBenchmarkSD.ino @@ -0,0 +1,125 @@ +/* + * This program is a simple Print benchmark. + */ +#include +#include + +// SD chip select pin +const uint8_t chipSelect = SS; + +// number of lines to print +const uint16_t N_PRINT = 20000; + + +// test file +File file; + +//------------------------------------------------------------------------------ +void error(const char* s) { + Serial.println(s); + while (1) { + yield(); + } +} +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + yield(); + } +} +//------------------------------------------------------------------------------ +void loop() { + uint32_t maxLatency; + uint32_t minLatency; + uint32_t totalLatency; + + // Read any existing Serial data. + do { + delay(10); + } while (Serial.available() && Serial.read() >= 0); + + // F() stores strings in flash to save RAM + Serial.println(F("Type any character to start")); + while (!Serial.available()) { + yield(); + } + + // initialize the SD card + if (!SD.begin(chipSelect)) { + error("begin"); + } + + Serial.println(F("Starting print test. Please wait.\n")); + + // do write test + for (int test = 0; test < 2; test++) { + file = SD.open("bench.txt", FILE_WRITE); + + if (!file) { + error("open failed"); + } + switch(test) { + case 0: + Serial.println(F("Test of println(uint16_t)")); + break; + + case 1: + Serial.println(F("Test of println(double)")); + break; + } + maxLatency = 0; + minLatency = 999999; + totalLatency = 0; + uint32_t t = millis(); + for (uint16_t i = 0; i < N_PRINT; i++) { + uint32_t m = micros(); + + switch(test) { + case 0: + file.println(i); + break; + + case 1: + file.println((double)0.01*i); + break; + } + + if (file.getWriteError()) { + error("write failed"); + } + m = micros() - m; + if (maxLatency < m) { + maxLatency = m; + } + if (minLatency > m) { + minLatency = m; + } + totalLatency += m; + } + file.flush(); + t = millis() - t; + double s = file.size(); + Serial.print(F("Time ")); + Serial.print(0.001*t); + Serial.println(F(" sec")); + Serial.print(F("File size ")); + Serial.print(0.001*s); + Serial.print(F(" KB\n")); + Serial.print(F("Write ")); + Serial.print(s/t); + Serial.print(F(" KB/sec\n")); + Serial.print(F("Maximum latency: ")); + Serial.print(maxLatency); + Serial.print(F(" usec, Minimum Latency: ")); + Serial.print(minLatency); + Serial.print(F(" usec, Avg Latency: ")); + Serial.print(totalLatency/N_PRINT); + Serial.println(F(" usec\n")); + SD.remove("bench.txt"); + } + file.close(); + Serial.println(F("Done!\n")); +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/SD_Size/SD_Size.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/SD_Size/SD_Size.ino new file mode 100644 index 0000000..8d27c6d --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/SD_Size/SD_Size.ino @@ -0,0 +1,30 @@ +/* + * Program to compare size of Arduino SD library with SdFat. + * See SdFatSize.ino for SdFat program. + */ +#include +#include + +File file; +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + yield(); + } + + if (!SD.begin()) { + Serial.println("begin failed"); + return; + } + file = SD.open("TEST_SD.TXT", FILE_WRITE); + + file.println("Hello"); + + file.close(); + Serial.println("Done"); +} +//------------------------------------------------------------------------------ +void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/SdFatSize/SdFatSize.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/SdFatSize/SdFatSize.ino new file mode 100644 index 0000000..b44d617 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/SdFatSize/SdFatSize.ino @@ -0,0 +1,33 @@ +/* + * Program to compare size of SdFat with Arduino SD library. + * See SD_Size.ino for Arduino SD program. + * + */ +#include +#include "SdFat.h" + +SdFat sd; + +SdFile file; +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + + if (!sd.begin()) { + Serial.println("begin failed"); + return; + } + file.open("SizeTest.txt", O_RDWR | O_CREAT | O_AT_END); + + file.println("Hello"); + + file.close(); + Serial.println("Done"); +} +//------------------------------------------------------------------------------ +void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/StreamParseInt/StreamParseInt.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/StreamParseInt/StreamParseInt.ino new file mode 100644 index 0000000..2da1f7c --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/StreamParseInt/StreamParseInt.ino @@ -0,0 +1,44 @@ +// Simple demo of the Stream parsInt() member function. +#include +// The next two lines replace #include . +#include "SdFat.h" +SdFat SD; + +// SD card chip select pin - Modify the value of csPin for your SD module. +const uint8_t csPin = SS; + +File file; +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + // Wait for USB Serial. + while(!Serial) { + SysCall::yield(); + } + Serial.println(F("Type any character to start")); + while (!Serial.available()) { + SysCall::yield(); + } + // Initialize the SD. + if (!SD.begin(csPin)) { + Serial.println(F("begin error")); + return; + } + // Create and open the file. Use flag to truncate an existing file. + file = SD.open("stream.txt", O_RDWR|O_CREAT|O_TRUNC); + if (!file) { + Serial.println(F("open error")); + return; + } + // Write a test number to the file. + file.println("12345"); + + // Rewind the file and read the number with parseInt(). + file.seek(0); + int i = file.parseInt(); + Serial.print(F("parseInt: ")); + Serial.println(i); + file.close(); +} + +void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/append/append.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/append/append.ino new file mode 100644 index 0000000..291fcdc --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/append/append.ino @@ -0,0 +1,77 @@ +/* + * Append Example + * + * This program shows how to use open for append. + * The program will append 100 line each time it opens the file. + * The program will open and close the file 100 times. + */ +#include +#include "SdFat.h" +#include "sdios.h" + +// SD chip select pin +const uint8_t chipSelect = SS; + +// file system object +SdFat sd; + +// create Serial stream +ArduinoOutStream cout(Serial); + +// store error strings in flash to save RAM +#define error(s) sd.errorHalt(F(s)) +//------------------------------------------------------------------------------ +void setup() { + // filename for this example + char name[] = "append.txt"; + + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + // F() stores strings in flash to save RAM + cout << endl << F("Type any character to start\n"); + while (!Serial.available()) { + SysCall::yield(); + } + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } + + cout << F("Appending to: ") << name; + + for (uint8_t i = 0; i < 100; i++) { + // open stream for append + ofstream sdout(name, ios::out | ios::app); + if (!sdout) { + error("open failed"); + } + + // append 100 lines to the file + for (uint8_t j = 0; j < 100; j++) { + // use int() so byte will print as decimal number + sdout << "line " << int(j) << " of pass " << int(i); + sdout << " millis = " << millis() << endl; + } + // close the stream + sdout.close(); + + if (!sdout) { + error("append data failed"); + } + + // output progress indicator + if (i % 25 == 0) { + cout << endl; + } + cout << '.'; + } + cout << endl << "Done" << endl; +} +//------------------------------------------------------------------------------ +void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/average/average.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/average/average.ino new file mode 100644 index 0000000..32c4c84 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/average/average.ino @@ -0,0 +1,82 @@ +/* + * Calculate the sum and average of a list of floating point numbers + */ +#include +#include "SdFat.h" +#include "sdios.h" + +// SD chip select pin +const uint8_t chipSelect = SS; + +// object for the SD file system +SdFat sd; + +// define a serial output stream +ArduinoOutStream cout(Serial); +//------------------------------------------------------------------------------ +void writeTestFile() { + // open the output file + ofstream sdout("AvgTest.txt"); + + // write a series of float numbers + for (int16_t i = -1001; i < 2000; i += 13) { + sdout << 0.1 * i << endl; + } + if (!sdout) { + sd.errorHalt("sdout failed"); + } + + sdout.close(); +} +//------------------------------------------------------------------------------ +void calcAverage() { + uint16_t n = 0; // count of input numbers + double num; // current input number + double sum = 0; // sum of input numbers + + // open the input file + ifstream sdin("AvgTest.txt"); + + // check for an open failure + if (!sdin) { + sd.errorHalt("sdin failed"); + } + + // read and sum the numbers + while (sdin >> num) { + n++; + sum += num; + } + + // print the results + cout << "sum of " << n << " numbers = " << sum << endl; + cout << "average = " << sum/n << endl; +} +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + // F() stores strings in flash to save RAM + cout << F("Type any character to start\n"); + while (!Serial.available()) { + SysCall::yield(); + } + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } + + // write the test file + writeTestFile(); + + // read the test file and calculate the average + calcAverage(); +} +//------------------------------------------------------------------------------ +void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/benchSD/benchSD.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/benchSD/benchSD.ino new file mode 100644 index 0000000..cffef28 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/benchSD/benchSD.ino @@ -0,0 +1,149 @@ +/* + * This program is a simple binary write/read benchmark + * for the standard Arduino SD.h library. + */ +#include +#include + +// SD chip select pin +const uint8_t chipSelect = SS; + +#define FILE_SIZE_MB 5 +#define FILE_SIZE (1000000UL*FILE_SIZE_MB) +#define BUF_SIZE 100 + +uint8_t buf[BUF_SIZE]; + +// test file +File file; + +//------------------------------------------------------------------------------ +void error(const char* s) { + Serial.println(s); + while (1) { + yield(); + } +} +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + yield(); + } +} +//------------------------------------------------------------------------------ +void loop() { + uint32_t maxLatency; + uint32_t minLatency; + uint32_t totalLatency; + + // Discard any input. + do { + delay(10); + } while (Serial.available() && Serial.read() >= 0); + + // F() stores strings in flash to save RAM + Serial.println(F("Type any character to start")); + + while (!Serial.available()) { + yield(); + } + if (!SD.begin(chipSelect)) { + error("begin"); + } + + // open or create file - truncate existing file. + file = SD.open("Bench.dat", O_RDWR | O_TRUNC | O_CREAT); + if (!file) { + error("open failed"); + } + + // fill buf with known data + for (uint16_t i = 0; i < (BUF_SIZE-2); i++) { + buf[i] = 'A' + (i % 26); + } + buf[BUF_SIZE-2] = '\r'; + buf[BUF_SIZE-1] = '\n'; + + Serial.print(F("File size ")); + Serial.print(FILE_SIZE_MB); + Serial.println(F("MB")); + Serial.print(F("Buffer size ")); + Serial.print(BUF_SIZE); + Serial.println(F(" bytes")); + Serial.println(F("Starting write test. Please wait up to a minute")); + + // do write test + uint32_t n = FILE_SIZE/sizeof(buf); + maxLatency = 0; + minLatency = 999999; + totalLatency = 0; + uint32_t t = millis(); + for (uint32_t i = 0; i < n; i++) { + uint32_t m = micros(); + if (file.write(buf, sizeof(buf)) != sizeof(buf)) { + error("write failed"); + } + m = micros() - m; + if (maxLatency < m) { + maxLatency = m; + } + if (minLatency > m) { + minLatency = m; + } + totalLatency += m; + } + file.flush(); + t = millis() - t; + double s = file.size(); + Serial.print(F("Write ")); + Serial.print(s/t); + Serial.print(F(" KB/sec\n")); + Serial.print(F("Maximum latency: ")); + Serial.print(maxLatency); + Serial.print(F(" usec, Minimum Latency: ")); + Serial.print(minLatency); + Serial.print(F(" usec, Avg Latency: ")); + Serial.print(totalLatency/n); + Serial.print(F(" usec\n\n")); + Serial.println(F("Starting read test. Please wait up to a minute")); + // do read test + file.seek(0); + maxLatency = 0; + minLatency = 99999; + totalLatency = 0; + t = millis(); + for (uint32_t i = 0; i < n; i++) { + buf[BUF_SIZE-1] = 0; + uint32_t m = micros(); + if (file.read(buf, sizeof(buf)) != sizeof(buf)) { + error("read failed"); + } + m = micros() - m; + if (maxLatency < m) { + maxLatency = m; + } + if (minLatency > m) { + minLatency = m; + } + totalLatency += m; + if (buf[BUF_SIZE-1] != '\n') { + error("data check"); + } + } + t = millis() - t; + Serial.print(F("Read ")); + Serial.print(s/t); + Serial.print(F(" KB/sec\n")); + Serial.print(F("Maximum latency: ")); + Serial.print(maxLatency); + Serial.print(F(" usec, Minimum Latency: ")); + Serial.print(minLatency); + Serial.print(F(" usec, Avg Latency: ")); + Serial.print(totalLatency/n); + Serial.print(F(" usec\n\n")); + Serial.print(F("Done\n\n")); + file.close(); +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/bufstream/bufstream.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/bufstream/bufstream.ino new file mode 100644 index 0000000..eda0f1a --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/bufstream/bufstream.ino @@ -0,0 +1,39 @@ +/* + * Use of ibufsteam to parse a line and obufstream to format a line + */ +#include +#include "SdFat.h" +#include "sdios.h" + +// create a serial output stream +ArduinoOutStream cout(Serial); +//------------------------------------------------------------------------------ +void setup() { + char buf[20]; // buffer for formatted line + int i, j, k; // values from parsed line + + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + delay(2000); + + // initialize input string + ibufstream bin("123 456 789"); + + // parse the string "123 456 789" + bin >> i >> j >> k; + + // initialize output buffer + obufstream bout(buf, sizeof(buf)); + + // format the output string + bout << k << ',' << j << ',' << i << endl; + + // write the string to serial + cout << buf; +} + +void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/cin_cout/cin_cout.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/cin_cout/cin_cout.ino new file mode 100644 index 0000000..30e49ef --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/cin_cout/cin_cout.ino @@ -0,0 +1,39 @@ +/* + * Demo of ArduinoInStream and ArduinoOutStream + */ +#include +#include "SdFat.h" +#include "sdios.h" + +// create serial output stream +ArduinoOutStream cout(Serial); + +// input line buffer +char cinBuf[40]; + +// create serial input stream +ArduinoInStream cin(Serial, cinBuf, sizeof(cinBuf)); +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } +} +//------------------------------------------------------------------------------ +void loop() { + int32_t n = 0; + + cout << "\nenter an integer\n"; + + cin.readline(); + + if (cin >> n) { + cout << "The number is: " << n; + } else { + // will fail if no digits or not in range [-2147483648, 2147483647] + cout << "Invalid input: " << cinBuf; + } + cout << endl; +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/eventlog/eventlog.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/eventlog/eventlog.ino new file mode 100644 index 0000000..e295a32 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/eventlog/eventlog.ino @@ -0,0 +1,62 @@ +/* + * Append a line to a file - demo of pathnames and streams + */ +#include +#include "SdFat.h" +#include "sdios.h" +// SD chip select pin +const uint8_t chipSelect = SS; + +// file system object +SdFat sd; + +// define a serial output stream +ArduinoOutStream cout(Serial); +//------------------------------------------------------------------------------ +/* + * Append a line to logfile.txt + */ +void logEvent(const char *msg) { + // create dir if needed + sd.mkdir("logs/2014/Jan"); + + // create or open a file for append + ofstream sdlog("logs/2014/Jan/logfile.txt", ios::out | ios::app); + + // append a line to the file + sdlog << msg << endl; + + // check for errors + if (!sdlog) { + sd.errorHalt("append failed"); + } + + sdlog.close(); +} +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + // F() stores strings in flash to save RAM + cout << F("Type any character to start\n"); + while (!Serial.available()) { + SysCall::yield(); + } + delay(400); // catch Due reset problem + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } + + // append a line to the logfile + logEvent("Another line for the logfile"); + + cout << F("Done - check /logs/2014/Jan/logfile.txt on the SD") << endl; +} +//------------------------------------------------------------------------------ +void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/fgetsRewrite/fgetsRewrite.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/fgetsRewrite/fgetsRewrite.ino new file mode 100644 index 0000000..41a3730 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/fgetsRewrite/fgetsRewrite.ino @@ -0,0 +1,111 @@ +// Demo of rewriting a line read by fgets +#include +#include "SdFat.h" +#include "sdios.h" + +// SD card chip select pin +const uint8_t chipSelect = SS; + +// file system +SdFat sd; + +// print stream +ArduinoOutStream cout(Serial); +//------------------------------------------------------------------------------ +// store error strings in flash memory +#define error(s) sd.errorHalt(F(s)) +//------------------------------------------------------------------------------ +void demoFgets() { + char line[25]; + int c; + uint32_t pos; + + // open test file + SdFile rdfile("fgets.txt", O_RDWR); + + // check for open error + if (!rdfile.isOpen()) { + error("demoFgets"); + } + + // list file + cout << F("-----Before Rewrite\r\n"); + while ((c = rdfile.read()) >= 0) { + Serial.write(c); + } + + rdfile.rewind(); + // read lines from the file to get position + while (1) { + pos = rdfile.curPosition(); + if (rdfile.fgets(line, sizeof(line)) < 0) { + error("Line not found"); + } + // find line that contains "Line C" + if (strstr(line, "Line C")) { + break; + } + } + + // rewrite line with 'C' + if (!rdfile.seekSet(pos)) { + error("seekSet"); + } + rdfile.println("Line R"); + rdfile.rewind(); + + // list file + cout << F("\r\n-----After Rewrite\r\n"); + while ((c = rdfile.read()) >= 0) { + Serial.write(c); + } + + // close so rewrite is not lost + rdfile.close(); +} +//------------------------------------------------------------------------------ +void makeTestFile() { + // create or open test file + SdFile wrfile("fgets.txt", O_WRONLY | O_CREAT | O_TRUNC); + + // check for open error + if (!wrfile.isOpen()) { + error("MakeTestFile"); + } + + // write test file + wrfile.print(F( + "Line A\r\n" + "Line B\r\n" + "Line C\r\n" + "Line D\r\n" + "Line E\r\n" + )); + wrfile.close(); +} +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + cout << F("Type any character to start\n"); + while (!Serial.available()) { + SysCall::yield(); + } + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } + + makeTestFile(); + + demoFgets(); + + cout << F("\nDone\n"); +} +void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/readlog/readlog.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/readlog/readlog.ino new file mode 100644 index 0000000..ca72cf9 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/readlog/readlog.ino @@ -0,0 +1,51 @@ +/* + * Read the logfile created by the eventlog.ino example. + * Demo of pathnames and working directories + */ +#include +#include "SdFat.h" +#include "sdios.h" + +// SD chip select pin +const uint8_t chipSelect = SS; + +// file system object +SdFat sd; + +// define a serial output stream +ArduinoOutStream cout(Serial); +//------------------------------------------------------------------------------ +void setup() { + int c; + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } + + // set current working directory + if (!sd.chdir("logs/2014/Jan/")) { + sd.errorHalt("chdir failed. Did you run eventlog.ino?"); + } + // open file in current working directory + ifstream file("logfile.txt"); + + if (!file.is_open()) { + sd.errorHalt("open failed"); + } + + // copy the file to Serial + while ((c = file.get()) >= 0) { + cout << (char)c; + } + + cout << "Done" << endl; +} +//------------------------------------------------------------------------------ +void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/readme.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/readme.txt new file mode 100644 index 0000000..1943dcd --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/readme.txt @@ -0,0 +1,34 @@ +Old and debug examples. + +AnalogLogger - A simple data logger for one or more analog pins. + +append - This sketch creates a large file by successive + open/write/close operations. + +average - A demonstration of parsing floating point numbers. + +BaseExtCaseTest - Long file name test. + +benchSD - A read/write benchmark for the standard Arduino SD.h library. + +bufstream - ibufsteam to parse a line and obufstream to format a line. + +cin_cout - Demo of ArduinoInStream and ArduinoOutStream. + +eventlog - Append a line to a file - demo of pathnames and streams. + +fgetsRewrite - Demo of rewriting a line read by fgets. + +HelloWorld - Create a serial output stream. + +MiniSerial - SdFat minimal serial support for debug. + +PrintBenchmarkSD - Bench mark SD.h print. + +readlog - Read file. Demo of pathnames and current working directory. + +SD_Size - Determine flash used by SD.h example. + +SdFatSize - Determine flash used by SdFat. + +StreamParseInt - Simple demo of the Stream parsInt() member function. diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/AnalogBinLogger/AnalogBinLogger.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/AnalogBinLogger/AnalogBinLogger.h new file mode 100644 index 0000000..a793e2d --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/AnalogBinLogger/AnalogBinLogger.h @@ -0,0 +1,39 @@ +#ifndef AnalogBinLogger_h +#define AnalogBinLogger_h +//------------------------------------------------------------------------------ +// First block of file. +struct metadata_t { + unsigned long adcFrequency; // ADC clock frequency + unsigned long cpuFrequency; // CPU clock frequency + unsigned long sampleInterval; // Sample interval in CPU cycles. + unsigned long recordEightBits; // Size of ADC values, nonzero for 8-bits. + unsigned long pinCount; // Number of analog pins in a sample. + unsigned long pinNumber[123]; // List of pin numbers in a sample. +}; +//------------------------------------------------------------------------------ +// Data block for 8-bit ADC mode. +const size_t DATA_DIM8 = 508; +struct block8_t { + unsigned short count; // count of data values + unsigned short overrun; // count of overruns since last block + unsigned char data[DATA_DIM8]; +}; +//------------------------------------------------------------------------------ +// Data block for 10-bit ADC mode. +const size_t DATA_DIM16 = 254; +struct block16_t { + unsigned short count; // count of data values + unsigned short overrun; // count of overruns since last block + unsigned short data[DATA_DIM16]; +}; +//------------------------------------------------------------------------------ +// Data block for PC use +struct adcdata_t { + unsigned short count; // count of data values + unsigned short overrun; // count of overruns since last block + union { + unsigned char u8[DATA_DIM8]; + unsigned short u16[DATA_DIM16]; + } data; +}; +#endif // AnalogBinLogger_h \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/AnalogBinLogger/AnalogBinLogger.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/AnalogBinLogger/AnalogBinLogger.ino new file mode 100644 index 0000000..67cf62b --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/AnalogBinLogger/AnalogBinLogger.ino @@ -0,0 +1,826 @@ +/** + * This program logs data from the Arduino ADC to a binary file. + * + * Samples are logged at regular intervals. Each Sample consists of the ADC + * values for the analog pins defined in the PIN_LIST array. The pins numbers + * may be in any order. + * + * Edit the configuration constants below to set the sample pins, sample rate, + * and other configuration values. + * + * If your SD card has a long write latency, it may be necessary to use + * slower sample rates. Using a Mega Arduino helps overcome latency + * problems since 13 512 byte buffers will be used. + * + * Each 512 byte data block in the file has a four byte header followed by up + * to 508 bytes of data. (508 values in 8-bit mode or 254 values in 10-bit mode) + * Each block contains an integral number of samples with unused space at the + * end of the block. + * + * Data is written to the file using a SD multiple block write command. + */ +#ifdef __AVR__ +#include +#include "SdFat.h" +#include "FreeStack.h" +#include "AnalogBinLogger.h" +//------------------------------------------------------------------------------ +// Analog pin number list for a sample. Pins may be in any order and pin +// numbers may be repeated. +const uint8_t PIN_LIST[] = {0, 1, 2, 3, 4}; +//------------------------------------------------------------------------------ +// Sample rate in samples per second. +const float SAMPLE_RATE = 5000; // Must be 0.25 or greater. + +// The interval between samples in seconds, SAMPLE_INTERVAL, may be set to a +// constant instead of being calculated from SAMPLE_RATE. SAMPLE_RATE is not +// used in the code below. For example, setting SAMPLE_INTERVAL = 2.0e-4 +// will result in a 200 microsecond sample interval. +const float SAMPLE_INTERVAL = 1.0/SAMPLE_RATE; + +// Setting ROUND_SAMPLE_INTERVAL non-zero will cause the sample interval to +// be rounded to a a multiple of the ADC clock period and will reduce sample +// time jitter. +#define ROUND_SAMPLE_INTERVAL 1 +//------------------------------------------------------------------------------ +// ADC clock rate. +// The ADC clock rate is normally calculated from the pin count and sample +// interval. The calculation attempts to use the lowest possible ADC clock +// rate. +// +// You can select an ADC clock rate by defining the symbol ADC_PRESCALER to +// one of these values. You must choose an appropriate ADC clock rate for +// your sample interval. +// #define ADC_PRESCALER 7 // F_CPU/128 125 kHz on an Uno +// #define ADC_PRESCALER 6 // F_CPU/64 250 kHz on an Uno +// #define ADC_PRESCALER 5 // F_CPU/32 500 kHz on an Uno +// #define ADC_PRESCALER 4 // F_CPU/16 1000 kHz on an Uno +// #define ADC_PRESCALER 3 // F_CPU/8 2000 kHz on an Uno (8-bit mode only) +//------------------------------------------------------------------------------ +// Reference voltage. See the processor data-sheet for reference details. +// uint8_t const ADC_REF = 0; // External Reference AREF pin. +uint8_t const ADC_REF = (1 << REFS0); // Vcc Reference. +// uint8_t const ADC_REF = (1 << REFS1); // Internal 1.1 (only 644 1284P Mega) +// uint8_t const ADC_REF = (1 << REFS1) | (1 << REFS0); // Internal 1.1 or 2.56 +//------------------------------------------------------------------------------ +// File definitions. +// +// Maximum file size in blocks. +// The program creates a contiguous file with FILE_BLOCK_COUNT 512 byte blocks. +// This file is flash erased using special SD commands. The file will be +// truncated if logging is stopped early. +const uint32_t FILE_BLOCK_COUNT = 256000; + +// log file base name. Must be six characters or less. +#define FILE_BASE_NAME "analog" + +// Set RECORD_EIGHT_BITS non-zero to record only the high 8-bits of the ADC. +#define RECORD_EIGHT_BITS 0 +//------------------------------------------------------------------------------ +// Pin definitions. +// +// Digital pin to indicate an error, set to -1 if not used. +// The led blinks for fatal errors. The led goes on solid for SD write +// overrun errors and logging continues. +const int8_t ERROR_LED_PIN = 3; + +// SD chip select pin. +const uint8_t SD_CS_PIN = SS; +//------------------------------------------------------------------------------ +// Buffer definitions. +// +// The logger will use SdFat's buffer plus BUFFER_BLOCK_COUNT additional +// buffers. QUEUE_DIM must be a power of two larger than +//(BUFFER_BLOCK_COUNT + 1). +// +#if RAMEND < 0X8FF +#error Too little SRAM +// +#elif RAMEND < 0X10FF +// Use total of two 512 byte buffers. +const uint8_t BUFFER_BLOCK_COUNT = 1; +// Dimension for queues of 512 byte SD blocks. +const uint8_t QUEUE_DIM = 4; // Must be a power of two! +// +#elif RAMEND < 0X20FF +// Use total of five 512 byte buffers. +const uint8_t BUFFER_BLOCK_COUNT = 4; +// Dimension for queues of 512 byte SD blocks. +const uint8_t QUEUE_DIM = 8; // Must be a power of two! +// +#elif RAMEND < 0X40FF +// Use total of 13 512 byte buffers. +const uint8_t BUFFER_BLOCK_COUNT = 12; +// Dimension for queues of 512 byte SD blocks. +const uint8_t QUEUE_DIM = 16; // Must be a power of two! +// +#else // RAMEND +// Use total of 29 512 byte buffers. +const uint8_t BUFFER_BLOCK_COUNT = 28; +// Dimension for queues of 512 byte SD blocks. +const uint8_t QUEUE_DIM = 32; // Must be a power of two! +#endif // RAMEND +//============================================================================== +// End of configuration constants. +//============================================================================== +// Temporary log file. Will be deleted if a reset or power failure occurs. +#define TMP_FILE_NAME "tmp_log.bin" + +// Size of file base name. Must not be larger than six. +const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1; + +// Number of analog pins to log. +const uint8_t PIN_COUNT = sizeof(PIN_LIST)/sizeof(PIN_LIST[0]); + +// Minimum ADC clock cycles per sample interval +const uint16_t MIN_ADC_CYCLES = 15; + +// Extra cpu cycles to setup ADC with more than one pin per sample. +const uint16_t ISR_SETUP_ADC = PIN_COUNT > 1 ? 100 : 0; + +// Maximum cycles for timer0 system interrupt, millis, micros. +const uint16_t ISR_TIMER0 = 160; +//============================================================================== +SdFat sd; + +SdBaseFile binFile; + +char binName[13] = FILE_BASE_NAME "00.bin"; + +#if RECORD_EIGHT_BITS +const size_t SAMPLES_PER_BLOCK = DATA_DIM8/PIN_COUNT; +typedef block8_t block_t; +#else // RECORD_EIGHT_BITS +const size_t SAMPLES_PER_BLOCK = DATA_DIM16/PIN_COUNT; +typedef block16_t block_t; +#endif // RECORD_EIGHT_BITS + +block_t* emptyQueue[QUEUE_DIM]; +uint8_t emptyHead; +uint8_t emptyTail; + +block_t* fullQueue[QUEUE_DIM]; +volatile uint8_t fullHead; // volatile insures non-interrupt code sees changes. +uint8_t fullTail; + +// queueNext assumes QUEUE_DIM is a power of two +inline uint8_t queueNext(uint8_t ht) { + return (ht + 1) & (QUEUE_DIM -1); +} +//============================================================================== +// Interrupt Service Routines + +// Pointer to current buffer. +block_t* isrBuf; + +// Need new buffer if true. +bool isrBufNeeded = true; + +// overrun count +uint16_t isrOver = 0; + +// ADC configuration for each pin. +uint8_t adcmux[PIN_COUNT]; +uint8_t adcsra[PIN_COUNT]; +uint8_t adcsrb[PIN_COUNT]; +uint8_t adcindex = 1; + +// Insure no timer events are missed. +volatile bool timerError = false; +volatile bool timerFlag = false; +//------------------------------------------------------------------------------ +// ADC done interrupt. +ISR(ADC_vect) { + // Read ADC data. +#if RECORD_EIGHT_BITS + uint8_t d = ADCH; +#else // RECORD_EIGHT_BITS + // This will access ADCL first. + uint16_t d = ADC; +#endif // RECORD_EIGHT_BITS + + if (isrBufNeeded && emptyHead == emptyTail) { + // no buffers - count overrun + if (isrOver < 0XFFFF) { + isrOver++; + } + + // Avoid missed timer error. + timerFlag = false; + return; + } + // Start ADC + if (PIN_COUNT > 1) { + ADMUX = adcmux[adcindex]; + ADCSRB = adcsrb[adcindex]; + ADCSRA = adcsra[adcindex]; + if (adcindex == 0) { + timerFlag = false; + } + adcindex = adcindex < (PIN_COUNT - 1) ? adcindex + 1 : 0; + } else { + timerFlag = false; + } + // Check for buffer needed. + if (isrBufNeeded) { + // Remove buffer from empty queue. + isrBuf = emptyQueue[emptyTail]; + emptyTail = queueNext(emptyTail); + isrBuf->count = 0; + isrBuf->overrun = isrOver; + isrBufNeeded = false; + } + // Store ADC data. + isrBuf->data[isrBuf->count++] = d; + + // Check for buffer full. + if (isrBuf->count >= PIN_COUNT*SAMPLES_PER_BLOCK) { + // Put buffer isrIn full queue. + uint8_t tmp = fullHead; // Avoid extra fetch of volatile fullHead. + fullQueue[tmp] = (block_t*)isrBuf; + fullHead = queueNext(tmp); + + // Set buffer needed and clear overruns. + isrBufNeeded = true; + isrOver = 0; + } +} +//------------------------------------------------------------------------------ +// timer1 interrupt to clear OCF1B +ISR(TIMER1_COMPB_vect) { + // Make sure ADC ISR responded to timer event. + if (timerFlag) { + timerError = true; + } + timerFlag = true; +} +//============================================================================== +// Error messages stored in flash. +#define error(msg) {sd.errorPrint(F(msg));fatalBlink();} +//------------------------------------------------------------------------------ +// +void fatalBlink() { + while (true) { + if (ERROR_LED_PIN >= 0) { + digitalWrite(ERROR_LED_PIN, HIGH); + delay(200); + digitalWrite(ERROR_LED_PIN, LOW); + delay(200); + } + } +} +//============================================================================== +#if ADPS0 != 0 || ADPS1 != 1 || ADPS2 != 2 +#error unexpected ADC prescaler bits +#endif +//------------------------------------------------------------------------------ +// initialize ADC and timer1 +void adcInit(metadata_t* meta) { + uint8_t adps; // prescaler bits for ADCSRA + uint32_t ticks = F_CPU*SAMPLE_INTERVAL + 0.5; // Sample interval cpu cycles. + + if (ADC_REF & ~((1 << REFS0) | (1 << REFS1))) { + error("Invalid ADC reference"); + } +#ifdef ADC_PRESCALER + if (ADC_PRESCALER > 7 || ADC_PRESCALER < 2) { + error("Invalid ADC prescaler"); + } + adps = ADC_PRESCALER; +#else // ADC_PRESCALER + // Allow extra cpu cycles to change ADC settings if more than one pin. + int32_t adcCycles = (ticks - ISR_TIMER0)/PIN_COUNT - ISR_SETUP_ADC; + + for (adps = 7; adps > 0; adps--) { + if (adcCycles >= (MIN_ADC_CYCLES << adps)) { + break; + } + } +#endif // ADC_PRESCALER + meta->adcFrequency = F_CPU >> adps; + if (meta->adcFrequency > (RECORD_EIGHT_BITS ? 2000000 : 1000000)) { + error("Sample Rate Too High"); + } +#if ROUND_SAMPLE_INTERVAL + // Round so interval is multiple of ADC clock. + ticks += 1 << (adps - 1); + ticks >>= adps; + ticks <<= adps; +#endif // ROUND_SAMPLE_INTERVAL + + if (PIN_COUNT > sizeof(meta->pinNumber)/sizeof(meta->pinNumber[0])) { + error("Too many pins"); + } + meta->pinCount = PIN_COUNT; + meta->recordEightBits = RECORD_EIGHT_BITS; + + for (int i = 0; i < PIN_COUNT; i++) { + uint8_t pin = PIN_LIST[i]; + if (pin >= NUM_ANALOG_INPUTS) { + error("Invalid Analog pin number"); + } + meta->pinNumber[i] = pin; + + // Set ADC reference and low three bits of analog pin number. + adcmux[i] = (pin & 7) | ADC_REF; + if (RECORD_EIGHT_BITS) { + adcmux[i] |= 1 << ADLAR; + } + + // If this is the first pin, trigger on timer/counter 1 compare match B. + adcsrb[i] = i == 0 ? (1 << ADTS2) | (1 << ADTS0) : 0; +#ifdef MUX5 + if (pin > 7) { + adcsrb[i] |= (1 << MUX5); + } +#endif // MUX5 + adcsra[i] = (1 << ADEN) | (1 << ADIE) | adps; + adcsra[i] |= i == 0 ? 1 << ADATE : 1 << ADSC; + } + + // Setup timer1 + TCCR1A = 0; + uint8_t tshift; + if (ticks < 0X10000) { + // no prescale, CTC mode + TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS10); + tshift = 0; + } else if (ticks < 0X10000*8) { + // prescale 8, CTC mode + TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11); + tshift = 3; + } else if (ticks < 0X10000*64) { + // prescale 64, CTC mode + TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11) | (1 << CS10); + tshift = 6; + } else if (ticks < 0X10000*256) { + // prescale 256, CTC mode + TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12); + tshift = 8; + } else if (ticks < 0X10000*1024) { + // prescale 1024, CTC mode + TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12) | (1 << CS10); + tshift = 10; + } else { + error("Sample Rate Too Slow"); + } + // divide by prescaler + ticks >>= tshift; + // set TOP for timer reset + ICR1 = ticks - 1; + // compare for ADC start + OCR1B = 0; + + // multiply by prescaler + ticks <<= tshift; + + // Sample interval in CPU clock ticks. + meta->sampleInterval = ticks; + meta->cpuFrequency = F_CPU; + float sampleRate = (float)meta->cpuFrequency/meta->sampleInterval; + Serial.print(F("Sample pins:")); + for (uint8_t i = 0; i < meta->pinCount; i++) { + Serial.print(' '); + Serial.print(meta->pinNumber[i], DEC); + } + Serial.println(); + Serial.print(F("ADC bits: ")); + Serial.println(meta->recordEightBits ? 8 : 10); + Serial.print(F("ADC clock kHz: ")); + Serial.println(meta->adcFrequency/1000); + Serial.print(F("Sample Rate: ")); + Serial.println(sampleRate); + Serial.print(F("Sample interval usec: ")); + Serial.println(1000000.0/sampleRate, 4); +} +//------------------------------------------------------------------------------ +// enable ADC and timer1 interrupts +void adcStart() { + // initialize ISR + isrBufNeeded = true; + isrOver = 0; + adcindex = 1; + + // Clear any pending interrupt. + ADCSRA |= 1 << ADIF; + + // Setup for first pin. + ADMUX = adcmux[0]; + ADCSRB = adcsrb[0]; + ADCSRA = adcsra[0]; + + // Enable timer1 interrupts. + timerError = false; + timerFlag = false; + TCNT1 = 0; + TIFR1 = 1 << OCF1B; + TIMSK1 = 1 << OCIE1B; +} +//------------------------------------------------------------------------------ +void adcStop() { + TIMSK1 = 0; + ADCSRA = 0; +} +//------------------------------------------------------------------------------ +// Convert binary file to csv file. +void binaryToCsv() { + uint8_t lastPct = 0; + block_t buf; + metadata_t* pm; + uint32_t t0 = millis(); + char csvName[13]; + StdioStream csvStream; + + if (!binFile.isOpen()) { + Serial.println(F("No current binary file")); + return; + } + binFile.rewind(); + if (binFile.read(&buf , 512) != 512) { + error("Read metadata failed"); + } + // Create a new csv file. + strcpy(csvName, binName); + strcpy(&csvName[BASE_NAME_SIZE + 3], "csv"); + + if (!csvStream.fopen(csvName, "w")) { + error("open csvStream failed"); + } + Serial.println(); + Serial.print(F("Writing: ")); + Serial.print(csvName); + Serial.println(F(" - type any character to stop")); + pm = (metadata_t*)&buf; + csvStream.print(F("Interval,")); + float intervalMicros = 1.0e6*pm->sampleInterval/(float)pm->cpuFrequency; + csvStream.print(intervalMicros, 4); + csvStream.println(F(",usec")); + for (uint8_t i = 0; i < pm->pinCount; i++) { + if (i) { + csvStream.putc(','); + } + csvStream.print(F("pin")); + csvStream.print(pm->pinNumber[i]); + } + csvStream.println(); + uint32_t tPct = millis(); + while (!Serial.available() && binFile.read(&buf, 512) == 512) { + if (buf.count == 0) { + break; + } + if (buf.overrun) { + csvStream.print(F("OVERRUN,")); + csvStream.println(buf.overrun); + } + for (uint16_t j = 0; j < buf.count; j += PIN_COUNT) { + for (uint16_t i = 0; i < PIN_COUNT; i++) { + if (i) { + csvStream.putc(','); + } + csvStream.print(buf.data[i + j]); + } + csvStream.println(); + } + if ((millis() - tPct) > 1000) { + uint8_t pct = binFile.curPosition()/(binFile.fileSize()/100); + if (pct != lastPct) { + tPct = millis(); + lastPct = pct; + Serial.print(pct, DEC); + Serial.println('%'); + } + } + if (Serial.available()) { + break; + } + } + csvStream.fclose(); + Serial.print(F("Done: ")); + Serial.print(0.001*(millis() - t0)); + Serial.println(F(" Seconds")); +} +//------------------------------------------------------------------------------ +// read data file and check for overruns +void checkOverrun() { + bool headerPrinted = false; + block_t buf; + uint32_t bgnBlock, endBlock; + uint32_t bn = 0; + + if (!binFile.isOpen()) { + Serial.println(F("No current binary file")); + return; + } + if (!binFile.contiguousRange(&bgnBlock, &endBlock)) { + error("contiguousRange failed"); + } + binFile.rewind(); + Serial.println(); + Serial.println(F("Checking overrun errors - type any character to stop")); + if (binFile.read(&buf , 512) != 512) { + error("Read metadata failed"); + } + bn++; + while (binFile.read(&buf, 512) == 512) { + if (buf.count == 0) { + break; + } + if (buf.overrun) { + if (!headerPrinted) { + Serial.println(); + Serial.println(F("Overruns:")); + Serial.println(F("fileBlockNumber,sdBlockNumber,overrunCount")); + headerPrinted = true; + } + Serial.print(bn); + Serial.print(','); + Serial.print(bgnBlock + bn); + Serial.print(','); + Serial.println(buf.overrun); + } + bn++; + } + if (!headerPrinted) { + Serial.println(F("No errors found")); + } else { + Serial.println(F("Done")); + } +} +//------------------------------------------------------------------------------ +// dump data file to Serial +void dumpData() { + block_t buf; + if (!binFile.isOpen()) { + Serial.println(F("No current binary file")); + return; + } + binFile.rewind(); + if (binFile.read(&buf , 512) != 512) { + error("Read metadata failed"); + } + Serial.println(); + Serial.println(F("Type any character to stop")); + delay(1000); + while (!Serial.available() && binFile.read(&buf , 512) == 512) { + if (buf.count == 0) { + break; + } + if (buf.overrun) { + Serial.print(F("OVERRUN,")); + Serial.println(buf.overrun); + } + for (uint16_t i = 0; i < buf.count; i++) { + Serial.print(buf.data[i], DEC); + if ((i+1)%PIN_COUNT) { + Serial.print(','); + } else { + Serial.println(); + } + } + } + Serial.println(F("Done")); +} +//------------------------------------------------------------------------------ +// log data +// max number of blocks to erase per erase call +uint32_t const ERASE_SIZE = 262144L; +void logData() { + uint32_t bgnBlock, endBlock; + + // Allocate extra buffer space. + block_t block[BUFFER_BLOCK_COUNT]; + + Serial.println(); + + // Initialize ADC and timer1. + adcInit((metadata_t*) &block[0]); + + // Find unused file name. + if (BASE_NAME_SIZE > 6) { + error("FILE_BASE_NAME too long"); + } + while (sd.exists(binName)) { + if (binName[BASE_NAME_SIZE + 1] != '9') { + binName[BASE_NAME_SIZE + 1]++; + } else { + binName[BASE_NAME_SIZE + 1] = '0'; + if (binName[BASE_NAME_SIZE] == '9') { + error("Can't create file name"); + } + binName[BASE_NAME_SIZE]++; + } + } + // Delete old tmp file. + if (sd.exists(TMP_FILE_NAME)) { + Serial.println(F("Deleting tmp file")); + if (!sd.remove(TMP_FILE_NAME)) { + error("Can't remove tmp file"); + } + } + // Create new file. + Serial.println(F("Creating new file")); + binFile.close(); + if (!binFile.createContiguous(TMP_FILE_NAME, 512 * FILE_BLOCK_COUNT)) { + error("createContiguous failed"); + } + // Get the address of the file on the SD. + if (!binFile.contiguousRange(&bgnBlock, &endBlock)) { + error("contiguousRange failed"); + } + // Use SdFat's internal buffer. + uint8_t* cache = (uint8_t*)sd.vol()->cacheClear(); + if (cache == 0) { + error("cacheClear failed"); + } + + // Flash erase all data in the file. + Serial.println(F("Erasing all data")); + uint32_t bgnErase = bgnBlock; + uint32_t endErase; + while (bgnErase < endBlock) { + endErase = bgnErase + ERASE_SIZE; + if (endErase > endBlock) { + endErase = endBlock; + } + if (!sd.card()->erase(bgnErase, endErase)) { + error("erase failed"); + } + bgnErase = endErase + 1; + } + // Start a multiple block write. + if (!sd.card()->writeStart(bgnBlock, FILE_BLOCK_COUNT)) { + error("writeBegin failed"); + } + // Write metadata. + if (!sd.card()->writeData((uint8_t*)&block[0])) { + error("Write metadata failed"); + } + // Initialize queues. + emptyHead = emptyTail = 0; + fullHead = fullTail = 0; + + // Use SdFat buffer for one block. + emptyQueue[emptyHead] = (block_t*)cache; + emptyHead = queueNext(emptyHead); + + // Put rest of buffers in the empty queue. + for (uint8_t i = 0; i < BUFFER_BLOCK_COUNT; i++) { + emptyQueue[emptyHead] = &block[i]; + emptyHead = queueNext(emptyHead); + } + // Give SD time to prepare for big write. + delay(1000); + Serial.println(F("Logging - type any character to stop")); + // Wait for Serial Idle. + Serial.flush(); + delay(10); + uint32_t bn = 1; + uint32_t t0 = millis(); + uint32_t t1 = t0; + uint32_t overruns = 0; + uint32_t count = 0; + uint32_t maxLatency = 0; + + // Start logging interrupts. + adcStart(); + while (1) { + if (fullHead != fullTail) { + // Get address of block to write. + block_t* pBlock = fullQueue[fullTail]; + + // Write block to SD. + uint32_t usec = micros(); + if (!sd.card()->writeData((uint8_t*)pBlock)) { + error("write data failed"); + } + usec = micros() - usec; + t1 = millis(); + if (usec > maxLatency) { + maxLatency = usec; + } + count += pBlock->count; + + // Add overruns and possibly light LED. + if (pBlock->overrun) { + overruns += pBlock->overrun; + if (ERROR_LED_PIN >= 0) { + digitalWrite(ERROR_LED_PIN, HIGH); + } + } + // Move block to empty queue. + emptyQueue[emptyHead] = pBlock; + emptyHead = queueNext(emptyHead); + fullTail = queueNext(fullTail); + bn++; + if (bn == FILE_BLOCK_COUNT) { + // File full so stop ISR calls. + adcStop(); + break; + } + } + if (timerError) { + error("Missed timer event - rate too high"); + } + if (Serial.available()) { + // Stop ISR calls. + adcStop(); + if (isrBuf != 0 && isrBuf->count >= PIN_COUNT) { + // Truncate to last complete sample. + isrBuf->count = PIN_COUNT*(isrBuf->count/PIN_COUNT); + // Put buffer in full queue. + fullQueue[fullHead] = isrBuf; + fullHead = queueNext(fullHead); + isrBuf = 0; + } + if (fullHead == fullTail) { + break; + } + } + } + if (!sd.card()->writeStop()) { + error("writeStop failed"); + } + // Truncate file if recording stopped early. + if (bn != FILE_BLOCK_COUNT) { + Serial.println(F("Truncating file")); + if (!binFile.truncate(512L * bn)) { + error("Can't truncate file"); + } + } + if (!binFile.rename(binName)) { + error("Can't rename file"); + } + Serial.print(F("File renamed: ")); + Serial.println(binName); + Serial.print(F("Max block write usec: ")); + Serial.println(maxLatency); + Serial.print(F("Record time sec: ")); + Serial.println(0.001*(t1 - t0), 3); + Serial.print(F("Sample count: ")); + Serial.println(count/PIN_COUNT); + Serial.print(F("Samples/sec: ")); + Serial.println((1000.0/PIN_COUNT)*count/(t1-t0)); + Serial.print(F("Overruns: ")); + Serial.println(overruns); + Serial.println(F("Done")); +} +//------------------------------------------------------------------------------ +void setup(void) { + if (ERROR_LED_PIN >= 0) { + pinMode(ERROR_LED_PIN, OUTPUT); + } + Serial.begin(9600); + + // Read the first sample pin to init the ADC. + analogRead(PIN_LIST[0]); + + Serial.print(F("FreeStack: ")); + Serial.println(FreeStack()); + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50))) { + sd.initErrorPrint(); + fatalBlink(); + } +} +//------------------------------------------------------------------------------ +void loop(void) { + // Read any Serial data. + do { + delay(10); + } while (Serial.available() && Serial.read() >= 0); + Serial.println(); + Serial.println(F("type:")); + Serial.println(F("c - convert file to csv")); + Serial.println(F("d - dump data to Serial")); + Serial.println(F("e - overrun error details")); + Serial.println(F("r - record ADC data")); + + while(!Serial.available()) { + SysCall::yield(); + } + char c = tolower(Serial.read()); + if (ERROR_LED_PIN >= 0) { + digitalWrite(ERROR_LED_PIN, LOW); + } + // Read any Serial data. + do { + delay(10); + } while (Serial.available() && Serial.read() >= 0); + + if (c == 'c') { + binaryToCsv(); + } else if (c == 'd') { + dumpData(); + } else if (c == 'e') { + checkOverrun(); + } else if (c == 'r') { + logData(); + } else { + Serial.println(F("Invalid entry")); + } +} +#else // __AVR__ +#error This program is only for AVR. +#endif // __AVR__ \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/DirectoryFunctions/DirectoryFunctions.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/DirectoryFunctions/DirectoryFunctions.ino new file mode 100644 index 0000000..2c72b57 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/DirectoryFunctions/DirectoryFunctions.ino @@ -0,0 +1,129 @@ +/* + * Example use of chdir(), ls(), mkdir(), and rmdir(). + */ +#include +#include "SdFat.h" +#include "sdios.h" +// SD card chip select pin. +const uint8_t chipSelect = SS; +//------------------------------------------------------------------------------ + +// File system object. +SdFat sd; + +// Directory file. +SdFile root; + +// Use for file creation in folders. +SdFile file; + +// Create a Serial output stream. +ArduinoOutStream cout(Serial); + +// Buffer for Serial input. +char cinBuf[40]; + +// Create a serial input stream. +ArduinoInStream cin(Serial, cinBuf, sizeof(cinBuf)); +//============================================================================== +// Error messages stored in flash. +#define error(msg) sd.errorHalt(F(msg)) +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + delay(1000); + + cout << F("Type any character to start\n"); + // Wait for input line and discard. + cin.readline(); + cout << endl; + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } + if (sd.exists("Folder1") + || sd.exists("Folder1/file1.txt") + || sd.exists("Folder1/File2.txt")) { + error("Please remove existing Folder1, file1.txt, and File2.txt"); + } + + int rootFileCount = 0; + if (!root.open("/")){ + error("open root failed"); + } + while (file.openNext(&root, O_RDONLY)) { + if (!file.isHidden()) { + rootFileCount++; + } + file.close(); + if (rootFileCount > 10) { + error("Too many files in root. Please use an empty SD."); + } + } + if (rootFileCount) { + cout << F("\nPlease use an empty SD for best results.\n\n"); + delay(1000); + } + // Create a new folder. + if (!sd.mkdir("Folder1")) { + error("Create Folder1 failed"); + } + cout << F("Created Folder1\n"); + + // Create a file in Folder1 using a path. + if (!file.open("Folder1/file1.txt", O_WRONLY | O_CREAT)) { + error("create Folder1/file1.txt failed"); + } + file.close(); + cout << F("Created Folder1/file1.txt\n"); + + // Change volume working directory to Folder1. + if (!sd.chdir("Folder1")) { + error("chdir failed for Folder1.\n"); + } + cout << F("chdir to Folder1\n"); + + // Create File2.txt in current directory. + if (!file.open("File2.txt", O_WRONLY | O_CREAT)) { + error("create File2.txt failed"); + } + file.close(); + cout << F("Created File2.txt in current directory\n"); + + cout << F("\nList of files on the SD.\n"); + sd.ls("/", LS_R); + + // Remove files from current directory. + if (!sd.remove("file1.txt") || !sd.remove("File2.txt")) { + error("remove failed"); + } + cout << F("\nfile1.txt and File2.txt removed.\n"); + + // Change current directory to root. + if (!sd.chdir()) { + error("chdir to root failed.\n"); + } + + cout << F("\nList of files on the SD.\n"); + sd.ls(LS_R); + + // Remove Folder1. + if (!sd.rmdir("Folder1")) { + error("rmdir for Folder1 failed\n"); + } + + cout << F("\nFolder1 removed.\n"); + cout << F("\nList of files on the SD.\n"); + sd.ls(LS_R); + cout << F("Done!\n"); +} +//------------------------------------------------------------------------------ +// Nothing happens in loop. +void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/LongFileName.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/LongFileName.ino new file mode 100644 index 0000000..92d04a0 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/LongFileName.ino @@ -0,0 +1,102 @@ +// Example use of lfnOpenNext and open by index. +// You can use test files located in +// SdFat/examples/LongFileName/testFiles. +#include +#include "SdFat.h" +#include "FreeStack.h" + +// SD card chip select pin. +const uint8_t SD_CS_PIN = SS; + +SdFat sd; +SdFile file; +SdFile dirFile; + +// Number of files found. +uint16_t n = 0; + +// Max of ten files since files are selected with a single digit. +const uint16_t nMax = 10; + +// Position of file's directory entry. +uint16_t dirIndex[nMax]; +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + while (!Serial) {} + delay(1000); + + // Print the location of some test files. + Serial.println(F("\r\n" + "You can use test files located in\r\n" + "SdFat/examples/LongFileName/testFiles")); + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } + Serial.print(F("FreeStack: ")); + Serial.println(FreeStack()); + Serial.println(); + + // List files in root directory. + if (!dirFile.open("/", O_RDONLY)) { + sd.errorHalt("open root failed"); + } + while (n < nMax && file.openNext(&dirFile, O_RDONLY)) { + + // Skip directories and hidden files. + if (!file.isSubDir() && !file.isHidden()) { + + // Save dirIndex of file in directory. + dirIndex[n] = file.dirIndex(); + + // Print the file number and name. + Serial.print(n++); + Serial.write(' '); + file.printName(&Serial); + Serial.println(); + } + file.close(); + } +} +//------------------------------------------------------------------------------ +void loop() { + int c; + + // Read any existing Serial data. + do { + delay(10); + } while (Serial.available() && Serial.read() >= 0); + Serial.print(F("\r\nEnter File Number: ")); + + while (!Serial.available()) { + SysCall::yield(); + } + c = Serial.read(); + uint8_t i = c - '0'; + if (!isdigit(c) || i >= n) { + Serial.println(F("Invald number")); + return; + } + Serial.println(i); + if (!file.open(&dirFile, dirIndex[i], O_RDONLY)) { + sd.errorHalt(F("open")); + } + Serial.println(); + + char last = 0; + + // Copy up to 500 characters to Serial. + for (int k = 0; k < 500 && (c = file.read()) > 0; k++) { + Serial.write(last = (char)c); + } + // Add new line if missing from last line. + if (last != '\n') { + Serial.println(); + } + file.close(); + Serial.flush(); + delay(100); +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/A long name can be 255 characters.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/A long name can be 255 characters.txt new file mode 100644 index 0000000..ccccc1f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/A long name can be 255 characters.txt @@ -0,0 +1,4 @@ +This is "A long name can be 255 characters.txt" +This file has a typical Long File Name. + +The maximum length of a Long File Name is 255 characters. diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/LFN,NAME.TXT b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/LFN,NAME.TXT new file mode 100644 index 0000000..3fc38d6 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/LFN,NAME.TXT @@ -0,0 +1 @@ +LFN,NAME.TXT is not 8.3 since it has a comma. \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/MIXCASE.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/MIXCASE.txt new file mode 100644 index 0000000..cd47677 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/MIXCASE.txt @@ -0,0 +1,5 @@ +MIXCASE.txt does not have a Long File Name. + +Starting with NT, file names of this form, +have the basename and extension character case +encoded in two bits of the 8.3 directory entry. diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/Not_8_3.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/Not_8_3.txt new file mode 100644 index 0000000..acfc433 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/Not_8_3.txt @@ -0,0 +1,2 @@ +Not_8_3.txt has a Long File Name +since the basename is mixed case. \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/OK%83.TXT b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/OK%83.TXT new file mode 100644 index 0000000..6935e78 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/OK%83.TXT @@ -0,0 +1 @@ +OK%83.TXT is a valid 8.3 name. \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/STD_8_3.TXT b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/STD_8_3.TXT new file mode 100644 index 0000000..e0d2234 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/STD_8_3.TXT @@ -0,0 +1 @@ +STD_8_3.TXT - a vanilla 8.3 name. \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/With Blank.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/With Blank.txt new file mode 100644 index 0000000..29cd8a8 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/With Blank.txt @@ -0,0 +1,2 @@ +With Blank.txt +Just another example of a Long File Name. diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/With.Two dots.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/With.Two dots.txt new file mode 100644 index 0000000..f796ec6 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/With.Two dots.txt @@ -0,0 +1,2 @@ +"With Two.dots.txt" +Lots of reasons this is a Long File Name. diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/lower.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/lower.txt new file mode 100644 index 0000000..6f2fa28 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/lower.txt @@ -0,0 +1,5 @@ +lower.txt does not have a Long File Name. + +Starting with NT, file names of this form, +have the basename and extension character case +encoded in two bits of the 8.3 directory entry. diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/mixed.TXT b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/mixed.TXT new file mode 100644 index 0000000..8f54d9a --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/mixed.TXT @@ -0,0 +1,5 @@ +mixed.TXT does not have a Long File Name. + +Starting with NT, file names of this form, +have the basename and extension character case +encoded in two bits of the 8.3 directory entry. \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/LowLatencyLogger.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/LowLatencyLogger.ino new file mode 100644 index 0000000..40aa40d --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/LowLatencyLogger.ino @@ -0,0 +1,655 @@ +/** + * This program logs data to a binary file. Functions are included + * to convert the binary file to a csv text file. + * + * Samples are logged at regular intervals. The maximum logging rate + * depends on the quality of your SD card and the time required to + * read sensor data. This example has been tested at 500 Hz with + * good SD card on an Uno. 4000 HZ is possible on a Due. + * + * If your SD card has a long write latency, it may be necessary to use + * slower sample rates. Using a Mega Arduino helps overcome latency + * problems since 12 512 byte buffers will be used. + * + * Data is written to the file using a SD multiple block write command. + */ +#include +#include "SdFat.h" +#include "FreeStack.h" +#include "UserTypes.h" + +#ifdef __AVR_ATmega328P__ +#include "MinimumSerial.h" +MinimumSerial MinSerial; +#define Serial MinSerial +#endif // __AVR_ATmega328P__ +//============================================================================== +// Start of configuration constants. +//============================================================================== +// Abort run on an overrun. Data before the overrun will be saved. +#define ABORT_ON_OVERRUN 1 +//------------------------------------------------------------------------------ +//Interval between data records in microseconds. +const uint32_t LOG_INTERVAL_USEC = 2000; +//------------------------------------------------------------------------------ +// Set USE_SHARED_SPI non-zero for use of an SPI sensor. +// May not work for some cards. +#ifndef USE_SHARED_SPI +#define USE_SHARED_SPI 0 +#endif // USE_SHARED_SPI +//------------------------------------------------------------------------------ +// Pin definitions. +// +// SD chip select pin. +const uint8_t SD_CS_PIN = SS; +// +// Digital pin to indicate an error, set to -1 if not used. +// The led blinks for fatal errors. The led goes on solid for +// overrun errors and logging continues unless ABORT_ON_OVERRUN +// is non-zero. +#ifdef ERROR_LED_PIN +#undef ERROR_LED_PIN +#endif // ERROR_LED_PIN +const int8_t ERROR_LED_PIN = -1; +//------------------------------------------------------------------------------ +// File definitions. +// +// Maximum file size in blocks. +// The program creates a contiguous file with FILE_BLOCK_COUNT 512 byte blocks. +// This file is flash erased using special SD commands. The file will be +// truncated if logging is stopped early. +const uint32_t FILE_BLOCK_COUNT = 256000; +// +// log file base name if not defined in UserTypes.h +#ifndef FILE_BASE_NAME +#define FILE_BASE_NAME "data" +#endif // FILE_BASE_NAME +//------------------------------------------------------------------------------ +// Buffer definitions. +// +// The logger will use SdFat's buffer plus BUFFER_BLOCK_COUNT-1 additional +// buffers. +// +#ifndef RAMEND +// Assume ARM. Use total of ten 512 byte buffers. +const uint8_t BUFFER_BLOCK_COUNT = 10; +// +#elif RAMEND < 0X8FF +#error Too little SRAM +// +#elif RAMEND < 0X10FF +// Use total of two 512 byte buffers. +const uint8_t BUFFER_BLOCK_COUNT = 2; +// +#elif RAMEND < 0X20FF +// Use total of four 512 byte buffers. +const uint8_t BUFFER_BLOCK_COUNT = 4; +// +#else // RAMEND +// Use total of 12 512 byte buffers. +const uint8_t BUFFER_BLOCK_COUNT = 12; +#endif // RAMEND +//============================================================================== +// End of configuration constants. +//============================================================================== +// Temporary log file. Will be deleted if a reset or power failure occurs. +#define TMP_FILE_NAME FILE_BASE_NAME "##.bin" + +// Size of file base name. +const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1; +const uint8_t FILE_NAME_DIM = BASE_NAME_SIZE + 7; +char binName[FILE_NAME_DIM] = FILE_BASE_NAME "00.bin"; + +SdFat sd; + +SdBaseFile binFile; + +// Number of data records in a block. +const uint16_t DATA_DIM = (512 - 4)/sizeof(data_t); + +//Compute fill so block size is 512 bytes. FILL_DIM may be zero. +const uint16_t FILL_DIM = 512 - 4 - DATA_DIM*sizeof(data_t); + +struct block_t { + uint16_t count; + uint16_t overrun; + data_t data[DATA_DIM]; + uint8_t fill[FILL_DIM]; +}; +//============================================================================== +// Error messages stored in flash. +#define error(msg) {sd.errorPrint(&Serial, F(msg));fatalBlink();} +//------------------------------------------------------------------------------ +// +void fatalBlink() { + while (true) { + SysCall::yield(); + if (ERROR_LED_PIN >= 0) { + digitalWrite(ERROR_LED_PIN, HIGH); + delay(200); + digitalWrite(ERROR_LED_PIN, LOW); + delay(200); + } + } +} +//------------------------------------------------------------------------------ +// read data file and check for overruns +void checkOverrun() { + bool headerPrinted = false; + block_t block; + uint32_t bn = 0; + + if (!binFile.isOpen()) { + Serial.println(); + Serial.println(F("No current binary file")); + return; + } + binFile.rewind(); + Serial.println(); + Serial.print(F("FreeStack: ")); + Serial.println(FreeStack()); + Serial.println(F("Checking overrun errors - type any character to stop")); + while (binFile.read(&block, 512) == 512) { + if (block.count == 0) { + break; + } + if (block.overrun) { + if (!headerPrinted) { + Serial.println(); + Serial.println(F("Overruns:")); + Serial.println(F("fileBlockNumber,sdBlockNumber,overrunCount")); + headerPrinted = true; + } + Serial.print(bn); + Serial.print(','); + Serial.print(binFile.firstBlock() + bn); + Serial.print(','); + Serial.println(block.overrun); + } + bn++; + } + if (!headerPrinted) { + Serial.println(F("No errors found")); + } else { + Serial.println(F("Done")); + } +} +//----------------------------------------------------------------------------- +// Convert binary file to csv file. +void binaryToCsv() { + uint8_t lastPct = 0; + block_t block; + uint32_t t0 = millis(); + uint32_t syncCluster = 0; + SdFile csvFile; + char csvName[FILE_NAME_DIM]; + + if (!binFile.isOpen()) { + Serial.println(); + Serial.println(F("No current binary file")); + return; + } + Serial.println(); + Serial.print(F("FreeStack: ")); + Serial.println(FreeStack()); + + // Create a new csvFile. + strcpy(csvName, binName); + strcpy(&csvName[BASE_NAME_SIZE + 3], "csv"); + + if (!csvFile.open(csvName, O_WRONLY | O_CREAT | O_TRUNC)) { + error("open csvFile failed"); + } + binFile.rewind(); + Serial.print(F("Writing: ")); + Serial.print(csvName); + Serial.println(F(" - type any character to stop")); + printHeader(&csvFile); + uint32_t tPct = millis(); + while (!Serial.available() && binFile.read(&block, 512) == 512) { + uint16_t i; + if (block.count == 0 || block.count > DATA_DIM) { + break; + } + if (block.overrun) { + csvFile.print(F("OVERRUN,")); + csvFile.println(block.overrun); + } + for (i = 0; i < block.count; i++) { + printData(&csvFile, &block.data[i]); + } + if (csvFile.curCluster() != syncCluster) { + csvFile.sync(); + syncCluster = csvFile.curCluster(); + } + if ((millis() - tPct) > 1000) { + uint8_t pct = binFile.curPosition()/(binFile.fileSize()/100); + if (pct != lastPct) { + tPct = millis(); + lastPct = pct; + Serial.print(pct, DEC); + Serial.println('%'); + } + } + if (Serial.available()) { + break; + } + } + csvFile.close(); + Serial.print(F("Done: ")); + Serial.print(0.001*(millis() - t0)); + Serial.println(F(" Seconds")); +} +//----------------------------------------------------------------------------- +void createBinFile() { + // max number of blocks to erase per erase call + const uint32_t ERASE_SIZE = 262144L; + uint32_t bgnBlock, endBlock; + + // Delete old tmp file. + if (sd.exists(TMP_FILE_NAME)) { + Serial.println(F("Deleting tmp file " TMP_FILE_NAME)); + if (!sd.remove(TMP_FILE_NAME)) { + error("Can't remove tmp file"); + } + } + // Create new file. + Serial.println(F("\nCreating new file")); + binFile.close(); + if (!binFile.createContiguous(TMP_FILE_NAME, 512 * FILE_BLOCK_COUNT)) { + error("createContiguous failed"); + } + // Get the address of the file on the SD. + if (!binFile.contiguousRange(&bgnBlock, &endBlock)) { + error("contiguousRange failed"); + } + // Flash erase all data in the file. + Serial.println(F("Erasing all data")); + uint32_t bgnErase = bgnBlock; + uint32_t endErase; + while (bgnErase < endBlock) { + endErase = bgnErase + ERASE_SIZE; + if (endErase > endBlock) { + endErase = endBlock; + } + if (!sd.card()->erase(bgnErase, endErase)) { + error("erase failed"); + } + bgnErase = endErase + 1; + } +} +//------------------------------------------------------------------------------ +// dump data file to Serial +void dumpData() { + block_t block; + if (!binFile.isOpen()) { + Serial.println(); + Serial.println(F("No current binary file")); + return; + } + binFile.rewind(); + Serial.println(); + Serial.println(F("Type any character to stop")); + delay(1000); + printHeader(&Serial); + while (!Serial.available() && binFile.read(&block , 512) == 512) { + if (block.count == 0) { + break; + } + if (block.overrun) { + Serial.print(F("OVERRUN,")); + Serial.println(block.overrun); + } + for (uint16_t i = 0; i < block.count; i++) { + printData(&Serial, &block.data[i]); + } + } + Serial.println(F("Done")); +} +//------------------------------------------------------------------------------ +// log data +void logData() { + createBinFile(); + recordBinFile(); + renameBinFile(); +} +//------------------------------------------------------------------------------ +void openBinFile() { + char name[FILE_NAME_DIM]; + strcpy(name, binName); + Serial.println(F("\nEnter two digit version")); + Serial.write(name, BASE_NAME_SIZE); + for (int i = 0; i < 2; i++) { + while (!Serial.available()) { + SysCall::yield(); + } + char c = Serial.read(); + Serial.write(c); + if (c < '0' || c > '9') { + Serial.println(F("\nInvalid digit")); + return; + } + name[BASE_NAME_SIZE + i] = c; + } + Serial.println(&name[BASE_NAME_SIZE+2]); + if (!sd.exists(name)) { + Serial.println(F("File does not exist")); + return; + } + binFile.close(); + strcpy(binName, name); + if (!binFile.open(binName, O_RDONLY)) { + Serial.println(F("open failed")); + return; + } + Serial.println(F("File opened")); +} +//------------------------------------------------------------------------------ +void recordBinFile() { + const uint8_t QUEUE_DIM = BUFFER_BLOCK_COUNT + 1; + // Index of last queue location. + const uint8_t QUEUE_LAST = QUEUE_DIM - 1; + + // Allocate extra buffer space. + block_t block[BUFFER_BLOCK_COUNT - 1]; + + block_t* curBlock = 0; + + block_t* emptyStack[BUFFER_BLOCK_COUNT]; + uint8_t emptyTop; + uint8_t minTop; + + block_t* fullQueue[QUEUE_DIM]; + uint8_t fullHead = 0; + uint8_t fullTail = 0; + + // Use SdFat's internal buffer. + emptyStack[0] = (block_t*)sd.vol()->cacheClear(); + if (emptyStack[0] == 0) { + error("cacheClear failed"); + } + // Put rest of buffers on the empty stack. + for (int i = 1; i < BUFFER_BLOCK_COUNT; i++) { + emptyStack[i] = &block[i - 1]; + } + emptyTop = BUFFER_BLOCK_COUNT; + minTop = BUFFER_BLOCK_COUNT; + + // Start a multiple block write. + if (!sd.card()->writeStart(binFile.firstBlock())) { + error("writeStart failed"); + } + Serial.print(F("FreeStack: ")); + Serial.println(FreeStack()); + Serial.println(F("Logging - type any character to stop")); + bool closeFile = false; + uint32_t bn = 0; + uint32_t maxLatency = 0; + uint32_t overrun = 0; + uint32_t overrunTotal = 0; + uint32_t logTime = micros(); + while(1) { + // Time for next data record. + logTime += LOG_INTERVAL_USEC; + if (Serial.available()) { + closeFile = true; + } + if (closeFile) { + if (curBlock != 0) { + // Put buffer in full queue. + fullQueue[fullHead] = curBlock; + fullHead = fullHead < QUEUE_LAST ? fullHead + 1 : 0; + curBlock = 0; + } + } else { + if (curBlock == 0 && emptyTop != 0) { + curBlock = emptyStack[--emptyTop]; + if (emptyTop < minTop) { + minTop = emptyTop; + } + curBlock->count = 0; + curBlock->overrun = overrun; + overrun = 0; + } + if ((int32_t)(logTime - micros()) < 0) { + error("Rate too fast"); + } + int32_t delta; + do { + delta = micros() - logTime; + } while (delta < 0); + if (curBlock == 0) { + overrun++; + overrunTotal++; + if (ERROR_LED_PIN >= 0) { + digitalWrite(ERROR_LED_PIN, HIGH); + } +#if ABORT_ON_OVERRUN + Serial.println(F("Overrun abort")); + break; + #endif // ABORT_ON_OVERRUN + } else { +#if USE_SHARED_SPI + sd.card()->spiStop(); +#endif // USE_SHARED_SPI + acquireData(&curBlock->data[curBlock->count++]); +#if USE_SHARED_SPI + sd.card()->spiStart(); +#endif // USE_SHARED_SPI + if (curBlock->count == DATA_DIM) { + fullQueue[fullHead] = curBlock; + fullHead = fullHead < QUEUE_LAST ? fullHead + 1 : 0; + curBlock = 0; + } + } + } + if (fullHead == fullTail) { + // Exit loop if done. + if (closeFile) { + break; + } + } else if (!sd.card()->isBusy()) { + // Get address of block to write. + block_t* pBlock = fullQueue[fullTail]; + fullTail = fullTail < QUEUE_LAST ? fullTail + 1 : 0; + // Write block to SD. + uint32_t usec = micros(); + if (!sd.card()->writeData((uint8_t*)pBlock)) { + error("write data failed"); + } + usec = micros() - usec; + if (usec > maxLatency) { + maxLatency = usec; + } + // Move block to empty queue. + emptyStack[emptyTop++] = pBlock; + bn++; + if (bn == FILE_BLOCK_COUNT) { + // File full so stop + break; + } + } + } + if (!sd.card()->writeStop()) { + error("writeStop failed"); + } + Serial.print(F("Min Free buffers: ")); + Serial.println(minTop); + Serial.print(F("Max block write usec: ")); + Serial.println(maxLatency); + Serial.print(F("Overruns: ")); + Serial.println(overrunTotal); + // Truncate file if recording stopped early. + if (bn != FILE_BLOCK_COUNT) { + Serial.println(F("Truncating file")); + if (!binFile.truncate(512L * bn)) { + error("Can't truncate file"); + } + } +} +//------------------------------------------------------------------------------ +void recoverTmpFile() { + uint16_t count; + if (!binFile.open(TMP_FILE_NAME, O_RDWR)) { + return; + } + if (binFile.read(&count, 2) != 2 || count != DATA_DIM) { + error("Please delete existing " TMP_FILE_NAME); + } + Serial.println(F("\nRecovering data in tmp file " TMP_FILE_NAME)); + uint32_t bgnBlock = 0; + uint32_t endBlock = binFile.fileSize()/512 - 1; + // find last used block. + while (bgnBlock < endBlock) { + uint32_t midBlock = (bgnBlock + endBlock + 1)/2; + binFile.seekSet(512*midBlock); + if (binFile.read(&count, 2) != 2) error("read"); + if (count == 0 || count > DATA_DIM) { + endBlock = midBlock - 1; + } else { + bgnBlock = midBlock; + } + } + // truncate after last used block. + if (!binFile.truncate(512*(bgnBlock + 1))) { + error("Truncate " TMP_FILE_NAME " failed"); + } + renameBinFile(); +} +//----------------------------------------------------------------------------- +void renameBinFile() { + while (sd.exists(binName)) { + if (binName[BASE_NAME_SIZE + 1] != '9') { + binName[BASE_NAME_SIZE + 1]++; + } else { + binName[BASE_NAME_SIZE + 1] = '0'; + if (binName[BASE_NAME_SIZE] == '9') { + error("Can't create file name"); + } + binName[BASE_NAME_SIZE]++; + } + } + if (!binFile.rename(binName)) { + error("Can't rename file"); + } + Serial.print(F("File renamed: ")); + Serial.println(binName); + Serial.print(F("File size: ")); + Serial.print(binFile.fileSize()/512); + Serial.println(F(" blocks")); +} +//------------------------------------------------------------------------------ +void testSensor() { + const uint32_t interval = 200000; + int32_t diff; + data_t data; + Serial.println(F("\nTesting - type any character to stop\n")); + // Wait for Serial Idle. + delay(1000); + printHeader(&Serial); + uint32_t m = micros(); + while (!Serial.available()) { + m += interval; + do { + diff = m - micros(); + } while (diff > 0); + acquireData(&data); + printData(&Serial, &data); + } +} +//------------------------------------------------------------------------------ +void setup(void) { + if (ERROR_LED_PIN >= 0) { + pinMode(ERROR_LED_PIN, OUTPUT); + } + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + Serial.print(F("\nFreeStack: ")); + Serial.println(FreeStack()); + Serial.print(F("Records/block: ")); + Serial.println(DATA_DIM); + if (sizeof(block_t) != 512) { + error("Invalid block size"); + } + // Allow userSetup access to SPI bus. + pinMode(SD_CS_PIN, OUTPUT); + digitalWrite(SD_CS_PIN, HIGH); + + // Setup sensors. + userSetup(); + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50))) { + sd.initErrorPrint(&Serial); + fatalBlink(); + } + // recover existing tmp file. + if (sd.exists(TMP_FILE_NAME)) { + Serial.println(F("\nType 'Y' to recover existing tmp file " TMP_FILE_NAME)); + while (!Serial.available()) { + SysCall::yield(); + } + if (Serial.read() == 'Y') { + recoverTmpFile(); + } else { + error("'Y' not typed, please manually delete " TMP_FILE_NAME); + } + } +} +//------------------------------------------------------------------------------ +void loop(void) { + // Read any Serial data. + do { + delay(10); + } while (Serial.available() && Serial.read() >= 0); + Serial.println(); + Serial.println(F("type:")); + Serial.println(F("b - open existing bin file")); + Serial.println(F("c - convert file to csv")); + Serial.println(F("d - dump data to Serial")); + Serial.println(F("e - overrun error details")); + Serial.println(F("l - list files")); + Serial.println(F("r - record data")); + Serial.println(F("t - test without logging")); + while(!Serial.available()) { + SysCall::yield(); + } +#if WDT_YIELD_TIME_MICROS + Serial.println(F("LowLatencyLogger can not run with watchdog timer")); + SysCall::halt(); +#endif + + char c = tolower(Serial.read()); + + // Discard extra Serial data. + do { + delay(10); + } while (Serial.available() && Serial.read() >= 0); + + if (ERROR_LED_PIN >= 0) { + digitalWrite(ERROR_LED_PIN, LOW); + } + if (c == 'b') { + openBinFile(); + } else if (c == 'c') { + binaryToCsv(); + } else if (c == 'd') { + dumpData(); + } else if (c == 'e') { + checkOverrun(); + } else if (c == 'l') { + Serial.println(F("\nls:")); + sd.ls(&Serial, LS_SIZE); + } else if (c == 'r') { + logData(); + } else if (c == 't') { + testSensor(); + } else { + Serial.println(F("Invalid entry")); + } +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/UserFunctions.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/UserFunctions.cpp new file mode 100644 index 0000000..23be667 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/UserFunctions.cpp @@ -0,0 +1,41 @@ +#include "UserTypes.h" +// User data functions. Modify these functions for your data items. + +// Start time for data +static uint32_t startMicros; + +// Acquire a data record. +void acquireData(data_t* data) { + data->time = micros(); + for (int i = 0; i < ADC_DIM; i++) { + data->adc[i] = analogRead(i); + } +} + +// Print a data record. +void printData(Print* pr, data_t* data) { + if (startMicros == 0) { + startMicros = data->time; + } + pr->print(data->time - startMicros); + for (int i = 0; i < ADC_DIM; i++) { + pr->write(','); + pr->print(data->adc[i]); + } + pr->println(); +} + +// Print data header. +void printHeader(Print* pr) { + startMicros = 0; + pr->print(F("micros")); + for (int i = 0; i < ADC_DIM; i++) { + pr->print(F(",adc")); + pr->print(i); + } + pr->println(); +} + +// Sensor setup +void userSetup() { +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/UserTypes.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/UserTypes.h new file mode 100644 index 0000000..840d4c7 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/UserTypes.h @@ -0,0 +1,15 @@ +#ifndef UserTypes_h +#define UserTypes_h +#include "Arduino.h" +// User data types. Modify for your data items. +#define FILE_BASE_NAME "adc4pin" +const uint8_t ADC_DIM = 4; +struct data_t { + uint32_t time; + uint16_t adc[ADC_DIM]; +}; +void acquireData(data_t* data); +void printData(Print* pr, data_t* data); +void printHeader(Print* pr); +void userSetup(); +#endif // UserTypes_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/LowLatencyLogger.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/LowLatencyLogger.ino new file mode 100644 index 0000000..40aa40d --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/LowLatencyLogger.ino @@ -0,0 +1,655 @@ +/** + * This program logs data to a binary file. Functions are included + * to convert the binary file to a csv text file. + * + * Samples are logged at regular intervals. The maximum logging rate + * depends on the quality of your SD card and the time required to + * read sensor data. This example has been tested at 500 Hz with + * good SD card on an Uno. 4000 HZ is possible on a Due. + * + * If your SD card has a long write latency, it may be necessary to use + * slower sample rates. Using a Mega Arduino helps overcome latency + * problems since 12 512 byte buffers will be used. + * + * Data is written to the file using a SD multiple block write command. + */ +#include +#include "SdFat.h" +#include "FreeStack.h" +#include "UserTypes.h" + +#ifdef __AVR_ATmega328P__ +#include "MinimumSerial.h" +MinimumSerial MinSerial; +#define Serial MinSerial +#endif // __AVR_ATmega328P__ +//============================================================================== +// Start of configuration constants. +//============================================================================== +// Abort run on an overrun. Data before the overrun will be saved. +#define ABORT_ON_OVERRUN 1 +//------------------------------------------------------------------------------ +//Interval between data records in microseconds. +const uint32_t LOG_INTERVAL_USEC = 2000; +//------------------------------------------------------------------------------ +// Set USE_SHARED_SPI non-zero for use of an SPI sensor. +// May not work for some cards. +#ifndef USE_SHARED_SPI +#define USE_SHARED_SPI 0 +#endif // USE_SHARED_SPI +//------------------------------------------------------------------------------ +// Pin definitions. +// +// SD chip select pin. +const uint8_t SD_CS_PIN = SS; +// +// Digital pin to indicate an error, set to -1 if not used. +// The led blinks for fatal errors. The led goes on solid for +// overrun errors and logging continues unless ABORT_ON_OVERRUN +// is non-zero. +#ifdef ERROR_LED_PIN +#undef ERROR_LED_PIN +#endif // ERROR_LED_PIN +const int8_t ERROR_LED_PIN = -1; +//------------------------------------------------------------------------------ +// File definitions. +// +// Maximum file size in blocks. +// The program creates a contiguous file with FILE_BLOCK_COUNT 512 byte blocks. +// This file is flash erased using special SD commands. The file will be +// truncated if logging is stopped early. +const uint32_t FILE_BLOCK_COUNT = 256000; +// +// log file base name if not defined in UserTypes.h +#ifndef FILE_BASE_NAME +#define FILE_BASE_NAME "data" +#endif // FILE_BASE_NAME +//------------------------------------------------------------------------------ +// Buffer definitions. +// +// The logger will use SdFat's buffer plus BUFFER_BLOCK_COUNT-1 additional +// buffers. +// +#ifndef RAMEND +// Assume ARM. Use total of ten 512 byte buffers. +const uint8_t BUFFER_BLOCK_COUNT = 10; +// +#elif RAMEND < 0X8FF +#error Too little SRAM +// +#elif RAMEND < 0X10FF +// Use total of two 512 byte buffers. +const uint8_t BUFFER_BLOCK_COUNT = 2; +// +#elif RAMEND < 0X20FF +// Use total of four 512 byte buffers. +const uint8_t BUFFER_BLOCK_COUNT = 4; +// +#else // RAMEND +// Use total of 12 512 byte buffers. +const uint8_t BUFFER_BLOCK_COUNT = 12; +#endif // RAMEND +//============================================================================== +// End of configuration constants. +//============================================================================== +// Temporary log file. Will be deleted if a reset or power failure occurs. +#define TMP_FILE_NAME FILE_BASE_NAME "##.bin" + +// Size of file base name. +const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1; +const uint8_t FILE_NAME_DIM = BASE_NAME_SIZE + 7; +char binName[FILE_NAME_DIM] = FILE_BASE_NAME "00.bin"; + +SdFat sd; + +SdBaseFile binFile; + +// Number of data records in a block. +const uint16_t DATA_DIM = (512 - 4)/sizeof(data_t); + +//Compute fill so block size is 512 bytes. FILL_DIM may be zero. +const uint16_t FILL_DIM = 512 - 4 - DATA_DIM*sizeof(data_t); + +struct block_t { + uint16_t count; + uint16_t overrun; + data_t data[DATA_DIM]; + uint8_t fill[FILL_DIM]; +}; +//============================================================================== +// Error messages stored in flash. +#define error(msg) {sd.errorPrint(&Serial, F(msg));fatalBlink();} +//------------------------------------------------------------------------------ +// +void fatalBlink() { + while (true) { + SysCall::yield(); + if (ERROR_LED_PIN >= 0) { + digitalWrite(ERROR_LED_PIN, HIGH); + delay(200); + digitalWrite(ERROR_LED_PIN, LOW); + delay(200); + } + } +} +//------------------------------------------------------------------------------ +// read data file and check for overruns +void checkOverrun() { + bool headerPrinted = false; + block_t block; + uint32_t bn = 0; + + if (!binFile.isOpen()) { + Serial.println(); + Serial.println(F("No current binary file")); + return; + } + binFile.rewind(); + Serial.println(); + Serial.print(F("FreeStack: ")); + Serial.println(FreeStack()); + Serial.println(F("Checking overrun errors - type any character to stop")); + while (binFile.read(&block, 512) == 512) { + if (block.count == 0) { + break; + } + if (block.overrun) { + if (!headerPrinted) { + Serial.println(); + Serial.println(F("Overruns:")); + Serial.println(F("fileBlockNumber,sdBlockNumber,overrunCount")); + headerPrinted = true; + } + Serial.print(bn); + Serial.print(','); + Serial.print(binFile.firstBlock() + bn); + Serial.print(','); + Serial.println(block.overrun); + } + bn++; + } + if (!headerPrinted) { + Serial.println(F("No errors found")); + } else { + Serial.println(F("Done")); + } +} +//----------------------------------------------------------------------------- +// Convert binary file to csv file. +void binaryToCsv() { + uint8_t lastPct = 0; + block_t block; + uint32_t t0 = millis(); + uint32_t syncCluster = 0; + SdFile csvFile; + char csvName[FILE_NAME_DIM]; + + if (!binFile.isOpen()) { + Serial.println(); + Serial.println(F("No current binary file")); + return; + } + Serial.println(); + Serial.print(F("FreeStack: ")); + Serial.println(FreeStack()); + + // Create a new csvFile. + strcpy(csvName, binName); + strcpy(&csvName[BASE_NAME_SIZE + 3], "csv"); + + if (!csvFile.open(csvName, O_WRONLY | O_CREAT | O_TRUNC)) { + error("open csvFile failed"); + } + binFile.rewind(); + Serial.print(F("Writing: ")); + Serial.print(csvName); + Serial.println(F(" - type any character to stop")); + printHeader(&csvFile); + uint32_t tPct = millis(); + while (!Serial.available() && binFile.read(&block, 512) == 512) { + uint16_t i; + if (block.count == 0 || block.count > DATA_DIM) { + break; + } + if (block.overrun) { + csvFile.print(F("OVERRUN,")); + csvFile.println(block.overrun); + } + for (i = 0; i < block.count; i++) { + printData(&csvFile, &block.data[i]); + } + if (csvFile.curCluster() != syncCluster) { + csvFile.sync(); + syncCluster = csvFile.curCluster(); + } + if ((millis() - tPct) > 1000) { + uint8_t pct = binFile.curPosition()/(binFile.fileSize()/100); + if (pct != lastPct) { + tPct = millis(); + lastPct = pct; + Serial.print(pct, DEC); + Serial.println('%'); + } + } + if (Serial.available()) { + break; + } + } + csvFile.close(); + Serial.print(F("Done: ")); + Serial.print(0.001*(millis() - t0)); + Serial.println(F(" Seconds")); +} +//----------------------------------------------------------------------------- +void createBinFile() { + // max number of blocks to erase per erase call + const uint32_t ERASE_SIZE = 262144L; + uint32_t bgnBlock, endBlock; + + // Delete old tmp file. + if (sd.exists(TMP_FILE_NAME)) { + Serial.println(F("Deleting tmp file " TMP_FILE_NAME)); + if (!sd.remove(TMP_FILE_NAME)) { + error("Can't remove tmp file"); + } + } + // Create new file. + Serial.println(F("\nCreating new file")); + binFile.close(); + if (!binFile.createContiguous(TMP_FILE_NAME, 512 * FILE_BLOCK_COUNT)) { + error("createContiguous failed"); + } + // Get the address of the file on the SD. + if (!binFile.contiguousRange(&bgnBlock, &endBlock)) { + error("contiguousRange failed"); + } + // Flash erase all data in the file. + Serial.println(F("Erasing all data")); + uint32_t bgnErase = bgnBlock; + uint32_t endErase; + while (bgnErase < endBlock) { + endErase = bgnErase + ERASE_SIZE; + if (endErase > endBlock) { + endErase = endBlock; + } + if (!sd.card()->erase(bgnErase, endErase)) { + error("erase failed"); + } + bgnErase = endErase + 1; + } +} +//------------------------------------------------------------------------------ +// dump data file to Serial +void dumpData() { + block_t block; + if (!binFile.isOpen()) { + Serial.println(); + Serial.println(F("No current binary file")); + return; + } + binFile.rewind(); + Serial.println(); + Serial.println(F("Type any character to stop")); + delay(1000); + printHeader(&Serial); + while (!Serial.available() && binFile.read(&block , 512) == 512) { + if (block.count == 0) { + break; + } + if (block.overrun) { + Serial.print(F("OVERRUN,")); + Serial.println(block.overrun); + } + for (uint16_t i = 0; i < block.count; i++) { + printData(&Serial, &block.data[i]); + } + } + Serial.println(F("Done")); +} +//------------------------------------------------------------------------------ +// log data +void logData() { + createBinFile(); + recordBinFile(); + renameBinFile(); +} +//------------------------------------------------------------------------------ +void openBinFile() { + char name[FILE_NAME_DIM]; + strcpy(name, binName); + Serial.println(F("\nEnter two digit version")); + Serial.write(name, BASE_NAME_SIZE); + for (int i = 0; i < 2; i++) { + while (!Serial.available()) { + SysCall::yield(); + } + char c = Serial.read(); + Serial.write(c); + if (c < '0' || c > '9') { + Serial.println(F("\nInvalid digit")); + return; + } + name[BASE_NAME_SIZE + i] = c; + } + Serial.println(&name[BASE_NAME_SIZE+2]); + if (!sd.exists(name)) { + Serial.println(F("File does not exist")); + return; + } + binFile.close(); + strcpy(binName, name); + if (!binFile.open(binName, O_RDONLY)) { + Serial.println(F("open failed")); + return; + } + Serial.println(F("File opened")); +} +//------------------------------------------------------------------------------ +void recordBinFile() { + const uint8_t QUEUE_DIM = BUFFER_BLOCK_COUNT + 1; + // Index of last queue location. + const uint8_t QUEUE_LAST = QUEUE_DIM - 1; + + // Allocate extra buffer space. + block_t block[BUFFER_BLOCK_COUNT - 1]; + + block_t* curBlock = 0; + + block_t* emptyStack[BUFFER_BLOCK_COUNT]; + uint8_t emptyTop; + uint8_t minTop; + + block_t* fullQueue[QUEUE_DIM]; + uint8_t fullHead = 0; + uint8_t fullTail = 0; + + // Use SdFat's internal buffer. + emptyStack[0] = (block_t*)sd.vol()->cacheClear(); + if (emptyStack[0] == 0) { + error("cacheClear failed"); + } + // Put rest of buffers on the empty stack. + for (int i = 1; i < BUFFER_BLOCK_COUNT; i++) { + emptyStack[i] = &block[i - 1]; + } + emptyTop = BUFFER_BLOCK_COUNT; + minTop = BUFFER_BLOCK_COUNT; + + // Start a multiple block write. + if (!sd.card()->writeStart(binFile.firstBlock())) { + error("writeStart failed"); + } + Serial.print(F("FreeStack: ")); + Serial.println(FreeStack()); + Serial.println(F("Logging - type any character to stop")); + bool closeFile = false; + uint32_t bn = 0; + uint32_t maxLatency = 0; + uint32_t overrun = 0; + uint32_t overrunTotal = 0; + uint32_t logTime = micros(); + while(1) { + // Time for next data record. + logTime += LOG_INTERVAL_USEC; + if (Serial.available()) { + closeFile = true; + } + if (closeFile) { + if (curBlock != 0) { + // Put buffer in full queue. + fullQueue[fullHead] = curBlock; + fullHead = fullHead < QUEUE_LAST ? fullHead + 1 : 0; + curBlock = 0; + } + } else { + if (curBlock == 0 && emptyTop != 0) { + curBlock = emptyStack[--emptyTop]; + if (emptyTop < minTop) { + minTop = emptyTop; + } + curBlock->count = 0; + curBlock->overrun = overrun; + overrun = 0; + } + if ((int32_t)(logTime - micros()) < 0) { + error("Rate too fast"); + } + int32_t delta; + do { + delta = micros() - logTime; + } while (delta < 0); + if (curBlock == 0) { + overrun++; + overrunTotal++; + if (ERROR_LED_PIN >= 0) { + digitalWrite(ERROR_LED_PIN, HIGH); + } +#if ABORT_ON_OVERRUN + Serial.println(F("Overrun abort")); + break; + #endif // ABORT_ON_OVERRUN + } else { +#if USE_SHARED_SPI + sd.card()->spiStop(); +#endif // USE_SHARED_SPI + acquireData(&curBlock->data[curBlock->count++]); +#if USE_SHARED_SPI + sd.card()->spiStart(); +#endif // USE_SHARED_SPI + if (curBlock->count == DATA_DIM) { + fullQueue[fullHead] = curBlock; + fullHead = fullHead < QUEUE_LAST ? fullHead + 1 : 0; + curBlock = 0; + } + } + } + if (fullHead == fullTail) { + // Exit loop if done. + if (closeFile) { + break; + } + } else if (!sd.card()->isBusy()) { + // Get address of block to write. + block_t* pBlock = fullQueue[fullTail]; + fullTail = fullTail < QUEUE_LAST ? fullTail + 1 : 0; + // Write block to SD. + uint32_t usec = micros(); + if (!sd.card()->writeData((uint8_t*)pBlock)) { + error("write data failed"); + } + usec = micros() - usec; + if (usec > maxLatency) { + maxLatency = usec; + } + // Move block to empty queue. + emptyStack[emptyTop++] = pBlock; + bn++; + if (bn == FILE_BLOCK_COUNT) { + // File full so stop + break; + } + } + } + if (!sd.card()->writeStop()) { + error("writeStop failed"); + } + Serial.print(F("Min Free buffers: ")); + Serial.println(minTop); + Serial.print(F("Max block write usec: ")); + Serial.println(maxLatency); + Serial.print(F("Overruns: ")); + Serial.println(overrunTotal); + // Truncate file if recording stopped early. + if (bn != FILE_BLOCK_COUNT) { + Serial.println(F("Truncating file")); + if (!binFile.truncate(512L * bn)) { + error("Can't truncate file"); + } + } +} +//------------------------------------------------------------------------------ +void recoverTmpFile() { + uint16_t count; + if (!binFile.open(TMP_FILE_NAME, O_RDWR)) { + return; + } + if (binFile.read(&count, 2) != 2 || count != DATA_DIM) { + error("Please delete existing " TMP_FILE_NAME); + } + Serial.println(F("\nRecovering data in tmp file " TMP_FILE_NAME)); + uint32_t bgnBlock = 0; + uint32_t endBlock = binFile.fileSize()/512 - 1; + // find last used block. + while (bgnBlock < endBlock) { + uint32_t midBlock = (bgnBlock + endBlock + 1)/2; + binFile.seekSet(512*midBlock); + if (binFile.read(&count, 2) != 2) error("read"); + if (count == 0 || count > DATA_DIM) { + endBlock = midBlock - 1; + } else { + bgnBlock = midBlock; + } + } + // truncate after last used block. + if (!binFile.truncate(512*(bgnBlock + 1))) { + error("Truncate " TMP_FILE_NAME " failed"); + } + renameBinFile(); +} +//----------------------------------------------------------------------------- +void renameBinFile() { + while (sd.exists(binName)) { + if (binName[BASE_NAME_SIZE + 1] != '9') { + binName[BASE_NAME_SIZE + 1]++; + } else { + binName[BASE_NAME_SIZE + 1] = '0'; + if (binName[BASE_NAME_SIZE] == '9') { + error("Can't create file name"); + } + binName[BASE_NAME_SIZE]++; + } + } + if (!binFile.rename(binName)) { + error("Can't rename file"); + } + Serial.print(F("File renamed: ")); + Serial.println(binName); + Serial.print(F("File size: ")); + Serial.print(binFile.fileSize()/512); + Serial.println(F(" blocks")); +} +//------------------------------------------------------------------------------ +void testSensor() { + const uint32_t interval = 200000; + int32_t diff; + data_t data; + Serial.println(F("\nTesting - type any character to stop\n")); + // Wait for Serial Idle. + delay(1000); + printHeader(&Serial); + uint32_t m = micros(); + while (!Serial.available()) { + m += interval; + do { + diff = m - micros(); + } while (diff > 0); + acquireData(&data); + printData(&Serial, &data); + } +} +//------------------------------------------------------------------------------ +void setup(void) { + if (ERROR_LED_PIN >= 0) { + pinMode(ERROR_LED_PIN, OUTPUT); + } + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + Serial.print(F("\nFreeStack: ")); + Serial.println(FreeStack()); + Serial.print(F("Records/block: ")); + Serial.println(DATA_DIM); + if (sizeof(block_t) != 512) { + error("Invalid block size"); + } + // Allow userSetup access to SPI bus. + pinMode(SD_CS_PIN, OUTPUT); + digitalWrite(SD_CS_PIN, HIGH); + + // Setup sensors. + userSetup(); + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50))) { + sd.initErrorPrint(&Serial); + fatalBlink(); + } + // recover existing tmp file. + if (sd.exists(TMP_FILE_NAME)) { + Serial.println(F("\nType 'Y' to recover existing tmp file " TMP_FILE_NAME)); + while (!Serial.available()) { + SysCall::yield(); + } + if (Serial.read() == 'Y') { + recoverTmpFile(); + } else { + error("'Y' not typed, please manually delete " TMP_FILE_NAME); + } + } +} +//------------------------------------------------------------------------------ +void loop(void) { + // Read any Serial data. + do { + delay(10); + } while (Serial.available() && Serial.read() >= 0); + Serial.println(); + Serial.println(F("type:")); + Serial.println(F("b - open existing bin file")); + Serial.println(F("c - convert file to csv")); + Serial.println(F("d - dump data to Serial")); + Serial.println(F("e - overrun error details")); + Serial.println(F("l - list files")); + Serial.println(F("r - record data")); + Serial.println(F("t - test without logging")); + while(!Serial.available()) { + SysCall::yield(); + } +#if WDT_YIELD_TIME_MICROS + Serial.println(F("LowLatencyLogger can not run with watchdog timer")); + SysCall::halt(); +#endif + + char c = tolower(Serial.read()); + + // Discard extra Serial data. + do { + delay(10); + } while (Serial.available() && Serial.read() >= 0); + + if (ERROR_LED_PIN >= 0) { + digitalWrite(ERROR_LED_PIN, LOW); + } + if (c == 'b') { + openBinFile(); + } else if (c == 'c') { + binaryToCsv(); + } else if (c == 'd') { + dumpData(); + } else if (c == 'e') { + checkOverrun(); + } else if (c == 'l') { + Serial.println(F("\nls:")); + sd.ls(&Serial, LS_SIZE); + } else if (c == 'r') { + logData(); + } else if (c == 't') { + testSensor(); + } else { + Serial.println(F("Invalid entry")); + } +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/LowLatencyLoggerADXL345.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/LowLatencyLoggerADXL345.ino new file mode 100644 index 0000000..91c8fcc --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/LowLatencyLoggerADXL345.ino @@ -0,0 +1 @@ +// Empty file with name LowLatencyLoggerADXL345.ino to make IDE happy. \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/UserFunctions.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/UserFunctions.cpp new file mode 100644 index 0000000..2f1fea3 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/UserFunctions.cpp @@ -0,0 +1,70 @@ +#include "UserTypes.h" +// User data functions. Modify these functions for your data items. + +// Start time for data +static uint32_t startMicros; + +const uint8_t ADXL345_CS = 9; + +const uint8_t POWER_CTL = 0x2D; //Power Control Register +const uint8_t DATA_FORMAT = 0x31; +const uint8_t DATAX0 = 0x32; //X-Axis Data 0 +const uint8_t DATAX1 = 0x33; //X-Axis Data 1 +const uint8_t DATAY0 = 0x34; //Y-Axis Data 0 +const uint8_t DATAY1 = 0x35; //Y-Axis Data 1 +const uint8_t DATAZ0 = 0x36; //Z-Axis Data 0 +const uint8_t DATAZ1 = 0x37; //Z-Axis Data 1 + +void writeADXL345Register(const uint8_t registerAddress, const uint8_t value) { + // Max SPI clock frequency is 5 MHz with CPOL = 1 and CPHA = 1. + SPI.beginTransaction(SPISettings(5000000, MSBFIRST, SPI_MODE3)); + digitalWrite(ADXL345_CS, LOW); + SPI.transfer(registerAddress); + SPI.transfer(value); + digitalWrite(ADXL345_CS, HIGH); + SPI.endTransaction(); +} + +void userSetup() { + SPI.begin(); + pinMode(ADXL345_CS, OUTPUT); + digitalWrite(ADXL345_CS, HIGH); + //Put the ADXL345 into +/- 4G range by writing the value 0x01 to the DATA_FORMAT register. + writeADXL345Register(DATA_FORMAT, 0x01); + //Put the ADXL345 into Measurement Mode by writing 0x08 to the POWER_CTL register. + writeADXL345Register(POWER_CTL, 0x08); //Measurement mode +} + +// Acquire a data record. +void acquireData(data_t* data) { + // Max SPI clock frequency is 5 MHz with CPOL = 1 and CPHA = 1. + SPI.beginTransaction(SPISettings(5000000, MSBFIRST, SPI_MODE3)); + data->time = micros(); + digitalWrite(ADXL345_CS, LOW); + // Read multiple bytes so or 0XC0 with address. + SPI.transfer(DATAX0 | 0XC0); + data->accel[0] = SPI.transfer(0) | (SPI.transfer(0) << 8); + data->accel[1] = SPI.transfer(0) | (SPI.transfer(0) << 8); + data->accel[2] = SPI.transfer(0) | (SPI.transfer(0) << 8); + digitalWrite(ADXL345_CS, HIGH); + SPI.endTransaction(); +} + +// Print a data record. +void printData(Print* pr, data_t* data) { + if (startMicros == 0) { + startMicros = data->time; + } + pr->print(data->time - startMicros); + for (int i = 0; i < ACCEL_DIM; i++) { + pr->write(','); + pr->print(data->accel[i]); + } + pr->println(); +} + +// Print data header. +void printHeader(Print* pr) { + startMicros = 0; + pr->println(F("micros,ax,ay,az")); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/UserTypes.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/UserTypes.h new file mode 100644 index 0000000..56bc873 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/UserTypes.h @@ -0,0 +1,17 @@ +#ifndef UserTypes_h +#define UserTypes_h +#include "Arduino.h" +#include "SPI.h" +#define USE_SHARED_SPI 1 +#define FILE_BASE_NAME "ADXL4G" +// User data types. Modify for your data items. +const uint8_t ACCEL_DIM = 3; +struct data_t { + uint32_t time; + int16_t accel[ACCEL_DIM]; +}; +void acquireData(data_t* data); +void printData(Print* pr, data_t* data); +void printHeader(Print* pr); +void userSetup(); +#endif // UserTypes_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/readme.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/readme.txt new file mode 100644 index 0000000..a68ba78 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/readme.txt @@ -0,0 +1 @@ +Test of shared SPI for LowLatencyLogger. \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/LowLatencyLogger.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/LowLatencyLogger.ino new file mode 100644 index 0000000..40aa40d --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/LowLatencyLogger.ino @@ -0,0 +1,655 @@ +/** + * This program logs data to a binary file. Functions are included + * to convert the binary file to a csv text file. + * + * Samples are logged at regular intervals. The maximum logging rate + * depends on the quality of your SD card and the time required to + * read sensor data. This example has been tested at 500 Hz with + * good SD card on an Uno. 4000 HZ is possible on a Due. + * + * If your SD card has a long write latency, it may be necessary to use + * slower sample rates. Using a Mega Arduino helps overcome latency + * problems since 12 512 byte buffers will be used. + * + * Data is written to the file using a SD multiple block write command. + */ +#include +#include "SdFat.h" +#include "FreeStack.h" +#include "UserTypes.h" + +#ifdef __AVR_ATmega328P__ +#include "MinimumSerial.h" +MinimumSerial MinSerial; +#define Serial MinSerial +#endif // __AVR_ATmega328P__ +//============================================================================== +// Start of configuration constants. +//============================================================================== +// Abort run on an overrun. Data before the overrun will be saved. +#define ABORT_ON_OVERRUN 1 +//------------------------------------------------------------------------------ +//Interval between data records in microseconds. +const uint32_t LOG_INTERVAL_USEC = 2000; +//------------------------------------------------------------------------------ +// Set USE_SHARED_SPI non-zero for use of an SPI sensor. +// May not work for some cards. +#ifndef USE_SHARED_SPI +#define USE_SHARED_SPI 0 +#endif // USE_SHARED_SPI +//------------------------------------------------------------------------------ +// Pin definitions. +// +// SD chip select pin. +const uint8_t SD_CS_PIN = SS; +// +// Digital pin to indicate an error, set to -1 if not used. +// The led blinks for fatal errors. The led goes on solid for +// overrun errors and logging continues unless ABORT_ON_OVERRUN +// is non-zero. +#ifdef ERROR_LED_PIN +#undef ERROR_LED_PIN +#endif // ERROR_LED_PIN +const int8_t ERROR_LED_PIN = -1; +//------------------------------------------------------------------------------ +// File definitions. +// +// Maximum file size in blocks. +// The program creates a contiguous file with FILE_BLOCK_COUNT 512 byte blocks. +// This file is flash erased using special SD commands. The file will be +// truncated if logging is stopped early. +const uint32_t FILE_BLOCK_COUNT = 256000; +// +// log file base name if not defined in UserTypes.h +#ifndef FILE_BASE_NAME +#define FILE_BASE_NAME "data" +#endif // FILE_BASE_NAME +//------------------------------------------------------------------------------ +// Buffer definitions. +// +// The logger will use SdFat's buffer plus BUFFER_BLOCK_COUNT-1 additional +// buffers. +// +#ifndef RAMEND +// Assume ARM. Use total of ten 512 byte buffers. +const uint8_t BUFFER_BLOCK_COUNT = 10; +// +#elif RAMEND < 0X8FF +#error Too little SRAM +// +#elif RAMEND < 0X10FF +// Use total of two 512 byte buffers. +const uint8_t BUFFER_BLOCK_COUNT = 2; +// +#elif RAMEND < 0X20FF +// Use total of four 512 byte buffers. +const uint8_t BUFFER_BLOCK_COUNT = 4; +// +#else // RAMEND +// Use total of 12 512 byte buffers. +const uint8_t BUFFER_BLOCK_COUNT = 12; +#endif // RAMEND +//============================================================================== +// End of configuration constants. +//============================================================================== +// Temporary log file. Will be deleted if a reset or power failure occurs. +#define TMP_FILE_NAME FILE_BASE_NAME "##.bin" + +// Size of file base name. +const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1; +const uint8_t FILE_NAME_DIM = BASE_NAME_SIZE + 7; +char binName[FILE_NAME_DIM] = FILE_BASE_NAME "00.bin"; + +SdFat sd; + +SdBaseFile binFile; + +// Number of data records in a block. +const uint16_t DATA_DIM = (512 - 4)/sizeof(data_t); + +//Compute fill so block size is 512 bytes. FILL_DIM may be zero. +const uint16_t FILL_DIM = 512 - 4 - DATA_DIM*sizeof(data_t); + +struct block_t { + uint16_t count; + uint16_t overrun; + data_t data[DATA_DIM]; + uint8_t fill[FILL_DIM]; +}; +//============================================================================== +// Error messages stored in flash. +#define error(msg) {sd.errorPrint(&Serial, F(msg));fatalBlink();} +//------------------------------------------------------------------------------ +// +void fatalBlink() { + while (true) { + SysCall::yield(); + if (ERROR_LED_PIN >= 0) { + digitalWrite(ERROR_LED_PIN, HIGH); + delay(200); + digitalWrite(ERROR_LED_PIN, LOW); + delay(200); + } + } +} +//------------------------------------------------------------------------------ +// read data file and check for overruns +void checkOverrun() { + bool headerPrinted = false; + block_t block; + uint32_t bn = 0; + + if (!binFile.isOpen()) { + Serial.println(); + Serial.println(F("No current binary file")); + return; + } + binFile.rewind(); + Serial.println(); + Serial.print(F("FreeStack: ")); + Serial.println(FreeStack()); + Serial.println(F("Checking overrun errors - type any character to stop")); + while (binFile.read(&block, 512) == 512) { + if (block.count == 0) { + break; + } + if (block.overrun) { + if (!headerPrinted) { + Serial.println(); + Serial.println(F("Overruns:")); + Serial.println(F("fileBlockNumber,sdBlockNumber,overrunCount")); + headerPrinted = true; + } + Serial.print(bn); + Serial.print(','); + Serial.print(binFile.firstBlock() + bn); + Serial.print(','); + Serial.println(block.overrun); + } + bn++; + } + if (!headerPrinted) { + Serial.println(F("No errors found")); + } else { + Serial.println(F("Done")); + } +} +//----------------------------------------------------------------------------- +// Convert binary file to csv file. +void binaryToCsv() { + uint8_t lastPct = 0; + block_t block; + uint32_t t0 = millis(); + uint32_t syncCluster = 0; + SdFile csvFile; + char csvName[FILE_NAME_DIM]; + + if (!binFile.isOpen()) { + Serial.println(); + Serial.println(F("No current binary file")); + return; + } + Serial.println(); + Serial.print(F("FreeStack: ")); + Serial.println(FreeStack()); + + // Create a new csvFile. + strcpy(csvName, binName); + strcpy(&csvName[BASE_NAME_SIZE + 3], "csv"); + + if (!csvFile.open(csvName, O_WRONLY | O_CREAT | O_TRUNC)) { + error("open csvFile failed"); + } + binFile.rewind(); + Serial.print(F("Writing: ")); + Serial.print(csvName); + Serial.println(F(" - type any character to stop")); + printHeader(&csvFile); + uint32_t tPct = millis(); + while (!Serial.available() && binFile.read(&block, 512) == 512) { + uint16_t i; + if (block.count == 0 || block.count > DATA_DIM) { + break; + } + if (block.overrun) { + csvFile.print(F("OVERRUN,")); + csvFile.println(block.overrun); + } + for (i = 0; i < block.count; i++) { + printData(&csvFile, &block.data[i]); + } + if (csvFile.curCluster() != syncCluster) { + csvFile.sync(); + syncCluster = csvFile.curCluster(); + } + if ((millis() - tPct) > 1000) { + uint8_t pct = binFile.curPosition()/(binFile.fileSize()/100); + if (pct != lastPct) { + tPct = millis(); + lastPct = pct; + Serial.print(pct, DEC); + Serial.println('%'); + } + } + if (Serial.available()) { + break; + } + } + csvFile.close(); + Serial.print(F("Done: ")); + Serial.print(0.001*(millis() - t0)); + Serial.println(F(" Seconds")); +} +//----------------------------------------------------------------------------- +void createBinFile() { + // max number of blocks to erase per erase call + const uint32_t ERASE_SIZE = 262144L; + uint32_t bgnBlock, endBlock; + + // Delete old tmp file. + if (sd.exists(TMP_FILE_NAME)) { + Serial.println(F("Deleting tmp file " TMP_FILE_NAME)); + if (!sd.remove(TMP_FILE_NAME)) { + error("Can't remove tmp file"); + } + } + // Create new file. + Serial.println(F("\nCreating new file")); + binFile.close(); + if (!binFile.createContiguous(TMP_FILE_NAME, 512 * FILE_BLOCK_COUNT)) { + error("createContiguous failed"); + } + // Get the address of the file on the SD. + if (!binFile.contiguousRange(&bgnBlock, &endBlock)) { + error("contiguousRange failed"); + } + // Flash erase all data in the file. + Serial.println(F("Erasing all data")); + uint32_t bgnErase = bgnBlock; + uint32_t endErase; + while (bgnErase < endBlock) { + endErase = bgnErase + ERASE_SIZE; + if (endErase > endBlock) { + endErase = endBlock; + } + if (!sd.card()->erase(bgnErase, endErase)) { + error("erase failed"); + } + bgnErase = endErase + 1; + } +} +//------------------------------------------------------------------------------ +// dump data file to Serial +void dumpData() { + block_t block; + if (!binFile.isOpen()) { + Serial.println(); + Serial.println(F("No current binary file")); + return; + } + binFile.rewind(); + Serial.println(); + Serial.println(F("Type any character to stop")); + delay(1000); + printHeader(&Serial); + while (!Serial.available() && binFile.read(&block , 512) == 512) { + if (block.count == 0) { + break; + } + if (block.overrun) { + Serial.print(F("OVERRUN,")); + Serial.println(block.overrun); + } + for (uint16_t i = 0; i < block.count; i++) { + printData(&Serial, &block.data[i]); + } + } + Serial.println(F("Done")); +} +//------------------------------------------------------------------------------ +// log data +void logData() { + createBinFile(); + recordBinFile(); + renameBinFile(); +} +//------------------------------------------------------------------------------ +void openBinFile() { + char name[FILE_NAME_DIM]; + strcpy(name, binName); + Serial.println(F("\nEnter two digit version")); + Serial.write(name, BASE_NAME_SIZE); + for (int i = 0; i < 2; i++) { + while (!Serial.available()) { + SysCall::yield(); + } + char c = Serial.read(); + Serial.write(c); + if (c < '0' || c > '9') { + Serial.println(F("\nInvalid digit")); + return; + } + name[BASE_NAME_SIZE + i] = c; + } + Serial.println(&name[BASE_NAME_SIZE+2]); + if (!sd.exists(name)) { + Serial.println(F("File does not exist")); + return; + } + binFile.close(); + strcpy(binName, name); + if (!binFile.open(binName, O_RDONLY)) { + Serial.println(F("open failed")); + return; + } + Serial.println(F("File opened")); +} +//------------------------------------------------------------------------------ +void recordBinFile() { + const uint8_t QUEUE_DIM = BUFFER_BLOCK_COUNT + 1; + // Index of last queue location. + const uint8_t QUEUE_LAST = QUEUE_DIM - 1; + + // Allocate extra buffer space. + block_t block[BUFFER_BLOCK_COUNT - 1]; + + block_t* curBlock = 0; + + block_t* emptyStack[BUFFER_BLOCK_COUNT]; + uint8_t emptyTop; + uint8_t minTop; + + block_t* fullQueue[QUEUE_DIM]; + uint8_t fullHead = 0; + uint8_t fullTail = 0; + + // Use SdFat's internal buffer. + emptyStack[0] = (block_t*)sd.vol()->cacheClear(); + if (emptyStack[0] == 0) { + error("cacheClear failed"); + } + // Put rest of buffers on the empty stack. + for (int i = 1; i < BUFFER_BLOCK_COUNT; i++) { + emptyStack[i] = &block[i - 1]; + } + emptyTop = BUFFER_BLOCK_COUNT; + minTop = BUFFER_BLOCK_COUNT; + + // Start a multiple block write. + if (!sd.card()->writeStart(binFile.firstBlock())) { + error("writeStart failed"); + } + Serial.print(F("FreeStack: ")); + Serial.println(FreeStack()); + Serial.println(F("Logging - type any character to stop")); + bool closeFile = false; + uint32_t bn = 0; + uint32_t maxLatency = 0; + uint32_t overrun = 0; + uint32_t overrunTotal = 0; + uint32_t logTime = micros(); + while(1) { + // Time for next data record. + logTime += LOG_INTERVAL_USEC; + if (Serial.available()) { + closeFile = true; + } + if (closeFile) { + if (curBlock != 0) { + // Put buffer in full queue. + fullQueue[fullHead] = curBlock; + fullHead = fullHead < QUEUE_LAST ? fullHead + 1 : 0; + curBlock = 0; + } + } else { + if (curBlock == 0 && emptyTop != 0) { + curBlock = emptyStack[--emptyTop]; + if (emptyTop < minTop) { + minTop = emptyTop; + } + curBlock->count = 0; + curBlock->overrun = overrun; + overrun = 0; + } + if ((int32_t)(logTime - micros()) < 0) { + error("Rate too fast"); + } + int32_t delta; + do { + delta = micros() - logTime; + } while (delta < 0); + if (curBlock == 0) { + overrun++; + overrunTotal++; + if (ERROR_LED_PIN >= 0) { + digitalWrite(ERROR_LED_PIN, HIGH); + } +#if ABORT_ON_OVERRUN + Serial.println(F("Overrun abort")); + break; + #endif // ABORT_ON_OVERRUN + } else { +#if USE_SHARED_SPI + sd.card()->spiStop(); +#endif // USE_SHARED_SPI + acquireData(&curBlock->data[curBlock->count++]); +#if USE_SHARED_SPI + sd.card()->spiStart(); +#endif // USE_SHARED_SPI + if (curBlock->count == DATA_DIM) { + fullQueue[fullHead] = curBlock; + fullHead = fullHead < QUEUE_LAST ? fullHead + 1 : 0; + curBlock = 0; + } + } + } + if (fullHead == fullTail) { + // Exit loop if done. + if (closeFile) { + break; + } + } else if (!sd.card()->isBusy()) { + // Get address of block to write. + block_t* pBlock = fullQueue[fullTail]; + fullTail = fullTail < QUEUE_LAST ? fullTail + 1 : 0; + // Write block to SD. + uint32_t usec = micros(); + if (!sd.card()->writeData((uint8_t*)pBlock)) { + error("write data failed"); + } + usec = micros() - usec; + if (usec > maxLatency) { + maxLatency = usec; + } + // Move block to empty queue. + emptyStack[emptyTop++] = pBlock; + bn++; + if (bn == FILE_BLOCK_COUNT) { + // File full so stop + break; + } + } + } + if (!sd.card()->writeStop()) { + error("writeStop failed"); + } + Serial.print(F("Min Free buffers: ")); + Serial.println(minTop); + Serial.print(F("Max block write usec: ")); + Serial.println(maxLatency); + Serial.print(F("Overruns: ")); + Serial.println(overrunTotal); + // Truncate file if recording stopped early. + if (bn != FILE_BLOCK_COUNT) { + Serial.println(F("Truncating file")); + if (!binFile.truncate(512L * bn)) { + error("Can't truncate file"); + } + } +} +//------------------------------------------------------------------------------ +void recoverTmpFile() { + uint16_t count; + if (!binFile.open(TMP_FILE_NAME, O_RDWR)) { + return; + } + if (binFile.read(&count, 2) != 2 || count != DATA_DIM) { + error("Please delete existing " TMP_FILE_NAME); + } + Serial.println(F("\nRecovering data in tmp file " TMP_FILE_NAME)); + uint32_t bgnBlock = 0; + uint32_t endBlock = binFile.fileSize()/512 - 1; + // find last used block. + while (bgnBlock < endBlock) { + uint32_t midBlock = (bgnBlock + endBlock + 1)/2; + binFile.seekSet(512*midBlock); + if (binFile.read(&count, 2) != 2) error("read"); + if (count == 0 || count > DATA_DIM) { + endBlock = midBlock - 1; + } else { + bgnBlock = midBlock; + } + } + // truncate after last used block. + if (!binFile.truncate(512*(bgnBlock + 1))) { + error("Truncate " TMP_FILE_NAME " failed"); + } + renameBinFile(); +} +//----------------------------------------------------------------------------- +void renameBinFile() { + while (sd.exists(binName)) { + if (binName[BASE_NAME_SIZE + 1] != '9') { + binName[BASE_NAME_SIZE + 1]++; + } else { + binName[BASE_NAME_SIZE + 1] = '0'; + if (binName[BASE_NAME_SIZE] == '9') { + error("Can't create file name"); + } + binName[BASE_NAME_SIZE]++; + } + } + if (!binFile.rename(binName)) { + error("Can't rename file"); + } + Serial.print(F("File renamed: ")); + Serial.println(binName); + Serial.print(F("File size: ")); + Serial.print(binFile.fileSize()/512); + Serial.println(F(" blocks")); +} +//------------------------------------------------------------------------------ +void testSensor() { + const uint32_t interval = 200000; + int32_t diff; + data_t data; + Serial.println(F("\nTesting - type any character to stop\n")); + // Wait for Serial Idle. + delay(1000); + printHeader(&Serial); + uint32_t m = micros(); + while (!Serial.available()) { + m += interval; + do { + diff = m - micros(); + } while (diff > 0); + acquireData(&data); + printData(&Serial, &data); + } +} +//------------------------------------------------------------------------------ +void setup(void) { + if (ERROR_LED_PIN >= 0) { + pinMode(ERROR_LED_PIN, OUTPUT); + } + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + Serial.print(F("\nFreeStack: ")); + Serial.println(FreeStack()); + Serial.print(F("Records/block: ")); + Serial.println(DATA_DIM); + if (sizeof(block_t) != 512) { + error("Invalid block size"); + } + // Allow userSetup access to SPI bus. + pinMode(SD_CS_PIN, OUTPUT); + digitalWrite(SD_CS_PIN, HIGH); + + // Setup sensors. + userSetup(); + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50))) { + sd.initErrorPrint(&Serial); + fatalBlink(); + } + // recover existing tmp file. + if (sd.exists(TMP_FILE_NAME)) { + Serial.println(F("\nType 'Y' to recover existing tmp file " TMP_FILE_NAME)); + while (!Serial.available()) { + SysCall::yield(); + } + if (Serial.read() == 'Y') { + recoverTmpFile(); + } else { + error("'Y' not typed, please manually delete " TMP_FILE_NAME); + } + } +} +//------------------------------------------------------------------------------ +void loop(void) { + // Read any Serial data. + do { + delay(10); + } while (Serial.available() && Serial.read() >= 0); + Serial.println(); + Serial.println(F("type:")); + Serial.println(F("b - open existing bin file")); + Serial.println(F("c - convert file to csv")); + Serial.println(F("d - dump data to Serial")); + Serial.println(F("e - overrun error details")); + Serial.println(F("l - list files")); + Serial.println(F("r - record data")); + Serial.println(F("t - test without logging")); + while(!Serial.available()) { + SysCall::yield(); + } +#if WDT_YIELD_TIME_MICROS + Serial.println(F("LowLatencyLogger can not run with watchdog timer")); + SysCall::halt(); +#endif + + char c = tolower(Serial.read()); + + // Discard extra Serial data. + do { + delay(10); + } while (Serial.available() && Serial.read() >= 0); + + if (ERROR_LED_PIN >= 0) { + digitalWrite(ERROR_LED_PIN, LOW); + } + if (c == 'b') { + openBinFile(); + } else if (c == 'c') { + binaryToCsv(); + } else if (c == 'd') { + dumpData(); + } else if (c == 'e') { + checkOverrun(); + } else if (c == 'l') { + Serial.println(F("\nls:")); + sd.ls(&Serial, LS_SIZE); + } else if (c == 'r') { + logData(); + } else if (c == 't') { + testSensor(); + } else { + Serial.println(F("Invalid entry")); + } +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/LowLatencyLoggerMPU6050.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/LowLatencyLoggerMPU6050.ino new file mode 100644 index 0000000..7c592a8 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/LowLatencyLoggerMPU6050.ino @@ -0,0 +1,2 @@ +// Empty file with name LowLatencyLoggerMPU6050.ino to make IDE happy. + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/UserFunctions.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/UserFunctions.cpp new file mode 100644 index 0000000..601869a --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/UserFunctions.cpp @@ -0,0 +1,51 @@ +// User data functions. Modify these functions for your data items. +#include "UserTypes.h" +#include "Wire.h" +#include "I2Cdev.h" +#include "MPU6050.h" +//------------------------------------------------------------------------------ +MPU6050 mpu; +static uint32_t startMicros; +// Acquire a data record. +void acquireData(data_t* data) { + data->time = micros(); + mpu.getMotion6(&data->ax, &data->ay, &data->az, + &data->gx, &data->gy, &data->gz); +} + +// setup AVR I2C +void userSetup() { +#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE + Wire.begin(); + Wire.setClock(400000); +#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE + Fastwire::setup(400, true); +#endif + mpu.initialize(); +} + +// Print a data record. +void printData(Print* pr, data_t* data) { + if (startMicros == 0) { + startMicros = data->time; + } + pr->print(data->time- startMicros); + pr->write(','); + pr->print(data->ax); + pr->write(','); + pr->print(data->ay); + pr->write(','); + pr->print(data->az); + pr->write(','); + pr->print(data->gx); + pr->write(','); + pr->print(data->gy); + pr->write(','); + pr->println(data->gz); +} + +// Print data header. +void printHeader(Print* pr) { + startMicros = 0; + pr->println(F("micros,ax,ay,az,gx,gy,gz")); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/UserTypes.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/UserTypes.h new file mode 100644 index 0000000..05f7e9f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/UserTypes.h @@ -0,0 +1,18 @@ +#ifndef UserTypes_h +#define UserTypes_h +#include "Arduino.h" +#define FILE_BASE_NAME "mpuraw" +struct data_t { + unsigned long time; + int16_t ax; + int16_t ay; + int16_t az; + int16_t gx; + int16_t gy; + int16_t gz; +}; +void acquireData(data_t* data); +void printData(Print* pr, data_t* data); +void printHeader(Print* pr); +void userSetup(); +#endif // UserTypes_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/OpenNext/OpenNext.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/OpenNext/OpenNext.ino new file mode 100644 index 0000000..ac6c4b6 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/OpenNext/OpenNext.ino @@ -0,0 +1,60 @@ +/* + * Print size, modify date/time, and name for all files in root. + */ +#include +#include "SdFat.h" + +// SD default chip select pin. +const uint8_t chipSelect = SS; + +// file system object +SdFat sd; + +SdFile root; +SdFile file; +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + + Serial.println("Type any character to start"); + while (!Serial.available()) { + SysCall::yield(); + } + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } + if (!root.open("/")) { + sd.errorHalt("open root failed"); + } + // Open next file in root. + // Warning, openNext starts at the current directory position + // so a rewind of the directory may be required. + while (file.openNext(&root, O_RDONLY)) { + file.printFileSize(&Serial); + Serial.write(' '); + file.printModifyDateTime(&Serial); + Serial.write(' '); + file.printName(&Serial); + if (file.isDir()) { + // Indicate a directory. + Serial.write('/'); + } + Serial.println(); + file.close(); + } + if (root.getError()) { + Serial.println("openNext failed"); + } else { + Serial.println("Done!"); + } +} +//------------------------------------------------------------------------------ +void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/PrintBenchmark/PrintBenchmark.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/PrintBenchmark/PrintBenchmark.ino new file mode 100644 index 0000000..8556b62 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/PrintBenchmark/PrintBenchmark.ino @@ -0,0 +1,152 @@ +/* + * This program is a simple Print benchmark. + */ +#include +#include "SdFat.h" +#include "sdios.h" +#include "FreeStack.h" + +// SD chip select pin +const uint8_t chipSelect = SS; + +// number of lines to print +const uint16_t N_PRINT = 20000; + +// file system +SdFat sd; + +// test file +SdFile file; + +// Serial output stream +ArduinoOutStream cout(Serial); +//------------------------------------------------------------------------------ +// store error strings in flash to save RAM +#define error(s) sd.errorHalt(F(s)) +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } +} +//------------------------------------------------------------------------------ +void loop() { + uint32_t maxLatency; + uint32_t minLatency; + uint32_t totalLatency; + + // Read any existing Serial data. + do { + delay(10); + } while (Serial.available() && Serial.read() >= 0); + // F stores strings in flash to save RAM + cout << F("Type any character to start\n"); + while (!Serial.available()) { + SysCall::yield(); + } + delay(400); // catch Due reset problem + + cout << F("FreeStack: ") << FreeStack() << endl; + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } + + cout << F("Type is FAT") << int(sd.vol()->fatType()) << endl; + + cout << F("Starting print test. Please wait.\n\n"); + + // do write test + for (int test = 0; test < 6; test++) { + char fileName[13] = "bench0.txt"; + fileName[5] = '0' + test; + // open or create file - truncate existing file. + if (!file.open(fileName, O_RDWR | O_CREAT | O_TRUNC)) { + error("open failed"); + } + maxLatency = 0; + minLatency = 999999; + totalLatency = 0; + switch(test) { + case 0: + cout << F("Test of println(uint16_t)\n"); + break; + + case 1: + cout << F("Test of printField(uint16_t, char)\n"); + break; + + case 2: + cout << F("Test of println(uint32_t)\n"); + break; + + case 3: + cout << F("Test of printField(uint32_t, char)\n"); + break; + case 4: + cout << F("Test of println(float)\n"); + break; + + case 5: + cout << F("Test of printField(float, char)\n"); + break; + } + + uint32_t t = millis(); + for (uint16_t i = 0; i < N_PRINT; i++) { + uint32_t m = micros(); + + switch(test) { + case 0: + file.println(i); + break; + + case 1: + file.printField(i, '\n'); + break; + + case 2: + file.println(12345678UL + i); + break; + + case 3: + file.printField(12345678UL + i, '\n'); + break; + + case 4: + file.println((float)0.01*i); + break; + + case 5: + file.printField((float)0.01*i, '\n'); + break; + } + if (file.getWriteError()) { + error("write failed"); + } + m = micros() - m; + if (maxLatency < m) { + maxLatency = m; + } + if (minLatency > m) { + minLatency = m; + } + totalLatency += m; + } + file.close(); + t = millis() - t; + double s = file.fileSize(); + cout << F("Time ") << 0.001*t << F(" sec\n"); + cout << F("File size ") << 0.001*s << F(" KB\n"); + cout << F("Write ") << s/t << F(" KB/sec\n"); + cout << F("Maximum latency: ") << maxLatency; + cout << F(" usec, Minimum Latency: ") << minLatency; + cout << F(" usec, Avg Latency: "); + cout << totalLatency/N_PRINT << F(" usec\n\n"); + } + cout << F("Done!\n\n"); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/QuickStart/QuickStart.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/QuickStart/QuickStart.ino new file mode 100644 index 0000000..a36a14b --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/QuickStart/QuickStart.ino @@ -0,0 +1,161 @@ +// Quick hardware test for SPI card access. +// +#include +#include "SdFat.h" +#include "sdios.h" +// +// Set DISABLE_CHIP_SELECT to disable a second SPI device. +// For example, with the Ethernet shield, set DISABLE_CHIP_SELECT +// to 10 to disable the Ethernet controller. +const int8_t DISABLE_CHIP_SELECT = -1; +// +// Test with reduced SPI speed for breadboards. SD_SCK_MHZ(4) will select +// the highest speed supported by the board that is not over 4 MHz. +// Change SPI_SPEED to SD_SCK_MHZ(50) for best performance. +#define SPI_SPEED SD_SCK_MHZ(4) +//------------------------------------------------------------------------------ +// File system object. +SdFat sd; + +// Serial streams +ArduinoOutStream cout(Serial); + +// input buffer for line +char cinBuf[40]; +ArduinoInStream cin(Serial, cinBuf, sizeof(cinBuf)); + +// SD card chip select +int chipSelect; + +void cardOrSpeed() { + cout << F("Try another SD card or reduce the SPI bus speed.\n"); + cout << F("Edit SPI_SPEED in this program to change it.\n"); +} + +void reformatMsg() { + cout << F("Try reformatting the card. For best results use\n"); + cout << F("the SdFormatter program in SdFat/examples or download\n"); + cout << F("and use SDFormatter from www.sdcard.org/downloads.\n"); +} + +void setup() { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + cout << F("\nSPI pins:\n"); + cout << F("MISO: ") << int(MISO) << endl; + cout << F("MOSI: ") << int(MOSI) << endl; + cout << F("SCK: ") << int(SCK) << endl; + cout << F("SS: ") << int(SS) << endl; + + if (DISABLE_CHIP_SELECT < 0) { + cout << F( + "\nBe sure to edit DISABLE_CHIP_SELECT if you have\n" + "a second SPI device. For example, with the Ethernet\n" + "shield, DISABLE_CHIP_SELECT should be set to 10\n" + "to disable the Ethernet controller.\n"); + } + cout << F( + "\nSD chip select is the key hardware option.\n" + "Common values are:\n" + "Arduino Ethernet shield, pin 4\n" + "Sparkfun SD shield, pin 8\n" + "Adafruit SD shields and modules, pin 10\n"); +} + +bool firstTry = true; +void loop() { + // Read any existing Serial data. + do { + delay(10); + } while (Serial.available() && Serial.read() >= 0); + + if (!firstTry) { + cout << F("\nRestarting\n"); + } + firstTry = false; + + cout << F("\nEnter the chip select pin number: "); + while (!Serial.available()) { + SysCall::yield(); + } + cin.readline(); + if (cin >> chipSelect) { + cout << chipSelect << endl; + } else { + cout << F("\nInvalid pin number\n"); + return; + } + if (DISABLE_CHIP_SELECT < 0) { + cout << F( + "\nAssuming the SD is the only SPI device.\n" + "Edit DISABLE_CHIP_SELECT to disable another device.\n"); + } else { + cout << F("\nDisabling SPI device on pin "); + cout << int(DISABLE_CHIP_SELECT) << endl; + pinMode(DISABLE_CHIP_SELECT, OUTPUT); + digitalWrite(DISABLE_CHIP_SELECT, HIGH); + } + if (!sd.begin(chipSelect, SPI_SPEED)) { + if (sd.card()->errorCode()) { + cout << F( + "\nSD initialization failed.\n" + "Do not reformat the card!\n" + "Is the card correctly inserted?\n" + "Is chipSelect set to the correct value?\n" + "Does another SPI device need to be disabled?\n" + "Is there a wiring/soldering problem?\n"); + cout << F("\nerrorCode: ") << hex << showbase; + cout << int(sd.card()->errorCode()); + cout << F(", errorData: ") << int(sd.card()->errorData()); + cout << dec << noshowbase << endl; + return; + } + if (sd.vol()->fatType() == 0) { + cout << F("Can't find a valid FAT16/FAT32 partition.\n"); + reformatMsg(); + return; + } + cout << F("begin failed, can't determine error type\n"); + return; + } + cout << F("\nCard successfully initialized.\n"); + cout << endl; + + uint32_t size = sd.card()->cardSize(); + if (size == 0) { + cout << F("Can't determine the card size.\n"); + cardOrSpeed(); + return; + } + uint32_t sizeMB = 0.000512 * size + 0.5; + cout << F("Card size: ") << sizeMB; + cout << F(" MB (MB = 1,000,000 bytes)\n"); + cout << endl; + cout << F("Volume is FAT") << int(sd.vol()->fatType()); + cout << F(", Cluster size (bytes): ") << 512L * sd.vol()->blocksPerCluster(); + cout << endl << endl; + + cout << F("Files found (date time size name):\n"); + sd.ls(LS_R | LS_DATE | LS_SIZE); + + if ((sizeMB > 1100 && sd.vol()->blocksPerCluster() < 64) + || (sizeMB < 2200 && sd.vol()->fatType() == 32)) { + cout << F("\nThis card should be reformatted for best performance.\n"); + cout << F("Use a cluster size of 32 KB for cards larger than 1 GB.\n"); + cout << F("Only cards larger than 2 GB should be formatted FAT32.\n"); + reformatMsg(); + return; + } + // Read any extra Serial data. + do { + delay(10); + } while (Serial.available() && Serial.read() >= 0); + cout << F("\nSuccess! Type any character to restart.\n"); + while (!Serial.available()) { + SysCall::yield(); + } +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/RawWrite/RawWrite.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/RawWrite/RawWrite.ino new file mode 100644 index 0000000..a355f45 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/RawWrite/RawWrite.ino @@ -0,0 +1,180 @@ +/* + * This program illustrates raw write functions in SdFat that + * can be used for high speed data logging. + * + * This program simulates logging from a source that produces + * data at a constant rate of RATE_KB_PER_SEC. + * + * Note: Apps should create a very large file then truncates it + * to the length that is used for a logging. It only takes + * a few seconds to erase a 500 MB file since the card only + * marks the blocks as erased; no data transfer is required. + */ +#include +#include "SdFat.h" +#include "sdios.h" +#include "FreeStack.h" + +// SD chip select pin +const uint8_t chipSelect = SS; + +const uint32_t RATE_KB_PER_SEC = 100; + +const uint32_t TEST_TIME_SEC = 100; + +// Time between printing progress dots +const uint32_t DOT_TIME_MS = 5000UL; + +// number of blocks in the contiguous file +const uint32_t BLOCK_COUNT = (1000*RATE_KB_PER_SEC*TEST_TIME_SEC + 511)/512; + +// file system +SdFat sd; + +// test file +SdFile file; + +// file extent +uint32_t bgnBlock, endBlock; + +// Serial output stream +ArduinoOutStream cout(Serial); +//------------------------------------------------------------------------------ +// store error strings in flash to save RAM +#define error(s) sd.errorHalt(F(s)) +//------------------------------------------------------------------------------ +void setup(void) { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } +} +//------------------------------------------------------------------------------ +void loop(void) { + // Read any extra Serial data. + do { + delay(10); + } while (Serial.available() && Serial.read() >= 0); + // F stores strings in flash to save RAM + cout << F("Type any character to start\n"); + while (!Serial.available()) { + SysCall::yield(); + } + + cout << F("FreeStack: ") << FreeStack() << endl; + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } + + // delete possible existing file + sd.remove("RawWrite.txt"); + + // create a contiguous file + if (!file.createContiguous("RawWrite.txt", 512UL*BLOCK_COUNT)) { + error("createContiguous failed"); + } + // get the location of the file's blocks + if (!file.contiguousRange(&bgnBlock, &endBlock)) { + error("contiguousRange failed"); + } + //*********************NOTE************************************** + // NO SdFile calls are allowed while cache is used for raw writes + //*************************************************************** + + // clear the cache and use it as a 512 byte buffer + uint8_t* pCache = (uint8_t*)sd.vol()->cacheClear(); + + // fill cache with eight lines of 64 bytes each + memset(pCache, ' ', 512); + for (uint16_t i = 0; i < 512; i += 64) { + // put line number at end of line then CR/LF + pCache[i + 61] = '0' + (i/64); + pCache[i + 62] = '\r'; + pCache[i + 63] = '\n'; + } + + cout << F("Start raw write of ") << file.fileSize()/1000UL << F(" KB\n"); + cout << F("Target rate: ") << RATE_KB_PER_SEC << F(" KB/sec\n"); + cout << F("Target time: ") << TEST_TIME_SEC << F(" seconds\n"); + + // tell card to setup for multiple block write with pre-erase + if (!sd.card()->writeStart(bgnBlock, BLOCK_COUNT)) { + error("writeStart failed"); + } + // init stats + + delay(1000); + uint32_t dotCount = 0; + uint32_t maxQueuePrint = 0; + uint32_t maxWriteTime = 0; + uint32_t minWriteTime = 9999999; + uint32_t totalWriteTime = 0; + uint32_t maxQueueSize = 0; + uint32_t nWrite = 0; + uint32_t b = 0; + + // write data + uint32_t startTime = millis(); + while (nWrite < BLOCK_COUNT) { + uint32_t nProduced = RATE_KB_PER_SEC*(millis() - startTime)/512UL; + uint32_t queueSize = nProduced - nWrite; + if (queueSize == 0) continue; + if (queueSize > maxQueueSize) { + maxQueueSize = queueSize; + } + if ((millis() - startTime - dotCount*DOT_TIME_MS) > DOT_TIME_MS) { + if (maxQueueSize != maxQueuePrint) { + cout << F("\nQ: ") << maxQueueSize << endl; + maxQueuePrint = maxQueueSize; + } else { + cout << "."; + if (++dotCount%10 == 0) { + cout << endl; + } + } + } + // put block number at start of first line in block + uint32_t n = b++; + for (int8_t d = 5; d >= 0; d--) { + pCache[d] = n || d == 5 ? n % 10 + '0' : ' '; + n /= 10; + } + // write a 512 byte block + uint32_t tw = micros(); + if (!sd.card()->writeData(pCache)) { + error("writeData failed"); + } + tw = micros() - tw; + totalWriteTime += tw; + // check for max write time + if (tw > maxWriteTime) { + maxWriteTime = tw; + } + if (tw < minWriteTime) { + minWriteTime = tw; + } + nWrite++; + } + uint32_t endTime = millis(); + uint32_t avgWriteTime = totalWriteTime/BLOCK_COUNT; + // end multiple block write mode + if (!sd.card()->writeStop()) { + error("writeStop failed"); + } + + cout << F("\nDone\n"); + cout << F("maxQueueSize: ") << maxQueueSize << endl; + cout << F("Elapsed time: ") << setprecision(3)<< 1.e-3*(endTime - startTime); + cout << F(" seconds\n"); + cout << F("Min block write time: ") << minWriteTime << F(" micros\n"); + cout << F("Max block write time: ") << maxWriteTime << F(" micros\n"); + cout << F("Avg block write time: ") << avgWriteTime << F(" micros\n"); + // close file for next pass of loop + file.close(); + Serial.println(); +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsv/ReadCsv.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsv/ReadCsv.ino new file mode 100644 index 0000000..d57aadf --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsv/ReadCsv.ino @@ -0,0 +1,212 @@ + +// Functions to read a CSV text file one field at a time. +// +#include +#include + +// next line for SD.h +//#include + +// next two lines for SdFat +#include +SdFat SD; + +#define CS_PIN SS + +// example can use comma or semicolon +#define CSV_DELIM ',' + +File file; + +/* + * Read a file one field at a time. + * + * file - File to read. + * + * str - Character array for the field. + * + * size - Size of str array. + * + * delim - csv delimiter. + * + * return - negative value for failure. + * delimiter, '\n' or zero(EOF) for success. + */ +int csvReadText(File* file, char* str, size_t size, char delim) { + char ch; + int rtn; + size_t n = 0; + while (true) { + // check for EOF + if (!file->available()) { + rtn = 0; + break; + } + if (file->read(&ch, 1) != 1) { + // read error + rtn = -1; + break; + } + // Delete CR. + if (ch == '\r') { + continue; + } + if (ch == delim || ch == '\n') { + rtn = ch; + break; + } + if ((n + 1) >= size) { + // string too long + rtn = -2; + n--; + break; + } + str[n++] = ch; + } + str[n] = '\0'; + return rtn; +} +//------------------------------------------------------------------------------ +int csvReadInt32(File* file, int32_t* num, char delim) { + char buf[20]; + char* ptr; + int rtn = csvReadText(file, buf, sizeof(buf), delim); + if (rtn < 0) return rtn; + *num = strtol(buf, &ptr, 10); + if (buf == ptr) return -3; + while(isspace(*ptr)) ptr++; + return *ptr == 0 ? rtn : -4; +} +//------------------------------------------------------------------------------ +int csvReadInt16(File* file, int16_t* num, char delim) { + int32_t tmp; + int rtn = csvReadInt32(file, &tmp, delim); + if (rtn < 0) return rtn; + if (tmp < INT_MIN || tmp > INT_MAX) return -5; + *num = tmp; + return rtn; +} +//------------------------------------------------------------------------------ +int csvReadUint32(File* file, uint32_t* num, char delim) { + char buf[20]; + char* ptr; + int rtn = csvReadText(file, buf, sizeof(buf), delim); + if (rtn < 0) return rtn; + *num = strtoul(buf, &ptr, 10); + if (buf == ptr) return -3; + while(isspace(*ptr)) ptr++; + return *ptr == 0 ? rtn : -4; +} +//------------------------------------------------------------------------------ +int csvReadUint16(File* file, uint16_t* num, char delim) { + uint32_t tmp; + int rtn = csvReadUint32(file, &tmp, delim); + if (rtn < 0) return rtn; + if (tmp > UINT_MAX) return -5; + *num = tmp; + return rtn; +} +//------------------------------------------------------------------------------ +int csvReadDouble(File* file, double* num, char delim) { + char buf[20]; + char* ptr; + int rtn = csvReadText(file, buf, sizeof(buf), delim); + if (rtn < 0) return rtn; + *num = strtod(buf, &ptr); + if (buf == ptr) return -3; + while(isspace(*ptr)) ptr++; + return *ptr == 0 ? rtn : -4; +} +//------------------------------------------------------------------------------ +int csvReadFloat(File* file, float* num, char delim) { + double tmp; + int rtn = csvReadDouble(file, &tmp, delim); + if (rtn < 0)return rtn; + // could test for too large. + *num = tmp; + return rtn; +} +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + yield(); + } + Serial.println("Type any character to start"); + while (!Serial.available()) { + yield(); + } + // Initialize the SD. + if (!SD.begin(CS_PIN)) { + Serial.println("begin failed"); + return; + } + // Remove existing file. + SD.remove("READTEST.TXT"); + + // Create the file. + file = SD.open("READTEST.TXT", FILE_WRITE); + if (!file) { + Serial.println("open failed"); + return; + } + // Write test data. + file.print(F( +#if CSV_DELIM == ',' + "36,23.20,20.70,57.60,79.50,01:08:14,23.06.16\r\n" + "37,23.21,20.71,57.61,79.51,02:08:14,23.07.16\r\n" +#elif CSV_DELIM == ';' + "36;23.20;20.70;57.60;79.50;01:08:14;23.06.16\r\n" + "37;23.21;20.71;57.61;79.51;02:08:14;23.07.16\r\n" +#else +#error "Bad CSV_DELIM" +#endif +)); + + // Rewind the file for read. + file.seek(0); + + // Read the file and print fields. + int16_t tcalc; + float t1, t2, h1, h2; + // Must be dim 9 to allow for zero byte. + char timeS[9], dateS[9]; + while (file.available()) { + if (csvReadInt16(&file, &tcalc, CSV_DELIM) != CSV_DELIM + || csvReadFloat(&file, &t1, CSV_DELIM) != CSV_DELIM + || csvReadFloat(&file, &t2, CSV_DELIM) != CSV_DELIM + || csvReadFloat(&file, &h1, CSV_DELIM) != CSV_DELIM + || csvReadFloat(&file, &h2, CSV_DELIM) != CSV_DELIM + || csvReadText(&file, timeS, sizeof(timeS), CSV_DELIM) != CSV_DELIM + || csvReadText(&file, dateS, sizeof(dateS), CSV_DELIM) != '\n') { + Serial.println("read error"); + int ch; + int nr = 0; + // print part of file after error. + while ((ch = file.read()) > 0 && nr++ < 100) { + Serial.write(ch); + } + break; + } + Serial.print(tcalc); + Serial.print(CSV_DELIM); + Serial.print(t1); + Serial.print(CSV_DELIM); + Serial.print(t2); + Serial.print(CSV_DELIM); + Serial.print(h1); + Serial.print(CSV_DELIM); + Serial.print(h2); + Serial.print(CSV_DELIM); + Serial.print(timeS); + Serial.print(CSV_DELIM); + Serial.println(dateS); + } + file.close(); +} +//------------------------------------------------------------------------------ +void loop() { +} + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsvArray/ReadCsvArray.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsvArray/ReadCsvArray.ino new file mode 100644 index 0000000..b837a89 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsvArray/ReadCsvArray.ino @@ -0,0 +1,139 @@ +// Read a two dimensional array from a CSV file. +// +#include +#include +#define CS_PIN SS + +// 5 X 4 array +#define ROW_DIM 5 +#define COL_DIM 4 + +SdFat SD; +File file; + +/* + * Read a file one field at a time. + * + * file - File to read. + * + * str - Character array for the field. + * + * size - Size of str array. + * + * delim - String containing field delimiters. + * + * return - length of field including terminating delimiter. + * + * Note, the last character of str will not be a delimiter if + * a read error occurs, the field is too long, or the file + * does not end with a delimiter. Consider this an error + * if not at end-of-file. + * + */ +size_t readField(File* file, char* str, size_t size, const char* delim) { + char ch; + size_t n = 0; + while ((n + 1) < size && file->read(&ch, 1) == 1) { + // Delete CR. + if (ch == '\r') { + continue; + } + str[n++] = ch; + if (strchr(delim, ch)) { + break; + } + } + str[n] = '\0'; + return n; +} +//------------------------------------------------------------------------------ +#define errorHalt(msg) {Serial.println(F(msg)); SysCall::halt();} +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + Serial.println("Type any character to start"); + while (!Serial.available()) { + SysCall::yield(); + } + // Initialize the SD. + if (!SD.begin(CS_PIN)) { + errorHalt("begin failed"); + } + // Create or open the file. + file = SD.open("READNUM.TXT", FILE_WRITE); + if (!file) { + errorHalt("open failed"); + } + // Rewind file so test data is not appended. + file.rewind(); + + // Write test data. + file.print(F( + "11,12,13,14\r\n" + "21,22,23,24\r\n" + "31,32,33,34\r\n" + "41,42,43,44\r\n" + "51,52,53,54" // Allow missing endl at eof. + )); + + // Rewind the file for read. + file.rewind(); + + // Array for data. + int array[ROW_DIM][COL_DIM]; + int i = 0; // First array index. + int j = 0; // Second array index + size_t n; // Length of returned field with delimiter. + char str[20]; // Must hold longest field with delimiter and zero byte. + char *ptr; // Test for valid field. + + // Read the file and store the data. + + for (i = 0; i < ROW_DIM; i++) { + for (j = 0; j < COL_DIM; j++) { + n = readField(&file, str, sizeof(str), ",\n"); + if (n == 0) { + errorHalt("Too few lines"); + } + array[i][j] = strtol(str, &ptr, 10); + if (ptr == str) { + errorHalt("bad number"); + } + while (*ptr == ' ') { + ptr++; + } + if (*ptr != ',' && *ptr != '\n' && *ptr != '\0') { + errorHalt("extra characters in field"); + } + if (j < (COL_DIM-1) && str[n-1] != ',') { + errorHalt("line with too few fields"); + } + } + // Allow missing endl at eof. + if (str[n-1] != '\n' && file.available()) { + errorHalt("missing endl"); + } + } + + // Print the array. + for (i = 0; i < ROW_DIM; i++) { + for (j = 0; j < COL_DIM; j++) { + if (j) { + Serial.print(' '); + } + Serial.print(array[i][j]); + } + Serial.println(); + } + Serial.println("Done"); + file.close(); +} +//------------------------------------------------------------------------------ +void loop() { +} + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsvStream/ReadCsvStream.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsvStream/ReadCsvStream.ino new file mode 100644 index 0000000..022ab3e --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsvStream/ReadCsvStream.ino @@ -0,0 +1,121 @@ +/* + * This example reads a simple CSV, comma-separated values, file. + * Each line of the file has a label and three values, a long and two floats. + */ +#include +#include "SdFat.h" +#include "sdios.h" + +// SD chip select pin +const uint8_t chipSelect = SS; + +// file system object +SdFat sd; + +// create Serial stream +ArduinoOutStream cout(Serial); + +char fileName[] = "testfile.csv"; +//------------------------------------------------------------------------------ +// store error strings in flash to save RAM +#define error(s) sd.errorHalt(F(s)) +//------------------------------------------------------------------------------ +// read and print CSV test file +void readFile() { + long lg = 0; + float f1, f2; + char text[10]; + char c1, c2, c3; // space for commas. + + // open input file + ifstream sdin(fileName); + + // check for open error + if (!sdin.is_open()) { + error("open"); + } + + // read until input fails + while (1) { + // Get text field. + sdin.get(text, sizeof(text), ','); + + // Assume EOF if fail. + if (sdin.fail()) { + break; + } + + // Get commas and numbers. + sdin >> c1 >> lg >> c2 >> f1 >> c3 >> f2; + + // Skip CR/LF. + sdin.skipWhite(); + + if (sdin.fail()) { + error("bad input"); + } + + // error in line if not commas + if (c1 != ',' || c2 != ',' || c3 != ',') { + error("comma"); + } + + // print in six character wide columns + cout << text << setw(6) << lg << setw(6) << f1 << setw(6) << f2 << endl; + } + // Error in an input line if file is not at EOF. + if (!sdin.eof()) { + error("readFile"); + } +} +//------------------------------------------------------------------------------ +// write test file +void writeFile() { + + // create or open and truncate output file + ofstream sdout(fileName); + + // write file from string stored in flash + sdout << F( + "Line 1,1,2.3,4.5\n" + "Line 2,6,7.8,9.0\n" + "Line 3,9,8.7,6.5\n" + "Line 4,-4,-3.2,-1\n") << flush; + + // check for any errors + if (!sdout) { + error("writeFile"); + } + + sdout.close(); +} +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + cout << F("Type any character to start\n"); + while (!Serial.available()) { + SysCall::yield(); + } + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } + + // create test file + writeFile(); + + cout << endl; + + // read and print test + readFile(); + + cout << "\nDone!" << endl; +} +void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadWrite/ReadWrite.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadWrite/ReadWrite.ino new file mode 100644 index 0000000..15b6c98 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadWrite/ReadWrite.ino @@ -0,0 +1,81 @@ +/* + SD card read/write + + This example shows how to read and write data to and from an SD card file + The circuit: + * SD card attached to SPI bus as follows: + ** MOSI - pin 11 + ** MISO - pin 12 + ** CLK - pin 13 + + created Nov 2010 + by David A. Mellis + modified 9 Apr 2012 + by Tom Igoe + + This example code is in the public domain. + + */ + +#include +//#include +#include "SdFat.h" +SdFat SD; + +#define SD_CS_PIN SS +File myFile; + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + + Serial.print("Initializing SD card..."); + + if (!SD.begin(SD_CS_PIN)) { + Serial.println("initialization failed!"); + return; + } + Serial.println("initialization done."); + + // open the file. note that only one file can be open at a time, + // so you have to close this one before opening another. + myFile = SD.open("test.txt", FILE_WRITE); + + // if the file opened okay, write to it: + if (myFile) { + Serial.print("Writing to test.txt..."); + myFile.println("testing 1, 2, 3."); + // close the file: + myFile.close(); + Serial.println("done."); + } else { + // if the file didn't open, print an error: + Serial.println("error opening test.txt"); + } + + // re-open the file for reading: + myFile = SD.open("test.txt"); + if (myFile) { + Serial.println("test.txt:"); + + // read from the file until there's nothing else in it: + while (myFile.available()) { + Serial.write(myFile.read()); + } + // close the file: + myFile.close(); + } else { + // if the file didn't open, print an error: + Serial.println("error opening test.txt"); + } +} + +void loop() { + // nothing happens after setup +} + + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/STM32Test/STM32Test.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/STM32Test/STM32Test.ino new file mode 100644 index 0000000..d01c9a5 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/STM32Test/STM32Test.ino @@ -0,0 +1,175 @@ +/* + * Example use of two SPI ports on an STM32 board. + * Note SPI speed is limited to 18 MHz. + */ +#include +#include "SdFat.h" +#include "FreeStack.h" + +// set ENABLE_EXTENDED_TRANSFER_CLASS non-zero to use faster EX classes + +// Use first SPI port +SdFat sd1; +// SdFatEX sd1; +const uint8_t SD1_CS = PA4; // chip select for sd1 + +// Use second SPI port +SPIClass SPI_2(2); +SdFat sd2(&SPI_2); +// SdFatEX sd2(&SPI_2); + +const uint8_t SD2_CS = PB12; // chip select for sd2 + +const uint8_t BUF_DIM = 100; +uint8_t buf[BUF_DIM]; + +const uint32_t FILE_SIZE = 1000000; +const uint16_t NWRITE = FILE_SIZE/BUF_DIM; +//------------------------------------------------------------------------------ +// print error msg, any SD error codes, and halt. +// store messages in flash +#define errorExit(msg) errorHalt(F(msg)) +#define initError(msg) initErrorHalt(F(msg)) +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + // Wait for USB Serial + while (!Serial) { + } + + // fill buffer with known data + for (size_t i = 0; i < sizeof(buf); i++) { + buf[i] = i; + } + + Serial.println(F("type any character to start")); + while (!Serial.available()) { + } + Serial.print(F("FreeStack: ")); + Serial.println(FreeStack()); + + // initialize the first card + if (!sd1.begin(SD1_CS, SD_SCK_MHZ(18))) { + sd1.initError("sd1:"); + } + // create Dir1 on sd1 if it does not exist + if (!sd1.exists("/Dir1")) { + if (!sd1.mkdir("/Dir1")) { + sd1.errorExit("sd1.mkdir"); + } + } + // initialize the second card + if (!sd2.begin(SD2_CS, SD_SCK_MHZ(18))) { + sd2.initError("sd2:"); + } +// create Dir2 on sd2 if it does not exist + if (!sd2.exists("/Dir2")) { + if (!sd2.mkdir("/Dir2")) { + sd2.errorExit("sd2.mkdir"); + } + } + // list root directory on both cards + Serial.println(F("------sd1 root-------")); + sd1.ls(); + Serial.println(F("------sd2 root-------")); + sd2.ls(); + + // make /Dir1 the default directory for sd1 + if (!sd1.chdir("/Dir1")) { + sd1.errorExit("sd1.chdir"); + } + // remove test.bin from /Dir1 directory of sd1 + if (sd1.exists("test.bin")) { + if (!sd1.remove("test.bin")) { + sd2.errorExit("remove test.bin"); + } + } + // make /Dir2 the default directory for sd2 + if (!sd2.chdir("/Dir2")) { + sd2.errorExit("sd2.chdir"); + } + // remove rename.bin from /Dir2 directory of sd2 + if (sd2.exists("rename.bin")) { + if (!sd2.remove("rename.bin")) { + sd2.errorExit("remove rename.bin"); + } + } + // list current directory on both cards + Serial.println(F("------sd1 Dir1-------")); + sd1.ls(); + Serial.println(F("------sd2 Dir2-------")); + sd2.ls(); + Serial.println(F("---------------------")); + + // set the current working directory for open() to sd1 + sd1.chvol(); + + // create or open /Dir1/test.bin and truncate it to zero length + SdFile file1; + if (!file1.open("test.bin", O_RDWR | O_CREAT | O_TRUNC)) { + sd1.errorExit("file1"); + } + Serial.println(F("Writing test.bin to sd1")); + + // write data to /Dir1/test.bin on sd1 + for (uint16_t i = 0; i < NWRITE; i++) { + if (file1.write(buf, sizeof(buf)) != sizeof(buf)) { + sd1.errorExit("sd1.write"); + } + } + // set the current working directory for open() to sd2 + sd2.chvol(); + + // create or open /Dir2/copy.bin and truncate it to zero length + SdFile file2; + if (!file2.open("copy.bin", O_WRONLY | O_CREAT | O_TRUNC)) { + sd2.errorExit("file2"); + } + Serial.println(F("Copying test.bin to copy.bin")); + + // copy file1 to file2 + file1.rewind(); + uint32_t t = millis(); + + while (1) { + int n = file1.read(buf, sizeof(buf)); + if (n < 0) { + sd1.errorExit("read1"); + } + if (n == 0) { + break; + } + if ((int)file2.write(buf, n) != n) { + sd2.errorExit("write2"); + } + } + t = millis() - t; + Serial.print(F("File size: ")); + Serial.println(file2.fileSize()); + Serial.print(F("Copy time: ")); + Serial.print(t); + Serial.println(F(" millis")); + // close test.bin + file1.close(); + file2.close(); + // list current directory on both cards + Serial.println(F("------sd1 -------")); + sd1.ls("/", LS_R | LS_DATE | LS_SIZE); + Serial.println(F("------sd2 -------")); + sd2.ls("/", LS_R | LS_DATE | LS_SIZE); + Serial.println(F("---------------------")); + Serial.println(F("Renaming copy.bin")); + // rename the copy + if (!sd2.rename("copy.bin", "rename.bin")) { + sd2.errorExit("sd2.rename"); + } + // list current directory on both cards + Serial.println(F("------sd1 -------")); + sd1.ls("/", LS_R | LS_DATE | LS_SIZE); + Serial.println(F("------sd2 -------")); + sd2.ls("/", LS_R | LS_DATE | LS_SIZE); + Serial.println(F("---------------------")); + Serial.println(F("Done")); +} +//------------------------------------------------------------------------------ +void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SdFormatter/SdFormatter.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SdFormatter/SdFormatter.ino new file mode 100644 index 0000000..39e7850 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SdFormatter/SdFormatter.ino @@ -0,0 +1,552 @@ +/* + * This program will format an SD or SDHC card. + * Warning all data will be deleted! + * + * For SD/SDHC cards larger than 64 MB this + * program attempts to match the format + * generated by SDFormatter available here: + * + * http://www.sdcard.org/consumers/formatter/ + * + * For smaller cards this program uses FAT16 + * and SDFormatter uses FAT12. + */ + +// Set USE_SDIO to zero for SPI card access. +#define USE_SDIO 0 +// +// Change the value of chipSelect if your hardware does +// not use the default value, SS. Common values are: +// Arduino Ethernet shield: pin 4 +// Sparkfun SD shield: pin 8 +// Adafruit SD shields and modules: pin 10 +const uint8_t chipSelect = SS; + +// Initialize at highest supported speed not over 50 MHz. +// Reduce max speed if errors occur. +#define SPI_SPEED SD_SCK_MHZ(50) + +// Print extra info for debug if DEBUG_PRINT is nonzero +#define DEBUG_PRINT 0 +#include +#include "SdFat.h" +#include "sdios.h" +#if DEBUG_PRINT +#include "FreeStack.h" +#endif // DEBUG_PRINT + +// Serial output stream +ArduinoOutStream cout(Serial); + +#if USE_SDIO +// Use faster SdioCardEX +SdioCardEX card; +// SdioCard card; +#else // USE_SDIO +Sd2Card card; +#endif // USE_SDIO + +uint32_t cardSizeBlocks; +uint32_t cardCapacityMB; + +// cache for SD block +cache_t cache; + +// MBR information +uint8_t partType; +uint32_t relSector; +uint32_t partSize; + +// Fake disk geometry +uint8_t numberOfHeads; +uint8_t sectorsPerTrack; + +// FAT parameters +uint16_t reservedSectors; +uint8_t sectorsPerCluster; +uint32_t fatStart; +uint32_t fatSize; +uint32_t dataStart; + +// constants for file system structure +uint16_t const BU16 = 128; +uint16_t const BU32 = 8192; + +// strings needed in file system structures +char noName[] = "NO NAME "; +char fat16str[] = "FAT16 "; +char fat32str[] = "FAT32 "; +//------------------------------------------------------------------------------ +#define sdError(msg) {cout << F("error: ") << F(msg) << endl; sdErrorHalt();} +//------------------------------------------------------------------------------ +void sdErrorHalt() { + if (card.errorCode()) { + cout << F("SD error: ") << hex << int(card.errorCode()); + cout << ',' << int(card.errorData()) << dec << endl; + } + SysCall::halt(); +} +//------------------------------------------------------------------------------ +#if DEBUG_PRINT +void debugPrint() { + cout << F("FreeStack: ") << FreeStack() << endl; + cout << F("partStart: ") << relSector << endl; + cout << F("partSize: ") << partSize << endl; + cout << F("reserved: ") << reservedSectors << endl; + cout << F("fatStart: ") << fatStart << endl; + cout << F("fatSize: ") << fatSize << endl; + cout << F("dataStart: ") << dataStart << endl; + cout << F("clusterCount: "); + cout << ((relSector + partSize - dataStart)/sectorsPerCluster) << endl; + cout << endl; + cout << F("Heads: ") << int(numberOfHeads) << endl; + cout << F("Sectors: ") << int(sectorsPerTrack) << endl; + cout << F("Cylinders: "); + cout << cardSizeBlocks/(numberOfHeads*sectorsPerTrack) << endl; +} +#endif // DEBUG_PRINT +//------------------------------------------------------------------------------ +// write cached block to the card +uint8_t writeCache(uint32_t lbn) { + return card.writeBlock(lbn, cache.data); +} +//------------------------------------------------------------------------------ +// initialize appropriate sizes for SD capacity +void initSizes() { + if (cardCapacityMB <= 6) { + sdError("Card is too small."); + } else if (cardCapacityMB <= 16) { + sectorsPerCluster = 2; + } else if (cardCapacityMB <= 32) { + sectorsPerCluster = 4; + } else if (cardCapacityMB <= 64) { + sectorsPerCluster = 8; + } else if (cardCapacityMB <= 128) { + sectorsPerCluster = 16; + } else if (cardCapacityMB <= 1024) { + sectorsPerCluster = 32; + } else if (cardCapacityMB <= 32768) { + sectorsPerCluster = 64; + } else { + // SDXC cards + sectorsPerCluster = 128; + } + + cout << F("Blocks/Cluster: ") << int(sectorsPerCluster) << endl; + // set fake disk geometry + sectorsPerTrack = cardCapacityMB <= 256 ? 32 : 63; + + if (cardCapacityMB <= 16) { + numberOfHeads = 2; + } else if (cardCapacityMB <= 32) { + numberOfHeads = 4; + } else if (cardCapacityMB <= 128) { + numberOfHeads = 8; + } else if (cardCapacityMB <= 504) { + numberOfHeads = 16; + } else if (cardCapacityMB <= 1008) { + numberOfHeads = 32; + } else if (cardCapacityMB <= 2016) { + numberOfHeads = 64; + } else if (cardCapacityMB <= 4032) { + numberOfHeads = 128; + } else { + numberOfHeads = 255; + } +} +//------------------------------------------------------------------------------ +// zero cache and optionally set the sector signature +void clearCache(uint8_t addSig) { + memset(&cache, 0, sizeof(cache)); + if (addSig) { + cache.mbr.mbrSig0 = BOOTSIG0; + cache.mbr.mbrSig1 = BOOTSIG1; + } +} +//------------------------------------------------------------------------------ +// zero FAT and root dir area on SD +void clearFatDir(uint32_t bgn, uint32_t count) { + clearCache(false); +#if USE_SDIO + for (uint32_t i = 0; i < count; i++) { + if (!card.writeBlock(bgn + i, cache.data)) { + sdError("Clear FAT/DIR writeBlock failed"); + } + if ((i & 0XFF) == 0) { + cout << '.'; + } + } +#else // USE_SDIO + if (!card.writeStart(bgn, count)) { + sdError("Clear FAT/DIR writeStart failed"); + } + for (uint32_t i = 0; i < count; i++) { + if ((i & 0XFF) == 0) { + cout << '.'; + } + if (!card.writeData(cache.data)) { + sdError("Clear FAT/DIR writeData failed"); + } + } + if (!card.writeStop()) { + sdError("Clear FAT/DIR writeStop failed"); + } +#endif // USE_SDIO + cout << endl; +} +//------------------------------------------------------------------------------ +// return cylinder number for a logical block number +uint16_t lbnToCylinder(uint32_t lbn) { + return lbn / (numberOfHeads * sectorsPerTrack); +} +//------------------------------------------------------------------------------ +// return head number for a logical block number +uint8_t lbnToHead(uint32_t lbn) { + return (lbn % (numberOfHeads * sectorsPerTrack)) / sectorsPerTrack; +} +//------------------------------------------------------------------------------ +// return sector number for a logical block number +uint8_t lbnToSector(uint32_t lbn) { + return (lbn % sectorsPerTrack) + 1; +} +//------------------------------------------------------------------------------ +// format and write the Master Boot Record +void writeMbr() { + clearCache(true); + part_t* p = cache.mbr.part; + p->boot = 0; + uint16_t c = lbnToCylinder(relSector); + if (c > 1023) { + sdError("MBR CHS"); + } + p->beginCylinderHigh = c >> 8; + p->beginCylinderLow = c & 0XFF; + p->beginHead = lbnToHead(relSector); + p->beginSector = lbnToSector(relSector); + p->type = partType; + uint32_t endLbn = relSector + partSize - 1; + c = lbnToCylinder(endLbn); + if (c <= 1023) { + p->endCylinderHigh = c >> 8; + p->endCylinderLow = c & 0XFF; + p->endHead = lbnToHead(endLbn); + p->endSector = lbnToSector(endLbn); + } else { + // Too big flag, c = 1023, h = 254, s = 63 + p->endCylinderHigh = 3; + p->endCylinderLow = 255; + p->endHead = 254; + p->endSector = 63; + } + p->firstSector = relSector; + p->totalSectors = partSize; + if (!writeCache(0)) { + sdError("write MBR"); + } +} +//------------------------------------------------------------------------------ +// generate serial number from card size and micros since boot +uint32_t volSerialNumber() { + return (cardSizeBlocks << 8) + micros(); +} +//------------------------------------------------------------------------------ +// format the SD as FAT16 +void makeFat16() { + uint32_t nc; + for (dataStart = 2 * BU16;; dataStart += BU16) { + nc = (cardSizeBlocks - dataStart)/sectorsPerCluster; + fatSize = (nc + 2 + 255)/256; + uint32_t r = BU16 + 1 + 2 * fatSize + 32; + if (dataStart < r) { + continue; + } + relSector = dataStart - r + BU16; + break; + } + // check valid cluster count for FAT16 volume + if (nc < 4085 || nc >= 65525) { + sdError("Bad cluster count"); + } + reservedSectors = 1; + fatStart = relSector + reservedSectors; + partSize = nc * sectorsPerCluster + 2 * fatSize + reservedSectors + 32; + if (partSize < 32680) { + partType = 0X01; + } else if (partSize < 65536) { + partType = 0X04; + } else { + partType = 0X06; + } + // write MBR + writeMbr(); + clearCache(true); + fat_boot_t* pb = &cache.fbs; + pb->jump[0] = 0XEB; + pb->jump[1] = 0X00; + pb->jump[2] = 0X90; + for (uint8_t i = 0; i < sizeof(pb->oemId); i++) { + pb->oemId[i] = ' '; + } + pb->bytesPerSector = 512; + pb->sectorsPerCluster = sectorsPerCluster; + pb->reservedSectorCount = reservedSectors; + pb->fatCount = 2; + pb->rootDirEntryCount = 512; + pb->mediaType = 0XF8; + pb->sectorsPerFat16 = fatSize; + pb->sectorsPerTrack = sectorsPerTrack; + pb->headCount = numberOfHeads; + pb->hidddenSectors = relSector; + pb->totalSectors32 = partSize; + pb->driveNumber = 0X80; + pb->bootSignature = EXTENDED_BOOT_SIG; + pb->volumeSerialNumber = volSerialNumber(); + memcpy(pb->volumeLabel, noName, sizeof(pb->volumeLabel)); + memcpy(pb->fileSystemType, fat16str, sizeof(pb->fileSystemType)); + // write partition boot sector + if (!writeCache(relSector)) { + sdError("FAT16 write PBS failed"); + } + // clear FAT and root directory + clearFatDir(fatStart, dataStart - fatStart); + clearCache(false); + cache.fat16[0] = 0XFFF8; + cache.fat16[1] = 0XFFFF; + // write first block of FAT and backup for reserved clusters + if (!writeCache(fatStart) + || !writeCache(fatStart + fatSize)) { + sdError("FAT16 reserve failed"); + } +} +//------------------------------------------------------------------------------ +// format the SD as FAT32 +void makeFat32() { + uint32_t nc; + relSector = BU32; + for (dataStart = 2 * BU32;; dataStart += BU32) { + nc = (cardSizeBlocks - dataStart)/sectorsPerCluster; + fatSize = (nc + 2 + 127)/128; + uint32_t r = relSector + 9 + 2 * fatSize; + if (dataStart >= r) { + break; + } + } + // error if too few clusters in FAT32 volume + if (nc < 65525) { + sdError("Bad cluster count"); + } + reservedSectors = dataStart - relSector - 2 * fatSize; + fatStart = relSector + reservedSectors; + partSize = nc * sectorsPerCluster + dataStart - relSector; + // type depends on address of end sector + // max CHS has lbn = 16450560 = 1024*255*63 + if ((relSector + partSize) <= 16450560) { + // FAT32 + partType = 0X0B; + } else { + // FAT32 with INT 13 + partType = 0X0C; + } + writeMbr(); + clearCache(true); + + fat32_boot_t* pb = &cache.fbs32; + pb->jump[0] = 0XEB; + pb->jump[1] = 0X00; + pb->jump[2] = 0X90; + for (uint8_t i = 0; i < sizeof(pb->oemId); i++) { + pb->oemId[i] = ' '; + } + pb->bytesPerSector = 512; + pb->sectorsPerCluster = sectorsPerCluster; + pb->reservedSectorCount = reservedSectors; + pb->fatCount = 2; + pb->mediaType = 0XF8; + pb->sectorsPerTrack = sectorsPerTrack; + pb->headCount = numberOfHeads; + pb->hidddenSectors = relSector; + pb->totalSectors32 = partSize; + pb->sectorsPerFat32 = fatSize; + pb->fat32RootCluster = 2; + pb->fat32FSInfo = 1; + pb->fat32BackBootBlock = 6; + pb->driveNumber = 0X80; + pb->bootSignature = EXTENDED_BOOT_SIG; + pb->volumeSerialNumber = volSerialNumber(); + memcpy(pb->volumeLabel, noName, sizeof(pb->volumeLabel)); + memcpy(pb->fileSystemType, fat32str, sizeof(pb->fileSystemType)); + // write partition boot sector and backup + if (!writeCache(relSector) + || !writeCache(relSector + 6)) { + sdError("FAT32 write PBS failed"); + } + clearCache(true); + // write extra boot area and backup + if (!writeCache(relSector + 2) + || !writeCache(relSector + 8)) { + sdError("FAT32 PBS ext failed"); + } + fat32_fsinfo_t* pf = &cache.fsinfo; + pf->leadSignature = FSINFO_LEAD_SIG; + pf->structSignature = FSINFO_STRUCT_SIG; + pf->freeCount = 0XFFFFFFFF; + pf->nextFree = 0XFFFFFFFF; + // write FSINFO sector and backup + if (!writeCache(relSector + 1) + || !writeCache(relSector + 7)) { + sdError("FAT32 FSINFO failed"); + } + clearFatDir(fatStart, 2 * fatSize + sectorsPerCluster); + clearCache(false); + cache.fat32[0] = 0x0FFFFFF8; + cache.fat32[1] = 0x0FFFFFFF; + cache.fat32[2] = 0x0FFFFFFF; + // write first block of FAT and backup for reserved clusters + if (!writeCache(fatStart) + || !writeCache(fatStart + fatSize)) { + sdError("FAT32 reserve failed"); + } +} +//------------------------------------------------------------------------------ +// flash erase all data +uint32_t const ERASE_SIZE = 262144L; +void eraseCard() { + cout << endl << F("Erasing\n"); + uint32_t firstBlock = 0; + uint32_t lastBlock; + uint16_t n = 0; + + do { + lastBlock = firstBlock + ERASE_SIZE - 1; + if (lastBlock >= cardSizeBlocks) { + lastBlock = cardSizeBlocks - 1; + } + if (!card.erase(firstBlock, lastBlock)) { + sdError("erase failed"); + } + cout << '.'; + if ((n++)%32 == 31) { + cout << endl; + } + firstBlock += ERASE_SIZE; + } while (firstBlock < cardSizeBlocks); + cout << endl; + + if (!card.readBlock(0, cache.data)) { + sdError("readBlock"); + } + cout << hex << showbase << setfill('0') << internal; + cout << F("All data set to ") << setw(4) << int(cache.data[0]) << endl; + cout << dec << noshowbase << setfill(' ') << right; + cout << F("Erase done\n"); +} +//------------------------------------------------------------------------------ +void formatCard() { + cout << endl; + cout << F("Formatting\n"); + initSizes(); + if (card.type() != SD_CARD_TYPE_SDHC) { + cout << F("FAT16\n"); + makeFat16(); + } else { + cout << F("FAT32\n"); + makeFat32(); + } +#if DEBUG_PRINT + debugPrint(); +#endif // DEBUG_PRINT + cout << F("Format done\n"); +} +//------------------------------------------------------------------------------ +void setup() { + char c; + Serial.begin(9600); + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + cout << F("Type any character to start\n"); + while (!Serial.available()) { + SysCall::yield(); + } + // Discard any extra characters. + do { + delay(10); + } while (Serial.available() && Serial.read() >= 0); + cout << F( + "\n" + "This program can erase and/or format SD/SDHC cards.\n" + "\n" + "Erase uses the card's fast flash erase command.\n" + "Flash erase sets all data to 0X00 for most cards\n" + "and 0XFF for a few vendor's cards.\n" + "\n" + "Cards larger than 2 GB will be formatted FAT32 and\n" + "smaller cards will be formatted FAT16.\n" + "\n" + "Warning, all data on the card will be erased.\n" + "Enter 'Y' to continue: "); + while (!Serial.available()) { + SysCall::yield(); + } + + c = Serial.read(); + cout << c << endl; + if (c != 'Y') { + cout << F("Quiting, you did not enter 'Y'.\n"); + return; + } + // Read any existing Serial data. + do { + delay(10); + } while (Serial.available() && Serial.read() >= 0); + + cout << F( + "\n" + "Options are:\n" + "E - erase the card and skip formatting.\n" + "F - erase and then format the card. (recommended)\n" + "Q - quick format the card without erase.\n" + "\n" + "Enter option: "); + + while (!Serial.available()) { + SysCall::yield(); + } + c = Serial.read(); + cout << c << endl; + if (!strchr("EFQ", c)) { + cout << F("Quiting, invalid option entered.") << endl; + return; + } +#if USE_SDIO + if (!card.begin()) { + sdError("card.begin failed"); + } +#else // USE_SDIO + if (!card.begin(chipSelect, SPI_SPEED)) { + cout << F( + "\nSD initialization failure!\n" + "Is the SD card inserted correctly?\n" + "Is chip select correct at the top of this program?\n"); + sdError("card.begin failed"); + } +#endif + cardSizeBlocks = card.cardSize(); + if (cardSizeBlocks == 0) { + sdError("cardSize"); + } + cardCapacityMB = (cardSizeBlocks + 2047)/2048; + + cout << F("Card Size: ") << setprecision(0) << 1.048576*cardCapacityMB; + cout << F(" MB, (MB = 1,000,000 bytes)") << endl; + + if (c == 'E' || c == 'F') { + eraseCard(); + } + if (c == 'F' || c == 'Q') { + formatCard(); + } +} +//------------------------------------------------------------------------------ +void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SdInfo/SdInfo.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SdInfo/SdInfo.ino new file mode 100644 index 0000000..07f8601 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SdInfo/SdInfo.ino @@ -0,0 +1,248 @@ +/* + * This program attempts to initialize an SD card and analyze its structure. + */ +#include +#include "SdFat.h" +#include "sdios.h" + +// Set USE_SDIO to zero for SPI card access. +#define USE_SDIO 0 +/* + * SD chip select pin. Common values are: + * + * Arduino Ethernet shield, pin 4. + * SparkFun SD shield, pin 8. + * Adafruit SD shields and modules, pin 10. + * Default SD chip select is the SPI SS pin. + */ +const uint8_t SD_CHIP_SELECT = SS; +/* + * Set DISABLE_CHIP_SELECT to disable a second SPI device. + * For example, with the Ethernet shield, set DISABLE_CHIP_SELECT + * to 10 to disable the Ethernet controller. + */ +const int8_t DISABLE_CHIP_SELECT = -1; + +#if USE_SDIO +// Use faster SdioCardEX +SdFatSdioEX sd; +// SdFatSdio sd; +#else // USE_SDIO +SdFat sd; +#endif // USE_SDIO + +// serial output steam +ArduinoOutStream cout(Serial); + +// global for card size +uint32_t cardSize; + +// global for card erase size +uint32_t eraseSize; +//------------------------------------------------------------------------------ +// store error strings in flash +#define sdErrorMsg(msg) sd.errorPrint(F(msg)); +//------------------------------------------------------------------------------ +uint8_t cidDmp() { + cid_t cid; + if (!sd.card()->readCID(&cid)) { + sdErrorMsg("readCID failed"); + return false; + } + cout << F("\nManufacturer ID: "); + cout << hex << int(cid.mid) << dec << endl; + cout << F("OEM ID: ") << cid.oid[0] << cid.oid[1] << endl; + cout << F("Product: "); + for (uint8_t i = 0; i < 5; i++) { + cout << cid.pnm[i]; + } + cout << F("\nVersion: "); + cout << int(cid.prv_n) << '.' << int(cid.prv_m) << endl; + cout << F("Serial number: ") << hex << cid.psn << dec << endl; + cout << F("Manufacturing date: "); + cout << int(cid.mdt_month) << '/'; + cout << (2000 + cid.mdt_year_low + 10 * cid.mdt_year_high) << endl; + cout << endl; + return true; +} +//------------------------------------------------------------------------------ +uint8_t csdDmp() { + csd_t csd; + uint8_t eraseSingleBlock; + if (!sd.card()->readCSD(&csd)) { + sdErrorMsg("readCSD failed"); + return false; + } + if (csd.v1.csd_ver == 0) { + eraseSingleBlock = csd.v1.erase_blk_en; + eraseSize = (csd.v1.sector_size_high << 1) | csd.v1.sector_size_low; + } else if (csd.v2.csd_ver == 1) { + eraseSingleBlock = csd.v2.erase_blk_en; + eraseSize = (csd.v2.sector_size_high << 1) | csd.v2.sector_size_low; + } else { + cout << F("csd version error\n"); + return false; + } + eraseSize++; + cout << F("cardSize: ") << 0.000512*cardSize; + cout << F(" MB (MB = 1,000,000 bytes)\n"); + + cout << F("flashEraseSize: ") << int(eraseSize) << F(" blocks\n"); + cout << F("eraseSingleBlock: "); + if (eraseSingleBlock) { + cout << F("true\n"); + } else { + cout << F("false\n"); + } + return true; +} +//------------------------------------------------------------------------------ +// print partition table +uint8_t partDmp() { + mbr_t mbr; + if (!sd.card()->readBlock(0, (uint8_t*)&mbr)) { + sdErrorMsg("read MBR failed"); + return false; + } + for (uint8_t ip = 1; ip < 5; ip++) { + part_t *pt = &mbr.part[ip - 1]; + if ((pt->boot & 0X7F) != 0 || pt->firstSector > cardSize) { + cout << F("\nNo MBR. Assuming Super Floppy format.\n"); + return true; + } + } + cout << F("\nSD Partition Table\n"); + cout << F("part,boot,type,start,length\n"); + for (uint8_t ip = 1; ip < 5; ip++) { + part_t *pt = &mbr.part[ip - 1]; + cout << int(ip) << ',' << hex << int(pt->boot) << ',' << int(pt->type); + cout << dec << ',' << pt->firstSector <<',' << pt->totalSectors << endl; + } + return true; +} +//------------------------------------------------------------------------------ +void volDmp() { + cout << F("\nVolume is FAT") << int(sd.vol()->fatType()) << endl; + cout << F("blocksPerCluster: ") << int(sd.vol()->blocksPerCluster()) << endl; + cout << F("clusterCount: ") << sd.vol()->clusterCount() << endl; + cout << F("freeClusters: "); + uint32_t volFree = sd.vol()->freeClusterCount(); + cout << volFree << endl; + float fs = 0.000512*volFree*sd.vol()->blocksPerCluster(); + cout << F("freeSpace: ") << fs << F(" MB (MB = 1,000,000 bytes)\n"); + cout << F("fatStartBlock: ") << sd.vol()->fatStartBlock() << endl; + cout << F("fatCount: ") << int(sd.vol()->fatCount()) << endl; + cout << F("blocksPerFat: ") << sd.vol()->blocksPerFat() << endl; + cout << F("rootDirStart: ") << sd.vol()->rootDirStart() << endl; + cout << F("dataStartBlock: ") << sd.vol()->dataStartBlock() << endl; + if (sd.vol()->dataStartBlock() % eraseSize) { + cout << F("Data area is not aligned on flash erase boundaries!\n"); + cout << F("Download and use formatter from www.sdcard.org!\n"); + } +} +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + + // use uppercase in hex and use 0X base prefix + cout << uppercase << showbase << endl; + + // F stores strings in flash to save RAM + cout << F("SdFat version: ") << SD_FAT_VERSION << endl; +#if !USE_SDIO + if (DISABLE_CHIP_SELECT < 0) { + cout << F( + "\nAssuming the SD is the only SPI device.\n" + "Edit DISABLE_CHIP_SELECT to disable another device.\n"); + } else { + cout << F("\nDisabling SPI device on pin "); + cout << int(DISABLE_CHIP_SELECT) << endl; + pinMode(DISABLE_CHIP_SELECT, OUTPUT); + digitalWrite(DISABLE_CHIP_SELECT, HIGH); + } + cout << F("\nAssuming the SD chip select pin is: ") <= 0); + + // F stores strings in flash to save RAM + cout << F("\ntype any character to start\n"); + while (!Serial.available()) { + SysCall::yield(); + } + + uint32_t t = millis(); +#if USE_SDIO + if (!sd.cardBegin()) { + sdErrorMsg("\ncardBegin failed"); + return; + } +#else // USE_SDIO + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.cardBegin(SD_CHIP_SELECT, SD_SCK_MHZ(50))) { + sdErrorMsg("cardBegin failed"); + return; + } + #endif // USE_SDIO + t = millis() - t; + + cardSize = sd.card()->cardSize(); + if (cardSize == 0) { + sdErrorMsg("cardSize failed"); + return; + } + cout << F("\ninit time: ") << t << " ms" << endl; + cout << F("\nCard type: "); + switch (sd.card()->type()) { + case SD_CARD_TYPE_SD1: + cout << F("SD1\n"); + break; + + case SD_CARD_TYPE_SD2: + cout << F("SD2\n"); + break; + + case SD_CARD_TYPE_SDHC: + if (cardSize < 70000000) { + cout << F("SDHC\n"); + } else { + cout << F("SDXC\n"); + } + break; + + default: + cout << F("Unknown\n"); + } + if (!cidDmp()) { + return; + } + if (!csdDmp()) { + return; + } + uint32_t ocr; + if (!sd.card()->readOCR(&ocr)) { + sdErrorMsg("\nreadOCR failed"); + return; + } + cout << F("OCR: ") << hex << ocr << dec << endl; + if (!partDmp()) { + return; + } + if (!sd.fsBegin()) { + sdErrorMsg("\nFile System initialization failed.\n"); + return; + } + volDmp(); +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SoftwareSpi/SoftwareSpi.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SoftwareSpi/SoftwareSpi.ino new file mode 100644 index 0000000..cad7763 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SoftwareSpi/SoftwareSpi.ino @@ -0,0 +1,58 @@ +// An example of the SdFatSoftSpi template class. +// This example is for an Adafruit Data Logging Shield on a Mega. +// Software SPI is required on Mega since this shield connects to pins 10-13. +// This example will also run on an Uno and other boards using software SPI. +// +#include +#include "SdFat.h" +#if ENABLE_SOFTWARE_SPI_CLASS // Must be set in SdFat/SdFatConfig.h +// +// Pin numbers in templates must be constants. +const uint8_t SOFT_MISO_PIN = 12; +const uint8_t SOFT_MOSI_PIN = 11; +const uint8_t SOFT_SCK_PIN = 13; +// +// Chip select may be constant or RAM variable. +const uint8_t SD_CHIP_SELECT_PIN = 10; + +// SdFat software SPI template +SdFatSoftSpi sd; + +// Test file. +SdFile file; + +void setup() { + Serial.begin(9600); + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + Serial.println("Type any character to start"); + while (!Serial.available()) { + SysCall::yield(); + } + + if (!sd.begin(SD_CHIP_SELECT_PIN)) { + sd.initErrorHalt(); + } + + if (!file.open("SoftSPI.txt", O_RDWR | O_CREAT)) { + sd.errorHalt(F("open failed")); + } + file.println(F("This line was printed using software SPI.")); + + file.rewind(); + + while (file.available()) { + Serial.write(file.read()); + } + + file.close(); + + Serial.println(F("Done.")); +} +//------------------------------------------------------------------------------ +void loop() {} +#else // ENABLE_SOFTWARE_SPI_CLASS +#error ENABLE_SOFTWARE_SPI_CLASS must be set non-zero in SdFat/SdFatConfig.h +#endif //ENABLE_SOFTWARE_SPI_CLASS \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/StdioBench/StdioBench.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/StdioBench/StdioBench.ino new file mode 100644 index 0000000..2afe836 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/StdioBench/StdioBench.ino @@ -0,0 +1,214 @@ +// Benchmark comparing SdFile and StdioStream. +#include +#include "SdFat.h" + +// Define PRINT_FIELD nonzero to use printField. +#define PRINT_FIELD 0 + +// Number of lines to list on Serial. +#define STDIO_LIST_COUNT 0 +#define VERIFY_CONTENT 0 + +const uint8_t SD_CS_PIN = SS; +SdFat sd; + +SdFile printFile; +StdioStream stdioFile; + +float f[100]; +char buf[20]; +const char* label[] = +{ "uint8_t 0 to 255, 100 times ", "uint16_t 0 to 20000", + "uint32_t 0 to 20000", "uint32_t 1000000000 to 1000010000", + "float nnn.ffff, 10000 times" +}; +//------------------------------------------------------------------------------ +void setup() { + uint32_t printSize; + uint32_t stdioSize = 0; + uint32_t printTime; + uint32_t stdioTime = 0; + + Serial.begin(9600); + while (!Serial) { + SysCall::yield(); + } + + Serial.println(F("Type any character to start")); + while (!Serial.available()) { + SysCall::yield(); + } + Serial.println(F("Starting test")); + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50))) { + sd.errorHalt(); + } + + for (uint8_t i = 0; i < 100; i++) { + f[i] = 123.0 + 0.1234*i; + } + + for (uint8_t dataType = 0; dataType < 5; dataType++) { + for (uint8_t fileType = 0; fileType < 2; fileType++) { + if (!fileType) { + if (!printFile.open("print.txt", O_RDWR | O_CREAT | O_TRUNC)) { + Serial.println(F("open fail")); + return; + } + printTime = millis(); + switch (dataType) { + case 0: + for (uint16_t i =0; i < 100; i++) { + for (uint8_t j = 0; j < 255; j++) { + printFile.println(j); + } + } + break; + case 1: + for (uint16_t i = 0; i < 20000; i++) { + printFile.println(i); + } + break; + + case 2: + for (uint32_t i = 0; i < 20000; i++) { + printFile.println(i); + } + break; + + case 3: + for (uint16_t i = 0; i < 10000; i++) { + printFile.println(i + 1000000000UL); + } + break; + + case 4: + for (int j = 0; j < 100; j++) { + for (uint8_t i = 0; i < 100; i++) { + printFile.println(f[i], 4); + } + } + break; + default: + break; + } + printFile.sync(); + printTime = millis() - printTime; + printFile.rewind(); + printSize = printFile.fileSize(); + + } else { + if (!stdioFile.fopen("stream.txt", "w+")) { + Serial.println(F("fopen fail")); + return; + } + stdioTime = millis(); + + switch (dataType) { + case 0: + for (uint16_t i =0; i < 100; i++) { + for (uint8_t j = 0; j < 255; j++) { +#if PRINT_FIELD + stdioFile.printField(j, '\n'); +#else // PRINT_FIELD + stdioFile.println(j); +#endif // PRINT_FIELD + } + } + break; + case 1: + for (uint16_t i = 0; i < 20000; i++) { +#if PRINT_FIELD + stdioFile.printField(i, '\n'); +#else // PRINT_FIELD + stdioFile.println(i); +#endif // PRINT_FIELD + } + break; + + case 2: + for (uint32_t i = 0; i < 20000; i++) { +#if PRINT_FIELD + stdioFile.printField(i, '\n'); +#else // PRINT_FIELD + stdioFile.println(i); +#endif // PRINT_FIELD + } + break; + + case 3: + for (uint16_t i = 0; i < 10000; i++) { + uint32_t n = i + 1000000000UL; +#if PRINT_FIELD + stdioFile.printField(n, '\n'); +#else // PRINT_FIELD + stdioFile.println(n); +#endif // PRINT_FIELD + } + break; + + case 4: + for (int j = 0; j < 100; j++) { + for (uint8_t i = 0; i < 100; i++) { +#if PRINT_FIELD + stdioFile.printField(f[i], '\n', 4); +#else // PRINT_FIELD + stdioFile.println(f[i], 4); +#endif // PRINT_FIELD + } + } + break; + default: + break; + } + stdioFile.fflush(); + stdioTime = millis() - stdioTime; + stdioSize = stdioFile.ftell(); + if (STDIO_LIST_COUNT) { + size_t len; + stdioFile.rewind(); + for (int i = 0; i < STDIO_LIST_COUNT; i++) { + stdioFile.fgets(buf, sizeof(buf), &len); + Serial.print(len); + Serial.print(','); + Serial.print(buf); + } + } + + } + + } + Serial.println(label[dataType]); + if (VERIFY_CONTENT && printSize == stdioSize) { + printFile.rewind(); + stdioFile.rewind(); + for (uint32_t i = 0; i < stdioSize; i++) { + if (printFile.read() != stdioFile.getc()) { + Serial.print(F("Files differ at pos: ")); + Serial.println(i); + return; + } + } + } + + Serial.print(F("fileSize: ")); + if (printSize != stdioSize) { + Serial.print(printSize); + Serial.print(F(" != ")); + } + Serial.println(stdioSize); + Serial.print(F("print millis: ")); + Serial.println(printTime); + Serial.print(F("stdio millis: ")); + Serial.println(stdioTime); + Serial.print(F("ratio: ")); + Serial.println((float)printTime/(float)stdioTime); + Serial.println(); + printFile.close(); + stdioFile.fclose(); + } + Serial.println(F("Done")); +} +void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/TeensySdioDemo/TeensySdioDemo.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/TeensySdioDemo/TeensySdioDemo.ino new file mode 100644 index 0000000..988a921 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/TeensySdioDemo/TeensySdioDemo.ino @@ -0,0 +1,169 @@ +// Simple performance test for Teensy 3.5/3.6 SDHC. +// Demonstrates yield() efficiency. + +// Warning SdFatSdio and SdFatSdioEX normally should +// not both be used in a program. +// Each has its own cache and member variables. + +#include "SdFat.h" + +// 32 KiB buffer. +const size_t BUF_DIM = 32768; + +// 8 MiB file. +const uint32_t FILE_SIZE = 256UL*BUF_DIM; + +SdFatSdio sd; + +SdFatSdioEX sdEx; + +File file; + +uint8_t buf[BUF_DIM]; + +// buffer as uint32_t +uint32_t* buf32 = (uint32_t*)buf; + +// Total usec in read/write calls. +uint32_t totalMicros = 0; +// Time in yield() function. +uint32_t yieldMicros = 0; +// Number of yield calls. +uint32_t yieldCalls = 0; +// Max busy time for single yield call. +uint32_t yieldMaxUsec = 0; +// Control access to the two versions of SdFat. +bool useEx = false; +//----------------------------------------------------------------------------- +bool sdBusy() { + return useEx ? sdEx.card()->isBusy() : sd.card()->isBusy(); +} +//----------------------------------------------------------------------------- +void errorHalt(const char* msg) { + if (useEx) { + sdEx.errorHalt(msg); + } else { + sd.errorHalt(msg); + } +} +//------------------------------------------------------------------------------ +uint32_t kHzSdClk() { + return useEx ? sdEx.card()->kHzSdClk() : sd.card()->kHzSdClk(); +} +//------------------------------------------------------------------------------ +// Replace "weak" system yield() function. +void yield() { + // Only count cardBusy time. + if (!sdBusy()) { + return; + } + uint32_t m = micros(); + yieldCalls++; + while (sdBusy()) { + // Do something here. + } + m = micros() - m; + if (m > yieldMaxUsec) { + yieldMaxUsec = m; + } + yieldMicros += m; +} +//----------------------------------------------------------------------------- +void runTest() { + // Zero Stats + totalMicros = 0; + yieldMicros = 0; + yieldCalls = 0; + yieldMaxUsec = 0; + if (!file.open("TeensyDemo.bin", O_RDWR | O_CREAT)) { + errorHalt("open failed"); + } + Serial.println("\nsize,write,read"); + Serial.println("bytes,KB/sec,KB/sec"); + for (size_t nb = 512; nb <= BUF_DIM; nb *= 2) { + file.truncate(0); + uint32_t nRdWr = FILE_SIZE/nb; + Serial.print(nb); + Serial.print(','); + uint32_t t = micros(); + for (uint32_t n = 0; n < nRdWr; n++) { + // Set start and end of buffer. + buf32[0] = n; + buf32[nb/4 - 1] = n; + if (nb != file.write(buf, nb)) { + errorHalt("write failed"); + } + } + t = micros() - t; + totalMicros += t; + Serial.print(1000.0*FILE_SIZE/t); + Serial.print(','); + file.rewind(); + t = micros(); + + for (uint32_t n = 0; n < nRdWr; n++) { + if ((int)nb != file.read(buf, nb)) { + errorHalt("read failed"); + } + // crude check of data. + if (buf32[0] != n || buf32[nb/4 - 1] != n) { + errorHalt("data check"); + } + } + t = micros() - t; + totalMicros += t; + Serial.println(1000.0*FILE_SIZE/t); + } + file.close(); + Serial.print("\ntotalMicros "); + Serial.println(totalMicros); + Serial.print("yieldMicros "); + Serial.println(yieldMicros); + Serial.print("yieldCalls "); + Serial.println(yieldCalls); + Serial.print("yieldMaxUsec "); + Serial.println(yieldMaxUsec); + Serial.print("kHzSdClk "); + Serial.println(kHzSdClk()); + Serial.println("Done"); +} +//----------------------------------------------------------------------------- +void setup() { + Serial.begin(9600); + while (!Serial) { + } + Serial.println("SdFatSdioEX uses extended multi-block transfers without DMA."); + Serial.println("SdFatSdio uses a traditional DMA SDIO implementation."); + Serial.println("Note the difference is speed and busy yield time.\n"); +} +//----------------------------------------------------------------------------- +void loop() { + do { + delay(10); + } while (Serial.available() && Serial.read()); + + Serial.println("Type '1' for SdFatSdioEX or '2' for SdFatSdio"); + while (!Serial.available()) { + } + char c = Serial.read(); + if (c != '1' && c != '2') { + Serial.println("Invalid input"); + return; + } + if (c =='1') { + useEx = true; + if (!sdEx.begin()) { + sd.initErrorHalt("SdFatSdioEX begin() failed"); + } + // make sdEx the current volume. + sdEx.chvol(); + } else { + useEx = false; + if (!sd.begin()) { + sd.initErrorHalt("SdFatSdio begin() failed"); + } + // make sd the current volume. + sd.chvol(); + } + runTest(); +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/Timestamp/Timestamp.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/Timestamp/Timestamp.ino new file mode 100644 index 0000000..74982e1 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/Timestamp/Timestamp.ino @@ -0,0 +1,176 @@ +/* + * This program tests the dateTimeCallback() function + * and the timestamp() function. + */ +#include +#include "SdFat.h" +#include "sdios.h" + +SdFat sd; + +SdFile file; + +// Default SD chip select is SS pin +const uint8_t chipSelect = SS; + +// create Serial stream +ArduinoOutStream cout(Serial); +//------------------------------------------------------------------------------ +// store error strings in flash to save RAM +#define error(s) sd.errorHalt(F(s)) +//------------------------------------------------------------------------------ +/* + * date/time values for debug + * normally supplied by a real-time clock or GPS + */ +// date 1-Oct-14 +uint16_t year = 2014; +uint8_t month = 10; +uint8_t day = 1; + +// time 20:30:40 +uint8_t hour = 20; +uint8_t minute = 30; +uint8_t second = 40; +//------------------------------------------------------------------------------ +/* + * User provided date time callback function. + * See SdFile::dateTimeCallback() for usage. + */ +void dateTime(uint16_t* date, uint16_t* time) { + // User gets date and time from GPS or real-time + // clock in real callback function + + // return date using FAT_DATE macro to format fields + *date = FAT_DATE(year, month, day); + + // return time using FAT_TIME macro to format fields + *time = FAT_TIME(hour, minute, second); +} +//------------------------------------------------------------------------------ +/* + * Function to print all timestamps. + */ +void printTimestamps(SdFile& f) { + dir_t d; + if (!f.dirEntry(&d)) { + error("f.dirEntry failed"); + } + + cout << F("Creation: "); + f.printFatDate(d.creationDate); + cout << ' '; + f.printFatTime(d.creationTime); + cout << endl; + + cout << F("Modify: "); + f.printFatDate(d.lastWriteDate); + cout <<' '; + f.printFatTime(d.lastWriteTime); + cout << endl; + + cout << F("Access: "); + f.printFatDate(d.lastAccessDate); + cout << endl; +} +//------------------------------------------------------------------------------ +void setup(void) { + Serial.begin(9600); + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + cout << F("Type any character to start\n"); + while (!Serial.available()) { + SysCall::yield(); + } + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } + + // remove files if they exist + sd.remove("callback.txt"); + sd.remove("default.txt"); + sd.remove("stamp.txt"); + + // create a new file with default timestamps + if (!file.open("default.txt", O_WRONLY | O_CREAT)) { + error("open default.txt failed"); + } + cout << F("\nOpen with default times\n"); + printTimestamps(file); + + // close file + file.close(); + /* + * Test the date time callback function. + * + * dateTimeCallback() sets the function + * that is called when a file is created + * or when a file's directory entry is + * modified by sync(). + * + * The callback can be disabled by the call + * SdFile::dateTimeCallbackCancel() + */ + // set date time callback function + SdFile::dateTimeCallback(dateTime); + + // create a new file with callback timestamps + if (!file.open("callback.txt", O_WRONLY | O_CREAT)) { + error("open callback.txt failed"); + } + cout << ("\nOpen with callback times\n"); + printTimestamps(file); + + // change call back date + day += 1; + + // must add two to see change since FAT second field is 5-bits + second += 2; + + // modify file by writing a byte + file.write('t'); + + // force dir update + file.sync(); + + cout << F("\nTimes after write\n"); + printTimestamps(file); + + // close file + file.close(); + /* + * Test timestamp() function + * + * Cancel callback so sync will not + * change access/modify timestamp + */ + SdFile::dateTimeCallbackCancel(); + + // create a new file with default timestamps + if (!file.open("stamp.txt", O_WRONLY | O_CREAT)) { + error("open stamp.txt failed"); + } + // set creation date time + if (!file.timestamp(T_CREATE, 2014, 11, 10, 1, 2, 3)) { + error("set create time failed"); + } + // set write/modification date time + if (!file.timestamp(T_WRITE, 2014, 11, 11, 4, 5, 6)) { + error("set write time failed"); + } + // set access date + if (!file.timestamp(T_ACCESS, 2014, 11, 12, 7, 8, 9)) { + error("set access time failed"); + } + cout << F("\nTimes after timestamp() calls\n"); + printTimestamps(file); + + file.close(); + cout << F("\nDone\n"); +} + +void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/TwoCards/TwoCards.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/TwoCards/TwoCards.ino new file mode 100644 index 0000000..98800cc --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/TwoCards/TwoCards.ino @@ -0,0 +1,170 @@ +/* + * Warning This example requires extra RAM and may crash on Uno. + * Example use of two SD cards. + */ +#include +#include "SdFat.h" +#include "FreeStack.h" + +SdFat sd1; +const uint8_t SD1_CS = 10; // chip select for sd1 + +SdFat sd2; +const uint8_t SD2_CS = 4; // chip select for sd2 + +const uint8_t BUF_DIM = 100; +uint8_t buf[BUF_DIM]; + +const uint32_t FILE_SIZE = 1000000; +const uint16_t NWRITE = FILE_SIZE/BUF_DIM; +//------------------------------------------------------------------------------ +// print error msg, any SD error codes, and halt. +// store messages in flash +#define errorExit(msg) errorHalt(F(msg)) +#define initError(msg) initErrorHalt(F(msg)) +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + Serial.print(F("FreeStack: ")); + + Serial.println(FreeStack()); + + // fill buffer with known data + for (size_t i = 0; i < sizeof(buf); i++) { + buf[i] = i; + } + + Serial.println(F("type any character to start")); + while (!Serial.available()) { + SysCall::yield(); + } + + // disable sd2 while initializing sd1 + pinMode(SD2_CS, OUTPUT); + digitalWrite(SD2_CS, HIGH); + + // initialize the first card + if (!sd1.begin(SD1_CS)) { + sd1.initError("sd1:"); + } + // create Dir1 on sd1 if it does not exist + if (!sd1.exists("/Dir1")) { + if (!sd1.mkdir("/Dir1")) { + sd1.errorExit("sd1.mkdir"); + } + } + // initialize the second card + if (!sd2.begin(SD2_CS)) { + sd2.initError("sd2:"); + } +// create Dir2 on sd2 if it does not exist + if (!sd2.exists("/Dir2")) { + if (!sd2.mkdir("/Dir2")) { + sd2.errorExit("sd2.mkdir"); + } + } + // list root directory on both cards + Serial.println(F("------sd1 root-------")); + sd1.ls(); + Serial.println(F("------sd2 root-------")); + sd2.ls(); + + // make /Dir1 the default directory for sd1 + if (!sd1.chdir("/Dir1")) { + sd1.errorExit("sd1.chdir"); + } + + // make /Dir2 the default directory for sd2 + if (!sd2.chdir("/Dir2")) { + sd2.errorExit("sd2.chdir"); + } + + // list current directory on both cards + Serial.println(F("------sd1 Dir1-------")); + sd1.ls(); + Serial.println(F("------sd2 Dir2-------")); + sd2.ls(); + Serial.println(F("---------------------")); + + // remove rename.bin from /Dir2 directory of sd2 + if (sd2.exists("rename.bin")) { + if (!sd2.remove("rename.bin")) { + sd2.errorExit("remove rename.bin"); + } + } + // set the current working directory for open() to sd1 + sd1.chvol(); + + // create or open /Dir1/test.bin and truncate it to zero length + SdFile file1; + if (!file1.open("test.bin", O_RDWR | O_CREAT | O_TRUNC)) { + sd1.errorExit("file1"); + } + Serial.println(F("Writing test.bin to sd1")); + + // write data to /Dir1/test.bin on sd1 + for (uint16_t i = 0; i < NWRITE; i++) { + if (file1.write(buf, sizeof(buf)) != sizeof(buf)) { + sd1.errorExit("sd1.write"); + } + } + // set the current working directory for open() to sd2 + sd2.chvol(); + + // create or open /Dir2/copy.bin and truncate it to zero length + SdFile file2; + if (!file2.open("copy.bin", O_WRONLY | O_CREAT | O_TRUNC)) { + sd2.errorExit("file2"); + } + Serial.println(F("Copying test.bin to copy.bin")); + + // copy file1 to file2 + file1.rewind(); + uint32_t t = millis(); + + while (1) { + int n = file1.read(buf, sizeof(buf)); + if (n < 0) { + sd1.errorExit("read1"); + } + if (n == 0) { + break; + } + if ((int)file2.write(buf, n) != n) { + sd2.errorExit("write2"); + } + } + t = millis() - t; + Serial.print(F("File size: ")); + Serial.println(file2.fileSize()); + Serial.print(F("Copy time: ")); + Serial.print(t); + Serial.println(F(" millis")); + // close test.bin + file1.close(); + file2.close(); + // list current directory on both cards + Serial.println(F("------sd1 -------")); + sd1.ls("/", LS_R | LS_DATE | LS_SIZE); + Serial.println(F("------sd2 -------")); + sd2.ls("/", LS_R | LS_DATE | LS_SIZE); + Serial.println(F("---------------------")); + Serial.println(F("Renaming copy.bin")); + // rename the copy + if (!sd2.rename("copy.bin", "rename.bin")) { + sd2.errorExit("sd2.rename"); + } + // list current directory on both cards + Serial.println(F("------sd1 -------")); + sd1.ls("/", LS_R | LS_DATE | LS_SIZE); + Serial.println(F("------sd2 -------")); + sd2.ls("/", LS_R | LS_DATE | LS_SIZE); + Serial.println(F("---------------------")); + Serial.println(F("Done")); +} +//------------------------------------------------------------------------------ +void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/VolumeFreeSpace/VolumeFreeSpace.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/VolumeFreeSpace/VolumeFreeSpace.ino new file mode 100644 index 0000000..fb0fe9f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/VolumeFreeSpace/VolumeFreeSpace.ino @@ -0,0 +1,82 @@ +/* + * This program demonstrates the freeClusterCount() call. + */ +#include +#include "SdFat.h" +#include "sdios.h" +/* + * SD chip select pin. Common values are: + * + * Arduino Ethernet shield, pin 4. + * SparkFun SD shield, pin 8. + * Adafruit Datalogging shield, pin 10. + * Default SD chip select is the SPI SS pin. + */ +const uint8_t chipSelect = SS; + +#define TEST_FILE "Cluster.test" +// file system +SdFat sd; + +// test file +SdFile file; + +// Serial output stream +ArduinoOutStream cout(Serial); +//------------------------------------------------------------------------------ +void printFreeSpace() { + cout << F("freeClusterCount() call time: "); + uint32_t m = micros(); + uint32_t volFree = sd.vol()->freeClusterCount(); + cout << micros() - m << F(" micros\n"); + cout << F("freeClusters: ") << volFree << setprecision(3) << endl; + float fs = 0.000512*volFree*sd.vol()->blocksPerCluster(); + cout << F("freeSpace: ") << fs << F(" MB (MB = 1,000,000 bytes)\n\n"); +} +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + if (!MAINTAIN_FREE_CLUSTER_COUNT) { + cout << F("Please edit SdFatConfig.h and set\n"); + cout << F("MAINTAIN_FREE_CLUSTER_COUNT nonzero for\n"); + cout << F("maximum freeClusterCount() performance.\n\n"); + } + // F stores strings in flash to save RAM + cout << F("Type any character to start\n"); + while (!Serial.available()) { + SysCall::yield(); + } + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } + // Insure no TEST_FILE. + sd.remove(TEST_FILE); + + cout << F("\nFirst call to freeClusterCount scans the FAT.\n\n"); + printFreeSpace(); + + cout << F("Create and write to ") << TEST_FILE << endl; + if (!file.open(TEST_FILE, O_WRONLY | O_CREAT)) { + sd.errorHalt(F("Create failed")); + } + file.print(F("Cause a cluster to be allocated")); + file.close(); + + cout << F("\nSecond freeClusterCount call is faster if\n"); + cout << F("MAINTAIN_FREE_CLUSTER_COUNT is nonzero.\n\n"); + + printFreeSpace(); + + cout << F("Remove ") << TEST_FILE << endl << endl; + sd.remove(TEST_FILE); + printFreeSpace(); + cout << F("Done") << endl; +} +//------------------------------------------------------------------------------ +void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/bench/bench.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/bench/bench.ino new file mode 100644 index 0000000..1a155a8 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/bench/bench.ino @@ -0,0 +1,222 @@ +/* + * This program is a simple binary write/read benchmark. + */ +#include +#include "SdFat.h" +#include "sdios.h" +#include "FreeStack.h" + +// Set USE_SDIO to zero for SPI card access. +#define USE_SDIO 0 + +// SD chip select pin +const uint8_t chipSelect = SS; + +// Size of read/write. +const size_t BUF_SIZE = 512; + +// File size in MB where MB = 1,000,000 bytes. +const uint32_t FILE_SIZE_MB = 5; + +// Write pass count. +const uint8_t WRITE_COUNT = 2; + +// Read pass count. +const uint8_t READ_COUNT = 2; +//============================================================================== +// End of configuration constants. +//------------------------------------------------------------------------------ +// File size in bytes. +const uint32_t FILE_SIZE = 1000000UL*FILE_SIZE_MB; + +uint8_t buf[BUF_SIZE]; + +// file system +#if USE_SDIO +// Traditional DMA version. +// SdFatSdio sd; +// Faster version. +SdFatSdioEX sd; +#else // USE_SDIO +SdFat sd; +#endif // USE_SDIO + +// Set ENABLE_EXTENDED_TRANSFER_CLASS to use extended SD I/O. +// Requires dedicated use of the SPI bus. +// SdFatEX sd; + +// Set ENABLE_SOFTWARE_SPI_CLASS to use software SPI. +// Args are misoPin, mosiPin, sckPin. +// SdFatSoftSpi<6, 7, 5> sd; + +// test file +SdFile file; + +// Serial output stream +ArduinoOutStream cout(Serial); +//------------------------------------------------------------------------------ +// Store error strings in flash to save RAM. +#define error(s) sd.errorHalt(F(s)) +//------------------------------------------------------------------------------ +void cidDmp() { + cid_t cid; + if (!sd.card()->readCID(&cid)) { + error("readCID failed"); + } + cout << F("\nManufacturer ID: "); + cout << hex << int(cid.mid) << dec << endl; + cout << F("OEM ID: ") << cid.oid[0] << cid.oid[1] << endl; + cout << F("Product: "); + for (uint8_t i = 0; i < 5; i++) { + cout << cid.pnm[i]; + } + cout << F("\nVersion: "); + cout << int(cid.prv_n) << '.' << int(cid.prv_m) << endl; + cout << F("Serial number: ") << hex << cid.psn << dec << endl; + cout << F("Manufacturing date: "); + cout << int(cid.mdt_month) << '/'; + cout << (2000 + cid.mdt_year_low + 10 * cid.mdt_year_high) << endl; + cout << endl; +} +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + delay(1000); + cout << F("\nUse a freshly formatted SD for best performance.\n"); + + // use uppercase in hex and use 0X base prefix + cout << uppercase << showbase << endl; +} +//------------------------------------------------------------------------------ +void loop() { + float s; + uint32_t t; + uint32_t maxLatency; + uint32_t minLatency; + uint32_t totalLatency; + + // Discard any input. + do { + delay(10); + } while (Serial.available() && Serial.read() >= 0); + + // F( stores strings in flash to save RAM + cout << F("Type any character to start\n"); + while (!Serial.available()) { + SysCall::yield(); + } + cout << F("chipSelect: ") << int(chipSelect) << endl; + cout << F("FreeStack: ") << FreeStack() << endl; + +#if USE_SDIO + if (!sd.begin()) { + sd.initErrorHalt(); + } +#else // USE_SDIO + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } +#endif // USE_SDIO + cout << F("Type is FAT") << int(sd.vol()->fatType()) << endl; + cout << F("Card size: ") << sd.card()->cardSize()*512E-9; + cout << F(" GB (GB = 1E9 bytes)") << endl; + + cidDmp(); + + // open or create file - truncate existing file. + if (!file.open("bench.dat", O_RDWR | O_CREAT | O_TRUNC)) { + error("open failed"); + } + + // fill buf with known data + for (size_t i = 0; i < (BUF_SIZE-2); i++) { + buf[i] = 'A' + (i % 26); + } + buf[BUF_SIZE-2] = '\r'; + buf[BUF_SIZE-1] = '\n'; + + cout << F("File size ") << FILE_SIZE_MB << F(" MB\n"); + cout << F("Buffer size ") << BUF_SIZE << F(" bytes\n"); + cout << F("Starting write test, please wait.") << endl << endl; + + // do write test + uint32_t n = FILE_SIZE/sizeof(buf); + cout < m) { + minLatency = m; + } + totalLatency += m; + } + file.sync(); + t = millis() - t; + s = file.fileSize(); + cout << s/t <<',' << maxLatency << ',' << minLatency; + cout << ',' << totalLatency/n << endl; + } + cout << endl << F("Starting read test, please wait.") << endl; + cout << endl < m) { + minLatency = m; + } + totalLatency += m; + if (buf[BUF_SIZE-1] != '\n') { + error("data check"); + } + } + s = file.fileSize(); + t = millis() - t; + cout << s/t <<',' << maxLatency << ',' << minLatency; + cout << ',' << totalLatency/n << endl; + } + cout << endl << F("Done") << endl; + file.close(); +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/dataLogger/dataLogger.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/dataLogger/dataLogger.ino new file mode 100644 index 0000000..d4a4b4a --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/dataLogger/dataLogger.ino @@ -0,0 +1,150 @@ +/* + * Simple data logger. + */ +#include +#include "SdFat.h" + +// SD chip select pin. Be sure to disable any other SPI devices such as Enet. +const uint8_t chipSelect = SS; + +// Interval between data records in milliseconds. +// The interval must be greater than the maximum SD write latency plus the +// time to acquire and write data to the SD to avoid overrun errors. +// Run the bench example to check the quality of your SD card. +const uint32_t SAMPLE_INTERVAL_MS = 1000; + +// Log file base name. Must be six characters or less. +#define FILE_BASE_NAME "Data" +//------------------------------------------------------------------------------ +// File system object. +SdFat sd; + +// Log file. +SdFile file; + +// Time in micros for next data record. +uint32_t logTime; + +//============================================================================== +// User functions. Edit writeHeader() and logData() for your requirements. + +const uint8_t ANALOG_COUNT = 4; +//------------------------------------------------------------------------------ +// Write data header. +void writeHeader() { + file.print(F("micros")); + for (uint8_t i = 0; i < ANALOG_COUNT; i++) { + file.print(F(",adc")); + file.print(i, DEC); + } + file.println(); +} +//------------------------------------------------------------------------------ +// Log a data record. +void logData() { + uint16_t data[ANALOG_COUNT]; + + // Read all channels to avoid SD write latency between readings. + for (uint8_t i = 0; i < ANALOG_COUNT; i++) { + data[i] = analogRead(i); + } + // Write data to file. Start with log time in micros. + file.print(logTime); + + // Write ADC data to CSV record. + for (uint8_t i = 0; i < ANALOG_COUNT; i++) { + file.write(','); + file.print(data[i]); + } + file.println(); +} +//============================================================================== +// Error messages stored in flash. +#define error(msg) sd.errorHalt(F(msg)) +//------------------------------------------------------------------------------ +void setup() { + const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1; + char fileName[13] = FILE_BASE_NAME "00.csv"; + + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + delay(1000); + + Serial.println(F("Type any character to start")); + while (!Serial.available()) { + SysCall::yield(); + } + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } + + // Find an unused file name. + if (BASE_NAME_SIZE > 6) { + error("FILE_BASE_NAME too long"); + } + while (sd.exists(fileName)) { + if (fileName[BASE_NAME_SIZE + 1] != '9') { + fileName[BASE_NAME_SIZE + 1]++; + } else if (fileName[BASE_NAME_SIZE] != '9') { + fileName[BASE_NAME_SIZE + 1] = '0'; + fileName[BASE_NAME_SIZE]++; + } else { + error("Can't create file name"); + } + } + if (!file.open(fileName, O_WRONLY | O_CREAT | O_EXCL)) { + error("file.open"); + } + // Read any Serial data. + do { + delay(10); + } while (Serial.available() && Serial.read() >= 0); + + Serial.print(F("Logging to: ")); + Serial.println(fileName); + Serial.println(F("Type any character to stop")); + + // Write data header. + writeHeader(); + + // Start on a multiple of the sample interval. + logTime = micros()/(1000UL*SAMPLE_INTERVAL_MS) + 1; + logTime *= 1000UL*SAMPLE_INTERVAL_MS; +} +//------------------------------------------------------------------------------ +void loop() { + // Time for next record. + logTime += 1000UL*SAMPLE_INTERVAL_MS; + + // Wait for log time. + int32_t diff; + do { + diff = micros() - logTime; + } while (diff < 0); + + // Check for data rate too high. + if (diff > 10) { + error("Missed data record"); + } + + logData(); + + // Force data to SD and update the directory entry to avoid data loss. + if (!file.sync() || file.getWriteError()) { + error("write error"); + } + + if (Serial.available()) { + // Close file and stop. + file.close(); + Serial.println(F("Done")); + SysCall::halt(); + } +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/fgets/fgets.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/fgets/fgets.ino new file mode 100644 index 0000000..5996b69 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/fgets/fgets.ino @@ -0,0 +1,88 @@ +// Demo of fgets function to read lines from a file. +#include +#include "SdFat.h" +#include "sdios.h" + +// SD chip select pin +const uint8_t chipSelect = SS; + +SdFat sd; +// print stream +ArduinoOutStream cout(Serial); +//------------------------------------------------------------------------------ +// store error strings in flash memory +#define error(s) sd.errorHalt(F(s)) +//------------------------------------------------------------------------------ +void demoFgets() { + char line[25]; + int n; + // open test file + SdFile rdfile("fgets.txt", O_RDONLY); + + // check for open error + if (!rdfile.isOpen()) { + error("demoFgets"); + } + + cout << endl << F( + "Lines with '>' end with a '\\n' character\n" + "Lines with '#' do not end with a '\\n' character\n" + "\n"); + + // read lines from the file + while ((n = rdfile.fgets(line, sizeof(line))) > 0) { + if (line[n - 1] == '\n') { + cout << '>' << line; + } else { + cout << '#' << line << endl; + } + } +} +//------------------------------------------------------------------------------ +void makeTestFile() { + // create or open test file + SdFile wrfile("fgets.txt", O_WRONLY | O_CREAT | O_TRUNC); + + // check for open error + if (!wrfile.isOpen()) { + error("MakeTestFile"); + } + + // write test file + wrfile.print(F( + "Line with CRLF\r\n" + "Line with only LF\n" + "Long line that will require an extra read\n" + "\n" // empty line + "Line at EOF without NL" + )); + wrfile.close(); +} +//------------------------------------------------------------------------------ +void setup(void) { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + + cout << F("Type any character to start\n"); + while (!Serial.available()) { + SysCall::yield(); + } + delay(400); // catch Due reset problem + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } + + makeTestFile(); + + demoFgets(); + + cout << F("\nDone\n"); +} +void loop(void) {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/formatting/formatting.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/formatting/formatting.ino new file mode 100644 index 0000000..3268965 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/formatting/formatting.ino @@ -0,0 +1,73 @@ +/* + * Print a table with various formatting options + * Format dates + */ +#include +#include "SdFat.h" +#include "sdios.h" + +// create Serial stream +ArduinoOutStream cout(Serial); +//------------------------------------------------------------------------------ +// print a table to demonstrate format manipulators +void example(void) { + const int max = 10; + const int width = 4; + + for (int row = 1; row <= max; row++) { + for (int col = 1; col <= max; col++) { + cout << setw(width) << row * col << (col == max ? '\n' : ' '); + } + } + cout << endl; +} +//------------------------------------------------------------------------------ +// print a date as mm/dd/yyyy with zero fill in mm and dd +// shows how to set and restore the fill character +void showDate(int m, int d, int y) { + // convert two digit year + if (y < 100) { + y += 2000; + } + + // set new fill to '0' save old fill character + char old = cout.fill('0'); + + // print date + cout << setw(2) << m << '/' << setw(2) << d << '/' << y << endl; + + // restore old fill character + cout.fill(old); +} +//------------------------------------------------------------------------------ +void setup(void) { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + delay(2000); + + cout << endl << "default formatting" << endl; + example(); + + cout << showpos << "showpos" << endl; + example(); + + cout << hex << left << showbase << "hex left showbase" << endl; + example(); + + cout << internal << setfill('0') << uppercase; + cout << "uppercase hex internal showbase fill('0')" < +#include "SdFat.h" +#include "sdios.h" + +// SD chip select pin +const uint8_t chipSelect = SS; + +// file system object +SdFat sd; + +// create a serial stream +ArduinoOutStream cout(Serial); +//------------------------------------------------------------------------------ +void makeTestFile() { + ofstream sdout("getline.txt"); + // use flash for text to save RAM + sdout << F( + "short line\n" + "\n" + "17 character line\n" + "too long for buffer\n" + "line with no nl"); + + sdout.close(); +} +//------------------------------------------------------------------------------ +void testGetline() { + const int line_buffer_size = 18; + char buffer[line_buffer_size]; + ifstream sdin("getline.txt"); + int line_number = 0; + + while (sdin.getline(buffer, line_buffer_size, '\n') || sdin.gcount()) { + int count = sdin.gcount(); + if (sdin.fail()) { + cout << "Partial long line"; + sdin.clear(sdin.rdstate() & ~ios_base::failbit); + } else if (sdin.eof()) { + cout << "Partial final line"; // sdin.fail() is false + } else { + count--; // Don’t include newline in count + cout << "Line " << ++line_number; + } + cout << " (" << count << " chars): " << buffer << endl; + } +} +//------------------------------------------------------------------------------ +void setup(void) { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + + // F stores strings in flash to save RAM + cout << F("Type any character to start\n"); + while (!Serial.available()) { + SysCall::yield(); + } + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } + + // make the test file + makeTestFile(); + + // run the example + testGetline(); + cout << "\nDone!\n"; +} +//------------------------------------------------------------------------------ +void loop(void) {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/rename/rename.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/rename/rename.ino new file mode 100644 index 0000000..ad4a2d9 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/rename/rename.ino @@ -0,0 +1,107 @@ +/* + * This program demonstrates use of SdFile::rename() + * and SdFat::rename(). + */ +#include +#include "SdFat.h" +#include "sdios.h" + +// SD chip select pin +const uint8_t chipSelect = SS; + +// file system +SdFat sd; + +// Serial print stream +ArduinoOutStream cout(Serial); +//------------------------------------------------------------------------------ +// store error strings in flash to save RAM +#define error(s) sd.errorHalt(F(s)) +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + cout << F("Insert an empty SD. Type any character to start.") << endl; + while (!Serial.available()) { + SysCall::yield(); + } + + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } + + // Remove file/dirs from previous run. + if (sd.exists("dir2/DIR3/NAME3.txt")) { + cout << F("Removing /dir2/DIR3/NAME3.txt") << endl; + if (!sd.remove("dir2/DIR3/NAME3.txt") || + !sd.rmdir("dir2/DIR3/") || + !sd.rmdir("dir2/")) { + error("remove/rmdir failed"); + } + } + // create a file and write one line to the file + SdFile file("Name1.txt", O_WRONLY | O_CREAT); + if (!file.isOpen()) { + error("Name1.txt"); + } + file.println("A test line for Name1.txt"); + + // rename the file name2.txt and add a line. + // Use current working directory, root. + if (!file.rename("name2.txt")) { + error("name2.txt"); + } + file.println("A test line for name2.txt"); + + // list files + cout << F("------") << endl; + sd.ls(LS_R); + + // make a new directory - "Dir1" + if (!sd.mkdir("Dir1")) { + error("Dir1"); + } + + // move file into Dir1, rename it NAME3.txt and add a line + if (!file.rename("Dir1/NAME3.txt")) { + error("NAME3.txt"); + } + file.println("A line for Dir1/NAME3.txt"); + + // list files + cout << F("------") << endl; + sd.ls(LS_R); + + // make directory "dir2" + if (!sd.mkdir("dir2")) { + error("dir2"); + } + + // close file before rename(oldPath, newPath) + file.close(); + + // move Dir1 into dir2 and rename it DIR3 + if (!sd.rename("Dir1", "dir2/DIR3")) { + error("dir2/DIR3"); + } + + // open file for append in new location and add a line + if (!file.open("dir2/DIR3/NAME3.txt", O_WRONLY | O_APPEND)) { + error("dir2/DIR3/NAME3.txt"); + } + file.println("A line for dir2/DIR3/NAME3.txt"); + file.close(); + + // list files + cout << F("------") << endl; + sd.ls(LS_R); + + cout << F("Done") << endl; +} +void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/wipe/wipe.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/wipe/wipe.ino new file mode 100644 index 0000000..6d1bc93 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/wipe/wipe.ino @@ -0,0 +1,42 @@ +// Example to wipe all data from an already formatted SD. +#include +#include "SdFat.h" +const int chipSelect = SS; + +SdFat sd; + +void setup() { + int c; + Serial.begin(9600); + // Wait for USB Serial + while (!Serial) { + SysCall::yield(); + } + Serial.println("Type 'Y' to wipe all data."); + while (!Serial.available()) { + SysCall::yield(); + } + c = Serial.read(); + if (c != 'Y') { + sd.errorHalt("Quitting, you did not type 'Y'."); + } + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + sd.initErrorHalt(); + } + // Use wipe() for no dot progress indicator. + if (!sd.wipe(&Serial)) { + sd.errorHalt("Wipe failed."); + } + // Must reinitialize after wipe. + // Initialize at the highest speed supported by the board that is + // not over 50 MHz. Try a lower speed if SPI errors occur. + if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { + sd.errorHalt("Second init failed."); + } + Serial.println("Done"); +} + +void loop() { +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/AdcErrorStudy.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/AdcErrorStudy.txt new file mode 100644 index 0000000..0f7cbd1 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/AdcErrorStudy.txt @@ -0,0 +1,98 @@ +Static Tests of the Arduino Internal ADC. + +Several people have asked about the DC accuracy of the Arduino ADC when used in my data logging applications at slow sample rates. + +Here are my results of some "hobby level" measurements of the Arduino ADC. + +One question is how important is the ADC clock rate. I did measurents for an ADC clock rate of 125 kHz to 2MHz. + +Another question is how much does Noise Reduction Mode help. I did a series of measurements using this mode. + +Noise Reduction Mode only reduced the mean absolute error slightly. + +I do calibration to remove Offset Error and Gain Error. Calibration is very important for good accuracy. + +These tests depend on the Arduino voltage regulator providing a stable voltage during the tests. The Arduino ADC reference voltage is Vcc for these tests. This may not be realistic for practical applications + +Integral Non-linearity (INL) is the main remaining source of error. + +Here are my results for static (DC) tests of the internal ADC for three UNOs. + +The Arduinos are powered by a high quality nine volt power supply. + +These tests measure a DC level so do not include problems due to time jitter, S/H time, and other dynamic errors. +There are several studies of the dynamic behavior of the Arduino ADC that determine ENOB (Effective Number Of Bits). + +I used a shield with a 12-bit MCP4921 DAC to generate voltage levels. This ADC has an output buffer so it provides a very low impedance source. + +I measured the voltage of the DAC with a calibrated 18-bit MCP3422 ADC on the shield. + +I used DAC levels from 20 to 4075 to avoid zero offset errors at low voltages and DAC buffer problems at high voltages. + +Each series of measurements has 4056 data points. + +This is a voltage range of about 0.023 to 4.972 volts. + +I calibrated the Arduino ADC for each series of measurements with a linear fit of the form. + +v = a + b*adcValue + +Errors are the difference between the value measured with the 18-bit ADC and the calibrated value measured with the AVR ADC. + +I also show the results for no calibration, the NoCal column, using the datasheet formula. + +Vin = Vref*adcValue/1024 + + +The rows in the tables tables are. + +Min - minimum error in millivolts + +Max - maximum error in millivolts + +MAE - mean absolute error in millivolts + + +The columns in the tables are: + +Ideal - results for a perfect 10-bit ADC for comparison. + +NoCal - datasheet formula (5/1024)*adcValue with Noise Reduction Mode. + +NR128 - Noise Reduction mode with Prescaler of 128 (ADC clock of 125 kHz). + +PS128 - analogRead with Prescaler of 128 (ADC clock of 125 kHz). + +PS64 - analogRead with Prescaler of 64 (ADC clock of 250 kHz). + +PS32 - analogRead with Prescaler of 32 (ADC clock of 500 kHz). + +PS16 - analogRead with Prescaler of 16 (ADC clock of 1 MHz). + +PS8 - analogRead with Prescaler of 8 (ADC clock of 2 MHz). + + +Results for three UNO Arduinos + + First Arduino - Error Millivolts + + Ideal NoCal NR128 PS128 PS64 PS32 PS16 PS8 +Min -2.44 -2.43 -3.72 -4.01 -3.88 -4.53 -6.57 -27.18 +Max 2.44 11.69 3.74 4.24 4.15 5.17 8.69 23.21 +MAE 1.22 5.02 1.33 1.38 1.37 1.44 1.96 4.11 + + Second Arduino - Error Millivolts + + Ideal NoCal NR128 PS128 PS64 PS32 PS16 PS8 +Min -2.44 -9.24 -4.87 -4.86 -5.05 -5.34 -6.52 -24.04 +Max 2.44 11.62 3.95 4.64 4.69 5.71 8.41 21.29 +MAE 1.22 5.33 1.41 1.43 1.44 1.53 2.02 4.05 + + Third Arduino - Error Millivolts + + Ideal NoCal NR128 PS128 PS64 PS32 PS16 PS8 +Min -2.44 -7.88 -4.12 -4.40 -4.32 -4.41 -6.97 -26.93 +Max 2.44 12.53 3.80 4.04 4.18 5.27 8.84 24.59 +MAE 1.22 4.85 1.29 1.33 1.34 1.42 1.91 4.10 + + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/RateTable.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/RateTable.txt new file mode 100644 index 0000000..627d143 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/RateTable.txt @@ -0,0 +1,21 @@ +Maximum Sample Rate Table + + ADC clock kHz + 125 250 500 1000 +pins +1 7692 14286 25000 40000 +2 3810 6667 11111 16667 +3 2572 4790 8421 13559 +4 1942 3636 6452 10526 +5 1559 2930 5229 8602 +6 1303 2454 4396 7273 +7 1119 2111 3791 6299 +8 980 1852 3333 5556 +9 872 1649 2974 4969 +10 786 1487 2685 4494 +11 715 1354 2446 4103 +12 656 1242 2247 3774 +13 606 1148 2078 3493 +14 563 1067 1932 3252 +15 525 996 1806 3042 +16 493 935 1695 2857 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/bintocsv/AnalogBinLogger.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/bintocsv/AnalogBinLogger.h new file mode 100644 index 0000000..f24afa2 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/bintocsv/AnalogBinLogger.h @@ -0,0 +1,39 @@ +#ifndef AnalogBinLogger_h +#define AnalogBinLogger_h +//------------------------------------------------------------------------------ +// First block of file. +struct metadata_t { + unsigned long adcFrequency; // ADC clock frequency + unsigned long cpuFrequency; // CPU clock frequency + unsigned long sampleInterval; // Sample interval in CPU cycles. + unsigned long recordEightBits; // Size of ADC values, nonzero for 8-bits. + unsigned long pinCount; // Number of analog pins in a sample. + unsigned long pinNumber[123]; // List of pin numbers in a sample. +}; +//------------------------------------------------------------------------------ +// Data block for 8-bit ADC mode. +const size_t DATA_DIM8 = 508; +struct block8_t { + unsigned short count; // count of data bytes + unsigned short overrun; // count of overruns since last block + unsigned char data[DATA_DIM8]; +}; +//------------------------------------------------------------------------------ +// Data block for 10-bit ADC mode. +const size_t DATA_DIM16 = 254; +struct block16_t { + unsigned short count; // count of data bytes + unsigned short overrun; // count of overruns since last block + unsigned short data[DATA_DIM16]; +}; +//------------------------------------------------------------------------------ +// Data block for PC use +struct adcdata_t { + unsigned short count; // count of data bytes + unsigned short overrun; // count of overruns since last block + union { + unsigned char u8[DATA_DIM8]; + unsigned short u16[DATA_DIM16]; + } data; +}; +#endif // AnalogBinLogger_h \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/bintocsv/bintocsv.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/bintocsv/bintocsv.cpp new file mode 100644 index 0000000..517e061 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/bintocsv/bintocsv.cpp @@ -0,0 +1,82 @@ +#include +#include "AnalogBinLogger.h" +FILE *source; +FILE *destination; +int count = 0; + +int main(int argc, char** argv) { + metadata_t meta; + adcdata_t adc; + // Make sure no padding/size problems. + if (sizeof(meta) != 512 || sizeof(adc) != 512) { + printf("block size error\n"); + return 0; + } + if (argc != 3) { + printf("missing arguments:\n"); + printf("%s binFile csvFile\n", argv[0]); + return 0; + } + source = fopen(argv[1], "rb"); + if (!source) { + printf("open failed for %s\n", argv[1]); + return 0; + } + if (fread(&meta, sizeof(meta), 1, source) != 1) { + printf("read meta data failed\n"); + return 0; + } + if ( meta.pinCount == 0 + || meta.pinCount > (sizeof(meta.pinNumber)/sizeof(meta.pinNumber[0])) + || meta.adcFrequency < 50000 || meta.adcFrequency > 4000000) { + printf("Invalid meta data\n"); + return 0; + } + destination = fopen(argv[2], "w"); + if (!destination) { + printf("open failed for %s\n", argv[2]); + return 0; + } + int pinCount = meta.pinCount; + printf("pinCount: %d\n", pinCount); + printf("Sample pins:"); + for (unsigned i = 0; i < meta.pinCount; i++) { + printf(" %d", meta.pinNumber[i]); + } + printf("\n"); + printf("ADC clock rate: %g kHz\n", 0.001*meta.adcFrequency); + float sampleInterval = (float)meta.sampleInterval/(float)meta.cpuFrequency; + printf("Sample rate: %g per sec\n", 1.0/sampleInterval); + printf("Sample interval: %.4f usec\n", 1.0e6*sampleInterval); + + fprintf(destination, "Interval,%.4f,usec\n", 1.0e6*sampleInterval); + // Write header with pin numbers + for (int i = 0; i < ((int)meta.pinCount - 1); i++) { + fprintf(destination, "pin%d,", meta.pinNumber[i]); + } + fprintf(destination, "pin%d\n", meta.pinNumber[meta.pinCount - 1]); + unsigned maxCount = meta.recordEightBits ? DATA_DIM8 : DATA_DIM16; + while (!feof(source)) { + if (fread(&adc, sizeof(adc), 1, source) != 1) break; + if (adc.count > maxCount) { + printf("****Invalid data block****\n"); + return 0; + } + if (adc.overrun) { + fprintf(destination, "Overruns,%d\n", adc.overrun); + } + for (int i = 0; i < adc.count; i++) { + unsigned value = meta.recordEightBits ? adc.data.u8[i] : adc.data.u16[i]; + if ((i + 1)%pinCount) { + fprintf(destination, "%d,", value); + } else { + fprintf(destination, "%d\n", value); + } + } + count += adc.count; + } + printf("%d ADC values read\n", count); + fclose(source); + fclose(destination); + return 0; +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/readme.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/readme.txt new file mode 100644 index 0000000..2c12fd8 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/readme.txt @@ -0,0 +1,95 @@ +AnalogBinLogger.ino logs analog data to a binary SD file at high rates. + +Samples are logged at regular intervals by using timer1. Timer/Counter1 +Compare Match B is used to trigger the ADC for the first pin in a sample. +The ADC is triggered for remaining sample pins in the ADC conversion complete +interrupt routine. + +Data is captured in the ADC interrupt routine and saved in 512 byte buffers. + +Buffered data is written to the SD in a function called from loop(). The +entire data set is written to a large contiguous file as a single multi-block +write. This reduces write latency problems. + +Many inexpensive SD cards work well at lower rates. I used a $6.00 +SanDisk 4 GB class 4 card for testing. + +SanDisk class 4 cards work well at fairly high rates. I used the 4 GB SanDisk +card to log a single pin at 40,000 samples per second. + +You may need to increase the time between samples if your card has higher +latency. Using a Mega Arduino can help since it has more buffering. + +The bintocsv folder contains a PC program for converting binary files to +CSV files. Build it from the included source files. bintocvs is a command line program. + +bintocsv binFile csvFile + +AnalogBinLogger requires a recent version of the SdFat library. The SdFat +folder contains a beta version I used for development. + +The latest stable version is here: +http://code.google.com/p/sdfatlib/downloads/list + +You also need to install the included BufferedWriter library. It provides +fast text formatting. + +Example data for a 2 kHz sine wave logged at 40,000 samples per second is +shown in DATA.PNG and FFT.PNG shows a FFT of the data. See ExcelFFT.pdf +in the ADCdocs folder for details on calculating a FFT. + +The accuracy of the ADC samples depends on the ADC clock rate. See the +ADC_ENOB.PNG file for a plot of accuracy vs ADC clock frequency. + +See files in the ADCdocs folder for more information on ADC accuracy. + +To modify this program you will need a good knowledge of the Arduino +ADC, timer1 and C++ programming. This is not for the newbie. + +I have an LED and resistor connected to pin 3 to signal fatal errors and +data overruns. Fatal errors are indicated by a blinking led. Overrun errors +are indicated by a solid lit led. The count of samples dropped is written +to the SD and data logging continues. + +You can disable the error led feature by setting the error pin number negative: + +To use AnalogBinLogger, install these items. + +Place the BufferWriter and SdFat folders in your sketchbook libraries folder. + +Place the AnalogIsrLogger folder in your sketchbook folder. + +You must edit the configuration constants at the beginning of the program +to set the sample pins, sample rate, and other configuration values. + +Initially the program is setup to log the first five analog pins at 5000 +samples per second. Change these values to suit your needs. + +See RateTable.txt for maximum allowed sample rates vs pin count and ADC clock +frequency. + +The program has four commands: + +c - convert file to CSV +d - dump data to Serial +e - overrun error details +r - record ADC data + +All commands can be terminated by entering a character from the serial monitor. + +The c command converts the current binary file to a text file. Entering a +character on the serial monitor terminates the command. + +The d command converts the binary file to text and displays it on the serial +monitor. Entering a character on the serial monitor terminates the command. + +The e command displays details about overruns in the current binary file. +Data overruns happen when data samples are lost due to long write latency +of the SD. + +The r command will record ADC data to a binary file. It will terminate +when a character is entered on the serial monitor or the the maximum file +block count has been reached. + +A number of program options can be set by changing constants at the beginning +of the program. \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/MainPage/SdFatmainpage.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/MainPage/SdFatmainpage.h new file mode 100644 index 0000000..f83e90f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/MainPage/SdFatmainpage.h @@ -0,0 +1,403 @@ +/** + * Copyright (c) 20011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +/** +\mainpage Arduino %SdFat Library +
Copyright © 2012-2018 by William Greiman +
+ +\section Intro Introduction +The Arduino %SdFat Library is a minimal implementation of FAT16 and FAT32 +file systems on SD flash memory cards. Standard SD and high capacity SDHC +cards are supported. + +Experimental support for FAT12 can be enabled by setting FAT12_SUPPORT +nonzero in SdFatConfig.h. + +The %SdFat library supports Long %File Names or short 8.3 names. +Edit the SdFatConfig.h file to select short or long file names. + +The main classes in %SdFat are SdFat, SdFatEX, SdFatSoftSpi, SdFatSoftSpiEX, +SdBaseFile, SdFile, File, StdioStream, \ref fstream, \ref ifstream, +and \ref ofstream. + +The SdFat, SdFatEX, SdFatSoftSpi and SdFatSoftSpiEX classes maintain a +FAT volume, a current working directory, and simplify initialization +of other classes. The SdFat and SdFatEX classes uses a fast custom hardware SPI +implementation. The SdFatSoftSpi and SdFatSoftSpiEX classes uses software SPI. + +the SdFatEX and SdFatSoftSpiEX use extended multi-block I/O for enhanced +performance. These classes must have exclusive use of the SPI bus. + +The SdBaseFile class provides basic file access functions such as open(), +binary read(), binary write(), close(), remove(), and sync(). SdBaseFile +is the smallest file class. + +The SdFile class has all the SdBaseFile class functions plus the Arduino +Print class functions. + +The File class has all the SdBaseFile functions plus the functions in +the Arduino SD.h File class. This provides compatibility with the +Arduino SD.h library. + +The StdioStream class implements functions similar to Linux/Unix standard +buffered input/output. + +The \ref fstream class implements C++ iostreams for both reading and writing +text files. + +The \ref ifstream class implements C++ iostreams for reading text files. + +The \ref ofstream class implements C++ iostreams for writing text files. + +The classes \ref ifstream, \ref ofstream, \ref istream, and \ref ostream +follow the C++ \ref iostream standard when possible. + +There are many tutorials and much documentation about using C++ iostreams +on the web. + +http://www.cplusplus.com/ is a good C++ site for learning iostreams. + +The classes \ref ibufstream and \ref obufstream format and parse character + strings in memory buffers. + +the classes ArduinoInStream and ArduinoOutStream provide iostream functions +for Serial, LiquidCrystal, and other devices. + +A number of example are provided in the %SdFat/examples folder. These were +developed to test %SdFat and illustrate its use. + +\section Install Installation + +You must manually install SdFat by copying the SdFat folder from the download +package to the Arduino libraries folder in your sketch folder. + +See the Manual installation section of this guide. + +http://arduino.cc/en/Guide/Libraries + +\section SDconfig SdFat Configuration + +Several configuration options may be changed by editing the SdFatConfig.h +file in the %SdFat folder. + +Set USE_LONG_FILE_NAMES nonzero to enable Long %File Names. By default, +Long %File Names are enabled. For the leanest fastest library disable +Long %File Names. Long %File names require extra flash but no extra RAM. +Opening Long %File Names can be slower than opening Short %File Names. +Data read and write performance is not changed by the type of %File Name. + +If the symbol ENABLE_EXTENDED_TRANSFER_CLASS is nonzero, the class SdFatEX +will be defined. If the symbol ENABLE_SOFTWARE_SPI_CLASS is also nonzero, +the class SdFatSoftSpiEX will be defined. +These classes used extended multi-block SD I/O for better performance. +the SPI bus may not be shared with other devices in this mode. + +Set USE_STANDARD_SPI_LIBRARY and ENABLE_SOFTWARE_SPI_CLASS to +enable various SPI options. set USE_STANDARD_SPI_LIBRARY to use the standard +Arduino SPI library. set ENABLE_SOFTWARE_SPI_CLASS to enable the SdFatSoftSpi +class which uses software SPI. + +To enable SD card CRC checking set USE_SD_CRC nonzero. + +Set FAT12_SUPPORT nonzero to enable use of FAT12 volumes. +FAT12 has not been well tested and requires additional flash. + +\section SDPath Paths and Working Directories + +Relative paths in SdFat are resolved in a manner similar to Windows. + +Each instance of SdFat has a current directory. In SdFat this directory +is called the volume working directory, vwd. Initially this directory is +the root directory for the volume. + +The volume working directory is changed by calling SdFat::chdir(path). + +The call sd.chdir("/2014") will change the volume working directory +for sd to "/2014", assuming "/2014" exists. + +Relative paths for SdFat member functions are resolved by starting at +the volume working directory. + +For example, the call sd.mkdir("April") will create the directory +"/2014/April" assuming the volume working directory is "/2014". + +SdFat has a current working directory, cwd, that is used to resolve paths +for file.open() calls. + +For a single SD card the current working directory is always the volume +working directory for that card. + +For multiple SD cards the current working directory is set to the volume +working directory of a card by calling the SdFat::chvol() member function. +The chvol() call is like the Windows \: command. + +The call sd2.chvol() will set the current working directory to the volume +working directory for sd2. + +If the volume working directory for sd2 is "/music" the call + +file.open("BigBand.wav", O_READ); + +will then open "/music/BigBand.wav" on sd2. + +The following functions are used to change or get current directories. +See the html documentation for more information. +@code +bool SdFat::chdir(bool set_cwd = false); +bool SdFat::chdir(const char* path, bool set_cwd = false); +void SdFat::chvol(); +SdBaseFile* SdFat::vwd(); +static SdBaseFile* SdBaseFile::cwd(); +@endcode + +\section SDcard SD\SDHC Cards + +Arduinos access SD cards using the cards SPI protocol. PCs, Macs, and +most consumer devices use the 4-bit parallel SD protocol. A card that +functions well on A PC or Mac may not work well on the Arduino. + +Most cards have good SPI read performance but cards vary widely in SPI +write performance. Write performance is limited by how efficiently the +card manages internal erase/remapping operations. The Arduino cannot +optimize writes to reduce erase operations because of its limit RAM. + +SanDisk cards generally have good write performance. They seem to have +more internal RAM buffering than other cards and therefore can limit +the number of flash erase operations that the Arduino forces due to its +limited RAM. + +\section Hardware Hardware Configuration + +%SdFat was developed using an + Adafruit Industries +Data Logging Shield. + +The hardware interface to the SD card should not use a resistor based level +shifter. %SdFat sets the SPI bus frequency to 8 MHz which results in signal +rise times that are too slow for the edge detectors in many newer SD card +controllers when resistor voltage dividers are used. + +The 5 to 3.3 V level shifter for 5 V Arduinos should be IC based like the +74HC4050N based circuit shown in the file SdLevel.png. The Adafruit Wave Shield +uses a 74AHC125N. Gravitech sells SD and MicroSD Card Adapters based on the +74LCX245. + +If you are using a resistor based level shifter and are having problems try +setting the SPI bus frequency to 4 MHz. This can be done by using +card.init(SPI_HALF_SPEED) to initialize the SD card. + +A feature to use software SPI is available. Software SPI is slower +than hardware SPI but allows any digital pins to be used. See +SdFatConfig.h for software SPI definitions. + +\section comment Bugs and Comments + +If you wish to report bugs or have comments, send email to +fat16lib@sbcglobal.net. If possible, include a simple program that illustrates +the bug or problem. + +\section Trouble Troubleshooting + +The two example programs QuickStart, and SdInfo are useful for troubleshooting. + +A message like this from SdInfo with errorCode 0X1 indicates the SD card +is not seen by SdFat. This is often caused by a wiring error and reformatting +the card will not solve the problem. +
+cardBegin failed
+SD errorCode: 0X1
+SD errorData: 0XFF
+
+Here is a similar message from QuickStart: +
+SD initialization failed.
+Do not reformat the card!
+Is the card correctly inserted?
+Is chipSelect set to the correct value?
+Does another SPI device need to be disabled?
+Is there a wiring/soldering problem?
+
+errorCode: 0x1, errorData: 0xff
+
+Here is a message from QuickStart that indicates a formatting problem: +
+Card successfully initialized.
+Can't find a valid FAT16/FAT32 partition.
+Try reformatting the card.  For best results use
+the SdFormatter program in SdFat/examples or download
+and use SDFormatter from www.sdcard.org/downloads.
+
+ +The best source of recent information and help is the Arduino forum. + +http://arduino.cc/forum/ + +Also search the Adafruit forum. + +http://forums.adafruit.com/ + +If you are using a Teensy try. + +http://forum.pjrc.com/forum.php + +\section SdFatClass SdFat Usage + +SdFat supports Long File Names. Long names in SdFat are limited to 7-bit +ASCII characters in the range 0X20 - 0XFE The following are reserved characters: +
    +
  • < (less than) +
  • > (greater than) +
  • : (colon) +
  • " (double quote) +
  • / (forward slash) +
  • \ (backslash) +
  • | (vertical bar or pipe) +
  • ? (question mark) +
  • * (asterisk) +
+%SdFat uses a slightly restricted form of short names. +Short names are limited to 8 characters followed by an optional period (.) +and extension of up to 3 characters. The characters may be any combination +of letters and digits. The following special characters are also allowed: + +$ % ' - _ @ ~ ` ! ( ) { } ^ # & + +Short names are always converted to upper case and their original case +value is lost. Files that have a base-name where all characters have the +same case and an extension where all characters have the same case will +display properly. Examples this type name are UPPER.low, lower.TXT, +UPPER.TXT, and lower.txt. + +An application which writes to a file using print(), println() or +write() must close the file or call sync() at the appropriate time to +force data and directory information to be written to the SD Card. + +Applications must use care calling sync() +since 2048 bytes of I/O is required to update file and +directory information. This includes writing the current data block, reading +the block that contains the directory entry for update, writing the directory +block back and reading back the current data block. + +It is possible to open a file with two or more instances of a file object. +A file may be corrupted if data is written to the file by more than one +instance of a file object. + +\section HowTo How to format SD Cards as FAT Volumes + +The best way to restore an SD card's format on a PC or Mac is to use +SDFormatter which can be downloaded from: + +http://www.sdcard.org/downloads + +A formatter program, SdFormatter.ino, is included in the +%SdFat/examples/SdFormatter directory. This program attempts to +emulate SD Association's SDFormatter. + +SDFormatter aligns flash erase boundaries with file +system structures which reduces write latency and file system overhead. + +The PC/Mac SDFormatter does not have an option for FAT type so it may format +very small cards as FAT12. Use the SdFat formatter to force FAT16 +formatting of small cards. + +Do not format the SD card with an OS utility, OS utilities do not format SD +cards in conformance with the SD standard. + +You should use a freshly formatted SD card for best performance. FAT +file systems become slower if many files have been created and deleted. +This is because the directory entry for a deleted file is marked as deleted, +but is not deleted. When a new file is created, these entries must be scanned +before creating the file. Also files can become +fragmented which causes reads and writes to be slower. + +\section ExampleFilder Examples + +A number of examples are provided in the SdFat/examples folder. +See the html documentation for a list. + +To access these examples from the Arduino development environment +go to: %File -> Examples -> %SdFat -> \ + +Compile, upload to your Arduino and click on Serial Monitor to run +the example. + +Here is a list: + +AnalogBinLogger - Fast AVR ADC logger - see the AnalogBinLoggerExtras folder. + +bench - A read/write benchmark. + +dataLogger - A simple modifiable data logger. + +DirectoryFunctions - Demo of chdir(), ls(), mkdir(), and rmdir(). + +fgets - Demo of the fgets read line/string function. + +formating - Print a table with various formatting options. + +getline - Example of getline from section 27.7.1.3 of the C++ standard. + +LongFileName - Example use of openNext, printName, and open by index. + +LowLatencyLogger - A data logger for higher data rates. ADC version. + +LowLatencyLoggerADXL345 - A data logger for higher data rates. ADXL345 SPI. + +LowLatencyLoggerMPU6050 - A data logger for higher data rates. MPU6050 I2C. + +OpenNext - Open all files in the root dir and print their filename. + +PrintBenchmark - A simple benchmark for printing to a text file. + +QuickStart - A program to quickly test your SD card and SD shield/module. + +RawWrite - A test of raw write functions for contiguous files. + +ReadCsv - Function to read a CSV text file one field at a time. + +ReadCsvStream - Read a comma-separated value file using iostream extractors. + +ReadCsvArray - Read a two dimensional array from a CSV file. + +ReadWrite - Compatibility test of Arduino SD ReadWrite example. + +rename - A demo of SdFat::rename(old, new) and SdFile::rename(dirFile, newPath). + +SdFormatter - This program will format an SD or SDHC card. + +SoftwareSpi - Simple demonstration of the SdFatSoftSpi template class. + +SdInfo - Initialize an SD card and analyze its structure for trouble shooting. + +StdioBench - Demo and test of stdio style stream. + +Timestamp - Sets file create, modify, and access timestamps. + +TwoCards - Example using two SD cards. + +VolumeFreeSpace - Demonstrate the freeClusterCount() call. + +wipe - Example to wipe all data from an already formatted SD. + */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/SdFatTestSuite.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/SdFatTestSuite.cpp new file mode 100644 index 0000000..8511b0f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/SdFatTestSuite.cpp @@ -0,0 +1,87 @@ +/** + * Copyright (c) 20011-2017 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#include +static uint16_t failCount; +static uint16_t testCount; +static Print* testOut = &Serial; +//------------------------------------------------------------------------------ +static size_t strlenPGM(PGM_P str) { + PGM_P end = str; + while (pgm_read_byte(end++)) {} + return end - str; +} +//------------------------------------------------------------------------------ +void testBegin() { + Serial.begin(9600); + while (!Serial) {} // wait for leonardo + testOut = &Serial; + Serial.println(F("Type any character to begin.")); + while (Serial.read() <= 0) {} + delay(200); // Catch Due reset problem + + testOut->print(F("FreeStack: ")); + testOut->println(FreeStack()); + testOut->println(); + failCount = 0; + testCount = 0; +} +//------------------------------------------------------------------------------ +void testEnd() { + testOut->println(); + testOut->println(F("Compiled: " __DATE__ " " __TIME__)); + testOut->print(F("FreeStack: ")); + testOut->println(FreeStack()); + testOut->print(F("Test count: ")); + testOut->println(testCount); + testOut->print(F("Fail count: ")); + testOut->println(failCount); +} +//------------------------------------------------------------------------------ +static void testResult(bool b, uint8_t n) { + while (n++ < 60) testOut->write(' '); + if (b) { + testOut->println(F("..ok")); + } else { + testOut->println(F("FAIL")); + failCount++; + } + testCount++; +} +//------------------------------------------------------------------------------ +void testVerify_P(char* result, PGM_P expect) { + testOut->write('"'); + testOut->print(result); + testOut->print("\",\""); + testOut->print((const __FlashStringHelper*)expect); + testOut->write('"'); + uint8_t n = strlen(result) + strlenPGM(expect) + 5; + testResult(!strcmp_P(result, expect), n); +} +//------------------------------------------------------------------------------ +void testVerify_P(bool b, PGM_P msg) { + testOut->print((const __FlashStringHelper*)msg); + uint8_t n = strlenPGM(msg); + testResult(b, n); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/SdFatTestSuite.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/SdFatTestSuite.h new file mode 100644 index 0000000..4d096d9 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/SdFatTestSuite.h @@ -0,0 +1,50 @@ +/** + * Copyright (c) 20011-2017 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 SdFatTestSuite_h +#define SdFatTestSuite_h +#include "SdFat.h" +#include "FreeStack.h" + +#if defined(__arm__) && !defined(strcmp_P) +#define strcmp_P(a, b) strcmp((a), (b)) +#endif // strcmp_P + +#if defined(__arm__) && !defined(strncpy_P) +#define strncpy_P(s, t, n) strncpy(s, t, n) +#endif // strncpy_P + +#if defined(__arm__) && !defined(strlen_P) +#define strlen_P(str) strlen(str) +#endif // strlen_P + +#define testVerifyBool(result) testVerify_P(result, PSTR(#result)) +#define testVerifyMsg(result, msg) testVerify_P(result, PSTR(msg)) +#define testVerifyStr(result, expect) testVerify_P(result, PSTR(expect)) + +void testBegin(); +void testEnd(); +void testVerify_P(bool b, PGM_P msg); +void testVerify_P(char* result, PGM_P expect); +#endif // SdFatTestSuite_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_File/ATS_SD_File.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_File/ATS_SD_File.ino new file mode 100644 index 0000000..2fc6be7 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_File/ATS_SD_File.ino @@ -0,0 +1,105 @@ +// modified from ArduinoTestSuite 0022 by William Greiman +// Tests writing to and reading from a file, in particular the +// the Stream implementation (e.g. read() and peek()). + +#include +#include +#include +SdFat SD; +#define ATS_PrintTestStatus(msg, b) testVerify_P(b, PSTR(msg)) +void setup() { + boolean b; + SdFile f; + uint32_t fs; + + testBegin(); + + ATS_PrintTestStatus("SD.begin()", b = SD.begin()); + if (!b) goto done; + + SD.remove("test.txt"); + + f.open("test.txt", FILE_WRITE); + ATS_PrintTestStatus("SD.open()", f.isOpen()); + if (!f.isOpen()) goto done; + + f.print("abc"); + f.print("de"); + f.close(); + + f.open("test.txt", FILE_WRITE); + ATS_PrintTestStatus("SD.open()", f.isOpen()); + if (!f.isOpen()) goto done; + + f.print("fgh"); + f.close(); + + f.open("test.txt", O_READ); + ATS_PrintTestStatus("SD.open()", f.isOpen()); + if (!f.isOpen()) goto done; + fs =f.fileSize(); + ATS_PrintTestStatus("read()", f.read() == 'a'); + ATS_PrintTestStatus("peek()", f.peek() == 'b'); + ATS_PrintTestStatus("read()", f.read() == 'b'); + ATS_PrintTestStatus("read()", f.read() == 'c'); + ATS_PrintTestStatus("peek()", f.peek() == 'd'); + ATS_PrintTestStatus("peek()", f.peek() == 'd'); + ATS_PrintTestStatus("peek()", f.peek() == 'd'); + ATS_PrintTestStatus("peek()", f.peek() == 'd'); + ATS_PrintTestStatus("read()", f.read() == 'd'); + ATS_PrintTestStatus("available()", f.curPosition() != fs); + ATS_PrintTestStatus("read()", f.read() == 'e'); + ATS_PrintTestStatus("available()", f.curPosition() != fs); + ATS_PrintTestStatus("peek()", f.peek() == 'f'); + ATS_PrintTestStatus("read()", f.read() == 'f'); + ATS_PrintTestStatus("peek()", f.peek() == 'g'); + ATS_PrintTestStatus("available()", f.curPosition() != fs); + ATS_PrintTestStatus("peek()", f.peek() == 'g'); + ATS_PrintTestStatus("read()", f.read() == 'g'); + ATS_PrintTestStatus("available()", f.curPosition() != fs); + ATS_PrintTestStatus("available()", f.curPosition() != fs); + ATS_PrintTestStatus("available()", f.curPosition() != fs); + ATS_PrintTestStatus("peek()", f.peek() == 'h'); + ATS_PrintTestStatus("read()", f.read() == 'h'); + ATS_PrintTestStatus("available()", f.curPosition() == fs); + ATS_PrintTestStatus("peek()", f.peek() == -1); + ATS_PrintTestStatus("read()", f.read() == -1); + ATS_PrintTestStatus("peek()", f.peek() == -1); + ATS_PrintTestStatus("read()", f.read() == -1); + + f.close(); + + SD.remove("test2.txt"); + + f.open("test2.txt", FILE_WRITE); + ATS_PrintTestStatus("SD.open()", f.isOpen()); + if (!f.isOpen()) goto done; + + f.print("ABC"); + f.close(); + + f.open("test.txt", O_READ); + ATS_PrintTestStatus("SD.open()", f.isOpen()); + if (!f.isOpen()) goto done; + + ATS_PrintTestStatus("peek()", f.peek() == 'a'); + + f.close(); + + f.open("test2.txt", O_READ); + ATS_PrintTestStatus("SD.open()", f.isOpen()); + if (!f.isOpen()) goto done; + + ATS_PrintTestStatus("peek()", f.peek() == 'A'); + ATS_PrintTestStatus("read()", f.read() == 'A'); + + f.close(); + +done: + testEnd(); + +} + +void loop() {} + + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_Files/ATS_SD_Files.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_Files/ATS_SD_Files.ino new file mode 100644 index 0000000..aa04c84 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_Files/ATS_SD_Files.ino @@ -0,0 +1,75 @@ +// modified from ArduinoTestSuite 0022 by William Greiman +#include +#include +#include +SdFat SD; +#define ATS_PrintTestStatus(msg, b) testVerify_P(b, PSTR(msg)) + +void setup() { + boolean b; + SdFile f; + + testBegin(); + + ATS_PrintTestStatus("SD.begin()", b = SD.begin()); + if (!b) goto done; + + ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf.txt")); + ATS_PrintTestStatus("SD.open()", f.open("asdf.txt", FILE_WRITE)); f.close(); + ATS_PrintTestStatus("SD.exists()", SD.exists("asdf.txt")); + ATS_PrintTestStatus("SD.exists()", SD.exists("/asdf.txt")); + ATS_PrintTestStatus("SD.remove()", SD.remove("asdf.txt")); + ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf.txt")); + + ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf")); + ATS_PrintTestStatus("SD.mkdir()", SD.mkdir("asdf")); + ATS_PrintTestStatus("SD.exists()", SD.exists("asdf")); + ATS_PrintTestStatus("SD.exists()", SD.exists("/asdf")); + ATS_PrintTestStatus("SD.exists()", SD.exists("asdf/")); + ATS_PrintTestStatus("SD.rmdir()", SD.rmdir("asdf")); + ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf")); + + ATS_PrintTestStatus("SD.mkdir()", SD.mkdir("x/y/z")); + ATS_PrintTestStatus("SD.exists()", SD.exists("x")); + ATS_PrintTestStatus("SD.exists()", SD.exists("x/")); + ATS_PrintTestStatus("SD.exists()", SD.exists("x/y")); + ATS_PrintTestStatus("SD.exists()", SD.exists("x/y/")); + ATS_PrintTestStatus("SD.exists()", SD.exists("x/y/z")); + ATS_PrintTestStatus("SD.exists()", SD.exists("x/y/z/")); + ATS_PrintTestStatus("SD.exists()", SD.exists("/x/y/z/")); + ATS_PrintTestStatus("SD.rmdir()", SD.rmdir("x/y/z")); + ATS_PrintTestStatus("SD.exists()", SD.exists("x")); + ATS_PrintTestStatus("SD.exists()", SD.exists("x/y")); + ATS_PrintTestStatus("!SD.exists()", !SD.exists("x/y/z")); + ATS_PrintTestStatus("SD.rmdir()", SD.rmdir("x/y/")); + ATS_PrintTestStatus("SD.exists()", SD.exists("x")); + ATS_PrintTestStatus("!SD.exists()", !SD.exists("x/y")); + ATS_PrintTestStatus("!SD.exists()", !SD.exists("x/y/z")); + ATS_PrintTestStatus("SD.rmdir()", SD.rmdir("/x")); + ATS_PrintTestStatus("!SD.exists()", !SD.exists("x")); + ATS_PrintTestStatus("!SD.exists()", !SD.exists("x/y")); + ATS_PrintTestStatus("!SD.exists()", !SD.exists("x/y/z")); + + ATS_PrintTestStatus("!SD.open()", !(f.open("asdf/asdf.txt", FILE_WRITE))); f.close(); + ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf")); + ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf.txt")); + ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf/asdf.txt")); + ATS_PrintTestStatus("SD.mkdir()", SD.mkdir("asdf")); + ATS_PrintTestStatus("SD.exists()", SD.exists("asdf")); + ATS_PrintTestStatus("SD.open()", f.open("asdf/asdf.txt", FILE_WRITE)); f.close(); + ATS_PrintTestStatus("SD.exists()", SD.exists("asdf/asdf.txt")); + ATS_PrintTestStatus("!SD.rmdir()", !SD.rmdir("asdf")); + ATS_PrintTestStatus("SD.exists()", SD.exists("asdf")); + ATS_PrintTestStatus("SD.exists()", SD.exists("asdf/asdf.txt")); + ATS_PrintTestStatus("SD.remove()", SD.remove("asdf/asdf.txt")); + ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf/asdf.txt")); + ATS_PrintTestStatus("SD.exists()", SD.exists("asdf")); + ATS_PrintTestStatus("SD.rmdir()", SD.rmdir("asdf")); + ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf")); + +done: + + testEnd(); + +} +void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_Seek/ATS_SD_Seek.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_Seek/ATS_SD_Seek.ino new file mode 100644 index 0000000..2f20f7d --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_Seek/ATS_SD_Seek.ino @@ -0,0 +1,108 @@ +// modified from ArduinoTestSuite 0022 by William Greiman +// Tests writing to and reading from a file, in particular the +// the Stream implementation (e.g. read() and peek()). +#include +#include +#include +SdFat SD; +#define ATS_PrintTestStatus(msg, b) testVerify_P(b, PSTR(msg)) + +void setup() { + boolean b; + SdFile f; + + testBegin(); + + ATS_PrintTestStatus("SD.begin()", b = SD.begin()); + if (!b) goto done; + + SD.remove("test.txt"); + + f.open("test.txt", FILE_WRITE); + ATS_PrintTestStatus("SD.open()", f.isOpen()); + if (!f.isOpen()) goto done; + + ATS_PrintTestStatus("initial position", f.curPosition() == 0); + ATS_PrintTestStatus("initial size", f.fileSize() == 0); + + f.print("0123456789"); + + ATS_PrintTestStatus("position after writing", f.curPosition() == 10); + ATS_PrintTestStatus("size after writing", f.fileSize() == 10); + + f.seekSet(0); + + ATS_PrintTestStatus("size after seek", f.fileSize() == 10); + ATS_PrintTestStatus("position after seek", f.curPosition() == 0); + + f.seekSet(7); + + ATS_PrintTestStatus("position after seek", f.curPosition() == 7); + ATS_PrintTestStatus("reading after seek", f.read() == '7'); + ATS_PrintTestStatus("position after reading after seeking", f.curPosition() == 8); + ATS_PrintTestStatus("reading after reading after seeking", f.read() == '8'); + + f.seekSet(3); + + ATS_PrintTestStatus("position after seeking", f.curPosition() == 3); + ATS_PrintTestStatus("peeking after seeking", f.peek() == '3'); + ATS_PrintTestStatus("position after peeking after seeking", f.curPosition() == 3); + ATS_PrintTestStatus("peeking after peeking after seeking", f.peek() == '3'); + ATS_PrintTestStatus("position after peeking after seeking", f.curPosition() == 3); + ATS_PrintTestStatus("peeking after peeking after seeking", f.read() == '3'); + ATS_PrintTestStatus("position after peeking after seeking", f.curPosition() == 4); + + f.seekSet(1); + + ATS_PrintTestStatus("position after seeking", f.curPosition() == 1); + ATS_PrintTestStatus("peeking after seeking", f.peek() == '1'); + + f.seekSet(4); + + ATS_PrintTestStatus("position after seeking", f.curPosition() == 4); + ATS_PrintTestStatus("peeking after seeking", f.peek() == '4'); + + f.seekSet(7); + + ATS_PrintTestStatus("position()", f.curPosition() == 7); + ATS_PrintTestStatus("read()", f.read() == '7'); + + f.seekSet(0); + f.peek(); + f.print("AB"); + + ATS_PrintTestStatus("position()", f.curPosition() == 2); + ATS_PrintTestStatus("size()", f.fileSize() == 10); + ATS_PrintTestStatus("read()", f.read() == '2'); + + f.seekSet(0); + + ATS_PrintTestStatus("read()", f.read() == 'A'); + ATS_PrintTestStatus("read()", f.read() == 'B'); + ATS_PrintTestStatus("read()", f.read() == '2'); + + f.close(); + + f.open("test.txt", O_READ); + ATS_PrintTestStatus("SD.open()", f.isOpen()); + if (!f.isOpen()) goto done; + + ATS_PrintTestStatus("position()", f.curPosition() == 0); + ATS_PrintTestStatus("size()", f.fileSize() == 10); + ATS_PrintTestStatus("peek()", f.peek() == 'A'); + ATS_PrintTestStatus("read()", f.read() == 'A'); + + f.seekSet(4); + + ATS_PrintTestStatus("position()", f.curPosition() == 4); + ATS_PrintTestStatus("size()", f.fileSize() == 10); + ATS_PrintTestStatus("peek()", f.peek() == '4'); + ATS_PrintTestStatus("read()", f.read() == '4'); + + f.close(); + +done: + testEnd(); +} + +void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/StressTest/StressTest.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/StressTest/StressTest.ino new file mode 100644 index 0000000..a990925 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/StressTest/StressTest.ino @@ -0,0 +1,76 @@ +// This stress test will create and write files until the SD is full. +#include +#include + +// SD chip select pin. +const uint8_t SD_CS_PIN = SS; + +// Set write buffer size. +#ifdef __arm__ +#ifndef CORE_TEENSY +// Due +const size_t BUF_SIZE = 32768; +#else // CORE_TEENSY +// Teensy 3.0 +const size_t BUF_SIZE = 8192; +#endif // CORE_TEENSY +#elif defined(RAMEND) && RAMEND > 5000 +// AVR with more than 4 KB RAM +const size_t BUF_SIZE = 4096; +#else // __arm__ +// other +const size_t BUF_SIZE = 512; +#endif // __arm__ + +const size_t FILE_SIZE_KB = 10240; +const uint16_t BUFS_PER_FILE = (1024L*FILE_SIZE_KB/BUF_SIZE); + +SdFat sd; + +SdFile file; + +uint8_t buf[BUF_SIZE]; +char name[13]; +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + Serial.print("BUF_SIZE "); + Serial.println(BUF_SIZE); + Serial.println("Type any character to start"); + while (Serial.read() < 0) {} + + if (!sd.begin(SD_CS_PIN))sd.errorHalt("sd.begin"); + + // Fill buf with known value. + for (size_t i = 0; i < BUF_SIZE; i++) buf[i] = i; + + // Wait to begin. + do {delay(10);} while (Serial.read() >= 0); + Serial.println("Type any character to stop after next file"); +} +//------------------------------------------------------------------------------ +void loop() { + // Free KB on SD. + uint32_t freeKB = sd.vol()->freeClusterCount()*sd.vol()->blocksPerCluster()/2; + + Serial.print("Free KB: "); + Serial.println(freeKB); + if (freeKB < 2*FILE_SIZE_KB) { + Serial.println(" Done!"); + while(1); + } + sprintf(name, "%lu.DAT", freeKB); + if (!file.open(name, O_WRITE | O_CREAT | O_TRUNC)) { + sd.errorHalt("Open error!"); + } + for (uint16_t i = 0; i < BUFS_PER_FILE; i++) { + if (file.write(buf, BUF_SIZE) != BUF_SIZE) { + sd.errorHalt("Write error!"); + } + } + file.close(); + if (Serial.available()) { + Serial.println("Stopped!"); + while(1); + } +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/TestMkdir/TestMkdir.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/TestMkdir/TestMkdir.ino new file mode 100644 index 0000000..3fa9434 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/TestMkdir/TestMkdir.ino @@ -0,0 +1,138 @@ +/* + * This sketch is a test of subdirectory and file creation. + * It also tests allocation of clusters to directories. + * + * It will create two subdirectories and create enough files + * to force the allocation of a cluster to each directory. + * + * More than 3000 files may be created on a FAT32 volume. + * + * Note: Some cards may 'stutter' others just get slow due + * to the number of flash erases this program causes. + */ +#include +#include +#include + +const uint8_t SD_CHIP_SELECT = SS; + +SdFat sd; + +// store error strings in flash to save RAM +#define error(s) sd.errorHalt(F(s)) + +/* + * create enough files to force a cluster to be allocated to dir. + */ +void dirAllocTest(FatFile* dir) { + char buf[32], name[32]; + SdFile file; + uint16_t n; + uint32_t size = dir->dirSize(); + + // create files and write name to file + for (n = 0; ; n++){ + // make file name + sprintf(name, "%u.TXT", n); + + // open start time + uint32_t t0 = millis(); + if (!file.open(dir, name, O_WRITE | O_CREAT | O_EXCL)) { + error("open for write failed"); + } + + // open end time and write start time + uint32_t t1 = millis(); + // write file name to file + file.print(name); + if (!file.close()) error("close write"); + + // write end time + uint32_t t2 = millis(); + Serial.print(F("WR ")); + Serial.print(n); + Serial.write(' '); + + // print time to create file + Serial.print(t1 - t0); + Serial.write(' '); + + // print time to write file + Serial.println(t2 - t1); + + // directory size will change when a cluster is added + if (dir->curPosition() > size) break; + } + + // read files and check content + for (uint16_t i = 0; i <= n; i++) { + sprintf(name, "%u.TXT", i); + + // open start time + uint32_t t0 = millis(); + if (!file.open(dir, name, O_READ)) { + error("open for read failed"); + } + + // open end time and read start time + uint32_t t1 = millis(); + int16_t nr = file.read(buf, sizeof(buf)); + if (nr < 5) error("file.read failed"); + + // read end time + uint32_t t2 = millis(); + + // check file content + if (strlen(name) != (size_t)nr || strncmp(name, buf, nr)) { + error("content compare failed"); + } + if (!file.close()) error("close read failed"); + + Serial.print(F("RD ")); + Serial.print(i); + Serial.write(' '); + + // print open time + Serial.print(t1 - t0); + Serial.write(' '); + + // print read time + Serial.println(t2 - t1); + } +} + +void setup() { + Serial.begin(9600); + while (!Serial) {} // wait for Leonardo + Serial.println(F("Type any character to start")); + while (Serial.read() <= 0) {} + delay(200); // Catch Due reset problem + + // initialize the SD card at SPI_FULL_SPEED for best performance. + // try SPI_HALF_SPEED if bus errors occur. + if (!sd.begin(SD_CHIP_SELECT, SPI_FULL_SPEED)) sd.initErrorHalt(); + + uint32_t m = millis(); + // write files to root if FAT32 + if (sd.vol()->fatType() == 32) { + Serial.println(F("Writing files to root")); + dirAllocTest(sd.vwd()); + } + + // create sub1 and write files + SdFile sub1; + if (!sub1.mkdir(sd.vwd(), "SUB1")) error("makdeDir SUB1 failed"); + Serial.println(F("Writing files to SUB1")); + dirAllocTest(&sub1); + + // create sub2 and write files + SdFile sub2; + if (!sub2.mkdir(&sub1, "SUB2")) error("mkdir SUB2 failed"); + Serial.println(F("Writing files to SUB2")); + dirAllocTest(&sub2); + m = millis() - m; + Serial.print(F("Done millis: ")); + Serial.println(m); +} + +void loop() { } \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/TestRmdir/TestRmdir.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/TestRmdir/TestRmdir.ino new file mode 100644 index 0000000..41ce89d --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/TestRmdir/TestRmdir.ino @@ -0,0 +1,98 @@ +/* + * This sketch will remove the files and directories + * created by the SdFatMakeDir.pde sketch. + * + * Performance is erratic due to the large number + * of flash erase operations caused by many random + * writes to file structures. + */ +#include +#include +#include + +const uint8_t SD_CHIP_SELECT = SS; + +SdFat sd; + +// store error strings in flash to save RAM +#define error(s) sd.errorHalt(F(s)) + +/* + * remove all files in dir. + */ +void deleteFiles(FatFile* dir) { + char name[32]; + SdFile file; + + // open and delete files + for (uint16_t n = 0; ; n++){ + sprintf(name, "%u.TXT", n); + + // open start time + uint32_t t0 = millis(); + + // assume done if open fails + if (!file.open(dir, name, O_WRITE)) return; + + // open end time and remove start time + uint32_t t1 = millis(); + if (!file.remove()) error("file.remove failed"); + + // remove end time + uint32_t t2 = millis(); + + Serial.print(F("RM ")); + Serial.print(n); + Serial.write(' '); + + // open time + Serial.print(t1 - t0); + Serial.write(' '); + + // remove time + Serial.println(t2 - t1); + } +} + +void setup() { + Serial.begin(9600); + while (!Serial) {} // wait for Leonardo + Serial.println(F("Type any character to start")); + while (Serial.read() <= 0) {} + delay(200); // Catch Due reset problem + + // initialize the SD card at SPI_FULL_SPEED for best performance. + // try SPI_HALF_SPEED if bus errors occur. + if (!sd.begin(SD_CHIP_SELECT, SPI_FULL_SPEED)) sd.initErrorHalt(); + + + // delete files in root if FAT32 + if (sd.vol()->fatType() == 32) { + Serial.println(F("Remove files in root")); + deleteFiles(sd.vwd()); + } + + // open SUB1 and delete files + SdFile sub1; + if (!sub1.open("SUB1", O_READ)) error("open SUB1 failed"); + Serial.println(F("Remove files in SUB1")); + deleteFiles(&sub1); + + // open SUB2 and delete files + SdFile sub2; + if (!sub2.open(&sub1, "SUB2", O_READ)) error("open SUB2 failed"); + Serial.println(F("Remove files in SUB2")); + deleteFiles(&sub2); + + // remove SUB2 + if (!sub2.rmdir()) error("sub2.rmdir failed"); + Serial.println(F("SUB2 removed")); + + // remove SUB1 + if (!sub1.rmdir()) error("sub1.rmdir failed"); + Serial.println(F("SUB1 removed")); + + Serial.println(F("Done")); +} + +void loop() { } diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/fstreamTest/fstreamTest.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/fstreamTest/fstreamTest.ino new file mode 100644 index 0000000..2bd9bd5 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/fstreamTest/fstreamTest.ino @@ -0,0 +1,94 @@ +#include +#include +#include +SdFat sd; +const char *testName = "SDFAT.TST"; +//------------------------------------------------------------------------------ +void fstreamOpen() { + ios::openmode nocreate[] = {ios::in, ios::in | ios::out}; + ios::openmode create[] = + {ios::out, ios::out | ios::app, ios::app, ios::out | ios::trunc, + ios::in | ios::out | ios::trunc, ios::in | ios::out | ios::app, + ios::in | ios::app}; + ios::openmode illegal[] = + {0, ios::trunc, ios::app | ios::trunc, ios::in | ios::app | ios::trunc, + ios::in | ios::trunc, ios::out | ios::app | ios::trunc, + ios::in | ios::out | ios::app | ios::trunc}; + + sd.remove(testName); + fstream file(testName); + testVerifyMsg(!file.is_open()&& !sd.exists(testName), "fstream constructor"); + + for (uint8_t i = 0 ; i < sizeof(nocreate)/sizeof(nocreate[1]); i++) { + file.close(); + sd.remove(testName); + file.open(testName, nocreate[i]); + testVerifyMsg(!sd.exists(testName) && !file.is_open(), "fstream nocreate !exists"); + } + for (uint8_t i = 0 ; i < sizeof(create)/sizeof(create[1]); i++) { + file.close(); + sd.remove(testName); + file.open(testName, create[i]); + testVerifyMsg(sd.exists(testName) && file.is_open(), "fstream create openmode"); + } + for (uint8_t i = 0 ; i < sizeof(illegal)/sizeof(illegal[1]); i++) { + file.close(); + file.open(testName, illegal[i]); + testVerifyMsg(sd.exists(testName) && !file.is_open(), "fstream illegal openmode"); + } + for (uint8_t i = 0 ; i < sizeof(nocreate)/sizeof(nocreate[1]); i++) { + file.close(); + file.open(testName, nocreate[i]); + testVerifyMsg(sd.exists(testName) && file.is_open(), "fstream nocreate exists"); + } +} +//------------------------------------------------------------------------------ +void testPosition() { + sd.remove(testName); + ofstream ofs(testName); + testVerifyBool(ofs.good() && ofs.tellp() == 0); + ofs.seekp(0, ios::end); + testVerifyBool(ofs.good() && ofs.tellp() == 0); + ofs << "abcde"; + testVerifyBool(ofs.good() && ofs.tellp() == 5); + ofs.seekp(4); + testVerifyBool(ofs.good() && ofs.tellp() == 4); + ofs.seekp(-1, ios::cur); + testVerifyBool(ofs.good() && ofs.tellp() == 3); + ofs.close(); + ifstream ifs(testName, ios::ate); + testVerifyBool(ifs.good() && ifs.tellg() == 5); + ifs.seekg(0); + testVerifyBool(ifs.get() == 'a' && ifs.get() == 'b'); + testVerifyBool(ifs.tellg() == 2 && ifs.good()); + ifs.seekg(3, ios::cur); + testVerifyBool(ifs.tellg() == 5 && ifs.good()); + ifs.seekg(4, ios::beg); + testVerifyBool(ifs.good() && ifs.tellg() == 4); + ifs.close(); + ofs.open(testName, ios::app); + testVerifyBool(ofs.good() && ofs.tellp() == 0); + ofs << 'f'; + testVerifyBool(ofs.good() && ofs.tellp() == 6); + ofs.close(); + ofs.open(testName, ios::trunc); + ofs.seekp(0, ios::end); + testVerifyBool(ofs.good() && ofs.tellp() == 0); + ofs << "ABCDEF"; + ofs.close(); + fstream fs(testName); + testVerifyBool(fs.good() && fs.tellp() == 0 && fs.tellg() == 0); + fs.seekg(2); + testVerifyBool(fs.good() && fs.get() == 'C'); +} +//------------------------------------------------------------------------------ +void setup() { + + testBegin(); + if (!sd.begin()) sd.initErrorHalt(); + fstreamOpen(); + testPosition(); + testEnd(); +} +//------------------------------------------------------------------------------ +void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/istreamTest/istreamTest.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/istreamTest/istreamTest.ino new file mode 100644 index 0000000..15d33fb --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/istreamTest/istreamTest.ino @@ -0,0 +1,261 @@ +#include +#include +#include + +char buf[100]; +ibufstream ib; +#define ibInit(s) ibInit_P(PSTR(s)) + +//---------------------------------------------------------- +void ibInit_P(PGM_P p) { + if (strlen_P(p) >= sizeof(buf)) { + ib.init(""); + ib.setstate(ios::badbit); + } else { + ib.clear(); + strncpy_P(buf, p, sizeof(buf)); + ib.init(buf); + } +} +//------------------------------------------------------------------------------ +void istreamBool() { + bool b; + ibInit(" 0 1 2"); + testVerifyBool((ib >> b) && !b); + testVerifyBool((ib >> b) && b); + testVerifyBool(!(ib >> b) && !ib.good()); + + ibInit(" true false err"); + testVerifyBool((ib >> boolalpha >> b) && b && ib.good()); + testVerifyBool((ib >> b) && !b && ib.good()); + testVerifyBool(!(ib >> b) && ib.fail()); + + ibInit("1"); + testVerifyBool((ib >> noboolalpha >> b) && b && ib.eof()); +} +//------------------------------------------------------------------------------ +void istreamChar() { + char c; + signed char sc; + unsigned char uc; + + ibInit("c s u g"); + testVerifyBool((ib >> c) && ib.good() && c == 'c'); + testVerifyBool((ib >> sc) && ib.good() && sc == 's'); + testVerifyBool((ib >> uc) && ib.good() && uc == 'u'); + testVerifyBool(ib.get() == ' '); + testVerifyBool(ib.peek() == 'g' && ib.good()); + testVerifyBool(ib.get() == 'g' && ib.good()); + testVerifyBool(ib.get() == -1 && ib.eof()); +} +//------------------------------------------------------------------------------ +void istreamDouble() { + double f; + ibInit("0 .1 1. 2 3.4 .1e5 1e5 -1E6 +2.3e-3 -123.4567"); + testVerifyBool((ib >> f) && f == 0 && ib.good()); + testVerifyBool((ib >> f) && f == 0.1 && ib.good()); + testVerifyBool((ib >> f) && f == 1.0 && ib.good()); + testVerifyBool((ib >> f) && f == 2.0 && ib.good()); + testVerifyBool((ib >> f) && f == 3.4 && ib.good()); + testVerifyBool((ib >> f) && f == 10000.0 && ib.good()); + testVerifyBool((ib >> f) && f == 1e5 && ib.good()); + testVerifyBool((ib >> f) && f == -1E6 && ib.good()); + testVerifyBool((ib >> f) && f == 2.3e-3 && ib.good()); + testVerifyBool((ib >> f) && fabs(f + 123.4567) < 1e-5 && ib.eof()); + if (fabs(f + 123.4567) >= 1e-5) Serial.println(f, 8); +} +//------------------------------------------------------------------------------ +void istreamFloat() { + float f; + ibInit("0 .1 1. 2 3.4 .1e5 1e5 -1E6 +2.3e-3 -123.4567"); + testVerifyBool((ib >> f) && f == 0 && ib.good()); + testVerifyBool((ib >> f) && f == 0.1f && ib.good()); + testVerifyBool((ib >> f) && f == 1.0 && ib.good()); + testVerifyBool((ib >> f) && f == 2.0 && ib.good()); + testVerifyBool((ib >> f) && f == 3.4f && ib.good()); + testVerifyBool((ib >> f) && f == 10000.0 && ib.good()); + testVerifyBool((ib >> f) && f == 1e5 && ib.good()); + testVerifyBool((ib >> f) && f == -1E6 && ib.good()); + testVerifyBool((ib >> f) && f == 2.3e-3f && ib.good()); + testVerifyBool((ib >> f) && fabs(f + 123.4567f) < 1e-5 && ib.eof()); + if (fabs(f + 123.4567) >= 1e-5) Serial.println(f, 8); +} +//------------------------------------------------------------------------------ +void istreamGet() { + char s[4]; + ibInit("ab c"); + testVerifyBool(ib.get() == 'a' && ib.good() && ib.gcount() == 1); + testVerifyBool(ib.get() == 'b' && ib.good() && ib.gcount() == 1); + testVerifyBool(ib.get() == ' ' && ib.good() && ib.gcount() == 1); + testVerifyBool(ib.get() == 'c' && ib.good() && ib.gcount() == 1); + testVerifyBool(ib.get() == -1 && ib.eof() && ib.gcount() == 0); + + ibInit("ab\ncdef"); + ib.get(s, sizeof(s)); + testVerifyBool(ib.good() && ib.gcount() == 2); + testVerifyStr(s, "ab"); + testVerifyBool(ib.get() == '\n' && ib.good() && ib.gcount() == 1); + ib.get(s, sizeof(s)); + testVerifyBool(ib.good() && ib.gcount() == 3); + testVerifyStr(s, "cde"); + ib.get(s, sizeof(s)); + testVerifyBool(ib.eof() && ib.gcount() == 1); + testVerifyStr(s, "f"); + + ibInit( + "short line\n" + "\n" + "17 character line\n" + "too long for buffer\n" + "line with no nl" + ); + char buf[18]; + ib.getline(buf, sizeof(buf)); + testVerifyBool(ib.good() && ib.gcount() == 11); + testVerifyStr(buf, "short line"); + ib.getline(buf, sizeof(buf)); + testVerifyBool(ib.good() && ib.gcount() == 1 && buf[0] == '\0'); + ib.getline(buf, sizeof(buf)); + testVerifyBool(ib.good() && ib.gcount() == 18); + testVerifyStr(buf, "17 character line"); + ib.getline(buf, sizeof(buf)); + testVerifyBool(ib.fail() && !ib.eof() && ib.gcount() == 17); + testVerifyStr(buf, "too long for buff"); + ib.clear(); + ib.getline(buf, sizeof(buf)); + testVerifyBool(ib.good() && !ib.eof() && ib.gcount() == 3); + testVerifyStr(buf, "er"); + ib.getline(buf, sizeof(buf)); + testVerifyBool(!ib.fail() && ib.eof() && ib.gcount() == 15); + testVerifyStr(buf, "line with no nl"); +} +//------------------------------------------------------------------------------ +void istreamNumber() { + short s; + signed short ss; + unsigned short us; + int i; + signed int si; + unsigned int ui; + long l; + signed long sl; + unsigned long ul; + + ibInit("-32769"); + testVerifyBool(!(ib >> s) && ib.fail()); + ibInit("-32768 0 32767 32768"); + testVerifyBool((ib >> s) && s == -32768 && ib.good()); + testVerifyBool((ib >> s) && s == 0 && ib.good()); + testVerifyBool((ib >> s) && s == 32767 && ib.good()); + testVerifyBool(!(ib >> s) && ib.fail()); + + ibInit("-32769"); + testVerifyBool(!(ib >> ss) && ib.fail()); + ibInit("-32768 0 32767 32768"); + testVerifyBool((ib >> ss) && ss == -32768 && ib.good()); + testVerifyBool((ib >> ss) && ss == 0 && ib.good()); + testVerifyBool((ib >> ss) && ss == 32767 && ib.good()); + testVerifyBool(!(ib >> ss) && ib.fail()); + + ibInit("0 65535 65536"); + testVerifyBool((ib >> us) && us == 0 && ib.good()); + testVerifyBool((ib >> us) && us == 65535 && ib.good()); + testVerifyBool(!(ib >> us) && ib.fail()); + +if (sizeof(int) == 2) { + ibInit("-32769"); + testVerifyBool(!(ib >> i) && ib.fail()); + ibInit("-32768 0 32767 32768"); + testVerifyBool((ib >> i) && i == -32768 && ib.good()); + testVerifyBool((ib >> i) && i == 0 && ib.good()); + testVerifyBool((ib >> i) && i == 32767 && ib.good()); + testVerifyBool(!(ib >> i) && ib.fail()); + + ibInit("-32769"); + testVerifyBool(!(ib >> si) && ib.fail()); + ibInit("-32768 0 32767 32768"); + testVerifyBool((ib >> si) && si == -32768 && ib.good()); + testVerifyBool((ib >> si) && si == 0 && ib.good()); + testVerifyBool((ib >> si) && si == 32767 && ib.good()); + testVerifyBool(!(ib >> si) && ib.fail()); + + ibInit("0 65535 65536"); + testVerifyBool((ib >> ui) && ui == 0 && ib.good()); + testVerifyBool((ib >> ui) && ui == 65535 && ib.good()); + testVerifyBool(!(ib >> ui) && ib.fail()); + } else { + ibInit("-2147483649"); + testVerifyBool(!(ib >> i) && ib.fail()); + ibInit("-2147483648 0 2147483647 2147483648"); + testVerifyBool((ib >> i) && i == -2147483648 && ib.good()); + testVerifyBool((ib >> i) && i == 0 && ib.good()); + testVerifyBool((ib >> i) && i == 2147483647 && ib.good()); + testVerifyBool(!(ib >> i) && ib.fail()); + + ibInit("-2147483649"); + testVerifyBool(!(ib >> si) && ib.fail()); + ibInit("-2147483648 0 2147483647 2147483648"); + testVerifyBool((ib >> si) && si == -2147483648 && ib.good()); + testVerifyBool((ib >> si) && si == 0 && ib.good()); + testVerifyBool((ib >> si) && si == 2147483647 && ib.good()); + testVerifyBool(!(ib >> si) && ib.fail()); + + ibInit("0 4294967295 4294967296"); + testVerifyBool((ib >> ui) && ui == 0 && ib.good()); + testVerifyBool((ib >> ui) && ui == 4294967295 && ib.good()); + testVerifyBool(!(ib >> ui) && ib.fail()); + } + ibInit("-2147483649"); + testVerifyBool(!(ib >> l) && ib.fail()); + ibInit("-2147483648 0 2147483647 2147483648"); + testVerifyBool((ib >> l) && l == -2147483648 && ib.good()); + testVerifyBool((ib >> l) && l == 0 && ib.good()); + testVerifyBool((ib >> l) && l == 2147483647 && ib.good()); + testVerifyBool(!(ib >> l) && ib.fail()); + + ibInit("-2147483649"); + testVerifyBool(!(ib >> sl) && ib.fail()); + ibInit("-2147483648 0 2147483647 2147483648"); + testVerifyBool((ib >> sl) && sl == -2147483648 && ib.good()); + testVerifyBool((ib >> sl) && sl == 0 && ib.good()); + testVerifyBool((ib >> sl) && sl == 2147483647 && ib.good()); + testVerifyBool(!(ib >> sl) && ib.fail()); + + ibInit("0 4294967295 4294967296"); + testVerifyBool((ib >> ul) && ul == 0 && ib.good()); + testVerifyBool((ib >> ul) && ul == 4294967295 && ib.good()); + testVerifyBool(!(ib >> ul) && ib.fail()); + + // octal hex + ibInit("123 abc 0xdef 0XABC 567"); + testVerifyBool((ib >> oct >> i) && i == 83); + testVerifyBool((ib >> hex >> i) && i == 0xabc); + testVerifyBool((ib >> i) && i == 0xdef); + testVerifyBool((ib >> i) && i == 0xabc); + testVerifyBool((ib >> dec >> i) && i ==567); +} +//------------------------------------------------------------------------------ +void istreamStr() { + char str[20]; + ibInit("abc def\r\n hij"); + testVerifyBool((ib >> str) && ib.good()); + testVerifyStr(str, "abc"); + testVerifyBool((ib >> str) && ib.good()); + testVerifyStr(str, "def"); + testVerifyBool((ib >> str) && ib.eof()); + testVerifyStr(str, "hij"); +} +//------------------------------------------------------------------------------ +void setup() { + testBegin(); + istreamBool(); + istreamChar(); + istreamDouble(); + istreamFloat(); + istreamGet(); + istreamNumber(); + istreamStr(); + testEnd(); +} +//------------------------------------------------------------------------------ +void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnSize/lfnSize.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnSize/lfnSize.ino new file mode 100644 index 0000000..a0d20b0 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnSize/lfnSize.ino @@ -0,0 +1,36 @@ +// Program to compare size of SdFat with the SD.h library. +#include +// Select the test library by commenting out one of the following two lines. +// #include +#include + +// SD chip select pin. +const uint8_t SD_CS_PIN = SS; + +#ifdef __SD_H__ +File file; +#else // __SD_H__ +SdFat SD; +SdFile file; +#endif // __SD_H__ + +void setup() { + Serial.begin(9600); + while (!Serial) {} // wait for Leonardo + + if (!SD.begin(SD_CS_PIN)) { + Serial.println("begin failed"); + return; + } + #ifdef __SD_H__ + file = SD.open("SFN_file.txt", FILE_WRITE); + #else // __SD_H__ + file.open("LFN_file.txt", O_RDWR | O_CREAT); + #endif // __SD_H__ + + file.println("Hello"); + file.close(); + Serial.println("Done"); +} +//------------------------------------------------------------------------------ +void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnTest/lfnTest.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnTest/lfnTest.ino new file mode 100644 index 0000000..f7c0ece --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnTest/lfnTest.ino @@ -0,0 +1,234 @@ +#include +#include +#include +const uint8_t SD_CS_PIN = SS; +SdFat sd; +SdFile file; +char name[260]; + +//------------------------------------------------------------------------------ +const char* testName[] = { + "low.low", + "low.Mix", + "low.UP", + "Mix.low", + "Mix.Mix", + "Mix.UP", + "UP.low", + "UP.Mix", + "UP.UP", + ".dot", + ".dot.dot", + "A b c . txt", + " Leading space and no extension", + "Trailing dots and space . . .", + "Long extension.extension", + "Space after dot. txt", + "Dot.dot.test.txt", + "Dot.dot.test.seq.txt", + "LOW.LOW", + "MIX.MIX", + "Invalid character *.test" +}; +//------------------------------------------------------------------------------ +bool checkName(char first, size_t len) { + size_t i; + if (len < 5 || len > sizeof(name)) { + return false; + } + if ( name[0] != first) { + return false; + } + for (i = 1; i < (len - 4); i++) { + if (name[i] != (char)('0' + (i + 1) %10)) { + return false; + } + } + const char* p = ".txt"; + while (*p) { + if (name[i++] != *p++) { + return false; + } + } + return name[i] == 0; +} +//------------------------------------------------------------------------------ +void makeName(char first, size_t len) { + size_t i; + if (len > sizeof(name)) { + len = 255; + } + if (len < 5) { + len = 5; + } + name[0] = first; + for (i = 1; i < (len - 4); i++) { + name[i] = '0' + (i + 1) %10; + } + const char* p = ".txt"; + while (*p) name[i++] = *p++; + name[i] = 0; +} +//------------------------------------------------------------------------------ +// test open, remove, getName, and ls. +void basicTest() { + size_t i; + size_t n = sd.vol()->fatType() == 32 ? 255 : 99; + uint16_t maxIndex = 0; + + makeName('Z', 256); + if (!file.open(name, O_RDWR | O_CREAT)) { + Serial.println(F("255 limit OK")); + } else { + sd.errorHalt(F("255 limit")); + } + for (i = 5; i <= n; i++) { + makeName('A', i); + + if (!file.open(name, O_RDWR | O_CREAT)) { + sd.errorHalt(F("open A")); + } + file.println(name); + Serial.print(i); + Serial.write(' '); + Serial.print(file.dirIndex()); + Serial.write(' '); + Serial.print(file.fileSize()); + Serial.println(F(" open A")); + if (file.fileSize() != (i + 2)) { + sd.errorHalt(F("file size A")); + } + if (file.dirIndex() >= maxIndex) { + maxIndex = file.dirIndex(); + } else { + Serial.print(maxIndex); Serial.print(',');Serial.println(file.dirIndex()); + sd.errorHalt(F("dirIndex")); + } + file.close(); + if (!file.open(sd.vwd(), maxIndex, O_READ)) { + sd.errorHalt(F("open by index")); + } + memset(name, 0, sizeof(name)); + if (!file.getName(name, sizeof(name))) { + sd.errorHalt(F("getName")); + } + if (!checkName('A', i)) { + Serial.println(name); + sd.errorHalt(F("checkName")); + } + file.close(); + } + for (i = n; i >= 5; i -= 2) { + makeName('A', i); + Serial.print(i); + Serial.println(F( " rm A")); + if (!sd.remove(name)) { + sd.errorHalt(F("remove A")); + } + } + for (i = n; i >= 5; i -= 2) { + makeName('B', i); + if (!file.open(name, O_RDWR | O_CREAT)) { + sd.errorHalt(F("open B")); + } + file.println(name); + Serial.print(i); + Serial.write(' '); + Serial.print(file.dirIndex()); + Serial.write(' '); + Serial.print(file.fileSize()); + Serial.println(F(" open B")); + if (file.fileSize() != (i + 2)) { + sd.errorHalt(F("file size B")); + } + if (file.dirIndex() > maxIndex) { + sd.errorHalt(F("maxIndex")); + } + file.close(); + } + Serial.println(F("----- ls ------")); + sd.ls(); + for (i = 5; i <= n; i++) { + char fc = i & 1 ? 'B' : 'A'; + makeName(fc, i); + Serial.print(i); + Serial.print(F(" rm ")); + Serial.println(fc); + if (!sd.remove(name)) { + sd.errorHalt(F("remove A/B")); + } + } + if (file.openNext(sd.vwd())) { + sd.errorHalt(F("remove all")); + } + Serial.println(); + Serial.println(F("basicTest done")); +} +//------------------------------------------------------------------------------ +void nameTest() { + Serial.println(); + uint8_t n = sizeof(testName)/sizeof(char*); + for (uint8_t i = 0; i < n; i++) { + Serial.print(F("Name: ")); + Serial.write('"'); + Serial.print(testName[i]); + Serial.println('"'); + if(!file.open(testName[i], O_CREAT | O_RDWR)) { + Serial.println(F("Open failed")); + } else { + file.println(testName[i]); + if (!file.getName(name, sizeof(name))) { + sd.errorHalt(F("getFilemame")); + } + file.println(name); + Serial.print(F("LFN: ")); + Serial.write('"'); + Serial.print(name); + Serial.println('"'); + Serial.print(F("SFN: ")); + Serial.write('"'); + file.printSFN(&Serial); + Serial.println('"'); + Serial.print(F("Index: ")); + if (file.dirIndex() < 10) { + Serial.write(' '); + } + Serial.println(file.dirIndex()); + file.close(); + } + Serial.println(); + } + Serial.println(F("----- ls ------")); + sd.ls(); + Serial.println(); + Serial.println(F("nameTest done")); +} +//------------------------------------------------------------------------------ +void setup() { + Serial.begin(9600); + while(!Serial); + Serial.print(F("\r\nFreeRam: ")); + Serial.println(FreeRam()); + Serial.println(F("Type any character to start.")); + while (Serial.read() < 0) {} + if (!sd.begin(SD_CS_PIN)) sd.initErrorHalt(); + if (file.openNext(sd.vwd())) { + file.close(); + delay(100); + while (Serial.read() >= 0) {} + Serial.print(F("Type 'W' to wipe the card: ")); + int c; + while ((c = Serial.read()) < 0) {} + if (c != 'W') { + sd.errorHalt(F("Invalid")); + } + Serial.println((char)c); + if (!sd.wipe(&Serial) || !sd.begin(SD_CS_PIN)) { + sd.errorHalt(F("wipe failed")); + } + } + basicTest(); + nameTest(); +} +//------------------------------------------------------------------------------ +void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnTestCout/lfnTestCout.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnTestCout/lfnTestCout.ino new file mode 100644 index 0000000..a331bd9 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnTestCout/lfnTestCout.ino @@ -0,0 +1,218 @@ +#include +#include +#include +const uint8_t SD_CS_PIN = SS; +SdFat sd; +SdFile file; +char name[260]; + +// Serial output stream +ArduinoOutStream cout(Serial); + +// Serial in buffer. +char cinBuf[10]; + +// Serial input stream +ArduinoInStream cin(Serial, cinBuf, sizeof(cinBuf)); +//------------------------------------------------------------------------------ +const char* testName[] = { + "low.low", + "low.Mix", + "low.UP", + "Mix.low", + "Mix.Mix", + "Mix.UP", + "UP.low", + "UP.Mix", + "UP.UP", + ".dot", + ".dot.dot", + "A b c . txt", + " Leading space and no extension", + "Trailing dots and space . . .", + "Long extension.extension", + "Space after dot. txt", + "Dot.dot.test.txt", + "Dot.dot.test.seq.txt", + "LOW.LOW", + "MIX.MIX", + "Invalid character *.test" +}; +//------------------------------------------------------------------------------ +bool checkName(char first, size_t len) { + size_t i; + if (len < 5 || len > sizeof(name)) { + return false; + } + if ( name[0] != first) { + return false; + } + for (i = 1; i < (len - 4); i++) { + if (name[i] != (char)('0' + (i + 1) %10)) { + return false; + } + } + const char* p = ".txt"; + while (*p) { + if (name[i++] != *p++) { + return false; + } + } + return name[i] == 0; +} +//------------------------------------------------------------------------------ +void makeName(char first, size_t len) { + size_t i; + if (len > sizeof(name)) { + len = 255; + } + if (len < 5) { + len = 5; + } + name[0] = first; + for (i = 1; i < (len - 4); i++) { + name[i] = '0' + (i + 1) %10; + } + const char* p = ".txt"; + while (*p) name[i++] = *p++; + name[i] = 0; +} +//------------------------------------------------------------------------------ +// test open, remove, getName, and ls. +void basicTest() { + size_t i; + size_t n = sd.vol()->fatType() == 32 ? 255 : 99; + uint16_t maxIndex = 0; + + makeName('Z', 256); + if (!file.open(name, O_RDWR | O_CREAT)) { + cout << F("255 limit OK") << endl; + } else { + sd.errorHalt(F("255 limit")); + } + for (i = 5; i <= n; i++) { + makeName('A', i); + + if (!file.open(name, O_RDWR | O_CREAT)) { + sd.errorHalt(F("open A")); + } + file.println(name); + cout << setw(3) << i << setw(5) << file.dirIndex() << F(" open A") << endl; + + if (file.fileSize() != (i + 2)) { + sd.errorHalt(F("file size A")); + } + if (file.dirIndex() >= maxIndex) { + maxIndex = file.dirIndex(); + } else { + sd.errorHalt(F("dirIndex")); + } + file.close(); + if (!file.open(sd.vwd(), maxIndex, O_READ)) { + sd.errorHalt(F("open by index")); + } + memset(name, 0, sizeof(name)); + if (!file.getName(name, sizeof(name))) { + sd.errorHalt(F("getName")); + } + if (!checkName('A', i)) { + cout << name << endl; + sd.errorHalt(F("checkName")); + } + file.close(); + } + for (i = n; i >= 5; i -= 2) { + makeName('A', i); + cout << setw(3) << i << F( " rm A") << endl; + if (!sd.remove(name)) { + sd.errorHalt(F("remove A")); + } + } + for (i = n; i >= 5; i -= 2) { + makeName('B', i); + if (!file.open(name, O_RDWR | O_CREAT)) { + sd.errorHalt(F("open B")); + } + file.println(name); + + cout << setw(3) << i << setw(5) << file.dirIndex() << F(" open B") << endl; + + if (file.fileSize() != (i + 2)) { + sd.errorHalt(F("file size B")); + } + if (file.dirIndex() > maxIndex) { + sd.errorHalt(F("maxIndex")); + } + file.close(); + } + cout << endl << F("----- ls ------") << endl; + sd.ls(); + for (i = 5; i <= n; i++) { + char fc = i & 1 ? 'B' : 'A'; + makeName(fc, i); + cout << setw(3) << i << F(" rm ") << fc << endl; + if (!sd.remove(name)) { + sd.errorHalt(F("remove A/B")); + } + } + if (file.openNext(sd.vwd())) { + sd.errorHalt(F("remove all")); + } + cout << endl << F("basicTest done") << endl; +} +//------------------------------------------------------------------------------ +void nameTest() { + cout << endl; + uint8_t n = sizeof(testName)/sizeof(char*); + for (uint8_t i = 0; i < n; i++) { + cout << F("Name: \"") << testName[i] << '"' << endl; + if(!file.open(testName[i], O_CREAT | O_RDWR)) { + cout < +#include +#include +//------------------------------------------------------------------------------ +void ostreamBool() { + char buf[40]; + obufstream ob(buf, sizeof(buf)); + bool f = false; + bool t = true; + ob << t << ',' << f << ',' << setw(2) << t << ',' << left << setw(2) << f; + testVerifyStr(buf, "1,0, 1,0 "); + + ob.init(buf, sizeof(buf)); + ob << boolalpha << t << ',' << f << ',' << setw(5) << t; + ob << ',' << right << setw(6) << f; + testVerifyStr(buf, "true,false,true , false"); +} +//------------------------------------------------------------------------------ +void ostreamChar() { + char buf[40]; + obufstream ob(buf, sizeof(buf)); + char c = 'c'; + signed char sc = 's'; + unsigned char uc = 'u'; + ob <<'l' << c << sc << uc; + ob.put('p'); + testVerifyStr(buf, "lcsup"); + + ob.init(buf, sizeof(buf)); + ob << 's' << setw(2) << 'r' << 'n' << left << setw(2) << 'l'; + ob << 'm' << right << setw(2) << 'e'; + testVerifyStr(buf, "s rnl m e"); + + ob.init(buf, sizeof(buf)); + ob << setfill('f') << setw(5) << 'r'; + testVerifyStr(buf, "ffffr"); +} +//------------------------------------------------------------------------------ +void ostreamFloat() { + char buf[50]; + obufstream ob(buf, sizeof(buf)); + float f = 9.87654; + double d = -123.4567; + ob << f <<','; + ob << internal << setw(10) << d << ','; + ob << setfill('0') << setw(10) << d; + testVerifyStr(buf, "9.88,- 123.46,-000123.46"); + + ob.init(buf, sizeof(buf)); + ob << setw(10) << left << d << ',' << showpos << -d << ','; + ob << setprecision(0) << d; + testVerifyStr(buf, "-123.46000,+123.46,-123"); + + ob.init(buf, sizeof(buf)); + ob << showpoint << d << noshowpoint << ',' << d << ','; + ob << setprecision(4) << f << ',' << setprecision(2) << noshowpos << f; + testVerifyStr(buf, "-123.,-123,+9.8765,9.88"); +} +//------------------------------------------------------------------------------ +void ostreamNumber() { + char buf[50]; + obufstream ob(buf, sizeof(buf)); + + short s = 1; + short signed ss = 2; + short unsigned su = 3; + int i = 4; + int signed is = 5; + int unsigned iu = 6; + long l = 7; + long signed ls = 8; + long unsigned lu = 9; + + + ob << s << ss << su << i << is << iu << l < +maintainer=Bill Greiman +sentence=FAT16/FAT32 file system for SD cards. +paragraph=FAT16/FAT32 file system for SD cards. +category=Data Storage +url=https://github.com/greiman/SdFat +repository=https://github.com/greiman/SdFat.git +architectures=* diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/BlockDriver.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/BlockDriver.h new file mode 100644 index 0000000..2e4f131 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/BlockDriver.h @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ + /** + * \file + * \brief Define block driver. + */ +#ifndef BlockDriver_h +#define BlockDriver_h +#include "FatLib/BaseBlockDriver.h" +#include "SdCard/SdSpiCard.h" +//----------------------------------------------------------------------------- +/** typedef for BlockDriver */ +#if ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS +typedef BaseBlockDriver BlockDriver; +#else // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS +typedef SdSpiCard BlockDriver; +#endif // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS +#endif // BlockDriver_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ArduinoFiles.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ArduinoFiles.h new file mode 100644 index 0000000..286f509 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ArduinoFiles.h @@ -0,0 +1,249 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +/** + * \file + * \brief PrintFile class + */ +#ifndef ArduinoFiles_h +#define ArduinoFiles_h +#include "FatLibConfig.h" +#if ENABLE_ARDUINO_FEATURES +#include "FatFile.h" +#include +//------------------------------------------------------------------------------ +/** Arduino SD.h style flag for open for read. */ +#define FILE_READ O_RDONLY +/** Arduino SD.h style flag for open at EOF for read/write with create. */ +#define FILE_WRITE (O_RDWR | O_CREAT | O_AT_END) +//============================================================================== +/** + * \class PrintFile + * \brief FatFile with Print. + */ +class PrintFile : public FatFile, public Print { + public: + PrintFile() {} + /** Create a file object and open it in the current working directory. + * + * \param[in] path A path for a file to be opened. + * + * \param[in] oflag Values for \a oflag are constructed by a + * bitwise-inclusive OR of open flags. see + * FatFile::open(FatFile*, const char*, oflag_t). + */ + PrintFile(const char* path, oflag_t oflag) : FatFile(path, oflag) {} +#if DESTRUCTOR_CLOSES_FILE + ~PrintFile() {} +#endif // DESTRUCTOR_CLOSES_FILE + using FatFile::clearWriteError; + using FatFile::getWriteError; + using FatFile::read; + using FatFile::write; + /** \return number of bytes available from the current position to EOF + * or INT_MAX if more than INT_MAX bytes are available. + */ + int available() { + uint32_t n = FatFile::available(); + return n > INT_MAX ? INT_MAX : n; + } + /** Ensure that any bytes written to the file are saved to the SD card. */ + void flush() { + FatFile::sync(); + } + /** Return the next available byte without consuming it. + * + * \return The byte if no error and not at eof else -1; + */ + int peek() { + return FatFile::peek(); + } + /** Read the next byte from a file. + * + * \return For success return the next byte in the file as an int. + * If an error occurs or end of file is reached return -1. + */ +// int read() { +// return FatFile::read(); +// } + /** Write a byte to a file. Required by the Arduino Print class. + * \param[in] b the byte to be written. + * Use getWriteError to check for errors. + * \return 1 for success and 0 for failure. + */ + size_t write(uint8_t b) { + return FatFile::write(b); + } + /** Write data to an open file. Form required by Print. + * + * \note Data is moved to the cache but may not be written to the + * storage device until sync() is called. + * + * \param[in] buf Pointer to the location of the data to be written. + * + * \param[in] size Number of bytes to write. + * + * \return For success write() returns the number of bytes written, always + * \a nbyte. If an error occurs, write() returns -1. Possible errors + * include write() is called before a file has been opened, write is called + * for a read-only file, device is full, a corrupt file system or an + * I/O error. + */ + size_t write(const uint8_t *buf, size_t size) { + return FatFile::write(buf, size); + } +}; +//============================================================================== +/** + * \class File + * \brief Arduino SD.h style File API + */ +class File : public FatFile, public Stream { + public: + File() {} + /** Create a file object and open it in the current working directory. + * + * \param[in] path A path with a valid 8.3 DOS name for a file to be opened. + * + * \param[in] oflag Values for \a oflag are constructed by a + * bitwise-inclusive OR of open flags. see + * FatFile::open(FatFile*, const char*, oflag_t). + */ + File(const char* path, oflag_t oflag) { + open(path, oflag); + } + using FatFile::clearWriteError; + using FatFile::getWriteError; + using FatFile::read; + using FatFile::write; + /** The parenthesis operator. + * + * \return true if a file is open. + */ + operator bool() { + return isOpen(); + } + /** \return number of bytes available from the current position to EOF + * or INT_MAX if more than INT_MAX bytes are available. + */ + int available() { + uint32_t n = FatFile::available(); + return n > INT_MAX ? INT_MAX : n; + } + /** Ensure that any bytes written to the file are saved to the SD card. */ + void flush() { + FatFile::sync(); + } + /** This function reports if the current file is a directory or not. + * \return true if the file is a directory. + */ + bool isDirectory() { + return isDir(); + } + /** No longer implemented due to Long File Names. + * + * Use getName(char* name, size_t size). + * \return a pointer to replacement suggestion. + */ + const char* name() const { + return "use getName()"; + } + /** Return the next available byte without consuming it. + * + * \return The byte if no error and not at eof else -1; + */ + int peek() { + return FatFile::peek(); + } + /** \return the current file position. */ + uint32_t position() { + return curPosition(); + } + /** Opens the next file or folder in a directory. + * + * \param[in] oflag open oflag flags. + * \return a File object. + */ + File openNextFile(oflag_t oflag = O_RDONLY) { + File tmpFile; + tmpFile.openNext(this, oflag); + return tmpFile; + } + /** Read the next byte from a file. + * + * \return For success return the next byte in the file as an int. + * If an error occurs or end of file is reached return -1. + */ + int read() { + return FatFile::read(); + } + /** Rewind a file if it is a directory */ + void rewindDirectory() { + if (isDir()) { + rewind(); + } + } + /** + * Seek to a new position in the file, which must be between + * 0 and the size of the file (inclusive). + * + * \param[in] pos the new file position. + * \return true for success else false. + */ + bool seek(uint32_t pos) { + return seekSet(pos); + } + /** \return the file's size. */ + uint32_t size() { + return fileSize(); + } + /** Write a byte to a file. Required by the Arduino Print class. + * \param[in] b the byte to be written. + * Use getWriteError to check for errors. + * \return 1 for success and 0 for failure. + */ + size_t write(uint8_t b) { + return FatFile::write(b); + } + /** Write data to an open file. Form required by Print. + * + * \note Data is moved to the cache but may not be written to the + * storage device until sync() is called. + * + * \param[in] buf Pointer to the location of the data to be written. + * + * \param[in] size Number of bytes to write. + * + * \return For success write() returns the number of bytes written, always + * \a nbyte. If an error occurs, write() returns -1. Possible errors + * include write() is called before a file has been opened, write is called + * for a read-only file, device is full, a corrupt file system or an + * I/O error. + */ + size_t write(const uint8_t *buf, size_t size) { + return FatFile::write(buf, size); + } +}; +#endif // ENABLE_ARDUINO_FEATURES +#endif // ArduinoFiles_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ArduinoStream.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ArduinoStream.h new file mode 100644 index 0000000..a42f400 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ArduinoStream.h @@ -0,0 +1,153 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 ArduinoStream_h +#define ArduinoStream_h +/** + * \file + * \brief ArduinoInStream and ArduinoOutStream classes + */ +#include "FatLibConfig.h" +#if ENABLE_ARDUINO_FEATURES +#include "bufstream.h" +//============================================================================== +/** + * \class ArduinoInStream + * \brief Input stream for Arduino Stream objects + */ +class ArduinoInStream : public ibufstream { + public: + /** + * Constructor + * \param[in] hws hardware stream + * \param[in] buf buffer for input line + * \param[in] size size of input buffer + */ + ArduinoInStream(Stream &hws, char* buf, size_t size) { + m_hw = &hws; + m_line = buf; + m_size = size; + } + /** read a line. */ + void readline() { + size_t i = 0; + uint32_t t; + m_line[0] = '\0'; + while (!m_hw->available()) { + yield(); + } + + while (1) { + t = millis(); + while (!m_hw->available()) { + if ((millis() - t) > 10) { + goto done; + } + } + if (i >= (m_size - 1)) { + setstate(failbit); + return; + } + m_line[i++] = m_hw->read(); + m_line[i] = '\0'; + } +done: + init(m_line); + } + + protected: + /** Internal - do not use. + * \param[in] off + * \param[in] way + * \return true/false. + */ + bool seekoff(off_type off, seekdir way) { + (void)off; + (void)way; + return false; + } + /** Internal - do not use. + * \param[in] pos + * \return true/false. + */ + bool seekpos(pos_type pos) { + (void)pos; + return false; + } + + private: + char *m_line; + size_t m_size; + Stream* m_hw; +}; +//============================================================================== +/** + * \class ArduinoOutStream + * \brief Output stream for Arduino Print objects + */ +class ArduinoOutStream : public ostream { + public: + /** constructor + * + * \param[in] pr Print object for this ArduinoOutStream. + */ + explicit ArduinoOutStream(Print& pr) : m_pr(&pr) {} + + protected: + /// @cond SHOW_PROTECTED + /** + * Internal do not use + * \param[in] c + */ + void putch(char c) { + if (c == '\n') { + m_pr->write('\r'); + } + m_pr->write(c); + } + void putstr(const char* str) { + m_pr->write(str); + } + bool seekoff(off_type off, seekdir way) { + (void)off; + (void)way; + return false; + } + bool seekpos(pos_type pos) { + (void)pos; + return false; + } + bool sync() { + return true; + } + pos_type tellpos() { + return 0; + } + /// @endcond + private: + ArduinoOutStream() {} + Print* m_pr; +}; +#endif // ENABLE_ARDUINO_FEATURES +#endif // ArduinoStream_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/BaseBlockDriver.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/BaseBlockDriver.h new file mode 100644 index 0000000..c824a18 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/BaseBlockDriver.h @@ -0,0 +1,80 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 BaseBlockDriver_h +#define BaseBlockDriver_h +#include "FatLibConfig.h" +/** + * \class BaseBlockDriver + * \brief Base block driver. + */ +class BaseBlockDriver { + public: + /** + * Read a 512 byte block from an SD card. + * + * \param[in] block Logical block to be read. + * \param[out] dst Pointer to the location that will receive the data. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + virtual bool readBlock(uint32_t block, uint8_t* dst) = 0; + /** End multi-block transfer and go to idle state. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + virtual bool syncBlocks() = 0; + /** + * Writes a 512 byte block to an SD card. + * + * \param[in] block Logical block to be written. + * \param[in] src Pointer to the location of the data to be written. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + virtual bool writeBlock(uint32_t block, const uint8_t* src) = 0; +#if USE_MULTI_BLOCK_IO + /** + * Read multiple 512 byte blocks from an SD card. + * + * \param[in] block Logical block to be read. + * \param[in] nb Number of blocks to be read. + * \param[out] dst Pointer to the location that will receive the data. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + virtual bool readBlocks(uint32_t block, uint8_t* dst, size_t nb) = 0; + /** + * Write multiple 512 byte blocks to an SD card. + * + * \param[in] block Logical block to be written. + * \param[in] nb Number of blocks to be written. + * \param[in] src Pointer to the location of the data to be written. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + virtual bool writeBlocks(uint32_t block, const uint8_t* src, size_t nb) = 0; +#endif // USE_MULTI_BLOCK_IO +}; +#endif // BaseBlockDriver_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatApiConstants.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatApiConstants.h new file mode 100644 index 0000000..52f4225 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatApiConstants.h @@ -0,0 +1,87 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 FatApiConstants_h +#define FatApiConstants_h +#include "SdFatConfig.h" + +#if USE_FCNTL_H +#include +/* values for GNU Arm Embedded Toolchain. + * O_RDONLY: 0x0 + * O_WRONLY: 0x1 + * O_RDWR: 0x2 + * O_ACCMODE: 0x3 + * O_APPEND: 0x8 + * O_CREAT: 0x200 + * O_TRUNC: 0x400 + * O_EXCL: 0x800 + * O_SYNC: 0x2000 + * O_NONBLOCK: 0x4000 + */ +/** Use O_NONBLOCK for open at EOF */ +#define O_AT_END O_NONBLOCK ///< Open at EOF. +typedef int oflag_t; +#else // USE_FCNTL_H +#define O_RDONLY 0X00 ///< Open for reading only. +#define O_WRONLY 0X01 ///< Open for writing only. +#define O_RDWR 0X02 ///< Open for reading and writing. +#define O_AT_END 0X04 ///< Open at EOF. +#define O_APPEND 0X08 ///< Set append mode. +#define O_CREAT 0x10 ///< Create file if it does not exist. +#define O_TRUNC 0x20 ///< Truncate file to zero length. +#define O_EXCL 0x40 ///< Fail if the file exists. +#define O_SYNC 0x80 ///< Synchronized write I/O operations. + +#define O_ACCMODE (O_RDONLY|O_WRONLY|O_RDWR) ///< Mask for access mode. +typedef uint8_t oflag_t; +#endif // USE_FCNTL_H + +#define O_READ O_RDONLY +#define O_WRITE O_WRONLY + +inline bool isWriteMode(oflag_t oflag) { + oflag &= O_ACCMODE; + return oflag == O_WRONLY || oflag == O_RDWR; +} + +// FatFile class static and const definitions +// flags for ls() +/** ls() flag for list all files including hidden. */ +const uint8_t LS_A = 1; +/** ls() flag to print modify. date */ +const uint8_t LS_DATE = 2; +/** ls() flag to print file size. */ +const uint8_t LS_SIZE = 4; +/** ls() flag for recursive list of subdirectories */ +const uint8_t LS_R = 8; + +// flags for timestamp +/** set the file's last access date */ +const uint8_t T_ACCESS = 1; +/** set the file's creation date and time */ +const uint8_t T_CREATE = 2; +/** Set the file's write date and time */ +const uint8_t T_WRITE = 4; +#endif // FatApiConstants_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFile.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFile.cpp new file mode 100644 index 0000000..7342e36 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFile.cpp @@ -0,0 +1,1530 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#include "FatFile.h" +#include "FatFileSystem.h" +//------------------------------------------------------------------------------ +// Pointer to cwd directory. +FatFile* FatFile::m_cwd = 0; +// Callback function for date/time. +void (*FatFile::m_dateTime)(uint16_t* date, uint16_t* time) = 0; +//------------------------------------------------------------------------------ +// Add a cluster to a file. +bool FatFile::addCluster() { + m_flags |= F_FILE_DIR_DIRTY; + return m_vol->allocateCluster(m_curCluster, &m_curCluster); +} +//------------------------------------------------------------------------------ +// Add a cluster to a directory file and zero the cluster. +// Return with first block of cluster in the cache. +bool FatFile::addDirCluster() { + uint32_t block; + cache_t* pc; + + if (isRootFixed()) { + DBG_FAIL_MACRO; + goto fail; + } + // max folder size + if (m_curPosition >= 512UL*4095) { + DBG_FAIL_MACRO; + goto fail; + } + if (!addCluster()) { + DBG_FAIL_MACRO; + goto fail; + } + block = m_vol->clusterFirstBlock(m_curCluster); + pc = m_vol->cacheFetchData(block, FatCache::CACHE_RESERVE_FOR_WRITE); + if (!pc) { + DBG_FAIL_MACRO; + goto fail; + } + memset(pc, 0, 512); + // zero rest of clusters + for (uint8_t i = 1; i < m_vol->blocksPerCluster(); i++) { + if (!m_vol->writeBlock(block + i, pc->data)) { + DBG_FAIL_MACRO; + goto fail; + } + } + // Set position to EOF to avoid inconsistent curCluster/curPosition. + m_curPosition += 512UL*m_vol->blocksPerCluster(); + return true; + +fail: + return false; +} +//------------------------------------------------------------------------------ +// cache a file's directory entry +// return pointer to cached entry or null for failure +dir_t* FatFile::cacheDirEntry(uint8_t action) { + cache_t* pc; + pc = m_vol->cacheFetchData(m_dirBlock, action); + if (!pc) { + DBG_FAIL_MACRO; + goto fail; + } + return pc->dir + (m_dirIndex & 0XF); + +fail: + return 0; +} +//------------------------------------------------------------------------------ +bool FatFile::close() { + bool rtn = sync(); + m_attr = FILE_ATTR_CLOSED; + return rtn; +} +//------------------------------------------------------------------------------ +bool FatFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock) { + // error if no blocks + if (m_firstCluster == 0) { + DBG_FAIL_MACRO; + goto fail; + } + for (uint32_t c = m_firstCluster; ; c++) { + uint32_t next; + int8_t fg = m_vol->fatGet(c, &next); + if (fg < 0) { + DBG_FAIL_MACRO; + goto fail; + } + // check for contiguous + if (fg == 0 || next != (c + 1)) { + // error if not end of chain + if (fg) { + DBG_FAIL_MACRO; + goto fail; + } + *bgnBlock = m_vol->clusterFirstBlock(m_firstCluster); + *endBlock = m_vol->clusterFirstBlock(c) + + m_vol->blocksPerCluster() - 1; + return true; + } + } + +fail: + return false; +} +//------------------------------------------------------------------------------ +bool FatFile::createContiguous(FatFile* dirFile, + const char* path, uint32_t size) { + uint32_t count; + + // don't allow zero length file + if (size == 0) { + DBG_FAIL_MACRO; + goto fail; + } + if (!open(dirFile, path, O_RDWR | O_CREAT | O_EXCL)) { + DBG_FAIL_MACRO; + goto fail; + } + // calculate number of clusters needed + count = ((size - 1) >> (m_vol->clusterSizeShift() + 9)) + 1; + + // allocate clusters + if (!m_vol->allocContiguous(count, &m_firstCluster)) { + remove(); + DBG_FAIL_MACRO; + goto fail; + } + m_fileSize = size; + + // insure sync() will update dir entry + m_flags |= F_FILE_DIR_DIRTY; + return sync(); + +fail: + return false; +} +//------------------------------------------------------------------------------ +bool FatFile::dirEntry(dir_t* dst) { + dir_t* dir; + // Make sure fields on device are correct. + if (!sync()) { + DBG_FAIL_MACRO; + goto fail; + } + // read entry + dir = cacheDirEntry(FatCache::CACHE_FOR_READ); + if (!dir) { + DBG_FAIL_MACRO; + goto fail; + } + // copy to caller's struct + memcpy(dst, dir, sizeof(dir_t)); + return true; + +fail: + return false; +} +//------------------------------------------------------------------------------ +uint8_t FatFile::dirName(const dir_t* dir, char* name) { + uint8_t j = 0; + uint8_t lcBit = DIR_NT_LC_BASE; + for (uint8_t i = 0; i < 11; i++) { + if (dir->name[i] == ' ') { + continue; + } + if (i == 8) { + // Position bit for extension. + lcBit = DIR_NT_LC_EXT; + name[j++] = '.'; + } + char c = dir->name[i]; + if ('A' <= c && c <= 'Z' && (lcBit & dir->reservedNT)) { + c += 'a' - 'A'; + } + name[j++] = c; + } + name[j] = 0; + return j; +} + +//------------------------------------------------------------------------------ +uint32_t FatFile::dirSize() { + int8_t fg; + if (!isDir()) { + return 0; + } + if (isRootFixed()) { + return 32*m_vol->rootDirEntryCount(); + } + uint16_t n = 0; + uint32_t c = isRoot32() ? m_vol->rootDirStart() : m_firstCluster; + do { + fg = m_vol->fatGet(c, &c); + if (fg < 0 || n > 4095) { + return 0; + } + n += m_vol->blocksPerCluster(); + } while (fg); + return 512UL*n; +} +//------------------------------------------------------------------------------ +int16_t FatFile::fgets(char* str, int16_t num, char* delim) { + char ch; + int16_t n = 0; + int16_t r = -1; + while ((n + 1) < num && (r = read(&ch, 1)) == 1) { + // delete CR + if (ch == '\r') { + continue; + } + str[n++] = ch; + if (!delim) { + if (ch == '\n') { + break; + } + } else { + if (strchr(delim, ch)) { + break; + } + } + } + if (r < 0) { + // read error + return -1; + } + str[n] = '\0'; + return n; +} +//------------------------------------------------------------------------------ +void FatFile::getpos(FatPos_t* pos) { + pos->position = m_curPosition; + pos->cluster = m_curCluster; +} +//------------------------------------------------------------------------------ +bool FatFile::mkdir(FatFile* parent, const char* path, bool pFlag) { + fname_t fname; + FatFile tmpDir; + + if (isOpen() || !parent->isDir()) { + DBG_FAIL_MACRO; + goto fail; + } + if (isDirSeparator(*path)) { + while (isDirSeparator(*path)) { + path++; + } + if (!tmpDir.openRoot(parent->m_vol)) { + DBG_FAIL_MACRO; + goto fail; + } + parent = &tmpDir; + } + while (1) { + if (!parsePathName(path, &fname, &path)) { + DBG_FAIL_MACRO; + goto fail; + } + if (!*path) { + break; + } + if (!open(parent, &fname, O_RDONLY)) { + if (!pFlag || !mkdir(parent, &fname)) { + DBG_FAIL_MACRO; + goto fail; + } + } + tmpDir = *this; + parent = &tmpDir; + close(); + } + return mkdir(parent, &fname); + +fail: + return false; +} +//------------------------------------------------------------------------------ +bool FatFile::mkdir(FatFile* parent, fname_t* fname) { + uint32_t block; + dir_t dot; + dir_t* dir; + cache_t* pc; + + if (!parent->isDir()) { + DBG_FAIL_MACRO; + goto fail; + } + // create a normal file + if (!open(parent, fname, O_RDWR | O_CREAT | O_EXCL)) { + DBG_FAIL_MACRO; + goto fail; + } + // convert file to directory + m_flags = F_READ; + m_attr = FILE_ATTR_SUBDIR; + + // allocate and zero first cluster + if (!addDirCluster()) { + DBG_FAIL_MACRO; + goto fail; + } + m_firstCluster = m_curCluster; + // Set to start of dir + rewind(); + // force entry to device + if (!sync()) { + DBG_FAIL_MACRO; + goto fail; + } + // cache entry - should already be in cache due to sync() call + dir = cacheDirEntry(FatCache::CACHE_FOR_WRITE); + if (!dir) { + DBG_FAIL_MACRO; + goto fail; + } + // change directory entry attribute + dir->attributes = DIR_ATT_DIRECTORY; + + // make entry for '.' + memcpy(&dot, dir, sizeof(dot)); + dot.name[0] = '.'; + for (uint8_t i = 1; i < 11; i++) { + dot.name[i] = ' '; + } + + // cache block for '.' and '..' + block = m_vol->clusterFirstBlock(m_firstCluster); + pc = m_vol->cacheFetchData(block, FatCache::CACHE_FOR_WRITE); + if (!pc) { + DBG_FAIL_MACRO; + goto fail; + } + // copy '.' to block + memcpy(&pc->dir[0], &dot, sizeof(dot)); + // make entry for '..' + dot.name[1] = '.'; + dot.firstClusterLow = parent->m_firstCluster & 0XFFFF; + dot.firstClusterHigh = parent->m_firstCluster >> 16; + // copy '..' to block + memcpy(&pc->dir[1], &dot, sizeof(dot)); + // write first block + return m_vol->cacheSync(); + +fail: + return false; +} +//------------------------------------------------------------------------------ +bool FatFile::open(FatFileSystem* fs, const char* path, oflag_t oflag) { + return open(fs->vwd(), path, oflag); +} +//------------------------------------------------------------------------------ +bool FatFile::open(FatFile* dirFile, const char* path, oflag_t oflag) { + FatFile tmpDir; + fname_t fname; + + // error if already open + if (isOpen() || !dirFile->isDir()) { + DBG_FAIL_MACRO; + goto fail; + } + if (isDirSeparator(*path)) { + while (isDirSeparator(*path)) { + path++; + } + if (*path == 0) { + return openRoot(dirFile->m_vol); + } + if (!tmpDir.openRoot(dirFile->m_vol)) { + DBG_FAIL_MACRO; + goto fail; + } + dirFile = &tmpDir; + } + while (1) { + if (!parsePathName(path, &fname, &path)) { + DBG_FAIL_MACRO; + goto fail; + } + if (*path == 0) { + break; + } + if (!open(dirFile, &fname, O_RDONLY)) { + DBG_FAIL_MACRO; + goto fail; + } + tmpDir = *this; + dirFile = &tmpDir; + close(); + } + return open(dirFile, &fname, oflag); + +fail: + return false; +} +//------------------------------------------------------------------------------ +bool FatFile::open(FatFile* dirFile, uint16_t index, oflag_t oflag) { + uint8_t chksum = 0; + uint8_t lfnOrd = 0; + dir_t* dir; + ldir_t*ldir; + + // Error if already open. + if (isOpen() || !dirFile->isDir()) { + DBG_FAIL_MACRO; + goto fail; + } + // Don't open existing file if O_EXCL - user call error. + if (oflag & O_EXCL) { + DBG_FAIL_MACRO; + goto fail; + } + if (index) { + // Check for LFN. + if (!dirFile->seekSet(32UL*(index -1))) { + DBG_FAIL_MACRO; + goto fail; + } + ldir = reinterpret_cast(dirFile->readDirCache()); + if (!ldir) { + DBG_FAIL_MACRO; + goto fail; + } + if (ldir->attr == DIR_ATT_LONG_NAME) { + if (1 == (ldir->ord & 0X1F)) { + chksum = ldir->chksum; + // Use largest possible number. + lfnOrd = index > 20 ? 20 : index; + } + } + } else { + dirFile->rewind(); + } + // read entry into cache + dir = dirFile->readDirCache(); + if (!dir) { + DBG_FAIL_MACRO; + goto fail; + } + // error if empty slot or '.' or '..' + if (dir->name[0] == DIR_NAME_DELETED || + dir->name[0] == DIR_NAME_FREE || + dir->name[0] == '.') { + DBG_FAIL_MACRO; + goto fail; + } + if (lfnOrd && chksum != lfnChecksum(dir->name)) { + DBG_FAIL_MACRO; + goto fail; + } + // open cached entry + if (!openCachedEntry(dirFile, index, oflag, lfnOrd)) { + DBG_FAIL_MACRO; + goto fail; + } + return true; + +fail: + return false; +} +//------------------------------------------------------------------------------ +// open a cached directory entry. + +bool FatFile::openCachedEntry(FatFile* dirFile, uint16_t dirIndex, + oflag_t oflag, uint8_t lfnOrd) { + uint32_t firstCluster; + memset(this, 0, sizeof(FatFile)); + // location of entry in cache + m_vol = dirFile->m_vol; + m_dirIndex = dirIndex; + m_dirCluster = dirFile->m_firstCluster; + dir_t* dir = &m_vol->cacheAddress()->dir[0XF & dirIndex]; + + // Must be file or subdirectory. + if (!DIR_IS_FILE_OR_SUBDIR(dir)) { + DBG_FAIL_MACRO; + goto fail; + } + m_attr = dir->attributes & FILE_ATTR_COPY; + if (DIR_IS_FILE(dir)) { + m_attr |= FILE_ATTR_FILE; + } + m_lfnOrd = lfnOrd; + + switch (oflag & O_ACCMODE) { + case O_RDONLY: + if (oflag & O_TRUNC) { + DBG_FAIL_MACRO; + goto fail; + } + m_flags = F_READ; + break; + + case O_RDWR: + m_flags = F_READ | F_WRITE; + break; + + case O_WRONLY: + m_flags = F_WRITE; + break; + + default: + DBG_FAIL_MACRO; + goto fail; + } + + if (m_flags & F_WRITE) { + if (isSubDir() || isReadOnly()) { + DBG_FAIL_MACRO; + goto fail; + } + } + + m_flags |= (oflag & O_APPEND ? F_APPEND : 0) | (oflag & O_SYNC ? F_SYNC : 0); + + m_dirBlock = m_vol->cacheBlockNumber(); + + // copy first cluster number for directory fields + firstCluster = ((uint32_t)dir->firstClusterHigh << 16) + | dir->firstClusterLow; + + if (oflag & O_TRUNC) { + if (firstCluster && !m_vol->freeChain(firstCluster)) { + DBG_FAIL_MACRO; + goto fail; + } + // need to update directory entry + m_flags |= F_FILE_DIR_DIRTY; + } else { + m_firstCluster = firstCluster; + m_fileSize = dir->fileSize; + } + if ((oflag & O_AT_END) && !seekSet(m_fileSize)) { + DBG_FAIL_MACRO; + goto fail; + } + return true; + +fail: + m_attr = FILE_ATTR_CLOSED; + return false; +} +//------------------------------------------------------------------------------ +bool FatFile::openCwd() { + if (!cwd()) { + DBG_FAIL_MACRO; + return false; + } + *this = *cwd(); + rewind(); + return true; +} +//------------------------------------------------------------------------------ +bool FatFile::openNext(FatFile* dirFile, oflag_t oflag) { + uint8_t chksum = 0; + ldir_t* ldir; + uint8_t lfnOrd = 0; + uint16_t index; + + // Check for not open and valid directory.. + if (isOpen() || !dirFile->isDir() || (dirFile->curPosition() & 0X1F)) { + DBG_FAIL_MACRO; + goto fail; + } + while (1) { + // read entry into cache + index = dirFile->curPosition()/32; + dir_t* dir = dirFile->readDirCache(); + if (!dir) { + if (dirFile->getError()) { + DBG_FAIL_MACRO; + } + goto fail; + } + // done if last entry + if (dir->name[0] == DIR_NAME_FREE) { + goto fail; + } + // skip empty slot or '.' or '..' + if (dir->name[0] == '.' || dir->name[0] == DIR_NAME_DELETED) { + lfnOrd = 0; + } else if (DIR_IS_FILE_OR_SUBDIR(dir)) { + if (lfnOrd && chksum != lfnChecksum(dir->name)) { + DBG_FAIL_MACRO; + goto fail; + } + if (!openCachedEntry(dirFile, index, oflag, lfnOrd)) { + DBG_FAIL_MACRO; + goto fail; + } + return true; + } else if (DIR_IS_LONG_NAME(dir)) { + ldir = reinterpret_cast(dir); + if (ldir->ord & LDIR_ORD_LAST_LONG_ENTRY) { + lfnOrd = ldir->ord & 0X1F; + chksum = ldir->chksum; + } + } else { + lfnOrd = 0; + } + } + +fail: + return false; +} +#ifndef DOXYGEN_SHOULD_SKIP_THIS +//------------------------------------------------------------------------------ +/** Open a file's parent directory. + * + * \param[in] file Parent of this directory will be opened. Must not be root. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ +bool FatFile::openParent(FatFile* dirFile) { + FatFile dotdot; + uint32_t lbn; + dir_t* dir; + uint32_t ddc; + cache_t* cb; + + if (isOpen() || !dirFile->isOpen()) { + goto fail; + } + if (dirFile->m_dirCluster == 0) { + return openRoot(dirFile->m_vol); + } + lbn = dirFile->m_vol->clusterFirstBlock(dirFile->m_dirCluster); + cb = dirFile->m_vol->cacheFetchData(lbn, FatCache::CACHE_FOR_READ); + if (!cb) { + DBG_FAIL_MACRO; + goto fail; + } + // Point to dir entery for .. + dir = cb->dir + 1; + ddc = dir->firstClusterLow | ((uint32_t)dir->firstClusterHigh << 16); + if (ddc == 0) { + if (!dotdot.openRoot(dirFile->m_vol)) { + DBG_FAIL_MACRO; + goto fail; + } + } else { + memset(&dotdot, 0, sizeof(FatFile)); + dotdot.m_attr = FILE_ATTR_SUBDIR; + dotdot.m_flags = F_READ; + dotdot.m_vol = dirFile->m_vol; + dotdot.m_firstCluster = ddc; + } + uint32_t di; + do { + di = dotdot.curPosition()/32; + dir = dotdot.readDirCache(); + if (!dir) { + DBG_FAIL_MACRO; + goto fail; + } + ddc = dir->firstClusterLow | ((uint32_t)dir->firstClusterHigh << 16); + } while (ddc != dirFile->m_dirCluster); + return open(&dotdot, di, O_RDONLY); + +fail: + return false; +} +#endif // DOXYGEN_SHOULD_SKIP_THIS +//------------------------------------------------------------------------------ +bool FatFile::openRoot(FatVolume* vol) { + // error if file is already open + if (isOpen()) { + DBG_FAIL_MACRO; + goto fail; + } + memset(this, 0, sizeof(FatFile)); + + m_vol = vol; + switch (vol->fatType()) { +#if FAT12_SUPPORT + case 12: +#endif // FAT12_SUPPORT + case 16: + m_attr = FILE_ATTR_ROOT_FIXED; + break; + + case 32: + m_attr = FILE_ATTR_ROOT32; + break; + + default: + DBG_FAIL_MACRO; + goto fail; + } + // read only + m_flags = F_READ; + return true; + +fail: + return false; +} +//------------------------------------------------------------------------------ +int FatFile::peek() { + FatPos_t pos; + getpos(&pos); + int c = read(); + if (c >= 0) { + setpos(&pos); + } + return c; +} +//------------------------------------------------------------------------------ +int FatFile::read(void* buf, size_t nbyte) { + int8_t fg; + uint8_t blockOfCluster = 0; + uint8_t* dst = reinterpret_cast(buf); + uint16_t offset; + size_t toRead; + uint32_t block; // raw device block number + cache_t* pc; + + // error if not open for read + if (!isOpen() || !(m_flags & F_READ)) { + DBG_FAIL_MACRO; + goto fail; + } + + if (isFile()) { + uint32_t tmp32 = m_fileSize - m_curPosition; + if (nbyte >= tmp32) { + nbyte = tmp32; + } + } else if (isRootFixed()) { + uint16_t tmp16 = 32*m_vol->m_rootDirEntryCount - (uint16_t)m_curPosition; + if (nbyte > tmp16) { + nbyte = tmp16; + } + } + toRead = nbyte; + while (toRead) { + size_t n; + offset = m_curPosition & 0X1FF; // offset in block + if (isRootFixed()) { + block = m_vol->rootDirStart() + (m_curPosition >> 9); + } else { + blockOfCluster = m_vol->blockOfCluster(m_curPosition); + if (offset == 0 && blockOfCluster == 0) { + // start of new cluster + if (m_curPosition == 0) { + // use first cluster in file + m_curCluster = isRoot32() ? m_vol->rootDirStart() : m_firstCluster; + } else { + // get next cluster from FAT + fg = m_vol->fatGet(m_curCluster, &m_curCluster); + if (fg < 0) { + DBG_FAIL_MACRO; + goto fail; + } + if (fg == 0) { + if (isDir()) { + break; + } + DBG_FAIL_MACRO; + goto fail; + } + } + } + block = m_vol->clusterFirstBlock(m_curCluster) + blockOfCluster; + } + if (offset != 0 || toRead < 512 || block == m_vol->cacheBlockNumber()) { + // amount to be read from current block + n = 512 - offset; + if (n > toRead) { + n = toRead; + } + // read block to cache and copy data to caller + pc = m_vol->cacheFetchData(block, FatCache::CACHE_FOR_READ); + if (!pc) { + DBG_FAIL_MACRO; + goto fail; + } + uint8_t* src = pc->data + offset; + memcpy(dst, src, n); +#if USE_MULTI_BLOCK_IO + } else if (toRead >= 1024) { + size_t nb = toRead >> 9; + if (!isRootFixed()) { + uint8_t mb = m_vol->blocksPerCluster() - blockOfCluster; + if (mb < nb) { + nb = mb; + } + } + n = 512*nb; + if (m_vol->cacheBlockNumber() <= block + && block < (m_vol->cacheBlockNumber() + nb)) { + // flush cache if a block is in the cache + if (!m_vol->cacheSyncData()) { + DBG_FAIL_MACRO; + goto fail; + } + } + if (!m_vol->readBlocks(block, dst, nb)) { + DBG_FAIL_MACRO; + goto fail; + } +#endif // USE_MULTI_BLOCK_IO + } else { + // read single block + n = 512; + if (!m_vol->readBlock(block, dst)) { + DBG_FAIL_MACRO; + goto fail; + } + } + dst += n; + m_curPosition += n; + toRead -= n; + } + return nbyte - toRead; + +fail: + m_error |= READ_ERROR; + return -1; +} +//------------------------------------------------------------------------------ +int8_t FatFile::readDir(dir_t* dir) { + int16_t n; + // if not a directory file or miss-positioned return an error + if (!isDir() || (0X1F & m_curPosition)) { + return -1; + } + + while (1) { + n = read(dir, sizeof(dir_t)); + if (n != sizeof(dir_t)) { + return n == 0 ? 0 : -1; + } + // last entry if DIR_NAME_FREE + if (dir->name[0] == DIR_NAME_FREE) { + return 0; + } + // skip empty entries and entry for . and .. + if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') { + continue; + } + // return if normal file or subdirectory + if (DIR_IS_FILE_OR_SUBDIR(dir)) { + return n; + } + } +} +//------------------------------------------------------------------------------ +// Read next directory entry into the cache +// Assumes file is correctly positioned +dir_t* FatFile::readDirCache(bool skipReadOk) { +// uint8_t b; + uint8_t i = (m_curPosition >> 5) & 0XF; + + if (i == 0 || !skipReadOk) { + int8_t n = read(&n, 1); + if (n != 1) { + if (n != 0) { + DBG_FAIL_MACRO; + } + goto fail; + } + m_curPosition += 31; + } else { + m_curPosition += 32; + } + // return pointer to entry + return m_vol->cacheAddress()->dir + i; + +fail: + return 0; +} +//------------------------------------------------------------------------------ +bool FatFile::remove(FatFile* dirFile, const char* path) { + FatFile file; + if (!file.open(dirFile, path, O_WRONLY)) { + DBG_FAIL_MACRO; + goto fail; + } + return file.remove(); + +fail: + return false; +} +//------------------------------------------------------------------------------ +bool FatFile::rename(FatFile* dirFile, const char* newPath) { + dir_t entry; + uint32_t dirCluster = 0; + FatFile file; + FatFile oldFile; + cache_t* pc; + dir_t* dir; + + // Must be an open file or subdirectory. + if (!(isFile() || isSubDir())) { + DBG_FAIL_MACRO; + goto fail; + } + // Can't rename LFN in 8.3 mode. + if (!USE_LONG_FILE_NAMES && isLFN()) { + DBG_FAIL_MACRO; + goto fail; + } + // Can't move file to new volume. + if (m_vol != dirFile->m_vol) { + DBG_FAIL_MACRO; + goto fail; + } + // sync() and cache directory entry + sync(); + oldFile = *this; + dir = cacheDirEntry(FatCache::CACHE_FOR_READ); + if (!dir) { + DBG_FAIL_MACRO; + goto fail; + } + // save directory entry + memcpy(&entry, dir, sizeof(entry)); + // make directory entry for new path + if (isFile()) { + if (!file.open(dirFile, newPath, O_WRONLY | O_CREAT | O_EXCL)) { + DBG_FAIL_MACRO; + goto fail; + } + } else { + // don't create missing path prefix components + if (!file.mkdir(dirFile, newPath, false)) { + DBG_FAIL_MACRO; + goto fail; + } + // save cluster containing new dot dot + dirCluster = file.m_firstCluster; + } + // change to new directory entry + + m_dirBlock = file.m_dirBlock; + m_dirIndex = file.m_dirIndex; + m_lfnOrd = file.m_lfnOrd; + m_dirCluster = file.m_dirCluster; + // mark closed to avoid possible destructor close call + file.m_attr = FILE_ATTR_CLOSED; + + // cache new directory entry + dir = cacheDirEntry(FatCache::CACHE_FOR_WRITE); + if (!dir) { + DBG_FAIL_MACRO; + goto fail; + } + // copy all but name and name flags to new directory entry + memcpy(&dir->creationTimeTenths, &entry.creationTimeTenths, + sizeof(entry) - sizeof(dir->name) - 2); + dir->attributes = entry.attributes; + + // update dot dot if directory + if (dirCluster) { + // get new dot dot + uint32_t block = m_vol->clusterFirstBlock(dirCluster); + pc = m_vol->cacheFetchData(block, FatCache::CACHE_FOR_READ); + if (!pc) { + DBG_FAIL_MACRO; + goto fail; + } + memcpy(&entry, &pc->dir[1], sizeof(entry)); + + // free unused cluster + if (!m_vol->freeChain(dirCluster)) { + DBG_FAIL_MACRO; + goto fail; + } + // store new dot dot + block = m_vol->clusterFirstBlock(m_firstCluster); + pc = m_vol->cacheFetchData(block, FatCache::CACHE_FOR_WRITE); + if (!pc) { + DBG_FAIL_MACRO; + goto fail; + } + memcpy(&pc->dir[1], &entry, sizeof(entry)); + } + // Remove old directory entry; + oldFile.m_firstCluster = 0; + oldFile.m_flags = F_WRITE; + oldFile.m_attr = FILE_ATTR_FILE; + if (!oldFile.remove()) { + DBG_FAIL_MACRO; + goto fail; + } + return m_vol->cacheSync(); + +fail: + return false; +} +//------------------------------------------------------------------------------ +bool FatFile::rmdir() { + // must be open subdirectory + if (!isSubDir() || (!USE_LONG_FILE_NAMES && isLFN())) { + DBG_FAIL_MACRO; + goto fail; + } + rewind(); + + // make sure directory is empty + while (1) { + dir_t* dir = readDirCache(true); + if (!dir) { + // EOF if no error. + if (!getError()) { + break; + } + DBG_FAIL_MACRO; + goto fail; + } + // done if past last used entry + if (dir->name[0] == DIR_NAME_FREE) { + break; + } + // skip empty slot, '.' or '..' + if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') { + continue; + } + // error not empty + if (DIR_IS_FILE_OR_SUBDIR(dir)) { + DBG_FAIL_MACRO; + goto fail; + } + } + // convert empty directory to normal file for remove + m_attr = FILE_ATTR_FILE; + m_flags |= F_WRITE; + return remove(); + +fail: + return false; +} +//------------------------------------------------------------------------------ +bool FatFile::rmRfStar() { + uint16_t index; + FatFile f; + if (!isDir()) { + DBG_FAIL_MACRO; + goto fail; + } + rewind(); + while (1) { + // remember position + index = m_curPosition/32; + + dir_t* dir = readDirCache(); + if (!dir) { + // At EOF if no error. + if (!getError()) { + break; + } + DBG_FAIL_MACRO; + goto fail; + } + // done if past last entry + if (dir->name[0] == DIR_NAME_FREE) { + break; + } + + // skip empty slot or '.' or '..' + if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') { + continue; + } + + // skip if part of long file name or volume label in root + if (!DIR_IS_FILE_OR_SUBDIR(dir)) { + continue; + } + + if (!f.open(this, index, O_RDONLY)) { + DBG_FAIL_MACRO; + goto fail; + } + if (f.isSubDir()) { + // recursively delete + if (!f.rmRfStar()) { + DBG_FAIL_MACRO; + goto fail; + } + } else { + // ignore read-only + f.m_flags |= F_WRITE; + if (!f.remove()) { + DBG_FAIL_MACRO; + goto fail; + } + } + // position to next entry if required + if (m_curPosition != (32UL*(index + 1))) { + if (!seekSet(32UL*(index + 1))) { + DBG_FAIL_MACRO; + goto fail; + } + } + } + // don't try to delete root + if (!isRoot()) { + if (!rmdir()) { + DBG_FAIL_MACRO; + goto fail; + } + } + return true; + +fail: + return false; +} +//------------------------------------------------------------------------------ +bool FatFile::seekSet(uint32_t pos) { + uint32_t nCur; + uint32_t nNew; + uint32_t tmp = m_curCluster; + // error if file not open + if (!isOpen()) { + DBG_FAIL_MACRO; + goto fail; + } + // Optimize O_APPEND writes. + if (pos == m_curPosition) { + return true; + } + if (pos == 0) { + // set position to start of file + m_curCluster = 0; + goto done; + } + if (isFile()) { + if (pos > m_fileSize) { + DBG_FAIL_MACRO; + goto fail; + } + } else if (isRootFixed()) { + if (pos <= 32*m_vol->rootDirEntryCount()) { + goto done; + } + DBG_FAIL_MACRO; + goto fail; + } + // calculate cluster index for cur and new position + nCur = (m_curPosition - 1) >> (m_vol->clusterSizeShift() + 9); + nNew = (pos - 1) >> (m_vol->clusterSizeShift() + 9); + + if (nNew < nCur || m_curPosition == 0) { + // must follow chain from first cluster + m_curCluster = isRoot32() ? m_vol->rootDirStart() : m_firstCluster; + } else { + // advance from curPosition + nNew -= nCur; + } + while (nNew--) { + if (m_vol->fatGet(m_curCluster, &m_curCluster) <= 0) { + DBG_FAIL_MACRO; + goto fail; + } + } + +done: + m_curPosition = pos; + return true; + +fail: + m_curCluster = tmp; + return false; +} +//------------------------------------------------------------------------------ +void FatFile::setpos(FatPos_t* pos) { + m_curPosition = pos->position; + m_curCluster = pos->cluster; +} +//------------------------------------------------------------------------------ +bool FatFile::sync() { + if (!isOpen()) { + return true; + } + if (m_flags & F_FILE_DIR_DIRTY) { + dir_t* dir = cacheDirEntry(FatCache::CACHE_FOR_WRITE); + // check for deleted by another open file object + if (!dir || dir->name[0] == DIR_NAME_DELETED) { + DBG_FAIL_MACRO; + goto fail; + } + // do not set filesize for dir files + if (isFile()) { + dir->fileSize = m_fileSize; + } + + // update first cluster fields + dir->firstClusterLow = m_firstCluster & 0XFFFF; + dir->firstClusterHigh = m_firstCluster >> 16; + + // set modify time if user supplied a callback date/time function + if (m_dateTime) { + m_dateTime(&dir->lastWriteDate, &dir->lastWriteTime); + dir->lastAccessDate = dir->lastWriteDate; + } + // clear directory dirty + m_flags &= ~F_FILE_DIR_DIRTY; + } + if (m_vol->cacheSync()) { + return true; + } + DBG_FAIL_MACRO; + +fail: + m_error |= WRITE_ERROR; + return false; +} +//------------------------------------------------------------------------------ +bool FatFile::timestamp(FatFile* file) { + dir_t* dir; + dir_t srcDir; + + // most be files get timestamps + if (!isFile() || !file->isFile() || !file->dirEntry(&srcDir)) { + DBG_FAIL_MACRO; + goto fail; + } + // update directory fields + if (!sync()) { + DBG_FAIL_MACRO; + goto fail; + } + dir = cacheDirEntry(FatCache::CACHE_FOR_WRITE); + if (!dir) { + DBG_FAIL_MACRO; + goto fail; + } + // copy timestamps + dir->lastAccessDate = srcDir.lastAccessDate; + dir->creationDate = srcDir.creationDate; + dir->creationTime = srcDir.creationTime; + dir->creationTimeTenths = srcDir.creationTimeTenths; + dir->lastWriteDate = srcDir.lastWriteDate; + dir->lastWriteTime = srcDir.lastWriteTime; + + // write back entry + return m_vol->cacheSync(); + +fail: + return false; +} +//------------------------------------------------------------------------------ +bool FatFile::timestamp(uint8_t flags, uint16_t year, uint8_t month, + uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) { + uint16_t dirDate; + uint16_t dirTime; + dir_t* dir; + + if (!isFile() + || year < 1980 + || year > 2107 + || month < 1 + || month > 12 + || day < 1 + || day > 31 + || hour > 23 + || minute > 59 + || second > 59) { + DBG_FAIL_MACRO; + goto fail; + } + // update directory entry + if (!sync()) { + DBG_FAIL_MACRO; + goto fail; + } + dir = cacheDirEntry(FatCache::CACHE_FOR_WRITE); + if (!dir) { + DBG_FAIL_MACRO; + goto fail; + } + dirDate = FAT_DATE(year, month, day); + dirTime = FAT_TIME(hour, minute, second); + if (flags & T_ACCESS) { + dir->lastAccessDate = dirDate; + } + if (flags & T_CREATE) { + dir->creationDate = dirDate; + dir->creationTime = dirTime; + // seems to be units of 1/100 second not 1/10 as Microsoft states + dir->creationTimeTenths = second & 1 ? 100 : 0; + } + if (flags & T_WRITE) { + dir->lastWriteDate = dirDate; + dir->lastWriteTime = dirTime; + } + return m_vol->cacheSync(); + +fail: + return false; +} +//------------------------------------------------------------------------------ +bool FatFile::truncate(uint32_t length) { + uint32_t newPos; + // error if not a normal file or read-only + if (!isFile() || !(m_flags & F_WRITE)) { + DBG_FAIL_MACRO; + goto fail; + } + // error if length is greater than current size + if (length > m_fileSize) { + DBG_FAIL_MACRO; + goto fail; + } + // fileSize and length are zero - nothing to do + if (m_fileSize == 0) { + return true; + } + + // remember position for seek after truncation + newPos = m_curPosition > length ? length : m_curPosition; + + // position to last cluster in truncated file + if (!seekSet(length)) { + DBG_FAIL_MACRO; + goto fail; + } + if (length == 0) { + // free all clusters + if (!m_vol->freeChain(m_firstCluster)) { + DBG_FAIL_MACRO; + goto fail; + } + m_firstCluster = 0; + } else { + uint32_t toFree; + int8_t fg = m_vol->fatGet(m_curCluster, &toFree); + if (fg < 0) { + DBG_FAIL_MACRO; + goto fail; + } + if (fg) { + // free extra clusters + if (!m_vol->freeChain(toFree)) { + DBG_FAIL_MACRO; + goto fail; + } + // current cluster is end of chain + if (!m_vol->fatPutEOC(m_curCluster)) { + DBG_FAIL_MACRO; + goto fail; + } + } + } + m_fileSize = length; + + // need to update directory entry + m_flags |= F_FILE_DIR_DIRTY; + + if (!sync()) { + DBG_FAIL_MACRO; + goto fail; + } + // set file to correct position + return seekSet(newPos); + +fail: + return false; +} +//------------------------------------------------------------------------------ +int FatFile::write(const void* buf, size_t nbyte) { + // convert void* to uint8_t* - must be before goto statements + const uint8_t* src = reinterpret_cast(buf); + cache_t* pc; + uint8_t cacheOption; + // number of bytes left to write - must be before goto statements + size_t nToWrite = nbyte; + size_t n; + // error if not a normal file or is read-only + if (!isFile() || !(m_flags & F_WRITE)) { + DBG_FAIL_MACRO; + goto fail; + } + // seek to end of file if append flag + if ((m_flags & F_APPEND)) { + if (!seekSet(m_fileSize)) { + DBG_FAIL_MACRO; + goto fail; + } + } + // Don't exceed max fileSize. + if (nbyte > (0XFFFFFFFF - m_curPosition)) { + DBG_FAIL_MACRO; + goto fail; + } + while (nToWrite) { + uint8_t blockOfCluster = m_vol->blockOfCluster(m_curPosition); + uint16_t blockOffset = m_curPosition & 0X1FF; + if (blockOfCluster == 0 && blockOffset == 0) { + // start of new cluster + if (m_curCluster != 0) { + int8_t fg = m_vol->fatGet(m_curCluster, &m_curCluster); + if (fg < 0) { + DBG_FAIL_MACRO; + goto fail; + } + if (fg == 0) { + // add cluster if at end of chain + if (!addCluster()) { + DBG_FAIL_MACRO; + goto fail; + } + } + } else { + if (m_firstCluster == 0) { + // allocate first cluster of file + if (!addCluster()) { + DBG_FAIL_MACRO; + goto fail; + } + m_firstCluster = m_curCluster; + } else { + m_curCluster = m_firstCluster; + } + } + } + // block for data write + uint32_t block = m_vol->clusterFirstBlock(m_curCluster) + blockOfCluster; + + if (blockOffset != 0 || nToWrite < 512) { + // partial block - must use cache + // max space in block + n = 512 - blockOffset; + // lesser of space and amount to write + if (n > nToWrite) { + n = nToWrite; + } + + if (blockOffset == 0 && m_curPosition >= m_fileSize) { + // start of new block don't need to read into cache + cacheOption = FatCache::CACHE_RESERVE_FOR_WRITE; + } else { + // rewrite part of block + cacheOption = FatCache::CACHE_FOR_WRITE; + } + pc = m_vol->cacheFetchData(block, cacheOption); + if (!pc) { + DBG_FAIL_MACRO; + goto fail; + } + uint8_t* dst = pc->data + blockOffset; + memcpy(dst, src, n); + if (512 == (n + blockOffset)) { + // Force write if block is full - improves large writes. + if (!m_vol->cacheSyncData()) { + DBG_FAIL_MACRO; + goto fail; + } + } +#if USE_MULTI_BLOCK_IO + } else if (nToWrite >= 1024) { + // use multiple block write command + uint8_t maxBlocks = m_vol->blocksPerCluster() - blockOfCluster; + size_t nb = nToWrite >> 9; + if (nb > maxBlocks) { + nb = maxBlocks; + } + n = 512*nb; + if (m_vol->cacheBlockNumber() <= block + && block < (m_vol->cacheBlockNumber() + nb)) { + // invalidate cache if block is in cache + m_vol->cacheInvalidate(); + } + if (!m_vol->writeBlocks(block, src, nb)) { + DBG_FAIL_MACRO; + goto fail; + } +#endif // USE_MULTI_BLOCK_IO + } else { + // use single block write command + n = 512; + if (m_vol->cacheBlockNumber() == block) { + m_vol->cacheInvalidate(); + } + if (!m_vol->writeBlock(block, src)) { + DBG_FAIL_MACRO; + goto fail; + } + } + m_curPosition += n; + src += n; + nToWrite -= n; + } + if (m_curPosition > m_fileSize) { + // update fileSize and insure sync will update dir entry + m_fileSize = m_curPosition; + m_flags |= F_FILE_DIR_DIRTY; + } else if (m_dateTime) { + // insure sync will update modified date and time + m_flags |= F_FILE_DIR_DIRTY; + } + + if (m_flags & F_SYNC) { + if (!sync()) { + DBG_FAIL_MACRO; + goto fail; + } + } + return nbyte; + +fail: + // return for write error + m_error |= WRITE_ERROR; + return -1; +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFile.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFile.h new file mode 100644 index 0000000..028fd0f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFile.h @@ -0,0 +1,1029 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 FatFile_h +#define FatFile_h +/** + * \file + * \brief FatFile class + */ +// #include +#include +#include +#include +#include "FatLibConfig.h" +#include "FatApiConstants.h" +#include "FatStructs.h" +#include "FatVolume.h" +class FatFileSystem; +//------------------------------------------------------------------------------ +// Stuff to store strings in AVR flash. +#ifdef __AVR__ +#include +#else // __AVR__ +#ifndef PSTR +/** store literal string in flash for ARM */ +#define PSTR(x) (x) +#endif // PSTR +#ifndef pgm_read_byte +/** read 8-bits from flash for ARM */ +#define pgm_read_byte(addr) (*(const unsigned char*)(addr)) +#endif // pgm_read_byte +#ifndef pgm_read_word +/** read 16-bits from flash for ARM */ +#define pgm_read_word(addr) (*(const uint16_t*)(addr)) +#endif // pgm_read_word +#ifndef PROGMEM +/** store in flash for ARM */ +#define PROGMEM +#endif // PROGMEM +#endif // __AVR__ +//------------------------------------------------------------------------------ +/** + * \struct FatPos_t + * \brief Internal type for file position - do not use in user apps. + */ +struct FatPos_t { + /** stream position */ + uint32_t position; + /** cluster for position */ + uint32_t cluster; + FatPos_t() : position(0), cluster(0) {} +}; +//------------------------------------------------------------------------------ +/** Expression for path name separator. */ +#define isDirSeparator(c) ((c) == '/') +//------------------------------------------------------------------------------ +/** + * \struct fname_t + * \brief Internal type for Short File Name - do not use in user apps. + */ +struct fname_t { + /** Flags for base and extension character case and LFN. */ + uint8_t flags; + /** length of Long File Name */ + size_t len; + /** Long File Name start. */ + const char* lfn; + /** position for sequence number */ + uint8_t seqPos; + /** Short File Name */ + uint8_t sfn[11]; +}; +/** Derived from a LFN with loss or conversion of characters. */ +const uint8_t FNAME_FLAG_LOST_CHARS = 0X01; +/** Base-name or extension has mixed case. */ +const uint8_t FNAME_FLAG_MIXED_CASE = 0X02; +/** LFN entries are required for file name. */ +const uint8_t FNAME_FLAG_NEED_LFN = + FNAME_FLAG_LOST_CHARS | FNAME_FLAG_MIXED_CASE; +/** Filename base-name is all lower case */ +const uint8_t FNAME_FLAG_LC_BASE = DIR_NT_LC_BASE; +/** Filename extension is all lower case. */ +const uint8_t FNAME_FLAG_LC_EXT = DIR_NT_LC_EXT; +//============================================================================== +/** + * \class FatFile + * \brief Basic file class. + */ +class FatFile { + public: + /** Create an instance. */ + FatFile() : m_attr(FILE_ATTR_CLOSED), m_error(0) {} + /** Create a file object and open it in the current working directory. + * + * \param[in] path A path with a valid 8.3 DOS name for a file to be opened. + * + * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive + * OR of open flags. see FatFile::open(FatFile*, const char*, oflag_t). + */ + FatFile(const char* path, oflag_t oflag) { + m_attr = FILE_ATTR_CLOSED; + m_error = 0; + open(path, oflag); + } +#if DESTRUCTOR_CLOSES_FILE + ~FatFile() { + if (isOpen()) { + close(); + } + } +#endif // DESTRUCTOR_CLOSES_FILE + +#if ENABLE_ARDUINO_FEATURES + /** List directory contents. + * + * \param[in] flags The inclusive OR of + * + * LS_DATE - %Print file modification date + * + * LS_SIZE - %Print file size. + * + * LS_R - Recursive list of subdirectories. + * + * \return true for success or false if an error occurred. + */ + bool ls(uint8_t flags = 0) { + return ls(&Serial, flags); + } + /** %Print a directory date field. + * + * Format is yyyy-mm-dd. + * + * \param[in] fatDate The date field from a directory entry. + */ + static void printFatDate(uint16_t fatDate) { + printFatDate(&Serial, fatDate); + } + /** %Print a directory time field. + * + * Format is hh:mm:ss. + * + * \param[in] fatTime The time field from a directory entry. + */ + static void printFatTime(uint16_t fatTime) { + printFatTime(&Serial, fatTime); + } + /** Print a file's name. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + size_t printName() { + return FatFile::printName(&Serial); + } +#endif // ENABLE_ARDUINO_FEATURES + + /** \return value of writeError */ + bool getWriteError() { + return m_error & WRITE_ERROR; + } + /** Set writeError to zero */ + void clearWriteError() { + m_error &= ~WRITE_ERROR; + } + /** Clear all error bits. */ + void clearError() { + m_error = 0; + } + /** \return All error bits. */ + uint8_t getError() { + return m_error; + } + /** get position for streams + * \param[out] pos struct to receive position + */ + void getpos(FatPos_t* pos); + /** set position for streams + * \param[out] pos struct with value for new position + */ + void setpos(FatPos_t* pos); + /** \return The number of bytes available from the current position + * to EOF for normal files. Zero is returned for directory files. + */ + uint32_t available() { + return isFile() ? fileSize() - curPosition() : 0; + } + /** Close a file and force cached data and directory information + * to be written to the storage device. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool close(); + /** Check for contiguous file and return its raw block range. + * + * \param[out] bgnBlock the first block address for the file. + * \param[out] endBlock the last block address for the file. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock); + /** Create and open a new contiguous file of a specified size. + * + * \param[in] dirFile The directory where the file will be created. + * \param[in] path A path with a validfile name. + * \param[in] size The desired file size. + * + * \return The value true is returned for success and + * the value false, is returned for failure. + */ + bool createContiguous(FatFile* dirFile, + const char* path, uint32_t size); + /** Create and open a new contiguous file of a specified size. + * + * \param[in] path A path with a validfile name. + * \param[in] size The desired file size. + * + * \return The value true is returned for success and + * the value false, is returned for failure. + */ + bool createContiguous(const char* path, uint32_t size) { + return createContiguous(m_cwd, path, size); + } + /** \return The current cluster number for a file or directory. */ + uint32_t curCluster() const { + return m_curCluster; + } + /** \return The current position for a file or directory. */ + uint32_t curPosition() const { + return m_curPosition; + } + /** \return Current working directory */ + static FatFile* cwd() { + return m_cwd; + } + /** Set the date/time callback function + * + * \param[in] dateTime The user's call back function. The callback + * function is of the form: + * + * \code + * void dateTime(uint16_t* date, uint16_t* time) { + * uint16_t year; + * uint8_t month, day, hour, minute, second; + * + * // User gets date and time from GPS or real-time clock here + * + * // return date using FAT_DATE macro to format fields + * *date = FAT_DATE(year, month, day); + * + * // return time using FAT_TIME macro to format fields + * *time = FAT_TIME(hour, minute, second); + * } + * \endcode + * + * Sets the function that is called when a file is created or when + * a file's directory entry is modified by sync(). All timestamps, + * access, creation, and modify, are set when a file is created. + * sync() maintains the last access date and last modify date/time. + * + * See the timestamp() function. + */ + static void dateTimeCallback( + void (*dateTime)(uint16_t* date, uint16_t* time)) { + m_dateTime = dateTime; + } + /** Cancel the date/time callback function. */ + static void dateTimeCallbackCancel() { + m_dateTime = 0; + } + /** Return a file's directory entry. + * + * \param[out] dir Location for return of the file's directory entry. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool dirEntry(dir_t* dir); + /** + * \return The index of this file in it's directory. + */ + uint16_t dirIndex() { + return m_dirIndex; + } + /** Format the name field of \a dir into the 13 byte array + * \a name in standard 8.3 short name format. + * + * \param[in] dir The directory structure containing the name. + * \param[out] name A 13 byte char array for the formatted name. + * \return length of the name. + */ + static uint8_t dirName(const dir_t* dir, char* name); + /** \return The number of bytes allocated to a directory or zero + * if an error occurs. + */ + uint32_t dirSize(); + /** Dump file in Hex + * \param[in] pr Print stream for list. + * \param[in] pos Start position in file. + * \param[in] n number of locations to dump. + */ + void dmpFile(print_t* pr, uint32_t pos, size_t n); + /** Test for the existence of a file in a directory + * + * \param[in] path Path of the file to be tested for. + * + * The calling instance must be an open directory file. + * + * dirFile.exists("TOFIND.TXT") searches for "TOFIND.TXT" in the directory + * dirFile. + * + * \return true if the file exists else false. + */ + bool exists(const char* path) { + FatFile file; + return file.open(this, path, O_RDONLY); + } + /** + * Get a string from a file. + * + * fgets() reads bytes from a file into the array pointed to by \a str, until + * \a num - 1 bytes are read, or a delimiter is read and transferred to \a str, + * or end-of-file is encountered. The string is then terminated + * with a null byte. + * + * fgets() deletes CR, '\\r', from the string. This insures only a '\\n' + * terminates the string for Windows text files which use CRLF for newline. + * + * \param[out] str Pointer to the array where the string is stored. + * \param[in] num Maximum number of characters to be read + * (including the final null byte). Usually the length + * of the array \a str is used. + * \param[in] delim Optional set of delimiters. The default is "\n". + * + * \return For success fgets() returns the length of the string in \a str. + * If no data is read, fgets() returns zero for EOF or -1 if an error occurred. + */ + int16_t fgets(char* str, int16_t num, char* delim = 0); + /** \return The total number of bytes in a file. */ + uint32_t fileSize() const { + return m_fileSize; + } + /** \return The first cluster number for a file or directory. */ + uint32_t firstCluster() const { + return m_firstCluster; + } + /** + * Get a file's name followed by a zero byte. + * + * \param[out] name An array of characters for the file's name. + * \param[in] size The size of the array in bytes. The array + * must be at least 13 bytes long. The file's name will be + * truncated if the file's name is too long. + * \return The value true, is returned for success and + * the value false, is returned for failure. + */ + bool getName(char* name, size_t size); + /** + * Get a file's Short File Name followed by a zero byte. + * + * \param[out] name An array of characters for the file's name. + * The array must be at least 13 bytes long. + * \return The value true, is returned for success and + * the value false, is returned for failure. + */ + bool getSFN(char* name); + /** \return True if this is a directory else false. */ + bool isDir() const { + return m_attr & FILE_ATTR_DIR; + } + /** \return True if this is a normal file else false. */ + bool isFile() const { + return m_attr & FILE_ATTR_FILE; + } + /** \return True if this is a hidden file else false. */ + bool isHidden() const { + return m_attr & FILE_ATTR_HIDDEN; + } + /** \return true if this file has a Long File Name. */ + bool isLFN() const { + return m_lfnOrd; + } + /** \return True if this is an open file/directory else false. */ + bool isOpen() const { + return m_attr; + } + /** \return True if this is the root directory. */ + bool isRoot() const { + return m_attr & FILE_ATTR_ROOT; + } + /** \return True if this is the FAT32 root directory. */ + bool isRoot32() const { + return m_attr & FILE_ATTR_ROOT32; + } + /** \return True if this is the FAT12 of FAT16 root directory. */ + bool isRootFixed() const { + return m_attr & FILE_ATTR_ROOT_FIXED; + } + /** \return True if file is read-only */ + bool isReadOnly() const { + return m_attr & FILE_ATTR_READ_ONLY; + } + /** \return True if this is a subdirectory else false. */ + bool isSubDir() const { + return m_attr & FILE_ATTR_SUBDIR; + } + /** \return True if this is a system file else false. */ + bool isSystem() const { + return m_attr & FILE_ATTR_SYSTEM; + } + /** Check for a legal 8.3 character. + * \param[in] c Character to be checked. + * \return true for a legal 8.3 character else false. + */ + static bool legal83Char(uint8_t c) { + if (c == '"' || c == '|') { + return false; + } + // *+,./ + if (0X2A <= c && c <= 0X2F && c != 0X2D) { + return false; + } + // :;<=>? + if (0X3A <= c && c <= 0X3F) { + return false; + } + // [\] + if (0X5B <= c && c <= 0X5D) { + return false; + } + return 0X20 < c && c < 0X7F; + } + /** List directory contents. + * + * \param[in] pr Print stream for list. + * + * \param[in] flags The inclusive OR of + * + * LS_DATE - %Print file modification date + * + * LS_SIZE - %Print file size. + * + * LS_R - Recursive list of subdirectories. + * + * \param[in] indent Amount of space before file name. Used for recursive + * list to indicate subdirectory level. + * + * \return true for success or false if an error occurred. + */ + bool ls(print_t* pr, uint8_t flags = 0, uint8_t indent = 0); + /** Make a new directory. + * + * \param[in] dir An open FatFile instance for the directory that will + * contain the new directory. + * + * \param[in] path A path with a valid 8.3 DOS name for the new directory. + * + * \param[in] pFlag Create missing parent directories if true. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool mkdir(FatFile* dir, const char* path, bool pFlag = true); + /** Open a file in the volume working directory of a FatFileSystem. + * + * \param[in] fs File System where the file is located. + * + * \param[in] path with a valid 8.3 DOS name for a file to be opened. + * + * \param[in] oflag bitwise-inclusive OR of open mode flags. + * See see FatFile::open(FatFile*, const char*, oflag_t). + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool open(FatFileSystem* fs, const char* path, oflag_t oflag); + /** Open a file by index. + * + * \param[in] dirFile An open FatFile instance for the directory. + * + * \param[in] index The \a index of the directory entry for the file to be + * opened. The value for \a index is (directory file position)/32. + * + * \param[in] oflag bitwise-inclusive OR of open mode flags. + * See see FatFile::open(FatFile*, const char*, oflag_t). + * + * See open() by path for definition of flags. + * \return true for success or false for failure. + */ + bool open(FatFile* dirFile, uint16_t index, oflag_t oflag); + /** Open a file or directory by name. + * + * \param[in] dirFile An open FatFile instance for the directory containing + * the file to be opened. + * + * \param[in] path A path with a valid 8.3 DOS name for a file to be opened. + * + * \param[in] oflag Values for \a oflag are constructed by a + * bitwise-inclusive OR of flags from the following list + * + * O_RDONLY - Open for reading. + * + * O_READ - Same as O_RDONLY (GNU). + * + * O_WRONLY - Open for writing. + * + * O_WRITE - Same as O_WRONLY (GNU). + * + * O_RDWR - Open for reading and writing. + * + * O_APPEND - If set, the file offset shall be set to the end of the + * file prior to each write. + * + * O_AT_END - Set the initial position at the end of the file. + * + * O_CREAT - If the file exists, this flag has no effect except as noted + * under O_EXCL below. Otherwise, the file shall be created + * + * O_EXCL - If O_CREAT and O_EXCL are set, open() shall fail if the file exists. + * + * O_SYNC - Call sync() after each write. This flag should not be used with + * write(uint8_t) or any functions do character at a time writes since sync() + * will be called after each byte. + * + * O_TRUNC - If the file exists and is a regular file, and the file is + * successfully opened and is not read only, its length shall be truncated to 0. + * + * WARNING: A given file must not be opened by more than one FatFile object + * or file corruption may occur. + * + * \note Directory files must be opened read only. Write and truncation is + * not allowed for directory files. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool open(FatFile* dirFile, const char* path, oflag_t oflag); + /** Open a file in the current working directory. + * + * \param[in] path A path with a valid 8.3 DOS name for a file to be opened. + * + * \param[in] oflag bitwise-inclusive OR of open mode flags. + * See see FatFile::open(FatFile*, const char*, oflag_t). + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool open(const char* path, oflag_t oflag = O_RDONLY) { + return open(m_cwd, path, oflag); + } + /** Open current working directory. + * + * \return true for success or false for failure. + */ + bool openCwd(); + /** Open the next file or subdirectory in a directory. + * + * \param[in] dirFile An open FatFile instance for the directory + * containing the file to be opened. + * + * \param[in] oflag bitwise-inclusive OR of open mode flags. + * See see FatFile::open(FatFile*, const char*, oflag_t). + * + * \return true for success or false for failure. + */ + bool openNext(FatFile* dirFile, oflag_t oflag = O_RDONLY); + /** Open a volume's root directory. + * + * \param[in] vol The FAT volume containing the root directory to be opened. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool openRoot(FatVolume* vol); + /** Return the next available byte without consuming it. + * + * \return The byte if no error and not at eof else -1; + */ + int peek(); + /** Print a file's creation date and time + * + * \param[in] pr Print stream for output. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool printCreateDateTime(print_t* pr); + /** %Print a directory date field. + * + * Format is yyyy-mm-dd. + * + * \param[in] pr Print stream for output. + * \param[in] fatDate The date field from a directory entry. + */ + static void printFatDate(print_t* pr, uint16_t fatDate); + /** %Print a directory time field. + * + * Format is hh:mm:ss. + * + * \param[in] pr Print stream for output. + * \param[in] fatTime The time field from a directory entry. + */ + static void printFatTime(print_t* pr, uint16_t fatTime); + /** Print a number followed by a field terminator. + * \param[in] value The number to be printed. + * \param[in] term The field terminator. Use '\\n' for CR LF. + * \param[in] prec Number of digits after decimal point. + * \return The number of bytes written or -1 if an error occurs. + */ + int printField(float value, char term, uint8_t prec = 2); + /** Print a number followed by a field terminator. + * \param[in] value The number to be printed. + * \param[in] term The field terminator. Use '\\n' for CR LF. + * \return The number of bytes written or -1 if an error occurs. + */ + int printField(int16_t value, char term); + /** Print a number followed by a field terminator. + * \param[in] value The number to be printed. + * \param[in] term The field terminator. Use '\\n' for CR LF. + * \return The number of bytes written or -1 if an error occurs. + */ + int printField(uint16_t value, char term); + /** Print a number followed by a field terminator. + * \param[in] value The number to be printed. + * \param[in] term The field terminator. Use '\\n' for CR LF. + * \return The number of bytes written or -1 if an error occurs. + */ + int printField(int32_t value, char term); + /** Print a number followed by a field terminator. + * \param[in] value The number to be printed. + * \param[in] term The field terminator. Use '\\n' for CR LF. + * \return The number of bytes written or -1 if an error occurs. + */ + int printField(uint32_t value, char term); + /** Print a file's modify date and time + * + * \param[in] pr Print stream for output. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool printModifyDateTime(print_t* pr); + /** Print a file's name + * + * \param[in] pr Print stream for output. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + size_t printName(print_t* pr); + /** Print a file's size. + * + * \param[in] pr Print stream for output. + * + * \return The number of characters printed is returned + * for success and zero is returned for failure. + */ + size_t printFileSize(print_t* pr); + /** Print a file's Short File Name. + * + * \param[in] pr Print stream for output. + * + * \return The number of characters printed is returned + * for success and zero is returned for failure. + */ + size_t printSFN(print_t* pr); + /** Read the next byte from a file. + * + * \return For success read returns the next byte in the file as an int. + * If an error occurs or end of file is reached -1 is returned. + */ + int read() { + uint8_t b; + return read(&b, 1) == 1 ? b : -1; + } + /** Read data from a file starting at the current position. + * + * \param[out] buf Pointer to the location that will receive the data. + * + * \param[in] nbyte Maximum number of bytes to read. + * + * \return For success read() returns the number of bytes read. + * A value less than \a nbyte, including zero, will be returned + * if end of file is reached. + * If an error occurs, read() returns -1. Possible errors include + * read() called before a file has been opened, corrupt file system + * or an I/O error occurred. + */ + int read(void* buf, size_t nbyte); + /** Read the next directory entry from a directory file. + * + * \param[out] dir The dir_t struct that will receive the data. + * + * \return For success readDir() returns the number of bytes read. + * A value of zero will be returned if end of file is reached. + * If an error occurs, readDir() returns -1. Possible errors include + * readDir() called before a directory has been opened, this is not + * a directory file or an I/O error occurred. + */ + int8_t readDir(dir_t* dir); + /** Remove a file. + * + * The directory entry and all data for the file are deleted. + * + * \note This function should not be used to delete the 8.3 version of a + * file that has a long name. For example if a file has the long name + * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool remove(); + /** Remove a file. + * + * The directory entry and all data for the file are deleted. + * + * \param[in] dirFile The directory that contains the file. + * \param[in] path Path for the file to be removed. + * + * \note This function should not be used to delete the 8.3 version of a + * file that has a long name. For example if a file has the long name + * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + static bool remove(FatFile* dirFile, const char* path); + /** Set the file's current position to zero. */ + void rewind() { + seekSet(0); + } + /** Rename a file or subdirectory. + * + * \note the file will be moved to the current working directory. + * + * \param[in] newPath New path name for the file/directory. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool rename(const char* newPath) { + return rename(cwd(), newPath); + } + /** Rename a file or subdirectory. + * + * \param[in] dirFile Directory for the new path. + * \param[in] newPath New path name for the file/directory. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool rename(FatFile* dirFile, const char* newPath); + /** Remove a directory file. + * + * The directory file will be removed only if it is empty and is not the + * root directory. rmdir() follows DOS and Windows and ignores the + * read-only attribute for the directory. + * + * \note This function should not be used to delete the 8.3 version of a + * directory that has a long name. For example if a directory has the + * long name "New folder" you should not delete the 8.3 name "NEWFOL~1". + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool rmdir(); + /** Recursively delete a directory and all contained files. + * + * This is like the Unix/Linux 'rm -rf *' if called with the root directory + * hence the name. + * + * Warning - This will remove all contents of the directory including + * subdirectories. The directory will then be removed if it is not root. + * The read-only attribute for files will be ignored. + * + * \note This function should not be used to delete the 8.3 version of + * a directory that has a long name. See remove() and rmdir(). + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool rmRfStar(); + /** Set the files position to current position + \a pos. See seekSet(). + * \param[in] offset The new position in bytes from the current position. + * \return true for success or false for failure. + */ + bool seekCur(int32_t offset) { + return seekSet(m_curPosition + offset); + } + /** Set the files position to end-of-file + \a offset. See seekSet(). + * Can't be used for directory files since file size is not defined. + * \param[in] offset The new position in bytes from end-of-file. + * \return true for success or false for failure. + */ + bool seekEnd(int32_t offset = 0) { + return isFile() ? seekSet(m_fileSize + offset) : false; + } + /** Sets a file's position. + * + * \param[in] pos The new position in bytes from the beginning of the file. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool seekSet(uint32_t pos); + /** Set the current working directory. + * + * \param[in] dir New current working directory. + * + * \return true for success else false. + */ + static bool setCwd(FatFile* dir) { + if (!dir->isDir()) { + return false; + } + m_cwd = dir; + return true; + } + /** \return first block of file or zero for empty file. */ + uint32_t firstBlock() { + if (m_firstCluster) { + return m_vol->clusterFirstBlock(m_firstCluster); + } + return 0; + } + /** The sync() call causes all modified data and directory fields + * to be written to the storage device. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool sync(); + /** Copy a file's timestamps + * + * \param[in] file File to copy timestamps from. + * + * \note + * Modify and access timestamps may be overwritten if a date time callback + * function has been set by dateTimeCallback(). + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool timestamp(FatFile* file); + /** Set a file's timestamps in its directory entry. + * + * \param[in] flags Values for \a flags are constructed by a bitwise-inclusive + * OR of flags from the following list + * + * T_ACCESS - Set the file's last access date. + * + * T_CREATE - Set the file's creation date and time. + * + * T_WRITE - Set the file's last write/modification date and time. + * + * \param[in] year Valid range 1980 - 2107 inclusive. + * + * \param[in] month Valid range 1 - 12 inclusive. + * + * \param[in] day Valid range 1 - 31 inclusive. + * + * \param[in] hour Valid range 0 - 23 inclusive. + * + * \param[in] minute Valid range 0 - 59 inclusive. + * + * \param[in] second Valid range 0 - 59 inclusive + * + * \note It is possible to set an invalid date since there is no check for + * the number of days in a month. + * + * \note + * Modify and access timestamps may be overwritten if a date time callback + * function has been set by dateTimeCallback(). + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool timestamp(uint8_t flags, uint16_t year, uint8_t month, uint8_t day, + uint8_t hour, uint8_t minute, uint8_t second); + /** Type of file. You should use isFile() or isDir() instead of fileType() + * if possible. + * + * \return The file or directory type. + */ + uint8_t fileAttr() const { + return m_attr; + } + /** Truncate a file to a specified length. The current file position + * will be maintained if it is less than or equal to \a length otherwise + * it will be set to end of file. + * + * \param[in] length The desired length for the file. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool truncate(uint32_t length); + /** \return FatVolume that contains this file. */ + FatVolume* volume() const { + return m_vol; + } + /** Write a string to a file. Used by the Arduino Print class. + * \param[in] str Pointer to the string. + * Use getWriteError to check for errors. + * \return count of characters written for success or -1 for failure. + */ + int write(const char* str) { + return write(str, strlen(str)); + } + /** Write a single byte. + * \param[in] b The byte to be written. + * \return +1 for success or -1 for failure. + */ + int write(uint8_t b) { + return write(&b, 1); + } + /** Write data to an open file. + * + * \note Data is moved to the cache but may not be written to the + * storage device until sync() is called. + * + * \param[in] buf Pointer to the location of the data to be written. + * + * \param[in] nbyte Number of bytes to write. + * + * \return For success write() returns the number of bytes written, always + * \a nbyte. If an error occurs, write() returns -1. Possible errors + * include write() is called before a file has been opened, write is called + * for a read-only file, device is full, a corrupt file system or an I/O error. + * + */ + int write(const void* buf, size_t nbyte); +//------------------------------------------------------------------------------ + private: + /** This file has not been opened. */ + static const uint8_t FILE_ATTR_CLOSED = 0; + /** File is read-only. */ + static const uint8_t FILE_ATTR_READ_ONLY = DIR_ATT_READ_ONLY; + /** File should be hidden in directory listings. */ + static const uint8_t FILE_ATTR_HIDDEN = DIR_ATT_HIDDEN; + /** Entry is for a system file. */ + static const uint8_t FILE_ATTR_SYSTEM = DIR_ATT_SYSTEM; + /** Entry for normal data file */ + static const uint8_t FILE_ATTR_FILE = 0X08; + /** Entry is for a subdirectory */ + static const uint8_t FILE_ATTR_SUBDIR = DIR_ATT_DIRECTORY; + /** A FAT12 or FAT16 root directory */ + static const uint8_t FILE_ATTR_ROOT_FIXED = 0X20; + /** A FAT32 root directory */ + static const uint8_t FILE_ATTR_ROOT32 = 0X40; + /** Entry is for root. */ + static const uint8_t FILE_ATTR_ROOT = FILE_ATTR_ROOT_FIXED | FILE_ATTR_ROOT32; + /** Directory type bits */ + static const uint8_t FILE_ATTR_DIR = FILE_ATTR_SUBDIR | FILE_ATTR_ROOT; + /** Attributes to copy from directory entry */ + static const uint8_t FILE_ATTR_COPY = DIR_ATT_READ_ONLY | DIR_ATT_HIDDEN | + DIR_ATT_SYSTEM | DIR_ATT_DIRECTORY; + + /** experimental don't use */ + + bool openParent(FatFile* dir); + + // private functions + bool addCluster(); + bool addDirCluster(); + dir_t* cacheDirEntry(uint8_t action); + static uint8_t lfnChecksum(uint8_t* name); + bool lfnUniqueSfn(fname_t* fname); + bool openCluster(FatFile* file); + static bool parsePathName(const char* str, fname_t* fname, const char** ptr); + bool mkdir(FatFile* parent, fname_t* fname); + bool open(FatFile* dirFile, fname_t* fname, oflag_t oflag); + bool openCachedEntry(FatFile* dirFile, uint16_t cacheIndex, oflag_t oflag, + uint8_t lfnOrd); + bool readLBN(uint32_t* lbn); + dir_t* readDirCache(bool skipReadOk = false); + bool setDirSize(); + + // bits defined in m_flags + static const uint8_t F_READ = 0X01; + static const uint8_t F_WRITE = 0X02; + static const uint8_t F_FILE_DIR_DIRTY = 0X04; + static const uint8_t F_APPEND = 0X08; + static const uint8_t F_SYNC = 0X80; + + + // global pointer to cwd dir + static FatFile* m_cwd; + // data time callback function + static void (*m_dateTime)(uint16_t* date, uint16_t* time); + // private data + static const uint8_t WRITE_ERROR = 0X1; + static const uint8_t READ_ERROR = 0X2; + uint8_t m_attr; // File attributes + uint8_t m_error; // Error bits. + uint8_t m_flags; // See above for definition of m_flags bits + uint8_t m_lfnOrd; + uint16_t m_dirIndex; // index of directory entry in dir file + FatVolume* m_vol; // volume where file is located + uint32_t m_dirCluster; + uint32_t m_curCluster; // cluster for current file position + uint32_t m_curPosition; // current file position + uint32_t m_dirBlock; // block for this files directory entry + uint32_t m_fileSize; // file size in bytes + uint32_t m_firstCluster; // first cluster of file +}; +#endif // FatFile_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileLFN.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileLFN.cpp new file mode 100644 index 0000000..f7e4627 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileLFN.cpp @@ -0,0 +1,688 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#include "FatFile.h" +//------------------------------------------------------------------------------ +// +uint8_t FatFile::lfnChecksum(uint8_t* name) { + uint8_t sum = 0; + for (uint8_t i = 0; i < 11; i++) { + sum = (((sum & 1) << 7) | ((sum & 0xfe) >> 1)) + name[i]; + } + return sum; +} +#if USE_LONG_FILE_NAMES +//------------------------------------------------------------------------------ +// Saves about 90 bytes of flash on 328 over tolower(). +inline char lfnToLower(char c) { + return 'A' <= c && c <= 'Z' ? c + 'a' - 'A' : c; +} +//------------------------------------------------------------------------------ +// Daniel Bernstein University of Illinois at Chicago. +// Original had + instead of ^ +static uint16_t Bernstein(uint16_t hash, const char *str, size_t len) { + for (size_t i = 0; i < len; i++) { + // hash = hash * 33 ^ str[i]; + hash = ((hash << 5) + hash) ^ str[i]; + } + return hash; +} +//------------------------------------------------------------------------------ +/** + * Fetch a 16-bit long file name character. + * + * \param[in] ldir Pointer to long file name directory entry. + * \param[in] i Index of character. + * \return The 16-bit character. + */ +static uint16_t lfnGetChar(ldir_t *ldir, uint8_t i) { + if (i < LDIR_NAME1_DIM) { + return ldir->name1[i]; + } else if (i < (LDIR_NAME1_DIM + LDIR_NAME2_DIM)) { + return ldir->name2[i - LDIR_NAME1_DIM]; + } else if (i < (LDIR_NAME1_DIM + LDIR_NAME2_DIM + LDIR_NAME2_DIM)) { + return ldir->name3[i - LDIR_NAME1_DIM - LDIR_NAME2_DIM]; + } + return 0; +} +//------------------------------------------------------------------------------ +static bool lfnGetName(ldir_t *ldir, char* name, size_t n) { + uint8_t i; + size_t k = 13*((ldir->ord & 0X1F) - 1); + for (i = 0; i < 13; i++) { + uint16_t c = lfnGetChar(ldir, i); + if (c == 0 || k >= n) { + break; + } + name[k++] = c >= 0X7F ? '?' : c; + } + // Terminate with zero byte if name fits. + if (k < n && (ldir->ord & LDIR_ORD_LAST_LONG_ENTRY)) { + name[k] = 0; + } + // Truncate if name is too long. + name[n - 1] = 0; + return true; +} +//------------------------------------------------------------------------------ +inline bool lfnLegalChar(char c) { + if (c == '/' || c == '\\' || c == '"' || c == '*' || + c == ':' || c == '<' || c == '>' || c == '?' || c == '|') { + return false; + } + return 0X1F < c && c < 0X7F; +} +//------------------------------------------------------------------------------ +/** + * Store a 16-bit long file name character. + * + * \param[in] ldir Pointer to long file name directory entry. + * \param[in] i Index of character. + * \param[in] c The 16-bit character. + */ +static void lfnPutChar(ldir_t *ldir, uint8_t i, uint16_t c) { + if (i < LDIR_NAME1_DIM) { + ldir->name1[i] = c; + } else if (i < (LDIR_NAME1_DIM + LDIR_NAME2_DIM)) { + ldir->name2[i - LDIR_NAME1_DIM] = c; + } else if (i < (LDIR_NAME1_DIM + LDIR_NAME2_DIM + LDIR_NAME2_DIM)) { + ldir->name3[i - LDIR_NAME1_DIM - LDIR_NAME2_DIM] = c; + } +} +//------------------------------------------------------------------------------ +static void lfnPutName(ldir_t *ldir, const char* name, size_t n) { + size_t k = 13*((ldir->ord & 0X1F) - 1); + for (uint8_t i = 0; i < 13; i++, k++) { + uint16_t c = k < n ? name[k] : k == n ? 0 : 0XFFFF; + lfnPutChar(ldir, i, c); + } +} +//============================================================================== +bool FatFile::getName(char* name, size_t size) { + FatFile dirFile; + ldir_t* ldir; + if (!isOpen() || size < 13) { + DBG_FAIL_MACRO; + goto fail; + } + if (!isLFN()) { + return getSFN(name); + } + if (!dirFile.openCluster(this)) { + DBG_FAIL_MACRO; + goto fail; + } + for (uint8_t ord = 1; ord <= m_lfnOrd; ord++) { + if (!dirFile.seekSet(32UL*(m_dirIndex - ord))) { + DBG_FAIL_MACRO; + goto fail; + } + ldir = reinterpret_cast(dirFile.readDirCache()); + if (!ldir) { + DBG_FAIL_MACRO; + goto fail; + } + if (ldir->attr != DIR_ATT_LONG_NAME) { + DBG_FAIL_MACRO; + goto fail; + } + if (ord != (ldir->ord & 0X1F)) { + DBG_FAIL_MACRO; + goto fail; + } + if (!lfnGetName(ldir, name, size)) { + DBG_FAIL_MACRO; + goto fail; + } + if (ldir->ord & LDIR_ORD_LAST_LONG_ENTRY) { + return true; + } + } + // Fall into fail. + DBG_FAIL_MACRO; + +fail: + name[0] = 0; + return false; +} +//------------------------------------------------------------------------------ +bool FatFile::openCluster(FatFile* file) { + if (file->m_dirCluster == 0) { + return openRoot(file->m_vol); + } + memset(this, 0, sizeof(FatFile)); + m_attr = FILE_ATTR_SUBDIR; + m_flags = F_READ; + m_vol = file->m_vol; + m_firstCluster = file->m_dirCluster; + return true; +} +//------------------------------------------------------------------------------ +bool FatFile::parsePathName(const char* path, + fname_t* fname, const char** ptr) { + char c; + bool is83; + uint8_t bit = DIR_NT_LC_BASE; + uint8_t lc = 0; + uint8_t uc = 0; + uint8_t i = 0; + uint8_t in = 7; + int end; + int len = 0; + int si; + int dot; + + // Skip leading spaces. + while (*path == ' ') { + path++; + } + fname->lfn = path; + + for (len = 0; ; len++) { + c = path[len]; + if (c == 0 || isDirSeparator(c)) { + break; + } + if (!lfnLegalChar(c)) { + return false; + } + } + // Advance to next path component. + for (end = len; path[end] == ' ' || isDirSeparator(path[end]); end++) {} + *ptr = &path[end]; + + // Back over spaces and dots. + while (len) { + c = path[len - 1]; + if (c != '.' && c != ' ') { + break; + } + len--; + } + // Max length of LFN is 255. + if (len > 255) { + return false; + } + fname->len = len; + // Blank file short name. + for (uint8_t k = 0; k < 11; k++) { + fname->sfn[k] = ' '; + } + // skip leading spaces and dots. + for (si = 0; path[si] == '.' || path[si] == ' '; si++) {} + // Not 8.3 if leading dot or space. + is83 = !si; + + // find last dot. + for (dot = len - 1; dot >= 0 && path[dot] != '.'; dot--) {} + for (; si < len; si++) { + c = path[si]; + if (c == ' ' || (c == '.' && dot != si)) { + is83 = false; + continue; + } + if (!legal83Char(c) && si != dot) { + is83 = false; + c = '_'; + } + if (si == dot || i > in) { + if (in == 10) { + // Done - extension longer than three characters. + is83 = false; + break; + } + if (si != dot) { + is83 = false; + } + // Break if no dot and base-name is longer than eight characters. + if (si > dot) { + break; + } + si = dot; + in = 10; // Max index for full 8.3 name. + i = 8; // Place for extension. + bit = DIR_NT_LC_EXT; // bit for extension. + } else { + if ('a' <= c && c <= 'z') { + c += 'A' - 'a'; + lc |= bit; + } else if ('A' <= c && c <= 'Z') { + uc |= bit; + } + fname->sfn[i++] = c; + if (i < 7) { + fname->seqPos = i; + } + } + } + if (fname->sfn[0] == ' ') { + return false; + } + + if (is83) { + fname->flags = lc & uc ? FNAME_FLAG_MIXED_CASE : lc; + } else { + fname->flags = FNAME_FLAG_LOST_CHARS; + fname->sfn[fname->seqPos] = '~'; + fname->sfn[fname->seqPos + 1] = '1'; + } + return true; +} +//------------------------------------------------------------------------------ +bool FatFile::open(FatFile* dirFile, fname_t* fname, oflag_t oflag) { + bool fnameFound = false; + uint8_t lfnOrd = 0; + uint8_t freeNeed; + uint8_t freeFound = 0; + uint8_t ord = 0; + uint8_t chksum = 0; + uint16_t freeIndex = 0; + uint16_t curIndex; + dir_t* dir; + ldir_t* ldir; + size_t len = fname->len; + + if (!dirFile->isDir() || isOpen()) { + DBG_FAIL_MACRO; + goto fail; + } + // Number of directory entries needed. + freeNeed = fname->flags & FNAME_FLAG_NEED_LFN ? 1 + (len + 12)/13 : 1; + + dirFile->rewind(); + while (1) { + curIndex = dirFile->m_curPosition/32; + dir = dirFile->readDirCache(true); + if (!dir) { + if (dirFile->getError()) { + DBG_FAIL_MACRO; + goto fail; + } + // At EOF + goto create; + } + if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == DIR_NAME_FREE) { + if (freeFound == 0) { + freeIndex = curIndex; + } + if (freeFound < freeNeed) { + freeFound++; + } + if (dir->name[0] == DIR_NAME_FREE) { + goto create; + } + } else { + if (freeFound < freeNeed) { + freeFound = 0; + } + } + // skip empty slot or '.' or '..' + if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') { + lfnOrd = 0; + } else if (DIR_IS_LONG_NAME(dir)) { + ldir_t *ldir = reinterpret_cast(dir); + if (!lfnOrd) { + if ((ldir->ord & LDIR_ORD_LAST_LONG_ENTRY) == 0) { + continue; + } + lfnOrd = ord = ldir->ord & 0X1F; + chksum = ldir->chksum; + } else if (ldir->ord != --ord || chksum != ldir->chksum) { + lfnOrd = 0; + continue; + } + size_t k = 13*(ord - 1); + if (k >= len) { + // Not found. + lfnOrd = 0; + continue; + } + for (uint8_t i = 0; i < 13; i++) { + uint16_t u = lfnGetChar(ldir, i); + if (k == len) { + if (u != 0) { + // Not found. + lfnOrd = 0; + } + break; + } + if (u > 255 || lfnToLower(u) != lfnToLower(fname->lfn[k++])) { + // Not found. + lfnOrd = 0; + break; + } + } + } else if (DIR_IS_FILE_OR_SUBDIR(dir)) { + if (lfnOrd) { + if (1 == ord && lfnChecksum(dir->name) == chksum) { + goto found; + } + DBG_FAIL_MACRO; + goto fail; + } + if (!memcmp(dir->name, fname->sfn, sizeof(fname->sfn))) { + if (!(fname->flags & FNAME_FLAG_LOST_CHARS)) { + goto found; + } + fnameFound = true; + } + } else { + lfnOrd = 0; + } + } + +found: + // Don't open if create only. + if (oflag & O_EXCL) { + DBG_FAIL_MACRO; + goto fail; + } + goto open; + +create: + // don't create unless O_CREAT and write mode. + if (!(oflag & O_CREAT) || !isWriteMode(oflag)) { + DBG_FAIL_MACRO; + goto fail; + } + // If at EOF start in next cluster. + if (freeFound == 0) { + freeIndex = curIndex; + } + + while (freeFound < freeNeed) { + dir = dirFile->readDirCache(); + if (!dir) { + if (dirFile->getError()) { + DBG_FAIL_MACRO; + goto fail; + } + // EOF if no error. + break; + } + freeFound++; + } + while (freeFound < freeNeed) { + // Will fail if FAT16 root. + if (!dirFile->addDirCluster()) { + DBG_FAIL_MACRO; + goto fail; + } + // Done if more than one block per cluster. Max freeNeed is 21. + if (dirFile->m_vol->blocksPerCluster() > 1) { + break; + } + freeFound += 16; + } + if (fnameFound) { + if (!dirFile->lfnUniqueSfn(fname)) { + goto fail; + } + } + if (!dirFile->seekSet(32UL*freeIndex)) { + DBG_FAIL_MACRO; + goto fail; + } + lfnOrd = freeNeed - 1; + for (uint8_t ord = lfnOrd ; ord ; ord--) { + ldir = reinterpret_cast(dirFile->readDirCache()); + if (!ldir) { + DBG_FAIL_MACRO; + goto fail; + } + dirFile->m_vol->cacheDirty(); + ldir->ord = ord == lfnOrd ? LDIR_ORD_LAST_LONG_ENTRY | ord : ord; + ldir->attr = DIR_ATT_LONG_NAME; + ldir->type = 0; + ldir->chksum = lfnChecksum(fname->sfn); + ldir->mustBeZero = 0; + lfnPutName(ldir, fname->lfn, len); + } + curIndex = dirFile->m_curPosition/32; + dir = dirFile->readDirCache(); + if (!dir) { + DBG_FAIL_MACRO; + goto fail; + } + // initialize as empty file + memset(dir, 0, sizeof(dir_t)); + memcpy(dir->name, fname->sfn, 11); + + // Set base-name and extension lower case bits. + dir->reservedNT = (DIR_NT_LC_BASE | DIR_NT_LC_EXT) & fname->flags; + + // set timestamps + if (m_dateTime) { + // call user date/time function + m_dateTime(&dir->creationDate, &dir->creationTime); + } else { + // use default date/time + dir->creationDate = FAT_DEFAULT_DATE; + dir->creationTime = FAT_DEFAULT_TIME; + } + dir->lastAccessDate = dir->creationDate; + dir->lastWriteDate = dir->creationDate; + dir->lastWriteTime = dir->creationTime; + + // Force write of entry to device. + dirFile->m_vol->cacheDirty(); + +open: + // open entry in cache. + if (!openCachedEntry(dirFile, curIndex, oflag, lfnOrd)) { + DBG_FAIL_MACRO; + goto fail; + } + return true; + +fail: + return false; +} +//------------------------------------------------------------------------------ +size_t FatFile::printName(print_t* pr) { + FatFile dirFile; + uint16_t u; + size_t n = 0; + ldir_t* ldir; + + if (!isLFN()) { + return printSFN(pr); + } + if (!dirFile.openCluster(this)) { + DBG_FAIL_MACRO; + goto fail; + } + for (uint8_t ord = 1; ord <= m_lfnOrd; ord++) { + if (!dirFile.seekSet(32UL*(m_dirIndex - ord))) { + DBG_FAIL_MACRO; + goto fail; + } + ldir = reinterpret_cast(dirFile.readDirCache()); + if (!ldir) { + DBG_FAIL_MACRO; + goto fail; + } + if (ldir->attr != DIR_ATT_LONG_NAME || + ord != (ldir->ord & 0X1F)) { + DBG_FAIL_MACRO; + goto fail; + } + for (uint8_t i = 0; i < 13; i++) { + u = lfnGetChar(ldir, i); + if (u == 0) { + // End of name. + break; + } + if (u > 0X7E) { + u = '?'; + } + pr->write(static_cast(u)); + n++; + } + if (ldir->ord & LDIR_ORD_LAST_LONG_ENTRY) { + return n; + } + } + // Fall into fail; + DBG_FAIL_MACRO; + +fail: + return 0; +} +//------------------------------------------------------------------------------ +bool FatFile::remove() { + bool last; + uint8_t chksum; + uint8_t ord; + FatFile dirFile; + dir_t* dir; + ldir_t* ldir; + + // Cant' remove not open for write. + if (!isFile() || !(m_flags & F_WRITE)) { + DBG_FAIL_MACRO; + goto fail; + } + // Free any clusters. + if (m_firstCluster && !m_vol->freeChain(m_firstCluster)) { + DBG_FAIL_MACRO; + goto fail; + } + // Cache directory entry. + dir = cacheDirEntry(FatCache::CACHE_FOR_WRITE); + if (!dir) { + DBG_FAIL_MACRO; + goto fail; + } + chksum = lfnChecksum(dir->name); + + // Mark entry deleted. + dir->name[0] = DIR_NAME_DELETED; + + // Set this file closed. + m_attr = FILE_ATTR_CLOSED; + + // Write entry to device. + if (!m_vol->cacheSync()) { + DBG_FAIL_MACRO; + goto fail; + } + if (!isLFN()) { + // Done, no LFN entries. + return true; + } + if (!dirFile.openCluster(this)) { + DBG_FAIL_MACRO; + goto fail; + } + for (ord = 1; ord <= m_lfnOrd; ord++) { + if (!dirFile.seekSet(32UL*(m_dirIndex - ord))) { + DBG_FAIL_MACRO; + goto fail; + } + ldir = reinterpret_cast(dirFile.readDirCache()); + if (!ldir) { + DBG_FAIL_MACRO; + goto fail; + } + if (ldir->attr != DIR_ATT_LONG_NAME || + ord != (ldir->ord & 0X1F) || + chksum != ldir->chksum) { + DBG_FAIL_MACRO; + goto fail; + } + last = ldir->ord & LDIR_ORD_LAST_LONG_ENTRY; + ldir->ord = DIR_NAME_DELETED; + m_vol->cacheDirty(); + if (last) { + if (!m_vol->cacheSync()) { + DBG_FAIL_MACRO; + goto fail; + } + return true; + } + } + // Fall into fail. + DBG_FAIL_MACRO; + +fail: + return false; +} +//------------------------------------------------------------------------------ +bool FatFile::lfnUniqueSfn(fname_t* fname) { + const uint8_t FIRST_HASH_SEQ = 2; // min value is 2 + uint8_t pos = fname->seqPos;; + dir_t *dir; + uint16_t hex; + + DBG_HALT_IF(!(fname->flags & FNAME_FLAG_LOST_CHARS)); + DBG_HALT_IF(fname->sfn[pos] != '~' && fname->sfn[pos + 1] != '1'); + + for (uint8_t seq = 2; seq < 100; seq++) { + if (seq < FIRST_HASH_SEQ) { + fname->sfn[pos + 1] = '0' + seq; + } else { + DBG_PRINT_IF(seq > FIRST_HASH_SEQ); + hex = Bernstein(seq + fname->len, fname->lfn, fname->len); + if (pos > 3) { + // Make space in name for ~HHHH. + pos = 3; + } + for (uint8_t i = pos + 4 ; i > pos; i--) { + uint8_t h = hex & 0XF; + fname->sfn[i] = h < 10 ? h + '0' : h + 'A' - 10; + hex >>= 4; + } + } + fname->sfn[pos] = '~'; + rewind(); + while (1) { + dir = readDirCache(true); + if (!dir) { + if (!getError()) { + // At EOF and name not found if no error. + goto done; + } + DBG_FAIL_MACRO; + goto fail; + } + if (dir->name[0] == DIR_NAME_FREE) { + goto done; + } + if (DIR_IS_FILE_OR_SUBDIR(dir) && !memcmp(fname->sfn, dir->name, 11)) { + // Name found - try another. + break; + } + } + } + // fall inti fail - too many tries. + DBG_FAIL_MACRO; + +fail: + return false; + +done: + return true; +} +#endif // #if USE_LONG_FILE_NAMES diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFilePrint.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFilePrint.cpp new file mode 100644 index 0000000..bc1b00e --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFilePrint.cpp @@ -0,0 +1,267 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#include +#include "FatFile.h" +#include "FmtNumber.h" +//------------------------------------------------------------------------------ +// print uint8_t with width 2 +static void print2u(print_t* pr, uint8_t v) { + char c0 = '?'; + char c1 = '?'; + if (v < 100) { + c1 = v/10; + c0 = v - 10*c1 + '0'; + c1 += '0'; + } + pr->write(c1); + pr->write(c0); +} +//------------------------------------------------------------------------------ +static void printU32(print_t* pr, uint32_t v) { + char buf[11]; + char* ptr = buf + sizeof(buf); + *--ptr = 0; + pr->write(fmtDec(v, ptr)); +} +//------------------------------------------------------------------------------ +static void printHex(print_t* pr, uint8_t w, uint16_t h) { + char buf[5]; + char* ptr = buf + sizeof(buf); + *--ptr = 0; + for (uint8_t i = 0; i < w; i++) { + char c = h & 0XF; + *--ptr = c < 10 ? c + '0' : c + 'A' - 10; + h >>= 4; + } + pr->write(ptr); +} +//------------------------------------------------------------------------------ +void FatFile::dmpFile(print_t* pr, uint32_t pos, size_t n) { + char text[17]; + text[16] = 0; + if (n >= 0XFFF0) { + n = 0XFFF0; + } + if (!seekSet(pos)) { + return; + } + for (size_t i = 0; i <= n; i++) { + if ((i & 15) == 0) { + if (i) { + pr->write(' '); + pr->write(text); + if (i == n) { + break; + } + } + pr->write('\r'); + pr->write('\n'); + if (i >= n) { + break; + } + printHex(pr, 4, i); + pr->write(' '); + } + int16_t h = read(); + if (h < 0) { + break; + } + pr->write(' '); + printHex(pr, 2, h); + text[i&15] = ' ' <= h && h < 0X7F ? h : '.'; + } + pr->write('\r'); + pr->write('\n'); +} +//------------------------------------------------------------------------------ +bool FatFile::ls(print_t* pr, uint8_t flags, uint8_t indent) { + FatFile file; + if (!isDir() || getError()) { + DBG_FAIL_MACRO; + goto fail; + } + rewind(); + while (file.openNext(this, O_RDONLY)) { + if (!file.isHidden() || (flags & LS_A)) { + // indent for dir level + for (uint8_t i = 0; i < indent; i++) { + pr->write(' '); + } + if (flags & LS_DATE) { + file.printModifyDateTime(pr); + pr->write(' '); + } + if (flags & LS_SIZE) { + file.printFileSize(pr); + pr->write(' '); + } + file.printName(pr); + if (file.isDir()) { + pr->write('/'); + } + pr->write('\r'); + pr->write('\n'); + if ((flags & LS_R) && file.isDir()) { + if (!file.ls(pr, flags, indent + 2)) { + DBG_FAIL_MACRO; + goto fail; + } + } + } + file.close(); + } + if (getError()) { + DBG_FAIL_MACRO; + goto fail; + } + return true; + + fail: + return false; +} +//------------------------------------------------------------------------------ +bool FatFile::printCreateDateTime(print_t* pr) { + dir_t dir; + if (!dirEntry(&dir)) { + DBG_FAIL_MACRO; + goto fail; + } + printFatDate(pr, dir.creationDate); + pr->write(' '); + printFatTime(pr, dir.creationTime); + return true; + +fail: + return false; +} +//------------------------------------------------------------------------------ +void FatFile::printFatDate(print_t* pr, uint16_t fatDate) { + printU32(pr, FAT_YEAR(fatDate)); + pr->write('-'); + print2u(pr, FAT_MONTH(fatDate)); + pr->write('-'); + print2u(pr, FAT_DAY(fatDate)); +} +//------------------------------------------------------------------------------ +void FatFile::printFatTime(print_t* pr, uint16_t fatTime) { + print2u(pr, FAT_HOUR(fatTime)); + pr->write(':'); + print2u(pr, FAT_MINUTE(fatTime)); + pr->write(':'); + print2u(pr, FAT_SECOND(fatTime)); +} +//------------------------------------------------------------------------------ +/** Template for FatFile::printField() */ +template +static int printFieldT(FatFile* file, char sign, Type value, char term) { + char buf[3*sizeof(Type) + 3]; + char* str = &buf[sizeof(buf)]; + + if (term) { + *--str = term; + if (term == '\n') { + *--str = '\r'; + } + } +#ifdef OLD_FMT + do { + Type m = value; + value /= 10; + *--str = '0' + m - 10*value; + } while (value); +#else // OLD_FMT + str = fmtDec(value, str); +#endif // OLD_FMT + if (sign) { + *--str = sign; + } + return file->write(str, &buf[sizeof(buf)] - str); +} +//------------------------------------------------------------------------------ + +int FatFile::printField(float value, char term, uint8_t prec) { + char buf[24]; + char* str = &buf[sizeof(buf)]; + if (term) { + *--str = term; + if (term == '\n') { + *--str = '\r'; + } + } + str = fmtFloat(value, str, prec); + return write(str, buf + sizeof(buf) - str); +} +//------------------------------------------------------------------------------ +int FatFile::printField(uint16_t value, char term) { + return printFieldT(this, 0, value, term); +} +//------------------------------------------------------------------------------ +int FatFile::printField(int16_t value, char term) { + char sign = 0; + if (value < 0) { + sign = '-'; + value = -value; + } + return printFieldT(this, sign, (uint16_t)value, term); +} +//------------------------------------------------------------------------------ +int FatFile::printField(uint32_t value, char term) { + return printFieldT(this, 0, value, term); +} +//------------------------------------------------------------------------------ +int FatFile::printField(int32_t value, char term) { + char sign = 0; + if (value < 0) { + sign = '-'; + value = -value; + } + return printFieldT(this, sign, (uint32_t)value, term); +} +//------------------------------------------------------------------------------ +bool FatFile::printModifyDateTime(print_t* pr) { + dir_t dir; + if (!dirEntry(&dir)) { + DBG_FAIL_MACRO; + goto fail; + } + printFatDate(pr, dir.lastWriteDate); + pr->write(' '); + printFatTime(pr, dir.lastWriteTime); + return true; + +fail: + return false; +} +//------------------------------------------------------------------------------ +size_t FatFile::printFileSize(print_t* pr) { + char buf[11]; + char *ptr = buf + sizeof(buf); + *--ptr = 0; + ptr = fmtDec(fileSize(), ptr); + while (ptr > buf) { + *--ptr = ' '; + } + return pr->write(buf); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileSFN.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileSFN.cpp new file mode 100644 index 0000000..c49b4be --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileSFN.cpp @@ -0,0 +1,278 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#include "FatFile.h" +#include "FatFileSystem.h" +//------------------------------------------------------------------------------ +bool FatFile::getSFN(char* name) { + dir_t* dir; + if (!isOpen()) { + DBG_FAIL_MACRO; + goto fail; + } + if (isRoot()) { + name[0] = '/'; + name[1] = '\0'; + return true; + } + // cache entry + dir = cacheDirEntry(FatCache::CACHE_FOR_READ); + if (!dir) { + DBG_FAIL_MACRO; + goto fail; + } + // format name + dirName(dir, name); + return true; + +fail: + return false; +} +//------------------------------------------------------------------------------ +size_t FatFile::printSFN(print_t* pr) { + char name[13]; + if (!getSFN(name)) { + DBG_FAIL_MACRO; + goto fail; + } + return pr->write(name); + +fail: + return 0; +} +#if !USE_LONG_FILE_NAMES +//------------------------------------------------------------------------------ +bool FatFile::getName(char* name, size_t size) { + return size < 13 ? 0 : getSFN(name); +} +//------------------------------------------------------------------------------ +// format directory name field from a 8.3 name string +bool FatFile::parsePathName(const char* path, fname_t* fname, + const char** ptr) { + uint8_t uc = 0; + uint8_t lc = 0; + uint8_t bit = FNAME_FLAG_LC_BASE; + // blank fill name and extension + for (uint8_t i = 0; i < 11; i++) { + fname->sfn[i] = ' '; + } + + for (uint8_t i = 0, n = 7;; path++) { + uint8_t c = *path; + if (c == 0 || isDirSeparator(c)) { + // Done. + break; + } + if (c == '.' && n == 7) { + n = 10; // max index for full 8.3 name + i = 8; // place for extension + + // bit for extension. + bit = FNAME_FLAG_LC_EXT; + } else { + if (!legal83Char(c) || i > n) { + DBG_FAIL_MACRO; + goto fail; + } + if ('a' <= c && c <= 'z') { + c += 'A' - 'a'; + lc |= bit; + } else if ('A' <= c && c <= 'Z') { + uc |= bit; + } + fname->sfn[i++] = c; + } + } + // must have a file name, extension is optional + if (fname->sfn[0] == ' ') { + DBG_FAIL_MACRO; + goto fail; + } + // Set base-name and extension bits. + fname->flags = lc & uc ? 0 : lc; + while (isDirSeparator(*path)) { + path++; + } + *ptr = path; + return true; + +fail: + return false; +} +//------------------------------------------------------------------------------ +// open with filename in fname +#define SFN_OPEN_USES_CHKSUM 0 +bool FatFile::open(FatFile* dirFile, fname_t* fname, oflag_t oflag) { + bool emptyFound = false; +#if SFN_OPEN_USES_CHKSUM + uint8_t chksum; +#endif + uint8_t lfnOrd = 0; + uint16_t emptyIndex; + uint16_t index = 0; + dir_t* dir; + ldir_t* ldir; + + dirFile->rewind(); + while (1) { + if (!emptyFound) { + emptyIndex = index; + } + dir = dirFile->readDirCache(true); + if (!dir) { + if (dirFile->getError()) { + DBG_FAIL_MACRO; + goto fail; + } + // At EOF if no error. + break; + } + if (dir->name[0] == DIR_NAME_FREE) { + emptyFound = true; + break; + } + if (dir->name[0] == DIR_NAME_DELETED) { + lfnOrd = 0; + emptyFound = true; + } else if (DIR_IS_FILE_OR_SUBDIR(dir)) { + if (!memcmp(fname->sfn, dir->name, 11)) { + // don't open existing file if O_EXCL + if (oflag & O_EXCL) { + DBG_FAIL_MACRO; + goto fail; + } +#if SFN_OPEN_USES_CHKSUM + if (lfnOrd && chksum != lfnChecksum(dir->name)) { + DBG_FAIL_MACRO; + goto fail; + } +#endif // SFN_OPEN_USES_CHKSUM + if (!openCachedEntry(dirFile, index, oflag, lfnOrd)) { + DBG_FAIL_MACRO; + goto fail; + } + return true; + } else { + lfnOrd = 0; + } + } else if (DIR_IS_LONG_NAME(dir)) { + ldir = reinterpret_cast(dir); + if (ldir->ord & LDIR_ORD_LAST_LONG_ENTRY) { + lfnOrd = ldir->ord & 0X1F; +#if SFN_OPEN_USES_CHKSUM + chksum = ldir->chksum; +#endif // SFN_OPEN_USES_CHKSUM + } + } else { + lfnOrd = 0; + } + index++; + } + // don't create unless O_CREAT and write mode + if (!(oflag & O_CREAT) || !isWriteMode(oflag)) { + DBG_FAIL_MACRO; + goto fail; + } + if (emptyFound) { + index = emptyIndex; + } else { + if (!dirFile->addDirCluster()) { + DBG_FAIL_MACRO; + goto fail; + } + } + if (!dirFile->seekSet(32UL*index)) { + DBG_FAIL_MACRO; + goto fail; + } + dir = dirFile->readDirCache(); + if (!dir) { + DBG_FAIL_MACRO; + goto fail; + } + // initialize as empty file + memset(dir, 0, sizeof(dir_t)); + memcpy(dir->name, fname->sfn, 11); + + // Set base-name and extension lower case bits. + dir->reservedNT = (DIR_NT_LC_BASE | DIR_NT_LC_EXT) & fname->flags; + + // set timestamps + if (m_dateTime) { + // call user date/time function + m_dateTime(&dir->creationDate, &dir->creationTime); + } else { + // use default date/time + dir->creationDate = FAT_DEFAULT_DATE; + dir->creationTime = FAT_DEFAULT_TIME; + } + dir->lastAccessDate = dir->creationDate; + dir->lastWriteDate = dir->creationDate; + dir->lastWriteTime = dir->creationTime; + + // Force write of entry to device. + dirFile->m_vol->cacheDirty(); + + // open entry in cache. + return openCachedEntry(dirFile, index, oflag, 0); + +fail: + return false; +} +//------------------------------------------------------------------------------ +size_t FatFile::printName(print_t* pr) { + return printSFN(pr); +} +//------------------------------------------------------------------------------ +bool FatFile::remove() { + dir_t* dir; + // Can't remove if LFN or not open for write. + if (!isFile() || isLFN() || !(m_flags & F_WRITE)) { + DBG_FAIL_MACRO; + goto fail; + } + // Free any clusters. + if (m_firstCluster && !m_vol->freeChain(m_firstCluster)) { + DBG_FAIL_MACRO; + goto fail; + } + // Cache directory entry. + dir = cacheDirEntry(FatCache::CACHE_FOR_WRITE); + if (!dir) { + DBG_FAIL_MACRO; + goto fail; + } + // Mark entry deleted. + dir->name[0] = DIR_NAME_DELETED; + + // Set this file closed. + m_attr = FILE_ATTR_CLOSED; + + // Write entry to device. + return m_vol->cacheSync(); + +fail: + return false; +} +#endif // !USE_LONG_FILE_NAMES diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileSystem.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileSystem.h new file mode 100644 index 0000000..4c78b13 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileSystem.h @@ -0,0 +1,332 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 FatFileSystem_h +#define FatFileSystem_h +#include "FatVolume.h" +#include "FatFile.h" +#include "ArduinoFiles.h" +/** + * \file + * \brief FatFileSystem class + */ +//------------------------------------------------------------------------------ +/** + * \class FatFileSystem + * \brief Integration class for the FatLib library. + */ +class FatFileSystem : public FatVolume { + public: + /** + * Initialize an FatFileSystem object. + * \param[in] blockDev Device block driver. + * \param[in] part partition to initialize. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool begin(BlockDriver* blockDev, uint8_t part = 0) { + m_blockDev = blockDev; + vwd()->close(); + return (part ? init(part) : init(1) || init(0)) + && vwd()->openRoot(this) && FatFile::setCwd(vwd()); + } +#if ENABLE_ARDUINO_FEATURES + /** List the directory contents of the volume working directory to Serial. + * + * \param[in] flags The inclusive OR of + * + * LS_DATE - %Print file modification date + * + * LS_SIZE - %Print file size. + * + * LS_R - Recursive list of subdirectories. + * + * \return true for success or false if an error occurred. + */ + bool ls(uint8_t flags = 0) { + return ls(&Serial, flags); + } + /** List the directory contents of a directory to Serial. + * + * \param[in] path directory to list. + * + * \param[in] flags The inclusive OR of + * + * LS_DATE - %Print file modification date + * + * LS_SIZE - %Print file size. + * + * LS_R - Recursive list of subdirectories. + * + * \return true for success or false if an error occurred. + */ + bool ls(const char* path, uint8_t flags = 0) { + return ls(&Serial, path, flags); + } + /** open a file + * + * \param[in] path location of file to be opened. + * \param[in] oflag open flags. + * \return a File object. + */ + File open(const char *path, oflag_t oflag = FILE_READ) { + File tmpFile; + tmpFile.open(vwd(), path, oflag); + return tmpFile; + } + /** open a file + * + * \param[in] path location of file to be opened. + * \param[in] oflag open flags. + * \return a File object. + */ + File open(const String &path, oflag_t oflag = FILE_READ) { + return open(path.c_str(), oflag ); + } +#endif // ENABLE_ARDUINO_FEATURES + /** Change a volume's working directory to root + * + * Changes the volume's working directory to the SD's root directory. + * Optionally set the current working directory to the volume's + * working directory. + * + * \param[in] set_cwd Set the current working directory to this volume's + * working directory if true. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool chdir(bool set_cwd = false) { + vwd()->close(); + return vwd()->openRoot(this) && (set_cwd ? FatFile::setCwd(vwd()) : true); + } + /** Change a volume's working directory + * + * Changes the volume working directory to the \a path subdirectory. + * Optionally set the current working directory to the volume's + * working directory. + * + * Example: If the volume's working directory is "/DIR", chdir("SUB") + * will change the volume's working directory from "/DIR" to "/DIR/SUB". + * + * If path is "/", the volume's working directory will be changed to the + * root directory + * + * \param[in] path The name of the subdirectory. + * + * \param[in] set_cwd Set the current working directory to this volume's + * working directory if true. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + //---------------------------------------------------------------------------- + bool chdir(const char *path, bool set_cwd = false) { + FatFile dir; + if (path[0] == '/' && path[1] == '\0') { + return chdir(set_cwd); + } + if (!dir.open(vwd(), path, O_RDONLY)) { + goto fail; + } + if (!dir.isDir()) { + goto fail; + } + m_vwd = dir; + if (set_cwd) { + FatFile::setCwd(vwd()); + } + return true; + +fail: + return false; + } + //---------------------------------------------------------------------------- + /** Set the current working directory to a volume's working directory. + * + * This is useful with multiple SD cards. + * + * The current working directory is changed to this + * volume's working directory. + * + * This is like the Windows/DOS \: command. + */ + void chvol() { + FatFile::setCwd(vwd()); + } + //---------------------------------------------------------------------------- + /** + * Test for the existence of a file. + * + * \param[in] path Path of the file to be tested for. + * + * \return true if the file exists else false. + */ + bool exists(const char* path) { + return vwd()->exists(path); + } + //---------------------------------------------------------------------------- + /** List the directory contents of the volume working directory. + * + * \param[in] pr Print stream for list. + * + * \param[in] flags The inclusive OR of + * + * LS_DATE - %Print file modification date + * + * LS_SIZE - %Print file size. + * + * LS_R - Recursive list of subdirectories. + * + * \return true for success or false if an error occurred. + */ + bool ls(print_t* pr, uint8_t flags = 0) { + return vwd()->ls(pr, flags); + } + //---------------------------------------------------------------------------- + /** List the directory contents of a directory. + * + * \param[in] pr Print stream for list. + * + * \param[in] path directory to list. + * + * \param[in] flags The inclusive OR of + * + * LS_DATE - %Print file modification date + * + * LS_SIZE - %Print file size. + * + * LS_R - Recursive list of subdirectories. + * + * \return true for success or false if an error occurred. + */ + bool ls(print_t* pr, const char* path, uint8_t flags) { + FatFile dir; + return dir.open(vwd(), path, O_RDONLY) && dir.ls(pr, flags); + } + //---------------------------------------------------------------------------- + /** Make a subdirectory in the volume working directory. + * + * \param[in] path A path with a valid 8.3 DOS name for the subdirectory. + * + * \param[in] pFlag Create missing parent directories if true. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool mkdir(const char* path, bool pFlag = true) { + FatFile sub; + return sub.mkdir(vwd(), path, pFlag); + } + //---------------------------------------------------------------------------- + /** Remove a file from the volume working directory. + * + * \param[in] path A path with a valid 8.3 DOS name for the file. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool remove(const char* path) { + return FatFile::remove(vwd(), path); + } + //---------------------------------------------------------------------------- + /** Rename a file or subdirectory. + * + * \param[in] oldPath Path name to the file or subdirectory to be renamed. + * + * \param[in] newPath New path name of the file or subdirectory. + * + * The \a newPath object must not exist before the rename call. + * + * The file to be renamed must not be open. The directory entry may be + * moved and file system corruption could occur if the file is accessed by + * a file object that was opened before the rename() call. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool rename(const char *oldPath, const char *newPath) { + FatFile file; + if (!file.open(vwd(), oldPath, O_RDONLY)) { + return false; + } + return file.rename(vwd(), newPath); + } + //---------------------------------------------------------------------------- + /** Remove a subdirectory from the volume's working directory. + * + * \param[in] path A path with a valid 8.3 DOS name for the subdirectory. + * + * The subdirectory file will be removed only if it is empty. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool rmdir(const char* path) { + FatFile sub; + if (!sub.open(vwd(), path, O_RDONLY)) { + return false; + } + return sub.rmdir(); + } + //---------------------------------------------------------------------------- + /** Truncate a file to a specified length. The current file position + * will be maintained if it is less than or equal to \a length otherwise + * it will be set to end of file. + * + * \param[in] path A path with a valid 8.3 DOS name for the file. + * \param[in] length The desired length for the file. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool truncate(const char* path, uint32_t length) { + FatFile file; + if (!file.open(vwd(), path, O_WRONLY)) { + return false; + } + return file.truncate(length); + } + /** \return a pointer to the FatVolume object. */ + FatVolume* vol() { + return this; + } + /** \return a pointer to the volume working directory. */ + FatFile* vwd() { + return &m_vwd; + } + /** Wipe all data from the volume. You must reinitialize the volume before + * accessing it again. + * \param[in] pr print stream for status dots. + * \return true for success else false. + */ + bool wipe(print_t* pr = 0) { + vwd()->close(); + return FatVolume::wipe(pr); + } + + private: + FatFile m_vwd; +}; +#endif // FatFileSystem_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatLib.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatLib.h new file mode 100644 index 0000000..008979d --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatLib.h @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 FatLib_h +#define FatLib_h +#include "ArduinoFiles.h" +#include "FatFileSystem.h" +#include "FatLibConfig.h" +#include "FatVolume.h" +#include "FatFile.h" +#include "StdioStream.h" +//------------------------------------------------------------------------------ +/** FatFileSystem version YYYYMMDD */ +#define FAT_LIB_VERSION 20150131 +#endif // FatLib_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatLibConfig.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatLibConfig.h new file mode 100644 index 0000000..5036eb2 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatLibConfig.h @@ -0,0 +1,146 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +/** + * \file + * \brief configuration definitions + */ +#ifndef FatLibConfig_h +#define FatLibConfig_h +#include +// Allow this file to override defaults. +#include "SdFatConfig.h" + +#ifdef __AVR__ +#include +#endif // __AVR__ +//------------------------------------------------------------------------------ +/** + * Set USE_LONG_FILE_NAMES nonzero to use long file names (LFN). + * Long File Name are limited to a maximum length of 255 characters. + * + * This implementation allows 7-bit characters in the range + * 0X20 to 0X7E. The following characters are not allowed: + * + * < (less than) + * > (greater than) + * : (colon) + * " (double quote) + * / (forward slash) + * \ (backslash) + * | (vertical bar or pipe) + * ? (question mark) + * * (asterisk) + * + */ +#ifndef USE_LONG_FILE_NAMES +#define USE_LONG_FILE_NAMES 1 +#endif // USE_LONG_FILE_NAMES +//------------------------------------------------------------------------------ +/** + * Set USE_SEPARATE_FAT_CACHE non-zero to use a second 512 byte cache + * for FAT table entries. Improves performance for large writes that + * are not a multiple of 512 bytes. + */ +#ifndef USE_SEPARATE_FAT_CACHE +#ifdef __arm__ +#define USE_SEPARATE_FAT_CACHE 1 +#else // __arm__ +#define USE_SEPARATE_FAT_CACHE 0 +#endif // __arm__ +#endif // USE_SEPARATE_FAT_CACHE +//------------------------------------------------------------------------------ +/** + * Set USE_MULTI_BLOCK_IO non-zero to use multi-block SD read/write. + * + * Don't use mult-block read/write on small AVR boards. + */ +#ifndef USE_MULTI_BLOCK_IO +#if defined(RAMEND) && RAMEND < 3000 +#define USE_MULTI_BLOCK_IO 0 +#else // RAMEND +#define USE_MULTI_BLOCK_IO 1 +#endif // RAMEND +#endif // USE_MULTI_BLOCK_IO +//------------------------------------------------------------------------------ +/** + * Set MAINTAIN_FREE_CLUSTER_COUNT nonzero to keep the count of free clusters + * updated. This will increase the speed of the freeClusterCount() call + * after the first call. Extra flash will be required. + */ +#ifndef MAINTAIN_FREE_CLUSTER_COUNT +#define MAINTAIN_FREE_CLUSTER_COUNT 0 +#endif // MAINTAIN_FREE_CLUSTER_COUNT +//------------------------------------------------------------------------------ +/** + * Set DESTRUCTOR_CLOSES_FILE non-zero to close a file in its destructor. + * + * Causes use of lots of heap in ARM. + */ +#ifndef DESTRUCTOR_CLOSES_FILE +#define DESTRUCTOR_CLOSES_FILE 0 +#endif // DESTRUCTOR_CLOSES_FILE +//------------------------------------------------------------------------------ +/** + * Call flush for endl if ENDL_CALLS_FLUSH is non-zero + * + * The standard for iostreams is to call flush. This is very costly for + * SdFat. Each call to flush causes 2048 bytes of I/O to the SD. + * + * SdFat has a single 512 byte buffer for I/O so it must write the current + * data block to the SD, read the directory block from the SD, update the + * directory entry, write the directory block to the SD and read the data + * block back into the buffer. + * + * The SD flash memory controller is not designed for this many rewrites + * so performance may be reduced by more than a factor of 100. + * + * If ENDL_CALLS_FLUSH is zero, you must call flush and/or close to force + * all data to be written to the SD. + */ +#ifndef ENDL_CALLS_FLUSH +#define ENDL_CALLS_FLUSH 0 +#endif // ENDL_CALLS_FLUSH +//------------------------------------------------------------------------------ +/** + * Allow FAT12 volumes if FAT12_SUPPORT is non-zero. + * FAT12 has not been well tested. + */ +#ifndef FAT12_SUPPORT +#define FAT12_SUPPORT 0 +#endif // FAT12_SUPPORT +//------------------------------------------------------------------------------ +/** + * Enable Extra features for Arduino. + */ +// #define ENABLE_ARDUINO_FEATURES 0 ////////////////////////FIX THIS ///////////////// +#ifndef ENABLE_ARDUINO_FEATURES +#include +#if defined(ARDUINO) || defined(PLATFORM_ID) || defined(DOXYGEN) +#define ENABLE_ARDUINO_FEATURES 1 +#else // #if defined(ARDUINO) || defined(DOXYGEN) +#define ENABLE_ARDUINO_FEATURES 0 +#endif // defined(ARDUINO) || defined(DOXYGEN) +#endif // ENABLE_ARDUINO_FEATURES +#endif // FatLibConfig_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatStructs.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatStructs.h new file mode 100644 index 0000000..cf4ccb8 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatStructs.h @@ -0,0 +1,882 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 FatStructs_h +#define FatStructs_h +/** + * \file + * \brief FAT file structures + */ +/* + * mostly from Microsoft document fatgen103.doc + * http://www.microsoft.com/whdc/system/platform/firmware/fatgen.mspx + */ +//------------------------------------------------------------------------------ +/** Value for byte 510 of boot block or MBR */ +const uint8_t BOOTSIG0 = 0X55; +/** Value for byte 511 of boot block or MBR */ +const uint8_t BOOTSIG1 = 0XAA; +/** Value for bootSignature field int FAT/FAT32 boot sector */ +const uint8_t EXTENDED_BOOT_SIG = 0X29; +//------------------------------------------------------------------------------ +/** + * \struct partitionTable + * \brief MBR partition table entry + * + * A partition table entry for a MBR formatted storage device. + * The MBR partition table has four entries. + */ +struct partitionTable { + /** + * Boot Indicator . Indicates whether the volume is the active + * partition. Legal values include: 0X00. Do not use for booting. + * 0X80 Active partition. + */ + uint8_t boot; + /** + * Head part of Cylinder-head-sector address of the first block in + * the partition. Legal values are 0-255. Only used in old PC BIOS. + */ + uint8_t beginHead; + /** + * Sector part of Cylinder-head-sector address of the first block in + * the partition. Legal values are 1-63. Only used in old PC BIOS. + */ + unsigned beginSector : 6; + /** High bits cylinder for first block in partition. */ + unsigned beginCylinderHigh : 2; + /** + * Combine beginCylinderLow with beginCylinderHigh. Legal values + * are 0-1023. Only used in old PC BIOS. + */ + uint8_t beginCylinderLow; + /** + * Partition type. See defines that begin with PART_TYPE_ for + * some Microsoft partition types. + */ + uint8_t type; + /** + * head part of cylinder-head-sector address of the last sector in the + * partition. Legal values are 0-255. Only used in old PC BIOS. + */ + uint8_t endHead; + /** + * Sector part of cylinder-head-sector address of the last sector in + * the partition. Legal values are 1-63. Only used in old PC BIOS. + */ + unsigned endSector : 6; + /** High bits of end cylinder */ + unsigned endCylinderHigh : 2; + /** + * Combine endCylinderLow with endCylinderHigh. Legal values + * are 0-1023. Only used in old PC BIOS. + */ + uint8_t endCylinderLow; + /** Logical block address of the first block in the partition. */ + uint32_t firstSector; + /** Length of the partition, in blocks. */ + uint32_t totalSectors; +} __attribute__((packed)); +/** Type name for partitionTable */ +typedef struct partitionTable part_t; +//------------------------------------------------------------------------------ +/** + * \struct masterBootRecord + * + * \brief Master Boot Record + * + * The first block of a storage device that is formatted with a MBR. + */ +struct masterBootRecord { + /** Code Area for master boot program. */ + uint8_t codeArea[440]; + /** Optional Windows NT disk signature. May contain boot code. */ + uint32_t diskSignature; + /** Usually zero but may be more boot code. */ + uint16_t usuallyZero; + /** Partition tables. */ + part_t part[4]; + /** First MBR signature byte. Must be 0X55 */ + uint8_t mbrSig0; + /** Second MBR signature byte. Must be 0XAA */ + uint8_t mbrSig1; +} __attribute__((packed)); +/** Type name for masterBootRecord */ +typedef struct masterBootRecord mbr_t; +//------------------------------------------------------------------------------ +/** + * \struct biosParmBlock + * + * \brief BIOS parameter block + * + * The BIOS parameter block describes the physical layout of a FAT volume. + */ +struct biosParmBlock { + /** + * Count of bytes per sector. This value may take on only the + * following values: 512, 1024, 2048 or 4096 + */ + uint16_t bytesPerSector; + /** + * Number of sectors per allocation unit. This value must be a + * power of 2 that is greater than 0. The legal values are + * 1, 2, 4, 8, 16, 32, 64, and 128. + */ + uint8_t sectorsPerCluster; + /** + * Number of sectors before the first FAT. + * This value must not be zero. + */ + uint16_t reservedSectorCount; + /** The count of FAT data structures on the volume. This field should + * always contain the value 2 for any FAT volume of any type. + */ + uint8_t fatCount; + /** + * For FAT12 and FAT16 volumes, this field contains the count of + * 32-byte directory entries in the root directory. For FAT32 volumes, + * this field must be set to 0. For FAT12 and FAT16 volumes, this + * value should always specify a count that when multiplied by 32 + * results in a multiple of bytesPerSector. FAT16 volumes should + * use the value 512. + */ + uint16_t rootDirEntryCount; + /** + * This field is the old 16-bit total count of sectors on the volume. + * This count includes the count of all sectors in all four regions + * of the volume. This field can be 0; if it is 0, then totalSectors32 + * must be nonzero. For FAT32 volumes, this field must be 0. For + * FAT12 and FAT16 volumes, this field contains the sector count, and + * totalSectors32 is 0 if the total sector count fits + * (is less than 0x10000). + */ + uint16_t totalSectors16; + /** + * This dates back to the old MS-DOS 1.x media determination and is + * no longer usually used for anything. 0xF8 is the standard value + * for fixed (nonremovable) media. For removable media, 0xF0 is + * frequently used. Legal values are 0xF0 or 0xF8-0xFF. + */ + uint8_t mediaType; + /** + * Count of sectors occupied by one FAT on FAT12/FAT16 volumes. + * On FAT32 volumes this field must be 0, and sectorsPerFat32 + * contains the FAT size count. + */ + uint16_t sectorsPerFat16; + /** Sectors per track for interrupt 0x13. Not used otherwise. */ + uint16_t sectorsPerTrtack; + /** Number of heads for interrupt 0x13. Not used otherwise. */ + uint16_t headCount; + /** + * Count of hidden sectors preceding the partition that contains this + * FAT volume. This field is generally only relevant for media + * visible on interrupt 0x13. + */ + uint32_t hidddenSectors; + /** + * This field is the new 32-bit total count of sectors on the volume. + * This count includes the count of all sectors in all four regions + * of the volume. This field can be 0; if it is 0, then + * totalSectors16 must be nonzero. + */ + uint32_t totalSectors32; + /** + * Count of sectors occupied by one FAT on FAT32 volumes. + */ + uint32_t sectorsPerFat32; + /** + * This field is only defined for FAT32 media and does not exist on + * FAT12 and FAT16 media. + * Bits 0-3 -- Zero-based number of active FAT. + * Only valid if mirroring is disabled. + * Bits 4-6 -- Reserved. + * Bit 7 -- 0 means the FAT is mirrored at runtime into all FATs. + * -- 1 means only one FAT is active; it is the one referenced in bits 0-3. + * Bits 8-15 -- Reserved. + */ + uint16_t fat32Flags; + /** + * FAT32 version. High byte is major revision number. + * Low byte is minor revision number. Only 0.0 define. + */ + uint16_t fat32Version; + /** + * Cluster number of the first cluster of the root directory for FAT32. + * This usually 2 but not required to be 2. + */ + uint32_t fat32RootCluster; + /** + * Sector number of FSINFO structure in the reserved area of the + * FAT32 volume. Usually 1. + */ + uint16_t fat32FSInfo; + /** + * If nonzero, indicates the sector number in the reserved area + * of the volume of a copy of the boot record. Usually 6. + * No value other than 6 is recommended. + */ + uint16_t fat32BackBootBlock; + /** + * Reserved for future expansion. Code that formats FAT32 volumes + * should always set all of the bytes of this field to 0. + */ + uint8_t fat32Reserved[12]; +} __attribute__((packed)); +/** Type name for biosParmBlock */ +typedef struct biosParmBlock bpb_t; +//------------------------------------------------------------------------------ +/** + * \struct fat_boot + * + * \brief Boot sector for a FAT12/FAT16 volume. + * + */ +struct fat_boot { + /** + * The first three bytes of the boot sector must be valid, + * executable x 86-based CPU instructions. This includes a + * jump instruction that skips the next non-executable bytes. + */ + uint8_t jump[3]; + /** + * This is typically a string of characters that identifies + * the operating system that formatted the volume. + */ + char oemId[8]; + /** + * The size of a hardware sector. Valid decimal values for this + * field are 512, 1024, 2048, and 4096. For most disks used in + * the United States, the value of this field is 512. + */ + uint16_t bytesPerSector; + /** + * Number of sectors per allocation unit. This value must be a + * power of 2 that is greater than 0. The legal values are + * 1, 2, 4, 8, 16, 32, 64, and 128. 128 should be avoided. + */ + uint8_t sectorsPerCluster; + /** + * The number of sectors preceding the start of the first FAT, + * including the boot sector. The value of this field is always 1. + */ + uint16_t reservedSectorCount; + /** + * The number of copies of the FAT on the volume. + * The value of this field is always 2. + */ + uint8_t fatCount; + /** + * For FAT12 and FAT16 volumes, this field contains the count of + * 32-byte directory entries in the root directory. For FAT32 volumes, + * this field must be set to 0. For FAT12 and FAT16 volumes, this + * value should always specify a count that when multiplied by 32 + * results in a multiple of bytesPerSector. FAT16 volumes should + * use the value 512. + */ + uint16_t rootDirEntryCount; + /** + * This field is the old 16-bit total count of sectors on the volume. + * This count includes the count of all sectors in all four regions + * of the volume. This field can be 0; if it is 0, then totalSectors32 + * must be non-zero. For FAT32 volumes, this field must be 0. For + * FAT12 and FAT16 volumes, this field contains the sector count, and + * totalSectors32 is 0 if the total sector count fits + * (is less than 0x10000). + */ + uint16_t totalSectors16; + /** + * This dates back to the old MS-DOS 1.x media determination and is + * no longer usually used for anything. 0xF8 is the standard value + * for fixed (non-removable) media. For removable media, 0xF0 is + * frequently used. Legal values are 0xF0 or 0xF8-0xFF. + */ + uint8_t mediaType; + /** + * Count of sectors occupied by one FAT on FAT12/FAT16 volumes. + * On FAT32 volumes this field must be 0, and sectorsPerFat32 + * contains the FAT size count. + */ + uint16_t sectorsPerFat16; + /** Sectors per track for interrupt 0x13. Not used otherwise. */ + uint16_t sectorsPerTrack; + /** Number of heads for interrupt 0x13. Not used otherwise. */ + uint16_t headCount; + /** + * Count of hidden sectors preceding the partition that contains this + * FAT volume. This field is generally only relevant for media + * visible on interrupt 0x13. + */ + uint32_t hidddenSectors; + /** + * This field is the new 32-bit total count of sectors on the volume. + * This count includes the count of all sectors in all four regions + * of the volume. This field can be 0; if it is 0, then + * totalSectors16 must be non-zero. + */ + uint32_t totalSectors32; + /** + * Related to the BIOS physical drive number. Floppy drives are + * identified as 0x00 and physical hard disks are identified as + * 0x80, regardless of the number of physical disk drives. + * Typically, this value is set prior to issuing an INT 13h BIOS + * call to specify the device to access. The value is only + * relevant if the device is a boot device. + */ + uint8_t driveNumber; + /** used by Windows NT - should be zero for FAT */ + uint8_t reserved1; + /** 0X29 if next three fields are valid */ + uint8_t bootSignature; + /** + * A random serial number created when formatting a disk, + * which helps to distinguish between disks. + * Usually generated by combining date and time. + */ + uint32_t volumeSerialNumber; + /** + * A field once used to store the volume label. The volume label + * is now stored as a special file in the root directory. + */ + char volumeLabel[11]; + /** + * A field with a value of either FAT, FAT12 or FAT16, + * depending on the disk format. + */ + char fileSystemType[8]; + /** X86 boot code */ + uint8_t bootCode[448]; + /** must be 0X55 */ + uint8_t bootSectorSig0; + /** must be 0XAA */ + uint8_t bootSectorSig1; +} __attribute__((packed)); +/** Type name for FAT Boot Sector */ +typedef struct fat_boot fat_boot_t; +//------------------------------------------------------------------------------ +/** + * \struct fat32_boot + * + * \brief Boot sector for a FAT32 volume. + * + */ +struct fat32_boot { + /** + * The first three bytes of the boot sector must be valid, + * executable x 86-based CPU instructions. This includes a + * jump instruction that skips the next non-executable bytes. + */ + uint8_t jump[3]; + /** + * This is typically a string of characters that identifies + * the operating system that formatted the volume. + */ + char oemId[8]; + /** + * The size of a hardware sector. Valid decimal values for this + * field are 512, 1024, 2048, and 4096. For most disks used in + * the United States, the value of this field is 512. + */ + uint16_t bytesPerSector; + /** + * Number of sectors per allocation unit. This value must be a + * power of 2 that is greater than 0. The legal values are + * 1, 2, 4, 8, 16, 32, 64, and 128. 128 should be avoided. + */ + uint8_t sectorsPerCluster; + /** + * The number of sectors preceding the start of the first FAT, + * including the boot sector. Must not be zero + */ + uint16_t reservedSectorCount; + /** + * The number of copies of the FAT on the volume. + * The value of this field is always 2. + */ + uint8_t fatCount; + /** + * FAT12/FAT16 only. For FAT32 volumes, this field must be set to 0. + */ + uint16_t rootDirEntryCount; + /** + * For FAT32 volumes, this field must be 0. + */ + uint16_t totalSectors16; + /** + * This dates back to the old MS-DOS 1.x media determination and is + * no longer usually used for anything. 0xF8 is the standard value + * for fixed (non-removable) media. For removable media, 0xF0 is + * frequently used. Legal values are 0xF0 or 0xF8-0xFF. + */ + uint8_t mediaType; + /** + * On FAT32 volumes this field must be 0, and sectorsPerFat32 + * contains the FAT size count. + */ + uint16_t sectorsPerFat16; + /** Sectors per track for interrupt 0x13. Not used otherwise. */ + uint16_t sectorsPerTrack; + /** Number of heads for interrupt 0x13. Not used otherwise. */ + uint16_t headCount; + /** + * Count of hidden sectors preceding the partition that contains this + * FAT volume. This field is generally only relevant for media + * visible on interrupt 0x13. + */ + uint32_t hidddenSectors; + /** + * Contains the total number of sectors in the FAT32 volume. + */ + uint32_t totalSectors32; + /** + * Count of sectors occupied by one FAT on FAT32 volumes. + */ + uint32_t sectorsPerFat32; + /** + * This field is only defined for FAT32 media and does not exist on + * FAT12 and FAT16 media. + * Bits 0-3 -- Zero-based number of active FAT. + * Only valid if mirroring is disabled. + * Bits 4-6 -- Reserved. + * Bit 7 -- 0 means the FAT is mirrored at runtime into all FATs. + * -- 1 means only one FAT is active; it is the one referenced + * in bits 0-3. + * Bits 8-15 -- Reserved. + */ + uint16_t fat32Flags; + /** + * FAT32 version. High byte is major revision number. + * Low byte is minor revision number. Only 0.0 define. + */ + uint16_t fat32Version; + /** + * Cluster number of the first cluster of the root directory for FAT32. + * This usually 2 but not required to be 2. + */ + uint32_t fat32RootCluster; + /** + * Sector number of FSINFO structure in the reserved area of the + * FAT32 volume. Usually 1. + */ + uint16_t fat32FSInfo; + /** + * If non-zero, indicates the sector number in the reserved area + * of the volume of a copy of the boot record. Usually 6. + * No value other than 6 is recommended. + */ + uint16_t fat32BackBootBlock; + /** + * Reserved for future expansion. Code that formats FAT32 volumes + * should always set all of the bytes of this field to 0. + */ + uint8_t fat32Reserved[12]; + /** + * Related to the BIOS physical drive number. Floppy drives are + * identified as 0x00 and physical hard disks are identified as + * 0x80, regardless of the number of physical disk drives. + * Typically, this value is set prior to issuing an INT 13h BIOS + * call to specify the device to access. The value is only + * relevant if the device is a boot device. + */ + uint8_t driveNumber; + /** used by Windows NT - should be zero for FAT */ + uint8_t reserved1; + /** 0X29 if next three fields are valid */ + uint8_t bootSignature; + /** + * A random serial number created when formatting a disk, + * which helps to distinguish between disks. + * Usually generated by combining date and time. + */ + uint32_t volumeSerialNumber; + /** + * A field once used to store the volume label. The volume label + * is now stored as a special file in the root directory. + */ + char volumeLabel[11]; + /** + * A text field with a value of FAT32. + */ + char fileSystemType[8]; + /** X86 boot code */ + uint8_t bootCode[420]; + /** must be 0X55 */ + uint8_t bootSectorSig0; + /** must be 0XAA */ + uint8_t bootSectorSig1; +} __attribute__((packed)); +/** Type name for FAT32 Boot Sector */ +typedef struct fat32_boot fat32_boot_t; +//------------------------------------------------------------------------------ +/** Lead signature for a FSINFO sector */ +const uint32_t FSINFO_LEAD_SIG = 0x41615252; +/** Struct signature for a FSINFO sector */ +const uint32_t FSINFO_STRUCT_SIG = 0x61417272; +/** + * \struct fat32_fsinfo + * + * \brief FSINFO sector for a FAT32 volume. + * + */ +struct fat32_fsinfo { + /** must be 0X52, 0X52, 0X61, 0X41 */ + uint32_t leadSignature; + /** must be zero */ + uint8_t reserved1[480]; + /** must be 0X72, 0X72, 0X41, 0X61 */ + uint32_t structSignature; + /** + * Contains the last known free cluster count on the volume. + * If the value is 0xFFFFFFFF, then the free count is unknown + * and must be computed. Any other value can be used, but is + * not necessarily correct. It should be range checked at least + * to make sure it is <= volume cluster count. + */ + uint32_t freeCount; + /** + * This is a hint for the FAT driver. It indicates the cluster + * number at which the driver should start looking for free clusters. + * If the value is 0xFFFFFFFF, then there is no hint and the driver + * should start looking at cluster 2. + */ + uint32_t nextFree; + /** must be zero */ + uint8_t reserved2[12]; + /** must be 0X00, 0X00, 0X55, 0XAA */ + uint8_t tailSignature[4]; +} __attribute__((packed)); +/** Type name for FAT32 FSINFO Sector */ +typedef struct fat32_fsinfo fat32_fsinfo_t; +//------------------------------------------------------------------------------ +// End Of Chain values for FAT entries +/** FAT12 end of chain value used by Microsoft. */ +const uint16_t FAT12EOC = 0XFFF; +/** Minimum value for FAT12 EOC. Use to test for EOC. */ +const uint16_t FAT12EOC_MIN = 0XFF8; +/** FAT16 end of chain value used by Microsoft. */ +const uint16_t FAT16EOC = 0XFFFF; +/** Minimum value for FAT16 EOC. Use to test for EOC. */ +const uint16_t FAT16EOC_MIN = 0XFFF8; +/** FAT32 end of chain value used by Microsoft. */ +const uint32_t FAT32EOC = 0X0FFFFFFF; +/** Minimum value for FAT32 EOC. Use to test for EOC. */ +const uint32_t FAT32EOC_MIN = 0X0FFFFFF8; +/** Mask a for FAT32 entry. Entries are 28 bits. */ +const uint32_t FAT32MASK = 0X0FFFFFFF; +//------------------------------------------------------------------------------ +/** + * \struct directoryEntry + * \brief FAT short directory entry + * + * Short means short 8.3 name, not the entry size. + * + * Date Format. A FAT directory entry date stamp is a 16-bit field that is + * basically a date relative to the MS-DOS epoch of 01/01/1980. Here is the + * format (bit 0 is the LSB of the 16-bit word, bit 15 is the MSB of the + * 16-bit word): + * + * Bits 9-15: Count of years from 1980, valid value range 0-127 + * inclusive (1980-2107). + * + * Bits 5-8: Month of year, 1 = January, valid value range 1-12 inclusive. + * + * Bits 0-4: Day of month, valid value range 1-31 inclusive. + * + * Time Format. A FAT directory entry time stamp is a 16-bit field that has + * a granularity of 2 seconds. Here is the format (bit 0 is the LSB of the + * 16-bit word, bit 15 is the MSB of the 16-bit word). + * + * Bits 11-15: Hours, valid value range 0-23 inclusive. + * + * Bits 5-10: Minutes, valid value range 0-59 inclusive. + * + * Bits 0-4: 2-second count, valid value range 0-29 inclusive (0 - 58 seconds). + * + * The valid time range is from Midnight 00:00:00 to 23:59:58. + */ +struct directoryEntry { + /** Short 8.3 name. + * + * The first eight bytes contain the file name with blank fill. + * The last three bytes contain the file extension with blank fill. + */ + uint8_t name[11]; + /** Entry attributes. + * + * The upper two bits of the attribute byte are reserved and should + * always be set to 0 when a file is created and never modified or + * looked at after that. See defines that begin with DIR_ATT_. + */ + uint8_t attributes; + /** + * Reserved for use by Windows NT. Set value to 0 when a file is + * created and never modify or look at it after that. + */ + uint8_t reservedNT; + /** + * The granularity of the seconds part of creationTime is 2 seconds + * so this field is a count of tenths of a second and its valid + * value range is 0-199 inclusive. (WHG note - seems to be hundredths) + */ + uint8_t creationTimeTenths; + /** Time file was created. */ + uint16_t creationTime; + /** Date file was created. */ + uint16_t creationDate; + /** + * Last access date. Note that there is no last access time, only + * a date. This is the date of last read or write. In the case of + * a write, this should be set to the same date as lastWriteDate. + */ + uint16_t lastAccessDate; + /** + * High word of this entry's first cluster number (always 0 for a + * FAT12 or FAT16 volume). + */ + uint16_t firstClusterHigh; + /** Time of last write. File creation is considered a write. */ + uint16_t lastWriteTime; + /** Date of last write. File creation is considered a write. */ + uint16_t lastWriteDate; + /** Low word of this entry's first cluster number. */ + uint16_t firstClusterLow; + /** 32-bit unsigned holding this file's size in bytes. */ + uint32_t fileSize; +} __attribute__((packed)); +/** Type name for directoryEntry */ +typedef struct directoryEntry dir_t; +//------------------------------------------------------------------------------ +// Definitions for directory entries +// +/** escape for name[0] = 0XE5 */ +const uint8_t DIR_NAME_0XE5 = 0X05; +/** name[0] value for entry that is free after being "deleted" */ +const uint8_t DIR_NAME_DELETED = 0XE5; +/** name[0] value for entry that is free and no allocated entries follow */ +const uint8_t DIR_NAME_FREE = 0X00; +/** file is read-only */ +const uint8_t DIR_ATT_READ_ONLY = 0X01; +/** File should e hidden in directory listings */ +const uint8_t DIR_ATT_HIDDEN = 0X02; +/** Entry is for a system file */ +const uint8_t DIR_ATT_SYSTEM = 0X04; +/** Directory entry contains the volume label */ +const uint8_t DIR_ATT_VOLUME_ID = 0X08; +/** Entry is for a directory */ +const uint8_t DIR_ATT_DIRECTORY = 0X10; +/** Old DOS archive bit for backup support */ +const uint8_t DIR_ATT_ARCHIVE = 0X20; +/** Test value for long name entry. Test is + (d->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME. */ +const uint8_t DIR_ATT_LONG_NAME = 0X0F; +/** Test mask for long name entry */ +const uint8_t DIR_ATT_LONG_NAME_MASK = 0X3F; +/** defined attribute bits */ +const uint8_t DIR_ATT_DEFINED_BITS = 0X3F; + +/** Mask for file/subdirectory tests */ +const uint8_t DIR_ATT_FILE_TYPE_MASK = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY); + +/** Filename base-name is all lower case */ +const uint8_t DIR_NT_LC_BASE = 0X08; +/** Filename extension is all lower case.*/ +const uint8_t DIR_NT_LC_EXT = 0X10; + + +/** Directory entry is for a file + * \param[in] dir Pointer to a directory entry. + * + * \return true if the entry is for a normal file else false. + */ +static inline uint8_t DIR_IS_FILE(const dir_t* dir) { + return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == 0; +} +/** Directory entry is for a file or subdirectory + * \param[in] dir Pointer to a directory entry. + * + * \return true if the entry is for a normal file or subdirectory else false. + */ +static inline uint8_t DIR_IS_FILE_OR_SUBDIR(const dir_t* dir) { + return (dir->attributes & DIR_ATT_VOLUME_ID) == 0; +} +/** Directory entry is part of a long name + * \param[in] dir Pointer to a directory entry. + * + * \return true if the entry is for part of a long name else false. + */ +static inline uint8_t DIR_IS_LONG_NAME(const dir_t* dir) { + return dir->attributes == DIR_ATT_LONG_NAME; +} +/** Directory entry is hidden + * \param[in] dir Pointer to a directory entry. + * + * \return true if the entry is hidden else false. + */ +static inline uint8_t DIR_IS_HIDDEN(const dir_t* dir) { + return dir->attributes & DIR_ATT_HIDDEN; +} +/** Directory entry is for a subdirectory + * \param[in] dir Pointer to a directory entry. + * + * \return true if the entry is for a subdirectory else false. + */ +static inline uint8_t DIR_IS_SUBDIR(const dir_t* dir) { + return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == DIR_ATT_DIRECTORY; +} +/** Directory entry is system type + * \param[in] dir Pointer to a directory entry. + * + * \return true if the entry is system else false. + */ +static inline uint8_t DIR_IS_SYSTEM(const dir_t* dir) { + return dir->attributes & DIR_ATT_SYSTEM; +} +/** date field for FAT directory entry + * \param[in] year [1980,2107] + * \param[in] month [1,12] + * \param[in] day [1,31] + * + * \return Packed date for dir_t entry. + */ +static inline uint16_t FAT_DATE(uint16_t year, uint8_t month, uint8_t day) { + return (year - 1980) << 9 | month << 5 | day; +} +/** year part of FAT directory date field + * \param[in] fatDate Date in packed dir format. + * + * \return Extracted year [1980,2107] + */ +static inline uint16_t FAT_YEAR(uint16_t fatDate) { + return 1980 + (fatDate >> 9); +} +/** month part of FAT directory date field + * \param[in] fatDate Date in packed dir format. + * + * \return Extracted month [1,12] + */ +static inline uint8_t FAT_MONTH(uint16_t fatDate) { + return (fatDate >> 5) & 0XF; +} +/** day part of FAT directory date field + * \param[in] fatDate Date in packed dir format. + * + * \return Extracted day [1,31] + */ +static inline uint8_t FAT_DAY(uint16_t fatDate) { + return fatDate & 0X1F; +} +/** time field for FAT directory entry + * \param[in] hour [0,23] + * \param[in] minute [0,59] + * \param[in] second [0,59] + * + * \return Packed time for dir_t entry. + */ +static inline uint16_t FAT_TIME(uint8_t hour, uint8_t minute, uint8_t second) { + return hour << 11 | minute << 5 | second >> 1; +} +/** hour part of FAT directory time field + * \param[in] fatTime Time in packed dir format. + * + * \return Extracted hour [0,23] + */ +static inline uint8_t FAT_HOUR(uint16_t fatTime) { + return fatTime >> 11; +} +/** minute part of FAT directory time field + * \param[in] fatTime Time in packed dir format. + * + * \return Extracted minute [0,59] + */ +static inline uint8_t FAT_MINUTE(uint16_t fatTime) { + return (fatTime >> 5) & 0X3F; +} +/** second part of FAT directory time field + * \note second/2 is stored in packed time. + * + * \param[in] fatTime Time in packed dir format. + * + * \return Extracted second [0,58] + */ +static inline uint8_t FAT_SECOND(uint16_t fatTime) { + return 2*(fatTime & 0X1F); +} +/** Default date for file timestamps is 1 Jan 2000 */ +const uint16_t FAT_DEFAULT_DATE = ((2000 - 1980) << 9) | (1 << 5) | 1; +/** Default time for file timestamp is 1 am */ +const uint16_t FAT_DEFAULT_TIME = (1 << 11); +//------------------------------------------------------------------------------ +/** Dimension of first name field in long directory entry */ +const uint8_t LDIR_NAME1_DIM = 5; +/** Dimension of first name field in long directory entry */ +const uint8_t LDIR_NAME2_DIM = 6; +/** Dimension of first name field in long directory entry */ +const uint8_t LDIR_NAME3_DIM = 2; +/** + * \struct longDirectoryEntry + * \brief FAT long directory entry + */ +struct longDirectoryEntry { + /** + * The order of this entry in the sequence of long dir entries + * associated with the short dir entry at the end of the long dir set. + * + * If masked with 0X40 (LAST_LONG_ENTRY), this indicates the + * entry is the last long dir entry in a set of long dir entries. + * All valid sets of long dir entries must begin with an entry having + * this mask. + */ + uint8_t ord; + /** Characters 1-5 of the long-name sub-component in this entry. */ + uint16_t name1[LDIR_NAME1_DIM]; + /** Attributes - must be ATTR_LONG_NAME */ + uint8_t attr; + /** + * If zero, indicates a directory entry that is a sub-component of a + * long name. NOTE: Other values reserved for future extensions. + * + * Non-zero implies other directory entry types. + */ + uint8_t type; + /** + * Checksum of name in the short dir entry at the end of the + * long dir set. + */ + uint8_t chksum; + /** Characters 6-11 of the long-name sub-component in this entry. */ + uint16_t name2[LDIR_NAME2_DIM]; + /** Must be ZERO. This is an artifact of the FAT "first cluster" */ + uint16_t mustBeZero; + /** Characters 12 and 13 of the long-name sub-component in this entry. */ + uint16_t name3[LDIR_NAME3_DIM]; +} __attribute__((packed)); +/** Type name for longDirectoryEntry */ +typedef struct longDirectoryEntry ldir_t; +/** + * Ord mast that indicates the entry is the last long dir entry in a + * set of long dir entries. All valid sets of long dir entries must + * begin with an entry having this mask. + */ +const uint8_t LDIR_ORD_LAST_LONG_ENTRY = 0X40; +#endif // FatStructs_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatVolume.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatVolume.cpp new file mode 100644 index 0000000..ceb9068 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatVolume.cpp @@ -0,0 +1,614 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#include +#include "FatVolume.h" +//------------------------------------------------------------------------------ +cache_t* FatCache::read(uint32_t lbn, uint8_t option) { + if (m_lbn != lbn) { + if (!sync()) { + DBG_FAIL_MACRO; + goto fail; + } + if (!(option & CACHE_OPTION_NO_READ)) { + if (!m_vol->readBlock(lbn, m_block.data)) { + DBG_FAIL_MACRO; + goto fail; + } + } + m_status = 0; + m_lbn = lbn; + } + m_status |= option & CACHE_STATUS_MASK; + return &m_block; + +fail: + + return 0; +} +//------------------------------------------------------------------------------ +bool FatCache::sync() { + if (m_status & CACHE_STATUS_DIRTY) { + if (!m_vol->writeBlock(m_lbn, m_block.data)) { + DBG_FAIL_MACRO; + goto fail; + } + // mirror second FAT + if (m_status & CACHE_STATUS_MIRROR_FAT) { + uint32_t lbn = m_lbn + m_vol->blocksPerFat(); + if (!m_vol->writeBlock(lbn, m_block.data)) { + DBG_FAIL_MACRO; + goto fail; + } + } + m_status &= ~CACHE_STATUS_DIRTY; + } + return true; + +fail: + return false; +} +//------------------------------------------------------------------------------ +bool FatVolume::allocateCluster(uint32_t current, uint32_t* next) { + uint32_t find; + bool setStart; + if (m_allocSearchStart < current) { + // Try to keep file contiguous. Start just after current cluster. + find = current; + setStart = false; + } else { + find = m_allocSearchStart; + setStart = true; + } + while (1) { + find++; + if (find > m_lastCluster) { + if (setStart) { + // Can't find space, checked all clusters. + DBG_FAIL_MACRO; + goto fail; + } + find = m_allocSearchStart; + setStart = true; + continue; + } + if (find == current) { + // Can't find space, already searched clusters after current. + DBG_FAIL_MACRO; + goto fail; + } + uint32_t f; + int8_t fg = fatGet(find, &f); + if (fg < 0) { + DBG_FAIL_MACRO; + goto fail; + } + if (fg && f == 0) { + break; + } + } + if (setStart) { + m_allocSearchStart = find; + } + // Mark end of chain. + if (!fatPutEOC(find)) { + DBG_FAIL_MACRO; + goto fail; + } + if (current) { + // Link clusters. + if (!fatPut(current, find)) { + DBG_FAIL_MACRO; + goto fail; + } + } + updateFreeClusterCount(-1); + *next = find; + return true; + +fail: + return false; +} +//------------------------------------------------------------------------------ +// find a contiguous group of clusters +bool FatVolume::allocContiguous(uint32_t count, uint32_t* firstCluster) { + // flag to save place to start next search + bool setStart = true; + // start of group + uint32_t bgnCluster; + // end of group + uint32_t endCluster; + // Start at cluster after last allocated cluster. + endCluster = bgnCluster = m_allocSearchStart + 1; + + // search the FAT for free clusters + while (1) { + if (endCluster > m_lastCluster) { + // Can't find space. + DBG_FAIL_MACRO; + goto fail; + } + uint32_t f; + int8_t fg = fatGet(endCluster, &f); + if (fg < 0) { + DBG_FAIL_MACRO; + goto fail; + } + if (f || fg == 0) { + // don't update search start if unallocated clusters before endCluster. + if (bgnCluster != endCluster) { + setStart = false; + } + // cluster in use try next cluster as bgnCluster + bgnCluster = endCluster + 1; + } else if ((endCluster - bgnCluster + 1) == count) { + // done - found space + break; + } + endCluster++; + } + // Remember possible next free cluster. + if (setStart) { + m_allocSearchStart = endCluster; + } + // mark end of chain + if (!fatPutEOC(endCluster)) { + DBG_FAIL_MACRO; + goto fail; + } + // link clusters + while (endCluster > bgnCluster) { + if (!fatPut(endCluster - 1, endCluster)) { + DBG_FAIL_MACRO; + goto fail; + } + endCluster--; + } + // Maintain count of free clusters. + updateFreeClusterCount(-count); + + // return first cluster number to caller + *firstCluster = bgnCluster; + return true; + +fail: + return false; +} +//------------------------------------------------------------------------------ +uint32_t FatVolume::clusterFirstBlock(uint32_t cluster) const { + return m_dataStartBlock + ((cluster - 2) << m_clusterSizeShift); +} +//------------------------------------------------------------------------------ +// Fetch a FAT entry - return -1 error, 0 EOC, else 1. +int8_t FatVolume::fatGet(uint32_t cluster, uint32_t* value) { + uint32_t lba; + uint32_t next; + cache_t* pc; + + // error if reserved cluster of beyond FAT + if (cluster < 2 || cluster > m_lastCluster) { + DBG_FAIL_MACRO; + goto fail; + } + + if (fatType() == 32) { + lba = m_fatStartBlock + (cluster >> 7); + pc = cacheFetchFat(lba, FatCache::CACHE_FOR_READ); + if (!pc) { + DBG_FAIL_MACRO; + goto fail; + } + next = pc->fat32[cluster & 0X7F] & FAT32MASK; + goto done; + } + if (fatType() == 16) { + lba = m_fatStartBlock + ((cluster >> 8) & 0XFF); + pc = cacheFetchFat(lba, FatCache::CACHE_FOR_READ); + if (!pc) { + DBG_FAIL_MACRO; + goto fail; + } + next = pc->fat16[cluster & 0XFF]; + goto done; + } + if (FAT12_SUPPORT && fatType() == 12) { + uint16_t index = cluster; + index += index >> 1; + lba = m_fatStartBlock + (index >> 9); + pc = cacheFetchFat(lba, FatCache::CACHE_FOR_READ); + if (!pc) { + DBG_FAIL_MACRO; + goto fail; + } + index &= 0X1FF; + uint16_t tmp = pc->data[index]; + index++; + if (index == 512) { + pc = cacheFetchFat(lba + 1, FatCache::CACHE_FOR_READ); + if (!pc) { + DBG_FAIL_MACRO; + goto fail; + } + index = 0; + } + tmp |= pc->data[index] << 8; + next = cluster & 1 ? tmp >> 4 : tmp & 0XFFF; + goto done; + } else { + DBG_FAIL_MACRO; + goto fail; + } +done: + if (isEOC(next)) { + return 0; + } + *value = next; + return 1; + +fail: + return -1; +} +//------------------------------------------------------------------------------ +// Store a FAT entry +bool FatVolume::fatPut(uint32_t cluster, uint32_t value) { + uint32_t lba; + cache_t* pc; + + // error if reserved cluster of beyond FAT + if (cluster < 2 || cluster > m_lastCluster) { + DBG_FAIL_MACRO; + goto fail; + } + + if (fatType() == 32) { + lba = m_fatStartBlock + (cluster >> 7); + pc = cacheFetchFat(lba, FatCache::CACHE_FOR_WRITE); + if (!pc) { + DBG_FAIL_MACRO; + goto fail; + } + pc->fat32[cluster & 0X7F] = value; + return true; + } + + if (fatType() == 16) { + lba = m_fatStartBlock + ((cluster >> 8) & 0XFF); + pc = cacheFetchFat(lba, FatCache::CACHE_FOR_WRITE); + if (!pc) { + DBG_FAIL_MACRO; + goto fail; + } + pc->fat16[cluster & 0XFF] = value; + return true; + } + + if (FAT12_SUPPORT && fatType() == 12) { + uint16_t index = cluster; + index += index >> 1; + lba = m_fatStartBlock + (index >> 9); + pc = cacheFetchFat(lba, FatCache::CACHE_FOR_WRITE); + if (!pc) { + DBG_FAIL_MACRO; + goto fail; + } + index &= 0X1FF; + uint8_t tmp = value; + if (cluster & 1) { + tmp = (pc->data[index] & 0XF) | tmp << 4; + } + pc->data[index] = tmp; + + index++; + if (index == 512) { + lba++; + index = 0; + pc = cacheFetchFat(lba, FatCache::CACHE_FOR_WRITE); + if (!pc) { + DBG_FAIL_MACRO; + goto fail; + } + } + tmp = value >> 4; + if (!(cluster & 1)) { + tmp = ((pc->data[index] & 0XF0)) | tmp >> 4; + } + pc->data[index] = tmp; + return true; + } else { + DBG_FAIL_MACRO; + goto fail; + } + +fail: + return false; +} +//------------------------------------------------------------------------------ +// free a cluster chain +bool FatVolume::freeChain(uint32_t cluster) { + uint32_t next; + int8_t fg; + do { + fg = fatGet(cluster, &next); + if (fg < 0) { + DBG_FAIL_MACRO; + goto fail; + } + // free cluster + if (!fatPut(cluster, 0)) { + DBG_FAIL_MACRO; + goto fail; + } + // Add one to count of free clusters. + updateFreeClusterCount(1); + + if (cluster <= m_allocSearchStart) { + m_allocSearchStart = cluster - 1; + } + cluster = next; + } while (fg); + + return true; + +fail: + return false; +} +//------------------------------------------------------------------------------ +int32_t FatVolume::freeClusterCount() { +#if MAINTAIN_FREE_CLUSTER_COUNT + if (m_freeClusterCount >= 0) { + return m_freeClusterCount; + } +#endif // MAINTAIN_FREE_CLUSTER_COUNT + uint32_t free = 0; + uint32_t lba; + uint32_t todo = m_lastCluster + 1; + uint16_t n; + + if (FAT12_SUPPORT && fatType() == 12) { + for (unsigned i = 2; i < todo; i++) { + uint32_t c; + int8_t fg = fatGet(i, &c); + if (fg < 0) { + DBG_FAIL_MACRO; + goto fail; + } + if (fg && c == 0) { + free++; + } + } + } else if (fatType() == 16 || fatType() == 32) { + lba = m_fatStartBlock; + while (todo) { + cache_t* pc = cacheFetchFat(lba++, FatCache::CACHE_FOR_READ); + if (!pc) { + DBG_FAIL_MACRO; + goto fail; + } + n = fatType() == 16 ? 256 : 128; + if (todo < n) { + n = todo; + } + if (fatType() == 16) { + for (uint16_t i = 0; i < n; i++) { + if (pc->fat16[i] == 0) { + free++; + } + } + } else { + for (uint16_t i = 0; i < n; i++) { + if (pc->fat32[i] == 0) { + free++; + } + } + } + todo -= n; + } + } else { + // invalid FAT type + DBG_FAIL_MACRO; + goto fail; + } + setFreeClusterCount(free); + return free; + +fail: + return -1; +} +//------------------------------------------------------------------------------ +bool FatVolume::init(uint8_t part) { + uint32_t clusterCount; + uint32_t totalBlocks; + uint32_t volumeStartBlock = 0; + fat32_boot_t* fbs; + cache_t* pc; + uint8_t tmp; + m_fatType = 0; + m_allocSearchStart = 1; + m_cache.init(this); +#if USE_SEPARATE_FAT_CACHE + m_fatCache.init(this); +#endif // USE_SEPARATE_FAT_CACHE + // if part == 0 assume super floppy with FAT boot sector in block zero + // if part > 0 assume mbr volume with partition table + if (part) { + if (part > 4) { + DBG_FAIL_MACRO; + goto fail; + } + pc = cacheFetchData(0, FatCache::CACHE_FOR_READ); + if (!pc) { + DBG_FAIL_MACRO; + goto fail; + } + part_t* p = &pc->mbr.part[part - 1]; + if ((p->boot & 0X7F) != 0 || p->firstSector == 0) { + // not a valid partition + DBG_FAIL_MACRO; + goto fail; + } + volumeStartBlock = p->firstSector; + } + pc = cacheFetchData(volumeStartBlock, FatCache::CACHE_FOR_READ); + if (!pc) { + DBG_FAIL_MACRO; + goto fail; + } + fbs = &(pc->fbs32); + if (fbs->bytesPerSector != 512 || + fbs->fatCount != 2 || + fbs->reservedSectorCount == 0) { + // not valid FAT volume + DBG_FAIL_MACRO; + goto fail; + } + m_blocksPerCluster = fbs->sectorsPerCluster; + m_clusterBlockMask = m_blocksPerCluster - 1; + // determine shift that is same as multiply by m_blocksPerCluster + m_clusterSizeShift = 0; + for (tmp = 1; m_blocksPerCluster != tmp; tmp <<= 1, m_clusterSizeShift++) { + if (tmp == 0) { + DBG_FAIL_MACRO; + goto fail; + } + } + m_blocksPerFat = fbs->sectorsPerFat16 ? + fbs->sectorsPerFat16 : fbs->sectorsPerFat32; + + m_fatStartBlock = volumeStartBlock + fbs->reservedSectorCount; + + // count for FAT16 zero for FAT32 + m_rootDirEntryCount = fbs->rootDirEntryCount; + + // directory start for FAT16 dataStart for FAT32 + m_rootDirStart = m_fatStartBlock + 2 * m_blocksPerFat; + // data start for FAT16 and FAT32 + m_dataStartBlock = m_rootDirStart + ((32 * fbs->rootDirEntryCount + 511)/512); + + // total blocks for FAT16 or FAT32 + totalBlocks = fbs->totalSectors16 ? + fbs->totalSectors16 : fbs->totalSectors32; + // total data blocks + clusterCount = totalBlocks - (m_dataStartBlock - volumeStartBlock); + + // divide by cluster size to get cluster count + clusterCount >>= m_clusterSizeShift; + m_lastCluster = clusterCount + 1; + + // Indicate unknown number of free clusters. + setFreeClusterCount(-1); + // FAT type is determined by cluster count + if (clusterCount < 4085) { + m_fatType = 12; + if (!FAT12_SUPPORT) { + DBG_FAIL_MACRO; + goto fail; + } + } else if (clusterCount < 65525) { + m_fatType = 16; + } else { + m_rootDirStart = fbs->fat32RootCluster; + m_fatType = 32; + } + return true; + +fail: + return false; +} +//------------------------------------------------------------------------------ +bool FatVolume::wipe(print_t* pr) { + cache_t* cache; + uint16_t count; + uint32_t lbn; + if (!fatType()) { + DBG_FAIL_MACRO; + goto fail; + } + cache = cacheClear(); + if (!cache) { + DBG_FAIL_MACRO; + goto fail; + } + memset(cache->data, 0, 512); + // Zero root. + if (fatType() == 32) { + lbn = clusterFirstBlock(m_rootDirStart); + count = m_blocksPerCluster; + } else { + lbn = m_rootDirStart; + count = m_rootDirEntryCount/16; + } + for (uint32_t n = 0; n < count; n++) { + if (!writeBlock(lbn + n, cache->data)) { + DBG_FAIL_MACRO; + goto fail; + } + } + // Clear FATs. + count = 2*m_blocksPerFat; + lbn = m_fatStartBlock; + for (uint32_t nb = 0; nb < count; nb++) { + if (pr && (nb & 0XFF) == 0) { + pr->write('.'); + } + if (!writeBlock(lbn + nb, cache->data)) { + DBG_FAIL_MACRO; + goto fail; + } + } + // Reserve first two clusters. + if (fatType() == 32) { + cache->fat32[0] = 0x0FFFFFF8; + cache->fat32[1] = 0x0FFFFFFF; + } else if (fatType() == 16) { + cache->fat16[0] = 0XFFF8; + cache->fat16[1] = 0XFFFF; + } else if (FAT12_SUPPORT && fatType() == 12) { + cache->fat32[0] = 0XFFFFF8; + } else { + DBG_FAIL_MACRO; + goto fail; + } + if (!writeBlock(m_fatStartBlock, cache->data) || + !writeBlock(m_fatStartBlock + m_blocksPerFat, cache->data)) { + DBG_FAIL_MACRO; + goto fail; + } + if (fatType() == 32) { + // Reserve root cluster. + if (!fatPutEOC(m_rootDirStart) || !cacheSync()) { + DBG_FAIL_MACRO; + goto fail; + } + } + if (pr) { + pr->write('\r'); + pr->write('\n'); + } + m_fatType = 0; + return true; + +fail: + m_fatType = 0; + return false; +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatVolume.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatVolume.h new file mode 100644 index 0000000..96f16b0 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatVolume.h @@ -0,0 +1,375 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 FatVolume_h +#define FatVolume_h +/** + * \file + * \brief FatVolume class + */ +#include +#include "FatLibConfig.h" +#include "FatStructs.h" +#include "BlockDriver.h" +//------------------------------------------------------------------------------ +#ifndef DOXYGEN_SHOULD_SKIP_THIS +/** Macro for debug. */ +#define DEBUG_MODE 0 +#if DEBUG_MODE +#define DBG_FAIL_MACRO Serial.print(F(__FILE__)); Serial.println(__LINE__); +#define DBG_PRINT_IF(b) if (b) {Serial.println(F(#b)); DBG_FAIL_MACRO;} +#define DBG_HALT_IF(b) if (b) {Serial.println(F(#b));\ + DBG_FAIL_MACRO; while (1);} +#else // DEBUG_MODE +#define DBG_FAIL_MACRO +#define DBG_PRINT_IF(b) +#define DBG_HALT_IF(b) +#endif // DEBUG_MODE +#endif // DOXYGEN_SHOULD_SKIP_THIS +//------------------------------------------------------------------------------ +#if ENABLE_ARDUINO_FEATURES +/** Use Print for Arduino */ +typedef Print print_t; +#else // ENABLE_ARDUINO_FEATURES +/** + * \class CharWriter + * \brief Character output - often serial port. + */ +class CharWriter { + public: + virtual size_t write(char c) = 0; + virtual size_t write(const char* s) = 0; +}; +typedef CharWriter print_t; +#endif // ENABLE_ARDUINO_FEATURES +//------------------------------------------------------------------------------ +// Forward declaration of FatVolume. +class FatVolume; +//------------------------------------------------------------------------------ +/** + * \brief Cache for an raw data block. + */ +union cache_t { + /** Used to access cached file data blocks. */ + uint8_t data[512]; + /** Used to access cached FAT16 entries. */ + uint16_t fat16[256]; + /** Used to access cached FAT32 entries. */ + uint32_t fat32[128]; + /** Used to access cached directory entries. */ + dir_t dir[16]; + /** Used to access a cached Master Boot Record. */ + mbr_t mbr; + /** Used to access to a cached FAT boot sector. */ + fat_boot_t fbs; + /** Used to access to a cached FAT32 boot sector. */ + fat32_boot_t fbs32; + /** Used to access to a cached FAT32 FSINFO sector. */ + fat32_fsinfo_t fsinfo; +}; +//============================================================================== +/** + * \class FatCache + * \brief Block cache. + */ +class FatCache { + public: + /** Cached block is dirty */ + static const uint8_t CACHE_STATUS_DIRTY = 1; + /** Cashed block is FAT entry and must be mirrored in second FAT. */ + static const uint8_t CACHE_STATUS_MIRROR_FAT = 2; + /** Cache block status bits */ + static const uint8_t CACHE_STATUS_MASK + = CACHE_STATUS_DIRTY | CACHE_STATUS_MIRROR_FAT; + /** Sync existing block but do not read new block. */ + static const uint8_t CACHE_OPTION_NO_READ = 4; + /** Cache block for read. */ + static const uint8_t CACHE_FOR_READ = 0; + /** Cache block for write. */ + static const uint8_t CACHE_FOR_WRITE = CACHE_STATUS_DIRTY; + /** Reserve cache block for write - do not read from block device. */ + static const uint8_t CACHE_RESERVE_FOR_WRITE + = CACHE_STATUS_DIRTY | CACHE_OPTION_NO_READ; + /** \return Cache block address. */ + cache_t* block() { + return &m_block; + } + /** Set current block dirty. */ + void dirty() { + m_status |= CACHE_STATUS_DIRTY; + } + /** Initialize the cache. + * \param[in] vol FatVolume that owns this FatCache. + */ + void init(FatVolume *vol) { + m_vol = vol; + invalidate(); + } + /** Invalidate current cache block. */ + void invalidate() { + m_status = 0; + m_lbn = 0XFFFFFFFF; + } + /** \return dirty status */ + bool isDirty() { + return m_status & CACHE_STATUS_DIRTY; + } + /** \return Logical block number for cached block. */ + uint32_t lbn() { + return m_lbn; + } + /** Read a block into the cache. + * \param[in] lbn Block to read. + * \param[in] option mode for cached block. + * \return Address of cached block. */ + cache_t* read(uint32_t lbn, uint8_t option); + /** Write current block if dirty. + * \return true for success else false. + */ + bool sync(); + + private: + uint8_t m_status; + FatVolume* m_vol; + uint32_t m_lbn; + cache_t m_block; +}; +//============================================================================== +/** + * \class FatVolume + * \brief Access FAT16 and FAT32 volumes on raw file devices. + */ +class FatVolume { + public: + /** Create an instance of FatVolume + */ + FatVolume() : m_fatType(0) {} + + /** \return The volume's cluster size in blocks. */ + uint8_t blocksPerCluster() const { + return m_blocksPerCluster; + } + /** \return The number of blocks in one FAT. */ + uint32_t blocksPerFat() const { + return m_blocksPerFat; + } + /** Clear the cache and returns a pointer to the cache. Not for normal apps. + * \return A pointer to the cache buffer or zero if an error occurs. + */ + cache_t* cacheClear() { + if (!cacheSync()) { + return 0; + } + m_cache.invalidate(); + return m_cache.block(); + } + /** \return The total number of clusters in the volume. */ + uint32_t clusterCount() const { + return m_lastCluster - 1; + } + /** \return The shift count required to multiply by blocksPerCluster. */ + uint8_t clusterSizeShift() const { + return m_clusterSizeShift; + } + /** \return The logical block number for the start of file data. */ + uint32_t dataStartBlock() const { + return m_dataStartBlock; + } + /** \return The number of File Allocation Tables. */ + uint8_t fatCount() { + return 2; + } + /** \return The logical block number for the start of the first FAT. */ + uint32_t fatStartBlock() const { + return m_fatStartBlock; + } + /** \return The FAT type of the volume. Values are 12, 16 or 32. */ + uint8_t fatType() const { + return m_fatType; + } + /** Volume free space in clusters. + * + * \return Count of free clusters for success or -1 if an error occurs. + */ + int32_t freeClusterCount(); + /** Initialize a FAT volume. Try partition one first then try super + * floppy format. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool init() { + return init(1) || init(0); + } + /** Initialize a FAT volume. + + * \param[in] part The partition to be used. Legal values for \a part are + * 1-4 to use the corresponding partition on a device formatted with + * a MBR, Master Boot Record, or zero if the device is formatted as + * a super floppy with the FAT boot sector in block zero. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool init(uint8_t part); + /** \return The number of entries in the root directory for FAT16 volumes. */ + uint16_t rootDirEntryCount() const { + return m_rootDirEntryCount; + } + /** \return The logical block number for the start of the root directory + on FAT16 volumes or the first cluster number on FAT32 volumes. */ + uint32_t rootDirStart() const { + return m_rootDirStart; + } + /** \return The number of blocks in the volume */ + uint32_t volumeBlockCount() const { + return blocksPerCluster()*clusterCount(); + } + /** Wipe all data from the volume. + * \param[in] pr print stream for status dots. + * \return true for success else false. + */ + bool wipe(print_t* pr = 0); + /** Debug access to FAT table + * + * \param[in] n cluster number. + * \param[out] v value of entry + * \return -1 error, 0 EOC, else 1. + */ + int8_t dbgFat(uint32_t n, uint32_t* v) { + return fatGet(n, v); + } +//------------------------------------------------------------------------------ + private: + // Allow FatFile and FatCache access to FatVolume private functions. + friend class FatCache; ///< Allow access to FatVolume. + friend class FatFile; ///< Allow access to FatVolume. + friend class FatFileSystem; ///< Allow access to FatVolume. +//------------------------------------------------------------------------------ + BlockDriver* m_blockDev; // block device + uint8_t m_blocksPerCluster; // Cluster size in blocks. + uint8_t m_clusterBlockMask; // Mask to extract block of cluster. + uint8_t m_clusterSizeShift; // Cluster count to block count shift. + uint8_t m_fatType; // Volume type (12, 16, OR 32). + uint16_t m_rootDirEntryCount; // Number of entries in FAT16 root dir. + uint32_t m_allocSearchStart; // Start cluster for alloc search. + uint32_t m_blocksPerFat; // FAT size in blocks + uint32_t m_dataStartBlock; // First data block number. + uint32_t m_fatStartBlock; // Start block for first FAT. + uint32_t m_lastCluster; // Last cluster number in FAT. + uint32_t m_rootDirStart; // Start block for FAT16, cluster for FAT32. +//------------------------------------------------------------------------------ + // block I/O functions. + bool readBlock(uint32_t block, uint8_t* dst) { + return m_blockDev->readBlock(block, dst); + } + bool syncBlocks() { + return m_blockDev->syncBlocks(); + } + bool writeBlock(uint32_t block, const uint8_t* src) { + return m_blockDev->writeBlock(block, src); + } +#if USE_MULTI_BLOCK_IO + bool readBlocks(uint32_t block, uint8_t* dst, size_t nb) { + return m_blockDev->readBlocks(block, dst, nb); + } + bool writeBlocks(uint32_t block, const uint8_t* src, size_t nb) { + return m_blockDev->writeBlocks(block, src, nb); + } +#endif // USE_MULTI_BLOCK_IO +#if MAINTAIN_FREE_CLUSTER_COUNT + int32_t m_freeClusterCount; // Count of free clusters in volume. + void setFreeClusterCount(int32_t value) { + m_freeClusterCount = value; + } + void updateFreeClusterCount(int32_t change) { + if (m_freeClusterCount >= 0) { + m_freeClusterCount += change; + } + } +#else // MAINTAIN_FREE_CLUSTER_COUNT + void setFreeClusterCount(int32_t value) { + (void)value; + } + void updateFreeClusterCount(int32_t change) { + (void)change; + } +#endif // MAINTAIN_FREE_CLUSTER_COUNT + +// block caches + FatCache m_cache; +#if USE_SEPARATE_FAT_CACHE + FatCache m_fatCache; + cache_t* cacheFetchFat(uint32_t blockNumber, uint8_t options) { + return m_fatCache.read(blockNumber, + options | FatCache::CACHE_STATUS_MIRROR_FAT); + } + bool cacheSync() { + return m_cache.sync() && m_fatCache.sync() && syncBlocks(); + } +#else // + cache_t* cacheFetchFat(uint32_t blockNumber, uint8_t options) { + return cacheFetchData(blockNumber, + options | FatCache::CACHE_STATUS_MIRROR_FAT); + } + bool cacheSync() { + return m_cache.sync() && syncBlocks(); + } +#endif // USE_SEPARATE_FAT_CACHE + cache_t* cacheFetchData(uint32_t blockNumber, uint8_t options) { + return m_cache.read(blockNumber, options); + } + void cacheInvalidate() { + m_cache.invalidate(); + } + bool cacheSyncData() { + return m_cache.sync(); + } + cache_t *cacheAddress() { + return m_cache.block(); + } + uint32_t cacheBlockNumber() { + return m_cache.lbn(); + } + void cacheDirty() { + m_cache.dirty(); + } +//------------------------------------------------------------------------------ + bool allocateCluster(uint32_t current, uint32_t* next); + bool allocContiguous(uint32_t count, uint32_t* firstCluster); + uint8_t blockOfCluster(uint32_t position) const { + return (position >> 9) & m_clusterBlockMask; + } + uint32_t clusterFirstBlock(uint32_t cluster) const; + int8_t fatGet(uint32_t cluster, uint32_t* value); + bool fatPut(uint32_t cluster, uint32_t value); + bool fatPutEOC(uint32_t cluster) { + return fatPut(cluster, 0x0FFFFFFF); + } + bool freeChain(uint32_t cluster); + bool isEOC(uint32_t cluster) const { + return cluster > m_lastCluster; + } +}; +#endif // FatVolume diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FmtNumber.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FmtNumber.cpp new file mode 100644 index 0000000..a318ab5 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FmtNumber.cpp @@ -0,0 +1,460 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#include "FmtNumber.h" +// Use Stimmer div/mod 10 on avr +#ifdef __AVR__ +#include +#define USE_STIMMER +#endif // __AVR__ +//------------------------------------------------------------------------------ +// Stimmer div/mod 10 for AVR +// this code fragment works out i/10 and i%10 by calculating +// i*(51/256)*(256/255)/2 == i*51/510 == i/10 +// by "j.k" I mean 32.8 fixed point, j is integer part, k is fractional part +// j.k = ((j+1.0)*51.0)/256.0 +// (we add 1 because we will be using the floor of the result later) +// divmod10_asm16 and divmod10_asm32 are public domain code by Stimmer. +// http://forum.arduino.cc/index.php?topic=167414.msg1293679#msg1293679 +#define divmod10_asm16(in32, mod8, tmp8) \ +asm volatile( \ + " ldi %2,51 \n\t" \ + " mul %A0,%2 \n\t" \ + " clr %A0 \n\t" \ + " add r0,%2 \n\t" \ + " adc %A0,r1 \n\t" \ + " mov %1,r0 \n\t" \ + " mul %B0,%2 \n\t" \ + " clr %B0 \n\t" \ + " add %A0,r0 \n\t" \ + " adc %B0,r1 \n\t" \ + " clr r1 \n\t" \ + " add %1,%A0 \n\t" \ + " adc %A0,%B0 \n\t" \ + " adc %B0,r1 \n\t" \ + " add %1,%B0 \n\t" \ + " adc %A0,r1 \n\t" \ + " adc %B0,r1 \n\t" \ + " lsr %B0 \n\t" \ + " ror %A0 \n\t" \ + " ror %1 \n\t" \ + " ldi %2,10 \n\t" \ + " mul %1,%2 \n\t" \ + " mov %1,r1 \n\t" \ + " clr r1 \n\t" \ + :"+r"(in32), "=d"(mod8), "=d"(tmp8) : : "r0") + +#define divmod10_asm32(in32, mod8, tmp8) \ +asm volatile( \ + " ldi %2,51 \n\t" \ + " mul %A0,%2 \n\t" \ + " clr %A0 \n\t" \ + " add r0,%2 \n\t" \ + " adc %A0,r1 \n\t" \ + " mov %1,r0 \n\t" \ + " mul %B0,%2 \n\t" \ + " clr %B0 \n\t" \ + " add %A0,r0 \n\t" \ + " adc %B0,r1 \n\t" \ + " mul %C0,%2 \n\t" \ + " clr %C0 \n\t" \ + " add %B0,r0 \n\t" \ + " adc %C0,r1 \n\t" \ + " mul %D0,%2 \n\t" \ + " clr %D0 \n\t" \ + " add %C0,r0 \n\t" \ + " adc %D0,r1 \n\t" \ + " clr r1 \n\t" \ + " add %1,%A0 \n\t" \ + " adc %A0,%B0 \n\t" \ + " adc %B0,%C0 \n\t" \ + " adc %C0,%D0 \n\t" \ + " adc %D0,r1 \n\t" \ + " add %1,%B0 \n\t" \ + " adc %A0,%C0 \n\t" \ + " adc %B0,%D0 \n\t" \ + " adc %C0,r1 \n\t" \ + " adc %D0,r1 \n\t" \ + " add %1,%D0 \n\t" \ + " adc %A0,r1 \n\t" \ + " adc %B0,r1 \n\t" \ + " adc %C0,r1 \n\t" \ + " adc %D0,r1 \n\t" \ + " lsr %D0 \n\t" \ + " ror %C0 \n\t" \ + " ror %B0 \n\t" \ + " ror %A0 \n\t" \ + " ror %1 \n\t" \ + " ldi %2,10 \n\t" \ + " mul %1,%2 \n\t" \ + " mov %1,r1 \n\t" \ + " clr r1 \n\t" \ + :"+r"(in32), "=d"(mod8), "=d"(tmp8) : : "r0") +//------------------------------------------------------------------------------ +/* +// C++ code is based on this version of divmod10 by robtillaart. +// http://forum.arduino.cc/index.php?topic=167414.msg1246851#msg1246851 +// from robtillaart post: +// The code is based upon the divu10() code from the book Hackers Delight1. +// My insight was that the error formula in divu10() was in fact modulo 10 +// but not always. Sometimes it was 10 more. +void divmod10(uint32_t in, uint32_t &div, uint32_t &mod) +{ + // q = in * 0.8; + uint32_t q = (in >> 1) + (in >> 2); + q = q + (q >> 4); + q = q + (q >> 8); + q = q + (q >> 16); // not needed for 16 bit version + + // q = q / 8; ==> q = in *0.1; + q = q >> 3; + + // determine error + uint32_t r = in - ((q << 3) + (q << 1)); // r = in - q*10; + div = q + (r > 9); + if (r > 9) mod = r - 10; + else mod = r; +} +// Hackers delight function is here: +// http://www.hackersdelight.org/hdcodetxt/divuc.c.txt +// Code below uses 8/10 = 0.1100 1100 1100 1100 1100 1100 1100 1100. +// 15 ops including the multiply, or 17 elementary ops. +unsigned divu10(unsigned n) { + unsigned q, r; + + q = (n >> 1) + (n >> 2); + q = q + (q >> 4); + q = q + (q >> 8); + q = q + (q >> 16); + q = q >> 3; + r = n - q*10; + return q + ((r + 6) >> 4); +// return q + (r > 9); +} +*/ +//------------------------------------------------------------------------------ +#ifndef DOXYGEN_SHOULD_SKIP_THIS +#ifdef __AVR__ +static const float m[] PROGMEM = {1e-1, 1e-2, 1e-4, 1e-8, 1e-16, 1e-32}; +static const float p[] PROGMEM = {1e+1, 1e+2, 1e+4, 1e+8, 1e+16, 1e+32}; +#else // __AVR__ +static const float m[] = {1e-1, 1e-2, 1e-4, 1e-8, 1e-16, 1e-32}; +static const float p[] = {1e+1, 1e+2, 1e+4, 1e+8, 1e+16, 1e+32}; +#endif // __AVR__ +#endif // DOXYGEN_SHOULD_SKIP_THIS +// scale float v by power of ten. return v*10^n +float scale10(float v, int8_t n) { + const float *s; + if (n < 0) { + n = -n; + s = m; + } else { + s = p; + } + n &= 63; + for (uint8_t i = 0; n; n >>= 1, i++) { +#ifdef __AVR__ + if (n & 1) { + v *= pgm_read_float(&s[i]); + } +#else // __AVR__ + if (n & 1) { + v *= s[i]; + } +#endif // __AVR__ + } + return v; +} +//------------------------------------------------------------------------------ +// Format 16-bit unsigned +char* fmtDec(uint16_t n, char* p) { + while (n > 9) { +#ifdef USE_STIMMER + uint8_t tmp8, r; + divmod10_asm16(n, r, tmp8); +#else // USE_STIMMER + uint16_t t = n; + n = (n >> 1) + (n >> 2); + n = n + (n >> 4); + n = n + (n >> 8); + // n = n + (n >> 16); // no code for 16-bit n + n = n >> 3; + uint8_t r = t - (((n << 2) + n) << 1); + if (r > 9) { + n++; + r -= 10; + } +#endif // USE_STIMMER + *--p = r + '0'; + } + *--p = n + '0'; + return p; +} +//------------------------------------------------------------------------------ +// format 32-bit unsigned +char* fmtDec(uint32_t n, char* p) { + while (n >> 16) { +#ifdef USE_STIMMER + uint8_t tmp8, r; + divmod10_asm32(n, r, tmp8); +#else // USE_STIMMER + uint32_t t = n; + n = (n >> 1) + (n >> 2); + n = n + (n >> 4); + n = n + (n >> 8); + n = n + (n >> 16); + n = n >> 3; + uint8_t r = t - (((n << 2) + n) << 1); + if (r > 9) { + n++; + r -= 10; + } +#endif // USE_STIMMER + *--p = r + '0'; + } + return fmtDec((uint16_t)n, p); +} +//------------------------------------------------------------------------------ +char* fmtFloat(float value, char* p, uint8_t prec) { + char sign = value < 0 ? '-' : 0; + if (sign) { + value = -value; + } + + if (isnan(value)) { + *--p = 'n'; + *--p = 'a'; + *--p = 'n'; + return p; + } + if (isinf(value)) { + *--p = 'f'; + *--p = 'n'; + *--p = 'i'; + return p; + } + if (value > 4294967040.0) { + *--p = 'f'; + *--p = 'v'; + *--p = 'o'; + return p; + } + if (prec > 9) { + prec = 9; + } + value += scale10(0.5, -prec); + + uint32_t whole = value; + if (prec) { + char* tmp = p - prec; + uint32_t fraction = scale10(value - whole, prec); + p = fmtDec(fraction, p); + while (p > tmp) { + *--p = '0'; + } + *--p = '.'; + } + p = fmtDec(whole, p); + if (sign) { + *--p = sign; + } + return p; +} +//------------------------------------------------------------------------------ +/** Print a number followed by a field terminator. + * \param[in] value The number to be printed. + * \param[in] ptr Pointer to last char in buffer. + * \param[in] prec Number of digits after decimal point. + * \param[in] expChar Use exp format if non zero. + * \return Pointer to first character of result. + */ +char* fmtFloat(float value, char* ptr, uint8_t prec, char expChar) { + bool neg = value < 0; + if (neg) { + value = -value; + } + + // check for nan inf ovf + if (isnan(value)) { + *--ptr = 'n'; + *--ptr = 'a'; + *--ptr = 'n'; + return ptr; + } + if (isinf(value)) { + *--ptr = 'f'; + *--ptr = 'n'; + *--ptr = 'i'; + return ptr; + } + if (!expChar && value > 4294967040.0) { + *--ptr = 'f'; + *--ptr = 'v'; + *--ptr = 'o'; + return ptr; + } + if (prec > 9) { + prec = 9; + } + float round = scale10(0.5, -prec); + if (expChar) { + int8_t exp = 0; + bool expNeg = false; + if (value) { + while (value > 10.0) { + value *= 0.1; + exp++; + } + while (value < 1.0) { + value *= 10.0; + exp--; + } + value += round; + if (value > 10.0) { + value *= 0.1; + exp++; + } + expNeg = exp < 0; + if (expNeg) { + exp = -exp; + } + } + ptr = fmtDec((uint16_t)exp, ptr); + if (exp < 10) { + *--ptr = '0'; + } + *--ptr = expNeg ? '-' : '+'; + *--ptr = expChar; + } else { + // round value + value += round; + } + uint32_t whole = value; + if (prec) { + char* tmp = ptr - prec; + uint32_t fraction = scale10(value - whole, prec); + ptr = fmtDec(fraction, ptr); + while (ptr > tmp) { + *--ptr = '0'; + } + *--ptr = '.'; + } + ptr = fmtDec(whole, ptr); + if (neg) { + *--ptr = '-'; + } + return ptr; +} +//------------------------------------------------------------------------------ +char* fmtHex(uint32_t n, char* p) { + do { + uint8_t h = n & 0XF; + *--p = h + (h < 10 ? '0' : 'A' - 10); + n >>= 4; + } while (n); + return p; +} +//------------------------------------------------------------------------------ +float scanFloat(const char* str, char** ptr) { + int16_t const EXP_LIMIT = 100; + bool digit = false; + bool dot = false; + uint32_t fract = 0; + int fracExp = 0; + uint8_t nd = 0; + bool neg; + int c; + float v; + const char* successPtr = str; + + if (ptr) { + *ptr = const_cast(str); + } + + while (isSpace((c = *str++))) {} + neg = c == '-'; + if (c == '-' || c == '+') { + c = *str++; + } + // Skip leading zeros + while (c == '0') { + c = *str++; + digit = true; + } + for (;;) { + if (isDigit(c)) { + digit = true; + if (nd < 9) { + fract = 10*fract + c - '0'; + nd++; + if (dot) { + fracExp--; + } + } else { + if (!dot) { + fracExp++; + } + } + } else if (c == '.') { + if (dot) { + goto fail; + } + dot = true; + } else { + if (!digit) { + goto fail; + } + break; + } + successPtr = str; + c = *str++; + } + if (c == 'e' || c == 'E') { + int exp = 0; + c = *str++; + bool expNeg = c == '-'; + if (c == '-' || c == '+') { + c = *str++; + } + while (isDigit(c)) { + if (exp > EXP_LIMIT) { + goto fail; + } + exp = 10*exp + c - '0'; + successPtr = str; + c = *str++; + } + fracExp += expNeg ? -exp : exp; + } + if (ptr) { + *ptr = const_cast(successPtr); + } + v = scale10(static_cast(fract), fracExp); + return neg ? -v : v; + +fail: + return 0; +} + + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FmtNumber.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FmtNumber.h new file mode 100644 index 0000000..daa926e --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FmtNumber.h @@ -0,0 +1,43 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 FmtNumber_h +#define FmtNumber_h +// #include +inline bool isDigit(char c) { + return '0' <= c && c <= '9'; +} +inline bool isSpace(char c) { + return c == ' ' || (0X9 <= c && c <= 0XD); +} +#include +#include +char* fmtDec(uint16_t n, char* p); +char* fmtDec(uint32_t n, char* p); +char* fmtFloat(float value, char* p, uint8_t prec); +char* fmtFloat(float value, char* ptr, uint8_t prec, char expChar); +char* fmtHex(uint32_t n, char* p); +float scale10(float v, int8_t n); +float scanFloat(const char* str, char** ptr); +#endif // FmtNumber_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/StdioStream.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/StdioStream.cpp new file mode 100644 index 0000000..a6d2e9b --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/StdioStream.cpp @@ -0,0 +1,508 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#include "StdioStream.h" +#include "FmtNumber.h" +//------------------------------------------------------------------------------ +int StdioStream::fclose() { + int rtn = 0; + if (!m_status) { + return EOF; + } + if (m_status & S_SWR) { + if (!flushBuf()) { + rtn = EOF; + } + } + if (!FatFile::close()) { + rtn = EOF; + } + m_r = 0; + m_w = 0; + m_status = 0; + return rtn; +} +//------------------------------------------------------------------------------ +int StdioStream::fflush() { + if ((m_status & (S_SWR | S_SRW)) && !(m_status & S_SRD)) { + if (flushBuf() && FatFile::sync()) { + return 0; + } + } + return EOF; +} +//------------------------------------------------------------------------------ +char* StdioStream::fgets(char* str, size_t num, size_t* len) { + char* s = str; + size_t n; + if (num-- == 0) { + return 0; + } + while (num) { + if ((n = m_r) == 0) { + if (!fillBuf()) { + if (s == str) { + return 0; + } + break; + } + n = m_r; + } + if (n > num) { + n = num; + } + uint8_t* end = reinterpret_cast(memchr(m_p, '\n', n)); + if (end != 0) { + n = ++end - m_p; + memcpy(s, m_p, n); + m_r -= n; + m_p = end; + s += n; + break; + } + memcpy(s, m_p, n); + m_r -= n; + m_p += n; + s += n; + num -= n; + } + *s = 0; + if (len) { + *len = s - str; + } + return str; +} +//------------------------------------------------------------------------------ +bool StdioStream::fopen(const char* path, const char* mode) { + oflag_t oflag; + uint8_t m; + switch (*mode++) { + case 'a': + m = O_WRONLY; + oflag = O_CREAT | O_APPEND; + m_status = S_SWR; + break; + + case 'r': + m = O_RDONLY; + oflag = 0; + m_status = S_SRD; + break; + + case 'w': + m = O_WRONLY; + oflag = O_CREAT | O_TRUNC; + m_status = S_SWR; + break; + + default: + goto fail; + } + while (*mode) { + switch (*mode++) { + case '+': + m_status = S_SRW; + m = O_RDWR; + break; + + case 'b': + break; + + case 'x': + oflag |= O_EXCL; + break; + + default: + goto fail; + } + } + oflag |= m; + + if (!FatFile::open(path, oflag)) { + goto fail; + } + m_r = 0; + m_w = 0; + m_p = m_buf; + return true; + +fail: + m_status = 0; + return false; +} +//------------------------------------------------------------------------------ +int StdioStream::fputs(const char* str) { + size_t len = strlen(str); + return fwrite(str, 1, len) == len ? len : EOF; +} +//------------------------------------------------------------------------------ +size_t StdioStream::fread(void* ptr, size_t size, size_t count) { + uint8_t* dst = reinterpret_cast(ptr); + size_t total = size*count; + if (total == 0) { + return 0; + } + size_t need = total; + while (need > m_r) { + memcpy(dst, m_p, m_r); + dst += m_r; + m_p += m_r; + need -= m_r; + if (!fillBuf()) { + return (total - need)/size; + } + } + memcpy(dst, m_p, need); + m_r -= need; + m_p += need; + return count; +} +//------------------------------------------------------------------------------ +int StdioStream::fseek(int32_t offset, int origin) { + int32_t pos; + if (m_status & S_SWR) { + if (!flushBuf()) { + goto fail; + } + } + switch (origin) { + case SEEK_CUR: + pos = ftell(); + if (pos < 0) { + goto fail; + } + pos += offset; + if (!FatFile::seekCur(pos)) { + goto fail; + } + break; + + case SEEK_SET: + if (!FatFile::seekSet(offset)) { + goto fail; + } + break; + + case SEEK_END: + if (!FatFile::seekEnd(offset)) { + goto fail; + } + break; + + default: + goto fail; + } + m_r = 0; + m_p = m_buf; + return 0; + +fail: + return EOF; +} +//------------------------------------------------------------------------------ +int32_t StdioStream::ftell() { + uint32_t pos = FatFile::curPosition(); + if (m_status & S_SRD) { + if (m_r > pos) { + return -1L; + } + pos -= m_r; + } else if (m_status & S_SWR) { + pos += m_p - m_buf; + } + return pos; +} +//------------------------------------------------------------------------------ +size_t StdioStream::fwrite(const void* ptr, size_t size, size_t count) { + return write(ptr, count*size) < 0 ? EOF : count; +} +//------------------------------------------------------------------------------ +int StdioStream::write(const void* buf, size_t count) { + const uint8_t* src = static_cast(buf); + size_t todo = count; + + while (todo > m_w) { + memcpy(m_p, src, m_w); + m_p += m_w; + src += m_w; + todo -= m_w; + if (!flushBuf()) { + return EOF; + } + } + memcpy(m_p, src, todo); + m_p += todo; + m_w -= todo; + return count; +} +//------------------------------------------------------------------------------ +#if (defined(ARDUINO) && ENABLE_ARDUINO_FEATURES) || defined(DOXYGEN) +size_t StdioStream::print(const __FlashStringHelper *str) { + const char *p = (const char*)str; + uint8_t c; + while ((c = pgm_read_byte(p))) { + if (putc(c) < 0) { + return 0; + } + p++; + } + return p - (const char*)str; +} +#endif // (defined(ARDUINO) && ENABLE_ARDUINO_FEATURES) || defined(DOXYGEN) +//------------------------------------------------------------------------------ +int StdioStream::printDec(float value, uint8_t prec) { + char buf[24]; + char *ptr = fmtFloat(value, buf + sizeof(buf), prec); + return write(ptr, buf + sizeof(buf) - ptr); +} +//------------------------------------------------------------------------------ +int StdioStream::printDec(signed char n) { + if (n < 0) { + if (fputc('-') < 0) { + return -1; + } + n = -n; + } + return printDec((unsigned char)n); +} +//------------------------------------------------------------------------------ +int StdioStream::printDec(int16_t n) { + int s; + uint8_t rtn = 0; + if (n < 0) { + if (fputc('-') < 0) { + return -1; + } + n = -n; + rtn++; + } + if ((s = printDec((uint16_t)n)) < 0) { + return s; + } + return rtn; +} +//------------------------------------------------------------------------------ +int StdioStream::printDec(uint16_t n) { +#define NEW_WAY +#ifdef NEW_WAY + char buf[5]; + char *ptr = fmtDec(n, buf + sizeof(buf)); + uint8_t len = buf + sizeof(buf) - ptr; + return write(ptr, len); +#else + uint8_t len; + if (n < 100) { + len = n < 10 ? 1 : 2; + } else { + len = n < 1000 ? 3 : n < 10000 ? 4 : 5; + } + char* str = fmtSpace(len); + if (!str) { + return -1; + } + fmtDec(n, str); + return len; +#endif +} +//------------------------------------------------------------------------------ +int StdioStream::printDec(int32_t n) { + uint8_t s = 0; + if (n < 0) { + if (fputc('-') < 0) { + return -1; + } + n = -n; + s = 1; + } + int rtn = printDec((uint32_t)n); + return rtn > 0 ? rtn + s : -1; +} +//------------------------------------------------------------------------------ +int StdioStream::printDec(uint32_t n) { +#ifdef NEW_WAY + char buf[10]; + char *ptr = fmtDec(n, buf + sizeof(buf)); + uint8_t len = buf + sizeof(buf) - ptr; + return write(ptr, len); +#else + uint8_t len; + if (n < 0X10000) { + return printDec((uint16_t)n); + } + if (n < 10000000) { + len = n < 100000 ? 5 : n < 1000000 ? 6 : 7; + } else { + len = n < 100000000 ? 8 : n < 1000000000 ? 9 : 10; + } + + char* str = fmtSpace(len); + if (!str) { + return -1; + } + fmtDec(n, str); + return len; +#endif +} +//------------------------------------------------------------------------------ +int StdioStream::printHex(uint32_t n) { +#ifdef NEW_WAY + char buf[8]; + char *ptr = fmtHex(n, buf + sizeof(buf)); + uint8_t len = buf + sizeof(buf) - ptr; + return write(ptr, len); +#else + size_t len; + if (n < 0X10000) { + len = n < 0X10 ? 1 : n < 0X100 ? 2 : n < 0X1000 ? 3 : 4; + } else { + len = n < 0X100000 ? 5 : n < 0X1000000 ? 6 : n < 0X10000000 ? 7 : 8; + } + char* str = fmtSpace(len); + if (!str) { + return -1; + } + + do { + uint8_t h = n & 0XF; + *str-- = h + (h < 10 ? '0' : 'A' - 10); + n >>= 4; + } while (n); + return len; +#endif +} +//------------------------------------------------------------------------------ +bool StdioStream::rewind() { + if (m_status & S_SWR) { + if (!flushBuf()) { + return false; + } + } + FatFile::seekSet(0); + m_r = 0; + return true; +} +//------------------------------------------------------------------------------ +int StdioStream::ungetc(int c) { + // error if EOF. + if (c == EOF) { + return EOF; + } + // error if not reading. + if ((m_status & S_SRD) == 0) { + return EOF; + } + // error if no space. + if (m_p == m_buf) { + return EOF; + } + m_r++; + m_status &= ~S_EOF; + return *--m_p = (uint8_t)c; +} +//============================================================================== +// private +//------------------------------------------------------------------------------ +int StdioStream::fillGet() { + if (!fillBuf()) { + return EOF; + } + m_r--; + return *m_p++; +} +//------------------------------------------------------------------------------ +// private +bool StdioStream::fillBuf() { + if (!(m_status & + S_SRD)) { // check for S_ERR and S_EOF ??///////////////// + if (!(m_status & S_SRW)) { + m_status |= S_ERR; + return false; + } + if (m_status & S_SWR) { + if (!flushBuf()) { + return false; + } + m_status &= ~S_SWR; + m_status |= S_SRD; + m_w = 0; + } + } + m_p = m_buf + UNGETC_BUF_SIZE; + int nr = FatFile::read(m_p, sizeof(m_buf) - UNGETC_BUF_SIZE); + if (nr <= 0) { + m_status |= nr < 0 ? S_ERR : S_EOF; + m_r = 0; + return false; + } + m_r = nr; + return true; +} +//------------------------------------------------------------------------------ +// private +bool StdioStream::flushBuf() { + if (!(m_status & + S_SWR)) { // check for S_ERR ??//////////////////////// + if (!(m_status & S_SRW)) { + m_status |= S_ERR; + return false; + } + m_status &= ~S_SRD; + m_status |= S_SWR; + m_r = 0; + m_w = sizeof(m_buf); + m_p = m_buf; + return true; + } + uint8_t n = m_p - m_buf; + m_p = m_buf; + m_w = sizeof(m_buf); + if (FatFile::write(m_buf, n) == n) { + return true; + } + m_status |= S_ERR; + return false; +} +//------------------------------------------------------------------------------ +int StdioStream::flushPut(uint8_t c) { + if (!flushBuf()) { + return EOF; + } + m_w--; + return *m_p++ = c; +} +//------------------------------------------------------------------------------ +char* StdioStream::fmtSpace(uint8_t len) { + if (m_w < len) { + if (!flushBuf() || m_w < len) { + return 0; + } + } + if (len > m_w) { + return 0; + } + m_p += len; + m_w -= len; + return reinterpret_cast(m_p); +} + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/StdioStream.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/StdioStream.h new file mode 100644 index 0000000..9fcd064 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/StdioStream.h @@ -0,0 +1,667 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 StdioStream_h +#define StdioStream_h +/** + * \file + * \brief StdioStream class + */ +#include +#include "FatFile.h" +//------------------------------------------------------------------------------ +/** Total size of stream buffer. The entire buffer is used for output. + * During input UNGETC_BUF_SIZE of this space is reserved for ungetc. + */ +const uint8_t STREAM_BUF_SIZE = 64; +/** Amount of buffer allocated for ungetc during input. */ +const uint8_t UNGETC_BUF_SIZE = 2; +//------------------------------------------------------------------------------ +// Get rid of any macros defined in . +#include +#undef clearerr +#undef fclose +#undef feof +#undef ferror +#undef fflush +#undef fgetc +#undef fgetpos +#undef fgets +#undef fopen +#undef fprintf +#undef fputc +#undef fputs +#undef fread +#undef freopen +#undef fscanf +#undef fseek +#undef fsetpos +#undef ftell +#undef fwrite +#undef getc +#undef getchar +#undef gets +#undef perror +//#undef printf // NOLINT +#undef putc +#undef putchar +#undef puts +#undef remove +#undef rename +#undef rewind +#undef scanf +#undef setbuf +#undef setvbuf +//#undef sprintf // NOLINT +#undef sscanf +#undef tmpfile +#undef tmpnam +#undef ungetc +#undef vfprintf +#undef vprintf +#undef vsprintf + +// make sure needed macros are defined +#ifndef EOF +/** End-of-file return value. */ +#define EOF (-1) +#endif // EOF +#ifndef NULL +/** Null pointer */ +#define NULL 0 +#endif // NULL +#ifndef SEEK_CUR +/** Seek relative to current position. */ +#define SEEK_CUR 1 +#endif // SEEK_CUR +#ifndef SEEK_END +/** Seek relative to end-of-file. */ +#define SEEK_END 2 +#endif // SEEK_END +#ifndef SEEK_SET +/** Seek relative to start-of-file. */ +#define SEEK_SET 0 +#endif // SEEK_SET +//------------------------------------------------------------------------------ +/** \class StdioStream + * \brief StdioStream implements a minimal stdio stream. + * + * StdioStream does not support subdirectories or long file names. + */ +class StdioStream : private FatFile { + public: + /** Constructor + * + */ + StdioStream() { + m_w = m_r = 0; + m_p = m_buf; + m_status = 0; + } + //---------------------------------------------------------------------------- + /** Clear the stream's end-of-file and error indicators. */ + void clearerr() { + m_status &= ~(S_ERR | S_EOF); + } + //---------------------------------------------------------------------------- + /** Close a stream. + * + * A successful call to the fclose function causes the stream to be + * flushed and the associated file to be closed. Any unwritten buffered + * data is written to the file; any unread buffered data is discarded. + * Whether or not the call succeeds, the stream is disassociated from + * the file. + * + * \return zero if the stream was successfully closed, or EOF if any any + * errors are detected. + */ + int fclose(); + //---------------------------------------------------------------------------- + /** Test the stream's end-of-file indicator. + * \return non-zero if and only if the end-of-file indicator is set. + */ + int feof() { + return (m_status & S_EOF) != 0; + } + //---------------------------------------------------------------------------- + /** Test the stream's error indicator. + * \return return non-zero if and only if the error indicator is set. + */ + int ferror() { + return (m_status & S_ERR) != 0; + } + //---------------------------------------------------------------------------- + /** Flush the stream. + * + * If stream is an output stream or an update stream in which the most + * recent operation was not input, any unwritten data is written to the + * file; otherwise the call is an error since any buffered input data + * would be lost. + * + * \return sets the error indicator for the stream and returns EOF if an + * error occurs, otherwise it returns zero. + */ + int fflush(); + //---------------------------------------------------------------------------- + /** Get a byte from the stream. + * + * \return If the end-of-file indicator for the stream is set, or if the + * stream is at end-of-file, the end-of-file indicator for the stream is + * set and the fgetc function returns EOF. Otherwise, the fgetc function + * returns the next character from the input stream. + */ + int fgetc() { + return m_r-- == 0 ? fillGet() : *m_p++; + } + //---------------------------------------------------------------------------- + /** Get a string from a stream. + * + * The fgets function reads at most one less than the number of + * characters specified by num from the stream into the array pointed + * to by str. No additional characters are read after a new-line + * character (which is retained) or after end-of-file. A null character + * is written immediately after the last character read into the array. + * + * \param[out] str Pointer to an array of where the string is copied. + * + * \param[in] num Maximum number of characters including the null + * character. + * + * \param[out] len If len is not null and fgets is successful, the + * length of the string is returned. + * + * \return str if successful. If end-of-file is encountered and no + * characters have been read into the array, the contents of the array + * remain unchanged and a null pointer is returned. If a read error + * occurs during the operation, the array contents are indeterminate + * and a null pointer is returned. + */ + char* fgets(char* str, size_t num, size_t* len = 0); + //---------------------------------------------------------------------------- + /** Open a stream. + * + * Open a file and associates the stream with it. + * + * \param[in] path file to be opened. + * + * \param[in] mode a string that indicates the open mode. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
"r" or "rb"Open a file for reading. The file must exist.
"w" or "wb"Truncate an existing to zero length or create an empty file + * for writing.
"wx" or "wbx"Create a file for writing. Fails if the file already exists.
"a" or "ab"Append; open or create file for writing at end-of-file.
"r+" or "rb+" or "r+b"Open a file for update (reading and writing).
"w+" or "w+b" or "wb+"Truncate an existing to zero length or create a file for update.
"w+x" or "w+bx" or "wb+x"Create a file for update. Fails if the file already exists.
"a+" or "a+b" or "ab+"Append; open or create a file for update, writing at end-of-file.
+ * The character 'b' shall have no effect, but is allowed for ISO C + * standard conformance. + * + * Opening a file with append mode causes all subsequent writes to the + * file to be forced to the then current end-of-file, regardless of + * intervening calls to the fseek function. + * + * When a file is opened with update mode, both input and output may be + * performed on the associated stream. However, output shall not be + * directly followed by input without an intervening call to the fflush + * function or to a file positioning function (fseek, or rewind), and + * input shall not be directly followed by output without an intervening + * call to a file positioning function, unless the input operation + * encounters end-of-file. + * + * \return true for success or false for failure. + */ + bool fopen(const char* path, const char * mode); + //---------------------------------------------------------------------------- + /** Write a byte to a stream. + * + * \param[in] c the byte to be written (converted to an unsigned char). + * + * \return Upon successful completion, fputc() returns the value it + * has written. Otherwise, it returns EOF and sets the error indicator for + * the stream. + */ + int fputc(int c) { + return m_w-- == 0 ? flushPut(c) : *m_p++ = c; + } + //---------------------------------------------------------------------------- + /** Write a string to a stream. + * + * \param[in] str a pointer to the string to be written. + * + * \return for success, fputs() returns a non-negative + * number. Otherwise, it returns EOF and sets the error indicator for + * the stream. + */ + int fputs(const char* str); + //---------------------------------------------------------------------------- + /** Binary input. + * + * Reads an array of up to count elements, each one with a size of size + * bytes. + * \param[out] ptr pointer to area of at least (size*count) bytes where + * the data will be stored. + * + * \param[in] size the size, in bytes, of each element to be read. + * + * \param[in] count the number of elements to be read. + * + * \return number of elements successfully read, which may be less than + * count if a read error or end-of-file is encountered. If size or count + * is zero, fread returns zero and the contents of the array and the + * state of the stream remain unchanged. + */ + size_t fread(void* ptr, size_t size, size_t count); + //---------------------------------------------------------------------------- + /** Set the file position for the stream. + * + * \param[in] offset number of offset from the origin. + * + * \param[in] origin position used as reference for the offset. It is + * specified by one of the following constants. + * + * SEEK_SET - Beginning of file. + * + * SEEK_CUR - Current position of the file pointer. + * + * SEEK_END - End of file. + * + * \return zero for success. Otherwise, it returns non-zero and sets the + * error indicator for the stream. + */ + int fseek(int32_t offset, int origin); + //---------------------------------------------------------------------------- + /** Get the current position in a stream. + * + * \return If successful, ftell return the current value of the position + * indicator. On failure, ftell returns −1L. + */ + int32_t ftell(); + //---------------------------------------------------------------------------- + /** Binary output. + * + * Writes an array of up to count elements, each one with a size of size + * bytes. + * \param[in] ptr pointer to (size*count) bytes of data to be written. + * + * \param[in] size the size, in bytes, of each element to be written. + * + * \param[in] count the number of elements to be written. + * + * \return number of elements successfully written. if this number is + * less than count, an error has occurred. If size or count is zero, + * fwrite returns zero. + */ + size_t fwrite(const void * ptr, size_t size, size_t count); + //---------------------------------------------------------------------------- + /** Get a byte from the stream. + * + * getc and fgetc are equivalent but getc is in-line so it is faster but + * require more flash memory. + * + * \return If the end-of-file indicator for the stream is set, or if the + * stream is at end-of-file, the end-of-file indicator for the stream is + * set and the fgetc function returns EOF. Otherwise, the fgetc function + * returns the next character from the input stream. + */ + inline __attribute__((always_inline)) + int getc() { + return m_r-- == 0 ? fillGet() : *m_p++; + } + //---------------------------------------------------------------------------- + /** Write a byte to a stream. + * + * putc and fputc are equivalent but putc is in-line so it is faster but + * require more flash memory. + * + * \param[in] c the byte to be written (converted to an unsigned char). + * + * \return Upon successful completion, fputc() returns the value it + * has written. Otherwise, it returns EOF and sets the error indicator for + * the stream. + */ + inline __attribute__((always_inline)) + int putc(int c) { + return m_w-- == 0 ? flushPut(c) : *m_p++ = c; + } + //---------------------------------------------------------------------------- + /** Write a CR/LF. + * + * \return two, the number of bytes written, for success or -1 for failure. + */ + inline __attribute__((always_inline)) + int putCRLF() { + if (m_w < 2) { + if (!flushBuf()) { + return -1; + } + } + *m_p++ = '\r'; + *m_p++ = '\n'; + m_w -= 2; + return 2; + } + //---------------------------------------------------------------------------- + /** Write a character. + * \param[in] c the character to write. + * \return the number of bytes written. + */ + size_t print(char c) { + return putc(c) < 0 ? 0 : 1; + } + //---------------------------------------------------------------------------- + /** Write a string. + * + * \param[in] str the string to be written. + * + * \return the number of bytes written. + */ + size_t print(const char* str) { + int n = fputs(str); + return n < 0 ? 0 : n; + } + //---------------------------------------------------------------------------- +#if (defined(ARDUINO) && ENABLE_ARDUINO_FEATURES) || defined(DOXYGEN) + /** Print a string stored in flash memory. + * + * \param[in] str the string to print. + * + * \return the number of bytes written. + */ + size_t print(const __FlashStringHelper *str); +#endif // (defined(ARDUINO) && ENABLE_ARDUINO_FEATURES) || defined(DOXYGEN) + //---------------------------------------------------------------------------- + /** Print a floating point number. + * + * \param[in] prec Number of digits after decimal point. + * + * \param[in] val the number to be printed. + * + * \return the number of bytes written. + */ + size_t print(double val, uint8_t prec = 2) { + return print(static_cast(val), prec); + } + //---------------------------------------------------------------------------- + /** Print a floating point number. + * + * \param[in] prec Number of digits after decimal point. + * + * \param[in] val the number to be printed. + * + * \return the number of bytes written. + */ + size_t print(float val, uint8_t prec = 2) { + int n = printDec(val, prec); + return n > 0 ? n : 0; + } + //---------------------------------------------------------------------------- + /** Print a number. + * + * \param[in] val the number to be printed. + * + * \return the number of bytes written. + */ + template + size_t print(T val) { + int n = printDec(val); + return n > 0 ? n : 0; + } + //---------------------------------------------------------------------------- + /** Write a CR/LF. + * + * \return two, the number of bytes written, for success or zero for failure. + */ + size_t println() { + return putCRLF() > 0 ? 2 : 0; + } + //---------------------------------------------------------------------------- + /** Print a floating point number followed by CR/LF. + * + * \param[in] val the number to be printed. + * + * \param[in] prec Number of digits after decimal point. + * + * \return the number of bytes written. + */ + size_t println(double val, uint8_t prec = 2) { + return println(static_cast(val), prec); + } + //---------------------------------------------------------------------------- + /** Print a floating point number followed by CR/LF. + * + * \param[in] val the number to be printed. + * + * \param[in] prec Number of digits after decimal point. + * + * \return the number of bytes written. + */ + size_t println(float val, uint8_t prec = 2) { + int n = printDec(val, prec); + return n > 0 && putCRLF() > 0 ? n + 2 : 0; + } + //---------------------------------------------------------------------------- + /** Print an item followed by CR/LF + * + * \param[in] val the item to be printed. + * + * \return the number of bytes written. + */ + template + size_t println(T val) { + int n = print(val); + return putCRLF() > 0 ? n + 2 : 0; + } + //---------------------------------------------------------------------------- + /** Print a char as a number. + * \param[in] n number to be printed. + * \return The number of bytes written or -1 if an error occurs. + */ + int printDec(char n) { + if (CHAR_MIN == 0) { + return printDec((unsigned char)n); + } else { + return printDec((signed char)n); + } + } + //---------------------------------------------------------------------------- + /** print a signed 8-bit integer + * \param[in] n number to be printed. + * \return The number of bytes written or -1 if an error occurs. + */ + int printDec(signed char n); + //---------------------------------------------------------------------------- + /** Print an unsigned 8-bit number. + * \param[in] n number to be print. + * \return The number of bytes written or -1 if an error occurs. + */ + int printDec(unsigned char n) { + return printDec((uint16_t)n); + } + //---------------------------------------------------------------------------- + /** Print a int16_t + * \param[in] n number to be printed. + * \return The number of bytes written or -1 if an error occurs. + */ + int printDec(int16_t n); + //---------------------------------------------------------------------------- + /** print a uint16_t. + * \param[in] n number to be printed. + * \return The number of bytes written or -1 if an error occurs. + */ + int printDec(uint16_t n); + //---------------------------------------------------------------------------- + /** Print a signed 32-bit integer. + * \param[in] n number to be printed. + * \return The number of bytes written or -1 if an error occurs. + */ + int printDec(int32_t n); + //---------------------------------------------------------------------------- + /** Write an unsigned 32-bit number. + * \param[in] n number to be printed. + * \return The number of bytes written or -1 if an error occurs. + */ + int printDec(uint32_t n); + //---------------------------------------------------------------------------- + /** Print a double. + * \param[in] value The number to be printed. + * \param[in] prec Number of digits after decimal point. + * \return The number of bytes written or -1 if an error occurs. + */ + int printDec(double value, uint8_t prec) { + return printDec(static_cast(value), prec); + } + //---------------------------------------------------------------------------- + /** Print a float. + * \param[in] value The number to be printed. + * \param[in] prec Number of digits after decimal point. + * \return The number of bytes written or -1 if an error occurs. + */ + int printDec(float value, uint8_t prec); + //---------------------------------------------------------------------------- + /** Print a number followed by a field terminator. + * \param[in] value The number to be printed. + * \param[in] term The field terminator. + * \param[in] prec Number of digits after decimal point. + * \return The number of bytes written or -1 if an error occurs. + */ + int printField(double value, char term, uint8_t prec = 2) { + return printField(static_cast(value), term, prec) > 0; + } + //---------------------------------------------------------------------------- + /** Print a number followed by a field terminator. + * \param[in] value The number to be printed. + * \param[in] term The field terminator. + * \param[in] prec Number of digits after decimal point. + * \return The number of bytes written or -1 if an error occurs. + */ + int printField(float value, char term, uint8_t prec = 2) { + int rtn = printDec(value, prec); + return rtn < 0 || putc(term) < 0 ? -1 : rtn + 1; + } + //---------------------------------------------------------------------------- + /** Print a number followed by a field terminator. + * \param[in] value The number to be printed. + * \param[in] term The field terminator. + * \return The number of bytes written or -1 if an error occurs. + */ + template + int printField(T value, char term) { + int rtn = printDec(value); + return rtn < 0 || putc(term) < 0 ? -1 : rtn + 1; + } + //---------------------------------------------------------------------------- + /** Print HEX + * \param[in] n number to be printed as HEX. + * + * \return The number of bytes written or -1 if an error occurs. + */ + int printHex(uint32_t n); + //---------------------------------------------------------------------------- + /** Print HEX with CRLF + * \param[in] n number to be printed as HEX. + * + * \return The number of bytes written or -1 if an error occurs. + */ + int printHexln(uint32_t n) { + int rtn = printHex(n); + return rtn < 0 || putCRLF() != 2 ? -1 : rtn + 2; + } + //---------------------------------------------------------------------------- + /** Set position of a stream to the beginning. + * + * The rewind function sets the file position to the beginning of the + * file. It is equivalent to fseek(0L, SEEK_SET) except that the error + * indicator for the stream is also cleared. + * + * \return true for success or false for failure. + */ + bool rewind(); + //---------------------------------------------------------------------------- + /** Push a byte back into an input stream. + * + * \param[in] c the byte (converted to an unsigned char) to be pushed back. + * + * One character of push-back is guaranteed. If the ungetc function is + * called too many times without an intervening read or file positioning + * operation on that stream, the operation may fail. + * + * A successful intervening call to a file positioning function (fseek, + * fsetpos, or rewind) discards any pushed-back characters for the stream. + * + * \return Upon successful completion, ungetc() returns the byte pushed + * back after conversion. Otherwise it returns EOF. + */ + int ungetc(int c); + //============================================================================ + private: + bool fillBuf(); + int fillGet(); + bool flushBuf(); + int flushPut(uint8_t c); + char* fmtSpace(uint8_t len); + int write(const void* buf, size_t count); + //---------------------------------------------------------------------------- + // S_SRD and S_WR are never simultaneously asserted + static const uint8_t S_SRD = 0x01; // OK to read + static const uint8_t S_SWR = 0x02; // OK to write + static const uint8_t S_SRW = 0x04; // open for reading & writing + static const uint8_t S_EOF = 0x10; // found EOF + static const uint8_t S_ERR = 0x20; // found error + //---------------------------------------------------------------------------- + uint8_t m_status; + uint8_t* m_p; + uint8_t m_r; + uint8_t m_w; + uint8_t m_buf[STREAM_BUF_SIZE]; +}; +//------------------------------------------------------------------------------ +#endif // StdioStream_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/bufstream.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/bufstream.h new file mode 100644 index 0000000..5390aa7 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/bufstream.h @@ -0,0 +1,172 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 bufstream_h +#define bufstream_h +/** + * \file + * \brief \ref ibufstream and \ref obufstream classes + */ +#include +#include "iostream.h" +//============================================================================== +/** + * \class ibufstream + * \brief parse a char string + */ +class ibufstream : public istream { + public: + /** Constructor */ + ibufstream() : m_buf(0), m_len(0) {} + /** Constructor + * \param[in] str pointer to string to be parsed + * Warning: The string will not be copied so must stay in scope. + */ + explicit ibufstream(const char* str) { + init(str); + } + /** Initialize an ibufstream + * \param[in] str pointer to string to be parsed + * Warning: The string will not be copied so must stay in scope. + */ + void init(const char* str) { + m_buf = str; + m_len = strlen(m_buf); + m_pos = 0; + clear(); + } + + protected: + /// @cond SHOW_PROTECTED + int16_t getch() { + if (m_pos < m_len) { + return m_buf[m_pos++]; + } + setstate(eofbit); + return -1; + } + void getpos(FatPos_t *pos) { + pos->position = m_pos; + } + bool seekoff(off_type off, seekdir way) { + (void)off; + (void)way; + return false; + } + bool seekpos(pos_type pos) { + if (pos < m_len) { + m_pos = pos; + return true; + } + return false; + } + void setpos(FatPos_t *pos) { + m_pos = pos->position; + } + pos_type tellpos() { + return m_pos; + } + /// @endcond + private: + const char* m_buf; + size_t m_len; + size_t m_pos; +}; +//============================================================================== +/** + * \class obufstream + * \brief format a char string + */ +class obufstream : public ostream { + public: + /** constructor */ + obufstream() : m_in(0) {} + /** Constructor + * \param[in] buf buffer for formatted string + * \param[in] size buffer size + */ + obufstream(char *buf, size_t size) { + init(buf, size); + } + /** Initialize an obufstream + * \param[in] buf buffer for formatted string + * \param[in] size buffer size + */ + void init(char *buf, size_t size) { + m_buf = buf; + buf[0] = '\0'; + m_size = size; + m_in = 0; + } + /** \return a pointer to the buffer */ + char* buf() { + return m_buf; + } + /** \return the length of the formatted string */ + size_t length() { + return m_in; + } + + protected: + /// @cond SHOW_PROTECTED + void putch(char c) { + if (m_in >= (m_size - 1)) { + setstate(badbit); + return; + } + m_buf[m_in++] = c; + m_buf[m_in] = '\0'; + } + void putstr(const char *str) { + while (*str) { + putch(*str++); + } + } + bool seekoff(off_type off, seekdir way) { + (void)off; + (void)way; + return false; + } + bool seekpos(pos_type pos) { + if (pos > m_in) { + return false; + } + m_in = pos; + m_buf[m_in] = '\0'; + return true; + } + bool sync() { + return true; + } + + pos_type tellpos() { + return m_in; + } + /// @endcond + private: + char *m_buf; + size_t m_size; + size_t m_in; +}; +#endif // bufstream_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/fstream.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/fstream.cpp new file mode 100644 index 0000000..a5a0541 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/fstream.cpp @@ -0,0 +1,172 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#include "fstream.h" +//============================================================================== +/// @cond SHOW_PROTECTED +int16_t FatStreamBase::getch() { + uint8_t c; + int8_t s = read(&c, 1); + if (s != 1) { + if (s < 0) { + setstate(badbit); + } else { + setstate(eofbit); + } + return -1; + } + if (c != '\r' || (getmode() & ios::binary)) { + return c; + } + s = read(&c, 1); + if (s == 1 && c == '\n') { + return c; + } + if (s == 1) { + seekCur(-1); + } + return '\r'; +} +//------------------------------------------------------------------------------ +void FatStreamBase::open(const char* path, ios::openmode mode) { + oflag_t oflag; + switch (mode & (app | in | out | trunc)) { + case app | in: + case app | in | out: + oflag = O_RDWR | O_APPEND | O_CREAT; + break; + + case app: + case app | out: + oflag = O_WRONLY | O_APPEND | O_CREAT; + break; + + case in: + oflag = O_RDONLY; + break; + + case in | out: + oflag = O_RDWR; + break; + + case in | out | trunc: + oflag = O_RDWR | O_TRUNC | O_CREAT; + break; + + case out: + case out | trunc: + oflag = O_WRONLY | O_TRUNC | O_CREAT; + break; + + default: + goto fail; + } + if (mode & ios::ate) { + oflag |= O_AT_END; + } + if (!FatFile::open(path, oflag)) { + goto fail; + } + setmode(mode); + clear(); + return; + +fail: + FatFile::close(); + setstate(failbit); + return; +} +//------------------------------------------------------------------------------ +void FatStreamBase::putch(char c) { + if (c == '\n' && !(getmode() & ios::binary)) { + write('\r'); + } + write(c); + if (getWriteError()) { + setstate(badbit); + } +} +//------------------------------------------------------------------------------ +void FatStreamBase::putstr(const char* str) { + size_t n = 0; + while (1) { + char c = str[n]; + if (c == '\0' || (c == '\n' && !(getmode() & ios::binary))) { + if (n > 0) { + write(str, n); + } + if (c == '\0') { + break; + } + write('\r'); + str += n; + n = 0; + } + n++; + } + if (getWriteError()) { + setstate(badbit); + } +} +//------------------------------------------------------------------------------ +/** Internal do not use + * \param[in] off + * \param[in] way + */ +bool FatStreamBase::seekoff(off_type off, seekdir way) { + pos_type pos; + switch (way) { + case beg: + pos = off; + break; + + case cur: + pos = curPosition() + off; + break; + + case end: + pos = fileSize() + off; + break; + + default: + return false; + } + return seekpos(pos); +} +//------------------------------------------------------------------------------ +/** Internal do not use + * \param[in] pos + */ +bool FatStreamBase::seekpos(pos_type pos) { + return seekSet(pos); +} +//------------------------------------------------------------------------------ +int FatStreamBase::write(const void* buf, size_t n) { + return FatFile::write(buf, n); +} +//------------------------------------------------------------------------------ +void FatStreamBase::write(char c) { + write(&c, 1); +} +/// @endcond diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/fstream.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/fstream.h new file mode 100644 index 0000000..e0228cd --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/fstream.h @@ -0,0 +1,320 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 fstream_h +#define fstream_h +/** + * \file + * \brief \ref fstream, \ref ifstream, and \ref ofstream classes + */ +#include "FatFile.h" +#include "iostream.h" +//============================================================================== +/** + * \class FatStreamBase + * \brief Base class for C++ style streams + */ +class FatStreamBase : protected FatFile, virtual public ios { + protected: + /// @cond SHOW_PROTECTED + int16_t getch(); + void putch(char c); + void putstr(const char *str); + void open(const char* path, ios::openmode mode); + /** Internal do not use + * \return mode + */ + ios::openmode getmode() { + return m_mode; + } + /** Internal do not use + * \param[in] mode + */ + void setmode(ios::openmode mode) { + m_mode = mode; + } + bool seekoff(off_type off, seekdir way); + bool seekpos(pos_type pos); + int write(const void* buf, size_t n); + void write(char c); + /// @endcond + private: + ios::openmode m_mode; +}; +//============================================================================== +/** + * \class fstream + * \brief file input/output stream. + */ +class fstream : public iostream, FatStreamBase { + public: + using iostream::peek; + fstream() {} + /** Constructor with open + * + * \param[in] path path to open + * \param[in] mode open mode + */ + explicit fstream(const char* path, openmode mode = in | out) { + open(path, mode); + } +#if DESTRUCTOR_CLOSES_FILE + ~fstream() {} +#endif // DESTRUCTOR_CLOSES_FILE + /** Clear state and writeError + * \param[in] state new state for stream + */ + void clear(iostate state = goodbit) { + ios::clear(state); + FatFile::clearWriteError(); + } + /** Close a file and force cached data and directory information + * to be written to the storage device. + */ + void close() { + FatFile::close(); + } + /** Open a fstream + * \param[in] path file to open + * \param[in] mode open mode + * + * Valid open modes are (at end, ios::ate, and/or ios::binary may be added): + * + * ios::in - Open file for reading. + * + * ios::out or ios::out | ios::trunc - Truncate to 0 length, if existent, + * or create a file for writing only. + * + * ios::app or ios::out | ios::app - Append; open or create file for + * writing at end-of-file. + * + * ios::in | ios::out - Open file for update (reading and writing). + * + * ios::in | ios::out | ios::trunc - Truncate to zero length, if existent, + * or create file for update. + * + * ios::in | ios::app or ios::in | ios::out | ios::app - Append; open or + * create text file for update, writing at end of file. + */ + void open(const char* path, openmode mode = in | out) { + FatStreamBase::open(path, mode); + } + /** \return True if stream is open else false. */ + bool is_open() { + return FatFile::isOpen(); + } + + protected: + /// @cond SHOW_PROTECTED + /** Internal - do not use + * \return + */ + int16_t getch() { + return FatStreamBase::getch(); + } + /** Internal - do not use + * \param[out] pos + */ + void getpos(FatPos_t* pos) { + FatFile::getpos(pos); + } + /** Internal - do not use + * \param[in] c + */ + void putch(char c) { + FatStreamBase::putch(c); + } + /** Internal - do not use + * \param[in] str + */ + void putstr(const char *str) { + FatStreamBase::putstr(str); + } + /** Internal - do not use + * \param[in] pos + */ + bool seekoff(off_type off, seekdir way) { + return FatStreamBase::seekoff(off, way); + } + bool seekpos(pos_type pos) { + return FatStreamBase::seekpos(pos); + } + void setpos(FatPos_t* pos) { + FatFile::setpos(pos); + } + bool sync() { + return FatStreamBase::sync(); + } + pos_type tellpos() { + return FatStreamBase::curPosition(); + } + /// @endcond +}; +//============================================================================== +/** + * \class ifstream + * \brief file input stream. + */ +class ifstream : public istream, FatStreamBase { + public: + using istream::peek; + ifstream() {} + /** Constructor with open + * \param[in] path file to open + * \param[in] mode open mode + */ + explicit ifstream(const char* path, openmode mode = in) { + open(path, mode); + } +#if DESTRUCTOR_CLOSES_FILE + ~ifstream() {} +#endif // DESTRUCTOR_CLOSES_FILE + /** Close a file and force cached data and directory information + * to be written to the storage device. + */ + void close() { + FatFile::close(); + } + /** \return True if stream is open else false. */ + bool is_open() { + return FatFile::isOpen(); + } + /** Open an ifstream + * \param[in] path file to open + * \param[in] mode open mode + * + * \a mode See fstream::open() for valid modes. + */ + void open(const char* path, openmode mode = in) { + FatStreamBase::open(path, mode | in); + } + + protected: + /// @cond SHOW_PROTECTED + /** Internal - do not use + * \return + */ + int16_t getch() { + return FatStreamBase::getch(); + } + /** Internal - do not use + * \param[out] pos + */ + void getpos(FatPos_t* pos) { + FatFile::getpos(pos); + } + /** Internal - do not use + * \param[in] pos + */ + bool seekoff(off_type off, seekdir way) { + return FatStreamBase::seekoff(off, way); + } + bool seekpos(pos_type pos) { + return FatStreamBase::seekpos(pos); + } + void setpos(FatPos_t* pos) { + FatFile::setpos(pos); + } + pos_type tellpos() { + return FatStreamBase::curPosition(); + } + /// @endcond +}; +//============================================================================== +/** + * \class ofstream + * \brief file output stream. + */ +class ofstream : public ostream, FatStreamBase { + public: + ofstream() {} + /** Constructor with open + * \param[in] path file to open + * \param[in] mode open mode + */ + explicit ofstream(const char* path, ios::openmode mode = out) { + open(path, mode); + } +#if DESTRUCTOR_CLOSES_FILE + ~ofstream() {} +#endif // DESTRUCTOR_CLOSES_FILE + /** Clear state and writeError + * \param[in] state new state for stream + */ + void clear(iostate state = goodbit) { + ios::clear(state); + FatFile::clearWriteError(); + } + /** Close a file and force cached data and directory information + * to be written to the storage device. + */ + void close() { + FatFile::close(); + } + /** Open an ofstream + * \param[in] path file to open + * \param[in] mode open mode + * + * \a mode See fstream::open() for valid modes. + */ + void open(const char* path, openmode mode = out) { + FatStreamBase::open(path, mode | out); + } + /** \return True if stream is open else false. */ + bool is_open() { + return FatFile::isOpen(); + } + + protected: + /// @cond SHOW_PROTECTED + /** + * Internal do not use + * \param[in] c + */ + void putch(char c) { + FatStreamBase::putch(c); + } + void putstr(const char* str) { + FatStreamBase::putstr(str); + } + bool seekoff(off_type off, seekdir way) { + return FatStreamBase::seekoff(off, way); + } + bool seekpos(pos_type pos) { + return FatStreamBase::seekpos(pos); + } + /** + * Internal do not use + * \param[in] b + */ + bool sync() { + return FatStreamBase::sync(); + } + pos_type tellpos() { + return FatStreamBase::curPosition(); + } + /// @endcond +}; +//------------------------------------------------------------------------------ +#endif // fstream_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ios.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ios.h new file mode 100644 index 0000000..7085f2c --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ios.h @@ -0,0 +1,423 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 ios_h +#define ios_h +#include "FatFile.h" +/** + * \file + * \brief \ref ios_base and \ref ios classes + */ +//============================================================================== +/** + * \class ios_base + * \brief Base class for all streams + */ +class ios_base { + public: + /** typedef for iostate bitmask */ + typedef unsigned char iostate; + // State flags. + /** iostate for no flags */ + static const iostate goodbit = 0x00; + /** iostate bad bit for a nonrecoverable error. */ + static const iostate badbit = 0X01; + /** iostate bit for end of file reached */ + static const iostate eofbit = 0x02; + /** iostate fail bit for nonfatal error */ + static const iostate failbit = 0X04; + /** + * unsigned size that can represent maximum file size. + * (violates spec - should be signed) + */ + typedef uint32_t streamsize; + /** type for absolute seek position */ + typedef uint32_t pos_type; + /** type for relative seek offset */ + typedef int32_t off_type; + + /** enumerated type for the direction of relative seeks */ + enum seekdir { + /** seek relative to the beginning of the stream */ + beg, + /** seek relative to the current stream position */ + cur, + /** seek relative to the end of the stream */ + end + }; + /** type for format flags */ + typedef unsigned int fmtflags; + /** left adjust fields */ + static const fmtflags left = 0x0001; + /** right adjust fields */ + static const fmtflags right = 0x0002; + /** fill between sign/base prefix and number */ + static const fmtflags internal = 0x0004; + /** base 10 flag*/ + static const fmtflags dec = 0x0008; + /** base 16 flag */ + static const fmtflags hex = 0x0010; + /** base 8 flag */ + static const fmtflags oct = 0x0020; + // static const fmtflags fixed = 0x0040; + // static const fmtflags scientific = 0x0080; + /** use strings true/false for bool */ + static const fmtflags boolalpha = 0x0100; + /** use prefix 0X for hex and 0 for oct */ + static const fmtflags showbase = 0x0200; + /** always show '.' for floating numbers */ + static const fmtflags showpoint = 0x0400; + /** show + sign for nonnegative numbers */ + static const fmtflags showpos = 0x0800; + /** skip initial white space */ + static const fmtflags skipws = 0x1000; + // static const fmtflags unitbuf = 0x2000; + /** use uppercase letters in number representations */ + static const fmtflags uppercase = 0x4000; + /** mask for adjustfield */ + static const fmtflags adjustfield = left | right | internal; + /** mask for basefield */ + static const fmtflags basefield = dec | hex | oct; + // static const fmtflags floatfield = scientific | fixed; + //---------------------------------------------------------------------------- + /** typedef for iostream open mode */ + typedef uint8_t openmode; + + // Openmode flags. + /** seek to end before each write */ + static const openmode app = 0X4; + /** open and seek to end immediately after opening */ + static const openmode ate = 0X8; + /** perform input and output in binary mode (as opposed to text mode) */ + static const openmode binary = 0X10; + /** open for input */ + static const openmode in = 0X20; + /** open for output */ + static const openmode out = 0X40; + /** truncate an existing stream when opening */ + static const openmode trunc = 0X80; + //---------------------------------------------------------------------------- + ios_base() : m_fill(' '), m_fmtflags(dec | right | skipws) + , m_precision(2), m_width(0) {} + /** \return fill character */ + char fill() { + return m_fill; + } + /** Set fill character + * \param[in] c new fill character + * \return old fill character + */ + char fill(char c) { + char r = m_fill; + m_fill = c; + return r; + } + /** \return format flags */ + fmtflags flags() const { + return m_fmtflags; + } + /** set format flags + * \param[in] fl new flag + * \return old flags + */ + fmtflags flags(fmtflags fl) { + fmtflags tmp = m_fmtflags; + m_fmtflags = fl; + return tmp; + } + /** \return precision */ + int precision() const { + return m_precision; + } + /** set precision + * \param[in] n new precision + * \return old precision + */ + int precision(unsigned int n) { + int r = m_precision; + m_precision = n; + return r; + } + /** set format flags + * \param[in] fl new flags to be or'ed in + * \return old flags + */ + fmtflags setf(fmtflags fl) { + fmtflags r = m_fmtflags; + m_fmtflags |= fl; + return r; + } + /** modify format flags + * \param[in] mask flags to be removed + * \param[in] fl flags to be set after mask bits have been cleared + * \return old flags + */ + fmtflags setf(fmtflags fl, fmtflags mask) { + fmtflags r = m_fmtflags; + m_fmtflags &= ~mask; + m_fmtflags |= fl; + return r; + } + /** clear format flags + * \param[in] fl flags to be cleared + * \return old flags + */ + void unsetf(fmtflags fl) { + m_fmtflags &= ~fl; + } + /** \return width */ + unsigned width() { + return m_width; + } + /** set width + * \param[in] n new width + * \return old width + */ + unsigned width(unsigned n) { + unsigned r = m_width; + m_width = n; + return r; + } + + protected: + /** \return current number base */ + uint8_t flagsToBase() { + uint8_t f = flags() & basefield; + return f == oct ? 8 : f != hex ? 10 : 16; + } + + private: + char m_fill; + fmtflags m_fmtflags; + unsigned char m_precision; + unsigned int m_width; +}; +//------------------------------------------------------------------------------ +/** function for boolalpha manipulator + * \param[in] str The stream + * \return The stream + */ +inline ios_base& boolalpha(ios_base& str) { + str.setf(ios_base::boolalpha); + return str; +} +/** function for dec manipulator + * \param[in] str The stream + * \return The stream + */ +inline ios_base& dec(ios_base& str) { + str.setf(ios_base::dec, ios_base::basefield); + return str; +} +/** function for hex manipulator + * \param[in] str The stream + * \return The stream + */ +inline ios_base& hex(ios_base& str) { + str.setf(ios_base::hex, ios_base::basefield); + return str; +} +/** function for internal manipulator + * \param[in] str The stream + * \return The stream + */ +inline ios_base& internal(ios_base& str) { + str.setf(ios_base::internal, ios_base::adjustfield); + return str; +} +/** function for left manipulator + * \param[in] str The stream + * \return The stream + */ +inline ios_base& left(ios_base& str) { + str.setf(ios_base::left, ios_base::adjustfield); + return str; +} +/** function for noboolalpha manipulator + * \param[in] str The stream + * \return The stream + */ +inline ios_base& noboolalpha(ios_base& str) { + str.unsetf(ios_base::boolalpha); + return str; +} +/** function for noshowbase manipulator + * \param[in] str The stream + * \return The stream + */ +inline ios_base& noshowbase(ios_base& str) { + str.unsetf(ios_base::showbase); + return str; +} +/** function for noshowpoint manipulator + * \param[in] str The stream + * \return The stream + */ +inline ios_base& noshowpoint(ios_base& str) { + str.unsetf(ios_base::showpoint); + return str; +} +/** function for noshowpos manipulator + * \param[in] str The stream + * \return The stream + */ +inline ios_base& noshowpos(ios_base& str) { + str.unsetf(ios_base::showpos); + return str; +} +/** function for noskipws manipulator + * \param[in] str The stream + * \return The stream + */ +inline ios_base& noskipws(ios_base& str) { + str.unsetf(ios_base::skipws); + return str; +} +/** function for nouppercase manipulator + * \param[in] str The stream + * \return The stream + */ +inline ios_base& nouppercase(ios_base& str) { + str.unsetf(ios_base::uppercase); + return str; +} +/** function for oct manipulator + * \param[in] str The stream + * \return The stream + */ +inline ios_base& oct(ios_base& str) { + str.setf(ios_base::oct, ios_base::basefield); + return str; +} +/** function for right manipulator + * \param[in] str The stream + * \return The stream + */ +inline ios_base& right(ios_base& str) { + str.setf(ios_base::right, ios_base::adjustfield); + return str; +} +/** function for showbase manipulator + * \param[in] str The stream + * \return The stream + */ +inline ios_base& showbase(ios_base& str) { + str.setf(ios_base::showbase); + return str; +} +/** function for showpos manipulator + * \param[in] str The stream + * \return The stream + */ +inline ios_base& showpos(ios_base& str) { + str.setf(ios_base::showpos); + return str; +} +/** function for showpoint manipulator + * \param[in] str The stream + * \return The stream + */ +inline ios_base& showpoint(ios_base& str) { + str.setf(ios_base::showpoint); + return str; +} +/** function for skipws manipulator + * \param[in] str The stream + * \return The stream + */ +inline ios_base& skipws(ios_base& str) { + str.setf(ios_base::skipws); + return str; +} +/** function for uppercase manipulator + * \param[in] str The stream + * \return The stream + */ +inline ios_base& uppercase(ios_base& str) { + str.setf(ios_base::uppercase); + return str; +} +//============================================================================== +/** + * \class ios + * \brief Error and state information for all streams + */ +class ios : public ios_base { + public: + /** Create ios with no error flags set */ + ios() : m_iostate(0) {} + + /** \return null pointer if fail() is true. */ + operator const void*() const { + return !fail() ? reinterpret_cast(this) : 0; + } + /** \return true if fail() else false. */ + bool operator!() const { + return fail(); + } + /** \return The iostate flags for this file. */ + iostate rdstate() const { + return m_iostate; + } + /** \return True if no iostate flags are set else false. */ + bool good() const { + return m_iostate == goodbit; + } + /** \return true if end of file has been reached else false. + * + * Warning: An empty file returns false before the first read. + * + * Moral: eof() is only useful in combination with fail(), to find out + * whether EOF was the cause for failure + */ + bool eof() const { + return m_iostate & eofbit; + } + /** \return true if any iostate bit other than eof are set else false. */ + bool fail() const { + return m_iostate & (failbit | badbit); + } + /** \return true if bad bit is set else false. */ + bool bad() const { + return m_iostate & badbit; + } + /** Clear iostate bits. + * + * \param[in] state The flags you want to set after clearing all flags. + **/ + void clear(iostate state = goodbit) { + m_iostate = state; + } + /** Set iostate bits. + * + * \param[in] state Bitts to set. + **/ + void setstate(iostate state) { + m_iostate |= state; + } + + private: + iostate m_iostate; +}; +#endif // ios_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/iostream.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/iostream.h new file mode 100644 index 0000000..91801e3 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/iostream.h @@ -0,0 +1,158 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 iostream_h +#define iostream_h +/** + * \file + * \brief \ref iostream class + */ +#include "istream.h" +#include "ostream.h" +/** Skip white space + * \param[in] is the Stream + * \return The stream + */ +inline istream& ws(istream& is) { + is.skipWhite(); + return is; +} +/** insert endline + * \param[in] os The Stream + * \return The stream + */ +inline ostream& endl(ostream& os) { + os.put('\n'); +#if ENDL_CALLS_FLUSH + os.flush(); +#endif // ENDL_CALLS_FLUSH + return os; +} +/** flush manipulator + * \param[in] os The stream + * \return The stream + */ +inline ostream& flush(ostream& os) { + os.flush(); + return os; +} +/** + * \struct setfill + * \brief type for setfill manipulator + */ +struct setfill { + /** fill character */ + char c; + /** constructor + * + * \param[in] arg new fill character + */ + explicit setfill(char arg) : c(arg) {} +}; +/** setfill manipulator + * \param[in] os the stream + * \param[in] arg set setfill object + * \return the stream + */ +inline ostream &operator<< (ostream &os, const setfill &arg) { + os.fill(arg.c); + return os; +} +/** setfill manipulator + * \param[in] obj the stream + * \param[in] arg set setfill object + * \return the stream + */ +inline istream &operator>>(istream &obj, const setfill &arg) { + obj.fill(arg.c); + return obj; +} +//------------------------------------------------------------------------------ +/** \struct setprecision + * \brief type for setprecision manipulator + */ +struct setprecision { + /** precision */ + unsigned int p; + /** constructor + * \param[in] arg new precision + */ + explicit setprecision(unsigned int arg) : p(arg) {} +}; +/** setprecision manipulator + * \param[in] os the stream + * \param[in] arg set setprecision object + * \return the stream + */ +inline ostream &operator<< (ostream &os, const setprecision &arg) { + os.precision(arg.p); + return os; +} +/** setprecision manipulator + * \param[in] is the stream + * \param[in] arg set setprecision object + * \return the stream + */ +inline istream &operator>>(istream &is, const setprecision &arg) { + is.precision(arg.p); + return is; +} +//------------------------------------------------------------------------------ +/** \struct setw + * \brief type for setw manipulator + */ +struct setw { + /** width */ + unsigned w; + /** constructor + * \param[in] arg new width + */ + explicit setw(unsigned arg) : w(arg) {} +}; +/** setw manipulator + * \param[in] os the stream + * \param[in] arg set setw object + * \return the stream + */ +inline ostream &operator<< (ostream &os, const setw &arg) { + os.width(arg.w); + return os; +} +/** setw manipulator + * \param[in] is the stream + * \param[in] arg set setw object + * \return the stream + */ +inline istream &operator>>(istream &is, const setw &arg) { + is.width(arg.w); + return is; +} +//============================================================================== +/** + * \class iostream + * \brief Input/Output stream + */ +class iostream : public istream, public ostream { +}; +#endif // iostream_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/istream.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/istream.cpp new file mode 100644 index 0000000..86c56f4 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/istream.cpp @@ -0,0 +1,396 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +// #include +#include +#include +#include "istream.h" +//------------------------------------------------------------------------------ +int istream::get() { + int c; + m_gcount = 0; + c = getch(); + if (c < 0) { + setstate(failbit); + } else { + m_gcount = 1; + } + return c; +} +//------------------------------------------------------------------------------ +istream& istream::get(char& c) { + int tmp = get(); + if (tmp >= 0) { + c = tmp; + } + return *this; +} +//------------------------------------------------------------------------------ +istream& istream::get(char *str, streamsize n, char delim) { + int c; + FatPos_t pos; + m_gcount = 0; + while ((m_gcount + 1) < n) { + c = getch(&pos); + if (c < 0) { + break; + } + if (c == delim) { + setpos(&pos); + break; + } + str[m_gcount++] = c; + } + if (n > 0) { + str[m_gcount] = '\0'; + } + if (m_gcount == 0) { + setstate(failbit); + } + return *this; +} +//------------------------------------------------------------------------------ +void istream::getBool(bool *b) { + if ((flags() & boolalpha) == 0) { + getNumber(b); + return; + } +#ifdef __AVR__ + PGM_P truePtr = PSTR("true"); + PGM_P falsePtr = PSTR("false"); +#else // __AVR__ + const char* truePtr = "true"; + const char* falsePtr = "false"; +#endif // __AVR + const uint8_t true_len = 4; + const uint8_t false_len = 5; + bool trueOk = true; + bool falseOk = true; + uint8_t i = 0; + int c = readSkip(); + while (1) { +#ifdef __AVR__ + falseOk = falseOk && c == pgm_read_byte(falsePtr + i); + trueOk = trueOk && c == pgm_read_byte(truePtr + i); +#else // __AVR__ + falseOk = falseOk && c == falsePtr[i]; + trueOk = trueOk && c == truePtr[i]; +#endif // __AVR__ + if (trueOk == false && falseOk == false) { + break; + } + i++; + if (trueOk && i == true_len) { + *b = true; + return; + } + if (falseOk && i == false_len) { + *b = false; + return; + } + c = getch(); + } + setstate(failbit); +} +//------------------------------------------------------------------------------ +void istream::getChar(char* ch) { + int16_t c = readSkip(); + if (c < 0) { + setstate(failbit); + } else { + *ch = c; + } +} +//------------------------------------------------------------------------------ +// +// http://www.exploringbinary.com/category/numbers-in-computers/ +// +int16_t const EXP_LIMIT = 100; +static const uint32_t uint32_max = (uint32_t)-1; +bool istream::getDouble(double* value) { + bool got_digit = false; + bool got_dot = false; + bool neg; + int16_t c; + bool expNeg = false; + int16_t exp = 0; + int16_t fracExp = 0; + uint32_t frac = 0; + FatPos_t endPos; + double pow10; + double v; + + getpos(&endPos); + c = readSkip(); + neg = c == '-'; + if (c == '-' || c == '+') { + c = getch(); + } + while (1) { + if (isdigit(c)) { + got_digit = true; + if (frac < uint32_max/10) { + frac = frac * 10 + (c - '0'); + if (got_dot) { + fracExp--; + } + } else { + if (!got_dot) { + fracExp++; + } + } + } else if (!got_dot && c == '.') { + got_dot = true; + } else { + break; + } + if (fracExp < -EXP_LIMIT || fracExp > EXP_LIMIT) { + goto fail; + } + c = getch(&endPos); + } + if (!got_digit) { + goto fail; + } + if (c == 'e' || c == 'E') { + c = getch(); + expNeg = c == '-'; + if (c == '-' || c == '+') { + c = getch(); + } + while (isdigit(c)) { + if (exp > EXP_LIMIT) { + goto fail; + } + exp = exp * 10 + (c - '0'); + c = getch(&endPos); + } + } + v = static_cast(frac); + exp = expNeg ? fracExp - exp : fracExp + exp; + expNeg = exp < 0; + if (expNeg) { + exp = -exp; + } + pow10 = 10.0; + while (exp) { + if (exp & 1) { + if (expNeg) { + // check for underflow + if (v < FLT_MIN * pow10 && frac != 0) { + goto fail; + } + v /= pow10; + } else { + // check for overflow + if (v > FLT_MAX / pow10) { + goto fail; + } + v *= pow10; + } + } + pow10 *= pow10; + exp >>= 1; + } + setpos(&endPos); + *value = neg ? -v : v; + return true; + +fail: + // error restore position to last good place + setpos(&endPos); + setstate(failbit); + return false; +} +//------------------------------------------------------------------------------ + +istream& istream::getline(char *str, streamsize n, char delim) { + FatPos_t pos; + int c; + m_gcount = 0; + if (n > 0) { + str[0] = '\0'; + } + while (1) { + c = getch(&pos); + if (c < 0) { + break; + } + if (c == delim) { + m_gcount++; + break; + } + if ((m_gcount + 1) >= n) { + setpos(&pos); + setstate(failbit); + break; + } + str[m_gcount++] = c; + str[m_gcount] = '\0'; + } + if (m_gcount == 0) { + setstate(failbit); + } + return *this; +} +//------------------------------------------------------------------------------ +bool istream::getNumber(uint32_t posMax, uint32_t negMax, uint32_t* num) { + int16_t c; + int8_t any = 0; + int8_t have_zero = 0; + uint8_t neg; + uint32_t val = 0; + uint32_t cutoff; + uint8_t cutlim; + FatPos_t endPos; + uint8_t f = flags() & basefield; + uint8_t base = f == oct ? 8 : f != hex ? 10 : 16; + getpos(&endPos); + c = readSkip(); + + neg = c == '-' ? 1 : 0; + if (c == '-' || c == '+') { + c = getch(); + } + + if (base == 16 && c == '0') { // TESTSUITE + c = getch(&endPos); + if (c == 'X' || c == 'x') { + c = getch(); + // remember zero in case no hex digits follow x/X + have_zero = 1; + } else { + any = 1; + } + } + // set values for overflow test + cutoff = neg ? negMax : posMax; + cutlim = cutoff % base; + cutoff /= base; + + while (1) { + if (isdigit(c)) { + c -= '0'; + } else if (isalpha(c)) { + c -= isupper(c) ? 'A' - 10 : 'a' - 10; + } else { + break; + } + if (c >= base) { + break; + } + if (val > cutoff || (val == cutoff && c > cutlim)) { + // indicate overflow error + any = -1; + break; + } + val = val * base + c; + c = getch(&endPos); + any = 1; + } + setpos(&endPos); + if (any > 0 || (have_zero && any >= 0)) { + *num = neg ? -val : val; + return true; + } + setstate(failbit); + return false; +} +//------------------------------------------------------------------------------ +void istream::getStr(char *str) { + FatPos_t pos; + uint16_t i = 0; + uint16_t m = width() ? width() - 1 : 0XFFFE; + if (m != 0) { + getpos(&pos); + int c = readSkip(); + + while (i < m) { + if (c < 0) { + break; + } + if (isspace(c)) { + setpos(&pos); + break; + } + str[i++] = c; + c = getch(&pos); + } + } + str[i] = '\0'; + if (i == 0) { + setstate(failbit); + } + width(0); +} +//------------------------------------------------------------------------------ +istream& istream::ignore(streamsize n, int delim) { + int c; + m_gcount = 0; + while (m_gcount < n) { + c = getch(); + if (c < 0) { + break; + } + m_gcount++; + if (c == delim) { + break; + } + } + return *this; +} +//------------------------------------------------------------------------------ +int istream::peek() { + int16_t c; + FatPos_t pos; + m_gcount = 0; + getpos(&pos); + c = getch(); + if (c < 0) { + if (!bad()) { + setstate(eofbit); + } + } else { + setpos(&pos); + } + return c; +} +//------------------------------------------------------------------------------ +int16_t istream::readSkip() { + int16_t c; + do { + c = getch(); + } while (isspace(c) && (flags() & skipws)); + return c; +} +//------------------------------------------------------------------------------ +/** used to implement ws() */ +void istream::skipWhite() { + int c; + FatPos_t pos; + do { + c = getch(&pos); + } while (isspace(c)); + setpos(&pos); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/istream.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/istream.h new file mode 100644 index 0000000..40d15f2 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/istream.h @@ -0,0 +1,384 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 istream_h +#define istream_h +/** + * \file + * \brief \ref istream class + */ +#include "ios.h" + +/** + * \class istream + * \brief Input Stream + */ +class istream : public virtual ios { + public: + istream() {} + /** call manipulator + * \param[in] pf function to call + * \return the stream + */ + istream& operator>>(istream& (*pf)(istream& str)) { + return pf(*this); + } + /** call manipulator + * \param[in] pf function to call + * \return the stream + */ + istream& operator>>(ios_base& (*pf)(ios_base& str)) { + pf(*this); + return *this; + } + /** call manipulator + * \param[in] pf function to call + * \return the stream + */ + istream& operator>>(ios& (*pf)(ios& str)) { + pf(*this); + return *this; + } + /** + * Extract a character string + * \param[out] str location to store the string. + * \return Is always *this. Failure is indicated by the state of *this. + */ + istream& operator>>(char *str) { + getStr(str); + return *this; + } + /** + * Extract a character + * \param[out] ch location to store the character. + * \return Is always *this. Failure is indicated by the state of *this. + */ + istream& operator>>(char& ch) { + getChar(&ch); + return *this; + } + /** + * Extract a character string + * \param[out] str location to store the string. + * \return Is always *this. Failure is indicated by the state of *this. + */ + istream& operator>>(signed char *str) { + getStr(reinterpret_cast(str)); + return *this; + } + /** + * Extract a character + * \param[out] ch location to store the character. + * \return Is always *this. Failure is indicated by the state of *this. + */ + istream& operator>>(signed char& ch) { + getChar(reinterpret_cast(&ch)); + return *this; + } + /** + * Extract a character string + * \param[out] str location to store the string. + * \return Is always *this. Failure is indicated by the state of *this. + */ + istream& operator>>(unsigned char *str) { + getStr(reinterpret_cast(str)); + return *this; + } + /** + * Extract a character + * \param[out] ch location to store the character. + * \return Is always *this. Failure is indicated by the state of *this. + */ + istream& operator>>(unsigned char& ch) { + getChar(reinterpret_cast(&ch)); + return *this; + } + /** + * Extract a value of type bool. + * \param[out] arg location to store the value. + * \return Is always *this. Failure is indicated by the state of *this. + */ + istream& operator>>(bool& arg) { + getBool(&arg); + return *this; + } + /** + * Extract a value of type short. + * \param[out] arg location to store the value. + * \return Is always *this. Failure is indicated by the state of *this. + */ + istream &operator>>(short& arg) { // NOLINT + getNumber(&arg); + return *this; + } + /** + * Extract a value of type unsigned short. + * \param[out] arg location to store the value. + * \return Is always *this. Failure is indicated by the state of *this. + */ + istream &operator>>(unsigned short& arg) { // NOLINT + getNumber(&arg); + return *this; + } + /** + * Extract a value of type int. + * \param[out] arg location to store the value. + * \return Is always *this. Failure is indicated by the state of *this. + */ + istream &operator>>(int& arg) { + getNumber(&arg); + return *this; + } + /** + * Extract a value of type unsigned int. + * \param[out] arg location to store the value. + * \return Is always *this. Failure is indicated by the state of *this. + */ + istream &operator>>(unsigned int& arg) { + getNumber(&arg); + return *this; + } + /** + * Extract a value of type long. + * \param[out] arg location to store the value. + * \return Is always *this. Failure is indicated by the state of *this. + */ + istream &operator>>(long& arg) { // NOLINT + getNumber(&arg); + return *this; + } + /** + * Extract a value of type unsigned long. + * \param[out] arg location to store the value. + * \return Is always *this. Failure is indicated by the state of *this. + */ + istream &operator>>(unsigned long& arg) { // NOLINT + getNumber(&arg); + return *this; + } + /** + * Extract a value of type double. + * \param[out] arg location to store the value. + * \return Is always *this. Failure is indicated by the state of *this. + */ + istream &operator>> (double& arg) { + getDouble(&arg); + return *this; + } + /** + * Extract a value of type float. + * \param[out] arg location to store the value. + * \return Is always *this. Failure is indicated by the state of *this. + */ + istream &operator>> (float& arg) { + double v; + getDouble(&v); + arg = v; + return *this; + } + /** + * Extract a value of type void*. + * \param[out] arg location to store the value. + * \return Is always *this. Failure is indicated by the state of *this. + */ + istream& operator>> (void*& arg) { + uint32_t val; + getNumber(&val); + arg = reinterpret_cast(val); + return *this; + } + /** + * \return The number of characters extracted by the last unformatted + * input function. + */ + streamsize gcount() const { + return m_gcount; + } + /** + * Extract a character if one is available. + * + * \return The character or -1 if a failure occurs. A failure is indicated + * by the stream state. + */ + int get(); + /** + * Extract a character if one is available. + * + * \param[out] ch location to receive the extracted character. + * + * \return always returns *this. A failure is indicated by the stream state. + */ + istream& get(char& ch); + /** + * Extract characters. + * + * \param[out] str Location to receive extracted characters. + * \param[in] n Size of str. + * \param[in] delim Delimiter + * + * Characters are extracted until extraction fails, n is less than 1, + * n-1 characters are extracted, or the next character equals + * \a delim (delim is not extracted). If no characters are extracted + * failbit is set. If end-of-file occurs the eofbit is set. + * + * \return always returns *this. A failure is indicated by the stream state. + */ + istream& get(char *str, streamsize n, char delim = '\n'); + /** + * Extract characters + * + * \param[out] str Location to receive extracted characters. + * \param[in] n Size of str. + * \param[in] delim Delimiter + * + * Characters are extracted until extraction fails, + * the next character equals \a delim (delim is extracted), or n-1 + * characters are extracted. + * + * The failbit is set if no characters are extracted or n-1 characters + * are extracted. If end-of-file occurs the eofbit is set. + * + * \return always returns *this. A failure is indicated by the stream state. + */ + istream& getline(char *str, streamsize n, char delim = '\n'); + /** + * Extract characters and discard them. + * + * \param[in] n maximum number of characters to ignore. + * \param[in] delim Delimiter. + * + * Characters are extracted until extraction fails, \a n characters + * are extracted, or the next input character equals \a delim + * (the delimiter is extracted). If end-of-file occurs the eofbit is set. + * + * Failures are indicated by the state of the stream. + * + * \return *this + * + */ + istream& ignore(streamsize n = 1, int delim = -1); + /** + * Return the next available character without consuming it. + * + * \return The character if the stream state is good else -1; + * + */ + int peek(); +// istream& read(char *str, streamsize count); +// streamsize readsome(char *str, streamsize count); + /** + * \return the stream position + */ + pos_type tellg() { + return tellpos(); + } + /** + * Set the stream position + * \param[in] pos The absolute position in which to move the read pointer. + * \return Is always *this. Failure is indicated by the state of *this. + */ + istream& seekg(pos_type pos) { + if (!seekpos(pos)) { + setstate(failbit); + } + return *this; + } + /** + * Set the stream position. + * + * \param[in] off An offset to move the read pointer relative to way. + * \a off is a signed 32-bit int so the offset is limited to +- 2GB. + * \param[in] way One of ios::beg, ios::cur, or ios::end. + * \return Is always *this. Failure is indicated by the state of *this. + */ + istream& seekg(off_type off, seekdir way) { + if (!seekoff(off, way)) { + setstate(failbit); + } + return *this; + } + void skipWhite(); + + protected: + /// @cond SHOW_PROTECTED + /** + * Internal - do not use + * \return + */ + virtual int16_t getch() = 0; + /** + * Internal - do not use + * \param[out] pos + * \return + */ + int16_t getch(FatPos_t* pos) { + getpos(pos); + return getch(); + } + /** + * Internal - do not use + * \param[out] pos + */ + virtual void getpos(FatPos_t* pos) = 0; + /** + * Internal - do not use + * \param[in] pos + */ + virtual bool seekoff(off_type off, seekdir way) = 0; + virtual bool seekpos(pos_type pos) = 0; + virtual void setpos(FatPos_t* pos) = 0; + virtual pos_type tellpos() = 0; + + /// @endcond + private: + void getBool(bool *b); + void getChar(char* ch); + bool getDouble(double* value); + template void getNumber(T* value); + bool getNumber(uint32_t posMax, uint32_t negMax, uint32_t* num); + void getStr(char *str); + int16_t readSkip(); + + size_t m_gcount; +}; +//------------------------------------------------------------------------------ +template +void istream::getNumber(T* value) { + uint32_t tmp; + if ((T)-1 < 0) { + // number is signed, max positive value + uint32_t const m = ((uint32_t)-1) >> (33 - sizeof(T) * 8); + // max absolute value of negative number is m + 1. + if (getNumber(m, m + 1, &tmp)) { + *value = (T)tmp; + } + } else { + // max unsigned value for T + uint32_t const m = (T)-1; + if (getNumber(m, m, &tmp)) { + *value = (T)tmp; + } + } +} +#endif // istream_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ostream.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ostream.cpp new file mode 100644 index 0000000..61486bb --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ostream.cpp @@ -0,0 +1,196 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#include +#include "ostream.h" +#ifndef PSTR +#define PSTR(x) x +#endif +//------------------------------------------------------------------------------ +void ostream::do_fill(unsigned len) { + for (; len < width(); len++) { + putch(fill()); + } + width(0); +} +//------------------------------------------------------------------------------ +void ostream::fill_not_left(unsigned len) { + if ((flags() & adjustfield) != left) { + do_fill(len); + } +} +//------------------------------------------------------------------------------ +char* ostream::fmtNum(uint32_t n, char *ptr, uint8_t base) { + char a = flags() & uppercase ? 'A' - 10 : 'a' - 10; + do { + uint32_t m = n; + n /= base; + char c = m - base * n; + *--ptr = c < 10 ? c + '0' : c + a; + } while (n); + return ptr; +} +//------------------------------------------------------------------------------ +void ostream::putBool(bool b) { + if (flags() & boolalpha) { + if (b) { + putPgm(PSTR("true")); + } else { + putPgm(PSTR("false")); + } + } else { + putChar(b ? '1' : '0'); + } +} +//------------------------------------------------------------------------------ +void ostream::putChar(char c) { + fill_not_left(1); + putch(c); + do_fill(1); +} +//------------------------------------------------------------------------------ +void ostream::putDouble(double n) { + uint8_t nd = precision(); + double round = 0.5; + char sign; + char buf[13]; // room for sign, 10 digits, '.', and zero byte + char *end = buf + sizeof(buf) - 1; + char *str = end; + // terminate string + *end = '\0'; + + // get sign and make nonnegative + if (n < 0.0) { + sign = '-'; + n = -n; + } else { + sign = flags() & showpos ? '+' : '\0'; + } + // check for larger than uint32_t + if (n > 4.0E9) { + putPgm(PSTR("BIG FLT")); + return; + } + // round up and separate int and fraction parts + for (uint8_t i = 0; i < nd; ++i) { + round *= 0.1; + } + n += round; + uint32_t intPart = n; + double fractionPart = n - intPart; + + // format intPart and decimal point + if (nd || (flags() & showpoint)) { + *--str = '.'; + } + str = fmtNum(intPart, str, 10); + + // calculate length for fill + uint8_t len = sign ? 1 : 0; + len += nd + end - str; + + // extract adjust field + fmtflags adj = flags() & adjustfield; + if (adj == internal) { + if (sign) { + putch(sign); + } + do_fill(len); + } else { + // do fill for internal or right + fill_not_left(len); + if (sign) { + *--str = sign; + } + } + putstr(str); + // output fraction + while (nd-- > 0) { + fractionPart *= 10.0; + int digit = static_cast(fractionPart); + putch(digit + '0'); + fractionPart -= digit; + } + // do fill if not done above + do_fill(len); +} +//------------------------------------------------------------------------------ +void ostream::putNum(int32_t n) { + bool neg = n < 0 && flagsToBase() == 10; + if (neg) { + n = -n; + } + putNum(n, neg); +} +//------------------------------------------------------------------------------ +void ostream::putNum(uint32_t n, bool neg) { + char buf[13]; + char* end = buf + sizeof(buf) - 1; + char* num; + char* str; + uint8_t base = flagsToBase(); + *end = '\0'; + str = num = fmtNum(n, end, base); + if (base == 10) { + if (neg) { + *--str = '-'; + } else if (flags() & showpos) { + *--str = '+'; + } + } else if (flags() & showbase) { + if (flags() & hex) { + *--str = flags() & uppercase ? 'X' : 'x'; + } + *--str = '0'; + } + uint8_t len = end - str; + fmtflags adj = flags() & adjustfield; + if (adj == internal) { + while (str < num) { + putch(*str++); + } + } + if (adj != left) { + do_fill(len); + } + putstr(str); + do_fill(len); +} +//------------------------------------------------------------------------------ +void ostream::putPgm(const char* str) { + int n; + for (n = 0; pgm_read_byte(&str[n]); n++) {} + fill_not_left(n); + for (uint8_t c; (c = pgm_read_byte(str)); str++) { + putch(c); + } + do_fill(n); +} +//------------------------------------------------------------------------------ +void ostream::putStr(const char *str) { + unsigned n = strlen(str); + fill_not_left(n); + putstr(str); + do_fill(n); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ostream.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ostream.h new file mode 100644 index 0000000..57609e2 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ostream.h @@ -0,0 +1,276 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 ostream_h +#define ostream_h +/** + * \file + * \brief \ref ostream class + */ +#include "ios.h" +//============================================================================== +/** + * \class ostream + * \brief Output Stream + */ +class ostream : public virtual ios { + public: + ostream() {} + + /** call manipulator + * \param[in] pf function to call + * \return the stream + */ + ostream& operator<< (ostream& (*pf)(ostream& str)) { + return pf(*this); + } + /** call manipulator + * \param[in] pf function to call + * \return the stream + */ + ostream& operator<< (ios_base& (*pf)(ios_base& str)) { + pf(*this); + return *this; + } + /** Output bool + * \param[in] arg value to output + * \return the stream + */ + ostream &operator<< (bool arg) { + putBool(arg); + return *this; + } + /** Output string + * \param[in] arg string to output + * \return the stream + */ + ostream &operator<< (const char *arg) { + putStr(arg); + return *this; + } + /** Output string + * \param[in] arg string to output + * \return the stream + */ + ostream &operator<< (const signed char *arg) { + putStr((const char*)arg); + return *this; + } + /** Output string + * \param[in] arg string to output + * \return the stream + */ + ostream &operator<< (const unsigned char *arg) { + putStr((const char*)arg); + return *this; + } + /** Output character + * \param[in] arg character to output + * \return the stream + */ + ostream &operator<< (char arg) { + putChar(arg); + return *this; + } + /** Output character + * \param[in] arg character to output + * \return the stream + */ + ostream &operator<< (signed char arg) { + putChar(static_cast(arg)); + return *this; + } + /** Output character + * \param[in] arg character to output + * \return the stream + */ + ostream &operator<< (unsigned char arg) { + putChar(static_cast(arg)); + return *this; + } + /** Output double + * \param[in] arg value to output + * \return the stream + */ + ostream &operator<< (double arg) { + putDouble(arg); + return *this; + } + /** Output float + * \param[in] arg value to output + * \return the stream + */ + ostream &operator<< (float arg) { + putDouble(arg); + return *this; + } + /** Output signed short + * \param[in] arg value to output + * \return the stream + */ + ostream &operator<< (short arg) { // NOLINT + putNum((int32_t)arg); + return *this; + } + /** Output unsigned short + * \param[in] arg value to output + * \return the stream + */ + ostream &operator<< (unsigned short arg) { // NOLINT + putNum((uint32_t)arg); + return *this; + } + /** Output signed int + * \param[in] arg value to output + * \return the stream + */ + ostream &operator<< (int arg) { + putNum((int32_t)arg); + return *this; + } + /** Output unsigned int + * \param[in] arg value to output + * \return the stream + */ + ostream &operator<< (unsigned int arg) { + putNum((uint32_t)arg); + return *this; + } + /** Output signed long + * \param[in] arg value to output + * \return the stream + */ + ostream &operator<< (long arg) { // NOLINT + putNum((int32_t)arg); + return *this; + } + /** Output unsigned long + * \param[in] arg value to output + * \return the stream + */ + ostream &operator<< (unsigned long arg) { // NOLINT + putNum((uint32_t)arg); + return *this; + } + /** Output pointer + * \param[in] arg value to output + * \return the stream + */ + ostream& operator<< (const void* arg) { + putNum(reinterpret_cast(arg)); + return *this; + } +#if (defined(ARDUINO) && ENABLE_ARDUINO_FEATURES) || defined(DOXYGEN) + /** Output a string from flash using the Arduino F() macro. + * \param[in] arg pointing to flash string + * \return the stream + */ + ostream &operator<< (const __FlashStringHelper *arg) { + putPgm(reinterpret_cast(arg)); + return *this; + } +#endif // (defined(ARDUINO) && ENABLE_ARDUINO_FEATURES) || defined(DOXYGEN) + /** + * Puts a character in a stream. + * + * The unformatted output function inserts the element \a ch. + * It returns *this. + * + * \param[in] ch The character + * \return A reference to the ostream object. + */ + ostream& put(char ch) { + putch(ch); + return *this; + } +// ostream& write(char *str, streamsize count); + /** + * Flushes the buffer associated with this stream. The flush function + * calls the sync function of the associated file. + * \return A reference to the ostream object. + */ + ostream& flush() { + if (!sync()) { + setstate(badbit); + } + return *this; + } + /** + * \return the stream position + */ + pos_type tellp() { + return tellpos(); + } + /** + * Set the stream position + * \param[in] pos The absolute position in which to move the write pointer. + * \return Is always *this. Failure is indicated by the state of *this. + */ + ostream& seekp(pos_type pos) { + if (!seekpos(pos)) { + setstate(failbit); + } + return *this; + } + /** + * Set the stream position. + * + * \param[in] off An offset to move the write pointer relative to way. + * \a off is a signed 32-bit int so the offset is limited to +- 2GB. + * \param[in] way One of ios::beg, ios::cur, or ios::end. + * \return Is always *this. Failure is indicated by the state of *this. + */ + ostream& seekp(off_type off, seekdir way) { + if (!seekoff(off, way)) { + setstate(failbit); + } + return *this; + } + + protected: + /// @cond SHOW_PROTECTED + /** Put character with binary/text conversion + * \param[in] ch character to write + */ + virtual void putch(char ch) = 0; + virtual void putstr(const char *str) = 0; + virtual bool seekoff(off_type pos, seekdir way) = 0; + virtual bool seekpos(pos_type pos) = 0; + virtual bool sync() = 0; + + virtual pos_type tellpos() = 0; + /// @endcond + private: + void do_fill(unsigned len); + void fill_not_left(unsigned len); + char* fmtNum(uint32_t n, char *ptr, uint8_t base); + void putBool(bool b); + void putChar(char c); + void putDouble(double n); + void putNum(uint32_t n, bool neg = false); + void putNum(int32_t n); + void putPgm(const char* str); + void putStr(const char* str); +}; +#endif // ostream_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FreeStack.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FreeStack.h new file mode 100644 index 0000000..709fc46 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FreeStack.h @@ -0,0 +1,61 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 FreeStack_h +#define FreeStack_h +/** + * \file + * \brief FreeStack() function. + */ +#if defined(__AVR__) || defined(DOXYGEN) +/** boundary between stack and heap. */ +extern char *__brkval; +/** End of bss section.*/ +extern char __bss_end; +/** Amount of free stack space. + * \return The number of free bytes. + */ +static int FreeStack() { + char* sp = reinterpret_cast(SP); + return __brkval ? sp - __brkval : sp - &__bss_end; +// char top; +// return __brkval ? &top - __brkval : &top - &__bss_end; +} +#elif defined(PLATFORM_ID) // Particle board +static int FreeStack() { + return System.freeMemory(); +} +#elif defined(__arm__) +extern "C" char* sbrk(int incr); +static int FreeStack() { + char top = 't'; + return &top - reinterpret_cast(sbrk(0)); +} +#else +#warning FreeStack is not defined for this system. +static int FreeStack() { + return 0; +} +#endif +#endif // FreeStack_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/MinimumSerial.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/MinimumSerial.cpp new file mode 100644 index 0000000..d7161e8 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/MinimumSerial.cpp @@ -0,0 +1,71 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#include "SysCall.h" +#if defined(UDR0) || defined(DOXYGEN) +#include "MinimumSerial.h" +const uint16_t MIN_2X_BAUD = F_CPU/(4*(2*0XFFF + 1)) + 1; +//------------------------------------------------------------------------------ +int MinimumSerial::available() { + return UCSR0A & (1 << RXC0) ? 1 : 0; +} +//------------------------------------------------------------------------------ +void MinimumSerial::begin(uint32_t baud) { + uint16_t baud_setting; + // don't worry, the compiler will squeeze out F_CPU != 16000000UL + if ((F_CPU != 16000000UL || baud != 57600) && baud > MIN_2X_BAUD) { + // Double the USART Transmission Speed + UCSR0A = 1 << U2X0; + baud_setting = (F_CPU / 4 / baud - 1) / 2; + } else { + // hardcoded exception for compatibility with the bootloader shipped + // with the Duemilanove and previous boards and the firmware on the 8U2 + // on the Uno and Mega 2560. + UCSR0A = 0; + baud_setting = (F_CPU / 8 / baud - 1) / 2; + } + // assign the baud_setting + UBRR0H = baud_setting >> 8; + UBRR0L = baud_setting; + // enable transmit and receive + UCSR0B |= (1 << TXEN0) | (1 << RXEN0); +} +//------------------------------------------------------------------------------ +void MinimumSerial::flush() { + while (((1 << UDRIE0) & UCSR0B) || !(UCSR0A & (1 << UDRE0))) {} +} +//------------------------------------------------------------------------------ +int MinimumSerial::read() { + if (UCSR0A & (1 << RXC0)) { + return UDR0; + } + return -1; +} +//------------------------------------------------------------------------------ +size_t MinimumSerial::write(uint8_t b) { + while (((1 << UDRIE0) & UCSR0B) || !(UCSR0A & (1 << UDRE0))) {} + UDR0 = b; + return 1; +} +#endif // defined(UDR0) || defined(DOXYGEN) diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/MinimumSerial.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/MinimumSerial.h new file mode 100644 index 0000000..6fba5b8 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/MinimumSerial.h @@ -0,0 +1,67 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ + /** + * \file + * \brief Minimal AVR Serial driver. + */ +#ifndef MinimumSerial_h +#define MinimumSerial_h +#include "SysCall.h" +//============================================================================== +/** + * \class MinimumSerial + * \brief mini serial class for the %SdFat library. + */ +class MinimumSerial : public Print { + public: + /** \return true for hardware serial */ + operator bool() { return true; } + /** + * \return one if data is available. + */ + int available(); + /** + * Set baud rate for serial port zero and enable in non interrupt mode. + * Do not call this function if you use another serial library. + * \param[in] baud rate + */ + void begin(uint32_t baud); + /** Wait for write done. */ + void flush(); + /** + * Unbuffered read + * \return -1 if no character is available or an available character. + */ + int read(); + /** + * Unbuffered write + * + * \param[in] b byte to write. + * \return 1 + */ + size_t write(uint8_t b); + using Print::write; +}; +#endif // MinimumSerial_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdInfo.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdInfo.h new file mode 100644 index 0000000..f8943b4 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdInfo.h @@ -0,0 +1,485 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 SdInfo_h +#define SdInfo_h +#include +// Based on the document: +// +// SD Specifications +// Part 1 +// Physical Layer +// Simplified Specification +// Version 5.00 +// Aug 10, 2016 +// +// https://www.sdcard.org/downloads/pls/ +//------------------------------------------------------------------------------ +// SD card errors +// See the SD Specification for command info. +typedef enum { + SD_CARD_ERROR_NONE = 0, + + // Basic commands and switch command. + SD_CARD_ERROR_CMD0 = 0X20, + SD_CARD_ERROR_CMD2, + SD_CARD_ERROR_CMD3, + SD_CARD_ERROR_CMD6, + SD_CARD_ERROR_CMD7, + SD_CARD_ERROR_CMD8, + SD_CARD_ERROR_CMD9, + SD_CARD_ERROR_CMD10, + SD_CARD_ERROR_CMD12, + SD_CARD_ERROR_CMD13, + + // Read, write, erase, and extension commands. + SD_CARD_ERROR_CMD17 = 0X30, + SD_CARD_ERROR_CMD18, + SD_CARD_ERROR_CMD24, + SD_CARD_ERROR_CMD25, + SD_CARD_ERROR_CMD32, + SD_CARD_ERROR_CMD33, + SD_CARD_ERROR_CMD38, + SD_CARD_ERROR_CMD58, + SD_CARD_ERROR_CMD59, + + // Application specific commands. + SD_CARD_ERROR_ACMD6 = 0X40, + SD_CARD_ERROR_ACMD13, + SD_CARD_ERROR_ACMD23, + SD_CARD_ERROR_ACMD41, + + // Read/write errors + SD_CARD_ERROR_READ = 0X50, + SD_CARD_ERROR_READ_CRC, + SD_CARD_ERROR_READ_FIFO, + SD_CARD_ERROR_READ_REG, + SD_CARD_ERROR_READ_START, + SD_CARD_ERROR_READ_TIMEOUT, + SD_CARD_ERROR_STOP_TRAN, + SD_CARD_ERROR_WRITE, + SD_CARD_ERROR_WRITE_FIFO, + SD_CARD_ERROR_WRITE_START, + SD_CARD_ERROR_FLASH_PROGRAMMING, + SD_CARD_ERROR_WRITE_TIMEOUT, + + // Misc errors. + SD_CARD_ERROR_DMA = 0X60, + SD_CARD_ERROR_ERASE, + SD_CARD_ERROR_ERASE_SINGLE_BLOCK, + SD_CARD_ERROR_ERASE_TIMEOUT, + SD_CARD_ERROR_INIT_NOT_CALLED, + SD_CARD_ERROR_FUNCTION_NOT_SUPPORTED +} sd_error_code_t; +//------------------------------------------------------------------------------ +// card types +/** Standard capacity V1 SD card */ +const uint8_t SD_CARD_TYPE_SD1 = 1; +/** Standard capacity V2 SD card */ +const uint8_t SD_CARD_TYPE_SD2 = 2; +/** High Capacity SD card */ +const uint8_t SD_CARD_TYPE_SDHC = 3; +//------------------------------------------------------------------------------ +#define SD_SCK_HZ(maxSpeed) SPISettings(maxSpeed, MSBFIRST, SPI_MODE0) +#define SD_SCK_MHZ(maxMhz) SPISettings(1000000UL*maxMhz, MSBFIRST, SPI_MODE0) +// SPI divisor constants +/** Set SCK to max rate of F_CPU/2. */ +#define SPI_FULL_SPEED SD_SCK_MHZ(50) +/** Set SCK rate to F_CPU/3 for Due */ +#define SPI_DIV3_SPEED SD_SCK_HZ(F_CPU/3) +/** Set SCK rate to F_CPU/4. */ +#define SPI_HALF_SPEED SD_SCK_HZ(F_CPU/4) +/** Set SCK rate to F_CPU/6 for Due */ +#define SPI_DIV6_SPEED SD_SCK_HZ(F_CPU/6) +/** Set SCK rate to F_CPU/8. */ +#define SPI_QUARTER_SPEED SD_SCK_HZ(F_CPU/8) +/** Set SCK rate to F_CPU/16. */ +#define SPI_EIGHTH_SPEED SD_SCK_HZ(F_CPU/16) +/** Set SCK rate to F_CPU/32. */ +#define SPI_SIXTEENTH_SPEED SD_SCK_HZ(F_CPU/32) +//------------------------------------------------------------------------------ +// SD operation timeouts +/** CMD0 retry count */ +const uint8_t SD_CMD0_RETRY = 10; +/** command timeout ms */ +const uint16_t SD_CMD_TIMEOUT = 300; +/** init timeout ms */ +const uint16_t SD_INIT_TIMEOUT = 2000; +/** erase timeout ms */ +const uint16_t SD_ERASE_TIMEOUT = 10000; +/** read timeout ms */ +const uint16_t SD_READ_TIMEOUT = 1000; +/** write time out ms */ +const uint16_t SD_WRITE_TIMEOUT = 2000; +//------------------------------------------------------------------------------ +// SD card commands +/** GO_IDLE_STATE - init card in spi mode if CS low */ +const uint8_t CMD0 = 0X00; +/** ALL_SEND_CID - Asks any card to send the CID. */ +const uint8_t CMD2 = 0X02; +/** SEND_RELATIVE_ADDR - Ask the card to publish a new RCA. */ +const uint8_t CMD3 = 0X03; +/** SWITCH_FUNC - Switch Function Command */ +const uint8_t CMD6 = 0X06; +/** SELECT/DESELECT_CARD - toggles between the stand-by and transfer states. */ +const uint8_t CMD7 = 0X07; +/** SEND_IF_COND - verify SD Memory Card interface operating condition.*/ +const uint8_t CMD8 = 0X08; +/** SEND_CSD - read the Card Specific Data (CSD register) */ +const uint8_t CMD9 = 0X09; +/** SEND_CID - read the card identification information (CID register) */ +const uint8_t CMD10 = 0X0A; +/** STOP_TRANSMISSION - end multiple block read sequence */ +const uint8_t CMD12 = 0X0C; +/** SEND_STATUS - read the card status register */ +const uint8_t CMD13 = 0X0D; +/** READ_SINGLE_BLOCK - read a single data block from the card */ +const uint8_t CMD17 = 0X11; +/** READ_MULTIPLE_BLOCK - read a multiple data blocks from the card */ +const uint8_t CMD18 = 0X12; +/** WRITE_BLOCK - write a single data block to the card */ +const uint8_t CMD24 = 0X18; +/** WRITE_MULTIPLE_BLOCK - write blocks of data until a STOP_TRANSMISSION */ +const uint8_t CMD25 = 0X19; +/** ERASE_WR_BLK_START - sets the address of the first block to be erased */ +const uint8_t CMD32 = 0X20; +/** ERASE_WR_BLK_END - sets the address of the last block of the continuous + range to be erased*/ +const uint8_t CMD33 = 0X21; +/** ERASE - erase all previously selected blocks */ +const uint8_t CMD38 = 0X26; +/** APP_CMD - escape for application specific command */ +const uint8_t CMD55 = 0X37; +/** READ_OCR - read the OCR register of a card */ +const uint8_t CMD58 = 0X3A; +/** CRC_ON_OFF - enable or disable CRC checking */ +const uint8_t CMD59 = 0X3B; +/** SET_BUS_WIDTH - Defines the data bus width for data transfer. */ +const uint8_t ACMD6 = 0X06; +/** SD_STATUS - Send the SD Status. */ +const uint8_t ACMD13 = 0X0D; +/** SET_WR_BLK_ERASE_COUNT - Set the number of write blocks to be + pre-erased before writing */ +const uint8_t ACMD23 = 0X17; +/** SD_SEND_OP_COMD - Sends host capacity support information and + activates the card's initialization process */ +const uint8_t ACMD41 = 0X29; +//============================================================================== +// CARD_STATUS +/** The command's argument was out of the allowed range for this card. */ +const uint32_t CARD_STATUS_OUT_OF_RANGE = 1UL << 31; +/** A misaligned address which did not match the block length. */ +const uint32_t CARD_STATUS_ADDRESS_ERROR = 1UL << 30; +/** The transferred block length is not allowed for this card. */ +const uint32_t CARD_STATUS_BLOCK_LEN_ERROR = 1UL << 29; +/** An error in the sequence of erase commands occurred. */ +const uint32_t CARD_STATUS_ERASE_SEQ_ERROR = 1UL <<28; +/** An invalid selection of write-blocks for erase occurred. */ +const uint32_t CARD_STATUS_ERASE_PARAM = 1UL << 27; +/** Set when the host attempts to write to a protected block. */ +const uint32_t CARD_STATUS_WP_VIOLATION = 1UL << 26; +/** When set, signals that the card is locked by the host. */ +const uint32_t CARD_STATUS_CARD_IS_LOCKED = 1UL << 25; +/** Set when a sequence or password error has been detected. */ +const uint32_t CARD_STATUS_LOCK_UNLOCK_FAILED = 1UL << 24; +/** The CRC check of the previous command failed. */ +const uint32_t CARD_STATUS_COM_CRC_ERROR = 1UL << 23; +/** Command not legal for the card state. */ +const uint32_t CARD_STATUS_ILLEGAL_COMMAND = 1UL << 22; +/** Card internal ECC was applied but failed to correct the data. */ +const uint32_t CARD_STATUS_CARD_ECC_FAILED = 1UL << 21; +/** Internal card controller error */ +const uint32_t CARD_STATUS_CC_ERROR = 1UL << 20; +/** A general or an unknown error occurred during the operation. */ +const uint32_t CARD_STATUS_ERROR = 1UL << 19; +// bits 19, 18, and 17 reserved. +/** Permanent WP set or attempt to change read only values of CSD. */ +const uint32_t CARD_STATUS_CSD_OVERWRITE = 1UL <<16; +/** partial address space was erased due to write protect. */ +const uint32_t CARD_STATUS_WP_ERASE_SKIP = 1UL << 15; +/** The command has been executed without using the internal ECC. */ +const uint32_t CARD_STATUS_CARD_ECC_DISABLED = 1UL << 14; +/** out of erase sequence command was received. */ +const uint32_t CARD_STATUS_ERASE_RESET = 1UL << 13; +/** The state of the card when receiving the command. + * 0 = idle + * 1 = ready + * 2 = ident + * 3 = stby + * 4 = tran + * 5 = data + * 6 = rcv + * 7 = prg + * 8 = dis + * 9-14 = reserved + * 15 = reserved for I/O mode + */ +const uint32_t CARD_STATUS_CURRENT_STATE = 0XF << 9; +/** Shift for current state. */ +const uint32_t CARD_STATUS_CURRENT_STATE_SHIFT = 9; +/** Corresponds to buffer empty signaling on the bus. */ +const uint32_t CARD_STATUS_READY_FOR_DATA = 1UL << 8; +// bit 7 reserved. +/** Extension Functions may set this bit to get host to deal with events. */ +const uint32_t CARD_STATUS_FX_EVENT = 1UL << 6; +/** The card will expect ACMD, or the command has been interpreted as ACMD */ +const uint32_t CARD_STATUS_APP_CMD = 1UL << 5; +// bit 4 reserved. +/** Error in the sequence of the authentication process. */ +const uint32_t CARD_STATUS_AKE_SEQ_ERROR = 1UL << 3; +// bits 2,1, and 0 reserved for manufacturer test mode. +//============================================================================== +/** status for card in the ready state */ +const uint8_t R1_READY_STATE = 0X00; +/** status for card in the idle state */ +const uint8_t R1_IDLE_STATE = 0X01; +/** status bit for illegal command */ +const uint8_t R1_ILLEGAL_COMMAND = 0X04; +/** start data token for read or write single block*/ +const uint8_t DATA_START_BLOCK = 0XFE; +/** stop token for write multiple blocks*/ +const uint8_t STOP_TRAN_TOKEN = 0XFD; +/** start data token for write multiple blocks*/ +const uint8_t WRITE_MULTIPLE_TOKEN = 0XFC; +/** mask for data response tokens after a write block operation */ +const uint8_t DATA_RES_MASK = 0X1F; +/** write data accepted token */ +const uint8_t DATA_RES_ACCEPTED = 0X05; +//============================================================================== +/** + * \class CID + * \brief Card IDentification (CID) register. + */ +typedef struct CID { + // byte 0 + /** Manufacturer ID */ + unsigned char mid; + // byte 1-2 + /** OEM/Application ID */ + char oid[2]; + // byte 3-7 + /** Product name */ + char pnm[5]; + // byte 8 + /** Product revision least significant digit */ + unsigned char prv_m : 4; + /** Product revision most significant digit */ + unsigned char prv_n : 4; + // byte 9-12 + /** Product serial number */ + uint32_t psn; + // byte 13 + /** Manufacturing date year low digit */ + unsigned char mdt_year_high : 4; + /** not used */ + unsigned char reserved : 4; + // byte 14 + /** Manufacturing date month */ + unsigned char mdt_month : 4; + /** Manufacturing date year low digit */ + unsigned char mdt_year_low : 4; + // byte 15 + /** not used always 1 */ + unsigned char always1 : 1; + /** CRC7 checksum */ + unsigned char crc : 7; +} __attribute__((packed)) cid_t; + +//============================================================================== +/** + * \class CSDV1 + * \brief CSD register for version 1.00 cards . + */ +typedef struct CSDV1 { + // byte 0 + unsigned char reserved1 : 6; + unsigned char csd_ver : 2; + // byte 1 + unsigned char taac; + // byte 2 + unsigned char nsac; + // byte 3 + unsigned char tran_speed; + // byte 4 + unsigned char ccc_high; + // byte 5 + unsigned char read_bl_len : 4; + unsigned char ccc_low : 4; + // byte 6 + unsigned char c_size_high : 2; + unsigned char reserved2 : 2; + unsigned char dsr_imp : 1; + unsigned char read_blk_misalign : 1; + unsigned char write_blk_misalign : 1; + unsigned char read_bl_partial : 1; + // byte 7 + unsigned char c_size_mid; + // byte 8 + unsigned char vdd_r_curr_max : 3; + unsigned char vdd_r_curr_min : 3; + unsigned char c_size_low : 2; + // byte 9 + unsigned char c_size_mult_high : 2; + unsigned char vdd_w_cur_max : 3; + unsigned char vdd_w_curr_min : 3; + // byte 10 + unsigned char sector_size_high : 6; + unsigned char erase_blk_en : 1; + unsigned char c_size_mult_low : 1; + // byte 11 + unsigned char wp_grp_size : 7; + unsigned char sector_size_low : 1; + // byte 12 + unsigned char write_bl_len_high : 2; + unsigned char r2w_factor : 3; + unsigned char reserved3 : 2; + unsigned char wp_grp_enable : 1; + // byte 13 + unsigned char reserved4 : 5; + unsigned char write_partial : 1; + unsigned char write_bl_len_low : 2; + // byte 14 + unsigned char reserved5: 2; + unsigned char file_format : 2; + unsigned char tmp_write_protect : 1; + unsigned char perm_write_protect : 1; + unsigned char copy : 1; + /** Indicates the file format on the card */ + unsigned char file_format_grp : 1; + // byte 15 + unsigned char always1 : 1; + unsigned char crc : 7; +} __attribute__((packed)) csd1_t; +//============================================================================== +/** + * \class CSDV2 + * \brief CSD register for version 2.00 cards. + */ +typedef struct CSDV2 { + // byte 0 + unsigned char reserved1 : 6; + unsigned char csd_ver : 2; + // byte 1 + /** fixed to 0X0E */ + unsigned char taac; + // byte 2 + /** fixed to 0 */ + unsigned char nsac; + // byte 3 + unsigned char tran_speed; + // byte 4 + unsigned char ccc_high; + // byte 5 + /** This field is fixed to 9h, which indicates READ_BL_LEN=512 Byte */ + unsigned char read_bl_len : 4; + unsigned char ccc_low : 4; + // byte 6 + /** not used */ + unsigned char reserved2 : 4; + unsigned char dsr_imp : 1; + /** fixed to 0 */ + unsigned char read_blk_misalign : 1; + /** fixed to 0 */ + unsigned char write_blk_misalign : 1; + /** fixed to 0 - no partial read */ + unsigned char read_bl_partial : 1; + // byte 7 + /** high part of card size */ + unsigned char c_size_high : 6; + /** not used */ + unsigned char reserved3 : 2; + // byte 8 + /** middle part of card size */ + unsigned char c_size_mid; + // byte 9 + /** low part of card size */ + unsigned char c_size_low; + // byte 10 + /** sector size is fixed at 64 KB */ + unsigned char sector_size_high : 6; + /** fixed to 1 - erase single is supported */ + unsigned char erase_blk_en : 1; + /** not used */ + unsigned char reserved4 : 1; + // byte 11 + unsigned char wp_grp_size : 7; + /** sector size is fixed at 64 KB */ + unsigned char sector_size_low : 1; + // byte 12 + /** write_bl_len fixed for 512 byte blocks */ + unsigned char write_bl_len_high : 2; + /** fixed value of 2 */ + unsigned char r2w_factor : 3; + /** not used */ + unsigned char reserved5 : 2; + /** fixed value of 0 - no write protect groups */ + unsigned char wp_grp_enable : 1; + // byte 13 + unsigned char reserved6 : 5; + /** always zero - no partial block read*/ + unsigned char write_partial : 1; + /** write_bl_len fixed for 512 byte blocks */ + unsigned char write_bl_len_low : 2; + // byte 14 + unsigned char reserved7: 2; + /** Do not use always 0 */ + unsigned char file_format : 2; + unsigned char tmp_write_protect : 1; + unsigned char perm_write_protect : 1; + unsigned char copy : 1; + /** Do not use always 0 */ + unsigned char file_format_grp : 1; + // byte 15 + /** not used always 1 */ + unsigned char always1 : 1; + /** checksum */ + unsigned char crc : 7; +} __attribute__((packed)) csd2_t; +//============================================================================== +/** + * \class csd_t + * \brief Union of old and new style CSD register. + */ +union csd_t { + csd1_t v1; + csd2_t v2; +}; +//----------------------------------------------------------------------------- +inline uint32_t sdCardCapacity(csd_t* csd) { + if (csd->v1.csd_ver == 0) { + uint8_t read_bl_len = csd->v1.read_bl_len; + uint16_t c_size = (csd->v1.c_size_high << 10) + | (csd->v1.c_size_mid << 2) | csd->v1.c_size_low; + uint8_t c_size_mult = (csd->v1.c_size_mult_high << 1) + | csd->v1.c_size_mult_low; + return (uint32_t)(c_size + 1) << (c_size_mult + read_bl_len - 7); + } else if (csd->v2.csd_ver == 1) { + uint32_t c_size = 0X10000L * csd->v2.c_size_high + 0X100L + * (uint32_t)csd->v2.c_size_mid + csd->v2.c_size_low; + return (c_size + 1) << 10; + } else { + return 0; + } +} +#endif // SdInfo_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCard.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCard.cpp new file mode 100644 index 0000000..4497120 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCard.cpp @@ -0,0 +1,802 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#include "SdSpiCard.h" +//============================================================================== +// debug trace macro +#define SD_TRACE(m, b) +// #define SD_TRACE(m, b) Serial.print(m);Serial.println(b); +#define SD_CS_DBG(m) +// #define SD_CS_DBG(m) Serial.println(F(m)); + +#define DBG_PROFILE_STATS 0 +#if DBG_PROFILE_STATS + +#define DBG_TAG_LIST\ + DBG_TAG(DBG_CMD0_TIME, "CMD0 time")\ + DBG_TAG(DBG_ACMD41_TIME, "ACMD41 time")\ + DBG_TAG(DBG_CMD_BUSY, "cmd busy")\ + DBG_TAG(DBG_ERASE_BUSY, "erase busy")\ + DBG_TAG(DBG_WAIT_READ, "wait read")\ + DBG_TAG(DBG_WRITE_FLASH, "write flash")\ + DBG_TAG(DBG_WRITE_BUSY, "write busy")\ + DBG_TAG(DBG_WRITE_STOP, "write stop")\ + DBG_TAG(DBG_ACMD41_COUNT, "ACMD41 count")\ + DBG_TAG(DBG_CMD0_COUNT, "CMD0 count") + +#define DBG_TIME_DIM DBG_ACMD41_COUNT + +enum DbgTag { + #define DBG_TAG(tag, str) tag, + DBG_TAG_LIST + DBG_COUNT_DIM + #undef DBG_TAG +}; + +static uint32_t dbgCount[DBG_COUNT_DIM]; +static uint32_t dbgBgnTime[DBG_TIME_DIM]; +static uint32_t dbgMaxTime[DBG_TIME_DIM]; +static uint32_t dbgMinTime[DBG_TIME_DIM]; +static uint32_t dbgTotalTime[DBG_TIME_DIM]; +//------------------------------------------------------------------------------ +static void dbgBeginTime(DbgTag tag) { + dbgBgnTime[tag] = micros(); +} +//------------------------------------------------------------------------------ +static void dbgClearStats() { + for (int i = 0; i < DBG_COUNT_DIM; i++) { + dbgCount[i] = 0; + if (i < DBG_TIME_DIM) { + dbgMaxTime[i] = 0; + dbgMinTime[i] = 9999999; + dbgTotalTime[i] = 0; + } + } +} +//------------------------------------------------------------------------------ +static void dbgEndTime(DbgTag tag) { + uint32_t m = micros() - dbgBgnTime[tag]; + dbgTotalTime[tag] += m; + if (m > dbgMaxTime[tag]) { + dbgMaxTime[tag] = m; + } + if (m < dbgMinTime[tag]) { + dbgMinTime[tag] = m; + } + dbgCount[tag]++; +} +//------------------------------------------------------------------------------ +static void dbgEventCount(DbgTag tag) { + dbgCount[tag]++; +} +//------------------------------------------------------------------------------ +static void dbgPrintTagText(uint8_t tag) { + #define DBG_TAG(e, m) case e: Serial.print(F(m)); break; + switch (tag) { + DBG_TAG_LIST + } + #undef DBG_TAG +} +//------------------------------------------------------------------------------ +static void dbgPrintStats() { + Serial.println(); + Serial.println(F("=======================")); + Serial.println(F("item,event,min,max,avg")); + Serial.println(F("tag,count,usec,usec,usec")); + for (int i = 0; i < DBG_COUNT_DIM; i++) { + if (dbgCount[i]) { + dbgPrintTagText(i); + Serial.print(','); + Serial.print(dbgCount[i]); + if (i < DBG_TIME_DIM) { + Serial.print(','); + Serial.print(dbgMinTime[i]); + Serial.print(','); + Serial.print(dbgMaxTime[i]); + Serial.print(','); + Serial.print(dbgTotalTime[i]/dbgCount[i]); + } + Serial.println(); + } + } + Serial.println(F("=======================")); + Serial.println(); +} +#undef DBG_TAG_LIST +#define DBG_BEGIN_TIME(tag) dbgBeginTime(tag) +#define DBG_END_TIME(tag) dbgEndTime(tag) +#define DBG_EVENT_COUNT(tag) dbgEventCount(tag) +#else // DBG_PROFILE_STATS +#define DBG_BEGIN_TIME(tag) +#define DBG_END_TIME(tag) +#define DBG_EVENT_COUNT(tag) +static void dbgClearStats() {} +static void dbgPrintStats() {} +#endif // DBG_PROFILE_STATS +//============================================================================== +#if USE_SD_CRC +// CRC functions +//------------------------------------------------------------------------------ +static uint8_t CRC7(const uint8_t* data, uint8_t n) { + uint8_t crc = 0; + for (uint8_t i = 0; i < n; i++) { + uint8_t d = data[i]; + for (uint8_t j = 0; j < 8; j++) { + crc <<= 1; + if ((d & 0x80) ^ (crc & 0x80)) { + crc ^= 0x09; + } + d <<= 1; + } + } + return (crc << 1) | 1; +} +//------------------------------------------------------------------------------ +#if USE_SD_CRC == 1 +// Shift based CRC-CCITT +// uses the x^16,x^12,x^5,x^1 polynomial. +static uint16_t CRC_CCITT(const uint8_t *data, size_t n) { + uint16_t crc = 0; + for (size_t i = 0; i < n; i++) { + crc = (uint8_t)(crc >> 8) | (crc << 8); + crc ^= data[i]; + crc ^= (uint8_t)(crc & 0xff) >> 4; + crc ^= crc << 12; + crc ^= (crc & 0xff) << 5; + } + return crc; +} +#elif USE_SD_CRC > 1 // CRC_CCITT +//------------------------------------------------------------------------------ +// Table based CRC-CCITT +// uses the x^16,x^12,x^5,x^1 polynomial. +#ifdef __AVR__ +static const uint16_t crctab[] PROGMEM = { +#else // __AVR__ +static const uint16_t crctab[] = { +#endif // __AVR__ + 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, + 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, + 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, + 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, + 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, + 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, + 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, + 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, + 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, + 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, + 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, + 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, + 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, + 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, + 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, + 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, + 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, + 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, + 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, + 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, + 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, + 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, + 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, + 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, + 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, + 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, + 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, + 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, + 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, + 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, + 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, + 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0 +}; +static uint16_t CRC_CCITT(const uint8_t* data, size_t n) { + uint16_t crc = 0; + for (size_t i = 0; i < n; i++) { +#ifdef __AVR__ + crc = pgm_read_word(&crctab[(crc >> 8 ^ data[i]) & 0XFF]) ^ (crc << 8); +#else // __AVR__ + crc = crctab[(crc >> 8 ^ data[i]) & 0XFF] ^ (crc << 8); +#endif // __AVR__ + } + return crc; +} +#endif // CRC_CCITT +#endif // USE_SD_CRC +//============================================================================== +// SdSpiCard member functions +//------------------------------------------------------------------------------ +bool SdSpiCard::begin(SdSpiDriver* spi, uint8_t csPin, SPISettings settings) { + m_spiActive = false; + m_errorCode = SD_CARD_ERROR_NONE; + m_type = 0; + m_spiDriver = spi; + uint16_t t0 = curTimeMS(); + uint32_t arg; + + m_spiDriver->begin(csPin); + m_spiDriver->setSpiSettings(SD_SCK_HZ(250000)); + spiStart(); + + // must supply min of 74 clock cycles with CS high. + spiUnselect(); + for (uint8_t i = 0; i < 10; i++) { + spiSend(0XFF); + } + spiSelect(); + + DBG_BEGIN_TIME(DBG_CMD0_TIME); + // command to go idle in SPI mode + for (uint8_t i = 1;; i++) { + DBG_EVENT_COUNT(DBG_CMD0_COUNT); + if (cardCommand(CMD0, 0) == R1_IDLE_STATE) { + break; + } + if (i == SD_CMD0_RETRY) { + error(SD_CARD_ERROR_CMD0); + goto fail; + } + // stop multi-block write + spiSend(STOP_TRAN_TOKEN); + // finish block transfer + for (int i = 0; i < 520; i++) { + spiReceive(); + } + } + DBG_END_TIME(DBG_CMD0_TIME); +#if USE_SD_CRC + if (cardCommand(CMD59, 1) != R1_IDLE_STATE) { + error(SD_CARD_ERROR_CMD59); + goto fail; + } +#endif // USE_SD_CRC + // check SD version + if (cardCommand(CMD8, 0x1AA) == (R1_ILLEGAL_COMMAND | R1_IDLE_STATE)) { + type(SD_CARD_TYPE_SD1); + } else { + for (uint8_t i = 0; i < 4; i++) { + m_status = spiReceive(); + } + if (m_status == 0XAA) { + type(SD_CARD_TYPE_SD2); + } else { + error(SD_CARD_ERROR_CMD8); + goto fail; + } + } + // initialize card and send host supports SDHC if SD2 + arg = type() == SD_CARD_TYPE_SD2 ? 0X40000000 : 0; + DBG_BEGIN_TIME(DBG_ACMD41_TIME); + while (cardAcmd(ACMD41, arg) != R1_READY_STATE) { + DBG_EVENT_COUNT(DBG_ACMD41_COUNT); + // check for timeout + if (isTimedOut(t0, SD_INIT_TIMEOUT)) { + error(SD_CARD_ERROR_ACMD41); + goto fail; + } + } + DBG_END_TIME(DBG_ACMD41_TIME); + // if SD2 read OCR register to check for SDHC card + if (type() == SD_CARD_TYPE_SD2) { + if (cardCommand(CMD58, 0)) { + error(SD_CARD_ERROR_CMD58); + goto fail; + } + if ((spiReceive() & 0XC0) == 0XC0) { + type(SD_CARD_TYPE_SDHC); + } + // Discard rest of ocr - contains allowed voltage range. + for (uint8_t i = 0; i < 3; i++) { + spiReceive(); + } + } + spiStop(); + m_spiDriver->setSpiSettings(settings); + return true; + +fail: + spiStop(); + return false; +} +//------------------------------------------------------------------------------ +// send command and return error code. Return zero for OK +uint8_t SdSpiCard::cardCommand(uint8_t cmd, uint32_t arg) { + // select card + if (!m_spiActive) { + spiStart(); + } + // wait if busy unless CMD0 + if (cmd != CMD0) { + DBG_BEGIN_TIME(DBG_CMD_BUSY); + waitNotBusy(SD_CMD_TIMEOUT); + DBG_END_TIME(DBG_CMD_BUSY); + } + +#if USE_SD_CRC + // form message + uint8_t buf[6]; + buf[0] = (uint8_t)0x40U | cmd; + buf[1] = (uint8_t)(arg >> 24U); + buf[2] = (uint8_t)(arg >> 16U); + buf[3] = (uint8_t)(arg >> 8U); + buf[4] = (uint8_t)arg; + + // add CRC + buf[5] = CRC7(buf, 5); + + // send message + spiSend(buf, 6); +#else // USE_SD_CRC + // send command + spiSend(cmd | 0x40); + + // send argument + uint8_t *pa = reinterpret_cast(&arg); + for (int8_t i = 3; i >= 0; i--) { + spiSend(pa[i]); + } + // send CRC - correct for CMD0 with arg zero or CMD8 with arg 0X1AA + spiSend(cmd == CMD0 ? 0X95 : 0X87); +#endif // USE_SD_CRC + + // discard first fill byte to avoid MISO pull-up problem. + spiReceive(); + + // there are 1-8 fill bytes before response. fill bytes should be 0XFF. + for (uint8_t i = 0; ((m_status = spiReceive()) & 0X80) && i < 10; i++) { + } + return m_status; +} +//------------------------------------------------------------------------------ +uint32_t SdSpiCard::cardSize() { + csd_t csd; + return readCSD(&csd) ? sdCardCapacity(&csd) : 0; +} +//------------------------------------------------------------------------------ +void SdSpiCard::dbgClearStats() {::dbgClearStats();} +//------------------------------------------------------------------------------ +void SdSpiCard::dbgPrintStats() {::dbgPrintStats();} +//------------------------------------------------------------------------------ +bool SdSpiCard::erase(uint32_t firstBlock, uint32_t lastBlock) { + csd_t csd; + if (!readCSD(&csd)) { + goto fail; + } + // check for single block erase + if (!csd.v1.erase_blk_en) { + // erase size mask + uint8_t m = (csd.v1.sector_size_high << 1) | csd.v1.sector_size_low; + if ((firstBlock & m) != 0 || ((lastBlock + 1) & m) != 0) { + // error card can't erase specified area + error(SD_CARD_ERROR_ERASE_SINGLE_BLOCK); + goto fail; + } + } + if (m_type != SD_CARD_TYPE_SDHC) { + firstBlock <<= 9; + lastBlock <<= 9; + } + if (cardCommand(CMD32, firstBlock) + || cardCommand(CMD33, lastBlock) + || cardCommand(CMD38, 0)) { + error(SD_CARD_ERROR_ERASE); + goto fail; + } + DBG_BEGIN_TIME(DBG_ERASE_BUSY); + if (!waitNotBusy(SD_ERASE_TIMEOUT)) { + error(SD_CARD_ERROR_ERASE_TIMEOUT); + goto fail; + } + DBG_END_TIME(DBG_ERASE_BUSY); + spiStop(); + return true; + +fail: + spiStop(); + return false; +} +//------------------------------------------------------------------------------ +bool SdSpiCard::eraseSingleBlockEnable() { + csd_t csd; + return readCSD(&csd) ? csd.v1.erase_blk_en : false; +} +//------------------------------------------------------------------------------ +bool SdSpiCard::isBusy() { + bool rtn = true; + bool spiActive = m_spiActive; + if (!spiActive) { + spiStart(); + } + for (uint8_t i = 0; i < 8; i++) { + if (0XFF == spiReceive()) { + rtn = false; + break; + } + } + if (!spiActive) { + spiStop(); + } + return rtn; +} +//------------------------------------------------------------------------------ +bool SdSpiCard::isTimedOut(uint16_t startMS, uint16_t timeoutMS) { +#if WDT_YIELD_TIME_MICROS + static uint32_t last; + if ((micros() - last) > WDT_YIELD_TIME_MICROS) { + SysCall::yield(); + last = micros(); + } +#endif // WDT_YIELD_TIME_MICROS + return (curTimeMS() - startMS) > timeoutMS; +} +//------------------------------------------------------------------------------ +bool SdSpiCard::readBlock(uint32_t blockNumber, uint8_t* dst) { + SD_TRACE("RB", blockNumber); + // use address if not SDHC card + if (type() != SD_CARD_TYPE_SDHC) { + blockNumber <<= 9; + } + if (cardCommand(CMD17, blockNumber)) { + error(SD_CARD_ERROR_CMD17); + goto fail; + } + if (!readData(dst, 512)) { + goto fail; + } + spiStop(); + return true; + +fail: + spiStop(); + return false; +} +//------------------------------------------------------------------------------ +bool SdSpiCard::readBlocks(uint32_t block, uint8_t* dst, size_t count) { + if (!readStart(block)) { + return false; + } + for (uint16_t b = 0; b < count; b++, dst += 512) { + if (!readData(dst, 512)) { + return false; + } + } + return readStop(); +} +//------------------------------------------------------------------------------ +bool SdSpiCard::readData(uint8_t *dst) { + return readData(dst, 512); +} +//------------------------------------------------------------------------------ +bool SdSpiCard::readData(uint8_t* dst, size_t count) { +#if USE_SD_CRC + uint16_t crc; +#endif // USE_SD_CRC + DBG_BEGIN_TIME(DBG_WAIT_READ); + // wait for start block token + uint16_t t0 = curTimeMS(); + while ((m_status = spiReceive()) == 0XFF) { + if (isTimedOut(t0, SD_READ_TIMEOUT)) { + error(SD_CARD_ERROR_READ_TIMEOUT); + goto fail; + } + } + DBG_END_TIME(DBG_WAIT_READ); + if (m_status != DATA_START_BLOCK) { + error(SD_CARD_ERROR_READ); + goto fail; + } + // transfer data + if ((m_status = spiReceive(dst, count))) { + error(SD_CARD_ERROR_DMA); + goto fail; + } + +#if USE_SD_CRC + // get crc + crc = (spiReceive() << 8) | spiReceive(); + if (crc != CRC_CCITT(dst, count)) { + error(SD_CARD_ERROR_READ_CRC); + goto fail; + } +#else + // discard crc + spiReceive(); + spiReceive(); +#endif // USE_SD_CRC + return true; + +fail: + spiStop(); + return false; +} +//------------------------------------------------------------------------------ +bool SdSpiCard::readOCR(uint32_t* ocr) { + uint8_t *p = reinterpret_cast(ocr); + if (cardCommand(CMD58, 0)) { + error(SD_CARD_ERROR_CMD58); + goto fail; + } + for (uint8_t i = 0; i < 4; i++) { + p[3 - i] = spiReceive(); + } + + spiStop(); + return true; + +fail: + spiStop(); + return false; +} +//------------------------------------------------------------------------------ +/** read CID or CSR register */ +bool SdSpiCard::readRegister(uint8_t cmd, void* buf) { + uint8_t* dst = reinterpret_cast(buf); + if (cardCommand(cmd, 0)) { + error(SD_CARD_ERROR_READ_REG); + goto fail; + } + if (!readData(dst, 16)) { + goto fail; + } + spiStop(); + return true; + +fail: + spiStop(); + return false; +} +//------------------------------------------------------------------------------ +bool SdSpiCard::readStart(uint32_t blockNumber) { + SD_TRACE("RS", blockNumber); + if (type() != SD_CARD_TYPE_SDHC) { + blockNumber <<= 9; + } + if (cardCommand(CMD18, blockNumber)) { + error(SD_CARD_ERROR_CMD18); + goto fail; + } +// spiStop(); + return true; + +fail: + spiStop(); + return false; +} +//----------------------------------------------------------------------------- +bool SdSpiCard::readStatus(uint8_t* status) { + // retrun is R2 so read extra status byte. + if (cardAcmd(ACMD13, 0) || spiReceive()) { + error(SD_CARD_ERROR_ACMD13); + goto fail; + } + if (!readData(status, 64)) { + goto fail; + } + spiStop(); + return true; + +fail: + spiStop(); + return false; +} +//----------------------------------------------------------------------------- +void SdSpiCard::spiStart() { + if (!m_spiActive) { + spiActivate(); + spiSelect(); + m_spiActive = true; + } +} +//----------------------------------------------------------------------------- +void SdSpiCard::spiStop() { + if (m_spiActive) { + spiUnselect(); + spiSend(0XFF); + spiDeactivate(); + m_spiActive = false; + } +} +//------------------------------------------------------------------------------ +bool SdSpiCard::readStop() { + if (cardCommand(CMD12, 0)) { + error(SD_CARD_ERROR_CMD12); + goto fail; + } + spiStop(); + return true; + +fail: + spiStop(); + return false; +} +//------------------------------------------------------------------------------ +// wait for card to go not busy +bool SdSpiCard::waitNotBusy(uint16_t timeoutMS) { + uint16_t t0 = curTimeMS(); +#if WDT_YIELD_TIME_MICROS + // Call isTimedOut first to insure yield is called. + while (!isTimedOut(t0, timeoutMS)) { + if (spiReceive() == 0XFF) { + return true; + } + } + return false; +#else // WDT_YIELD_TIME_MICROS + // Check not busy first since yield is not called in isTimedOut. + while (spiReceive() != 0XFF) { + if (isTimedOut(t0, timeoutMS)) { + return false; + } + } + return true; +#endif // WDT_YIELD_TIME_MICROS +} +//------------------------------------------------------------------------------ +bool SdSpiCard::writeBlock(uint32_t blockNumber, const uint8_t* src) { + SD_TRACE("WB", blockNumber); + // use address if not SDHC card + if (type() != SD_CARD_TYPE_SDHC) { + blockNumber <<= 9; + } + if (cardCommand(CMD24, blockNumber)) { + error(SD_CARD_ERROR_CMD24); + goto fail; + } + if (!writeData(DATA_START_BLOCK, src)) { + goto fail; + } + + +#if CHECK_FLASH_PROGRAMMING + // wait for flash programming to complete + DBG_BEGIN_TIME(DBG_WRITE_FLASH); + if (!waitNotBusy(SD_WRITE_TIMEOUT)) { + error(SD_CARD_ERROR_FLASH_PROGRAMMING); + goto fail; + } + DBG_END_TIME(DBG_WRITE_FLASH); + // response is r2 so get and check two bytes for nonzero + if (cardCommand(CMD13, 0) || spiReceive()) { + error(SD_CARD_ERROR_CMD13); + goto fail; + } +#endif // CHECK_PROGRAMMING + + spiStop(); + return true; + +fail: + spiStop(); + return false; +} +//------------------------------------------------------------------------------ +bool SdSpiCard::writeBlocks(uint32_t block, const uint8_t* src, size_t count) { + if (!writeStart(block)) { + goto fail; + } + for (size_t b = 0; b < count; b++, src += 512) { + if (!writeData(src)) { + goto fail; + } + } + return writeStop(); + + fail: + spiStop(); + return false; +} +//------------------------------------------------------------------------------ +bool SdSpiCard::writeData(const uint8_t* src) { + // wait for previous write to finish + DBG_BEGIN_TIME(DBG_WRITE_BUSY); + if (!waitNotBusy(SD_WRITE_TIMEOUT)) { + error(SD_CARD_ERROR_WRITE_TIMEOUT); + goto fail; + } + DBG_END_TIME(DBG_WRITE_BUSY); + if (!writeData(WRITE_MULTIPLE_TOKEN, src)) { + goto fail; + } + return true; + +fail: + spiStop(); + return false; +} +//------------------------------------------------------------------------------ +// send one block of data for write block or write multiple blocks +bool SdSpiCard::writeData(uint8_t token, const uint8_t* src) { +#if USE_SD_CRC + uint16_t crc = CRC_CCITT(src, 512); +#else // USE_SD_CRC + uint16_t crc = 0XFFFF; +#endif // USE_SD_CRC + spiSend(token); + spiSend(src, 512); + spiSend(crc >> 8); + spiSend(crc & 0XFF); + + m_status = spiReceive(); + if ((m_status & DATA_RES_MASK) != DATA_RES_ACCEPTED) { + error(SD_CARD_ERROR_WRITE); + goto fail; + } + return true; + +fail: + spiStop(); + return false; +} +//------------------------------------------------------------------------------ +bool SdSpiCard::writeStart(uint32_t blockNumber) { + // use address if not SDHC card + if (type() != SD_CARD_TYPE_SDHC) { + blockNumber <<= 9; + } + if (cardCommand(CMD25, blockNumber)) { + error(SD_CARD_ERROR_CMD25); + goto fail; + } + return true; + +fail: + spiStop(); + return false; +} +//------------------------------------------------------------------------------ +bool SdSpiCard::writeStart(uint32_t blockNumber, uint32_t eraseCount) { + SD_TRACE("WS", blockNumber); + // send pre-erase count + if (cardAcmd(ACMD23, eraseCount)) { + error(SD_CARD_ERROR_ACMD23); + goto fail; + } + // use address if not SDHC card + if (type() != SD_CARD_TYPE_SDHC) { + blockNumber <<= 9; + } + if (cardCommand(CMD25, blockNumber)) { + error(SD_CARD_ERROR_CMD25); + goto fail; + } + return true; + +fail: + spiStop(); + return false; +} +//------------------------------------------------------------------------------ +bool SdSpiCard::writeStop() { + DBG_BEGIN_TIME(DBG_WRITE_STOP); + if (!waitNotBusy(SD_WRITE_TIMEOUT)) { + goto fail; + } + DBG_END_TIME(DBG_WRITE_STOP); + spiSend(STOP_TRAN_TOKEN); + spiStop(); + return true; + +fail: + error(SD_CARD_ERROR_STOP_TRAN); + spiStop(); + return false; +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCard.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCard.h new file mode 100644 index 0000000..e89d09f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCard.h @@ -0,0 +1,377 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 SdSpiCard_h +#define SdSpiCard_h +/** + * \file + * \brief SdSpiCard class for V2 SD/SDHC cards + */ +#include +#include "SysCall.h" +#include "SdInfo.h" +#include "../FatLib/BaseBlockDriver.h" +#include "../SpiDriver/SdSpiDriver.h" +//============================================================================== +/** + * \class SdSpiCard + * \brief Raw access to SD and SDHC flash memory cards via SPI protocol. + */ +#if ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS +class SdSpiCard : public BaseBlockDriver { +#else // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS +class SdSpiCard { +#endif // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS + public: + /** Construct an instance of SdSpiCard. */ + SdSpiCard() : m_errorCode(SD_CARD_ERROR_INIT_NOT_CALLED), m_type(0) {} + /** Initialize the SD card. + * \param[in] spi SPI driver for card. + * \param[in] csPin card chip select pin. + * \param[in] spiSettings SPI speed, mode, and bit order. + * \return true for success else false. + */ + bool begin(SdSpiDriver* spi, uint8_t csPin, SPISettings spiSettings); + /** + * Determine the size of an SD flash memory card. + * + * \return The number of 512 byte data blocks in the card + * or zero if an error occurs. + */ + uint32_t cardSize(); + /** Clear debug stats. */ + void dbgClearStats(); + /** Print debug stats. */ + void dbgPrintStats(); + /** Erase a range of blocks. + * + * \param[in] firstBlock The address of the first block in the range. + * \param[in] lastBlock The address of the last block in the range. + * + * \note This function requests the SD card to do a flash erase for a + * range of blocks. The data on the card after an erase operation is + * either 0 or 1, depends on the card vendor. The card must support + * single block erase. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool erase(uint32_t firstBlock, uint32_t lastBlock); + /** Determine if card supports single block erase. + * + * \return true is returned if single block erase is supported. + * false is returned if single block erase is not supported. + */ + bool eraseSingleBlockEnable(); + /** + * Set SD error code. + * \param[in] code value for error code. + */ + void error(uint8_t code) { + m_errorCode = code; + } + /** + * \return code for the last error. See SdInfo.h for a list of error codes. + */ + int errorCode() const { + return m_errorCode; + } + /** \return error data for last error. */ + int errorData() const { + return m_status; + } + /** + * Check for busy. MISO low indicates the card is busy. + * + * \return true if busy else false. + */ + bool isBusy(); + /** + * Read a 512 byte block from an SD card. + * + * \param[in] lba Logical block to be read. + * \param[out] dst Pointer to the location that will receive the data. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool readBlock(uint32_t lba, uint8_t* dst); + /** + * Read multiple 512 byte blocks from an SD card. + * + * \param[in] lba Logical block to be read. + * \param[in] nb Number of blocks to be read. + * \param[out] dst Pointer to the location that will receive the data. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool readBlocks(uint32_t lba, uint8_t* dst, size_t nb); + /** + * Read a card's CID register. The CID contains card identification + * information such as Manufacturer ID, Product name, Product serial + * number and Manufacturing date. + * + * \param[out] cid pointer to area for returned data. + * + * \return true for success or false for failure. + */ + bool readCID(cid_t* cid) { + return readRegister(CMD10, cid); + } + /** + * Read a card's CSD register. The CSD contains Card-Specific Data that + * provides information regarding access to the card's contents. + * + * \param[out] csd pointer to area for returned data. + * + * \return true for success or false for failure. + */ + bool readCSD(csd_t* csd) { + return readRegister(CMD9, csd); + } + /** Read one data block in a multiple block read sequence + * + * \param[out] dst Pointer to the location for the data to be read. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool readData(uint8_t *dst); + /** Read OCR register. + * + * \param[out] ocr Value of OCR register. + * \return true for success else false. + */ + bool readOCR(uint32_t* ocr); + /** Start a read multiple blocks sequence. + * + * \param[in] blockNumber Address of first block in sequence. + * + * \note This function is used with readData() and readStop() for optimized + * multiple block reads. SPI chipSelect must be low for the entire sequence. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool readStart(uint32_t blockNumber); + /** Return the 64 byte card status + * \param[out] status location for 64 status bytes. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool readStatus(uint8_t* status); + /** End a read multiple blocks sequence. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool readStop(); + /** \return success if sync successful. Not for user apps. */ + bool syncBlocks() {return true;} + /** Return the card type: SD V1, SD V2 or SDHC + * \return 0 - SD V1, 1 - SD V2, or 3 - SDHC. + */ + int type() const { + return m_type; + } + /** + * Writes a 512 byte block to an SD card. + * + * \param[in] lba Logical block to be written. + * \param[in] src Pointer to the location of the data to be written. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool writeBlock(uint32_t lba, const uint8_t* src); + /** + * Write multiple 512 byte blocks to an SD card. + * + * \param[in] lba Logical block to be written. + * \param[in] nb Number of blocks to be written. + * \param[in] src Pointer to the location of the data to be written. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool writeBlocks(uint32_t lba, const uint8_t* src, size_t nb); + /** Write one data block in a multiple block write sequence. + * \param[in] src Pointer to the location of the data to be written. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool writeData(const uint8_t* src); + /** Start a write multiple blocks sequence. + * + * \param[in] blockNumber Address of first block in sequence. + * + * \note This function is used with writeData() and writeStop() + * for optimized multiple block writes. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool writeStart(uint32_t blockNumber); + + /** Start a write multiple blocks sequence with pre-erase. + * + * \param[in] blockNumber Address of first block in sequence. + * \param[in] eraseCount The number of blocks to be pre-erased. + * + * \note This function is used with writeData() and writeStop() + * for optimized multiple block writes. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool writeStart(uint32_t blockNumber, uint32_t eraseCount); + /** End a write multiple blocks sequence. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool writeStop(); + /** Set CS low and activate the card. */ + void spiStart(); + /** Set CS high and deactivate the card. */ + void spiStop(); + + private: + // private functions + uint8_t cardAcmd(uint8_t cmd, uint32_t arg) { + cardCommand(CMD55, 0); + return cardCommand(cmd, arg); + } + uint8_t cardCommand(uint8_t cmd, uint32_t arg); + bool isTimedOut(uint16_t startMS, uint16_t timeoutMS); + bool readData(uint8_t* dst, size_t count); + bool readRegister(uint8_t cmd, void* buf); + + void type(uint8_t value) { + m_type = value; + } + + bool waitNotBusy(uint16_t timeoutMS); + bool writeData(uint8_t token, const uint8_t* src); + + //--------------------------------------------------------------------------- + // functions defined in SdSpiDriver.h + void spiActivate() { + m_spiDriver->activate(); + } + void spiDeactivate() { + m_spiDriver->deactivate(); + } + uint8_t spiReceive() { + return m_spiDriver->receive(); + } + uint8_t spiReceive(uint8_t* buf, size_t n) { + return m_spiDriver->receive(buf, n); + } + void spiSend(uint8_t data) { + m_spiDriver->send(data); + } + void spiSend(const uint8_t* buf, size_t n) { + m_spiDriver->send(buf, n); + } + void spiSelect() { + m_spiDriver->select(); + } + void spiUnselect() { + m_spiDriver->unselect(); + } + uint8_t m_errorCode; + SdSpiDriver *m_spiDriver; + bool m_spiActive; + uint8_t m_status; + uint8_t m_type; +}; +//============================================================================== +/** + * \class SdSpiCardEX + * \brief Extended SD I/O block driver. + */ +class SdSpiCardEX : public SdSpiCard { + public: + /** Initialize the SD card + * + * \param[in] spi SPI driver. + * \param[in] csPin Card chip select pin number. + * \param[in] spiSettings SPI speed, mode, and bit order. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool begin(SdSpiDriver* spi, uint8_t csPin, SPISettings spiSettings) { + m_curState = IDLE_STATE; + return SdSpiCard::begin(spi, csPin, spiSettings); + } + /** + * Read a 512 byte block from an SD card. + * + * \param[in] block Logical block to be read. + * \param[out] dst Pointer to the location that will receive the data. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool readBlock(uint32_t block, uint8_t* dst); + /** End multi-block transfer and go to idle state. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool syncBlocks(); + /** + * Writes a 512 byte block to an SD card. + * + * \param[in] block Logical block to be written. + * \param[in] src Pointer to the location of the data to be written. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool writeBlock(uint32_t block, const uint8_t* src); + /** + * Read multiple 512 byte blocks from an SD card. + * + * \param[in] block Logical block to be read. + * \param[in] nb Number of blocks to be read. + * \param[out] dst Pointer to the location that will receive the data. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool readBlocks(uint32_t block, uint8_t* dst, size_t nb); + /** + * Write multiple 512 byte blocks to an SD card. + * + * \param[in] block Logical block to be written. + * \param[in] nb Number of blocks to be written. + * \param[in] src Pointer to the location of the data to be written. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool writeBlocks(uint32_t block, const uint8_t* src, size_t nb); + + private: + static const uint32_t IDLE_STATE = 0; + static const uint32_t READ_STATE = 1; + static const uint32_t WRITE_STATE = 2; + uint32_t m_curBlock; + uint8_t m_curState; +}; +#endif // SdSpiCard_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCardEX.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCardEX.cpp new file mode 100644 index 0000000..e3ab056 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCardEX.cpp @@ -0,0 +1,94 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#include "SdSpiCard.h" +bool SdSpiCardEX::readBlock(uint32_t block, uint8_t* dst) { + if (m_curState != READ_STATE || block != m_curBlock) { + if (!syncBlocks()) { + return false; + } + if (!SdSpiCard::readStart(block)) { + return false; + } + m_curBlock = block; + m_curState = READ_STATE; + } + if (!SdSpiCard::readData(dst)) { + return false; + } + m_curBlock++; + return true; +} +//----------------------------------------------------------------------------- +bool SdSpiCardEX::readBlocks(uint32_t block, uint8_t* dst, size_t nb) { + for (size_t i = 0; i < nb; i++) { + if (!readBlock(block + i, dst + i*512UL)) { + return false; + } + } + return true; +} +//----------------------------------------------------------------------------- +bool SdSpiCardEX::syncBlocks() { + if (m_curState == READ_STATE) { + m_curState = IDLE_STATE; + if (!SdSpiCard::readStop()) { + return false; + } + } else if (m_curState == WRITE_STATE) { + m_curState = IDLE_STATE; + if (!SdSpiCard::writeStop()) { + return false; + } + } + return true; +} +//----------------------------------------------------------------------------- +bool SdSpiCardEX::writeBlock(uint32_t block, const uint8_t* src) { + if (m_curState != WRITE_STATE || m_curBlock != block) { + if (!syncBlocks()) { + return false; + } + if (!SdSpiCard::writeStart(block)) { + return false; + } + m_curBlock = block; + m_curState = WRITE_STATE; + } + if (!SdSpiCard::writeData(src)) { + return false; + } + m_curBlock++; + return true; +} +//----------------------------------------------------------------------------- +bool SdSpiCardEX::writeBlocks(uint32_t block, + const uint8_t* src, size_t nb) { + for (size_t i = 0; i < nb; i++) { + if (!writeBlock(block + i, src + i*512UL)) { + return false; + } + } + return true; +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioCard.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioCard.h new file mode 100644 index 0000000..06ef571 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioCard.h @@ -0,0 +1,301 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 SdioCard_h +#define SdioCard_h +#include "SysCall.h" +#include "BlockDriver.h" +/** + * \class SdioCard + * \brief Raw SDIO access to SD and SDHC flash memory cards. + */ +class SdioCard : public BaseBlockDriver { + public: + /** Initialize the SD card. + * \return true for success else false. + */ + bool begin(); + /** + * Determine the size of an SD flash memory card. + * + * \return The number of 512 byte data blocks in the card + * or zero if an error occurs. + */ + uint32_t cardSize(); + /** Erase a range of blocks. + * + * \param[in] firstBlock The address of the first block in the range. + * \param[in] lastBlock The address of the last block in the range. + * + * \note This function requests the SD card to do a flash erase for a + * range of blocks. The data on the card after an erase operation is + * either 0 or 1, depends on the card vendor. The card must support + * single block erase. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool erase(uint32_t firstBlock, uint32_t lastBlock); + /** + * \return code for the last error. See SdInfo.h for a list of error codes. + */ + uint8_t errorCode(); + /** \return error data for last error. */ + uint32_t errorData(); + /** \return error line for last error. Tmp function for debug. */ + uint32_t errorLine(); + /** + * Check for busy with CMD13. + * + * \return true if busy else false. + */ + bool isBusy(); + /** \return the SD clock frequency in kHz. */ + uint32_t kHzSdClk(); + /** + * Read a 512 byte block from an SD card. + * + * \param[in] lba Logical block to be read. + * \param[out] dst Pointer to the location that will receive the data. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool readBlock(uint32_t lba, uint8_t* dst); + /** + * Read multiple 512 byte blocks from an SD card. + * + * \param[in] lba Logical block to be read. + * \param[in] nb Number of blocks to be read. + * \param[out] dst Pointer to the location that will receive the data. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool readBlocks(uint32_t lba, uint8_t* dst, size_t nb); + /** + * Read a card's CID register. The CID contains card identification + * information such as Manufacturer ID, Product name, Product serial + * number and Manufacturing date. + * + * \param[out] cid pointer to area for returned data. + * + * \return true for success or false for failure. + */ + bool readCID(void* cid); + /** + * Read a card's CSD register. The CSD contains Card-Specific Data that + * provides information regarding access to the card's contents. + * + * \param[out] csd pointer to area for returned data. + * + * \return true for success or false for failure. + */ + bool readCSD(void* csd); + /** Read one data block in a multiple block read sequence + * + * \param[out] dst Pointer to the location for the data to be read. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool readData(uint8_t *dst); + /** Read OCR register. + * + * \param[out] ocr Value of OCR register. + * \return true for success else false. + */ + bool readOCR(uint32_t* ocr); + /** Start a read multiple blocks sequence. + * + * \param[in] lba Address of first block in sequence. + * + * \note This function is used with readData() and readStop() for optimized + * multiple block reads. SPI chipSelect must be low for the entire sequence. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool readStart(uint32_t lba); + /** Start a read multiple blocks sequence. + * + * \param[in] lba Address of first block in sequence. + * \param[in] count Maximum block count. + * \note This function is used with readData() and readStop() for optimized + * multiple block reads. SPI chipSelect must be low for the entire sequence. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool readStart(uint32_t lba, uint32_t count); + /** End a read multiple blocks sequence. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool readStop(); + /** \return success if sync successful. Not for user apps. */ + bool syncBlocks(); + /** Return the card type: SD V1, SD V2 or SDHC + * \return 0 - SD V1, 1 - SD V2, or 3 - SDHC. + */ + uint8_t type(); + /** + * Writes a 512 byte block to an SD card. + * + * \param[in] lba Logical block to be written. + * \param[in] src Pointer to the location of the data to be written. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool writeBlock(uint32_t lba, const uint8_t* src); + /** + * Write multiple 512 byte blocks to an SD card. + * + * \param[in] lba Logical block to be written. + * \param[in] nb Number of blocks to be written. + * \param[in] src Pointer to the location of the data to be written. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool writeBlocks(uint32_t lba, const uint8_t* src, size_t nb); + /** Write one data block in a multiple block write sequence. + * \param[in] src Pointer to the location of the data to be written. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool writeData(const uint8_t* src); + /** Start a write multiple blocks sequence. + * + * \param[in] lba Address of first block in sequence. + * + * \note This function is used with writeData() and writeStop() + * for optimized multiple block writes. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool writeStart(uint32_t lba); + /** Start a write multiple blocks sequence. + * + * \param[in] lba Address of first block in sequence. + * \param[in] count Maximum block count. + * \note This function is used with writeData() and writeStop() + * for optimized multiple block writes. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool writeStart(uint32_t lba, uint32_t count); + + /** End a write multiple blocks sequence. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool writeStop(); +}; +//============================================================================== +/** + * \class SdioCardEX + * \brief Extended SD I/O block driver. + */ +class SdioCardEX : public SdioCard { + public: + /** Initialize the SD card + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool begin() { + m_curState = IDLE_STATE; + return SdioCard::begin(); + } + /** Erase a range of blocks. + * + * \param[in] firstBlock The address of the first block in the range. + * \param[in] lastBlock The address of the last block in the range. + * + * \note This function requests the SD card to do a flash erase for a + * range of blocks. The data on the card after an erase operation is + * either 0 or 1, depends on the card vendor. The card must support + * single block erase. + * + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool erase(uint32_t firstBlock, uint32_t lastBlock) { + return syncBlocks() && SdioCard::erase(firstBlock, lastBlock); + } + /** + * Read a 512 byte block from an SD card. + * + * \param[in] block Logical block to be read. + * \param[out] dst Pointer to the location that will receive the data. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool readBlock(uint32_t block, uint8_t* dst); + /** End multi-block transfer and go to idle state. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool syncBlocks(); + /** + * Writes a 512 byte block to an SD card. + * + * \param[in] block Logical block to be written. + * \param[in] src Pointer to the location of the data to be written. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool writeBlock(uint32_t block, const uint8_t* src); + /** + * Read multiple 512 byte blocks from an SD card. + * + * \param[in] block Logical block to be read. + * \param[in] nb Number of blocks to be read. + * \param[out] dst Pointer to the location that will receive the data. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool readBlocks(uint32_t block, uint8_t* dst, size_t nb); + /** + * Write multiple 512 byte blocks to an SD card. + * + * \param[in] block Logical block to be written. + * \param[in] nb Number of blocks to be written. + * \param[in] src Pointer to the location of the data to be written. + * \return The value true is returned for success and + * the value false is returned for failure. + */ + bool writeBlocks(uint32_t block, const uint8_t* src, size_t nb); + + private: + static const uint32_t IDLE_STATE = 0; + static const uint32_t READ_STATE = 1; + static const uint32_t WRITE_STATE = 2; + uint32_t m_curLba; + uint32_t m_limitLba; + uint8_t m_curState; +}; +#endif // SdioCard_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioCardEX.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioCardEX.cpp new file mode 100644 index 0000000..8029c97 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioCardEX.cpp @@ -0,0 +1,108 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#include "SdioCard.h" + +// limit of K66 due to errata KINETIS_K_0N65N. +const uint32_t MAX_SDHC_COUNT = 0XFFFF; + +// Max RU is 1024 blocks. +const uint32_t RU_MASK = 0X03FF; + +bool SdioCardEX::readBlock(uint32_t lba, uint8_t* dst) { + if (m_curState != READ_STATE || lba != m_curLba) { + if (!syncBlocks()) { + return false; + } + m_limitLba = (lba + MAX_SDHC_COUNT) & ~RU_MASK; + if (!SdioCard::readStart(lba, m_limitLba - lba)) { + return false; + } + m_curLba = lba; + m_curState = READ_STATE; + } + if (!SdioCard::readData(dst)) { + return false; + } + m_curLba++; + if (m_curLba >= m_limitLba) { + m_curState = IDLE_STATE; + } + return true; +} +//----------------------------------------------------------------------------- +bool SdioCardEX::readBlocks(uint32_t lba, uint8_t* dst, size_t nb) { + for (size_t i = 0; i < nb; i++) { + if (!readBlock(lba + i, dst + i*512UL)) { + return false; + } + } + return true; +} +//----------------------------------------------------------------------------- +bool SdioCardEX::syncBlocks() { + if (m_curState == READ_STATE) { + m_curState = IDLE_STATE; + if (!SdioCard::readStop()) { + return false; + } + } else if (m_curState == WRITE_STATE) { + m_curState = IDLE_STATE; + if (!SdioCard::writeStop()) { + return false; + } + } + return true; +} +//----------------------------------------------------------------------------- +bool SdioCardEX::writeBlock(uint32_t lba, const uint8_t* src) { + if (m_curState != WRITE_STATE || m_curLba != lba) { + if (!syncBlocks()) { + return false; + } + m_limitLba = (lba + MAX_SDHC_COUNT) & ~RU_MASK; + if (!SdioCard::writeStart(lba , m_limitLba - lba)) { + return false; + } + m_curLba = lba; + m_curState = WRITE_STATE; + } + if (!SdioCard::writeData(src)) { + return false; + } + m_curLba++; + if (m_curLba >= m_limitLba) { + m_curState = IDLE_STATE; + } + return true; +} +//----------------------------------------------------------------------------- +bool SdioCardEX::writeBlocks(uint32_t lba, const uint8_t* src, size_t nb) { + for (size_t i = 0; i < nb; i++) { + if (!writeBlock(lba + i, src + i*512UL)) { + return false; + } + } + return true; +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioTeensy.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioTeensy.cpp new file mode 100644 index 0000000..53c2140 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioTeensy.cpp @@ -0,0 +1,800 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#if defined(__MK64FX512__) || defined(__MK66FX1M0__) +#include "SdioCard.h" +//============================================================================== +#define SDHC_PROCTL_DTW_4BIT 0x01 +const uint32_t FIFO_WML = 16; +const uint32_t CMD8_RETRIES = 10; +const uint32_t BUSY_TIMEOUT_MICROS = 500000; +//============================================================================== +const uint32_t SDHC_IRQSTATEN_MASK = + SDHC_IRQSTATEN_DMAESEN | SDHC_IRQSTATEN_AC12ESEN | + SDHC_IRQSTATEN_DEBESEN | SDHC_IRQSTATEN_DCESEN | + SDHC_IRQSTATEN_DTOESEN | SDHC_IRQSTATEN_CIESEN | + SDHC_IRQSTATEN_CEBESEN | SDHC_IRQSTATEN_CCESEN | + SDHC_IRQSTATEN_CTOESEN | SDHC_IRQSTATEN_DINTSEN | + SDHC_IRQSTATEN_TCSEN | SDHC_IRQSTATEN_CCSEN; + +const uint32_t SDHC_IRQSTAT_CMD_ERROR = + SDHC_IRQSTAT_CIE | SDHC_IRQSTAT_CEBE | + SDHC_IRQSTAT_CCE | SDHC_IRQSTAT_CTOE; + +const uint32_t SDHC_IRQSTAT_DATA_ERROR = + SDHC_IRQSTAT_AC12E | SDHC_IRQSTAT_DEBE | + SDHC_IRQSTAT_DCE | SDHC_IRQSTAT_DTOE; + +const uint32_t SDHC_IRQSTAT_ERROR = + SDHC_IRQSTAT_DMAE | SDHC_IRQSTAT_CMD_ERROR | + SDHC_IRQSTAT_DATA_ERROR; + +const uint32_t SDHC_IRQSIGEN_MASK = + SDHC_IRQSIGEN_DMAEIEN | SDHC_IRQSIGEN_AC12EIEN | + SDHC_IRQSIGEN_DEBEIEN | SDHC_IRQSIGEN_DCEIEN | + SDHC_IRQSIGEN_DTOEIEN | SDHC_IRQSIGEN_CIEIEN | + SDHC_IRQSIGEN_CEBEIEN | SDHC_IRQSIGEN_CCEIEN | + SDHC_IRQSIGEN_CTOEIEN | SDHC_IRQSIGEN_TCIEN; +//============================================================================= +const uint32_t CMD_RESP_NONE = SDHC_XFERTYP_RSPTYP(0); + +const uint32_t CMD_RESP_R1 = SDHC_XFERTYP_CICEN | SDHC_XFERTYP_CCCEN | + SDHC_XFERTYP_RSPTYP(2); + +const uint32_t CMD_RESP_R1b = SDHC_XFERTYP_CICEN | SDHC_XFERTYP_CCCEN | + SDHC_XFERTYP_RSPTYP(3); + +const uint32_t CMD_RESP_R2 = SDHC_XFERTYP_CCCEN | SDHC_XFERTYP_RSPTYP(1); + +const uint32_t CMD_RESP_R3 = SDHC_XFERTYP_RSPTYP(2); + +const uint32_t CMD_RESP_R6 = CMD_RESP_R1; + +const uint32_t CMD_RESP_R7 = CMD_RESP_R1; + +const uint32_t DATA_READ = SDHC_XFERTYP_DTDSEL | SDHC_XFERTYP_DPSEL; + +const uint32_t DATA_READ_DMA = DATA_READ | SDHC_XFERTYP_DMAEN; + +const uint32_t DATA_READ_MULTI_DMA = DATA_READ_DMA | SDHC_XFERTYP_MSBSEL | + SDHC_XFERTYP_AC12EN | SDHC_XFERTYP_BCEN; + +const uint32_t DATA_READ_MULTI_PGM = DATA_READ | SDHC_XFERTYP_MSBSEL | + SDHC_XFERTYP_BCEN | SDHC_XFERTYP_AC12EN; + +const uint32_t DATA_WRITE_DMA = SDHC_XFERTYP_DPSEL | SDHC_XFERTYP_DMAEN; + +const uint32_t DATA_WRITE_MULTI_DMA = DATA_WRITE_DMA | SDHC_XFERTYP_MSBSEL | + SDHC_XFERTYP_AC12EN | SDHC_XFERTYP_BCEN; + +const uint32_t DATA_WRITE_MULTI_PGM = SDHC_XFERTYP_DPSEL | + SDHC_XFERTYP_MSBSEL | + SDHC_XFERTYP_BCEN | SDHC_XFERTYP_AC12EN; + +const uint32_t ACMD6_XFERTYP = SDHC_XFERTYP_CMDINX(ACMD6) | CMD_RESP_R1; + +const uint32_t ACMD41_XFERTYP = SDHC_XFERTYP_CMDINX(ACMD41) | CMD_RESP_R3; + +const uint32_t CMD0_XFERTYP = SDHC_XFERTYP_CMDINX(CMD0) | CMD_RESP_NONE; + +const uint32_t CMD2_XFERTYP = SDHC_XFERTYP_CMDINX(CMD2) | CMD_RESP_R2; + +const uint32_t CMD3_XFERTYP = SDHC_XFERTYP_CMDINX(CMD3) | CMD_RESP_R6; + +const uint32_t CMD6_XFERTYP = SDHC_XFERTYP_CMDINX(CMD6) | CMD_RESP_R1 | + DATA_READ_DMA; + +const uint32_t CMD7_XFERTYP = SDHC_XFERTYP_CMDINX(CMD7) | CMD_RESP_R1b; + +const uint32_t CMD8_XFERTYP = SDHC_XFERTYP_CMDINX(CMD8) | CMD_RESP_R7; + +const uint32_t CMD9_XFERTYP = SDHC_XFERTYP_CMDINX(CMD9) | CMD_RESP_R2; + +const uint32_t CMD10_XFERTYP = SDHC_XFERTYP_CMDINX(CMD10) | CMD_RESP_R2; + +const uint32_t CMD12_XFERTYP = SDHC_XFERTYP_CMDINX(CMD12) | CMD_RESP_R1b | + SDHC_XFERTYP_CMDTYP(3); + +const uint32_t CMD13_XFERTYP = SDHC_XFERTYP_CMDINX(CMD13) | CMD_RESP_R1; + +const uint32_t CMD17_DMA_XFERTYP = SDHC_XFERTYP_CMDINX(CMD17) | CMD_RESP_R1 | + DATA_READ_DMA; + +const uint32_t CMD18_DMA_XFERTYP = SDHC_XFERTYP_CMDINX(CMD18) | CMD_RESP_R1 | + DATA_READ_MULTI_DMA; + +const uint32_t CMD18_PGM_XFERTYP = SDHC_XFERTYP_CMDINX(CMD18) | CMD_RESP_R1 | + DATA_READ_MULTI_PGM; + +const uint32_t CMD24_DMA_XFERTYP = SDHC_XFERTYP_CMDINX(CMD24) | CMD_RESP_R1 | + DATA_WRITE_DMA; + +const uint32_t CMD25_DMA_XFERTYP = SDHC_XFERTYP_CMDINX(CMD25) | CMD_RESP_R1 | + DATA_WRITE_MULTI_DMA; + +const uint32_t CMD25_PGM_XFERTYP = SDHC_XFERTYP_CMDINX(CMD25) | CMD_RESP_R1 | + DATA_WRITE_MULTI_PGM; + +const uint32_t CMD32_XFERTYP = SDHC_XFERTYP_CMDINX(CMD32) | CMD_RESP_R1; + +const uint32_t CMD33_XFERTYP = SDHC_XFERTYP_CMDINX(CMD33) | CMD_RESP_R1; + +const uint32_t CMD38_XFERTYP = SDHC_XFERTYP_CMDINX(CMD38) | CMD_RESP_R1b; + +const uint32_t CMD55_XFERTYP = SDHC_XFERTYP_CMDINX(CMD55) | CMD_RESP_R1; + +//============================================================================= +static bool cardCommand(uint32_t xfertyp, uint32_t arg); +static void enableGPIO(bool enable); +static void enableDmaIrs(); +static void initSDHC(); +static bool isBusyCMD13(); +static bool isBusyCommandComplete(); +static bool isBusyCommandInhibit(); +static bool readReg16(uint32_t xfertyp, void* data); +static void setSdclk(uint32_t kHzMax); +static bool yieldTimeout(bool (*fcn)()); +static bool waitDmaStatus(); +static bool waitTimeout(bool (*fcn)()); +//----------------------------------------------------------------------------- +static bool (*m_busyFcn)() = 0; +static bool m_initDone = false; +static bool m_version2; +static bool m_highCapacity; +static uint8_t m_errorCode = SD_CARD_ERROR_INIT_NOT_CALLED; +static uint32_t m_errorLine = 0; +static uint32_t m_rca; +static volatile bool m_dmaBusy = false; +static volatile uint32_t m_irqstat; +static uint32_t m_sdClkKhz = 0; +static uint32_t m_ocr; +static cid_t m_cid; +static csd_t m_csd; +//============================================================================= +#define USE_DEBUG_MODE 0 +#if USE_DEBUG_MODE +#define DBG_IRQSTAT() if (SDHC_IRQSTAT) {Serial.print(__LINE__);\ + Serial.print(" IRQSTAT "); Serial.println(SDHC_IRQSTAT, HEX);} + +static void printRegs(uint32_t line) { + Serial.print(line); + Serial.print(" PRSSTAT "); + Serial.print(SDHC_PRSSTAT, HEX); + Serial.print(" PROCTL "); + Serial.print(SDHC_PROCTL, HEX); + Serial.print(" IRQSTAT "); + Serial.print(SDHC_IRQSTAT, HEX); + Serial.print(" m_irqstat "); + Serial.println(m_irqstat, HEX); +} +#else // USE_DEBUG_MODE +#define DBG_IRQSTAT() +#endif // USE_DEBUG_MODE +//============================================================================= +// Error function and macro. +#define sdError(code) setSdErrorCode(code, __LINE__) +inline bool setSdErrorCode(uint8_t code, uint32_t line) { + m_errorCode = code; + m_errorLine = line; + return false; // setSdErrorCode +} +//============================================================================= +// ISR +void sdhc_isr() { + SDHC_IRQSIGEN = 0; + m_irqstat = SDHC_IRQSTAT; + SDHC_IRQSTAT = m_irqstat; + m_dmaBusy = false; +} +//============================================================================= +// Static functions. +static bool cardAcmd(uint32_t rca, uint32_t xfertyp, uint32_t arg) { + return cardCommand(CMD55_XFERTYP, rca) && cardCommand (xfertyp, arg); +} +//----------------------------------------------------------------------------- +static bool cardCommand(uint32_t xfertyp, uint32_t arg) { + DBG_IRQSTAT(); + if (waitTimeout(isBusyCommandInhibit)) { + return false; // Caller will set errorCode. + } + SDHC_CMDARG = arg; + SDHC_XFERTYP = xfertyp; + if (waitTimeout(isBusyCommandComplete)) { + return false; // Caller will set errorCode. + } + m_irqstat = SDHC_IRQSTAT; + SDHC_IRQSTAT = m_irqstat; + + return (m_irqstat & SDHC_IRQSTAT_CC) && + !(m_irqstat & SDHC_IRQSTAT_CMD_ERROR); +} +//----------------------------------------------------------------------------- +static bool cardCMD6(uint32_t arg, uint8_t* status) { + // CMD6 returns 64 bytes. + if (waitTimeout(isBusyCMD13)) { + return sdError(SD_CARD_ERROR_CMD13); + } + enableDmaIrs(); + SDHC_DSADDR = (uint32_t)status; + SDHC_CMDARG = arg; + SDHC_BLKATTR = SDHC_BLKATTR_BLKCNT(1) | SDHC_BLKATTR_BLKSIZE(64); + SDHC_IRQSIGEN = SDHC_IRQSIGEN_MASK; + SDHC_XFERTYP = CMD6_XFERTYP; + + if (!waitDmaStatus()) { + return sdError(SD_CARD_ERROR_CMD6); + } + return true; +} +//----------------------------------------------------------------------------- +static void enableGPIO(bool enable) { + const uint32_t PORT_CLK = PORT_PCR_MUX(4) | PORT_PCR_DSE; + const uint32_t PORT_CMD_DATA = PORT_CLK | PORT_PCR_PS | PORT_PCR_PE; + + PORTE_PCR0 = enable ? PORT_CMD_DATA : 0; // SDHC_D1 + PORTE_PCR1 = enable ? PORT_CMD_DATA : 0; // SDHC_D0 + PORTE_PCR2 = enable ? PORT_CLK : 0; // SDHC_CLK + PORTE_PCR3 = enable ? PORT_CMD_DATA : 0; // SDHC_CMD + PORTE_PCR4 = enable ? PORT_CMD_DATA : 0; // SDHC_D3 + PORTE_PCR5 = enable ? PORT_CMD_DATA : 0; // SDHC_D2 +} +//----------------------------------------------------------------------------- +static void enableDmaIrs() { + m_dmaBusy = true; + m_irqstat = 0; +} +//----------------------------------------------------------------------------- +static void initSDHC() { +#ifdef HAS_KINETIS_MPU + // Allow SDHC Bus Master access. + MPU_RGDAAC0 |= 0x0C000000; +#endif + // Enable SDHC clock. + SIM_SCGC3 |= SIM_SCGC3_SDHC; + + // Disable GPIO clock. + enableGPIO(false); + + // Reset SDHC. Use default Water Mark Level of 16. + SDHC_SYSCTL = SDHC_SYSCTL_RSTA; + while (SDHC_SYSCTL & SDHC_SYSCTL_RSTA) { + } + // Set initial SCK rate. + setSdclk(400); + + enableGPIO(true); + + // Enable desired IRQSTAT bits. + SDHC_IRQSTATEN = SDHC_IRQSTATEN_MASK; + + NVIC_SET_PRIORITY(IRQ_SDHC, 6*16); + NVIC_ENABLE_IRQ(IRQ_SDHC); + + // Send 80 clocks to card. + SDHC_SYSCTL |= SDHC_SYSCTL_INITA; + while (SDHC_SYSCTL & SDHC_SYSCTL_INITA) { + } +} +//----------------------------------------------------------------------------- +static bool isBusyCMD13() { + if (!cardCommand(CMD13_XFERTYP, m_rca)) { + // Caller will timeout. + return true; + } + return !(SDHC_CMDRSP0 & CARD_STATUS_READY_FOR_DATA); +} +//----------------------------------------------------------------------------- +static bool isBusyCommandComplete() { + return !(SDHC_IRQSTAT &(SDHC_IRQSTAT_CC | SDHC_IRQSTAT_CMD_ERROR)); +} +//----------------------------------------------------------------------------- +static bool isBusyCommandInhibit() { + return SDHC_PRSSTAT & SDHC_PRSSTAT_CIHB; +} +//----------------------------------------------------------------------------- +static bool isBusyDMA() { + return m_dmaBusy; +} +//----------------------------------------------------------------------------- +static bool isBusyFifoRead() { + return !(SDHC_PRSSTAT & SDHC_PRSSTAT_BREN); +} +//----------------------------------------------------------------------------- +static bool isBusyFifoWrite() { + return !(SDHC_PRSSTAT & SDHC_PRSSTAT_BWEN); +} +//----------------------------------------------------------------------------- +static bool isBusyTransferComplete() { + return !(SDHC_IRQSTAT & (SDHC_IRQSTAT_TC | SDHC_IRQSTAT_ERROR)); +} +//----------------------------------------------------------------------------- +static bool rdWrBlocks(uint32_t xfertyp, + uint32_t lba, uint8_t* buf, size_t n) { + if ((3 & (uint32_t)buf) || n == 0) { + return sdError(SD_CARD_ERROR_DMA); + } + if (yieldTimeout(isBusyCMD13)) { + return sdError(SD_CARD_ERROR_CMD13); + } + enableDmaIrs(); + SDHC_DSADDR = (uint32_t)buf; + SDHC_CMDARG = m_highCapacity ? lba : 512*lba; + SDHC_BLKATTR = SDHC_BLKATTR_BLKCNT(n) | SDHC_BLKATTR_BLKSIZE(512); + SDHC_IRQSIGEN = SDHC_IRQSIGEN_MASK; + SDHC_XFERTYP = xfertyp; + + return waitDmaStatus(); +} +//----------------------------------------------------------------------------- +// Read 16 byte CID or CSD register. +static bool readReg16(uint32_t xfertyp, void* data) { + uint8_t* d = reinterpret_cast(data); + if (!cardCommand(xfertyp, m_rca)) { + return false; // Caller will set errorCode. + } + uint32_t sr[] = {SDHC_CMDRSP0, SDHC_CMDRSP1, SDHC_CMDRSP2, SDHC_CMDRSP3}; + for (int i = 0; i < 15; i++) { + d[14 - i] = sr[i/4] >> 8*(i%4); + } + d[15] = 0; + return true; +} +//----------------------------------------------------------------------------- +static void setSdclk(uint32_t kHzMax) { + const uint32_t DVS_LIMIT = 0X10; + const uint32_t SDCLKFS_LIMIT = 0X100; + uint32_t dvs = 1; + uint32_t sdclkfs = 1; + uint32_t maxSdclk = 1000*kHzMax; + + while ((F_CPU/(sdclkfs*DVS_LIMIT) > maxSdclk) && (sdclkfs < SDCLKFS_LIMIT)) { + sdclkfs <<= 1; + } + while ((F_CPU/(sdclkfs*dvs) > maxSdclk) && (dvs < DVS_LIMIT)) { + dvs++; + } + m_sdClkKhz = F_CPU/(1000*sdclkfs*dvs); + sdclkfs >>= 1; + dvs--; + + // Disable SDHC clock. + SDHC_SYSCTL &= ~SDHC_SYSCTL_SDCLKEN; + + // Change dividers. + uint32_t sysctl = SDHC_SYSCTL & ~(SDHC_SYSCTL_DTOCV_MASK + | SDHC_SYSCTL_DVS_MASK | SDHC_SYSCTL_SDCLKFS_MASK); + + SDHC_SYSCTL = sysctl | SDHC_SYSCTL_DTOCV(0x0E) | SDHC_SYSCTL_DVS(dvs) + | SDHC_SYSCTL_SDCLKFS(sdclkfs); + + // Wait until the SDHC clock is stable. + while (!(SDHC_PRSSTAT & SDHC_PRSSTAT_SDSTB)) { + } + // Enable the SDHC clock. + SDHC_SYSCTL |= SDHC_SYSCTL_SDCLKEN; +} +//----------------------------------------------------------------------------- +static bool transferStop() { + DBG_IRQSTAT(); + + if (!cardCommand(CMD12_XFERTYP, 0)) { + return sdError(SD_CARD_ERROR_CMD12); + } + if (yieldTimeout(isBusyCMD13)) { + return sdError(SD_CARD_ERROR_CMD13); + } + // Save registers before reset DAT lines. + uint32_t irqsststen = SDHC_IRQSTATEN; + uint32_t proctl = SDHC_PROCTL & ~SDHC_PROCTL_SABGREQ; + + // Do reset to clear CDIHB. Should be a better way! + SDHC_SYSCTL |= SDHC_SYSCTL_RSTD; + + // Restore registers. + SDHC_IRQSTATEN = irqsststen; + SDHC_PROCTL = proctl; + + return true; +} +//----------------------------------------------------------------------------- +// Return true if timeout occurs. +static bool yieldTimeout(bool (*fcn)()) { + m_busyFcn = fcn; + uint32_t m = micros(); + while (fcn()) { + if ((micros() - m) > BUSY_TIMEOUT_MICROS) { + m_busyFcn = 0; + return true; + } + yield(); + } + m_busyFcn = 0; + return false; // Caller will set errorCode. +} +//----------------------------------------------------------------------------- +static bool waitDmaStatus() { + if (yieldTimeout(isBusyDMA)) { + return false; // Caller will set errorCode. + } + return (m_irqstat & SDHC_IRQSTAT_TC) && !(m_irqstat & SDHC_IRQSTAT_ERROR); +} +//----------------------------------------------------------------------------- +// Return true if timeout occurs. +static bool waitTimeout(bool (*fcn)()) { + uint32_t m = micros(); + while (fcn()) { + if ((micros() - m) > BUSY_TIMEOUT_MICROS) { + return true; + } + } + return false; // Caller will set errorCode. +} +//============================================================================= +bool SdioCard::begin() { + uint32_t kHzSdClk; + uint32_t arg; + m_initDone = false; + m_errorCode = SD_CARD_ERROR_NONE; + m_highCapacity = false; + m_version2 = false; + + // initialize controller. + initSDHC(); + + if (!cardCommand(CMD0_XFERTYP, 0)) { + return sdError(SD_CARD_ERROR_CMD0); + } + // Try several times for case of reset delay. + for (uint32_t i = 0; i < CMD8_RETRIES; i++) { + if (cardCommand(CMD8_XFERTYP, 0X1AA)) { + if (SDHC_CMDRSP0 != 0X1AA) { + return sdError(SD_CARD_ERROR_CMD8); + } + m_version2 = true; + break; + } + } + arg = m_version2 ? 0X40300000 : 0x00300000; + uint32_t m = micros(); + do { + if (!cardAcmd(0, ACMD41_XFERTYP, arg) || + ((micros() - m) > BUSY_TIMEOUT_MICROS)) { + return sdError(SD_CARD_ERROR_ACMD41); + } + } while ((SDHC_CMDRSP0 & 0x80000000) == 0); + + m_ocr = SDHC_CMDRSP0; + if (SDHC_CMDRSP0 & 0x40000000) { + // Is high capacity. + m_highCapacity = true; + } + if (!cardCommand(CMD2_XFERTYP, 0)) { + return sdError(SD_CARD_ERROR_CMD2); + } + if (!cardCommand(CMD3_XFERTYP, 0)) { + return sdError(SD_CARD_ERROR_CMD3); + } + m_rca = SDHC_CMDRSP0 & 0xFFFF0000; + + if (!readReg16(CMD9_XFERTYP, &m_csd)) { + return sdError(SD_CARD_ERROR_CMD9); + } + if (!readReg16(CMD10_XFERTYP, &m_cid)) { + return sdError(SD_CARD_ERROR_CMD10); + } + if (!cardCommand(CMD7_XFERTYP, m_rca)) { + return sdError(SD_CARD_ERROR_CMD7); + } + // Set card to bus width four. + if (!cardAcmd(m_rca, ACMD6_XFERTYP, 2)) { + return sdError(SD_CARD_ERROR_ACMD6); + } + // Set SDHC to bus width four. + SDHC_PROCTL &= ~SDHC_PROCTL_DTW_MASK; + SDHC_PROCTL |= SDHC_PROCTL_DTW(SDHC_PROCTL_DTW_4BIT); + + SDHC_WML = SDHC_WML_RDWML(FIFO_WML) | SDHC_WML_WRWML(FIFO_WML); + + // Determine if High Speed mode is supported and set frequency. + uint8_t status[64]; + if (cardCMD6(0X00FFFFFF, status) && (2 & status[13]) && + cardCMD6(0X80FFFFF1, status) && (status[16] & 0XF) == 1) { + kHzSdClk = 50000; + } else { + kHzSdClk = 25000; + } + // disable GPIO + enableGPIO(false); + + // Set the SDHC SCK frequency. + setSdclk(kHzSdClk); + + // enable GPIO + enableGPIO(true); + m_initDone = true; + return true; +} +//----------------------------------------------------------------------------- +uint32_t SdioCard::cardSize() { + return sdCardCapacity(&m_csd); +} +//----------------------------------------------------------------------------- +bool SdioCard::erase(uint32_t firstBlock, uint32_t lastBlock) { + // check for single block erase + if (!m_csd.v1.erase_blk_en) { + // erase size mask + uint8_t m = (m_csd.v1.sector_size_high << 1) | m_csd.v1.sector_size_low; + if ((firstBlock & m) != 0 || ((lastBlock + 1) & m) != 0) { + // error card can't erase specified area + return sdError(SD_CARD_ERROR_ERASE_SINGLE_BLOCK); + } + } + if (!m_highCapacity) { + firstBlock <<= 9; + lastBlock <<= 9; + } + if (!cardCommand(CMD32_XFERTYP, firstBlock)) { + return sdError(SD_CARD_ERROR_CMD32); + } + if (!cardCommand(CMD33_XFERTYP, lastBlock)) { + return sdError(SD_CARD_ERROR_CMD33); + } + if (!cardCommand(CMD38_XFERTYP, 0)) { + return sdError(SD_CARD_ERROR_CMD38); + } + if (waitTimeout(isBusyCMD13)) { + return sdError(SD_CARD_ERROR_ERASE_TIMEOUT); + } + return true; +} +//----------------------------------------------------------------------------- +uint8_t SdioCard::errorCode() { + return m_errorCode; +} +//----------------------------------------------------------------------------- +uint32_t SdioCard::errorData() { + return m_irqstat; +} +//----------------------------------------------------------------------------- +uint32_t SdioCard::errorLine() { + return m_errorLine; +} +//----------------------------------------------------------------------------- +bool SdioCard::isBusy() { + return m_busyFcn ? m_busyFcn() : m_initDone && isBusyCMD13(); +} +//----------------------------------------------------------------------------- +uint32_t SdioCard::kHzSdClk() { + return m_sdClkKhz; +} +//----------------------------------------------------------------------------- +bool SdioCard::readBlock(uint32_t lba, uint8_t* buf) { + uint8_t aligned[512]; + + uint8_t* ptr = (uint32_t)buf & 3 ? aligned : buf; + + if (!rdWrBlocks(CMD17_DMA_XFERTYP, lba, ptr, 1)) { + return sdError(SD_CARD_ERROR_CMD18); + } + if (ptr != buf) { + memcpy(buf, aligned, 512); + } + return true; +} +//----------------------------------------------------------------------------- +bool SdioCard::readBlocks(uint32_t lba, uint8_t* buf, size_t n) { + if ((uint32_t)buf & 3) { + for (size_t i = 0; i < n; i++, lba++, buf += 512) { + if (!readBlock(lba, buf)) { + return false; // readBlock will set errorCode. + } + } + return true; + } + if (!rdWrBlocks(CMD18_DMA_XFERTYP, lba, buf, n)) { + return sdError(SD_CARD_ERROR_CMD18); + } + return true; +} +//----------------------------------------------------------------------------- +bool SdioCard::readCID(void* cid) { + memcpy(cid, &m_cid, 16); + return true; +} +//----------------------------------------------------------------------------- +bool SdioCard::readCSD(void* csd) { + memcpy(csd, &m_csd, 16); + return true; +} +//----------------------------------------------------------------------------- +bool SdioCard::readData(uint8_t *dst) { + DBG_IRQSTAT(); + uint32_t *p32 = reinterpret_cast(dst); + + if (!(SDHC_PRSSTAT & SDHC_PRSSTAT_RTA)) { + SDHC_PROCTL &= ~SDHC_PROCTL_SABGREQ; + if ((SDHC_BLKATTR & 0XFFFF0000) == 0X10000) { + // Don't stop at block gap if last block. Allows auto CMD12. + SDHC_PROCTL |= SDHC_PROCTL_CREQ; + } else { + noInterrupts(); + SDHC_PROCTL |= SDHC_PROCTL_CREQ; + SDHC_PROCTL |= SDHC_PROCTL_SABGREQ; + interrupts(); + } + } + if (waitTimeout(isBusyFifoRead)) { + return sdError(SD_CARD_ERROR_READ_FIFO); + } + for (uint32_t iw = 0 ; iw < 512/(4*FIFO_WML); iw++) { + while (0 == (SDHC_PRSSTAT & SDHC_PRSSTAT_BREN)) { + } + for (uint32_t i = 0; i < FIFO_WML; i++) { + p32[i] = SDHC_DATPORT; + } + p32 += FIFO_WML; + } + if (waitTimeout(isBusyTransferComplete)) { + return sdError(SD_CARD_ERROR_READ_TIMEOUT); + } + m_irqstat = SDHC_IRQSTAT; + SDHC_IRQSTAT = m_irqstat; + return (m_irqstat & SDHC_IRQSTAT_TC) && !(m_irqstat & SDHC_IRQSTAT_ERROR); +} +//----------------------------------------------------------------------------- +bool SdioCard::readOCR(uint32_t* ocr) { + *ocr = m_ocr; + return true; +} +//----------------------------------------------------------------------------- +bool SdioCard::readStart(uint32_t lba) { + // K66/K65 Errata - SDHC: Does not support Infinite Block Transfer Mode. + return sdError(SD_CARD_ERROR_FUNCTION_NOT_SUPPORTED); +} +//----------------------------------------------------------------------------- +// SDHC will do Auto CMD12 after count blocks. +bool SdioCard::readStart(uint32_t lba, uint32_t count) { + DBG_IRQSTAT(); + if (count > 0XFFFF) { + return sdError(SD_CARD_ERROR_READ_START); + } + if (yieldTimeout(isBusyCMD13)) { + return sdError(SD_CARD_ERROR_CMD13); + } + if (count > 1) { + SDHC_PROCTL |= SDHC_PROCTL_SABGREQ; + } + SDHC_BLKATTR = SDHC_BLKATTR_BLKCNT(count) | SDHC_BLKATTR_BLKSIZE(512); + if (!cardCommand(CMD18_PGM_XFERTYP, m_highCapacity ? lba : 512*lba)) { + return sdError(SD_CARD_ERROR_CMD18); + } + return true; +} +//----------------------------------------------------------------------------- +bool SdioCard::readStop() { + return transferStop(); +} +//----------------------------------------------------------------------------- +bool SdioCard::syncBlocks() { + return true; +} +//----------------------------------------------------------------------------- +uint8_t SdioCard::type() { + return m_version2 ? m_highCapacity ? + SD_CARD_TYPE_SDHC : SD_CARD_TYPE_SD2 : SD_CARD_TYPE_SD1; +} +//----------------------------------------------------------------------------- +bool SdioCard::writeBlock(uint32_t lba, const uint8_t* buf) { + uint8_t *ptr; + uint8_t aligned[512]; + if (3 & (uint32_t)buf) { + ptr = aligned; + memcpy(aligned, buf, 512); + } else { + ptr = const_cast(buf); + } + if (!rdWrBlocks(CMD24_DMA_XFERTYP, lba, ptr, 1)) { + return sdError(SD_CARD_ERROR_CMD24); + } + return true; +} +//----------------------------------------------------------------------------- +bool SdioCard::writeBlocks(uint32_t lba, const uint8_t* buf, size_t n) { + uint8_t* ptr = const_cast(buf); + if (3 & (uint32_t)ptr) { + for (size_t i = 0; i < n; i++, lba++, ptr += 512) { + if (!writeBlock(lba, ptr)) { + return false; // writeBlock will set errorCode. + } + } + return true; + } + if (!rdWrBlocks(CMD25_DMA_XFERTYP, lba, ptr, n)) { + return sdError(SD_CARD_ERROR_CMD25); + } + return true; +} +//----------------------------------------------------------------------------- +bool SdioCard::writeData(const uint8_t* src) { + DBG_IRQSTAT(); + const uint32_t* p32 = reinterpret_cast(src); + + if (!(SDHC_PRSSTAT & SDHC_PRSSTAT_WTA)) { + SDHC_PROCTL &= ~SDHC_PROCTL_SABGREQ; + // Don't stop at block gap if last block. Allows auto CMD12. + if ((SDHC_BLKATTR & 0XFFFF0000) == 0X10000) { + SDHC_PROCTL |= SDHC_PROCTL_CREQ; + } else { + SDHC_PROCTL |= SDHC_PROCTL_CREQ; + SDHC_PROCTL |= SDHC_PROCTL_SABGREQ; + } + } + if (waitTimeout(isBusyFifoWrite)) { + return sdError(SD_CARD_ERROR_WRITE_FIFO); + } + for (uint32_t iw = 0 ; iw < 512/(4*FIFO_WML); iw++) { + while (0 == (SDHC_PRSSTAT & SDHC_PRSSTAT_BWEN)) { + } + for (uint32_t i = 0; i < FIFO_WML; i++) { + SDHC_DATPORT = p32[i]; + } + p32 += FIFO_WML; + } + if (waitTimeout(isBusyTransferComplete)) { + return sdError(SD_CARD_ERROR_WRITE_TIMEOUT); + } + m_irqstat = SDHC_IRQSTAT; + SDHC_IRQSTAT = m_irqstat; + return (m_irqstat & SDHC_IRQSTAT_TC) && !(m_irqstat & SDHC_IRQSTAT_ERROR); +} +//----------------------------------------------------------------------------- +bool SdioCard::writeStart(uint32_t lba) { + // K66/K65 Errata - SDHC: Does not support Infinite Block Transfer Mode. + return sdError(SD_CARD_ERROR_FUNCTION_NOT_SUPPORTED); +} +//----------------------------------------------------------------------------- +// SDHC will do Auto CMD12 after count blocks. +bool SdioCard::writeStart(uint32_t lba, uint32_t count) { + if (count > 0XFFFF) { + return sdError(SD_CARD_ERROR_WRITE_START); + } + DBG_IRQSTAT(); + if (yieldTimeout(isBusyCMD13)) { + return sdError(SD_CARD_ERROR_CMD13); + } + if (count > 1) { + SDHC_PROCTL |= SDHC_PROCTL_SABGREQ; + } + SDHC_BLKATTR = SDHC_BLKATTR_BLKCNT(count) | SDHC_BLKATTR_BLKSIZE(512); + + if (!cardCommand(CMD25_PGM_XFERTYP, m_highCapacity ? lba : 512*lba)) { + return sdError(SD_CARD_ERROR_CMD25); + } + return true; +} +//----------------------------------------------------------------------------- +bool SdioCard::writeStop() { + return transferStop(); +} +#endif // defined(__MK64FX512__) || defined(__MK66FX1M0__) diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdFat.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdFat.h new file mode 100644 index 0000000..3cdc970 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdFat.h @@ -0,0 +1,512 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 SdFat_h +#define SdFat_h +/** + * \file + * \brief SdFat class + */ +#include "SysCall.h" +#include "BlockDriver.h" +#include "FatLib/FatLib.h" +#include "SdCard/SdioCard.h" +#if INCLUDE_SDIOS +#include "sdios.h" +#endif // INCLUDE_SDIOS +//------------------------------------------------------------------------------ +/** SdFat version */ +#define SD_FAT_VERSION "1.0.15" +//============================================================================== +/** + * \class SdBaseFile + * \brief Class for backward compatibility. + */ +class SdBaseFile : public FatFile { + public: + SdBaseFile() {} + /** Create a file object and open it in the current working directory. + * + * \param[in] path A path for a file to be opened. + * + * \param[in] oflag Values for \a oflag are constructed by a + * bitwise-inclusive OR of open flags. see + * FatFile::open(FatFile*, const char*, oflag_t). + */ + SdBaseFile(const char* path, oflag_t oflag) : FatFile(path, oflag) {} +}; +//----------------------------------------------------------------------------- +#if ENABLE_ARDUINO_FEATURES +/** + * \class SdFile + * \brief Class for backward compatibility. + */ +class SdFile : public PrintFile { + public: + SdFile() {} + /** Create a file object and open it in the current working directory. + * + * \param[in] path A path for a file to be opened. + * + * \param[in] oflag Values for \a oflag are constructed by a + * bitwise-inclusive OR of open flags. see + * FatFile::open(FatFile*, const char*, oflag_t). + */ + SdFile(const char* path, oflag_t oflag) : PrintFile(path, oflag) {} +}; +#endif // #if ENABLE_ARDUINO_FEATURES +//----------------------------------------------------------------------------- +/** + * \class SdFileSystem + * \brief Virtual base class for %SdFat library. + */ +template +class SdFileSystem : public FatFileSystem { + public: + /** Initialize file system. + * \return true for success else false. + */ + bool begin() { + return FatFileSystem::begin(&m_card); + } + /** \return Pointer to SD card object */ + SdDriverClass *card() { + m_card.syncBlocks(); + return &m_card; + } + /** %Print any SD error code to Serial and halt. */ + void errorHalt() { + errorHalt(&Serial); + } + /** %Print any SD error code and halt. + * + * \param[in] pr Print destination. + */ + void errorHalt(Print* pr) { + errorPrint(pr); + SysCall::halt(); + } + /** %Print msg, any SD error code and halt. + * + * \param[in] msg Message to print. + */ + void errorHalt(char const* msg) { + errorHalt(&Serial, msg); + } + /** %Print msg, any SD error code, and halt. + * + * \param[in] pr Print destination. + * \param[in] msg Message to print. + */ + void errorHalt(Print* pr, char const* msg) { + errorPrint(pr, msg); + SysCall::halt(); + } + /** %Print any SD error code to Serial */ + void errorPrint() { + errorPrint(&Serial); + } + /** %Print any SD error code. + * \param[in] pr Print device. + */ + void errorPrint(Print* pr) { + if (!cardErrorCode()) { + return; + } + pr->print(F("SD errorCode: 0X")); + pr->print(cardErrorCode(), HEX); + pr->print(F(",0X")); + pr->println(cardErrorData(), HEX); + } + /** %Print msg, any SD error code. + * + * \param[in] msg Message to print. + */ + void errorPrint(const char* msg) { + errorPrint(&Serial, msg); + } + /** %Print msg, any SD error code. + * + * \param[in] pr Print destination. + * \param[in] msg Message to print. + */ + void errorPrint(Print* pr, char const* msg) { + pr->print(F("error: ")); + pr->println(msg); + errorPrint(pr); + } + /** %Print any SD error code and halt. */ + void initErrorHalt() { + initErrorHalt(&Serial); + } + /** %Print error details and halt after begin fails. + * + * \param[in] pr Print destination. + */ + void initErrorHalt(Print* pr) { + initErrorPrint(pr); + SysCall::halt(); + } + /**Print message, error details, and halt after begin() fails. + * + * \param[in] msg Message to print. + */ + void initErrorHalt(char const *msg) { + initErrorHalt(&Serial, msg); + } + /**Print message, error details, and halt after begin() fails. + * \param[in] pr Print device. + * \param[in] msg Message to print. + */ + void initErrorHalt(Print* pr, char const *msg) { + pr->println(msg); + initErrorHalt(pr); + } + + /** Print error details after begin() fails. */ + void initErrorPrint() { + initErrorPrint(&Serial); + } + /** Print error details after begin() fails. + * + * \param[in] pr Print destination. + */ + void initErrorPrint(Print* pr) { + if (cardErrorCode()) { + pr->println(F("Can't access SD card. Do not reformat.")); + if (cardErrorCode() == SD_CARD_ERROR_CMD0) { + pr->println(F("No card, wrong chip select pin, or SPI problem?")); + } + errorPrint(pr); + } else if (vol()->fatType() == 0) { + pr->println(F("Invalid format, reformat SD.")); + } else if (!vwd()->isOpen()) { + pr->println(F("Can't open root directory.")); + } else { + pr->println(F("No error found.")); + } + } + /**Print message and error details and halt after begin() fails. + * + * \param[in] msg Message to print. + */ + void initErrorPrint(char const *msg) { + initErrorPrint(&Serial, msg); + } + /**Print message and error details and halt after begin() fails. + * + * \param[in] pr Print destination. + * \param[in] msg Message to print. + */ + void initErrorPrint(Print* pr, char const *msg) { + pr->println(msg); + initErrorPrint(pr); + } +#if defined(ARDUINO) || defined(DOXYGEN) + /** %Print msg, any SD error code, and halt. + * + * \param[in] msg Message to print. + */ + void errorHalt(const __FlashStringHelper* msg) { + errorHalt(&Serial, msg); + } + /** %Print msg, any SD error code, and halt. + * + * \param[in] pr Print destination. + * \param[in] msg Message to print. + */ + void errorHalt(Print* pr, const __FlashStringHelper* msg) { + errorPrint(pr, msg); + SysCall::halt(); + } + + /** %Print msg, any SD error code. + * + * \param[in] msg Message to print. + */ + void errorPrint(const __FlashStringHelper* msg) { + errorPrint(&Serial, msg); + } + /** %Print msg, any SD error code. + * + * \param[in] pr Print destination. + * \param[in] msg Message to print. + */ + void errorPrint(Print* pr, const __FlashStringHelper* msg) { + pr->print(F("error: ")); + pr->println(msg); + errorPrint(pr); + } + /**Print message, error details, and halt after begin() fails. + * + * \param[in] msg Message to print. + */ + void initErrorHalt(const __FlashStringHelper* msg) { + initErrorHalt(&Serial, msg); + } + /**Print message, error details, and halt after begin() fails. + * \param[in] pr Print device for message. + * \param[in] msg Message to print. + */ + void initErrorHalt(Print* pr, const __FlashStringHelper* msg) { + pr->println(msg); + initErrorHalt(pr); + } + /**Print message and error details and halt after begin() fails. + * + * \param[in] msg Message to print. + */ + void initErrorPrint(const __FlashStringHelper* msg) { + initErrorPrint(&Serial, msg); + } + /**Print message and error details and halt after begin() fails. + * + * \param[in] pr Print destination. + * \param[in] msg Message to print. + */ + void initErrorPrint(Print* pr, const __FlashStringHelper* msg) { + pr->println(msg); + initErrorPrint(pr); + } +#endif // defined(ARDUINO) || defined(DOXYGEN) + /** \return The card error code */ + uint8_t cardErrorCode() { + return m_card.errorCode(); + } + /** \return the card error data */ + uint32_t cardErrorData() { + return m_card.errorData(); + } + + protected: + SdDriverClass m_card; +}; +//============================================================================== +/** + * \class SdFat + * \brief Main file system class for %SdFat library. + */ +class SdFat : public SdFileSystem { + public: +#if IMPLEMENT_SPI_PORT_SELECTION || defined(DOXYGEN) + SdFat() { + m_spi.setPort(nullptr); + } + /** Constructor with SPI port selection. + * \param[in] spiPort SPI port number. + */ + explicit SdFat(SPIClass* spiPort) { + m_spi.setPort(spiPort); + } +#endif // IMPLEMENT_SPI_PORT_SELECTION + /** Initialize SD card and file system. + * + * \param[in] csPin SD card chip select pin. + * \param[in] spiSettings SPI speed, mode, and bit order. + * \return true for success else false. + */ + bool begin(uint8_t csPin = SS, SPISettings spiSettings = SPI_FULL_SPEED) { + return m_card.begin(&m_spi, csPin, spiSettings) && + SdFileSystem::begin(); + } + /** Initialize SD card for diagnostic use only. + * + * \param[in] csPin SD card chip select pin. + * \param[in] settings SPI speed, mode, and bit order. + * \return true for success else false. + */ + bool cardBegin(uint8_t csPin = SS, SPISettings settings = SPI_FULL_SPEED) { + return m_card.begin(&m_spi, csPin, settings); + } + /** Initialize file system for diagnostic use only. + * \return true for success else false. + */ + bool fsBegin() { + return FatFileSystem::begin(card()); + } + + private: + SdFatSpiDriver m_spi; +}; +//============================================================================== +#if ENABLE_SDIO_CLASS || defined(DOXYGEN) +/** + * \class SdFatSdio + * \brief SdFat class using SDIO. + */ +class SdFatSdio : public SdFileSystem { + public: + /** Initialize SD card and file system. + * \return true for success else false. + */ + bool begin() { + return m_card.begin() && SdFileSystem::begin(); + } + /** Initialize SD card for diagnostic use only. + * + * \return true for success else false. + */ + bool cardBegin() { + return m_card.begin(); + } + /** Initialize file system for diagnostic use only. + * \return true for success else false. + */ + bool fsBegin() { + return SdFileSystem::begin(); + } +}; +#if ENABLE_SDIOEX_CLASS || defined(DOXYGEN) +//----------------------------------------------------------------------------- +/** + * \class SdFatSdioEX + * \brief SdFat class using SDIO. + */ +class SdFatSdioEX : public SdFileSystem { + public: + /** Initialize SD card and file system. + * \return true for success else false. + */ + bool begin() { + return m_card.begin() && SdFileSystem::begin(); + } + /** \return Pointer to SD card object */ + SdioCardEX* card() { + return &m_card; + } + /** Initialize SD card for diagnostic use only. + * + * \return true for success else false. + */ + bool cardBegin() { + return m_card.begin(); + } + /** Initialize file system for diagnostic use only. + * \return true for success else false. + */ + bool fsBegin() { + return SdFileSystem::begin(); + } +}; +#endif // ENABLE_SDIOEX_CLASS || defined(DOXYGEN) +#endif // ENABLE_SDIO_CLASS || defined(DOXYGEN) +//============================================================================= +#if ENABLE_SOFTWARE_SPI_CLASS || defined(DOXYGEN) +/** + * \class SdFatSoftSpi + * \brief SdFat class using software SPI. + */ +template +class SdFatSoftSpi : public SdFileSystem { + public: + /** Initialize SD card and file system. + * + * \param[in] csPin SD card chip select pin. + * \param[in] spiSettings ignored for software SPI.. + * \return true for success else false. + */ + bool begin(uint8_t csPin = SS, SPISettings spiSettings = SPI_FULL_SPEED) { + return m_card.begin(&m_spi, csPin, spiSettings) && + SdFileSystem::begin(); + } + private: + SdSpiSoftDriver m_spi; +}; +#endif // #if ENABLE_SOFTWARE_SPI_CLASS || defined(DOXYGEN) +//============================================================================== +#if ENABLE_EXTENDED_TRANSFER_CLASS || defined(DOXYGEN) +/** + * \class SdFatEX + * \brief SdFat class with extended SD I/O. + */ +class SdFatEX : public SdFileSystem { + public: +#if IMPLEMENT_SPI_PORT_SELECTION || defined(DOXYGEN) + SdFatEX() { + m_spi.setPort(nullptr); + } + /** Constructor with SPI port selection. + * \param[in] spiPort SPI port number. + */ + explicit SdFatEX(SPIClass* spiPort) { + m_spi.setPort(spiPort); + } +#endif // IMPLEMENT_SPI_PORT_SELECTION + /** Initialize SD card and file system. + * + * \param[in] csPin SD card chip select pin. + * \param[in] spiSettings SPI speed, mode, and bit order. + * \return true for success else false. + */ + bool begin(uint8_t csPin = SS, SPISettings spiSettings = SPI_FULL_SPEED) { + return m_card.begin(&m_spi, csPin, spiSettings) && + SdFileSystem::begin(); + } + + private: + SdFatSpiDriver m_spi; +}; +//============================================================================== +#if ENABLE_SOFTWARE_SPI_CLASS || defined(DOXYGEN) +/** + * \class SdFatSoftSpiEX + * \brief SdFat class using software SPI and extended SD I/O. + */ +template +class SdFatSoftSpiEX : public SdFileSystem { + public: + /** Initialize SD card and file system. + * + * \param[in] csPin SD card chip select pin. + * \param[in] spiSettings ignored for software SPI. + * \return true for success else false. + */ + bool begin(uint8_t csPin = SS, SPISettings spiSettings = SPI_FULL_SPEED) { + return m_card.begin(&m_spi, csPin, spiSettings) && + SdFileSystem::begin(); + } + private: + SdSpiSoftDriver m_spi; +}; +#endif // #if ENABLE_SOFTWARE_SPI_CLASS || defined(DOXYGEN) +#endif // ENABLE_EXTENDED_TRANSFER_CLASS || defined(DOXYGEN) +//============================================================================= +/** + * \class Sd2Card + * \brief Raw access to SD and SDHC card using default SPI library. + */ +class Sd2Card : public SdSpiCard { + public: + /** Initialize the SD card. + * \param[in] csPin SD chip select pin. + * \param[in] settings SPI speed, mode, and bit order. + * \return true for success else false. + */ + bool begin(uint8_t csPin = SS, SPISettings settings = SD_SCK_MHZ(50)) { + return SdSpiCard::begin(&m_spi, csPin, settings); + } + private: + SdFatSpiDriver m_spi; +}; +#endif // SdFat_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdFatConfig.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdFatConfig.h new file mode 100644 index 0000000..c0d1ade --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdFatConfig.h @@ -0,0 +1,233 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +/** + * \file + * \brief configuration definitions + */ +#ifndef SdFatConfig_h +#define SdFatConfig_h +#include +#include +#ifdef __AVR__ +#include +#endif // __AVR__ +//------------------------------------------------------------------------------ +/** + * Set INCLUDE_SDIOS nonzero to include sdios.h in SdFat.h. + * sdios.h provides C++ style IO Streams. + */ +#define INCLUDE_SDIOS 1 +//------------------------------------------------------------------------------ +/** + * Set USE_LONG_FILE_NAMES nonzero to use long file names (LFN). + * Long File Name are limited to a maximum length of 255 characters. + * + * This implementation allows 7-bit characters in the range + * 0X20 to 0X7E except the following characters are not allowed: + * + * < (less than) + * > (greater than) + * : (colon) + * " (double quote) + * / (forward slash) + * \ (backslash) + * | (vertical bar or pipe) + * ? (question mark) + * * (asterisk) + * + */ +#define USE_LONG_FILE_NAMES 1 +//------------------------------------------------------------------------------ +/** + * If the symbol ENABLE_EXTENDED_TRANSFER_CLASS is nonzero, the class SdFatEX + * will be defined. If the symbol ENABLE_SOFTWARE_SPI_CLASS is also nonzero, + * the class SdFatSoftSpiEX will be defined. + * + * These classes used extended multi-block SD I/O for better performance. + * the SPI bus may not be shared with other devices in this mode. + */ +#define ENABLE_EXTENDED_TRANSFER_CLASS 0 +//------------------------------------------------------------------------------ +/** + * If the symbol USE_STANDARD_SPI_LIBRARY is zero, an optimized custom SPI + * driver is used if it exists. If the symbol USE_STANDARD_SPI_LIBRARY is + * one, the standard Arduino SPI.h library is used with SPI. If the symbol + * USE_STANDARD_SPI_LIBRARY is two, the SPI port can be selected with the + * constructors SdFat(SPIClass* spiPort) and SdFatEX(SPIClass* spiPort). + */ +#define USE_STANDARD_SPI_LIBRARY 0 +//------------------------------------------------------------------------------ +/** + * If the symbol ENABLE_SOFTWARE_SPI_CLASS is nonzero, the class SdFatSoftSpi + * will be defined. If ENABLE_EXTENDED_TRANSFER_CLASS is also nonzero, + * the class SdFatSoftSpiEX will be defined. + */ +#define ENABLE_SOFTWARE_SPI_CLASS 0 +//------------------------------------------------------------------------------ +/** If the symbol USE_FCNTL_H is nonzero, open flags for access modes O_RDONLY, + * O_WRONLY, O_RDWR and the open modifiers O_APPEND, O_CREAT, O_EXCL, O_SYNC + * will be defined by including the system file fcntl.h. + */ +#if defined(__AVR__) +// AVR fcntl.h does not define open flags. +#define USE_FCNTL_H 0 +#elif defined(PLATFORM_ID) +// Particle boards - use fcntl.h. +#define USE_FCNTL_H 1 +#elif defined(__arm__) +// ARM gcc defines open flags. +#define USE_FCNTL_H 1 +#else // defined(__AVR__) +#define USE_FCNTL_H 0 +#endif // defined(__AVR__) +//------------------------------------------------------------------------------ +/** + * If CHECK_FLASH_PROGRAMMING is zero, overlap of single sector flash + * programming and other operations will be allowed for faster write + * performance. + * + * Some cards will not sleep in low power mode unless CHECK_FLASH_PROGRAMMING + * is non-zero. + */ +#define CHECK_FLASH_PROGRAMMING 1 +//------------------------------------------------------------------------------ +/** + * Set MAINTAIN_FREE_CLUSTER_COUNT nonzero to keep the count of free clusters + * updated. This will increase the speed of the freeClusterCount() call + * after the first call. Extra flash will be required. + */ +#define MAINTAIN_FREE_CLUSTER_COUNT 0 +//------------------------------------------------------------------------------ +/** + * To enable SD card CRC checking set USE_SD_CRC nonzero. + * + * Set USE_SD_CRC to 1 to use a smaller CRC-CCITT function. This function + * is slower for AVR but may be fast for ARM and other processors. + * + * Set USE_SD_CRC to 2 to used a larger table driven CRC-CCITT function. This + * function is faster for AVR but may be slower for ARM and other processors. + */ +#define USE_SD_CRC 0 +//------------------------------------------------------------------------------ +/** + * Handle Watchdog Timer for WiFi modules. + * + * Yield will be called before accessing the SPI bus if it has been more + * than WDT_YIELD_TIME_MICROS microseconds since the last yield call by SdFat. + */ +#if defined(PLATFORM_ID) || defined(ESP8266) +// If Particle device or ESP8266 call yield. +#define WDT_YIELD_TIME_MICROS 100000 +#else +#define WDT_YIELD_TIME_MICROS 0 +#endif +//------------------------------------------------------------------------------ +/** + * Set FAT12_SUPPORT nonzero to enable use if FAT12 volumes. + * FAT12 has not been well tested and requires additional flash. + */ +#define FAT12_SUPPORT 0 +//------------------------------------------------------------------------------ +/** + * Set DESTRUCTOR_CLOSES_FILE nonzero to close a file in its destructor. + * + * Causes use of lots of heap in ARM. + */ +#define DESTRUCTOR_CLOSES_FILE 0 +//------------------------------------------------------------------------------ +/** + * Call flush for endl if ENDL_CALLS_FLUSH is nonzero + * + * The standard for iostreams is to call flush. This is very costly for + * SdFat. Each call to flush causes 2048 bytes of I/O to the SD. + * + * SdFat has a single 512 byte buffer for SD I/O so it must write the current + * data block to the SD, read the directory block from the SD, update the + * directory entry, write the directory block to the SD and read the data + * block back into the buffer. + * + * The SD flash memory controller is not designed for this many rewrites + * so performance may be reduced by more than a factor of 100. + * + * If ENDL_CALLS_FLUSH is zero, you must call flush and/or close to force + * all data to be written to the SD. + */ +#define ENDL_CALLS_FLUSH 0 +//------------------------------------------------------------------------------ +/** + * Set USE_SEPARATE_FAT_CACHE nonzero to use a second 512 byte cache + * for FAT table entries. This improves performance for large writes + * that are not a multiple of 512 bytes. + */ +#ifdef __arm__ +#define USE_SEPARATE_FAT_CACHE 1 +#else // __arm__ +#define USE_SEPARATE_FAT_CACHE 0 +#endif // __arm__ +//------------------------------------------------------------------------------ +/** + * Set USE_MULTI_BLOCK_IO nonzero to use multi-block SD read/write. + * + * Don't use mult-block read/write on small AVR boards. + */ +#if defined(RAMEND) && RAMEND < 3000 +#define USE_MULTI_BLOCK_IO 0 +#else // RAMEND +#define USE_MULTI_BLOCK_IO 1 +#endif // RAMEND +//----------------------------------------------------------------------------- +/** Enable SDIO driver if available. */ +#if defined(__MK64FX512__) || defined(__MK66FX1M0__) +#define ENABLE_SDIO_CLASS 1 +#define ENABLE_SDIOEX_CLASS 1 +#else // ENABLE_SDIO_CLASS +#define ENABLE_SDIO_CLASS 0 +#endif // ENABLE_SDIO_CLASS +//------------------------------------------------------------------------------ +/** + * Determine the default SPI configuration. + */ +#if defined(__STM32F1__) || defined(__STM32F4__) || defined(PLATFORM_ID) +// has multiple SPI ports +#define SD_HAS_CUSTOM_SPI 2 +#elif defined(__AVR__)\ + || defined(__SAM3X8E__) || defined(__SAM3X8H__)\ + || (defined(__arm__) && defined(CORE_TEENSY))\ + || defined(ESP8266) +#define SD_HAS_CUSTOM_SPI 1 +#else // SD_HAS_CUSTOM_SPI +// Use standard SPI library. +#define SD_HAS_CUSTOM_SPI 0 +#endif // SD_HAS_CUSTOM_SPI +//------------------------------------------------------------------------------ +/** + * Check if API to select HW SPI port is needed. + */ +#if USE_STANDARD_SPI_LIBRARY > 1 || SD_HAS_CUSTOM_SPI > 1 +#define IMPLEMENT_SPI_PORT_SELECTION 1 +#else // IMPLEMENT_SPI_PORT_SELECTION +#define IMPLEMENT_SPI_PORT_SELECTION 0 +#endif // IMPLEMENT_SPI_PORT_SELECTION +#endif // SdFatConfig_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/DigitalPin.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/DigitalPin.h new file mode 100644 index 0000000..38859d9 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/DigitalPin.h @@ -0,0 +1,386 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +/** + * @file + * @brief Fast Digital Pin functions + * + * @defgroup digitalPin Fast Pin I/O + * @details Fast Digital I/O functions and template class. + * @{ + */ +#ifndef DigitalPin_h +#define DigitalPin_h +#if defined(__AVR__) || defined(DOXYGEN) +#include +/** GpioPinMap type */ +struct GpioPinMap_t { + volatile uint8_t* pin; /**< address of PIN for this pin */ + volatile uint8_t* ddr; /**< address of DDR for this pin */ + volatile uint8_t* port; /**< address of PORT for this pin */ + uint8_t mask; /**< bit mask for this pin */ +}; + +/** Initializer macro. */ +#define GPIO_PIN(reg, bit) {&PIN##reg, &DDR##reg, &PORT##reg, 1 << bit} + +// Include pin map for current board. +#include "boards/GpioPinMap.h" +//------------------------------------------------------------------------------ +/** generate bad pin number error */ +void badPinNumber(void) + __attribute__((error("Pin number is too large or not a constant"))); +//------------------------------------------------------------------------------ +/** Check for valid pin number + * @param[in] pin Number of pin to be checked. + */ +static inline __attribute__((always_inline)) +void badPinCheck(uint8_t pin) { + if (!__builtin_constant_p(pin) || pin >= NUM_DIGITAL_PINS) { + badPinNumber(); + } +} +//------------------------------------------------------------------------------ +/** DDR register address + * @param[in] pin Arduino pin number + * @return register address + */ +static inline __attribute__((always_inline)) +volatile uint8_t* ddrReg(uint8_t pin) { + badPinCheck(pin); + return GpioPinMap[pin].ddr; +} +//------------------------------------------------------------------------------ +/** Bit mask for pin + * @param[in] pin Arduino pin number + * @return mask + */ +static inline __attribute__((always_inline)) +uint8_t pinMask(uint8_t pin) { + badPinCheck(pin); + return GpioPinMap[pin].mask; +} +//------------------------------------------------------------------------------ +/** PIN register address + * @param[in] pin Arduino pin number + * @return register address + */ +static inline __attribute__((always_inline)) +volatile uint8_t* pinReg(uint8_t pin) { + badPinCheck(pin); + return GpioPinMap[pin].pin; +} +//------------------------------------------------------------------------------ +/** PORT register address + * @param[in] pin Arduino pin number + * @return register address + */ +static inline __attribute__((always_inline)) +volatile uint8_t* portReg(uint8_t pin) { + badPinCheck(pin); + return GpioPinMap[pin].port; +} +//------------------------------------------------------------------------------ +/** Fast write helper. + * @param[in] address I/O register address + * @param[in] mask bit mask for pin + * @param[in] level value for bit + */ +static inline __attribute__((always_inline)) +void fastBitWriteSafe(volatile uint8_t* address, uint8_t mask, bool level) { + uint8_t s; + if (address > reinterpret_cast(0X3F)) { + s = SREG; + cli(); + } + if (level) { + *address |= mask; + } else { + *address &= ~mask; + } + if (address > reinterpret_cast(0X3F)) { + SREG = s; + } +} +//------------------------------------------------------------------------------ +/** Read pin value. + * @param[in] pin Arduino pin number + * @return value read + */ +static inline __attribute__((always_inline)) +bool fastDigitalRead(uint8_t pin) { + return *pinReg(pin) & pinMask(pin); +} +//------------------------------------------------------------------------------ +/** Toggle a pin. + * @param[in] pin Arduino pin number + * + * If the pin is in output mode toggle the pin level. + * If the pin is in input mode toggle the state of the 20K pullup. + */ +static inline __attribute__((always_inline)) +void fastDigitalToggle(uint8_t pin) { + if (pinReg(pin) > reinterpret_cast(0X3F)) { + // must write bit to high address port + *pinReg(pin) = pinMask(pin); + } else { + // will compile to sbi and PIN register will not be read. + *pinReg(pin) |= pinMask(pin); + } +} +//------------------------------------------------------------------------------ +/** Set pin value. + * @param[in] pin Arduino pin number + * @param[in] level value to write + */ +static inline __attribute__((always_inline)) +void fastDigitalWrite(uint8_t pin, bool level) { + fastBitWriteSafe(portReg(pin), pinMask(pin), level); +} +//------------------------------------------------------------------------------ +/** Write the DDR register. + * @param[in] pin Arduino pin number + * @param[in] level value to write + */ +static inline __attribute__((always_inline)) +void fastDdrWrite(uint8_t pin, bool level) { + fastBitWriteSafe(ddrReg(pin), pinMask(pin), level); +} +//------------------------------------------------------------------------------ +/** Set pin mode. + * @param[in] pin Arduino pin number + * @param[in] mode INPUT, OUTPUT, or INPUT_PULLUP. + * + * The internal pullup resistors will be enabled if mode is INPUT_PULLUP + * and disabled if the mode is INPUT. + */ +static inline __attribute__((always_inline)) +void fastPinMode(uint8_t pin, uint8_t mode) { + fastDdrWrite(pin, mode == OUTPUT); + if (mode != OUTPUT) { + fastDigitalWrite(pin, mode == INPUT_PULLUP); + } +} +#else // defined(__AVR__) +#if defined(CORE_TEENSY) +//------------------------------------------------------------------------------ +/** read pin value + * @param[in] pin Arduino pin number + * @return value read + */ +static inline __attribute__((always_inline)) +bool fastDigitalRead(uint8_t pin) { + return *portInputRegister(pin); +} +//------------------------------------------------------------------------------ +/** Set pin value + * @param[in] pin Arduino pin number + * @param[in] level value to write + */ +static inline __attribute__((always_inline)) +void fastDigitalWrite(uint8_t pin, bool value) { + if (value) { + *portSetRegister(pin) = 1; + } else { + *portClearRegister(pin) = 1; + } +} +#elif defined(__SAM3X8E__) || defined(__SAM3X8H__) +//------------------------------------------------------------------------------ +/** read pin value + * @param[in] pin Arduino pin number + * @return value read + */ +static inline __attribute__((always_inline)) +bool fastDigitalRead(uint8_t pin) { + return g_APinDescription[pin].pPort->PIO_PDSR & g_APinDescription[pin].ulPin; +} +//------------------------------------------------------------------------------ +/** Set pin value + * @param[in] pin Arduino pin number + * @param[in] level value to write + */ +static inline __attribute__((always_inline)) +void fastDigitalWrite(uint8_t pin, bool value) { + if (value) { + g_APinDescription[pin].pPort->PIO_SODR = g_APinDescription[pin].ulPin; + } else { + g_APinDescription[pin].pPort->PIO_CODR = g_APinDescription[pin].ulPin; + } +} +#elif defined(ESP8266) +//------------------------------------------------------------------------------ +/** Set pin value + * @param[in] pin Arduino pin number + * @param[in] val value to write + */ +static inline __attribute__((always_inline)) +void fastDigitalWrite(uint8_t pin, uint8_t val) { + if (pin < 16) { + if (val) { + GPOS = (1 << pin); + } else { + GPOC = (1 << pin); + } + } else if (pin == 16) { + if (val) { + GP16O |= 1; + } else { + GP16O &= ~1; + } + } +} +//------------------------------------------------------------------------------ +/** Read pin value + * @param[in] pin Arduino pin number + * @return value read + */ +static inline __attribute__((always_inline)) +bool fastDigitalRead(uint8_t pin) { + if (pin < 16) { + return GPIP(pin); + } else if (pin == 16) { + return GP16I & 0x01; + } + return 0; +} +#else // CORE_TEENSY +//------------------------------------------------------------------------------ +inline void fastDigitalWrite(uint8_t pin, bool value) { + digitalWrite(pin, value); +} +//------------------------------------------------------------------------------ +inline bool fastDigitalRead(uint8_t pin) { + return digitalRead(pin); +} +#endif // CORE_TEENSY +//------------------------------------------------------------------------------ +inline void fastDigitalToggle(uint8_t pin) { + fastDigitalWrite(pin, !fastDigitalRead(pin)); +} +//------------------------------------------------------------------------------ +inline void fastPinMode(uint8_t pin, uint8_t mode) { + pinMode(pin, mode); +} +#endif // __AVR__ +//------------------------------------------------------------------------------ +/** set pin configuration + * @param[in] pin Arduino pin number + * @param[in] mode mode INPUT or OUTPUT. + * @param[in] level If mode is output, set level high/low. + * If mode is input, enable or disable the pin's 20K pullup. + */ +#define fastPinConfig(pin, mode, level)\ + {fastPinMode(pin, mode); fastDigitalWrite(pin, level);} +//============================================================================== +/** + * @class DigitalPin + * @brief Fast digital port I/O + */ +template +class DigitalPin { + public: + //---------------------------------------------------------------------------- + /** Constructor */ + DigitalPin() {} + //---------------------------------------------------------------------------- + /** Asignment operator. + * @param[in] value If true set the pin's level high else set the + * pin's level low. + * + * @return This DigitalPin instance. + */ + inline DigitalPin & operator = (bool value) __attribute__((always_inline)) { + write(value); + return *this; + } + //---------------------------------------------------------------------------- + /** Parenthesis operator. + * @return Pin's level + */ + inline operator bool () const __attribute__((always_inline)) { + return read(); + } + //---------------------------------------------------------------------------- + /** Set pin configuration. + * @param[in] mode: INPUT or OUTPUT. + * @param[in] level If mode is OUTPUT, set level high/low. + * If mode is INPUT, enable or disable the pin's 20K pullup. + */ + inline __attribute__((always_inline)) + void config(uint8_t mode, bool level) { + fastPinConfig(PinNumber, mode, level); + } + //---------------------------------------------------------------------------- + /** + * Set pin level high if output mode or enable 20K pullup if input mode. + */ + inline __attribute__((always_inline)) + void high() {write(true);} + //---------------------------------------------------------------------------- + /** + * Set pin level low if output mode or disable 20K pullup if input mode. + */ + inline __attribute__((always_inline)) + void low() {write(false);} + //---------------------------------------------------------------------------- + /** + * Set pin mode. + * @param[in] mode: INPUT, OUTPUT, or INPUT_PULLUP. + * + * The internal pullup resistors will be enabled if mode is INPUT_PULLUP + * and disabled if the mode is INPUT. + */ + inline __attribute__((always_inline)) + void mode(uint8_t mode) { + fastPinMode(PinNumber, mode); + } + //---------------------------------------------------------------------------- + /** @return Pin's level. */ + inline __attribute__((always_inline)) + bool read() const { + return fastDigitalRead(PinNumber); + } + //---------------------------------------------------------------------------- + /** Toggle a pin. + * + * If the pin is in output mode toggle the pin's level. + * If the pin is in input mode toggle the state of the 20K pullup. + */ + inline __attribute__((always_inline)) + void toggle() { + fastDigitalToggle(PinNumber); + } + //---------------------------------------------------------------------------- + /** Write the pin's level. + * @param[in] value If true set the pin's level high else set the + * pin's level low. + */ + inline __attribute__((always_inline)) + void write(bool value) { + fastDigitalWrite(PinNumber, value); + } +}; +#endif // DigitalPin_h +/** @} */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiBaseDriver.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiBaseDriver.h new file mode 100644 index 0000000..a3374a5 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiBaseDriver.h @@ -0,0 +1,79 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 SdSpiBaseDriver_h +#define SdSpiBaseDriver_h +/** + * \class SdSpiBaseDriver + * \brief SPI base driver. + */ +class SdSpiBaseDriver { + public: + /** Set SPI options for access to SD/SDHC cards. + * + */ + virtual void activate() = 0; + /** Initialize the SPI bus. + * + * \param[in] chipSelectPin SD card chip select pin. + */ + virtual void begin(uint8_t chipSelectPin) = 0; + /** + * End SPI transaction. + */ + virtual void deactivate() = 0; + /** Receive a byte. + * + * \return The byte. + */ + virtual uint8_t receive() = 0; + /** Receive multiple bytes. + * + * \param[out] buf Buffer to receive the data. + * \param[in] n Number of bytes to receive. + * + * \return Zero for no error or nonzero error code. + */ + virtual uint8_t receive(uint8_t* buf, size_t n) = 0; + /** Send a byte. + * + * \param[in] data Byte to send + */ + virtual void send(uint8_t data) = 0; + /** Send multiple bytes. + * + * \param[in] buf Buffer for data to be sent. + * \param[in] n Number of bytes to send. + */ + virtual void send(const uint8_t* buf, size_t n) = 0; + /** Set CS low. */ + virtual void select() = 0; + /** Save SPI settings. + * \param[in] spiSettings SPI speed, mode, and bit order. + */ + virtual void setSpiSettings(SPISettings spiSettings) = 0; + /** Set CS high. */ + virtual void unselect() = 0; +}; +#endif // SdSpiBaseDriver_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiDriver.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiDriver.h new file mode 100644 index 0000000..47d5538 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiDriver.h @@ -0,0 +1,438 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +/** + * \file + * \brief SpiDriver classes + */ +#ifndef SdSpiDriver_h +#define SdSpiDriver_h +#include +#include "SPI.h" +#include "SdSpiBaseDriver.h" +#include "SdFatConfig.h" +//------------------------------------------------------------------------------ +/** SDCARD_SPI is defined if board has built-in SD card socket */ +#ifndef SDCARD_SPI +#define SDCARD_SPI SPI +#endif // SDCARD_SPI +//------------------------------------------------------------------------------ +/** + * \class SdSpiLibDriver + * \brief SdSpiLibDriver - use standard SPI library. + */ +#if ENABLE_SOFTWARE_SPI_CLASS +class SdSpiLibDriver : public SdSpiBaseDriver { +#else // ENABLE_SOFTWARE_SPI_CLASS +class SdSpiLibDriver { +#endif // ENABLE_SOFTWARE_SPI_CLASS + public: +#if IMPLEMENT_SPI_PORT_SELECTION + /** Activate SPI hardware. */ + void activate() { + m_spi->beginTransaction(m_spiSettings); + } + /** Deactivate SPI hardware. */ + void deactivate() { + m_spi->endTransaction(); + } + /** Initialize the SPI bus. + * + * \param[in] csPin SD card chip select pin. + */ + void begin(uint8_t csPin) { + m_csPin = csPin; + digitalWrite(csPin, HIGH); + pinMode(csPin, OUTPUT); + m_spi->begin(); + } + /** Receive a byte. + * + * \return The byte. + */ + uint8_t receive() { + return m_spi->transfer( 0XFF); + } + /** Receive multiple bytes. + * + * \param[out] buf Buffer to receive the data. + * \param[in] n Number of bytes to receive. + * + * \return Zero for no error or nonzero error code. + */ + uint8_t receive(uint8_t* buf, size_t n) { + for (size_t i = 0; i < n; i++) { + buf[i] = m_spi->transfer(0XFF); + } + return 0; + } + /** Send a byte. + * + * \param[in] data Byte to send + */ + void send(uint8_t data) { + m_spi->transfer(data); + } + /** Send multiple bytes. + * + * \param[in] buf Buffer for data to be sent. + * \param[in] n Number of bytes to send. + */ + void send(const uint8_t* buf, size_t n) { + for (size_t i = 0; i < n; i++) { + m_spi->transfer(buf[i]); + } + } +#else // IMPLEMENT_SPI_PORT_SELECTION + /** Activate SPI hardware. */ + void activate() { + SDCARD_SPI.beginTransaction(m_spiSettings); + } + /** Deactivate SPI hardware. */ + void deactivate() { + SDCARD_SPI.endTransaction(); + } + /** Initialize the SPI bus. + * + * \param[in] csPin SD card chip select pin. + */ + void begin(uint8_t csPin) { + m_csPin = csPin; + digitalWrite(csPin, HIGH); + pinMode(csPin, OUTPUT); + SDCARD_SPI.begin(); + } + /** Receive a byte. + * + * \return The byte. + */ + uint8_t receive() { + return SDCARD_SPI.transfer( 0XFF); + } + /** Receive multiple bytes. + * + * \param[out] buf Buffer to receive the data. + * \param[in] n Number of bytes to receive. + * + * \return Zero for no error or nonzero error code. + */ + uint8_t receive(uint8_t* buf, size_t n) { + for (size_t i = 0; i < n; i++) { + buf[i] = SDCARD_SPI.transfer(0XFF); + } + return 0; + } + /** Send a byte. + * + * \param[in] data Byte to send + */ + void send(uint8_t data) { + SDCARD_SPI.transfer(data); + } + /** Send multiple bytes. + * + * \param[in] buf Buffer for data to be sent. + * \param[in] n Number of bytes to send. + */ + void send(const uint8_t* buf, size_t n) { + for (size_t i = 0; i < n; i++) { + SDCARD_SPI.transfer(buf[i]); + } + } +#endif // IMPLEMENT_SPI_PORT_SELECTION + /** Set CS low. */ + void select() { + digitalWrite(m_csPin, LOW); + } + /** Save SPISettings. + * + * \param[in] spiSettings SPI speed, mode, and byte order. + */ + void setSpiSettings(SPISettings spiSettings) { + m_spiSettings = spiSettings; + } + /** Set CS high. */ + void unselect() { + digitalWrite(m_csPin, HIGH); + } +#if IMPLEMENT_SPI_PORT_SELECTION || defined(DOXYGEN) + /** Set SPI port. + * \param[in] spiPort Hardware SPI port. + */ + void setPort(SPIClass* spiPort) { + m_spi = spiPort ? spiPort : &SDCARD_SPI; + } + private: + SPIClass* m_spi; +#else // IMPLEMENT_SPI_PORT_SELECTION + private: +#endif // IMPLEMENT_SPI_PORT_SELECTION + SPISettings m_spiSettings; + uint8_t m_csPin; +}; +//------------------------------------------------------------------------------ +/** + * \class SdSpiAltDriver + * \brief Optimized SPI class for access to SD and SDHC flash memory cards. + */ +#if ENABLE_SOFTWARE_SPI_CLASS +class SdSpiAltDriver : public SdSpiBaseDriver { +#else // ENABLE_SOFTWARE_SPI_CLASS +class SdSpiAltDriver { +#endif // ENABLE_SOFTWARE_SPI_CLASS + public: + /** Activate SPI hardware. */ + void activate(); + /** Deactivate SPI hardware. */ + void deactivate(); + /** Initialize the SPI bus. + * + * \param[in] csPin SD card chip select pin. + */ + void begin(uint8_t csPin); + /** Receive a byte. + * + * \return The byte. + */ + uint8_t receive(); + /** Receive multiple bytes. + * + * \param[out] buf Buffer to receive the data. + * \param[in] n Number of bytes to receive. + * + * \return Zero for no error or nonzero error code. + */ + uint8_t receive(uint8_t* buf, size_t n); + /** Send a byte. + * + * \param[in] data Byte to send + */ + void send(uint8_t data); + /** Send multiple bytes. + * + * \param[in] buf Buffer for data to be sent. + * \param[in] n Number of bytes to send. + */ + void send(const uint8_t* buf, size_t n); + /** Set CS low. */ + void select() { + digitalWrite(m_csPin, LOW); + } + /** Save SPISettings. + * + * \param[in] spiSettings SPI speed, mode, and byte order. + */ + void setSpiSettings(SPISettings spiSettings) { + m_spiSettings = spiSettings; + } + /** Set CS high. */ + void unselect() { + digitalWrite(m_csPin, HIGH); + } +#if IMPLEMENT_SPI_PORT_SELECTION || defined(DOXYGEN) + /** Set SPI port number. + * \param[in] spiPort Hardware SPI port. + */ + void setPort(SPIClass* spiPort) { + m_spi = spiPort ? spiPort : &SDCARD_SPI; + } + private: + SPIClass* m_spi; +#else // IMPLEMENT_SPI_PORT_SELECTION + private: +#endif // IMPLEMENT_SPI_PORT_SELECTION + SPISettings m_spiSettings; + uint8_t m_csPin; +}; +//------------------------------------------------------------------------------ +#if ENABLE_SOFTWARE_SPI_CLASS || defined(DOXYGEN) +#ifdef ARDUINO +#include "SoftSPI.h" +#elif defined(PLATFORM_ID) // Only defined if a Particle device +#include "SoftSPIParticle.h" +#endif // ARDUINO +/** + * \class SdSpiSoftDriver + * \brief Software SPI class for access to SD and SDHC flash memory cards. + */ +template +class SdSpiSoftDriver : public SdSpiBaseDriver { + public: + /** Dummy activate SPI hardware for software SPI */ + void activate() {} + /** Dummy deactivate SPI hardware for software SPI */ + void deactivate() {} + /** Initialize the SPI bus. + * + * \param[in] csPin SD card chip select pin. + */ + void begin(uint8_t csPin) { + m_csPin = csPin; + pinMode(m_csPin, OUTPUT); + digitalWrite(m_csPin, HIGH); + m_spi.begin(); + } + /** Receive a byte. + * + * \return The byte. + */ + uint8_t receive() { + return m_spi.receive(); + } + /** Receive multiple bytes. + * + * \param[out] buf Buffer to receive the data. + * \param[in] n Number of bytes to receive. + * + * \return Zero for no error or nonzero error code. + */ + uint8_t receive(uint8_t* buf, size_t n) { + for (size_t i = 0; i < n; i++) { + buf[i] = receive(); + } + return 0; + } + /** Send a byte. + * + * \param[in] data Byte to send + */ + void send(uint8_t data) { + m_spi.send(data); + } + /** Send multiple bytes. + * + * \param[in] buf Buffer for data to be sent. + * \param[in] n Number of bytes to send. + */ + void send(const uint8_t* buf , size_t n) { + for (size_t i = 0; i < n; i++) { + send(buf[i]); + } + } + /** Set CS low. */ + void select() { + digitalWrite(m_csPin, LOW); + } + /** Save SPISettings. + * + * \param[in] spiSettings SPI speed, mode, and byte order. + */ + void setSpiSettings(SPISettings spiSettings) { + (void)spiSettings; + } + /** Set CS high. */ + void unselect() { + digitalWrite(m_csPin, HIGH); + } + + private: + uint8_t m_csPin; + SoftSPI m_spi; +}; +#endif // ENABLE_SOFTWARE_SPI_CLASS || defined(DOXYGEN) +//------------------------------------------------------------------------------ +// Choose SPI driver for SdFat and SdFatEX classes. +#if USE_STANDARD_SPI_LIBRARY || !SD_HAS_CUSTOM_SPI +/** SdFat uses Arduino library SPI. */ +typedef SdSpiLibDriver SdFatSpiDriver; +#else // USE_STANDARD_SPI_LIBRARY || !SD_HAS_CUSTOM_SPI +/** SdFat uses custom fast SPI. */ +typedef SdSpiAltDriver SdFatSpiDriver; +#endif // USE_STANDARD_SPI_LIBRARY || !SD_HAS_CUSTOM_SPI + +/** typedef for for SdSpiCard class. */ +#if ENABLE_SOFTWARE_SPI_CLASS +// Need virtual driver. +typedef SdSpiBaseDriver SdSpiDriver; +#else // ENABLE_SOFTWARE_SPI_CLASS +// Don't need virtual driver. +typedef SdFatSpiDriver SdSpiDriver; +#endif // ENABLE_SOFTWARE_SPI_CLASS +//============================================================================== +// Use of in-line for AVR to save flash. +#ifdef __AVR__ +//------------------------------------------------------------------------------ +inline void SdSpiAltDriver::begin(uint8_t csPin) { + m_csPin = csPin; + pinMode(m_csPin, OUTPUT); + digitalWrite(m_csPin, HIGH); + SPI.begin(); +} +//------------------------------------------------------------------------------ +inline void SdSpiAltDriver::activate() { + SPI.beginTransaction(m_spiSettings); +} +//------------------------------------------------------------------------------ +inline void SdSpiAltDriver::deactivate() { + SPI.endTransaction(); +} +//------------------------------------------------------------------------------ +inline uint8_t SdSpiAltDriver::receive() { + SPDR = 0XFF; + while (!(SPSR & (1 << SPIF))) {} + return SPDR; +} +//------------------------------------------------------------------------------ +inline uint8_t SdSpiAltDriver::receive(uint8_t* buf, size_t n) { + if (n-- == 0) { + return 0; + } + SPDR = 0XFF; + for (size_t i = 0; i < n; i++) { + while (!(SPSR & (1 << SPIF))) {} + uint8_t b = SPDR; + SPDR = 0XFF; + buf[i] = b; + } + while (!(SPSR & (1 << SPIF))) {} + buf[n] = SPDR; + return 0; +} +//------------------------------------------------------------------------------ +inline void SdSpiAltDriver::send(uint8_t data) { + SPDR = data; + while (!(SPSR & (1 << SPIF))) {} +} +//------------------------------------------------------------------------------ +inline void SdSpiAltDriver::send(const uint8_t* buf , size_t n) { + if (n == 0) { + return; + } + SPDR = buf[0]; + if (n > 1) { + uint8_t b = buf[1]; + size_t i = 2; + while (1) { + while (!(SPSR & (1 << SPIF))) {} + SPDR = b; + if (i == n) { + break; + } + b = buf[i++]; + } + } + while (!(SPSR & (1 << SPIF))) {} +} +#endif // __AVR__ +#endif // SdSpiDriver_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiESP8266.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiESP8266.cpp new file mode 100644 index 0000000..9167446 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiESP8266.cpp @@ -0,0 +1,93 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#if defined(ESP8266) +#include "SdSpiDriver.h" +//------------------------------------------------------------------------------ +/** Initialize the SPI bus. + * + * \param[in] chipSelectPin SD card chip select pin. + */ +void SdSpiAltDriver::begin(uint8_t csPin) { + m_csPin = csPin; + pinMode(m_csPin, OUTPUT); + digitalWrite(m_csPin, HIGH); + SPI.begin(); +} +//------------------------------------------------------------------------------ +/** Set SPI options for access to SD/SDHC cards. + * + */ +void SdSpiAltDriver::activate() { + SPI.beginTransaction(m_spiSettings); +} +//------------------------------------------------------------------------------ +void SdSpiAltDriver::deactivate() { + // Note: endTransaction is an empty function on ESP8266. + SPI.endTransaction(); +} +//------------------------------------------------------------------------------ +/** Receive a byte. + * + * \return The byte. + */ +uint8_t SdSpiAltDriver::receive() { + return SPI.transfer(0XFF); +} +//------------------------------------------------------------------------------ +/** Receive multiple bytes. + * + * \param[out] buf Buffer to receive the data. + * \param[in] n Number of bytes to receive. + * + * \return Zero for no error or nonzero error code. + */ +uint8_t SdSpiAltDriver::receive(uint8_t* buf, size_t n) { + // Works without 32-bit alignment of buf. + SPI.transferBytes(0, buf, n); + return 0; +} +//------------------------------------------------------------------------------ +/** Send a byte. + * + * \param[in] b Byte to send + */ +void SdSpiAltDriver::send(uint8_t b) { + SPI.transfer(b); +} +//------------------------------------------------------------------------------ +/** Send multiple bytes. + * + * \param[in] buf Buffer for data to be sent. + * \param[in] n Number of bytes to send. + */ +void SdSpiAltDriver::send(const uint8_t* buf , size_t n) { + // Adjust to 32-bit alignment. + while ((reinterpret_cast(buf) & 0X3) && n) { + SPI.transfer(*buf++); + n--; + } + SPI.transferBytes(const_cast(buf), 0, n); +} +#endif // defined(ESP8266) diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiParticle.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiParticle.cpp new file mode 100644 index 0000000..59e45c2 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiParticle.cpp @@ -0,0 +1,102 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#if defined(PLATFORM_ID) +#include "SdSpiDriver.h" +static volatile bool SPI_DMA_TransferCompleted = false; +//----------------------------------------------------------------------------- +static void SD_SPI_DMA_TransferComplete_Callback(void) { + SPI_DMA_TransferCompleted = true; +} +//------------------------------------------------------------------------------ +/** Set SPI options for access to SD/SDHC cards. + * + * \param[in] divisor SCK clock divider relative to the APB1 or APB2 clock. + */ +void SdSpiAltDriver::activate() { + m_spi->beginTransaction(m_spiSettings); +} +//------------------------------------------------------------------------------ +/** Initialize the SPI bus. + * + * \param[in] chipSelectPin SD card chip select pin. + */ +void SdSpiAltDriver::begin(uint8_t csPin) { + m_csPin = csPin; + m_spi->begin(); + pinMode(m_csPin, OUTPUT); + digitalWrite(m_csPin, HIGH); +} +//------------------------------------------------------------------------------ +/** + * End SPI transaction. + */ +void SdSpiAltDriver::deactivate() { + m_spi->endTransaction(); +} +//------------------------------------------------------------------------------ +/** Receive a byte. + * + * \return The byte. + */ +uint8_t SdSpiAltDriver::receive() { + return m_spi->transfer(0XFF); +} +//------------------------------------------------------------------------------ +/** Receive multiple bytes. + * + * \param[out] buf Buffer to receive the data. + * \param[in] n Number of bytes to receive. + * + * \return Zero for no error or nonzero error code. + */ +uint8_t SdSpiAltDriver::receive(uint8_t* buf, size_t n) { + SPI_DMA_TransferCompleted = false; + m_spi->transfer(nullptr, buf, n, SD_SPI_DMA_TransferComplete_Callback); + while (!SPI_DMA_TransferCompleted) {} + return 0; +} +//------------------------------------------------------------------------------ +/** Send a byte. + * + * \param[in] b Byte to send + */ +void SdSpiAltDriver::send(uint8_t b) { + m_spi->transfer(b); +} +//------------------------------------------------------------------------------ +/** Send multiple bytes. + * + * \param[in] buf Buffer for data to be sent. + * \param[in] n Number of bytes to send. + */ +void SdSpiAltDriver::send(const uint8_t* buf , size_t n) { + SPI_DMA_TransferCompleted = false; + + m_spi->transfer(const_cast(buf), nullptr, n, + SD_SPI_DMA_TransferComplete_Callback); + + while (!SPI_DMA_TransferCompleted) {} +} +#endif // defined(PLATFORM_ID) diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiSAM3X.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiSAM3X.cpp new file mode 100644 index 0000000..91f8fb5 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiSAM3X.cpp @@ -0,0 +1,218 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#include "SdSpiDriver.h" +#if defined(__SAM3X8E__) || defined(__SAM3X8H__) +/** Use SAM3X DMAC if nonzero */ +#define USE_SAM3X_DMAC 1 +/** Use extra Bus Matrix arbitration fix if nonzero */ +#define USE_SAM3X_BUS_MATRIX_FIX 0 +/** Time in ms for DMA receive timeout */ +#define SAM3X_DMA_TIMEOUT 100 +/** chip select register number */ +#define SPI_CHIP_SEL 3 +/** DMAC receive channel */ +#define SPI_DMAC_RX_CH 1 +/** DMAC transmit channel */ +#define SPI_DMAC_TX_CH 0 +/** DMAC Channel HW Interface Number for SPI TX. */ +#define SPI_TX_IDX 1 +/** DMAC Channel HW Interface Number for SPI RX. */ +#define SPI_RX_IDX 2 +//------------------------------------------------------------------------------ +/** Disable DMA Controller. */ +static void dmac_disable() { + DMAC->DMAC_EN &= (~DMAC_EN_ENABLE); +} +/** Enable DMA Controller. */ +static void dmac_enable() { + DMAC->DMAC_EN = DMAC_EN_ENABLE; +} +/** Disable DMA Channel. */ +static void dmac_channel_disable(uint32_t ul_num) { + DMAC->DMAC_CHDR = DMAC_CHDR_DIS0 << ul_num; +} +/** Enable DMA Channel. */ +static void dmac_channel_enable(uint32_t ul_num) { + DMAC->DMAC_CHER = DMAC_CHER_ENA0 << ul_num; +} +/** Poll for transfer complete. */ +static bool dmac_channel_transfer_done(uint32_t ul_num) { + return (DMAC->DMAC_CHSR & (DMAC_CHSR_ENA0 << ul_num)) ? false : true; +} +//------------------------------------------------------------------------------ +void SdSpiAltDriver::begin(uint8_t csPin) { + m_csPin = csPin; + pinMode(m_csPin, OUTPUT); + digitalWrite(m_csPin, HIGH); +SPI.begin(); +#if USE_SAM3X_DMAC + pmc_enable_periph_clk(ID_DMAC); + dmac_disable(); + DMAC->DMAC_GCFG = DMAC_GCFG_ARB_CFG_FIXED; + dmac_enable(); +#if USE_SAM3X_BUS_MATRIX_FIX + MATRIX->MATRIX_WPMR = 0x4d415400; + MATRIX->MATRIX_MCFG[1] = 1; + MATRIX->MATRIX_MCFG[2] = 1; + MATRIX->MATRIX_SCFG[0] = 0x01000010; + MATRIX->MATRIX_SCFG[1] = 0x01000010; + MATRIX->MATRIX_SCFG[7] = 0x01000010; +#endif // USE_SAM3X_BUS_MATRIX_FIX +#endif // USE_SAM3X_DMAC +} +//------------------------------------------------------------------------------ +// start RX DMA +static void spiDmaRX(uint8_t* dst, uint16_t count) { + dmac_channel_disable(SPI_DMAC_RX_CH); + DMAC->DMAC_CH_NUM[SPI_DMAC_RX_CH].DMAC_SADDR = (uint32_t)&SPI0->SPI_RDR; + DMAC->DMAC_CH_NUM[SPI_DMAC_RX_CH].DMAC_DADDR = (uint32_t)dst; + DMAC->DMAC_CH_NUM[SPI_DMAC_RX_CH].DMAC_DSCR = 0; + DMAC->DMAC_CH_NUM[SPI_DMAC_RX_CH].DMAC_CTRLA = count | + DMAC_CTRLA_SRC_WIDTH_BYTE | DMAC_CTRLA_DST_WIDTH_BYTE; + DMAC->DMAC_CH_NUM[SPI_DMAC_RX_CH].DMAC_CTRLB = DMAC_CTRLB_SRC_DSCR | + DMAC_CTRLB_DST_DSCR | DMAC_CTRLB_FC_PER2MEM_DMA_FC | + DMAC_CTRLB_SRC_INCR_FIXED | DMAC_CTRLB_DST_INCR_INCREMENTING; + DMAC->DMAC_CH_NUM[SPI_DMAC_RX_CH].DMAC_CFG = DMAC_CFG_SRC_PER(SPI_RX_IDX) | + DMAC_CFG_SRC_H2SEL | DMAC_CFG_SOD | DMAC_CFG_FIFOCFG_ASAP_CFG; + dmac_channel_enable(SPI_DMAC_RX_CH); +} +//------------------------------------------------------------------------------ +// start TX DMA +static void spiDmaTX(const uint8_t* src, uint16_t count) { + static uint8_t ff = 0XFF; + uint32_t src_incr = DMAC_CTRLB_SRC_INCR_INCREMENTING; + if (!src) { + src = &ff; + src_incr = DMAC_CTRLB_SRC_INCR_FIXED; + } + dmac_channel_disable(SPI_DMAC_TX_CH); + DMAC->DMAC_CH_NUM[SPI_DMAC_TX_CH].DMAC_SADDR = (uint32_t)src; + DMAC->DMAC_CH_NUM[SPI_DMAC_TX_CH].DMAC_DADDR = (uint32_t)&SPI0->SPI_TDR; + DMAC->DMAC_CH_NUM[SPI_DMAC_TX_CH].DMAC_DSCR = 0; + DMAC->DMAC_CH_NUM[SPI_DMAC_TX_CH].DMAC_CTRLA = count | + DMAC_CTRLA_SRC_WIDTH_BYTE | DMAC_CTRLA_DST_WIDTH_BYTE; + + DMAC->DMAC_CH_NUM[SPI_DMAC_TX_CH].DMAC_CTRLB = DMAC_CTRLB_SRC_DSCR | + DMAC_CTRLB_DST_DSCR | DMAC_CTRLB_FC_MEM2PER_DMA_FC | + src_incr | DMAC_CTRLB_DST_INCR_FIXED; + + DMAC->DMAC_CH_NUM[SPI_DMAC_TX_CH].DMAC_CFG = DMAC_CFG_DST_PER(SPI_TX_IDX) | + DMAC_CFG_DST_H2SEL | DMAC_CFG_SOD | DMAC_CFG_FIFOCFG_ALAP_CFG; + + dmac_channel_enable(SPI_DMAC_TX_CH); +} +//------------------------------------------------------------------------------ +// initialize SPI controller +void SdSpiAltDriver::activate() { + SPI.beginTransaction(m_spiSettings); + + Spi* pSpi = SPI0; + // Save the divisor + uint32_t scbr = pSpi->SPI_CSR[SPI_CHIP_SEL] & 0XFF00; + // Disable SPI + pSpi->SPI_CR = SPI_CR_SPIDIS; + // reset SPI + pSpi->SPI_CR = SPI_CR_SWRST; + // no mode fault detection, set master mode + pSpi->SPI_MR = SPI_PCS(SPI_CHIP_SEL) | SPI_MR_MODFDIS | SPI_MR_MSTR; + // mode 0, 8-bit, + pSpi->SPI_CSR[SPI_CHIP_SEL] = scbr | SPI_CSR_CSAAT | SPI_CSR_NCPHA; + // enable SPI + pSpi->SPI_CR |= SPI_CR_SPIEN; +} +//------------------------------------------------------------------------------ +void SdSpiAltDriver::deactivate() { + SPI.endTransaction(); +} +//------------------------------------------------------------------------------ +static inline uint8_t spiTransfer(uint8_t b) { + Spi* pSpi = SPI0; + + pSpi->SPI_TDR = b; + while ((pSpi->SPI_SR & SPI_SR_RDRF) == 0) {} + b = pSpi->SPI_RDR; + return b; +} +//------------------------------------------------------------------------------ +/** SPI receive a byte */ +uint8_t SdSpiAltDriver::receive() { + return spiTransfer(0XFF); +} +//------------------------------------------------------------------------------ +/** SPI receive multiple bytes */ +uint8_t SdSpiAltDriver::receive(uint8_t* buf, size_t n) { + Spi* pSpi = SPI0; + int rtn = 0; +#if USE_SAM3X_DMAC + // clear overrun error + pSpi->SPI_SR; + + spiDmaRX(buf, n); + spiDmaTX(0, n); + + uint32_t m = millis(); + while (!dmac_channel_transfer_done(SPI_DMAC_RX_CH)) { + if ((millis() - m) > SAM3X_DMA_TIMEOUT) { + dmac_channel_disable(SPI_DMAC_RX_CH); + dmac_channel_disable(SPI_DMAC_TX_CH); + rtn = 2; + break; + } + } + if (pSpi->SPI_SR & SPI_SR_OVRES) { + rtn |= 1; + } +#else // USE_SAM3X_DMAC + for (size_t i = 0; i < n; i++) { + pSpi->SPI_TDR = 0XFF; + while ((pSpi->SPI_SR & SPI_SR_RDRF) == 0) {} + buf[i] = pSpi->SPI_RDR; + } +#endif // USE_SAM3X_DMAC + return rtn; +} +//------------------------------------------------------------------------------ +/** SPI send a byte */ +void SdSpiAltDriver::send(uint8_t b) { + spiTransfer(b); +} +//------------------------------------------------------------------------------ +void SdSpiAltDriver::send(const uint8_t* buf , size_t n) { + Spi* pSpi = SPI0; +#if USE_SAM3X_DMAC + spiDmaTX(buf, n); + while (!dmac_channel_transfer_done(SPI_DMAC_TX_CH)) {} +#else // #if USE_SAM3X_DMAC + while ((pSpi->SPI_SR & SPI_SR_TXEMPTY) == 0) {} + for (size_t i = 0; i < n; i++) { + pSpi->SPI_TDR = buf[i]; + while ((pSpi->SPI_SR & SPI_SR_TDRE) == 0) {} + } +#endif // #if USE_SAM3X_DMAC + while ((pSpi->SPI_SR & SPI_SR_TXEMPTY) == 0) {} + // leave RDR empty + pSpi->SPI_RDR; +} +#endif // defined(__SAM3X8E__) || defined(__SAM3X8H__) diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiSTM32.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiSTM32.cpp new file mode 100644 index 0000000..114c239 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiSTM32.cpp @@ -0,0 +1,105 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#if defined(__STM32F1__) || defined(__STM32F4__) +#include "SdSpiDriver.h" +#if defined(__STM32F1__) +#define USE_STM32_DMA 1 +#elif defined(__STM32F4__) +#define USE_STM32_DMA 1 +#else // defined(__STM32F1__) +#error Unknown STM32 type +#endif // defined(__STM32F1__) +//------------------------------------------------------------------------------ +/** Set SPI options for access to SD/SDHC cards. + * + * \param[in] divisor SCK clock divider relative to the APB1 or APB2 clock. + */ +void SdSpiAltDriver::activate() { + m_spi->beginTransaction(m_spiSettings); +} +//------------------------------------------------------------------------------ +/** Initialize the SPI bus. + * + * \param[in] chipSelectPin SD card chip select pin. + */ +void SdSpiAltDriver::begin(uint8_t csPin) { + m_csPin = csPin; + pinMode(m_csPin, OUTPUT); + digitalWrite(m_csPin, HIGH); + m_spi->begin(); +} +//------------------------------------------------------------------------------ +/** + * End SPI transaction. + */ +void SdSpiAltDriver::deactivate() { + m_spi->endTransaction(); +} +//------------------------------------------------------------------------------ +/** Receive a byte. + * + * \return The byte. + */ +uint8_t SdSpiAltDriver::receive() { + return m_spi->transfer(0XFF); +} +//------------------------------------------------------------------------------ +/** Receive multiple bytes. + * + * \param[out] buf Buffer to receive the data. + * \param[in] n Number of bytes to receive. + * + * \return Zero for no error or nonzero error code. + */ +uint8_t SdSpiAltDriver::receive(uint8_t* buf, size_t n) { +#if USE_STM32_DMA + return m_spi->dmaTransfer(nullptr, buf, n); +#else // USE_STM32_DMA + m_spi->read(buf, n); + return 0; +#endif // USE_STM32_DMA +} +//------------------------------------------------------------------------------ +/** Send a byte. + * + * \param[in] b Byte to send + */ +void SdSpiAltDriver::send(uint8_t b) { + m_spi->transfer(b); +} +//------------------------------------------------------------------------------ +/** Send multiple bytes. + * + * \param[in] buf Buffer for data to be sent. + * \param[in] n Number of bytes to send. + */ +void SdSpiAltDriver::send(const uint8_t* buf , size_t n) { +#if USE_STM32_DMA + m_spi->dmaTransfer(const_cast(buf), nullptr, n); +#else // USE_STM32_DMA + m_spi->write(const_cast(buf), n); +#endif // USE_STM32_DMA +} +#endif // defined(__STM32F1__) || defined(__STM32F4__) diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiTeensy3.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiTeensy3.cpp new file mode 100644 index 0000000..17bb572 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiTeensy3.cpp @@ -0,0 +1,233 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +#include "SdSpiDriver.h" +#if defined(__arm__) && defined(CORE_TEENSY) +// SPI definitions +#include "kinetis.h" + +//------------------------------------------------------------------------------ +void SdSpiAltDriver::activate() { + SPI.beginTransaction(m_spiSettings); +} +//------------------------------------------------------------------------------ +void SdSpiAltDriver::begin(uint8_t chipSelectPin) { + m_csPin = chipSelectPin; + pinMode(m_csPin, OUTPUT); + digitalWrite(m_csPin, HIGH); + SPI.begin(); +} +//------------------------------------------------------------------------------ +void SdSpiAltDriver::deactivate() { + SPI.endTransaction(); +} +//============================================================================== +#ifdef KINETISK + +// use 16-bit frame if SPI_USE_8BIT_FRAME is zero +#define SPI_USE_8BIT_FRAME 0 +// Limit initial fifo to three entries to avoid fifo overrun +#define SPI_INITIAL_FIFO_DEPTH 3 +// define some symbols that are not in mk20dx128.h +#ifndef SPI_SR_RXCTR +#define SPI_SR_RXCTR 0XF0 +#endif // SPI_SR_RXCTR +#ifndef SPI_PUSHR_CONT +#define SPI_PUSHR_CONT 0X80000000 +#endif // SPI_PUSHR_CONT +#ifndef SPI_PUSHR_CTAS +#define SPI_PUSHR_CTAS(n) (((n) & 7) << 28) +#endif // SPI_PUSHR_CTAS +//------------------------------------------------------------------------------ +/** SPI receive a byte */ +uint8_t SdSpiAltDriver::receive() { + SPI0_MCR |= SPI_MCR_CLR_RXF; + SPI0_SR = SPI_SR_TCF; + SPI0_PUSHR = 0xFF; + while (!(SPI0_SR & SPI_SR_TCF)) {} + return SPI0_POPR; +} +//------------------------------------------------------------------------------ +/** SPI receive multiple bytes */ +uint8_t SdSpiAltDriver::receive(uint8_t* buf, size_t n) { + // clear any data in RX FIFO + SPI0_MCR = SPI_MCR_MSTR | SPI_MCR_CLR_RXF | SPI_MCR_PCSIS(0x1F); +#if SPI_USE_8BIT_FRAME + // initial number of bytes to push into TX FIFO + int nf = n < SPI_INITIAL_FIFO_DEPTH ? n : SPI_INITIAL_FIFO_DEPTH; + for (int i = 0; i < nf; i++) { + SPI0_PUSHR = 0XFF; + } + // limit for pushing dummy data into TX FIFO + uint8_t* limit = buf + n - nf; + while (buf < limit) { + while (!(SPI0_SR & SPI_SR_RXCTR)) {} + SPI0_PUSHR = 0XFF; + *buf++ = SPI0_POPR; + } + // limit for rest of RX data + limit += nf; + while (buf < limit) { + while (!(SPI0_SR & SPI_SR_RXCTR)) {} + *buf++ = SPI0_POPR; + } +#else // SPI_USE_8BIT_FRAME + // use 16 bit frame to avoid TD delay between frames + // get one byte if n is odd + if (n & 1) { + *buf++ = receive(); + n--; + } + // initial number of words to push into TX FIFO + int nf = n/2 < SPI_INITIAL_FIFO_DEPTH ? n/2 : SPI_INITIAL_FIFO_DEPTH; + for (int i = 0; i < nf; i++) { + SPI0_PUSHR = SPI_PUSHR_CONT | SPI_PUSHR_CTAS(1) | 0XFFFF; + } + uint8_t* limit = buf + n - 2*nf; + while (buf < limit) { + while (!(SPI0_SR & SPI_SR_RXCTR)) {} + SPI0_PUSHR = SPI_PUSHR_CONT | SPI_PUSHR_CTAS(1) | 0XFFFF; + uint16_t w = SPI0_POPR; + *buf++ = w >> 8; + *buf++ = w & 0XFF; + } + // limit for rest of RX data + limit += 2*nf; + while (buf < limit) { + while (!(SPI0_SR & SPI_SR_RXCTR)) {} + uint16_t w = SPI0_POPR; + *buf++ = w >> 8; + *buf++ = w & 0XFF; + } +#endif // SPI_USE_8BIT_FRAME + return 0; +} +//------------------------------------------------------------------------------ +/** SPI send a byte */ +void SdSpiAltDriver::send(uint8_t b) { + SPI0_MCR |= SPI_MCR_CLR_RXF; + SPI0_SR = SPI_SR_TCF; + SPI0_PUSHR = b; + while (!(SPI0_SR & SPI_SR_TCF)) {} +} +//------------------------------------------------------------------------------ +/** SPI send multiple bytes */ +void SdSpiAltDriver::send(const uint8_t* buf , size_t n) { + // clear any data in RX FIFO + SPI0_MCR = SPI_MCR_MSTR | SPI_MCR_CLR_RXF | SPI_MCR_PCSIS(0x1F); +#if SPI_USE_8BIT_FRAME + // initial number of bytes to push into TX FIFO + int nf = n < SPI_INITIAL_FIFO_DEPTH ? n : SPI_INITIAL_FIFO_DEPTH; + // limit for pushing data into TX fifo + const uint8_t* limit = buf + n; + for (int i = 0; i < nf; i++) { + SPI0_PUSHR = *buf++; + } + // write data to TX FIFO + while (buf < limit) { + while (!(SPI0_SR & SPI_SR_RXCTR)) {} + SPI0_PUSHR = *buf++; + SPI0_POPR; + } + // wait for data to be sent + while (nf) { + while (!(SPI0_SR & SPI_SR_RXCTR)) {} + SPI0_POPR; + nf--; + } +#else // SPI_USE_8BIT_FRAME + // use 16 bit frame to avoid TD delay between frames + // send one byte if n is odd + if (n & 1) { + send(*buf++); + n--; + } + // initial number of words to push into TX FIFO + int nf = n/2 < SPI_INITIAL_FIFO_DEPTH ? n/2 : SPI_INITIAL_FIFO_DEPTH; + // limit for pushing data into TX fifo + const uint8_t* limit = buf + n; + for (int i = 0; i < nf; i++) { + uint16_t w = (*buf++) << 8; + w |= *buf++; + SPI0_PUSHR = SPI_PUSHR_CONT | SPI_PUSHR_CTAS(1) | w; + } + // write data to TX FIFO + while (buf < limit) { + uint16_t w = *buf++ << 8; + w |= *buf++; + while (!(SPI0_SR & SPI_SR_RXCTR)) {} + SPI0_PUSHR = SPI_PUSHR_CONT | SPI_PUSHR_CTAS(1) | w; + SPI0_POPR; + } + // wait for data to be sent + while (nf) { + while (!(SPI0_SR & SPI_SR_RXCTR)) {} + SPI0_POPR; + nf--; + } +#endif // SPI_USE_8BIT_FRAME +} +#else // KINETISK +//============================================================================== +// Use standard SPI library if not KINETISK +//------------------------------------------------------------------------------ +/** Receive a byte. + * + * \return The byte. + */ +uint8_t SdSpiAltDriver::receive() { + return SPI.transfer(0XFF); +} +/** Receive multiple bytes. + * + * \param[out] buf Buffer to receive the data. + * \param[in] n Number of bytes to receive. + * + * \return Zero for no error or nonzero error code. + */ +uint8_t SdSpiAltDriver::receive(uint8_t* buf, size_t n) { + for (size_t i = 0; i < n; i++) { + buf[i] = SPI.transfer(0XFF); + } + return 0; +} +/** Send a byte. + * + * \param[in] b Byte to send + */ +void SdSpiAltDriver::send(uint8_t b) { + SPI.transfer(b); +} +/** Send multiple bytes. + * + * \param[in] buf Buffer for data to be sent. + * \param[in] n Number of bytes to send. + */ +void SdSpiAltDriver::send(const uint8_t* buf , size_t n) { + for (size_t i = 0; i < n; i++) { + SPI.transfer(buf[i]); + } +} +#endif // KINETISK +#endif // defined(__arm__) && defined(CORE_TEENSY) diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SoftSPI.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SoftSPI.h new file mode 100644 index 0000000..fd21e1e --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SoftSPI.h @@ -0,0 +1,167 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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. + */ +/** + * @file + * @brief Software SPI. + * + * @defgroup softSPI Software SPI + * @details Software SPI Template Class. + * @{ + */ + +#ifndef SoftSPI_h +#define SoftSPI_h +#include "DigitalPin.h" +//------------------------------------------------------------------------------ +/** Nop for timing. */ +#define nop asm volatile ("nop\n\t") +//------------------------------------------------------------------------------ +/** Pin Mode for MISO is input.*/ +#define MISO_MODE INPUT +/** Pullups disabled for MISO are disabled. */ +#define MISO_LEVEL false +/** Pin Mode for MOSI is output.*/ +#define MOSI_MODE OUTPUT +/** Pin Mode for SCK is output. */ +#define SCK_MODE OUTPUT +//------------------------------------------------------------------------------ +/** + * @class SoftSPI + * @brief Fast software SPI. + */ +template +class SoftSPI { + public: + //---------------------------------------------------------------------------- + /** Initialize SoftSPI pins. */ + void begin() { + fastPinConfig(MisoPin, MISO_MODE, MISO_LEVEL); + fastPinConfig(MosiPin, MOSI_MODE, !MODE_CPHA(Mode)); + fastPinConfig(SckPin, SCK_MODE, MODE_CPOL(Mode)); + } + //---------------------------------------------------------------------------- + /** Soft SPI receive byte. + * @return Data byte received. + */ + inline __attribute__((always_inline)) + uint8_t receive() { + uint8_t data = 0; + receiveBit(7, &data); + receiveBit(6, &data); + receiveBit(5, &data); + receiveBit(4, &data); + receiveBit(3, &data); + receiveBit(2, &data); + receiveBit(1, &data); + receiveBit(0, &data); + return data; + } + //---------------------------------------------------------------------------- + /** Soft SPI send byte. + * @param[in] data Data byte to send. + */ + inline __attribute__((always_inline)) + void send(uint8_t data) { + sendBit(7, data); + sendBit(6, data); + sendBit(5, data); + sendBit(4, data); + sendBit(3, data); + sendBit(2, data); + sendBit(1, data); + sendBit(0, data); + } + //---------------------------------------------------------------------------- + /** Soft SPI transfer byte. + * @param[in] txData Data byte to send. + * @return Data byte received. + */ + inline __attribute__((always_inline)) + uint8_t transfer(uint8_t txData) { + uint8_t rxData = 0; + transferBit(7, &rxData, txData); + transferBit(6, &rxData, txData); + transferBit(5, &rxData, txData); + transferBit(4, &rxData, txData); + transferBit(3, &rxData, txData); + transferBit(2, &rxData, txData); + transferBit(1, &rxData, txData); + transferBit(0, &rxData, txData); + return rxData; + } + + private: + //---------------------------------------------------------------------------- + inline __attribute__((always_inline)) + bool MODE_CPHA(uint8_t mode) {return (mode & 1) != 0;} + inline __attribute__((always_inline)) + bool MODE_CPOL(uint8_t mode) {return (mode & 2) != 0;} + inline __attribute__((always_inline)) + void receiveBit(uint8_t bit, uint8_t* data) { + if (MODE_CPHA(Mode)) { + fastDigitalWrite(SckPin, !MODE_CPOL(Mode)); + } + nop; + nop; + fastDigitalWrite(SckPin, + MODE_CPHA(Mode) ? MODE_CPOL(Mode) : !MODE_CPOL(Mode)); + if (fastDigitalRead(MisoPin)) *data |= 1 << bit; + if (!MODE_CPHA(Mode)) { + fastDigitalWrite(SckPin, MODE_CPOL(Mode)); + } + } + //---------------------------------------------------------------------------- + inline __attribute__((always_inline)) + void sendBit(uint8_t bit, uint8_t data) { + if (MODE_CPHA(Mode)) { + fastDigitalWrite(SckPin, !MODE_CPOL(Mode)); + } + fastDigitalWrite(MosiPin, data & (1 << bit)); + fastDigitalWrite(SckPin, + MODE_CPHA(Mode) ? MODE_CPOL(Mode) : !MODE_CPOL(Mode)); + nop; + nop; + if (!MODE_CPHA(Mode)) { + fastDigitalWrite(SckPin, MODE_CPOL(Mode)); + } + } + //---------------------------------------------------------------------------- + inline __attribute__((always_inline)) + void transferBit(uint8_t bit, uint8_t* rxData, uint8_t txData) { + if (MODE_CPHA(Mode)) { + fastDigitalWrite(SckPin, !MODE_CPOL(Mode)); + } + fastDigitalWrite(MosiPin, txData & (1 << bit)); + fastDigitalWrite(SckPin, + MODE_CPHA(Mode) ? MODE_CPOL(Mode) : !MODE_CPOL(Mode)); + if (fastDigitalRead(MisoPin)) *rxData |= 1 << bit; + if (!MODE_CPHA(Mode)) { + fastDigitalWrite(SckPin, MODE_CPOL(Mode)); + } + } + //---------------------------------------------------------------------------- +}; +#endif // SoftSPI_h +/** @} */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/AvrDevelopersGpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/AvrDevelopersGpioPinMap.h new file mode 100644 index 0000000..3393173 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/AvrDevelopersGpioPinMap.h @@ -0,0 +1,37 @@ +#ifndef AvrDevelopersGpioPinMap_h +#define AvrDevelopersGpioPinMap_h +static const GpioPinMap_t GpioPinMap[] = { + GPIO_PIN(B, 0), // D0 + GPIO_PIN(B, 1), // D1 + GPIO_PIN(B, 2), // D2 + GPIO_PIN(B, 3), // D3 + GPIO_PIN(B, 4), // D4 + GPIO_PIN(B, 5), // D5 + GPIO_PIN(B, 6), // D6 + GPIO_PIN(B, 7), // D7 + GPIO_PIN(D, 0), // D8 + GPIO_PIN(D, 1), // D9 + GPIO_PIN(D, 2), // D10 + GPIO_PIN(D, 3), // D11 + GPIO_PIN(D, 4), // D12 + GPIO_PIN(D, 5), // D13 + GPIO_PIN(D, 6), // D14 + GPIO_PIN(D, 7), // D15 + GPIO_PIN(C, 0), // D16 + GPIO_PIN(C, 1), // D17 + GPIO_PIN(C, 2), // D18 + GPIO_PIN(C, 3), // D19 + GPIO_PIN(C, 4), // D20 + GPIO_PIN(C, 5), // D21 + GPIO_PIN(C, 6), // D22 + GPIO_PIN(C, 7), // D23 + GPIO_PIN(A, 7), // D24 + GPIO_PIN(A, 6), // D25 + GPIO_PIN(A, 5), // D26 + GPIO_PIN(A, 4), // D27 + GPIO_PIN(A, 3), // D28 + GPIO_PIN(A, 2), // D29 + GPIO_PIN(A, 1), // D30 + GPIO_PIN(A, 0) // D31 +}; +#endif // AvrDevelopersGpioPinMap_h \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/BobuinoGpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/BobuinoGpioPinMap.h new file mode 100644 index 0000000..966786e --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/BobuinoGpioPinMap.h @@ -0,0 +1,37 @@ +#ifndef BobuinoGpioPinMap_h +#define BobuinoGpioPinMap_h +static const GpioPinMap_t GpioPinMap[] = { + GPIO_PIN(B, 0), // D0 + GPIO_PIN(B, 1), // D1 + GPIO_PIN(B, 2), // D2 + GPIO_PIN(B, 3), // D3 + GPIO_PIN(B, 4), // D4 + GPIO_PIN(B, 5), // D5 + GPIO_PIN(B, 6), // D6 + GPIO_PIN(B, 7), // D7 + GPIO_PIN(D, 0), // D8 + GPIO_PIN(D, 1), // D9 + GPIO_PIN(D, 2), // D10 + GPIO_PIN(D, 3), // D11 + GPIO_PIN(D, 4), // D12 + GPIO_PIN(D, 5), // D13 + GPIO_PIN(D, 6), // D14 + GPIO_PIN(D, 7), // D15 + GPIO_PIN(C, 0), // D16 + GPIO_PIN(C, 1), // D17 + GPIO_PIN(C, 2), // D18 + GPIO_PIN(C, 3), // D19 + GPIO_PIN(C, 4), // D20 + GPIO_PIN(C, 5), // D21 + GPIO_PIN(C, 6), // D22 + GPIO_PIN(C, 7), // D23 + GPIO_PIN(A, 0), // D24 + GPIO_PIN(A, 1), // D25 + GPIO_PIN(A, 2), // D26 + GPIO_PIN(A, 3), // D27 + GPIO_PIN(A, 4), // D28 + GPIO_PIN(A, 5), // D29 + GPIO_PIN(A, 6), // D30 + GPIO_PIN(A, 7) // D31 +}; +#endif // BobuinoGpioPinMap_h \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/GpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/GpioPinMap.h new file mode 100644 index 0000000..4abf99c --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/GpioPinMap.h @@ -0,0 +1,45 @@ +#ifndef GpioPinMap_h +#define GpioPinMap_h +#if defined(__AVR_ATmega168__)\ +||defined(__AVR_ATmega168P__)\ +||defined(__AVR_ATmega328P__) +// 168 and 328 Arduinos +#include "UnoGpioPinMap.h" +#elif defined(__AVR_ATmega1280__)\ +|| defined(__AVR_ATmega2560__) +// Mega ADK +#include "MegaGpioPinMap.h" +#elif defined(__AVR_ATmega32U4__) +#ifdef CORE_TEENSY +#include "Teensy2GpioPinMap.h" +#else // CORE_TEENSY +// Leonardo or Yun +#include "LeonardoGpioPinMap.h" +#endif // CORE_TEENSY +#elif defined(__AVR_AT90USB646__)\ +|| defined(__AVR_AT90USB1286__) +// Teensy++ 1.0 & 2.0 +#include "Teensy2ppGpioPinMap.h" +#elif defined(__AVR_ATmega1284P__)\ +|| defined(__AVR_ATmega1284__)\ +|| defined(__AVR_ATmega644P__)\ +|| defined(__AVR_ATmega644__)\ +|| defined(__AVR_ATmega64__)\ +|| defined(__AVR_ATmega32__)\ +|| defined(__AVR_ATmega324__)\ +|| defined(__AVR_ATmega16__) +#ifdef ARDUINO_1284P_AVR_DEVELOPERS +#include "AvrDevelopersGpioPinMap.h" +#elif defined(BOBUINO_PINOUT) || defined(ARDUINO_1284P_BOBUINO) +#include "BobuinoGpioPinMap.h" +#elif defined(ARDUINO_1284P_SLEEPINGBEAUTY) +#include "SleepingBeautyGpioPinMap.h" +#elif defined(STANDARD_PINOUT) || defined(ARDUINO_1284P_STANDARD) +#include "Standard1284GpioPinMap.h" +#else // ARDUINO_1284P_AVR_DEVELOPERS +#error Undefined variant 1284, 644, 324 +#endif // ARDUINO_1284P_AVR_DEVELOPERS +#else // 1284P, 1284, 644 +#error Unknown board type. +#endif // end all boards +#endif // GpioPinMap_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/LeonardoGpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/LeonardoGpioPinMap.h new file mode 100644 index 0000000..bd68d66 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/LeonardoGpioPinMap.h @@ -0,0 +1,35 @@ +#ifndef LeonardoGpioPinMap_h +#define LeonardoGpioPinMap_h +static const GpioPinMap_t GpioPinMap[] = { + GPIO_PIN(D, 2), // D0 + GPIO_PIN(D, 3), // D1 + GPIO_PIN(D, 1), // D2 + GPIO_PIN(D, 0), // D3 + GPIO_PIN(D, 4), // D4 + GPIO_PIN(C, 6), // D5 + GPIO_PIN(D, 7), // D6 + GPIO_PIN(E, 6), // D7 + GPIO_PIN(B, 4), // D8 + GPIO_PIN(B, 5), // D9 + GPIO_PIN(B, 6), // D10 + GPIO_PIN(B, 7), // D11 + GPIO_PIN(D, 6), // D12 + GPIO_PIN(C, 7), // D13 + GPIO_PIN(B, 3), // D14 + GPIO_PIN(B, 1), // D15 + GPIO_PIN(B, 2), // D16 + GPIO_PIN(B, 0), // D17 + GPIO_PIN(F, 7), // D18 + GPIO_PIN(F, 6), // D19 + GPIO_PIN(F, 5), // D20 + GPIO_PIN(F, 4), // D21 + GPIO_PIN(F, 1), // D22 + GPIO_PIN(F, 0), // D23 + GPIO_PIN(D, 4), // D24 + GPIO_PIN(D, 7), // D25 + GPIO_PIN(B, 4), // D26 + GPIO_PIN(B, 5), // D27 + GPIO_PIN(B, 6), // D28 + GPIO_PIN(D, 6) // D29 +}; +#endif // LeonardoGpioPinMap_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/MegaGpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/MegaGpioPinMap.h new file mode 100644 index 0000000..25e7807 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/MegaGpioPinMap.h @@ -0,0 +1,75 @@ +#ifndef MegaGpioPinMap_h +#define MegaGpioPinMap_h +static const GpioPinMap_t GpioPinMap[] = { + GPIO_PIN(E, 0), // D0 + GPIO_PIN(E, 1), // D1 + GPIO_PIN(E, 4), // D2 + GPIO_PIN(E, 5), // D3 + GPIO_PIN(G, 5), // D4 + GPIO_PIN(E, 3), // D5 + GPIO_PIN(H, 3), // D6 + GPIO_PIN(H, 4), // D7 + GPIO_PIN(H, 5), // D8 + GPIO_PIN(H, 6), // D9 + GPIO_PIN(B, 4), // D10 + GPIO_PIN(B, 5), // D11 + GPIO_PIN(B, 6), // D12 + GPIO_PIN(B, 7), // D13 + GPIO_PIN(J, 1), // D14 + GPIO_PIN(J, 0), // D15 + GPIO_PIN(H, 1), // D16 + GPIO_PIN(H, 0), // D17 + GPIO_PIN(D, 3), // D18 + GPIO_PIN(D, 2), // D19 + GPIO_PIN(D, 1), // D20 + GPIO_PIN(D, 0), // D21 + GPIO_PIN(A, 0), // D22 + GPIO_PIN(A, 1), // D23 + GPIO_PIN(A, 2), // D24 + GPIO_PIN(A, 3), // D25 + GPIO_PIN(A, 4), // D26 + GPIO_PIN(A, 5), // D27 + GPIO_PIN(A, 6), // D28 + GPIO_PIN(A, 7), // D29 + GPIO_PIN(C, 7), // D30 + GPIO_PIN(C, 6), // D31 + GPIO_PIN(C, 5), // D32 + GPIO_PIN(C, 4), // D33 + GPIO_PIN(C, 3), // D34 + GPIO_PIN(C, 2), // D35 + GPIO_PIN(C, 1), // D36 + GPIO_PIN(C, 0), // D37 + GPIO_PIN(D, 7), // D38 + GPIO_PIN(G, 2), // D39 + GPIO_PIN(G, 1), // D40 + GPIO_PIN(G, 0), // D41 + GPIO_PIN(L, 7), // D42 + GPIO_PIN(L, 6), // D43 + GPIO_PIN(L, 5), // D44 + GPIO_PIN(L, 4), // D45 + GPIO_PIN(L, 3), // D46 + GPIO_PIN(L, 2), // D47 + GPIO_PIN(L, 1), // D48 + GPIO_PIN(L, 0), // D49 + GPIO_PIN(B, 3), // D50 + GPIO_PIN(B, 2), // D51 + GPIO_PIN(B, 1), // D52 + GPIO_PIN(B, 0), // D53 + GPIO_PIN(F, 0), // D54 + GPIO_PIN(F, 1), // D55 + GPIO_PIN(F, 2), // D56 + GPIO_PIN(F, 3), // D57 + GPIO_PIN(F, 4), // D58 + GPIO_PIN(F, 5), // D59 + GPIO_PIN(F, 6), // D60 + GPIO_PIN(F, 7), // D61 + GPIO_PIN(K, 0), // D62 + GPIO_PIN(K, 1), // D63 + GPIO_PIN(K, 2), // D64 + GPIO_PIN(K, 3), // D65 + GPIO_PIN(K, 4), // D66 + GPIO_PIN(K, 5), // D67 + GPIO_PIN(K, 6), // D68 + GPIO_PIN(K, 7) // D69 +}; +#endif // MegaGpioPinMap_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/SleepingBeautyGpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/SleepingBeautyGpioPinMap.h new file mode 100644 index 0000000..0ac7301 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/SleepingBeautyGpioPinMap.h @@ -0,0 +1,37 @@ +#ifndef SleepingBeautyGpioPinMap_h +#define SleepingBeautyGpioPinMap_h +static const GpioPinMap_t GpioPinMap[] = { + GPIO_PIN(D, 0), // D0 + GPIO_PIN(D, 1), // D1 + GPIO_PIN(D, 2), // D2 + GPIO_PIN(D, 3), // D3 + GPIO_PIN(B, 0), // D4 + GPIO_PIN(B, 1), // D5 + GPIO_PIN(B, 2), // D6 + GPIO_PIN(B, 3), // D7 + GPIO_PIN(D, 6), // D8 + GPIO_PIN(D, 5), // D9 + GPIO_PIN(B, 4), // D10 + GPIO_PIN(B, 5), // D11 + GPIO_PIN(B, 6), // D12 + GPIO_PIN(B, 7), // D13 + GPIO_PIN(C, 7), // D14 + GPIO_PIN(C, 6), // D15 + GPIO_PIN(A, 5), // D16 + GPIO_PIN(A, 4), // D17 + GPIO_PIN(A, 3), // D18 + GPIO_PIN(A, 2), // D19 + GPIO_PIN(A, 1), // D20 + GPIO_PIN(A, 0), // D21 + GPIO_PIN(D, 4), // D22 + GPIO_PIN(D, 7), // D23 + GPIO_PIN(C, 2), // D24 + GPIO_PIN(C, 3), // D25 + GPIO_PIN(C, 4), // D26 + GPIO_PIN(C, 5), // D27 + GPIO_PIN(C, 1), // D28 + GPIO_PIN(C, 0), // D29 + GPIO_PIN(A, 6), // D30 + GPIO_PIN(A, 7) // D31 +}; +#endif // SleepingBeautyGpioPinMap_h \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Standard1284GpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Standard1284GpioPinMap.h new file mode 100644 index 0000000..8a1dba3 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Standard1284GpioPinMap.h @@ -0,0 +1,37 @@ +#ifndef Standard1284GpioPinMap_h +#define Standard1284GpioPinMap_h +static const GpioPinMap_t GpioPinMap[] = { + GPIO_PIN(B, 0), // D0 + GPIO_PIN(B, 1), // D1 + GPIO_PIN(B, 2), // D2 + GPIO_PIN(B, 3), // D3 + GPIO_PIN(B, 4), // D4 + GPIO_PIN(B, 5), // D5 + GPIO_PIN(B, 6), // D6 + GPIO_PIN(B, 7), // D7 + GPIO_PIN(D, 0), // D8 + GPIO_PIN(D, 1), // D9 + GPIO_PIN(D, 2), // D10 + GPIO_PIN(D, 3), // D11 + GPIO_PIN(D, 4), // D12 + GPIO_PIN(D, 5), // D13 + GPIO_PIN(D, 6), // D14 + GPIO_PIN(D, 7), // D15 + GPIO_PIN(C, 0), // D16 + GPIO_PIN(C, 1), // D17 + GPIO_PIN(C, 2), // D18 + GPIO_PIN(C, 3), // D19 + GPIO_PIN(C, 4), // D20 + GPIO_PIN(C, 5), // D21 + GPIO_PIN(C, 6), // D22 + GPIO_PIN(C, 7), // D23 + GPIO_PIN(A, 0), // D24 + GPIO_PIN(A, 1), // D25 + GPIO_PIN(A, 2), // D26 + GPIO_PIN(A, 3), // D27 + GPIO_PIN(A, 4), // D28 + GPIO_PIN(A, 5), // D29 + GPIO_PIN(A, 6), // D30 + GPIO_PIN(A, 7) // D31 +}; +#endif // Standard1284GpioPinMap_h \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Teensy2GpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Teensy2GpioPinMap.h new file mode 100644 index 0000000..3e436c7 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Teensy2GpioPinMap.h @@ -0,0 +1,30 @@ +#ifndef Teensy2GpioPinMap_h +#define Teensy2GpioPinMap_h +static const GpioPinMap_t GpioPinMap[] = { + GPIO_PIN(B, 0), // D0 + GPIO_PIN(B, 1), // D1 + GPIO_PIN(B, 2), // D2 + GPIO_PIN(B, 3), // D3 + GPIO_PIN(B, 7), // D4 + GPIO_PIN(D, 0), // D5 + GPIO_PIN(D, 1), // D6 + GPIO_PIN(D, 2), // D7 + GPIO_PIN(D, 3), // D8 + GPIO_PIN(C, 6), // D9 + GPIO_PIN(C, 7), // D10 + GPIO_PIN(D, 6), // D11 + GPIO_PIN(D, 7), // D12 + GPIO_PIN(B, 4), // D13 + GPIO_PIN(B, 5), // D14 + GPIO_PIN(B, 6), // D15 + GPIO_PIN(F, 7), // D16 + GPIO_PIN(F, 6), // D17 + GPIO_PIN(F, 5), // D18 + GPIO_PIN(F, 4), // D19 + GPIO_PIN(F, 1), // D20 + GPIO_PIN(F, 0), // D21 + GPIO_PIN(D, 4), // D22 + GPIO_PIN(D, 5), // D23 + GPIO_PIN(E, 6), // D24 +}; +#endif // Teensy2GpioPinMap_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Teensy2ppGpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Teensy2ppGpioPinMap.h new file mode 100644 index 0000000..f944991 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Teensy2ppGpioPinMap.h @@ -0,0 +1,51 @@ +#ifndef Teensypp2GpioPinMap_h +#define Teensypp2GpioPinMap_h +static const GpioPinMap_t GpioPinMap[] = { + GPIO_PIN(D, 0), // D0 + GPIO_PIN(D, 1), // D1 + GPIO_PIN(D, 2), // D2 + GPIO_PIN(D, 3), // D3 + GPIO_PIN(D, 4), // D4 + GPIO_PIN(D, 5), // D5 + GPIO_PIN(D, 6), // D6 + GPIO_PIN(D, 7), // D7 + GPIO_PIN(E, 0), // D8 + GPIO_PIN(E, 1), // D9 + GPIO_PIN(C, 0), // D10 + GPIO_PIN(C, 1), // D11 + GPIO_PIN(C, 2), // D12 + GPIO_PIN(C, 3), // D13 + GPIO_PIN(C, 4), // D14 + GPIO_PIN(C, 5), // D15 + GPIO_PIN(C, 6), // D16 + GPIO_PIN(C, 7), // D17 + GPIO_PIN(E, 6), // D18 + GPIO_PIN(E, 7), // D19 + GPIO_PIN(B, 0), // D20 + GPIO_PIN(B, 1), // D21 + GPIO_PIN(B, 2), // D22 + GPIO_PIN(B, 3), // D23 + GPIO_PIN(B, 4), // D24 + GPIO_PIN(B, 5), // D25 + GPIO_PIN(B, 6), // D26 + GPIO_PIN(B, 7), // D27 + GPIO_PIN(A, 0), // D28 + GPIO_PIN(A, 1), // D29 + GPIO_PIN(A, 2), // D30 + GPIO_PIN(A, 3), // D31 + GPIO_PIN(A, 4), // D32 + GPIO_PIN(A, 5), // D33 + GPIO_PIN(A, 6), // D34 + GPIO_PIN(A, 7), // D35 + GPIO_PIN(E, 4), // D36 + GPIO_PIN(E, 5), // D37 + GPIO_PIN(F, 0), // D38 + GPIO_PIN(F, 1), // D39 + GPIO_PIN(F, 2), // D40 + GPIO_PIN(F, 3), // D41 + GPIO_PIN(F, 4), // D42 + GPIO_PIN(F, 5), // D43 + GPIO_PIN(F, 6), // D44 + GPIO_PIN(F, 7), // D45 +}; +#endif // Teensypp2GpioPinMap_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/UnoGpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/UnoGpioPinMap.h new file mode 100644 index 0000000..2ffbb4e --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/UnoGpioPinMap.h @@ -0,0 +1,25 @@ +#ifndef UnoGpioPinMap_h +#define UnoGpioPinMap_h +static const GpioPinMap_t GpioPinMap[] = { + GPIO_PIN(D, 0), // D0 + GPIO_PIN(D, 1), // D1 + GPIO_PIN(D, 2), // D2 + GPIO_PIN(D, 3), // D3 + GPIO_PIN(D, 4), // D4 + GPIO_PIN(D, 5), // D5 + GPIO_PIN(D, 6), // D6 + GPIO_PIN(D, 7), // D7 + GPIO_PIN(B, 0), // D8 + GPIO_PIN(B, 1), // D9 + GPIO_PIN(B, 2), // D10 + GPIO_PIN(B, 3), // D11 + GPIO_PIN(B, 4), // D12 + GPIO_PIN(B, 5), // D13 + GPIO_PIN(C, 0), // D14 + GPIO_PIN(C, 1), // D15 + GPIO_PIN(C, 2), // D16 + GPIO_PIN(C, 3), // D17 + GPIO_PIN(C, 4), // D18 + GPIO_PIN(C, 5) // D19 +}; +#endif // UnoGpioPinMap_h \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SysCall.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SysCall.h new file mode 100644 index 0000000..b8a2e25 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SysCall.h @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 SysCall_h +#define SysCall_h +/** + * \file + * \brief SysCall class + */ +#if defined(ARDUINO) +#include +#include +#elif defined(PLATFORM_ID) // Only defined if a Particle device +#include "application.h" +#else // defined(ARDUINO) +#error "Unknown system" +#endif // defined(ARDUINO) +//------------------------------------------------------------------------------ +#ifdef ESP8266 +// undefine F macro if ESP8266. +#undef F +#endif // ESP8266 +//------------------------------------------------------------------------------ +#ifndef F +/** Define macro for strings stored in flash. */ +#define F(str) (str) +#endif // F +//------------------------------------------------------------------------------ +/** \return the time in milliseconds. */ +inline uint16_t curTimeMS() { + return millis(); +} +//------------------------------------------------------------------------------ +/** + * \class SysCall + * \brief SysCall - Class to wrap system calls. + */ +class SysCall { + public: + /** Halt execution of this thread. */ + static void halt() { + while (1) { + yield(); + } + } + /** Yield to other threads. */ + static void yield(); +}; + +#if defined(ESP8266) +inline void SysCall::yield() { + // Avoid ESP8266 bug + delay(0); +} +#elif defined(ARDUINO) +inline void SysCall::yield() { + // Use the external Arduino yield() function. + ::yield(); +} +#elif defined(PLATFORM_ID) // Only defined if a Particle device +inline void SysCall::yield() { + Particle.process(); +} +#else // ESP8266 +inline void SysCall::yield() {} +#endif // ESP8266 +#endif // SysCall_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/sdios.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/sdios.h new file mode 100644 index 0000000..3a8db59 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/sdios.h @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2011-2018 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * 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 sdios_h +#define sdios_h +/** + * \file + * \brief C++ IO Streams features. + */ +#include "FatLib/fstream.h" +#include "FatLib/ArduinoStream.h" +#endif // sdios_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/Adafruit_ASFcore.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/Adafruit_ASFcore.h new file mode 100644 index 0000000..e69de29 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/README.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/README.md new file mode 100644 index 0000000..8de73c7 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/README.md @@ -0,0 +1,33 @@ +# ASF (Atmel Software Framework) for Arduino Zero / Adafruit Feather M0 (SAMD21) + +Copy of ASF (Atmel Software Framework) excerpts for the SAMD21 processor used in the Arduino Zero / Adafruit Feather M0 boards. +You typically won't use this library directly, instead other libraries will depend on this library and use the code +within it to simplify their implementation. + +All code is taken directly from Atmel's ASF: http://www.atmel.com/tools/avrsoftwareframework.aspx?tab=overview + +The code is copyright Atmel and released by them under the following license: + + 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. The name of Atmel may not be used to endorse or promote products derived from this software without specific + prior written permission. + + 4. This software may only be redistributed and used in connection with an Atmel microcontroller product. + + THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN + NO EVENT SHALL ATMEL 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. diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/clock.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/clock.h new file mode 100644 index 0000000..549e3e9 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/clock.h @@ -0,0 +1,53 @@ +/** + * \file + * + * \brief SAM Clock Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef SYSTEM_CLOCK_H_INCLUDED +#define SYSTEM_CLOCK_H_INCLUDED + +#include "compiler.h" +#include "gclk.h" +#include "clock_feature.h" + +#endif /* SYSTEM_CLOCK_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/clock_feature.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/clock_feature.h new file mode 100644 index 0000000..be63c7c --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/clock_feature.h @@ -0,0 +1,1492 @@ +/** + * \file + * + * \brief SAM Clock Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef SYSTEM_CLOCK_FEATURE_H_INCLUDED +#define SYSTEM_CLOCK_FEATURE_H_INCLUDED + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup asfdoc_sam0_system_clock_group SAM System Clock Management Driver (SYSTEM CLOCK) + * + * This driver for Atmel® | SMART ARM®-based microcontrollers provides an interface for the configuration + * and management of the device's clocking related functions. This includes + * the various clock sources, bus clocks, and generic clocks within the device, + * with functions to manage the enabling, disabling, source selection, and + * prescaling of clocks to various internal peripherals. + * + * The following peripherals are used by this module: + * + * - GCLK (Generic Clock Management) + * - PM (Power Management) + * - SYSCTRL (Clock Source Control) + * + * The following devices can use this module: + * - Atmel | SMART SAM D20/D21 + * - Atmel | SMART SAM R21 + * - Atmel | SMART SAM D10/D11 + * - Atmel | SMART SAM DA0/DA1 + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_system_clock_prerequisites + * - \ref asfdoc_sam0_system_clock_module_overview + * - \ref asfdoc_sam0_system_clock_special_considerations + * - \ref asfdoc_sam0_system_clock_extra_info + * - \ref asfdoc_sam0_system_clock_examples + * - \ref asfdoc_sam0_system_clock_api_overview + * + * + * \section asfdoc_sam0_system_clock_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * + * \section asfdoc_sam0_system_clock_module_overview Module Overview + * The SAM devices contain a sophisticated clocking system, which is designed + * to give the maximum flexibility to the user application. This system allows + * a system designer to tune the performance and power consumption of the device + * in a dynamic manner, to achieve the best trade-off between the two for a + * particular application. + * + * This driver provides a set of functions for the configuration and management + * of the various clock related functionality within the device. + * + * \subsection asfdoc_sam0_system_clock_module_features Driver Feature Macro Definition + * + * + * + * + * + * + * + * + * + *
Driver Feature MacroSupported devices
FEATURE_SYSTEM_CLOCK_DPLLSAMD21, SAMR21, SAMD10, SAMD11, SAMDAx
+ * \note The specific features are only available in the driver when the + * selected device supports those features. + * + * \subsection asfdoc_sam0_system_clock_module_overview_clock_sources Clock Sources + * The SAM devices have a number of master clock source modules, each of + * which being capable of producing a stabilized output frequency, which can then + * be fed into the various peripherals and modules within the device. + * + * Possible clock source modules include internal R/C oscillators, internal + * DFLL modules, as well as external crystal oscillators and/or clock inputs. + * + * \subsection asfdoc_sam0_system_clock_module_overview_cpu_clock CPU / Bus Clocks + * The CPU and AHB/APBx buses are clocked by the same physical clock source + * (referred in this module as the Main Clock), however the APBx buses may + * have additional prescaler division ratios set to give each peripheral bus a + * different clock speed. + * + * The general main clock tree for the CPU and associated buses is shown in + * \ref asfdoc_sam0_system_clock_module_clock_tree "the figure below". + * + * \anchor asfdoc_sam0_system_clock_module_clock_tree + * \dot + * digraph overview { + * rankdir=LR; + * clk_src [label="Clock Sources", shape=none, height=0]; + * node [label="CPU Bus" shape=ellipse] cpu_bus; + * node [label="AHB Bus" shape=ellipse] ahb_bus; + * node [label="APBA Bus" shape=ellipse] apb_a_bus; + * node [label="APBB Bus" shape=ellipse] apb_b_bus; + * node [label="APBC Bus" shape=ellipse] apb_c_bus; + * node [label="Main Bus\nPrescaler" shape=square] main_prescaler; + * node [label="APBA Bus\nPrescaler" shape=square] apb_a_prescaler; + * node [label="APBB Bus\nPrescaler" shape=square] apb_b_prescaler; + * node [label="APBC Bus\nPrescaler" shape=square] apb_c_prescaler; + * node [label="", shape=polygon, sides=4, distortion=0.6, orientation=90, style=filled, fillcolor=black, height=0.9, width=0.2] main_clock_mux; + * + * clk_src -> main_clock_mux; + * main_clock_mux -> main_prescaler; + * main_prescaler -> cpu_bus; + * main_prescaler -> ahb_bus; + * main_prescaler -> apb_a_prescaler; + * main_prescaler -> apb_b_prescaler; + * main_prescaler -> apb_c_prescaler; + * apb_a_prescaler -> apb_a_bus; + * apb_b_prescaler -> apb_b_bus; + * apb_c_prescaler -> apb_c_bus; + * } + * \enddot + * + * \subsection asfdoc_sam0_system_clock_module_overview_clock_masking Clock Masking + * To save power, the input clock to one or more peripherals on the AHB and APBx + * buses can be masked away - when masked, no clock is passed into the module. + * Disabling of clocks of unused modules will prevent all access to the masked + * module, but will reduce the overall device power consumption. + * + * \subsection asfdoc_sam0_system_clock_module_overview_gclk Generic Clocks + * Within the SAM devices there are a number of Generic Clocks; these are used to + * provide clocks to the various peripheral clock domains in the device in a + * standardized manner. One or more master source clocks can be selected as the + * input clock to a Generic Clock Generator, which can prescale down the input + * frequency to a slower rate for use in a peripheral. + * + * Additionally, a number of individually selectable Generic Clock Channels are + * provided, which multiplex and gate the various generator outputs for one or + * more peripherals within the device. This setup allows for a single common + * generator to feed one or more channels, which can then be enabled or disabled + * individually as required. + * + * \anchor asfdoc_sam0_system_clock_module_chain_overview + * \dot + * digraph overview { + * rankdir=LR; + * node [label="Clock\nSource a" shape=square] system_clock_source; + * node [label="Generator 1" shape=square] clock_gen; + * node [label="Channel x" shape=square] clock_chan0; + * node [label="Channel y" shape=square] clock_chan1; + * node [label="Peripheral x" shape=ellipse style=filled fillcolor=lightgray] peripheral0; + * node [label="Peripheral y" shape=ellipse style=filled fillcolor=lightgray] peripheral1; + * + * system_clock_source -> clock_gen; + * clock_gen -> clock_chan0; + * clock_chan0 -> peripheral0; + * clock_gen -> clock_chan1; + * clock_chan1 -> peripheral1; + * } + * \enddot + * + * \subsubsection asfdoc_sam0_system_clock_module_chain_example Clock Chain Example + * An example setup of a complete clock chain within the device is shown in + * \ref asfdoc_sam0_system_clock_module_chain_example_fig "the figure below". + * + * \anchor asfdoc_sam0_system_clock_module_chain_example_fig + * \dot + * digraph overview { + * rankdir=LR; + * node [label="External\nOscillator" shape=square] system_clock_source0; + * node [label="Generator 0" shape=square] clock_gen0; + * node [label="Channel x" shape=square] clock_chan0; + * node [label="Core CPU" shape=ellipse style=filled fillcolor=lightgray] peripheral0; + * + * system_clock_source0 -> clock_gen0; + * clock_gen0 -> clock_chan0; + * clock_chan0 -> peripheral0; + * node [label="8MHz R/C\nOscillator (OSC8M)" shape=square fillcolor=white] system_clock_source1; + * node [label="Generator 1" shape=square] clock_gen1; + * node [label="Channel y" shape=square] clock_chan1; + * node [label="Channel z" shape=square] clock_chan2; + * node [label="SERCOM\nModule" shape=ellipse style=filled fillcolor=lightgray] peripheral1; + * node [label="Timer\nModule" shape=ellipse style=filled fillcolor=lightgray] peripheral2; + * + * system_clock_source1 -> clock_gen1; + * clock_gen1 -> clock_chan1; + * clock_gen1 -> clock_chan2; + * clock_chan1 -> peripheral1; + * clock_chan2 -> peripheral2; + * } + * \enddot + * + * \subsubsection asfdoc_sam0_system_clock_module_overview_gclk_generators Generic Clock Generators + * Each Generic Clock generator within the device can source its input clock + * from one of the provided Source Clocks, and prescale the output for one or + * more Generic Clock Channels in a one-to-many relationship. The generators + * thus allow for several clocks to be generated of different frequencies, + * power usages, and accuracies, which can be turned on and off individually to + * disable the clocks to multiple peripherals as a group. + * + * \subsubsection asfdoc_sam0_system_clock_module_overview_gclk_channels Generic Clock Channels + * To connect a Generic Clock Generator to a peripheral within the + * device, a Generic Clock Channel is used. Each peripheral or + * peripheral group has an associated Generic Clock Channel, which serves as the + * clock input for the peripheral(s). To supply a clock to the peripheral + * module(s), the associated channel must be connected to a running Generic + * Clock Generator and the channel enabled. + * + * \section asfdoc_sam0_system_clock_special_considerations Special Considerations + * + * There are no special considerations for this module. + * + * + * \section asfdoc_sam0_system_clock_extra_info Extra Information + * + * For extra information, see \ref asfdoc_sam0_system_clock_extra. This includes: + * - \ref asfdoc_sam0_system_clock_extra_acronyms + * - \ref asfdoc_sam0_system_clock_extra_dependencies + * - \ref asfdoc_sam0_system_clock_extra_errata + * - \ref asfdoc_sam0_system_clock_extra_history + * + * + * \section asfdoc_sam0_system_clock_examples Examples + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_system_clock_exqsg. + * + * + * \section asfdoc_sam0_system_clock_api_overview API Overview + * @{ + */ + +#include "compiler.h" +#include "gclk.h" + +/** + * \name Driver Feature Definition + * Define system clock features set according to different device family. + * @{ + */ +#if (SAMD21) || (SAMR21) || (SAMD11) || (SAMD10) || (SAMDA1) || defined(__DOXYGEN__) +/** Digital Phase Locked Loop (DPLL) feature support. */ +# define FEATURE_SYSTEM_CLOCK_DPLL +#endif +/*@}*/ + +/** + * \brief Available start-up times for the XOSC32K. + * + * Available external 32KHz oscillator start-up times, as a number of external + * clock cycles. + */ +enum system_xosc32k_startup { + /** Wait zero clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_0, + /** Wait 32 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_32, + /** Wait 2048 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_2048, + /** Wait 4096 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_4096, + /** Wait 16384 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_16384, + /** Wait 32768 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_32768, + /** Wait 65536 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_65536, + /** Wait 131072 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC32K_STARTUP_131072, +}; + +/** + * \brief Available start-up times for the XOSC. + * + * Available external oscillator start-up times, as a number of external clock + * cycles. + */ +enum system_xosc_startup { + /** Wait one clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_1, + /** Wait two clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_2, + /** Wait four clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_4, + /** Wait eight clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_8, + /** Wait 16 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_16, + /** Wait 32 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_32, + /** Wait 64 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_64, + /** Wait 128 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_128, + /** Wait 256 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_256, + /** Wait 512 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_512, + /** Wait 1024 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_1024, + /** Wait 2048 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_2048, + /** Wait 4096 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_4096, + /** Wait 8192 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_8192, + /** Wait 16384 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_16384, + /** Wait 32768 clock cycles until the clock source is considered stable. */ + SYSTEM_XOSC_STARTUP_32768, +}; + +/** + * \brief Available start-up times for the OSC32K. + * + * Available internal 32KHz oscillator start-up times, as a number of internal + * OSC32K clock cycles. + */ +enum system_osc32k_startup { + /** Wait three clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_3, + /** Wait four clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_4, + /** Wait six clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_6, + /** Wait ten clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_10, + /** Wait 18 clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_18, + /** Wait 34 clock cycles until the clock source is considered stable */ + SYSTEM_OSC32K_STARTUP_34, + /** Wait 66 clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_66, + /** Wait 130 clock cycles until the clock source is considered stable. */ + SYSTEM_OSC32K_STARTUP_130, +}; + +/** + * \brief Division prescalers for the internal 8MHz system clock. + * + * Available prescalers for the internal 8MHz (nominal) system clock. + */ +enum system_osc8m_div { + /** Do not divide the 8MHz RC oscillator output. */ + SYSTEM_OSC8M_DIV_1, + /** Divide the 8MHz RC oscillator output by two. */ + SYSTEM_OSC8M_DIV_2, + /** Divide the 8MHz RC oscillator output by four. */ + SYSTEM_OSC8M_DIV_4, + /** Divide the 8MHz RC oscillator output by eight. */ + SYSTEM_OSC8M_DIV_8, +}; + +/** + * \brief Frequency range for the internal 8MHz RC oscillator. + * + * Internal 8MHz RC oscillator frequency range setting + */ +enum system_osc8m_frequency_range { + /** Frequency range 4MHz to 6MHz. */ + SYSTEM_OSC8M_FREQUENCY_RANGE_4_TO_6, + /** Frequency range 6MHz to 8MHz. */ + SYSTEM_OSC8M_FREQUENCY_RANGE_6_TO_8, + /** Frequency range 8MHz to 11MHz. */ + SYSTEM_OSC8M_FREQUENCY_RANGE_8_TO_11, + /** Frequency range 11MHz to 15MHz. */ + SYSTEM_OSC8M_FREQUENCY_RANGE_11_TO_15, +}; + +/** + * \brief Main CPU and APB/AHB bus clock source prescaler values. + * + * Available division ratios for the CPU and APB/AHB bus clocks. + */ +enum system_main_clock_div { + /** Divide Main clock by one. */ + SYSTEM_MAIN_CLOCK_DIV_1, + /** Divide Main clock by two. */ + SYSTEM_MAIN_CLOCK_DIV_2, + /** Divide Main clock by four. */ + SYSTEM_MAIN_CLOCK_DIV_4, + /** Divide Main clock by eight. */ + SYSTEM_MAIN_CLOCK_DIV_8, + /** Divide Main clock by 16. */ + SYSTEM_MAIN_CLOCK_DIV_16, + /** Divide Main clock by 32. */ + SYSTEM_MAIN_CLOCK_DIV_32, + /** Divide Main clock by 64. */ + SYSTEM_MAIN_CLOCK_DIV_64, + /** Divide Main clock by 128. */ + SYSTEM_MAIN_CLOCK_DIV_128, +}; + +/** + * \brief External clock source types. + * + * Available external clock source types. + */ +enum system_clock_external { + /** The external clock source is a crystal oscillator. */ + SYSTEM_CLOCK_EXTERNAL_CRYSTAL, + /** The connected clock source is an external logic level clock signal. */ + SYSTEM_CLOCK_EXTERNAL_CLOCK, +}; + +/** + * \brief Operating modes of the DFLL clock source. + * + * Available operating modes of the DFLL clock source module. + */ +enum system_clock_dfll_loop_mode { + /** The DFLL is operating in open loop mode with no feedback. */ + SYSTEM_CLOCK_DFLL_LOOP_MODE_OPEN, + /** The DFLL is operating in closed loop mode with frequency feedback from + * a low frequency reference clock. + */ + SYSTEM_CLOCK_DFLL_LOOP_MODE_CLOSED = SYSCTRL_DFLLCTRL_MODE, + +#ifdef SYSCTRL_DFLLCTRL_USBCRM + /** The DFLL is operating in USB recovery mode with frequency feedback + * from USB SOF. + */ + SYSTEM_CLOCK_DFLL_LOOP_MODE_USB_RECOVERY = SYSCTRL_DFLLCTRL_USBCRM, +#endif +}; + +/** + * \brief Locking behavior for the DFLL during device wake-up. + * + * DFLL lock behavior modes on device wake-up from sleep. + */ +enum system_clock_dfll_wakeup_lock { + /** Keep DFLL lock when the device wakes from sleep. */ + SYSTEM_CLOCK_DFLL_WAKEUP_LOCK_KEEP, + /** Lose DFLL lock when the devices wakes from sleep. */ + SYSTEM_CLOCK_DFLL_WAKEUP_LOCK_LOSE = SYSCTRL_DFLLCTRL_LLAW, +}; + +/** + * \brief Fine tracking behavior for the DFLL once a lock has been acquired. + * + * DFLL fine tracking behavior modes after a lock has been acquired. + */ +enum system_clock_dfll_stable_tracking { + /** Keep tracking after the DFLL has gotten a fine lock. */ + SYSTEM_CLOCK_DFLL_STABLE_TRACKING_TRACK_AFTER_LOCK, + /** Stop tracking after the DFLL has gotten a fine lock. */ + SYSTEM_CLOCK_DFLL_STABLE_TRACKING_FIX_AFTER_LOCK = SYSCTRL_DFLLCTRL_STABLE, +}; + +/** + * \brief Chill-cycle behavior of the DFLL module. + * + * DFLL chill-cycle behavior modes of the DFLL module. A chill cycle is a period + * of time when the DFLL output frequency is not measured by the unit, to allow + * the output to stabilize after a change in the input clock source. + */ +enum system_clock_dfll_chill_cycle { + /** Enable a chill cycle, where the DFLL output frequency is not measured. */ + SYSTEM_CLOCK_DFLL_CHILL_CYCLE_ENABLE, + /** Disable a chill cycle, where the DFLL output frequency is not measured. */ + SYSTEM_CLOCK_DFLL_CHILL_CYCLE_DISABLE = SYSCTRL_DFLLCTRL_CCDIS, +}; + +/** + * \brief QuickLock settings for the DFLL module. + * + * DFLL QuickLock settings for the DFLL module, to allow for a faster lock of + * the DFLL output frequency at the expense of accuracy. + */ +enum system_clock_dfll_quick_lock { + /** Enable the QuickLock feature for looser lock requirements on the DFLL. */ + SYSTEM_CLOCK_DFLL_QUICK_LOCK_ENABLE, + /** Disable the QuickLock feature for strict lock requirements on the DFLL. */ + SYSTEM_CLOCK_DFLL_QUICK_LOCK_DISABLE = SYSCTRL_DFLLCTRL_QLDIS, +}; + +/** + * \brief Available clock sources in the system. + * + * Clock sources available to the GCLK generators. + */ +enum system_clock_source { + /** Internal 8MHz RC oscillator. */ + SYSTEM_CLOCK_SOURCE_OSC8M = GCLK_SOURCE_OSC8M, + /** Internal 32KHz RC oscillator. */ + SYSTEM_CLOCK_SOURCE_OSC32K = GCLK_SOURCE_OSC32K, + /** External oscillator. */ + SYSTEM_CLOCK_SOURCE_XOSC = GCLK_SOURCE_XOSC , + /** External 32KHz oscillator. */ + SYSTEM_CLOCK_SOURCE_XOSC32K = GCLK_SOURCE_XOSC32K, + /** Digital Frequency Locked Loop (DFLL). */ + SYSTEM_CLOCK_SOURCE_DFLL = GCLK_SOURCE_DFLL48M, + /** Internal Ultra Low Power 32KHz oscillator. */ + SYSTEM_CLOCK_SOURCE_ULP32K = GCLK_SOURCE_OSCULP32K, + /** Generator input pad. */ + SYSTEM_CLOCK_SOURCE_GCLKIN = GCLK_SOURCE_GCLKIN, + /** Generic clock generator one output. */ + SYSTEM_CLOCK_SOURCE_GCLKGEN1 = GCLK_SOURCE_GCLKGEN1, +#ifdef FEATURE_SYSTEM_CLOCK_DPLL + /** Digital Phase Locked Loop (DPLL). + * Check \c FEATURE_SYSTEM_CLOCK_DPLL for which device support it. + */ + SYSTEM_CLOCK_SOURCE_DPLL = GCLK_SOURCE_FDPLL, +#endif +}; + +/** + * \brief List of APB peripheral buses. + * + * Available bus clock domains on the APB bus. + */ +enum system_clock_apb_bus { + /** Peripheral bus A on the APB bus. */ + SYSTEM_CLOCK_APB_APBA, + /** Peripheral bus B on the APB bus. */ + SYSTEM_CLOCK_APB_APBB, + /** Peripheral bus C on the APB bus. */ + SYSTEM_CLOCK_APB_APBC, +}; + +/** + * \brief Configuration structure for XOSC. + * + * External oscillator clock configuration structure. + */ +struct system_clock_source_xosc_config { + /** External clock type. */ + enum system_clock_external external_clock; + /** Crystal oscillator start-up time. */ + enum system_xosc_startup startup_time; + /** Enable automatic amplitude gain control. */ + bool auto_gain_control; + /** External clock/crystal frequency. */ + uint32_t frequency; + /** Keep the XOSC enabled in standby sleep mode. */ + bool run_in_standby; + /** Run On Demand. If this is set the XOSC won't run + * until requested by a peripheral. */ + bool on_demand; +}; + +/** + * \brief Configuration structure for XOSC32K. + * + * External 32KHz oscillator clock configuration structure. + */ +struct system_clock_source_xosc32k_config { + /** External clock type. */ + enum system_clock_external external_clock; + /** Crystal oscillator start-up time. */ + enum system_xosc32k_startup startup_time; + /** Enable automatic amplitude control. */ + bool auto_gain_control; + /** Enable 1KHz output. */ + bool enable_1khz_output; + /** Enable 32KHz output. */ + bool enable_32khz_output; + /** External clock/crystal frequency. */ + uint32_t frequency; + /** Keep the XOSC32K enabled in standby sleep mode. */ + bool run_in_standby; + /** Run On Demand. If this is set the XOSC32K won't run + * until requested by a peripheral. */ + bool on_demand; + /** Lock configuration after it has been written, + * a device reset will release the lock. */ + bool write_once; +}; + +/** + * \brief Configuration structure for OSC8M. + * + * Internal 8MHz (nominal) oscillator configuration structure. + */ +struct system_clock_source_osc8m_config { + /** Internal 8MHz RC oscillator prescaler. */ + enum system_osc8m_div prescaler; + /** Keep the OSC8M enabled in standby sleep mode. */ + bool run_in_standby; + /** Run On Demand. If this is set the OSC8M won't run + * until requested by a peripheral. */ + bool on_demand; +}; + +/** + * \brief Configuration structure for OSC32K. + * + * Internal 32KHz (nominal) oscillator configuration structure. + */ +struct system_clock_source_osc32k_config { + /** Startup time. */ + enum system_osc32k_startup startup_time; + /** Enable 1KHz output. */ + bool enable_1khz_output; + /** Enable 32KHz output. */ + bool enable_32khz_output; + /** Keep the OSC32K enabled in standby sleep mode. */ + bool run_in_standby; + /** Run On Demand. If this is set the OSC32K won't run + * until requested by a peripheral. */ + bool on_demand; + /** Lock configuration after it has been written, + * a device reset will release the lock. */ + bool write_once; +}; + +/** + * \brief Configuration structure for DFLL. + * + * DFLL oscillator configuration structure. + */ +struct system_clock_source_dfll_config { + /** Loop mode. */ + enum system_clock_dfll_loop_mode loop_mode; + /** Run On Demand. If this is set the DFLL won't run + * until requested by a peripheral. */ + bool on_demand; + /** Enable Quick Lock. */ + enum system_clock_dfll_quick_lock quick_lock; + /** Enable Chill Cycle. */ + enum system_clock_dfll_chill_cycle chill_cycle; + /** DFLL lock state on wakeup. */ + enum system_clock_dfll_wakeup_lock wakeup_lock; + /** DFLL tracking after fine lock. */ + enum system_clock_dfll_stable_tracking stable_tracking; + /** Coarse calibration value (Open loop mode). */ + uint8_t coarse_value; + /** Fine calibration value (Open loop mode). */ + uint16_t fine_value; + /** Coarse adjustment maximum step size (Closed loop mode). */ + uint8_t coarse_max_step; + /** Fine adjustment maximum step size (Closed loop mode). */ + uint16_t fine_max_step; + /** DFLL multiply factor (Closed loop mode. */ + uint16_t multiply_factor; +}; + +/** + * \name External Oscillator Management + * @{ + */ + +/** + * \brief Retrieve the default configuration for XOSC. + * + * Fills a configuration structure with the default configuration for an + * external oscillator module: + * - External Crystal + * - Start-up time of 16384 external clock cycles + * - Automatic crystal gain control mode enabled + * - Frequency of 12MHz + * - Don't run in STANDBY sleep mode + * - Run only when requested by peripheral (on demand) + * + * \param[out] config Configuration structure to fill with default values + */ +static inline void system_clock_source_xosc_get_config_defaults( + struct system_clock_source_xosc_config *const config) +{ + Assert(config); + + config->external_clock = SYSTEM_CLOCK_EXTERNAL_CRYSTAL; + config->startup_time = SYSTEM_XOSC_STARTUP_16384; + config->auto_gain_control = true; + config->frequency = 12000000UL; + config->run_in_standby = false; + config->on_demand = true; +} + +void system_clock_source_xosc_set_config( + struct system_clock_source_xosc_config *const config); + +/** + * @} + */ + + +/** + * \name External 32KHz Oscillator Management + * @{ + */ + +/** + * \brief Retrieve the default configuration for XOSC32K. + * + * Fills a configuration structure with the default configuration for an + * external 32KHz oscillator module: + * - External Crystal + * - Start-up time of 16384 external clock cycles + * - Automatic crystal gain control mode disabled + * - Frequency of 32.768KHz + * - 1KHz clock output disabled + * - 32KHz clock output enabled + * - Don't run in STANDBY sleep mode + * - Run only when requested by peripheral (on demand) + * - Don't lock registers after configuration has been written + * + * \param[out] config Configuration structure to fill with default values + */ +static inline void system_clock_source_xosc32k_get_config_defaults( + struct system_clock_source_xosc32k_config *const config) +{ + Assert(config); + + config->external_clock = SYSTEM_CLOCK_EXTERNAL_CRYSTAL; + config->startup_time = SYSTEM_XOSC32K_STARTUP_16384; + config->auto_gain_control = false; + config->frequency = 32768UL; + config->enable_1khz_output = false; + config->enable_32khz_output = true; + config->run_in_standby = false; + config->on_demand = true; + config->write_once = false; +} + +void system_clock_source_xosc32k_set_config( + struct system_clock_source_xosc32k_config *const config); +/** + * @} + */ + + +/** + * \name Internal 32KHz Oscillator Management + * @{ + */ + +/** + * \brief Retrieve the default configuration for OSC32K. + * + * Fills a configuration structure with the default configuration for an + * internal 32KHz oscillator module: + * - 1KHz clock output enabled + * - 32KHz clock output enabled + * - Don't run in STANDBY sleep mode + * - Run only when requested by peripheral (on demand) + * - Set startup time to 130 cycles + * - Don't lock registers after configuration has been written + * + * \param[out] config Configuration structure to fill with default values + */ +static inline void system_clock_source_osc32k_get_config_defaults( + struct system_clock_source_osc32k_config *const config) +{ + Assert(config); + + config->enable_1khz_output = true; + config->enable_32khz_output = true; + config->run_in_standby = false; + config->on_demand = true; + config->startup_time = SYSTEM_OSC32K_STARTUP_130; + config->write_once = false; +} + +void system_clock_source_osc32k_set_config( + struct system_clock_source_osc32k_config *const config); + +/** + * @} + */ + + +/** + * \name Internal 8MHz Oscillator Management + * @{ + */ + +/** + * \brief Retrieve the default configuration for OSC8M. + * + * Fills a configuration structure with the default configuration for an + * internal 8MHz (nominal) oscillator module: + * - Clock output frequency divided by a factor of eight + * - Don't run in STANDBY sleep mode + * - Run only when requested by peripheral (on demand) + * + * \param[out] config Configuration structure to fill with default values + */ +static inline void system_clock_source_osc8m_get_config_defaults( + struct system_clock_source_osc8m_config *const config) +{ + Assert(config); + + config->prescaler = SYSTEM_OSC8M_DIV_8; + config->run_in_standby = false; + config->on_demand = true; +} + +void system_clock_source_osc8m_set_config( + struct system_clock_source_osc8m_config *const config); + +/** + * @} + */ + + +/** + * \name Internal DFLL Management + * @{ + */ + +/** + * \brief Retrieve the default configuration for DFLL. + * + * Fills a configuration structure with the default configuration for a + * DFLL oscillator module: + * - Open loop mode + * - QuickLock mode enabled + * - Chill cycle enabled + * - Output frequency lock maintained during device wake-up + * - Continuous tracking of the output frequency + * - Default tracking values at the mid-points for both coarse and fine + * tracking parameters + * - Don't run in STANDBY sleep mode + * - Run only when requested by peripheral (on demand) + * + * \param[out] config Configuration structure to fill with default values + */ +static inline void system_clock_source_dfll_get_config_defaults( + struct system_clock_source_dfll_config *const config) +{ + Assert(config); + + config->loop_mode = SYSTEM_CLOCK_DFLL_LOOP_MODE_OPEN; + config->quick_lock = SYSTEM_CLOCK_DFLL_QUICK_LOCK_ENABLE; + config->chill_cycle = SYSTEM_CLOCK_DFLL_CHILL_CYCLE_ENABLE; + config->wakeup_lock = SYSTEM_CLOCK_DFLL_WAKEUP_LOCK_KEEP; + config->stable_tracking = SYSTEM_CLOCK_DFLL_STABLE_TRACKING_TRACK_AFTER_LOCK; + config->on_demand = true; + + /* Open loop mode calibration value */ + config->coarse_value = 0x1f / 4; /* Midpoint */ + config->fine_value = 0xff / 4; /* Midpoint */ + + /* Closed loop mode */ + config->coarse_max_step = 1; + config->fine_max_step = 1; + config->multiply_factor = 6; /* Multiply 8MHz by 6 to get 48MHz */ +} + +void system_clock_source_dfll_set_config( + struct system_clock_source_dfll_config *const config); + +/** + * @} + */ + +/** + * \name Clock Source Management + * @{ + */ +enum status_code system_clock_source_write_calibration( + const enum system_clock_source system_clock_source, + const uint16_t calibration_value, + const uint8_t freq_range); + +enum status_code system_clock_source_enable( + const enum system_clock_source system_clock_source); + +enum status_code system_clock_source_disable( + const enum system_clock_source clk_source); + +bool system_clock_source_is_ready( + const enum system_clock_source clk_source); + +uint32_t system_clock_source_get_hz( + const enum system_clock_source clk_source); + +/** + * @} + */ + +/** + * \name Main Clock Management + * @{ + */ + +/** + * \brief Set main CPU clock divider. + * + * Sets the clock divider used on the main clock to provide the CPU clock. + * + * \param[in] divider CPU clock divider to set + */ +static inline void system_cpu_clock_set_divider( + const enum system_main_clock_div divider) +{ + Assert(((uint32_t)divider & PM_CPUSEL_CPUDIV_Msk) == divider); + PM->CPUSEL.reg = (uint32_t)divider; +} + +/** + * \brief Retrieves the current frequency of the CPU core. + * + * Retrieves the operating frequency of the CPU core, obtained from the main + * generic clock and the set CPU bus divider. + * + * \return Current CPU frequency in Hz. + */ +static inline uint32_t system_cpu_clock_get_hz(void) +{ + return (system_gclk_gen_get_hz(GCLK_GENERATOR_0) >> PM->CPUSEL.reg); +} + +/** + * \brief Set APBx clock divider. + * + * Set the clock divider used on the main clock to provide the clock for the + * given APBx bus. + * + * \param[in] divider APBx bus divider to set + * \param[in] bus APBx bus to set divider + * + * \returns Status of the clock division change operation. + * + * \retval STATUS_ERR_INVALID_ARG Invalid bus ID was given + * \retval STATUS_OK The APBx clock was set successfully + */ +static inline enum status_code system_apb_clock_set_divider( + const enum system_clock_apb_bus bus, + const enum system_main_clock_div divider) +{ + switch (bus) { + case SYSTEM_CLOCK_APB_APBA: + PM->APBASEL.reg = (uint32_t)divider; + break; + case SYSTEM_CLOCK_APB_APBB: + PM->APBBSEL.reg = (uint32_t)divider; + break; + case SYSTEM_CLOCK_APB_APBC: + PM->APBCSEL.reg = (uint32_t)divider; + break; + default: + Assert(false); + return STATUS_ERR_INVALID_ARG; + } + + return STATUS_OK; +} + +/** + * \brief Retrieves the current frequency of a ABPx. + * + * Retrieves the operating frequency of an APBx bus, obtained from the main + * generic clock and the set APBx bus divider. + * + * \return Current APBx bus frequency in Hz. + */ +static inline uint32_t system_apb_clock_get_hz( + const enum system_clock_apb_bus bus) +{ + uint16_t bus_divider = 0; + + switch (bus) { + case SYSTEM_CLOCK_APB_APBA: + bus_divider = PM->APBASEL.reg; + break; + case SYSTEM_CLOCK_APB_APBB: + bus_divider = PM->APBBSEL.reg; + break; + case SYSTEM_CLOCK_APB_APBC: + bus_divider = PM->APBCSEL.reg; + break; + default: + Assert(false); + return 0; + } + + return (system_gclk_gen_get_hz(GCLK_GENERATOR_0) >> bus_divider); +} + + +/** + * @} + */ + +/** + * \name Bus Clock Masking + * @{ + */ + +/** + * \brief Set bits in the clock mask for the AHB bus. + * + * This function will set bits in the clock mask for the AHB bus. + * Any bits set to 1 will enable that clock, 0 bits in the mask + * will be ignored. + * + * \param[in] ahb_mask AHB clock mask to enable + */ +static inline void system_ahb_clock_set_mask( + const uint32_t ahb_mask) +{ + PM->AHBMASK.reg |= ahb_mask; +} + +/** + * \brief Clear bits in the clock mask for the AHB bus. + * + * This function will clear bits in the clock mask for the AHB bus. + * Any bits set to 1 will disable that clock, 0 bits in the mask + * will be ignored. + * + * \param[in] ahb_mask AHB clock mask to disable + */ +static inline void system_ahb_clock_clear_mask( + const uint32_t ahb_mask) +{ + PM->AHBMASK.reg &= ~ahb_mask; +} + +/** + * \brief Set bits in the clock mask for an APBx bus. + * + * This function will set bits in the clock mask for an APBx bus. + * Any bits set to 1 will enable the corresponding module clock, zero bits in + * the mask will be ignored. + * + * \param[in] mask APBx clock mask, a \c SYSTEM_CLOCK_APB_APBx constant from + * the device header files + * \param[in] bus Bus to set clock mask bits for, a mask of \c PM_APBxMASK_* + * constants from the device header files + * + * \returns Status indicating the result of the clock mask change operation. + * + * \retval STATUS_ERR_INVALID_ARG Invalid bus given + * \retval STATUS_OK The clock mask was set successfully + */ +static inline enum status_code system_apb_clock_set_mask( + const enum system_clock_apb_bus bus, + const uint32_t mask) +{ + switch (bus) { + case SYSTEM_CLOCK_APB_APBA: + PM->APBAMASK.reg |= mask; + break; + + case SYSTEM_CLOCK_APB_APBB: + PM->APBBMASK.reg |= mask; + break; + + case SYSTEM_CLOCK_APB_APBC: + PM->APBCMASK.reg |= mask; + break; + + default: + Assert(false); + return STATUS_ERR_INVALID_ARG; + + } + + return STATUS_OK; +} + +/** + * \brief Clear bits in the clock mask for an APBx bus. + * + * This function will clear bits in the clock mask for an APBx bus. + * Any bits set to 1 will disable the corresponding module clock, zero bits in + * the mask will be ignored. + * + * \param[in] mask APBx clock mask, a \c SYSTEM_CLOCK_APB_APBx constant from + * the device header files + * \param[in] bus Bus to clear clock mask bits + * + * \returns Status indicating the result of the clock mask change operation. + * + * \retval STATUS_ERR_INVALID_ARG Invalid bus ID was given + * \retval STATUS_OK The clock mask was changed successfully + */ +static inline enum status_code system_apb_clock_clear_mask( + const enum system_clock_apb_bus bus, + const uint32_t mask) +{ + switch (bus) { + case SYSTEM_CLOCK_APB_APBA: + PM->APBAMASK.reg &= ~mask; + break; + + case SYSTEM_CLOCK_APB_APBB: + PM->APBBMASK.reg &= ~mask; + break; + + case SYSTEM_CLOCK_APB_APBC: + PM->APBCMASK.reg &= ~mask; + break; + + default: + Assert(false); + return STATUS_ERR_INVALID_ARG; + } + + return STATUS_OK; +} + +/** + * @} + */ + +#ifdef FEATURE_SYSTEM_CLOCK_DPLL +/** + * \brief Reference clock source of the DPLL module. + */ +enum system_clock_source_dpll_reference_clock { + /** Select XOSC32K as clock reference. */ + SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_XOSC32K, + /** Select XOSC as clock reference. */ + SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_XOSC, + /** Select GCLK as clock reference. */ + SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_GCLK, +}; + +/** + * \brief Lock time-out value of the DPLL module. + */ +enum system_clock_source_dpll_lock_time { + /** Set no time-out as default. */ + SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_DEFAULT, + /** Set time-out if no lock within 8ms. */ + SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_8MS = 0x04, + /** Set time-out if no lock within 9ms. */ + SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_9MS, + /** Set time-out if no lock within 10ms. */ + SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_10MS, + /** Set time-out if no lock within 11ms. */ + SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_11MS, +}; + +/** + * \brief Filter type of the DPLL module. + */ +enum system_clock_source_dpll_filter { + /** Default filter mode. */ + SYSTEM_CLOCK_SOURCE_DPLL_FILTER_DEFAULT, + /** Low bandwidth filter. */ + SYSTEM_CLOCK_SOURCE_DPLL_FILTER_LOW_BANDWIDTH_FILTER, + /** High bandwidth filter. */ + SYSTEM_CLOCK_SOURCE_DPLL_FILTER_HIGH_BANDWIDTH_FILTER, + /** High damping filter. */ + SYSTEM_CLOCK_SOURCE_DPLL_FILTER_HIGH_DAMPING_FILTER, +}; + +/** + * \brief Configuration structure for DPLL. + * + * DPLL oscillator configuration structure. + */ +struct system_clock_source_dpll_config { + /** Run On Demand. If this is set the DPLL won't run + * until requested by a peripheral. */ + bool on_demand; + /** Keep the DPLL enabled in standby sleep mode. */ + bool run_in_standby; + /** Bypass lock signal. */ + bool lock_bypass; + /** Wake up fast. If this is set DPLL output clock is enabled after + * the startup time. */ + bool wake_up_fast; + /** Enable low power mode. */ + bool low_power_enable; + + /** Output frequency of the clock. */ + uint32_t output_frequency; + /** Reference frequency of the clock. */ + uint32_t reference_frequency; + /** Devider of reference clock. */ + uint16_t reference_divider; + + /** Filter type of the DPLL module. */ + enum system_clock_source_dpll_filter filter; + /** Lock time-out value of the DPLL module. */ + enum system_clock_source_dpll_lock_time lock_time; + /** Reference clock source of the DPLL module. */ + enum system_clock_source_dpll_reference_clock reference_clock; +}; + +/** + * \name Internal DPLL Management + * @{ + */ + +/** + * \brief Retrieve the default configuration for DPLL. + * + * Fills a configuration structure with the default configuration for a + * DPLL oscillator module: + * - Run only when requested by peripheral (on demand) + * - Don't run in STANDBY sleep mode + * - Lock bypass disabled + * - Fast wake up disabled + * - Low power mode disabled + * - Output frequency is 48MHz + * - Reference clock frequency is 32768Hz + * - Not divide reference clock + * - Select REF0 as reference clock + * - Set lock time to default mode + * - Use default filter + * + * \param[out] config Configuration structure to fill with default values + */ +static inline void system_clock_source_dpll_get_config_defaults( + struct system_clock_source_dpll_config *const config) +{ + config->on_demand = true; + config->run_in_standby = false; + config->lock_bypass = false; + config->wake_up_fast = false; + config->low_power_enable = false; + + config->output_frequency = 48000000; + config->reference_frequency = 32768; + config->reference_divider = 1; + config->reference_clock = SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_XOSC32K; + + config->lock_time = SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_DEFAULT; + config->filter = SYSTEM_CLOCK_SOURCE_DPLL_FILTER_DEFAULT; +}; + +void system_clock_source_dpll_set_config( + struct system_clock_source_dpll_config *const config); + +/* @} */ +#endif + +/** + * \name System Clock Initialization + * @{ + */ + +void system_clock_init(void); + +/** + * @} + */ + +/** + * \name System Flash Wait States + * @{ + */ + +/** + * \brief Set flash controller wait states. + * + * Will set the number of wait states that are used by the onboard + * flash memory. The number of wait states depend on both device + * supply voltage and CPU speed. The required number of wait states + * can be found in the electrical characteristics of the device. + * + * \param[in] wait_states Number of wait states to use for internal flash + */ +static inline void system_flash_set_waitstates(uint8_t wait_states) +{ + Assert(NVMCTRL_CTRLB_RWS((uint32_t)wait_states) == + ((uint32_t)wait_states << NVMCTRL_CTRLB_RWS_Pos)); + + NVMCTRL->CTRLB.bit.RWS = wait_states; +} +/** + * @} + */ + +/** + * @} + */ + +/** + * \page asfdoc_sam0_system_clock_extra Extra Information for SYSTEM CLOCK Driver + * + * \section asfdoc_sam0_system_clock_extra_acronyms Acronyms + * Below is a table listing the acronyms used in this module, along with their + * intended meanings. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
AcronymDescription
DFLLDigital Frequency Locked Loop
MUXMultiplexer
OSC32KInternal 32KHz Oscillator
OSC8MInternal 8MHz Oscillator
PLLPhase Locked Loop
OSCOscillator
XOSCExternal Oscillator
XOSC32KExternal 32KHz Oscillator
AHBAdvanced High-performance Bus
APBAdvanced Peripheral Bus
DPLLDigital Phase Locked Loop
+ * + * + * \section asfdoc_sam0_system_clock_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - None + * + * + * \section asfdoc_sam0_system_clock_extra_errata Errata + * + * - This driver implements experimental workaround for errata 9905 + * + * "The DFLL clock must be requested before being configured otherwise a + * write access to a DFLL register can freeze the device." + * This driver will enable and configure the DFLL before the ONDEMAND bit is set. + * + * + * \section asfdoc_sam0_system_clock_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Changelog
+ * \li Corrected OSC32K startup time definitions + * \li Support locking of OSC32K and XOSC32K config register (default: false) + * \li Added DPLL support, functions added: + * \c system_clock_source_dpll_get_config_defaults() and + * \c system_clock_source_dpll_set_config() + * \li Moved gclk channel locking feature out of the config struct + * functions added: + * \c system_gclk_chan_lock(), + * \c system_gclk_chan_is_locked() + * \c system_gclk_chan_is_enabled() and + * \c system_gclk_gen_is_enabled() + *
Fixed \c system_gclk_chan_disable() deadlocking if a channel is enabled + * and configured to a failed/not running clock generator
+ * \li Changed default value for CONF_CLOCK_DFLL_ON_DEMAND from \c true to \c false + * \li Fixed system_flash_set_waitstates() failing with an assertion + * if an odd number of wait states provided + *
+ * \li Updated dfll configuration function to implement workaround for + * errata 9905 in the DFLL module + * \li Updated \c system_clock_init() to reset interrupt flags before + * they are used + * \li Fixed \c system_clock_source_get_hz() to return correcy DFLL + * frequency number + *
\li Fixed \c system_clock_source_is_ready not returning the correct + * state for \c SYSTEM_CLOCK_SOURCE_OSC8M + * \li Renamed the various \c system_clock_source_*_get_default_config() + * functions to \c system_clock_source_*_get_config_defaults() to + * match the remainder of ASF + * \li Added OSC8M calibration constant loading from the device signature + * row when the oscillator is initialized + * \li Updated default configuration of the XOSC32 to disable Automatic + * Gain Control due to silicon errata + *
Initial Release
+ */ + +/** + * \page asfdoc_sam0_system_clock_exqsg Examples for System Clock Driver + * + * This is a list of the available Quick Start guides (QSGs) and example + * applications for \ref asfdoc_sam0_system_clock_group. QSGs are simple + * examples with step-by-step instructions to configure and use this driver in + * a selection of use cases. Note that QSGs can be compiled as a standalone + * application or be added to the user application. + * + * - \subpage asfdoc_sam0_system_clock_basic_use_case + * - \subpage asfdoc_sam0_system_gclk_basic_use_case + * + * \page asfdoc_sam0_system_clock_document_revision_history Document Revision History + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Doc. Rev. + * Date + * Comments + *
E04/2015Added support for SAMDAx.
D12/2014Added support for SAMR21 and SAMD10/D11.
C01/2014Added support for SAMD21.
B06/2013Corrected documentation typos. Fixed missing steps in the Basic + * Use Case Quick Start Guide.
A06/2013Initial release
+ */ + +#ifdef __cplusplus +} +#endif + +#endif /* SYSTEM_CLOCK_FEATURE_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/compiler.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/compiler.h new file mode 100644 index 0000000..2d95f97 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/compiler.h @@ -0,0 +1,1157 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef UTILS_COMPILER_H_INCLUDED +#define UTILS_COMPILER_H_INCLUDED + +/** + * \defgroup group_sam0_utils Compiler abstraction layer and code utilities + * + * Compiler abstraction layer and code utilities for Cortex-M0+ based Atmel SAM devices. + * This module provides various abstraction layers and utilities to make code compatible between different compilers. + * + * @{ + */ + +#if (defined __ICCARM__) +# include +#endif + +#include +//#include +#include "status_codes.h" +#include "preprocessor/preprocessor.h" +#include + +#ifndef __ASSEMBLY__ + +#include +#include +#include +#include + +/** + * \def UNUSED + * \brief Marking \a v as a unused parameter or value. + */ +#define UNUSED(v) (void)(v) + +/** + * \def barrier + * \brief Memory barrier + */ +#ifdef __GNUC__ +# define barrier() asm volatile("" ::: "memory") +#else +# define barrier() asm ("") +#endif + +/** + * \brief Emit the compiler pragma \a arg. + * + * \param[in] arg The pragma directive as it would appear after \e \#pragma + * (i.e. not stringified). + */ +#define COMPILER_PRAGMA(arg) _Pragma(#arg) + +/** + * \def COMPILER_PACK_SET(alignment) + * \brief Set maximum alignment for subsequent struct and union definitions to \a alignment. + */ +#define COMPILER_PACK_SET(alignment) COMPILER_PRAGMA(pack(alignment)) + +/** + * \def COMPILER_PACK_RESET() + * \brief Set default alignment for subsequent struct and union definitions. + */ +#define COMPILER_PACK_RESET() COMPILER_PRAGMA(pack()) + + +/** + * \brief Set aligned boundary. + */ +#if (defined __GNUC__) || (defined __CC_ARM) +# define COMPILER_ALIGNED(a) __attribute__((__aligned__(a))) +#elif (defined __ICCARM__) +# define COMPILER_ALIGNED(a) COMPILER_PRAGMA(data_alignment = a) +#endif + +/** + * \brief Set word-aligned boundary. + */ +#if (defined __GNUC__) || defined(__CC_ARM) +#define COMPILER_WORD_ALIGNED __attribute__((__aligned__(4))) +#elif (defined __ICCARM__) +#define COMPILER_WORD_ALIGNED COMPILER_PRAGMA(data_alignment = 4) +#endif + +/** + * \def __always_inline + * \brief The function should always be inlined. + * + * This annotation instructs the compiler to ignore its inlining + * heuristics and inline the function no matter how big it thinks it + * becomes. + */ +#if defined(__CC_ARM) +# define __always_inline __forceinline +#elif (defined __GNUC__) +# define __always_inline __attribute__((__always_inline__)) +#elif (defined __ICCARM__) +# define __always_inline _Pragma("inline=forced") +#endif + +/** + * \def __no_inline + * \brief The function should never be inlined + * + * This annotation instructs the compiler to ignore its inlining + * heuristics and not inline the function no matter how small it thinks it + * becomes. + */ +#if defined(__CC_ARM) +# define __no_inline __attribute__((noinline)) +#elif (defined __GNUC__) +# define __no_inline __attribute__((noinline)) +#elif (defined __ICCARM__) +# define __no_inline _Pragma("inline=never") +#endif + + +/** \brief This macro is used to test fatal errors. + * + * The macro tests if the expression is false. If it is, a fatal error is + * detected and the application hangs up. If \c TEST_SUITE_DEFINE_ASSERT_MACRO + * is defined, a unit test version of the macro is used, to allow execution + * of further tests after a false expression. + * + * \param[in] expr Expression to evaluate and supposed to be nonzero. + */ +#if defined(_ASSERT_ENABLE_) +# if defined(TEST_SUITE_DEFINE_ASSERT_MACRO) +# include "unit_test/suite.h" +# else +# undef TEST_SUITE_DEFINE_ASSERT_MACRO +# define Assert(expr) \ + {\ + if (!(expr)) asm("BKPT #0");\ + } +# endif +#else +# define Assert(expr) ((void) 0) +#endif + +/* Define WEAK attribute */ +#if defined ( __CC_ARM ) +# define WEAK __attribute__ ((weak)) +#elif defined ( __ICCARM__ ) +# define WEAK __weak +#elif defined ( __GNUC__ ) +# define WEAK __attribute__ ((weak)) +#endif + +/* Define NO_INIT attribute */ +#if defined ( __CC_ARM ) +# define NO_INIT __attribute__((zero_init)) +#elif defined ( __ICCARM__ ) +# define NO_INIT __no_init +#elif defined ( __GNUC__ ) +# define NO_INIT __attribute__((section(".no_init"))) +#endif + +#include "interrupt.h" + +/** \name Usual Types + * @{ */ +#ifndef __cplusplus +# if !defined(__bool_true_false_are_defined) +typedef unsigned char bool; +# endif +#endif +typedef uint16_t le16_t; +typedef uint16_t be16_t; +typedef uint32_t le32_t; +typedef uint32_t be32_t; +typedef uint32_t iram_size_t; +/** @} */ + +/** \name Aliasing Aggregate Types + * @{ */ + +/** 16-bit union. */ +typedef union +{ + int16_t s16; + uint16_t u16; + int8_t s8[2]; + uint8_t u8[2]; +} Union16; + +/** 32-bit union. */ +typedef union +{ + int32_t s32; + uint32_t u32; + int16_t s16[2]; + uint16_t u16[2]; + int8_t s8[4]; + uint8_t u8[4]; +} Union32; + +/** 64-bit union. */ +typedef union +{ + int64_t s64; + uint64_t u64; + int32_t s32[2]; + uint32_t u32[2]; + int16_t s16[4]; + uint16_t u16[4]; + int8_t s8[8]; + uint8_t u8[8]; +} Union64; + +/** Union of pointers to 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef union +{ + int64_t *s64ptr; + uint64_t *u64ptr; + int32_t *s32ptr; + uint32_t *u32ptr; + int16_t *s16ptr; + uint16_t *u16ptr; + int8_t *s8ptr; + uint8_t *u8ptr; +} UnionPtr; + +/** Union of pointers to volatile 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef union +{ + volatile int64_t *s64ptr; + volatile uint64_t *u64ptr; + volatile int32_t *s32ptr; + volatile uint32_t *u32ptr; + volatile int16_t *s16ptr; + volatile uint16_t *u16ptr; + volatile int8_t *s8ptr; + volatile uint8_t *u8ptr; +} UnionVPtr; + +/** Union of pointers to constant 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef union +{ + const int64_t *s64ptr; + const uint64_t *u64ptr; + const int32_t *s32ptr; + const uint32_t *u32ptr; + const int16_t *s16ptr; + const uint16_t *u16ptr; + const int8_t *s8ptr; + const uint8_t *u8ptr; +} UnionCPtr; + +/** Union of pointers to constant volatile 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef union +{ + const volatile int64_t *s64ptr; + const volatile uint64_t *u64ptr; + const volatile int32_t *s32ptr; + const volatile uint32_t *u32ptr; + const volatile int16_t *s16ptr; + const volatile uint16_t *u16ptr; + const volatile int8_t *s8ptr; + const volatile uint8_t *u8ptr; +} UnionCVPtr; + +/** Structure of pointers to 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef struct +{ + int64_t *s64ptr; + uint64_t *u64ptr; + int32_t *s32ptr; + uint32_t *u32ptr; + int16_t *s16ptr; + uint16_t *u16ptr; + int8_t *s8ptr; + uint8_t *u8ptr; +} StructPtr; + +/** Structure of pointers to volatile 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef struct +{ + volatile int64_t *s64ptr; + volatile uint64_t *u64ptr; + volatile int32_t *s32ptr; + volatile uint32_t *u32ptr; + volatile int16_t *s16ptr; + volatile uint16_t *u16ptr; + volatile int8_t *s8ptr; + volatile uint8_t *u8ptr; +} StructVPtr; + +/** Structure of pointers to constant 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef struct +{ + const int64_t *s64ptr; + const uint64_t *u64ptr; + const int32_t *s32ptr; + const uint32_t *u32ptr; + const int16_t *s16ptr; + const uint16_t *u16ptr; + const int8_t *s8ptr; + const uint8_t *u8ptr; +} StructCPtr; + +/** Structure of pointers to constant volatile 64-, 32-, 16- and 8-bit unsigned integers. */ +typedef struct +{ + const volatile int64_t *s64ptr; + const volatile uint64_t *u64ptr; + const volatile int32_t *s32ptr; + const volatile uint32_t *u32ptr; + const volatile int16_t *s16ptr; + const volatile uint16_t *u16ptr; + const volatile int8_t *s8ptr; + const volatile uint8_t *u8ptr; +} StructCVPtr; + +/** @} */ + +#endif /* #ifndef __ASSEMBLY__ */ + +/** \name Usual Constants + * @{ */ +#define DISABLE 0 +//#define ENABLE 1 + +#ifndef __cplusplus +# if !defined(__bool_true_false_are_defined) +# define false 0 +# define true 1 +# endif +#endif +/** @} */ + +#ifndef __ASSEMBLY__ + +/** \name Optimization Control + * @{ */ + +/** + * \def likely(exp) + * \brief The expression \a exp is likely to be true + */ +#if !defined(likely) || defined(__DOXYGEN__) +# define likely(exp) (exp) +#endif + +/** + * \def unlikely(exp) + * \brief The expression \a exp is unlikely to be true + */ +#if !defined(unlikely) || defined(__DOXYGEN__) +# define unlikely(exp) (exp) +#endif + +/** + * \def is_constant(exp) + * \brief Determine if an expression evaluates to a constant value. + * + * \param[in] exp Any expression + * + * \return true if \a exp is constant, false otherwise. + */ +#if (defined __GNUC__) || (defined __CC_ARM) +# define is_constant(exp) __builtin_constant_p(exp) +#else +# define is_constant(exp) (0) +#endif + +/** @} */ + +/** \name Bit-Field Handling + * @{ */ + +/** \brief Reads the bits of a value specified by a given bit-mask. + * + * \param[in] value Value to read bits from. + * \param[in] mask Bit-mask indicating bits to read. + * + * \return Read bits. + */ +#define Rd_bits( value, mask) ((value) & (mask)) + +/** \brief Writes the bits of a C lvalue specified by a given bit-mask. + * + * \param[in] lvalue C lvalue to write bits to. + * \param[in] mask Bit-mask indicating bits to write. + * \param[in] bits Bits to write. + * + * \return Resulting value with written bits. + */ +#define Wr_bits(lvalue, mask, bits) ((lvalue) = ((lvalue) & ~(mask)) |\ + ((bits ) & (mask))) + +/** \brief Tests the bits of a value specified by a given bit-mask. + * + * \param[in] value Value of which to test bits. + * \param[in] mask Bit-mask indicating bits to test. + * + * \return \c 1 if at least one of the tested bits is set, else \c 0. + */ +#define Tst_bits( value, mask) (Rd_bits(value, mask) != 0) + +/** \brief Clears the bits of a C lvalue specified by a given bit-mask. + * + * \param[in] lvalue C lvalue of which to clear bits. + * \param[in] mask Bit-mask indicating bits to clear. + * + * \return Resulting value with cleared bits. + */ +#define Clr_bits(lvalue, mask) ((lvalue) &= ~(mask)) + +/** \brief Sets the bits of a C lvalue specified by a given bit-mask. + * + * \param[in] lvalue C lvalue of which to set bits. + * \param[in] mask Bit-mask indicating bits to set. + * + * \return Resulting value with set bits. + */ +#define Set_bits(lvalue, mask) ((lvalue) |= (mask)) + +/** \brief Toggles the bits of a C lvalue specified by a given bit-mask. + * + * \param[in] lvalue C lvalue of which to toggle bits. + * \param[in] mask Bit-mask indicating bits to toggle. + * + * \return Resulting value with toggled bits. + */ +#define Tgl_bits(lvalue, mask) ((lvalue) ^= (mask)) + +/** \brief Reads the bit-field of a value specified by a given bit-mask. + * + * \param[in] value Value to read a bit-field from. + * \param[in] mask Bit-mask indicating the bit-field to read. + * + * \return Read bit-field. + */ +#define Rd_bitfield( value, mask) (Rd_bits( value, mask) >> ctz(mask)) + +/** \brief Writes the bit-field of a C lvalue specified by a given bit-mask. + * + * \param[in] lvalue C lvalue to write a bit-field to. + * \param[in] mask Bit-mask indicating the bit-field to write. + * \param[in] bitfield Bit-field to write. + * + * \return Resulting value with written bit-field. + */ +#define Wr_bitfield(lvalue, mask, bitfield) (Wr_bits(lvalue, mask, (uint32_t)(bitfield) << ctz(mask))) + +/** @} */ + + +/** \name Zero-Bit Counting + * + * Under GCC, __builtin_clz and __builtin_ctz behave like macros when + * applied to constant expressions (values known at compile time), so they are + * more optimized than the use of the corresponding assembly instructions and + * they can be used as constant expressions e.g. to initialize objects having + * static storage duration, and like the corresponding assembly instructions + * when applied to non-constant expressions (values unknown at compile time), so + * they are more optimized than an assembly periphrasis. Hence, clz and ctz + * ensure a possible and optimized behavior for both constant and non-constant + * expressions. + * + * @{ */ + +/** \brief Counts the leading zero bits of the given value considered as a 32-bit integer. + * + * \param[in] u Value of which to count the leading zero bits. + * + * \return The count of leading zero bits in \a u. + */ +#if (defined __GNUC__) || (defined __CC_ARM) +# define clz(u) __builtin_clz(u) +#else +# define clz(u) (((u) == 0) ? 32 : \ + ((u) & (1ul << 31)) ? 0 : \ + ((u) & (1ul << 30)) ? 1 : \ + ((u) & (1ul << 29)) ? 2 : \ + ((u) & (1ul << 28)) ? 3 : \ + ((u) & (1ul << 27)) ? 4 : \ + ((u) & (1ul << 26)) ? 5 : \ + ((u) & (1ul << 25)) ? 6 : \ + ((u) & (1ul << 24)) ? 7 : \ + ((u) & (1ul << 23)) ? 8 : \ + ((u) & (1ul << 22)) ? 9 : \ + ((u) & (1ul << 21)) ? 10 : \ + ((u) & (1ul << 20)) ? 11 : \ + ((u) & (1ul << 19)) ? 12 : \ + ((u) & (1ul << 18)) ? 13 : \ + ((u) & (1ul << 17)) ? 14 : \ + ((u) & (1ul << 16)) ? 15 : \ + ((u) & (1ul << 15)) ? 16 : \ + ((u) & (1ul << 14)) ? 17 : \ + ((u) & (1ul << 13)) ? 18 : \ + ((u) & (1ul << 12)) ? 19 : \ + ((u) & (1ul << 11)) ? 20 : \ + ((u) & (1ul << 10)) ? 21 : \ + ((u) & (1ul << 9)) ? 22 : \ + ((u) & (1ul << 8)) ? 23 : \ + ((u) & (1ul << 7)) ? 24 : \ + ((u) & (1ul << 6)) ? 25 : \ + ((u) & (1ul << 5)) ? 26 : \ + ((u) & (1ul << 4)) ? 27 : \ + ((u) & (1ul << 3)) ? 28 : \ + ((u) & (1ul << 2)) ? 29 : \ + ((u) & (1ul << 1)) ? 30 : \ + 31) +#endif + +/** \brief Counts the trailing zero bits of the given value considered as a 32-bit integer. + * + * \param[in] u Value of which to count the trailing zero bits. + * + * \return The count of trailing zero bits in \a u. + */ +#if (defined __GNUC__) || (defined __CC_ARM) +# define ctz(u) __builtin_ctz(u) +#else +# define ctz(u) ((u) & (1ul << 0) ? 0 : \ + (u) & (1ul << 1) ? 1 : \ + (u) & (1ul << 2) ? 2 : \ + (u) & (1ul << 3) ? 3 : \ + (u) & (1ul << 4) ? 4 : \ + (u) & (1ul << 5) ? 5 : \ + (u) & (1ul << 6) ? 6 : \ + (u) & (1ul << 7) ? 7 : \ + (u) & (1ul << 8) ? 8 : \ + (u) & (1ul << 9) ? 9 : \ + (u) & (1ul << 10) ? 10 : \ + (u) & (1ul << 11) ? 11 : \ + (u) & (1ul << 12) ? 12 : \ + (u) & (1ul << 13) ? 13 : \ + (u) & (1ul << 14) ? 14 : \ + (u) & (1ul << 15) ? 15 : \ + (u) & (1ul << 16) ? 16 : \ + (u) & (1ul << 17) ? 17 : \ + (u) & (1ul << 18) ? 18 : \ + (u) & (1ul << 19) ? 19 : \ + (u) & (1ul << 20) ? 20 : \ + (u) & (1ul << 21) ? 21 : \ + (u) & (1ul << 22) ? 22 : \ + (u) & (1ul << 23) ? 23 : \ + (u) & (1ul << 24) ? 24 : \ + (u) & (1ul << 25) ? 25 : \ + (u) & (1ul << 26) ? 26 : \ + (u) & (1ul << 27) ? 27 : \ + (u) & (1ul << 28) ? 28 : \ + (u) & (1ul << 29) ? 29 : \ + (u) & (1ul << 30) ? 30 : \ + (u) & (1ul << 31) ? 31 : \ + 32) +#endif + +/** @} */ + + +/** \name Bit Reversing + * @{ */ + +/** \brief Reverses the bits of \a u8. + * + * \param[in] u8 U8 of which to reverse the bits. + * + * \return Value resulting from \a u8 with reversed bits. + */ +#define bit_reverse8(u8) ((U8)(bit_reverse32((U8)(u8)) >> 24)) + +/** \brief Reverses the bits of \a u16. + * + * \param[in] u16 U16 of which to reverse the bits. + * + * \return Value resulting from \a u16 with reversed bits. + */ +#define bit_reverse16(u16) ((uint16_t)(bit_reverse32((uint16_t)(u16)) >> 16)) + +/** \brief Reverses the bits of \a u32. + * + * \param[in] u32 U32 of which to reverse the bits. + * + * \return Value resulting from \a u32 with reversed bits. + */ +#define bit_reverse32(u32) __RBIT(u32) + +/** \brief Reverses the bits of \a u64. + * + * \param[in] u64 U64 of which to reverse the bits. + * + * \return Value resulting from \a u64 with reversed bits. + */ +#define bit_reverse64(u64) ((uint64_t)(((uint64_t)bit_reverse32((uint64_t)(u64) >> 32)) |\ + ((uint64_t)bit_reverse32((uint64_t)(u64)) << 32))) + +/** @} */ + + +/** \name Alignment + * @{ */ + +/** \brief Tests alignment of the number \a val with the \a n boundary. + * + * \param[in] val Input value. + * \param[in] n Boundary. + * + * \return \c 1 if the number \a val is aligned with the \a n boundary, else \c 0. + */ +#define Test_align(val, n) (!Tst_bits( val, (n) - 1 ) ) + +/** \brief Gets alignment of the number \a val with respect to the \a n boundary. + * + * \param[in] val Input value. + * \param[in] n Boundary. + * + * \return Alignment of the number \a val with respect to the \a n boundary. + */ +#define Get_align(val, n) ( Rd_bits( val, (n) - 1 ) ) + +/** \brief Sets alignment of the lvalue number \a lval to \a alg with respect to the \a n boundary. + * + * \param[in] lval Input/output lvalue. + * \param[in] n Boundary. + * \param[in] alg Alignment. + * + * \return New value of \a lval resulting from its alignment set to \a alg with respect to the \a n boundary. + */ +#define Set_align(lval, n, alg) ( Wr_bits(lval, (n) - 1, alg) ) + +/** \brief Aligns the number \a val with the upper \a n boundary. + * + * \param[in] val Input value. + * \param[in] n Boundary. + * + * \return Value resulting from the number \a val aligned with the upper \a n boundary. + */ +#define Align_up( val, n) (((val) + ((n) - 1)) & ~((n) - 1)) + +/** \brief Aligns the number \a val with the lower \a n boundary. + * + * \param[in] val Input value. + * \param[in] n Boundary. + * + * \return Value resulting from the number \a val aligned with the lower \a n boundary. + */ +#define Align_down(val, n) ( (val) & ~((n) - 1)) + +/** @} */ + + +/** \name Mathematics + * + * The same considerations as for clz and ctz apply here but GCC does not + * provide built-in functions to access the assembly instructions abs, min and + * max and it does not produce them by itself in most cases, so two sets of + * macros are defined here: + * - Abs, Min and Max to apply to constant expressions (values known at + * compile time); + * - abs, min and max to apply to non-constant expressions (values unknown at + * compile time), abs is found in stdlib.h. + * + * @{ */ + +/** \brief Takes the absolute value of \a a. + * + * \param[in] a Input value. + * + * \return Absolute value of \a a. + * + * \note More optimized if only used with values known at compile time. + */ +#define Abs(a) (((a) < 0 ) ? -(a) : (a)) + +/** \brief Takes the minimal value of \a a and \a b. + * + * \param[in] a Input value. + * \param[in] b Input value. + * + * \return Minimal value of \a a and \a b. + * + * \note More optimized if only used with values known at compile time. + */ +#define Min(a, b) (((a) < (b)) ? (a) : (b)) + +/** \brief Takes the maximal value of \a a and \a b. + * + * \param[in] a Input value. + * \param[in] b Input value. + * + * \return Maximal value of \a a and \a b. + * + * \note More optimized if only used with values known at compile time. + */ +#define Max(a, b) (((a) > (b)) ? (a) : (b)) + +/** \brief Takes the minimal value of \a a and \a b. + * + * \param[in] a Input value. + * \param[in] b Input value. + * + * \return Minimal value of \a a and \a b. + * + * \note More optimized if only used with values unknown at compile time. + */ +#define min(a, b) Min(a, b) + +/** \brief Takes the maximal value of \a a and \a b. + * + * \param[in] a Input value. + * \param[in] b Input value. + * + * \return Maximal value of \a a and \a b. + * + * \note More optimized if only used with values unknown at compile time. + */ +#define max(a, b) Max(a, b) + +/** @} */ + + +/** \brief Calls the routine at address \a addr. + * + * It generates a long call opcode. + * + * For example, `Long_call(0x80000000)' generates a software reset on a UC3 if + * it is invoked from the CPU supervisor mode. + * + * \param[in] addr Address of the routine to call. + * + * \note It may be used as a long jump opcode in some special cases. + */ +#define Long_call(addr) ((*(void (*)(void))(addr))()) + + +/** \name MCU Endianism Handling + * ARM is MCU little endian. + * + * @{ */ +#define BE16(x) Swap16(x) +#define LE16(x) (x) + +#define le16_to_cpu(x) (x) +#define cpu_to_le16(x) (x) +#define LE16_TO_CPU(x) (x) +#define CPU_TO_LE16(x) (x) + +#define be16_to_cpu(x) Swap16(x) +#define cpu_to_be16(x) Swap16(x) +#define BE16_TO_CPU(x) Swap16(x) +#define CPU_TO_BE16(x) Swap16(x) + +#define le32_to_cpu(x) (x) +#define cpu_to_le32(x) (x) +#define LE32_TO_CPU(x) (x) +#define CPU_TO_LE32(x) (x) + +#define be32_to_cpu(x) swap32(x) +#define cpu_to_be32(x) swap32(x) +#define BE32_TO_CPU(x) swap32(x) +#define CPU_TO_BE32(x) swap32(x) +/** @} */ + + +/** \name Endianism Conversion + * + * The same considerations as for clz and ctz apply here but GCC's + * __builtin_bswap_32 and __builtin_bswap_64 do not behave like macros when + * applied to constant expressions, so two sets of macros are defined here: + * - Swap16, Swap32 and Swap64 to apply to constant expressions (values known + * at compile time); + * - swap16, swap32 and swap64 to apply to non-constant expressions (values + * unknown at compile time). + * + * @{ */ + +/** \brief Toggles the endianism of \a u16 (by swapping its bytes). + * + * \param[in] u16 U16 of which to toggle the endianism. + * + * \return Value resulting from \a u16 with toggled endianism. + * + * \note More optimized if only used with values known at compile time. + */ +#define Swap16(u16) ((uint16_t)(((uint16_t)(u16) >> 8) |\ + ((uint16_t)(u16) << 8))) + +/** \brief Toggles the endianism of \a u32 (by swapping its bytes). + * + * \param[in] u32 U32 of which to toggle the endianism. + * + * \return Value resulting from \a u32 with toggled endianism. + * + * \note More optimized if only used with values known at compile time. + */ +#define Swap32(u32) ((uint32_t)(((uint32_t)Swap16((uint32_t)(u32) >> 16)) |\ + ((uint32_t)Swap16((uint32_t)(u32)) << 16))) + +/** \brief Toggles the endianism of \a u64 (by swapping its bytes). + * + * \param[in] u64 U64 of which to toggle the endianism. + * + * \return Value resulting from \a u64 with toggled endianism. + * + * \note More optimized if only used with values known at compile time. + */ +#define Swap64(u64) ((uint64_t)(((uint64_t)Swap32((uint64_t)(u64) >> 32)) |\ + ((uint64_t)Swap32((uint64_t)(u64)) << 32))) + +/** \brief Toggles the endianism of \a u16 (by swapping its bytes). + * + * \param[in] u16 U16 of which to toggle the endianism. + * + * \return Value resulting from \a u16 with toggled endianism. + * + * \note More optimized if only used with values unknown at compile time. + */ +#define swap16(u16) Swap16(u16) + +/** \brief Toggles the endianism of \a u32 (by swapping its bytes). + * + * \param[in] u32 U32 of which to toggle the endianism. + * + * \return Value resulting from \a u32 with toggled endianism. + * + * \note More optimized if only used with values unknown at compile time. + */ +#if (defined __GNUC__) +# define swap32(u32) ((uint32_t)__builtin_bswap32((uint32_t)(u32))) +#else +# define swap32(u32) Swap32(u32) +#endif + +/** \brief Toggles the endianism of \a u64 (by swapping its bytes). + * + * \param[in] u64 U64 of which to toggle the endianism. + * + * \return Value resulting from \a u64 with toggled endianism. + * + * \note More optimized if only used with values unknown at compile time. + */ +#if (defined __GNUC__) +# define swap64(u64) ((uint64_t)__builtin_bswap64((uint64_t)(u64))) +#else +# define swap64(u64) ((uint64_t)(((uint64_t)swap32((uint64_t)(u64) >> 32)) |\ + ((uint64_t)swap32((uint64_t)(u64)) << 32))) +#endif + +/** @} */ + + +/** \name Target Abstraction + * + * @{ */ + +#define _GLOBEXT_ extern /**< extern storage-class specifier. */ +#define _CONST_TYPE_ const /**< const type qualifier. */ +#define _MEM_TYPE_SLOW_ /**< Slow memory type. */ +#define _MEM_TYPE_MEDFAST_ /**< Fairly fast memory type. */ +#define _MEM_TYPE_FAST_ /**< Fast memory type. */ + +#define memcmp_ram2ram memcmp /**< Target-specific memcmp of RAM to RAM. */ +#define memcmp_code2ram memcmp /**< Target-specific memcmp of RAM to NVRAM. */ +#define memcpy_ram2ram memcpy /**< Target-specific memcpy from RAM to RAM. */ +#define memcpy_code2ram memcpy /**< Target-specific memcpy from NVRAM to RAM. */ + +/** @} */ + +/** + * \brief Calculate \f$ \left\lceil \frac{a}{b} \right\rceil \f$ using + * integer arithmetic. + * + * \param[in] a An integer + * \param[in] b Another integer + * + * \return (\a a / \a b) rounded up to the nearest integer. + */ +#define div_ceil(a, b) (((a) + (b) - 1) / (b)) + +#endif /* #ifndef __ASSEMBLY__ */ +#ifdef __ICCARM__ +/** \name Compiler Keywords + * + * Port of some keywords from GCC to IAR Embedded Workbench. + * + * @{ */ + +#define __asm__ asm +#define __inline__ inline +#define __volatile__ + +/** @} */ + +#endif + +#define FUNC_PTR void * +/** + * \def unused + * \brief Marking \a v as a unused parameter or value. + */ +#define unused(v) do { (void)(v); } while(0) + +/* Define RAMFUNC attribute */ +#if defined ( __CC_ARM ) /* Keil uVision 4 */ +# define RAMFUNC __attribute__ ((section(".ramfunc"))) +#elif defined ( __ICCARM__ ) /* IAR Ewarm 5.41+ */ +# define RAMFUNC __ramfunc +#elif defined ( __GNUC__ ) /* GCC CS3 2009q3-68 */ +# define RAMFUNC __attribute__ ((section(".ramfunc"))) +#endif + +/* Define OPTIMIZE_HIGH attribute */ +#if defined ( __CC_ARM ) /* Keil uVision 4 */ +# define OPTIMIZE_HIGH _Pragma("O3") +#elif defined ( __ICCARM__ ) /* IAR Ewarm 5.41+ */ +# define OPTIMIZE_HIGH _Pragma("optimize=high") +#elif defined ( __GNUC__ ) /* GCC CS3 2009q3-68 */ +# define OPTIMIZE_HIGH __attribute__((optimize(s))) +#endif +#define PASS 0 +#define FAIL 1 +#define LOW 0 +#define HIGH 1 + +typedef int8_t S8 ; //!< 8-bit signed integer. +typedef uint8_t U8 ; //!< 8-bit unsigned integer. +typedef int16_t S16; //!< 16-bit signed integer. +typedef uint16_t U16; //!< 16-bit unsigned integer. +typedef int32_t S32; //!< 32-bit signed integer. +typedef uint32_t U32; //!< 32-bit unsigned integer. +typedef int64_t S64; //!< 64-bit signed integer. +typedef uint64_t U64; //!< 64-bit unsigned integer. +typedef float F32; //!< 32-bit floating-point number. +typedef double F64; //!< 64-bit floating-point number. + +#define MSB(u16) (((U8 *)&(u16))[1]) //!< Most significant byte of \a u16. +#define LSB(u16) (((U8 *)&(u16))[0]) //!< Least significant byte of \a u16. + +#define MSH(u32) (((U16 *)&(u32))[1]) //!< Most significant half-word of \a u32. +#define LSH(u32) (((U16 *)&(u32))[0]) //!< Least significant half-word of \a u32. +#define MSB0W(u32) (((U8 *)&(u32))[3]) //!< Most significant byte of 1st rank of \a u32. +#define MSB1W(u32) (((U8 *)&(u32))[2]) //!< Most significant byte of 2nd rank of \a u32. +#define MSB2W(u32) (((U8 *)&(u32))[1]) //!< Most significant byte of 3rd rank of \a u32. +#define MSB3W(u32) (((U8 *)&(u32))[0]) //!< Most significant byte of 4th rank of \a u32. +#define LSB3W(u32) MSB0W(u32) //!< Least significant byte of 4th rank of \a u32. +#define LSB2W(u32) MSB1W(u32) //!< Least significant byte of 3rd rank of \a u32. +#define LSB1W(u32) MSB2W(u32) //!< Least significant byte of 2nd rank of \a u32. +#define LSB0W(u32) MSB3W(u32) //!< Least significant byte of 1st rank of \a u32. + +#define MSW(u64) (((U32 *)&(u64))[1]) //!< Most significant word of \a u64. +#define LSW(u64) (((U32 *)&(u64))[0]) //!< Least significant word of \a u64. +#define MSH0(u64) (((U16 *)&(u64))[3]) //!< Most significant half-word of 1st rank of \a u64. +#define MSH1(u64) (((U16 *)&(u64))[2]) //!< Most significant half-word of 2nd rank of \a u64. +#define MSH2(u64) (((U16 *)&(u64))[1]) //!< Most significant half-word of 3rd rank of \a u64. +#define MSH3(u64) (((U16 *)&(u64))[0]) //!< Most significant half-word of 4th rank of \a u64. +#define LSH3(u64) MSH0(u64) //!< Least significant half-word of 4th rank of \a u64. +#define LSH2(u64) MSH1(u64) //!< Least significant half-word of 3rd rank of \a u64. +#define LSH1(u64) MSH2(u64) //!< Least significant half-word of 2nd rank of \a u64. +#define LSH0(u64) MSH3(u64) //!< Least significant half-word of 1st rank of \a u64. +#define MSB0D(u64) (((U8 *)&(u64))[7]) //!< Most significant byte of 1st rank of \a u64. +#define MSB1D(u64) (((U8 *)&(u64))[6]) //!< Most significant byte of 2nd rank of \a u64. +#define MSB2D(u64) (((U8 *)&(u64))[5]) //!< Most significant byte of 3rd rank of \a u64. +#define MSB3D(u64) (((U8 *)&(u64))[4]) //!< Most significant byte of 4th rank of \a u64. +#define MSB4D(u64) (((U8 *)&(u64))[3]) //!< Most significant byte of 5th rank of \a u64. +#define MSB5D(u64) (((U8 *)&(u64))[2]) //!< Most significant byte of 6th rank of \a u64. +#define MSB6D(u64) (((U8 *)&(u64))[1]) //!< Most significant byte of 7th rank of \a u64. +#define MSB7D(u64) (((U8 *)&(u64))[0]) //!< Most significant byte of 8th rank of \a u64. +#define LSB7D(u64) MSB0D(u64) //!< Least significant byte of 8th rank of \a u64. +#define LSB6D(u64) MSB1D(u64) //!< Least significant byte of 7th rank of \a u64. +#define LSB5D(u64) MSB2D(u64) //!< Least significant byte of 6th rank of \a u64. +#define LSB4D(u64) MSB3D(u64) //!< Least significant byte of 5th rank of \a u64. +#define LSB3D(u64) MSB4D(u64) //!< Least significant byte of 4th rank of \a u64. +#define LSB2D(u64) MSB5D(u64) //!< Least significant byte of 3rd rank of \a u64. +#define LSB1D(u64) MSB6D(u64) //!< Least significant byte of 2nd rank of \a u64. +#define LSB0D(u64) MSB7D(u64) //!< Least significant byte of 1st rank of \a u64. + +#define LSB0(u32) LSB0W(u32) //!< Least significant byte of 1st rank of \a u32. +#define LSB1(u32) LSB1W(u32) //!< Least significant byte of 2nd rank of \a u32. +#define LSB2(u32) LSB2W(u32) //!< Least significant byte of 3rd rank of \a u32. +#define LSB3(u32) LSB3W(u32) //!< Least significant byte of 4th rank of \a u32. +#define MSB3(u32) MSB3W(u32) //!< Most significant byte of 4th rank of \a u32. +#define MSB2(u32) MSB2W(u32) //!< Most significant byte of 3rd rank of \a u32. +#define MSB1(u32) MSB1W(u32) //!< Most significant byte of 2nd rank of \a u32. +#define MSB0(u32) MSB0W(u32) //!< Most significant byte of 1st rank of \a u32. + +#if defined(__ICCARM__) +#define SHORTENUM __packed +#elif defined(__GNUC__) +#define SHORTENUM __attribute__((packed)) +#endif + +/* No operation */ +#if defined(__ICCARM__) +#define nop() __no_operation() +#elif defined(__GNUC__) +#define nop() (__NOP()) +#endif + +#define FLASH_DECLARE(x) const x +#define FLASH_EXTERN(x) extern const x +#define PGM_READ_BYTE(x) *(x) +#define PGM_READ_WORD(x) *(x) +#define MEMCPY_ENDIAN memcpy +#define PGM_READ_BLOCK(dst, src, len) memcpy((dst), (src), (len)) + +/*Defines the Flash Storage for the request and response of MAC*/ +#define CMD_ID_OCTET (0) + +/* Converting of values from CPU endian to little endian. */ +#define CPU_ENDIAN_TO_LE16(x) (x) +#define CPU_ENDIAN_TO_LE32(x) (x) +#define CPU_ENDIAN_TO_LE64(x) (x) + +/* Converting of values from little endian to CPU endian. */ +#define LE16_TO_CPU_ENDIAN(x) (x) +#define LE32_TO_CPU_ENDIAN(x) (x) +#define LE64_TO_CPU_ENDIAN(x) (x) + +/* Converting of constants from little endian to CPU endian. */ +#define CLE16_TO_CPU_ENDIAN(x) (x) +#define CLE32_TO_CPU_ENDIAN(x) (x) +#define CLE64_TO_CPU_ENDIAN(x) (x) + +/* Converting of constants from CPU endian to little endian. */ +#define CCPU_ENDIAN_TO_LE16(x) (x) +#define CCPU_ENDIAN_TO_LE32(x) (x) +#define CCPU_ENDIAN_TO_LE64(x) (x) + +#define ADDR_COPY_DST_SRC_16(dst, src) ((dst) = (src)) +#define ADDR_COPY_DST_SRC_64(dst, src) ((dst) = (src)) + +/** + * @brief Converts a 64-Bit value into a 8 Byte array + * + * @param[in] value 64-Bit value + * @param[out] data Pointer to the 8 Byte array to be updated with 64-Bit value + * @ingroup apiPalApi + */ +static inline void convert_64_bit_to_byte_array(uint64_t value, uint8_t *data) +{ + uint8_t index = 0; + + while (index < 8) + { + data[index++] = value & 0xFF; + value = value >> 8; + } +} + +/** + * @brief Converts a 16-Bit value into a 2 Byte array + * + * @param[in] value 16-Bit value + * @param[out] data Pointer to the 2 Byte array to be updated with 16-Bit value + * @ingroup apiPalApi + */ +static inline void convert_16_bit_to_byte_array(uint16_t value, uint8_t *data) +{ + data[0] = value & 0xFF; + data[1] = (value >> 8) & 0xFF; +} + +/* Converts a 16-Bit value into a 2 Byte array */ +static inline void convert_spec_16_bit_to_byte_array(uint16_t value, uint8_t *data) +{ + data[0] = value & 0xFF; + data[1] = (value >> 8) & 0xFF; +} + +/* Converts a 16-Bit value into a 2 Byte array */ +static inline void convert_16_bit_to_byte_address(uint16_t value, uint8_t *data) +{ + data[0] = value & 0xFF; + data[1] = (value >> 8) & 0xFF; +} + +/* + * @brief Converts a 2 Byte array into a 16-Bit value + * + * @param data Specifies the pointer to the 2 Byte array + * + * @return 16-Bit value + * @ingroup apiPalApi + */ +static inline uint16_t convert_byte_array_to_16_bit(uint8_t *data) +{ + return (data[0] | ((uint16_t)data[1] << 8)); +} + +/* Converts a 4 Byte array into a 32-Bit value */ +static inline uint32_t convert_byte_array_to_32_bit(uint8_t *data) +{ + union + { + uint32_t u32; + uint8_t u8[4]; + }long_addr; + uint8_t index; + for (index = 0; index < 4; index++) + { + long_addr.u8[index] = *data++; + } + return long_addr.u32; +} + +/** + * @brief Converts a 8 Byte array into a 64-Bit value + * + * @param data Specifies the pointer to the 8 Byte array + * + * @return 64-Bit value + * @ingroup apiPalApi + */ +static inline uint64_t convert_byte_array_to_64_bit(uint8_t *data) +{ + union + { + uint64_t u64; + uint8_t u8[8]; + } long_addr; + + uint8_t index; + + for (index = 0; index < 8; index++) + { + long_addr.u8[index] = *data++; + } + + return long_addr.u64; +} + +/** @} */ + +#endif /* UTILS_COMPILER_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/gclk.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/gclk.c new file mode 100644 index 0000000..1199a19 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/gclk.c @@ -0,0 +1,522 @@ +/** + * \file + * + * \brief SAM D21/R21/DA0/DA1 Generic Clock Driver + * + * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#include +#include +#include + +/** + * \brief Determines if the hardware module(s) are currently synchronizing to the bus. + * + * Checks to see if the underlying hardware peripheral module(s) are currently + * synchronizing across multiple clock domains to the hardware bus, This + * function can be used to delay further operations on a module until such time + * that it is ready, to prevent blocking delays for synchronization in the + * user application. + * + * \return Synchronization status of the underlying hardware module(s). + * + * \retval false if the module has completed synchronization + * \retval true if the module synchronization is ongoing + */ +static inline bool system_gclk_is_syncing(void) +{ + if (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY){ + return true; + } + + return false; +} + +/** + * \brief Initializes the GCLK driver. + * + * Initializes the Generic Clock module, disabling and resetting all active + * Generic Clock Generators and Channels to their power-on default values. + */ +void system_gclk_init(void) +{ + /* Turn on the digital interface clock */ + system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBA, PM_APBAMASK_GCLK); + + /* Software reset the module to ensure it is re-initialized correctly */ + GCLK->CTRL.reg = GCLK_CTRL_SWRST; + while (GCLK->CTRL.reg & GCLK_CTRL_SWRST) { + /* Wait for reset to complete */ + } +} + +/** + * \brief Writes a Generic Clock Generator configuration to the hardware module. + * + * Writes out a given configuration of a Generic Clock Generator configuration + * to the hardware module. + * + * \note Changing the clock source on the fly (on a running + * generator) can take additional time if the clock source is configured + * to only run on-demand (ONDEMAND bit is set) and it is not currently + * running (no peripheral is requesting the clock source). In this case + * the GCLK will request the new clock while still keeping a request to + * the old clock source until the new clock source is ready. + * + * \note This function will not start a generator that is not already running; + * to start the generator, call \ref system_gclk_gen_enable() + * after configuring a generator. + * + * \param[in] generator Generic Clock Generator index to configure + * \param[in] config Configuration settings for the generator + */ +void system_gclk_gen_set_config( + const uint8_t generator, + struct system_gclk_gen_config *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Cache new register configurations to minimize sync requirements. */ + uint32_t new_genctrl_config = (generator << GCLK_GENCTRL_ID_Pos); + uint32_t new_gendiv_config = (generator << GCLK_GENDIV_ID_Pos); + + /* Select the requested source clock for the generator */ + new_genctrl_config |= config->source_clock << GCLK_GENCTRL_SRC_Pos; + + /* Configure the clock to be either high or low when disabled */ + if (config->high_when_disabled) { + new_genctrl_config |= GCLK_GENCTRL_OOV; + } + + /* Configure if the clock output to I/O pin should be enabled. */ + if (config->output_enable) { + new_genctrl_config |= GCLK_GENCTRL_OE; + } + + /* Set division factor */ + if (config->division_factor > 1) { + /* Check if division is a power of two */ + if (((config->division_factor & (config->division_factor - 1)) == 0)) { + /* Determine the index of the highest bit set to get the + * division factor that must be loaded into the division + * register */ + + uint32_t div2_count = 0; + + uint32_t mask; + for (mask = (1UL << 1); mask < config->division_factor; + mask <<= 1) { + div2_count++; + } + + /* Set binary divider power of 2 division factor */ + new_gendiv_config |= div2_count << GCLK_GENDIV_DIV_Pos; + new_genctrl_config |= GCLK_GENCTRL_DIVSEL; + } else { + /* Set integer division factor */ + + new_gendiv_config |= + (config->division_factor) << GCLK_GENDIV_DIV_Pos; + + /* Enable non-binary division with increased duty cycle accuracy */ + new_genctrl_config |= GCLK_GENCTRL_IDC; + } + + } + + /* Enable or disable the clock in standby mode */ + if (config->run_in_standby) { + new_genctrl_config |= GCLK_GENCTRL_RUNSTDBY; + } + + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + system_interrupt_enter_critical_section(); + + /* Select the correct generator */ + *((uint8_t*)&GCLK->GENDIV.reg) = generator; + + /* Write the new generator configuration */ + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + GCLK->GENDIV.reg = new_gendiv_config; + + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + GCLK->GENCTRL.reg = new_genctrl_config | (GCLK->GENCTRL.reg & GCLK_GENCTRL_GENEN); + + system_interrupt_leave_critical_section(); +} + +/** + * \brief Enables a Generic Clock Generator that was previously configured. + * + * Starts the clock generation of a Generic Clock Generator that was previously + * configured via a call to \ref system_gclk_gen_set_config(). + * + * \param[in] generator Generic Clock Generator index to enable + */ +void system_gclk_gen_enable( + const uint8_t generator) +{ + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + system_interrupt_enter_critical_section(); + + /* Select the requested generator */ + *((uint8_t*)&GCLK->GENCTRL.reg) = generator; + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + /* Enable generator */ + GCLK->GENCTRL.reg |= GCLK_GENCTRL_GENEN; + + system_interrupt_leave_critical_section(); +} + +/** + * \brief Disables a Generic Clock Generator that was previously enabled. + * + * Stops the clock generation of a Generic Clock Generator that was previously + * started via a call to \ref system_gclk_gen_enable(). + * + * \param[in] generator Generic Clock Generator index to disable + */ +void system_gclk_gen_disable( + const uint8_t generator) +{ + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + system_interrupt_enter_critical_section(); + + /* Select the requested generator */ + *((uint8_t*)&GCLK->GENCTRL.reg) = generator; + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + /* Disable generator */ + GCLK->GENCTRL.reg &= ~GCLK_GENCTRL_GENEN; + while (GCLK->GENCTRL.reg & GCLK_GENCTRL_GENEN) { + /* Wait for clock to become disabled */ + } + + system_interrupt_leave_critical_section(); +} + +/** + * \brief Determins if the specified Generic Clock Generator is enabled. + * + * \param[in] generator Generic Clock Generator index to check + * + * \return The enabled status. + * \retval true The Generic Clock Generator is enabled + * \retval false The Generic Clock Generator is disabled + */ +bool system_gclk_gen_is_enabled( + const uint8_t generator) +{ + bool enabled; + + system_interrupt_enter_critical_section(); + + /* Select the requested generator */ + *((uint8_t*)&GCLK->GENCTRL.reg) = generator; + /* Obtain the enabled status */ + enabled = (GCLK->GENCTRL.reg & GCLK_GENCTRL_GENEN); + + system_interrupt_leave_critical_section(); + + return enabled; +} + +/** + * \brief Retrieves the clock frequency of a Generic Clock generator. + * + * Determines the clock frequency (in Hz) of a specified Generic Clock + * generator, used as a source to a Generic Clock Channel module. + * + * \param[in] generator Generic Clock Generator index + * + * \return The frequency of the generic clock generator, in Hz. + */ +uint32_t system_gclk_gen_get_hz( + const uint8_t generator) +{ + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + system_interrupt_enter_critical_section(); + + /* Select the appropriate generator */ + *((uint8_t*)&GCLK->GENCTRL.reg) = generator; + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + /* Get the frequency of the source connected to the GCLK generator */ + uint32_t gen_input_hz = system_clock_source_get_hz( + (enum system_clock_source)GCLK->GENCTRL.bit.SRC); + + *((uint8_t*)&GCLK->GENCTRL.reg) = generator; + + uint8_t divsel = GCLK->GENCTRL.bit.DIVSEL; + + /* Select the appropriate generator division register */ + *((uint8_t*)&GCLK->GENDIV.reg) = generator; + while (system_gclk_is_syncing()) { + /* Wait for synchronization */ + }; + + uint32_t divider = GCLK->GENDIV.bit.DIV; + + system_interrupt_leave_critical_section(); + + /* Check if the generator is using fractional or binary division */ + if (!divsel && divider > 1) { + gen_input_hz /= divider; + } else if (divsel) { + gen_input_hz >>= (divider+1); + } + + return gen_input_hz; +} + +/** + * \brief Writes a Generic Clock configuration to the hardware module. + * + * Writes out a given configuration of a Generic Clock configuration to the + * hardware module. If the clock is currently running, it will be stopped. + * + * \note Once called the clock will not be running; to start the clock, + * call \ref system_gclk_chan_enable() after configuring a clock channel. + * + * \param[in] channel Generic Clock channel to configure + * \param[in] config Configuration settings for the clock + * + */ +void system_gclk_chan_set_config( + const uint8_t channel, + struct system_gclk_chan_config *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Cache the new config to reduce sync requirements */ + uint32_t new_clkctrl_config = (channel << GCLK_CLKCTRL_ID_Pos); + + /* Select the desired generic clock generator */ + new_clkctrl_config |= config->source_generator << GCLK_CLKCTRL_GEN_Pos; + + /* Disable generic clock channel */ + system_gclk_chan_disable(channel); + + /* Write the new configuration */ + GCLK->CLKCTRL.reg = new_clkctrl_config; +} + +/** + * \brief Enables a Generic Clock that was previously configured. + * + * Starts the clock generation of a Generic Clock that was previously + * configured via a call to \ref system_gclk_chan_set_config(). + * + * \param[in] channel Generic Clock channel to enable + */ +void system_gclk_chan_enable( + const uint8_t channel) +{ + system_interrupt_enter_critical_section(); + + /* Select the requested generator channel */ + *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; + + /* Enable the generic clock */ + GCLK->CLKCTRL.reg |= GCLK_CLKCTRL_CLKEN; + + system_interrupt_leave_critical_section(); +} + +/** + * \brief Disables a Generic Clock that was previously enabled. + * + * Stops the clock generation of a Generic Clock that was previously started + * via a call to \ref system_gclk_chan_enable(). + * + * \param[in] channel Generic Clock channel to disable + */ +void system_gclk_chan_disable( + const uint8_t channel) +{ + system_interrupt_enter_critical_section(); + + /* Select the requested generator channel */ + *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; + + /* Sanity check WRTLOCK */ + Assert(!GCLK->CLKCTRL.bit.WRTLOCK); + + /* Switch to known-working source so that the channel can be disabled */ + uint32_t prev_gen_id = GCLK->CLKCTRL.bit.GEN; + GCLK->CLKCTRL.bit.GEN = 0; + + /* Disable the generic clock */ + GCLK->CLKCTRL.reg &= ~GCLK_CLKCTRL_CLKEN; + while (GCLK->CLKCTRL.reg & GCLK_CLKCTRL_CLKEN) { + /* Wait for clock to become disabled */ + } + + /* Restore previous configured clock generator */ + GCLK->CLKCTRL.bit.GEN = prev_gen_id; + + system_interrupt_leave_critical_section(); +} + +/** + * \brief Determins if the specified Generic Clock channel is enabled. + * + * \param[in] channel Generic Clock Channel index + * + * \return The enabled status. + * \retval true The Generic Clock channel is enabled + * \retval false The Generic Clock channel is disabled + */ +bool system_gclk_chan_is_enabled( + const uint8_t channel) +{ + bool enabled; + + system_interrupt_enter_critical_section(); + + /* Select the requested generic clock channel */ + *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; + enabled = GCLK->CLKCTRL.bit.CLKEN; + + system_interrupt_leave_critical_section(); + + return enabled; +} + +/** + * \brief Locks a Generic Clock channel from further configuration writes. + * + * Locks a generic clock channel from further configuration writes. It is only + * possible to unlock the channel configuration through a power on reset. + * + * \param[in] channel Generic Clock channel to enable + */ +void system_gclk_chan_lock( + const uint8_t channel) +{ + system_interrupt_enter_critical_section(); + + /* Select the requested generator channel */ + *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; + + /* Lock the generic clock */ + GCLK->CLKCTRL.reg |= GCLK_CLKCTRL_WRTLOCK; + + system_interrupt_leave_critical_section(); +} + +/** + * \brief Determins if the specified Generic Clock channel is locked. + * + * \param[in] channel Generic Clock Channel index + * + * \return The lock status. + * \retval true The Generic Clock channel is locked + * \retval false The Generic Clock channel is not locked + */ +bool system_gclk_chan_is_locked( + const uint8_t channel) +{ + bool locked; + + system_interrupt_enter_critical_section(); + + /* Select the requested generic clock channel */ + *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; + locked = GCLK->CLKCTRL.bit.WRTLOCK; + + system_interrupt_leave_critical_section(); + + return locked; +} + +/** + * \brief Retrieves the clock frequency of a Generic Clock channel. + * + * Determines the clock frequency (in Hz) of a specified Generic Clock + * channel, used as a source to a device peripheral module. + * + * \param[in] channel Generic Clock Channel index + * + * \return The frequency of the generic clock channel, in Hz. + */ +uint32_t system_gclk_chan_get_hz( + const uint8_t channel) +{ + uint8_t gen_id; + + system_interrupt_enter_critical_section(); + + /* Select the requested generic clock channel */ + *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; + gen_id = GCLK->CLKCTRL.bit.GEN; + + system_interrupt_leave_critical_section(); + + /* Return the clock speed of the associated GCLK generator */ + return system_gclk_gen_get_hz(gen_id); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/gclk.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/gclk.h new file mode 100644 index 0000000..1e3caf3 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/gclk.h @@ -0,0 +1,307 @@ +/** + * \file + * + * \brief SAM Generic Clock Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef SYSTEM_CLOCK_GCLK_H_INCLUDED +#define SYSTEM_CLOCK_GCLK_H_INCLUDED + +/** + * \addtogroup asfdoc_sam0_system_clock_group + * + * @{ + */ + +#include "compiler.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief List of available GCLK generators. + * + * List of Available GCLK generators. This enum is used in the peripheral + * device drivers to select the GCLK generator to be used for its operation. + * + * The number of GCLK generators available is device dependent. + */ +enum gclk_generator { + /** GCLK generator channel 0 */ + GCLK_GENERATOR_0, +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 0) + /** GCLK generator channel 1 */ + GCLK_GENERATOR_1, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 1) + /** GCLK generator channel 2 */ + GCLK_GENERATOR_2, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 2) + /** GCLK generator channel 3 */ + GCLK_GENERATOR_3, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 3) + /** GCLK generator channel 4 */ + GCLK_GENERATOR_4, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 4) + /** GCLK generator channel 5 */ + GCLK_GENERATOR_5, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 5) + /** GCLK generator channel 6 */ + GCLK_GENERATOR_6, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 6) + /** GCLK generator channel 7 */ + GCLK_GENERATOR_7, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 7) + /** GCLK generator channel 8 */ + GCLK_GENERATOR_8, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 8) + /** GCLK generator channel 9 */ + GCLK_GENERATOR_9, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 9) + /** GCLK generator channel 10 */ + GCLK_GENERATOR_10, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 10) + /** GCLK generator channel 11 */ + GCLK_GENERATOR_11, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 11) + /** GCLK generator channel 12 */ + GCLK_GENERATOR_12, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 12) + /** GCLK generator channel 13 */ + GCLK_GENERATOR_13, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 13) + /** GCLK generator channel 14 */ + GCLK_GENERATOR_14, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 14) + /** GCLK generator channel 15 */ + GCLK_GENERATOR_15, +#endif +#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 15) + /** GCLK generator channel 16 */ + GCLK_GENERATOR_16, +#endif +}; + +/** + * \brief Generic Clock Generator configuration structure. + * + * Configuration structure for a Generic Clock Generator channel. This + * structure should be initialized by the + * \ref system_gclk_gen_get_config_defaults() function before being modified by + * the user application. + */ +struct system_gclk_gen_config { + /** Source clock input channel index, see the \ref system_clock_source */ + uint8_t source_clock; + /** If \c true, the generator output level is high when disabled */ + bool high_when_disabled; + /** Integer division factor of the clock output compared to the input */ + uint32_t division_factor; + /** If \c true, the clock is kept enabled during device standby mode */ + bool run_in_standby; + /** If \c true, enables GCLK generator clock output to a GPIO pin */ + bool output_enable; +}; + +/** + * \brief Generic Clock configuration structure. + * + * Configuration structure for a Generic Clock channel. This structure + * should be initialized by the \ref system_gclk_chan_get_config_defaults() + * function before being modified by the user application. + */ +struct system_gclk_chan_config { + /** Generic Clock Generator source channel */ + enum gclk_generator source_generator; +}; + +/** \name Generic Clock Management + * @{ + */ +void system_gclk_init(void); + +/** @} */ + + +/** + * \name Generic Clock Management (Generators) + * @{ + */ + +/** + * \brief Initializes a Generic Clock Generator configuration structure to defaults. + * + * Initializes a given Generic Clock Generator configuration structure to + * a set of known default values. This function should be called on all + * new instances of these configuration structures before being modified + * by the user application. + * + * The default configuration is: + * \li Clock is generated undivided from the source frequency + * \li Clock generator output is low when the generator is disabled + * \li The input clock is sourced from input clock channel 0 + * \li Clock will be disabled during sleep + * \li The clock output will not be routed to a physical GPIO pin + * + * \param[out] config Configuration structure to initialize to default values + */ +static inline void system_gclk_gen_get_config_defaults( + struct system_gclk_gen_config *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Default configuration values */ + config->division_factor = 1; + config->high_when_disabled = false; +#if SAML21 || SAML22 + config->source_clock = GCLK_SOURCE_OSC16M; +#elif (SAMC20) || (SAMC21) + config->source_clock = GCLK_SOURCE_OSC48M; +#else + config->source_clock = GCLK_SOURCE_OSC8M; +#endif + config->run_in_standby = false; + config->output_enable = false; +} + +void system_gclk_gen_set_config( + const uint8_t generator, + struct system_gclk_gen_config *const config); + +void system_gclk_gen_enable( + const uint8_t generator); + +void system_gclk_gen_disable( + const uint8_t generator); + +bool system_gclk_gen_is_enabled( + const uint8_t generator); + +/** @} */ + + +/** + * \name Generic Clock Management (Channels) + * @{ + */ + +/** + * \brief Initializes a Generic Clock configuration structure to defaults. + * + * Initializes a given Generic Clock configuration structure to a set of + * known default values. This function should be called on all new + * instances of these configuration structures before being modified by the + * user application. + * + * The default configuration is as follows: + * \li Clock is sourced from the Generic Clock Generator channel 0 + * \li Clock configuration will not be write-locked when set + * + * \param[out] config Configuration structure to initialize to default values + */ +static inline void system_gclk_chan_get_config_defaults( + struct system_gclk_chan_config *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Default configuration values */ + config->source_generator = GCLK_GENERATOR_0; +} + +void system_gclk_chan_set_config( + const uint8_t channel, + struct system_gclk_chan_config *const config); + +void system_gclk_chan_enable( + const uint8_t channel); + +void system_gclk_chan_disable( + const uint8_t channel); + +bool system_gclk_chan_is_enabled( + const uint8_t channel); + +void system_gclk_chan_lock( + const uint8_t channel); + +bool system_gclk_chan_is_locked( + const uint8_t channel); + +/** @} */ + + +/** + * \name Generic Clock Frequency Retrieval + * @{ + */ + +uint32_t system_gclk_gen_get_hz( + const uint8_t generator); + +uint32_t system_gclk_chan_get_hz( + const uint8_t channel); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/i2s.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/i2s.c new file mode 100644 index 0000000..31fe2d9 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/i2s.c @@ -0,0 +1,750 @@ +/** + * \file + * + * \brief SAM I2S - Inter-IC Sound Controller + * + * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#include "i2s.h" + +/** + * \brief Initializes a hardware I2S module instance + * + * Enables the clock and initialize the I2S module. + * + * \param[in,out] module_inst Pointer to the software module instance struct + * \param[in] hw Pointer to the TCC hardware module + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The module was initialized successfully + * \retval STATUS_BUSY Hardware module was busy when the + * initialization procedure was attempted + * \retval STATUS_ERR_DENIED Hardware module was already enabled + */ +enum status_code i2s_init( + struct i2s_module *const module_inst, + I2s *hw) +{ + Assert(module_inst); + Assert(hw); + + /* Enable the user interface clock in the PM */ + system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, PM_APBCMASK_I2S); + + /* Status check */ + uint32_t ctrla; + ctrla = module_inst->hw->CTRLA.reg; + if (ctrla & I2S_CTRLA_ENABLE) { + if (ctrla & (I2S_CTRLA_SEREN1 | + I2S_CTRLA_SEREN0 | I2S_CTRLA_CKEN1 | I2S_CTRLA_CKEN0)) { + return STATUS_BUSY; + } else { + return STATUS_ERR_DENIED; + } + } + + /* Initialize module */ + module_inst->hw = hw; + + /* Initialize serializers */ +#if I2S_CALLBACK_MODE == true + int i, j; + for (i = 0; i < 2; i ++) { + for (j = 0; j < I2S_SERIALIZER_CALLBACK_N; j ++) { + module_inst->serializer[i].callback[j] = NULL; + } + module_inst->serializer[i].registered_callback_mask = 0; + module_inst->serializer[i].enabled_callback_mask = 0; + + module_inst->serializer[i].job_buffer = NULL; + module_inst->serializer[i].job_status = STATUS_OK; + module_inst->serializer[i].requested_words = 0; + module_inst->serializer[i].transferred_words = 0; + + module_inst->serializer[i].mode = I2S_SERIALIZER_RECEIVE; + module_inst->serializer[i].data_size = I2S_DATA_SIZE_32BIT; + } + + _i2s_instances[0] = module_inst; + + system_interrupt_enable(SYSTEM_INTERRUPT_MODULE_I2S); +#endif + + return STATUS_OK; +} + + +/** + * \brief Configure specified I2S clock unit + * + * Enables the clock and initialize the clock unit, based on the given + * configurations. + * + * \param[in,out] module_inst Pointer to the software module instance struct + * \param[in] clock_unit I2S clock unit to initialize and configure + * \param[in] config Pointer to the I2S clock unit configuration + * options struct + * + * \return Status of the configuration procedure. + * + * \retval STATUS_OK The module was initialized successfully + * \retval STATUS_BUSY Hardware module was busy when the + * configuration procedure was attempted + * \retval STATUS_ERR_DENIED Hardware module was already enabled + * \retval STATUS_ERR_INVALID_ARG Invalid divider value or + * MCK direction setting conflict + */ +enum status_code i2s_clock_unit_set_config( + struct i2s_module *const module_inst, + const enum i2s_clock_unit clock_unit, + const struct i2s_clock_unit_config *config) +{ + Assert(module_inst); + Assert(module_inst->hw); + Assert(clock_unit < I2S_CLOCK_UNIT_N); + Assert(config); + + /* Status check */ + uint32_t ctrla, syncbusy; + syncbusy = module_inst->hw->SYNCBUSY.reg; + ctrla = module_inst->hw->CTRLA.reg; + + /* Busy ? */ + if (syncbusy & (I2S_SYNCBUSY_CKEN0 << clock_unit)) { + return STATUS_BUSY; + } + /* Already enabled ? */ + if (ctrla & (I2S_CTRLA_CKEN0 << clock_unit)) { + return STATUS_ERR_DENIED; + } + /* Parameter check */ + if (config->clock.mck_src && config->clock.mck_out_enable) { + return STATUS_ERR_INVALID_ARG; + } + + /* Initialize Clock Unit */ + uint32_t clkctrl = + (config->clock.mck_out_invert ? I2S_CLKCTRL_MCKOUTINV : 0) | + (config->clock.sck_out_invert ? I2S_CLKCTRL_SCKOUTINV : 0) | + (config->frame.frame_sync.invert_out ? I2S_CLKCTRL_FSOUTINV : 0) | + (config->clock.mck_out_enable ? I2S_CLKCTRL_MCKEN : 0) | + (config->clock.mck_src ? I2S_CLKCTRL_MCKSEL : 0) | + (config->clock.sck_src ? I2S_CLKCTRL_SCKSEL : 0) | + (config->frame.frame_sync.invert_use ? I2S_CLKCTRL_FSINV : 0) | + (config->frame.frame_sync.source ? I2S_CLKCTRL_FSSEL : 0) | + (config->frame.data_delay ? I2S_CLKCTRL_BITDELAY : 0); + + uint8_t div_val = config->clock.mck_out_div; + if ((div_val > 0x21) || (div_val == 0)) { + return STATUS_ERR_INVALID_ARG; + } else { + div_val --; + } + clkctrl |= I2S_CLKCTRL_MCKOUTDIV(div_val); + + div_val = config->clock.sck_div; + if ((div_val > 0x21) || (div_val == 0)) { + return STATUS_ERR_INVALID_ARG; + } else { + div_val --; + } + clkctrl |= I2S_CLKCTRL_MCKDIV(div_val); + + uint8_t number_slots = config->frame.number_slots; + if (number_slots > 8) { + return STATUS_ERR_INVALID_ARG; + } else if (number_slots > 0) { + number_slots --; + } + clkctrl |= + I2S_CLKCTRL_NBSLOTS(number_slots) | + I2S_CLKCTRL_FSWIDTH(config->frame.frame_sync.width) | + I2S_CLKCTRL_SLOTSIZE(config->frame.slot_size); + + /* Write clock unit configurations */ + module_inst->hw->CLKCTRL[clock_unit].reg = clkctrl; + + /* Select general clock source */ + const uint8_t i2s_gclk_ids[2] = {I2S_GCLK_ID_0, I2S_GCLK_ID_1}; + struct system_gclk_chan_config gclk_chan_config; + system_gclk_chan_get_config_defaults(&gclk_chan_config); + gclk_chan_config.source_generator = config->clock.gclk_src; + system_gclk_chan_set_config(i2s_gclk_ids[clock_unit], &gclk_chan_config); + system_gclk_chan_enable(i2s_gclk_ids[clock_unit]); + + /* Initialize pins */ + struct system_pinmux_config pin_config; + system_pinmux_get_config_defaults(&pin_config); + if (config->mck_pin.enable) { + pin_config.mux_position = config->mck_pin.mux; + system_pinmux_pin_set_config(config->mck_pin.gpio, &pin_config); + } + if (config->sck_pin.enable) { + pin_config.mux_position = config->sck_pin.mux; + system_pinmux_pin_set_config(config->sck_pin.gpio, &pin_config); + } + if (config->fs_pin.enable) { + pin_config.mux_position = config->fs_pin.mux; + system_pinmux_pin_set_config(config->fs_pin.gpio, &pin_config); + } + + return STATUS_OK; +} + + +/** + * \brief Configure specified I2S serializer + * + * Enables the clock and initialize the serializer, based on the given + * configurations. + * + * \param[in,out] module_inst Pointer to the software module instance struct + * \param[in] serializer I2S serializer to initialize and configure + * \param[in] config Pointer to the I2S serializer configuration + * options struct + * + * \return Status of the configuration procedure. + * + * \retval STATUS_OK The module was initialized successfully + * \retval STATUS_BUSY Hardware module was busy when the + * configuration procedure was attempted + * \retval STATUS_ERR_DENIED Hardware module was already enabled + */ +enum status_code i2s_serializer_set_config( + struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + const struct i2s_serializer_config *config) +{ + Assert(module_inst); + Assert(module_inst->hw); + Assert(serializer < I2S_SERIALIZER_N); + Assert(config); + + /* Status check */ + uint32_t ctrla, syncbusy; + syncbusy = module_inst->hw->SYNCBUSY.reg; + ctrla = module_inst->hw->CTRLA.reg; + + /* Busy ? */ + if (syncbusy & ((I2S_SYNCBUSY_SEREN0 | I2S_SYNCBUSY_DATA0) << serializer)) { + return STATUS_BUSY; + } + /* Already enabled ? */ + if (ctrla & (I2S_CTRLA_CKEN0 << serializer)) { + return STATUS_ERR_DENIED; + } + + /* Initialize Serializer */ + uint32_t serctrl = + (config->loop_back ? I2S_SERCTRL_RXLOOP : 0) | + (config->dma_usage ? I2S_SERCTRL_DMA : 0) | + (config->mono_mode ? I2S_SERCTRL_MONO : 0) | + (config->disable_data_slot[7] ? I2S_SERCTRL_SLOTDIS7 : 0) | + (config->disable_data_slot[6] ? I2S_SERCTRL_SLOTDIS6 : 0) | + (config->disable_data_slot[5] ? I2S_SERCTRL_SLOTDIS5 : 0) | + (config->disable_data_slot[4] ? I2S_SERCTRL_SLOTDIS4 : 0) | + (config->disable_data_slot[3] ? I2S_SERCTRL_SLOTDIS3 : 0) | + (config->disable_data_slot[2] ? I2S_SERCTRL_SLOTDIS2 : 0) | + (config->disable_data_slot[1] ? I2S_SERCTRL_SLOTDIS1 : 0) | + (config->disable_data_slot[0] ? I2S_SERCTRL_SLOTDIS0 : 0) | + (config->transfer_lsb_first ? I2S_SERCTRL_BITREV : 0) | + (config->data_adjust_left_in_word ? I2S_SERCTRL_WORDADJ : 0) | + (config->data_adjust_left_in_slot ? I2S_SERCTRL_SLOTADJ : 0) | + (config->data_padding ? I2S_SERCTRL_TXSAME : 0); + + if (config->clock_unit < I2S_CLOCK_UNIT_N) { + serctrl |= (config->clock_unit ? I2S_SERCTRL_CLKSEL : 0); + } else { + return STATUS_ERR_INVALID_ARG; + } + + serctrl |= + I2S_SERCTRL_SERMODE(config->mode) | + I2S_SERCTRL_TXDEFAULT(config->line_default_state) | + I2S_SERCTRL_DATASIZE(config->data_size) | + I2S_SERCTRL_EXTEND(config->bit_padding); + + /* Write Serializer configuration */ + module_inst->hw->SERCTRL[serializer].reg = serctrl; + + /* Initialize pins */ + struct system_pinmux_config pin_config; + system_pinmux_get_config_defaults(&pin_config); + if (config->data_pin.enable) { + pin_config.mux_position = config->data_pin.mux; + system_pinmux_pin_set_config(config->data_pin.gpio, &pin_config); + } + + /* Save configure */ + module_inst->serializer[serializer].mode = config->mode; + module_inst->serializer[serializer].data_size = config->data_size; + + return STATUS_OK; +} + + + +/** + * \brief Retrieves the current module status. + * + * Retrieves the status of the module, giving overall state information. + * + * \param[in] module_inst Pointer to the I2S software instance struct + * + * \return Bitmask of \c I2S_STATUS_* flags + * + * \retval I2S_STATUS_SYNC_BUSY Module is busy synchronization + * \retval I2S_STATUS_TRANSMIT_UNDERRUN(x) Serializer x (0~1) is underrun + * \retval I2S_STATUS_TRANSMIT_READY(x) Serializer x (0~1) is ready to + * transmit new data word + * \retval I2S_STATUS_RECEIVE_OVERRUN(x) Serializer x (0~1) is overrun + * \retval I2S_STATUS_RECEIVE_READY(x) Serializer x (0~1) has data ready to + * read + */ +uint32_t i2s_get_status( + const struct i2s_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + uint32_t intflag = module_inst->hw->INTFLAG.reg; + uint32_t status; + if (module_inst->hw->SYNCBUSY.reg) { + status = I2S_STATUS_SYNC_BUSY; + } else { + status = 0; + } + if (intflag & I2S_INTFLAG_TXUR0) { + status |= I2S_STATUS_TRANSMIT_UNDERRUN(0); + } + if (intflag & I2S_INTFLAG_TXUR1) { + status |= I2S_STATUS_TRANSMIT_UNDERRUN(1); + } + if ((intflag & I2S_INTFLAG_TXRDY0) && + !module_inst->hw->SYNCBUSY.bit.DATA0) { + status |= I2S_STATUS_TRANSMIT_READY(0); + } + if ((intflag & I2S_INTFLAG_TXRDY1) && + !module_inst->hw->SYNCBUSY.bit.DATA1) { + status |= I2S_STATUS_TRANSMIT_READY(1); + } + if (intflag & I2S_INTFLAG_RXOR0) { + status |= I2S_STATUS_RECEIVE_OVERRUN(0); + } + if (intflag & I2S_INTFLAG_RXOR1) { + status |= I2S_STATUS_RECEIVE_OVERRUN(1); + } + if (intflag & I2S_INTFLAG_RXRDY0) { + status |= I2S_STATUS_RECEIVE_READY(0); + } + if (intflag & I2S_INTFLAG_RXRDY1) { + status |= I2S_STATUS_RECEIVE_READY(1); + } + return status; +} + +/** + * \brief Clears a module status flags. + * + * Clears the given status flags of the module. + * + * \param[in] module_inst Pointer to the I2S software instance struct + * \param[in] status Bitmask of \c I2S_STATUS_* flags to clear + */ +void i2s_clear_status( + const struct i2s_module *const module_inst, + uint32_t status) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + uint32_t intflag = 0; + + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { + intflag = I2S_INTFLAG_TXUR0; + } + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { + intflag = I2S_INTFLAG_TXUR1; + } + if (status & I2S_STATUS_TRANSMIT_READY(0)) { + intflag = I2S_INTFLAG_TXRDY0; + } + if (status & I2S_STATUS_TRANSMIT_READY(1)) { + intflag = I2S_INTFLAG_TXRDY1; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { + intflag = I2S_INTFLAG_RXOR0; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { + intflag = I2S_INTFLAG_RXOR1; + } + if (status & I2S_STATUS_RECEIVE_READY(0)) { + intflag = I2S_INTFLAG_RXRDY0; + } + if (status & I2S_STATUS_RECEIVE_READY(1)) { + intflag = I2S_INTFLAG_RXRDY1; + } + module_inst->hw->INTFLAG.reg = intflag; +} + +/** + * \brief Enable interrupts on status set + * + * Enable the given status interrupt request from the I2S module. + * + * \param[in] module_inst Pointer to the I2S software instance struct + * \param[in] status Status interrupts to enable + * + * \return Status of enable procedure + * + * \retval STATUS_OK Interrupt is enabled successfully + * \retval STATUS_ERR_INVALID_ARG Status with no interrupt is passed + */ +enum status_code i2s_enable_status_interrupt( + struct i2s_module *const module_inst, + uint32_t status) +{ + /* Sanity check arguments */ + Assert(module_inst); + + /* No sync busy interrupt */ + if (status & I2S_STATUS_SYNC_BUSY) { + return STATUS_ERR_INVALID_ARG; + } + Assert(module_inst->hw); + + uint32_t intflag = 0; + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { + intflag = I2S_INTFLAG_TXUR0; + } + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { + intflag = I2S_INTFLAG_TXUR1; + } + if (status & I2S_STATUS_TRANSMIT_READY(0)) { + intflag = I2S_INTFLAG_TXRDY0; + } + if (status & I2S_STATUS_TRANSMIT_READY(1)) { + intflag = I2S_INTFLAG_TXRDY1; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { + intflag = I2S_INTFLAG_RXOR0; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { + intflag = I2S_INTFLAG_RXOR1; + } + if (status & I2S_STATUS_RECEIVE_READY(0)) { + intflag = I2S_INTFLAG_RXRDY0; + } + if (status & I2S_STATUS_RECEIVE_READY(1)) { + intflag = I2S_INTFLAG_RXRDY1; + } + module_inst->hw->INTENSET.reg = intflag; + return STATUS_OK; +} + +/** + * \brief Disable interrupts on status set + * + * Disable the given status interrupt request from the I2S module. + * + * \param[in] module_inst Pointer to the I2S software instance struct + * \param[in] status Status interrupts to disable + */ +void i2s_disable_status_interrupt( + struct i2s_module *const module_inst, + uint32_t status) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + uint32_t intflag = 0; + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { + intflag = I2S_INTFLAG_TXUR0; + } + if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { + intflag = I2S_INTFLAG_TXUR1; + } + if (status & I2S_STATUS_TRANSMIT_READY(0)) { + intflag = I2S_INTFLAG_TXRDY0; + } + if (status & I2S_STATUS_TRANSMIT_READY(1)) { + intflag = I2S_INTFLAG_TXRDY1; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { + intflag = I2S_INTFLAG_RXOR0; + } + if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { + intflag = I2S_INTFLAG_RXOR1; + } + if (status & I2S_STATUS_RECEIVE_READY(0)) { + intflag = I2S_INTFLAG_RXRDY0; + } + if (status & I2S_STATUS_RECEIVE_READY(1)) { + intflag = I2S_INTFLAG_RXRDY1; + } + module_inst->hw->INTENCLR.reg = intflag; +} + + +/** + * \brief Write buffer to the specified Serializer of I2S module + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The serializer to write to + * \param[in] buffer The data buffer to write + * \param[in] size Number of data words to write + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The data was sent successfully + * \retval STATUS_ERR_DENIED The module or serializer is disabled + * \retval STATUS_ERR_INVALID_ARG An invalid buffer pointer was supplied + */ +enum status_code i2s_serializer_write_buffer_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + void *buffer, uint32_t size) +{ + Assert(module_inst); + Assert(module_inst->hw); + Assert(serializer < I2S_SERIALIZER_N); + Assert(buffer); + + if (size == 0) { + return STATUS_OK; + } + + uint8_t data_size = 1; /* number of bytes */ + struct i2s_serializer_module *data_module = (struct i2s_serializer_module *) + &module_inst->serializer[serializer]; + + /* Check buffer */ + switch(data_module->data_size) { + case I2S_DATA_SIZE_32BIT: + case I2S_DATA_SIZE_24BIT: + case I2S_DATA_SIZE_20BIT: + case I2S_DATA_SIZE_18BIT: + if ((uint32_t)buffer & 0x3) { + return STATUS_ERR_INVALID_ARG; + } + data_size = 4; + break; + case I2S_DATA_SIZE_16BIT: + case I2S_DATA_SIZE_16BIT_COMPACT: + if ((uint32_t)buffer & 0x1) { + return STATUS_ERR_INVALID_ARG; + } + data_size = 2; + break; + default: + break; + } + + /* Check status */ + if (!(module_inst->hw->CTRLA.reg & + (I2S_CTRLA_ENABLE | (I2S_CTRLA_SEREN0 << serializer)))) { + return STATUS_ERR_DENIED; + } + + /* Write */ + uint32_t i; + uint32_t sync_bit = I2S_SYNCBUSY_DATA0 << serializer; + uint32_t ready_bit = I2S_INTFLAG_TXRDY0 << serializer; + if (4 == data_size) { + uint32_t *p32 = (uint32_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Tx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + module_inst->hw->DATA[serializer].reg = p32[i]; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } else if (2 == data_size) { + uint16_t *p16 = (uint16_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Tx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + module_inst->hw->DATA[serializer].reg = p16[i]; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } else { + uint8_t *p8 = (uint8_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Tx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + module_inst->hw->DATA[serializer].reg = p8[i]; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } + + return STATUS_OK; +} + +/** + * \brief Read from the specified Serializer of I2S module to a buffer + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The serializer to write to + * \param[in] buffer The buffer to fill read data (NULL to discard) + * \param[in] size Number of data words to read + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The data was sent successfully + * \retval STATUS_ERR_DENIED The module or serializer is disabled + * \retval STATUS_ERR_INVALID_ARG An invalid buffer pointer was supplied + */ +enum status_code i2s_serializer_read_buffer_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + void *buffer, uint32_t size) +{ + Assert(module_inst); + Assert(module_inst->hw); + + if (size == 0) { + return STATUS_OK; + } + + uint8_t data_size = 1; /* number of bytes */ + struct i2s_serializer_module *data_module = (struct i2s_serializer_module *) + &module_inst->serializer[serializer]; + + /* Check buffer */ + switch(data_module->data_size) { + case I2S_DATA_SIZE_32BIT: + case I2S_DATA_SIZE_24BIT: + case I2S_DATA_SIZE_20BIT: + case I2S_DATA_SIZE_18BIT: + if ((uint32_t)buffer & 0x3) { + return STATUS_ERR_INVALID_ARG; + } + data_size = 4; + break; + case I2S_DATA_SIZE_16BIT: + case I2S_DATA_SIZE_16BIT_COMPACT: + if ((uint32_t)buffer & 0x1) { + return STATUS_ERR_INVALID_ARG; + } + data_size = 2; + break; + default: + break; + } + + /* Check status */ + if (!(module_inst->hw->CTRLA.reg & + (I2S_CTRLA_ENABLE | (I2S_CTRLA_SEREN0 << serializer)))) { + return STATUS_ERR_DENIED; + } + + /* Read */ + uint32_t i; + uint32_t sync_bit = I2S_SYNCBUSY_DATA0 << serializer; + uint32_t ready_bit = I2S_INTFLAG_RXRDY0 << serializer; + if (buffer == NULL) { + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Rx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } + else if (4 == data_size) { + uint32_t *p32 = (uint32_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Rx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + p32[i] = module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } else if (2 == data_size) { + uint16_t *p16 = (uint16_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Rx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + p16[i] = module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } else { + uint8_t *p8 = (uint8_t*)buffer; + for (i = 0; i < size; i ++) { + while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait Tx ready */ + } + while(module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait Sync */ + } + p8[i] = module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + } + } + + return STATUS_OK; +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/i2s.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/i2s.h new file mode 100644 index 0000000..9911e6d --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/i2s.h @@ -0,0 +1,1404 @@ +/** + * \file + * + * \brief SAM I2S - Inter-IC Sound Controller + * + * Copyright (c) 2014-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#ifndef I2S_H_INCLUDED +#define I2S_H_INCLUDED + +/** + * \defgroup asfdoc_sam0_i2s_group SAM Inter-IC Sound Controller Driver (I2S) + * + * This driver for Atmel® | SMART SAM devices provides an interface for the configuration + * and management of the device's Inter-IC Sound Controller functionality. + * + * The following driver API modes are covered by this manual: + * - Polled APIs + * \if I2S_CALLBACK_MODE + * - Callback APIs + * \endif + * + * The following peripherals are used by this module: + * - I2S (Inter-IC Sound Controller) + * + * The following devices can use this module: + * - Atmel | SMART SAM D21 + * - Atmel | SMART SAM DA1 + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_i2s_prerequisites + * - \ref asfdoc_sam0_i2s_module_overview + * - \ref asfdoc_sam0_i2s_special_considerations + * - \ref asfdoc_sam0_i2s_extra_info + * - \ref asfdoc_sam0_i2s_examples + * - \ref asfdoc_sam0_i2s_api_overview + * + * \section asfdoc_sam0_i2s_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * \section asfdoc_sam0_i2s_module_overview Module Overview + * + * The I2S provides bidirectional, synchronous, digital audio link with external + * audio devices through these signal pins: + * - Serial Data (SDm) + * - Frame Sync (FSn) + * - Serial Clock (SCKn) + * - Master Clock (MCKn) + * + * The I2S consists of 2 Clock Units and 2 Serializers, which can be separately + * configured and enabled, to provide varies functionalities as follow: + * - Communicate to Audio CODECs as Master or Slave, or provides clock and + * frame sync signals as Controller + * - Communicate to DAC or ADC through dedicated I2S serial interface + * - Communicate to multi-slot or multiple stereo DACs or ADCs, via + * Time Division Multiplexed (TDM) format + * - Reading mono or stereo MEMS microphones, using the Pulse Density + * Modulation (PDM) interface + * + * The I2S supports compact stereo data word, where left channel data bits are + * in lower half and right channel data bits are in upper half. It reduces the + * number of data words for stereo audio data and the DMA bandwidth. + * + * In master mode, the frame is configured by number of slots and slot size, and + * allows range covering 16fs to 1024fs MCK, to provide oversampling clock to an + * external audio CODEC or digital signal processor (DSP). + * + * A block diagram of the I2S can be seen in + * \ref asfdoc_sam0_i2s_module_block_diagram "the figure below". + * + * \anchor asfdoc_sam0_i2s_module_block_diagram + * \image html i2s_blocks.svg "I2S Block Diagram" + * + * This driver for I2S module provides an interface to + * - initialize and control I2S module + * - configure and control the I2S Clock Unit and Serializer + * - transmit/receive data through I2S Serializer + * + * \subsection asfdoc_sam0_i2s_module_overview_clocks Clocks + * + * To use I2S module, the I2S bus interface clock (clk_i2s) must be enabled via + * Power Manager. + * + * For each I2S Clock Unit, a generic clock (gclk_i2s_n) is connnected. When I2S + * works in master mode the generic clock is used. It should be prepared before + * clock unit is used. In master mode the input generic clock will be used as + * MCK for SCKn and FSn generation, in addition, the MCK could be devided and + * output to I2S MCKn pin, as oversampling clock to external audio device. + * + * The I2S Serializer uses clock and control signal from Clock Unit to handle + * transfer. Select different clock unit with different configurations allows + * the I2S to work as master or slave, to work on non-related clocks. + * + * When using the driver with ASF, enabling the register interface is normally + * done by the \c init function. + * The gclk source for the asynchronous domain is normally configured and set + * through the _configuration struct_ / _init_ function. + * If gclk source != 0 is used, this source has to be configured and enabled + * through invoking the system_gclk driver function when needed, or modifying + * conf_clock.h to enable it at the beginning. + * + * \subsection asfdoc_sam0_i2s_module_overview_frame Audio Frame Generation + * + * Audio sample data for all channels are sent in frames, one frame can consist + * 1 - 8 slots where each slot can be configured to a size 8-bit, 16-bit, 24-bit + * or 32-bit. The audio frame synch clock is generated by the I2S Clock unit in + * the master/controller mode. The frame rate (or frame sync frequency) is + * calculated as follow: + * + * FS = SCK / number_of_slots / number_of_bits_in_slot + * + * The serial clock (SCK) source is either an external source (slave mode) or + * generated by the I2S clock unit (controller or master mode) using the MCK as + * source. + * + * SCK = MCK / sck_div + * \note SCK generation division value is MCKDIV in register. + * + * MCK is either an external source or generated using the gclk input from a + * generic clock generator. + * + * \subsection asfdoc_sam0_i2s_module_overview_mode Master, Controller and Slave modes + * + * The i2s module has three modes: master, controller and slave. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_mode_mst Master + * In master mode the module will control the data flow on the i2s bus and can + * be responsible for clock generation. The Serializers are enabled and will + * transmit/receive data. On a bus with only master and slave the SCK and FS + * clock signal will be outputted on the SCK and FS pin on the master module. + * MCK can optionally be outputted on the MCK pin, if there is a controller + * module on the bus the SCK, FS and optionally the MCK clock is sourced from + * the same pins. Serial data will be trancieved on the SD pin in both + * scenarios. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_mode_ctl Controller + * In controller mode the module will generate the clock signals, but the + * Serializers are disabled and no data will be transmitted/received by the + * module in this mode. The clock signals is outputted on the SCK, FS and + * optionally the MCK pin. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_mode_slv Slave + * In slave mode the module will use the SCK and FS clock source from the master + * or the controller which is received on the SCK and FS pin. The MCK can + * optionally be sourced externally on the MCK pin. The Serializers are enabled + * and will tranceive data on the SD pin. All data flow is controlled by the + * master. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_mode_chg Switch modes + * The mode switching between master, controller and slave modes are actually + * done by modifying the source mode of I2S pins. + * The source mode of I2S pins are selected by writing corresponding bits in + * CLKCTRLn. + * Since source mode switching changes the direction of pin, the mode must be + * changed when the I2S Clock Unit is stopped. + * + * \subsection asfdoc_sam0_i2s_module_overview_data Data Stream Reception/Transmission + * + * The I2S module support several data stream formats: + * - I2S format + * - Time Division Multiplexed (TDM) format + * - Pulse Density Modulation (PDM) format (reception only) + * + * Basically the I2S module can send several words within each frame, it's more + * like TDM format. With adjust to the number of data words in a frame, the FS + * width, the FS to data bits delay, etc., the module is able to handle I2S + * compliant data stream. + * + * Also the Serializer can receive PDM format data stream, which allows the I2S + * module receive 1 PDM data on each SCK edge. + * + * \subsubsection asfdoc_sam0_i2s_module_overview_data_i2s I2S Stream Reception/Transmission + * + * For 2-channel I2S compliant data stream format the i2s module uses the FS + * line as word select (WS) signal and will send left channel data word on low + * WS level and right channel data word on high WS level as specified in the I2S + * standard. The supported word sizes are 8-, 16-, 18-, 20-, 24- and 32- bit. + * + * Thus for I2S stream, the following settings should be applied to the module: + * - Data starting delay after FS transition : one SCK period + * - FS width : half of frame + * - Data bits adjust in word : left-adjusted + * - Bit transmitting order : MSB first + * + * Following is an example for I2S application connections and waveforms. See + * \ref asfdoc_sam0_i2s_module_i2s_example_diagram "the figure below". + * + * \anchor asfdoc_sam0_i2s_module_i2s_example_diagram + * \image html i2s_example.svg "I2S Example Diagram" + * + * \subsubsection asfdoc_sam0_i2s_module_overview_data_tdm TDM Stream Reception/Transmission + * In TDM format, the module sends several data words in each frame. For this + * data stream format most of the configurations could be adjusted: + * - Main Frame related settings are as follow: + * - Frame Sync (FS) options: + * - the active edge of the FS (or if FS is inverted before use) + * - the width of the FS + * - the delay between FS to first data bit + * - Data alignment in slot + * - The number of slots and slot size can be adjusted, it has been mentioned + * in \ref asfdoc_sam0_i2s_module_overview_frame + * - The data word size is controlled by Serializer, it can be chosen among + * 8, 16, 18, 20, 24 and 32 bits. + * + * The general TDM waveform generation is as follow: + * + * \anchor asfdoc_sam0_i2s_module_tdm_wave_diagram + * \image html tdm_wave.svg "TDM Waveform generation" + * + * Some other settings could also be found to set up clock, data formatting and + * pin mux. + * refer to \ref i2s_clock_unit_config "Clock Unit Configurations" + * and \ref i2s_serializer_config "Serializer Configurations" for more + * details. + * + * Following is examples for different application use cases. + * + * See \ref asfdoc_sam0_i2s_module_tdm_timeslot_example_diagram "here" for + * the Time Slot Application connection and waveform example. + * + * \anchor asfdoc_sam0_i2s_module_tdm_timeslot_example_diagram + * \image html tdm_timeslot_example.svg "Codec Example Diagram" + * + * See \ref asfdoc_sam0_i2s_module_tdm_codec_example_diagram "here" for the + * Codec Application connection and waveform example. + * + * \anchor asfdoc_sam0_i2s_module_tdm_codec_example_diagram + * \image html tdm_codec_example.svg "Time Slot Example Diagram" + * + * \subsubsection asfdoc_sam0_i2s_module_overview_data_pdm PDM Reception + * The I2S Serializer integrates PDM reception feature, to use this feature, + * simply select PDM2 mode in Serializer configuration. In PDM2 mode, it assumes + * two microphones are input for stereo stream. The left microphone bits will + * be stored in lower half and right microphone bits in upper half of the data + * word, like in compact stereo format. + * + * See \ref asfdoc_sam0_i2s_module_pdm_example_diagram "following figure" for an + * example of PDM Microphones Application with both left and right channel + * microphone connected. + * + * \anchor asfdoc_sam0_i2s_module_pdm_example_diagram + * \image html pdm_example.svg "Time PDM2 Example Diagram" + * + * \subsubsection asfdoc_sam0_i2s_module_overview_data_fmt MONO and Compact Data + * The I2S Serializer can accept some pre-defined data format and generates + * the data stream in specified way. + * + * When transmitting data, the Serializer can work in MONO mode: assum input + * is single channel mono data on left channel and copy it to right channel + * automatically. + * + * Also the I2S Serializer can support compact stereo data word. The data word + * size of the Serializer can be set to \ref I2S_DATA_SIZE_16BIT_COMPACT + * "16-bit compact" or \ref I2S_DATA_SIZE_8BIT_COMPACT "8-bit compact", with + * these option I2S Serializer will compact left channel data and right channel + * data together, the left channel data will take lower bytes and right channel + * data take higher bytes. + * + * \subsection asfdoc_sam0_i2s_module_overview_loop Loop-back Mode + * The I2S can be configured to loop back the Transmitter to Receiver. In this + * mode Serializer's input will be connected to another Serializer's output + * internally. + * + * \subsection asfdoc_sam0_i2s_module_overview_sleep Sleep Modes + * The I2S will continue to operate in any sleep mode, where the selected source + * clocks are running. + * + * \section asfdoc_sam0_i2s_special_considerations Special Considerations + * + * There is no special considerations for I2S module. + * + * \section asfdoc_sam0_i2s_extra_info Extra Information + * + * For extra information see \ref asfdoc_sam0_i2s_extra. This includes: + * - \ref asfdoc_sam0_i2s_extra_acronyms + * - \ref asfdoc_sam0_i2s_extra_dependencies + * - \ref asfdoc_sam0_i2s_extra_errata + * - \ref asfdoc_sam0_i2s_extra_history + * + * \section asfdoc_sam0_i2s_examples Examples + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_i2s_exqsg. + * + * + * \section asfdoc_sam0_i2s_api_overview API Overview + * @{ + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#if I2S_CALLBACK_MODE == true +# include + +#if !defined(__DOXYGEN__) +extern struct i2s_module *_i2s_instances[I2S_INST_NUM]; +#endif + +/** Forward definition of the device instance */ +struct i2s_module; + +/** Type of the callback functions */ +typedef void (*i2s_serializer_callback_t) + (struct i2s_module *const module); + +/** + * \brief I2S Serializer Callback enum + */ +enum i2s_serializer_callback { + /** Callback for buffer read/write finished */ + I2S_SERIALIZER_CALLBACK_BUFFER_DONE, + /** Callback for Serializer overrun/underrun */ + I2S_SERIALIZER_CALLBACK_OVER_UNDER_RUN, +# if !defined(__DOXYGEN__) + I2S_SERIALIZER_CALLBACK_N +# endif +}; + +#endif /* #if I2S_CALLBACK_MODE == true */ + +/** + * \name Module status flags + * + * I2S status flags, returned by \ref i2s_get_status() and cleared by + * \ref i2s_clear_status(). + * + * @{ + */ + +/** Module Serializer x (0~1) Transmit Underrun */ +#define I2S_STATUS_TRANSMIT_UNDERRUN(x) (1u << ((x)+0)) +/** Module Serializer x (0~1) is ready to accept new data to be transmitted */ +#define I2S_STATUS_TRANSMIT_READY(x) (1u << ((x)+2)) +/** Module Serializer x (0~1) Receive Overrun */ +#define I2S_STATUS_RECEIVE_OVERRUN(x) (1u << ((x)+4)) +/** Module Serializer x (0~1) has received a new data */ +#define I2S_STATUS_RECEIVE_READY(x) (1u << ((x)+6)) +/** Module is busy on synchronization */ +#define I2S_STATUS_SYNC_BUSY (1u << 8) + +/** @} */ + +/** + * Master Clock (MCK) source selection + */ +enum i2s_master_clock_source { + /** Master Clock (MCK) is from general clock */ + I2S_MASTER_CLOCK_SOURCE_GCLK, + /** Master Clock (MCK) is from MCK input pin */ + I2S_MASTER_CLOCK_SOURCE_MCKPIN +}; + +/** + * Serial Clock (SCK) source selection + */ +enum i2s_serial_clock_source { + /** Serial Clock (SCK) is divided from Master Clock */ + I2S_SERIAL_CLOCK_SOURCE_MCKDIV, + /** Serial Clock (SCK) is input from SCK input pin */ + I2S_SERIAL_CLOCK_SOURCE_SCKPIN +}; + +/** + * Data delay from Frame Sync (FS) + */ +enum i2s_data_delay { + /** Left Justified (no delay) */ + I2S_DATA_DELAY_0, + /** I2S data delay (1-bit delay) */ + I2S_DATA_DELAY_1, + /** Left Justified (no delay) */ + I2S_DATA_DELAY_LEFT_JUSTIFIED = I2S_DATA_DELAY_0, + /** I2S data delay (1-bit delay) */ + I2S_DATA_DELAY_I2S = I2S_DATA_DELAY_1 +}; + +/** + * Frame Sync (FS) source + */ +enum i2s_frame_sync_source { + /** Frame Sync (FS) is divided from I2S Serial Clock */ + I2S_FRAME_SYNC_SOURCE_SCKDIV, + /** Frame Sync (FS) is input from FS input pin */ + I2S_FRAME_SYNC_SOURCE_FSPIN +}; + +/** + * Frame Sync (FS) output pulse width + */ +enum i2s_frame_sync_width { + /** Frame Sync (FS) Pulse is 1 Slot width */ + I2S_FRAME_SYNC_WIDTH_SLOT, + /** Frame Sync (FS) Pulse is half a Frame width */ + I2S_FRAME_SYNC_WIDTH_HALF_FRAME, + /** Frame Sync (FS) Pulse is 1 Bit width */ + I2S_FRAME_SYNC_WIDTH_BIT, + /** 1-bit wide Frame Sync (FS) per Data sample, only used when Data transfer + * is requested */ + I2S_FRAME_SYNC_WIDTH_BURST +}; + +/** + * Time Slot Size in number of I2S serial clocks (bits) + */ +enum i2s_slot_size { + /** 8-bit slot */ + I2S_SLOT_SIZE_8_BIT, + /** 16-bit slot */ + I2S_SLOT_SIZE_16_BIT, + /** 24-bit slot */ + I2S_SLOT_SIZE_24_BIT, + /** 32-bit slot */ + I2S_SLOT_SIZE_32_BIT +}; + +/** + * DMA channels usage for I2S + */ +enum i2s_dma_usage { + /** Single DMA channel for all I2S channels */ + I2S_DMA_USE_SINGLE_CHANNEL_FOR_ALL, + /** One DMA channel per data channel */ + I2S_DMA_USE_ONE_CHANNEL_PER_DATA_CHANNEL +}; + +/** + * I2S data format, to extend mono data to 2 channels + */ +enum i2s_data_format { + /** Normal mode, keep data to its right channel */ + I2S_DATA_FORMAT_STEREO, + /** Assume input is mono data for left channel, the data is duplicated to + * right channel */ + I2S_DATA_FORMAT_MONO +}; + +/** + * I2S data bit order + */ +enum i2s_bit_order { + /** Transfer Data Most Significant Bit first (Default for I2S protocol) */ + I2S_BIT_ORDER_MSB_FIRST, + /** Transfer Data Least Significant Bit first */ + I2S_BIT_ORDER_LSB_FIRST +}; + +/** + * I2S data bit padding + */ +enum i2s_bit_padding { + /** Padding with 0 */ + I2S_BIT_PADDING_0, + /** Padding with 1 */ + I2S_BIT_PADDING_1, + /** Padding with MSBit */ + I2S_BIT_PADDING_MSB, + /** Padding with LSBit */ + I2S_BIT_PADDING_LSB, +}; + +/** + * I2S data word adjust + */ +enum i2s_data_adjust { + /** Data is right adjusted in word */ + I2S_DATA_ADJUST_RIGHT, + /** Data is left adjusted in word */ + I2S_DATA_ADJUST_LEFT +}; + +/** + * I2S data word size + */ +enum i2s_data_size { + /** 32-bit */ + I2S_DATA_SIZE_32BIT, + /** 24-bit */ + I2S_DATA_SIZE_24BIT, + /** 20-bit */ + I2S_DATA_SIZE_20BIT, + /** 18-bit */ + I2S_DATA_SIZE_18BIT, + /** 16-bit */ + I2S_DATA_SIZE_16BIT, + /** 16-bit compact stereo */ + I2S_DATA_SIZE_16BIT_COMPACT, + /** 8-bit */ + I2S_DATA_SIZE_8BIT, + /** 8-bit compact stereo */ + I2S_DATA_SIZE_8BIT_COMPACT +}; + +/** + * I2S data slot adjust + */ +enum i2s_slot_adjust { + /** Data is right adjusted in slot */ + I2S_SLOT_ADJUST_RIGHT, + /** Data is left adjusted in slot */ + I2S_SLOT_ADJUST_LEFT +}; + +/** + * I2S data padding + */ +enum i2s_data_padding { + /** Padding 0 in case of under-run */ + I2S_DATA_PADDING_0, + /** Padding last data in case of under-run */ + I2S_DATA_PADDING_SAME_AS_LAST, + /** Padding last data in case of under-run + * (abbr. \c I2S_DATA_PADDING_SAME_AS_LAST) */ + I2S_DATA_PADDING_LAST = I2S_DATA_PADDING_SAME_AS_LAST, + /** Padding last data in case of under-run + * (abbr. \c I2S_DATA_PADDING_SAME_AS_LAST) */ + I2S_DATA_PADDING_SAME = I2S_DATA_PADDING_SAME_AS_LAST +}; + +/** + * I2S line default value when slot disabled + */ +enum i2s_line_default_state { + /** Output default value is 0 */ + I2S_LINE_DEFAULT_0, + /** Output default value is 1 */ + I2S_LINE_DEFAULT_1, + /** Output default value is high impedance */ + I2S_LINE_DEFAULT_HIGH_IMPEDANCE = 3, + /** Output default value is high impedance + * (abbr. \c I2S_LINE_DEFAULT_HIGH_IMPEDANCE) */ + I2S_LINE_DEFAULT_HIZ = I2S_LINE_DEFAULT_HIGH_IMPEDANCE +}; + +/** + * I2S Serializer mode + */ +enum i2s_serializer_mode { + /** Serializer is used to receive data */ + I2S_SERIALIZER_RECEIVE, + /** Serializer is used to transmit data */ + I2S_SERIALIZER_TRANSMIT, + /** Serializer is used to receive PDM data on each clock edge */ + I2S_SERIALIZER_PDM2 +}; + +/** + * I2S clock unit selection + */ +enum i2s_clock_unit { + /** Clock Unit channel 0 */ + I2S_CLOCK_UNIT_0, + /** Clock Unit channel 1 */ + I2S_CLOCK_UNIT_1, + /** Number of Clock Unit channels */ + I2S_CLOCK_UNIT_N +}; + +/** + * I2S Serializer selection + */ +enum i2s_serializer { + /** Serializer channel 0 */ + I2S_SERIALIZER_0, + /** Serializer channel 1 */ + I2S_SERIALIZER_1, + /** Number of Serializer channels */ + I2S_SERIALIZER_N +}; + + +/** + * Configure for I2S pin + */ +struct i2s_pin_config { + /** GPIO index to access the pin */ + uint8_t gpio; + /** Pin function MUX */ + uint8_t mux; + /** Enable this pin for I2S module */ + bool enable; +}; + +/** + * Configure for I2S clock (SCK) + */ +struct i2s_clock_config { + /** Divide generic clock to master clock output (1~32, 0,1 means no div) */ + uint8_t mck_out_div; + /** Divide generic clock to serial clock (1~32, 0,1 means no div) */ + uint8_t sck_div; + /** Clock source selection */ + enum gclk_generator gclk_src; + /** Master clock source selection: generated or input from pin */ + enum i2s_master_clock_source mck_src; + /** Serial clock source selection: generated or input from pin */ + enum i2s_serial_clock_source sck_src; + /** Invert master clock output */ + bool mck_out_invert; + /** Invert serial clock output */ + bool sck_out_invert; + /** Generate MCK clock output */ + bool mck_out_enable; +}; + +/** + * Configure fir I2S frame sync (FS) + */ +struct i2s_frame_sync_config { + /** Frame Sync (FS) generated or input from pin */ + enum i2s_frame_sync_source source; + /** Frame Sync (FS) width */ + enum i2s_frame_sync_width width; + /** Invert Frame Sync (FS) signal before use */ + bool invert_use; + /** Invert Frame Sync (FS) signal before output */ + bool invert_out; +}; + +/** + * Configure fir I2S frame + */ +struct i2s_frame_config { + /** Number of slots in a frame (1~8, 0,1 means minimum 1) */ + uint8_t number_slots; + /** Size of each slot in frame */ + enum i2s_slot_size slot_size; + /** Data delay from Frame Sync (FS) to first data bit */ + enum i2s_data_delay data_delay; + /** Frame sync (FS) */ + struct i2s_frame_sync_config frame_sync; +}; + +/** + * Configure for I2S clock unit + */ +struct i2s_clock_unit_config { + /** Configure clock generation */ + struct i2s_clock_config clock; + /** Configure frame generation */ + struct i2s_frame_config frame; + + /** Configure master clock pin */ + struct i2s_pin_config mck_pin; + /** Configure serial clock pin */ + struct i2s_pin_config sck_pin; + /** Configure frame sync pin */ + struct i2s_pin_config fs_pin; +}; + +/** + * Configure for I2S Serializer + */ +struct i2s_serializer_config { + /** Configure Serializer data pin */ + struct i2s_pin_config data_pin; + + /** Set to \c true to loop-back output to input pin for test */ + bool loop_back; + + /** Set to \c true to assumes mono input and duplicate it (left channel) to + * right channel */ + bool mono_mode; + + /** Disable data slot */ + bool disable_data_slot[8]; + + /** Set to \c true to transfer LSB first, \c false to transfer MSB first */ + bool transfer_lsb_first; + /** Data Word Formatting Adjust, + * set to \c true to adjust bits in word to left */ + bool data_adjust_left_in_word; + /** Data Slot Formatting Adjust, + * set to \c true to adjust words in slot to left */ + bool data_adjust_left_in_slot; + + /** Data Word Size */ + enum i2s_data_size data_size; + /** Data Formatting Bit Extension */ + enum i2s_bit_padding bit_padding; + /** Data padding when under-run */ + enum i2s_data_padding data_padding; + + /** DMA usage */ + enum i2s_dma_usage dma_usage; + + /** Clock unit selection */ + enum i2s_clock_unit clock_unit; + + /** Line default state where slot is disabled */ + enum i2s_line_default_state line_default_state; + + /** Serializer Mode */ + enum i2s_serializer_mode mode; +}; + +/** + * \brief I2S Serializer instance struct + */ +struct i2s_serializer_module { + +#if I2S_CALLBACK_MODE == true + /** Callbacks list for Serializer */ + i2s_serializer_callback_t callback[I2S_SERIALIZER_CALLBACK_N]; + + /** Job buffer */ + void *job_buffer; + /** Requested data words to read/write */ + uint32_t requested_words; + /** Transferred data words for read/write */ + uint32_t transferred_words; + + /** Callback mask for registered callbacks */ + uint8_t registered_callback_mask; + /** Callback mask for enabled callbacks */ + uint8_t enabled_callback_mask; + + /** Status of the ongoing or last transfer job */ + enum status_code job_status; +#endif + + /** Serializer mode */ + enum i2s_serializer_mode mode; + /** Serializer data word size */ + enum i2s_data_size data_size; +}; + +/** + * \brief I2S Software Module instance struct + */ +struct i2s_module { + /** Module HW register access base */ + I2s *hw; + + /** Module Serializer used */ + struct i2s_serializer_module serializer[2]; +}; + +/** + * \brief Determines if the hardware module(s) are currently synchronizing to the bus. + * + * Checks to see if the underlying hardware peripheral module(s) are currently + * synchronizing across multiple clock domains to the hardware bus, This + * function can be used to delay further operations on a module until such time + * that it is ready, to prevent blocking delays for synchronization in the + * user application. + * + * \param[in] module_inst Pointer to the software module instance struct + * + * \return Synchronization status of the underlying hardware module(s). + * + * \retval false If the module has completed synchronization + * \retval true If the module synchronization is ongoing + */ +static inline bool i2s_is_syncing( + const struct i2s_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + return (module_inst->hw->SYNCBUSY.reg > 0); +} + +/** + * \name Driver Initialization + * @{ + */ + +enum status_code i2s_init( + struct i2s_module *const module_inst, + I2s *hw); + +/** @} */ + +/** + * \name Enable/Disable/Reset + * @{ + */ + +/** + * \brief Enable the I2S module. + * + * Enables a I2S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void i2s_enable(const struct i2s_module *const module_inst) +{ + Assert(module_inst); + Assert(module_inst->hw); + + while (module_inst->hw->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg |= I2S_SYNCBUSY_ENABLE; +} + +/** + * \brief Disables the I2S module. + * + * Disables a I2S module. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void i2s_disable(const struct i2s_module *const module_inst) +{ + Assert(module_inst); + Assert(module_inst->hw); + + while (module_inst->hw->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg &= ~I2S_SYNCBUSY_ENABLE; +} + +/** + * \brief Resets the I2S module. + * + * Resets the I2S module, restoring all hardware module registers to their + * default values and disabling the module. The I2S module will not be + * accessible while the reset is being performed. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void i2s_reset(const struct i2s_module *const module_inst) +{ + Assert(module_inst); + Assert(module_inst->hw); + + /* Disable the module if it is running */ + if (module_inst->hw->CTRLA.reg & I2S_CTRLA_ENABLE) { + i2s_disable(module_inst); + while (i2s_is_syncing(module_inst)) { + /* Sync wait */ + } + } + /* Reset the HW module */ + module_inst->hw->CTRLA.reg = I2S_CTRLA_SWRST; +} + +/** @} */ + +/** + * \name Clock Unit Initialization and Configuration + * @{ + */ + +/** + * \brief Initializes config with predefined default values for I2S clock unit. + * + * This function will initialize a given I2S Clock Unit configuration structure + * to a set of known default values. This function should be called on any new + * instance of the configuration structures before being modified by the user + * application. + * + * The default configuration is as follow: + * - The clock unit does not generate output clocks (MCK, SCK and FS) + * - The pins (MCK, SCK and FS) and Mux configurations are not set + * + * \param[out] config Pointer to a I2S module clock unit configuration struct + * to set + */ +static inline void i2s_clock_unit_get_config_defaults( + struct i2s_clock_unit_config *const config) +{ + Assert(config); + + config->clock.mck_out_enable = false; + config->clock.gclk_src = GCLK_GENERATOR_0; + + config->clock.mck_src = I2S_MASTER_CLOCK_SOURCE_GCLK; + config->clock.mck_out_div = 1; + config->clock.mck_out_invert = false; + + config->clock.sck_src = I2S_SERIAL_CLOCK_SOURCE_MCKDIV; + config->clock.sck_div = 1; + config->clock.sck_out_invert = false; + + config->frame.number_slots = 1; + config->frame.slot_size = I2S_SLOT_SIZE_32_BIT; + config->frame.data_delay = I2S_DATA_DELAY_I2S; + + config->frame.frame_sync.source = I2S_FRAME_SYNC_SOURCE_SCKDIV; + config->frame.frame_sync.width = I2S_FRAME_SYNC_WIDTH_HALF_FRAME; + config->frame.frame_sync.invert_use = false; + config->frame.frame_sync.invert_out = false; + + config->mck_pin.enable = false; + config->mck_pin.mux = 0; + config->mck_pin.gpio = 0; + + config->sck_pin.enable = false; + config->sck_pin.mux = 0; + config->sck_pin.gpio = 0; + + config->fs_pin.enable = false; + config->fs_pin.mux = 0; + config->fs_pin.gpio = 0; +} + +enum status_code i2s_clock_unit_set_config( + struct i2s_module *const module_inst, + const enum i2s_clock_unit clock_unit, + const struct i2s_clock_unit_config *config); + +/** @} */ + + +/** + * \name Clock Unit Enable/Disable + * @{ + */ + +/** + * \brief Enable the Specified Clock Unit of I2S module. + * + * Enables a Clock Unit in I2S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] clock_unit I2S Clock Unit to enable + */ +static inline void i2s_clock_unit_enable( + const struct i2s_module *const module_inst, + const enum i2s_clock_unit clock_unit) +{ + uint32_t cken_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + cken_bit = I2S_CTRLA_CKEN0 << clock_unit; + + while (module_inst->hw->SYNCBUSY.reg & cken_bit) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg |= cken_bit; +} + +/** + * \brief Disable the Specified Clock Unit of I2S module. + * + * Disables a Clock Unit in I2S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] clock_unit I2S Clock Unit to disable + */ +static inline void i2s_clock_unit_disable( + const struct i2s_module *const module_inst, + const enum i2s_clock_unit clock_unit) +{ + uint32_t cken_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + cken_bit = I2S_CTRLA_CKEN0 << clock_unit; + + while (module_inst->hw->SYNCBUSY.reg & cken_bit) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg &= ~cken_bit; +} + +/** @} */ + + +/** + * \name Serializer Initialization and Configuration + * @{ + */ + +/** + * \brief Initializes config with predefined default values for I2S Serializer. + * + * This function will initialize a given I2S Clock Unit configuration structure + * to a set of known default values. This function should be called on any new + * instance of the configuration structures before being modified by the user + * application. + * + * The default configuration is as follow: + * - Output data does not internally loopback to input line + * - Does not extend mono data (left channel) to right channel + * - None of the data slot is disabled + * - MSB of I2S data is transferred first + * - In data word data is adjusted right + * - In slot data word is adjusted left + * - The data size is 16-bit width + * - I2S will padd 0 to not defined bits + * - I2S will padd 0 to not defined words + * - I2S will use single DMA channel for all data channels + * - I2S will use clock unit 0 to serve as clock + * - The default data line state is 0, when there is no data + * - I2S will transmit data to output line + * - The data pin and Mux configuration are not set + * + * \param[out] config Pointer to a I2S module Serializer configuration struct + * to set + */ +static inline void i2s_serializer_get_config_defaults( + struct i2s_serializer_config *const config) +{ + config->loop_back = false; + + config->mono_mode = false; + + config->disable_data_slot[0] = false; + config->disable_data_slot[1] = false; + config->disable_data_slot[2] = false; + config->disable_data_slot[3] = false; + config->disable_data_slot[4] = false; + config->disable_data_slot[5] = false; + config->disable_data_slot[6] = false; + config->disable_data_slot[7] = false; + + config->transfer_lsb_first = false; + config->data_adjust_left_in_word = false; + config->data_adjust_left_in_slot = true; + + config->data_size = I2S_DATA_SIZE_16BIT; + + config->bit_padding = I2S_BIT_PADDING_0; + config->data_padding = I2S_DATA_PADDING_0; + + config->dma_usage = I2S_DMA_USE_SINGLE_CHANNEL_FOR_ALL; + + config->clock_unit = I2S_CLOCK_UNIT_0; + + config->line_default_state = I2S_LINE_DEFAULT_0; + + config->mode = I2S_SERIALIZER_TRANSMIT; + + config->data_pin.enable = false; + config->data_pin.gpio = 0; + config->data_pin.mux = 0; +} + +enum status_code i2s_serializer_set_config( + struct i2s_module *const module_inst, + const enum i2s_serializer serializer, + const struct i2s_serializer_config *config); +/** @} */ + +/** + * \name Serializer Enable/Disable + * @{ + */ + +/** + * \brief Enable the Specified Serializer of I2S module. + * + * Enables a Serializer in I2S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer I2S Serializer to enable + */ +static inline void i2s_serializer_enable( + const struct i2s_module *const module_inst, + const enum i2s_serializer serializer) +{ + uint32_t seren_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + seren_bit = I2S_CTRLA_SEREN0 << serializer; + + while (module_inst->hw->SYNCBUSY.reg & seren_bit) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg |= seren_bit; +} + +/** + * \brief Disable the Specified Serializer of I2S module. + * + * Disables a Serializer in I2S module that has been previously initialized. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer I2S Serializer to disable + */ +static inline void i2s_serializer_disable( + const struct i2s_module *const module_inst, + const enum i2s_serializer serializer) +{ + uint32_t seren_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + seren_bit = I2S_CTRLA_SEREN0 << serializer; + + while (module_inst->hw->SYNCBUSY.reg & seren_bit) { + /* Sync wait */ + } + module_inst->hw->CTRLA.reg &= ~seren_bit; +} +/** @} */ + +/** + * \name Status Management + * @{ + */ + +uint32_t i2s_get_status( + const struct i2s_module *const module_inst); + +void i2s_clear_status( + const struct i2s_module *const module_inst, + uint32_t status); + + +enum status_code i2s_enable_status_interrupt( + struct i2s_module *const module_inst, + uint32_t status); + +void i2s_disable_status_interrupt( + struct i2s_module *const module_inst, + uint32_t status); + +/** @}*/ + +/** + * \name Data read/write + * @{ + */ + +/** + * \brief Write a data word to the specified Serializer of I2S module + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The Serializer to write to + * \param[in] data The data to write + * + */ +static inline void i2s_serializer_write_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + uint32_t data) +{ + uint32_t sync_bit, ready_bit; + + Assert(module_inst); + Assert(module_inst->hw); + + ready_bit = I2S_INTFLAG_TXRDY0 << serializer; + while (!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait until ready to transmit */ + } + sync_bit = I2S_SYNCBUSY_DATA0 << serializer; + while (module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait sync */ + } + /* Write data */ + module_inst->hw->DATA[serializer].reg = data; + module_inst->hw->INTFLAG.reg = ready_bit; +} + +/** + * \brief Read a data word from the specified Serializer of I2S module + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The Serializer to read + */ +static inline uint32_t i2s_serializer_read_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer) +{ + uint32_t sync_bit, ready_bit; + uint32_t data; + + Assert(module_inst); + Assert(module_inst->hw); + + ready_bit = I2S_INTFLAG_RXRDY0 << serializer; + while (!(module_inst->hw->INTFLAG.reg & ready_bit)) { + /* Wait until ready to transmit */ + } + sync_bit = I2S_SYNCBUSY_DATA0 << serializer; + while (module_inst->hw->SYNCBUSY.reg & sync_bit) { + /* Wait sync */ + } + /* Read data */ + data = module_inst->hw->DATA[serializer].reg; + module_inst->hw->INTFLAG.reg = ready_bit; + return data; +} + + +/** + * \brief Write buffer to the specified Serializer of I2S module + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The Serializer to write to + * \param[in] buffer The data buffer to write + * \param[in] size Number of data words to write + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The data was sent successfully + * \retval STATUS_INVALID_ARG An invalid buffer pointer was supplied + */ +enum status_code i2s_serializer_write_buffer_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + void *buffer, uint32_t size); + +/** + * \brief Read from the specified Serializer of I2S module to a buffer + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] serializer The Serializer to write to + * \param[in] buffer The buffer to fill read data + * \param[in] size Number of data words to read + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The data was sent successfully + * \retval STATUS_INVALID_ARG An invalid buffer pointer was supplied + */ +enum status_code i2s_serializer_read_buffer_wait( + const struct i2s_module *const module_inst, + enum i2s_serializer serializer, + void *buffer, uint32_t size); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +/** @} */ + + +/** + * \page asfdoc_sam0_i2s_extra Extra Information for I2S Driver + * + * \section asfdoc_sam0_i2s_extra_acronyms Acronyms + * Below is a table listing the acronyms used in this module, along with their + * intended meanings. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
AcronymDescription
I2S, IISInter-IC Sound Controller
MCKMaster Clock
SCKSerial Clock
FSFrame Sync
SDSerial Data
ADCAnalog-to-Digital Converter
DACDigital-to-Analog Converter
TDMTime Division Multiplexed
PDMPulse Density Modulation
LSBLeast Significant Bit
MSBMost Significant Bit
DSPDigital Signal Processor
+ * + * + * \section asfdoc_sam0_i2s_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - \ref asfdoc_sam0_system_pinmux_group "System Pin Multiplexer Driver" + * + * + * \section asfdoc_sam0_i2s_extra_errata Errata + * There are no errata related to this driver. + * + * + * \section asfdoc_sam0_i2s_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * + * + * + *
Changelog
Initial Release
+ */ + +/** + * \page asfdoc_sam0_i2s_exqsg Examples for I2S Driver + * + * This is a list of the available Quick Start guides (QSGs) and example + * applications for \ref asfdoc_sam0_i2s_group. QSGs are simple examples with + * step-by-step instructions to configure and use this driver in a selection of + * use cases. Note that QSGs can be compiled as a standalone application or be + * added to the user application. + * + * - \subpage asfdoc_sam0_i2s_basic_use_case + * \if I2S_CALLBACK_MODE + * - \subpage asfdoc_sam0_i2s_callback_use_case + * \endif + * - \subpage asfdoc_sam0_i2s_dma_use_case + * + * \page asfdoc_sam0_i2s_document_revision_history Document Revision History + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Doc. Rev. + * Date + * Comments + *
B04/2015Added support for SAMDA1.
A01/2014Initial release
+ */ + +#endif /* #ifndef I2S_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt.h new file mode 100644 index 0000000..fa4878e --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt.h @@ -0,0 +1,117 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ +#ifndef UTILS_INTERRUPT_H +#define UTILS_INTERRUPT_H + +//#include + +#include "interrupt/interrupt_sam_nvic.h" + +/** + * \defgroup interrupt_group Global interrupt management + * + * This is a driver for global enabling and disabling of interrupts. + * + * @{ + */ + +#if defined(__DOXYGEN__) +/** + * \def CONFIG_INTERRUPT_FORCE_INTC + * \brief Force usage of the ASF INTC driver + * + * Predefine this symbol when preprocessing to force the use of the ASF INTC driver. + * This is useful to ensure compatibility across compilers and shall be used only when required + * by the application needs. + */ +# define CONFIG_INTERRUPT_FORCE_INTC +#endif + +//! \name Global interrupt flags +//@{ +/** + * \typedef irqflags_t + * \brief Type used for holding state of interrupt flag + */ + +/** + * \def cpu_irq_enable + * \brief Enable interrupts globally + */ + +/** + * \def cpu_irq_disable + * \brief Disable interrupts globally + */ + +/** + * \fn irqflags_t cpu_irq_save(void) + * \brief Get and clear the global interrupt flags + * + * Use in conjunction with \ref cpu_irq_restore. + * + * \return Current state of interrupt flags. + * + * \note This function leaves interrupts disabled. + */ + +/** + * \fn void cpu_irq_restore(irqflags_t flags) + * \brief Restore global interrupt flags + * + * Use in conjunction with \ref cpu_irq_save. + * + * \param flags State to set interrupt flag to. + */ + +/** + * \fn bool cpu_irq_is_enabled_flags(irqflags_t flags) + * \brief Check if interrupts are globally enabled in supplied flags + * + * \param flags Currents state of interrupt flags. + * + * \return True if interrupts are enabled. + */ + +/** + * \def cpu_irq_is_enabled + * \brief Check if interrupts are globally enabled + * + * \return True if interrupts are enabled. + */ +//@} + +//! @} + +/** + * \ingroup interrupt_group + * \defgroup interrupt_deprecated_group Deprecated interrupt definitions + */ + +#endif /* UTILS_INTERRUPT_H */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c new file mode 100644 index 0000000..d813485 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c @@ -0,0 +1,69 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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 "interrupt_sam_nvic.h" + +#if !defined(__DOXYGEN__) +/* Deprecated - global flag to determine the global interrupt state. Required by + * QTouch library, however new applications should use cpu_irq_is_enabled() + * which probes the true global interrupt state from the CPU special registers. + */ +volatile bool g_interrupt_enabled = true; +#endif + +void cpu_irq_enter_critical(void) +{ + if (cpu_irq_critical_section_counter == 0) { + if (cpu_irq_is_enabled()) { + cpu_irq_disable(); + cpu_irq_prev_interrupt_state = true; + } else { + /* Make sure the to save the prev state as false */ + cpu_irq_prev_interrupt_state = false; + } + + } + + cpu_irq_critical_section_counter++; +} + +void cpu_irq_leave_critical(void) +{ + /* Check if the user is trying to leave a critical section when not in a critical section */ + Assert(cpu_irq_critical_section_counter > 0); + + cpu_irq_critical_section_counter--; + + /* Only enable global interrupts when the counter reaches 0 and the state of the global interrupt flag + was enabled when entering critical state */ + if ((cpu_irq_critical_section_counter == 0) && (cpu_irq_prev_interrupt_state)) { + cpu_irq_enable(); + } +} + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h new file mode 100644 index 0000000..9b5645b --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h @@ -0,0 +1,172 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef UTILS_INTERRUPT_INTERRUPT_H +#define UTILS_INTERRUPT_INTERRUPT_H + +#include +//#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \weakgroup interrupt_group + * + * @{ + */ + +/** + * \name Interrupt Service Routine definition + * + * @{ + */ + +/** + * \brief Define service routine + * + * \note For NVIC devices the interrupt service routines are predefined to + * add to vector table in binary generation, so there is no service + * register at run time. The routine collections are in exceptions.h. + * + * Usage: + * \code + ISR(foo_irq_handler) + { + // Function definition + ... + } +\endcode + * + * \param func Name for the function. + */ +# define ISR(func) \ + void func (void) + +/** + * \brief Initialize interrupt vectors + * + * For NVIC the interrupt vectors are put in vector table. So nothing + * to do to initialize them, except defined the vector function with + * right name. + * + * This must be called prior to \ref irq_register_handler. + */ +# define irq_initialize_vectors() \ + do { \ + } while(0) + +/** + * \brief Register handler for interrupt + * + * For NVIC the interrupt vectors are put in vector table. So nothing + * to do to register them, except defined the vector function with + * right name. + * + * Usage: + * \code + irq_initialize_vectors(); + irq_register_handler(foo_irq_handler); +\endcode + * + * \note The function \a func must be defined with the \ref ISR macro. + * \note The functions prototypes can be found in the device exception header + * files (exceptions.h). + */ +# define irq_register_handler(int_num, int_prio) \ + NVIC_ClearPendingIRQ( (IRQn_Type)int_num); \ + NVIC_SetPriority( (IRQn_Type)int_num, int_prio); \ + NVIC_EnableIRQ( (IRQn_Type)int_num); \ + +//@} + +# define cpu_irq_enable() \ + do { \ + g_interrupt_enabled = true; \ + __DMB(); \ + __enable_irq(); \ + } while (0) +# define cpu_irq_disable() \ + do { \ + __disable_irq(); \ + __DMB(); \ + g_interrupt_enabled = false; \ + } while (0) + +typedef uint32_t irqflags_t; + +#if !defined(__DOXYGEN__) +extern volatile bool g_interrupt_enabled; +#endif + +#define cpu_irq_is_enabled() (__get_PRIMASK() == 0) + +static volatile uint32_t cpu_irq_critical_section_counter; +static volatile bool cpu_irq_prev_interrupt_state; + +static inline irqflags_t cpu_irq_save(void) +{ + irqflags_t flags = cpu_irq_is_enabled(); + cpu_irq_disable(); + return flags; +} + +static inline bool cpu_irq_is_enabled_flags(irqflags_t flags) +{ + return (flags); +} + +static inline void cpu_irq_restore(irqflags_t flags) +{ + if (cpu_irq_is_enabled_flags(flags)) + cpu_irq_enable(); +} + +void cpu_irq_enter_critical(void); +void cpu_irq_leave_critical(void); + +/** + * \weakgroup interrupt_deprecated_group + * @{ + */ + +#define Enable_global_interrupt() cpu_irq_enable() +#define Disable_global_interrupt() cpu_irq_disable() +#define Is_global_interrupt_enabled() cpu_irq_is_enabled() + +//@} + +//@} + +#ifdef __cplusplus +} +#endif + +#endif /* UTILS_INTERRUPT_INTERRUPT_H */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c new file mode 100644 index 0000000..26dcc91 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c @@ -0,0 +1,86 @@ +/** + * \file + * + * \brief Global interrupt management for SAM D20, SAM3 and SAM4 (NVIC based) + * + * Copyright (c) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#include "interrupt_sam_nvic.h" + +#if !defined(__DOXYGEN__) +/* Deprecated - global flag to determine the global interrupt state. Required by + * QTouch library, however new applications should use cpu_irq_is_enabled() + * which probes the true global interrupt state from the CPU special registers. + */ +volatile bool g_interrupt_enabled = true; +#endif + +void cpu_irq_enter_critical(void) +{ + if (cpu_irq_critical_section_counter == 0) { + if (cpu_irq_is_enabled()) { + cpu_irq_disable(); + cpu_irq_prev_interrupt_state = true; + } else { + /* Make sure the to save the prev state as false */ + cpu_irq_prev_interrupt_state = false; + } + + } + + cpu_irq_critical_section_counter++; +} + +void cpu_irq_leave_critical(void) +{ + /* Check if the user is trying to leave a critical section when not in a critical section */ + Assert(cpu_irq_critical_section_counter > 0); + + cpu_irq_critical_section_counter--; + + /* Only enable global interrupts when the counter reaches 0 and the state of the global interrupt flag + was enabled when entering critical state */ + if ((cpu_irq_critical_section_counter == 0) && (cpu_irq_prev_interrupt_state)) { + cpu_irq_enable(); + } +} + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h new file mode 100644 index 0000000..f996e92 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h @@ -0,0 +1,189 @@ +/** + * \file + * + * \brief Global interrupt management for SAM D20, SAM3 and SAM4 (NVIC based) + * + * Copyright (c) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#ifndef UTILS_INTERRUPT_INTERRUPT_H +#define UTILS_INTERRUPT_INTERRUPT_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \weakgroup interrupt_group + * + * @{ + */ + +/** + * \name Interrupt Service Routine definition + * + * @{ + */ + +/** + * \brief Define service routine + * + * \note For NVIC devices the interrupt service routines are predefined to + * add to vector table in binary generation, so there is no service + * register at run time. The routine collections are in exceptions.h. + * + * Usage: + * \code + ISR(foo_irq_handler) + { + // Function definition + ... + } +\endcode + * + * \param func Name for the function. + */ +# define ISR(func) \ + void func (void) + +/** + * \brief Initialize interrupt vectors + * + * For NVIC the interrupt vectors are put in vector table. So nothing + * to do to initialize them, except defined the vector function with + * right name. + * + * This must be called prior to \ref irq_register_handler. + */ +# define irq_initialize_vectors() \ + do { \ + } while(0) + +/** + * \brief Register handler for interrupt + * + * For NVIC the interrupt vectors are put in vector table. So nothing + * to do to register them, except defined the vector function with + * right name. + * + * Usage: + * \code + irq_initialize_vectors(); + irq_register_handler(foo_irq_handler); +\endcode + * + * \note The function \a func must be defined with the \ref ISR macro. + * \note The functions prototypes can be found in the device exception header + * files (exceptions.h). + */ +# define irq_register_handler(int_num, int_prio) \ + NVIC_ClearPendingIRQ( (IRQn_Type)int_num); \ + NVIC_SetPriority( (IRQn_Type)int_num, int_prio); \ + NVIC_EnableIRQ( (IRQn_Type)int_num); \ + +//@} + +# define cpu_irq_enable() \ + do { \ + g_interrupt_enabled = true; \ + __DMB(); \ + __enable_irq(); \ + } while (0) +# define cpu_irq_disable() \ + do { \ + __disable_irq(); \ + __DMB(); \ + g_interrupt_enabled = false; \ + } while (0) + +typedef uint32_t irqflags_t; + +#if !defined(__DOXYGEN__) +extern volatile bool g_interrupt_enabled; +#endif + +#define cpu_irq_is_enabled() (__get_PRIMASK() == 0) + +static volatile uint32_t cpu_irq_critical_section_counter; +static volatile bool cpu_irq_prev_interrupt_state; + +static inline irqflags_t cpu_irq_save(void) +{ + irqflags_t flags = cpu_irq_is_enabled(); + cpu_irq_disable(); + return flags; +} + +static inline bool cpu_irq_is_enabled_flags(irqflags_t flags) +{ + return (flags); +} + +static inline void cpu_irq_restore(irqflags_t flags) +{ + if (cpu_irq_is_enabled_flags(flags)) + cpu_irq_enable(); +} + +void cpu_irq_enter_critical(void); +void cpu_irq_leave_critical(void); + +/** + * \weakgroup interrupt_deprecated_group + * @{ + */ + +#define Enable_global_interrupt() cpu_irq_enable() +#define Disable_global_interrupt() cpu_irq_disable() +#define Is_global_interrupt_enabled() cpu_irq_is_enabled() + +//@} + +//@} + +#ifdef __cplusplus +} +#endif + +#endif /* UTILS_INTERRUPT_INTERRUPT_H */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/library.properties b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/library.properties new file mode 100644 index 0000000..e2af108 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/library.properties @@ -0,0 +1,9 @@ +name=Adafruit Arduino Zero ASF Core Library +version=1.0.0 +author=Adafruit +maintainer=Adafruit +sentence=ASF (Atmel Software Framework) files used by Adafruit's Arduino Zero/SAMD21 libraries. +paragraph=ASF (Atmel Software Framework) files used by Adafruit's Arduino Zero/SAMD21 libraries. This is a dependency of other libraries like Adafruit_ZeroTimer. +category=Other +url=https://github.com/adafruit/Adafruit_ASFcore +architectures=* diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/parts.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/parts.h new file mode 100644 index 0000000..40be022 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/parts.h @@ -0,0 +1,1601 @@ +/** + * \file + * + * \brief Atmel part identification macros + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#ifndef ATMEL_PARTS_H +#define ATMEL_PARTS_H + +/** + * \defgroup part_macros_group Atmel part identification macros + * + * This collection of macros identify which series and families that the various + * Atmel parts belong to. These can be used to select part-dependent sections of + * code at compile time. + * + * @{ + */ + +/** + * \name Convenience macros for part checking + * @{ + */ +/* ! Check GCC and IAR part definition for 8-bit AVR */ +#define AVR8_PART_IS_DEFINED(part) \ + (defined(__ ## part ## __) || defined(__AVR_ ## part ## __)) + +/* ! Check GCC and IAR part definition for 32-bit AVR */ +#define AVR32_PART_IS_DEFINED(part) \ + (defined(__AT32 ## part ## __) || defined(__AVR32_ ## part ## __)) + +/* ! Check GCC and IAR part definition for SAM */ +#define SAM_PART_IS_DEFINED(part) (defined(__ ## part ## __)) +/** @} */ + +/** + * \defgroup uc3_part_macros_group AVR UC3 parts + * @{ + */ + +/** + * \name AVR UC3 A series + * @{ + */ +#define UC3A0 ( \ + AVR32_PART_IS_DEFINED(UC3A0128) || \ + AVR32_PART_IS_DEFINED(UC3A0256) || \ + AVR32_PART_IS_DEFINED(UC3A0512) \ + ) + +#define UC3A1 ( \ + AVR32_PART_IS_DEFINED(UC3A1128) || \ + AVR32_PART_IS_DEFINED(UC3A1256) || \ + AVR32_PART_IS_DEFINED(UC3A1512) \ + ) + +#define UC3A3 ( \ + AVR32_PART_IS_DEFINED(UC3A364) || \ + AVR32_PART_IS_DEFINED(UC3A364S) || \ + AVR32_PART_IS_DEFINED(UC3A3128) || \ + AVR32_PART_IS_DEFINED(UC3A3128S) || \ + AVR32_PART_IS_DEFINED(UC3A3256) || \ + AVR32_PART_IS_DEFINED(UC3A3256S) \ + ) + +#define UC3A4 ( \ + AVR32_PART_IS_DEFINED(UC3A464) || \ + AVR32_PART_IS_DEFINED(UC3A464S) || \ + AVR32_PART_IS_DEFINED(UC3A4128) || \ + AVR32_PART_IS_DEFINED(UC3A4128S) || \ + AVR32_PART_IS_DEFINED(UC3A4256) || \ + AVR32_PART_IS_DEFINED(UC3A4256S) \ + ) +/** @} */ + +/** + * \name AVR UC3 B series + * @{ + */ +#define UC3B0 ( \ + AVR32_PART_IS_DEFINED(UC3B064) || \ + AVR32_PART_IS_DEFINED(UC3B0128) || \ + AVR32_PART_IS_DEFINED(UC3B0256) || \ + AVR32_PART_IS_DEFINED(UC3B0512) \ + ) + +#define UC3B1 ( \ + AVR32_PART_IS_DEFINED(UC3B164) || \ + AVR32_PART_IS_DEFINED(UC3B1128) || \ + AVR32_PART_IS_DEFINED(UC3B1256) || \ + AVR32_PART_IS_DEFINED(UC3B1512) \ + ) +/** @} */ + +/** + * \name AVR UC3 C series + * @{ + */ +#define UC3C0 ( \ + AVR32_PART_IS_DEFINED(UC3C064C) || \ + AVR32_PART_IS_DEFINED(UC3C0128C) || \ + AVR32_PART_IS_DEFINED(UC3C0256C) || \ + AVR32_PART_IS_DEFINED(UC3C0512C) \ + ) + +#define UC3C1 ( \ + AVR32_PART_IS_DEFINED(UC3C164C) || \ + AVR32_PART_IS_DEFINED(UC3C1128C) || \ + AVR32_PART_IS_DEFINED(UC3C1256C) || \ + AVR32_PART_IS_DEFINED(UC3C1512C) \ + ) + +#define UC3C2 ( \ + AVR32_PART_IS_DEFINED(UC3C264C) || \ + AVR32_PART_IS_DEFINED(UC3C2128C) || \ + AVR32_PART_IS_DEFINED(UC3C2256C) || \ + AVR32_PART_IS_DEFINED(UC3C2512C) \ + ) +/** @} */ + +/** + * \name AVR UC3 D series + * @{ + */ +#define UC3D3 ( \ + AVR32_PART_IS_DEFINED(UC64D3) || \ + AVR32_PART_IS_DEFINED(UC128D3) \ + ) + +#define UC3D4 ( \ + AVR32_PART_IS_DEFINED(UC64D4) || \ + AVR32_PART_IS_DEFINED(UC128D4) \ + ) +/** @} */ + +/** + * \name AVR UC3 L series + * @{ + */ +#define UC3L0 ( \ + AVR32_PART_IS_DEFINED(UC3L016) || \ + AVR32_PART_IS_DEFINED(UC3L032) || \ + AVR32_PART_IS_DEFINED(UC3L064) \ + ) + +#define UC3L0128 ( \ + AVR32_PART_IS_DEFINED(UC3L0128) \ + ) + +#define UC3L0256 ( \ + AVR32_PART_IS_DEFINED(UC3L0256) \ + ) + +#define UC3L3 ( \ + AVR32_PART_IS_DEFINED(UC64L3U) || \ + AVR32_PART_IS_DEFINED(UC128L3U) || \ + AVR32_PART_IS_DEFINED(UC256L3U) \ + ) + +#define UC3L4 ( \ + AVR32_PART_IS_DEFINED(UC64L4U) || \ + AVR32_PART_IS_DEFINED(UC128L4U) || \ + AVR32_PART_IS_DEFINED(UC256L4U) \ + ) + +#define UC3L3_L4 (UC3L3 || UC3L4) +/** @} */ + +/** + * \name AVR UC3 families + * @{ + */ +/** AVR UC3 A family */ +#define UC3A (UC3A0 || UC3A1 || UC3A3 || UC3A4) + +/** AVR UC3 B family */ +#define UC3B (UC3B0 || UC3B1) + +/** AVR UC3 C family */ +#define UC3C (UC3C0 || UC3C1 || UC3C2) + +/** AVR UC3 D family */ +#define UC3D (UC3D3 || UC3D4) + +/** AVR UC3 L family */ +#define UC3L (UC3L0 || UC3L0128 || UC3L0256 || UC3L3_L4) +/** @} */ + +/** AVR UC3 product line */ +#define UC3 (UC3A || UC3B || UC3C || UC3D || UC3L) + +/** @} */ + +/** + * \defgroup xmega_part_macros_group AVR XMEGA parts + * @{ + */ + +/** + * \name AVR XMEGA A series + * @{ + */ +#define XMEGA_A1 ( \ + AVR8_PART_IS_DEFINED(ATxmega64A1) || \ + AVR8_PART_IS_DEFINED(ATxmega128A1) \ + ) + +#define XMEGA_A3 ( \ + AVR8_PART_IS_DEFINED(ATxmega64A3) || \ + AVR8_PART_IS_DEFINED(ATxmega128A3) || \ + AVR8_PART_IS_DEFINED(ATxmega192A3) || \ + AVR8_PART_IS_DEFINED(ATxmega256A3) \ + ) + +#define XMEGA_A3B ( \ + AVR8_PART_IS_DEFINED(ATxmega256A3B) \ + ) + +#define XMEGA_A4 ( \ + AVR8_PART_IS_DEFINED(ATxmega16A4) || \ + AVR8_PART_IS_DEFINED(ATxmega32A4) \ + ) +/** @} */ + +/** + * \name AVR XMEGA AU series + * @{ + */ +#define XMEGA_A1U ( \ + AVR8_PART_IS_DEFINED(ATxmega64A1U) || \ + AVR8_PART_IS_DEFINED(ATxmega128A1U) \ + ) + +#define XMEGA_A3U ( \ + AVR8_PART_IS_DEFINED(ATxmega64A3U) || \ + AVR8_PART_IS_DEFINED(ATxmega128A3U) || \ + AVR8_PART_IS_DEFINED(ATxmega192A3U) || \ + AVR8_PART_IS_DEFINED(ATxmega256A3U) \ + ) + +#define XMEGA_A3BU ( \ + AVR8_PART_IS_DEFINED(ATxmega256A3BU) \ + ) + +#define XMEGA_A4U ( \ + AVR8_PART_IS_DEFINED(ATxmega16A4U) || \ + AVR8_PART_IS_DEFINED(ATxmega32A4U) || \ + AVR8_PART_IS_DEFINED(ATxmega64A4U) || \ + AVR8_PART_IS_DEFINED(ATxmega128A4U) \ + ) +/** @} */ + +/** + * \name AVR XMEGA B series + * @{ + */ +#define XMEGA_B1 ( \ + AVR8_PART_IS_DEFINED(ATxmega64B1) || \ + AVR8_PART_IS_DEFINED(ATxmega128B1) \ + ) + +#define XMEGA_B3 ( \ + AVR8_PART_IS_DEFINED(ATxmega64B3) || \ + AVR8_PART_IS_DEFINED(ATxmega128B3) \ + ) +/** @} */ + +/** + * \name AVR XMEGA C series + * @{ + */ +#define XMEGA_C3 ( \ + AVR8_PART_IS_DEFINED(ATxmega384C3) || \ + AVR8_PART_IS_DEFINED(ATxmega256C3) || \ + AVR8_PART_IS_DEFINED(ATxmega192C3) || \ + AVR8_PART_IS_DEFINED(ATxmega128C3) || \ + AVR8_PART_IS_DEFINED(ATxmega64C3) || \ + AVR8_PART_IS_DEFINED(ATxmega32C3) \ + ) + +#define XMEGA_C4 ( \ + AVR8_PART_IS_DEFINED(ATxmega32C4) || \ + AVR8_PART_IS_DEFINED(ATxmega16C4) \ + ) +/** @} */ + +/** + * \name AVR XMEGA D series + * @{ + */ +#define XMEGA_D3 ( \ + AVR8_PART_IS_DEFINED(ATxmega32D3) || \ + AVR8_PART_IS_DEFINED(ATxmega64D3) || \ + AVR8_PART_IS_DEFINED(ATxmega128D3) || \ + AVR8_PART_IS_DEFINED(ATxmega192D3) || \ + AVR8_PART_IS_DEFINED(ATxmega256D3) || \ + AVR8_PART_IS_DEFINED(ATxmega384D3) \ + ) + +#define XMEGA_D4 ( \ + AVR8_PART_IS_DEFINED(ATxmega16D4) || \ + AVR8_PART_IS_DEFINED(ATxmega32D4) || \ + AVR8_PART_IS_DEFINED(ATxmega64D4) || \ + AVR8_PART_IS_DEFINED(ATxmega128D4) \ + ) +/** @} */ + +/** + * \name AVR XMEGA E series + * @{ + */ +#define XMEGA_E5 ( \ + AVR8_PART_IS_DEFINED(ATxmega8E5) || \ + AVR8_PART_IS_DEFINED(ATxmega16E5) || \ + AVR8_PART_IS_DEFINED(ATxmega32E5) \ + ) +/** @} */ + + +/** + * \name AVR XMEGA families + * @{ + */ +/** AVR XMEGA A family */ +#define XMEGA_A (XMEGA_A1 || XMEGA_A3 || XMEGA_A3B || XMEGA_A4) + +/** AVR XMEGA AU family */ +#define XMEGA_AU (XMEGA_A1U || XMEGA_A3U || XMEGA_A3BU || XMEGA_A4U) + +/** AVR XMEGA B family */ +#define XMEGA_B (XMEGA_B1 || XMEGA_B3) + +/** AVR XMEGA C family */ +#define XMEGA_C (XMEGA_C3 || XMEGA_C4) + +/** AVR XMEGA D family */ +#define XMEGA_D (XMEGA_D3 || XMEGA_D4) + +/** AVR XMEGA E family */ +#define XMEGA_E (XMEGA_E5) +/** @} */ + + +/** AVR XMEGA product line */ +#define XMEGA (XMEGA_A || XMEGA_AU || XMEGA_B || XMEGA_C || XMEGA_D || XMEGA_E) + +/** @} */ + +/** + * \defgroup mega_part_macros_group megaAVR parts + * + * \note These megaAVR groupings are based on the groups in AVR Libc for the + * part header files. They are not names of official megaAVR device series or + * families. + * + * @{ + */ + +/** + * \name ATmegaxx0/xx1 subgroups + * @{ + */ +#define MEGA_XX0 ( \ + AVR8_PART_IS_DEFINED(ATmega640) || \ + AVR8_PART_IS_DEFINED(ATmega1280) || \ + AVR8_PART_IS_DEFINED(ATmega2560) \ + ) + +#define MEGA_XX1 ( \ + AVR8_PART_IS_DEFINED(ATmega1281) || \ + AVR8_PART_IS_DEFINED(ATmega2561) \ + ) +/** @} */ + +/** + * \name megaAVR groups + * @{ + */ +/** ATmegaxx0/xx1 group */ +#define MEGA_XX0_1 (MEGA_XX0 || MEGA_XX1) + +/** ATmegaxx4 group */ +#define MEGA_XX4 ( \ + AVR8_PART_IS_DEFINED(ATmega164A) || \ + AVR8_PART_IS_DEFINED(ATmega164PA) || \ + AVR8_PART_IS_DEFINED(ATmega324A) || \ + AVR8_PART_IS_DEFINED(ATmega324PA) || \ + AVR8_PART_IS_DEFINED(ATmega644) || \ + AVR8_PART_IS_DEFINED(ATmega644A) || \ + AVR8_PART_IS_DEFINED(ATmega644PA) || \ + AVR8_PART_IS_DEFINED(ATmega1284P) || \ + AVR8_PART_IS_DEFINED(ATmega128RFA1) \ + ) + +/** ATmegaxx4 group */ +#define MEGA_XX4_A ( \ + AVR8_PART_IS_DEFINED(ATmega164A) || \ + AVR8_PART_IS_DEFINED(ATmega164PA) || \ + AVR8_PART_IS_DEFINED(ATmega324A) || \ + AVR8_PART_IS_DEFINED(ATmega324PA) || \ + AVR8_PART_IS_DEFINED(ATmega644A) || \ + AVR8_PART_IS_DEFINED(ATmega644PA) || \ + AVR8_PART_IS_DEFINED(ATmega1284P) \ + ) + +/** ATmegaxx8 group */ +#define MEGA_XX8 ( \ + AVR8_PART_IS_DEFINED(ATmega48) || \ + AVR8_PART_IS_DEFINED(ATmega48A) || \ + AVR8_PART_IS_DEFINED(ATmega48PA) || \ + AVR8_PART_IS_DEFINED(ATmega88) || \ + AVR8_PART_IS_DEFINED(ATmega88A) || \ + AVR8_PART_IS_DEFINED(ATmega88PA) || \ + AVR8_PART_IS_DEFINED(ATmega168) || \ + AVR8_PART_IS_DEFINED(ATmega168A) || \ + AVR8_PART_IS_DEFINED(ATmega168PA) || \ + AVR8_PART_IS_DEFINED(ATmega328) || \ + AVR8_PART_IS_DEFINED(ATmega328P) \ + ) + +/** ATmegaxx8A/P/PA group */ +#define MEGA_XX8_A ( \ + AVR8_PART_IS_DEFINED(ATmega48A) || \ + AVR8_PART_IS_DEFINED(ATmega48PA) || \ + AVR8_PART_IS_DEFINED(ATmega88A) || \ + AVR8_PART_IS_DEFINED(ATmega88PA) || \ + AVR8_PART_IS_DEFINED(ATmega168A) || \ + AVR8_PART_IS_DEFINED(ATmega168PA) || \ + AVR8_PART_IS_DEFINED(ATmega328P) \ + ) + +/** ATmegaxx group */ +#define MEGA_XX ( \ + AVR8_PART_IS_DEFINED(ATmega16) || \ + AVR8_PART_IS_DEFINED(ATmega16A) || \ + AVR8_PART_IS_DEFINED(ATmega32) || \ + AVR8_PART_IS_DEFINED(ATmega32A) || \ + AVR8_PART_IS_DEFINED(ATmega64) || \ + AVR8_PART_IS_DEFINED(ATmega64A) || \ + AVR8_PART_IS_DEFINED(ATmega128) || \ + AVR8_PART_IS_DEFINED(ATmega128A) \ + ) + +/** ATmegaxxA/P/PA group */ +#define MEGA_XX_A ( \ + AVR8_PART_IS_DEFINED(ATmega16A) || \ + AVR8_PART_IS_DEFINED(ATmega32A) || \ + AVR8_PART_IS_DEFINED(ATmega64A) || \ + AVR8_PART_IS_DEFINED(ATmega128A) \ + ) +/** ATmegaxxRFA1 group */ +#define MEGA_RFA1 ( \ + AVR8_PART_IS_DEFINED(ATmega128RFA1) \ + ) + +/** ATmegaxxRFR2 group */ +#define MEGA_RFR2 ( \ + AVR8_PART_IS_DEFINED(ATmega64RFR2) || \ + AVR8_PART_IS_DEFINED(ATmega128RFR2) || \ + AVR8_PART_IS_DEFINED(ATmega256RFR2) || \ + AVR8_PART_IS_DEFINED(ATmega644RFR2) || \ + AVR8_PART_IS_DEFINED(ATmega1284RFR2) || \ + AVR8_PART_IS_DEFINED(ATmega2564RFR2) \ + ) + + +/** ATmegaxxRFxx group */ +#define MEGA_RF (MEGA_RFA1 || MEGA_RFR2) + +/** + * \name ATmegaxx_un0/un1/un2 subgroups + * @{ + */ +#define MEGA_XX_UN0 ( \ + AVR8_PART_IS_DEFINED(ATmega16) || \ + AVR8_PART_IS_DEFINED(ATmega16A) || \ + AVR8_PART_IS_DEFINED(ATmega32) || \ + AVR8_PART_IS_DEFINED(ATmega32A) \ + ) + +/** ATmegaxx group without power reduction and + * And interrupt sense register. + */ +#define MEGA_XX_UN1 ( \ + AVR8_PART_IS_DEFINED(ATmega64) || \ + AVR8_PART_IS_DEFINED(ATmega64A) || \ + AVR8_PART_IS_DEFINED(ATmega128) || \ + AVR8_PART_IS_DEFINED(ATmega128A) \ + ) + +/** ATmegaxx group without power reduction and + * And interrupt sense register. + */ +#define MEGA_XX_UN2 ( \ + AVR8_PART_IS_DEFINED(ATmega169P) || \ + AVR8_PART_IS_DEFINED(ATmega169PA) || \ + AVR8_PART_IS_DEFINED(ATmega329P) || \ + AVR8_PART_IS_DEFINED(ATmega329PA) \ + ) + +/** Devices added to complete megaAVR offering. + * Please do not use this group symbol as it is not intended + * to be permanent: the devices should be regrouped. + */ +#define MEGA_UNCATEGORIZED ( \ + AVR8_PART_IS_DEFINED(AT90CAN128) || \ + AVR8_PART_IS_DEFINED(AT90CAN32) || \ + AVR8_PART_IS_DEFINED(AT90CAN64) || \ + AVR8_PART_IS_DEFINED(AT90PWM1) || \ + AVR8_PART_IS_DEFINED(AT90PWM216) || \ + AVR8_PART_IS_DEFINED(AT90PWM2B) || \ + AVR8_PART_IS_DEFINED(AT90PWM316) || \ + AVR8_PART_IS_DEFINED(AT90PWM3B) || \ + AVR8_PART_IS_DEFINED(AT90PWM81) || \ + AVR8_PART_IS_DEFINED(AT90USB1286) || \ + AVR8_PART_IS_DEFINED(AT90USB1287) || \ + AVR8_PART_IS_DEFINED(AT90USB162) || \ + AVR8_PART_IS_DEFINED(AT90USB646) || \ + AVR8_PART_IS_DEFINED(AT90USB647) || \ + AVR8_PART_IS_DEFINED(AT90USB82) || \ + AVR8_PART_IS_DEFINED(ATmega1284) || \ + AVR8_PART_IS_DEFINED(ATmega162) || \ + AVR8_PART_IS_DEFINED(ATmega164P) || \ + AVR8_PART_IS_DEFINED(ATmega165A) || \ + AVR8_PART_IS_DEFINED(ATmega165P) || \ + AVR8_PART_IS_DEFINED(ATmega165PA) || \ + AVR8_PART_IS_DEFINED(ATmega168P) || \ + AVR8_PART_IS_DEFINED(ATmega169A) || \ + AVR8_PART_IS_DEFINED(ATmega16M1) || \ + AVR8_PART_IS_DEFINED(ATmega16U2) || \ + AVR8_PART_IS_DEFINED(ATmega16U4) || \ + AVR8_PART_IS_DEFINED(ATmega256RFA2) || \ + AVR8_PART_IS_DEFINED(ATmega324P) || \ + AVR8_PART_IS_DEFINED(ATmega325) || \ + AVR8_PART_IS_DEFINED(ATmega3250) || \ + AVR8_PART_IS_DEFINED(ATmega3250A) || \ + AVR8_PART_IS_DEFINED(ATmega3250P) || \ + AVR8_PART_IS_DEFINED(ATmega3250PA) || \ + AVR8_PART_IS_DEFINED(ATmega325A) || \ + AVR8_PART_IS_DEFINED(ATmega325P) || \ + AVR8_PART_IS_DEFINED(ATmega325PA) || \ + AVR8_PART_IS_DEFINED(ATmega329) || \ + AVR8_PART_IS_DEFINED(ATmega3290) || \ + AVR8_PART_IS_DEFINED(ATmega3290A) || \ + AVR8_PART_IS_DEFINED(ATmega3290P) || \ + AVR8_PART_IS_DEFINED(ATmega3290PA) || \ + AVR8_PART_IS_DEFINED(ATmega329A) || \ + AVR8_PART_IS_DEFINED(ATmega32M1) || \ + AVR8_PART_IS_DEFINED(ATmega32U2) || \ + AVR8_PART_IS_DEFINED(ATmega32U4) || \ + AVR8_PART_IS_DEFINED(ATmega48P) || \ + AVR8_PART_IS_DEFINED(ATmega644P) || \ + AVR8_PART_IS_DEFINED(ATmega645) || \ + AVR8_PART_IS_DEFINED(ATmega6450) || \ + AVR8_PART_IS_DEFINED(ATmega6450A) || \ + AVR8_PART_IS_DEFINED(ATmega6450P) || \ + AVR8_PART_IS_DEFINED(ATmega645A) || \ + AVR8_PART_IS_DEFINED(ATmega645P) || \ + AVR8_PART_IS_DEFINED(ATmega649) || \ + AVR8_PART_IS_DEFINED(ATmega6490) || \ + AVR8_PART_IS_DEFINED(ATmega6490A) || \ + AVR8_PART_IS_DEFINED(ATmega6490P) || \ + AVR8_PART_IS_DEFINED(ATmega649A) || \ + AVR8_PART_IS_DEFINED(ATmega649P) || \ + AVR8_PART_IS_DEFINED(ATmega64M1) || \ + AVR8_PART_IS_DEFINED(ATmega64RFA2) || \ + AVR8_PART_IS_DEFINED(ATmega8) || \ + AVR8_PART_IS_DEFINED(ATmega8515) || \ + AVR8_PART_IS_DEFINED(ATmega8535) || \ + AVR8_PART_IS_DEFINED(ATmega88P) || \ + AVR8_PART_IS_DEFINED(ATmega8A) || \ + AVR8_PART_IS_DEFINED(ATmega8U2) \ + ) + +/** Unspecified group */ +#define MEGA_UNSPECIFIED (MEGA_XX_UN0 || MEGA_XX_UN1 || MEGA_XX_UN2 || \ + MEGA_UNCATEGORIZED) + +/** @} */ + +/** megaAVR product line */ +#define MEGA (MEGA_XX0_1 || MEGA_XX4 || MEGA_XX8 || MEGA_XX || MEGA_RF || \ + MEGA_UNSPECIFIED) + +/** @} */ + +/** + * \defgroup tiny_part_macros_group tinyAVR parts + * + * @{ + */ + +/** + * \name tinyAVR groups + * @{ + */ + +/** Devices added to complete tinyAVR offering. + * Please do not use this group symbol as it is not intended + * to be permanent: the devices should be regrouped. + */ +#define TINY_UNCATEGORIZED ( \ + AVR8_PART_IS_DEFINED(ATtiny10) || \ + AVR8_PART_IS_DEFINED(ATtiny13) || \ + AVR8_PART_IS_DEFINED(ATtiny13A) || \ + AVR8_PART_IS_DEFINED(ATtiny1634) || \ + AVR8_PART_IS_DEFINED(ATtiny167) || \ + AVR8_PART_IS_DEFINED(ATtiny20) || \ + AVR8_PART_IS_DEFINED(ATtiny2313) || \ + AVR8_PART_IS_DEFINED(ATtiny2313A) || \ + AVR8_PART_IS_DEFINED(ATtiny24) || \ + AVR8_PART_IS_DEFINED(ATtiny24A) || \ + AVR8_PART_IS_DEFINED(ATtiny25) || \ + AVR8_PART_IS_DEFINED(ATtiny26) || \ + AVR8_PART_IS_DEFINED(ATtiny261) || \ + AVR8_PART_IS_DEFINED(ATtiny261A) || \ + AVR8_PART_IS_DEFINED(ATtiny4) || \ + AVR8_PART_IS_DEFINED(ATtiny40) || \ + AVR8_PART_IS_DEFINED(ATtiny4313) || \ + AVR8_PART_IS_DEFINED(ATtiny43U) || \ + AVR8_PART_IS_DEFINED(ATtiny44) || \ + AVR8_PART_IS_DEFINED(ATtiny44A) || \ + AVR8_PART_IS_DEFINED(ATtiny45) || \ + AVR8_PART_IS_DEFINED(ATtiny461) || \ + AVR8_PART_IS_DEFINED(ATtiny461A) || \ + AVR8_PART_IS_DEFINED(ATtiny48) || \ + AVR8_PART_IS_DEFINED(ATtiny5) || \ + AVR8_PART_IS_DEFINED(ATtiny828) || \ + AVR8_PART_IS_DEFINED(ATtiny84) || \ + AVR8_PART_IS_DEFINED(ATtiny84A) || \ + AVR8_PART_IS_DEFINED(ATtiny85) || \ + AVR8_PART_IS_DEFINED(ATtiny861) || \ + AVR8_PART_IS_DEFINED(ATtiny861A) || \ + AVR8_PART_IS_DEFINED(ATtiny87) || \ + AVR8_PART_IS_DEFINED(ATtiny88) || \ + AVR8_PART_IS_DEFINED(ATtiny9) \ + ) + +/** @} */ + +/** tinyAVR product line */ +#define TINY (TINY_UNCATEGORIZED) + +/** @} */ + +/** + * \defgroup sam_part_macros_group SAM parts + * @{ + */ + +/** + * \name SAM3S series + * @{ + */ +#define SAM3S1 ( \ + SAM_PART_IS_DEFINED(SAM3S1A) || \ + SAM_PART_IS_DEFINED(SAM3S1B) || \ + SAM_PART_IS_DEFINED(SAM3S1C) \ + ) + +#define SAM3S2 ( \ + SAM_PART_IS_DEFINED(SAM3S2A) || \ + SAM_PART_IS_DEFINED(SAM3S2B) || \ + SAM_PART_IS_DEFINED(SAM3S2C) \ + ) + +#define SAM3S4 ( \ + SAM_PART_IS_DEFINED(SAM3S4A) || \ + SAM_PART_IS_DEFINED(SAM3S4B) || \ + SAM_PART_IS_DEFINED(SAM3S4C) \ + ) + +#define SAM3S8 ( \ + SAM_PART_IS_DEFINED(SAM3S8B) || \ + SAM_PART_IS_DEFINED(SAM3S8C) \ + ) + +#define SAM3SD8 ( \ + SAM_PART_IS_DEFINED(SAM3SD8B) || \ + SAM_PART_IS_DEFINED(SAM3SD8C) \ + ) +/** @} */ + +/** + * \name SAM3U series + * @{ + */ +#define SAM3U1 ( \ + SAM_PART_IS_DEFINED(SAM3U1C) || \ + SAM_PART_IS_DEFINED(SAM3U1E) \ + ) + +#define SAM3U2 ( \ + SAM_PART_IS_DEFINED(SAM3U2C) || \ + SAM_PART_IS_DEFINED(SAM3U2E) \ + ) + +#define SAM3U4 ( \ + SAM_PART_IS_DEFINED(SAM3U4C) || \ + SAM_PART_IS_DEFINED(SAM3U4E) \ + ) +/** @} */ + +/** + * \name SAM3N series + * @{ + */ +#define SAM3N00 ( \ + SAM_PART_IS_DEFINED(SAM3N00A) || \ + SAM_PART_IS_DEFINED(SAM3N00B) \ + ) + +#define SAM3N0 ( \ + SAM_PART_IS_DEFINED(SAM3N0A) || \ + SAM_PART_IS_DEFINED(SAM3N0B) || \ + SAM_PART_IS_DEFINED(SAM3N0C) \ + ) + +#define SAM3N1 ( \ + SAM_PART_IS_DEFINED(SAM3N1A) || \ + SAM_PART_IS_DEFINED(SAM3N1B) || \ + SAM_PART_IS_DEFINED(SAM3N1C) \ + ) + +#define SAM3N2 ( \ + SAM_PART_IS_DEFINED(SAM3N2A) || \ + SAM_PART_IS_DEFINED(SAM3N2B) || \ + SAM_PART_IS_DEFINED(SAM3N2C) \ + ) + +#define SAM3N4 ( \ + SAM_PART_IS_DEFINED(SAM3N4A) || \ + SAM_PART_IS_DEFINED(SAM3N4B) || \ + SAM_PART_IS_DEFINED(SAM3N4C) \ + ) +/** @} */ + +/** + * \name SAM3X series + * @{ + */ +#define SAM3X4 ( \ + SAM_PART_IS_DEFINED(SAM3X4C) || \ + SAM_PART_IS_DEFINED(SAM3X4E) \ + ) + +#define SAM3X8 ( \ + SAM_PART_IS_DEFINED(SAM3X8C) || \ + SAM_PART_IS_DEFINED(SAM3X8E) || \ + SAM_PART_IS_DEFINED(SAM3X8H) \ + ) +/** @} */ + +/** + * \name SAM3A series + * @{ + */ +#define SAM3A4 ( \ + SAM_PART_IS_DEFINED(SAM3A4C) \ + ) + +#define SAM3A8 ( \ + SAM_PART_IS_DEFINED(SAM3A8C) \ + ) +/** @} */ + +/** + * \name SAM4S series + * @{ + */ +#define SAM4S2 ( \ + SAM_PART_IS_DEFINED(SAM4S2A) || \ + SAM_PART_IS_DEFINED(SAM4S2B) || \ + SAM_PART_IS_DEFINED(SAM4S2C) \ + ) + +#define SAM4S4 ( \ + SAM_PART_IS_DEFINED(SAM4S4A) || \ + SAM_PART_IS_DEFINED(SAM4S4B) || \ + SAM_PART_IS_DEFINED(SAM4S4C) \ + ) + +#define SAM4S8 ( \ + SAM_PART_IS_DEFINED(SAM4S8B) || \ + SAM_PART_IS_DEFINED(SAM4S8C) \ + ) + +#define SAM4S16 ( \ + SAM_PART_IS_DEFINED(SAM4S16B) || \ + SAM_PART_IS_DEFINED(SAM4S16C) \ + ) + +#define SAM4SA16 ( \ + SAM_PART_IS_DEFINED(SAM4SA16B) || \ + SAM_PART_IS_DEFINED(SAM4SA16C) \ + ) + +#define SAM4SD16 ( \ + SAM_PART_IS_DEFINED(SAM4SD16B) || \ + SAM_PART_IS_DEFINED(SAM4SD16C) \ + ) + +#define SAM4SD32 ( \ + SAM_PART_IS_DEFINED(SAM4SD32B) || \ + SAM_PART_IS_DEFINED(SAM4SD32C) \ + ) +/** @} */ + +/** + * \name SAM4L series + * @{ + */ +#define SAM4LS ( \ + SAM_PART_IS_DEFINED(SAM4LS2A) || \ + SAM_PART_IS_DEFINED(SAM4LS2B) || \ + SAM_PART_IS_DEFINED(SAM4LS2C) || \ + SAM_PART_IS_DEFINED(SAM4LS4A) || \ + SAM_PART_IS_DEFINED(SAM4LS4B) || \ + SAM_PART_IS_DEFINED(SAM4LS4C) || \ + SAM_PART_IS_DEFINED(SAM4LS8A) || \ + SAM_PART_IS_DEFINED(SAM4LS8B) || \ + SAM_PART_IS_DEFINED(SAM4LS8C) \ + ) + +#define SAM4LC ( \ + SAM_PART_IS_DEFINED(SAM4LC2A) || \ + SAM_PART_IS_DEFINED(SAM4LC2B) || \ + SAM_PART_IS_DEFINED(SAM4LC2C) || \ + SAM_PART_IS_DEFINED(SAM4LC4A) || \ + SAM_PART_IS_DEFINED(SAM4LC4B) || \ + SAM_PART_IS_DEFINED(SAM4LC4C) || \ + SAM_PART_IS_DEFINED(SAM4LC8A) || \ + SAM_PART_IS_DEFINED(SAM4LC8B) || \ + SAM_PART_IS_DEFINED(SAM4LC8C) \ + ) +/** @} */ + +/** + * \name SAMD20 series + * @{ + */ +#define SAMD20J ( \ + SAM_PART_IS_DEFINED(SAMD20J14) || \ + SAM_PART_IS_DEFINED(SAMD20J15) || \ + SAM_PART_IS_DEFINED(SAMD20J16) || \ + SAM_PART_IS_DEFINED(SAMD20J17) || \ + SAM_PART_IS_DEFINED(SAMD20J18) \ + ) + +#define SAMD20G ( \ + SAM_PART_IS_DEFINED(SAMD20G14) || \ + SAM_PART_IS_DEFINED(SAMD20G15) || \ + SAM_PART_IS_DEFINED(SAMD20G16) || \ + SAM_PART_IS_DEFINED(SAMD20G17) || \ + SAM_PART_IS_DEFINED(SAMD20G17U) || \ + SAM_PART_IS_DEFINED(SAMD20G18) || \ + SAM_PART_IS_DEFINED(SAMD20G18U) \ + ) + +#define SAMD20E ( \ + SAM_PART_IS_DEFINED(SAMD20E14) || \ + SAM_PART_IS_DEFINED(SAMD20E15) || \ + SAM_PART_IS_DEFINED(SAMD20E16) || \ + SAM_PART_IS_DEFINED(SAMD20E17) || \ + SAM_PART_IS_DEFINED(SAMD20E18) \ + ) +/** @} */ + +/** + * \name SAMD21 series + * @{ + */ +#define SAMD21J ( \ + SAM_PART_IS_DEFINED(SAMD21J15A) || \ + SAM_PART_IS_DEFINED(SAMD21J16A) || \ + SAM_PART_IS_DEFINED(SAMD21J17A) || \ + SAM_PART_IS_DEFINED(SAMD21J18A) || \ + SAM_PART_IS_DEFINED(SAMD21J15B) || \ + SAM_PART_IS_DEFINED(SAMD21J16B) \ + ) + +#define SAMD21G ( \ + SAM_PART_IS_DEFINED(SAMD21G15A) || \ + SAM_PART_IS_DEFINED(SAMD21G16A) || \ + SAM_PART_IS_DEFINED(SAMD21G17A) || \ + SAM_PART_IS_DEFINED(SAMD21G17AU) || \ + SAM_PART_IS_DEFINED(SAMD21G18A) || \ + SAM_PART_IS_DEFINED(SAMD21G18AU) || \ + SAM_PART_IS_DEFINED(SAMD21G15B) || \ + SAM_PART_IS_DEFINED(SAMD21G16B) || \ + SAM_PART_IS_DEFINED(SAMD21G15L) || \ + SAM_PART_IS_DEFINED(SAMD21G16L) \ + ) + +#define SAMD21GXXL ( \ + SAM_PART_IS_DEFINED(SAMD21G15L) || \ + SAM_PART_IS_DEFINED(SAMD21G16L) \ + ) + +#define SAMD21E ( \ + SAM_PART_IS_DEFINED(SAMD21E15A) || \ + SAM_PART_IS_DEFINED(SAMD21E16A) || \ + SAM_PART_IS_DEFINED(SAMD21E17A) || \ + SAM_PART_IS_DEFINED(SAMD21E18A) || \ + SAM_PART_IS_DEFINED(SAMD21E15B) || \ + SAM_PART_IS_DEFINED(SAMD21E15BU) || \ + SAM_PART_IS_DEFINED(SAMD21E16B) || \ + SAM_PART_IS_DEFINED(SAMD21E16BU) || \ + SAM_PART_IS_DEFINED(SAMD21E15L) || \ + SAM_PART_IS_DEFINED(SAMD21E16L) \ + ) + +#define SAMD21EXXL ( \ + SAM_PART_IS_DEFINED(SAMD21E15L) || \ + SAM_PART_IS_DEFINED(SAMD21E16L) \ + ) + +/** @} */ + +/** + * \name SAMR21 series + * @{ + */ +#define SAMR21G ( \ + SAM_PART_IS_DEFINED(SAMR21G16A) || \ + SAM_PART_IS_DEFINED(SAMR21G17A) || \ + SAM_PART_IS_DEFINED(SAMR21G18A) \ + ) + +#define SAMR21E ( \ + SAM_PART_IS_DEFINED(SAMR21E16A) || \ + SAM_PART_IS_DEFINED(SAMR21E17A) || \ + SAM_PART_IS_DEFINED(SAMR21E18A) || \ + SAM_PART_IS_DEFINED(SAMR21E19A) \ + ) +/** @} */ + +/** + * \name SAMD09 series + * @{ + */ +#define SAMD09C ( \ + SAM_PART_IS_DEFINED(SAMD09C13A) \ + ) + +#define SAMD09D ( \ + SAM_PART_IS_DEFINED(SAMD09D14A) \ + ) +/** @} */ + +/** + * \name SAMD10 series + * @{ + */ +#define SAMD10C ( \ + SAM_PART_IS_DEFINED(SAMD10C12A) || \ + SAM_PART_IS_DEFINED(SAMD10C13A) || \ + SAM_PART_IS_DEFINED(SAMD10C14A) \ + ) + +#define SAMD10DS ( \ + SAM_PART_IS_DEFINED(SAMD10D12AS) || \ + SAM_PART_IS_DEFINED(SAMD10D13AS) || \ + SAM_PART_IS_DEFINED(SAMD10D14AS) \ + ) + +#define SAMD10DM ( \ + SAM_PART_IS_DEFINED(SAMD10D12AM) || \ + SAM_PART_IS_DEFINED(SAMD10D13AM) || \ + SAM_PART_IS_DEFINED(SAMD10D14AM) \ + ) +/** @} */ + +/** + * \name SAMD11 series + * @{ + */ +#define SAMD11C ( \ + SAM_PART_IS_DEFINED(SAMD11C14A) \ + ) + +#define SAMD11DS ( \ + SAM_PART_IS_DEFINED(SAMD11D14AS) \ + ) + +#define SAMD11DM ( \ + SAM_PART_IS_DEFINED(SAMD11D14AM) \ + ) +/** @} */ + +/** + * \name SAML21 series + * @{ + */ +#define SAML21E ( \ + SAM_PART_IS_DEFINED(SAML21E18A) || \ + SAM_PART_IS_DEFINED(SAML21E15B) || \ + SAM_PART_IS_DEFINED(SAML21E16B) || \ + SAM_PART_IS_DEFINED(SAML21E17B) || \ + SAM_PART_IS_DEFINED(SAML21E18B) \ + ) + +#define SAML21G ( \ + SAM_PART_IS_DEFINED(SAML21G18A) || \ + SAM_PART_IS_DEFINED(SAML21G16B) || \ + SAM_PART_IS_DEFINED(SAML21G17B) || \ + SAM_PART_IS_DEFINED(SAML21G18B) \ + ) + +#define SAML21J ( \ + SAM_PART_IS_DEFINED(SAML21J18A) || \ + SAM_PART_IS_DEFINED(SAML21J16B) || \ + SAM_PART_IS_DEFINED(SAML21J17B) || \ + SAM_PART_IS_DEFINED(SAML21J18B) \ + ) + +/* Group for SAML21 A variant: SAML21[E/G/J][18]A */ +#define SAML21XXXA ( \ + SAM_PART_IS_DEFINED(SAML21E18A) || \ + SAM_PART_IS_DEFINED(SAML21G18A) || \ + SAM_PART_IS_DEFINED(SAML21J18A) \ + ) + +/* Group for SAML21 B variant: SAML21[E/G/J][15/16/1718]B */ +#define SAML21XXXB ( \ + SAM_PART_IS_DEFINED(SAML21E15B) || \ + SAM_PART_IS_DEFINED(SAML21E16B) || \ + SAM_PART_IS_DEFINED(SAML21E17B) || \ + SAM_PART_IS_DEFINED(SAML21E18B) || \ + SAM_PART_IS_DEFINED(SAML21G16B) || \ + SAM_PART_IS_DEFINED(SAML21G17B) || \ + SAM_PART_IS_DEFINED(SAML21G18B) || \ + SAM_PART_IS_DEFINED(SAML21J16B) || \ + SAM_PART_IS_DEFINED(SAML21J17B) || \ + SAM_PART_IS_DEFINED(SAML21J18B) \ + ) + +/** @} */ + +/** + * \name SAML22 series + * @{ + */ +#define SAML22N ( \ + SAM_PART_IS_DEFINED(SAML22N16A) || \ + SAM_PART_IS_DEFINED(SAML22N17A) || \ + SAM_PART_IS_DEFINED(SAML22N18A) \ + ) + +#define SAML22G ( \ + SAM_PART_IS_DEFINED(SAML22G16A) || \ + SAM_PART_IS_DEFINED(SAML22G17A) || \ + SAM_PART_IS_DEFINED(SAML22G18A) \ + ) + +#define SAML22J ( \ + SAM_PART_IS_DEFINED(SAML22J16A) || \ + SAM_PART_IS_DEFINED(SAML22J17A) || \ + SAM_PART_IS_DEFINED(SAML22J18A) \ + ) +/** @} */ + +/** + * \name SAMDA0 series + * @{ + */ +#define SAMDA0J ( \ + SAM_PART_IS_DEFINED(SAMDA0J14A) || \ + SAM_PART_IS_DEFINED(SAMDA0J15A) || \ + SAM_PART_IS_DEFINED(SAMDA0J16A) \ + ) + +#define SAMDA0G ( \ + SAM_PART_IS_DEFINED(SAMDA0G14A) || \ + SAM_PART_IS_DEFINED(SAMDA0G15A) || \ + SAM_PART_IS_DEFINED(SAMDA0G16A) \ + ) + +#define SAMDA0E ( \ + SAM_PART_IS_DEFINED(SAMDA0E14A) || \ + SAM_PART_IS_DEFINED(SAMDA0E15A) || \ + SAM_PART_IS_DEFINED(SAMDA0E16A) \ + ) +/** @} */ + +/** + * \name SAMDA1 series + * @{ + */ +#define SAMDA1J ( \ + SAM_PART_IS_DEFINED(SAMDA1J14A) || \ + SAM_PART_IS_DEFINED(SAMDA1J15A) || \ + SAM_PART_IS_DEFINED(SAMDA1J16A) \ + ) + +#define SAMDA1G ( \ + SAM_PART_IS_DEFINED(SAMDA1G14A) || \ + SAM_PART_IS_DEFINED(SAMDA1G15A) || \ + SAM_PART_IS_DEFINED(SAMDA1G16A) \ + ) + +#define SAMDA1E ( \ + SAM_PART_IS_DEFINED(SAMDA1E14A) || \ + SAM_PART_IS_DEFINED(SAMDA1E15A) || \ + SAM_PART_IS_DEFINED(SAMDA1E16A) \ + ) +/** @} */ + +/** + * \name SAMC20 series + * @{ + */ +#define SAMC20E ( \ + SAM_PART_IS_DEFINED(SAMC20E15A) || \ + SAM_PART_IS_DEFINED(SAMC20E16A) || \ + SAM_PART_IS_DEFINED(SAMC20E17A) || \ + SAM_PART_IS_DEFINED(SAMC20E18A) \ + ) + +#define SAMC20G ( \ + SAM_PART_IS_DEFINED(SAMC20G15A) || \ + SAM_PART_IS_DEFINED(SAMC20G16A) || \ + SAM_PART_IS_DEFINED(SAMC20G17A) || \ + SAM_PART_IS_DEFINED(SAMC20G18A) \ + ) + +#define SAMC20J ( \ + SAM_PART_IS_DEFINED(SAMC20J15A) || \ + SAM_PART_IS_DEFINED(SAMC20J16A) || \ + SAM_PART_IS_DEFINED(SAMC20J17A) || \ + SAM_PART_IS_DEFINED(SAMC20J18A) \ + ) +/** @} */ + +/** + * \name SAMC21 series + * @{ + */ +#define SAMC21E ( \ + SAM_PART_IS_DEFINED(SAMC21E15A) || \ + SAM_PART_IS_DEFINED(SAMC21E16A) || \ + SAM_PART_IS_DEFINED(SAMC21E17A) || \ + SAM_PART_IS_DEFINED(SAMC21E18A) \ + ) + +#define SAMC21G ( \ + SAM_PART_IS_DEFINED(SAMC21G15A) || \ + SAM_PART_IS_DEFINED(SAMC21G16A) || \ + SAM_PART_IS_DEFINED(SAMC21G17A) || \ + SAM_PART_IS_DEFINED(SAMC21G18A) \ + ) + +#define SAMC21J ( \ + SAM_PART_IS_DEFINED(SAMC21J15A) || \ + SAM_PART_IS_DEFINED(SAMC21J16A) || \ + SAM_PART_IS_DEFINED(SAMC21J17A) || \ + SAM_PART_IS_DEFINED(SAMC21J18A) \ + ) +/** @} */ + +/** + * \name SAM4E series + * @{ + */ +#define SAM4E8 ( \ + SAM_PART_IS_DEFINED(SAM4E8C) || \ + SAM_PART_IS_DEFINED(SAM4E8E) \ + ) + +#define SAM4E16 ( \ + SAM_PART_IS_DEFINED(SAM4E16C) || \ + SAM_PART_IS_DEFINED(SAM4E16E) \ + ) +/** @} */ + +/** + * \name SAM4N series + * @{ + */ +#define SAM4N8 ( \ + SAM_PART_IS_DEFINED(SAM4N8A) || \ + SAM_PART_IS_DEFINED(SAM4N8B) || \ + SAM_PART_IS_DEFINED(SAM4N8C) \ + ) + +#define SAM4N16 ( \ + SAM_PART_IS_DEFINED(SAM4N16B) || \ + SAM_PART_IS_DEFINED(SAM4N16C) \ + ) +/** @} */ + +/** + * \name SAM4C series + * @{ + */ +#define SAM4C4_0 ( \ + SAM_PART_IS_DEFINED(SAM4C4C_0) \ + ) + +#define SAM4C4_1 ( \ + SAM_PART_IS_DEFINED(SAM4C4C_1) \ + ) + +#define SAM4C4 (SAM4C4_0 || SAM4C4_1) + +#define SAM4C8_0 ( \ + SAM_PART_IS_DEFINED(SAM4C8C_0) \ + ) + +#define SAM4C8_1 ( \ + SAM_PART_IS_DEFINED(SAM4C8C_1) \ + ) + +#define SAM4C8 (SAM4C8_0 || SAM4C8_1) + +#define SAM4C16_0 ( \ + SAM_PART_IS_DEFINED(SAM4C16C_0) \ + ) + +#define SAM4C16_1 ( \ + SAM_PART_IS_DEFINED(SAM4C16C_1) \ + ) + +#define SAM4C16 (SAM4C16_0 || SAM4C16_1) + +#define SAM4C32_0 ( \ + SAM_PART_IS_DEFINED(SAM4C32C_0) ||\ + SAM_PART_IS_DEFINED(SAM4C32E_0) \ + ) + +#define SAM4C32_1 ( \ + SAM_PART_IS_DEFINED(SAM4C32C_1) ||\ + SAM_PART_IS_DEFINED(SAM4C32E_1) \ + ) + + +#define SAM4C32 (SAM4C32_0 || SAM4C32_1) + +/** @} */ + +/** + * \name SAM4CM series + * @{ + */ +#define SAM4CMP8_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMP8C_0) \ + ) + +#define SAM4CMP8_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMP8C_1) \ + ) + +#define SAM4CMP8 (SAM4CMP8_0 || SAM4CMP8_1) + +#define SAM4CMP16_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMP16C_0) \ + ) + +#define SAM4CMP16_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMP16C_1) \ + ) + +#define SAM4CMP16 (SAM4CMP16_0 || SAM4CMP16_1) + +#define SAM4CMP32_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMP32C_0) \ + ) + +#define SAM4CMP32_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMP32C_1) \ + ) + +#define SAM4CMP32 (SAM4CMP32_0 || SAM4CMP32_1) + +#define SAM4CMS4_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMS4C_0) \ + ) + +#define SAM4CMS4_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMS4C_1) \ + ) + +#define SAM4CMS4 (SAM4CMS4_0 || SAM4CMS4_1) + +#define SAM4CMS8_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMS8C_0) \ + ) + +#define SAM4CMS8_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMS8C_1) \ + ) + +#define SAM4CMS8 (SAM4CMS8_0 || SAM4CMS8_1) + +#define SAM4CMS16_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMS16C_0) \ + ) + +#define SAM4CMS16_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMS16C_1) \ + ) + +#define SAM4CMS16 (SAM4CMS16_0 || SAM4CMS16_1) + +#define SAM4CMS32_0 ( \ + SAM_PART_IS_DEFINED(SAM4CMS32C_0) \ + ) + +#define SAM4CMS32_1 ( \ + SAM_PART_IS_DEFINED(SAM4CMS32C_1) \ + ) + +#define SAM4CMS32 (SAM4CMS32_0 || SAM4CMS32_1) + +/** @} */ + +/** + * \name SAM4CP series + * @{ + */ +#define SAM4CP16_0 ( \ + SAM_PART_IS_DEFINED(SAM4CP16B_0) \ + ) + +#define SAM4CP16_1 ( \ + SAM_PART_IS_DEFINED(SAM4CP16B_1) \ + ) + +#define SAM4CP16 (SAM4CP16_0 || SAM4CP16_1) +/** @} */ + +/** + * \name SAMG series + * @{ + */ +#define SAMG51 ( \ + SAM_PART_IS_DEFINED(SAMG51G18) \ + ) + +#define SAMG53 ( \ + SAM_PART_IS_DEFINED(SAMG53G19) ||\ + SAM_PART_IS_DEFINED(SAMG53N19) \ + ) + +#define SAMG54 ( \ + SAM_PART_IS_DEFINED(SAMG54G19) ||\ + SAM_PART_IS_DEFINED(SAMG54J19) ||\ + SAM_PART_IS_DEFINED(SAMG54N19) \ + ) + +#define SAMG55 ( \ + SAM_PART_IS_DEFINED(SAMG55G18) ||\ + SAM_PART_IS_DEFINED(SAMG55G19) ||\ + SAM_PART_IS_DEFINED(SAMG55J18) ||\ + SAM_PART_IS_DEFINED(SAMG55J19) ||\ + SAM_PART_IS_DEFINED(SAMG55N19) \ + ) +/** @} */ + +/** + * \name SAMV71 series + * @{ + */ +#define SAMV71J ( \ + SAM_PART_IS_DEFINED(SAMV71J19) || \ + SAM_PART_IS_DEFINED(SAMV71J20) || \ + SAM_PART_IS_DEFINED(SAMV71J21) \ + ) + +#define SAMV71N ( \ + SAM_PART_IS_DEFINED(SAMV71N19) || \ + SAM_PART_IS_DEFINED(SAMV71N20) || \ + SAM_PART_IS_DEFINED(SAMV71N21) \ + ) + +#define SAMV71Q ( \ + SAM_PART_IS_DEFINED(SAMV71Q19) || \ + SAM_PART_IS_DEFINED(SAMV71Q20) || \ + SAM_PART_IS_DEFINED(SAMV71Q21) \ + ) +/** @} */ + +/** + * \name SAMV70 series + * @{ + */ +#define SAMV70J ( \ + SAM_PART_IS_DEFINED(SAMV70J19) || \ + SAM_PART_IS_DEFINED(SAMV70J20) \ + ) + +#define SAMV70N ( \ + SAM_PART_IS_DEFINED(SAMV70N19) || \ + SAM_PART_IS_DEFINED(SAMV70N20) \ + ) + +#define SAMV70Q ( \ + SAM_PART_IS_DEFINED(SAMV70Q19) || \ + SAM_PART_IS_DEFINED(SAMV70Q20) \ + ) +/** @} */ + +/** + * \name SAMS70 series + * @{ + */ +#define SAMS70J ( \ + SAM_PART_IS_DEFINED(SAMS70J19) || \ + SAM_PART_IS_DEFINED(SAMS70J20) || \ + SAM_PART_IS_DEFINED(SAMS70J21) \ + ) + +#define SAMS70N ( \ + SAM_PART_IS_DEFINED(SAMS70N19) || \ + SAM_PART_IS_DEFINED(SAMS70N20) || \ + SAM_PART_IS_DEFINED(SAMS70N21) \ + ) + +#define SAMS70Q ( \ + SAM_PART_IS_DEFINED(SAMS70Q19) || \ + SAM_PART_IS_DEFINED(SAMS70Q20) || \ + SAM_PART_IS_DEFINED(SAMS70Q21) \ + ) +/** @} */ + +/** + * \name SAME70 series + * @{ + */ +#define SAME70J ( \ + SAM_PART_IS_DEFINED(SAME70J19) || \ + SAM_PART_IS_DEFINED(SAME70J20) || \ + SAM_PART_IS_DEFINED(SAME70J21) \ + ) + +#define SAME70N ( \ + SAM_PART_IS_DEFINED(SAME70N19) || \ + SAM_PART_IS_DEFINED(SAME70N20) || \ + SAM_PART_IS_DEFINED(SAME70N21) \ + ) + +#define SAME70Q ( \ + SAM_PART_IS_DEFINED(SAME70Q19) || \ + SAM_PART_IS_DEFINED(SAME70Q20) || \ + SAM_PART_IS_DEFINED(SAME70Q21) \ + ) +/** @} */ + +/** + * \name SAM families + * @{ + */ +/** SAM3S Family */ +#define SAM3S (SAM3S1 || SAM3S2 || SAM3S4 || SAM3S8 || SAM3SD8) + +/** SAM3U Family */ +#define SAM3U (SAM3U1 || SAM3U2 || SAM3U4) + +/** SAM3N Family */ +#define SAM3N (SAM3N00 || SAM3N0 || SAM3N1 || SAM3N2 || SAM3N4) + +/** SAM3XA Family */ +#define SAM3XA (SAM3X4 || SAM3X8 || SAM3A4 || SAM3A8) + +/** SAM4S Family */ +#define SAM4S (SAM4S2 || SAM4S4 || SAM4S8 || SAM4S16 || SAM4SA16 || SAM4SD16 || SAM4SD32) + +/** SAM4L Family */ +#define SAM4L (SAM4LS || SAM4LC) + +/** SAMD20 Family */ +#define SAMD20 (SAMD20J || SAMD20G || SAMD20E) + +/** SAMD21 Family */ +#define SAMD21 (SAMD21J || SAMD21G || SAMD21E) + +/** SAMD09 Family */ +#define SAMD09 (SAMD09C || SAMD09D) + +/** SAMD10 Family */ +#define SAMD10 (SAMD10C || SAMD10DS || SAMD10DM) + +/** SAMD11 Family */ +#define SAMD11 (SAMD11C || SAMD11DS || SAMD11DM) + +/** SAMDA1 Family */ +#define SAMDA1 (SAMDA1J || SAMDA1G || SAMDA1E) + +/** SAMD Family */ +#define SAMD (SAMD20 || SAMD21 || SAMD09 || SAMD10 || SAMD11 || SAMDA1) + +/** SAMR21 Family */ +#define SAMR21 (SAMR21G || SAMR21E) + +/** SAML21 Family */ +#define SAML21 (SAML21J || SAML21G || SAML21E) + +/** SAML22 Family */ +#define SAML22 (SAML22J || SAML22G || SAML22N) +/** SAMC20 Family */ +#define SAMC20 (SAMC20J || SAMC20G || SAMC20E) + +/** SAMC21 Family */ +#define SAMC21 (SAMC21J || SAMC21G || SAMC21E) + +/** SAM4E Family */ +#define SAM4E (SAM4E8 || SAM4E16) + +/** SAM4N Family */ +#define SAM4N (SAM4N8 || SAM4N16) + +/** SAM4C Family */ +#define SAM4C_0 (SAM4C4_0 || SAM4C8_0 || SAM4C16_0 || SAM4C32_0) +#define SAM4C_1 (SAM4C4_1 || SAM4C8_1 || SAM4C16_1 || SAM4C32_1) +#define SAM4C (SAM4C4 || SAM4C8 || SAM4C16 || SAM4C32) + +/** SAM4CM Family */ +#define SAM4CM_0 (SAM4CMP8_0 || SAM4CMP16_0 || SAM4CMP32_0 || \ + SAM4CMS4_0 || SAM4CMS8_0 || SAM4CMS16_0 || SAM4CMS32_0) +#define SAM4CM_1 (SAM4CMP8_1 || SAM4CMP16_1 || SAM4CMP32_1 || \ + SAM4CMS4_1 || SAM4CMS8_1 || SAM4CMS16_1 || SAM4CMS32_1) +#define SAM4CM (SAM4CMP8 || SAM4CMP16 || SAM4CMP32 || \ + SAM4CMS4 || SAM4CMS8 || SAM4CMS16 || SAM4CMS32) + +/** SAM4CP Family */ +#define SAM4CP_0 (SAM4CP16_0) +#define SAM4CP_1 (SAM4CP16_1) +#define SAM4CP (SAM4CP16) + +/** SAMG Family */ +#define SAMG (SAMG51 || SAMG53 || SAMG54 || SAMG55) + +/** SAMV71 Family */ +#define SAMV71 (SAMV71J || SAMV71N || SAMV71Q) + +/** SAMV70 Family */ +#define SAMV70 (SAMV70J || SAMV70N || SAMV70Q) + +/** SAME70 Family */ +#define SAME70 (SAME70J || SAME70N || SAME70Q) + +/** SAMS70 Family */ +#define SAMS70 (SAMS70J || SAMS70N || SAMS70Q) + +/** SAM0 product line (cortex-m0+) */ +#define SAM0 (SAMD20 || SAMD21 || SAMR21 || SAMD10 || SAMD11 || SAML21 ||\ + SAMDA1 || SAMC20 || SAMC21 || SAML22 || SAMD09) + +/** @} */ + +/** SAM product line */ +#define SAM (SAM3S || SAM3U || SAM3N || SAM3XA || SAM4S || SAM4L || SAM4E || \ + SAM0 || SAM4N || SAM4C || SAM4CM || SAM4CP || SAMG || SAMV71 || SAMV70 || SAME70 || SAMS70) + +/** @} */ + +/** @} */ + +/** @} */ + +#endif /* ATMEL_PARTS_H */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/pinmux.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/pinmux.c new file mode 100644 index 0000000..a2c9c7c --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/pinmux.c @@ -0,0 +1,311 @@ +/** + * \file + * + * \brief SAM Pin Multiplexer Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#include + +/** + * \internal + * Writes out a given configuration of a Port pin configuration to the + * hardware module. + * + * \note If the pin direction is set as an output, the pull-up/pull-down input + * configuration setting is ignored. + * + * \param[in] port Base of the PORT module to configure + * \param[in] pin_mask Mask of the port pin to configure + * \param[in] config Configuration settings for the pin + */ +static void _system_pinmux_config( + PortGroup *const port, + const uint32_t pin_mask, + const struct system_pinmux_config *const config) +{ + Assert(port); + Assert(config); + + /* Track the configuration bits into a temporary variable before writing */ + uint32_t pin_cfg = 0; + + /* Enabled powersave mode, don't create configuration */ + if (!config->powersave) { + /* Enable the pin peripheral MUX flag if non-GPIO selected (pinmux will + * be written later) and store the new MUX mask */ + if (config->mux_position != SYSTEM_PINMUX_GPIO) { + pin_cfg |= PORT_WRCONFIG_PMUXEN; + pin_cfg |= (config->mux_position << PORT_WRCONFIG_PMUX_Pos); + } + + /* Check if the user has requested that the input buffer be enabled */ + if ((config->direction == SYSTEM_PINMUX_PIN_DIR_INPUT) || + (config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK)) { + /* Enable input buffer flag */ + pin_cfg |= PORT_WRCONFIG_INEN; + + /* Enable pull-up/pull-down control flag if requested */ + if (config->input_pull != SYSTEM_PINMUX_PIN_PULL_NONE) { + pin_cfg |= PORT_WRCONFIG_PULLEN; + } + + /* Clear the port DIR bits to disable the output buffer */ + port->DIRCLR.reg = pin_mask; + } + + /* Check if the user has requested that the output buffer be enabled */ + if ((config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT) || + (config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK)) { + /* Cannot use a pull-up if the output driver is enabled, + * if requested the input buffer can only sample the current + * output state */ + pin_cfg &= ~PORT_WRCONFIG_PULLEN; + } + } else { + port->DIRCLR.reg = pin_mask; + } + + /* The Write Configuration register (WRCONFIG) requires the + * pins to to grouped into two 16-bit half-words - split them out here */ + uint32_t lower_pin_mask = (pin_mask & 0xFFFF); + uint32_t upper_pin_mask = (pin_mask >> 16); + + /* Configure the lower 16-bits of the port to the desired configuration, + * including the pin peripheral multiplexer just in case it is enabled */ + port->WRCONFIG.reg + = (lower_pin_mask << PORT_WRCONFIG_PINMASK_Pos) | + pin_cfg | PORT_WRCONFIG_WRPMUX | PORT_WRCONFIG_WRPINCFG; + + /* Configure the upper 16-bits of the port to the desired configuration, + * including the pin peripheral multiplexer just in case it is enabled */ + port->WRCONFIG.reg + = (upper_pin_mask << PORT_WRCONFIG_PINMASK_Pos) | + pin_cfg | PORT_WRCONFIG_WRPMUX | PORT_WRCONFIG_WRPINCFG | + PORT_WRCONFIG_HWSEL; + + if(!config->powersave) { + /* Set the pull-up state once the port pins are configured if one was + * requested and it does not violate the valid set of port + * configurations */ + if (pin_cfg & PORT_WRCONFIG_PULLEN) { + /* Set the OUT register bits to enable the pull-up if requested, + * clear to enable pull-down */ + if (config->input_pull == SYSTEM_PINMUX_PIN_PULL_UP) { + port->OUTSET.reg = pin_mask; + } else { + port->OUTCLR.reg = pin_mask; + } + } + + /* Check if the user has requested that the output buffer be enabled */ + if ((config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT) || + (config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK)) { + /* Set the port DIR bits to enable the output buffer */ + port->DIRSET.reg = pin_mask; + } + } +} + +/** + * \brief Writes a Port pin configuration to the hardware module. + * + * Writes out a given configuration of a Port pin configuration to the hardware + * module. + * + * \note If the pin direction is set as an output, the pull-up/pull-down input + * configuration setting is ignored. + * + * \param[in] gpio_pin Index of the GPIO pin to configure + * \param[in] config Configuration settings for the pin + */ +void system_pinmux_pin_set_config( + const uint8_t gpio_pin, + const struct system_pinmux_config *const config) +{ + PortGroup *const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); + uint32_t pin_mask = (1UL << (gpio_pin % 32)); + + _system_pinmux_config(port, pin_mask, config); +} + +/** + * \brief Writes a Port pin group configuration to the hardware module. + * + * Writes out a given configuration of a Port pin group configuration to the + * hardware module. + * + * \note If the pin direction is set as an output, the pull-up/pull-down input + * configuration setting is ignored. + * + * \param[in] port Base of the PORT module to configure + * \param[in] mask Mask of the port pin(s) to configure + * \param[in] config Configuration settings for the pin + */ +void system_pinmux_group_set_config( + PortGroup *const port, + const uint32_t mask, + const struct system_pinmux_config *const config) +{ + Assert(port); + + for (int i = 0; i < 32; i++) { + if (mask & (1UL << i)) { + _system_pinmux_config(port, (1UL << i), config); + } + } +} + +/** + * \brief Configures the input sampling mode for a group of pins. + * + * Configures the input sampling mode for a group of pins, to + * control when the physical I/O pin value is sampled and + * stored inside the microcontroller. + * + * \param[in] port Base of the PORT module to configure + * \param[in] mask Mask of the port pin(s) to configure + * \param[in] mode New pin sampling mode to configure + */ +void system_pinmux_group_set_input_sample_mode( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_sample mode) +{ + Assert(port); + + if (mode == SYSTEM_PINMUX_PIN_SAMPLE_ONDEMAND) { + port->CTRL.reg |= mask; + } else { + port->CTRL.reg &= ~mask; + } +} + +#ifdef FEATURE_SYSTEM_PINMUX_SLEWRATE_LIMITER +/** + * \brief Configures the output slew rate mode for a group of pins. + * + * Configures the output slew rate mode for a group of pins, to + * control the speed at which the physical output pin can react to + * logical changes of the I/O pin value. + * + * \param[in] port Base of the PORT module to configure + * \param[in] mask Mask of the port pin(s) to configure + * \param[in] mode New pin slew rate mode to configure + */ +void system_pinmux_group_set_output_slew_rate( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_slew_rate mode) +{ + Assert(port); + + for (int i = 0; i < 32; i++) { + if (mask & (1UL << i)) { + if (mode == SYSTEM_PINMUX_PIN_SLEW_RATE_LIMITED) { + port->PINCFG[i].reg |= PORT_PINCFG_SLEWLIM; + } else { + port->PINCFG[i].reg &= ~PORT_PINCFG_SLEWLIM; + } + } + } +} +#endif + +#ifdef FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTH +/** + * \brief Configures the output driver strength mode for a group of pins. + * + * Configures the output drive strength for a group of pins, to + * control the amount of current the pad is able to sink/source. + * + * \param[in] port Base of the PORT module to configure + * \param[in] mask Mask of the port pin(s) to configure + * \param[in] mode New output driver strength mode to configure + */ +void system_pinmux_group_set_output_strength( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_strength mode) +{ + Assert(port); + + for (int i = 0; i < 32; i++) { + if (mask & (1UL << i)) { + if (mode == SYSTEM_PINMUX_PIN_STRENGTH_HIGH) { + port->PINCFG[i].reg |= PORT_PINCFG_DRVSTR; + } else { + port->PINCFG[i].reg &= ~PORT_PINCFG_DRVSTR; + } + } + } +} +#endif + +#ifdef FEATURE_SYSTEM_PINMUX_OPEN_DRAIN +/** + * \brief Configures the output driver mode for a group of pins. + * + * Configures the output driver mode for a group of pins, to + * control the pad behavior. + * + * \param[in] port Base of the PORT module to configure + * \param[in] mask Mask of the port pin(s) to configure + * \param[in] mode New pad output driver mode to configure + */ +void system_pinmux_group_set_output_drive( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_drive mode) +{ + Assert(port); + + for (int i = 0; i < 32; i++) { + if (mask & (1UL << i)) { + if (mode == SYSTEM_PINMUX_PIN_DRIVE_OPEN_DRAIN) { + port->PINCFG[i].reg |= PORT_PINCFG_ODRAIN; + } else { + port->PINCFG[i].reg &= ~PORT_PINCFG_ODRAIN; + } + } + } +} +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/pinmux.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/pinmux.h new file mode 100644 index 0000000..7a441cc --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/pinmux.h @@ -0,0 +1,678 @@ +/** + * \file + * + * \brief SAM Pin Multiplexer Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef PINMUX_H_INCLUDED +#define PINMUX_H_INCLUDED + +/** + * \defgroup asfdoc_sam0_system_pinmux_group SAM System Pin Multiplexer (SYSTEM PINMUX) Driver + * + * This driver for Atmel® | SMART ARM®-based microcontrollers provides + * an interface for the configuration and management of the device's physical + * I/O Pins, to alter the direction and input/drive characteristics as well as + * to configure the pin peripheral multiplexer selection. + * + * The following peripheral is used by this module: + * - PORT (Port I/O Management) + * + * The following devices can use this module: + * - Atmel | SMART SAM D20/D21 + * - Atmel | SMART SAM R21 + * - Atmel | SMART SAM D09/D10/D11 + * - Atmel | SMART SAM L21/L22 + * - Atmel | SMART SAM DA1 + * - Atmel | SMART SAM C20/C21 + * + * Physically, the modules are interconnected within the device as shown in the + * following diagram: + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_system_pinmux_prerequisites + * - \ref asfdoc_sam0_system_pinmux_module_overview + * - \ref asfdoc_sam0_system_pinmux_special_considerations + * - \ref asfdoc_sam0_system_pinmux_extra_info + * - \ref asfdoc_sam0_system_pinmux_examples + * - \ref asfdoc_sam0_system_pinmux_api_overview + * + * + * \section asfdoc_sam0_system_pinmux_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * + * \section asfdoc_sam0_system_pinmux_module_overview Module Overview + * + * The SAM devices contain a number of General Purpose I/O pins, used to + * interface the user application logic and internal hardware peripherals to + * an external system. The Pin Multiplexer (PINMUX) driver provides a method + * of configuring the individual pin peripheral multiplexers to select + * alternate pin functions. + * + * \subsection asfdoc_sam0_system_pinmux_features Driver Feature Macro Definition + * + * + * + * + * + * + * + * + * + *
Driver Feature MacroSupported devices
FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTHSAM L21, SAM C20/C21
+ * \note The specific features are only available in the driver when the + * selected device supports those features. + * + * \subsection asfdoc_sam0_system_pinmux_physical_logical_pins Physical and Logical GPIO Pins + * SAM devices use two naming conventions for the I/O pins in the device; one + * physical and one logical. Each physical pin on a device package is assigned + * both a physical port and pin identifier (e.g. "PORTA.0") as well as a + * monotonically incrementing logical GPIO number (e.g. "GPIO0"). While the + * former is used to map physical pins to their physical internal device module + * counterparts, for simplicity the design of this driver uses the logical GPIO + * numbers instead. + * + * \subsection asfdoc_sam0_system_pinmux_peripheral_muxing Peripheral Multiplexing + * SAM devices contain a peripheral MUX, which is individually controllable + * for each I/O pin of the device. The peripheral MUX allows you to select the + * function of a physical package pin - whether it will be controlled as a user + * controllable GPIO pin, or whether it will be connected internally to one of + * several peripheral modules (such as an I2C module). When a pin is + * configured in GPIO mode, other peripherals connected to the same pin will be + * disabled. + * + * \subsection asfdoc_sam0_system_pinmux_pad_characteristics Special Pad Characteristics + * There are several special modes that can be selected on one or more I/O pins + * of the device, which alter the input and output characteristics of the pad. + * + * \subsubsection asfdoc_sam0_system_pinmux_drive_strength Drive Strength + * The Drive Strength configures the strength of the output driver on the + * pad. Normally, there is a fixed current limit that each I/O pin can safely + * drive, however some I/O pads offer a higher drive mode which increases this + * limit for that I/O pin at the expense of an increased power consumption. + * + * \subsubsection asfdoc_sam0_system_pinmux_slew_rate Slew Rate + * The Slew Rate configures the slew rate of the output driver, limiting the + * rate at which the pad output voltage can change with time. + * + * \subsubsection asfdoc_sam0_system_pinmux_input_sample_mode Input Sample Mode + * The Input Sample Mode configures the input sampler buffer of the pad. By + * default, the input buffer is only sampled "on-demand", i.e. when the user + * application attempts to read from the input buffer. This mode is the most + * power efficient, but increases the latency of the input sample by two clock + * cycles of the port clock. To reduce latency, the input sampler can instead + * be configured to always sample the input buffer on each port clock cycle, at + * the expense of an increased power consumption. + * + * \subsection asfdoc_sam0_system_pinmux_module_overview_physical Physical Connection + * + * \ref asfdoc_sam0_system_pinmux_intconnections "The diagram below" shows + * how this module is interconnected within the device: + * + * \anchor asfdoc_sam0_system_pinmux_intconnections + * \dot + * digraph overview { + * node [label="Port Pad" shape=square] pad; + * + * subgraph driver { + * node [label="Peripheral MUX" shape=trapezium] pinmux; + * node [label="GPIO Module" shape=ellipse shape=ellipse style=filled fillcolor=lightgray] gpio; + * node [label="Other Peripheral Modules" shape=ellipse style=filled fillcolor=lightgray] peripherals; + * } + * + * pinmux -> gpio; + * pad -> pinmux; + * pinmux -> peripherals; + * } + * \enddot + * + * \section asfdoc_sam0_system_pinmux_special_considerations Special Considerations + * + * The SAM port pin input sampling mode is set in groups of four physical + * pins; setting the sampling mode of any pin in a sub-group of eight I/O pins + * will configure the sampling mode of the entire sub-group. + * + * High Drive Strength output driver mode is not available on all device pins - + * refer to your device specific datasheet. + * + * + * \section asfdoc_sam0_system_pinmux_extra_info Extra Information + * + * For extra information, see \ref asfdoc_sam0_system_pinmux_extra. This includes: + * - \ref asfdoc_sam0_system_pinmux_extra_acronyms + * - \ref asfdoc_sam0_system_pinmux_extra_dependencies + * - \ref asfdoc_sam0_system_pinmux_extra_errata + * - \ref asfdoc_sam0_system_pinmux_extra_history + * + * + * \section asfdoc_sam0_system_pinmux_examples Examples + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_system_pinmux_exqsg. + * + * + * \section asfdoc_sam0_system_pinmux_api_overview API Overview + * @{ + */ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/*@{*/ +#if (SAML21) || (SAMC20) || (SAMC21) || defined(__DOXYGEN__) +/** Output Driver Strength Selection feature support */ +# define FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTH +#endif +/*@}*/ + +/** Peripheral multiplexer index to select GPIO mode for a pin */ +#define SYSTEM_PINMUX_GPIO (1 << 7) + +/** + * \brief Port pin direction configuration enum. + * + * Enum for the possible pin direction settings of the port pin configuration + * structure, to indicate the direction the pin should use. + */ +enum system_pinmux_pin_dir { + /** The pin's input buffer should be enabled, so that the pin state can + * be read */ + SYSTEM_PINMUX_PIN_DIR_INPUT, + /** The pin's output buffer should be enabled, so that the pin state can + * be set (but not read back) */ + SYSTEM_PINMUX_PIN_DIR_OUTPUT, + /** The pin's output and input buffers should both be enabled, so that the + * pin state can be set and read back */ + SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK, +}; + +/** + * \brief Port pin input pull configuration enum. + * + * Enum for the possible pin pull settings of the port pin configuration + * structure, to indicate the type of logic level pull the pin should use. + */ +enum system_pinmux_pin_pull { + /** No logical pull should be applied to the pin */ + SYSTEM_PINMUX_PIN_PULL_NONE, + /** Pin should be pulled up when idle */ + SYSTEM_PINMUX_PIN_PULL_UP, + /** Pin should be pulled down when idle */ + SYSTEM_PINMUX_PIN_PULL_DOWN, +}; + +/** + * \brief Port pin digital input sampling mode enum. + * + * Enum for the possible input sampling modes for the port pin configuration + * structure, to indicate the type of sampling a port pin should use. + */ +enum system_pinmux_pin_sample { + /** Pin input buffer should continuously sample the pin state */ + SYSTEM_PINMUX_PIN_SAMPLE_CONTINUOUS, + /** Pin input buffer should be enabled when the IN register is read */ + SYSTEM_PINMUX_PIN_SAMPLE_ONDEMAND, +}; + +/** + * \brief Port pin configuration structure. + * + * Configuration structure for a port pin instance. This structure should + * be initialized by the \ref system_pinmux_get_config_defaults() function + * before being modified by the user application. + */ +struct system_pinmux_config { + /** MUX index of the peripheral that should control the pin, if peripheral + * control is desired. For GPIO use, this should be set to + * \ref SYSTEM_PINMUX_GPIO. */ + uint8_t mux_position; + + /** Port buffer input/output direction */ + enum system_pinmux_pin_dir direction; + + /** Logic level pull of the input buffer */ + enum system_pinmux_pin_pull input_pull; + + /** Enable lowest possible powerstate on the pin. + * + * \note All other configurations will be ignored, the pin will be disabled. + */ + bool powersave; +}; + +/** \name Configuration and Initialization + * @{ + */ + +/** + * \brief Initializes a Port pin configuration structure to defaults. + * + * Initializes a given Port pin configuration structure to a set of + * known default values. This function should be called on all new + * instances of these configuration structures before being modified by the + * user application. + * + * The default configuration is as follows: + * \li Non peripheral (i.e. GPIO) controlled + * \li Input mode with internal pull-up enabled + * + * \param[out] config Configuration structure to initialize to default values + */ +static inline void system_pinmux_get_config_defaults( + struct system_pinmux_config *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Default configuration values */ + config->mux_position = SYSTEM_PINMUX_GPIO; + config->direction = SYSTEM_PINMUX_PIN_DIR_INPUT; + config->input_pull = SYSTEM_PINMUX_PIN_PULL_UP; + config->powersave = false; +} + +void system_pinmux_pin_set_config( + const uint8_t gpio_pin, + const struct system_pinmux_config *const config); + +void system_pinmux_group_set_config( + PortGroup *const port, + const uint32_t mask, + const struct system_pinmux_config *const config); + +/** @} */ + +/** \name Special Mode Configuration (Physical Group Orientated) + * @{ + */ + +/** + * \brief Retrieves the PORT module group instance from a given GPIO pin number. + * + * Retrieves the PORT module group instance associated with a given logical + * GPIO pin number. + * + * \param[in] gpio_pin Index of the GPIO pin to convert + * + * \return Base address of the associated PORT module. + */ +static inline PortGroup* system_pinmux_get_group_from_gpio_pin( + const uint8_t gpio_pin) +{ + uint8_t port_index = (gpio_pin / 128); + uint8_t group_index = (gpio_pin / 32); + + /* Array of available ports */ + Port *const ports[PORT_INST_NUM] = PORT_INSTS; + + if (port_index < PORT_INST_NUM) { + return &(ports[port_index]->Group[group_index]); + } else { + Assert(false); + return NULL; + } +} + +void system_pinmux_group_set_input_sample_mode( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_sample mode); + +/** @} */ + +/** \name Special Mode Configuration (Logical Pin Orientated) + * @{ + */ + +/** + * \brief Retrieves the currently selected MUX position of a logical pin. + * + * Retrieves the selected MUX peripheral on a given logical GPIO pin. + * + * \param[in] gpio_pin Index of the GPIO pin to configure + * + * \return Currently selected peripheral index on the specified pin. + */ +static inline uint8_t system_pinmux_pin_get_mux_position( + const uint8_t gpio_pin) +{ + PortGroup *const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); + uint32_t pin_index = (gpio_pin % 32); + + if (!(port->PINCFG[pin_index].reg & PORT_PINCFG_PMUXEN)) { + return SYSTEM_PINMUX_GPIO; + } + + uint32_t pmux_reg = port->PMUX[pin_index / 2].reg; + + if (pin_index & 1) { + return (pmux_reg & PORT_PMUX_PMUXO_Msk) >> PORT_PMUX_PMUXO_Pos; + } + else { + return (pmux_reg & PORT_PMUX_PMUXE_Msk) >> PORT_PMUX_PMUXE_Pos; + } +} + +/** + * \brief Configures the input sampling mode for a GPIO pin. + * + * Configures the input sampling mode for a GPIO input, to + * control when the physical I/O pin value is sampled and + * stored inside the microcontroller. + * + * \param[in] gpio_pin Index of the GPIO pin to configure + * \param[in] mode New pin sampling mode to configure + */ +static inline void system_pinmux_pin_set_input_sample_mode( + const uint8_t gpio_pin, + const enum system_pinmux_pin_sample mode) +{ + PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); + uint32_t pin_index = (gpio_pin % 32); + + if (mode == SYSTEM_PINMUX_PIN_SAMPLE_ONDEMAND) { + port->CTRL.reg |= (1 << pin_index); + } else { + port->CTRL.reg &= ~(1 << pin_index); + } +} + +/** @} */ + +#ifdef FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTH +/** + * \brief Port pin drive output strength enum. + * + * Enum for the possible output drive strengths for the port pin + * configuration structure, to indicate the driver strength the pin should + * use. + */ +enum system_pinmux_pin_strength { + /** Normal output driver strength */ + SYSTEM_PINMUX_PIN_STRENGTH_NORMAL, + /** High current output driver strength */ + SYSTEM_PINMUX_PIN_STRENGTH_HIGH, +}; + +/** + * \brief Configures the output driver strength mode for a GPIO pin. + * + * Configures the output drive strength for a GPIO output, to + * control the amount of current the pad is able to sink/source. + * + * \param[in] gpio_pin Index of the GPIO pin to configure + * \param[in] mode New output driver strength mode to configure + */ +static inline void system_pinmux_pin_set_output_strength( + const uint8_t gpio_pin, + const enum system_pinmux_pin_strength mode) +{ + PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); + uint32_t pin_index = (gpio_pin % 32); + + if (mode == SYSTEM_PINMUX_PIN_STRENGTH_HIGH) { + port->PINCFG[pin_index].reg |= PORT_PINCFG_DRVSTR; + } + else { + port->PINCFG[pin_index].reg &= ~PORT_PINCFG_DRVSTR; + } +} + +void system_pinmux_group_set_output_strength( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_strength mode); +#endif + +#ifdef FEATURE_SYSTEM_PINMUX_SLEWRATE_LIMITER +/** + * \brief Port pin output slew rate enum. + * + * Enum for the possible output drive slew rates for the port pin + * configuration structure, to indicate the driver slew rate the pin should + * use. + */ +enum system_pinmux_pin_slew_rate { + /** Normal pin output slew rate */ + SYSTEM_PINMUX_PIN_SLEW_RATE_NORMAL, + /** Enable slew rate limiter on the pin */ + SYSTEM_PINMUX_PIN_SLEW_RATE_LIMITED, +}; + +/** + * \brief Configures the output slew rate mode for a GPIO pin. + * + * Configures the output slew rate mode for a GPIO output, to + * control the speed at which the physical output pin can react to + * logical changes of the I/O pin value. + * + * \param[in] gpio_pin Index of the GPIO pin to configure + * \param[in] mode New pin slew rate mode to configure + */ +static inline void system_pinmux_pin_set_output_slew_rate( + const uint8_t gpio_pin, + const enum system_pinmux_pin_slew_rate mode) +{ + PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); + uint32_t pin_index = (gpio_pin % 32); + + if (mode == SYSTEM_PINMUX_PIN_SLEW_RATE_LIMITED) { + port->PINCFG[pin_index].reg |= PORT_PINCFG_SLEWLIM; + } + else { + port->PINCFG[pin_index].reg &= ~PORT_PINCFG_SLEWLIM; + } +} + +void system_pinmux_group_set_output_slew_rate( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_slew_rate mode); +#endif + +#ifdef FEATURE_SYSTEM_PINMUX_OPEN_DRAIN +/** + * \brief Port pin output drive mode enum. + * + * Enum for the possible output drive modes for the port pin configuration + * structure, to indicate the output mode the pin should use. + */ +enum system_pinmux_pin_drive { + /** Use totem pole output drive mode */ + SYSTEM_PINMUX_PIN_DRIVE_TOTEM, + /** Use open drain output drive mode */ + SYSTEM_PINMUX_PIN_DRIVE_OPEN_DRAIN, +}; + +/** + * \brief Configures the output driver mode for a GPIO pin. + * + * Configures the output driver mode for a GPIO output, to + * control the pad behavior. + * + * \param[in] gpio_pin Index of the GPIO pin to configure + * \param[in] mode New pad output driver mode to configure + */ +static inline void system_pinmux_pin_set_output_drive( + const uint8_t gpio_pin, + const enum system_pinmux_pin_drive mode) +{ + PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); + uint32_t pin_index = (gpio_pin % 32); + + if (mode == SYSTEM_PINMUX_PIN_DRIVE_OPEN_DRAIN) { + port->PINCFG[pin_index].reg |= PORT_PINCFG_ODRAIN; + } + else { + port->PINCFG[pin_index].reg &= ~PORT_PINCFG_ODRAIN; + } +} + +void system_pinmux_group_set_output_drive( + PortGroup *const port, + const uint32_t mask, + const enum system_pinmux_pin_drive mode); +#endif + +#ifdef __cplusplus +} +#endif + +/** @} */ + +/** + * \page asfdoc_sam0_system_pinmux_extra Extra Information for SYSTEM PINMUX Driver + * + * \section asfdoc_sam0_system_pinmux_extra_acronyms Acronyms + * The table below presents the acronyms used in this module: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
AcronymDescription
GPIOGeneral Purpose Input/Output
MUXMultiplexer
+ * + * + * \section asfdoc_sam0_system_pinmux_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - None + * + * + * \section asfdoc_sam0_system_pinmux_extra_errata Errata + * There are no errata related to this driver. + * + * + * \section asfdoc_sam0_system_pinmux_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Changelog
Removed code of open drain, slew limit and drive strength + * features
Fixed broken sampling mode function implementations, which wrote + * corrupt configuration values to the device registers
Added missing NULL pointer asserts to the PORT driver functions
Initial Release
+ */ + +/** + * \page asfdoc_sam0_system_pinmux_exqsg Examples for SYSTEM PINMUX Driver + * + * This is a list of the available Quick Start guides (QSGs) and example + * applications for \ref asfdoc_sam0_system_pinmux_group. QSGs are simple + * examples with step-by-step instructions to configure and use this driver in a + * selection of use cases. Note that a QSG can be compiled as a standalone + * application or be added to the user application. + * + * - \subpage asfdoc_sam0_system_pinmux_basic_use_case + * + * \page asfdoc_sam0_system_pinmux_document_revision_history Document Revision History + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Doc. Rev. + * Date + * Comments + *
42121F08/2015Added support for SAM L21/L22, SAM DA1, and SAM C20/C21
42121E12/2014Added support for SAM R21 and SAM D10/D11
42121D01/2014Added support for SAM D21
42121C09/2013Fixed incorrect documentation for the device pin sampling mode
42121B06/2013Corrected documentation typos
42121A06/2013Initial release
+ */ + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/power.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/power.h new file mode 100644 index 0000000..5e90585 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/power.h @@ -0,0 +1,224 @@ +/** + * \file + * + * \brief SAM Power related functionality + * + * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef POWER_H_INCLUDED +#define POWER_H_INCLUDED + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \addtogroup asfdoc_sam0_system_group + * @{ + */ + +/** + * \brief Voltage references within the device. + * + * List of available voltage references (VREF) that may be used within the + * device. + */ +enum system_voltage_reference { + /** Temperature sensor voltage reference. */ + SYSTEM_VOLTAGE_REFERENCE_TEMPSENSE, + /** Bandgap voltage reference. */ + SYSTEM_VOLTAGE_REFERENCE_BANDGAP, +}; + +/** + * \brief Device sleep modes. + * + * List of available sleep modes in the device. A table of clocks available in + * different sleep modes can be found in \ref asfdoc_sam0_system_module_overview_sleep_mode. + */ +enum system_sleepmode { + /** IDLE 0 sleep mode. */ + SYSTEM_SLEEPMODE_IDLE_0, + /** IDLE 1 sleep mode. */ + SYSTEM_SLEEPMODE_IDLE_1, + /** IDLE 2 sleep mode. */ + SYSTEM_SLEEPMODE_IDLE_2, + /** Standby sleep mode. */ + SYSTEM_SLEEPMODE_STANDBY, +}; + + + +/** + * \name Voltage References + * @{ + */ + +/** + * \brief Enable the selected voltage reference + * + * Enables the selected voltage reference source, making the voltage reference + * available on a pin as well as an input source to the analog peripherals. + * + * \param[in] vref Voltage reference to enable + */ +static inline void system_voltage_reference_enable( + const enum system_voltage_reference vref) +{ + switch (vref) { + case SYSTEM_VOLTAGE_REFERENCE_TEMPSENSE: + SYSCTRL->VREF.reg |= SYSCTRL_VREF_TSEN; + break; + + case SYSTEM_VOLTAGE_REFERENCE_BANDGAP: + SYSCTRL->VREF.reg |= SYSCTRL_VREF_BGOUTEN; + break; + + default: + Assert(false); + return; + } +} + +/** + * \brief Disable the selected voltage reference + * + * Disables the selected voltage reference source. + * + * \param[in] vref Voltage reference to disable + */ +static inline void system_voltage_reference_disable( + const enum system_voltage_reference vref) +{ + switch (vref) { + case SYSTEM_VOLTAGE_REFERENCE_TEMPSENSE: + SYSCTRL->VREF.reg &= ~SYSCTRL_VREF_TSEN; + break; + + case SYSTEM_VOLTAGE_REFERENCE_BANDGAP: + SYSCTRL->VREF.reg &= ~SYSCTRL_VREF_BGOUTEN; + break; + + default: + Assert(false); + return; + } +} + +/** + * @} + */ + + +/** + * \name Device Sleep Control + * @{ + */ + +/** + * \brief Set the sleep mode of the device + * + * Sets the sleep mode of the device; the configured sleep mode will be entered + * upon the next call of the \ref system_sleep() function. + * + * For an overview of which systems are disabled in sleep for the different + * sleep modes, see \ref asfdoc_sam0_system_module_overview_sleep_mode. + * + * \param[in] sleep_mode Sleep mode to configure for the next sleep operation + * + * \retval STATUS_OK Operation completed successfully + * \retval STATUS_ERR_INVALID_ARG The requested sleep mode was invalid or not + * available + */ +static inline enum status_code system_set_sleepmode( + const enum system_sleepmode sleep_mode) +{ +#if (SAMD20 || SAMD21) + /* Errata: Make sure that the Flash does not power all the way down + * when in sleep mode. */ + NVMCTRL->CTRLB.bit.SLEEPPRM = NVMCTRL_CTRLB_SLEEPPRM_DISABLED_Val; +#endif + + switch (sleep_mode) { + case SYSTEM_SLEEPMODE_IDLE_0: + case SYSTEM_SLEEPMODE_IDLE_1: + case SYSTEM_SLEEPMODE_IDLE_2: + SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk; + PM->SLEEP.reg = sleep_mode; + break; + + case SYSTEM_SLEEPMODE_STANDBY: + SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; + break; + + default: + return STATUS_ERR_INVALID_ARG; + } + + return STATUS_OK; +} + +/** + * \brief Put the system to sleep waiting for interrupt + * + * Executes a device DSB (Data Synchronization Barrier) instruction to ensure + * all ongoing memory accesses have completed, then a WFI (Wait For Interrupt) + * instruction to place the device into the sleep mode specified by + * \ref system_set_sleepmode until woken by an interrupt. + */ +static inline void system_sleep(void) +{ + __DSB(); + __WFI(); +} + +/** + * @} + */ + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* POWER_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h new file mode 100644 index 0000000..4447927 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h @@ -0,0 +1,581 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef _MRECURSION_H_ +#define _MRECURSION_H_ + +/** + * \defgroup group_sam0_utils_mrecursion Preprocessor - Macro Recursion + * + * \ingroup group_sam0_utils + * + * @{ + */ + +#include "preprocessor.h" + +#define DEC_256 255 +#define DEC_255 254 +#define DEC_254 253 +#define DEC_253 252 +#define DEC_252 251 +#define DEC_251 250 +#define DEC_250 249 +#define DEC_249 248 +#define DEC_248 247 +#define DEC_247 246 +#define DEC_246 245 +#define DEC_245 244 +#define DEC_244 243 +#define DEC_243 242 +#define DEC_242 241 +#define DEC_241 240 +#define DEC_240 239 +#define DEC_239 238 +#define DEC_238 237 +#define DEC_237 236 +#define DEC_236 235 +#define DEC_235 234 +#define DEC_234 233 +#define DEC_233 232 +#define DEC_232 231 +#define DEC_231 230 +#define DEC_230 229 +#define DEC_229 228 +#define DEC_228 227 +#define DEC_227 226 +#define DEC_226 225 +#define DEC_225 224 +#define DEC_224 223 +#define DEC_223 222 +#define DEC_222 221 +#define DEC_221 220 +#define DEC_220 219 +#define DEC_219 218 +#define DEC_218 217 +#define DEC_217 216 +#define DEC_216 215 +#define DEC_215 214 +#define DEC_214 213 +#define DEC_213 212 +#define DEC_212 211 +#define DEC_211 210 +#define DEC_210 209 +#define DEC_209 208 +#define DEC_208 207 +#define DEC_207 206 +#define DEC_206 205 +#define DEC_205 204 +#define DEC_204 203 +#define DEC_203 202 +#define DEC_202 201 +#define DEC_201 200 +#define DEC_200 199 +#define DEC_199 198 +#define DEC_198 197 +#define DEC_197 196 +#define DEC_196 195 +#define DEC_195 194 +#define DEC_194 193 +#define DEC_193 192 +#define DEC_192 191 +#define DEC_191 190 +#define DEC_190 189 +#define DEC_189 188 +#define DEC_188 187 +#define DEC_187 186 +#define DEC_186 185 +#define DEC_185 184 +#define DEC_184 183 +#define DEC_183 182 +#define DEC_182 181 +#define DEC_181 180 +#define DEC_180 179 +#define DEC_179 178 +#define DEC_178 177 +#define DEC_177 176 +#define DEC_176 175 +#define DEC_175 174 +#define DEC_174 173 +#define DEC_173 172 +#define DEC_172 171 +#define DEC_171 170 +#define DEC_170 169 +#define DEC_169 168 +#define DEC_168 167 +#define DEC_167 166 +#define DEC_166 165 +#define DEC_165 164 +#define DEC_164 163 +#define DEC_163 162 +#define DEC_162 161 +#define DEC_161 160 +#define DEC_160 159 +#define DEC_159 158 +#define DEC_158 157 +#define DEC_157 156 +#define DEC_156 155 +#define DEC_155 154 +#define DEC_154 153 +#define DEC_153 152 +#define DEC_152 151 +#define DEC_151 150 +#define DEC_150 149 +#define DEC_149 148 +#define DEC_148 147 +#define DEC_147 146 +#define DEC_146 145 +#define DEC_145 144 +#define DEC_144 143 +#define DEC_143 142 +#define DEC_142 141 +#define DEC_141 140 +#define DEC_140 139 +#define DEC_139 138 +#define DEC_138 137 +#define DEC_137 136 +#define DEC_136 135 +#define DEC_135 134 +#define DEC_134 133 +#define DEC_133 132 +#define DEC_132 131 +#define DEC_131 130 +#define DEC_130 129 +#define DEC_129 128 +#define DEC_128 127 +#define DEC_127 126 +#define DEC_126 125 +#define DEC_125 124 +#define DEC_124 123 +#define DEC_123 122 +#define DEC_122 121 +#define DEC_121 120 +#define DEC_120 119 +#define DEC_119 118 +#define DEC_118 117 +#define DEC_117 116 +#define DEC_116 115 +#define DEC_115 114 +#define DEC_114 113 +#define DEC_113 112 +#define DEC_112 111 +#define DEC_111 110 +#define DEC_110 109 +#define DEC_109 108 +#define DEC_108 107 +#define DEC_107 106 +#define DEC_106 105 +#define DEC_105 104 +#define DEC_104 103 +#define DEC_103 102 +#define DEC_102 101 +#define DEC_101 100 +#define DEC_100 99 +#define DEC_99 98 +#define DEC_98 97 +#define DEC_97 96 +#define DEC_96 95 +#define DEC_95 94 +#define DEC_94 93 +#define DEC_93 92 +#define DEC_92 91 +#define DEC_91 90 +#define DEC_90 89 +#define DEC_89 88 +#define DEC_88 87 +#define DEC_87 86 +#define DEC_86 85 +#define DEC_85 84 +#define DEC_84 83 +#define DEC_83 82 +#define DEC_82 81 +#define DEC_81 80 +#define DEC_80 79 +#define DEC_79 78 +#define DEC_78 77 +#define DEC_77 76 +#define DEC_76 75 +#define DEC_75 74 +#define DEC_74 73 +#define DEC_73 72 +#define DEC_72 71 +#define DEC_71 70 +#define DEC_70 69 +#define DEC_69 68 +#define DEC_68 67 +#define DEC_67 66 +#define DEC_66 65 +#define DEC_65 64 +#define DEC_64 63 +#define DEC_63 62 +#define DEC_62 61 +#define DEC_61 60 +#define DEC_60 59 +#define DEC_59 58 +#define DEC_58 57 +#define DEC_57 56 +#define DEC_56 55 +#define DEC_55 54 +#define DEC_54 53 +#define DEC_53 52 +#define DEC_52 51 +#define DEC_51 50 +#define DEC_50 49 +#define DEC_49 48 +#define DEC_48 47 +#define DEC_47 46 +#define DEC_46 45 +#define DEC_45 44 +#define DEC_44 43 +#define DEC_43 42 +#define DEC_42 41 +#define DEC_41 40 +#define DEC_40 39 +#define DEC_39 38 +#define DEC_38 37 +#define DEC_37 36 +#define DEC_36 35 +#define DEC_35 34 +#define DEC_34 33 +#define DEC_33 32 +#define DEC_32 31 +#define DEC_31 30 +#define DEC_30 29 +#define DEC_29 28 +#define DEC_28 27 +#define DEC_27 26 +#define DEC_26 25 +#define DEC_25 24 +#define DEC_24 23 +#define DEC_23 22 +#define DEC_22 21 +#define DEC_21 20 +#define DEC_20 19 +#define DEC_19 18 +#define DEC_18 17 +#define DEC_17 16 +#define DEC_16 15 +#define DEC_15 14 +#define DEC_14 13 +#define DEC_13 12 +#define DEC_12 11 +#define DEC_11 10 +#define DEC_10 9 +#define DEC_9 8 +#define DEC_8 7 +#define DEC_7 6 +#define DEC_6 5 +#define DEC_5 4 +#define DEC_4 3 +#define DEC_3 2 +#define DEC_2 1 +#define DEC_1 0 +#define DEC_(n) DEC_##n + + +/** Maximal number of repetitions supported by MRECURSION. */ +#define MRECURSION_LIMIT 256 + +/** \brief Macro recursion. + * + * This macro represents a horizontal repetition construct. + * + * \param[in] count The number of repetitious calls to macro. Valid values + * range from 0 to MRECURSION_LIMIT. + * \param[in] macro A binary operation of the form macro(data, n). This macro + * is expanded by MRECURSION with the current repetition number + * and the auxiliary data argument. + * \param[in] data A recursive threshold, building on this to decline by times + * defined with param count. + * + * \return macro(data-count+1,0) macro(data-count+2,1)...macro(data,count-1) + */ +#define MRECURSION(count, macro, data) TPASTE2(MRECURSION, count) (macro, data) + +#define MRECURSION0( macro, data) +#define MRECURSION1( macro, data) MRECURSION0( macro, DEC_(data)) macro(data, 0) +#define MRECURSION2( macro, data) MRECURSION1( macro, DEC_(data)) macro(data, 1) +#define MRECURSION3( macro, data) MRECURSION2( macro, DEC_(data)) macro(data, 2) +#define MRECURSION4( macro, data) MRECURSION3( macro, DEC_(data)) macro(data, 3) +#define MRECURSION5( macro, data) MRECURSION4( macro, DEC_(data)) macro(data, 4) +#define MRECURSION6( macro, data) MRECURSION5( macro, DEC_(data)) macro(data, 5) +#define MRECURSION7( macro, data) MRECURSION6( macro, DEC_(data)) macro(data, 6) +#define MRECURSION8( macro, data) MRECURSION7( macro, DEC_(data)) macro(data, 7) +#define MRECURSION9( macro, data) MRECURSION8( macro, DEC_(data)) macro(data, 8) +#define MRECURSION10( macro, data) MRECURSION9( macro, DEC_(data)) macro(data, 9) +#define MRECURSION11( macro, data) MRECURSION10( macro, DEC_(data)) macro(data, 10) +#define MRECURSION12( macro, data) MRECURSION11( macro, DEC_(data)) macro(data, 11) +#define MRECURSION13( macro, data) MRECURSION12( macro, DEC_(data)) macro(data, 12) +#define MRECURSION14( macro, data) MRECURSION13( macro, DEC_(data)) macro(data, 13) +#define MRECURSION15( macro, data) MRECURSION14( macro, DEC_(data)) macro(data, 14) +#define MRECURSION16( macro, data) MRECURSION15( macro, DEC_(data)) macro(data, 15) +#define MRECURSION17( macro, data) MRECURSION16( macro, DEC_(data)) macro(data, 16) +#define MRECURSION18( macro, data) MRECURSION17( macro, DEC_(data)) macro(data, 17) +#define MRECURSION19( macro, data) MRECURSION18( macro, DEC_(data)) macro(data, 18) +#define MRECURSION20( macro, data) MRECURSION19( macro, DEC_(data)) macro(data, 19) +#define MRECURSION21( macro, data) MRECURSION20( macro, DEC_(data)) macro(data, 20) +#define MRECURSION22( macro, data) MRECURSION21( macro, DEC_(data)) macro(data, 21) +#define MRECURSION23( macro, data) MRECURSION22( macro, DEC_(data)) macro(data, 22) +#define MRECURSION24( macro, data) MRECURSION23( macro, DEC_(data)) macro(data, 23) +#define MRECURSION25( macro, data) MRECURSION24( macro, DEC_(data)) macro(data, 24) +#define MRECURSION26( macro, data) MRECURSION25( macro, DEC_(data)) macro(data, 25) +#define MRECURSION27( macro, data) MRECURSION26( macro, DEC_(data)) macro(data, 26) +#define MRECURSION28( macro, data) MRECURSION27( macro, DEC_(data)) macro(data, 27) +#define MRECURSION29( macro, data) MRECURSION28( macro, DEC_(data)) macro(data, 28) +#define MRECURSION30( macro, data) MRECURSION29( macro, DEC_(data)) macro(data, 29) +#define MRECURSION31( macro, data) MRECURSION30( macro, DEC_(data)) macro(data, 30) +#define MRECURSION32( macro, data) MRECURSION31( macro, DEC_(data)) macro(data, 31) +#define MRECURSION33( macro, data) MRECURSION32( macro, DEC_(data)) macro(data, 32) +#define MRECURSION34( macro, data) MRECURSION33( macro, DEC_(data)) macro(data, 33) +#define MRECURSION35( macro, data) MRECURSION34( macro, DEC_(data)) macro(data, 34) +#define MRECURSION36( macro, data) MRECURSION35( macro, DEC_(data)) macro(data, 35) +#define MRECURSION37( macro, data) MRECURSION36( macro, DEC_(data)) macro(data, 36) +#define MRECURSION38( macro, data) MRECURSION37( macro, DEC_(data)) macro(data, 37) +#define MRECURSION39( macro, data) MRECURSION38( macro, DEC_(data)) macro(data, 38) +#define MRECURSION40( macro, data) MRECURSION39( macro, DEC_(data)) macro(data, 39) +#define MRECURSION41( macro, data) MRECURSION40( macro, DEC_(data)) macro(data, 40) +#define MRECURSION42( macro, data) MRECURSION41( macro, DEC_(data)) macro(data, 41) +#define MRECURSION43( macro, data) MRECURSION42( macro, DEC_(data)) macro(data, 42) +#define MRECURSION44( macro, data) MRECURSION43( macro, DEC_(data)) macro(data, 43) +#define MRECURSION45( macro, data) MRECURSION44( macro, DEC_(data)) macro(data, 44) +#define MRECURSION46( macro, data) MRECURSION45( macro, DEC_(data)) macro(data, 45) +#define MRECURSION47( macro, data) MRECURSION46( macro, DEC_(data)) macro(data, 46) +#define MRECURSION48( macro, data) MRECURSION47( macro, DEC_(data)) macro(data, 47) +#define MRECURSION49( macro, data) MRECURSION48( macro, DEC_(data)) macro(data, 48) +#define MRECURSION50( macro, data) MRECURSION49( macro, DEC_(data)) macro(data, 49) +#define MRECURSION51( macro, data) MRECURSION50( macro, DEC_(data)) macro(data, 50) +#define MRECURSION52( macro, data) MRECURSION51( macro, DEC_(data)) macro(data, 51) +#define MRECURSION53( macro, data) MRECURSION52( macro, DEC_(data)) macro(data, 52) +#define MRECURSION54( macro, data) MRECURSION53( macro, DEC_(data)) macro(data, 53) +#define MRECURSION55( macro, data) MRECURSION54( macro, DEC_(data)) macro(data, 54) +#define MRECURSION56( macro, data) MRECURSION55( macro, DEC_(data)) macro(data, 55) +#define MRECURSION57( macro, data) MRECURSION56( macro, DEC_(data)) macro(data, 56) +#define MRECURSION58( macro, data) MRECURSION57( macro, DEC_(data)) macro(data, 57) +#define MRECURSION59( macro, data) MRECURSION58( macro, DEC_(data)) macro(data, 58) +#define MRECURSION60( macro, data) MRECURSION59( macro, DEC_(data)) macro(data, 59) +#define MRECURSION61( macro, data) MRECURSION60( macro, DEC_(data)) macro(data, 60) +#define MRECURSION62( macro, data) MRECURSION61( macro, DEC_(data)) macro(data, 61) +#define MRECURSION63( macro, data) MRECURSION62( macro, DEC_(data)) macro(data, 62) +#define MRECURSION64( macro, data) MRECURSION63( macro, DEC_(data)) macro(data, 63) +#define MRECURSION65( macro, data) MRECURSION64( macro, DEC_(data)) macro(data, 64) +#define MRECURSION66( macro, data) MRECURSION65( macro, DEC_(data)) macro(data, 65) +#define MRECURSION67( macro, data) MRECURSION66( macro, DEC_(data)) macro(data, 66) +#define MRECURSION68( macro, data) MRECURSION67( macro, DEC_(data)) macro(data, 67) +#define MRECURSION69( macro, data) MRECURSION68( macro, DEC_(data)) macro(data, 68) +#define MRECURSION70( macro, data) MRECURSION69( macro, DEC_(data)) macro(data, 69) +#define MRECURSION71( macro, data) MRECURSION70( macro, DEC_(data)) macro(data, 70) +#define MRECURSION72( macro, data) MRECURSION71( macro, DEC_(data)) macro(data, 71) +#define MRECURSION73( macro, data) MRECURSION72( macro, DEC_(data)) macro(data, 72) +#define MRECURSION74( macro, data) MRECURSION73( macro, DEC_(data)) macro(data, 73) +#define MRECURSION75( macro, data) MRECURSION74( macro, DEC_(data)) macro(data, 74) +#define MRECURSION76( macro, data) MRECURSION75( macro, DEC_(data)) macro(data, 75) +#define MRECURSION77( macro, data) MRECURSION76( macro, DEC_(data)) macro(data, 76) +#define MRECURSION78( macro, data) MRECURSION77( macro, DEC_(data)) macro(data, 77) +#define MRECURSION79( macro, data) MRECURSION78( macro, DEC_(data)) macro(data, 78) +#define MRECURSION80( macro, data) MRECURSION79( macro, DEC_(data)) macro(data, 79) +#define MRECURSION81( macro, data) MRECURSION80( macro, DEC_(data)) macro(data, 80) +#define MRECURSION82( macro, data) MRECURSION81( macro, DEC_(data)) macro(data, 81) +#define MRECURSION83( macro, data) MRECURSION82( macro, DEC_(data)) macro(data, 82) +#define MRECURSION84( macro, data) MRECURSION83( macro, DEC_(data)) macro(data, 83) +#define MRECURSION85( macro, data) MRECURSION84( macro, DEC_(data)) macro(data, 84) +#define MRECURSION86( macro, data) MRECURSION85( macro, DEC_(data)) macro(data, 85) +#define MRECURSION87( macro, data) MRECURSION86( macro, DEC_(data)) macro(data, 86) +#define MRECURSION88( macro, data) MRECURSION87( macro, DEC_(data)) macro(data, 87) +#define MRECURSION89( macro, data) MRECURSION88( macro, DEC_(data)) macro(data, 88) +#define MRECURSION90( macro, data) MRECURSION89( macro, DEC_(data)) macro(data, 89) +#define MRECURSION91( macro, data) MRECURSION90( macro, DEC_(data)) macro(data, 90) +#define MRECURSION92( macro, data) MRECURSION91( macro, DEC_(data)) macro(data, 91) +#define MRECURSION93( macro, data) MRECURSION92( macro, DEC_(data)) macro(data, 92) +#define MRECURSION94( macro, data) MRECURSION93( macro, DEC_(data)) macro(data, 93) +#define MRECURSION95( macro, data) MRECURSION94( macro, DEC_(data)) macro(data, 94) +#define MRECURSION96( macro, data) MRECURSION95( macro, DEC_(data)) macro(data, 95) +#define MRECURSION97( macro, data) MRECURSION96( macro, DEC_(data)) macro(data, 96) +#define MRECURSION98( macro, data) MRECURSION97( macro, DEC_(data)) macro(data, 97) +#define MRECURSION99( macro, data) MRECURSION98( macro, DEC_(data)) macro(data, 98) +#define MRECURSION100(macro, data) MRECURSION99( macro, DEC_(data)) macro(data, 99) +#define MRECURSION101(macro, data) MRECURSION100( macro, DEC_(data)) macro(data, 100) +#define MRECURSION102(macro, data) MRECURSION101( macro, DEC_(data)) macro(data, 101) +#define MRECURSION103(macro, data) MRECURSION102( macro, DEC_(data)) macro(data, 102) +#define MRECURSION104(macro, data) MRECURSION103( macro, DEC_(data)) macro(data, 103) +#define MRECURSION105(macro, data) MRECURSION104( macro, DEC_(data)) macro(data, 104) +#define MRECURSION106(macro, data) MRECURSION105( macro, DEC_(data)) macro(data, 105) +#define MRECURSION107(macro, data) MRECURSION106( macro, DEC_(data)) macro(data, 106) +#define MRECURSION108(macro, data) MRECURSION107( macro, DEC_(data)) macro(data, 107) +#define MRECURSION109(macro, data) MRECURSION108( macro, DEC_(data)) macro(data, 108) +#define MRECURSION110(macro, data) MRECURSION109( macro, DEC_(data)) macro(data, 109) +#define MRECURSION111(macro, data) MRECURSION110( macro, DEC_(data)) macro(data, 110) +#define MRECURSION112(macro, data) MRECURSION111( macro, DEC_(data)) macro(data, 111) +#define MRECURSION113(macro, data) MRECURSION112( macro, DEC_(data)) macro(data, 112) +#define MRECURSION114(macro, data) MRECURSION113( macro, DEC_(data)) macro(data, 113) +#define MRECURSION115(macro, data) MRECURSION114( macro, DEC_(data)) macro(data, 114) +#define MRECURSION116(macro, data) MRECURSION115( macro, DEC_(data)) macro(data, 115) +#define MRECURSION117(macro, data) MRECURSION116( macro, DEC_(data)) macro(data, 116) +#define MRECURSION118(macro, data) MRECURSION117( macro, DEC_(data)) macro(data, 117) +#define MRECURSION119(macro, data) MRECURSION118( macro, DEC_(data)) macro(data, 118) +#define MRECURSION120(macro, data) MRECURSION119( macro, DEC_(data)) macro(data, 119) +#define MRECURSION121(macro, data) MRECURSION120( macro, DEC_(data)) macro(data, 120) +#define MRECURSION122(macro, data) MRECURSION121( macro, DEC_(data)) macro(data, 121) +#define MRECURSION123(macro, data) MRECURSION122( macro, DEC_(data)) macro(data, 122) +#define MRECURSION124(macro, data) MRECURSION123( macro, DEC_(data)) macro(data, 123) +#define MRECURSION125(macro, data) MRECURSION124( macro, DEC_(data)) macro(data, 124) +#define MRECURSION126(macro, data) MRECURSION125( macro, DEC_(data)) macro(data, 125) +#define MRECURSION127(macro, data) MRECURSION126( macro, DEC_(data)) macro(data, 126) +#define MRECURSION128(macro, data) MRECURSION127( macro, DEC_(data)) macro(data, 127) +#define MRECURSION129(macro, data) MRECURSION128( macro, DEC_(data)) macro(data, 128) +#define MRECURSION130(macro, data) MRECURSION129( macro, DEC_(data)) macro(data, 129) +#define MRECURSION131(macro, data) MRECURSION130( macro, DEC_(data)) macro(data, 130) +#define MRECURSION132(macro, data) MRECURSION131( macro, DEC_(data)) macro(data, 131) +#define MRECURSION133(macro, data) MRECURSION132( macro, DEC_(data)) macro(data, 132) +#define MRECURSION134(macro, data) MRECURSION133( macro, DEC_(data)) macro(data, 133) +#define MRECURSION135(macro, data) MRECURSION134( macro, DEC_(data)) macro(data, 134) +#define MRECURSION136(macro, data) MRECURSION135( macro, DEC_(data)) macro(data, 135) +#define MRECURSION137(macro, data) MRECURSION136( macro, DEC_(data)) macro(data, 136) +#define MRECURSION138(macro, data) MRECURSION137( macro, DEC_(data)) macro(data, 137) +#define MRECURSION139(macro, data) MRECURSION138( macro, DEC_(data)) macro(data, 138) +#define MRECURSION140(macro, data) MRECURSION139( macro, DEC_(data)) macro(data, 139) +#define MRECURSION141(macro, data) MRECURSION140( macro, DEC_(data)) macro(data, 140) +#define MRECURSION142(macro, data) MRECURSION141( macro, DEC_(data)) macro(data, 141) +#define MRECURSION143(macro, data) MRECURSION142( macro, DEC_(data)) macro(data, 142) +#define MRECURSION144(macro, data) MRECURSION143( macro, DEC_(data)) macro(data, 143) +#define MRECURSION145(macro, data) MRECURSION144( macro, DEC_(data)) macro(data, 144) +#define MRECURSION146(macro, data) MRECURSION145( macro, DEC_(data)) macro(data, 145) +#define MRECURSION147(macro, data) MRECURSION146( macro, DEC_(data)) macro(data, 146) +#define MRECURSION148(macro, data) MRECURSION147( macro, DEC_(data)) macro(data, 147) +#define MRECURSION149(macro, data) MRECURSION148( macro, DEC_(data)) macro(data, 148) +#define MRECURSION150(macro, data) MRECURSION149( macro, DEC_(data)) macro(data, 149) +#define MRECURSION151(macro, data) MRECURSION150( macro, DEC_(data)) macro(data, 150) +#define MRECURSION152(macro, data) MRECURSION151( macro, DEC_(data)) macro(data, 151) +#define MRECURSION153(macro, data) MRECURSION152( macro, DEC_(data)) macro(data, 152) +#define MRECURSION154(macro, data) MRECURSION153( macro, DEC_(data)) macro(data, 153) +#define MRECURSION155(macro, data) MRECURSION154( macro, DEC_(data)) macro(data, 154) +#define MRECURSION156(macro, data) MRECURSION155( macro, DEC_(data)) macro(data, 155) +#define MRECURSION157(macro, data) MRECURSION156( macro, DEC_(data)) macro(data, 156) +#define MRECURSION158(macro, data) MRECURSION157( macro, DEC_(data)) macro(data, 157) +#define MRECURSION159(macro, data) MRECURSION158( macro, DEC_(data)) macro(data, 158) +#define MRECURSION160(macro, data) MRECURSION159( macro, DEC_(data)) macro(data, 159) +#define MRECURSION161(macro, data) MRECURSION160( macro, DEC_(data)) macro(data, 160) +#define MRECURSION162(macro, data) MRECURSION161( macro, DEC_(data)) macro(data, 161) +#define MRECURSION163(macro, data) MRECURSION162( macro, DEC_(data)) macro(data, 162) +#define MRECURSION164(macro, data) MRECURSION163( macro, DEC_(data)) macro(data, 163) +#define MRECURSION165(macro, data) MRECURSION164( macro, DEC_(data)) macro(data, 164) +#define MRECURSION166(macro, data) MRECURSION165( macro, DEC_(data)) macro(data, 165) +#define MRECURSION167(macro, data) MRECURSION166( macro, DEC_(data)) macro(data, 166) +#define MRECURSION168(macro, data) MRECURSION167( macro, DEC_(data)) macro(data, 167) +#define MRECURSION169(macro, data) MRECURSION168( macro, DEC_(data)) macro(data, 168) +#define MRECURSION170(macro, data) MRECURSION169( macro, DEC_(data)) macro(data, 169) +#define MRECURSION171(macro, data) MRECURSION170( macro, DEC_(data)) macro(data, 170) +#define MRECURSION172(macro, data) MRECURSION171( macro, DEC_(data)) macro(data, 171) +#define MRECURSION173(macro, data) MRECURSION172( macro, DEC_(data)) macro(data, 172) +#define MRECURSION174(macro, data) MRECURSION173( macro, DEC_(data)) macro(data, 173) +#define MRECURSION175(macro, data) MRECURSION174( macro, DEC_(data)) macro(data, 174) +#define MRECURSION176(macro, data) MRECURSION175( macro, DEC_(data)) macro(data, 175) +#define MRECURSION177(macro, data) MRECURSION176( macro, DEC_(data)) macro(data, 176) +#define MRECURSION178(macro, data) MRECURSION177( macro, DEC_(data)) macro(data, 177) +#define MRECURSION179(macro, data) MRECURSION178( macro, DEC_(data)) macro(data, 178) +#define MRECURSION180(macro, data) MRECURSION179( macro, DEC_(data)) macro(data, 179) +#define MRECURSION181(macro, data) MRECURSION180( macro, DEC_(data)) macro(data, 180) +#define MRECURSION182(macro, data) MRECURSION181( macro, DEC_(data)) macro(data, 181) +#define MRECURSION183(macro, data) MRECURSION182( macro, DEC_(data)) macro(data, 182) +#define MRECURSION184(macro, data) MRECURSION183( macro, DEC_(data)) macro(data, 183) +#define MRECURSION185(macro, data) MRECURSION184( macro, DEC_(data)) macro(data, 184) +#define MRECURSION186(macro, data) MRECURSION185( macro, DEC_(data)) macro(data, 185) +#define MRECURSION187(macro, data) MRECURSION186( macro, DEC_(data)) macro(data, 186) +#define MRECURSION188(macro, data) MRECURSION187( macro, DEC_(data)) macro(data, 187) +#define MRECURSION189(macro, data) MRECURSION188( macro, DEC_(data)) macro(data, 188) +#define MRECURSION190(macro, data) MRECURSION189( macro, DEC_(data)) macro(data, 189) +#define MRECURSION191(macro, data) MRECURSION190( macro, DEC_(data)) macro(data, 190) +#define MRECURSION192(macro, data) MRECURSION191( macro, DEC_(data)) macro(data, 191) +#define MRECURSION193(macro, data) MRECURSION192( macro, DEC_(data)) macro(data, 192) +#define MRECURSION194(macro, data) MRECURSION193( macro, DEC_(data)) macro(data, 193) +#define MRECURSION195(macro, data) MRECURSION194( macro, DEC_(data)) macro(data, 194) +#define MRECURSION196(macro, data) MRECURSION195( macro, DEC_(data)) macro(data, 195) +#define MRECURSION197(macro, data) MRECURSION196( macro, DEC_(data)) macro(data, 196) +#define MRECURSION198(macro, data) MRECURSION197( macro, DEC_(data)) macro(data, 197) +#define MRECURSION199(macro, data) MRECURSION198( macro, DEC_(data)) macro(data, 198) +#define MRECURSION200(macro, data) MRECURSION199( macro, DEC_(data)) macro(data, 199) +#define MRECURSION201(macro, data) MRECURSION200( macro, DEC_(data)) macro(data, 200) +#define MRECURSION202(macro, data) MRECURSION201( macro, DEC_(data)) macro(data, 201) +#define MRECURSION203(macro, data) MRECURSION202( macro, DEC_(data)) macro(data, 202) +#define MRECURSION204(macro, data) MRECURSION203( macro, DEC_(data)) macro(data, 203) +#define MRECURSION205(macro, data) MRECURSION204( macro, DEC_(data)) macro(data, 204) +#define MRECURSION206(macro, data) MRECURSION205( macro, DEC_(data)) macro(data, 205) +#define MRECURSION207(macro, data) MRECURSION206( macro, DEC_(data)) macro(data, 206) +#define MRECURSION208(macro, data) MRECURSION207( macro, DEC_(data)) macro(data, 207) +#define MRECURSION209(macro, data) MRECURSION208( macro, DEC_(data)) macro(data, 208) +#define MRECURSION210(macro, data) MRECURSION209( macro, DEC_(data)) macro(data, 209) +#define MRECURSION211(macro, data) MRECURSION210( macro, DEC_(data)) macro(data, 210) +#define MRECURSION212(macro, data) MRECURSION211( macro, DEC_(data)) macro(data, 211) +#define MRECURSION213(macro, data) MRECURSION212( macro, DEC_(data)) macro(data, 212) +#define MRECURSION214(macro, data) MRECURSION213( macro, DEC_(data)) macro(data, 213) +#define MRECURSION215(macro, data) MRECURSION214( macro, DEC_(data)) macro(data, 214) +#define MRECURSION216(macro, data) MRECURSION215( macro, DEC_(data)) macro(data, 215) +#define MRECURSION217(macro, data) MRECURSION216( macro, DEC_(data)) macro(data, 216) +#define MRECURSION218(macro, data) MRECURSION217( macro, DEC_(data)) macro(data, 217) +#define MRECURSION219(macro, data) MRECURSION218( macro, DEC_(data)) macro(data, 218) +#define MRECURSION220(macro, data) MRECURSION219( macro, DEC_(data)) macro(data, 219) +#define MRECURSION221(macro, data) MRECURSION220( macro, DEC_(data)) macro(data, 220) +#define MRECURSION222(macro, data) MRECURSION221( macro, DEC_(data)) macro(data, 221) +#define MRECURSION223(macro, data) MRECURSION222( macro, DEC_(data)) macro(data, 222) +#define MRECURSION224(macro, data) MRECURSION223( macro, DEC_(data)) macro(data, 223) +#define MRECURSION225(macro, data) MRECURSION224( macro, DEC_(data)) macro(data, 224) +#define MRECURSION226(macro, data) MRECURSION225( macro, DEC_(data)) macro(data, 225) +#define MRECURSION227(macro, data) MRECURSION226( macro, DEC_(data)) macro(data, 226) +#define MRECURSION228(macro, data) MRECURSION227( macro, DEC_(data)) macro(data, 227) +#define MRECURSION229(macro, data) MRECURSION228( macro, DEC_(data)) macro(data, 228) +#define MRECURSION230(macro, data) MRECURSION229( macro, DEC_(data)) macro(data, 229) +#define MRECURSION231(macro, data) MRECURSION230( macro, DEC_(data)) macro(data, 230) +#define MRECURSION232(macro, data) MRECURSION231( macro, DEC_(data)) macro(data, 231) +#define MRECURSION233(macro, data) MRECURSION232( macro, DEC_(data)) macro(data, 232) +#define MRECURSION234(macro, data) MRECURSION233( macro, DEC_(data)) macro(data, 233) +#define MRECURSION235(macro, data) MRECURSION234( macro, DEC_(data)) macro(data, 234) +#define MRECURSION236(macro, data) MRECURSION235( macro, DEC_(data)) macro(data, 235) +#define MRECURSION237(macro, data) MRECURSION236( macro, DEC_(data)) macro(data, 236) +#define MRECURSION238(macro, data) MRECURSION237( macro, DEC_(data)) macro(data, 237) +#define MRECURSION239(macro, data) MRECURSION238( macro, DEC_(data)) macro(data, 238) +#define MRECURSION240(macro, data) MRECURSION239( macro, DEC_(data)) macro(data, 239) +#define MRECURSION241(macro, data) MRECURSION240( macro, DEC_(data)) macro(data, 240) +#define MRECURSION242(macro, data) MRECURSION241( macro, DEC_(data)) macro(data, 241) +#define MRECURSION243(macro, data) MRECURSION242( macro, DEC_(data)) macro(data, 242) +#define MRECURSION244(macro, data) MRECURSION243( macro, DEC_(data)) macro(data, 243) +#define MRECURSION245(macro, data) MRECURSION244( macro, DEC_(data)) macro(data, 244) +#define MRECURSION246(macro, data) MRECURSION245( macro, DEC_(data)) macro(data, 245) +#define MRECURSION247(macro, data) MRECURSION246( macro, DEC_(data)) macro(data, 246) +#define MRECURSION248(macro, data) MRECURSION247( macro, DEC_(data)) macro(data, 247) +#define MRECURSION249(macro, data) MRECURSION248( macro, DEC_(data)) macro(data, 248) +#define MRECURSION250(macro, data) MRECURSION249( macro, DEC_(data)) macro(data, 249) +#define MRECURSION251(macro, data) MRECURSION250( macro, DEC_(data)) macro(data, 250) +#define MRECURSION252(macro, data) MRECURSION251( macro, DEC_(data)) macro(data, 251) +#define MRECURSION253(macro, data) MRECURSION252( macro, DEC_(data)) macro(data, 252) +#define MRECURSION254(macro, data) MRECURSION253( macro, DEC_(data)) macro(data, 253) +#define MRECURSION255(macro, data) MRECURSION254( macro, DEC_(data)) macro(data, 254) +#define MRECURSION256(macro, data) MRECURSION255( macro, DEC_(data)) macro(data, 255) + +/** @} */ + +#endif /* _MRECURSION_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h new file mode 100644 index 0000000..fb820d5 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h @@ -0,0 +1,321 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef _MREPEAT_H_ +#define _MREPEAT_H_ + +/** + * \defgroup group_sam0_utils_mrepeat Preprocessor - Macro Repeat + * + * \ingroup group_sam0_utils + * + * @{ + */ + +#include "preprocessor.h" + +/** Maximal number of repetitions supported by MREPEAT. */ +#define MREPEAT_LIMIT 256 + +/** \brief Macro repeat. + * + * This macro represents a horizontal repetition construct. + * + * \param[in] count The number of repetitious calls to macro. Valid values + * range from 0 to MREPEAT_LIMIT. + * \param[in] macro A binary operation of the form macro(n, data). This macro + * is expanded by MREPEAT with the current repetition number + * and the auxiliary data argument. + * \param[in] data Auxiliary data passed to macro. + * + * \return macro(0, data) macro(1, data) ... macro(count - 1, data) + */ +#define MREPEAT(count, macro, data) TPASTE2(MREPEAT, count) (macro, data) + +#define MREPEAT0( macro, data) +#define MREPEAT1( macro, data) MREPEAT0( macro, data) macro( 0, data) +#define MREPEAT2( macro, data) MREPEAT1( macro, data) macro( 1, data) +#define MREPEAT3( macro, data) MREPEAT2( macro, data) macro( 2, data) +#define MREPEAT4( macro, data) MREPEAT3( macro, data) macro( 3, data) +#define MREPEAT5( macro, data) MREPEAT4( macro, data) macro( 4, data) +#define MREPEAT6( macro, data) MREPEAT5( macro, data) macro( 5, data) +#define MREPEAT7( macro, data) MREPEAT6( macro, data) macro( 6, data) +#define MREPEAT8( macro, data) MREPEAT7( macro, data) macro( 7, data) +#define MREPEAT9( macro, data) MREPEAT8( macro, data) macro( 8, data) +#define MREPEAT10( macro, data) MREPEAT9( macro, data) macro( 9, data) +#define MREPEAT11( macro, data) MREPEAT10( macro, data) macro( 10, data) +#define MREPEAT12( macro, data) MREPEAT11( macro, data) macro( 11, data) +#define MREPEAT13( macro, data) MREPEAT12( macro, data) macro( 12, data) +#define MREPEAT14( macro, data) MREPEAT13( macro, data) macro( 13, data) +#define MREPEAT15( macro, data) MREPEAT14( macro, data) macro( 14, data) +#define MREPEAT16( macro, data) MREPEAT15( macro, data) macro( 15, data) +#define MREPEAT17( macro, data) MREPEAT16( macro, data) macro( 16, data) +#define MREPEAT18( macro, data) MREPEAT17( macro, data) macro( 17, data) +#define MREPEAT19( macro, data) MREPEAT18( macro, data) macro( 18, data) +#define MREPEAT20( macro, data) MREPEAT19( macro, data) macro( 19, data) +#define MREPEAT21( macro, data) MREPEAT20( macro, data) macro( 20, data) +#define MREPEAT22( macro, data) MREPEAT21( macro, data) macro( 21, data) +#define MREPEAT23( macro, data) MREPEAT22( macro, data) macro( 22, data) +#define MREPEAT24( macro, data) MREPEAT23( macro, data) macro( 23, data) +#define MREPEAT25( macro, data) MREPEAT24( macro, data) macro( 24, data) +#define MREPEAT26( macro, data) MREPEAT25( macro, data) macro( 25, data) +#define MREPEAT27( macro, data) MREPEAT26( macro, data) macro( 26, data) +#define MREPEAT28( macro, data) MREPEAT27( macro, data) macro( 27, data) +#define MREPEAT29( macro, data) MREPEAT28( macro, data) macro( 28, data) +#define MREPEAT30( macro, data) MREPEAT29( macro, data) macro( 29, data) +#define MREPEAT31( macro, data) MREPEAT30( macro, data) macro( 30, data) +#define MREPEAT32( macro, data) MREPEAT31( macro, data) macro( 31, data) +#define MREPEAT33( macro, data) MREPEAT32( macro, data) macro( 32, data) +#define MREPEAT34( macro, data) MREPEAT33( macro, data) macro( 33, data) +#define MREPEAT35( macro, data) MREPEAT34( macro, data) macro( 34, data) +#define MREPEAT36( macro, data) MREPEAT35( macro, data) macro( 35, data) +#define MREPEAT37( macro, data) MREPEAT36( macro, data) macro( 36, data) +#define MREPEAT38( macro, data) MREPEAT37( macro, data) macro( 37, data) +#define MREPEAT39( macro, data) MREPEAT38( macro, data) macro( 38, data) +#define MREPEAT40( macro, data) MREPEAT39( macro, data) macro( 39, data) +#define MREPEAT41( macro, data) MREPEAT40( macro, data) macro( 40, data) +#define MREPEAT42( macro, data) MREPEAT41( macro, data) macro( 41, data) +#define MREPEAT43( macro, data) MREPEAT42( macro, data) macro( 42, data) +#define MREPEAT44( macro, data) MREPEAT43( macro, data) macro( 43, data) +#define MREPEAT45( macro, data) MREPEAT44( macro, data) macro( 44, data) +#define MREPEAT46( macro, data) MREPEAT45( macro, data) macro( 45, data) +#define MREPEAT47( macro, data) MREPEAT46( macro, data) macro( 46, data) +#define MREPEAT48( macro, data) MREPEAT47( macro, data) macro( 47, data) +#define MREPEAT49( macro, data) MREPEAT48( macro, data) macro( 48, data) +#define MREPEAT50( macro, data) MREPEAT49( macro, data) macro( 49, data) +#define MREPEAT51( macro, data) MREPEAT50( macro, data) macro( 50, data) +#define MREPEAT52( macro, data) MREPEAT51( macro, data) macro( 51, data) +#define MREPEAT53( macro, data) MREPEAT52( macro, data) macro( 52, data) +#define MREPEAT54( macro, data) MREPEAT53( macro, data) macro( 53, data) +#define MREPEAT55( macro, data) MREPEAT54( macro, data) macro( 54, data) +#define MREPEAT56( macro, data) MREPEAT55( macro, data) macro( 55, data) +#define MREPEAT57( macro, data) MREPEAT56( macro, data) macro( 56, data) +#define MREPEAT58( macro, data) MREPEAT57( macro, data) macro( 57, data) +#define MREPEAT59( macro, data) MREPEAT58( macro, data) macro( 58, data) +#define MREPEAT60( macro, data) MREPEAT59( macro, data) macro( 59, data) +#define MREPEAT61( macro, data) MREPEAT60( macro, data) macro( 60, data) +#define MREPEAT62( macro, data) MREPEAT61( macro, data) macro( 61, data) +#define MREPEAT63( macro, data) MREPEAT62( macro, data) macro( 62, data) +#define MREPEAT64( macro, data) MREPEAT63( macro, data) macro( 63, data) +#define MREPEAT65( macro, data) MREPEAT64( macro, data) macro( 64, data) +#define MREPEAT66( macro, data) MREPEAT65( macro, data) macro( 65, data) +#define MREPEAT67( macro, data) MREPEAT66( macro, data) macro( 66, data) +#define MREPEAT68( macro, data) MREPEAT67( macro, data) macro( 67, data) +#define MREPEAT69( macro, data) MREPEAT68( macro, data) macro( 68, data) +#define MREPEAT70( macro, data) MREPEAT69( macro, data) macro( 69, data) +#define MREPEAT71( macro, data) MREPEAT70( macro, data) macro( 70, data) +#define MREPEAT72( macro, data) MREPEAT71( macro, data) macro( 71, data) +#define MREPEAT73( macro, data) MREPEAT72( macro, data) macro( 72, data) +#define MREPEAT74( macro, data) MREPEAT73( macro, data) macro( 73, data) +#define MREPEAT75( macro, data) MREPEAT74( macro, data) macro( 74, data) +#define MREPEAT76( macro, data) MREPEAT75( macro, data) macro( 75, data) +#define MREPEAT77( macro, data) MREPEAT76( macro, data) macro( 76, data) +#define MREPEAT78( macro, data) MREPEAT77( macro, data) macro( 77, data) +#define MREPEAT79( macro, data) MREPEAT78( macro, data) macro( 78, data) +#define MREPEAT80( macro, data) MREPEAT79( macro, data) macro( 79, data) +#define MREPEAT81( macro, data) MREPEAT80( macro, data) macro( 80, data) +#define MREPEAT82( macro, data) MREPEAT81( macro, data) macro( 81, data) +#define MREPEAT83( macro, data) MREPEAT82( macro, data) macro( 82, data) +#define MREPEAT84( macro, data) MREPEAT83( macro, data) macro( 83, data) +#define MREPEAT85( macro, data) MREPEAT84( macro, data) macro( 84, data) +#define MREPEAT86( macro, data) MREPEAT85( macro, data) macro( 85, data) +#define MREPEAT87( macro, data) MREPEAT86( macro, data) macro( 86, data) +#define MREPEAT88( macro, data) MREPEAT87( macro, data) macro( 87, data) +#define MREPEAT89( macro, data) MREPEAT88( macro, data) macro( 88, data) +#define MREPEAT90( macro, data) MREPEAT89( macro, data) macro( 89, data) +#define MREPEAT91( macro, data) MREPEAT90( macro, data) macro( 90, data) +#define MREPEAT92( macro, data) MREPEAT91( macro, data) macro( 91, data) +#define MREPEAT93( macro, data) MREPEAT92( macro, data) macro( 92, data) +#define MREPEAT94( macro, data) MREPEAT93( macro, data) macro( 93, data) +#define MREPEAT95( macro, data) MREPEAT94( macro, data) macro( 94, data) +#define MREPEAT96( macro, data) MREPEAT95( macro, data) macro( 95, data) +#define MREPEAT97( macro, data) MREPEAT96( macro, data) macro( 96, data) +#define MREPEAT98( macro, data) MREPEAT97( macro, data) macro( 97, data) +#define MREPEAT99( macro, data) MREPEAT98( macro, data) macro( 98, data) +#define MREPEAT100(macro, data) MREPEAT99( macro, data) macro( 99, data) +#define MREPEAT101(macro, data) MREPEAT100(macro, data) macro(100, data) +#define MREPEAT102(macro, data) MREPEAT101(macro, data) macro(101, data) +#define MREPEAT103(macro, data) MREPEAT102(macro, data) macro(102, data) +#define MREPEAT104(macro, data) MREPEAT103(macro, data) macro(103, data) +#define MREPEAT105(macro, data) MREPEAT104(macro, data) macro(104, data) +#define MREPEAT106(macro, data) MREPEAT105(macro, data) macro(105, data) +#define MREPEAT107(macro, data) MREPEAT106(macro, data) macro(106, data) +#define MREPEAT108(macro, data) MREPEAT107(macro, data) macro(107, data) +#define MREPEAT109(macro, data) MREPEAT108(macro, data) macro(108, data) +#define MREPEAT110(macro, data) MREPEAT109(macro, data) macro(109, data) +#define MREPEAT111(macro, data) MREPEAT110(macro, data) macro(110, data) +#define MREPEAT112(macro, data) MREPEAT111(macro, data) macro(111, data) +#define MREPEAT113(macro, data) MREPEAT112(macro, data) macro(112, data) +#define MREPEAT114(macro, data) MREPEAT113(macro, data) macro(113, data) +#define MREPEAT115(macro, data) MREPEAT114(macro, data) macro(114, data) +#define MREPEAT116(macro, data) MREPEAT115(macro, data) macro(115, data) +#define MREPEAT117(macro, data) MREPEAT116(macro, data) macro(116, data) +#define MREPEAT118(macro, data) MREPEAT117(macro, data) macro(117, data) +#define MREPEAT119(macro, data) MREPEAT118(macro, data) macro(118, data) +#define MREPEAT120(macro, data) MREPEAT119(macro, data) macro(119, data) +#define MREPEAT121(macro, data) MREPEAT120(macro, data) macro(120, data) +#define MREPEAT122(macro, data) MREPEAT121(macro, data) macro(121, data) +#define MREPEAT123(macro, data) MREPEAT122(macro, data) macro(122, data) +#define MREPEAT124(macro, data) MREPEAT123(macro, data) macro(123, data) +#define MREPEAT125(macro, data) MREPEAT124(macro, data) macro(124, data) +#define MREPEAT126(macro, data) MREPEAT125(macro, data) macro(125, data) +#define MREPEAT127(macro, data) MREPEAT126(macro, data) macro(126, data) +#define MREPEAT128(macro, data) MREPEAT127(macro, data) macro(127, data) +#define MREPEAT129(macro, data) MREPEAT128(macro, data) macro(128, data) +#define MREPEAT130(macro, data) MREPEAT129(macro, data) macro(129, data) +#define MREPEAT131(macro, data) MREPEAT130(macro, data) macro(130, data) +#define MREPEAT132(macro, data) MREPEAT131(macro, data) macro(131, data) +#define MREPEAT133(macro, data) MREPEAT132(macro, data) macro(132, data) +#define MREPEAT134(macro, data) MREPEAT133(macro, data) macro(133, data) +#define MREPEAT135(macro, data) MREPEAT134(macro, data) macro(134, data) +#define MREPEAT136(macro, data) MREPEAT135(macro, data) macro(135, data) +#define MREPEAT137(macro, data) MREPEAT136(macro, data) macro(136, data) +#define MREPEAT138(macro, data) MREPEAT137(macro, data) macro(137, data) +#define MREPEAT139(macro, data) MREPEAT138(macro, data) macro(138, data) +#define MREPEAT140(macro, data) MREPEAT139(macro, data) macro(139, data) +#define MREPEAT141(macro, data) MREPEAT140(macro, data) macro(140, data) +#define MREPEAT142(macro, data) MREPEAT141(macro, data) macro(141, data) +#define MREPEAT143(macro, data) MREPEAT142(macro, data) macro(142, data) +#define MREPEAT144(macro, data) MREPEAT143(macro, data) macro(143, data) +#define MREPEAT145(macro, data) MREPEAT144(macro, data) macro(144, data) +#define MREPEAT146(macro, data) MREPEAT145(macro, data) macro(145, data) +#define MREPEAT147(macro, data) MREPEAT146(macro, data) macro(146, data) +#define MREPEAT148(macro, data) MREPEAT147(macro, data) macro(147, data) +#define MREPEAT149(macro, data) MREPEAT148(macro, data) macro(148, data) +#define MREPEAT150(macro, data) MREPEAT149(macro, data) macro(149, data) +#define MREPEAT151(macro, data) MREPEAT150(macro, data) macro(150, data) +#define MREPEAT152(macro, data) MREPEAT151(macro, data) macro(151, data) +#define MREPEAT153(macro, data) MREPEAT152(macro, data) macro(152, data) +#define MREPEAT154(macro, data) MREPEAT153(macro, data) macro(153, data) +#define MREPEAT155(macro, data) MREPEAT154(macro, data) macro(154, data) +#define MREPEAT156(macro, data) MREPEAT155(macro, data) macro(155, data) +#define MREPEAT157(macro, data) MREPEAT156(macro, data) macro(156, data) +#define MREPEAT158(macro, data) MREPEAT157(macro, data) macro(157, data) +#define MREPEAT159(macro, data) MREPEAT158(macro, data) macro(158, data) +#define MREPEAT160(macro, data) MREPEAT159(macro, data) macro(159, data) +#define MREPEAT161(macro, data) MREPEAT160(macro, data) macro(160, data) +#define MREPEAT162(macro, data) MREPEAT161(macro, data) macro(161, data) +#define MREPEAT163(macro, data) MREPEAT162(macro, data) macro(162, data) +#define MREPEAT164(macro, data) MREPEAT163(macro, data) macro(163, data) +#define MREPEAT165(macro, data) MREPEAT164(macro, data) macro(164, data) +#define MREPEAT166(macro, data) MREPEAT165(macro, data) macro(165, data) +#define MREPEAT167(macro, data) MREPEAT166(macro, data) macro(166, data) +#define MREPEAT168(macro, data) MREPEAT167(macro, data) macro(167, data) +#define MREPEAT169(macro, data) MREPEAT168(macro, data) macro(168, data) +#define MREPEAT170(macro, data) MREPEAT169(macro, data) macro(169, data) +#define MREPEAT171(macro, data) MREPEAT170(macro, data) macro(170, data) +#define MREPEAT172(macro, data) MREPEAT171(macro, data) macro(171, data) +#define MREPEAT173(macro, data) MREPEAT172(macro, data) macro(172, data) +#define MREPEAT174(macro, data) MREPEAT173(macro, data) macro(173, data) +#define MREPEAT175(macro, data) MREPEAT174(macro, data) macro(174, data) +#define MREPEAT176(macro, data) MREPEAT175(macro, data) macro(175, data) +#define MREPEAT177(macro, data) MREPEAT176(macro, data) macro(176, data) +#define MREPEAT178(macro, data) MREPEAT177(macro, data) macro(177, data) +#define MREPEAT179(macro, data) MREPEAT178(macro, data) macro(178, data) +#define MREPEAT180(macro, data) MREPEAT179(macro, data) macro(179, data) +#define MREPEAT181(macro, data) MREPEAT180(macro, data) macro(180, data) +#define MREPEAT182(macro, data) MREPEAT181(macro, data) macro(181, data) +#define MREPEAT183(macro, data) MREPEAT182(macro, data) macro(182, data) +#define MREPEAT184(macro, data) MREPEAT183(macro, data) macro(183, data) +#define MREPEAT185(macro, data) MREPEAT184(macro, data) macro(184, data) +#define MREPEAT186(macro, data) MREPEAT185(macro, data) macro(185, data) +#define MREPEAT187(macro, data) MREPEAT186(macro, data) macro(186, data) +#define MREPEAT188(macro, data) MREPEAT187(macro, data) macro(187, data) +#define MREPEAT189(macro, data) MREPEAT188(macro, data) macro(188, data) +#define MREPEAT190(macro, data) MREPEAT189(macro, data) macro(189, data) +#define MREPEAT191(macro, data) MREPEAT190(macro, data) macro(190, data) +#define MREPEAT192(macro, data) MREPEAT191(macro, data) macro(191, data) +#define MREPEAT193(macro, data) MREPEAT192(macro, data) macro(192, data) +#define MREPEAT194(macro, data) MREPEAT193(macro, data) macro(193, data) +#define MREPEAT195(macro, data) MREPEAT194(macro, data) macro(194, data) +#define MREPEAT196(macro, data) MREPEAT195(macro, data) macro(195, data) +#define MREPEAT197(macro, data) MREPEAT196(macro, data) macro(196, data) +#define MREPEAT198(macro, data) MREPEAT197(macro, data) macro(197, data) +#define MREPEAT199(macro, data) MREPEAT198(macro, data) macro(198, data) +#define MREPEAT200(macro, data) MREPEAT199(macro, data) macro(199, data) +#define MREPEAT201(macro, data) MREPEAT200(macro, data) macro(200, data) +#define MREPEAT202(macro, data) MREPEAT201(macro, data) macro(201, data) +#define MREPEAT203(macro, data) MREPEAT202(macro, data) macro(202, data) +#define MREPEAT204(macro, data) MREPEAT203(macro, data) macro(203, data) +#define MREPEAT205(macro, data) MREPEAT204(macro, data) macro(204, data) +#define MREPEAT206(macro, data) MREPEAT205(macro, data) macro(205, data) +#define MREPEAT207(macro, data) MREPEAT206(macro, data) macro(206, data) +#define MREPEAT208(macro, data) MREPEAT207(macro, data) macro(207, data) +#define MREPEAT209(macro, data) MREPEAT208(macro, data) macro(208, data) +#define MREPEAT210(macro, data) MREPEAT209(macro, data) macro(209, data) +#define MREPEAT211(macro, data) MREPEAT210(macro, data) macro(210, data) +#define MREPEAT212(macro, data) MREPEAT211(macro, data) macro(211, data) +#define MREPEAT213(macro, data) MREPEAT212(macro, data) macro(212, data) +#define MREPEAT214(macro, data) MREPEAT213(macro, data) macro(213, data) +#define MREPEAT215(macro, data) MREPEAT214(macro, data) macro(214, data) +#define MREPEAT216(macro, data) MREPEAT215(macro, data) macro(215, data) +#define MREPEAT217(macro, data) MREPEAT216(macro, data) macro(216, data) +#define MREPEAT218(macro, data) MREPEAT217(macro, data) macro(217, data) +#define MREPEAT219(macro, data) MREPEAT218(macro, data) macro(218, data) +#define MREPEAT220(macro, data) MREPEAT219(macro, data) macro(219, data) +#define MREPEAT221(macro, data) MREPEAT220(macro, data) macro(220, data) +#define MREPEAT222(macro, data) MREPEAT221(macro, data) macro(221, data) +#define MREPEAT223(macro, data) MREPEAT222(macro, data) macro(222, data) +#define MREPEAT224(macro, data) MREPEAT223(macro, data) macro(223, data) +#define MREPEAT225(macro, data) MREPEAT224(macro, data) macro(224, data) +#define MREPEAT226(macro, data) MREPEAT225(macro, data) macro(225, data) +#define MREPEAT227(macro, data) MREPEAT226(macro, data) macro(226, data) +#define MREPEAT228(macro, data) MREPEAT227(macro, data) macro(227, data) +#define MREPEAT229(macro, data) MREPEAT228(macro, data) macro(228, data) +#define MREPEAT230(macro, data) MREPEAT229(macro, data) macro(229, data) +#define MREPEAT231(macro, data) MREPEAT230(macro, data) macro(230, data) +#define MREPEAT232(macro, data) MREPEAT231(macro, data) macro(231, data) +#define MREPEAT233(macro, data) MREPEAT232(macro, data) macro(232, data) +#define MREPEAT234(macro, data) MREPEAT233(macro, data) macro(233, data) +#define MREPEAT235(macro, data) MREPEAT234(macro, data) macro(234, data) +#define MREPEAT236(macro, data) MREPEAT235(macro, data) macro(235, data) +#define MREPEAT237(macro, data) MREPEAT236(macro, data) macro(236, data) +#define MREPEAT238(macro, data) MREPEAT237(macro, data) macro(237, data) +#define MREPEAT239(macro, data) MREPEAT238(macro, data) macro(238, data) +#define MREPEAT240(macro, data) MREPEAT239(macro, data) macro(239, data) +#define MREPEAT241(macro, data) MREPEAT240(macro, data) macro(240, data) +#define MREPEAT242(macro, data) MREPEAT241(macro, data) macro(241, data) +#define MREPEAT243(macro, data) MREPEAT242(macro, data) macro(242, data) +#define MREPEAT244(macro, data) MREPEAT243(macro, data) macro(243, data) +#define MREPEAT245(macro, data) MREPEAT244(macro, data) macro(244, data) +#define MREPEAT246(macro, data) MREPEAT245(macro, data) macro(245, data) +#define MREPEAT247(macro, data) MREPEAT246(macro, data) macro(246, data) +#define MREPEAT248(macro, data) MREPEAT247(macro, data) macro(247, data) +#define MREPEAT249(macro, data) MREPEAT248(macro, data) macro(248, data) +#define MREPEAT250(macro, data) MREPEAT249(macro, data) macro(249, data) +#define MREPEAT251(macro, data) MREPEAT250(macro, data) macro(250, data) +#define MREPEAT252(macro, data) MREPEAT251(macro, data) macro(251, data) +#define MREPEAT253(macro, data) MREPEAT252(macro, data) macro(252, data) +#define MREPEAT254(macro, data) MREPEAT253(macro, data) macro(253, data) +#define MREPEAT255(macro, data) MREPEAT254(macro, data) macro(254, data) +#define MREPEAT256(macro, data) MREPEAT255(macro, data) macro(255, data) + +/** @} */ + +#endif /* _MREPEAT_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h new file mode 100644 index 0000000..7f67d8a --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h @@ -0,0 +1,38 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef _PREPROCESSOR_H_ +#define _PREPROCESSOR_H_ + +#include "tpaste.h" +#include "stringz.h" +#include "mrepeat.h" +#include "mrecursion.h" + +#endif // _PREPROCESSOR_H_ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/stringz.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/stringz.h new file mode 100644 index 0000000..70937c4 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/stringz.h @@ -0,0 +1,67 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef _STRINGZ_H_ +#define _STRINGZ_H_ + +/** + * \defgroup group_sam0_utils_stringz Preprocessor - Stringize + * + * \ingroup group_sam0_utils + * + * @{ + */ + +/** \brief Stringize. + * + * Stringize a preprocessing token, this token being allowed to be \#defined. + * + * May be used only within macros with the token passed as an argument if the + * token is \#defined. + * + * For example, writing STRINGZ(PIN) within a macro \#defined by PIN_NAME(PIN) + * and invoked as PIN_NAME(PIN0) with PIN0 \#defined as A0 is equivalent to + * writing "A0". + */ +#define STRINGZ(x) #x + +/** \brief Absolute stringize. + * + * Stringize a preprocessing token, this token being allowed to be \#defined. + * + * No restriction of use if the token is \#defined. + * + * For example, writing ASTRINGZ(PIN0) anywhere with PIN0 \#defined as A0 is + * equivalent to writing "A0". + */ +#define ASTRINGZ(x) STRINGZ(x) + +/** @} */ + +#endif // _STRINGZ_H_ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/tpaste.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/tpaste.h new file mode 100644 index 0000000..9108183 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/tpaste.h @@ -0,0 +1,85 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ +#ifndef _TPASTE_H_ +#define _TPASTE_H_ + +/** + * \defgroup group_sam0_utils_tpaste Preprocessor - Token Paste + * + * \ingroup group_sam0_utils + * + * @{ + */ + +/** \name Token Paste + * + * Paste N preprocessing tokens together, these tokens being allowed to be \#defined. + * + * May be used only within macros with the tokens passed as arguments if the tokens are \#defined. + * + * For example, writing TPASTE2(U, WIDTH) within a macro \#defined by + * UTYPE(WIDTH) and invoked as UTYPE(UL_WIDTH) with UL_WIDTH \#defined as 32 is + * equivalent to writing U32. + * + * @{ */ +#define TPASTE2( a, b) a##b +#define TPASTE3( a, b, c) a##b##c +#define TPASTE4( a, b, c, d) a##b##c##d +#define TPASTE5( a, b, c, d, e) a##b##c##d##e +#define TPASTE6( a, b, c, d, e, f) a##b##c##d##e##f +#define TPASTE7( a, b, c, d, e, f, g) a##b##c##d##e##f##g +#define TPASTE8( a, b, c, d, e, f, g, h) a##b##c##d##e##f##g##h +#define TPASTE9( a, b, c, d, e, f, g, h, i) a##b##c##d##e##f##g##h##i +#define TPASTE10(a, b, c, d, e, f, g, h, i, j) a##b##c##d##e##f##g##h##i##j +/** @} */ + +/** \name Absolute Token Paste + * + * Paste N preprocessing tokens together, these tokens being allowed to be \#defined. + * + * No restriction of use if the tokens are \#defined. + * + * For example, writing ATPASTE2(U, UL_WIDTH) anywhere with UL_WIDTH \#defined + * as 32 is equivalent to writing U32. + * + * @{ */ +#define ATPASTE2( a, b) TPASTE2( a, b) +#define ATPASTE3( a, b, c) TPASTE3( a, b, c) +#define ATPASTE4( a, b, c, d) TPASTE4( a, b, c, d) +#define ATPASTE5( a, b, c, d, e) TPASTE5( a, b, c, d, e) +#define ATPASTE6( a, b, c, d, e, f) TPASTE6( a, b, c, d, e, f) +#define ATPASTE7( a, b, c, d, e, f, g) TPASTE7( a, b, c, d, e, f, g) +#define ATPASTE8( a, b, c, d, e, f, g, h) TPASTE8( a, b, c, d, e, f, g, h) +#define ATPASTE9( a, b, c, d, e, f, g, h, i) TPASTE9( a, b, c, d, e, f, g, h, i) +#define ATPASTE10(a, b, c, d, e, f, g, h, i, j) TPASTE10(a, b, c, d, e, f, g, h, i, j) +/** @} */ + +/** @} */ + +#endif // _TPASTE_H_ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/reset.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/reset.h new file mode 100644 index 0000000..ae1eb5a --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/reset.h @@ -0,0 +1,119 @@ +/** + * \file + * + * \brief SAM Reset related functionality + * + * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef RESET_H_INCLUDED +#define RESET_H_INCLUDED + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \addtogroup asfdoc_sam0_system_group + * @{ + */ + +/** + * \brief Reset causes of the system. + * + * List of possible reset causes of the system. + */ +enum system_reset_cause { + /** The system was last reset by a software reset. */ + SYSTEM_RESET_CAUSE_SOFTWARE = PM_RCAUSE_SYST, + /** The system was last reset by the watchdog timer. */ + SYSTEM_RESET_CAUSE_WDT = PM_RCAUSE_WDT, + /** The system was last reset because the external reset line was pulled low. */ + SYSTEM_RESET_CAUSE_EXTERNAL_RESET = PM_RCAUSE_EXT, + /** The system was last reset by the BOD33. */ + SYSTEM_RESET_CAUSE_BOD33 = PM_RCAUSE_BOD33, + /** The system was last reset by the BOD12. */ + SYSTEM_RESET_CAUSE_BOD12 = PM_RCAUSE_BOD12, + /** The system was last reset by the POR (Power on reset). */ + SYSTEM_RESET_CAUSE_POR = PM_RCAUSE_POR, +}; + + +/** + * \name Reset Control + * @{ + */ + +/** + * \brief Reset the MCU. + * + * Resets the MCU and all associated peripherals and registers, except RTC, all 32KHz sources, + * WDT (if ALWAYSON is set) and GCLK (if WRTLOCK is set). + * + */ +static inline void system_reset(void) +{ + NVIC_SystemReset(); +} + +/** + * \brief Return the reset cause. + * + * Retrieves the cause of the last system reset. + * + * \return An enum value indicating the cause of the last system reset. + */ +static inline enum system_reset_cause system_get_reset_cause(void) +{ + return (enum system_reset_cause)PM->RCAUSE.reg; +} + +/** + * @} + */ + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* RESET_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/status_codes.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/status_codes.h new file mode 100644 index 0000000..29bbf41 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/status_codes.h @@ -0,0 +1,138 @@ +/* ---------------------------------------------------------------------------- + * SAM Software Package License + * ---------------------------------------------------------------------------- + * Copyright (c) 2011-2012, Atmel Corporation + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following condition is met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the disclaimer below. + * + * Atmel's name may not be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * ---------------------------------------------------------------------------- + */ + +#ifndef STATUS_CODES_H_INCLUDED +#define STATUS_CODES_H_INCLUDED + +#include + +/** + * \defgroup group_sam0_utils_status_codes Status Codes + * + * \ingroup group_sam0_utils + * + * @{ + */ + +/** Mask to retrieve the error category of a status code. */ +#define STATUS_CATEGORY_MASK 0xF0 + +/** Mask to retrieve the error code within the category of a status code. */ +#define STATUS_ERROR_MASK 0x0F + +/** Status code error categories. */ +enum status_categories { + STATUS_CATEGORY_OK = 0x00, + STATUS_CATEGORY_COMMON = 0x10, + STATUS_CATEGORY_ANALOG = 0x30, + STATUS_CATEGORY_COM = 0x40, + STATUS_CATEGORY_IO = 0x50, +}; + +/** + * Status code that may be returned by shell commands and protocol + * implementations. + * + * \note Any change to these status codes and the corresponding + * message strings is strictly forbidden. New codes can be added, + * however, but make sure that any message string tables are updated + * at the same time. + */ +enum status_code { + STATUS_OK = STATUS_CATEGORY_OK | 0x00, + STATUS_VALID_DATA = STATUS_CATEGORY_OK | 0x01, + STATUS_NO_CHANGE = STATUS_CATEGORY_OK | 0x02, + STATUS_ABORTED = STATUS_CATEGORY_OK | 0x04, + STATUS_BUSY = STATUS_CATEGORY_OK | 0x05, + STATUS_SUSPEND = STATUS_CATEGORY_OK | 0x06, + + STATUS_ERR_IO = STATUS_CATEGORY_COMMON | 0x00, + STATUS_ERR_REQ_FLUSHED = STATUS_CATEGORY_COMMON | 0x01, + STATUS_ERR_TIMEOUT = STATUS_CATEGORY_COMMON | 0x02, + STATUS_ERR_BAD_DATA = STATUS_CATEGORY_COMMON | 0x03, + STATUS_ERR_NOT_FOUND = STATUS_CATEGORY_COMMON | 0x04, + STATUS_ERR_UNSUPPORTED_DEV = STATUS_CATEGORY_COMMON | 0x05, + STATUS_ERR_NO_MEMORY = STATUS_CATEGORY_COMMON | 0x06, + STATUS_ERR_INVALID_ARG = STATUS_CATEGORY_COMMON | 0x07, + STATUS_ERR_BAD_ADDRESS = STATUS_CATEGORY_COMMON | 0x08, + STATUS_ERR_BAD_FORMAT = STATUS_CATEGORY_COMMON | 0x0A, + STATUS_ERR_BAD_FRQ = STATUS_CATEGORY_COMMON | 0x0B, + STATUS_ERR_DENIED = STATUS_CATEGORY_COMMON | 0x0c, + STATUS_ERR_ALREADY_INITIALIZED = STATUS_CATEGORY_COMMON | 0x0d, + STATUS_ERR_OVERFLOW = STATUS_CATEGORY_COMMON | 0x0e, + STATUS_ERR_NOT_INITIALIZED = STATUS_CATEGORY_COMMON | 0x0f, + + STATUS_ERR_SAMPLERATE_UNAVAILABLE = STATUS_CATEGORY_ANALOG | 0x00, + STATUS_ERR_RESOLUTION_UNAVAILABLE = STATUS_CATEGORY_ANALOG | 0x01, + + STATUS_ERR_BAUDRATE_UNAVAILABLE = STATUS_CATEGORY_COM | 0x00, + STATUS_ERR_PACKET_COLLISION = STATUS_CATEGORY_COM | 0x01, + STATUS_ERR_PROTOCOL = STATUS_CATEGORY_COM | 0x02, + + STATUS_ERR_PIN_MUX_INVALID = STATUS_CATEGORY_IO | 0x00, +}; +typedef enum status_code status_code_genare_t; + +/** + Status codes used by MAC stack. + */ +enum status_code_wireless { + //STATUS_OK = 0, //!< Success + ERR_IO_ERROR = -1, //!< I/O error + ERR_FLUSHED = -2, //!< Request flushed from queue + ERR_TIMEOUT = -3, //!< Operation timed out + ERR_BAD_DATA = -4, //!< Data integrity check failed + ERR_PROTOCOL = -5, //!< Protocol error + ERR_UNSUPPORTED_DEV = -6, //!< Unsupported device + ERR_NO_MEMORY = -7, //!< Insufficient memory + ERR_INVALID_ARG = -8, //!< Invalid argument + ERR_BAD_ADDRESS = -9, //!< Bad address + ERR_BUSY = -10, //!< Resource is busy + ERR_BAD_FORMAT = -11, //!< Data format not recognized + ERR_NO_TIMER = -12, //!< No timer available + ERR_TIMER_ALREADY_RUNNING = -13, //!< Timer already running + ERR_TIMER_NOT_RUNNING = -14, //!< Timer not running + + /** + * \brief Operation in progress + * + * This status code is for driver-internal use when an operation + * is currently being performed. + * + * \note Drivers should never return this status code to any + * callers. It is strictly for internal use. + */ + OPERATION_IN_PROGRESS = -128, +}; + +typedef enum status_code_wireless status_code_t; + +/** @} */ + +#endif /* STATUS_CODES_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system.c new file mode 100644 index 0000000..0121588 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system.c @@ -0,0 +1,111 @@ +/** + * \file + * + * \brief SAM System related functionality + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#include + +/** + * \internal + * Dummy initialization function, used as a weak alias target for the various + * init functions called by \ref system_init(). + */ +void _system_dummy_init(void); +void _system_dummy_init(void) +{ + return; +} + +#if !defined(__DOXYGEN__) +# if defined(__GNUC__) +void system_clock_init(void) WEAK __attribute__((alias("_system_dummy_init"))); +void system_board_init(void) WEAK __attribute__((alias("_system_dummy_init"))); +void _system_events_init(void) WEAK __attribute__((alias("_system_dummy_init"))); +void _system_extint_init(void) WEAK __attribute__((alias("_system_dummy_init"))); +void _system_divas_init(void) WEAK __attribute__((alias("_system_dummy_init"))); +# elif defined(__ICCARM__) +void system_clock_init(void); +void system_board_init(void); +void _system_events_init(void); +void _system_extint_init(void); +void _system_divas_init(void); +# pragma weak system_clock_init=_system_dummy_init +# pragma weak system_board_init=_system_dummy_init +# pragma weak _system_events_init=_system_dummy_init +# pragma weak _system_extint_init=_system_dummy_init +# pragma weak _system_divas_init=_system_dummy_init +# endif +#endif + +/** + * \brief Initialize system + * + * This function will call the various initialization functions within the + * system namespace. If a given optional system module is not available, the + * associated call will effectively be a NOP (No Operation). + * + * Currently the following initialization functions are supported: + * - System clock initialization (via the SYSTEM CLOCK sub-module) + * - Board hardware initialization (via the Board module) + * - Event system driver initialization (via the EVSYS module) + * - External Interrupt driver initialization (via the EXTINT module) + */ +void system_init(void) +{ + /* Configure GCLK and clock sources according to conf_clocks.h */ + system_clock_init(); + + /* Initialize board hardware */ + system_board_init(); + + /* Initialize EVSYS hardware */ + _system_events_init(); + + /* Initialize External hardware */ + _system_extint_init(); + + /* Initialize DIVAS hardware */ + _system_divas_init(); +} + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system.h new file mode 100644 index 0000000..7b7bc00 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system.h @@ -0,0 +1,726 @@ +/** + * \file + * + * \brief SAM System related functionality + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef SYSTEM_H_INCLUDED +#define SYSTEM_H_INCLUDED + +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup asfdoc_sam0_system_group SAM System (SYSTEM) Driver + * + * This driver for Atmel® | SMART ARM®-based microcontrollers provides an interface for the configuration + * and management of the device's system relation functionality, necessary for + * the basic device operation. This is not limited to a single peripheral, but + * extends across multiple hardware peripherals. + * + * The following peripherals are used by this module: + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * - PM (Power Manager) + * - RSTC(Reset Controller) + * - SUPC(Supply Controller) + * \endif + * \if DEVICE_SAMC21_SYSTEM_SUPPORT + * - PM (Power Manager) + * - RSTC(Reset Controller) + * - SUPC(Supply Controller) + * \endif + * \if DEVICE_SAMD21_SYSTEM_SUPPORT + * - SYSCTRL (System Control) + * - PM (Power Manager) + * \endif + * + * The following devices can use this module: + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * - Atmel | SMART SAM L21 + * \endif + * \if DEVICE_SAMC21_SYSTEM_SUPPORT + * - Atmel | SMART SAM C20/C21 + * \endif + * \if DEVICE_SAMD21_SYSTEM_SUPPORT + * - Atmel | SMART SAM D20/D21 + * - Atmel | SMART SAM R21 + * - Atmel | SMART SAM D09/D10/D11 + * - Atmel | SMART SAM DAx + * \endif + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_system_prerequisites + * - \ref asfdoc_sam0_system_module_overview + * - \ref asfdoc_sam0_system_special_considerations + * - \ref asfdoc_sam0_system_extra_info + * - \ref asfdoc_sam0_system_examples + * - \ref asfdoc_sam0_system_api_overview + * + * + * \section asfdoc_sam0_system_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * + * \section asfdoc_sam0_system_module_overview Module Overview + * + * The System driver provides a collection of interfaces between the user + * application logic, and the core device functionality (such as clocks, reset + * cause determination, etc.) that is required for all applications. It contains + * a number of sub-modules that control one specific aspect of the device: + * + * - System Core (this module) + * - \ref asfdoc_sam0_system_clock_group "System Clock Control" (sub-module) + * - \ref asfdoc_sam0_system_interrupt_group "System Interrupt Control" (sub-module) + * - \ref asfdoc_sam0_system_pinmux_group "System Pin Multiplexer Control" (sub-module) + * + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * \subsection asfdoc_sam0_system_module_overview_vreg_l21 Voltage Regulator + * The SAM device controls the voltage regulators for the core (VDDCORE) and + * backup (VDDBU) domains. It sets the voltage regulators according to the sleep + * modes, the performance level, or the user configuration. + * + * In active mode, the voltage regulator can be chosen on the fly between a LDO + * or a Buck converter. In standby mode, the low power voltage regulator is used + * to supply VDDCORE. + * + * \subsection asfdoc_sam0_system_module_overview_bbps Battery Backup Power Switch + * The SAM device supports connection of a battery backup to the VBAT power pin. + * It includes functionality that enables automatic power switching between main + * power and battery backup power. This will ensure power to the backup domain, + * when the main battery or power source is unavailable. + * \endif + * + * \if DEVICE_SAMC21_SYSTEM_SUPPORT + * \subsection asfdoc_sam0_system_module_overview_vreg_c21 Voltage Regulator + * The SAM device controls the voltage regulators for the core (VDDCORE). It sets + * the voltage regulators according to the sleep modes. + * + * There are a selectable reference voltage and voltage dependent on the temperature + * which can be used by analog modules like the ADC. + * \endif + * + * \subsection asfdoc_sam0_system_module_overview_vref Voltage References + * The various analog modules within the SAM devices (such as AC, ADC, and + * DAC) require a voltage reference to be configured to act as a reference point + * for comparisons and conversions. + * + * The SAM devices contain multiple references, including an internal + * temperature sensor and a fixed band-gap voltage source. When enabled, the + * associated voltage reference can be selected within the desired peripheral + * where applicable. + * + * \subsection asfdoc_sam0_system_module_overview_reset_cause System Reset Cause + * In some applications there may be a need to execute a different program + * flow based on how the device was reset. For example, if the cause of reset + * was the Watchdog timer (WDT), this might indicate an error in the application, + * and a form of error handling or error logging might be needed. + * + * For this reason, an API is provided to retrieve the cause of the last system + * reset, so that appropriate action can be taken. + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * There are three groups of reset sources: + * - Power supply reset: Resets caused by an electrical issue. It covers POR and BOD reset. + * - User reset: Resets caused by the application. It covers external reset, + * system reset, and watchdog reset. + * - Backup reset: Resets caused by a backup mode exit condition. + * + * \subsection asfdoc_sam0_system_module_overview_performance_level Performance Level + * Performance level allows the user to adjust the regulator output voltage to reduce + * power consumption. The user can on the fly select the most suitable performance + * level, depending on the application demands. + * + * The SAM device can operate at two different performance levels (PL0 and PL2). + * When operating at PL0, the voltage applied on the full logic area is reduced + * by voltage scaling. This voltage scaling technique allows to reduce the active + * power consumption while decreasing the maximum frequency of the device. When + * operating at PL2, the voltage regulator supplies the highest voltage, allowing + * the device to run at higher clock speeds. + * + * Performance level transition is possible only when the device is in active + * mode. After a reset, the device starts at the lowest performance level + * (lowest power consumption and lowest max. frequency). The application can then + * switch to another performance level at any time without any stop in the code + * execution. As shown in \ref asfdoc_sam0_system_performance_level_transition_figure. + * + * \note When scaling down the performance level, the bus frequency should first be + * scaled down in order to not exceed the maximum frequency allowed for the + * low performance level. + * When scaling up the performance level (e.g. from PL0 to PL2), check the performance + * level status before increasing the bus frequency. It can be increased only + * when the performance level transition is completed. + * + * \anchor asfdoc_sam0_system_performance_level_transition_figure + * \image html performance_level_transition.svg "Performance Level Transition" + * + * \subsection asfdoc_sam0_system_module_overview_power_domain Power Domain Gating + * Power domain gating allows power saving by reducing the voltage in logic + * areas in the device to a low-power supply. The feature is available in + * Standby sleep mode and will reduce the voltage in domains where all peripherals + * are idle. Internal logic will maintain its content, meaning the corresponding + * peripherals will not need to be reconfigured when normal operating voltage + * is returned. Most power domains can be in the following three states: + * + * - Active state: The power domain is powered on. + * - Retention state: The main voltage supply for the power domain is switched off, + * while maintaining a secondary low-power supply for the sequential cells. The + * logic context is restored when waking up. + * - Off state: The power domain is entirely powered off. The logic context is lost. + * + * The SAM L21 device contains three power domains which can be controlled using + * power domain gating, namely PD0, PD1, and PD2. These power domains can be + * configured to the following cases: + * - Default with no sleepwalking peripherals: A power domain is automatically set + * to retention state in standby sleep mode if no activity require it. The application + * can force all power domains to remain in active state during standby sleep mode + * in order to accelerate wakeup time. + * - Default with sleepwalking peripherals: If one or more peripherals are enabled + * to perform sleepwalking tasks in standby sleep mode, the corresponding power + * domain (PDn) remains in active state as well as all inferior power domains (PDn) in order + * to perform a sleepwalking task. The superior power domain is then automatically + * set to active state. At the end of the sleepwalking task, the device can either + * be woken up or the superior power domain can return to retention state. + * + * Power domains can be linked to each other, it allows a power domain (PDn) to be kept + * in active state if the inferior power domain (PDn-1) is in active state too. + * + * \ref asfdoc_sam0_system_power_domain_overview_table illustrates the + * four cases to consider in standby mode. + * + * \anchor asfdoc_sam0_system_power_domain_overview_table + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Sleep Mode versus Power Domain State Overview
Sleep modePD0PD1PD2PDTOPPDBACKUP
Idleactiveactiveactiveactiveactive
Standby - Case 1activeactiveactiveactiveactive
Standby - Case 2activeactiveretentionactiveactive
Standby - Case 3activeretentionretentionactiveactive
Standby - Case 4retentionretentionretentionactiveactive
Backupoffoffoffoffactive
Offoffoffoffoffoff
+ * + * \subsection asfdoc_sam0_system_module_overview_ram_state RAMs Low Power Mode + * By default, in standby sleep mode, RAM is in low power mode (back biased) + * if its power domain is in retention state. + * \ref asfdoc_sam0_system_power_ram_state_table lists RAMs low power mode. + * + * \anchor asfdoc_sam0_system_power_ram_state_table + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
RAM Back-biasing Mode
RAM modeDescription
Retention Back-biasing modeRAM is back-biased if its power domain is in retention mode
Standby Back-biasing modeRAM is back-biased if the device is in standby mode
Standby OFF modeRAM is OFF if the device is in standby mode
Always OFF modeRAM is OFF if the device is in RET mode
+ * + * \endif + * + * \subsection asfdoc_sam0_system_module_overview_sleep_mode Sleep Modes + * The SAM devices have several sleep modes. The sleep mode controls + * which clock systems on the device will remain enabled or disabled when the + * device enters a low power sleep mode. + * \ref asfdoc_sam0_system_module_sleep_mode_table "The table below" lists the + * clock settings of the different sleep modes. + * + * \anchor asfdoc_sam0_system_module_sleep_mode_table + * + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * \else + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * \endif + *
SAM Device Sleep Modes
Sleep modeSystem clockCPU clockAHB/AHB clockGCLK clocksOscillators (ONDEMAND = 0)Oscillators (ONDEMAND = 1)Regulator modeRAM mode
IdleRunStopRun if requestedRunRunRun if requestedNormalNormal
StandbyStopStopRun if requestedRun if requestedRun if requested or RUNSTDBY = 1Run if requestedLow pwerLow pwer
BackupStopStopStopStopStopStopBackupOff
OffOffOffOffOffOffOffOffOff
Sleep modeCPU clockAHB clockAPB clocksClock sourcesSystem clock32KHzReg modeRAM mode
Idle 0StopRunRunRunRunRunNormalNormal
Idle 1StopStopRunRunRunRunNormalNormal
Idle 2StopStopStopRunRunRunNormalNormal
StandbyStopStopStopStopStopStopLow PowerSource/Drain biasing
+ * + * Before entering device sleep, one of the available sleep modes must be set. + * The device will automatically wake up in response to an interrupt being + * generated or upon any other sleep mode exit condition. + * + * Some peripheral clocks will remain enabled during sleep, depending on their + * configuration. If desired, the modules can remain clocked during sleep to allow + * them continue to operate while other parts of the system are powered down + * to save power. + * + * + * \section asfdoc_sam0_system_special_considerations Special Considerations + * + * Most of the functions in this driver have device specific restrictions and + * caveats; refer to your device datasheet. + * + * + * \section asfdoc_sam0_system_extra_info Extra Information + * + * For extra information, see \ref asfdoc_sam0_system_extra. This includes: + * - \ref asfdoc_sam0_system_extra_acronyms + * - \ref asfdoc_sam0_system_extra_dependencies + * - \ref asfdoc_sam0_system_extra_errata + * - \ref asfdoc_sam0_system_extra_history + * + * + * \section asfdoc_sam0_system_examples Examples + * + * For SYSTEM module related examples, refer to the sub-modules listed in + * the \ref asfdoc_sam0_system_module_overview "system module overview". + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_drivers_power_exqsg. + * + * + * \section asfdoc_sam0_system_api_overview API Overview + * @{ + */ + +/** + * \name System Debugger + * @{ + */ + +/** + * \brief Check if debugger is present. + * + * Check if debugger is connected to the onboard debug system (DAP). + * + * \return A bool identifying if a debugger is present. + * + * \retval true Debugger is connected to the system + * \retval false Debugger is not connected to the system + * + */ +static inline bool system_is_debugger_present(void) +{ + return DSU->STATUSB.reg & DSU_STATUSB_DBGPRES; +} + +/** + * @} + */ + +/** + * \name System Identification + * @{ + */ + +/** + * \brief Retrieve the device identification signature. + * + * Retrieves the signature of the current device. + * + * \return Device ID signature as a 32-bit integer. + */ +static inline uint32_t system_get_device_id(void) +{ + return DSU->DID.reg; +} + +/** + * @} + */ + +/** + * \name System Initialization + * @{ + */ + +void system_init(void); + +/** + * @} + */ + + +/** + * @} + */ + +/** + +* \page asfdoc_sam0_drivers_power_exqsg Examples for Power Driver + * + * This is a list of the available Quick Start Guides (QSGs) and example + * applications. QSGs are simple examples with step-by-step instructions to + * configure and use this driver in a selection of + * use cases. Note that a QSG can be compiled as a standalone application or be + * added to the user application. + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * - \subpage asfdoc_sam0_power_basic_use_case + * \endif + * + * \page asfdoc_sam0_system_extra Extra Information for SYSTEM Driver + * + * \section asfdoc_sam0_system_extra_acronyms Acronyms + * Below is a table listing the acronyms used in this module, along with their + * intended meanings. + * + * + * + * + * + * + * + * + * + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * + * + * + * + * + * + * + * + * \endif + * \if DEVICE_SAMC21_SYSTEM_SUPPORT + * + * + * + * + * + * + * + * + * \endif + * \if DEVICE_SAMD21_SYSTEM_SUPPORT + * + * + * + * + * \endif + *
AcronymDefinition
PMPower Manager
SUPCSupply Controller
RSTCReset Controller
SUPCSupply Controller
RSTCReset Controller
SYSCTRLSystem control interface
+ * + * + * \section asfdoc_sam0_system_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - None + * + * + * \section asfdoc_sam0_system_extra_errata Errata + * There are no errata related to this driver. + * + * + * \section asfdoc_sam0_system_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * + * + * + * \endif + * \if DEVICE_SAMC21_SYSTEM_SUPPORT + * + * + * + * \endif + * \if DEVICE_SAMD21_SYSTEM_SUPPORT + * + * + * + * + * + * + * + * + * + * \endif + *
Changelog
Initial Release
Initial Release
Added new \c system_reset() to reset the complete MCU with some exceptions
Added new \c system_get_device_id() function to retrieved the device + * ID.
Initial Release
+ * + * \page asfdoc_sam0_system_document_revision_history Document Revision History + * + * + * + * + * \if DEVICE_SAML21_SYSTEM_SUPPORT + * + * + * + * + * + * \endif + * \if DEVICE_SAMC21_SYSTEM_SUPPORT + * + * + * + * + * + * \endif + * \if DEVICE_SAMD21_SYSTEM_SUPPORT + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * \endif + *
Doc. Rev. + * Date + * Comments + *
42449A07/2015Initial document release
42484A08/2015Initial document release.
42120E04/2015Added support for SAMDAx
42120D12/2014Added support for SAMR21 and SAMD10/D11
42120C01/2014Added support for SAMD21
42120B06/2013Corrected documentation typos
42120A06/2013Initial document release
+ */ + +#ifdef __cplusplus +} +#endif + +#endif /* SYSTEM_H_INCLUDED */ + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system_interrupt.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system_interrupt.h new file mode 100644 index 0000000..93a542d --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system_interrupt.h @@ -0,0 +1,429 @@ +/** + * \file + * + * \brief SAM System Interrupt Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef SYSTEM_INTERRUPT_H_INCLUDED +#define SYSTEM_INTERRUPT_H_INCLUDED + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup asfdoc_sam0_system_interrupt_group SAM System Interrupt (SYSTEM INTERRUPT) Driver + * + * This driver for Atmel® | SMART ARM®-based microcontrollers provides + * an interface for the configuration and management of internal software and + * hardware interrupts/exceptions. + * + * The following peripheral is used by this module: + * - NVIC (Nested Vector Interrupt Controller) + * + * The following devices can use this module: + * - Atmel | SMART SAM D20/D21 + * - Atmel | SMART SAM R21 + * - Atmel | SMART SAM D09/D10/D11 + * - Atmel | SMART SAM L21/L22 + * - Atmel | SMART SAM DA1 + * - Atmel | SMART SAM C20/C21 + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_system_interrupt_prerequisites + * - \ref asfdoc_sam0_system_interrupt_module_overview + * - \ref asfdoc_sam0_system_interrupt_special_considerations + * - \ref asfdoc_sam0_system_interrupt_extra_info + * - \ref asfdoc_sam0_system_interrupt_examples + * - \ref asfdoc_sam0_system_interrupt_api_overview + * + * + * \section asfdoc_sam0_system_interrupt_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * + * \section asfdoc_sam0_system_interrupt_module_overview Module Overview + * + * The ARM® Cortex® M0+ core contains an interrupt and exception vector table, which + * can be used to configure the device's interrupt handlers; individual + * interrupts and exceptions can be enabled and disabled, as well as configured + * with a variable priority. + * + * This driver provides a set of wrappers around the core interrupt functions, + * to expose a simple API for the management of global and individual interrupts + * within the device. + * + * \subsection asfdoc_sam0_system_interrupt_module_overview_criticalsec Critical Sections + * In some applications it is important to ensure that no interrupts may be + * executed by the system whilst a critical portion of code is being run; for + * example, a buffer may be copied from one context to another - during which + * interrupts must be disabled to avoid corruption of the source buffer contents + * until the copy has completed. This driver provides a basic API to enter and + * exit nested critical sections, so that global interrupts can be kept disabled + * for as long as necessary to complete a critical application code section. + * + * \subsection asfdoc_sam0_system_interrupt_module_overview_softints Software Interrupts + * For some applications, it may be desirable to raise a module or core + * interrupt via software. For this reason, a set of APIs to set an interrupt or + * exception as pending are provided to the user application. + * + * \section asfdoc_sam0_system_interrupt_special_considerations Special Considerations + * + * Interrupts from peripherals in the SAM devices are on a per-module basis; + * an interrupt raised from any source within a module will cause a single, + * module-common handler to execute. It is the user application or driver's + * responsibility to de-multiplex the module-common interrupt to determine the + * exact interrupt cause. + * + * \section asfdoc_sam0_system_interrupt_extra_info Extra Information + * + * For extra information, see \ref asfdoc_sam0_system_interrupt_extra. This includes: + * - \ref asfdoc_sam0_system_interrupt_extra_acronyms + * - \ref asfdoc_sam0_system_interrupt_extra_dependencies + * - \ref asfdoc_sam0_system_interrupt_extra_errata + * - \ref asfdoc_sam0_system_interrupt_extra_history + * + * + * \section asfdoc_sam0_system_interrupt_examples Examples + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_system_interrupt_exqsg. + * + * \section asfdoc_sam0_system_interrupt_api_overview API Overview + * @{ + */ + +#include "compiler.h" +#include +#include "system_interrupt_features.h" + +/** + * \brief Table of possible system interrupt/exception vector priorities. + * + * Table of all possible interrupt and exception vector priorities within the + * device. + */ +enum system_interrupt_priority_level { + /** Priority level 0, the highest possible interrupt priority */ + SYSTEM_INTERRUPT_PRIORITY_LEVEL_0 = 0, + /** Priority level 1 */ + SYSTEM_INTERRUPT_PRIORITY_LEVEL_1 = 1, + /** Priority level 2 */ + SYSTEM_INTERRUPT_PRIORITY_LEVEL_2 = 2, + /** Priority level 3, the lowest possible interrupt priority */ + SYSTEM_INTERRUPT_PRIORITY_LEVEL_3 = 3, +}; + +/** + * \name Critical Section Management + * @{ + */ + +/** + * \brief Enters a critical section. + * + * Disables global interrupts. To support nested critical sections, an internal + * count of the critical section nesting will be kept, so that global interrupts + * are only re-enabled upon leaving the outermost nested critical section. + * + */ +static inline void system_interrupt_enter_critical_section(void) +{ + cpu_irq_enter_critical(); +} + +/** + * \brief Leaves a critical section. + * + * Enables global interrupts. To support nested critical sections, an internal + * count of the critical section nesting will be kept, so that global interrupts + * are only re-enabled upon leaving the outermost nested critical section. + * + */ +static inline void system_interrupt_leave_critical_section(void) +{ + cpu_irq_leave_critical(); +} + +/** @} */ + +/** + * \name Interrupt Enabling/Disabling + * @{ + */ + +/** + * \brief Check if global interrupts are enabled. + * + * Checks if global interrupts are currently enabled. + * + * \returns A boolean that identifies if the global interrupts are enabled or not. + * + * \retval true Global interrupts are currently enabled + * \retval false Global interrupts are currently disabled + * + */ +static inline bool system_interrupt_is_global_enabled(void) +{ + return cpu_irq_is_enabled(); +} + +/** + * \brief Enables global interrupts. + * + * Enables global interrupts in the device to fire any enabled interrupt handlers. + */ +static inline void system_interrupt_enable_global(void) +{ + cpu_irq_enable(); +} + +/** + * \brief Disables global interrupts. + * + * Disabled global interrupts in the device, preventing any enabled interrupt + * handlers from executing. + */ +static inline void system_interrupt_disable_global(void) +{ + cpu_irq_disable(); +} + +/** + * \brief Checks if an interrupt vector is enabled or not. + * + * Checks if a specific interrupt vector is currently enabled. + * + * \param[in] vector Interrupt vector number to check + * + * \returns A variable identifying if the requested interrupt vector is enabled. + * + * \retval true Specified interrupt vector is currently enabled + * \retval false Specified interrupt vector is currently disabled + * + */ +static inline bool system_interrupt_is_enabled( + const enum system_interrupt_vector vector) +{ + return (bool)((NVIC->ISER[0] >> (uint32_t)vector) & 0x00000001); +} + +/** + * \brief Enable interrupt vector. + * + * Enables execution of the software handler for the requested interrupt vector. + * + * \param[in] vector Interrupt vector to enable + */ +static inline void system_interrupt_enable( + const enum system_interrupt_vector vector) +{ + NVIC->ISER[0] = (uint32_t)(1 << ((uint32_t)vector & 0x0000001f)); +} + +/** + * \brief Disable interrupt vector. + * + * Disables execution of the software handler for the requested interrupt vector. + * + * \param[in] vector Interrupt vector to disable + */ +static inline void system_interrupt_disable( + const enum system_interrupt_vector vector) +{ + NVIC->ICER[0] = (uint32_t)(1 << ((uint32_t)vector & 0x0000001f)); +} + +/** @} */ + +/** + * \name Interrupt State Management + * @{ + */ + +/** + * \brief Get active interrupt (if any). + * + * Return the vector number for the current executing software handler, if any. + * + * \return Interrupt number that is currently executing. + */ +static inline enum system_interrupt_vector system_interrupt_get_active(void) +{ + uint32_t IPSR = __get_IPSR(); + /* The IPSR returns the Exception number, which with an offset 16 to IRQ number. */ + return (enum system_interrupt_vector)((IPSR & _SYSTEM_INTERRUPT_IPSR_MASK) - 16); +} + +bool system_interrupt_is_pending( + const enum system_interrupt_vector vector); + +enum status_code system_interrupt_set_pending( + const enum system_interrupt_vector vector); + +enum status_code system_interrupt_clear_pending( + const enum system_interrupt_vector vector); + +/** @} */ + +/** + * \name Interrupt Priority Management + * @{ + */ + +enum status_code system_interrupt_set_priority( + const enum system_interrupt_vector vector, + const enum system_interrupt_priority_level priority_level); + +enum system_interrupt_priority_level system_interrupt_get_priority( + const enum system_interrupt_vector vector); + +/** @} */ + +/** @} */ + +/** + * \page asfdoc_sam0_system_interrupt_extra Extra Information for SYSTEM INTERRUPT Driver + * + * \section asfdoc_sam0_system_interrupt_extra_acronyms Acronyms + * The table below presents the acronyms used in this module: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
AcronymDescription
ISRInterrupt Service Routine
NMINon-maskable Interrupt
SERCOMSerial Communication Interface
+ * + * + * \section asfdoc_sam0_system_interrupt_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - None + * + * + * \section asfdoc_sam0_system_interrupt_extra_errata Errata + * There are no errata related to this driver. + * + * + * \section asfdoc_sam0_system_interrupt_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * + * + * + *
Changelog
Initial Release
+ */ + +/** + * \page asfdoc_sam0_system_interrupt_exqsg Examples for SYSTEM INTERRUPT Driver + * + * This is a list of the available Quick Start guides (QSGs) and example + * applications for \ref asfdoc_sam0_system_interrupt_group. QSGs are simple examples with + * step-by-step instructions to configure and use this driver in a selection of + * use cases. Note that a QSG can be compiled as a standalone application or be + * added to the user application. + * + * - \subpage asfdoc_sam0_system_interrupt_critsec_use_case + * - \subpage asfdoc_sam0_system_interrupt_enablemodint_use_case + * + * \page asfdoc_sam0_system_interrupt_document_revision_history Document Revision History + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Doc. Rev. + * Date + * Comments + *
42122E08/2015Added support for SAM L21/L22, SAM DA1, and SAM C20/C21
42122D12/2014Added support for SAM R21 and SAM D10/D11
42122C01/2014Added support for SAM D21
42122B06/2013Corrected documentation typos
42122A06/2013Initial release
+ */ + +#ifdef __cplusplus +} +#endif + +#endif // #ifndef SYSTEM_INTERRUPT_H_INCLUDED diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system_interrupt_features.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system_interrupt_features.h new file mode 100644 index 0000000..25dfa83 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system_interrupt_features.h @@ -0,0 +1,195 @@ +/** + * \file + * + * \brief SAM D21 System Interrupt Driver + * + * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#ifndef SYSTEM_INTERRUPT_FEATURES_H_INCLUDED +#define SYSTEM_INTERRUPT_FEATURES_H_INCLUDED + +#if !defined(__DOXYGEN__) + +/* Generates a interrupt vector table enum list entry for a given module type + and index (e.g. "SYSTEM_INTERRUPT_MODULE_TC0 = TC0_IRQn,"). */ +# define _MODULE_IRQn(n, module) \ + SYSTEM_INTERRUPT_MODULE_##module##n = module##n##_IRQn, + +/* Generates interrupt vector table enum list entries for all instances of a + given module type on the selected device. */ +# define _SYSTEM_INTERRUPT_MODULES(name) \ + MREPEAT(name##_INST_NUM, _MODULE_IRQn, name) + +# define _SYSTEM_INTERRUPT_IPSR_MASK 0x0000003f +# define _SYSTEM_INTERRUPT_PRIORITY_MASK 0x00000003 + +# define _SYSTEM_INTERRUPT_EXTERNAL_VECTOR_START 0 + +# define _SYSTEM_INTERRUPT_SYSTICK_PRI_POS 30 +#endif + +/** + * \addtogroup asfdoc_sam0_system_interrupt_group + * @{ + */ + +/** + * \brief Table of possible system interrupt/exception vector numbers. + * + * Table of all possible interrupt and exception vector indexes within the + * SAM D21 device. Check peripherals configuration in SAM D21 datasheet for + * available vector index for specific device. + * + */ +#if defined(__DOXYGEN__) +/** \note The actual enumeration name is "system_interrupt_vector". */ +enum system_interrupt_vector_samd21 { +#else +enum system_interrupt_vector { +#endif + /** Interrupt vector index for a NMI interrupt */ + SYSTEM_INTERRUPT_NON_MASKABLE = NonMaskableInt_IRQn, + /** Interrupt vector index for a Hard Fault memory access exception */ + SYSTEM_INTERRUPT_HARD_FAULT = HardFault_IRQn, + /** Interrupt vector index for a Supervisor Call exception */ + SYSTEM_INTERRUPT_SV_CALL = SVCall_IRQn, + /** Interrupt vector index for a Pending Supervisor interrupt */ + SYSTEM_INTERRUPT_PENDING_SV = PendSV_IRQn, + /** Interrupt vector index for a System Tick interrupt */ + SYSTEM_INTERRUPT_SYSTICK = SysTick_IRQn, + + /** Interrupt vector index for a Power Manager peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_PM = PM_IRQn, + /** Interrupt vector index for a System Control peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_SYSCTRL = SYSCTRL_IRQn, + /** Interrupt vector index for a Watch Dog peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_WDT = WDT_IRQn, + /** Interrupt vector index for a Real Time Clock peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_RTC = RTC_IRQn, + /** Interrupt vector index for an External Interrupt peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_EIC = EIC_IRQn, + /** Interrupt vector index for a Non Volatile Memory Controller interrupt */ + SYSTEM_INTERRUPT_MODULE_NVMCTRL = NVMCTRL_IRQn, + /** Interrupt vector index for a Direct Memory Access interrupt */ + SYSTEM_INTERRUPT_MODULE_DMA = DMAC_IRQn, +#if defined(__DOXYGEN__) || defined(ID_USB) + /** Interrupt vector index for a Universal Serial Bus interrupt */ + SYSTEM_INTERRUPT_MODULE_USB = USB_IRQn, +#endif + /** Interrupt vector index for an Event System interrupt */ + SYSTEM_INTERRUPT_MODULE_EVSYS = EVSYS_IRQn, +#if defined(__DOXYGEN__) + /** Interrupt vector index for a SERCOM peripheral interrupt. + * + * Each specific device may contain several SERCOM peripherals; each module + * instance will have its own entry in the table, with the instance number + * substituted for "n" in the entry name (e.g. + * \c SYSTEM_INTERRUPT_MODULE_SERCOM0). + */ + SYSTEM_INTERRUPT_MODULE_SERCOMn = SERCOMn_IRQn, + + /** Interrupt vector index for a Timer/Counter Control peripheral interrupt. + * + * Each specific device may contain several TCC peripherals; each module + * instance will have its own entry in the table, with the instance number + * substituted for "n" in the entry name (e.g. + * \c SYSTEM_INTERRUPT_MODULE_TCC0). + */ + SYSTEM_INTERRUPT_MODULE_TCCn = TCCn_IRQn, + + /** Interrupt vector index for a Timer/Counter peripheral interrupt. + * + * Each specific device may contain several TC peripherals; each module + * instance will have its own entry in the table, with the instance number + * substituted for "n" in the entry name (e.g. + * \c SYSTEM_INTERRUPT_MODULE_TC3). + */ + SYSTEM_INTERRUPT_MODULE_TCn = TCn_IRQn, +#else + _SYSTEM_INTERRUPT_MODULES(SERCOM) + + _SYSTEM_INTERRUPT_MODULES(TCC) + + SYSTEM_INTERRUPT_MODULE_TC3 = TC3_IRQn, + SYSTEM_INTERRUPT_MODULE_TC4 = TC4_IRQn, + SYSTEM_INTERRUPT_MODULE_TC5 = TC5_IRQn, +# if defined(ID_TC6) + SYSTEM_INTERRUPT_MODULE_TC6 = TC6_IRQn, +# endif +# if defined(ID_TC7) + SYSTEM_INTERRUPT_MODULE_TC7 = TC7_IRQn, +# endif +#endif + +#if defined(__DOXYGEN__) || defined(ID_ADC) + /** Interrupt vector index for an Analog-to-Digital peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_ADC = ADC_IRQn, +#endif + +#if defined(__DOXYGEN__) || defined(ID_AC) + /** Interrupt vector index for an Analog Comparator peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_AC = AC_IRQn, +#endif + +#if defined(__DOXYGEN__) || defined(ID_DAC) + /** Interrupt vector index for a Digital-to-Analog peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_DAC = DAC_IRQn, +#endif +#if defined(__DOXYGEN__) || defined(ID_PTC) + /** Interrupt vector index for a Peripheral Touch Controller peripheral + * interrupt */ + SYSTEM_INTERRUPT_MODULE_PTC = PTC_IRQn, +#endif +#if defined(__DOXYGEN__) || defined(ID_I2S) + /** Interrupt vector index for a Inter-IC Sound Interface peripheral + * interrupt */ + SYSTEM_INTERRUPT_MODULE_I2S = I2S_IRQn, +#endif +#if defined(__DOXYGEN__) || defined(ID_AC1) + /** Interrupt vector index for an Analog Comparator 1 peripheral interrupt */ + SYSTEM_INTERRUPT_MODULE_AC1 = AC1_IRQn, +#endif +}; + +/** @} */ + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc.c new file mode 100644 index 0000000..23e2703 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc.c @@ -0,0 +1,685 @@ +/** + * \file + * + * \brief SAM TC - Timer Counter Driver + * + * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#include "tc.h" + +#if TC_ASYNC == true +# include "tc_interrupt.h" +# include + +/** \internal + * Converts a given TC index to its interrupt vector index. + */ +# define _TC_INTERRUPT_VECT_NUM(n, unused) \ + SYSTEM_INTERRUPT_MODULE_TC##n, +#endif + +#if !defined(__DOXYGEN__) +# define _TC_GCLK_ID(n,unused) TPASTE3(TC,n,_GCLK_ID) , +# define _TC_PM_APBCMASK(n,unused) TPASTE2(PM_APBCMASK_TC,n) , + +# define TC_INST_GCLK_ID { MRECURSION(TC_INST_NUM, _TC_GCLK_ID, TC_INST_MAX_ID) } +# define TC_INST_PM_APBCMASK { MRECURSION(TC_INST_NUM, _TC_PM_APBCMASK, TC_INST_MAX_ID) } + +#endif + +/** + * \internal Find the index of given TC module instance. + * + * \param[in] TC module instance pointer. + * + * \return Index of the given TC module instance. + */ +uint8_t _tc_get_inst_index( + Tc *const hw) +{ + /* List of available TC modules. */ + Tc *const tc_modules[TC_INST_NUM] = TC_INSTS; + + /* Find index for TC instance. */ + for (uint32_t i = 0; i < TC_INST_NUM; i++) { + if (hw == tc_modules[i]) { + return i; + } + } + + /* Invalid data given. */ + Assert(false); + return 0; +} + + +/** + * \brief Initializes a hardware TC module instance. + * + * Enables the clock and initializes the TC module, based on the given + * configuration values. + * + * \param[in,out] module_inst Pointer to the software module instance struct + * \param[in] hw Pointer to the TC hardware module + * \param[in] config Pointer to the TC configuration options struct + * + * \return Status of the initialization procedure. + * + * \retval STATUS_OK The module was initialized successfully + * \retval STATUS_BUSY Hardware module was busy when the + * initialization procedure was attempted + * \retval STATUS_INVALID_ARG An invalid configuration option or argument + * was supplied + * \retval STATUS_ERR_DENIED Hardware module was already enabled, or the + * hardware module is configured in 32-bit + * slave mode + */ +enum status_code tc_init( + struct tc_module *const module_inst, + Tc *const hw, + const struct tc_config *const config) +{ + /* Sanity check arguments */ + Assert(hw); + Assert(module_inst); + Assert(config); + + /* Temporary variable to hold all updates to the CTRLA + * register before they are written to it */ + uint16_t ctrla_tmp = 0; + /* Temporary variable to hold all updates to the CTRLBSET + * register before they are written to it */ + uint8_t ctrlbset_tmp = 0; + /* Temporary variable to hold all updates to the CTRLC + * register before they are written to it */ + uint8_t ctrlc_tmp = 0; + /* Temporary variable to hold TC instance number */ + uint8_t instance = _tc_get_inst_index(hw); + + /* Array of GLCK ID for different TC instances */ + uint8_t inst_gclk_id[] = TC_INST_GCLK_ID; + /* Array of PM APBC mask bit position for different TC instances */ + uint16_t inst_pm_apbmask[] = TC_INST_PM_APBCMASK; + + struct system_pinmux_config pin_config; + struct system_gclk_chan_config gclk_chan_config; + +#if TC_ASYNC == true + /* Initialize parameters */ + for (uint8_t i = 0; i < TC_CALLBACK_N; i++) { + module_inst->callback[i] = NULL; + } + module_inst->register_callback_mask = 0x00; + module_inst->enable_callback_mask = 0x00; + + /* Register this instance for callbacks*/ + _tc_instances[instance] = module_inst; +#endif + + /* Associate the given device instance with the hardware module */ + module_inst->hw = hw; + +#if SAMD09 || SAMD10 || SAMD11 + /* Check if even numbered TC modules are being configured in 32-bit + * counter size. Only odd numbered counters are allowed to be + * configured in 32-bit counter size. + */ + if ((config->counter_size == TC_COUNTER_SIZE_32BIT) && + !((instance + TC_INSTANCE_OFFSET) & 0x01)) { + Assert(false); + return STATUS_ERR_INVALID_ARG; + } +#else + /* Check if odd numbered TC modules are being configured in 32-bit + * counter size. Only even numbered counters are allowed to be + * configured in 32-bit counter size. + */ + if ((config->counter_size == TC_COUNTER_SIZE_32BIT) && + ((instance + TC_INSTANCE_OFFSET) & 0x01)) { + Assert(false); + return STATUS_ERR_INVALID_ARG; + } +#endif + + /* Make the counter size variable in the module_inst struct reflect + * the counter size in the module + */ + module_inst->counter_size = config->counter_size; + + if (hw->COUNT8.CTRLA.reg & TC_CTRLA_SWRST) { + /* We are in the middle of a reset. Abort. */ + return STATUS_BUSY; + } + + if (hw->COUNT8.STATUS.reg & TC_STATUS_SLAVE) { + /* Module is used as a slave */ + return STATUS_ERR_DENIED; + } + + if (hw->COUNT8.CTRLA.reg & TC_CTRLA_ENABLE) { + /* Module must be disabled before initialization. Abort. */ + return STATUS_ERR_DENIED; + } + + /* Set up the TC PWM out pin for channel 0 */ + if (config->pwm_channel[0].enabled) { + system_pinmux_get_config_defaults(&pin_config); + pin_config.mux_position = config->pwm_channel[0].pin_mux; + pin_config.direction = SYSTEM_PINMUX_PIN_DIR_OUTPUT; + system_pinmux_pin_set_config( + config->pwm_channel[0].pin_out, &pin_config); + } + + /* Set up the TC PWM out pin for channel 1 */ + if (config->pwm_channel[1].enabled) { + system_pinmux_get_config_defaults(&pin_config); + pin_config.mux_position = config->pwm_channel[1].pin_mux; + pin_config.direction = SYSTEM_PINMUX_PIN_DIR_OUTPUT; + system_pinmux_pin_set_config( + config->pwm_channel[1].pin_out, &pin_config); + } + + /* Enable the user interface clock in the PM */ + system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, + inst_pm_apbmask[instance]); + + /* Enable the slave counter if counter_size is 32-bit */ + if ((config->counter_size == TC_COUNTER_SIZE_32BIT)) + { + /* Enable the user interface clock in the PM */ + system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, + inst_pm_apbmask[instance + 1]); + } + + /* Setup clock for module */ + system_gclk_chan_get_config_defaults(&gclk_chan_config); + gclk_chan_config.source_generator = config->clock_source; + system_gclk_chan_set_config(inst_gclk_id[instance], &gclk_chan_config); + system_gclk_chan_enable(inst_gclk_id[instance]); + + /* Set ctrla register */ + ctrla_tmp = + (uint32_t)config->counter_size | + (uint32_t)config->wave_generation | + (uint32_t)config->reload_action | + (uint32_t)config->clock_prescaler; + + if (config->run_in_standby) { + ctrla_tmp |= TC_CTRLA_RUNSTDBY; + } + + /* Write configuration to register */ + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + hw->COUNT8.CTRLA.reg = ctrla_tmp; + + /* Set ctrlb register */ + if (config->oneshot) { + ctrlbset_tmp = TC_CTRLBSET_ONESHOT; + } + + if (config->count_direction) { + ctrlbset_tmp |= TC_CTRLBSET_DIR; + } + + /* Clear old ctrlb configuration */ + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + hw->COUNT8.CTRLBCLR.reg = 0xFF; + + /* Check if we actually need to go into a wait state. */ + if (ctrlbset_tmp) { + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + /* Write configuration to register */ + hw->COUNT8.CTRLBSET.reg = ctrlbset_tmp; + } + + /* Set ctrlc register*/ + ctrlc_tmp = config->waveform_invert_output; + for (uint8_t i = 0; i < NUMBER_OF_COMPARE_CAPTURE_CHANNELS; i++) { + if (config->enable_capture_on_channel[i] == true) { + ctrlc_tmp |= (TC_CTRLC_CPTEN(1) << i); + } + } + + /* Write configuration to register */ + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + hw->COUNT8.CTRLC.reg = ctrlc_tmp; + + /* Write configuration to register */ + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Switch for TC counter size */ + switch (module_inst->counter_size) { + case TC_COUNTER_SIZE_8BIT: + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT8.COUNT.reg = + config->counter_8_bit.value; + + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT8.PER.reg = + config->counter_8_bit.period; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT8.CC[0].reg = + config->counter_8_bit.compare_capture_channel[0]; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT8.CC[1].reg = + config->counter_8_bit.compare_capture_channel[1]; + + return STATUS_OK; + + case TC_COUNTER_SIZE_16BIT: + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT16.COUNT.reg + = config->counter_16_bit.value; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT16.CC[0].reg = + config->counter_16_bit.compare_capture_channel[0]; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT16.CC[1].reg = + config->counter_16_bit.compare_capture_channel[1]; + + return STATUS_OK; + + case TC_COUNTER_SIZE_32BIT: + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT32.COUNT.reg + = config->counter_32_bit.value; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT32.CC[0].reg = + config->counter_32_bit.compare_capture_channel[0]; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + hw->COUNT32.CC[1].reg = + config->counter_32_bit.compare_capture_channel[1]; + + return STATUS_OK; + } + + Assert(false); + return STATUS_ERR_INVALID_ARG; +} + +/** + * \brief Sets TC module count value. + * + * Sets the current timer count value of a initialized TC module. The + * specified TC module may be started or stopped. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] count New timer count value to set + * + * \return Status of the count update procedure. + * + * \retval STATUS_OK The timer count was updated successfully + * \retval STATUS_ERR_INVALID_ARG An invalid timer counter size was specified + */ +enum status_code tc_set_count_value( + const struct tc_module *const module_inst, + const uint32_t count) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance*/ + Tc *const tc_module = module_inst->hw; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Write to based on the TC counter_size */ + switch (module_inst->counter_size) { + case TC_COUNTER_SIZE_8BIT: + tc_module->COUNT8.COUNT.reg = (uint8_t)count; + return STATUS_OK; + + case TC_COUNTER_SIZE_16BIT: + tc_module->COUNT16.COUNT.reg = (uint16_t)count; + return STATUS_OK; + + case TC_COUNTER_SIZE_32BIT: + tc_module->COUNT32.COUNT.reg = (uint32_t)count; + return STATUS_OK; + + default: + return STATUS_ERR_INVALID_ARG; + } +} + +/** + * \brief Get TC module count value. + * + * Retrieves the current count value of a TC module. The specified TC module + * may be started or stopped. + * + * \param[in] module_inst Pointer to the software module instance struct + * + * \return Count value of the specified TC module. + */ +uint32_t tc_get_count_value( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + Tc *const tc_module = module_inst->hw; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Read from based on the TC counter size */ + switch (module_inst->counter_size) { + case TC_COUNTER_SIZE_8BIT: + return (uint32_t)tc_module->COUNT8.COUNT.reg; + + case TC_COUNTER_SIZE_16BIT: + return (uint32_t)tc_module->COUNT16.COUNT.reg; + + case TC_COUNTER_SIZE_32BIT: + return tc_module->COUNT32.COUNT.reg; + } + + Assert(false); + return 0; +} + +/** + * \brief Gets the TC module capture value. + * + * Retrieves the capture value in the indicated TC module capture channel. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] channel_index Index of the Compare Capture channel to read + * + * \return Capture value stored in the specified timer channel. + */ +uint32_t tc_get_capture_value( + const struct tc_module *const module_inst, + const enum tc_compare_capture_channel channel_index) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + Tc *const tc_module = module_inst->hw; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Read out based on the TC counter size */ + switch (module_inst->counter_size) { + case TC_COUNTER_SIZE_8BIT: + if (channel_index < + NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { + return tc_module->COUNT8.CC[channel_index].reg; + } + + case TC_COUNTER_SIZE_16BIT: + if (channel_index < + NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { + return tc_module->COUNT16.CC[channel_index].reg; + } + + case TC_COUNTER_SIZE_32BIT: + if (channel_index < + NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { + return tc_module->COUNT32.CC[channel_index].reg; + } + } + + Assert(false); + return 0; +} + +/** + * \brief Sets a TC module compare value. + * + * Writes a compare value to the given TC module compare/capture channel. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] channel_index Index of the compare channel to write to + * \param[in] compare New compare value to set + * + * \return Status of the compare update procedure. + * + * \retval STATUS_OK The compare value was updated successfully + * \retval STATUS_ERR_INVALID_ARG An invalid channel index was supplied + */ +enum status_code tc_set_compare_value( + const struct tc_module *const module_inst, + const enum tc_compare_capture_channel channel_index, + const uint32_t compare) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + Tc *const tc_module = module_inst->hw; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Read out based on the TC counter size */ + switch (module_inst->counter_size) { + case TC_COUNTER_SIZE_8BIT: + if (channel_index < + NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { + tc_module->COUNT8.CC[channel_index].reg = + (uint8_t)compare; + return STATUS_OK; + } + + case TC_COUNTER_SIZE_16BIT: + if (channel_index < + NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { + tc_module->COUNT16.CC[channel_index].reg = + (uint16_t)compare; + return STATUS_OK; + } + + case TC_COUNTER_SIZE_32BIT: + if (channel_index < + NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { + tc_module->COUNT32.CC[channel_index].reg = + (uint32_t)compare; + return STATUS_OK; + } + } + + return STATUS_ERR_INVALID_ARG; +} + +/** + * \brief Resets the TC module. + * + * Resets the TC module, restoring all hardware module registers to their + * default values and disabling the module. The TC module will not be + * accessible while the reset is being performed. + * + * \note When resetting a 32-bit counter only the master TC module's instance + * structure should be passed to the function. + * + * \param[in] module_inst Pointer to the software module instance struct + * + * \return Status of the procedure. + * \retval STATUS_OK The module was reset successfully + * \retval STATUS_ERR_UNSUPPORTED_DEV A 32-bit slave TC module was passed to + * the function. Only use reset on master + * TC + */ +enum status_code tc_reset( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + if (tc_module->STATUS.reg & TC_STATUS_SLAVE) { + return STATUS_ERR_UNSUPPORTED_DEV; + } + + /* Disable this module if it is running */ + if (tc_module->CTRLA.reg & TC_CTRLA_ENABLE) { + tc_disable(module_inst); + while (tc_is_syncing(module_inst)) { + /* wait while module is disabling */ + } + } + + /* Reset this TC module */ + tc_module->CTRLA.reg |= TC_CTRLA_SWRST; + + return STATUS_OK; +} + +/** + * \brief Set the timer TOP/period value. + * + * For 8-bit counter size this function writes the top value to the period + * register. + * + * For 16- and 32-bit counter size this function writes the top value to + * Capture Compare register 0. The value in this register can not be used for + * any other purpose. + * + * \note This function is designed to be used in PWM or frequency + * match modes only. When the counter is set to 16- or 32-bit counter + * size. In 8-bit counter size it will always be possible to change the + * top value even in normal mode. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] top_value New timer TOP value to set + * + * \return Status of the TOP set procedure. + * + * \retval STATUS_OK The timer TOP value was updated successfully + * \retval STATUS_ERR_INVALID_ARG The configured TC module counter size in the + * module instance is invalid + */ +enum status_code tc_set_top_value ( + const struct tc_module *const module_inst, + const uint32_t top_value) +{ + Assert(module_inst); + Assert(module_inst->hw); + Assert(top_value); + + Tc *const tc_module = module_inst->hw; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + switch (module_inst->counter_size) { + case TC_COUNTER_SIZE_8BIT: + tc_module->COUNT8.PER.reg = (uint8_t)top_value; + return STATUS_OK; + + case TC_COUNTER_SIZE_16BIT: + tc_module->COUNT16.CC[0].reg = (uint16_t)top_value; + return STATUS_OK; + + case TC_COUNTER_SIZE_32BIT: + tc_module->COUNT32.CC[0].reg = (uint32_t)top_value; + return STATUS_OK; + + default: + Assert(false); + return STATUS_ERR_INVALID_ARG; + } +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc.h new file mode 100644 index 0000000..0ee7006 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc.h @@ -0,0 +1,1783 @@ +/** + * \file + * + * \brief SAM TC - Timer Counter Driver + * + * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ + +#ifndef TC_H_INCLUDED +#define TC_H_INCLUDED + +/** + * \defgroup asfdoc_sam0_tc_group SAM Timer/Counter Driver (TC) + * + * This driver for Atmel® | SMART ARM®-based microcontrollers provides an interface for the configuration + * and management of the timer modules within the device, for waveform + * generation and timing operations. The following driver API modes are covered + * by this manual: + * + * - Polled APIs + * \if TC_CALLBACK_MODE + * - Callback APIs + * \endif + * + * + * The following peripherals are used by this module: + * - TC (Timer/Counter) + * + * The following devices can use this module: + * - Atmel | SMART SAM D20/D21 + * - Atmel | SMART SAM R21 + * - Atmel | SMART SAM D09/D10/D11 + * - Atmel | SMART SAM L21/L22 + * - Atmel | SMART SAM DA1 + * - Atmel | SMART SAM C20/C21 + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_tc_prerequisites + * - \ref asfdoc_sam0_tc_module_overview + * - \ref asfdoc_sam0_tc_special_considerations + * - \ref asfdoc_sam0_tc_extra_info + * - \ref asfdoc_sam0_tc_examples + * - \ref asfdoc_sam0_tc_api_overview + * + * + * \section asfdoc_sam0_tc_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * + * \section asfdoc_sam0_tc_module_overview Module Overview + * + * The Timer/Counter (TC) module provides a set of timing and counting related + * functionality, such as the generation of periodic waveforms, the capturing + * of a periodic waveform's frequency/duty cycle, and software timekeeping for + * periodic operations. TC modules can be configured to use an 8-, 16-, or + * 32-bit counter size. + * + * This TC module for the SAM is capable of the following functions: + * + * - Generation of PWM signals + * - Generation of timestamps for events + * - General time counting + * - Waveform period capture + * - Waveform frequency capture + * + * \ref asfdoc_sam0_tc_block_diagram "The diagram below" shows the overview + * of the TC module design. + * + * \anchor asfdoc_sam0_tc_block_diagram + * \image html overview.svg "Basic Overview of the TC Module" + * + * + * \subsection asfdoc_sam0_tc_features Driver Feature Macro Definition + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Driver Feature MacroSupported devices
FEATURE_TC_DOUBLE_BUFFEREDSAM L21/L22/C20/C21
FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2SAM L21/L22/C20/C21
FEATURE_TC_STAMP_PW_CAPTURESAM L21/L22/C20/C21
FEATURE_TC_READ_SYNCSAM L21/L22/C20/C21
FEATURE_TC_IO_CAPTURESAM L21/L22/C20/C21
FEATURE_TC_GENERATE_DMA_TRIGGERSAM L21/L22
+ * \note The specific features are only available in the driver when the + * selected device supports those features. + * + * \subsection asfdoc_sam0_tc_module_overview_func_desc Functional Description + * Independent of the configured counter size, each TC module can be set up + * in one of two different modes; capture and compare. + * + * In capture mode, the counter value is stored when a configurable event + * occurs. This mode can be used to generate timestamps used in event capture, + * or it can be used for the measurement of a periodic input signal's + * frequency/duty cycle. + * + * In compare mode, the counter value is compared against one or more of the + * configured channel compare values. When the counter value coincides with a + * compare value an action can be taken automatically by the module, such as + * generating an output event or toggling a pin when used for frequency or PWM + * signal generation. + * + * \note The connection of events between modules requires the use of the + * \ref asfdoc_sam0_events_group "SAM Event System Driver (EVENTS)" + * to route output event of one module to the input event of another. + * For more information on event routing, refer to the event driver + * documentation. + * + * \subsection asfdoc_sam0_tc_module_overview_tc_size Timer/Counter Size + * Each timer module can be configured in one of three different counter + * sizes; 8-, 16-, and 32-bit. The size of the counter determines the maximum + * value it can count to before an overflow occurs and the count is reset back + * to zero. \ref asfdoc_sam0_tc_count_size_vs_top "The table below" shows the + * maximum values for each of the possible counter sizes. + * + * \anchor asfdoc_sam0_tc_count_size_vs_top + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Timer Counter Sizes and Their Maximum Count Values
Counter sizeMax. (hexadecimal)Max. (decimal)
8-bit0xFF255
16-bit0xFFFF65,535
32-bit0xFFFFFFFF4,294,967,295
+ * + * When using the counter in 16- or 32-bit count mode, Compare Capture + * register 0 (CC0) is used to store the period value when running in PWM + * generation match mode. + * + * When using 32-bit counter size, two 16-bit counters are chained together + * in a cascade formation. Except in SAM D09/D10/D11, Even numbered TC modules + * (e.g. TC0, TC2) can be configured as 32-bit counters. The odd numbered + * counters will act as slaves to the even numbered masters, and will not + * be reconfigurable until the master timer is disabled. The pairing of timer + * modules for 32-bit mode is shown in \ref asfdoc_sam0_tc_module_ms_pairs + * "the table below". + * + * \anchor asfdoc_sam0_tc_module_ms_pairs + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
TC Master and Slave Module Pairings
Master TC ModuleSlave TC Module
TC0TC1
TC2TC3
......
TCn-1TCn
+ * + * In SAM D09/D10/D11, odd numbered TC modules (e.g. TC1) can be configured as 32-bit + * counters. The even numbered(e.g. TC2) counters will act as slaves to the odd + * numbered masters. + * + * \subsection asfdoc_sam0_tc_module_overview_clock Clock Settings + * + * \subsubsection asfdoc_sam0_tc_module_overview_clock_selection Clock Selection + * Each TC peripheral is clocked asynchronously to the system clock by a GCLK + * (Generic Clock) channel. The GCLK channel connects to any of the GCLK + * generators. The GCLK generators are configured to use one of the available + * clock sources on the system such as internal oscillator, external crystals, + * etc. see the \ref asfdoc_sam0_system_clock_group "Generic Clock driver" + *for + * more information. + * + * \subsubsection asfdoc_sam0_tc_module_overview_clock_prescaler Prescaler + * Each TC module in the SAM has its own individual clock prescaler, which + * can be used to divide the input clock frequency used in the counter. This + * prescaler only scales the clock used to provide clock pulses for the counter + * to count, and does not affect the digital register interface portion of + * the module, thus the timer registers will synchronize to the raw GCLK + * frequency input to the module. + * + * As a result of this, when selecting a GCLK frequency and timer prescaler + * value the user application should consider both the timer resolution + * required and the synchronization frequency, to avoid lengthy + * synchronization times of the module if a very slow GCLK frequency is fed + * into the TC module. It is preferable to use a higher module GCLK frequency + * as the input to the timer, and prescale this down as much as possible to + * obtain a suitable counter frequency in latency-sensitive applications. + * + * \subsubsection asfdoc_sam0_tc_module_overview_clock_reloading Reloading + * Timer modules also contain a configurable reload action, used when a + * re-trigger event occurs. Examples of a re-trigger event are the counter + * reaching the maximum value when counting up, or when an event from the event + * system tells the counter to re-trigger. The reload action determines if the + * prescaler should be reset, and when this should happen. The counter will + * always be reloaded with the value it is set to start counting from. The user + * can choose between three different reload actions, described in + * \ref asfdoc_sam0_tc_module_reload_act "the table below". + * + * \anchor asfdoc_sam0_tc_module_reload_act + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
TC Module Reload Actions
Reload actionDescription
\ref TC_RELOAD_ACTION_GCLK Reload TC counter value on next GCLK cycle. Leave prescaler + * as-is.
\ref TC_RELOAD_ACTION_PRESC Reloads TC counter value on next prescaler clock. Leave prescaler + * as-is.
\ref TC_RELOAD_ACTION_RESYNC Reload TC counter value on next GCLK cycle. Clear prescaler to + * zero.
+ * + * The reload action to use will depend on the specific application being + * implemented. One example is when an external trigger for a reload occurs; if + * the TC uses the prescaler, the counter in the prescaler should not have a + * value between zero and the division factor. The TC counter and the counter + * in the prescaler should both start at zero. When the counter is set to + * re-trigger when it reaches the maximum value on the other hand, this is not the + * right option to use. In such a case it would be better if the prescaler is + * left unaltered when the re-trigger happens, letting the counter reset on the + * next GCLK cycle. + * + * \subsection asfdoc_sam0_tc_module_overview_compare_match Compare Match Operations + * In compare match operation, Compare/Capture registers are used in comparison + * with the counter value. When the timer's count value matches the value of a + * compare channel, a user defined action can be taken. + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_timer Basic Timer + * + * A Basic Timer is a simple application where compare match operations is used + * to determine when a specific period has elapsed. In Basic Timer operations, + * one or more values in the module's Compare/Capture registers are used to + * specify the time (as a number of prescaled GCLK cycles) when an action should + * be taken by the microcontroller. This can be an Interrupt Service Routine + * (ISR), event generator via the event system, or a software flag that is + * polled via the user application. + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_wg Waveform Generation + * + * Waveform generation enables the TC module to generate square waves, or if + * combined with an external passive low-pass filter; analog waveforms. + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_wg_pwm Waveform Generation - PWM + * + * Pulse width modulation is a form of waveform generation and a signalling + * technique that can be useful in many situations. When PWM mode is used, + * a digital pulse train with a configurable frequency and duty cycle can be + * generated by the TC module and output to a GPIO pin of the device. + * + * Often PWM is used to communicate a control or information parameter to an + * external circuit or component. Differing impedances of the source generator + * and sink receiver circuits is less of an issue when using PWM compared to + * using an analog voltage value, as noise will not generally affect the + * signal's integrity to a meaningful extent. + * + * \ref asfdoc_sam0_tc_module_pwm_normal_diag "The figure below" illustrates + * operations and different states of the counter and its output when running + * the counter in PWM normal mode. As can be seen, the TOP value is unchanged + * and is set to MAX. The compare match value is changed at several points to + * illustrate the resulting waveform output changes. The PWM output is set to + * normal (i.e. non-inverted) output mode. + * + * \anchor asfdoc_sam0_tc_module_pwm_normal_diag + * \image html pwm_normal_ex.svg "Example of PWM in Normal Mode, and Different Counter Operations" + * + * + * In \ref asfdoc_sam0_tc_module_pwm_match_diag "the figure below", the + * counter is set to generate PWM in Match mode. The PWM output is inverted via + * the appropriate configuration option in the TC driver configuration + * structure. In this example, the counter value is changed once, but the + * compare match value is kept unchanged. As can be seen, it is possible to + * change the TOP value when running in PWM match mode. + * + * \anchor asfdoc_sam0_tc_module_pwm_match_diag + * \image html pwm_match_ex.svg "Example of PWM in Match Mode, and Different Counter Operations" + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_wg_freq Waveform Generation - Frequency + * + * Frequency Generation mode is in many ways identical to PWM + * generation. However, in Frequency Generation a toggle only occurs + * on the output when a match on a capture channels occurs. When the + * match is made, the timer value is reset, resulting in a variable + * frequency square wave with a fixed 50% duty cycle. + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_capt Capture Operations + * + * In capture operations, any event from the event system or a pin change can + * trigger a capture of the counter value. This captured counter value can be + * used as a timestamp for the event, or it can be used in frequency and pulse + * width capture. + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_capt_event_capture Capture Operations - Event + * + * Event capture is a simple use of the capture functionality, + * designed to create timestamps for specific events. When the TC + * module's input capture pin is externally toggled, the current timer + * count value is copied into a buffered register which can then be + * read out by the user application. + * + * Note that when performing any capture operation, there is a risk that the + * counter reaches its top value (MAX) when counting up, or the bottom value + * (zero) when counting down, before the capture event occurs. This can distort + * the result, making event timestamps to appear shorter than reality; the + * user application should check for timer overflow when reading a capture + * result in order to detect this situation and perform an appropriate + * adjustment. + * + * Before checking for a new capture, \ref TC_STATUS_COUNT_OVERFLOW + * should be checked. The response to an overflow error is left to the user + * application, however it may be necessary to clear both the capture overflow + * flag and the capture flag upon each capture reading. + * + * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_capt_pwc Capture Operations - Pulse Width + * + * Pulse Width Capture mode makes it possible to measure the pulse width and + * period of PWM signals. This mode uses two capture channels of the counter. + * This means that the counter module used for Pulse Width Capture can not be + * used for any other purpose. There are two modes for pulse width capture; + * Pulse Width Period (PWP) and Period Pulse Width (PPW). In PWP mode, capture + * channel 0 is used for storing the pulse width and capture channel 1 stores + * the observed period. While in PPW mode, the roles of the two capture channels + * is reversed. + * + * As in the above example it is necessary to poll on interrupt flags to see + * if a new capture has happened and check that a capture overflow error has + * not occurred. + * + * \subsection asfdoc_sam0_tc_module_overview_oneshot One-shot Mode + * + * TC modules can be configured into a one-shot mode. When configured in this + * manner, starting the timer will cause it to count until the next overflow + * or underflow condition before automatically halting, waiting to be manually + * triggered by the user application software or an event signal from the event + * system. + * + * \subsubsection asfdoc_sam0_tc_module_overview_inversion Wave Generation Output Inversion + * + * The output of the wave generation can be inverted by hardware if desired, + * resulting in the logically inverted value being output to the configured + * device GPIO pin. + * + * + * \section asfdoc_sam0_tc_special_considerations Special Considerations + * + * The number of capture compare registers in each TC module is dependent on + * the specific SAM device being used, and in some cases the counter size. + * + * The maximum amount of capture compare registers available in any SAM + * device is two when running in 32-bit mode and four in 8- and 16-bit modes. + * + * + * \section asfdoc_sam0_tc_extra_info Extra Information + * + * For extra information, see \ref asfdoc_sam0_tc_extra. This includes: + * - \ref asfdoc_sam0_tc_extra_acronyms + * - \ref asfdoc_sam0_tc_extra_dependencies + * - \ref asfdoc_sam0_tc_extra_errata + * - \ref asfdoc_sam0_tc_extra_history + * + * + * \section asfdoc_sam0_tc_examples Examples + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_tc_exqsg. + * + * \section asfdoc_sam0_tc_api_overview API Overview + * @{ + */ + +#include "compiler.h" +#include "clock.h" +#include "gclk.h" +#include "pinmux.h" + +// fix for Arduino zero +#if defined(__SAMD21G18A__) + #define SAMD21 1 + #define SAMD21G 1 + #define TC_ASYNC 1 +#endif + +// fix for Trinket/Gemma M0 +#if defined(__SAMD21E18A__) + #define SAMD21 1 + #define SAMD21E 1 + #define TC_ASYNC 1 +#endif + +/** + * Define port features set according to different device family + * @{ +*/ +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) || defined(__DOXYGEN__) +/** TC double buffered. */ +# define FEATURE_TC_DOUBLE_BUFFERED +/** SYNCBUSY scheme version 2. */ +# define FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2 +/** TC time stamp capture and pulse width capture. */ +# define FEATURE_TC_STAMP_PW_CAPTURE +/** Read synchronization of COUNT. */ +# define FEATURE_TC_READ_SYNC +/** IO pin edge capture. */ +# define FEATURE_TC_IO_CAPTURE +#endif + +#if (SAML21XXXB) || defined(__DOXYGEN__) +/** Generate DMA triggers*/ +# define FEATURE_TC_GENERATE_DMA_TRIGGER +#endif +/*@}*/ + +#if !defined(__DOXYGEN__) +#if SAMD20 || SAML21 || SAML22 || SAMC20 || SAMC21 +# define TC_INSTANCE_OFFSET 0 +#endif +#if SAMD21 || SAMR21 || SAMDA1 +# define TC_INSTANCE_OFFSET 3 +#endif +#if SAMD09 || SAMD10 || SAMD11 +# define TC_INSTANCE_OFFSET 1 +#endif + +#if SAMD20 +# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC0_CC8_NUM +#elif SAML21 || SAML22 || SAMC20 || SAMC21 +# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC0_CC_NUM +#elif SAMD09 || SAMD10 || SAMD11 +# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC1_CC8_NUM +#else +# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC3_CC8_NUM + /* Same number for 8-, 16- and 32-bit TC and all TC instances */ +#endif + +/** TC Instance MAX ID Number. */ +#if SAMD20E || SAMD21G || SAMD21E || SAMR21 +# if SAMD21GXXL +# define TC_INST_MAX_ID 7 +# else +# define TC_INST_MAX_ID 5 +# endif +#elif SAML21 || SAMC20 || SAMC21 +# define TC_INST_MAX_ID 4 +#elif SAML22 +# define TC_INST_MAX_ID 3 +#elif SAMD09 || SAMD10 || SAMD11 +# define TC_INST_MAX_ID 2 +#else +# define TC_INST_MAX_ID 7 +#endif + +#endif + +#if TC_ASYNC == true +# include "system_interrupt.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#if TC_ASYNC == true +/** Enum for the possible callback types for the TC module. */ +enum tc_callback { + /** Callback for TC overflow. */ + TC_CALLBACK_OVERFLOW, + /** Callback for capture overflow error. */ + TC_CALLBACK_ERROR, + /** Callback for capture compare channel 0. */ + TC_CALLBACK_CC_CHANNEL0, + /** Callback for capture compare channel 1. */ + TC_CALLBACK_CC_CHANNEL1, +# if !defined(__DOXYGEN__) + /** Number of available callbacks. */ + TC_CALLBACK_N, +# endif +}; +#endif + +/** + * \name Module Status Flags + * + * TC status flags, returned by \ref tc_get_status() and cleared by + * \ref tc_clear_status(). + * + * @{ + */ + +/** Timer channel 0 has matched against its compare value, or has captured a + * new value. + */ +#define TC_STATUS_CHANNEL_0_MATCH (1UL << 0) + +/** Timer channel 1 has matched against its compare value, or has captured a + * new value. + */ +#define TC_STATUS_CHANNEL_1_MATCH (1UL << 1) + +/** Timer register synchronization has completed, and the synchronized count + * value may be read. + */ +#define TC_STATUS_SYNC_READY (1UL << 2) + +/** A new value was captured before the previous value was read, resulting in + * lost data. + */ +#define TC_STATUS_CAPTURE_OVERFLOW (1UL << 3) + +/** The timer count value has overflowed from its maximum value to its minimum + * when counting upward, or from its minimum value to its maximum when + * counting downward. + */ +#define TC_STATUS_COUNT_OVERFLOW (1UL << 4) + +#ifdef FEATURE_TC_DOUBLE_BUFFERED +/** Channel 0 compare or capture buffer valid. */ +#define TC_STATUS_CHN0_BUFFER_VALID (1UL << 5) +/** Channel 1 compare or capture buffer valid. */ +#define TC_STATUS_CHN1_BUFFER_VALID (1UL << 6) +/** Period buffer valid. */ +#define TC_STATUS_PERIOD_BUFFER_VALID (1UL << 7) +#endif +/** @} */ + +/** + * \brief Index of the compare capture channels. + * + * This enum is used to specify which capture/compare channel to do + * operations on. + */ +enum tc_compare_capture_channel { + /** Index of compare capture channel 0. */ + TC_COMPARE_CAPTURE_CHANNEL_0, + /** Index of compare capture channel 1. */ + TC_COMPARE_CAPTURE_CHANNEL_1, +}; + +/** TC wave generation mode. */ +#if SAML21 || SAML22 || SAMC20 || SAMC21 +#define TC_WAVE_GENERATION_NORMAL_FREQ_MODE TC_WAVE_WAVEGEN_NFRQ +#define TC_WAVE_GENERATION_MATCH_FREQ_MODE TC_WAVE_WAVEGEN_MFRQ +#define TC_WAVE_GENERATION_NORMAL_PWM_MODE TC_WAVE_WAVEGEN_NPWM +#define TC_WAVE_GENERATION_MATCH_PWM_MODE TC_WAVE_WAVEGEN_MPWM +#else +#define TC_WAVE_GENERATION_NORMAL_FREQ_MODE TC_CTRLA_WAVEGEN_NFRQ +#define TC_WAVE_GENERATION_MATCH_FREQ_MODE TC_CTRLA_WAVEGEN_MFRQ +#define TC_WAVE_GENERATION_NORMAL_PWM_MODE TC_CTRLA_WAVEGEN_NPWM +#define TC_WAVE_GENERATION_MATCH_PWM_MODE TC_CTRLA_WAVEGEN_MPWM +#endif + +/** + * \brief TC wave generation mode enum. + * + * This enum is used to select which mode to run the wave + * generation in. + * + */ +enum tc_wave_generation { + /** Top is maximum, except in 8-bit counter size where it is the PER + * register. + */ + TC_WAVE_GENERATION_NORMAL_FREQ = TC_WAVE_GENERATION_NORMAL_FREQ_MODE, + + /** Top is CC0, except in 8-bit counter size where it is the PER + * register. + */ + TC_WAVE_GENERATION_MATCH_FREQ = TC_WAVE_GENERATION_MATCH_FREQ_MODE, + + /** Top is maximum, except in 8-bit counter size where it is the PER + * register. + */ + TC_WAVE_GENERATION_NORMAL_PWM = TC_WAVE_GENERATION_NORMAL_PWM_MODE, + + /** Top is CC0, except in 8-bit counter size where it is the PER + * register. + */ + TC_WAVE_GENERATION_MATCH_PWM = TC_WAVE_GENERATION_MATCH_PWM_MODE, +}; + +/** + * \brief Specifies if the counter is 8-, 16-, or 32-bit. + * + * This enum specifies the maximum value it is possible to count to. + */ +enum tc_counter_size { + /** The counter's maximum value is 0xFF, the period register is + * available to be used as top value. + */ + TC_COUNTER_SIZE_8BIT = TC_CTRLA_MODE_COUNT8, + + /** The counter's maximum value is 0xFFFF. There is no separate + * period register, to modify top one of the capture compare + * registers has to be used. This limits the amount of + * available channels. + */ + TC_COUNTER_SIZE_16BIT = TC_CTRLA_MODE_COUNT16, + + /** The counter's maximum value is 0xFFFFFFFF. There is no separate + * period register, to modify top one of the capture compare + * registers has to be used. This limits the amount of + * available channels. + */ + TC_COUNTER_SIZE_32BIT = TC_CTRLA_MODE_COUNT32, +}; + +/** + * \brief TC Counter reload action enum. + * + * This enum specify how the counter and prescaler should reload. + */ +enum tc_reload_action { + /** The counter is reloaded/reset on the next GCLK and starts + * counting on the prescaler clock. + */ + TC_RELOAD_ACTION_GCLK = TC_CTRLA_PRESCSYNC_GCLK, + + /** The counter is reloaded/reset on the next prescaler clock. + */ + TC_RELOAD_ACTION_PRESC = TC_CTRLA_PRESCSYNC_PRESC, + + /** The counter is reloaded/reset on the next GCLK, and the + * prescaler is restarted as well. + */ + TC_RELOAD_ACTION_RESYNC = TC_CTRLA_PRESCSYNC_RESYNC, +}; + +/** + * \brief TC clock prescaler values. + * + * This enum is used to choose the clock prescaler + * configuration. The prescaler divides the clock frequency of the TC + * module to make the counter count slower. + */ +enum tc_clock_prescaler { + /** Divide clock by 1. */ + TC_CLOCK_PRESCALER_DIV1 = TC_CTRLA_PRESCALER(0), + /** Divide clock by 2. */ + TC_CLOCK_PRESCALER_DIV2 = TC_CTRLA_PRESCALER(1), + /** Divide clock by 4. */ + TC_CLOCK_PRESCALER_DIV4 = TC_CTRLA_PRESCALER(2), + /** Divide clock by 8. */ + TC_CLOCK_PRESCALER_DIV8 = TC_CTRLA_PRESCALER(3), + /** Divide clock by 16. */ + TC_CLOCK_PRESCALER_DIV16 = TC_CTRLA_PRESCALER(4), + /** Divide clock by 64. */ + TC_CLOCK_PRESCALER_DIV64 = TC_CTRLA_PRESCALER(5), + /** Divide clock by 256. */ + TC_CLOCK_PRESCALER_DIV256 = TC_CTRLA_PRESCALER(6), + /** Divide clock by 1024. */ + TC_CLOCK_PRESCALER_DIV1024 = TC_CTRLA_PRESCALER(7), +}; + +/** + * \brief TC module count direction. + * + * Timer/Counter count direction. + */ +enum tc_count_direction { + /** Timer should count upward from zero to MAX. */ + TC_COUNT_DIRECTION_UP, + + /** Timer should count downward to zero from MAX. */ + TC_COUNT_DIRECTION_DOWN, +}; + +/** Waveform inversion mode. */ +#if SAML21 || SAML22 || SAMC20 || SAMC21 +#define TC_WAVEFORM_INVERT_CC0_MODE TC_DRVCTRL_INVEN(1) +#define TC_WAVEFORM_INVERT_CC1_MODE TC_DRVCTRL_INVEN(2) +#else +#define TC_WAVEFORM_INVERT_CC0_MODE TC_CTRLC_INVEN(1) +#define TC_WAVEFORM_INVERT_CC1_MODE TC_CTRLC_INVEN(2) +#endif + +/** + * \brief Waveform inversion mode. + * + * Output waveform inversion mode. + */ +enum tc_waveform_invert_output { + /** No inversion of the waveform output. */ + TC_WAVEFORM_INVERT_OUTPUT_NONE = 0, + /** Invert output from compare channel 0. */ + TC_WAVEFORM_INVERT_OUTPUT_CHANNEL_0 = TC_WAVEFORM_INVERT_CC0_MODE, + /** Invert output from compare channel 1. */ + TC_WAVEFORM_INVERT_OUTPUT_CHANNEL_1 = TC_WAVEFORM_INVERT_CC1_MODE, +}; + +/** + * \brief Action to perform when the TC module is triggered by an event. + * + * Event action to perform when the module is triggered by an event. + */ +enum tc_event_action { + /** No event action. */ + TC_EVENT_ACTION_OFF = TC_EVCTRL_EVACT_OFF, + /** Re-trigger on event. */ + TC_EVENT_ACTION_RETRIGGER = TC_EVCTRL_EVACT_RETRIGGER, + /** Increment counter on event. */ + TC_EVENT_ACTION_INCREMENT_COUNTER = TC_EVCTRL_EVACT_COUNT, + /** Start counter on event. */ + TC_EVENT_ACTION_START = TC_EVCTRL_EVACT_START, + + /** Store period in capture register 0, pulse width in capture + * register 1. + */ + TC_EVENT_ACTION_PPW = TC_EVCTRL_EVACT_PPW, + + /** Store pulse width in capture register 0, period in capture + * register 1. + */ + TC_EVENT_ACTION_PWP = TC_EVCTRL_EVACT_PWP, +#ifdef FEATURE_TC_STAMP_PW_CAPTURE + /** Time stamp capture. */ + TC_EVENT_ACTION_STAMP = TC_EVCTRL_EVACT_STAMP, + /** Pulse width capture. */ + TC_EVENT_ACTION_PW = TC_EVCTRL_EVACT_PW, +#endif +}; + +/** + * \brief TC event enable/disable structure. + * + * Event flags for the \ref tc_enable_events() and \ref tc_disable_events(). + */ +struct tc_events { + /** Generate an output event on a compare channel match. */ + bool generate_event_on_compare_channel + [NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; + /** Generate an output event on counter overflow. */ + bool generate_event_on_overflow; + /** Perform the configured event action when an incoming event is signalled. */ + bool on_event_perform_action; + /** Specifies if the input event source is inverted, when used in PWP or + * PPW event action modes. + */ + bool invert_event_input; + /** Specifies which event to trigger if an event is triggered. */ + enum tc_event_action event_action; +}; + +/** + * \brief Configuration struct for TC module in 8-bit size counter mode. + */ +struct tc_8bit_config { + /** Initial timer count value. */ + uint8_t value; + /** Where to count to or from depending on the direction on the counter. */ + uint8_t period; + /** Value to be used for compare match on each channel. */ + uint8_t compare_capture_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; +}; + +/** + * \brief Configuration struct for TC module in 16-bit size counter mode. + */ +struct tc_16bit_config { + /** Initial timer count value. */ + uint16_t value; + /** Value to be used for compare match on each channel. */ + uint16_t compare_capture_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; +}; + +/** + * \brief Configuration struct for TC module in 32-bit size counter mode. + */ +struct tc_32bit_config { + /** Initial timer count value. */ + uint32_t value; + /** Value to be used for compare match on each channel. */ + uint32_t compare_capture_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; +}; + +/** + * \brief Configuration struct for TC module in 32-bit size counter mode. + */ +struct tc_pwm_channel { + /** When \c true, PWM output for the given channel is enabled. */ + bool enabled; + /** Specifies pin output for each channel. */ + uint32_t pin_out; + /** Specifies MUX setting for each output channel pin. */ + uint32_t pin_mux; +}; + +/** + * \brief TC configuration structure. + * + * Configuration struct for a TC instance. This structure should be + * initialized by the \ref tc_get_config_defaults function before being + * modified by the user application. + */ +struct tc_config { + /** GCLK generator used to clock the peripheral. */ + enum gclk_generator clock_source; + + /** When \c true the module is enabled during standby. */ + bool run_in_standby; +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) + /** Run on demand. */ + bool on_demand; +#endif + /** Specifies either 8-, 16-, or 32-bit counter size. */ + enum tc_counter_size counter_size; + /** Specifies the prescaler value for GCLK_TC. */ + enum tc_clock_prescaler clock_prescaler; + /** Specifies which waveform generation mode to use. */ + enum tc_wave_generation wave_generation; + + /** Specifies the reload or reset time of the counter and prescaler + * resynchronization on a re-trigger event for the TC. + */ + enum tc_reload_action reload_action; + + /** Specifies which channel(s) to invert the waveform on. + For SAM L21/L22/C20/C21, it's also used to invert IO input pin. */ + uint8_t waveform_invert_output; + + /** Specifies which channel(s) to enable channel capture + * operation on. + */ + bool enable_capture_on_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; +#ifdef FEATURE_TC_IO_CAPTURE + /** Specifies which channel(s) to enable I/O capture + * operation on. + */ + bool enable_capture_on_IO[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; +#endif + + /** When \c true, one-shot will stop the TC on next hardware or software + * re-trigger event or overflow/underflow. + */ + bool oneshot; + + /** Specifies the direction for the TC to count. */ + enum tc_count_direction count_direction; + + /** Specifies the PWM channel for TC. */ + struct tc_pwm_channel pwm_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; + + /** Access the different counter size settings though this configuration member. */ + union { + /** Struct for 8-bit specific timer configuration. */ + struct tc_8bit_config counter_8_bit; + /** Struct for 16-bit specific timer configuration. */ + struct tc_16bit_config counter_16_bit; + /** Struct for 32-bit specific timer configuration. */ + struct tc_32bit_config counter_32_bit; + }; + +#ifdef FEATURE_TC_DOUBLE_BUFFERED + /** Set to \c true to enable double buffering write. When enabled any write + * through \ref tc_set_top_value(), \ref tc_set_compare_value() and + * will direct to the buffer register as buffered + * value, and the buffered value will be committed to effective register + * on UPDATE condition, if update is not locked. + */ + bool double_buffering_enabled; +#endif +}; + +#if TC_ASYNC == true +/* Forward Declaration for the device instance. */ +struct tc_module; + +/* Type of the callback functions. */ +typedef void (*tc_callback_t)(struct tc_module *const module); +#endif + +/** + * \brief TC software device instance structure. + * + * TC software instance structure, used to retain software state information + * of an associated hardware module instance. + * + * \note The fields of this structure should not be altered by the user + * application; they are reserved for module-internal use only. + */ +struct tc_module { +#if !defined(__DOXYGEN__) + /** Hardware module pointer of the associated Timer/Counter peripheral. */ + Tc *hw; + + /** Size of the initialized Timer/Counter module configuration. */ + enum tc_counter_size counter_size; +# if TC_ASYNC == true + /** Array of callbacks. */ + tc_callback_t callback[TC_CALLBACK_N]; + /** Bit mask for callbacks registered. */ + uint8_t register_callback_mask; + /** Bit mask for callbacks enabled. */ + uint8_t enable_callback_mask; +# endif +#ifdef FEATURE_TC_DOUBLE_BUFFERED + /** Set to \c true to enable double buffering write. */ + bool double_buffering_enabled; +#endif +#endif +}; + +#if !defined(__DOXYGEN__) +uint8_t _tc_get_inst_index( + Tc *const hw); +#endif + +/** + * \name Driver Initialization and Configuration + * @{ + */ + +/** + * \brief Determines if the hardware module(s) are currently synchronizing to + *the bus. + * + * Checks to see if the underlying hardware peripheral module(s) are currently + * synchronizing across multiple clock domains to the hardware bus. This + * function can be used to delay further operations on a module until such time + * that it is ready, to prevent blocking delays for synchronization in the + * user application. + * + * \param[in] module_inst Pointer to the software module instance struct + * + * \return Synchronization status of the underlying hardware module(s). + * + * \retval false If the module has completed synchronization + * \retval true If the module synchronization is ongoing + */ +static inline bool tc_is_syncing( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) + return (tc_module->SYNCBUSY.reg); +#else + return (tc_module->STATUS.reg & TC_STATUS_SYNCBUSY); +#endif +} + +/** + * \brief Initializes config with predefined default values. + * + * This function will initialize a given TC configuration structure to + * a set of known default values. This function should be called on + * any new instance of the configuration structures before being + * modified by the user application. + * + * The default configuration is as follows: + * \li GCLK generator 0 (GCLK main) clock source + * \li 16-bit counter size on the counter + * \li No prescaler + * \li Normal frequency wave generation + * \li GCLK reload action + * \li Don't run in standby + * \li Don't run on demand for SAM L21/L22/C20/C21 + * \li No inversion of waveform output + * \li No capture enabled + * \li No I/O capture enabled for SAM L21/L22/C20/C21 + * \li No event input enabled + * \li Count upward + * \li Don't perform one-shot operations + * \li No event action + * \li No channel 0 PWM output + * \li No channel 1 PWM output + * \li Counter starts on 0 + * \li Capture compare channel 0 set to 0 + * \li Capture compare channel 1 set to 0 + * \li No PWM pin output enabled + * \li Pin and MUX configuration not set + * \li Double buffer disabled (if have this feature) + * + * \param[out] config Pointer to a TC module configuration structure to set + */ +static inline void tc_get_config_defaults( + struct tc_config *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Write default config to config struct */ + config->clock_source = GCLK_GENERATOR_0; + config->counter_size = TC_COUNTER_SIZE_16BIT; + config->clock_prescaler = TC_CLOCK_PRESCALER_DIV1; + config->wave_generation = TC_WAVE_GENERATION_NORMAL_FREQ; + config->reload_action = TC_RELOAD_ACTION_GCLK; + config->run_in_standby = false; +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) + config->on_demand = false; +#endif + config->waveform_invert_output = TC_WAVEFORM_INVERT_OUTPUT_NONE; + config->enable_capture_on_channel[TC_COMPARE_CAPTURE_CHANNEL_0] = false; + config->enable_capture_on_channel[TC_COMPARE_CAPTURE_CHANNEL_1] = false; +#ifdef FEATURE_TC_IO_CAPTURE + config->enable_capture_on_IO[TC_COMPARE_CAPTURE_CHANNEL_0] = false; + config->enable_capture_on_IO[TC_COMPARE_CAPTURE_CHANNEL_1] = false; +#endif + + config->count_direction = TC_COUNT_DIRECTION_UP; + config->oneshot = false; + + config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_0].enabled = false; + config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_0].pin_out = 0; + config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_0].pin_mux = 0; + + config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_1].enabled = false; + config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_1].pin_out = 0; + config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_1].pin_mux = 0; + + config->counter_16_bit.value = 0x0000; + config->counter_16_bit.compare_capture_channel\ + [TC_COMPARE_CAPTURE_CHANNEL_0] = 0x0000; + config->counter_16_bit.compare_capture_channel\ + [TC_COMPARE_CAPTURE_CHANNEL_1] = 0x0000; +#ifdef FEATURE_TC_DOUBLE_BUFFERED + config->double_buffering_enabled = false; +#endif + +} + +enum status_code tc_init( + struct tc_module *const module_inst, + Tc *const hw, + const struct tc_config *const config); + +/** @} */ + +/** + * \name Event Management + * @{ + */ + +/** + * \brief Enables a TC module event input or output. + * + * Enables one or more input or output events to or from the TC module. + * See \ref tc_events for a list of events this module supports. + * + * \note Events cannot be altered while the module is enabled. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] events Struct containing flags of events to enable + */ +static inline void tc_enable_events( + struct tc_module *const module_inst, + struct tc_events *const events) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + Assert(events); + + Tc *const tc_module = module_inst->hw; + + uint32_t event_mask = 0; + + if (events->invert_event_input == true) { + event_mask |= TC_EVCTRL_TCINV; + } + + if (events->on_event_perform_action == true) { + event_mask |= TC_EVCTRL_TCEI; + } + + if (events->generate_event_on_overflow == true) { + event_mask |= TC_EVCTRL_OVFEO; + } + + for (uint8_t i = 0; i < NUMBER_OF_COMPARE_CAPTURE_CHANNELS; i++) { + if (events->generate_event_on_compare_channel[i] == true) { + event_mask |= (TC_EVCTRL_MCEO(1) << i); + } + } + + tc_module->COUNT8.EVCTRL.reg |= event_mask | events->event_action; +} + +/** + * \brief Disables a TC module event input or output. + * + * Disables one or more input or output events to or from the TC module. + * See \ref tc_events for a list of events this module supports. + * + * \note Events cannot be altered while the module is enabled. + * + * \param[in] module_inst Pointer to the software module instance struct + * \param[in] events Struct containing flags of events to disable + */ +static inline void tc_disable_events( + struct tc_module *const module_inst, + struct tc_events *const events) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + Assert(events); + + Tc *const tc_module = module_inst->hw; + + uint32_t event_mask = 0; + + if (events->invert_event_input == true) { + event_mask |= TC_EVCTRL_TCINV; + } + + if (events->on_event_perform_action == true) { + event_mask |= TC_EVCTRL_TCEI; + } + + if (events->generate_event_on_overflow == true) { + event_mask |= TC_EVCTRL_OVFEO; + } + + for (uint8_t i = 0; i < NUMBER_OF_COMPARE_CAPTURE_CHANNELS; i++) { + if (events->generate_event_on_compare_channel[i] == true) { + event_mask |= (TC_EVCTRL_MCEO(1) << i); + } + } + + tc_module->COUNT8.EVCTRL.reg &= ~event_mask; +} + +/** @} */ + +/** + * \name Enable/Disable/Reset + * @{ + */ + +enum status_code tc_reset( + const struct tc_module *const module_inst); + +/** + * \brief Enable the TC module. + * + * Enables a TC module that has been previously initialized. The counter will + * start when the counter is enabled. + * + * \note When the counter is configured to re-trigger on an event, the counter + * will not start until the start function is used. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_enable( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Enable TC module */ + tc_module->CTRLA.reg |= TC_CTRLA_ENABLE; +} + +/** + * \brief Disables the TC module. + * + * Disables a TC module and stops the counter. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_disable( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Disable TC module */ + tc_module->CTRLA.reg &= ~TC_CTRLA_ENABLE; +} + +/** @} */ + +/** + * \name Get/Set Count Value + * @{ + */ + +uint32_t tc_get_count_value( + const struct tc_module *const module_inst); + +enum status_code tc_set_count_value( + const struct tc_module *const module_inst, + const uint32_t count); + +/** @} */ + +/** + * \name Start/Stop Counter + * @{ + */ + +/** + * \brief Stops the counter. + * + * This function will stop the counter. When the counter is stopped + * the value in the count value is set to 0 if the counter was + * counting up, or maximum if the counter was counting + * down when stopped. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_stop_counter( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Write command to execute */ + tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_STOP_Val); +} + +/** + * \brief Starts the counter. + * + * Starts or restarts an initialized TC module's counter. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_start_counter( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Make certain that there are no conflicting commands in the register */ + tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Write command to execute */ + tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_RETRIGGER_Val); +} + +/** @} */ + +#ifdef FEATURE_TC_DOUBLE_BUFFERED +/** + * \name Double Buffering + * @{ + */ + +/** + * \brief Update double buffer. + * + * Update double buffer. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_update_double_buffer( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Make certain that there are no conflicting commands in the register */ + tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Write command to execute */ + tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_UPDATE_Val); +} +/** @} */ +#endif + +#ifdef FEATURE_TC_READ_SYNC +/** + * \name Count Read Synchronization + * @{ + */ + +/** + * \brief Read synchronization of COUNT. + * + * Read synchronization of COUNT. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_sync_read_count( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Make certain that there are no conflicting commands in the register */ + tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Write command to execute */ + tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_READSYNC_Val); +} +/** @} */ +#endif + +#ifdef FEATURE_TC_GENERATE_DMA_TRIGGER +/** + * \name Generate TC DMA Triggers command + * @{ + */ + +/** + * \brief TC DMA Trigger. + * + * TC DMA trigger command. + * + * \param[in] module_inst Pointer to the software module instance struct + */ +static inline void tc_dma_trigger_command( + const struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + + /* Make certain that there are no conflicting commands in the register */ + tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; + + while (tc_is_syncing(module_inst)) { + /* Wait for sync */ + } + +#if (SAMC20) || (SAMC21) || (SAML22) || (SAML21XXXB) + /* Write command to execute */ + tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_DMAOS_Val); +#endif +} +/** @} */ +#endif + +/** + * \name Get Capture Set Compare + * @{ + */ + +uint32_t tc_get_capture_value( + const struct tc_module *const module_inst, + const enum tc_compare_capture_channel channel_index); + +enum status_code tc_set_compare_value( + const struct tc_module *const module_inst, + const enum tc_compare_capture_channel channel_index, + const uint32_t compare_value); + +/** @} */ + +/** + * \name Set Top Value + * @{ + */ + +enum status_code tc_set_top_value( + const struct tc_module *const module_inst, + const uint32_t top_value); + +/** @} */ + +/** + * \name Status Management + * @{ + */ + +/** + * \brief Retrieves the current module status. + * + * Retrieves the status of the module, giving overall state information. + * + * \param[in] module_inst Pointer to the TC software instance struct + * + * \return Bitmask of \c TC_STATUS_* flags. + * + * \retval TC_STATUS_CHANNEL_0_MATCH Timer channel 0 compare/capture match + * \retval TC_STATUS_CHANNEL_1_MATCH Timer channel 1 compare/capture match + * \retval TC_STATUS_SYNC_READY Timer read synchronization has completed + * \retval TC_STATUS_CAPTURE_OVERFLOW Timer capture data has overflowed + * \retval TC_STATUS_COUNT_OVERFLOW Timer count value has overflowed + * \retval TC_STATUS_CHN0_BUFFER_VALID Timer count channel 0 compare/capture buffer valid + * \retval TC_STATUS_CHN1_BUFFER_VALID Timer count channel 1 compare/capture buffer valid + * \retval TC_STATUS_PERIOD_BUFFER_VALID Timer count period buffer valid + */ +static inline uint32_t tc_get_status( + struct tc_module *const module_inst) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + uint32_t int_flags = tc_module->INTFLAG.reg; + + uint32_t status_flags = 0; + + /* Check for TC channel 0 match */ + if (int_flags & TC_INTFLAG_MC(1)) { + status_flags |= TC_STATUS_CHANNEL_0_MATCH; + } + + /* Check for TC channel 1 match */ + if (int_flags & TC_INTFLAG_MC(2)) { + status_flags |= TC_STATUS_CHANNEL_1_MATCH; + } + +#if !defined(FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2) + /* Check for TC read synchronization ready */ + if (int_flags & TC_INTFLAG_SYNCRDY) { + status_flags |= TC_STATUS_SYNC_READY; + } +#endif + + /* Check for TC capture overflow */ + if (int_flags & TC_INTFLAG_ERR) { + status_flags |= TC_STATUS_CAPTURE_OVERFLOW; + } + + /* Check for TC count overflow */ + if (int_flags & TC_INTFLAG_OVF) { + status_flags |= TC_STATUS_COUNT_OVERFLOW; + } +#ifdef FEATURE_TC_DOUBLE_BUFFERED + uint8_t double_buffer_valid_status = tc_module->STATUS.reg; + + /* Check channel 0 compare or capture buffer valid */ + if (double_buffer_valid_status & TC_STATUS_CCBUFV0) { + status_flags |= TC_STATUS_CHN0_BUFFER_VALID; + } + /* Check channel 0 compare or capture buffer valid */ + if (double_buffer_valid_status & TC_STATUS_CCBUFV1) { + status_flags |= TC_STATUS_CHN1_BUFFER_VALID; + } + /* Check period buffer valid */ + if (double_buffer_valid_status & TC_STATUS_PERBUFV) { + status_flags |= TC_STATUS_PERIOD_BUFFER_VALID; + } +#endif + + return status_flags; +} + +/** + * \brief Clears a module status flag. + * + * Clears the given status flag of the module. + * + * \param[in] module_inst Pointer to the TC software instance struct + * \param[in] status_flags Bitmask of \c TC_STATUS_* flags to clear + */ +static inline void tc_clear_status( + struct tc_module *const module_inst, + const uint32_t status_flags) +{ + /* Sanity check arguments */ + Assert(module_inst); + Assert(module_inst->hw); + + /* Get a pointer to the module's hardware instance */ + TcCount8 *const tc_module = &(module_inst->hw->COUNT8); + + uint32_t int_flags = 0; + + /* Check for TC channel 0 match */ + if (status_flags & TC_STATUS_CHANNEL_0_MATCH) { + int_flags |= TC_INTFLAG_MC(1); + } + + /* Check for TC channel 1 match */ + if (status_flags & TC_STATUS_CHANNEL_1_MATCH) { + int_flags |= TC_INTFLAG_MC(2); + } + +#if !defined(FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2) + /* Check for TC read synchronization ready */ + if (status_flags & TC_STATUS_SYNC_READY) { + int_flags |= TC_INTFLAG_SYNCRDY; + } +#endif + + /* Check for TC capture overflow */ + if (status_flags & TC_STATUS_CAPTURE_OVERFLOW) { + int_flags |= TC_INTFLAG_ERR; + } + + /* Check for TC count overflow */ + if (status_flags & TC_STATUS_COUNT_OVERFLOW) { + int_flags |= TC_INTFLAG_OVF; + } + + /* Clear interrupt flag */ + tc_module->INTFLAG.reg = int_flags; +} + +/** @} */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +/** + * \page asfdoc_sam0_tc_extra Extra Information for TC Driver + * + * \section asfdoc_sam0_tc_extra_acronyms Acronyms + * The table below presents the acronyms used in this module: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
AcronymDescription
DMADirect Memory Access
TCTimer Counter
PWMPulse Width Modulation
PWPPulse Width Period
PPWPeriod Pulse Width
+ * + * + * \section asfdoc_sam0_tc_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - \ref asfdoc_sam0_system_pinmux_group "System Pin Multiplexer Driver" + * + * + * \section asfdoc_sam0_tc_extra_errata Errata + * There are no errata related to this driver. + * + * + * \section asfdoc_sam0_tc_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Changelog
Added support for SAMD21 and do some modifications as below: + * \li Clean up in the configuration structure, the counter size + * setting specific registers is accessed through the counter_8_bit, + * counter_16_bit and counter_32_bit structures + * \li All event related settings moved into the tc_event structure
Added automatic digital clock interface enable for the slave TC + * module when a timer is initialized in 32-bit mode
Initial Release
+ */ + +/** + * \page asfdoc_sam0_tc_exqsg Examples for TC Driver + * + * This is a list of the available Quick Start guides (QSGs) and example + * applications for \ref asfdoc_sam0_tc_group. QSGs are simple examples with + * step-by-step instructions to configure and use this driver in a selection of + * use cases. Note that QSGs can be compiled as a standalone application or be + * added to the user application. + * + * - \subpage asfdoc_sam0_tc_basic_use_case + * - \subpage asfdoc_sam0_tc_macth_freq_use_case + * \if TC_CALLBACK_MODE + * - \subpage asfdoc_sam0_tc_timer_use_case + * - \subpage asfdoc_sam0_tc_callback_use_case + * \endif + * - \subpage asfdoc_sam0_tc_dma_use_case + * + * \page asfdoc_sam0_tc_document_revision_history Document Revision History + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Doc. Rev. + * Date + * Comments + *
F08/2015Added support for SAM C21 and SAM L22
E04/2015Added support for SAM L21 and SAM DA1
D12/2014Added timer use case. + * Added support for SAM R21 and SAM D10/D11
C01/2014Added support for SAM D21
B06/2013Corrected documentation typos
A06/2013Initial release
+ */ + +#endif /* TC_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc_interrupt.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc_interrupt.c new file mode 100644 index 0000000..032be2f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc_interrupt.c @@ -0,0 +1,199 @@ +/** + * \file + * + * \brief SAM TC - Timer Counter Callback Driver + * + * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/* + * Support and FAQ: visit Atmel Support + */ + +#include "tc_interrupt.h" + +void *_tc_instances[TC_INST_NUM]; + +void _tc_interrupt_handler(uint8_t instance); + +/** + * \brief Registers a callback. + * + * Registers a callback function which is implemented by the user. + * + * \note The callback must be enabled by \ref tc_enable_callback, + * in order for the interrupt handler to call it when the conditions for the + * callback type is met. + * + * \param[in] module Pointer to TC software instance struct + * \param[in] callback_func Pointer to callback function + * \param[in] callback_type Callback type given by an enum + */ +enum status_code tc_register_callback( + struct tc_module *const module, + tc_callback_t callback_func, + const enum tc_callback callback_type) +{ + /* Sanity check arguments */ + Assert(module); + Assert(callback_func); + + /* Register callback function */ + module->callback[callback_type] = callback_func; + + /* Set the bit corresponding to the callback_type */ + if (callback_type == TC_CALLBACK_CC_CHANNEL0) { + module->register_callback_mask |= TC_INTFLAG_MC(1); + } + else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { + module->register_callback_mask |= TC_INTFLAG_MC(2); + } + else { + module->register_callback_mask |= (1 << callback_type); + } + return STATUS_OK; +} + +/** + * \brief Unregisters a callback. + * + * Unregisters a callback function implemented by the user. The callback should be + * disabled before it is unregistered. + * + * \param[in] module Pointer to TC software instance struct + * \param[in] callback_type Callback type given by an enum + */ +enum status_code tc_unregister_callback( + struct tc_module *const module, + const enum tc_callback callback_type) +{ + /* Sanity check arguments */ + Assert(module); + + /* Unregister callback function */ + module->callback[callback_type] = NULL; + + /* Clear the bit corresponding to the callback_type */ + if (callback_type == TC_CALLBACK_CC_CHANNEL0) { + module->register_callback_mask &= ~TC_INTFLAG_MC(1); + } + else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { + module->register_callback_mask &= ~TC_INTFLAG_MC(2); + } + else { + module->register_callback_mask &= ~(1 << callback_type); + } + return STATUS_OK; +} + +/** + * \internal ISR handler for TC + * + * Auto-generate a set of interrupt handlers for each TC in the device. + */ +#define _TC_INTERRUPT_HANDLER(n, m) \ + void TC##n##_Handler(void) \ + { \ + _tc_interrupt_handler(m); \ + } + +#if (SAML21E) || (SAML21G) + _TC_INTERRUPT_HANDLER(0,0) + _TC_INTERRUPT_HANDLER(1,1) + _TC_INTERRUPT_HANDLER(4,2) +#else + MRECURSION(TC_INST_NUM, _TC_INTERRUPT_HANDLER, TC_INST_MAX_ID) +#endif + + +/** + * \internal Interrupt Handler for TC module + * + * Handles interrupts as they occur, it will run the callback functions + * that are registered and enabled. + * + * \param[in] instance ID of the TC instance calling the interrupt + * handler. + */ +void _tc_interrupt_handler( + uint8_t instance) +{ + /* Temporary variable */ + uint8_t interrupt_and_callback_status_mask; + + /* Get device instance from the look-up table */ + struct tc_module *module + = (struct tc_module *)_tc_instances[instance]; + + /* Read and mask interrupt flag register */ + interrupt_and_callback_status_mask = module->hw->COUNT8.INTFLAG.reg & + module->register_callback_mask & + module->enable_callback_mask; + + /* Check if an Overflow interrupt has occurred */ + if (interrupt_and_callback_status_mask & TC_INTFLAG_OVF) { + /* Invoke registered and enabled callback function */ + (module->callback[TC_CALLBACK_OVERFLOW])(module); + /* Clear interrupt flag */ + module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_OVF; + } + + /* Check if an Error interrupt has occurred */ + if (interrupt_and_callback_status_mask & TC_INTFLAG_ERR) { + /* Invoke registered and enabled callback function */ + (module->callback[TC_CALLBACK_ERROR])(module); + /* Clear interrupt flag */ + module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_ERR; + } + + /* Check if an Match/Capture Channel 0 interrupt has occurred */ + if (interrupt_and_callback_status_mask & TC_INTFLAG_MC(1)) { + /* Invoke registered and enabled callback function */ + (module->callback[TC_CALLBACK_CC_CHANNEL0])(module); + /* Clear interrupt flag */ + module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_MC(1); + } + + /* Check if an Match/Capture Channel 1 interrupt has occurred */ + if (interrupt_and_callback_status_mask & TC_INTFLAG_MC(2)) { + /* Invoke registered and enabled callback function */ + (module->callback[TC_CALLBACK_CC_CHANNEL1])(module); + /* Clear interrupt flag */ + module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_MC(2); + } +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc_interrupt.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc_interrupt.h new file mode 100644 index 0000000..4e1fd8e --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc_interrupt.h @@ -0,0 +1,179 @@ +/** + * \file + * + * \brief SAM TC - Timer Counter Callback Driver + * + * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/* + * Support and FAQ: visit Atmel Support + */ + +#ifndef TC_INTERRUPT_H_INCLUDED +#define TC_INTERRUPT_H_INCLUDED + +#include "tc.h" +#include "system_interrupt.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(__DOXYGEN__) +extern void *_tc_instances[TC_INST_NUM]; + +# define _TC_INTERRUPT_VECT_NUM(n, unused) \ + SYSTEM_INTERRUPT_MODULE_TC##n, +/** + * \internal Get the interrupt vector for the given device instance + * + * \param[in] TC module instance number. + * + * \return Interrupt vector for of the given TC module instance. + */ +static enum system_interrupt_vector _tc_interrupt_get_interrupt_vector( + uint32_t inst_num) +{ + static uint8_t tc_interrupt_vectors[TC_INST_NUM] = + { +#if (SAML21E) || (SAML21G) + SYSTEM_INTERRUPT_MODULE_TC0, + SYSTEM_INTERRUPT_MODULE_TC1, + SYSTEM_INTERRUPT_MODULE_TC4 +#else + MRECURSION(TC_INST_NUM, _TC_INTERRUPT_VECT_NUM, TC_INST_MAX_ID) +#endif + }; + + return (enum system_interrupt_vector)tc_interrupt_vectors[inst_num]; +} +#endif /* !defined(__DOXYGEN__) */ + +/** + * \name Callback Management + * {@ + */ + +enum status_code tc_register_callback( + struct tc_module *const module, + tc_callback_t callback_func, + const enum tc_callback callback_type); + +enum status_code tc_unregister_callback( + struct tc_module *const module, + const enum tc_callback callback_type); + +/** + * \brief Enables callback. + * + * Enables the callback function registered by the \ref + * tc_register_callback. The callback function will be called from the + * interrupt handler when the conditions for the callback type are + * met. This function will also enable the appropriate interrupts. + * + * \param[in] module Pointer to TC software instance struct + * \param[in] callback_type Callback type given by an enum + */ +static inline void tc_enable_callback( + struct tc_module *const module, + const enum tc_callback callback_type) +{ + /* Sanity check arguments */ + Assert(module); + + + /* Enable interrupts for this TC module */ + system_interrupt_enable(_tc_interrupt_get_interrupt_vector(_tc_get_inst_index(module->hw))); + + /* Enable callback */ + if (callback_type == TC_CALLBACK_CC_CHANNEL0) { + module->enable_callback_mask |= TC_INTFLAG_MC(1); + module->hw->COUNT8.INTENSET.reg = TC_INTFLAG_MC(1); + } + else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { + module->enable_callback_mask |= TC_INTFLAG_MC(2); + module->hw->COUNT8.INTENSET.reg = TC_INTFLAG_MC(2); + } + else { + module->enable_callback_mask |= (1 << callback_type); + module->hw->COUNT8.INTENSET.reg = (1 << callback_type); + } +} + +/** + * \brief Disables callback. + * + * Disables the callback function registered by the \ref + * tc_register_callback, and the callback will not be called from the + * interrupt routine. The function will also disable the appropriate + * interrupts. + * + * \param[in] module Pointer to TC software instance struct + * \param[in] callback_type Callback type given by an enum + */ +static inline void tc_disable_callback( + struct tc_module *const module, + const enum tc_callback callback_type){ + /* Sanity check arguments */ + Assert(module); + + /* Disable callback */ + if (callback_type == TC_CALLBACK_CC_CHANNEL0) { + module->hw->COUNT8.INTENCLR.reg = TC_INTFLAG_MC(1); + module->enable_callback_mask &= ~TC_INTFLAG_MC(1); + } + else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { + module->hw->COUNT8.INTENCLR.reg = TC_INTFLAG_MC(2); + module->enable_callback_mask &= ~TC_INTFLAG_MC(2); + } + else { + module->hw->COUNT8.INTENCLR.reg = (1 << callback_type); + module->enable_callback_mask &= ~(1 << callback_type); + } +} + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* TC_INTERRUPT_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/wdt.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/wdt.c new file mode 100644 index 0000000..c5b0895 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/wdt.c @@ -0,0 +1,264 @@ +/** + * \file + * + * \brief SAM Watchdog Driver + * + * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#include "wdt.h" +#include + +/** + * \brief Sets up the WDT hardware module based on the configuration. + * + * Writes a given configuration of a WDT configuration to the + * hardware module, and initializes the internal device struct. + * + * \param[in] config Pointer to the configuration struct + * + * \return Status of the configuration procedure. + * + * \retval STATUS_OK If the module was configured correctly + * \retval STATUS_ERR_INVALID_ARG If invalid argument(s) were supplied + * \retval STATUS_ERR_IO If the Watchdog module is locked to be always on + */ +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) +enum status_code wdt_set_config( + const struct wdt_conf *const config) +{ + /* Sanity check arguments */ + Assert(config); + + Wdt *const WDT_module = WDT; + + /* Turn on the digital interface clock */ + system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBA, MCLK_APBAMASK_WDT); + + /* Check of the Watchdog has been locked to be always on, if so, abort */ + if (wdt_is_locked()) { + return STATUS_ERR_IO; + } + + /* Check for an invalid timeout period, abort if found */ + if (config->timeout_period == WDT_PERIOD_NONE) { + return STATUS_ERR_INVALID_ARG; + } + + /* Make sure the Window and Early Warning periods are not more than the + * reset period, abort if either is invalid */ + if ((config->timeout_period < config->window_period) || + (config->timeout_period < config->early_warning_period)) { + return STATUS_ERR_INVALID_ARG; + } + + /* Disable the Watchdog module */ + WDT_module->CTRLA.reg &= ~WDT_CTRLA_ENABLE; + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + if(config->enable == false) { + return STATUS_OK; + } + + uint32_t new_config = 0; + + /* Update the timeout period value with the requested period */ + new_config |= (config->timeout_period - 1) << WDT_CONFIG_PER_Pos; + + /* Check if the user has requested a reset window period */ + if (config->window_period != WDT_PERIOD_NONE) { + WDT_module->CTRLA.reg |= WDT_CTRLA_WEN; + + /* Update and enable the timeout period value */ + new_config |= (config->window_period - 1) << WDT_CONFIG_WINDOW_Pos; + } else { + /* Ensure the window enable control flag is cleared */ + WDT_module->CTRLA.reg &= ~WDT_CTRLA_WEN; + } + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + /* Write the new Watchdog configuration */ + WDT_module->CONFIG.reg = new_config; + + /* Check if the user has requested an early warning period */ + if (config->early_warning_period != WDT_PERIOD_NONE) { + /* Set the Early Warning period */ + WDT_module->EWCTRL.reg + = (config->early_warning_period - 1) << WDT_EWCTRL_EWOFFSET_Pos; + } + + /* Either enable or lock-enable the Watchdog timer depending on the user + * settings */ + if (config->always_on) { + WDT_module->CTRLA.reg |= WDT_CTRLA_ALWAYSON; + } else { + WDT_module->CTRLA.reg |= WDT_CTRLA_ENABLE; + } + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + return STATUS_OK; +} +#else +enum status_code wdt_set_config( + const struct wdt_conf *const config) +{ + /* Sanity check arguments */ + Assert(config); + + Wdt *const WDT_module = WDT; + + /* Turn on the digital interface clock */ + system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBA, PM_APBAMASK_WDT); + + /* Check of the Watchdog has been locked to be always on, if so, abort */ + if (wdt_is_locked()) { + return STATUS_ERR_IO; + } + + /* Check for an invalid timeout period, abort if found */ + if (config->timeout_period == WDT_PERIOD_NONE) { + return STATUS_ERR_INVALID_ARG; + } + + /* Make sure the Window and Early Warning periods are not more than the + * reset period, abort if either is invalid */ + if ((config->timeout_period < config->window_period) || + (config->timeout_period < config->early_warning_period)) { + return STATUS_ERR_INVALID_ARG; + } + + /* Disable the Watchdog module */ + WDT_module->CTRL.reg &= ~WDT_CTRL_ENABLE; + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + if(config->enable == false) { + return STATUS_OK; + } + + /* Configure GCLK channel and enable clock */ + struct system_gclk_chan_config gclk_chan_conf; + gclk_chan_conf.source_generator = config->clock_source; + system_gclk_chan_set_config(WDT_GCLK_ID, &gclk_chan_conf); + system_gclk_chan_enable(WDT_GCLK_ID); + if (config->always_on) { + system_gclk_chan_lock(WDT_GCLK_ID); + } + + uint32_t new_config = 0; + + /* Update the timeout period value with the requested period */ + new_config |= (config->timeout_period - 1) << WDT_CONFIG_PER_Pos; + + /* Check if the user has requested a reset window period */ + if (config->window_period != WDT_PERIOD_NONE) { + WDT_module->CTRL.reg |= WDT_CTRL_WEN; + + /* Update and enable the timeout period value */ + new_config |= (config->window_period - 1) << WDT_CONFIG_WINDOW_Pos; + } else { + /* Ensure the window enable control flag is cleared */ + WDT_module->CTRL.reg &= ~WDT_CTRL_WEN; + } + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + /* Write the new Watchdog configuration */ + WDT_module->CONFIG.reg = new_config; + + /* Check if the user has requested an early warning period */ + if (config->early_warning_period != WDT_PERIOD_NONE) { + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + /* Set the Early Warning period */ + WDT_module->EWCTRL.reg + = (config->early_warning_period - 1) << WDT_EWCTRL_EWOFFSET_Pos; + } + + /* Either enable or lock-enable the Watchdog timer depending on the user + * settings */ + if (config->always_on) { + WDT_module->CTRL.reg |= WDT_CTRL_ALWAYSON; + } else { + WDT_module->CTRL.reg |= WDT_CTRL_ENABLE; + } + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } + + return STATUS_OK; +} +#endif + +/** + * \brief Resets the count of the running Watchdog Timer that was previously enabled. + * + * Resets the current count of the Watchdog Timer, restarting the timeout + * period count elapsed. This function should be called after the window + * period (if one was set in the module configuration) but before the timeout + * period to prevent a reset of the system. + */ +void wdt_reset_count(void) +{ + Wdt *const WDT_module = WDT; + + /* Disable the Watchdog module */ + WDT_module->CLEAR.reg = WDT_CLEAR_CLEAR_KEY; + + while (wdt_is_syncing()) { + /* Wait for all hardware modules to complete synchronization */ + } +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/wdt.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/wdt.h new file mode 100644 index 0000000..c4c37cf --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/wdt.h @@ -0,0 +1,501 @@ +/** + * \file + * + * \brief SAM Watchdog Driver + * + * Copyright (c) 2012-2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/* + * Support and FAQ: visit Atmel Support + */ +#ifndef WDT_H_INCLUDED +#define WDT_H_INCLUDED + +/** + * \defgroup asfdoc_sam0_wdt_group SAM Watchdog Driver (WDT) + * + * This driver for Atmel® | SMART SAM devices provides an interface for the configuration + * and management of the device's Watchdog Timer module, including the enabling, + * disabling, and kicking within the device. The following driver API modes are + * covered by this manual: + * + * - Polled APIs + * \if WDT_CALLBACK_MODE + * - Callback APIs + * \endif + * + * The following peripherals are used by this module: + * - WDT (Watchdog Timer) + * + * The following devices can use this module: + * - Atmel | SMART SAM D20/D21 + * - Atmel | SMART SAM R21 + * - Atmel | SMART SAM D09/D10/D11 + * - Atmel | SMART SAM L21/L22 + * - Atmel | SMART SAM DA1 + * - Atmel | SMART SAM C20/C21 + * + * The outline of this documentation is as follows: + * - \ref asfdoc_sam0_wdt_prerequisites + * - \ref asfdoc_sam0_wdt_module_overview + * - \ref asfdoc_sam0_wdt_special_considerations + * - \ref asfdoc_sam0_wdt_extra_info + * - \ref asfdoc_sam0_wdt_examples + * - \ref asfdoc_sam0_wdt_api_overview + * + * + * \section asfdoc_sam0_wdt_prerequisites Prerequisites + * + * There are no prerequisites for this module. + * + * + * \section asfdoc_sam0_wdt_module_overview Module Overview + * + * The Watchdog module (WDT) is designed to give an added level of safety in + * critical systems, to ensure a system reset is triggered in the case of a + * deadlock or other software malfunction that prevents normal device operation. + * + * At a basic level, the Watchdog is a system timer with a fixed period; once + * enabled, it will continue to count ticks of its asynchronous clock until + * it is periodically reset, or the timeout period is reached. In the event of a + * Watchdog timeout, the module will trigger a system reset identical to a pulse + * of the device's reset pin, resetting all peripherals to their power-on + * default states and restarting the application software from the reset vector. + * + * In many systems, there is an obvious upper bound to the amount of time each + * iteration of the main application loop can be expected to run, before a + * malfunction can be assumed (either due to a deadlock waiting on hardware or + * software, or due to other means). When the Watchdog is configured with a + * timeout period equal to this upper bound, a malfunction in the system will + * force a full system reset to allow for a graceful recovery. + * + * \subsection asfdoc_sam0_wdt_module_locked_mode Locked Mode + * The Watchdog configuration can be set in the device fuses and locked in + * hardware, so that no software changes can be made to the Watchdog + * configuration. Additionally, the Watchdog can be locked on in software if it + * is not already locked, so that the module configuration cannot be modified + * until a power on reset of the device. + * + * The locked configuration can be used to ensure that faulty software does not + * cause the Watchdog configuration to be changed, preserving the level of + * safety given by the module. + * + * \subsection asfdoc_sam0_wdt_module_window_mode Window Mode + * Just as there is a reasonable upper bound to the time the main program loop + * should take for each iteration, there is also in many applications a lower + * bound, i.e. a \a minimum time for which each loop iteration should run for + * under normal circumstances. To guard against a system failure resetting the + * Watchdog in a tight loop (or a failure in the system application causing the + * main loop to run faster than expected) a "Window" mode can be enabled to + * disallow resetting of the Watchdog counter before a certain period of time. + * If the Watchdog is not reset \a after the window opens but not \a before the + * Watchdog expires, the system will reset. + * + * \subsection asfdoc_sam0_wdt_module_early_warning Early Warning + * In some cases it is desirable to receive an early warning that the Watchdog is + * about to expire, so that some system action (such as saving any system + * configuration data for failure analysis purposes) can be performed before the + * system reset occurs. The Early Warning feature of the Watchdog module allows + * such a notification to be requested; after the configured early warning time + * (but before the expiry of the Watchdog counter) the Early Warning flag will + * become set, so that the user application can take an appropriate action. + * + * \note It is important to note that the purpose of the Early Warning feature + * is \a not to allow the user application to reset the Watchdog; doing + * so will defeat the safety the module gives to the user application. + * Instead, this feature should be used purely to perform any tasks that + * need to be undertaken before the system reset occurs. + * + * \subsection asfdoc_sam0_wdt_module_overview_physical Physical Connection + * + * \ref asfdoc_sam0_wdt_module_int_connections "The figure below" shows how + * this module is interconnected within the device. + * + * \anchor asfdoc_sam0_wdt_module_int_connections + * \dot + * digraph overview { + * rankdir=LR; + * node [label="GCLK*\nGeneric Clock" shape=square] wdt_clock; + * + * subgraph driver { + * node [label=" WDT | Watchdog Counter" shape=record] wdt_module; + * node [label="System Reset Logic" shape=ellipse style=filled fillcolor=lightgray] sys_reset; + * } + * + * wdt_clock -> wdt_module:f1; + * wdt_module:f1 -> sys_reset; + * } + * \enddot + * + * \note Watchdog Counter of SAM L21/L22 is \a not provided by GCLK, but it uses an + * internal 1KHz OSCULP32K output clock. + * + * \section asfdoc_sam0_wdt_special_considerations Special Considerations + * + * On some devices the Watchdog configuration can be fused to be always on in + * a particular configuration; if this mode is enabled the Watchdog is not + * software configurable and can have its count reset and early warning state + * checked/cleared only. + * + * \section asfdoc_sam0_wdt_extra_info Extra Information + * + * For extra information, see \ref asfdoc_sam0_wdt_extra. This includes: + * - \ref asfdoc_sam0_wdt_extra_acronyms + * - \ref asfdoc_sam0_wdt_extra_dependencies + * - \ref asfdoc_sam0_wdt_extra_errata + * - \ref asfdoc_sam0_wdt_extra_history + * + * + * \section asfdoc_sam0_wdt_examples Examples + * + * For a list of examples related to this driver, see + * \ref asfdoc_sam0_wdt_exqsg. + * + * \section asfdoc_sam0_wdt_api_overview API Overview + * @{ + */ + +#include +#include +#include + +#if WDT_CALLBACK_MODE == true +# include "wdt_callback.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Watchdog Timer period configuration enum. + * + * Enum for the possible period settings of the Watchdog timer module, for + * values requiring a period as a number of Watchdog timer clock ticks. + */ +enum wdt_period { + /** No Watchdog period. This value can only be used when setting the + * Window and Early Warning periods; its use as the Watchdog Reset + * Period is invalid. */ + WDT_PERIOD_NONE = 0, + /** Watchdog period of 8 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_8CLK = 1, + /** Watchdog period of 16 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_16CLK = 2, + /** Watchdog period of 32 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_32CLK = 3, + /** Watchdog period of 64 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_64CLK = 4, + /** Watchdog period of 128 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_128CLK = 5, + /** Watchdog period of 256 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_256CLK = 6, + /** Watchdog period of 512 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_512CLK = 7, + /** Watchdog period of 1024 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_1024CLK = 8, + /** Watchdog period of 2048 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_2048CLK = 9, + /** Watchdog period of 4096 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_4096CLK = 10, + /** Watchdog period of 8192 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_8192CLK = 11, + /** Watchdog period of 16384 clocks of the Watchdog Timer Generic Clock. */ + WDT_PERIOD_16384CLK = 12, +}; + +/** + * \brief Watchdog Timer configuration structure. + * + * Configuration structure for a Watchdog Timer instance. This + * structure should be initialized by the \ref wdt_get_config_defaults() + * function before being modified by the user application. + */ +struct wdt_conf { + /** If \c true, the Watchdog will be locked to the current configuration + * settings when the Watchdog is enabled. */ + bool always_on; + /** Enable/Disable the Watchdog Timer. */ + bool enable; +#if !(SAML21) && !(SAML22) && !(SAMC20) && !(SAMC21) + /** GCLK generator used to clock the peripheral except SAM L21/L22/C21/C20.*/ + enum gclk_generator clock_source; +#endif + /** Number of Watchdog timer clock ticks until the Watchdog expires. */ + enum wdt_period timeout_period; + /** Number of Watchdog timer clock ticks until the reset window opens. */ + enum wdt_period window_period; + /** Number of Watchdog timer clock ticks until the early warning flag is + * set. */ + enum wdt_period early_warning_period; +}; + +/** \name Configuration and Initialization + * @{ + */ + +/** + * \brief Determines if the hardware module(s) are currently synchronizing to the bus. + * + * Checks to see if the underlying hardware peripheral module(s) are currently + * synchronizing across multiple clock domains to the hardware bus. This + * function can be used to delay further operations on a module until such time + * that it is ready, to prevent blocking delays for synchronization in the + * user application. + * + * \return Synchronization status of the underlying hardware module(s). + * + * \retval false If the module has completed synchronization + * \retval true If the module synchronization is ongoing + */ +static inline bool wdt_is_syncing(void) +{ + Wdt *const WDT_module = WDT; + +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) + if (WDT_module->SYNCBUSY.reg) { +#else + if (WDT_module->STATUS.reg & WDT_STATUS_SYNCBUSY) { +#endif + return true; + } + + return false; +} + +/** + * \brief Initializes a Watchdog Timer configuration structure to defaults. + * + * Initializes a given Watchdog Timer configuration structure to a set of + * known default values. This function should be called on all new + * instances of these configuration structures before being modified by the + * user application. + * + * The default configuration is as follows: + * \li Not locked, to allow for further (re-)configuration + * \li Enable WDT + * \li Watchdog timer sourced from Generic Clock Channel 4 + * \li A timeout period of 16384 clocks of the Watchdog module clock + * \li No window period, so that the Watchdog count can be reset at any time + * \li No early warning period to indicate the Watchdog will soon expire + * + * \param[out] config Configuration structure to initialize to default values + */ +static inline void wdt_get_config_defaults( + struct wdt_conf *const config) +{ + /* Sanity check arguments */ + Assert(config); + + /* Default configuration values */ + config->always_on = false; + config->enable = true; +#if !(SAML21) && !(SAML22) && !(SAMC20) && !(SAMC21) + config->clock_source = GCLK_GENERATOR_4; +#endif + config->timeout_period = WDT_PERIOD_16384CLK; + config->window_period = WDT_PERIOD_NONE; + config->early_warning_period = WDT_PERIOD_NONE; +} + +enum status_code wdt_set_config( + const struct wdt_conf *const config); + +/** \brief Determines if the Watchdog timer is currently locked in an enabled state. + * + * Determines if the Watchdog timer is currently enabled and locked, so that + * it cannot be disabled or otherwise reconfigured. + * + * \return Current Watchdog lock state. + */ +static inline bool wdt_is_locked(void) +{ + Wdt *const WDT_module = WDT; + +#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) + return (WDT_module->CTRLA.reg & WDT_CTRLA_ALWAYSON); +#else + return (WDT_module->CTRL.reg & WDT_CTRL_ALWAYSON); +#endif +} + +/** @} */ + +/** \name Timeout and Early Warning Management + * @{ + */ + +/** \brief Clears the Watchdog timer early warning period elapsed flag. + * + * Clears the Watchdog timer early warning period elapsed flag, so that a new + * early warning period can be detected. + */ +static inline void wdt_clear_early_warning(void) +{ + Wdt *const WDT_module = WDT; + + WDT_module->INTFLAG.reg = WDT_INTFLAG_EW; +} + +/** \brief Determines if the Watchdog timer early warning period has elapsed. + * + * Determines if the Watchdog timer early warning period has elapsed. + * + * \note If no early warning period was configured, the value returned by this + * function is invalid. + * + * \return Current Watchdog Early Warning state. + */ +static inline bool wdt_is_early_warning(void) +{ + Wdt *const WDT_module = WDT; + + return (WDT_module->INTFLAG.reg & WDT_INTFLAG_EW); +} + +void wdt_reset_count(void); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +/** @} */ + +/** + * \page asfdoc_sam0_wdt_extra Extra Information for WDT Driver + * + * \section asfdoc_sam0_wdt_extra_acronyms Acronyms + * The table below presents the acronyms used in this module: + * + * + * + * + * + * + * + * + * + * + *
AcronymDescription
WDTWatchdog Timer
+ * + * + * \section asfdoc_sam0_wdt_extra_dependencies Dependencies + * This driver has the following dependencies: + * + * - \ref asfdoc_sam0_system_clock_group "System Clock Driver" + * + * + * \section asfdoc_sam0_wdt_extra_errata Errata + * There are no errata related to this driver. + * + * + * \section asfdoc_sam0_wdt_extra_history Module History + * An overview of the module history is presented in the table below, with + * details on the enhancements and fixes made to the module since its first + * release. The current version of this corresponds to the newest version in + * the table. + * + * + * + * + * + * + * + * + * + * + * + *
Changelog
Driver updated to follow driver type convention: + * \li wdt_init, wdt_enable, wdt_disable functions removed + * \li wdt_set_config function added + * \li WDT module enable state moved inside the configuration struct
Initial Release
+ */ + +/** + * \page asfdoc_sam0_wdt_exqsg Examples for WDT Driver + * + * This is a list of the available Quick Start guides (QSGs) and example + * applications for \ref asfdoc_sam0_wdt_group. QSGs are simple examples with + * step-by-step instructions to configure and use this driver in a selection of + * use cases. Note that QSGs can be compiled as a standalone application or be + * added to the user application. + * + * - \subpage asfdoc_sam0_wdt_basic_use_case + * \if WDT_CALLBACK_MODE + * - \subpage asfdoc_sam0_wdt_callback_use_case + * \endif + * + * \page asfdoc_sam0_wdt_document_revision_history Document Revision History + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Doc. Rev. + * Date + * Comments + *
E08/2015Added support for SAM L21/L22, SAM DA1, and SAM C20/C2
D12/2014Added SAMR21 and SAMD10/D11 support
C01/2014Add SAMD21 support
B06/2013Corrected documentation typos
A06/2013Initial release
+ */ + +#endif /* WDT_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp new file mode 100644 index 0000000..fe721be --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp @@ -0,0 +1,2079 @@ +/*************************************************** + This is a library for our Adafruit FONA Cellular Module + + Designed specifically to work with the Adafruit FONA + ----> http://www.adafruit.com/products/1946 + ----> http://www.adafruit.com/products/1963 + + These displays use TTL Serial to communicate, 2 pins are required to + interface + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ****************************************************/ + // next line per http://postwarrior.com/arduino-ethershield-error-prog_char-does-not-name-a-type/ + +#include "Adafruit_FONA.h" + + + + +Adafruit_FONA::Adafruit_FONA(int8_t rst) +{ + _rstpin = rst; + + apn = F("FONAnet"); + apnusername = 0; + apnpassword = 0; + mySerial = 0; + httpsredirect = false; + useragent = F("FONA"); + ok_reply = F("OK"); +} + +uint8_t Adafruit_FONA::type(void) { + return _type; +} + +boolean Adafruit_FONA::begin(Stream &port) { + mySerial = &port; + + pinMode(_rstpin, OUTPUT); + digitalWrite(_rstpin, HIGH); + delay(10); + digitalWrite(_rstpin, LOW); + delay(100); + digitalWrite(_rstpin, HIGH); + + DEBUG_PRINTLN(F("Attempting to open comm with ATs")); + // give 7 seconds to reboot + int16_t timeout = 7000; + + while (timeout > 0) { + while (mySerial->available()) mySerial->read(); + if (sendCheckReply(F("AT"), ok_reply)) + break; + while (mySerial->available()) mySerial->read(); + if (sendCheckReply(F("AT"), F("AT"))) + break; + delay(500); + timeout-=500; + } + +#ifdef ADAFRUIT_FONA_DEBUG + if (timeout <= 0) + DEBUG_PRINTLN(F("Timeout: No response to AT... last ditch attempt.")); +#endif + + sendCheckReply(F("AT"), ok_reply); + delay(100); + sendCheckReply(F("AT"), ok_reply); + delay(100); + sendCheckReply(F("AT"), ok_reply); + delay(100); + + // turn off Echo! + sendCheckReply(F("ATE0"), ok_reply); + delay(100); + + if (! sendCheckReply(F("ATE0"), ok_reply)) { + return false; + } + + // turn on hangupitude + sendCheckReply(F("AT+CVHU=0"), ok_reply); + + delay(100); + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN("ATI"); + + mySerial->println("ATI"); + readline(500, true); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + + + if (prog_char_strstr(replybuffer, (prog_char *)F("SIM808 R14")) != 0) { + _type = FONA808_V2; + } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIM808 R13")) != 0) { + _type = FONA808_V1; + } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIM800 R14")) != 0) { + _type = FONA800L; + } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIMCOM_SIM5320A")) != 0) { + _type = FONA3G_A; + } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIMCOM_SIM5320E")) != 0) { + _type = FONA3G_E; + } + + if (_type == FONA800L) { + // determine if L or H + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN("AT+GMM"); + + mySerial->println("AT+GMM"); + readline(500, true); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + + if (prog_char_strstr(replybuffer, (prog_char *)F("SIM800H")) != 0) { + _type = FONA800H; + } + } + +#if defined(FONA_PREF_SMS_STORAGE) + sendCheckReply(F("AT+CPMS=\"" FONA_PREF_SMS_STORAGE "\""), ok_reply); +#endif + + return true; +} + + +/********* Serial port ********************************************/ +boolean Adafruit_FONA::setBaudrate(uint16_t baud) { + return sendCheckReply(F("AT+IPREX="), baud, ok_reply); +} + +/********* Real Time Clock ********************************************/ + +boolean Adafruit_FONA::readRTC(uint8_t *year, uint8_t *month, uint8_t *date, uint8_t *hr, uint8_t *min, uint8_t *sec) { + uint16_t v; + sendParseReply(F("AT+CCLK?"), F("+CCLK: "), &v, '/', 0); + *year = v; + + DEBUG_PRINTLN(*year); +} + +boolean Adafruit_FONA::enableRTC(uint8_t i) { + if (! sendCheckReply(F("AT+CLTS="), i, ok_reply)) + return false; + return sendCheckReply(F("AT&W"), ok_reply); +} + + +/********* BATTERY & ADC ********************************************/ + +/* returns value in mV (uint16_t) */ +boolean Adafruit_FONA::getBattVoltage(uint16_t *v) { + return sendParseReply(F("AT+CBC"), F("+CBC: "), v, ',', 2); +} + +/* returns value in mV (uint16_t) */ +boolean Adafruit_FONA_3G::getBattVoltage(uint16_t *v) { + float f; + boolean b = sendParseReply(F("AT+CBC"), F("+CBC: "), &f, ',', 2); + *v = f*1000; + return b; +} + + +/* returns the percentage charge of battery as reported by sim800 */ +boolean Adafruit_FONA::getBattPercent(uint16_t *p) { + return sendParseReply(F("AT+CBC"), F("+CBC: "), p, ',', 1); +} + +boolean Adafruit_FONA::getADCVoltage(uint16_t *v) { + return sendParseReply(F("AT+CADC?"), F("+CADC: 1,"), v); +} + +/********* SIM ***********************************************************/ + +uint8_t Adafruit_FONA::unlockSIM(char *pin) +{ + char sendbuff[14] = "AT+CPIN="; + sendbuff[8] = pin[0]; + sendbuff[9] = pin[1]; + sendbuff[10] = pin[2]; + sendbuff[11] = pin[3]; + sendbuff[12] = '\0'; + + return sendCheckReply(sendbuff, ok_reply); +} + +uint8_t Adafruit_FONA::getSIMCCID(char *ccid) { + getReply(F("AT+CCID")); + // up to 28 chars for reply, 20 char total ccid + if (replybuffer[0] == '+') { + // fona 3g? + strncpy(ccid, replybuffer+8, 20); + } else { + // fona 800 or 800 + strncpy(ccid, replybuffer, 20); + } + ccid[20] = 0; + + readline(); // eat 'OK' + + return strlen(ccid); +} + +/********* IMEI **********************************************************/ + +uint8_t Adafruit_FONA::getIMEI(char *imei) { + getReply(F("AT+GSN")); + + // up to 15 chars + strncpy(imei, replybuffer, 15); + imei[15] = 0; + + readline(); // eat 'OK' + + return strlen(imei); +} + +/********* NETWORK *******************************************************/ + +uint8_t Adafruit_FONA::getNetworkStatus(void) { + uint16_t status; + + if (! sendParseReply(F("AT+CREG?"), F("+CREG: "), &status, ',', 1)) return 0; + + return status; +} + + +uint8_t Adafruit_FONA::getRSSI(void) { + uint16_t reply; + + if (! sendParseReply(F("AT+CSQ"), F("+CSQ: "), &reply) ) return 0; + + return reply; +} + +/********* AUDIO *******************************************************/ + +boolean Adafruit_FONA::setAudio(uint8_t a) { + // 0 is headset, 1 is external audio + if (a > 1) return false; + + return sendCheckReply(F("AT+CHFA="), a, ok_reply); +} + +uint8_t Adafruit_FONA::getVolume(void) { + uint16_t reply; + + if (! sendParseReply(F("AT+CLVL?"), F("+CLVL: "), &reply) ) return 0; + + return reply; +} + +boolean Adafruit_FONA::setVolume(uint8_t i) { + return sendCheckReply(F("AT+CLVL="), i, ok_reply); +} + + +boolean Adafruit_FONA::playDTMF(char dtmf) { + char str[4]; + str[0] = '\"'; + str[1] = dtmf; + str[2] = '\"'; + str[3] = 0; + return sendCheckReply(F("AT+CLDTMF=3,"), str, ok_reply); +} + +boolean Adafruit_FONA::playToolkitTone(uint8_t t, uint16_t len) { + return sendCheckReply(F("AT+STTONE=1,"), t, len, ok_reply); +} + +boolean Adafruit_FONA_3G::playToolkitTone(uint8_t t, uint16_t len) { + if (! sendCheckReply(F("AT+CPTONE="), t, ok_reply)) + return false; + delay(len); + return sendCheckReply(F("AT+CPTONE=0"), ok_reply); +} + +boolean Adafruit_FONA::setMicVolume(uint8_t a, uint8_t level) { + // 0 is headset, 1 is external audio + if (a > 1) return false; + + return sendCheckReply(F("AT+CMIC="), a, level, ok_reply); +} + +/********* FM RADIO *******************************************************/ + + +boolean Adafruit_FONA::FMradio(boolean onoff, uint8_t a) { + if (! onoff) { + return sendCheckReply(F("AT+FMCLOSE"), ok_reply); + } + + // 0 is headset, 1 is external audio + if (a > 1) return false; + + return sendCheckReply(F("AT+FMOPEN="), a, ok_reply); +} + +boolean Adafruit_FONA::tuneFMradio(uint16_t station) { + // Fail if FM station is outside allowed range. + if ((station < 870) || (station > 1090)) + return false; + + return sendCheckReply(F("AT+FMFREQ="), station, ok_reply); +} + +boolean Adafruit_FONA::setFMVolume(uint8_t i) { + // Fail if volume is outside allowed range (0-6). + if (i > 6) { + return false; + } + // Send FM volume command and verify response. + return sendCheckReply(F("AT+FMVOLUME="), i, ok_reply); +} + +int8_t Adafruit_FONA::getFMVolume() { + uint16_t level; + + if (! sendParseReply(F("AT+FMVOLUME?"), F("+FMVOLUME: "), &level) ) return 0; + + return level; +} + +int8_t Adafruit_FONA::getFMSignalLevel(uint16_t station) { + // Fail if FM station is outside allowed range. + if ((station < 875) || (station > 1080)) { + return -1; + } + + // Send FM signal level query command. + // Note, need to explicitly send timeout so right overload is chosen. + getReply(F("AT+FMSIGNAL="), station, FONA_DEFAULT_TIMEOUT_MS); + // Check response starts with expected value. + char *p = prog_char_strstr(replybuffer, PSTR("+FMSIGNAL: ")); + if (p == 0) return -1; + p+=11; + // Find second colon to get start of signal quality. + p = strchr(p, ':'); + if (p == 0) return -1; + p+=1; + // Parse signal quality. + int8_t level = atoi(p); + readline(); // eat the "OK" + return level; +} + +/********* PWM/BUZZER **************************************************/ + +boolean Adafruit_FONA::setPWM(uint16_t period, uint8_t duty) { + if (period > 2000) return false; + if (duty > 100) return false; + + return sendCheckReply(F("AT+SPWM=0,"), period, duty, ok_reply); +} + +/********* CALL PHONES **************************************************/ +boolean Adafruit_FONA::callPhone(char *number) { + char sendbuff[35] = "ATD"; + strncpy(sendbuff+3, number, min(30, strlen(number))); + uint8_t x = strlen(sendbuff); + sendbuff[x] = ';'; + sendbuff[x+1] = 0; + //DEBUG_PRINTLN(sendbuff); + + return sendCheckReply(sendbuff, ok_reply); +} + + +uint8_t Adafruit_FONA::getCallStatus(void) { + uint16_t phoneStatus; + + if (! sendParseReply(F("AT+CPAS"), F("+CPAS: "), &phoneStatus)) + return FONA_CALL_FAILED; // 1, since 0 is actually a known, good reply + + return phoneStatus; // 0 ready, 2 unkown, 3 ringing, 4 call in progress +} + +boolean Adafruit_FONA::hangUp(void) { + return sendCheckReply(F("ATH0"), ok_reply); +} + +boolean Adafruit_FONA_3G::hangUp(void) { + getReply(F("ATH")); + + return (prog_char_strstr(replybuffer, (prog_char *)F("VOICE CALL: END")) != 0); +} + +boolean Adafruit_FONA::pickUp(void) { + return sendCheckReply(F("ATA"), ok_reply); +} + +boolean Adafruit_FONA_3G::pickUp(void) { + return sendCheckReply(F("ATA"), F("VOICE CALL: BEGIN")); +} + + +void Adafruit_FONA::onIncomingCall() { + + DEBUG_PRINT(F("> ")); DEBUG_PRINTLN(F("Incoming call...")); + + Adafruit_FONA::_incomingCall = true; +} + +boolean Adafruit_FONA::_incomingCall = false; + +boolean Adafruit_FONA::callerIdNotification(boolean enable, uint8_t interrupt) { + if(enable){ + attachInterrupt(interrupt, onIncomingCall, FALLING); + return sendCheckReply(F("AT+CLIP=1"), ok_reply); + } + + detachInterrupt(interrupt); + return sendCheckReply(F("AT+CLIP=0"), ok_reply); +} + +boolean Adafruit_FONA::incomingCallNumber(char* phonenum) { + //+CLIP: "",145,"",0,"",0 + if(!Adafruit_FONA::_incomingCall) + return false; + + readline(); + while(!prog_char_strcmp(replybuffer, (prog_char*)F("RING")) == 0) { + flushInput(); + readline(); + } + + readline(); //reads incoming phone number line + + parseReply(F("+CLIP: \""), phonenum, '"'); + + + DEBUG_PRINT(F("Phone Number: ")); + DEBUG_PRINTLN(replybuffer); + + + Adafruit_FONA::_incomingCall = false; + return true; +} + +/********* SMS **********************************************************/ + +uint8_t Adafruit_FONA::getSMSInterrupt(void) { + uint16_t reply; + + if (! sendParseReply(F("AT+CFGRI?"), F("+CFGRI: "), &reply) ) return 0; + + return reply; +} + +boolean Adafruit_FONA::setSMSInterrupt(uint8_t i) { + return sendCheckReply(F("AT+CFGRI="), i, ok_reply); +} + +int8_t Adafruit_FONA::getNumSMS(void) { + uint16_t numsms; + + // get into text mode + if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return -1; + + // ask how many sms are stored + if (sendParseReply(F("AT+CPMS?"), F("\"SM\","), &numsms)) + return numsms; + if (sendParseReply(F("AT+CPMS?"), F("\"SM_P\","), &numsms)) + return numsms; + return -1; +} + +// Reading SMS's is a bit involved so we don't use helpers that may cause delays or debug +// printouts! +boolean Adafruit_FONA::readSMS(uint8_t i, char *smsbuff, + uint16_t maxlen, uint16_t *readlen) { + // text mode + if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return false; + + // show all text mode parameters + if (! sendCheckReply(F("AT+CSDH=1"), ok_reply)) return false; + + // parse out the SMS len + uint16_t thesmslen = 0; + + + DEBUG_PRINT(F("AT+CMGR=")); + DEBUG_PRINTLN(i); + + + //getReply(F("AT+CMGR="), i, 1000); // do not print debug! + mySerial->print(F("AT+CMGR=")); + mySerial->println(i); + readline(1000); // timeout + + //DEBUG_PRINT(F("Reply: ")); DEBUG_PRINTLN(replybuffer); + // parse it out... + + + DEBUG_PRINTLN(replybuffer); + + + if (! parseReply(F("+CMGR:"), &thesmslen, ',', 11)) { + *readlen = 0; + return false; + } + + readRaw(thesmslen); + + flushInput(); + + uint16_t thelen = min(maxlen, strlen(replybuffer)); + strncpy(smsbuff, replybuffer, thelen); + smsbuff[thelen] = 0; // end the string + + + DEBUG_PRINTLN(replybuffer); + + *readlen = thelen; + return true; +} + +// Retrieve the sender of the specified SMS message and copy it as a string to +// the sender buffer. Up to senderlen characters of the sender will be copied +// and a null terminator will be added if less than senderlen charactesr are +// copied to the result. Returns true if a result was successfully retrieved, +// otherwise false. +boolean Adafruit_FONA::getSMSSender(uint8_t i, char *sender, int senderlen) { + // Ensure text mode and all text mode parameters are sent. + if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return false; + if (! sendCheckReply(F("AT+CSDH=1"), ok_reply)) return false; + + + DEBUG_PRINT(F("AT+CMGR=")); + DEBUG_PRINTLN(i); + + + // Send command to retrieve SMS message and parse a line of response. + mySerial->print(F("AT+CMGR=")); + mySerial->println(i); + readline(1000); + + + DEBUG_PRINTLN(replybuffer); + + + // Parse the second field in the response. + boolean result = parseReplyQuoted(F("+CMGR:"), sender, senderlen, ',', 1); + // Drop any remaining data from the response. + flushInput(); + return result; +} + +boolean Adafruit_FONA::sendSMS(char *smsaddr, char *smsmsg) { + if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return -1; + + char sendcmd[30] = "AT+CMGS=\""; + strncpy(sendcmd+9, smsaddr, 30-9-2); // 9 bytes beginning, 2 bytes for close quote + null + sendcmd[strlen(sendcmd)] = '\"'; + + if (! sendCheckReply(sendcmd, F("> "))) return false; + + DEBUG_PRINT(F("> ")); DEBUG_PRINTLN(smsmsg); + + mySerial->println(smsmsg); + mySerial->println(); + mySerial->write(0x1A); + + DEBUG_PRINTLN("^Z"); + + if ( (_type == FONA3G_A) || (_type == FONA3G_E) ) { + // Eat two sets of CRLF + readline(200); + //DEBUG_PRINT("Line 1: "); DEBUG_PRINTLN(strlen(replybuffer)); + readline(200); + //DEBUG_PRINT("Line 2: "); DEBUG_PRINTLN(strlen(replybuffer)); + } + readline(10000); // read the +CMGS reply, wait up to 10 seconds!!! + //DEBUG_PRINT("Line 3: "); DEBUG_PRINTLN(strlen(replybuffer)); + if (strstr(replybuffer, "+CMGS") == 0) { + return false; + } + readline(1000); // read OK + //DEBUG_PRINT("* "); DEBUG_PRINTLN(replybuffer); + + if (strcmp(replybuffer, "OK") != 0) { + return false; + } + + return true; +} + + +boolean Adafruit_FONA::deleteSMS(uint8_t i) { + if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return -1; + // read an sms + char sendbuff[12] = "AT+CMGD=000"; + sendbuff[8] = (i / 100) + '0'; + i %= 100; + sendbuff[9] = (i / 10) + '0'; + i %= 10; + sendbuff[10] = i + '0'; + + return sendCheckReply(sendbuff, ok_reply, 2000); +} + +/********* USSD *********************************************************/ + +boolean Adafruit_FONA::sendUSSD(char *ussdmsg, char *ussdbuff, uint16_t maxlen, uint16_t *readlen) { + if (! sendCheckReply(F("AT+CUSD=1"), ok_reply)) return -1; + + char sendcmd[30] = "AT+CUSD=1,\""; + strncpy(sendcmd+11, ussdmsg, 30-11-2); // 11 bytes beginning, 2 bytes for close quote + null + sendcmd[strlen(sendcmd)] = '\"'; + + if (! sendCheckReply(sendcmd, ok_reply)) { + *readlen = 0; + return false; + } else { + readline(10000); // read the +CUSD reply, wait up to 10 seconds!!! + //DEBUG_PRINT("* "); DEBUG_PRINTLN(replybuffer); + char *p = prog_char_strstr(replybuffer, PSTR("+CUSD: ")); + if (p == 0) { + *readlen = 0; + return false; + } + p+=7; //+CUSD + // Find " to get start of ussd message. + p = strchr(p, '\"'); + if (p == 0) { + *readlen = 0; + return false; + } + p+=1; //" + // Find " to get end of ussd message. + char *strend = strchr(p, '\"'); + + uint16_t lentocopy = min(maxlen-1, strend - p); + strncpy(ussdbuff, p, lentocopy+1); + ussdbuff[lentocopy] = 0; + *readlen = lentocopy; + } + return true; +} + + +/********* TIME **********************************************************/ + +boolean Adafruit_FONA::enableNetworkTimeSync(boolean onoff) { + if (onoff) { + if (! sendCheckReply(F("AT+CLTS=1"), ok_reply)) + return false; + } else { + if (! sendCheckReply(F("AT+CLTS=0"), ok_reply)) + return false; + } + + flushInput(); // eat any 'Unsolicted Result Code' + + return true; +} + +boolean Adafruit_FONA::enableNTPTimeSync(boolean onoff, FONAFlashStringPtr ntpserver) { + if (onoff) { + if (! sendCheckReply(F("AT+CNTPCID=1"), ok_reply)) + return false; + + mySerial->print(F("AT+CNTP=\"")); + if (ntpserver != 0) { + mySerial->print(ntpserver); + } else { + mySerial->print(F("pool.ntp.org")); + } + mySerial->println(F("\",0")); + readline(FONA_DEFAULT_TIMEOUT_MS); + if (strcmp(replybuffer, "OK") != 0) + return false; + + if (! sendCheckReply(F("AT+CNTP"), ok_reply, 10000)) + return false; + + uint16_t status; + readline(10000); + if (! parseReply(F("+CNTP:"), &status)) + return false; + } else { + if (! sendCheckReply(F("AT+CNTPCID=0"), ok_reply)) + return false; + } + + return true; +} + +boolean Adafruit_FONA::getTime(char *buff, uint16_t maxlen) { + getReply(F("AT+CCLK?"), (uint16_t) 10000); + if (strncmp(replybuffer, "+CCLK: ", 7) != 0) + return false; + + char *p = replybuffer+7; + uint16_t lentocopy = min(maxlen-1, strlen(p)); + strncpy(buff, p, lentocopy+1); + buff[lentocopy] = 0; + + readline(); // eat OK + + return true; +} + +/********* GPS **********************************************************/ + + +boolean Adafruit_FONA::enableGPS(boolean onoff) { + uint16_t state; + + // first check if its already on or off + + if (_type == FONA808_V2) { + if (! sendParseReply(F("AT+CGNSPWR?"), F("+CGNSPWR: "), &state) ) + return false; + } else { + if (! sendParseReply(F("AT+CGPSPWR?"), F("+CGPSPWR: "), &state)) + return false; + } + + if (onoff && !state) { + if (_type == FONA808_V2) { + if (! sendCheckReply(F("AT+CGNSPWR=1"), ok_reply)) // try GNS command + return false; + } else { + if (! sendCheckReply(F("AT+CGPSPWR=1"), ok_reply)) + return false; + } + } else if (!onoff && state) { + if (_type == FONA808_V2) { + if (! sendCheckReply(F("AT+CGNSPWR=0"), ok_reply)) // try GNS command + return false; + } else { + if (! sendCheckReply(F("AT+CGPSPWR=0"), ok_reply)) + return false; + } + } + return true; +} + + + +boolean Adafruit_FONA_3G::enableGPS(boolean onoff) { + uint16_t state; + + // first check if its already on or off + if (! Adafruit_FONA::sendParseReply(F("AT+CGPS?"), F("+CGPS: "), &state) ) + return false; + + if (onoff && !state) { + if (! sendCheckReply(F("AT+CGPS=1"), ok_reply)) + return false; + } else if (!onoff && state) { + if (! sendCheckReply(F("AT+CGPS=0"), ok_reply)) + return false; + // this takes a little time + readline(2000); // eat '+CGPS: 0' + } + return true; +} + +int8_t Adafruit_FONA::GPSstatus(void) { + if (_type == FONA808_V2) { + // 808 V2 uses GNS commands and doesn't have an explicit 2D/3D fix status. + // Instead just look for a fix and if found assume it's a 3D fix. + getReply(F("AT+CGNSINF")); + char *p = prog_char_strstr(replybuffer, (prog_char*)F("+CGNSINF: ")); + if (p == 0) return -1; + p+=12; // Skip to second value, fix status. + readline(); // eat 'OK' + //DEBUG_PRINTLN(p); + // Assume if the fix status is '1' then we have a 3D fix, otherwise no fix. + if (p[0] == '1') return 3; + else return 0; + } + if (_type == FONA3G_A || _type == FONA3G_E) { + // FONA 3G doesn't have an explicit 2D/3D fix status. + // Instead just look for a fix and if found assume it's a 3D fix. + getReply(F("AT+CGPSINFO")); + char *p = prog_char_strstr(replybuffer, (prog_char*)F("+CGPSINFO:")); + if (p == 0) return -1; + if (p[10] != ',') return 3; // if you get anything, its 3D fix + return 0; + } + else { + // 808 V1 looks for specific 2D or 3D fix state. + getReply(F("AT+CGPSSTATUS?")); + char *p = prog_char_strstr(replybuffer, (prog_char*)F("SSTATUS: Location ")); + if (p == 0) return -1; + p+=18; + readline(); // eat 'OK' + //DEBUG_PRINTLN(p); + if (p[0] == 'U') return 0; + if (p[0] == 'N') return 1; + if (p[0] == '2') return 2; + if (p[0] == '3') return 3; + } + // else + return 0; +} + +uint8_t Adafruit_FONA::getGPS(uint8_t arg, char *buffer, uint8_t maxbuff) { + int32_t x = arg; + + if ( (_type == FONA3G_A) || (_type == FONA3G_E) ) { + getReply(F("AT+CGPSINFO")); + } else if (_type == FONA808_V1) { + getReply(F("AT+CGPSINF="), x); + } else { + getReply(F("AT+CGNSINF")); + } + + char *p = prog_char_strstr(replybuffer, (prog_char*)F("SINF")); + if (p == 0) { + buffer[0] = 0; + return 0; + } + + p+=6; + + uint8_t len = max(maxbuff-1, strlen(p)); + strncpy(buffer, p, len); + buffer[len] = 0; + + readline(); // eat 'OK' + return len; +} + +boolean Adafruit_FONA::getGPS(float *lat, float *lon, float *speed_kph, float *heading, float *altitude) { + + char gpsbuffer[120]; + + // we need at least a 2D fix + if (GPSstatus() < 2) + return false; + + // grab the mode 2^5 gps csv from the sim808 + uint8_t res_len = getGPS(32, gpsbuffer, 120); + + // make sure we have a response + if (res_len == 0) + return false; + + if (_type == FONA3G_A || _type == FONA3G_E) { + // Parse 3G respose + // +CGPSINFO:4043.000000,N,07400.000000,W,151015,203802.1,-12.0,0.0,0 + // skip beginning + char *tok; + + // grab the latitude + char *latp = strtok(gpsbuffer, ","); + if (! latp) return false; + + // grab latitude direction + char *latdir = strtok(NULL, ","); + if (! latdir) return false; + + // grab longitude + char *longp = strtok(NULL, ","); + if (! longp) return false; + + // grab longitude direction + char *longdir = strtok(NULL, ","); + if (! longdir) return false; + + // skip date & time + tok = strtok(NULL, ","); + tok = strtok(NULL, ","); + + // only grab altitude if needed + if (altitude != NULL) { + // grab altitude + char *altp = strtok(NULL, ","); + if (! altp) return false; + *altitude = atof(altp); + } + + // only grab speed if needed + if (speed_kph != NULL) { + // grab the speed in km/h + char *speedp = strtok(NULL, ","); + if (! speedp) return false; + + *speed_kph = atof(speedp); + } + + // only grab heading if needed + if (heading != NULL) { + + // grab the speed in knots + char *coursep = strtok(NULL, ","); + if (! coursep) return false; + + *heading = atof(coursep); + } + + double latitude = atof(latp); + double longitude = atof(longp); + + // convert latitude from minutes to decimal + float degrees = floor(latitude / 100); + double minutes = latitude - (100 * degrees); + minutes /= 60; + degrees += minutes; + + // turn direction into + or - + if (latdir[0] == 'S') degrees *= -1; + + *lat = degrees; + + // convert longitude from minutes to decimal + degrees = floor(longitude / 100); + minutes = longitude - (100 * degrees); + minutes /= 60; + degrees += minutes; + + // turn direction into + or - + if (longdir[0] == 'W') degrees *= -1; + + *lon = degrees; + + } else if (_type == FONA808_V2) { + // Parse 808 V2 response. See table 2-3 from here for format: + // http://www.adafruit.com/datasheets/SIM800%20Series_GNSS_Application%20Note%20V1.00.pdf + + // skip GPS run status + char *tok = strtok(gpsbuffer, ","); + if (! tok) return false; + + // skip fix status + tok = strtok(NULL, ","); + if (! tok) return false; + + // skip date + tok = strtok(NULL, ","); + if (! tok) return false; + + // grab the latitude + char *latp = strtok(NULL, ","); + if (! latp) return false; + + // grab longitude + char *longp = strtok(NULL, ","); + if (! longp) return false; + + *lat = atof(latp); + *lon = atof(longp); + + // only grab altitude if needed + if (altitude != NULL) { + // grab altitude + char *altp = strtok(NULL, ","); + if (! altp) return false; + + *altitude = atof(altp); + } + + // only grab speed if needed + if (speed_kph != NULL) { + // grab the speed in km/h + char *speedp = strtok(NULL, ","); + if (! speedp) return false; + + *speed_kph = atof(speedp); + } + + // only grab heading if needed + if (heading != NULL) { + + // grab the speed in knots + char *coursep = strtok(NULL, ","); + if (! coursep) return false; + + *heading = atof(coursep); + } + } + else { + // Parse 808 V1 response. + + // skip mode + char *tok = strtok(gpsbuffer, ","); + if (! tok) return false; + + // skip date + tok = strtok(NULL, ","); + if (! tok) return false; + + // skip fix + tok = strtok(NULL, ","); + if (! tok) return false; + + // grab the latitude + char *latp = strtok(NULL, ","); + if (! latp) return false; + + // grab latitude direction + char *latdir = strtok(NULL, ","); + if (! latdir) return false; + + // grab longitude + char *longp = strtok(NULL, ","); + if (! longp) return false; + + // grab longitude direction + char *longdir = strtok(NULL, ","); + if (! longdir) return false; + + double latitude = atof(latp); + double longitude = atof(longp); + + // convert latitude from minutes to decimal + float degrees = floor(latitude / 100); + double minutes = latitude - (100 * degrees); + minutes /= 60; + degrees += minutes; + + // turn direction into + or - + if (latdir[0] == 'S') degrees *= -1; + + *lat = degrees; + + // convert longitude from minutes to decimal + degrees = floor(longitude / 100); + minutes = longitude - (100 * degrees); + minutes /= 60; + degrees += minutes; + + // turn direction into + or - + if (longdir[0] == 'W') degrees *= -1; + + *lon = degrees; + + // only grab speed if needed + if (speed_kph != NULL) { + + // grab the speed in knots + char *speedp = strtok(NULL, ","); + if (! speedp) return false; + + // convert to kph + *speed_kph = atof(speedp) * 1.852; + + } + + // only grab heading if needed + if (heading != NULL) { + + // grab the speed in knots + char *coursep = strtok(NULL, ","); + if (! coursep) return false; + + *heading = atof(coursep); + + } + + // no need to continue + if (altitude == NULL) + return true; + + // we need at least a 3D fix for altitude + if (GPSstatus() < 3) + return false; + + // grab the mode 0 gps csv from the sim808 + res_len = getGPS(0, gpsbuffer, 120); + + // make sure we have a response + if (res_len == 0) + return false; + + // skip mode + tok = strtok(gpsbuffer, ","); + if (! tok) return false; + + // skip lat + tok = strtok(NULL, ","); + if (! tok) return false; + + // skip long + tok = strtok(NULL, ","); + if (! tok) return false; + + // grab altitude + char *altp = strtok(NULL, ","); + if (! altp) return false; + + *altitude = atof(altp); + } + + return true; + +} + +boolean Adafruit_FONA::enableGPSNMEA(uint8_t i) { + + char sendbuff[15] = "AT+CGPSOUT=000"; + sendbuff[11] = (i / 100) + '0'; + i %= 100; + sendbuff[12] = (i / 10) + '0'; + i %= 10; + sendbuff[13] = i + '0'; + + if (_type == FONA808_V2) { + if (i) + return sendCheckReply(F("AT+CGNSTST=1"), ok_reply); + else + return sendCheckReply(F("AT+CGNSTST=0"), ok_reply); + } else { + return sendCheckReply(sendbuff, ok_reply, 2000); + } +} + + +/********* GPRS **********************************************************/ + + +boolean Adafruit_FONA::enableGPRS(boolean onoff) { + + if (onoff) { + // disconnect all sockets + sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 20000); + + if (! sendCheckReply(F("AT+CGATT=1"), ok_reply, 10000)) + return false; + + // set bearer profile! connection type GPRS + if (! sendCheckReply(F("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\""), + ok_reply, 10000)) + return false; + + // set bearer profile access point name + if (apn) { + // Send command AT+SAPBR=3,1,"APN","" where is the configured APN value. + if (! sendCheckReplyQuoted(F("AT+SAPBR=3,1,\"APN\","), apn, ok_reply, 10000)) + return false; + + // send AT+CSTT,"apn","user","pass" + flushInput(); + + mySerial->print(F("AT+CSTT=\"")); + mySerial->print(apn); + if (apnusername) { + mySerial->print("\",\""); + mySerial->print(apnusername); + } + if (apnpassword) { + mySerial->print("\",\""); + mySerial->print(apnpassword); + } + mySerial->println("\""); + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(F("AT+CSTT=\"")); + DEBUG_PRINT(apn); + + if (apnusername) { + DEBUG_PRINT("\",\""); + DEBUG_PRINT(apnusername); + } + if (apnpassword) { + DEBUG_PRINT("\",\""); + DEBUG_PRINT(apnpassword); + } + DEBUG_PRINTLN("\""); + + if (! expectReply(ok_reply)) return false; + + // set username/password + if (apnusername) { + // Send command AT+SAPBR=3,1,"USER","" where is the configured APN username. + if (! sendCheckReplyQuoted(F("AT+SAPBR=3,1,\"USER\","), apnusername, ok_reply, 10000)) + return false; + } + if (apnpassword) { + // Send command AT+SAPBR=3,1,"PWD","" where is the configured APN password. + if (! sendCheckReplyQuoted(F("AT+SAPBR=3,1,\"PWD\","), apnpassword, ok_reply, 10000)) + return false; + } + } + + // open GPRS context + if (! sendCheckReply(F("AT+SAPBR=1,1"), ok_reply, 30000)) + return false; + + // bring up wireless connection + if (! sendCheckReply(F("AT+CIICR"), ok_reply, 10000)) + return false; + + } else { + // disconnect all sockets + if (! sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 20000)) + return false; + + // close GPRS context + if (! sendCheckReply(F("AT+SAPBR=0,1"), ok_reply, 10000)) + return false; + + if (! sendCheckReply(F("AT+CGATT=0"), ok_reply, 10000)) + return false; + + } + return true; +} + +boolean Adafruit_FONA_3G::enableGPRS(boolean onoff) { + + if (onoff) { + // disconnect all sockets + //sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 5000); + + if (! sendCheckReply(F("AT+CGATT=1"), ok_reply, 10000)) + return false; + + + // set bearer profile access point name + if (apn) { + // Send command AT+CGSOCKCONT=1,"IP","" where is the configured APN name. + if (! sendCheckReplyQuoted(F("AT+CGSOCKCONT=1,\"IP\","), apn, ok_reply, 10000)) + return false; + + // set username/password + if (apnusername) { + char authstring[100] = "AT+CGAUTH=1,1,\""; + char *strp = authstring + strlen(authstring); + prog_char_strcpy(strp, (prog_char *)apnusername); + strp+=prog_char_strlen((prog_char *)apnusername); + strp[0] = '\"'; + strp++; + strp[0] = 0; + + if (apnpassword) { + strp[0] = ','; strp++; + strp[0] = '\"'; strp++; + prog_char_strcpy(strp, (prog_char *)apnpassword); + strp+=prog_char_strlen((prog_char *)apnpassword); + strp[0] = '\"'; + strp++; + strp[0] = 0; + } + + if (! sendCheckReply(authstring, ok_reply, 10000)) + return false; + } + } + + // connect in transparent + if (! sendCheckReply(F("AT+CIPMODE=1"), ok_reply, 10000)) + return false; + // open network (?) + if (! sendCheckReply(F("AT+NETOPEN=,,1"), F("Network opened"), 10000)) + return false; + + readline(); // eat 'OK' + } else { + // close GPRS context + if (! sendCheckReply(F("AT+NETCLOSE"), F("Network closed"), 10000)) + return false; + + readline(); // eat 'OK' + } + + return true; +} + +uint8_t Adafruit_FONA::GPRSstate(void) { + uint16_t state; + + if (! sendParseReply(F("AT+CGATT?"), F("+CGATT: "), &state) ) + return -1; + + return state; +} + +void Adafruit_FONA::setGPRSNetworkSettings(FONAFlashStringPtr apn, + FONAFlashStringPtr username, FONAFlashStringPtr password) { + this->apn = apn; + this->apnusername = username; + this->apnpassword = password; +} + +boolean Adafruit_FONA::getGSMLoc(uint16_t *errorcode, char *buff, uint16_t maxlen) { + + getReply(F("AT+CIPGSMLOC=1,1"), (uint16_t)10000); + + if (! parseReply(F("+CIPGSMLOC: "), errorcode)) + return false; + + char *p = replybuffer+14; + uint16_t lentocopy = min(maxlen-1, strlen(p)); + strncpy(buff, p, lentocopy+1); + + readline(); // eat OK + + return true; +} + +boolean Adafruit_FONA::getGSMLoc(float *lat, float *lon) { + + uint16_t returncode; + char gpsbuffer[120]; + + // make sure we could get a response + if (! getGSMLoc(&returncode, gpsbuffer, 120)) + return false; + + // make sure we have a valid return code + if (returncode != 0) + return false; + + // +CIPGSMLOC: 0,-74.007729,40.730160,2015/10/15,19:24:55 + // tokenize the gps buffer to locate the lat & long + char *longp = strtok(gpsbuffer, ","); + if (! longp) return false; + + char *latp = strtok(NULL, ","); + if (! latp) return false; + + *lat = atof(latp); + *lon = atof(longp); + + return true; + +} +/********* TCP FUNCTIONS ************************************/ + + +boolean Adafruit_FONA::TCPconnect(char *server, uint16_t port) { + flushInput(); + + // close all old connections + if (! sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 20000) ) return false; + + // single connection at a time + if (! sendCheckReply(F("AT+CIPMUX=0"), ok_reply) ) return false; + + // manually read data + if (! sendCheckReply(F("AT+CIPRXGET=1"), ok_reply) ) return false; + + + DEBUG_PRINT(F("AT+CIPSTART=\"TCP\",\"")); + DEBUG_PRINT(server); + DEBUG_PRINT(F("\",\"")); + DEBUG_PRINT(port); + DEBUG_PRINTLN(F("\"")); + + + mySerial->print(F("AT+CIPSTART=\"TCP\",\"")); + mySerial->print(server); + mySerial->print(F("\",\"")); + mySerial->print(port); + mySerial->println(F("\"")); + + if (! expectReply(ok_reply)) return false; + if (! expectReply(F("CONNECT OK"))) return false; + + // looks like it was a success (?) + return true; +} + +boolean Adafruit_FONA::TCPclose(void) { + return sendCheckReply(F("AT+CIPCLOSE"), ok_reply); +} + +boolean Adafruit_FONA::TCPconnected(void) { + if (! sendCheckReply(F("AT+CIPSTATUS"), ok_reply, 100) ) return false; + readline(100); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return (strcmp(replybuffer, "STATE: CONNECT OK") == 0); +} + +boolean Adafruit_FONA::TCPsend(char *packet, uint8_t len) { + + DEBUG_PRINT(F("AT+CIPSEND=")); + DEBUG_PRINTLN(len); +#ifdef ADAFRUIT_FONA_DEBUG + for (uint16_t i=0; iprint(F("AT+CIPSEND=")); + mySerial->println(len); + readline(); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + if (replybuffer[0] != '>') return false; + + mySerial->write(packet, len); + readline(3000); // wait up to 3 seconds to send the data + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + + return (strcmp(replybuffer, "SEND OK") == 0); +} + +uint16_t Adafruit_FONA::TCPavailable(void) { + uint16_t avail; + + if (! sendParseReply(F("AT+CIPRXGET=4"), F("+CIPRXGET: 4,"), &avail, ',', 0) ) return false; + + + DEBUG_PRINT (avail); DEBUG_PRINTLN(F(" bytes available")); + + + return avail; +} + + +uint16_t Adafruit_FONA::TCPread(uint8_t *buff, uint8_t len) { + uint16_t avail; + + mySerial->print(F("AT+CIPRXGET=2,")); + mySerial->println(len); + readline(); + if (! parseReply(F("+CIPRXGET: 2,"), &avail, ',', 0)) return false; + + readRaw(avail); + +#ifdef ADAFRUIT_FONA_DEBUG + DEBUG_PRINT (avail); DEBUG_PRINTLN(F(" bytes read")); + for (uint8_t i=0;i ")); + DEBUG_PRINT(F("AT+HTTPPARA=\"")); + DEBUG_PRINT(parameter); + DEBUG_PRINTLN('"'); + + + mySerial->print(F("AT+HTTPPARA=\"")); + mySerial->print(parameter); + if (quoted) + mySerial->print(F("\",\"")); + else + mySerial->print(F("\",")); +} + +boolean Adafruit_FONA::HTTP_para_end(boolean quoted) { + if (quoted) + mySerial->println('"'); + else + mySerial->println(); + + return expectReply(ok_reply); +} + +boolean Adafruit_FONA::HTTP_para(FONAFlashStringPtr parameter, + const char *value) { + HTTP_para_start(parameter, true); + mySerial->print(value); + return HTTP_para_end(true); +} + +boolean Adafruit_FONA::HTTP_para(FONAFlashStringPtr parameter, + FONAFlashStringPtr value) { + HTTP_para_start(parameter, true); + mySerial->print(value); + return HTTP_para_end(true); +} + +boolean Adafruit_FONA::HTTP_para(FONAFlashStringPtr parameter, + int32_t value) { + HTTP_para_start(parameter, false); + mySerial->print(value); + return HTTP_para_end(false); +} + +boolean Adafruit_FONA::HTTP_data(uint32_t size, uint32_t maxTime) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); + DEBUG_PRINT(F("AT+HTTPDATA=")); + DEBUG_PRINT(size); + DEBUG_PRINT(','); + DEBUG_PRINTLN(maxTime); + + + mySerial->print(F("AT+HTTPDATA=")); + mySerial->print(size); + mySerial->print(","); + mySerial->println(maxTime); + + return expectReply(F("DOWNLOAD")); +} + +boolean Adafruit_FONA::HTTP_action(uint8_t method, uint16_t *status, + uint16_t *datalen, int32_t timeout) { + // Send request. + if (! sendCheckReply(F("AT+HTTPACTION="), method, ok_reply)) + return false; + + // Parse response status and size. + readline(timeout); + if (! parseReply(F("+HTTPACTION:"), status, ',', 1)) + return false; + if (! parseReply(F("+HTTPACTION:"), datalen, ',', 2)) + return false; + + return true; +} + +boolean Adafruit_FONA::HTTP_readall(uint16_t *datalen) { + getReply(F("AT+HTTPREAD")); + if (! parseReply(F("+HTTPREAD:"), datalen, ',', 0)) + return false; + + return true; +} + +boolean Adafruit_FONA::HTTP_ssl(boolean onoff) { + return sendCheckReply(F("AT+HTTPSSL="), onoff ? 1 : 0, ok_reply); +} + +/********* HTTP HIGH LEVEL FUNCTIONS ***************************/ + +boolean Adafruit_FONA::HTTP_GET_start(char *url, + uint16_t *status, uint16_t *datalen){ + if (! HTTP_setup(url)) + return false; + + // HTTP GET + if (! HTTP_action(FONA_HTTP_GET, status, datalen, 30000)) + return false; + + DEBUG_PRINT(F("Status: ")); DEBUG_PRINTLN(*status); + DEBUG_PRINT(F("Len: ")); DEBUG_PRINTLN(*datalen); + + // HTTP response data + if (! HTTP_readall(datalen)) + return false; + + return true; +} + +/* +boolean Adafruit_FONA_3G::HTTP_GET_start(char *ipaddr, char *path, uint16_t port + uint16_t *status, uint16_t *datalen){ + char send[100] = "AT+CHTTPACT=\""; + char *sendp = send + strlen(send); + memset(sendp, 0, 100 - strlen(send)); + + strcpy(sendp, ipaddr); + sendp+=strlen(ipaddr); + sendp[0] = '\"'; + sendp++; + sendp[0] = ','; + itoa(sendp, port); + getReply(send, 500); + + return; + + if (! HTTP_setup(url)) + + return false; + + // HTTP GET + if (! HTTP_action(FONA_HTTP_GET, status, datalen)) + return false; + + DEBUG_PRINT("Status: "); DEBUG_PRINTLN(*status); + DEBUG_PRINT("Len: "); DEBUG_PRINTLN(*datalen); + + // HTTP response data + if (! HTTP_readall(datalen)) + return false; + + return true; +} +*/ + +void Adafruit_FONA::HTTP_GET_end(void) { + HTTP_term(); +} + +boolean Adafruit_FONA::HTTP_POST_start(char *url, + FONAFlashStringPtr contenttype, + const uint8_t *postdata, uint16_t postdatalen, + uint16_t *status, uint16_t *datalen){ + if (! HTTP_setup(url)) + return false; + + if (! HTTP_para(F("CONTENT"), contenttype)) { + return false; + } + + // HTTP POST data + if (! HTTP_data(postdatalen, 10000)) + return false; + mySerial->write(postdata, postdatalen); + if (! expectReply(ok_reply)) + return false; + + // HTTP POST + if (! HTTP_action(FONA_HTTP_POST, status, datalen)) + return false; + + DEBUG_PRINT(F("Status: ")); DEBUG_PRINTLN(*status); + DEBUG_PRINT(F("Len: ")); DEBUG_PRINTLN(*datalen); + + // HTTP response data + if (! HTTP_readall(datalen)) + return false; + + return true; +} + +void Adafruit_FONA::HTTP_POST_end(void) { + HTTP_term(); +} + +void Adafruit_FONA::setUserAgent(FONAFlashStringPtr useragent) { + this->useragent = useragent; +} + +void Adafruit_FONA::setHTTPSRedirect(boolean onoff) { + httpsredirect = onoff; +} + +/********* HTTP HELPERS ****************************************/ + +boolean Adafruit_FONA::HTTP_setup(char *url) { + // Handle any pending + HTTP_term(); + + // Initialize and set parameters + if (! HTTP_init()) + return false; + if (! HTTP_para(F("CID"), 1)) + return false; + if (! HTTP_para(F("UA"), useragent)) + return false; + if (! HTTP_para(F("URL"), url)) + return false; + + // HTTPS redirect + if (httpsredirect) { + if (! HTTP_para(F("REDIR"),1)) + return false; + + if (! HTTP_ssl(true)) + return false; + } + + return true; +} + +/********* HELPERS *********************************************/ + +boolean Adafruit_FONA::expectReply(FONAFlashStringPtr reply, + uint16_t timeout) { + readline(timeout); + + DEBUG_PRINT(F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return (prog_char_strcmp(replybuffer, (prog_char*)reply) == 0); +} + +/********* LOW LEVEL *******************************************/ + +inline int Adafruit_FONA::available(void) { + return mySerial->available(); +} + +inline size_t Adafruit_FONA::write(uint8_t x) { + return mySerial->write(x); +} + +inline int Adafruit_FONA::read(void) { + return mySerial->read(); +} + +inline int Adafruit_FONA::peek(void) { + return mySerial->peek(); +} + +inline void Adafruit_FONA::flush() { + mySerial->flush(); +} + +void Adafruit_FONA::flushInput() { + // Read all available serial input to flush pending data. + uint16_t timeoutloop = 0; + while (timeoutloop++ < 40) { + while(available()) { + read(); + timeoutloop = 0; // If char was received reset the timer + } + delay(1); + } +} + +uint16_t Adafruit_FONA::readRaw(uint16_t b) { + uint16_t idx = 0; + + while (b && (idx < sizeof(replybuffer)-1)) { + if (mySerial->available()) { + replybuffer[idx] = mySerial->read(); + idx++; + b--; + } + } + replybuffer[idx] = 0; + + return idx; +} + +uint8_t Adafruit_FONA::readline(uint16_t timeout, boolean multiline) { + uint16_t replyidx = 0; + + while (timeout--) { + if (replyidx >= 254) { + //DEBUG_PRINTLN(F("SPACE")); + break; + } + + while(mySerial->available()) { + char c = mySerial->read(); + if (c == '\r') continue; + if (c == 0xA) { + if (replyidx == 0) // the first 0x0A is ignored + continue; + + if (!multiline) { + timeout = 0; // the second 0x0A is the end of the line + break; + } + } + replybuffer[replyidx] = c; + //DEBUG_PRINT(c, HEX); DEBUG_PRINT("#"); DEBUG_PRINTLN(c); + replyidx++; + } + + if (timeout == 0) { + //DEBUG_PRINTLN(F("TIMEOUT")); + break; + } + delay(1); + } + replybuffer[replyidx] = 0; // null term + return replyidx; +} + +uint8_t Adafruit_FONA::getReply(char *send, uint16_t timeout) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN(send); + + + mySerial->println(send); + + uint8_t l = readline(timeout); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return l; +} + +uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr send, uint16_t timeout) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN(send); + + + mySerial->println(send); + + uint8_t l = readline(timeout); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return l; +} + +// Send prefix, suffix, and newline. Return response (and also set replybuffer with response). +uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr prefix, char *suffix, uint16_t timeout) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); DEBUG_PRINTLN(suffix); + + + mySerial->print(prefix); + mySerial->println(suffix); + + uint8_t l = readline(timeout); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return l; +} + +// Send prefix, suffix, and newline. Return response (and also set replybuffer with response). +uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr prefix, int32_t suffix, uint16_t timeout) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); DEBUG_PRINTLN(suffix, DEC); + + + mySerial->print(prefix); + mySerial->println(suffix, DEC); + + uint8_t l = readline(timeout); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return l; +} + +// Send prefix, suffix, suffix2, and newline. Return response (and also set replybuffer with response). +uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr prefix, int32_t suffix1, int32_t suffix2, uint16_t timeout) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); + DEBUG_PRINT(suffix1, DEC); DEBUG_PRINT(','); DEBUG_PRINTLN(suffix2, DEC); + + + mySerial->print(prefix); + mySerial->print(suffix1); + mySerial->print(','); + mySerial->println(suffix2, DEC); + + uint8_t l = readline(timeout); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return l; +} + +// Send prefix, ", suffix, ", and newline. Return response (and also set replybuffer with response). +uint8_t Adafruit_FONA::getReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, uint16_t timeout) { + flushInput(); + + + DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); + DEBUG_PRINT('"'); DEBUG_PRINT(suffix); DEBUG_PRINTLN('"'); + + + mySerial->print(prefix); + mySerial->print('"'); + mySerial->print(suffix); + mySerial->println('"'); + + uint8_t l = readline(timeout); + + DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); + + return l; +} + +boolean Adafruit_FONA::sendCheckReply(char *send, char *reply, uint16_t timeout) { + if (! getReply(send, timeout) ) + return false; +/* + for (uint8_t i=0; i http://www.adafruit.com/products/1946 + ----> http://www.adafruit.com/products/1963 + + These displays use TTL Serial to communicate, 2 pins are required to + interface + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ****************************************************/ +#ifndef ADAFRUIT_FONA_H +#define ADAFRUIT_FONA_H + +#include "includes/FONAConfig.h" +#include "includes/FONAExtIncludes.h" +#include "includes/platform/FONAPlatform.h" + + + +#define FONA800L 1 +#define FONA800H 6 + +#define FONA808_V1 2 +#define FONA808_V2 3 + +#define FONA3G_A 4 +#define FONA3G_E 5 + +// Uncomment to changed the preferred SMS storage +//#define FONA_PREF_SMS_STORAGE "SM" + +#define FONA_HEADSETAUDIO 0 +#define FONA_EXTAUDIO 1 + +#define FONA_STTONE_DIALTONE 1 +#define FONA_STTONE_BUSY 2 +#define FONA_STTONE_CONGESTION 3 +#define FONA_STTONE_PATHACK 4 +#define FONA_STTONE_DROPPED 5 +#define FONA_STTONE_ERROR 6 +#define FONA_STTONE_CALLWAIT 7 +#define FONA_STTONE_RINGING 8 +#define FONA_STTONE_BEEP 16 +#define FONA_STTONE_POSTONE 17 +#define FONA_STTONE_ERRTONE 18 +#define FONA_STTONE_INDIANDIALTONE 19 +#define FONA_STTONE_USADIALTONE 20 + +#define FONA_DEFAULT_TIMEOUT_MS 500 + +#define FONA_HTTP_GET 0 +#define FONA_HTTP_POST 1 +#define FONA_HTTP_HEAD 2 + +#define FONA_CALL_READY 0 +#define FONA_CALL_FAILED 1 +#define FONA_CALL_UNKNOWN 2 +#define FONA_CALL_RINGING 3 +#define FONA_CALL_INPROGRESS 4 + +class Adafruit_FONA : public FONAStreamType { + public: + Adafruit_FONA(int8_t r); + boolean begin(FONAStreamType &port); + uint8_t type(); + + // Stream + int available(void); + size_t write(uint8_t x); + int read(void); + int peek(void); + void flush(); + + // FONA 3G requirements + boolean setBaudrate(uint16_t baud); + + // RTC + boolean enableRTC(uint8_t i); + boolean readRTC(uint8_t *year, uint8_t *month, uint8_t *date, uint8_t *hr, uint8_t *min, uint8_t *sec); + + // Battery and ADC + boolean getADCVoltage(uint16_t *v); + boolean getBattPercent(uint16_t *p); + boolean getBattVoltage(uint16_t *v); + + // SIM query + uint8_t unlockSIM(char *pin); + uint8_t getSIMCCID(char *ccid); + uint8_t getNetworkStatus(void); + uint8_t getRSSI(void); + + // IMEI + uint8_t getIMEI(char *imei); + + // set Audio output + boolean setAudio(uint8_t a); + boolean setVolume(uint8_t i); + uint8_t getVolume(void); + boolean playToolkitTone(uint8_t t, uint16_t len); + boolean setMicVolume(uint8_t a, uint8_t level); + boolean playDTMF(char tone); + + // FM radio functions. + boolean tuneFMradio(uint16_t station); + boolean FMradio(boolean onoff, uint8_t a = FONA_HEADSETAUDIO); + boolean setFMVolume(uint8_t i); + int8_t getFMVolume(); + int8_t getFMSignalLevel(uint16_t station); + + // SMS handling + boolean setSMSInterrupt(uint8_t i); + uint8_t getSMSInterrupt(void); + int8_t getNumSMS(void); + boolean readSMS(uint8_t i, char *smsbuff, uint16_t max, uint16_t *readsize); + boolean sendSMS(char *smsaddr, char *smsmsg); + boolean deleteSMS(uint8_t i); + boolean getSMSSender(uint8_t i, char *sender, int senderlen); + boolean sendUSSD(char *ussdmsg, char *ussdbuff, uint16_t maxlen, uint16_t *readlen); + + // Time + boolean enableNetworkTimeSync(boolean onoff); + boolean enableNTPTimeSync(boolean onoff, FONAFlashStringPtr ntpserver=0); + boolean getTime(char *buff, uint16_t maxlen); + + // GPRS handling + boolean enableGPRS(boolean onoff); + uint8_t GPRSstate(void); + boolean getGSMLoc(uint16_t *replycode, char *buff, uint16_t maxlen); + boolean getGSMLoc(float *lat, float *lon); + void setGPRSNetworkSettings(FONAFlashStringPtr apn, FONAFlashStringPtr username=0, FONAFlashStringPtr password=0); + + // GPS handling + boolean enableGPS(boolean onoff); + int8_t GPSstatus(void); + uint8_t getGPS(uint8_t arg, char *buffer, uint8_t maxbuff); + boolean getGPS(float *lat, float *lon, float *speed_kph=0, float *heading=0, float *altitude=0); + boolean enableGPSNMEA(uint8_t nmea); + + // TCP raw connections + boolean TCPconnect(char *server, uint16_t port); + boolean TCPclose(void); + boolean TCPconnected(void); + boolean TCPsend(char *packet, uint8_t len); + uint16_t TCPavailable(void); + uint16_t TCPread(uint8_t *buff, uint8_t len); + + // HTTP low level interface (maps directly to SIM800 commands). + boolean HTTP_init(); + boolean HTTP_term(); + void HTTP_para_start(FONAFlashStringPtr parameter, boolean quoted = true); + boolean HTTP_para_end(boolean quoted = true); + boolean HTTP_para(FONAFlashStringPtr parameter, const char *value); + boolean HTTP_para(FONAFlashStringPtr parameter, FONAFlashStringPtr value); + boolean HTTP_para(FONAFlashStringPtr parameter, int32_t value); + boolean HTTP_data(uint32_t size, uint32_t maxTime=10000); + boolean HTTP_action(uint8_t method, uint16_t *status, uint16_t *datalen, int32_t timeout = 10000); + boolean HTTP_readall(uint16_t *datalen); + boolean HTTP_ssl(boolean onoff); + + // HTTP high level interface (easier to use, less flexible). + boolean HTTP_GET_start(char *url, uint16_t *status, uint16_t *datalen); + void HTTP_GET_end(void); + boolean HTTP_POST_start(char *url, FONAFlashStringPtr contenttype, const uint8_t *postdata, uint16_t postdatalen, uint16_t *status, uint16_t *datalen); + void HTTP_POST_end(void); + void setUserAgent(FONAFlashStringPtr useragent); + + // HTTPS + void setHTTPSRedirect(boolean onoff); + + // PWM (buzzer) + boolean setPWM(uint16_t period, uint8_t duty = 50); + + // Phone calls + boolean callPhone(char *phonenum); + uint8_t getCallStatus(void); + boolean hangUp(void); + boolean pickUp(void); + boolean callerIdNotification(boolean enable, uint8_t interrupt = 0); + boolean incomingCallNumber(char* phonenum); + + // Helper functions to verify responses. + boolean expectReply(FONAFlashStringPtr reply, uint16_t timeout = 10000); + boolean sendCheckReply(char *send, char *reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + boolean sendCheckReply(FONAFlashStringPtr send, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + boolean sendCheckReply(char* send, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + + + protected: + int8_t _rstpin; + uint8_t _type; + + char replybuffer[255]; + FONAFlashStringPtr apn; + FONAFlashStringPtr apnusername; + FONAFlashStringPtr apnpassword; + boolean httpsredirect; + FONAFlashStringPtr useragent; + FONAFlashStringPtr ok_reply; + + // HTTP helpers + boolean HTTP_setup(char *url); + + void flushInput(); + uint16_t readRaw(uint16_t b); + uint8_t readline(uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS, boolean multiline = false); + uint8_t getReply(char *send, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + uint8_t getReply(FONAFlashStringPtr send, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + uint8_t getReply(FONAFlashStringPtr prefix, char *suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + uint8_t getReply(FONAFlashStringPtr prefix, int32_t suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + uint8_t getReply(FONAFlashStringPtr prefix, int32_t suffix1, int32_t suffix2, uint16_t timeout); // Don't set default value or else function call is ambiguous. + uint8_t getReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + + boolean sendCheckReply(FONAFlashStringPtr prefix, char *suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + boolean sendCheckReply(FONAFlashStringPtr prefix, int32_t suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + boolean sendCheckReply(FONAFlashStringPtr prefix, int32_t suffix, int32_t suffix2, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + boolean sendCheckReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); + + + boolean parseReply(FONAFlashStringPtr toreply, + uint16_t *v, char divider = ',', uint8_t index=0); + boolean parseReply(FONAFlashStringPtr toreply, + char *v, char divider = ',', uint8_t index=0); + boolean parseReplyQuoted(FONAFlashStringPtr toreply, + char *v, int maxlen, char divider, uint8_t index); + + boolean sendParseReply(FONAFlashStringPtr tosend, + FONAFlashStringPtr toreply, + uint16_t *v, char divider = ',', uint8_t index=0); + + static boolean _incomingCall; + static void onIncomingCall(); + + FONAStreamType *mySerial; +}; + +class Adafruit_FONA_3G : public Adafruit_FONA { + + public: + Adafruit_FONA_3G (int8_t r) : Adafruit_FONA(r) { _type = FONA3G_A; } + + boolean getBattVoltage(uint16_t *v); + boolean playToolkitTone(uint8_t t, uint16_t len); + boolean hangUp(void); + boolean pickUp(void); + boolean enableGPRS(boolean onoff); + boolean enableGPS(boolean onoff); + + protected: + boolean parseReply(FONAFlashStringPtr toreply, + float *f, char divider, uint8_t index); + + boolean sendParseReply(FONAFlashStringPtr tosend, + FONAFlashStringPtr toreply, + float *f, char divider = ',', uint8_t index=0); +}; + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/README.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/README.md new file mode 100644 index 0000000..73452ca --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/README.md @@ -0,0 +1,29 @@ +# Adafruit FONA Library [![Build Status](https://secure.travis-ci.org/adafruit/Adafruit_FONA_Library.svg?branch=master)](https://travis-ci.org/adafruit/Adafruit_FONA_Library) + +**This library requires Arduino v1.0.6 or higher** + +This is a library for the Adafruit FONA Cellular GSM Breakouts etc + +Designed specifically to work with the Adafruit FONA Breakout + * https://www.adafruit.com/products/1946 + * https://www.adafruit.com/products/1963 + * http://www.adafruit.com/products/2468 + * http://www.adafruit.com/products/2542 + +These modules use TTL Serial to communicate, 2 pins are required to interface + +Adafruit invests time and resources providing this open source code, +please support Adafruit and open-source hardware by purchasing +products from Adafruit! + +Check out the links above for our tutorials and wiring diagrams + +Written by Limor Fried/Ladyada for Adafruit Industries. +BSD license, all text above must be included in any redistribution +With updates from Samy Kamkar + +To download. click the DOWNLOADS button in the top right corner, rename the uncompressed folder Adafruit_FONA +Check that the Adafruit_FONA folder contains Adafruit_FONA.cpp and Adafruit_FONA.h + +Place the Adafruit_FONA library folder your *arduinosketchfolder*/libraries/ folder. +You may need to create the libraries subfolder if its your first library. Restart the IDE. diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/.esp8266.test.skip b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/.esp8266.test.skip new file mode 100644 index 0000000..e69de29 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino new file mode 100644 index 0000000..b0be4c5 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino @@ -0,0 +1,77 @@ +/*************************************************** + This is an example for our Adafruit FONA Cellular Module + since the FONA 3G does not do auto-baud very well, this demo + fixes the baud rate to 4800 from the default 115200 + + Designed specifically to work with the Adafruit FONA 3G + ----> http://www.adafruit.com/products/2691 + ----> http://www.adafruit.com/products/2687 + + These cellular modules use TTL Serial to communicate, 2 pins are + required to interface + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ****************************************************/ + +#include "Adafruit_FONA.h" + +#define FONA_RX 2 +#define FONA_TX 3 +#define FONA_RST 4 + +// this is a large buffer for replies +char replybuffer[255]; + +// We default to using software serial. If you want to use hardware serial +// (because softserial isnt supported) comment out the following three lines +// and uncomment the HardwareSerial line +#include +SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); +SoftwareSerial *fonaSerial = &fonaSS; + +// Hardware serial is also possible! +// HardwareSerial *fonaSerial = &Serial1; + +Adafruit_FONA fona = Adafruit_FONA(FONA_RST); + +uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); + +void setup() { + while (!Serial); + + Serial.begin(115200); + Serial.println(F("FONA set baudrate")); + + Serial.println(F("First trying 115200 baud")); + // start at 115200 baud + fonaSerial->begin(115200); + fona.begin(*fonaSerial); + + // send the command to reset the baud rate to 4800 + fona.setBaudrate(4800); + + // restart with 4800 baud + fonaSerial->begin(4800); + Serial.println(F("Initializing @ 4800 baud...")); + + if (! fona.begin(*fonaSerial)) { + Serial.println(F("Couldn't find FONA")); + while(1); + } + Serial.println(F("FONA is OK")); + + // Print module IMEI number. + char imei[15] = {0}; // MUST use a 16 character buffer for IMEI! + uint8_t imeiLen = fona.getIMEI(imei); + if (imeiLen > 0) { + Serial.print("Module IMEI: "); Serial.println(imei); + } + +} + +void loop() { +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/.esp8266.test.skip b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/.esp8266.test.skip new file mode 100644 index 0000000..e69de29 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino new file mode 100644 index 0000000..7201641 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino @@ -0,0 +1,131 @@ +/*************************************************** + This is an example for our Adafruit FONA Cellular Module + + Designed specifically to work with the Adafruit FONA + ----> http://www.adafruit.com/products/1946 + ----> http://www.adafruit.com/products/1963 + ----> http://www.adafruit.com/products/2468 + ----> http://www.adafruit.com/products/2542 + + These cellular modules use TTL Serial to communicate, 2 pins are + required to interface + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ****************************************************/ + +/* +THIS CODE IS STILL IN PROGRESS! + +Open up the serial console on the Arduino at 115200 baud to interact with FONA + + +This code will receive an SMS, identify the sender's phone number, and automatically send a response + +For use with FONA 800 & 808, not 3G +*/ + +#include "Adafruit_FONA.h" + +#define FONA_RX 2 +#define FONA_TX 3 +#define FONA_RST 4 + +// this is a large buffer for replies +char replybuffer[255]; + +// We default to using software serial. If you want to use hardware serial +// (because softserial isnt supported) comment out the following three lines +// and uncomment the HardwareSerial line +#include +SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); +SoftwareSerial *fonaSerial = &fonaSS; + +// Hardware serial is also possible! +// HardwareSerial *fonaSerial = &Serial1; + +Adafruit_FONA fona = Adafruit_FONA(FONA_RST); + +uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); + +void setup() { + while (!Serial); + + Serial.begin(115200); + Serial.println(F("FONA SMS caller ID test")); + Serial.println(F("Initializing....(May take 3 seconds)")); + + // make it slow so its easy to read! + fonaSerial->begin(4800); + if (! fona.begin(*fonaSerial)) { + Serial.println(F("Couldn't find FONA")); + while(1); + } + Serial.println(F("FONA is OK")); + + // Print SIM card IMEI number. + char imei[15] = {0}; // MUST use a 16 character buffer for IMEI! + uint8_t imeiLen = fona.getIMEI(imei); + if (imeiLen > 0) { + Serial.print("SIM card IMEI: "); Serial.println(imei); + } + + Serial.println("FONA Ready"); +} + + +char fonaInBuffer[64]; //for notifications from the FONA + +void loop() { + + char* bufPtr = fonaInBuffer; //handy buffer pointer + + if (fona.available()) //any data available from the FONA? + { + int slot = 0; //this will be the slot number of the SMS + int charCount = 0; + //Read the notification into fonaInBuffer + do { + *bufPtr = fona.read(); + Serial.write(*bufPtr); + delay(1); + } while ((*bufPtr++ != '\n') && (fona.available()) && (++charCount < (sizeof(fonaInBuffer)-1))); + + //Add a terminal NULL to the notification string + *bufPtr = 0; + + //Scan the notification string for an SMS received notification. + // If it's an SMS message, we'll get the slot number in 'slot' + if (1 == sscanf(fonaInBuffer, "+CMTI: \"SM\",%d", &slot)) { + Serial.print("slot: "); Serial.println(slot); + + char callerIDbuffer[32]; //we'll store the SMS sender number in here + + // Retrieve SMS sender address/phone number. + if (! fona.getSMSSender(slot, callerIDbuffer, 31)) { + Serial.println("Didn't find SMS message in slot!"); + } + Serial.print(F("FROM: ")); Serial.println(callerIDbuffer); + + //Send back an automatic response + Serial.println("Sending reponse..."); + if (!fona.sendSMS(callerIDbuffer, "Hey, I got your text!")) { + Serial.println(F("Failed")); + } else { + Serial.println(F("Sent!")); + } + + // delete the original msg after it is processed + // otherwise, we will fill up all the slots + // and then we won't be able to receive SMS anymore + if (fona.deleteSMS(slot)) { + Serial.println(F("OK!")); + } else { + Serial.println(F("Couldn't delete")); + } + } + } +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/.esp8266.test.skip b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/.esp8266.test.skip new file mode 100644 index 0000000..e69de29 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino new file mode 100644 index 0000000..1b27732 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino @@ -0,0 +1,886 @@ +/*************************************************** + This is an example for our Adafruit FONA Cellular Module + + Designed specifically to work with the Adafruit FONA + ----> http://www.adafruit.com/products/1946 + ----> http://www.adafruit.com/products/1963 + ----> http://www.adafruit.com/products/2468 + ----> http://www.adafruit.com/products/2542 + + These cellular modules use TTL Serial to communicate, 2 pins are + required to interface + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ****************************************************/ + +/* +THIS CODE IS STILL IN PROGRESS! + +Open up the serial console on the Arduino at 115200 baud to interact with FONA + +Note that if you need to set a GPRS APN, username, and password scroll down to +the commented section below at the end of the setup() function. +*/ +#include "Adafruit_FONA.h" + +#define FONA_RX 2 +#define FONA_TX 3 +#define FONA_RST 4 + +// this is a large buffer for replies +char replybuffer[255]; + +// We default to using software serial. If you want to use hardware serial +// (because softserial isnt supported) comment out the following three lines +// and uncomment the HardwareSerial line +#include +SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); +SoftwareSerial *fonaSerial = &fonaSS; + +// Hardware serial is also possible! +// HardwareSerial *fonaSerial = &Serial1; + +// Use this for FONA 800 and 808s +Adafruit_FONA fona = Adafruit_FONA(FONA_RST); +// Use this one for FONA 3G +//Adafruit_FONA_3G fona = Adafruit_FONA_3G(FONA_RST); + +uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); + +uint8_t type; + +void setup() { + while (!Serial); + + Serial.begin(115200); + Serial.println(F("FONA basic test")); + Serial.println(F("Initializing....(May take 3 seconds)")); + + fonaSerial->begin(4800); + if (! fona.begin(*fonaSerial)) { + Serial.println(F("Couldn't find FONA")); + while (1); + } + type = fona.type(); + Serial.println(F("FONA is OK")); + Serial.print(F("Found ")); + switch (type) { + case FONA800L: + Serial.println(F("FONA 800L")); break; + case FONA800H: + Serial.println(F("FONA 800H")); break; + case FONA808_V1: + Serial.println(F("FONA 808 (v1)")); break; + case FONA808_V2: + Serial.println(F("FONA 808 (v2)")); break; + case FONA3G_A: + Serial.println(F("FONA 3G (American)")); break; + case FONA3G_E: + Serial.println(F("FONA 3G (European)")); break; + default: + Serial.println(F("???")); break; + } + + // Print module IMEI number. + char imei[15] = {0}; // MUST use a 16 character buffer for IMEI! + uint8_t imeiLen = fona.getIMEI(imei); + if (imeiLen > 0) { + Serial.print("Module IMEI: "); Serial.println(imei); + } + + // Optionally configure a GPRS APN, username, and password. + // You might need to do this to access your network's GPRS/data + // network. Contact your provider for the exact APN, username, + // and password values. Username and password are optional and + // can be removed, but APN is required. + //fona.setGPRSNetworkSettings(F("your APN"), F("your username"), F("your password")); + + // Optionally configure HTTP gets to follow redirects over SSL. + // Default is not to follow SSL redirects, however if you uncomment + // the following line then redirects over SSL will be followed. + //fona.setHTTPSRedirect(true); + + printMenu(); +} + +void printMenu(void) { + Serial.println(F("-------------------------------------")); + Serial.println(F("[?] Print this menu")); + Serial.println(F("[a] read the ADC 2.8V max (FONA800 & 808)")); + Serial.println(F("[b] read the Battery V and % charged")); + Serial.println(F("[C] read the SIM CCID")); + Serial.println(F("[U] Unlock SIM with PIN code")); + Serial.println(F("[i] read RSSI")); + Serial.println(F("[n] get Network status")); + Serial.println(F("[v] set audio Volume")); + Serial.println(F("[V] get Volume")); + Serial.println(F("[H] set Headphone audio (FONA800 & 808)")); + Serial.println(F("[e] set External audio (FONA800 & 808)")); + Serial.println(F("[T] play audio Tone")); + Serial.println(F("[P] PWM/Buzzer out (FONA800 & 808)")); + + // FM (SIM800 only!) + Serial.println(F("[f] tune FM radio (FONA800)")); + Serial.println(F("[F] turn off FM (FONA800)")); + Serial.println(F("[m] set FM volume (FONA800)")); + Serial.println(F("[M] get FM volume (FONA800)")); + Serial.println(F("[q] get FM station signal level (FONA800)")); + + // Phone + Serial.println(F("[c] make phone Call")); + Serial.println(F("[A] get call status")); + Serial.println(F("[h] Hang up phone")); + Serial.println(F("[p] Pick up phone")); + + // SMS + Serial.println(F("[N] Number of SMSs")); + Serial.println(F("[r] Read SMS #")); + Serial.println(F("[R] Read All SMS")); + Serial.println(F("[d] Delete SMS #")); + Serial.println(F("[s] Send SMS")); + Serial.println(F("[u] Send USSD")); + + // Time + Serial.println(F("[y] Enable network time sync (FONA 800 & 808)")); + Serial.println(F("[Y] Enable NTP time sync (GPRS FONA 800 & 808)")); + Serial.println(F("[t] Get network time")); + + // GPRS + Serial.println(F("[G] Enable GPRS")); + Serial.println(F("[g] Disable GPRS")); + Serial.println(F("[l] Query GSMLOC (GPRS)")); + Serial.println(F("[w] Read webpage (GPRS)")); + Serial.println(F("[W] Post to website (GPRS)")); + + // GPS + if ((type == FONA3G_A) || (type == FONA3G_E) || (type == FONA808_V1) || (type == FONA808_V2)) { + Serial.println(F("[O] Turn GPS on (FONA 808 & 3G)")); + Serial.println(F("[o] Turn GPS off (FONA 808 & 3G)")); + Serial.println(F("[L] Query GPS location (FONA 808 & 3G)")); + if (type == FONA808_V1) { + Serial.println(F("[x] GPS fix status (FONA808 v1 only)")); + } + Serial.println(F("[E] Raw NMEA out (FONA808)")); + } + + Serial.println(F("[S] create Serial passthru tunnel")); + Serial.println(F("-------------------------------------")); + Serial.println(F("")); + +} +void loop() { + Serial.print(F("FONA> ")); + while (! Serial.available() ) { + if (fona.available()) { + Serial.write(fona.read()); + } + } + + char command = Serial.read(); + Serial.println(command); + + + switch (command) { + case '?': { + printMenu(); + break; + } + + case 'a': { + // read the ADC + uint16_t adc; + if (! fona.getADCVoltage(&adc)) { + Serial.println(F("Failed to read ADC")); + } else { + Serial.print(F("ADC = ")); Serial.print(adc); Serial.println(F(" mV")); + } + break; + } + + case 'b': { + // read the battery voltage and percentage + uint16_t vbat; + if (! fona.getBattVoltage(&vbat)) { + Serial.println(F("Failed to read Batt")); + } else { + Serial.print(F("VBat = ")); Serial.print(vbat); Serial.println(F(" mV")); + } + + + if (! fona.getBattPercent(&vbat)) { + Serial.println(F("Failed to read Batt")); + } else { + Serial.print(F("VPct = ")); Serial.print(vbat); Serial.println(F("%")); + } + + break; + } + + case 'U': { + // Unlock the SIM with a PIN code + char PIN[5]; + flushSerial(); + Serial.println(F("Enter 4-digit PIN")); + readline(PIN, 3); + Serial.println(PIN); + Serial.print(F("Unlocking SIM card: ")); + if (! fona.unlockSIM(PIN)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + + case 'C': { + // read the CCID + fona.getSIMCCID(replybuffer); // make sure replybuffer is at least 21 bytes! + Serial.print(F("SIM CCID = ")); Serial.println(replybuffer); + break; + } + + case 'i': { + // read the RSSI + uint8_t n = fona.getRSSI(); + int8_t r; + + Serial.print(F("RSSI = ")); Serial.print(n); Serial.print(": "); + if (n == 0) r = -115; + if (n == 1) r = -111; + if (n == 31) r = -52; + if ((n >= 2) && (n <= 30)) { + r = map(n, 2, 30, -110, -54); + } + Serial.print(r); Serial.println(F(" dBm")); + + break; + } + + case 'n': { + // read the network/cellular status + uint8_t n = fona.getNetworkStatus(); + Serial.print(F("Network status ")); + Serial.print(n); + Serial.print(F(": ")); + if (n == 0) Serial.println(F("Not registered")); + if (n == 1) Serial.println(F("Registered (home)")); + if (n == 2) Serial.println(F("Not registered (searching)")); + if (n == 3) Serial.println(F("Denied")); + if (n == 4) Serial.println(F("Unknown")); + if (n == 5) Serial.println(F("Registered roaming")); + break; + } + + /*** Audio ***/ + case 'v': { + // set volume + flushSerial(); + if ( (type == FONA3G_A) || (type == FONA3G_E) ) { + Serial.print(F("Set Vol [0-8] ")); + } else { + Serial.print(F("Set Vol % [0-100] ")); + } + uint8_t vol = readnumber(); + Serial.println(); + if (! fona.setVolume(vol)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + + case 'V': { + uint8_t v = fona.getVolume(); + Serial.print(v); + if ( (type == FONA3G_A) || (type == FONA3G_E) ) { + Serial.println(" / 8"); + } else { + Serial.println("%"); + } + break; + } + + case 'H': { + // Set Headphone output + if (! fona.setAudio(FONA_HEADSETAUDIO)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + fona.setMicVolume(FONA_HEADSETAUDIO, 15); + break; + } + case 'e': { + // Set External output + if (! fona.setAudio(FONA_EXTAUDIO)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + + fona.setMicVolume(FONA_EXTAUDIO, 10); + break; + } + + case 'T': { + // play tone + flushSerial(); + Serial.print(F("Play tone #")); + uint8_t kittone = readnumber(); + Serial.println(); + // play for 1 second (1000 ms) + if (! fona.playToolkitTone(kittone, 1000)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + + /*** FM Radio ***/ + + case 'f': { + // get freq + flushSerial(); + Serial.print(F("FM Freq (eg 1011 == 101.1 MHz): ")); + uint16_t station = readnumber(); + Serial.println(); + // FM radio ON using headset + if (fona.FMradio(true, FONA_HEADSETAUDIO)) { + Serial.println(F("Opened")); + } + if (! fona.tuneFMradio(station)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("Tuned")); + } + break; + } + case 'F': { + // FM radio off + if (! fona.FMradio(false)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + case 'm': { + // Set FM volume. + flushSerial(); + Serial.print(F("Set FM Vol [0-6]:")); + uint8_t vol = readnumber(); + Serial.println(); + if (!fona.setFMVolume(vol)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + case 'M': { + // Get FM volume. + uint8_t fmvol = fona.getFMVolume(); + if (fmvol < 0) { + Serial.println(F("Failed")); + } else { + Serial.print(F("FM volume: ")); + Serial.println(fmvol, DEC); + } + break; + } + case 'q': { + // Get FM station signal level (in decibels). + flushSerial(); + Serial.print(F("FM Freq (eg 1011 == 101.1 MHz): ")); + uint16_t station = readnumber(); + Serial.println(); + int8_t level = fona.getFMSignalLevel(station); + if (level < 0) { + Serial.println(F("Failed! Make sure FM radio is on (tuned to station).")); + } else { + Serial.print(F("Signal level (dB): ")); + Serial.println(level, DEC); + } + break; + } + + /*** PWM ***/ + + case 'P': { + // PWM Buzzer output @ 2KHz max + flushSerial(); + Serial.print(F("PWM Freq, 0 = Off, (1-2000): ")); + uint16_t freq = readnumber(); + Serial.println(); + if (! fona.setPWM(freq)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + + /*** Call ***/ + case 'c': { + // call a phone! + char number[30]; + flushSerial(); + Serial.print(F("Call #")); + readline(number, 30); + Serial.println(); + Serial.print(F("Calling ")); Serial.println(number); + if (!fona.callPhone(number)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("Sent!")); + } + + break; + } + case 'A': { + // get call status + int8_t callstat = fona.getCallStatus(); + switch (callstat) { + case 0: Serial.println(F("Ready")); break; + case 1: Serial.println(F("Could not get status")); break; + case 3: Serial.println(F("Ringing (incoming)")); break; + case 4: Serial.println(F("Ringing/in progress (outgoing)")); break; + default: Serial.println(F("Unknown")); break; + } + break; + } + + case 'h': { + // hang up! + if (! fona.hangUp()) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + + case 'p': { + // pick up! + if (! fona.pickUp()) { + Serial.println(F("Failed")); + } else { + Serial.println(F("OK!")); + } + break; + } + + /*** SMS ***/ + + case 'N': { + // read the number of SMS's! + int8_t smsnum = fona.getNumSMS(); + if (smsnum < 0) { + Serial.println(F("Could not read # SMS")); + } else { + Serial.print(smsnum); + Serial.println(F(" SMS's on SIM card!")); + } + break; + } + case 'r': { + // read an SMS + flushSerial(); + Serial.print(F("Read #")); + uint8_t smsn = readnumber(); + Serial.print(F("\n\rReading SMS #")); Serial.println(smsn); + + // Retrieve SMS sender address/phone number. + if (! fona.getSMSSender(smsn, replybuffer, 250)) { + Serial.println("Failed!"); + break; + } + Serial.print(F("FROM: ")); Serial.println(replybuffer); + + // Retrieve SMS value. + uint16_t smslen; + if (! fona.readSMS(smsn, replybuffer, 250, &smslen)) { // pass in buffer and max len! + Serial.println("Failed!"); + break; + } + Serial.print(F("***** SMS #")); Serial.print(smsn); + Serial.print(" ("); Serial.print(smslen); Serial.println(F(") bytes *****")); + Serial.println(replybuffer); + Serial.println(F("*****")); + + break; + } + case 'R': { + // read all SMS + int8_t smsnum = fona.getNumSMS(); + uint16_t smslen; + int8_t smsn; + + if ( (type == FONA3G_A) || (type == FONA3G_E) ) { + smsn = 0; // zero indexed + smsnum--; + } else { + smsn = 1; // 1 indexed + } + + for ( ; smsn <= smsnum; smsn++) { + Serial.print(F("\n\rReading SMS #")); Serial.println(smsn); + if (!fona.readSMS(smsn, replybuffer, 250, &smslen)) { // pass in buffer and max len! + Serial.println(F("Failed!")); + break; + } + // if the length is zero, its a special case where the index number is higher + // so increase the max we'll look at! + if (smslen == 0) { + Serial.println(F("[empty slot]")); + smsnum++; + continue; + } + + Serial.print(F("***** SMS #")); Serial.print(smsn); + Serial.print(" ("); Serial.print(smslen); Serial.println(F(") bytes *****")); + Serial.println(replybuffer); + Serial.println(F("*****")); + } + break; + } + + case 'd': { + // delete an SMS + flushSerial(); + Serial.print(F("Delete #")); + uint8_t smsn = readnumber(); + + Serial.print(F("\n\rDeleting SMS #")); Serial.println(smsn); + if (fona.deleteSMS(smsn)) { + Serial.println(F("OK!")); + } else { + Serial.println(F("Couldn't delete")); + } + break; + } + + case 's': { + // send an SMS! + char sendto[21], message[141]; + flushSerial(); + Serial.print(F("Send to #")); + readline(sendto, 20); + Serial.println(sendto); + Serial.print(F("Type out one-line message (140 char): ")); + readline(message, 140); + Serial.println(message); + if (!fona.sendSMS(sendto, message)) { + Serial.println(F("Failed")); + } else { + Serial.println(F("Sent!")); + } + + break; + } + + case 'u': { + // send a USSD! + char message[141]; + flushSerial(); + Serial.print(F("Type out one-line message (140 char): ")); + readline(message, 140); + Serial.println(message); + + uint16_t ussdlen; + if (!fona.sendUSSD(message, replybuffer, 250, &ussdlen)) { // pass in buffer and max len! + Serial.println(F("Failed")); + } else { + Serial.println(F("Sent!")); + Serial.print(F("***** USSD Reply")); + Serial.print(" ("); Serial.print(ussdlen); Serial.println(F(") bytes *****")); + Serial.println(replybuffer); + Serial.println(F("*****")); + } + } + + /*** Time ***/ + + case 'y': { + // enable network time sync + if (!fona.enableNetworkTimeSync(true)) + Serial.println(F("Failed to enable")); + break; + } + + case 'Y': { + // enable NTP time sync + if (!fona.enableNTPTimeSync(true, F("pool.ntp.org"))) + Serial.println(F("Failed to enable")); + break; + } + + case 't': { + // read the time + char buffer[23]; + + fona.getTime(buffer, 23); // make sure replybuffer is at least 23 bytes! + Serial.print(F("Time = ")); Serial.println(buffer); + break; + } + + + /*********************************** GPS (SIM808 only) */ + + case 'o': { + // turn GPS off + if (!fona.enableGPS(false)) + Serial.println(F("Failed to turn off")); + break; + } + case 'O': { + // turn GPS on + if (!fona.enableGPS(true)) + Serial.println(F("Failed to turn on")); + break; + } + case 'x': { + int8_t stat; + // check GPS fix + stat = fona.GPSstatus(); + if (stat < 0) + Serial.println(F("Failed to query")); + if (stat == 0) Serial.println(F("GPS off")); + if (stat == 1) Serial.println(F("No fix")); + if (stat == 2) Serial.println(F("2D fix")); + if (stat == 3) Serial.println(F("3D fix")); + break; + } + + case 'L': { + // check for GPS location + char gpsdata[120]; + fona.getGPS(0, gpsdata, 120); + if (type == FONA808_V1) + Serial.println(F("Reply in format: mode,longitude,latitude,altitude,utctime(yyyymmddHHMMSS),ttff,satellites,speed,course")); + else + Serial.println(F("Reply in format: mode,fixstatus,utctime(yyyymmddHHMMSS),latitude,longitude,altitude,speed,course,fixmode,reserved1,HDOP,PDOP,VDOP,reserved2,view_satellites,used_satellites,reserved3,C/N0max,HPA,VPA")); + Serial.println(gpsdata); + + break; + } + + case 'E': { + flushSerial(); + if (type == FONA808_V1) { + Serial.print(F("GPS NMEA output sentences (0 = off, 34 = RMC+GGA, 255 = all)")); + } else { + Serial.print(F("On (1) or Off (0)? ")); + } + uint8_t nmeaout = readnumber(); + + // turn on NMEA output + fona.enableGPSNMEA(nmeaout); + + break; + } + + /*********************************** GPRS */ + + case 'g': { + // turn GPRS off + if (!fona.enableGPRS(false)) + Serial.println(F("Failed to turn off")); + break; + } + case 'G': { + // turn GPRS on + if (!fona.enableGPRS(true)) + Serial.println(F("Failed to turn on")); + break; + } + case 'l': { + // check for GSMLOC (requires GPRS) + uint16_t returncode; + + if (!fona.getGSMLoc(&returncode, replybuffer, 250)) + Serial.println(F("Failed!")); + if (returncode == 0) { + Serial.println(replybuffer); + } else { + Serial.print(F("Fail code #")); Serial.println(returncode); + } + + break; + } + case 'w': { + // read website URL + uint16_t statuscode; + int16_t length; + char url[80]; + + flushSerial(); + Serial.println(F("NOTE: in beta! Use small webpages to read!")); + Serial.println(F("URL to read (e.g. www.adafruit.com/testwifi/index.html):")); + Serial.print(F("http://")); readline(url, 79); + Serial.println(url); + + Serial.println(F("****")); + if (!fona.HTTP_GET_start(url, &statuscode, (uint16_t *)&length)) { + Serial.println("Failed!"); + break; + } + while (length > 0) { + while (fona.available()) { + char c = fona.read(); + + // Serial.write is too slow, we'll write directly to Serial register! +#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) + loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data register empty. */ + UDR0 = c; +#else + Serial.write(c); +#endif + length--; + if (! length) break; + } + } + Serial.println(F("\n****")); + fona.HTTP_GET_end(); + break; + } + + case 'W': { + // Post data to website + uint16_t statuscode; + int16_t length; + char url[80]; + char data[80]; + + flushSerial(); + Serial.println(F("NOTE: in beta! Use simple websites to post!")); + Serial.println(F("URL to post (e.g. httpbin.org/post):")); + Serial.print(F("http://")); readline(url, 79); + Serial.println(url); + Serial.println(F("Data to post (e.g. \"foo\" or \"{\"simple\":\"json\"}\"):")); + readline(data, 79); + Serial.println(data); + + Serial.println(F("****")); + if (!fona.HTTP_POST_start(url, F("text/plain"), (uint8_t *) data, strlen(data), &statuscode, (uint16_t *)&length)) { + Serial.println("Failed!"); + break; + } + while (length > 0) { + while (fona.available()) { + char c = fona.read(); + +#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) + loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data register empty. */ + UDR0 = c; +#else + Serial.write(c); +#endif + + length--; + if (! length) break; + } + } + Serial.println(F("\n****")); + fona.HTTP_POST_end(); + break; + } + /*****************************************/ + + case 'S': { + Serial.println(F("Creating SERIAL TUBE")); + while (1) { + while (Serial.available()) { + delay(1); + fona.write(Serial.read()); + } + if (fona.available()) { + Serial.write(fona.read()); + } + } + break; + } + + default: { + Serial.println(F("Unknown command")); + printMenu(); + break; + } + } + // flush input + flushSerial(); + while (fona.available()) { + Serial.write(fona.read()); + } + +} + +void flushSerial() { + while (Serial.available()) + Serial.read(); +} + +char readBlocking() { + while (!Serial.available()); + return Serial.read(); +} +uint16_t readnumber() { + uint16_t x = 0; + char c; + while (! isdigit(c = readBlocking())) { + //Serial.print(c); + } + Serial.print(c); + x = c - '0'; + while (isdigit(c = readBlocking())) { + Serial.print(c); + x *= 10; + x += c - '0'; + } + return x; +} + +uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout) { + uint16_t buffidx = 0; + boolean timeoutvalid = true; + if (timeout == 0) timeoutvalid = false; + + while (true) { + if (buffidx > maxbuff) { + //Serial.println(F("SPACE")); + break; + } + + while (Serial.available()) { + char c = Serial.read(); + + //Serial.print(c, HEX); Serial.print("#"); Serial.println(c); + + if (c == '\r') continue; + if (c == 0xA) { + if (buffidx == 0) // the first 0x0A is ignored + continue; + + timeout = 0; // the second 0x0A is the end of the line + timeoutvalid = true; + break; + } + buff[buffidx] = c; + buffidx++; + } + + if (timeoutvalid && timeout == 0) { + //Serial.println(F("TIMEOUT")); + break; + } + delay(1); + } + buff[buffidx] = 0; // null term + return buffidx; +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/GPS/.esp8266.test.skip b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/GPS/.esp8266.test.skip new file mode 100644 index 0000000..e69de29 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino new file mode 100644 index 0000000..cce63d5 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino @@ -0,0 +1,112 @@ +/** + * ___ ___ _ _ _ ___ __ ___ ___ ___ ___ + * | __/ _ \| \| | /_\ ( _ )/ \( _ ) / __| _ \/ __| + * | _| (_) | .` |/ _ \ / _ \ () / _ \ | (_ | _/\__ \ + * |_| \___/|_|\_/_/ \_\ \___/\__/\___/ \___|_| |___/ + * + * This example is meant to work with the Adafruit + * FONA 808 or 3G Shield or Breakout + * + * Copyright: 2015 Adafruit + * Author: Todd Treece + * Licence: MIT + * + */ +#include "Adafruit_FONA.h" + +// standard pins for the shield, adjust as necessary +#define FONA_RX 2 +#define FONA_TX 3 +#define FONA_RST 4 + +// We default to using software serial. If you want to use hardware serial +// (because softserial isnt supported) comment out the following three lines +// and uncomment the HardwareSerial line +#include +SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); +SoftwareSerial *fonaSerial = &fonaSS; + +// Hardware serial is also possible! +// HardwareSerial *fonaSerial = &Serial1; + +Adafruit_FONA fona = Adafruit_FONA(FONA_RST); + +// Have a FONA 3G? use this object type instead +//Adafruit_FONA_3G fona = Adafruit_FONA_3G(FONA_RST); + + +void setup() { + + while (! Serial); + + Serial.begin(115200); + Serial.println(F("Adafruit FONA 808 & 3G GPS demo")); + Serial.println(F("Initializing FONA... (May take a few seconds)")); + + fonaSerial->begin(4800); + if (! fona.begin(*fonaSerial)) { + Serial.println(F("Couldn't find FONA")); + while(1); + } + Serial.println(F("FONA is OK")); + // Try to enable GPRS + + + Serial.println(F("Enabling GPS...")); + fona.enableGPS(true); +} + +void loop() { + delay(2000); + + float latitude, longitude, speed_kph, heading, speed_mph, altitude; + + // if you ask for an altitude reading, getGPS will return false if there isn't a 3D fix + boolean gps_success = fona.getGPS(&latitude, &longitude, &speed_kph, &heading, &altitude); + + if (gps_success) { + + Serial.print("GPS lat:"); + Serial.println(latitude, 6); + Serial.print("GPS long:"); + Serial.println(longitude, 6); + Serial.print("GPS speed KPH:"); + Serial.println(speed_kph); + Serial.print("GPS speed MPH:"); + speed_mph = speed_kph * 0.621371192; + Serial.println(speed_mph); + Serial.print("GPS heading:"); + Serial.println(heading); + Serial.print("GPS altitude:"); + Serial.println(altitude); + + } else { + Serial.println("Waiting for FONA GPS 3D fix..."); + } + + // Fona 3G doesnt have GPRSlocation :/ + if ((fona.type() == FONA3G_A) || (fona.type() == FONA3G_E)) + return; + // Check for network, then GPRS + Serial.println(F("Checking for Cell network...")); + if (fona.getNetworkStatus() == 1) { + // network & GPRS? Great! Print out the GSM location to compare + boolean gsmloc_success = fona.getGSMLoc(&latitude, &longitude); + + if (gsmloc_success) { + Serial.print("GSMLoc lat:"); + Serial.println(latitude, 6); + Serial.print("GSMLoc long:"); + Serial.println(longitude, 6); + } else { + Serial.println("GSM location failed..."); + Serial.println(F("Disabling GPRS")); + fona.enableGPRS(false); + Serial.println(F("Enabling GPRS")); + if (!fona.enableGPRS(true)) { + Serial.println(F("Failed to turn GPRS on")); + } + } + } +} + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/.esp8266.test.skip b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/.esp8266.test.skip new file mode 100644 index 0000000..e69de29 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino new file mode 100644 index 0000000..8dba308 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino @@ -0,0 +1,62 @@ +// FONA Incoming Call Number Example +// Listens for a call and displays the phone number of the caller (if available). +// Use this example to add phone call detection to your own FONA sketch. +#include "Adafruit_FONA.h" + +// Pins which are connected to the FONA. +// Note that this is different from FONAtest! +#define FONA_RX 3 +#define FONA_TX 4 +#define FONA_RST 5 + +// Note you need to map interrupt number to pin number +// for your board. On an Uno & Mega interrupt 0 is +// digital pin 2, and on a Leonardo interrupt 0 is +// digital pin 3. See this page for a complete table: +// http://arduino.cc/en/Reference/attachInterrupt +// Make sure this interrupt pin is connected to FONA RI! +#define FONA_RI_INTERRUPT 0 + +// We default to using software serial. If you want to use hardware serial +// (because softserial isnt supported) comment out the following three lines +// and uncomment the HardwareSerial line +#include +SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); +SoftwareSerial *fonaSerial = &fonaSS; + +// Hardware serial is also possible! +// HardwareSerial *fonaSerial = &Serial1; + +Adafruit_FONA fona = Adafruit_FONA(FONA_RST); + +void setup() { + Serial.begin(115200); + Serial.println(F("FONA incoming call example")); + Serial.println(F("Initializing....(May take 3 seconds)")); + + fonaSerial->begin(4800); + if (! fona.begin(*fonaSerial)) { + Serial.println(F("Couldn't find FONA")); + while(1); + } + Serial.println(F("FONA is OK")); + + // Enable incoming call notification. + if(fona.callerIdNotification(true, FONA_RI_INTERRUPT)) { + Serial.println(F("Caller id notification enabled.")); + } + else { + Serial.println(F("Caller id notification disabled")); + } +} + +void loop(){ + // Create a small string buffer to hold incoming call number. + char phone[32] = {0}; + // Check for an incoming call. Will return true if a call is incoming. + if(fona.incomingCallNumber(phone)){ + Serial.println(F("RING!")); + Serial.print(F("Phone Number: ")); + Serial.println(phone); + } +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/FONAConfig.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/FONAConfig.h new file mode 100644 index 0000000..5fa3e13 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/FONAConfig.h @@ -0,0 +1,34 @@ +/* + * FONAConfig.h -- compile-time configuration + * This is part of the library for the Adafruit FONA Cellular Module + * + * Designed specifically to work with the Adafruit FONA + * ----> https://www.adafruit.com/products/1946 + * ----> https://www.adafruit.com/products/1963 + * ----> http://www.adafruit.com/products/2468 + * ----> http://www.adafruit.com/products/2542 + * + * Adafruit invests time and resources providing this open source code, + * please support Adafruit and open-source hardware by purchasing + * products from Adafruit! + * + * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in + * the Adafruit_FONA_Library and released under the + * BSD license, all text above must be included in any redistribution. + * + * Created on: Jan 16, 2016 + * Author: Pat Deegan + */ + +#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONACONFIG_H_ +#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONACONFIG_H_ + +/* ADAFRUIT_FONA_DEBUG + * When defined, will cause extensive debug output on the + * DebugStream set in the appropriate platform/ header. + */ + +#define ADAFRUIT_FONA_DEBUG + + +#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONACONFIG_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h new file mode 100644 index 0000000..f8fe878 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h @@ -0,0 +1,33 @@ +/* + * FONAExtIncludes.h -- system-wide includes + * This is part of the library for the Adafruit FONA Cellular Module + * + * Designed specifically to work with the Adafruit FONA + * ----> https://www.adafruit.com/products/1946 + * ----> https://www.adafruit.com/products/1963 + * ----> http://www.adafruit.com/products/2468 + * ----> http://www.adafruit.com/products/2542 + * + * Adafruit invests time and resources providing this open source code, + * please support Adafruit and open-source hardware by purchasing + * products from Adafruit! + * + * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in + * the Adafruit_FONA_Library and released under the + * BSD license, all text above must be included in any redistribution. + * + * Created on: Jan 16, 2016 + * Author: Pat Deegan + */ + + +#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONAEXTINCLUDES_H_ +#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONAEXTINCLUDES_H_ + + +#include "FONAConfig.h" +// include any system-wide includes required here + + + +#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONAEXTINCLUDES_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h new file mode 100644 index 0000000..85bc8fe --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h @@ -0,0 +1,67 @@ +/* + * FONAPlatStd.h -- standard AVR/Arduino platform. + * + * This is part of the library for the Adafruit FONA Cellular Module + * + * Designed specifically to work with the Adafruit FONA + * ----> https://www.adafruit.com/products/1946 + * ----> https://www.adafruit.com/products/1963 + * ----> http://www.adafruit.com/products/2468 + * ----> http://www.adafruit.com/products/2542 + * + * Adafruit invests time and resources providing this open source code, + * please support Adafruit and open-source hardware by purchasing + * products from Adafruit! + * + * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in + * the Adafruit_FONA_Library and released under the + * BSD license, all text above must be included in any redistribution. + * + * Created on: Jan 16, 2016 + * Author: Pat Deegan + */ + + +#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATSTD_H_ +#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATSTD_H_ + +#include "../FONAConfig.h" + + +#if (ARDUINO >= 100) + #include "Arduino.h" + #if !defined(__SAM3X8E__) && !defined(ARDUINO_ARCH_SAMD) // Arduino Due doesn't support #include + #endif +#else + #include "WProgram.h" + #include +#endif + +#include + + +// DebugStream sets the Stream output to use +// for debug (only applies when ADAFRUIT_FONA_DEBUG +// is defined in config) +#define DebugStream Serial + +#ifdef ADAFRUIT_FONA_DEBUG +// need to do some debugging... +#define DEBUG_PRINT(...) DebugStream.print(__VA_ARGS__) +#define DEBUG_PRINTLN(...) DebugStream.println(__VA_ARGS__) +#endif + +// a few typedefs to keep things portable +typedef Stream FONAStreamType; +typedef const __FlashStringHelper * FONAFlashStringPtr; + +#define prog_char char PROGMEM + +#define prog_char_strcmp(a, b) strcmp_P((a), (b)) +// define prog_char_strncmp(a, b, c) strncmp_P((a), (b), (c)) +#define prog_char_strstr(a, b) strstr_P((a), (b)) +#define prog_char_strlen(a) strlen_P((a)) +#define prog_char_strcpy(to, fromprogmem) strcpy_P((to), (fromprogmem)) +//define prog_char_strncpy(to, from, len) strncpy_P((to), (fromprogmem), (len)) + +#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATSTD_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h new file mode 100644 index 0000000..0bf98d0 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h @@ -0,0 +1,62 @@ +/* + * FONAPlatform.h -- platform definitions includes. + * + * This is part of the library for the Adafruit FONA Cellular Module + * + * Designed specifically to work with the Adafruit FONA + * ----> https://www.adafruit.com/products/1946 + * ----> https://www.adafruit.com/products/1963 + * ----> http://www.adafruit.com/products/2468 + * ----> http://www.adafruit.com/products/2542 + * + * Adafruit invests time and resources providing this open source code, + * please support Adafruit and open-source hardware by purchasing + * products from Adafruit! + * + * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in + * the Adafruit_FONA_Library and released under the + * BSD license, all text above must be included in any redistribution. + * + * Created on: Jan 16, 2016 + * Author: Pat Deegan + */ + + +#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATFORM_H_ +#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATFORM_H_ + +#include "../FONAConfig.h" + +// only "standard" config supported in this release -- namely AVR-based arduino type affairs +#include "FONAPlatStd.h" + + + +#ifndef DEBUG_PRINT +// debug is disabled + +#define DEBUG_PRINT(...) +#define DEBUG_PRINTLN(...) + +#endif + + +#ifndef prog_char_strcmp +#define prog_char_strcmp(a, b) strcmp((a), (b)) +#endif + +#ifndef prog_char_strstr +#define prog_char_strstr(a, b) strstr((a), (b)) +#endif + +#ifndef prog_char_strlen +#define prog_char_strlen(a) strlen((a)) +#endif + + +#ifndef prog_char_strcpy +#define prog_char_strcpy(to, fromprogmem) strcpy((to), (fromprogmem)) +#endif + + +#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATFORM_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/library.properties b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/library.properties new file mode 100644 index 0000000..bb7099c --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/library.properties @@ -0,0 +1,9 @@ +name=Adafruit FONA Library +version=1.3.2 +author=Adafruit +maintainer=Adafruit +sentence=Arduino library for the Adafruit FONA +paragraph=Arduino library for the Adafruit FONA +category=Communication +url=https://github.com/adafruit/Adafruit_FONA_Library +architectures=* diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp new file mode 100644 index 0000000..9448278 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp @@ -0,0 +1,4 @@ +#include "Adafruit_SleepyDog.h" + +// Global instance of the main class for sketches to use. +WatchdogType Watchdog; diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h new file mode 100644 index 0000000..4cdf4b4 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h @@ -0,0 +1,28 @@ +#ifndef ADAFRUIT_SLEEPYDOG_H +#define ADAFRUIT_SLEEPYDOG_H + +// Platform-specific code goes below. Each #ifdef should check for the presence +// of their platform and pull in the appropriate watchdog implementation type, +// then typedef it to WatchdogType so the .cpp file can create a global instance. +#if defined(ARDUINO_ARCH_AVR) || defined(__AVR__) + #include "utility/WatchdogAVR.h" + typedef WatchdogAVR WatchdogType; +#elif defined(ARDUINO_ARCH_SAMD) + // Arduino Zero / ATSAMD series CPU watchdog support. + #include "utility/WatchdogSAMD.h" + typedef WatchdogSAMD WatchdogType; +#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) + // Teensy 3.x watchdog support. + #include "utility/WatchdogKinetisK.h" + typedef WatchdogKinetisKseries WatchdogType; +#elif defined(__MKL26Z64__) + // Teensy LC watchdog support. + #include "utility/WatchdogKinetisL.h" + typedef WatchdogKinetisLseries WatchdogType; +#else + #error Unsupported platform for the Adafruit Watchdog library! +#endif + +extern WatchdogType Watchdog; + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/LICENSE b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/LICENSE new file mode 100644 index 0000000..04ebb92 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Adafruit Industries + +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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/README.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/README.md new file mode 100644 index 0000000..3aa268a --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/README.md @@ -0,0 +1,6 @@ +# Adafruit SleepyDog Arduino Library + +Arduino library to use the watchdog timer for system reset and low power sleep. + +Currently supports the following hardware: +* Arduino Uno or compatible (ATmega328P). diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino new file mode 100644 index 0000000..8d47041 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino @@ -0,0 +1,62 @@ +// Adafruit Watchdog Library Basic Usage Example +// +// Simple example of how to use the watchdog library. +// +// Author: Tony DiCola + +#include + +void setup() { + Serial.begin(115200); + while (!Serial) ; // wait for Arduino Serial Monitor (native USB boards) + Serial.println("Adafruit Watchdog Library Demo!"); + Serial.println(); + + // First a normal example of using the watchdog timer. + // Enable the watchdog by calling Watchdog.enable() as below. This will turn + // on the watchdog timer with a ~4 second timeout before reseting the Arduino. + // The estimated actual milliseconds before reset (in milliseconds) is returned. + // Make sure to reset the watchdog before the countdown expires or the Arduino + // will reset! + int countdownMS = Watchdog.enable(4000); + Serial.print("Enabled the watchdog with max countdown of "); + Serial.print(countdownMS, DEC); + Serial.println(" milliseconds!"); + Serial.println(); + + // Now loop a few times and periodically reset the watchdog. + Serial.println("Looping ten times while resetting the watchdog..."); + for (int i = 1; i <= 10; ++i) { + Serial.print("Loop #"); Serial.println(i, DEC); + delay(1000); + // Reset the watchdog with every loop to make sure the sketch keeps running. + // If you comment out this call watch what happens after about 4 iterations! + Watchdog.reset(); + } + Serial.println(); + + // Disable the watchdog entirely by calling Watchdog.disable(); + Watchdog.disable(); + + // Finally demonstrate the watchdog resetting by enabling it for a shorter + // period of time and waiting a long time without a reset. Notice you can pass + // a _maximum_ countdown time (in milliseconds) to the enable call. The library + // will try to use that value as the countdown, but it might pick a smaller + // value if the hardware doesn't support it. The actual countdown value will + // be returned so you can see what it is. + countdownMS = Watchdog.enable(4000); + Serial.print("Get ready, the watchdog will reset in "); + Serial.print(countdownMS, DEC); + Serial.println(" milliseconds!"); + Serial.println(); + delay(countdownMS+1000); + + // Execution will never get here because the watchdog resets the Arduino! +} + +void loop() { + // We'll never actually get to the loop because the watchdog will reset in + // the setup function. + Serial.println("You shouldn't see this message."); + delay(1000); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino new file mode 100644 index 0000000..d8eab80 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino @@ -0,0 +1,37 @@ +// Adafruit Watchdog Library Sleep Example +// +// Simple example of how to do low power sleep with the watchdog timer. +// +// Author: Tony DiCola + +#include + +void setup() { + Serial.begin(115200); + while (!Serial) ; // wait for Arduino Serial Monitor (native USB boards) + Serial.println("Adafruit Watchdog Library Sleep Demo!"); + Serial.println(); +} + +void loop() { + Serial.println("Going to sleep in one second..."); + delay(1000); + + // To enter low power sleep mode call Watchdog.sleep() like below + // and the watchdog will allow low power sleep for as long as possible. + // The actual amount of time spent in sleep will be returned (in + // milliseconds). + int sleepMS = Watchdog.sleep(); + + // Alternatively you can provide a millisecond value to specify + // how long you'd like the chip to sleep, but the hardware only + // supports a limited range of values so the actual sleep time might + // be smaller. The time spent in sleep will be returned (in + // milliseconds). + // int sleepMS = Watchdog.sleep(1000); // Sleep for up to 1 second. + + Serial.print("I'm awake now! I slept for "); + Serial.print(sleepMS, DEC); + Serial.println(" milliseconds."); + Serial.println(); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/library.properties b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/library.properties new file mode 100644 index 0000000..c41d74b --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/library.properties @@ -0,0 +1,9 @@ +name=Adafruit SleepyDog Library +version=1.1.1 +author=Adafruit +maintainer=Adafruit +sentence=Arduino library to use the watchdog timer for system reset and low power sleep. +paragraph=Arduino library to use the watchdog timer for system reset and low power sleep. +category=Other +url=https://github.com/adafruit/Adafruit_SleepyDog +architectures=* diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp new file mode 100644 index 0000000..3355c13 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp @@ -0,0 +1,137 @@ +// Be careful to use a platform-specific conditional include to only make the +// code visible for the appropriate platform. Arduino will try to compile and +// link all .cpp files regardless of platform. +#if defined(ARDUINO_ARCH_AVR) || defined(__AVR__) + +#include +#include +#include +#include + +#include "WatchdogAVR.h" + +// Define watchdog timer interrupt. +ISR(WDT_vect) +{ + // Nothing needs to be done, however interrupt handler must be defined to + // prevent a reset. +} + +int WatchdogAVR::enable(int maxPeriodMS) { + // Pick the closest appropriate watchdog timer value. + int actualMS; + _setPeriod(maxPeriodMS, _wdto, actualMS); + // Enable the watchdog and return the actual countdown value. + wdt_enable(_wdto); + return actualMS; +} + +void WatchdogAVR::reset() { + // Reset the watchdog. + wdt_reset(); +} + +void WatchdogAVR::disable() { + // Disable the watchdog and clear any saved watchdog timer value. + wdt_disable(); + _wdto = -1; +} + +int WatchdogAVR::sleep(int maxPeriodMS) { + // Pick the closest appropriate watchdog timer value. + int sleepWDTO, actualMS; + _setPeriod(maxPeriodMS, sleepWDTO, actualMS); + + // Build watchdog prescaler register value before timing critical code. + uint8_t wdps = ((sleepWDTO & 0x08 ? 1 : 0) << WDP3) | + ((sleepWDTO & 0x04 ? 1 : 0) << WDP2) | + ((sleepWDTO & 0x02 ? 1 : 0) << WDP1) | + ((sleepWDTO & 0x01 ? 1 : 0) << WDP0); + + // The next section is timing critical so interrupts are disabled. + cli(); + // First clear any previous watchdog reset. + MCUSR &= ~(1<= 8000) || (maxMS == 0)) { + wdto = WDTO_8S; + actualMS = 8000; + } + else if (maxMS >= 4000) { + wdto = WDTO_4S; + actualMS = 4000; + } + else if (maxMS >= 2000) { + wdto = WDTO_2S; + actualMS = 2000; + } + else if (maxMS >= 1000) { + wdto = WDTO_1S; + actualMS = 1000; + } + else if (maxMS >= 500) { + wdto = WDTO_500MS; + actualMS = 500; + } + else if (maxMS >= 250) { + wdto = WDTO_250MS; + actualMS = 250; + } + else if (maxMS >= 120) { + wdto = WDTO_120MS; + actualMS = 120; + } + else if (maxMS >= 60) { + wdto = WDTO_60MS; + actualMS = 60; + } + else if (maxMS >= 30) { + wdto = WDTO_30MS; + actualMS = 30; + } + else { + wdto = WDTO_15MS; + actualMS = 15; + } +} + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h new file mode 100644 index 0000000..9753b08 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h @@ -0,0 +1,47 @@ +#ifndef WATCHDOGAVR_H +#define WATCHDOGAVR_H + +class WatchdogAVR { +public: + WatchdogAVR(): + _wdto(-1) + {} + + // Enable the watchdog timer to reset the machine after a period of time + // without any calls to reset(). The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware does + // not support the exact desired value. + // + // The actual period (in milliseconds) before a watchdog timer reset is + // returned. + int enable(int maxPeriodMS = 0); + + // Reset or 'kick' the watchdog timer to prevent a reset of the device. + void reset(); + + // Completely disable the watchdog timer. + void disable(); + + // Enter the lowest power sleep mode (using the watchdog timer) for the + // desired period of time. The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware does + // not support the exact desired value + // + // The actual period (in milliseconds) that the hardware was asleep will be + // returned. + int sleep(int maxPeriodMS = 0); + +private: + // Pick the closest (but not higher) watchdog timer value from the provided + // maximum period. Sets wdto to the chosen period value suitable for + // passing to wdt_enable(), and actualMS to the chosen period value in + // milliseconds. A max value of 0 will pick the longest value possible. + void _setPeriod(int maxMS, int &wdto, int &actualMS); + + // Keep the last selected watchdog timer period so that the watchdog can be + // re-enabled at that rate after sleep. A value of -1 means no watchdog + // timer was enabled. + int _wdto; +}; + +#endif \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp new file mode 100644 index 0000000..9705859 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp @@ -0,0 +1,104 @@ +// Be careful to use a platform-specific conditional include to only make the +// code visible for the appropriate platform. Arduino will try to compile and +// link all .cpp files regardless of platform. +#if defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) + +#include +#include "WatchdogKinetisK.h" + +static void one_bus_cycle(void) __attribute__((always_inline)); +static void watchdog_config(int cfg, int val); + +// Enable the watchdog timer to reset the machine after a period of time +// without any calls to reset(). The passed in period (in milliseconds) is +// just a suggestion and a lower value might be picked if the hardware does +// not support the exact desired value. +// +// The actual period (in milliseconds) before a watchdog timer reset is +// returned. +int WatchdogKinetisKseries::enable(int maxPeriodMS) +{ + if (maxPeriodMS < 4) { + maxPeriodMS = 8000; // default is 8 seconds + } + if (setting != maxPeriodMS) { + watchdog_config(WDOG_STCTRLH_WDOGEN, maxPeriodMS); + setting = maxPeriodMS; + } + return maxPeriodMS; +} + +// Reset or 'kick' the watchdog timer to prevent a reset of the device. +void WatchdogKinetisKseries::reset() +{ + __disable_irq(); + WDOG_REFRESH = 0xA602; + WDOG_REFRESH = 0xB480; + __enable_irq(); +} + +// Completely disable the watchdog timer. +void WatchdogKinetisKseries::disable() +{ + if (setting > 0) { + watchdog_config(0, 4); + setting = 0; + } +} + +// Enter the lowest power sleep mode for the desired period of time. The +// passed in period (in milliseconds) is just a suggestion and a lower value +// might be picked if the hardware does not support the exact desired value +// +// The actual period (in milliseconds) that the hardware was asleep will be +// returned. +int WatchdogKinetisKseries::sleep(int maxPeriodMS) +{ + if (maxPeriodMS <= 0) return 0; + // TODO.... + return 0; +} + +static void watchdog_config(int cfg, int val) +{ + __disable_irq(); + WDOG_UNLOCK = WDOG_UNLOCK_SEQ1; + WDOG_UNLOCK = WDOG_UNLOCK_SEQ2; + one_bus_cycle(); + WDOG_STCTRLH = cfg | WDOG_STCTRLH_ALLOWUPDATE; + WDOG_TOVALH = val >> 16; + WDOG_TOVALL = val; + WDOG_PRESC = 0; + __enable_irq(); + for (int i=0; i < 256; i++) { + one_bus_cycle(); + } +} + +static void one_bus_cycle(void) +{ + __asm__ volatile ("nop"); + #if (F_CPU / F_BUS) > 1 + __asm__ volatile ("nop"); + #endif + #if (F_CPU / F_BUS) > 2 + __asm__ volatile ("nop"); + #endif + #if (F_CPU / F_BUS) > 3 + __asm__ volatile ("nop"); + #endif + #if (F_CPU / F_BUS) > 4 + __asm__ volatile ("nop"); + #endif + #if (F_CPU / F_BUS) > 5 + __asm__ volatile ("nop"); + #endif + #if (F_CPU / F_BUS) > 6 + __asm__ volatile ("nop"); + #endif + #if (F_CPU / F_BUS) > 7 + __asm__ volatile ("nop"); + #endif +} + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h new file mode 100644 index 0000000..e09a0c2 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h @@ -0,0 +1,38 @@ +#ifndef WATCHDOGKINETISK_H +#define WATCHDOGKINETISK_H + +class WatchdogKinetisKseries { +public: + WatchdogKinetisKseries(): setting(0) {} + + // Enable the watchdog timer to reset the machine after a period of time + // without any calls to reset(). The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware does + // not support the exact desired value. + // + // The actual period (in milliseconds) before a watchdog timer reset is + // returned. + int enable(int maxPeriodMS = 0); + + // Reset or 'kick' the watchdog timer to prevent a reset of the device. + void reset(); + + // Completely disable the watchdog timer. + void disable(); + + // Enter the lowest power sleep mode (using the watchdog timer) for the + // desired period of time. The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware does + // not support the exact desired value + // + // The actual period (in milliseconds) that the hardware was asleep will be + // returned. + // + // NOTE: This is currently not implemented on the SAMD21! + int sleep(int maxPeriodMS = 0); + +private: + int setting; +}; + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp new file mode 100644 index 0000000..501e9c0 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp @@ -0,0 +1,74 @@ +// Be careful to use a platform-specific conditional include to only make the +// code visible for the appropriate platform. Arduino will try to compile and +// link all .cpp files regardless of platform. +#if defined(__MKL26Z64__) + +#include +#include "WatchdogKinetisL.h" + +// Normally the watchdog is disabled at startup. This removes the startup +// code. The watchdog will be active with 1024 ms timeout. Hopefully the +// user will configure the watchdog and begin resetting it before it causes +// a reboot. There is no way to start up without the watchdog and then +// enable it later... +extern "C" void startup_early_hook(void) {} + + +// Enable the watchdog timer to reset the machine after a period of time +// without any calls to reset(). The passed in period (in milliseconds) is +// just a suggestion and a lower value might be picked if the hardware does +// not support the exact desired value. +// +// The actual period (in milliseconds) before a watchdog timer reset is +// returned. +int WatchdogKinetisLseries::enable(int maxPeriodMS) +{ + // The watchdog can only be programmed once. Then it's forever + // locked to this setting (until the chip reboots). + if (maxPeriodMS <= 0 || maxPeriodMS > 256) { + SIM_COPC = 12; + } else if (maxPeriodMS > 32) { + SIM_COPC = 8; + } else { + SIM_COPC = 4; + } + // Read the actual setting. + int val = SIM_COPC & 12; + if (val == 12) return 1024; + if (val == 8) return 256; + return 32; +} + +// Reset or 'kick' the watchdog timer to prevent a reset of the device. +void WatchdogKinetisLseries::reset() +{ + __disable_irq(); + SIM_SRVCOP = 0x55; + SIM_SRVCOP = 0xAA; + __enable_irq(); +} + +// Completely disable the watchdog timer. +void WatchdogKinetisLseries::disable() +{ + // no can do.... + // The watchdog timer in this chip is write-once. + // The chip boots up with the watchdog at 1024 ms. + // You only get to configure it once. Then it + // remains locked to that setting, until a reboot. +} + +// Enter the lowest power sleep mode for the desired period of time. The +// passed in period (in milliseconds) is just a suggestion and a lower value +// might be picked if the hardware does not support the exact desired value +// +// The actual period (in milliseconds) that the hardware was asleep will be +// returned. +int WatchdogKinetisLseries::sleep(int maxPeriodMS) +{ + if (maxPeriodMS <= 0) return 0; + // TODO.... + return 0; +} + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h new file mode 100644 index 0000000..3c68d5e --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h @@ -0,0 +1,35 @@ +#ifndef WATCHDOGKINETISL_H +#define WATCHDOGKINETISL_H + +class WatchdogKinetisLseries { +public: + WatchdogKinetisLseries() {} + + // Enable the watchdog timer to reset the machine after a period of time + // without any calls to reset(). The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware does + // not support the exact desired value. + // + // The actual period (in milliseconds) before a watchdog timer reset is + // returned. + int enable(int maxPeriodMS = 0); + + // Reset or 'kick' the watchdog timer to prevent a reset of the device. + void reset(); + + // Completely disable the watchdog timer. + void disable(); + + // Enter the lowest power sleep mode (using the watchdog timer) for the + // desired period of time. The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware does + // not support the exact desired value + // + // The actual period (in milliseconds) that the hardware was asleep will be + // returned. + // + // NOTE: This is currently not implemented on the SAMD21! + int sleep(int maxPeriodMS = 0); +}; + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp new file mode 100644 index 0000000..d21d9a9 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp @@ -0,0 +1,175 @@ +// Requires Adafruit_ASFcore library! + +// Be careful to use a platform-specific conditional include to only make the +// code visible for the appropriate platform. Arduino will try to compile and +// link all .cpp files regardless of platform. +#if defined(ARDUINO_ARCH_SAMD) + +#include +#include +#include +#include "WatchdogSAMD.h" + +int WatchdogSAMD::enable(int maxPeriodMS, bool isForSleep) { + // Enable the watchdog with a period up to the specified max period in + // milliseconds. + + // Review the watchdog section from the SAMD21 datasheet section 17: + // http://www.atmel.com/images/atmel-42181-sam-d21_datasheet.pdf + + int cycles, actualMS; + uint8_t bits; + + if(!_initialized) _initialize_wdt(); + + WDT->CTRL.reg = 0; // Disable watchdog for config + while(WDT->STATUS.bit.SYNCBUSY); + + // You'll see some occasional conversion here compensating between + // milliseconds (1000 Hz) and WDT clock cycles (~1024 Hz). The low- + // power oscillator used by the WDT ostensibly runs at 32,768 Hz with + // a 1:32 prescale, thus 1024 Hz, though probably not super precise. + + if((maxPeriodMS >= 16000) || !maxPeriodMS) { + cycles = 16384; + bits = 0xB; + } else { + cycles = (maxPeriodMS * 1024L + 500) / 1000; // ms -> WDT cycles + if(cycles >= 8192) { + cycles = 8192; + bits = 0xA; + } else if(cycles >= 4096) { + cycles = 4096; + bits = 0x9; + } else if(cycles >= 2048) { + cycles = 2048; + bits = 0x8; + } else if(cycles >= 1024) { + cycles = 1024; + bits = 0x7; + } else if(cycles >= 512) { + cycles = 512; + bits = 0x6; + } else if(cycles >= 256) { + cycles = 256; + bits = 0x5; + } else if(cycles >= 128) { + cycles = 128; + bits = 0x4; + } else if(cycles >= 64) { + cycles = 64; + bits = 0x3; + } else if(cycles >= 32) { + cycles = 32; + bits = 0x2; + } else if(cycles >= 16) { + cycles = 16; + bits = 0x1; + } else { + cycles = 8; + bits = 0x0; + } + } + + // Watchdog timer on SAMD is a slightly different animal than on AVR. + // On AVR, the WTD timeout is configured in one register and then an + // interrupt can optionally be enabled to handle the timeout in code + // (as in waking from sleep) vs resetting the chip. Easy. + // On SAMD, when the WDT fires, that's it, the chip's getting reset. + // Instead, it has an "early warning interrupt" with a different set + // interval prior to the reset. For equivalent behavior to the AVR + // library, this requires a slightly different configuration depending + // whether we're coming from the sleep() function (which needs the + // interrupt), or just enable() (no interrupt, we want the chip reset + // unless the WDT is cleared first). In the sleep case, 'windowed' + // mode is used in order to allow access to the longest available + // sleep interval (about 16 sec); the WDT 'period' (when a reset + // occurs) follows this and is always just set to the max, since the + // interrupt will trigger first. In the enable case, windowed mode + // is not used, the WDT period is set and that's that. + // The 'isForSleep' argument determines which behavior is used; + // this isn't present in the AVR code, just here. It defaults to + // 'false' so existing Arduino code works as normal, while the sleep() + // function (later in this file) explicitly passes 'true' to get the + // alternate behavior. + + if(isForSleep) { + WDT->INTENSET.bit.EW = 1; // Enable early warning interrupt + WDT->CONFIG.bit.PER = 0xB; // Period = max + WDT->CONFIG.bit.WINDOW = bits; // Set time of interrupt + WDT->CTRL.bit.WEN = 1; // Enable window mode + while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write + } else { + WDT->INTENCLR.bit.EW = 1; // Disable early warning interrupt + WDT->CONFIG.bit.PER = bits; // Set period for chip reset + WDT->CTRL.bit.WEN = 0; // Disable window mode + while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write + } + + actualMS = (cycles * 1000L + 512) / 1024; // WDT cycles -> ms + + reset(); // Clear watchdog interval + WDT->CTRL.bit.ENABLE = 1; // Start watchdog now! + while(WDT->STATUS.bit.SYNCBUSY); + + return actualMS; +} + +void WatchdogSAMD::reset() { + // Write the watchdog clear key value (0xA5) to the watchdog + // clear register to clear the watchdog timer and reset it. + WDT->CLEAR.reg = WDT_CLEAR_CLEAR_KEY; + while(WDT->STATUS.bit.SYNCBUSY); +} + +void WatchdogSAMD::disable() { + WDT->CTRL.bit.ENABLE = 0; + while(WDT->STATUS.bit.SYNCBUSY); +} + +void WDT_Handler(void) { + // ISR for watchdog early warning, DO NOT RENAME! + WDT->CTRL.bit.ENABLE = 0; // Disable watchdog + while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write + WDT->INTFLAG.bit.EW = 1; // Clear interrupt flag +} + +int WatchdogSAMD::sleep(int maxPeriodMS) { + + int actualPeriodMS = enable(maxPeriodMS, true); // true = for sleep + + system_set_sleepmode(SYSTEM_SLEEPMODE_STANDBY); // Deepest sleep + system_sleep(); + // Code resumes here on wake (WDT early warning interrupt) + + return actualPeriodMS; +} + +void WatchdogSAMD::_initialize_wdt() { + // One-time initialization of watchdog timer. + // Insights from rickrlh and rbrucemtl in Arduino forum! + + // Generic clock generator 2, divisor = 32 (2^(DIV+1)) + GCLK->GENDIV.reg = GCLK_GENDIV_ID(2) | GCLK_GENDIV_DIV(4); + // Enable clock generator 2 using low-power 32KHz oscillator. + // With /32 divisor above, this yields 1024Hz(ish) clock. + GCLK->GENCTRL.reg = GCLK_GENCTRL_ID(2) | + GCLK_GENCTRL_GENEN | + GCLK_GENCTRL_SRC_OSCULP32K | + GCLK_GENCTRL_DIVSEL; + while(GCLK->STATUS.bit.SYNCBUSY); + // WDT clock = clock gen 2 + GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID_WDT | + GCLK_CLKCTRL_CLKEN | + GCLK_CLKCTRL_GEN_GCLK2; + + // Enable WDT early-warning interrupt + NVIC_DisableIRQ(WDT_IRQn); + NVIC_ClearPendingIRQ(WDT_IRQn); + NVIC_SetPriority(WDT_IRQn, 0); // Top priority + NVIC_EnableIRQ(WDT_IRQn); + + _initialized = true; +} + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h new file mode 100644 index 0000000..8b03c27 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h @@ -0,0 +1,43 @@ +#ifndef WATCHDOGSAMD_H +#define WATCHDOGSAMD_H + +class WatchdogSAMD { +public: + WatchdogSAMD(): + _initialized(false) + {} + + // Enable the watchdog timer to reset the machine after a period of time + // without any calls to reset(). The passed in period (in milliseconds) + // is just a suggestion and a lower value might be picked if the hardware + // does not support the exact desired value. + // User code should NOT set the 'isForSleep' argument either way -- + // it's used internally by the library, but your sketch should leave this + // out when calling enable(), just let the default have its way. + // + // The actual period (in milliseconds) before a watchdog timer reset is + // returned. + int enable(int maxPeriodMS = 0, bool isForSleep = false); + + // Reset or 'kick' the watchdog timer to prevent a reset of the device. + void reset(); + + // Completely disable the watchdog timer. + void disable(); + + // Enter the lowest power sleep mode (using the watchdog timer) for the + // desired period of time. The passed in period (in milliseconds) is + // just a suggestion and a lower value might be picked if the hardware + // does not support the exact desired value + // + // The actual period (in milliseconds) that the hardware was asleep will be + // returned. + int sleep(int maxPeriodMS = 0); + +private: + void _initialize_wdt(); + + bool _initialized; +}; + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/.gitignore b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/.gitignore new file mode 100644 index 0000000..89d225a --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/.gitignore @@ -0,0 +1,2 @@ +.development +examples/node_test_server/node_modules/ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/CHANGELOG.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/CHANGELOG.md new file mode 100644 index 0000000..5645508 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/CHANGELOG.md @@ -0,0 +1,25 @@ +## ArduinoHttpClient 0.3.1 - 2017.09.25 + +* Changed examples to support Arduino Create secret tabs +* Increase WebSocket secrect-key length to 24 characters + +## ArduinoHttpClient 0.3.0 - 2017.04.20 + +* Added support for PATCH operations +* Added support for chunked response bodies +* Added new beginBody API + +## ArduinoHttpClient 0.2.0 - 2017.01.12 + +* Added PATCH method +* Added basic auth example +* Added custom header example + +## ArduinoHttpClient 0.1.1 - 2016.12.16 + +* More robust response parser + +## ArduinoHttpClient 0.1.0 - 2016.07.05 + +* Initial release + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/README.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/README.md new file mode 100644 index 0000000..655b618 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/README.md @@ -0,0 +1,22 @@ +# ArduinoHttpClient + +ArduinoHttpClient is a library to make it easier to interact with web servers from Arduino. + +Derived from [Adrian McEwen's HttpClient library](https://github.com/amcewen/HttpClient) + +## Dependencies + +- Requires a networking hardware and a library that provides transport specific `Client` instance, such as: + - [WiFi101](https://github.com/arduino-libraries/WiFi101) + - [Ethernet](https://github.com/arduino-libraries/Ethernet) + - [WiFi](https://github.com/arduino-libraries/WiFi) + - [GSM](https://github.com/arduino-libraries/GSM) + +## Usage + +In normal usage, handles the outgoing request and Host header. The returned status code is parsed for you, as is the Content-Length header (if present). + +Because it expects an object of type Client, you can use it with any of the networking classes that derive from that. Which means it will work with WiFiClient, EthernetClient and GSMClient. + +See the examples for more detail on how the library is used. + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino new file mode 100644 index 0000000..e793d47 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino @@ -0,0 +1,69 @@ +/* + GET client with HTTP basic authentication for ArduinoHttpClient library + Connects to server once every five seconds, sends a GET request + + + + created 14 Feb 2016 + by Tom Igoe + modified 3 Jan 2017 to add HTTP basic authentication + by Sandeep Mistry + + this example is in the public domain + */ +#include +#include +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("making GET request with HTTP basic authentication"); + client.beginRequest(); + client.get("/secure"); + client.sendBasicAuth("username", "password"); // send the username and password for authentication + client.endRequest(); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + Serial.println("Wait five seconds"); + delay(5000); +} + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino new file mode 100644 index 0000000..fa44aca --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino @@ -0,0 +1,96 @@ +/* + Custom request header example for the ArduinoHttpClient + library. This example sends a GET and a POST request with a custom header every 5 seconds. + + note: WiFi SSID and password are stored in config.h file. + If it is not present, add a new tab, call it "config.h" + and add the following variables: + char ssid[] = "ssid"; // your network SSID (name) + char pass[] = "password"; // your network password + + based on SimpleGet example by Tom Igoe + header modifications by Todd Treece + + this example is in the public domain + */ + +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + + Serial.println("making GET request"); + client.beginRequest(); + client.get("/"); + client.sendHeader("X-CUSTOM-HEADER", "custom_value"); + client.endRequest(); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("GET Status code: "); + Serial.println(statusCode); + Serial.print("GET Response: "); + Serial.println(response); + + Serial.println("Wait five seconds"); + delay(5000); + + Serial.println("making POST request"); + String postData = "name=Alice&age=12"; + client.beginRequest(); + client.post("/"); + client.sendHeader(HTTP_HEADER_CONTENT_TYPE, "application/x-www-form-urlencoded"); + client.sendHeader(HTTP_HEADER_CONTENT_LENGTH, postData.length()); + client.sendHeader("X-CUSTOM-HEADER", "custom_value"); + client.endRequest(); + client.write((const byte*)postData.c_str(), postData.length()); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("POST Status code: "); + Serial.println(statusCode); + Serial.print("POST Response: "); + Serial.println(response); + + Serial.println("Wait five seconds"); + delay(5000); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino new file mode 100644 index 0000000..51abd3f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino @@ -0,0 +1,107 @@ +/* + Dweet.io GET client for ArduinoHttpClient library + Connects to dweet.io once every ten seconds, + sends a GET request and a request body. Uses SSL + + Shows how to use Strings to assemble path and parse content + from response. dweet.io expects: + https://dweet.io/get/latest/dweet/for/thingName + + For more on dweet.io, see https://dweet.io/play/ + + + + created 15 Feb 2016 + updated 16 Feb 2016 + by Tom Igoe + + this example is in the public domain +*/ +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + +const char serverAddress[] = "dweet.io"; // server address +int port = 80; +String dweetName = "scandalous-cheese-hoarder"; // use your own thing name here + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +int statusCode = 0; +String response; + +void setup() { + Serial.begin(9600); + while (!Serial); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + // assemble the path for the GET message: + String path = "/get/latest/dweet/for/" + dweetName; + + // send the GET request + Serial.println("making GET request"); + client.get(path); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + /* + Typical response is: + {"this":"succeeded", + "by":"getting", + "the":"dweets", + "with":[{"thing":"my-thing-name", + "created":"2016-02-16T05:10:36.589Z", + "content":{"sensorValue":456}}]} + + You want "content": numberValue + */ + // now parse the response looking for "content": + int labelStart = response.indexOf("content\":"); + // find the first { after "content": + int contentStart = response.indexOf("{", labelStart); + // find the following } and get what's between the braces: + int contentEnd = response.indexOf("}", labelStart); + String content = response.substring(contentStart + 1, contentEnd); + Serial.println(content); + + // now get the value after the colon, and convert to an int: + int valueStart = content.indexOf(":"); + String valueString = content.substring(valueStart + 1); + int number = valueString.toInt(); + Serial.print("Value string: "); + Serial.println(valueString); + Serial.print("Actual value: "); + Serial.println(number); + + Serial.println("Wait ten seconds\n"); + delay(10000); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino new file mode 100644 index 0000000..41c6f2f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino @@ -0,0 +1,87 @@ +/* + Dweet.io POST client for ArduinoHttpClient library + Connects to dweet.io once every ten seconds, + sends a POST request and a request body. + + Shows how to use Strings to assemble path and body + + note: WiFi SSID and password are stored in config.h file. + If it is not present, add a new tab, call it "config.h" + and add the following variables: + char ssid[] = "ssid"; // your network SSID (name) + char pass[] = "password"; // your network password + + created 15 Feb 2016 + by Tom Igoe + + this example is in the public domain +*/ +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + +const char serverAddress[] = "dweet.io"; // server address +int port = 80; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +int statusCode = 0; +String response; + +void setup() { + Serial.begin(9600); + while(!Serial); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + // assemble the path for the POST message: + String dweetName = "scandalous-cheese-hoarder"; + String path = "/dweet/for/" + dweetName; + + String contentType = "application/json"; + + // assemble the body of the POST message: + int sensorValue = analogRead(A0); + String postData = "{\"sensorValue\":\""; + postData += sensorValue; + postData += "\"}"; + + Serial.println("making POST request"); + + // send the POST request + client.post(path, contentType, postData); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + Serial.println("Wait ten seconds\n"); + delay(10000); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino new file mode 100644 index 0000000..c18ae47 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino @@ -0,0 +1,102 @@ +/* HueBlink example for ArduinoHttpClient library + + Uses ArduinoHttpClient library to control Philips Hue + For more on Hue developer API see http://developer.meethue.com + + To control a light, the Hue expects a HTTP PUT request to: + + http://hue.hub.address/api/hueUserName/lights/lightNumber/state + + The body of the PUT request looks like this: + {"on": true} or {"on":false} + + This example shows how to concatenate Strings to assemble the + PUT request and the body of the request. + + + + modified 15 Feb 2016 + by Tom Igoe (tigoe) to match new API +*/ + +#include +#include +#include +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + +int status = WL_IDLE_STATUS; // the Wifi radio's status + +char hueHubIP[] = "192.168.0.3"; // IP address of the HUE bridge +String hueUserName = "huebridgeusername"; // hue bridge username + +// make a wifi instance and a HttpClient instance: +WiFiClient wifi; +HttpClient httpClient = HttpClient(wifi, hueHubIP); + + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial); // wait for serial port to connect. + + // attempt to connect to Wifi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to WPA SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // you're connected now, so print out the data: + Serial.print("You're connected to the network IP = "); + IPAddress ip = WiFi.localIP(); + Serial.println(ip); +} + +void loop() { + sendRequest(3, "on", "true"); // turn light on + delay(2000); // wait 2 seconds + sendRequest(3, "on", "false"); // turn light off + delay(2000); // wait 2 seconds +} + +void sendRequest(int light, String cmd, String value) { + // make a String for the HTTP request path: + String request = "/api/" + hueUserName; + request += "/lights/"; + request += light; + request += "/state/"; + + String contentType = "application/json"; + + // make a string for the JSON command: + String hueCmd = "{\"" + cmd; + hueCmd += "\":"; + hueCmd += value; + hueCmd += "}"; + // see what you assembled to send: + Serial.print("PUT request to server: "); + Serial.println(request); + Serial.print("JSON command to server: "); + + // make the PUT request to the hub: + httpClient.put(request, contentType, hueCmd); + + // read the status code and body of the response + int statusCode = httpClient.responseStatusCode(); + String response = httpClient.responseBody(); + + Serial.println(hueCmd); + Serial.print("Status code from server: "); + Serial.println(statusCode); + Serial.print("Server response: "); + Serial.println(response); + Serial.println(); +} + + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino new file mode 100644 index 0000000..835a26f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino @@ -0,0 +1,79 @@ +/* + POST with headers client for ArduinoHttpClient library + Connects to server once every five seconds, sends a POST request + with custome headers and a request body + + + + created 14 Feb 2016 + by Tom Igoe + modified 18 Mar 2017 + by Sandeep Mistry + + this example is in the public domain + */ +#include +#include + +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("making POST request"); + String postData = "name=Alice&age=12"; + + client.beginRequest(); + client.post("/"); + client.sendHeader("Content-Type", "application/x-www-form-urlencoded"); + client.sendHeader("Content-Length", postData.length()); + client.sendHeader("X-Custom-Header", "custom-header-value"); + client.beginBody(); + client.print(postData); + client.endRequest(); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + Serial.println("Wait five seconds"); + delay(5000); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino new file mode 100644 index 0000000..374a145 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino @@ -0,0 +1,71 @@ +/* + Simple DELETE client for ArduinoHttpClient library + Connects to server once every five seconds, sends a DELETE request + and a request body + + + + created 14 Feb 2016 + by Tom Igoe + + this example is in the public domain + */ +#include +#include + +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("making DELETE request"); + String contentType = "application/x-www-form-urlencoded"; + String delData = "name=light&age=46"; + + client.del("/", contentType, delData); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + Serial.println("Wait five seconds"); + delay(5000); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino new file mode 100644 index 0000000..75db9a7 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino @@ -0,0 +1,66 @@ +/* + Simple GET client for ArduinoHttpClient library + Connects to server once every five seconds, sends a GET request + + + + created 14 Feb 2016 + by Tom Igoe + + this example is in the public domain + */ +#include +#include + +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("making GET request"); + client.get("/"); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + Serial.println("Wait five seconds"); + delay(5000); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino new file mode 100644 index 0000000..f64b9ba --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino @@ -0,0 +1,133 @@ +// (c) Copyright 2010-2012 MCQN Ltd. +// Released under Apache License, version 2.0 +// +// Simple example to show how to use the HttpClient library +// Get's the web page given at http:// and +// outputs the content to the serial port + +#include +#include +#include + +// This example downloads the URL "http://arduino.cc/" + +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + + + +// Name of the server we want to connect to +const char kHostname[] = "arduino.cc"; +// Path to download (this is the bit after the hostname in the URL +// that you want to download +const char kPath[] = "/"; + +// Number of milliseconds to wait without receiving any data before we give up +const int kNetworkTimeout = 30*1000; +// Number of milliseconds to wait if no data is available before trying again +const int kNetworkDelay = 1000; + +WiFiClient c; +HttpClient http(c, kHostname); + +void setup() +{ + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // attempt to connect to Wifi network: + Serial.print("Attempting to connect to WPA SSID: "); + Serial.println(ssid); + while (WiFi.begin(ssid, pass) != WL_CONNECTED) { + // unsuccessful, retry in 4 seconds + Serial.print("failed ... "); + delay(4000); + Serial.print("retrying ... "); + } + + Serial.println("connected"); +} + +void loop() +{ + int err =0; + + err = http.get(kPath); + if (err == 0) + { + Serial.println("startedRequest ok"); + + err = http.responseStatusCode(); + if (err >= 0) + { + Serial.print("Got status code: "); + Serial.println(err); + + // Usually you'd check that the response code is 200 or a + // similar "success" code (200-299) before carrying on, + // but we'll print out whatever response we get + + // If you are interesting in the response headers, you + // can read them here: + //while(http.headerAvailable()) + //{ + // String headerName = http.readHeaderName(); + // String headerValue = http.readHeaderValue(); + //} + + int bodyLen = http.contentLength(); + Serial.print("Content length is: "); + Serial.println(bodyLen); + Serial.println(); + Serial.println("Body returned follows:"); + + // Now we've got to the body, so we can print it out + unsigned long timeoutStart = millis(); + char c; + // Whilst we haven't timed out & haven't reached the end of the body + while ( (http.connected() || http.available()) && + (!http.endOfBodyReached()) && + ((millis() - timeoutStart) < kNetworkTimeout) ) + { + if (http.available()) + { + c = http.read(); + // Print out this character + Serial.print(c); + + // We read something, reset the timeout counter + timeoutStart = millis(); + } + else + { + // We haven't got any data, so let's pause to allow some to + // arrive + delay(kNetworkDelay); + } + } + } + else + { + Serial.print("Getting response failed: "); + Serial.println(err); + } + } + else + { + Serial.print("Connect failed: "); + Serial.println(err); + } + http.stop(); + + // And just stop, now that we've tried a download + while(1); +} + + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino new file mode 100644 index 0000000..6cc3517 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino @@ -0,0 +1,70 @@ +/* + Simple POST client for ArduinoHttpClient library + Connects to server once every five seconds, sends a POST request + and a request body + + + + created 14 Feb 2016 + by Tom Igoe + + this example is in the public domain + */ +#include +#include +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("making POST request"); + String contentType = "application/x-www-form-urlencoded"; + String postData = "name=Alice&age=12"; + + client.post("/", contentType, postData); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + Serial.println("Wait five seconds"); + delay(5000); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino new file mode 100644 index 0000000..1b06105 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino @@ -0,0 +1,70 @@ +/* + Simple PUT client for ArduinoHttpClient library + Connects to server once every five seconds, sends a PUT request + and a request body + + + + created 14 Feb 2016 + by Tom Igoe + + this example is in the public domain + */ +#include +#include +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + + +char serverAddress[] = "192.168.0.3"; // server address +int port = 8080; + +WiFiClient wifi; +HttpClient client = HttpClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +String response; +int statusCode = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("making PUT request"); + String contentType = "application/x-www-form-urlencoded"; + String putData = "name=light&age=46"; + + client.put("/", contentType, putData); + + // read the status code and body of the response + statusCode = client.responseStatusCode(); + response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + Serial.println("Wait five seconds"); + delay(5000); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino new file mode 100644 index 0000000..baac12f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino @@ -0,0 +1,80 @@ +/* + Simple WebSocket client for ArduinoHttpClient library + Connects to the WebSocket server, and sends a hello + message every 5 seconds + + + created 28 Jun 2016 + by Sandeep Mistry + + this example is in the public domain +*/ +#include +#include +#include "arduino_secrets.h" + +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +/////// Wifi Settings /////// +char ssid[] = SECRET_SSID; +char pass[] = SECRET_PASS; + +char serverAddress[] = "echo.websocket.org"; // server address +int port = 80; + +WiFiClient wifi; +WebSocketClient client = WebSocketClient(wifi, serverAddress, port); +int status = WL_IDLE_STATUS; +int count = 0; + +void setup() { + Serial.begin(9600); + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + } + + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("starting WebSocket client"); + client.begin(); + + while (client.connected()) { + Serial.print("Sending hello "); + Serial.println(count); + + // send a hello # + client.beginMessage(TYPE_TEXT); + client.print("hello "); + client.print(count); + client.endMessage(); + + // increment count for next message + count++; + + // check if a message is available to be received + int messageSize = client.parseMessage(); + + if (messageSize > 0) { + Serial.println("Received a message:"); + Serial.println(client.readString()); + } + + // wait 5 seconds + delay(5000); + } + + Serial.println("disconnected"); +} + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js new file mode 100644 index 0000000..f3dd4d8 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js @@ -0,0 +1,102 @@ +/* + Express.js GET/POST example + Shows how handle GET, POST, PUT, DELETE + in Express.js 4.0 + + created 14 Feb 2016 + by Tom Igoe +*/ + +var express = require('express'); // include express.js +var app = express(); // a local instance of it +var bodyParser = require('body-parser'); // include body-parser +var WebSocketServer = require('ws').Server // include Web Socket server + +// you need a body parser: +app.use(bodyParser.urlencoded({extended: false})); // for application/x-www-form-urlencoded + +// this runs after the server successfully starts: +function serverStart() { + var port = server.address().port; + console.log('Server listening on port '+ port); +} + +app.get('/chunked', function(request, response) { + response.write('\n'); + response.write(' `:;;;,` .:;;:. \n'); + response.write(' .;;;;;;;;;;;` :;;;;;;;;;;: TM \n'); + response.write(' `;;;;;;;;;;;;;;;` :;;;;;;;;;;;;;;; \n'); + response.write(' :;;;;;;;;;;;;;;;;;; `;;;;;;;;;;;;;;;;;; \n'); + response.write(' ;;;;;;;;;;;;;;;;;;;;; .;;;;;;;;;;;;;;;;;;;; \n'); + response.write(' ;;;;;;;;:` `;;;;;;;;; ,;;;;;;;;.` .;;;;;;;; \n'); + response.write(' .;;;;;;, :;;;;;;; .;;;;;;; ;;;;;;; \n'); + response.write(' ;;;;;; ;;;;;;; ;;;;;;, ;;;;;;. \n'); + response.write(' ,;;;;; ;;;;;;.;;;;;;` ;;;;;; \n'); + response.write(' ;;;;;. ;;;;;;;;;;;` ``` ;;;;;`\n'); + response.write(' ;;;;; ;;;;;;;;;, ;;; .;;;;;\n'); + response.write('`;;;;: `;;;;;;;; ;;; ;;;;;\n'); + response.write(',;;;;` `,,,,,,,, ;;;;;;; .,,;;;,,, ;;;;;\n'); + response.write(':;;;;` .;;;;;;;; ;;;;;, :;;;;;;;; ;;;;;\n'); + response.write(':;;;;` .;;;;;;;; `;;;;;; :;;;;;;;; ;;;;;\n'); + response.write('.;;;;. ;;;;;;;. ;;; ;;;;;\n'); + response.write(' ;;;;; ;;;;;;;;; ;;; ;;;;;\n'); + response.write(' ;;;;; .;;;;;;;;;; ;;; ;;;;;,\n'); + response.write(' ;;;;;; `;;;;;;;;;;;; ;;;;; \n'); + response.write(' `;;;;;, .;;;;;; ;;;;;;; ;;;;;; \n'); + response.write(' ;;;;;;: :;;;;;;. ;;;;;;; ;;;;;; \n'); + response.write(' ;;;;;;;` .;;;;;;;, ;;;;;;;; ;;;;;;;: \n'); + response.write(' ;;;;;;;;;:,:;;;;;;;;;: ;;;;;;;;;;:,;;;;;;;;;; \n'); + response.write(' `;;;;;;;;;;;;;;;;;;;. ;;;;;;;;;;;;;;;;;;;; \n'); + response.write(' ;;;;;;;;;;;;;;;;; :;;;;;;;;;;;;;;;;: \n'); + response.write(' ,;;;;;;;;;;;;;, ;;;;;;;;;;;;;; \n'); + response.write(' .;;;;;;;;;` ,;;;;;;;;: \n'); + response.write(' \n'); + response.write(' \n'); + response.write(' \n'); + response.write(' \n'); + response.write(' ;;; ;;;;;` ;;;;: .;; ;; ,;;;;;, ;;. `;, ;;;; \n'); + response.write(' ;;; ;;:;;; ;;;;;; .;; ;; ,;;;;;: ;;; `;, ;;;:;; \n'); + response.write(' ,;:; ;; ;; ;; ;; .;; ;; ,;, ;;;,`;, ;; ;; \n'); + response.write(' ;; ;: ;; ;; ;; ;; .;; ;; ,;, ;;;;`;, ;; ;;. \n'); + response.write(' ;: ;; ;;;;;: ;; ;; .;; ;; ,;, ;;`;;;, ;; ;;` \n'); + response.write(' ,;;;;; ;;`;; ;; ;; .;; ;; ,;, ;; ;;;, ;; ;; \n'); + response.write(' ;; ,;, ;; .;; ;;;;;: ;;;;;: ,;;;;;: ;; ;;, ;;;;;; \n'); + response.write(' ;; ;; ;; ;;` ;;;;. `;;;: ,;;;;;, ;; ;;, ;;;; \n'); + response.write('\n'); + response.end(); +}); + +// this is the POST handler: +app.all('/*', function (request, response) { + console.log('Got a ' + request.method + ' request'); + // the parameters of a GET request are passed in + // request.body. Pass that to formatResponse() + // for formatting: + console.log(request.headers); + if (request.method == 'GET') { + console.log(request.query); + } else { + console.log(request.body); + } + + // send the response: + response.send('OK'); + response.end(); +}); + +// start the server: +var server = app.listen(8080, serverStart); + +// create a WebSocket server and attach it to the server +var wss = new WebSocketServer({server: server}); + +wss.on('connection', function connection(ws) { + // new connection, add message listener + ws.on('message', function incoming(message) { + // received a message + console.log('received: %s', message); + + // echo it back + ws.send(message); + }); +}); diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/node_test_server/package.json b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/node_test_server/package.json new file mode 100644 index 0000000..09f2d8b --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/node_test_server/package.json @@ -0,0 +1,13 @@ +{ + "name": "node_test_server", + "version": "0.0.1", + "author": { + "name": "Tom Igoe" + }, + "dependencies": { + "body-parser": ">=1.11.0", + "express": ">=4.0.0", + "multer": "*", + "ws": "^1.1.1" + } +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/keywords.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/keywords.txt new file mode 100644 index 0000000..27cd516 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/keywords.txt @@ -0,0 +1,64 @@ +####################################### +# Syntax Coloring Map For HttpClient +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +ArduinoHttpClient KEYWORD1 +HttpClient KEYWORD1 +WebSocketClient KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +get KEYWORD2 +post KEYWORD2 +put KEYWORD2 +patch KEYWORD2 +startRequest KEYWORD2 +beginRequest KEYWORD2 +beginBody KEYWORD2 +sendHeader KEYWORD2 +sendBasicAuth KEYWORD2 +endRequest KEYWORD2 +responseStatusCode KEYWORD2 +readHeader KEYWORD2 +skipResponseHeaders KEYWORD2 +endOfHeadersReached KEYWORD2 +endOfBodyReached KEYWORD2 +completed KEYWORD2 +contentLength KEYWORD2 +isResponseChunked KEYWORD2 +connectionKeepAlive KEYWORD2 +noDefaultRequestHeaders KEYWORD2 +headerAvailable KEYWORD2 +readHeaderName KEYWORD2 +readHeaderValue KEYWORD2 +responseBody KEYWORD2 + +beginMessage KEYWORD2 +endMessage KEYWORD2 +parseMessage KEYWORD2 +messageType KEYWORD2 +isFinal KEYWORD2 +readString KEYWORD2 +ping KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### +HTTP_SUCCESS LITERAL1 +HTTP_ERROR_CONNECTION_FAILED LITERAL1 +HTTP_ERROR_API LITERAL1 +HTTP_ERROR_TIMED_OUT LITERAL1 +HTTP_ERROR_INVALID_RESPONSE LITERAL1 + +TYPE_CONTINUATION LITERAL1 +TYPE_TEXT LITERAL1 +TYPE_BINARY LITERAL1 +TYPE_CONNECTION_CLOSE LITERAL1 +TYPE_PING LITERAL1 +TYPE_PONG LITERAL1 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/library.json b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/library.json new file mode 100644 index 0000000..6bbda24 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/library.json @@ -0,0 +1,12 @@ +{ + "name": "ArduinoHttpClient", + "keywords": "http, web, client, ethernet, wifi, GSM", + "description": "Easily interact with web servers from Arduino, using HTTP and WebSocket's.", + "repository": + { + "type": "git", + "url": "https://github.com/arduino-libraries/ArduinoHttpClient.git" + }, + "frameworks": "arduino", + "platforms": "*" +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/library.properties b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/library.properties new file mode 100644 index 0000000..2ac5bb5 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/library.properties @@ -0,0 +1,10 @@ +name=ArduinoHttpClient +version=0.3.1 +author=Arduino +maintainer=Arduino +sentence=[EXPERIMENTAL] Easily interact with web servers from Arduino, using HTTP and WebSocket's. +paragraph=This library can be used for HTTP (GET, POST, PUT, DELETE) requests to a web server. It also supports exchanging messages with WebSocket servers. Based on Adrian McEwen's HttpClient library. +category=Communication +url=https://github.com/arduino-libraries/ArduinoHttpClient +architectures=* +includes=ArduinoHttpClient.h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h new file mode 100644 index 0000000..578733f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h @@ -0,0 +1,11 @@ +// Library to simplify HTTP fetching on Arduino +// (c) Copyright Arduino. 2016 +// Released under Apache License, version 2.0 + +#ifndef ArduinoHttpClient_h +#define ArduinoHttpClient_h + +#include "HttpClient.h" +#include "WebSocketClient.h" + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/HttpClient.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/HttpClient.cpp new file mode 100644 index 0000000..7517eea --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/HttpClient.cpp @@ -0,0 +1,862 @@ +// Class to simplify HTTP fetching on Arduino +// (c) Copyright 2010-2011 MCQN Ltd +// Released under Apache License, version 2.0 + +#include "HttpClient.h" +#include "b64.h" + +// Initialize constants +const char* HttpClient::kUserAgent = "Arduino/2.2.0"; +const char* HttpClient::kContentLengthPrefix = HTTP_HEADER_CONTENT_LENGTH ": "; +const char* HttpClient::kTransferEncodingChunked = HTTP_HEADER_TRANSFER_ENCODING ": " HTTP_HEADER_VALUE_CHUNKED; + +HttpClient::HttpClient(Client& aClient, const char* aServerName, uint16_t aServerPort) + : iClient(&aClient), iServerName(aServerName), iServerAddress(), iServerPort(aServerPort), + iConnectionClose(true), iSendDefaultRequestHeaders(true) +{ + resetState(); +} + +HttpClient::HttpClient(Client& aClient, const String& aServerName, uint16_t aServerPort) + : HttpClient(aClient, aServerName.c_str(), aServerPort) +{ +} + +HttpClient::HttpClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort) + : iClient(&aClient), iServerName(NULL), iServerAddress(aServerAddress), iServerPort(aServerPort), + iConnectionClose(true), iSendDefaultRequestHeaders(true) +{ + resetState(); +} + +void HttpClient::resetState() +{ + iState = eIdle; + iStatusCode = 0; + iContentLength = kNoContentLengthHeader; + iBodyLengthConsumed = 0; + iContentLengthPtr = kContentLengthPrefix; + iTransferEncodingChunkedPtr = kTransferEncodingChunked; + iIsChunked = false; + iChunkLength = 0; + iHttpResponseTimeout = kHttpResponseTimeout; +} + +void HttpClient::stop() +{ + iClient->stop(); + resetState(); +} + +void HttpClient::connectionKeepAlive() +{ + iConnectionClose = false; +} + +void HttpClient::noDefaultRequestHeaders() +{ + iSendDefaultRequestHeaders = false; +} + +void HttpClient::beginRequest() +{ + iState = eRequestStarted; +} + +int HttpClient::startRequest(const char* aURLPath, const char* aHttpMethod, + const char* aContentType, int aContentLength, const byte aBody[]) +{ + if (iState == eReadingBody || iState == eReadingChunkLength || iState == eReadingBodyChunk) + { + flushClientRx(); + + resetState(); + } + + tHttpState initialState = iState; + + if ((eIdle != iState) && (eRequestStarted != iState)) + { + return HTTP_ERROR_API; + } + + if (iConnectionClose || !iClient->connected()) + { + if (iServerName) + { + if (!iClient->connect(iServerName, iServerPort) > 0) + { +#ifdef LOGGING + Serial.println("Connection failed"); +#endif + return HTTP_ERROR_CONNECTION_FAILED; + } + } + else + { + if (!iClient->connect(iServerAddress, iServerPort) > 0) + { +#ifdef LOGGING + Serial.println("Connection failed"); +#endif + return HTTP_ERROR_CONNECTION_FAILED; + } + } + } + else + { +#ifdef LOGGING + Serial.println("Connection already open"); +#endif + } + + // Now we're connected, send the first part of the request + int ret = sendInitialHeaders(aURLPath, aHttpMethod); + + if (HTTP_SUCCESS == ret) + { + if (aContentType) + { + sendHeader(HTTP_HEADER_CONTENT_TYPE, aContentType); + } + + if (aContentLength > 0) + { + sendHeader(HTTP_HEADER_CONTENT_LENGTH, aContentLength); + } + + bool hasBody = (aBody && aContentLength > 0); + + if (initialState == eIdle || hasBody) + { + // This was a simple version of the API, so terminate the headers now + finishHeaders(); + } + // else we'll call it in endRequest or in the first call to print, etc. + + if (hasBody) + { + write(aBody, aContentLength); + } + } + + return ret; +} + +int HttpClient::sendInitialHeaders(const char* aURLPath, const char* aHttpMethod) +{ +#ifdef LOGGING + Serial.println("Connected"); +#endif + // Send the HTTP command, i.e. "GET /somepath/ HTTP/1.0" + iClient->print(aHttpMethod); + iClient->print(" "); + + iClient->print(aURLPath); + iClient->println(" HTTP/1.1"); + if (iSendDefaultRequestHeaders) + { + // The host header, if required + if (iServerName) + { + iClient->print("Host: "); + iClient->print(iServerName); + if (iServerPort != kHttpPort) + { + iClient->print(":"); + iClient->print(iServerPort); + } + iClient->println(); + } + // And user-agent string + sendHeader(HTTP_HEADER_USER_AGENT, kUserAgent); + } + + if (iConnectionClose) + { + // Tell the server to + // close this connection after we're done + sendHeader(HTTP_HEADER_CONNECTION, "close"); + } + + // Everything has gone well + iState = eRequestStarted; + return HTTP_SUCCESS; +} + +void HttpClient::sendHeader(const char* aHeader) +{ + iClient->println(aHeader); +} + +void HttpClient::sendHeader(const char* aHeaderName, const char* aHeaderValue) +{ + iClient->print(aHeaderName); + iClient->print(": "); + iClient->println(aHeaderValue); +} + +void HttpClient::sendHeader(const char* aHeaderName, const int aHeaderValue) +{ + iClient->print(aHeaderName); + iClient->print(": "); + iClient->println(aHeaderValue); +} + +void HttpClient::sendBasicAuth(const char* aUser, const char* aPassword) +{ + // Send the initial part of this header line + iClient->print("Authorization: Basic "); + // Now Base64 encode "aUser:aPassword" and send that + // This seems trickier than it should be but it's mostly to avoid either + // (a) some arbitrarily sized buffer which hopes to be big enough, or + // (b) allocating and freeing memory + // ...so we'll loop through 3 bytes at a time, outputting the results as we + // go. + // In Base64, each 3 bytes of unencoded data become 4 bytes of encoded data + unsigned char input[3]; + unsigned char output[5]; // Leave space for a '\0' terminator so we can easily print + int userLen = strlen(aUser); + int passwordLen = strlen(aPassword); + int inputOffset = 0; + for (int i = 0; i < (userLen+1+passwordLen); i++) + { + // Copy the relevant input byte into the input + if (i < userLen) + { + input[inputOffset++] = aUser[i]; + } + else if (i == userLen) + { + input[inputOffset++] = ':'; + } + else + { + input[inputOffset++] = aPassword[i-(userLen+1)]; + } + // See if we've got a chunk to encode + if ( (inputOffset == 3) || (i == userLen+passwordLen) ) + { + // We've either got to a 3-byte boundary, or we've reached then end + b64_encode(input, inputOffset, output, 4); + // NUL-terminate the output string + output[4] = '\0'; + // And write it out + iClient->print((char*)output); +// FIXME We might want to fill output with '=' characters if b64_encode doesn't +// FIXME do it for us when we're encoding the final chunk + inputOffset = 0; + } + } + // And end the header we've sent + iClient->println(); +} + +void HttpClient::finishHeaders() +{ + iClient->println(); + iState = eRequestSent; +} + +void HttpClient::flushClientRx() +{ + while (iClient->available()) + { + iClient->read(); + } +} + +void HttpClient::endRequest() +{ + beginBody(); +} + +void HttpClient::beginBody() +{ + if (iState < eRequestSent) + { + // We still need to finish off the headers + finishHeaders(); + } + // else the end of headers has already been sent, so nothing to do here +} + +int HttpClient::get(const char* aURLPath) +{ + return startRequest(aURLPath, HTTP_METHOD_GET); +} + +int HttpClient::get(const String& aURLPath) +{ + return get(aURLPath.c_str()); +} + +int HttpClient::post(const char* aURLPath) +{ + return startRequest(aURLPath, HTTP_METHOD_POST); +} + +int HttpClient::post(const String& aURLPath) +{ + return post(aURLPath.c_str()); +} + +int HttpClient::post(const char* aURLPath, const char* aContentType, const char* aBody) +{ + return post(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); +} + +int HttpClient::post(const String& aURLPath, const String& aContentType, const String& aBody) +{ + return post(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); +} + +int HttpClient::post(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) +{ + return startRequest(aURLPath, HTTP_METHOD_POST, aContentType, aContentLength, aBody); +} + +int HttpClient::put(const char* aURLPath) +{ + return startRequest(aURLPath, HTTP_METHOD_PUT); +} + +int HttpClient::put(const String& aURLPath) +{ + return put(aURLPath.c_str()); +} + +int HttpClient::put(const char* aURLPath, const char* aContentType, const char* aBody) +{ + return put(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); +} + +int HttpClient::put(const String& aURLPath, const String& aContentType, const String& aBody) +{ + return put(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); +} + +int HttpClient::put(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) +{ + return startRequest(aURLPath, HTTP_METHOD_PUT, aContentType, aContentLength, aBody); +} + +int HttpClient::patch(const char* aURLPath) +{ + return startRequest(aURLPath, HTTP_METHOD_PATCH); +} + +int HttpClient::patch(const String& aURLPath) +{ + return patch(aURLPath.c_str()); +} + +int HttpClient::patch(const char* aURLPath, const char* aContentType, const char* aBody) +{ + return patch(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); +} + +int HttpClient::patch(const String& aURLPath, const String& aContentType, const String& aBody) +{ + return patch(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); +} + +int HttpClient::patch(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) +{ + return startRequest(aURLPath, HTTP_METHOD_PATCH, aContentType, aContentLength, aBody); +} + +int HttpClient::del(const char* aURLPath) +{ + return startRequest(aURLPath, HTTP_METHOD_DELETE); +} + +int HttpClient::del(const String& aURLPath) +{ + return del(aURLPath.c_str()); +} + +int HttpClient::del(const char* aURLPath, const char* aContentType, const char* aBody) +{ + return del(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); +} + +int HttpClient::del(const String& aURLPath, const String& aContentType, const String& aBody) +{ + return del(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); +} + +int HttpClient::del(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) +{ + return startRequest(aURLPath, HTTP_METHOD_DELETE, aContentType, aContentLength, aBody); +} + +int HttpClient::responseStatusCode() +{ + if (iState < eRequestSent) + { + return HTTP_ERROR_API; + } + // The first line will be of the form Status-Line: + // HTTP-Version SP Status-Code SP Reason-Phrase CRLF + // Where HTTP-Version is of the form: + // HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT + + int c = '\0'; + do + { + // Make sure the status code is reset, and likewise the state. This + // lets us easily cope with 1xx informational responses by just + // ignoring them really, and reading the next line for a proper response + iStatusCode = 0; + iState = eRequestSent; + + unsigned long timeoutStart = millis(); + // Psuedo-regexp we're expecting before the status-code + const char* statusPrefix = "HTTP/*.* "; + const char* statusPtr = statusPrefix; + // Whilst we haven't timed out & haven't reached the end of the headers + while ((c != '\n') && + ( (millis() - timeoutStart) < iHttpResponseTimeout )) + { + if (available()) + { + c = read(); + if (c != -1) + { + switch(iState) + { + case eRequestSent: + // We haven't reached the status code yet + if ( (*statusPtr == '*') || (*statusPtr == c) ) + { + // This character matches, just move along + statusPtr++; + if (*statusPtr == '\0') + { + // We've reached the end of the prefix + iState = eReadingStatusCode; + } + } + else + { + return HTTP_ERROR_INVALID_RESPONSE; + } + break; + case eReadingStatusCode: + if (isdigit(c)) + { + // This assumes we won't get more than the 3 digits we + // want + iStatusCode = iStatusCode*10 + (c - '0'); + } + else + { + // We've reached the end of the status code + // We could sanity check it here or double-check for ' ' + // rather than anything else, but let's be lenient + iState = eStatusCodeRead; + } + break; + case eStatusCodeRead: + // We're just waiting for the end of the line now + break; + + default: + break; + }; + // We read something, reset the timeout counter + timeoutStart = millis(); + } + } + else + { + // We haven't got any data, so let's pause to allow some to + // arrive + delay(kHttpWaitForDataDelay); + } + } + if ( (c == '\n') && (iStatusCode < 200 && iStatusCode != 101) ) + { + // We've reached the end of an informational status line + c = '\0'; // Clear c so we'll go back into the data reading loop + } + } + // If we've read a status code successfully but it's informational (1xx) + // loop back to the start + while ( (iState == eStatusCodeRead) && (iStatusCode < 200 && iStatusCode != 101) ); + + if ( (c == '\n') && (iState == eStatusCodeRead) ) + { + // We've read the status-line successfully + return iStatusCode; + } + else if (c != '\n') + { + // We must've timed out before we reached the end of the line + return HTTP_ERROR_TIMED_OUT; + } + else + { + // This wasn't a properly formed status line, or at least not one we + // could understand + return HTTP_ERROR_INVALID_RESPONSE; + } +} + +int HttpClient::skipResponseHeaders() +{ + // Just keep reading until we finish reading the headers or time out + unsigned long timeoutStart = millis(); + // Whilst we haven't timed out & haven't reached the end of the headers + while ((!endOfHeadersReached()) && + ( (millis() - timeoutStart) < iHttpResponseTimeout )) + { + if (available()) + { + (void)readHeader(); + // We read something, reset the timeout counter + timeoutStart = millis(); + } + else + { + // We haven't got any data, so let's pause to allow some to + // arrive + delay(kHttpWaitForDataDelay); + } + } + if (endOfHeadersReached()) + { + // Success + return HTTP_SUCCESS; + } + else + { + // We must've timed out + return HTTP_ERROR_TIMED_OUT; + } +} + +bool HttpClient::endOfHeadersReached() +{ + return (iState == eReadingBody || iState == eReadingChunkLength || iState == eReadingBodyChunk); +}; + +int HttpClient::contentLength() +{ + // skip the response headers, if they haven't been read already + if (!endOfHeadersReached()) + { + skipResponseHeaders(); + } + + return iContentLength; +} + +String HttpClient::responseBody() +{ + int bodyLength = contentLength(); + String response; + + if (bodyLength > 0) + { + // try to reserve bodyLength bytes + if (response.reserve(bodyLength) == 0) { + // String reserve failed + return String((const char*)NULL); + } + } + + // keep on timedRead'ing, until: + // - we have a content length: body length equals consumed or no bytes + // available + // - no content length: no bytes are available + while (iBodyLengthConsumed != bodyLength) + { + int c = timedRead(); + + if (c == -1) { + // read timed out, done + break; + } + + if (!response.concat((char)c)) { + // adding char failed + return String((const char*)NULL); + } + } + + if (bodyLength > 0 && (unsigned int)bodyLength != response.length()) { + // failure, we did not read in reponse content length bytes + return String((const char*)NULL); + } + + return response; +} + +bool HttpClient::endOfBodyReached() +{ + if (endOfHeadersReached() && (contentLength() != kNoContentLengthHeader)) + { + // We've got to the body and we know how long it will be + return (iBodyLengthConsumed >= contentLength()); + } + return false; +} + +int HttpClient::available() +{ + if (iState == eReadingChunkLength) + { + while (iClient->available()) + { + char c = iClient->read(); + + if (c == '\n') + { + iState = eReadingBodyChunk; + break; + } + else if (c == '\r') + { + // no-op + } + else if (isHexadecimalDigit(c)) + { + char digit[2] = {c, '\0'}; + + iChunkLength = (iChunkLength * 16) + strtol(digit, NULL, 16); + } + } + } + + if (iState == eReadingBodyChunk && iChunkLength == 0) + { + iState = eReadingChunkLength; + } + + if (iState == eReadingChunkLength) + { + return 0; + } + + int clientAvailable = iClient->available(); + + if (iState == eReadingBodyChunk) + { + return min(clientAvailable, iChunkLength); + } + else + { + return clientAvailable; + } +} + + +int HttpClient::read() +{ + if (iIsChunked && !available()) + { + return -1; + } + + int ret = iClient->read(); + if (ret >= 0) + { + if (endOfHeadersReached() && iContentLength > 0) + { + // We're outputting the body now and we've seen a Content-Length header + // So keep track of how many bytes are left + iBodyLengthConsumed++; + } + + if (iState == eReadingBodyChunk) + { + iChunkLength--; + + if (iChunkLength == 0) + { + iState = eReadingChunkLength; + } + } + } + return ret; +} + +bool HttpClient::headerAvailable() +{ + // clear the currently store header line + iHeaderLine = ""; + + while (!endOfHeadersReached()) + { + // read a byte from the header + int c = readHeader(); + + if (c == '\r' || c == '\n') + { + if (iHeaderLine.length()) + { + // end of the line, all done + break; + } + else + { + // ignore any CR or LF characters + continue; + } + } + + // append byte to header line + iHeaderLine += (char)c; + } + + return (iHeaderLine.length() > 0); +} + +String HttpClient::readHeaderName() +{ + int colonIndex = iHeaderLine.indexOf(':'); + + if (colonIndex == -1) + { + return ""; + } + + return iHeaderLine.substring(0, colonIndex); +} + +String HttpClient::readHeaderValue() +{ + int colonIndex = iHeaderLine.indexOf(':'); + int startIndex = colonIndex + 1; + + if (colonIndex == -1) + { + return ""; + } + + // trim any leading whitespace + while (startIndex < (int)iHeaderLine.length() && isSpace(iHeaderLine[startIndex])) + { + startIndex++; + } + + return iHeaderLine.substring(startIndex); +} + +int HttpClient::read(uint8_t *buf, size_t size) +{ + int ret =iClient->read(buf, size); + if (endOfHeadersReached() && iContentLength > 0) + { + // We're outputting the body now and we've seen a Content-Length header + // So keep track of how many bytes are left + if (ret >= 0) + { + iBodyLengthConsumed += ret; + } + } + return ret; +} + +int HttpClient::readHeader() +{ + char c = read(); + + if (endOfHeadersReached()) + { + // We've passed the headers, but rather than return an error, we'll just + // act as a slightly less efficient version of read() + return c; + } + + // Whilst reading out the headers to whoever wants them, we'll keep an + // eye out for the "Content-Length" header + switch(iState) + { + case eStatusCodeRead: + // We're at the start of a line, or somewhere in the middle of reading + // the Content-Length prefix + if (*iContentLengthPtr == c) + { + // This character matches, just move along + iContentLengthPtr++; + if (*iContentLengthPtr == '\0') + { + // We've reached the end of the prefix + iState = eReadingContentLength; + // Just in case we get multiple Content-Length headers, this + // will ensure we just get the value of the last one + iContentLength = 0; + iBodyLengthConsumed = 0; + } + } + else if (*iTransferEncodingChunkedPtr == c) + { + // This character matches, just move along + iTransferEncodingChunkedPtr++; + if (*iTransferEncodingChunkedPtr == '\0') + { + // We've reached the end of the Transfer Encoding: chunked header + iIsChunked = true; + iState = eSkipToEndOfHeader; + } + } + else if (((iContentLengthPtr == kContentLengthPrefix) && (iTransferEncodingChunkedPtr == kTransferEncodingChunked)) && (c == '\r')) + { + // We've found a '\r' at the start of a line, so this is probably + // the end of the headers + iState = eLineStartingCRFound; + } + else + { + // This isn't the Content-Length or Transfer Encoding chunked header, skip to the end of the line + iState = eSkipToEndOfHeader; + } + break; + case eReadingContentLength: + if (isdigit(c)) + { + iContentLength = iContentLength*10 + (c - '0'); + } + else + { + // We've reached the end of the content length + // We could sanity check it here or double-check for "\r\n" + // rather than anything else, but let's be lenient + iState = eSkipToEndOfHeader; + } + break; + case eLineStartingCRFound: + if (c == '\n') + { + if (iIsChunked) + { + iState = eReadingChunkLength; + iChunkLength = 0; + } + else + { + iState = eReadingBody; + } + } + break; + default: + // We're just waiting for the end of the line now + break; + }; + + if ( (c == '\n') && !endOfHeadersReached() ) + { + // We've got to the end of this line, start processing again + iState = eStatusCodeRead; + iContentLengthPtr = kContentLengthPrefix; + iTransferEncodingChunkedPtr = kTransferEncodingChunked; + } + // And return the character read to whoever wants it + return c; +} + + + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/HttpClient.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/HttpClient.h new file mode 100644 index 0000000..c954872 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/HttpClient.h @@ -0,0 +1,392 @@ +// Class to simplify HTTP fetching on Arduino +// (c) Copyright MCQN Ltd. 2010-2012 +// Released under Apache License, version 2.0 + +#ifndef HttpClient_h +#define HttpClient_h + +#include +#include +#include "Client.h" + +static const int HTTP_SUCCESS =0; +// The end of the headers has been reached. This consumes the '\n' +// Could not connect to the server +static const int HTTP_ERROR_CONNECTION_FAILED =-1; +// This call was made when the HttpClient class wasn't expecting it +// to be called. Usually indicates your code is using the class +// incorrectly +static const int HTTP_ERROR_API =-2; +// Spent too long waiting for a reply +static const int HTTP_ERROR_TIMED_OUT =-3; +// The response from the server is invalid, is it definitely an HTTP +// server? +static const int HTTP_ERROR_INVALID_RESPONSE =-4; + +// Define some of the common methods and headers here +// That lets other code reuse them without having to declare another copy +// of them, so saves code space and RAM +#define HTTP_METHOD_GET "GET" +#define HTTP_METHOD_POST "POST" +#define HTTP_METHOD_PUT "PUT" +#define HTTP_METHOD_PATCH "PATCH" +#define HTTP_METHOD_DELETE "DELETE" +#define HTTP_HEADER_CONTENT_LENGTH "Content-Length" +#define HTTP_HEADER_CONTENT_TYPE "Content-Type" +#define HTTP_HEADER_CONNECTION "Connection" +#define HTTP_HEADER_TRANSFER_ENCODING "Transfer-Encoding" +#define HTTP_HEADER_USER_AGENT "User-Agent" +#define HTTP_HEADER_VALUE_CHUNKED "chunked" + +class HttpClient : public Client +{ +public: + static const int kNoContentLengthHeader =-1; + static const int kHttpPort =80; + static const char* kUserAgent; + +// FIXME Write longer API request, using port and user-agent, example +// FIXME Update tempToPachube example to calculate Content-Length correctly + + HttpClient(Client& aClient, const char* aServerName, uint16_t aServerPort = kHttpPort); + HttpClient(Client& aClient, const String& aServerName, uint16_t aServerPort = kHttpPort); + HttpClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort = kHttpPort); + + /** Start a more complex request. + Use this when you need to send additional headers in the request, + but you will also need to call endRequest() when you are finished. + */ + void beginRequest(); + + /** End a more complex request. + Use this when you need to have sent additional headers in the request, + but you will also need to call beginRequest() at the start. + */ + void endRequest(); + + /** Start the body of a more complex request. + Use this when you need to send the body after additional headers + in the request, but can optionally call endRequest() when + you are finished. + */ + void beginBody(); + + /** Connect to the server and start to send a GET request. + @param aURLPath Url to request + @return 0 if successful, else error + */ + int get(const char* aURLPath); + int get(const String& aURLPath); + + /** Connect to the server and start to send a POST request. + @param aURLPath Url to request + @return 0 if successful, else error + */ + int post(const char* aURLPath); + int post(const String& aURLPath); + + /** Connect to the server and send a POST request + with body and content type + @param aURLPath Url to request + @param aContentType Content type of request body + @param aBody Body of the request + @return 0 if successful, else error + */ + int post(const char* aURLPath, const char* aContentType, const char* aBody); + int post(const String& aURLPath, const String& aContentType, const String& aBody); + int post(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); + + /** Connect to the server and start to send a PUT request. + @param aURLPath Url to request + @return 0 if successful, else error + */ + int put(const char* aURLPath); + int put(const String& aURLPath); + + /** Connect to the server and send a PUT request + with body and content type + @param aURLPath Url to request + @param aContentType Content type of request body + @param aBody Body of the request + @return 0 if successful, else error + */ + int put(const char* aURLPath, const char* aContentType, const char* aBody); + int put(const String& aURLPath, const String& aContentType, const String& aBody); + int put(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); + + /** Connect to the server and start to send a PATCH request. + @param aURLPath Url to request + @return 0 if successful, else error + */ + int patch(const char* aURLPath); + int patch(const String& aURLPath); + + /** Connect to the server and send a PATCH request + with body and content type + @param aURLPath Url to request + @param aContentType Content type of request body + @param aBody Body of the request + @return 0 if successful, else error + */ + int patch(const char* aURLPath, const char* aContentType, const char* aBody); + int patch(const String& aURLPath, const String& aContentType, const String& aBody); + int patch(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); + + /** Connect to the server and start to send a DELETE request. + @param aURLPath Url to request + @return 0 if successful, else error + */ + int del(const char* aURLPath); + int del(const String& aURLPath); + + /** Connect to the server and send a DELETE request + with body and content type + @param aURLPath Url to request + @param aContentType Content type of request body + @param aBody Body of the request + @return 0 if successful, else error + */ + int del(const char* aURLPath, const char* aContentType, const char* aBody); + int del(const String& aURLPath, const String& aContentType, const String& aBody); + int del(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); + + /** Connect to the server and start to send the request. + If a body is provided, the entire request (including headers and body) will be sent + @param aURLPath Url to request + @param aHttpMethod Type of HTTP request to make, e.g. "GET", "POST", etc. + @param aContentType Content type of request body (optional) + @param aContentLength Length of request body (optional) + @param aBody Body of request (optional) + @return 0 if successful, else error + */ + int startRequest(const char* aURLPath, + const char* aHttpMethod, + const char* aContentType = NULL, + int aContentLength = -1, + const byte aBody[] = NULL); + + /** Send an additional header line. This can only be called in between the + calls to startRequest and finishRequest. + @param aHeader Header line to send, in its entirety (but without the + trailing CRLF. E.g. "Authorization: Basic YQDDCAIGES" + */ + void sendHeader(const char* aHeader); + + void sendHeader(const String& aHeader) + { sendHeader(aHeader.c_str()); } + + /** Send an additional header line. This is an alternate form of + sendHeader() which takes the header name and content as separate strings. + The call will add the ": " to separate the header, so for example, to + send a XXXXXX header call sendHeader("XXXXX", "Something") + @param aHeaderName Type of header being sent + @param aHeaderValue Value for that header + */ + void sendHeader(const char* aHeaderName, const char* aHeaderValue); + + void sendHeader(const String& aHeaderName, const String& aHeaderValue) + { sendHeader(aHeaderName.c_str(), aHeaderValue.c_str()); } + + /** Send an additional header line. This is an alternate form of + sendHeader() which takes the header name and content separately but where + the value is provided as an integer. + The call will add the ": " to separate the header, so for example, to + send a XXXXXX header call sendHeader("XXXXX", 123) + @param aHeaderName Type of header being sent + @param aHeaderValue Value for that header + */ + void sendHeader(const char* aHeaderName, const int aHeaderValue); + + void sendHeader(const String& aHeaderName, const int aHeaderValue) + { sendHeader(aHeaderName.c_str(), aHeaderValue); } + + /** Send a basic authentication header. This will encode the given username + and password, and send them in suitable header line for doing Basic + Authentication. + @param aUser Username for the authorization + @param aPassword Password for the user aUser + */ + void sendBasicAuth(const char* aUser, const char* aPassword); + + void sendBasicAuth(const String& aUser, const String& aPassword) + { sendBasicAuth(aUser.c_str(), aPassword.c_str()); } + + /** Get the HTTP status code contained in the response. + For example, 200 for successful request, 404 for file not found, etc. + */ + int responseStatusCode(); + + /** Check if a header is available to be read. + Use readHeaderName() to read header name, and readHeaderValue() to + read the header value + MUST be called after responseStatusCode() and before contentLength() + */ + bool headerAvailable(); + + /** Read the name of the current response header. + Returns empty string if a header is not available. + */ + String readHeaderName(); + + /** Read the vallue of the current response header. + Returns empty string if a header is not available. + */ + String readHeaderValue(); + + /** Read the next character of the response headers. + This functions in the same way as read() but to be used when reading + through the headers. Check whether or not the end of the headers has + been reached by calling endOfHeadersReached(), although after that point + this will still return data as read() would, but slightly less efficiently + MUST be called after responseStatusCode() and before contentLength() + @return The next character of the response headers + */ + int readHeader(); + + /** Skip any response headers to get to the body. + Use this if you don't want to do any special processing of the headers + returned in the response. You can also use it after you've found all of + the headers you're interested in, and just want to get on with processing + the body. + MUST be called after responseStatusCode() + @return HTTP_SUCCESS if successful, else an error code + */ + int skipResponseHeaders(); + + /** Test whether all of the response headers have been consumed. + @return true if we are now processing the response body, else false + */ + bool endOfHeadersReached(); + + /** Test whether the end of the body has been reached. + Only works if the Content-Length header was returned by the server + @return true if we are now at the end of the body, else false + */ + bool endOfBodyReached(); + virtual bool endOfStream() { return endOfBodyReached(); }; + virtual bool completed() { return endOfBodyReached(); }; + + /** Return the length of the body. + Also skips response headers if they have not been read already + MUST be called after responseStatusCode() + @return Length of the body, in bytes, or kNoContentLengthHeader if no + Content-Length header was returned by the server + */ + int contentLength(); + + /** Returns if the response body is chunked + @return true if response body is chunked, false otherwise + */ + int isResponseChunked() { return iIsChunked; } + + /** Return the response body as a String + Also skips response headers if they have not been read already + MUST be called after responseStatusCode() + @return response body of request as a String + */ + String responseBody(); + + /** Enables connection keep-alive mode + */ + void connectionKeepAlive(); + + /** Disables sending the default request headers (Host and User Agent) + */ + void noDefaultRequestHeaders(); + + // Inherited from Print + // Note: 1st call to these indicates the user is sending the body, so if need + // Note: be we should finish the header first + virtual size_t write(uint8_t aByte) { if (iState < eRequestSent) { finishHeaders(); }; return iClient-> write(aByte); }; + virtual size_t write(const uint8_t *aBuffer, size_t aSize) { if (iState < eRequestSent) { finishHeaders(); }; return iClient->write(aBuffer, aSize); }; + // Inherited from Stream + virtual int available(); + /** Read the next byte from the server. + @return Byte read or -1 if there are no bytes available. + */ + virtual int read(); + virtual int read(uint8_t *buf, size_t size); + virtual int peek() { return iClient->peek(); }; + virtual void flush() { return iClient->flush(); }; + + // Inherited from Client + virtual int connect(IPAddress ip, uint16_t port) { return iClient->connect(ip, port); }; + virtual int connect(const char *host, uint16_t port) { return iClient->connect(host, port); }; + virtual void stop(); + virtual uint8_t connected() { return iClient->connected(); }; + virtual operator bool() { return bool(iClient); }; + virtual uint32_t httpResponseTimeout() { return iHttpResponseTimeout; }; + virtual void setHttpResponseTimeout(uint32_t timeout) { iHttpResponseTimeout = timeout; }; +protected: + /** Reset internal state data back to the "just initialised" state + */ + void resetState(); + + /** Send the first part of the request and the initial headers. + @param aURLPath Url to request + @param aHttpMethod Type of HTTP request to make, e.g. "GET", "POST", etc. + @return 0 if successful, else error + */ + int sendInitialHeaders(const char* aURLPath, + const char* aHttpMethod); + + /* Let the server know that we've reached the end of the headers + */ + void finishHeaders(); + + /** Reading any pending data from the client (used in connection keep alive mode) + */ + void flushClientRx(); + + // Number of milliseconds that we wait each time there isn't any data + // available to be read (during status code and header processing) + static const int kHttpWaitForDataDelay = 1000; + // Number of milliseconds that we'll wait in total without receiveing any + // data before returning HTTP_ERROR_TIMED_OUT (during status code and header + // processing) + static const int kHttpResponseTimeout = 30*1000; + static const char* kContentLengthPrefix; + static const char* kTransferEncodingChunked; + typedef enum { + eIdle, + eRequestStarted, + eRequestSent, + eReadingStatusCode, + eStatusCodeRead, + eReadingContentLength, + eSkipToEndOfHeader, + eLineStartingCRFound, + eReadingBody, + eReadingChunkLength, + eReadingBodyChunk + } tHttpState; + // Client we're using + Client* iClient; + // Server we are connecting to + const char* iServerName; + IPAddress iServerAddress; + // Port of server we are connecting to + uint16_t iServerPort; + // Current state of the finite-state-machine + tHttpState iState; + // Stores the status code for the response, once known + int iStatusCode; + // Stores the value of the Content-Length header, if present + int iContentLength; + // How many bytes of the response body have been read by the user + int iBodyLengthConsumed; + // How far through a Content-Length header prefix we are + const char* iContentLengthPtr; + // How far through a Transfer-Encoding chunked header we are + const char* iTransferEncodingChunkedPtr; + // Stores if the response body is chunked + bool iIsChunked; + // Stores the value of the current chunk length, if present + int iChunkLength; + uint32_t iHttpResponseTimeout; + bool iConnectionClose; + bool iSendDefaultRequestHeaders; + String iHeaderLine; +}; + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/WebSocketClient.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/WebSocketClient.cpp new file mode 100644 index 0000000..ab41b0a --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/WebSocketClient.cpp @@ -0,0 +1,372 @@ +// (c) Copyright Arduino. 2016 +// Released under Apache License, version 2.0 + +#include "b64.h" + +#include "WebSocketClient.h" + +WebSocketClient::WebSocketClient(Client& aClient, const char* aServerName, uint16_t aServerPort) + : HttpClient(aClient, aServerName, aServerPort), + iTxStarted(false), + iRxSize(0) +{ +} + +WebSocketClient::WebSocketClient(Client& aClient, const String& aServerName, uint16_t aServerPort) + : HttpClient(aClient, aServerName, aServerPort), + iTxStarted(false), + iRxSize(0) +{ +} + +WebSocketClient::WebSocketClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort) + : HttpClient(aClient, aServerAddress, aServerPort), + iTxStarted(false), + iRxSize(0) +{ +} + +int WebSocketClient::begin(const char* aPath) +{ + // start the GET request + beginRequest(); + connectionKeepAlive(); + int status = get(aPath); + + if (status == 0) + { + uint8_t randomKey[16]; + char base64RandomKey[25]; + + // create a random key for the connection upgrade + for (int i = 0; i < (int)sizeof(randomKey); i++) + { + randomKey[i] = random(0x01, 0xff); + } + memset(base64RandomKey, 0x00, sizeof(base64RandomKey)); + b64_encode(randomKey, sizeof(randomKey), (unsigned char*)base64RandomKey, sizeof(base64RandomKey)); + + // start the connection upgrade sequence + sendHeader("Upgrade", "websocket"); + sendHeader("Connection", "Upgrade"); + sendHeader("Sec-WebSocket-Key", base64RandomKey); + sendHeader("Sec-WebSocket-Version", "13"); + endRequest(); + + status = responseStatusCode(); + + if (status > 0) + { + skipResponseHeaders(); + } + } + + iRxSize = 0; + + // status code of 101 means success + return (status == 101) ? 0 : status; +} + +int WebSocketClient::begin(const String& aPath) +{ + return begin(aPath.c_str()); +} + +int WebSocketClient::beginMessage(int aType) +{ + if (iTxStarted) + { + // fail TX already started + return 1; + } + + iTxStarted = true; + iTxMessageType = (aType & 0xf); + iTxSize = 0; + + return 0; +} + +int WebSocketClient::endMessage() +{ + if (!iTxStarted) + { + // fail TX not started + return 1; + } + + // send FIN + the message type (opcode) + HttpClient::write(0x80 | iTxMessageType); + + // the message is masked (0x80) + // send the length + if (iTxSize < 126) + { + HttpClient::write(0x80 | (uint8_t)iTxSize); + } + else if (iTxSize < 0xffff) + { + HttpClient::write(0x80 | 126); + HttpClient::write((iTxSize >> 8) & 0xff); + HttpClient::write((iTxSize >> 0) & 0xff); + } + else + { + HttpClient::write(0x80 | 127); + HttpClient::write((iTxSize >> 56) & 0xff); + HttpClient::write((iTxSize >> 48) & 0xff); + HttpClient::write((iTxSize >> 40) & 0xff); + HttpClient::write((iTxSize >> 32) & 0xff); + HttpClient::write((iTxSize >> 24) & 0xff); + HttpClient::write((iTxSize >> 16) & 0xff); + HttpClient::write((iTxSize >> 8) & 0xff); + HttpClient::write((iTxSize >> 0) & 0xff); + } + + uint8_t maskKey[4]; + + // create a random mask for the data and send + for (int i = 0; i < (int)sizeof(maskKey); i++) + { + maskKey[i] = random(0xff); + } + HttpClient::write(maskKey, sizeof(maskKey)); + + // mask the data and send + for (int i = 0; i < (int)iTxSize; i++) { + iTxBuffer[i] ^= maskKey[i % sizeof(maskKey)]; + } + + size_t txSize = iTxSize; + + iTxStarted = false; + iTxSize = 0; + + return (HttpClient::write(iTxBuffer, txSize) == txSize) ? 0 : 1; +} + +size_t WebSocketClient::write(uint8_t aByte) +{ + return write(&aByte, sizeof(aByte)); +} + +size_t WebSocketClient::write(const uint8_t *aBuffer, size_t aSize) +{ + if (iState < eReadingBody) + { + // have not upgraded the connection yet + return HttpClient::write(aBuffer, aSize); + } + + if (!iTxStarted) + { + // fail TX not started + return 0; + } + + // check if the write size, fits in the buffer + if ((iTxSize + aSize) > sizeof(iTxBuffer)) + { + aSize = sizeof(iTxSize) - iTxSize; + } + + // copy data into the buffer + memcpy(iTxBuffer + iTxSize, aBuffer, aSize); + + iTxSize += aSize; + + return aSize; +} + +int WebSocketClient::parseMessage() +{ + flushRx(); + + // make sure 2 bytes (opcode + length) + // are available + if (HttpClient::available() < 2) + { + return 0; + } + + // read open code and length + uint8_t opcode = HttpClient::read(); + int length = HttpClient::read(); + + if ((opcode & 0x0f) == 0) + { + // continuation, use previous opcode and update flags + iRxOpCode |= opcode; + } + else + { + iRxOpCode = opcode; + } + + iRxMasked = (length & 0x80); + length &= 0x7f; + + // read the RX size + if (length < 126) + { + iRxSize = length; + } + else if (length == 126) + { + iRxSize = (HttpClient::read() << 8) | HttpClient::read(); + } + else + { + iRxSize = ((uint64_t)HttpClient::read() << 56) | + ((uint64_t)HttpClient::read() << 48) | + ((uint64_t)HttpClient::read() << 40) | + ((uint64_t)HttpClient::read() << 32) | + ((uint64_t)HttpClient::read() << 24) | + ((uint64_t)HttpClient::read() << 16) | + ((uint64_t)HttpClient::read() << 8) | + (uint64_t)HttpClient::read(); + } + + // read in the mask, if present + if (iRxMasked) + { + for (int i = 0; i < (int)sizeof(iRxMaskKey); i++) + { + iRxMaskKey[i] = HttpClient::read(); + } + } + + iRxMaskIndex = 0; + + if (TYPE_CONNECTION_CLOSE == messageType()) + { + flushRx(); + stop(); + iRxSize = 0; + } + else if (TYPE_PING == messageType()) + { + beginMessage(TYPE_PONG); + while(available()) + { + write(read()); + } + endMessage(); + + iRxSize = 0; + } + else if (TYPE_PONG == messageType()) + { + flushRx(); + iRxSize = 0; + } + + return iRxSize; +} + +int WebSocketClient::messageType() +{ + return (iRxOpCode & 0x0f); +} + +bool WebSocketClient::isFinal() +{ + return ((iRxOpCode & 0x80) != 0); +} + +String WebSocketClient::readString() +{ + int avail = available(); + String s; + + if (avail > 0) + { + s.reserve(avail); + + for (int i = 0; i < avail; i++) + { + s += (char)read(); + } + } + + return s; +} + +int WebSocketClient::ping() +{ + uint8_t pingData[16]; + + // create random data for the ping + for (int i = 0; i < (int)sizeof(pingData); i++) + { + pingData[i] = random(0xff); + } + + beginMessage(TYPE_PING); + write(pingData, sizeof(pingData)); + return endMessage(); +} + +int WebSocketClient::available() +{ + if (iState < eReadingBody) + { + return HttpClient::available(); + } + + return iRxSize; +} + +int WebSocketClient::read() +{ + byte b; + + if (read(&b, sizeof(b))) + { + return b; + } + + return -1; +} + +int WebSocketClient::read(uint8_t *aBuffer, size_t aSize) +{ + int readCount = HttpClient::read(aBuffer, aSize); + + if (readCount > 0) + { + iRxSize -= readCount; + + // unmask the RX data if needed + if (iRxMasked) + { + for (int i = 0; i < (int)aSize; i++, iRxMaskIndex++) + { + aBuffer[i] ^= iRxMaskKey[iRxMaskIndex % sizeof(iRxMaskKey)]; + } + } + } + + return readCount; +} + +int WebSocketClient::peek() +{ + int p = HttpClient::peek(); + + if (p != -1 && iRxMasked) + { + // unmask the RX data if needed + p = (uint8_t)p ^ iRxMaskKey[iRxMaskIndex % sizeof(iRxMaskKey)]; + } + + return p; +} + +void WebSocketClient::flushRx() +{ + while(available()) + { + read(); + } +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/WebSocketClient.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/WebSocketClient.h new file mode 100644 index 0000000..4b009e6 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/WebSocketClient.h @@ -0,0 +1,99 @@ +// (c) Copyright Arduino. 2016 +// Released under Apache License, version 2.0 + +#ifndef WebSocketClient_h +#define WebSocketClient_h + +#include + +#include "HttpClient.h" + +static const int TYPE_CONTINUATION = 0x0; +static const int TYPE_TEXT = 0x1; +static const int TYPE_BINARY = 0x2; +static const int TYPE_CONNECTION_CLOSE = 0x8; +static const int TYPE_PING = 0x9; +static const int TYPE_PONG = 0xa; + +class WebSocketClient : public HttpClient +{ +public: + WebSocketClient(Client& aClient, const char* aServerName, uint16_t aServerPort = HttpClient::kHttpPort); + WebSocketClient(Client& aClient, const String& aServerName, uint16_t aServerPort = HttpClient::kHttpPort); + WebSocketClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort = HttpClient::kHttpPort); + + /** Start the Web Socket connection to the specified path + @param aURLPath Path to use in request (optional, "/" is used by default) + @return 0 if successful, else error + */ + int begin(const char* aPath = "/"); + int begin(const String& aPath); + + /** Begin to send a message of type (TYPE_TEXT or TYPE_BINARY) + Use the write or Stream API's to set message content, followed by endMessage + to complete the message. + @param aURLPath Path to use in request + @return 0 if successful, else error + */ + int beginMessage(int aType); + + /** Completes sending of a message started by beginMessage + @return 0 if successful, else error + */ + int endMessage(); + + /** Try to parse an incoming messages + @return 0 if no message available, else size of parsed message + */ + int parseMessage(); + + /** Returns type of current parsed message + @return type of current parsedMessage (TYPE_TEXT or TYPE_BINARY) + */ + int messageType(); + + /** Returns if the current message is the final chunk of a split + message + @return true for final message, false otherwise + */ + bool isFinal(); + + /** Read the current messages as a string + @return current message as a string + */ + String readString(); + + /** Send a ping + @return 0 if successful, else error + */ + int ping(); + + // Inherited from Print + virtual size_t write(uint8_t aByte); + virtual size_t write(const uint8_t *aBuffer, size_t aSize); + // Inherited from Stream + virtual int available(); + /** Read the next byte from the server. + @return Byte read or -1 if there are no bytes available. + */ + virtual int read(); + virtual int read(uint8_t *buf, size_t size); + virtual int peek(); + +private: + void flushRx(); + +private: + bool iTxStarted; + uint8_t iTxMessageType; + uint8_t iTxBuffer[128]; + uint64_t iTxSize; + + uint8_t iRxOpCode; + uint64_t iRxSize; + bool iRxMasked; + int iRxMaskIndex; + uint8_t iRxMaskKey[4]; +}; + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/b64.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/b64.cpp new file mode 100644 index 0000000..683d60a --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/b64.cpp @@ -0,0 +1,72 @@ +// Simple Base64 code +// (c) Copyright 2010 MCQN Ltd. +// Released under Apache License, version 2.0 + +#include "b64.h" + +/* Simple test program +#include +void main() +{ + char* in = "amcewen"; + char out[22]; + + b64_encode(in, 15, out, 22); + out[21] = '\0'; + + printf(out); +} +*/ + +int b64_encode(const unsigned char* aInput, int aInputLen, unsigned char* aOutput, int aOutputLen) +{ + // Work out if we've got enough space to encode the input + // Every 6 bits of input becomes a byte of output + if (aOutputLen < (aInputLen*8)/6) + { + // FIXME Should we return an error here, or just the length + return (aInputLen*8)/6; + } + + // If we get here we've got enough space to do the encoding + + const char* b64_dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + if (aInputLen == 3) + { + aOutput[0] = b64_dictionary[aInput[0] >> 2]; + aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4|(aInput[1]>>4)]; + aOutput[2] = b64_dictionary[(aInput[1]&0x0F)<<2|(aInput[2]>>6)]; + aOutput[3] = b64_dictionary[aInput[2]&0x3F]; + } + else if (aInputLen == 2) + { + aOutput[0] = b64_dictionary[aInput[0] >> 2]; + aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4|(aInput[1]>>4)]; + aOutput[2] = b64_dictionary[(aInput[1]&0x0F)<<2]; + aOutput[3] = '='; + } + else if (aInputLen == 1) + { + aOutput[0] = b64_dictionary[aInput[0] >> 2]; + aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4]; + aOutput[2] = '='; + aOutput[3] = '='; + } + else + { + // Break the input into 3-byte chunks and process each of them + int i; + for (i = 0; i < aInputLen/3; i++) + { + b64_encode(&aInput[i*3], 3, &aOutput[i*4], 4); + } + if (aInputLen % 3 > 0) + { + // It doesn't fit neatly into a 3-byte chunk, so process what's left + b64_encode(&aInput[i*3], aInputLen % 3, &aOutput[i*4], aOutputLen - (i*4)); + } + } + + return ((aInputLen+2)/3)*4; +} + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/b64.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/b64.h new file mode 100644 index 0000000..cdb1226 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/b64.h @@ -0,0 +1,6 @@ +#ifndef b64_h +#define b64_h + +int b64_encode(const unsigned char* aInput, int aInputLen, unsigned char* aOutput, int aOutputLen); + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/.github/ISSUE_TEMPLATE.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..f0e2614 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,46 @@ +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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..7b641eb --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,26 @@ +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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/README.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/README.md new file mode 100644 index 0000000..661e18d --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/README.md @@ -0,0 +1,42 @@ +This is a fork of JeeLab's fantastic real time clock library for Arduino. + +For details on using this library with an RTC module like the DS1307, PCF8523, or DS3231, see the guide at: https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/overview + +To download. click the DOWNLOADS button to the right, and rename the uncompressed folder RTClib. + +Place the RTClib folder in your *arduinosketchfolder*/libraries/ folder. +You may need to create the libraries subfolder if its your first library. Restart the IDE. + +Please note that dayOfTheWeek() ranges from 0 to 6 inclusive with 0 being 'Sunday' + + + +## Compatibility + +MCU | Tested Works | Doesn't Work | Not Tested | Notes +------------------ | :----------: | :----------: | :---------: | ----- +Atmega328 @ 16MHz | X | | | +Atmega328 @ 12MHz | X | | | +Atmega32u4 @ 16MHz | X | | | Use SDA/SCL on pins D3 & D2 +Atmega32u4 @ 8MHz | X | | | Use SDA/SCL on pins D3 & D2 +ESP8266 | X | | | SDA/SCL default to pins 4 & 5 but any two pins can be assigned as SDA/SCL using Wire.begin(SDA,SCL) +Atmega2560 @ 16MHz | X | | | Use SDA/SCL on Pins 20 & 21 +ATSAM3X8E | X | | | Use SDA1 and SCL1 +ATSAM21D | X | | | +ATtiny85 @ 16MHz | X | | | +ATtiny85 @ 8MHz | X | | | +Intel Curie @ 32MHz | | | X | +STM32F2 | | | X | + + * ATmega328 @ 16MHz : Arduino UNO, Adafruit Pro Trinket 5V, Adafruit Metro 328, Adafruit Metro Mini + * ATmega328 @ 12MHz : Adafruit Pro Trinket 3V + * ATmega32u4 @ 16MHz : Arduino Leonardo, Arduino Micro, Arduino Yun, Teensy 2.0 + * ATmega32u4 @ 8MHz : Adafruit Flora, Bluefruit Micro + * ESP8266 : Adafruit Huzzah + * ATmega2560 @ 16MHz : Arduino Mega + * ATSAM3X8E : Arduino Due + * ATSAM21D : Arduino Zero, M0 Pro + * ATtiny85 @ 16MHz : Adafruit Trinket 5V + * ATtiny85 @ 8MHz : Adafruit Gemma, Arduino Gemma, Adafruit Trinket 3V + + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/RTClib.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/RTClib.cpp new file mode 100644 index 0000000..a08dfe9 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/RTClib.cpp @@ -0,0 +1,506 @@ +// Code by JeeLabs http://news.jeelabs.org/code/ +// Released to the public domain! Enjoy! + +#include +#include "RTClib.h" +#ifdef __AVR__ + #include +#elif defined(ESP8266) + #include +#elif defined(ARDUINO_ARCH_SAMD) +// nothing special needed +#elif defined(ARDUINO_SAM_DUE) + #define PROGMEM + #define pgm_read_byte(addr) (*(const unsigned char *)(addr)) + #define Wire Wire1 +#endif + + + +#if (ARDUINO >= 100) + #include // capital A so it is error prone on case-sensitive filesystems + // Macro to deal with the difference in I2C write functions from old and new Arduino versions. + #define _I2C_WRITE write + #define _I2C_READ read +#else + #include + #define _I2C_WRITE send + #define _I2C_READ receive +#endif + + +static uint8_t read_i2c_register(uint8_t addr, uint8_t reg) { + Wire.beginTransmission(addr); + Wire._I2C_WRITE((byte)reg); + Wire.endTransmission(); + + Wire.requestFrom(addr, (byte)1); + return Wire._I2C_READ(); +} + +static void write_i2c_register(uint8_t addr, uint8_t reg, uint8_t val) { + Wire.beginTransmission(addr); + Wire._I2C_WRITE((byte)reg); + Wire._I2C_WRITE((byte)val); + Wire.endTransmission(); +} + + +//////////////////////////////////////////////////////////////////////////////// +// utility code, some of this could be exposed in the DateTime API if needed + +const uint8_t daysInMonth [] PROGMEM = { 31,28,31,30,31,30,31,31,30,31,30,31 }; + +// number of days since 2000/01/01, valid for 2001..2099 +static uint16_t date2days(uint16_t y, uint8_t m, uint8_t d) { + if (y >= 2000) + y -= 2000; + uint16_t days = d; + for (uint8_t i = 1; i < m; ++i) + days += pgm_read_byte(daysInMonth + i - 1); + if (m > 2 && y % 4 == 0) + ++days; + return days + 365 * y + (y + 3) / 4 - 1; +} + +static long time2long(uint16_t days, uint8_t h, uint8_t m, uint8_t s) { + return ((days * 24L + h) * 60 + m) * 60 + s; +} + +//////////////////////////////////////////////////////////////////////////////// +// DateTime implementation - ignores time zones and DST changes +// NOTE: also ignores leap seconds, see http://en.wikipedia.org/wiki/Leap_second + +DateTime::DateTime (uint32_t t) { + t -= SECONDS_FROM_1970_TO_2000; // bring to 2000 timestamp from 1970 + + ss = t % 60; + t /= 60; + mm = t % 60; + t /= 60; + hh = t % 24; + uint16_t days = t / 24; + uint8_t leap; + for (yOff = 0; ; ++yOff) { + leap = yOff % 4 == 0; + if (days < 365 + leap) + break; + days -= 365 + leap; + } + for (m = 1; ; ++m) { + uint8_t daysPerMonth = pgm_read_byte(daysInMonth + m - 1); + if (leap && m == 2) + ++daysPerMonth; + if (days < daysPerMonth) + break; + days -= daysPerMonth; + } + d = days + 1; +} + +DateTime::DateTime (uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t min, uint8_t sec) { + if (year >= 2000) + year -= 2000; + yOff = year; + m = month; + d = day; + hh = hour; + mm = min; + ss = sec; +} + +DateTime::DateTime (const DateTime& copy): + yOff(copy.yOff), + m(copy.m), + d(copy.d), + hh(copy.hh), + mm(copy.mm), + ss(copy.ss) +{} + +static uint8_t conv2d(const char* p) { + uint8_t v = 0; + if ('0' <= *p && *p <= '9') + v = *p - '0'; + return 10 * v + *++p - '0'; +} + +// A convenient constructor for using "the compiler's time": +// DateTime now (__DATE__, __TIME__); +// NOTE: using F() would further reduce the RAM footprint, see below. +DateTime::DateTime (const char* date, const char* time) { + // sample input: date = "Dec 26 2009", time = "12:34:56" + yOff = conv2d(date + 9); + // Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec + switch (date[0]) { + case 'J': m = (date[1] == 'a') ? 1 : ((date[2] == 'n') ? 6 : 7); break; + case 'F': m = 2; break; + case 'A': m = date[2] == 'r' ? 4 : 8; break; + case 'M': m = date[2] == 'r' ? 3 : 5; break; + case 'S': m = 9; break; + case 'O': m = 10; break; + case 'N': m = 11; break; + case 'D': m = 12; break; + } + d = conv2d(date + 4); + hh = conv2d(time); + mm = conv2d(time + 3); + ss = conv2d(time + 6); +} + +// A convenient constructor for using "the compiler's time": +// This version will save RAM by using PROGMEM to store it by using the F macro. +// DateTime now (F(__DATE__), F(__TIME__)); +DateTime::DateTime (const __FlashStringHelper* date, const __FlashStringHelper* time) { + // sample input: date = "Dec 26 2009", time = "12:34:56" + char buff[11]; + memcpy_P(buff, date, 11); + yOff = conv2d(buff + 9); + // Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec + switch (buff[0]) { + case 'J': m = (buff[1] == 'a') ? 1 : ((buff[2] == 'n') ? 6 : 7); break; + case 'F': m = 2; break; + case 'A': m = buff[2] == 'r' ? 4 : 8; break; + case 'M': m = buff[2] == 'r' ? 3 : 5; break; + case 'S': m = 9; break; + case 'O': m = 10; break; + case 'N': m = 11; break; + case 'D': m = 12; break; + } + d = conv2d(buff + 4); + memcpy_P(buff, time, 8); + hh = conv2d(buff); + mm = conv2d(buff + 3); + ss = conv2d(buff + 6); +} + +uint8_t DateTime::dayOfTheWeek() const { + uint16_t day = date2days(yOff, m, d); + return (day + 6) % 7; // Jan 1, 2000 is a Saturday, i.e. returns 6 +} + +uint32_t DateTime::unixtime(void) const { + uint32_t t; + uint16_t days = date2days(yOff, m, d); + t = time2long(days, hh, mm, ss); + t += SECONDS_FROM_1970_TO_2000; // seconds from 1970 to 2000 + + return t; +} + +long DateTime::secondstime(void) const { + long t; + uint16_t days = date2days(yOff, m, d); + t = time2long(days, hh, mm, ss); + return t; +} + +DateTime DateTime::operator+(const TimeSpan& span) { + return DateTime(unixtime()+span.totalseconds()); +} + +DateTime DateTime::operator-(const TimeSpan& span) { + return DateTime(unixtime()-span.totalseconds()); +} + +TimeSpan DateTime::operator-(const DateTime& right) { + return TimeSpan(unixtime()-right.unixtime()); +} + +//////////////////////////////////////////////////////////////////////////////// +// TimeSpan implementation + +TimeSpan::TimeSpan (int32_t seconds): + _seconds(seconds) +{} + +TimeSpan::TimeSpan (int16_t days, int8_t hours, int8_t minutes, int8_t seconds): + _seconds((int32_t)days*86400L + (int32_t)hours*3600 + (int32_t)minutes*60 + seconds) +{} + +TimeSpan::TimeSpan (const TimeSpan& copy): + _seconds(copy._seconds) +{} + +TimeSpan TimeSpan::operator+(const TimeSpan& right) { + return TimeSpan(_seconds+right._seconds); +} + +TimeSpan TimeSpan::operator-(const TimeSpan& right) { + return TimeSpan(_seconds-right._seconds); +} + +//////////////////////////////////////////////////////////////////////////////// +// RTC_DS1307 implementation + +static uint8_t bcd2bin (uint8_t val) { return val - 6 * (val >> 4); } +static uint8_t bin2bcd (uint8_t val) { return val + 6 * (val / 10); } + +boolean RTC_DS1307::begin(void) { + Wire.begin(); + return true; +} + +uint8_t RTC_DS1307::isrunning(void) { + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE((byte)0); + Wire.endTransmission(); + + Wire.requestFrom(DS1307_ADDRESS, 1); + uint8_t ss = Wire._I2C_READ(); + return !(ss>>7); +} + +void RTC_DS1307::adjust(const DateTime& dt) { + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE((byte)0); // start at location 0 + Wire._I2C_WRITE(bin2bcd(dt.second())); + Wire._I2C_WRITE(bin2bcd(dt.minute())); + Wire._I2C_WRITE(bin2bcd(dt.hour())); + Wire._I2C_WRITE(bin2bcd(0)); + Wire._I2C_WRITE(bin2bcd(dt.day())); + Wire._I2C_WRITE(bin2bcd(dt.month())); + Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); + Wire.endTransmission(); +} + +DateTime RTC_DS1307::now() { + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE((byte)0); + Wire.endTransmission(); + + Wire.requestFrom(DS1307_ADDRESS, 7); + uint8_t ss = bcd2bin(Wire._I2C_READ() & 0x7F); + uint8_t mm = bcd2bin(Wire._I2C_READ()); + uint8_t hh = bcd2bin(Wire._I2C_READ()); + Wire._I2C_READ(); + uint8_t d = bcd2bin(Wire._I2C_READ()); + uint8_t m = bcd2bin(Wire._I2C_READ()); + uint16_t y = bcd2bin(Wire._I2C_READ()) + 2000; + + return DateTime (y, m, d, hh, mm, ss); +} + +Ds1307SqwPinMode RTC_DS1307::readSqwPinMode() { + int mode; + + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE(DS1307_CONTROL); + Wire.endTransmission(); + + Wire.requestFrom((uint8_t)DS1307_ADDRESS, (uint8_t)1); + mode = Wire._I2C_READ(); + + mode &= 0x93; + return static_cast(mode); +} + +void RTC_DS1307::writeSqwPinMode(Ds1307SqwPinMode mode) { + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE(DS1307_CONTROL); + Wire._I2C_WRITE(mode); + Wire.endTransmission(); +} + +void RTC_DS1307::readnvram(uint8_t* buf, uint8_t size, uint8_t address) { + int addrByte = DS1307_NVRAM + address; + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE(addrByte); + Wire.endTransmission(); + + Wire.requestFrom((uint8_t) DS1307_ADDRESS, size); + for (uint8_t pos = 0; pos < size; ++pos) { + buf[pos] = Wire._I2C_READ(); + } +} + +void RTC_DS1307::writenvram(uint8_t address, uint8_t* buf, uint8_t size) { + int addrByte = DS1307_NVRAM + address; + Wire.beginTransmission(DS1307_ADDRESS); + Wire._I2C_WRITE(addrByte); + for (uint8_t pos = 0; pos < size; ++pos) { + Wire._I2C_WRITE(buf[pos]); + } + Wire.endTransmission(); +} + +uint8_t RTC_DS1307::readnvram(uint8_t address) { + uint8_t data; + readnvram(&data, 1, address); + return data; +} + +void RTC_DS1307::writenvram(uint8_t address, uint8_t data) { + writenvram(address, &data, 1); +} + +//////////////////////////////////////////////////////////////////////////////// +// RTC_Millis implementation + +long RTC_Millis::offset = 0; + +void RTC_Millis::adjust(const DateTime& dt) { + offset = dt.unixtime() - millis() / 1000; +} + +DateTime RTC_Millis::now() { + return (uint32_t)(offset + millis() / 1000); +} + +//////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////////////// +// RTC_PCF8563 implementation + +boolean RTC_PCF8523::begin(void) { + Wire.begin(); + return true; +} + +boolean RTC_PCF8523::initialized(void) { + Wire.beginTransmission(PCF8523_ADDRESS); + Wire._I2C_WRITE((byte)PCF8523_CONTROL_3); + Wire.endTransmission(); + + Wire.requestFrom(PCF8523_ADDRESS, 1); + uint8_t ss = Wire._I2C_READ(); + return ((ss & 0xE0) != 0xE0); +} + +void RTC_PCF8523::adjust(const DateTime& dt) { + Wire.beginTransmission(PCF8523_ADDRESS); + Wire._I2C_WRITE((byte)3); // start at location 3 + Wire._I2C_WRITE(bin2bcd(dt.second())); + Wire._I2C_WRITE(bin2bcd(dt.minute())); + Wire._I2C_WRITE(bin2bcd(dt.hour())); + Wire._I2C_WRITE(bin2bcd(dt.day())); + Wire._I2C_WRITE(bin2bcd(0)); // skip weekdays + Wire._I2C_WRITE(bin2bcd(dt.month())); + Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); + Wire.endTransmission(); + + // set to battery switchover mode + Wire.beginTransmission(PCF8523_ADDRESS); + Wire._I2C_WRITE((byte)PCF8523_CONTROL_3); + Wire._I2C_WRITE((byte)0x00); + Wire.endTransmission(); +} + +DateTime RTC_PCF8523::now() { + Wire.beginTransmission(PCF8523_ADDRESS); + Wire._I2C_WRITE((byte)3); + Wire.endTransmission(); + + Wire.requestFrom(PCF8523_ADDRESS, 7); + uint8_t ss = bcd2bin(Wire._I2C_READ() & 0x7F); + uint8_t mm = bcd2bin(Wire._I2C_READ()); + uint8_t hh = bcd2bin(Wire._I2C_READ()); + uint8_t d = bcd2bin(Wire._I2C_READ()); + Wire._I2C_READ(); // skip 'weekdays' + uint8_t m = bcd2bin(Wire._I2C_READ()); + uint16_t y = bcd2bin(Wire._I2C_READ()) + 2000; + + return DateTime (y, m, d, hh, mm, ss); +} + +Pcf8523SqwPinMode RTC_PCF8523::readSqwPinMode() { + int mode; + + Wire.beginTransmission(PCF8523_ADDRESS); + Wire._I2C_WRITE(PCF8523_CLKOUTCONTROL); + Wire.endTransmission(); + + Wire.requestFrom((uint8_t)PCF8523_ADDRESS, (uint8_t)1); + mode = Wire._I2C_READ(); + + mode >>= 3; + mode &= 0x7; + return static_cast(mode); +} + +void RTC_PCF8523::writeSqwPinMode(Pcf8523SqwPinMode mode) { + Wire.beginTransmission(PCF8523_ADDRESS); + Wire._I2C_WRITE(PCF8523_CLKOUTCONTROL); + Wire._I2C_WRITE(mode << 3); + Wire.endTransmission(); +} + + + + +//////////////////////////////////////////////////////////////////////////////// +// RTC_DS3231 implementation + +boolean RTC_DS3231::begin(void) { + Wire.begin(); + return true; +} + +bool RTC_DS3231::lostPower(void) { + return (read_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG) >> 7); +} + +void RTC_DS3231::adjust(const DateTime& dt) { + Wire.beginTransmission(DS3231_ADDRESS); + Wire._I2C_WRITE((byte)0); // start at location 0 + Wire._I2C_WRITE(bin2bcd(dt.second())); + Wire._I2C_WRITE(bin2bcd(dt.minute())); + Wire._I2C_WRITE(bin2bcd(dt.hour())); + Wire._I2C_WRITE(bin2bcd(0)); + Wire._I2C_WRITE(bin2bcd(dt.day())); + Wire._I2C_WRITE(bin2bcd(dt.month())); + Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); + Wire.endTransmission(); + + uint8_t statreg = read_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG); + statreg &= ~0x80; // flip OSF bit + write_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG, statreg); +} + +DateTime RTC_DS3231::now() { + Wire.beginTransmission(DS3231_ADDRESS); + Wire._I2C_WRITE((byte)0); + Wire.endTransmission(); + + Wire.requestFrom(DS3231_ADDRESS, 7); + uint8_t ss = bcd2bin(Wire._I2C_READ() & 0x7F); + uint8_t mm = bcd2bin(Wire._I2C_READ()); + uint8_t hh = bcd2bin(Wire._I2C_READ()); + Wire._I2C_READ(); + uint8_t d = bcd2bin(Wire._I2C_READ()); + uint8_t m = bcd2bin(Wire._I2C_READ()); + uint16_t y = bcd2bin(Wire._I2C_READ()) + 2000; + + return DateTime (y, m, d, hh, mm, ss); +} + +Ds3231SqwPinMode RTC_DS3231::readSqwPinMode() { + int mode; + + Wire.beginTransmission(DS3231_ADDRESS); + Wire._I2C_WRITE(DS3231_CONTROL); + Wire.endTransmission(); + + Wire.requestFrom((uint8_t)DS3231_ADDRESS, (uint8_t)1); + mode = Wire._I2C_READ(); + + mode &= 0x93; + return static_cast(mode); +} + +void RTC_DS3231::writeSqwPinMode(Ds3231SqwPinMode mode) { + uint8_t ctrl; + ctrl = read_i2c_register(DS3231_ADDRESS, DS3231_CONTROL); + + ctrl &= ~0x04; // turn off INTCON + ctrl &= ~0x18; // set freq bits to 0 + + if (mode == DS3231_OFF) { + ctrl |= 0x04; // turn on INTCN + } else { + ctrl |= mode; + } + write_i2c_register(DS3231_ADDRESS, DS3231_CONTROL, ctrl); + + //Serial.println( read_i2c_register(DS3231_ADDRESS, DS3231_CONTROL), HEX); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/RTClib.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/RTClib.h new file mode 100644 index 0000000..abf5d9b --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/RTClib.h @@ -0,0 +1,135 @@ +// Code by JeeLabs http://news.jeelabs.org/code/ +// Released to the public domain! Enjoy! + +#ifndef _RTCLIB_H_ +#define _RTCLIB_H_ + +#include +class TimeSpan; + + +#define PCF8523_ADDRESS 0x68 +#define PCF8523_CLKOUTCONTROL 0x0F +#define PCF8523_CONTROL_3 0x02 + +#define DS1307_ADDRESS 0x68 +#define DS1307_CONTROL 0x07 +#define DS1307_NVRAM 0x08 + +#define DS3231_ADDRESS 0x68 +#define DS3231_CONTROL 0x0E +#define DS3231_STATUSREG 0x0F + +#define SECONDS_PER_DAY 86400L + +#define SECONDS_FROM_1970_TO_2000 946684800 + + + +// Simple general-purpose date/time class (no TZ / DST / leap second handling!) +class DateTime { +public: + DateTime (uint32_t t =0); + DateTime (uint16_t year, uint8_t month, uint8_t day, + uint8_t hour =0, uint8_t min =0, uint8_t sec =0); + DateTime (const DateTime& copy); + DateTime (const char* date, const char* time); + DateTime (const __FlashStringHelper* date, const __FlashStringHelper* time); + uint16_t year() const { return 2000 + yOff; } + uint8_t month() const { return m; } + uint8_t day() const { return d; } + uint8_t hour() const { return hh; } + uint8_t minute() const { return mm; } + uint8_t second() const { return ss; } + uint8_t dayOfTheWeek() const; + + // 32-bit times as seconds since 1/1/2000 + long secondstime() const; + // 32-bit times as seconds since 1/1/1970 + uint32_t unixtime(void) const; + + DateTime operator+(const TimeSpan& span); + DateTime operator-(const TimeSpan& span); + TimeSpan operator-(const DateTime& right); + +protected: + uint8_t yOff, m, d, hh, mm, ss; +}; + +// Timespan which can represent changes in time with seconds accuracy. +class TimeSpan { +public: + TimeSpan (int32_t seconds = 0); + TimeSpan (int16_t days, int8_t hours, int8_t minutes, int8_t seconds); + TimeSpan (const TimeSpan& copy); + int16_t days() const { return _seconds / 86400L; } + int8_t hours() const { return _seconds / 3600 % 24; } + int8_t minutes() const { return _seconds / 60 % 60; } + int8_t seconds() const { return _seconds % 60; } + int32_t totalseconds() const { return _seconds; } + + TimeSpan operator+(const TimeSpan& right); + TimeSpan operator-(const TimeSpan& right); + +protected: + int32_t _seconds; +}; + +// RTC based on the DS1307 chip connected via I2C and the Wire library +enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 }; + +class RTC_DS1307 { +public: + boolean begin(void); + static void adjust(const DateTime& dt); + uint8_t isrunning(void); + static DateTime now(); + static Ds1307SqwPinMode readSqwPinMode(); + static void writeSqwPinMode(Ds1307SqwPinMode mode); + uint8_t readnvram(uint8_t address); + void readnvram(uint8_t* buf, uint8_t size, uint8_t address); + void writenvram(uint8_t address, uint8_t data); + void writenvram(uint8_t address, uint8_t* buf, uint8_t size); +}; + +// RTC based on the DS3231 chip connected via I2C and the Wire library +enum Ds3231SqwPinMode { DS3231_OFF = 0x01, DS3231_SquareWave1Hz = 0x00, DS3231_SquareWave1kHz = 0x08, DS3231_SquareWave4kHz = 0x10, DS3231_SquareWave8kHz = 0x18 }; + +class RTC_DS3231 { +public: + boolean begin(void); + static void adjust(const DateTime& dt); + bool lostPower(void); + static DateTime now(); + static Ds3231SqwPinMode readSqwPinMode(); + static void writeSqwPinMode(Ds3231SqwPinMode mode); +}; + + +// RTC based on the PCF8523 chip connected via I2C and the Wire library +enum Pcf8523SqwPinMode { PCF8523_OFF = 7, PCF8523_SquareWave1HZ = 6, PCF8523_SquareWave32HZ = 5, PCF8523_SquareWave1kHz = 4, PCF8523_SquareWave4kHz = 3, PCF8523_SquareWave8kHz = 2, PCF8523_SquareWave16kHz = 1, PCF8523_SquareWave32kHz = 0 }; + +class RTC_PCF8523 { +public: + boolean begin(void); + void adjust(const DateTime& dt); + boolean initialized(void); + static DateTime now(); + + Pcf8523SqwPinMode readSqwPinMode(); + void writeSqwPinMode(Pcf8523SqwPinMode mode); +}; + +// RTC using the internal millis() clock, has to be initialized before use +// NOTE: this clock won't be correct once the millis() timer rolls over (>49d?) +class RTC_Millis { +public: + static void begin(const DateTime& dt) { adjust(dt); } + static void adjust(const DateTime& dt); + static DateTime now(); + +protected: + static long offset; +}; + +#endif // _RTCLIB_H_ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/datecalc/datecalc.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/datecalc/datecalc.ino new file mode 100644 index 0000000..771dacd --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/datecalc/datecalc.ino @@ -0,0 +1,111 @@ +// Simple date conversions and calculations + +#include +#include "RTClib.h" + +#if defined(ARDUINO_ARCH_SAMD) +// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! + #define Serial SerialUSB +#endif + +void showDate(const char* txt, const DateTime& dt) { + Serial.print(txt); + Serial.print(' '); + Serial.print(dt.year(), DEC); + Serial.print('/'); + Serial.print(dt.month(), DEC); + Serial.print('/'); + Serial.print(dt.day(), DEC); + Serial.print(' '); + Serial.print(dt.hour(), DEC); + Serial.print(':'); + Serial.print(dt.minute(), DEC); + Serial.print(':'); + Serial.print(dt.second(), DEC); + + Serial.print(" = "); + Serial.print(dt.unixtime()); + Serial.print("s / "); + Serial.print(dt.unixtime() / 86400L); + Serial.print("d since 1970"); + + Serial.println(); +} + +void showTimeSpan(const char* txt, const TimeSpan& ts) { + Serial.print(txt); + Serial.print(" "); + Serial.print(ts.days(), DEC); + Serial.print(" days "); + Serial.print(ts.hours(), DEC); + Serial.print(" hours "); + Serial.print(ts.minutes(), DEC); + Serial.print(" minutes "); + Serial.print(ts.seconds(), DEC); + Serial.print(" seconds ("); + Serial.print(ts.totalseconds(), DEC); + Serial.print(" total seconds)"); + Serial.println(); +} + +void setup () { + +#ifndef ESP8266 + while (!Serial); // for Leonardo/Micro/Zero +#endif + Serial.begin(57600); + + DateTime dt0 (0, 1, 1, 0, 0, 0); + showDate("dt0", dt0); + + DateTime dt1 (1, 1, 1, 0, 0, 0); + showDate("dt1", dt1); + + DateTime dt2 (2009, 1, 1, 0, 0, 0); + showDate("dt2", dt2); + + DateTime dt3 (2009, 1, 2, 0, 0, 0); + showDate("dt3", dt3); + + DateTime dt4 (2009, 1, 27, 0, 0, 0); + showDate("dt4", dt4); + + DateTime dt5 (2009, 2, 27, 0, 0, 0); + showDate("dt5", dt5); + + DateTime dt6 (2009, 12, 27, 0, 0, 0); + showDate("dt6", dt6); + + DateTime dt7 (dt6.unixtime() + 3600); // One hour later. + showDate("dt7", dt7); + + DateTime dt75 = dt6 + TimeSpan(0, 1, 0, 0); // One hour later with TimeSpan addition. + showDate("dt7.5", dt75); + + DateTime dt8 (dt6.unixtime() + 86400L); // One day later. + showDate("dt8", dt8); + + DateTime dt85 = dt6 + TimeSpan(1, 0, 0, 0); // One day later with TimeSpan addition. + showDate("dt8.5", dt85); + + DateTime dt9 (dt6.unixtime() + 7 * 86400L); // One week later. + showDate("dt9", dt9); + + DateTime dt95 = dt6 + TimeSpan(7, 0, 0, 0); // One week later with TimeSpan addition. + showDate("dt9.5", dt95); + + DateTime dt10 = dt6 + TimeSpan(0, 0, 42, 42); // Fourty two minutes and fourty two seconds later. + showDate("dt10", dt10); + + DateTime dt11 = dt6 - TimeSpan(7, 0, 0, 0); // One week ago. + showDate("dt11", dt11); + + TimeSpan ts1 = dt6 - dt5; + showTimeSpan("dt6-dt5", ts1); + + TimeSpan ts2 = dt10 - dt6; + showTimeSpan("dt10-dt6", ts2); +} + +void loop () { +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307/ds1307.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307/ds1307.ino new file mode 100644 index 0000000..7d9162f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307/ds1307.ino @@ -0,0 +1,71 @@ +// Date and time functions using a DS1307 RTC connected via I2C and Wire lib +#include +#include "RTClib.h" + +RTC_DS1307 rtc; + +char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; + +void setup () { + while (!Serial); // for Leonardo/Micro/Zero + + Serial.begin(57600); + if (! rtc.begin()) { + Serial.println("Couldn't find RTC"); + while (1); + } + + if (! rtc.isrunning()) { + Serial.println("RTC is NOT running!"); + // following line sets the RTC to the date & time this sketch was compiled + // rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); + // This line sets the RTC with an explicit date & time, for example to set + // January 21, 2014 at 3am you would call: + // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); + } +} + +void loop () { + DateTime now = rtc.now(); + + Serial.print(now.year(), DEC); + Serial.print('/'); + Serial.print(now.month(), DEC); + Serial.print('/'); + Serial.print(now.day(), DEC); + Serial.print(" ("); + Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); + Serial.print(") "); + Serial.print(now.hour(), DEC); + Serial.print(':'); + Serial.print(now.minute(), DEC); + Serial.print(':'); + Serial.print(now.second(), DEC); + Serial.println(); + + Serial.print(" since midnight 1/1/1970 = "); + Serial.print(now.unixtime()); + Serial.print("s = "); + Serial.print(now.unixtime() / 86400L); + Serial.println("d"); + + // calculate a date which is 7 days and 30 seconds into the future + DateTime future (now + TimeSpan(7,12,30,6)); + + Serial.print(" now + 7d + 30s: "); + Serial.print(future.year(), DEC); + Serial.print('/'); + Serial.print(future.month(), DEC); + Serial.print('/'); + Serial.print(future.day(), DEC); + Serial.print(' '); + Serial.print(future.hour(), DEC); + Serial.print(':'); + Serial.print(future.minute(), DEC); + Serial.print(':'); + Serial.print(future.second(), DEC); + Serial.println(); + + Serial.println(); + delay(3000); +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino new file mode 100644 index 0000000..c12c26c --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino @@ -0,0 +1,68 @@ +// SQW/OUT pin mode using a DS1307 RTC connected via I2C. +// +// According to the data sheet (http://datasheets.maxim-ic.com/en/ds/DS1307.pdf), the +// DS1307's SQW/OUT pin can be set to low, high, 1Hz, 4.096kHz, 8.192kHz, or 32.768kHz. +// +// This sketch reads the state of the pin, then iterates through the possible values at +// 5 second intervals. +// + +// NOTE: +// You must connect a pull up resistor (~10kohm) from the SQW pin up to VCC. Without +// this pull up the wave output will not work! + +#include +#include "RTClib.h" + +#if defined(ARDUINO_ARCH_SAMD) +// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! + #define Serial SerialUSB +#endif + +RTC_DS1307 rtc; + +int mode_index = 0; + +Ds1307SqwPinMode modes[] = {OFF, ON, SquareWave1HZ, SquareWave4kHz, SquareWave8kHz, SquareWave32kHz}; + + +void print_mode() { + Ds1307SqwPinMode mode = rtc.readSqwPinMode(); + + Serial.print("Sqw Pin Mode: "); + switch(mode) { + case OFF: Serial.println("OFF"); break; + case ON: Serial.println("ON"); break; + case SquareWave1HZ: Serial.println("1Hz"); break; + case SquareWave4kHz: Serial.println("4.096kHz"); break; + case SquareWave8kHz: Serial.println("8.192kHz"); break; + case SquareWave32kHz: Serial.println("32.768kHz"); break; + default: Serial.println("UNKNOWN"); break; + } +} + +void setup () { + +#ifndef ESP8266 + while (!Serial); // for Leonardo/Micro/Zero +#endif + + Serial.begin(57600); + if (! rtc.begin()) { + Serial.println("Couldn't find RTC"); + while (1); + } + + print_mode(); +} + +void loop () { + rtc.writeSqwPinMode(modes[mode_index++]); + print_mode(); + + if (mode_index > 5) { + mode_index = 0; + } + + delay(5000); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino new file mode 100644 index 0000000..0acd0cf --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino @@ -0,0 +1,63 @@ +// Example of using the non-volatile RAM storage on the DS1307. +// You can write up to 56 bytes from address 0 to 55. +// Data will be persisted as long as the DS1307 has battery power. + +#include +#include "RTClib.h" + +#if defined(ARDUINO_ARCH_SAMD) +// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! + #define Serial SerialUSB +#endif + +RTC_DS1307 rtc; + +void printnvram(uint8_t address) { + Serial.print("Address 0x"); + Serial.print(address, HEX); + Serial.print(" = 0x"); + Serial.println(rtc.readnvram(address), HEX); +} + +void setup () { + +#ifndef ESP8266 + while (!Serial); // for Leonardo/Micro/Zero +#endif + Serial.begin(57600); + rtc.begin(); + + // Print old RAM contents on startup. + Serial.println("Current NVRAM values:"); + for (int i = 0; i < 6; ++i) { + printnvram(i); + } + + // Write some bytes to non-volatile RAM storage. + // NOTE: You can only read and write from addresses 0 to 55 (i.e. 56 byte values). + Serial.println("Writing NVRAM values."); + // Example writing one byte at a time: + rtc.writenvram(0, 0xFE); + rtc.writenvram(1, 0xED); + // Example writing multiple bytes: + uint8_t writeData[4] = { 0xBE, 0xEF, 0x01, 0x02 }; + rtc.writenvram(2, writeData, 4); + + // Read bytes from non-volatile RAM storage. + Serial.println("Reading NVRAM values:"); + // Example reading one byte at a time. + Serial.println(rtc.readnvram(0), HEX); + Serial.println(rtc.readnvram(1), HEX); + // Example reading multiple bytes: + uint8_t readData[4] = {0}; + rtc.readnvram(readData, 4, 2); + Serial.println(readData[0], HEX); + Serial.println(readData[1], HEX); + Serial.println(readData[2], HEX); + Serial.println(readData[3], HEX); + +} + +void loop () { + // Do nothing in the loop. +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds3231/ds3231.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds3231/ds3231.ino new file mode 100644 index 0000000..b62d510 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds3231/ds3231.ino @@ -0,0 +1,77 @@ +// Date and time functions using a DS3231 RTC connected via I2C and Wire lib +#include +#include "RTClib.h" + +RTC_DS3231 rtc; + +char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; + +void setup () { + +#ifndef ESP8266 + while (!Serial); // for Leonardo/Micro/Zero +#endif + + Serial.begin(9600); + + delay(3000); // wait for console opening + + if (! rtc.begin()) { + Serial.println("Couldn't find RTC"); + while (1); + } + + if (rtc.lostPower()) { + Serial.println("RTC lost power, lets set the time!"); + // following line sets the RTC to the date & time this sketch was compiled + rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); + // This line sets the RTC with an explicit date & time, for example to set + // January 21, 2014 at 3am you would call: + // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); + } +} + +void loop () { + DateTime now = rtc.now(); + + Serial.print(now.year(), DEC); + Serial.print('/'); + Serial.print(now.month(), DEC); + Serial.print('/'); + Serial.print(now.day(), DEC); + Serial.print(" ("); + Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); + Serial.print(") "); + Serial.print(now.hour(), DEC); + Serial.print(':'); + Serial.print(now.minute(), DEC); + Serial.print(':'); + Serial.print(now.second(), DEC); + Serial.println(); + + Serial.print(" since midnight 1/1/1970 = "); + Serial.print(now.unixtime()); + Serial.print("s = "); + Serial.print(now.unixtime() / 86400L); + Serial.println("d"); + + // calculate a date which is 7 days and 30 seconds into the future + DateTime future (now + TimeSpan(7,12,30,6)); + + Serial.print(" now + 7d + 30s: "); + Serial.print(future.year(), DEC); + Serial.print('/'); + Serial.print(future.month(), DEC); + Serial.print('/'); + Serial.print(future.day(), DEC); + Serial.print(' '); + Serial.print(future.hour(), DEC); + Serial.print(':'); + Serial.print(future.minute(), DEC); + Serial.print(':'); + Serial.print(future.second(), DEC); + Serial.println(); + + Serial.println(); + delay(3000); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/pcf8523/pcf8523.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/pcf8523/pcf8523.ino new file mode 100644 index 0000000..fc7dfe8 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/pcf8523/pcf8523.ino @@ -0,0 +1,74 @@ +// Date and time functions using a DS1307 RTC connected via I2C and Wire lib +#include +#include "RTClib.h" + +RTC_PCF8523 rtc; + +char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; + +void setup () { + + while (!Serial) { + delay(1); // for Leonardo/Micro/Zero + } + + Serial.begin(57600); + if (! rtc.begin()) { + Serial.println("Couldn't find RTC"); + while (1); + } + + if (! rtc.initialized()) { + Serial.println("RTC is NOT running!"); + // following line sets the RTC to the date & time this sketch was compiled + // rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); + // This line sets the RTC with an explicit date & time, for example to set + // January 21, 2014 at 3am you would call: + // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); + } +} + +void loop () { + DateTime now = rtc.now(); + + Serial.print(now.year(), DEC); + Serial.print('/'); + Serial.print(now.month(), DEC); + Serial.print('/'); + Serial.print(now.day(), DEC); + Serial.print(" ("); + Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); + Serial.print(") "); + Serial.print(now.hour(), DEC); + Serial.print(':'); + Serial.print(now.minute(), DEC); + Serial.print(':'); + Serial.print(now.second(), DEC); + Serial.println(); + + Serial.print(" since midnight 1/1/1970 = "); + Serial.print(now.unixtime()); + Serial.print("s = "); + Serial.print(now.unixtime() / 86400L); + Serial.println("d"); + + // calculate a date which is 7 days and 30 seconds into the future + DateTime future (now + TimeSpan(7,12,30,6)); + + Serial.print(" now + 7d + 30s: "); + Serial.print(future.year(), DEC); + Serial.print('/'); + Serial.print(future.month(), DEC); + Serial.print('/'); + Serial.print(future.day(), DEC); + Serial.print(' '); + Serial.print(future.hour(), DEC); + Serial.print(':'); + Serial.print(future.minute(), DEC); + Serial.print(':'); + Serial.print(future.second(), DEC); + Serial.println(); + + Serial.println(); + delay(3000); +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/softrtc/softrtc.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/softrtc/softrtc.ino new file mode 100644 index 0000000..80f1886 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/softrtc/softrtc.ino @@ -0,0 +1,61 @@ +// Date and time functions using just software, based on millis() & timer + +#include +#include // this #include still required because the RTClib depends on it +#include "RTClib.h" + +#if defined(ARDUINO_ARCH_SAMD) +// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! + #define Serial SerialUSB +#endif + +RTC_Millis rtc; + +void setup () { + Serial.begin(57600); + // following line sets the RTC to the date & time this sketch was compiled + rtc.begin(DateTime(F(__DATE__), F(__TIME__))); + // This line sets the RTC with an explicit date & time, for example to set + // January 21, 2014 at 3am you would call: + // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); +} + +void loop () { + DateTime now = rtc.now(); + + Serial.print(now.year(), DEC); + Serial.print('/'); + Serial.print(now.month(), DEC); + Serial.print('/'); + Serial.print(now.day(), DEC); + Serial.print(' '); + Serial.print(now.hour(), DEC); + Serial.print(':'); + Serial.print(now.minute(), DEC); + Serial.print(':'); + Serial.print(now.second(), DEC); + Serial.println(); + + Serial.print(" seconds since 1970: "); + Serial.println(now.unixtime()); + + // calculate a date which is 7 days and 30 seconds into the future + DateTime future (now.unixtime() + 7 * 86400L + 30); + + Serial.print(" now + 7d + 30s: "); + Serial.print(future.year(), DEC); + Serial.print('/'); + Serial.print(future.month(), DEC); + Serial.print('/'); + Serial.print(future.day(), DEC); + Serial.print(' '); + Serial.print(future.hour(), DEC); + Serial.print(':'); + Serial.print(future.minute(), DEC); + Serial.print(':'); + Serial.print(future.second(), DEC); + Serial.println(); + + Serial.println(); + delay(3000); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/keywords.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/keywords.txt new file mode 100644 index 0000000..26cdc1e --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/keywords.txt @@ -0,0 +1,37 @@ +####################################### +# Syntax Coloring Map For RTC +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +DateTime KEYWORD1 +RTC_DS1307 KEYWORD1 +RTC_Millis KEYWORD1 +Ds1307SqwPinMode KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +year KEYWORD2 +month KEYWORD2 +day KEYWORD2 +hour KEYWORD2 +minute KEYWORD2 +second KEYWORD2 +dayOfWeek KEYWORD2 +secondstime KEYWORD2 +unixtime KEYWORD2 +begin KEYWORD2 +adjust KEYWORD2 +isrunning KEYWORD2 +now KEYWORD2 +readSqwPinMode KEYWORD2 +writeSqwPinMode KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/library.properties b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/library.properties new file mode 100644 index 0000000..13d6177 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/library.properties @@ -0,0 +1,9 @@ +name=RTClib +version=1.2.1 +author=Adafruit +maintainer=Adafruit +sentence=A fork of Jeelab's fantastic RTC library +paragraph=A fork of Jeelab's fantastic RTC library +category=Timing +url=https://github.com/adafruit/RTClib +architectures=* diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/File.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/File.cpp new file mode 100755 index 0000000..5e37166 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/File.cpp @@ -0,0 +1,168 @@ +/* + + SD - a slightly more friendly wrapper for sdfatlib + + This library aims to expose a subset of SD card functionality + in the form of a higher level "wrapper" object. + + License: GNU General Public License V3 + (Because sdfatlib is licensed with this.) + + (C) Copyright 2010 SparkFun Electronics + +*/ + +#include + +/* for debugging file open/close leaks + uint8_t nfilecount=0; +*/ + +File::File(SdFile f, const char *n) { + // oh man you are kidding me, new() doesn't exist? Ok we do it by hand! + _file = (SdFile *)malloc(sizeof(SdFile)); + if (_file) { + memcpy(_file, &f, sizeof(SdFile)); + + strncpy(_name, n, 12); + _name[12] = 0; + + /* for debugging file open/close leaks + nfilecount++; + Serial.print("Created \""); + Serial.print(n); + Serial.print("\": "); + Serial.println(nfilecount, DEC); + */ + } +} + +File::File(void) { + _file = 0; + _name[0] = 0; + //Serial.print("Created empty file object"); +} + +// returns a pointer to the file name +char *File::name(void) { + return _name; +} + +// a directory is a special type of file +boolean File::isDirectory(void) { + return (_file && _file->isDir()); +} + + +size_t File::write(uint8_t val) { + return write(&val, 1); +} + +size_t File::write(const uint8_t *buf, size_t size) { + size_t t; + if (!_file) { + setWriteError(); + return 0; + } + _file->clearWriteError(); + t = _file->write(buf, size); + if (_file->getWriteError()) { + setWriteError(); + return 0; + } + return t; +} + +int File::availableForWrite() { + if (_file) { + return _file->availableForWrite(); + } + return 0; +} + +int File::peek() { + if (! _file) { + return 0; + } + + int c = _file->read(); + if (c != -1) { + _file->seekCur(-1); + } + return c; +} + +int File::read() { + if (_file) { + return _file->read(); + } + return -1; +} + +// buffered read for more efficient, high speed reading +int File::read(void *buf, uint16_t nbyte) { + if (_file) { + return _file->read(buf, nbyte); + } + return 0; +} + +int File::available() { + if (! _file) { + return 0; + } + + uint32_t n = size() - position(); + + return n > 0X7FFF ? 0X7FFF : n; +} + +void File::flush() { + if (_file) { + _file->sync(); + } +} + +boolean File::seek(uint32_t pos) { + if (! _file) { + return false; + } + + return _file->seekSet(pos); +} + +uint32_t File::position() { + if (! _file) { + return -1; + } + return _file->curPosition(); +} + +uint32_t File::size() { + if (! _file) { + return 0; + } + return _file->fileSize(); +} + +void File::close() { + if (_file) { + _file->close(); + free(_file); + _file = 0; + + /* for debugging file open/close leaks + nfilecount--; + Serial.print("Deleted "); + Serial.println(nfilecount, DEC); + */ + } +} + +File::operator bool() { + if (_file) { + return _file->isOpen(); + } + return false; +} + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/README.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/README.txt new file mode 100755 index 0000000..495ea4c --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/README.txt @@ -0,0 +1,13 @@ + +** SD - a slightly more friendly wrapper for sdfatlib ** + +This library aims to expose a subset of SD card functionality in the +form of a higher level "wrapper" object. + +License: GNU General Public License V3 + (Because sdfatlib is licensed with this.) + +(C) Copyright 2010 SparkFun Electronics + +Now better than ever with optimization, multiple file support, directory handling, etc - ladyada! + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/SD.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/SD.cpp new file mode 100755 index 0000000..8c9a29e --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/SD.cpp @@ -0,0 +1,637 @@ +/* + + SD - a slightly more friendly wrapper for sdfatlib + + This library aims to expose a subset of SD card functionality + in the form of a higher level "wrapper" object. + + License: GNU General Public License V3 + (Because sdfatlib is licensed with this.) + + (C) Copyright 2010 SparkFun Electronics + + + This library provides four key benefits: + + Including `SD.h` automatically creates a global + `SD` object which can be interacted with in a similar + manner to other standard global objects like `Serial` and `Ethernet`. + + Boilerplate initialisation code is contained in one method named + `begin` and no further objects need to be created in order to access + the SD card. + + Calls to `open` can supply a full path name including parent + directories which simplifies interacting with files in subdirectories. + + Utility methods are provided to determine whether a file exists + and to create a directory hierarchy. + + + Note however that not all functionality provided by the underlying + sdfatlib library is exposed. + +*/ + +/* + + Implementation Notes + + In order to handle multi-directory path traversal, functionality that + requires this ability is implemented as callback functions. + + Individual methods call the `walkPath` function which performs the actual + directory traversal (swapping between two different directory/file handles + along the way) and at each level calls the supplied callback function. + + Some types of functionality will take an action at each level (e.g. exists + or make directory) which others will only take an action at the bottom + level (e.g. open). + +*/ + +#include "SD.h" + +namespace SDLib { + + // Used by `getNextPathComponent` +#define MAX_COMPONENT_LEN 12 // What is max length? +#define PATH_COMPONENT_BUFFER_LEN MAX_COMPONENT_LEN+1 + + bool getNextPathComponent(const char *path, unsigned int *p_offset, + char *buffer) { + /* + + Parse individual path components from a path. + + e.g. after repeated calls '/foo/bar/baz' will be split + into 'foo', 'bar', 'baz'. + + This is similar to `strtok()` but copies the component into the + supplied buffer rather than modifying the original string. + + + `buffer` needs to be PATH_COMPONENT_BUFFER_LEN in size. + + `p_offset` needs to point to an integer of the offset at + which the previous path component finished. + + Returns `true` if more components remain. + + Returns `false` if this is the last component. + (This means path ended with 'foo' or 'foo/'.) + + */ + + // TODO: Have buffer local to this function, so we know it's the + // correct length? + + int bufferOffset = 0; + + int offset = *p_offset; + + // Skip root or other separator + if (path[offset] == '/') { + offset++; + } + + // Copy the next next path segment + while (bufferOffset < MAX_COMPONENT_LEN + && (path[offset] != '/') + && (path[offset] != '\0')) { + buffer[bufferOffset++] = path[offset++]; + } + + buffer[bufferOffset] = '\0'; + + // Skip trailing separator so we can determine if this + // is the last component in the path or not. + if (path[offset] == '/') { + offset++; + } + + *p_offset = offset; + + return (path[offset] != '\0'); + } + + + + boolean walkPath(const char *filepath, SdFile& parentDir, + boolean(*callback)(SdFile& parentDir, + const char *filePathComponent, + boolean isLastComponent, + void *object), + void *object = NULL) { + /* + + When given a file path (and parent directory--normally root), + this function traverses the directories in the path and at each + level calls the supplied callback function while also providing + the supplied object for context if required. + + e.g. given the path '/foo/bar/baz' + the callback would be called at the equivalent of + '/foo', '/foo/bar' and '/foo/bar/baz'. + + The implementation swaps between two different directory/file + handles as it traverses the directories and does not use recursion + in an attempt to use memory efficiently. + + If a callback wishes to stop the directory traversal it should + return false--in this case the function will stop the traversal, + tidy up and return false. + + If a directory path doesn't exist at some point this function will + also return false and not subsequently call the callback. + + If a directory path specified is complete, valid and the callback + did not indicate the traversal should be interrupted then this + function will return true. + + */ + + + SdFile subfile1; + SdFile subfile2; + + char buffer[PATH_COMPONENT_BUFFER_LEN]; + + unsigned int offset = 0; + + SdFile *p_parent; + SdFile *p_child; + + SdFile *p_tmp_sdfile; + + p_child = &subfile1; + + p_parent = &parentDir; + + while (true) { + + boolean moreComponents = getNextPathComponent(filepath, &offset, buffer); + + boolean shouldContinue = callback((*p_parent), buffer, !moreComponents, object); + + if (!shouldContinue) { + // TODO: Don't repeat this code? + // If it's one we've created then we + // don't need the parent handle anymore. + if (p_parent != &parentDir) { + (*p_parent).close(); + } + return false; + } + + if (!moreComponents) { + break; + } + + boolean exists = (*p_child).open(*p_parent, buffer, O_RDONLY); + + // If it's one we've created then we + // don't need the parent handle anymore. + if (p_parent != &parentDir) { + (*p_parent).close(); + } + + // Handle case when it doesn't exist and we can't continue... + if (exists) { + // We alternate between two file handles as we go down + // the path. + if (p_parent == &parentDir) { + p_parent = &subfile2; + } + + p_tmp_sdfile = p_parent; + p_parent = p_child; + p_child = p_tmp_sdfile; + } else { + return false; + } + } + + if (p_parent != &parentDir) { + (*p_parent).close(); // TODO: Return/ handle different? + } + + return true; + } + + + + /* + + The callbacks used to implement various functionality follow. + + Each callback is supplied with a parent directory handle, + character string with the name of the current file path component, + a flag indicating if this component is the last in the path and + a pointer to an arbitrary object used for context. + + */ + + boolean callback_pathExists(SdFile& parentDir, const char *filePathComponent, + boolean /* isLastComponent */, void * /* object */) { + /* + + Callback used to determine if a file/directory exists in parent + directory. + + Returns true if file path exists. + + */ + SdFile child; + + boolean exists = child.open(parentDir, filePathComponent, O_RDONLY); + + if (exists) { + child.close(); + } + + return exists; + } + + + + boolean callback_makeDirPath(SdFile& parentDir, const char *filePathComponent, + boolean isLastComponent, void *object) { + /* + + Callback used to create a directory in the parent directory if + it does not already exist. + + Returns true if a directory was created or it already existed. + + */ + boolean result = false; + SdFile child; + + result = callback_pathExists(parentDir, filePathComponent, isLastComponent, object); + if (!result) { + result = child.makeDir(parentDir, filePathComponent); + } + + return result; + } + + + /* + + boolean callback_openPath(SdFile& parentDir, char *filePathComponent, + boolean isLastComponent, void *object) { + + Callback used to open a file specified by a filepath that may + specify one or more directories above it. + + Expects the context object to be an instance of `SDClass` and + will use the `file` property of the instance to open the requested + file/directory with the associated file open mode property. + + Always returns true if the directory traversal hasn't reached the + bottom of the directory hierarchy. + + Returns false once the file has been opened--to prevent the traversal + from descending further. (This may be unnecessary.) + + if (isLastComponent) { + SDClass *p_SD = static_cast(object); + p_SD->file.open(parentDir, filePathComponent, p_SD->fileOpenMode); + if (p_SD->fileOpenMode == FILE_WRITE) { + p_SD->file.seekSet(p_SD->file.fileSize()); + } + // TODO: Return file open result? + return false; + } + return true; + } + */ + + + + boolean callback_remove(SdFile& parentDir, const char *filePathComponent, + boolean isLastComponent, void * /* object */) { + if (isLastComponent) { + return SdFile::remove(parentDir, filePathComponent); + } + return true; + } + + boolean callback_rmdir(SdFile& parentDir, const char *filePathComponent, + boolean isLastComponent, void * /* object */) { + if (isLastComponent) { + SdFile f; + if (!f.open(parentDir, filePathComponent, O_READ)) { + return false; + } + return f.rmDir(); + } + return true; + } + + + + /* Implementation of class used to create `SDCard` object. */ + + + + boolean SDClass::begin(uint8_t csPin) { + if (root.isOpen()) { + root.close(); + } + + /* + + Performs the initialisation required by the sdfatlib library. + + Return true if initialization succeeds, false otherwise. + + */ + return card.init(SPI_HALF_SPEED, csPin) && + volume.init(card) && + root.openRoot(volume); + } + + boolean SDClass::begin(uint32_t clock, uint8_t csPin) { + if (root.isOpen()) { + root.close(); + } + + return card.init(SPI_HALF_SPEED, csPin) && + card.setSpiClock(clock) && + volume.init(card) && + root.openRoot(volume); + } + + //call this when a card is removed. It will allow you to insert and initialise a new card. + void SDClass::end() { + root.close(); + } + + // this little helper is used to traverse paths + SdFile SDClass::getParentDir(const char *filepath, int *index) { + // get parent directory + SdFile d1; + SdFile d2; + + d1.openRoot(volume); // start with the mostparent, root! + + // we'll use the pointers to swap between the two objects + SdFile *parent = &d1; + SdFile *subdir = &d2; + + const char *origpath = filepath; + + while (strchr(filepath, '/')) { + + // get rid of leading /'s + if (filepath[0] == '/') { + filepath++; + continue; + } + + if (! strchr(filepath, '/')) { + // it was in the root directory, so leave now + break; + } + + // extract just the name of the next subdirectory + uint8_t idx = strchr(filepath, '/') - filepath; + if (idx > 12) { + idx = 12; // don't let them specify long names + } + char subdirname[13]; + strncpy(subdirname, filepath, idx); + subdirname[idx] = 0; + + // close the subdir (we reuse them) if open + subdir->close(); + if (! subdir->open(parent, subdirname, O_READ)) { + // failed to open one of the subdirectories + return SdFile(); + } + // move forward to the next subdirectory + filepath += idx; + + // we reuse the objects, close it. + parent->close(); + + // swap the pointers + SdFile *t = parent; + parent = subdir; + subdir = t; + } + + *index = (int)(filepath - origpath); + // parent is now the parent directory of the file! + return *parent; + } + + + File SDClass::open(const char *filepath, uint8_t mode) { + /* + + Open the supplied file path for reading or writing. + + The file content can be accessed via the `file` property of + the `SDClass` object--this property is currently + a standard `SdFile` object from `sdfatlib`. + + Defaults to read only. + + If `write` is true, default action (when `append` is true) is to + append data to the end of the file. + + If `append` is false then the file will be truncated first. + + If the file does not exist and it is opened for writing the file + will be created. + + An attempt to open a file for reading that does not exist is an + error. + + */ + + int pathidx; + + // do the interactive search + SdFile parentdir = getParentDir(filepath, &pathidx); + // no more subdirs! + + filepath += pathidx; + + if (! filepath[0]) { + // it was the directory itself! + return File(parentdir, "/"); + } + + // Open the file itself + SdFile file; + + // failed to open a subdir! + if (!parentdir.isOpen()) { + return File(); + } + + if (! file.open(parentdir, filepath, mode)) { + return File(); + } + // close the parent + parentdir.close(); + + if ((mode & (O_APPEND | O_WRITE)) == (O_APPEND | O_WRITE)) { + file.seekSet(file.fileSize()); + } + return File(file, filepath); + } + + + /* + File SDClass::open(char *filepath, uint8_t mode) { + // + + Open the supplied file path for reading or writing. + + The file content can be accessed via the `file` property of + the `SDClass` object--this property is currently + a standard `SdFile` object from `sdfatlib`. + + Defaults to read only. + + If `write` is true, default action (when `append` is true) is to + append data to the end of the file. + + If `append` is false then the file will be truncated first. + + If the file does not exist and it is opened for writing the file + will be created. + + An attempt to open a file for reading that does not exist is an + error. + + // + + // TODO: Allow for read&write? (Possibly not, as it requires seek.) + + fileOpenMode = mode; + walkPath(filepath, root, callback_openPath, this); + + return File(); + + } + */ + + + //boolean SDClass::close() { + // /* + // + // Closes the file opened by the `open` method. + // + // */ + // file.close(); + //} + + + boolean SDClass::exists(const char *filepath) { + /* + + Returns true if the supplied file path exists. + + */ + return walkPath(filepath, root, callback_pathExists); + } + + + //boolean SDClass::exists(char *filepath, SdFile& parentDir) { + // /* + // + // Returns true if the supplied file path rooted at `parentDir` + // exists. + // + // */ + // return walkPath(filepath, parentDir, callback_pathExists); + //} + + + boolean SDClass::mkdir(const char *filepath) { + /* + + Makes a single directory or a hierarchy of directories. + + A rough equivalent to `mkdir -p`. + + */ + return walkPath(filepath, root, callback_makeDirPath); + } + + boolean SDClass::rmdir(const char *filepath) { + /* + + Remove a single directory or a hierarchy of directories. + + A rough equivalent to `rm -rf`. + + */ + return walkPath(filepath, root, callback_rmdir); + } + + boolean SDClass::remove(const char *filepath) { + return walkPath(filepath, root, callback_remove); + } + + + // allows you to recurse into a directory + File File::openNextFile(uint8_t mode) { + dir_t p; + + //Serial.print("\t\treading dir..."); + while (_file->readDir(&p) > 0) { + + // done if past last used entry + if (p.name[0] == DIR_NAME_FREE) { + //Serial.println("end"); + return File(); + } + + // skip deleted entry and entries for . and .. + if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') { + //Serial.println("dots"); + continue; + } + + // only list subdirectories and files + if (!DIR_IS_FILE_OR_SUBDIR(&p)) { + //Serial.println("notafile"); + continue; + } + + // print file name with possible blank fill + SdFile f; + char name[13]; + _file->dirName(p, name); + //Serial.print("try to open file "); + //Serial.println(name); + + if (f.open(_file, name, mode)) { + //Serial.println("OK!"); + return File(f, name); + } else { + //Serial.println("ugh"); + return File(); + } + } + + //Serial.println("nothing"); + return File(); + } + + void File::rewindDirectory(void) { + if (isDirectory()) { + _file->rewind(); + } + } + + SDClass SD; + +}; diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/SD.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/SD.h new file mode 100755 index 0000000..fa34ccd --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/SD.h @@ -0,0 +1,138 @@ +/* + + SD - a slightly more friendly wrapper for sdfatlib + + This library aims to expose a subset of SD card functionality + in the form of a higher level "wrapper" object. + + License: GNU General Public License V3 + (Because sdfatlib is licensed with this.) + + (C) Copyright 2010 SparkFun Electronics + +*/ + +#ifndef __SD_H__ +#define __SD_H__ + +#include + +#include "utility/SdFat.h" +#include "utility/SdFatUtil.h" + +#define FILE_READ O_READ +#define FILE_WRITE (O_READ | O_WRITE | O_CREAT | O_APPEND) + +namespace SDLib { + + class File : public Stream { + private: + char _name[13]; // our name + SdFile *_file; // underlying file pointer + + public: + File(SdFile f, const char *name); // wraps an underlying SdFile + File(void); // 'empty' constructor + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + virtual int availableForWrite(); + virtual int read(); + virtual int peek(); + virtual int available(); + virtual void flush(); + int read(void *buf, uint16_t nbyte); + boolean seek(uint32_t pos); + uint32_t position(); + uint32_t size(); + void close(); + operator bool(); + char * name(); + + boolean isDirectory(void); + File openNextFile(uint8_t mode = O_RDONLY); + void rewindDirectory(void); + + using Print::write; + }; + + class SDClass { + + private: + // These are required for initialisation and use of sdfatlib + Sd2Card card; + SdVolume volume; + SdFile root; + + // my quick&dirty iterator, should be replaced + SdFile getParentDir(const char *filepath, int *indx); + public: + // This needs to be called to set up the connection to the SD card + // before other methods are used. + boolean begin(uint8_t csPin = SD_CHIP_SELECT_PIN); + boolean begin(uint32_t clock, uint8_t csPin); + + //call this when a card is removed. It will allow you to insert and initialise a new card. + void end(); + + // Open the specified file/directory with the supplied mode (e.g. read or + // write, etc). Returns a File object for interacting with the file. + // Note that currently only one file can be open at a time. + File open(const char *filename, uint8_t mode = FILE_READ); + File open(const String &filename, uint8_t mode = FILE_READ) { + return open(filename.c_str(), mode); + } + + // Methods to determine if the requested file path exists. + boolean exists(const char *filepath); + boolean exists(const String &filepath) { + return exists(filepath.c_str()); + } + + // Create the requested directory heirarchy--if intermediate directories + // do not exist they will be created. + boolean mkdir(const char *filepath); + boolean mkdir(const String &filepath) { + return mkdir(filepath.c_str()); + } + + // Delete the file. + boolean remove(const char *filepath); + boolean remove(const String &filepath) { + return remove(filepath.c_str()); + } + + boolean rmdir(const char *filepath); + boolean rmdir(const String &filepath) { + return rmdir(filepath.c_str()); + } + + private: + + // This is used to determine the mode used to open a file + // it's here because it's the easiest place to pass the + // information through the directory walking function. But + // it's probably not the best place for it. + // It shouldn't be set directly--it is set via the parameters to `open`. + int fileOpenMode; + + friend class File; + friend boolean callback_openPath(SdFile&, const char *, boolean, void *); + }; + + extern SDClass SD; + +}; + +// We enclose File and SD classes in namespace SDLib to avoid conflicts +// with others legacy libraries that redefines File class. + +// This ensure compatibility with sketches that uses only SD library +using namespace SDLib; + +// This allows sketches to use SDLib::File with other libraries (in the +// sketch you must use SDFile instead of File to disambiguate) +typedef SDLib::File SDFile; +typedef SDLib::SDClass SDFileSystemClass; +#define SDFileSystem SDLib::SD + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/FatStructs.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/FatStructs.h new file mode 100755 index 0000000..84c1cc7 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/FatStructs.h @@ -0,0 +1,418 @@ +/* Arduino SdFat Library + Copyright (C) 2009 by William Greiman + + This file is part of the Arduino SdFat Library + + This Library 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 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino SdFat Library. If not, see + . +*/ +#ifndef FatStructs_h +#define FatStructs_h +/** + \file + FAT file structures +*/ +/* + mostly from Microsoft document fatgen103.doc + http://www.microsoft.com/whdc/system/platform/firmware/fatgen.mspx +*/ +//------------------------------------------------------------------------------ +/** Value for byte 510 of boot block or MBR */ +uint8_t const BOOTSIG0 = 0X55; +/** Value for byte 511 of boot block or MBR */ +uint8_t const BOOTSIG1 = 0XAA; +//------------------------------------------------------------------------------ +/** + \struct partitionTable + \brief MBR partition table entry + + A partition table entry for a MBR formatted storage device. + The MBR partition table has four entries. +*/ +struct partitionTable { + /** + Boot Indicator . Indicates whether the volume is the active + partition. Legal values include: 0X00. Do not use for booting. + 0X80 Active partition. + */ + uint8_t boot; + /** + Head part of Cylinder-head-sector address of the first block in + the partition. Legal values are 0-255. Only used in old PC BIOS. + */ + uint8_t beginHead; + /** + Sector part of Cylinder-head-sector address of the first block in + the partition. Legal values are 1-63. Only used in old PC BIOS. + */ + unsigned beginSector : 6; + /** High bits cylinder for first block in partition. */ + unsigned beginCylinderHigh : 2; + /** + Combine beginCylinderLow with beginCylinderHigh. Legal values + are 0-1023. Only used in old PC BIOS. + */ + uint8_t beginCylinderLow; + /** + Partition type. See defines that begin with PART_TYPE_ for + some Microsoft partition types. + */ + uint8_t type; + /** + head part of cylinder-head-sector address of the last sector in the + partition. Legal values are 0-255. Only used in old PC BIOS. + */ + uint8_t endHead; + /** + Sector part of cylinder-head-sector address of the last sector in + the partition. Legal values are 1-63. Only used in old PC BIOS. + */ + unsigned endSector : 6; + /** High bits of end cylinder */ + unsigned endCylinderHigh : 2; + /** + Combine endCylinderLow with endCylinderHigh. Legal values + are 0-1023. Only used in old PC BIOS. + */ + uint8_t endCylinderLow; + /** Logical block address of the first block in the partition. */ + uint32_t firstSector; + /** Length of the partition, in blocks. */ + uint32_t totalSectors; +} __attribute__((packed)); +/** Type name for partitionTable */ +typedef struct partitionTable part_t; +//------------------------------------------------------------------------------ +/** + \struct masterBootRecord + + \brief Master Boot Record + + The first block of a storage device that is formatted with a MBR. +*/ +struct masterBootRecord { + /** Code Area for master boot program. */ + uint8_t codeArea[440]; + /** Optional WindowsNT disk signature. May contain more boot code. */ + uint32_t diskSignature; + /** Usually zero but may be more boot code. */ + uint16_t usuallyZero; + /** Partition tables. */ + part_t part[4]; + /** First MBR signature byte. Must be 0X55 */ + uint8_t mbrSig0; + /** Second MBR signature byte. Must be 0XAA */ + uint8_t mbrSig1; +} __attribute__((packed)); +/** Type name for masterBootRecord */ +typedef struct masterBootRecord mbr_t; +//------------------------------------------------------------------------------ +/** + \struct biosParmBlock + + \brief BIOS parameter block + + The BIOS parameter block describes the physical layout of a FAT volume. +*/ +struct biosParmBlock { + /** + Count of bytes per sector. This value may take on only the + following values: 512, 1024, 2048 or 4096 + */ + uint16_t bytesPerSector; + /** + Number of sectors per allocation unit. This value must be a + power of 2 that is greater than 0. The legal values are + 1, 2, 4, 8, 16, 32, 64, and 128. + */ + uint8_t sectorsPerCluster; + /** + Number of sectors before the first FAT. + This value must not be zero. + */ + uint16_t reservedSectorCount; + /** The count of FAT data structures on the volume. This field should + always contain the value 2 for any FAT volume of any type. + */ + uint8_t fatCount; + /** + For FAT12 and FAT16 volumes, this field contains the count of + 32-byte directory entries in the root directory. For FAT32 volumes, + this field must be set to 0. For FAT12 and FAT16 volumes, this + value should always specify a count that when multiplied by 32 + results in a multiple of bytesPerSector. FAT16 volumes should + use the value 512. + */ + uint16_t rootDirEntryCount; + /** + This field is the old 16-bit total count of sectors on the volume. + This count includes the count of all sectors in all four regions + of the volume. This field can be 0; if it is 0, then totalSectors32 + must be non-zero. For FAT32 volumes, this field must be 0. For + FAT12 and FAT16 volumes, this field contains the sector count, and + totalSectors32 is 0 if the total sector count fits + (is less than 0x10000). + */ + uint16_t totalSectors16; + /** + This dates back to the old MS-DOS 1.x media determination and is + no longer usually used for anything. 0xF8 is the standard value + for fixed (non-removable) media. For removable media, 0xF0 is + frequently used. Legal values are 0xF0 or 0xF8-0xFF. + */ + uint8_t mediaType; + /** + Count of sectors occupied by one FAT on FAT12/FAT16 volumes. + On FAT32 volumes this field must be 0, and sectorsPerFat32 + contains the FAT size count. + */ + uint16_t sectorsPerFat16; + /** Sectors per track for interrupt 0x13. Not used otherwise. */ + uint16_t sectorsPerTrtack; + /** Number of heads for interrupt 0x13. Not used otherwise. */ + uint16_t headCount; + /** + Count of hidden sectors preceding the partition that contains this + FAT volume. This field is generally only relevant for media + visible on interrupt 0x13. + */ + uint32_t hidddenSectors; + /** + This field is the new 32-bit total count of sectors on the volume. + This count includes the count of all sectors in all four regions + of the volume. This field can be 0; if it is 0, then + totalSectors16 must be non-zero. + */ + uint32_t totalSectors32; + /** + Count of sectors occupied by one FAT on FAT32 volumes. + */ + uint32_t sectorsPerFat32; + /** + This field is only defined for FAT32 media and does not exist on + FAT12 and FAT16 media. + Bits 0-3 -- Zero-based number of active FAT. + Only valid if mirroring is disabled. + Bits 4-6 -- Reserved. + Bit 7 -- 0 means the FAT is mirrored at runtime into all FATs. + -- 1 means only one FAT is active; it is the one referenced in bits 0-3. + Bits 8-15 -- Reserved. + */ + uint16_t fat32Flags; + /** + FAT32 version. High byte is major revision number. + Low byte is minor revision number. Only 0.0 define. + */ + uint16_t fat32Version; + /** + Cluster number of the first cluster of the root directory for FAT32. + This usually 2 but not required to be 2. + */ + uint32_t fat32RootCluster; + /** + Sector number of FSINFO structure in the reserved area of the + FAT32 volume. Usually 1. + */ + uint16_t fat32FSInfo; + /** + If non-zero, indicates the sector number in the reserved area + of the volume of a copy of the boot record. Usually 6. + No value other than 6 is recommended. + */ + uint16_t fat32BackBootBlock; + /** + Reserved for future expansion. Code that formats FAT32 volumes + should always set all of the bytes of this field to 0. + */ + uint8_t fat32Reserved[12]; +} __attribute__((packed)); +/** Type name for biosParmBlock */ +typedef struct biosParmBlock bpb_t; +//------------------------------------------------------------------------------ +/** + \struct fat32BootSector + + \brief Boot sector for a FAT16 or FAT32 volume. + +*/ +struct fat32BootSector { + /** X86 jmp to boot program */ + uint8_t jmpToBootCode[3]; + /** informational only - don't depend on it */ + char oemName[8]; + /** BIOS Parameter Block */ + bpb_t bpb; + /** for int0x13 use value 0X80 for hard drive */ + uint8_t driveNumber; + /** used by Windows NT - should be zero for FAT */ + uint8_t reserved1; + /** 0X29 if next three fields are valid */ + uint8_t bootSignature; + /** usually generated by combining date and time */ + uint32_t volumeSerialNumber; + /** should match volume label in root dir */ + char volumeLabel[11]; + /** informational only - don't depend on it */ + char fileSystemType[8]; + /** X86 boot code */ + uint8_t bootCode[420]; + /** must be 0X55 */ + uint8_t bootSectorSig0; + /** must be 0XAA */ + uint8_t bootSectorSig1; +} __attribute__((packed)); +//------------------------------------------------------------------------------ +// End Of Chain values for FAT entries +/** FAT16 end of chain value used by Microsoft. */ +uint16_t const FAT16EOC = 0XFFFF; +/** Minimum value for FAT16 EOC. Use to test for EOC. */ +uint16_t const FAT16EOC_MIN = 0XFFF8; +/** FAT32 end of chain value used by Microsoft. */ +uint32_t const FAT32EOC = 0X0FFFFFFF; +/** Minimum value for FAT32 EOC. Use to test for EOC. */ +uint32_t const FAT32EOC_MIN = 0X0FFFFFF8; +/** Mask a for FAT32 entry. Entries are 28 bits. */ +uint32_t const FAT32MASK = 0X0FFFFFFF; + +/** Type name for fat32BootSector */ +typedef struct fat32BootSector fbs_t; +//------------------------------------------------------------------------------ +/** + \struct directoryEntry + \brief FAT short directory entry + + Short means short 8.3 name, not the entry size. + + Date Format. A FAT directory entry date stamp is a 16-bit field that is + basically a date relative to the MS-DOS epoch of 01/01/1980. Here is the + format (bit 0 is the LSB of the 16-bit word, bit 15 is the MSB of the + 16-bit word): + + Bits 9-15: Count of years from 1980, valid value range 0-127 + inclusive (1980-2107). + + Bits 5-8: Month of year, 1 = January, valid value range 1-12 inclusive. + + Bits 0-4: Day of month, valid value range 1-31 inclusive. + + Time Format. A FAT directory entry time stamp is a 16-bit field that has + a granularity of 2 seconds. Here is the format (bit 0 is the LSB of the + 16-bit word, bit 15 is the MSB of the 16-bit word). + + Bits 11-15: Hours, valid value range 0-23 inclusive. + + Bits 5-10: Minutes, valid value range 0-59 inclusive. + + Bits 0-4: 2-second count, valid value range 0-29 inclusive (0 - 58 seconds). + + The valid time range is from Midnight 00:00:00 to 23:59:58. +*/ +struct directoryEntry { + /** + Short 8.3 name. + The first eight bytes contain the file name with blank fill. + The last three bytes contain the file extension with blank fill. + */ + uint8_t name[11]; + /** Entry attributes. + + The upper two bits of the attribute byte are reserved and should + always be set to 0 when a file is created and never modified or + looked at after that. See defines that begin with DIR_ATT_. + */ + uint8_t attributes; + /** + Reserved for use by Windows NT. Set value to 0 when a file is + created and never modify or look at it after that. + */ + uint8_t reservedNT; + /** + The granularity of the seconds part of creationTime is 2 seconds + so this field is a count of tenths of a second and its valid + value range is 0-199 inclusive. (WHG note - seems to be hundredths) + */ + uint8_t creationTimeTenths; + /** Time file was created. */ + uint16_t creationTime; + /** Date file was created. */ + uint16_t creationDate; + /** + Last access date. Note that there is no last access time, only + a date. This is the date of last read or write. In the case of + a write, this should be set to the same date as lastWriteDate. + */ + uint16_t lastAccessDate; + /** + High word of this entry's first cluster number (always 0 for a + FAT12 or FAT16 volume). + */ + uint16_t firstClusterHigh; + /** Time of last write. File creation is considered a write. */ + uint16_t lastWriteTime; + /** Date of last write. File creation is considered a write. */ + uint16_t lastWriteDate; + /** Low word of this entry's first cluster number. */ + uint16_t firstClusterLow; + /** 32-bit unsigned holding this file's size in bytes. */ + uint32_t fileSize; +} __attribute__((packed)); +//------------------------------------------------------------------------------ +// Definitions for directory entries +// +/** Type name for directoryEntry */ +typedef struct directoryEntry dir_t; +/** escape for name[0] = 0XE5 */ +uint8_t const DIR_NAME_0XE5 = 0X05; +/** name[0] value for entry that is free after being "deleted" */ +uint8_t const DIR_NAME_DELETED = 0XE5; +/** name[0] value for entry that is free and no allocated entries follow */ +uint8_t const DIR_NAME_FREE = 0X00; +/** file is read-only */ +uint8_t const DIR_ATT_READ_ONLY = 0X01; +/** File should hidden in directory listings */ +uint8_t const DIR_ATT_HIDDEN = 0X02; +/** Entry is for a system file */ +uint8_t const DIR_ATT_SYSTEM = 0X04; +/** Directory entry contains the volume label */ +uint8_t const DIR_ATT_VOLUME_ID = 0X08; +/** Entry is for a directory */ +uint8_t const DIR_ATT_DIRECTORY = 0X10; +/** Old DOS archive bit for backup support */ +uint8_t const DIR_ATT_ARCHIVE = 0X20; +/** Test value for long name entry. Test is + (d->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME. */ +uint8_t const DIR_ATT_LONG_NAME = 0X0F; +/** Test mask for long name entry */ +uint8_t const DIR_ATT_LONG_NAME_MASK = 0X3F; +/** defined attribute bits */ +uint8_t const DIR_ATT_DEFINED_BITS = 0X3F; +/** Directory entry is part of a long name */ +static inline uint8_t DIR_IS_LONG_NAME(const dir_t* dir) { + return (dir->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME; +} +/** Mask for file/subdirectory tests */ +uint8_t const DIR_ATT_FILE_TYPE_MASK = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY); +/** Directory entry is for a file */ +static inline uint8_t DIR_IS_FILE(const dir_t* dir) { + return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == 0; +} +/** Directory entry is for a subdirectory */ +static inline uint8_t DIR_IS_SUBDIR(const dir_t* dir) { + return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == DIR_ATT_DIRECTORY; +} +/** Directory entry is for a file or subdirectory */ +static inline uint8_t DIR_IS_FILE_OR_SUBDIR(const dir_t* dir) { + return (dir->attributes & DIR_ATT_VOLUME_ID) == 0; +} +#endif // FatStructs_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2Card.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2Card.cpp new file mode 100755 index 0000000..7cfbe73 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2Card.cpp @@ -0,0 +1,777 @@ +/* Arduino Sd2Card Library + Copyright (C) 2009 by William Greiman + + This file is part of the Arduino Sd2Card Library + + This Library 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 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino Sd2Card Library. If not, see + . +*/ +#define USE_SPI_LIB +#include +#include "Sd2Card.h" +//------------------------------------------------------------------------------ +#ifndef SOFTWARE_SPI +#ifdef USE_SPI_LIB + + #ifndef SDCARD_SPI + #define SDCARD_SPI SPI + #endif + + #include + static SPISettings settings; +#endif +// functions for hardware SPI +/** Send a byte to the card */ +static void spiSend(uint8_t b) { + #ifndef USE_SPI_LIB + SPDR = b; + while (!(SPSR & (1 << SPIF))) + ; + #else + SDCARD_SPI.transfer(b); + #endif +} +/** Receive a byte from the card */ +static uint8_t spiRec(void) { + #ifndef USE_SPI_LIB + spiSend(0XFF); + return SPDR; + #else + return SDCARD_SPI.transfer(0xFF); + #endif +} +#else // SOFTWARE_SPI +//------------------------------------------------------------------------------ +/** nop to tune soft SPI timing */ +#define nop asm volatile ("nop\n\t") +//------------------------------------------------------------------------------ +/** Soft SPI receive */ +uint8_t spiRec(void) { + uint8_t data = 0; + // no interrupts during byte receive - about 8 us + cli(); + // output pin high - like sending 0XFF + fastDigitalWrite(SPI_MOSI_PIN, HIGH); + + for (uint8_t i = 0; i < 8; i++) { + fastDigitalWrite(SPI_SCK_PIN, HIGH); + + // adjust so SCK is nice + nop; + nop; + + data <<= 1; + + if (fastDigitalRead(SPI_MISO_PIN)) { + data |= 1; + } + + fastDigitalWrite(SPI_SCK_PIN, LOW); + } + // enable interrupts + sei(); + return data; +} +//------------------------------------------------------------------------------ +/** Soft SPI send */ +void spiSend(uint8_t data) { + // no interrupts during byte send - about 8 us + cli(); + for (uint8_t i = 0; i < 8; i++) { + fastDigitalWrite(SPI_SCK_PIN, LOW); + + fastDigitalWrite(SPI_MOSI_PIN, data & 0X80); + + data <<= 1; + + fastDigitalWrite(SPI_SCK_PIN, HIGH); + } + // hold SCK high for a few ns + nop; + nop; + nop; + nop; + + fastDigitalWrite(SPI_SCK_PIN, LOW); + // enable interrupts + sei(); +} +#endif // SOFTWARE_SPI +//------------------------------------------------------------------------------ +// send command and return error code. Return zero for OK +uint8_t Sd2Card::cardCommand(uint8_t cmd, uint32_t arg) { + // end read if in partialBlockRead mode + readEnd(); + + // select card + chipSelectLow(); + + // wait up to 300 ms if busy + waitNotBusy(300); + + // send command + spiSend(cmd | 0x40); + + // send argument + for (int8_t s = 24; s >= 0; s -= 8) { + spiSend(arg >> s); + } + + // send CRC + uint8_t crc = 0XFF; + if (cmd == CMD0) { + crc = 0X95; // correct crc for CMD0 with arg 0 + } + if (cmd == CMD8) { + crc = 0X87; // correct crc for CMD8 with arg 0X1AA + } + spiSend(crc); + + // wait for response + for (uint8_t i = 0; ((status_ = spiRec()) & 0X80) && i != 0XFF; i++) + ; + return status_; +} +//------------------------------------------------------------------------------ +/** + Determine the size of an SD flash memory card. + + \return The number of 512 byte data blocks in the card + or zero if an error occurs. +*/ +uint32_t Sd2Card::cardSize(void) { + csd_t csd; + if (!readCSD(&csd)) { + return 0; + } + if (csd.v1.csd_ver == 0) { + uint8_t read_bl_len = csd.v1.read_bl_len; + uint16_t c_size = (csd.v1.c_size_high << 10) + | (csd.v1.c_size_mid << 2) | csd.v1.c_size_low; + uint8_t c_size_mult = (csd.v1.c_size_mult_high << 1) + | csd.v1.c_size_mult_low; + return (uint32_t)(c_size + 1) << (c_size_mult + read_bl_len - 7); + } else if (csd.v2.csd_ver == 1) { + uint32_t c_size = ((uint32_t)csd.v2.c_size_high << 16) + | (csd.v2.c_size_mid << 8) | csd.v2.c_size_low; + return (c_size + 1) << 10; + } else { + error(SD_CARD_ERROR_BAD_CSD); + return 0; + } +} +//------------------------------------------------------------------------------ +static uint8_t chip_select_asserted = 0; + +void Sd2Card::chipSelectHigh(void) { + digitalWrite(chipSelectPin_, HIGH); + #ifdef USE_SPI_LIB + if (chip_select_asserted) { + chip_select_asserted = 0; + SDCARD_SPI.endTransaction(); + } + #endif +} +//------------------------------------------------------------------------------ +void Sd2Card::chipSelectLow(void) { + #ifdef USE_SPI_LIB + if (!chip_select_asserted) { + chip_select_asserted = 1; + SDCARD_SPI.beginTransaction(settings); + } + #endif + digitalWrite(chipSelectPin_, LOW); +} +//------------------------------------------------------------------------------ +/** Erase a range of blocks. + + \param[in] firstBlock The address of the first block in the range. + \param[in] lastBlock The address of the last block in the range. + + \note This function requests the SD card to do a flash erase for a + range of blocks. The data on the card after an erase operation is + either 0 or 1, depends on the card vendor. The card must support + single block erase. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t Sd2Card::erase(uint32_t firstBlock, uint32_t lastBlock) { + if (!eraseSingleBlockEnable()) { + error(SD_CARD_ERROR_ERASE_SINGLE_BLOCK); + goto fail; + } + if (type_ != SD_CARD_TYPE_SDHC) { + firstBlock <<= 9; + lastBlock <<= 9; + } + if (cardCommand(CMD32, firstBlock) + || cardCommand(CMD33, lastBlock) + || cardCommand(CMD38, 0)) { + error(SD_CARD_ERROR_ERASE); + goto fail; + } + if (!waitNotBusy(SD_ERASE_TIMEOUT)) { + error(SD_CARD_ERROR_ERASE_TIMEOUT); + goto fail; + } + chipSelectHigh(); + return true; + +fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** Determine if card supports single block erase. + + \return The value one, true, is returned if single block erase is supported. + The value zero, false, is returned if single block erase is not supported. +*/ +uint8_t Sd2Card::eraseSingleBlockEnable(void) { + csd_t csd; + return readCSD(&csd) ? csd.v1.erase_blk_en : 0; +} +//------------------------------------------------------------------------------ +/** + Initialize an SD flash memory card. + + \param[in] sckRateID SPI clock rate selector. See setSckRate(). + \param[in] chipSelectPin SD chip select pin number. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. The reason for failure + can be determined by calling errorCode() and errorData(). +*/ +uint8_t Sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin) { + errorCode_ = inBlock_ = partialBlockRead_ = type_ = 0; + chipSelectPin_ = chipSelectPin; + // 16-bit init start time allows over a minute + unsigned int t0 = millis(); + uint32_t arg; + + // set pin modes + pinMode(chipSelectPin_, OUTPUT); + digitalWrite(chipSelectPin_, HIGH); + #ifndef USE_SPI_LIB + pinMode(SPI_MISO_PIN, INPUT); + pinMode(SPI_MOSI_PIN, OUTPUT); + pinMode(SPI_SCK_PIN, OUTPUT); + #endif + + #ifndef SOFTWARE_SPI + #ifndef USE_SPI_LIB + // SS must be in output mode even it is not chip select + pinMode(SS_PIN, OUTPUT); + digitalWrite(SS_PIN, HIGH); // disable any SPI device using hardware SS pin + // Enable SPI, Master, clock rate f_osc/128 + SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR1) | (1 << SPR0); + // clear double speed + SPSR &= ~(1 << SPI2X); + #else // USE_SPI_LIB + SDCARD_SPI.begin(); + settings = SPISettings(250000, MSBFIRST, SPI_MODE0); + #endif // USE_SPI_LIB + #endif // SOFTWARE_SPI + + // must supply min of 74 clock cycles with CS high. + #ifdef USE_SPI_LIB + SDCARD_SPI.beginTransaction(settings); + #endif + for (uint8_t i = 0; i < 10; i++) { + spiSend(0XFF); + } + #ifdef USE_SPI_LIB + SDCARD_SPI.endTransaction(); + #endif + + chipSelectLow(); + + // command to go idle in SPI mode + while ((status_ = cardCommand(CMD0, 0)) != R1_IDLE_STATE) { + unsigned int d = millis() - t0; + if (d > SD_INIT_TIMEOUT) { + error(SD_CARD_ERROR_CMD0); + goto fail; + } + } + // check SD version + if ((cardCommand(CMD8, 0x1AA) & R1_ILLEGAL_COMMAND)) { + type(SD_CARD_TYPE_SD1); + } else { + // only need last byte of r7 response + for (uint8_t i = 0; i < 4; i++) { + status_ = spiRec(); + } + if (status_ != 0XAA) { + error(SD_CARD_ERROR_CMD8); + goto fail; + } + type(SD_CARD_TYPE_SD2); + } + // initialize card and send host supports SDHC if SD2 + arg = type() == SD_CARD_TYPE_SD2 ? 0X40000000 : 0; + + while ((status_ = cardAcmd(ACMD41, arg)) != R1_READY_STATE) { + // check for timeout + unsigned int d = millis() - t0; + if (d > SD_INIT_TIMEOUT) { + error(SD_CARD_ERROR_ACMD41); + goto fail; + } + } + // if SD2 read OCR register to check for SDHC card + if (type() == SD_CARD_TYPE_SD2) { + if (cardCommand(CMD58, 0)) { + error(SD_CARD_ERROR_CMD58); + goto fail; + } + if ((spiRec() & 0XC0) == 0XC0) { + type(SD_CARD_TYPE_SDHC); + } + // discard rest of ocr - contains allowed voltage range + for (uint8_t i = 0; i < 3; i++) { + spiRec(); + } + } + chipSelectHigh(); + + #ifndef SOFTWARE_SPI + return setSckRate(sckRateID); + #else // SOFTWARE_SPI + return true; + #endif // SOFTWARE_SPI + +fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** + Enable or disable partial block reads. + + Enabling partial block reads improves performance by allowing a block + to be read over the SPI bus as several sub-blocks. Errors may occur + if the time between reads is too long since the SD card may timeout. + The SPI SS line will be held low until the entire block is read or + readEnd() is called. + + Use this for applications like the Adafruit Wave Shield. + + \param[in] value The value TRUE (non-zero) or FALSE (zero).) +*/ +void Sd2Card::partialBlockRead(uint8_t value) { + readEnd(); + partialBlockRead_ = value; +} +//------------------------------------------------------------------------------ +/** + Read a 512 byte block from an SD card device. + + \param[in] block Logical block to be read. + \param[out] dst Pointer to the location that will receive the data. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t Sd2Card::readBlock(uint32_t block, uint8_t* dst) { + return readData(block, 0, 512, dst); +} +//------------------------------------------------------------------------------ +/** + Read part of a 512 byte block from an SD card. + + \param[in] block Logical block to be read. + \param[in] offset Number of bytes to skip at start of block + \param[out] dst Pointer to the location that will receive the data. + \param[in] count Number of bytes to read + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t Sd2Card::readData(uint32_t block, + uint16_t offset, uint16_t count, uint8_t* dst) { + if (count == 0) { + return true; + } + if ((count + offset) > 512) { + goto fail; + } + if (!inBlock_ || block != block_ || offset < offset_) { + block_ = block; + // use address if not SDHC card + if (type() != SD_CARD_TYPE_SDHC) { + block <<= 9; + } + if (cardCommand(CMD17, block)) { + error(SD_CARD_ERROR_CMD17); + goto fail; + } + if (!waitStartBlock()) { + goto fail; + } + offset_ = 0; + inBlock_ = 1; + } + + #ifdef OPTIMIZE_HARDWARE_SPI + // start first spi transfer + SPDR = 0XFF; + + // skip data before offset + for (; offset_ < offset; offset_++) { + while (!(SPSR & (1 << SPIF))) + ; + SPDR = 0XFF; + } + // transfer data + n = count - 1; + for (uint16_t i = 0; i < n; i++) { + while (!(SPSR & (1 << SPIF))) + ; + dst[i] = SPDR; + SPDR = 0XFF; + } + // wait for last byte + while (!(SPSR & (1 << SPIF))) + ; + dst[n] = SPDR; + + #else // OPTIMIZE_HARDWARE_SPI + + // skip data before offset + for (; offset_ < offset; offset_++) { + spiRec(); + } + // transfer data + for (uint16_t i = 0; i < count; i++) { + dst[i] = spiRec(); + } + #endif // OPTIMIZE_HARDWARE_SPI + + offset_ += count; + if (!partialBlockRead_ || offset_ >= 512) { + // read rest of data, checksum and set chip select high + readEnd(); + } + return true; + +fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** Skip remaining data in a block when in partial block read mode. */ +void Sd2Card::readEnd(void) { + if (inBlock_) { + // skip data and crc + #ifdef OPTIMIZE_HARDWARE_SPI + // optimize skip for hardware + SPDR = 0XFF; + while (offset_++ < 513) { + while (!(SPSR & (1 << SPIF))) + ; + SPDR = 0XFF; + } + // wait for last crc byte + while (!(SPSR & (1 << SPIF))) + ; + #else // OPTIMIZE_HARDWARE_SPI + while (offset_++ < 514) { + spiRec(); + } + #endif // OPTIMIZE_HARDWARE_SPI + chipSelectHigh(); + inBlock_ = 0; + } +} +//------------------------------------------------------------------------------ +/** read CID or CSR register */ +uint8_t Sd2Card::readRegister(uint8_t cmd, void* buf) { + uint8_t* dst = reinterpret_cast(buf); + if (cardCommand(cmd, 0)) { + error(SD_CARD_ERROR_READ_REG); + goto fail; + } + if (!waitStartBlock()) { + goto fail; + } + // transfer data + for (uint16_t i = 0; i < 16; i++) { + dst[i] = spiRec(); + } + spiRec(); // get first crc byte + spiRec(); // get second crc byte + chipSelectHigh(); + return true; + +fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** + Set the SPI clock rate. + + \param[in] sckRateID A value in the range [0, 6]. + + The SPI clock will be set to F_CPU/pow(2, 1 + sckRateID). The maximum + SPI rate is F_CPU/2 for \a sckRateID = 0 and the minimum rate is F_CPU/128 + for \a scsRateID = 6. + + \return The value one, true, is returned for success and the value zero, + false, is returned for an invalid value of \a sckRateID. +*/ +uint8_t Sd2Card::setSckRate(uint8_t sckRateID) { + if (sckRateID > 6) { + error(SD_CARD_ERROR_SCK_RATE); + return false; + } + #ifndef USE_SPI_LIB + // see avr processor datasheet for SPI register bit definitions + if ((sckRateID & 1) || sckRateID == 6) { + SPSR &= ~(1 << SPI2X); + } else { + SPSR |= (1 << SPI2X); + } + SPCR &= ~((1 << SPR1) | (1 << SPR0)); + SPCR |= (sckRateID & 4 ? (1 << SPR1) : 0) + | (sckRateID & 2 ? (1 << SPR0) : 0); + #else // USE_SPI_LIB + switch (sckRateID) { + case 0: settings = SPISettings(25000000, MSBFIRST, SPI_MODE0); break; + case 1: settings = SPISettings(4000000, MSBFIRST, SPI_MODE0); break; + case 2: settings = SPISettings(2000000, MSBFIRST, SPI_MODE0); break; + case 3: settings = SPISettings(1000000, MSBFIRST, SPI_MODE0); break; + case 4: settings = SPISettings(500000, MSBFIRST, SPI_MODE0); break; + case 5: settings = SPISettings(250000, MSBFIRST, SPI_MODE0); break; + default: settings = SPISettings(125000, MSBFIRST, SPI_MODE0); + } + #endif // USE_SPI_LIB + return true; +} +#ifdef USE_SPI_LIB +//------------------------------------------------------------------------------ +// set the SPI clock frequency +uint8_t Sd2Card::setSpiClock(uint32_t clock) { + settings = SPISettings(clock, MSBFIRST, SPI_MODE0); + return true; +} +#endif +//------------------------------------------------------------------------------ +// wait for card to go not busy +uint8_t Sd2Card::waitNotBusy(unsigned int timeoutMillis) { + unsigned int t0 = millis(); + unsigned int d; + do { + if (spiRec() == 0XFF) { + return true; + } + d = millis() - t0; + } while (d < timeoutMillis); + return false; +} +//------------------------------------------------------------------------------ +/** Wait for start block token */ +uint8_t Sd2Card::waitStartBlock(void) { + unsigned int t0 = millis(); + while ((status_ = spiRec()) == 0XFF) { + unsigned int d = millis() - t0; + if (d > SD_READ_TIMEOUT) { + error(SD_CARD_ERROR_READ_TIMEOUT); + goto fail; + } + } + if (status_ != DATA_START_BLOCK) { + error(SD_CARD_ERROR_READ); + goto fail; + } + return true; + +fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** + Writes a 512 byte block to an SD card. + + \param[in] blockNumber Logical block to be written. + \param[in] src Pointer to the location of the data to be written. + \param[in] blocking If the write should be blocking. + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t Sd2Card::writeBlock(uint32_t blockNumber, const uint8_t* src, uint8_t blocking) { + #if SD_PROTECT_BLOCK_ZERO + // don't allow write to first block + if (blockNumber == 0) { + error(SD_CARD_ERROR_WRITE_BLOCK_ZERO); + goto fail; + } + #endif // SD_PROTECT_BLOCK_ZERO + + // use address if not SDHC card + if (type() != SD_CARD_TYPE_SDHC) { + blockNumber <<= 9; + } + if (cardCommand(CMD24, blockNumber)) { + error(SD_CARD_ERROR_CMD24); + goto fail; + } + if (!writeData(DATA_START_BLOCK, src)) { + goto fail; + } + if (blocking) { + // wait for flash programming to complete + if (!waitNotBusy(SD_WRITE_TIMEOUT)) { + error(SD_CARD_ERROR_WRITE_TIMEOUT); + goto fail; + } + // response is r2 so get and check two bytes for nonzero + if (cardCommand(CMD13, 0) || spiRec()) { + error(SD_CARD_ERROR_WRITE_PROGRAMMING); + goto fail; + } + } + chipSelectHigh(); + return true; + +fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** Write one data block in a multiple block write sequence */ +uint8_t Sd2Card::writeData(const uint8_t* src) { + // wait for previous write to finish + if (!waitNotBusy(SD_WRITE_TIMEOUT)) { + error(SD_CARD_ERROR_WRITE_MULTIPLE); + chipSelectHigh(); + return false; + } + return writeData(WRITE_MULTIPLE_TOKEN, src); +} +//------------------------------------------------------------------------------ +// send one block of data for write block or write multiple blocks +uint8_t Sd2Card::writeData(uint8_t token, const uint8_t* src) { + #ifdef OPTIMIZE_HARDWARE_SPI + + // send data - optimized loop + SPDR = token; + + // send two byte per iteration + for (uint16_t i = 0; i < 512; i += 2) { + while (!(SPSR & (1 << SPIF))) + ; + SPDR = src[i]; + while (!(SPSR & (1 << SPIF))) + ; + SPDR = src[i + 1]; + } + + // wait for last data byte + while (!(SPSR & (1 << SPIF))) + ; + + #else // OPTIMIZE_HARDWARE_SPI + spiSend(token); + for (uint16_t i = 0; i < 512; i++) { + spiSend(src[i]); + } + #endif // OPTIMIZE_HARDWARE_SPI + spiSend(0xff); // dummy crc + spiSend(0xff); // dummy crc + + status_ = spiRec(); + if ((status_ & DATA_RES_MASK) != DATA_RES_ACCEPTED) { + error(SD_CARD_ERROR_WRITE); + chipSelectHigh(); + return false; + } + return true; +} +//------------------------------------------------------------------------------ +/** Start a write multiple blocks sequence. + + \param[in] blockNumber Address of first block in sequence. + \param[in] eraseCount The number of blocks to be pre-erased. + + \note This function is used with writeData() and writeStop() + for optimized multiple block writes. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t Sd2Card::writeStart(uint32_t blockNumber, uint32_t eraseCount) { + #if SD_PROTECT_BLOCK_ZERO + // don't allow write to first block + if (blockNumber == 0) { + error(SD_CARD_ERROR_WRITE_BLOCK_ZERO); + goto fail; + } + #endif // SD_PROTECT_BLOCK_ZERO + // send pre-erase count + if (cardAcmd(ACMD23, eraseCount)) { + error(SD_CARD_ERROR_ACMD23); + goto fail; + } + // use address if not SDHC card + if (type() != SD_CARD_TYPE_SDHC) { + blockNumber <<= 9; + } + if (cardCommand(CMD25, blockNumber)) { + error(SD_CARD_ERROR_CMD25); + goto fail; + } + return true; + +fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** End a write multiple blocks sequence. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t Sd2Card::writeStop(void) { + if (!waitNotBusy(SD_WRITE_TIMEOUT)) { + goto fail; + } + spiSend(STOP_TRAN_TOKEN); + if (!waitNotBusy(SD_WRITE_TIMEOUT)) { + goto fail; + } + chipSelectHigh(); + return true; + +fail: + error(SD_CARD_ERROR_STOP_TRAN); + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** Check if the SD card is busy + + \return The value one, true, is returned when is busy and + the value zero, false, is returned for when is NOT busy. +*/ +uint8_t Sd2Card::isBusy(void) { + chipSelectLow(); + byte b = spiRec(); + chipSelectHigh(); + + return (b != 0XFF); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2Card.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2Card.h new file mode 100755 index 0000000..5d91ebf --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2Card.h @@ -0,0 +1,273 @@ +/* Arduino Sd2Card Library + Copyright (C) 2009 by William Greiman + + This file is part of the Arduino Sd2Card Library + + This Library 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 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino Sd2Card Library. If not, see + . +*/ +#ifndef Sd2Card_h +#define Sd2Card_h +/** + \file + Sd2Card class +*/ +#include "Sd2PinMap.h" +#include "SdInfo.h" +/** Set SCK to max rate of F_CPU/2. See Sd2Card::setSckRate(). */ +uint8_t const SPI_FULL_SPEED = 0; +/** Set SCK rate to F_CPU/4. See Sd2Card::setSckRate(). */ +uint8_t const SPI_HALF_SPEED = 1; +/** Set SCK rate to F_CPU/8. Sd2Card::setSckRate(). */ +uint8_t const SPI_QUARTER_SPEED = 2; +/** + USE_SPI_LIB: if set, use the SPI library bundled with Arduino IDE, otherwise + run with a standalone driver for AVR. +*/ +#define USE_SPI_LIB +/** + Define MEGA_SOFT_SPI non-zero to use software SPI on Mega Arduinos. + Pins used are SS 10, MOSI 11, MISO 12, and SCK 13. + + MEGA_SOFT_SPI allows an unmodified Adafruit GPS Shield to be used + on Mega Arduinos. Software SPI works well with GPS Shield V1.1 + but many SD cards will fail with GPS Shield V1.0. +*/ +#define MEGA_SOFT_SPI 0 +//------------------------------------------------------------------------------ +#if MEGA_SOFT_SPI && (defined(__AVR_ATmega1280__)||defined(__AVR_ATmega2560__)) + #define SOFTWARE_SPI +#endif // MEGA_SOFT_SPI +//------------------------------------------------------------------------------ +// SPI pin definitions +// +#ifndef SOFTWARE_SPI + // hardware pin defs + + // include pins_arduino.h or variant.h depending on architecture, via Arduino.h + #include + + /** + SD Chip Select pin + + Warning if this pin is redefined the hardware SS will pin will be enabled + as an output by init(). An avr processor will not function as an SPI + master unless SS is set to output mode. + */ + #ifndef SDCARD_SS_PIN + /** The default chip select pin for the SD card is SS. */ + uint8_t const SD_CHIP_SELECT_PIN = SS; + #else + uint8_t const SD_CHIP_SELECT_PIN = SDCARD_SS_PIN; + #endif + + // The following three pins must not be redefined for hardware SPI, + // so ensure that they are taken from pins_arduino.h or variant.h, depending on architecture. + #ifndef SDCARD_MOSI_PIN + /** SPI Master Out Slave In pin */ + uint8_t const SPI_MOSI_PIN = MOSI; + /** SPI Master In Slave Out pin */ + uint8_t const SPI_MISO_PIN = MISO; + /** SPI Clock pin */ + uint8_t const SPI_SCK_PIN = SCK; + #else + uint8_t const SPI_MOSI_PIN = SDCARD_MOSI_PIN; + uint8_t const SPI_MISO_PIN = SDCARD_MISO_PIN; + uint8_t const SPI_SCK_PIN = SDCARD_SCK_PIN; + #endif + + /** optimize loops for hardware SPI */ + #ifndef USE_SPI_LIB + #define OPTIMIZE_HARDWARE_SPI + #endif + +#else // SOFTWARE_SPI + // define software SPI pins so Mega can use unmodified GPS Shield + /** SPI chip select pin */ + uint8_t const SD_CHIP_SELECT_PIN = 10; + /** SPI Master Out Slave In pin */ + uint8_t const SPI_MOSI_PIN = 11; + /** SPI Master In Slave Out pin */ + uint8_t const SPI_MISO_PIN = 12; + /** SPI Clock pin */ + uint8_t const SPI_SCK_PIN = 13; +#endif // SOFTWARE_SPI +//------------------------------------------------------------------------------ +/** Protect block zero from write if nonzero */ +#define SD_PROTECT_BLOCK_ZERO 1 +/** init timeout ms */ +unsigned int const SD_INIT_TIMEOUT = 2000; +/** erase timeout ms */ +unsigned int const SD_ERASE_TIMEOUT = 10000; +/** read timeout ms */ +unsigned int const SD_READ_TIMEOUT = 300; +/** write time out ms */ +unsigned int const SD_WRITE_TIMEOUT = 600; +//------------------------------------------------------------------------------ +// SD card errors +/** timeout error for command CMD0 */ +uint8_t const SD_CARD_ERROR_CMD0 = 0X1; +/** CMD8 was not accepted - not a valid SD card*/ +uint8_t const SD_CARD_ERROR_CMD8 = 0X2; +/** card returned an error response for CMD17 (read block) */ +uint8_t const SD_CARD_ERROR_CMD17 = 0X3; +/** card returned an error response for CMD24 (write block) */ +uint8_t const SD_CARD_ERROR_CMD24 = 0X4; +/** WRITE_MULTIPLE_BLOCKS command failed */ +uint8_t const SD_CARD_ERROR_CMD25 = 0X05; +/** card returned an error response for CMD58 (read OCR) */ +uint8_t const SD_CARD_ERROR_CMD58 = 0X06; +/** SET_WR_BLK_ERASE_COUNT failed */ +uint8_t const SD_CARD_ERROR_ACMD23 = 0X07; +/** card's ACMD41 initialization process timeout */ +uint8_t const SD_CARD_ERROR_ACMD41 = 0X08; +/** card returned a bad CSR version field */ +uint8_t const SD_CARD_ERROR_BAD_CSD = 0X09; +/** erase block group command failed */ +uint8_t const SD_CARD_ERROR_ERASE = 0X0A; +/** card not capable of single block erase */ +uint8_t const SD_CARD_ERROR_ERASE_SINGLE_BLOCK = 0X0B; +/** Erase sequence timed out */ +uint8_t const SD_CARD_ERROR_ERASE_TIMEOUT = 0X0C; +/** card returned an error token instead of read data */ +uint8_t const SD_CARD_ERROR_READ = 0X0D; +/** read CID or CSD failed */ +uint8_t const SD_CARD_ERROR_READ_REG = 0X0E; +/** timeout while waiting for start of read data */ +uint8_t const SD_CARD_ERROR_READ_TIMEOUT = 0X0F; +/** card did not accept STOP_TRAN_TOKEN */ +uint8_t const SD_CARD_ERROR_STOP_TRAN = 0X10; +/** card returned an error token as a response to a write operation */ +uint8_t const SD_CARD_ERROR_WRITE = 0X11; +/** attempt to write protected block zero */ +uint8_t const SD_CARD_ERROR_WRITE_BLOCK_ZERO = 0X12; +/** card did not go ready for a multiple block write */ +uint8_t const SD_CARD_ERROR_WRITE_MULTIPLE = 0X13; +/** card returned an error to a CMD13 status check after a write */ +uint8_t const SD_CARD_ERROR_WRITE_PROGRAMMING = 0X14; +/** timeout occurred during write programming */ +uint8_t const SD_CARD_ERROR_WRITE_TIMEOUT = 0X15; +/** incorrect rate selected */ +uint8_t const SD_CARD_ERROR_SCK_RATE = 0X16; +//------------------------------------------------------------------------------ +// card types +/** Standard capacity V1 SD card */ +uint8_t const SD_CARD_TYPE_SD1 = 1; +/** Standard capacity V2 SD card */ +uint8_t const SD_CARD_TYPE_SD2 = 2; +/** High Capacity SD card */ +uint8_t const SD_CARD_TYPE_SDHC = 3; +//------------------------------------------------------------------------------ +/** + \class Sd2Card + \brief Raw access to SD and SDHC flash memory cards. +*/ +class Sd2Card { + public: + /** Construct an instance of Sd2Card. */ + Sd2Card(void) : errorCode_(0), inBlock_(0), partialBlockRead_(0), type_(0) {} + uint32_t cardSize(void); + uint8_t erase(uint32_t firstBlock, uint32_t lastBlock); + uint8_t eraseSingleBlockEnable(void); + /** + \return error code for last error. See Sd2Card.h for a list of error codes. + */ + uint8_t errorCode(void) const { + return errorCode_; + } + /** \return error data for last error. */ + uint8_t errorData(void) const { + return status_; + } + /** + Initialize an SD flash memory card with default clock rate and chip + select pin. See sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin). + */ + uint8_t init(void) { + return init(SPI_FULL_SPEED, SD_CHIP_SELECT_PIN); + } + /** + Initialize an SD flash memory card with the selected SPI clock rate + and the default SD chip select pin. + See sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin). + */ + uint8_t init(uint8_t sckRateID) { + return init(sckRateID, SD_CHIP_SELECT_PIN); + } + uint8_t init(uint8_t sckRateID, uint8_t chipSelectPin); + void partialBlockRead(uint8_t value); + /** Returns the current value, true or false, for partial block read. */ + uint8_t partialBlockRead(void) const { + return partialBlockRead_; + } + uint8_t readBlock(uint32_t block, uint8_t* dst); + uint8_t readData(uint32_t block, + uint16_t offset, uint16_t count, uint8_t* dst); + /** + Read a cards CID register. The CID contains card identification + information such as Manufacturer ID, Product name, Product serial + number and Manufacturing date. */ + uint8_t readCID(cid_t* cid) { + return readRegister(CMD10, cid); + } + /** + Read a cards CSD register. The CSD contains Card-Specific Data that + provides information regarding access to the card's contents. */ + uint8_t readCSD(csd_t* csd) { + return readRegister(CMD9, csd); + } + void readEnd(void); + uint8_t setSckRate(uint8_t sckRateID); + #ifdef USE_SPI_LIB + uint8_t setSpiClock(uint32_t clock); + #endif + /** Return the card type: SD V1, SD V2 or SDHC */ + uint8_t type(void) const { + return type_; + } + uint8_t writeBlock(uint32_t blockNumber, const uint8_t* src, uint8_t blocking = 1); + uint8_t writeData(const uint8_t* src); + uint8_t writeStart(uint32_t blockNumber, uint32_t eraseCount); + uint8_t writeStop(void); + uint8_t isBusy(void); + private: + uint32_t block_; + uint8_t chipSelectPin_; + uint8_t errorCode_; + uint8_t inBlock_; + uint16_t offset_; + uint8_t partialBlockRead_; + uint8_t status_; + uint8_t type_; + // private functions + uint8_t cardAcmd(uint8_t cmd, uint32_t arg) { + cardCommand(CMD55, 0); + return cardCommand(cmd, arg); + } + uint8_t cardCommand(uint8_t cmd, uint32_t arg); + void error(uint8_t code) { + errorCode_ = code; + } + uint8_t readRegister(uint8_t cmd, void* buf); + uint8_t sendWriteCommand(uint32_t blockNumber, uint32_t eraseCount); + void chipSelectHigh(void); + void chipSelectLow(void); + void type(uint8_t value) { + type_ = value; + } + uint8_t waitNotBusy(unsigned int timeoutMillis); + uint8_t writeData(uint8_t token, const uint8_t* src); + uint8_t waitStartBlock(void); +}; +#endif // Sd2Card_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2PinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2PinMap.h new file mode 100755 index 0000000..0609ffe --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2PinMap.h @@ -0,0 +1,525 @@ +/* Arduino SdFat Library + Copyright (C) 2010 by William Greiman + + This file is part of the Arduino SdFat Library + + This Library 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 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino SdFat Library. If not, see + . +*/ +#if defined(__arm__) // Arduino Due Board follows + +#ifndef Sd2PinMap_h + #define Sd2PinMap_h + + #include + + uint8_t const SS_PIN = SS; + uint8_t const MOSI_PIN = MOSI; + uint8_t const MISO_PIN = MISO; + uint8_t const SCK_PIN = SCK; + +#endif // Sd2PinMap_h + +#elif defined(__AVR_ATmega4809__) // Arduino UNO WiFI Rev2 follows + +#ifndef Sd2PinMap_h + #define Sd2PinMap_h + + #include + + uint8_t const SS_PIN = SS; + uint8_t const MOSI_PIN = MOSI; + uint8_t const MISO_PIN = MISO; + uint8_t const SCK_PIN = SCK; + +#endif // Sd2PinMap_h + +#elif defined(__AVR__) // Other AVR based Boards follows + +// Warning this file was generated by a program. +#ifndef Sd2PinMap_h +#define Sd2PinMap_h +#include + +//------------------------------------------------------------------------------ +/** struct for mapping digital pins */ +struct pin_map_t { + volatile uint8_t* ddr; + volatile uint8_t* pin; + volatile uint8_t* port; + uint8_t bit; +}; +//------------------------------------------------------------------------------ +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +// Mega + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 20; +uint8_t const SCL_PIN = 21; + +// SPI port +uint8_t const SS_PIN = 53; +uint8_t const MOSI_PIN = 51; +uint8_t const MISO_PIN = 50; +uint8_t const SCK_PIN = 52; + +static const pin_map_t digitalPinMap[] = { + {&DDRE, &PINE, &PORTE, 0}, // E0 0 + {&DDRE, &PINE, &PORTE, 1}, // E1 1 + {&DDRE, &PINE, &PORTE, 4}, // E4 2 + {&DDRE, &PINE, &PORTE, 5}, // E5 3 + {&DDRG, &PING, &PORTG, 5}, // G5 4 + {&DDRE, &PINE, &PORTE, 3}, // E3 5 + {&DDRH, &PINH, &PORTH, 3}, // H3 6 + {&DDRH, &PINH, &PORTH, 4}, // H4 7 + {&DDRH, &PINH, &PORTH, 5}, // H5 8 + {&DDRH, &PINH, &PORTH, 6}, // H6 9 + {&DDRB, &PINB, &PORTB, 4}, // B4 10 + {&DDRB, &PINB, &PORTB, 5}, // B5 11 + {&DDRB, &PINB, &PORTB, 6}, // B6 12 + {&DDRB, &PINB, &PORTB, 7}, // B7 13 + {&DDRJ, &PINJ, &PORTJ, 1}, // J1 14 + {&DDRJ, &PINJ, &PORTJ, 0}, // J0 15 + {&DDRH, &PINH, &PORTH, 1}, // H1 16 + {&DDRH, &PINH, &PORTH, 0}, // H0 17 + {&DDRD, &PIND, &PORTD, 3}, // D3 18 + {&DDRD, &PIND, &PORTD, 2}, // D2 19 + {&DDRD, &PIND, &PORTD, 1}, // D1 20 + {&DDRD, &PIND, &PORTD, 0}, // D0 21 + {&DDRA, &PINA, &PORTA, 0}, // A0 22 + {&DDRA, &PINA, &PORTA, 1}, // A1 23 + {&DDRA, &PINA, &PORTA, 2}, // A2 24 + {&DDRA, &PINA, &PORTA, 3}, // A3 25 + {&DDRA, &PINA, &PORTA, 4}, // A4 26 + {&DDRA, &PINA, &PORTA, 5}, // A5 27 + {&DDRA, &PINA, &PORTA, 6}, // A6 28 + {&DDRA, &PINA, &PORTA, 7}, // A7 29 + {&DDRC, &PINC, &PORTC, 7}, // C7 30 + {&DDRC, &PINC, &PORTC, 6}, // C6 31 + {&DDRC, &PINC, &PORTC, 5}, // C5 32 + {&DDRC, &PINC, &PORTC, 4}, // C4 33 + {&DDRC, &PINC, &PORTC, 3}, // C3 34 + {&DDRC, &PINC, &PORTC, 2}, // C2 35 + {&DDRC, &PINC, &PORTC, 1}, // C1 36 + {&DDRC, &PINC, &PORTC, 0}, // C0 37 + {&DDRD, &PIND, &PORTD, 7}, // D7 38 + {&DDRG, &PING, &PORTG, 2}, // G2 39 + {&DDRG, &PING, &PORTG, 1}, // G1 40 + {&DDRG, &PING, &PORTG, 0}, // G0 41 + {&DDRL, &PINL, &PORTL, 7}, // L7 42 + {&DDRL, &PINL, &PORTL, 6}, // L6 43 + {&DDRL, &PINL, &PORTL, 5}, // L5 44 + {&DDRL, &PINL, &PORTL, 4}, // L4 45 + {&DDRL, &PINL, &PORTL, 3}, // L3 46 + {&DDRL, &PINL, &PORTL, 2}, // L2 47 + {&DDRL, &PINL, &PORTL, 1}, // L1 48 + {&DDRL, &PINL, &PORTL, 0}, // L0 49 + {&DDRB, &PINB, &PORTB, 3}, // B3 50 + {&DDRB, &PINB, &PORTB, 2}, // B2 51 + {&DDRB, &PINB, &PORTB, 1}, // B1 52 + {&DDRB, &PINB, &PORTB, 0}, // B0 53 + {&DDRF, &PINF, &PORTF, 0}, // F0 54 + {&DDRF, &PINF, &PORTF, 1}, // F1 55 + {&DDRF, &PINF, &PORTF, 2}, // F2 56 + {&DDRF, &PINF, &PORTF, 3}, // F3 57 + {&DDRF, &PINF, &PORTF, 4}, // F4 58 + {&DDRF, &PINF, &PORTF, 5}, // F5 59 + {&DDRF, &PINF, &PORTF, 6}, // F6 60 + {&DDRF, &PINF, &PORTF, 7}, // F7 61 + {&DDRK, &PINK, &PORTK, 0}, // K0 62 + {&DDRK, &PINK, &PORTK, 1}, // K1 63 + {&DDRK, &PINK, &PORTK, 2}, // K2 64 + {&DDRK, &PINK, &PORTK, 3}, // K3 65 + {&DDRK, &PINK, &PORTK, 4}, // K4 66 + {&DDRK, &PINK, &PORTK, 5}, // K5 67 + {&DDRK, &PINK, &PORTK, 6}, // K6 68 + {&DDRK, &PINK, &PORTK, 7} // K7 69 +}; +//------------------------------------------------------------------------------ +#elif (defined(__AVR_ATmega644P__) || defined(__AVR_ATmega1284P__)) && defined(CORE_MICRODUINO) +// Microduino Core+ + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 20; +uint8_t const SCL_PIN = 21; + +// SPI port +uint8_t const SS_PIN = 10; +uint8_t const MOSI_PIN = 11; +uint8_t const MISO_PIN = 12; +uint8_t const SCK_PIN = 13; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 0}, // D0 PD0 + {&DDRD, &PIND, &PORTD, 1}, // D1 PD1 + {&DDRD, &PIND, &PORTD, 2}, // D2 PD2 + {&DDRD, &PIND, &PORTD, 3}, // D3 PD3 + {&DDRB, &PINB, &PORTB, 0}, // D4 PB0 + {&DDRB, &PINB, &PORTB, 1}, // D5 PB1 + {&DDRB, &PINB, &PORTB, 2}, // D6 PB2 + {&DDRB, &PINB, &PORTB, 3}, // D7 PB3 + {&DDRD, &PIND, &PORTD, 6}, // D8 PD6 + {&DDRD, &PIND, &PORTD, 5}, // D9 PD5 + {&DDRB, &PINB, &PORTB, 4}, // D10 PB4 + {&DDRB, &PINB, &PORTB, 5}, // D11 PB5 + {&DDRB, &PINB, &PORTB, 6}, // D12 PB6 + {&DDRB, &PINB, &PORTB, 7}, // D13 PB7 + {&DDRC, &PINC, &PORTC, 7}, // D14 PC7 + {&DDRC, &PINC, &PORTC, 6}, // D15 PC6 + {&DDRC, &PINC, &PORTC, 5}, // D16 PC5 + {&DDRC, &PINC, &PORTC, 4}, // D17 PC4 + {&DDRC, &PINC, &PORTC, 3}, // D18 PC3 + {&DDRC, &PINC, &PORTC, 2}, // D19 PC2 + {&DDRC, &PINC, &PORTC, 1}, // D20 PC1 + {&DDRC, &PINC, &PORTC, 0}, // D21 PC0 + {&DDRD, &PIND, &PORTD, 4}, // D22 PD4 + {&DDRD, &PIND, &PORTD, 7}, // D23 PD7 + {&DDRA, &PINA, &PORTA, 7}, // D24 PA7 + {&DDRA, &PINA, &PORTA, 6}, // D25 PA6 + {&DDRA, &PINA, &PORTA, 5}, // D26 PA5 + {&DDRA, &PINA, &PORTA, 4}, // D27 PA4 + {&DDRA, &PINA, &PORTA, 3}, // D28 PA3 + {&DDRA, &PINA, &PORTA, 2}, // D29 PA2 + {&DDRA, &PINA, &PORTA, 1}, // D30 PA1 + {&DDRA, &PINA, &PORTA, 0} // D31 PA0 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega128RFA1__) && defined(CORE_MICRODUINO) +// Microduino Core RF + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 18; +uint8_t const SCL_PIN = 19; + +// SPI port +uint8_t const SS_PIN = 10; +uint8_t const MOSI_PIN = 11; +uint8_t const MISO_PIN = 12; +uint8_t const SCK_PIN = 13; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PINE, &PORTE, 0}, // D0 PE0 + {&DDRD, &PINE, &PORTE, 1}, // D1 PE1 + {&DDRD, &PIND, &PORTD, 2}, // D2 PD2 + {&DDRD, &PIND, &PORTD, 3}, // D3 PD3 + {&DDRB, &PINE, &PORTE, 3}, // D4 PE3 + {&DDRB, &PINE, &PORTE, 4}, // D5 PE4 + {&DDRB, &PINE, &PORTE, 5}, // D6 PE5 + {&DDRB, &PINB, &PORTB, 7}, // D7 PB7 + {&DDRD, &PINB, &PORTB, 6}, // D8 PB6 + {&DDRD, &PINB, &PORTB, 5}, // D9 PB5 + {&DDRB, &PINB, &PORTB, 4}, // D10 PB4 + {&DDRB, &PINB, &PORTB, 2}, // D11 PB2 + {&DDRB, &PINB, &PORTB, 3}, // D12 PB3 + {&DDRB, &PINB, &PORTB, 1}, // D13 PB1 + {&DDRF, &PINF, &PORTF, 7}, // D14 PF7 + {&DDRF, &PINF, &PORTF, 6}, // D15 PF6 + {&DDRF, &PINF, &PORTF, 5}, // D16 PF5 + {&DDRF, &PINF, &PORTF, 4}, // D17 PF4 + {&DDRD, &PIND, &PORTD, 1}, // D18 PD1 + {&DDRD, &PIND, &PORTD, 0}, // D19 PD0 + {&DDRF, &PINF, &PORTF, 3}, // D20 PF3 + {&DDRF, &PINF, &PORTF, 2}, // D21 PF2 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega32U4__) && defined(CORE_MICRODUINO) +// Microduino Core USB + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 18; +uint8_t const SCL_PIN = 19; + +// SPI port +uint8_t const SS_PIN = 10; +uint8_t const MOSI_PIN = 11; +uint8_t const MISO_PIN = 12; +uint8_t const SCK_PIN = 13; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 2}, // D0 - PD2 + {&DDRD, &PIND, &PORTD, 3}, // D1 - PD3 + {&DDRE, &PINE, &PORTE, 6}, // D2 - PE6 + {&DDRD, &PIND, &PORTD, 6}, // D3 - PD6 + {&DDRD, &PIND, &PORTD, 7}, // D4 - PD7 + {&DDRC, &PINC, &PORTC, 6}, // D5 - PC6 + {&DDRC, &PINC, &PORTC, 7}, // D6 - PC7 + {&DDRE, &PINE, &PORTE, 7}, // D7 - PE7 + {&DDRB, &PINB, &PORTB, 6}, // D8 - PB6 + {&DDRB, &PINB, &PORTB, 5}, // D9 - PB5 + {&DDRB, &PINB, &PORTB, 0}, // D10 - PB0 + {&DDRB, &PINB, &PORTB, 2}, // D11 - MOSI - PB2 + {&DDRB, &PINB, &PORTB, 3}, // D12 -MISO - PB3 + {&DDRB, &PINB, &PORTB, 1}, // D13 -SCK - PB1 + {&DDRF, &PINF, &PORTF, 7}, // D14 - A0 - PF7 + {&DDRF, &PINF, &PORTF, 6}, // D15 - A1 - PF6 + {&DDRF, &PINF, &PORTF, 5}, // D16 - A2 - PF5 + {&DDRF, &PINF, &PORTF, 4}, // D17 - A3 - PF4 + {&DDRD, &PIND, &PORTD, 1}, // D18 - PD1 + {&DDRD, &PIND, &PORTD, 0}, // D19 - PD0 + {&DDRF, &PINF, &PORTF, 1}, // D20 - A6 - PF1 + {&DDRF, &PINF, &PORTF, 0}, // D21 - A7 - PF0 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) +// Sanguino + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 17; +uint8_t const SCL_PIN = 18; + +// SPI port +uint8_t const SS_PIN = 4; +uint8_t const MOSI_PIN = 5; +uint8_t const MISO_PIN = 6; +uint8_t const SCK_PIN = 7; + +static const pin_map_t digitalPinMap[] = { + {&DDRB, &PINB, &PORTB, 0}, // B0 0 + {&DDRB, &PINB, &PORTB, 1}, // B1 1 + {&DDRB, &PINB, &PORTB, 2}, // B2 2 + {&DDRB, &PINB, &PORTB, 3}, // B3 3 + {&DDRB, &PINB, &PORTB, 4}, // B4 4 + {&DDRB, &PINB, &PORTB, 5}, // B5 5 + {&DDRB, &PINB, &PORTB, 6}, // B6 6 + {&DDRB, &PINB, &PORTB, 7}, // B7 7 + {&DDRD, &PIND, &PORTD, 0}, // D0 8 + {&DDRD, &PIND, &PORTD, 1}, // D1 9 + {&DDRD, &PIND, &PORTD, 2}, // D2 10 + {&DDRD, &PIND, &PORTD, 3}, // D3 11 + {&DDRD, &PIND, &PORTD, 4}, // D4 12 + {&DDRD, &PIND, &PORTD, 5}, // D5 13 + {&DDRD, &PIND, &PORTD, 6}, // D6 14 + {&DDRD, &PIND, &PORTD, 7}, // D7 15 + {&DDRC, &PINC, &PORTC, 0}, // C0 16 + {&DDRC, &PINC, &PORTC, 1}, // C1 17 + {&DDRC, &PINC, &PORTC, 2}, // C2 18 + {&DDRC, &PINC, &PORTC, 3}, // C3 19 + {&DDRC, &PINC, &PORTC, 4}, // C4 20 + {&DDRC, &PINC, &PORTC, 5}, // C5 21 + {&DDRC, &PINC, &PORTC, 6}, // C6 22 + {&DDRC, &PINC, &PORTC, 7}, // C7 23 + {&DDRA, &PINA, &PORTA, 7}, // A7 24 + {&DDRA, &PINA, &PORTA, 6}, // A6 25 + {&DDRA, &PINA, &PORTA, 5}, // A5 26 + {&DDRA, &PINA, &PORTA, 4}, // A4 27 + {&DDRA, &PINA, &PORTA, 3}, // A3 28 + {&DDRA, &PINA, &PORTA, 2}, // A2 29 + {&DDRA, &PINA, &PORTA, 1}, // A1 30 + {&DDRA, &PINA, &PORTA, 0} // A0 31 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega32U4__) +// Leonardo + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 2; +uint8_t const SCL_PIN = 3; + +// SPI port +uint8_t const SS_PIN = 17; +uint8_t const MOSI_PIN = 16; +uint8_t const MISO_PIN = 14; +uint8_t const SCK_PIN = 15; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 2}, // D2 0 + {&DDRD, &PIND, &PORTD, 3}, // D3 1 + {&DDRD, &PIND, &PORTD, 1}, // D1 2 + {&DDRD, &PIND, &PORTD, 0}, // D0 3 + {&DDRD, &PIND, &PORTD, 4}, // D4 4 + {&DDRC, &PINC, &PORTC, 6}, // C6 5 + {&DDRD, &PIND, &PORTD, 7}, // D7 6 + {&DDRE, &PINE, &PORTE, 6}, // E6 7 + {&DDRB, &PINB, &PORTB, 4}, // B4 8 + {&DDRB, &PINB, &PORTB, 5}, // B5 9 + {&DDRB, &PINB, &PORTB, 6}, // B6 10 + {&DDRB, &PINB, &PORTB, 7}, // B7 11 + {&DDRD, &PIND, &PORTD, 6}, // D6 12 + {&DDRC, &PINC, &PORTC, 7}, // C7 13 + {&DDRB, &PINB, &PORTB, 3}, // B3 14 + {&DDRB, &PINB, &PORTB, 1}, // B1 15 + {&DDRB, &PINB, &PORTB, 2}, // B2 16 + {&DDRB, &PINB, &PORTB, 0}, // B0 17 + {&DDRF, &PINF, &PORTF, 7}, // F7 18 + {&DDRF, &PINF, &PORTF, 6}, // F6 19 + {&DDRF, &PINF, &PORTF, 5}, // F5 20 + {&DDRF, &PINF, &PORTF, 4}, // F4 21 + {&DDRF, &PINF, &PORTF, 1}, // F1 22 + {&DDRF, &PINF, &PORTF, 0}, // F0 23 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) +// Teensy++ 1.0 & 2.0 + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 1; +uint8_t const SCL_PIN = 0; + +// SPI port +uint8_t const SS_PIN = 20; +uint8_t const MOSI_PIN = 22; +uint8_t const MISO_PIN = 23; +uint8_t const SCK_PIN = 21; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 0}, // D0 0 + {&DDRD, &PIND, &PORTD, 1}, // D1 1 + {&DDRD, &PIND, &PORTD, 2}, // D2 2 + {&DDRD, &PIND, &PORTD, 3}, // D3 3 + {&DDRD, &PIND, &PORTD, 4}, // D4 4 + {&DDRD, &PIND, &PORTD, 5}, // D5 5 + {&DDRD, &PIND, &PORTD, 6}, // D6 6 + {&DDRD, &PIND, &PORTD, 7}, // D7 7 + {&DDRE, &PINE, &PORTE, 0}, // E0 8 + {&DDRE, &PINE, &PORTE, 1}, // E1 9 + {&DDRC, &PINC, &PORTC, 0}, // C0 10 + {&DDRC, &PINC, &PORTC, 1}, // C1 11 + {&DDRC, &PINC, &PORTC, 2}, // C2 12 + {&DDRC, &PINC, &PORTC, 3}, // C3 13 + {&DDRC, &PINC, &PORTC, 4}, // C4 14 + {&DDRC, &PINC, &PORTC, 5}, // C5 15 + {&DDRC, &PINC, &PORTC, 6}, // C6 16 + {&DDRC, &PINC, &PORTC, 7}, // C7 17 + {&DDRE, &PINE, &PORTE, 6}, // E6 18 + {&DDRE, &PINE, &PORTE, 7}, // E7 19 + {&DDRB, &PINB, &PORTB, 0}, // B0 20 + {&DDRB, &PINB, &PORTB, 1}, // B1 21 + {&DDRB, &PINB, &PORTB, 2}, // B2 22 + {&DDRB, &PINB, &PORTB, 3}, // B3 23 + {&DDRB, &PINB, &PORTB, 4}, // B4 24 + {&DDRB, &PINB, &PORTB, 5}, // B5 25 + {&DDRB, &PINB, &PORTB, 6}, // B6 26 + {&DDRB, &PINB, &PORTB, 7}, // B7 27 + {&DDRA, &PINA, &PORTA, 0}, // A0 28 + {&DDRA, &PINA, &PORTA, 1}, // A1 29 + {&DDRA, &PINA, &PORTA, 2}, // A2 30 + {&DDRA, &PINA, &PORTA, 3}, // A3 31 + {&DDRA, &PINA, &PORTA, 4}, // A4 32 + {&DDRA, &PINA, &PORTA, 5}, // A5 33 + {&DDRA, &PINA, &PORTA, 6}, // A6 34 + {&DDRA, &PINA, &PORTA, 7}, // A7 35 + {&DDRE, &PINE, &PORTE, 4}, // E4 36 + {&DDRE, &PINE, &PORTE, 5}, // E5 37 + {&DDRF, &PINF, &PORTF, 0}, // F0 38 + {&DDRF, &PINF, &PORTF, 1}, // F1 39 + {&DDRF, &PINF, &PORTF, 2}, // F2 40 + {&DDRF, &PINF, &PORTF, 3}, // F3 41 + {&DDRF, &PINF, &PORTF, 4}, // F4 42 + {&DDRF, &PINF, &PORTF, 5}, // F5 43 + {&DDRF, &PINF, &PORTF, 6}, // F6 44 + {&DDRF, &PINF, &PORTF, 7} // F7 45 +}; +//------------------------------------------------------------------------------ +#else // defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +// 168 and 328 Arduinos + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 18; +uint8_t const SCL_PIN = 19; + +// SPI port +uint8_t const SS_PIN = 10; +uint8_t const MOSI_PIN = 11; +uint8_t const MISO_PIN = 12; +uint8_t const SCK_PIN = 13; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 0}, // D0 0 + {&DDRD, &PIND, &PORTD, 1}, // D1 1 + {&DDRD, &PIND, &PORTD, 2}, // D2 2 + {&DDRD, &PIND, &PORTD, 3}, // D3 3 + {&DDRD, &PIND, &PORTD, 4}, // D4 4 + {&DDRD, &PIND, &PORTD, 5}, // D5 5 + {&DDRD, &PIND, &PORTD, 6}, // D6 6 + {&DDRD, &PIND, &PORTD, 7}, // D7 7 + {&DDRB, &PINB, &PORTB, 0}, // B0 8 + {&DDRB, &PINB, &PORTB, 1}, // B1 9 + {&DDRB, &PINB, &PORTB, 2}, // B2 10 + {&DDRB, &PINB, &PORTB, 3}, // B3 11 + {&DDRB, &PINB, &PORTB, 4}, // B4 12 + {&DDRB, &PINB, &PORTB, 5}, // B5 13 + {&DDRC, &PINC, &PORTC, 0}, // C0 14 + {&DDRC, &PINC, &PORTC, 1}, // C1 15 + {&DDRC, &PINC, &PORTC, 2}, // C2 16 + {&DDRC, &PINC, &PORTC, 3}, // C3 17 + {&DDRC, &PINC, &PORTC, 4}, // C4 18 + {&DDRC, &PINC, &PORTC, 5} // C5 19 +}; +#endif // defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +//------------------------------------------------------------------------------ +static const uint8_t digitalPinCount = sizeof(digitalPinMap) / sizeof(pin_map_t); + +uint8_t badPinNumber(void) +__attribute__((error("Pin number is too large or not a constant"))); + +static inline __attribute__((always_inline)) +uint8_t getPinMode(uint8_t pin) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + return (*digitalPinMap[pin].ddr >> digitalPinMap[pin].bit) & 1; + } else { + return badPinNumber(); + } +} +static inline __attribute__((always_inline)) +void setPinMode(uint8_t pin, uint8_t mode) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + if (mode) { + *digitalPinMap[pin].ddr |= 1 << digitalPinMap[pin].bit; + } else { + *digitalPinMap[pin].ddr &= ~(1 << digitalPinMap[pin].bit); + } + } else { + badPinNumber(); + } +} +static inline __attribute__((always_inline)) +uint8_t fastDigitalRead(uint8_t pin) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + return (*digitalPinMap[pin].pin >> digitalPinMap[pin].bit) & 1; + } else { + return badPinNumber(); + } +} +static inline __attribute__((always_inline)) +void fastDigitalWrite(uint8_t pin, uint8_t value) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + if (value) { + *digitalPinMap[pin].port |= 1 << digitalPinMap[pin].bit; + } else { + *digitalPinMap[pin].port &= ~(1 << digitalPinMap[pin].bit); + } + } else { + badPinNumber(); + } +} +#endif // Sd2PinMap_h + +#elif defined (__CPU_ARC__) + +#if defined (__ARDUINO_ARC__) + // Two Wire (aka I2C) ports + uint8_t const SDA_PIN = 18; + uint8_t const SCL_PIN = 19; + + // SPI port + uint8_t const SS_PIN = 10; + uint8_t const MOSI_PIN = 11; + uint8_t const MISO_PIN = 12; + uint8_t const SCK_PIN = 13; + +#endif // Arduino ARC + +#else +#error Architecture or board not supported. +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFat.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFat.h new file mode 100755 index 0000000..e57974d --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFat.h @@ -0,0 +1,641 @@ +/* Arduino SdFat Library + Copyright (C) 2009 by William Greiman + + This file is part of the Arduino SdFat Library + + This Library 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 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino SdFat Library. If not, see + . +*/ +#ifndef SdFat_h +#define SdFat_h +/** + \file + SdFile and SdVolume classes +*/ +#if defined (__AVR__) || defined (__CPU_ARC__) + #include +#endif +#include "Sd2Card.h" +#include "FatStructs.h" +#include +//------------------------------------------------------------------------------ +/** + Allow use of deprecated functions if non-zero +*/ +#define ALLOW_DEPRECATED_FUNCTIONS 1 +//------------------------------------------------------------------------------ +// forward declaration since SdVolume is used in SdFile +class SdVolume; +//============================================================================== +// SdFile class + +#ifdef O_RDONLY //ARDUINO_ARCH_MBED +#undef O_READ +#undef O_RDONLY +#undef O_WRITE +#undef O_WRONLY +#undef O_RDWR +#undef O_ACCMODE +#undef O_APPEND +#undef O_SYNC +#undef O_CREAT +#undef O_EXCL +#undef O_TRUNC +#endif + +// flags for ls() +/** ls() flag to print modify date */ +uint8_t const LS_DATE = 1; +/** ls() flag to print file size */ +uint8_t const LS_SIZE = 2; +/** ls() flag for recursive list of subdirectories */ +uint8_t const LS_R = 4; + +// use the gnu style oflag in open() +/** open() oflag for reading */ +uint8_t const O_READ = 0X01; +/** open() oflag - same as O_READ */ +uint8_t const O_RDONLY = O_READ; +/** open() oflag for write */ +uint8_t const O_WRITE = 0X02; +/** open() oflag - same as O_WRITE */ +uint8_t const O_WRONLY = O_WRITE; +/** open() oflag for reading and writing */ +uint8_t const O_RDWR = (O_READ | O_WRITE); +/** open() oflag mask for access modes */ +uint8_t const O_ACCMODE = (O_READ | O_WRITE); +/** The file offset shall be set to the end of the file prior to each write. */ +uint8_t const O_APPEND = 0X04; +/** synchronous writes - call sync() after each write */ +uint8_t const O_SYNC = 0X08; +/** create the file if nonexistent */ +uint8_t const O_CREAT = 0X10; +/** If O_CREAT and O_EXCL are set, open() shall fail if the file exists */ +uint8_t const O_EXCL = 0X20; +/** truncate the file to zero length */ +uint8_t const O_TRUNC = 0X40; + +// flags for timestamp +/** set the file's last access date */ +uint8_t const T_ACCESS = 1; +/** set the file's creation date and time */ +uint8_t const T_CREATE = 2; +/** Set the file's write date and time */ +uint8_t const T_WRITE = 4; +// values for type_ +/** This SdFile has not been opened. */ +uint8_t const FAT_FILE_TYPE_CLOSED = 0; +/** SdFile for a file */ +uint8_t const FAT_FILE_TYPE_NORMAL = 1; +/** SdFile for a FAT16 root directory */ +uint8_t const FAT_FILE_TYPE_ROOT16 = 2; +/** SdFile for a FAT32 root directory */ +uint8_t const FAT_FILE_TYPE_ROOT32 = 3; +/** SdFile for a subdirectory */ +uint8_t const FAT_FILE_TYPE_SUBDIR = 4; +/** Test value for directory type */ +uint8_t const FAT_FILE_TYPE_MIN_DIR = FAT_FILE_TYPE_ROOT16; + +/** date field for FAT directory entry */ +static inline uint16_t FAT_DATE(uint16_t year, uint8_t month, uint8_t day) { + return (year - 1980) << 9 | month << 5 | day; +} +/** year part of FAT directory date field */ +static inline uint16_t FAT_YEAR(uint16_t fatDate) { + return 1980 + (fatDate >> 9); +} +/** month part of FAT directory date field */ +static inline uint8_t FAT_MONTH(uint16_t fatDate) { + return (fatDate >> 5) & 0XF; +} +/** day part of FAT directory date field */ +static inline uint8_t FAT_DAY(uint16_t fatDate) { + return fatDate & 0X1F; +} +/** time field for FAT directory entry */ +static inline uint16_t FAT_TIME(uint8_t hour, uint8_t minute, uint8_t second) { + return hour << 11 | minute << 5 | second >> 1; +} +/** hour part of FAT directory time field */ +static inline uint8_t FAT_HOUR(uint16_t fatTime) { + return fatTime >> 11; +} +/** minute part of FAT directory time field */ +static inline uint8_t FAT_MINUTE(uint16_t fatTime) { + return (fatTime >> 5) & 0X3F; +} +/** second part of FAT directory time field */ +static inline uint8_t FAT_SECOND(uint16_t fatTime) { + return 2 * (fatTime & 0X1F); +} +/** Default date for file timestamps is 1 Jan 2000 */ +uint16_t const FAT_DEFAULT_DATE = ((2000 - 1980) << 9) | (1 << 5) | 1; +/** Default time for file timestamp is 1 am */ +uint16_t const FAT_DEFAULT_TIME = (1 << 11); +//------------------------------------------------------------------------------ +/** + \class SdFile + \brief Access FAT16 and FAT32 files on SD and SDHC cards. +*/ +class SdFile : public Print { + public: + /** Create an instance of SdFile. */ + SdFile(void) : type_(FAT_FILE_TYPE_CLOSED) {} + /** + writeError is set to true if an error occurs during a write(). + Set writeError to false before calling print() and/or write() and check + for true after calls to print() and/or write(). + */ + //bool writeError; + /** + Cancel unbuffered reads for this file. + See setUnbufferedRead() + */ + void clearUnbufferedRead(void) { + flags_ &= ~F_FILE_UNBUFFERED_READ; + } + uint8_t close(void); + uint8_t contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock); + uint8_t createContiguous(SdFile* dirFile, + const char* fileName, uint32_t size); + /** \return The current cluster number for a file or directory. */ + uint32_t curCluster(void) const { + return curCluster_; + } + /** \return The current position for a file or directory. */ + uint32_t curPosition(void) const { + return curPosition_; + } + /** + Set the date/time callback function + + \param[in] dateTime The user's call back function. The callback + function is of the form: + + \code + void dateTime(uint16_t* date, uint16_t* time) { + uint16_t year; + uint8_t month, day, hour, minute, second; + + // User gets date and time from GPS or real-time clock here + + // return date using FAT_DATE macro to format fields + * *date = FAT_DATE(year, month, day); + + // return time using FAT_TIME macro to format fields + * *time = FAT_TIME(hour, minute, second); + } + \endcode + + Sets the function that is called when a file is created or when + a file's directory entry is modified by sync(). All timestamps, + access, creation, and modify, are set when a file is created. + sync() maintains the last access date and last modify date/time. + + See the timestamp() function. + */ + static void dateTimeCallback( + void (*dateTime)(uint16_t* date, uint16_t* time)) { + dateTime_ = dateTime; + } + /** + Cancel the date/time callback function. + */ + static void dateTimeCallbackCancel(void) { + // use explicit zero since NULL is not defined for Sanguino + dateTime_ = 0; + } + /** \return Address of the block that contains this file's directory. */ + uint32_t dirBlock(void) const { + return dirBlock_; + } + uint8_t dirEntry(dir_t* dir); + /** \return Index of this file's directory in the block dirBlock. */ + uint8_t dirIndex(void) const { + return dirIndex_; + } + static void dirName(const dir_t& dir, char* name); + /** \return The total number of bytes in a file or directory. */ + uint32_t fileSize(void) const { + return fileSize_; + } + /** \return The first cluster number for a file or directory. */ + uint32_t firstCluster(void) const { + return firstCluster_; + } + /** \return True if this is a SdFile for a directory else false. */ + uint8_t isDir(void) const { + return type_ >= FAT_FILE_TYPE_MIN_DIR; + } + /** \return True if this is a SdFile for a file else false. */ + uint8_t isFile(void) const { + return type_ == FAT_FILE_TYPE_NORMAL; + } + /** \return True if this is a SdFile for an open file/directory else false. */ + uint8_t isOpen(void) const { + return type_ != FAT_FILE_TYPE_CLOSED; + } + /** \return True if this is a SdFile for a subdirectory else false. */ + uint8_t isSubDir(void) const { + return type_ == FAT_FILE_TYPE_SUBDIR; + } + /** \return True if this is a SdFile for the root directory. */ + uint8_t isRoot(void) const { + return type_ == FAT_FILE_TYPE_ROOT16 || type_ == FAT_FILE_TYPE_ROOT32; + } + void ls(uint8_t flags = 0, uint8_t indent = 0); + uint8_t makeDir(SdFile* dir, const char* dirName); + uint8_t open(SdFile* dirFile, uint16_t index, uint8_t oflag); + uint8_t open(SdFile* dirFile, const char* fileName, uint8_t oflag); + + uint8_t openRoot(SdVolume* vol); + static void printDirName(const dir_t& dir, uint8_t width); + static void printFatDate(uint16_t fatDate); + static void printFatTime(uint16_t fatTime); + static void printTwoDigits(uint8_t v); + /** + Read the next byte from a file. + + \return For success read returns the next byte in the file as an int. + If an error occurs or end of file is reached -1 is returned. + */ + int16_t read(void) { + uint8_t b; + return read(&b, 1) == 1 ? b : -1; + } + int16_t read(void* buf, uint16_t nbyte); + int8_t readDir(dir_t* dir); + static uint8_t remove(SdFile* dirFile, const char* fileName); + uint8_t remove(void); + /** Set the file's current position to zero. */ + void rewind(void) { + curPosition_ = curCluster_ = 0; + } + uint8_t rmDir(void); + uint8_t rmRfStar(void); + /** Set the files position to current position + \a pos. See seekSet(). */ + uint8_t seekCur(uint32_t pos) { + return seekSet(curPosition_ + pos); + } + /** + Set the files current position to end of file. Useful to position + a file for append. See seekSet(). + */ + uint8_t seekEnd(void) { + return seekSet(fileSize_); + } + uint8_t seekSet(uint32_t pos); + /** + Use unbuffered reads to access this file. Used with Wave + Shield ISR. Used with Sd2Card::partialBlockRead() in WaveRP. + + Not recommended for normal applications. + */ + void setUnbufferedRead(void) { + if (isFile()) { + flags_ |= F_FILE_UNBUFFERED_READ; + } + } + uint8_t timestamp(uint8_t flag, uint16_t year, uint8_t month, uint8_t day, + uint8_t hour, uint8_t minute, uint8_t second); + uint8_t sync(uint8_t blocking = 1); + /** Type of this SdFile. You should use isFile() or isDir() instead of type() + if possible. + + \return The file or directory type. + */ + uint8_t type(void) const { + return type_; + } + uint8_t truncate(uint32_t size); + /** \return Unbuffered read flag. */ + uint8_t unbufferedRead(void) const { + return flags_ & F_FILE_UNBUFFERED_READ; + } + /** \return SdVolume that contains this file. */ + SdVolume* volume(void) const { + return vol_; + } + size_t write(uint8_t b); + size_t write(const void* buf, uint16_t nbyte); + size_t write(const char* str); + #ifdef __AVR__ + void write_P(PGM_P str); + void writeln_P(PGM_P str); + #endif + int availableForWrite(void); + //------------------------------------------------------------------------------ + #if ALLOW_DEPRECATED_FUNCTIONS + // Deprecated functions - suppress cpplint warnings with NOLINT comment + /** \deprecated Use: + uint8_t SdFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock); + */ + uint8_t contiguousRange(uint32_t& bgnBlock, uint32_t& endBlock) { // NOLINT + return contiguousRange(&bgnBlock, &endBlock); + } + /** \deprecated Use: + uint8_t SdFile::createContiguous(SdFile* dirFile, + const char* fileName, uint32_t size) + */ + uint8_t createContiguous(SdFile& dirFile, // NOLINT + const char* fileName, uint32_t size) { + return createContiguous(&dirFile, fileName, size); + } + + /** + \deprecated Use: + static void SdFile::dateTimeCallback( + void (*dateTime)(uint16_t* date, uint16_t* time)); + */ + static void dateTimeCallback( + void (*dateTime)(uint16_t& date, uint16_t& time)) { // NOLINT + oldDateTime_ = dateTime; + dateTime_ = dateTime ? oldToNew : 0; + } + /** \deprecated Use: uint8_t SdFile::dirEntry(dir_t* dir); */ + uint8_t dirEntry(dir_t& dir) { + return dirEntry(&dir); // NOLINT + } + /** \deprecated Use: + uint8_t SdFile::makeDir(SdFile* dir, const char* dirName); + */ + uint8_t makeDir(SdFile& dir, const char* dirName) { // NOLINT + return makeDir(&dir, dirName); + } + /** \deprecated Use: + uint8_t SdFile::open(SdFile* dirFile, const char* fileName, uint8_t oflag); + */ + uint8_t open(SdFile& dirFile, // NOLINT + const char* fileName, uint8_t oflag) { + return open(&dirFile, fileName, oflag); + } + /** \deprecated Do not use in new apps */ + uint8_t open(SdFile& dirFile, const char* fileName) { // NOLINT + return open(dirFile, fileName, O_RDWR); + } + /** \deprecated Use: + uint8_t SdFile::open(SdFile* dirFile, uint16_t index, uint8_t oflag); + */ + uint8_t open(SdFile& dirFile, uint16_t index, uint8_t oflag) { // NOLINT + return open(&dirFile, index, oflag); + } + /** \deprecated Use: uint8_t SdFile::openRoot(SdVolume* vol); */ + uint8_t openRoot(SdVolume& vol) { + return openRoot(&vol); // NOLINT + } + + /** \deprecated Use: int8_t SdFile::readDir(dir_t* dir); */ + int8_t readDir(dir_t& dir) { + return readDir(&dir); // NOLINT + } + /** \deprecated Use: + static uint8_t SdFile::remove(SdFile* dirFile, const char* fileName); + */ + static uint8_t remove(SdFile& dirFile, const char* fileName) { // NOLINT + return remove(&dirFile, fileName); + } + //------------------------------------------------------------------------------ + // rest are private + private: + static void (*oldDateTime_)(uint16_t& date, uint16_t& time); // NOLINT + static void oldToNew(uint16_t* date, uint16_t* time) { + uint16_t d; + uint16_t t; + oldDateTime_(d, t); + *date = d; + *time = t; + } + #endif // ALLOW_DEPRECATED_FUNCTIONS + private: + // bits defined in flags_ + // should be 0XF + static uint8_t const F_OFLAG = (O_ACCMODE | O_APPEND | O_SYNC); + // available bits + static uint8_t const F_FILE_NON_BLOCKING_WRITE = 0X10; + // a new cluster was added to the file + static uint8_t const F_FILE_CLUSTER_ADDED = 0X20; + // use unbuffered SD read + static uint8_t const F_FILE_UNBUFFERED_READ = 0X40; + // sync of directory entry required + static uint8_t const F_FILE_DIR_DIRTY = 0X80; + + // make sure F_OFLAG is ok + #if ((F_FILE_NON_BLOCKING_WRITE | F_FILE_CLUSTER_ADDED | F_FILE_UNBUFFERED_READ | F_FILE_DIR_DIRTY) & F_OFLAG) +#error flags_ bits conflict + #endif // flags_ bits + + // private data + uint8_t flags_; // See above for definition of flags_ bits + uint8_t type_; // type of file see above for values + uint32_t curCluster_; // cluster for current file position + uint32_t curPosition_; // current file position in bytes from beginning + uint32_t dirBlock_; // SD block that contains directory entry for file + uint8_t dirIndex_; // index of entry in dirBlock 0 <= dirIndex_ <= 0XF + uint32_t fileSize_; // file size in bytes + uint32_t firstCluster_; // first cluster of file + SdVolume* vol_; // volume where file is located + + // private functions + uint8_t addCluster(void); + uint8_t addDirCluster(void); + dir_t* cacheDirEntry(uint8_t action); + static void (*dateTime_)(uint16_t* date, uint16_t* time); + static uint8_t make83Name(const char* str, uint8_t* name); + uint8_t openCachedEntry(uint8_t cacheIndex, uint8_t oflags); + dir_t* readDirCache(void); +}; +//============================================================================== +// SdVolume class +/** + \brief Cache for an SD data block +*/ +union cache_t { + /** Used to access cached file data blocks. */ + uint8_t data[512]; + /** Used to access cached FAT16 entries. */ + uint16_t fat16[256]; + /** Used to access cached FAT32 entries. */ + uint32_t fat32[128]; + /** Used to access cached directory entries. */ + dir_t dir[16]; + /** Used to access a cached MasterBoot Record. */ + mbr_t mbr; + /** Used to access to a cached FAT boot sector. */ + fbs_t fbs; +}; +//------------------------------------------------------------------------------ +/** + \class SdVolume + \brief Access FAT16 and FAT32 volumes on SD and SDHC cards. +*/ +class SdVolume { + public: + /** Create an instance of SdVolume */ + SdVolume(void) : allocSearchStart_(2), fatType_(0) {} + /** Clear the cache and returns a pointer to the cache. Used by the WaveRP + recorder to do raw write to the SD card. Not for normal apps. + */ + static uint8_t* cacheClear(void) { + cacheFlush(); + cacheBlockNumber_ = 0XFFFFFFFF; + return cacheBuffer_.data; + } + /** + Initialize a FAT volume. Try partition one first then try super + floppy format. + + \param[in] dev The Sd2Card where the volume is located. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. Reasons for + failure include not finding a valid partition, not finding a valid + FAT file system or an I/O error. + */ + uint8_t init(Sd2Card* dev) { + return init(dev, 1) ? true : init(dev, 0); + } + uint8_t init(Sd2Card* dev, uint8_t part); + + // inline functions that return volume info + /** \return The volume's cluster size in blocks. */ + uint8_t blocksPerCluster(void) const { + return blocksPerCluster_; + } + /** \return The number of blocks in one FAT. */ + uint32_t blocksPerFat(void) const { + return blocksPerFat_; + } + /** \return The total number of clusters in the volume. */ + uint32_t clusterCount(void) const { + return clusterCount_; + } + /** \return The shift count required to multiply by blocksPerCluster. */ + uint8_t clusterSizeShift(void) const { + return clusterSizeShift_; + } + /** \return The logical block number for the start of file data. */ + uint32_t dataStartBlock(void) const { + return dataStartBlock_; + } + /** \return The number of FAT structures on the volume. */ + uint8_t fatCount(void) const { + return fatCount_; + } + /** \return The logical block number for the start of the first FAT. */ + uint32_t fatStartBlock(void) const { + return fatStartBlock_; + } + /** \return The FAT type of the volume. Values are 12, 16 or 32. */ + uint8_t fatType(void) const { + return fatType_; + } + /** \return The number of entries in the root directory for FAT16 volumes. */ + uint32_t rootDirEntryCount(void) const { + return rootDirEntryCount_; + } + /** \return The logical block number for the start of the root directory + on FAT16 volumes or the first cluster number on FAT32 volumes. */ + uint32_t rootDirStart(void) const { + return rootDirStart_; + } + /** return a pointer to the Sd2Card object for this volume */ + static Sd2Card* sdCard(void) { + return sdCard_; + } + //------------------------------------------------------------------------------ + #if ALLOW_DEPRECATED_FUNCTIONS + // Deprecated functions - suppress cpplint warnings with NOLINT comment + /** \deprecated Use: uint8_t SdVolume::init(Sd2Card* dev); */ + uint8_t init(Sd2Card& dev) { + return init(&dev); // NOLINT + } + + /** \deprecated Use: uint8_t SdVolume::init(Sd2Card* dev, uint8_t vol); */ + uint8_t init(Sd2Card& dev, uint8_t part) { // NOLINT + return init(&dev, part); + } + #endif // ALLOW_DEPRECATED_FUNCTIONS + //------------------------------------------------------------------------------ + private: + // Allow SdFile access to SdVolume private data. + friend class SdFile; + + // value for action argument in cacheRawBlock to indicate read from cache + static uint8_t const CACHE_FOR_READ = 0; + // value for action argument in cacheRawBlock to indicate cache dirty + static uint8_t const CACHE_FOR_WRITE = 1; + + static cache_t cacheBuffer_; // 512 byte cache for device blocks + static uint32_t cacheBlockNumber_; // Logical number of block in the cache + static Sd2Card* sdCard_; // Sd2Card object for cache + static uint8_t cacheDirty_; // cacheFlush() will write block if true + static uint32_t cacheMirrorBlock_; // block number for mirror FAT + // + uint32_t allocSearchStart_; // start cluster for alloc search + uint8_t blocksPerCluster_; // cluster size in blocks + uint32_t blocksPerFat_; // FAT size in blocks + uint32_t clusterCount_; // clusters in one FAT + uint8_t clusterSizeShift_; // shift to convert cluster count to block count + uint32_t dataStartBlock_; // first data block number + uint8_t fatCount_; // number of FATs on volume + uint32_t fatStartBlock_; // start block for first FAT + uint8_t fatType_; // volume type (12, 16, OR 32) + uint16_t rootDirEntryCount_; // number of entries in FAT16 root dir + uint32_t rootDirStart_; // root start block for FAT16, cluster for FAT32 + //---------------------------------------------------------------------------- + uint8_t allocContiguous(uint32_t count, uint32_t* curCluster); + uint8_t blockOfCluster(uint32_t position) const { + return (position >> 9) & (blocksPerCluster_ - 1); + } + uint32_t clusterStartBlock(uint32_t cluster) const { + return dataStartBlock_ + ((cluster - 2) << clusterSizeShift_); + } + uint32_t blockNumber(uint32_t cluster, uint32_t position) const { + return clusterStartBlock(cluster) + blockOfCluster(position); + } + static uint8_t cacheFlush(uint8_t blocking = 1); + static uint8_t cacheMirrorBlockFlush(uint8_t blocking); + static uint8_t cacheRawBlock(uint32_t blockNumber, uint8_t action); + static void cacheSetDirty(void) { + cacheDirty_ |= CACHE_FOR_WRITE; + } + static uint8_t cacheZeroBlock(uint32_t blockNumber); + uint8_t chainSize(uint32_t beginCluster, uint32_t* size) const; + uint8_t fatGet(uint32_t cluster, uint32_t* value) const; + uint8_t fatPut(uint32_t cluster, uint32_t value); + uint8_t fatPutEOC(uint32_t cluster) { + return fatPut(cluster, 0x0FFFFFFF); + } + uint8_t freeChain(uint32_t cluster); + uint8_t isEOC(uint32_t cluster) const { + return cluster >= (fatType_ == 16 ? FAT16EOC_MIN : FAT32EOC_MIN); + } + uint8_t readBlock(uint32_t block, uint8_t* dst) { + return sdCard_->readBlock(block, dst); + } + uint8_t readData(uint32_t block, uint16_t offset, + uint16_t count, uint8_t* dst) { + return sdCard_->readData(block, offset, count, dst); + } + uint8_t writeBlock(uint32_t block, const uint8_t* dst, uint8_t blocking = 1) { + return sdCard_->writeBlock(block, dst, blocking); + } + uint8_t isBusy(void) { + return sdCard_->isBusy(); + } + uint8_t isCacheMirrorBlockDirty(void) { + return (cacheMirrorBlock_ != 0); + } +}; +#endif // SdFat_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFatUtil.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFatUtil.h new file mode 100755 index 0000000..4b93de8 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFatUtil.h @@ -0,0 +1,77 @@ +/* Arduino SdFat Library + Copyright (C) 2008 by William Greiman + + This file is part of the Arduino SdFat Library + + This Library 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 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino SdFat Library. If not, see + . +*/ +#ifndef SdFatUtil_h +#define SdFatUtil_h +/** + \file + Useful utility functions. +*/ +#include +#ifdef __AVR__ + #include + /** Store and print a string in flash memory.*/ + #define PgmPrint(x) SerialPrint_P(PSTR(x)) + /** Store and print a string in flash memory followed by a CR/LF.*/ + #define PgmPrintln(x) SerialPrintln_P(PSTR(x)) + /** Defined so doxygen works for function definitions. */ +#endif +#define NOINLINE __attribute__((noinline,unused)) +#define UNUSEDOK __attribute__((unused)) +//------------------------------------------------------------------------------ +/** Return the number of bytes currently free in RAM. */ +static UNUSEDOK int FreeRam(void) { + extern int __bss_end; + extern int* __brkval; + int free_memory; + if (reinterpret_cast(__brkval) == 0) { + // if no heap use from end of bss section + free_memory = reinterpret_cast(&free_memory) + - reinterpret_cast(&__bss_end); + } else { + // use from top of stack to heap + free_memory = reinterpret_cast(&free_memory) + - reinterpret_cast(__brkval); + } + return free_memory; +} +#ifdef __AVR__ +//------------------------------------------------------------------------------ +/** + %Print a string in flash memory to the serial port. + + \param[in] str Pointer to string stored in flash memory. +*/ +static NOINLINE void SerialPrint_P(PGM_P str) { + for (uint8_t c; (c = pgm_read_byte(str)); str++) { + Serial.write(c); + } +} +//------------------------------------------------------------------------------ +/** + %Print a string in flash memory followed by a CR/LF. + + \param[in] str Pointer to string stored in flash memory. +*/ +static NOINLINE void SerialPrintln_P(PGM_P str) { + SerialPrint_P(str); + Serial.println(); +} +#endif // __AVR__ +#endif // #define SdFatUtil_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFatmainpage.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFatmainpage.h new file mode 100755 index 0000000..1e6d96f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFatmainpage.h @@ -0,0 +1,202 @@ +/* Arduino SdFat Library + Copyright (C) 2009 by William Greiman + + This file is part of the Arduino SdFat Library + + This Library 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 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino SdFat Library. If not, see + . +*/ + +/** + \mainpage Arduino SdFat Library +
Copyright © 2009 by William Greiman +
+ + \section Intro Introduction + The Arduino SdFat Library is a minimal implementation of FAT16 and FAT32 + file systems on SD flash memory cards. Standard SD and high capacity + SDHC cards are supported. + + The SdFat only supports short 8.3 names. + + The main classes in SdFat are Sd2Card, SdVolume, and SdFile. + + The Sd2Card class supports access to standard SD cards and SDHC cards. Most + applications will only need to call the Sd2Card::init() member function. + + The SdVolume class supports FAT16 and FAT32 partitions. Most applications + will only need to call the SdVolume::init() member function. + + The SdFile class provides file access functions such as open(), read(), + remove(), write(), close() and sync(). This class supports access to the root + directory and subdirectories. + + A number of example are provided in the SdFat/examples folder. These were + developed to test SdFat and illustrate its use. + + SdFat was developed for high speed data recording. SdFat was used to implement + an audio record/play class, WaveRP, for the Adafruit Wave Shield. This + application uses special Sd2Card calls to write to contiguous files in raw mode. + These functions reduce write latency so that audio can be recorded with the + small amount of RAM in the Arduino. + + \section SDcard SD\SDHC Cards + + Arduinos access SD cards using the cards SPI protocol. PCs, Macs, and + most consumer devices use the 4-bit parallel SD protocol. A card that + functions well on A PC or Mac may not work well on the Arduino. + + Most cards have good SPI read performance but cards vary widely in SPI + write performance. Write performance is limited by how efficiently the + card manages internal erase/remapping operations. The Arduino cannot + optimize writes to reduce erase operations because of its limit RAM. + + SanDisk cards generally have good write performance. They seem to have + more internal RAM buffering than other cards and therefore can limit + the number of flash erase operations that the Arduino forces due to its + limited RAM. + + \section Hardware Hardware Configuration + + SdFat was developed using an + Adafruit Industries + Wave Shield. + + The hardware interface to the SD card should not use a resistor based level + shifter. SdFat sets the SPI bus frequency to 8 MHz which results in signal + rise times that are too slow for the edge detectors in many newer SD card + controllers when resistor voltage dividers are used. + + The 5 to 3.3 V level shifter for 5 V Arduinos should be IC based like the + 74HC4050N based circuit shown in the file SdLevel.png. The Adafruit Wave Shield + uses a 74AHC125N. Gravitech sells SD and MicroSD Card Adapters based on the + 74LCX245. + + If you are using a resistor based level shifter and are having problems try + setting the SPI bus frequency to 4 MHz. This can be done by using + card.init(SPI_HALF_SPEED) to initialize the SD card. + + \section comment Bugs and Comments + + If you wish to report bugs or have comments, send email to fat16lib@sbcglobal.net. + + \section SdFatClass SdFat Usage + + SdFat uses a slightly restricted form of short names. + Only printable ASCII characters are supported. No characters with code point + values greater than 127 are allowed. Space is not allowed even though space + was allowed in the API of early versions of DOS. + + Short names are limited to 8 characters followed by an optional period (.) + and extension of up to 3 characters. The characters may be any combination + of letters and digits. The following special characters are also allowed: + + $ % ' - _ @ ~ ` ! ( ) { } ^ # & + + Short names are always converted to upper case and their original case + value is lost. + + \note + The Arduino Print class uses character + at a time writes so it was necessary to use a \link SdFile::sync() sync() \endlink + function to control when data is written to the SD card. + + \par + An application which writes to a file using \link Print::print() print()\endlink, + \link Print::println() println() \endlink + or \link SdFile::write write() \endlink must call \link SdFile::sync() sync() \endlink + at the appropriate time to force data and directory information to be written + to the SD Card. Data and directory information are also written to the SD card + when \link SdFile::close() close() \endlink is called. + + \par + Applications must use care calling \link SdFile::sync() sync() \endlink + since 2048 bytes of I/O is required to update file and + directory information. This includes writing the current data block, reading + the block that contains the directory entry for update, writing the directory + block back and reading back the current data block. + + It is possible to open a file with two or more instances of SdFile. A file may + be corrupted if data is written to the file by more than one instance of SdFile. + + \section HowTo How to format SD Cards as FAT Volumes + + You should use a freshly formatted SD card for best performance. FAT + file systems become slower if many files have been created and deleted. + This is because the directory entry for a deleted file is marked as deleted, + but is not deleted. When a new file is created, these entries must be scanned + before creating the file, a flaw in the FAT design. Also files can become + fragmented which causes reads and writes to be slower. + + Microsoft operating systems support removable media formatted with a + Master Boot Record, MBR, or formatted as a super floppy with a FAT Boot Sector + in block zero. + + Microsoft operating systems expect MBR formatted removable media + to have only one partition. The first partition should be used. + + Microsoft operating systems do not support partitioning SD flash cards. + If you erase an SD card with a program like KillDisk, Most versions of + Windows will format the card as a super floppy. + + The best way to restore an SD card's format is to use SDFormatter + which can be downloaded from: + + http://www.sdcard.org/consumers/formatter/ + + SDFormatter aligns flash erase boundaries with file + system structures which reduces write latency and file system overhead. + + SDFormatter does not have an option for FAT type so it may format + small cards as FAT12. + + After the MBR is restored by SDFormatter you may need to reformat small + cards that have been formatted FAT12 to force the volume type to be FAT16. + + If you reformat the SD card with an OS utility, choose a cluster size that + will result in: + + 4084 < CountOfClusters && CountOfClusters < 65525 + + The volume will then be FAT16. + + If you are formatting an SD card on OS X or Linux, be sure to use the first + partition. Format this partition with a cluster count in above range. + + \section References References + + Adafruit Industries: + + http://www.adafruit.com/ + + http://www.ladyada.net/make/waveshield/ + + The Arduino site: + + http://www.arduino.cc/ + + For more information about FAT file systems see: + + http://www.microsoft.com/whdc/system/platform/firmware/fatgen.mspx + + For information about using SD cards as SPI devices see: + + http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf + + The ATmega328 datasheet: + + http://www.atmel.com/dyn/resources/prod_documents/doc8161.pdf + + +*/ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFile.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFile.cpp new file mode 100755 index 0000000..18a1db6 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFile.cpp @@ -0,0 +1,1527 @@ +/* Arduino SdFat Library + Copyright (C) 2009 by William Greiman + + This file is part of the Arduino SdFat Library + + This Library 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 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino SdFat Library. If not, see + . +*/ +#include "SdFat.h" +#ifdef __AVR__ + #include +#endif +#include +//------------------------------------------------------------------------------ +// callback function for date/time +void (*SdFile::dateTime_)(uint16_t* date, uint16_t* time) = NULL; + +#if ALLOW_DEPRECATED_FUNCTIONS + // suppress cpplint warnings with NOLINT comment + void (*SdFile::oldDateTime_)(uint16_t& date, uint16_t& time) = NULL; // NOLINT +#endif // ALLOW_DEPRECATED_FUNCTIONS +//------------------------------------------------------------------------------ +// add a cluster to a file +uint8_t SdFile::addCluster() { + if (!vol_->allocContiguous(1, &curCluster_)) { + return false; + } + + // if first cluster of file link to directory entry + if (firstCluster_ == 0) { + firstCluster_ = curCluster_; + flags_ |= F_FILE_DIR_DIRTY; + } + flags_ |= F_FILE_CLUSTER_ADDED; + return true; +} +//------------------------------------------------------------------------------ +// Add a cluster to a directory file and zero the cluster. +// return with first block of cluster in the cache +uint8_t SdFile::addDirCluster(void) { + if (!addCluster()) { + return false; + } + + // zero data in cluster insure first cluster is in cache + uint32_t block = vol_->clusterStartBlock(curCluster_); + for (uint8_t i = vol_->blocksPerCluster_; i != 0; i--) { + if (!SdVolume::cacheZeroBlock(block + i - 1)) { + return false; + } + } + // Increase directory file size by cluster size + fileSize_ += 512UL << vol_->clusterSizeShift_; + return true; +} +//------------------------------------------------------------------------------ +// cache a file's directory entry +// return pointer to cached entry or null for failure +dir_t* SdFile::cacheDirEntry(uint8_t action) { + if (!SdVolume::cacheRawBlock(dirBlock_, action)) { + return NULL; + } + return SdVolume::cacheBuffer_.dir + dirIndex_; +} +//------------------------------------------------------------------------------ +/** + Close a file and force cached data and directory information + to be written to the storage device. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include no file is open or an I/O error. +*/ +uint8_t SdFile::close(void) { + if (!sync()) { + return false; + } + type_ = FAT_FILE_TYPE_CLOSED; + return true; +} +//------------------------------------------------------------------------------ +/** + Check for contiguous file and return its raw block range. + + \param[out] bgnBlock the first block address for the file. + \param[out] endBlock the last block address for the file. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include file is not contiguous, file has zero length + or an I/O error occurred. +*/ +uint8_t SdFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock) { + // error if no blocks + if (firstCluster_ == 0) { + return false; + } + + for (uint32_t c = firstCluster_; ; c++) { + uint32_t next; + if (!vol_->fatGet(c, &next)) { + return false; + } + + // check for contiguous + if (next != (c + 1)) { + // error if not end of chain + if (!vol_->isEOC(next)) { + return false; + } + *bgnBlock = vol_->clusterStartBlock(firstCluster_); + *endBlock = vol_->clusterStartBlock(c) + + vol_->blocksPerCluster_ - 1; + return true; + } + } +} +//------------------------------------------------------------------------------ +/** + Create and open a new contiguous file of a specified size. + + \note This function only supports short DOS 8.3 names. + See open() for more information. + + \param[in] dirFile The directory where the file will be created. + \param[in] fileName A valid DOS 8.3 file name. + \param[in] size The desired file size. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include \a fileName contains + an invalid DOS 8.3 file name, the FAT volume has not been initialized, + a file is already open, the file already exists, the root + directory is full or an I/O error. + +*/ +uint8_t SdFile::createContiguous(SdFile* dirFile, + const char* fileName, uint32_t size) { + // don't allow zero length file + if (size == 0) { + return false; + } + if (!open(dirFile, fileName, O_CREAT | O_EXCL | O_RDWR)) { + return false; + } + + // calculate number of clusters needed + uint32_t count = ((size - 1) >> (vol_->clusterSizeShift_ + 9)) + 1; + + // allocate clusters + if (!vol_->allocContiguous(count, &firstCluster_)) { + remove(); + return false; + } + fileSize_ = size; + + // insure sync() will update dir entry + flags_ |= F_FILE_DIR_DIRTY; + return sync(); +} +//------------------------------------------------------------------------------ +/** + Return a files directory entry + + \param[out] dir Location for return of the files directory entry. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t SdFile::dirEntry(dir_t* dir) { + // make sure fields on SD are correct + if (!sync()) { + return false; + } + + // read entry + dir_t* p = cacheDirEntry(SdVolume::CACHE_FOR_READ); + if (!p) { + return false; + } + + // copy to caller's struct + memcpy(dir, p, sizeof(dir_t)); + return true; +} +//------------------------------------------------------------------------------ +/** + Format the name field of \a dir into the 13 byte array + \a name in standard 8.3 short name format. + + \param[in] dir The directory structure containing the name. + \param[out] name A 13 byte char array for the formatted name. +*/ +void SdFile::dirName(const dir_t& dir, char* name) { + uint8_t j = 0; + for (uint8_t i = 0; i < 11; i++) { + if (dir.name[i] == ' ') { + continue; + } + if (i == 8) { + name[j++] = '.'; + } + name[j++] = dir.name[i]; + } + name[j] = 0; +} +//------------------------------------------------------------------------------ +/** List directory contents to Serial. + + \param[in] flags The inclusive OR of + + LS_DATE - %Print file modification date + + LS_SIZE - %Print file size. + + LS_R - Recursive list of subdirectories. + + \param[in] indent Amount of space before file name. Used for recursive + list to indicate subdirectory level. +*/ +void SdFile::ls(uint8_t flags, uint8_t indent) { + dir_t* p; + + rewind(); + while ((p = readDirCache())) { + // done if past last used entry + if (p->name[0] == DIR_NAME_FREE) { + break; + } + + // skip deleted entry and entries for . and .. + if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') { + continue; + } + + // only list subdirectories and files + if (!DIR_IS_FILE_OR_SUBDIR(p)) { + continue; + } + + // print any indent spaces + for (int8_t i = 0; i < indent; i++) { + Serial.print(' '); + } + + // print file name with possible blank fill + printDirName(*p, flags & (LS_DATE | LS_SIZE) ? 14 : 0); + + // print modify date/time if requested + if (flags & LS_DATE) { + printFatDate(p->lastWriteDate); + Serial.print(' '); + printFatTime(p->lastWriteTime); + } + // print size if requested + if (!DIR_IS_SUBDIR(p) && (flags & LS_SIZE)) { + Serial.print(' '); + Serial.print(p->fileSize); + } + Serial.println(); + + // list subdirectory content if requested + if ((flags & LS_R) && DIR_IS_SUBDIR(p)) { + uint16_t index = curPosition() / 32 - 1; + SdFile s; + if (s.open(this, index, O_READ)) { + s.ls(flags, indent + 2); + } + seekSet(32 * (index + 1)); + } + } +} +//------------------------------------------------------------------------------ +// format directory name field from a 8.3 name string +uint8_t SdFile::make83Name(const char* str, uint8_t* name) { + uint8_t c; + uint8_t n = 7; // max index for part before dot + uint8_t i = 0; + // blank fill name and extension + while (i < 11) { + name[i++] = ' '; + } + i = 0; + while ((c = *str++) != '\0') { + if (c == '.') { + if (n == 10) { + return false; // only one dot allowed + } + n = 10; // max index for full 8.3 name + i = 8; // place for extension + } else { + // illegal FAT characters + uint8_t b; + #if defined(__AVR__) + PGM_P p = PSTR("|<>^+=?/[];,*\"\\"); + while ((b = pgm_read_byte(p++))) if (b == c) { + return false; + } + #elif defined(__arm__) + const uint8_t valid[] = "|<>^+=?/[];,*\"\\"; + const uint8_t *p = valid; + while ((b = *p++)) if (b == c) { + return false; + } + #endif + // check size and only allow ASCII printable characters + if (i > n || c < 0X21 || c > 0X7E) { + return false; + } + // only upper case allowed in 8.3 names - convert lower to upper + name[i++] = c < 'a' || c > 'z' ? c : c + ('A' - 'a'); + } + } + // must have a file name, extension is optional + return name[0] != ' '; +} +//------------------------------------------------------------------------------ +/** Make a new directory. + + \param[in] dir An open SdFat instance for the directory that will containing + the new directory. + + \param[in] dirName A valid 8.3 DOS name for the new directory. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include this SdFile is already open, \a dir is not a + directory, \a dirName is invalid or already exists in \a dir. +*/ +uint8_t SdFile::makeDir(SdFile* dir, const char* dirName) { + dir_t d; + + // create a normal file + if (!open(dir, dirName, O_CREAT | O_EXCL | O_RDWR)) { + return false; + } + + // convert SdFile to directory + flags_ = O_READ; + type_ = FAT_FILE_TYPE_SUBDIR; + + // allocate and zero first cluster + if (!addDirCluster()) { + return false; + } + + // force entry to SD + if (!sync()) { + return false; + } + + // cache entry - should already be in cache due to sync() call + dir_t* p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!p) { + return false; + } + + // change directory entry attribute + p->attributes = DIR_ATT_DIRECTORY; + + // make entry for '.' + memcpy(&d, p, sizeof(d)); + for (uint8_t i = 1; i < 11; i++) { + d.name[i] = ' '; + } + d.name[0] = '.'; + + // cache block for '.' and '..' + uint32_t block = vol_->clusterStartBlock(firstCluster_); + if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) { + return false; + } + + // copy '.' to block + memcpy(&SdVolume::cacheBuffer_.dir[0], &d, sizeof(d)); + + // make entry for '..' + d.name[1] = '.'; + if (dir->isRoot()) { + d.firstClusterLow = 0; + d.firstClusterHigh = 0; + } else { + d.firstClusterLow = dir->firstCluster_ & 0XFFFF; + d.firstClusterHigh = dir->firstCluster_ >> 16; + } + // copy '..' to block + memcpy(&SdVolume::cacheBuffer_.dir[1], &d, sizeof(d)); + + // set position after '..' + curPosition_ = 2 * sizeof(d); + + // write first block + return SdVolume::cacheFlush(); +} +//------------------------------------------------------------------------------ +/** + Open a file or directory by name. + + \param[in] dirFile An open SdFat instance for the directory containing the + file to be opened. + + \param[in] fileName A valid 8.3 DOS name for a file to be opened. + + \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive + OR of flags from the following list + + O_READ - Open for reading. + + O_RDONLY - Same as O_READ. + + O_WRITE - Open for writing. + + O_WRONLY - Same as O_WRITE. + + O_RDWR - Open for reading and writing. + + O_APPEND - If set, the file offset shall be set to the end of the + file prior to each write. + + O_CREAT - If the file exists, this flag has no effect except as noted + under O_EXCL below. Otherwise, the file shall be created + + O_EXCL - If O_CREAT and O_EXCL are set, open() shall fail if the file exists. + + O_SYNC - Call sync() after each write. This flag should not be used with + write(uint8_t), write_P(PGM_P), writeln_P(PGM_P), or the Arduino Print class. + These functions do character at a time writes so sync() will be called + after each byte. + + O_TRUNC - If the file exists and is a regular file, and the file is + successfully opened and is not read only, its length shall be truncated to 0. + + \note Directory files must be opened read only. Write and truncation is + not allowed for directory files. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include this SdFile is already open, \a difFile is not + a directory, \a fileName is invalid, the file does not exist + or can't be opened in the access mode specified by oflag. +*/ +uint8_t SdFile::open(SdFile* dirFile, const char* fileName, uint8_t oflag) { + uint8_t dname[11]; + dir_t* p; + + // error if already open + if (isOpen()) { + return false; + } + + if (!make83Name(fileName, dname)) { + return false; + } + vol_ = dirFile->vol_; + dirFile->rewind(); + + // bool for empty entry found + uint8_t emptyFound = false; + + // search for file + while (dirFile->curPosition_ < dirFile->fileSize_) { + uint8_t index = 0XF & (dirFile->curPosition_ >> 5); + p = dirFile->readDirCache(); + if (p == NULL) { + return false; + } + + if (p->name[0] == DIR_NAME_FREE || p->name[0] == DIR_NAME_DELETED) { + // remember first empty slot + if (!emptyFound) { + emptyFound = true; + dirIndex_ = index; + dirBlock_ = SdVolume::cacheBlockNumber_; + } + // done if no entries follow + if (p->name[0] == DIR_NAME_FREE) { + break; + } + } else if (!memcmp(dname, p->name, 11)) { + // don't open existing file if O_CREAT and O_EXCL + if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) { + return false; + } + + // open found file + return openCachedEntry(0XF & index, oflag); + } + } + // only create file if O_CREAT and O_WRITE + if ((oflag & (O_CREAT | O_WRITE)) != (O_CREAT | O_WRITE)) { + return false; + } + + // cache found slot or add cluster if end of file + if (emptyFound) { + p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!p) { + return false; + } + } else { + if (dirFile->type_ == FAT_FILE_TYPE_ROOT16) { + return false; + } + + // add and zero cluster for dirFile - first cluster is in cache for write + if (!dirFile->addDirCluster()) { + return false; + } + + // use first entry in cluster + dirIndex_ = 0; + p = SdVolume::cacheBuffer_.dir; + } + // initialize as empty file + memset(p, 0, sizeof(dir_t)); + memcpy(p->name, dname, 11); + + // set timestamps + if (dateTime_) { + // call user function + dateTime_(&p->creationDate, &p->creationTime); + } else { + // use default date/time + p->creationDate = FAT_DEFAULT_DATE; + p->creationTime = FAT_DEFAULT_TIME; + } + p->lastAccessDate = p->creationDate; + p->lastWriteDate = p->creationDate; + p->lastWriteTime = p->creationTime; + + // force write of entry to SD + if (!SdVolume::cacheFlush()) { + return false; + } + + // open entry in cache + return openCachedEntry(dirIndex_, oflag); +} +//------------------------------------------------------------------------------ +/** + Open a file by index. + + \param[in] dirFile An open SdFat instance for the directory. + + \param[in] index The \a index of the directory entry for the file to be + opened. The value for \a index is (directory file position)/32. + + \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive + OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC. + + See open() by fileName for definition of flags and return values. + +*/ +uint8_t SdFile::open(SdFile* dirFile, uint16_t index, uint8_t oflag) { + // error if already open + if (isOpen()) { + return false; + } + + // don't open existing file if O_CREAT and O_EXCL - user call error + if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) { + return false; + } + + vol_ = dirFile->vol_; + + // seek to location of entry + if (!dirFile->seekSet(32 * index)) { + return false; + } + + // read entry into cache + dir_t* p = dirFile->readDirCache(); + if (p == NULL) { + return false; + } + + // error if empty slot or '.' or '..' + if (p->name[0] == DIR_NAME_FREE || + p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') { + return false; + } + // open cached entry + return openCachedEntry(index & 0XF, oflag); +} +//------------------------------------------------------------------------------ +// open a cached directory entry. Assumes vol_ is initializes +uint8_t SdFile::openCachedEntry(uint8_t dirIndex, uint8_t oflag) { + // location of entry in cache + dir_t* p = SdVolume::cacheBuffer_.dir + dirIndex; + + // write or truncate is an error for a directory or read-only file + if (p->attributes & (DIR_ATT_READ_ONLY | DIR_ATT_DIRECTORY)) { + if (oflag & (O_WRITE | O_TRUNC)) { + return false; + } + } + // remember location of directory entry on SD + dirIndex_ = dirIndex; + dirBlock_ = SdVolume::cacheBlockNumber_; + + // copy first cluster number for directory fields + firstCluster_ = (uint32_t)p->firstClusterHigh << 16; + firstCluster_ |= p->firstClusterLow; + + // make sure it is a normal file or subdirectory + if (DIR_IS_FILE(p)) { + fileSize_ = p->fileSize; + type_ = FAT_FILE_TYPE_NORMAL; + } else if (DIR_IS_SUBDIR(p)) { + if (!vol_->chainSize(firstCluster_, &fileSize_)) { + return false; + } + type_ = FAT_FILE_TYPE_SUBDIR; + } else { + return false; + } + // save open flags for read/write + flags_ = oflag & (O_ACCMODE | O_SYNC | O_APPEND); + + // set to start of file + curCluster_ = 0; + curPosition_ = 0; + + // truncate file to zero length if requested + if (oflag & O_TRUNC) { + return truncate(0); + } + return true; +} +//------------------------------------------------------------------------------ +/** + Open a volume's root directory. + + \param[in] vol The FAT volume containing the root directory to be opened. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include the FAT volume has not been initialized + or it a FAT12 volume. +*/ +uint8_t SdFile::openRoot(SdVolume* vol) { + // error if file is already open + if (isOpen()) { + return false; + } + + if (vol->fatType() == 16) { + type_ = FAT_FILE_TYPE_ROOT16; + firstCluster_ = 0; + fileSize_ = 32 * vol->rootDirEntryCount(); + } else if (vol->fatType() == 32) { + type_ = FAT_FILE_TYPE_ROOT32; + firstCluster_ = vol->rootDirStart(); + if (!vol->chainSize(firstCluster_, &fileSize_)) { + return false; + } + } else { + // volume is not initialized or FAT12 + return false; + } + vol_ = vol; + // read only + flags_ = O_READ; + + // set to start of file + curCluster_ = 0; + curPosition_ = 0; + + // root has no directory entry + dirBlock_ = 0; + dirIndex_ = 0; + return true; +} +//------------------------------------------------------------------------------ +/** %Print the name field of a directory entry in 8.3 format to Serial. + + \param[in] dir The directory structure containing the name. + \param[in] width Blank fill name if length is less than \a width. +*/ +void SdFile::printDirName(const dir_t& dir, uint8_t width) { + uint8_t w = 0; + for (uint8_t i = 0; i < 11; i++) { + if (dir.name[i] == ' ') { + continue; + } + if (i == 8) { + Serial.print('.'); + w++; + } + Serial.write(dir.name[i]); + w++; + } + if (DIR_IS_SUBDIR(&dir)) { + Serial.print('/'); + w++; + } + while (w < width) { + Serial.print(' '); + w++; + } +} +//------------------------------------------------------------------------------ +/** %Print a directory date field to Serial. + + Format is yyyy-mm-dd. + + \param[in] fatDate The date field from a directory entry. +*/ +void SdFile::printFatDate(uint16_t fatDate) { + Serial.print(FAT_YEAR(fatDate)); + Serial.print('-'); + printTwoDigits(FAT_MONTH(fatDate)); + Serial.print('-'); + printTwoDigits(FAT_DAY(fatDate)); +} +//------------------------------------------------------------------------------ +/** %Print a directory time field to Serial. + + Format is hh:mm:ss. + + \param[in] fatTime The time field from a directory entry. +*/ +void SdFile::printFatTime(uint16_t fatTime) { + printTwoDigits(FAT_HOUR(fatTime)); + Serial.print(':'); + printTwoDigits(FAT_MINUTE(fatTime)); + Serial.print(':'); + printTwoDigits(FAT_SECOND(fatTime)); +} +//------------------------------------------------------------------------------ +/** %Print a value as two digits to Serial. + + \param[in] v Value to be printed, 0 <= \a v <= 99 +*/ +void SdFile::printTwoDigits(uint8_t v) { + char str[3]; + str[0] = '0' + v / 10; + str[1] = '0' + v % 10; + str[2] = 0; + Serial.print(str); +} +//------------------------------------------------------------------------------ +/** + Read data from a file starting at the current position. + + \param[out] buf Pointer to the location that will receive the data. + + \param[in] nbyte Maximum number of bytes to read. + + \return For success read() returns the number of bytes read. + A value less than \a nbyte, including zero, will be returned + if end of file is reached. + If an error occurs, read() returns -1. Possible errors include + read() called before a file has been opened, corrupt file system + or an I/O error occurred. +*/ +int16_t SdFile::read(void* buf, uint16_t nbyte) { + uint8_t* dst = reinterpret_cast(buf); + + // error if not open or write only + if (!isOpen() || !(flags_ & O_READ)) { + return -1; + } + + // max bytes left in file + if (nbyte > (fileSize_ - curPosition_)) { + nbyte = fileSize_ - curPosition_; + } + + // amount left to read + uint16_t toRead = nbyte; + while (toRead > 0) { + uint32_t block; // raw device block number + uint16_t offset = curPosition_ & 0X1FF; // offset in block + if (type_ == FAT_FILE_TYPE_ROOT16) { + block = vol_->rootDirStart() + (curPosition_ >> 9); + } else { + uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_); + if (offset == 0 && blockOfCluster == 0) { + // start of new cluster + if (curPosition_ == 0) { + // use first cluster in file + curCluster_ = firstCluster_; + } else { + // get next cluster from FAT + if (!vol_->fatGet(curCluster_, &curCluster_)) { + return -1; + } + } + } + block = vol_->clusterStartBlock(curCluster_) + blockOfCluster; + } + uint16_t n = toRead; + + // amount to be read from current block + if (n > (512 - offset)) { + n = 512 - offset; + } + + // no buffering needed if n == 512 or user requests no buffering + if ((unbufferedRead() || n == 512) && + block != SdVolume::cacheBlockNumber_) { + if (!vol_->readData(block, offset, n, dst)) { + return -1; + } + dst += n; + } else { + // read block to cache and copy data to caller + if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_READ)) { + return -1; + } + uint8_t* src = SdVolume::cacheBuffer_.data + offset; + uint8_t* end = src + n; + while (src != end) { + *dst++ = *src++; + } + } + curPosition_ += n; + toRead -= n; + } + return nbyte; +} +//------------------------------------------------------------------------------ +/** + Read the next directory entry from a directory file. + + \param[out] dir The dir_t struct that will receive the data. + + \return For success readDir() returns the number of bytes read. + A value of zero will be returned if end of file is reached. + If an error occurs, readDir() returns -1. Possible errors include + readDir() called before a directory has been opened, this is not + a directory file or an I/O error occurred. +*/ +int8_t SdFile::readDir(dir_t* dir) { + int8_t n; + // if not a directory file or miss-positioned return an error + if (!isDir() || (0X1F & curPosition_)) { + return -1; + } + + while ((n = read(dir, sizeof(dir_t))) == sizeof(dir_t)) { + // last entry if DIR_NAME_FREE + if (dir->name[0] == DIR_NAME_FREE) { + break; + } + // skip empty entries and entry for . and .. + if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') { + continue; + } + // return if normal file or subdirectory + if (DIR_IS_FILE_OR_SUBDIR(dir)) { + return n; + } + } + // error, end of file, or past last entry + return n < 0 ? -1 : 0; +} +//------------------------------------------------------------------------------ +// Read next directory entry into the cache +// Assumes file is correctly positioned +dir_t* SdFile::readDirCache(void) { + // error if not directory + if (!isDir()) { + return NULL; + } + + // index of entry in cache + uint8_t i = (curPosition_ >> 5) & 0XF; + + // use read to locate and cache block + if (read() < 0) { + return NULL; + } + + // advance to next entry + curPosition_ += 31; + + // return pointer to entry + return (SdVolume::cacheBuffer_.dir + i); +} +//------------------------------------------------------------------------------ +/** + Remove a file. + + The directory entry and all data for the file are deleted. + + \note This function should not be used to delete the 8.3 version of a + file that has a long name. For example if a file has the long name + "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include the file read-only, is a directory, + or an I/O error occurred. +*/ +uint8_t SdFile::remove(void) { + // free any clusters - will fail if read-only or directory + if (!truncate(0)) { + return false; + } + + // cache directory entry + dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!d) { + return false; + } + + // mark entry deleted + d->name[0] = DIR_NAME_DELETED; + + // set this SdFile closed + type_ = FAT_FILE_TYPE_CLOSED; + + // write entry to SD + return SdVolume::cacheFlush(); +} +//------------------------------------------------------------------------------ +/** + Remove a file. + + The directory entry and all data for the file are deleted. + + \param[in] dirFile The directory that contains the file. + \param[in] fileName The name of the file to be removed. + + \note This function should not be used to delete the 8.3 version of a + file that has a long name. For example if a file has the long name + "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include the file is a directory, is read only, + \a dirFile is not a directory, \a fileName is not found + or an I/O error occurred. +*/ +uint8_t SdFile::remove(SdFile* dirFile, const char* fileName) { + SdFile file; + if (!file.open(dirFile, fileName, O_WRITE)) { + return false; + } + return file.remove(); +} +//------------------------------------------------------------------------------ +/** Remove a directory file. + + The directory file will be removed only if it is empty and is not the + root directory. rmDir() follows DOS and Windows and ignores the + read-only attribute for the directory. + + \note This function should not be used to delete the 8.3 version of a + directory that has a long name. For example if a directory has the + long name "New folder" you should not delete the 8.3 name "NEWFOL~1". + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include the file is not a directory, is the root + directory, is not empty, or an I/O error occurred. +*/ +uint8_t SdFile::rmDir(void) { + // must be open subdirectory + if (!isSubDir()) { + return false; + } + + rewind(); + + // make sure directory is empty + while (curPosition_ < fileSize_) { + dir_t* p = readDirCache(); + if (p == NULL) { + return false; + } + // done if past last used entry + if (p->name[0] == DIR_NAME_FREE) { + break; + } + // skip empty slot or '.' or '..' + if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') { + continue; + } + // error not empty + if (DIR_IS_FILE_OR_SUBDIR(p)) { + return false; + } + } + // convert empty directory to normal file for remove + type_ = FAT_FILE_TYPE_NORMAL; + flags_ |= O_WRITE; + return remove(); +} +//------------------------------------------------------------------------------ +/** Recursively delete a directory and all contained files. + + This is like the Unix/Linux 'rm -rf *' if called with the root directory + hence the name. + + Warning - This will remove all contents of the directory including + subdirectories. The directory will then be removed if it is not root. + The read-only attribute for files will be ignored. + + \note This function should not be used to delete the 8.3 version of + a directory that has a long name. See remove() and rmDir(). + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t SdFile::rmRfStar(void) { + rewind(); + while (curPosition_ < fileSize_) { + SdFile f; + + // remember position + uint16_t index = curPosition_ / 32; + + dir_t* p = readDirCache(); + if (!p) { + return false; + } + + // done if past last entry + if (p->name[0] == DIR_NAME_FREE) { + break; + } + + // skip empty slot or '.' or '..' + if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') { + continue; + } + + // skip if part of long file name or volume label in root + if (!DIR_IS_FILE_OR_SUBDIR(p)) { + continue; + } + + if (!f.open(this, index, O_READ)) { + return false; + } + if (f.isSubDir()) { + // recursively delete + if (!f.rmRfStar()) { + return false; + } + } else { + // ignore read-only + f.flags_ |= O_WRITE; + if (!f.remove()) { + return false; + } + } + // position to next entry if required + if (curPosition_ != (32u * (index + 1))) { + if (!seekSet(32u * (index + 1))) { + return false; + } + } + } + // don't try to delete root + if (isRoot()) { + return true; + } + return rmDir(); +} +//------------------------------------------------------------------------------ +/** + Sets a file's position. + + \param[in] pos The new position in bytes from the beginning of the file. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t SdFile::seekSet(uint32_t pos) { + // error if file not open or seek past end of file + if (!isOpen() || pos > fileSize_) { + return false; + } + + if (type_ == FAT_FILE_TYPE_ROOT16) { + curPosition_ = pos; + return true; + } + if (pos == 0) { + // set position to start of file + curCluster_ = 0; + curPosition_ = 0; + return true; + } + // calculate cluster index for cur and new position + uint32_t nCur = (curPosition_ - 1) >> (vol_->clusterSizeShift_ + 9); + uint32_t nNew = (pos - 1) >> (vol_->clusterSizeShift_ + 9); + + if (nNew < nCur || curPosition_ == 0) { + // must follow chain from first cluster + curCluster_ = firstCluster_; + } else { + // advance from curPosition + nNew -= nCur; + } + while (nNew--) { + if (!vol_->fatGet(curCluster_, &curCluster_)) { + return false; + } + } + curPosition_ = pos; + return true; +} +//------------------------------------------------------------------------------ +/** + The sync() call causes all modified data and directory fields + to be written to the storage device. + + \param[in] blocking If the sync should block until fully complete. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include a call to sync() before a file has been + opened or an I/O error. +*/ +uint8_t SdFile::sync(uint8_t blocking) { + // only allow open files and directories + if (!isOpen()) { + return false; + } + + if (flags_ & F_FILE_DIR_DIRTY) { + dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!d) { + return false; + } + + // do not set filesize for dir files + if (!isDir()) { + d->fileSize = fileSize_; + } + + // update first cluster fields + d->firstClusterLow = firstCluster_ & 0XFFFF; + d->firstClusterHigh = firstCluster_ >> 16; + + // set modify time if user supplied a callback date/time function + if (dateTime_) { + dateTime_(&d->lastWriteDate, &d->lastWriteTime); + d->lastAccessDate = d->lastWriteDate; + } + // clear directory dirty + flags_ &= ~F_FILE_DIR_DIRTY; + } + + if (!blocking) { + flags_ &= ~F_FILE_NON_BLOCKING_WRITE; + } + + return SdVolume::cacheFlush(blocking); +} +//------------------------------------------------------------------------------ +/** + Set a file's timestamps in its directory entry. + + \param[in] flags Values for \a flags are constructed by a bitwise-inclusive + OR of flags from the following list + + T_ACCESS - Set the file's last access date. + + T_CREATE - Set the file's creation date and time. + + T_WRITE - Set the file's last write/modification date and time. + + \param[in] year Valid range 1980 - 2107 inclusive. + + \param[in] month Valid range 1 - 12 inclusive. + + \param[in] day Valid range 1 - 31 inclusive. + + \param[in] hour Valid range 0 - 23 inclusive. + + \param[in] minute Valid range 0 - 59 inclusive. + + \param[in] second Valid range 0 - 59 inclusive + + \note It is possible to set an invalid date since there is no check for + the number of days in a month. + + \note + Modify and access timestamps may be overwritten if a date time callback + function has been set by dateTimeCallback(). + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t SdFile::timestamp(uint8_t flags, uint16_t year, uint8_t month, + uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) { + if (!isOpen() + || year < 1980 + || year > 2107 + || month < 1 + || month > 12 + || day < 1 + || day > 31 + || hour > 23 + || minute > 59 + || second > 59) { + return false; + } + dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!d) { + return false; + } + + uint16_t dirDate = FAT_DATE(year, month, day); + uint16_t dirTime = FAT_TIME(hour, minute, second); + if (flags & T_ACCESS) { + d->lastAccessDate = dirDate; + } + if (flags & T_CREATE) { + d->creationDate = dirDate; + d->creationTime = dirTime; + // seems to be units of 1/100 second not 1/10 as Microsoft states + d->creationTimeTenths = second & 1 ? 100 : 0; + } + if (flags & T_WRITE) { + d->lastWriteDate = dirDate; + d->lastWriteTime = dirTime; + } + SdVolume::cacheSetDirty(); + return sync(); +} +//------------------------------------------------------------------------------ +/** + Truncate a file to a specified length. The current file position + will be maintained if it is less than or equal to \a length otherwise + it will be set to end of file. + + \param[in] length The desired length for the file. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include file is read only, file is a directory, + \a length is greater than the current file size or an I/O error occurs. +*/ +uint8_t SdFile::truncate(uint32_t length) { + // error if not a normal file or read-only + if (!isFile() || !(flags_ & O_WRITE)) { + return false; + } + + // error if length is greater than current size + if (length > fileSize_) { + return false; + } + + // fileSize and length are zero - nothing to do + if (fileSize_ == 0) { + return true; + } + + // remember position for seek after truncation + uint32_t newPos = curPosition_ > length ? length : curPosition_; + + // position to last cluster in truncated file + if (!seekSet(length)) { + return false; + } + + if (length == 0) { + // free all clusters + if (!vol_->freeChain(firstCluster_)) { + return false; + } + firstCluster_ = 0; + } else { + uint32_t toFree; + if (!vol_->fatGet(curCluster_, &toFree)) { + return false; + } + + if (!vol_->isEOC(toFree)) { + // free extra clusters + if (!vol_->freeChain(toFree)) { + return false; + } + + // current cluster is end of chain + if (!vol_->fatPutEOC(curCluster_)) { + return false; + } + } + } + fileSize_ = length; + + // need to update directory entry + flags_ |= F_FILE_DIR_DIRTY; + + if (!sync()) { + return false; + } + + // set file to correct position + return seekSet(newPos); +} +//------------------------------------------------------------------------------ +/** + Write data to an open file. + + \note Data is moved to the cache but may not be written to the + storage device until sync() is called. + + \param[in] buf Pointer to the location of the data to be written. + + \param[in] nbyte Number of bytes to write. + + \return For success write() returns the number of bytes written, always + \a nbyte. If an error occurs, write() returns 0. Possible errors + include write() is called before a file has been opened, write is called + for a read-only file, device is full, a corrupt file system or an I/O error. + +*/ +size_t SdFile::write(const void* buf, uint16_t nbyte) { + // convert void* to uint8_t* - must be before goto statements + const uint8_t* src = reinterpret_cast(buf); + + // number of bytes left to write - must be before goto statements + uint16_t nToWrite = nbyte; + // if blocking writes should be used + uint8_t blocking = (flags_ & F_FILE_NON_BLOCKING_WRITE) == 0x00; + + // error if not a normal file or is read-only + if (!isFile() || !(flags_ & O_WRITE)) { + goto writeErrorReturn; + } + + // seek to end of file if append flag + if ((flags_ & O_APPEND) && curPosition_ != fileSize_) { + if (!seekEnd()) { + goto writeErrorReturn; + } + } + + while (nToWrite > 0) { + uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_); + uint16_t blockOffset = curPosition_ & 0X1FF; + if (blockOfCluster == 0 && blockOffset == 0) { + // start of new cluster + if (curCluster_ == 0) { + if (firstCluster_ == 0) { + // allocate first cluster of file + if (!addCluster()) { + goto writeErrorReturn; + } + } else { + curCluster_ = firstCluster_; + } + } else { + uint32_t next; + if (!vol_->fatGet(curCluster_, &next)) { + return false; + } + if (vol_->isEOC(next)) { + // add cluster if at end of chain + if (!addCluster()) { + goto writeErrorReturn; + } + } else { + curCluster_ = next; + } + } + } + // max space in block + uint16_t n = 512 - blockOffset; + + // lesser of space and amount to write + if (n > nToWrite) { + n = nToWrite; + } + + // block for data write + uint32_t block = vol_->clusterStartBlock(curCluster_) + blockOfCluster; + if (n == 512) { + // full block - don't need to use cache + // invalidate cache if block is in cache + if (SdVolume::cacheBlockNumber_ == block) { + SdVolume::cacheBlockNumber_ = 0XFFFFFFFF; + } + if (!vol_->writeBlock(block, src, blocking)) { + goto writeErrorReturn; + } + src += 512; + } else { + if (blockOffset == 0 && curPosition_ >= fileSize_) { + // start of new block don't need to read into cache + if (!SdVolume::cacheFlush()) { + goto writeErrorReturn; + } + SdVolume::cacheBlockNumber_ = block; + SdVolume::cacheSetDirty(); + } else { + // rewrite part of block + if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) { + goto writeErrorReturn; + } + } + uint8_t* dst = SdVolume::cacheBuffer_.data + blockOffset; + uint8_t* end = dst + n; + while (dst != end) { + *dst++ = *src++; + } + } + nToWrite -= n; + curPosition_ += n; + } + if (curPosition_ > fileSize_) { + // update fileSize and insure sync will update dir entry + fileSize_ = curPosition_; + flags_ |= F_FILE_DIR_DIRTY; + } else if (dateTime_ && nbyte) { + // insure sync will update modified date and time + flags_ |= F_FILE_DIR_DIRTY; + } + + if (flags_ & O_SYNC) { + if (!sync()) { + goto writeErrorReturn; + } + } + return nbyte; + +writeErrorReturn: + // return for write error + //writeError = true; + setWriteError(); + return 0; +} +//------------------------------------------------------------------------------ +/** + Write a byte to a file. Required by the Arduino Print class. + + Use SdFile::writeError to check for errors. +*/ +size_t SdFile::write(uint8_t b) { + return write(&b, 1); +} +//------------------------------------------------------------------------------ +/** + Write a string to a file. Used by the Arduino Print class. + + Use SdFile::writeError to check for errors. +*/ +size_t SdFile::write(const char* str) { + return write(str, strlen(str)); +} +#ifdef __AVR__ +//------------------------------------------------------------------------------ +/** + Write a PROGMEM string to a file. + + Use SdFile::writeError to check for errors. +*/ +void SdFile::write_P(PGM_P str) { + for (uint8_t c; (c = pgm_read_byte(str)); str++) { + write(c); + } +} +//------------------------------------------------------------------------------ +/** + Write a PROGMEM string followed by CR/LF to a file. + + Use SdFile::writeError to check for errors. +*/ +void SdFile::writeln_P(PGM_P str) { + write_P(str); + println(); +} +#endif +//------------------------------------------------------------------------------ +/** + Check how many bytes can be written without blocking. + + \return The number of bytes that can be written without blocking. +*/ +int SdFile::availableForWrite() { + if (!isFile() || !(flags_ & O_WRITE)) { + return 0; + } + + // seek to end of file if append flag + if ((flags_ & O_APPEND) && curPosition_ != fileSize_) { + if (!seekEnd()) { + return 0; + } + } + + if (vol_->isBusy()) { + return 0; + } + + if (flags_ & F_FILE_CLUSTER_ADDED) { + // new cluster added, trigger a non-blocking sync + sync(0); + flags_ &= ~F_FILE_CLUSTER_ADDED; + return 0; + } + + if (vol_->isCacheMirrorBlockDirty()) { + // cache mirror block is dirty, trigger a non-blocking sync + vol_->cacheMirrorBlockFlush(0); + return 0; + } + + flags_ |= F_FILE_NON_BLOCKING_WRITE; + + uint16_t blockOffset = curPosition_ & 0X1FF; + uint16_t n = 512 - blockOffset; + + return n; +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdInfo.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdInfo.h new file mode 100755 index 0000000..6a0e087 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdInfo.h @@ -0,0 +1,232 @@ +/* Arduino Sd2Card Library + Copyright (C) 2009 by William Greiman + + This file is part of the Arduino Sd2Card Library + + This Library 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 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino Sd2Card Library. If not, see + . +*/ +#ifndef SdInfo_h +#define SdInfo_h +#include +// Based on the document: +// +// SD Specifications +// Part 1 +// Physical Layer +// Simplified Specification +// Version 2.00 +// September 25, 2006 +// +// www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf +//------------------------------------------------------------------------------ +// SD card commands +/** GO_IDLE_STATE - init card in spi mode if CS low */ +uint8_t const CMD0 = 0X00; +/** SEND_IF_COND - verify SD Memory Card interface operating condition.*/ +uint8_t const CMD8 = 0X08; +/** SEND_CSD - read the Card Specific Data (CSD register) */ +uint8_t const CMD9 = 0X09; +/** SEND_CID - read the card identification information (CID register) */ +uint8_t const CMD10 = 0X0A; +/** SEND_STATUS - read the card status register */ +uint8_t const CMD13 = 0X0D; +/** READ_BLOCK - read a single data block from the card */ +uint8_t const CMD17 = 0X11; +/** WRITE_BLOCK - write a single data block to the card */ +uint8_t const CMD24 = 0X18; +/** WRITE_MULTIPLE_BLOCK - write blocks of data until a STOP_TRANSMISSION */ +uint8_t const CMD25 = 0X19; +/** ERASE_WR_BLK_START - sets the address of the first block to be erased */ +uint8_t const CMD32 = 0X20; +/** ERASE_WR_BLK_END - sets the address of the last block of the continuous + range to be erased*/ +uint8_t const CMD33 = 0X21; +/** ERASE - erase all previously selected blocks */ +uint8_t const CMD38 = 0X26; +/** APP_CMD - escape for application specific command */ +uint8_t const CMD55 = 0X37; +/** READ_OCR - read the OCR register of a card */ +uint8_t const CMD58 = 0X3A; +/** SET_WR_BLK_ERASE_COUNT - Set the number of write blocks to be + pre-erased before writing */ +uint8_t const ACMD23 = 0X17; +/** SD_SEND_OP_COMD - Sends host capacity support information and + activates the card's initialization process */ +uint8_t const ACMD41 = 0X29; +//------------------------------------------------------------------------------ +/** status for card in the ready state */ +uint8_t const R1_READY_STATE = 0X00; +/** status for card in the idle state */ +uint8_t const R1_IDLE_STATE = 0X01; +/** status bit for illegal command */ +uint8_t const R1_ILLEGAL_COMMAND = 0X04; +/** start data token for read or write single block*/ +uint8_t const DATA_START_BLOCK = 0XFE; +/** stop token for write multiple blocks*/ +uint8_t const STOP_TRAN_TOKEN = 0XFD; +/** start data token for write multiple blocks*/ +uint8_t const WRITE_MULTIPLE_TOKEN = 0XFC; +/** mask for data response tokens after a write block operation */ +uint8_t const DATA_RES_MASK = 0X1F; +/** write data accepted token */ +uint8_t const DATA_RES_ACCEPTED = 0X05; +//------------------------------------------------------------------------------ +typedef struct CID { + // byte 0 + uint8_t mid; // Manufacturer ID + // byte 1-2 + char oid[2]; // OEM/Application ID + // byte 3-7 + char pnm[5]; // Product name + // byte 8 + unsigned prv_m : 4; // Product revision n.m + unsigned prv_n : 4; + // byte 9-12 + uint32_t psn; // Product serial number + // byte 13 + unsigned mdt_year_high : 4; // Manufacturing date + unsigned reserved : 4; + // byte 14 + unsigned mdt_month : 4; + unsigned mdt_year_low : 4; + // byte 15 + unsigned always1 : 1; + unsigned crc : 7; +} cid_t; +//------------------------------------------------------------------------------ +// CSD for version 1.00 cards +typedef struct CSDV1 { + // byte 0 + unsigned reserved1 : 6; + unsigned csd_ver : 2; + // byte 1 + uint8_t taac; + // byte 2 + uint8_t nsac; + // byte 3 + uint8_t tran_speed; + // byte 4 + uint8_t ccc_high; + // byte 5 + unsigned read_bl_len : 4; + unsigned ccc_low : 4; + // byte 6 + unsigned c_size_high : 2; + unsigned reserved2 : 2; + unsigned dsr_imp : 1; + unsigned read_blk_misalign : 1; + unsigned write_blk_misalign : 1; + unsigned read_bl_partial : 1; + // byte 7 + uint8_t c_size_mid; + // byte 8 + unsigned vdd_r_curr_max : 3; + unsigned vdd_r_curr_min : 3; + unsigned c_size_low : 2; + // byte 9 + unsigned c_size_mult_high : 2; + unsigned vdd_w_cur_max : 3; + unsigned vdd_w_curr_min : 3; + // byte 10 + unsigned sector_size_high : 6; + unsigned erase_blk_en : 1; + unsigned c_size_mult_low : 1; + // byte 11 + unsigned wp_grp_size : 7; + unsigned sector_size_low : 1; + // byte 12 + unsigned write_bl_len_high : 2; + unsigned r2w_factor : 3; + unsigned reserved3 : 2; + unsigned wp_grp_enable : 1; + // byte 13 + unsigned reserved4 : 5; + unsigned write_partial : 1; + unsigned write_bl_len_low : 2; + // byte 14 + unsigned reserved5: 2; + unsigned file_format : 2; + unsigned tmp_write_protect : 1; + unsigned perm_write_protect : 1; + unsigned copy : 1; + unsigned file_format_grp : 1; + // byte 15 + unsigned always1 : 1; + unsigned crc : 7; +} csd1_t; +//------------------------------------------------------------------------------ +// CSD for version 2.00 cards +typedef struct CSDV2 { + // byte 0 + unsigned reserved1 : 6; + unsigned csd_ver : 2; + // byte 1 + uint8_t taac; + // byte 2 + uint8_t nsac; + // byte 3 + uint8_t tran_speed; + // byte 4 + uint8_t ccc_high; + // byte 5 + unsigned read_bl_len : 4; + unsigned ccc_low : 4; + // byte 6 + unsigned reserved2 : 4; + unsigned dsr_imp : 1; + unsigned read_blk_misalign : 1; + unsigned write_blk_misalign : 1; + unsigned read_bl_partial : 1; + // byte 7 + unsigned reserved3 : 2; + unsigned c_size_high : 6; + // byte 8 + uint8_t c_size_mid; + // byte 9 + uint8_t c_size_low; + // byte 10 + unsigned sector_size_high : 6; + unsigned erase_blk_en : 1; + unsigned reserved4 : 1; + // byte 11 + unsigned wp_grp_size : 7; + unsigned sector_size_low : 1; + // byte 12 + unsigned write_bl_len_high : 2; + unsigned r2w_factor : 3; + unsigned reserved5 : 2; + unsigned wp_grp_enable : 1; + // byte 13 + unsigned reserved6 : 5; + unsigned write_partial : 1; + unsigned write_bl_len_low : 2; + // byte 14 + unsigned reserved7: 2; + unsigned file_format : 2; + unsigned tmp_write_protect : 1; + unsigned perm_write_protect : 1; + unsigned copy : 1; + unsigned file_format_grp : 1; + // byte 15 + unsigned always1 : 1; + unsigned crc : 7; +} csd2_t; +//------------------------------------------------------------------------------ +// union of old and new style CSD register +union csd_t { + csd1_t v1; + csd2_t v2; +}; +#endif // SdInfo_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdVolume.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdVolume.cpp new file mode 100755 index 0000000..60375c4 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdVolume.cpp @@ -0,0 +1,351 @@ +/* Arduino SdFat Library + Copyright (C) 2009 by William Greiman + + This file is part of the Arduino SdFat Library + + This Library 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 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino SdFat Library. If not, see + . +*/ +#include "SdFat.h" +//------------------------------------------------------------------------------ +// raw block cache +// init cacheBlockNumber_to invalid SD block number +uint32_t SdVolume::cacheBlockNumber_ = 0XFFFFFFFF; +cache_t SdVolume::cacheBuffer_; // 512 byte cache for Sd2Card +Sd2Card* SdVolume::sdCard_; // pointer to SD card object +uint8_t SdVolume::cacheDirty_ = 0; // cacheFlush() will write block if true +uint32_t SdVolume::cacheMirrorBlock_ = 0; // mirror block for second FAT +//------------------------------------------------------------------------------ +// find a contiguous group of clusters +uint8_t SdVolume::allocContiguous(uint32_t count, uint32_t* curCluster) { + // start of group + uint32_t bgnCluster; + + // flag to save place to start next search + uint8_t setStart; + + // set search start cluster + if (*curCluster) { + // try to make file contiguous + bgnCluster = *curCluster + 1; + + // don't save new start location + setStart = false; + } else { + // start at likely place for free cluster + bgnCluster = allocSearchStart_; + + // save next search start if one cluster + setStart = 1 == count; + } + // end of group + uint32_t endCluster = bgnCluster; + + // last cluster of FAT + uint32_t fatEnd = clusterCount_ + 1; + + // search the FAT for free clusters + for (uint32_t n = 0;; n++, endCluster++) { + // can't find space checked all clusters + if (n >= clusterCount_) { + return false; + } + + // past end - start from beginning of FAT + if (endCluster > fatEnd) { + bgnCluster = endCluster = 2; + } + uint32_t f; + if (!fatGet(endCluster, &f)) { + return false; + } + + if (f != 0) { + // cluster in use try next cluster as bgnCluster + bgnCluster = endCluster + 1; + } else if ((endCluster - bgnCluster + 1) == count) { + // done - found space + break; + } + } + // mark end of chain + if (!fatPutEOC(endCluster)) { + return false; + } + + // link clusters + while (endCluster > bgnCluster) { + if (!fatPut(endCluster - 1, endCluster)) { + return false; + } + endCluster--; + } + if (*curCluster != 0) { + // connect chains + if (!fatPut(*curCluster, bgnCluster)) { + return false; + } + } + // return first cluster number to caller + *curCluster = bgnCluster; + + // remember possible next free cluster + if (setStart) { + allocSearchStart_ = bgnCluster + 1; + } + + return true; +} +//------------------------------------------------------------------------------ +uint8_t SdVolume::cacheFlush(uint8_t blocking) { + if (cacheDirty_) { + if (!sdCard_->writeBlock(cacheBlockNumber_, cacheBuffer_.data, blocking)) { + return false; + } + + if (!blocking) { + return true; + } + + // mirror FAT tables + if (!cacheMirrorBlockFlush(blocking)) { + return false; + } + cacheDirty_ = 0; + } + return true; +} +//------------------------------------------------------------------------------ +uint8_t SdVolume::cacheMirrorBlockFlush(uint8_t blocking) { + if (cacheMirrorBlock_) { + if (!sdCard_->writeBlock(cacheMirrorBlock_, cacheBuffer_.data, blocking)) { + return false; + } + cacheMirrorBlock_ = 0; + } + return true; +} +//------------------------------------------------------------------------------ +uint8_t SdVolume::cacheRawBlock(uint32_t blockNumber, uint8_t action) { + if (cacheBlockNumber_ != blockNumber) { + if (!cacheFlush()) { + return false; + } + if (!sdCard_->readBlock(blockNumber, cacheBuffer_.data)) { + return false; + } + cacheBlockNumber_ = blockNumber; + } + cacheDirty_ |= action; + return true; +} +//------------------------------------------------------------------------------ +// cache a zero block for blockNumber +uint8_t SdVolume::cacheZeroBlock(uint32_t blockNumber) { + if (!cacheFlush()) { + return false; + } + + // loop take less flash than memset(cacheBuffer_.data, 0, 512); + for (uint16_t i = 0; i < 512; i++) { + cacheBuffer_.data[i] = 0; + } + cacheBlockNumber_ = blockNumber; + cacheSetDirty(); + return true; +} +//------------------------------------------------------------------------------ +// return the size in bytes of a cluster chain +uint8_t SdVolume::chainSize(uint32_t cluster, uint32_t* size) const { + uint32_t s = 0; + do { + if (!fatGet(cluster, &cluster)) { + return false; + } + s += 512UL << clusterSizeShift_; + } while (!isEOC(cluster)); + *size = s; + return true; +} +//------------------------------------------------------------------------------ +// Fetch a FAT entry +uint8_t SdVolume::fatGet(uint32_t cluster, uint32_t* value) const { + if (cluster > (clusterCount_ + 1)) { + return false; + } + uint32_t lba = fatStartBlock_; + lba += fatType_ == 16 ? cluster >> 8 : cluster >> 7; + if (lba != cacheBlockNumber_) { + if (!cacheRawBlock(lba, CACHE_FOR_READ)) { + return false; + } + } + if (fatType_ == 16) { + *value = cacheBuffer_.fat16[cluster & 0XFF]; + } else { + *value = cacheBuffer_.fat32[cluster & 0X7F] & FAT32MASK; + } + return true; +} +//------------------------------------------------------------------------------ +// Store a FAT entry +uint8_t SdVolume::fatPut(uint32_t cluster, uint32_t value) { + // error if reserved cluster + if (cluster < 2) { + return false; + } + + // error if not in FAT + if (cluster > (clusterCount_ + 1)) { + return false; + } + + // calculate block address for entry + uint32_t lba = fatStartBlock_; + lba += fatType_ == 16 ? cluster >> 8 : cluster >> 7; + + if (lba != cacheBlockNumber_) { + if (!cacheRawBlock(lba, CACHE_FOR_READ)) { + return false; + } + } + // store entry + if (fatType_ == 16) { + cacheBuffer_.fat16[cluster & 0XFF] = value; + } else { + cacheBuffer_.fat32[cluster & 0X7F] = value; + } + cacheSetDirty(); + + // mirror second FAT + if (fatCount_ > 1) { + cacheMirrorBlock_ = lba + blocksPerFat_; + } + return true; +} +//------------------------------------------------------------------------------ +// free a cluster chain +uint8_t SdVolume::freeChain(uint32_t cluster) { + // clear free cluster location + allocSearchStart_ = 2; + + do { + uint32_t next; + if (!fatGet(cluster, &next)) { + return false; + } + + // free cluster + if (!fatPut(cluster, 0)) { + return false; + } + + cluster = next; + } while (!isEOC(cluster)); + + return true; +} +//------------------------------------------------------------------------------ +/** + Initialize a FAT volume. + + \param[in] dev The SD card where the volume is located. + + \param[in] part The partition to be used. Legal values for \a part are + 1-4 to use the corresponding partition on a device formatted with + a MBR, Master Boot Record, or zero if the device is formatted as + a super floppy with the FAT boot sector in block zero. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. Reasons for + failure include not finding a valid partition, not finding a valid + FAT file system in the specified partition or an I/O error. +*/ +uint8_t SdVolume::init(Sd2Card* dev, uint8_t part) { + uint32_t volumeStartBlock = 0; + sdCard_ = dev; + // if part == 0 assume super floppy with FAT boot sector in block zero + // if part > 0 assume mbr volume with partition table + if (part) { + if (part > 4) { + return false; + } + if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) { + return false; + } + part_t* p = &cacheBuffer_.mbr.part[part - 1]; + if ((p->boot & 0X7F) != 0 || + p->totalSectors < 100 || + p->firstSector == 0) { + // not a valid partition + return false; + } + volumeStartBlock = p->firstSector; + } + if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) { + return false; + } + bpb_t* bpb = &cacheBuffer_.fbs.bpb; + if (bpb->bytesPerSector != 512 || + bpb->fatCount == 0 || + bpb->reservedSectorCount == 0 || + bpb->sectorsPerCluster == 0) { + // not valid FAT volume + return false; + } + fatCount_ = bpb->fatCount; + blocksPerCluster_ = bpb->sectorsPerCluster; + + // determine shift that is same as multiply by blocksPerCluster_ + clusterSizeShift_ = 0; + while (blocksPerCluster_ != (1 << clusterSizeShift_)) { + // error if not power of 2 + if (clusterSizeShift_++ > 7) { + return false; + } + } + blocksPerFat_ = bpb->sectorsPerFat16 ? + bpb->sectorsPerFat16 : bpb->sectorsPerFat32; + + fatStartBlock_ = volumeStartBlock + bpb->reservedSectorCount; + + // count for FAT16 zero for FAT32 + rootDirEntryCount_ = bpb->rootDirEntryCount; + + // directory start for FAT16 dataStart for FAT32 + rootDirStart_ = fatStartBlock_ + bpb->fatCount * blocksPerFat_; + + // data start for FAT16 and FAT32 + dataStartBlock_ = rootDirStart_ + ((32 * bpb->rootDirEntryCount + 511) / 512); + + // total blocks for FAT16 or FAT32 + uint32_t totalBlocks = bpb->totalSectors16 ? + bpb->totalSectors16 : bpb->totalSectors32; + // total data blocks + clusterCount_ = totalBlocks - (dataStartBlock_ - volumeStartBlock); + + // divide by cluster size to get cluster count + clusterCount_ >>= clusterSizeShift_; + + // FAT type is determined by cluster count + if (clusterCount_ < 4085) { + fatType_ = 12; + } else if (clusterCount_ < 65525) { + fatType_ = 16; + } else { + rootDirStart_ = bpb->fat32RootCluster; + fatType_ = 32; + } + return true; +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/.travis.yml b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/.travis.yml new file mode 100644 index 0000000..465c761 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/.travis.yml @@ -0,0 +1,48 @@ +language: generic +env: + global: + - IDE_VERSION=1.8.2 + matrix: + - BOARD="arduino:avr:uno" + - BOARD="arduino:avr:mega:cpu=atmega2560" + - BOARD="arduino:sam:arduino_due_x_dbg" + - BOARD="arduino:samd:arduino_zero_edbg" + - BOARD="arduino:samd:mkr1000" + - BOARD="Intel:arc32:arduino_101" +before_install: + - wget http://downloads.arduino.cc/arduino-$IDE_VERSION-linux64.tar.xz + - tar xf arduino-$IDE_VERSION-linux64.tar.xz + - mv arduino-$IDE_VERSION $HOME/arduino-ide + - export PATH=$PATH:$HOME/arduino-ide + - if [[ "$BOARD" =~ "arduino:sam:" ]]; then + arduino --install-boards arduino:sam; + fi + - if [[ "$BOARD" =~ "arduino:samd:" ]]; then + arduino --install-boards arduino:samd; + fi + - if [[ "$BOARD" =~ "Intel:arc32" ]]; then + arduino --install-boards Intel:arc32; + fi + - buildExampleSketch() { arduino --verbose-build --verify --board $BOARD $PWD/examples/$1/$1.ino; } +install: + - mkdir -p $HOME/Arduino/libraries + - ln -s $PWD $HOME/Arduino/libraries/. +script: + - buildExampleSketch AP_SimpleWebServer + - buildExampleSketch CheckWifi101FirmwareVersion + - buildExampleSketch ConnectNoEncryption + - buildExampleSketch ConnectWithWEP + - buildExampleSketch ConnectWithWPA + - buildExampleSketch FirmwareUpdater + - buildExampleSketch MDNS_WiFiWebServer + - buildExampleSketch ScanNetworks + - buildExampleSketch SimpleWebServerWiFi + - buildExampleSketch WiFiChatServer + - buildExampleSketch WiFiPing + - buildExampleSketch WiFiSSLClient + - buildExampleSketch WiFiUdpNtpClient + - buildExampleSketch WiFiUdpSendReceiveString + - buildExampleSketch WiFiWebClient + - buildExampleSketch WiFiWebClientRepeating + - buildExampleSketch WiFiWebServer + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/CHANGELOG b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/CHANGELOG new file mode 100644 index 0000000..fbe1643 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/CHANGELOG @@ -0,0 +1,122 @@ +WiFi101 ?.?.? - ????.??.?? + +WiFi101 0.14.3 - 2017.06.01 + +* Fixed issues with WiFiMDNSResponder and large request packets +* Fixed issues with WiFiClient and sending data after the socket is closed + +WiFi101 0.14.2 - 2017.05.08 + +* Fixed issues with WiFiServer::write not working + +WiFi101 0.14.1 - 2017.04.20 + +* Fixed issues with WiFiMDNSResponder and Windows using Bonjour +* Correct cast of buffer size when processing received data + +WiFi101 0.14.0 - 2017.03.22 + +* Added support for firmware 19.5.2 +* Add ability to create Access Point with WPA security (f/w 19.5.2 or higher) +* Add WiFi.hostname(name) method to set custom host name for DHCP (f/w 19.5.2 or higher) +* Enables support for AES-256 Ciphers (f/w 19.5.2 or higher) +* Make provisioning mode backwards compatible with f/w 19.4.4 and older + +WiFi101 0.13.0 - 2017.03.01 + +* Added WiFi.channel() and WiFi.BSSID() + +WiFi101 0.12.1 - 2017.01.19 + +* Fixed tomorrow day issue in WiFi.getTime() + +WiFi101 0.12.0 - 2017.01.05 + +* Made provisioning mode easier and added example sketch +* Fixed WiFi.getTime() not returning 0, if time has not been synced via NTP +* Fixed crashing when connecting after scanning +* Fixed WiFiServer::available() returning valid client on outbound client connection +* Added WiFiUdp::beginMulticast(port) function for compatiblity with EthernetUdp, as beginMulti was inconsistent + +WiFi101 0.11.2 - 2016.12.15 + +* Fixed value of WiFi.getTime() being off by one day +* Fixed calling WiFi.RSSI() causing lockups + +WiFi101 0.11.1 - 2016.11.29 + +* Fixed regression for non-AVR boards that resulted in corrupt with data over than 1400 bytes was received + +WiFi101 0.11.0 - 2016.11.14 + +* Changed WiFi.ping(...) to return round trip time on success, negative value on error. Thanks @PKGeorgiev +* WiFi.end() now powers down the WiFi module +* WiFi.config(ip) can now be used to set a static IP for WiFi.begin(...) +* Fixed WiFi.BSSID(bssid) returning reversed MAC address +* Added WiFi.APClientMacAddress() API to get MAC address of AP client in AP mode +* Added WiFi.getTime() API to get epoch from NTP + +WiFi101 0.10.0 - 2016.09.08 + +* Added WiFi.end() to disconnect from the AP or end AP mode +* Added new WiFi.ping(...) functionality. Thanks @PKGeorgiev +* Added WiFi.setPins(...) to customize the CS, INTN, RESET and CHIPEN pins +* Add new WL_AP_LISTENING, WL_AP_CONNECTED, and WL_AP_FAILED status types for AP mode +* Fixed return value of WiFiUDP::beginPacket(host, port) when host is successfully resolved +* Added power management methods: WiFi.lowPowerMode(), WiFi.maxLowPowerMode(), WiFi.noLowPowerMode() +* Close TCP sockets when physical link is disconnected +* Fixed WiFi.RSSI() returning 0 when there was pending socket data + +WiFi101 0.9.1 - 2016.04.19 + +* Increased compatibility with 3rd party boards and architectures. +* Rename WiFiMdnsResponder.h/cpp to WiFiMDNSResponder.h/cpp +* Fixed buffering of UDP packet + +WiFi101 0.9.0 - 2016.03.21 + +* Fixed WiFi.status() hanging when shield is not present +* Fixed MAC address returning 00:00:00:00:00:00 with firmware version 19.3.0 +* Fixed SSL write functionality with firmware version 19.3.0 +* Fixed previous version of the library not working on the Uno and other boards that used PCINT's +* Added beginAP(...) API's to create access point with WEP passwords +* Fixed beginAP(...) channel off by one error +* Fixed WiFi.status() always returning WL_CONNECTED once connected, even if access point is disconnected later +* Added beginMulti API for Multicast UDP support +* Added WiFiMDNSResponder class and MDNS Web server example + +WiFi101 0.8.0 - 2016.02.15 + +* Added example for Access Point web server (thanks @ladyada) +* Fixed MAC Address printed in reverse order +* Allow another library to override PCINT ISR (fix issues when using the WiFi101 + library with other libraries like SoftwareSerial) + +WiFi101 0.7.0 - 2015.01.11 + +* Added support for WiFi Firmware 19.4.4 +* WiFi.hostByName(...) will not try resolve the domain name if it's already a numeric IP +* Fixed manual IP configuration (no DHCP) +* Fixed WiFiServer.available(), now follows API specification +* Fixed WEP key connection +* Fixed WiFiClient copy constructor and assignment operator. This improves stability when + Client objects are assigned or returned from functions. +* Control pins are now configurable through defines from variant. + +WiFi101 0.6.0 - 2015.11.27 + +* Fixed bug with AVR boards when Web Server is used +* Fixed UDP read bug on AVR Boards +* Added missing inlcude for SSL Client +* Fixed peek() function +* Fixed some examples + +WiFi101 0.5.1 - 2015.10.06 + +* Improved support for AVR Boards (Uno, Mega, Leonardo, etc.) and + ARM based boards (Due and Zero). + +WiFi101 0.5.0 - 2015.10.01 + +* Initial release + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/README.adoc b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/README.adoc new file mode 100644 index 0000000..8eb6924 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/README.adoc @@ -0,0 +1,27 @@ += WiFi library for the Arduino WiFi Shield 101 and MKR1000 board = + +image:https://travis-ci.org/arduino-libraries/WiFi101.svg?branch=master["Build Status", link="https://travis-ci.org/arduino-libraries/WiFi101"] + +This library implements a network driver for devices based +on the ATMEL WINC1500 WiFi module. + +For more information about this library please visit us at +https://www.arduino.cc/en/Reference/WiFi101 + +== License == + +Copyright (c) Arduino LLC. All right reserved. + +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 2.1 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 Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino new file mode 100644 index 0000000..b5caf7a --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino @@ -0,0 +1,176 @@ +/* + WiFi Web Server LED Blink + + A simple web server that lets you blink an LED via the web. + This sketch will create a new access point (with no password). + It will then launch a new server and print out the IP address + to the Serial monitor. From there, you can open that address in a web browser + to turn on and off the LED on pin 13. + + If the IP address of your shield is yourAddress: + http://yourAddress/H turns the LED on + http://yourAddress/L turns it off + + created 25 Nov 2012 + by Tom Igoe + adapted to WiFi AP by Adafruit + */ + +#include +#include +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int led = LED_BUILTIN; +int status = WL_IDLE_STATUS; +WiFiServer server(80); + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + Serial.println("Access Point Web Server"); + + pinMode(led, OUTPUT); // set the LED pin mode + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue + while (true); + } + + // by default the local IP address of will be 192.168.1.1 + // you can override it with the following: + // WiFi.config(IPAddress(10, 0, 0, 1)); + + // print the network name (SSID); + Serial.print("Creating access point named: "); + Serial.println(ssid); + + // Create open network. Change this line if you want to create an WEP network: + status = WiFi.beginAP(ssid); + if (status != WL_AP_LISTENING) { + Serial.println("Creating access point failed"); + // don't continue + while (true); + } + + // wait 10 seconds for connection: + delay(10000); + + // start the web server on port 80 + server.begin(); + + // you're connected now, so print out the status + printWiFiStatus(); +} + + +void loop() { + // compare the previous status to the current status + if (status != WiFi.status()) { + // it has changed update the variable + status = WiFi.status(); + + if (status == WL_AP_CONNECTED) { + byte remoteMac[6]; + + // a device has connected to the AP + Serial.print("Device connected to AP, MAC address: "); + WiFi.APClientMacAddress(remoteMac); + Serial.print(remoteMac[5], HEX); + Serial.print(":"); + Serial.print(remoteMac[4], HEX); + Serial.print(":"); + Serial.print(remoteMac[3], HEX); + Serial.print(":"); + Serial.print(remoteMac[2], HEX); + Serial.print(":"); + Serial.print(remoteMac[1], HEX); + Serial.print(":"); + Serial.println(remoteMac[0], HEX); + } else { + // a device has disconnected from the AP, and we are back in listening mode + Serial.println("Device disconnected from AP"); + } + } + + WiFiClient client = server.available(); // listen for incoming clients + + if (client) { // if you get a client, + Serial.println("new client"); // print a message out the serial port + String currentLine = ""; // make a String to hold incoming data from the client + while (client.connected()) { // loop while the client's connected + if (client.available()) { // if there's bytes to read from the client, + char c = client.read(); // read a byte, then + Serial.write(c); // print it out the serial monitor + if (c == '\n') { // if the byte is a newline character + + // if the current line is blank, you got two newline characters in a row. + // that's the end of the client HTTP request, so send a response: + if (currentLine.length() == 0) { + // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) + // and a content-type so the client knows what's coming, then a blank line: + client.println("HTTP/1.1 200 OK"); + client.println("Content-type:text/html"); + client.println(); + + // the content of the HTTP response follows the header: + client.print("Click here turn the LED on
"); + client.print("Click here turn the LED off
"); + + // The HTTP response ends with another blank line: + client.println(); + // break out of the while loop: + break; + } + else { // if you got a newline, then clear currentLine: + currentLine = ""; + } + } + else if (c != '\r') { // if you got anything else but a carriage return character, + currentLine += c; // add it to the end of the currentLine + } + + // Check to see if the client request was "GET /H" or "GET /L": + if (currentLine.endsWith("GET /H")) { + digitalWrite(led, HIGH); // GET /H turns the LED on + } + if (currentLine.endsWith("GET /L")) { + digitalWrite(led, LOW); // GET /L turns the LED off + } + } + } + // close the connection: + client.stop(); + Serial.println("client disconnected"); + } +} + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); + // print where to go in a browser: + Serial.print("To see this page in action, open a browser to http://"); + Serial.println(ip); + +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino new file mode 100644 index 0000000..8cd312e --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino @@ -0,0 +1,67 @@ +/* + * This example check if the firmware loaded on the WiFi101 + * shield is updated. + * + * Circuit: + * - WiFi101 Shield attached + * + * Created 29 July 2015 by Cristian Maglie + * This code is in the public domain. + */ +#include +#include +#include + +void setup() { + // Initialize serial + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // Print a welcome message + Serial.println("WiFi101 firmware check."); + Serial.println(); + + // Check for the presence of the shield + Serial.print("WiFi101 shield: "); + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("NOT PRESENT"); + return; // don't continue + } + Serial.println("DETECTED"); + + // Print firmware version on the shield + String fv = WiFi.firmwareVersion(); + String latestFv; + Serial.print("Firmware version installed: "); + Serial.println(fv); + + if (REV(GET_CHIPID()) >= REV_3A0) { + // model B + latestFv = WIFI_FIRMWARE_LATEST_MODEL_B; + } else { + // model A + latestFv = WIFI_FIRMWARE_LATEST_MODEL_A; + } + + // Print required firmware version + Serial.print("Latest firmware version available : "); + Serial.println(latestFv); + + // Check if the latest version is installed + Serial.println(); + if (fv == latestFv) { + Serial.println("Check result: PASSED"); + } else { + Serial.println("Check result: NOT PASSED"); + Serial.println(" - The firmware version on the shield do not match the"); + Serial.println(" version required by the library, you may experience"); + Serial.println(" issues or failures."); + } +} + +void loop() { + // do nothing +} + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino new file mode 100644 index 0000000..f43a232 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino @@ -0,0 +1,123 @@ +/* + + This example connects to an unencrypted WiFi network. + Then it prints the MAC address of the WiFi shield, + the IP address obtained, and other network details. + + Circuit: + * WiFi shield attached + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + */ +#include +#include +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +int status = WL_IDLE_STATUS; // the WiFi radio's status + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to open SSID: "); + Serial.println(ssid); + status = WiFi.begin(ssid); + + // wait 10 seconds for connection: + delay(10000); + } + + // you're connected now, so print out the data: + Serial.print("You're connected to the network"); + printCurrentNet(); + printWiFiData(); +} + +void loop() { + // check the network connection once every 10 seconds: + delay(10000); + printCurrentNet(); +} + +void printWiFiData() { + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + Serial.println(ip); + + // print your MAC address: + byte mac[6]; + WiFi.macAddress(mac); + Serial.print("MAC address: "); + Serial.print(mac[5], HEX); + Serial.print(":"); + Serial.print(mac[4], HEX); + Serial.print(":"); + Serial.print(mac[3], HEX); + Serial.print(":"); + Serial.print(mac[2], HEX); + Serial.print(":"); + Serial.print(mac[1], HEX); + Serial.print(":"); + Serial.println(mac[0], HEX); + + // print your subnet mask: + IPAddress subnet = WiFi.subnetMask(); + Serial.print("NetMask: "); + Serial.println(subnet); + + // print your gateway address: + IPAddress gateway = WiFi.gatewayIP(); + Serial.print("Gateway: "); + Serial.println(gateway); +} + +void printCurrentNet() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print the MAC address of the router you're attached to: + byte bssid[6]; + WiFi.BSSID(bssid); + Serial.print("BSSID: "); + Serial.print(bssid[5], HEX); + Serial.print(":"); + Serial.print(bssid[4], HEX); + Serial.print(":"); + Serial.print(bssid[3], HEX); + Serial.print(":"); + Serial.print(bssid[2], HEX); + Serial.print(":"); + Serial.print(bssid[1], HEX); + Serial.print(":"); + Serial.println(bssid[0], HEX); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.println(rssi); + + // print the encryption type: + byte encryption = WiFi.encryptionType(); + Serial.print("Encryption Type:"); + Serial.println(encryption, HEX); +} + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h new file mode 100644 index 0000000..07c1148 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h @@ -0,0 +1 @@ +#define SECRET_SSID "" diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino new file mode 100644 index 0000000..c226fa7 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino @@ -0,0 +1,129 @@ +/* + + This example connects to a WEP-encrypted WiFi network. + Then it prints the MAC address of the WiFi shield, + the IP address obtained, and other network details. + + If you use 40-bit WEP, you need a key that is 10 characters long, + and the characters must be hexadecimal (0-9 or A-F). + e.g. for 40-bit, ABBADEAF01 will work, but ABBADEAF won't work + (too short) and ABBAISDEAF won't work (I and S are not + hexadecimal characters). + + For 128-bit, you need a string that is 26 characters long. + D0D0DEADF00DABBADEAFBEADED will work because it's 26 characters, + all in the 0-9, A-F range. + + Circuit: + * WiFi shield attached + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + */ +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char key[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number +int status = WL_IDLE_STATUS; // the WiFi radio's status + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to WEP network, SSID: "); + Serial.println(ssid); + status = WiFi.begin(ssid, keyIndex, key); + + // wait 10 seconds for connection: + delay(10000); + } + + // once you are connected : + Serial.print("You're connected to the network"); + printCurrentNet(); + printWiFiData(); +} + +void loop() { + // check the network connection once every 10 seconds: + delay(10000); + printCurrentNet(); +} + +void printWiFiData() { + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + Serial.println(ip); + + // print your MAC address: + byte mac[6]; + WiFi.macAddress(mac); + Serial.print("MAC address: "); + Serial.print(mac[5], HEX); + Serial.print(":"); + Serial.print(mac[4], HEX); + Serial.print(":"); + Serial.print(mac[3], HEX); + Serial.print(":"); + Serial.print(mac[2], HEX); + Serial.print(":"); + Serial.print(mac[1], HEX); + Serial.print(":"); + Serial.println(mac[0], HEX); +} + +void printCurrentNet() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print the MAC address of the router you're attached to: + byte bssid[6]; + WiFi.BSSID(bssid); + Serial.print("BSSID: "); + Serial.print(bssid[5], HEX); + Serial.print(":"); + Serial.print(bssid[4], HEX); + Serial.print(":"); + Serial.print(bssid[3], HEX); + Serial.print(":"); + Serial.print(bssid[2], HEX); + Serial.print(":"); + Serial.print(bssid[1], HEX); + Serial.print(":"); + Serial.println(bssid[0], HEX); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.println(rssi); + + // print the encryption type: + byte encryption = WiFi.encryptionType(); + Serial.print("Encryption Type:"); + Serial.println(encryption, HEX); + Serial.println(); +} + + + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino new file mode 100644 index 0000000..b98af65 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino @@ -0,0 +1,119 @@ +/* + + This example connects to an unencrypted WiFi network. + Then it prints the MAC address of the WiFi shield, + the IP address obtained, and other network details. + + Circuit: + * WiFi shield attached + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + */ +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int status = WL_IDLE_STATUS; // the WiFi radio's status + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to WPA SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + + // you're connected now, so print out the data: + Serial.print("You're connected to the network"); + printCurrentNet(); + printWiFiData(); + +} + +void loop() { + // check the network connection once every 10 seconds: + delay(10000); + printCurrentNet(); +} + +void printWiFiData() { + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + Serial.println(ip); + + // print your MAC address: + byte mac[6]; + WiFi.macAddress(mac); + Serial.print("MAC address: "); + Serial.print(mac[5], HEX); + Serial.print(":"); + Serial.print(mac[4], HEX); + Serial.print(":"); + Serial.print(mac[3], HEX); + Serial.print(":"); + Serial.print(mac[2], HEX); + Serial.print(":"); + Serial.print(mac[1], HEX); + Serial.print(":"); + Serial.println(mac[0], HEX); + +} + +void printCurrentNet() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print the MAC address of the router you're attached to: + byte bssid[6]; + WiFi.BSSID(bssid); + Serial.print("BSSID: "); + Serial.print(bssid[5], HEX); + Serial.print(":"); + Serial.print(bssid[4], HEX); + Serial.print(":"); + Serial.print(bssid[3], HEX); + Serial.print(":"); + Serial.print(bssid[2], HEX); + Serial.print(":"); + Serial.print(bssid[1], HEX); + Serial.print(":"); + Serial.println(bssid[0], HEX); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.println(rssi); + + // print the encryption type: + byte encryption = WiFi.encryptionType(); + Serial.print("Encryption Type:"); + Serial.println(encryption, HEX); + Serial.println(); +} + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino new file mode 100644 index 0000000..897c770 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino @@ -0,0 +1,62 @@ +/* + Endianess.ino - Network byte order conversion functions. + Copyright (c) 2015 Arduino LLC. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + + +bool isBigEndian() { + uint32_t test = 0x11223344; + uint8_t *pTest = reinterpret_cast(&test); + return pTest[0] == 0x11; +} + +uint32_t fromNetwork32(uint32_t from) { + static const bool be = isBigEndian(); + if (be) { + return from; + } else { + uint8_t *pFrom = reinterpret_cast(&from); + uint32_t to; + to = pFrom[0]; to <<= 8; + to |= pFrom[1]; to <<= 8; + to |= pFrom[2]; to <<= 8; + to |= pFrom[3]; + return to; + } +} + +uint16_t fromNetwork16(uint16_t from) { + static bool be = isBigEndian(); + if (be) { + return from; + } else { + uint8_t *pFrom = reinterpret_cast(&from); + uint16_t to; + to = pFrom[0]; to <<= 8; + to |= pFrom[1]; + return to; + } +} + +uint32_t toNetwork32(uint32_t to) { + return fromNetwork32(to); +} + +uint16_t toNetwork16(uint16_t to) { + return fromNetwork16(to); +} + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino new file mode 100644 index 0000000..1bbd6b9 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino @@ -0,0 +1,129 @@ +/* + FirmwareUpdate.h - Firmware Updater for WiFi101 / WINC1500. + Copyright (c) 2015 Arduino LLC. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include +#include + +typedef struct __attribute__((__packed__)) { + uint8_t command; + uint32_t address; + uint32_t arg1; + uint16_t payloadLength; + + // payloadLenght bytes of data follows... +} UartPacket; + +static const int MAX_PAYLOAD_SIZE = 1024; + +#define CMD_READ_FLASH 0x01 +#define CMD_WRITE_FLASH 0x02 +#define CMD_ERASE_FLASH 0x03 +#define CMD_MAX_PAYLOAD_SIZE 0x50 +#define CMD_HELLO 0x99 + +void setup() { + Serial.begin(115200); + + nm_bsp_init(); + if (m2m_wifi_download_mode() != M2M_SUCCESS) { + Serial.println(F("Failed to put the WiFi module in download mode")); + while (true) + ; + } +} + +void receivePacket(UartPacket *pkt, uint8_t *payload) { + // Read command + uint8_t *p = reinterpret_cast(pkt); + uint16_t l = sizeof(UartPacket); + while (l > 0) { + int c = Serial.read(); + if (c == -1) + continue; + *p++ = c; + l--; + } + + // Convert parameters from network byte order to cpu byte order + pkt->address = fromNetwork32(pkt->address); + pkt->arg1 = fromNetwork32(pkt->arg1); + pkt->payloadLength = fromNetwork16(pkt->payloadLength); + + // Read payload + l = pkt->payloadLength; + while (l > 0) { + int c = Serial.read(); + if (c == -1) + continue; + *payload++ = c; + l--; + } +} + +// Allocated statically so the compiler can tell us +// about the amount of used RAM +static UartPacket pkt; +static uint8_t payload[MAX_PAYLOAD_SIZE]; + +void loop() { + receivePacket(&pkt, payload); + + if (pkt.command == CMD_HELLO) { + if (pkt.address == 0x11223344 && pkt.arg1 == 0x55667788) + Serial.print("v10000"); + } + + if (pkt.command == CMD_MAX_PAYLOAD_SIZE) { + uint16_t res = toNetwork16(MAX_PAYLOAD_SIZE); + Serial.write(reinterpret_cast(&res), sizeof(res)); + } + + if (pkt.command == CMD_READ_FLASH) { + uint32_t address = pkt.address; + uint32_t len = pkt.arg1; + if (spi_flash_read(payload, address, len) != M2M_SUCCESS) { + Serial.println("ER"); + } else { + Serial.write(payload, len); + Serial.print("OK"); + } + } + + if (pkt.command == CMD_WRITE_FLASH) { + uint32_t address = pkt.address; + uint32_t len = pkt.payloadLength; + if (spi_flash_write(payload, address, len) != M2M_SUCCESS) { + Serial.print("ER"); + } else { + Serial.print("OK"); + } + } + + if (pkt.command == CMD_ERASE_FLASH) { + uint32_t address = pkt.address; + uint32_t len = pkt.arg1; + if (spi_flash_erase(address, len) != M2M_SUCCESS) { + Serial.print("ER"); + } else { + Serial.print("OK"); + } + } +} + + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino new file mode 100644 index 0000000..f62ac62 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino @@ -0,0 +1,170 @@ +/* + MDNS WiFi Web Server + + A simple web server that shows the value of the analog input pins, + and exposes itself on the MDNS name 'wifi101.local'. + + On Linux (like Ubuntu 15.04) or OSX you can access the web page + on the device in a browser at 'http://wifi101.local/'. + + On Windows you'll first need to install the Bonjour Printer Services + from: + https://support.apple.com/kb/dl999?locale=en_US + Then you can access the device in a browser at 'http://wifi101.local/'. + + This example is written for a network using WPA encryption. For + WEP or WPA, change the WiFi.begin() call accordingly. + + Circuit: + * WiFi shield attached + * Analog inputs attached to pins A0 through A5 (optional) + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + modified 27 January 2016 + by Tony DiCola + +*/ + +#include +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +char mdnsName[] = "wifi101"; // the MDNS name that the board will respond to +// Note that the actual MDNS name will have '.local' after +// the name above, so "wifi101" will be accessible on +// the MDNS name "wifi101.local". + +int status = WL_IDLE_STATUS; + +// Create a MDNS responder to listen and respond to MDNS name requests. +WiFiMDNSResponder mdnsResponder; + +WiFiServer server(80); + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + // you're connected now, so print out the status: + printWiFiStatus(); + + server.begin(); + + // Setup the MDNS responder to listen to the configured name. + // NOTE: You _must_ call this _after_ connecting to the WiFi network and + // being assigned an IP address. + if (!mdnsResponder.begin(mdnsName)) { + Serial.println("Failed to start MDNS responder!"); + while(1); + } + + Serial.print("Server listening at http://"); + Serial.print(mdnsName); + Serial.println(".local/"); +} + + +void loop() { + // Call the update() function on the MDNS responder every loop iteration to + // make sure it can detect and respond to name requests. + mdnsResponder.poll(); + + // listen for incoming clients + WiFiClient client = server.available(); + if (client) { + Serial.println("new client"); + // an http request ends with a blank line + boolean currentLineIsBlank = true; + while (client.connected()) { + if (client.available()) { + char c = client.read(); + Serial.write(c); + // if you've gotten to the end of the line (received a newline + // character) and the line is blank, the http request has ended, + // so you can send a reply + if (c == '\n' && currentLineIsBlank) { + // send a standard http response header + client.println("HTTP/1.1 200 OK"); + client.println("Content-Type: text/html"); + client.println("Connection: close"); // the connection will be closed after completion of the response + client.println("Refresh: 5"); // refresh the page automatically every 5 sec + client.println(); + client.println(""); + client.println(""); + // output the value of each analog input pin + for (int analogChannel = 0; analogChannel < 6; analogChannel++) { + int sensorReading = analogRead(analogChannel); + client.print("analog input "); + client.print(analogChannel); + client.print(" is "); + client.print(sensorReading); + client.println("
"); + } + client.println(""); + break; + } + if (c == '\n') { + // you're starting a new line + currentLineIsBlank = true; + } + else if (c != '\r') { + // you've gotten a character on the current line + currentLineIsBlank = false; + } + } + } + // give the web browser time to receive the data + delay(1); + + // close the connection: + client.stop(); + Serial.println("client disconnected"); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino new file mode 100644 index 0000000..0297707 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino @@ -0,0 +1,167 @@ +/* + WiFi Web Server + + A simple web server that shows the value of the analog input pins. + using a WiFi shield. + + This example is written to configure the WiFi settings using provisioning mode. + It also sets up an mDNS server so the IP address of the board doesn't have to + be obtained via the serial monitor. + + Circuit: + WiFi shield attached + Analog inputs attached to pins A0 through A5 (optional) + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + +*/ + +#include +#include +#include + +const int ledPin = 6; // LED pin for connectivity status indicator + +char mdnsName[] = "wifi101"; // the MDNS name that the board will respond to + // after WiFi settings have been provisioned +// Note that the actual MDNS name will have '.local' after +// the name above, so "wifi101" will be accessible on +// the MDNS name "wifi101.local". + +WiFiServer server(80); + +// Create a MDNS responder to listen and respond to MDNS name requests. +WiFiMDNSResponder mdnsResponder; + +void setup() { + //Initialize serial: + Serial.begin(9600); + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // configure the LED pin for output mode + pinMode(ledPin, OUTPUT); + + // Start in provisioning mode: + // 1) This will try to connect to a previously associated access point. + // 2) If this fails, an access point named "wifi101-XXXX" will be created, where XXXX + // is the last 4 digits of the boards MAC address. Once you are connected to the access point, + // you can configure an SSID and password by visiting http://wifi101/ + WiFi.beginProvision(); + + while (WiFi.status() != WL_CONNECTED) { + // wait while not connected + + // blink the led to show an unconnected status + digitalWrite(ledPin, HIGH); + delay(500); + digitalWrite(ledPin, LOW); + delay(500); + } + + // connected, make the LED stay on + digitalWrite(ledPin, HIGH); + + server.begin(); + + // Setup the MDNS responder to listen to the configured name. + // NOTE: You _must_ call this _after_ connecting to the WiFi network and + // being assigned an IP address. + if (!mdnsResponder.begin(mdnsName)) { + Serial.println("Failed to start MDNS responder!"); + while(1); + } + + Serial.print("Server listening at http://"); + Serial.print(mdnsName); + Serial.println(".local/"); + + // you're connected now, so print out the status: + printWiFiStatus(); +} + + +void loop() { + // Call the update() function on the MDNS responder every loop iteration to + // make sure it can detect and respond to name requests. + mdnsResponder.poll(); + + // listen for incoming clients + WiFiClient client = server.available(); + if (client) { + Serial.println("new client"); + // an http request ends with a blank line + boolean currentLineIsBlank = true; + while (client.connected()) { + if (client.available()) { + char c = client.read(); + Serial.write(c); + // if you've gotten to the end of the line (received a newline + // character) and the line is blank, the http request has ended, + // so you can send a reply + if (c == '\n' && currentLineIsBlank) { + // send a standard http response header + client.println("HTTP/1.1 200 OK"); + client.println("Content-Type: text/html"); + client.println("Connection: close"); // the connection will be closed after completion of the response + client.println("Refresh: 5"); // refresh the page automatically every 5 sec + client.println(); + client.println(""); + client.println(""); + // output the value of each analog input pin + for (int analogChannel = 0; analogChannel < 6; analogChannel++) { + int sensorReading = analogRead(analogChannel); + client.print("analog input "); + client.print(analogChannel); + client.print(" is "); + client.print(sensorReading); + client.println("
"); + } + client.println(""); + break; + } + if (c == '\n') { + // you're starting a new line + currentLineIsBlank = true; + } + else if (c != '\r') { + // you've gotten a character on the current line + currentLineIsBlank = false; + } + } + } + // give the web browser time to receive the data + delay(1); + + // close the connection: + client.stop(); + Serial.println("client disonnected"); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino new file mode 100644 index 0000000..45b908e --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino @@ -0,0 +1,120 @@ +/* + + This example prints the WiFi shield's MAC address, and + scans for available WiFi networks using the WiFi shield. + Every ten seconds, it scans again. It doesn't actually + connect to any network, so no encryption scheme is specified. + + Circuit: + * WiFi shield attached + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 21 Junn 2012 + by Tom Igoe and Jaymes Dec + */ + + +#include +#include + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // Print WiFi MAC address: + printMacAddress(); + + // scan for existing networks: + Serial.println("Scanning available networks..."); + listNetworks(); +} + +void loop() { + delay(10000); + // scan for existing networks: + Serial.println("Scanning available networks..."); + listNetworks(); +} + +void printMacAddress() { + // the MAC address of your WiFi shield + byte mac[6]; + + // print your MAC address: + WiFi.macAddress(mac); + Serial.print("MAC: "); + Serial.print(mac[5], HEX); + Serial.print(":"); + Serial.print(mac[4], HEX); + Serial.print(":"); + Serial.print(mac[3], HEX); + Serial.print(":"); + Serial.print(mac[2], HEX); + Serial.print(":"); + Serial.print(mac[1], HEX); + Serial.print(":"); + Serial.println(mac[0], HEX); +} + +void listNetworks() { + // scan for nearby networks: + Serial.println("** Scan Networks **"); + int numSsid = WiFi.scanNetworks(); + if (numSsid == -1) + { + Serial.println("Couldn't get a wifi connection"); + while (true); + } + + // print the list of networks seen: + Serial.print("number of available networks:"); + Serial.println(numSsid); + + // print the network number and name for each network found: + for (int thisNet = 0; thisNet < numSsid; thisNet++) { + Serial.print(thisNet); + Serial.print(") "); + Serial.print(WiFi.SSID(thisNet)); + Serial.print("\tSignal: "); + Serial.print(WiFi.RSSI(thisNet)); + Serial.print(" dBm"); + Serial.print("\tEncryption: "); + printEncryptionType(WiFi.encryptionType(thisNet)); + Serial.flush(); + } +} + +void printEncryptionType(int thisType) { + // read the encryption type and print out the name: + switch (thisType) { + case ENC_TYPE_WEP: + Serial.println("WEP"); + break; + case ENC_TYPE_TKIP: + Serial.println("WPA"); + break; + case ENC_TYPE_CCMP: + Serial.println("WPA2"); + break; + case ENC_TYPE_NONE: + Serial.println("None"); + break; + case ENC_TYPE_AUTO: + Serial.println("Auto"); + break; + } +} + + + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino new file mode 100644 index 0000000..2afb544 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino @@ -0,0 +1,149 @@ +/* + + This example prints the WiFi 101 shield or MKR1000 MAC address, and + scans for available WiFi networks using the WiFi 101 shield or MKR1000 board. + Every ten seconds, it scans again. It doesn't actually + connect to any network, so no encryption scheme is specified. + BSSID and WiFi channel are printed + + Circuit: + WiFi 101 shield attached or MKR1000 board + + This example is based on ScanNetworks + + created 1 Mar 2017 + by Arturo Guadalupi +*/ + + +#include +#include + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // Print WiFi MAC address: + printMacAddress(); + + // scan for existing networks: + Serial.println(); + Serial.println("Scanning available networks..."); + listNetworks(); +} + +void loop() { + delay(10000); + // scan for existing networks: + Serial.println("Scanning available networks..."); + listNetworks(); +} + +void printMacAddress() { + // the MAC address of your WiFi shield + byte mac[6]; + + // print your MAC address: + WiFi.macAddress(mac); + Serial.print("MAC: "); + print2Digits(mac[5]); + Serial.print(":"); + print2Digits(mac[4]); + Serial.print(":"); + print2Digits(mac[3]); + Serial.print(":"); + print2Digits(mac[2]); + Serial.print(":"); + print2Digits(mac[1]); + Serial.print(":"); + print2Digits(mac[0]); +} + +void listNetworks() { + // scan for nearby networks: + Serial.println("** Scan Networks **"); + int numSsid = WiFi.scanNetworks(); + if (numSsid == -1) + { + Serial.println("Couldn't get a WiFi connection"); + while (true); + } + + // print the list of networks seen: + Serial.print("number of available networks: "); + Serial.println(numSsid); + + // print the network number and name for each network found: + for (int thisNet = 0; thisNet < numSsid; thisNet++) { + Serial.print(thisNet + 1); + Serial.print(") "); + Serial.print("Signal: "); + Serial.print(WiFi.RSSI(thisNet)); + Serial.print(" dBm"); + Serial.print("\tChannel: "); + Serial.print(WiFi.channel(thisNet)); + byte bssid[6]; + Serial.print("\t\tBSSID: "); + printBSSID(WiFi.BSSID(thisNet, bssid)); + Serial.print("\tEncryption: "); + printEncryptionType(WiFi.encryptionType(thisNet)); + Serial.print("\t\tSSID: "); + Serial.println(WiFi.SSID(thisNet)); + Serial.flush(); + } + Serial.println(); +} + +void printBSSID(byte bssid[]) { + print2Digits(bssid[5]); + Serial.print(":"); + print2Digits(bssid[4]); + Serial.print(":"); + print2Digits(bssid[3]); + Serial.print(":"); + print2Digits(bssid[2]); + Serial.print(":"); + print2Digits(bssid[1]); + Serial.print(":"); + print2Digits(bssid[0]); +} + +void printEncryptionType(int thisType) { + // read the encryption type and print out the name: + switch (thisType) { + case ENC_TYPE_WEP: + Serial.print("WEP"); + break; + case ENC_TYPE_TKIP: + Serial.print("WPA"); + break; + case ENC_TYPE_CCMP: + Serial.print("WPA2"); + break; + case ENC_TYPE_NONE: + Serial.print("None"); + break; + case ENC_TYPE_AUTO: + Serial.print("Auto"); + break; + } +} + +void print2Digits(byte thisByte) { + if (thisByte < 0xF) { + Serial.print("0"); + } + Serial.print(thisByte, HEX); +} + + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino new file mode 100644 index 0000000..aeaf0c6 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino @@ -0,0 +1,131 @@ +/* + WiFi Web Server LED Blink + + A simple web server that lets you blink an LED via the web. + This sketch will print the IP address of your WiFi Shield (once connected) + to the Serial monitor. From there, you can open that address in a web browser + to turn on and off the LED on pin 9. + + If the IP address of your shield is yourAddress: + http://yourAddress/H turns the LED on + http://yourAddress/L turns it off + + This example is written for a network using WPA encryption. For + WEP or WPA, change the WiFi.begin() call accordingly. + + Circuit: + * WiFi shield attached + * LED attached to pin 9 + + created 25 Nov 2012 + by Tom Igoe + */ +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int status = WL_IDLE_STATUS; +WiFiServer server(80); + +void setup() { + Serial.begin(9600); // initialize serial communication + pinMode(9, OUTPUT); // set the LED pin mode + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + while (true); // don't continue + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to Network named: "); + Serial.println(ssid); // print the network name (SSID); + + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + // wait 10 seconds for connection: + delay(10000); + } + server.begin(); // start the web server on port 80 + printWiFiStatus(); // you're connected now, so print out the status +} + + +void loop() { + WiFiClient client = server.available(); // listen for incoming clients + + if (client) { // if you get a client, + Serial.println("new client"); // print a message out the serial port + String currentLine = ""; // make a String to hold incoming data from the client + while (client.connected()) { // loop while the client's connected + if (client.available()) { // if there's bytes to read from the client, + char c = client.read(); // read a byte, then + Serial.write(c); // print it out the serial monitor + if (c == '\n') { // if the byte is a newline character + + // if the current line is blank, you got two newline characters in a row. + // that's the end of the client HTTP request, so send a response: + if (currentLine.length() == 0) { + // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) + // and a content-type so the client knows what's coming, then a blank line: + client.println("HTTP/1.1 200 OK"); + client.println("Content-type:text/html"); + client.println(); + + // the content of the HTTP response follows the header: + client.print("Click here turn the LED on pin 9 on
"); + client.print("Click here turn the LED on pin 9 off
"); + + // The HTTP response ends with another blank line: + client.println(); + // break out of the while loop: + break; + } + else { // if you got a newline, then clear currentLine: + currentLine = ""; + } + } + else if (c != '\r') { // if you got anything else but a carriage return character, + currentLine += c; // add it to the end of the currentLine + } + + // Check to see if the client request was "GET /H" or "GET /L": + if (currentLine.endsWith("GET /H")) { + digitalWrite(9, HIGH); // GET /H turns the LED on + } + if (currentLine.endsWith("GET /L")) { + digitalWrite(9, LOW); // GET /L turns the LED off + } + } + } + // close the connection: + client.stop(); + Serial.println("client disonnected"); + } +} + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); + // print where to go in a browser: + Serial.print("To see this page in action, open a browser to http://"); + Serial.println(ip); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino new file mode 100644 index 0000000..ac7bd76 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino @@ -0,0 +1,114 @@ +/* + Chat Server + + A simple server that distributes any incoming messages to all + connected clients. To use telnet to your device's IP address and type. + You can see the client's input in the serial monitor as well. + + This example is written for a network using WPA encryption. For + WEP or WPA, change the WiFi.begin() call accordingly. + + + Circuit: + * WiFi shield attached + + created 18 Dec 2009 + by David A. Mellis + modified 31 May 2012 + by Tom Igoe + + */ + +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) + +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int status = WL_IDLE_STATUS; + +WiFiServer server(23); + +boolean alreadyConnected = false; // whether or not the client was connected previously + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + + // start the server: + server.begin(); + // you're connected now, so print out the status: + printWiFiStatus(); +} + + +void loop() { + // wait for a new client: + WiFiClient client = server.available(); + + + // when the client sends the first byte, say hello: + if (client) { + if (!alreadyConnected) { + // clead out the input buffer: + client.flush(); + Serial.println("We have a new client"); + client.println("Hello, client!"); + alreadyConnected = true; + } + + if (client.available() > 0) { + // read the bytes incoming from the client: + char thisChar = client.read(); + // echo the bytes back to the client: + server.write(thisChar); + // echo the bytes to the server as well: + Serial.write(thisChar); + } + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} + + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino new file mode 100644 index 0000000..9a51c19 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino @@ -0,0 +1,140 @@ +/* + + This example connects to a encrypted WiFi network (WPA/WPA2). + Then it prints the MAC address of the WiFi shield, + the IP address obtained, and other network details. + Then it continuously pings given host specified by IP Address or name. + + Circuit: + WiFi shield attached / MKR1000 + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 09 June 2016 + by Petar Georgiev +*/ +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int status = WL_IDLE_STATUS; // the WiFi radio's status + +// Specify IP address or hostname +String hostName = "www.google.com"; +int pingResult; + +void setup() { + // Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to WPA SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network: + status = WiFi.begin(ssid, pass); + + // wait 5 seconds for connection: + delay(5000); + } + + // you're connected now, so print out the data: + Serial.println("You're connected to the network"); + printCurrentNet(); + printWiFiData(); +} + +void loop() { + Serial.print("Pinging "); + Serial.print(hostName); + Serial.print(": "); + + pingResult = WiFi.ping(hostName); + + if (pingResult >= 0) { + Serial.print("SUCCESS! RTT = "); + Serial.print(pingResult); + Serial.println(" ms"); + } else { + Serial.print("FAILED! Error code: "); + Serial.println(pingResult); + } + + delay(5000); +} + +void printWiFiData() { + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP address : "); + Serial.println(ip); + + Serial.print("Subnet mask: "); + Serial.println((IPAddress)WiFi.subnetMask()); + + Serial.print("Gateway IP : "); + Serial.println((IPAddress)WiFi.gatewayIP()); + + // print your MAC address: + byte mac[6]; + WiFi.macAddress(mac); + Serial.print("MAC address: "); + Serial.print(mac[5], HEX); + Serial.print(":"); + Serial.print(mac[4], HEX); + Serial.print(":"); + Serial.print(mac[3], HEX); + Serial.print(":"); + Serial.print(mac[2], HEX); + Serial.print(":"); + Serial.print(mac[1], HEX); + Serial.print(":"); + Serial.println(mac[0], HEX); + Serial.println(); +} + +void printCurrentNet() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print the MAC address of the router you're attached to: + byte bssid[6]; + WiFi.BSSID(bssid); + Serial.print("BSSID: "); + Serial.print(bssid[5], HEX); + Serial.print(":"); + Serial.print(bssid[4], HEX); + Serial.print(":"); + Serial.print(bssid[3], HEX); + Serial.print(":"); + Serial.print(bssid[2], HEX); + Serial.print(":"); + Serial.print(bssid[1], HEX); + Serial.print(":"); + Serial.println(bssid[0], HEX); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI): "); + Serial.println(rssi); + + // print the encryption type: + byte encryption = WiFi.encryptionType(); + Serial.print("Encryption Type: "); + Serial.println(encryption, HEX); + Serial.println(); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino new file mode 100644 index 0000000..a436902 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino @@ -0,0 +1,107 @@ +/* +This example creates a client object that connects and transfers +data using always SSL. + +It is compatible with the methods normally related to plain +connections, like client.connect(host, port). + +Written by Arturo Guadalupi +last revision November 2015 + +*/ + +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int status = WL_IDLE_STATUS; +// if you don't want to use DNS (and reduce your sketch size) +// use the numeric IP instead of the name for the server: +//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) +char server[] = "www.google.com"; // name address for Google (using DNS) + +// Initialize the Ethernet client library +// with the IP address and port of the server +// that you want to connect to (port 80 is default for HTTP): +WiFiSSLClient client; + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while (status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + Serial.println("Connected to wifi"); + printWiFiStatus(); + + Serial.println("\nStarting connection to server..."); + // if you get a connection, report back via serial: + if (client.connect(server, 443)) { + Serial.println("connected to server"); + // Make a HTTP request: + client.println("GET /search?q=arduino HTTP/1.1"); + client.println("Host: www.google.com"); + client.println("Connection: close"); + client.println(); + } +} + +void loop() { + // if there are incoming bytes available + // from the server, read them and print them: + while (client.available()) { + char c = client.read(); + Serial.write(c); + } + + // if the server's disconnected, stop the client: + if (!client.connected()) { + Serial.println(); + Serial.println("disconnecting from server."); + client.stop(); + + // do nothing forevermore: + while (true); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino new file mode 100644 index 0000000..e82fbaa --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino @@ -0,0 +1,182 @@ +/* + + Udp NTP Client + + Get the time from a Network Time Protocol (NTP) time server + Demonstrates use of UDP sendPacket and ReceivePacket + For more on NTP time servers and the messages needed to communicate with them, + see http://en.wikipedia.org/wiki/Network_Time_Protocol + + created 4 Sep 2010 + by Michael Margolis + modified 9 Apr 2012 + by Tom Igoe + + This code is in the public domain. + + */ + +#include +#include +#include + +int status = WL_IDLE_STATUS; +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +unsigned int localPort = 2390; // local port to listen for UDP packets + +IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server + +const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message + +byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets + +// A UDP instance to let us send and receive packets over UDP +WiFiUDP Udp; + +void setup() +{ + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + + Serial.println("Connected to wifi"); + printWiFiStatus(); + + Serial.println("\nStarting connection to server..."); + Udp.begin(localPort); +} + +void loop() +{ + sendNTPpacket(timeServer); // send an NTP packet to a time server + // wait to see if a reply is available + delay(1000); + if ( Udp.parsePacket() ) { + Serial.println("packet received"); + // We've received a packet, read the data from it + Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer + + //the timestamp starts at byte 40 of the received packet and is four bytes, + // or two words, long. First, esxtract the two words: + + unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); + unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); + // combine the four bytes (two words) into a long integer + // this is NTP time (seconds since Jan 1 1900): + unsigned long secsSince1900 = highWord << 16 | lowWord; + Serial.print("Seconds since Jan 1 1900 = " ); + Serial.println(secsSince1900); + + // now convert NTP time into everyday time: + Serial.print("Unix time = "); + // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: + const unsigned long seventyYears = 2208988800UL; + // subtract seventy years: + unsigned long epoch = secsSince1900 - seventyYears; + // print Unix time: + Serial.println(epoch); + + + // print the hour, minute and second: + Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) + Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) + Serial.print(':'); + if ( ((epoch % 3600) / 60) < 10 ) { + // In the first 10 minutes of each hour, we'll want a leading '0' + Serial.print('0'); + } + Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) + Serial.print(':'); + if ( (epoch % 60) < 10 ) { + // In the first 10 seconds of each minute, we'll want a leading '0' + Serial.print('0'); + } + Serial.println(epoch % 60); // print the second + } + // wait ten seconds before asking for the time again + delay(10000); +} + +// send an NTP request to the time server at the given address +unsigned long sendNTPpacket(IPAddress& address) +{ + //Serial.println("1"); + // set all bytes in the buffer to 0 + memset(packetBuffer, 0, NTP_PACKET_SIZE); + // Initialize values needed to form NTP request + // (see URL above for details on the packets) + //Serial.println("2"); + packetBuffer[0] = 0b11100011; // LI, Version, Mode + packetBuffer[1] = 0; // Stratum, or type of clock + packetBuffer[2] = 6; // Polling Interval + packetBuffer[3] = 0xEC; // Peer Clock Precision + // 8 bytes of zero for Root Delay & Root Dispersion + packetBuffer[12] = 49; + packetBuffer[13] = 0x4E; + packetBuffer[14] = 49; + packetBuffer[15] = 52; + + //Serial.println("3"); + + // all NTP fields have been given values, now + // you can send a packet requesting a timestamp: + Udp.beginPacket(address, 123); //NTP requests are to port 123 + //Serial.println("4"); + Udp.write(packetBuffer, NTP_PACKET_SIZE); + //Serial.println("5"); + Udp.endPacket(); + //Serial.println("6"); +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} + + + + + + + + + + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino new file mode 100644 index 0000000..cbc9f7f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino @@ -0,0 +1,113 @@ +/* + WiFi UDP Send and Receive String + + This sketch wait an UDP packet on localPort using a WiFi shield. + When a packet is received an Acknowledge packet is sent to the client on port remotePort + + Circuit: + * WiFi shield attached + + created 30 December 2012 + by dlf (Metodo2 srl) + + */ + + +#include +#include +#include + +int status = WL_IDLE_STATUS; +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +unsigned int localPort = 2390; // local port to listen on + +char packetBuffer[255]; //buffer to hold incoming packet +char ReplyBuffer[] = "acknowledged"; // a string to send back + +WiFiUDP Udp; + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + Serial.println("Connected to wifi"); + printWiFiStatus(); + + Serial.println("\nStarting connection to server..."); + // if you get a connection, report back via serial: + Udp.begin(localPort); +} + +void loop() { + + // if there's data available, read a packet + int packetSize = Udp.parsePacket(); + if (packetSize) + { + Serial.print("Received packet of size "); + Serial.println(packetSize); + Serial.print("From "); + IPAddress remoteIp = Udp.remoteIP(); + Serial.print(remoteIp); + Serial.print(", port "); + Serial.println(Udp.remotePort()); + + // read the packet into packetBufffer + int len = Udp.read(packetBuffer, 255); + if (len > 0) packetBuffer[len] = 0; + Serial.println("Contents:"); + Serial.println(packetBuffer); + + // send a reply, to the IP address and port that sent us the packet we received + Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); + Udp.write(ReplyBuffer); + Udp.endPacket(); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} + + + + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino new file mode 100644 index 0000000..5faa779 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino @@ -0,0 +1,121 @@ +/* + Web client + + This sketch connects to a website (http://www.google.com) + using a WiFi shield. + + This example is written for a network using WPA encryption. For + WEP or WPA, change the WiFi.begin() call accordingly. + + This example is written for a network using WPA encryption. For + WEP or WPA, change the WiFi.begin() call accordingly. + + Circuit: + * WiFi shield attached + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + */ + + +#include +#include +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int status = WL_IDLE_STATUS; +// if you don't want to use DNS (and reduce your sketch size) +// use the numeric IP instead of the name for the server: +//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) +char server[] = "www.google.com"; // name address for Google (using DNS) + +// Initialize the Ethernet client library +// with the IP address and port of the server +// that you want to connect to (port 80 is default for HTTP): +WiFiClient client; + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while (status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + Serial.println("Connected to wifi"); + printWiFiStatus(); + + Serial.println("\nStarting connection to server..."); + // if you get a connection, report back via serial: + if (client.connect(server, 80)) { + Serial.println("connected to server"); + // Make a HTTP request: + client.println("GET /search?q=arduino HTTP/1.1"); + client.println("Host: www.google.com"); + client.println("Connection: close"); + client.println(); + } +} + +void loop() { + // if there are incoming bytes available + // from the server, read them and print them: + while (client.available()) { + char c = client.read(); + Serial.write(c); + } + + // if the server's disconnected, stop the client: + if (!client.connected()) { + Serial.println(); + Serial.println("disconnecting from server."); + client.stop(); + + // do nothing forevermore: + while (true); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} + + + + + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino new file mode 100644 index 0000000..ac8b4e5 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino @@ -0,0 +1,127 @@ +/* + Repeating WiFi Web Client + + This sketch connects to a a web server and makes a request + using an Arduino WiFi shield. + + Circuit: + * WiFi shield attached to pins SPI pins and pin 7 + + created 23 April 2012 + modified 31 May 2012 + by Tom Igoe + modified 13 Jan 2014 + by Federico Vanzati + + http://arduino.cc/en/Tutorial/WiFiWebClientRepeating + This code is in the public domain. + */ + +#include +#include + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int status = WL_IDLE_STATUS; + +// Initialize the WiFi client library +WiFiClient client; + +// server address: +char server[] = "www.arduino.cc"; +//IPAddress server(64,131,82,241); + +unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds +const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + // you're connected now, so print out the status: + printWiFiStatus(); +} + +void loop() { + // if there's incoming data from the net connection. + // send it out the serial port. This is for debugging + // purposes only: + while (client.available()) { + char c = client.read(); + Serial.write(c); + } + + // if ten seconds have passed since your last connection, + // then connect again and send data: + if (millis() - lastConnectionTime > postingInterval) { + httpRequest(); + } + +} + +// this method makes a HTTP connection to the server: +void httpRequest() { + // close any connection before send a new request. + // This will free the socket on the WiFi shield + client.stop(); + + // if there's a successful connection: + if (client.connect(server, 80)) { + Serial.println("connecting..."); + // send the HTTP PUT request: + client.println("GET /latest.txt HTTP/1.1"); + client.println("Host: www.arduino.cc"); + client.println("User-Agent: ArduinoWiFi/1.1"); + client.println("Connection: close"); + client.println(); + + // note the time that the connection was made: + lastConnectionTime = millis(); + } + else { + // if you couldn't make a connection: + Serial.println("connection failed"); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino new file mode 100644 index 0000000..24d0083 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino @@ -0,0 +1,135 @@ +/* + WiFi Web Server + + A simple web server that shows the value of the analog input pins. + using a WiFi shield. + + This example is written for a network using WPA encryption. For + WEP or WPA, change the WiFi.begin() call accordingly. + + Circuit: + * WiFi shield attached + * Analog inputs attached to pins A0 through A5 (optional) + + created 13 July 2010 + by dlf (Metodo2 srl) + modified 31 May 2012 + by Tom Igoe + + */ + +#include +#include + + +#include "arduino_secrets.h" +///////please enter your sensitive data in the Secret tab/arduino_secrets.h +char ssid[] = SECRET_SSID; // your network SSID (name) +char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) +int keyIndex = 0; // your network key Index number (needed only for WEP) + +int status = WL_IDLE_STATUS; + +WiFiServer server(80); + +void setup() { + //Initialize serial and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to WiFi network: + while (status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(ssid, pass); + + // wait 10 seconds for connection: + delay(10000); + } + server.begin(); + // you're connected now, so print out the status: + printWiFiStatus(); +} + + +void loop() { + // listen for incoming clients + WiFiClient client = server.available(); + if (client) { + Serial.println("new client"); + // an http request ends with a blank line + boolean currentLineIsBlank = true; + while (client.connected()) { + if (client.available()) { + char c = client.read(); + Serial.write(c); + // if you've gotten to the end of the line (received a newline + // character) and the line is blank, the http request has ended, + // so you can send a reply + if (c == '\n' && currentLineIsBlank) { + // send a standard http response header + client.println("HTTP/1.1 200 OK"); + client.println("Content-Type: text/html"); + client.println("Connection: close"); // the connection will be closed after completion of the response + client.println("Refresh: 5"); // refresh the page automatically every 5 sec + client.println(); + client.println(""); + client.println(""); + // output the value of each analog input pin + for (int analogChannel = 0; analogChannel < 6; analogChannel++) { + int sensorReading = analogRead(analogChannel); + client.print("analog input "); + client.print(analogChannel); + client.print(" is "); + client.print(sensorReading); + client.println("
"); + } + client.println(""); + break; + } + if (c == '\n') { + // you're starting a new line + currentLineIsBlank = true; + } + else if (c != '\r') { + // you've gotten a character on the current line + currentLineIsBlank = false; + } + } + } + // give the web browser time to receive the data + delay(1); + + // close the connection: + client.stop(); + Serial.println("client disconnected"); + } +} + + +void printWiFiStatus() { + // print the SSID of the network you're attached to: + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print your WiFi shield's IP address: + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h new file mode 100644 index 0000000..a8ff904 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h @@ -0,0 +1,3 @@ +#define SECRET_SSID "" +#define SECRET_PASS "" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/keywords.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/keywords.txt new file mode 100644 index 0000000..498954d --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/keywords.txt @@ -0,0 +1,61 @@ +####################################### +# Syntax Coloring Map For WiFi +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +WiFi KEYWORD1 +WiFi101 KEYWORD1 +Client KEYWORD1 +Server KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +setPins KEYWORD2 +status KEYWORD2 +connect KEYWORD2 +connectSSL KEYWORD2 +write KEYWORD2 +available KEYWORD2 +read KEYWORD2 +flush KEYWORD2 +stop KEYWORD2 +connected KEYWORD2 +begin KEYWORD2 +beginProvision KEYWORD2 +beginOrProvision KEYWORD2 +beginMulticast KEYWORD2 +disconnect KEYWORD2 +macAddress KEYWORD2 +localIP KEYWORD2 +subnetMask KEYWORD2 +gatewayIP KEYWORD2 +SSID KEYWORD2 +BSSID KEYWORD2 +APClientMacAddress KEYWORD2 +RSSI KEYWORD2 +encryptionType KEYWORD2 +channel KEYWORD2 +provisioned KEYWORD2 +getResult KEYWORD2 +getSocket KEYWORD2 +poll KEYWORD2 +getTime KEYWORD2 +hostname KEYWORD2 +WiFiClient KEYWORD2 +WiFiServer KEYWORD2 +WiFiSSLClient KEYWORD2 +WiFiMDNSResponder KEYWORD2 + +lowPowerMode KEYWORD2 +maxLowPowerMode KEYWORD2 +noLowPowerMode KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/library.properties b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/library.properties new file mode 100644 index 0000000..f6d0b6d --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/library.properties @@ -0,0 +1,10 @@ +name=WiFi101 +version=0.14.4 +author=Arduino +maintainer=Arduino +sentence=Network driver for ATMEL WINC1500 module (used on Arduino/Genuino Wifi Shield 101 and MKR1000 boards) +paragraph=This library implements a network driver for devices based on the ATMEL WINC1500 wifi module +category=Communication +url=http://www.arduino.cc/en/Reference/WiFi101 +architectures=* +includes=WiFi101.h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFi.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFi.cpp new file mode 100644 index 0000000..0c71ffc --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFi.cpp @@ -0,0 +1,1106 @@ +/* + WiFi.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifdef ARDUINO_ARCH_AVR +#include +#if (__AVR_LIBC_MAJOR__ < 2) +#define WIFI_101_NO_TIME_H +#endif +#endif + +#ifndef WIFI_101_NO_TIME_H +#include +#endif + +#if !defined(_TIME_H_) && !defined(TIME_H) +// another library overrided the time.h header +#define WIFI_101_NO_TIME_H +#endif + +#include "WiFi101.h" + +extern "C" { + #include "bsp/include/nm_bsp.h" + #include "bsp/include/nm_bsp_arduino.h" + #include "socket/include/socket_buffer.h" + #include "socket/include/m2m_socket_host_if.h" + #include "driver/source/nmasic.h" + #include "driver/include/m2m_periph.h" + #include "driver/include/m2m_ssl.h" +} + +static void wifi_cb(uint8_t u8MsgType, void *pvMsg) +{ + switch (u8MsgType) { + case M2M_WIFI_RESP_DEFAULT_CONNECT: + { + tstrM2MDefaultConnResp *pstrDefaultConnResp = (tstrM2MDefaultConnResp *)pvMsg; + if (pstrDefaultConnResp->s8ErrorCode) { + WiFi._status = WL_DISCONNECTED; + } + } + break; + + case M2M_WIFI_RESP_CON_STATE_CHANGED: + { + tstrM2mWifiStateChanged *pstrWifiState = (tstrM2mWifiStateChanged *)pvMsg; + if (pstrWifiState->u8CurrState == M2M_WIFI_CONNECTED) { + //SERIAL_PORT_MONITOR.println("wifi_cb: M2M_WIFI_RESP_CON_STATE_CHANGED: CONNECTED"); + if (WiFi._mode == WL_STA_MODE && !WiFi._dhcp) { + WiFi._status = WL_CONNECTED; + + // WiFi led ON. + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); + } else if (WiFi._mode == WL_AP_MODE) { + WiFi._status = WL_AP_CONNECTED; + } + } else if (pstrWifiState->u8CurrState == M2M_WIFI_DISCONNECTED) { + //SERIAL_PORT_MONITOR.println("wifi_cb: M2M_WIFI_RESP_CON_STATE_CHANGED: DISCONNECTED"); + if (WiFi._mode == WL_STA_MODE) { + WiFi._status = WL_DISCONNECTED; + if (WiFi._dhcp) { + WiFi._localip = 0; + WiFi._submask = 0; + WiFi._gateway = 0; + } + // Close sockets to clean state + // Clients will need to reconnect once the physical link will be re-established + for (int i=0; i < TCP_SOCK_MAX; i++) { + if (WiFi._client[i]) + WiFi._client[i]->stop(); + } + } else if (WiFi._mode == WL_AP_MODE) { + WiFi._status = WL_AP_LISTENING; + } + // WiFi led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); + } + } + break; + + case M2M_WIFI_REQ_DHCP_CONF: + { + if (WiFi._mode == WL_STA_MODE) { + tstrM2MIPConfig *pstrIPCfg = (tstrM2MIPConfig *)pvMsg; + WiFi._localip = pstrIPCfg->u32StaticIP; + WiFi._submask = pstrIPCfg->u32SubnetMask; + WiFi._gateway = pstrIPCfg->u32Gateway; + + WiFi._status = WL_CONNECTED; + + // WiFi led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0); + } + /*uint8_t *pu8IPAddress = (uint8_t *)pvMsg; + SERIAL_PORT_MONITOR.print("wifi_cb: M2M_WIFI_REQ_DHCP_CONF: IP is "); + SERIAL_PORT_MONITOR.print(pu8IPAddress[0], 10); + SERIAL_PORT_MONITOR.print("."); + SERIAL_PORT_MONITOR.print(pu8IPAddress[1], 10); + SERIAL_PORT_MONITOR.print("."); + SERIAL_PORT_MONITOR.print(pu8IPAddress[2], 10); + SERIAL_PORT_MONITOR.print("."); + SERIAL_PORT_MONITOR.print(pu8IPAddress[3], 10); + SERIAL_PORT_MONITOR.println("");*/ + } + break; + + case M2M_WIFI_RESP_CURRENT_RSSI: + { + WiFi._resolve = *((int8_t *)pvMsg); + } + break; + + case M2M_WIFI_RESP_PROVISION_INFO: + { + tstrM2MProvisionInfo *pstrProvInfo = (tstrM2MProvisionInfo *)pvMsg; + //SERIAL_PORT_MONITOR.println("wifi_cb: M2M_WIFI_RESP_PROVISION_INFO"); + + if (pstrProvInfo->u8Status == M2M_SUCCESS) { + memset(WiFi._ssid, 0, M2M_MAX_SSID_LEN); + memcpy(WiFi._ssid, (char *)pstrProvInfo->au8SSID, strlen((char *)pstrProvInfo->au8SSID)); + WiFi._mode = WL_STA_MODE; + WiFi._localip = 0; + WiFi._submask = 0; + WiFi._gateway = 0; + m2m_wifi_connect((char *)pstrProvInfo->au8SSID, strlen((char *)pstrProvInfo->au8SSID), + pstrProvInfo->u8SecType, pstrProvInfo->au8Password, M2M_WIFI_CH_ALL); + } else { + WiFi._status = WL_PROVISIONING_FAILED; + //SERIAL_PORT_MONITOR.println("wifi_cb: Provision failed.\r\n"); + WiFi.beginProvision(); + } + } + break; + + case M2M_WIFI_RESP_SCAN_DONE: + { + tstrM2mScanDone *pstrInfo = (tstrM2mScanDone *)pvMsg; + if (pstrInfo->u8NumofCh >= 1) { + WiFi._status = WL_SCAN_COMPLETED; + } + } + break; + + case M2M_WIFI_RESP_SCAN_RESULT: + { + tstrM2mWifiscanResult *pstrScanResult = (tstrM2mWifiscanResult *)pvMsg; + uint16_t scan_ssid_len = strlen((const char *)pstrScanResult->au8SSID); + memset(WiFi._scan_ssid, 0, M2M_MAX_SSID_LEN); + if (scan_ssid_len) { + memcpy(WiFi._scan_ssid, (const char *)pstrScanResult->au8SSID, scan_ssid_len); + } + if (WiFi._remoteMacAddress) { + // reverse copy the remote MAC + for(int i = 0; i < 6; i++) { + WiFi._remoteMacAddress[i] = pstrScanResult->au8BSSID[5-i]; + } + } + WiFi._resolve = pstrScanResult->s8rssi; + WiFi._scan_auth = pstrScanResult->u8AuthType; + WiFi._scan_channel = pstrScanResult->u8ch; + WiFi._status = WL_SCAN_COMPLETED; + } + break; + + case M2M_WIFI_RESP_CONN_INFO: + { + tstrM2MConnInfo *pstrConnInfo = (tstrM2MConnInfo*)pvMsg; + + if (WiFi._remoteMacAddress) { + // reverse copy the remote MAC + for(int i = 0; i < 6; i++) { + WiFi._remoteMacAddress[i] = pstrConnInfo->au8MACAddress[5-i]; + } + WiFi._remoteMacAddress = 0; + } + + strcpy((char *)WiFi._ssid, pstrConnInfo->acSSID); + } + break; + + case M2M_WIFI_RESP_GET_SYS_TIME: + { + if (WiFi._resolve != 0) { + memcpy((tstrSystemTime *)WiFi._resolve, pvMsg, sizeof(tstrSystemTime)); + + WiFi._resolve = 0; + } + } + break; + + default: + break; + } +} + +static void resolve_cb(uint8_t * /* hostName */, uint32_t hostIp) +{ + WiFi._resolve = hostIp; +} + +static void ping_cb(uint32 u32IPAddr, uint32 u32RTT, uint8 u8ErrorCode) +{ + if (PING_ERR_SUCCESS == u8ErrorCode) { + // Ensure this ICMP reply comes from requested IP address + if (WiFi._resolve == u32IPAddr) { + WiFi._resolve = (uint32_t)u32RTT; + } else { + // Another network device replied to the our ICMP request + WiFi._resolve = (uint32_t)WL_PING_DEST_UNREACHABLE; + } + } else if (PING_ERR_DEST_UNREACH == u8ErrorCode) { + WiFi._resolve = (uint32_t)WL_PING_DEST_UNREACHABLE; + } else if (PING_ERR_TIMEOUT == u8ErrorCode) { + WiFi._resolve = (uint32_t)WL_PING_TIMEOUT; + } else { + WiFi._resolve = (uint32_t)WL_PING_ERROR; + } +} + +WiFiClass::WiFiClass() +{ + _mode = WL_RESET_MODE; + _status = WL_NO_SHIELD; + _init = 0; +} + +void WiFiClass::setPins(int8_t cs, int8_t irq, int8_t rst, int8_t en) +{ + gi8Winc1501CsPin = cs; + gi8Winc1501IntnPin = irq; + gi8Winc1501ResetPin = rst; + gi8Winc1501ChipEnPin = en; +} + +int WiFiClass::init() +{ + tstrWifiInitParam param; + int8_t ret; + + // Initialize the WiFi BSP: + nm_bsp_init(); + + // Initialize WiFi module and register status callback: + param.pfAppWifiCb = wifi_cb; + ret = m2m_wifi_init(¶m); + if (M2M_SUCCESS != ret && M2M_ERR_FW_VER_MISMATCH != ret) { + // Error led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO18, 0); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO6, 1); + return ret; + } + + // Initialize socket API and register socket callback: + socketInit(); + socketBufferInit(); + registerSocketCallback(socketBufferCb, resolve_cb); + _init = 1; + _status = WL_IDLE_STATUS; + _localip = 0; + _submask = 0; + _gateway = 0; + _dhcp = 1; + _resolve = 0; + _remoteMacAddress = 0; + memset(_client, 0, sizeof(WiFiClient *) * TCP_SOCK_MAX); + + extern uint32 nmdrv_firm_ver; + + if (nmdrv_firm_ver >= M2M_MAKE_VERSION(19, 5, 0)) { + // enable AES-128 and AES-256 Ciphers, if firmware is 19.5.0 or higher + m2m_ssl_set_active_ciphersuites(SSL_NON_ECC_CIPHERS_AES_128 | SSL_NON_ECC_CIPHERS_AES_256); + } + + // Initialize IO expander LED control (rev A then rev B).. + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO18, 1); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO15, 1); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO18, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO6, 1); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO4, 1); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO5, 1); + m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO6, 1); + + return ret; +} + +extern "C" { + sint8 nm_get_firmware_info(tstrM2mRev* M2mRev); +} + +char* WiFiClass::firmwareVersion() +{ + tstrM2mRev rev; + + if (!_init) { + init(); + } + nm_get_firmware_info(&rev); + memset(_version, 0, 9); + if (rev.u8FirmwareMajor != rev.u8DriverMajor && rev.u8FirmwareMinor != rev.u8DriverMinor) { + sprintf(_version, "-Err-"); + } + else { + sprintf(_version, "%d.%d.%d", rev.u8FirmwareMajor, rev.u8FirmwareMinor, rev.u8FirmwarePatch); + } + return _version; +} + +uint8_t WiFiClass::begin() +{ + if (!_init) { + init(); + } + + // Connect to router: + if (_dhcp) { + _localip = 0; + _submask = 0; + _gateway = 0; + } + if (m2m_wifi_default_connect() < 0) { + _status = WL_CONNECT_FAILED; + return _status; + } + _status = WL_IDLE_STATUS; + _mode = WL_STA_MODE; + + // Wait for connection or timeout: + unsigned long start = millis(); + while (!(_status & WL_CONNECTED) && + !(_status & WL_DISCONNECTED) && + millis() - start < 60000) { + m2m_wifi_handle_events(NULL); + } + + memset(_ssid, 0, M2M_MAX_SSID_LEN); + + if (!(_status & WL_CONNECTED)) { + _mode = WL_RESET_MODE; + } else { + m2m_wifi_get_connection_info(); + + m2m_wifi_handle_events(NULL); + } + + return _status; +} + +uint8_t WiFiClass::begin(const char *ssid) +{ + return startConnect(ssid, M2M_WIFI_SEC_OPEN, (void *)0); +} + +uint8_t WiFiClass::begin(const char *ssid, uint8_t key_idx, const char* key) +{ + tstrM2mWifiWepParams wep_params; + + memset(&wep_params, 0, sizeof(tstrM2mWifiWepParams)); + wep_params.u8KeyIndx = key_idx; + wep_params.u8KeySz = strlen(key); + strcpy((char *)&wep_params.au8WepKey[0], key); + return startConnect(ssid, M2M_WIFI_SEC_WEP, &wep_params); +} + +uint8_t WiFiClass::begin(const char *ssid, const char *key) +{ + return startConnect(ssid, M2M_WIFI_SEC_WPA_PSK, key); +} + +uint8_t WiFiClass::startConnect(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo) +{ + if (!_init) { + init(); + } + + // Connect to router: + if (_dhcp) { + _localip = 0; + _submask = 0; + _gateway = 0; + } + if (m2m_wifi_connect((char*)ssid, strlen(ssid), u8SecType, (void*)pvAuthInfo, M2M_WIFI_CH_ALL) < 0) { + _status = WL_CONNECT_FAILED; + return _status; + } + _status = WL_IDLE_STATUS; + _mode = WL_STA_MODE; + + // Wait for connection or timeout: + unsigned long start = millis(); + while (!(_status & WL_CONNECTED) && + !(_status & WL_DISCONNECTED) && + millis() - start < 60000) { + m2m_wifi_handle_events(NULL); + } + if (!(_status & WL_CONNECTED)) { + _mode = WL_RESET_MODE; + } + + memset(_ssid, 0, M2M_MAX_SSID_LEN); + memcpy(_ssid, ssid, strlen(ssid)); + return _status; +} + +uint8_t WiFiClass::beginAP(const char *ssid) +{ + return beginAP(ssid, 1); +} + +uint8_t WiFiClass::beginAP(const char *ssid, uint8_t channel) +{ + return startAP(ssid, M2M_WIFI_SEC_OPEN, NULL, channel); +} + +uint8_t WiFiClass::beginAP(const char *ssid, uint8_t key_idx, const char* key) +{ + return beginAP(ssid, key_idx, key, 1); +} + +uint8_t WiFiClass::beginAP(const char *ssid, uint8_t key_idx, const char* key, uint8_t channel) +{ + tstrM2mWifiWepParams wep_params; + + if (key_idx == 0) { + key_idx = 1; // 1 is the minimum key index + } + + memset(&wep_params, 0, sizeof(tstrM2mWifiWepParams)); + wep_params.u8KeyIndx = key_idx; + wep_params.u8KeySz = strlen(key); + strcpy((char *)&wep_params.au8WepKey[0], key); + + return startAP(ssid, M2M_WIFI_SEC_WEP, &wep_params, channel); +} + +uint8_t WiFiClass::beginAP(const char *ssid, const char* key) +{ + return beginAP(ssid, key, 1); +} + +uint8_t WiFiClass::beginAP(const char *ssid, const char* key, uint8_t channel) +{ + return startAP(ssid, M2M_WIFI_SEC_WPA_PSK, key, channel); +} + +uint8_t WiFiClass::startAP(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo, uint8_t channel) +{ + tstrM2MAPConfig strM2MAPConfig; + + if (!_init) { + init(); + } + + if (channel == 0) { + channel = 1; // channel 1 is the minium channel + } + + // Enter Access Point mode: + memset(&strM2MAPConfig, 0x00, sizeof(tstrM2MAPConfig)); + strcpy((char *)&strM2MAPConfig.au8SSID, ssid); + strM2MAPConfig.u8ListenChannel = channel; + strM2MAPConfig.u8SecType = u8SecType; + if (_localip == 0) { + strM2MAPConfig.au8DHCPServerIP[0] = 192; + strM2MAPConfig.au8DHCPServerIP[1] = 168; + strM2MAPConfig.au8DHCPServerIP[2] = 1; + strM2MAPConfig.au8DHCPServerIP[3] = 1; + } else { + memcpy(strM2MAPConfig.au8DHCPServerIP, &_localip, sizeof(_localip)); + if (strM2MAPConfig.au8DHCPServerIP[3] == 100) { + // limitation of WINC1500 firmware, IP address of client is always x.x.x.100 + _status = WL_AP_FAILED; + return _status; + } + } + + if (u8SecType == M2M_WIFI_SEC_WEP) { + tstrM2mWifiWepParams* wep_params = (tstrM2mWifiWepParams*)pvAuthInfo; + + strM2MAPConfig.u8KeyIndx = wep_params->u8KeyIndx; + strM2MAPConfig.u8KeySz = wep_params->u8KeySz; + strcpy((char*)strM2MAPConfig.au8WepKey, (char *)wep_params->au8WepKey); + } + + if (u8SecType == M2M_WIFI_SEC_WPA_PSK) { + strM2MAPConfig.u8KeySz = strlen((char*)pvAuthInfo); + strcpy((char*)strM2MAPConfig.au8Key, (char *)pvAuthInfo); + } + + if (m2m_wifi_enable_ap(&strM2MAPConfig) < 0) { + _status = WL_AP_FAILED; + return _status; + } + _status = WL_AP_LISTENING; + _mode = WL_AP_MODE; + + memset(_ssid, 0, M2M_MAX_SSID_LEN); + memcpy(_ssid, ssid, strlen(ssid)); + m2m_memcpy((uint8 *)&_localip, (uint8 *)&strM2MAPConfig.au8DHCPServerIP[0], 4); + _submask = 0x00FFFFFF; + _gateway = _localip; + + // WiFi led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0); + + return _status; +} + +uint8_t WiFiClass::beginProvision() +{ + return beginProvision(1); +} + +uint8_t WiFiClass::beginProvision(uint8_t channel) +{ + // try to connect using begin + if (begin() != WL_CONNECTED) { + // failed, enter provisioning mode + + uint8_t mac[6]; + char provSsid[13]; + + // get MAC address for provisioning SSID + macAddress(mac); + sprintf(provSsid, "wifi101-%.2X%2X", mac[1], mac[0]); + + // start provisioning mode + startProvision(provSsid, "wifi101", channel); + } + + return status(); +} + +uint8_t WiFiClass::startProvision(const char *ssid, const char *url, uint8_t channel) +{ + tstrM2MAPConfig strM2MAPConfig; + + if (!_init) { + init(); + } + + // Enter Provision mode: + memset(&strM2MAPConfig, 0x00, sizeof(tstrM2MAPConfig)); + strcpy((char *)&strM2MAPConfig.au8SSID, ssid); + strM2MAPConfig.u8ListenChannel = channel; + strM2MAPConfig.u8SecType = M2M_WIFI_SEC_OPEN; + strM2MAPConfig.u8SsidHide = SSID_MODE_VISIBLE; + strM2MAPConfig.au8DHCPServerIP[0] = 192; + strM2MAPConfig.au8DHCPServerIP[1] = 168; + strM2MAPConfig.au8DHCPServerIP[2] = 1; + strM2MAPConfig.au8DHCPServerIP[3] = 1; + + if (m2m_wifi_start_provision_mode((tstrM2MAPConfig *)&strM2MAPConfig, (char*)url, 1) < 0) { + _status = WL_PROVISIONING_FAILED; + return _status; + } + _status = WL_PROVISIONING; + _mode = WL_PROV_MODE; + + memset(_ssid, 0, M2M_MAX_SSID_LEN); + memcpy(_ssid, ssid, strlen(ssid)); + m2m_memcpy((uint8 *)&_localip, (uint8 *)&strM2MAPConfig.au8DHCPServerIP[0], 4); + _submask = 0x00FFFFFF; + _gateway = _localip; + + // WiFi led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0); + + return _status; +} + +uint32_t WiFiClass::provisioned() +{ + m2m_wifi_handle_events(NULL); + + if (_mode == WL_STA_MODE) { + return 1; + } + else { + return 0; + } +} + +void WiFiClass::config(IPAddress local_ip) +{ + config(local_ip, (uint32_t)0); +} + +void WiFiClass::config(IPAddress local_ip, IPAddress dns_server) +{ + config(local_ip, dns_server, (uint32_t)0); +} + +void WiFiClass::config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway) +{ + config(local_ip, dns_server, gateway, (uint32_t)0); +} + +void WiFiClass::config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet) +{ + tstrM2MIPConfig conf; + + if (!_init) { + init(); + } + + conf.u32DNS = (uint32_t)dns_server; + conf.u32Gateway = (uint32_t)gateway; + conf.u32StaticIP = (uint32_t)local_ip; + conf.u32SubnetMask = (uint32_t)subnet; + _dhcp = 0; + m2m_wifi_enable_dhcp(0); // disable DHCP + m2m_wifi_set_static_ip(&conf); + _localip = conf.u32StaticIP; + _submask = conf.u32SubnetMask; + _gateway = conf.u32Gateway; +} + +void WiFiClass::hostname(const char* name) +{ + if (!_init) { + init(); + } + + m2m_wifi_set_device_name((uint8 *)name, strlen(name)); +} + +void WiFiClass::disconnect() +{ + m2m_wifi_disconnect(); + + // WiFi led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); +} + +void WiFiClass::end() +{ + if (_mode == WL_AP_MODE) { + m2m_wifi_disable_ap(); + } else { + if (_mode == WL_PROV_MODE) { + m2m_wifi_stop_provision_mode(); + } + + m2m_wifi_disconnect(); + } + + // WiFi led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); + + socketDeinit(); + + m2m_wifi_deinit(NULL); + + nm_bsp_deinit(); + + _mode = WL_RESET_MODE; + _status = WL_NO_SHIELD; + _init = 0; +} + +uint8_t *WiFiClass::macAddress(uint8_t *mac) +{ + m2m_wifi_get_mac_address(mac); + byte tmpMac[6], i; + + m2m_wifi_get_mac_address(tmpMac); + + for(i = 0; i < 6; i++) + mac[i] = tmpMac[5-i]; + + return mac; +} + +uint32_t WiFiClass::localIP() +{ + return _localip; +} + +uint32_t WiFiClass::subnetMask() +{ + return _submask; +} + +uint32_t WiFiClass::gatewayIP() +{ + return _gateway; +} + +char* WiFiClass::SSID() +{ + if (_status == WL_CONNECTED || _status == WL_AP_LISTENING || _status == WL_AP_CONNECTED) { + return _ssid; + } + else { + return 0; + } +} + +uint8_t* WiFiClass::BSSID(uint8_t* bssid) +{ + if (_mode == WL_AP_MODE) { + return macAddress(bssid); + } else { + return remoteMacAddress(bssid); + } +} + +uint8_t* WiFiClass::APClientMacAddress(uint8_t* mac) +{ + if (_mode == WL_AP_MODE) { + return remoteMacAddress(mac); + } else { + memset(mac, 0, 6); + return mac; + } +} + +uint8_t* WiFiClass::remoteMacAddress(uint8_t* remoteMacAddress) +{ + _remoteMacAddress = remoteMacAddress; + memset(remoteMacAddress, 0, 6); + + m2m_wifi_get_connection_info(); + + // Wait for connection or timeout: + unsigned long start = millis(); + while (_remoteMacAddress != 0 && millis() - start < 1000) { + m2m_wifi_handle_events(NULL); + } + + _remoteMacAddress = 0; + return remoteMacAddress; +} + +int32_t WiFiClass::RSSI() +{ + // Clear pending events: + m2m_wifi_handle_events(NULL); + + // Send RSSI request: + _resolve = 0; + if (m2m_wifi_req_curr_rssi() < 0) { + return 0; + } + + // Wait for connection or timeout: + unsigned long start = millis(); + while (_resolve == 0 && millis() - start < 1000) { + m2m_wifi_handle_events(NULL); + } + + int32_t rssi = _resolve; + + _resolve = 0; + + return rssi; +} + +int8_t WiFiClass::scanNetworks() +{ + wl_status_t tmp = _status; + + if (!_init) { + init(); + } + + // Start scan: + if (m2m_wifi_request_scan(M2M_WIFI_CH_ALL) < 0) { + return 0; + } + + // Wait for scan result or timeout: + _status = WL_IDLE_STATUS; + unsigned long start = millis(); + while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 5000) { + m2m_wifi_handle_events(NULL); + } + _status = tmp; + return m2m_wifi_get_num_ap_found(); +} + +char* WiFiClass::SSID(uint8_t pos) +{ + wl_status_t tmp = _status; + + // Get scan SSID result: + memset(_scan_ssid, 0, M2M_MAX_SSID_LEN); + if (m2m_wifi_req_scan_result(pos) < 0) { + return 0; + } + + // Wait for connection or timeout: + _status = WL_IDLE_STATUS; + unsigned long start = millis(); + while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + + _status = tmp; + _resolve = 0; + + return _scan_ssid; +} + +int32_t WiFiClass::RSSI(uint8_t pos) +{ + wl_status_t tmp = _status; + + // Get scan RSSI result: + if (m2m_wifi_req_scan_result(pos) < 0) { + return 0; + } + + // Wait for connection or timeout: + _status = WL_IDLE_STATUS; + unsigned long start = millis(); + while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + + _status = tmp; + + int32_t rssi = _resolve; + + _resolve = 0; + + return rssi; +} + +uint8_t WiFiClass::encryptionType() +{ + int8_t net = scanNetworks(); + + for (uint8_t i = 0; i < net; ++i) { + SSID(i); + if (strcmp(_scan_ssid, _ssid) == 0) { + break; + } + } + + return _scan_auth; +} + +uint8_t WiFiClass::encryptionType(uint8_t pos) +{ + wl_status_t tmp = _status; + + // Get scan auth result: + if (m2m_wifi_req_scan_result(pos) < 0) { + return 0; + } + + // Wait for connection or timeout: + _status = WL_IDLE_STATUS; + unsigned long start = millis(); + while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + + _status = tmp; + _resolve = 0; + + return _scan_auth; +} + +uint8_t* WiFiClass::BSSID(uint8_t pos, uint8_t* bssid) +{ + wl_status_t tmp = _status; + + _remoteMacAddress = bssid; + + // Get scan auth result: + if (m2m_wifi_req_scan_result(pos) < 0) { + return 0; + } + + // Wait for connection or timeout: + _status = WL_IDLE_STATUS; + unsigned long start = millis(); + while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + + _status = tmp; + _resolve = 0; + _remoteMacAddress = 0; + + return bssid; +} + +uint8_t WiFiClass::channel(uint8_t pos) +{ + wl_status_t tmp = _status; + + // Get scan auth result: + if (m2m_wifi_req_scan_result(pos) < 0) { + return 0; + } + + // Wait for connection or timeout: + _status = WL_IDLE_STATUS; + unsigned long start = millis(); + while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + + _status = tmp; + _resolve = 0; + + return _scan_channel; +} + +uint8_t WiFiClass::status() +{ + if (!_init) { + init(); + } + + m2m_wifi_handle_events(NULL); + + return _status; +} + +int WiFiClass::hostByName(const char* aHostname, IPAddress& aResult) +{ + + // check if aHostname is already an ipaddress + if (aResult.fromString(aHostname)) { + // if fromString returns true we have an IP address ready + return 1; + + } else { + // Network led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); + + // Send DNS request: + _resolve = 0; + if (gethostbyname((uint8 *)aHostname) < 0) { + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + return 0; + } + + // Wait for connection or timeout: + unsigned long start = millis(); + while (_resolve == 0 && millis() - start < 20000) { + m2m_wifi_handle_events(NULL); + } + + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + + if (_resolve == 0) { + return 0; + } + + aResult = _resolve; + _resolve = 0; + return 1; + } +} + +void WiFiClass::refresh(void) +{ + // Update state machine: + m2m_wifi_handle_events(NULL); +} + +void WiFiClass::lowPowerMode(void) +{ + m2m_wifi_set_sleep_mode(M2M_PS_H_AUTOMATIC, true); +} + +void WiFiClass::maxLowPowerMode(void) +{ + m2m_wifi_set_sleep_mode(M2M_PS_DEEP_AUTOMATIC, true); +} + +void WiFiClass::noLowPowerMode(void) +{ + m2m_wifi_set_sleep_mode(M2M_NO_PS, false); +} + +int WiFiClass::ping(const char* hostname, uint8_t ttl) +{ + IPAddress ip; + + if (hostByName(hostname, ip) > 0) { + return ping(ip, ttl); + } else { + return WL_PING_UNKNOWN_HOST; + } +} + +int WiFiClass::ping(const String &hostname, uint8_t ttl) +{ + return ping(hostname.c_str(), ttl); +} + +int WiFiClass::ping(IPAddress host, uint8_t ttl) +{ + // Network led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); + + uint32_t dstHost = (uint32_t)host; + _resolve = dstHost; + + if (m2m_ping_req((uint32_t)host, ttl, &ping_cb) < 0) { + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + // Error sending ping request + return WL_PING_ERROR; + } + + // Wait for success or timeout: + unsigned long start = millis(); + while (_resolve == dstHost && millis() - start < 5000) { + m2m_wifi_handle_events(NULL); + } + + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + + if (_resolve == dstHost) { + _resolve = 0; + return WL_PING_TIMEOUT; + } else { + int rtt = (int)_resolve; + _resolve = 0; + return rtt; + } +} + +uint32_t WiFiClass::getTime() +{ +#ifdef WIFI_101_NO_TIME_H + #warning "No system header included, WiFi.getTime() will always return 0" + return 0; +#else + tstrSystemTime systemTime; + + _resolve = (uint32_t)&systemTime; + + m2m_wifi_get_sytem_time(); + + unsigned long start = millis(); + while (_resolve != 0 && millis() - start < 5000) { + m2m_wifi_handle_events(NULL); + } + + time_t t = 0; + + if (_resolve == 0 && systemTime.u16Year > 0) { + struct tm tm; + + tm.tm_year = systemTime.u16Year - 1900; + tm.tm_mon = systemTime.u8Month - 1; + tm.tm_mday = systemTime.u8Day; + tm.tm_hour = systemTime.u8Hour; + tm.tm_min = systemTime.u8Minute; + tm.tm_sec = systemTime.u8Second; + tm.tm_isdst = -1; + + t = mktime(&tm); + } + + _resolve = 0; + + return t; +#endif +} + +WiFiClass WiFi; diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFi101.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFi101.h new file mode 100644 index 0000000..6e46fab --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFi101.h @@ -0,0 +1,193 @@ +/* + WiFi.h - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef WIFI_H +#define WIFI_H + +#define WIFI_FIRMWARE_LATEST_MODEL_A "19.4.4" +#define WIFI_FIRMWARE_LATEST_MODEL_B "19.5.2" + +// for backwards compatibility +#define WIFI_FIRMWARE_REQUIRED WIFI_FIRMWARE_LATEST_MODEL_B + +#include + +extern "C" { + #include "driver/include/m2m_wifi.h" + #include "socket/include/socket.h" +} + +#include "WiFiClient.h" +#include "WiFiSSLClient.h" +#include "WiFiServer.h" + +typedef enum { + WL_NO_SHIELD = 255, + WL_IDLE_STATUS = 0, + WL_NO_SSID_AVAIL, + WL_SCAN_COMPLETED, + WL_CONNECTED, + WL_CONNECT_FAILED, + WL_CONNECTION_LOST, + WL_DISCONNECTED, + WL_AP_LISTENING, + WL_AP_CONNECTED, + WL_AP_FAILED, + WL_PROVISIONING, + WL_PROVISIONING_FAILED +} wl_status_t; + +/* Encryption modes */ +enum wl_enc_type { /* Values map to 802.11 encryption suites... */ + ENC_TYPE_WEP = M2M_WIFI_SEC_WEP, + ENC_TYPE_TKIP = M2M_WIFI_SEC_WPA_PSK, + ENC_TYPE_CCMP = M2M_WIFI_SEC_802_1X, + /* ... except these two, 7 and 8 are reserved in 802.11-2007 */ + ENC_TYPE_NONE = M2M_WIFI_SEC_OPEN, + ENC_TYPE_AUTO = M2M_WIFI_SEC_INVALID +}; + +typedef enum { + WL_RESET_MODE = 0, + WL_STA_MODE, + WL_PROV_MODE, + WL_AP_MODE +} wl_mode_t; + +typedef enum { + WL_PING_DEST_UNREACHABLE = -1, + WL_PING_TIMEOUT = -2, + WL_PING_UNKNOWN_HOST = -3, + WL_PING_ERROR = -4 +} wl_ping_result_t; + +class WiFiClass +{ +public: + uint32_t _localip; + uint32_t _submask; + uint32_t _gateway; + int _dhcp; + uint32_t _resolve; + byte *_remoteMacAddress; + wl_mode_t _mode; + wl_status_t _status; + char _scan_ssid[M2M_MAX_SSID_LEN]; + uint8_t _scan_auth; + uint8_t _scan_channel; + char _ssid[M2M_MAX_SSID_LEN]; + WiFiClient *_client[TCP_SOCK_MAX]; + + WiFiClass(); + + void setPins(int8_t cs, int8_t irq, int8_t rst, int8_t en = -1); + + int init(); + + char* firmwareVersion(); + + /* Start Wifi connection with WPA/WPA2 encryption. + * + * param ssid: Pointer to the SSID string. + * param key: Key input buffer. + */ + uint8_t begin(); + uint8_t begin(const char *ssid); + uint8_t begin(const char *ssid, uint8_t key_idx, const char* key); + uint8_t begin(const char *ssid, const char *key); + uint8_t begin(const String &ssid) { return begin(ssid.c_str()); } + uint8_t begin(const String &ssid, uint8_t key_idx, const String &key) { return begin(ssid.c_str(), key_idx, key.c_str()); } + uint8_t begin(const String &ssid, const String &key) { return begin(ssid.c_str(), key.c_str()); } + + /* Start Wifi in Access Point, with open security. + * Only one client can connect to the AP at a time. + * + * param ssid: Pointer to the SSID string. + * param channel: Wifi channel to use. Valid values are 1-12. + */ + uint8_t beginAP(const char *ssid); + uint8_t beginAP(const char *ssid, uint8_t channel); + uint8_t beginAP(const char *ssid, uint8_t key_idx, const char* key); + uint8_t beginAP(const char *ssid, uint8_t key_idx, const char* key, uint8_t channel); + uint8_t beginAP(const char *ssid, const char* key); + uint8_t beginAP(const char *ssid, const char* key, uint8_t channel); + + uint8_t beginProvision(); + uint8_t beginProvision(uint8_t channel); + + uint32_t provisioned(); + + void config(IPAddress local_ip); + void config(IPAddress local_ip, IPAddress dns_server); + void config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway); + void config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet); + + void hostname(const char* name); + + void disconnect(); + void end(); + + uint8_t *macAddress(uint8_t *mac); + + uint32_t localIP(); + uint32_t subnetMask(); + uint32_t gatewayIP(); + char* SSID(); + int32_t RSSI(); + uint8_t encryptionType(); + uint8_t* BSSID(uint8_t* bssid); + uint8_t* APClientMacAddress(uint8_t* mac); + int8_t scanNetworks(); + char* SSID(uint8_t pos); + int32_t RSSI(uint8_t pos); + uint8_t encryptionType(uint8_t pos); + uint8_t* BSSID(uint8_t pos, uint8_t* bssid); + uint8_t channel(uint8_t pos); + + uint8_t status(); + + int hostByName(const char* hostname, IPAddress& result); + int hostByName(const String &hostname, IPAddress& result) { return hostByName(hostname.c_str(), result); } + + int ping(const char* hostname, uint8_t ttl = 128); + int ping(const String &hostname, uint8_t ttl = 128); + int ping(IPAddress host, uint8_t ttl = 128); + + unsigned long getTime(); + + void refresh(void); + + void lowPowerMode(void); + void maxLowPowerMode(void); + void noLowPowerMode(void); + +private: + int _init; + char _version[9]; + + uint8_t startConnect(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo); + uint8_t startAP(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo, uint8_t channel); + uint8_t* remoteMacAddress(uint8_t* remoteMacAddress); + + uint8_t startProvision(const char *ssid, const char *url, uint8_t channel); +}; + +extern WiFiClass WiFi; + +#endif /* WIFI_H */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiClient.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiClient.cpp new file mode 100644 index 0000000..8298618 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiClient.cpp @@ -0,0 +1,308 @@ +/* + WiFiClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +extern "C" { + #include "socket/include/socket.h" + #include "driver/include/m2m_periph.h" +} + +#include "WiFi101.h" +#include "WiFiClient.h" + +#define IS_CONNECTED (_flag & SOCKET_BUFFER_FLAG_CONNECTED) + +WiFiClient::WiFiClient() +{ + _socket = -1; + _flag = 0; + _head = 0; + _tail = 0; +} + +WiFiClient::WiFiClient(uint8_t sock, uint8_t parentsock) +{ + // Spawn connected TCP client from TCP server socket: + _socket = sock; + _flag = SOCKET_BUFFER_FLAG_CONNECTED; + if (parentsock) { + _flag |= ((uint32_t)parentsock) << SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS; + } + _head = 0; + _tail = 0; + for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { + if (WiFi._client[sock] == this) + WiFi._client[sock] = 0; + } + WiFi._client[_socket] = this; + + // Add socket buffer handler: + socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_buffer); + + // Enable receive buffer: + recv(_socket, _buffer, SOCKET_BUFFER_MTU, 0); + + m2m_wifi_handle_events(NULL); +} + +WiFiClient::WiFiClient(const WiFiClient& other) +{ + copyFrom(other); +} + +void WiFiClient::copyFrom(const WiFiClient& other) +{ + _socket = other._socket; + _flag = other._flag; + _head = other._head; + _tail = other._tail; + if (_head > _tail) { + memcpy(_buffer + _tail, other._buffer + _tail, (_head - _tail)); + } + + for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { + if (WiFi._client[sock] == this) + WiFi._client[sock] = 0; + } + + if (_socket > -1) { + WiFi._client[_socket] = this; + + // Add socket buffer handler: + socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_buffer); + + // Enable receive buffer: + recv(_socket, _buffer, SOCKET_BUFFER_MTU, 0); + } + + m2m_wifi_handle_events(NULL); +} + +int WiFiClient::connectSSL(const char* host, uint16_t port) +{ + return connect(host, port, SOCKET_FLAGS_SSL); +} + +int WiFiClient::connectSSL(IPAddress ip, uint16_t port) +{ + return connect(ip, port, SOCKET_FLAGS_SSL, 0); +} + +int WiFiClient::connect(const char* host, uint16_t port) +{ + return connect(host, port, 0); +} + +int WiFiClient::connect(IPAddress ip, uint16_t port) +{ + return connect(ip, port, 0, 0); +} + +int WiFiClient::connect(const char* host, uint16_t port, uint8_t opt) +{ + IPAddress remote_addr; + if (WiFi.hostByName(host, remote_addr)) { + return connect(remote_addr, port, opt, (const uint8_t *)host); + } + return 0; +} + +int WiFiClient::connect(IPAddress ip, uint16_t port, uint8_t opt, const uint8_t *hostname) +{ + struct sockaddr_in addr; + + // Initialize socket address structure: + addr.sin_family = AF_INET; + addr.sin_port = _htons(port); + addr.sin_addr.s_addr = ip; + + // Create TCP socket: + _flag = 0; + _head = 0; + _tail = 0; + if ((_socket = socket(AF_INET, SOCK_STREAM, opt)) < 0) { + return 0; + } + + if (opt & SOCKET_FLAGS_SSL && hostname) { + setsockopt(_socket, SOL_SSL_SOCKET, SO_SSL_SNI, hostname, m2m_strlen((uint8_t *)hostname)); + } + + // Add socket buffer handler: + socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_buffer); + + // Connect to remote host: + if (connectSocket(_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { + close(_socket); + _socket = -1; + return 0; + } + + // Wait for connection or timeout: + unsigned long start = millis(); + while (!IS_CONNECTED && millis() - start < 20000) { + m2m_wifi_handle_events(NULL); + } + if (!IS_CONNECTED) { + close(_socket); + _socket = -1; + return 0; + } + + WiFi._client[_socket] = this; + + return 1; +} + +size_t WiFiClient::write(uint8_t b) +{ + return write(&b, 1); +} + +size_t WiFiClient::write(const uint8_t *buf, size_t size) +{ + sint16 err; + + if (_socket < 0 || size == 0 || !IS_CONNECTED) { + setWriteError(); + return 0; + } + + // Network led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); + + m2m_wifi_handle_events(NULL); + + while ((err = send(_socket, (void *)buf, size, 0)) < 0) { + // Exit on fatal error, retry if buffer not ready. + if (err != SOCK_ERR_BUFFER_FULL) { + setWriteError(); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + return 0; + } + m2m_wifi_handle_events(NULL); + } + + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + + return size; +} + +int WiFiClient::available() +{ + m2m_wifi_handle_events(NULL); + + if (_socket != -1) { + return _head - _tail; + } + return 0; +} + +int WiFiClient::read() +{ + uint8_t b; + + if (read(&b, sizeof(b)) == -1) { + return -1; + } + + return b; +} + +int WiFiClient::read(uint8_t* buf, size_t size) +{ + // sizeof(size_t) is architecture dependent + // but we need a 16 bit data type here + uint16_t size_tmp = available(); + + if (size_tmp == 0) { + return -1; + } + + if (size < size_tmp) { + size_tmp = size; + } + + for (uint32_t i = 0; i < size_tmp; ++i) { + buf[i] = _buffer[_tail++]; + } + + if (_tail == _head) { + _tail = _head = 0; + _flag &= ~SOCKET_BUFFER_FLAG_FULL; + recv(_socket, _buffer, SOCKET_BUFFER_MTU, 0); + m2m_wifi_handle_events(NULL); + } + + return size_tmp; +} + +int WiFiClient::peek() +{ + if (!available()) + return -1; + + return _buffer[_tail]; +} + +void WiFiClient::flush() +{ + while (available()) + read(); +} + +void WiFiClient::stop() +{ + if (_socket < 0) + return; + + socketBufferUnregister(_socket); + close(_socket); + _socket = -1; + _flag = 0; +} + +uint8_t WiFiClient::connected() +{ + m2m_wifi_handle_events(NULL); + if (available()) + return 1; + return IS_CONNECTED; +} + +uint8_t WiFiClient::status() +{ + // Deprecated. + return 0; +} + +WiFiClient::operator bool() +{ + return _socket != -1; +} + +WiFiClient& WiFiClient::operator =(const WiFiClient& other) +{ + copyFrom(other); + + return *this; +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiClient.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiClient.h new file mode 100644 index 0000000..bef171d --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiClient.h @@ -0,0 +1,68 @@ +/* + WiFiClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef WIFICLIENT_H +#define WIFICLIENT_H + +#include +#include +#include +#include "socket/include/socket_buffer.h" + +class WiFiClient : public Client { + +public: + WiFiClient(); + WiFiClient(uint8_t sock, uint8_t parentsock = 0); + WiFiClient(const WiFiClient& other); + + uint8_t status(); + + int connectSSL(IPAddress ip, uint16_t port); + int connectSSL(const char* host, uint16_t port); + virtual int connect(IPAddress ip, uint16_t port); + virtual int connect(const char* host, uint16_t port); + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + virtual int available(); + virtual int read(); + virtual int read(uint8_t *buf, size_t size); + virtual int peek(); + virtual void flush(); + virtual void stop(); + virtual uint8_t connected(); + virtual operator bool(); + virtual WiFiClient& operator =(const WiFiClient& other); + + using Print::write; + + uint32_t _flag; + +private: + SOCKET _socket; + uint32_t _head; + uint32_t _tail; + uint8_t _buffer[SOCKET_BUFFER_TCP_SIZE]; + int connect(const char* host, uint16_t port, uint8_t opt); + int connect(IPAddress ip, uint16_t port, uint8_t opt, const uint8_t *hostname); + void copyFrom(const WiFiClient& other); + +}; + +#endif /* WIFICLIENT_H */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiMDNSResponder.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiMDNSResponder.cpp new file mode 100644 index 0000000..a192113 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiMDNSResponder.cpp @@ -0,0 +1,220 @@ +// Port of CC3000 MDNS Responder to WINC1500. +// Author: Tony DiCola +// +// This MDNSResponder class implements just enough MDNS functionality to respond +// to name requests, for example 'foo.local'. This does not implement any other +// MDNS or Bonjour functionality like services, etc. +// +// Copyright (c) 2016 Adafruit Industries. All right reserved. +// +// 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 2.1 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 Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +#include +#ifndef ARDUINO_ARCH_AVR +#include +#endif + +#include "Arduino.h" +#include "WiFiMDNSResponder.h" + +// Important RFC's for reference: +// - DNS request and response: http://www.ietf.org/rfc/rfc1035.txt +// - Multicast DNS: http://www.ietf.org/rfc/rfc6762.txt + +#define HEADER_SIZE 12 +#define TTL_OFFSET 4 +#define IP_OFFSET 10 + +const uint8_t expectedRequestHeader[HEADER_SIZE] PROGMEM = { + 0x00, 0x00, + 0x00, 0x00, + 0x00, 0x01, // questions (these 2 bytes are ignored) + 0x00, 0x00, + 0x00, 0x00, + 0x00, 0x00 +}; + +const uint8_t responseHeader[] PROGMEM = { + 0x00, 0x00, // ID = 0 + 0x84, 0x00, // Flags = response + authoritative answer + 0x00, 0x00, // Question count = 0 + 0x00, 0x01, // Answer count = 1 + 0x00, 0x00, // Name server records = 0 + 0x00, 0x01 // Additional records = 1 +}; + +// Generate positive response for IPV4 address +const uint8_t aRecord[] PROGMEM = { + 0x00, 0x01, // Type = 1, A record/IPV4 address + 0x80, 0x01, // Class = Internet, with cache flush bit + 0x00, 0x00, 0x00, 0x00, // TTL in seconds, to be filled in later + 0x00, 0x04, // Length of record + 0x00, 0x00, 0x00, 0x00 // IP address, to be filled in later +}; + +// Generate negative response for IPV6 address (CC3000 doesn't support IPV6) +const uint8_t nsecRecord[] PROGMEM = { + 0xC0, 0x0C, // Name offset + 0x00, 0x2F, // Type = 47, NSEC (overloaded by MDNS) + 0x80, 0x01, // Class = Internet, with cache flush bit + 0x00, 0x00, 0x00, 0x00, // TTL in seconds, to be filled in later + 0x00, 0x08, // Length of record + 0xC0, 0x0C, // Next domain = offset to FQDN + 0x00, // Block number = 0 + 0x04, // Length of bitmap = 4 bytes + 0x40, 0x00, 0x00, 0x00 // Bitmap value = Only first bit (A record/IPV4) is set +}; + +const uint8_t domain[] PROGMEM = { 'l', 'o', 'c', 'a', 'l' }; + +WiFiMDNSResponder::WiFiMDNSResponder() : + minimumExpectedRequestLength(0) +{ +} + +WiFiMDNSResponder::~WiFiMDNSResponder() +{ +} + +bool WiFiMDNSResponder::begin(const char* _name, uint32_t _ttlSeconds) +{ + int nameLength = strlen(_name); + + if (nameLength > 255) { + // Can only handle domains that are upto 255 chars in length. + minimumExpectedRequestLength = 0; + return false; + } + + name = _name; + ttlSeconds = _ttlSeconds; + + name.toLowerCase(); + minimumExpectedRequestLength = HEADER_SIZE + 1 + nameLength + 1 + sizeof(domain) + 5; + + // Open the MDNS UDP listening socket on port 5353 with multicast address + // 224.0.0.251 (0xE00000FB) + if (!udpSocket.beginMulticast(IPAddress(224, 0, 0, 251), 5353)) { + return false; + } + + return true; +} + +void WiFiMDNSResponder::poll() +{ + if (parseRequest()) { + replyToRequest(); + } +} + +bool WiFiMDNSResponder::parseRequest() +{ + int packetLength = udpSocket.parsePacket(); + + if (packetLength) { + // check if parsed packet matches expected request length + if (packetLength < minimumExpectedRequestLength) { + // it does not, read the full packet in and drop data + while(udpSocket.available()) { + udpSocket.read(); + } + + return false; + } + + // read up to the min expect request length + uint8_t request[minimumExpectedRequestLength]; + udpSocket.read(request, minimumExpectedRequestLength); + + // discard the rest + while(udpSocket.available()) { + udpSocket.read(); + } + + // parse request + uint8_t requestNameLength = request[HEADER_SIZE]; + uint8_t* requestName = &request[HEADER_SIZE + 1]; + uint8_t requestDomainLength = request[HEADER_SIZE + 1 + requestNameLength]; + uint8_t* requestDomain = &request[HEADER_SIZE + 1 + requestNameLength + 1]; + uint16_t requestQtype; + uint16_t requestQclass; + + memcpy(&requestQtype, &request[minimumExpectedRequestLength - 4], sizeof(requestQtype)); + memcpy(&requestQclass, &request[minimumExpectedRequestLength - 2], sizeof(requestQclass)); + + requestQtype = _ntohs(requestQtype); + requestQclass = _ntohs(requestQclass); + + // compare request + if (memcmp_P(request, expectedRequestHeader, 4) == 0 && // request header start match + memcmp_P(&request[6], &expectedRequestHeader[6], 6) == 0 && // request header end match + requestNameLength == name.length() && // name length match + strncasecmp(name.c_str(), (char*)requestName, requestNameLength) == 0 && // name match + requestDomainLength == sizeof(domain) && // domain length match + memcmp_P(requestDomain, domain, requestDomainLength) == 0 && // suffix match + requestQtype == 0x0001 && // request QType match + requestQclass == 0x0001) { // request QClass match + + return true; + } + } + + return false; +} + +void WiFiMDNSResponder::replyToRequest() +{ + int nameLength = name.length(); + int domainLength = sizeof(domain); + uint32_t ipAddress = WiFi.localIP(); + uint32_t ttl = _htonl(ttlSeconds); + + int responseSize = sizeof(responseHeader) + 1 + nameLength + 1 + domainLength + 1 + sizeof(aRecord) + sizeof(nsecRecord); + uint8_t response[responseSize]; + uint8_t* r = response; + + // copy header + memcpy_P(r, responseHeader, sizeof(responseHeader)); + r += sizeof(responseHeader); + + // copy name + *r = nameLength; + memcpy(r + 1, name.c_str(), nameLength); + r += (1 + nameLength); + + // copy domain + *r = domainLength; + memcpy_P(r + 1, domain, domainLength); + r += (1 + domainLength); + + // terminator + *r = 0x00; + r++; + + // copy A record + memcpy_P(r, aRecord, sizeof(aRecord)); + memcpy(r + TTL_OFFSET, &ttl, sizeof(ttl)); // replace TTL value + memcpy(r + IP_OFFSET, &ipAddress, sizeof(ipAddress)); // replace IP address value + r += sizeof(aRecord); + + // copy NSEC record + memcpy_P(r, nsecRecord, sizeof(nsecRecord)); + r += sizeof(nsecRecord); + + udpSocket.beginPacket(IPAddress(224, 0, 0, 251), 5353); + udpSocket.write(response, responseSize); + udpSocket.endPacket(); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiMDNSResponder.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiMDNSResponder.h new file mode 100644 index 0000000..d7e3d43 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiMDNSResponder.h @@ -0,0 +1,51 @@ +// Port of CC3000 MDNS Responder to WINC1500. +// Author: Tony DiCola +// +// This MDNSResponder class implements just enough MDNS functionality to respond +// to name requests, for example 'foo.local'. This does not implement any other +// MDNS or Bonjour functionality like services, etc. +// +// Copyright (c) 2016 Adafruit Industries. All right reserved. +// +// 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 2.1 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 Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +#ifndef WIFIMDNSRESPONDER_H +#define WIFIMDNSRESPONDER_H + +#include "WiFi101.h" +#include "WiFiUdp.h" + +class WiFiMDNSResponder { +public: + WiFiMDNSResponder(); + ~WiFiMDNSResponder(); + bool begin(const char* _name, uint32_t _ttlSeconds = 3600); + void poll(); + +private: + bool parseRequest(); + void replyToRequest(); + +private: + String name; + uint32_t ttlSeconds; + + int minimumExpectedRequestLength; + + // UDP socket for receiving/sending MDNS data. + WiFiUDP udpSocket; +}; + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiSSLClient.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiSSLClient.cpp new file mode 100644 index 0000000..e7be43c --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiSSLClient.cpp @@ -0,0 +1,45 @@ +/* + WiFiSSLClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "WiFiSSLClient.h" + +WiFiSSLClient::WiFiSSLClient() : + WiFiClient() +{ +} + +WiFiSSLClient::WiFiSSLClient(uint8_t sock, uint8_t parentsock) : + WiFiClient(sock, parentsock) +{ +} + +WiFiSSLClient::WiFiSSLClient(const WiFiSSLClient& other) : + WiFiClient(other) +{ +} + +int WiFiSSLClient::connect(IPAddress ip, uint16_t port) +{ + return WiFiClient::connectSSL(ip, port); +} + +int WiFiSSLClient::connect(const char* host, uint16_t port) +{ + return WiFiClient::connectSSL(host, port); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiSSLClient.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiSSLClient.h new file mode 100644 index 0000000..c5851e5 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiSSLClient.h @@ -0,0 +1,36 @@ +/* + WiFiSSLClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef WIFISSLCLIENT_H +#define WIFISSLCLIENT_H + +#include "WiFiClient.h" + +class WiFiSSLClient : public WiFiClient { + +public: + WiFiSSLClient(); + WiFiSSLClient(uint8_t sock, uint8_t parentsock = 0); + WiFiSSLClient(const WiFiSSLClient& other); + + virtual int connect(IPAddress ip, uint16_t port); + virtual int connect(const char* host, uint16_t port); +}; + +#endif /* WIFISSLCLIENT_H */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiServer.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiServer.cpp new file mode 100644 index 0000000..5f330ba --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiServer.cpp @@ -0,0 +1,140 @@ +/* + WiFiClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +extern "C" { + #include "socket/include/socket.h" +} + +#include "WiFi101.h" +#include "WiFiClient.h" +#include "WiFiServer.h" + +#define READY (_flag & SOCKET_BUFFER_FLAG_BIND) + +WiFiServer::WiFiServer(uint16_t port) +{ + _port = port; + _flag = 0; +} + +void WiFiServer::begin() +{ + begin(0); +} + +uint8_t WiFiServer::beginSSL() +{ + return begin(SOCKET_FLAGS_SSL); +} + +uint8_t WiFiServer::begin(uint8_t opt) +{ + struct sockaddr_in addr; + + _flag = 0; + + // Initialize socket address structure. + addr.sin_family = AF_INET; + addr.sin_port = _htons(_port); + addr.sin_addr.s_addr = 0; + + // Open TCP server socket. + if ((_socket = socket(AF_INET, SOCK_STREAM, opt)) < 0) { + return 0; + } + + // Add socket buffer handler: + socketBufferRegister(_socket, &_flag, 0, 0, 0); + + // Bind socket: + if (bind(_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { + close(_socket); + _socket = -1; + return 0; + } + + // Wait for connection or timeout: + unsigned long start = millis(); + while (!READY && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + if (!READY) { + close(_socket); + _socket = -1; + return 0; + } + _flag &= ~SOCKET_BUFFER_FLAG_BIND; + + return 1; +} + +WiFiClient WiFiServer::available(uint8_t* status) +{ + uint32_t flag; + + m2m_wifi_handle_events(NULL); + if (_flag & SOCKET_BUFFER_FLAG_SPAWN) { + flag = _flag; + _flag &= ~SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK; + _flag &= ~SOCKET_BUFFER_FLAG_SPAWN; + if (status != NULL) { + *status = 0; + } + return WiFiClient(((flag & SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK) >> SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS), _socket + 1); + } else { + WiFiClient *client; + + for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { + client = WiFi._client[sock]; + if (client && client->_flag & SOCKET_BUFFER_FLAG_CONNECTED) { + if (((client->_flag >> SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS) & 0xff) == (uint8)(_socket + 1)) { + return *client; + } + } + } + } + + return WiFiClient(); +} + +uint8_t WiFiServer::status() { + // Deprecated. + return 0; +} + +size_t WiFiServer::write(uint8_t b) +{ + return write(&b, 1); +} + +size_t WiFiServer::write(const uint8_t *buffer, size_t size) +{ + size_t n = 0; + WiFiClient *client; + + for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { + client = WiFi._client[sock]; + if (client && client->_flag & SOCKET_BUFFER_FLAG_CONNECTED) { + if (((client->_flag >> SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS) & 0xff) == (uint8)(_socket + 1)) { + n += client->write(buffer, size); + } + } + } + return n; +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiServer.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiServer.h new file mode 100644 index 0000000..d658b2f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiServer.h @@ -0,0 +1,49 @@ +/* + WiFiClient.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef WIFISERVER_H +#define WIFISERVER_H + +#include +#include + +class WiFiClient; + +class WiFiServer : public Server { + +private: + SOCKET _socket; + uint32_t _flag; + uint16_t _port; + uint8_t begin(uint8_t opt); + +public: + WiFiServer(uint16_t); + WiFiClient available(uint8_t* status = NULL); + void begin(); + uint8_t beginSSL(); + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + uint8_t status(); + + using Print::write; + +}; + +#endif /* WIFISERVER_H */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiUdp.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiUdp.cpp new file mode 100644 index 0000000..e55c965 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiUdp.cpp @@ -0,0 +1,289 @@ +/* + WiFiUdp.cpp - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +extern "C" { + #include "socket/include/socket.h" + #include "driver/include/m2m_periph.h" + extern uint8 hif_small_xfer; +} + +#include +#include "WiFi101.h" +#include "WiFiUdp.h" +#include "WiFiClient.h" +#include "WiFiServer.h" + +#define READY (_flag & SOCKET_BUFFER_FLAG_BIND) + +/* Constructor. */ +WiFiUDP::WiFiUDP() +{ + _socket = -1; + _flag = 0; + _head = 0; + _tail = 0; + _rcvSize = 0; + _rcvPort = 0; + _rcvIP = 0; + _sndSize = 0; +} + +/* Start WiFiUDP socket, listening at local port PORT */ +uint8_t WiFiUDP::begin(uint16_t port) +{ + struct sockaddr_in addr; + uint32 u32EnableCallbacks = 0; + + _flag = 0; + _head = 0; + _tail = 0; + _rcvSize = 0; + _rcvPort = 0; + _rcvIP = 0; + _sndSize = 0; + + // Initialize socket address structure. + addr.sin_family = AF_INET; + addr.sin_port = _htons(port); + addr.sin_addr.s_addr = 0; + + // Open TCP server socket. + if ((_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { + return 0; + } + + // Add socket buffer handler: + socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_recvBuffer); + setsockopt(_socket, SOL_SOCKET, SO_SET_UDP_SEND_CALLBACK, &u32EnableCallbacks, 0); + + // Bind socket: + if (bind(_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { + close(_socket); + _socket = -1; + return 0; + } + + // Wait for connection or timeout: + unsigned long start = millis(); + while (!READY && millis() - start < 2000) { + m2m_wifi_handle_events(NULL); + } + if (!READY) { + close(_socket); + _socket = -1; + return 0; + } + _flag &= ~SOCKET_BUFFER_FLAG_BIND; + + return 1; +} + +uint8_t WiFiUDP::beginMulticast(IPAddress ip, uint16_t port) +{ + uint32_t multiIp = ip; + + if (!begin(port)) { + return 0; + } + + setsockopt(_socket, SOL_SOCKET, IP_ADD_MEMBERSHIP, &multiIp, sizeof(multiIp)); + + return 1; +} + +/* return number of bytes available in the current packet, + will return zero if parsePacket hasn't been called yet */ +int WiFiUDP::available() +{ + m2m_wifi_handle_events(NULL); + + if (_socket != -1) { + return _rcvSize; + } + return 0; + } + +/* Release any resources being used by this WiFiUDP instance */ +void WiFiUDP::stop() +{ + if (_socket < 0) + return; + + socketBufferUnregister(_socket); + close(_socket); + _socket = -1; +} + +int WiFiUDP::beginPacket(const char *host, uint16_t port) +{ + IPAddress ip; + if (WiFi.hostByName(host, ip)) { + return beginPacket(ip, port); + } + + return 0; +} + +int WiFiUDP::beginPacket(IPAddress ip, uint16_t port) +{ + _sndIP = ip; + _sndPort = port; + _sndSize = 0; + + return 1; +} + +int WiFiUDP::endPacket() +{ + struct sockaddr_in addr; + + // Network led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); + + addr.sin_family = AF_INET; + addr.sin_port = _htons(_sndPort); + addr.sin_addr.s_addr = _sndIP; + + if (sendto(_socket, (void *)_sndBuffer, _sndSize, 0, + (struct sockaddr *)&addr, sizeof(addr)) < 0) { + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + return 0; + } + + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + + return 1; +} + +size_t WiFiUDP::write(uint8_t byte) +{ + return write(&byte, 1); +} + +size_t WiFiUDP::write(const uint8_t *buffer, size_t size) +{ + if ((size + _sndSize) > sizeof(_sndBuffer)) { + size = sizeof(_sndBuffer) - _sndSize; + } + + memcpy(_sndBuffer + _sndSize, buffer, size); + + _sndSize += size; + + return size; +} + +int WiFiUDP::parsePacket() +{ + m2m_wifi_handle_events(NULL); + + if (_socket != -1) { + if (_rcvSize != 0) { + return _rcvSize; + } + if (_head != _tail) { + _rcvSize = ((uint16_t)_recvBuffer[_tail] << 8) + (uint16_t)_recvBuffer[_tail + 1]; + _rcvPort = ((uint16_t)_recvBuffer[_tail + 2] << 8) + (uint16_t)_recvBuffer[_tail + 3]; + _rcvIP = ((uint32_t)_recvBuffer[_tail + 4] << 24) + ((uint32_t)_recvBuffer[_tail + 5] << 16) + + ((uint32_t)_recvBuffer[_tail + 6] << 8) + (uint32_t)_recvBuffer[_tail + 7]; + _tail += SOCKET_BUFFER_UDP_HEADER_SIZE; + return _rcvSize; + } + } + return 0; +} + +int WiFiUDP::read() +{ + uint8_t b; + + if (read(&b, sizeof(b)) == -1) { + return -1; + } + + return b; +} + +int WiFiUDP::read(unsigned char* buf, size_t size) +{ + // sizeof(size_t) is architecture dependent + // but we need a 16 bit data type here + uint16_t size_tmp = available(); + + if (size_tmp == 0) { + return -1; + } + + if (size < size_tmp) { + size_tmp = size; + } + + for (uint32_t i = 0; i < size_tmp; ++i) { + buf[i] = _recvBuffer[_tail++]; + _rcvSize--; + + if (_tail == _head) { + // the full buffered data has been read, reset head and tail for next transfer + _tail = _head = 0; + + // clear the buffer full flag + _flag &= ~SOCKET_BUFFER_FLAG_FULL; + + // setup buffer and buffer size to transfer the remainder of the current packet + // or next received packet + if (hif_small_xfer) { + recvfrom(_socket, _recvBuffer, SOCKET_BUFFER_MTU, 0); + } else { + recvfrom(_socket, _recvBuffer + SOCKET_BUFFER_UDP_HEADER_SIZE, SOCKET_BUFFER_MTU, 0); + } + m2m_wifi_handle_events(NULL); + } + } + + return size_tmp; +} + +int WiFiUDP::peek() +{ + if (!available()) + return -1; + + return _recvBuffer[_tail]; +} + +void WiFiUDP::flush() +{ + while (available()) + read(); +} + +IPAddress WiFiUDP::remoteIP() +{ + return _rcvIP; +} + +uint16_t WiFiUDP::remotePort() +{ + return _rcvPort; +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiUdp.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiUdp.h new file mode 100644 index 0000000..d961682 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiUdp.h @@ -0,0 +1,89 @@ +/* + WiFiUdp.h - Library for Arduino Wifi shield. + Copyright (c) 2011-2014 Arduino. All right reserved. + + 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 2.1 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 Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef WIFIUDP_H +#define WIFIUDP_H + +#include + +class WiFiUDP : public UDP { +private: + SOCKET _socket; + uint32_t _flag; + uint32_t _head; + uint32_t _tail; + uint8_t _recvBuffer[SOCKET_BUFFER_UDP_SIZE]; + uint16_t _rcvSize; + uint16_t _rcvPort; + uint32_t _rcvIP; + uint8_t _sndBuffer[SOCKET_BUFFER_UDP_SIZE]; + uint16_t _sndSize; + uint16_t _sndPort; + uint32_t _sndIP; + +public: + WiFiUDP(); // Constructor + virtual uint8_t begin(uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use + virtual uint8_t beginMulticast(IPAddress, uint16_t); // initialize, start listening on specified multicast IP address and port. Returns 1 if successful, 0 if there are no sockets available to use + virtual uint8_t beginMulti(IPAddress ip, uint16_t port) { return beginMulticast(ip, port); } + virtual void stop(); // Finish with the UDP socket + + // Sending UDP packets + + // Start building up a packet to send to the remote host specific in ip and port + // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port + virtual int beginPacket(IPAddress ip, uint16_t port); + // Start building up a packet to send to the remote host specific in host and port + // Returns 1 if successful, 0 if there was a problem resolving the hostname or port + virtual int beginPacket(const char *host, uint16_t port); + // Finish off this packet and send it + // Returns 1 if the packet was sent successfully, 0 if there was an error + virtual int endPacket(); + // Write a single byte into the packet + virtual size_t write(uint8_t); + // Write size bytes from buffer into the packet + virtual size_t write(const uint8_t *buffer, size_t size); + + using Print::write; + + // Start processing the next available incoming packet + // Returns the size of the packet in bytes, or 0 if no packets are available + virtual int parsePacket(); + // Number of bytes remaining in the current packet + virtual int available(); + // Read a single byte from the current packet + virtual int read(); + // Read up to len bytes from the current packet and place them into buffer + // Returns the number of bytes read, or 0 if none are available + virtual int read(unsigned char* buffer, size_t len); + // Read up to len characters from the current packet and place them into buffer + // Returns the number of characters read, or 0 if none are available + virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; + // Return the next byte from the current packet without moving on to the next byte + virtual int peek(); + virtual void flush(); // Finish reading the current packet + + // Return the IP address of the host who sent the current incoming packet + virtual IPAddress remoteIP(); + // Return the port of the host who sent the current incoming packet + virtual uint16_t remotePort(); + +}; + +#endif /* WIFIUDP_H */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp.h new file mode 100644 index 0000000..5527bab --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp.h @@ -0,0 +1,283 @@ +/** + * + * \file + * + * \brief WINC BSP API Declarations. + * + * Copyright (c) 2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/** \defgroup nm_bsp BSP + */ +/**@defgroup BSPDefine Defines + * @ingroup nm_bsp + * @{ + */ +#ifndef _NM_BSP_H_ +#define _NM_BSP_H_ + +#define NMI_API +/*!< +* Attribute used to define memory section to map Functions in host memory. +*/ +#define CONST const + +/*!< +* Used for code portability. +*/ + +/*! + * @typedef void (*tpfNmBspIsr) (void); + * @brief Pointer to function.\n + * Used as a data type of ISR function registered by \ref nm_bsp_register_isr + * @return None + */ +typedef void (*tpfNmBspIsr)(void); + + + +#ifndef NULL +#define NULL ((void*)0) +#endif +/*!< +* Void Pointer to '0' in case of NULL is not defined. +*/ + + +#define BSP_MIN(x,y) ((x)>(y)?(y):(x)) +/*!< +* Computes the minimum of \b x and \b y. +*/ + + //@} + +/**@defgroup DataT DataTypes + * @ingroup nm_bsp + * @{ + */ + + /*! + * @ingroup DataTypes + * @typedef unsigned char uint8; + * @brief Range of values between 0 to 255 + */ +typedef unsigned char uint8; + + /*! + * @ingroup DataTypes + * @typedef unsigned short uint16; + * @brief Range of values between 0 to 65535 + */ +typedef unsigned short uint16; + + /*! + * @ingroup Data Types + * @typedef unsigned long uint32; + * @brief Range of values between 0 to 4294967295 + */ +typedef unsigned long uint32; + + + /*! + * @ingroup Data Types + * @typedef signed char sint8; + * @brief Range of values between -128 to 127 + */ +typedef signed char sint8; + + /*! + * @ingroup DataTypes + * @typedef signed short sint16; + * @brief Range of values between -32768 to 32767 + */ +typedef signed short sint16; + + /*! + * @ingroup DataTypes + * @typedef signed long sint32; + * @brief Range of values between -2147483648 to 2147483647 + */ + +typedef signed long sint32; + //@} + +#ifndef CORTUS_APP + + +#ifdef __cplusplus +extern "C"{ +#endif + +/** \defgroup BSPAPI Function + * @ingroup nm_bsp + */ + + +/** @defgroup NmBspInitFn nm_bsp_init + * @ingroup BSPAPI + * Initialization for BSP such as Reset and Chip Enable Pins for WINC, delays, register ISR, enable/disable IRQ for WINC, ...etc. You must use this function in the head of your application to + * enable WINC and Host Driver communicate each other. + */ + /**@{*/ +/*! + * @fn sint8 nm_bsp_init(void); + * @note Implementation of this function is host dependent. + * @warning Missing use will lead to unavailability of host communication.\n + * + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + + */ +sint8 nm_bsp_init(void); + /**@}*/ + + + /** @defgroup NmBspDeinitFn nm_bsp_deinit + * @ingroup BSPAPI + * De-initialization for BSP (\e Board \e Support \e Package) + */ + /**@{*/ +/*! + * @fn sint8 nm_bsp_deinit(void); + * @pre Initialize \ref nm_bsp_init first + * @note Implementation of this function is host dependent. + * @warning Missing use may lead to unknown behavior in case of soft reset.\n + * @see nm_bsp_init + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + + */ +sint8 nm_bsp_deinit(void); + /**@}*/ + + +/** @defgroup NmBspResetFn nm_bsp_reset +* @ingroup BSPAPI +* Resetting NMC1500 SoC by setting CHIP_EN and RESET_N signals low, then after specific delay the function will put CHIP_EN high then RESET_N high, +* for the timing between signals please review the WINC data-sheet +*/ +/**@{*/ + /*! + * @fn void nm_bsp_reset(void); + * @param [in] None + * @pre Initialize \ref nm_bsp_init first + * @note Implementation of this function is host dependent and called by HIF layer. + * @see nm_bsp_init + * @return None + + */ +void nm_bsp_reset(void); + /**@}*/ + + +/** @defgroup NmBspSleepFn nm_bsp_sleep +* @ingroup BSPAPI +* Sleep in units of milliseconds.\n +* This function used by HIF Layer according to different situations. +*/ +/**@{*/ +/*! + * @fn void nm_bsp_sleep(uint32); + * @brief + * @param [in] u32TimeMsec + * Time unit in milliseconds + * @pre Initialize \ref nm_bsp_init first + * @warning Maximum value must nor exceed 4294967295 milliseconds which is equal to 4294967.295 seconds.\n + * @note Implementation of this function is host dependent. + * @see nm_bsp_init + * @return None + */ +void nm_bsp_sleep(uint32 u32TimeMsec); +/**@}*/ + + +/** @defgroup NmBspRegisterFn nm_bsp_register_isr +* @ingroup BSPAPI +* Register ISR (Interrupt Service Routine) in the initialization of HIF (Host Interface) Layer. +* When the interrupt trigger the BSP layer should call the pfisr function once inside the interrupt. +*/ +/**@{*/ +/*! + * @fn void nm_bsp_register_isr(tpfNmBspIsr); + * @param [in] tpfNmBspIsr pfIsr + * Pointer to ISR handler in HIF + * @warning Make sure that ISR for IRQ pin for WINC is disabled by default in your implementation. + * @note Implementation of this function is host dependent and called by HIF layer. + * @see tpfNmBspIsr + * @return None + + */ +void nm_bsp_register_isr(tpfNmBspIsr pfIsr); +/**@}*/ + + +/** @defgroup NmBspInterruptCtrl nm_bsp_interrupt_ctrl +* @ingroup BSPAPI +* Synchronous enable/disable interrupts function +*/ +/**@{*/ +/*! + * @fn void nm_bsp_interrupt_ctrl(uint8); + * @brief Enable/Disable interrupts + * @param [in] u8Enable + * '0' disable interrupts. '1' enable interrupts + * @see tpfNmBspIsr + * @note Implementation of this function is host dependent and called by HIF layer. + * @return None + + */ +void nm_bsp_interrupt_ctrl(uint8 u8Enable); + /**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif + +#ifdef _NM_BSP_BIG_END +#define NM_BSP_B_L_32(x) \ +((((x) & 0x000000FF) << 24) + \ +(((x) & 0x0000FF00) << 8) + \ +(((x) & 0x00FF0000) >> 8) + \ +(((x) & 0xFF000000) >> 24)) +#define NM_BSP_B_L_16(x) \ +((((x) & 0x00FF) << 8) + \ +(((x) & 0xFF00) >> 8)) +#else +#define NM_BSP_B_L_32(x) (x) +#define NM_BSP_B_L_16(x) (x) +#endif + + +#endif /*_NM_BSP_H_*/ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h new file mode 100644 index 0000000..77417e8 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h @@ -0,0 +1,74 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 BSP APIs definitions. + * + * Copyright (c) 2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NM_BSP_ARDUINO_H_ +#define _NM_BSP_ARDUINO_H_ + +#include + +#include + +/* + * Arduino variants may redefine those pins. + * If no pins are specified the following defaults are used: + * WINC1501_RESET_PIN - pin 5 + * WINC1501_INTN_PIN - pin 7 + * WINC1501_CHIP_EN_PIN - not connected (tied to VCC) + */ +#if !defined(WINC1501_RESET_PIN) + #define WINC1501_RESET_PIN 5 +#endif +#if !defined(WINC1501_INTN_PIN) + #define WINC1501_INTN_PIN 7 +#endif +#if !defined(WINC1501_SPI_CS_PIN) + #define WINC1501_SPI_CS_PIN 10 +#endif +#if !defined(WINC1501_CHIP_EN_PIN) + #define WINC1501_CHIP_EN_PIN -1 +#endif + +extern int8_t gi8Winc1501CsPin; +extern int8_t gi8Winc1501ResetPin; +extern int8_t gi8Winc1501IntnPin; +extern int8_t gi8Winc1501ChipEnPin; + +#endif /* _NM_BSP_ARDUINO_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h new file mode 100644 index 0000000..c5991f2 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h @@ -0,0 +1,54 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 BSP APIs definitions. + * + * Copyright (c) 2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NM_BSP_AVR_H_ +#define _NM_BSP_AVR_H_ + +#pragma once + +#define NM_DEBUG 0 +#define NM_BSP_PRINTF + +#define CONF_WINC_USE_SPI 1 + +#define NM_EDGE_INTERRUPT 1 + +#endif /* _NM_BSP_AVR_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h new file mode 100644 index 0000000..45d3ff2 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h @@ -0,0 +1,59 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 BSP APIs declarations. + * + * Copyright (c) 2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +/**@defgroup BSPDefine Defines + * @ingroup nm_bsp + * @{ + */ +#ifndef _NM_BSP_INTERNAL_H_ +#define _NM_BSP_INTERNAL_H_ + +#ifdef ARDUINO_ARCH_AVR +#define LIMITED_RAM_DEVICE +#include "bsp/include/nm_bsp_avr.h" +#else +#include "bsp/include/nm_bsp_samd21.h" +#endif + +#ifdef ARDUINO +#define CONF_PERIPH +#endif + +#endif //_NM_BSP_INTERNAL_H_ \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h new file mode 100644 index 0000000..296cd20 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h @@ -0,0 +1,52 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 BSP APIs definitions. + * + * Copyright (c) 2015 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NM_BSP_SAMD21_H_ +#define _NM_BSP_SAMD21_H_ + +#define NM_DEBUG 0 +#define NM_BSP_PRINTF + +#define CONF_WINC_USE_SPI 1 + +#define NM_EDGE_INTERRUPT 1 + +#endif /* _NM_BSP_SAMD21_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c new file mode 100644 index 0000000..e27be14 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c @@ -0,0 +1,205 @@ +/** + * + * \file + * + * \brief This module contains SAMD21 BSP APIs implementation. + * + * Copyright (c) 2014 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "bsp/include/nm_bsp.h" +#include "bsp/include/nm_bsp_arduino.h" +#include "common/include/nm_common.h" + +int8_t gi8Winc1501CsPin = WINC1501_SPI_CS_PIN; +int8_t gi8Winc1501ResetPin = WINC1501_RESET_PIN; +int8_t gi8Winc1501IntnPin = WINC1501_INTN_PIN; +int8_t gi8Winc1501ChipEnPin = WINC1501_CHIP_EN_PIN; + +static tpfNmBspIsr gpfIsr; + +void __attribute__((weak)) attachInterruptMultiArch(uint32_t pin, void *chip_isr, uint32_t mode) +{ + attachInterrupt(pin, chip_isr, mode); +} + +void __attribute__((weak)) detachInterruptMultiArch(uint32_t pin) +{ + detachInterrupt(pin); +} + +static void chip_isr(void) +{ + if (gpfIsr) { + gpfIsr(); + } +} + +/* + * @fn init_chip_pins + * @brief Initialize reset, chip enable and wake pin + * @author M.S.M + * @date 11 July 2012 + * @version 1.0 + */ +static void init_chip_pins(void) +{ + /* Configure RESETN pin as output. */ + pinMode(gi8Winc1501ResetPin, OUTPUT); + digitalWrite(gi8Winc1501ResetPin, HIGH); + + /* Configure INTN pins as input. */ + pinMode(gi8Winc1501IntnPin, INPUT); + + if (gi8Winc1501ChipEnPin > -1) + { + /* Configure CHIP_EN as pull-up */ + pinMode(gi8Winc1501ChipEnPin, INPUT_PULLUP); + } +} + +static void deinit_chip_pins(void) +{ + digitalWrite(gi8Winc1501ResetPin, LOW); + pinMode(gi8Winc1501ResetPin, INPUT); + + if (gi8Winc1501ChipEnPin > -1) + { + pinMode(gi8Winc1501ChipEnPin, INPUT); + } +} + +/* + * @fn nm_bsp_init + * @brief Initialize BSP + * @return 0 in case of success and -1 in case of failure + * @author M.S.M + * @date 11 July 2012 + * @version 1.0 + */ +sint8 nm_bsp_init(void) +{ + gpfIsr = NULL; + + init_chip_pins(); + + nm_bsp_reset(); + + return M2M_SUCCESS; +} + +/** + * @fn nm_bsp_deinit + * @brief De-iInitialize BSP + * @return 0 in case of success and -1 in case of failure + * @author M. Abdelmawla + * @date 11 July 2012 + * @version 1.0 + */ +sint8 nm_bsp_deinit(void) +{ + deinit_chip_pins(); + + return M2M_SUCCESS; +} + +/** + * @fn nm_bsp_reset + * @brief Reset NMC1500 SoC by setting CHIP_EN and RESET_N signals low, + * CHIP_EN high then RESET_N high + * @author M. Abdelmawla + * @date 11 July 2012 + * @version 1.0 + */ +void nm_bsp_reset(void) +{ + digitalWrite(gi8Winc1501ResetPin, LOW); + nm_bsp_sleep(100); + digitalWrite(gi8Winc1501ResetPin, HIGH); + nm_bsp_sleep(100); +} + +/* + * @fn nm_bsp_sleep + * @brief Sleep in units of mSec + * @param[IN] u32TimeMsec + * Time in milliseconds + * @author M.S.M + * @date 28 OCT 2013 + * @version 1.0 + */ +void nm_bsp_sleep(uint32 u32TimeMsec) +{ + while (u32TimeMsec--) { + delay(1); + } +} + +/* + * @fn nm_bsp_register_isr + * @brief Register interrupt service routine + * @param[IN] pfIsr + * Pointer to ISR handler + * @author M.S.M + * @date 28 OCT 2013 + * @sa tpfNmBspIsr + * @version 1.0 + */ +void nm_bsp_register_isr(tpfNmBspIsr pfIsr) +{ + gpfIsr = pfIsr; + attachInterruptMultiArch(gi8Winc1501IntnPin, chip_isr, FALLING); +} + +/* + * @fn nm_bsp_interrupt_ctrl + * @brief Enable/Disable interrupts + * @param[IN] u8Enable + * '0' disable interrupts. '1' enable interrupts + * @author M.S.M + * @date 28 OCT 2013 + * @version 1.0 + */ +void nm_bsp_interrupt_ctrl(uint8 u8Enable) +{ + if (u8Enable) { + attachInterruptMultiArch(gi8Winc1501IntnPin, chip_isr, FALLING); + } else { + detachInterruptMultiArch(gi8Winc1501IntnPin); + } +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c new file mode 100644 index 0000000..050d5d5 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c @@ -0,0 +1,164 @@ +/** + * + * \file + * + * \brief This module contains SAMD21 BSP APIs implementation. + * + * Copyright (c) 2014 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifdef ARDUINO_ARCH_AVR + +#include "bsp/include/nm_bsp.h" +#include "bsp/include/nm_bsp_arduino.h" +#include "common/include/nm_common.h" + +#define IS_MEGA (defined(ARDUINO_AVR_MEGA) || defined(ARDUINO_AVR_MEGA2560)) + +static tpfNmBspIsr gpfIsr; + +volatile uint8_t *_receivePortRegister; +volatile uint8_t *_pcint_maskreg; +uint8_t _receiveBitMask; +volatile uint8_t prev_pin_read = 1; + +uint8_t rx_pin_read() +{ + return *_receivePortRegister & _receiveBitMask; +} + +#if !IS_MEGA + +#if defined(PCINT0_vect) +ISR(PCINT0_vect) +{ + if (!rx_pin_read() && gpfIsr) + { + gpfIsr(); + } +} +#endif + +#if defined(PCINT1_vect) +ISR(PCINT1_vect, ISR_ALIASOF(PCINT0_vect)); +#endif + +#if defined(PCINT2_vect) +ISR(PCINT2_vect, ISR_ALIASOF(PCINT0_vect)); +#endif + +#if defined(PCINT3_vect) +ISR(PCINT3_vect, ISR_ALIASOF(PCINT0_vect)); +#endif + +#endif // !IS_MEGA + +#if defined(TIMER4_OVF_vect) +ISR(TIMER4_OVF_vect) { + uint8_t curr_pin_read = rx_pin_read(); + if ((curr_pin_read != prev_pin_read) && !curr_pin_read && gpfIsr) + { + gpfIsr(); + } + prev_pin_read = curr_pin_read; +} + +// stategy 3 - start a timer and perform a sort of polling +void attachFakeInterruptToTimer(void) { + TCCR4B = (1< I2C/UART. Parameter:tstrNmI2cDefault/tstrNmUartDefault */ +#define NM_BUS_IOCTL_W ((uint8)1) /*!< Write only ==> I2C/UART. Parameter type tstrNmI2cDefault/tstrNmUartDefault*/ +#define NM_BUS_IOCTL_W_SPECIAL ((uint8)2) /*!< Write two buffers within the same transaction + (same start/stop conditions) ==> I2C only. Parameter:tstrNmI2cSpecial */ +#define NM_BUS_IOCTL_RW ((uint8)3) /*!< Read/Write at the same time ==> SPI only. Parameter:tstrNmSpiRw */ + +#define NM_BUS_IOCTL_WR_RESTART ((uint8)4) /*!< Write buffer then made restart condition then read ==> I2C only. parameter:tstrNmI2cSpecial */ +/** +* @struct tstrNmBusCapabilities +* @brief Structure holding bus capabilities information +* @sa NM_BUS_TYPE_I2C, NM_BUS_TYPE_SPI +*/ +typedef struct +{ + uint16 u16MaxTrxSz; /*!< Maximum transfer size. Must be >= 16 bytes*/ +} tstrNmBusCapabilities; + +/** +* @struct tstrNmI2cDefault +* @brief Structure holding I2C default operation parameters +* @sa NM_BUS_IOCTL_R, NM_BUS_IOCTL_W +*/ +typedef struct +{ + uint8 u8SlaveAdr; + uint8 *pu8Buf; /*!< Operation buffer */ + uint16 u16Sz; /*!< Operation size */ +} tstrNmI2cDefault; + +/** +* @struct tstrNmI2cSpecial +* @brief Structure holding I2C special operation parameters +* @sa NM_BUS_IOCTL_W_SPECIAL +*/ +typedef struct +{ + uint8 u8SlaveAdr; + uint8 *pu8Buf1; /*!< pointer to the 1st buffer */ + uint8 *pu8Buf2; /*!< pointer to the 2nd buffer */ + uint16 u16Sz1; /*!< 1st buffer size */ + uint16 u16Sz2; /*!< 2nd buffer size */ +} tstrNmI2cSpecial; + +/** +* @struct tstrNmSpiRw +* @brief Structure holding SPI R/W parameters +* @sa NM_BUS_IOCTL_RW +*/ +typedef struct +{ + uint8 *pu8InBuf; /*!< pointer to input buffer. + Can be set to null and in this case zeros should be sent at MOSI */ + uint8 *pu8OutBuf; /*!< pointer to output buffer. + Can be set to null and in this case data from MISO can be ignored */ + uint16 u16Sz; /*!< Transfere size */ +} tstrNmSpiRw; + + +/** +* @struct tstrNmUartDefault +* @brief Structure holding UART default operation parameters +* @sa NM_BUS_IOCTL_R, NM_BUS_IOCTL_W +*/ +typedef struct +{ + uint8 *pu8Buf; /*!< Operation buffer */ + uint16 u16Sz; /*!< Operation size */ +} tstrNmUartDefault; +/*!< Bus capabilities. This structure must be declared at platform specific bus wrapper */ +extern tstrNmBusCapabilities egstrNmBusCapabilities; + + +#ifdef __cplusplus + extern "C" { + #endif +/** +* @fn nm_bus_init +* @brief Initialize the bus wrapper +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_bus_init(void *); + +/** +* @fn nm_bus_ioctl +* @brief send/receive from the bus +* @param [in] u8Cmd +* IOCTL command for the operation +* @param [in] pvParameter +* Arbitrary parameter depending on IOCTL +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +* @note For SPI only, it's important to be able to send/receive at the same time +*/ +sint8 nm_bus_ioctl(uint8 u8Cmd, void* pvParameter); + +/** +* @fn nm_bus_deinit +* @brief De-initialize the bus wrapper +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_bus_deinit(void); + +/* +* @fn nm_bus_reinit +* @brief re-initialize the bus wrapper +* @param [in] void *config +* re-init configuration data +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_bus_reinit(void *); +/* +* @fn nm_bus_get_chip_type +* @brief get chip type +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +#ifdef CONF_WINC_USE_UART +uint8 nm_bus_get_chip_type(void); +#endif +#ifdef __cplusplus + } + #endif + +#endif /*_NM_BUS_WRAPPER_H_*/ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp new file mode 100644 index 0000000..22a7473 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp @@ -0,0 +1,200 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 bus wrapper APIs implementation. + * + * Copyright (c) 2014 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include +#include + +/* + * Variants may define an alternative SPI instace to use for WiFi101. + * If not defined the following defaults are used: + * WINC1501_SPI - SPI + */ +#if !defined(WINC1501_SPI) + #define WINC1501_SPI SPI +#endif + +extern "C" { + +#include "bsp/include/nm_bsp.h" +#include "bsp/include/nm_bsp_arduino.h" +#include "common/include/nm_common.h" +#include "bus_wrapper/include/nm_bus_wrapper.h" + +} + +#define NM_BUS_MAX_TRX_SZ 256 + +tstrNmBusCapabilities egstrNmBusCapabilities = +{ + NM_BUS_MAX_TRX_SZ +}; + +static const SPISettings wifi_SPISettings(12000000L, MSBFIRST, SPI_MODE0); + +static sint8 spi_rw(uint8* pu8Mosi, uint8* pu8Miso, uint16 u16Sz) +{ + uint8 u8Dummy = 0; + uint8 u8SkipMosi = 0, u8SkipMiso = 0; + + if (!pu8Mosi) { + pu8Mosi = &u8Dummy; + u8SkipMosi = 1; + } + else if(!pu8Miso) { + pu8Miso = &u8Dummy; + u8SkipMiso = 1; + } + else { + return M2M_ERR_BUS_FAIL; + } + + WINC1501_SPI.beginTransaction(wifi_SPISettings); + digitalWrite(gi8Winc1501CsPin, LOW); + + while (u16Sz) { + *pu8Miso = WINC1501_SPI.transfer(*pu8Mosi); + + u16Sz--; + if (!u8SkipMiso) + pu8Miso++; + if (!u8SkipMosi) + pu8Mosi++; + } + + digitalWrite(gi8Winc1501CsPin, HIGH); + WINC1501_SPI.endTransaction(); + + return M2M_SUCCESS; +} + +extern "C" { + +/* +* @fn nm_bus_init +* @brief Initialize the bus wrapper +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M.S.M +* @date 28 oct 2013 +* @version 1.0 +*/ +sint8 nm_bus_init(void * /* pvInitValue */) +{ + sint8 result = M2M_SUCCESS; + + /* Configure SPI peripheral. */ + WINC1501_SPI.begin(); + + /* Configure CS PIN. */ + pinMode(gi8Winc1501CsPin, OUTPUT); + digitalWrite(gi8Winc1501CsPin, HIGH); + + /* Reset WINC1500. */ + nm_bsp_reset(); + nm_bsp_sleep(1); + + return result; +} + +/* +* @fn nm_bus_ioctl +* @brief send/receive from the bus +* @param[IN] u8Cmd +* IOCTL command for the operation +* @param[IN] pvParameter +* Arbitrary parameter depenging on IOCTL +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M.S.M +* @date 28 oct 2013 +* @note For SPI only, it's important to be able to send/receive at the same time +* @version 1.0 +*/ +sint8 nm_bus_ioctl(uint8 u8Cmd, void* pvParameter) +{ + sint8 s8Ret = 0; + switch(u8Cmd) + { + case NM_BUS_IOCTL_RW: { + tstrNmSpiRw *pstrParam = (tstrNmSpiRw *)pvParameter; + s8Ret = spi_rw(pstrParam->pu8InBuf, pstrParam->pu8OutBuf, pstrParam->u16Sz); + } + break; + default: + s8Ret = -1; + M2M_ERR("invalide ioclt cmd\n"); + break; + } + + return s8Ret; +} + +/* +* @fn nm_bus_deinit +* @brief De-initialize the bus wrapper +* @author M.S.M +* @date 28 oct 2013 +* @version 1.0 +*/ +sint8 nm_bus_deinit(void) +{ + WINC1501_SPI.end(); + return 0; +} + +/* +* @fn nm_bus_reinit +* @brief re-initialize the bus wrapper +* @param [in] void *config +* re-init configuration data +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Dina El Sissy +* @date 19 Sept 2012 +* @version 1.0 +*/ +sint8 nm_bus_reinit(void* /* config */) +{ + return M2M_SUCCESS; +} + +} // extern "C" + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/include/nm_common.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/include/nm_common.h new file mode 100644 index 0000000..d66fbdb --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/include/nm_common.h @@ -0,0 +1,153 @@ +/** + * + * \file + * + * \brief WINC Driver Common API Declarations. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NM_COMMON_H_ +#define _NM_COMMON_H_ + +#include "bsp/include/nm_bsp.h" +#include "common/include/nm_debug.h" + +/**@defgroup CommonDefines CommonDefines + * @ingroup WlanDefines + */ +/**@{*/ +#define M2M_TIME_OUT_DELAY 10000 + +/*states*/ +#define M2M_SUCCESS ((sint8)0) +#define M2M_ERR_SEND ((sint8)-1) +#define M2M_ERR_RCV ((sint8)-2) +#define M2M_ERR_MEM_ALLOC ((sint8)-3) +#define M2M_ERR_TIME_OUT ((sint8)-4) +#define M2M_ERR_INIT ((sint8)-5) +#define M2M_ERR_BUS_FAIL ((sint8)-6) +#define M2M_NOT_YET ((sint8)-7) +#define M2M_ERR_FIRMWARE ((sint8)-8) +#define M2M_SPI_FAIL ((sint8)-9) +#define M2M_ERR_FIRMWARE_bURN ((sint8)-10) +#define M2M_ACK ((sint8)-11) +#define M2M_ERR_FAIL ((sint8)-12) +#define M2M_ERR_FW_VER_MISMATCH ((sint8)-13) +#define M2M_ERR_SCAN_IN_PROGRESS ((sint8)-14) +#define M2M_ERR_INVALID_ARG ((sint8)-15) +#define M2M_ERR_INVALID ((sint8)-16) + +/*i2c MAASTER ERR*/ +#define I2C_ERR_LARGE_ADDRESS 0xE1UL /*the address exceed the max addressing mode in i2c flash*/ +#define I2C_ERR_TX_ABRT 0xE2UL /*NO ACK from slave*/ +#define I2C_ERR_OVER_SIZE 0xE3UL /**/ +#define ERR_PREFIX_NMIS 0xE4UL /*wrong first four byte in flash NMIS*/ +#define ERR_FIRMEWARE_EXCEED_SIZE 0xE5UL /*Total size of firmware exceed the max size 256k*/ +/**/ +#define PROGRAM_START 0x26961735UL +#define BOOT_SUCCESS 0x10add09eUL +#define BOOT_START 0x12345678UL + + +#define NBIT31 (0x80000000) +#define NBIT30 (0x40000000) +#define NBIT29 (0x20000000) +#define NBIT28 (0x10000000) +#define NBIT27 (0x08000000) +#define NBIT26 (0x04000000) +#define NBIT25 (0x02000000) +#define NBIT24 (0x01000000) +#define NBIT23 (0x00800000) +#define NBIT22 (0x00400000) +#define NBIT21 (0x00200000) +#define NBIT20 (0x00100000) +#define NBIT19 (0x00080000) +#define NBIT18 (0x00040000) +#define NBIT17 (0x00020000) +#define NBIT16 (0x00010000) +#define NBIT15 (0x00008000) +#define NBIT14 (0x00004000) +#define NBIT13 (0x00002000) +#define NBIT12 (0x00001000) +#define NBIT11 (0x00000800) +#define NBIT10 (0x00000400) +#define NBIT9 (0x00000200) +#define NBIT8 (0x00000100) +#define NBIT7 (0x00000080) +#define NBIT6 (0x00000040) +#define NBIT5 (0x00000020) +#define NBIT4 (0x00000010) +#define NBIT3 (0x00000008) +#define NBIT2 (0x00000004) +#define NBIT1 (0x00000002) +#define NBIT0 (0x00000001) + +#define M2M_MAX(A,B) ((A) > (B) ? (A) : (B)) +#define M2M_SEL(x,m1,m2,m3) ((x>1)?((x>2)?(m3):(m2)):(m1)) +#define WORD_ALIGN(val) (((val) & 0x03) ? ((val) + 4 - ((val) & 0x03)) : (val)) + + + +#define DATA_PKT_OFFSET 4 + +#ifndef BIG_ENDIAN +#define BYTE_0(word) ((uint8)(((word) >> 0 ) & 0x000000FFUL)) +#define BYTE_1(word) ((uint8)(((word) >> 8 ) & 0x000000FFUL)) +#define BYTE_2(word) ((uint8)(((word) >> 16) & 0x000000FFUL)) +#define BYTE_3(word) ((uint8)(((word) >> 24) & 0x000000FFUL)) +#else +#define BYTE_0(word) ((uint8)(((word) >> 24) & 0x000000FFUL)) +#define BYTE_1(word) ((uint8)(((word) >> 16) & 0x000000FFUL)) +#define BYTE_2(word) ((uint8)(((word) >> 8 ) & 0x000000FFUL)) +#define BYTE_3(word) ((uint8)(((word) >> 0 ) & 0x000000FFUL)) +#endif + +/**@}*/ +#ifdef __cplusplus + extern "C" { + #endif +NMI_API void m2m_memcpy(uint8* pDst,uint8* pSrc,uint32 sz); +NMI_API void m2m_memset(uint8* pBuf,uint8 val,uint32 sz); +NMI_API uint16 m2m_strlen(uint8 * pcStr); +NMI_API sint8 m2m_memcmp(uint8 *pu8Buff1,uint8 *pu8Buff2 ,uint32 u32Size); +NMI_API uint8 m2m_strncmp(uint8 *pcS1, uint8 *pcS2, uint16 u16Len); +NMI_API uint8 * m2m_strstr(uint8 *pcIn, uint8 *pcStr); +NMI_API uint8 m2m_checksum(uint8* buf, int sz); + +#ifdef __cplusplus +} + #endif +#endif /*_NM_COMMON_H_*/ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/include/nm_debug.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/include/nm_debug.h new file mode 100644 index 0000000..a710f6c --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/include/nm_debug.h @@ -0,0 +1,95 @@ +/** + * + * \file + * + * \brief This module contains debug APIs declarations. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NM_DEBUG_H_ +#define _NM_DEBUG_H_ + +#include "bsp/include/nm_bsp.h" +#include "bsp/include/nm_bsp_internal.h" + +/**@defgroup DebugDefines DebugDefines + * @ingroup WlanDefines + */ +/**@{*/ + + +#define M2M_LOG_NONE 0 +#define M2M_LOG_ERROR 1 +#define M2M_LOG_INFO 2 +#define M2M_LOG_REQ 3 +#define M2M_LOG_DBG 4 + +#if (defined __APS3_CORTUS__) +#define M2M_LOG_LEVEL M2M_LOG_INFO +#else +#define M2M_LOG_LEVEL M2M_LOG_REQ +#endif + + +#define M2M_ERR(...) +#define M2M_INFO(...) +#define M2M_REQ(...) +#define M2M_DBG(...) +#define M2M_PRINT(...) + +#if (CONF_WINC_DEBUG == 1) +#undef M2M_PRINT +#define M2M_PRINT(...) do{CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) +#if (M2M_LOG_LEVEL >= M2M_LOG_ERROR) +#undef M2M_ERR +#define M2M_ERR(...) do{CONF_WINC_PRINTF("(APP)(ERR)[%s][%d]",__FUNCTION__,__LINE__); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) +#if (M2M_LOG_LEVEL >= M2M_LOG_INFO) +#undef M2M_INFO +#define M2M_INFO(...) do{CONF_WINC_PRINTF("(APP)(INFO)"); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) +#if (M2M_LOG_LEVEL >= M2M_LOG_REQ) +#undef M2M_REQ +#define M2M_REQ(...) do{CONF_WINC_PRINTF("(APP)(R)"); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) +#if (M2M_LOG_LEVEL >= M2M_LOG_DBG) +#undef M2M_DBG +#define M2M_DBG(...) do{CONF_WINC_PRINTF("(APP)(DBG)[%s][%d]",__FUNCTION__,__LINE__); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) +#endif /*M2M_LOG_DBG*/ +#endif /*M2M_LOG_REQ*/ +#endif /*M2M_LOG_INFO*/ +#endif /*M2M_LOG_ERROR*/ +#endif /*CONF_WINC_DEBUG */ + +/**@}*/ +#endif /* _NM_DEBUG_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/source/nm_common.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/source/nm_common.c new file mode 100644 index 0000000..8b3c941 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/source/nm_common.c @@ -0,0 +1,136 @@ +/** + * + * \file + * + * \brief This module contains common APIs declarations. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +#include "common/include/nm_common.h" + +void m2m_memcpy(uint8* pDst,uint8* pSrc,uint32 sz) +{ + if(sz == 0) return; + do + { + *pDst = *pSrc; + pDst++; + pSrc++; + }while(--sz); +} +uint8 m2m_checksum(uint8* buf, int sz) +{ + uint8 cs = 0; + while(--sz) + { + cs ^= *buf; + buf++; + } + + return cs; +} + +void m2m_memset(uint8* pBuf,uint8 val,uint32 sz) +{ + if(sz == 0) return; + do + { + *pBuf = val; + pBuf++; + }while(--sz); +} + +uint16 m2m_strlen(uint8 * pcStr) +{ + uint16 u16StrLen = 0; + while(*pcStr) + { + u16StrLen ++; + pcStr++; + } + return u16StrLen; +} + +uint8 m2m_strncmp(uint8 *pcS1, uint8 *pcS2, uint16 u16Len) +{ + for ( ; u16Len > 0; pcS1++, pcS2++, --u16Len) + if (*pcS1 != *pcS2) + return ((*(uint8 *)pcS1 < *(uint8 *)pcS2) ? -1 : +1); + else if (*pcS1 == '\0') + return 0; + return 0; +} + +/* Finds the occurance of pcStr in pcIn. +If pcStr is part of pcIn it returns a valid pointer to the start of pcStr within pcIn. +Otherwise a NULL Pointer is returned. +*/ +uint8 * m2m_strstr(uint8 *pcIn, uint8 *pcStr) +{ + uint8 u8c; + uint16 u16StrLen; + + u8c = *pcStr++; + if (!u8c) + return (uint8 *) pcIn; // Trivial empty string case + + u16StrLen = m2m_strlen(pcStr); + do { + uint8 u8Sc; + + do { + u8Sc = *pcIn++; + if (!u8Sc) + return (uint8 *) 0; + } while (u8Sc != u8c); + } while (m2m_strncmp(pcIn, pcStr, u16StrLen) != 0); + + return (uint8 *) (pcIn - 1); +} + +sint8 m2m_memcmp(uint8 *pu8Buff1,uint8 *pu8Buff2 ,uint32 u32Size) +{ + uint32 i; + sint8 s8Result = 0; + for(i = 0 ; i < u32Size ; i++) + { + if(pu8Buff1[i] != pu8Buff2[i]) + { + s8Result = 1; + break; + } + } + return s8Result; +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/ecc_types.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/ecc_types.h new file mode 100644 index 0000000..764c3b9 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/ecc_types.h @@ -0,0 +1,245 @@ +/** + * + * \file + * + * \brief WINC Application Interface Internal Types. + * + * Copyright (c) 2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef __ECC_TYPES_H__ +#define __ECC_TYPES_H__ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "m2m_types.h" + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + + +#define ECC_LARGEST_CURVE_SIZE (32) +/*!< + The size of the the largest supported EC. For now, assuming + the 256-bit EC is the largest supported curve type. +*/ + + +#define ECC_POINT_MAX_SIZE ECC_LARGEST_CURVE_SIZE +/*!< + Maximum size of one coordinate of an EC point. +*/ + + +#define ECC_POINT_MAX_SIZE_WORDS (ECC_POINT_MAX_SIZE / 4) +/*!< + SIZE in 32-bit words. +*/ + +#if 0 +#define ECC_NUM_SUPP_CURVES ((sizeof(gastrECCSuppList)) / (sizeof(tstrEllipticCurve))) +#endif +/*!< +*/ + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +/*! +@enum \ + tenuEcNamedCurve + +@brief EC Named Curves + + Defines a list of supported ECC named curves. +*/ +typedef enum EcNamedCurve{ + EC_SECP192R1 = 19, + /*!< + It is defined by NIST as P192 and by the SEC Group as secp192r1. + */ + EC_SECP256R1 = 23, + /*!< + It is defined by NIST as P256 and by the SEC Group as secp256r1. + */ + EC_SECP384R1 = 24, + /*!< + It is defined by NIST as P384 and by the SEC Group as secp384r1. + */ + EC_SECP521R1 = 25, + /*!< + It is defined by NIST as P521 and by the SEC Group as secp521r1. + */ + EC_UNKNOWN = 255 +}tenuEcNamedCurve; + + +/*! +@struct \ + tstrECPoint + +@brief Elliptic Curve point representation +*/ +typedef struct EcPoint{ + uint8 X[ECC_POINT_MAX_SIZE]; + /*!< + The X-coordinate of the ec point. + */ + uint8 Y[ECC_POINT_MAX_SIZE]; + /*!< + The Y-coordinate of the ec point. + */ + uint16 u16Size; + /*!< + Point size in bytes (for each of the coordinates). + */ + uint16 u16PrivKeyID; + /*!< + ID for the corresponding private key. + */ +}tstrECPoint; + + +/*! +@struct \ + tstrECDomainParam + +@brief ECC Curve Domain Parameters + + The structure defines the ECC domain parameters for curves defined over prime finite fields. +*/ +typedef struct EcDomainParam{ + uint32 p[ECC_POINT_MAX_SIZE_WORDS]; + uint32 a[ECC_POINT_MAX_SIZE_WORDS]; + uint32 b[ECC_POINT_MAX_SIZE_WORDS]; + tstrECPoint G; +}tstrECDomainParam; + + +/*! +@struct \ + tstrEllipticCurve + +@brief + Definition of an elliptic curve +*/ +typedef struct{ + tenuEcNamedCurve enuType; + tstrECDomainParam strParam; +}tstrEllipticCurve; + + +typedef enum{ + ECC_REQ_NONE, + ECC_REQ_CLIENT_ECDH, + ECC_REQ_SERVER_ECDH, + ECC_REQ_GEN_KEY, + ECC_REQ_SIGN_GEN, + ECC_REQ_SIGN_VERIFY +}tenuEccREQ; + + +typedef struct{ + tstrECPoint strPubKey; + uint8 au8Key[ECC_POINT_MAX_SIZE]; +}tstrEcdhReqInfo; + + +typedef struct{ + uint32 u32nSig; +}tstrEcdsaVerifyReqInfo; + + +typedef struct{ + uint16 u16CurveType; + uint16 u16HashSz; +}tstrEcdsaSignReqInfo; + + +typedef struct{ + uint16 u16REQ; + uint16 u16Status; + uint32 u32UserData; + uint32 u32SeqNo; + union{ + tstrEcdhReqInfo strEcdhREQ; + tstrEcdsaSignReqInfo strEcdsaSignREQ; + tstrEcdsaVerifyReqInfo strEcdsaVerifyREQ; + }; +}tstrEccReqInfo; + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +GLOBALS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#if 0 +static tstrEllipticCurve gastrECCSuppList[] = { + { + EC_SECP256R1, + { + {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF}, + {0xFFFFFFFC, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF}, + {0x27D2604B, 0x3BCE3C3E, 0xCC53B0F6, 0x651D06B0, 0x769886BC, 0xB3EBBD55, 0xAA3A93E7, 0x5AC635D8}, + { + { + 0x6B, 0x17, 0xD1, 0xF2, 0xE1, 0x2C, 0x42, 0x47, 0xF8, 0xBC, 0xE6, 0xE5, 0x63, 0xA4, 0x40, 0xF2, + 0x77, 0x03, 0x7D, 0x81, 0x2D, 0xEB, 0x33, 0xA0, 0xF4, 0xA1, 0x39, 0x45, 0xD8, 0x98, 0xC2, 0x96 + }, + { + 0x4F, 0xE3, 0x42, 0xE2, 0xFE, 0x1A, 0x7F, 0x9B, 0x8E, 0xE7, 0xEB, 0x4A, 0x7C, 0x0F, 0x9E, 0x16, + 0x2B, 0xCE, 0x33, 0x57, 0x6B, 0x31, 0x5E, 0xCE, 0xCB, 0xB6, 0x40, 0x68, 0x37, 0xBF, 0x51, 0xF5 + }, + 32 + } + } + } +}; +#endif + +/*!< + List of supported Elliptic Curves ordered by security level (most secure curve is at index ZERO). +*/ + + + +#endif /* __ECC_TYPES_H__ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_ate_mode.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_ate_mode.h new file mode 100644 index 0000000..a17d298 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_ate_mode.h @@ -0,0 +1,732 @@ +/** + * + * \file + * + * \brief WINC ATE Test Driver Interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifdef _M2M_ATE_FW_ + +#ifndef _M2M_ATE_MODE_H_ +#define _M2M_ATE_MODE_H_ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#include "common/include/nm_common.h" +#include "driver/include/m2m_types.h" + +/** \defgroup m2m_ate ATE +*/ +/**@defgroup ATEDefine Defines + * @ingroup m2m_ate + * @{ + */ +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#define M2M_ATE_MAX_NUM_OF_RATES (20) +/*!< +Maximum number of all rates (b,g and n) + */ +#define M2M_ATE_MAX_FRAME_LENGTH (1024) +/*!< Maximum number of length for each frame + */ +#define M2M_ATE_MIN_FRAME_LENGTH (1) +/*!< Minimum number of length for each frame + */ +#define M2M_ATE_SUCCESS (M2M_SUCCESS) +/*!< No Error and operation has been completed successfully. +*/ +#define M2M_ATE_ERR_VALIDATE (M2M_ERR_FAIL) +/*!< Error in parameters passed to functions. + */ +#define M2M_ATE_ERR_TX_ALREADY_RUNNING (-1) +/*!< Error in starting a transmission test. Another test is already running and its not allowed to start another ATE test. + */ +#define M2M_ATE_ERR_RX_ALREADY_RUNNING (-2) +/*!< Error in starting a reception test. Another test is already running and its not allowed to start another ATE test. + */ +#define M2M_ATE_ERR_UNHANDLED_CASE (-3) +/*!< Invalid case. + */ +#define M2M_ATE_RX_DISABLE_DA 0x0 +/*!< Filter selection for received frames: Disable filtering received frames by the destination address. + */ +#define M2M_ATE_RX_ENABLE_DA 0x1 +/*!< Filter selection for received frames: Enable filtering received frames by the destination address. + */ +#define M2M_ATE_RX_DISABLE_SA 0x0 +/*!< Filter selection for received frames: Disable filtering received frames by the source address. + */ +#define M2M_ATE_RX_ENABLE_SA 0x1 +/*!< Filter selection for received frames: Enable filtering received frames by the source address. + */ +#define M2M_ATE_DISABLE_SELF_MACADDR 0x0 +/*!\n",ret); + while(1); + } + //Initialize the OTA module + m2m_ota_init(OtaUpdateCb,NULL); + //connect to AP that provide connection to the OTA server + m2m_wifi_default_connect(); + + while(1) + { + + //Handle the app state machine plus the WINC event handler + while(m2m_wifi_handle_events(NULL) != M2M_SUCCESS) { + + } + + } +} +@endcode + +*/ +NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl); + /**@}*/ +/** @defgroup OtaStartUpdatefn m2m_ota_start_update_crt +* @ingroup WLANAPI +* Request OTA start for cortus application image using the downloaded URL, the OTA module will download the OTA image and ensure integrity of the image, +* and update the validity of the image in control structure. Switching to that image requires calling @ref m2m_ota_switch_crt API. +* As a prerequisite @ref m2m_ota_init should be called before using @ref m2m_ota_start_update_crt(). +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl); + +@param [in] u8DownloadUrl + The cortus application image url. +@warning + Calling this API does not guarantee cortus application image update, It depends on the connection with the download server and the validity of the image. + If the API response is failure this may invalidate the roll-back image if it was previously valid, since the WINC does not have any internal memory + except the flash roll-back image location to validate the downloaded image from + +@see + m2m_ota_init + tpfOtaUpdateCb + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl); + /**@}*/ +/** @defgroup OtaRollbackfn m2m_ota_rollback +* @ingroup WLANAPI + Request OTA Roll-back to the old (other) WINC image, the WINC firmware will check the validation of the Roll-back image + and switch to it if it is valid. + If the API response is success, system restart is required (re-initialize the driver with hardware rest) update the host driver version may + be required if it is did not match the minimum version supported by the WINC firmware. + +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ota_rollback(void); + +@sa + m2m_ota_init + m2m_ota_start_update + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_rollback(void); + /**@}*/ +/** @defgroup OtaRollbackfn m2m_ota_rollback_crt +* @ingroup WLANAPI + Request Cortus application OTA Roll-back to the old (other) cortus application image, the WINC firmware will check the validation of the Roll-back image + and switch to it if it is valid. + If the API response is success, system restart is required (re-initialize the driver with hardware rest) update the host driver version may + be required. + +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ota_rollback_crt(void); + +@sa + m2m_ota_init + m2m_ota_start_update_crt + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_rollback_crt(void); + /**@}*/ +/** @defgroup OtaAbortfn m2m_ota_abort +* @ingroup WLANAPI + Request abort of current OTA download. + The WINC firmware will terminate the OTA download if one is in progress. + If no download is in progress, the API will respond with failure. +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ota_abort(void); + +@return + The function returns @ref M2M_SUCCESS for successful operation and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_abort(void); + /**@}*/ + /**@}*/ +/** @defgroup OtaSwitchFirmware m2m_ota_switch_firmware +* @ingroup WLANAPI +* Switch to the upgraded Firmware, that API will update the control structure working image to the upgraded image + take effect will be on the next system restart +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ota_switch_firmware(void); + +@warning + It is important to note that if the API succeeds, system restart is required (re-initializing the driver with hardware reset) updating the host driver version may be required + if it does not match the minimum driver version supported by the WINC's firmware. +@sa + m2m_ota_init + m2m_ota_start_update + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_switch_firmware(void); + /**@}*/ + /**@}*/ +/** @defgroup OtaSwitchFirmware m2m_ota_switch_crt +* @ingroup WLANAPI +* Switch to the upgraded cortus application, that API will update the control structure working image to the upgraded image + take effect will be on the next system restart +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ota_switch_firmware(void); + +@warning + It is important to note that if the API succeeds, system restart is required (re-initializing the driver with hardware reset) updating the host driver version may be required + if it does not match the minimum driver version supported by the WINC's firmware. +@sa + m2m_ota_init + m2m_ota_start_update_crt + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_switch_crt(void); +/*! +@fn \ + NMI_API sint8 m2m_ota_get_firmware_version(void); + +@brief + Get the OTA Firmware version. + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_get_firmware_version(tstrM2mRev *pstrRev); + /**@}*/ +NMI_API sint8 m2m_ota_test(void); + +#ifdef __cplusplus +} +#endif +#endif /* __M2M_OTA_H__ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_periph.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_periph.h new file mode 100644 index 0000000..1012882 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_periph.h @@ -0,0 +1,411 @@ +/** + * + * \file + * + * \brief WINC Peripherals Application Interface. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _M2M_PERIPH_H_ +#define _M2M_PERIPH_H_ + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +#include "common/include/nm_common.h" +#include "driver/include/m2m_types.h" + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*! +@struct \ + tstrPerphInitParam + +@brief + Peripheral module initialization parameters. +*/ +typedef struct { + void * arg; +} tstrPerphInitParam; + + +/*! +@enum \ + tenuGpioNum + +@brief + A list of GPIO numbers configurable through the m2m_periph module. +*/ +typedef enum { + M2M_PERIPH_GPIO3, /*!< GPIO15 pad */ + M2M_PERIPH_GPIO4, /*!< GPIO16 pad */ + M2M_PERIPH_GPIO5, /*!< GPIO18 pad */ + M2M_PERIPH_GPIO6, /*!< GPIO18 pad */ + M2M_PERIPH_GPIO15, /*!< GPIO15 pad */ + M2M_PERIPH_GPIO16, /*!< GPIO16 pad */ + M2M_PERIPH_GPIO18, /*!< GPIO18 pad */ + M2M_PERIPH_GPIO_MAX +} tenuGpioNum; + + +/*! +@enum \ + tenuI2cMasterSclMuxOpt + +@brief + Allowed pin multiplexing options for I2C master SCL signal. +*/ +typedef enum { + M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_HOST_WAKEUP, /*!< I2C master SCL is avaiable on HOST_WAKEUP. */ + M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_SD_DAT3, /*!< I2C master SCL is avaiable on SD_DAT3 (GPIO 7). */ + M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_GPIO13, /*!< I2C master SCL is avaiable on GPIO 13. */ + M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_GPIO4, /*!< I2C master SCL is avaiable on GPIO 4.*/ + M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_I2C_SCL, /*!< I2C master SCL is avaiable on I2C slave SCL. */ + M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_NUM +} tenuI2cMasterSclMuxOpt; + +/*! +@enum \ + tenuI2cMasterSdaMuxOpt + +@brief + Allowed pin multiplexing options for I2C master SDA signal. +*/ +typedef enum { + M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_RTC_CLK , /*!< I2C master SDA is avaiable on RTC_CLK. */ + M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_SD_CLK, /*!< I2C master SDA is avaiable on SD_CLK (GPIO 8). */ + M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_GPIO14, /*!< I2C master SDA is avaiable on GPIO 14. */ + M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_GPIO6, /*!< I2C master SDA is avaiable on GPIO 6.*/ + M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_I2C_SDA, /*!< I2C master SDA is avaiable on I2C slave SDA. */ + M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_NUM +} tenuI2cMasterSdaMuxOpt; + + +/*! +@struct \ + tstrI2cMasterInitParam + +@brief + I2C master configuration parameters. +@sa + tenuI2cMasterSclMuxOpt + tenuI2cMasterSdaMuxOpt +*/ +typedef struct { + uint8 enuSclMuxOpt; /*!< SCL multiplexing option. Allowed value are defined in tenuI2cMasterSclMuxOpt */ + uint8 enuSdaMuxOpt; /*!< SDA multiplexing option. Allowed value are defined in tenuI2cMasterSdaMuxOpt */ + uint8 u8ClkSpeedKHz; /*!< I2C master clock speed in KHz. */ +} tstrI2cMasterInitParam; + +/*! +@enum \ + tenuI2cMasterFlags + +@brief + Bitwise-ORed flags for use in m2m_periph_i2c_master_write and m2m_periph_i2c_master_read +@sa + m2m_periph_i2c_master_write + m2m_periph_i2c_master_read +*/ +typedef enum { + I2C_MASTER_NO_FLAGS = 0x00, + /*!< No flags. */ + I2C_MASTER_NO_STOP = 0x01, + /*!< No stop bit after this transaction. Useful for scattered buffer read/write operations. */ + I2C_MASTER_NO_START = 0x02, + /*!< No start bit at the beginning of this transaction. Useful for scattered buffer read/write operations.*/ +} tenuI2cMasterFlags; + +/*! +@enum \ + tenuPullupMask + +@brief + Bitwise-ORed flags for use in m2m_perph_pullup_ctrl. +@sa + m2m_periph_pullup_ctrl + +*/ +typedef enum { + M2M_PERIPH_PULLUP_DIS_HOST_WAKEUP = (1ul << 0), + M2M_PERIPH_PULLUP_DIS_RTC_CLK = (1ul << 1), + M2M_PERIPH_PULLUP_DIS_IRQN = (1ul << 2), + M2M_PERIPH_PULLUP_DIS_GPIO_3 = (1ul << 3), + M2M_PERIPH_PULLUP_DIS_GPIO_4 = (1ul << 4), + M2M_PERIPH_PULLUP_DIS_GPIO_5 = (1ul << 5), + M2M_PERIPH_PULLUP_DIS_SD_DAT3 = (1ul << 6), + M2M_PERIPH_PULLUP_DIS_SD_DAT2_SPI_RXD = (1ul << 7), + M2M_PERIPH_PULLUP_DIS_SD_DAT1_SPI_SSN = (1ul << 9), + M2M_PERIPH_PULLUP_DIS_SD_CMD_SPI_SCK = (1ul << 10), + M2M_PERIPH_PULLUP_DIS_SD_DAT0_SPI_TXD = (1ul << 11), + M2M_PERIPH_PULLUP_DIS_GPIO_6 = (1ul << 12), + M2M_PERIPH_PULLUP_DIS_SD_CLK = (1ul << 13), + M2M_PERIPH_PULLUP_DIS_I2C_SCL = (1ul << 14), + M2M_PERIPH_PULLUP_DIS_I2C_SDA = (1ul << 15), + M2M_PERIPH_PULLUP_DIS_GPIO_11 = (1ul << 16), + M2M_PERIPH_PULLUP_DIS_GPIO_12 = (1ul << 17), + M2M_PERIPH_PULLUP_DIS_GPIO_13 = (1ul << 18), + M2M_PERIPH_PULLUP_DIS_GPIO_14 = (1ul << 19), + M2M_PERIPH_PULLUP_DIS_GPIO_15 = (1ul << 20), + M2M_PERIPH_PULLUP_DIS_GPIO_16 = (1ul << 21), + M2M_PERIPH_PULLUP_DIS_GPIO_17 = (1ul << 22), + M2M_PERIPH_PULLUP_DIS_GPIO_18 = (1ul << 23), + M2M_PERIPH_PULLUP_DIS_GPIO_19 = (1ul << 24), + M2M_PERIPH_PULLUP_DIS_GPIO_20 = (1ul << 25), + M2M_PERIPH_PULLUP_DIS_GPIO_21 = (1ul << 26), + M2M_PERIPH_PULLUP_DIS_GPIO_22 = (1ul << 27), + M2M_PERIPH_PULLUP_DIS_GPIO_23 = (1ul << 28), + M2M_PERIPH_PULLUP_DIS_GPIO_24 = (1ul << 29), +} tenuPullupMask; + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +#ifdef __cplusplus + extern "C" { +#endif + +/*! +@fn \ + NMI_API sint8 m2m_periph_init(tstrPerphInitParam * param); + +@brief + Initialize the NMC1500 peripheral driver module. + +@param [in] param + Peripheral module initialization structure. See members of tstrPerphInitParam. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tstrPerphInitParam +*/ +NMI_API sint8 m2m_periph_init(tstrPerphInitParam * param); + +/*! +@fn \ + NMI_API sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir); + +@brief + Configure a specific NMC1500 pad as a GPIO and sets its direction (input or output). + +@param [in] u8GpioNum + GPIO number. Allowed values are defined in tenuGpioNum. + +@param [in] u8GpioDir + GPIO direction: Zero = input. Non-zero = output. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuGpioNum +*/ +NMI_API sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir); + +/*! +@fn \ + NMI_API sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal); + +@brief + Set an NMC1500 GPIO output level high or low. + +@param [in] u8GpioNum + GPIO number. Allowed values are defined in tenuGpioNum. + +@param [in] u8GpioVal + GPIO output value. Zero = low, non-zero = high. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuGpioNum +*/ +NMI_API sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal); + +/*! +@fn \ + NMI_API sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal); + +@brief + Read an NMC1500 GPIO input level. + +@param [in] u8GpioNum + GPIO number. Allowed values are defined in tenuGpioNum. + +@param [out] pu8GpioVal + GPIO input value. Zero = low, non-zero = high. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuGpioNum +*/ +NMI_API sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal); + +/*! +@fn \ + NMI_API sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn); + +@brief + Set an NMC1500 GPIO pullup resisitor enable or disable. + +@param [in] u8GpioNum + GPIO number. Allowed values are defined in tenuGpioNum. + +@param [in] u8PullupEn + Zero: pullup disabled. Non-zero: pullup enabled. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuGpioNum +*/ +NMI_API sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn); + +/*! +@fn \ + NMI_API sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param); + +@brief + Initialize and configure the NMC1500 I2C master peripheral. + +@param [in] param + I2C master initialization structure. See members of tstrI2cMasterInitParam. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tstrI2cMasterInitParam +*/ +NMI_API sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param); + +/*! +@fn \ + NMI_API sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags); + +@brief + Write a stream of bytes to the I2C slave device. + +@param [in] u8SlaveAddr + 7-bit I2C slave address. +@param [in] pu8Buf + A pointer to an input buffer which contains a stream of bytes. +@param [in] u16BufLen + Input buffer length in bytes. +@param [in] flags + Write operation bitwise-ORed flags. See tenuI2cMasterFlags. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuI2cMasterFlags +*/ +NMI_API sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags); + + +/*! +@fn \ + NMI_API sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags); + +@brief + Write a stream of bytes to the I2C slave device. + +@param [in] u8SlaveAddr + 7-bit I2C slave address. +@param [out] pu8Buf + A pointer to an output buffer in which a stream of bytes are received. +@param [in] u16BufLen + Max output buffer length in bytes. +@param [out] pu16ReadLen + Actual number of bytes received. +@param [in] flags + Write operation bitwise-ORed flags. See tenuI2cMasterFlags. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuI2cMasterFlags +*/ +NMI_API sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags); + + +/*! +@fn \ + NMI_API sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable); + +@brief + Control the programmable pull-up resistor on the chip pads . + + +@param [in] pinmask + Write operation bitwise-ORed mask for which pads to control. Allowed values are defined in tenuPullupMask. + +@param [in] enable + Set to 0 to disable pull-up resistor. Non-zero will enable the pull-up. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +@sa + tenuPullupMask +*/ +NMI_API sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable); + +#ifdef __cplusplus +} +#endif + + +#endif /* _M2M_PERIPH_H_ */ \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_ssl.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_ssl.h new file mode 100644 index 0000000..f5271f0 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_ssl.h @@ -0,0 +1,182 @@ +/** + * + * \file + * + * \brief WINC Application Interface Internal Types. + * + * Copyright (c) 2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/**@defgroup SSLAPI SSL +*/ + +#ifndef __M2M_SSL_H__ +#define __M2M_SSL_H__ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "common/include/nm_common.h" +#include "driver/include/m2m_types.h" +#include "driver/source/nmdrv.h" +#include "ecc_types.h" +#include "socket/include/socket.h" + +/**@defgroup SSLEnums Enumeration/Typedefs + * @ingroup SSLAPI + * @{*/ + +/*! +@typedef \ + void (*tpfAppSslCb) (uint8 u8MsgType, void * pvMsg); + +@brief A callback to get SSL notifications. + +@param[in] u8MsgType +@param[in] pvMsg A structure to provide notification payload. +*/ +typedef void (*tpfAppSSLCb) (uint8 u8MsgType, void * pvMsg); + +/**@} +*/ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/** \defgroup SSLFUNCTIONS Functions +* @ingroup SSLAPI +*/ + +/**@{*/ +/*! + @fn \ m2m_ssl_init(tpfAppSslCb pfAppSslCb); + @brief Initializes the SSL layer. + @param [in] pfAppSslCb + Application SSL callback function. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_init(tpfAppSSLCb pfAppSSLCb); + +/*! + @fn \ NMI_API sint8 m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz) + @brief Sends ECC responses to the WINC + @param [in] strECCResp + ECC Response struct. + @param [in] pu8RspDataBuffe + Pointer of the response data to be sent. + @param [in] u16RspDataSz + Response data size. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz); + +/*! + @fn \ NMI_API sint8 m2m_ssl_send_certs_to_winc(uint8* pu8Buffer, uint32 u32BufferSz) + @brief Sends certificates to the WINC + @param [in] pu8Buffer + Pointer to the certificates. + @param [in] u32BufferSz + Size of the certificates. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_send_certs_to_winc(uint8* pu8Buffer, uint32 u32BufferSz); + +/*! + @fn \ NMI_API sint8 m2m_ssl_retrieve_cert(uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key) + @brief Retrieve the certificate to be verified from the WINC + @param [in] pu16CurveType + Pointer to the certificate curve type. + @param [in] pu8Hash + Pointer to the certificate hash. + @param [in] pu8Sig + Pointer to the certificate signature. + @param [in] pu8Key + Pointer to the certificate Key. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_retrieve_cert(uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key); + +/*! + @fn \ NMI_API sint8 m2m_ssl_retrieve_hash(uint8* pu8Hash, uint16 u16HashSz) + @brief Retrieve the certificate hash + @param [in] pu8Hash + Pointer to the certificate hash. + @param [in] u16HashSz + Hash size. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_retrieve_hash(uint8* pu8Hash, uint16 u16HashSz); + +/*! + @fn \ NMI_API void m2m_ssl_stop_processing_certs(void) + @brief Allow ssl driver to tidy up in case application does not read all available certificates. + @warning This API must only be called if some certificates are left unread. + @return None. +*/ +NMI_API void m2m_ssl_stop_processing_certs(void); + +/*! + @fn \ NMI_API void m2m_ssl_ecc_process_done(void) + @brief Allow ssl driver to tidy up after application has finished processing ecc message. + @warning This API must be called after receiving a SSL callback with type @ref M2M_SSL_REQ_ECC + @return None. +*/ +NMI_API void m2m_ssl_ecc_process_done(void); + +/*! +@fn \ + NMI_API sint8 m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP); + Override the default Active SSL ciphers in the SSL module with a certain combination selected by the caller in the form of + a bitmap containing the required ciphers to be on. + There is no need to call this function if the application will not change the default ciphersuites. + +@param [in] u32SslCsBMP + Bitmap containing the desired ciphers to be enabled for the SSL module. The ciphersuites are defined in + @ref SSLCipherSuiteID. + The default ciphersuites are all ciphersuites supported by the firmware with the exception of ECC ciphersuites. + The caller can override the default with any desired combination, except for combinations involving both RSA + and ECC; if any RSA ciphersuite is enabled, then firmware will disable all ECC ciphersuites. + If u32SslCsBMP does not contain any ciphersuites supported by firmware, then the current active list will not + be changed. + +@return + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) +*/ +sint8 m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP); + + /**@}*/ +#endif /* __M2M_SSL_H__ */ \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_types.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_types.h new file mode 100644 index 0000000..a847f3f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_types.h @@ -0,0 +1,2383 @@ +/** + * + * \file + * + * \brief WINC Application Interface Internal Types. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef __M2M_WIFI_TYPES_H__ +#define __M2M_WIFI_TYPES_H__ + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#ifndef _BOOT_ +#ifndef _FIRMWARE_ +#include "common/include/nm_common.h" +#else +#include "m2m_common.h" +#endif +#endif + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/**@defgroup WlanDefines Defines + * @ingroup m2m_wifi + */ +/**@{*/ +#define M2M_MAJOR_SHIFT (8) +#define M2M_MINOR_SHIFT (4) +#define M2M_PATCH_SHIFT (0) + +#define M2M_DRV_VERSION_SHIFT (16) +#define M2M_FW_VERSION_SHIFT (0) + +#define M2M_GET_MAJOR(ver_info_hword) ((uint8)((ver_info_hword) >> M2M_MAJOR_SHIFT) & 0xff) +#define M2M_GET_MINOR(ver_info_hword) ((uint8)((ver_info_hword) >> M2M_MINOR_SHIFT) & 0x0f) +#define M2M_GET_PATCH(ver_info_hword) ((uint8)((ver_info_hword) >> M2M_PATCH_SHIFT) & 0x0f) + +#define M2M_GET_FW_VER(ver_info_word) ((uint16) ((ver_info_word) >> M2M_FW_VERSION_SHIFT)) +#define M2M_GET_DRV_VER(ver_info_word) ((uint16) ((ver_info_word) >> M2M_DRV_VERSION_SHIFT)) + +#define M2M_GET_DRV_MAJOR(ver_info_word) M2M_GET_MAJOR(M2M_GET_DRV_VER(ver_info_word)) +#define M2M_GET_DRV_MINOR(ver_info_word) M2M_GET_MINOR(M2M_GET_DRV_VER(ver_info_word)) +#define M2M_GET_DRV_PATCH(ver_info_word) M2M_GET_PATCH(M2M_GET_DRV_VER(ver_info_word)) + +#define M2M_GET_FW_MAJOR(ver_info_word) M2M_GET_MAJOR(M2M_GET_FW_VER(ver_info_word)) +#define M2M_GET_FW_MINOR(ver_info_word) M2M_GET_MINOR(M2M_GET_FW_VER(ver_info_word)) +#define M2M_GET_FW_PATCH(ver_info_word) M2M_GET_PATCH(M2M_GET_FW_VER(ver_info_word)) + +#define M2M_MAKE_VERSION(major, minor, patch) ( \ + ((uint16)((major) & 0xff) << M2M_MAJOR_SHIFT) | \ + ((uint16)((minor) & 0x0f) << M2M_MINOR_SHIFT) | \ + ((uint16)((patch) & 0x0f) << M2M_PATCH_SHIFT)) + +#define M2M_MAKE_VERSION_INFO(fw_major, fw_minor, fw_patch, drv_major, drv_minor, drv_patch) \ + ( \ + ( ((uint32)M2M_MAKE_VERSION((fw_major), (fw_minor), (fw_patch))) << M2M_FW_VERSION_SHIFT) | \ + ( ((uint32)M2M_MAKE_VERSION((drv_major), (drv_minor), (drv_patch))) << M2M_DRV_VERSION_SHIFT)) + +#define REL_19_5_2_VER M2M_MAKE_VERSION_INFO(19,5,2,19,3,0) +#define REL_19_5_1_VER M2M_MAKE_VERSION_INFO(19,5,1,19,3,0) +#define REL_19_5_0_VER M2M_MAKE_VERSION_INFO(19,5,0,19,3,0) +#define REL_19_4_6_VER M2M_MAKE_VERSION_INFO(19,4,6,19,3,0) +#define REL_19_4_5_VER M2M_MAKE_VERSION_INFO(19,4,5,19,3,0) +#define REL_19_4_4_VER M2M_MAKE_VERSION_INFO(19,4,4,19,3,0) +#define REL_19_4_3_VER M2M_MAKE_VERSION_INFO(19,4,3,19,3,0) +#define REL_19_4_2_VER M2M_MAKE_VERSION_INFO(19,4,2,19,3,0) +#define REL_19_4_1_VER M2M_MAKE_VERSION_INFO(19,4,1,19,3,0) +#define REL_19_4_0_VER M2M_MAKE_VERSION_INFO(19,4,0,19,3,0) +#define REL_19_3_1_VER M2M_MAKE_VERSION_INFO(19,3,1,19,3,0) +#define REL_19_3_0_VER M2M_MAKE_VERSION_INFO(19,3,0,19,3,0) +#define REL_19_2_2_VER M2M_MAKE_VERSION_INFO(19,2,2,19,2,0) +#define REL_19_2_1_VER M2M_MAKE_VERSION_INFO(19,2,1,19,2,0) +#define REL_19_2_0_VER M2M_MAKE_VERSION_INFO(19,2,0,19,2,0) +#define REL_19_1_0_VER M2M_MAKE_VERSION_INFO(19,1,0,18,2,0) +#define REL_19_0_0_VER M2M_MAKE_VERSION_INFO(19,0,0,18,1,1) + +/*======*======*======*======* + FIRMWARE VERSION NO INFO + *======*======*======*======*/ + +#define M2M_RELEASE_VERSION_MAJOR_NO (19) +/*!< Firmware Major release version number. +*/ + + +#define M2M_RELEASE_VERSION_MINOR_NO (5) +/*!< Firmware Minor release version number. +*/ + +#define M2M_RELEASE_VERSION_PATCH_NO (2) +/*!< Firmware patch release version number. +*/ + +/*======*======*======*======* + SUPPORTED DRIVER VERSION NO INFO + *======*======*======*======*/ + +#define M2M_MIN_REQ_DRV_VERSION_MAJOR_NO (19) +/*!< Driver Major release version number. +*/ + + +#define M2M_MIN_REQ_DRV_VERSION_MINOR_NO (3) +/*!< Driver Minor release version number. +*/ + +#define M2M_MIN_REQ_DRV_VERSION_PATCH_NO (0) +/*!< Driver patch release version number. +*/ + +#define M2M_MIN_REQ_DRV_SVN_VERSION (0) +/*!< Driver svn version. +*/ + + + +#if !defined(M2M_RELEASE_VERSION_MAJOR_NO) || !defined(M2M_RELEASE_VERSION_MINOR_NO) +#error Undefined version number +#endif + +#define M2M_BUFFER_MAX_SIZE (1600UL - 4) +/*!< Maximum size for the shared packet buffer. + */ + + +#define M2M_MAC_ADDRES_LEN 6 +/*!< The size fo 802 MAC address. + */ + +#define M2M_ETHERNET_HDR_OFFSET 34 +/*!< The offset of the Ethernet header within the WLAN Tx Buffer. + */ + + +#define M2M_ETHERNET_HDR_LEN 14 +/*!< Length of the Etherenet header in bytes. +*/ + + +#define M2M_MAX_SSID_LEN 33 +/*!< Maximum size for the Wi-Fi SSID including the NULL termination. + */ + + +#define M2M_MAX_PSK_LEN 65 +/*!< Maximum size for the WPA PSK including the NULL termination. + */ + +#define M2M_MIN_PSK_LEN 9 +/*!< Maximum size for the WPA PSK including the NULL termination. + */ + +#define M2M_DEVICE_NAME_MAX 48 +/*!< Maximum Size for the device name including the NULL termination. + */ + + +#define M2M_LISTEN_INTERVAL 1 +/*!< The STA uses the Listen Interval parameter to indicate to the AP how + many beacon intervals it shall sleep before it retrieves the queued frames + from the AP. +*/ + +#define MAX_HIDDEN_SITES 4 +/*!< + max number of hidden SSID suuported by scan request +*/ + + +#define M2M_1X_USR_NAME_MAX 21 +/*!< The maximum size of the user name including the NULL termination. + It is used for RADIUS authentication in case of connecting the device to + an AP secured with WPA-Enterprise. +*/ + + +#define M2M_1X_PWD_MAX 41 +/*!< The maximum size of the password including the NULL termination. + It is used for RADIUS authentication in case of connecting the device to + an AP secured with WPA-Enterprise. +*/ + +#define M2M_CUST_IE_LEN_MAX 252 +/*!< The maximum size of IE (Information Element). +*/ + +#define PWR_DEFAULT PWR_HIGH +/********************* + * + * WIFI GROUP requests + */ + +#define M2M_CONFIG_CMD_BASE 1 +/*!< The base value of all the host configuration commands opcodes. +*/ +#define M2M_STA_CMD_BASE 40 +/*!< The base value of all the station mode host commands opcodes. +*/ +#define M2M_AP_CMD_BASE 70 +/*!< The base value of all the Access Point mode host commands opcodes. +*/ +#define M2M_P2P_CMD_BASE 90 +/*!< The base value of all the P2P mode host commands opcodes. +*/ +#define M2M_SERVER_CMD_BASE 100 +/*!< The base value of all the power save mode host commands codes. +*/ +/********************** + * OTA GROUP requests + */ +#define M2M_OTA_CMD_BASE 100 +/*!< The base value of all the OTA mode host commands opcodes. + * The OTA Have special group so can extended from 1-M2M_MAX_GRP_NUM_REQ +*/ +/*********************** + * + * CRYPTO group requests + */ +#define M2M_CRYPTO_CMD_BASE 1 +/*!< The base value of all the crypto mode host commands opcodes. + * The crypto Have special group so can extended from 1-M2M_MAX_GRP_NUM_REQ +*/ + +#define M2M_MAX_GRP_NUM_REQ (127) +/*!< max number of request in one group equal to 127 as the last bit reserved for config or data pkt +*/ + +#define WEP_40_KEY_STRING_SIZE ((uint8)10) +/*!< Indicate the wep key size in bytes for 40 bit string passphrase. +*/ + +#define WEP_104_KEY_STRING_SIZE ((uint8)26) +/*!< Indicate the wep key size in bytes for 104 bit string passphrase. +*/ +#define WEP_KEY_MAX_INDEX ((uint8)4) +/*!< Indicate the max key index value for WEP authentication +*/ +#define M2M_SHA256_CONTEXT_BUFF_LEN (128) +/*!< sha256 context size +*/ +#define M2M_SCAN_DEFAULT_NUM_SLOTS (2) +/*!< The default. number of scan slots performed by the WINC board. +*/ +#define M2M_SCAN_DEFAULT_SLOT_TIME (30) +/*!< The default. duration in miliseconds of a scan slots performed by the WINC board. +*/ +#define M2M_SCAN_DEFAULT_NUM_PROBE (2) +/*!< The default. number of scan slots performed by the WINC board. +*/ + + +/*======*======*======*======* + CONNECTION ERROR DEFINITIONS + *======*======*======*======*/ +typedef enum { + M2M_DEFAULT_CONN_INPROGRESS = ((sint8)-23), + /*!< + A failure that indicates that a default connection or forced connection is in progress + */ + M2M_DEFAULT_CONN_FAIL, + /*!< + A failure response that indicates that the winc failed to connect to the cached network + */ + M2M_DEFAULT_CONN_SCAN_MISMATCH, + /*!< + A failure response that indicates that no one of the cached networks + was found in the scan results, as a result to the function call m2m_default_connect. + */ + M2M_DEFAULT_CONN_EMPTY_LIST + /*!< + A failure response that indicates an empty network list as + a result to the function call m2m_default_connect. + */ + +}tenuM2mDefaultConnErrcode; + + + +/*======*======*======*======* + TLS DEFINITIONS + *======*======*======*======*/ +#define TLS_FILE_NAME_MAX 48 +/*!< Maximum length for each TLS certificate file name including null terminator. +*/ +#define TLS_SRV_SEC_MAX_FILES 8 +/*!< Maximum number of certificates allowed in TLS_SRV section. +*/ +#define TLS_SRV_SEC_START_PATTERN_LEN 8 +/*!< Length of certificate struct start pattern. +*/ +/*======*======*======*======* + OTA DEFINITIONS + *======*======*======*======*/ + +#define OTA_STATUS_VALID (0x12526285) +/*!< + Magic value updated in the Control structure in case of ROLLACK image Valid +*/ +#define OTA_STATUS_INVALID (0x23987718) +/*!< + Magic value updated in the Control structure in case of ROLLACK image InValid +*/ +#define OTA_MAGIC_VALUE (0x1ABCDEF9) +/*!< + Magic value set at the beginning of the OTA image header +*/ +#define M2M_MAGIC_APP (0xef522f61UL) +/*!< + Magic value set at the beginning of the Cortus OTA image header +*/ + +#define OTA_FORMAT_VER_0 (0) /*Till 19.2.2 format*/ +#define OTA_FORMAT_VER_1 (1) /*starting from 19.3.0 CRC is used and sequence number is used*/ +/*!< + Control structure format version +*/ +#define OTA_SHA256_DIGEST_SIZE (32) +/*!< + Sha256 digest size in the OTA image, + the sha256 digest is set at the beginning of image before the OTA header + */ + +/*======*======*======*======* + SSL DEFINITIONS + *======*======*======*======*/ + +#define TLS_CRL_DATA_MAX_LEN 64 +/* Every bit have 3dB gain control each. + for example: + 1 ->3db + 3 ->6db + 7 ->9db + */ + uint16 u8PPAGFor11GN; + /*!< PPA gain for 11GN (as the RF document represented) + PPA_AGC<0:2> Every bit have 3dB gain control each. + for example: + 1 ->3db + 3 ->6db + 7 ->9db + */ +}tstrM2mWifiGainsParams; + +/*! +@struct \ + tstrM2mWifiWepParams + +@brief + WEP security key parameters. +*/ +typedef struct{ + uint8 u8KeyIndx; + /*!< Wep key Index. + */ + uint8 u8KeySz; + /*!< Wep key Size. + */ + uint8 au8WepKey[WEP_104_KEY_STRING_SIZE + 1]; + /*!< WEP Key represented as a NULL terminated ASCII string. + */ + uint8 __PAD24__[3]; + /*!< Padding bytes to keep the structure word alligned. + */ +}tstrM2mWifiWepParams; + + +/*! +@struct \ + tstr1xAuthCredentials + +@brief + Credentials for the user to authenticate with the AAA server (WPA-Enterprise Mode IEEE802.1x). +*/ +typedef struct{ + uint8 au8UserName[M2M_1X_USR_NAME_MAX]; + /*!< User Name. It must be Null terminated string. + */ + uint8 au8Passwd[M2M_1X_PWD_MAX]; + /*!< Password corresponding to the user name. It must be Null terminated string. + */ +}tstr1xAuthCredentials; + + +/*! +@union \ + tuniM2MWifiAuth + +@brief + Wi-Fi Security Parameters for all supported security modes. +*/ +typedef union{ + uint8 au8PSK[M2M_MAX_PSK_LEN]; + /*!< Pre-Shared Key in case of WPA-Personal security. + */ + tstr1xAuthCredentials strCred1x; + /*!< Credentials for RADIUS server authentication in case of WPA-Enterprise security. + */ + tstrM2mWifiWepParams strWepInfo; + /*!< WEP key parameters in case of WEP security. + */ +}tuniM2MWifiAuth; + + +/*! +@struct \ + tstrM2MWifiSecInfo + +@brief + Authentication credentials to connect to a Wi-Fi network. +*/ +typedef struct{ + tuniM2MWifiAuth uniAuth; + /*!< Union holding all possible authentication parameters corresponding the current security types. + */ + uint8 u8SecType; + /*!< Wi-Fi network security type. See tenuM2mSecType for supported security types. + */ +#define __PADDING__ (4 - ((sizeof(tuniM2MWifiAuth) + 1) % 4)) + uint8 __PAD__[__PADDING__]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2MWifiSecInfo; + + +/*! +@struct \ + tstrM2mWifiConnect + +@brief + Wi-Fi Connect Request +*/ +typedef struct{ + tstrM2MWifiSecInfo strSec; + /*!< Security parameters for authenticating with the AP. + */ + uint16 u16Ch; + /*!< RF Channel for the target SSID. + */ + uint8 au8SSID[M2M_MAX_SSID_LEN]; + /*!< SSID of the desired AP. It must be NULL terminated string. + */ + uint8 u8NoSaveCred; +#define __CONN_PAD_SIZE__ (4 - ((sizeof(tstrM2MWifiSecInfo) + M2M_MAX_SSID_LEN + 3) % 4)) + uint8 __PAD__[__CONN_PAD_SIZE__]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mWifiConnect; + + +/*! +@struct \ + tstrM2MWPSConnect + +@brief + WPS Configuration parameters + +@sa + tenuWPSTrigger +*/ +typedef struct { + uint8 u8TriggerType; + /*!< WPS triggering method (Push button or PIN) + */ + char acPinNumber[8]; + /*!< WPS PIN No (for PIN method) + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2MWPSConnect; + + +/*! +@struct \ + tstrM2MWPSInfo + +@brief WPS Result + + This structure is passed to the application in response to a WPS request. If the WPS session is completed successfully, the + structure will have Non-ZERO authentication type. If the WPS Session fails (due to error or timeout) the authentication type + is set to ZERO. + +@sa + tenuM2mSecType +*/ +typedef struct{ + uint8 u8AuthType; + /*!< Network authentication type. + */ + uint8 u8Ch; + /*!< RF Channel for the AP. + */ + uint8 au8SSID[M2M_MAX_SSID_LEN]; + /*!< SSID obtained from WPS. + */ + uint8 au8PSK[M2M_MAX_PSK_LEN]; + /*!< PSK for the network obtained from WPS. + */ +}tstrM2MWPSInfo; + + +/*! +@struct \ + tstrM2MDefaultConnResp + +@brief + Response error of the m2m_default_connect + +@sa + M2M_DEFAULT_CONN_SCAN_MISMATCH + M2M_DEFAULT_CONN_EMPTY_LIST +*/ +typedef struct{ + sint8 s8ErrorCode; + /*!< + Default connect error code. possible values are: + - M2M_DEFAULT_CONN_EMPTY_LIST + - M2M_DEFAULT_CONN_SCAN_MISMATCH + */ + uint8 __PAD24__[3]; +}tstrM2MDefaultConnResp; + +/*! +@struct \ + tstrM2MScanOption + +@brief + Scan options and configurations. + +@sa + tenuM2mScanCh + tstrM2MScan +*/ +typedef struct { + uint8 u8NumOfSlot; + /*|< The min number of slots is 2 for every channel, + every slot the soc will send Probe Request on air, and wait/listen for PROBE RESP/BEACONS for the u16slotTime + */ + uint8 u8SlotTime; + /*|< the time that the Soc will wait on every channel listening to the frames on air + when that time increaseed number of AP will increased in the scan results + min time is 10 ms and the max is 250 ms + */ + uint8 u8ProbesPerSlot; + /*!< Number of probe requests to be sent per channel scan slot. + */ + sint8 s8RssiThresh; + /*! < The RSSI threshold of the AP which will be connected to directly. + */ + +}tstrM2MScanOption; + +/*! +@struct \ + tstrM2MScanRegion + +@brief + Wi-Fi channel regulation region information. + +@sa + tenuM2mScanRegion +*/ +typedef struct { + uint16 u16ScanRegion; + /*|< Specifies the number of channels allowed in the region (e.g. North America = 11 ... etc.). + */ + uint8 __PAD16__[2]; + +}tstrM2MScanRegion; + +/*! +@struct \ + tstrM2MScan + +@brief + Wi-Fi Scan Request + +@sa + tenuM2mScanCh + tstrM2MScanOption +*/ +typedef struct { + uint8 u8ChNum; + /*!< The Wi-Fi RF Channel number + */ + uint8 __RSVD8__[1]; + /*!< Reserved for future use. + */ + uint16 u16PassiveScanTime; + /*!< Passive Scan Timeout in ms. The field is ignored for active scan. + */ +}tstrM2MScan; + +/*! +@struct \ + tstrCyptoResp + +@brief + crypto response +*/ +typedef struct { + sint8 s8Resp; + /***/ + uint8 __PAD24__[3]; + /* + */ +}tstrCyptoResp; + + +/*! +@struct \ + tstrM2mScanDone + +@brief + Wi-Fi Scan Result +*/ +typedef struct{ + uint8 u8NumofCh; + /*!< Number of found APs + */ + sint8 s8ScanState; + /*!< Scan status + */ + uint8 __PAD16__[2]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mScanDone; + + +/*! +@struct \ + tstrM2mReqScanResult + +@brief Scan Result Request + + The Wi-Fi Scan results list is stored in Firmware. The application can request a certain scan result by its index. +*/ +typedef struct { + uint8 u8Index; + /*!< Index of the desired scan result + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mReqScanResult; + + +/*! +@struct \ + tstrM2mWifiscanResult + +@brief Wi-Fi Scan Result + + Information corresponding to an AP in the Scan Result list identified by its order (index) in the list. +*/ +typedef struct { + uint8 u8index; + /*!< AP index in the scan result list. + */ + sint8 s8rssi; + /*!< AP signal strength. + */ + uint8 u8AuthType; + /*!< AP authentication type. + */ + uint8 u8ch; + /*!< AP RF channel. + */ + uint8 au8BSSID[6]; + /*!< BSSID of the AP. + */ + uint8 au8SSID[M2M_MAX_SSID_LEN]; + /*!< AP ssid. + */ + uint8 _PAD8_; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mWifiscanResult; + + +/*! +@struct \ + tstrM2mWifiStateChanged + +@brief + Wi-Fi Connection State + +@sa + M2M_WIFI_DISCONNECTED, M2M_WIFI_CONNECTED, M2M_WIFI_REQ_CON_STATE_CHANGED,tenuM2mConnChangedErrcode +*/ +typedef struct { + uint8 u8CurrState; + /*!< Current Wi-Fi connection state + */ + uint8 u8ErrCode; + /*!< Error type review tenuM2mConnChangedErrcode + */ + uint8 __PAD16__[2]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mWifiStateChanged; + + +/*! +@struct \ + tstrM2mPsType + +@brief + Power Save Configuration + +@sa + tenuPowerSaveModes +*/ +typedef struct{ + uint8 u8PsType; + /*!< Power save operating mode + */ + uint8 u8BcastEn; + /*!< + */ + uint8 __PAD16__[2]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mPsType; + +/*! +@struct \ + tstrM2mSlpReqTime + +@brief + Manual power save request sleep time + +*/ +typedef struct { + /*!< Sleep time in ms + */ + uint32 u32SleepTime; + +} tstrM2mSlpReqTime; + +/*! +@struct \ + tstrM2mLsnInt + +@brief Listen interval + + It is the value of the Wi-Fi STA listen interval for power saving. It is given in units of Beacon period. + Periodically after the listen interval fires, the WINC is wakeup and listen to the beacon and check for any buffered frames for it from the AP. +*/ +typedef struct { + uint16 u16LsnInt; + /*!< Listen interval in Beacon period count. + */ + uint8 __PAD16__[2]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mLsnInt; + + +/*! +@struct \ + tstrM2MWifiMonitorModeCtrl + +@brief Wi-Fi Monitor Mode Filter + + This structure sets the filtering criteria for WLAN packets when monitoring mode is enable. + The received packets matching the filtering parameters, are passed directly to the application. +*/ +typedef struct{ + uint8 u8ChannelID; + /* !< RF Channel ID. It must use values from tenuM2mScanCh + */ + uint8 u8FrameType; + /*!< It must use values from tenuWifiFrameType. + */ + uint8 u8FrameSubtype; + /*!< It must use values from tenuSubTypes. + */ + uint8 au8SrcMacAddress[6]; + /* ZERO means DO NOT FILTER Source address. + */ + uint8 au8DstMacAddress[6]; + /* ZERO means DO NOT FILTER Destination address. + */ + uint8 au8BSSID[6]; + /* ZERO means DO NOT FILTER BSSID. + */ + uint8 u8EnRecvHdr; + /* + Enable recv the full hder before the payload + */ + uint8 __PAD16__[2]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2MWifiMonitorModeCtrl; + + +/*! +@struct \ + tstrM2MWifiRxPacketInfo + +@brief Wi-Fi RX Frame Header + + The M2M application has the ability to allow Wi-Fi monitoring mode for receiving all Wi-Fi Raw frames matching a well defined filtering criteria. + When a target Wi-Fi packet is received, the header information are extracted and assigned in this structure. +*/ +typedef struct{ + uint8 u8FrameType; + /*!< It must use values from tenuWifiFrameType. + */ + uint8 u8FrameSubtype; + /*!< It must use values from tenuSubTypes. + */ + uint8 u8ServiceClass; + /*!< Service class from Wi-Fi header. + */ + uint8 u8Priority; + /*!< Priority from Wi-Fi header. + */ + uint8 u8HeaderLength; + /*!< Frame Header length. + */ + uint8 u8CipherType; + /*!< Encryption type for the rx packet. + */ + uint8 au8SrcMacAddress[6]; + /* ZERO means DO NOT FILTER Source address. + */ + uint8 au8DstMacAddress[6]; + /* ZERO means DO NOT FILTER Destination address. + */ + uint8 au8BSSID[6]; + /* ZERO means DO NOT FILTER BSSID. + */ + uint16 u16DataLength; + /*!< Data payload length (Header excluded). + */ + uint16 u16FrameLength; + /*!< Total frame length (Header + Data). + */ + uint32 u32DataRateKbps; + /*!< Data Rate in Kbps. + */ + sint8 s8RSSI; + /*!< RSSI. + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2MWifiRxPacketInfo; + + +/*! +@struct \ + tstrM2MWifiTxPacketInfo + +@brief Wi-Fi TX Packet Info + + The M2M Application has the ability to compose a RAW Wi-Fi frames (under the application responsibility). + When transmitting a Wi-Fi packet, the application must supply the firmware with this structure for sending the target frame. +*/ +typedef struct{ + uint16 u16PacketSize; + /*!< Wlan frame length. + */ + uint16 u16HeaderLength; + /*!< Wlan frame header length. + */ +}tstrM2MWifiTxPacketInfo; + + +/*! + @struct \ + tstrM2MP2PConnect + + @brief + Set the device to operate in the Wi-Fi Direct (P2P) mode. +*/ +typedef struct { + uint8 u8ListenChannel; + /*!< P2P Listen Channel (1, 6 or 11) + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2MP2PConnect; + +/*! +@struct \ + tstrM2MAPConfig + +@brief AP Configuration + + This structure holds the configuration parameters for the M2M AP mode. It should be set by the application when + it requests to enable the M2M AP operation mode. The M2M AP mode currently supports only WEP security (with + the NO Security option available of course). +*/ +typedef struct { + /*!< + Configuration parameters for the WiFi AP. + */ + uint8 au8SSID[M2M_MAX_SSID_LEN]; + /*!< AP SSID + */ + uint8 u8ListenChannel; + /*!< Wi-Fi RF Channel which the AP will operate on + */ + uint8 u8KeyIndx; + /*!< Wep key Index + */ + uint8 u8KeySz; + /*!< Wep/WPA key Size + */ + uint8 au8WepKey[WEP_104_KEY_STRING_SIZE + 1]; + /*!< Wep key + */ + uint8 u8SecType; + /*!< Security type: Open or WEP or WPA in the current implementation + */ + uint8 u8SsidHide; + /*!< SSID Status "Hidden(1)/Visible(0)" + */ + uint8 au8DHCPServerIP[4]; + /*!< Ap IP server address + */ + uint8 au8Key[M2M_MAX_PSK_LEN]; + /*!< WPA key + */ + uint8 __PAD24__[2]; + /*!< Padding bytes for forcing alignment + */ +}tstrM2MAPConfig; + + +/*! +@struct \ + tstrM2mServerInit + +@brief + PS Server initialization. +*/ +typedef struct { + uint8 u8Channel; + /*!< Server Listen channel + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mServerInit; + + +/*! +@struct \ + tstrM2mClientState + +@brief + PS Client State. +*/ +typedef struct { + uint8 u8State; + /*!< PS Client State + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mClientState; + + +/*! +@struct \ + tstrM2Mservercmd + +@brief + PS Server CMD +*/ +typedef struct { + uint8 u8cmd; + /*!< PS Server Cmd + */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2Mservercmd; + + +/*! +@struct \ + tstrM2mSetMacAddress + +@brief + Sets the MAC address from application. The WINC load the mac address from the effuse by default to the WINC configuration memory, + but that function is used to let the application overwrite the configuration memory with the mac address from the host. + +@note + It's recommended to call this only once before calling connect request and after the m2m_wifi_init +*/ +typedef struct { + uint8 au8Mac[6]; + /*!< MAC address array + */ + uint8 __PAD16__[2]; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2mSetMacAddress; + + +/*! +@struct \ + tstrM2MDeviceNameConfig + +@brief Device name + + It is assigned by the application. It is used mainly for Wi-Fi Direct device + discovery and WPS device information. +*/ +typedef struct { + uint8 au8DeviceName[M2M_DEVICE_NAME_MAX]; + /*!< NULL terminated device name + */ +}tstrM2MDeviceNameConfig; + + +/*! +@struct \ + tstrM2MIPConfig + +@brief + Static IP configuration. + +@note + All member IP addresses are expressed in Network Byte Order (eg. "192.168.10.1" will be expressed as 0x010AA8C0). + */ +typedef struct { + uint32 u32StaticIP; + /*!< The static IP assigned to the device. + */ + uint32 u32Gateway; + /*!< IP of the Default internet gateway. + */ + uint32 u32DNS; + /*!< IP for the DNS server. + */ + uint32 u32SubnetMask; + /*!< Subnet mask for the local area network. + */ + uint32 u32DhcpLeaseTime; + /*!< Dhcp Lease Time in sec + */ +} tstrM2MIPConfig; + +/*! +@struct \ + tstrM2mIpRsvdPkt + +@brief + Received Packet Size and Data Offset + + */ +typedef struct{ + uint16 u16PktSz; + uint16 u16PktOffset; +} tstrM2mIpRsvdPkt; + + +/*! +@struct \ + tstrM2MProvisionModeConfig + +@brief + M2M Provisioning Mode Configuration + */ + +typedef struct { + tstrM2MAPConfig strApConfig; + /*!< + Configuration parameters for the WiFi AP. + */ + char acHttpServerDomainName[64]; + /*!< + The device domain name for HTTP provisioning. + */ + uint8 u8EnableRedirect; + /*!< + A flag to enable/disable HTTP redirect feature for the HTTP Provisioning server. If the Redirect is enabled, + all HTTP traffic (http://URL) from the device associated with WINC AP will be redirected to the HTTP Provisioning Web page. + - 0 : Disable HTTP Redirect. + - 1 : Enable HTTP Redirect. + */ + uint8 __PAD24__[3]; +}tstrM2MProvisionModeConfig; + + +/*! +@struct \ + tstrM2MProvisionInfo + +@brief + M2M Provisioning Information obtained from the HTTP Provisioning server. + */ +typedef struct{ + uint8 au8SSID[M2M_MAX_SSID_LEN]; + /*!< + Provisioned SSID. + */ + uint8 au8Password[M2M_MAX_PSK_LEN]; + /*!< + Provisioned Password. + */ + uint8 u8SecType; + /*!< + Wifi Security type. + */ + uint8 u8Status; + /*!< + Provisioning status. It must be checked before reading the provisioning information. It may be + - M2M_SUCCESS : Provision successful. + - M2M_FAIL : Provision Failed. + */ +}tstrM2MProvisionInfo; + + +/*! +@struct \ + tstrM2MConnInfo + +@brief + M2M Provisioning Information obtained from the HTTP Provisioning server. + */ +typedef struct{ + char acSSID[M2M_MAX_SSID_LEN]; + /*!< AP connection SSID name */ + uint8 u8SecType; + /*!< Security type */ + uint8 au8IPAddr[4]; + /*!< Connection IP address */ + uint8 au8MACAddress[6]; + /*!< MAC address of the peer Wi-Fi station */ + sint8 s8RSSI; + /*!< Connection RSSI signal */ + uint8 __PAD24__[3]; + /*!< Padding bytes for forcing 4-byte alignment */ +}tstrM2MConnInfo; + +/*! +@struct \ + tstrOtaInitHdr + +@brief + OTA Image Header + */ + +typedef struct{ + uint32 u32OtaMagicValue; + /*!< Magic value kept in the OTA image after the + sha256 Digest buffer to define the Start of OTA Header */ + uint32 u32OtaPayloadSzie; + /*!< + The Total OTA image payload size, include the sha256 key size + */ + +}tstrOtaInitHdr; + + +/*! +@struct \ + tstrOtaControlSec + +@brief + Control section structure is used to define the working image and + the validity of the roll-back image and its offset, also both firmware versions is kept in that structure. + */ + +typedef struct { + uint32 u32OtaMagicValue; +/*!< + Magic value used to ensure the structure is valid or not +*/ + uint32 u32OtaFormatVersion; +/*!< + NA NA NA Flash version cs struct version + 00 00 00 00 00 + Control structure format version, the value will be incremented in case of structure changed or updated +*/ + uint32 u32OtaSequenceNumber; +/*!< + Sequence number is used while update the control structure to keep track of how many times that section updated +*/ + uint32 u32OtaLastCheckTime; +/*!< + Last time OTA check for update +*/ + uint32 u32OtaCurrentworkingImagOffset; +/*!< + Current working offset in flash +*/ + uint32 u32OtaCurrentworkingImagFirmwareVer; +/*!< + current working image version ex 18.0.1 +*/ + uint32 u32OtaRollbackImageOffset; +/*!< + Roll-back image offset in flash +*/ + uint32 u32OtaRollbackImageValidStatus; +/*!< + roll-back image valid status +*/ + uint32 u32OtaRollbackImagFirmwareVer; +/*!< + Roll-back image version (ex 18.0.3) +*/ + uint32 u32OtaCortusAppWorkingOffset; +/*!< + cortus app working offset in flash +*/ + uint32 u32OtaCortusAppWorkingValidSts; +/*!< + Working Cortus app valid status +*/ + uint32 u32OtaCortusAppWorkingVer; +/*!< + Working cortus app version (ex 18.0.3) +*/ + uint32 u32OtaCortusAppRollbackOffset; +/*!< + cortus app rollback offset in flash +*/ + uint32 u32OtaCortusAppRollbackValidSts; +/*!< + roll-back cortus app valid status +*/ + uint32 u32OtaCortusAppRollbackVer; +/*!< + Roll-back cortus app version (ex 18.0.3) +*/ + uint32 u32OtaControlSecCrc; +/*!< + CRC for the control structure to ensure validity +*/ +} tstrOtaControlSec; + +/*! +@enum \ + tenuOtaUpdateStatus + +@brief + OTA return status +*/ +typedef enum { + OTA_STATUS_SUCSESS = 0, + /*!< OTA Success with not errors. */ + OTA_STATUS_FAIL = 1, + /*!< OTA generic fail. */ + OTA_STATUS_INVAILD_ARG = 2, + /*!< Invalid or malformed download URL. */ + OTA_STATUS_INVAILD_RB_IMAGE = 3, + /*!< Invalid rollback image. */ + OTA_STATUS_INVAILD_FLASH_SIZE = 4, + /*!< Flash size on device is not enough for OTA. */ + OTA_STATUS_AlREADY_ENABLED = 5, + /*!< An OTA operation is already enabled. */ + OTA_STATUS_UPDATE_INPROGRESS = 6, + /*!< An OTA operation update is in progress */ + OTA_STATUS_IMAGE_VERIF_FAILED = 7, + /*!< OTA Verfication failed */ + OTA_STATUS_CONNECTION_ERROR = 8, + /*!< OTA connection error */ + OTA_STATUS_SERVER_ERROR = 9, + /*!< OTA server Error (file not found or else ...) */ + OTA_STATUS_ABORTED = 10 + /*!< OTA download has been aborted by the application. */ +} tenuOtaUpdateStatus; +/*! +@enum \ + tenuOtaUpdateStatusType + +@brief + OTA update Status type +*/ +typedef enum { + + DL_STATUS = 1, + /*!< Download OTA file status + */ + SW_STATUS = 2, + /*!< Switching to the upgrade firmware status + */ + RB_STATUS = 3, + /*!< Roll-back status + */ + AB_STATUS = 4 + /*!< Abort status + */ +}tenuOtaUpdateStatusType; + + +/*! +@struct \ + tstrOtaUpdateStatusResp + +@brief + OTA Update Information + +@sa + tenuWPSTrigger +*/ +typedef struct { + uint8 u8OtaUpdateStatusType; + /*!< + Status type tenuOtaUpdateStatusType + */ + uint8 u8OtaUpdateStatus; + /*!< + OTA_SUCCESS + OTA_ERR_WORKING_IMAGE_LOAD_FAIL + OTA_ERR_INVAILD_CONTROL_SEC + M2M_ERR_OTA_SWITCH_FAIL + M2M_ERR_OTA_START_UPDATE_FAIL + M2M_ERR_OTA_ROLLBACK_FAIL + M2M_ERR_OTA_INVAILD_FLASH_SIZE + M2M_ERR_OTA_INVAILD_ARG + */ + uint8 _PAD16_[2]; +}tstrOtaUpdateStatusResp; + +/*! +@struct \ + tstrOtaUpdateInfo + +@brief + OTA Update Information + +@sa + tenuWPSTrigger +*/ +typedef struct { + uint32 u8NcfUpgradeVersion; + /*!< NCF OTA Upgrade Version + */ + uint32 u8NcfCurrentVersion; + /*!< NCF OTA Current firmware version + */ + uint32 u8NcdUpgradeVersion; + /*!< NCD (host) upgraded version (if the u8NcdRequiredUpgrade == true) + */ + uint8 u8NcdRequiredUpgrade; + /*!< NCD Required upgrade to the above version + */ + uint8 u8DownloadUrlOffset; + /*!< Download URL offset in the received packet + */ + uint8 u8DownloadUrlSize; + /*!< Download URL size in the received packet + */ + uint8 __PAD8__; + /*!< Padding bytes for forcing 4-byte alignment + */ +} tstrOtaUpdateInfo; + +/*! +@struct \ + tstrSystemTime + +@brief + Used for time storage. +*/ +typedef struct{ + uint16 u16Year; + uint8 u8Month; + uint8 u8Day; + uint8 u8Hour; + uint8 u8Minute; + uint8 u8Second; + uint8 __PAD8__; +}tstrSystemTime; + +/*! +@struct \ + tstrM2MMulticastMac + +@brief + M2M add/remove multi-cast mac address + */ + typedef struct { + uint8 au8macaddress[M2M_MAC_ADDRES_LEN]; + /*!< + Mac address needed to be added or removed from filter. + */ + uint8 u8AddRemove; + /*!< + set by 1 to add or 0 to remove from filter. + */ + uint8 __PAD8__; + /*!< Padding bytes for forcing 4-byte alignment + */ +}tstrM2MMulticastMac; + +/*! +@struct \ + tstrPrng + +@brief + M2M Request PRNG + */ + typedef struct { + /*!< + return buffer address + */ + uint8 *pu8RngBuff; + /*!< + PRNG size requested + */ + uint16 u16PrngSize; + /*!< + PRNG pads + */ + uint8 __PAD16__[2]; +}tstrPrng; + +/* + * TLS certificate revocation list + * Typedefs common between fw and host + */ + +/*! +@struct \ + tstrTlsCrlEntry + +@brief + Certificate data for inclusion in a revocation list (CRL) +*/ +typedef struct { + uint8 u8DataLen; + /*!< + Length of certificate data (maximum possible is @ref TLS_CRL_DATA_MAX_LEN) + */ + uint8 au8Data[TLS_CRL_DATA_MAX_LEN]; + /*!< + Certificate data + */ + uint8 __PAD24__[3]; + /*!< + Padding bytes for forcing 4-byte alignment + */ +}tstrTlsCrlEntry; + +/*! +@struct \ + tstrTlsCrlInfo + +@brief + Certificate revocation list details +*/ +typedef struct { + uint8 u8CrlType; + /*!< + Type of certificate data contained in list + */ + uint8 u8Rsv1; + /*!< + Reserved for future use + */ + uint8 u8Rsv2; + /*!< + Reserved for future use + */ + uint8 u8Rsv3; + /*!< + Reserved for future use + */ + tstrTlsCrlEntry astrTlsCrl[TLS_CRL_MAX_ENTRIES]; + /*!< + List entries + */ +}tstrTlsCrlInfo; + + /*! +@enum\ + tenuSslCertExpSettings + +@brief SSL Certificate Expiry Validation Options +*/ +typedef enum{ + SSL_CERT_EXP_CHECK_DISABLE, + /*!< + ALWAYS OFF. + Ignore certificate expiration date validation. If a certificate is + expired or there is no configured system time, the SSL connection SUCCEEDs. + */ + SSL_CERT_EXP_CHECK_ENABLE, + /*!< + ALWAYS ON. + Validate certificate expiration date. If a certificate is expired or + there is no configured system time, the SSL connection FAILs. + */ + SSL_CERT_EXP_CHECK_EN_IF_SYS_TIME + /*!< + CONDITIONAL VALIDATION (Default setting at startup). + Validate the certificate expiration date only if there is a configured system time. + If there is no configured system time, the certificate expiration is bypassed and the + SSL connection SUCCEEDs. + */ +}tenuSslCertExpSettings; + + +/*! +@struct \ + tstrTlsSrvSecFileEntry + +@brief + This struct contains a TLS certificate. + */ +typedef struct{ + char acFileName[TLS_FILE_NAME_MAX]; + /*!< Name of the certificate. */ + uint32 u32FileSize; + /*!< Size of the certificate. */ + uint32 u32FileAddr; + /*!< Error Code. */ +}tstrTlsSrvSecFileEntry; + +/*! +@struct \ + tstrTlsSrvSecHdr + +@brief + This struct contains a set of TLS certificates. + */ +typedef struct{ + uint8 au8SecStartPattern[TLS_SRV_SEC_START_PATTERN_LEN]; + /*!< Start pattern. */ + uint32 u32nEntries; + /*!< Number of certificates stored in the struct. */ + uint32 u32NextWriteAddr; + /*!< TLS Certificates. */ + tstrTlsSrvSecFileEntry astrEntries[TLS_SRV_SEC_MAX_FILES]; +}tstrTlsSrvSecHdr; + +typedef struct{ + uint32 u32CsBMP; +}tstrSslSetActiveCsList; + + + /**@}*/ + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_wifi.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_wifi.h new file mode 100644 index 0000000..3477196 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_wifi.h @@ -0,0 +1,2882 @@ +/** + * + * \file + * + * \brief WINC WLAN Application Interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef __M2M_WIFI_H__ +#define __M2M_WIFI_H__ + +/** \defgroup m2m_wifi WLAN + * + */ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "common/include/nm_common.h" +#include "driver/include/m2m_types.h" +#include "driver/source/nmdrv.h" + +#ifdef CONF_MGMT + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/**@defgroup WlanEnums DataTypes + * @ingroup m2m_wifi + * @{*/ +/*! +@enum \ + tenuWifiFrameType + +@brief + Enumeration for Wi-Fi MAC frame type codes (2-bit) + The following types are used to identify the type of frame sent or received. + Each frame type constitutes a number of frame subtypes as defined in @ref tenuSubTypes to specify the exact type of frame. + Values are defined as per the IEEE 802.11 standard. + +@remarks + The following frame types are useful for advanced user usage when monitoring mode is used (defining @ref CONF_MGMT) + and the user application requires to monitor the frame transmission and reception. +@see + tenuSubTypes +*/ +typedef enum { + MANAGEMENT = 0x00, + /*!< Wi-Fi Management frame (Probe Req/Resp, Beacon, Association Req/Resp ...etc). + */ + CONTROL = 0x04, + /*!< Wi-Fi Control frame (eg. ACK frame). + */ + DATA_BASICTYPE = 0x08, + /*!< Wi-Fi Data frame. + */ + RESERVED = 0x0C, + + M2M_WIFI_FRAME_TYPE_ANY = 0xFF +/*!< Set monitor mode to receive any of the frames types +*/ +}tenuWifiFrameType; + + +/*! +@enum \ + tenuSubTypes + +@brief + Enumeration for Wi-Fi MAC Frame subtype code (6-bit). + The frame subtypes fall into one of the three frame type groups as defined in @ref tenuWifiFrameType + (MANAGEMENT, CONTROL & DATA). + Values are defined as per the IEEE 802.11 standard. +@remarks + The following sub-frame types are useful for advanced user usage when @ref CONF_MGMT is defined + and the application developer requires to monitor the frame transmission and reception. +@see + tenuWifiFrameType + tstrM2MWifiMonitorModeCtrl +*/ +typedef enum { + /*!< Sub-Types related to Management Sub-Types */ + ASSOC_REQ = 0x00, + ASSOC_RSP = 0x10, + REASSOC_REQ = 0x20, + REASSOC_RSP = 0x30, + PROBE_REQ = 0x40, + PROBE_RSP = 0x50, + BEACON = 0x80, + ATIM = 0x90, + DISASOC = 0xA0, + AUTH = 0xB0, + DEAUTH = 0xC0, + ACTION = 0xD0, +/**@{*/ + /* Sub-Types related to Control */ + PS_POLL = 0xA4, + RTS = 0xB4, + CTS = 0xC4, + ACK = 0xD4, + CFEND = 0xE4, + CFEND_ACK = 0xF4, + BLOCKACK_REQ = 0x84, + BLOCKACK = 0x94, +/**@{*/ + /* Sub-Types related to Data */ + DATA = 0x08, + DATA_ACK = 0x18, + DATA_POLL = 0x28, + DATA_POLL_ACK = 0x38, + NULL_FRAME = 0x48, + CFACK = 0x58, + CFPOLL = 0x68, + CFPOLL_ACK = 0x78, + QOS_DATA = 0x88, + QOS_DATA_ACK = 0x98, + QOS_DATA_POLL = 0xA8, + QOS_DATA_POLL_ACK = 0xB8, + QOS_NULL_FRAME = 0xC8, + QOS_CFPOLL = 0xE8, + QOS_CFPOLL_ACK = 0xF8, + M2M_WIFI_FRAME_SUB_TYPE_ANY = 0xFF + /*!< Set monitor mode to receive any of the frames types + */ +}tenuSubTypes; + + +/*! +@enum \ + tenuInfoElementId + +@brief + Enumeration for the Wi-Fi Information Element(IE) IDs, which indicates the specific type of IEs. + IEs are management frame information included in management frames. + Values are defined as per the IEEE 802.11 standard. + +*/ +typedef enum { + ISSID = 0, + /*!< Service Set Identifier (SSID) + */ + ISUPRATES = 1, + /*!< Supported Rates + */ + IFHPARMS = 2, + /*!< FH parameter set + */ + IDSPARMS = 3, + /*!< DS parameter set + */ + ICFPARMS = 4, + /*!< CF parameter set + */ + ITIM = 5, + /*!< Traffic Information Map + */ + IIBPARMS = 6, + /*!< IBSS parameter set + */ + ICOUNTRY = 7, + /*!< Country element. + */ + IEDCAPARAMS = 12, + /*!< EDCA parameter set + */ + ITSPEC = 13, + /*!< Traffic Specification + */ + ITCLAS = 14, + /*!< Traffic Classification + */ + ISCHED = 15, + /*!< Schedule. + */ + ICTEXT = 16, + /*!< Challenge Text + */ + IPOWERCONSTRAINT = 32, + /*!< Power Constraint. + */ + IPOWERCAPABILITY = 33, + /*!< Power Capability + */ + ITPCREQUEST = 34, + /*!< TPC Request + */ + ITPCREPORT = 35, + /*!< TPC Report + */ + ISUPCHANNEL = 36, + /* Supported channel list + */ + ICHSWANNOUNC = 37, + /*!< Channel Switch Announcement + */ + IMEASUREMENTREQUEST = 38, + /*!< Measurement request + */ + IMEASUREMENTREPORT = 39, + /*!< Measurement report + */ + IQUIET = 40, + /*!< Quiet element Info + */ + IIBSSDFS = 41, + /*!< IBSS DFS + */ + IERPINFO = 42, + /*!< ERP Information + */ + ITSDELAY = 43, + /*!< TS Delay + */ + ITCLASPROCESS = 44, + /*!< TCLAS Processing + */ + IHTCAP = 45, + /*!< HT Capabilities + */ + IQOSCAP = 46, + /*!< QoS Capability + */ + IRSNELEMENT = 48, + /*!< RSN Information Element + */ + IEXSUPRATES = 50, + /*!< Extended Supported Rates + */ + IEXCHSWANNOUNC = 60, + /*!< Extended Ch Switch Announcement + */ + IHTOPERATION = 61, + /*!< HT Information + */ + ISECCHOFF = 62, + /*!< Secondary Channel Offset + */ + I2040COEX = 72, + /*!< 20/40 Coexistence IE + */ + I2040INTOLCHREPORT = 73, + /*!< 20/40 Intolerant channel report + */ + IOBSSSCAN = 74, + /*!< OBSS Scan parameters + */ + IEXTCAP = 127, + /*!< Extended capability + */ + IWMM = 221, + /*!< WMM parameters + */ + IWPAELEMENT = 221 + /*!< WPA Information Element + */ +}tenuInfoElementId; + + +/*! +@struct \ + tenuWifiCapability + +@brief + Enumeration for capability Information field bit. + The value of the capability information field from the 802.11 management frames received by the wireless LAN interface. + Defining the capabilities of the Wi-Fi system. Values are defined as per the IEEE 802.11 standard. + +@details + Capabilities:- + ESS/IBSS : Defines whether a frame is coming from an AP or not. + POLLABLE : CF Poll-able + POLLREQ : Request to be polled + PRIVACY : WEP encryption supported + SHORTPREAMBLE : Short Preamble is supported + SHORTSLOT : Short Slot is supported + PBCC :PBCC + CHANNELAGILITY :Channel Agility + SPECTRUM_MGMT :Spectrum Management + DSSS_OFDM : DSSS-OFDM +*/ +typedef enum{ + ESS = 0x01, + /*!< ESS capability + */ + IBSS = 0x02, + /*!< IBSS mode + */ + POLLABLE = 0x04, + /*!< CF Pollable + */ + POLLREQ = 0x08, + /*!< Request to be polled + */ + PRIVACY = 0x10, + /*!< WEP encryption supported + */ + SHORTPREAMBLE = 0x20, + /*!< Short Preamble is supported + */ + SHORTSLOT = 0x400, + /*!< Short Slot is supported + */ + PBCC = 0x40, + /*!< PBCC + */ + CHANNELAGILITY = 0x80, + /*!< Channel Agility + */ + SPECTRUM_MGMT = 0x100, + /*!< Spectrum Management + */ + DSSS_OFDM = 0x2000 + /*!< DSSS-OFDM + */ +}tenuWifiCapability; + + +#endif + +/*! +@typedef \ + tpfAppWifiCb + +@brief + Wi-Fi's main callback function handler, for handling the M2M_WIFI events received on the Wi-Fi interface. + Such notifications are received in response to Wi-Fi/P2P operations such as @ref m2m_wifi_request_scan, + @ref m2m_wifi_connect. + Wi-Fi/P2P operations are implemented in an asynchronous mode, and all incoming information/status + are to be handled through this callback function when the corresponding notification is received. + Applications are expected to assign this wi-fi callback function by calling @ref m2m_wifi_init +@param [in] u8MsgType + Type of notifications. Possible types are: + /ref M2M_WIFI_RESP_CON_STATE_CHANGED + /ref M2M_WIFI_RESP_CONN_INFO + /ref M2M_WIFI_REQ_DHCP_CONF + /ref M2M_WIFI_REQ_WPS + /ref M2M_WIFI_RESP_IP_CONFLICT + /ref M2M_WIFI_RESP_SCAN_DONE + /ref M2M_WIFI_RESP_SCAN_RESULT + /ref M2M_WIFI_RESP_CURRENT_RSSI + /ref M2M_WIFI_RESP_CLIENT_INFO + /ref M2M_WIFI_RESP_PROVISION_INFO + /ref M2M_WIFI_RESP_DEFAULT_CONNECT + + In case Ethernet/Bypass mode is defined : + @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET + + In case monitoring mode is used: + @ref M2M_WIFI_RESP_WIFI_RX_PACKET + +@param [in] pvMsg + A pointer to a buffer containing the notification parameters (if any). It should be + casted to the correct data type corresponding to the notification type. + +@see + tstrM2mWifiStateChanged + tstrM2MWPSInfo + tstrM2mScanDone + tstrM2mWifiscanResult +*/ +typedef void (*tpfAppWifiCb) (uint8 u8MsgType, void * pvMsg); + +/*! +@typedef \ + tpfAppEthCb + +@brief + ETHERNET (bypass mode) notification callback function receiving Bypass mode events as defined in + the Wi-Fi responses enumeration @ref tenuM2mStaCmd. + +@param [in] u8MsgType + Type of notification. Possible types are: + - [M2M_WIFI_RESP_ETHERNET_RX_PACKET](@ref M2M_WIFI_RESP_ETHERNET_RX_PACKET) + +@param [in] pvMsg + A pointer to a buffer containing the notification parameters (if any). It should be + casted to the correct data type corresponding to the notification type. + For example, it could be a pointer to the buffer holding the received frame in case of @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET + event. + +@param [in] pvControlBuf + A pointer to control buffer describing the accompanied message. + To be casted to @ref tstrM2mIpCtrlBuf in case of @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET event. + +@warning + Make sure that the application defines @ref ETH_MODE. + +@see + m2m_wifi_init + +*/ +typedef void (*tpfAppEthCb) (uint8 u8MsgType, void * pvMsg,void * pvCtrlBuf); + +/*! +@typedef \ + tpfAppMonCb + +@brief + Wi-Fi monitoring mode callback function. This function delivers all received wi-Fi packets through the Wi-Fi interface. + Applications requiring to operate in the monitoring should call the asynchronous function m2m_wifi_enable_monitoring_mode + and expect to receive the Wi-Fi packets through this callback function, when the event is received. + To disable the monitoring mode a call to @ref m2m_wifi_disable_monitoring_mode should be made. +@param [in] pstrWifiRxPacket + Pointer to a structure holding the Wi-Fi packet header parameters. + +@param [in] pu8Payload + Pointer to the buffer holding the Wi-Fi packet payload information required by the application starting from the + defined OFFSET by the application (when calling m2m_wifi_enable_monitoring_mode). + Could hold a value of NULL, if the application does not need any data from the payload. + +@param [in] u16PayloadSize + The size of the payload in bytes. + +@see + m2m_wifi_enable_monitoring_mode,m2m_wifi_init + +@warning + u16PayloadSize should not exceed the buffer size given through m2m_wifi_enable_monitoring_mode. + +*/ +typedef void (*tpfAppMonCb) (tstrM2MWifiRxPacketInfo *pstrWifiRxPacket, uint8 * pu8Payload, uint16 u16PayloadSize); + +/** +@struct \ + tstrEthInitParam + +@brief + Structure to hold Ethernet interface parameters. + Structure is to be defined and have its attributes set,based on the application's functionality before + a call is made to initialize the Wi-Fi operations by calling the @ref m2m_wifi_init function. + This structure is part of the Wi-Fi configuration structure @ref tstrWifiInitParam. + Applications shouldn't need to define this structure, if the bypass mode is not defined. + +@see + tpfAppEthCb + tpfAppWifiCb + m2m_wifi_init + +@warning + Make sure that application defines @ref ETH_MODE before using @ref tstrEthInitParam. + +*/ +typedef struct { + tpfAppWifiCb pfAppWifiCb; + /*!< + Callback for wifi notifications. + */ + tpfAppEthCb pfAppEthCb; + /*!< + Callback for Ethernet interface. + */ + uint8 * au8ethRcvBuf; + /*!< + Pointer to Receive Buffer of Ethernet Packet + */ + uint16 u16ethRcvBufSize; + /*!< + Size of Receive Buffer for Ethernet Packet + */ + uint8 u8EthernetEnable; + /*!< + Enable Ethernet mode flag + */ + uint8 __PAD8__; + /*!< + Padding + */ +} tstrEthInitParam; +/*! +@struct \ + tstrM2mIpCtrlBuf + +@brief + Structure holding the incoming buffer's data size information, indicating the data size of the buffer and the remaining buffer's data size . + The data of the buffer which holds the packet sent to the host when in the bypass mode, is placed in the @ref tstrEthInitParam structure in the + @ref au8ethRcvBuf attribute. This following information is retrieved in the host when an event @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET is received in + the Wi-Fi callback function @ref tpfAppWifiCb. + + The application is expected to use this structure's information to determine if there is still incoming data to be received from the firmware. + + @see + tpfAppEthCb + tstrEthInitParam + + @warning + Make sure that ETHERNET/bypass mode is defined before using @ref tstrM2mIpCtrlBuf + + */ +typedef struct{ + uint16 u16DataSize; + /*!< + Size of the received data in bytes. + */ + uint16 u16RemainigDataSize; + /*!< + Size of the remaining data bytes to be delivered to host. + */ +} tstrM2mIpCtrlBuf; + + +/** +@struct \ + tstrWifiInitParam + +@brief + Structure, holding the Wi-fi configuration attributes such as the wi-fi callback , monitoring mode callback and Ethernet parameter initialization structure. + Such configuration parameters are required to be set before calling the wi-fi initialization function @ref m2m_wifi_init. + @ref pfAppWifiCb attribute must be set to handle the wi-fi callback operations. + @ref pfAppMonCb attribute, is optional based on whether the application requires the monitoring mode configuration, and can there not + be set before the initialization. + @ref strEthInitParam structure, is another optional configuration based on whether the bypass mode is set. + + @see + tpfAppEthCb + tpfAppMonCb + tstrEthInitParam + +*/ +typedef struct { + tpfAppWifiCb pfAppWifiCb; + /*!< + Callback for Wi-Fi notifications. + */ + tpfAppMonCb pfAppMonCb; + /*!< + Callback for monitoring interface. + */ + tstrEthInitParam strEthInitParam ; + /*!< + Structure to hold Ethernet interface parameters. + */ + +} tstrWifiInitParam; + //@} +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/** \defgroup WLANAPI Function + * @ingroup m2m_wifi + */ +#ifdef __cplusplus + extern "C" { +#endif + /** @defgroup WiFiDownloadFn m2m_wifi_download_mode + * @ingroup WLANAPI + * Synchronous download mode entry function that prepares the WINC board to enter the download mode, ready for the firmware or certificate download. +* The WINC board is prepared for download, through initializations for the WINC driver including bus initializations and interrupt enabling, it also halts the chip, to allow for the firmware downloads. +* Firmware can be downloaded through a number of interfaces, UART, I2C and SPI. + */ + /**@{*/ +/*! +@fn \ + NMI_API void m2m_wifi_download_mode(void); +@brief Prepares the WINC broard before downloading any data (Firmware, Certificates .. etc) + + This function should called before starting to download any data to the WINC board. The WINC board is prepared for download, through initializations for the WINC driver including bus initializations + and interrupt enabling, it also halts the chip, to allow for the firmware downloads Firmware can be downloaded through a number of interfaces, UART, I2C and SPI. + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_download_mode(void); + + /**@}*/ + /** @defgroup WifiInitFn m2m_wifi_init + * @ingroup WLANAPI + * Synchronous initialization function for the WINC driver. This function initializes the driver by, registering the call back function for M2M_WIFI layer(also the call back function for bypass mode/monitoring mode if defined), + * initializing the host interface layer and the bus interfaces. + * Wi-Fi callback registering is essential to allow the handling of the events received, in response to the asynchronous Wi-Fi operations. + +Following are the possible Wi-Fi events that are expected to be received through the call back function(provided by the application) to the M2M_WIFI layer are : + + @ref M2M_WIFI_RESP_CON_STATE_CHANGED \n + @ref M2M_WIFI_RESP_CONN_INFO \n + @ref M2M_WIFI_REQ_DHCP_CONF \n + @ref M2M_WIFI_REQ_WPS \n + @ref M2M_WIFI_RESP_IP_CONFLICT \n + @ref M2M_WIFI_RESP_SCAN_DONE \n + @ref M2M_WIFI_RESP_SCAN_RESULT \n + @ref M2M_WIFI_RESP_CURRENT_RSSI \n + @ref M2M_WIFI_RESP_CLIENT_INFO \n + @ref M2M_WIFI_RESP_PROVISION_INFO \n + @ref M2M_WIFI_RESP_DEFAULT_CONNECT \n + Example: \n + In case Bypass mode is defined : \n + @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET + + In case Monitoring mode is used: \n + @ref M2M_WIFI_RESP_WIFI_RX_PACKET + + Any application using the WINC driver must call this function at the start of its main function. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_init(tstrWifiInitParam * pWifiInitParam); + +@param [in] pWifiInitParam + This is a pointer to the @ref tstrWifiInitParam structure which holds the pointer to the application WIFI layer call back function, + monitoring mode call back and @ref tstrEthInitParam structure containing bypass mode parameters. + +@brief Initialize the WINC host driver. + This function initializes the driver by, registering the call back function for M2M_WIFI layer(also the call back function for bypass mode/monitoring mode if defined), + initializing the host interface layer and the bus interfaces. + +@pre + Prior to this function call, The application should initialize the BSP using "nm_bsp_init". + Also,application users must provide a call back function responsible for receiving all the WI-FI events that are received on the M2M_WIFI layer. + +@warning + Failure to successfully complete function indicates that the driver couldn't be initialized and a fatal error will prevent the application from proceeding. + +@see + nm_bsp_init + m2m_wifi_deinit + tenuM2mStaCmd + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_init(tstrWifiInitParam * pWifiInitParam); + /**@}*/ + /** @defgroup WifiDeinitFn m2m_wifi_deinit + * @ingroup WLANAPI + * Synchronous de-initialization function to the WINC1500 driver. De-initializes the host interface and frees any resources used by the M2M_WIFI layer. + * This function must be called in the application closing phase to ensure that all resources have been correctly released. No arguments are expected to be passed in. + */ +/**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_deinit(void * arg); + +@param [in] arg + Generic argument. Not used in the current implementation. +@brief Deinitilize the WINC driver and host enterface. + This function must be called at the De-initilization stage of the application. Generally This function should be the last function before switching off the chip + and it should be followed only by "nm_bsp_deinit" function call. Every function call of "nm_wifi_init" should be matched with a call to nm_wifi_deinit. +@see + nm_bsp_deinit + nm_wifi_init + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_deinit(void * arg); + + /**@}*/ +/** @defgroup WifiHandleEventsFn m2m_wifi_handle_events +* @ingroup WLANAPI +* Synchronous M2M event handler function, responsible for handling interrupts received from the WINC firmware. +* Application developers should call this function periodically in-order to receive the events that are to be handled by the +* callback functions implemented by the application. + + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_handle_events(void * arg); + +@pre + Prior to receiving events, the WINC driver should have been successfully initialized by calling the @ref m2m_wifi_init function. + +@brief Handle the varios events received from the WINC board. + Whenever an event happen in the WINC board (e.g. Connection, Disconnection , DHCP .. etc), WINC will interrupt the host to let it know that a new + event has occured. The host driver will attempt to handle these events whenever the host driver decides to do that by calling the "m2m_wifi_handle_events" function. + It's mandatory to call this function periodically and independantly of any other condition. It's ideal to include this function in the main and the most frequent loop of the + host application. +@warning + Failure to successfully complete this function indicates bus errors and hence a fatal error that will prevent the application from proceeding. + +@return + The function returns @ref M2M_SUCCESS for successful interrupt handling and a negative value otherwise. +*/ + +NMI_API sint8 m2m_wifi_handle_events(void * arg); + + /**@}*/ +/** @defgroup WifiSendCRLFn m2m_wifi_send_crl +* @ingroup WLANAPI +* Asynchronous API that notifies the WINC with the Certificate Revocation List to be used for TLS. + + */ + /**@{*/ +/*! +@fn \ + sint8 m2m_wifi_send_crl(tstrTlsCrlInfo* pCRL); + +@brief + Asynchronous API that notifies the WINC with the Certificate Revocation List. + +@param [in] pCRL + Pointer to the structure containing certificate revocation list details. + +@return + The function returns @ref M2M_SUCCESS if the command has been successfully queued to the WINC, + and a negative value otherwise. +*/ + +sint8 m2m_wifi_send_crl(tstrTlsCrlInfo* pCRL); + + /**@}*/ +/** @defgroup WifiDefaultConnectFn m2m_wifi_default_connect + * @ingroup WLANAPI + * Asynchronous Wi-Fi connection function. An application calling this function will cause the firmware to correspondingly connect to the last successfully connected AP from the cached connections. + * A failure to connect will result in a response of @ref M2M_WIFI_RESP_DEFAULT_CONNECT indicating the connection error as defined in the structure @ref tstrM2MDefaultConnResp. + * Possible errors are: + * The connection list is empty @ref M2M_DEFAULT_CONN_EMPTY_LIST or a mismatch for the saved AP name @ref M2M_DEFAULT_CONN_SCAN_MISMATCH. + * only difference between this function and @ref m2m_wifi_connect, is the connection parameters. + * Connection using this function is expected to connect using cached connection parameters. + + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_default_connect(void); + +@pre + Prior to connecting, the WINC driver should have been successfully initialized by calling the @ref m2m_wifi_init function. + +@brief Connect to the last successfully connected AP from the cached connections. + +@warning + This function must be called in station mode only. + It's important to note that successful completion of a call to m2m_wifi_default_connect() does not guarantee success of the WIFI connection, + and a negative return value indicates only locally-detected errors. + +@see + m2m_wifi_connect + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_default_connect(void); + /**@}*/ +/** @defgroup WifiConnectFn m2m_wifi_connect + * @ingroup WLANAPI + * Asynchronous wi-fi connection function to a specific AP. Prior to a successful connection, the application must define the SSID of the AP, the security type, + * the authentication information parameters and the channel number to which the connection will be established. + * The connection status is known when a response of @ref M2M_WIFI_RESP_CON_STATE_CHANGED is received based on the states defined in @ref tenuM2mConnState, + * successful connection is defined by @ref M2M_WIFI_CONNECTED +* + * The only difference between this function and @ref m2m_wifi_default_connect, is the connection parameters. + * Connection using this function is expected to be made to a specific AP and to a specified channel. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_connect(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch); + +@param [in] pcSsid + A buffer holding the SSID corresponding to the requested AP. + +@param [in] u8SsidLen + Length of the given SSID (not including the NULL termination). + A length less than ZERO or greater than the maximum defined SSID @ref M2M_MAX_SSID_LEN will result in a negative error + @ref M2M_ERR_FAIL. + +@param [in] u8SecType + Wi-Fi security type security for the network. It can be one of the following types: + -@ref M2M_WIFI_SEC_OPEN + -@ref M2M_WIFI_SEC_WEP + -@ref M2M_WIFI_SEC_WPA_PSK + -@ref M2M_WIFI_SEC_802_1X + A value outside these possible values will result in a negative return error @ref M2M_ERR_FAIL. + +@param [in] pvAuthInfo + Authentication parameters required for completing the connection. It is type is based on the Security type. + If the authentication parameters are NULL or are greater than the maximum length of the authentication parameters length as defined by + @ref M2M_MAX_PSK_LEN a negative error will return @ref M2M_ERR_FAIL(-12) indicating connection failure. + +@param [in] u16Ch + Wi-Fi channel number as defined in @ref tenuM2mScanCh enumeration. + Channel number greater than @ref M2M_WIFI_CH_14 returns a negative error @ref M2M_ERR_FAIL(-12). + Except if the value is M2M_WIFI_CH_ALL(255), since this indicates that the firmware should scan all channels to find the SSID requested to connect to. + Failure to find the connection match will return a negative error @ref M2M_DEFAULT_CONN_SCAN_MISMATCH. +@pre + Prior to a successful connection request, the Wi-Fi driver must have been successfully initialized through the call of the @ref @m2m_wifi_init function +@see + tuniM2MWifiAuth + tstr1xAuthCredentials + tstrM2mWifiWepParams + +@warning + -This function must be called in station mode only. + -Successful completion of this function does not guarantee success of the WIFI connection, and + a negative return value indicates only locally-detected errors. + +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_connect(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch); + /**@}*/ +/** @defgroup WifiConnectFn m2m_wifi_connect_sc + * @ingroup WLANAPI + * Asynchronous wi-fi connection function to a specific AP. Prior to a successful connection, the application developers must know the SSID of the AP, the security type, + * the authentication information parameters and the channel number to which the connection will be established.this API allows the user to choose + * whether to + * The connection status is known when a response of @ref M2M_WIFI_RESP_CON_STATE_CHANGED is received based on the states defined in @ref tenuM2mConnState, + * successful connection is defined by @ref M2M_WIFI_CONNECTED + * The only difference between this function and @ref m2m_wifi_connect, is the option to save the acess point info ( SSID, password...etc) or not. + * Connection using this function is expected to be made to a specific AP and to a specified channel. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_connect_sc(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch,uint8 u8SaveCred); + +@param [in] pcSsid + A buffer holding the SSID corresponding to the requested AP. + +@param [in] u8SsidLen + Length of the given SSID (not including the NULL termination). + A length less than ZERO or greater than the maximum defined SSID @ref M2M_MAX_SSID_LEN will result in a negative error + @ref M2M_ERR_FAIL. + +@param [in] u8SecType + Wi-Fi security type security for the network. It can be one of the following types: + -@ref M2M_WIFI_SEC_OPEN + -@ref M2M_WIFI_SEC_WEP + -@ref M2M_WIFI_SEC_WPA_PSK + -@ref M2M_WIFI_SEC_802_1X + A value outside these possible values will result in a negative return error @ref M2M_ERR_FAIL. + +@param [in] pvAuthInfo + Authentication parameters required for completing the connection. It is type is based on the Security type. + If the authentication parameters are NULL or are greater than the maximum length of the authentication parameters length as defined by + @ref M2M_MAX_PSK_LEN a negative error will return @ref M2M_ERR_FAIL(-12) indicating connection failure. + +@param [in] u16Ch + Wi-Fi channel number as defined in @ref tenuM2mScanCh enumeration. + Channel number greater than @ref M2M_WIFI_CH_14 returns a negative error @ref M2M_ERR_FAIL(-12). + Except if the value is M2M_WIFI_CH_ALL(255), since this indicates that the firmware should scan all channels to find the SSID requested to connect to. + Failure to find the connection match will return a negative error @ref M2M_DEFAULT_CONN_SCAN_MISMATCH. + +@param [in] u8NoSaveCred + Option to store the acess point SSID and password into the WINC flash memory or not. + +@pre + Prior to a successful connection request, the wi-fi driver must have been successfully initialized through the call of the @ref @m2m_wifi_init function +@see + tuniM2MWifiAuth + tstr1xAuthCredentials + tstrM2mWifiWepParams + +@warning + -This function must be called in station mode only. + -Successful completion of this function does not guarantee success of the WIFI connection, and + a negative return value indicates only locally-detected errors. + +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ + NMI_API sint8 m2m_wifi_connect_sc(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch, uint8 u8SaveCred); + /**@}*/ +/** @defgroup WifiDisconnectFn m2m_wifi_disconnect + * @ingroup WLANAPI + * Synchronous wi-fi disconnection function, requesting a Wi-Fi disconnection from the currently connected AP. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_disconnect(void); + +@pre + Disconnection request must be made to a successfully connected AP. If the WINC is not in the connected state, a call to this function will hold insignificant. + +@brief Request a Wi-Fi disconnect from the currently connected AP. + After the Disconnect is complete the driver should recieve a response of @ref M2M_WIFI_RESP_CON_STATE_CHANGED based on the states defined + in @ref tenuM2mConnState, successful disconnection is defined by @ref M2M_WIFI_DISCONNECTED . +@warning + This function must be called in station mode only. + +@see + m2m_wifi_connect + m2m_wifi_default_connect + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_disconnect(void); + + /**@}*/ +/** @defgroup StartProvisionModeFn m2m_wifi_start_provision_mode + * @ingroup WLANAPI + * Asynchronous Wi-Fi provisioning function, which starts the WINC HTTP PROVISIONING mode. + The function triggers the WINC to activate the Wi-Fi AP (HOTSPOT) mode with the passed configuration parameters and then starts the + HTTP Provision WEB Server. + The provisioning status is returned in an event @ref M2M_WIFI_RESP_PROVISION_INFO + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_start_provision_mode(tstrM2MAPConfig *pstrAPConfig, char *pcHttpServerDomainName, uint8 bEnableHttpRedirect); + +@param [in] pstrAPConfig + AP configuration parameters as defined in @ref tstrM2MAPConfig configuration structure. + A NULL value passed in, will result in a negative error @ref M2M_ERR_FAIL. + +@param [in] pcHttpServerDomainName + Domain name of the HTTP Provision WEB server which others will use to load the provisioning Home page. + The domain name can have one of the following 3 forms: + 1- "wincprov.com" + 2- "http://wincprov.com" + 3- "https://wincprov.com" + The forms 1 and 2 are equivalent, they both will start a plain http server, while form 3 + will start a secure HTTP provisioning Session (HTTP over SSL connection). + +@param [in] bEnableHttpRedirect + A flag to enable/disable the HTTP redirect feature. If Secure provisioning is enabled (i.e. the server + domain name uses "https" prefix) this flag is ignored (no meaning for redirect in HTTPS). + Possible values are: + - ZERO DO NOT Use HTTP Redirect. In this case the associated device could open the provisioning page ONLY when + the HTTP Provision URL of the WINC HTTP Server is correctly written on the browser. + - Non-Zero value Use HTTP Redirect. In this case, all http traffic (http://URL) from the associated + device (Phone, PC, ...etc) will be redirected to the WINC HTTP Provisioning Home page. + +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback + is done through passing it to the initialization @ref m2m_wifi_init function. + - The event @ref M2M_WIFI_RESP_CONN_INFO must be handled in the callback to receive the requested connection info. + +@see + tpfAppWifiCb + m2m_wifi_init + M2M_WIFI_RESP_PROVISION_INFO + m2m_wifi_stop_provision_mode + tstrM2MAPConfig + +@warning + DO Not use ".local" in the pcHttpServerDomainName. + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +\section Example + The example demonstrates a code snippet for how provisioning is triggered and the response event received accordingly. +@code + #include "m2m_wifi.h" + #include "m2m_types.h" + + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_PROVISION_INFO: + { + tstrM2MProvisionInfo *pstrProvInfo = (tstrM2MProvisionInfo*)pvMsg; + if(pstrProvInfo->u8Status == M2M_SUCCESS) + { + m2m_wifi_connect((char*)pstrProvInfo->au8SSID, (uint8)strlen(pstrProvInfo->au8SSID), pstrProvInfo->u8SecType, + pstrProvInfo->au8Password, M2M_WIFI_CH_ALL); + + printf("PROV SSID : %s\n",pstrProvInfo->au8SSID); + printf("PROV PSK : %s\n",pstrProvInfo->au8Password); + } + else + { + printf("(ERR) Provisioning Failed\n"); + } + } + break; + + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + tstrM2MAPConfig apConfig; + uint8 bEnableRedirect = 1; + + strcpy(apConfig.au8SSID, "WINC_SSID"); + apConfig.u8ListenChannel = 1; + apConfig.u8SecType = M2M_WIFI_SEC_OPEN; + apConfig.u8SsidHide = 0; + + // IP Address + apConfig.au8DHCPServerIP[0] = 192; + apConfig.au8DHCPServerIP[1] = 168; + apConfig.au8DHCPServerIP[2] = 1; + apConfig.au8DHCPServerIP[0] = 1; + + m2m_wifi_start_provision_mode(&apConfig, "atmelwincconf.com", bEnableRedirect); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API sint8 m2m_wifi_start_provision_mode(tstrM2MAPConfig *pstrAPConfig, char *pcHttpServerDomainName, uint8 bEnableHttpRedirect); + /**@}*/ +/** @defgroup StopProvisioningModeFn m2m_wifi_stop_provision_mode + * @ingroup WLANAPI + * Synchronous provision termination function which stops the provision mode if it is active. + */ + /**@{*/ +/*! +@fn \ + sint8 m2m_wifi_stop_provision_mode(void); + +@pre + An active provisioning session must be active before it is terminated through this function. +@see + m2m_wifi_start_provision_mode + +@return + The function returns ZERO for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_stop_provision_mode(void); + /**@}*/ +/** @defgroup GetConnectionInfoFn m2m_wifi_get_connection_info + * @ingroup WLANAPI + * Asynchronous connection status retrieval function, retrieves the status information of the currently connected AP. The result is passed to the Wi-Fi notification callback +* through the event @ref M2M_WIFI_RESP_CONN_INFO. Connection information is retrieved from the structure @ref tstrM2MConnInfo. + */ + /**@{*/ +/*! +@fn \ + sint8 m2m_wifi_get_connection_info(void); + +@brief + Retrieve the current Connection information. The result is passed to the Wi-Fi notification callback + with [M2M_WIFI_RESP_CONN_INFO](@ref M2M_WIFI_RESP_CONN_INFO). +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback + is done through passing it to the initialization @ref m2m_wifi_init function. + - The event @ref M2M_WIFI_RESP_CONN_INFO must be handled in the callback to receive the requested connection info. + + Connection Information retrieved: + + + -Connection Security + -Connection RSSI + -Remote MAC address + -Remote IP address + + and in case of WINC station mode the SSID of the AP is also retrieved. +@warning + -In case of WINC AP mode or P2P mode, ignore the SSID field (NULL string). +@sa + M2M_WIFI_RESP_CONN_INFO, + tstrM2MConnInfo +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet shows an example of how wi-fi connection information is retrieved . +@code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_CONN_INFO: + { + tstrM2MConnInfo *pstrConnInfo = (tstrM2MConnInfo*)pvMsg; + + printf("CONNECTED AP INFO\n"); + printf("SSID : %s\n",pstrConnInfo->acSSID); + printf("SEC TYPE : %d\n",pstrConnInfo->u8SecType); + printf("Signal Strength : %d\n", pstrConnInfo->s8RSSI); + printf("Local IP Address : %d.%d.%d.%d\n", + pstrConnInfo->au8IPAddr[0] , pstrConnInfo->au8IPAddr[1], pstrConnInfo->au8IPAddr[2], pstrConnInfo->au8IPAddr[3]); + } + break; + + case M2M_WIFI_REQ_DHCP_CONF: + { + // Get the current AP information. + m2m_wifi_get_connection_info(); + } + break; + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // connect to the default AP + m2m_wifi_default_connect(); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API sint8 m2m_wifi_get_connection_info(void); + /**@}*/ +/** @defgroup WifiSetMacAddFn m2m_wifi_set_mac_address + * @ingroup WLANAPI + * Synchronous MAC address assigning to the NMC1500. It is used for non-production SW. Assign MAC address to the WINC device. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_set_mac_address(uint8 au8MacAddress[6]); + +@brief Assign a MAC address to the WINC board. + This function override the already assigned MAC address of the WINC board with a user provided one. This is for experimental + use only and should never be used in the production SW. + +@param [in] au8MacAddress + MAC Address to be set to the WINC. + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_set_mac_address(uint8 au8MacAddress[6]); + + /**@}*/ +/** @defgroup WifiWpsFn m2m_wifi_wps + * @ingroup WLANAPI + * Asynchronous WPS triggering function. + * This function is called for the WINC to enter the WPS (Wi-Fi Protected Setup) mode. The result is passed to the Wi-Fi notification callback +* with the event @ref M2M_WIFI_REQ_WPS. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_wps(uint8 u8TriggerType,const char * pcPinNumber); + +@param [in] u8TriggerType + WPS Trigger method. Could be: + - [WPS_PIN_TRIGGER](@ref WPS_PIN_TRIGGER) Push button method + - [WPS_PBC_TRIGGER](@ref WPS_PBC_TRIGGER) Pin method + +@param [in] pcPinNumber + PIN number for WPS PIN method. It is not used if the trigger type is WPS_PBC_TRIGGER. It must follow the rules + stated by the WPS standard. + +@warning + This function is not allowed in AP or P2P modes. + +@pre + - A Wi-Fi notification callback of type (@ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback + is done through passing it to the [m2m_wifi_init](@ref m2m_wifi_init). + - The event [M2M_WIFI_REQ_WPS](@ref M2M_WIFI_REQ_WPS) must be handled in the callback to receive the WPS status. + - The WINC device MUST be in IDLE or STA mode. If AP or P2P mode is active, the WPS will not be performed. + - The [m2m_wifi_handle_events](@ref m2m_wifi_handle_events) MUST be called periodically to receive the responses in the callback. +@see + tpfAppWifiCb + m2m_wifi_init + M2M_WIFI_REQ_WPS + tenuWPSTrigger + tstrM2MWPSInfo + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet shows an example of how Wi-Fi WPS is triggered . +@code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + switch(u8WiFiEvent) + { + case M2M_WIFI_REQ_WPS: + { + tstrM2MWPSInfo *pstrWPS = (tstrM2MWPSInfo*)pvMsg; + if(pstrWPS->u8AuthType != 0) + { + printf("WPS SSID : %s\n",pstrWPS->au8SSID); + printf("WPS PSK : %s\n",pstrWPS->au8PSK); + printf("WPS SSID Auth Type : %s\n",pstrWPS->u8AuthType == M2M_WIFI_SEC_OPEN ? "OPEN" : "WPA/WPA2"); + printf("WPS Channel : %d\n",pstrWPS->u8Ch + 1); + + // establish Wi-Fi connection + m2m_wifi_connect((char*)pstrWPS->au8SSID, (uint8)m2m_strlen(pstrWPS->au8SSID), + pstrWPS->u8AuthType, pstrWPS->au8PSK, pstrWPS->u8Ch); + } + else + { + printf("(ERR) WPS Is not enabled OR Timed out\n"); + } + } + break; + + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // Trigger WPS in Push button mode. + m2m_wifi_wps(WPS_PBC_TRIGGER, NULL); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API sint8 m2m_wifi_wps(uint8 u8TriggerType,const char *pcPinNumber); + /**@}*/ +/** @defgroup WifiWpsDisableFn m2m_wifi_wps_disable + * @ingroup WLANAPI + * Disable the WINC1500 WPS operation. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_wps_disable(void); + +@pre WINC should be already in WPS mode using @ref m2m_wifi_wps + +@brief Stops the WPS ongoing session. + +@see + m2m_wifi_wps + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_wps_disable(void); + + /**@}*/ +/** @defgroup WifiP2PFn m2m_wifi_p2p + * @ingroup WLANAPI + * Asynchronous Wi-Fi direct (P2P) enabling mode function. + The WINC supports P2P in device listening mode ONLY (intent is ZERO). + The WINC P2P implementation does not support P2P GO (Group Owner) mode. + Active P2P devices (e.g. phones) could find the WINC in the search list. When a device is connected to WINC, a Wi-Fi notification event + @ref M2M_WIFI_RESP_CON_STATE_CHANGED is triggered. After a short while, the DHCP IP Address is obtained + and an event @ref M2M_WIFI_REQ_DHCP_CONF is triggered. Refer to the code examples for a more illustrative example. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_p2p(uint8 u8Channel); + +@param [in] u8Channel + P2P Listen RF channel. According to the P2P standard It must hold only one of the following values 1, 6 or 11. + +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback + is done through passing it to the @ref m2m_wifi_init. + - The events @ref M2M_WIFI_RESP_CON_STATE_CHANGED and @ref M2M_WIFI_REQ_DHCP_CONF + must be handled in the callback. + - The @ref m2m_wifi_handle_events MUST be called to receive the responses in the callback. + +@warning + This function is not allowed in AP or STA modes. + +@see + tpfAppWifiCb + m2m_wifi_init + M2M_WIFI_RESP_CON_STATE_CHANGED + M2M_WIFI_REQ_DHCP_CONF + tstrM2mWifiStateChanged + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet shown an example of how the p2p mode operates. +@code + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_CON_STATE_CHANGED: + { + tstrM2mWifiStateChanged *pstrWifiState = (tstrM2mWifiStateChanged*)pvMsg; + M2M_INFO("Wifi State :: %s :: ErrCode %d\n", pstrWifiState->u8CurrState? "CONNECTED":"DISCONNECTED",pstrWifiState->u8ErrCode); + + // Do something + } + break; + + case M2M_WIFI_REQ_DHCP_CONF: + { + uint8 *pu8IPAddress = (uint8*)pvMsg; + + printf("P2P IP Address \"%u.%u.%u.%u\"\n",pu8IPAddress[0],pu8IPAddress[1],pu8IPAddress[2],pu8IPAddress[3]); + } + break; + + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // Trigger P2P + m2m_wifi_p2p(M2M_WIFI_CH_1); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode + +*/ +NMI_API sint8 m2m_wifi_p2p(uint8 u8Channel); + /**@}*/ +/** @defgroup WifiP2PDisconnectFn m2m_wifi_p2p_disconnect + * @ingroup WLANAPI + * Disable the WINC1500 device Wi-Fi direct mode (P2P). + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_p2p_disconnect(void); +@pre + The p2p mode must have be enabled and active before a disconnect can be called. + +@see + m2m_wifi_p2p +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_p2p_disconnect(void); + /**@}*/ +/** @defgroup WifiEnableApFn m2m_wifi_enable_ap + * @ingroup WLANAPI + * Asynchronous Wi-FI hot-spot enabling function. + * The WINC supports AP mode operation with the following limitations: + - Only 1 STA could be associated at a time. + - Open and WEP are the only supported security types + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_enable_ap(CONST tstrM2MAPConfig* pstrM2MAPConfig); + +@param [in] pstrM2MAPConfig + A structure holding the AP configurations. + +@warning + This function is not allowed in P2P or STA modes. + +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback + is done through passing it to the [m2m_wifi_init](@ref m2m_wifi_init). + - The event @ref M2M_WIFI_REQ_DHCP_CONF must be handled in the callback. + - The @ref m2m_wifi_handle_events MUST be called to receive the responses in the callback. + +@see + tpfAppWifiCb + tenuM2mSecType + m2m_wifi_init + M2M_WIFI_REQ_DHCP_CONF + tstrM2mWifiStateChanged + tstrM2MAPConfig + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet demonstrates how the AP mode is enabled after the driver is initialized in the application's main function and the handling + of the event @ref M2M_WIFI_REQ_DHCP_CONF, to indicate successful connection. +@code + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + switch(u8WiFiEvent) + { + case M2M_WIFI_REQ_DHCP_CONF: + { + uint8 *pu8IPAddress = (uint8*)pvMsg; + + printf("Associated STA has IP Address \"%u.%u.%u.%u\"\n",pu8IPAddress[0],pu8IPAddress[1],pu8IPAddress[2],pu8IPAddress[3]); + } + break; + + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + tstrM2MAPConfig apConfig; + + strcpy(apConfig.au8SSID, "WINC_SSID"); + apConfig.u8ListenChannel = 1; + apConfig.u8SecType = M2M_WIFI_SEC_OPEN; + apConfig.u8SsidHide = 0; + + // IP Address + apConfig.au8DHCPServerIP[0] = 192; + apConfig.au8DHCPServerIP[1] = 168; + apConfig.au8DHCPServerIP[2] = 1; + apConfig.au8DHCPServerIP[0] = 1; + + // Trigger AP + m2m_wifi_enable_ap(&apConfig); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode + +*/ +NMI_API sint8 m2m_wifi_enable_ap(CONST tstrM2MAPConfig* pstrM2MAPConfig); + /**@}*/ +/** @defgroup WifiDisableApFn m2m_wifi_disable_ap + * @ingroup WLANAPI + * Synchronous Wi-Fi hot-spot disabling function. Must be called only when the AP is enabled through the @ref m2m_wifi_enable_ap + * function. Otherwise the call to this function will not be useful. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_disable_ap(void); +@see + m2m_wifi_enable_ap +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_disable_ap(void); + /**@}*/ +/** @defgroup SetStaticIPFn m2m_wifi_set_static_ip + * @ingroup WLANAPI + * Synchronous static IP Address configuration function. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_set_static_ip(tstrM2MIPConfig * pstrStaticIPConf); + +@param [in] pstrStaticIPConf + Pointer to a structure holding the static IP Configurations (IP, + Gateway, subnet mask and DNS address). + +@pre The application must disable auto DHCP using @ref m2m_wifi_enable_dhcp before assigning a static IP address. + +@brief Assign a static IP address to the WINC board. + This function assigns a static IP address in case the AP doesn't have a DHCP server or in case the application wants to assign + a predefined known IP address. The user must take in mind that assigning a static IP address might result in an IP address + conflict. In case of an IP address conflict observed by the WINC board the user will get a response of @ref M2M_WIFI_RESP_IP_CONFLICT + in the wifi callback. The application is then responsible to either solve the conflict or assign another IP address. +@warning + Normally this function normally should not be used. DHCP configuration is requested automatically after successful Wi-Fi connection is established. + +@see + tstrM2MIPConfig + + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_set_static_ip(tstrM2MIPConfig * pstrStaticIPConf); + + /**@}*/ +/** @defgroup RequestDHCPClientFn m2m_wifi_request_dhcp_client + * @ingroup WLANAPI + * Starts the DHCP client operation(DHCP requested by the firmware automatically in STA/AP/P2P mode). + * + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_request_dhcp_client(void); + +@warning + This function is legacy and exists only for compatability with older applications. DHCP configuration is requested automatically after successful Wi-Fi connection is established. + +@return + The function returns @ref M2M_SUCCESS always. +*/ +NMI_API sint8 m2m_wifi_request_dhcp_client(void); + /**@}*/ +/** @defgroup RequestDHCPServerFn m2m_wifi_request_dhcp_server + * @ingroup WLANAPI + * Dhcp requested by the firmware automatically in STA/AP/P2P mode). + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_request_dhcp_server(uint8* addr); + +@warning + This function is legacy and exists only for compatability with older applications. DHCP server is started automatically when enabling the AP mode. + + +@return + The function returns @ref M2M_SUCCESS always. +*/ +NMI_API sint8 m2m_wifi_request_dhcp_server(uint8* addr); + /**@}*/ +/** @defgroup WifiDHCPEnableFn m2m_wifi_enable_dhcp + * @ingroup WLANAPI + * Synchronous Wi-Fi DHCP enable function. This function Enable/Disable DHCP protocol. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_enable_dhcp(uint8 u8DhcpEn ); + +@brief + Enable/Disable the DHCP client after connection. + +@param [in] u8DhcpEn + Possible values: + 1: Enable DHCP client after connection. + 0: Disable DHCP client after connection. +@warnings + -DHCP client is enabled by default + -This Function should be called before using m2m_wifi_set_static_ip() + + +@sa + m2m_wifi_set_static_ip() + +@return + The function SHALL return @ref M2M_SUCCESS for successful operation and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_enable_dhcp(uint8 u8DhcpEn ); + /**@}*/ +/** @defgroup WifiSetScanOptionFn m2m_wifi_set_scan_options + * @ingroup WLANAPI + * Synchronous Wi-Fi scan settings function. This function sets the time configuration parameters for the scan operation. + */ + +/*! +@fn \ + sint8 m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption) + +@param [in] ptstrM2MScanOption; + Pointer to the structure holding the Scan Parameters. + +@see + tenuM2mScanCh + m2m_wifi_request_scan + tstrM2MScanOption + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption); + /**@}*/ +/** @defgroup WifiSetScanRegionFn m2m_wifi_set_scan_region + * @ingroup WLANAPI + * Synchronous wi-fi scan region setting function. + * This function sets the scan region, which will affect the range of possible scan channels. + * For 2.5GHz supported in the current release, the requested scan region can't exceed the maximum number of channels (14). + *@{*/ +/*! +@fn \ + sint8 m2m_wifi_set_scan_region(uint16 ScanRegion) + +@param [in] ScanRegion; + ASIA + NORTH_AMERICA +@see + tenuM2mScanCh + m2m_wifi_request_scan + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_set_scan_region(uint16 ScanRegion); + /**@}*/ +/** @defgroup WifiRequestScanFn m2m_wifi_request_scan +* @ingroup WLANAPI +* Asynchronous Wi-FI scan request on the given channel. The scan status is delivered in the wifi event callback and then the application +* is supposed to read the scan results sequentially. +* The number of APs found (N) is returned in event @ref M2M_WIFI_RESP_SCAN_DONE with the number of found +* APs. +* The application reads the list of APs by calling the function @ref m2m_wifi_req_scan_result N times. +* +*@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_request_scan(uint8 ch); + +@param [in] ch + RF Channel ID for SCAN operation. It should be set according to tenuM2mScanCh. + With a value of M2M_WIFI_CH_ALL(255)), means to scan all channels. + +@warning + This function is not allowed in P2P or AP modes. It works only for STA mode (both connected or disconnected states). + +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback + is done through passing it to the @ref m2m_wifi_init. + - The events @ref M2M_WIFI_RESP_SCAN_DONE and @ref M2M_WIFI_RESP_SCAN_RESULT. + must be handled in the callback. + - The @ref m2m_wifi_handle_events function MUST be called to receive the responses in the callback. + +@see + M2M_WIFI_RESP_SCAN_DONE + M2M_WIFI_RESP_SCAN_RESULT + tpfAppWifiCb + tstrM2mWifiscanResult + tenuM2mScanCh + m2m_wifi_init + m2m_wifi_handle_events + m2m_wifi_req_scan_result + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of + the events received in response. +@code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + static uint8 u8ScanResultIdx = 0; + + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_SCAN_DONE: + { + tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; + + printf("Num of AP found %d\n",pstrInfo->u8NumofCh); + if(pstrInfo->s8ScanState == M2M_SUCCESS) + { + u8ScanResultIdx = 0; + if(pstrInfo->u8NumofCh >= 1) + { + m2m_wifi_req_scan_result(u8ScanResultIdx); + u8ScanResultIdx ++; + } + else + { + printf("No AP Found Rescan\n"); + m2m_wifi_request_scan(M2M_WIFI_CH_ALL); + } + } + else + { + printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); + } + } + break; + + case M2M_WIFI_RESP_SCAN_RESULT: + { + tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; + uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); + + printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", + pstrScanResult->u8index,pstrScanResult->s8rssi, + pstrScanResult->u8AuthType, + pstrScanResult->u8ch, + pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], + pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], + pstrScanResult->au8SSID); + + if(u8ScanResultIdx < u8NumFoundAPs) + { + // Read the next scan result + m2m_wifi_req_scan_result(index); + u8ScanResultIdx ++; + } + } + break; + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // Scan all channels + m2m_wifi_request_scan(M2M_WIFI_CH_ALL); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API sint8 m2m_wifi_request_scan(uint8 ch); + + /**@}*/ +/** @defgroup WifiRequestScanFn m2m_wifi_request_scan_passive +* @ingroup WLANAPI +* Same as m2m_wifi_request_scan but perform passive scanning while the other one perform active scanning. + +* +*@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_request_scan_passive(uint8 ch, uint16 scan_time); + +@param [in] ch + RF Channel ID for SCAN operation. It should be set according to tenuM2mScanCh. + With a value of M2M_WIFI_CH_ALL(255)), means to scan all channels. + +@param [in] scan_time + The time in ms that passive scan is listening to beacons on each channel per one slot, enter 0 for deafult setting. + +@warning + This function is not allowed in P2P or AP modes. It works only for STA mode (both connected or disconnected states). + +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback + is done through passing it to the @ref m2m_wifi_init. + - The events @ref M2M_WIFI_RESP_SCAN_DONE and @ref M2M_WIFI_RESP_SCAN_RESULT. + must be handled in the callback. + - The @ref m2m_wifi_handle_events function MUST be called to receive the responses in the callback. + +@see + m2m_wifi_request_scan + M2M_WIFI_RESP_SCAN_DONE + M2M_WIFI_RESP_SCAN_RESULT + tpfAppWifiCb + tstrM2mWifiscanResult + tenuM2mScanCh + m2m_wifi_init + m2m_wifi_handle_events + m2m_wifi_req_scan_result + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_request_scan_passive(uint8 ch, uint16 scan_time); + + + /**@}*/ +/** @defgroup WifiRequestScanFn m2m_wifi_request_scan_ssid_list +* @ingroup WLANAPI +* Asynchronous wi-fi scan request on the given channel and the hidden scan list. The scan status is delivered in the wi-fi event callback and then the application +* is to read the scan results sequentially. +* The number of APs found (N) is returned in event @ref M2M_WIFI_RESP_SCAN_DONE with the number of found +* APs. +* The application could read the list of APs by calling the function @ref m2m_wifi_req_scan_result N times. +* +*@{*/ +/*! +@fn \ + NMI_API sint8 m2m_wifi_request_scan_ssid_list(uint8 ch,uint8 * u8SsidList); + +@param [in] ch + RF Channel ID for SCAN operation. It should be set according to tenuM2mScanCh. + With a value of M2M_WIFI_CH_ALL(255)), means to scan all channels. +@param [in] u8SsidList + u8SsidList is a buffer containing a list of hidden SSIDs to + include during the scan. The first byte in the buffer, u8SsidList[0], + is the number of SSIDs encoded in the string. The number of hidden SSIDs + cannot exceed MAX_HIDDEN_SITES. All SSIDs are concatenated in the following + bytes and each SSID is prefixed with a one-byte header containing its length. + The total number of bytes in u8SsidList buffer, including length byte, cannot + exceed 133 bytes (MAX_HIDDEN_SITES SSIDs x 32 bytes each, which is max SSID length). + For instance, encoding the two hidden SSIDs "DEMO_AP" and "TEST" + results in the following buffer content: +@code + uint8 u8SsidList[14]; + u8SsidList[0] = 2; // Number of SSIDs is 2 + u8SsidList[1] = 7; // Length of the string "DEMO_AP" without NULL termination + memcpy(&u8SsidList[2], "DEMO_AP", 7); // Bytes index 2-9 containing the string DEMO_AP + u8SsidList[9] = 4; // Length of the string "TEST" without NULL termination + memcpy(&u8SsidList[10], "TEST", 4); // Bytes index 10-13 containing the string TEST +@endcode + +@warning + This function is not allowed in P2P. It works only for STA/AP mode (connected or disconnected). + +@pre + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback + is done through passing it to the @ref m2m_wifi_init. + - The events @ref M2M_WIFI_RESP_SCAN_DONE and @ref M2M_WIFI_RESP_SCAN_RESULT. + must be handled in the callback. + - The @ref m2m_wifi_handle_events function MUST be called to receive the responses in the callback. + +@see + M2M_WIFI_RESP_SCAN_DONE + M2M_WIFI_RESP_SCAN_RESULT + tpfAppWifiCb + tstrM2mWifiscanResult + tenuM2mScanCh + m2m_wifi_init + m2m_wifi_handle_events + m2m_wifi_req_scan_result + +@return + The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of + the events received in response. +@code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + static void request_scan_hidden_demo_ap(void); + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + static uint8 u8ScanResultIdx = 0; + + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_SCAN_DONE: + { + tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; + + printf("Num of AP found %d\n",pstrInfo->u8NumofCh); + if(pstrInfo->s8ScanState == M2M_SUCCESS) + { + u8ScanResultIdx = 0; + if(pstrInfo->u8NumofCh >= 1) + { + m2m_wifi_req_scan_result(u8ScanResultIdx); + u8ScanResultIdx ++; + } + else + { + printf("No AP Found Rescan\n"); + request_scan_hidden_demo_ap(); + } + } + else + { + printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); + } + } + break; + + case M2M_WIFI_RESP_SCAN_RESULT: + { + tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; + uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); + + printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", + pstrScanResult->u8index,pstrScanResult->s8rssi, + pstrScanResult->u8AuthType, + pstrScanResult->u8ch, + pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], + pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], + pstrScanResult->au8SSID); + + if(u8ScanResultIdx < u8NumFoundAPs) + { + // Read the next scan result + m2m_wifi_req_scan_result(index); + u8ScanResultIdx ++; + } + } + break; + default: + break; + } + } + + static void request_scan_hidden_demo_ap(void) + { + uint8 list[9]; + char ssid[] = "DEMO_AP"; + uint8 len = (uint8)(sizeof(ssid)-1); + + list[0] = 1; + list[1] = len; + memcpy(&list[2], ssid, len); // copy 7 bytes + // Scan all channels + m2m_wifi_request_scan_ssid_list(M2M_WIFI_CH_ALL, list); + } + + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + request_scan_hidden_demo_ap(); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API sint8 m2m_wifi_request_scan_ssid_list(uint8 ch,uint8 * u8Ssidlist); + +/**@}*/ +/** @defgroup WifiGetNumAPFoundFn m2m_wifi_get_num_ap_found + * @ingroup WLANAPI +* Synchronous function to retrieve the number of AP's found in the last scan request, The function reads the number of APs from global variable which was updated in the Wi-Fi callback function through the M2M_WIFI_RESP_SCAN_DONE event. +* Function used only in STA mode only. + */ + /**@{*/ +/*! +@fn NMI_API uint8 m2m_wifi_get_num_ap_found(void); + +@see m2m_wifi_request_scan + M2M_WIFI_RESP_SCAN_DONE + M2M_WIFI_RESP_SCAN_RESULT +@pre m2m_wifi_request_scan need to be called first + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback + is done through passing it to the @ref m2m_wifi_init. + - The event @ref M2M_WIFI_RESP_SCAN_DONE must be handled in the callback to receive the requested scan information. +@warning This function must be called only in the wi-fi callback function when the events @ref M2M_WIFI_RESP_SCAN_DONE or @ref M2M_WIFI_RESP_SCAN_RESULT + are received. + Calling this function in any other place will result in undefined/outdated numbers. +@return Return the number of AP's found in the last Scan Request. + +\section Example + The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of + the events received in response. +@code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + static uint8 u8ScanResultIdx = 0; + + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_SCAN_DONE: + { + tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; + + printf("Num of AP found %d\n",pstrInfo->u8NumofCh); + if(pstrInfo->s8ScanState == M2M_SUCCESS) + { + u8ScanResultIdx = 0; + if(pstrInfo->u8NumofCh >= 1) + { + m2m_wifi_req_scan_result(u8ScanResultIdx); + u8ScanResultIdx ++; + } + else + { + printf("No AP Found Rescan\n"); + m2m_wifi_request_scan(M2M_WIFI_CH_ALL); + } + } + else + { + printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); + } + } + break; + + case M2M_WIFI_RESP_SCAN_RESULT: + { + tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; + uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); + + printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", + pstrScanResult->u8index,pstrScanResult->s8rssi, + pstrScanResult->u8AuthType, + pstrScanResult->u8ch, + pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], + pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], + pstrScanResult->au8SSID); + + if(u8ScanResultIdx < u8NumFoundAPs) + { + // Read the next scan result + m2m_wifi_req_scan_result(index); + u8ScanResultIdx ++; + } + } + break; + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // Scan all channels + m2m_wifi_request_scan(M2M_WIFI_CH_ALL); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API uint8 m2m_wifi_get_num_ap_found(void); +/**@}*/ +/** @defgroup WifiReqScanResult m2m_wifi_req_scan_result +* @ingroup WLANAPI +* Synchronous call to read the AP information from the SCAN Result list with the given index. +* This function is expected to be called when the response events M2M_WIFI_RESP_SCAN_RESULT or +* M2M_WIFI_RESP_SCAN_DONE are received in the wi-fi callback function. +* The response information received can be obtained through the casting to the @ref tstrM2mWifiscanResult structure + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_req_scan_result(uint8 index); +@param [in] index + Index for the requested result, the index range start from 0 till number of AP's found + +@see tstrM2mWifiscanResult + m2m_wifi_get_num_ap_found + m2m_wifi_request_scan + +@pre @ref m2m_wifi_request_scan needs to be called first, then m2m_wifi_get_num_ap_found + to get the number of AP's found + - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback + is done through passing it to the @ref m2m_wifi_init function. + - The event @ref M2M_WIFI_RESP_SCAN_RESULT must be handled in the callback to receive the requested scan information. +@warning Function used in STA mode only. the scan results are updated only if the scan request is called. + Calling this function only without a scan request will lead to firmware errors. + Refrain from introducing a large delay between the scan request and the scan result request, to prevent + errors occurring. + +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of + the events received in response. +@code + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + static uint8 u8ScanResultIdx = 0; + + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_SCAN_DONE: + { + tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; + + printf("Num of AP found %d\n",pstrInfo->u8NumofCh); + if(pstrInfo->s8ScanState == M2M_SUCCESS) + { + u8ScanResultIdx = 0; + if(pstrInfo->u8NumofCh >= 1) + { + m2m_wifi_req_scan_result(u8ScanResultIdx); + u8ScanResultIdx ++; + } + else + { + printf("No AP Found Rescan\n"); + m2m_wifi_request_scan(M2M_WIFI_CH_ALL); + } + } + else + { + printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); + } + } + break; + + case M2M_WIFI_RESP_SCAN_RESULT: + { + tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; + uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); + + printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", + pstrScanResult->u8index,pstrScanResult->s8rssi, + pstrScanResult->u8AuthType, + pstrScanResult->u8ch, + pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], + pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], + pstrScanResult->au8SSID); + + if(u8ScanResultIdx < u8NumFoundAPs) + { + // Read the next scan result + m2m_wifi_req_scan_result(index); + u8ScanResultIdx ++; + } + } + break; + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // Scan all channels + m2m_wifi_request_scan(M2M_WIFI_CH_ALL); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode +*/ +NMI_API sint8 m2m_wifi_req_scan_result(uint8 index); +/**@}*/ +/** @defgroup WifiReqCurrentRssiFn m2m_wifi_req_curr_rssi + * @ingroup WLANAPI + * Asynchronous request for the current RSSI of the connected AP. + * The response received in through the @ref M2M_WIFI_RESP_CURRENT_RSSI event. + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_req_curr_rssi(void); +@pre - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered before initialization. Registering the callback + is done through passing it to the [m2m_wifi_init](@ref m2m_wifi_init) through the @ref tstrWifiInitParam initialization structure. + - The event @ref M2M_WIFI_RESP_CURRENT_RSSI must be handled in the callback to receive the requested Rssi information. +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +\section Example + The code snippet demonstrates how the RSSI request is called in the application's main function and the handling of the event received in the callback. +@code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) + { + static uint8 u8ScanResultIdx = 0; + + switch(u8WiFiEvent) + { + case M2M_WIFI_RESP_CURRENT_RSSI: + { + sint8 *rssi = (sint8*)pvMsg; + M2M_INFO("ch rssi %d\n",*rssi); + } + break; + default: + break; + } + } + + int main() + { + tstrWifiInitParam param; + + param.pfAppWifiCb = wifi_event_cb; + if(!m2m_wifi_init(¶m)) + { + // Scan all channels + m2m_wifi_req_curr_rssi(); + + while(1) + { + m2m_wifi_handle_events(NULL); + } + } + } + +@endcode + +*/ +NMI_API sint8 m2m_wifi_req_curr_rssi(void); +/**@}*/ +/** @defgroup WifiGetOtpMacAddFn m2m_wifi_get_otp_mac_address +* @ingroup WLANAPI +* Request the MAC address stored on the One Time Programmable(OTP) memory of the device. +* The function is blocking until the response is received. +*/ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); + +@param [out] pu8MacAddr + Output MAC address buffer of 6 bytes size. Valid only if *pu8Valid=1. +@param [out] pu8IsValid + Output boolean value to indicate the validity of pu8MacAddr in OTP. + Output zero if the OTP memory is not programmed, non-zero otherwise. +@pre m2m_wifi_init required to be called before any WIFI/socket function +@see m2m_wifi_get_mac_address + +@return The function returns @ref M2M_SUCCESS for success and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); +/**@}*/ +/** @defgroup WifiGetMacAddFn m2m_wifi_get_mac_address +* @ingroup WLANAPI +* Function to retrieve the current MAC address. The function is blocking until the response is received. +*/ +/**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr) +@param [out] pu8MacAddr + Output MAC address buffer of 6 bytes size. +@pre m2m_wifi_init required to be called before any WIFI/socket function +@see m2m_wifi_get_otp_mac_address +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr); +/**@}*/ +/** @defgroup SetSleepModeFn m2m_wifi_set_sleep_mode + * @ingroup WLANAPI + * This is one of the two synchronous power-save setting functions that + * allow the host MCU application to tweak the system power consumption. Such tweaking can be done through one of two ways: +* 1) Changing the power save mode, to one of the allowed power save modes @ref tenuPowerSaveModes. This is done by setting the first parameter +* 2) Configuring DTIM monitoring: Configuring beacon monitoring parameters by enabling or disabling the reception of broadcast/multicast data. +* this is done by setting the second parameter. + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn); +@param [in] PsTyp + Desired power saving mode. Supported types are enumerated in @ref tenuPowerSaveModes. +@param [in] BcastEn + Broadcast reception enable flag. + If it is 1, the WINC1500 will be awake each DTIM beacon for receiving broadcast traffic. + If it is 0, the WINC1500: disable broadcast traffic. Through this flag the WINC1500 will not wakeup at the DTIM beacon, but it will wakeup depends only + on the the configured Listen Interval. + +@warning The function called once after initialization. + +@see tenuPowerSaveModes + m2m_wifi_get_sleep_mode + m2m_wifi_set_lsn_int + +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn); +/**@}*/ +/** @defgroup WifiRequestSleepFn m2m_wifi_request_sleep + * @ingroup WLANAPI + * Synchronous power-save sleep request function, which requests from the WINC1500 device to sleep in the currenlty configured power save mode as defined + * by the @ref m2m_wifi_set_sleep_mode, for a specific time as defined by the passed in parameter. + * This function should be used in the @ref M2M_PS_MANUAL power save mode only. + * A wake up request is automatically performed by the WINC1500 device when any host driver API function, e.g. Wi-Fi or socket operation is called. + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_request_sleep(uint32 u32SlpReqTime); +@param [in] u32SlpReqTime + Request sleep time in ms + The best recommended sleep duration is left to be determined by the application. Taking into account that if the application sends notifications very rarely, + sleeping for a long time can be a power-efficient decision. In contrast applications that are senstive for long periods of absence can experience + performance degradation in the connection if long sleeping times are used. +@warning The function should be called in @ref M2M_PS_MANUAL power save mode only. As enumerated in @ref tenuPowerSaveModes + It's also important to note that during the sleeping time while in the M2M_PS_MANUAL mode, AP beacon monitoring is bypassed and the wifi-connection may drop if + the sleep period is enlongated. +@see tenuPowerSaveModes + m2m_wifi_set_sleep_mode + +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_request_sleep(uint32 u32SlpReqTime); +/**@}*/ +/** @defgroup GetSleepModeFn m2m_wifi_get_sleep_mode + * @ingroup WLANAPI + * Synchronous power save mode retrieval function. + */ + /**@{*/ +/*! +@fn NMI_API uint8 m2m_wifi_get_sleep_mode(void); +@see tenuPowerSaveModes + m2m_wifi_set_sleep_mode +@return The current operating power saving mode based on the enumerated sleep modes @ref tenuPowerSaveModes. +*/ +NMI_API uint8 m2m_wifi_get_sleep_mode(void); +/**@}*/ +/** @defgroup WifiReqClientCtrlFn m2m_wifi_req_client_ctrl + * @ingroup WLANAPI + * Asynchronous command sending function to the PS Client (An WINC1500 board running the ps_firmware) +* if the PS client send any command it will be received through the @ref M2M_WIFI_RESP_CLIENT_INFO event + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_req_client_ctrl(uint8 cmd); +@brief +@param [in] cmd + Control command sent from PS Server to PS Client (command values defined by the application) +@pre @ref m2m_wifi_req_server_init should be called first +@warning This mode is not supported in the current release. +@see m2m_wifi_req_server_init + M2M_WIFI_RESP_CLIENT_INFO +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_req_client_ctrl(uint8 cmd); +/**@}*/ +/** @defgroup WifiReqServerInit m2m_wifi_req_server_init + * @ingroup WLANAPI + * Synchronous function to initialize the PS Server. + * The WINC1500 supports non secure communication with another WINC1500, +* (SERVER/CLIENT) through one byte command (probe request and probe response) without any connection setup. +* The server mode can't be used with any other modes (STA/P2P/AP) +*/ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_req_server_init(uint8 ch); +@param [in] ch + Server listening channel +@see m2m_wifi_req_client_ctrl +@warning This mode is not supported in the current release. +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_req_server_init(uint8 ch); +/**@}*/ +/** @defgroup WifiSetDeviceNameFn m2m_wifi_set_device_name + * @ingroup WLANAPI + * Sets the WINC device name. The name string is used as a device name in both (P2P) WiFi-Direct mode as well as DHCP hostname (option 12). + * For P2P devices to communicate a device name must be present. If it is not set through this function a default name is assigned. + * The default name is WINC-XX-YY, where XX and YY are the last 2 octets of the OTP MAC address. If OTP (eFuse) is programmed, + * then the default name is WINC-00-00. + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength); +@param [in] pu8DeviceName + A Buffer holding the device name. Device name is a null terminated C string. +@param [in] u8DeviceNameLength + The length of the device name. Should not exceed the maximum device name's length @ref M2M_DEVICE_NAME_MAX (including null character). +@warning The function called once after initialization. + Used for the Wi-Fi Direct (P2P) as well as DHCP client hostname option (12). +@warning Device name shall contain only characters allowed in valid internet host name as defined in RFC 952 and 1123. +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength); +/**@}*/ +/** @defgroup WifiSetLsnIntFn m2m_wifi_set_lsn_int + * @ingroup WLANAPI +* This is one of the two synchronous power-save setting functions that +* allow the host MCU application to tweak the system power consumption. Such tweaking can be done by modifying the +* the Wi-Fi listen interval. The listen interval is how many beacon periods the station can sleep before it wakes up to receive data buffer in AP. +* It is represented in units of AP beacon periods(100ms). +*/ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt * pstrM2mLsnInt); + +@param [in] pstrM2mLsnInt + Structure holding the listen interval configurations. +@pre Function @m2m_wifi_set_sleep_mode shall be called first, to set the power saving mode required. +@warning The function should be called once after initialization. +@see tstrM2mLsnInt + m2m_wifi_set_sleep_mode +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*/ +NMI_API sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt *pstrM2mLsnInt); +/**@}*/ +/** @defgroup WifiEnableMonitorModeFn m2m_wifi_enable_monitoring_mode + * @ingroup WLANAPI + * Asynchronous Wi-Fi monitoring mode (Promiscuous mode) enabling function. This function enables the monitoring mode, thus allowing two operations to be performed: + * 1) Transmission of manually configured frames, through using the @ref m2m_wifi_send_wlan_pkt function. + * 2) Reception of frames based on a defined filtering criteria + * When the monitoring mode is enabled, reception of all frames that satisfy the filter criteria passed in as a parameter is allowed, on the current wireless channel \n. + * All packets that meet the filtering criteria are passed to the application layer, to be handled by the assigned monitoring callback function \n. + * The monitoring callback function must be implemented before starting the monitoring mode, in-order to handle the packets received \n. + * Registering of the implemented callback function is through the callback pointer @ref tpfAppMonCb in the @ref tstrWifiInitParam structure\n. + * passed to @ref m2m_wifi_init function at initialization. + * + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_enable_monitoring_mode(tstrM2MWifiMonitorModeCtrl *, uint8 *, uint16 , uint16); + * @param [in] pstrMtrCtrl + * Pointer to @ref tstrM2MWifiMonitorModeCtrl structure holding the filtering parameters. + * @param [in] pu8PayloadBuffer + * Pointer to a buffer allocated by the application. The buffer SHALL hold the Data field of + * the WIFI RX Packet (Or a part from it). If it is set to NULL, the WIFI data payload will + * be discarded by the monitoring driver. + * @param [in] u16BufferSize + * The total size of the pu8PayloadBuffer in bytes. + * @param [in] u16DataOffset + * Starting offset in the DATA FIELD of the received WIFI packet. The application may be interested + * in reading specific information from the received packet. It must assign the offset to the starting + * position of it relative to the DATA payload start.\n + * \e Example, \e if \e the \e SSID \e is \e needed \e to \e be \e read \e from \e a \e PROBE \e REQ \e packet, \e the \e u16Offset \e MUST \e be \e set \e to \e 0. + * @warning When This mode is enabled, you can not be connected in any mode (Station, Access Point, or P2P).\n + * @see tstrM2MWifiMonitorModeCtrl + tstrM2MWifiRxPacketInfo + tstrWifiInitParam + tenuM2mScanCh + m2m_wifi_disable_monitoring_mode + m2m_wifi_send_wlan_pkt + m2m_wifi_send_ethernet_pkt + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + +*\section Example +* The example demonstrates the main function where-by the monitoring enable function is called after the initialization of the driver and the packets are +* handled in the callback function. +* @code + + #include "m2m_wifi.h" + #include "m2m_types.h" + + //Declare receive buffer + uint8 gmgmt[1600]; + + //Callback functions + void wifi_cb(uint8 u8WiFiEvent, void * pvMsg) + { + ; + } + void wifi_monitoring_cb(tstrM2MWifiRxPacketInfo *pstrWifiRxPacket, uint8 *pu8Payload, uint16 u16PayloadSize) + { + if((NULL != pstrWifiRxPacket) && (0 != u16PayloadSize)) { + if(MANAGEMENT == pstrWifiRxPacket->u8FrameType) { + M2M_INFO("***# MGMT PACKET #***\n"); + } else if(DATA_BASICTYPE == pstrWifiRxPacket->u8FrameType) { + M2M_INFO("***# DATA PACKET #***\n"); + } else if(CONTROL == pstrWifiRxPacket->u8FrameType) { + M2M_INFO("***# CONTROL PACKET #***\n"); + } + } + } + + int main() + { + //Register wifi_monitoring_cb + tstrWifiInitParam param; + param.pfAppWifiCb = wifi_cb; + param.pfAppMonCb = wifi_monitoring_cb; + + nm_bsp_init(); + + if(!m2m_wifi_init(¶m)) { + //Enable Monitor Mode with filter to receive all data frames on channel 1 + tstrM2MWifiMonitorModeCtrl strMonitorCtrl = {0}; + strMonitorCtrl.u8ChannelID = M2M_WIFI_CH_1; + strMonitorCtrl.u8FrameType = DATA_BASICTYPE; + strMonitorCtrl.u8FrameSubtype = M2M_WIFI_FRAME_SUB_TYPE_ANY; //Receive any subtype of data frame + m2m_wifi_enable_monitoring_mode(&strMonitorCtrl, gmgmt, sizeof(gmgmt), 0); + + while(1) { + m2m_wifi_handle_events(NULL); + } + } + return 0; + } + * @endcode + */ +NMI_API sint8 m2m_wifi_enable_monitoring_mode(tstrM2MWifiMonitorModeCtrl *pstrMtrCtrl, uint8 *pu8PayloadBuffer, + uint16 u16BufferSize, uint16 u16DataOffset); +/**@}*/ +/** @defgroup WifiDisableMonitorModeFn m2m_wifi_disable_monitoring_mode + * @ingroup WLANAPI + * Synchronous function to disable Wi-Fi monitoring mode (Promiscuous mode). Expected to be called, if the enable monitoring mode is set, but if it was called without enabling + * no negative impact will reside. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_disable_monitoring_mode(void); + * @see m2m_wifi_enable_monitoring_mode + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_disable_monitoring_mode(void); + /**@}*/ + /** @defgroup SendWlanPktFn m2m_wifi_send_wlan_pkt + * @ingroup WLANAPI + * Synchronous function to transmit a WIFI RAW packet while the implementation of this packet is left to the application developer. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_send_wlan_pkt(uint8 *, uint16, uint16); + + * @param [in] pu8WlanPacket + * Pointer to a buffer holding the whole WIFI frame. + * @param [in] u16WlanHeaderLength + * The size of the WIFI packet header ONLY. + * @param [in] u16WlanPktSize + * The size of the whole bytes in packet. + * @see m2m_wifi_enable_monitoring_mode + m2m_wifi_disable_monitoring_mode + * @pre Enable Monitoring mode first using @ref m2m_wifi_enable_monitoring_mode + * @warning This function available in monitoring mode ONLY.\n + * @note Packets are user's responsibility. + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_send_wlan_pkt(uint8 *pu8WlanPacket, uint16 u16WlanHeaderLength, uint16 u16WlanPktSize); +/**@}*/ +/** @defgroup WifiSendEthernetPktFn m2m_wifi_send_ethernet_pkt + * @ingroup WLANAPI + * Synchronous function to transmit an Ethernet packet. Transmit a packet directly in ETHERNET/bypass mode where the TCP/IP stack is disabled and the implementation of this packet is left to the application developer. + * The Ethernet packet composition is left to the application developer. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_send_ethernet_pkt(uint8* pu8Packet,uint16 u16PacketSize) + * @param [in] pu8Packet + * Pointer to a buffer holding the whole Ethernet frame. + * @param [in] u16PacketSize + * The size of the whole bytes in packet. + * @warning This function available in ETHERNET/Bypass mode ONLY. Make sure that application defines @ref ETH_MODE.\n + * @note Packets are the user's responsibility. + * @sa m2m_wifi_enable_mac_mcast,m2m_wifi_set_receive_buffer + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + + */ +NMI_API sint8 m2m_wifi_send_ethernet_pkt(uint8* pu8Packet,uint16 u16PacketSize); +/**@}*/ +/** @defgroup WifiEnableSntpFn m2m_wifi_enable_sntp + * @ingroup WLANAPI + * Synchronous function to enable/disable the native Simple Network Time Protocol(SNTP) client in the WINC1500 firmware.\n + * The SNTP is enabled by default at start-up.The SNTP client at firmware is used to synchronize the system clock to the UTC time from the well known time + * servers (e.g. "time-c.nist.gov"). The SNTP client uses a default update cycle of 1 day. + * The UTC is important for checking the expiration date of X509 certificates used while establishing + * TLS (Transport Layer Security) connections. + * It is highly recommended to use it if there is no other means to get the UTC time. If there is a RTC + * on the host MCU, the SNTP could be disabled and the host should set the system time to the firmware + * using the @ref m2m_wifi_set_system_time function. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_enable_sntp(uint8); + * @param [in] bEnable +* Enabling/Disabling flag + * '0' :disable SNTP + * '1' :enable SNTP + * @see m2m_wifi_set_sytem_time + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_enable_sntp(uint8 bEnable); +/**@}*/ +/** @defgroup WifiSetSystemTime m2m_wifi_set_sytem_time + * @ingroup WLANAPI + * Synchronous function for setting the system time in time/date format (@ref uint32).\n + * The @ref tstrSystemTime structure can be used as a reference to the time values that should be set and pass its value as @ref uint32 + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_set_sytem_time(uint32); + * @param [in] u32UTCSeconds + * Seconds elapsed since January 1, 1900 (NTP Timestamp). + * @see m2m_wifi_enable_sntp + * tstrSystemTime + * @note If there is an RTC on the host MCU, the SNTP could be disabled and the host should set the system time to the firmware + * using the API @ref m2m_wifi_set_sytem_time. + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_set_sytem_time(uint32 u32UTCSeconds); +/**@}*/ +/** @defgroup WifiGetSystemTime m2m_wifi_get_sytem_time + * @ingroup WLANAPI + * Asynchronous function used to retrieve the system time through the use of the response @ref M2M_WIFI_RESP_GET_SYS_TIME. + * Response time retrieved is parsed into the members defined in the structure @ref tstrSystemTime. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_get_sytem_time(void); + * @see m2m_wifi_enable_sntp + tstrSystemTime + * @note Get the system time from the SNTP client + * using the API @ref m2m_wifi_get_sytem_time. + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_get_sytem_time(void); +/**@}*/ +/** @defgroup WifiSetCustInfoElementFn m2m_wifi_set_cust_InfoElement + * @ingroup WLANAPI + * Synchronous function to Add/Remove user-defined Information Element to the WIFIBeacon and Probe Response frames while chip mode is Access Point Mode.\n + * According to the information element layout shown bellow, if it is required to set new data for the information elements, pass in the buffer with the + * information according to the sizes and ordering defined bellow. However, if it's required to delete these IEs, fill the buffer with zeros. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_set_cust_InfoElement(uint8*); + * @param [in] pau8M2mCustInfoElement + * Pointer to Buffer containing the IE to be sent. It is the application developer's responsibility to ensure on the correctness of the information element's ordering passed in. + * @warning - Size of All elements combined must not exceed 255 byte.\n + * - Used in Access Point Mode \n + * @note IEs Format will be follow the following layout:\n + * @verbatim + --------------- ---------- ---------- ------------------- -------- -------- ----------- ---------------------- + | Byte[0] | Byte[1] | Byte[2] | Byte[3:length1+2] | ..... | Byte[n] | Byte[n+1] | Byte[n+2:lengthx+2] | + |---------------|----------|----------|-------------------|-------- --------|-----------|------------------| + | #of all Bytes | IE1 ID | Length1 | Data1(Hex Coded) | ..... | IEx ID | Lengthx | Datax(Hex Coded) | + --------------- ---------- ---------- ------------------- -------- -------- ----------- ---------------------- + * @endverbatim + * @see m2m_wifi_enable_sntp + * tstrSystemTime + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + \section Example + The example demonstrates how the information elements are set using this function. + *@code + * + char elementData[21]; + static char state = 0; // To Add, Append, and Delete + if(0 == state) { //Add 3 IEs + state = 1; + //Total Number of Bytes + elementData[0]=12; + //First IE + elementData[1]=200; elementData[2]=1; elementData[3]='A'; + //Second IE + elementData[4]=201; elementData[5]=2; elementData[6]='B'; elementData[7]='C'; + //Third IE + elementData[8]=202; elementData[9]=3; elementData[10]='D'; elementData[11]=0; elementData[12]='F'; + } else if(1 == state) { + //Append 2 IEs to others, Notice that we keep old data in array starting with\n + //element 13 and total number of bytes increased to 20 + state = 2; + //Total Number of Bytes + elementData[0]=20; + //Fourth IE + elementData[13]=203; elementData[14]=1; elementData[15]='G'; + //Fifth IE + elementData[16]=204; elementData[17]=3; elementData[18]='X'; elementData[19]=5; elementData[20]='Z'; + } else if(2 == state) { //Delete All IEs + state = 0; + //Total Number of Bytes + elementData[0]=0; + } + m2m_wifi_set_cust_InfoElement(elementData); + * @endcode + */ +NMI_API sint8 m2m_wifi_set_cust_InfoElement(uint8* pau8M2mCustInfoElement); + /**@}*/ +/** @defgroup WifiSetPowerProfile m2m_wifi_set_power_profile + * @ingroup WLANAPI + * Change the power profile mode + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode); +@brief +@param [in] u8PwrMode + Change the WINC1500 power profile to different mode based on the enumeration + @ref tenuM2mPwrMode +@pre Must be called after the initializations and before any connection request and can't be changed in run time. +@sa tenuM2mPwrMode + m2m_wifi_init +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode); + /**@}*/ + /** @defgroup WifiSetTxPower m2m_wifi_set_tx_power + * @ingroup WLANAPI + * Set the TX power tenuM2mTxPwrLevel + */ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel); +@param [in] u8TxPwrLevel + change the TX power based on the enumeration tenuM2mTxPwrLevel +@pre Must be called after the initialization and before any connection request and can't be changed in runtime. +@sa tenuM2mTxPwrLevel + m2m_wifi_init +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel); + /**@}*/ +/** @defgroup WifiEnableFirmware m2m_wifi_enable_firmware_logs +* @ingroup WLANAPI +* Enable or Disable logs in run time (Disabling Firmware logs will +* enhance the firmware start-up time and performance) +*/ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable); +@param [in] u8Enable + Set 1 to enable the logs, 0 for disable +@pre Must be called after intialization through the following function @ref m2m_wifi_init +@sa __DISABLE_FIRMWARE_LOGS__ (build option to disable logs from initializations) + m2m_wifi_init +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable); + /**@}*/ + /** @defgroup WifiSetBatteryVoltage m2m_wifi_set_battery_voltage +* @ingroup WLANAPI +* Set the battery voltage to update the firmware calculations +*/ + /**@{*/ +/*! +@fn NMI_API sint8 m2m_wifi_set_battery_voltage(uint8 u8BattVolt) +@brief Set the battery voltage to update the firmware calculations +@param [in] dbBattVolt + Battery Volt in double +@pre Must be called after intialization through the following function @ref m2m_wifi_init +@sa m2m_wifi_init +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +sint8 m2m_wifi_set_battery_voltage(uint16 u16BattVoltx100); + /**@}*/ + /** @defgroup WifiSetGains m2m_wifi_set_gains +* @ingroup WLANAPI +* Set the chip gains mainly (PPA for 11b/11gn) +*/ + /**@{*/ +/*! +@fn sint8 m2m_wifi_set_gains(tstrM2mWifiGainsParams* pstrM2mGain); +@brief Set the chip PPA gain for 11b/11gn +@param [in] pstrM2mGain + tstrM2mWifiGainsParams contain gain parmaters as implemnted in rf document +@pre Must be called after intialization through the following function @ref m2m_wifi_init +@sa m2m_wifi_init +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +sint8 m2m_wifi_set_gains(tstrM2mWifiGainsParams* pstrM2mGain); + /**@}*/ +/** @defgroup WifiGetFirmwareVersion m2m_wifi_get_firmware_version +* @ingroup WLANAPI +* Get Firmware version info as defined in the structure @ref tstrM2mRev. +*/ + /**@{*/ +/*! +@fn m2m_wifi_get_firmware_version(tstrM2mRev* pstrRev) +@param [out] M2mRev + Pointer to the structure @ref tstrM2mRev that contains the firmware version parameters +@pre Must be called after intialization through the following function @ref m2m_wifi_init +@sa m2m_wifi_init +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +sint8 m2m_wifi_get_firmware_version(tstrM2mRev *pstrRev); +/**@}*/ +#ifdef ETH_MODE +/** @defgroup WifiEnableMacMcastFn m2m_wifi_enable_mac_mcast + * @ingroup WLANAPI + * Synchronous function for filtering received MAC addresses from certain MAC address groups. + * This function allows the addtion/removal of certain MAC addresses, used in the multicast filter. + */ + /**@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8 *, uint8); + * @brief + * @param [in] pu8MulticastMacAddress + * Pointer to MAC address + * @param [in] u8AddRemove + * A flag to add or remove the MAC ADDRESS, based on the following values: + * - 0 : remove MAC address + * - 1 : add MAC address + * @warning This function is available in ETHERNET/bypass mode ONLY. Make sure that the application defines @ref ETH_MODE.\n + * @note Maximum number of MAC addresses that could be added is 8. + * @sa m2m_wifi_set_receive_buffer, m2m_wifi_send_ethernet_pkt + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8* pu8MulticastMacAddress, uint8 u8AddRemove); +/**@}*/ +/** @defgroup SetReceiveBufferFn m2m_wifi_set_receive_buffer + * @ingroup WLANAPI + * Synchronous function for setting or modifying the receiver buffer's length. + * In the ETHERNET/bypass mode the application should define a callback of type @ref tpfAppEthCb, through which the application handles the received + * ethernet frames. It is through this callback function that the user can dynamically modify the length of the currently used receiver buffer. + *@{*/ +/*! + * @fn NMI_API sint8 m2m_wifi_set_receive_buffer(void *, uint16); + + * @param [in] pvBuffer + * Pointer to Buffer to receive data. + * NULL pointer causes a negative error @ref M2M_ERR_FAIL. + * + * @param [in] u16BufferLen + * Length of data to be received. Maximum length of data should not exceed the size defined by TCP/IP + * defined as @ref SOCKET_BUFFER_MAX_LENGTH + * + * @warning This function is available in the Ethernet/bypass mode ONLY. Make sure that the application defines @ref ETH_MODE.\n + * @sa m2m_wifi_enable_mac_mcast,m2m_wifi_send_ethernet_pkt + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +NMI_API sint8 m2m_wifi_set_receive_buffer(void* pvBuffer,uint16 u16BufferLen); +/**@}*/ +#endif /* ETH_MODE */ +/** @defgroup GetPrngBytes m2m_wifi_prng_get_random_bytes + * @ingroup WLANAPI + * Asynchronous function for retrieving from the firmware a pseudo-random set of bytes as specifed in the size passed in as a parameter. + * The registered wifi-cb function retrieves the random bytes through the response @ref M2M_WIFI_RESP_GET_PRNG + *@{*/ +/*! + * @fn sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PRNGBuff,uint16 u16PRNGSize) + * @param [out] pu8PrngBuff + * Pointer to a buffer to receive data. + * @param [in] u16PrngSize + * Request size in bytes + *@warning Size greater than the maximum specified (@ref M2M_BUFFER_MAX_SIZE - sizeof(tstrPrng)) + * causes a negative error @ref M2M_ERR_FAIL. + *@see tstrPrng + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PrngBuff,uint16 u16PrngSize); +/**@}*/ +#ifdef __cplusplus +} +#endif +#endif /* __M2M_WIFI_H__ */ + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ate_mode.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ate_mode.c new file mode 100644 index 0000000..beb1af8 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ate_mode.c @@ -0,0 +1,826 @@ +/** + * + * \file + * + * \brief NMC1500 Peripherials Application Interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifdef _M2M_ATE_FW_ +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#include "driver/include/m2m_ate_mode.h" +#include "driver/source/nmasic.h" +#include "driver/source/nmdrv.h" +#include "m2m_hif.h" +#include "driver/source/nmbus.h" +#include "bsp/include/nm_bsp.h" + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#define rInterrupt_CORTUS_0 (0x10a8) +#define rInterrupt_CORTUS_1 (0x10ac) +#define rInterrupt_CORTUS_2 (0x10b0) + +#define rBurstTx_NMI_TX_RATE (0x161d00) +#define rBurstTx_NMI_NUM_TX_FRAMES (0x161d04) +#define rBurstTx_NMI_TX_FRAME_LEN (0x161d08) +#define rBurstTx_NMI_TX_CW_PARAM (0x161d0c) +#define rBurstTx_NMI_TX_GAIN (0x161d10) +#define rBurstTx_NMI_TX_DPD_CTRL (0x161d14) +#define rBurstTx_NMI_USE_PMU (0x161d18) +#define rBurstTx_NMI_TEST_CH (0x161d1c) +#define rBurstTx_NMI_TX_PHY_CONT (0x161d20) +#define rBurstTx_NMI_TX_CW_MODE (0x161d24) +#define rBurstTx_NMI_TEST_XO_OFF (0x161d28) +#define rBurstTx_NMI_USE_EFUSE_XO_OFF (0x161d2c) + +#define rBurstTx_NMI_MAC_FILTER_ENABLE_DA (0x161d30) +#define rBurstTx_NMI_MAC_ADDR_LO_PEER (0x161d34) +#define rBurstTx_NMI_MAC_ADDR_LO_SELF (0x161d38) +#define rBurstTx_NMI_MAC_ADDR_HI_PEER (0x161d3c) +#define rBurstTx_NMI_MAC_ADDR_HI_SELF (0x161d40) +#define rBurstTx_NMI_RX_PKT_CNT_SUCCESS (0x161d44) +#define rBurstTx_NMI_RX_PKT_CNT_FAIL (0x161d48) +#define rBurstTx_NMI_SET_SELF_MAC_ADDR (0x161d4c) +#define rBurstTx_NMI_MAC_ADDR_LO_SA (0x161d50) +#define rBurstTx_NMI_MAC_ADDR_HI_SA (0x161d54) +#define rBurstTx_NMI_MAC_FILTER_ENABLE_SA (0x161d58) + +#define rBurstRx_NMI_RX_ALL_PKTS_CONT (0x9898) +#define rBurstRx_NMI_RX_ERR_PKTS_CONT (0x988c) + +#define TX_DGAIN_MAX_NUM_REGS (4) +#define TX_DGAIN_REG_BASE_ADDRESS (0x1240) +#define TX_GAIN_CODE_MAX_NUM_REGS (3) +#define TX_GAIN_CODE_BASE_ADDRESS (0x1250) +#define TX_PA_MAX_NUM_REGS (3) +#define TX_PA_BASE_ADDRESS (0x1e58) +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +VARIABLES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +volatile static uint8 gu8AteIsRunning = 0; /*!< ATE firmware status, 1 means ATE is running otherwise stopped */ +volatile static uint8 gu8RxState = 0; /*!< RX status, 1 means Rx is running otherwise stopped */ +volatile static uint8 gu8TxState = 0; /*!< TX status, 1 means Tx is running otherwise stopped */ +volatile static uint32 gaAteFwTxRates[M2M_ATE_MAX_NUM_OF_RATES] = +{ + 0x01, 0x02, 0x05, 0x0B, /*B-Rats*/ + 0x06, 0x09, 0x0C, 0x12, 0x18, 0x24, 0x30, 0x36, /*G-Rats*/ + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87 /*N-Rats*/ +}; + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +STATIC FUNCTIONS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +static void m2m_ate_set_rx_status(uint8 u8Value) +{ + gu8RxState = u8Value; +} + +static void m2m_ate_set_tx_status(uint8 u8Value) +{ + gu8TxState = u8Value; +} + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION IMPLEMENTATION +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/*! +@fn \ + sint8 m2m_ate_init(void); + +@brief + This function used to download ATE firmware from flash and start it + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_init(void) +{ + sint8 s8Ret = M2M_SUCCESS; + uint8 u8WifiMode = M2M_WIFI_MODE_ATE_HIGH; + + s8Ret = nm_drv_init(&u8WifiMode); + + return s8Ret; +} + +/*! +@fn \ + sint8 m2m_ate_init(tstrM2mAteInit *pstrInit); + +@brief + This function used to download ATE firmware from flash and start it + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_init_param(tstrM2mAteInit *pstrInit) +{ + sint8 s8Ret = M2M_SUCCESS; + + s8Ret = nm_drv_init((void*)&pstrInit->u8RxPwrMode); + + return s8Ret; +} + +/*! +@fn \ + sint8 m2m_ate_deinit(void); + +@brief + De-Initialization of ATE firmware mode + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_deinit(void) +{ + return nm_drv_deinit(NULL); +} + +/*! +@fn \ + sint8 m2m_ate_set_fw_state(uint8); + +@brief + This function used to change ATE firmware status from running to stopped or vice versa. + +@param [in] u8State + Required state of ATE firmware, one of \ref tenuM2mAteFwState enumeration values. +@return + The function SHALL return 0 for success and a negative value otherwise. +\sa + m2m_ate_init +*/ +sint8 m2m_ate_set_fw_state(uint8 u8State) +{ + sint8 s8Ret = M2M_SUCCESS; + uint32_t u32Val = 0; + + if((M2M_ATE_FW_STATE_STOP == u8State) && (M2M_ATE_FW_STATE_STOP != gu8AteIsRunning)) + { + u32Val = nm_read_reg(rNMI_GLB_RESET); + u32Val &= ~(1 << 10); + s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val); + gu8AteIsRunning = M2M_ATE_FW_STATE_STOP; + } + else if((M2M_ATE_FW_STATE_RUN == u8State) && (M2M_ATE_FW_STATE_RUN != gu8AteIsRunning)) + { + /* 0x1118[0]=0 at power-on-reset: pad-based control. */ + /* Switch cortus reset register to register control. 0x1118[0]=1. */ + u32Val = nm_read_reg(rNMI_BOOT_RESET_MUX); + u32Val |= (1 << 0); + s8Ret = nm_write_reg(rNMI_BOOT_RESET_MUX, u32Val); + if(M2M_SUCCESS != s8Ret) + { + goto __EXIT; + } + /** + Write the firmware download complete magic value 0x10ADD09E at + location 0xFFFF000C (Cortus map) or C000C (AHB map). + This will let the boot-rom code execute from RAM. + **/ + s8Ret = nm_write_reg(0xc0000, 0x71); + if(M2M_SUCCESS != s8Ret) + { + goto __EXIT; + } + + u32Val = nm_read_reg(rNMI_GLB_RESET); + if((u32Val & (1ul << 10)) == (1ul << 10)) + { + u32Val &= ~(1ul << 10); + s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val); + if(M2M_SUCCESS != s8Ret) + { + goto __EXIT; + } + } + + u32Val |= (1ul << 10); + s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val); + if(M2M_SUCCESS != s8Ret) + { + goto __EXIT; + } + gu8AteIsRunning = M2M_ATE_FW_STATE_RUN; + } + else + { + s8Ret = M2M_ATE_ERR_UNHANDLED_CASE; + } + +__EXIT: + if((M2M_SUCCESS == s8Ret) && (M2M_ATE_FW_STATE_RUN == gu8AteIsRunning)) + { + nm_bsp_sleep(500); /*wait for ATE firmware start up*/ + } + return s8Ret; +} + +/*! +@fn \ + sint8 m2m_ate_get_fw_state(uint8); + +@brief + This function used to return status of ATE firmware. + +@return + The function SHALL return status of ATE firmware, one of \ref tenuM2mAteFwState enumeration values. +\sa + m2m_ate_init, m2m_ate_set_fw_state +*/ +sint8 m2m_ate_get_fw_state(void) +{ + return gu8AteIsRunning; +} + +/*! +@fn \ + uint32 m2m_ate_get_tx_rate(uint8); + +@brief + This function used to return value of TX rate required by application developer. + +@param [in] u8Index + Index of required rate , one of \ref tenuM2mAteTxIndexOfRates enumeration values. +@return + The function SHALL return 0 for in case of failure otherwise selected rate value. +\sa + tenuM2mAteTxIndexOfRates +*/ +uint32 m2m_ate_get_tx_rate(uint8 u8Index) +{ + if(M2M_ATE_MAX_NUM_OF_RATES <= u8Index) + { + return 0; + } + return gaAteFwTxRates[u8Index]; +} + +/*! +@fn \ + sint8 m2m_ate_get_tx_status(void); + +@brief + This function used to return status of TX test case either running or stopped. + +@return + The function SHALL return status of ATE firmware, 1 if TX is running otherwise 0. +\sa + m2m_ate_start_tx, m2m_ate_stop_tx +*/ +sint8 m2m_ate_get_tx_status(void) +{ + return gu8TxState; +} + +/*! +@fn \ + sint8 m2m_ate_start_tx(tstrM2mAteTx *) + +@brief + This function used to start TX test case. + +@param [in] strM2mAteTx + Type of \ref tstrM2mAteTx, with the values required to enable TX test case. You must use \ref m2m_ate_init first. +@return + The function SHALL return 0 for success and a negative value otherwise. +\sa + m2m_ate_init, m2m_ate_stop_tx, m2m_ate_get_tx_status +*/ +sint8 m2m_ate_start_tx(tstrM2mAteTx * strM2mAteTx) +{ + sint8 s8Ret = M2M_SUCCESS; + uint8 u8LoopCntr = 0; + uint32_t val32; + + + if(NULL == strM2mAteTx) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + if(0 != m2m_ate_get_tx_status()) + { + s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING; + goto __EXIT; + } + + if(0 != m2m_ate_get_rx_status()) + { + s8Ret = M2M_ATE_ERR_RX_ALREADY_RUNNING; + goto __EXIT; + } + + if( (strM2mAteTx->channel_num < M2M_ATE_CHANNEL_1) || + (strM2mAteTx->channel_num > M2M_ATE_CHANNEL_14) || + (strM2mAteTx->tx_gain_sel < M2M_ATE_TX_GAIN_DYNAMIC) || + (strM2mAteTx->tx_gain_sel > M2M_ATE_TX_GAIN_TELEC) || + (strM2mAteTx->frame_len > M2M_ATE_MAX_FRAME_LENGTH) || + (strM2mAteTx->frame_len < M2M_ATE_MIN_FRAME_LENGTH) + ) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + if( (strM2mAteTx->duty_cycle < M2M_ATE_TX_DUTY_MAX_VALUE /*1*/) || + (strM2mAteTx->duty_cycle > M2M_ATE_TX_DUTY_MIN_VALUE /*10*/ ) || + (strM2mAteTx->dpd_ctrl < M2M_ATE_TX_DPD_DYNAMIC) || + (strM2mAteTx->dpd_ctrl > M2M_ATE_TX_DPD_ENABLED) || + (strM2mAteTx->use_pmu > M2M_ATE_PMU_ENABLE) || + (strM2mAteTx->phy_burst_tx < M2M_ATE_TX_SRC_MAC) || + (strM2mAteTx->phy_burst_tx > M2M_ATE_TX_SRC_PHY) || + (strM2mAteTx->cw_tx < M2M_ATE_TX_MODE_NORM) || + (strM2mAteTx->cw_tx > M2M_ATE_TX_MODE_CW) + ) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + for(u8LoopCntr=0; u8LoopCntrdata_rate) + { + break; + } + } + + if(M2M_ATE_MAX_NUM_OF_RATES == u8LoopCntr) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + + + s8Ret += nm_write_reg(rBurstTx_NMI_USE_PMU, strM2mAteTx->use_pmu); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_PHY_CONT, strM2mAteTx->phy_burst_tx); + s8Ret += nm_write_reg(rBurstTx_NMI_NUM_TX_FRAMES, strM2mAteTx->num_frames); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_GAIN, strM2mAteTx->tx_gain_sel); + s8Ret += nm_write_reg(rBurstTx_NMI_TEST_CH, strM2mAteTx->channel_num); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_FRAME_LEN, strM2mAteTx->frame_len); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_CW_PARAM, strM2mAteTx->duty_cycle); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_DPD_CTRL, strM2mAteTx->dpd_ctrl); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_RATE, strM2mAteTx->data_rate); + s8Ret += nm_write_reg(rBurstTx_NMI_TX_CW_MODE, strM2mAteTx->cw_tx); + s8Ret += nm_write_reg(rBurstTx_NMI_TEST_XO_OFF, strM2mAteTx->xo_offset_x1000); + s8Ret += nm_write_reg(rBurstTx_NMI_USE_EFUSE_XO_OFF, strM2mAteTx->use_efuse_xo_offset); + + val32 = strM2mAteTx->peer_mac_addr[5] << 0; + val32 |= strM2mAteTx->peer_mac_addr[4] << 8; + val32 |= strM2mAteTx->peer_mac_addr[3] << 16; + nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_PEER, val32 ); + + val32 = strM2mAteTx->peer_mac_addr[2] << 0; + val32 |= strM2mAteTx->peer_mac_addr[1] << 8; + val32 |= strM2mAteTx->peer_mac_addr[0] << 16; + nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_PEER, val32 ); + + if(M2M_SUCCESS == s8Ret) + { + s8Ret += nm_write_reg(rInterrupt_CORTUS_0, 1); /*Interrupt Cortus*/ + m2m_ate_set_tx_status(1); + nm_bsp_sleep(200); /*Recommended*/ + } + +__EXIT: + return s8Ret; +} + +/*! +@fn \ + sint8 m2m_ate_stop_tx(void) + +@brief + This function used to stop TX test case. + +@return + The function SHALL return 0 for success and a negative value otherwise. +\sa + m2m_ate_init, m2m_ate_start_tx, m2m_ate_get_tx_status +*/ +sint8 m2m_ate_stop_tx(void) +{ + sint8 s8Ret = M2M_SUCCESS; + + s8Ret = nm_write_reg(rInterrupt_CORTUS_1, 1); + if(M2M_SUCCESS == s8Ret) + { + m2m_ate_set_tx_status(0); + } + + return s8Ret; +} + +/*! +@fn \ + sint8 m2m_ate_get_rx_status(uint8); + +@brief + This function used to return status of RX test case either running or stopped. + +@return + The function SHALL return status of ATE firmware, 1 if RX is running otherwise 0. +\sa + m2m_ate_start_rx, m2m_ate_stop_rx +*/ +sint8 m2m_ate_get_rx_status(void) +{ + return gu8RxState; +} + +/*! +@fn \ + sint8 m2m_ate_start_rx(tstrM2mAteRx *) + +@brief + This function used to start RX test case. + +@param [in] strM2mAteRx + Type of \ref tstrM2mAteRx, with the values required to enable RX test case. You must use \ref m2m_ate_init first. +@return + The function SHALL return 0 for success and a negative value otherwise. +\sa + m2m_ate_init, m2m_ate_stop_rx, m2m_ate_get_rx_status +*/ +sint8 m2m_ate_start_rx(tstrM2mAteRx * strM2mAteRxStr) +{ + sint8 s8Ret = M2M_SUCCESS; + uint32 val32; + if(NULL == strM2mAteRxStr) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + if(0 != m2m_ate_get_tx_status()) + { + s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING; + goto __EXIT; + } + + if(0 != m2m_ate_get_rx_status()) + { + s8Ret = M2M_ATE_ERR_RX_ALREADY_RUNNING; + goto __EXIT; + } + + if( (strM2mAteRxStr->channel_num < M2M_ATE_CHANNEL_1) || + (strM2mAteRxStr->channel_num > M2M_ATE_CHANNEL_14)|| + (strM2mAteRxStr->use_pmu > M2M_ATE_PMU_ENABLE) + ) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + s8Ret += nm_write_reg(rBurstTx_NMI_TEST_CH, strM2mAteRxStr->channel_num); + s8Ret += nm_write_reg(rBurstTx_NMI_USE_PMU, strM2mAteRxStr->use_pmu); + s8Ret += nm_write_reg(rBurstTx_NMI_TEST_XO_OFF, strM2mAteRxStr->xo_offset_x1000); + s8Ret += nm_write_reg(rBurstTx_NMI_USE_EFUSE_XO_OFF, strM2mAteRxStr->use_efuse_xo_offset); + + if(strM2mAteRxStr->override_self_mac_addr) + { + val32 = strM2mAteRxStr->self_mac_addr[5] << 0; + val32 |= strM2mAteRxStr->self_mac_addr[4] << 8; + val32 |= strM2mAteRxStr->self_mac_addr[3] << 16; + nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_SELF, val32 ); + + val32 = strM2mAteRxStr->self_mac_addr[2] << 0; + val32 |= strM2mAteRxStr->self_mac_addr[1] << 8; + val32 |= strM2mAteRxStr->self_mac_addr[0] << 16; + nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_SELF, val32 ); + } + + if(strM2mAteRxStr->mac_filter_en_sa) + { + val32 = strM2mAteRxStr->peer_mac_addr[5] << 0; + val32 |= strM2mAteRxStr->peer_mac_addr[4] << 8; + val32 |= strM2mAteRxStr->peer_mac_addr[3] << 16; + nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_SA, val32 ); + + val32 = strM2mAteRxStr->peer_mac_addr[2] << 0; + val32 |= strM2mAteRxStr->peer_mac_addr[1] << 8; + val32 |= strM2mAteRxStr->peer_mac_addr[0] << 16; + nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_SA, val32 ); + } + + nm_write_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_DA, strM2mAteRxStr->mac_filter_en_da); + nm_write_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_SA, strM2mAteRxStr->mac_filter_en_sa); + nm_write_reg(rBurstTx_NMI_SET_SELF_MAC_ADDR, strM2mAteRxStr->override_self_mac_addr); + + if(M2M_SUCCESS == s8Ret) + { + s8Ret += nm_write_reg(rInterrupt_CORTUS_2, 1); /*Interrupt Cortus*/ + m2m_ate_set_rx_status(1); + nm_bsp_sleep(10); /*Recommended*/ + } + +__EXIT: + return s8Ret; +} + +/*! +@fn \ + sint8 m2m_ate_stop_rx(void) + +@brief + This function used to stop RX test case. + +@return + The function SHALL return 0 for success and a negative value otherwise. +\sa + m2m_ate_init, m2m_ate_start_rx, m2m_ate_get_rx_status +*/ +sint8 m2m_ate_stop_rx(void) +{ + m2m_ate_set_rx_status(0); + nm_bsp_sleep(200); /*Recommended*/ + return M2M_SUCCESS; +} + +/*! +@fn \ + sint8 m2m_ate_read_rx_status(tstrM2mAteRxStatus *) + +@brief + This function used to read RX statistics from ATE firmware. + +@param [out] strM2mAteRxStatus + Type of \ref tstrM2mAteRxStatus used to save statistics of RX test case. You must use \ref m2m_ate_start_rx first. +@return + The function SHALL return 0 for success and a negative value otherwise. +\sa + m2m_ate_init, m2m_ate_start_rx +*/ +sint8 m2m_ate_read_rx_status(tstrM2mAteRxStatus *strM2mAteRxStatus) +{ + sint8 s8Ret = M2M_SUCCESS; + + if(NULL == strM2mAteRxStatus) + { + s8Ret = M2M_ATE_ERR_VALIDATE; + goto __EXIT; + } + + if(0 != m2m_ate_get_tx_status()) + { + s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING; + goto __EXIT; + } + + if (nm_read_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_DA) || nm_read_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_SA)) + { + strM2mAteRxStatus->num_rx_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_SUCCESS) + nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_FAIL); + strM2mAteRxStatus->num_good_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_SUCCESS); + strM2mAteRxStatus->num_err_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_FAIL); + } + else + { + strM2mAteRxStatus->num_rx_pkts = nm_read_reg(rBurstRx_NMI_RX_ALL_PKTS_CONT) + nm_read_reg(0x989c); + strM2mAteRxStatus->num_err_pkts = nm_read_reg(rBurstRx_NMI_RX_ERR_PKTS_CONT); + strM2mAteRxStatus->num_good_pkts = strM2mAteRxStatus->num_rx_pkts - strM2mAteRxStatus->num_err_pkts; + } + +__EXIT: + return s8Ret; +} +/*! +@fn \ + sint8 m2m_ate_set_dig_gain(double dGaindB) + +@brief + This function is used to set the digital gain + +@param [in] double dGaindB + The digital gain value required to be set. +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_set_dig_gain(double dGaindB) +{ + uint32_t dGain, val32; + dGain = (uint32_t)(pow(10, dGaindB/20.0) * 1024.0); + + val32 = nm_read_reg(0x160cd0); + val32 &= ~(0x1ffful << 0); + val32 |= (((uint32_t)dGain) << 0); + nm_write_reg(0x160cd0, val32); + return M2M_SUCCESS; +} +/*! +@fn \ + sint8 m2m_ate_get_dig_gain(double * dGaindB) + +@brief + This function is used to get the digital gain + +@param [out] double * dGaindB + The retrieved digital gain value obtained from HW registers in dB. +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_get_dig_gain(double * dGaindB) +{ + uint32 dGain, val32; + + if(!dGaindB) return M2M_ERR_INVALID_ARG; + + val32 = nm_read_reg(0x160cd0); + + dGain = (val32 >> 0) & 0x1ffful; + *dGaindB = 20.0*log10((double)dGain / 1024.0); + + return M2M_SUCCESS; +} +/*! +@fn \ + void m2m_ate_set_pa_gain(uint8 gain_db) + +@brief + This function is used to set the PA gain (18/15/12/9/6/3/0 only) + +@param [in] uint8 gain_db + PA gain level allowed (18/15/12/9/6/3/0 only) + +*/ +void m2m_ate_set_pa_gain(uint8 gain_db) +{ + uint32 PA_1e9c; + uint8 aGain[] = { + /* "0 dB" */ 0x00, + /* "3 dB" */ 0x01, + /* "6 dB" */ 0x03, + /* "9 dB" */ 0x07, + /* "12 dB" */ 0x0f, + /* "15 dB" */ 0x1f, + /* "18 dB" */ 0x3f }; + /* The variable PA gain is valid only for High power mode */ + PA_1e9c = nm_read_reg(0x1e9c); + /* TX bank 0. */ + PA_1e9c &= ~(0x3ful << 8); + PA_1e9c |= (((uint32)aGain[gain_db/3] & 0x3f) << 8); + nm_write_reg(0x1e9c, PA_1e9c); +} +/*! +@fn \ + sint8 m2m_ate_get_pa_gain(double *paGaindB) + +@brief + This function is used to get the PA gain + +@param [out] double *paGaindB + The retrieved PA gain value obtained from HW registers in dB. +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_get_pa_gain(double *paGaindB) +{ + uint32 val32, paGain; + uint32 m_cmbPAGainStep; + + if(!paGaindB) + return M2M_ERR_INVALID_ARG; + + val32 = nm_read_reg(0x1e9c); + + paGain = (val32 >> 8) & 0x3f; + + switch(paGain){ + case 0x1: + m_cmbPAGainStep = 5; + break; + case 0x3: + m_cmbPAGainStep = 4; + break; + case 0x7: + m_cmbPAGainStep = 3; + break; + case 0xf: + m_cmbPAGainStep = 2; + break; + case 0x1f: + m_cmbPAGainStep = 1; + break; + case 0x3f: + m_cmbPAGainStep = 0; + break; + default: + m_cmbPAGainStep = 0; + break; + } + + *paGaindB = 18 - m_cmbPAGainStep*3; + + return M2M_SUCCESS; +} +/*! +@fn \ + sint8 m2m_ate_get_ppa_gain(double * ppaGaindB) + +@brief + This function is used to get the PPA gain + +@param [out] uint32 * ppaGaindB + The retrieved PPA gain value obtained from HW registers in dB. +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_get_ppa_gain(double * ppaGaindB) +{ + uint32 val32, ppaGain, m_cmbPPAGainStep; + + if(!ppaGaindB) return M2M_ERR_INVALID_ARG; + + val32 = nm_read_reg(0x1ea0); + + ppaGain = (val32 >> 5) & 0x7; + + switch(ppaGain){ + case 0x1: + m_cmbPPAGainStep = 2; + break; + case 0x3: + m_cmbPPAGainStep = 1; + break; + case 0x7: + m_cmbPPAGainStep = 0; + break; + default: + m_cmbPPAGainStep = 3; + break; + } + + *ppaGaindB = 9 - m_cmbPPAGainStep*3; + + + return M2M_SUCCESS; +} +/*! +@fn \ + sint8 m2m_ate_get_tot_gain(double * totGaindB) + +@brief + This function is used to calculate the total gain + +@param [out] double * totGaindB + The retrieved total gain value obtained from calculations made based on the digital gain, PA and PPA gain values. +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +sint8 m2m_ate_get_tot_gain(double * totGaindB) +{ + double dGaindB, paGaindB, ppaGaindB; + + if(!totGaindB) return M2M_ERR_INVALID_ARG; + + m2m_ate_get_pa_gain(&paGaindB); + m2m_ate_get_ppa_gain(&ppaGaindB); + m2m_ate_get_dig_gain(&dGaindB); + + *totGaindB = dGaindB + paGaindB + ppaGaindB; + + return M2M_SUCCESS; +} + +#endif //_M2M_ATE_FW_ \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_crypto.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_crypto.c new file mode 100644 index 0000000..9ac7711 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_crypto.c @@ -0,0 +1,1010 @@ +/** + * + * \file + * + * \brief WINC Crypto module. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "driver/include/m2m_crypto.h" +#include "driver/source/nmbus.h" +#include "driver/source/nmasic.h" + +#ifdef CONF_CRYPTO_HW + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*======*======*======*======*======*=======* +* WINC SHA256 HW Engine Register Definition * +*======*======*======*======*======*========*/ + +#define SHA_BLOCK_SIZE (64) + +#define SHARED_MEM_BASE (0xd0000) + + +#define SHA256_MEM_BASE (0x180000UL) +#define SHA256_ENGINE_ADDR (0x180000ul) + +/* SHA256 Registers */ +#define SHA256_CTRL (SHA256_MEM_BASE+0x00) +#define SHA256_CTRL_START_CALC_MASK (NBIT0) +#define SHA256_CTRL_START_CALC_SHIFT (0) +#define SHA256_CTRL_PREPROCESS_MASK (NBIT1) +#define SHA256_CTRL_PREPROCESS_SHIFT (1) +#define SHA256_CTRL_HASH_HASH_MASK (NBIT2) +#define SHA256_CTRL_HASH_HASH_SHIFT (2) +#define SHA256_CTRL_INIT_SHA256_STATE_MASK (NBIT3) +#define SHA256_CTRL_INIT_SHA256_STATE_SHIFT (3) +#define SHA256_CTRL_WR_BACK_HASH_VALUE_MASK (NBIT4) +#define SHA256_CTRL_WR_BACK_HASH_VALUE_SHIFT (4) +#define SHA256_CTRL_FORCE_SHA256_QUIT_MASK (NBIT5) +#define SHA256_CTRL_FORCE_SHA256_QUIT_SHIFT (5) + +#define SHA256_REGS_SHA256_CTRL_AHB_BYTE_REV_EN (NBIT6) +#define SHA256_REGS_SHA256_CTRL_RESERVED (NBIT7) +#define SHA256_REGS_SHA256_CTRL_CORE_TO_AHB_CLK_RATIO (NBIT8+ NBIT9+ NBIT10) +#define SHA256_REGS_SHA256_CTRL_CORE_TO_AHB_CLK_RATIO_MASK (NBIT2+ NBIT1+ NBIT0) +#define SHA256_REGS_SHA256_CTRL_CORE_TO_AHB_CLK_RATIO_SHIFT (8) +#define SHA256_REGS_SHA256_CTRL_RESERVED_11 (NBIT11) +#define SHA256_REGS_SHA256_CTRL_SHA1_CALC (NBIT12) +#define SHA256_REGS_SHA256_CTRL_PBKDF2_SHA1_CALC (NBIT13) + + +#define SHA256_START_RD_ADDR (SHA256_MEM_BASE+0x04UL) +#define SHA256_DATA_LENGTH (SHA256_MEM_BASE+0x08UL) +#define SHA256_START_WR_ADDR (SHA256_MEM_BASE+0x0cUL) +#define SHA256_COND_CHK_CTRL (SHA256_MEM_BASE+0x10) +#define SHA256_COND_CHK_CTRL_HASH_VAL_COND_CHK_MASK (NBIT1 | NBIT0) +#define SHA256_COND_CHK_CTRL_HASH_VAL_COND_CHK_SHIFT (0) +#define SHA256_COND_CHK_CTRL_STEP_VAL_MASK (NBIT6 | NBIT5 | NBIT4 | NBIT3 | NBIT2) +#define SHA256_COND_CHK_CTRL_STEP_VAL_SHIFT (2) +#define SHA256_COND_CHK_CTRL_COND_CHK_RESULT_MASK (NBIT7) +#define SHA256_COND_CHK_CTRL_COND_CHK_RESULT_SHIFT (7) + +#define SHA256_MOD_DATA_RANGE (SHA256_MEM_BASE+0x14) +#define SHA256_MOD_DATA_RANGE_ST_BYTE_2_ADD_STP_MASK (NBIT24-1) +#define SHA256_MOD_DATA_RANGE_ST_BYTE_2_ADD_STP_SHIFT (0) +#define SHA256_MOD_DATA_RANGE_MOD_DATA_LEN_MASK (NBIT24 | NBIT25| NBIT26) +#define SHA256_MOD_DATA_RANGE_MOD_DATA_LEN_SHIFT (24) + + +#define SHA256_COND_CHK_STS_1 (SHA256_MEM_BASE+0x18) +#define SHA256_COND_CHK_STS_2 (SHA256_MEM_BASE+0x1c) +#define SHA256_DONE_INTR_ENABLE (SHA256_MEM_BASE+0x20) +#define SHA256_DONE_INTR_STS (SHA256_MEM_BASE+0x24) +#define SHA256_TARGET_HASH_H1 (SHA256_MEM_BASE+0x28) +#define SHA256_TARGET_HASH_H2 (SHA256_MEM_BASE+0x2c) +#define SHA256_TARGET_HASH_H3 (SHA256_MEM_BASE+0x30) +#define SHA256_TARGET_HASH_H4 (SHA256_MEM_BASE+0x34) +#define SHA256_TARGET_HASH_H5 (SHA256_MEM_BASE+0x38) +#define SHA256_TARGET_HASH_H6 (SHA256_MEM_BASE+0x3c) +#define SHA256_TARGET_HASH_H7 (SHA256_MEM_BASE+0x40) +#define SHA256_TARGET_HASH_H8 (SHA256_MEM_BASE+0x44) + +/*======*======*======*======*======*=======* +* WINC BIGINT HW Engine Register Definition * +*======*======*======*======*======*========*/ + + +#define BIGINT_ENGINE_ADDR (0x180080ul) +#define BIGINT_VERSION (BIGINT_ENGINE_ADDR + 0x00) + +#define BIGINT_MISC_CTRL (BIGINT_ENGINE_ADDR + 0x04) +#define BIGINT_MISC_CTRL_CTL_START (NBIT0) +#define BIGINT_MISC_CTRL_CTL_RESET (NBIT1) +#define BIGINT_MISC_CTRL_CTL_MSW_FIRST (NBIT2) +#define BIGINT_MISC_CTRL_CTL_SWAP_BYTE_ORDER (NBIT3) +#define BIGINT_MISC_CTRL_CTL_FORCE_BARRETT (NBIT4) +#define BIGINT_MISC_CTRL_CTL_M_PRIME_VALID (NBIT5) + +#define BIGINT_M_PRIME (BIGINT_ENGINE_ADDR + 0x08) + +#define BIGINT_STATUS (BIGINT_ENGINE_ADDR + 0x0C) +#define BIGINT_STATUS_STS_DONE (NBIT0) + +#define BIGINT_CLK_COUNT (BIGINT_ENGINE_ADDR + 0x10) +#define BIGINT_ADDR_X (BIGINT_ENGINE_ADDR + 0x14) +#define BIGINT_ADDR_E (BIGINT_ENGINE_ADDR + 0x18) +#define BIGINT_ADDR_M (BIGINT_ENGINE_ADDR + 0x1C) +#define BIGINT_ADDR_R (BIGINT_ENGINE_ADDR + 0x20) +#define BIGINT_LENGTH (BIGINT_ENGINE_ADDR + 0x24) + +#define BIGINT_IRQ_STS (BIGINT_ENGINE_ADDR + 0x28) +#define BIGINT_IRQ_STS_DONE (NBIT0) +#define BIGINT_IRQ_STS_CHOOSE_MONT (NBIT1) +#define BIGINT_IRQ_STS_M_READ (NBIT2) +#define BIGINT_IRQ_STS_X_READ (NBIT3) +#define BIGINT_IRQ_STS_START (NBIT4) +#define BIGINT_IRQ_STS_PRECOMP_FINISH (NBIT5) + +#define BIGINT_IRQ_MASK (BIGINT_ENGINE_ADDR + 0x2C) +#define BIGINT_IRQ_MASK_CTL_IRQ_MASK_START (NBIT4) + +#define ENABLE_FLIPPING 1 + + + + +#define GET_UINT32(BUF,OFFSET) (((uint32)((BUF)[OFFSET])) | ((uint32)(((BUF)[OFFSET + 1]) << 8)) | \ +((uint32)(((BUF)[OFFSET + 2]) << 16)) | ((uint32)(((BUF)[OFFSET + 3]) << 24))) + +#define PUTU32(VAL32,BUF,OFFSET) \ +do \ +{ \ + (BUF)[OFFSET ] = BYTE_3((VAL32)); \ + (BUF)[OFFSET +1 ] = BYTE_2((VAL32)); \ + (BUF)[OFFSET +2 ] = BYTE_1((VAL32)); \ + (BUF)[OFFSET +3 ] = BYTE_0((VAL32)); \ +}while(0) + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*! +@struct \ + tstrHashContext + +@brief +*/ +typedef struct{ + uint32 au32HashState[M2M_SHA256_DIGEST_LEN/4]; + uint8 au8CurrentBlock[64]; + uint32 u32TotalLength; + uint8 u8InitHashFlag; +}tstrSHA256HashCtxt; + + + +/*======*======*======*======*======*=======* +* SHA256 IMPLEMENTATION * +*======*======*======*======*======*========*/ + +sint8 m2m_crypto_sha256_hash_init(tstrM2mSha256Ctxt *pstrSha256Ctxt) +{ + tstrSHA256HashCtxt *pstrSHA256 = (tstrSHA256HashCtxt*)pstrSha256Ctxt; + if(pstrSHA256 != NULL) + { + m2m_memset((uint8*)pstrSha256Ctxt, 0, sizeof(tstrM2mSha256Ctxt)); + pstrSHA256->u8InitHashFlag = 1; + } + return 0; +} + +sint8 m2m_crypto_sha256_hash_update(tstrM2mSha256Ctxt *pstrSha256Ctxt, uint8 *pu8Data, uint16 u16DataLength) +{ + sint8 s8Ret = M2M_ERR_FAIL; + tstrSHA256HashCtxt *pstrSHA256 = (tstrSHA256HashCtxt*)pstrSha256Ctxt; + if(pstrSHA256 != NULL) + { + uint32 u32ReadAddr; + uint32 u32WriteAddr = SHARED_MEM_BASE; + uint32 u32Addr = u32WriteAddr; + uint32 u32ResidualBytes; + uint32 u32NBlocks; + uint32 u32Offset; + uint32 u32CurrentBlock = 0; + uint8 u8IsDone = 0; + + /* Get the remaining bytes from the previous update (if the length is not block aligned). */ + u32ResidualBytes = pstrSHA256->u32TotalLength % SHA_BLOCK_SIZE; + + /* Update the total data length. */ + pstrSHA256->u32TotalLength += u16DataLength; + + if(u32ResidualBytes != 0) + { + if((u32ResidualBytes + u16DataLength) >= SHA_BLOCK_SIZE) + { + u32Offset = SHA_BLOCK_SIZE - u32ResidualBytes; + m2m_memcpy(&pstrSHA256->au8CurrentBlock[u32ResidualBytes], pu8Data, u32Offset); + pu8Data += u32Offset; + u16DataLength -= u32Offset; + + nm_write_block(u32Addr, pstrSHA256->au8CurrentBlock, SHA_BLOCK_SIZE); + u32Addr += SHA_BLOCK_SIZE; + u32CurrentBlock = 1; + } + else + { + m2m_memcpy(&pstrSHA256->au8CurrentBlock[u32ResidualBytes], pu8Data, u16DataLength); + u16DataLength = 0; + } + } + + /* Get the number of HASH BLOCKs and the residual bytes. */ + u32NBlocks = u16DataLength / SHA_BLOCK_SIZE; + u32ResidualBytes = u16DataLength % SHA_BLOCK_SIZE; + + if(u32NBlocks != 0) + { + nm_write_block(u32Addr, pu8Data, (uint16)(u32NBlocks * SHA_BLOCK_SIZE)); + pu8Data += (u32NBlocks * SHA_BLOCK_SIZE); + } + + u32NBlocks += u32CurrentBlock; + if(u32NBlocks != 0) + { + uint32 u32RegVal = 0; + + nm_write_reg(SHA256_CTRL, u32RegVal); + u32RegVal |= SHA256_CTRL_FORCE_SHA256_QUIT_MASK; + nm_write_reg(SHA256_CTRL, u32RegVal); + + if(pstrSHA256->u8InitHashFlag) + { + pstrSHA256->u8InitHashFlag = 0; + u32RegVal |= SHA256_CTRL_INIT_SHA256_STATE_MASK; + } + + u32ReadAddr = u32WriteAddr + (u32NBlocks * SHA_BLOCK_SIZE); + nm_write_reg(SHA256_DATA_LENGTH, (u32NBlocks * SHA_BLOCK_SIZE)); + nm_write_reg(SHA256_START_RD_ADDR, u32WriteAddr); + nm_write_reg(SHA256_START_WR_ADDR, u32ReadAddr); + + u32RegVal |= SHA256_CTRL_START_CALC_MASK; + + u32RegVal &= ~(0x7 << 8); + u32RegVal |= (2 << 8); + + nm_write_reg(SHA256_CTRL, u32RegVal); + + /* 5. Wait for done_intr */ + while(!u8IsDone) + { + u32RegVal = nm_read_reg(SHA256_DONE_INTR_STS); + u8IsDone = u32RegVal & NBIT0; + } + } + if(u32ResidualBytes != 0) + { + m2m_memcpy(pstrSHA256->au8CurrentBlock, pu8Data, u32ResidualBytes); + } + s8Ret = M2M_SUCCESS; + } + return s8Ret; +} + + +sint8 m2m_crypto_sha256_hash_finish(tstrM2mSha256Ctxt *pstrSha256Ctxt, uint8 *pu8Sha256Digest) +{ + sint8 s8Ret = M2M_ERR_FAIL; + tstrSHA256HashCtxt *pstrSHA256 = (tstrSHA256HashCtxt*)pstrSha256Ctxt; + if(pstrSHA256 != NULL) + { + uint32 u32ReadAddr; + uint32 u32WriteAddr = SHARED_MEM_BASE; + uint32 u32Addr = u32WriteAddr; + uint16 u16Offset; + uint16 u16PaddingLength; + uint16 u16NBlocks = 1; + uint32 u32RegVal = 0; + uint32 u32Idx,u32ByteIdx; + uint32 au32Digest[M2M_SHA256_DIGEST_LEN / 4]; + uint8 u8IsDone = 0; + + nm_write_reg(SHA256_CTRL,u32RegVal); + u32RegVal |= SHA256_CTRL_FORCE_SHA256_QUIT_MASK; + nm_write_reg(SHA256_CTRL,u32RegVal); + + if(pstrSHA256->u8InitHashFlag) + { + pstrSHA256->u8InitHashFlag = 0; + u32RegVal |= SHA256_CTRL_INIT_SHA256_STATE_MASK; + } + + /* Calculate the offset of the last data byte in the current block. */ + u16Offset = (uint16)(pstrSHA256->u32TotalLength % SHA_BLOCK_SIZE); + + /* Add the padding byte 0x80. */ + pstrSHA256->au8CurrentBlock[u16Offset ++] = 0x80; + + /* Calculate the required padding to complete + one Hash Block Size. + */ + u16PaddingLength = SHA_BLOCK_SIZE - u16Offset; + m2m_memset(&pstrSHA256->au8CurrentBlock[u16Offset], 0, u16PaddingLength); + + /* If the padding count is not enough to hold 64-bit representation of + the total input message length, one padding block is required. + */ + if(u16PaddingLength < 8) + { + nm_write_block(u32Addr, pstrSHA256->au8CurrentBlock, SHA_BLOCK_SIZE); + u32Addr += SHA_BLOCK_SIZE; + m2m_memset(pstrSHA256->au8CurrentBlock, 0, SHA_BLOCK_SIZE); + u16NBlocks ++; + } + + /* pack the length at the end of the padding block */ + PUTU32(pstrSHA256->u32TotalLength << 3, pstrSHA256->au8CurrentBlock, (SHA_BLOCK_SIZE - 4)); + + u32ReadAddr = u32WriteAddr + (u16NBlocks * SHA_BLOCK_SIZE); + nm_write_block(u32Addr, pstrSHA256->au8CurrentBlock, SHA_BLOCK_SIZE); + nm_write_reg(SHA256_DATA_LENGTH, (u16NBlocks * SHA_BLOCK_SIZE)); + nm_write_reg(SHA256_START_RD_ADDR, u32WriteAddr); + nm_write_reg(SHA256_START_WR_ADDR, u32ReadAddr); + + u32RegVal |= SHA256_CTRL_START_CALC_MASK; + u32RegVal |= SHA256_CTRL_WR_BACK_HASH_VALUE_MASK; + u32RegVal &= ~(0x7UL << 8); + u32RegVal |= (0x2UL << 8); + + nm_write_reg(SHA256_CTRL,u32RegVal); + + + /* 5. Wait for done_intr */ + while(!u8IsDone) + { + u32RegVal = nm_read_reg(SHA256_DONE_INTR_STS); + u8IsDone = u32RegVal & NBIT0; + } + nm_read_block(u32ReadAddr, (uint8*)au32Digest, 32); + + /* Convert the output words to an array of bytes. + */ + u32ByteIdx = 0; + for(u32Idx = 0; u32Idx < (M2M_SHA256_DIGEST_LEN / 4); u32Idx ++) + { + pu8Sha256Digest[u32ByteIdx ++] = BYTE_3(au32Digest[u32Idx]); + pu8Sha256Digest[u32ByteIdx ++] = BYTE_2(au32Digest[u32Idx]); + pu8Sha256Digest[u32ByteIdx ++] = BYTE_1(au32Digest[u32Idx]); + pu8Sha256Digest[u32ByteIdx ++] = BYTE_0(au32Digest[u32Idx]); + } + s8Ret = M2M_SUCCESS; + } + return s8Ret; +} + + +/*======*======*======*======*======*=======* +* RSA IMPLEMENTATION * +*======*======*======*======*======*========*/ + +static void FlipBuffer(uint8 *pu8InBuffer, uint8 *pu8OutBuffer, uint16 u16BufferSize) +{ + uint16 u16Idx; + for(u16Idx = 0; u16Idx < u16BufferSize; u16Idx ++) + { +#if ENABLE_FLIPPING == 1 + pu8OutBuffer[u16Idx] = pu8InBuffer[u16BufferSize - u16Idx - 1]; +#else + pu8OutBuffer[u16Idx] = pu8InBuffer[u16Idx]; +#endif + } +} + +void BigInt_ModExp +( + uint8 *pu8X, uint16 u16XSize, + uint8 *pu8E, uint16 u16ESize, + uint8 *pu8M, uint16 u16MSize, + uint8 *pu8R, uint16 u16RSize + ) +{ + uint32 u32Reg; + uint8 au8Tmp[780] = {0}; + uint32 u32XAddr = SHARED_MEM_BASE; + uint32 u32MAddr; + uint32 u32EAddr; + uint32 u32RAddr; + uint8 u8EMswBits = 32; + uint32 u32Mprime = 0x7F; + uint16 u16XSizeWords,u16ESizeWords; + uint32 u32Exponent; + + u16XSizeWords = (u16XSize + 3) / 4; + u16ESizeWords = (u16ESize + 3) / 4; + + u32MAddr = u32XAddr + (u16XSizeWords * 4); + u32EAddr = u32MAddr + (u16XSizeWords * 4); + u32RAddr = u32EAddr + (u16ESizeWords * 4); + + /* Reset the core. + */ + u32Reg = 0; + u32Reg |= BIGINT_MISC_CTRL_CTL_RESET; + u32Reg = nm_read_reg(BIGINT_MISC_CTRL); + u32Reg &= ~BIGINT_MISC_CTRL_CTL_RESET; + u32Reg = nm_read_reg(BIGINT_MISC_CTRL); + + nm_write_block(u32RAddr,au8Tmp, u16RSize); + + /* Write Input Operands to Chip Memory. + */ + /*------- X -------*/ + FlipBuffer(pu8X,au8Tmp,u16XSize); + nm_write_block(u32XAddr,au8Tmp,u16XSizeWords * 4); + + /*------- E -------*/ + m2m_memset(au8Tmp, 0, sizeof(au8Tmp)); + FlipBuffer(pu8E, au8Tmp, u16ESize); + nm_write_block(u32EAddr, au8Tmp, u16ESizeWords * 4); + u32Exponent = GET_UINT32(au8Tmp, (u16ESizeWords * 4) - 4); + while((u32Exponent & NBIT31)== 0) + { + u32Exponent <<= 1; + u8EMswBits --; + } + + /*------- M -------*/ + m2m_memset(au8Tmp, 0, sizeof(au8Tmp)); + FlipBuffer(pu8M, au8Tmp, u16XSize); + nm_write_block(u32MAddr, au8Tmp, u16XSizeWords * 4); + + /* Program the addresses of the input operands. + */ + nm_write_reg(BIGINT_ADDR_X, u32XAddr); + nm_write_reg(BIGINT_ADDR_E, u32EAddr); + nm_write_reg(BIGINT_ADDR_M, u32MAddr); + nm_write_reg(BIGINT_ADDR_R, u32RAddr); + + /* Mprime. + */ + nm_write_reg(BIGINT_M_PRIME,u32Mprime); + + /* Length. + */ + u32Reg = (u16XSizeWords & 0xFF); + u32Reg += ((u16ESizeWords & 0xFF) << 8); + u32Reg += (u8EMswBits << 16); + nm_write_reg(BIGINT_LENGTH,u32Reg); + + /* CTRL Register. + */ + u32Reg = nm_read_reg(BIGINT_MISC_CTRL); + u32Reg ^= BIGINT_MISC_CTRL_CTL_START; + u32Reg |= BIGINT_MISC_CTRL_CTL_FORCE_BARRETT; + //u32Reg |= BIGINT_MISC_CTRL_CTL_M_PRIME_VALID; +#if ENABLE_FLIPPING == 0 + u32Reg |= BIGINT_MISC_CTRL_CTL_MSW_FIRST; +#endif + nm_write_reg(BIGINT_MISC_CTRL,u32Reg); + + /* Wait for computation to complete. */ + while(1) + { + u32Reg = nm_read_reg(BIGINT_IRQ_STS); + if(u32Reg & BIGINT_IRQ_STS_DONE) + { + break; + } + } + nm_write_reg(BIGINT_IRQ_STS,0); + m2m_memset(au8Tmp, 0, sizeof(au8Tmp)); + nm_read_block(u32RAddr, au8Tmp, u16RSize); + FlipBuffer(au8Tmp, pu8R, u16RSize); +} + + + +#define MD5_DIGEST_SIZE (16) +#define SHA1_DIGEST_SIZE (20) + +static const uint8 au8TEncodingMD5[] = +{ + 0x30, 0x20, 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86, + 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05, 0x05, 0x00, + 0x04 +}; +/*!< Fixed part of the Encoding T for the MD5 hash algorithm. +*/ + + +static const uint8 au8TEncodingSHA1[] = +{ + 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, + 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04 +}; +/*!< Fixed part of the Encoding T for the SHA-1 hash algorithm. +*/ + + +static const uint8 au8TEncodingSHA2[] = +{ + 0x30, 0x31, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, + 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, + 0x00, 0x04 +}; +/*!< Fixed part of the Encoding T for the SHA-2 hash algorithm. +*/ + + +sint8 m2m_crypto_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash, + uint16 u16HashLength, uint8 *pu8RsaSignature) +{ + sint8 s8Ret = M2M_RSA_SIGN_FAIL; + + if((pu8N != NULL) && (pu8E != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL)) + { + uint16 u16TLength, u16TEncodingLength; + uint8 *pu8T; + uint8 au8EM[512]; + + /* Selection of correct T Encoding based on the hash size. + */ + if(u16HashLength == MD5_DIGEST_SIZE) + { + pu8T = (uint8*)au8TEncodingMD5; + u16TEncodingLength = sizeof(au8TEncodingMD5); + } + else if(u16HashLength == SHA1_DIGEST_SIZE) + { + pu8T = (uint8*)au8TEncodingSHA1; + u16TEncodingLength = sizeof(au8TEncodingSHA1); + } + else + { + pu8T = (uint8*)au8TEncodingSHA2; + u16TEncodingLength = sizeof(au8TEncodingSHA2); + } + u16TLength = u16TEncodingLength + 1 + u16HashLength; + + /* If emLen < tLen + 11. + */ + if(u16NSize >= (u16TLength + 11)) + { + uint32 u32PSLength,u32Idx = 0; + + /* + RSA verification + */ + BigInt_ModExp(pu8RsaSignature, u16NSize, pu8E, u16ESize, pu8N, u16NSize, au8EM, u16NSize); + + u32PSLength = u16NSize - u16TLength - 3; + + /* + The calculated EM must match the following pattern. + *======*======*======*======*======* + * 0x00 || 0x01 || PS || 0x00 || T * + *======*======*======*======*======* + Where PS is all 0xFF + T is defined based on the hash algorithm. + */ + if((au8EM[0] == 0x00) && (au8EM[1] == 0x01)) + { + for(u32Idx = 2; au8EM[u32Idx] == 0xFF; u32Idx ++); + if(u32Idx == (u32PSLength + 2)) + { + if(au8EM[u32Idx ++] == 0x00) + { + if(!m2m_memcmp(&au8EM[u32Idx], pu8T, u16TEncodingLength)) + { + u32Idx += u16TEncodingLength; + if(au8EM[u32Idx ++] == u16HashLength) + s8Ret = m2m_memcmp(&au8EM[u32Idx], pu8SignedMsgHash, u16HashLength); + } + } + } + } + } + } + return s8Ret; +} + + +sint8 m2m_crypto_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash, + uint16 u16HashLength, uint8 *pu8RsaSignature) +{ + sint8 s8Ret = M2M_RSA_SIGN_FAIL; + + if((pu8N != NULL) && (pu8d != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL)) + { + uint16 u16TLength, u16TEncodingLength; + uint8 *pu8T; + uint8 au8EM[512]; + + /* Selection of correct T Encoding based on the hash size. + */ + if(u16HashLength == MD5_DIGEST_SIZE) + { + pu8T = (uint8*)au8TEncodingMD5; + u16TEncodingLength = sizeof(au8TEncodingMD5); + } + else if(u16HashLength == SHA1_DIGEST_SIZE) + { + pu8T = (uint8*)au8TEncodingSHA1; + u16TEncodingLength = sizeof(au8TEncodingSHA1); + } + else + { + pu8T = (uint8*)au8TEncodingSHA2; + u16TEncodingLength = sizeof(au8TEncodingSHA2); + } + u16TLength = u16TEncodingLength + 1 + u16HashLength; + + /* If emLen < tLen + 11. + */ + if(u16NSize >= (u16TLength + 11)) + { + uint16 u16PSLength = 0; + uint16 u16Offset = 0; + + /* + The calculated EM must match the following pattern. + *======*======*======*======*======* + * 0x00 || 0x01 || PS || 0x00 || T * + *======*======*======*======*======* + Where PS is all 0xFF + T is defined based on the hash algorithm. + */ + au8EM[u16Offset ++] = 0; + au8EM[u16Offset ++] = 1; + u16PSLength = u16NSize - u16TLength - 3; + m2m_memset(&au8EM[u16Offset], 0xFF, u16PSLength); + u16Offset += u16PSLength; + au8EM[u16Offset ++] = 0; + m2m_memcpy(&au8EM[u16Offset], pu8T, u16TEncodingLength); + u16Offset += u16TEncodingLength; + au8EM[u16Offset ++] = u16HashLength; + m2m_memcpy(&au8EM[u16Offset], pu8SignedMsgHash, u16HashLength); + + /* + RSA Signature Generation + */ + BigInt_ModExp(au8EM, u16NSize, pu8d, u16dSize, pu8N, u16NSize, pu8RsaSignature, u16NSize); + s8Ret = M2M_RSA_SIGN_OK; + } + } + return s8Ret; +} + +#endif /* CONF_CRYPTO */ + +#ifdef CONF_CRYPTO_SOFT + +typedef struct { + tpfAppCryproCb pfAppCryptoCb; + uint8 * pu8Digest; + uint8 * pu8Rsa; + uint8 u8CryptoBusy; +}tstrCryptoCtxt; + +typedef struct { + uint8 au8N[M2M_MAX_RSA_LEN]; + uint8 au8E[M2M_MAX_RSA_LEN]; + uint8 au8Hash[M2M_SHA256_DIGEST_LEN]; + uint16 u16Nsz; + uint16 u16Esz; + uint16 u16Hsz; + uint8 _pad16_[2]; +}tstrRsaPayload; + +static tstrCryptoCtxt gstrCryptoCtxt; + + +/** +* @fn m2m_crypto_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +* @brief WiFi call back function +* @param [in] u8OpCode +* HIF Opcode type. +* @param [in] u16DataSize +* HIF data length. +* @param [in] u32Addr +* HIF address. +* @author +* @date +* @version 1.0 +*/ +static void m2m_crypto_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +{ + sint8 ret = M2M_SUCCESS; + gstrCryptoCtxt.u8CryptoBusy = 0; + if(u8OpCode == M2M_CRYPTO_RESP_SHA256_INIT) + { + tstrM2mSha256Ctxt strCtxt; + if (hif_receive(u32Addr, (uint8*) &strCtxt,sizeof(tstrM2mSha256Ctxt), 0) == M2M_SUCCESS) + { + tstrCyptoResp strResp; + if(hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt), (uint8*) &strResp,sizeof(tstrCyptoResp), 1) == M2M_SUCCESS) + { + if (gstrCryptoCtxt.pfAppCryptoCb) + gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,&strCtxt); + } + } + } + else if(u8OpCode == M2M_CRYPTO_RESP_SHA256_UPDATE) + { + tstrM2mSha256Ctxt strCtxt; + if (hif_receive(u32Addr, (uint8*) &strCtxt,sizeof(tstrM2mSha256Ctxt), 0) == M2M_SUCCESS) + { + tstrCyptoResp strResp; + if (hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt), (uint8*) &strResp,sizeof(tstrCyptoResp), 1) == M2M_SUCCESS) + { + if (gstrCryptoCtxt.pfAppCryptoCb) + gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,&strCtxt); + } + } + + } + else if(u8OpCode == M2M_CRYPTO_RESP_SHA256_FINSIH) + { + tstrCyptoResp strResp; + if (hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt), (uint8*) &strResp,sizeof(tstrCyptoResp), 0) == M2M_SUCCESS) + { + if (hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt) + sizeof(tstrCyptoResp), (uint8*)gstrCryptoCtxt.pu8Digest,M2M_SHA256_DIGEST_LEN, 1) == M2M_SUCCESS) + { + if (gstrCryptoCtxt.pfAppCryptoCb) + gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,gstrCryptoCtxt.pu8Digest); + + } + } + } + else if(u8OpCode == M2M_CRYPTO_RESP_RSA_SIGN_GEN) + { + tstrCyptoResp strResp; + if (hif_receive(u32Addr + sizeof(tstrRsaPayload), (uint8*)&strResp,sizeof(tstrCyptoResp), 0) == M2M_SUCCESS) + { + if (hif_receive(u32Addr + sizeof(tstrRsaPayload) + sizeof(tstrCyptoResp), (uint8*)gstrCryptoCtxt.pu8Rsa,M2M_MAX_RSA_LEN, 0) == M2M_SUCCESS) + { + if (gstrCryptoCtxt.pfAppCryptoCb) + gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,gstrCryptoCtxt.pu8Rsa); + } + } + } + else if(u8OpCode == M2M_CRYPTO_RESP_RSA_SIGN_VERIFY) + { + tstrCyptoResp strResp; + if (hif_receive(u32Addr + sizeof(tstrRsaPayload), (uint8*)&strResp,sizeof(tstrCyptoResp), 1) == M2M_SUCCESS) + { + if (gstrCryptoCtxt.pfAppCryptoCb) + gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,NULL); + } + } + else + { + M2M_ERR("u8Code %d ??\n",u8OpCode); + } + +} +/*! +@fn \ + sint8 m2m_crypto_init(); + +@brief crypto initialization + +@param[in] pfAppCryproCb + +*/ +sint8 m2m_crypto_init(tpfAppCryproCb pfAppCryproCb) +{ + sint8 ret = M2M_ERR_FAIL; + m2m_memset((uint8*)&gstrCryptoCtxt,0,sizeof(tstrCryptoCtxt)); + if(pfAppCryproCb != NULL) + { + gstrCryptoCtxt.pfAppCryptoCb = pfAppCryproCb; + ret = hif_register_cb(M2M_REQ_GROUP_CRYPTO,m2m_crypto_cb); + } + return ret; +} +/*! +@fn \ + sint8 m2m_sha256_hash_init(tstrM2mSha256Ctxt *psha256Ctxt); + +@brief SHA256 hash initialization + +@param[in] psha256Ctxt + Pointer to a sha256 context allocated by the caller. +*/ +sint8 m2m_crypto_sha256_hash_init(tstrM2mSha256Ctxt *psha256Ctxt) +{ + sint8 ret = M2M_ERR_FAIL; + if((psha256Ctxt != NULL)&&(!gstrCryptoCtxt.u8CryptoBusy)) + { + ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_SHA256_INIT|M2M_REQ_DATA_PKT,(uint8*)psha256Ctxt,sizeof(tstrM2mSha256Ctxt),NULL,0,0); + } + return ret; +} + + +/*! +@fn \ + sint8 m2m_sha256_hash_update(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Data, uint16 u16DataLength); + +@brief SHA256 hash update + +@param [in] psha256Ctxt + Pointer to the sha256 context. + +@param [in] pu8Data + Buffer holding the data submitted to the hash. + +@param [in] u16DataLength + Size of the data bufefr in bytes. +*/ +sint8 m2m_crypto_sha256_hash_update(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Data, uint16 u16DataLength) +{ + sint8 ret = M2M_ERR_FAIL; + if((!gstrCryptoCtxt.u8CryptoBusy) && (psha256Ctxt != NULL) && (pu8Data != NULL) && (u16DataLength < M2M_SHA256_MAX_DATA)) + { + ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_SHA256_UPDATE|M2M_REQ_DATA_PKT,(uint8*)psha256Ctxt,sizeof(tstrM2mSha256Ctxt),pu8Data,u16DataLength,sizeof(tstrM2mSha256Ctxt) + sizeof(tstrCyptoResp)); + } + return ret; + +} + + +/*! +@fn \ + sint8 m2m_sha256_hash_finish(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Sha256Digest); + +@brief SHA256 hash finalization + +@param[in] psha256Ctxt + Pointer to a sha256 context allocated by the caller. + +@param [in] pu8Sha256Digest + Buffer allocated by the caller which will hold the resultant SHA256 Digest. It must be allocated no less than M2M_SHA256_DIGEST_LEN. +*/ +sint8 m2m_crypto_sha256_hash_finish(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Sha256Digest) +{ + sint8 ret = M2M_ERR_FAIL; + if((!gstrCryptoCtxt.u8CryptoBusy) && (psha256Ctxt != NULL) && (pu8Sha256Digest != NULL)) + { + gstrCryptoCtxt.pu8Digest = pu8Sha256Digest; + ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_SHA256_FINSIH|M2M_REQ_DATA_PKT,(uint8*)psha256Ctxt,sizeof(tstrM2mSha256Ctxt),NULL,0,0); + } + return ret; +} + + + + +/*! +@fn \ + sint8 m2m_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash, \ + uint16 u16HashLength, uint8 *pu8RsaSignature); + +@brief RSA Signature Verification + + The function shall request the RSA Signature verification from the WINC Firmware for the given message. The signed message shall be + compressed to the corresponding hash algorithm before calling this function. + The hash type is identified by the given hash length. For example, if the hash length is 32 bytes, then it is SHA256. + +@param[in] pu8N + RSA Key modulus n. + +@param[in] u16NSize + Size of the RSA modulus n in bytes. + +@param[in] pu8E + RSA public exponent. + +@param[in] u16ESize + Size of the RSA public exponent in bytes. + +@param[in] pu8SignedMsgHash + The hash digest of the signed message. + +@param[in] u16HashLength + The length of the hash digest. + +@param[out] pu8RsaSignature + Signature value to be verified. +*/ + + +sint8 m2m_crypto_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash, + uint16 u16HashLength, uint8 *pu8RsaSignature) +{ + sint8 ret = M2M_ERR_FAIL; + if((!gstrCryptoCtxt.u8CryptoBusy) && (pu8N != NULL) && (pu8E != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL) + && (u16NSize != 0) && (u16ESize != 0) && (u16HashLength != 0) && (pu8RsaSignature != NULL) ) + + { + tstrRsaPayload strRsa = {0}; + + m2m_memcpy(strRsa.au8N,pu8N,u16NSize); + m2m_memcpy(strRsa.au8E,pu8E,u16ESize); + m2m_memcpy(strRsa.au8Hash,pu8SignedMsgHash,u16HashLength); + + strRsa.u16Esz = u16ESize; + strRsa.u16Hsz = u16HashLength; + strRsa.u16Nsz = u16NSize; + + ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_RSA_SIGN_VERIFY|M2M_REQ_DATA_PKT,(uint8*)&strRsa,sizeof(tstrRsaPayload),NULL,0,0); + + } + return ret; +} + + +/*! +@fn \ + sint8 m2m_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash, \ + uint16 u16HashLength, uint8 *pu8RsaSignature); + +@brief RSA Signature Generation + + The function shall request the RSA Signature generation from the WINC Firmware for the given message. The signed message shall be + compressed to the corresponding hash algorithm before calling this function. + The hash type is identified by the given hash length. For example, if the hash length is 32 bytes, then it is SHA256. + +@param[in] pu8N + RSA Key modulus n. + +@param[in] u16NSize + Size of the RSA modulus n in bytes. + +@param[in] pu8d + RSA private exponent. + +@param[in] u16dSize + Size of the RSA private exponent in bytes. + +@param[in] pu8SignedMsgHash + The hash digest of the signed message. + +@param[in] u16HashLength + The length of the hash digest. + +@param[out] pu8RsaSignature + Pointer to a user buffer allocated by teh caller shall hold the generated signature. +*/ +sint8 m2m_crypto_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash, + uint16 u16HashLength, uint8 *pu8RsaSignature) +{ + sint8 ret = M2M_ERR_FAIL; + if((!gstrCryptoCtxt.u8CryptoBusy) && (pu8N != NULL) && (pu8d != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL) + && (u16NSize != 0) && (u16dSize != 0) && (u16HashLength != 0) && (pu8RsaSignature != NULL)) + + { + tstrRsaPayload strRsa = {0}; + + m2m_memcpy(strRsa.au8N,pu8N,u16NSize); + m2m_memcpy(strRsa.au8E,pu8d,u16dSize); + m2m_memcpy(strRsa.au8Hash,pu8SignedMsgHash,u16HashLength); + + strRsa.u16Esz = u16dSize; + strRsa.u16Hsz = u16HashLength; + strRsa.u16Nsz = u16NSize; + + gstrCryptoCtxt.pu8Rsa = pu8RsaSignature; + ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_RSA_SIGN_GEN|M2M_REQ_DATA_PKT,(uint8*)&strRsa,sizeof(tstrRsaPayload),NULL,0,0); + + } + return ret; +} + +#endif \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_hif.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_hif.c new file mode 100644 index 0000000..f0ed93a --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_hif.c @@ -0,0 +1,767 @@ +/** + * + * \file + * + * \brief This module contains M2M host interface APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "common/include/nm_common.h" +#include "driver/source/nmbus.h" +#include "bsp/include/nm_bsp.h" +#include "m2m_hif.h" +#include "driver/include/m2m_types.h" +#include "driver/source/nmasic.h" +#include "driver/include/m2m_periph.h" + +#if (defined NM_EDGE_INTERRUPT)&&(defined NM_LEVEL_INTERRUPT) +#error "only one type of interrupt NM_EDGE_INTERRUPT,NM_LEVEL_INTERRUPT" +#endif + +#if !((defined NM_EDGE_INTERRUPT)||(defined NM_LEVEL_INTERRUPT)) +#error "define interrupt type NM_EDGE_INTERRUPT,NM_LEVEL_INTERRUPT" +#endif + +#ifndef CORTUS_APP +#define NMI_AHB_DATA_MEM_BASE 0x30000 +#define NMI_AHB_SHARE_MEM_BASE 0xd0000 + +#define WIFI_HOST_RCV_CTRL_0 (0x1070) +#define WIFI_HOST_RCV_CTRL_1 (0x1084) +#define WIFI_HOST_RCV_CTRL_2 (0x1078) +#define WIFI_HOST_RCV_CTRL_3 (0x106c) +#define WIFI_HOST_RCV_CTRL_4 (0x150400) +#define WIFI_HOST_RCV_CTRL_5 (0x1088) + +typedef struct { + uint8 u8ChipMode; + uint8 u8ChipSleep; + uint8 u8HifRXDone; + uint8 u8Interrupt; + uint32 u32RxAddr; + uint32 u32RxSize; + tpfHifCallBack pfWifiCb; + tpfHifCallBack pfIpCb; + tpfHifCallBack pfOtaCb; + tpfHifCallBack pfSigmaCb; + tpfHifCallBack pfHifCb; + tpfHifCallBack pfCryptoCb; + tpfHifCallBack pfSslCb; +}tstrHifContext; + +volatile tstrHifContext gstrHifCxt; + +static void isr(void) +{ + gstrHifCxt.u8Interrupt++; +#ifdef NM_LEVEL_INTERRUPT + nm_bsp_interrupt_ctrl(0); +#endif +} +static sint8 hif_set_rx_done(void) +{ + uint32 reg; + sint8 ret = M2M_SUCCESS; + + gstrHifCxt.u8HifRXDone = 0; +#ifdef NM_EDGE_INTERRUPT + nm_bsp_interrupt_ctrl(1); +#endif + ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0,®); + if(ret != M2M_SUCCESS)goto ERR1; + /* Set RX Done */ + reg |= NBIT1; + ret = nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg); + if(ret != M2M_SUCCESS)goto ERR1; +#ifdef NM_LEVEL_INTERRUPT + nm_bsp_interrupt_ctrl(1); +#endif +ERR1: + return ret; + +} +/** +* @fn static void m2m_hif_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +* @brief WiFi call back function +* @param [in] u8OpCode +* HIF Opcode type. +* @param [in] u16DataSize +* HIF data length. +* @param [in] u32Addr +* HIF address. +* @param [in] grp +* HIF group type. +* @author +* @date +* @version 1.0 +*/ +static void m2m_hif_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)u8OpCode; + (void)u16DataSize; + (void)u32Addr; +#endif +} +/** +* @fn NMI_API sint8 hif_chip_wake(void); +* @brief To Wakeup the chip. +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +sint8 hif_chip_wake(void) +{ + sint8 ret = M2M_SUCCESS; + if(gstrHifCxt.u8HifRXDone) + { + /*chip already wake for the rx not done no need to send wake request*/ + return ret; + } + if(gstrHifCxt.u8ChipSleep == 0) + { + if(gstrHifCxt.u8ChipMode != M2M_NO_PS) + { + ret = chip_wake(); + if(ret != M2M_SUCCESS)goto ERR1; + } + else + { + } + } + gstrHifCxt.u8ChipSleep++; +ERR1: + return ret; +} +/*! +@fn \ + NMI_API void hif_set_sleep_mode(uint8 u8Pstype); + +@brief + Set the sleep mode of the HIF layer. + +@param [in] u8Pstype + Sleep mode. + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ + +void hif_set_sleep_mode(uint8 u8Pstype) +{ + gstrHifCxt.u8ChipMode = u8Pstype; +} +/*! +@fn \ + NMI_API uint8 hif_get_sleep_mode(void); + +@brief + Get the sleep mode of the HIF layer. + +@return + The function SHALL return the sleep mode of the HIF layer. +*/ + +uint8 hif_get_sleep_mode(void) +{ + return gstrHifCxt.u8ChipMode; +} + +/** +* @fn NMI_API sint8 hif_chip_sleep_sc(void); +* @brief To clear the chip sleep but keep the chip sleep +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +sint8 hif_chip_sleep_sc(void) +{ + if(gstrHifCxt.u8ChipSleep >= 1) + { + gstrHifCxt.u8ChipSleep--; + } + return M2M_SUCCESS; +} +/** +* @fn NMI_API sint8 hif_chip_sleep(void); +* @brief To make the chip sleep. +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +sint8 hif_chip_sleep(void) +{ + sint8 ret = M2M_SUCCESS; + + if(gstrHifCxt.u8ChipSleep >= 1) + { + gstrHifCxt.u8ChipSleep--; + } + + if(gstrHifCxt.u8ChipSleep == 0) + { + if(gstrHifCxt.u8ChipMode != M2M_NO_PS) + { + ret = chip_sleep(); + if(ret != M2M_SUCCESS)goto ERR1; + + } + else + { + } + } +ERR1: + return ret; +} +/** +* @fn NMI_API sint8 hif_init(void * arg); +* @brief To initialize HIF layer. +* @param [in] arg +* Pointer to the arguments. +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +sint8 hif_init(void * arg) +{ +#ifdef ARDUINO + (void)arg; // Silence "unused" warning +#endif + m2m_memset((uint8*)&gstrHifCxt,0,sizeof(tstrHifContext)); + nm_bsp_register_isr(isr); + hif_register_cb(M2M_REQ_GROUP_HIF,m2m_hif_cb); + return M2M_SUCCESS; +} +/** +* @fn NMI_API sint8 hif_deinit(void * arg); +* @brief To De-initialize HIF layer. +* @param [in] arg +* Pointer to the arguments. +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ +sint8 hif_deinit(void * arg) +{ +#ifdef ARDUINO + (void)arg; // Silence "unused" warning +#endif + sint8 ret = M2M_SUCCESS; + ret = hif_chip_wake(); + m2m_memset((uint8*)&gstrHifCxt,0,sizeof(tstrHifContext)); + return ret; +} +/** +* @fn NMI_API sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, + uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) +* @brief Send packet using host interface. + +* @param [in] u8Gid +* Group ID. +* @param [in] u8Opcode +* Operation ID. +* @param [in] pu8CtrlBuf +* Pointer to the Control buffer. +* @param [in] u16CtrlBufSize + Control buffer size. +* @param [in] u16DataOffset + Packet Data offset. +* @param [in] pu8DataBuf +* Packet buffer Allocated by the caller. +* @param [in] u16DataSize + Packet buffer size (including the HIF header). +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, + uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) +{ + sint8 ret = M2M_ERR_SEND; + volatile tstrHifHdr strHif; + + strHif.u8Opcode = u8Opcode&(~NBIT7); + strHif.u8Gid = u8Gid; + strHif.u16Length = M2M_HIF_HDR_OFFSET; + if(pu8DataBuf != NULL) + { + strHif.u16Length += u16DataOffset + u16DataSize; + } + else + { + strHif.u16Length += u16CtrlBufSize; + } + ret = hif_chip_wake(); + if(ret == M2M_SUCCESS) + { + volatile uint32 reg, dma_addr = 0; + volatile uint16 cnt = 0; +//#define OPTIMIZE_BUS +/*please define in firmware also*/ +#ifndef OPTIMIZE_BUS + reg = 0UL; + reg |= (uint32)u8Gid; + reg |= ((uint32)u8Opcode<<8); + reg |= ((uint32)strHif.u16Length<<16); + ret = nm_write_reg(NMI_STATE_REG,reg); + if(M2M_SUCCESS != ret) goto ERR1; + + reg = 0UL; + reg |= NBIT1; + ret = nm_write_reg(WIFI_HOST_RCV_CTRL_2, reg); + if(M2M_SUCCESS != ret) goto ERR1; +#else + reg = 0UL; + reg |= NBIT1; + reg |= ((u8Opcode & NBIT7) ? (NBIT2):(0)); /*Data = 1 or config*/ + reg |= (u8Gid == M2M_REQ_GROUP_IP) ? (NBIT3):(0); /*IP = 1 or non IP*/ + reg |= ((uint32)strHif.u16Length << 4); /*length of pkt max = 4096*/ + ret = nm_write_reg(WIFI_HOST_RCV_CTRL_2, reg); + if(M2M_SUCCESS != ret) goto ERR1; +#endif + dma_addr = 0; + + for(cnt = 0; cnt < 1000; cnt ++) + { + ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_2,(uint32 *)®); + if(ret != M2M_SUCCESS) break; + /* + * If it takes too long to get a response, the slow down to + * avoid back-to-back register read operations. + */ + if(cnt >= 500) { + if(cnt < 501) { + M2M_INFO("Slowing down...\n"); + } + nm_bsp_sleep(1); + } + if (!(reg & NBIT1)) + { + ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_4,(uint32 *)&dma_addr); + if(ret != M2M_SUCCESS) { + /*in case of read error clear the DMA address and return error*/ + dma_addr = 0; + goto ERR1; + } + /*in case of success break */ + break; + } + } + + if (dma_addr != 0) + { + volatile uint32 u32CurrAddr; + u32CurrAddr = dma_addr; + strHif.u16Length=NM_BSP_B_L_16(strHif.u16Length); + ret = nm_write_block(u32CurrAddr, (uint8*)&strHif, M2M_HIF_HDR_OFFSET); + if(M2M_SUCCESS != ret) goto ERR1; + u32CurrAddr += M2M_HIF_HDR_OFFSET; + if(pu8CtrlBuf != NULL) + { + ret = nm_write_block(u32CurrAddr, pu8CtrlBuf, u16CtrlBufSize); + if(M2M_SUCCESS != ret) goto ERR1; + u32CurrAddr += u16CtrlBufSize; + } + if(pu8DataBuf != NULL) + { + u32CurrAddr += (u16DataOffset - u16CtrlBufSize); + ret = nm_write_block(u32CurrAddr, pu8DataBuf, u16DataSize); + if(M2M_SUCCESS != ret) goto ERR1; + u32CurrAddr += u16DataSize; + } + + reg = dma_addr << 2; + reg |= NBIT1; + ret = nm_write_reg(WIFI_HOST_RCV_CTRL_3, reg); + if(M2M_SUCCESS != ret) goto ERR1; + } + else + { + ret = hif_chip_sleep(); + M2M_DBG("Failed to alloc rx size %d\r",ret); + ret = M2M_ERR_MEM_ALLOC; + goto ERR2; + } + + } + else + { + M2M_ERR("(HIF)Fail to wakup the chip\n"); + goto ERR2; + } + /*actual sleep ret = M2M_SUCCESS*/ + ret = hif_chip_sleep(); + return ret; +ERR1: + /*reset the count but no actual sleep as it already bus error*/ + hif_chip_sleep_sc(); +ERR2: + /*logical error*/ + return ret; +} + +#ifdef ARDUINO +volatile uint8 hif_small_xfer = 0; +#endif + +/** +* @fn hif_isr +* @brief Host interface interrupt service routine +* @author M. Abdelmawla +* @date 15 July 2012 +* @return 1 in case of interrupt received else 0 will be returned +* @version 1.0 +*/ +static sint8 hif_isr(void) +{ + sint8 ret = M2M_SUCCESS; + volatile uint32 reg; + volatile tstrHifHdr strHif; + +#ifdef ARDUINO + ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, (uint32*)®); +#else + ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, ®); +#endif + if(M2M_SUCCESS == ret) + { + if(reg & 0x1) /* New interrupt has been received */ + { + uint16 size; + + nm_bsp_interrupt_ctrl(0); + /*Clearing RX interrupt*/ + reg &= ~NBIT0; + ret = nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg); + if(ret != M2M_SUCCESS)goto ERR1; + gstrHifCxt.u8HifRXDone = 1; + size = (uint16)((reg >> 2) & 0xfff); + if (size > 0) { + uint32 address = 0; + /** + start bus transfer + **/ + ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_1, &address); + if(M2M_SUCCESS != ret) + { + M2M_ERR("(hif) WIFI_HOST_RCV_CTRL_1 bus fail\n"); + nm_bsp_interrupt_ctrl(1); + goto ERR1; + } + gstrHifCxt.u32RxAddr = address; + gstrHifCxt.u32RxSize = size; + ret = nm_read_block(address, (uint8*)&strHif, sizeof(tstrHifHdr)); + strHif.u16Length = NM_BSP_B_L_16(strHif.u16Length); + if(M2M_SUCCESS != ret) + { + M2M_ERR("(hif) address bus fail\n"); + nm_bsp_interrupt_ctrl(1); + goto ERR1; + } + if(strHif.u16Length != size) + { + if((size - strHif.u16Length) > 4) + { + M2M_ERR("(hif) Corrupted packet Size = %u \n", + size, strHif.u16Length, strHif.u8Gid, strHif.u8Opcode); + nm_bsp_interrupt_ctrl(1); + ret = M2M_ERR_BUS_FAIL; + goto ERR1; + } + } + + if(M2M_REQ_GROUP_WIFI == strHif.u8Gid) + { + if(gstrHifCxt.pfWifiCb) + gstrHifCxt.pfWifiCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); + else +#ifdef ARDUINO + { +#endif + M2M_ERR("WIFI callback is not registered\n"); +#ifdef ARDUINO + } +#endif + } + else if(M2M_REQ_GROUP_IP == strHif.u8Gid) + { + if(gstrHifCxt.pfIpCb) + gstrHifCxt.pfIpCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); + else +#ifdef ARDUINO + { +#endif + M2M_ERR("Scoket callback is not registered\n"); +#ifdef ARDUINO + } +#endif + } + else if(M2M_REQ_GROUP_OTA == strHif.u8Gid) + { + if(gstrHifCxt.pfOtaCb) + gstrHifCxt.pfOtaCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); + else +#ifdef ARDUINO + { +#endif + M2M_ERR("Ota callback is not registered\n"); +#ifdef ARDUINO + } +#endif + } + else if(M2M_REQ_GROUP_CRYPTO == strHif.u8Gid) + { + if(gstrHifCxt.pfCryptoCb) + gstrHifCxt.pfCryptoCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); + + else +#ifdef ARDUINO + { +#endif + M2M_ERR("Crypto callback is not registered\n"); +#ifdef ARDUINO + } +#endif + } + else if(M2M_REQ_GROUP_SIGMA == strHif.u8Gid) + { + if(gstrHifCxt.pfSigmaCb) + gstrHifCxt.pfSigmaCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); + else +#ifdef ARDUINO + { +#endif + M2M_ERR("Sigma callback is not registered\n"); +#ifdef ARDUINO + } +#endif + } + else if(M2M_REQ_GROUP_SSL == strHif.u8Gid) + { + if(gstrHifCxt.pfSslCb) + gstrHifCxt.pfSslCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); + } + else + { + M2M_ERR("(hif) invalid group ID\n"); + ret = M2M_ERR_BUS_FAIL; + goto ERR1; + } +#ifdef ARDUINO + if(hif_small_xfer) + { + /*Pause SPI transfer*/ + return ret; + } +#endif + if(gstrHifCxt.u8HifRXDone) + { + M2M_ERR("(hif) host app didn't set RX Done <%u><%X>\n", strHif.u8Gid, strHif.u8Opcode); + ret = hif_set_rx_done(); + if(ret != M2M_SUCCESS) goto ERR1; + } + } + else + { + M2M_ERR("(hif) Wrong Size\n"); + ret = M2M_ERR_RCV; + goto ERR1; + } + } + else + { +#ifndef WIN32 + M2M_ERR("(hif) False interrupt %lx",reg); + ret = M2M_ERR_FAIL; + goto ERR1; +#else +#endif + } + } + else + { + M2M_ERR("(hif) Fail to Read interrupt reg\n"); + goto ERR1; + } + +ERR1: + return ret; +} + +#ifdef ARDUINO +void Socket_ReadSocketData_Small(void); +#endif + +/** +* @fn hif_handle_isr(void) +* @brief Handle interrupt received from NMC1500 firmware. +* @return The function SHALL return 0 for success and a negative value otherwise. +*/ + +sint8 hif_handle_isr(void) +{ + sint8 ret = M2M_SUCCESS; + +#ifdef ARDUINO + if(hif_small_xfer) { + /*SPI protocol paused to allow small transfer*/ + Socket_ReadSocketData_Small(); + return ret; + } +#endif + + while (gstrHifCxt.u8Interrupt) { + /*must be at that place because of the race of interrupt increment and that decrement*/ + /*when the interrupt enabled*/ + gstrHifCxt.u8Interrupt--; + while(1) + { + ret = hif_isr(); +#ifdef ARDUINO + if(hif_small_xfer) { + return ret; + } +#endif + if(ret == M2M_SUCCESS) { + /*we will try forever untill we get that interrupt*/ + /*Fail return errors here due to bus errors (reading expected values)*/ + break; + } else { + M2M_ERR("(HIF) Fail to handle interrupt %d try Again..\n",ret); + } + } + } + + return ret; +} +/* +* @fn hif_receive +* @brief Host interface interrupt serviece routine +* @param [in] u32Addr +* Receive start address +* @param [out] pu8Buf +* Pointer to receive buffer. Allocated by the caller +* @param [in] u16Sz +* Receive buffer size +* @param [in] isDone +* If you don't need any more packets send True otherwise send false +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ +sint8 hif_receive(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz, uint8 isDone) +{ + sint8 ret = M2M_SUCCESS; + if((u32Addr == 0)||(pu8Buf == NULL) || (u16Sz == 0)) + { + if(isDone) + { + /* set RX done */ + ret = hif_set_rx_done(); + } + else + { + ret = M2M_ERR_FAIL; + M2M_ERR(" hif_receive: Invalid argument\n"); + } + goto ERR1; + } + + if(u16Sz > gstrHifCxt.u32RxSize) + { + ret = M2M_ERR_FAIL; + M2M_ERR("APP Requested Size is larger than the recived buffer size <%u><%lu>\n",u16Sz, gstrHifCxt.u32RxSize); + goto ERR1; + } + if((u32Addr < gstrHifCxt.u32RxAddr)||((u32Addr + u16Sz)>(gstrHifCxt.u32RxAddr + gstrHifCxt.u32RxSize))) + { + ret = M2M_ERR_FAIL; + M2M_ERR("APP Requested Address beyond the recived buffer address and length\n"); + goto ERR1; + } + + /* Receive the payload */ + ret = nm_read_block(u32Addr, pu8Buf, u16Sz); + if(ret != M2M_SUCCESS)goto ERR1; + + /* check if this is the last packet */ + if((((gstrHifCxt.u32RxAddr + gstrHifCxt.u32RxSize) - (u32Addr + u16Sz)) <= 0) || isDone) + { + /* set RX done */ + ret = hif_set_rx_done(); + } + +ERR1: + return ret; +} + +/** +* @fn hif_register_cb +* @brief To set Callback function for every compantent Component +* @param [in] u8Grp +* Group to which the Callback function should be set. +* @param [in] fn +* function to be set +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +sint8 hif_register_cb(uint8 u8Grp,tpfHifCallBack fn) +{ + sint8 ret = M2M_SUCCESS; + switch(u8Grp) + { + case M2M_REQ_GROUP_IP: + gstrHifCxt.pfIpCb = fn; + break; + case M2M_REQ_GROUP_WIFI: + gstrHifCxt.pfWifiCb = fn; + break; + case M2M_REQ_GROUP_OTA: + gstrHifCxt.pfOtaCb = fn; + break; + case M2M_REQ_GROUP_HIF: + gstrHifCxt.pfHifCb = fn; + break; + case M2M_REQ_GROUP_CRYPTO: + gstrHifCxt.pfCryptoCb = fn; + break; + case M2M_REQ_GROUP_SIGMA: + gstrHifCxt.pfSigmaCb = fn; + break; + case M2M_REQ_GROUP_SSL: + gstrHifCxt.pfSslCb = fn; + break; + default: + M2M_ERR("GRp ? %d\n",u8Grp); + ret = M2M_ERR_FAIL; + break; + } + return ret; +} + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_hif.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_hif.h new file mode 100644 index 0000000..1187183 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_hif.h @@ -0,0 +1,249 @@ +/** + * + * \file + * + * \brief This module contains M2M host interface APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _M2M_HIF_ +#define _M2M_HIF_ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "common/include/nm_common.h" +/*!< Include depends on UNO Board is used or not*/ +#ifdef ENABLE_UNO_BOARD +#include "m2m_uno_hif.h" +#endif + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#define M2M_HIF_MAX_PACKET_SIZE (1600 - 4) +/*!< Maximum size of the buffer could be transferred between Host and Firmware. +*/ + +#define M2M_HIF_HDR_OFFSET (sizeof(tstrHifHdr) + 4) + +/** +* @struct tstrHifHdr +* @brief Structure to hold HIF header +*/ +typedef struct +{ + uint8 u8Gid; /*!< Group ID */ + uint8 u8Opcode; /*!< OP code */ + uint16 u16Length; /*!< Payload length */ +}tstrHifHdr; + +#ifdef __cplusplus + extern "C" { +#endif + +/*! +@typedef typedef void (*tpfHifCallBack)(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr); +@brief used to point to Wi-Fi call back function depend on Arduino project or other projects. +@param [in] u8OpCode + HIF Opcode type. +@param [in] u16DataSize + HIF data length. +@param [in] u32Addr + HIF address. +@param [in] grp + HIF group type. +*/ +typedef void (*tpfHifCallBack)(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr); +/** +* @fn NMI_API sint8 hif_init(void * arg); +* @brief + To initialize HIF layer. +* @param [in] arg +* Pointer to the arguments. +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 hif_init(void * arg); +/** +* @fn NMI_API sint8 hif_deinit(void * arg); +* @brief + To Deinitialize HIF layer. +* @param [in] arg +* Pointer to the arguments. +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 hif_deinit(void * arg); +/** +* @fn NMI_API sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, + uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) +* @brief Send packet using host interface. + +* @param [in] u8Gid +* Group ID. +* @param [in] u8Opcode +* Operation ID. +* @param [in] pu8CtrlBuf +* Pointer to the Control buffer. +* @param [in] u16CtrlBufSize + Control buffer size. +* @param [in] u16DataOffset + Packet Data offset. +* @param [in] pu8DataBuf +* Packet buffer Allocated by the caller. +* @param [in] u16DataSize + Packet buffer size (including the HIF header). +* @return The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, + uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset); +/* +* @fn hif_receive +* @brief Host interface interrupt serviece routine +* @param [in] u32Addr +* Receive start address +* @param [out] pu8Buf +* Pointer to receive buffer. Allocated by the caller +* @param [in] u16Sz +* Receive buffer size +* @param [in] isDone +* If you don't need any more packets send True otherwise send false +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +NMI_API sint8 hif_receive(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz, uint8 isDone); +/** +* @fn hif_register_cb +* @brief + To set Callback function for every Component. + +* @param [in] u8Grp +* Group to which the Callback function should be set. + +* @param [in] fn +* function to be set to the specified group. +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 hif_register_cb(uint8 u8Grp,tpfHifCallBack fn); +/** +* @fn NMI_API sint8 hif_chip_sleep(void); +* @brief + To make the chip sleep. +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 hif_chip_sleep(void); +/** +* @fn NMI_API sint8 hif_chip_sleep_sc(void); +* @brief + To clear the chip count only but keep the chip awake +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 hif_chip_sleep_sc(void); +/** +* @fn NMI_API sint8 hif_chip_wake(void); +* @brief + To Wakeup the chip. +* @return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ + +NMI_API sint8 hif_chip_wake(void); +/*! +@fn \ + NMI_API void hif_set_sleep_mode(uint8 u8Pstype); + +@brief + Set the sleep mode of the HIF layer. + +@param [in] u8Pstype + Sleep mode. + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ + +NMI_API void hif_set_sleep_mode(uint8 u8Pstype); +/*! +@fn \ + NMI_API uint8 hif_get_sleep_mode(void); + +@brief + Get the sleep mode of the HIF layer. + +@return + The function SHALL return the sleep mode of the HIF layer. +*/ + +NMI_API uint8 hif_get_sleep_mode(void); + +#ifdef CORTUS_APP +/** +* @fn hif_Resp_handler(uint8 *pu8Buffer, uint16 u16BufferSize) +* @brief + Response handler for HIF layer. + +* @param [in] pu8Buffer + Pointer to the buffer. + +* @param [in] u16BufferSize + Buffer size. + +* @return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 hif_Resp_handler(uint8 *pu8Buffer, uint16 u16BufferSize); +#endif + +/** +* @fn hif_handle_isr(void) +* @brief + Handle interrupt received from NMC1500 firmware. +* @return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 hif_handle_isr(void); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ota.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ota.c new file mode 100644 index 0000000..cf4a30f --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ota.c @@ -0,0 +1,417 @@ +/** + * + * \file + * + * \brief NMC1500 IoT OTA Interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#include "common/include/nm_common.h" +#include "driver/include/m2m_types.h" +#include "driver/include/m2m_ota.h" +#include "driver/source/m2m_hif.h" +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +static tpfOtaUpdateCb gpfOtaUpdateCb = NULL; +static tpfOtaNotifCb gpfOtaNotifCb = NULL; + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/** +* @fn m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr, uint8 grp) +* @brief WiFi call back function +* @param [in] u8OpCode +* HIF Opcode type. +* @param [in] u16DataSize +* HIF data length. +* @param [in] u32Addr +* HIF address. +* @param [in] grp +* HIF group type. +* @author +* @date +* @version 1.0 +*/ +static void m2m_ota_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +{ +#ifdef ARDUINO + (void)u16DataSize; // Silence "unused" warning +#endif + sint8 ret = M2M_SUCCESS; + if(u8OpCode == M2M_OTA_RESP_NOTIF_UPDATE_INFO) + { + tstrOtaUpdateInfo strOtaUpdateInfo; + m2m_memset((uint8*)&strOtaUpdateInfo,0,sizeof(tstrOtaUpdateInfo)); + ret = hif_receive(u32Addr,(uint8*)&strOtaUpdateInfo,sizeof(tstrOtaUpdateInfo),0); + if(ret == M2M_SUCCESS) + { + if(gpfOtaNotifCb) + gpfOtaNotifCb(&strOtaUpdateInfo); + } + } + else if (u8OpCode == M2M_OTA_RESP_UPDATE_STATUS) + { + tstrOtaUpdateStatusResp strOtaUpdateStatusResp; + m2m_memset((uint8*)&strOtaUpdateStatusResp,0,sizeof(tstrOtaUpdateStatusResp)); + ret = hif_receive(u32Addr, (uint8*) &strOtaUpdateStatusResp,sizeof(tstrOtaUpdateStatusResp), 0); + if(ret == M2M_SUCCESS) + { + if(gpfOtaUpdateCb) + gpfOtaUpdateCb(strOtaUpdateStatusResp.u8OtaUpdateStatusType,strOtaUpdateStatusResp.u8OtaUpdateStatus); + } + } + else + { + M2M_ERR("Invaild OTA resp %d ?\n",u8OpCode); + } + +} +/*! +@fn \ + NMI_API sint8 m2m_ota_init(tpfOtaUpdateCb pfOtaUpdateCb, tpfOtaNotifCb pfOtaNotifCb); + +@brief + Initialize the OTA layer. + +@param [in] pfOtaUpdateCb + OTA Update callback function + +@param [in] pfOtaNotifCb + OTA notify callback function + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_init(tpfOtaUpdateCb pfOtaUpdateCb, tpfOtaNotifCb pfOtaNotifCb) +{ + sint8 ret = M2M_SUCCESS; + + if(pfOtaUpdateCb){ + gpfOtaUpdateCb = pfOtaUpdateCb; + }else{ + M2M_ERR("Invaild Ota update cb\n"); + } + if(pfOtaNotifCb){ + gpfOtaNotifCb = pfOtaNotifCb; + }else{ + M2M_ERR("Invaild Ota notify cb\n"); + } + + hif_register_cb(M2M_REQ_GROUP_OTA,m2m_ota_cb); + + return ret; +} +/*! +@fn \ + NMI_API sint8 m2m_ota_notif_set_url(uint8 * u8Url); + +@brief + Set the OTA url + +@param [in] u8Url + The url server address + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_notif_set_url(uint8 * u8Url) +{ + sint8 ret = M2M_SUCCESS; + uint16 u16UrlSize = m2m_strlen(u8Url) + 1; + /*Todo: we may change it to data pkt but we need to give it higer priority + but the priorty is not implemnted yet in data pkt + */ + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_NOTIF_SET_URL,u8Url,u16UrlSize,NULL,0,0); + return ret; + +} + +/*! +@fn \ + NMI_API sint8 m2m_ota_notif_check_for_update(void); + +@brief + check for ota update + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_notif_check_for_update(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_NOTIF_CHECK_FOR_UPDATE,NULL,0,NULL,0,0); + return ret; +} + +/*! +@fn \ + NMI_API sint8 m2m_ota_notif_sched(uint32 u32Period); + +@brief + Schedule OTA update + +@param [in] u32Period + Period in days + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_notif_sched(uint32 u32Period) +{ +#ifdef ARDUINO + (void)u32Period; // Silence "unused" warning +#endif + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_NOTIF_CHECK_FOR_UPDATE,NULL,0,NULL,0,0); + return ret; +} + +/*! +@fn \ + NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl); + +@brief + Request OTA start update using the downloaded url + +@param [in] u8DownloadUrl + The download firmware url, you get it from device info + +@return + The function SHALL return 0 for success and a negative value otherwise. + +*/ +NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl) +{ + sint8 ret = M2M_SUCCESS; + uint16 u16DurlSize = m2m_strlen(u8DownloadUrl) + 1; + /*Todo: we may change it to data pkt but we need to give it higer priority + but the priorty is not implemnted yet in data pkt + */ + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_START_FW_UPDATE,u8DownloadUrl,u16DurlSize,NULL,0,0); + return ret; +} +/*! +@fn \ + NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl); + +@brief + Request OTA start for the Cortus app image. + +@param [in] u8DownloadUrl + The cortus application image url. + +@return + The function SHALL return 0 for success and a negative value otherwise. + +*/ +NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl) +{ + sint8 ret = M2M_SUCCESS; + uint16 u16DurlSize = m2m_strlen(u8DownloadUrl) + 1; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_START_CRT_UPDATE,u8DownloadUrl,u16DurlSize,NULL,0,0); + return ret; +} + + +/*! +@fn \ + NMI_API sint8 m2m_ota_rollback(void); + +@brief + Request OTA Rollback image + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_rollback(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_ROLLBACK_FW,NULL,0,NULL,0,0); + return ret; +} +/*! +@fn \ + NMI_API sint8 m2m_ota_rollback_crt(void); + +@brief + Request Cortus application OTA Rollback image + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_rollback_crt(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_ROLLBACK_CRT,NULL,0,NULL,0,0); + return ret; +} + +/*! +@fn \ + NMI_API sint8 m2m_ota_abort(void); + +@brief + Request OTA Abort + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_abort(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_ABORT,NULL,0,NULL,0,0); + return ret; +} + + +/*! +@fn \ + NMI_API sint8 m2m_ota_switch_firmware(void); + +@brief + Switch to the upgraded Firmware + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_switch_firmware(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_SWITCH_FIRMWARE,NULL,0,NULL,0,0); + return ret; +} +/*! +@fn \ + NMI_API sint8 m2m_ota_switch_crt(void); + +@brief + Switch to the upgraded cortus application. + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_switch_crt(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_SWITCH_CRT_IMG,NULL,0,NULL,0,0); + return ret; +} + +/*! +@fn \ + NMI_API sint8 m2m_ota_get_firmware_version(tstrM2mRev * pstrRev); + +@brief + Get the OTA Firmware version. + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ota_get_firmware_version(tstrM2mRev * pstrRev) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_chip_wake(); + if(ret == M2M_SUCCESS) + { + ret = nm_get_ota_firmware_info(pstrRev); + hif_chip_sleep(); + } + return ret; +} +#if 0 +#define M2M_OTA_FILE "../../../m2m_ota.dat" +NMI_API sint8 m2m_ota_test(void) +{ + uint32 page = 0; + uint8 buffer[1500]; + uint32 u32Sz = 0; + sint8 ret = M2M_SUCCESS; + FILE *fp =NULL; + fp = fopen(M2M_OTA_FILE,"rb"); + if(fp) + { + fseek(fp, 0L, SEEK_END); + u32Sz = ftell(fp); + fseek(fp, 0L, SEEK_SET); + + while(u32Sz > 0) + { + { + page = (rand()%1400); + + if((page<100)||(page>1400)) page = 1400; + } + + if(u32Sz>page) + { + u32Sz-=page; + } + else + { + page = u32Sz; + u32Sz = 0; + } + printf("page %d\n", (int)page); + fread(buffer,page,1,fp); + ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_TEST|M2M_REQ_DATA_PKT,NULL,0,(uint8*)&buffer,page,0); + if(ret != M2M_SUCCESS) + { + M2M_ERR("\n"); + } + nm_bsp_sleep(1); + } + + } + else + { + M2M_ERR("nO err\n"); + } + return ret; +} +#endif + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_periph.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_periph.c new file mode 100644 index 0000000..0f8890b --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_periph.c @@ -0,0 +1,187 @@ +/** + * + * \file + * + * \brief NMC1500 Peripherials Application Interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "driver/include/m2m_periph.h" +#include "driver/source/nmasic.h" +#include "m2m_hif.h" + +#ifdef CONF_PERIPH + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#define GPIO_OP_DIR 0 +#define GPIO_OP_SET 1 +#define GPIO_OP_GET 2 +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +STATIC FUNCTIONS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +static sint8 get_gpio_idx(uint8 u8GpioNum) +{ + if(u8GpioNum >= M2M_PERIPH_GPIO_MAX) return -1; + if(u8GpioNum == M2M_PERIPH_GPIO15) { return 15; + } else if(u8GpioNum == M2M_PERIPH_GPIO16) { return 16; + } else if(u8GpioNum == M2M_PERIPH_GPIO18) { return 18; + } else if(u8GpioNum == M2M_PERIPH_GPIO3) { return 3; + } else if(u8GpioNum == M2M_PERIPH_GPIO4) { return 4; + } else if(u8GpioNum == M2M_PERIPH_GPIO5) { return 5; + } else if(u8GpioNum == M2M_PERIPH_GPIO6) { return 6; + } else { + return -2; + } +} +/* + * GPIO read/write skeleton with wakeup/sleep capability. + */ +static sint8 gpio_ioctl(uint8 op, uint8 u8GpioNum, uint8 u8InVal, uint8 * pu8OutVal) +{ + sint8 ret, gpio; + + ret = hif_chip_wake(); + if(ret != M2M_SUCCESS) goto _EXIT; + + gpio = get_gpio_idx(u8GpioNum); + if(gpio < 0) goto _EXIT1; + + if(op == GPIO_OP_DIR) { + ret = set_gpio_dir((uint8)gpio, u8InVal); + } else if(op == GPIO_OP_SET) { + ret = set_gpio_val((uint8)gpio, u8InVal); + } else if(op == GPIO_OP_GET) { + ret = get_gpio_val((uint8)gpio, pu8OutVal); + } + if(ret != M2M_SUCCESS) goto _EXIT1; + +_EXIT1: + ret = hif_chip_sleep(); +_EXIT: + return ret; +} +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION IMPLEMENTATION +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +sint8 m2m_periph_init(tstrPerphInitParam * param) +{ +#ifdef ARDUINO + (void)param; // Silence "unused" warning +#endif + return M2M_SUCCESS; +} + +sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir) +{ + return gpio_ioctl(GPIO_OP_DIR, u8GpioNum, u8GpioDir, NULL); +} + +sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal) +{ + return gpio_ioctl(GPIO_OP_SET, u8GpioNum, u8GpioVal, NULL); +} + +sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal) +{ + return gpio_ioctl(GPIO_OP_GET, u8GpioNum, 0, pu8GpioVal); +} + +sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn) +{ +#ifdef ARDUINO + (void)u8GpioNum; // Silence "unused" warning + (void)u8PullupEn; +#endif + /* TBD */ + return M2M_SUCCESS; +} + +sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)param; +#endif + /* TBD */ + return M2M_SUCCESS; +} + +sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)u8SlaveAddr; + (void)pu8Buf; + (void)u16BufLen; + (void)flags; +#endif + /* TBD */ + return M2M_SUCCESS; +} + +sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)u8SlaveAddr; + (void)pu8Buf; + (void)u16BufLen; + (void)pu16ReadLen; + (void)flags; +#endif + /* TBD */ + return M2M_SUCCESS; +} + + +sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable) +{ + return pullup_ctrl(pinmask, enable); +} +#endif /* CONF_PERIPH */ \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ssl.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ssl.c new file mode 100644 index 0000000..07513f7 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ssl.c @@ -0,0 +1,309 @@ +/** + * + * \file + * + * \brief This module contains M2M Wi-Fi APIs implementation. + * + * Copyright (c) 2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "driver/include/m2m_ssl.h" +#include "driver/source/m2m_hif.h" +#include "driver/source/nmasic.h" + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +static tpfAppSSLCb gpfAppSSLCb = NULL; +static uint32 gu32HIFAddr = 0; + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/*! + @fn \ m2m_ssl_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) + @brief SSL callback function + @param [in] u8OpCode + HIF Opcode type. + @param [in] u16DataSize + HIF data length. + @param [in] u32Addr + HIF address. +*/ +static void m2m_ssl_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +{ +#ifdef ARDUINO + (void)u16DataSize; // Silence "unused" warning +#endif + sint8 s8tmp = M2M_SUCCESS; + switch(u8OpCode) + { + case M2M_SSL_REQ_ECC: + { + tstrEccReqInfo strEccREQ; + s8tmp = hif_receive(u32Addr, (uint8*)&strEccREQ, sizeof(tstrEccReqInfo), 0); + if(s8tmp == M2M_SUCCESS) + { + if (gpfAppSSLCb) + { + gu32HIFAddr = u32Addr + sizeof(tstrEccReqInfo); + gpfAppSSLCb(M2M_SSL_REQ_ECC, &strEccREQ); + } + } + } + break; + case M2M_SSL_RESP_SET_CS_LIST: + { + tstrSslSetActiveCsList strCsList; + s8tmp = hif_receive(u32Addr, (uint8*)&strCsList, sizeof(tstrSslSetActiveCsList), 0); + if(s8tmp == M2M_SUCCESS) + { + if (gpfAppSSLCb) + gpfAppSSLCb(M2M_SSL_RESP_SET_CS_LIST, &strCsList); + } + } + break; + } + if(s8tmp != M2M_SUCCESS) + { + M2M_ERR("Error receiving SSL from the HIF\n"); + } +} + + +/*! + @fn \ m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz) + @brief Sends ECC responses to the WINC + @param [in] strECCResp + ECC Response struct. + @param [in] pu8RspDataBuffe + Pointer of the response data to be sent. + @param [in] u16RspDataSz + Response data size. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz) +{ + sint8 s8Ret = M2M_SUCCESS; + + s8Ret = hif_send(M2M_REQ_GROUP_SSL, (M2M_SSL_RESP_ECC | M2M_REQ_DATA_PKT), (uint8*)strECCResp, sizeof(tstrEccReqInfo), pu8RspDataBuff, u16RspDataSz, sizeof(tstrEccReqInfo)); + + return s8Ret; +} + +/*! + @fn \ m2m_ssl_send_certs_to_winc(uint8* sector_buffer, uint32 sector_size) + @brief Sends certificates to the WINC + @param [in] pu8Buffer + Pointer to the certificates. + @param [in] u32BufferSz + Size of the certificates. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_send_certs_to_winc(uint8* pu8Buffer, uint32 u32BufferSz) +{ + sint8 s8Ret = M2M_SUCCESS; + + s8Ret = hif_send(M2M_REQ_GROUP_SSL, (M2M_SSL_IND_CERTS_ECC | M2M_REQ_DATA_PKT), NULL, 0, pu8Buffer, u32BufferSz, 0); + + return s8Ret; +} + +/*! + @fn \ m2m_ssl_retrieve_cert(uint32 u32ReadAddr, uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key) + @brief Retrieve the certificate to be verified from the WINC + @param [in] pu16CurveType + Pointer to the certificate curve type. + @param [in] pu8Hash + Pointer to the certificate hash. + @param [in] pu8Sig + Pointer to the certificate signature. + @param [in] pu8Key + Pointer to the certificate Key. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_retrieve_cert(uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key) +{ + uint8 bSetRxDone = 1; + uint16 u16HashSz, u16SigSz, u16KeySz; + sint8 s8Ret = M2M_SUCCESS; + + if(gu32HIFAddr == 0) return M2M_ERR_FAIL; + + if(hif_receive(gu32HIFAddr, (uint8*)pu16CurveType, 2, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += 2; + + if(hif_receive(gu32HIFAddr, (uint8*)&u16KeySz, 2, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += 2; + + if(hif_receive(gu32HIFAddr, (uint8*)&u16HashSz, 2, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += 2; + + if(hif_receive(gu32HIFAddr, (uint8*)&u16SigSz, 2, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += 2; + + (*pu16CurveType)= _htons((*pu16CurveType)); + pu8Key->u16Size = _htons(u16KeySz); + u16HashSz = _htons(u16HashSz); + u16SigSz = _htons(u16SigSz); + + if(hif_receive(gu32HIFAddr, pu8Key->X, pu8Key->u16Size * 2, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += (pu8Key->u16Size * 2); + + if(hif_receive(gu32HIFAddr, pu8Hash, u16HashSz, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += u16HashSz; + + if(hif_receive(gu32HIFAddr, pu8Sig, u16SigSz, 0) != M2M_SUCCESS) goto __ERR; + gu32HIFAddr += u16SigSz; + + bSetRxDone = 0; + +__ERR: + if(bSetRxDone) + { + s8Ret = M2M_ERR_FAIL; + hif_receive(0, NULL, 0, 1); + } + return s8Ret; +} + +/*! + @fn \ m2m_ssl_retrieve_hash(uint32 u32ReadAddr, uint8* pu8Hash, uint16 u16HashSz) + @brief Retrieve the certificate hash + @param [in] pu8Hash + Pointer to the certificate hash. + @param [in] u16HashSz + Hash size. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_retrieve_hash(uint8* pu8Hash, uint16 u16HashSz) +{ + uint8 bSetRxDone = 1; + sint8 s8Ret = M2M_SUCCESS; + + if(gu32HIFAddr == 0) return M2M_ERR_FAIL; + + if(hif_receive(gu32HIFAddr, pu8Hash, u16HashSz, 0) != M2M_SUCCESS) goto __ERR; + + bSetRxDone = 0; + +__ERR: + if(bSetRxDone) + { + s8Ret = M2M_ERR_FAIL; + hif_receive(0, NULL, 0, 1); + } + return s8Ret; +} + +/*! + @fn \ m2m_ssl_stop_processing_certs(void) + @brief Stops receiving from the HIF +*/ +NMI_API void m2m_ssl_stop_processing_certs(void) +{ + hif_receive(0, NULL, 0, 1); +} + +/*! + @fn \ m2m_ssl_ecc_process_done(void) + @brief Stops receiving from the HIF +*/ +NMI_API void m2m_ssl_ecc_process_done(void) +{ + gu32HIFAddr = 0; +} + +/*! +@fn \ + m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP); + Override the default Active SSL ciphers in the SSL module with a certain combination selected by the caller in the form of + a bitmap containing the required ciphers to be on. + There is no need to call this function if the application will not change the default ciphersuites. + +@param [in] u32SslCsBMP + Bitmap containing the desired ciphers to be enabled for the SSL module. The ciphersuites are defined in + @ref SSLCipherSuiteID. + The default ciphersuites are all ciphersuites supported by the firmware with the exception of ECC ciphersuites. + The caller can override the default with any desired combination, except for combinations involving both RSA + and ECC; if any RSA ciphersuite is enabled, then firmware will disable all ECC ciphersuites. + If u32SslCsBMP does not contain any ciphersuites supported by firmware, then the current active list will not + be changed. + +@return + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) +*/ +sint8 m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP) +{ + sint8 s8Ret = M2M_SUCCESS; + tstrSslSetActiveCsList strCsList; + + strCsList.u32CsBMP = u32SslCsBMP; + s8Ret = hif_send(M2M_REQ_GROUP_SSL, M2M_SSL_REQ_SET_CS_LIST, (uint8*)&strCsList, sizeof(tstrSslSetActiveCsList), NULL, 0, 0); + + return s8Ret; +} + +/*! + @fn \ m2m_ssl_init(tpfAppSslCb pfAppSslCb); + @brief Initializes the SSL layer. + @param [in] pfAppSslCb + Application SSL callback function. + @return The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_ssl_init(tpfAppSSLCb pfAppSSLCb) +{ + sint8 s8Ret = M2M_SUCCESS; + + gpfAppSSLCb = pfAppSSLCb; + gu32HIFAddr = 0; + + s8Ret = hif_register_cb(M2M_REQ_GROUP_SSL,m2m_ssl_cb); + if (s8Ret != M2M_SUCCESS) + { + M2M_ERR("hif_register_cb() failed with ret=%d", s8Ret); + } + return s8Ret; +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_wifi.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_wifi.c new file mode 100644 index 0000000..7998623 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_wifi.c @@ -0,0 +1,1522 @@ +/** + * + * \file + * + * \brief This module contains M2M Wi-Fi APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "driver/include/m2m_wifi.h" +#include "driver/source/m2m_hif.h" +#include "driver/source/nmasic.h" + +static volatile uint8 gu8ChNum; +static volatile uint8 gu8scanInProgress = 0; +static tpfAppWifiCb gpfAppWifiCb = NULL; + + +#ifdef ETH_MODE +static tpfAppEthCb gpfAppEthCb = NULL; +static uint8* gau8ethRcvBuf=NULL; +static uint16 gu16ethRcvBufSize ; +#endif + + +//#define CONF_MGMT +#ifdef CONF_MGMT +static tpfAppMonCb gpfAppMonCb = NULL; +static struct _tstrMgmtCtrl +{ + uint8* pu8Buf; + uint16 u16Offset; + uint16 u16Sz; +} +gstrMgmtCtrl = {NULL, 0 , 0}; +#endif +/** +* @fn m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr, uint8 grp) +* @brief WiFi call back function +* @param [in] u8OpCode +* HIF Opcode type. +* @param [in] u16DataSize +* HIF data length. +* @param [in] u32Addr +* HIF address. +* @param [in] grp +* HIF group type. +* @author +* @date +* @version 1.0 +*/ +static void m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) +{ +#ifdef ARDUINO + (void)u16DataSize; // Silence "unused" warning +#endif + uint8 rx_buf[8]; + if (u8OpCode == M2M_WIFI_RESP_CON_STATE_CHANGED) + { + tstrM2mWifiStateChanged strState; + if (hif_receive(u32Addr, (uint8*) &strState,sizeof(tstrM2mWifiStateChanged), 0) == M2M_SUCCESS) + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_CON_STATE_CHANGED, &strState); + } + } + else if (u8OpCode == M2M_WIFI_RESP_GET_SYS_TIME) + { + tstrSystemTime strSysTime; + if (hif_receive(u32Addr, (uint8*) &strSysTime,sizeof(tstrSystemTime), 0) == M2M_SUCCESS) + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_GET_SYS_TIME, &strSysTime); + } + } + else if(u8OpCode == M2M_WIFI_RESP_CONN_INFO) + { + tstrM2MConnInfo strConnInfo; + if(hif_receive(u32Addr, (uint8*)&strConnInfo, sizeof(tstrM2MConnInfo), 1) == M2M_SUCCESS) + { + if(gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_CONN_INFO, &strConnInfo); + } + } + else if (u8OpCode == M2M_WIFI_RESP_MEMORY_RECOVER) + { +#if 0 + if (hif_receive(u32Addr, rx_buf, 4, 1) == M2M_SUCCESS) + { + tstrM2mWifiStateChanged strState; + m2m_memcpy((uint8*) &strState, rx_buf,sizeof(tstrM2mWifiStateChanged)); + if (app_wifi_recover_cb) + app_wifi_recover_cb(strState.u8CurrState); + } +#endif + } + else if (u8OpCode == M2M_WIFI_REQ_DHCP_CONF) + { + tstrM2MIPConfig strIpConfig; +#ifdef ARDUINO + extern uint32 nmdrv_firm_ver; + uint16 rxSize = sizeof(tstrM2MIPConfig); + + if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 5, 0)) { + // for backwards compatibility with firmware 19.4.4 and older, + // the old tstrM2MIPConfig does not contain the u32DhcpLeaseTime field + rxSize -= sizeof(strIpConfig.u32DhcpLeaseTime); + } + + if (hif_receive(u32Addr, (uint8 *)&strIpConfig, rxSize, 0) == M2M_SUCCESS) +#else + if (hif_receive(u32Addr, (uint8 *)&strIpConfig, sizeof(tstrM2MIPConfig), 0) == M2M_SUCCESS) +#endif + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_REQ_DHCP_CONF, (uint8 *)&strIpConfig); + } + } + else if (u8OpCode == M2M_WIFI_REQ_WPS) + { + tstrM2MWPSInfo strWps; + m2m_memset((uint8*)&strWps,0,sizeof(tstrM2MWPSInfo)); + if(hif_receive(u32Addr, (uint8*)&strWps, sizeof(tstrM2MWPSInfo), 0) == M2M_SUCCESS) + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_REQ_WPS, &strWps); + } + } + else if (u8OpCode == M2M_WIFI_RESP_IP_CONFLICT) + { + uint32 u32ConflictedIP; + if(hif_receive(u32Addr, (uint8 *)&u32ConflictedIP, sizeof(u32ConflictedIP), 0) == M2M_SUCCESS) + { + M2M_INFO("Conflicted IP \" %u.%u.%u.%u \" \n", + BYTE_0(u32ConflictedIP),BYTE_1(u32ConflictedIP),BYTE_2(u32ConflictedIP),BYTE_3(u32ConflictedIP)); + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_IP_CONFLICT, NULL); + + } + } + else if (u8OpCode == M2M_WIFI_RESP_SCAN_DONE) + { + tstrM2mScanDone strState; + gu8scanInProgress = 0; + if(hif_receive(u32Addr, (uint8*)&strState, sizeof(tstrM2mScanDone), 0) == M2M_SUCCESS) + { + gu8ChNum = strState.u8NumofCh; + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_SCAN_DONE, &strState); + } + } + else if (u8OpCode == M2M_WIFI_RESP_SCAN_RESULT) + { + tstrM2mWifiscanResult strScanResult; + if(hif_receive(u32Addr, (uint8*)&strScanResult, sizeof(tstrM2mWifiscanResult), 0) == M2M_SUCCESS) + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_SCAN_RESULT, &strScanResult); + } + } + else if (u8OpCode == M2M_WIFI_RESP_CURRENT_RSSI) + { + if (hif_receive(u32Addr, rx_buf, 4, 0) == M2M_SUCCESS) + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_CURRENT_RSSI, rx_buf); + } + } + else if (u8OpCode == M2M_WIFI_RESP_CLIENT_INFO) + { + if (hif_receive(u32Addr, rx_buf, 4, 0) == M2M_SUCCESS) + { + if (gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_CLIENT_INFO, rx_buf); + } + } + else if(u8OpCode == M2M_WIFI_RESP_PROVISION_INFO) + { + tstrM2MProvisionInfo strProvInfo; + if(hif_receive(u32Addr, (uint8*)&strProvInfo, sizeof(tstrM2MProvisionInfo), 1) == M2M_SUCCESS) + { + if(gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_PROVISION_INFO, &strProvInfo); + } + } + else if(u8OpCode == M2M_WIFI_RESP_DEFAULT_CONNECT) + { + tstrM2MDefaultConnResp strResp; + if(hif_receive(u32Addr, (uint8*)&strResp, sizeof(tstrM2MDefaultConnResp), 1) == M2M_SUCCESS) + { + if(gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_DEFAULT_CONNECT, &strResp); + } + } + + else if(u8OpCode == M2M_WIFI_RESP_GET_PRNG) + { + tstrPrng strPrng; + if(hif_receive(u32Addr, (uint8*)&strPrng,sizeof(tstrPrng), 0) == M2M_SUCCESS) + { + if(hif_receive(u32Addr + sizeof(tstrPrng),strPrng.pu8RngBuff,strPrng.u16PrngSize, 1) == M2M_SUCCESS) + { + if(gpfAppWifiCb) + gpfAppWifiCb(M2M_WIFI_RESP_GET_PRNG,&strPrng); + } + } + } +#ifdef ETH_MODE + else if(u8OpCode == M2M_WIFI_RESP_ETHERNET_RX_PACKET) + { + uint8 u8SetRxDone; + tstrM2mIpRsvdPkt strM2mRsvd; + if(hif_receive(u32Addr, &strM2mRsvd ,sizeof(tstrM2mIpRsvdPkt), 0) == M2M_SUCCESS) + { + tstrM2mIpCtrlBuf strM2mIpCtrlBuf; + uint16 u16Offset = strM2mRsvd.u16PktOffset; + strM2mIpCtrlBuf.u16RemainigDataSize = strM2mRsvd.u16PktSz; + if((gpfAppEthCb) && (gau8ethRcvBuf) && (gu16ethRcvBufSize > 0)) + { + do + { + u8SetRxDone = 1; + if(strM2mIpCtrlBuf.u16RemainigDataSize > gu16ethRcvBufSize) + { + u8SetRxDone = 0; + strM2mIpCtrlBuf.u16DataSize = gu16ethRcvBufSize; + } + else + { + strM2mIpCtrlBuf.u16DataSize = strM2mIpCtrlBuf.u16RemainigDataSize; + } + + if(hif_receive(u32Addr + u16Offset, gau8ethRcvBuf, strM2mIpCtrlBuf.u16DataSize, u8SetRxDone) == M2M_SUCCESS) + { + strM2mIpCtrlBuf.u16RemainigDataSize -= strM2mIpCtrlBuf.u16DataSize; + u16Offset += strM2mIpCtrlBuf.u16DataSize; + gpfAppEthCb(M2M_WIFI_RESP_ETHERNET_RX_PACKET, gau8ethRcvBuf, &(strM2mIpCtrlBuf)); + } + else + { + break; + } + }while (strM2mIpCtrlBuf.u16RemainigDataSize > 0); + } + } + } +#endif /* ETH_MODE */ +#ifdef CONF_MGMT + else if(u8OpCode == M2M_WIFI_RESP_WIFI_RX_PACKET) + { + + tstrM2MWifiRxPacketInfo strRxPacketInfo; + if(u16DataSize >= sizeof(tstrM2MWifiRxPacketInfo)) { + if(hif_receive(u32Addr, (uint8*)&strRxPacketInfo, sizeof(tstrM2MWifiRxPacketInfo), 0) == M2M_SUCCESS) + { + u16DataSize -= sizeof(tstrM2MWifiRxPacketInfo); + if(u16DataSize > 0 && gstrMgmtCtrl.pu8Buf != NULL) + { + if(u16DataSize > (gstrMgmtCtrl.u16Sz + gstrMgmtCtrl.u16Offset)) + { + u16DataSize = gstrMgmtCtrl.u16Sz; + } + u32Addr += sizeof(tstrM2MWifiRxPacketInfo) + gstrMgmtCtrl.u16Offset; + if(hif_receive(u32Addr , gstrMgmtCtrl.pu8Buf, u16DataSize, 1) != M2M_SUCCESS) return; + } + if(gpfAppMonCb) + gpfAppMonCb(&strRxPacketInfo, gstrMgmtCtrl.pu8Buf,u16DataSize); + } + } else { + M2M_ERR("Incorrect mon data size %u\n", u16DataSize); + } + } +#endif + else + { + M2M_ERR("REQ Not defined %d\n",u8OpCode); + } +} + +sint8 m2m_wifi_download_mode() +{ + sint8 ret = M2M_SUCCESS; + /* Apply device specific initialization. */ + ret = nm_drv_init_download_mode(); + if(ret != M2M_SUCCESS) goto _EXIT0; + + + + enable_interrupts(); + +_EXIT0: + return ret; +} + +static sint8 m2m_validate_ap_parameters(CONST tstrM2MAPConfig* pstrM2MAPConfig) +{ + sint8 s8Ret = M2M_SUCCESS; + /* Check for incoming pointer */ + if(pstrM2MAPConfig == NULL) + { + M2M_ERR("INVALID POINTER\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + /* Check for SSID */ + if((m2m_strlen((uint8 *)pstrM2MAPConfig->au8SSID) <= 0) || (m2m_strlen((uint8 *)pstrM2MAPConfig->au8SSID) >= M2M_MAX_SSID_LEN)) + { + M2M_ERR("INVALID SSID\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + /* Check for Channel */ + if(pstrM2MAPConfig->u8ListenChannel > M2M_WIFI_CH_14 || pstrM2MAPConfig->u8ListenChannel < M2M_WIFI_CH_1) + { + M2M_ERR("INVALID CH\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + /* Check for DHCP Server IP address */ + if(!(pstrM2MAPConfig->au8DHCPServerIP[0] || pstrM2MAPConfig->au8DHCPServerIP[1])) + { + if(!(pstrM2MAPConfig->au8DHCPServerIP[2])) + { + M2M_ERR("INVALID DHCP SERVER IP\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + } + /* Check for Security */ + if(pstrM2MAPConfig->u8SecType == M2M_WIFI_SEC_OPEN) + { + goto ERR1; + } + else if(pstrM2MAPConfig->u8SecType == M2M_WIFI_SEC_WEP) + { + /* Check for WEP Key index */ + if((pstrM2MAPConfig->u8KeyIndx <= 0) || (pstrM2MAPConfig->u8KeyIndx > WEP_KEY_MAX_INDEX)) + { + M2M_ERR("INVALID KEY INDEX\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + /* Check for WEP Key size */ + if( (pstrM2MAPConfig->u8KeySz != WEP_40_KEY_STRING_SIZE) && + (pstrM2MAPConfig->u8KeySz != WEP_104_KEY_STRING_SIZE) + ) + { + M2M_ERR("INVALID KEY STRING SIZE\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + + if((m2m_strlen((uint8 *)pstrM2MAPConfig->au8WepKey) <= 0) || (m2m_strlen((uint8 *)pstrM2MAPConfig->au8WepKey) > WEP_104_KEY_STRING_SIZE)) + { + M2M_ERR("INVALID KEY SIZE\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + } + else if(pstrM2MAPConfig->u8SecType == M2M_WIFI_SEC_WPA_PSK) + { + /* Check for WPA Key size */ + if( ((pstrM2MAPConfig->u8KeySz + 1) < M2M_MIN_PSK_LEN) || ((pstrM2MAPConfig->u8KeySz + 1) > M2M_MAX_PSK_LEN)) + { + M2M_ERR("INVALID WPA KEY SIZE\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + } + else + { + M2M_ERR("INVALID AUTHENTICATION MODE\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR1; + } + +ERR1: + return s8Ret; +} +static sint8 m2m_validate_scan_options(tstrM2MScanOption* ptstrM2MScanOption) +{ + sint8 s8Ret = M2M_SUCCESS; + /* Check for incoming pointer */ + if(ptstrM2MScanOption == NULL) + { + M2M_ERR("INVALID POINTER\n"); + s8Ret = M2M_ERR_FAIL; + goto ERR; + } + /* Check for valid No of slots */ + if(ptstrM2MScanOption->u8NumOfSlot == 0) + { + M2M_ERR("INVALID No of scan slots! %d\n",ptstrM2MScanOption->u8NumOfSlot); + s8Ret = M2M_ERR_FAIL; + goto ERR; + } + /* Check for valid time of slots */ + if(ptstrM2MScanOption->u8SlotTime < 10 || ptstrM2MScanOption->u8SlotTime > 250) + { + M2M_ERR("INVALID scan slot time! %d\n",ptstrM2MScanOption->u8SlotTime); + s8Ret = M2M_ERR_FAIL; + goto ERR; + } + /* Check for valid No of probe requests per slot */ + if((ptstrM2MScanOption->u8ProbesPerSlot == 0)||(ptstrM2MScanOption->u8ProbesPerSlot > M2M_SCAN_DEFAULT_NUM_PROBE)) + { + M2M_ERR("INVALID No of probe requests per scan slot %d\n",ptstrM2MScanOption->u8ProbesPerSlot); + s8Ret = M2M_ERR_FAIL; + goto ERR; + } + /* Check for valid RSSI threshold */ + if((ptstrM2MScanOption->s8RssiThresh < -99) || (ptstrM2MScanOption->s8RssiThresh >= 0)) + { + M2M_ERR("INVALID RSSI threshold %d \n",ptstrM2MScanOption->s8RssiThresh); + s8Ret = M2M_ERR_FAIL; + } + +ERR: + return s8Ret; +} + +sint8 m2m_wifi_send_crl(tstrTlsCrlInfo* pCRL) +{ + sint8 s8Ret = M2M_ERR_FAIL; + s8Ret = hif_send(M2M_REQ_GROUP_SSL, M2M_SSL_IND_CRL|M2M_REQ_DATA_PKT, NULL, 0, (uint8*)pCRL, sizeof(tstrTlsCrlInfo), 0); + return s8Ret; +} + +sint8 m2m_wifi_init(tstrWifiInitParam * param) +{ + tstrM2mRev strtmp; + sint8 ret = M2M_SUCCESS; + uint8 u8WifiMode = M2M_WIFI_MODE_NORMAL; + + if(param == NULL) { + ret = M2M_ERR_FAIL; + goto _EXIT0; + } + + gpfAppWifiCb = param->pfAppWifiCb; + +#ifdef ETH_MODE + gpfAppEthCb = param->strEthInitParam.pfAppEthCb; + gau8ethRcvBuf = param->strEthInitParam.au8ethRcvBuf; + gu16ethRcvBufSize = param->strEthInitParam.u16ethRcvBufSize; + u8WifiMode = param->strEthInitParam.u8EthernetEnable; +#endif /* ETH_MODE */ + +#ifdef CONF_MGMT + gpfAppMonCb = param->pfAppMonCb; +#endif + gu8scanInProgress = 0; + /* Apply device specific initialization. */ + ret = nm_drv_init(&u8WifiMode); + if(ret != M2M_SUCCESS) goto _EXIT0; + /* Initialize host interface module */ + ret = hif_init(NULL); + if(ret != M2M_SUCCESS) goto _EXIT1; + + hif_register_cb(M2M_REQ_GROUP_WIFI,m2m_wifi_cb); + + ret = nm_get_firmware_full_info(&strtmp); + +#ifdef ARDUINO + if (M2M_ERR_FAIL == ret) + { + // for compatibility with firmware version 19.3.0 + ret = nm_get_firmware_info(&strtmp); + } +#endif + M2M_INFO("Firmware ver : %u.%u.%u Svnrev %u\n", strtmp.u8FirmwareMajor, strtmp.u8FirmwareMinor, strtmp.u8FirmwarePatch,strtmp.u16FirmwareSvnNum); + M2M_INFO("Firmware Build %s Time %s\n",strtmp.BuildDate,strtmp.BuildTime); + M2M_INFO("Firmware Min driver ver : %u.%u.%u\n", strtmp.u8DriverMajor, strtmp.u8DriverMinor, strtmp.u8DriverPatch); + M2M_INFO("Driver ver: %u.%u.%u\n", M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); + M2M_INFO("Driver built at %s\t%s\n",__DATE__,__TIME__); + if(M2M_ERR_FW_VER_MISMATCH == ret) + { + M2M_ERR("Mismatch Firmawre Version\n"); + } + + goto _EXIT0; + +_EXIT1: + nm_drv_deinit(NULL); +_EXIT0: + return ret; +} + +sint8 m2m_wifi_deinit(void * arg) +{ +#ifdef ARDUINO + (void)arg; // Silence "unused" warning +#endif + hif_deinit(NULL); + + nm_drv_deinit(NULL); + + return M2M_SUCCESS; +} + + +#ifdef ARDUINO +#include "socket/include/socket_buffer.h" +extern tstrSocketBuffer gastrSocketBuffer[]; +#endif + +sint8 m2m_wifi_handle_events(void * arg) +{ +#ifdef ARDUINO + (void)arg; // Silence "unused" warning + + uint8 i; + + /* Arduino API LIMITATION: */ + /* To be compliant with the standard Arduino WiFi API socket must be buffered. */ + /* WiFi101 shield does not have this ability and automatically pushes incoming */ + /* data to the Arduino MCU. Function m2m_wifi_handle_events() is taking care of */ + /* this transfer. Hence by ensuring that all the MCU socket buffers are available */ + /* we can perform the transfer. */ + /* However, if one socket buffer is full, we have to delay this transfer by */ + /* returning an error value, as we have no way of knowing which socket is about */ + /* to be used. */ + /* Consequently, the Arduino sketch must NOT block on reading only one socket if */ + /* several sockets are to be used. Instead, application must carefully read for */ + /* all sockets, anytime. */ + for (i = 0; i < MAX_SOCKET; ++i) { + if (gastrSocketBuffer[i].flag && (*(gastrSocketBuffer[i].flag) & SOCKET_BUFFER_FLAG_FULL)) { + return M2M_ERR_FAIL; + } + } +#endif + return hif_handle_isr(); +} + +sint8 m2m_wifi_default_connect(void) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DEFAULT_CONNECT, NULL, 0,NULL, 0,0); +} + +sint8 m2m_wifi_connect(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch) +{ + return m2m_wifi_connect_sc(pcSsid, u8SsidLen, u8SecType, pvAuthInfo, u16Ch,0); +} +sint8 m2m_wifi_connect_sc(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch, uint8 u8NoSaveCred) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mWifiConnect strConnect; + tstrM2MWifiSecInfo *pstrAuthInfo; + + if(u8SecType != M2M_WIFI_SEC_OPEN) + { + if(pvAuthInfo == NULL) + { + M2M_ERR("Key is not valid\n"); + ret = M2M_ERR_FAIL; + goto ERR1; + } + if((u8SecType == M2M_WIFI_SEC_WPA_PSK) && (m2m_strlen(pvAuthInfo) == (M2M_MAX_PSK_LEN-1))) + { + uint8 i = 0; + uint8* pu8Psk = (uint8*)pvAuthInfo; + while(i < (M2M_MAX_PSK_LEN-1)) + { + if(pu8Psk[i]<'0' || (pu8Psk[i]>'9' && pu8Psk[i] < 'A')|| (pu8Psk[i]>'F' && pu8Psk[i] < 'a') || pu8Psk[i] > 'f') + { + M2M_ERR("Invalid Key\n"); + ret = M2M_ERR_FAIL; + goto ERR1; + } + i++; + } + } + } + if((u8SsidLen<=0)||(u8SsidLen>=M2M_MAX_SSID_LEN)) + { + M2M_ERR("SSID LEN INVALID\n"); + ret = M2M_ERR_FAIL; + goto ERR1; + } + + if(u16Ch < M2M_WIFI_CH_1|| u16Ch > M2M_WIFI_CH_14) + { + if(u16Ch!=M2M_WIFI_CH_ALL) + { + M2M_ERR("CH INVALID\n"); + ret = M2M_ERR_FAIL; + goto ERR1; + } + } + + + m2m_memcpy(strConnect.au8SSID, (uint8*)pcSsid, u8SsidLen); + strConnect.au8SSID[u8SsidLen] = 0; + strConnect.u16Ch = NM_BSP_B_L_16(u16Ch); + /* Credentials will be Not be saved if u8NoSaveCred is set */ + strConnect.u8NoSaveCred = u8NoSaveCred ? 1:0; + pstrAuthInfo = &strConnect.strSec; + pstrAuthInfo->u8SecType = u8SecType; + + if(u8SecType == M2M_WIFI_SEC_WEP) + { + tstrM2mWifiWepParams * pstrWepParams = (tstrM2mWifiWepParams*)pvAuthInfo; + tstrM2mWifiWepParams *pstrWep = &pstrAuthInfo->uniAuth.strWepInfo; +#ifdef ARDUINO + pstrWep->u8KeyIndx =pstrWepParams->u8KeyIndx; +#else + pstrWep->u8KeyIndx =pstrWepParams->u8KeyIndx-1; +#endif + + if(pstrWep->u8KeyIndx >= WEP_KEY_MAX_INDEX) + { + M2M_ERR("Invalid Wep key index %d\n", pstrWep->u8KeyIndx); + ret = M2M_ERR_FAIL; + goto ERR1; + } +#ifdef ARDUINO + pstrWep->u8KeySz = pstrWepParams->u8KeySz; +#else + pstrWep->u8KeySz = pstrWepParams->u8KeySz-1; +#endif + if ((pstrWep->u8KeySz != WEP_40_KEY_STRING_SIZE)&& (pstrWep->u8KeySz != WEP_104_KEY_STRING_SIZE)) + { + M2M_ERR("Invalid Wep key length %d\n", pstrWep->u8KeySz); + ret = M2M_ERR_FAIL; + goto ERR1; + } + m2m_memcpy((uint8*)pstrWep->au8WepKey,(uint8*)pstrWepParams->au8WepKey, pstrWepParams->u8KeySz); + pstrWep->au8WepKey[pstrWepParams->u8KeySz] = 0; + + } + + + else if(u8SecType == M2M_WIFI_SEC_WPA_PSK) + { + uint16 u16KeyLen = m2m_strlen((uint8*)pvAuthInfo); + if((u16KeyLen <= 0)||(u16KeyLen >= M2M_MAX_PSK_LEN)) + { + M2M_ERR("Incorrect PSK key length\n"); + ret = M2M_ERR_FAIL; + goto ERR1; + } + m2m_memcpy(pstrAuthInfo->uniAuth.au8PSK, (uint8*)pvAuthInfo, u16KeyLen + 1); + } + else if(u8SecType == M2M_WIFI_SEC_802_1X) + { + m2m_memcpy((uint8*)&pstrAuthInfo->uniAuth.strCred1x, (uint8*)pvAuthInfo, sizeof(tstr1xAuthCredentials)); + } + else if(u8SecType == M2M_WIFI_SEC_OPEN) + { + + } + else + { + M2M_ERR("undefined sec type\n"); + ret = M2M_ERR_FAIL; + goto ERR1; + } + + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CONNECT, (uint8*)&strConnect, sizeof(tstrM2mWifiConnect),NULL, 0,0); + +ERR1: + return ret; +} + +sint8 m2m_wifi_disconnect(void) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISCONNECT, NULL, 0, NULL, 0,0); +} +sint8 m2m_wifi_set_mac_address(uint8 au8MacAddress[6]) +{ + tstrM2mSetMacAddress strTmp; + m2m_memcpy((uint8*) strTmp.au8Mac, (uint8*) au8MacAddress, 6); + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_MAC_ADDRESS, + (uint8*) &strTmp, sizeof(tstrM2mSetMacAddress), NULL, 0,0); +} + +sint8 m2m_wifi_set_static_ip(tstrM2MIPConfig * pstrStaticIPConf) +{ + pstrStaticIPConf->u32DNS = NM_BSP_B_L_32(pstrStaticIPConf->u32DNS); + pstrStaticIPConf->u32Gateway = NM_BSP_B_L_32(pstrStaticIPConf->u32Gateway); + pstrStaticIPConf->u32StaticIP = NM_BSP_B_L_32( + pstrStaticIPConf->u32StaticIP); + pstrStaticIPConf->u32SubnetMask = NM_BSP_B_L_32( + pstrStaticIPConf->u32SubnetMask); + return hif_send(M2M_REQ_GROUP_IP, M2M_IP_REQ_STATIC_IP_CONF, + (uint8*) pstrStaticIPConf, sizeof(tstrM2MIPConfig), NULL, 0,0); +} + +sint8 m2m_wifi_request_dhcp_client(void) +{ + /*legacy API should be removed */ + return 0; +} +sint8 m2m_wifi_request_dhcp_server(uint8* addr) +{ +#ifdef ARDUINO + (void)addr; // Silence "unused" warning +#endif + /*legacy API should be removed */ + return 0; +} +/*! +@fn NMI_API sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt * pstrM2mLsnInt); +@brief Set the Wi-Fi listen interval for power save operation. It is represented in units + of AP Beacon periods. +@param [in] pstrM2mLsnInt + Structure holding the listen interval configurations. +@return The function SHALL return 0 for success and a negative value otherwise. +@sa tstrM2mLsnInt , m2m_wifi_set_sleep_mode +@pre m2m_wifi_set_sleep_mode shall be called first +@warning The Function called once after initialization. +*/ +sint8 m2m_wifi_enable_dhcp(uint8 u8DhcpEn ) +{ + + uint8 u8Req; + u8Req = u8DhcpEn ? M2M_IP_REQ_ENABLE_DHCP : M2M_IP_REQ_DISABLE_DHCP; + return hif_send(M2M_REQ_GROUP_IP, u8Req, NULL, 0, NULL, 0, 0); + + +} + +sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt* pstrM2mLsnInt) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_LSN_INT, (uint8*)pstrM2mLsnInt, sizeof(tstrM2mLsnInt), NULL, 0, 0); +} + +sint8 m2m_wifi_set_cust_InfoElement(uint8* pau8M2mCustInfoElement) +{ + + sint8 ret = M2M_ERR_FAIL; + if(pau8M2mCustInfoElement != NULL) + { + if((pau8M2mCustInfoElement[0] + 1) < M2M_CUST_IE_LEN_MAX) + { + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CUST_INFO_ELEMENT|M2M_REQ_DATA_PKT, (uint8*)pau8M2mCustInfoElement, pau8M2mCustInfoElement[0]+1, NULL, 0, 0); + } + } + return ret; +} + +sint8 m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption) +{ + sint8 s8Ret = M2M_ERR_FAIL; + if(m2m_validate_scan_options (ptstrM2MScanOption) == M2M_SUCCESS) + { + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_SCAN_OPTION, (uint8*)ptstrM2MScanOption, sizeof(tstrM2MScanOption),NULL, 0,0); + } + return s8Ret; +} +sint8 m2m_wifi_set_scan_region(uint16 ScanRegion) +{ + sint8 s8Ret = M2M_ERR_FAIL; + tstrM2MScanRegion strScanRegion; + strScanRegion.u16ScanRegion = ScanRegion; + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_SCAN_REGION, (uint8*)&strScanRegion, sizeof(tstrM2MScanRegion),NULL, 0,0); + return s8Ret; +} +sint8 m2m_wifi_request_scan(uint8 ch) +{ + sint8 s8Ret = M2M_SUCCESS; + + if(!gu8scanInProgress) + { + if(((ch >= M2M_WIFI_CH_1) && (ch <= M2M_WIFI_CH_14)) || (ch == M2M_WIFI_CH_ALL)) + { + tstrM2MScan strtmp; + strtmp.u8ChNum = ch; + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SCAN, (uint8*)&strtmp, sizeof(tstrM2MScan),NULL, 0,0); + if(s8Ret == M2M_SUCCESS) + { + gu8scanInProgress = 1; + } + } + else + { + s8Ret = M2M_ERR_INVALID_ARG; + } + } + else + { + s8Ret = M2M_ERR_SCAN_IN_PROGRESS; + } + return s8Ret; +} + +sint8 m2m_wifi_request_scan_passive(uint8 ch, uint16 scan_time) +{ + sint8 s8Ret = M2M_SUCCESS; + + if(!gu8scanInProgress) + { + if(((ch >= M2M_WIFI_CH_1) && (ch <= M2M_WIFI_CH_14)) || (ch == M2M_WIFI_CH_ALL)) + { + tstrM2MScan strtmp; + strtmp.u8ChNum = ch; + + strtmp.u16PassiveScanTime = scan_time; + + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_PASSIVE_SCAN, (uint8*)&strtmp, sizeof(tstrM2MScan),NULL, 0,0); + if(s8Ret == M2M_SUCCESS) + { + gu8scanInProgress = 1; + } + } + else + { + s8Ret = M2M_ERR_INVALID_ARG; + } + } + else + { + s8Ret = M2M_ERR_SCAN_IN_PROGRESS; + } + return s8Ret; +} + +sint8 m2m_wifi_request_scan_ssid_list(uint8 ch,uint8 * u8Ssidlist) +{ + sint8 s8Ret = M2M_ERR_INVALID_ARG; + + if(!gu8scanInProgress) + { + if((((ch >= M2M_WIFI_CH_1) && (ch <= M2M_WIFI_CH_14)) || (ch == M2M_WIFI_CH_ALL))&&(u8Ssidlist != NULL)) + { + tstrM2MScan strtmp; + uint16 u16Lsize = 0; + uint8 u8Apnum = u8Ssidlist[u16Lsize]; + if(u8Apnum <= MAX_HIDDEN_SITES) + { + u16Lsize++; + while(u8Apnum) + { + if(u8Ssidlist[u16Lsize] >= M2M_MAX_SSID_LEN){ + goto EXIT; + }else { + u16Lsize += u8Ssidlist[u16Lsize] + 1; + u8Apnum--; + } + } + strtmp.u8ChNum = ch; + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SCAN_SSID_LIST|M2M_REQ_DATA_PKT, (uint8*)&strtmp, sizeof(tstrM2MScan),u8Ssidlist, u16Lsize,sizeof(tstrM2MScan)); + if(s8Ret == M2M_SUCCESS) + { + gu8scanInProgress = 1; + } + } + } + } + else + { + s8Ret = M2M_ERR_SCAN_IN_PROGRESS; + } +EXIT: + return s8Ret; +} +sint8 m2m_wifi_wps(uint8 u8TriggerType,const char *pcPinNumber) +{ + tstrM2MWPSConnect strtmp; + + /* Stop Scan if it is ongoing. + */ + gu8scanInProgress = 0; + strtmp.u8TriggerType = u8TriggerType; + /*If WPS is using PIN METHOD*/ + if (u8TriggerType == WPS_PIN_TRIGGER) + m2m_memcpy ((uint8*)strtmp.acPinNumber,(uint8*) pcPinNumber,8); + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_WPS, (uint8*)&strtmp,sizeof(tstrM2MWPSConnect), NULL, 0,0); +} +sint8 m2m_wifi_wps_disable(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_WPS, NULL,0, NULL, 0, 0); + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_req_client_ctrl(uint8 cmd); +@brief Send a command to the PS Client (An WINC1500 board running the ps_firmware), + if the PS client send any commands it will be received in wifi_cb M2M_WIFI_RESP_CLIENT_INFO +@param [in] cmd + Control command sent from PS Server to PS Client (command values defined by the application) +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. +@sa m2m_wifi_req_server_init, M2M_WIFI_RESP_CLIENT_INFO +@pre m2m_wifi_req_server_init should be called first +@warning +*/ +sint8 m2m_wifi_req_client_ctrl(uint8 u8Cmd) +{ + + sint8 ret = M2M_SUCCESS; +#ifdef _PS_SERVER_ + tstrM2Mservercmd strCmd; + strCmd.u8cmd = u8Cmd; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CLIENT_CTRL, (uint8*)&strCmd, sizeof(tstrM2Mservercmd), NULL, 0, 0); +#else +#ifdef ARDUINO + (void)u8Cmd; // Silence "unused" warning +#endif + M2M_ERR("_PS_SERVER_ is not defined\n"); +#endif + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_req_server_init(uint8 ch); +@brief Initialize the PS Server, The WINC1500 support Non secure communication with another WINC1500, + (SERVER/CLIENT) through one byte command (probe request and probe response) without any connection setup +@param [in] ch + Server listening channel +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise +@sa m2m_wifi_req_client_ctrl +@warning The server mode can't be used with any other modes (STA/P2P/AP) +*/ +sint8 m2m_wifi_req_server_init(uint8 ch) +{ + sint8 ret = M2M_SUCCESS; +#ifdef _PS_SERVER_ + tstrM2mServerInit strServer; + strServer.u8Channel = ch; + ret = hif_send(M2M_REQ_GROUP_WIFI,M2M_WIFI_REQ_SERVER_INIT, (uint8*)&strServer, sizeof(tstrM2mServerInit), NULL, 0, 0); +#else +#ifdef ARDUINO + (void)ch; // Silence "unused" warning +#endif + M2M_ERR("_PS_SERVER_ is not defined\n"); +#endif + return ret; +} +sint8 m2m_wifi_p2p(uint8 u8Channel) +{ + sint8 ret = M2M_SUCCESS; + if((u8Channel == M2M_WIFI_CH_1) || (u8Channel == M2M_WIFI_CH_6) || (u8Channel == M2M_WIFI_CH_11)) + { + tstrM2MP2PConnect strtmp; + strtmp.u8ListenChannel = u8Channel; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_P2P, (uint8*)&strtmp, sizeof(tstrM2MP2PConnect), NULL, 0,0); + } + else + { + M2M_ERR("Listen channel should only be M2M_WIFI_CH_1/6/11 \n"); + ret = M2M_ERR_FAIL; + } + return ret; +} +sint8 m2m_wifi_p2p_disconnect(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_P2P, NULL, 0, NULL, 0, 0); + return ret; +} +sint8 m2m_wifi_enable_ap(CONST tstrM2MAPConfig* pstrM2MAPConfig) +{ + sint8 ret = M2M_ERR_FAIL; + if(M2M_SUCCESS == m2m_validate_ap_parameters(pstrM2MAPConfig)) + { +#ifdef ARDUINO + extern uint32 nmdrv_firm_ver; + uint16 txSize = sizeof(tstrM2MAPConfig); + + if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 5, 0)) { + // for backwards compat with firmwware 19.4.x and older + // (listen channel is 0 based, there is no au8Key field) + ((tstrM2MAPConfig*)pstrM2MAPConfig)->u8ListenChannel--; + txSize -= sizeof(pstrM2MAPConfig->au8Key) + 1; + } + + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_AP, (uint8 *)pstrM2MAPConfig, txSize, NULL, 0, 0); +#else + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_AP, (uint8 *)pstrM2MAPConfig, sizeof(tstrM2MAPConfig), NULL, 0, 0); +#endif + } + return ret; +} + +sint8 m2m_wifi_set_gains(tstrM2mWifiGainsParams* pstrM2mGain) +{ + sint8 ret = M2M_ERR_FAIL; + if(pstrM2mGain != NULL) + { + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_GAINS, (uint8 *)pstrM2mGain, sizeof(tstrM2mWifiGainsParams), NULL, 0, 0); + } + return ret; +} +sint8 m2m_wifi_disable_ap(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_AP, NULL, 0, NULL, 0, 0); + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_req_curr_rssi(void); +@brief Request the current RSSI for the current connected AP, + the response received in wifi_cb M2M_WIFI_RESP_CURRENT_RSSI +@sa M2M_WIFI_RESP_CURRENT_RSSI +@return The function shall return M2M_SUCCESS for success and a negative value otherwise. +*/ +sint8 m2m_wifi_req_curr_rssi(void) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CURRENT_RSSI, NULL, 0, NULL,0, 0); + return ret; +} +sint8 m2m_wifi_send_ethernet_pkt(uint8* pu8Packet,uint16 u16PacketSize) +{ + sint8 s8Ret = -1; + if((pu8Packet != NULL)&&(u16PacketSize>0)) + { + tstrM2MWifiTxPacketInfo strTxPkt; + + strTxPkt.u16PacketSize = u16PacketSize; + strTxPkt.u16HeaderLength = M2M_ETHERNET_HDR_LEN; + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SEND_ETHERNET_PACKET | M2M_REQ_DATA_PKT, + (uint8*)&strTxPkt, sizeof(tstrM2MWifiTxPacketInfo), pu8Packet, u16PacketSize, M2M_ETHERNET_HDR_OFFSET - M2M_HIF_HDR_OFFSET); + } + return s8Ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); +@brief Request the MAC address stored on the OTP (one time programmable) memory of the device. + (the function is Blocking until response received) +@param [out] pu8MacAddr + Output MAC address buffer of 6 bytes size. Valid only if *pu8Valid=1. +@param [out] pu8IsValid + A output boolean value to indicate the validity of pu8MacAddr in OTP. + Output zero if the OTP memory is not programmed, non-zero otherwise. +@return The function shall return M2M_SUCCESS for success and a negative value otherwise. +@sa m2m_wifi_get_mac_address +@pre m2m_wifi_init required to call any WIFI/socket function +*/ +sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8* pu8IsValid) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_chip_wake(); + if(ret == M2M_SUCCESS) + { + ret = nmi_get_otp_mac_address(pu8MacAddr, pu8IsValid); + if(ret == M2M_SUCCESS) + { + ret = hif_chip_sleep(); + } + } + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr) +@brief Request the current MAC address of the device (the working mac address). + (the function is Blocking until response received) +@param [out] pu8MacAddr + Output MAC address buffer of 6 bytes size. +@return The function shall return M2M_SUCCESS for success and a negative value otherwise. +@sa m2m_wifi_get_otp_mac_address +@pre m2m_wifi_init required to call any WIFI/socket function +*/ +sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_chip_wake(); + if(ret == M2M_SUCCESS) + { + ret = nmi_get_mac_address(pu8MacAddr); + if(ret == M2M_SUCCESS) + { + ret = hif_chip_sleep(); + } + } + + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_req_scan_result(uint8 index); +@brief Reads the AP information from the Scan Result list with the given index, + the response received in wifi_cb M2M_WIFI_RESP_SCAN_RESULT, + the response pointer should be casted with tstrM2mWifiscanResult structure +@param [in] index + Index for the requested result, the index range start from 0 till number of AP's found +@sa tstrM2mWifiscanResult,m2m_wifi_get_num_ap_found,m2m_wifi_request_scan +@return The function shall return M2M_SUCCESE for success and a negative value otherwise +@pre m2m_wifi_request_scan need to be called first, then m2m_wifi_get_num_ap_found + to get the number of AP's found +@warning Function used only in STA mode only. the scan result updated only if scan request called, + else it will be cashed in firmware for the host scan request result, + which mean if large delay occur between the scan request and the scan result request, + the result will not be up-to-date +*/ + +sint8 m2m_wifi_req_scan_result(uint8 index) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mReqScanResult strReqScanRlt; + strReqScanRlt.u8Index = index; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SCAN_RESULT, (uint8*) &strReqScanRlt, sizeof(tstrM2mReqScanResult), NULL, 0, 0); + return ret; +} +/*! +@fn NMI_API uint8 m2m_wifi_get_num_ap_found(void); +@brief Reads the number of AP's found in the last Scan Request, + The function read the number of AP's from global variable which updated in the + wifi_cb in M2M_WIFI_RESP_SCAN_DONE. +@sa m2m_wifi_request_scan +@return Return the number of AP's found in the last Scan Request. +@pre m2m_wifi_request_scan need to be called first +@warning That function need to be called in the wifi_cb in M2M_WIFI_RESP_SCAN_DONE, + calling that function in any other place will return undefined/undated numbers. + Function used only in STA mode only. +*/ +uint8 m2m_wifi_get_num_ap_found(void) +{ + return gu8ChNum; +} +/*! +@fn NMI_API uint8 m2m_wifi_get_sleep_mode(void); +@brief Get the current Power save mode. +@return The current operating power saving mode. +@sa tenuPowerSaveModes , m2m_wifi_set_sleep_mode +*/ +uint8 m2m_wifi_get_sleep_mode(void) +{ + return hif_get_sleep_mode(); +} +/*! +@fn NMI_API sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn); +@brief Set the power saving mode for the WINC1500. +@param [in] PsTyp + Desired power saving mode. Supported types are defined in tenuPowerSaveModes. +@param [in] BcastEn + Broadcast reception enable flag. + If it is 1, the WINC1500 must be awake each DTIM Beacon for receiving Broadcast traffic. + If it is 0, the WINC1500 will not wakeup at the DTIM Beacon, but its wakeup depends only + on the the configured Listen Interval. +@return The function SHALL return 0 for success and a negative value otherwise. +@sa tenuPowerSaveModes +@warning The function called once after initialization. +*/ +sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mPsType strPs; + strPs.u8PsType = PsTyp; + strPs.u8BcastEn = BcastEn; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SLEEP, (uint8*) &strPs,sizeof(tstrM2mPsType), NULL, 0, 0); + M2M_INFO("POWER SAVE %d\n",PsTyp); + hif_set_sleep_mode(PsTyp); + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_request_sleep(void) +@brief Request from WINC1500 device to Sleep for specific time in the M2M_PS_MANUAL Power save mode (only). +@param [in] u32SlpReqTime + Request Sleep in ms +@return The function SHALL return M2M_SUCCESS for success and a negative value otherwise. +@sa tenuPowerSaveModes , m2m_wifi_set_sleep_mode +@warning the Function should be called in M2M_PS_MANUAL power save only +*/ +sint8 m2m_wifi_request_sleep(uint32 u32SlpReqTime) +{ + sint8 ret = M2M_SUCCESS; + uint8 psType; + psType = hif_get_sleep_mode(); + if(psType == M2M_PS_MANUAL) + { + tstrM2mSlpReqTime strPs; + strPs.u32SleepTime = u32SlpReqTime; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DOZE, (uint8*) &strPs,sizeof(tstrM2mSlpReqTime), NULL, 0, 0); + } + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength); +@brief Set the WINC1500 device name which is used as P2P device name. +@param [in] pu8DeviceName + Buffer holding the device name. +@param [in] u8DeviceNameLength + Length of the device name. +@return The function SHALL return M2M_SUCCESS for success and a negative value otherwise. +@warning The Function called once after initialization. +*/ +sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength) +{ + tstrM2MDeviceNameConfig strDeviceName; + if(u8DeviceNameLength >= M2M_DEVICE_NAME_MAX) + { + u8DeviceNameLength = M2M_DEVICE_NAME_MAX; + } + //pu8DeviceName[u8DeviceNameLength] = '\0'; + u8DeviceNameLength ++; + m2m_memcpy(strDeviceName.au8DeviceName, pu8DeviceName, u8DeviceNameLength); + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_DEVICE_NAME, + (uint8*)&strDeviceName, sizeof(tstrM2MDeviceNameConfig), NULL, 0,0); +} +sint8 m2m_wifi_get_firmware_version(tstrM2mRev *pstrRev) +{ + sint8 ret = M2M_SUCCESS; + ret = hif_chip_wake(); + if(ret == M2M_SUCCESS) + { + ret = nm_get_firmware_full_info(pstrRev); + hif_chip_sleep(); + } + return ret; +} +#ifdef CONF_MGMT +sint8 m2m_wifi_enable_monitoring_mode(tstrM2MWifiMonitorModeCtrl *pstrMtrCtrl, uint8 *pu8PayloadBuffer, + uint16 u16BufferSize, uint16 u16DataOffset) +{ + sint8 s8Ret = -1; + if((pstrMtrCtrl->u8ChannelID >= M2M_WIFI_CH_1) && (pstrMtrCtrl->u8ChannelID <= M2M_WIFI_CH_14)) + { + gstrMgmtCtrl.pu8Buf = pu8PayloadBuffer; + gstrMgmtCtrl.u16Sz = u16BufferSize; + gstrMgmtCtrl.u16Offset = u16DataOffset; + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_MONITORING, + (uint8*)pstrMtrCtrl, sizeof(tstrM2MWifiMonitorModeCtrl), NULL, 0,0); + } + return s8Ret; +} + +sint8 m2m_wifi_disable_monitoring_mode(void) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_MONITORING, NULL, 0, NULL, 0,0); +} + +sint8 m2m_wifi_send_wlan_pkt(uint8 *pu8WlanPacket, uint16 u16WlanHeaderLength, uint16 u16WlanPktSize) +{ + sint8 s8Ret = -1; + if(pu8WlanPacket != NULL) + { + tstrM2MWifiTxPacketInfo strTxPkt; + + strTxPkt.u16PacketSize = u16WlanPktSize; + strTxPkt.u16HeaderLength = u16WlanHeaderLength; + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SEND_WIFI_PACKET | M2M_REQ_DATA_PKT, + (uint8*)&strTxPkt, sizeof(tstrM2MWifiTxPacketInfo), pu8WlanPacket, u16WlanPktSize, sizeof(tstrM2MWifiTxPacketInfo)); + } + return s8Ret; +} +#endif + +sint8 m2m_wifi_start_provision_mode(tstrM2MAPConfig *pstrAPConfig, char *pcHttpServerDomainName, uint8 bEnableHttpRedirect) +{ + sint8 s8Ret = M2M_ERR_FAIL; + + if((pstrAPConfig != NULL)) + { + tstrM2MProvisionModeConfig strProvConfig; + if(M2M_SUCCESS == m2m_validate_ap_parameters(pstrAPConfig)) + { + m2m_memcpy((uint8*)&strProvConfig.strApConfig, (uint8*)pstrAPConfig, sizeof(tstrM2MAPConfig)); + if((m2m_strlen((uint8 *)pcHttpServerDomainName) <= 0) || (NULL == pcHttpServerDomainName)) + { + M2M_ERR("INVALID DOMAIN NAME\n"); + goto ERR1; + } + m2m_memcpy((uint8*)strProvConfig.acHttpServerDomainName, (uint8*)pcHttpServerDomainName, 64); + strProvConfig.u8EnableRedirect = bEnableHttpRedirect; + + /* Stop Scan if it is ongoing. + */ + gu8scanInProgress = 0; +#ifdef ARDUINO + extern uint32 nmdrv_firm_ver; + uint16 txSize = sizeof(tstrM2MProvisionModeConfig); + + if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 5, 0)) { + // for backwards compat with firmwware 19.4.x and older + // (listen channel is 0 based, there is no au8Key field) + strProvConfig.strApConfig.u8ListenChannel--; + txSize -= sizeof(strProvConfig.strApConfig.au8Key) + 1; + m2m_memcpy((uint8*)&strProvConfig.strApConfig.au8Key[3], (uint8*)pcHttpServerDomainName, 64); + uint8* pu8EnableRedirect = (uint8*)strProvConfig.strApConfig.au8Key; + pu8EnableRedirect[3 + 64] = bEnableHttpRedirect; + } + + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_START_PROVISION_MODE | M2M_REQ_DATA_PKT, + (uint8*)&strProvConfig, txSize, NULL, 0, 0); +#else + s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_START_PROVISION_MODE | M2M_REQ_DATA_PKT, + (uint8*)&strProvConfig, sizeof(tstrM2MProvisionModeConfig), NULL, 0, 0); +#endif + } + else + { + /*goto ERR1;*/ + } + } +ERR1: + return s8Ret; +} + +sint8 m2m_wifi_stop_provision_mode(void) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_STOP_PROVISION_MODE, NULL, 0, NULL, 0, 0); +} + +sint8 m2m_wifi_get_connection_info(void) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_GET_CONN_INFO, NULL, 0, NULL, 0, 0); +} + +sint8 m2m_wifi_set_sytem_time(uint32 u32UTCSeconds) +{ + /* + The firmware accepts timestamps relative to 1900 like NTP Timestamp. + */ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_SYS_TIME, (uint8*)&u32UTCSeconds, sizeof(tstrSystemTime), NULL, 0, 0); +} +/*! + * @fn NMI_API sint8 m2m_wifi_get_sytem_time(void); + * @see m2m_wifi_enable_sntp + tstrSystemTime + * @note get the system time from the sntp client + * using the API \ref m2m_wifi_get_sytem_time. + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +sint8 m2m_wifi_get_sytem_time(void) +{ + return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_GET_SYS_TIME, NULL,0, NULL, 0, 0); +} + +sint8 m2m_wifi_enable_sntp(uint8 bEnable) +{ + uint8 u8Req; + + u8Req = bEnable ? M2M_WIFI_REQ_ENABLE_SNTP_CLIENT : M2M_WIFI_REQ_DISABLE_SNTP_CLIENT; + return hif_send(M2M_REQ_GROUP_WIFI, u8Req, NULL, 0, NULL, 0, 0); +} +/*! +@fn NMI_API sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode); +@brief Change the power profile mode +@param [in] u8PwrMode + Change the WINC power profile to different mode + PWR_LOW1/PWR_LOW2/PWR_HIGH/PWR_AUTO (tenuM2mPwrMode) +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. +@sa tenuM2mPwrMode +@pre m2m_wifi_init +@warning must be called after the initializations and before any connection request and can't be changed in run time, +*/ +sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mPwrMode strM2mPwrMode; + strM2mPwrMode.u8PwrMode = u8PwrMode; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_POWER_PROFILE, (uint8*)&strM2mPwrMode,sizeof(tstrM2mPwrMode), NULL, 0, 0); + return ret; +} +/*! +@fn NMI_API sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel); +@brief set the TX power tenuM2mTxPwrLevel +@param [in] u8TxPwrLevel + change the TX power tenuM2mTxPwrLevel +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. +@sa tenuM2mTxPwrLevel +@pre m2m_wifi_init +@warning +*/ +sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mTxPwrLevel strM2mTxPwrLevel; + strM2mTxPwrLevel.u8TxPwrLevel = u8TxPwrLevel; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_TX_POWER, (uint8*)&strM2mTxPwrLevel,sizeof(tstrM2mTxPwrLevel), NULL, 0, 0); + return ret; +} + +/*! +@fn NMI_API sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable); +@brief Enable or Disable logs in run time (Disable Firmware logs will + enhance the firmware start-up time and performance) +@param [in] u8Enable + Set 1 to enable the logs 0 for disable +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. +@sa __DISABLE_FIRMWARE_LOGS__ (build option to disable logs from initializations) +@pre m2m_wifi_init +@warning +*/ +sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mEnableLogs strM2mEnableLogs; + strM2mEnableLogs.u8Enable = u8Enable; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_ENABLE_LOGS, (uint8*)&strM2mEnableLogs,sizeof(tstrM2mEnableLogs), NULL, 0, 0); + return ret; +} + +/*! +@fn NMI_API sint8 m2m_wifi_set_battery_voltage(uint16 u16BattVoltx100); +@brief Enable or Disable logs in run time (Disable Firmware logs will + enhance the firmware start-up time and performance) +@param [in] u16BattVoltx100 + battery voltage multiplied by 100 +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. +@sa __DISABLE_FIRMWARE_LOGS__ (build option to disable logs from initializations) +@pre m2m_wifi_init +@warning +*/ +sint8 m2m_wifi_set_battery_voltage(uint16 u16BattVoltx100) +{ + sint8 ret = M2M_SUCCESS; + tstrM2mBatteryVoltage strM2mBattVol = {0}; + strM2mBattVol.u16BattVolt = u16BattVoltx100; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_BATTERY_VOLTAGE, (uint8*)&strM2mBattVol,sizeof(tstrM2mBatteryVoltage), NULL, 0, 0); + return ret; +} +/*! +@fn sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PrngBuff,uint16 u16PrngSize) +@brief Get random bytes using the PRNG bytes. +@param [in] u16PrngSize + Size of the required random bytes to be generated. +@param [in] pu8PrngBuff + Pointer to user allocated buffer. +@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. +*/ +sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PrngBuff,uint16 u16PrngSize) +{ + sint8 ret = M2M_ERR_FAIL; + tstrPrng strRng = {0}; + if((u16PrngSize < (M2M_BUFFER_MAX_SIZE - sizeof(tstrPrng)))&&(pu8PrngBuff != NULL)) + { + strRng.u16PrngSize = u16PrngSize; + strRng.pu8RngBuff = pu8PrngBuff; + ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_GET_PRNG|M2M_REQ_DATA_PKT,(uint8 *)&strRng, sizeof(tstrPrng),NULL,0, 0); + } + else + { + M2M_ERR("PRNG Buffer exceeded maximum size %d or NULL Buffer\n",u16PrngSize); + } + return ret; +} +#ifdef ETH_MODE +/*! +@fn \ + NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8* pu8MulticastMacAddress, uint8 u8AddRemove) + +@brief + Add MAC filter to receive Multicast packets. + +@param [in] pu8MulticastMacAddress + Pointer to the MAC address. +@param [in] u8AddRemove + Flag to Add/Remove MAC address. +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ + +NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8* pu8MulticastMacAddress, uint8 u8AddRemove) +{ + sint8 s8ret = M2M_ERR_FAIL; + tstrM2MMulticastMac strMulticastMac; + + if(pu8MulticastMacAddress != NULL ) + { + strMulticastMac.u8AddRemove = u8AddRemove; + m2m_memcpy(strMulticastMac.au8macaddress,pu8MulticastMacAddress,M2M_MAC_ADDRES_LEN); + M2M_DBG("mac multicast: %x:%x:%x:%x:%x:%x\r\n",strMulticastMac.au8macaddress[0],strMulticastMac.au8macaddress[1],strMulticastMac.au8macaddress[2],strMulticastMac.au8macaddress[3],strMulticastMac.au8macaddress[4],strMulticastMac.au8macaddress[5]); + s8ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_MAC_MCAST, (uint8 *)&strMulticastMac,sizeof(tstrM2MMulticastMac),NULL,0,0); + } + + return s8ret; + +} + +/*! +@fn \ + NMI_API sint8 m2m_wifi_set_receive_buffer(void* pvBuffer,uint16 u16BufferLen); + +@brief + set the ethernet receive buffer, should be called in the receive call back. + +@param [in] pvBuffer + Pointer to the ethernet receive buffer. +@param [in] u16BufferLen + Length of the buffer. + +@return + The function SHALL return 0 for success and a negative value otherwise. +*/ +NMI_API sint8 m2m_wifi_set_receive_buffer(void* pvBuffer,uint16 u16BufferLen) +{ + sint8 s8ret = M2M_SUCCESS; + if(pvBuffer != NULL) + { + gau8ethRcvBuf = pvBuffer; + gu16ethRcvBufSize= u16BufferLen; + } + else + { + s8ret = M2M_ERR_FAIL; + M2M_ERR("Buffer NULL pointer\r\n"); + } + return s8ret; +} +#endif /* ETH_MODE */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmasic.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmasic.c new file mode 100644 index 0000000..91c0e5a --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmasic.c @@ -0,0 +1,688 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 ASIC specific internal APIs. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "common/include/nm_common.h" +#include "driver/source/nmbus.h" +#include "bsp/include/nm_bsp.h" +#include "driver/source/nmasic.h" +#include "driver/include/m2m_types.h" + +#define NMI_GLB_RESET_0 (NMI_PERIPH_REG_BASE + 0x400) +#define NMI_INTR_REG_BASE (NMI_PERIPH_REG_BASE + 0xa00) +#define NMI_PIN_MUX_0 (NMI_PERIPH_REG_BASE + 0x408) +#define NMI_INTR_ENABLE (NMI_INTR_REG_BASE) +#define GET_UINT32(X,Y) (X[0+Y] + ((uint32)X[1+Y]<<8) + ((uint32)X[2+Y]<<16) +((uint32)X[3+Y]<<24)) + +/*SPI and I2C only*/ +#define CORT_HOST_COMM (0x10) +#define HOST_CORT_COMM (0x0b) +#define WAKE_CLK_REG (0x1) +#define CLOCKS_EN_REG (0xf) + + + +#ifdef ARDUINO +#define TIMEOUT (2000) +#else +#define TIMEOUT (0xfffffffful) +#endif +#define WAKUP_TRAILS_TIMEOUT (4) + +sint8 chip_apply_conf(uint32 u32Conf) +{ + sint8 ret = M2M_SUCCESS; + uint32 val32 = u32Conf; + +#if (defined __ENABLE_PMU__) || (defined CONF_WINC_INT_PMU) + val32 |= rHAVE_USE_PMU_BIT; +#endif +#ifdef __ENABLE_SLEEP_CLK_SRC_RTC__ + val32 |= rHAVE_SLEEP_CLK_SRC_RTC_BIT; +#elif defined __ENABLE_SLEEP_CLK_SRC_XO__ + val32 |= rHAVE_SLEEP_CLK_SRC_XO_BIT; +#endif +#ifdef __ENABLE_EXT_PA_INV_TX_RX__ + val32 |= rHAVE_EXT_PA_INV_TX_RX; +#endif +#ifdef __ENABLE_LEGACY_RF_SETTINGS__ + val32 |= rHAVE_LEGACY_RF_SETTINGS; +#endif +#ifdef __DISABLE_FIRMWARE_LOGS__ + val32 |= rHAVE_LOGS_DISABLED_BIT; +#endif + + val32 |= rHAVE_RESERVED1_BIT; + do { + nm_write_reg(rNMI_GP_REG_1, val32); + if(val32 != 0) { + uint32 reg = 0; + ret = nm_read_reg_with_ret(rNMI_GP_REG_1, ®); + if(ret == M2M_SUCCESS) { + if(reg == val32) + break; + } + } else { + break; + } + } while(1); + + return M2M_SUCCESS; +} +void chip_idle(void) +{ + uint32 reg = 0; + nm_read_reg_with_ret(WAKE_CLK_REG, ®); + if(reg & NBIT1) + { + reg &=~ NBIT1; + nm_write_reg(WAKE_CLK_REG, reg); + } +} + +sint8 enable_interrupts(void) +{ + uint32 reg = 0; + sint8 ret = M2M_SUCCESS; + /** + interrupt pin mux select + **/ + ret = nm_read_reg_with_ret(NMI_PIN_MUX_0, ®); + if (M2M_SUCCESS != ret) goto ERR1; + + reg |= ((uint32) 1 << 8); + ret = nm_write_reg(NMI_PIN_MUX_0, reg); + if (M2M_SUCCESS != ret) goto ERR1; + + /** + interrupt enable + **/ + ret = nm_read_reg_with_ret(NMI_INTR_ENABLE, ®); + if (M2M_SUCCESS != ret) goto ERR1; + + reg |= ((uint32) 1 << 16); + ret = nm_write_reg(NMI_INTR_ENABLE, reg); + if (M2M_SUCCESS != ret) goto ERR1; +ERR1: + return ret; +} + +sint8 cpu_start(void) { + uint32 reg = 0; + sint8 ret; + + /** + reset regs + */ + ret = nm_write_reg(BOOTROM_REG,0); + ret += nm_write_reg(NMI_STATE_REG,0); + ret += nm_write_reg(NMI_REV_REG,0); + /** + Go... + **/ + ret += nm_read_reg_with_ret(0x1118, ®); + reg |= (1 << 0); + ret += nm_write_reg(0x1118, reg); + ret += nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); + if ((reg & (1ul << 10)) == (1ul << 10)) { + reg &= ~(1ul << 10); + ret += nm_write_reg(NMI_GLB_RESET_0, reg); + } + reg |= (1ul << 10); + ret += nm_write_reg(NMI_GLB_RESET_0, reg); + nm_bsp_sleep(1); + return ret; +} + +uint32 nmi_get_chipid(void) +{ + static uint32 chipid = 0; + + if (chipid == 0) { + uint32 rfrevid; + + if((nm_read_reg_with_ret(0x1000, &chipid)) != M2M_SUCCESS) { + chipid = 0; + return 0; + } + //if((ret = nm_read_reg_with_ret(0x11fc, &revid)) != M2M_SUCCESS) { + // return 0; + //} + if((nm_read_reg_with_ret(0x13f4, &rfrevid)) != M2M_SUCCESS) { + chipid = 0; + return 0; + } + + if (chipid == 0x1002a0) { + if (rfrevid == 0x1) { /* 1002A0 */ + } else /* if (rfrevid == 0x2) */ { /* 1002A1 */ + chipid = 0x1002a1; + } + } else if(chipid == 0x1002b0) { + if(rfrevid == 3) { /* 1002B0 */ + } else if(rfrevid == 4) { /* 1002B1 */ + chipid = 0x1002b1; + } else /* if(rfrevid == 5) */ { /* 1002B2 */ + chipid = 0x1002b2; + } + }else if(chipid == 0x1000F0) { + if((nm_read_reg_with_ret(0x3B0000, &chipid)) != M2M_SUCCESS) { + chipid = 0; + return 0; + } + }else { + + } +//#define PROBE_FLASH +#ifdef PROBE_FLASH + if(chipid) { + UWORD32 flashid; + + flashid = probe_spi_flash(); + if(flashid == 0x1230ef) { + chipid &= ~(0x0f0000); + chipid |= 0x050000; + } + if(flashid == 0xc21320c2) { + chipid &= ~(0x0f0000); + chipid |= 0x050000; + } + } +#else + /*M2M is by default have SPI flash*/ + chipid &= ~(0x0f0000); + chipid |= 0x050000; +#endif /* PROBE_FLASH */ + } + return chipid; +} + +uint32 nmi_get_rfrevid(void) +{ + uint32 rfrevid; + if((nm_read_reg_with_ret(0x13f4, &rfrevid)) != M2M_SUCCESS) { + rfrevid = 0; + return 0; + } + return rfrevid; +} + +void restore_pmu_settings_after_global_reset(void) +{ + /* + * Must restore PMU register value after + * global reset if PMU toggle is done at + * least once since the last hard reset. + */ + if(REV(nmi_get_chipid()) >= REV_2B0) { + nm_write_reg(0x1e48, 0xb78469ce); + } +} + +void nmi_update_pll(void) +{ + uint32 pll; + + pll = nm_read_reg(0x1428); + pll &= ~0x1ul; + nm_write_reg(0x1428, pll); + pll |= 0x1ul; + nm_write_reg(0x1428, pll); + +} +void nmi_set_sys_clk_src_to_xo(void) +{ + uint32 val32; + + /* Switch system clock source to XO. This will take effect after nmi_update_pll(). */ + val32 = nm_read_reg(0x141c); + val32 |= (1 << 2); + nm_write_reg(0x141c, val32); + + /* Do PLL update */ + nmi_update_pll(); +} +sint8 chip_sleep(void) +{ + uint32 reg; + sint8 ret = M2M_SUCCESS; + + while(1) + { + ret = nm_read_reg_with_ret(CORT_HOST_COMM,®); + if(ret != M2M_SUCCESS) goto ERR1; + if((reg & NBIT0) == 0) break; + } + + /* Clear bit 1 */ + ret = nm_read_reg_with_ret(WAKE_CLK_REG, ®); + if(ret != M2M_SUCCESS)goto ERR1; + if(reg & NBIT1) + { + reg &=~NBIT1; + ret = nm_write_reg(WAKE_CLK_REG, reg); + if(ret != M2M_SUCCESS)goto ERR1; + } + + ret = nm_read_reg_with_ret(HOST_CORT_COMM, ®); + if(ret != M2M_SUCCESS)goto ERR1; + if(reg & NBIT0) + { + reg &= ~NBIT0; + ret = nm_write_reg(HOST_CORT_COMM, reg); + if(ret != M2M_SUCCESS)goto ERR1; + } + +ERR1: + return ret; +} +sint8 chip_wake(void) +{ + sint8 ret = M2M_SUCCESS; + uint32 reg = 0, clk_status_reg = 0,trials = 0; + + ret = nm_read_reg_with_ret(HOST_CORT_COMM, ®); + if(ret != M2M_SUCCESS)goto _WAKE_EXIT; + + if(!(reg & NBIT0)) + { + /*USE bit 0 to indicate host wakeup*/ + ret = nm_write_reg(HOST_CORT_COMM, reg|NBIT0); + if(ret != M2M_SUCCESS)goto _WAKE_EXIT; + } + + ret = nm_read_reg_with_ret(WAKE_CLK_REG, ®); + if(ret != M2M_SUCCESS)goto _WAKE_EXIT; + /* Set bit 1 */ + if(!(reg & NBIT1)) + { + ret = nm_write_reg(WAKE_CLK_REG, reg | NBIT1); + if(ret != M2M_SUCCESS) goto _WAKE_EXIT; + } + + do + { + ret = nm_read_reg_with_ret(CLOCKS_EN_REG, &clk_status_reg); + if(ret != M2M_SUCCESS) { + M2M_ERR("Bus error (5).%d %lx\n",ret,clk_status_reg); + goto _WAKE_EXIT; + } + if(clk_status_reg & NBIT2) { + break; + } + nm_bsp_sleep(2); + trials++; + if(trials > WAKUP_TRAILS_TIMEOUT) + { + M2M_ERR("Failed to wakup the chip\n"); + ret = M2M_ERR_TIME_OUT; + goto _WAKE_EXIT; + } + }while(1); + + /*workaround sometimes spi fail to read clock regs after reading/writing clockless registers*/ + nm_bus_reset(); + +_WAKE_EXIT: + return ret; +} +sint8 cpu_halt(void) +{ + sint8 ret; + uint32 reg = 0; + ret = nm_read_reg_with_ret(0x1118, ®); + reg |= (1 << 0); + ret += nm_write_reg(0x1118, reg); + ret += nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); + if ((reg & (1ul << 10)) == (1ul << 10)) { + reg &= ~(1ul << 10); + ret += nm_write_reg(NMI_GLB_RESET_0, reg); + ret += nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); + } + return ret; +} +sint8 chip_reset_and_cpu_halt(void) +{ + sint8 ret = M2M_SUCCESS; + + /*Wakeup needed only for I2C interface*/ + ret = chip_wake(); + if(ret != M2M_SUCCESS) goto ERR1; + /*Reset and CPU halt need for no wait board only*/ + ret = chip_reset(); + if(ret != M2M_SUCCESS) goto ERR1; + ret = cpu_halt(); + if(ret != M2M_SUCCESS) goto ERR1; +ERR1: + return ret; +} +sint8 chip_reset(void) +{ + sint8 ret = M2M_SUCCESS; + ret = nm_write_reg(NMI_GLB_RESET_0, 0); + nm_bsp_sleep(50); + return ret; +} + +sint8 wait_for_bootrom(uint8 arg) +{ + sint8 ret = M2M_SUCCESS; + uint32 reg = 0, cnt = 0; + uint32 u32GpReg1 = 0; + uint32 u32DriverVerInfo = M2M_MAKE_VERSION_INFO(M2M_RELEASE_VERSION_MAJOR_NO,\ + M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO,\ + M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO,\ + M2M_RELEASE_VERSION_PATCH_NO); + + + reg = 0; + while(1) { + reg = nm_read_reg(0x1014); /* wait for efuse loading done */ + if (reg & 0x80000000) { + break; + } + nm_bsp_sleep(1); /* TODO: Why bus error if this delay is not here. */ + } + reg = nm_read_reg(M2M_WAIT_FOR_HOST_REG); + reg &= 0x1; + + /* check if waiting for the host will be skipped or not */ + if(reg == 0) + { + reg = 0; + while(reg != M2M_FINISH_BOOT_ROM) + { + nm_bsp_sleep(1); + reg = nm_read_reg(BOOTROM_REG); + + if(++cnt > TIMEOUT) + { + M2M_DBG("failed to load firmware from flash.\n"); + ret = M2M_ERR_INIT; + goto ERR2; + } + } + } + + if(M2M_WIFI_MODE_ATE_HIGH == arg) { + nm_write_reg(NMI_REV_REG, M2M_ATE_FW_START_VALUE); + nm_write_reg(NMI_STATE_REG, NBIT20); + }else if(M2M_WIFI_MODE_ATE_LOW == arg) { + nm_write_reg(NMI_REV_REG, M2M_ATE_FW_START_VALUE); + nm_write_reg(NMI_STATE_REG, 0); + }else if(M2M_WIFI_MODE_ETHERNET == arg){ + u32GpReg1 = rHAVE_ETHERNET_MODE_BIT; + nm_write_reg(NMI_STATE_REG, u32DriverVerInfo); + } else { + /*bypass this step*/ + nm_write_reg(NMI_STATE_REG, u32DriverVerInfo); + } + + if(REV(nmi_get_chipid()) >= REV_3A0){ + chip_apply_conf(u32GpReg1 | rHAVE_USE_PMU_BIT); + } else { + chip_apply_conf(u32GpReg1); + } + M2M_INFO("DriverVerInfo: 0x%08lx\n",u32DriverVerInfo); + + nm_write_reg(BOOTROM_REG,M2M_START_FIRMWARE); + +#ifdef __ROM_TEST__ + rom_test(); +#endif /* __ROM_TEST__ */ + +ERR2: + return ret; +} + +sint8 wait_for_firmware_start(uint8 arg) +{ + sint8 ret = M2M_SUCCESS; + uint32 reg = 0, cnt = 0; + uint32 u32Timeout = TIMEOUT; + volatile uint32 regAddress = NMI_STATE_REG; + volatile uint32 checkValue = M2M_FINISH_INIT_STATE; + + if((M2M_WIFI_MODE_ATE_HIGH == arg)||(M2M_WIFI_MODE_ATE_LOW == arg)) { + regAddress = NMI_REV_REG; + checkValue = M2M_ATE_FW_IS_UP_VALUE; + } else { + /*bypass this step*/ + } + + + while (checkValue != reg) + { + nm_bsp_sleep(2); /* TODO: Why bus error if this delay is not here. */ + M2M_DBG("%x %x %x\n",(unsigned int)nm_read_reg(0x108c),(unsigned int)nm_read_reg(0x108c),(unsigned int)nm_read_reg(0x14A0)); + reg = nm_read_reg(regAddress); + if(++cnt >= u32Timeout) + { + M2M_DBG("Time out for wait firmware Run\n"); + ret = M2M_ERR_INIT; + goto ERR; + } + } + if(M2M_FINISH_INIT_STATE == checkValue) + { + nm_write_reg(NMI_STATE_REG, 0); + } +ERR: + return ret; +} + +sint8 chip_deinit(void) +{ + uint32 reg = 0; + sint8 ret; + + /** + stop the firmware, need a re-download + **/ + ret = nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); + if (ret != M2M_SUCCESS) { + M2M_ERR("failed to de-initialize\n"); + goto ERR1; + } + reg &= ~(1 << 10); + ret = nm_write_reg(NMI_GLB_RESET_0, reg); + if (ret != M2M_SUCCESS) { + M2M_ERR("failed to de-initialize\n"); + goto ERR1; + } + +ERR1: + return ret; +} + +#ifdef CONF_PERIPH + +sint8 set_gpio_dir(uint8 gpio, uint8 dir) +{ + uint32 val32; + sint8 ret; + + ret = nm_read_reg_with_ret(0x20108, &val32); + if(ret != M2M_SUCCESS) goto _EXIT; + + if(dir) { + val32 |= (1ul << gpio); + } else { + val32 &= ~(1ul << gpio); + } + + ret = nm_write_reg(0x20108, val32); + +_EXIT: + return ret; +} +sint8 set_gpio_val(uint8 gpio, uint8 val) +{ + uint32 val32; + sint8 ret; + + ret = nm_read_reg_with_ret(0x20100, &val32); + if(ret != M2M_SUCCESS) goto _EXIT; + + if(val) { + val32 |= (1ul << gpio); + } else { + val32 &= ~(1ul << gpio); + } + + ret = nm_write_reg(0x20100, val32); + +_EXIT: + return ret; +} + +sint8 get_gpio_val(uint8 gpio, uint8* val) +{ + uint32 val32; + sint8 ret; + + ret = nm_read_reg_with_ret(0x20104, &val32); + if(ret != M2M_SUCCESS) goto _EXIT; + + *val = (uint8)((val32 >> gpio) & 0x01); + +_EXIT: + return ret; +} + +sint8 pullup_ctrl(uint32 pinmask, uint8 enable) +{ + sint8 s8Ret; + uint32 val32; + s8Ret = nm_read_reg_with_ret(0x142c, &val32); + if(s8Ret != M2M_SUCCESS) { + M2M_ERR("[pullup_ctrl]: failed to read\n"); + goto _EXIT; + } + if(enable) { + val32 &= ~pinmask; + } else { + val32 |= pinmask; + } + s8Ret = nm_write_reg(0x142c, val32); + if(s8Ret != M2M_SUCCESS) { + M2M_ERR("[pullup_ctrl]: failed to write\n"); + goto _EXIT; + } +_EXIT: + return s8Ret; +} +#endif /* CONF_PERIPH */ + +sint8 nmi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid) +{ + sint8 ret; + uint32 u32RegValue; + uint8 mac[6]; + tstrGpRegs strgp = {0}; + + ret = nm_read_reg_with_ret(rNMI_GP_REG_2, &u32RegValue); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; +#ifdef ARDUINO + if (u32RegValue) { + ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; + u32RegValue = strgp.u32Mac_efuse_mib; + } else { + // firmware version 19.3.0 + ret = nm_read_reg_with_ret(rNMI_GP_REG_0, &u32RegValue); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; + } +#else + ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; + u32RegValue = strgp.u32Mac_efuse_mib; +#endif + if(!EFUSED_MAC(u32RegValue)) { + M2M_DBG("Default MAC\n"); + m2m_memset(pu8MacAddr, 0, 6); + goto _EXIT_ERR; + } + + M2M_DBG("OTP MAC\n"); + u32RegValue >>=16; + ret = nm_read_block(u32RegValue|0x30000, mac, 6); + m2m_memcpy(pu8MacAddr,mac,6); + if(pu8IsValid) *pu8IsValid = 1; + return ret; + +_EXIT_ERR: + if(pu8IsValid) *pu8IsValid = 0; + return ret; +} + +sint8 nmi_get_mac_address(uint8 *pu8MacAddr) +{ + sint8 ret; + uint32 u32RegValue; + uint8 mac[6]; + tstrGpRegs strgp = {0}; + + ret = nm_read_reg_with_ret(rNMI_GP_REG_2, &u32RegValue); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; +#ifdef ARDUINO + if (u32RegValue) { + ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; + u32RegValue = strgp.u32Mac_efuse_mib; + } else { + // firmware version 19.3.0 + ret = nm_read_reg_with_ret(rNMI_GP_REG_0, &u32RegValue); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; + } +#else + ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); + if(ret != M2M_SUCCESS) goto _EXIT_ERR; + u32RegValue = strgp.u32Mac_efuse_mib; +#endif + u32RegValue &=0x0000ffff; + ret = nm_read_block(u32RegValue|0x30000, mac, 6); + m2m_memcpy(pu8MacAddr, mac, 6); + + return ret; + +_EXIT_ERR: + return ret; +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmasic.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmasic.h new file mode 100644 index 0000000..84a395b --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmasic.h @@ -0,0 +1,215 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 ASIC specific internal APIs. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +#ifndef _NMASIC_H_ +#define _NMASIC_H_ + +#include "common/include/nm_common.h" + +#define NMI_PERIPH_REG_BASE 0x1000 +#define NMI_CHIPID (NMI_PERIPH_REG_BASE) +#define rNMI_GP_REG_0 (0x149c) +#define rNMI_GP_REG_1 (0x14A0) +#define rNMI_GP_REG_2 (0xc0008) +#define rNMI_GLB_RESET (0x1400) +#define rNMI_BOOT_RESET_MUX (0x1118) +#define NMI_STATE_REG (0x108c) +#define BOOTROM_REG (0xc000c) +#define NMI_REV_REG (0x207ac) /*Also, Used to load ATE firmware from SPI Flash and to ensure that it is running too*/ +#define NMI_REV_REG_ATE (0x1048) /*Revision info register in case of ATE FW*/ +#define M2M_WAIT_FOR_HOST_REG (0x207bc) +#define M2M_FINISH_INIT_STATE 0x02532636UL +#define M2M_FINISH_BOOT_ROM 0x10add09eUL +#define M2M_START_FIRMWARE 0xef522f61UL +#define M2M_START_PS_FIRMWARE 0x94992610UL + +#define M2M_ATE_FW_START_VALUE (0x3C1CD57D) /*Also, Change this value in boot_firmware if it will be changed here*/ +#define M2M_ATE_FW_IS_UP_VALUE (0xD75DC1C3) /*Also, Change this value in ATE (Burst) firmware if it will be changed here*/ + +#define REV_2B0 (0x2B0) +#define REV_B0 (0x2B0) +#define REV_3A0 (0x3A0) +#define GET_CHIPID() nmi_get_chipid() +#define ISNMC1000(id) ((((id) & 0xfffff000) == 0x100000) ? 1 : 0) +#define ISNMC1500(id) ((((id) & 0xfffff000) == 0x150000) ? 1 : 0) +#define ISNMC3000(id) ((((id) & 0xfff00000) == 0x300000) ? 1 : 0) +#define REV(id) (((id) & 0x00000fff )) +#define EFUSED_MAC(value) (value & 0xffff0000) + +#define rHAVE_SDIO_IRQ_GPIO_BIT (NBIT0) +#define rHAVE_USE_PMU_BIT (NBIT1) +#define rHAVE_SLEEP_CLK_SRC_RTC_BIT (NBIT2) +#define rHAVE_SLEEP_CLK_SRC_XO_BIT (NBIT3) +#define rHAVE_EXT_PA_INV_TX_RX (NBIT4) +#define rHAVE_LEGACY_RF_SETTINGS (NBIT5) +#define rHAVE_LOGS_DISABLED_BIT (NBIT6) +#define rHAVE_ETHERNET_MODE_BIT (NBIT7) +#define rHAVE_RESERVED1_BIT (NBIT8) + +typedef struct{ + uint32 u32Mac_efuse_mib; + uint32 u32Firmware_Ota_rev; +}tstrGpRegs; + +#ifdef __cplusplus + extern "C" { +#endif + +/* +* @fn cpu_halt +* @brief +*/ +sint8 cpu_halt(void); +/* +* @fn chip_sleep +* @brief +*/ +sint8 chip_sleep(void); +/* +* @fn chip_wake +* @brief +*/ +sint8 chip_wake(void); +/* +* @fn chip_idle +* @brief +*/ +void chip_idle(void); +/* +* @fn enable_interrupts +* @brief +*/ +sint8 enable_interrupts(void); +/* +* @fn cpu_start +* @brief +*/ +sint8 cpu_start(void); +/* +* @fn nmi_get_chipid +* @brief +*/ +uint32 nmi_get_chipid(void); +/* +* @fn nmi_get_rfrevid +* @brief +*/ +uint32 nmi_get_rfrevid(void); +/* +* @fn restore_pmu_settings_after_global_reset +* @brief +*/ +void restore_pmu_settings_after_global_reset(void); +/* +* @fn nmi_update_pll +* @brief +*/ +void nmi_update_pll(void); +/* +* @fn nmi_set_sys_clk_src_to_xo +* @brief +*/ +void nmi_set_sys_clk_src_to_xo(void); +/* +* @fn chip_reset +* @brief +*/ +sint8 chip_reset(void); +/* +* @fn wait_for_bootrom +* @brief +*/ +sint8 wait_for_bootrom(uint8); +/* +* @fn wait_for_firmware_start +* @brief +*/ +sint8 wait_for_firmware_start(uint8); +/* +* @fn chip_deinit +* @brief +*/ +sint8 chip_deinit(void); +/* +* @fn chip_reset_and_cpu_halt +* @brief +*/ +sint8 chip_reset_and_cpu_halt(void); +/* +* @fn set_gpio_dir +* @brief +*/ +sint8 set_gpio_dir(uint8 gpio, uint8 dir); +/* +* @fn set_gpio_val +* @brief +*/ +sint8 set_gpio_val(uint8 gpio, uint8 val); +/* +* @fn get_gpio_val +* @brief +*/ +sint8 get_gpio_val(uint8 gpio, uint8* val); +/* +* @fn pullup_ctrl +* @brief +*/ +sint8 pullup_ctrl(uint32 pinmask, uint8 enable); +/* +* @fn nmi_get_otp_mac_address +* @brief +*/ +sint8 nmi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); +/* +* @fn nmi_get_mac_address +* @brief +*/ +sint8 nmi_get_mac_address(uint8 *pu8MacAddr); +/* +* @fn chip_apply_conf +* @brief +*/ +sint8 chip_apply_conf(uint32 u32conf); + +#ifdef __cplusplus + } +#endif + +#endif /*_NMASIC_H_*/ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmbus.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmbus.c new file mode 100644 index 0000000..d001d72 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmbus.c @@ -0,0 +1,301 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 bus APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +#ifndef CORTUS_APP + +#include "nmbus.h" +#include "nmi2c.h" +#include "nmspi.h" +#include "nmuart.h" + +#define MAX_TRX_CFG_SZ 8 + +/** +* @fn nm_bus_iface_init +* @brief Initialize bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_bus_iface_init(void *pvInitVal) +{ + sint8 ret = M2M_SUCCESS; + ret = nm_bus_init(pvInitVal); + return ret; +} + +/** +* @fn nm_bus_iface_deinit +* @brief Deinitialize bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Samer Sarhan +* @date 07 April 2014 +* @version 1.0 +*/ +sint8 nm_bus_iface_deinit(void) +{ + sint8 ret = M2M_SUCCESS; + ret = nm_bus_deinit(); + + return ret; +} + +/** +* @fn nm_bus_reset +* @brief reset bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @version 1.0 +*/ +sint8 nm_bus_reset(void) +{ + sint8 ret = M2M_SUCCESS; +#ifdef CONF_WINC_USE_UART +#elif defined (CONF_WINC_USE_SPI) + return nm_spi_reset(); +#elif defined (CONF_WINC_USE_I2C) +#else +#error "Plesae define bus usage" +#endif + + return ret; +} + +/** +* @fn nm_bus_iface_reconfigure +* @brief reconfigure bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Viswanathan Murugesan +* @date 22 Oct 2014 +* @version 1.0 +*/ +sint8 nm_bus_iface_reconfigure(void *ptr) +{ +#ifdef ARDUINO + (void)ptr; // Silence "unused" warning +#endif + sint8 ret = M2M_SUCCESS; +#ifdef CONF_WINC_USE_UART + ret = nm_uart_reconfigure(ptr); +#endif + return ret; +} +/* +* @fn nm_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +uint32 nm_read_reg(uint32 u32Addr) +{ +#ifdef CONF_WINC_USE_UART + return nm_uart_read_reg(u32Addr); +#elif defined (CONF_WINC_USE_SPI) + return nm_spi_read_reg(u32Addr); +#elif defined (CONF_WINC_USE_I2C) + return nm_i2c_read_reg(u32Addr); +#else +#error "Plesae define bus usage" +#endif + +} + +/* +* @fn nm_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) +{ +#ifdef CONF_WINC_USE_UART + return nm_uart_read_reg_with_ret(u32Addr,pu32RetVal); +#elif defined (CONF_WINC_USE_SPI) + return nm_spi_read_reg_with_ret(u32Addr,pu32RetVal); +#elif defined (CONF_WINC_USE_I2C) + return nm_i2c_read_reg_with_ret(u32Addr,pu32RetVal); +#else +#error "Plesae define bus usage" +#endif +} + +/* +* @fn nm_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_write_reg(uint32 u32Addr, uint32 u32Val) +{ +#ifdef CONF_WINC_USE_UART + return nm_uart_write_reg(u32Addr,u32Val); +#elif defined (CONF_WINC_USE_SPI) + return nm_spi_write_reg(u32Addr,u32Val); +#elif defined (CONF_WINC_USE_I2C) + return nm_i2c_write_reg(u32Addr,u32Val); +#else +#error "Plesae define bus usage" +#endif +} + +static sint8 p_nm_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) +{ +#ifdef CONF_WINC_USE_UART + return nm_uart_read_block(u32Addr,puBuf,u16Sz); +#elif defined (CONF_WINC_USE_SPI) + return nm_spi_read_block(u32Addr,puBuf,u16Sz); +#elif defined (CONF_WINC_USE_I2C) + return nm_i2c_read_block(u32Addr,puBuf,u16Sz); +#else +#error "Plesae define bus usage" +#endif + +} +/* +* @fn nm_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u32Sz +* Number of bytes to read. The buffer size must be >= u32Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_read_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz) +{ + uint16 u16MaxTrxSz = egstrNmBusCapabilities.u16MaxTrxSz - MAX_TRX_CFG_SZ; + uint32 off = 0; + sint8 s8Ret = M2M_SUCCESS; + + for(;;) + { + if(u32Sz <= u16MaxTrxSz) + { + s8Ret += p_nm_read_block(u32Addr, &puBuf[off], (uint16)u32Sz); + break; + } + else + { + s8Ret += p_nm_read_block(u32Addr, &puBuf[off], u16MaxTrxSz); + if(M2M_SUCCESS != s8Ret) break; + u32Sz -= u16MaxTrxSz; + off += u16MaxTrxSz; + u32Addr += u16MaxTrxSz; + } + } + + return s8Ret; +} + +static sint8 p_nm_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) +{ +#ifdef CONF_WINC_USE_UART + return nm_uart_write_block(u32Addr,puBuf,u16Sz); +#elif defined (CONF_WINC_USE_SPI) + return nm_spi_write_block(u32Addr,puBuf,u16Sz); +#elif defined (CONF_WINC_USE_I2C) + return nm_i2c_write_block(u32Addr,puBuf,u16Sz); +#else +#error "Plesae define bus usage" +#endif + +} +/** +* @fn nm_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u32Sz +* Number of bytes to write. The buffer size must be >= u32Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_write_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz) +{ + uint16 u16MaxTrxSz = egstrNmBusCapabilities.u16MaxTrxSz - MAX_TRX_CFG_SZ; + uint32 off = 0; + sint8 s8Ret = M2M_SUCCESS; + + for(;;) + { + if(u32Sz <= u16MaxTrxSz) + { + s8Ret += p_nm_write_block(u32Addr, &puBuf[off], (uint16)u32Sz); + break; + } + else + { + s8Ret += p_nm_write_block(u32Addr, &puBuf[off], u16MaxTrxSz); + if(M2M_SUCCESS != s8Ret) break; + u32Sz -= u16MaxTrxSz; + off += u16MaxTrxSz; + u32Addr += u16MaxTrxSz; + } + } + + return s8Ret; +} + +#endif + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmbus.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmbus.h new file mode 100644 index 0000000..2ea7838 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmbus.h @@ -0,0 +1,147 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 bus APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NMBUS_H_ +#define _NMBUS_H_ + +#include "common/include/nm_common.h" +#include "bus_wrapper/include/nm_bus_wrapper.h" + + + +#ifdef __cplusplus +extern "C"{ +#endif +/** +* @fn nm_bus_iface_init +* @brief Initialize bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_bus_iface_init(void *); + + +/** +* @fn nm_bus_iface_deinit +* @brief Deinitialize bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_bus_iface_deinit(void); + +/** +* @fn nm_bus_reset +* @brief reset bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @version 1.0 +*/ +sint8 nm_bus_reset(void); + +/** +* @fn nm_bus_iface_reconfigure +* @brief reconfigure bus interface +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_bus_iface_reconfigure(void *ptr); + +/** +* @fn nm_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +*/ +uint32 nm_read_reg(uint32 u32Addr); + +/** +* @fn nm_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); + +/** +* @fn nm_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_write_reg(uint32 u32Addr, uint32 u32Val); + +/** +* @fn nm_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u32Sz +* Number of bytes to read. The buffer size must be >= u32Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_read_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz); + +/** +* @fn nm_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u32Sz +* Number of bytes to write. The buffer size must be >= u32Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_write_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz); + + + + +#ifdef __cplusplus +} +#endif + +#endif /* _NMBUS_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmdrv.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmdrv.c new file mode 100644 index 0000000..b3f2a8a --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmdrv.c @@ -0,0 +1,402 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 M2M driver APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "common/include/nm_common.h" +#include "driver/source/nmbus.h" +#include "bsp/include/nm_bsp.h" +#include "driver/source/nmdrv.h" +#include "driver/source/nmasic.h" +#include "driver/include/m2m_types.h" +#include "spi_flash/include/spi_flash.h" + +#ifdef CONF_WINC_USE_SPI +#include "driver/source/nmspi.h" +#endif + +#ifdef ARDUINO + uint32 nmdrv_firm_ver = 0; +#endif + +/** +* @fn nm_get_firmware_info(tstrM2mRev* M2mRev) +* @brief Get Firmware version info +* @param [out] M2mRev +* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters +* @version 1.0 +*/ +sint8 nm_get_firmware_info(tstrM2mRev* M2mRev) +{ + uint16 curr_drv_ver, min_req_drv_ver,curr_firm_ver; + uint32 reg = 0; + sint8 ret = M2M_SUCCESS; + + ret = nm_read_reg_with_ret(NMI_REV_REG, ®); + //In case the Firmware running is ATE fw + if(M2M_ATE_FW_IS_UP_VALUE == reg) + { + //Read FW info again from the register specified for ATE + ret = nm_read_reg_with_ret(NMI_REV_REG_ATE, ®); + } + M2mRev->u8DriverMajor = M2M_GET_DRV_MAJOR(reg); + M2mRev->u8DriverMinor = M2M_GET_DRV_MINOR(reg); + M2mRev->u8DriverPatch = M2M_GET_DRV_PATCH(reg); + M2mRev->u8FirmwareMajor = M2M_GET_FW_MAJOR(reg); + M2mRev->u8FirmwareMinor = M2M_GET_FW_MINOR(reg); + M2mRev->u8FirmwarePatch = M2M_GET_FW_PATCH(reg); + M2mRev->u32Chipid = nmi_get_chipid(); + M2mRev->u16FirmwareSvnNum = 0; + + curr_firm_ver = M2M_MAKE_VERSION(M2mRev->u8FirmwareMajor, M2mRev->u8FirmwareMinor,M2mRev->u8FirmwarePatch); +#ifdef ARDUINO + nmdrv_firm_ver = curr_firm_ver; +#endif + curr_drv_ver = M2M_MAKE_VERSION(M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); + min_req_drv_ver = M2M_MAKE_VERSION(M2mRev->u8DriverMajor, M2mRev->u8DriverMinor,M2mRev->u8DriverPatch); + if(curr_drv_ver < min_req_drv_ver) { + /*The current driver version should be larger or equal + than the min driver that the current firmware support */ + ret = M2M_ERR_FW_VER_MISMATCH; + } + if(curr_drv_ver > curr_firm_ver) { + /*The current driver should be equal or less than the firmware version*/ + ret = M2M_ERR_FW_VER_MISMATCH; + } + return ret; +} +/** +* @fn nm_get_firmware_info(tstrM2mRev* M2mRev) +* @brief Get Firmware version info +* @param [out] M2mRev +* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters +* @version 1.0 +*/ +sint8 nm_get_firmware_full_info(tstrM2mRev* pstrRev) +{ + uint16 curr_drv_ver, min_req_drv_ver,curr_firm_ver; + uint32 reg = 0; + sint8 ret = M2M_SUCCESS; + tstrGpRegs strgp = {0}; + if (pstrRev != NULL) + { + m2m_memset((uint8*)pstrRev,0,sizeof(tstrM2mRev)); + ret = nm_read_reg_with_ret(rNMI_GP_REG_2, ®); + if(ret == M2M_SUCCESS) + { + if(reg != 0) + { + ret = nm_read_block(reg|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); + if(ret == M2M_SUCCESS) + { + reg = strgp.u32Firmware_Ota_rev; + reg &= 0x0000ffff; + if(reg != 0) + { + ret = nm_read_block(reg|0x30000,(uint8*)pstrRev,sizeof(tstrM2mRev)); + if(ret == M2M_SUCCESS) + { + curr_firm_ver = M2M_MAKE_VERSION(pstrRev->u8FirmwareMajor, pstrRev->u8FirmwareMinor,pstrRev->u8FirmwarePatch); +#ifdef ARDUINO + nmdrv_firm_ver = curr_firm_ver; +#endif + curr_drv_ver = M2M_MAKE_VERSION(M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); + min_req_drv_ver = M2M_MAKE_VERSION(pstrRev->u8DriverMajor, pstrRev->u8DriverMinor,pstrRev->u8DriverPatch); + if((curr_firm_ver == 0)||(min_req_drv_ver == 0)||(min_req_drv_ver == 0)){ + ret = M2M_ERR_FAIL; + goto EXIT; + } + if(curr_drv_ver < min_req_drv_ver) { + /*The current driver version should be larger or equal + than the min driver that the current firmware support */ + ret = M2M_ERR_FW_VER_MISMATCH; + goto EXIT; + } + if(curr_drv_ver > curr_firm_ver) { + /*The current driver should be equal or less than the firmware version*/ + ret = M2M_ERR_FW_VER_MISMATCH; + goto EXIT; + } + } + }else { + ret = M2M_ERR_FAIL; + } + } + }else{ + ret = M2M_ERR_FAIL; + } + } + } +EXIT: + return ret; +} +/** +* @fn nm_get_ota_firmware_info(tstrM2mRev* pstrRev) +* @brief Get Firmware version info +* @param [out] M2mRev +* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters + +* @version 1.0 +*/ +sint8 nm_get_ota_firmware_info(tstrM2mRev* pstrRev) +{ + uint16 curr_drv_ver, min_req_drv_ver,curr_firm_ver; + uint32 reg = 0; + sint8 ret; + tstrGpRegs strgp = {0}; + + if (pstrRev != NULL) + { + m2m_memset((uint8*)pstrRev,0,sizeof(tstrM2mRev)); + ret = nm_read_reg_with_ret(rNMI_GP_REG_2, ®); + if(ret == M2M_SUCCESS) + { + if(reg != 0) + { + ret = nm_read_block(reg|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); + if(ret == M2M_SUCCESS) + { + reg = strgp.u32Firmware_Ota_rev; + reg >>= 16; + if(reg != 0) + { + ret = nm_read_block(reg|0x30000,(uint8*)pstrRev,sizeof(tstrM2mRev)); + if(ret == M2M_SUCCESS) + { + curr_firm_ver = M2M_MAKE_VERSION(pstrRev->u8FirmwareMajor, pstrRev->u8FirmwareMinor,pstrRev->u8FirmwarePatch); + curr_drv_ver = M2M_MAKE_VERSION(M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); + min_req_drv_ver = M2M_MAKE_VERSION(pstrRev->u8DriverMajor, pstrRev->u8DriverMinor,pstrRev->u8DriverPatch); + if((curr_firm_ver == 0)||(min_req_drv_ver == 0)||(min_req_drv_ver == 0)){ + ret = M2M_ERR_FAIL; + goto EXIT; + } + if(curr_drv_ver < min_req_drv_ver) { + /*The current driver version should be larger or equal + than the min driver that the current firmware support */ + ret = M2M_ERR_FW_VER_MISMATCH; + } + if(curr_drv_ver > curr_firm_ver) { + /*The current driver should be equal or less than the firmware version*/ + ret = M2M_ERR_FW_VER_MISMATCH; + } + } + }else{ + ret = M2M_ERR_INVALID; + } + } + }else{ + ret = M2M_ERR_FAIL; + } + } + } else { + ret = M2M_ERR_INVALID_ARG; + } +EXIT: + return ret; +} + + + +/* +* @fn nm_drv_init_download_mode +* @brief Initialize NMC1000 driver +* @return M2M_SUCCESS in case of success and Negative error code in case of failure +* @param [in] arg +* Generic argument +* @author Viswanathan Murugesan +* @date 10 Oct 2014 +* @version 1.0 +*/ +sint8 nm_drv_init_download_mode() +{ + sint8 ret = M2M_SUCCESS; + + ret = nm_bus_iface_init(NULL); + if (M2M_SUCCESS != ret) { + M2M_ERR("[nmi start]: fail init bus\n"); + goto ERR1; + } + + /** + TODO:reset the chip and halt the cpu in case of no wait efuse is set (add the no wait effuse check) + */ + if(!ISNMC3000(GET_CHIPID())) + { + /*Execuate that function only for 1500A/B, no room in 3000, but it may be needed in 3400 no wait*/ + chip_reset_and_cpu_halt(); + } + +#ifdef CONF_WINC_USE_SPI + /* Must do this after global reset to set SPI data packet size. */ + nm_spi_init(); +#endif + + M2M_INFO("Chip ID %lx\n", nmi_get_chipid()); + + /*disable all interrupt in ROM (to disable uart) in 2b0 chip*/ + nm_write_reg(0x20300,0); + +ERR1: + return ret; +} + +/* +* @fn nm_drv_init +* @brief Initialize NMC1000 driver +* @return M2M_SUCCESS in case of success and Negative error code in case of failure +* @param [in] arg +* Generic argument +* @author M. Abdelmawla +* @date 15 July 2012 +* @version 1.0 +*/ +sint8 nm_drv_init(void * arg) +{ + sint8 ret = M2M_SUCCESS; + uint8 u8Mode; + + if(NULL != arg) { + u8Mode = *((uint8 *)arg); + if((u8Mode < M2M_WIFI_MODE_NORMAL)||(u8Mode >= M2M_WIFI_MODE_MAX)) { + u8Mode = M2M_WIFI_MODE_NORMAL; + } + } else { + u8Mode = M2M_WIFI_MODE_NORMAL; + } + + ret = nm_bus_iface_init(NULL); + if (M2M_SUCCESS != ret) { + M2M_ERR("[nmi start]: fail init bus\n"); + goto ERR1; + } + +#ifdef BUS_ONLY + return; +#endif + + +#ifdef NO_HW_CHIP_EN + ret = chip_wake(); + if (M2M_SUCCESS != ret) { + M2M_ERR("[nmi start]: fail chip_wakeup\n"); + goto ERR2; + } + /** + Go... + **/ + ret = chip_reset(); + if (M2M_SUCCESS != ret) { + goto ERR2; + } +#endif + M2M_INFO("Chip ID %lx\n", nmi_get_chipid()); +#ifdef CONF_WINC_USE_SPI + /* Must do this after global reset to set SPI data packet size. */ + nm_spi_init(); +#endif + ret = wait_for_bootrom(u8Mode); + if (M2M_SUCCESS != ret) { + goto ERR2; + } + + ret = wait_for_firmware_start(u8Mode); + if (M2M_SUCCESS != ret) { + goto ERR2; + } + + if((M2M_WIFI_MODE_ATE_HIGH == u8Mode)||(M2M_WIFI_MODE_ATE_LOW == u8Mode)) { + goto ERR1; + } else { + /*continue running*/ + } + + ret = enable_interrupts(); + if (M2M_SUCCESS != ret) { + M2M_ERR("failed to enable interrupts..\n"); + goto ERR2; + } + return ret; +ERR2: + nm_bus_iface_deinit(); +ERR1: + return ret; +} + +/* +* @fn nm_drv_deinit +* @brief Deinitialize NMC1000 driver +* @author M. Abdelmawla +* @date 17 July 2012 +* @version 1.0 +*/ +sint8 nm_drv_deinit(void * arg) +{ +#ifdef ARDUINO + (void)arg; // Silence "unused" warning +#endif + sint8 ret; + + ret = chip_deinit(); + if (M2M_SUCCESS != ret) { + M2M_ERR("[nmi stop]: chip_deinit fail\n"); + goto ERR1; + } + + /* Disable SPI flash to save power when the chip is off */ + ret = spi_flash_enable(0); + if (M2M_SUCCESS != ret) { + M2M_ERR("[nmi stop]: SPI flash disable fail\n"); + goto ERR1; + } + + ret = nm_bus_iface_deinit(); + if (M2M_SUCCESS != ret) { + M2M_ERR("[nmi stop]: fail init bus\n"); + goto ERR1; + } +#ifdef CONF_WINC_USE_SPI + /* Must do this after global reset to set SPI data packet size. */ + nm_spi_deinit(); +#endif + +ERR1: + return ret; +} + + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmdrv.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmdrv.h new file mode 100644 index 0000000..6a416b2 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmdrv.h @@ -0,0 +1,138 @@ +/** + * + * \file + * + * \brief This module contains NMC1500 M2M driver APIs declarations. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NMDRV_H_ +#define _NMDRV_H_ + +#include "common/include/nm_common.h" + +/** +* @struct tstrM2mRev +* @brief Structure holding firmware version parameters and build date/time +*/ +typedef struct { + uint32 u32Chipid; /* HW revision which will be basically the chip ID */ + uint8 u8FirmwareMajor; /* Version Major Number which represents the official release base */ + uint8 u8FirmwareMinor; /* Version Minor Number which represents the engineering release base */ + uint8 u8FirmwarePatch; /* Version pathc Number which represents the pathces release base */ + uint8 u8DriverMajor; /* Version Major Number which represents the official release base */ + uint8 u8DriverMinor; /* Version Minor Number which represents the engineering release base */ + uint8 u8DriverPatch; /* Version Patch Number which represents the pathces release base */ + uint8 BuildDate[sizeof(__DATE__)]; + uint8 BuildTime[sizeof(__TIME__)]; + uint8 _PAD8_; + uint16 u16FirmwareSvnNum; + uint16 _PAD16_[2]; +} tstrM2mRev; + +/** +* @struct tstrM2mBinaryHeader +* @brief Structure holding compatibility version info for firmware binaries +*/ +typedef struct { + tstrM2mRev binVerInfo; + uint32 flashOffset; + uint32 payloadSize; +} tstrM2mBinaryHeader; + +#ifdef __cplusplus + extern "C" { + #endif +/** +* @fn nm_get_firmware_info(tstrM2mRev* M2mRev) +* @brief Get Firmware version info +* @param [out] M2mRev +* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters +* @version 1.0 +*/ +sint8 nm_get_firmware_info(tstrM2mRev* M2mRev); +/** +* @fn nm_get_firmware_full_info(tstrM2mRev* pstrRev) +* @brief Get Firmware version info +* @param [out] M2mRev +* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters +* @version 1.0 +*/ +sint8 nm_get_firmware_full_info(tstrM2mRev* pstrRev); +/** +* @fn nm_get_ota_firmware_info(tstrM2mRev* pstrRev) +* @brief Get Firmware version info +* @param [out] M2mRev +* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters + +* @version 1.0 +*/ +sint8 nm_get_ota_firmware_info(tstrM2mRev* pstrRev); +/* +* @fn nm_drv_init +* @brief Initialize NMC1000 driver +* @return ZERO in case of success and Negative error code in case of failure +*/ +sint8 nm_drv_init_download_mode(void); + +/* +* @fn nm_drv_init +* @brief Initialize NMC1000 driver +* @return M2M_SUCCESS in case of success and Negative error code in case of failure +* @param [in] arg +* Generic argument TBD +* @return ZERO in case of success and Negative error code in case of failure + +*/ +sint8 nm_drv_init(void * arg); + +/** +* @fn nm_drv_deinit +* @brief Deinitialize NMC1000 driver +* @author M. Abdelmawla +* @param [in] arg +* Generic argument TBD +* @return ZERO in case of success and Negative error code in case of failure +*/ +sint8 nm_drv_deinit(void * arg); + +#ifdef __cplusplus + } + #endif + +#endif /*_NMDRV_H_*/ + + diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmi2c.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmi2c.c new file mode 100644 index 0000000..e11d2f7 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmi2c.c @@ -0,0 +1,269 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 I2C protocol bus APIs implementation. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "common/include/nm_common.h" + +#ifdef CONF_WINC_USE_I2C + +#include "nmi2c.h" +#include "bus_wrapper/include/nm_bus_wrapper.h" + + +/* +* @fn nm_i2c_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ + sint8 nm_i2c_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) +{ + uint8 b[6]; + uint8 rsz; + tstrNmI2cDefault strI2c; + sint8 s8Ret = M2M_SUCCESS; + + if(u32Addr < 0xff) { /* clockless i2c */ + b[0] = 0x09; + b[1] = (uint8)(u32Addr); + rsz = 1; + strI2c.u16Sz = 2; + } else { + b[0] = 0x80; + b[1] = (uint8)(u32Addr >> 24); + b[2] = (uint8)(u32Addr >> 16); + b[3] = (uint8)(u32Addr >> 8); + b[4] = (uint8)(u32Addr); + b[5] = 0x04; + rsz = 4; + strI2c.u16Sz = 6; + } + + strI2c.pu8Buf = b; + + if(M2M_SUCCESS == nm_bus_ioctl(NM_BUS_IOCTL_W, &strI2c)) + { + strI2c.u16Sz = rsz; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strI2c)) + { + //M2M_ERR("read error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + M2M_ERR("failed to send cfg bytes\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + + if (rsz == 1) { + *pu32RetVal = b[0]; + } else { + *pu32RetVal = b[0] | ((uint32)b[1] << 8) | ((uint32)b[2] << 16) | ((uint32)b[3] << 24); + } + return s8Ret; +} + +/* +* @fn nm_i2c_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +uint32 nm_i2c_read_reg(uint32 u32Addr) +{ + uint32 val; + nm_i2c_read_reg_with_ret(u32Addr, &val); + return val; +} + +/* +* @fn nm_i2c_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_i2c_write_reg(uint32 u32Addr, uint32 u32Val) +{ + tstrNmI2cDefault strI2c; + uint8 b[16]; + sint8 s8Ret = M2M_SUCCESS; + + if(u32Addr < 0xff) { /* clockless i2c */ + b[0] = 0x19; + b[1] = (uint8)(u32Addr); + b[2] = (uint8)(u32Val); + strI2c.u16Sz = 3; + } else { + b[0] = 0x90; + b[1] = (uint8)(u32Addr >> 24); + b[2] = (uint8)(u32Addr >> 16); + b[3] = (uint8)(u32Addr >> 8); + b[4] = (uint8)u32Addr; + b[5] = 0x04; + b[6] = (uint8)u32Val; + b[7] = (uint8)(u32Val >> 8); + b[8] = (uint8)(u32Val >> 16); + b[9] = (uint8)(u32Val >> 24); + strI2c.u16Sz = 10; + } + + strI2c.pu8Buf = b; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strI2c)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + + return s8Ret; +} + +/* +* @fn nm_i2c_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u16Sz +* Number of bytes to read. The buffer size must be >= u16Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_i2c_read_block(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz) +{ + tstrNmI2cDefault strI2c; + uint8 au8Buf[7]; + sint8 s8Ret = M2M_SUCCESS; + + au8Buf[0] = 0x02; + au8Buf[1] = (uint8)(u32Addr >> 24); + au8Buf[2] = (uint8)(u32Addr >> 16); + au8Buf[3] = (uint8)(u32Addr >> 8); + au8Buf[4] = (uint8)(u32Addr >> 0); + au8Buf[5] = (uint8)(u16Sz >> 8); + au8Buf[6] = (uint8)(u16Sz); + + strI2c.pu8Buf = au8Buf; + strI2c.u16Sz = sizeof(au8Buf); + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strI2c)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + else + { + strI2c.pu8Buf = pu8Buf; + strI2c.u16Sz = u16Sz; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strI2c)) + { + M2M_ERR("read error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + + return s8Ret; +} + +/* +* @fn nm_i2c_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u16Sz +* Number of bytes to write. The buffer size must be >= u16Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_i2c_write_block(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz) +{ + uint8 au8Buf[7]; + tstrNmI2cSpecial strI2c; + sint8 s8Ret = M2M_SUCCESS; + + au8Buf[0] = 0x12; + au8Buf[1] = (uint8)(u32Addr >> 24); + au8Buf[2] = (uint8)(u32Addr >> 16); + au8Buf[3] = (uint8)(u32Addr >> 8); + au8Buf[4] = (uint8)(u32Addr); + au8Buf[5] = (uint8)(u16Sz >> 8); + au8Buf[6] = (uint8)(u16Sz); + + strI2c.pu8Buf1 = au8Buf; + strI2c.pu8Buf2 = pu8Buf; + strI2c.u16Sz1 = sizeof(au8Buf); + strI2c.u16Sz2 = u16Sz; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W_SPECIAL, &strI2c)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + + return s8Ret; +} + +#endif +/* EOF */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmi2c.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmi2c.h new file mode 100644 index 0000000..fea85e6 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmi2c.h @@ -0,0 +1,104 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 I2C protocol bus APIs implementation. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NMI2C_H_ +#define _NMI2C_H_ + +#include "common/include/nm_common.h" + +/** +* @fn nm_i2c_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +*/ +uint32 nm_i2c_read_reg(uint32 u32Addr); + +/** +* @fn nm_i2c_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_i2c_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); + +/** +* @fn nm_i2c_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_i2c_write_reg(uint32 u32Addr, uint32 u32Val); + +/** +* @fn nm_i2c_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u16Sz +* Number of bytes to read. The buffer size must be >= u16Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_i2c_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); + +/** +* @fn nm_i2c_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u16Sz +* Number of bytes to write. The buffer size must be >= u16Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_i2c_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); + +#endif /* _NMI2C_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmspi.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmspi.c new file mode 100644 index 0000000..9483ab7 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmspi.c @@ -0,0 +1,1401 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 SPI protocol bus APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +#include "common/include/nm_common.h" + +#ifdef CONF_WINC_USE_SPI + +#define USE_OLD_SPI_SW + +#include "bus_wrapper/include/nm_bus_wrapper.h" +#include "nmspi.h" + +#define NMI_PERIPH_REG_BASE 0x1000 +#define NMI_INTR_REG_BASE (NMI_PERIPH_REG_BASE+0xa00) +#define NMI_CHIPID (NMI_PERIPH_REG_BASE) +#define NMI_PIN_MUX_0 (NMI_PERIPH_REG_BASE + 0x408) +#define NMI_INTR_ENABLE (NMI_INTR_REG_BASE) + +#define NMI_SPI_REG_BASE 0xe800 +#define NMI_SPI_CTL (NMI_SPI_REG_BASE) +#define NMI_SPI_MASTER_DMA_ADDR (NMI_SPI_REG_BASE+0x4) +#define NMI_SPI_MASTER_DMA_COUNT (NMI_SPI_REG_BASE+0x8) +#define NMI_SPI_SLAVE_DMA_ADDR (NMI_SPI_REG_BASE+0xc) +#define NMI_SPI_SLAVE_DMA_COUNT (NMI_SPI_REG_BASE+0x10) +#define NMI_SPI_TX_MODE (NMI_SPI_REG_BASE+0x20) +#define NMI_SPI_PROTOCOL_CONFIG (NMI_SPI_REG_BASE+0x24) +#define NMI_SPI_INTR_CTL (NMI_SPI_REG_BASE+0x2c) +#define NMI_SPI_MISC_CTRL (NMI_SPI_REG_BASE+0x48) + +#define NMI_SPI_PROTOCOL_OFFSET (NMI_SPI_PROTOCOL_CONFIG-NMI_SPI_REG_BASE) + +#define SPI_BASE NMI_SPI_REG_BASE + +#define CMD_DMA_WRITE 0xc1 +#define CMD_DMA_READ 0xc2 +#define CMD_INTERNAL_WRITE 0xc3 +#define CMD_INTERNAL_READ 0xc4 +#define CMD_TERMINATE 0xc5 +#define CMD_REPEAT 0xc6 +#define CMD_DMA_EXT_WRITE 0xc7 +#define CMD_DMA_EXT_READ 0xc8 +#define CMD_SINGLE_WRITE 0xc9 +#define CMD_SINGLE_READ 0xca +#define CMD_RESET 0xcf + +#define N_OK 1 +#define N_FAIL 0 +#define N_RESET -1 +#define N_RETRY -2 + +#define SPI_RESP_RETRY_COUNT (10) +#define SPI_RETRY_COUNT (10) +#define DATA_PKT_SZ_256 256 +#define DATA_PKT_SZ_512 512 +#define DATA_PKT_SZ_1K 1024 +#define DATA_PKT_SZ_4K (4 * 1024) +#define DATA_PKT_SZ_8K (8 * 1024) +#define DATA_PKT_SZ DATA_PKT_SZ_8K + +static uint8 gu8Crc_off = 0; + +static sint8 nmi_spi_read(uint8* b, uint16 sz) +{ + tstrNmSpiRw spi; + spi.pu8InBuf = NULL; + spi.pu8OutBuf = b; + spi.u16Sz = sz; + return nm_bus_ioctl(NM_BUS_IOCTL_RW, &spi); +} + +static sint8 nmi_spi_write(uint8* b, uint16 sz) +{ + tstrNmSpiRw spi; + spi.pu8InBuf = b; + spi.pu8OutBuf = NULL; + spi.u16Sz = sz; + return nm_bus_ioctl(NM_BUS_IOCTL_RW, &spi); +} +#ifndef USE_OLD_SPI_SW +static sint8 nmi_spi_rw(uint8 *bin,uint8* bout,uint16 sz) +{ + tstrNmSpiRw spi; + spi.pu8InBuf = bin; + spi.pu8OutBuf = bout; + spi.u16Sz = sz; + return nm_bus_ioctl(NM_BUS_IOCTL_RW, &spi); +} +#endif +/******************************************** + + Crc7 + +********************************************/ +#if (defined ARDUINO_ARCH_AVR) +#include +static PROGMEM const uint8 crc7_syndrome_table[256] = { +#else +static const uint8 crc7_syndrome_table[256] = { +#endif + 0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f, + 0x48, 0x41, 0x5a, 0x53, 0x6c, 0x65, 0x7e, 0x77, + 0x19, 0x10, 0x0b, 0x02, 0x3d, 0x34, 0x2f, 0x26, + 0x51, 0x58, 0x43, 0x4a, 0x75, 0x7c, 0x67, 0x6e, + 0x32, 0x3b, 0x20, 0x29, 0x16, 0x1f, 0x04, 0x0d, + 0x7a, 0x73, 0x68, 0x61, 0x5e, 0x57, 0x4c, 0x45, + 0x2b, 0x22, 0x39, 0x30, 0x0f, 0x06, 0x1d, 0x14, + 0x63, 0x6a, 0x71, 0x78, 0x47, 0x4e, 0x55, 0x5c, + 0x64, 0x6d, 0x76, 0x7f, 0x40, 0x49, 0x52, 0x5b, + 0x2c, 0x25, 0x3e, 0x37, 0x08, 0x01, 0x1a, 0x13, + 0x7d, 0x74, 0x6f, 0x66, 0x59, 0x50, 0x4b, 0x42, + 0x35, 0x3c, 0x27, 0x2e, 0x11, 0x18, 0x03, 0x0a, + 0x56, 0x5f, 0x44, 0x4d, 0x72, 0x7b, 0x60, 0x69, + 0x1e, 0x17, 0x0c, 0x05, 0x3a, 0x33, 0x28, 0x21, + 0x4f, 0x46, 0x5d, 0x54, 0x6b, 0x62, 0x79, 0x70, + 0x07, 0x0e, 0x15, 0x1c, 0x23, 0x2a, 0x31, 0x38, + 0x41, 0x48, 0x53, 0x5a, 0x65, 0x6c, 0x77, 0x7e, + 0x09, 0x00, 0x1b, 0x12, 0x2d, 0x24, 0x3f, 0x36, + 0x58, 0x51, 0x4a, 0x43, 0x7c, 0x75, 0x6e, 0x67, + 0x10, 0x19, 0x02, 0x0b, 0x34, 0x3d, 0x26, 0x2f, + 0x73, 0x7a, 0x61, 0x68, 0x57, 0x5e, 0x45, 0x4c, + 0x3b, 0x32, 0x29, 0x20, 0x1f, 0x16, 0x0d, 0x04, + 0x6a, 0x63, 0x78, 0x71, 0x4e, 0x47, 0x5c, 0x55, + 0x22, 0x2b, 0x30, 0x39, 0x06, 0x0f, 0x14, 0x1d, + 0x25, 0x2c, 0x37, 0x3e, 0x01, 0x08, 0x13, 0x1a, + 0x6d, 0x64, 0x7f, 0x76, 0x49, 0x40, 0x5b, 0x52, + 0x3c, 0x35, 0x2e, 0x27, 0x18, 0x11, 0x0a, 0x03, + 0x74, 0x7d, 0x66, 0x6f, 0x50, 0x59, 0x42, 0x4b, + 0x17, 0x1e, 0x05, 0x0c, 0x33, 0x3a, 0x21, 0x28, + 0x5f, 0x56, 0x4d, 0x44, 0x7b, 0x72, 0x69, 0x60, + 0x0e, 0x07, 0x1c, 0x15, 0x2a, 0x23, 0x38, 0x31, + 0x46, 0x4f, 0x54, 0x5d, 0x62, 0x6b, 0x70, 0x79 +}; + + +static uint8 crc7_byte(uint8 crc, uint8 data) +{ +#if (defined ARDUINO_ARCH_AVR) + return pgm_read_byte_near(crc7_syndrome_table + ((crc << 1) ^ data)); +#else + return crc7_syndrome_table[(crc << 1) ^ data]; +#endif +} + +static uint8 crc7(uint8 crc, const uint8 *buffer, uint32 len) +{ + while (len--) + crc = crc7_byte(crc, *buffer++); + return crc; +} + +/******************************************** + + Spi protocol Function + +********************************************/ + +#define CMD_DMA_WRITE 0xc1 +#define CMD_DMA_READ 0xc2 +#define CMD_INTERNAL_WRITE 0xc3 +#define CMD_INTERNAL_READ 0xc4 +#define CMD_TERMINATE 0xc5 +#define CMD_REPEAT 0xc6 +#define CMD_DMA_EXT_WRITE 0xc7 +#define CMD_DMA_EXT_READ 0xc8 +#define CMD_SINGLE_WRITE 0xc9 +#define CMD_SINGLE_READ 0xca +#define CMD_RESET 0xcf + +#define DATA_PKT_SZ_256 256 +#define DATA_PKT_SZ_512 512 +#define DATA_PKT_SZ_1K 1024 +#define DATA_PKT_SZ_4K (4 * 1024) +#define DATA_PKT_SZ_8K (8 * 1024) +#define DATA_PKT_SZ DATA_PKT_SZ_8K + +static sint8 spi_cmd(uint8 cmd, uint32 adr, uint32 u32data, uint32 sz,uint8 clockless) +{ + uint8 bc[9]; + uint8 len = 5; + sint8 result = N_OK; + + bc[0] = cmd; + switch (cmd) { + case CMD_SINGLE_READ: /* single word (4 bytes) read */ + bc[1] = (uint8)(adr >> 16); + bc[2] = (uint8)(adr >> 8); + bc[3] = (uint8)adr; + len = 5; + break; + case CMD_INTERNAL_READ: /* internal register read */ + bc[1] = (uint8)(adr >> 8); + if(clockless) bc[1] |= (1 << 7); + bc[2] = (uint8)adr; + bc[3] = 0x00; + len = 5; + break; + case CMD_TERMINATE: /* termination */ + bc[1] = 0x00; + bc[2] = 0x00; + bc[3] = 0x00; + len = 5; + break; + case CMD_REPEAT: /* repeat */ + bc[1] = 0x00; + bc[2] = 0x00; + bc[3] = 0x00; + len = 5; + break; + case CMD_RESET: /* reset */ + bc[1] = 0xff; + bc[2] = 0xff; + bc[3] = 0xff; + len = 5; + break; + case CMD_DMA_WRITE: /* dma write */ + case CMD_DMA_READ: /* dma read */ + bc[1] = (uint8)(adr >> 16); + bc[2] = (uint8)(adr >> 8); + bc[3] = (uint8)adr; + bc[4] = (uint8)(sz >> 8); + bc[5] = (uint8)(sz); + len = 7; + break; + case CMD_DMA_EXT_WRITE: /* dma extended write */ + case CMD_DMA_EXT_READ: /* dma extended read */ + bc[1] = (uint8)(adr >> 16); + bc[2] = (uint8)(adr >> 8); + bc[3] = (uint8)adr; + bc[4] = (uint8)(sz >> 16); + bc[5] = (uint8)(sz >> 8); + bc[6] = (uint8)(sz); + len = 8; + break; + case CMD_INTERNAL_WRITE: /* internal register write */ + bc[1] = (uint8)(adr >> 8); + if(clockless) bc[1] |= (1 << 7); + bc[2] = (uint8)(adr); + bc[3] = (uint8)(u32data >> 24); + bc[4] = (uint8)(u32data >> 16); + bc[5] = (uint8)(u32data >> 8); + bc[6] = (uint8)(u32data); + len = 8; + break; + case CMD_SINGLE_WRITE: /* single word write */ + bc[1] = (uint8)(adr >> 16); + bc[2] = (uint8)(adr >> 8); + bc[3] = (uint8)(adr); + bc[4] = (uint8)(u32data >> 24); + bc[5] = (uint8)(u32data >> 16); + bc[6] = (uint8)(u32data >> 8); + bc[7] = (uint8)(u32data); + len = 9; + break; + default: + result = N_FAIL; + break; + } + + if (result) { + if (!gu8Crc_off) + bc[len-1] = (crc7(0x7f, (const uint8 *)&bc[0], len-1)) << 1; + else + len-=1; + + if (M2M_SUCCESS != nmi_spi_write(bc, len)) { + M2M_ERR("[nmi spi]: Failed cmd write, bus error...\n"); + result = N_FAIL; + } + } + + return result; +} + +static sint8 spi_data_rsp(uint8 cmd) +{ +#ifdef ARDUINO + (void)cmd; // Silence "unused" warning +#endif + uint8 len; + uint8 rsp[3]; + sint8 result = N_OK; + + if (!gu8Crc_off) + len = 2; + else + len = 3; + + if (M2M_SUCCESS != nmi_spi_read(&rsp[0], len)) { + M2M_ERR("[nmi spi]: Failed bus error...\n"); + result = N_FAIL; + goto _fail_; + } + + if((rsp[len-1] != 0)||(rsp[len-2] != 0xC3)) + { + M2M_ERR("[nmi spi]: Failed data response read, %x %x %x\n",rsp[0],rsp[1],rsp[2]); + result = N_FAIL; + goto _fail_; + } +_fail_: + + return result; +} + +static sint8 spi_cmd_rsp(uint8 cmd) +{ + uint8 rsp; + sint8 result = N_OK; + sint8 s8RetryCnt; + + /** + Command/Control response + **/ + if ((cmd == CMD_RESET) || + (cmd == CMD_TERMINATE) || + (cmd == CMD_REPEAT)) { + if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { + result = N_FAIL; + goto _fail_; + } + } + + /* wait for response */ + s8RetryCnt = SPI_RESP_RETRY_COUNT; + do + { + if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { + M2M_ERR("[nmi spi]: Failed cmd response read, bus error...\n"); + result = N_FAIL; + goto _fail_; + } + } while((rsp != cmd) && (s8RetryCnt-- >0)); + + /** + State response + **/ + /* wait for response */ + s8RetryCnt = SPI_RESP_RETRY_COUNT; + do + { + if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { + M2M_ERR("[nmi spi]: Failed cmd response read, bus error...\n"); + result = N_FAIL; + goto _fail_; + } + } while((rsp != 0x00) && (s8RetryCnt-- >0)); + +_fail_: + + return result; +} +#ifndef USE_OLD_SPI_SW +static int spi_cmd_complete(uint8_t cmd, uint32_t adr, uint8_t *b, uint32_t sz, uint8_t clockless) +{ + uint8_t wb[32], rb[32]; + uint8_t wix, rix; + uint32_t len2; + uint8_t rsp; + int len = 0; + int result = N_OK; + + wb[0] = cmd; + switch (cmd) { + case CMD_SINGLE_READ: /* single word (4 bytes) read */ + wb[1] = (uint8_t)(adr >> 16); + wb[2] = (uint8_t)(adr >> 8); + wb[3] = (uint8_t)adr; + len = 5; + break; + case CMD_INTERNAL_READ: /* internal register read */ + wb[1] = (uint8_t)(adr >> 8); + if(clockless == 1) wb[1] |= (1 << 7); + wb[2] = (uint8_t)adr; + wb[3] = 0x00; + len = 5; + break; + case CMD_TERMINATE: /* termination */ + wb[1] = 0x00; + wb[2] = 0x00; + wb[3] = 0x00; + len = 5; + break; + case CMD_REPEAT: /* repeat */ + wb[1] = 0x00; + wb[2] = 0x00; + wb[3] = 0x00; + len = 5; + break; + case CMD_RESET: /* reset */ + wb[1] = 0xff; + wb[2] = 0xff; + wb[3] = 0xff; + len = 5; + break; + case CMD_DMA_WRITE: /* dma write */ + case CMD_DMA_READ: /* dma read */ + wb[1] = (uint8_t)(adr >> 16); + wb[2] = (uint8_t)(adr >> 8); + wb[3] = (uint8_t)adr; + wb[4] = (uint8_t)(sz >> 8); + wb[5] = (uint8_t)(sz); + len = 7; + break; + case CMD_DMA_EXT_WRITE: /* dma extended write */ + case CMD_DMA_EXT_READ: /* dma extended read */ + wb[1] = (uint8_t)(adr >> 16); + wb[2] = (uint8_t)(adr >> 8); + wb[3] = (uint8_t)adr; + wb[4] = (uint8_t)(sz >> 16); + wb[5] = (uint8_t)(sz >> 8); + wb[6] = (uint8_t)(sz); + len = 8; + break; + case CMD_INTERNAL_WRITE: /* internal register write */ + wb[1] = (uint8_t)(adr >> 8); + if(clockless == 1) wb[1] |= (1 << 7); + wb[2] = (uint8_t)(adr); + wb[3] = b[3]; + wb[4] = b[2]; + wb[5] = b[1]; + wb[6] = b[0]; + len = 8; + break; + case CMD_SINGLE_WRITE: /* single word write */ + wb[1] = (uint8_t)(adr >> 16); + wb[2] = (uint8_t)(adr >> 8); + wb[3] = (uint8_t)(adr); + wb[4] = b[3]; + wb[5] = b[2]; + wb[6] = b[1]; + wb[7] = b[0]; + len = 9; + break; + default: + result = N_FAIL; + break; + } + + if (result != N_OK) { + return result; + } + + if (!gu8Crc_off) { + wb[len-1] = (crc7(0x7f, (const uint8_t *)&wb[0], len-1)) << 1; + } else { + len -=1; + } + +#define NUM_SKIP_BYTES (1) +#define NUM_RSP_BYTES (2) +#define NUM_DATA_HDR_BYTES (1) +#define NUM_DATA_BYTES (4) +#define NUM_CRC_BYTES (2) +#define NUM_DUMMY_BYTES (3) + + if ((cmd == CMD_RESET) || + (cmd == CMD_TERMINATE) || + (cmd == CMD_REPEAT)) { + len2 = len + (NUM_SKIP_BYTES + NUM_RSP_BYTES + NUM_DUMMY_BYTES); + } else if ((cmd == CMD_INTERNAL_READ) || (cmd == CMD_SINGLE_READ)) { + if (!gu8Crc_off) { + len2 = len + (NUM_RSP_BYTES + NUM_DATA_HDR_BYTES + NUM_DATA_BYTES + + NUM_CRC_BYTES + NUM_DUMMY_BYTES); + } else { + len2 = len + (NUM_RSP_BYTES + NUM_DATA_HDR_BYTES + NUM_DATA_BYTES + + NUM_DUMMY_BYTES); + } + } else { + len2 = len + (NUM_RSP_BYTES + NUM_DUMMY_BYTES); + } +#undef NUM_DUMMY_BYTES + + if(len2 > (sizeof(wb)/sizeof(wb[0]))) { + M2M_ERR("[nmi spi]: spi buffer size too small (%d) (%d)\n", + len2, (sizeof(wb)/sizeof(wb[0]))); + result = N_FAIL; + return result; + } + /* zero spi write buffers. */ + for(wix = len; wix< len2; wix++) { + wb[wix] = 0; + } + rix = len; + + if (nmi_spi_rw(wb, rb, len2) != M2M_SUCCESS) { + M2M_ERR("[nmi spi]: Failed cmd write, bus error...\n"); + result = N_FAIL; + return result; + } + +#if 0 + { + int jj; + printk("--- cnd = %x, len=%d, len2=%d\n", cmd, len, len2); + for(jj=0; jj= len2) break; + if(((jj+1)%16) != 0) { + if((jj%16) == 0) { + printk("wb[%02x]: %02x ", jj, wb[jj]); + } else { + printk("%02x ", wb[jj]); + } + } else { + printk("%02x\n", wb[jj]); + } + } + printk("\n"); + + for(jj=0; jj= len2) break; + if(((jj+1)%16) != 0) { + if((jj%16) == 0) { + printk("rb[%02x]: %02x ", jj, rb[jj]); + } else { + printk("%02x ", rb[jj]); + } + } else { + printk("%02x\n", rb[jj]); + } + } + printk("\n"); + } +#endif + + /** + Command/Control response + **/ + if ((cmd == CMD_RESET) || + (cmd == CMD_TERMINATE) || + (cmd == CMD_REPEAT)) { + rix++; /* skip 1 byte */ + } + + rsp = rb[rix++]; + + + if (rsp != cmd) { + M2M_ERR("[nmi spi]: Failed cmd response, cmd (%02x), resp (%02x)\n", cmd, rsp); + result = N_FAIL; + return result; + } + + /** + State response + **/ + rsp = rb[rix++]; + if (rsp != 0x00) { + M2M_ERR("[nmi spi]: Failed cmd state response state (%02x)\n", rsp); + result = N_FAIL; + return result; + } + + if ((cmd == CMD_INTERNAL_READ) || (cmd == CMD_SINGLE_READ) + || (cmd == CMD_DMA_READ) || (cmd == CMD_DMA_EXT_READ)) { + int retry; + //uint16_t crc1, crc2; + uint8_t crc[2]; + /** + Data Respnose header + **/ + retry = SPI_RESP_RETRY_COUNT; + do { + /* ensure there is room in buffer later to read data and crc */ + if(rix < len2) { + rsp = rb[rix++]; + } else { + retry = 0; + break; + } + if (((rsp >> 4) & 0xf) == 0xf) + break; + } while (retry--); + + if (retry <= 0) { + M2M_ERR("[nmi spi]: Error, data read response (%02x)\n", rsp); + result = N_RESET; + return result; + } + + if ((cmd == CMD_INTERNAL_READ) || (cmd == CMD_SINGLE_READ)) { + /** + Read bytes + **/ + if((rix+3) < len2) { + b[0] = rb[rix++]; + b[1] = rb[rix++]; + b[2] = rb[rix++]; + b[3] = rb[rix++]; + } else { + M2M_ERR("[nmi spi]: buffer overrun when reading data.\n"); + result = N_FAIL; + return result; + } + + if (!gu8Crc_off) { + /** + Read Crc + **/ + if((rix+1) < len2) { + crc[0] = rb[rix++]; + crc[1] = rb[rix++]; + } else { + M2M_ERR("[nmi spi]: buffer overrun when reading crc.\n"); + result = N_FAIL; + return result; + } + } + } else if((cmd == CMD_DMA_READ) || (cmd == CMD_DMA_EXT_READ)) { + int ix; + + /* some data may be read in response to dummy bytes. */ + for(ix=0; (rix < len2) && (ix < sz);) { + b[ix++] = rb[rix++]; + } +#if 0 + if(ix) M2M_INFO("ttt %d %d\n", sz, ix); +#endif + sz -= ix; + + if(sz > 0) { + int nbytes; + + if (sz <= (DATA_PKT_SZ-ix)) { + nbytes = sz; + } else { + nbytes = DATA_PKT_SZ-ix; + } + + /** + Read bytes + **/ + if (nmi_spi_read(&b[ix], nbytes) != M2M_SUCCESS) { + M2M_ERR("[nmi spi]: Failed data block read, bus error...\n"); + result = N_FAIL; + goto _error_; + } + + /** + Read Crc + **/ + if (!gu8Crc_off) { + if (nmi_spi_read(crc, 2) != M2M_SUCCESS) { + M2M_ERR("[nmi spi]: Failed data block crc read, bus error...\n"); + result = N_FAIL; + goto _error_; + } + } + + + ix += nbytes; + sz -= nbytes; + } + + /* if any data in left unread, then read the rest using normal DMA code.*/ + while(sz > 0) { + int nbytes; + + if (sz <= DATA_PKT_SZ) { + nbytes = sz; + } else { + nbytes = DATA_PKT_SZ; + } + + /** + read data response only on the next DMA cycles not + the first DMA since data response header is already + handled above for the first DMA. + **/ + /** + Data Respnose header + **/ + retry = SPI_RESP_RETRY_COUNT; + do { + if (nmi_spi_read(&rsp, 1) != M2M_SUCCESS) { + M2M_ERR("[nmi spi]: Failed data response read, bus error...\n"); + result = N_FAIL; + break; + } + if (((rsp >> 4) & 0xf) == 0xf) + break; + } while (retry--); + + if (result == N_FAIL) + break; + + + /** + Read bytes + **/ + if (nmi_spi_read(&b[ix], nbytes) != M2M_SUCCESS) { + M2M_ERR("[nmi spi]: Failed data block read, bus error...\n"); + result = N_FAIL; + break; + } + + /** + Read Crc + **/ + if (!gu8Crc_off) { + if (nmi_spi_read(crc, 2) != M2M_SUCCESS) { + M2M_ERR("[nmi spi]: Failed data block crc read, bus error...\n"); + result = N_FAIL; + break; + } + } + + ix += nbytes; + sz -= nbytes; + } + } + } +_error_: + return result; +} +#endif +static sint8 spi_data_read(uint8 *b, uint16 sz,uint8 clockless) +{ + sint16 retry, ix, nbytes; + sint8 result = N_OK; + uint8 crc[2]; + uint8 rsp; + + /** + Data + **/ + ix = 0; + do { + if (sz <= DATA_PKT_SZ) + nbytes = sz; + else + nbytes = DATA_PKT_SZ; + + /** + Data Respnose header + **/ + retry = SPI_RESP_RETRY_COUNT; + do { + if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { + M2M_ERR("[nmi spi]: Failed data response read, bus error...\n"); + result = N_FAIL; + break; + } + if (((rsp >> 4) & 0xf) == 0xf) + break; + } while (retry--); + + if (result == N_FAIL) + break; + + if (retry <= 0) { + M2M_ERR("[nmi spi]: Failed data response read...(%02x)\n", rsp); + result = N_FAIL; + break; + } + + /** + Read bytes + **/ + if (M2M_SUCCESS != nmi_spi_read(&b[ix], nbytes)) { + M2M_ERR("[nmi spi]: Failed data block read, bus error...\n"); + result = N_FAIL; + break; + } + if(!clockless) + { + /** + Read Crc + **/ + if (!gu8Crc_off) { + if (M2M_SUCCESS != nmi_spi_read(crc, 2)) { + M2M_ERR("[nmi spi]: Failed data block crc read, bus error...\n"); + result = N_FAIL; + break; + } + } + } + ix += nbytes; + sz -= nbytes; + + } while (sz); + + return result; +} + +static sint8 spi_data_write(uint8 *b, uint16 sz) +{ + sint16 ix; + uint16 nbytes; + sint8 result = 1; + uint8 cmd, order, crc[2] = {0}; + //uint8 rsp; + + /** + Data + **/ + ix = 0; + do { + if (sz <= DATA_PKT_SZ) + nbytes = sz; + else + nbytes = DATA_PKT_SZ; + + /** + Write command + **/ + cmd = 0xf0; + if (ix == 0) { + if (sz <= DATA_PKT_SZ) + order = 0x3; + else + order = 0x1; + } else { + if (sz <= DATA_PKT_SZ) + order = 0x3; + else + order = 0x2; + } + cmd |= order; + if (M2M_SUCCESS != nmi_spi_write(&cmd, 1)) { + M2M_ERR("[nmi spi]: Failed data block cmd write, bus error...\n"); + result = N_FAIL; + break; + } + + /** + Write data + **/ + if (M2M_SUCCESS != nmi_spi_write(&b[ix], nbytes)) { + M2M_ERR("[nmi spi]: Failed data block write, bus error...\n"); + result = N_FAIL; + break; + } + + /** + Write Crc + **/ + if (!gu8Crc_off) { + if (M2M_SUCCESS != nmi_spi_write(crc, 2)) { + M2M_ERR("[nmi spi]: Failed data block crc write, bus error...\n"); + result = N_FAIL; + break; + } + } + + ix += nbytes; + sz -= nbytes; + } while (sz); + + + return result; +} + +/******************************************** + + Spi Internal Read/Write Function + +********************************************/ + +/******************************************** + + Spi interfaces + +********************************************/ + +static sint8 spi_write_reg(uint32 addr, uint32 u32data) +{ + uint8 retry = SPI_RETRY_COUNT; + sint8 result = N_OK; + uint8 cmd = CMD_SINGLE_WRITE; + uint8 clockless = 0; + +_RETRY_: + if (addr <= 0x30) + { + /** + NMC1000 clockless registers. + **/ + cmd = CMD_INTERNAL_WRITE; + clockless = 1; + } + else + { + cmd = CMD_SINGLE_WRITE; + clockless = 0; + } + +#if defined USE_OLD_SPI_SW + result = spi_cmd(cmd, addr, u32data, 4, clockless); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd, write reg (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + + result = spi_cmd_rsp(cmd); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd response, write reg (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + +#else + + result = spi_cmd_complete(cmd, addr, (uint8*)&u32data, 4, clockless); + if (result != N_OK) { + M2M_ERR( "[nmi spi]: Failed cmd, write reg (%08x)...\n", addr); + goto _FAIL_; + } + +#endif +_FAIL_: + if(result != N_OK) + { + nm_bsp_sleep(1); + spi_cmd(CMD_RESET, 0, 0, 0, 0); + spi_cmd_rsp(CMD_RESET); + M2M_ERR("Reset and retry %d %lx %lx\n",retry,addr,u32data); + nm_bsp_sleep(1); + retry--; + if(retry) goto _RETRY_; + } + + return result; +} + +static sint8 nm_spi_write(uint32 addr, uint8 *buf, uint16 size) +{ + sint8 result; + uint8 retry = SPI_RETRY_COUNT; + uint8 cmd = CMD_DMA_EXT_WRITE; + + +_RETRY_: + /** + Command + **/ +#if defined USE_OLD_SPI_SW + //Workaround hardware problem with single byte transfers over SPI bus + if (size == 1) + size = 2; + + result = spi_cmd(cmd, addr, 0, size,0); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd, write block (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + + result = spi_cmd_rsp(cmd); + if (result != N_OK) { + M2M_ERR("[nmi spi ]: Failed cmd response, write block (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } +#else + result = spi_cmd_complete(cmd, addr, NULL, size, 0); + if (result != N_OK) { + M2M_ERR( "[nmi spi]: Failed cmd, write block (%08x)...\n", addr); + goto _FAIL_; + } +#endif + + /** + Data + **/ + result = spi_data_write(buf, size); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed block data write...\n"); + goto _FAIL_; + } + /** + Data RESP + **/ + result = spi_data_rsp(cmd); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed block data write...\n"); + goto _FAIL_; + } + +_FAIL_: + if(result != N_OK) + { + nm_bsp_sleep(1); + spi_cmd(CMD_RESET, 0, 0, 0, 0); + spi_cmd_rsp(CMD_RESET); + M2M_ERR("Reset and retry %d %lx %d\n",retry,addr,size); + nm_bsp_sleep(1); + retry--; + if(retry) goto _RETRY_; + } + + + return result; +} + +static sint8 spi_read_reg(uint32 addr, uint32 *u32data) +{ + uint8 retry = SPI_RETRY_COUNT; + sint8 result = N_OK; + uint8 cmd = CMD_SINGLE_READ; + uint8 tmp[4]; + uint8 clockless = 0; + +_RETRY_: + + if (addr <= 0xff) + { + /** + NMC1000 clockless registers. + **/ + cmd = CMD_INTERNAL_READ; + clockless = 1; + } + else + { + cmd = CMD_SINGLE_READ; + clockless = 0; + } + +#if defined USE_OLD_SPI_SW + result = spi_cmd(cmd, addr, 0, 4, clockless); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd, read reg (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + + result = spi_cmd_rsp(cmd); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd response, read reg (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + + /* to avoid endianess issues */ + result = spi_data_read(&tmp[0], 4, clockless); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed data read...\n"); + goto _FAIL_; + } +#else + result = spi_cmd_complete(cmd, addr, (uint8*)&tmp[0], 4, clockless); + if (result != N_OK) { + M2M_ERR( "[nmi spi]: Failed cmd, read reg (%08x)...\n", addr); + goto _FAIL_; + } + +#endif + + *u32data = tmp[0] | + ((uint32)tmp[1] << 8) | + ((uint32)tmp[2] << 16) | + ((uint32)tmp[3] << 24); + +_FAIL_: + if(result != N_OK) + { + + nm_bsp_sleep(1); + spi_cmd(CMD_RESET, 0, 0, 0, 0); + spi_cmd_rsp(CMD_RESET); + M2M_ERR("Reset and retry %d %lx\n",retry,addr); + nm_bsp_sleep(1); + retry--; + if(retry) goto _RETRY_; + } + + return result; +} + +static sint8 nm_spi_read(uint32 addr, uint8 *buf, uint16 size) +{ + uint8 cmd = CMD_DMA_EXT_READ; + sint8 result; + uint8 retry = SPI_RETRY_COUNT; +#if defined USE_OLD_SPI_SW + uint8 tmp[2]; + uint8 single_byte_workaround = 0; +#endif + +_RETRY_: + + /** + Command + **/ +#if defined USE_OLD_SPI_SW + if (size == 1) + { + //Workaround hardware problem with single byte transfers over SPI bus + size = 2; + single_byte_workaround = 1; + } + result = spi_cmd(cmd, addr, 0, size,0); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd, read block (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + + result = spi_cmd_rsp(cmd); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd response, read block (%08x)...\n", (unsigned int)addr); + goto _FAIL_; + } + + /** + Data + **/ + if (single_byte_workaround) + { + result = spi_data_read(tmp, size,0); + buf[0] = tmp[0]; + } + else + result = spi_data_read(buf, size,0); + + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed block data read...\n"); + goto _FAIL_; + } +#else + result = spi_cmd_complete(cmd, addr, buf, size, 0); + if (result != N_OK) { + M2M_ERR("[nmi spi]: Failed cmd, read block (%08x)...\n", addr); + goto _FAIL_; + } +#endif + +_FAIL_: + if(result != N_OK) + { + nm_bsp_sleep(1); + spi_cmd(CMD_RESET, 0, 0, 0, 0); + spi_cmd_rsp(CMD_RESET); + M2M_ERR("Reset and retry %d %lx %d\n",retry,addr,size); + nm_bsp_sleep(1); + retry--; + if(retry) goto _RETRY_; + } + + return result; +} + +/******************************************** + + Bus interfaces + +********************************************/ + +static void spi_init_pkt_sz(void) +{ + uint32 val32; + + /* Make sure SPI max. packet size fits the defined DATA_PKT_SZ. */ + val32 = nm_spi_read_reg(SPI_BASE+0x24); + val32 &= ~(0x7 << 4); + switch(DATA_PKT_SZ) + { + case 256: val32 |= (0 << 4); break; + case 512: val32 |= (1 << 4); break; + case 1024: val32 |= (2 << 4); break; + case 2048: val32 |= (3 << 4); break; + case 4096: val32 |= (4 << 4); break; + case 8192: val32 |= (5 << 4); break; + + } + nm_spi_write_reg(SPI_BASE+0x24, val32); +} + +sint8 nm_spi_reset(void) +{ + spi_cmd(CMD_RESET, 0, 0, 0, 0); + spi_cmd_rsp(CMD_RESET); + return M2M_SUCCESS; +} + +/* +* @fn nm_spi_init +* @brief Initialize the SPI +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_spi_init(void) +{ + uint32 chipid; + uint32 reg = 0; + + + /** + configure protocol + **/ + gu8Crc_off = 0; + + // TODO: We can remove the CRC trials if there is a definite way to reset + // the SPI to it's initial value. + if (!spi_read_reg(NMI_SPI_PROTOCOL_CONFIG, ®)) { + /* Read failed. Try with CRC off. This might happen when module + is removed but chip isn't reset*/ + gu8Crc_off = 1; + M2M_ERR("[nmi spi]: Failed internal read protocol with CRC on, retyring with CRC off...\n"); + if (!spi_read_reg(NMI_SPI_PROTOCOL_CONFIG, ®)){ + // Reaad failed with both CRC on and off, something went bad + M2M_ERR( "[nmi spi]: Failed internal read protocol...\n"); + return 0; + } + } + if(gu8Crc_off == 0) + { + reg &= ~0xc; /* disable crc checking */ + reg &= ~0x70; + reg |= (0x5 << 4); + if (!spi_write_reg(NMI_SPI_PROTOCOL_CONFIG, reg)) { + M2M_ERR( "[nmi spi]: Failed internal write protocol reg...\n"); + return 0; + } + gu8Crc_off = 1; + } + + /** + make sure can read back chip id correctly + **/ + if (!spi_read_reg(0x1000, &chipid)) { + M2M_ERR("[nmi spi]: Fail cmd read chip id...\n"); + return M2M_ERR_BUS_FAIL; + } + + M2M_DBG("[nmi spi]: chipid (%08x)\n", (unsigned int)chipid); + spi_init_pkt_sz(); + + + return M2M_SUCCESS; +} + +/* +* @fn nm_spi_init +* @brief DeInitialize the SPI +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Samer Sarhan +* @date 27 Feb 2015 +* @version 1.0 +*/ +sint8 nm_spi_deinit(void) +{ + gu8Crc_off = 0; + return M2M_SUCCESS; +} + +/* +* @fn nm_spi_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +uint32 nm_spi_read_reg(uint32 u32Addr) +{ + uint32 u32Val; + + spi_read_reg(u32Addr, &u32Val); + + return u32Val; +} + +/* +* @fn nm_spi_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_spi_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) +{ + sint8 s8Ret; + + s8Ret = spi_read_reg(u32Addr,pu32RetVal); + + if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; + else s8Ret = M2M_ERR_BUS_FAIL; + + return s8Ret; +} + +/* +* @fn nm_spi_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_spi_write_reg(uint32 u32Addr, uint32 u32Val) +{ + sint8 s8Ret; + + s8Ret = spi_write_reg(u32Addr, u32Val); + + if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; + else s8Ret = M2M_ERR_BUS_FAIL; + + return s8Ret; +} + +/* +* @fn nm_spi_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u16Sz +* Number of bytes to read. The buffer size must be >= u16Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_spi_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) +{ + sint8 s8Ret; + + s8Ret = nm_spi_read(u32Addr, puBuf, u16Sz); + + if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; + else s8Ret = M2M_ERR_BUS_FAIL; + + return s8Ret; +} + +/* +* @fn nm_spi_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u16Sz +* Number of bytes to write. The buffer size must be >= u16Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author M. Abdelmawla +* @date 11 July 2012 +* @version 1.0 +*/ +sint8 nm_spi_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) +{ + sint8 s8Ret; + + s8Ret = nm_spi_write(u32Addr, puBuf, u16Sz); + + if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; + else s8Ret = M2M_ERR_BUS_FAIL; + + return s8Ret; +} + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmspi.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmspi.h new file mode 100644 index 0000000..a1bd4a9 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmspi.h @@ -0,0 +1,132 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 SPI protocol bus APIs implementation. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NMSPI_H_ +#define _NMSPI_H_ + +#include "common/include/nm_common.h" + +#ifdef __cplusplus + extern "C" { +#endif + +/** +* @fn nm_spi_init +* @brief Initialize the SPI +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_init(void); +/** +* @fn nm_spi_reset +* @brief reset the SPI +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_reset(void); + +/** +* @fn nm_spi_deinit +* @brief DeInitialize the SPI +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_deinit(void); + +/** +* @fn nm_spi_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +*/ +uint32 nm_spi_read_reg(uint32 u32Addr); + +/** +* @fn nm_spi_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); + +/** +* @fn nm_spi_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_write_reg(uint32 u32Addr, uint32 u32Val); + +/** +* @fn nm_spi_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u16Sz +* Number of bytes to read. The buffer size must be >= u16Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); + +/** +* @fn nm_spi_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u16Sz +* Number of bytes to write. The buffer size must be >= u16Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_spi_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); + +#ifdef __cplusplus + } +#endif + +#endif /* _NMSPI_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmuart.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmuart.c new file mode 100644 index 0000000..63541cf --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmuart.c @@ -0,0 +1,536 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 UART protocol bus APIs implementation. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include "common/include/nm_common.h" + +#ifdef CONF_WINC_USE_UART + +#include "driver/source/nmuart.h" +#include "bus_wrapper/include/nm_bus_wrapper.h" + +#define HDR_SZ 12 + +static uint8 get_cs(uint8* b, uint8 sz){ + int i; + uint8 cs = 0; + for(i = 0; i < sz; i++) + cs ^= b[i]; + return cs; +} + +/* +* @fn nm_uart_sync_cmd +* @brief Check COM Port +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Dina El Sissy +* @date 13 AUG 2012 +* @version 1.0 +*/ +sint8 nm_uart_sync_cmd(void) +{ + tstrNmUartDefault strUart; + sint8 s8Ret = -1; + uint8 b [HDR_SZ+1]; + uint8 rsz; + uint8 onchip = 0; + + /*read reg*/ + b[0] = 0x12; + + rsz = 1; + strUart.pu8Buf = b; + strUart.u16Sz = 1; + + if(M2M_SUCCESS == nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + strUart.u16Sz = rsz; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + M2M_ERR("failed to send cfg bytes\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + if (b[0] == 0x5a) + { + s8Ret = 0; + onchip = 1; + M2M_INFO("Built-in WINC1500 UART Found\n"); + } + else if(b[0] == 0x5b) + { + s8Ret = 0; + onchip = 0; + M2M_INFO("WINC1500 Serial Bridge Found\n"); + } + /*TODO: this should be the way we read the register since the cortus is little endian*/ + /**pu32RetVal = b[0] | ((uint32)b[1] << 8) | ((uint32)b[2] << 16) | ((uint32)b[3] << 24);*/ + if(s8Ret == M2M_SUCCESS) + s8Ret = (sint8)onchip; + return s8Ret; +} + sint8 nm_uart_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) +{ + tstrNmUartDefault strUart; + sint8 s8Ret = M2M_SUCCESS; + uint8 b [HDR_SZ+1]; + uint8 rsz; + + /*read reg*/ + b[0] = 0xa5; + b[1] = 0; + b[2] = 0; + b[3] = 0; + b[4] = 0; + b[5] = (uint8)(u32Addr & 0x000000ff); + b[6] = (uint8)((u32Addr & 0x0000ff00)>>8); + b[7] = (uint8)((u32Addr & 0x00ff0000)>>16); + b[8] = (uint8)((u32Addr & 0xff000000)>>24); + b[9] = 0; + b[10] = 0; + b[11] = 0; + b[12] = 0; + + b[2] = get_cs(&b[1],HDR_SZ); + + rsz = 4; + strUart.pu8Buf = b; + strUart.u16Sz = sizeof(b); + + if(M2M_SUCCESS == nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + if(!nm_bus_get_chip_type()) + { + strUart.u16Sz = 1; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + if(b[0] == 0xAC) + { + M2M_DBG("Successfully sent the command\n"); + strUart.u16Sz = rsz; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + strUart.u16Sz = rsz; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + } + } + else + { + M2M_ERR("failed to send cfg bytes\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + /*TODO: this should be the way we read the register since the cortus is little endian*/ + /**pu32RetVal = b[0] | ((uint32)b[1] << 8) | ((uint32)b[2] << 16) | ((uint32)b[3] << 24);*/ + + *pu32RetVal = ((uint32)b[0] << 24) | ((uint32)b[1] << 16) | ((uint32)b[2] << 8) | b[3]; + + return s8Ret; +} + +/* +* @fn nm_uart_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +* @author Dina El Sissy +* @date 13 AUG 2012 +* @version 1.0 +*/ +uint32 nm_uart_read_reg(uint32 u32Addr) +{ + uint32 val; + nm_uart_read_reg_with_ret(u32Addr , &val); + return val; +} + +/* +* @fn nm_uart_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Dina El Sissy +* @date 13 AUG 2012 +* @version 1.0 +*/ +sint8 nm_uart_write_reg(uint32 u32Addr, uint32 u32Val) +{ + tstrNmUartDefault strUart; + sint8 s8Ret = M2M_SUCCESS; + uint8 b[HDR_SZ+1]; + + /*write reg*/ + b[0] = 0xa5; + b[1] = 1; + b[2] = 0; + b[3] = 0; + b[4] = 0; + b[5] = (uint8)(u32Addr & 0x000000ff); + b[6] = (uint8)((u32Addr & 0x0000ff00)>>8); + b[7] = (uint8)((u32Addr & 0x00ff0000)>>16); + b[8] = (uint8)((u32Addr & 0xff000000)>>24); + b[9] = (uint8)(u32Val & 0x000000ff); + b[10] = (uint8)((u32Val & 0x0000ff00)>>8); + b[11] = (uint8)((u32Val & 0x00ff0000)>>16); + b[12] = (uint8)((u32Val & 0xff000000)>>24); + + b[2] = get_cs(&b[1],HDR_SZ); + + get_cs(&b[1],HDR_SZ); + + strUart.pu8Buf = b; + strUart.u16Sz = sizeof(b); + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + else + { + if(!nm_bus_get_chip_type()) + { + //check for the ack from the SAMD21 for the packet reception. + strUart.u16Sz = 1; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + if(b[0] == 0xAC) + { + M2M_DBG("Successfully sent the reg write command\n"); + } + else + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + } + + return s8Ret; +} + + +/** +* @fn nm_uart_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u16Sz +* Number of bytes to read. The buffer size must be >= u16Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Dina El Sissy +* @date 13 AUG 2012 +* @version 1.0 +*/ +sint8 nm_uart_read_block(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz) +{ + tstrNmUartDefault strUart; + sint8 s8Ret = M2M_SUCCESS; + uint8 au8Buf[HDR_SZ+1]; + + au8Buf[0] = 0xa5; + au8Buf[1] = 2; + au8Buf[2] = 0; + au8Buf[3] = (uint8)(u16Sz & 0x00ff); + au8Buf[4] = (uint8)((u16Sz & 0xff00)>>8); + au8Buf[5] = (uint8)(u32Addr & 0x000000ff); + au8Buf[6] = (uint8)((u32Addr & 0x0000ff00)>>8); + au8Buf[7] = (uint8)((u32Addr & 0x00ff0000)>>16); + au8Buf[8] = (uint8)((u32Addr & 0xff000000)>>24); + au8Buf[9] = 0; + au8Buf[10] = 0; + au8Buf[11] = 0; + au8Buf[12] = 0; + + au8Buf[2] = get_cs(&au8Buf[1],HDR_SZ); + + strUart.pu8Buf = au8Buf; + strUart.u16Sz = sizeof(au8Buf); + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + else + { + if(!nm_bus_get_chip_type()) + { + //check for the ack from the SAMD21 for the packet reception. + strUart.u16Sz = 1; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + if(au8Buf[0] == 0xAC) + { + M2M_DBG("Successfully sent the block read command\n"); + strUart.pu8Buf = pu8Buf; + strUart.u16Sz = u16Sz; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + M2M_ERR("read error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + M2M_ERR("write error (Error sending the block read command)\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + strUart.pu8Buf = pu8Buf; + strUart.u16Sz = u16Sz; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + M2M_ERR("read error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + } + + return s8Ret; +} + +/** +* @fn nm_uart_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u16Sz +* Number of bytes to write. The buffer size must be >= u16Sz +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Dina El Sissy +* @date 13 AUG 2012 +* @version 1.0 +*/ +sint8 nm_uart_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) +{ + tstrNmUartDefault strUart; + sint8 s8Ret = M2M_SUCCESS; + static uint8 au8Buf[HDR_SZ+1]; + + au8Buf[0] = 0xa5; + au8Buf[1] = 3; + au8Buf[2] = 0; + au8Buf[3] = (uint8)(u16Sz & 0x00ff); + au8Buf[4] = (uint8)((u16Sz & 0xff00)>>8); + au8Buf[5] = (uint8)(u32Addr & 0x000000ff); + au8Buf[6] = (uint8)((u32Addr & 0x0000ff00)>>8); + au8Buf[7] = (uint8)((u32Addr & 0x00ff0000)>>16); + au8Buf[8] = (uint8)((u32Addr & 0xff000000)>>24); + au8Buf[9] = 0; + au8Buf[10] = 0; + au8Buf[11] = 0; + au8Buf[12] = 0; + + au8Buf[2] = get_cs(&au8Buf[1],HDR_SZ); + + strUart.pu8Buf = au8Buf; + strUart.u16Sz = sizeof(au8Buf); + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + else + { + if(!nm_bus_get_chip_type()) + { + //check for the ack from the SAMD21 for the packet reception. + strUart.u16Sz = 1; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + if(au8Buf[0] == 0xAC) + { + M2M_DBG("Successfully sent the block Write command\n"); + strUart.pu8Buf = puBuf; + strUart.u16Sz = u16Sz; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + else + { + //check for the ack from the SAMD21 for the payload reception. + strUart.pu8Buf = au8Buf; + strUart.u16Sz = 1; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + if(au8Buf[0] == 0xAC) + { + M2M_DBG("Successfully sent the data payload\n"); + } + else + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + } + else + { + M2M_ERR("write error (Error sending the block write command)\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + else + { + strUart.pu8Buf = puBuf; + strUart.u16Sz = u16Sz; + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + } + return s8Ret; +} + +/** +* @fn nm_uart_reconfigure +* @brief Reconfigures the UART interface +* @param [in] ptr +* Pointer to a DWORD containing baudrate at this moment. +* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure +* @author Viswanathan Murugesan +* @date 22 OCT 2014 +* @version 1.0 +*/ +sint8 nm_uart_reconfigure(void *ptr) +{ + tstrNmUartDefault strUart; + sint8 s8Ret = M2M_SUCCESS; + uint8 b[HDR_SZ+1]; + + /*write reg*/ + b[0] = 0xa5; + b[1] = 5; + b[2] = 0; + b[3] = 0; + b[4] = 0; + b[5] = 0; + b[6] = 0; + b[7] = 0; + b[8] = 0; + b[9] = (uint8)((*(unsigned long *)ptr) & 0x000000ff); + b[10] = (uint8)(((*(unsigned long *)ptr) & 0x0000ff00)>>8); + b[11] = (uint8)(((*(unsigned long *)ptr) & 0x00ff0000)>>16); + b[12] = (uint8)(((*(unsigned long *)ptr) & 0xff000000)>>24); + + b[2] = get_cs(&b[1],HDR_SZ); + + get_cs(&b[1],HDR_SZ); + + strUart.pu8Buf = b; + strUart.u16Sz = sizeof(b); + + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + else + { + if(!nm_bus_get_chip_type()) + { + //check for the ack from the SAMD21 for the packet reception. + strUart.u16Sz = 1; + if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) + { + s8Ret = M2M_ERR_BUS_FAIL; + } + if(b[0] == 0xAC) + { + M2M_DBG("Successfully sent the UART reconfigure command\n"); + } + else + { + M2M_ERR("write error\n"); + s8Ret = M2M_ERR_BUS_FAIL; + } + } + } + + return s8Ret; +} +#endif +/* EOF */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmuart.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmuart.h new file mode 100644 index 0000000..8f07d39 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmuart.h @@ -0,0 +1,118 @@ +/** + * + * \file + * + * \brief This module contains NMC1000 UART protocol bus APIs implementation. + * + * Copyright (c) 2016 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef _NMUART_H_ +#define _NMUART_H_ + +#include "common/include/nm_common.h" + +/* +* @fn nm_uart_sync_cmd +* @brief Check COM Port +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_uart_sync_cmd(void); +/** +* @fn nm_uart_read_reg +* @brief Read register +* @param [in] u32Addr +* Register address +* @return Register value +*/ +uint32 nm_uart_read_reg(uint32 u32Addr); + +/** +* @fn nm_uart_read_reg_with_ret +* @brief Read register with error code return +* @param [in] u32Addr +* Register address +* @param [out] pu32RetVal +* Pointer to u32 variable used to return the read value +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_uart_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); + +/** +* @fn nm_uart_write_reg +* @brief write register +* @param [in] u32Addr +* Register address +* @param [in] u32Val +* Value to be written to the register +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_uart_write_reg(uint32 u32Addr, uint32 u32Val); + +/** +* @fn nm_uart_read_block +* @brief Read block of data +* @param [in] u32Addr +* Start address +* @param [out] puBuf +* Pointer to a buffer used to return the read data +* @param [in] u16Sz +* Number of bytes to read. The buffer size must be >= u16Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_uart_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); + +/** +* @fn nm_uart_write_block +* @brief Write block of data +* @param [in] u32Addr +* Start address +* @param [in] puBuf +* Pointer to the buffer holding the data to be written +* @param [in] u16Sz +* Number of bytes to write. The buffer size must be >= u16Sz +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_uart_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); + +/** +* @fn nm_uart_reconfigure +* @brief Reconfigures the UART interface +* @param [in] ptr +* Pointer to a DWORD containing baudrate at this moment. +* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure +*/ +sint8 nm_uart_reconfigure(void *ptr); +#endif /* _NMI2C_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h new file mode 100644 index 0000000..933ad67 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h @@ -0,0 +1,461 @@ +/** + * + * \file + * + * \brief BSD compatible socket interface internal types. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +#ifndef __M2M_SOCKET_HOST_IF_H__ +#define __M2M_SOCKET_HOST_IF_H__ + + +#ifdef __cplusplus +extern "C" { +#endif + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#ifndef _BOOT_ +#ifndef _FIRMWARE_ +#include "socket/include/socket.h" +#else +#include "m2m_types.h" +#endif +#endif + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +/* + * HOSTNAME_MAX_SIZE is defined here and also in host_drv/socket/include/socket.h + * The two definitions must match. +*/ +#ifdef _FIRMWARE_ +#define HOSTNAME_MAX_SIZE (64) +#endif + +#define SSL_MAX_OPT_LEN HOSTNAME_MAX_SIZE + + + +#define SOCKET_CMD_INVALID 0x00 +/*!< + Invlaid Socket command value. +*/ + + +#define SOCKET_CMD_BIND 0x41 +/*!< + Socket Binding command value. +*/ + + +#define SOCKET_CMD_LISTEN 0x42 +/*!< + Socket Listening command value. +*/ + + +#define SOCKET_CMD_ACCEPT 0x43 +/*!< + Socket Accepting command value. +*/ + + +#define SOCKET_CMD_CONNECT 0x44 +/*!< + Socket Connecting command value. +*/ + + +#define SOCKET_CMD_SEND 0x45 +/*!< + Socket send command value. +*/ + + +#define SOCKET_CMD_RECV 0x46 +/*!< + Socket Recieve command value. +*/ + + +#define SOCKET_CMD_SENDTO 0x47 +/*!< + Socket sendTo command value. +*/ + + +#define SOCKET_CMD_RECVFROM 0x48 +/*!< + Socket RecieveFrom command value. +*/ + + +#define SOCKET_CMD_CLOSE 0x49 +/*!< + Socket Close command value. +*/ + + +#define SOCKET_CMD_DNS_RESOLVE 0x4A +/*!< + Socket DNS Resolve command value. +*/ + + +#define SOCKET_CMD_SSL_CONNECT 0x4B +/*!< + SSL-Socket Connect command value. +*/ + + +#define SOCKET_CMD_SSL_SEND 0x4C +/*!< + SSL-Socket Send command value. +*/ + + +#define SOCKET_CMD_SSL_RECV 0x4D +/*!< + SSL-Socket Recieve command value. +*/ + + +#define SOCKET_CMD_SSL_CLOSE 0x4E +/*!< + SSL-Socket Close command value. +*/ + + +#define SOCKET_CMD_SET_SOCKET_OPTION 0x4F +/*!< + Set Socket Option command value. +*/ + + +#define SOCKET_CMD_SSL_CREATE 0x50 +/*!< +*/ + + +#define SOCKET_CMD_SSL_SET_SOCK_OPT 0x51 +/*!< +*/ + + +#define SOCKET_CMD_PING 0x52 +/*!< +*/ + + +#define SOCKET_CMD_SSL_SET_CS_LIST 0x53 +/*!< + Recommend instead using @ref M2M_SSL_REQ_SET_CS_LIST and + associated response @ref M2M_SSL_RESP_SET_CS_LIST +*/ + + +#define SOCKET_CMD_SSL_BIND 0x54 +/*!< +*/ + + +#define SOCKET_CMD_SSL_EXP_CHECK 0x55 +/*!< +*/ + + + +#define PING_ERR_SUCCESS 0 +#define PING_ERR_DEST_UNREACH 1 +#define PING_ERR_TIMEOUT 2 + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +/*! +* @brief +*/ +typedef struct{ + uint16 u16Family; + uint16 u16Port; + uint32 u32IPAddr; +}tstrSockAddr; + + +typedef sint8 SOCKET; +typedef tstrSockAddr tstrUIPSockAddr; + + + +/*! +@struct \ + tstrDnsReply + +@brief + DNS Reply, contains hostName and HostIP. +*/ +typedef struct{ + char acHostName[HOSTNAME_MAX_SIZE]; + uint32 u32HostIP; +}tstrDnsReply; + + +/*! +@brief +*/ +typedef struct{ + tstrSockAddr strAddr; + SOCKET sock; + uint8 u8Void; + uint16 u16SessionID; +}tstrBindCmd; + + +/*! +@brief +*/ +typedef struct{ + SOCKET sock; + sint8 s8Status; + uint16 u16SessionID; +}tstrBindReply; + + +/*! +* @brief +*/ +typedef struct{ + SOCKET sock; + uint8 u8BackLog; + uint16 u16SessionID; +}tstrListenCmd; + + +/*! +@struct \ + tstrSocketRecvMsg + +@brief Socket recv status. + + It is passed to the APPSocketEventHandler with SOCKET_MSG_RECV or SOCKET_MSG_RECVFROM message type + in a response to a user call to the recv or recvfrom. + If the received data from the remote peer is larger than the USER Buffer size (given at recv call), the data is + delivered to the user in a number of consecutive chunks according to the USER Buffer size. +*/ +typedef struct{ + SOCKET sock; + sint8 s8Status; + uint16 u16SessionID; +}tstrListenReply; + + +/*! +* @brief +*/ +typedef struct{ + tstrSockAddr strAddr; + SOCKET sListenSock; + SOCKET sConnectedSock; + uint16 u16AppDataOffset; + /*!< + In further packet send requests the host interface should put the user application + data at this offset in the allocated shared data packet. + */ +}tstrAcceptReply; + + +/*! +* @brief +*/ +typedef struct{ + tstrSockAddr strAddr; + SOCKET sock; + uint8 u8SslFlags; + uint16 u16SessionID; +}tstrConnectCmd; + + +/*! +@struct \ + tstrConnectReply + +@brief + Connect Reply, contains sock number and error value +*/ +typedef struct{ + SOCKET sock; + sint8 s8Error; + uint16 u16AppDataOffset; + /*!< + In further packet send requests the host interface should put the user application + data at this offset in the allocated shared data packet. + */ +}tstrConnectReply; + + +/*! +@brief +*/ +typedef struct{ + SOCKET sock; + uint8 u8Void; + uint16 u16DataSize; + tstrSockAddr strAddr; + uint16 u16SessionID; + uint16 u16Void; +}tstrSendCmd; + + +/*! +@struct \ + tstrSendReply + +@brief + Send Reply, contains socket number and number of sent bytes. +*/ +typedef struct{ + SOCKET sock; + uint8 u8Void; + sint16 s16SentBytes; + uint16 u16SessionID; + uint16 u16Void; +}tstrSendReply; + + +/*! +* @brief +*/ +typedef struct{ + uint32 u32Timeoutmsec; + SOCKET sock; + uint8 u8Void; + uint16 u16SessionID; +}tstrRecvCmd; + + +/*! +@struct +@brief +*/ +typedef struct{ + tstrSockAddr strRemoteAddr; + sint16 s16RecvStatus; + uint16 u16DataOffset; + SOCKET sock; + uint8 u8Void; + uint16 u16SessionID; +}tstrRecvReply; + + +/*! +* @brief +*/ +typedef struct{ + uint32 u32OptionValue; + SOCKET sock; + uint8 u8Option; + uint16 u16SessionID; +}tstrSetSocketOptCmd; + + +typedef struct{ + SOCKET sslSock; + uint8 __PAD24__[3]; +}tstrSSLSocketCreateCmd; + + +/*! +* @brief +*/ +typedef struct{ + SOCKET sock; + uint8 u8Option; + uint16 u16SessionID; + uint32 u32OptLen; + uint8 au8OptVal[SSL_MAX_OPT_LEN]; +}tstrSSLSetSockOptCmd; + + +/*! +*/ +typedef struct{ + uint32 u32DestIPAddr; + uint32 u32CmdPrivate; + uint16 u16PingCount; + uint8 u8TTL; + uint8 __PAD8__; +}tstrPingCmd; + + +typedef struct{ + uint32 u32IPAddr; + uint32 u32CmdPrivate; + uint32 u32RTT; + uint16 u16Success; + uint16 u16Fail; + uint8 u8ErrorCode; + uint8 __PAD24__[3]; +}tstrPingReply; + + +/*! +@struct\ + tstrSslCertExpSettings + +@brief SSL Certificate Expiry Validation Settings + +@sa tenuSslCertExpSettings +*/ +typedef struct{ + uint32 u32CertExpValidationOpt; + /*!< + See @tenuSslCertExpSettings for possible values. + */ +}tstrSslCertExpSettings; + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* __M2M_SOCKET_HOST_IF_H__ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/socket.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/socket.h new file mode 100644 index 0000000..837959a --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/socket.h @@ -0,0 +1,2065 @@ +/** + * + * \file + * + * \brief WINC BSD compatible Socket Interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef __SOCKET_H__ +#define __SOCKET_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup SocketHeader Socket + * BSD compatible socket interface beftween the host layer and the network + * protocol stacks in the firmware. + * These functions are used by the host application to send or receive + * packets and to do other socket operations. + */ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "common/include/nm_common.h" +#include "driver/include/m2m_types.h" + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/** + * @defgroup SocketDefines Defines + * @ingroup SocketHeader + */ + +/** @defgroup IPDefines TCP/IP Defines + * @ingroup SocketDefines + * The following list of macros are used to define constants used throughout the socket layer. + * @{ + */ + +/* + * HOSTNAME_MAX_SIZE is defined here and also in host_drv/socket/include/m2m_socket_host_if.h + * The two definitions must match. +*/ +#define HOSTNAME_MAX_SIZE 64 +/*!< + Maximum allowed size for a host domain name passed to the function gethostbyname @ref gethostbyname. + command value. Used with the setsockopt function. + +*/ + +#define SOCKET_BUFFER_MAX_LENGTH 1400 +/*!< + Maximum allowed size for a socket data buffer. Used with @ref send socket + function to ensure that the buffer sent is within the allowed range. +*/ + +#define AF_INET 2 +/*!< + The AF_INET is the address family used for IPv4. An IPv4 transport address is specified with the @ref sockaddr_in structure. + (It is the only supported type for the current implementation.) +*/ + + +#define SOCK_STREAM 1 +/*!< + One of the IPv4 supported socket types for reliable connection-oriented stream connection. + Passed to the @ref socket function for the socket creation operation. +*/ + +#define SOCK_DGRAM 2 +/*!< + One of the IPv4 supported socket types for unreliable connectionless datagram connection. + Passed to the @ref socket function for the socket creation operation. +*/ + + +#define SOCKET_FLAGS_SSL 0x01 +/*!< + This flag shall be passed to the socket API for SSL session. +*/ + +#define TCP_SOCK_MAX (7) +/*!< + Maximum number of simultaneous TCP sockets. +*/ + +#define UDP_SOCK_MAX 4 +/*!< + Maximum number of simultaneous UDP sockets. +*/ + +#define MAX_SOCKET (TCP_SOCK_MAX + UDP_SOCK_MAX) +/*!< + Maximum number of Sockets. +*/ + +#define SOL_SOCKET 1 +/*!< + Socket option. + Used with the @ref setsockopt function +*/ + +#define SOL_SSL_SOCKET 2 +/*!< + SSL Socket option level. + Used with the @ref setsockopt function +*/ + +#define SO_SET_UDP_SEND_CALLBACK 0x00 +/*!< + Socket option used by the application to enable/disable + the use of UDP send callbacks. + Used with the @ref setsockopt function. +*/ + +#define IP_ADD_MEMBERSHIP 0x01 +/*!< + Set Socket Option Add Membership command value (to join a multicast group). + Used with the @ref setsockopt function. +*/ + + +#define IP_DROP_MEMBERSHIP 0x02 +/*!< + Set Socket Option Drop Membership command value (to leave a multicast group). + Used with the @ref setsockopt function. +*/ + //@} + + + +/** + * @defgroup TLSDefines TLS Defines + * @ingroup SocketDefines + */ + + + +/** @defgroup SSLSocketOptions TLS Socket Options + * @ingroup TLSDefines + * The following list of macros are used to define SSL Socket options. + * @{ + * @sa setsockopt + */ + +#define SO_SSL_BYPASS_X509_VERIF 0x01 +/*!< + Allow an opened SSL socket to bypass the X509 certificate + verification process. + It is highly required NOT to use this socket option in production + software applications. It is supported for debugging and testing + purposes. + The option value should be casted to int type and it is handled + as a boolean flag. +*/ + + +#define SO_SSL_SNI 0x02 +/*!< + Set the Server Name Indicator (SNI) for an SSL socket. The + SNI is a NULL terminated string containing the server name + associated with the connection. It must not exceed the size + of HOSTNAME_MAX_SIZE. +*/ + + +#define SO_SSL_ENABLE_SESSION_CACHING 0x03 +/*!< + This option allow the TLS to cache the session information for fast + TLS session establishment in future connections using the + TLS Protocol session resume features. +*/ + + +#define SO_SSL_ENABLE_SNI_VALIDATION 0x04 +/*!< + Enable SNI validation against the server's certificate subject + common name. If there is no SNI provided (via the SO_SSL_SNI + option), setting this option does nothing. +*/ + + +//@} + + + +/** @defgroup LegacySSLCipherSuite Legacy names for TLS Cipher Suite IDs + * @ingroup TLSDefines + * The following list of macros MUST NOT be used. Instead use the new names under SSLCipherSuiteID + * @sa sslSetActiveCipherSuites + * @{ + */ + +#define SSL_ENABLE_RSA_SHA_SUITES 0x01 +/*!< + Enable RSA Hmac_SHA based Cipher suites. For example, + TLS_RSA_WITH_AES_128_CBC_SHA +*/ + + +#define SSL_ENABLE_RSA_SHA256_SUITES 0x02 +/*!< + Enable RSA Hmac_SHA256 based Cipher suites. For example, + TLS_RSA_WITH_AES_128_CBC_SHA256 +*/ + + +#define SSL_ENABLE_DHE_SHA_SUITES 0x04 +/*!< + Enable DHE Hmac_SHA based Cipher suites. For example, + TLS_DHE_RSA_WITH_AES_128_CBC_SHA +*/ + + +#define SSL_ENABLE_DHE_SHA256_SUITES 0x08 +/*!< + Enable DHE Hmac_SHA256 based Cipher suites. For example, + TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 +*/ + + +#define SSL_ENABLE_RSA_GCM_SUITES 0x10 +/*!< + Enable RSA AEAD based Cipher suites. For example, + TLS_RSA_WITH_AES_128_GCM_SHA256 +*/ + + +#define SSL_ENABLE_DHE_GCM_SUITES 0x20 +/*!< + Enable DHE AEAD based Cipher suites. For example, + TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 +*/ + + +#define SSL_ENABLE_ALL_SUITES 0x0000003F +/*!< + Enable all possible supported cipher suites. +*/ + +//@} + + + +/** @defgroup SSLCipherSuiteID TLS Cipher Suite IDs + * @ingroup TLSDefines + * The following list of macros defined the list of supported TLS Cipher suites. + * Each MACRO defines a single Cipher suite. + * @sa m2m_ssl_set_active_ciphersuites + * @{ + */ + +#define SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA NBIT0 +#define SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 NBIT1 +#define SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA NBIT2 +#define SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 NBIT3 +#define SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 NBIT4 +#define SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 NBIT5 +#define SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA NBIT6 +#define SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 NBIT7 +#define SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA NBIT8 +#define SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 NBIT9 +#define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA NBIT10 +#define SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA NBIT11 +#define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 NBIT12 +#define SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 NBIT13 +#define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 NBIT14 +#define SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 NBIT15 + + + +#define SSL_ECC_ONLY_CIPHERS \ +(\ + SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 \ +) +/*!< + All ciphers that use ECC crypto only. This execuldes ciphers that use RSA. They use ECDSA instead. + These ciphers are turned off by default at startup. + The application may enable them if it has an ECC math engine (like ATECC508). +*/ +#define SSL_ECC_ALL_CIPHERS \ +(\ + SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA | \ + SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 | \ + SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 \ +) +/*!< + All supported ECC Ciphers including those ciphers that depend on RSA and ECC. + These ciphers are turned off by default at startup. + The application may enable them if it has an ECC math engine (like ATECC508). +*/ + +#define SSL_NON_ECC_CIPHERS_AES_128 \ +(\ + SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA | \ + SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA | \ + SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 | \ + SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 \ +) +/*!< + All supported AES-128 Ciphers (ECC ciphers are not counted). This is the default active group after startup. +*/ + + +#define SSL_ECC_CIPHERS_AES_256 \ +(\ + SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA \ +) +/*!< + ECC AES-256 supported ciphers. +*/ + + +#define SSL_NON_ECC_CIPHERS_AES_256 \ +(\ + SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA | \ + SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 | \ + SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA | \ + SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 \ +) +/*!< + AES-256 Ciphers. + This group is disabled by default at startup because the WINC1500 HW Accelerator + supports only AES-128. If the application needs to force AES-256 cipher support, + it could enable them (or any of them) explicitly by calling sslSetActiveCipherSuites. +*/ + + +#define SSL_CIPHER_ALL \ +(\ + SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA | \ + SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA | \ + SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 | \ + SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 | \ + SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA | \ + SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 | \ + SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA | \ + SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 | \ + SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA | \ + SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 | \ + SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \ + SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 | \ + SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA \ +) +/*!< + Turn On All TLS Ciphers. +*/ + + + //@} + + + + +/************** +Socket Errors +**************/ +/**@defgroup SocketErrorCode Error Codes + * @ingroup SocketHeader + * The following list of macros are used to define the possible error codes returned as a result of a call to a socket function. + * Errors are listed in numerical order with the error macro name. + * @{ + */ +#define SOCK_ERR_NO_ERROR 0 +/*!< + Successful socket operation +*/ + + +#define SOCK_ERR_INVALID_ADDRESS -1 +/*!< + Socket address is invalid. The socket operation cannot be completed successfully without specifying a specific address + For example: bind is called without specifying a port number +*/ + + +#define SOCK_ERR_ADDR_ALREADY_IN_USE -2 +/*!< + Socket operation cannot bind on the given address. With socket operations, only one IP address per socket is permitted. + Any attempt for a new socket to bind with an IP address already bound to another open socket, + will return the following error code. States that bind operation failed. +*/ + + +#define SOCK_ERR_MAX_TCP_SOCK -3 +/*!< + Exceeded the maximum number of TCP sockets. A maximum number of TCP sockets opened simultaneously is defined through TCP_SOCK_MAX. + It is not permitted to exceed that number at socket creation. Identifies that @ref socket operation failed. +*/ + + +#define SOCK_ERR_MAX_UDP_SOCK -4 +/*!< + Exceeded the maximum number of UDP sockets. A maximum number of UDP sockets opened simultaneously is defined through UDP_SOCK_MAX. + It is not permitted to exceed that number at socket creation. Identifies that @ref socket operation failed +*/ + + +#define SOCK_ERR_INVALID_ARG -6 +/*!< + An invalid argument is passed to a function. +*/ + + +#define SOCK_ERR_MAX_LISTEN_SOCK -7 +/*!< + Exceeded the maximum number of TCP passive listening sockets. + Identifies Identifies that @ref listen operation failed. +*/ + + +#define SOCK_ERR_INVALID -9 +/*!< + The requested socket operation is not valid in the + current socket state. + For example: @ref accept is called on a TCP socket before @ref bind or @ref listen. +*/ + + +#define SOCK_ERR_ADDR_IS_REQUIRED -11 +/*!< + Destination address is required. Failure to provide the socket address required for the socket operation to be completed. + It is generated as an error to the @ref sendto function when the address required to send the data to is not known. +*/ + + +#define SOCK_ERR_CONN_ABORTED -12 +/*!< + The socket is closed by the peer. The local socket is + closed also. +*/ + + +#define SOCK_ERR_TIMEOUT -13 +/*!< + The socket pending operation has Timedout. +*/ + + +#define SOCK_ERR_BUFFER_FULL -14 +/*!< + No buffer space available to be used for the requested socket operation. +*/ + +#ifdef _NM_BSP_BIG_END + +#define _htonl(m) (m) +#define _htons(A) (A) + +#else + +#define _htonl(m) \ + (uint32)(((uint32)(m << 24)) | ((uint32)((m & 0x0000FF00) << 8)) | ((uint32)((m & 0x00FF0000) >> 8)) | ((uint32)(m >> 24))) +/*!< + Convert a 4-byte integer from the host representation to the Network byte order representation. +*/ + + +#define _htons(A) (uint16)((((uint16) (A)) << 8) | (((uint16) (A)) >> 8)) +/*!< + Convert a 2-byte integer (short) from the host representation to the Network byte order representation. +*/ + + +#endif + + +#define _ntohl _htonl +/*!< + Convert a 4-byte integer from the Network byte order representation to the host representation . +*/ + + +#define _ntohs _htons +/*!< + Convert a 2-byte integer from the Network byte order representation to the host representation . +*/ + //@} + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/** @defgroup SocketEnums DataTypes + * @ingroup SocketHeader + * Specific Enumeration-typedefs used for socket operations + * @{ */ + +/*! +@typedef \ + SOCKET + +@brief + Definition for socket handler data type. + Socket ID,used with all socket operations to uniquely identify the socket handler. + Such an ID is uniquely assigned at socket creation when calling @ref socket operation. +*/ +typedef sint8 SOCKET; + + + +/*! +@struct \ + in_addr + +@brief + IPv4 address representation. + + This structure is used as a placeholder for IPV4 address in other structures. +@see + sockaddr_in +*/ +typedef struct{ + uint32 s_addr; + /*!< + Network Byte Order representation of the IPv4 address. For example, + the address "192.168.0.10" is represented as 0x0A00A8C0. + */ +}in_addr; + + +/*! +@struct \ + sockaddr + +@brief + Generic socket address structure. + +@see + sockaddr_in +*/ +struct sockaddr{ + uint16 sa_family; + /*!< +Socket address family. + */ + uint8 sa_data[14]; + /*!< + Maximum size of all the different socket address structures. + */ +}; + + +/*! +@struct \ + sockaddr_in + +@brief + Socket address structure for IPV4 addresses. Used to specify socket address information to which to connect to. + Can be cast to @ref sockaddr structure. +*/ +struct sockaddr_in{ + uint16 sin_family; + /*!< + Specifies the address family(AF). + Members of AF_INET address family are IPv4 addresses. + Hence,the only supported value for this is AF_INET. + */ + uint16 sin_port; + /*!< + Port number of the socket. + Network sockets are identified by a pair of IP addresses and port number. + It must be set in the Network Byte Order format , @ref _htons (e.g. _htons(80)). + Can NOT have zero value. + */ + in_addr sin_addr; + /*!< + IP Address of the socket. + The IP address is of type @ref in_addr structure. + Can be set to "0" to accept any IP address for server operation. non zero otherwise. + */ + uint8 sin_zero[8]; + /*!< + Padding to make structure the same size as @ref sockaddr. + */ +}; + //@} +/**@defgroup AsyncCalback Asynchronous Events + * @ingroup SocketEnums + * Specific Enumeration used for asynchronous operations + * @{ */ +/*! +@enum \ + tenuSocketCallbackMsgType + +@brief + Asynchronous APIs, make use of callback functions, in-order to return back the results once the corresponding socket operation is completed. + Hence resuming the normal execution of the application code while the socket operation returns the results. + Callback functions expect event messages to be passed in, in-order to identify the operation they're returning the results for. + The following enum identifies the type of events that are received in the callback function. + + Application Use: + In order for application developers to handle the pending events from the network controller through the callback functions. + A function call must be made to the function @ref m2m_wifi_handle_events at least once for each socket operation. + +@see + bind + listen + accept + connect + send + recv + +*/ +typedef enum{ + SOCKET_MSG_BIND = 1, + /*!< + Bind socket event. + */ + SOCKET_MSG_LISTEN, + /*!< + Listen socket event. + */ + SOCKET_MSG_DNS_RESOLVE, + /*!< + DNS Resolution event. + */ + SOCKET_MSG_ACCEPT, + /*!< + Accept socket event. + */ + SOCKET_MSG_CONNECT, + /*!< + Connect socket event. + */ + SOCKET_MSG_RECV, + /*!< + Receive socket event. + */ + SOCKET_MSG_SEND, + /*!< + Send socket event. + */ + SOCKET_MSG_SENDTO, + /*!< + sendto socket event. + */ + SOCKET_MSG_RECVFROM + /*!< + Recvfrom socket event. + */ +}tenuSocketCallbackMsgType; + + +/*! +@struct \ + tstrSocketBindMsg + +@brief Socket bind status. + + An asynchronous call to the @ref bind socket operation, returns information through this structure in response. + This structure together with the event @ref SOCKET_MSG_BIND are passed in paramters to the callback function. +@see + bind + +*/ +typedef struct{ + sint8 status; + /*!< + The result of the bind operation. + Holding a value of ZERO for a successful bind or otherwise a negative + error code corresponding to the type of error. + */ +}tstrSocketBindMsg; + + +/*! +@struct \ + tstrSocketListenMsg + +@brief Socket listen status. + + Socket listen information is returned through this structure in response to the asynchronous call to the @ref listen function. + This structure together with the event @ref SOCKET_MSG_LISTEN are passed-in parameters to the callback function. +@see + listen +*/ +typedef struct{ + sint8 status; + /*!< + Holding a value of ZERO for a successful listen or otherwise a negative + error code corresponding to the type of error. + */ +}tstrSocketListenMsg; + + + +/*! +@struct \ + tstrSocketAcceptMsg + +@brief Socket accept status. + + Socket accept information is returned through this structure in response to the asynchronous call to the @ref accept function. + This structure together with the event @ref SOCKET_MSG_ACCEPT are passed-in parameters to the callback function. +*/ +typedef struct{ + SOCKET sock; + /*!< + On a successful @ref accept operation, the return information is the socket ID for the accepted connection with the remote peer. + Otherwise a negative error code is returned to indicate failure of the accept operation. + */ + struct sockaddr_in strAddr; + /*!< + Socket address structure for the remote peer. + */ +}tstrSocketAcceptMsg; + + +/*! +@struct \ + tstrSocketConnectMsg + +@brief Socket connect status. + + Socket connect information is returned through this structure in response to the asynchronous call to the @ref connect socket function. + This structure together with the event @ref SOCKET_MSG_CONNECT are passed-in parameters to the callback function. +*/ +typedef struct{ + SOCKET sock; + /*!< + Socket ID referring to the socket passed to the connect function call. + */ + sint8 s8Error; + /*!< + Connect error code. + Holding a value of ZERO for a successful connect or otherwise a negative + error code corresponding to the type of error. + */ +}tstrSocketConnectMsg; + + +/*! +@struct \ + tstrSocketRecvMsg + +@brief Socket recv status. + + Socket receive information is returned through this structure in response to the asynchronous call to the recv or recvfrom socket functions. + This structure together with the events @ref SOCKET_MSG_RECV or @ref SOCKET_MSG_RECVFROM are passed-in parameters to the callback function. +@remark + In case the received data from the remote peer is larger than the USER buffer size defined during the asynchronous call to the @ref recv function, the data is + delivered to the user in a number of consecutive chunks according to the USER Buffer size. + a negative or zero buffer size indicates an error with the following code: + @ref SOCK_ERR_NO_ERROR : Socket connection closed + @ref SOCK_ERR_CONN_ABORTED : Socket connection aborted + @SOCK_ERR_TIMEOUT : Socket receive timed out +*/ +typedef struct{ + uint8 *pu8Buffer; + /*!< + Pointer to the USER buffer (passed to @ref recv and @ref recvfrom function) containing the received data chunk. + */ + sint16 s16BufferSize; + /*!< + The received data chunk size. + Holds a negative value if there is a receive error or ZERO on success upon reception of close socket message. + */ + uint16 u16RemainingSize; + /*!< + The number of bytes remaining in the current @ref recv operation. + */ + struct sockaddr_in strRemoteAddr; + /*!< + Socket address structure for the remote peer. It is valid for @ref SOCKET_MSG_RECVFROM event. + */ +}tstrSocketRecvMsg; + + +/*! +@typedef \ + tpfAppSocketCb + +@brief + The main socket application callback function. Applications register their main socket application callback through this function by calling @ref registerSocketCallback. + In response to events received, the following callback function is called to handle the corresponding asynchronous function called. Example: @ref bind, @ref connect,...etc. + +@param [in] sock + Socket ID for the callback. + + The socket callback function is called whenever a new event is recived in response + to socket operations. + +@param [in] u8Msg + Socket event type. Possible values are: + - @ref SOCKET_MSG_BIND + - @ref SOCKET_MSG_LISTEN + - @ref SOCKET_MSG_ACCEPT + - @ref SOCKET_MSG_CONNECT + - @ref SOCKET_MSG_RECV + - @ref SOCKET_MSG_SEND + - @ref SOCKET_MSG_SENDTO + - @ref SOCKET_MSG_RECVFROM + +@param [in] pvMsg + Pointer to message structure. Existing types are: + - tstrSocketBindMsg + - tstrSocketListenMsg + - tstrSocketAcceptMsg + - tstrSocketConnectMsg + - tstrSocketRecvMsg + +@see + tenuSocketCallbackMsgType + tstrSocketRecvMsg + tstrSocketConnectMsg + tstrSocketAcceptMsg + tstrSocketListenMsg + tstrSocketBindMsg +*/ +typedef void (*tpfAppSocketCb) (SOCKET sock, uint8 u8Msg, void * pvMsg); + + +/*! +@typedef \ + tpfAppResolveCb + +@brief + DNS resolution callback function. + Applications requiring DNS resolution should register their callback through this function by calling @ref registerSocketCallback. + The following callback is triggered in response to asynchronous call to the @ref gethostbyname function (DNS Resolution callback). + +@param [in] pu8DomainName + Domain name of the host. + +@param [in] u32ServerIP + Server IPv4 address encoded in NW byte order format. If it is Zero, then the DNS resolution failed. +*/ +typedef void (*tpfAppResolveCb) (uint8* pu8DomainName, uint32 u32ServerIP); + +/*! +@typedef \ + tpfPingCb + +@brief PING Callback + + The function delivers the ping statistics for the sent ping triggered by calling + m2m_ping_req. + +@param [in] u32IPAddr + Destination IP. + +@param [in] u32RTT + Round Trip Time. + +@param [in] u8ErrorCode + Ping error code. It may be one of: + - PING_ERR_SUCCESS + - PING_ERR_DEST_UNREACH + - PING_ERR_TIMEOUT +*/ +typedef void (*tpfPingCb)(uint32 u32IPAddr, uint32 u32RTT, uint8 u8ErrorCode); + + /**@}*/ +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/** \defgroup SocketAPI Function + * @ingroup SocketHeader + */ + +/** @defgroup SocketInitalizationFn socketInit + * @ingroup SocketAPI + * The function performs the necessary initializations for the socket library through the following steps: + - A check made by the global variable gbSocketInit, ensuring that initialization for sockets is performed only once, + in-order to prevent reseting the socket instances already created in the global socket array (gastrSockets). + - Zero initializations to the global socket array (gastrSockets), which holds the list of TCP sockets. + - Registers the socket (Host Interface)hif callback function through the call to the hif_register_cb function. + This facilitates handling all of the socket related functions received through interrupts from the firmware. + + */ + /**@{*/ +/*! +@fn \ + NMI_API void socketInit(void); + +@param [in] void + +@return void + +@remarks + This initialization function must be invoked before any socket operation is performed. + No error codes from this initialization function since the socket array is statically allocated based in the maximum number of + sockets @ref MAX_SOCKET based on the systems capability. +\section Example +This example demonstrates the use of the socketinit for socket initialization for an mqtt chat application. + \code + tstrWifiInitParam param; + int8_t ret; + char topic[strlen(MAIN_CHAT_TOPIC) + MAIN_CHAT_USER_NAME_SIZE + 1]; + + //Initialize the board. + system_init(); + + //Initialize the UART console. + configure_console(); + + // Initialize the BSP. + nm_bsp_init(); + + ---------- + + // Initialize socket interface. + socketInit(); + registerSocketCallback(socket_event_handler, socket_resolve_handler); + + // Connect to router. + m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), + MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); + +\endcode +*/ +NMI_API void socketInit(void); + + +/*! +@fn \ + NMI_API void socketDeinit(void); + +@brief Socket Layer De-initialization + + The function performs the necessary cleanup for the socket library static data + It must be invoked as the last any socket operation is performed on any active sockets. +*/ +NMI_API void socketDeinit(void); + + +/** @} */ +/** @defgroup SocketCallbackFn registerSocketCallback + * @ingroup SocketAPI + Register two callback functions one for asynchronous socket events and the other one for DNS callback registering function. + The registered callback functions are used to retrieve information in response to the asynchronous socket functions called. + */ + /**@{*/ + + +/*! +@fn \ + NMI_API void registerSocketCallback(tpfAppSocketCb socket_cb, tpfAppResolveCb resolve_cb); + +@param [in] tpfAppSocketCb + Assignment of callback function to the global callback @ref tpfAppSocketCb gpfAppSocketCb. Delivers + socket messages to the host application. In response to the asynchronous function calls, such as @ref bind + @ref listen @ref accept @ref connect + +@param [in] tpfAppResolveCb + Assignment of callback function to the global callback @ref tpfAppResolveCb gpfAppResolveCb. + Used for DNS resolving functionalities. The DNS resolving technique is determined by the application + registering the callback. + NULL is assigned when, DNS resolution is not required. + +@return void +@remarks + If any of the socket functionalities is not to be used, NULL is passed in as a parameter. + It must be invoked after socketinit and before other socket layer operations. + +\section Example + This example demonstrates the use of the registerSocketCallback to register a socket callback function with DNS resolution CB set to null + for a simple UDP server example. + \code + tstrWifiInitParam param; + int8_t ret; + struct sockaddr_in addr; + + // Initialize the board + system_init(); + + //Initialize the UART console. + configure_console(); + + // Initialize the BSP. + nm_bsp_init(); + + // Initialize socket address structure. + addr.sin_family = AF_INET; + addr.sin_port = _htons(MAIN_WIFI_M2M_SERVER_PORT); + addr.sin_addr.s_addr = _htonl(MAIN_WIFI_M2M_SERVER_IP); + + // Initialize Wi-Fi parameters structure. + memset((uint8_t *)¶m, 0, sizeof(tstrWifiInitParam)); + + // Initialize Wi-Fi driver with data and status callbacks. + param.pfAppWifiCb = wifi_cb; + ret = m2m_wifi_init(¶m); + if (M2M_SUCCESS != ret) { + printf("main: m2m_wifi_init call error!(%d)\r\n", ret); + while (1) { + } + } + + // Initialize socket module + socketInit(); + registerSocketCallback(socket_cb, NULL); + + // Connect to router. + m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); + \endcode +*/ +NMI_API void registerSocketCallback(tpfAppSocketCb socket_cb, tpfAppResolveCb resolve_cb); + + +/** @} */ + +/** @defgroup SocketFn socket + * @ingroup SocketAPI + * Synchronous socket allocation function based on the specified socket type. Created sockets are non-blocking and their possible types are either TCP or a UDP sockets. + * The maximum allowed number of TCP sockets is @ref TCP_SOCK_MAX sockets while the maximum number of UDP sockets that can be created simultaneously is @ref UDP_SOCK_MAX sockets. + * +*/ + /**@{*/ +/*! +@fn \ + NMI_API SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags); + + +@param [in] u16Domain + Socket family. The only allowed value is AF_INET (IPv4.0) for TCP/UDP sockets. + +@param [in] u8Type + Socket type. Allowed values are: + - [SOCK_STREAM](@ref SOCK_STREAM) + - [SOCK_DGRAM](@ref SOCK_DGRAM) + +@param [in] u8Flags + Used to specify the socket creation flags. It shall be set to zero for normal TCP/UDP sockets. + It could be @ref SOCKET_FLAGS_SSL if the socket is used for SSL session. The use of the flag + @ref SOCKET_FLAGS_SSL has no meaning in case of UDP sockets. + +@pre + The @ref socketInit function must be called once at the beginning of the application to initialize the socket handler. + before any call to the socket function can be made. + +@see + connect + bind + listen + accept + recv + recvfrom + send + sendto + close + setsockopt + getsockopt + +@return + On successful socket creation, a non-blocking socket type is created and a socket ID is returned + In case of failure the function returns a negative value, identifying one of the socket error codes defined. + For example: @ref SOCK_ERR_INVALID for invalid argument or + @ref SOCK_ERR_MAX_TCP_SOCK if the number of TCP allocated sockets exceeds the number of available sockets. + +@remarks + The socket function must be called a priori to any other related socket functions "e.g. send, recv, close ..etc" +\section Example + This example demonstrates the use of the socket function to allocate the socket, returning the socket handler to be used for other +socket operations. Socket creation is dependent on the socket type. +\subsection sub1 UDP example +@code + SOCKET UdpServerSocket = -1; + + UdpServerSocket = socket(AF_INET, SOCK_DGRAM, 0); + +@endcode +\subsection sub2 TCP example +@code + static SOCKET tcp_client_socket = -1; + + tcp_client_socket = socket(AF_INET, SOCK_STREAM, 0)); +@endcode +\subsection sub3 SSL example +@code +static SOCKET ssl_socket = -1; + +ssl_socket = socket(AF_INET, SOCK_STREAM, SOCK_FLAGS_SSL)); +@endcode +*/ +NMI_API SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags); + + +/** @} */ +/** @defgroup BindFn bind + * @ingroup SocketAPI +* Asynchronous bind function associates the provided address and local port to the socket. +* The function can be used with both TCP and UDP sockets it's mandatory to call the @ref bind function before starting any UDP or TCP server operation. +* Upon socket bind completion, the application will receive a @ref SOCKET_MSG_BIND message in the socket callback. +*/ + /**@{*/ +/*! +\fn \ + NMI_API sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); + + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] pstrAddr + Pointer to socket address structure "sockaddr_in" + [sockaddr_in](@ref sockaddr_in) + + +@param [in] u8AddrLen + Size of the given socket address structure in bytes. + +@pre + The socket function must be called to allocate a socket before passing the socket ID to the bind function. + +@see + socket + connect + listen + accept + recv + recvfrom + send + sendto + +@return + The function returns ZERO for successful operations and a negative value otherwise. + The possible error values are: + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + Indicating that the operation was successful. + + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) + Indicating passing invalid arguments such as negative socket ID or NULL socket address structure. + + - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID) + Indicate socket bind failure. +\section Example + This example demonstrates the call of the bind socket operation after a successful socket operation. +@code + struct sockaddr_in addr; + SOCKET udpServerSocket =-1; + int ret = -1; + + if(udpServerSocket == -1) + { + udpServerSocket = socket(AF_INET, SOCK_DGRAM, 0); + if(udpServerSocket >= 0) + { + addr.sin_family = AF_INET; + addr.sin_port = _htons(1234); + addr.sin_addr.s_addr = 0; + ret = bind(udpServerSocket,(struct sockaddr*)&addr,sizeof(addr)); + + if(ret != 0) + { + printf("Bind Failed. Error code = %d\n",ret); + close(udpServerSocket); + } + } + else + { + printf("UDP Server Socket Creation Failed\n"); + return; + } + } +@endcode +*/ +NMI_API sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); + + +/** @} */ + +/** @defgroup ListenFn listen + * @ingroup SocketAPI + * After successful socket binding to an IP address and port on the system, start listening on a passive socket for incoming connections. + The socket must be bound on a local port or the listen operation fails. + Upon the call to the asynchronous listen function, response is received through the event [SOCKET_MSG_BIND](@ref SOCKET_MSG_BIND) + in the socket callback. + A successful listen means the TCP server operation is active. If a connection is accepted, then the application socket callback function is + notified with the new connected socket through the event @ref SOCKET_MSG_ACCEPT. Hence there is no need to call the @ref accept function + after calling @ref listen. + + After a connection is accepted, the user is then required to call the @ref recv to receive any packets transmitted by the remote host or to receive notification of socket connection + termination. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 listen(SOCKET sock, uint8 backlog); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] backlog + Not used by the current implementation. + +@pre + The bind function must be called to assign the port number and IP address to the socket before the listen operation. + +@see + bind + accept + recv + recvfrom + send + sendto + +@return + The function returns ZERO for successful operations and a negative value otherwise. + The possible error values are: + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + Indicating that the operation was successful. + + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) + Indicating passing invalid arguments such as negative socket ID. + + - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID) + Indicate socket listen failure. +\section Example +This example demonstrates the call of the listen socket operation after a successful socket operation. +@code + static void TCP_Socketcallback(SOCKET sock, uint8 u8Msg, void * pvMsg) + { + int ret =-1; + + switch(u8Msg) + { + case SOCKET_MSG_BIND: + { + tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg; + if(pstrBind != NULL) + { + if(pstrBind->status == 0) + { + ret = listen(sock, 0); + + if(ret <0) + printf("Listen failure! Error = %d\n",ret); + } + else + { + M2M_ERR("bind Failure!\n"); + close(sock); + } + } + } + break; + + case SOCKET_MSG_LISTEN: + { + + tstrSocketListenMsg *pstrListen = (tstrSocketListenMsg*)pvMsg; + if(pstrListen != NULL) + { + if(pstrListen->status == 0) + { + ret = accept(sock,NULL,0); + } + else + { + M2M_ERR("listen Failure!\n"); + close(sock); + } + } + } + break; + + case SOCKET_MSG_ACCEPT: + { + tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg*)pvMsg; + + if(pstrAccept->sock >= 0) + { + TcpNotificationSocket = pstrAccept->sock; + recv(pstrAccept->sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT); + } + else + { + M2M_ERR("accept failure\n"); + } + } + break; + + default: + break; + } + } + +@endcode +*/ +NMI_API sint8 listen(SOCKET sock, uint8 backlog); +/** @} */ +/** @defgroup AcceptFn accept + * @ingroup SocketAPI + * The function has no current implementation. An empty deceleration is used to prevent errors when legacy application code is used. + * For recent application use, the accept function can be safer as it has no effect and could be safely removed from any application using it. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. +@param [in] addr + Not used in the current implementation. + +@param [in] addrlen + Not used in the current implementation. + +@return + The function returns ZERO for successful operations and a negative value otherwise. + The possible error values are: + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + Indicating that the operation was successful. + + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) + Indicating passing invalid arguments such as negative socket ID. +*/ +NMI_API sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen); +/** @} */ +/** @defgroup ConnectFn connect + * @ingroup SocketAPI + * Establishes a TCP connection with a remote server. + The asynchronous connect function must be called after receiving a valid socket ID from the @ref socket function. + The application socket callback function is notified of a successful new socket connection through the event @ref SOCKET_MSG_CONNECT. + A successful connect means the TCP session is active. The application is then required to make a call to the @ref recv + to receive any packets transmitted by the remote server, unless the application is interrupted by a notification of socket connection + termination. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] pstrAddr + Address of the remote server. +@param [in] pstrAddr + Pointer to socket address structure "sockaddr_in" + [sockaddr_in](@ref sockaddr_in) + +@param [in] u8AddrLen + Size of the given socket address structure in bytes. + Not currently used, implemented for BSD compatibility only. +@pre + The socket function must be called to allocate a TCP socket before passing the socket ID to the bind function. + If the socket is not bound, you do NOT have to call bind before the "connect" function. + +@see + socket + recv + send + close + +@return + The function returns ZERO for successful operations and a negative value otherwise. + The possible error values are: + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + Indicating that the operation was successful. + + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) + Indicating passing invalid arguments such as negative socket ID or NULL socket address structure. + + - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID) + Indicate socket connect failure. +\section Example + The example demonstrates a TCP application, showing how the asynchronous call to the connect function is made through the main function and how the + callback function handles the @ref SOCKET_MSG_CONNECT event. +\subsection sub1 Main Function +@code + struct sockaddr_in Serv_Addr; + SOCKET TcpClientSocket =-1; + int ret = -1 + + TcpClientSocket = socket(AF_INET,SOCK_STREAM,0); + Serv_Addr.sin_family = AF_INET; + Serv_Addr.sin_port = _htons(1234); + Serv_Addr.sin_addr.s_addr = inet_addr(SERVER); + printf("Connected to server via socket %u\n",TcpClientSocket); + + do + { + ret = connect(TcpClientSocket,(sockaddr_in*)&Serv_Addr,sizeof(Serv_Addr)); + if(ret != 0) + { + printf("Connection Error\n"); + } + else + { + printf("Connection successful.\n"); + break; + } + }while(1) +@endcode +\subsection sub2 Socket Callback +@code + if(u8Msg == SOCKET_MSG_CONNECT) + { + tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg*)pvMsg; + if(pstrConnect->s8Error == 0) + { + uint8 acBuffer[GROWL_MSG_SIZE]; + uint16 u16MsgSize; + + printf("Connect success!\n"); + + u16MsgSize = FormatMsg(u8ClientID, acBuffer); + send(sock, acBuffer, u16MsgSize, 0); + recv(pstrNotification->Socket, (void*)au8Msg,GROWL_DESCRIPTION_MAX_LENGTH, GROWL_RX_TIMEOUT); + u8Retry = GROWL_CONNECT_RETRY; + } + else + { + M2M_DBG("Connection Failed, Error: %d\n",pstrConnect->s8Error"); + close(pstrNotification->Socket); + } + } +@endcode +*/ +#ifdef ARDUINO +NMI_API sint8 connectSocket(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); +#else +NMI_API sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); +#endif +/** @} */ +/** @defgroup ReceiveFn recv + * @ingroup SocketAPI + * An asynchronous receive function, used to retrieve data from a TCP stream. + Before calling the recv function, a successful socket connection status must have been received through any of the two socket events + [SOCKET_MSG_CONNECT] or [SOCKET_MSG_ACCEPT], from the socket callback. Hence, indicating that the socket is already connected to a remote + host. + The application receives the required data in response to this asynchronous call through the reception of the event @ref SOCKET_MSG_RECV in the + socket callback. + + Receiving the SOCKET_MSG_RECV message in the callback with zero or negative buffer length indicates the following: + - SOCK_ERR_NO_ERROR : Socket connection closed + - SOCK_ERR_CONN_ABORTED : Socket connection aborted + - SOCK_ERR_TIMEOUT : Socket receive timed out + The application code is expected to close the socket through the call to the @ref close function upon the appearance of the above mentioned errors. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + + +@param [in] pvRecvBuf + Pointer to a buffer that will hold the received data. The buffer is used + in the recv callback to deliver the received data to the caller. The buffer must + be resident in memory (heap or global buffer). + +@param [in] u16BufLen + The buffer size in bytes. + +@param [in] u32Timeoutmsec + Timeout for the recv function in milli-seconds. If the value is set to ZERO, the timeout + will be set to infinite (the recv function waits forever). If the timeout period is + elapsed with no data received, the socket will get a timeout error. +@pre + - The socket function must be called to allocate a TCP socket before passing the socket ID to the recv function. + - The socket in a connected state is expected to receive data through the socket interface. + +@see + socket + connect + bind + listen + recvfrom + close + + +@return + The function returns ZERO for successful operations and a negative value otherwise. + The possible error values are: + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + Indicating that the operation was successful. + + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) + Indicating passing invalid arguments such as negative socket ID or NULL Recieve buffer. + + - [SOCK_ERR_BUFFER_FULL](@ref SOCK_ERR_BUFFER_FULL) + Indicate socket receive failure. +\section Example + The example demonstrates a code snippet for the calling of the recv function in the socket callback upon notification of the accept or connect events, and the parsing of the + received data when the SOCKET_MSG_RECV event is received. +@code + + switch(u8Msg) + { + + case SOCKET_MSG_ACCEPT: + { + tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg*)pvMsg; + + if(pstrAccept->sock >= 0) + { + recv(pstrAccept->sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT); + } + else + { + M2M_ERR("accept\n"); + } + } + break; + + + case SOCKET_MSG_RECV: + { + tstrSocketRecvMsg *pstrRx = (tstrSocketRecvMsg*)pvMsg; + + if(pstrRx->s16BufferSize > 0) + { + + recv(sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT); + } + else + { + printf("Socet recv Error: %d\n",pstrRx->s16BufferSize); + close(sock); + } + } + break; + + default: + break; + } +} +@endcode +*/ +NMI_API sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec); +/** @} */ +/** @defgroup ReceiveFromSocketFn recvfrom + * @ingroup SocketAPI + * Receives data from a UDP Socket. +* +* The asynchronous recvfrom function is used to retrieve data from a UDP socket. The socket must already be bound to +* a local port before a call to the recvfrom function is made (i.e message @ref SOCKET_MSG_BIND is received +* with successful status in the socket callback). +* +* Upon calling the recvfrom function with a successful return code, the application is expected to receive a notification +* in the socket callback whenever a message is received through the @ref SOCKET_MSG_RECVFROM event. +* +* Receiving the SOCKET_MSG_RECVFROM message in the callback with zero, indicates that the socket is closed. +* Whereby a negative buffer length indicates one of the socket error codes such as socket timeout error @SOCK_ERR_TIMEOUT: +* +* The recvfrom callback can also be used to show the IP address of the remote host that sent the frame by +* using the "strRemoteAddr" element in the @ref tstrSocketRecvMsg structure. (refer to the code example) + */ + /**@{*/ +/*! +@fn \ + NMI_API sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32TimeoutSeconds); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] pvRecvBuf + Pointer to a buffer that will hold the received data. The buffer shall be used + in the recv callback to deliver the received data to the caller. The buffer must + be resident in memory (heap or global buffer). + +@param [in] u16BufLen + The buffer size in bytes. + +@param [in] u32TimeoutSeconds + Timeout for the recv function in milli-seconds. If the value is set to ZERO, the timeout + will be set to infinite (the recv function waits forever). + +@pre + - The socket function must be called to allocate a UDP socket before passing the socket ID to the recvfrom function. + - The socket corresponding to the socket ID must be successfully bound to a local port through the call to a @ref bind function. + +@see + socket + bind + close + +@return + The function returns ZERO for successful operations and a negative value otherwise. + The possible error values are: + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + Indicating that the operation was successful. + + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) + Indicating passing invalid arguments such as negative socket ID or NULL Receive buffer. + + - [SOCK_ERR_BUFFER_FULL](@ref SOCK_ERR_BUFFER_FULL) + Indicate socket receive failure. +\section Example + The example demonstrates a code snippet for the calling of the recvfrom function in the socket callback upon notification of a successful bind event, and the parsing of the + received data when the SOCKET_MSG_RECVFROM event is received. +@code + switch(u8Msg) + { + + case SOCKET_MSG_BIND: + { + tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg; + + if(pstrBind != NULL) + { + if(pstrBind->status == 0) + { + recvfrom(sock, gau8SocketTestBuffer, TEST_BUFFER_SIZE, 0); + } + else + { + M2M_ERR("bind\n"); + } + } + } + break; + + + case SOCKET_MSG_RECVFROM: + { + tstrSocketRecvMsg *pstrRx = (tstrSocketRecvMsg*)pvMsg; + + if(pstrRx->s16BufferSize > 0) + { + //get the remote host address and port number + uint16 u16port = pstrRx->strRemoteAddr.sin_port; + uint32 strRemoteHostAddr = pstrRx->strRemoteAddr.sin_addr.s_addr; + + printf("Recieved frame with size = %d.\tHost address=%x, Port number = %d\n\n",pstrRx->s16BufferSize,strRemoteHostAddr, u16port); + + ret = recvfrom(sock,gau8SocketTestBuffer,sizeof(gau8SocketTestBuffer),TEST_RECV_TIMEOUT); + } + else + { + printf("Socet recv Error: %d\n",pstrRx->s16BufferSize); + ret = close(sock); + } + } + break; + + default: + break; + } +} +@endcode +*/ +NMI_API sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec); +/** @} */ +/** @defgroup SendFn send + * @ingroup SocketAPI +* Asynchronous sending function, used to send data on a TCP/UDP socket. + +* Called by the application code when there is outgoing data available required to be sent on a specific socket handler. +* The only difference between this function and the similar @ref sendto function, is the type of socket the data is sent on and the parameters passed in. +* @ref send function is most commonly called for sockets in a connected state. +* After the data is sent, the socket callback function registered using registerSocketCallback(), is expected to receive an event of type +* @ref SOCKET_MSG_SEND holding information containing the number of data bytes sent. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 u16Flags); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] pvSendBuffer + Pointer to a buffer holding data to be transmitted. + +@param [in] u16SendLength + The buffer size in bytes. + +@param [in] u16Flags + Not used in the current implementation. + +@pre + Sockets must be initialized using socketInit. \n + + For TCP Socket:\n + Must use a successfully connected Socket (so that the intended recipient address is known ahead of sending the data). + Hence this function is expected to be called after a successful socket connect operation(in client case or accept in the + the server case).\n + + For UDP Socket:\n + UDP sockets most commonly use @ref sendto function, where the destination address is defined. However, in-order to send outgoing data + using the @ref send function, at least one successful call must be made to the @ref sendto function a priori the consecutive calls to the @ref send function, + to ensure that the destination address is saved in the firmware. + +@see + socketInit + recv + sendto + socket + connect + accept + sendto + +@warning + u16SendLength must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. \n + Use a valid socket identifier through the a prior call to the @ref socket function. + Must use a valid buffer pointer. + Successful completion of a call to send() does not guarantee delivery of the message, + A negative return value indicates only locally-detected errors + + +@return + The function shall return @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise. +*/ +NMI_API sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 u16Flags); +/** @} */ +/** @defgroup SendToSocketFn sendto + * @ingroup SocketAPI +* Asynchronous sending function, used to send data on a UDP socket. +* Called by the application code when there is data required to be sent on a UDP socket handler. +* The application code is expected to receive data from a successful bounded socket node. +* The only difference between this function and the similar @ref send function, is the type of socket the data is received on. This function works +* only with UDP sockets. +* After the data is sent, the socket callback function registered using registerSocketCallback(), is expected to receive an event of type +* @ref SOCKET_MSG_SENDTO. +*/ + /**@{*/ +/*! +@fn \ + NMI_API sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] pvSendBuffer + Pointer to a buffer holding data to be transmitted. + A NULL value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@param [in] u16SendLength + The buffer size in bytes. It must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. + +@param [in] flags + Not used in the current implementation + +@param [in] pstrDestAddr + The destination address. + +@param [in] u8AddrLen + Destination address length in bytes. + Not used in the current implementation, only included for BSD compatibility. +@pre + Sockets must be initialized using socketInit. + +@see + socketInit + recvfrom + sendto + socket + connect + accept + send + +@warning + u16SendLength must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. \n + Use a valid socket (returned from socket ). + A valid buffer pointer must be used (not NULL). \n + Successful completion of a call to sendto() does not guarantee delivery of the message, + A negative return value indicates only locally-detected errors + +@return + The function returns @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise. +*/ +NMI_API sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen); +/** @} */ +/** @defgroup CloseSocketFn close + * @ingroup SocketAPI + * Synchronous close function, releases all the socket assigned resources. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 close(SOCKET sock); + +@param [in] sock + Socket ID, must hold a non negative value. + A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. + +@pre + Sockets must be initialized through the call of the socketInit function. + @ref close is called only for valid socket identifiers created through the @ref socket function. + +@warning + If @ref close is called while there are still pending messages (sent or received ) they will be discarded. + +@see + socketInit + socket + +@return + The function returned @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise. +*/ +NMI_API sint8 close(SOCKET sock); + + +/** @} */ +/** @defgroup InetAddressFn nmi_inet_addr +* @ingroup SocketAPI +* Synchronous function which returns a BSD socket compliant Internet Protocol (IPv4) socket address. +* This IPv4 address in the input string parameter could either be specified as a host name, or as a numeric string representation like n.n.n.n known as the IPv4 dotted-decimal format +* (i.e. "192.168.10.1"). +* This function is used whenever an ip address needs to be set in the proper format +* (i.e. for the @ref tstrM2MIPConfig structure). +*/ + /**@{*/ +/*! +@fn \ + NMI_API uint32 nmi_inet_addr(char *pcIpAddr); + +@param [in] pcIpAddr + A null terminated string containing the IP address in IPv4 dotted-decimal address. + +@return + Unsigned 32-bit integer representing the IP address in Network byte order + (eg. "192.168.10.1" will be expressed as 0x010AA8C0). + +*/ +NMI_API uint32 nmi_inet_addr(char *pcIpAddr); + + +/** @} */ +/** @defgroup gethostbynameFn gethostbyname + * @ingroup SocketAPI +* Asynchronous DNS resolving function. This function use DNS to resolve a domain name into the corresponding IP address. +* A call to this function will cause a DNS request to be sent and the response will be delivered to the DNS callback function registered using registerSocketCallback() + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 gethostbyname(uint8 * pcHostName); + +@param [in] pcHostName + NULL terminated string containing the domain name for the remote host. + Its size must not exceed [HOSTNAME_MAX_SIZE](@ref HOSTNAME_MAX_SIZE). + +@see + registerSocketCallback + +@warning + Successful completion of a call to gethostbyname() does not guarantee success of the DNS request, + a negative return value indicates only locally-detected errors + +@return + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) + - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) +*/ +NMI_API sint8 gethostbyname(uint8 * pcHostName); + + +/** @} */ +/** @defgroup sslEnableCertExpirationCheckFn sslEnableCertExpirationCheck + * @ingroup SocketAPI +* Configure the behavior of the SSL Library for Certificate Expiry Validation. + */ + /**@{*/ +/*! +@fn \ +NMI_API sint8 sslEnableCertExpirationCheck(tenuSslCertExpSettings enuValidationSetting); + +@param [in] enuValidationSetting + See @ref tenuSslCertExpSettings for details. + +@return + - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) for successful operation and negative error code otherwise. + +@sa tenuSslCertExpSettings +*/ +NMI_API sint8 sslEnableCertExpirationCheck(tenuSslCertExpSettings enuValidationSetting); + + +/** @} */ + +/** @defgroup SetSocketOptionFn setsockopt + * @ingroup SocketAPI +*The setsockopt() function shall set the option specified by the option_name +* argument, at the protocol level specified by the level argument, to the value +* pointed to by the option_value argument for the socket specified by the socket argument. +* +*

Possible protocol level values supported are @ref SOL_SOCKET and @ref SOL_SSL_SOCKET. +* Possible options when the protocol level is @ref SOL_SOCKET :

+* +* +* +* +* +* +* +* +* +* +* +* +* +*
@ref SO_SET_UDP_SEND_CALLBACKEnable/Disable callback messages for sendto(). +* Since UDP is unreliable by default the user maybe interested (or not) in +* receiving a message of @ref SOCKET_MSG_SENDTO for each call of sendto(). +* Enabled if option value equals @ref TRUE, disabled otherwise.
@ref IP_ADD_MEMBERSHIPValid for UDP sockets. This option is used to receive frames sent to +* a multicast group. option_value shall be a pointer to Unsigned 32-bit +* integer containing the multicast IPv4 address.
@ref IP_DROP_MEMBERSHIPValid for UDP sockets. This option is used to stop receiving frames +* sent to a multicast group. option_value shall be a pointer to Unsigned +* 32-bit integer containing the multicast IPv4 address.
+*

Possible options when the protcol leve  is @ref SOL_SSL_SOCKET

+* +* +* +* +* +* +* +* +* +* +* +* +* +*
+* @ref SO_SSL_BYPASS_X509_VERIFAllow an opened SSL socket to bypass the X509 +* certificate verification process. It is highly recommended NOT to use +* this socket option in production software applications. The option is +* supported for debugging and testing purposes. The option value should be +* casted to int type and it is handled as a boolean flag.
@ref SO_SSL_SNISet the Server Name Indicator (SNI) for an SSL socket. The SNI is a +* null terminated string containing the server name associated with the +* connection. It must not exceed the size of @ref HOSTNAME_MAX_SIZE.
@ref SO_SSL_ENABLE_SESSION_CACHINGThis option allow the TLS to cache the session information for fast +* TLS session establishment in future connections using the TLS Protocol +* session resume features.
+ */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 setsockopt(SOCKET socket, uint8 u8Level, uint8 option_name, + const void *option_value, uint16 u16OptionLen); + +@param [in] sock + Socket handler. + +@param [in] level + protocol level. See description above. + +@param [in] option_name + option to be set. See description above. + +@param [in] option_value + pointer to user provided value. + +@param [in] option_len + length of the option value in bytes. +@return + The function shall return \ref SOCK_ERR_NO_ERROR for successful operation + and a negative value (indicating the error) otherwise. +@sa SOL_SOCKET, SOL_SSL_SOCKET, IP_ADD_MEMBERSHIP, IP_DROP_MEMBERSHIP +*/ +NMI_API sint8 setsockopt(SOCKET socket, uint8 u8Level, uint8 option_name, + const void *option_value, uint16 u16OptionLen); + + +/** @} */ +/** @defgroup GetSocketOptionsFn getsockopt + * @ingroup SocketAPI + * Get socket options retrieves +* This Function isn't implemented yet but this is the form that will be released later. + */ + /**@{*/ +/*! +@fn \ + sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8 * pu8OptLen); + +@brief + +@param [in] sock + Socket Identifie. +@param [in] u8Level + The protocol level of the option. +@param [in] u8OptName + The u8OptName argument specifies a single option to get. +@param [out] pvOptValue + The pvOptValue argument contains pointer to a buffer containing the option value. +@param [out] pu8OptLen + Option value buffer length. +@return + The function shall return ZERO for successful operation and a negative value otherwise. +*/ +NMI_API sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8* pu8OptLen); +/** @} */ + +/**@}*/ +/** @defgroup PingFn m2m_ping_req + * @ingroup SocketAPI + * The function sends ping request to the given IP Address. + */ + /**@{*/ +/*! +@fn \ + NMI_API sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb); + +@param [in] u32DstIP + Target Destination IP Address for the ping request. It must be represented in Network byte order. + The function nmi_inet_addr could be used to translate the dotted decimal notation IP + to its Network bytes order integer represntative. + +@param [in] u8TTL + IP TTL value for the ping request. If set to ZERO, the dfault value SHALL be used. + +@param [in] fpPingCb + Callback will be called to deliver the ping statistics. + +@see nmi_inet_addr +@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. +*/ +NMI_API sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb); +/**@}*/ + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* __SOCKET_H__ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/socket_buffer.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/socket_buffer.h new file mode 100644 index 0000000..d93a7c8 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/socket_buffer.h @@ -0,0 +1,94 @@ +/** + * + * \file + * + * \brief BSD compatible socket interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifndef __SOCKET_BUFFER_H__ +#define __SOCKET_BUFFER_H__ + +#include "socket/include/socket.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define SOCKET_BUFFER_UDP_HEADER_SIZE (8) + +#if defined LIMITED_RAM_DEVICE +#define SOCKET_BUFFER_MTU (16u) +#define SOCKET_BUFFER_UDP_SIZE (SOCKET_BUFFER_UDP_HEADER_SIZE + 64u) +#define SOCKET_BUFFER_TCP_SIZE (64u) +#else +#ifdef ARDUINO +#define SOCKET_BUFFER_MTU (1446u) +#else +#define SOCKET_BUFFER_MTU (1400u) +#endif +#define SOCKET_BUFFER_UDP_SIZE (SOCKET_BUFFER_UDP_HEADER_SIZE + SOCKET_BUFFER_MTU) +#define SOCKET_BUFFER_TCP_SIZE (SOCKET_BUFFER_MTU) +#endif + +#define SOCKET_BUFFER_FLAG_CONNECTED (0x1 << 0) +#define SOCKET_BUFFER_FLAG_FULL (0x1 << 1) +#define SOCKET_BUFFER_FLAG_BIND (0x1 << 2) +#define SOCKET_BUFFER_FLAG_SPAWN (0x1 << 3) +#define SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS (16) +#define SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK (((uint32)0xFF) << SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS) +#define SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS (24) +#define SOCKET_BUFFER_FLAG_PARENT_SOCKET_MSK (((uint32)0xFF) << SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS) + +/* Parent stored as parent+1, as socket 1 ID is 0. */ + +typedef struct{ + uint8 *buffer; + uint32 *flag; + uint32 *head; + uint32 *tail; +}tstrSocketBuffer; + +void socketBufferInit(void); +void socketBufferRegister(SOCKET socket, uint32 *flag, uint32 *head, uint32 *tail, uint8 *buffer); +void socketBufferUnregister(SOCKET socket); +void socketBufferCb(SOCKET sock, uint8 u8Msg, void *pvMsg); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* __SOCKET_BUFFER_H__ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket.c new file mode 100644 index 0000000..877cc1a --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket.c @@ -0,0 +1,1445 @@ +/** + * + * \file + * + * \brief BSD compatible socket interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#include + +#include "bsp/include/nm_bsp.h" +#include "socket/include/socket.h" +#include "driver/source/m2m_hif.h" +#include "socket/source/socket_internal.h" +#include "driver/include/m2m_types.h" + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +MACROS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +#define TLS_RECORD_HEADER_LENGTH (5) +#define ETHERNET_HEADER_OFFSET (34) +#define ETHERNET_HEADER_LENGTH (14) +#define TCP_IP_HEADER_LENGTH (40) +#define UDP_IP_HEADER_LENGTH (28) + +#define IP_PACKET_OFFSET (ETHERNET_HEADER_LENGTH + ETHERNET_HEADER_OFFSET - M2M_HIF_HDR_OFFSET) + +#define TCP_TX_PACKET_OFFSET (IP_PACKET_OFFSET + TCP_IP_HEADER_LENGTH) +#define UDP_TX_PACKET_OFFSET (IP_PACKET_OFFSET + UDP_IP_HEADER_LENGTH) +#define SSL_TX_PACKET_OFFSET (TCP_TX_PACKET_OFFSET + TLS_RECORD_HEADER_LENGTH) + +#define SOCKET_REQUEST(reqID, reqArgs, reqSize, reqPayload, reqPayloadSize, reqPayloadOffset) \ + hif_send(M2M_REQ_GROUP_IP, reqID, reqArgs, reqSize, reqPayload, reqPayloadSize, reqPayloadOffset) + + +#define SSL_FLAGS_ACTIVE NBIT0 +#define SSL_FLAGS_BYPASS_X509 NBIT1 +#define SSL_FLAGS_2_RESERVD NBIT2 +#define SSL_FLAGS_3_RESERVD NBIT3 +#define SSL_FLAGS_CACHE_SESSION NBIT4 +#define SSL_FLAGS_NO_TX_COPY NBIT5 +#define SSL_FLAGS_CHECK_SNI NBIT6 + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +PRIVATE DATA TYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + + +/*! +* @brief +*/ +typedef struct{ + SOCKET sock; + uint8 u8Dummy; + uint16 u16SessionID; +}tstrCloseCmd; + + +/*! +* @brief +*/ +typedef struct{ + uint8 *pu8UserBuffer; + uint16 u16UserBufferSize; + uint16 u16SessionID; + uint16 u16DataOffset; + uint8 bIsUsed; + uint8 u8SSLFlags; + uint8 bIsRecvPending; +}tstrSocket; + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +GLOBALS +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +volatile sint8 gsockerrno; +volatile tstrSocket gastrSockets[MAX_SOCKET]; +volatile uint8 gu8OpCode; +volatile uint16 gu16BufferSize; +volatile uint16 gu16SessionID = 0; + +volatile tpfAppSocketCb gpfAppSocketCb; +volatile tpfAppResolveCb gpfAppResolveCb; +volatile uint8 gbSocketInit = 0; +volatile tpfPingCb gfpPingCb; + +/********************************************************************* +Function + Socket_ReadSocketData + +Description + Callback function used by the NMC1500 driver to deliver messages + for socket layer. + +Return + None. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 17 July 2012 +*********************************************************************/ +#ifdef ARDUINO +extern uint8 hif_small_xfer; +static uint32 u32Address; +static SOCKET sock_xfer; +static uint8 type_xfer; +static tstrSocketRecvMsg msg_xfer; +#endif +NMI_API void Socket_ReadSocketData(SOCKET sock, tstrSocketRecvMsg *pstrRecv,uint8 u8SocketMsg, + uint32 u32StartAddress,uint16 u16ReadCount) +{ + if((u16ReadCount > 0) && (gastrSockets[sock].pu8UserBuffer != NULL) && (gastrSockets[sock].u16UserBufferSize > 0) && (gastrSockets[sock].bIsUsed == 1)) + { +#ifdef ARDUINO + u32Address = u32StartAddress; +#else + uint32 u32Address = u32StartAddress; +#endif + uint16 u16Read; + sint16 s16Diff; + uint8 u8SetRxDone; +#ifdef ARDUINO + m2m_memcpy((uint8 *)&msg_xfer, (uint8 *)pstrRecv, sizeof(tstrSocketRecvMsg)); + msg_xfer.u16RemainingSize = u16ReadCount; +#else + pstrRecv->u16RemainingSize = u16ReadCount; +#endif + do + { + u8SetRxDone = 1; + u16Read = u16ReadCount; + s16Diff = u16Read - gastrSockets[sock].u16UserBufferSize; + if(s16Diff > 0) + { + u8SetRxDone = 0; + u16Read = gastrSockets[sock].u16UserBufferSize; +#ifdef ARDUINO + hif_small_xfer = 1; + sock_xfer = sock; + type_xfer = u8SocketMsg; +#endif + } + + if(hif_receive(u32Address, gastrSockets[sock].pu8UserBuffer, u16Read, u8SetRxDone) == M2M_SUCCESS) + { +#ifdef ARDUINO + msg_xfer.pu8Buffer = gastrSockets[sock].pu8UserBuffer; + msg_xfer.s16BufferSize = u16Read; + msg_xfer.u16RemainingSize -= u16Read; + + if (gpfAppSocketCb) + gpfAppSocketCb(sock,u8SocketMsg, &msg_xfer); + + u32Address += u16Read; +#else + pstrRecv->pu8Buffer = gastrSockets[sock].pu8UserBuffer; + pstrRecv->s16BufferSize = u16Read; + pstrRecv->u16RemainingSize -= u16Read; + + if (gpfAppSocketCb) + gpfAppSocketCb(sock,u8SocketMsg, pstrRecv); + + u16ReadCount -= u16Read; + u32Address += u16Read; + + if((!gastrSockets[sock].bIsUsed) && (u16ReadCount)) + { + M2M_DBG("Application Closed Socket While Rx Is not Complete\n"); + if(hif_receive(0, NULL, 0, 1) == M2M_SUCCESS) + M2M_DBG("hif_receive Success\n"); + else + M2M_DBG("hif_receive Fail\n"); + break; + } +#endif + } + else + { + M2M_INFO("(ERRR)Current <%d>\n", u16ReadCount); + break; + } +#ifdef ARDUINO + }while(0); +#else + }while(u16ReadCount != 0); +#endif + } +} +#ifdef ARDUINO +NMI_API void Socket_ReadSocketData_Small(void) +{ + if((msg_xfer.u16RemainingSize > 0) && (gastrSockets[sock_xfer].pu8UserBuffer != NULL) && (gastrSockets[sock_xfer].u16UserBufferSize > 0) && (gastrSockets[sock_xfer].bIsUsed == 1)) + { + uint16 u16Read; + sint16 s16Diff; + uint8 u8SetRxDone; + + //do + //{ + u8SetRxDone = 1; + u16Read = msg_xfer.u16RemainingSize; + s16Diff = u16Read - gastrSockets[sock_xfer].u16UserBufferSize; + if(s16Diff > 0) + { + /*Has to be subsequent transfer*/ + hif_small_xfer = 2; + u8SetRxDone = 0; + u16Read = gastrSockets[sock_xfer].u16UserBufferSize; + } + else + { + /*Last xfer, needed for UDP*/ + hif_small_xfer = 3; + } + if(hif_receive(u32Address, gastrSockets[sock_xfer].pu8UserBuffer, u16Read, u8SetRxDone) == M2M_SUCCESS) + { + msg_xfer.pu8Buffer = gastrSockets[sock_xfer].pu8UserBuffer; + msg_xfer.s16BufferSize = u16Read; + msg_xfer.u16RemainingSize -= u16Read; + + if (gpfAppSocketCb) + gpfAppSocketCb(sock_xfer,type_xfer, &msg_xfer); + + u32Address += u16Read; + } + else + { + M2M_INFO("(ERRR)Current <%d>\n", u16Read); + //break; + } + + if (hif_small_xfer == 3) + { + hif_small_xfer = 0; + hif_chip_sleep(); + } + + //}while(u16ReadCount != 0); + } +} +#endif +/********************************************************************* +Function + m2m_ip_cb + +Description + Callback function used by the NMC1000 driver to deliver messages + for socket layer. + +Return + None. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 17 July 2012 +*********************************************************************/ +static void m2m_ip_cb(uint8 u8OpCode, uint16 u16BufferSize,uint32 u32Address) +{ + if((u8OpCode == SOCKET_CMD_BIND) || (u8OpCode == SOCKET_CMD_SSL_BIND)) + { + tstrBindReply strBindReply; + tstrSocketBindMsg strBind; + + if(hif_receive(u32Address, (uint8*)&strBindReply, sizeof(tstrBindReply), 0) == M2M_SUCCESS) + { + strBind.status = strBindReply.s8Status; + if(gpfAppSocketCb) + gpfAppSocketCb(strBindReply.sock,SOCKET_MSG_BIND,&strBind); + } + } + else if(u8OpCode == SOCKET_CMD_LISTEN) + { + tstrListenReply strListenReply; + tstrSocketListenMsg strListen; + if(hif_receive(u32Address, (uint8*)&strListenReply, sizeof(tstrListenReply), 0) == M2M_SUCCESS) + { + strListen.status = strListenReply.s8Status; + if(gpfAppSocketCb) + gpfAppSocketCb(strListenReply.sock,SOCKET_MSG_LISTEN, &strListen); + } + } + else if(u8OpCode == SOCKET_CMD_ACCEPT) + { + tstrAcceptReply strAcceptReply; + tstrSocketAcceptMsg strAccept; + if(hif_receive(u32Address, (uint8*)&strAcceptReply, sizeof(tstrAcceptReply), 0) == M2M_SUCCESS) + { + if(strAcceptReply.sConnectedSock >= 0) + { + gastrSockets[strAcceptReply.sConnectedSock].u8SSLFlags = gastrSockets[strAcceptReply.sListenSock].u8SSLFlags; + gastrSockets[strAcceptReply.sConnectedSock].bIsUsed = 1; + gastrSockets[strAcceptReply.sConnectedSock].u16DataOffset = strAcceptReply.u16AppDataOffset - M2M_HIF_HDR_OFFSET; + + /* The session ID is used to distinguish different socket connections + by comparing the assigned session ID to the one reported by the firmware*/ + ++gu16SessionID; + if(gu16SessionID == 0) + ++gu16SessionID; + + gastrSockets[strAcceptReply.sConnectedSock].u16SessionID = gu16SessionID; + M2M_DBG("Socket %d session ID = %d\r\n",strAcceptReply.sConnectedSock , gu16SessionID ); + } + strAccept.sock = strAcceptReply.sConnectedSock; + strAccept.strAddr.sin_family = AF_INET; + strAccept.strAddr.sin_port = strAcceptReply.strAddr.u16Port; + strAccept.strAddr.sin_addr.s_addr = strAcceptReply.strAddr.u32IPAddr; + if(gpfAppSocketCb) + gpfAppSocketCb(strAcceptReply.sListenSock, SOCKET_MSG_ACCEPT, &strAccept); + } + } + else if((u8OpCode == SOCKET_CMD_CONNECT) || (u8OpCode == SOCKET_CMD_SSL_CONNECT)) + { + tstrConnectReply strConnectReply; + tstrSocketConnectMsg strConnMsg; + if(hif_receive(u32Address, (uint8*)&strConnectReply, sizeof(tstrConnectReply), 0) == M2M_SUCCESS) + { + strConnMsg.sock = strConnectReply.sock; + strConnMsg.s8Error = strConnectReply.s8Error; + if(strConnectReply.s8Error == SOCK_ERR_NO_ERROR) + { + gastrSockets[strConnectReply.sock].u16DataOffset = strConnectReply.u16AppDataOffset - M2M_HIF_HDR_OFFSET; + } + if(gpfAppSocketCb) + gpfAppSocketCb(strConnectReply.sock,SOCKET_MSG_CONNECT, &strConnMsg); + } + } + else if(u8OpCode == SOCKET_CMD_DNS_RESOLVE) + { + tstrDnsReply strDnsReply; + if(hif_receive(u32Address, (uint8*)&strDnsReply, sizeof(tstrDnsReply), 0) == M2M_SUCCESS) + { + if(gpfAppResolveCb) + gpfAppResolveCb((uint8*)strDnsReply.acHostName, strDnsReply.u32HostIP); + } + } + else if((u8OpCode == SOCKET_CMD_RECV) || (u8OpCode == SOCKET_CMD_RECVFROM) || (u8OpCode == SOCKET_CMD_SSL_RECV)) + { + SOCKET sock; + sint16 s16RecvStatus; + tstrRecvReply strRecvReply; + uint16 u16ReadSize; + tstrSocketRecvMsg strRecvMsg; + uint8 u8CallbackMsgID = SOCKET_MSG_RECV; + uint16 u16DataOffset; + + if(u8OpCode == SOCKET_CMD_RECVFROM) + u8CallbackMsgID = SOCKET_MSG_RECVFROM; + + /* Read RECV REPLY data structure. + */ + u16ReadSize = sizeof(tstrRecvReply); + if(hif_receive(u32Address, (uint8*)&strRecvReply, u16ReadSize, 0) == M2M_SUCCESS) + { + uint16 u16SessionID = 0; + + sock = strRecvReply.sock; + u16SessionID = strRecvReply.u16SessionID; + M2M_DBG("recv callback session ID = %d\r\n",u16SessionID); + + /* Reset the Socket RX Pending Flag. + */ + gastrSockets[sock].bIsRecvPending = 0; + + s16RecvStatus = NM_BSP_B_L_16(strRecvReply.s16RecvStatus); + u16DataOffset = NM_BSP_B_L_16(strRecvReply.u16DataOffset); + strRecvMsg.strRemoteAddr.sin_port = strRecvReply.strRemoteAddr.u16Port; + strRecvMsg.strRemoteAddr.sin_addr.s_addr = strRecvReply.strRemoteAddr.u32IPAddr; + + if(u16SessionID == gastrSockets[sock].u16SessionID) + { +#ifdef ARDUINO + if((s16RecvStatus > 0) && (s16RecvStatus < (sint32)u16BufferSize)) +#else + if((s16RecvStatus > 0) && (s16RecvStatus < u16BufferSize)) +#endif + { + /* Skip incoming bytes until reaching the Start of Application Data. + */ + u32Address += u16DataOffset; + + /* Read the Application data and deliver it to the application callback in + the given application buffer. If the buffer is smaller than the received data, + the data is passed to the application in chunks according to its buffer size. + */ + u16ReadSize = (uint16)s16RecvStatus; + Socket_ReadSocketData(sock, &strRecvMsg, u8CallbackMsgID, u32Address, u16ReadSize); + } + else + { + strRecvMsg.s16BufferSize = s16RecvStatus; + strRecvMsg.pu8Buffer = NULL; + if(gpfAppSocketCb) + gpfAppSocketCb(sock,u8CallbackMsgID, &strRecvMsg); + } + } + else + { + M2M_DBG("Discard recv callback %d %d \r\n",u16SessionID , gastrSockets[sock].u16SessionID); + if(u16ReadSize < u16BufferSize) + { + if(hif_receive(0, NULL, 0, 1) == M2M_SUCCESS) + M2M_DBG("hif_receive Success\n"); + else +#ifdef ARDUINO + { +#endif + M2M_DBG("hif_receive Fail\n"); +#ifdef ARDUINO + } +#endif + } + } + } + } + else if((u8OpCode == SOCKET_CMD_SEND) || (u8OpCode == SOCKET_CMD_SENDTO) || (u8OpCode == SOCKET_CMD_SSL_SEND)) + { + SOCKET sock; + sint16 s16Rcvd; + tstrSendReply strReply; + uint8 u8CallbackMsgID = SOCKET_MSG_SEND; + + if(u8OpCode == SOCKET_CMD_SENDTO) + u8CallbackMsgID = SOCKET_MSG_SENDTO; + + if(hif_receive(u32Address, (uint8*)&strReply, sizeof(tstrSendReply), 0) == M2M_SUCCESS) + { + uint16 u16SessionID = 0; + + sock = strReply.sock; + u16SessionID = strReply.u16SessionID; + M2M_DBG("send callback session ID = %d\r\n",u16SessionID); + + s16Rcvd = NM_BSP_B_L_16(strReply.s16SentBytes); + + if(u16SessionID == gastrSockets[sock].u16SessionID) + { + if(gpfAppSocketCb) + gpfAppSocketCb(sock,u8CallbackMsgID, &s16Rcvd); + } + else + { + M2M_DBG("Discard send callback %d %d \r\n",u16SessionID , gastrSockets[sock].u16SessionID); + } + } + } + else if(u8OpCode == SOCKET_CMD_PING) + { + tstrPingReply strPingReply; + if(hif_receive(u32Address, (uint8*)&strPingReply, sizeof(tstrPingReply), 1) == M2M_SUCCESS) + { + gfpPingCb = (void (*)(uint32 , uint32 , uint8))(uintptr_t)strPingReply.u32CmdPrivate; + if(gfpPingCb != NULL) + { + gfpPingCb(strPingReply.u32IPAddr, strPingReply.u32RTT, strPingReply.u8ErrorCode); + } + } + } +} +/********************************************************************* +Function + socketInit + +Description + +Return + None. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +void socketInit(void) +{ + if(gbSocketInit == 0) + { + m2m_memset((uint8*)gastrSockets, 0, MAX_SOCKET * sizeof(tstrSocket)); + hif_register_cb(M2M_REQ_GROUP_IP,m2m_ip_cb); + gbSocketInit = 1; + gu16SessionID = 0; + } +} +/********************************************************************* +Function + socketDeinit + +Description + +Return + None. + +Author + Samer Sarhan + +Version + 1.0 + +Date + 27 Feb 2015 +*********************************************************************/ +void socketDeinit(void) +{ + m2m_memset((uint8*)gastrSockets, 0, MAX_SOCKET * sizeof(tstrSocket)); + hif_register_cb(M2M_REQ_GROUP_IP, NULL); + gpfAppSocketCb = NULL; + gpfAppResolveCb = NULL; + gbSocketInit = 0; +} +/********************************************************************* +Function + registerSocketCallback + +Description + +Return + None. + +Author + Ahmed Ezzat + +Versio + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +void registerSocketCallback(tpfAppSocketCb pfAppSocketCb, tpfAppResolveCb pfAppResolveCb) +{ + gpfAppSocketCb = pfAppSocketCb; + gpfAppResolveCb = pfAppResolveCb; +} + +/********************************************************************* +Function + socket + +Description + Creates a socket. + +Return + - Negative value for error. + - ZERO or positive value as a socket ID if successful. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags) +{ + SOCKET sock = -1; + uint8 u8SockID; + uint8 u8Count; + volatile tstrSocket *pstrSock; + static volatile uint8 u8NextTcpSock = 0; + static volatile uint8 u8NextUdpSock = 0; + + /* The only supported family is the AF_INET for UDP and TCP transport layer protocols. */ + if(u16Domain == AF_INET) + { + if(u8Type == SOCK_STREAM) + { + for(u8Count = 0; u8Count < TCP_SOCK_MAX; u8Count ++) + { + u8SockID = u8NextTcpSock; + pstrSock = &gastrSockets[u8NextTcpSock]; + u8NextTcpSock = (u8NextTcpSock + 1) % TCP_SOCK_MAX; + if(!pstrSock->bIsUsed) + { + sock = (SOCKET)u8SockID; + break; + } + } + } + else if(u8Type == SOCK_DGRAM) + { + volatile tstrSocket *pastrUDPSockets = &gastrSockets[TCP_SOCK_MAX]; + for(u8Count = 0; u8Count < UDP_SOCK_MAX; u8Count ++) + { + u8SockID = u8NextUdpSock; + pstrSock = &pastrUDPSockets[u8NextUdpSock]; + u8NextUdpSock = (u8NextUdpSock + 1) % UDP_SOCK_MAX; + if(!pstrSock->bIsUsed) + { + sock = (SOCKET)(u8SockID + TCP_SOCK_MAX); + break; + } + } + } + + if(sock >= 0) + { + m2m_memset((uint8*)pstrSock, 0, sizeof(tstrSocket)); + pstrSock->bIsUsed = 1; + + /* The session ID is used to distinguish different socket connections + by comparing the assigned session ID to the one reported by the firmware*/ + ++gu16SessionID; + if(gu16SessionID == 0) + ++gu16SessionID; + + pstrSock->u16SessionID = gu16SessionID; + M2M_INFO("Socket %d session ID = %d\r\n",sock, gu16SessionID ); + + if(u8Flags & SOCKET_FLAGS_SSL) + { + tstrSSLSocketCreateCmd strSSLCreate; + strSSLCreate.sslSock = sock; + pstrSock->u8SSLFlags = SSL_FLAGS_ACTIVE | SSL_FLAGS_NO_TX_COPY; + SOCKET_REQUEST(SOCKET_CMD_SSL_CREATE, (uint8*)&strSSLCreate, sizeof(tstrSSLSocketCreateCmd), 0, 0, 0); + } + } + } + return sock; +} +/********************************************************************* +Function + bind + +Description + Request to bind a socket on a local address. + +Return + + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 5 June 2012 +*********************************************************************/ +sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen) +{ + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + if((pstrAddr != NULL) && (sock >= 0) && (gastrSockets[sock].bIsUsed == 1) && (u8AddrLen != 0)) + { + tstrBindCmd strBind; + uint8 u8CMD = SOCKET_CMD_BIND; + if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) + { + u8CMD = SOCKET_CMD_SSL_BIND; + } + + /* Build the bind request. */ + strBind.sock = sock; + m2m_memcpy((uint8 *)&strBind.strAddr, (uint8 *)pstrAddr, sizeof(tstrSockAddr)); + strBind.u16SessionID = gastrSockets[sock].u16SessionID; + + /* Send the request. */ + s8Ret = SOCKET_REQUEST(u8CMD, (uint8*)&strBind,sizeof(tstrBindCmd) , NULL , 0, 0); + if(s8Ret != SOCK_ERR_NO_ERROR) + { + s8Ret = SOCK_ERR_INVALID; + } + } + return s8Ret; +} +/********************************************************************* +Function + listen + +Description + + +Return + + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 5 June 2012 +*********************************************************************/ +sint8 listen(SOCKET sock, uint8 backlog) +{ + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + + if(sock >= 0 && (gastrSockets[sock].bIsUsed == 1)) + { + tstrListenCmd strListen; + + strListen.sock = sock; + strListen.u8BackLog = backlog; + strListen.u16SessionID = gastrSockets[sock].u16SessionID; + + s8Ret = SOCKET_REQUEST(SOCKET_CMD_LISTEN, (uint8*)&strListen, sizeof(tstrListenCmd), NULL, 0, 0); + if(s8Ret != SOCK_ERR_NO_ERROR) + { + s8Ret = SOCK_ERR_INVALID; + } + } + return s8Ret; +} +/********************************************************************* +Function + accept + +Description + +Return + + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 5 June 2012 +*********************************************************************/ +sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)addr; + (void)addrlen; +#endif + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + + if(sock >= 0 && (gastrSockets[sock].bIsUsed == 1) ) + { + s8Ret = SOCK_ERR_NO_ERROR; + } + return s8Ret; +} +/********************************************************************* +Function + connect + +Description + Connect to a remote TCP Server. + +Return + + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 5 June 2012 +*********************************************************************/ +#ifdef ARDUINO +sint8 connectSocket(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen) +#else +sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen) +#endif +{ + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + if((sock >= 0) && (pstrAddr != NULL) && (gastrSockets[sock].bIsUsed == 1) && (u8AddrLen != 0)) + { + tstrConnectCmd strConnect; + uint8 u8Cmd = SOCKET_CMD_CONNECT; + if((gastrSockets[sock].u8SSLFlags) & SSL_FLAGS_ACTIVE) + { + u8Cmd = SOCKET_CMD_SSL_CONNECT; + strConnect.u8SslFlags = gastrSockets[sock].u8SSLFlags; + } + strConnect.sock = sock; + m2m_memcpy((uint8 *)&strConnect.strAddr, (uint8 *)pstrAddr, sizeof(tstrSockAddr)); + + strConnect.u16SessionID = gastrSockets[sock].u16SessionID; + s8Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strConnect,sizeof(tstrConnectCmd), NULL, 0, 0); + if(s8Ret != SOCK_ERR_NO_ERROR) + { + s8Ret = SOCK_ERR_INVALID; + } + } + return s8Ret; +} +/********************************************************************* +Function + send + +Description + +Return + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 5 June 2012 +*********************************************************************/ +sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags) +{ +#ifdef ARDUINO + (void)flags; // Silence "unused" warning +#endif + sint16 s16Ret = SOCK_ERR_INVALID_ARG; + + if((sock >= 0) && (pvSendBuffer != NULL) && (u16SendLength <= SOCKET_BUFFER_MAX_LENGTH) && (gastrSockets[sock].bIsUsed == 1)) + { + uint16 u16DataOffset; + tstrSendCmd strSend; + uint8 u8Cmd; + + u8Cmd = SOCKET_CMD_SEND; + u16DataOffset = TCP_TX_PACKET_OFFSET; + + strSend.sock = sock; + strSend.u16DataSize = NM_BSP_B_L_16(u16SendLength); + strSend.u16SessionID = gastrSockets[sock].u16SessionID; + + if(sock >= TCP_SOCK_MAX) + { + u16DataOffset = UDP_TX_PACKET_OFFSET; + } + if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) + { + u8Cmd = SOCKET_CMD_SSL_SEND; + u16DataOffset = gastrSockets[sock].u16DataOffset; +#ifdef ARDUINO + extern uint32 nmdrv_firm_ver; + + if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 4, 0)) { + // firmware 19.3.0 and older only works with this specific offset + u16DataOffset = SSL_TX_PACKET_OFFSET; + } +#endif + } + + s16Ret = SOCKET_REQUEST(u8Cmd|M2M_REQ_DATA_PKT, (uint8*)&strSend, sizeof(tstrSendCmd), pvSendBuffer, u16SendLength, u16DataOffset); + if(s16Ret != SOCK_ERR_NO_ERROR) + { + s16Ret = SOCK_ERR_BUFFER_FULL; + } + } + return s16Ret; +} +/********************************************************************* +Function + sendto + +Description + +Return + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)flags; + (void)u8AddrLen; +#endif + sint16 s16Ret = SOCK_ERR_INVALID_ARG; + + if((sock >= 0) && (pvSendBuffer != NULL) && (u16SendLength <= SOCKET_BUFFER_MAX_LENGTH) && (gastrSockets[sock].bIsUsed == 1)) + { + if(gastrSockets[sock].bIsUsed) + { + tstrSendCmd strSendTo; + + m2m_memset((uint8*)&strSendTo, 0, sizeof(tstrSendCmd)); + + strSendTo.sock = sock; + strSendTo.u16DataSize = NM_BSP_B_L_16(u16SendLength); + strSendTo.u16SessionID = gastrSockets[sock].u16SessionID; + + if(pstrDestAddr != NULL) + { + struct sockaddr_in *pstrAddr; + pstrAddr = (void*)pstrDestAddr; + + strSendTo.strAddr.u16Family = pstrAddr->sin_family; + strSendTo.strAddr.u16Port = pstrAddr->sin_port; + strSendTo.strAddr.u32IPAddr = pstrAddr->sin_addr.s_addr; + } + s16Ret = SOCKET_REQUEST(SOCKET_CMD_SENDTO|M2M_REQ_DATA_PKT, (uint8*)&strSendTo, sizeof(tstrSendCmd), + pvSendBuffer, u16SendLength, UDP_TX_PACKET_OFFSET); + + if(s16Ret != SOCK_ERR_NO_ERROR) + { + s16Ret = SOCK_ERR_BUFFER_FULL; + } + } + } + return s16Ret; +} +/********************************************************************* +Function + recv + +Description + +Return + + +Author + Ahmed Ezzat + +Version + 1.0 + 2.0 9 April 2013 --> Add timeout for recv operation. + +Date + 5 June 2012 +*********************************************************************/ +sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec) +{ + sint16 s16Ret = SOCK_ERR_INVALID_ARG; + + if((sock >= 0) && (pvRecvBuf != NULL) && (u16BufLen != 0) && (gastrSockets[sock].bIsUsed == 1)) + { + s16Ret = SOCK_ERR_NO_ERROR; + gastrSockets[sock].pu8UserBuffer = (uint8*)pvRecvBuf; + gastrSockets[sock].u16UserBufferSize = u16BufLen; + + if(!gastrSockets[sock].bIsRecvPending) + { + tstrRecvCmd strRecv; + uint8 u8Cmd = SOCKET_CMD_RECV; + + gastrSockets[sock].bIsRecvPending = 1; + if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) + { + u8Cmd = SOCKET_CMD_SSL_RECV; + } + + /* Check the timeout value. */ + if(u32Timeoutmsec == 0) + strRecv.u32Timeoutmsec = 0xFFFFFFFF; + else + strRecv.u32Timeoutmsec = NM_BSP_B_L_32(u32Timeoutmsec); + strRecv.sock = sock; + strRecv.u16SessionID = gastrSockets[sock].u16SessionID; + + s16Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strRecv, sizeof(tstrRecvCmd), NULL , 0, 0); + if(s16Ret != SOCK_ERR_NO_ERROR) + { + s16Ret = SOCK_ERR_BUFFER_FULL; + } + } + } + return s16Ret; +} +/********************************************************************* +Function + close + +Description + +Return + None. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +sint8 close(SOCKET sock) +{ + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + M2M_INFO("Sock to delete <%d>\n", sock); + if(sock >= 0 && (gastrSockets[sock].bIsUsed == 1)) + { + uint8 u8Cmd = SOCKET_CMD_CLOSE; + tstrCloseCmd strclose; + strclose.sock = sock; + strclose.u16SessionID = gastrSockets[sock].u16SessionID; + + gastrSockets[sock].bIsUsed = 0; + gastrSockets[sock].u16SessionID =0; + + if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) + { + u8Cmd = SOCKET_CMD_SSL_CLOSE; + } + s8Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strclose, sizeof(tstrCloseCmd), NULL,0, 0); + if(s8Ret != SOCK_ERR_NO_ERROR) + { + s8Ret = SOCK_ERR_INVALID; + } + m2m_memset((uint8*)&gastrSockets[sock], 0, sizeof(tstrSocket)); + } + return s8Ret; +} +/********************************************************************* +Function + recvfrom + +Description + +Return + + +Author + Ahmed Ezzat + +Version + 1.0 + 2.0 9 April 2013 --> Add timeout for recv operation. + +Date + 5 June 2012 +*********************************************************************/ +sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec) +{ + sint16 s16Ret = SOCK_ERR_NO_ERROR; + if((sock >= 0) && (pvRecvBuf != NULL) && (u16BufLen != 0) && (gastrSockets[sock].bIsUsed == 1)) + { + if(gastrSockets[sock].bIsUsed) + { + s16Ret = SOCK_ERR_NO_ERROR; + gastrSockets[sock].pu8UserBuffer = (uint8*)pvRecvBuf; + gastrSockets[sock].u16UserBufferSize = u16BufLen; + + if(!gastrSockets[sock].bIsRecvPending) + { + tstrRecvCmd strRecv; + + gastrSockets[sock].bIsRecvPending = 1; + + /* Check the timeout value. */ + if(u32Timeoutmsec == 0) + strRecv.u32Timeoutmsec = 0xFFFFFFFF; + else + strRecv.u32Timeoutmsec = NM_BSP_B_L_32(u32Timeoutmsec); + strRecv.sock = sock; + strRecv.u16SessionID = gastrSockets[sock].u16SessionID; + + s16Ret = SOCKET_REQUEST(SOCKET_CMD_RECVFROM, (uint8*)&strRecv, sizeof(tstrRecvCmd), NULL , 0, 0); + if(s16Ret != SOCK_ERR_NO_ERROR) + { + s16Ret = SOCK_ERR_BUFFER_FULL; + } + } + } + } + else + { + s16Ret = SOCK_ERR_INVALID_ARG; + } + return s16Ret; +} +/********************************************************************* +Function + nmi_inet_addr + +Description + +Return + Unsigned 32-bit integer representing the IP address in Network + byte order. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +uint32 nmi_inet_addr(char *pcIpAddr) +{ + uint8 tmp; + uint32 u32IP = 0; + uint8 au8IP[4]; + uint8 c; + uint8 i, j; + + tmp = 0; + + for(i = 0; i < 4; ++i) + { + j = 0; + do + { + c = *pcIpAddr; + ++j; + if(j > 4) + { + return 0; + } + if(c == '.' || c == 0) + { + au8IP[i] = tmp; + tmp = 0; + } + else if(c >= '0' && c <= '9') + { + tmp = (tmp * 10) + (c - '0'); + } + else + { + return 0; + } + ++pcIpAddr; + } while(c != '.' && c != 0); + } + m2m_memcpy((uint8*)&u32IP, au8IP, 4); + return u32IP; +} +/********************************************************************* +Function + gethostbyname + +Description + +Return + None. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2012 +*********************************************************************/ +sint8 gethostbyname(uint8 * pcHostName) +{ + sint8 s8Err = SOCK_ERR_INVALID_ARG; + uint8 u8HostNameSize = (uint8)m2m_strlen(pcHostName); + if(u8HostNameSize <= HOSTNAME_MAX_SIZE) + { + s8Err = SOCKET_REQUEST(SOCKET_CMD_DNS_RESOLVE, (uint8*)pcHostName, u8HostNameSize + 1, NULL,0, 0); + } + return s8Err; +} +/********************************************************************* +Function + setsockopt + +Description + +Return + None. + +Author + Abdelrahman Diab + +Version + 1.0 + +Date + 9 September 2014 +*********************************************************************/ +static sint8 sslSetSockOpt(SOCKET sock, uint8 u8Opt, const void *pvOptVal, uint16 u16OptLen) +{ + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + if(sock < TCP_SOCK_MAX) + { + if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) + { + if(u8Opt == SO_SSL_BYPASS_X509_VERIF) + { + int optVal = *((int*)pvOptVal); + if(optVal) + { + gastrSockets[sock].u8SSLFlags |= SSL_FLAGS_BYPASS_X509; + } + else + { + gastrSockets[sock].u8SSLFlags &= ~SSL_FLAGS_BYPASS_X509; + } + s8Ret = SOCK_ERR_NO_ERROR; + } + else if(u8Opt == SO_SSL_ENABLE_SESSION_CACHING) + { + int optVal = *((int*)pvOptVal); + if(optVal) + { + gastrSockets[sock].u8SSLFlags |= SSL_FLAGS_CACHE_SESSION; + } + else + { + gastrSockets[sock].u8SSLFlags &= ~SSL_FLAGS_CACHE_SESSION; + } + s8Ret = SOCK_ERR_NO_ERROR; + } + else if(u8Opt == SO_SSL_ENABLE_SNI_VALIDATION) + { + int optVal = *((int*)pvOptVal); + if(optVal) + { + gastrSockets[sock].u8SSLFlags |= SSL_FLAGS_CHECK_SNI; + } + else + { + gastrSockets[sock].u8SSLFlags &= ~SSL_FLAGS_CHECK_SNI; + } + s8Ret = SOCK_ERR_NO_ERROR; + } + else if(u8Opt == SO_SSL_SNI) + { + if(u16OptLen < HOSTNAME_MAX_SIZE) + { + uint8 *pu8SNI = (uint8*)pvOptVal; + tstrSSLSetSockOptCmd strCmd; + + strCmd.sock = sock; + strCmd.u16SessionID = gastrSockets[sock].u16SessionID; + strCmd.u8Option = u8Opt; + strCmd.u32OptLen = u16OptLen; + m2m_memcpy(strCmd.au8OptVal, pu8SNI, HOSTNAME_MAX_SIZE); + + if(SOCKET_REQUEST(SOCKET_CMD_SSL_SET_SOCK_OPT, (uint8*)&strCmd, sizeof(tstrSSLSetSockOptCmd), + 0, 0, 0) == M2M_ERR_MEM_ALLOC) + { + s8Ret = SOCKET_REQUEST(SOCKET_CMD_SSL_SET_SOCK_OPT | M2M_REQ_DATA_PKT, + (uint8*)&strCmd, sizeof(tstrSSLSetSockOptCmd), 0, 0, 0); + } + s8Ret = SOCK_ERR_NO_ERROR; + } + else + { + M2M_ERR("SNI Exceeds Max Length\n"); + } + } + else + { + M2M_ERR("Unknown SSL Socket Option %d\n",u8Opt); + } + } + else + { + M2M_ERR("Not SSL Socket\n"); + } + } + return s8Ret; +} +/********************************************************************* +Function + setsockopt + +Description + +Return + None. + +Author + Abdelrahman Diab + +Version + 1.0 + +Date + 9 September 2014 +*********************************************************************/ +sint8 setsockopt(SOCKET sock, uint8 u8Level, uint8 option_name, + const void *option_value, uint16 u16OptionLen) +{ + sint8 s8Ret = SOCK_ERR_INVALID_ARG; + if((sock >= 0) && (option_value != NULL) && (gastrSockets[sock].bIsUsed == 1)) + { + if(u8Level == SOL_SSL_SOCKET) + { + s8Ret = sslSetSockOpt(sock, option_name, option_value, u16OptionLen); + } + else + { + uint8 u8Cmd = SOCKET_CMD_SET_SOCKET_OPTION; + tstrSetSocketOptCmd strSetSockOpt; + strSetSockOpt.u8Option=option_name; + strSetSockOpt.sock = sock; + strSetSockOpt.u32OptionValue = *(uint32*)option_value; + strSetSockOpt.u16SessionID = gastrSockets[sock].u16SessionID; + + s8Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strSetSockOpt, sizeof(tstrSetSocketOptCmd), NULL,0, 0); + if(s8Ret != SOCK_ERR_NO_ERROR) + { + s8Ret = SOCK_ERR_INVALID; + } + } + } + return s8Ret; +} +/********************************************************************* +Function + getsockopt + +Description + +Return + None. + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 24 August 2014 +*********************************************************************/ +sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8* pu8OptLen) +{ +#ifdef ARDUINO + // Silence "unused" warning + (void)sock; + (void)u8Level; + (void)u8OptName; + (void)pvOptValue; + (void)pu8OptLen; +#endif + /* TBD */ + return M2M_SUCCESS; +} +/********************************************************************* +Function + m2m_ping_req + +Description + Send Ping request. + +Return + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + 4 June 2015 +*********************************************************************/ +sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb) +{ + sint8 s8Ret = M2M_ERR_INVALID_ARG; + + if((u32DstIP != 0) && (fpPingCb != NULL)) + { + tstrPingCmd strPingCmd; + + strPingCmd.u16PingCount = 1; + strPingCmd.u32DestIPAddr = u32DstIP; +#ifdef ARDUINO + strPingCmd.u32CmdPrivate = (uint32)(uintptr_t)(fpPingCb); +#else + strPingCmd.u32CmdPrivate = (uint32)(fpPingCb); +#endif + strPingCmd.u8TTL = u8TTL; + + s8Ret = SOCKET_REQUEST(SOCKET_CMD_PING, (uint8*)&strPingCmd, sizeof(tstrPingCmd), NULL, 0, 0); + } + return s8Ret; +} +/********************************************************************* +Function + sslEnableCertExpirationCheck + +Description + Enable/Disable TLS Certificate Expiration Check. + +Return + +Author + Ahmed Ezzat + +Version + 1.0 + +Date + +*********************************************************************/ +sint8 sslEnableCertExpirationCheck(tenuSslCertExpSettings enuValidationSetting) +{ + tstrSslCertExpSettings strSettings; + strSettings.u32CertExpValidationOpt = (uint32)enuValidationSetting; + return SOCKET_REQUEST(SOCKET_CMD_SSL_EXP_CHECK, (uint8*)&strSettings, sizeof(tstrSslCertExpSettings), NULL, 0, 0); +} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket_buffer.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket_buffer.c new file mode 100644 index 0000000..d100558 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket_buffer.c @@ -0,0 +1,232 @@ +/** + * + * \file + * + * \brief BSD compatible socket interface. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#include +#include "socket/include/socket.h" +#include "driver/source/m2m_hif.h" +#include "socket/source/socket_internal.h" +#include "socket/include/socket_buffer.h" +#include "driver/include/m2m_periph.h" + +tstrSocketBuffer gastrSocketBuffer[MAX_SOCKET]; + +extern uint8 hif_small_xfer; + +void socketBufferInit(void) +{ + memset(gastrSocketBuffer, 0, sizeof(gastrSocketBuffer)); +} + +void socketBufferRegister(SOCKET socket, uint32 *flag, uint32 *head, uint32 *tail, uint8 *buffer) +{ + gastrSocketBuffer[socket].flag = flag; + gastrSocketBuffer[socket].head = head; + gastrSocketBuffer[socket].tail = tail; + gastrSocketBuffer[socket].buffer = buffer; +} + +void socketBufferUnregister(SOCKET socket) +{ + gastrSocketBuffer[socket].flag = 0; + gastrSocketBuffer[socket].head = 0; + gastrSocketBuffer[socket].tail = 0; + gastrSocketBuffer[socket].buffer = 0; +} + +void socketBufferCb(SOCKET sock, uint8 u8Msg, void *pvMsg) +{ + switch (u8Msg) { + /* Socket connected. */ + case SOCKET_MSG_CONNECT: + { + tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg *)pvMsg; + if (pstrConnect && pstrConnect->s8Error >= 0) { + recv(sock, gastrSocketBuffer[sock].buffer, SOCKET_BUFFER_MTU, 0); + *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_CONNECTED; + } else { + close(sock); + } + } + break; + + /* TCP Data receive. */ + case SOCKET_MSG_RECV: + { + // Network led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); + + tstrSocketRecvMsg *pstrRecv = (tstrSocketRecvMsg *)pvMsg; + if (pstrRecv && pstrRecv->s16BufferSize > 0) { + /* Protect against overflow. */ + if (*(gastrSocketBuffer[sock].head) + pstrRecv->s16BufferSize > SOCKET_BUFFER_TCP_SIZE) { + *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_FULL; + break; + } + + /* Add data size. */ + *(gastrSocketBuffer[sock].head) += pstrRecv->s16BufferSize; + + /* Buffer full, stop reception. */ + if (SOCKET_BUFFER_TCP_SIZE - *(gastrSocketBuffer[sock].head) < SOCKET_BUFFER_MTU) { + if (pstrRecv->u16RemainingSize != 0) { + *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_FULL; + } + } + else { + recv(sock, gastrSocketBuffer[sock].buffer + *(gastrSocketBuffer[sock].head), + SOCKET_BUFFER_MTU, 0); + } + } + /* Test EOF (Socket closed) condition for TCP socket. */ + else { + *(gastrSocketBuffer[sock].flag) &= ~SOCKET_BUFFER_FLAG_CONNECTED; + close(sock); + } + + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + } + break; + + /* UDP Data receive. */ + case SOCKET_MSG_RECVFROM: + { + // Network led ON (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); + + tstrSocketRecvMsg *pstrRecv = (tstrSocketRecvMsg *)pvMsg; + if (pstrRecv && pstrRecv->s16BufferSize > 0) { + + if (hif_small_xfer < 2) { + uint32 h = *(gastrSocketBuffer[sock].head); + uint8 *buf = gastrSocketBuffer[sock].buffer; + uint16 sz = pstrRecv->s16BufferSize + pstrRecv->u16RemainingSize; + + /* Store packet size. */ + buf[h++] = sz >> 8; + buf[h++] = sz; + + /* Store remote host port. */ + buf[h++] = pstrRecv->strRemoteAddr.sin_port; + buf[h++] = pstrRecv->strRemoteAddr.sin_port >> 8; + + /* Store remote host IP. */ + buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr >> 24; + buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr >> 16; + buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr >> 8; + buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr; + + /* Data received. */ + *(gastrSocketBuffer[sock].head) = h + pstrRecv->s16BufferSize; + } + else { + /* Data received. */ + *(gastrSocketBuffer[sock].head) += pstrRecv->s16BufferSize; + } + + /* Buffer full, stop reception. */ + if (SOCKET_BUFFER_UDP_SIZE - *(gastrSocketBuffer[sock].head) < SOCKET_BUFFER_MTU + SOCKET_BUFFER_UDP_HEADER_SIZE) { + if (pstrRecv->u16RemainingSize != 0) { + *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_FULL; + } + } + else { + if (hif_small_xfer && hif_small_xfer != 3) { + recvfrom(sock, gastrSocketBuffer[sock].buffer + *(gastrSocketBuffer[sock].head), + SOCKET_BUFFER_MTU, 0); + } + else { + recvfrom(sock, gastrSocketBuffer[sock].buffer + *(gastrSocketBuffer[sock].head) + SOCKET_BUFFER_UDP_HEADER_SIZE, + SOCKET_BUFFER_MTU, 0); + } + } + } + + // Network led OFF (rev A then rev B). + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); + m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); + } + break; + + /* Socket bind. */ + case SOCKET_MSG_BIND: + { + tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg *)pvMsg; + if (pstrBind && pstrBind->status == 0) { + *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_BIND; + /* TCP socket needs to enter Listen state. */ + if (sock < TCP_SOCK_MAX) { + listen(sock, 0); + } + /* UDP socket only needs to supply the receive buffer. */ + /* +8 is used to store size, port and IP of incoming data. */ + else { + recvfrom(sock, gastrSocketBuffer[sock].buffer + SOCKET_BUFFER_UDP_HEADER_SIZE, + SOCKET_BUFFER_MTU, 0); + } + } + } + break; + + /* Connect accept. */ + case SOCKET_MSG_ACCEPT: + { + tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg *)pvMsg; + if (pstrAccept && pstrAccept->sock >= 0) { + if (*(gastrSocketBuffer[sock].flag) & SOCKET_BUFFER_FLAG_SPAWN) { + /* One spawn connection already waiting, discard current one. */ + close(pstrAccept->sock); + } + else { + /* Use flag to store spawn TCP descriptor. */ + *(gastrSocketBuffer[sock].flag) &= ~SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK; + *(gastrSocketBuffer[sock].flag) |= (((uint32)pstrAccept->sock) << SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS); + *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_SPAWN; + } + } + } + break; + + } +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket_internal.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket_internal.h new file mode 100644 index 0000000..1904c23 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket_internal.h @@ -0,0 +1,71 @@ +/** + * + * \file + * + * \brief BSD compatible socket interface internal types. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ +#ifndef __SOCKET_INTERNAL_H__ +#define __SOCKET_INTERNAL_H__ + + +#ifdef __cplusplus +extern "C" { +#endif + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +INCLUDES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +#include "socket/include/socket.h" +#include "socket/include/m2m_socket_host_if.h" + + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* +FUNCTION PROTOTYPES +*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ + +NMI_API void Socket_ReadSocketData(SOCKET sock, tstrSocketRecvMsg *pstrRecv,uint8 u8SocketMsg, + uint32 u32StartAddress,uint16 u16ReadCount); +#ifdef ARDUINO +NMI_API void Socket_ReadSocketData_Small(void); +#endif + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* __SOCKET_H__ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/include/spi_flash.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/include/spi_flash.h new file mode 100644 index 0000000..a85aa72 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/include/spi_flash.h @@ -0,0 +1,233 @@ +/** + * + * \file + * + * \brief WINC1500 SPI Flash. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/** \defgroup SPIFLASH Spi Flash + * @file spi_flash.h + * @brief This file describe SPI flash APIs, how to use it and limitations with each one. + * @section Example + * This example illustrates a complete guide of how to use these APIs. + * @code{.c} + #include "spi_flash.h" + + #define DATA_TO_REPLACE "THIS IS A NEW SECTOR IN FLASH" + + int main() + { + uint8 au8FlashContent[FLASH_SECTOR_SZ] = {0}; + uint32 u32FlashTotalSize = 0; + uint32 u32FlashOffset = 0; + + ret = m2m_wifi_download_mode(); + if(M2M_SUCCESS != ret) + { + printf("Unable to enter download mode\r\n"); + } + else + { + u32FlashTotalSize = spi_flash_get_size(); + } + + while((u32FlashTotalSize > u32FlashOffset) && (M2M_SUCCESS == ret)) + { + ret = spi_flash_read(au8FlashContent, u32FlashOffset, FLASH_SECTOR_SZ); + if(M2M_SUCCESS != ret) + { + printf("Unable to read SPI sector\r\n"); + break; + } + memcpy(au8FlashContent, DATA_TO_REPLACE, strlen(DATA_TO_REPLACE)); + + ret = spi_flash_erase(u32FlashOffset, FLASH_SECTOR_SZ); + if(M2M_SUCCESS != ret) + { + printf("Unable to erase SPI sector\r\n"); + break; + } + + ret = spi_flash_write(au8FlashContent, u32FlashOffset, FLASH_SECTOR_SZ); + if(M2M_SUCCESS != ret) + { + printf("Unable to write SPI sector\r\n"); + break; + } + u32FlashOffset += FLASH_SECTOR_SZ; + } + + if(M2M_SUCCESS == ret) + { + printf("Successful operations\r\n"); + } + else + { + printf("Failed operations\r\n"); + } + + while(1); + return M2M_SUCCESS; + } + * @endcode + */ + +#ifndef __SPI_FLASH_H__ +#define __SPI_FLASH_H__ +#include "common/include/nm_common.h" +#include "bus_wrapper/include/nm_bus_wrapper.h" +#include "driver/source/nmbus.h" +#include "driver/source/nmasic.h" + +#ifdef ARDUINO +#ifdef __cplusplus +extern "C" { +#endif +#endif + +/** + * @fn spi_flash_enable + * @brief Enable spi flash operations + * @version 1.0 + */ +sint8 spi_flash_enable(uint8 enable); +/** \defgroup SPIFLASHAPI Function + * @ingroup SPIFLASH + */ + + /** @defgroup SPiFlashGetFn spi_flash_get_size + * @ingroup SPIFLASHAPI + */ + /**@{*/ +/*! + * @fn uint32 spi_flash_get_size(void); + * @brief Returns with \ref uint32 value which is total flash size\n + * @note Returned value in Mb (Mega Bit). + * @return SPI flash size in case of success and a ZERO value in case of failure. + */ +uint32 spi_flash_get_size(void); + /**@}*/ + + /** @defgroup SPiFlashRead spi_flash_read + * @ingroup SPIFLASHAPI + */ + /**@{*/ +/*! + * @fn sint8 spi_flash_read(uint8 *, uint32, uint32); + * @brief Read a specified portion of data from SPI Flash.\n + * @param [out] pu8Buf + * Pointer to data buffer which will fill in with data in case of successful operation. + * @param [in] u32Addr + * Address (Offset) to read from at the SPI flash. + * @param [in] u32Sz + * Total size of data to be read in bytes + * @warning + * - Address (offset) plus size of data must not exceed flash size.\n + * - No firmware is required for reading from SPI flash.\n + * - In case of there is a running firmware, it is required to pause your firmware first + * before any trial to access SPI flash to avoid any racing between host and running firmware on bus using + * @ref m2m_wifi_download_mode + * @note + * - It is blocking function\n + * @sa m2m_wifi_download_mode, spi_flash_get_size + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + */ +sint8 spi_flash_read(uint8 *pu8Buf, uint32 u32Addr, uint32 u32Sz); + /**@}*/ + + /** @defgroup SPiFlashWrite spi_flash_write + * @ingroup SPIFLASHAPI + */ + /**@{*/ +/*! + * @fn sint8 spi_flash_write(uint8 *, uint32, uint32); + * @brief Write a specified portion of data to SPI Flash.\n + * @param [in] pu8Buf + * Pointer to data buffer which contains the required to be written. + * @param [in] u32Offset + * Address (Offset) to write at the SPI flash. + * @param [in] u32Sz + * Total number of size of data bytes + * @note + * - It is blocking function\n + * - It is user's responsibility to verify that data has been written successfully + * by reading data again and compare it with the original. + * @warning + * - Address (offset) plus size of data must not exceed flash size.\n + * - No firmware is required for writing to SPI flash.\n + * - In case of there is a running firmware, it is required to pause your firmware first + * before any trial to access SPI flash to avoid any racing between host and running firmware on bus using + * @ref m2m_wifi_download_mode. + * - Before writing to any section, it is required to erase it first. + * @sa m2m_wifi_download_mode, spi_flash_get_size, spi_flash_erase + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + + */ +sint8 spi_flash_write(uint8* pu8Buf, uint32 u32Offset, uint32 u32Sz); + /**@}*/ + + /** @defgroup SPiFlashErase spi_flash_erase + * @ingroup SPIFLASHAPI + */ + /**@{*/ +/*! + * @fn sint8 spi_flash_erase(uint32, uint32); + * @brief Erase a specified portion of SPI Flash.\n + * @param [in] u32Offset + * Address (Offset) to erase from the SPI flash. + * @param [in] u32Sz + * Size of SPI flash required to be erased. + * @note It is blocking function \n +* @warning +* - Address (offset) plus size of data must not exceed flash size.\n +* - No firmware is required for writing to SPI flash.\n + * - In case of there is a running firmware, it is required to pause your firmware first + * before any trial to access SPI flash to avoid any racing between host and running firmware on bus using + * @ref m2m_wifi_download_mode + * - It is blocking function\n + * @sa m2m_wifi_download_mode, spi_flash_get_size + * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. + + */ +sint8 spi_flash_erase(uint32 u32Offset, uint32 u32Sz); + /**@}*/ +#ifdef ARDUINO +#ifdef __cplusplus +} +#endif +#endif +#endif //__SPI_FLASH_H__ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h new file mode 100644 index 0000000..3b0da53 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h @@ -0,0 +1,245 @@ +/** + * + * \file + * + * \brief WINC1500 SPI Flash. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +/** +* @file spi_flash_map.h +* @brief This module contains spi flash CONTENT +* @author M.S.M +* @date 17 SEPT 2013 +* @version 1.0 +*/ +#ifndef __SPI_FLASH_MAP_H__ +#define __SPI_FLASH_MAP_H__ + +#define FLASH_MAP_VER_0 (0) +#define FLASH_MAP_VER_1 (1) +#define FLASH_MAP_VER_2 (2) +#define FLASH_MAP_VER_3 (3) + +#define FLASH_MAP_VERSION FLASH_MAP_VER_3 + +//#define DOWNLOAD_ROLLBACK +//#define OTA_GEN +#define _PROGRAM_POWER_SAVE_ + +/* =======*=======*=======*=======*======= + * General Sizes for Flash Memory + * =======*=======*=======*=======*======= + */ + +#define FLASH_START_ADDR (0UL) +/*! location :xxxK + * "S:xxxK" -means-> Size is :xxxK + */ + +/* + * Boot Firmware: which used to select which firmware to run + * + */ +#define M2M_BOOT_FIRMWARE_STARTING_ADDR (FLASH_START_ADDR) +#define M2M_BOOT_FIRMWARE_FLASH_SZ (FLASH_SECTOR_SZ) + +/* + * Control Section: which used by Boot firmware + * + */ +#define M2M_CONTROL_FLASH_OFFSET (M2M_BOOT_FIRMWARE_STARTING_ADDR + M2M_BOOT_FIRMWARE_FLASH_SZ) +#define M2M_CONTROL_FLASH_BKP_OFFSET (M2M_CONTROL_FLASH_OFFSET + FLASH_SECTOR_SZ) +#define M2M_CONTROL_FLASH_SEC_SZ (FLASH_SECTOR_SZ) +#define M2M_CONTROL_FLASH_TOTAL_SZ (FLASH_SECTOR_SZ * 2) + +/* + * LUT for PLL and TX Gain settings: + * + */ +#define M2M_PLL_FLASH_OFFSET (M2M_CONTROL_FLASH_OFFSET + M2M_CONTROL_FLASH_TOTAL_SZ) +#define M2M_PLL_FLASH_SZ (1024 * 1) +#define M2M_GAIN_FLASH_OFFSET (M2M_PLL_FLASH_OFFSET + M2M_PLL_FLASH_SZ) +#define M2M_GAIN_FLASH_SZ (M2M_CONFIG_SECT_TOTAL_SZ - M2M_PLL_FLASH_SZ) +#define M2M_CONFIG_SECT_TOTAL_SZ (FLASH_SECTOR_SZ) + +/* + * Certificate: + * + */ +#define M2M_TLS_ROOTCER_FLASH_OFFSET (M2M_PLL_FLASH_OFFSET + M2M_CONFIG_SECT_TOTAL_SZ) +#define M2M_TLS_ROOTCER_FLASH_SIZE (FLASH_SECTOR_SZ * 1) + +/* + * TLS Server Key Files + * + */ +#define M2M_TLS_SERVER_FLASH_OFFSET (M2M_TLS_ROOTCER_FLASH_OFFSET + M2M_TLS_ROOTCER_FLASH_SIZE) +#define M2M_TLS_SERVER_FLASH_SIZE (FLASH_SECTOR_SZ * 2) + +/* + * HTTP Files + * + */ +#define M2M_HTTP_MEM_FLASH_OFFSET (M2M_TLS_SERVER_FLASH_OFFSET + M2M_TLS_SERVER_FLASH_SIZE) +#define M2M_HTTP_MEM_FLASH_SZ (FLASH_SECTOR_SZ * 2) + +/* + * Saved Connection Parameters: + * + */ +#define M2M_CACHED_CONNS_FLASH_OFFSET (M2M_HTTP_MEM_FLASH_OFFSET + M2M_HTTP_MEM_FLASH_SZ) +#define M2M_CACHED_CONNS_FLASH_SZ (FLASH_SECTOR_SZ * 1) + +/* + * + * Common section size + */ + +#define M2M_COMMON_DATA_SEC \ + (\ + M2M_BOOT_FIRMWARE_FLASH_SZ + \ + M2M_CONTROL_FLASH_TOTAL_SZ + \ + M2M_CONFIG_SECT_TOTAL_SZ + \ + M2M_TLS_ROOTCER_FLASH_SIZE + \ + M2M_TLS_SERVER_FLASH_SIZE + \ + M2M_HTTP_MEM_FLASH_SZ + \ + M2M_CACHED_CONNS_FLASH_SZ \ + ) + +/* + * + * OTA image1 Offset + */ + +#define M2M_OTA_IMAGE1_OFFSET (M2M_CACHED_CONNS_FLASH_OFFSET + M2M_CACHED_CONNS_FLASH_SZ) +/* + * Firmware Offset + * + */ +#if (defined _FIRMWARE_)||(defined OTA_GEN) +#define M2M_FIRMWARE_FLASH_OFFSET (0UL) +#else +#if (defined DOWNLOAD_ROLLBACK) +#define M2M_FIRMWARE_FLASH_OFFSET (M2M_OTA_IMAGE2_OFFSET) +#else +#define M2M_FIRMWARE_FLASH_OFFSET (M2M_OTA_IMAGE1_OFFSET) +#endif +#endif +/* + * + * Firmware + */ +#define M2M_FIRMWARE_FLASH_SZ (236 * 1024UL) +/** + * + * OTA image Size + */ +#define OTA_IMAGE_SIZE (M2M_FIRMWARE_FLASH_SZ) +/** + * + * Flash Total size + */ +#define FLASH_IMAGE1_CONTENT_SZ (M2M_COMMON_DATA_SEC + OTA_IMAGE_SIZE) + +/** + * + * OTA image 2 offset + */ +#define M2M_OTA_IMAGE2_OFFSET (FLASH_IMAGE1_CONTENT_SZ) + +/* + * App(Cortus App 4M): App. which runs over firmware + * + */ +#define M2M_APP_4M_MEM_FLASH_SZ (FLASH_SECTOR_SZ * 16) +#define M2M_APP_4M_MEM_FLASH_OFFSET (FLASH_4M_TOTAL_SZ - M2M_APP_4M_MEM_FLASH_SZ) +#define M2M_APP_8M_MEM_FLASH_OFFSET (M2M_OTA_IMAGE2_OFFSET + OTA_IMAGE_SIZE) +#define M2M_APP_8M_MEM_FLASH_SZ (FLASH_SECTOR_SZ * 32) +#define M2M_APP_OTA_MEM_FLASH_OFFSET (M2M_APP_8M_MEM_FLASH_OFFSET + M2M_APP_8M_MEM_FLASH_SZ) + +/* Check if total size of content + * don't exceed total size of memory allowed + **/ +#if (M2M_COMMON_DATA_SEC + (OTA_IMAGE_SIZE *2)> FLASH_4M_TOTAL_SZ) +#error "Excced 4M Flash Size" +#endif /* (FLASH_CONTENT_SZ > FLASH_TOTAL_SZ) */ + + +#endif /* __SPI_FLASH_MAP_H__ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/source/spi_flash.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/source/spi_flash.c new file mode 100644 index 0000000..12eff59 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/source/spi_flash.c @@ -0,0 +1,770 @@ +/** + * + * \file + * + * \brief WINC1500 SPI Flash. + * + * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + */ + +#ifdef PROFILING +#include "windows.h" +#endif +#include "spi_flash/include/spi_flash.h" +#define DUMMY_REGISTER (0x1084) + +#ifdef ARDUINO +#define u32(x) ((uint32)x) +#endif + +#define TIMEOUT (-1) /*MS*/ + +//#define DISABLE_UNSED_FLASH_FUNCTIONS + +#define FLASH_BLOCK_SIZE (32UL * 1024) +/*!> 16); + cmd[2] = (uint8)(u32FlashAdr >> 8); + cmd[3] = (uint8)(u32FlashAdr); + cmd[4] = 0xA5; + + ret += nm_write_reg(SPI_FLASH_DATA_CNT, u32Sz); +#ifdef ARDUINO + ret += nm_write_reg(SPI_FLASH_BUF1, u32(cmd[0])|u32(cmd[1]<<8)|u32(cmd[2]<<16)|u32(cmd[3]<<24)); +#else + ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]|(cmd[1]<<8)|(cmd[2]<<16)|(cmd[3]<<24)); +#endif + ret += nm_write_reg(SPI_FLASH_BUF2, cmd[4]); + ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x1f); + ret += nm_write_reg(SPI_FLASH_DMA_ADDR, u32MemAdr); + ret += nm_write_reg(SPI_FLASH_CMD_CNT, 5 | (1<<7)); + do + { + ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); + if(M2M_SUCCESS != ret) break; + } + while(val != 1); + + return ret; +} + +/** +* @fn spi_flash_sector_erase +* @brief Erase sector (4KB) +* @param[IN] u32FlashAdr +* Any memory address within the sector +* @return Status of execution +* @note Compatible with MX25L6465E and should be working with other types +* @author M. Abdelmawla +* @version 1.0 +*/ +static sint8 spi_flash_sector_erase(uint32 u32FlashAdr) +{ + uint8 cmd[4]; + uint32 val = 0; + sint8 ret = M2M_SUCCESS; + + cmd[0] = 0x20; + cmd[1] = (uint8)(u32FlashAdr >> 16); + cmd[2] = (uint8)(u32FlashAdr >> 8); + cmd[3] = (uint8)(u32FlashAdr); + + ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); +#ifdef ARDUINO + ret += nm_write_reg(SPI_FLASH_BUF1, u32(cmd[0])|u32(cmd[1]<<8)|u32(cmd[2]<<16)|u32(cmd[3]<<24)); +#else + ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]|(cmd[1]<<8)|(cmd[2]<<16)|(cmd[3]<<24)); +#endif + ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x0f); + ret += nm_write_reg(SPI_FLASH_DMA_ADDR, 0); + ret += nm_write_reg(SPI_FLASH_CMD_CNT, 4 | (1<<7)); + do + { + ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); + if(M2M_SUCCESS != ret) break; + } + while(val != 1); + + return ret; +} + +/** +* @fn spi_flash_write_enable +* @brief Send write enable command to SPI flash +* @return Status of execution +* @note Compatible with MX25L6465E and should be working with other types +* @author M. Abdelmawla +* @version 1.0 +*/ +static sint8 spi_flash_write_enable(void) +{ + uint8 cmd[1]; + uint32 val = 0; + sint8 ret = M2M_SUCCESS; + + cmd[0] = 0x06; + + ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); + ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]); + ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x01); + ret += nm_write_reg(SPI_FLASH_DMA_ADDR, 0); + ret += nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1<<7)); + do + { + ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); + if(M2M_SUCCESS != ret) break; + } + while(val != 1); + + return ret; +} + +/** +* @fn spi_flash_write_disable +* @brief Send write disable command to SPI flash +* @note Compatible with MX25L6465E and should be working with other types +* @author M. Abdelmawla +* @version 1.0 +*/ +static sint8 spi_flash_write_disable(void) +{ + uint8 cmd[1]; + uint32 val = 0; + sint8 ret = M2M_SUCCESS; + cmd[0] = 0x04; + + ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); + ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]); + ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x01); + ret += nm_write_reg(SPI_FLASH_DMA_ADDR, 0); + ret += nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1<<7)); + do + { + ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); + if(M2M_SUCCESS != ret) break; + } + while(val != 1); + + return ret; +} + +/** +* @fn spi_flash_page_program +* @brief Write data (less than page size) from cortus memory to SPI flash +* @param[IN] u32MemAdr +* Cortus data address. It must be set to its AHB access address +* @param[IN] u32FlashAdr +* Address to write to at the SPI flash +* @param[IN] u32Sz +* Data size +* @note Compatible with MX25L6465E and should be working with other types +* @author M. Abdelmawla +* @version 1.0 +*/ +static sint8 spi_flash_page_program(uint32 u32MemAdr, uint32 u32FlashAdr, uint32 u32Sz) +{ + uint8 cmd[4]; + uint32 val = 0; + sint8 ret = M2M_SUCCESS; + + cmd[0] = 0x02; + cmd[1] = (uint8)(u32FlashAdr >> 16); + cmd[2] = (uint8)(u32FlashAdr >> 8); + cmd[3] = (uint8)(u32FlashAdr); + + ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); +#ifdef ARDUINO + ret += nm_write_reg(SPI_FLASH_BUF1, u32(cmd[0])|u32(cmd[1]<<8)|u32(cmd[2]<<16)|u32(cmd[3]<<24)); +#else + ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]|(cmd[1]<<8)|(cmd[2]<<16)|(cmd[3]<<24)); +#endif + ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x0f); + ret += nm_write_reg(SPI_FLASH_DMA_ADDR, u32MemAdr); + ret += nm_write_reg(SPI_FLASH_CMD_CNT, 4 | (1<<7) | ((u32Sz & 0xfffff) << 8)); + do + { + ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); + if(M2M_SUCCESS != ret) break; + } + while(val != 1); + + return ret; +} + +/** +* @fn spi_flash_read_internal +* @brief Read from data from SPI flash +* @param[OUT] pu8Buf +* Pointer to data buffer +* @param[IN] u32Addr +* Address to read from at the SPI flash +* @param[IN] u32Sz +* Data size +* @note Data size must be < 64KB (limitation imposed by the bus wrapper) +* @author M. Abdelmawla +* @version 1.0 +*/ +static sint8 spi_flash_read_internal(uint8 *pu8Buf, uint32 u32Addr, uint32 u32Sz) +{ + sint8 ret = M2M_SUCCESS; + /* read size must be < 64KB */ + ret = spi_flash_load_to_cortus_mem(HOST_SHARE_MEM_BASE, u32Addr, u32Sz); + if(M2M_SUCCESS != ret) goto ERR; + ret = nm_read_block(HOST_SHARE_MEM_BASE, pu8Buf, u32Sz); +ERR: + return ret; +} + +/** +* @fn spi_flash_pp +* @brief Program data of size less than a page (256 bytes) at the SPI flash +* @param[IN] u32Offset +* Address to write to at the SPI flash +* @param[IN] pu8Buf +* Pointer to data buffer +* @param[IN] u32Sz +* Data size +* @return Status of execution +* @author M. Abdelmawla +* @version 1.0 +*/ +static sint8 spi_flash_pp(uint32 u32Offset, uint8 *pu8Buf, uint16 u16Sz) +{ + sint8 ret = M2M_SUCCESS; + uint8 tmp; + spi_flash_write_enable(); + /* use shared packet memory as temp mem */ + ret += nm_write_block(HOST_SHARE_MEM_BASE, pu8Buf, u16Sz); + ret += spi_flash_page_program(HOST_SHARE_MEM_BASE, u32Offset, u16Sz); + ret += spi_flash_read_status_reg(&tmp); + do + { + if(ret != M2M_SUCCESS) goto ERR; + ret += spi_flash_read_status_reg(&tmp); + }while(tmp & 0x01); + ret += spi_flash_write_disable(); +ERR: + return ret; +} + +/** +* @fn spi_flash_rdid +* @brief Read SPI Flash ID +* @return SPI FLash ID +* @author M.S.M +* @version 1.0 +*/ +static uint32 spi_flash_rdid(void) +{ + unsigned char cmd[1]; + uint32 reg = 0; + uint32 cnt = 0; + sint8 ret = M2M_SUCCESS; + + cmd[0] = 0x9f; + + ret += nm_write_reg(SPI_FLASH_DATA_CNT, 4); + ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]); + ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x1); + ret += nm_write_reg(SPI_FLASH_DMA_ADDR, DUMMY_REGISTER); + ret += nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1<<7)); + do + { + ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)®); + if(M2M_SUCCESS != ret) break; + if(++cnt > 500) + { + ret = M2M_ERR_INIT; + break; + } + } + while(reg != 1); + reg = (M2M_SUCCESS == ret)?(nm_read_reg(DUMMY_REGISTER)):(0); + M2M_PRINT("Flash ID %x \n",(unsigned int)reg); + return reg; +} + +/** +* @fn spi_flash_unlock +* @brief Unlock SPI Flash +* @author M.S.M +* @version 1.0 +*/ +#if 0 +static void spi_flash_unlock(void) +{ + uint8 tmp; + tmp = spi_flash_read_security_reg(); + spi_flash_clear_security_flags(); + if(tmp & 0x80) + { + spi_flash_write_enable(); + spi_flash_gang_unblock(); + } +} +#endif +static void spi_flash_enter_low_power_mode(void) { + volatile unsigned long tmp; + unsigned char* cmd = (unsigned char*) &tmp; + + cmd[0] = 0xb9; + + nm_write_reg(SPI_FLASH_DATA_CNT, 0); + nm_write_reg(SPI_FLASH_BUF1, cmd[0]); + nm_write_reg(SPI_FLASH_BUF_DIR, 0x1); + nm_write_reg(SPI_FLASH_DMA_ADDR, 0); + nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1 << 7)); + while(nm_read_reg(SPI_FLASH_TR_DONE) != 1); +} + + +static void spi_flash_leave_low_power_mode(void) { + volatile unsigned long tmp; + unsigned char* cmd = (unsigned char*) &tmp; + + cmd[0] = 0xab; + + nm_write_reg(SPI_FLASH_DATA_CNT, 0); + nm_write_reg(SPI_FLASH_BUF1, cmd[0]); + nm_write_reg(SPI_FLASH_BUF_DIR, 0x1); + nm_write_reg(SPI_FLASH_DMA_ADDR, 0); + nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1 << 7)); + while(nm_read_reg(SPI_FLASH_TR_DONE) != 1); +} +/*********************************************/ +/* GLOBAL FUNCTIONS */ +/*********************************************/ +/** + * @fn spi_flash_enable + * @brief Enable spi flash operations + * @author M. Abdelmawla + * @version 1.0 + */ +sint8 spi_flash_enable(uint8 enable) +{ + sint8 s8Ret = M2M_SUCCESS; + if(REV(nmi_get_chipid()) >= REV_3A0) { + uint32 u32Val; + + /* Enable pinmux to SPI flash. */ + s8Ret = nm_read_reg_with_ret(0x1410, &u32Val); + if(s8Ret != M2M_SUCCESS) { + goto ERR1; + } + /* GPIO15/16/17/18 */ + u32Val &= ~((0x7777ul) << 12); + u32Val |= ((0x1111ul) << 12); + nm_write_reg(0x1410, u32Val); + if(enable) { + spi_flash_leave_low_power_mode(); + } else { + spi_flash_enter_low_power_mode(); + } + /* Disable pinmux to SPI flash to minimize leakage. */ + u32Val &= ~((0x7777ul) << 12); + u32Val |= ((0x0010ul) << 12); + nm_write_reg(0x1410, u32Val); + } +ERR1: + return s8Ret; +} +/** +* @fn spi_flash_read +* @brief Read from data from SPI flash +* @param[OUT] pu8Buf +* Pointer to data buffer +* @param[IN] u32offset +* Address to read from at the SPI flash +* @param[IN] u32Sz +* Data size +* @return Status of execution +* @note Data size is limited by the SPI flash size only +* @author M. Abdelmawla +* @version 1.0 +*/ +sint8 spi_flash_read(uint8 *pu8Buf, uint32 u32offset, uint32 u32Sz) +{ + sint8 ret = M2M_SUCCESS; + if(u32Sz > FLASH_BLOCK_SIZE) + { + do + { + ret = spi_flash_read_internal(pu8Buf, u32offset, FLASH_BLOCK_SIZE); + if(M2M_SUCCESS != ret) goto ERR; + u32Sz -= FLASH_BLOCK_SIZE; + u32offset += FLASH_BLOCK_SIZE; + pu8Buf += FLASH_BLOCK_SIZE; + } while(u32Sz > FLASH_BLOCK_SIZE); + } + + ret = spi_flash_read_internal(pu8Buf, u32offset, u32Sz); + +ERR: + return ret; +} + +/** +* @fn spi_flash_write +* @brief Proram SPI flash +* @param[IN] pu8Buf +* Pointer to data buffer +* @param[IN] u32Offset +* Address to write to at the SPI flash +* @param[IN] u32Sz +* Data size +* @return Status of execution +* @author M. Abdelmawla +* @version 1.0 +*/ +sint8 spi_flash_write(uint8* pu8Buf, uint32 u32Offset, uint32 u32Sz) +{ +#ifdef PROFILING + uint32 t1 = 0; + uint32 percent =0; + uint32 tpercent =0; +#endif + sint8 ret = M2M_SUCCESS; + uint32 u32wsz; + uint32 u32off; + uint32 u32Blksz; + u32Blksz = FLASH_PAGE_SZ; + u32off = u32Offset % u32Blksz; +#ifdef PROFILING + tpercent = (u32Sz/u32Blksz)+((u32Sz%u32Blksz)>0); + t1 = GetTickCount(); + M2M_PRINT(">Start programming...\r\n"); +#endif + if(u32Sz<=0) + { + M2M_ERR("Data size = %d",(int)u32Sz); + ret = M2M_ERR_FAIL; + goto ERR; + } + + if (u32off)/*first part of data in the address page*/ + { + u32wsz = u32Blksz - u32off; + if(spi_flash_pp(u32Offset, pu8Buf, (uint16)BSP_MIN(u32Sz, u32wsz))!=M2M_SUCCESS) + { + ret = M2M_ERR_FAIL; + goto ERR; + } + if (u32Sz < u32wsz) goto EXIT; + pu8Buf += u32wsz; + u32Offset += u32wsz; + u32Sz -= u32wsz; + } + while (u32Sz > 0) + { + u32wsz = BSP_MIN(u32Sz, u32Blksz); + + /*write complete page or the remaining data*/ + if(spi_flash_pp(u32Offset, pu8Buf, (uint16)u32wsz)!=M2M_SUCCESS) + { + ret = M2M_ERR_FAIL; + goto ERR; + } + pu8Buf += u32wsz; + u32Offset += u32wsz; + u32Sz -= u32wsz; +#ifdef PROFILING + percent++; + printf("\r>Complete Percentage = %d%%.\r",((percent*100)/tpercent)); +#endif + } +EXIT: +#ifdef PROFILING + M2M_PRINT("\rDone\t\t\t\t\t\t"); + M2M_PRINT("\n#Programming time = %f sec\n\r",(GetTickCount() - t1)/1000.0); +#endif +ERR: + return ret; +} + +/** +* @fn spi_flash_erase +* @brief Erase from data from SPI flash +* @param[IN] u32Offset +* Address to write to at the SPI flash +* @param[IN] u32Sz +* Data size +* @return Status of execution +* @note Data size is limited by the SPI flash size only +* @author M. Abdelmawla +* @version 1.0 +*/ +sint8 spi_flash_erase(uint32 u32Offset, uint32 u32Sz) +{ + uint32 i = 0; + sint8 ret = M2M_SUCCESS; + uint8 tmp = 0; +#ifdef PROFILING + uint32 t; + t = GetTickCount(); +#endif + M2M_PRINT("\r\n>Start erasing...\r\n"); + for(i = u32Offset; i < (u32Sz +u32Offset); i += (16*FLASH_PAGE_SZ)) + { + ret += spi_flash_write_enable(); + ret += spi_flash_read_status_reg(&tmp); + ret += spi_flash_sector_erase(i + 10); + ret += spi_flash_read_status_reg(&tmp); + do + { + if(ret != M2M_SUCCESS) goto ERR; + ret += spi_flash_read_status_reg(&tmp); + }while(tmp & 0x01); + + } + M2M_PRINT("Done\r\n"); +#ifdef PROFILING + M2M_PRINT("#Erase time = %f sec\n", (GetTickCount()-t)/1000.0); +#endif +ERR: + return ret; +} + +/** +* @fn spi_flash_get_size +* @brief Get size of SPI Flash +* @return Size of Flash +* @author M.S.M +* @version 1.0 +*/ +uint32 spi_flash_get_size(void) +{ + uint32 u32FlashId = 0, u32FlashPwr = 0; + static uint32 gu32InernalFlashSize= 0; + + if(!gu32InernalFlashSize) + { + u32FlashId = spi_flash_rdid();//spi_flash_probe(); + if(u32FlashId != 0xffffffff) + { + /*flash size is the third byte from the FLASH RDID*/ + u32FlashPwr = ((u32FlashId>>16)&0xff) - 0x11; /*2MBIT is the min*/ + /*That number power 2 to get the flash size*/ + gu32InernalFlashSize = 1< +#include +#include "config.h" +#include +#include "watchdog.h" +#include "rtc.h" +#include "transmit.h" + +#ifdef HEATSEEK_FEATHER_WIFI_WICED +char const* get_encryption_str(int32_t enc_type); +#endif + +CONFIG_union CONFIG; +static DHT dht(DHT_DATA, DHT22); + +void write_config() { + File config_file; + + if (config_file = SD.open("config.bin", FILE_WRITE | O_TRUNC)) { + config_file.write(CONFIG.raw, sizeof(CONFIG)); + config_file.close(); + } else { + Serial.println("unable to update config"); + while(true); // watchdog will reboot + } +} + +bool read_config() { + File config_file; + bool success = false; + + if (config_file = SD.open("config.bin", FILE_READ)) { + int read_size = config_file.read(CONFIG.raw, sizeof(CONFIG)); + + if (sizeof(CONFIG) == read_size) { + Serial.print("Version from file: "); + Serial.print(CONFIG.data.version); + Serial.print("; expected version: "); + Serial.println(CONFIG_VERSION); + if (CONFIG.data.version == CONFIG_VERSION) { + Serial.println("config loaded"); + success = true; + } else { + Serial.println("incorrect config version"); + } + } else { + Serial.print("config incorrect size - expected: "); + Serial.print(sizeof(CONFIG)); + Serial.print(", got: "); + Serial.println(read_size); + } + + config_file.close(); + } else { + Serial.println("unable to read config"); + } + + return success; +} + +void set_default_config() { + CONFIG.data.version = CONFIG_VERSION; + CONFIG.data.reading_interval_s = 5 * 60; + CONFIG.data.cell_configured = 0; + CONFIG.data.wifi_configured = 0; + CONFIG.data.temperature_offset_f = 0.0; + + strcpy(CONFIG.data.hub_id, "featherhub"); + + strcpy(CONFIG.data.endpoint_domain, "relay.heatseek.org"); + strcpy(CONFIG.data.endpoint_path, "/temperatures"); + CONFIG.data.endpoint_configured = 1; +} + +int read_input_until_newline(char *message, char *buffer) { + int i = 0; + bool reached_newline = false; + + while (true) { + Serial.println(message); + + while (Serial.available()) { + char c = Serial.read(); + if (c == '\n') { +// Serial.println("done setting"); + reached_newline = true; + break; + } else { + buffer[i++] = c; + } + } + if (reached_newline) break; + + watchdog_feed(); + delay(2000); + } + + return i; +} + +void print_menu() { + Serial.println("-------------------------------------"); + Serial.println("[?] Print this menu"); + Serial.println("[t] Set RTC"); + Serial.println("[r] Set reading interval"); + Serial.println("[q] Clear reading transmission queue"); + Serial.println("[v] Calibrate temperature sensor"); + #ifdef TRANSMITTER_WIFI + Serial.println("[w] Setup wifi"); + Serial.println("[a] List nearby access points"); + #endif + Serial.println("[i] Setup Cell ID"); + Serial.println("[e] Setup API Endpoint"); + Serial.println("[p] Print config"); + Serial.println("[d] Reset config"); + Serial.println("[s] Exit config"); +} + +void print_config_info() { + Serial.println("-------------------------------------"); + Serial.println("Current config:"); + + #ifdef TRANSMITTER_WIFI + if (CONFIG.data.wifi_configured) { + Serial.print("wifi ssid: "); + Serial.print(CONFIG.data.wifi_ssid); + Serial.print(", wifi pass: "); + Serial.print(CONFIG.data.wifi_pass); + } else { + Serial.print("Wifi not configured"); + } + + Serial.println(); + #endif + + if (CONFIG.data.cell_configured) { + Serial.print("hub id: "); + Serial.print(CONFIG.data.hub_id); + Serial.print(", cell id: "); + Serial.print(CONFIG.data.cell_id); + } else { + Serial.print("cell id not configured"); + } + Serial.println(); + + if (CONFIG.data.endpoint_configured) { + Serial.print("endpoint: "); + Serial.print(CONFIG.data.endpoint_domain); + Serial.print(CONFIG.data.endpoint_path); + } else { + Serial.print("endpoint not configured"); + } + Serial.println(); + + Serial.print("reading_interval (seconds): "); + Serial.println(CONFIG.data.reading_interval_s); +} + +void enter_configuration() { + print_menu(); + + while(true) { + char command = Serial.read(); + while(Serial.available()) { Serial.read(); } + + switch (command) { + case '?': { + print_menu(); + break; + } + case 't': { + rtc_set(); + print_menu(); + break; + } + case 'q': { + clear_queued_transmissions(); + print_menu(); + break; + } + case 'r': { + char buffer[200]; + int length; + + length = read_input_until_newline("Enter Reading interval in seconds", buffer); + buffer[length] = '\0'; + CONFIG.data.reading_interval_s = strtol(buffer, NULL, 0); + + write_config(); + + update_last_reading_time(0); // take initial reading after configuration + clear_queued_transmissions(); // clear transmission queue + + Serial.println("Reading interval Configured"); + print_config_info(); + print_menu(); + break; + } +#ifdef TRANSMITTER_WIFI + case 'w': { + char buffer[200]; + int length; + + length = read_input_until_newline("Enter WiFi SSID", buffer); + buffer[length] = '\0'; + strcpy(CONFIG.data.wifi_ssid, buffer); + + length = read_input_until_newline("Enter WiFi password", buffer); + buffer[length] = '\0'; + strcpy(CONFIG.data.wifi_pass, buffer); + + CONFIG.data.wifi_configured = 1; + write_config(); + force_wifi_reconnect(); + + Serial.println("Wifi Configured"); + print_config_info(); + print_menu(); + break; + } +#endif +#ifdef HEATSEEK_FEATHER_WIFI_WICED + case 'a': { + wl_ap_info_t ap_list[20]; + int networkCount = 0; + networkCount = Feather.scanNetworks(ap_list, 20); + + Serial.println("========="); + Serial.print("Found "); Serial.print(networkCount); Serial.println(" Networks"); + + for (int i = 0; i < networkCount; i++) { + Serial.println("========="); + wl_ap_info_t ap = ap_list[i]; + Serial.print("SSID: "); Serial.println(ap.ssid); + Serial.print("RSSI: "); Serial.println(ap.rssi); + Serial.print("max data rate: "); Serial.println(ap.max_data_rate); + Serial.print("network type: "); Serial.println(ap.network_type); + Serial.print("security: "); Serial.print(ap.security); Serial.print(" - "); Serial.println(get_encryption_str(ap.security)); + Serial.print("channel: "); Serial.println(ap.channel); + Serial.print("band_2_4ghz: "); Serial.println(ap.band_2_4ghz); + } + + break; + } +#endif +#ifdef HEATSEEK_FEATHER_WIFI_M0 + case 'a': { + int networkCount = -1; + WiFi.setPins(8, 7, 4, 2); + networkCount = WiFi.scanNetworks(); + + Serial.println("========="); + Serial.print("Found "); Serial.print(networkCount); Serial.println(" Networks"); + + for (int i = 0; i < networkCount; i++) { + Serial.println("========="); + Serial.print("SSID: "); Serial.println(WiFi.SSID(i)); + Serial.print("RSSI: "); Serial.println(WiFi.RSSI(i)); + Serial.print("security: "); + switch (WiFi.encryptionType(i)) { + case ENC_TYPE_WEP: + Serial.println("WEP"); + case ENC_TYPE_TKIP: + Serial.println("WPA"); + case ENC_TYPE_CCMP: + Serial.println("WPA2"); + case ENC_TYPE_NONE: + Serial.println("None"); + case ENC_TYPE_AUTO: + Serial.println("Auto"); + } + } + print_menu(); + break; + } +#endif + case 'i': { + char buffer[200]; + int length; + +// hub is now always set to 'featherhub' +// length = read_input_until_newline("Enter HUB ID", buffer); +// buffer[length] = '\0'; +// strcpy(CONFIG.data.hub_id, buffer); + + length = read_input_until_newline("Enter CELL ID", buffer); + buffer[length] = '\0'; + strcpy(CONFIG.data.cell_id, buffer); + + CONFIG.data.cell_configured = 1; + write_config(); + + Serial.println("Cell ID Configured"); + print_config_info(); + print_menu(); + break; + } + case 'e': { + char buffer[200]; + int length; + + length = read_input_until_newline("Enter domain of API endpoint (Example: 'heatseek.org')", buffer); + buffer[length] = '\0'; + strcpy(CONFIG.data.endpoint_domain, buffer); + + length = read_input_until_newline("Enter path of API endpoint (Example: '/readings/create')", buffer); + buffer[length] = '\0'; + strcpy(CONFIG.data.endpoint_path, buffer); + + CONFIG.data.endpoint_configured = 1; + write_config(); + + Serial.println("API Endpoint configured"); + print_config_info(); + print_menu(); + break; + } + case 'd': { + Serial.println("reseting config"); + set_default_config(); + write_config(); + + print_config_info(); + print_menu(); + break; + } + case 'p': { + Serial.println("print config info"); + print_config_info(); + break; + } + case 's': { + Serial.println("exiting config"); + return; + } + case 'v': { + char buffer[200]; + int length; + float current_temp; + int readings_taken = 0; + float temperature_f; + float average_temperature_f = 0.0; + + length = read_input_until_newline("Enter current temperature, in fahrenheit, with one decimal place. For example: '41.0'. PLEASE ENSURE THAT SENSOR IS ON FOR APPROX. 5 MINUTES BEFORE CALIBRATING!", buffer); + buffer[length] = '\0'; + current_temp = strtof(buffer, NULL); + + while (readings_taken < 5) { + watchdog_feed(); + Serial.println("Calibrating, please wait..."); + temperature_f = dht.readTemperature(true); + + if (!isnan(temperature_f)) { + if (average_temperature_f == 0.0) { + average_temperature_f = temperature_f; + } else { + average_temperature_f = (average_temperature_f + temperature_f) / 2; + } + } else { + Serial.println("Failed to read temperature sensor; reboot device and try again."); + while(true); + } + + watchdog_feed(); + readings_taken++; + delay(2000); + } + + watchdog_feed(); + + float temperature_offset = current_temp - average_temperature_f; + CONFIG.data.temperature_offset_f = temperature_offset; + write_config(); + + Serial.print("Temperature offset set to: "); + Serial.println(temperature_offset); + + print_config_info(); + print_menu(); + break; + } + } + + watchdog_feed(); + delay(50); + } +} + +uint32_t get_last_reading_time() { + File reading_time_file; + uint8_t data[4]; + + if (reading_time_file = SD.open("time.bin", FILE_READ)) { + reading_time_file.read(data, sizeof(data)); + reading_time_file.close(); + } else { + Serial.println("unable to read last reading time"); + return 0; + } + + return data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); +} + +void update_last_reading_time(uint32_t timestamp) { + uint8_t data[4]; + + data[0] = (timestamp & 0x000000ff); + data[1] = (timestamp & 0x0000ff00) >> 8; + data[2] = (timestamp & 0x00ff0000) >> 16; + data[3] = (timestamp & 0xff000000) >> 24; + + File reading_time_file; + + if (reading_time_file = SD.open("time.bin", FILE_WRITE | O_TRUNC)) { + reading_time_file.write(data, sizeof(data)); + reading_time_file.close(); + } else { + Serial.println("unable to update last reading time"); + while(true); // watchdog will reboot + } + + Serial.println("updated last reading time"); +} + +#ifdef HEATSEEK_FEATHER_WIFI_WICED +char const* get_encryption_str(int32_t enc_type) +{ + // read the encryption type and print out the name: + switch (enc_type) + { + case ENC_TYPE_AUTO: return "ENC_TYPE_AUTO"; + case ENC_TYPE_OPEN: return "ENC_TYPE_OPEN"; + case ENC_TYPE_WEP: return "ENC_TYPE_WEP"; + case ENC_TYPE_WEP_SHARED: return "ENC_TYPE_WEP_SHARED"; + case ENC_TYPE_WPA_TKIP: return "ENC_TYPE_WPA_TKIP"; + case ENC_TYPE_WPA_AES: return "ENC_TYPE_WPA_AES"; + case ENC_TYPE_WPA_MIXED: return "ENC_TYPE_WPA_MIXED"; + case ENC_TYPE_WPA2_AES: return "ENC_TYPE_WPA2_AES"; + case ENC_TYPE_WPA2_TKIP: return "ENC_TYPE_WPA2_TKIP"; + case ENC_TYPE_WPA2_MIXED: return "ENC_TYPE_WPA2_MIXED"; + case ENC_TYPE_WPA_TKIP_ENT: return "ENC_TYPE_WPA_TKIP_ENT"; + case ENC_TYPE_WPA_AES_ENT: return "ENC_TYPE_WPA_AES_ENT"; + case ENC_TYPE_WPA_MIXED_ENT: return "ENC_TYPE_WPA_MIXED_ENT"; + case ENC_TYPE_WPA2_TKIP_ENT: return "ENC_TYPE_WPA2_TKIP_ENT"; + case ENC_TYPE_WPA2_AES_ENT: return "ENC_TYPE_WPA2_AES_ENT"; + case ENC_TYPE_WPA2_MIXED_ENT: return "ENC_TYPE_WPA2_MIXED_ENT"; + case ENC_TYPE_WPS_OPEN: return "ENC_TYPE_WPS_OPEN"; + case ENC_TYPE_WPS_SECURE: return "ENC_TYPE_WPS_SECURE"; + case ENC_TYPE_IBSS_OPEN: return "ENC_TYPE_IBSS_OPEN"; + default: return "UNKNOWN"; + } +} +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/config.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/config.h new file mode 100644 index 0000000..1a10ad2 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/config.h @@ -0,0 +1,39 @@ +#ifndef CONFIG_H +#define CONFIG_H + +#define CONFIG_VERSION 6 + +typedef struct { + uint16_t version; + int32_t reading_interval_s; + + float temperature_offset_f; + + uint8_t cell_configured; + char hub_id[50]; + char cell_id[50]; + + uint8_t wifi_configured; + char wifi_ssid[50]; + char wifi_pass[200]; + + uint8_t endpoint_configured; + char endpoint_domain[100]; + char endpoint_path[100]; +} CONFIG_struct; + +typedef union { + CONFIG_struct data; + uint8_t raw[sizeof(CONFIG_struct)]; +} CONFIG_union; + +extern CONFIG_union CONFIG; + +void write_config(); +bool read_config(); +void set_default_config(); +void enter_configuration(); +uint32_t get_last_reading_time(); +void update_last_reading_time(uint32_t timestamp); + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.cpp new file mode 100644 index 0000000..bc4d8eb --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.cpp @@ -0,0 +1,178 @@ +/******************************************************/ +// THIS IS A GENERATED FILE - DO NOT EDIT // +/******************************************************/ + +#include "application.h" +#line 1 "/Users/shrutiverma/feather_sensor/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.ino" +#include +#include +#include +#include +#include "user_config.h" +#include "transmit.h" +#include "config.h" +#include "watchdog.h" +#include "rtc.h" + +void setup(); +void loop(); +void read_temperatures(float *temperature_f, float *humidity, float *heat_index); +void log_to_sd(float temperature_f, float humidity, float heat_index, uint32_t current_time); +void initialize_sd(); +#line 11 "/Users/shrutiverma/feather_sensor/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.ino" +static DHT dht(DHT_DATA, DHT22); +uint32_t startup_millis = 0; + +void setup() { + watchdog_init(); + + Serial.begin(9600); + delay(2000); + + Serial.print("initializing heatseek data logger: "); + #ifdef TRANSMITTER_WIFI + Serial.println("WIFI"); + #else + Serial.println("cellular"); + #endif + + initialize_sd(); + rtc_initialize(); + + dht.begin(); + + if (!read_config()) set_default_config(); + + watchdog_feed(); + + startup_millis = millis(); +} + +void loop() { + float temperature_f; + float humidity; + float heat_index; + + int32_t current_time = rtc.now().unixtime(); + int32_t last_reading_time = get_last_reading_time(); + int32_t time_since_last_reading = current_time - last_reading_time; + + char command = Serial.read(); + if (command == 'C') { + enter_configuration(); + } + + Serial.print("Time since last reading: "); + Serial.print(time_since_last_reading); + Serial.print(", reading_interval: "); + Serial.print(CONFIG.data.reading_interval_s); + Serial.print(". Code version: "); + Serial.print(CODE_VERSION); + Serial.println(". Press 'C' to enter config."); + + if (millis() - startup_millis < 15000) { + Serial.println("Allowing 15 seconds to enter config mode [C] before taking first reading."); + watchdog_feed(); + delay(2000); + return; + } + + if (CONFIG.data.reading_interval_s - time_since_last_reading > SEND_SAVED_READINGS_THRESHOLD) { + Serial.println("Checking for queued temperature readings"); + watchdog_feed(); + transmit_queued_temps(); + delay(2000); + watchdog_feed(); + return; + } else if (time_since_last_reading < CONFIG.data.reading_interval_s) { + delay(2000); + watchdog_feed(); + return; + } + + watchdog_feed(); + + read_temperatures(&temperature_f, &humidity, &heat_index); + log_to_sd(temperature_f, humidity, heat_index, current_time); + + watchdog_feed(); + + update_last_reading_time(current_time); + watchdog_feed(); + + transmit(temperature_f, humidity, heat_index, current_time); + + watchdog_feed(); + + delay(2000); +} + +void read_temperatures(float *temperature_f, float *humidity, float *heat_index) { + while (true) { + bool success = true; + + *temperature_f = dht.readTemperature(true); + *humidity = dht.readHumidity(); + + if (!isnan(*temperature_f) && !isnan(*humidity)) { + Serial.print("Temperature (actual reading): "); + Serial.print(*temperature_f); + Serial.println(" *F"); + + *temperature_f = *temperature_f + CONFIG.data.temperature_offset_f; + Serial.print("Temperature (after calibration): "); + Serial.print(*temperature_f); + Serial.println(" *F"); + + Serial.print("Humidity: "); + Serial.print(*humidity); + Serial.println("%"); + + *heat_index = dht.computeHeatIndex(*temperature_f, *humidity); + + Serial.print("Heat index: "); + Serial.println(*heat_index); + + return; + + } else { + Serial.println("Error reading temperatures!"); + } + + delay(2000); + + // if we continue to fail to read a temperature, the watchdog will + // eventually cause a reboot + } +} + +void log_to_sd(float temperature_f, float humidity, float heat_index, uint32_t current_time) { + Serial.println("writing to SD card..."); + + File data_file; + + if (data_file = SD.open("data.csv", FILE_WRITE)) { + data_file.print(current_time); data_file.print(","); + data_file.print(temperature_f); data_file.print(","); + data_file.print(humidity); data_file.print(","); + data_file.print(heat_index); data_file.println(); + Serial.println("wrote to SD"); + data_file.close(); + } else { + Serial.println("unable to open data.csv"); + while(true); // watchdog will reboot + } +} + +void initialize_sd() { + // Stop LORA module from interfering with SPI + #ifdef TRANSMITTER_GSM + pinMode(LORA_CS, OUTPUT); + digitalWrite(LORA_CS, HIGH); + #endif + + while (!SD.begin(SD_CS)) { + Serial.println("failed to initialize SD card"); + delay(1000); // watchdog will reboot + } +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.ino new file mode 100644 index 0000000..4f28524 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.ino @@ -0,0 +1,166 @@ +#include +#include +#include +#include +#include "user_config.h" +#include "transmit.h" +#include "config.h" +#include "watchdog.h" +#include "rtc.h" + +static DHT dht(DHT_DATA, DHT22); +uint32_t startup_millis = 0; + +void setup() { + watchdog_init(); + + Serial.begin(9600); + delay(2000); + + Serial.print("initializing heatseek data logger: "); + #ifdef TRANSMITTER_WIFI + Serial.println("WIFI"); + #else + Serial.println("cellular"); + #endif + + initialize_sd(); + rtc_initialize(); + + dht.begin(); + + if (!read_config()) set_default_config(); + + watchdog_feed(); + + startup_millis = millis(); +} + +void loop() { + float temperature_f; + float humidity; + float heat_index; + + int32_t current_time = rtc.now().unixtime(); + int32_t last_reading_time = get_last_reading_time(); + int32_t time_since_last_reading = current_time - last_reading_time; + + char command = Serial.read(); + if (command == 'C') { + enter_configuration(); + } + + Serial.print("Time since last reading: "); + Serial.print(time_since_last_reading); + Serial.print(", reading_interval: "); + Serial.print(CONFIG.data.reading_interval_s); + Serial.print(". Code version: "); + Serial.print(CODE_VERSION); + Serial.println(". Press 'C' to enter config."); + + if (millis() - startup_millis < 15000) { + Serial.println("Allowing 15 seconds to enter config mode [C] before taking first reading."); + watchdog_feed(); + delay(2000); + return; + } + + if (CONFIG.data.reading_interval_s - time_since_last_reading > SEND_SAVED_READINGS_THRESHOLD) { + Serial.println("Checking for queued temperature readings"); + watchdog_feed(); + transmit_queued_temps(); + delay(2000); + watchdog_feed(); + return; + } else if (time_since_last_reading < CONFIG.data.reading_interval_s) { + delay(2000); + watchdog_feed(); + return; + } + + watchdog_feed(); + + read_temperatures(&temperature_f, &humidity, &heat_index); + log_to_sd(temperature_f, humidity, heat_index, current_time); + + watchdog_feed(); + + update_last_reading_time(current_time); + watchdog_feed(); + + transmit(temperature_f, humidity, heat_index, current_time); + + watchdog_feed(); + + delay(2000); +} + +void read_temperatures(float *temperature_f, float *humidity, float *heat_index) { + while (true) { + bool success = true; + + *temperature_f = dht.readTemperature(true); + *humidity = dht.readHumidity(); + + if (!isnan(*temperature_f) && !isnan(*humidity)) { + Serial.print("Temperature (actual reading): "); + Serial.print(*temperature_f); + Serial.println(" *F"); + + *temperature_f = *temperature_f + CONFIG.data.temperature_offset_f; + Serial.print("Temperature (after calibration): "); + Serial.print(*temperature_f); + Serial.println(" *F"); + + Serial.print("Humidity: "); + Serial.print(*humidity); + Serial.println("%"); + + *heat_index = dht.computeHeatIndex(*temperature_f, *humidity); + + Serial.print("Heat index: "); + Serial.println(*heat_index); + + return; + + } else { + Serial.println("Error reading temperatures!"); + } + + delay(2000); + + // if we continue to fail to read a temperature, the watchdog will + // eventually cause a reboot + } +} + +void log_to_sd(float temperature_f, float humidity, float heat_index, uint32_t current_time) { + Serial.println("writing to SD card..."); + + File data_file; + + if (data_file = SD.open("data.csv", FILE_WRITE)) { + data_file.print(current_time); data_file.print(","); + data_file.print(temperature_f); data_file.print(","); + data_file.print(humidity); data_file.print(","); + data_file.print(heat_index); data_file.println(); + Serial.println("wrote to SD"); + data_file.close(); + } else { + Serial.println("unable to open data.csv"); + while(true); // watchdog will reboot + } +} + +void initialize_sd() { + // Stop LORA module from interfering with SPI + #ifdef TRANSMITTER_GSM + pinMode(LORA_CS, OUTPUT); + digitalWrite(LORA_CS, HIGH); + #endif + + while (!SD.begin(SD_CS)) { + Serial.println("failed to initialize SD card"); + delay(1000); // watchdog will reboot + } +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/rtc.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/rtc.cpp new file mode 100644 index 0000000..108127e --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/rtc.cpp @@ -0,0 +1,58 @@ +#include "rtc.h" +#include "watchdog.h" +#include "config.h" + +RTC_PCF8523 rtc; + +void rtc_initialize() { + if (!rtc.begin()) { + Serial.println("Couldn't find RTC"); + while (true); // watchdog will reboot + } + + if (!rtc.initialized()) { + Serial.print("RTC is NOT running! "); + Serial.println(rtc.now().unixtime()); + // TODO - this could make a web request to set and continually update the RTC + rtc_set(); + } +} + +void rtc_set() { + char timestamp[50]; + int i = 0; + bool timestamp_input = false; + uint32_t value = 0; + + while (true) { + Serial.println("Setting RTC, enter the current unix timestamp"); + + while (Serial.available()) { + char c = Serial.read(); + timestamp[i++] = c; + if (c == '\n') { timestamp_input = true; } + } + + if (timestamp_input) { + value = strtoul(timestamp, NULL, 0); + + // sanity check + if (value < 1810148331 && value > 1494614996) { + Serial.println("done setting"); + break; + } else { + Serial.println("The value you entered looks wrong - please try again"); + timestamp_input = false; + i = 0; + } + } + watchdog_feed(); + delay(2000); + } + + Serial.print("setting timestamp to: "); + Serial.println(value); + + rtc.adjust(DateTime(value)); + update_last_reading_time(0); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/rtc.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/rtc.h new file mode 100644 index 0000000..21befff --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/rtc.h @@ -0,0 +1,11 @@ +#ifndef RTC_H +#define RTC_H + +#include + +extern RTC_PCF8523 rtc; + +void rtc_initialize(); +void rtc_set(); + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/transmit.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/transmit.cpp new file mode 100644 index 0000000..99ef317 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/transmit.cpp @@ -0,0 +1,513 @@ +#include "transmit.h" +#include "config.h" +#include "watchdog.h" +#include + +#ifdef HEATSEEK_BORON_LTE + TCPClient tcpClient; + bool lteConnected = false; +#endif + +#ifdef HEATSEEK_FEATHER_WIFI_WICED + AdafruitHTTP http; + bool wifiConnected = false; + volatile bool response_received = false; + volatile bool transmit_success = false; +#endif + +#ifdef HEATSEEK_FEATHER_WIFI_M0 + WiFiClient wifiClient; + bool wifiConnected = false; +#endif + +#ifdef TRANSMITTER_GSM + #include + + HardwareSerial *fonaSerial = &Serial1; + + Adafruit_FONA fona = Adafruit_FONA(FONA_RST); + bool gsmConnected = false; +#endif + +#ifdef TRANSMITTER_GSM + bool fona_post(float temperature_f, float humidity, float heat_index, uint32_t current_time) { + fona.HTTP_POST_end(); + + uint16_t statuscode; + int16_t length; + + char url[200]; + strcpy(url, CONFIG.data.endpoint_domain); + strcat(url, CONFIG.data.endpoint_path); + + char data[200]; + + char temperature_buffer[10]; + char humidity_buffer[10]; + char heat_index_buffer[10]; + + dtostrf(temperature_f, 4, 3, temperature_buffer); + dtostrf(humidity, 4, 3, humidity_buffer); + dtostrf(heat_index, 4, 3, heat_index_buffer); + + sprintf(data, "temp=%s&humidity=%s&heat_index=%s&hub=%s&cell=%s&time=%d&sp=%d&cell_version=%s", temperature_buffer, humidity_buffer, heat_index_buffer, CONFIG.data.hub_id, CONFIG.data.cell_id, current_time, CONFIG.data.reading_interval_s, CODE_VERSION); + + Serial.print("posting to: "); Serial.println(url); + Serial.print("with data: "); Serial.println(data); + + if (!fona.HTTP_POST_start(url, F("application/x-www-form-urlencoded"), (uint8_t *) data, strlen(data), &statuscode, (uint16_t *)&length)) { + return false; + } + + Serial.println("reading status"); + + if (statuscode != 200) { + Serial.print("status not 200: "); + Serial.println(statuscode); + return false; + } + + fona.HTTP_POST_end(); + return true; + } + + void connect_to_fona() { + Serial.println('starting fona serial'); + fonaSerial->begin(4800); + + Serial.println('starting fona serial 2'); + if (!fona.begin(*fonaSerial)) { + Serial.println("Couldn't find FONA"); + while(true); // watchdog will reboot + } + + watchdog_feed(); + delay(2000); + + Serial.println('enabling FONA GPRS'); + + uint32_t start = millis(); + + while (!fona.enableGPRS(true)) { + delay(1000); + watchdog_feed(); + + if (millis() - start > 60000) { + Serial.println("failed to start FONA GPRS after 60 sec"); + while (true); + } + } + + Serial.println("Enabled FONA GRPS"); + + gsmConnected = true; + } + + bool _transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time) { + if (!CONFIG.data.cell_configured || !CONFIG.data.endpoint_configured) { + Serial.println("cannot send data - not configured"); + return false; + } + + if (!gsmConnected) connect_to_fona(); + watchdog_feed(); + + int transmit_attempts = 1; + + while (!fona_post(temperature_f, humidity, heat_index, current_time)) { + Serial.print("failed to POST, trying again... attempt #"); + Serial.println(transmit_attempts); + + if (transmit_attempts < 4) { + transmit_attempts++; + watchdog_feed(); + delay(500); + } else { + while (true); + } + } + + return true; + } +#endif + +#ifdef HEATSEEK_FEATHER_WIFI_WICED + void force_wifi_reconnect(void) { + wifiConnected = false; + } + + void receive_callback(void) { + http.respParseHeader(); + int status_received = http.respStatus(); + + Serial.printf("transmitted - received status: (%d) \n", status_received); + + http.stop(); + response_received = true; + transmit_success = (status_received == 200); + } + + void connect_to_wifi() { + Serial.print("Please wait while connecting to:"); + Serial.print(CONFIG.data.wifi_ssid); + Serial.println("... "); + + if (Feather.connect(CONFIG.data.wifi_ssid, CONFIG.data.wifi_pass)) { + Serial.println("Connected!"); + wifiConnected = true; + } else { + Serial.printf("Failed! %s (%d) \n", Feather.errstr()); + } + Serial.println(); + + if (!Feather.connected()) { return; } + + // Connected: Print network info + Feather.printNetwork(); + + // Tell the HTTP client to auto print error codes and halt on errors + http.err_actions(true, true); + + // Set HTTP client verbose + http.verbose(true); + + // Set the callback handlers + http.setReceivedCallback(receive_callback); + } + + bool _transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time) { + if (!CONFIG.data.cell_configured || !CONFIG.data.wifi_configured || !CONFIG.data.endpoint_configured) { + Serial.println("cannot send data - not configured"); + return false; + } + + while (!wifiConnected) { connect_to_wifi(); } + + http.connect(CONFIG.data.endpoint_domain, PORT); // Will halt if an error occurs + + http.addHeader("User-Agent", USER_AGENT_HEADER); + http.addHeader("Connection", "close"); + http.addHeader("Content-Type", "application/x-www-form-urlencoded"); + + char time_buffer[30]; + char temperature_buffer[30]; + char humidity_buffer[30]; + char heat_index_buffer[30]; + char reading_interval_buffer[30]; + + sprintf(time_buffer, "%d", current_time); + sprintf(reading_interval_buffer, "%d", CONFIG.data.reading_interval_s); + sprintf(temperature_buffer, "%.3f", temperature_f); + sprintf(humidity_buffer, "%.3f", humidity); + sprintf(heat_index_buffer, "%.3f", heat_index); + + const char* post_data[][2] = + { + {"hub", CONFIG.data.hub_id}, + {"cell", CONFIG.data.cell_id}, + {"time", time_buffer}, + {"temp", temperature_buffer}, + {"humidity", humidity_buffer}, + {"sp", reading_interval_buffer}, + {"heat_index", heat_index_buffer}, + {"cell_version", CODE_VERSION}, + }; + int param_count = 8; + + response_received = false; + transmit_success = false; + + http.post(CONFIG.data.endpoint_domain, CONFIG.data.endpoint_path, post_data, param_count); // Will halt if an error occurs + + while (!response_received || !transmit_success); // Hang if transmit doesn't complete or fails + + return true; + } +#endif + +#ifdef HEATSEEK_FEATHER_WIFI_M0 + void force_wifi_reconnect(void) { + if (wifiConnected) { + wifiConnected = false; + WiFi.end(); + } + } + + void connect_to_wifi() { + WiFi.setPins(8, 7, 4, 2); + + Serial.print("Please wait while connecting to:"); + Serial.print(CONFIG.data.wifi_ssid); + Serial.println("... "); + + int status = WL_IDLE_STATUS; + + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + status = WiFi.begin(CONFIG.data.wifi_ssid, CONFIG.data.wifi_pass); + + while (status != WL_CONNECTED) { + delay(1000); + Serial.println("Establishing connection..."); + } + + wifiConnected = true; + Serial.println("Connected to WiFi"); + + Serial.print("SSID: "); + Serial.println(WiFi.SSID()); + + // print the received signal strength: + long rssi = WiFi.RSSI(); + Serial.print("signal strength (RSSI):"); + Serial.print(rssi); + Serial.println(" dBm"); + + watchdog_feed(); + } + + bool _transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time) { + if (!CONFIG.data.cell_configured || !CONFIG.data.wifi_configured || !CONFIG.data.endpoint_configured) { + Serial.println("cannot send data - not configured"); + return false; + } + + if (!wifiConnected) { connect_to_wifi(); } + + HttpClient client = HttpClient(wifiClient, CONFIG.data.endpoint_domain, 80); + + String contentType = "application/x-www-form-urlencoded"; + String data = "temp=" + String(temperature_f, 3) + "&humidity=" + String(humidity, 3) + "&heat_index=" + String(heat_index, 3) + "&hub=" + CONFIG.data.hub_id + "&cell=" + CONFIG.data.cell_id + "&time=" + current_time + "&sp=" + CONFIG.data.reading_interval_s + "&cell_version=" + CODE_VERSION; + + Serial.print("Posting data: "); + Serial.println(data); + + client.post(CONFIG.data.endpoint_path, contentType, data); + + int statusCode = client.responseStatusCode(); + String response = client.responseBody(); + + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + + return statusCode == 200; + } +#endif + +#ifdef HEATSEEK_BORON_LTE + // Function to reconnect to LTE? + void force_lte_reconnect(void); + + // Function to connect to Particle Cloud + void connect_to_lte(){ + // Configure the connection here. + Serial.println("Establishing connection..."); + // Connect to LTE network here. + Serial.println("Connected to LTE"); + watchdog_feed(); + } + + // Function to transmit + bool _transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time){ + // If cell / API endpoint not configured, indicate error + if (!CONFIG.data.cell_configured || !CONFIG.data.endpoint_configured) { + Serial.println("cannot send data - not configured"); + return false; + } + + // If not connected, connect + if(!lteConnected){ + connect_to_lte(); + } + + // Set up TCPClient + // Do some error checking + tcpClient.connect(CONFIG.data.endpoint_domain, 80); + String contentType = "application/x-www-form-urlencoded"; + String data = "temp=" + String(temperature_f, 3) + "&humidity=" + String(humidity, 3) + "&heat_index=" + String(heat_index, 3) + "&hub=" + CONFIG.data.hub_id + "&cell=" + CONFIG.data.cell_id + "&time=" + current_time + "&sp=" + CONFIG.data.reading_interval_s + "&cell_version=" + CODE_VERSION; + Serial.print("Posting data: "); + Serial.println(data); + tcpClient.println(data); + int statusCode = tcpClient.status(); + int numCharacters = tcpClient.available(); + String response = ""; + for (int i = 0; i < numCharacters; i++) + { + response += tcpClient.read(); + } + Serial.print("Status code: "); + Serial.println(statusCode); + Serial.print("Response: "); + Serial.println(response); + return statusCode == 200; + // Load data + // Post data via TCPClient + // Done. +} +#endif + +typedef struct { + float temperature_f; + float humidity; + float heat_index; +} temp_data_struct; + +typedef union { + temp_data_struct data; + uint8_t raw[sizeof(temp_data_struct)]; +} temp_data; + +// Create a file on the SD card representing a temperature reading +// The file name is the unix timestamp, however, due to FAT naming conventions, +// we have to place a period in it. e.g. 1500985299 -> 1500985.299 +// The content of the file is the binary reading data struct. +void queue_transmission(char *filename, temp_data temp, uint32_t current_time) { + char file_path[50]; + char timestamp[50]; + char timestamp_first_half[50]; + char timestamp_last_half[50]; + + // FAT only allows 8 character names, so we make the last 3 digits of the + // timestamp the file "extension" + sprintf(timestamp, "%d", current_time); + strncpy(timestamp_first_half, timestamp, 7); + timestamp_first_half[7] = '\0'; + strncpy(timestamp_last_half, timestamp+7, 3); + timestamp_last_half[3] = '\0'; + + sprintf(filename, "%s.%s", timestamp_first_half, timestamp_last_half); + sprintf(file_path, "pending/%s", filename); + + File temperature_file; + SD.mkdir("pending"); + if (temperature_file = SD.open(file_path, FILE_WRITE | O_TRUNC)) { + temperature_file.write(temp.raw, sizeof(temp)); + temperature_file.close(); + } else { + Serial.println("unable to write temperature"); + while(true); // watchdog will reboot + } +} + +// Take a filename for a reading, read the temperature data and +// transmit it. Then delete the file when the transfer is successful. +void transmit_queued_temp(char *filename) { + watchdog_feed(); + + File temperature_file; + temp_data temperature; + char read_time_buffer[100]; + char file_path[100]; + sprintf(file_path, "pending/%s", filename); + + Serial.print("transfering: "); + Serial.println(filename); + + strncpy(read_time_buffer, filename, 7); + strncpy(read_time_buffer+7, filename+8, 3); + read_time_buffer[10] = '\0'; + + uint32_t read_time = strtoul(read_time_buffer, NULL, 0); + + if (temperature_file = SD.open(file_path, FILE_READ)) { + int read_size = temperature_file.read(temperature.raw, sizeof(temperature)); + + if (sizeof(temperature) == read_size) { + bool transmit_success = _transmit(temperature.data.temperature_f, temperature.data.humidity, temperature.data.heat_index, read_time); + + temperature_file.close(); + delay(100); + + if (transmit_success) { + Serial.println("transferred."); + + if (SD.remove(file_path)) { + Serial.println("removed."); + } else { + Serial.println("failed to remove file"); + } + } else { + Serial.println("failed to transfer"); + } + } else { + Serial.print("file incorrect size - expected: "); + Serial.print(sizeof(temperature)); + Serial.print(", got: "); + Serial.println(read_size); + } + } else { + Serial.print("failed to open: "); + Serial.println(filename); + } + + watchdog_feed(); +} + +void transmit_queued_temps() { + char filename[100]; + File pending_dir = SD.open("pending"); + int temps_transfered_count = 0; + + while (temps_transfered_count < TRANSMITS_PER_LOOP) { + File entry = pending_dir.openNextFile(); + if (!entry) { break; } // No more files + + strcpy(filename, entry.name()); + entry.close(); + + transmit_queued_temp(filename); + temps_transfered_count += 1; + } + + pending_dir.close(); +} + +void clear_queued_transmissions() { + File pending_dir = SD.open("pending"); + + Serial.println("==== Removing queued temperature files"); + while (true) { + watchdog_feed(); + + File entry = pending_dir.openNextFile(); + if (!entry) { break; } // No more files + + char filename[100]; + strcpy(filename, entry.name()); + entry.close(); + + char file_path[100]; + sprintf(file_path, "pending/%s", filename); + + if (SD.remove(file_path)) { + Serial.println("removed queued temperature file."); + } else { + Serial.println("failed to remove queued temperature file."); + } + } + + Serial.println("===="); + + pending_dir.close(); +} + +void transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time) { + watchdog_feed(); + + temp_data temp; + temp.data.temperature_f = temperature_f; + temp.data.humidity = humidity; + temp.data.heat_index = heat_index; + + char filename[100]; + queue_transmission(filename, temp, current_time); + watchdog_feed(); + delay(1000); + + Serial.print("created file: "); + Serial.println(filename); + + transmit_queued_temp(filename); + transmit_queued_temps(); +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/transmit.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/transmit.h new file mode 100644 index 0000000..a817d47 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/transmit.h @@ -0,0 +1,58 @@ +#ifndef TRANSMIT_H +#define TRANSMIT_H + +#define CODE_VERSION "F-1.2.0" + +#include "user_config.h" + +#ifdef HEATSEEK_FEATHER_CELL_M0 + #define TRANSMITTER_GSM +#else + #define TRANSMITTER_WIFI +#endif + +#ifdef HEATSEEK_FEATHER_WIFI_WICED + #include + #include + #include + + #define DHT_DATA PC2 + #define SD_CS PB4 + + #define TRANSMITS_PER_LOOP 20 +#endif + +#ifdef HEATSEEK_FEATHER_WIFI_M0 + #include + #include + + #define DHT_DATA A2 + #define SD_CS 10 + + #define TRANSMITS_PER_LOOP 20 +#endif + +#ifdef TRANSMITTER_GSM + #include "Adafruit_FONA.h" + #include + + #define DHT_DATA A2 + #define SD_CS 10 + #define FONA_RST A4 + #define LORA_CS 8 + + #define TRANSMITS_PER_LOOP 5 +#endif + +#define SEND_SAVED_READINGS_THRESHOLD (10 * 60) +#define USER_AGENT_HEADER "curl/7.45.0" +#define PORT 80 + +void transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time); +void transmit_queued_temps(); +void clear_queued_transmissions(); +#ifdef TRANSMITTER_WIFI +void force_wifi_reconnect(); +#endif + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/user_config.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/user_config.h new file mode 100644 index 0000000..6011268 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/user_config.h @@ -0,0 +1,4 @@ +//#define HEATSEEK_FEATHER_CELL_M0 +//#define HEATSEEK_FEATHER_WIFI_M0 +#define HEATSEEK_BORON_LTE +//#define HEATSEEK_FEATHER_WIFI_WICED diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/watchdog.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/watchdog.cpp new file mode 100644 index 0000000..090b286 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/watchdog.cpp @@ -0,0 +1,25 @@ +#include "watchdog.h" + +#if defined(HEATSEEK_FEATHER_WIFI_M0) || defined(TRANSMITTER_GSM) + #include +#endif + +void watchdog_init() { + #ifdef HEATSEEK_FEATHER_WIFI_WICED + iwdg_init(IWDG_PRE_256, 3500); // 30 second watchdog, 40kHz processor + #endif + + #if defined(HEATSEEK_FEATHER_WIFI_M0) || defined(TRANSMITTER_GSM) + Watchdog.enable(16000); // 16 seconds (this is the max supported) + #endif +} + +void watchdog_feed() { + #ifdef HEATSEEK_FEATHER_WIFI_WICED + iwdg_feed(); + #endif + + #if defined(HEATSEEK_FEATHER_WIFI_M0) || defined(TRANSMITTER_GSM) + Watchdog.reset(); + #endif +} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/watchdog.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/watchdog.h new file mode 100644 index 0000000..7acb4e3 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/watchdog.h @@ -0,0 +1,9 @@ +#ifndef WATCHDOG_H +#define WATCHDOG_H + +#include "transmit.h" + +void watchdog_init(); +void watchdog_feed(); + +#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/target/1.1.0/boron/module_user_memory.ld b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/target/1.1.0/boron/module_user_memory.ld new file mode 100644 index 0000000..a348d59 --- /dev/null +++ b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/target/1.1.0/boron/module_user_memory.ld @@ -0,0 +1,4 @@ +user_module_app_flash_origin = 0xD4000; +user_module_app_flash_length = 128K; + +user_module_sram_length = 96K; From f65d74a298cc402080611749c5aae3118162d4d7 Mon Sep 17 00:00:00 2001 From: Jake Lee Date: Mon, 13 Jan 2020 18:41:34 -0800 Subject: [PATCH 7/7] Revert "Updated README" and later commits to move to separate repo. This reverts commit 4e3fd704ca7cf6454241585dc7bd4ecb0fee7ce1. --- .vscode/c_cpp_properties.json | 17 - .vscode/settings.json | 3 - README.md | 5 - boron | 1 - .../.vscode/c_cpp_properties.json | 18 - feather_sensor_lte/.vscode/launch.json | 92 - feather_sensor_lte/.vscode/settings.json | 11 - feather_sensor_lte/README.md | 35 - .../boron_firmware_1574447345899.bin | Bin 5592 -> 0 bytes .../boron_firmware_1574729317031.bin | Bin 5592 -> 0 bytes .../Adafruit_ASFcore/Adafruit_ASFcore.h | 0 .../libraries/Adafruit_ASFcore/README.md | 33 - .../libraries/Adafruit_ASFcore/clock.h | 53 - .../Adafruit_ASFcore/clock_feature.h | 1492 --------- .../libraries/Adafruit_ASFcore/compiler.h | 1157 ------- .../libraries/Adafruit_ASFcore/gclk.c | 522 --- .../libraries/Adafruit_ASFcore/gclk.h | 307 -- .../libraries/Adafruit_ASFcore/i2s.c | 750 ----- .../libraries/Adafruit_ASFcore/i2s.h | 1404 -------- .../libraries/Adafruit_ASFcore/interrupt.h | 117 - .../interrupt/interrupt_sam_nvic.c | 69 - .../interrupt/interrupt_sam_nvic.h | 172 - .../Adafruit_ASFcore/interrupt_sam_nvic.c | 86 - .../Adafruit_ASFcore/interrupt_sam_nvic.h | 189 -- .../Adafruit_ASFcore/library.properties | 9 - .../libraries/Adafruit_ASFcore/parts.h | 1601 --------- .../libraries/Adafruit_ASFcore/pinmux.c | 311 -- .../libraries/Adafruit_ASFcore/pinmux.h | 678 ---- .../libraries/Adafruit_ASFcore/power.h | 224 -- .../preprocessor/mrecursion.h | 581 ---- .../Adafruit_ASFcore/preprocessor/mrepeat.h | 321 -- .../preprocessor/preprocessor.h | 38 - .../Adafruit_ASFcore/preprocessor/stringz.h | 67 - .../Adafruit_ASFcore/preprocessor/tpaste.h | 85 - .../libraries/Adafruit_ASFcore/reset.h | 119 - .../libraries/Adafruit_ASFcore/status_codes.h | 138 - .../libraries/Adafruit_ASFcore/system.c | 111 - .../libraries/Adafruit_ASFcore/system.h | 726 ----- .../Adafruit_ASFcore/system_interrupt.h | 429 --- .../system_interrupt_features.h | 195 -- .../libraries/Adafruit_ASFcore/tc.c | 685 ---- .../libraries/Adafruit_ASFcore/tc.h | 1783 ---------- .../libraries/Adafruit_ASFcore/tc_interrupt.c | 199 -- .../libraries/Adafruit_ASFcore/tc_interrupt.h | 179 - .../libraries/Adafruit_ASFcore/wdt.c | 264 -- .../libraries/Adafruit_ASFcore/wdt.h | 501 --- .../Adafruit_FONA_Library/Adafruit_FONA.cpp | 2079 ------------ .../Adafruit_FONA_Library/Adafruit_FONA.h | 263 -- .../libraries/Adafruit_FONA_Library/README.md | 29 - .../FONA3G_setbaud/.esp8266.test.skip | 0 .../FONA3G_setbaud/FONA3G_setbaud.ino | 77 - .../FONA_SMS_Response/.esp8266.test.skip | 0 .../FONA_SMS_Response/FONA_SMS_Response.ino | 131 - .../examples/FONAtest/.esp8266.test.skip | 0 .../examples/FONAtest/FONAtest.ino | 886 ----- .../examples/GPS/.esp8266.test.skip | 0 .../examples/GPS/GPS.ino | 112 - .../examples/IncomingCall/.esp8266.test.skip | 0 .../examples/IncomingCall/IncomingCall.ino | 62 - .../includes/FONAConfig.h | 34 - .../includes/FONAExtIncludes.h | 33 - .../includes/platform/FONAPlatStd.h | 67 - .../includes/platform/FONAPlatform.h | 62 - .../Adafruit_FONA_Library/library.properties | 9 - .../Adafruit_SleepyDog.cpp | 4 - .../Adafruit_SleepyDog.h | 28 - .../Adafruit_SleepyDog_Library/LICENSE | 22 - .../Adafruit_SleepyDog_Library/README.md | 6 - .../examples/BasicUsage/BasicUsage.ino | 62 - .../examples/Sleep/Sleep.ino | 37 - .../library.properties | 9 - .../utility/WatchdogAVR.cpp | 137 - .../utility/WatchdogAVR.h | 47 - .../utility/WatchdogKinetisK.cpp | 104 - .../utility/WatchdogKinetisK.h | 38 - .../utility/WatchdogKinetisL.cpp | 74 - .../utility/WatchdogKinetisL.h | 35 - .../utility/WatchdogSAMD.cpp | 175 - .../utility/WatchdogSAMD.h | 43 - .../libraries/ArduinoHttpClient/.gitignore | 2 - .../libraries/ArduinoHttpClient/CHANGELOG.md | 25 - .../libraries/ArduinoHttpClient/README.md | 22 - .../examples/BasicAuthGet/BasicAuthGet.ino | 69 - .../examples/BasicAuthGet/arduino_secrets.h | 3 - .../examples/CustomHeader/CustomHeader.ino | 96 - .../examples/CustomHeader/arduino_secrets.h | 3 - .../examples/DweetGet/DweetGet.ino | 107 - .../examples/DweetGet/arduino_secrets.h | 3 - .../examples/DweetPost/DweetPost.ino | 87 - .../examples/DweetPost/arduino_secrets.h | 3 - .../examples/HueBlink/HueBlink.ino | 102 - .../examples/HueBlink/arduino_secrets.h | 3 - .../PostWithHeaders/PostWithHeaders.ino | 79 - .../PostWithHeaders/arduino_secrets.h | 3 - .../examples/SimpleDelete/SimpleDelete.ino | 71 - .../examples/SimpleDelete/arduino_secrets.h | 3 - .../examples/SimpleGet/SimpleGet.ino | 66 - .../examples/SimpleGet/arduino_secrets.h | 3 - .../SimpleHttpExample/SimpleHttpExample.ino | 133 - .../SimpleHttpExample/arduino_secrets.h | 3 - .../examples/SimplePost/SimplePost.ino | 70 - .../examples/SimplePost/arduino_secrets.h | 3 - .../examples/SimplePut/SimplePut.ino | 70 - .../examples/SimplePut/arduino_secrets.h | 3 - .../SimpleWebSocket/SimpleWebSocket.ino | 80 - .../SimpleWebSocket/arduino_secrets.h | 3 - .../node_test_server/getPostPutDelete.js | 102 - .../examples/node_test_server/package.json | 13 - .../libraries/ArduinoHttpClient/keywords.txt | 64 - .../libraries/ArduinoHttpClient/library.json | 12 - .../ArduinoHttpClient/library.properties | 10 - .../ArduinoHttpClient/src/ArduinoHttpClient.h | 11 - .../ArduinoHttpClient/src/HttpClient.cpp | 862 ----- .../ArduinoHttpClient/src/HttpClient.h | 392 --- .../ArduinoHttpClient/src/WebSocketClient.cpp | 372 --- .../ArduinoHttpClient/src/WebSocketClient.h | 99 - .../libraries/ArduinoHttpClient/src/b64.cpp | 72 - .../libraries/ArduinoHttpClient/src/b64.h | 6 - .../libraries/DHT/.github/ISSUE_TEMPLATE.md | 46 - .../DHT/.github/PULL_REQUEST_TEMPLATE.md | 26 - feather_sensor_lte/libraries/DHT/DHT.cpp | 259 -- feather_sensor_lte/libraries/DHT/DHT.h | 75 - feather_sensor_lte/libraries/DHT/DHT_U.cpp | 179 - feather_sensor_lte/libraries/DHT/DHT_U.h | 78 - feather_sensor_lte/libraries/DHT/README.md | 15 - .../DHT_Unified_Sensor/DHT_Unified_Sensor.ino | 84 - .../DHT/examples/DHTtester/DHTtester.ino | 69 - feather_sensor_lte/libraries/DHT/keywords.txt | 22 - .../libraries/DHT/library.properties | 9 - .../RTClib/.github/ISSUE_TEMPLATE.md | 46 - .../RTClib/.github/PULL_REQUEST_TEMPLATE.md | 26 - feather_sensor_lte/libraries/RTClib/README.md | 42 - .../libraries/RTClib/RTClib.cpp | 506 --- feather_sensor_lte/libraries/RTClib/RTClib.h | 135 - .../RTClib/examples/datecalc/datecalc.ino | 111 - .../RTClib/examples/ds1307/ds1307.ino | 71 - .../examples/ds1307SqwPin/ds1307SqwPin.ino | 68 - .../examples/ds1307nvram/ds1307nvram.ino | 63 - .../RTClib/examples/ds3231/ds3231.ino | 77 - .../RTClib/examples/pcf8523/pcf8523.ino | 74 - .../RTClib/examples/softrtc/softrtc.ino | 61 - .../libraries/RTClib/keywords.txt | 37 - .../libraries/RTClib/library.properties | 9 - .../libraries/WiFi101/.travis.yml | 48 - .../libraries/WiFi101/CHANGELOG | 122 - .../libraries/WiFi101/README.adoc | 27 - .../AP_SimpleWebServer/AP_SimpleWebServer.ino | 176 - .../AP_SimpleWebServer/arduino_secrets.h | 3 - .../CheckWifi101FirmwareVersion.ino | 67 - .../ConnectNoEncryption.ino | 123 - .../ConnectNoEncryption/arduino_secrets.h | 1 - .../ConnectWithWEP/ConnectWithWEP.ino | 129 - .../examples/ConnectWithWEP/arduino_secrets.h | 3 - .../ConnectWithWPA/ConnectWithWPA.ino | 119 - .../examples/ConnectWithWPA/arduino_secrets.h | 3 - .../examples/FirmwareUpdater/Endianess.ino | 62 - .../FirmwareUpdater/FirmwareUpdater.ino | 129 - .../MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino | 170 - .../MDNS_WiFiWebServer/arduino_secrets.h | 3 - .../Provisioning_WiFiWebServer.ino | 167 - .../examples/ScanNetworks/ScanNetworks.ino | 120 - .../ScanNetworksAdvanced.ino | 149 - .../SimpleWebServerWiFi.ino | 131 - .../SimpleWebServerWiFi/arduino_secrets.h | 3 - .../WiFiChatServer/WiFiChatServer.ino | 114 - .../examples/WiFiChatServer/arduino_secrets.h | 3 - .../WiFi101/examples/WiFiPing/WiFiPing.ino | 140 - .../examples/WiFiPing/arduino_secrets.h | 3 - .../examples/WiFiSSLClient/WiFiSSLClient.ino | 107 - .../examples/WiFiSSLClient/arduino_secrets.h | 3 - .../WiFiUdpNtpClient/WiFiUdpNtpClient.ino | 182 -- .../WiFiUdpNtpClient/arduino_secrets.h | 3 - .../WiFiUdpSendReceiveString.ino | 113 - .../arduino_secrets.h | 3 - .../examples/WiFiWebClient/WiFiWebClient.ino | 121 - .../examples/WiFiWebClient/arduino_secrets.h | 3 - .../WiFiWebClientRepeating.ino | 127 - .../WiFiWebClientRepeating/arduino_secrets.h | 3 - .../examples/WiFiWebServer/WiFiWebServer.ino | 135 - .../examples/WiFiWebServer/arduino_secrets.h | 3 - .../libraries/WiFi101/keywords.txt | 61 - .../libraries/WiFi101/library.properties | 10 - .../libraries/WiFi101/src/WiFi.cpp | 1106 ------- .../libraries/WiFi101/src/WiFi101.h | 193 -- .../libraries/WiFi101/src/WiFiClient.cpp | 308 -- .../libraries/WiFi101/src/WiFiClient.h | 68 - .../WiFi101/src/WiFiMDNSResponder.cpp | 220 -- .../libraries/WiFi101/src/WiFiMDNSResponder.h | 51 - .../libraries/WiFi101/src/WiFiSSLClient.cpp | 45 - .../libraries/WiFi101/src/WiFiSSLClient.h | 36 - .../libraries/WiFi101/src/WiFiServer.cpp | 140 - .../libraries/WiFi101/src/WiFiServer.h | 49 - .../libraries/WiFi101/src/WiFiUdp.cpp | 289 -- .../libraries/WiFi101/src/WiFiUdp.h | 89 - .../WiFi101/src/bsp/include/nm_bsp.h | 283 -- .../WiFi101/src/bsp/include/nm_bsp_arduino.h | 74 - .../WiFi101/src/bsp/include/nm_bsp_avr.h | 54 - .../WiFi101/src/bsp/include/nm_bsp_internal.h | 59 - .../WiFi101/src/bsp/include/nm_bsp_samd21.h | 52 - .../WiFi101/src/bsp/source/nm_bsp_arduino.c | 205 -- .../src/bsp/source/nm_bsp_arduino_avr.c | 164 - .../src/bus_wrapper/include/nm_bus_wrapper.h | 177 - .../source/nm_bus_wrapper_samd21.cpp | 200 -- .../WiFi101/src/common/include/nm_common.h | 153 - .../WiFi101/src/common/include/nm_debug.h | 95 - .../WiFi101/src/common/source/nm_common.c | 136 - .../WiFi101/src/driver/include/ecc_types.h | 245 -- .../WiFi101/src/driver/include/m2m_ate_mode.h | 732 ----- .../WiFi101/src/driver/include/m2m_crypto.h | 272 -- .../WiFi101/src/driver/include/m2m_ota.h | 428 --- .../WiFi101/src/driver/include/m2m_periph.h | 411 --- .../WiFi101/src/driver/include/m2m_ssl.h | 182 -- .../WiFi101/src/driver/include/m2m_types.h | 2383 -------------- .../WiFi101/src/driver/include/m2m_wifi.h | 2882 ----------------- .../WiFi101/src/driver/source/m2m_ate_mode.c | 826 ----- .../WiFi101/src/driver/source/m2m_crypto.c | 1010 ------ .../WiFi101/src/driver/source/m2m_hif.c | 767 ----- .../WiFi101/src/driver/source/m2m_hif.h | 249 -- .../WiFi101/src/driver/source/m2m_ota.c | 417 --- .../WiFi101/src/driver/source/m2m_periph.c | 187 -- .../WiFi101/src/driver/source/m2m_ssl.c | 309 -- .../WiFi101/src/driver/source/m2m_wifi.c | 1522 --------- .../WiFi101/src/driver/source/nmasic.c | 688 ---- .../WiFi101/src/driver/source/nmasic.h | 215 -- .../WiFi101/src/driver/source/nmbus.c | 301 -- .../WiFi101/src/driver/source/nmbus.h | 147 - .../WiFi101/src/driver/source/nmdrv.c | 402 --- .../WiFi101/src/driver/source/nmdrv.h | 138 - .../WiFi101/src/driver/source/nmi2c.c | 269 -- .../WiFi101/src/driver/source/nmi2c.h | 104 - .../WiFi101/src/driver/source/nmspi.c | 1401 -------- .../WiFi101/src/driver/source/nmspi.h | 132 - .../WiFi101/src/driver/source/nmuart.c | 536 --- .../WiFi101/src/driver/source/nmuart.h | 118 - .../src/socket/include/m2m_socket_host_if.h | 461 --- .../WiFi101/src/socket/include/socket.h | 2065 ------------ .../src/socket/include/socket_buffer.h | 94 - .../WiFi101/src/socket/source/socket.c | 1445 --------- .../WiFi101/src/socket/source/socket_buffer.c | 232 -- .../src/socket/source/socket_internal.h | 71 - .../WiFi101/src/spi_flash/include/spi_flash.h | 233 -- .../src/spi_flash/include/spi_flash_map.h | 245 -- .../WiFi101/src/spi_flash/source/spi_flash.c | 770 ----- feather_sensor_lte/project.properties | 1 - feather_sensor_lte/src/feather_sensor_lte.ino | 50 - .../.vscode/c_cpp_properties.json | 18 - feather_sensor_transmit/.vscode/launch.json | 92 - feather_sensor_transmit/.vscode/settings.json | 11 - .../boron_firmware_1574447345899.bin | Bin 5592 -> 0 bytes .../boron_firmware_1574729317031.bin | Bin 5592 -> 0 bytes .../Adafruit_ASFcore/Adafruit_ASFcore.h | 0 .../libraries/Adafruit_ASFcore/README.md | 33 - .../libraries/Adafruit_ASFcore/clock.h | 53 - .../Adafruit_ASFcore/clock_feature.h | 1492 --------- .../libraries/Adafruit_ASFcore/compiler.h | 1157 ------- .../libraries/Adafruit_ASFcore/gclk.c | 522 --- .../libraries/Adafruit_ASFcore/gclk.h | 307 -- .../libraries/Adafruit_ASFcore/i2s.c | 750 ----- .../libraries/Adafruit_ASFcore/i2s.h | 1404 -------- .../libraries/Adafruit_ASFcore/interrupt.h | 117 - .../interrupt/interrupt_sam_nvic.c | 69 - .../interrupt/interrupt_sam_nvic.h | 172 - .../Adafruit_ASFcore/interrupt_sam_nvic.c | 86 - .../Adafruit_ASFcore/interrupt_sam_nvic.h | 189 -- .../Adafruit_ASFcore/library.properties | 9 - .../libraries/Adafruit_ASFcore/parts.h | 1601 --------- .../libraries/Adafruit_ASFcore/pinmux.c | 311 -- .../libraries/Adafruit_ASFcore/pinmux.h | 678 ---- .../libraries/Adafruit_ASFcore/power.h | 224 -- .../preprocessor/mrecursion.h | 581 ---- .../Adafruit_ASFcore/preprocessor/mrepeat.h | 321 -- .../preprocessor/preprocessor.h | 38 - .../Adafruit_ASFcore/preprocessor/stringz.h | 67 - .../Adafruit_ASFcore/preprocessor/tpaste.h | 85 - .../libraries/Adafruit_ASFcore/reset.h | 119 - .../libraries/Adafruit_ASFcore/status_codes.h | 138 - .../libraries/Adafruit_ASFcore/system.c | 111 - .../libraries/Adafruit_ASFcore/system.h | 726 ----- .../Adafruit_ASFcore/system_interrupt.h | 429 --- .../system_interrupt_features.h | 195 -- .../libraries/Adafruit_ASFcore/tc.c | 685 ---- .../libraries/Adafruit_ASFcore/tc.h | 1783 ---------- .../libraries/Adafruit_ASFcore/tc_interrupt.c | 199 -- .../libraries/Adafruit_ASFcore/tc_interrupt.h | 179 - .../libraries/Adafruit_ASFcore/wdt.c | 264 -- .../libraries/Adafruit_ASFcore/wdt.h | 501 --- .../Adafruit_FONA_Library/Adafruit_FONA.cpp | 2079 ------------ .../Adafruit_FONA_Library/Adafruit_FONA.h | 263 -- .../libraries/Adafruit_FONA_Library/README.md | 29 - .../FONA3G_setbaud/.esp8266.test.skip | 0 .../FONA3G_setbaud/FONA3G_setbaud.ino | 77 - .../FONA_SMS_Response/.esp8266.test.skip | 0 .../FONA_SMS_Response/FONA_SMS_Response.ino | 131 - .../examples/FONAtest/.esp8266.test.skip | 0 .../examples/FONAtest/FONAtest.ino | 886 ----- .../examples/GPS/.esp8266.test.skip | 0 .../examples/GPS/GPS.ino | 112 - .../examples/IncomingCall/.esp8266.test.skip | 0 .../examples/IncomingCall/IncomingCall.ino | 62 - .../includes/FONAConfig.h | 34 - .../includes/FONAExtIncludes.h | 33 - .../includes/platform/FONAPlatStd.h | 67 - .../includes/platform/FONAPlatform.h | 62 - .../Adafruit_FONA_Library/library.properties | 9 - .../Adafruit_SleepyDog.cpp | 4 - .../Adafruit_SleepyDog.h | 28 - .../Adafruit_SleepyDog_Library/LICENSE | 22 - .../Adafruit_SleepyDog_Library/README.md | 6 - .../examples/BasicUsage/BasicUsage.ino | 62 - .../examples/Sleep/Sleep.ino | 37 - .../library.properties | 9 - .../utility/WatchdogAVR.cpp | 137 - .../utility/WatchdogAVR.h | 47 - .../utility/WatchdogKinetisK.cpp | 104 - .../utility/WatchdogKinetisK.h | 38 - .../utility/WatchdogKinetisL.cpp | 74 - .../utility/WatchdogKinetisL.h | 35 - .../utility/WatchdogSAMD.cpp | 175 - .../utility/WatchdogSAMD.h | 43 - .../libraries/ArduinoHttpClient/.gitignore | 2 - .../libraries/ArduinoHttpClient/CHANGELOG.md | 25 - .../libraries/ArduinoHttpClient/README.md | 22 - .../examples/BasicAuthGet/BasicAuthGet.ino | 69 - .../examples/BasicAuthGet/arduino_secrets.h | 3 - .../examples/CustomHeader/CustomHeader.ino | 96 - .../examples/CustomHeader/arduino_secrets.h | 3 - .../examples/DweetGet/DweetGet.ino | 107 - .../examples/DweetGet/arduino_secrets.h | 3 - .../examples/DweetPost/DweetPost.ino | 87 - .../examples/DweetPost/arduino_secrets.h | 3 - .../examples/HueBlink/HueBlink.ino | 102 - .../examples/HueBlink/arduino_secrets.h | 3 - .../PostWithHeaders/PostWithHeaders.ino | 79 - .../PostWithHeaders/arduino_secrets.h | 3 - .../examples/SimpleDelete/SimpleDelete.ino | 71 - .../examples/SimpleDelete/arduino_secrets.h | 3 - .../examples/SimpleGet/SimpleGet.ino | 66 - .../examples/SimpleGet/arduino_secrets.h | 3 - .../SimpleHttpExample/SimpleHttpExample.ino | 133 - .../SimpleHttpExample/arduino_secrets.h | 3 - .../examples/SimplePost/SimplePost.ino | 70 - .../examples/SimplePost/arduino_secrets.h | 3 - .../examples/SimplePut/SimplePut.ino | 70 - .../examples/SimplePut/arduino_secrets.h | 3 - .../SimpleWebSocket/SimpleWebSocket.ino | 80 - .../SimpleWebSocket/arduino_secrets.h | 3 - .../node_test_server/getPostPutDelete.js | 102 - .../examples/node_test_server/package.json | 13 - .../libraries/ArduinoHttpClient/keywords.txt | 64 - .../libraries/ArduinoHttpClient/library.json | 12 - .../ArduinoHttpClient/library.properties | 10 - .../ArduinoHttpClient/src/ArduinoHttpClient.h | 11 - .../ArduinoHttpClient/src/HttpClient.cpp | 862 ----- .../ArduinoHttpClient/src/HttpClient.h | 392 --- .../ArduinoHttpClient/src/WebSocketClient.cpp | 372 --- .../ArduinoHttpClient/src/WebSocketClient.h | 99 - .../libraries/ArduinoHttpClient/src/b64.cpp | 72 - .../libraries/ArduinoHttpClient/src/b64.h | 6 - .../libraries/DHT/.github/ISSUE_TEMPLATE.md | 46 - .../DHT/.github/PULL_REQUEST_TEMPLATE.md | 26 - feather_sensor_transmit/libraries/DHT/DHT.cpp | 259 -- feather_sensor_transmit/libraries/DHT/DHT.h | 75 - .../libraries/DHT/DHT_U.cpp | 179 - feather_sensor_transmit/libraries/DHT/DHT_U.h | 78 - .../libraries/DHT/README.md | 15 - .../DHT_Unified_Sensor/DHT_Unified_Sensor.ino | 84 - .../DHT/examples/DHTtester/DHTtester.ino | 69 - .../libraries/DHT/keywords.txt | 22 - .../libraries/DHT/library.properties | 9 - .../RTClib/.github/ISSUE_TEMPLATE.md | 46 - .../RTClib/.github/PULL_REQUEST_TEMPLATE.md | 26 - .../libraries/RTClib/README.md | 42 - .../libraries/RTClib/RTClib.cpp | 506 --- .../libraries/RTClib/RTClib.h | 135 - .../RTClib/examples/datecalc/datecalc.ino | 111 - .../RTClib/examples/ds1307/ds1307.ino | 71 - .../examples/ds1307SqwPin/ds1307SqwPin.ino | 68 - .../examples/ds1307nvram/ds1307nvram.ino | 63 - .../RTClib/examples/ds3231/ds3231.ino | 77 - .../RTClib/examples/pcf8523/pcf8523.ino | 74 - .../RTClib/examples/softrtc/softrtc.ino | 61 - .../libraries/RTClib/keywords.txt | 37 - .../libraries/RTClib/library.properties | 9 - .../libraries/WiFi101/.travis.yml | 48 - .../libraries/WiFi101/CHANGELOG | 122 - .../libraries/WiFi101/README.adoc | 27 - .../AP_SimpleWebServer/AP_SimpleWebServer.ino | 176 - .../AP_SimpleWebServer/arduino_secrets.h | 3 - .../CheckWifi101FirmwareVersion.ino | 67 - .../ConnectNoEncryption.ino | 123 - .../ConnectNoEncryption/arduino_secrets.h | 1 - .../ConnectWithWEP/ConnectWithWEP.ino | 129 - .../examples/ConnectWithWEP/arduino_secrets.h | 3 - .../ConnectWithWPA/ConnectWithWPA.ino | 119 - .../examples/ConnectWithWPA/arduino_secrets.h | 3 - .../examples/FirmwareUpdater/Endianess.ino | 62 - .../FirmwareUpdater/FirmwareUpdater.ino | 129 - .../MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino | 170 - .../MDNS_WiFiWebServer/arduino_secrets.h | 3 - .../Provisioning_WiFiWebServer.ino | 167 - .../examples/ScanNetworks/ScanNetworks.ino | 120 - .../ScanNetworksAdvanced.ino | 149 - .../SimpleWebServerWiFi.ino | 131 - .../SimpleWebServerWiFi/arduino_secrets.h | 3 - .../WiFiChatServer/WiFiChatServer.ino | 114 - .../examples/WiFiChatServer/arduino_secrets.h | 3 - .../WiFi101/examples/WiFiPing/WiFiPing.ino | 140 - .../examples/WiFiPing/arduino_secrets.h | 3 - .../examples/WiFiSSLClient/WiFiSSLClient.ino | 107 - .../examples/WiFiSSLClient/arduino_secrets.h | 3 - .../WiFiUdpNtpClient/WiFiUdpNtpClient.ino | 182 -- .../WiFiUdpNtpClient/arduino_secrets.h | 3 - .../WiFiUdpSendReceiveString.ino | 113 - .../arduino_secrets.h | 3 - .../examples/WiFiWebClient/WiFiWebClient.ino | 121 - .../examples/WiFiWebClient/arduino_secrets.h | 3 - .../WiFiWebClientRepeating.ino | 127 - .../WiFiWebClientRepeating/arduino_secrets.h | 3 - .../examples/WiFiWebServer/WiFiWebServer.ino | 135 - .../examples/WiFiWebServer/arduino_secrets.h | 3 - .../libraries/WiFi101/keywords.txt | 61 - .../libraries/WiFi101/library.properties | 10 - .../libraries/WiFi101/src/WiFi.cpp | 1106 ------- .../libraries/WiFi101/src/WiFi101.h | 193 -- .../libraries/WiFi101/src/WiFiClient.cpp | 308 -- .../libraries/WiFi101/src/WiFiClient.h | 68 - .../WiFi101/src/WiFiMDNSResponder.cpp | 220 -- .../libraries/WiFi101/src/WiFiMDNSResponder.h | 51 - .../libraries/WiFi101/src/WiFiSSLClient.cpp | 45 - .../libraries/WiFi101/src/WiFiSSLClient.h | 36 - .../libraries/WiFi101/src/WiFiServer.cpp | 140 - .../libraries/WiFi101/src/WiFiServer.h | 49 - .../libraries/WiFi101/src/WiFiUdp.cpp | 289 -- .../libraries/WiFi101/src/WiFiUdp.h | 89 - .../WiFi101/src/bsp/include/nm_bsp.h | 283 -- .../WiFi101/src/bsp/include/nm_bsp_arduino.h | 74 - .../WiFi101/src/bsp/include/nm_bsp_avr.h | 54 - .../WiFi101/src/bsp/include/nm_bsp_internal.h | 59 - .../WiFi101/src/bsp/include/nm_bsp_samd21.h | 52 - .../WiFi101/src/bsp/source/nm_bsp_arduino.c | 205 -- .../src/bsp/source/nm_bsp_arduino_avr.c | 164 - .../src/bus_wrapper/include/nm_bus_wrapper.h | 177 - .../source/nm_bus_wrapper_samd21.cpp | 200 -- .../WiFi101/src/common/include/nm_common.h | 153 - .../WiFi101/src/common/include/nm_debug.h | 95 - .../WiFi101/src/common/source/nm_common.c | 136 - .../WiFi101/src/driver/include/ecc_types.h | 245 -- .../WiFi101/src/driver/include/m2m_ate_mode.h | 732 ----- .../WiFi101/src/driver/include/m2m_crypto.h | 272 -- .../WiFi101/src/driver/include/m2m_ota.h | 428 --- .../WiFi101/src/driver/include/m2m_periph.h | 411 --- .../WiFi101/src/driver/include/m2m_ssl.h | 182 -- .../WiFi101/src/driver/include/m2m_types.h | 2383 -------------- .../WiFi101/src/driver/include/m2m_wifi.h | 2882 ----------------- .../WiFi101/src/driver/source/m2m_ate_mode.c | 826 ----- .../WiFi101/src/driver/source/m2m_crypto.c | 1010 ------ .../WiFi101/src/driver/source/m2m_hif.c | 767 ----- .../WiFi101/src/driver/source/m2m_hif.h | 249 -- .../WiFi101/src/driver/source/m2m_ota.c | 417 --- .../WiFi101/src/driver/source/m2m_periph.c | 187 -- .../WiFi101/src/driver/source/m2m_ssl.c | 309 -- .../WiFi101/src/driver/source/m2m_wifi.c | 1522 --------- .../WiFi101/src/driver/source/nmasic.c | 688 ---- .../WiFi101/src/driver/source/nmasic.h | 215 -- .../WiFi101/src/driver/source/nmbus.c | 301 -- .../WiFi101/src/driver/source/nmbus.h | 147 - .../WiFi101/src/driver/source/nmdrv.c | 402 --- .../WiFi101/src/driver/source/nmdrv.h | 138 - .../WiFi101/src/driver/source/nmi2c.c | 269 -- .../WiFi101/src/driver/source/nmi2c.h | 104 - .../WiFi101/src/driver/source/nmspi.c | 1401 -------- .../WiFi101/src/driver/source/nmspi.h | 132 - .../WiFi101/src/driver/source/nmuart.c | 536 --- .../WiFi101/src/driver/source/nmuart.h | 118 - .../src/socket/include/m2m_socket_host_if.h | 461 --- .../WiFi101/src/socket/include/socket.h | 2065 ------------ .../src/socket/include/socket_buffer.h | 94 - .../WiFi101/src/socket/source/socket.c | 1445 --------- .../WiFi101/src/socket/source/socket_buffer.c | 232 -- .../src/socket/source/socket_internal.h | 71 - .../WiFi101/src/spi_flash/include/spi_flash.h | 233 -- .../src/spi_flash/include/spi_flash_map.h | 245 -- .../WiFi101/src/spi_flash/source/spi_flash.c | 770 ----- feather_sensor_transmit/project.properties | 1 - feather_sensor_transmit/src/LICENSE.txt | 22 - feather_sensor_transmit/src/README.md | 67 - feather_sensor_transmit/src/config.cpp | 453 --- feather_sensor_transmit/src/config.h | 39 - .../src/heatseek_sensor.ino | 166 - feather_sensor_transmit/src/rtc.cpp | 58 - feather_sensor_transmit/src/rtc.h | 11 - feather_sensor_transmit/src/transmit.cpp | 513 --- feather_sensor_transmit/src/transmit.h | 58 - feather_sensor_transmit/src/user_config.h | 4 - feather_sensor_transmit/src/watchdog.cpp | 25 - feather_sensor_transmit/src/watchdog.h | 9 - .../.vscode/c_cpp_properties.json | 18 - .../.vscode/launch.json | 92 - .../.vscode/settings.json | 11 - .../feather_sensor_transmit_lte/README.md | 35 - .../boron_firmware_1574447345899.bin | Bin 5592 -> 0 bytes .../boron_firmware_1574729317031.bin | Bin 5592 -> 0 bytes .../lib/DHT/LICENSE.txt | 0 .../lib/DHT/README.md | 15 - .../DHT_Unified_Sensor/DHT_Unified_Sensor.ino | 84 - .../lib/DHT/examples/DHTtester/DHTtester.ino | 69 - .../lib/DHT/keywords.txt | 22 - .../lib/DHT/library.properties | 9 - .../lib/DHT/src/DHT.cpp | 259 -- .../lib/DHT/src/DHT.h | 75 - .../lib/DHT/src/DHT_U.cpp | 179 - .../lib/DHT/src/DHT_U.h | 78 - .../lib/SdFat/LICENSE.md | 21 - .../lib/SdFat/README.md | 42 - .../#attic/AnalogLogger/AnalogLogger.ino | 197 -- .../BaseExtCaseTest/BaseExtCaseTest.ino | 46 - .../examples/#attic/HelloWorld/HelloWorld.ino | 20 - .../examples/#attic/MiniSerial/MiniSerial.ino | 29 - .../PrintBenchmarkSD/PrintBenchmarkSD.ino | 125 - .../SdFat/examples/#attic/SD_Size/SD_Size.ino | 30 - .../examples/#attic/SdFatSize/SdFatSize.ino | 33 - .../#attic/StreamParseInt/StreamParseInt.ino | 44 - .../SdFat/examples/#attic/append/append.ino | 77 - .../SdFat/examples/#attic/average/average.ino | 82 - .../SdFat/examples/#attic/benchSD/benchSD.ino | 149 - .../examples/#attic/bufstream/bufstream.ino | 39 - .../examples/#attic/cin_cout/cin_cout.ino | 39 - .../examples/#attic/eventlog/eventlog.ino | 62 - .../#attic/fgetsRewrite/fgetsRewrite.ino | 111 - .../SdFat/examples/#attic/readlog/readlog.ino | 51 - .../lib/SdFat/examples/#attic/readme.txt | 34 - .../AnalogBinLogger/AnalogBinLogger.h | 39 - .../AnalogBinLogger/AnalogBinLogger.ino | 826 ----- .../DirectoryFunctions/DirectoryFunctions.ino | 129 - .../examples/LongFileName/LongFileName.ino | 102 - .../A long name can be 255 characters.txt | 4 - .../LongFileName/testFiles/LFN,NAME.TXT | 1 - .../LongFileName/testFiles/MIXCASE.txt | 5 - .../LongFileName/testFiles/Not_8_3.txt | 2 - .../examples/LongFileName/testFiles/OK%83.TXT | 1 - .../LongFileName/testFiles/STD_8_3.TXT | 1 - .../LongFileName/testFiles/With Blank.txt | 2 - .../LongFileName/testFiles/With.Two dots.txt | 2 - .../examples/LongFileName/testFiles/lower.txt | 5 - .../examples/LongFileName/testFiles/mixed.TXT | 5 - .../LowLatencyLogger/LowLatencyLogger.ino | 655 ---- .../LowLatencyLogger/UserFunctions.cpp | 41 - .../examples/LowLatencyLogger/UserTypes.h | 15 - .../LowLatencyLogger.ino | 655 ---- .../LowLatencyLoggerADXL345.ino | 1 - .../LowLatencyLoggerADXL345/UserFunctions.cpp | 70 - .../LowLatencyLoggerADXL345/UserTypes.h | 17 - .../LowLatencyLoggerADXL345/readme.txt | 1 - .../LowLatencyLogger.ino | 655 ---- .../LowLatencyLoggerMPU6050.ino | 2 - .../LowLatencyLoggerMPU6050/UserFunctions.cpp | 51 - .../LowLatencyLoggerMPU6050/UserTypes.h | 18 - .../lib/SdFat/examples/OpenNext/OpenNext.ino | 60 - .../PrintBenchmark/PrintBenchmark.ino | 152 - .../SdFat/examples/QuickStart/QuickStart.ino | 161 - .../lib/SdFat/examples/RawWrite/RawWrite.ino | 180 - .../lib/SdFat/examples/ReadCsv/ReadCsv.ino | 212 -- .../examples/ReadCsvArray/ReadCsvArray.ino | 139 - .../examples/ReadCsvStream/ReadCsvStream.ino | 121 - .../SdFat/examples/ReadWrite/ReadWrite.ino | 81 - .../SdFat/examples/STM32Test/STM32Test.ino | 175 - .../examples/SdFormatter/SdFormatter.ino | 552 ---- .../lib/SdFat/examples/SdInfo/SdInfo.ino | 248 -- .../examples/SoftwareSpi/SoftwareSpi.ino | 58 - .../SdFat/examples/StdioBench/StdioBench.ino | 214 -- .../TeensySdioDemo/TeensySdioDemo.ino | 169 - .../SdFat/examples/Timestamp/Timestamp.ino | 176 - .../lib/SdFat/examples/TwoCards/TwoCards.ino | 170 - .../VolumeFreeSpace/VolumeFreeSpace.ino | 82 - .../lib/SdFat/examples/bench/bench.ino | 222 -- .../SdFat/examples/dataLogger/dataLogger.ino | 150 - .../lib/SdFat/examples/fgets/fgets.ino | 88 - .../SdFat/examples/formatting/formatting.ino | 73 - .../lib/SdFat/examples/getline/getline.ino | 84 - .../lib/SdFat/examples/rename/rename.ino | 107 - .../lib/SdFat/examples/wipe/wipe.ino | 42 - .../AnalogBinLoggerExtras/AdcErrorStudy.txt | 98 - .../AnalogBinLoggerExtras/RateTable.txt | 21 - .../bintocsv/AnalogBinLogger.h | 39 - .../bintocsv/bintocsv.cpp | 82 - .../extras/AnalogBinLoggerExtras/readme.txt | 95 - .../lib/SdFat/extras/MainPage/SdFatmainpage.h | 403 --- .../extras/SdFatTestSuite/SdFatTestSuite.cpp | 87 - .../extras/SdFatTestSuite/SdFatTestSuite.h | 50 - .../examples/ATS_SD_File/ATS_SD_File.ino | 105 - .../examples/ATS_SD_Files/ATS_SD_Files.ino | 75 - .../examples/ATS_SD_Seek/ATS_SD_Seek.ino | 108 - .../examples/StressTest/StressTest.ino | 76 - .../examples/TestMkdir/TestMkdir.ino | 138 - .../examples/TestRmdir/TestRmdir.ino | 98 - .../examples/fstreamTest/fstreamTest.ino | 94 - .../examples/istreamTest/istreamTest.ino | 261 -- .../examples/lfnSize/lfnSize.ino | 36 - .../examples/lfnTest/lfnTest.ino | 234 -- .../examples/lfnTestCout/lfnTestCout.ino | 218 -- .../examples/ostreamTest/ostreamTest.ino | 172 - .../lib/SdFat/extras/changes.txt | 569 ---- .../lib/SdFat/extras/cpplint.txt | 1 - .../lib/SdFat/library.properties | 11 - .../lib/SdFat/src/BlockDriver.h | 40 - .../lib/SdFat/src/FatLib/ArduinoFiles.h | 249 -- .../lib/SdFat/src/FatLib/ArduinoStream.h | 153 - .../lib/SdFat/src/FatLib/BaseBlockDriver.h | 80 - .../lib/SdFat/src/FatLib/FatApiConstants.h | 87 - .../lib/SdFat/src/FatLib/FatFile.cpp | 1530 --------- .../lib/SdFat/src/FatLib/FatFile.h | 1029 ------ .../lib/SdFat/src/FatLib/FatFileLFN.cpp | 688 ---- .../lib/SdFat/src/FatLib/FatFilePrint.cpp | 267 -- .../lib/SdFat/src/FatLib/FatFileSFN.cpp | 278 -- .../lib/SdFat/src/FatLib/FatFileSystem.h | 332 -- .../lib/SdFat/src/FatLib/FatLib.h | 36 - .../lib/SdFat/src/FatLib/FatLibConfig.h | 146 - .../lib/SdFat/src/FatLib/FatStructs.h | 882 ----- .../lib/SdFat/src/FatLib/FatVolume.cpp | 614 ---- .../lib/SdFat/src/FatLib/FatVolume.h | 375 --- .../lib/SdFat/src/FatLib/FmtNumber.cpp | 460 --- .../lib/SdFat/src/FatLib/FmtNumber.h | 43 - .../lib/SdFat/src/FatLib/StdioStream.cpp | 508 --- .../lib/SdFat/src/FatLib/StdioStream.h | 667 ---- .../lib/SdFat/src/FatLib/bufstream.h | 172 - .../lib/SdFat/src/FatLib/fstream.cpp | 172 - .../lib/SdFat/src/FatLib/fstream.h | 320 -- .../lib/SdFat/src/FatLib/ios.h | 423 --- .../lib/SdFat/src/FatLib/iostream.h | 158 - .../lib/SdFat/src/FatLib/istream.cpp | 396 --- .../lib/SdFat/src/FatLib/istream.h | 384 --- .../lib/SdFat/src/FatLib/ostream.cpp | 196 -- .../lib/SdFat/src/FatLib/ostream.h | 276 -- .../lib/SdFat/src/FreeStack.h | 61 - .../lib/SdFat/src/MinimumSerial.cpp | 71 - .../lib/SdFat/src/MinimumSerial.h | 67 - .../lib/SdFat/src/SdCard/SdInfo.h | 485 --- .../lib/SdFat/src/SdCard/SdSpiCard.cpp | 802 ----- .../lib/SdFat/src/SdCard/SdSpiCard.h | 377 --- .../lib/SdFat/src/SdCard/SdSpiCardEX.cpp | 94 - .../lib/SdFat/src/SdCard/SdioCard.h | 301 -- .../lib/SdFat/src/SdCard/SdioCardEX.cpp | 108 - .../lib/SdFat/src/SdCard/SdioTeensy.cpp | 800 ----- .../lib/SdFat/src/SdFat.h | 512 --- .../lib/SdFat/src/SdFatConfig.h | 233 -- .../lib/SdFat/src/SpiDriver/DigitalPin.h | 386 --- .../lib/SdFat/src/SpiDriver/SdSpiBaseDriver.h | 79 - .../lib/SdFat/src/SpiDriver/SdSpiDriver.h | 438 --- .../lib/SdFat/src/SpiDriver/SdSpiESP8266.cpp | 93 - .../lib/SdFat/src/SpiDriver/SdSpiParticle.cpp | 102 - .../lib/SdFat/src/SpiDriver/SdSpiSAM3X.cpp | 218 -- .../lib/SdFat/src/SpiDriver/SdSpiSTM32.cpp | 105 - .../lib/SdFat/src/SpiDriver/SdSpiTeensy3.cpp | 233 -- .../lib/SdFat/src/SpiDriver/SoftSPI.h | 167 - .../boards/AvrDevelopersGpioPinMap.h | 37 - .../src/SpiDriver/boards/BobuinoGpioPinMap.h | 37 - .../SdFat/src/SpiDriver/boards/GpioPinMap.h | 45 - .../src/SpiDriver/boards/LeonardoGpioPinMap.h | 35 - .../src/SpiDriver/boards/MegaGpioPinMap.h | 75 - .../boards/SleepingBeautyGpioPinMap.h | 37 - .../SpiDriver/boards/Standard1284GpioPinMap.h | 37 - .../src/SpiDriver/boards/Teensy2GpioPinMap.h | 30 - .../SpiDriver/boards/Teensy2ppGpioPinMap.h | 51 - .../src/SpiDriver/boards/UnoGpioPinMap.h | 25 - .../lib/SdFat/src/SysCall.h | 88 - .../lib/SdFat/src/sdios.h | 33 - .../Adafruit_ASFcore/Adafruit_ASFcore.h | 0 .../libraries/Adafruit_ASFcore/README.md | 33 - .../libraries/Adafruit_ASFcore/clock.h | 53 - .../Adafruit_ASFcore/clock_feature.h | 1492 --------- .../libraries/Adafruit_ASFcore/compiler.h | 1157 ------- .../libraries/Adafruit_ASFcore/gclk.c | 522 --- .../libraries/Adafruit_ASFcore/gclk.h | 307 -- .../libraries/Adafruit_ASFcore/i2s.c | 750 ----- .../libraries/Adafruit_ASFcore/i2s.h | 1404 -------- .../libraries/Adafruit_ASFcore/interrupt.h | 117 - .../interrupt/interrupt_sam_nvic.c | 69 - .../interrupt/interrupt_sam_nvic.h | 172 - .../Adafruit_ASFcore/interrupt_sam_nvic.c | 86 - .../Adafruit_ASFcore/interrupt_sam_nvic.h | 189 -- .../Adafruit_ASFcore/library.properties | 9 - .../libraries/Adafruit_ASFcore/parts.h | 1601 --------- .../libraries/Adafruit_ASFcore/pinmux.c | 311 -- .../libraries/Adafruit_ASFcore/pinmux.h | 678 ---- .../libraries/Adafruit_ASFcore/power.h | 224 -- .../preprocessor/mrecursion.h | 581 ---- .../Adafruit_ASFcore/preprocessor/mrepeat.h | 321 -- .../preprocessor/preprocessor.h | 38 - .../Adafruit_ASFcore/preprocessor/stringz.h | 67 - .../Adafruit_ASFcore/preprocessor/tpaste.h | 85 - .../libraries/Adafruit_ASFcore/reset.h | 119 - .../libraries/Adafruit_ASFcore/status_codes.h | 138 - .../libraries/Adafruit_ASFcore/system.c | 111 - .../libraries/Adafruit_ASFcore/system.h | 726 ----- .../Adafruit_ASFcore/system_interrupt.h | 429 --- .../system_interrupt_features.h | 195 -- .../libraries/Adafruit_ASFcore/tc.c | 685 ---- .../libraries/Adafruit_ASFcore/tc.h | 1783 ---------- .../libraries/Adafruit_ASFcore/tc_interrupt.c | 199 -- .../libraries/Adafruit_ASFcore/tc_interrupt.h | 179 - .../libraries/Adafruit_ASFcore/wdt.c | 264 -- .../libraries/Adafruit_ASFcore/wdt.h | 501 --- .../Adafruit_FONA_Library/Adafruit_FONA.cpp | 2079 ------------ .../Adafruit_FONA_Library/Adafruit_FONA.h | 263 -- .../libraries/Adafruit_FONA_Library/README.md | 29 - .../FONA3G_setbaud/.esp8266.test.skip | 0 .../FONA3G_setbaud/FONA3G_setbaud.ino | 77 - .../FONA_SMS_Response/.esp8266.test.skip | 0 .../FONA_SMS_Response/FONA_SMS_Response.ino | 131 - .../examples/FONAtest/.esp8266.test.skip | 0 .../examples/FONAtest/FONAtest.ino | 886 ----- .../examples/GPS/.esp8266.test.skip | 0 .../examples/GPS/GPS.ino | 112 - .../examples/IncomingCall/.esp8266.test.skip | 0 .../examples/IncomingCall/IncomingCall.ino | 62 - .../includes/FONAConfig.h | 34 - .../includes/FONAExtIncludes.h | 33 - .../includes/platform/FONAPlatStd.h | 67 - .../includes/platform/FONAPlatform.h | 62 - .../Adafruit_FONA_Library/library.properties | 9 - .../Adafruit_SleepyDog.cpp | 4 - .../Adafruit_SleepyDog.h | 28 - .../Adafruit_SleepyDog_Library/LICENSE | 22 - .../Adafruit_SleepyDog_Library/README.md | 6 - .../examples/BasicUsage/BasicUsage.ino | 62 - .../examples/Sleep/Sleep.ino | 37 - .../library.properties | 9 - .../utility/WatchdogAVR.cpp | 137 - .../utility/WatchdogAVR.h | 47 - .../utility/WatchdogKinetisK.cpp | 104 - .../utility/WatchdogKinetisK.h | 38 - .../utility/WatchdogKinetisL.cpp | 74 - .../utility/WatchdogKinetisL.h | 35 - .../utility/WatchdogSAMD.cpp | 175 - .../utility/WatchdogSAMD.h | 43 - .../libraries/ArduinoHttpClient/.gitignore | 2 - .../libraries/ArduinoHttpClient/CHANGELOG.md | 25 - .../libraries/ArduinoHttpClient/README.md | 22 - .../examples/BasicAuthGet/BasicAuthGet.ino | 69 - .../examples/BasicAuthGet/arduino_secrets.h | 3 - .../examples/CustomHeader/CustomHeader.ino | 96 - .../examples/CustomHeader/arduino_secrets.h | 3 - .../examples/DweetGet/DweetGet.ino | 107 - .../examples/DweetGet/arduino_secrets.h | 3 - .../examples/DweetPost/DweetPost.ino | 87 - .../examples/DweetPost/arduino_secrets.h | 3 - .../examples/HueBlink/HueBlink.ino | 102 - .../examples/HueBlink/arduino_secrets.h | 3 - .../PostWithHeaders/PostWithHeaders.ino | 79 - .../PostWithHeaders/arduino_secrets.h | 3 - .../examples/SimpleDelete/SimpleDelete.ino | 71 - .../examples/SimpleDelete/arduino_secrets.h | 3 - .../examples/SimpleGet/SimpleGet.ino | 66 - .../examples/SimpleGet/arduino_secrets.h | 3 - .../SimpleHttpExample/SimpleHttpExample.ino | 133 - .../SimpleHttpExample/arduino_secrets.h | 3 - .../examples/SimplePost/SimplePost.ino | 70 - .../examples/SimplePost/arduino_secrets.h | 3 - .../examples/SimplePut/SimplePut.ino | 70 - .../examples/SimplePut/arduino_secrets.h | 3 - .../SimpleWebSocket/SimpleWebSocket.ino | 80 - .../SimpleWebSocket/arduino_secrets.h | 3 - .../node_test_server/getPostPutDelete.js | 102 - .../examples/node_test_server/package.json | 13 - .../libraries/ArduinoHttpClient/keywords.txt | 64 - .../libraries/ArduinoHttpClient/library.json | 12 - .../ArduinoHttpClient/library.properties | 10 - .../ArduinoHttpClient/src/ArduinoHttpClient.h | 11 - .../ArduinoHttpClient/src/HttpClient.cpp | 862 ----- .../ArduinoHttpClient/src/HttpClient.h | 392 --- .../ArduinoHttpClient/src/WebSocketClient.cpp | 372 --- .../ArduinoHttpClient/src/WebSocketClient.h | 99 - .../libraries/ArduinoHttpClient/src/b64.cpp | 72 - .../libraries/ArduinoHttpClient/src/b64.h | 6 - .../RTClib/.github/ISSUE_TEMPLATE.md | 46 - .../RTClib/.github/PULL_REQUEST_TEMPLATE.md | 26 - .../libraries/RTClib/README.md | 42 - .../libraries/RTClib/RTClib.cpp | 506 --- .../libraries/RTClib/RTClib.h | 135 - .../RTClib/examples/datecalc/datecalc.ino | 111 - .../RTClib/examples/ds1307/ds1307.ino | 71 - .../examples/ds1307SqwPin/ds1307SqwPin.ino | 68 - .../examples/ds1307nvram/ds1307nvram.ino | 63 - .../RTClib/examples/ds3231/ds3231.ino | 77 - .../RTClib/examples/pcf8523/pcf8523.ino | 74 - .../RTClib/examples/softrtc/softrtc.ino | 61 - .../libraries/RTClib/keywords.txt | 37 - .../libraries/RTClib/library.properties | 9 - .../libraries/SD/File.cpp | 168 - .../libraries/SD/README.txt | 13 - .../libraries/SD/SD.cpp | 637 ---- .../libraries/SD/SD.h | 138 - .../libraries/SD/utility/FatStructs.h | 418 --- .../libraries/SD/utility/Sd2Card.cpp | 777 ----- .../libraries/SD/utility/Sd2Card.h | 273 -- .../libraries/SD/utility/Sd2PinMap.h | 525 --- .../libraries/SD/utility/SdFat.h | 641 ---- .../libraries/SD/utility/SdFatUtil.h | 77 - .../libraries/SD/utility/SdFatmainpage.h | 202 -- .../libraries/SD/utility/SdFile.cpp | 1527 --------- .../libraries/SD/utility/SdInfo.h | 232 -- .../libraries/SD/utility/SdVolume.cpp | 351 -- .../libraries/WiFi101/.travis.yml | 48 - .../libraries/WiFi101/CHANGELOG | 122 - .../libraries/WiFi101/README.adoc | 27 - .../AP_SimpleWebServer/AP_SimpleWebServer.ino | 176 - .../AP_SimpleWebServer/arduino_secrets.h | 3 - .../CheckWifi101FirmwareVersion.ino | 67 - .../ConnectNoEncryption.ino | 123 - .../ConnectNoEncryption/arduino_secrets.h | 1 - .../ConnectWithWEP/ConnectWithWEP.ino | 129 - .../examples/ConnectWithWEP/arduino_secrets.h | 3 - .../ConnectWithWPA/ConnectWithWPA.ino | 119 - .../examples/ConnectWithWPA/arduino_secrets.h | 3 - .../examples/FirmwareUpdater/Endianess.ino | 62 - .../FirmwareUpdater/FirmwareUpdater.ino | 129 - .../MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino | 170 - .../MDNS_WiFiWebServer/arduino_secrets.h | 3 - .../Provisioning_WiFiWebServer.ino | 167 - .../examples/ScanNetworks/ScanNetworks.ino | 120 - .../ScanNetworksAdvanced.ino | 149 - .../SimpleWebServerWiFi.ino | 131 - .../SimpleWebServerWiFi/arduino_secrets.h | 3 - .../WiFiChatServer/WiFiChatServer.ino | 114 - .../examples/WiFiChatServer/arduino_secrets.h | 3 - .../WiFi101/examples/WiFiPing/WiFiPing.ino | 140 - .../examples/WiFiPing/arduino_secrets.h | 3 - .../examples/WiFiSSLClient/WiFiSSLClient.ino | 107 - .../examples/WiFiSSLClient/arduino_secrets.h | 3 - .../WiFiUdpNtpClient/WiFiUdpNtpClient.ino | 182 -- .../WiFiUdpNtpClient/arduino_secrets.h | 3 - .../WiFiUdpSendReceiveString.ino | 113 - .../arduino_secrets.h | 3 - .../examples/WiFiWebClient/WiFiWebClient.ino | 121 - .../examples/WiFiWebClient/arduino_secrets.h | 3 - .../WiFiWebClientRepeating.ino | 127 - .../WiFiWebClientRepeating/arduino_secrets.h | 3 - .../examples/WiFiWebServer/WiFiWebServer.ino | 135 - .../examples/WiFiWebServer/arduino_secrets.h | 3 - .../libraries/WiFi101/keywords.txt | 61 - .../libraries/WiFi101/library.properties | 10 - .../libraries/WiFi101/src/WiFi.cpp | 1106 ------- .../libraries/WiFi101/src/WiFi101.h | 193 -- .../libraries/WiFi101/src/WiFiClient.cpp | 308 -- .../libraries/WiFi101/src/WiFiClient.h | 68 - .../WiFi101/src/WiFiMDNSResponder.cpp | 220 -- .../libraries/WiFi101/src/WiFiMDNSResponder.h | 51 - .../libraries/WiFi101/src/WiFiSSLClient.cpp | 45 - .../libraries/WiFi101/src/WiFiSSLClient.h | 36 - .../libraries/WiFi101/src/WiFiServer.cpp | 140 - .../libraries/WiFi101/src/WiFiServer.h | 49 - .../libraries/WiFi101/src/WiFiUdp.cpp | 289 -- .../libraries/WiFi101/src/WiFiUdp.h | 89 - .../WiFi101/src/bsp/include/nm_bsp.h | 283 -- .../WiFi101/src/bsp/include/nm_bsp_arduino.h | 74 - .../WiFi101/src/bsp/include/nm_bsp_avr.h | 54 - .../WiFi101/src/bsp/include/nm_bsp_internal.h | 59 - .../WiFi101/src/bsp/include/nm_bsp_samd21.h | 52 - .../WiFi101/src/bsp/source/nm_bsp_arduino.c | 205 -- .../src/bsp/source/nm_bsp_arduino_avr.c | 164 - .../src/bus_wrapper/include/nm_bus_wrapper.h | 177 - .../source/nm_bus_wrapper_samd21.cpp | 200 -- .../WiFi101/src/common/include/nm_common.h | 153 - .../WiFi101/src/common/include/nm_debug.h | 95 - .../WiFi101/src/common/source/nm_common.c | 136 - .../WiFi101/src/driver/include/ecc_types.h | 245 -- .../WiFi101/src/driver/include/m2m_ate_mode.h | 732 ----- .../WiFi101/src/driver/include/m2m_crypto.h | 272 -- .../WiFi101/src/driver/include/m2m_ota.h | 428 --- .../WiFi101/src/driver/include/m2m_periph.h | 411 --- .../WiFi101/src/driver/include/m2m_ssl.h | 182 -- .../WiFi101/src/driver/include/m2m_types.h | 2383 -------------- .../WiFi101/src/driver/include/m2m_wifi.h | 2882 ----------------- .../WiFi101/src/driver/source/m2m_ate_mode.c | 826 ----- .../WiFi101/src/driver/source/m2m_crypto.c | 1010 ------ .../WiFi101/src/driver/source/m2m_hif.c | 767 ----- .../WiFi101/src/driver/source/m2m_hif.h | 249 -- .../WiFi101/src/driver/source/m2m_ota.c | 417 --- .../WiFi101/src/driver/source/m2m_periph.c | 187 -- .../WiFi101/src/driver/source/m2m_ssl.c | 309 -- .../WiFi101/src/driver/source/m2m_wifi.c | 1522 --------- .../WiFi101/src/driver/source/nmasic.c | 688 ---- .../WiFi101/src/driver/source/nmasic.h | 215 -- .../WiFi101/src/driver/source/nmbus.c | 301 -- .../WiFi101/src/driver/source/nmbus.h | 147 - .../WiFi101/src/driver/source/nmdrv.c | 402 --- .../WiFi101/src/driver/source/nmdrv.h | 138 - .../WiFi101/src/driver/source/nmi2c.c | 269 -- .../WiFi101/src/driver/source/nmi2c.h | 104 - .../WiFi101/src/driver/source/nmspi.c | 1401 -------- .../WiFi101/src/driver/source/nmspi.h | 132 - .../WiFi101/src/driver/source/nmuart.c | 536 --- .../WiFi101/src/driver/source/nmuart.h | 118 - .../src/socket/include/m2m_socket_host_if.h | 461 --- .../WiFi101/src/socket/include/socket.h | 2065 ------------ .../src/socket/include/socket_buffer.h | 94 - .../WiFi101/src/socket/source/socket.c | 1445 --------- .../WiFi101/src/socket/source/socket_buffer.c | 232 -- .../src/socket/source/socket_internal.h | 71 - .../WiFi101/src/spi_flash/include/spi_flash.h | 233 -- .../src/spi_flash/include/spi_flash_map.h | 245 -- .../WiFi101/src/spi_flash/source/spi_flash.c | 770 ----- .../project.properties | 3 - .../src/config.cpp | 453 --- .../feather_sensor_transmit_lte/src/config.h | 39 - .../src/feather_sensor_transmit_lte.cpp | 178 - .../src/feather_sensor_transmit_lte.ino | 166 - .../feather_sensor_transmit_lte/src/rtc.cpp | 58 - .../feather_sensor_transmit_lte/src/rtc.h | 11 - .../src/transmit.cpp | 513 --- .../src/transmit.h | 58 - .../src/user_config.h | 4 - .../src/watchdog.cpp | 25 - .../src/watchdog.h | 9 - .../target/1.1.0/boron/module_user_memory.ld | 4 - transmit.cpp | 41 - user_config.h | 3 +- 917 files changed, 1 insertion(+), 204759 deletions(-) delete mode 100644 .vscode/c_cpp_properties.json delete mode 100644 .vscode/settings.json delete mode 160000 boron delete mode 100644 feather_sensor_lte/.vscode/c_cpp_properties.json delete mode 100644 feather_sensor_lte/.vscode/launch.json delete mode 100644 feather_sensor_lte/.vscode/settings.json delete mode 100644 feather_sensor_lte/README.md delete mode 100644 feather_sensor_lte/boron_firmware_1574447345899.bin delete mode 100644 feather_sensor_lte/boron_firmware_1574729317031.bin delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/Adafruit_ASFcore.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/README.md delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/clock.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/clock_feature.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/compiler.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/gclk.c delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/gclk.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/i2s.c delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/i2s.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/library.properties delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/parts.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/pinmux.c delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/pinmux.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/power.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/stringz.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/tpaste.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/reset.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/status_codes.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/system.c delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/system.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/system_interrupt.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/system_interrupt_features.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/tc.c delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/tc.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/tc_interrupt.c delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/tc_interrupt.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/wdt.c delete mode 100644 feather_sensor_lte/libraries/Adafruit_ASFcore/wdt.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp delete mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/README.md delete mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/.esp8266.test.skip delete mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino delete mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/.esp8266.test.skip delete mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino delete mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/.esp8266.test.skip delete mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino delete mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/GPS/.esp8266.test.skip delete mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino delete mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/.esp8266.test.skip delete mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino delete mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/FONAConfig.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_FONA_Library/library.properties delete mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp delete mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/LICENSE delete mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/README.md delete mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino delete mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino delete mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/library.properties delete mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp delete mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp delete mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp delete mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h delete mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp delete mode 100644 feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/.gitignore delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/CHANGELOG.md delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/README.md delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/examples/node_test_server/package.json delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/keywords.txt delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/library.json delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/library.properties delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/src/HttpClient.cpp delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/src/HttpClient.h delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/src/WebSocketClient.cpp delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/src/WebSocketClient.h delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/src/b64.cpp delete mode 100644 feather_sensor_lte/libraries/ArduinoHttpClient/src/b64.h delete mode 100644 feather_sensor_lte/libraries/DHT/.github/ISSUE_TEMPLATE.md delete mode 100644 feather_sensor_lte/libraries/DHT/.github/PULL_REQUEST_TEMPLATE.md delete mode 100644 feather_sensor_lte/libraries/DHT/DHT.cpp delete mode 100644 feather_sensor_lte/libraries/DHT/DHT.h delete mode 100644 feather_sensor_lte/libraries/DHT/DHT_U.cpp delete mode 100644 feather_sensor_lte/libraries/DHT/DHT_U.h delete mode 100644 feather_sensor_lte/libraries/DHT/README.md delete mode 100644 feather_sensor_lte/libraries/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino delete mode 100644 feather_sensor_lte/libraries/DHT/examples/DHTtester/DHTtester.ino delete mode 100644 feather_sensor_lte/libraries/DHT/keywords.txt delete mode 100644 feather_sensor_lte/libraries/DHT/library.properties delete mode 100644 feather_sensor_lte/libraries/RTClib/.github/ISSUE_TEMPLATE.md delete mode 100644 feather_sensor_lte/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md delete mode 100644 feather_sensor_lte/libraries/RTClib/README.md delete mode 100644 feather_sensor_lte/libraries/RTClib/RTClib.cpp delete mode 100644 feather_sensor_lte/libraries/RTClib/RTClib.h delete mode 100644 feather_sensor_lte/libraries/RTClib/examples/datecalc/datecalc.ino delete mode 100644 feather_sensor_lte/libraries/RTClib/examples/ds1307/ds1307.ino delete mode 100644 feather_sensor_lte/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino delete mode 100644 feather_sensor_lte/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino delete mode 100644 feather_sensor_lte/libraries/RTClib/examples/ds3231/ds3231.ino delete mode 100644 feather_sensor_lte/libraries/RTClib/examples/pcf8523/pcf8523.ino delete mode 100644 feather_sensor_lte/libraries/RTClib/examples/softrtc/softrtc.ino delete mode 100644 feather_sensor_lte/libraries/RTClib/keywords.txt delete mode 100644 feather_sensor_lte/libraries/RTClib/library.properties delete mode 100644 feather_sensor_lte/libraries/WiFi101/.travis.yml delete mode 100644 feather_sensor_lte/libraries/WiFi101/CHANGELOG delete mode 100644 feather_sensor_lte/libraries/WiFi101/README.adoc delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino delete mode 100644 feather_sensor_lte/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/keywords.txt delete mode 100644 feather_sensor_lte/libraries/WiFi101/library.properties delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFi.cpp delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFi101.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiClient.cpp delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiClient.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiMDNSResponder.cpp delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiMDNSResponder.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiSSLClient.cpp delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiSSLClient.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiServer.cpp delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiServer.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiUdp.cpp delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/WiFiUdp.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/bus_wrapper/include/nm_bus_wrapper.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/common/include/nm_common.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/common/include/nm_debug.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/common/source/nm_common.c delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/include/ecc_types.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_ate_mode.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_crypto.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_ota.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_periph.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_ssl.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_types.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_wifi.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ate_mode.c delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_crypto.c delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_hif.c delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_hif.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ota.c delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_periph.c delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ssl.c delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_wifi.c delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmasic.c delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmasic.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmbus.c delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmbus.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmdrv.c delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmdrv.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmi2c.c delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmi2c.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmspi.c delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmspi.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmuart.c delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/driver/source/nmuart.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/socket/include/socket.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/socket/include/socket_buffer.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/socket/source/socket.c delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/socket/source/socket_buffer.c delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/socket/source/socket_internal.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/spi_flash/include/spi_flash.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h delete mode 100644 feather_sensor_lte/libraries/WiFi101/src/spi_flash/source/spi_flash.c delete mode 100644 feather_sensor_lte/project.properties delete mode 100644 feather_sensor_lte/src/feather_sensor_lte.ino delete mode 100644 feather_sensor_transmit/.vscode/c_cpp_properties.json delete mode 100644 feather_sensor_transmit/.vscode/launch.json delete mode 100644 feather_sensor_transmit/.vscode/settings.json delete mode 100644 feather_sensor_transmit/boron_firmware_1574447345899.bin delete mode 100644 feather_sensor_transmit/boron_firmware_1574729317031.bin delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/Adafruit_ASFcore.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/README.md delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/clock.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/clock_feature.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/compiler.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/gclk.c delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/gclk.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/i2s.c delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/i2s.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/library.properties delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/parts.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/pinmux.c delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/pinmux.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/power.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/stringz.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/tpaste.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/reset.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/status_codes.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/system.c delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/system.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/system_interrupt.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/system_interrupt_features.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/tc.c delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/tc.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/tc_interrupt.c delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/tc_interrupt.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/wdt.c delete mode 100644 feather_sensor_transmit/libraries/Adafruit_ASFcore/wdt.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp delete mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/Adafruit_FONA.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/README.md delete mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/.esp8266.test.skip delete mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino delete mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/.esp8266.test.skip delete mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino delete mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONAtest/.esp8266.test.skip delete mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino delete mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/GPS/.esp8266.test.skip delete mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino delete mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/IncomingCall/.esp8266.test.skip delete mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino delete mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/FONAConfig.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_FONA_Library/library.properties delete mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp delete mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/LICENSE delete mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/README.md delete mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino delete mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino delete mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/library.properties delete mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp delete mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp delete mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp delete mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h delete mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp delete mode 100644 feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/.gitignore delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/CHANGELOG.md delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/README.md delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/examples/node_test_server/package.json delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/keywords.txt delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/library.json delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/library.properties delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/src/HttpClient.cpp delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/src/HttpClient.h delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/src/WebSocketClient.cpp delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/src/WebSocketClient.h delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/src/b64.cpp delete mode 100644 feather_sensor_transmit/libraries/ArduinoHttpClient/src/b64.h delete mode 100644 feather_sensor_transmit/libraries/DHT/.github/ISSUE_TEMPLATE.md delete mode 100644 feather_sensor_transmit/libraries/DHT/.github/PULL_REQUEST_TEMPLATE.md delete mode 100644 feather_sensor_transmit/libraries/DHT/DHT.cpp delete mode 100644 feather_sensor_transmit/libraries/DHT/DHT.h delete mode 100644 feather_sensor_transmit/libraries/DHT/DHT_U.cpp delete mode 100644 feather_sensor_transmit/libraries/DHT/DHT_U.h delete mode 100644 feather_sensor_transmit/libraries/DHT/README.md delete mode 100644 feather_sensor_transmit/libraries/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino delete mode 100644 feather_sensor_transmit/libraries/DHT/examples/DHTtester/DHTtester.ino delete mode 100644 feather_sensor_transmit/libraries/DHT/keywords.txt delete mode 100644 feather_sensor_transmit/libraries/DHT/library.properties delete mode 100644 feather_sensor_transmit/libraries/RTClib/.github/ISSUE_TEMPLATE.md delete mode 100644 feather_sensor_transmit/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md delete mode 100644 feather_sensor_transmit/libraries/RTClib/README.md delete mode 100644 feather_sensor_transmit/libraries/RTClib/RTClib.cpp delete mode 100644 feather_sensor_transmit/libraries/RTClib/RTClib.h delete mode 100644 feather_sensor_transmit/libraries/RTClib/examples/datecalc/datecalc.ino delete mode 100644 feather_sensor_transmit/libraries/RTClib/examples/ds1307/ds1307.ino delete mode 100644 feather_sensor_transmit/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino delete mode 100644 feather_sensor_transmit/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino delete mode 100644 feather_sensor_transmit/libraries/RTClib/examples/ds3231/ds3231.ino delete mode 100644 feather_sensor_transmit/libraries/RTClib/examples/pcf8523/pcf8523.ino delete mode 100644 feather_sensor_transmit/libraries/RTClib/examples/softrtc/softrtc.ino delete mode 100644 feather_sensor_transmit/libraries/RTClib/keywords.txt delete mode 100644 feather_sensor_transmit/libraries/RTClib/library.properties delete mode 100644 feather_sensor_transmit/libraries/WiFi101/.travis.yml delete mode 100644 feather_sensor_transmit/libraries/WiFi101/CHANGELOG delete mode 100644 feather_sensor_transmit/libraries/WiFi101/README.adoc delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino delete mode 100644 feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/keywords.txt delete mode 100644 feather_sensor_transmit/libraries/WiFi101/library.properties delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFi.cpp delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFi101.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiClient.cpp delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiClient.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiMDNSResponder.cpp delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiMDNSResponder.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiSSLClient.cpp delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiSSLClient.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiServer.cpp delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiServer.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiUdp.cpp delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/WiFiUdp.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/bus_wrapper/include/nm_bus_wrapper.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/common/include/nm_common.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/common/include/nm_debug.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/common/source/nm_common.c delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/include/ecc_types.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_ate_mode.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_crypto.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_ota.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_periph.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_ssl.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_types.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_wifi.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ate_mode.c delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_crypto.c delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_hif.c delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_hif.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ota.c delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_periph.c delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ssl.c delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_wifi.c delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmasic.c delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmasic.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmbus.c delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmbus.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmdrv.c delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmdrv.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmi2c.c delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmi2c.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmspi.c delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmspi.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmuart.c delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmuart.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/socket/include/socket.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/socket/include/socket_buffer.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket.c delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket_buffer.c delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket_internal.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/spi_flash/include/spi_flash.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h delete mode 100644 feather_sensor_transmit/libraries/WiFi101/src/spi_flash/source/spi_flash.c delete mode 100644 feather_sensor_transmit/project.properties delete mode 100644 feather_sensor_transmit/src/LICENSE.txt delete mode 100644 feather_sensor_transmit/src/README.md delete mode 100644 feather_sensor_transmit/src/config.cpp delete mode 100644 feather_sensor_transmit/src/config.h delete mode 100644 feather_sensor_transmit/src/heatseek_sensor.ino delete mode 100644 feather_sensor_transmit/src/rtc.cpp delete mode 100644 feather_sensor_transmit/src/rtc.h delete mode 100644 feather_sensor_transmit/src/transmit.cpp delete mode 100644 feather_sensor_transmit/src/transmit.h delete mode 100644 feather_sensor_transmit/src/user_config.h delete mode 100644 feather_sensor_transmit/src/watchdog.cpp delete mode 100644 feather_sensor_transmit/src/watchdog.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/c_cpp_properties.json delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/launch.json delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/settings.json delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/README.md delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/boron_firmware_1574447345899.bin delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/boron_firmware_1574729317031.bin delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/LICENSE.txt delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/README.md delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/examples/DHTtester/DHTtester.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/keywords.txt delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/library.properties delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT_U.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT_U.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/LICENSE.md delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/README.md delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/AnalogLogger/AnalogLogger.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/BaseExtCaseTest/BaseExtCaseTest.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/HelloWorld/HelloWorld.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/MiniSerial/MiniSerial.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/PrintBenchmarkSD/PrintBenchmarkSD.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/SD_Size/SD_Size.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/SdFatSize/SdFatSize.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/StreamParseInt/StreamParseInt.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/append/append.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/average/average.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/benchSD/benchSD.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/bufstream/bufstream.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/cin_cout/cin_cout.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/eventlog/eventlog.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/fgetsRewrite/fgetsRewrite.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/readlog/readlog.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/readme.txt delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/AnalogBinLogger/AnalogBinLogger.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/AnalogBinLogger/AnalogBinLogger.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/DirectoryFunctions/DirectoryFunctions.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/LongFileName.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/A long name can be 255 characters.txt delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/LFN,NAME.TXT delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/MIXCASE.txt delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/Not_8_3.txt delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/OK%83.TXT delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/STD_8_3.TXT delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/With Blank.txt delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/With.Two dots.txt delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/lower.txt delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/mixed.TXT delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/LowLatencyLogger.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/UserFunctions.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/UserTypes.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/LowLatencyLogger.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/LowLatencyLoggerADXL345.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/UserFunctions.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/UserTypes.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/readme.txt delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/LowLatencyLogger.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/LowLatencyLoggerMPU6050.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/UserFunctions.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/UserTypes.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/OpenNext/OpenNext.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/PrintBenchmark/PrintBenchmark.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/QuickStart/QuickStart.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/RawWrite/RawWrite.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsv/ReadCsv.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsvArray/ReadCsvArray.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsvStream/ReadCsvStream.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadWrite/ReadWrite.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/STM32Test/STM32Test.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SdFormatter/SdFormatter.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SdInfo/SdInfo.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SoftwareSpi/SoftwareSpi.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/StdioBench/StdioBench.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/TeensySdioDemo/TeensySdioDemo.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/Timestamp/Timestamp.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/TwoCards/TwoCards.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/VolumeFreeSpace/VolumeFreeSpace.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/bench/bench.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/dataLogger/dataLogger.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/fgets/fgets.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/formatting/formatting.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/getline/getline.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/rename/rename.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/wipe/wipe.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/AdcErrorStudy.txt delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/RateTable.txt delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/bintocsv/AnalogBinLogger.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/bintocsv/bintocsv.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/readme.txt delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/MainPage/SdFatmainpage.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/SdFatTestSuite.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/SdFatTestSuite.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_File/ATS_SD_File.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_Files/ATS_SD_Files.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_Seek/ATS_SD_Seek.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/StressTest/StressTest.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/TestMkdir/TestMkdir.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/TestRmdir/TestRmdir.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/fstreamTest/fstreamTest.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/istreamTest/istreamTest.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnSize/lfnSize.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnTest/lfnTest.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnTestCout/lfnTestCout.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ostreamTest/ostreamTest.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/changes.txt delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/cpplint.txt delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/library.properties delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/BlockDriver.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ArduinoFiles.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ArduinoStream.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/BaseBlockDriver.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatApiConstants.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFile.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFile.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileLFN.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFilePrint.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileSFN.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileSystem.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatLib.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatLibConfig.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatStructs.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatVolume.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatVolume.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FmtNumber.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FmtNumber.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/StdioStream.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/StdioStream.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/bufstream.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/fstream.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/fstream.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ios.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/iostream.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/istream.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/istream.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ostream.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ostream.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FreeStack.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/MinimumSerial.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/MinimumSerial.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdInfo.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCard.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCard.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCardEX.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioCard.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioCardEX.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioTeensy.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdFat.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdFatConfig.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/DigitalPin.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiBaseDriver.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiDriver.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiESP8266.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiParticle.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiSAM3X.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiSTM32.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiTeensy3.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SoftSPI.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/AvrDevelopersGpioPinMap.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/BobuinoGpioPinMap.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/GpioPinMap.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/LeonardoGpioPinMap.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/MegaGpioPinMap.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/SleepingBeautyGpioPinMap.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Standard1284GpioPinMap.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Teensy2GpioPinMap.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Teensy2ppGpioPinMap.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/UnoGpioPinMap.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SysCall.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/sdios.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/Adafruit_ASFcore.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/README.md delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/clock.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/clock_feature.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/compiler.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/gclk.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/gclk.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/i2s.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/i2s.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/library.properties delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/parts.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/pinmux.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/pinmux.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/power.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/stringz.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/tpaste.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/reset.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/status_codes.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system_interrupt.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system_interrupt_features.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc_interrupt.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc_interrupt.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/wdt.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/wdt.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/README.md delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/.esp8266.test.skip delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/.esp8266.test.skip delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/.esp8266.test.skip delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/GPS/.esp8266.test.skip delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/.esp8266.test.skip delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/FONAConfig.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/library.properties delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/LICENSE delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/README.md delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/library.properties delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/.gitignore delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/CHANGELOG.md delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/README.md delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/node_test_server/package.json delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/keywords.txt delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/library.json delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/library.properties delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/HttpClient.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/HttpClient.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/WebSocketClient.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/WebSocketClient.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/b64.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/b64.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/.github/ISSUE_TEMPLATE.md delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/README.md delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/RTClib.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/RTClib.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/datecalc/datecalc.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307/ds1307.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds3231/ds3231.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/pcf8523/pcf8523.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/softrtc/softrtc.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/keywords.txt delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/library.properties delete mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/File.cpp delete mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/README.txt delete mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/SD.cpp delete mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/SD.h delete mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/FatStructs.h delete mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2Card.cpp delete mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2Card.h delete mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2PinMap.h delete mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFat.h delete mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFatUtil.h delete mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFatmainpage.h delete mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFile.cpp delete mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdInfo.h delete mode 100755 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdVolume.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/.travis.yml delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/CHANGELOG delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/README.adoc delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/keywords.txt delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/library.properties delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFi.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFi101.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiClient.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiClient.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiMDNSResponder.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiMDNSResponder.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiSSLClient.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiSSLClient.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiServer.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiServer.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiUdp.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiUdp.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bus_wrapper/include/nm_bus_wrapper.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/include/nm_common.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/include/nm_debug.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/source/nm_common.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/ecc_types.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_ate_mode.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_crypto.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_ota.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_periph.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_ssl.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_types.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_wifi.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ate_mode.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_crypto.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_hif.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_hif.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ota.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_periph.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ssl.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_wifi.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmasic.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmasic.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmbus.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmbus.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmdrv.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmdrv.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmi2c.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmi2c.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmspi.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmspi.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmuart.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmuart.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/socket.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/socket_buffer.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket_buffer.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket_internal.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/include/spi_flash.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/source/spi_flash.c delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/project.properties delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/config.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/config.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.ino delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/rtc.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/rtc.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/transmit.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/transmit.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/user_config.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/watchdog.cpp delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/watchdog.h delete mode 100644 feather_sensor_transmit_lte/feather_sensor_transmit_lte/target/1.1.0/boron/module_user_memory.ld diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json deleted file mode 100644 index 1df4412..0000000 --- a/.vscode/c_cpp_properties.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "configurations": [ - { - "name": "Win32", - "includePath": [ - "${workspaceFolder}/**" - ], - "defines": [ - "_DEBUG", - "UNICODE", - "_UNICODE" - ], - "intelliSenseMode": "msvc-x64" - } - ], - "version": 4 -} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 3b66410..0000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "git.ignoreLimitWarning": true -} \ No newline at end of file diff --git a/README.md b/README.md index 2c9fcfb..66933c2 100644 --- a/README.md +++ b/README.md @@ -54,11 +54,6 @@ - [Sticker Antenna](https://www.adafruit.com/product/3237) - [SIM800L GSM Breakout Module](http://www.ebay.com/itm/SIM800L-Quad-band-Network-Mini-GPRS-GSM-Breakout-Module-Ships-from-California-/172265821650?hash=item281bd7d5d2:g:97gAAOSwls5Y5qFG) -### Particle Boron (LTE) - -- Coming soon! -- All base parts -- [Particle Boron](https://docs.particle.io/boron/) ### Headseek Featherwing Board diff --git a/boron b/boron deleted file mode 160000 index bc0e560..0000000 --- a/boron +++ /dev/null @@ -1 +0,0 @@ -Subproject commit bc0e56015aaea350d627b8f199ba69fc7943cad1 diff --git a/feather_sensor_lte/.vscode/c_cpp_properties.json b/feather_sensor_lte/.vscode/c_cpp_properties.json deleted file mode 100644 index c16b552..0000000 --- a/feather_sensor_lte/.vscode/c_cpp_properties.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "configurations": [ - { - "name": "Win32", - "includePath": [ - "${workspaceFolder}/**" - ], - "defines": [ - "_DEBUG", - "UNICODE", - "_UNICODE" - ], - "intelliSenseMode": "msvc-x64", - "configurationProvider": "particle.particle-vscode-core" - } - ], - "version": 4 -} \ No newline at end of file diff --git a/feather_sensor_lte/.vscode/launch.json b/feather_sensor_lte/.vscode/launch.json deleted file mode 100644 index 4532e35..0000000 --- a/feather_sensor_lte/.vscode/launch.json +++ /dev/null @@ -1,92 +0,0 @@ -{ - "version": "0.1.0", - "configurations": [ - { - "type": "cortex-debug", - "request": "attach", - "name": "Particle Debugger (photon, p1, electron)", - "servertype": "openocd", - "interface": "swd", - "device": "STM32F205RG", - "cwd": "${workspaceRoot}", - "executable": "${command:particle.getDebuggerExecutable}", - "preLaunchTask": "Particle: Flash application for debug (local)", - "armToolchainPath": "${command:particle.getDebuggerCompilerDir}", - "svdFile": "${command:particle.getDebuggerSVDFile}", - "searchDir": [ - "${command:particle.getDebuggerSearchDir}" - ], - "configFiles": [ - "interface/cmsis-dap.cfg", - "target/stm32f2x.cfg" - ], - "postAttachCommands": [ - "monitor reset halt" - ], - "windows": { - "configFiles": [ - "interface\\cmsis-dap.cfg", - "target\\stm32f2x.cfg" - ] - } - }, - { - "type": "cortex-debug", - "request": "attach", - "name": "Particle Debugger (argon, boron / bsom, xenon)", - "servertype": "openocd", - "interface": "swd", - "device": "nRF52840_xxAA", - "cwd": "${workspaceRoot}", - "executable": "${command:particle.getDebuggerExecutable}", - "preLaunchTask": "Particle: Flash application for debug (local)", - "armToolchainPath": "${command:particle.getDebuggerCompilerDir}", - "svdFile": "${command:particle.getDebuggerSVDFile}", - "searchDir": [ - "${command:particle.getDebuggerSearchDir}" - ], - "configFiles": [ - "interface/cmsis-dap.cfg", - "target/nrf52-particle.cfg" - ], - "postAttachCommands": [ - "monitor reset halt" - ], - "windows": { - "configFiles": [ - "interface\\cmsis-dap.cfg", - "target\\nrf52-particle.cfg" - ] - } - }, - { - "type": "cortex-debug", - "request": "attach", - "name": "Particle Programmer Shield v1.0 (photon, p1, electron)", - "servertype": "openocd", - "interface": "swd", - "device": "STM32F205RG", - "cwd": "${workspaceRoot}", - "executable": "${command:particle.getDebuggerExecutable}", - "preLaunchTask": "Particle: Flash application for debug (local)", - "armToolchainPath": "${command:particle.getDebuggerCompilerDir}", - "svdFile": "${command:particle.getDebuggerSVDFile}", - "searchDir": [ - "${command:particle.getDebuggerSearchDir}" - ], - "configFiles": [ - "interface/particle-ftdi.cfg", - "target/stm32f2x.cfg" - ], - "postAttachCommands": [ - "monitor reset halt" - ], - "windows": { - "configFiles": [ - "interface\\particle-ftdi.cfg", - "target\\stm32f2x.cfg" - ] - } - } - ] -} \ No newline at end of file diff --git a/feather_sensor_lte/.vscode/settings.json b/feather_sensor_lte/.vscode/settings.json deleted file mode 100644 index 5d5f015..0000000 --- a/feather_sensor_lte/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "extensions.ignoreRecommendations": true, - "cortex-debug.openocdPath": "${command:particle.getDebuggerOpenocdPath}", - "files.associations": { - "*.ino": "cpp" - }, - "particle.targetDevice": "e00fce684c6a4946ca9fecd1", - "particle.firmwareVersion": "1.1.0", - "particle.targetPlatform": "boron", - "git.ignoreLimitWarning": true -} \ No newline at end of file diff --git a/feather_sensor_lte/README.md b/feather_sensor_lte/README.md deleted file mode 100644 index d7c8ea2..0000000 --- a/feather_sensor_lte/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# feather_sensor_lte - -A Particle project named feather_sensor_lte - -## Welcome to your project! - -Every new Particle project is composed of 3 important elements that you'll see have been created in your project directory for feather_sensor_lte. - -#### ```/src``` folder: -This is the source folder that contains the firmware files for your project. It should *not* be renamed. -Anything that is in this folder when you compile your project will be sent to our compile service and compiled into a firmware binary for the Particle device that you have targeted. - -If your application contains multiple files, they should all be included in the `src` folder. If your firmware depends on Particle libraries, those dependencies are specified in the `project.properties` file referenced below. - -#### ```.ino``` file: -This file is the firmware that will run as the primary application on your Particle device. It contains a `setup()` and `loop()` function, and can be written in Wiring or C/C++. For more information about using the Particle firmware API to create firmware for your Particle device, refer to the [Firmware Reference](https://docs.particle.io/reference/firmware/) section of the Particle documentation. - -#### ```project.properties``` file: -This is the file that specifies the name and version number of the libraries that your project depends on. Dependencies are added automatically to your `project.properties` file when you add a library to a project using the `particle library add` command in the CLI or add a library in the Desktop IDE. - -## Adding additional files to your project - -#### Projects with multiple sources -If you would like add additional files to your application, they should be added to the `/src` folder. All files in the `/src` folder will be sent to the Particle Cloud to produce a compiled binary. - -#### Projects with external libraries -If your project includes a library that has not been registered in the Particle libraries system, you should create a new folder named `/lib//src` under `/` and add the `.h`, `.cpp` & `library.properties` files for your library there. Read the [Firmware Libraries guide](https://docs.particle.io/guide/tools-and-features/libraries/) for more details on how to develop libraries. Note that all contents of the `/lib` folder and subfolders will also be sent to the Cloud for compilation. - -## Compiling your project - -When you're ready to compile your project, make sure you have the correct Particle device target selected and run `particle compile ` in the CLI or click the Compile button in the Desktop IDE. The following files in your project folder will be sent to the compile service: - -- Everything in the `/src` folder, including your `.ino` application file -- The `project.properties` file for your project -- Any libraries stored under `lib//src` diff --git a/feather_sensor_lte/boron_firmware_1574447345899.bin b/feather_sensor_lte/boron_firmware_1574447345899.bin deleted file mode 100644 index 544964835a60d84338704d5bd1234e633fc8cef4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5592 zcmd5=e{d9c6@PoXm%IEpxKOBP0?ghmXAchWXj;9NIunv~6LJX@soEAh-ZeSgND{6g zv1!FINUL;er>&(UE!JrT9O{V8)t*Cu?Ku{m))u|AD0ILPwKcS~y1|xP@@xHkckdS& z$G;rMo%!7Nz3;yFzVF9(-}jqPy^BtM&P7CJ!Uh zK!cF^yzUR}Y38oi#}d%H4mwk}Vr^~yVJGAzT|MutCvA&L+6N<~T^OOk;fW!wzC6*) zNqi#FOyo?JML4f#7ioW(5lqU``Q1yD9>m(rmvCxM`<%AGF3wBZ$r;WoLOL_E{=@qc zq&+_!*hQFsWd^etkDK%A`7qXf7Cz-|kfy^YTclR0Rk+8UYMYJ6+9uz1CBJDFzjqdY zW)@%jl`HivK2Wf~$$Ver_s-(a%;IaeFndM$O|$sg?knG0@!V8c?~EB=k*_uVE%H`; zMc#_9$XoFhc`KeGZ~0&3Eqk4X_4k_Vw-oqVbNwQ3$rpJm-Xg!rjIV?@?Rg6JEd3&X z#QL z%y|`9Tw~b0L$Xh1^lF2CutWCBwDP(PExmShn_>&vG8Mt{%(8Qb$7$|0nY+8fvapJ@ zHz&k%BbZs7>F=ucaR*7OnkkbW*5`+~L&CU|_gv>uZdaDc{4bq#`x+L=*-`GfvV)F8 zqB#rFv3{i1ne9aJLH}+LHRT<%263uJ+adyJ?r&RV^ zY5sc5Uzhn?le67u+D@cy-Y&>aDr4KVdU}gLmt7BFBQl(nsgz8aNHTRT~bheg9%3HkP z{$N(Ja>~)_SZi+~%{|Gtgw^-o!F>WyfLj4plXsendwl@evpU721!^xSwo@O$nBVpH zs>NN8`$eI9+*#172W9Q`M)N(huu_H3Z2|u>nY;xY#Z4>O>$z`tj}MLTD9Lc$*Rj}k~&!4x9yACvCBEhDSP`n`m14OzbUhD zql?_B`94U(uTgU@gnQAqhq;6Jf()w;ZnF+;lhGviW3TLJF|wm(6f1Zho_A8@OmPPqmj8f+bWb&wugiX6UY@QB%++KH}p6*?Se z_BYmxoT;iv9eU912Cvk1?P;b!`B`VA12d1#v5(~Q^Uyq zY?6z3qE2-=?#Yf6N%VM)yj8o0GqTYse)vvZm?Uzf8h2F$otayL<)h^|WmhN7Hy1q3 zM)n<}>|CkV%{i^}sE-?Kd~Fg{*Un8iB3C6vnfZVYf!d}g$;-E>=iT^EN@H0ZwKgVdfGcDlU(A5M^lPdI*wMo)`IuXRa@X7(~ z4c2XNcBs6v7iUN)_0Vu7_VUB}5;wPOPrAbA8kdBhOsculLH$*Y!yG!fQVn?~DgkD+D@)oEnP*$IrYf3U(6Gw2K z<1DvwS%r1GkxQI=xqdm<{7wfi-?=KsZJvGI65odM+fB$^pFr`B|eLwW;L9@Lv7klT) zsX%i7cqMNOa;Hgjt44MhJNdU$&Lp?|(pyHhdK%}-v}zTQO6h4oUbN&HRv~T^nB2n96hf@#$6&ar$nZzM5dxdhVA)oi5*{w9kImD;u4vKB{DT7GAx$7&n%XFTr8G+Tr8Hn42vZ%!(z$H zFrU8gmd?fwiT|wHng?x)*cf`VK0zHA3uhO|7 zEt?$m)NtWM^CJB3=XT%$;6b4Dd7#Nfj{r{s`+!5h2=FUl6nG2xEARo3e}cFxdx4Ju zE`S3*y4gkV0)GZh0VjY`9oA>AVfVS*!}``C-~k{GJPbSmJPjNG^3OY<%UfKu0QdsV zrg8AoKo;OJH-_;7kbgdgJBth8ff2mV0vCWk0jGcyz{^0XZ|t7)9Iz8$YkVE!mw~Oo zKHwf82IQaSRu|m>tOo8Ne=tfOAR z?uqsFQoOHkYabTw?dqUdcXvKH7{Af(q5)tF5Cc93tOY&;Tn_{RFHl;867~No*$8VN zUxU4X{rDF4sTXyuMvYehYk+e2@gVR=;MH|5YG04{x47u{KIr~kO#?Ku+fSs8q`McqAq MGC(&!fBm2T1#!eoE&u=k diff --git a/feather_sensor_lte/boron_firmware_1574729317031.bin b/feather_sensor_lte/boron_firmware_1574729317031.bin deleted file mode 100644 index 544964835a60d84338704d5bd1234e633fc8cef4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5592 zcmd5=e{d9c6@PoXm%IEpxKOBP0?ghmXAchWXj;9NIunv~6LJX@soEAh-ZeSgND{6g zv1!FINUL;er>&(UE!JrT9O{V8)t*Cu?Ku{m))u|AD0ILPwKcS~y1|xP@@xHkckdS& z$G;rMo%!7Nz3;yFzVF9(-}jqPy^BtM&P7CJ!Uh zK!cF^yzUR}Y38oi#}d%H4mwk}Vr^~yVJGAzT|MutCvA&L+6N<~T^OOk;fW!wzC6*) zNqi#FOyo?JML4f#7ioW(5lqU``Q1yD9>m(rmvCxM`<%AGF3wBZ$r;WoLOL_E{=@qc zq&+_!*hQFsWd^etkDK%A`7qXf7Cz-|kfy^YTclR0Rk+8UYMYJ6+9uz1CBJDFzjqdY zW)@%jl`HivK2Wf~$$Ver_s-(a%;IaeFndM$O|$sg?knG0@!V8c?~EB=k*_uVE%H`; zMc#_9$XoFhc`KeGZ~0&3Eqk4X_4k_Vw-oqVbNwQ3$rpJm-Xg!rjIV?@?Rg6JEd3&X z#QL z%y|`9Tw~b0L$Xh1^lF2CutWCBwDP(PExmShn_>&vG8Mt{%(8Qb$7$|0nY+8fvapJ@ zHz&k%BbZs7>F=ucaR*7OnkkbW*5`+~L&CU|_gv>uZdaDc{4bq#`x+L=*-`GfvV)F8 zqB#rFv3{i1ne9aJLH}+LHRT<%263uJ+adyJ?r&RV^ zY5sc5Uzhn?le67u+D@cy-Y&>aDr4KVdU}gLmt7BFBQl(nsgz8aNHTRT~bheg9%3HkP z{$N(Ja>~)_SZi+~%{|Gtgw^-o!F>WyfLj4plXsendwl@evpU721!^xSwo@O$nBVpH zs>NN8`$eI9+*#172W9Q`M)N(huu_H3Z2|u>nY;xY#Z4>O>$z`tj}MLTD9Lc$*Rj}k~&!4x9yACvCBEhDSP`n`m14OzbUhD zql?_B`94U(uTgU@gnQAqhq;6Jf()w;ZnF+;lhGviW3TLJF|wm(6f1Zho_A8@OmPPqmj8f+bWb&wugiX6UY@QB%++KH}p6*?Se z_BYmxoT;iv9eU912Cvk1?P;b!`B`VA12d1#v5(~Q^Uyq zY?6z3qE2-=?#Yf6N%VM)yj8o0GqTYse)vvZm?Uzf8h2F$otayL<)h^|WmhN7Hy1q3 zM)n<}>|CkV%{i^}sE-?Kd~Fg{*Un8iB3C6vnfZVYf!d}g$;-E>=iT^EN@H0ZwKgVdfGcDlU(A5M^lPdI*wMo)`IuXRa@X7(~ z4c2XNcBs6v7iUN)_0Vu7_VUB}5;wPOPrAbA8kdBhOsculLH$*Y!yG!fQVn?~DgkD+D@)oEnP*$IrYf3U(6Gw2K z<1DvwS%r1GkxQI=xqdm<{7wfi-?=KsZJvGI65odM+fB$^pFr`B|eLwW;L9@Lv7klT) zsX%i7cqMNOa;Hgjt44MhJNdU$&Lp?|(pyHhdK%}-v}zTQO6h4oUbN&HRv~T^nB2n96hf@#$6&ar$nZzM5dxdhVA)oi5*{w9kImD;u4vKB{DT7GAx$7&n%XFTr8G+Tr8Hn42vZ%!(z$H zFrU8gmd?fwiT|wHng?x)*cf`VK0zHA3uhO|7 zEt?$m)NtWM^CJB3=XT%$;6b4Dd7#Nfj{r{s`+!5h2=FUl6nG2xEARo3e}cFxdx4Ju zE`S3*y4gkV0)GZh0VjY`9oA>AVfVS*!}``C-~k{GJPbSmJPjNG^3OY<%UfKu0QdsV zrg8AoKo;OJH-_;7kbgdgJBth8ff2mV0vCWk0jGcyz{^0XZ|t7)9Iz8$YkVE!mw~Oo zKHwf82IQaSRu|m>tOo8Ne=tfOAR z?uqsFQoOHkYabTw?dqUdcXvKH7{Af(q5)tF5Cc93tOY&;Tn_{RFHl;867~No*$8VN zUxU4X{rDF4sTXyuMvYehYk+e2@gVR=;MH|5YG04{x47u{KIr~kO#?Ku+fSs8q`McqAq MGC(&!fBm2T1#!eoE&u=k diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/Adafruit_ASFcore.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/Adafruit_ASFcore.h deleted file mode 100644 index e69de29..0000000 diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/README.md b/feather_sensor_lte/libraries/Adafruit_ASFcore/README.md deleted file mode 100644 index 8de73c7..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# ASF (Atmel Software Framework) for Arduino Zero / Adafruit Feather M0 (SAMD21) - -Copy of ASF (Atmel Software Framework) excerpts for the SAMD21 processor used in the Arduino Zero / Adafruit Feather M0 boards. -You typically won't use this library directly, instead other libraries will depend on this library and use the code -within it to simplify their implementation. - -All code is taken directly from Atmel's ASF: http://www.atmel.com/tools/avrsoftwareframework.aspx?tab=overview - -The code is copyright Atmel and released by them under the following license: - - 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. The name of Atmel may not be used to endorse or promote products derived from this software without specific - prior written permission. - - 4. This software may only be redistributed and used in connection with an Atmel microcontroller product. - - THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A - PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN - NO EVENT SHALL ATMEL 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. diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/clock.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/clock.h deleted file mode 100644 index 549e3e9..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/clock.h +++ /dev/null @@ -1,53 +0,0 @@ -/** - * \file - * - * \brief SAM Clock Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef SYSTEM_CLOCK_H_INCLUDED -#define SYSTEM_CLOCK_H_INCLUDED - -#include "compiler.h" -#include "gclk.h" -#include "clock_feature.h" - -#endif /* SYSTEM_CLOCK_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/clock_feature.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/clock_feature.h deleted file mode 100644 index be63c7c..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/clock_feature.h +++ /dev/null @@ -1,1492 +0,0 @@ -/** - * \file - * - * \brief SAM Clock Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef SYSTEM_CLOCK_FEATURE_H_INCLUDED -#define SYSTEM_CLOCK_FEATURE_H_INCLUDED - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \defgroup asfdoc_sam0_system_clock_group SAM System Clock Management Driver (SYSTEM CLOCK) - * - * This driver for Atmel® | SMART ARM®-based microcontrollers provides an interface for the configuration - * and management of the device's clocking related functions. This includes - * the various clock sources, bus clocks, and generic clocks within the device, - * with functions to manage the enabling, disabling, source selection, and - * prescaling of clocks to various internal peripherals. - * - * The following peripherals are used by this module: - * - * - GCLK (Generic Clock Management) - * - PM (Power Management) - * - SYSCTRL (Clock Source Control) - * - * The following devices can use this module: - * - Atmel | SMART SAM D20/D21 - * - Atmel | SMART SAM R21 - * - Atmel | SMART SAM D10/D11 - * - Atmel | SMART SAM DA0/DA1 - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_system_clock_prerequisites - * - \ref asfdoc_sam0_system_clock_module_overview - * - \ref asfdoc_sam0_system_clock_special_considerations - * - \ref asfdoc_sam0_system_clock_extra_info - * - \ref asfdoc_sam0_system_clock_examples - * - \ref asfdoc_sam0_system_clock_api_overview - * - * - * \section asfdoc_sam0_system_clock_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * - * \section asfdoc_sam0_system_clock_module_overview Module Overview - * The SAM devices contain a sophisticated clocking system, which is designed - * to give the maximum flexibility to the user application. This system allows - * a system designer to tune the performance and power consumption of the device - * in a dynamic manner, to achieve the best trade-off between the two for a - * particular application. - * - * This driver provides a set of functions for the configuration and management - * of the various clock related functionality within the device. - * - * \subsection asfdoc_sam0_system_clock_module_features Driver Feature Macro Definition - * - * - * - * - * - * - * - * - * - *
Driver Feature MacroSupported devices
FEATURE_SYSTEM_CLOCK_DPLLSAMD21, SAMR21, SAMD10, SAMD11, SAMDAx
- * \note The specific features are only available in the driver when the - * selected device supports those features. - * - * \subsection asfdoc_sam0_system_clock_module_overview_clock_sources Clock Sources - * The SAM devices have a number of master clock source modules, each of - * which being capable of producing a stabilized output frequency, which can then - * be fed into the various peripherals and modules within the device. - * - * Possible clock source modules include internal R/C oscillators, internal - * DFLL modules, as well as external crystal oscillators and/or clock inputs. - * - * \subsection asfdoc_sam0_system_clock_module_overview_cpu_clock CPU / Bus Clocks - * The CPU and AHB/APBx buses are clocked by the same physical clock source - * (referred in this module as the Main Clock), however the APBx buses may - * have additional prescaler division ratios set to give each peripheral bus a - * different clock speed. - * - * The general main clock tree for the CPU and associated buses is shown in - * \ref asfdoc_sam0_system_clock_module_clock_tree "the figure below". - * - * \anchor asfdoc_sam0_system_clock_module_clock_tree - * \dot - * digraph overview { - * rankdir=LR; - * clk_src [label="Clock Sources", shape=none, height=0]; - * node [label="CPU Bus" shape=ellipse] cpu_bus; - * node [label="AHB Bus" shape=ellipse] ahb_bus; - * node [label="APBA Bus" shape=ellipse] apb_a_bus; - * node [label="APBB Bus" shape=ellipse] apb_b_bus; - * node [label="APBC Bus" shape=ellipse] apb_c_bus; - * node [label="Main Bus\nPrescaler" shape=square] main_prescaler; - * node [label="APBA Bus\nPrescaler" shape=square] apb_a_prescaler; - * node [label="APBB Bus\nPrescaler" shape=square] apb_b_prescaler; - * node [label="APBC Bus\nPrescaler" shape=square] apb_c_prescaler; - * node [label="", shape=polygon, sides=4, distortion=0.6, orientation=90, style=filled, fillcolor=black, height=0.9, width=0.2] main_clock_mux; - * - * clk_src -> main_clock_mux; - * main_clock_mux -> main_prescaler; - * main_prescaler -> cpu_bus; - * main_prescaler -> ahb_bus; - * main_prescaler -> apb_a_prescaler; - * main_prescaler -> apb_b_prescaler; - * main_prescaler -> apb_c_prescaler; - * apb_a_prescaler -> apb_a_bus; - * apb_b_prescaler -> apb_b_bus; - * apb_c_prescaler -> apb_c_bus; - * } - * \enddot - * - * \subsection asfdoc_sam0_system_clock_module_overview_clock_masking Clock Masking - * To save power, the input clock to one or more peripherals on the AHB and APBx - * buses can be masked away - when masked, no clock is passed into the module. - * Disabling of clocks of unused modules will prevent all access to the masked - * module, but will reduce the overall device power consumption. - * - * \subsection asfdoc_sam0_system_clock_module_overview_gclk Generic Clocks - * Within the SAM devices there are a number of Generic Clocks; these are used to - * provide clocks to the various peripheral clock domains in the device in a - * standardized manner. One or more master source clocks can be selected as the - * input clock to a Generic Clock Generator, which can prescale down the input - * frequency to a slower rate for use in a peripheral. - * - * Additionally, a number of individually selectable Generic Clock Channels are - * provided, which multiplex and gate the various generator outputs for one or - * more peripherals within the device. This setup allows for a single common - * generator to feed one or more channels, which can then be enabled or disabled - * individually as required. - * - * \anchor asfdoc_sam0_system_clock_module_chain_overview - * \dot - * digraph overview { - * rankdir=LR; - * node [label="Clock\nSource a" shape=square] system_clock_source; - * node [label="Generator 1" shape=square] clock_gen; - * node [label="Channel x" shape=square] clock_chan0; - * node [label="Channel y" shape=square] clock_chan1; - * node [label="Peripheral x" shape=ellipse style=filled fillcolor=lightgray] peripheral0; - * node [label="Peripheral y" shape=ellipse style=filled fillcolor=lightgray] peripheral1; - * - * system_clock_source -> clock_gen; - * clock_gen -> clock_chan0; - * clock_chan0 -> peripheral0; - * clock_gen -> clock_chan1; - * clock_chan1 -> peripheral1; - * } - * \enddot - * - * \subsubsection asfdoc_sam0_system_clock_module_chain_example Clock Chain Example - * An example setup of a complete clock chain within the device is shown in - * \ref asfdoc_sam0_system_clock_module_chain_example_fig "the figure below". - * - * \anchor asfdoc_sam0_system_clock_module_chain_example_fig - * \dot - * digraph overview { - * rankdir=LR; - * node [label="External\nOscillator" shape=square] system_clock_source0; - * node [label="Generator 0" shape=square] clock_gen0; - * node [label="Channel x" shape=square] clock_chan0; - * node [label="Core CPU" shape=ellipse style=filled fillcolor=lightgray] peripheral0; - * - * system_clock_source0 -> clock_gen0; - * clock_gen0 -> clock_chan0; - * clock_chan0 -> peripheral0; - * node [label="8MHz R/C\nOscillator (OSC8M)" shape=square fillcolor=white] system_clock_source1; - * node [label="Generator 1" shape=square] clock_gen1; - * node [label="Channel y" shape=square] clock_chan1; - * node [label="Channel z" shape=square] clock_chan2; - * node [label="SERCOM\nModule" shape=ellipse style=filled fillcolor=lightgray] peripheral1; - * node [label="Timer\nModule" shape=ellipse style=filled fillcolor=lightgray] peripheral2; - * - * system_clock_source1 -> clock_gen1; - * clock_gen1 -> clock_chan1; - * clock_gen1 -> clock_chan2; - * clock_chan1 -> peripheral1; - * clock_chan2 -> peripheral2; - * } - * \enddot - * - * \subsubsection asfdoc_sam0_system_clock_module_overview_gclk_generators Generic Clock Generators - * Each Generic Clock generator within the device can source its input clock - * from one of the provided Source Clocks, and prescale the output for one or - * more Generic Clock Channels in a one-to-many relationship. The generators - * thus allow for several clocks to be generated of different frequencies, - * power usages, and accuracies, which can be turned on and off individually to - * disable the clocks to multiple peripherals as a group. - * - * \subsubsection asfdoc_sam0_system_clock_module_overview_gclk_channels Generic Clock Channels - * To connect a Generic Clock Generator to a peripheral within the - * device, a Generic Clock Channel is used. Each peripheral or - * peripheral group has an associated Generic Clock Channel, which serves as the - * clock input for the peripheral(s). To supply a clock to the peripheral - * module(s), the associated channel must be connected to a running Generic - * Clock Generator and the channel enabled. - * - * \section asfdoc_sam0_system_clock_special_considerations Special Considerations - * - * There are no special considerations for this module. - * - * - * \section asfdoc_sam0_system_clock_extra_info Extra Information - * - * For extra information, see \ref asfdoc_sam0_system_clock_extra. This includes: - * - \ref asfdoc_sam0_system_clock_extra_acronyms - * - \ref asfdoc_sam0_system_clock_extra_dependencies - * - \ref asfdoc_sam0_system_clock_extra_errata - * - \ref asfdoc_sam0_system_clock_extra_history - * - * - * \section asfdoc_sam0_system_clock_examples Examples - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_system_clock_exqsg. - * - * - * \section asfdoc_sam0_system_clock_api_overview API Overview - * @{ - */ - -#include "compiler.h" -#include "gclk.h" - -/** - * \name Driver Feature Definition - * Define system clock features set according to different device family. - * @{ - */ -#if (SAMD21) || (SAMR21) || (SAMD11) || (SAMD10) || (SAMDA1) || defined(__DOXYGEN__) -/** Digital Phase Locked Loop (DPLL) feature support. */ -# define FEATURE_SYSTEM_CLOCK_DPLL -#endif -/*@}*/ - -/** - * \brief Available start-up times for the XOSC32K. - * - * Available external 32KHz oscillator start-up times, as a number of external - * clock cycles. - */ -enum system_xosc32k_startup { - /** Wait zero clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_0, - /** Wait 32 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_32, - /** Wait 2048 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_2048, - /** Wait 4096 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_4096, - /** Wait 16384 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_16384, - /** Wait 32768 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_32768, - /** Wait 65536 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_65536, - /** Wait 131072 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_131072, -}; - -/** - * \brief Available start-up times for the XOSC. - * - * Available external oscillator start-up times, as a number of external clock - * cycles. - */ -enum system_xosc_startup { - /** Wait one clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_1, - /** Wait two clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_2, - /** Wait four clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_4, - /** Wait eight clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_8, - /** Wait 16 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_16, - /** Wait 32 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_32, - /** Wait 64 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_64, - /** Wait 128 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_128, - /** Wait 256 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_256, - /** Wait 512 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_512, - /** Wait 1024 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_1024, - /** Wait 2048 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_2048, - /** Wait 4096 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_4096, - /** Wait 8192 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_8192, - /** Wait 16384 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_16384, - /** Wait 32768 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_32768, -}; - -/** - * \brief Available start-up times for the OSC32K. - * - * Available internal 32KHz oscillator start-up times, as a number of internal - * OSC32K clock cycles. - */ -enum system_osc32k_startup { - /** Wait three clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_3, - /** Wait four clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_4, - /** Wait six clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_6, - /** Wait ten clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_10, - /** Wait 18 clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_18, - /** Wait 34 clock cycles until the clock source is considered stable */ - SYSTEM_OSC32K_STARTUP_34, - /** Wait 66 clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_66, - /** Wait 130 clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_130, -}; - -/** - * \brief Division prescalers for the internal 8MHz system clock. - * - * Available prescalers for the internal 8MHz (nominal) system clock. - */ -enum system_osc8m_div { - /** Do not divide the 8MHz RC oscillator output. */ - SYSTEM_OSC8M_DIV_1, - /** Divide the 8MHz RC oscillator output by two. */ - SYSTEM_OSC8M_DIV_2, - /** Divide the 8MHz RC oscillator output by four. */ - SYSTEM_OSC8M_DIV_4, - /** Divide the 8MHz RC oscillator output by eight. */ - SYSTEM_OSC8M_DIV_8, -}; - -/** - * \brief Frequency range for the internal 8MHz RC oscillator. - * - * Internal 8MHz RC oscillator frequency range setting - */ -enum system_osc8m_frequency_range { - /** Frequency range 4MHz to 6MHz. */ - SYSTEM_OSC8M_FREQUENCY_RANGE_4_TO_6, - /** Frequency range 6MHz to 8MHz. */ - SYSTEM_OSC8M_FREQUENCY_RANGE_6_TO_8, - /** Frequency range 8MHz to 11MHz. */ - SYSTEM_OSC8M_FREQUENCY_RANGE_8_TO_11, - /** Frequency range 11MHz to 15MHz. */ - SYSTEM_OSC8M_FREQUENCY_RANGE_11_TO_15, -}; - -/** - * \brief Main CPU and APB/AHB bus clock source prescaler values. - * - * Available division ratios for the CPU and APB/AHB bus clocks. - */ -enum system_main_clock_div { - /** Divide Main clock by one. */ - SYSTEM_MAIN_CLOCK_DIV_1, - /** Divide Main clock by two. */ - SYSTEM_MAIN_CLOCK_DIV_2, - /** Divide Main clock by four. */ - SYSTEM_MAIN_CLOCK_DIV_4, - /** Divide Main clock by eight. */ - SYSTEM_MAIN_CLOCK_DIV_8, - /** Divide Main clock by 16. */ - SYSTEM_MAIN_CLOCK_DIV_16, - /** Divide Main clock by 32. */ - SYSTEM_MAIN_CLOCK_DIV_32, - /** Divide Main clock by 64. */ - SYSTEM_MAIN_CLOCK_DIV_64, - /** Divide Main clock by 128. */ - SYSTEM_MAIN_CLOCK_DIV_128, -}; - -/** - * \brief External clock source types. - * - * Available external clock source types. - */ -enum system_clock_external { - /** The external clock source is a crystal oscillator. */ - SYSTEM_CLOCK_EXTERNAL_CRYSTAL, - /** The connected clock source is an external logic level clock signal. */ - SYSTEM_CLOCK_EXTERNAL_CLOCK, -}; - -/** - * \brief Operating modes of the DFLL clock source. - * - * Available operating modes of the DFLL clock source module. - */ -enum system_clock_dfll_loop_mode { - /** The DFLL is operating in open loop mode with no feedback. */ - SYSTEM_CLOCK_DFLL_LOOP_MODE_OPEN, - /** The DFLL is operating in closed loop mode with frequency feedback from - * a low frequency reference clock. - */ - SYSTEM_CLOCK_DFLL_LOOP_MODE_CLOSED = SYSCTRL_DFLLCTRL_MODE, - -#ifdef SYSCTRL_DFLLCTRL_USBCRM - /** The DFLL is operating in USB recovery mode with frequency feedback - * from USB SOF. - */ - SYSTEM_CLOCK_DFLL_LOOP_MODE_USB_RECOVERY = SYSCTRL_DFLLCTRL_USBCRM, -#endif -}; - -/** - * \brief Locking behavior for the DFLL during device wake-up. - * - * DFLL lock behavior modes on device wake-up from sleep. - */ -enum system_clock_dfll_wakeup_lock { - /** Keep DFLL lock when the device wakes from sleep. */ - SYSTEM_CLOCK_DFLL_WAKEUP_LOCK_KEEP, - /** Lose DFLL lock when the devices wakes from sleep. */ - SYSTEM_CLOCK_DFLL_WAKEUP_LOCK_LOSE = SYSCTRL_DFLLCTRL_LLAW, -}; - -/** - * \brief Fine tracking behavior for the DFLL once a lock has been acquired. - * - * DFLL fine tracking behavior modes after a lock has been acquired. - */ -enum system_clock_dfll_stable_tracking { - /** Keep tracking after the DFLL has gotten a fine lock. */ - SYSTEM_CLOCK_DFLL_STABLE_TRACKING_TRACK_AFTER_LOCK, - /** Stop tracking after the DFLL has gotten a fine lock. */ - SYSTEM_CLOCK_DFLL_STABLE_TRACKING_FIX_AFTER_LOCK = SYSCTRL_DFLLCTRL_STABLE, -}; - -/** - * \brief Chill-cycle behavior of the DFLL module. - * - * DFLL chill-cycle behavior modes of the DFLL module. A chill cycle is a period - * of time when the DFLL output frequency is not measured by the unit, to allow - * the output to stabilize after a change in the input clock source. - */ -enum system_clock_dfll_chill_cycle { - /** Enable a chill cycle, where the DFLL output frequency is not measured. */ - SYSTEM_CLOCK_DFLL_CHILL_CYCLE_ENABLE, - /** Disable a chill cycle, where the DFLL output frequency is not measured. */ - SYSTEM_CLOCK_DFLL_CHILL_CYCLE_DISABLE = SYSCTRL_DFLLCTRL_CCDIS, -}; - -/** - * \brief QuickLock settings for the DFLL module. - * - * DFLL QuickLock settings for the DFLL module, to allow for a faster lock of - * the DFLL output frequency at the expense of accuracy. - */ -enum system_clock_dfll_quick_lock { - /** Enable the QuickLock feature for looser lock requirements on the DFLL. */ - SYSTEM_CLOCK_DFLL_QUICK_LOCK_ENABLE, - /** Disable the QuickLock feature for strict lock requirements on the DFLL. */ - SYSTEM_CLOCK_DFLL_QUICK_LOCK_DISABLE = SYSCTRL_DFLLCTRL_QLDIS, -}; - -/** - * \brief Available clock sources in the system. - * - * Clock sources available to the GCLK generators. - */ -enum system_clock_source { - /** Internal 8MHz RC oscillator. */ - SYSTEM_CLOCK_SOURCE_OSC8M = GCLK_SOURCE_OSC8M, - /** Internal 32KHz RC oscillator. */ - SYSTEM_CLOCK_SOURCE_OSC32K = GCLK_SOURCE_OSC32K, - /** External oscillator. */ - SYSTEM_CLOCK_SOURCE_XOSC = GCLK_SOURCE_XOSC , - /** External 32KHz oscillator. */ - SYSTEM_CLOCK_SOURCE_XOSC32K = GCLK_SOURCE_XOSC32K, - /** Digital Frequency Locked Loop (DFLL). */ - SYSTEM_CLOCK_SOURCE_DFLL = GCLK_SOURCE_DFLL48M, - /** Internal Ultra Low Power 32KHz oscillator. */ - SYSTEM_CLOCK_SOURCE_ULP32K = GCLK_SOURCE_OSCULP32K, - /** Generator input pad. */ - SYSTEM_CLOCK_SOURCE_GCLKIN = GCLK_SOURCE_GCLKIN, - /** Generic clock generator one output. */ - SYSTEM_CLOCK_SOURCE_GCLKGEN1 = GCLK_SOURCE_GCLKGEN1, -#ifdef FEATURE_SYSTEM_CLOCK_DPLL - /** Digital Phase Locked Loop (DPLL). - * Check \c FEATURE_SYSTEM_CLOCK_DPLL for which device support it. - */ - SYSTEM_CLOCK_SOURCE_DPLL = GCLK_SOURCE_FDPLL, -#endif -}; - -/** - * \brief List of APB peripheral buses. - * - * Available bus clock domains on the APB bus. - */ -enum system_clock_apb_bus { - /** Peripheral bus A on the APB bus. */ - SYSTEM_CLOCK_APB_APBA, - /** Peripheral bus B on the APB bus. */ - SYSTEM_CLOCK_APB_APBB, - /** Peripheral bus C on the APB bus. */ - SYSTEM_CLOCK_APB_APBC, -}; - -/** - * \brief Configuration structure for XOSC. - * - * External oscillator clock configuration structure. - */ -struct system_clock_source_xosc_config { - /** External clock type. */ - enum system_clock_external external_clock; - /** Crystal oscillator start-up time. */ - enum system_xosc_startup startup_time; - /** Enable automatic amplitude gain control. */ - bool auto_gain_control; - /** External clock/crystal frequency. */ - uint32_t frequency; - /** Keep the XOSC enabled in standby sleep mode. */ - bool run_in_standby; - /** Run On Demand. If this is set the XOSC won't run - * until requested by a peripheral. */ - bool on_demand; -}; - -/** - * \brief Configuration structure for XOSC32K. - * - * External 32KHz oscillator clock configuration structure. - */ -struct system_clock_source_xosc32k_config { - /** External clock type. */ - enum system_clock_external external_clock; - /** Crystal oscillator start-up time. */ - enum system_xosc32k_startup startup_time; - /** Enable automatic amplitude control. */ - bool auto_gain_control; - /** Enable 1KHz output. */ - bool enable_1khz_output; - /** Enable 32KHz output. */ - bool enable_32khz_output; - /** External clock/crystal frequency. */ - uint32_t frequency; - /** Keep the XOSC32K enabled in standby sleep mode. */ - bool run_in_standby; - /** Run On Demand. If this is set the XOSC32K won't run - * until requested by a peripheral. */ - bool on_demand; - /** Lock configuration after it has been written, - * a device reset will release the lock. */ - bool write_once; -}; - -/** - * \brief Configuration structure for OSC8M. - * - * Internal 8MHz (nominal) oscillator configuration structure. - */ -struct system_clock_source_osc8m_config { - /** Internal 8MHz RC oscillator prescaler. */ - enum system_osc8m_div prescaler; - /** Keep the OSC8M enabled in standby sleep mode. */ - bool run_in_standby; - /** Run On Demand. If this is set the OSC8M won't run - * until requested by a peripheral. */ - bool on_demand; -}; - -/** - * \brief Configuration structure for OSC32K. - * - * Internal 32KHz (nominal) oscillator configuration structure. - */ -struct system_clock_source_osc32k_config { - /** Startup time. */ - enum system_osc32k_startup startup_time; - /** Enable 1KHz output. */ - bool enable_1khz_output; - /** Enable 32KHz output. */ - bool enable_32khz_output; - /** Keep the OSC32K enabled in standby sleep mode. */ - bool run_in_standby; - /** Run On Demand. If this is set the OSC32K won't run - * until requested by a peripheral. */ - bool on_demand; - /** Lock configuration after it has been written, - * a device reset will release the lock. */ - bool write_once; -}; - -/** - * \brief Configuration structure for DFLL. - * - * DFLL oscillator configuration structure. - */ -struct system_clock_source_dfll_config { - /** Loop mode. */ - enum system_clock_dfll_loop_mode loop_mode; - /** Run On Demand. If this is set the DFLL won't run - * until requested by a peripheral. */ - bool on_demand; - /** Enable Quick Lock. */ - enum system_clock_dfll_quick_lock quick_lock; - /** Enable Chill Cycle. */ - enum system_clock_dfll_chill_cycle chill_cycle; - /** DFLL lock state on wakeup. */ - enum system_clock_dfll_wakeup_lock wakeup_lock; - /** DFLL tracking after fine lock. */ - enum system_clock_dfll_stable_tracking stable_tracking; - /** Coarse calibration value (Open loop mode). */ - uint8_t coarse_value; - /** Fine calibration value (Open loop mode). */ - uint16_t fine_value; - /** Coarse adjustment maximum step size (Closed loop mode). */ - uint8_t coarse_max_step; - /** Fine adjustment maximum step size (Closed loop mode). */ - uint16_t fine_max_step; - /** DFLL multiply factor (Closed loop mode. */ - uint16_t multiply_factor; -}; - -/** - * \name External Oscillator Management - * @{ - */ - -/** - * \brief Retrieve the default configuration for XOSC. - * - * Fills a configuration structure with the default configuration for an - * external oscillator module: - * - External Crystal - * - Start-up time of 16384 external clock cycles - * - Automatic crystal gain control mode enabled - * - Frequency of 12MHz - * - Don't run in STANDBY sleep mode - * - Run only when requested by peripheral (on demand) - * - * \param[out] config Configuration structure to fill with default values - */ -static inline void system_clock_source_xosc_get_config_defaults( - struct system_clock_source_xosc_config *const config) -{ - Assert(config); - - config->external_clock = SYSTEM_CLOCK_EXTERNAL_CRYSTAL; - config->startup_time = SYSTEM_XOSC_STARTUP_16384; - config->auto_gain_control = true; - config->frequency = 12000000UL; - config->run_in_standby = false; - config->on_demand = true; -} - -void system_clock_source_xosc_set_config( - struct system_clock_source_xosc_config *const config); - -/** - * @} - */ - - -/** - * \name External 32KHz Oscillator Management - * @{ - */ - -/** - * \brief Retrieve the default configuration for XOSC32K. - * - * Fills a configuration structure with the default configuration for an - * external 32KHz oscillator module: - * - External Crystal - * - Start-up time of 16384 external clock cycles - * - Automatic crystal gain control mode disabled - * - Frequency of 32.768KHz - * - 1KHz clock output disabled - * - 32KHz clock output enabled - * - Don't run in STANDBY sleep mode - * - Run only when requested by peripheral (on demand) - * - Don't lock registers after configuration has been written - * - * \param[out] config Configuration structure to fill with default values - */ -static inline void system_clock_source_xosc32k_get_config_defaults( - struct system_clock_source_xosc32k_config *const config) -{ - Assert(config); - - config->external_clock = SYSTEM_CLOCK_EXTERNAL_CRYSTAL; - config->startup_time = SYSTEM_XOSC32K_STARTUP_16384; - config->auto_gain_control = false; - config->frequency = 32768UL; - config->enable_1khz_output = false; - config->enable_32khz_output = true; - config->run_in_standby = false; - config->on_demand = true; - config->write_once = false; -} - -void system_clock_source_xosc32k_set_config( - struct system_clock_source_xosc32k_config *const config); -/** - * @} - */ - - -/** - * \name Internal 32KHz Oscillator Management - * @{ - */ - -/** - * \brief Retrieve the default configuration for OSC32K. - * - * Fills a configuration structure with the default configuration for an - * internal 32KHz oscillator module: - * - 1KHz clock output enabled - * - 32KHz clock output enabled - * - Don't run in STANDBY sleep mode - * - Run only when requested by peripheral (on demand) - * - Set startup time to 130 cycles - * - Don't lock registers after configuration has been written - * - * \param[out] config Configuration structure to fill with default values - */ -static inline void system_clock_source_osc32k_get_config_defaults( - struct system_clock_source_osc32k_config *const config) -{ - Assert(config); - - config->enable_1khz_output = true; - config->enable_32khz_output = true; - config->run_in_standby = false; - config->on_demand = true; - config->startup_time = SYSTEM_OSC32K_STARTUP_130; - config->write_once = false; -} - -void system_clock_source_osc32k_set_config( - struct system_clock_source_osc32k_config *const config); - -/** - * @} - */ - - -/** - * \name Internal 8MHz Oscillator Management - * @{ - */ - -/** - * \brief Retrieve the default configuration for OSC8M. - * - * Fills a configuration structure with the default configuration for an - * internal 8MHz (nominal) oscillator module: - * - Clock output frequency divided by a factor of eight - * - Don't run in STANDBY sleep mode - * - Run only when requested by peripheral (on demand) - * - * \param[out] config Configuration structure to fill with default values - */ -static inline void system_clock_source_osc8m_get_config_defaults( - struct system_clock_source_osc8m_config *const config) -{ - Assert(config); - - config->prescaler = SYSTEM_OSC8M_DIV_8; - config->run_in_standby = false; - config->on_demand = true; -} - -void system_clock_source_osc8m_set_config( - struct system_clock_source_osc8m_config *const config); - -/** - * @} - */ - - -/** - * \name Internal DFLL Management - * @{ - */ - -/** - * \brief Retrieve the default configuration for DFLL. - * - * Fills a configuration structure with the default configuration for a - * DFLL oscillator module: - * - Open loop mode - * - QuickLock mode enabled - * - Chill cycle enabled - * - Output frequency lock maintained during device wake-up - * - Continuous tracking of the output frequency - * - Default tracking values at the mid-points for both coarse and fine - * tracking parameters - * - Don't run in STANDBY sleep mode - * - Run only when requested by peripheral (on demand) - * - * \param[out] config Configuration structure to fill with default values - */ -static inline void system_clock_source_dfll_get_config_defaults( - struct system_clock_source_dfll_config *const config) -{ - Assert(config); - - config->loop_mode = SYSTEM_CLOCK_DFLL_LOOP_MODE_OPEN; - config->quick_lock = SYSTEM_CLOCK_DFLL_QUICK_LOCK_ENABLE; - config->chill_cycle = SYSTEM_CLOCK_DFLL_CHILL_CYCLE_ENABLE; - config->wakeup_lock = SYSTEM_CLOCK_DFLL_WAKEUP_LOCK_KEEP; - config->stable_tracking = SYSTEM_CLOCK_DFLL_STABLE_TRACKING_TRACK_AFTER_LOCK; - config->on_demand = true; - - /* Open loop mode calibration value */ - config->coarse_value = 0x1f / 4; /* Midpoint */ - config->fine_value = 0xff / 4; /* Midpoint */ - - /* Closed loop mode */ - config->coarse_max_step = 1; - config->fine_max_step = 1; - config->multiply_factor = 6; /* Multiply 8MHz by 6 to get 48MHz */ -} - -void system_clock_source_dfll_set_config( - struct system_clock_source_dfll_config *const config); - -/** - * @} - */ - -/** - * \name Clock Source Management - * @{ - */ -enum status_code system_clock_source_write_calibration( - const enum system_clock_source system_clock_source, - const uint16_t calibration_value, - const uint8_t freq_range); - -enum status_code system_clock_source_enable( - const enum system_clock_source system_clock_source); - -enum status_code system_clock_source_disable( - const enum system_clock_source clk_source); - -bool system_clock_source_is_ready( - const enum system_clock_source clk_source); - -uint32_t system_clock_source_get_hz( - const enum system_clock_source clk_source); - -/** - * @} - */ - -/** - * \name Main Clock Management - * @{ - */ - -/** - * \brief Set main CPU clock divider. - * - * Sets the clock divider used on the main clock to provide the CPU clock. - * - * \param[in] divider CPU clock divider to set - */ -static inline void system_cpu_clock_set_divider( - const enum system_main_clock_div divider) -{ - Assert(((uint32_t)divider & PM_CPUSEL_CPUDIV_Msk) == divider); - PM->CPUSEL.reg = (uint32_t)divider; -} - -/** - * \brief Retrieves the current frequency of the CPU core. - * - * Retrieves the operating frequency of the CPU core, obtained from the main - * generic clock and the set CPU bus divider. - * - * \return Current CPU frequency in Hz. - */ -static inline uint32_t system_cpu_clock_get_hz(void) -{ - return (system_gclk_gen_get_hz(GCLK_GENERATOR_0) >> PM->CPUSEL.reg); -} - -/** - * \brief Set APBx clock divider. - * - * Set the clock divider used on the main clock to provide the clock for the - * given APBx bus. - * - * \param[in] divider APBx bus divider to set - * \param[in] bus APBx bus to set divider - * - * \returns Status of the clock division change operation. - * - * \retval STATUS_ERR_INVALID_ARG Invalid bus ID was given - * \retval STATUS_OK The APBx clock was set successfully - */ -static inline enum status_code system_apb_clock_set_divider( - const enum system_clock_apb_bus bus, - const enum system_main_clock_div divider) -{ - switch (bus) { - case SYSTEM_CLOCK_APB_APBA: - PM->APBASEL.reg = (uint32_t)divider; - break; - case SYSTEM_CLOCK_APB_APBB: - PM->APBBSEL.reg = (uint32_t)divider; - break; - case SYSTEM_CLOCK_APB_APBC: - PM->APBCSEL.reg = (uint32_t)divider; - break; - default: - Assert(false); - return STATUS_ERR_INVALID_ARG; - } - - return STATUS_OK; -} - -/** - * \brief Retrieves the current frequency of a ABPx. - * - * Retrieves the operating frequency of an APBx bus, obtained from the main - * generic clock and the set APBx bus divider. - * - * \return Current APBx bus frequency in Hz. - */ -static inline uint32_t system_apb_clock_get_hz( - const enum system_clock_apb_bus bus) -{ - uint16_t bus_divider = 0; - - switch (bus) { - case SYSTEM_CLOCK_APB_APBA: - bus_divider = PM->APBASEL.reg; - break; - case SYSTEM_CLOCK_APB_APBB: - bus_divider = PM->APBBSEL.reg; - break; - case SYSTEM_CLOCK_APB_APBC: - bus_divider = PM->APBCSEL.reg; - break; - default: - Assert(false); - return 0; - } - - return (system_gclk_gen_get_hz(GCLK_GENERATOR_0) >> bus_divider); -} - - -/** - * @} - */ - -/** - * \name Bus Clock Masking - * @{ - */ - -/** - * \brief Set bits in the clock mask for the AHB bus. - * - * This function will set bits in the clock mask for the AHB bus. - * Any bits set to 1 will enable that clock, 0 bits in the mask - * will be ignored. - * - * \param[in] ahb_mask AHB clock mask to enable - */ -static inline void system_ahb_clock_set_mask( - const uint32_t ahb_mask) -{ - PM->AHBMASK.reg |= ahb_mask; -} - -/** - * \brief Clear bits in the clock mask for the AHB bus. - * - * This function will clear bits in the clock mask for the AHB bus. - * Any bits set to 1 will disable that clock, 0 bits in the mask - * will be ignored. - * - * \param[in] ahb_mask AHB clock mask to disable - */ -static inline void system_ahb_clock_clear_mask( - const uint32_t ahb_mask) -{ - PM->AHBMASK.reg &= ~ahb_mask; -} - -/** - * \brief Set bits in the clock mask for an APBx bus. - * - * This function will set bits in the clock mask for an APBx bus. - * Any bits set to 1 will enable the corresponding module clock, zero bits in - * the mask will be ignored. - * - * \param[in] mask APBx clock mask, a \c SYSTEM_CLOCK_APB_APBx constant from - * the device header files - * \param[in] bus Bus to set clock mask bits for, a mask of \c PM_APBxMASK_* - * constants from the device header files - * - * \returns Status indicating the result of the clock mask change operation. - * - * \retval STATUS_ERR_INVALID_ARG Invalid bus given - * \retval STATUS_OK The clock mask was set successfully - */ -static inline enum status_code system_apb_clock_set_mask( - const enum system_clock_apb_bus bus, - const uint32_t mask) -{ - switch (bus) { - case SYSTEM_CLOCK_APB_APBA: - PM->APBAMASK.reg |= mask; - break; - - case SYSTEM_CLOCK_APB_APBB: - PM->APBBMASK.reg |= mask; - break; - - case SYSTEM_CLOCK_APB_APBC: - PM->APBCMASK.reg |= mask; - break; - - default: - Assert(false); - return STATUS_ERR_INVALID_ARG; - - } - - return STATUS_OK; -} - -/** - * \brief Clear bits in the clock mask for an APBx bus. - * - * This function will clear bits in the clock mask for an APBx bus. - * Any bits set to 1 will disable the corresponding module clock, zero bits in - * the mask will be ignored. - * - * \param[in] mask APBx clock mask, a \c SYSTEM_CLOCK_APB_APBx constant from - * the device header files - * \param[in] bus Bus to clear clock mask bits - * - * \returns Status indicating the result of the clock mask change operation. - * - * \retval STATUS_ERR_INVALID_ARG Invalid bus ID was given - * \retval STATUS_OK The clock mask was changed successfully - */ -static inline enum status_code system_apb_clock_clear_mask( - const enum system_clock_apb_bus bus, - const uint32_t mask) -{ - switch (bus) { - case SYSTEM_CLOCK_APB_APBA: - PM->APBAMASK.reg &= ~mask; - break; - - case SYSTEM_CLOCK_APB_APBB: - PM->APBBMASK.reg &= ~mask; - break; - - case SYSTEM_CLOCK_APB_APBC: - PM->APBCMASK.reg &= ~mask; - break; - - default: - Assert(false); - return STATUS_ERR_INVALID_ARG; - } - - return STATUS_OK; -} - -/** - * @} - */ - -#ifdef FEATURE_SYSTEM_CLOCK_DPLL -/** - * \brief Reference clock source of the DPLL module. - */ -enum system_clock_source_dpll_reference_clock { - /** Select XOSC32K as clock reference. */ - SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_XOSC32K, - /** Select XOSC as clock reference. */ - SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_XOSC, - /** Select GCLK as clock reference. */ - SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_GCLK, -}; - -/** - * \brief Lock time-out value of the DPLL module. - */ -enum system_clock_source_dpll_lock_time { - /** Set no time-out as default. */ - SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_DEFAULT, - /** Set time-out if no lock within 8ms. */ - SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_8MS = 0x04, - /** Set time-out if no lock within 9ms. */ - SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_9MS, - /** Set time-out if no lock within 10ms. */ - SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_10MS, - /** Set time-out if no lock within 11ms. */ - SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_11MS, -}; - -/** - * \brief Filter type of the DPLL module. - */ -enum system_clock_source_dpll_filter { - /** Default filter mode. */ - SYSTEM_CLOCK_SOURCE_DPLL_FILTER_DEFAULT, - /** Low bandwidth filter. */ - SYSTEM_CLOCK_SOURCE_DPLL_FILTER_LOW_BANDWIDTH_FILTER, - /** High bandwidth filter. */ - SYSTEM_CLOCK_SOURCE_DPLL_FILTER_HIGH_BANDWIDTH_FILTER, - /** High damping filter. */ - SYSTEM_CLOCK_SOURCE_DPLL_FILTER_HIGH_DAMPING_FILTER, -}; - -/** - * \brief Configuration structure for DPLL. - * - * DPLL oscillator configuration structure. - */ -struct system_clock_source_dpll_config { - /** Run On Demand. If this is set the DPLL won't run - * until requested by a peripheral. */ - bool on_demand; - /** Keep the DPLL enabled in standby sleep mode. */ - bool run_in_standby; - /** Bypass lock signal. */ - bool lock_bypass; - /** Wake up fast. If this is set DPLL output clock is enabled after - * the startup time. */ - bool wake_up_fast; - /** Enable low power mode. */ - bool low_power_enable; - - /** Output frequency of the clock. */ - uint32_t output_frequency; - /** Reference frequency of the clock. */ - uint32_t reference_frequency; - /** Devider of reference clock. */ - uint16_t reference_divider; - - /** Filter type of the DPLL module. */ - enum system_clock_source_dpll_filter filter; - /** Lock time-out value of the DPLL module. */ - enum system_clock_source_dpll_lock_time lock_time; - /** Reference clock source of the DPLL module. */ - enum system_clock_source_dpll_reference_clock reference_clock; -}; - -/** - * \name Internal DPLL Management - * @{ - */ - -/** - * \brief Retrieve the default configuration for DPLL. - * - * Fills a configuration structure with the default configuration for a - * DPLL oscillator module: - * - Run only when requested by peripheral (on demand) - * - Don't run in STANDBY sleep mode - * - Lock bypass disabled - * - Fast wake up disabled - * - Low power mode disabled - * - Output frequency is 48MHz - * - Reference clock frequency is 32768Hz - * - Not divide reference clock - * - Select REF0 as reference clock - * - Set lock time to default mode - * - Use default filter - * - * \param[out] config Configuration structure to fill with default values - */ -static inline void system_clock_source_dpll_get_config_defaults( - struct system_clock_source_dpll_config *const config) -{ - config->on_demand = true; - config->run_in_standby = false; - config->lock_bypass = false; - config->wake_up_fast = false; - config->low_power_enable = false; - - config->output_frequency = 48000000; - config->reference_frequency = 32768; - config->reference_divider = 1; - config->reference_clock = SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_XOSC32K; - - config->lock_time = SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_DEFAULT; - config->filter = SYSTEM_CLOCK_SOURCE_DPLL_FILTER_DEFAULT; -}; - -void system_clock_source_dpll_set_config( - struct system_clock_source_dpll_config *const config); - -/* @} */ -#endif - -/** - * \name System Clock Initialization - * @{ - */ - -void system_clock_init(void); - -/** - * @} - */ - -/** - * \name System Flash Wait States - * @{ - */ - -/** - * \brief Set flash controller wait states. - * - * Will set the number of wait states that are used by the onboard - * flash memory. The number of wait states depend on both device - * supply voltage and CPU speed. The required number of wait states - * can be found in the electrical characteristics of the device. - * - * \param[in] wait_states Number of wait states to use for internal flash - */ -static inline void system_flash_set_waitstates(uint8_t wait_states) -{ - Assert(NVMCTRL_CTRLB_RWS((uint32_t)wait_states) == - ((uint32_t)wait_states << NVMCTRL_CTRLB_RWS_Pos)); - - NVMCTRL->CTRLB.bit.RWS = wait_states; -} -/** - * @} - */ - -/** - * @} - */ - -/** - * \page asfdoc_sam0_system_clock_extra Extra Information for SYSTEM CLOCK Driver - * - * \section asfdoc_sam0_system_clock_extra_acronyms Acronyms - * Below is a table listing the acronyms used in this module, along with their - * intended meanings. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
AcronymDescription
DFLLDigital Frequency Locked Loop
MUXMultiplexer
OSC32KInternal 32KHz Oscillator
OSC8MInternal 8MHz Oscillator
PLLPhase Locked Loop
OSCOscillator
XOSCExternal Oscillator
XOSC32KExternal 32KHz Oscillator
AHBAdvanced High-performance Bus
APBAdvanced Peripheral Bus
DPLLDigital Phase Locked Loop
- * - * - * \section asfdoc_sam0_system_clock_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - None - * - * - * \section asfdoc_sam0_system_clock_extra_errata Errata - * - * - This driver implements experimental workaround for errata 9905 - * - * "The DFLL clock must be requested before being configured otherwise a - * write access to a DFLL register can freeze the device." - * This driver will enable and configure the DFLL before the ONDEMAND bit is set. - * - * - * \section asfdoc_sam0_system_clock_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Changelog
- * \li Corrected OSC32K startup time definitions - * \li Support locking of OSC32K and XOSC32K config register (default: false) - * \li Added DPLL support, functions added: - * \c system_clock_source_dpll_get_config_defaults() and - * \c system_clock_source_dpll_set_config() - * \li Moved gclk channel locking feature out of the config struct - * functions added: - * \c system_gclk_chan_lock(), - * \c system_gclk_chan_is_locked() - * \c system_gclk_chan_is_enabled() and - * \c system_gclk_gen_is_enabled() - *
Fixed \c system_gclk_chan_disable() deadlocking if a channel is enabled - * and configured to a failed/not running clock generator
- * \li Changed default value for CONF_CLOCK_DFLL_ON_DEMAND from \c true to \c false - * \li Fixed system_flash_set_waitstates() failing with an assertion - * if an odd number of wait states provided - *
- * \li Updated dfll configuration function to implement workaround for - * errata 9905 in the DFLL module - * \li Updated \c system_clock_init() to reset interrupt flags before - * they are used - * \li Fixed \c system_clock_source_get_hz() to return correcy DFLL - * frequency number - *
\li Fixed \c system_clock_source_is_ready not returning the correct - * state for \c SYSTEM_CLOCK_SOURCE_OSC8M - * \li Renamed the various \c system_clock_source_*_get_default_config() - * functions to \c system_clock_source_*_get_config_defaults() to - * match the remainder of ASF - * \li Added OSC8M calibration constant loading from the device signature - * row when the oscillator is initialized - * \li Updated default configuration of the XOSC32 to disable Automatic - * Gain Control due to silicon errata - *
Initial Release
- */ - -/** - * \page asfdoc_sam0_system_clock_exqsg Examples for System Clock Driver - * - * This is a list of the available Quick Start guides (QSGs) and example - * applications for \ref asfdoc_sam0_system_clock_group. QSGs are simple - * examples with step-by-step instructions to configure and use this driver in - * a selection of use cases. Note that QSGs can be compiled as a standalone - * application or be added to the user application. - * - * - \subpage asfdoc_sam0_system_clock_basic_use_case - * - \subpage asfdoc_sam0_system_gclk_basic_use_case - * - * \page asfdoc_sam0_system_clock_document_revision_history Document Revision History - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Doc. Rev. - * Date - * Comments - *
E04/2015Added support for SAMDAx.
D12/2014Added support for SAMR21 and SAMD10/D11.
C01/2014Added support for SAMD21.
B06/2013Corrected documentation typos. Fixed missing steps in the Basic - * Use Case Quick Start Guide.
A06/2013Initial release
- */ - -#ifdef __cplusplus -} -#endif - -#endif /* SYSTEM_CLOCK_FEATURE_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/compiler.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/compiler.h deleted file mode 100644 index 2d95f97..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/compiler.h +++ /dev/null @@ -1,1157 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef UTILS_COMPILER_H_INCLUDED -#define UTILS_COMPILER_H_INCLUDED - -/** - * \defgroup group_sam0_utils Compiler abstraction layer and code utilities - * - * Compiler abstraction layer and code utilities for Cortex-M0+ based Atmel SAM devices. - * This module provides various abstraction layers and utilities to make code compatible between different compilers. - * - * @{ - */ - -#if (defined __ICCARM__) -# include -#endif - -#include -//#include -#include "status_codes.h" -#include "preprocessor/preprocessor.h" -#include - -#ifndef __ASSEMBLY__ - -#include -#include -#include -#include - -/** - * \def UNUSED - * \brief Marking \a v as a unused parameter or value. - */ -#define UNUSED(v) (void)(v) - -/** - * \def barrier - * \brief Memory barrier - */ -#ifdef __GNUC__ -# define barrier() asm volatile("" ::: "memory") -#else -# define barrier() asm ("") -#endif - -/** - * \brief Emit the compiler pragma \a arg. - * - * \param[in] arg The pragma directive as it would appear after \e \#pragma - * (i.e. not stringified). - */ -#define COMPILER_PRAGMA(arg) _Pragma(#arg) - -/** - * \def COMPILER_PACK_SET(alignment) - * \brief Set maximum alignment for subsequent struct and union definitions to \a alignment. - */ -#define COMPILER_PACK_SET(alignment) COMPILER_PRAGMA(pack(alignment)) - -/** - * \def COMPILER_PACK_RESET() - * \brief Set default alignment for subsequent struct and union definitions. - */ -#define COMPILER_PACK_RESET() COMPILER_PRAGMA(pack()) - - -/** - * \brief Set aligned boundary. - */ -#if (defined __GNUC__) || (defined __CC_ARM) -# define COMPILER_ALIGNED(a) __attribute__((__aligned__(a))) -#elif (defined __ICCARM__) -# define COMPILER_ALIGNED(a) COMPILER_PRAGMA(data_alignment = a) -#endif - -/** - * \brief Set word-aligned boundary. - */ -#if (defined __GNUC__) || defined(__CC_ARM) -#define COMPILER_WORD_ALIGNED __attribute__((__aligned__(4))) -#elif (defined __ICCARM__) -#define COMPILER_WORD_ALIGNED COMPILER_PRAGMA(data_alignment = 4) -#endif - -/** - * \def __always_inline - * \brief The function should always be inlined. - * - * This annotation instructs the compiler to ignore its inlining - * heuristics and inline the function no matter how big it thinks it - * becomes. - */ -#if defined(__CC_ARM) -# define __always_inline __forceinline -#elif (defined __GNUC__) -# define __always_inline __attribute__((__always_inline__)) -#elif (defined __ICCARM__) -# define __always_inline _Pragma("inline=forced") -#endif - -/** - * \def __no_inline - * \brief The function should never be inlined - * - * This annotation instructs the compiler to ignore its inlining - * heuristics and not inline the function no matter how small it thinks it - * becomes. - */ -#if defined(__CC_ARM) -# define __no_inline __attribute__((noinline)) -#elif (defined __GNUC__) -# define __no_inline __attribute__((noinline)) -#elif (defined __ICCARM__) -# define __no_inline _Pragma("inline=never") -#endif - - -/** \brief This macro is used to test fatal errors. - * - * The macro tests if the expression is false. If it is, a fatal error is - * detected and the application hangs up. If \c TEST_SUITE_DEFINE_ASSERT_MACRO - * is defined, a unit test version of the macro is used, to allow execution - * of further tests after a false expression. - * - * \param[in] expr Expression to evaluate and supposed to be nonzero. - */ -#if defined(_ASSERT_ENABLE_) -# if defined(TEST_SUITE_DEFINE_ASSERT_MACRO) -# include "unit_test/suite.h" -# else -# undef TEST_SUITE_DEFINE_ASSERT_MACRO -# define Assert(expr) \ - {\ - if (!(expr)) asm("BKPT #0");\ - } -# endif -#else -# define Assert(expr) ((void) 0) -#endif - -/* Define WEAK attribute */ -#if defined ( __CC_ARM ) -# define WEAK __attribute__ ((weak)) -#elif defined ( __ICCARM__ ) -# define WEAK __weak -#elif defined ( __GNUC__ ) -# define WEAK __attribute__ ((weak)) -#endif - -/* Define NO_INIT attribute */ -#if defined ( __CC_ARM ) -# define NO_INIT __attribute__((zero_init)) -#elif defined ( __ICCARM__ ) -# define NO_INIT __no_init -#elif defined ( __GNUC__ ) -# define NO_INIT __attribute__((section(".no_init"))) -#endif - -#include "interrupt.h" - -/** \name Usual Types - * @{ */ -#ifndef __cplusplus -# if !defined(__bool_true_false_are_defined) -typedef unsigned char bool; -# endif -#endif -typedef uint16_t le16_t; -typedef uint16_t be16_t; -typedef uint32_t le32_t; -typedef uint32_t be32_t; -typedef uint32_t iram_size_t; -/** @} */ - -/** \name Aliasing Aggregate Types - * @{ */ - -/** 16-bit union. */ -typedef union -{ - int16_t s16; - uint16_t u16; - int8_t s8[2]; - uint8_t u8[2]; -} Union16; - -/** 32-bit union. */ -typedef union -{ - int32_t s32; - uint32_t u32; - int16_t s16[2]; - uint16_t u16[2]; - int8_t s8[4]; - uint8_t u8[4]; -} Union32; - -/** 64-bit union. */ -typedef union -{ - int64_t s64; - uint64_t u64; - int32_t s32[2]; - uint32_t u32[2]; - int16_t s16[4]; - uint16_t u16[4]; - int8_t s8[8]; - uint8_t u8[8]; -} Union64; - -/** Union of pointers to 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef union -{ - int64_t *s64ptr; - uint64_t *u64ptr; - int32_t *s32ptr; - uint32_t *u32ptr; - int16_t *s16ptr; - uint16_t *u16ptr; - int8_t *s8ptr; - uint8_t *u8ptr; -} UnionPtr; - -/** Union of pointers to volatile 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef union -{ - volatile int64_t *s64ptr; - volatile uint64_t *u64ptr; - volatile int32_t *s32ptr; - volatile uint32_t *u32ptr; - volatile int16_t *s16ptr; - volatile uint16_t *u16ptr; - volatile int8_t *s8ptr; - volatile uint8_t *u8ptr; -} UnionVPtr; - -/** Union of pointers to constant 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef union -{ - const int64_t *s64ptr; - const uint64_t *u64ptr; - const int32_t *s32ptr; - const uint32_t *u32ptr; - const int16_t *s16ptr; - const uint16_t *u16ptr; - const int8_t *s8ptr; - const uint8_t *u8ptr; -} UnionCPtr; - -/** Union of pointers to constant volatile 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef union -{ - const volatile int64_t *s64ptr; - const volatile uint64_t *u64ptr; - const volatile int32_t *s32ptr; - const volatile uint32_t *u32ptr; - const volatile int16_t *s16ptr; - const volatile uint16_t *u16ptr; - const volatile int8_t *s8ptr; - const volatile uint8_t *u8ptr; -} UnionCVPtr; - -/** Structure of pointers to 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef struct -{ - int64_t *s64ptr; - uint64_t *u64ptr; - int32_t *s32ptr; - uint32_t *u32ptr; - int16_t *s16ptr; - uint16_t *u16ptr; - int8_t *s8ptr; - uint8_t *u8ptr; -} StructPtr; - -/** Structure of pointers to volatile 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef struct -{ - volatile int64_t *s64ptr; - volatile uint64_t *u64ptr; - volatile int32_t *s32ptr; - volatile uint32_t *u32ptr; - volatile int16_t *s16ptr; - volatile uint16_t *u16ptr; - volatile int8_t *s8ptr; - volatile uint8_t *u8ptr; -} StructVPtr; - -/** Structure of pointers to constant 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef struct -{ - const int64_t *s64ptr; - const uint64_t *u64ptr; - const int32_t *s32ptr; - const uint32_t *u32ptr; - const int16_t *s16ptr; - const uint16_t *u16ptr; - const int8_t *s8ptr; - const uint8_t *u8ptr; -} StructCPtr; - -/** Structure of pointers to constant volatile 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef struct -{ - const volatile int64_t *s64ptr; - const volatile uint64_t *u64ptr; - const volatile int32_t *s32ptr; - const volatile uint32_t *u32ptr; - const volatile int16_t *s16ptr; - const volatile uint16_t *u16ptr; - const volatile int8_t *s8ptr; - const volatile uint8_t *u8ptr; -} StructCVPtr; - -/** @} */ - -#endif /* #ifndef __ASSEMBLY__ */ - -/** \name Usual Constants - * @{ */ -#define DISABLE 0 -//#define ENABLE 1 - -#ifndef __cplusplus -# if !defined(__bool_true_false_are_defined) -# define false 0 -# define true 1 -# endif -#endif -/** @} */ - -#ifndef __ASSEMBLY__ - -/** \name Optimization Control - * @{ */ - -/** - * \def likely(exp) - * \brief The expression \a exp is likely to be true - */ -#if !defined(likely) || defined(__DOXYGEN__) -# define likely(exp) (exp) -#endif - -/** - * \def unlikely(exp) - * \brief The expression \a exp is unlikely to be true - */ -#if !defined(unlikely) || defined(__DOXYGEN__) -# define unlikely(exp) (exp) -#endif - -/** - * \def is_constant(exp) - * \brief Determine if an expression evaluates to a constant value. - * - * \param[in] exp Any expression - * - * \return true if \a exp is constant, false otherwise. - */ -#if (defined __GNUC__) || (defined __CC_ARM) -# define is_constant(exp) __builtin_constant_p(exp) -#else -# define is_constant(exp) (0) -#endif - -/** @} */ - -/** \name Bit-Field Handling - * @{ */ - -/** \brief Reads the bits of a value specified by a given bit-mask. - * - * \param[in] value Value to read bits from. - * \param[in] mask Bit-mask indicating bits to read. - * - * \return Read bits. - */ -#define Rd_bits( value, mask) ((value) & (mask)) - -/** \brief Writes the bits of a C lvalue specified by a given bit-mask. - * - * \param[in] lvalue C lvalue to write bits to. - * \param[in] mask Bit-mask indicating bits to write. - * \param[in] bits Bits to write. - * - * \return Resulting value with written bits. - */ -#define Wr_bits(lvalue, mask, bits) ((lvalue) = ((lvalue) & ~(mask)) |\ - ((bits ) & (mask))) - -/** \brief Tests the bits of a value specified by a given bit-mask. - * - * \param[in] value Value of which to test bits. - * \param[in] mask Bit-mask indicating bits to test. - * - * \return \c 1 if at least one of the tested bits is set, else \c 0. - */ -#define Tst_bits( value, mask) (Rd_bits(value, mask) != 0) - -/** \brief Clears the bits of a C lvalue specified by a given bit-mask. - * - * \param[in] lvalue C lvalue of which to clear bits. - * \param[in] mask Bit-mask indicating bits to clear. - * - * \return Resulting value with cleared bits. - */ -#define Clr_bits(lvalue, mask) ((lvalue) &= ~(mask)) - -/** \brief Sets the bits of a C lvalue specified by a given bit-mask. - * - * \param[in] lvalue C lvalue of which to set bits. - * \param[in] mask Bit-mask indicating bits to set. - * - * \return Resulting value with set bits. - */ -#define Set_bits(lvalue, mask) ((lvalue) |= (mask)) - -/** \brief Toggles the bits of a C lvalue specified by a given bit-mask. - * - * \param[in] lvalue C lvalue of which to toggle bits. - * \param[in] mask Bit-mask indicating bits to toggle. - * - * \return Resulting value with toggled bits. - */ -#define Tgl_bits(lvalue, mask) ((lvalue) ^= (mask)) - -/** \brief Reads the bit-field of a value specified by a given bit-mask. - * - * \param[in] value Value to read a bit-field from. - * \param[in] mask Bit-mask indicating the bit-field to read. - * - * \return Read bit-field. - */ -#define Rd_bitfield( value, mask) (Rd_bits( value, mask) >> ctz(mask)) - -/** \brief Writes the bit-field of a C lvalue specified by a given bit-mask. - * - * \param[in] lvalue C lvalue to write a bit-field to. - * \param[in] mask Bit-mask indicating the bit-field to write. - * \param[in] bitfield Bit-field to write. - * - * \return Resulting value with written bit-field. - */ -#define Wr_bitfield(lvalue, mask, bitfield) (Wr_bits(lvalue, mask, (uint32_t)(bitfield) << ctz(mask))) - -/** @} */ - - -/** \name Zero-Bit Counting - * - * Under GCC, __builtin_clz and __builtin_ctz behave like macros when - * applied to constant expressions (values known at compile time), so they are - * more optimized than the use of the corresponding assembly instructions and - * they can be used as constant expressions e.g. to initialize objects having - * static storage duration, and like the corresponding assembly instructions - * when applied to non-constant expressions (values unknown at compile time), so - * they are more optimized than an assembly periphrasis. Hence, clz and ctz - * ensure a possible and optimized behavior for both constant and non-constant - * expressions. - * - * @{ */ - -/** \brief Counts the leading zero bits of the given value considered as a 32-bit integer. - * - * \param[in] u Value of which to count the leading zero bits. - * - * \return The count of leading zero bits in \a u. - */ -#if (defined __GNUC__) || (defined __CC_ARM) -# define clz(u) __builtin_clz(u) -#else -# define clz(u) (((u) == 0) ? 32 : \ - ((u) & (1ul << 31)) ? 0 : \ - ((u) & (1ul << 30)) ? 1 : \ - ((u) & (1ul << 29)) ? 2 : \ - ((u) & (1ul << 28)) ? 3 : \ - ((u) & (1ul << 27)) ? 4 : \ - ((u) & (1ul << 26)) ? 5 : \ - ((u) & (1ul << 25)) ? 6 : \ - ((u) & (1ul << 24)) ? 7 : \ - ((u) & (1ul << 23)) ? 8 : \ - ((u) & (1ul << 22)) ? 9 : \ - ((u) & (1ul << 21)) ? 10 : \ - ((u) & (1ul << 20)) ? 11 : \ - ((u) & (1ul << 19)) ? 12 : \ - ((u) & (1ul << 18)) ? 13 : \ - ((u) & (1ul << 17)) ? 14 : \ - ((u) & (1ul << 16)) ? 15 : \ - ((u) & (1ul << 15)) ? 16 : \ - ((u) & (1ul << 14)) ? 17 : \ - ((u) & (1ul << 13)) ? 18 : \ - ((u) & (1ul << 12)) ? 19 : \ - ((u) & (1ul << 11)) ? 20 : \ - ((u) & (1ul << 10)) ? 21 : \ - ((u) & (1ul << 9)) ? 22 : \ - ((u) & (1ul << 8)) ? 23 : \ - ((u) & (1ul << 7)) ? 24 : \ - ((u) & (1ul << 6)) ? 25 : \ - ((u) & (1ul << 5)) ? 26 : \ - ((u) & (1ul << 4)) ? 27 : \ - ((u) & (1ul << 3)) ? 28 : \ - ((u) & (1ul << 2)) ? 29 : \ - ((u) & (1ul << 1)) ? 30 : \ - 31) -#endif - -/** \brief Counts the trailing zero bits of the given value considered as a 32-bit integer. - * - * \param[in] u Value of which to count the trailing zero bits. - * - * \return The count of trailing zero bits in \a u. - */ -#if (defined __GNUC__) || (defined __CC_ARM) -# define ctz(u) __builtin_ctz(u) -#else -# define ctz(u) ((u) & (1ul << 0) ? 0 : \ - (u) & (1ul << 1) ? 1 : \ - (u) & (1ul << 2) ? 2 : \ - (u) & (1ul << 3) ? 3 : \ - (u) & (1ul << 4) ? 4 : \ - (u) & (1ul << 5) ? 5 : \ - (u) & (1ul << 6) ? 6 : \ - (u) & (1ul << 7) ? 7 : \ - (u) & (1ul << 8) ? 8 : \ - (u) & (1ul << 9) ? 9 : \ - (u) & (1ul << 10) ? 10 : \ - (u) & (1ul << 11) ? 11 : \ - (u) & (1ul << 12) ? 12 : \ - (u) & (1ul << 13) ? 13 : \ - (u) & (1ul << 14) ? 14 : \ - (u) & (1ul << 15) ? 15 : \ - (u) & (1ul << 16) ? 16 : \ - (u) & (1ul << 17) ? 17 : \ - (u) & (1ul << 18) ? 18 : \ - (u) & (1ul << 19) ? 19 : \ - (u) & (1ul << 20) ? 20 : \ - (u) & (1ul << 21) ? 21 : \ - (u) & (1ul << 22) ? 22 : \ - (u) & (1ul << 23) ? 23 : \ - (u) & (1ul << 24) ? 24 : \ - (u) & (1ul << 25) ? 25 : \ - (u) & (1ul << 26) ? 26 : \ - (u) & (1ul << 27) ? 27 : \ - (u) & (1ul << 28) ? 28 : \ - (u) & (1ul << 29) ? 29 : \ - (u) & (1ul << 30) ? 30 : \ - (u) & (1ul << 31) ? 31 : \ - 32) -#endif - -/** @} */ - - -/** \name Bit Reversing - * @{ */ - -/** \brief Reverses the bits of \a u8. - * - * \param[in] u8 U8 of which to reverse the bits. - * - * \return Value resulting from \a u8 with reversed bits. - */ -#define bit_reverse8(u8) ((U8)(bit_reverse32((U8)(u8)) >> 24)) - -/** \brief Reverses the bits of \a u16. - * - * \param[in] u16 U16 of which to reverse the bits. - * - * \return Value resulting from \a u16 with reversed bits. - */ -#define bit_reverse16(u16) ((uint16_t)(bit_reverse32((uint16_t)(u16)) >> 16)) - -/** \brief Reverses the bits of \a u32. - * - * \param[in] u32 U32 of which to reverse the bits. - * - * \return Value resulting from \a u32 with reversed bits. - */ -#define bit_reverse32(u32) __RBIT(u32) - -/** \brief Reverses the bits of \a u64. - * - * \param[in] u64 U64 of which to reverse the bits. - * - * \return Value resulting from \a u64 with reversed bits. - */ -#define bit_reverse64(u64) ((uint64_t)(((uint64_t)bit_reverse32((uint64_t)(u64) >> 32)) |\ - ((uint64_t)bit_reverse32((uint64_t)(u64)) << 32))) - -/** @} */ - - -/** \name Alignment - * @{ */ - -/** \brief Tests alignment of the number \a val with the \a n boundary. - * - * \param[in] val Input value. - * \param[in] n Boundary. - * - * \return \c 1 if the number \a val is aligned with the \a n boundary, else \c 0. - */ -#define Test_align(val, n) (!Tst_bits( val, (n) - 1 ) ) - -/** \brief Gets alignment of the number \a val with respect to the \a n boundary. - * - * \param[in] val Input value. - * \param[in] n Boundary. - * - * \return Alignment of the number \a val with respect to the \a n boundary. - */ -#define Get_align(val, n) ( Rd_bits( val, (n) - 1 ) ) - -/** \brief Sets alignment of the lvalue number \a lval to \a alg with respect to the \a n boundary. - * - * \param[in] lval Input/output lvalue. - * \param[in] n Boundary. - * \param[in] alg Alignment. - * - * \return New value of \a lval resulting from its alignment set to \a alg with respect to the \a n boundary. - */ -#define Set_align(lval, n, alg) ( Wr_bits(lval, (n) - 1, alg) ) - -/** \brief Aligns the number \a val with the upper \a n boundary. - * - * \param[in] val Input value. - * \param[in] n Boundary. - * - * \return Value resulting from the number \a val aligned with the upper \a n boundary. - */ -#define Align_up( val, n) (((val) + ((n) - 1)) & ~((n) - 1)) - -/** \brief Aligns the number \a val with the lower \a n boundary. - * - * \param[in] val Input value. - * \param[in] n Boundary. - * - * \return Value resulting from the number \a val aligned with the lower \a n boundary. - */ -#define Align_down(val, n) ( (val) & ~((n) - 1)) - -/** @} */ - - -/** \name Mathematics - * - * The same considerations as for clz and ctz apply here but GCC does not - * provide built-in functions to access the assembly instructions abs, min and - * max and it does not produce them by itself in most cases, so two sets of - * macros are defined here: - * - Abs, Min and Max to apply to constant expressions (values known at - * compile time); - * - abs, min and max to apply to non-constant expressions (values unknown at - * compile time), abs is found in stdlib.h. - * - * @{ */ - -/** \brief Takes the absolute value of \a a. - * - * \param[in] a Input value. - * - * \return Absolute value of \a a. - * - * \note More optimized if only used with values known at compile time. - */ -#define Abs(a) (((a) < 0 ) ? -(a) : (a)) - -/** \brief Takes the minimal value of \a a and \a b. - * - * \param[in] a Input value. - * \param[in] b Input value. - * - * \return Minimal value of \a a and \a b. - * - * \note More optimized if only used with values known at compile time. - */ -#define Min(a, b) (((a) < (b)) ? (a) : (b)) - -/** \brief Takes the maximal value of \a a and \a b. - * - * \param[in] a Input value. - * \param[in] b Input value. - * - * \return Maximal value of \a a and \a b. - * - * \note More optimized if only used with values known at compile time. - */ -#define Max(a, b) (((a) > (b)) ? (a) : (b)) - -/** \brief Takes the minimal value of \a a and \a b. - * - * \param[in] a Input value. - * \param[in] b Input value. - * - * \return Minimal value of \a a and \a b. - * - * \note More optimized if only used with values unknown at compile time. - */ -#define min(a, b) Min(a, b) - -/** \brief Takes the maximal value of \a a and \a b. - * - * \param[in] a Input value. - * \param[in] b Input value. - * - * \return Maximal value of \a a and \a b. - * - * \note More optimized if only used with values unknown at compile time. - */ -#define max(a, b) Max(a, b) - -/** @} */ - - -/** \brief Calls the routine at address \a addr. - * - * It generates a long call opcode. - * - * For example, `Long_call(0x80000000)' generates a software reset on a UC3 if - * it is invoked from the CPU supervisor mode. - * - * \param[in] addr Address of the routine to call. - * - * \note It may be used as a long jump opcode in some special cases. - */ -#define Long_call(addr) ((*(void (*)(void))(addr))()) - - -/** \name MCU Endianism Handling - * ARM is MCU little endian. - * - * @{ */ -#define BE16(x) Swap16(x) -#define LE16(x) (x) - -#define le16_to_cpu(x) (x) -#define cpu_to_le16(x) (x) -#define LE16_TO_CPU(x) (x) -#define CPU_TO_LE16(x) (x) - -#define be16_to_cpu(x) Swap16(x) -#define cpu_to_be16(x) Swap16(x) -#define BE16_TO_CPU(x) Swap16(x) -#define CPU_TO_BE16(x) Swap16(x) - -#define le32_to_cpu(x) (x) -#define cpu_to_le32(x) (x) -#define LE32_TO_CPU(x) (x) -#define CPU_TO_LE32(x) (x) - -#define be32_to_cpu(x) swap32(x) -#define cpu_to_be32(x) swap32(x) -#define BE32_TO_CPU(x) swap32(x) -#define CPU_TO_BE32(x) swap32(x) -/** @} */ - - -/** \name Endianism Conversion - * - * The same considerations as for clz and ctz apply here but GCC's - * __builtin_bswap_32 and __builtin_bswap_64 do not behave like macros when - * applied to constant expressions, so two sets of macros are defined here: - * - Swap16, Swap32 and Swap64 to apply to constant expressions (values known - * at compile time); - * - swap16, swap32 and swap64 to apply to non-constant expressions (values - * unknown at compile time). - * - * @{ */ - -/** \brief Toggles the endianism of \a u16 (by swapping its bytes). - * - * \param[in] u16 U16 of which to toggle the endianism. - * - * \return Value resulting from \a u16 with toggled endianism. - * - * \note More optimized if only used with values known at compile time. - */ -#define Swap16(u16) ((uint16_t)(((uint16_t)(u16) >> 8) |\ - ((uint16_t)(u16) << 8))) - -/** \brief Toggles the endianism of \a u32 (by swapping its bytes). - * - * \param[in] u32 U32 of which to toggle the endianism. - * - * \return Value resulting from \a u32 with toggled endianism. - * - * \note More optimized if only used with values known at compile time. - */ -#define Swap32(u32) ((uint32_t)(((uint32_t)Swap16((uint32_t)(u32) >> 16)) |\ - ((uint32_t)Swap16((uint32_t)(u32)) << 16))) - -/** \brief Toggles the endianism of \a u64 (by swapping its bytes). - * - * \param[in] u64 U64 of which to toggle the endianism. - * - * \return Value resulting from \a u64 with toggled endianism. - * - * \note More optimized if only used with values known at compile time. - */ -#define Swap64(u64) ((uint64_t)(((uint64_t)Swap32((uint64_t)(u64) >> 32)) |\ - ((uint64_t)Swap32((uint64_t)(u64)) << 32))) - -/** \brief Toggles the endianism of \a u16 (by swapping its bytes). - * - * \param[in] u16 U16 of which to toggle the endianism. - * - * \return Value resulting from \a u16 with toggled endianism. - * - * \note More optimized if only used with values unknown at compile time. - */ -#define swap16(u16) Swap16(u16) - -/** \brief Toggles the endianism of \a u32 (by swapping its bytes). - * - * \param[in] u32 U32 of which to toggle the endianism. - * - * \return Value resulting from \a u32 with toggled endianism. - * - * \note More optimized if only used with values unknown at compile time. - */ -#if (defined __GNUC__) -# define swap32(u32) ((uint32_t)__builtin_bswap32((uint32_t)(u32))) -#else -# define swap32(u32) Swap32(u32) -#endif - -/** \brief Toggles the endianism of \a u64 (by swapping its bytes). - * - * \param[in] u64 U64 of which to toggle the endianism. - * - * \return Value resulting from \a u64 with toggled endianism. - * - * \note More optimized if only used with values unknown at compile time. - */ -#if (defined __GNUC__) -# define swap64(u64) ((uint64_t)__builtin_bswap64((uint64_t)(u64))) -#else -# define swap64(u64) ((uint64_t)(((uint64_t)swap32((uint64_t)(u64) >> 32)) |\ - ((uint64_t)swap32((uint64_t)(u64)) << 32))) -#endif - -/** @} */ - - -/** \name Target Abstraction - * - * @{ */ - -#define _GLOBEXT_ extern /**< extern storage-class specifier. */ -#define _CONST_TYPE_ const /**< const type qualifier. */ -#define _MEM_TYPE_SLOW_ /**< Slow memory type. */ -#define _MEM_TYPE_MEDFAST_ /**< Fairly fast memory type. */ -#define _MEM_TYPE_FAST_ /**< Fast memory type. */ - -#define memcmp_ram2ram memcmp /**< Target-specific memcmp of RAM to RAM. */ -#define memcmp_code2ram memcmp /**< Target-specific memcmp of RAM to NVRAM. */ -#define memcpy_ram2ram memcpy /**< Target-specific memcpy from RAM to RAM. */ -#define memcpy_code2ram memcpy /**< Target-specific memcpy from NVRAM to RAM. */ - -/** @} */ - -/** - * \brief Calculate \f$ \left\lceil \frac{a}{b} \right\rceil \f$ using - * integer arithmetic. - * - * \param[in] a An integer - * \param[in] b Another integer - * - * \return (\a a / \a b) rounded up to the nearest integer. - */ -#define div_ceil(a, b) (((a) + (b) - 1) / (b)) - -#endif /* #ifndef __ASSEMBLY__ */ -#ifdef __ICCARM__ -/** \name Compiler Keywords - * - * Port of some keywords from GCC to IAR Embedded Workbench. - * - * @{ */ - -#define __asm__ asm -#define __inline__ inline -#define __volatile__ - -/** @} */ - -#endif - -#define FUNC_PTR void * -/** - * \def unused - * \brief Marking \a v as a unused parameter or value. - */ -#define unused(v) do { (void)(v); } while(0) - -/* Define RAMFUNC attribute */ -#if defined ( __CC_ARM ) /* Keil uVision 4 */ -# define RAMFUNC __attribute__ ((section(".ramfunc"))) -#elif defined ( __ICCARM__ ) /* IAR Ewarm 5.41+ */ -# define RAMFUNC __ramfunc -#elif defined ( __GNUC__ ) /* GCC CS3 2009q3-68 */ -# define RAMFUNC __attribute__ ((section(".ramfunc"))) -#endif - -/* Define OPTIMIZE_HIGH attribute */ -#if defined ( __CC_ARM ) /* Keil uVision 4 */ -# define OPTIMIZE_HIGH _Pragma("O3") -#elif defined ( __ICCARM__ ) /* IAR Ewarm 5.41+ */ -# define OPTIMIZE_HIGH _Pragma("optimize=high") -#elif defined ( __GNUC__ ) /* GCC CS3 2009q3-68 */ -# define OPTIMIZE_HIGH __attribute__((optimize(s))) -#endif -#define PASS 0 -#define FAIL 1 -#define LOW 0 -#define HIGH 1 - -typedef int8_t S8 ; //!< 8-bit signed integer. -typedef uint8_t U8 ; //!< 8-bit unsigned integer. -typedef int16_t S16; //!< 16-bit signed integer. -typedef uint16_t U16; //!< 16-bit unsigned integer. -typedef int32_t S32; //!< 32-bit signed integer. -typedef uint32_t U32; //!< 32-bit unsigned integer. -typedef int64_t S64; //!< 64-bit signed integer. -typedef uint64_t U64; //!< 64-bit unsigned integer. -typedef float F32; //!< 32-bit floating-point number. -typedef double F64; //!< 64-bit floating-point number. - -#define MSB(u16) (((U8 *)&(u16))[1]) //!< Most significant byte of \a u16. -#define LSB(u16) (((U8 *)&(u16))[0]) //!< Least significant byte of \a u16. - -#define MSH(u32) (((U16 *)&(u32))[1]) //!< Most significant half-word of \a u32. -#define LSH(u32) (((U16 *)&(u32))[0]) //!< Least significant half-word of \a u32. -#define MSB0W(u32) (((U8 *)&(u32))[3]) //!< Most significant byte of 1st rank of \a u32. -#define MSB1W(u32) (((U8 *)&(u32))[2]) //!< Most significant byte of 2nd rank of \a u32. -#define MSB2W(u32) (((U8 *)&(u32))[1]) //!< Most significant byte of 3rd rank of \a u32. -#define MSB3W(u32) (((U8 *)&(u32))[0]) //!< Most significant byte of 4th rank of \a u32. -#define LSB3W(u32) MSB0W(u32) //!< Least significant byte of 4th rank of \a u32. -#define LSB2W(u32) MSB1W(u32) //!< Least significant byte of 3rd rank of \a u32. -#define LSB1W(u32) MSB2W(u32) //!< Least significant byte of 2nd rank of \a u32. -#define LSB0W(u32) MSB3W(u32) //!< Least significant byte of 1st rank of \a u32. - -#define MSW(u64) (((U32 *)&(u64))[1]) //!< Most significant word of \a u64. -#define LSW(u64) (((U32 *)&(u64))[0]) //!< Least significant word of \a u64. -#define MSH0(u64) (((U16 *)&(u64))[3]) //!< Most significant half-word of 1st rank of \a u64. -#define MSH1(u64) (((U16 *)&(u64))[2]) //!< Most significant half-word of 2nd rank of \a u64. -#define MSH2(u64) (((U16 *)&(u64))[1]) //!< Most significant half-word of 3rd rank of \a u64. -#define MSH3(u64) (((U16 *)&(u64))[0]) //!< Most significant half-word of 4th rank of \a u64. -#define LSH3(u64) MSH0(u64) //!< Least significant half-word of 4th rank of \a u64. -#define LSH2(u64) MSH1(u64) //!< Least significant half-word of 3rd rank of \a u64. -#define LSH1(u64) MSH2(u64) //!< Least significant half-word of 2nd rank of \a u64. -#define LSH0(u64) MSH3(u64) //!< Least significant half-word of 1st rank of \a u64. -#define MSB0D(u64) (((U8 *)&(u64))[7]) //!< Most significant byte of 1st rank of \a u64. -#define MSB1D(u64) (((U8 *)&(u64))[6]) //!< Most significant byte of 2nd rank of \a u64. -#define MSB2D(u64) (((U8 *)&(u64))[5]) //!< Most significant byte of 3rd rank of \a u64. -#define MSB3D(u64) (((U8 *)&(u64))[4]) //!< Most significant byte of 4th rank of \a u64. -#define MSB4D(u64) (((U8 *)&(u64))[3]) //!< Most significant byte of 5th rank of \a u64. -#define MSB5D(u64) (((U8 *)&(u64))[2]) //!< Most significant byte of 6th rank of \a u64. -#define MSB6D(u64) (((U8 *)&(u64))[1]) //!< Most significant byte of 7th rank of \a u64. -#define MSB7D(u64) (((U8 *)&(u64))[0]) //!< Most significant byte of 8th rank of \a u64. -#define LSB7D(u64) MSB0D(u64) //!< Least significant byte of 8th rank of \a u64. -#define LSB6D(u64) MSB1D(u64) //!< Least significant byte of 7th rank of \a u64. -#define LSB5D(u64) MSB2D(u64) //!< Least significant byte of 6th rank of \a u64. -#define LSB4D(u64) MSB3D(u64) //!< Least significant byte of 5th rank of \a u64. -#define LSB3D(u64) MSB4D(u64) //!< Least significant byte of 4th rank of \a u64. -#define LSB2D(u64) MSB5D(u64) //!< Least significant byte of 3rd rank of \a u64. -#define LSB1D(u64) MSB6D(u64) //!< Least significant byte of 2nd rank of \a u64. -#define LSB0D(u64) MSB7D(u64) //!< Least significant byte of 1st rank of \a u64. - -#define LSB0(u32) LSB0W(u32) //!< Least significant byte of 1st rank of \a u32. -#define LSB1(u32) LSB1W(u32) //!< Least significant byte of 2nd rank of \a u32. -#define LSB2(u32) LSB2W(u32) //!< Least significant byte of 3rd rank of \a u32. -#define LSB3(u32) LSB3W(u32) //!< Least significant byte of 4th rank of \a u32. -#define MSB3(u32) MSB3W(u32) //!< Most significant byte of 4th rank of \a u32. -#define MSB2(u32) MSB2W(u32) //!< Most significant byte of 3rd rank of \a u32. -#define MSB1(u32) MSB1W(u32) //!< Most significant byte of 2nd rank of \a u32. -#define MSB0(u32) MSB0W(u32) //!< Most significant byte of 1st rank of \a u32. - -#if defined(__ICCARM__) -#define SHORTENUM __packed -#elif defined(__GNUC__) -#define SHORTENUM __attribute__((packed)) -#endif - -/* No operation */ -#if defined(__ICCARM__) -#define nop() __no_operation() -#elif defined(__GNUC__) -#define nop() (__NOP()) -#endif - -#define FLASH_DECLARE(x) const x -#define FLASH_EXTERN(x) extern const x -#define PGM_READ_BYTE(x) *(x) -#define PGM_READ_WORD(x) *(x) -#define MEMCPY_ENDIAN memcpy -#define PGM_READ_BLOCK(dst, src, len) memcpy((dst), (src), (len)) - -/*Defines the Flash Storage for the request and response of MAC*/ -#define CMD_ID_OCTET (0) - -/* Converting of values from CPU endian to little endian. */ -#define CPU_ENDIAN_TO_LE16(x) (x) -#define CPU_ENDIAN_TO_LE32(x) (x) -#define CPU_ENDIAN_TO_LE64(x) (x) - -/* Converting of values from little endian to CPU endian. */ -#define LE16_TO_CPU_ENDIAN(x) (x) -#define LE32_TO_CPU_ENDIAN(x) (x) -#define LE64_TO_CPU_ENDIAN(x) (x) - -/* Converting of constants from little endian to CPU endian. */ -#define CLE16_TO_CPU_ENDIAN(x) (x) -#define CLE32_TO_CPU_ENDIAN(x) (x) -#define CLE64_TO_CPU_ENDIAN(x) (x) - -/* Converting of constants from CPU endian to little endian. */ -#define CCPU_ENDIAN_TO_LE16(x) (x) -#define CCPU_ENDIAN_TO_LE32(x) (x) -#define CCPU_ENDIAN_TO_LE64(x) (x) - -#define ADDR_COPY_DST_SRC_16(dst, src) ((dst) = (src)) -#define ADDR_COPY_DST_SRC_64(dst, src) ((dst) = (src)) - -/** - * @brief Converts a 64-Bit value into a 8 Byte array - * - * @param[in] value 64-Bit value - * @param[out] data Pointer to the 8 Byte array to be updated with 64-Bit value - * @ingroup apiPalApi - */ -static inline void convert_64_bit_to_byte_array(uint64_t value, uint8_t *data) -{ - uint8_t index = 0; - - while (index < 8) - { - data[index++] = value & 0xFF; - value = value >> 8; - } -} - -/** - * @brief Converts a 16-Bit value into a 2 Byte array - * - * @param[in] value 16-Bit value - * @param[out] data Pointer to the 2 Byte array to be updated with 16-Bit value - * @ingroup apiPalApi - */ -static inline void convert_16_bit_to_byte_array(uint16_t value, uint8_t *data) -{ - data[0] = value & 0xFF; - data[1] = (value >> 8) & 0xFF; -} - -/* Converts a 16-Bit value into a 2 Byte array */ -static inline void convert_spec_16_bit_to_byte_array(uint16_t value, uint8_t *data) -{ - data[0] = value & 0xFF; - data[1] = (value >> 8) & 0xFF; -} - -/* Converts a 16-Bit value into a 2 Byte array */ -static inline void convert_16_bit_to_byte_address(uint16_t value, uint8_t *data) -{ - data[0] = value & 0xFF; - data[1] = (value >> 8) & 0xFF; -} - -/* - * @brief Converts a 2 Byte array into a 16-Bit value - * - * @param data Specifies the pointer to the 2 Byte array - * - * @return 16-Bit value - * @ingroup apiPalApi - */ -static inline uint16_t convert_byte_array_to_16_bit(uint8_t *data) -{ - return (data[0] | ((uint16_t)data[1] << 8)); -} - -/* Converts a 4 Byte array into a 32-Bit value */ -static inline uint32_t convert_byte_array_to_32_bit(uint8_t *data) -{ - union - { - uint32_t u32; - uint8_t u8[4]; - }long_addr; - uint8_t index; - for (index = 0; index < 4; index++) - { - long_addr.u8[index] = *data++; - } - return long_addr.u32; -} - -/** - * @brief Converts a 8 Byte array into a 64-Bit value - * - * @param data Specifies the pointer to the 8 Byte array - * - * @return 64-Bit value - * @ingroup apiPalApi - */ -static inline uint64_t convert_byte_array_to_64_bit(uint8_t *data) -{ - union - { - uint64_t u64; - uint8_t u8[8]; - } long_addr; - - uint8_t index; - - for (index = 0; index < 8; index++) - { - long_addr.u8[index] = *data++; - } - - return long_addr.u64; -} - -/** @} */ - -#endif /* UTILS_COMPILER_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/gclk.c b/feather_sensor_lte/libraries/Adafruit_ASFcore/gclk.c deleted file mode 100644 index 1199a19..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/gclk.c +++ /dev/null @@ -1,522 +0,0 @@ -/** - * \file - * - * \brief SAM D21/R21/DA0/DA1 Generic Clock Driver - * - * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#include -#include -#include - -/** - * \brief Determines if the hardware module(s) are currently synchronizing to the bus. - * - * Checks to see if the underlying hardware peripheral module(s) are currently - * synchronizing across multiple clock domains to the hardware bus, This - * function can be used to delay further operations on a module until such time - * that it is ready, to prevent blocking delays for synchronization in the - * user application. - * - * \return Synchronization status of the underlying hardware module(s). - * - * \retval false if the module has completed synchronization - * \retval true if the module synchronization is ongoing - */ -static inline bool system_gclk_is_syncing(void) -{ - if (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY){ - return true; - } - - return false; -} - -/** - * \brief Initializes the GCLK driver. - * - * Initializes the Generic Clock module, disabling and resetting all active - * Generic Clock Generators and Channels to their power-on default values. - */ -void system_gclk_init(void) -{ - /* Turn on the digital interface clock */ - system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBA, PM_APBAMASK_GCLK); - - /* Software reset the module to ensure it is re-initialized correctly */ - GCLK->CTRL.reg = GCLK_CTRL_SWRST; - while (GCLK->CTRL.reg & GCLK_CTRL_SWRST) { - /* Wait for reset to complete */ - } -} - -/** - * \brief Writes a Generic Clock Generator configuration to the hardware module. - * - * Writes out a given configuration of a Generic Clock Generator configuration - * to the hardware module. - * - * \note Changing the clock source on the fly (on a running - * generator) can take additional time if the clock source is configured - * to only run on-demand (ONDEMAND bit is set) and it is not currently - * running (no peripheral is requesting the clock source). In this case - * the GCLK will request the new clock while still keeping a request to - * the old clock source until the new clock source is ready. - * - * \note This function will not start a generator that is not already running; - * to start the generator, call \ref system_gclk_gen_enable() - * after configuring a generator. - * - * \param[in] generator Generic Clock Generator index to configure - * \param[in] config Configuration settings for the generator - */ -void system_gclk_gen_set_config( - const uint8_t generator, - struct system_gclk_gen_config *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Cache new register configurations to minimize sync requirements. */ - uint32_t new_genctrl_config = (generator << GCLK_GENCTRL_ID_Pos); - uint32_t new_gendiv_config = (generator << GCLK_GENDIV_ID_Pos); - - /* Select the requested source clock for the generator */ - new_genctrl_config |= config->source_clock << GCLK_GENCTRL_SRC_Pos; - - /* Configure the clock to be either high or low when disabled */ - if (config->high_when_disabled) { - new_genctrl_config |= GCLK_GENCTRL_OOV; - } - - /* Configure if the clock output to I/O pin should be enabled. */ - if (config->output_enable) { - new_genctrl_config |= GCLK_GENCTRL_OE; - } - - /* Set division factor */ - if (config->division_factor > 1) { - /* Check if division is a power of two */ - if (((config->division_factor & (config->division_factor - 1)) == 0)) { - /* Determine the index of the highest bit set to get the - * division factor that must be loaded into the division - * register */ - - uint32_t div2_count = 0; - - uint32_t mask; - for (mask = (1UL << 1); mask < config->division_factor; - mask <<= 1) { - div2_count++; - } - - /* Set binary divider power of 2 division factor */ - new_gendiv_config |= div2_count << GCLK_GENDIV_DIV_Pos; - new_genctrl_config |= GCLK_GENCTRL_DIVSEL; - } else { - /* Set integer division factor */ - - new_gendiv_config |= - (config->division_factor) << GCLK_GENDIV_DIV_Pos; - - /* Enable non-binary division with increased duty cycle accuracy */ - new_genctrl_config |= GCLK_GENCTRL_IDC; - } - - } - - /* Enable or disable the clock in standby mode */ - if (config->run_in_standby) { - new_genctrl_config |= GCLK_GENCTRL_RUNSTDBY; - } - - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - system_interrupt_enter_critical_section(); - - /* Select the correct generator */ - *((uint8_t*)&GCLK->GENDIV.reg) = generator; - - /* Write the new generator configuration */ - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - GCLK->GENDIV.reg = new_gendiv_config; - - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - GCLK->GENCTRL.reg = new_genctrl_config | (GCLK->GENCTRL.reg & GCLK_GENCTRL_GENEN); - - system_interrupt_leave_critical_section(); -} - -/** - * \brief Enables a Generic Clock Generator that was previously configured. - * - * Starts the clock generation of a Generic Clock Generator that was previously - * configured via a call to \ref system_gclk_gen_set_config(). - * - * \param[in] generator Generic Clock Generator index to enable - */ -void system_gclk_gen_enable( - const uint8_t generator) -{ - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - system_interrupt_enter_critical_section(); - - /* Select the requested generator */ - *((uint8_t*)&GCLK->GENCTRL.reg) = generator; - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - /* Enable generator */ - GCLK->GENCTRL.reg |= GCLK_GENCTRL_GENEN; - - system_interrupt_leave_critical_section(); -} - -/** - * \brief Disables a Generic Clock Generator that was previously enabled. - * - * Stops the clock generation of a Generic Clock Generator that was previously - * started via a call to \ref system_gclk_gen_enable(). - * - * \param[in] generator Generic Clock Generator index to disable - */ -void system_gclk_gen_disable( - const uint8_t generator) -{ - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - system_interrupt_enter_critical_section(); - - /* Select the requested generator */ - *((uint8_t*)&GCLK->GENCTRL.reg) = generator; - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - /* Disable generator */ - GCLK->GENCTRL.reg &= ~GCLK_GENCTRL_GENEN; - while (GCLK->GENCTRL.reg & GCLK_GENCTRL_GENEN) { - /* Wait for clock to become disabled */ - } - - system_interrupt_leave_critical_section(); -} - -/** - * \brief Determins if the specified Generic Clock Generator is enabled. - * - * \param[in] generator Generic Clock Generator index to check - * - * \return The enabled status. - * \retval true The Generic Clock Generator is enabled - * \retval false The Generic Clock Generator is disabled - */ -bool system_gclk_gen_is_enabled( - const uint8_t generator) -{ - bool enabled; - - system_interrupt_enter_critical_section(); - - /* Select the requested generator */ - *((uint8_t*)&GCLK->GENCTRL.reg) = generator; - /* Obtain the enabled status */ - enabled = (GCLK->GENCTRL.reg & GCLK_GENCTRL_GENEN); - - system_interrupt_leave_critical_section(); - - return enabled; -} - -/** - * \brief Retrieves the clock frequency of a Generic Clock generator. - * - * Determines the clock frequency (in Hz) of a specified Generic Clock - * generator, used as a source to a Generic Clock Channel module. - * - * \param[in] generator Generic Clock Generator index - * - * \return The frequency of the generic clock generator, in Hz. - */ -uint32_t system_gclk_gen_get_hz( - const uint8_t generator) -{ - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - system_interrupt_enter_critical_section(); - - /* Select the appropriate generator */ - *((uint8_t*)&GCLK->GENCTRL.reg) = generator; - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - /* Get the frequency of the source connected to the GCLK generator */ - uint32_t gen_input_hz = system_clock_source_get_hz( - (enum system_clock_source)GCLK->GENCTRL.bit.SRC); - - *((uint8_t*)&GCLK->GENCTRL.reg) = generator; - - uint8_t divsel = GCLK->GENCTRL.bit.DIVSEL; - - /* Select the appropriate generator division register */ - *((uint8_t*)&GCLK->GENDIV.reg) = generator; - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - uint32_t divider = GCLK->GENDIV.bit.DIV; - - system_interrupt_leave_critical_section(); - - /* Check if the generator is using fractional or binary division */ - if (!divsel && divider > 1) { - gen_input_hz /= divider; - } else if (divsel) { - gen_input_hz >>= (divider+1); - } - - return gen_input_hz; -} - -/** - * \brief Writes a Generic Clock configuration to the hardware module. - * - * Writes out a given configuration of a Generic Clock configuration to the - * hardware module. If the clock is currently running, it will be stopped. - * - * \note Once called the clock will not be running; to start the clock, - * call \ref system_gclk_chan_enable() after configuring a clock channel. - * - * \param[in] channel Generic Clock channel to configure - * \param[in] config Configuration settings for the clock - * - */ -void system_gclk_chan_set_config( - const uint8_t channel, - struct system_gclk_chan_config *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Cache the new config to reduce sync requirements */ - uint32_t new_clkctrl_config = (channel << GCLK_CLKCTRL_ID_Pos); - - /* Select the desired generic clock generator */ - new_clkctrl_config |= config->source_generator << GCLK_CLKCTRL_GEN_Pos; - - /* Disable generic clock channel */ - system_gclk_chan_disable(channel); - - /* Write the new configuration */ - GCLK->CLKCTRL.reg = new_clkctrl_config; -} - -/** - * \brief Enables a Generic Clock that was previously configured. - * - * Starts the clock generation of a Generic Clock that was previously - * configured via a call to \ref system_gclk_chan_set_config(). - * - * \param[in] channel Generic Clock channel to enable - */ -void system_gclk_chan_enable( - const uint8_t channel) -{ - system_interrupt_enter_critical_section(); - - /* Select the requested generator channel */ - *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; - - /* Enable the generic clock */ - GCLK->CLKCTRL.reg |= GCLK_CLKCTRL_CLKEN; - - system_interrupt_leave_critical_section(); -} - -/** - * \brief Disables a Generic Clock that was previously enabled. - * - * Stops the clock generation of a Generic Clock that was previously started - * via a call to \ref system_gclk_chan_enable(). - * - * \param[in] channel Generic Clock channel to disable - */ -void system_gclk_chan_disable( - const uint8_t channel) -{ - system_interrupt_enter_critical_section(); - - /* Select the requested generator channel */ - *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; - - /* Sanity check WRTLOCK */ - Assert(!GCLK->CLKCTRL.bit.WRTLOCK); - - /* Switch to known-working source so that the channel can be disabled */ - uint32_t prev_gen_id = GCLK->CLKCTRL.bit.GEN; - GCLK->CLKCTRL.bit.GEN = 0; - - /* Disable the generic clock */ - GCLK->CLKCTRL.reg &= ~GCLK_CLKCTRL_CLKEN; - while (GCLK->CLKCTRL.reg & GCLK_CLKCTRL_CLKEN) { - /* Wait for clock to become disabled */ - } - - /* Restore previous configured clock generator */ - GCLK->CLKCTRL.bit.GEN = prev_gen_id; - - system_interrupt_leave_critical_section(); -} - -/** - * \brief Determins if the specified Generic Clock channel is enabled. - * - * \param[in] channel Generic Clock Channel index - * - * \return The enabled status. - * \retval true The Generic Clock channel is enabled - * \retval false The Generic Clock channel is disabled - */ -bool system_gclk_chan_is_enabled( - const uint8_t channel) -{ - bool enabled; - - system_interrupt_enter_critical_section(); - - /* Select the requested generic clock channel */ - *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; - enabled = GCLK->CLKCTRL.bit.CLKEN; - - system_interrupt_leave_critical_section(); - - return enabled; -} - -/** - * \brief Locks a Generic Clock channel from further configuration writes. - * - * Locks a generic clock channel from further configuration writes. It is only - * possible to unlock the channel configuration through a power on reset. - * - * \param[in] channel Generic Clock channel to enable - */ -void system_gclk_chan_lock( - const uint8_t channel) -{ - system_interrupt_enter_critical_section(); - - /* Select the requested generator channel */ - *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; - - /* Lock the generic clock */ - GCLK->CLKCTRL.reg |= GCLK_CLKCTRL_WRTLOCK; - - system_interrupt_leave_critical_section(); -} - -/** - * \brief Determins if the specified Generic Clock channel is locked. - * - * \param[in] channel Generic Clock Channel index - * - * \return The lock status. - * \retval true The Generic Clock channel is locked - * \retval false The Generic Clock channel is not locked - */ -bool system_gclk_chan_is_locked( - const uint8_t channel) -{ - bool locked; - - system_interrupt_enter_critical_section(); - - /* Select the requested generic clock channel */ - *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; - locked = GCLK->CLKCTRL.bit.WRTLOCK; - - system_interrupt_leave_critical_section(); - - return locked; -} - -/** - * \brief Retrieves the clock frequency of a Generic Clock channel. - * - * Determines the clock frequency (in Hz) of a specified Generic Clock - * channel, used as a source to a device peripheral module. - * - * \param[in] channel Generic Clock Channel index - * - * \return The frequency of the generic clock channel, in Hz. - */ -uint32_t system_gclk_chan_get_hz( - const uint8_t channel) -{ - uint8_t gen_id; - - system_interrupt_enter_critical_section(); - - /* Select the requested generic clock channel */ - *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; - gen_id = GCLK->CLKCTRL.bit.GEN; - - system_interrupt_leave_critical_section(); - - /* Return the clock speed of the associated GCLK generator */ - return system_gclk_gen_get_hz(gen_id); -} diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/gclk.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/gclk.h deleted file mode 100644 index 1e3caf3..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/gclk.h +++ /dev/null @@ -1,307 +0,0 @@ -/** - * \file - * - * \brief SAM Generic Clock Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef SYSTEM_CLOCK_GCLK_H_INCLUDED -#define SYSTEM_CLOCK_GCLK_H_INCLUDED - -/** - * \addtogroup asfdoc_sam0_system_clock_group - * - * @{ - */ - -#include "compiler.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief List of available GCLK generators. - * - * List of Available GCLK generators. This enum is used in the peripheral - * device drivers to select the GCLK generator to be used for its operation. - * - * The number of GCLK generators available is device dependent. - */ -enum gclk_generator { - /** GCLK generator channel 0 */ - GCLK_GENERATOR_0, -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 0) - /** GCLK generator channel 1 */ - GCLK_GENERATOR_1, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 1) - /** GCLK generator channel 2 */ - GCLK_GENERATOR_2, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 2) - /** GCLK generator channel 3 */ - GCLK_GENERATOR_3, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 3) - /** GCLK generator channel 4 */ - GCLK_GENERATOR_4, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 4) - /** GCLK generator channel 5 */ - GCLK_GENERATOR_5, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 5) - /** GCLK generator channel 6 */ - GCLK_GENERATOR_6, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 6) - /** GCLK generator channel 7 */ - GCLK_GENERATOR_7, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 7) - /** GCLK generator channel 8 */ - GCLK_GENERATOR_8, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 8) - /** GCLK generator channel 9 */ - GCLK_GENERATOR_9, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 9) - /** GCLK generator channel 10 */ - GCLK_GENERATOR_10, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 10) - /** GCLK generator channel 11 */ - GCLK_GENERATOR_11, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 11) - /** GCLK generator channel 12 */ - GCLK_GENERATOR_12, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 12) - /** GCLK generator channel 13 */ - GCLK_GENERATOR_13, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 13) - /** GCLK generator channel 14 */ - GCLK_GENERATOR_14, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 14) - /** GCLK generator channel 15 */ - GCLK_GENERATOR_15, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 15) - /** GCLK generator channel 16 */ - GCLK_GENERATOR_16, -#endif -}; - -/** - * \brief Generic Clock Generator configuration structure. - * - * Configuration structure for a Generic Clock Generator channel. This - * structure should be initialized by the - * \ref system_gclk_gen_get_config_defaults() function before being modified by - * the user application. - */ -struct system_gclk_gen_config { - /** Source clock input channel index, see the \ref system_clock_source */ - uint8_t source_clock; - /** If \c true, the generator output level is high when disabled */ - bool high_when_disabled; - /** Integer division factor of the clock output compared to the input */ - uint32_t division_factor; - /** If \c true, the clock is kept enabled during device standby mode */ - bool run_in_standby; - /** If \c true, enables GCLK generator clock output to a GPIO pin */ - bool output_enable; -}; - -/** - * \brief Generic Clock configuration structure. - * - * Configuration structure for a Generic Clock channel. This structure - * should be initialized by the \ref system_gclk_chan_get_config_defaults() - * function before being modified by the user application. - */ -struct system_gclk_chan_config { - /** Generic Clock Generator source channel */ - enum gclk_generator source_generator; -}; - -/** \name Generic Clock Management - * @{ - */ -void system_gclk_init(void); - -/** @} */ - - -/** - * \name Generic Clock Management (Generators) - * @{ - */ - -/** - * \brief Initializes a Generic Clock Generator configuration structure to defaults. - * - * Initializes a given Generic Clock Generator configuration structure to - * a set of known default values. This function should be called on all - * new instances of these configuration structures before being modified - * by the user application. - * - * The default configuration is: - * \li Clock is generated undivided from the source frequency - * \li Clock generator output is low when the generator is disabled - * \li The input clock is sourced from input clock channel 0 - * \li Clock will be disabled during sleep - * \li The clock output will not be routed to a physical GPIO pin - * - * \param[out] config Configuration structure to initialize to default values - */ -static inline void system_gclk_gen_get_config_defaults( - struct system_gclk_gen_config *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Default configuration values */ - config->division_factor = 1; - config->high_when_disabled = false; -#if SAML21 || SAML22 - config->source_clock = GCLK_SOURCE_OSC16M; -#elif (SAMC20) || (SAMC21) - config->source_clock = GCLK_SOURCE_OSC48M; -#else - config->source_clock = GCLK_SOURCE_OSC8M; -#endif - config->run_in_standby = false; - config->output_enable = false; -} - -void system_gclk_gen_set_config( - const uint8_t generator, - struct system_gclk_gen_config *const config); - -void system_gclk_gen_enable( - const uint8_t generator); - -void system_gclk_gen_disable( - const uint8_t generator); - -bool system_gclk_gen_is_enabled( - const uint8_t generator); - -/** @} */ - - -/** - * \name Generic Clock Management (Channels) - * @{ - */ - -/** - * \brief Initializes a Generic Clock configuration structure to defaults. - * - * Initializes a given Generic Clock configuration structure to a set of - * known default values. This function should be called on all new - * instances of these configuration structures before being modified by the - * user application. - * - * The default configuration is as follows: - * \li Clock is sourced from the Generic Clock Generator channel 0 - * \li Clock configuration will not be write-locked when set - * - * \param[out] config Configuration structure to initialize to default values - */ -static inline void system_gclk_chan_get_config_defaults( - struct system_gclk_chan_config *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Default configuration values */ - config->source_generator = GCLK_GENERATOR_0; -} - -void system_gclk_chan_set_config( - const uint8_t channel, - struct system_gclk_chan_config *const config); - -void system_gclk_chan_enable( - const uint8_t channel); - -void system_gclk_chan_disable( - const uint8_t channel); - -bool system_gclk_chan_is_enabled( - const uint8_t channel); - -void system_gclk_chan_lock( - const uint8_t channel); - -bool system_gclk_chan_is_locked( - const uint8_t channel); - -/** @} */ - - -/** - * \name Generic Clock Frequency Retrieval - * @{ - */ - -uint32_t system_gclk_gen_get_hz( - const uint8_t generator); - -uint32_t system_gclk_chan_get_hz( - const uint8_t channel); - -/** @} */ - -#ifdef __cplusplus -} -#endif - -/** @} */ - -#endif diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/i2s.c b/feather_sensor_lte/libraries/Adafruit_ASFcore/i2s.c deleted file mode 100644 index 31fe2d9..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/i2s.c +++ /dev/null @@ -1,750 +0,0 @@ -/** - * \file - * - * \brief SAM I2S - Inter-IC Sound Controller - * - * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#include "i2s.h" - -/** - * \brief Initializes a hardware I2S module instance - * - * Enables the clock and initialize the I2S module. - * - * \param[in,out] module_inst Pointer to the software module instance struct - * \param[in] hw Pointer to the TCC hardware module - * - * \return Status of the initialization procedure. - * - * \retval STATUS_OK The module was initialized successfully - * \retval STATUS_BUSY Hardware module was busy when the - * initialization procedure was attempted - * \retval STATUS_ERR_DENIED Hardware module was already enabled - */ -enum status_code i2s_init( - struct i2s_module *const module_inst, - I2s *hw) -{ - Assert(module_inst); - Assert(hw); - - /* Enable the user interface clock in the PM */ - system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, PM_APBCMASK_I2S); - - /* Status check */ - uint32_t ctrla; - ctrla = module_inst->hw->CTRLA.reg; - if (ctrla & I2S_CTRLA_ENABLE) { - if (ctrla & (I2S_CTRLA_SEREN1 | - I2S_CTRLA_SEREN0 | I2S_CTRLA_CKEN1 | I2S_CTRLA_CKEN0)) { - return STATUS_BUSY; - } else { - return STATUS_ERR_DENIED; - } - } - - /* Initialize module */ - module_inst->hw = hw; - - /* Initialize serializers */ -#if I2S_CALLBACK_MODE == true - int i, j; - for (i = 0; i < 2; i ++) { - for (j = 0; j < I2S_SERIALIZER_CALLBACK_N; j ++) { - module_inst->serializer[i].callback[j] = NULL; - } - module_inst->serializer[i].registered_callback_mask = 0; - module_inst->serializer[i].enabled_callback_mask = 0; - - module_inst->serializer[i].job_buffer = NULL; - module_inst->serializer[i].job_status = STATUS_OK; - module_inst->serializer[i].requested_words = 0; - module_inst->serializer[i].transferred_words = 0; - - module_inst->serializer[i].mode = I2S_SERIALIZER_RECEIVE; - module_inst->serializer[i].data_size = I2S_DATA_SIZE_32BIT; - } - - _i2s_instances[0] = module_inst; - - system_interrupt_enable(SYSTEM_INTERRUPT_MODULE_I2S); -#endif - - return STATUS_OK; -} - - -/** - * \brief Configure specified I2S clock unit - * - * Enables the clock and initialize the clock unit, based on the given - * configurations. - * - * \param[in,out] module_inst Pointer to the software module instance struct - * \param[in] clock_unit I2S clock unit to initialize and configure - * \param[in] config Pointer to the I2S clock unit configuration - * options struct - * - * \return Status of the configuration procedure. - * - * \retval STATUS_OK The module was initialized successfully - * \retval STATUS_BUSY Hardware module was busy when the - * configuration procedure was attempted - * \retval STATUS_ERR_DENIED Hardware module was already enabled - * \retval STATUS_ERR_INVALID_ARG Invalid divider value or - * MCK direction setting conflict - */ -enum status_code i2s_clock_unit_set_config( - struct i2s_module *const module_inst, - const enum i2s_clock_unit clock_unit, - const struct i2s_clock_unit_config *config) -{ - Assert(module_inst); - Assert(module_inst->hw); - Assert(clock_unit < I2S_CLOCK_UNIT_N); - Assert(config); - - /* Status check */ - uint32_t ctrla, syncbusy; - syncbusy = module_inst->hw->SYNCBUSY.reg; - ctrla = module_inst->hw->CTRLA.reg; - - /* Busy ? */ - if (syncbusy & (I2S_SYNCBUSY_CKEN0 << clock_unit)) { - return STATUS_BUSY; - } - /* Already enabled ? */ - if (ctrla & (I2S_CTRLA_CKEN0 << clock_unit)) { - return STATUS_ERR_DENIED; - } - /* Parameter check */ - if (config->clock.mck_src && config->clock.mck_out_enable) { - return STATUS_ERR_INVALID_ARG; - } - - /* Initialize Clock Unit */ - uint32_t clkctrl = - (config->clock.mck_out_invert ? I2S_CLKCTRL_MCKOUTINV : 0) | - (config->clock.sck_out_invert ? I2S_CLKCTRL_SCKOUTINV : 0) | - (config->frame.frame_sync.invert_out ? I2S_CLKCTRL_FSOUTINV : 0) | - (config->clock.mck_out_enable ? I2S_CLKCTRL_MCKEN : 0) | - (config->clock.mck_src ? I2S_CLKCTRL_MCKSEL : 0) | - (config->clock.sck_src ? I2S_CLKCTRL_SCKSEL : 0) | - (config->frame.frame_sync.invert_use ? I2S_CLKCTRL_FSINV : 0) | - (config->frame.frame_sync.source ? I2S_CLKCTRL_FSSEL : 0) | - (config->frame.data_delay ? I2S_CLKCTRL_BITDELAY : 0); - - uint8_t div_val = config->clock.mck_out_div; - if ((div_val > 0x21) || (div_val == 0)) { - return STATUS_ERR_INVALID_ARG; - } else { - div_val --; - } - clkctrl |= I2S_CLKCTRL_MCKOUTDIV(div_val); - - div_val = config->clock.sck_div; - if ((div_val > 0x21) || (div_val == 0)) { - return STATUS_ERR_INVALID_ARG; - } else { - div_val --; - } - clkctrl |= I2S_CLKCTRL_MCKDIV(div_val); - - uint8_t number_slots = config->frame.number_slots; - if (number_slots > 8) { - return STATUS_ERR_INVALID_ARG; - } else if (number_slots > 0) { - number_slots --; - } - clkctrl |= - I2S_CLKCTRL_NBSLOTS(number_slots) | - I2S_CLKCTRL_FSWIDTH(config->frame.frame_sync.width) | - I2S_CLKCTRL_SLOTSIZE(config->frame.slot_size); - - /* Write clock unit configurations */ - module_inst->hw->CLKCTRL[clock_unit].reg = clkctrl; - - /* Select general clock source */ - const uint8_t i2s_gclk_ids[2] = {I2S_GCLK_ID_0, I2S_GCLK_ID_1}; - struct system_gclk_chan_config gclk_chan_config; - system_gclk_chan_get_config_defaults(&gclk_chan_config); - gclk_chan_config.source_generator = config->clock.gclk_src; - system_gclk_chan_set_config(i2s_gclk_ids[clock_unit], &gclk_chan_config); - system_gclk_chan_enable(i2s_gclk_ids[clock_unit]); - - /* Initialize pins */ - struct system_pinmux_config pin_config; - system_pinmux_get_config_defaults(&pin_config); - if (config->mck_pin.enable) { - pin_config.mux_position = config->mck_pin.mux; - system_pinmux_pin_set_config(config->mck_pin.gpio, &pin_config); - } - if (config->sck_pin.enable) { - pin_config.mux_position = config->sck_pin.mux; - system_pinmux_pin_set_config(config->sck_pin.gpio, &pin_config); - } - if (config->fs_pin.enable) { - pin_config.mux_position = config->fs_pin.mux; - system_pinmux_pin_set_config(config->fs_pin.gpio, &pin_config); - } - - return STATUS_OK; -} - - -/** - * \brief Configure specified I2S serializer - * - * Enables the clock and initialize the serializer, based on the given - * configurations. - * - * \param[in,out] module_inst Pointer to the software module instance struct - * \param[in] serializer I2S serializer to initialize and configure - * \param[in] config Pointer to the I2S serializer configuration - * options struct - * - * \return Status of the configuration procedure. - * - * \retval STATUS_OK The module was initialized successfully - * \retval STATUS_BUSY Hardware module was busy when the - * configuration procedure was attempted - * \retval STATUS_ERR_DENIED Hardware module was already enabled - */ -enum status_code i2s_serializer_set_config( - struct i2s_module *const module_inst, - const enum i2s_serializer serializer, - const struct i2s_serializer_config *config) -{ - Assert(module_inst); - Assert(module_inst->hw); - Assert(serializer < I2S_SERIALIZER_N); - Assert(config); - - /* Status check */ - uint32_t ctrla, syncbusy; - syncbusy = module_inst->hw->SYNCBUSY.reg; - ctrla = module_inst->hw->CTRLA.reg; - - /* Busy ? */ - if (syncbusy & ((I2S_SYNCBUSY_SEREN0 | I2S_SYNCBUSY_DATA0) << serializer)) { - return STATUS_BUSY; - } - /* Already enabled ? */ - if (ctrla & (I2S_CTRLA_CKEN0 << serializer)) { - return STATUS_ERR_DENIED; - } - - /* Initialize Serializer */ - uint32_t serctrl = - (config->loop_back ? I2S_SERCTRL_RXLOOP : 0) | - (config->dma_usage ? I2S_SERCTRL_DMA : 0) | - (config->mono_mode ? I2S_SERCTRL_MONO : 0) | - (config->disable_data_slot[7] ? I2S_SERCTRL_SLOTDIS7 : 0) | - (config->disable_data_slot[6] ? I2S_SERCTRL_SLOTDIS6 : 0) | - (config->disable_data_slot[5] ? I2S_SERCTRL_SLOTDIS5 : 0) | - (config->disable_data_slot[4] ? I2S_SERCTRL_SLOTDIS4 : 0) | - (config->disable_data_slot[3] ? I2S_SERCTRL_SLOTDIS3 : 0) | - (config->disable_data_slot[2] ? I2S_SERCTRL_SLOTDIS2 : 0) | - (config->disable_data_slot[1] ? I2S_SERCTRL_SLOTDIS1 : 0) | - (config->disable_data_slot[0] ? I2S_SERCTRL_SLOTDIS0 : 0) | - (config->transfer_lsb_first ? I2S_SERCTRL_BITREV : 0) | - (config->data_adjust_left_in_word ? I2S_SERCTRL_WORDADJ : 0) | - (config->data_adjust_left_in_slot ? I2S_SERCTRL_SLOTADJ : 0) | - (config->data_padding ? I2S_SERCTRL_TXSAME : 0); - - if (config->clock_unit < I2S_CLOCK_UNIT_N) { - serctrl |= (config->clock_unit ? I2S_SERCTRL_CLKSEL : 0); - } else { - return STATUS_ERR_INVALID_ARG; - } - - serctrl |= - I2S_SERCTRL_SERMODE(config->mode) | - I2S_SERCTRL_TXDEFAULT(config->line_default_state) | - I2S_SERCTRL_DATASIZE(config->data_size) | - I2S_SERCTRL_EXTEND(config->bit_padding); - - /* Write Serializer configuration */ - module_inst->hw->SERCTRL[serializer].reg = serctrl; - - /* Initialize pins */ - struct system_pinmux_config pin_config; - system_pinmux_get_config_defaults(&pin_config); - if (config->data_pin.enable) { - pin_config.mux_position = config->data_pin.mux; - system_pinmux_pin_set_config(config->data_pin.gpio, &pin_config); - } - - /* Save configure */ - module_inst->serializer[serializer].mode = config->mode; - module_inst->serializer[serializer].data_size = config->data_size; - - return STATUS_OK; -} - - - -/** - * \brief Retrieves the current module status. - * - * Retrieves the status of the module, giving overall state information. - * - * \param[in] module_inst Pointer to the I2S software instance struct - * - * \return Bitmask of \c I2S_STATUS_* flags - * - * \retval I2S_STATUS_SYNC_BUSY Module is busy synchronization - * \retval I2S_STATUS_TRANSMIT_UNDERRUN(x) Serializer x (0~1) is underrun - * \retval I2S_STATUS_TRANSMIT_READY(x) Serializer x (0~1) is ready to - * transmit new data word - * \retval I2S_STATUS_RECEIVE_OVERRUN(x) Serializer x (0~1) is overrun - * \retval I2S_STATUS_RECEIVE_READY(x) Serializer x (0~1) has data ready to - * read - */ -uint32_t i2s_get_status( - const struct i2s_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - uint32_t intflag = module_inst->hw->INTFLAG.reg; - uint32_t status; - if (module_inst->hw->SYNCBUSY.reg) { - status = I2S_STATUS_SYNC_BUSY; - } else { - status = 0; - } - if (intflag & I2S_INTFLAG_TXUR0) { - status |= I2S_STATUS_TRANSMIT_UNDERRUN(0); - } - if (intflag & I2S_INTFLAG_TXUR1) { - status |= I2S_STATUS_TRANSMIT_UNDERRUN(1); - } - if ((intflag & I2S_INTFLAG_TXRDY0) && - !module_inst->hw->SYNCBUSY.bit.DATA0) { - status |= I2S_STATUS_TRANSMIT_READY(0); - } - if ((intflag & I2S_INTFLAG_TXRDY1) && - !module_inst->hw->SYNCBUSY.bit.DATA1) { - status |= I2S_STATUS_TRANSMIT_READY(1); - } - if (intflag & I2S_INTFLAG_RXOR0) { - status |= I2S_STATUS_RECEIVE_OVERRUN(0); - } - if (intflag & I2S_INTFLAG_RXOR1) { - status |= I2S_STATUS_RECEIVE_OVERRUN(1); - } - if (intflag & I2S_INTFLAG_RXRDY0) { - status |= I2S_STATUS_RECEIVE_READY(0); - } - if (intflag & I2S_INTFLAG_RXRDY1) { - status |= I2S_STATUS_RECEIVE_READY(1); - } - return status; -} - -/** - * \brief Clears a module status flags. - * - * Clears the given status flags of the module. - * - * \param[in] module_inst Pointer to the I2S software instance struct - * \param[in] status Bitmask of \c I2S_STATUS_* flags to clear - */ -void i2s_clear_status( - const struct i2s_module *const module_inst, - uint32_t status) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - uint32_t intflag = 0; - - if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { - intflag = I2S_INTFLAG_TXUR0; - } - if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { - intflag = I2S_INTFLAG_TXUR1; - } - if (status & I2S_STATUS_TRANSMIT_READY(0)) { - intflag = I2S_INTFLAG_TXRDY0; - } - if (status & I2S_STATUS_TRANSMIT_READY(1)) { - intflag = I2S_INTFLAG_TXRDY1; - } - if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { - intflag = I2S_INTFLAG_RXOR0; - } - if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { - intflag = I2S_INTFLAG_RXOR1; - } - if (status & I2S_STATUS_RECEIVE_READY(0)) { - intflag = I2S_INTFLAG_RXRDY0; - } - if (status & I2S_STATUS_RECEIVE_READY(1)) { - intflag = I2S_INTFLAG_RXRDY1; - } - module_inst->hw->INTFLAG.reg = intflag; -} - -/** - * \brief Enable interrupts on status set - * - * Enable the given status interrupt request from the I2S module. - * - * \param[in] module_inst Pointer to the I2S software instance struct - * \param[in] status Status interrupts to enable - * - * \return Status of enable procedure - * - * \retval STATUS_OK Interrupt is enabled successfully - * \retval STATUS_ERR_INVALID_ARG Status with no interrupt is passed - */ -enum status_code i2s_enable_status_interrupt( - struct i2s_module *const module_inst, - uint32_t status) -{ - /* Sanity check arguments */ - Assert(module_inst); - - /* No sync busy interrupt */ - if (status & I2S_STATUS_SYNC_BUSY) { - return STATUS_ERR_INVALID_ARG; - } - Assert(module_inst->hw); - - uint32_t intflag = 0; - if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { - intflag = I2S_INTFLAG_TXUR0; - } - if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { - intflag = I2S_INTFLAG_TXUR1; - } - if (status & I2S_STATUS_TRANSMIT_READY(0)) { - intflag = I2S_INTFLAG_TXRDY0; - } - if (status & I2S_STATUS_TRANSMIT_READY(1)) { - intflag = I2S_INTFLAG_TXRDY1; - } - if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { - intflag = I2S_INTFLAG_RXOR0; - } - if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { - intflag = I2S_INTFLAG_RXOR1; - } - if (status & I2S_STATUS_RECEIVE_READY(0)) { - intflag = I2S_INTFLAG_RXRDY0; - } - if (status & I2S_STATUS_RECEIVE_READY(1)) { - intflag = I2S_INTFLAG_RXRDY1; - } - module_inst->hw->INTENSET.reg = intflag; - return STATUS_OK; -} - -/** - * \brief Disable interrupts on status set - * - * Disable the given status interrupt request from the I2S module. - * - * \param[in] module_inst Pointer to the I2S software instance struct - * \param[in] status Status interrupts to disable - */ -void i2s_disable_status_interrupt( - struct i2s_module *const module_inst, - uint32_t status) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - uint32_t intflag = 0; - if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { - intflag = I2S_INTFLAG_TXUR0; - } - if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { - intflag = I2S_INTFLAG_TXUR1; - } - if (status & I2S_STATUS_TRANSMIT_READY(0)) { - intflag = I2S_INTFLAG_TXRDY0; - } - if (status & I2S_STATUS_TRANSMIT_READY(1)) { - intflag = I2S_INTFLAG_TXRDY1; - } - if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { - intflag = I2S_INTFLAG_RXOR0; - } - if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { - intflag = I2S_INTFLAG_RXOR1; - } - if (status & I2S_STATUS_RECEIVE_READY(0)) { - intflag = I2S_INTFLAG_RXRDY0; - } - if (status & I2S_STATUS_RECEIVE_READY(1)) { - intflag = I2S_INTFLAG_RXRDY1; - } - module_inst->hw->INTENCLR.reg = intflag; -} - - -/** - * \brief Write buffer to the specified Serializer of I2S module - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer The serializer to write to - * \param[in] buffer The data buffer to write - * \param[in] size Number of data words to write - * - * \return Status of the initialization procedure. - * - * \retval STATUS_OK The data was sent successfully - * \retval STATUS_ERR_DENIED The module or serializer is disabled - * \retval STATUS_ERR_INVALID_ARG An invalid buffer pointer was supplied - */ -enum status_code i2s_serializer_write_buffer_wait( - const struct i2s_module *const module_inst, - enum i2s_serializer serializer, - void *buffer, uint32_t size) -{ - Assert(module_inst); - Assert(module_inst->hw); - Assert(serializer < I2S_SERIALIZER_N); - Assert(buffer); - - if (size == 0) { - return STATUS_OK; - } - - uint8_t data_size = 1; /* number of bytes */ - struct i2s_serializer_module *data_module = (struct i2s_serializer_module *) - &module_inst->serializer[serializer]; - - /* Check buffer */ - switch(data_module->data_size) { - case I2S_DATA_SIZE_32BIT: - case I2S_DATA_SIZE_24BIT: - case I2S_DATA_SIZE_20BIT: - case I2S_DATA_SIZE_18BIT: - if ((uint32_t)buffer & 0x3) { - return STATUS_ERR_INVALID_ARG; - } - data_size = 4; - break; - case I2S_DATA_SIZE_16BIT: - case I2S_DATA_SIZE_16BIT_COMPACT: - if ((uint32_t)buffer & 0x1) { - return STATUS_ERR_INVALID_ARG; - } - data_size = 2; - break; - default: - break; - } - - /* Check status */ - if (!(module_inst->hw->CTRLA.reg & - (I2S_CTRLA_ENABLE | (I2S_CTRLA_SEREN0 << serializer)))) { - return STATUS_ERR_DENIED; - } - - /* Write */ - uint32_t i; - uint32_t sync_bit = I2S_SYNCBUSY_DATA0 << serializer; - uint32_t ready_bit = I2S_INTFLAG_TXRDY0 << serializer; - if (4 == data_size) { - uint32_t *p32 = (uint32_t*)buffer; - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Tx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - module_inst->hw->DATA[serializer].reg = p32[i]; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } else if (2 == data_size) { - uint16_t *p16 = (uint16_t*)buffer; - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Tx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - module_inst->hw->DATA[serializer].reg = p16[i]; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } else { - uint8_t *p8 = (uint8_t*)buffer; - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Tx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - module_inst->hw->DATA[serializer].reg = p8[i]; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } - - return STATUS_OK; -} - -/** - * \brief Read from the specified Serializer of I2S module to a buffer - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer The serializer to write to - * \param[in] buffer The buffer to fill read data (NULL to discard) - * \param[in] size Number of data words to read - * - * \return Status of the initialization procedure. - * - * \retval STATUS_OK The data was sent successfully - * \retval STATUS_ERR_DENIED The module or serializer is disabled - * \retval STATUS_ERR_INVALID_ARG An invalid buffer pointer was supplied - */ -enum status_code i2s_serializer_read_buffer_wait( - const struct i2s_module *const module_inst, - enum i2s_serializer serializer, - void *buffer, uint32_t size) -{ - Assert(module_inst); - Assert(module_inst->hw); - - if (size == 0) { - return STATUS_OK; - } - - uint8_t data_size = 1; /* number of bytes */ - struct i2s_serializer_module *data_module = (struct i2s_serializer_module *) - &module_inst->serializer[serializer]; - - /* Check buffer */ - switch(data_module->data_size) { - case I2S_DATA_SIZE_32BIT: - case I2S_DATA_SIZE_24BIT: - case I2S_DATA_SIZE_20BIT: - case I2S_DATA_SIZE_18BIT: - if ((uint32_t)buffer & 0x3) { - return STATUS_ERR_INVALID_ARG; - } - data_size = 4; - break; - case I2S_DATA_SIZE_16BIT: - case I2S_DATA_SIZE_16BIT_COMPACT: - if ((uint32_t)buffer & 0x1) { - return STATUS_ERR_INVALID_ARG; - } - data_size = 2; - break; - default: - break; - } - - /* Check status */ - if (!(module_inst->hw->CTRLA.reg & - (I2S_CTRLA_ENABLE | (I2S_CTRLA_SEREN0 << serializer)))) { - return STATUS_ERR_DENIED; - } - - /* Read */ - uint32_t i; - uint32_t sync_bit = I2S_SYNCBUSY_DATA0 << serializer; - uint32_t ready_bit = I2S_INTFLAG_RXRDY0 << serializer; - if (buffer == NULL) { - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Rx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - module_inst->hw->DATA[serializer].reg; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } - else if (4 == data_size) { - uint32_t *p32 = (uint32_t*)buffer; - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Rx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - p32[i] = module_inst->hw->DATA[serializer].reg; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } else if (2 == data_size) { - uint16_t *p16 = (uint16_t*)buffer; - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Rx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - p16[i] = module_inst->hw->DATA[serializer].reg; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } else { - uint8_t *p8 = (uint8_t*)buffer; - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Tx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - p8[i] = module_inst->hw->DATA[serializer].reg; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } - - return STATUS_OK; -} diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/i2s.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/i2s.h deleted file mode 100644 index 9911e6d..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/i2s.h +++ /dev/null @@ -1,1404 +0,0 @@ -/** - * \file - * - * \brief SAM I2S - Inter-IC Sound Controller - * - * Copyright (c) 2014-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#ifndef I2S_H_INCLUDED -#define I2S_H_INCLUDED - -/** - * \defgroup asfdoc_sam0_i2s_group SAM Inter-IC Sound Controller Driver (I2S) - * - * This driver for Atmel® | SMART SAM devices provides an interface for the configuration - * and management of the device's Inter-IC Sound Controller functionality. - * - * The following driver API modes are covered by this manual: - * - Polled APIs - * \if I2S_CALLBACK_MODE - * - Callback APIs - * \endif - * - * The following peripherals are used by this module: - * - I2S (Inter-IC Sound Controller) - * - * The following devices can use this module: - * - Atmel | SMART SAM D21 - * - Atmel | SMART SAM DA1 - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_i2s_prerequisites - * - \ref asfdoc_sam0_i2s_module_overview - * - \ref asfdoc_sam0_i2s_special_considerations - * - \ref asfdoc_sam0_i2s_extra_info - * - \ref asfdoc_sam0_i2s_examples - * - \ref asfdoc_sam0_i2s_api_overview - * - * \section asfdoc_sam0_i2s_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * \section asfdoc_sam0_i2s_module_overview Module Overview - * - * The I2S provides bidirectional, synchronous, digital audio link with external - * audio devices through these signal pins: - * - Serial Data (SDm) - * - Frame Sync (FSn) - * - Serial Clock (SCKn) - * - Master Clock (MCKn) - * - * The I2S consists of 2 Clock Units and 2 Serializers, which can be separately - * configured and enabled, to provide varies functionalities as follow: - * - Communicate to Audio CODECs as Master or Slave, or provides clock and - * frame sync signals as Controller - * - Communicate to DAC or ADC through dedicated I2S serial interface - * - Communicate to multi-slot or multiple stereo DACs or ADCs, via - * Time Division Multiplexed (TDM) format - * - Reading mono or stereo MEMS microphones, using the Pulse Density - * Modulation (PDM) interface - * - * The I2S supports compact stereo data word, where left channel data bits are - * in lower half and right channel data bits are in upper half. It reduces the - * number of data words for stereo audio data and the DMA bandwidth. - * - * In master mode, the frame is configured by number of slots and slot size, and - * allows range covering 16fs to 1024fs MCK, to provide oversampling clock to an - * external audio CODEC or digital signal processor (DSP). - * - * A block diagram of the I2S can be seen in - * \ref asfdoc_sam0_i2s_module_block_diagram "the figure below". - * - * \anchor asfdoc_sam0_i2s_module_block_diagram - * \image html i2s_blocks.svg "I2S Block Diagram" - * - * This driver for I2S module provides an interface to - * - initialize and control I2S module - * - configure and control the I2S Clock Unit and Serializer - * - transmit/receive data through I2S Serializer - * - * \subsection asfdoc_sam0_i2s_module_overview_clocks Clocks - * - * To use I2S module, the I2S bus interface clock (clk_i2s) must be enabled via - * Power Manager. - * - * For each I2S Clock Unit, a generic clock (gclk_i2s_n) is connnected. When I2S - * works in master mode the generic clock is used. It should be prepared before - * clock unit is used. In master mode the input generic clock will be used as - * MCK for SCKn and FSn generation, in addition, the MCK could be devided and - * output to I2S MCKn pin, as oversampling clock to external audio device. - * - * The I2S Serializer uses clock and control signal from Clock Unit to handle - * transfer. Select different clock unit with different configurations allows - * the I2S to work as master or slave, to work on non-related clocks. - * - * When using the driver with ASF, enabling the register interface is normally - * done by the \c init function. - * The gclk source for the asynchronous domain is normally configured and set - * through the _configuration struct_ / _init_ function. - * If gclk source != 0 is used, this source has to be configured and enabled - * through invoking the system_gclk driver function when needed, or modifying - * conf_clock.h to enable it at the beginning. - * - * \subsection asfdoc_sam0_i2s_module_overview_frame Audio Frame Generation - * - * Audio sample data for all channels are sent in frames, one frame can consist - * 1 - 8 slots where each slot can be configured to a size 8-bit, 16-bit, 24-bit - * or 32-bit. The audio frame synch clock is generated by the I2S Clock unit in - * the master/controller mode. The frame rate (or frame sync frequency) is - * calculated as follow: - * - * FS = SCK / number_of_slots / number_of_bits_in_slot - * - * The serial clock (SCK) source is either an external source (slave mode) or - * generated by the I2S clock unit (controller or master mode) using the MCK as - * source. - * - * SCK = MCK / sck_div - * \note SCK generation division value is MCKDIV in register. - * - * MCK is either an external source or generated using the gclk input from a - * generic clock generator. - * - * \subsection asfdoc_sam0_i2s_module_overview_mode Master, Controller and Slave modes - * - * The i2s module has three modes: master, controller and slave. - * - * \subsubsection asfdoc_sam0_i2s_module_overview_mode_mst Master - * In master mode the module will control the data flow on the i2s bus and can - * be responsible for clock generation. The Serializers are enabled and will - * transmit/receive data. On a bus with only master and slave the SCK and FS - * clock signal will be outputted on the SCK and FS pin on the master module. - * MCK can optionally be outputted on the MCK pin, if there is a controller - * module on the bus the SCK, FS and optionally the MCK clock is sourced from - * the same pins. Serial data will be trancieved on the SD pin in both - * scenarios. - * - * \subsubsection asfdoc_sam0_i2s_module_overview_mode_ctl Controller - * In controller mode the module will generate the clock signals, but the - * Serializers are disabled and no data will be transmitted/received by the - * module in this mode. The clock signals is outputted on the SCK, FS and - * optionally the MCK pin. - * - * \subsubsection asfdoc_sam0_i2s_module_overview_mode_slv Slave - * In slave mode the module will use the SCK and FS clock source from the master - * or the controller which is received on the SCK and FS pin. The MCK can - * optionally be sourced externally on the MCK pin. The Serializers are enabled - * and will tranceive data on the SD pin. All data flow is controlled by the - * master. - * - * \subsubsection asfdoc_sam0_i2s_module_overview_mode_chg Switch modes - * The mode switching between master, controller and slave modes are actually - * done by modifying the source mode of I2S pins. - * The source mode of I2S pins are selected by writing corresponding bits in - * CLKCTRLn. - * Since source mode switching changes the direction of pin, the mode must be - * changed when the I2S Clock Unit is stopped. - * - * \subsection asfdoc_sam0_i2s_module_overview_data Data Stream Reception/Transmission - * - * The I2S module support several data stream formats: - * - I2S format - * - Time Division Multiplexed (TDM) format - * - Pulse Density Modulation (PDM) format (reception only) - * - * Basically the I2S module can send several words within each frame, it's more - * like TDM format. With adjust to the number of data words in a frame, the FS - * width, the FS to data bits delay, etc., the module is able to handle I2S - * compliant data stream. - * - * Also the Serializer can receive PDM format data stream, which allows the I2S - * module receive 1 PDM data on each SCK edge. - * - * \subsubsection asfdoc_sam0_i2s_module_overview_data_i2s I2S Stream Reception/Transmission - * - * For 2-channel I2S compliant data stream format the i2s module uses the FS - * line as word select (WS) signal and will send left channel data word on low - * WS level and right channel data word on high WS level as specified in the I2S - * standard. The supported word sizes are 8-, 16-, 18-, 20-, 24- and 32- bit. - * - * Thus for I2S stream, the following settings should be applied to the module: - * - Data starting delay after FS transition : one SCK period - * - FS width : half of frame - * - Data bits adjust in word : left-adjusted - * - Bit transmitting order : MSB first - * - * Following is an example for I2S application connections and waveforms. See - * \ref asfdoc_sam0_i2s_module_i2s_example_diagram "the figure below". - * - * \anchor asfdoc_sam0_i2s_module_i2s_example_diagram - * \image html i2s_example.svg "I2S Example Diagram" - * - * \subsubsection asfdoc_sam0_i2s_module_overview_data_tdm TDM Stream Reception/Transmission - * In TDM format, the module sends several data words in each frame. For this - * data stream format most of the configurations could be adjusted: - * - Main Frame related settings are as follow: - * - Frame Sync (FS) options: - * - the active edge of the FS (or if FS is inverted before use) - * - the width of the FS - * - the delay between FS to first data bit - * - Data alignment in slot - * - The number of slots and slot size can be adjusted, it has been mentioned - * in \ref asfdoc_sam0_i2s_module_overview_frame - * - The data word size is controlled by Serializer, it can be chosen among - * 8, 16, 18, 20, 24 and 32 bits. - * - * The general TDM waveform generation is as follow: - * - * \anchor asfdoc_sam0_i2s_module_tdm_wave_diagram - * \image html tdm_wave.svg "TDM Waveform generation" - * - * Some other settings could also be found to set up clock, data formatting and - * pin mux. - * refer to \ref i2s_clock_unit_config "Clock Unit Configurations" - * and \ref i2s_serializer_config "Serializer Configurations" for more - * details. - * - * Following is examples for different application use cases. - * - * See \ref asfdoc_sam0_i2s_module_tdm_timeslot_example_diagram "here" for - * the Time Slot Application connection and waveform example. - * - * \anchor asfdoc_sam0_i2s_module_tdm_timeslot_example_diagram - * \image html tdm_timeslot_example.svg "Codec Example Diagram" - * - * See \ref asfdoc_sam0_i2s_module_tdm_codec_example_diagram "here" for the - * Codec Application connection and waveform example. - * - * \anchor asfdoc_sam0_i2s_module_tdm_codec_example_diagram - * \image html tdm_codec_example.svg "Time Slot Example Diagram" - * - * \subsubsection asfdoc_sam0_i2s_module_overview_data_pdm PDM Reception - * The I2S Serializer integrates PDM reception feature, to use this feature, - * simply select PDM2 mode in Serializer configuration. In PDM2 mode, it assumes - * two microphones are input for stereo stream. The left microphone bits will - * be stored in lower half and right microphone bits in upper half of the data - * word, like in compact stereo format. - * - * See \ref asfdoc_sam0_i2s_module_pdm_example_diagram "following figure" for an - * example of PDM Microphones Application with both left and right channel - * microphone connected. - * - * \anchor asfdoc_sam0_i2s_module_pdm_example_diagram - * \image html pdm_example.svg "Time PDM2 Example Diagram" - * - * \subsubsection asfdoc_sam0_i2s_module_overview_data_fmt MONO and Compact Data - * The I2S Serializer can accept some pre-defined data format and generates - * the data stream in specified way. - * - * When transmitting data, the Serializer can work in MONO mode: assum input - * is single channel mono data on left channel and copy it to right channel - * automatically. - * - * Also the I2S Serializer can support compact stereo data word. The data word - * size of the Serializer can be set to \ref I2S_DATA_SIZE_16BIT_COMPACT - * "16-bit compact" or \ref I2S_DATA_SIZE_8BIT_COMPACT "8-bit compact", with - * these option I2S Serializer will compact left channel data and right channel - * data together, the left channel data will take lower bytes and right channel - * data take higher bytes. - * - * \subsection asfdoc_sam0_i2s_module_overview_loop Loop-back Mode - * The I2S can be configured to loop back the Transmitter to Receiver. In this - * mode Serializer's input will be connected to another Serializer's output - * internally. - * - * \subsection asfdoc_sam0_i2s_module_overview_sleep Sleep Modes - * The I2S will continue to operate in any sleep mode, where the selected source - * clocks are running. - * - * \section asfdoc_sam0_i2s_special_considerations Special Considerations - * - * There is no special considerations for I2S module. - * - * \section asfdoc_sam0_i2s_extra_info Extra Information - * - * For extra information see \ref asfdoc_sam0_i2s_extra. This includes: - * - \ref asfdoc_sam0_i2s_extra_acronyms - * - \ref asfdoc_sam0_i2s_extra_dependencies - * - \ref asfdoc_sam0_i2s_extra_errata - * - \ref asfdoc_sam0_i2s_extra_history - * - * \section asfdoc_sam0_i2s_examples Examples - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_i2s_exqsg. - * - * - * \section asfdoc_sam0_i2s_api_overview API Overview - * @{ - */ - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include - -#if I2S_CALLBACK_MODE == true -# include - -#if !defined(__DOXYGEN__) -extern struct i2s_module *_i2s_instances[I2S_INST_NUM]; -#endif - -/** Forward definition of the device instance */ -struct i2s_module; - -/** Type of the callback functions */ -typedef void (*i2s_serializer_callback_t) - (struct i2s_module *const module); - -/** - * \brief I2S Serializer Callback enum - */ -enum i2s_serializer_callback { - /** Callback for buffer read/write finished */ - I2S_SERIALIZER_CALLBACK_BUFFER_DONE, - /** Callback for Serializer overrun/underrun */ - I2S_SERIALIZER_CALLBACK_OVER_UNDER_RUN, -# if !defined(__DOXYGEN__) - I2S_SERIALIZER_CALLBACK_N -# endif -}; - -#endif /* #if I2S_CALLBACK_MODE == true */ - -/** - * \name Module status flags - * - * I2S status flags, returned by \ref i2s_get_status() and cleared by - * \ref i2s_clear_status(). - * - * @{ - */ - -/** Module Serializer x (0~1) Transmit Underrun */ -#define I2S_STATUS_TRANSMIT_UNDERRUN(x) (1u << ((x)+0)) -/** Module Serializer x (0~1) is ready to accept new data to be transmitted */ -#define I2S_STATUS_TRANSMIT_READY(x) (1u << ((x)+2)) -/** Module Serializer x (0~1) Receive Overrun */ -#define I2S_STATUS_RECEIVE_OVERRUN(x) (1u << ((x)+4)) -/** Module Serializer x (0~1) has received a new data */ -#define I2S_STATUS_RECEIVE_READY(x) (1u << ((x)+6)) -/** Module is busy on synchronization */ -#define I2S_STATUS_SYNC_BUSY (1u << 8) - -/** @} */ - -/** - * Master Clock (MCK) source selection - */ -enum i2s_master_clock_source { - /** Master Clock (MCK) is from general clock */ - I2S_MASTER_CLOCK_SOURCE_GCLK, - /** Master Clock (MCK) is from MCK input pin */ - I2S_MASTER_CLOCK_SOURCE_MCKPIN -}; - -/** - * Serial Clock (SCK) source selection - */ -enum i2s_serial_clock_source { - /** Serial Clock (SCK) is divided from Master Clock */ - I2S_SERIAL_CLOCK_SOURCE_MCKDIV, - /** Serial Clock (SCK) is input from SCK input pin */ - I2S_SERIAL_CLOCK_SOURCE_SCKPIN -}; - -/** - * Data delay from Frame Sync (FS) - */ -enum i2s_data_delay { - /** Left Justified (no delay) */ - I2S_DATA_DELAY_0, - /** I2S data delay (1-bit delay) */ - I2S_DATA_DELAY_1, - /** Left Justified (no delay) */ - I2S_DATA_DELAY_LEFT_JUSTIFIED = I2S_DATA_DELAY_0, - /** I2S data delay (1-bit delay) */ - I2S_DATA_DELAY_I2S = I2S_DATA_DELAY_1 -}; - -/** - * Frame Sync (FS) source - */ -enum i2s_frame_sync_source { - /** Frame Sync (FS) is divided from I2S Serial Clock */ - I2S_FRAME_SYNC_SOURCE_SCKDIV, - /** Frame Sync (FS) is input from FS input pin */ - I2S_FRAME_SYNC_SOURCE_FSPIN -}; - -/** - * Frame Sync (FS) output pulse width - */ -enum i2s_frame_sync_width { - /** Frame Sync (FS) Pulse is 1 Slot width */ - I2S_FRAME_SYNC_WIDTH_SLOT, - /** Frame Sync (FS) Pulse is half a Frame width */ - I2S_FRAME_SYNC_WIDTH_HALF_FRAME, - /** Frame Sync (FS) Pulse is 1 Bit width */ - I2S_FRAME_SYNC_WIDTH_BIT, - /** 1-bit wide Frame Sync (FS) per Data sample, only used when Data transfer - * is requested */ - I2S_FRAME_SYNC_WIDTH_BURST -}; - -/** - * Time Slot Size in number of I2S serial clocks (bits) - */ -enum i2s_slot_size { - /** 8-bit slot */ - I2S_SLOT_SIZE_8_BIT, - /** 16-bit slot */ - I2S_SLOT_SIZE_16_BIT, - /** 24-bit slot */ - I2S_SLOT_SIZE_24_BIT, - /** 32-bit slot */ - I2S_SLOT_SIZE_32_BIT -}; - -/** - * DMA channels usage for I2S - */ -enum i2s_dma_usage { - /** Single DMA channel for all I2S channels */ - I2S_DMA_USE_SINGLE_CHANNEL_FOR_ALL, - /** One DMA channel per data channel */ - I2S_DMA_USE_ONE_CHANNEL_PER_DATA_CHANNEL -}; - -/** - * I2S data format, to extend mono data to 2 channels - */ -enum i2s_data_format { - /** Normal mode, keep data to its right channel */ - I2S_DATA_FORMAT_STEREO, - /** Assume input is mono data for left channel, the data is duplicated to - * right channel */ - I2S_DATA_FORMAT_MONO -}; - -/** - * I2S data bit order - */ -enum i2s_bit_order { - /** Transfer Data Most Significant Bit first (Default for I2S protocol) */ - I2S_BIT_ORDER_MSB_FIRST, - /** Transfer Data Least Significant Bit first */ - I2S_BIT_ORDER_LSB_FIRST -}; - -/** - * I2S data bit padding - */ -enum i2s_bit_padding { - /** Padding with 0 */ - I2S_BIT_PADDING_0, - /** Padding with 1 */ - I2S_BIT_PADDING_1, - /** Padding with MSBit */ - I2S_BIT_PADDING_MSB, - /** Padding with LSBit */ - I2S_BIT_PADDING_LSB, -}; - -/** - * I2S data word adjust - */ -enum i2s_data_adjust { - /** Data is right adjusted in word */ - I2S_DATA_ADJUST_RIGHT, - /** Data is left adjusted in word */ - I2S_DATA_ADJUST_LEFT -}; - -/** - * I2S data word size - */ -enum i2s_data_size { - /** 32-bit */ - I2S_DATA_SIZE_32BIT, - /** 24-bit */ - I2S_DATA_SIZE_24BIT, - /** 20-bit */ - I2S_DATA_SIZE_20BIT, - /** 18-bit */ - I2S_DATA_SIZE_18BIT, - /** 16-bit */ - I2S_DATA_SIZE_16BIT, - /** 16-bit compact stereo */ - I2S_DATA_SIZE_16BIT_COMPACT, - /** 8-bit */ - I2S_DATA_SIZE_8BIT, - /** 8-bit compact stereo */ - I2S_DATA_SIZE_8BIT_COMPACT -}; - -/** - * I2S data slot adjust - */ -enum i2s_slot_adjust { - /** Data is right adjusted in slot */ - I2S_SLOT_ADJUST_RIGHT, - /** Data is left adjusted in slot */ - I2S_SLOT_ADJUST_LEFT -}; - -/** - * I2S data padding - */ -enum i2s_data_padding { - /** Padding 0 in case of under-run */ - I2S_DATA_PADDING_0, - /** Padding last data in case of under-run */ - I2S_DATA_PADDING_SAME_AS_LAST, - /** Padding last data in case of under-run - * (abbr. \c I2S_DATA_PADDING_SAME_AS_LAST) */ - I2S_DATA_PADDING_LAST = I2S_DATA_PADDING_SAME_AS_LAST, - /** Padding last data in case of under-run - * (abbr. \c I2S_DATA_PADDING_SAME_AS_LAST) */ - I2S_DATA_PADDING_SAME = I2S_DATA_PADDING_SAME_AS_LAST -}; - -/** - * I2S line default value when slot disabled - */ -enum i2s_line_default_state { - /** Output default value is 0 */ - I2S_LINE_DEFAULT_0, - /** Output default value is 1 */ - I2S_LINE_DEFAULT_1, - /** Output default value is high impedance */ - I2S_LINE_DEFAULT_HIGH_IMPEDANCE = 3, - /** Output default value is high impedance - * (abbr. \c I2S_LINE_DEFAULT_HIGH_IMPEDANCE) */ - I2S_LINE_DEFAULT_HIZ = I2S_LINE_DEFAULT_HIGH_IMPEDANCE -}; - -/** - * I2S Serializer mode - */ -enum i2s_serializer_mode { - /** Serializer is used to receive data */ - I2S_SERIALIZER_RECEIVE, - /** Serializer is used to transmit data */ - I2S_SERIALIZER_TRANSMIT, - /** Serializer is used to receive PDM data on each clock edge */ - I2S_SERIALIZER_PDM2 -}; - -/** - * I2S clock unit selection - */ -enum i2s_clock_unit { - /** Clock Unit channel 0 */ - I2S_CLOCK_UNIT_0, - /** Clock Unit channel 1 */ - I2S_CLOCK_UNIT_1, - /** Number of Clock Unit channels */ - I2S_CLOCK_UNIT_N -}; - -/** - * I2S Serializer selection - */ -enum i2s_serializer { - /** Serializer channel 0 */ - I2S_SERIALIZER_0, - /** Serializer channel 1 */ - I2S_SERIALIZER_1, - /** Number of Serializer channels */ - I2S_SERIALIZER_N -}; - - -/** - * Configure for I2S pin - */ -struct i2s_pin_config { - /** GPIO index to access the pin */ - uint8_t gpio; - /** Pin function MUX */ - uint8_t mux; - /** Enable this pin for I2S module */ - bool enable; -}; - -/** - * Configure for I2S clock (SCK) - */ -struct i2s_clock_config { - /** Divide generic clock to master clock output (1~32, 0,1 means no div) */ - uint8_t mck_out_div; - /** Divide generic clock to serial clock (1~32, 0,1 means no div) */ - uint8_t sck_div; - /** Clock source selection */ - enum gclk_generator gclk_src; - /** Master clock source selection: generated or input from pin */ - enum i2s_master_clock_source mck_src; - /** Serial clock source selection: generated or input from pin */ - enum i2s_serial_clock_source sck_src; - /** Invert master clock output */ - bool mck_out_invert; - /** Invert serial clock output */ - bool sck_out_invert; - /** Generate MCK clock output */ - bool mck_out_enable; -}; - -/** - * Configure fir I2S frame sync (FS) - */ -struct i2s_frame_sync_config { - /** Frame Sync (FS) generated or input from pin */ - enum i2s_frame_sync_source source; - /** Frame Sync (FS) width */ - enum i2s_frame_sync_width width; - /** Invert Frame Sync (FS) signal before use */ - bool invert_use; - /** Invert Frame Sync (FS) signal before output */ - bool invert_out; -}; - -/** - * Configure fir I2S frame - */ -struct i2s_frame_config { - /** Number of slots in a frame (1~8, 0,1 means minimum 1) */ - uint8_t number_slots; - /** Size of each slot in frame */ - enum i2s_slot_size slot_size; - /** Data delay from Frame Sync (FS) to first data bit */ - enum i2s_data_delay data_delay; - /** Frame sync (FS) */ - struct i2s_frame_sync_config frame_sync; -}; - -/** - * Configure for I2S clock unit - */ -struct i2s_clock_unit_config { - /** Configure clock generation */ - struct i2s_clock_config clock; - /** Configure frame generation */ - struct i2s_frame_config frame; - - /** Configure master clock pin */ - struct i2s_pin_config mck_pin; - /** Configure serial clock pin */ - struct i2s_pin_config sck_pin; - /** Configure frame sync pin */ - struct i2s_pin_config fs_pin; -}; - -/** - * Configure for I2S Serializer - */ -struct i2s_serializer_config { - /** Configure Serializer data pin */ - struct i2s_pin_config data_pin; - - /** Set to \c true to loop-back output to input pin for test */ - bool loop_back; - - /** Set to \c true to assumes mono input and duplicate it (left channel) to - * right channel */ - bool mono_mode; - - /** Disable data slot */ - bool disable_data_slot[8]; - - /** Set to \c true to transfer LSB first, \c false to transfer MSB first */ - bool transfer_lsb_first; - /** Data Word Formatting Adjust, - * set to \c true to adjust bits in word to left */ - bool data_adjust_left_in_word; - /** Data Slot Formatting Adjust, - * set to \c true to adjust words in slot to left */ - bool data_adjust_left_in_slot; - - /** Data Word Size */ - enum i2s_data_size data_size; - /** Data Formatting Bit Extension */ - enum i2s_bit_padding bit_padding; - /** Data padding when under-run */ - enum i2s_data_padding data_padding; - - /** DMA usage */ - enum i2s_dma_usage dma_usage; - - /** Clock unit selection */ - enum i2s_clock_unit clock_unit; - - /** Line default state where slot is disabled */ - enum i2s_line_default_state line_default_state; - - /** Serializer Mode */ - enum i2s_serializer_mode mode; -}; - -/** - * \brief I2S Serializer instance struct - */ -struct i2s_serializer_module { - -#if I2S_CALLBACK_MODE == true - /** Callbacks list for Serializer */ - i2s_serializer_callback_t callback[I2S_SERIALIZER_CALLBACK_N]; - - /** Job buffer */ - void *job_buffer; - /** Requested data words to read/write */ - uint32_t requested_words; - /** Transferred data words for read/write */ - uint32_t transferred_words; - - /** Callback mask for registered callbacks */ - uint8_t registered_callback_mask; - /** Callback mask for enabled callbacks */ - uint8_t enabled_callback_mask; - - /** Status of the ongoing or last transfer job */ - enum status_code job_status; -#endif - - /** Serializer mode */ - enum i2s_serializer_mode mode; - /** Serializer data word size */ - enum i2s_data_size data_size; -}; - -/** - * \brief I2S Software Module instance struct - */ -struct i2s_module { - /** Module HW register access base */ - I2s *hw; - - /** Module Serializer used */ - struct i2s_serializer_module serializer[2]; -}; - -/** - * \brief Determines if the hardware module(s) are currently synchronizing to the bus. - * - * Checks to see if the underlying hardware peripheral module(s) are currently - * synchronizing across multiple clock domains to the hardware bus, This - * function can be used to delay further operations on a module until such time - * that it is ready, to prevent blocking delays for synchronization in the - * user application. - * - * \param[in] module_inst Pointer to the software module instance struct - * - * \return Synchronization status of the underlying hardware module(s). - * - * \retval false If the module has completed synchronization - * \retval true If the module synchronization is ongoing - */ -static inline bool i2s_is_syncing( - const struct i2s_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - return (module_inst->hw->SYNCBUSY.reg > 0); -} - -/** - * \name Driver Initialization - * @{ - */ - -enum status_code i2s_init( - struct i2s_module *const module_inst, - I2s *hw); - -/** @} */ - -/** - * \name Enable/Disable/Reset - * @{ - */ - -/** - * \brief Enable the I2S module. - * - * Enables a I2S module that has been previously initialized. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void i2s_enable(const struct i2s_module *const module_inst) -{ - Assert(module_inst); - Assert(module_inst->hw); - - while (module_inst->hw->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE) { - /* Sync wait */ - } - module_inst->hw->CTRLA.reg |= I2S_SYNCBUSY_ENABLE; -} - -/** - * \brief Disables the I2S module. - * - * Disables a I2S module. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void i2s_disable(const struct i2s_module *const module_inst) -{ - Assert(module_inst); - Assert(module_inst->hw); - - while (module_inst->hw->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE) { - /* Sync wait */ - } - module_inst->hw->CTRLA.reg &= ~I2S_SYNCBUSY_ENABLE; -} - -/** - * \brief Resets the I2S module. - * - * Resets the I2S module, restoring all hardware module registers to their - * default values and disabling the module. The I2S module will not be - * accessible while the reset is being performed. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void i2s_reset(const struct i2s_module *const module_inst) -{ - Assert(module_inst); - Assert(module_inst->hw); - - /* Disable the module if it is running */ - if (module_inst->hw->CTRLA.reg & I2S_CTRLA_ENABLE) { - i2s_disable(module_inst); - while (i2s_is_syncing(module_inst)) { - /* Sync wait */ - } - } - /* Reset the HW module */ - module_inst->hw->CTRLA.reg = I2S_CTRLA_SWRST; -} - -/** @} */ - -/** - * \name Clock Unit Initialization and Configuration - * @{ - */ - -/** - * \brief Initializes config with predefined default values for I2S clock unit. - * - * This function will initialize a given I2S Clock Unit configuration structure - * to a set of known default values. This function should be called on any new - * instance of the configuration structures before being modified by the user - * application. - * - * The default configuration is as follow: - * - The clock unit does not generate output clocks (MCK, SCK and FS) - * - The pins (MCK, SCK and FS) and Mux configurations are not set - * - * \param[out] config Pointer to a I2S module clock unit configuration struct - * to set - */ -static inline void i2s_clock_unit_get_config_defaults( - struct i2s_clock_unit_config *const config) -{ - Assert(config); - - config->clock.mck_out_enable = false; - config->clock.gclk_src = GCLK_GENERATOR_0; - - config->clock.mck_src = I2S_MASTER_CLOCK_SOURCE_GCLK; - config->clock.mck_out_div = 1; - config->clock.mck_out_invert = false; - - config->clock.sck_src = I2S_SERIAL_CLOCK_SOURCE_MCKDIV; - config->clock.sck_div = 1; - config->clock.sck_out_invert = false; - - config->frame.number_slots = 1; - config->frame.slot_size = I2S_SLOT_SIZE_32_BIT; - config->frame.data_delay = I2S_DATA_DELAY_I2S; - - config->frame.frame_sync.source = I2S_FRAME_SYNC_SOURCE_SCKDIV; - config->frame.frame_sync.width = I2S_FRAME_SYNC_WIDTH_HALF_FRAME; - config->frame.frame_sync.invert_use = false; - config->frame.frame_sync.invert_out = false; - - config->mck_pin.enable = false; - config->mck_pin.mux = 0; - config->mck_pin.gpio = 0; - - config->sck_pin.enable = false; - config->sck_pin.mux = 0; - config->sck_pin.gpio = 0; - - config->fs_pin.enable = false; - config->fs_pin.mux = 0; - config->fs_pin.gpio = 0; -} - -enum status_code i2s_clock_unit_set_config( - struct i2s_module *const module_inst, - const enum i2s_clock_unit clock_unit, - const struct i2s_clock_unit_config *config); - -/** @} */ - - -/** - * \name Clock Unit Enable/Disable - * @{ - */ - -/** - * \brief Enable the Specified Clock Unit of I2S module. - * - * Enables a Clock Unit in I2S module that has been previously initialized. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] clock_unit I2S Clock Unit to enable - */ -static inline void i2s_clock_unit_enable( - const struct i2s_module *const module_inst, - const enum i2s_clock_unit clock_unit) -{ - uint32_t cken_bit; - - Assert(module_inst); - Assert(module_inst->hw); - - cken_bit = I2S_CTRLA_CKEN0 << clock_unit; - - while (module_inst->hw->SYNCBUSY.reg & cken_bit) { - /* Sync wait */ - } - module_inst->hw->CTRLA.reg |= cken_bit; -} - -/** - * \brief Disable the Specified Clock Unit of I2S module. - * - * Disables a Clock Unit in I2S module that has been previously initialized. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] clock_unit I2S Clock Unit to disable - */ -static inline void i2s_clock_unit_disable( - const struct i2s_module *const module_inst, - const enum i2s_clock_unit clock_unit) -{ - uint32_t cken_bit; - - Assert(module_inst); - Assert(module_inst->hw); - - cken_bit = I2S_CTRLA_CKEN0 << clock_unit; - - while (module_inst->hw->SYNCBUSY.reg & cken_bit) { - /* Sync wait */ - } - module_inst->hw->CTRLA.reg &= ~cken_bit; -} - -/** @} */ - - -/** - * \name Serializer Initialization and Configuration - * @{ - */ - -/** - * \brief Initializes config with predefined default values for I2S Serializer. - * - * This function will initialize a given I2S Clock Unit configuration structure - * to a set of known default values. This function should be called on any new - * instance of the configuration structures before being modified by the user - * application. - * - * The default configuration is as follow: - * - Output data does not internally loopback to input line - * - Does not extend mono data (left channel) to right channel - * - None of the data slot is disabled - * - MSB of I2S data is transferred first - * - In data word data is adjusted right - * - In slot data word is adjusted left - * - The data size is 16-bit width - * - I2S will padd 0 to not defined bits - * - I2S will padd 0 to not defined words - * - I2S will use single DMA channel for all data channels - * - I2S will use clock unit 0 to serve as clock - * - The default data line state is 0, when there is no data - * - I2S will transmit data to output line - * - The data pin and Mux configuration are not set - * - * \param[out] config Pointer to a I2S module Serializer configuration struct - * to set - */ -static inline void i2s_serializer_get_config_defaults( - struct i2s_serializer_config *const config) -{ - config->loop_back = false; - - config->mono_mode = false; - - config->disable_data_slot[0] = false; - config->disable_data_slot[1] = false; - config->disable_data_slot[2] = false; - config->disable_data_slot[3] = false; - config->disable_data_slot[4] = false; - config->disable_data_slot[5] = false; - config->disable_data_slot[6] = false; - config->disable_data_slot[7] = false; - - config->transfer_lsb_first = false; - config->data_adjust_left_in_word = false; - config->data_adjust_left_in_slot = true; - - config->data_size = I2S_DATA_SIZE_16BIT; - - config->bit_padding = I2S_BIT_PADDING_0; - config->data_padding = I2S_DATA_PADDING_0; - - config->dma_usage = I2S_DMA_USE_SINGLE_CHANNEL_FOR_ALL; - - config->clock_unit = I2S_CLOCK_UNIT_0; - - config->line_default_state = I2S_LINE_DEFAULT_0; - - config->mode = I2S_SERIALIZER_TRANSMIT; - - config->data_pin.enable = false; - config->data_pin.gpio = 0; - config->data_pin.mux = 0; -} - -enum status_code i2s_serializer_set_config( - struct i2s_module *const module_inst, - const enum i2s_serializer serializer, - const struct i2s_serializer_config *config); -/** @} */ - -/** - * \name Serializer Enable/Disable - * @{ - */ - -/** - * \brief Enable the Specified Serializer of I2S module. - * - * Enables a Serializer in I2S module that has been previously initialized. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer I2S Serializer to enable - */ -static inline void i2s_serializer_enable( - const struct i2s_module *const module_inst, - const enum i2s_serializer serializer) -{ - uint32_t seren_bit; - - Assert(module_inst); - Assert(module_inst->hw); - - seren_bit = I2S_CTRLA_SEREN0 << serializer; - - while (module_inst->hw->SYNCBUSY.reg & seren_bit) { - /* Sync wait */ - } - module_inst->hw->CTRLA.reg |= seren_bit; -} - -/** - * \brief Disable the Specified Serializer of I2S module. - * - * Disables a Serializer in I2S module that has been previously initialized. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer I2S Serializer to disable - */ -static inline void i2s_serializer_disable( - const struct i2s_module *const module_inst, - const enum i2s_serializer serializer) -{ - uint32_t seren_bit; - - Assert(module_inst); - Assert(module_inst->hw); - - seren_bit = I2S_CTRLA_SEREN0 << serializer; - - while (module_inst->hw->SYNCBUSY.reg & seren_bit) { - /* Sync wait */ - } - module_inst->hw->CTRLA.reg &= ~seren_bit; -} -/** @} */ - -/** - * \name Status Management - * @{ - */ - -uint32_t i2s_get_status( - const struct i2s_module *const module_inst); - -void i2s_clear_status( - const struct i2s_module *const module_inst, - uint32_t status); - - -enum status_code i2s_enable_status_interrupt( - struct i2s_module *const module_inst, - uint32_t status); - -void i2s_disable_status_interrupt( - struct i2s_module *const module_inst, - uint32_t status); - -/** @}*/ - -/** - * \name Data read/write - * @{ - */ - -/** - * \brief Write a data word to the specified Serializer of I2S module - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer The Serializer to write to - * \param[in] data The data to write - * - */ -static inline void i2s_serializer_write_wait( - const struct i2s_module *const module_inst, - enum i2s_serializer serializer, - uint32_t data) -{ - uint32_t sync_bit, ready_bit; - - Assert(module_inst); - Assert(module_inst->hw); - - ready_bit = I2S_INTFLAG_TXRDY0 << serializer; - while (!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait until ready to transmit */ - } - sync_bit = I2S_SYNCBUSY_DATA0 << serializer; - while (module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait sync */ - } - /* Write data */ - module_inst->hw->DATA[serializer].reg = data; - module_inst->hw->INTFLAG.reg = ready_bit; -} - -/** - * \brief Read a data word from the specified Serializer of I2S module - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer The Serializer to read - */ -static inline uint32_t i2s_serializer_read_wait( - const struct i2s_module *const module_inst, - enum i2s_serializer serializer) -{ - uint32_t sync_bit, ready_bit; - uint32_t data; - - Assert(module_inst); - Assert(module_inst->hw); - - ready_bit = I2S_INTFLAG_RXRDY0 << serializer; - while (!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait until ready to transmit */ - } - sync_bit = I2S_SYNCBUSY_DATA0 << serializer; - while (module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait sync */ - } - /* Read data */ - data = module_inst->hw->DATA[serializer].reg; - module_inst->hw->INTFLAG.reg = ready_bit; - return data; -} - - -/** - * \brief Write buffer to the specified Serializer of I2S module - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer The Serializer to write to - * \param[in] buffer The data buffer to write - * \param[in] size Number of data words to write - * - * \return Status of the initialization procedure. - * - * \retval STATUS_OK The data was sent successfully - * \retval STATUS_INVALID_ARG An invalid buffer pointer was supplied - */ -enum status_code i2s_serializer_write_buffer_wait( - const struct i2s_module *const module_inst, - enum i2s_serializer serializer, - void *buffer, uint32_t size); - -/** - * \brief Read from the specified Serializer of I2S module to a buffer - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer The Serializer to write to - * \param[in] buffer The buffer to fill read data - * \param[in] size Number of data words to read - * - * \return Status of the initialization procedure. - * - * \retval STATUS_OK The data was sent successfully - * \retval STATUS_INVALID_ARG An invalid buffer pointer was supplied - */ -enum status_code i2s_serializer_read_buffer_wait( - const struct i2s_module *const module_inst, - enum i2s_serializer serializer, - void *buffer, uint32_t size); - -/** @} */ - -#ifdef __cplusplus -} -#endif - -/** @} */ - - -/** - * \page asfdoc_sam0_i2s_extra Extra Information for I2S Driver - * - * \section asfdoc_sam0_i2s_extra_acronyms Acronyms - * Below is a table listing the acronyms used in this module, along with their - * intended meanings. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
AcronymDescription
I2S, IISInter-IC Sound Controller
MCKMaster Clock
SCKSerial Clock
FSFrame Sync
SDSerial Data
ADCAnalog-to-Digital Converter
DACDigital-to-Analog Converter
TDMTime Division Multiplexed
PDMPulse Density Modulation
LSBLeast Significant Bit
MSBMost Significant Bit
DSPDigital Signal Processor
- * - * - * \section asfdoc_sam0_i2s_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - \ref asfdoc_sam0_system_pinmux_group "System Pin Multiplexer Driver" - * - * - * \section asfdoc_sam0_i2s_extra_errata Errata - * There are no errata related to this driver. - * - * - * \section asfdoc_sam0_i2s_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * - * - * - *
Changelog
Initial Release
- */ - -/** - * \page asfdoc_sam0_i2s_exqsg Examples for I2S Driver - * - * This is a list of the available Quick Start guides (QSGs) and example - * applications for \ref asfdoc_sam0_i2s_group. QSGs are simple examples with - * step-by-step instructions to configure and use this driver in a selection of - * use cases. Note that QSGs can be compiled as a standalone application or be - * added to the user application. - * - * - \subpage asfdoc_sam0_i2s_basic_use_case - * \if I2S_CALLBACK_MODE - * - \subpage asfdoc_sam0_i2s_callback_use_case - * \endif - * - \subpage asfdoc_sam0_i2s_dma_use_case - * - * \page asfdoc_sam0_i2s_document_revision_history Document Revision History - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Doc. Rev. - * Date - * Comments - *
B04/2015Added support for SAMDA1.
A01/2014Initial release
- */ - -#endif /* #ifndef I2S_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt.h deleted file mode 100644 index fa4878e..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt.h +++ /dev/null @@ -1,117 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ -#ifndef UTILS_INTERRUPT_H -#define UTILS_INTERRUPT_H - -//#include - -#include "interrupt/interrupt_sam_nvic.h" - -/** - * \defgroup interrupt_group Global interrupt management - * - * This is a driver for global enabling and disabling of interrupts. - * - * @{ - */ - -#if defined(__DOXYGEN__) -/** - * \def CONFIG_INTERRUPT_FORCE_INTC - * \brief Force usage of the ASF INTC driver - * - * Predefine this symbol when preprocessing to force the use of the ASF INTC driver. - * This is useful to ensure compatibility across compilers and shall be used only when required - * by the application needs. - */ -# define CONFIG_INTERRUPT_FORCE_INTC -#endif - -//! \name Global interrupt flags -//@{ -/** - * \typedef irqflags_t - * \brief Type used for holding state of interrupt flag - */ - -/** - * \def cpu_irq_enable - * \brief Enable interrupts globally - */ - -/** - * \def cpu_irq_disable - * \brief Disable interrupts globally - */ - -/** - * \fn irqflags_t cpu_irq_save(void) - * \brief Get and clear the global interrupt flags - * - * Use in conjunction with \ref cpu_irq_restore. - * - * \return Current state of interrupt flags. - * - * \note This function leaves interrupts disabled. - */ - -/** - * \fn void cpu_irq_restore(irqflags_t flags) - * \brief Restore global interrupt flags - * - * Use in conjunction with \ref cpu_irq_save. - * - * \param flags State to set interrupt flag to. - */ - -/** - * \fn bool cpu_irq_is_enabled_flags(irqflags_t flags) - * \brief Check if interrupts are globally enabled in supplied flags - * - * \param flags Currents state of interrupt flags. - * - * \return True if interrupts are enabled. - */ - -/** - * \def cpu_irq_is_enabled - * \brief Check if interrupts are globally enabled - * - * \return True if interrupts are enabled. - */ -//@} - -//! @} - -/** - * \ingroup interrupt_group - * \defgroup interrupt_deprecated_group Deprecated interrupt definitions - */ - -#endif /* UTILS_INTERRUPT_H */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c b/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c deleted file mode 100644 index d813485..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c +++ /dev/null @@ -1,69 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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 "interrupt_sam_nvic.h" - -#if !defined(__DOXYGEN__) -/* Deprecated - global flag to determine the global interrupt state. Required by - * QTouch library, however new applications should use cpu_irq_is_enabled() - * which probes the true global interrupt state from the CPU special registers. - */ -volatile bool g_interrupt_enabled = true; -#endif - -void cpu_irq_enter_critical(void) -{ - if (cpu_irq_critical_section_counter == 0) { - if (cpu_irq_is_enabled()) { - cpu_irq_disable(); - cpu_irq_prev_interrupt_state = true; - } else { - /* Make sure the to save the prev state as false */ - cpu_irq_prev_interrupt_state = false; - } - - } - - cpu_irq_critical_section_counter++; -} - -void cpu_irq_leave_critical(void) -{ - /* Check if the user is trying to leave a critical section when not in a critical section */ - Assert(cpu_irq_critical_section_counter > 0); - - cpu_irq_critical_section_counter--; - - /* Only enable global interrupts when the counter reaches 0 and the state of the global interrupt flag - was enabled when entering critical state */ - if ((cpu_irq_critical_section_counter == 0) && (cpu_irq_prev_interrupt_state)) { - cpu_irq_enable(); - } -} - diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h deleted file mode 100644 index 9b5645b..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h +++ /dev/null @@ -1,172 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef UTILS_INTERRUPT_INTERRUPT_H -#define UTILS_INTERRUPT_INTERRUPT_H - -#include -//#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \weakgroup interrupt_group - * - * @{ - */ - -/** - * \name Interrupt Service Routine definition - * - * @{ - */ - -/** - * \brief Define service routine - * - * \note For NVIC devices the interrupt service routines are predefined to - * add to vector table in binary generation, so there is no service - * register at run time. The routine collections are in exceptions.h. - * - * Usage: - * \code - ISR(foo_irq_handler) - { - // Function definition - ... - } -\endcode - * - * \param func Name for the function. - */ -# define ISR(func) \ - void func (void) - -/** - * \brief Initialize interrupt vectors - * - * For NVIC the interrupt vectors are put in vector table. So nothing - * to do to initialize them, except defined the vector function with - * right name. - * - * This must be called prior to \ref irq_register_handler. - */ -# define irq_initialize_vectors() \ - do { \ - } while(0) - -/** - * \brief Register handler for interrupt - * - * For NVIC the interrupt vectors are put in vector table. So nothing - * to do to register them, except defined the vector function with - * right name. - * - * Usage: - * \code - irq_initialize_vectors(); - irq_register_handler(foo_irq_handler); -\endcode - * - * \note The function \a func must be defined with the \ref ISR macro. - * \note The functions prototypes can be found in the device exception header - * files (exceptions.h). - */ -# define irq_register_handler(int_num, int_prio) \ - NVIC_ClearPendingIRQ( (IRQn_Type)int_num); \ - NVIC_SetPriority( (IRQn_Type)int_num, int_prio); \ - NVIC_EnableIRQ( (IRQn_Type)int_num); \ - -//@} - -# define cpu_irq_enable() \ - do { \ - g_interrupt_enabled = true; \ - __DMB(); \ - __enable_irq(); \ - } while (0) -# define cpu_irq_disable() \ - do { \ - __disable_irq(); \ - __DMB(); \ - g_interrupt_enabled = false; \ - } while (0) - -typedef uint32_t irqflags_t; - -#if !defined(__DOXYGEN__) -extern volatile bool g_interrupt_enabled; -#endif - -#define cpu_irq_is_enabled() (__get_PRIMASK() == 0) - -static volatile uint32_t cpu_irq_critical_section_counter; -static volatile bool cpu_irq_prev_interrupt_state; - -static inline irqflags_t cpu_irq_save(void) -{ - irqflags_t flags = cpu_irq_is_enabled(); - cpu_irq_disable(); - return flags; -} - -static inline bool cpu_irq_is_enabled_flags(irqflags_t flags) -{ - return (flags); -} - -static inline void cpu_irq_restore(irqflags_t flags) -{ - if (cpu_irq_is_enabled_flags(flags)) - cpu_irq_enable(); -} - -void cpu_irq_enter_critical(void); -void cpu_irq_leave_critical(void); - -/** - * \weakgroup interrupt_deprecated_group - * @{ - */ - -#define Enable_global_interrupt() cpu_irq_enable() -#define Disable_global_interrupt() cpu_irq_disable() -#define Is_global_interrupt_enabled() cpu_irq_is_enabled() - -//@} - -//@} - -#ifdef __cplusplus -} -#endif - -#endif /* UTILS_INTERRUPT_INTERRUPT_H */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c b/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c deleted file mode 100644 index 26dcc91..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c +++ /dev/null @@ -1,86 +0,0 @@ -/** - * \file - * - * \brief Global interrupt management for SAM D20, SAM3 and SAM4 (NVIC based) - * - * Copyright (c) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#include "interrupt_sam_nvic.h" - -#if !defined(__DOXYGEN__) -/* Deprecated - global flag to determine the global interrupt state. Required by - * QTouch library, however new applications should use cpu_irq_is_enabled() - * which probes the true global interrupt state from the CPU special registers. - */ -volatile bool g_interrupt_enabled = true; -#endif - -void cpu_irq_enter_critical(void) -{ - if (cpu_irq_critical_section_counter == 0) { - if (cpu_irq_is_enabled()) { - cpu_irq_disable(); - cpu_irq_prev_interrupt_state = true; - } else { - /* Make sure the to save the prev state as false */ - cpu_irq_prev_interrupt_state = false; - } - - } - - cpu_irq_critical_section_counter++; -} - -void cpu_irq_leave_critical(void) -{ - /* Check if the user is trying to leave a critical section when not in a critical section */ - Assert(cpu_irq_critical_section_counter > 0); - - cpu_irq_critical_section_counter--; - - /* Only enable global interrupts when the counter reaches 0 and the state of the global interrupt flag - was enabled when entering critical state */ - if ((cpu_irq_critical_section_counter == 0) && (cpu_irq_prev_interrupt_state)) { - cpu_irq_enable(); - } -} - diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h deleted file mode 100644 index f996e92..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h +++ /dev/null @@ -1,189 +0,0 @@ -/** - * \file - * - * \brief Global interrupt management for SAM D20, SAM3 and SAM4 (NVIC based) - * - * Copyright (c) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#ifndef UTILS_INTERRUPT_INTERRUPT_H -#define UTILS_INTERRUPT_INTERRUPT_H - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \weakgroup interrupt_group - * - * @{ - */ - -/** - * \name Interrupt Service Routine definition - * - * @{ - */ - -/** - * \brief Define service routine - * - * \note For NVIC devices the interrupt service routines are predefined to - * add to vector table in binary generation, so there is no service - * register at run time. The routine collections are in exceptions.h. - * - * Usage: - * \code - ISR(foo_irq_handler) - { - // Function definition - ... - } -\endcode - * - * \param func Name for the function. - */ -# define ISR(func) \ - void func (void) - -/** - * \brief Initialize interrupt vectors - * - * For NVIC the interrupt vectors are put in vector table. So nothing - * to do to initialize them, except defined the vector function with - * right name. - * - * This must be called prior to \ref irq_register_handler. - */ -# define irq_initialize_vectors() \ - do { \ - } while(0) - -/** - * \brief Register handler for interrupt - * - * For NVIC the interrupt vectors are put in vector table. So nothing - * to do to register them, except defined the vector function with - * right name. - * - * Usage: - * \code - irq_initialize_vectors(); - irq_register_handler(foo_irq_handler); -\endcode - * - * \note The function \a func must be defined with the \ref ISR macro. - * \note The functions prototypes can be found in the device exception header - * files (exceptions.h). - */ -# define irq_register_handler(int_num, int_prio) \ - NVIC_ClearPendingIRQ( (IRQn_Type)int_num); \ - NVIC_SetPriority( (IRQn_Type)int_num, int_prio); \ - NVIC_EnableIRQ( (IRQn_Type)int_num); \ - -//@} - -# define cpu_irq_enable() \ - do { \ - g_interrupt_enabled = true; \ - __DMB(); \ - __enable_irq(); \ - } while (0) -# define cpu_irq_disable() \ - do { \ - __disable_irq(); \ - __DMB(); \ - g_interrupt_enabled = false; \ - } while (0) - -typedef uint32_t irqflags_t; - -#if !defined(__DOXYGEN__) -extern volatile bool g_interrupt_enabled; -#endif - -#define cpu_irq_is_enabled() (__get_PRIMASK() == 0) - -static volatile uint32_t cpu_irq_critical_section_counter; -static volatile bool cpu_irq_prev_interrupt_state; - -static inline irqflags_t cpu_irq_save(void) -{ - irqflags_t flags = cpu_irq_is_enabled(); - cpu_irq_disable(); - return flags; -} - -static inline bool cpu_irq_is_enabled_flags(irqflags_t flags) -{ - return (flags); -} - -static inline void cpu_irq_restore(irqflags_t flags) -{ - if (cpu_irq_is_enabled_flags(flags)) - cpu_irq_enable(); -} - -void cpu_irq_enter_critical(void); -void cpu_irq_leave_critical(void); - -/** - * \weakgroup interrupt_deprecated_group - * @{ - */ - -#define Enable_global_interrupt() cpu_irq_enable() -#define Disable_global_interrupt() cpu_irq_disable() -#define Is_global_interrupt_enabled() cpu_irq_is_enabled() - -//@} - -//@} - -#ifdef __cplusplus -} -#endif - -#endif /* UTILS_INTERRUPT_INTERRUPT_H */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/library.properties b/feather_sensor_lte/libraries/Adafruit_ASFcore/library.properties deleted file mode 100644 index e2af108..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=Adafruit Arduino Zero ASF Core Library -version=1.0.0 -author=Adafruit -maintainer=Adafruit -sentence=ASF (Atmel Software Framework) files used by Adafruit's Arduino Zero/SAMD21 libraries. -paragraph=ASF (Atmel Software Framework) files used by Adafruit's Arduino Zero/SAMD21 libraries. This is a dependency of other libraries like Adafruit_ZeroTimer. -category=Other -url=https://github.com/adafruit/Adafruit_ASFcore -architectures=* diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/parts.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/parts.h deleted file mode 100644 index 40be022..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/parts.h +++ /dev/null @@ -1,1601 +0,0 @@ -/** - * \file - * - * \brief Atmel part identification macros - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#ifndef ATMEL_PARTS_H -#define ATMEL_PARTS_H - -/** - * \defgroup part_macros_group Atmel part identification macros - * - * This collection of macros identify which series and families that the various - * Atmel parts belong to. These can be used to select part-dependent sections of - * code at compile time. - * - * @{ - */ - -/** - * \name Convenience macros for part checking - * @{ - */ -/* ! Check GCC and IAR part definition for 8-bit AVR */ -#define AVR8_PART_IS_DEFINED(part) \ - (defined(__ ## part ## __) || defined(__AVR_ ## part ## __)) - -/* ! Check GCC and IAR part definition for 32-bit AVR */ -#define AVR32_PART_IS_DEFINED(part) \ - (defined(__AT32 ## part ## __) || defined(__AVR32_ ## part ## __)) - -/* ! Check GCC and IAR part definition for SAM */ -#define SAM_PART_IS_DEFINED(part) (defined(__ ## part ## __)) -/** @} */ - -/** - * \defgroup uc3_part_macros_group AVR UC3 parts - * @{ - */ - -/** - * \name AVR UC3 A series - * @{ - */ -#define UC3A0 ( \ - AVR32_PART_IS_DEFINED(UC3A0128) || \ - AVR32_PART_IS_DEFINED(UC3A0256) || \ - AVR32_PART_IS_DEFINED(UC3A0512) \ - ) - -#define UC3A1 ( \ - AVR32_PART_IS_DEFINED(UC3A1128) || \ - AVR32_PART_IS_DEFINED(UC3A1256) || \ - AVR32_PART_IS_DEFINED(UC3A1512) \ - ) - -#define UC3A3 ( \ - AVR32_PART_IS_DEFINED(UC3A364) || \ - AVR32_PART_IS_DEFINED(UC3A364S) || \ - AVR32_PART_IS_DEFINED(UC3A3128) || \ - AVR32_PART_IS_DEFINED(UC3A3128S) || \ - AVR32_PART_IS_DEFINED(UC3A3256) || \ - AVR32_PART_IS_DEFINED(UC3A3256S) \ - ) - -#define UC3A4 ( \ - AVR32_PART_IS_DEFINED(UC3A464) || \ - AVR32_PART_IS_DEFINED(UC3A464S) || \ - AVR32_PART_IS_DEFINED(UC3A4128) || \ - AVR32_PART_IS_DEFINED(UC3A4128S) || \ - AVR32_PART_IS_DEFINED(UC3A4256) || \ - AVR32_PART_IS_DEFINED(UC3A4256S) \ - ) -/** @} */ - -/** - * \name AVR UC3 B series - * @{ - */ -#define UC3B0 ( \ - AVR32_PART_IS_DEFINED(UC3B064) || \ - AVR32_PART_IS_DEFINED(UC3B0128) || \ - AVR32_PART_IS_DEFINED(UC3B0256) || \ - AVR32_PART_IS_DEFINED(UC3B0512) \ - ) - -#define UC3B1 ( \ - AVR32_PART_IS_DEFINED(UC3B164) || \ - AVR32_PART_IS_DEFINED(UC3B1128) || \ - AVR32_PART_IS_DEFINED(UC3B1256) || \ - AVR32_PART_IS_DEFINED(UC3B1512) \ - ) -/** @} */ - -/** - * \name AVR UC3 C series - * @{ - */ -#define UC3C0 ( \ - AVR32_PART_IS_DEFINED(UC3C064C) || \ - AVR32_PART_IS_DEFINED(UC3C0128C) || \ - AVR32_PART_IS_DEFINED(UC3C0256C) || \ - AVR32_PART_IS_DEFINED(UC3C0512C) \ - ) - -#define UC3C1 ( \ - AVR32_PART_IS_DEFINED(UC3C164C) || \ - AVR32_PART_IS_DEFINED(UC3C1128C) || \ - AVR32_PART_IS_DEFINED(UC3C1256C) || \ - AVR32_PART_IS_DEFINED(UC3C1512C) \ - ) - -#define UC3C2 ( \ - AVR32_PART_IS_DEFINED(UC3C264C) || \ - AVR32_PART_IS_DEFINED(UC3C2128C) || \ - AVR32_PART_IS_DEFINED(UC3C2256C) || \ - AVR32_PART_IS_DEFINED(UC3C2512C) \ - ) -/** @} */ - -/** - * \name AVR UC3 D series - * @{ - */ -#define UC3D3 ( \ - AVR32_PART_IS_DEFINED(UC64D3) || \ - AVR32_PART_IS_DEFINED(UC128D3) \ - ) - -#define UC3D4 ( \ - AVR32_PART_IS_DEFINED(UC64D4) || \ - AVR32_PART_IS_DEFINED(UC128D4) \ - ) -/** @} */ - -/** - * \name AVR UC3 L series - * @{ - */ -#define UC3L0 ( \ - AVR32_PART_IS_DEFINED(UC3L016) || \ - AVR32_PART_IS_DEFINED(UC3L032) || \ - AVR32_PART_IS_DEFINED(UC3L064) \ - ) - -#define UC3L0128 ( \ - AVR32_PART_IS_DEFINED(UC3L0128) \ - ) - -#define UC3L0256 ( \ - AVR32_PART_IS_DEFINED(UC3L0256) \ - ) - -#define UC3L3 ( \ - AVR32_PART_IS_DEFINED(UC64L3U) || \ - AVR32_PART_IS_DEFINED(UC128L3U) || \ - AVR32_PART_IS_DEFINED(UC256L3U) \ - ) - -#define UC3L4 ( \ - AVR32_PART_IS_DEFINED(UC64L4U) || \ - AVR32_PART_IS_DEFINED(UC128L4U) || \ - AVR32_PART_IS_DEFINED(UC256L4U) \ - ) - -#define UC3L3_L4 (UC3L3 || UC3L4) -/** @} */ - -/** - * \name AVR UC3 families - * @{ - */ -/** AVR UC3 A family */ -#define UC3A (UC3A0 || UC3A1 || UC3A3 || UC3A4) - -/** AVR UC3 B family */ -#define UC3B (UC3B0 || UC3B1) - -/** AVR UC3 C family */ -#define UC3C (UC3C0 || UC3C1 || UC3C2) - -/** AVR UC3 D family */ -#define UC3D (UC3D3 || UC3D4) - -/** AVR UC3 L family */ -#define UC3L (UC3L0 || UC3L0128 || UC3L0256 || UC3L3_L4) -/** @} */ - -/** AVR UC3 product line */ -#define UC3 (UC3A || UC3B || UC3C || UC3D || UC3L) - -/** @} */ - -/** - * \defgroup xmega_part_macros_group AVR XMEGA parts - * @{ - */ - -/** - * \name AVR XMEGA A series - * @{ - */ -#define XMEGA_A1 ( \ - AVR8_PART_IS_DEFINED(ATxmega64A1) || \ - AVR8_PART_IS_DEFINED(ATxmega128A1) \ - ) - -#define XMEGA_A3 ( \ - AVR8_PART_IS_DEFINED(ATxmega64A3) || \ - AVR8_PART_IS_DEFINED(ATxmega128A3) || \ - AVR8_PART_IS_DEFINED(ATxmega192A3) || \ - AVR8_PART_IS_DEFINED(ATxmega256A3) \ - ) - -#define XMEGA_A3B ( \ - AVR8_PART_IS_DEFINED(ATxmega256A3B) \ - ) - -#define XMEGA_A4 ( \ - AVR8_PART_IS_DEFINED(ATxmega16A4) || \ - AVR8_PART_IS_DEFINED(ATxmega32A4) \ - ) -/** @} */ - -/** - * \name AVR XMEGA AU series - * @{ - */ -#define XMEGA_A1U ( \ - AVR8_PART_IS_DEFINED(ATxmega64A1U) || \ - AVR8_PART_IS_DEFINED(ATxmega128A1U) \ - ) - -#define XMEGA_A3U ( \ - AVR8_PART_IS_DEFINED(ATxmega64A3U) || \ - AVR8_PART_IS_DEFINED(ATxmega128A3U) || \ - AVR8_PART_IS_DEFINED(ATxmega192A3U) || \ - AVR8_PART_IS_DEFINED(ATxmega256A3U) \ - ) - -#define XMEGA_A3BU ( \ - AVR8_PART_IS_DEFINED(ATxmega256A3BU) \ - ) - -#define XMEGA_A4U ( \ - AVR8_PART_IS_DEFINED(ATxmega16A4U) || \ - AVR8_PART_IS_DEFINED(ATxmega32A4U) || \ - AVR8_PART_IS_DEFINED(ATxmega64A4U) || \ - AVR8_PART_IS_DEFINED(ATxmega128A4U) \ - ) -/** @} */ - -/** - * \name AVR XMEGA B series - * @{ - */ -#define XMEGA_B1 ( \ - AVR8_PART_IS_DEFINED(ATxmega64B1) || \ - AVR8_PART_IS_DEFINED(ATxmega128B1) \ - ) - -#define XMEGA_B3 ( \ - AVR8_PART_IS_DEFINED(ATxmega64B3) || \ - AVR8_PART_IS_DEFINED(ATxmega128B3) \ - ) -/** @} */ - -/** - * \name AVR XMEGA C series - * @{ - */ -#define XMEGA_C3 ( \ - AVR8_PART_IS_DEFINED(ATxmega384C3) || \ - AVR8_PART_IS_DEFINED(ATxmega256C3) || \ - AVR8_PART_IS_DEFINED(ATxmega192C3) || \ - AVR8_PART_IS_DEFINED(ATxmega128C3) || \ - AVR8_PART_IS_DEFINED(ATxmega64C3) || \ - AVR8_PART_IS_DEFINED(ATxmega32C3) \ - ) - -#define XMEGA_C4 ( \ - AVR8_PART_IS_DEFINED(ATxmega32C4) || \ - AVR8_PART_IS_DEFINED(ATxmega16C4) \ - ) -/** @} */ - -/** - * \name AVR XMEGA D series - * @{ - */ -#define XMEGA_D3 ( \ - AVR8_PART_IS_DEFINED(ATxmega32D3) || \ - AVR8_PART_IS_DEFINED(ATxmega64D3) || \ - AVR8_PART_IS_DEFINED(ATxmega128D3) || \ - AVR8_PART_IS_DEFINED(ATxmega192D3) || \ - AVR8_PART_IS_DEFINED(ATxmega256D3) || \ - AVR8_PART_IS_DEFINED(ATxmega384D3) \ - ) - -#define XMEGA_D4 ( \ - AVR8_PART_IS_DEFINED(ATxmega16D4) || \ - AVR8_PART_IS_DEFINED(ATxmega32D4) || \ - AVR8_PART_IS_DEFINED(ATxmega64D4) || \ - AVR8_PART_IS_DEFINED(ATxmega128D4) \ - ) -/** @} */ - -/** - * \name AVR XMEGA E series - * @{ - */ -#define XMEGA_E5 ( \ - AVR8_PART_IS_DEFINED(ATxmega8E5) || \ - AVR8_PART_IS_DEFINED(ATxmega16E5) || \ - AVR8_PART_IS_DEFINED(ATxmega32E5) \ - ) -/** @} */ - - -/** - * \name AVR XMEGA families - * @{ - */ -/** AVR XMEGA A family */ -#define XMEGA_A (XMEGA_A1 || XMEGA_A3 || XMEGA_A3B || XMEGA_A4) - -/** AVR XMEGA AU family */ -#define XMEGA_AU (XMEGA_A1U || XMEGA_A3U || XMEGA_A3BU || XMEGA_A4U) - -/** AVR XMEGA B family */ -#define XMEGA_B (XMEGA_B1 || XMEGA_B3) - -/** AVR XMEGA C family */ -#define XMEGA_C (XMEGA_C3 || XMEGA_C4) - -/** AVR XMEGA D family */ -#define XMEGA_D (XMEGA_D3 || XMEGA_D4) - -/** AVR XMEGA E family */ -#define XMEGA_E (XMEGA_E5) -/** @} */ - - -/** AVR XMEGA product line */ -#define XMEGA (XMEGA_A || XMEGA_AU || XMEGA_B || XMEGA_C || XMEGA_D || XMEGA_E) - -/** @} */ - -/** - * \defgroup mega_part_macros_group megaAVR parts - * - * \note These megaAVR groupings are based on the groups in AVR Libc for the - * part header files. They are not names of official megaAVR device series or - * families. - * - * @{ - */ - -/** - * \name ATmegaxx0/xx1 subgroups - * @{ - */ -#define MEGA_XX0 ( \ - AVR8_PART_IS_DEFINED(ATmega640) || \ - AVR8_PART_IS_DEFINED(ATmega1280) || \ - AVR8_PART_IS_DEFINED(ATmega2560) \ - ) - -#define MEGA_XX1 ( \ - AVR8_PART_IS_DEFINED(ATmega1281) || \ - AVR8_PART_IS_DEFINED(ATmega2561) \ - ) -/** @} */ - -/** - * \name megaAVR groups - * @{ - */ -/** ATmegaxx0/xx1 group */ -#define MEGA_XX0_1 (MEGA_XX0 || MEGA_XX1) - -/** ATmegaxx4 group */ -#define MEGA_XX4 ( \ - AVR8_PART_IS_DEFINED(ATmega164A) || \ - AVR8_PART_IS_DEFINED(ATmega164PA) || \ - AVR8_PART_IS_DEFINED(ATmega324A) || \ - AVR8_PART_IS_DEFINED(ATmega324PA) || \ - AVR8_PART_IS_DEFINED(ATmega644) || \ - AVR8_PART_IS_DEFINED(ATmega644A) || \ - AVR8_PART_IS_DEFINED(ATmega644PA) || \ - AVR8_PART_IS_DEFINED(ATmega1284P) || \ - AVR8_PART_IS_DEFINED(ATmega128RFA1) \ - ) - -/** ATmegaxx4 group */ -#define MEGA_XX4_A ( \ - AVR8_PART_IS_DEFINED(ATmega164A) || \ - AVR8_PART_IS_DEFINED(ATmega164PA) || \ - AVR8_PART_IS_DEFINED(ATmega324A) || \ - AVR8_PART_IS_DEFINED(ATmega324PA) || \ - AVR8_PART_IS_DEFINED(ATmega644A) || \ - AVR8_PART_IS_DEFINED(ATmega644PA) || \ - AVR8_PART_IS_DEFINED(ATmega1284P) \ - ) - -/** ATmegaxx8 group */ -#define MEGA_XX8 ( \ - AVR8_PART_IS_DEFINED(ATmega48) || \ - AVR8_PART_IS_DEFINED(ATmega48A) || \ - AVR8_PART_IS_DEFINED(ATmega48PA) || \ - AVR8_PART_IS_DEFINED(ATmega88) || \ - AVR8_PART_IS_DEFINED(ATmega88A) || \ - AVR8_PART_IS_DEFINED(ATmega88PA) || \ - AVR8_PART_IS_DEFINED(ATmega168) || \ - AVR8_PART_IS_DEFINED(ATmega168A) || \ - AVR8_PART_IS_DEFINED(ATmega168PA) || \ - AVR8_PART_IS_DEFINED(ATmega328) || \ - AVR8_PART_IS_DEFINED(ATmega328P) \ - ) - -/** ATmegaxx8A/P/PA group */ -#define MEGA_XX8_A ( \ - AVR8_PART_IS_DEFINED(ATmega48A) || \ - AVR8_PART_IS_DEFINED(ATmega48PA) || \ - AVR8_PART_IS_DEFINED(ATmega88A) || \ - AVR8_PART_IS_DEFINED(ATmega88PA) || \ - AVR8_PART_IS_DEFINED(ATmega168A) || \ - AVR8_PART_IS_DEFINED(ATmega168PA) || \ - AVR8_PART_IS_DEFINED(ATmega328P) \ - ) - -/** ATmegaxx group */ -#define MEGA_XX ( \ - AVR8_PART_IS_DEFINED(ATmega16) || \ - AVR8_PART_IS_DEFINED(ATmega16A) || \ - AVR8_PART_IS_DEFINED(ATmega32) || \ - AVR8_PART_IS_DEFINED(ATmega32A) || \ - AVR8_PART_IS_DEFINED(ATmega64) || \ - AVR8_PART_IS_DEFINED(ATmega64A) || \ - AVR8_PART_IS_DEFINED(ATmega128) || \ - AVR8_PART_IS_DEFINED(ATmega128A) \ - ) - -/** ATmegaxxA/P/PA group */ -#define MEGA_XX_A ( \ - AVR8_PART_IS_DEFINED(ATmega16A) || \ - AVR8_PART_IS_DEFINED(ATmega32A) || \ - AVR8_PART_IS_DEFINED(ATmega64A) || \ - AVR8_PART_IS_DEFINED(ATmega128A) \ - ) -/** ATmegaxxRFA1 group */ -#define MEGA_RFA1 ( \ - AVR8_PART_IS_DEFINED(ATmega128RFA1) \ - ) - -/** ATmegaxxRFR2 group */ -#define MEGA_RFR2 ( \ - AVR8_PART_IS_DEFINED(ATmega64RFR2) || \ - AVR8_PART_IS_DEFINED(ATmega128RFR2) || \ - AVR8_PART_IS_DEFINED(ATmega256RFR2) || \ - AVR8_PART_IS_DEFINED(ATmega644RFR2) || \ - AVR8_PART_IS_DEFINED(ATmega1284RFR2) || \ - AVR8_PART_IS_DEFINED(ATmega2564RFR2) \ - ) - - -/** ATmegaxxRFxx group */ -#define MEGA_RF (MEGA_RFA1 || MEGA_RFR2) - -/** - * \name ATmegaxx_un0/un1/un2 subgroups - * @{ - */ -#define MEGA_XX_UN0 ( \ - AVR8_PART_IS_DEFINED(ATmega16) || \ - AVR8_PART_IS_DEFINED(ATmega16A) || \ - AVR8_PART_IS_DEFINED(ATmega32) || \ - AVR8_PART_IS_DEFINED(ATmega32A) \ - ) - -/** ATmegaxx group without power reduction and - * And interrupt sense register. - */ -#define MEGA_XX_UN1 ( \ - AVR8_PART_IS_DEFINED(ATmega64) || \ - AVR8_PART_IS_DEFINED(ATmega64A) || \ - AVR8_PART_IS_DEFINED(ATmega128) || \ - AVR8_PART_IS_DEFINED(ATmega128A) \ - ) - -/** ATmegaxx group without power reduction and - * And interrupt sense register. - */ -#define MEGA_XX_UN2 ( \ - AVR8_PART_IS_DEFINED(ATmega169P) || \ - AVR8_PART_IS_DEFINED(ATmega169PA) || \ - AVR8_PART_IS_DEFINED(ATmega329P) || \ - AVR8_PART_IS_DEFINED(ATmega329PA) \ - ) - -/** Devices added to complete megaAVR offering. - * Please do not use this group symbol as it is not intended - * to be permanent: the devices should be regrouped. - */ -#define MEGA_UNCATEGORIZED ( \ - AVR8_PART_IS_DEFINED(AT90CAN128) || \ - AVR8_PART_IS_DEFINED(AT90CAN32) || \ - AVR8_PART_IS_DEFINED(AT90CAN64) || \ - AVR8_PART_IS_DEFINED(AT90PWM1) || \ - AVR8_PART_IS_DEFINED(AT90PWM216) || \ - AVR8_PART_IS_DEFINED(AT90PWM2B) || \ - AVR8_PART_IS_DEFINED(AT90PWM316) || \ - AVR8_PART_IS_DEFINED(AT90PWM3B) || \ - AVR8_PART_IS_DEFINED(AT90PWM81) || \ - AVR8_PART_IS_DEFINED(AT90USB1286) || \ - AVR8_PART_IS_DEFINED(AT90USB1287) || \ - AVR8_PART_IS_DEFINED(AT90USB162) || \ - AVR8_PART_IS_DEFINED(AT90USB646) || \ - AVR8_PART_IS_DEFINED(AT90USB647) || \ - AVR8_PART_IS_DEFINED(AT90USB82) || \ - AVR8_PART_IS_DEFINED(ATmega1284) || \ - AVR8_PART_IS_DEFINED(ATmega162) || \ - AVR8_PART_IS_DEFINED(ATmega164P) || \ - AVR8_PART_IS_DEFINED(ATmega165A) || \ - AVR8_PART_IS_DEFINED(ATmega165P) || \ - AVR8_PART_IS_DEFINED(ATmega165PA) || \ - AVR8_PART_IS_DEFINED(ATmega168P) || \ - AVR8_PART_IS_DEFINED(ATmega169A) || \ - AVR8_PART_IS_DEFINED(ATmega16M1) || \ - AVR8_PART_IS_DEFINED(ATmega16U2) || \ - AVR8_PART_IS_DEFINED(ATmega16U4) || \ - AVR8_PART_IS_DEFINED(ATmega256RFA2) || \ - AVR8_PART_IS_DEFINED(ATmega324P) || \ - AVR8_PART_IS_DEFINED(ATmega325) || \ - AVR8_PART_IS_DEFINED(ATmega3250) || \ - AVR8_PART_IS_DEFINED(ATmega3250A) || \ - AVR8_PART_IS_DEFINED(ATmega3250P) || \ - AVR8_PART_IS_DEFINED(ATmega3250PA) || \ - AVR8_PART_IS_DEFINED(ATmega325A) || \ - AVR8_PART_IS_DEFINED(ATmega325P) || \ - AVR8_PART_IS_DEFINED(ATmega325PA) || \ - AVR8_PART_IS_DEFINED(ATmega329) || \ - AVR8_PART_IS_DEFINED(ATmega3290) || \ - AVR8_PART_IS_DEFINED(ATmega3290A) || \ - AVR8_PART_IS_DEFINED(ATmega3290P) || \ - AVR8_PART_IS_DEFINED(ATmega3290PA) || \ - AVR8_PART_IS_DEFINED(ATmega329A) || \ - AVR8_PART_IS_DEFINED(ATmega32M1) || \ - AVR8_PART_IS_DEFINED(ATmega32U2) || \ - AVR8_PART_IS_DEFINED(ATmega32U4) || \ - AVR8_PART_IS_DEFINED(ATmega48P) || \ - AVR8_PART_IS_DEFINED(ATmega644P) || \ - AVR8_PART_IS_DEFINED(ATmega645) || \ - AVR8_PART_IS_DEFINED(ATmega6450) || \ - AVR8_PART_IS_DEFINED(ATmega6450A) || \ - AVR8_PART_IS_DEFINED(ATmega6450P) || \ - AVR8_PART_IS_DEFINED(ATmega645A) || \ - AVR8_PART_IS_DEFINED(ATmega645P) || \ - AVR8_PART_IS_DEFINED(ATmega649) || \ - AVR8_PART_IS_DEFINED(ATmega6490) || \ - AVR8_PART_IS_DEFINED(ATmega6490A) || \ - AVR8_PART_IS_DEFINED(ATmega6490P) || \ - AVR8_PART_IS_DEFINED(ATmega649A) || \ - AVR8_PART_IS_DEFINED(ATmega649P) || \ - AVR8_PART_IS_DEFINED(ATmega64M1) || \ - AVR8_PART_IS_DEFINED(ATmega64RFA2) || \ - AVR8_PART_IS_DEFINED(ATmega8) || \ - AVR8_PART_IS_DEFINED(ATmega8515) || \ - AVR8_PART_IS_DEFINED(ATmega8535) || \ - AVR8_PART_IS_DEFINED(ATmega88P) || \ - AVR8_PART_IS_DEFINED(ATmega8A) || \ - AVR8_PART_IS_DEFINED(ATmega8U2) \ - ) - -/** Unspecified group */ -#define MEGA_UNSPECIFIED (MEGA_XX_UN0 || MEGA_XX_UN1 || MEGA_XX_UN2 || \ - MEGA_UNCATEGORIZED) - -/** @} */ - -/** megaAVR product line */ -#define MEGA (MEGA_XX0_1 || MEGA_XX4 || MEGA_XX8 || MEGA_XX || MEGA_RF || \ - MEGA_UNSPECIFIED) - -/** @} */ - -/** - * \defgroup tiny_part_macros_group tinyAVR parts - * - * @{ - */ - -/** - * \name tinyAVR groups - * @{ - */ - -/** Devices added to complete tinyAVR offering. - * Please do not use this group symbol as it is not intended - * to be permanent: the devices should be regrouped. - */ -#define TINY_UNCATEGORIZED ( \ - AVR8_PART_IS_DEFINED(ATtiny10) || \ - AVR8_PART_IS_DEFINED(ATtiny13) || \ - AVR8_PART_IS_DEFINED(ATtiny13A) || \ - AVR8_PART_IS_DEFINED(ATtiny1634) || \ - AVR8_PART_IS_DEFINED(ATtiny167) || \ - AVR8_PART_IS_DEFINED(ATtiny20) || \ - AVR8_PART_IS_DEFINED(ATtiny2313) || \ - AVR8_PART_IS_DEFINED(ATtiny2313A) || \ - AVR8_PART_IS_DEFINED(ATtiny24) || \ - AVR8_PART_IS_DEFINED(ATtiny24A) || \ - AVR8_PART_IS_DEFINED(ATtiny25) || \ - AVR8_PART_IS_DEFINED(ATtiny26) || \ - AVR8_PART_IS_DEFINED(ATtiny261) || \ - AVR8_PART_IS_DEFINED(ATtiny261A) || \ - AVR8_PART_IS_DEFINED(ATtiny4) || \ - AVR8_PART_IS_DEFINED(ATtiny40) || \ - AVR8_PART_IS_DEFINED(ATtiny4313) || \ - AVR8_PART_IS_DEFINED(ATtiny43U) || \ - AVR8_PART_IS_DEFINED(ATtiny44) || \ - AVR8_PART_IS_DEFINED(ATtiny44A) || \ - AVR8_PART_IS_DEFINED(ATtiny45) || \ - AVR8_PART_IS_DEFINED(ATtiny461) || \ - AVR8_PART_IS_DEFINED(ATtiny461A) || \ - AVR8_PART_IS_DEFINED(ATtiny48) || \ - AVR8_PART_IS_DEFINED(ATtiny5) || \ - AVR8_PART_IS_DEFINED(ATtiny828) || \ - AVR8_PART_IS_DEFINED(ATtiny84) || \ - AVR8_PART_IS_DEFINED(ATtiny84A) || \ - AVR8_PART_IS_DEFINED(ATtiny85) || \ - AVR8_PART_IS_DEFINED(ATtiny861) || \ - AVR8_PART_IS_DEFINED(ATtiny861A) || \ - AVR8_PART_IS_DEFINED(ATtiny87) || \ - AVR8_PART_IS_DEFINED(ATtiny88) || \ - AVR8_PART_IS_DEFINED(ATtiny9) \ - ) - -/** @} */ - -/** tinyAVR product line */ -#define TINY (TINY_UNCATEGORIZED) - -/** @} */ - -/** - * \defgroup sam_part_macros_group SAM parts - * @{ - */ - -/** - * \name SAM3S series - * @{ - */ -#define SAM3S1 ( \ - SAM_PART_IS_DEFINED(SAM3S1A) || \ - SAM_PART_IS_DEFINED(SAM3S1B) || \ - SAM_PART_IS_DEFINED(SAM3S1C) \ - ) - -#define SAM3S2 ( \ - SAM_PART_IS_DEFINED(SAM3S2A) || \ - SAM_PART_IS_DEFINED(SAM3S2B) || \ - SAM_PART_IS_DEFINED(SAM3S2C) \ - ) - -#define SAM3S4 ( \ - SAM_PART_IS_DEFINED(SAM3S4A) || \ - SAM_PART_IS_DEFINED(SAM3S4B) || \ - SAM_PART_IS_DEFINED(SAM3S4C) \ - ) - -#define SAM3S8 ( \ - SAM_PART_IS_DEFINED(SAM3S8B) || \ - SAM_PART_IS_DEFINED(SAM3S8C) \ - ) - -#define SAM3SD8 ( \ - SAM_PART_IS_DEFINED(SAM3SD8B) || \ - SAM_PART_IS_DEFINED(SAM3SD8C) \ - ) -/** @} */ - -/** - * \name SAM3U series - * @{ - */ -#define SAM3U1 ( \ - SAM_PART_IS_DEFINED(SAM3U1C) || \ - SAM_PART_IS_DEFINED(SAM3U1E) \ - ) - -#define SAM3U2 ( \ - SAM_PART_IS_DEFINED(SAM3U2C) || \ - SAM_PART_IS_DEFINED(SAM3U2E) \ - ) - -#define SAM3U4 ( \ - SAM_PART_IS_DEFINED(SAM3U4C) || \ - SAM_PART_IS_DEFINED(SAM3U4E) \ - ) -/** @} */ - -/** - * \name SAM3N series - * @{ - */ -#define SAM3N00 ( \ - SAM_PART_IS_DEFINED(SAM3N00A) || \ - SAM_PART_IS_DEFINED(SAM3N00B) \ - ) - -#define SAM3N0 ( \ - SAM_PART_IS_DEFINED(SAM3N0A) || \ - SAM_PART_IS_DEFINED(SAM3N0B) || \ - SAM_PART_IS_DEFINED(SAM3N0C) \ - ) - -#define SAM3N1 ( \ - SAM_PART_IS_DEFINED(SAM3N1A) || \ - SAM_PART_IS_DEFINED(SAM3N1B) || \ - SAM_PART_IS_DEFINED(SAM3N1C) \ - ) - -#define SAM3N2 ( \ - SAM_PART_IS_DEFINED(SAM3N2A) || \ - SAM_PART_IS_DEFINED(SAM3N2B) || \ - SAM_PART_IS_DEFINED(SAM3N2C) \ - ) - -#define SAM3N4 ( \ - SAM_PART_IS_DEFINED(SAM3N4A) || \ - SAM_PART_IS_DEFINED(SAM3N4B) || \ - SAM_PART_IS_DEFINED(SAM3N4C) \ - ) -/** @} */ - -/** - * \name SAM3X series - * @{ - */ -#define SAM3X4 ( \ - SAM_PART_IS_DEFINED(SAM3X4C) || \ - SAM_PART_IS_DEFINED(SAM3X4E) \ - ) - -#define SAM3X8 ( \ - SAM_PART_IS_DEFINED(SAM3X8C) || \ - SAM_PART_IS_DEFINED(SAM3X8E) || \ - SAM_PART_IS_DEFINED(SAM3X8H) \ - ) -/** @} */ - -/** - * \name SAM3A series - * @{ - */ -#define SAM3A4 ( \ - SAM_PART_IS_DEFINED(SAM3A4C) \ - ) - -#define SAM3A8 ( \ - SAM_PART_IS_DEFINED(SAM3A8C) \ - ) -/** @} */ - -/** - * \name SAM4S series - * @{ - */ -#define SAM4S2 ( \ - SAM_PART_IS_DEFINED(SAM4S2A) || \ - SAM_PART_IS_DEFINED(SAM4S2B) || \ - SAM_PART_IS_DEFINED(SAM4S2C) \ - ) - -#define SAM4S4 ( \ - SAM_PART_IS_DEFINED(SAM4S4A) || \ - SAM_PART_IS_DEFINED(SAM4S4B) || \ - SAM_PART_IS_DEFINED(SAM4S4C) \ - ) - -#define SAM4S8 ( \ - SAM_PART_IS_DEFINED(SAM4S8B) || \ - SAM_PART_IS_DEFINED(SAM4S8C) \ - ) - -#define SAM4S16 ( \ - SAM_PART_IS_DEFINED(SAM4S16B) || \ - SAM_PART_IS_DEFINED(SAM4S16C) \ - ) - -#define SAM4SA16 ( \ - SAM_PART_IS_DEFINED(SAM4SA16B) || \ - SAM_PART_IS_DEFINED(SAM4SA16C) \ - ) - -#define SAM4SD16 ( \ - SAM_PART_IS_DEFINED(SAM4SD16B) || \ - SAM_PART_IS_DEFINED(SAM4SD16C) \ - ) - -#define SAM4SD32 ( \ - SAM_PART_IS_DEFINED(SAM4SD32B) || \ - SAM_PART_IS_DEFINED(SAM4SD32C) \ - ) -/** @} */ - -/** - * \name SAM4L series - * @{ - */ -#define SAM4LS ( \ - SAM_PART_IS_DEFINED(SAM4LS2A) || \ - SAM_PART_IS_DEFINED(SAM4LS2B) || \ - SAM_PART_IS_DEFINED(SAM4LS2C) || \ - SAM_PART_IS_DEFINED(SAM4LS4A) || \ - SAM_PART_IS_DEFINED(SAM4LS4B) || \ - SAM_PART_IS_DEFINED(SAM4LS4C) || \ - SAM_PART_IS_DEFINED(SAM4LS8A) || \ - SAM_PART_IS_DEFINED(SAM4LS8B) || \ - SAM_PART_IS_DEFINED(SAM4LS8C) \ - ) - -#define SAM4LC ( \ - SAM_PART_IS_DEFINED(SAM4LC2A) || \ - SAM_PART_IS_DEFINED(SAM4LC2B) || \ - SAM_PART_IS_DEFINED(SAM4LC2C) || \ - SAM_PART_IS_DEFINED(SAM4LC4A) || \ - SAM_PART_IS_DEFINED(SAM4LC4B) || \ - SAM_PART_IS_DEFINED(SAM4LC4C) || \ - SAM_PART_IS_DEFINED(SAM4LC8A) || \ - SAM_PART_IS_DEFINED(SAM4LC8B) || \ - SAM_PART_IS_DEFINED(SAM4LC8C) \ - ) -/** @} */ - -/** - * \name SAMD20 series - * @{ - */ -#define SAMD20J ( \ - SAM_PART_IS_DEFINED(SAMD20J14) || \ - SAM_PART_IS_DEFINED(SAMD20J15) || \ - SAM_PART_IS_DEFINED(SAMD20J16) || \ - SAM_PART_IS_DEFINED(SAMD20J17) || \ - SAM_PART_IS_DEFINED(SAMD20J18) \ - ) - -#define SAMD20G ( \ - SAM_PART_IS_DEFINED(SAMD20G14) || \ - SAM_PART_IS_DEFINED(SAMD20G15) || \ - SAM_PART_IS_DEFINED(SAMD20G16) || \ - SAM_PART_IS_DEFINED(SAMD20G17) || \ - SAM_PART_IS_DEFINED(SAMD20G17U) || \ - SAM_PART_IS_DEFINED(SAMD20G18) || \ - SAM_PART_IS_DEFINED(SAMD20G18U) \ - ) - -#define SAMD20E ( \ - SAM_PART_IS_DEFINED(SAMD20E14) || \ - SAM_PART_IS_DEFINED(SAMD20E15) || \ - SAM_PART_IS_DEFINED(SAMD20E16) || \ - SAM_PART_IS_DEFINED(SAMD20E17) || \ - SAM_PART_IS_DEFINED(SAMD20E18) \ - ) -/** @} */ - -/** - * \name SAMD21 series - * @{ - */ -#define SAMD21J ( \ - SAM_PART_IS_DEFINED(SAMD21J15A) || \ - SAM_PART_IS_DEFINED(SAMD21J16A) || \ - SAM_PART_IS_DEFINED(SAMD21J17A) || \ - SAM_PART_IS_DEFINED(SAMD21J18A) || \ - SAM_PART_IS_DEFINED(SAMD21J15B) || \ - SAM_PART_IS_DEFINED(SAMD21J16B) \ - ) - -#define SAMD21G ( \ - SAM_PART_IS_DEFINED(SAMD21G15A) || \ - SAM_PART_IS_DEFINED(SAMD21G16A) || \ - SAM_PART_IS_DEFINED(SAMD21G17A) || \ - SAM_PART_IS_DEFINED(SAMD21G17AU) || \ - SAM_PART_IS_DEFINED(SAMD21G18A) || \ - SAM_PART_IS_DEFINED(SAMD21G18AU) || \ - SAM_PART_IS_DEFINED(SAMD21G15B) || \ - SAM_PART_IS_DEFINED(SAMD21G16B) || \ - SAM_PART_IS_DEFINED(SAMD21G15L) || \ - SAM_PART_IS_DEFINED(SAMD21G16L) \ - ) - -#define SAMD21GXXL ( \ - SAM_PART_IS_DEFINED(SAMD21G15L) || \ - SAM_PART_IS_DEFINED(SAMD21G16L) \ - ) - -#define SAMD21E ( \ - SAM_PART_IS_DEFINED(SAMD21E15A) || \ - SAM_PART_IS_DEFINED(SAMD21E16A) || \ - SAM_PART_IS_DEFINED(SAMD21E17A) || \ - SAM_PART_IS_DEFINED(SAMD21E18A) || \ - SAM_PART_IS_DEFINED(SAMD21E15B) || \ - SAM_PART_IS_DEFINED(SAMD21E15BU) || \ - SAM_PART_IS_DEFINED(SAMD21E16B) || \ - SAM_PART_IS_DEFINED(SAMD21E16BU) || \ - SAM_PART_IS_DEFINED(SAMD21E15L) || \ - SAM_PART_IS_DEFINED(SAMD21E16L) \ - ) - -#define SAMD21EXXL ( \ - SAM_PART_IS_DEFINED(SAMD21E15L) || \ - SAM_PART_IS_DEFINED(SAMD21E16L) \ - ) - -/** @} */ - -/** - * \name SAMR21 series - * @{ - */ -#define SAMR21G ( \ - SAM_PART_IS_DEFINED(SAMR21G16A) || \ - SAM_PART_IS_DEFINED(SAMR21G17A) || \ - SAM_PART_IS_DEFINED(SAMR21G18A) \ - ) - -#define SAMR21E ( \ - SAM_PART_IS_DEFINED(SAMR21E16A) || \ - SAM_PART_IS_DEFINED(SAMR21E17A) || \ - SAM_PART_IS_DEFINED(SAMR21E18A) || \ - SAM_PART_IS_DEFINED(SAMR21E19A) \ - ) -/** @} */ - -/** - * \name SAMD09 series - * @{ - */ -#define SAMD09C ( \ - SAM_PART_IS_DEFINED(SAMD09C13A) \ - ) - -#define SAMD09D ( \ - SAM_PART_IS_DEFINED(SAMD09D14A) \ - ) -/** @} */ - -/** - * \name SAMD10 series - * @{ - */ -#define SAMD10C ( \ - SAM_PART_IS_DEFINED(SAMD10C12A) || \ - SAM_PART_IS_DEFINED(SAMD10C13A) || \ - SAM_PART_IS_DEFINED(SAMD10C14A) \ - ) - -#define SAMD10DS ( \ - SAM_PART_IS_DEFINED(SAMD10D12AS) || \ - SAM_PART_IS_DEFINED(SAMD10D13AS) || \ - SAM_PART_IS_DEFINED(SAMD10D14AS) \ - ) - -#define SAMD10DM ( \ - SAM_PART_IS_DEFINED(SAMD10D12AM) || \ - SAM_PART_IS_DEFINED(SAMD10D13AM) || \ - SAM_PART_IS_DEFINED(SAMD10D14AM) \ - ) -/** @} */ - -/** - * \name SAMD11 series - * @{ - */ -#define SAMD11C ( \ - SAM_PART_IS_DEFINED(SAMD11C14A) \ - ) - -#define SAMD11DS ( \ - SAM_PART_IS_DEFINED(SAMD11D14AS) \ - ) - -#define SAMD11DM ( \ - SAM_PART_IS_DEFINED(SAMD11D14AM) \ - ) -/** @} */ - -/** - * \name SAML21 series - * @{ - */ -#define SAML21E ( \ - SAM_PART_IS_DEFINED(SAML21E18A) || \ - SAM_PART_IS_DEFINED(SAML21E15B) || \ - SAM_PART_IS_DEFINED(SAML21E16B) || \ - SAM_PART_IS_DEFINED(SAML21E17B) || \ - SAM_PART_IS_DEFINED(SAML21E18B) \ - ) - -#define SAML21G ( \ - SAM_PART_IS_DEFINED(SAML21G18A) || \ - SAM_PART_IS_DEFINED(SAML21G16B) || \ - SAM_PART_IS_DEFINED(SAML21G17B) || \ - SAM_PART_IS_DEFINED(SAML21G18B) \ - ) - -#define SAML21J ( \ - SAM_PART_IS_DEFINED(SAML21J18A) || \ - SAM_PART_IS_DEFINED(SAML21J16B) || \ - SAM_PART_IS_DEFINED(SAML21J17B) || \ - SAM_PART_IS_DEFINED(SAML21J18B) \ - ) - -/* Group for SAML21 A variant: SAML21[E/G/J][18]A */ -#define SAML21XXXA ( \ - SAM_PART_IS_DEFINED(SAML21E18A) || \ - SAM_PART_IS_DEFINED(SAML21G18A) || \ - SAM_PART_IS_DEFINED(SAML21J18A) \ - ) - -/* Group for SAML21 B variant: SAML21[E/G/J][15/16/1718]B */ -#define SAML21XXXB ( \ - SAM_PART_IS_DEFINED(SAML21E15B) || \ - SAM_PART_IS_DEFINED(SAML21E16B) || \ - SAM_PART_IS_DEFINED(SAML21E17B) || \ - SAM_PART_IS_DEFINED(SAML21E18B) || \ - SAM_PART_IS_DEFINED(SAML21G16B) || \ - SAM_PART_IS_DEFINED(SAML21G17B) || \ - SAM_PART_IS_DEFINED(SAML21G18B) || \ - SAM_PART_IS_DEFINED(SAML21J16B) || \ - SAM_PART_IS_DEFINED(SAML21J17B) || \ - SAM_PART_IS_DEFINED(SAML21J18B) \ - ) - -/** @} */ - -/** - * \name SAML22 series - * @{ - */ -#define SAML22N ( \ - SAM_PART_IS_DEFINED(SAML22N16A) || \ - SAM_PART_IS_DEFINED(SAML22N17A) || \ - SAM_PART_IS_DEFINED(SAML22N18A) \ - ) - -#define SAML22G ( \ - SAM_PART_IS_DEFINED(SAML22G16A) || \ - SAM_PART_IS_DEFINED(SAML22G17A) || \ - SAM_PART_IS_DEFINED(SAML22G18A) \ - ) - -#define SAML22J ( \ - SAM_PART_IS_DEFINED(SAML22J16A) || \ - SAM_PART_IS_DEFINED(SAML22J17A) || \ - SAM_PART_IS_DEFINED(SAML22J18A) \ - ) -/** @} */ - -/** - * \name SAMDA0 series - * @{ - */ -#define SAMDA0J ( \ - SAM_PART_IS_DEFINED(SAMDA0J14A) || \ - SAM_PART_IS_DEFINED(SAMDA0J15A) || \ - SAM_PART_IS_DEFINED(SAMDA0J16A) \ - ) - -#define SAMDA0G ( \ - SAM_PART_IS_DEFINED(SAMDA0G14A) || \ - SAM_PART_IS_DEFINED(SAMDA0G15A) || \ - SAM_PART_IS_DEFINED(SAMDA0G16A) \ - ) - -#define SAMDA0E ( \ - SAM_PART_IS_DEFINED(SAMDA0E14A) || \ - SAM_PART_IS_DEFINED(SAMDA0E15A) || \ - SAM_PART_IS_DEFINED(SAMDA0E16A) \ - ) -/** @} */ - -/** - * \name SAMDA1 series - * @{ - */ -#define SAMDA1J ( \ - SAM_PART_IS_DEFINED(SAMDA1J14A) || \ - SAM_PART_IS_DEFINED(SAMDA1J15A) || \ - SAM_PART_IS_DEFINED(SAMDA1J16A) \ - ) - -#define SAMDA1G ( \ - SAM_PART_IS_DEFINED(SAMDA1G14A) || \ - SAM_PART_IS_DEFINED(SAMDA1G15A) || \ - SAM_PART_IS_DEFINED(SAMDA1G16A) \ - ) - -#define SAMDA1E ( \ - SAM_PART_IS_DEFINED(SAMDA1E14A) || \ - SAM_PART_IS_DEFINED(SAMDA1E15A) || \ - SAM_PART_IS_DEFINED(SAMDA1E16A) \ - ) -/** @} */ - -/** - * \name SAMC20 series - * @{ - */ -#define SAMC20E ( \ - SAM_PART_IS_DEFINED(SAMC20E15A) || \ - SAM_PART_IS_DEFINED(SAMC20E16A) || \ - SAM_PART_IS_DEFINED(SAMC20E17A) || \ - SAM_PART_IS_DEFINED(SAMC20E18A) \ - ) - -#define SAMC20G ( \ - SAM_PART_IS_DEFINED(SAMC20G15A) || \ - SAM_PART_IS_DEFINED(SAMC20G16A) || \ - SAM_PART_IS_DEFINED(SAMC20G17A) || \ - SAM_PART_IS_DEFINED(SAMC20G18A) \ - ) - -#define SAMC20J ( \ - SAM_PART_IS_DEFINED(SAMC20J15A) || \ - SAM_PART_IS_DEFINED(SAMC20J16A) || \ - SAM_PART_IS_DEFINED(SAMC20J17A) || \ - SAM_PART_IS_DEFINED(SAMC20J18A) \ - ) -/** @} */ - -/** - * \name SAMC21 series - * @{ - */ -#define SAMC21E ( \ - SAM_PART_IS_DEFINED(SAMC21E15A) || \ - SAM_PART_IS_DEFINED(SAMC21E16A) || \ - SAM_PART_IS_DEFINED(SAMC21E17A) || \ - SAM_PART_IS_DEFINED(SAMC21E18A) \ - ) - -#define SAMC21G ( \ - SAM_PART_IS_DEFINED(SAMC21G15A) || \ - SAM_PART_IS_DEFINED(SAMC21G16A) || \ - SAM_PART_IS_DEFINED(SAMC21G17A) || \ - SAM_PART_IS_DEFINED(SAMC21G18A) \ - ) - -#define SAMC21J ( \ - SAM_PART_IS_DEFINED(SAMC21J15A) || \ - SAM_PART_IS_DEFINED(SAMC21J16A) || \ - SAM_PART_IS_DEFINED(SAMC21J17A) || \ - SAM_PART_IS_DEFINED(SAMC21J18A) \ - ) -/** @} */ - -/** - * \name SAM4E series - * @{ - */ -#define SAM4E8 ( \ - SAM_PART_IS_DEFINED(SAM4E8C) || \ - SAM_PART_IS_DEFINED(SAM4E8E) \ - ) - -#define SAM4E16 ( \ - SAM_PART_IS_DEFINED(SAM4E16C) || \ - SAM_PART_IS_DEFINED(SAM4E16E) \ - ) -/** @} */ - -/** - * \name SAM4N series - * @{ - */ -#define SAM4N8 ( \ - SAM_PART_IS_DEFINED(SAM4N8A) || \ - SAM_PART_IS_DEFINED(SAM4N8B) || \ - SAM_PART_IS_DEFINED(SAM4N8C) \ - ) - -#define SAM4N16 ( \ - SAM_PART_IS_DEFINED(SAM4N16B) || \ - SAM_PART_IS_DEFINED(SAM4N16C) \ - ) -/** @} */ - -/** - * \name SAM4C series - * @{ - */ -#define SAM4C4_0 ( \ - SAM_PART_IS_DEFINED(SAM4C4C_0) \ - ) - -#define SAM4C4_1 ( \ - SAM_PART_IS_DEFINED(SAM4C4C_1) \ - ) - -#define SAM4C4 (SAM4C4_0 || SAM4C4_1) - -#define SAM4C8_0 ( \ - SAM_PART_IS_DEFINED(SAM4C8C_0) \ - ) - -#define SAM4C8_1 ( \ - SAM_PART_IS_DEFINED(SAM4C8C_1) \ - ) - -#define SAM4C8 (SAM4C8_0 || SAM4C8_1) - -#define SAM4C16_0 ( \ - SAM_PART_IS_DEFINED(SAM4C16C_0) \ - ) - -#define SAM4C16_1 ( \ - SAM_PART_IS_DEFINED(SAM4C16C_1) \ - ) - -#define SAM4C16 (SAM4C16_0 || SAM4C16_1) - -#define SAM4C32_0 ( \ - SAM_PART_IS_DEFINED(SAM4C32C_0) ||\ - SAM_PART_IS_DEFINED(SAM4C32E_0) \ - ) - -#define SAM4C32_1 ( \ - SAM_PART_IS_DEFINED(SAM4C32C_1) ||\ - SAM_PART_IS_DEFINED(SAM4C32E_1) \ - ) - - -#define SAM4C32 (SAM4C32_0 || SAM4C32_1) - -/** @} */ - -/** - * \name SAM4CM series - * @{ - */ -#define SAM4CMP8_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMP8C_0) \ - ) - -#define SAM4CMP8_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMP8C_1) \ - ) - -#define SAM4CMP8 (SAM4CMP8_0 || SAM4CMP8_1) - -#define SAM4CMP16_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMP16C_0) \ - ) - -#define SAM4CMP16_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMP16C_1) \ - ) - -#define SAM4CMP16 (SAM4CMP16_0 || SAM4CMP16_1) - -#define SAM4CMP32_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMP32C_0) \ - ) - -#define SAM4CMP32_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMP32C_1) \ - ) - -#define SAM4CMP32 (SAM4CMP32_0 || SAM4CMP32_1) - -#define SAM4CMS4_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMS4C_0) \ - ) - -#define SAM4CMS4_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMS4C_1) \ - ) - -#define SAM4CMS4 (SAM4CMS4_0 || SAM4CMS4_1) - -#define SAM4CMS8_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMS8C_0) \ - ) - -#define SAM4CMS8_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMS8C_1) \ - ) - -#define SAM4CMS8 (SAM4CMS8_0 || SAM4CMS8_1) - -#define SAM4CMS16_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMS16C_0) \ - ) - -#define SAM4CMS16_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMS16C_1) \ - ) - -#define SAM4CMS16 (SAM4CMS16_0 || SAM4CMS16_1) - -#define SAM4CMS32_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMS32C_0) \ - ) - -#define SAM4CMS32_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMS32C_1) \ - ) - -#define SAM4CMS32 (SAM4CMS32_0 || SAM4CMS32_1) - -/** @} */ - -/** - * \name SAM4CP series - * @{ - */ -#define SAM4CP16_0 ( \ - SAM_PART_IS_DEFINED(SAM4CP16B_0) \ - ) - -#define SAM4CP16_1 ( \ - SAM_PART_IS_DEFINED(SAM4CP16B_1) \ - ) - -#define SAM4CP16 (SAM4CP16_0 || SAM4CP16_1) -/** @} */ - -/** - * \name SAMG series - * @{ - */ -#define SAMG51 ( \ - SAM_PART_IS_DEFINED(SAMG51G18) \ - ) - -#define SAMG53 ( \ - SAM_PART_IS_DEFINED(SAMG53G19) ||\ - SAM_PART_IS_DEFINED(SAMG53N19) \ - ) - -#define SAMG54 ( \ - SAM_PART_IS_DEFINED(SAMG54G19) ||\ - SAM_PART_IS_DEFINED(SAMG54J19) ||\ - SAM_PART_IS_DEFINED(SAMG54N19) \ - ) - -#define SAMG55 ( \ - SAM_PART_IS_DEFINED(SAMG55G18) ||\ - SAM_PART_IS_DEFINED(SAMG55G19) ||\ - SAM_PART_IS_DEFINED(SAMG55J18) ||\ - SAM_PART_IS_DEFINED(SAMG55J19) ||\ - SAM_PART_IS_DEFINED(SAMG55N19) \ - ) -/** @} */ - -/** - * \name SAMV71 series - * @{ - */ -#define SAMV71J ( \ - SAM_PART_IS_DEFINED(SAMV71J19) || \ - SAM_PART_IS_DEFINED(SAMV71J20) || \ - SAM_PART_IS_DEFINED(SAMV71J21) \ - ) - -#define SAMV71N ( \ - SAM_PART_IS_DEFINED(SAMV71N19) || \ - SAM_PART_IS_DEFINED(SAMV71N20) || \ - SAM_PART_IS_DEFINED(SAMV71N21) \ - ) - -#define SAMV71Q ( \ - SAM_PART_IS_DEFINED(SAMV71Q19) || \ - SAM_PART_IS_DEFINED(SAMV71Q20) || \ - SAM_PART_IS_DEFINED(SAMV71Q21) \ - ) -/** @} */ - -/** - * \name SAMV70 series - * @{ - */ -#define SAMV70J ( \ - SAM_PART_IS_DEFINED(SAMV70J19) || \ - SAM_PART_IS_DEFINED(SAMV70J20) \ - ) - -#define SAMV70N ( \ - SAM_PART_IS_DEFINED(SAMV70N19) || \ - SAM_PART_IS_DEFINED(SAMV70N20) \ - ) - -#define SAMV70Q ( \ - SAM_PART_IS_DEFINED(SAMV70Q19) || \ - SAM_PART_IS_DEFINED(SAMV70Q20) \ - ) -/** @} */ - -/** - * \name SAMS70 series - * @{ - */ -#define SAMS70J ( \ - SAM_PART_IS_DEFINED(SAMS70J19) || \ - SAM_PART_IS_DEFINED(SAMS70J20) || \ - SAM_PART_IS_DEFINED(SAMS70J21) \ - ) - -#define SAMS70N ( \ - SAM_PART_IS_DEFINED(SAMS70N19) || \ - SAM_PART_IS_DEFINED(SAMS70N20) || \ - SAM_PART_IS_DEFINED(SAMS70N21) \ - ) - -#define SAMS70Q ( \ - SAM_PART_IS_DEFINED(SAMS70Q19) || \ - SAM_PART_IS_DEFINED(SAMS70Q20) || \ - SAM_PART_IS_DEFINED(SAMS70Q21) \ - ) -/** @} */ - -/** - * \name SAME70 series - * @{ - */ -#define SAME70J ( \ - SAM_PART_IS_DEFINED(SAME70J19) || \ - SAM_PART_IS_DEFINED(SAME70J20) || \ - SAM_PART_IS_DEFINED(SAME70J21) \ - ) - -#define SAME70N ( \ - SAM_PART_IS_DEFINED(SAME70N19) || \ - SAM_PART_IS_DEFINED(SAME70N20) || \ - SAM_PART_IS_DEFINED(SAME70N21) \ - ) - -#define SAME70Q ( \ - SAM_PART_IS_DEFINED(SAME70Q19) || \ - SAM_PART_IS_DEFINED(SAME70Q20) || \ - SAM_PART_IS_DEFINED(SAME70Q21) \ - ) -/** @} */ - -/** - * \name SAM families - * @{ - */ -/** SAM3S Family */ -#define SAM3S (SAM3S1 || SAM3S2 || SAM3S4 || SAM3S8 || SAM3SD8) - -/** SAM3U Family */ -#define SAM3U (SAM3U1 || SAM3U2 || SAM3U4) - -/** SAM3N Family */ -#define SAM3N (SAM3N00 || SAM3N0 || SAM3N1 || SAM3N2 || SAM3N4) - -/** SAM3XA Family */ -#define SAM3XA (SAM3X4 || SAM3X8 || SAM3A4 || SAM3A8) - -/** SAM4S Family */ -#define SAM4S (SAM4S2 || SAM4S4 || SAM4S8 || SAM4S16 || SAM4SA16 || SAM4SD16 || SAM4SD32) - -/** SAM4L Family */ -#define SAM4L (SAM4LS || SAM4LC) - -/** SAMD20 Family */ -#define SAMD20 (SAMD20J || SAMD20G || SAMD20E) - -/** SAMD21 Family */ -#define SAMD21 (SAMD21J || SAMD21G || SAMD21E) - -/** SAMD09 Family */ -#define SAMD09 (SAMD09C || SAMD09D) - -/** SAMD10 Family */ -#define SAMD10 (SAMD10C || SAMD10DS || SAMD10DM) - -/** SAMD11 Family */ -#define SAMD11 (SAMD11C || SAMD11DS || SAMD11DM) - -/** SAMDA1 Family */ -#define SAMDA1 (SAMDA1J || SAMDA1G || SAMDA1E) - -/** SAMD Family */ -#define SAMD (SAMD20 || SAMD21 || SAMD09 || SAMD10 || SAMD11 || SAMDA1) - -/** SAMR21 Family */ -#define SAMR21 (SAMR21G || SAMR21E) - -/** SAML21 Family */ -#define SAML21 (SAML21J || SAML21G || SAML21E) - -/** SAML22 Family */ -#define SAML22 (SAML22J || SAML22G || SAML22N) -/** SAMC20 Family */ -#define SAMC20 (SAMC20J || SAMC20G || SAMC20E) - -/** SAMC21 Family */ -#define SAMC21 (SAMC21J || SAMC21G || SAMC21E) - -/** SAM4E Family */ -#define SAM4E (SAM4E8 || SAM4E16) - -/** SAM4N Family */ -#define SAM4N (SAM4N8 || SAM4N16) - -/** SAM4C Family */ -#define SAM4C_0 (SAM4C4_0 || SAM4C8_0 || SAM4C16_0 || SAM4C32_0) -#define SAM4C_1 (SAM4C4_1 || SAM4C8_1 || SAM4C16_1 || SAM4C32_1) -#define SAM4C (SAM4C4 || SAM4C8 || SAM4C16 || SAM4C32) - -/** SAM4CM Family */ -#define SAM4CM_0 (SAM4CMP8_0 || SAM4CMP16_0 || SAM4CMP32_0 || \ - SAM4CMS4_0 || SAM4CMS8_0 || SAM4CMS16_0 || SAM4CMS32_0) -#define SAM4CM_1 (SAM4CMP8_1 || SAM4CMP16_1 || SAM4CMP32_1 || \ - SAM4CMS4_1 || SAM4CMS8_1 || SAM4CMS16_1 || SAM4CMS32_1) -#define SAM4CM (SAM4CMP8 || SAM4CMP16 || SAM4CMP32 || \ - SAM4CMS4 || SAM4CMS8 || SAM4CMS16 || SAM4CMS32) - -/** SAM4CP Family */ -#define SAM4CP_0 (SAM4CP16_0) -#define SAM4CP_1 (SAM4CP16_1) -#define SAM4CP (SAM4CP16) - -/** SAMG Family */ -#define SAMG (SAMG51 || SAMG53 || SAMG54 || SAMG55) - -/** SAMV71 Family */ -#define SAMV71 (SAMV71J || SAMV71N || SAMV71Q) - -/** SAMV70 Family */ -#define SAMV70 (SAMV70J || SAMV70N || SAMV70Q) - -/** SAME70 Family */ -#define SAME70 (SAME70J || SAME70N || SAME70Q) - -/** SAMS70 Family */ -#define SAMS70 (SAMS70J || SAMS70N || SAMS70Q) - -/** SAM0 product line (cortex-m0+) */ -#define SAM0 (SAMD20 || SAMD21 || SAMR21 || SAMD10 || SAMD11 || SAML21 ||\ - SAMDA1 || SAMC20 || SAMC21 || SAML22 || SAMD09) - -/** @} */ - -/** SAM product line */ -#define SAM (SAM3S || SAM3U || SAM3N || SAM3XA || SAM4S || SAM4L || SAM4E || \ - SAM0 || SAM4N || SAM4C || SAM4CM || SAM4CP || SAMG || SAMV71 || SAMV70 || SAME70 || SAMS70) - -/** @} */ - -/** @} */ - -/** @} */ - -#endif /* ATMEL_PARTS_H */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/pinmux.c b/feather_sensor_lte/libraries/Adafruit_ASFcore/pinmux.c deleted file mode 100644 index a2c9c7c..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/pinmux.c +++ /dev/null @@ -1,311 +0,0 @@ -/** - * \file - * - * \brief SAM Pin Multiplexer Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#include - -/** - * \internal - * Writes out a given configuration of a Port pin configuration to the - * hardware module. - * - * \note If the pin direction is set as an output, the pull-up/pull-down input - * configuration setting is ignored. - * - * \param[in] port Base of the PORT module to configure - * \param[in] pin_mask Mask of the port pin to configure - * \param[in] config Configuration settings for the pin - */ -static void _system_pinmux_config( - PortGroup *const port, - const uint32_t pin_mask, - const struct system_pinmux_config *const config) -{ - Assert(port); - Assert(config); - - /* Track the configuration bits into a temporary variable before writing */ - uint32_t pin_cfg = 0; - - /* Enabled powersave mode, don't create configuration */ - if (!config->powersave) { - /* Enable the pin peripheral MUX flag if non-GPIO selected (pinmux will - * be written later) and store the new MUX mask */ - if (config->mux_position != SYSTEM_PINMUX_GPIO) { - pin_cfg |= PORT_WRCONFIG_PMUXEN; - pin_cfg |= (config->mux_position << PORT_WRCONFIG_PMUX_Pos); - } - - /* Check if the user has requested that the input buffer be enabled */ - if ((config->direction == SYSTEM_PINMUX_PIN_DIR_INPUT) || - (config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK)) { - /* Enable input buffer flag */ - pin_cfg |= PORT_WRCONFIG_INEN; - - /* Enable pull-up/pull-down control flag if requested */ - if (config->input_pull != SYSTEM_PINMUX_PIN_PULL_NONE) { - pin_cfg |= PORT_WRCONFIG_PULLEN; - } - - /* Clear the port DIR bits to disable the output buffer */ - port->DIRCLR.reg = pin_mask; - } - - /* Check if the user has requested that the output buffer be enabled */ - if ((config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT) || - (config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK)) { - /* Cannot use a pull-up if the output driver is enabled, - * if requested the input buffer can only sample the current - * output state */ - pin_cfg &= ~PORT_WRCONFIG_PULLEN; - } - } else { - port->DIRCLR.reg = pin_mask; - } - - /* The Write Configuration register (WRCONFIG) requires the - * pins to to grouped into two 16-bit half-words - split them out here */ - uint32_t lower_pin_mask = (pin_mask & 0xFFFF); - uint32_t upper_pin_mask = (pin_mask >> 16); - - /* Configure the lower 16-bits of the port to the desired configuration, - * including the pin peripheral multiplexer just in case it is enabled */ - port->WRCONFIG.reg - = (lower_pin_mask << PORT_WRCONFIG_PINMASK_Pos) | - pin_cfg | PORT_WRCONFIG_WRPMUX | PORT_WRCONFIG_WRPINCFG; - - /* Configure the upper 16-bits of the port to the desired configuration, - * including the pin peripheral multiplexer just in case it is enabled */ - port->WRCONFIG.reg - = (upper_pin_mask << PORT_WRCONFIG_PINMASK_Pos) | - pin_cfg | PORT_WRCONFIG_WRPMUX | PORT_WRCONFIG_WRPINCFG | - PORT_WRCONFIG_HWSEL; - - if(!config->powersave) { - /* Set the pull-up state once the port pins are configured if one was - * requested and it does not violate the valid set of port - * configurations */ - if (pin_cfg & PORT_WRCONFIG_PULLEN) { - /* Set the OUT register bits to enable the pull-up if requested, - * clear to enable pull-down */ - if (config->input_pull == SYSTEM_PINMUX_PIN_PULL_UP) { - port->OUTSET.reg = pin_mask; - } else { - port->OUTCLR.reg = pin_mask; - } - } - - /* Check if the user has requested that the output buffer be enabled */ - if ((config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT) || - (config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK)) { - /* Set the port DIR bits to enable the output buffer */ - port->DIRSET.reg = pin_mask; - } - } -} - -/** - * \brief Writes a Port pin configuration to the hardware module. - * - * Writes out a given configuration of a Port pin configuration to the hardware - * module. - * - * \note If the pin direction is set as an output, the pull-up/pull-down input - * configuration setting is ignored. - * - * \param[in] gpio_pin Index of the GPIO pin to configure - * \param[in] config Configuration settings for the pin - */ -void system_pinmux_pin_set_config( - const uint8_t gpio_pin, - const struct system_pinmux_config *const config) -{ - PortGroup *const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); - uint32_t pin_mask = (1UL << (gpio_pin % 32)); - - _system_pinmux_config(port, pin_mask, config); -} - -/** - * \brief Writes a Port pin group configuration to the hardware module. - * - * Writes out a given configuration of a Port pin group configuration to the - * hardware module. - * - * \note If the pin direction is set as an output, the pull-up/pull-down input - * configuration setting is ignored. - * - * \param[in] port Base of the PORT module to configure - * \param[in] mask Mask of the port pin(s) to configure - * \param[in] config Configuration settings for the pin - */ -void system_pinmux_group_set_config( - PortGroup *const port, - const uint32_t mask, - const struct system_pinmux_config *const config) -{ - Assert(port); - - for (int i = 0; i < 32; i++) { - if (mask & (1UL << i)) { - _system_pinmux_config(port, (1UL << i), config); - } - } -} - -/** - * \brief Configures the input sampling mode for a group of pins. - * - * Configures the input sampling mode for a group of pins, to - * control when the physical I/O pin value is sampled and - * stored inside the microcontroller. - * - * \param[in] port Base of the PORT module to configure - * \param[in] mask Mask of the port pin(s) to configure - * \param[in] mode New pin sampling mode to configure - */ -void system_pinmux_group_set_input_sample_mode( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_sample mode) -{ - Assert(port); - - if (mode == SYSTEM_PINMUX_PIN_SAMPLE_ONDEMAND) { - port->CTRL.reg |= mask; - } else { - port->CTRL.reg &= ~mask; - } -} - -#ifdef FEATURE_SYSTEM_PINMUX_SLEWRATE_LIMITER -/** - * \brief Configures the output slew rate mode for a group of pins. - * - * Configures the output slew rate mode for a group of pins, to - * control the speed at which the physical output pin can react to - * logical changes of the I/O pin value. - * - * \param[in] port Base of the PORT module to configure - * \param[in] mask Mask of the port pin(s) to configure - * \param[in] mode New pin slew rate mode to configure - */ -void system_pinmux_group_set_output_slew_rate( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_slew_rate mode) -{ - Assert(port); - - for (int i = 0; i < 32; i++) { - if (mask & (1UL << i)) { - if (mode == SYSTEM_PINMUX_PIN_SLEW_RATE_LIMITED) { - port->PINCFG[i].reg |= PORT_PINCFG_SLEWLIM; - } else { - port->PINCFG[i].reg &= ~PORT_PINCFG_SLEWLIM; - } - } - } -} -#endif - -#ifdef FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTH -/** - * \brief Configures the output driver strength mode for a group of pins. - * - * Configures the output drive strength for a group of pins, to - * control the amount of current the pad is able to sink/source. - * - * \param[in] port Base of the PORT module to configure - * \param[in] mask Mask of the port pin(s) to configure - * \param[in] mode New output driver strength mode to configure - */ -void system_pinmux_group_set_output_strength( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_strength mode) -{ - Assert(port); - - for (int i = 0; i < 32; i++) { - if (mask & (1UL << i)) { - if (mode == SYSTEM_PINMUX_PIN_STRENGTH_HIGH) { - port->PINCFG[i].reg |= PORT_PINCFG_DRVSTR; - } else { - port->PINCFG[i].reg &= ~PORT_PINCFG_DRVSTR; - } - } - } -} -#endif - -#ifdef FEATURE_SYSTEM_PINMUX_OPEN_DRAIN -/** - * \brief Configures the output driver mode for a group of pins. - * - * Configures the output driver mode for a group of pins, to - * control the pad behavior. - * - * \param[in] port Base of the PORT module to configure - * \param[in] mask Mask of the port pin(s) to configure - * \param[in] mode New pad output driver mode to configure - */ -void system_pinmux_group_set_output_drive( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_drive mode) -{ - Assert(port); - - for (int i = 0; i < 32; i++) { - if (mask & (1UL << i)) { - if (mode == SYSTEM_PINMUX_PIN_DRIVE_OPEN_DRAIN) { - port->PINCFG[i].reg |= PORT_PINCFG_ODRAIN; - } else { - port->PINCFG[i].reg &= ~PORT_PINCFG_ODRAIN; - } - } - } -} -#endif diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/pinmux.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/pinmux.h deleted file mode 100644 index 7a441cc..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/pinmux.h +++ /dev/null @@ -1,678 +0,0 @@ -/** - * \file - * - * \brief SAM Pin Multiplexer Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef PINMUX_H_INCLUDED -#define PINMUX_H_INCLUDED - -/** - * \defgroup asfdoc_sam0_system_pinmux_group SAM System Pin Multiplexer (SYSTEM PINMUX) Driver - * - * This driver for Atmel® | SMART ARM®-based microcontrollers provides - * an interface for the configuration and management of the device's physical - * I/O Pins, to alter the direction and input/drive characteristics as well as - * to configure the pin peripheral multiplexer selection. - * - * The following peripheral is used by this module: - * - PORT (Port I/O Management) - * - * The following devices can use this module: - * - Atmel | SMART SAM D20/D21 - * - Atmel | SMART SAM R21 - * - Atmel | SMART SAM D09/D10/D11 - * - Atmel | SMART SAM L21/L22 - * - Atmel | SMART SAM DA1 - * - Atmel | SMART SAM C20/C21 - * - * Physically, the modules are interconnected within the device as shown in the - * following diagram: - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_system_pinmux_prerequisites - * - \ref asfdoc_sam0_system_pinmux_module_overview - * - \ref asfdoc_sam0_system_pinmux_special_considerations - * - \ref asfdoc_sam0_system_pinmux_extra_info - * - \ref asfdoc_sam0_system_pinmux_examples - * - \ref asfdoc_sam0_system_pinmux_api_overview - * - * - * \section asfdoc_sam0_system_pinmux_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * - * \section asfdoc_sam0_system_pinmux_module_overview Module Overview - * - * The SAM devices contain a number of General Purpose I/O pins, used to - * interface the user application logic and internal hardware peripherals to - * an external system. The Pin Multiplexer (PINMUX) driver provides a method - * of configuring the individual pin peripheral multiplexers to select - * alternate pin functions. - * - * \subsection asfdoc_sam0_system_pinmux_features Driver Feature Macro Definition - * - * - * - * - * - * - * - * - * - *
Driver Feature MacroSupported devices
FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTHSAM L21, SAM C20/C21
- * \note The specific features are only available in the driver when the - * selected device supports those features. - * - * \subsection asfdoc_sam0_system_pinmux_physical_logical_pins Physical and Logical GPIO Pins - * SAM devices use two naming conventions for the I/O pins in the device; one - * physical and one logical. Each physical pin on a device package is assigned - * both a physical port and pin identifier (e.g. "PORTA.0") as well as a - * monotonically incrementing logical GPIO number (e.g. "GPIO0"). While the - * former is used to map physical pins to their physical internal device module - * counterparts, for simplicity the design of this driver uses the logical GPIO - * numbers instead. - * - * \subsection asfdoc_sam0_system_pinmux_peripheral_muxing Peripheral Multiplexing - * SAM devices contain a peripheral MUX, which is individually controllable - * for each I/O pin of the device. The peripheral MUX allows you to select the - * function of a physical package pin - whether it will be controlled as a user - * controllable GPIO pin, or whether it will be connected internally to one of - * several peripheral modules (such as an I2C module). When a pin is - * configured in GPIO mode, other peripherals connected to the same pin will be - * disabled. - * - * \subsection asfdoc_sam0_system_pinmux_pad_characteristics Special Pad Characteristics - * There are several special modes that can be selected on one or more I/O pins - * of the device, which alter the input and output characteristics of the pad. - * - * \subsubsection asfdoc_sam0_system_pinmux_drive_strength Drive Strength - * The Drive Strength configures the strength of the output driver on the - * pad. Normally, there is a fixed current limit that each I/O pin can safely - * drive, however some I/O pads offer a higher drive mode which increases this - * limit for that I/O pin at the expense of an increased power consumption. - * - * \subsubsection asfdoc_sam0_system_pinmux_slew_rate Slew Rate - * The Slew Rate configures the slew rate of the output driver, limiting the - * rate at which the pad output voltage can change with time. - * - * \subsubsection asfdoc_sam0_system_pinmux_input_sample_mode Input Sample Mode - * The Input Sample Mode configures the input sampler buffer of the pad. By - * default, the input buffer is only sampled "on-demand", i.e. when the user - * application attempts to read from the input buffer. This mode is the most - * power efficient, but increases the latency of the input sample by two clock - * cycles of the port clock. To reduce latency, the input sampler can instead - * be configured to always sample the input buffer on each port clock cycle, at - * the expense of an increased power consumption. - * - * \subsection asfdoc_sam0_system_pinmux_module_overview_physical Physical Connection - * - * \ref asfdoc_sam0_system_pinmux_intconnections "The diagram below" shows - * how this module is interconnected within the device: - * - * \anchor asfdoc_sam0_system_pinmux_intconnections - * \dot - * digraph overview { - * node [label="Port Pad" shape=square] pad; - * - * subgraph driver { - * node [label="Peripheral MUX" shape=trapezium] pinmux; - * node [label="GPIO Module" shape=ellipse shape=ellipse style=filled fillcolor=lightgray] gpio; - * node [label="Other Peripheral Modules" shape=ellipse style=filled fillcolor=lightgray] peripherals; - * } - * - * pinmux -> gpio; - * pad -> pinmux; - * pinmux -> peripherals; - * } - * \enddot - * - * \section asfdoc_sam0_system_pinmux_special_considerations Special Considerations - * - * The SAM port pin input sampling mode is set in groups of four physical - * pins; setting the sampling mode of any pin in a sub-group of eight I/O pins - * will configure the sampling mode of the entire sub-group. - * - * High Drive Strength output driver mode is not available on all device pins - - * refer to your device specific datasheet. - * - * - * \section asfdoc_sam0_system_pinmux_extra_info Extra Information - * - * For extra information, see \ref asfdoc_sam0_system_pinmux_extra. This includes: - * - \ref asfdoc_sam0_system_pinmux_extra_acronyms - * - \ref asfdoc_sam0_system_pinmux_extra_dependencies - * - \ref asfdoc_sam0_system_pinmux_extra_errata - * - \ref asfdoc_sam0_system_pinmux_extra_history - * - * - * \section asfdoc_sam0_system_pinmux_examples Examples - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_system_pinmux_exqsg. - * - * - * \section asfdoc_sam0_system_pinmux_api_overview API Overview - * @{ - */ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/*@{*/ -#if (SAML21) || (SAMC20) || (SAMC21) || defined(__DOXYGEN__) -/** Output Driver Strength Selection feature support */ -# define FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTH -#endif -/*@}*/ - -/** Peripheral multiplexer index to select GPIO mode for a pin */ -#define SYSTEM_PINMUX_GPIO (1 << 7) - -/** - * \brief Port pin direction configuration enum. - * - * Enum for the possible pin direction settings of the port pin configuration - * structure, to indicate the direction the pin should use. - */ -enum system_pinmux_pin_dir { - /** The pin's input buffer should be enabled, so that the pin state can - * be read */ - SYSTEM_PINMUX_PIN_DIR_INPUT, - /** The pin's output buffer should be enabled, so that the pin state can - * be set (but not read back) */ - SYSTEM_PINMUX_PIN_DIR_OUTPUT, - /** The pin's output and input buffers should both be enabled, so that the - * pin state can be set and read back */ - SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK, -}; - -/** - * \brief Port pin input pull configuration enum. - * - * Enum for the possible pin pull settings of the port pin configuration - * structure, to indicate the type of logic level pull the pin should use. - */ -enum system_pinmux_pin_pull { - /** No logical pull should be applied to the pin */ - SYSTEM_PINMUX_PIN_PULL_NONE, - /** Pin should be pulled up when idle */ - SYSTEM_PINMUX_PIN_PULL_UP, - /** Pin should be pulled down when idle */ - SYSTEM_PINMUX_PIN_PULL_DOWN, -}; - -/** - * \brief Port pin digital input sampling mode enum. - * - * Enum for the possible input sampling modes for the port pin configuration - * structure, to indicate the type of sampling a port pin should use. - */ -enum system_pinmux_pin_sample { - /** Pin input buffer should continuously sample the pin state */ - SYSTEM_PINMUX_PIN_SAMPLE_CONTINUOUS, - /** Pin input buffer should be enabled when the IN register is read */ - SYSTEM_PINMUX_PIN_SAMPLE_ONDEMAND, -}; - -/** - * \brief Port pin configuration structure. - * - * Configuration structure for a port pin instance. This structure should - * be initialized by the \ref system_pinmux_get_config_defaults() function - * before being modified by the user application. - */ -struct system_pinmux_config { - /** MUX index of the peripheral that should control the pin, if peripheral - * control is desired. For GPIO use, this should be set to - * \ref SYSTEM_PINMUX_GPIO. */ - uint8_t mux_position; - - /** Port buffer input/output direction */ - enum system_pinmux_pin_dir direction; - - /** Logic level pull of the input buffer */ - enum system_pinmux_pin_pull input_pull; - - /** Enable lowest possible powerstate on the pin. - * - * \note All other configurations will be ignored, the pin will be disabled. - */ - bool powersave; -}; - -/** \name Configuration and Initialization - * @{ - */ - -/** - * \brief Initializes a Port pin configuration structure to defaults. - * - * Initializes a given Port pin configuration structure to a set of - * known default values. This function should be called on all new - * instances of these configuration structures before being modified by the - * user application. - * - * The default configuration is as follows: - * \li Non peripheral (i.e. GPIO) controlled - * \li Input mode with internal pull-up enabled - * - * \param[out] config Configuration structure to initialize to default values - */ -static inline void system_pinmux_get_config_defaults( - struct system_pinmux_config *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Default configuration values */ - config->mux_position = SYSTEM_PINMUX_GPIO; - config->direction = SYSTEM_PINMUX_PIN_DIR_INPUT; - config->input_pull = SYSTEM_PINMUX_PIN_PULL_UP; - config->powersave = false; -} - -void system_pinmux_pin_set_config( - const uint8_t gpio_pin, - const struct system_pinmux_config *const config); - -void system_pinmux_group_set_config( - PortGroup *const port, - const uint32_t mask, - const struct system_pinmux_config *const config); - -/** @} */ - -/** \name Special Mode Configuration (Physical Group Orientated) - * @{ - */ - -/** - * \brief Retrieves the PORT module group instance from a given GPIO pin number. - * - * Retrieves the PORT module group instance associated with a given logical - * GPIO pin number. - * - * \param[in] gpio_pin Index of the GPIO pin to convert - * - * \return Base address of the associated PORT module. - */ -static inline PortGroup* system_pinmux_get_group_from_gpio_pin( - const uint8_t gpio_pin) -{ - uint8_t port_index = (gpio_pin / 128); - uint8_t group_index = (gpio_pin / 32); - - /* Array of available ports */ - Port *const ports[PORT_INST_NUM] = PORT_INSTS; - - if (port_index < PORT_INST_NUM) { - return &(ports[port_index]->Group[group_index]); - } else { - Assert(false); - return NULL; - } -} - -void system_pinmux_group_set_input_sample_mode( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_sample mode); - -/** @} */ - -/** \name Special Mode Configuration (Logical Pin Orientated) - * @{ - */ - -/** - * \brief Retrieves the currently selected MUX position of a logical pin. - * - * Retrieves the selected MUX peripheral on a given logical GPIO pin. - * - * \param[in] gpio_pin Index of the GPIO pin to configure - * - * \return Currently selected peripheral index on the specified pin. - */ -static inline uint8_t system_pinmux_pin_get_mux_position( - const uint8_t gpio_pin) -{ - PortGroup *const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); - uint32_t pin_index = (gpio_pin % 32); - - if (!(port->PINCFG[pin_index].reg & PORT_PINCFG_PMUXEN)) { - return SYSTEM_PINMUX_GPIO; - } - - uint32_t pmux_reg = port->PMUX[pin_index / 2].reg; - - if (pin_index & 1) { - return (pmux_reg & PORT_PMUX_PMUXO_Msk) >> PORT_PMUX_PMUXO_Pos; - } - else { - return (pmux_reg & PORT_PMUX_PMUXE_Msk) >> PORT_PMUX_PMUXE_Pos; - } -} - -/** - * \brief Configures the input sampling mode for a GPIO pin. - * - * Configures the input sampling mode for a GPIO input, to - * control when the physical I/O pin value is sampled and - * stored inside the microcontroller. - * - * \param[in] gpio_pin Index of the GPIO pin to configure - * \param[in] mode New pin sampling mode to configure - */ -static inline void system_pinmux_pin_set_input_sample_mode( - const uint8_t gpio_pin, - const enum system_pinmux_pin_sample mode) -{ - PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); - uint32_t pin_index = (gpio_pin % 32); - - if (mode == SYSTEM_PINMUX_PIN_SAMPLE_ONDEMAND) { - port->CTRL.reg |= (1 << pin_index); - } else { - port->CTRL.reg &= ~(1 << pin_index); - } -} - -/** @} */ - -#ifdef FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTH -/** - * \brief Port pin drive output strength enum. - * - * Enum for the possible output drive strengths for the port pin - * configuration structure, to indicate the driver strength the pin should - * use. - */ -enum system_pinmux_pin_strength { - /** Normal output driver strength */ - SYSTEM_PINMUX_PIN_STRENGTH_NORMAL, - /** High current output driver strength */ - SYSTEM_PINMUX_PIN_STRENGTH_HIGH, -}; - -/** - * \brief Configures the output driver strength mode for a GPIO pin. - * - * Configures the output drive strength for a GPIO output, to - * control the amount of current the pad is able to sink/source. - * - * \param[in] gpio_pin Index of the GPIO pin to configure - * \param[in] mode New output driver strength mode to configure - */ -static inline void system_pinmux_pin_set_output_strength( - const uint8_t gpio_pin, - const enum system_pinmux_pin_strength mode) -{ - PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); - uint32_t pin_index = (gpio_pin % 32); - - if (mode == SYSTEM_PINMUX_PIN_STRENGTH_HIGH) { - port->PINCFG[pin_index].reg |= PORT_PINCFG_DRVSTR; - } - else { - port->PINCFG[pin_index].reg &= ~PORT_PINCFG_DRVSTR; - } -} - -void system_pinmux_group_set_output_strength( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_strength mode); -#endif - -#ifdef FEATURE_SYSTEM_PINMUX_SLEWRATE_LIMITER -/** - * \brief Port pin output slew rate enum. - * - * Enum for the possible output drive slew rates for the port pin - * configuration structure, to indicate the driver slew rate the pin should - * use. - */ -enum system_pinmux_pin_slew_rate { - /** Normal pin output slew rate */ - SYSTEM_PINMUX_PIN_SLEW_RATE_NORMAL, - /** Enable slew rate limiter on the pin */ - SYSTEM_PINMUX_PIN_SLEW_RATE_LIMITED, -}; - -/** - * \brief Configures the output slew rate mode for a GPIO pin. - * - * Configures the output slew rate mode for a GPIO output, to - * control the speed at which the physical output pin can react to - * logical changes of the I/O pin value. - * - * \param[in] gpio_pin Index of the GPIO pin to configure - * \param[in] mode New pin slew rate mode to configure - */ -static inline void system_pinmux_pin_set_output_slew_rate( - const uint8_t gpio_pin, - const enum system_pinmux_pin_slew_rate mode) -{ - PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); - uint32_t pin_index = (gpio_pin % 32); - - if (mode == SYSTEM_PINMUX_PIN_SLEW_RATE_LIMITED) { - port->PINCFG[pin_index].reg |= PORT_PINCFG_SLEWLIM; - } - else { - port->PINCFG[pin_index].reg &= ~PORT_PINCFG_SLEWLIM; - } -} - -void system_pinmux_group_set_output_slew_rate( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_slew_rate mode); -#endif - -#ifdef FEATURE_SYSTEM_PINMUX_OPEN_DRAIN -/** - * \brief Port pin output drive mode enum. - * - * Enum for the possible output drive modes for the port pin configuration - * structure, to indicate the output mode the pin should use. - */ -enum system_pinmux_pin_drive { - /** Use totem pole output drive mode */ - SYSTEM_PINMUX_PIN_DRIVE_TOTEM, - /** Use open drain output drive mode */ - SYSTEM_PINMUX_PIN_DRIVE_OPEN_DRAIN, -}; - -/** - * \brief Configures the output driver mode for a GPIO pin. - * - * Configures the output driver mode for a GPIO output, to - * control the pad behavior. - * - * \param[in] gpio_pin Index of the GPIO pin to configure - * \param[in] mode New pad output driver mode to configure - */ -static inline void system_pinmux_pin_set_output_drive( - const uint8_t gpio_pin, - const enum system_pinmux_pin_drive mode) -{ - PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); - uint32_t pin_index = (gpio_pin % 32); - - if (mode == SYSTEM_PINMUX_PIN_DRIVE_OPEN_DRAIN) { - port->PINCFG[pin_index].reg |= PORT_PINCFG_ODRAIN; - } - else { - port->PINCFG[pin_index].reg &= ~PORT_PINCFG_ODRAIN; - } -} - -void system_pinmux_group_set_output_drive( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_drive mode); -#endif - -#ifdef __cplusplus -} -#endif - -/** @} */ - -/** - * \page asfdoc_sam0_system_pinmux_extra Extra Information for SYSTEM PINMUX Driver - * - * \section asfdoc_sam0_system_pinmux_extra_acronyms Acronyms - * The table below presents the acronyms used in this module: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
AcronymDescription
GPIOGeneral Purpose Input/Output
MUXMultiplexer
- * - * - * \section asfdoc_sam0_system_pinmux_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - None - * - * - * \section asfdoc_sam0_system_pinmux_extra_errata Errata - * There are no errata related to this driver. - * - * - * \section asfdoc_sam0_system_pinmux_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Changelog
Removed code of open drain, slew limit and drive strength - * features
Fixed broken sampling mode function implementations, which wrote - * corrupt configuration values to the device registers
Added missing NULL pointer asserts to the PORT driver functions
Initial Release
- */ - -/** - * \page asfdoc_sam0_system_pinmux_exqsg Examples for SYSTEM PINMUX Driver - * - * This is a list of the available Quick Start guides (QSGs) and example - * applications for \ref asfdoc_sam0_system_pinmux_group. QSGs are simple - * examples with step-by-step instructions to configure and use this driver in a - * selection of use cases. Note that a QSG can be compiled as a standalone - * application or be added to the user application. - * - * - \subpage asfdoc_sam0_system_pinmux_basic_use_case - * - * \page asfdoc_sam0_system_pinmux_document_revision_history Document Revision History - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Doc. Rev. - * Date - * Comments - *
42121F08/2015Added support for SAM L21/L22, SAM DA1, and SAM C20/C21
42121E12/2014Added support for SAM R21 and SAM D10/D11
42121D01/2014Added support for SAM D21
42121C09/2013Fixed incorrect documentation for the device pin sampling mode
42121B06/2013Corrected documentation typos
42121A06/2013Initial release
- */ - -#endif diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/power.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/power.h deleted file mode 100644 index 5e90585..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/power.h +++ /dev/null @@ -1,224 +0,0 @@ -/** - * \file - * - * \brief SAM Power related functionality - * - * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef POWER_H_INCLUDED -#define POWER_H_INCLUDED - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \addtogroup asfdoc_sam0_system_group - * @{ - */ - -/** - * \brief Voltage references within the device. - * - * List of available voltage references (VREF) that may be used within the - * device. - */ -enum system_voltage_reference { - /** Temperature sensor voltage reference. */ - SYSTEM_VOLTAGE_REFERENCE_TEMPSENSE, - /** Bandgap voltage reference. */ - SYSTEM_VOLTAGE_REFERENCE_BANDGAP, -}; - -/** - * \brief Device sleep modes. - * - * List of available sleep modes in the device. A table of clocks available in - * different sleep modes can be found in \ref asfdoc_sam0_system_module_overview_sleep_mode. - */ -enum system_sleepmode { - /** IDLE 0 sleep mode. */ - SYSTEM_SLEEPMODE_IDLE_0, - /** IDLE 1 sleep mode. */ - SYSTEM_SLEEPMODE_IDLE_1, - /** IDLE 2 sleep mode. */ - SYSTEM_SLEEPMODE_IDLE_2, - /** Standby sleep mode. */ - SYSTEM_SLEEPMODE_STANDBY, -}; - - - -/** - * \name Voltage References - * @{ - */ - -/** - * \brief Enable the selected voltage reference - * - * Enables the selected voltage reference source, making the voltage reference - * available on a pin as well as an input source to the analog peripherals. - * - * \param[in] vref Voltage reference to enable - */ -static inline void system_voltage_reference_enable( - const enum system_voltage_reference vref) -{ - switch (vref) { - case SYSTEM_VOLTAGE_REFERENCE_TEMPSENSE: - SYSCTRL->VREF.reg |= SYSCTRL_VREF_TSEN; - break; - - case SYSTEM_VOLTAGE_REFERENCE_BANDGAP: - SYSCTRL->VREF.reg |= SYSCTRL_VREF_BGOUTEN; - break; - - default: - Assert(false); - return; - } -} - -/** - * \brief Disable the selected voltage reference - * - * Disables the selected voltage reference source. - * - * \param[in] vref Voltage reference to disable - */ -static inline void system_voltage_reference_disable( - const enum system_voltage_reference vref) -{ - switch (vref) { - case SYSTEM_VOLTAGE_REFERENCE_TEMPSENSE: - SYSCTRL->VREF.reg &= ~SYSCTRL_VREF_TSEN; - break; - - case SYSTEM_VOLTAGE_REFERENCE_BANDGAP: - SYSCTRL->VREF.reg &= ~SYSCTRL_VREF_BGOUTEN; - break; - - default: - Assert(false); - return; - } -} - -/** - * @} - */ - - -/** - * \name Device Sleep Control - * @{ - */ - -/** - * \brief Set the sleep mode of the device - * - * Sets the sleep mode of the device; the configured sleep mode will be entered - * upon the next call of the \ref system_sleep() function. - * - * For an overview of which systems are disabled in sleep for the different - * sleep modes, see \ref asfdoc_sam0_system_module_overview_sleep_mode. - * - * \param[in] sleep_mode Sleep mode to configure for the next sleep operation - * - * \retval STATUS_OK Operation completed successfully - * \retval STATUS_ERR_INVALID_ARG The requested sleep mode was invalid or not - * available - */ -static inline enum status_code system_set_sleepmode( - const enum system_sleepmode sleep_mode) -{ -#if (SAMD20 || SAMD21) - /* Errata: Make sure that the Flash does not power all the way down - * when in sleep mode. */ - NVMCTRL->CTRLB.bit.SLEEPPRM = NVMCTRL_CTRLB_SLEEPPRM_DISABLED_Val; -#endif - - switch (sleep_mode) { - case SYSTEM_SLEEPMODE_IDLE_0: - case SYSTEM_SLEEPMODE_IDLE_1: - case SYSTEM_SLEEPMODE_IDLE_2: - SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk; - PM->SLEEP.reg = sleep_mode; - break; - - case SYSTEM_SLEEPMODE_STANDBY: - SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; - break; - - default: - return STATUS_ERR_INVALID_ARG; - } - - return STATUS_OK; -} - -/** - * \brief Put the system to sleep waiting for interrupt - * - * Executes a device DSB (Data Synchronization Barrier) instruction to ensure - * all ongoing memory accesses have completed, then a WFI (Wait For Interrupt) - * instruction to place the device into the sleep mode specified by - * \ref system_set_sleepmode until woken by an interrupt. - */ -static inline void system_sleep(void) -{ - __DSB(); - __WFI(); -} - -/** - * @} - */ - -/** @} */ -#ifdef __cplusplus -} -#endif - -#endif /* POWER_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h deleted file mode 100644 index 4447927..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h +++ /dev/null @@ -1,581 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef _MRECURSION_H_ -#define _MRECURSION_H_ - -/** - * \defgroup group_sam0_utils_mrecursion Preprocessor - Macro Recursion - * - * \ingroup group_sam0_utils - * - * @{ - */ - -#include "preprocessor.h" - -#define DEC_256 255 -#define DEC_255 254 -#define DEC_254 253 -#define DEC_253 252 -#define DEC_252 251 -#define DEC_251 250 -#define DEC_250 249 -#define DEC_249 248 -#define DEC_248 247 -#define DEC_247 246 -#define DEC_246 245 -#define DEC_245 244 -#define DEC_244 243 -#define DEC_243 242 -#define DEC_242 241 -#define DEC_241 240 -#define DEC_240 239 -#define DEC_239 238 -#define DEC_238 237 -#define DEC_237 236 -#define DEC_236 235 -#define DEC_235 234 -#define DEC_234 233 -#define DEC_233 232 -#define DEC_232 231 -#define DEC_231 230 -#define DEC_230 229 -#define DEC_229 228 -#define DEC_228 227 -#define DEC_227 226 -#define DEC_226 225 -#define DEC_225 224 -#define DEC_224 223 -#define DEC_223 222 -#define DEC_222 221 -#define DEC_221 220 -#define DEC_220 219 -#define DEC_219 218 -#define DEC_218 217 -#define DEC_217 216 -#define DEC_216 215 -#define DEC_215 214 -#define DEC_214 213 -#define DEC_213 212 -#define DEC_212 211 -#define DEC_211 210 -#define DEC_210 209 -#define DEC_209 208 -#define DEC_208 207 -#define DEC_207 206 -#define DEC_206 205 -#define DEC_205 204 -#define DEC_204 203 -#define DEC_203 202 -#define DEC_202 201 -#define DEC_201 200 -#define DEC_200 199 -#define DEC_199 198 -#define DEC_198 197 -#define DEC_197 196 -#define DEC_196 195 -#define DEC_195 194 -#define DEC_194 193 -#define DEC_193 192 -#define DEC_192 191 -#define DEC_191 190 -#define DEC_190 189 -#define DEC_189 188 -#define DEC_188 187 -#define DEC_187 186 -#define DEC_186 185 -#define DEC_185 184 -#define DEC_184 183 -#define DEC_183 182 -#define DEC_182 181 -#define DEC_181 180 -#define DEC_180 179 -#define DEC_179 178 -#define DEC_178 177 -#define DEC_177 176 -#define DEC_176 175 -#define DEC_175 174 -#define DEC_174 173 -#define DEC_173 172 -#define DEC_172 171 -#define DEC_171 170 -#define DEC_170 169 -#define DEC_169 168 -#define DEC_168 167 -#define DEC_167 166 -#define DEC_166 165 -#define DEC_165 164 -#define DEC_164 163 -#define DEC_163 162 -#define DEC_162 161 -#define DEC_161 160 -#define DEC_160 159 -#define DEC_159 158 -#define DEC_158 157 -#define DEC_157 156 -#define DEC_156 155 -#define DEC_155 154 -#define DEC_154 153 -#define DEC_153 152 -#define DEC_152 151 -#define DEC_151 150 -#define DEC_150 149 -#define DEC_149 148 -#define DEC_148 147 -#define DEC_147 146 -#define DEC_146 145 -#define DEC_145 144 -#define DEC_144 143 -#define DEC_143 142 -#define DEC_142 141 -#define DEC_141 140 -#define DEC_140 139 -#define DEC_139 138 -#define DEC_138 137 -#define DEC_137 136 -#define DEC_136 135 -#define DEC_135 134 -#define DEC_134 133 -#define DEC_133 132 -#define DEC_132 131 -#define DEC_131 130 -#define DEC_130 129 -#define DEC_129 128 -#define DEC_128 127 -#define DEC_127 126 -#define DEC_126 125 -#define DEC_125 124 -#define DEC_124 123 -#define DEC_123 122 -#define DEC_122 121 -#define DEC_121 120 -#define DEC_120 119 -#define DEC_119 118 -#define DEC_118 117 -#define DEC_117 116 -#define DEC_116 115 -#define DEC_115 114 -#define DEC_114 113 -#define DEC_113 112 -#define DEC_112 111 -#define DEC_111 110 -#define DEC_110 109 -#define DEC_109 108 -#define DEC_108 107 -#define DEC_107 106 -#define DEC_106 105 -#define DEC_105 104 -#define DEC_104 103 -#define DEC_103 102 -#define DEC_102 101 -#define DEC_101 100 -#define DEC_100 99 -#define DEC_99 98 -#define DEC_98 97 -#define DEC_97 96 -#define DEC_96 95 -#define DEC_95 94 -#define DEC_94 93 -#define DEC_93 92 -#define DEC_92 91 -#define DEC_91 90 -#define DEC_90 89 -#define DEC_89 88 -#define DEC_88 87 -#define DEC_87 86 -#define DEC_86 85 -#define DEC_85 84 -#define DEC_84 83 -#define DEC_83 82 -#define DEC_82 81 -#define DEC_81 80 -#define DEC_80 79 -#define DEC_79 78 -#define DEC_78 77 -#define DEC_77 76 -#define DEC_76 75 -#define DEC_75 74 -#define DEC_74 73 -#define DEC_73 72 -#define DEC_72 71 -#define DEC_71 70 -#define DEC_70 69 -#define DEC_69 68 -#define DEC_68 67 -#define DEC_67 66 -#define DEC_66 65 -#define DEC_65 64 -#define DEC_64 63 -#define DEC_63 62 -#define DEC_62 61 -#define DEC_61 60 -#define DEC_60 59 -#define DEC_59 58 -#define DEC_58 57 -#define DEC_57 56 -#define DEC_56 55 -#define DEC_55 54 -#define DEC_54 53 -#define DEC_53 52 -#define DEC_52 51 -#define DEC_51 50 -#define DEC_50 49 -#define DEC_49 48 -#define DEC_48 47 -#define DEC_47 46 -#define DEC_46 45 -#define DEC_45 44 -#define DEC_44 43 -#define DEC_43 42 -#define DEC_42 41 -#define DEC_41 40 -#define DEC_40 39 -#define DEC_39 38 -#define DEC_38 37 -#define DEC_37 36 -#define DEC_36 35 -#define DEC_35 34 -#define DEC_34 33 -#define DEC_33 32 -#define DEC_32 31 -#define DEC_31 30 -#define DEC_30 29 -#define DEC_29 28 -#define DEC_28 27 -#define DEC_27 26 -#define DEC_26 25 -#define DEC_25 24 -#define DEC_24 23 -#define DEC_23 22 -#define DEC_22 21 -#define DEC_21 20 -#define DEC_20 19 -#define DEC_19 18 -#define DEC_18 17 -#define DEC_17 16 -#define DEC_16 15 -#define DEC_15 14 -#define DEC_14 13 -#define DEC_13 12 -#define DEC_12 11 -#define DEC_11 10 -#define DEC_10 9 -#define DEC_9 8 -#define DEC_8 7 -#define DEC_7 6 -#define DEC_6 5 -#define DEC_5 4 -#define DEC_4 3 -#define DEC_3 2 -#define DEC_2 1 -#define DEC_1 0 -#define DEC_(n) DEC_##n - - -/** Maximal number of repetitions supported by MRECURSION. */ -#define MRECURSION_LIMIT 256 - -/** \brief Macro recursion. - * - * This macro represents a horizontal repetition construct. - * - * \param[in] count The number of repetitious calls to macro. Valid values - * range from 0 to MRECURSION_LIMIT. - * \param[in] macro A binary operation of the form macro(data, n). This macro - * is expanded by MRECURSION with the current repetition number - * and the auxiliary data argument. - * \param[in] data A recursive threshold, building on this to decline by times - * defined with param count. - * - * \return macro(data-count+1,0) macro(data-count+2,1)...macro(data,count-1) - */ -#define MRECURSION(count, macro, data) TPASTE2(MRECURSION, count) (macro, data) - -#define MRECURSION0( macro, data) -#define MRECURSION1( macro, data) MRECURSION0( macro, DEC_(data)) macro(data, 0) -#define MRECURSION2( macro, data) MRECURSION1( macro, DEC_(data)) macro(data, 1) -#define MRECURSION3( macro, data) MRECURSION2( macro, DEC_(data)) macro(data, 2) -#define MRECURSION4( macro, data) MRECURSION3( macro, DEC_(data)) macro(data, 3) -#define MRECURSION5( macro, data) MRECURSION4( macro, DEC_(data)) macro(data, 4) -#define MRECURSION6( macro, data) MRECURSION5( macro, DEC_(data)) macro(data, 5) -#define MRECURSION7( macro, data) MRECURSION6( macro, DEC_(data)) macro(data, 6) -#define MRECURSION8( macro, data) MRECURSION7( macro, DEC_(data)) macro(data, 7) -#define MRECURSION9( macro, data) MRECURSION8( macro, DEC_(data)) macro(data, 8) -#define MRECURSION10( macro, data) MRECURSION9( macro, DEC_(data)) macro(data, 9) -#define MRECURSION11( macro, data) MRECURSION10( macro, DEC_(data)) macro(data, 10) -#define MRECURSION12( macro, data) MRECURSION11( macro, DEC_(data)) macro(data, 11) -#define MRECURSION13( macro, data) MRECURSION12( macro, DEC_(data)) macro(data, 12) -#define MRECURSION14( macro, data) MRECURSION13( macro, DEC_(data)) macro(data, 13) -#define MRECURSION15( macro, data) MRECURSION14( macro, DEC_(data)) macro(data, 14) -#define MRECURSION16( macro, data) MRECURSION15( macro, DEC_(data)) macro(data, 15) -#define MRECURSION17( macro, data) MRECURSION16( macro, DEC_(data)) macro(data, 16) -#define MRECURSION18( macro, data) MRECURSION17( macro, DEC_(data)) macro(data, 17) -#define MRECURSION19( macro, data) MRECURSION18( macro, DEC_(data)) macro(data, 18) -#define MRECURSION20( macro, data) MRECURSION19( macro, DEC_(data)) macro(data, 19) -#define MRECURSION21( macro, data) MRECURSION20( macro, DEC_(data)) macro(data, 20) -#define MRECURSION22( macro, data) MRECURSION21( macro, DEC_(data)) macro(data, 21) -#define MRECURSION23( macro, data) MRECURSION22( macro, DEC_(data)) macro(data, 22) -#define MRECURSION24( macro, data) MRECURSION23( macro, DEC_(data)) macro(data, 23) -#define MRECURSION25( macro, data) MRECURSION24( macro, DEC_(data)) macro(data, 24) -#define MRECURSION26( macro, data) MRECURSION25( macro, DEC_(data)) macro(data, 25) -#define MRECURSION27( macro, data) MRECURSION26( macro, DEC_(data)) macro(data, 26) -#define MRECURSION28( macro, data) MRECURSION27( macro, DEC_(data)) macro(data, 27) -#define MRECURSION29( macro, data) MRECURSION28( macro, DEC_(data)) macro(data, 28) -#define MRECURSION30( macro, data) MRECURSION29( macro, DEC_(data)) macro(data, 29) -#define MRECURSION31( macro, data) MRECURSION30( macro, DEC_(data)) macro(data, 30) -#define MRECURSION32( macro, data) MRECURSION31( macro, DEC_(data)) macro(data, 31) -#define MRECURSION33( macro, data) MRECURSION32( macro, DEC_(data)) macro(data, 32) -#define MRECURSION34( macro, data) MRECURSION33( macro, DEC_(data)) macro(data, 33) -#define MRECURSION35( macro, data) MRECURSION34( macro, DEC_(data)) macro(data, 34) -#define MRECURSION36( macro, data) MRECURSION35( macro, DEC_(data)) macro(data, 35) -#define MRECURSION37( macro, data) MRECURSION36( macro, DEC_(data)) macro(data, 36) -#define MRECURSION38( macro, data) MRECURSION37( macro, DEC_(data)) macro(data, 37) -#define MRECURSION39( macro, data) MRECURSION38( macro, DEC_(data)) macro(data, 38) -#define MRECURSION40( macro, data) MRECURSION39( macro, DEC_(data)) macro(data, 39) -#define MRECURSION41( macro, data) MRECURSION40( macro, DEC_(data)) macro(data, 40) -#define MRECURSION42( macro, data) MRECURSION41( macro, DEC_(data)) macro(data, 41) -#define MRECURSION43( macro, data) MRECURSION42( macro, DEC_(data)) macro(data, 42) -#define MRECURSION44( macro, data) MRECURSION43( macro, DEC_(data)) macro(data, 43) -#define MRECURSION45( macro, data) MRECURSION44( macro, DEC_(data)) macro(data, 44) -#define MRECURSION46( macro, data) MRECURSION45( macro, DEC_(data)) macro(data, 45) -#define MRECURSION47( macro, data) MRECURSION46( macro, DEC_(data)) macro(data, 46) -#define MRECURSION48( macro, data) MRECURSION47( macro, DEC_(data)) macro(data, 47) -#define MRECURSION49( macro, data) MRECURSION48( macro, DEC_(data)) macro(data, 48) -#define MRECURSION50( macro, data) MRECURSION49( macro, DEC_(data)) macro(data, 49) -#define MRECURSION51( macro, data) MRECURSION50( macro, DEC_(data)) macro(data, 50) -#define MRECURSION52( macro, data) MRECURSION51( macro, DEC_(data)) macro(data, 51) -#define MRECURSION53( macro, data) MRECURSION52( macro, DEC_(data)) macro(data, 52) -#define MRECURSION54( macro, data) MRECURSION53( macro, DEC_(data)) macro(data, 53) -#define MRECURSION55( macro, data) MRECURSION54( macro, DEC_(data)) macro(data, 54) -#define MRECURSION56( macro, data) MRECURSION55( macro, DEC_(data)) macro(data, 55) -#define MRECURSION57( macro, data) MRECURSION56( macro, DEC_(data)) macro(data, 56) -#define MRECURSION58( macro, data) MRECURSION57( macro, DEC_(data)) macro(data, 57) -#define MRECURSION59( macro, data) MRECURSION58( macro, DEC_(data)) macro(data, 58) -#define MRECURSION60( macro, data) MRECURSION59( macro, DEC_(data)) macro(data, 59) -#define MRECURSION61( macro, data) MRECURSION60( macro, DEC_(data)) macro(data, 60) -#define MRECURSION62( macro, data) MRECURSION61( macro, DEC_(data)) macro(data, 61) -#define MRECURSION63( macro, data) MRECURSION62( macro, DEC_(data)) macro(data, 62) -#define MRECURSION64( macro, data) MRECURSION63( macro, DEC_(data)) macro(data, 63) -#define MRECURSION65( macro, data) MRECURSION64( macro, DEC_(data)) macro(data, 64) -#define MRECURSION66( macro, data) MRECURSION65( macro, DEC_(data)) macro(data, 65) -#define MRECURSION67( macro, data) MRECURSION66( macro, DEC_(data)) macro(data, 66) -#define MRECURSION68( macro, data) MRECURSION67( macro, DEC_(data)) macro(data, 67) -#define MRECURSION69( macro, data) MRECURSION68( macro, DEC_(data)) macro(data, 68) -#define MRECURSION70( macro, data) MRECURSION69( macro, DEC_(data)) macro(data, 69) -#define MRECURSION71( macro, data) MRECURSION70( macro, DEC_(data)) macro(data, 70) -#define MRECURSION72( macro, data) MRECURSION71( macro, DEC_(data)) macro(data, 71) -#define MRECURSION73( macro, data) MRECURSION72( macro, DEC_(data)) macro(data, 72) -#define MRECURSION74( macro, data) MRECURSION73( macro, DEC_(data)) macro(data, 73) -#define MRECURSION75( macro, data) MRECURSION74( macro, DEC_(data)) macro(data, 74) -#define MRECURSION76( macro, data) MRECURSION75( macro, DEC_(data)) macro(data, 75) -#define MRECURSION77( macro, data) MRECURSION76( macro, DEC_(data)) macro(data, 76) -#define MRECURSION78( macro, data) MRECURSION77( macro, DEC_(data)) macro(data, 77) -#define MRECURSION79( macro, data) MRECURSION78( macro, DEC_(data)) macro(data, 78) -#define MRECURSION80( macro, data) MRECURSION79( macro, DEC_(data)) macro(data, 79) -#define MRECURSION81( macro, data) MRECURSION80( macro, DEC_(data)) macro(data, 80) -#define MRECURSION82( macro, data) MRECURSION81( macro, DEC_(data)) macro(data, 81) -#define MRECURSION83( macro, data) MRECURSION82( macro, DEC_(data)) macro(data, 82) -#define MRECURSION84( macro, data) MRECURSION83( macro, DEC_(data)) macro(data, 83) -#define MRECURSION85( macro, data) MRECURSION84( macro, DEC_(data)) macro(data, 84) -#define MRECURSION86( macro, data) MRECURSION85( macro, DEC_(data)) macro(data, 85) -#define MRECURSION87( macro, data) MRECURSION86( macro, DEC_(data)) macro(data, 86) -#define MRECURSION88( macro, data) MRECURSION87( macro, DEC_(data)) macro(data, 87) -#define MRECURSION89( macro, data) MRECURSION88( macro, DEC_(data)) macro(data, 88) -#define MRECURSION90( macro, data) MRECURSION89( macro, DEC_(data)) macro(data, 89) -#define MRECURSION91( macro, data) MRECURSION90( macro, DEC_(data)) macro(data, 90) -#define MRECURSION92( macro, data) MRECURSION91( macro, DEC_(data)) macro(data, 91) -#define MRECURSION93( macro, data) MRECURSION92( macro, DEC_(data)) macro(data, 92) -#define MRECURSION94( macro, data) MRECURSION93( macro, DEC_(data)) macro(data, 93) -#define MRECURSION95( macro, data) MRECURSION94( macro, DEC_(data)) macro(data, 94) -#define MRECURSION96( macro, data) MRECURSION95( macro, DEC_(data)) macro(data, 95) -#define MRECURSION97( macro, data) MRECURSION96( macro, DEC_(data)) macro(data, 96) -#define MRECURSION98( macro, data) MRECURSION97( macro, DEC_(data)) macro(data, 97) -#define MRECURSION99( macro, data) MRECURSION98( macro, DEC_(data)) macro(data, 98) -#define MRECURSION100(macro, data) MRECURSION99( macro, DEC_(data)) macro(data, 99) -#define MRECURSION101(macro, data) MRECURSION100( macro, DEC_(data)) macro(data, 100) -#define MRECURSION102(macro, data) MRECURSION101( macro, DEC_(data)) macro(data, 101) -#define MRECURSION103(macro, data) MRECURSION102( macro, DEC_(data)) macro(data, 102) -#define MRECURSION104(macro, data) MRECURSION103( macro, DEC_(data)) macro(data, 103) -#define MRECURSION105(macro, data) MRECURSION104( macro, DEC_(data)) macro(data, 104) -#define MRECURSION106(macro, data) MRECURSION105( macro, DEC_(data)) macro(data, 105) -#define MRECURSION107(macro, data) MRECURSION106( macro, DEC_(data)) macro(data, 106) -#define MRECURSION108(macro, data) MRECURSION107( macro, DEC_(data)) macro(data, 107) -#define MRECURSION109(macro, data) MRECURSION108( macro, DEC_(data)) macro(data, 108) -#define MRECURSION110(macro, data) MRECURSION109( macro, DEC_(data)) macro(data, 109) -#define MRECURSION111(macro, data) MRECURSION110( macro, DEC_(data)) macro(data, 110) -#define MRECURSION112(macro, data) MRECURSION111( macro, DEC_(data)) macro(data, 111) -#define MRECURSION113(macro, data) MRECURSION112( macro, DEC_(data)) macro(data, 112) -#define MRECURSION114(macro, data) MRECURSION113( macro, DEC_(data)) macro(data, 113) -#define MRECURSION115(macro, data) MRECURSION114( macro, DEC_(data)) macro(data, 114) -#define MRECURSION116(macro, data) MRECURSION115( macro, DEC_(data)) macro(data, 115) -#define MRECURSION117(macro, data) MRECURSION116( macro, DEC_(data)) macro(data, 116) -#define MRECURSION118(macro, data) MRECURSION117( macro, DEC_(data)) macro(data, 117) -#define MRECURSION119(macro, data) MRECURSION118( macro, DEC_(data)) macro(data, 118) -#define MRECURSION120(macro, data) MRECURSION119( macro, DEC_(data)) macro(data, 119) -#define MRECURSION121(macro, data) MRECURSION120( macro, DEC_(data)) macro(data, 120) -#define MRECURSION122(macro, data) MRECURSION121( macro, DEC_(data)) macro(data, 121) -#define MRECURSION123(macro, data) MRECURSION122( macro, DEC_(data)) macro(data, 122) -#define MRECURSION124(macro, data) MRECURSION123( macro, DEC_(data)) macro(data, 123) -#define MRECURSION125(macro, data) MRECURSION124( macro, DEC_(data)) macro(data, 124) -#define MRECURSION126(macro, data) MRECURSION125( macro, DEC_(data)) macro(data, 125) -#define MRECURSION127(macro, data) MRECURSION126( macro, DEC_(data)) macro(data, 126) -#define MRECURSION128(macro, data) MRECURSION127( macro, DEC_(data)) macro(data, 127) -#define MRECURSION129(macro, data) MRECURSION128( macro, DEC_(data)) macro(data, 128) -#define MRECURSION130(macro, data) MRECURSION129( macro, DEC_(data)) macro(data, 129) -#define MRECURSION131(macro, data) MRECURSION130( macro, DEC_(data)) macro(data, 130) -#define MRECURSION132(macro, data) MRECURSION131( macro, DEC_(data)) macro(data, 131) -#define MRECURSION133(macro, data) MRECURSION132( macro, DEC_(data)) macro(data, 132) -#define MRECURSION134(macro, data) MRECURSION133( macro, DEC_(data)) macro(data, 133) -#define MRECURSION135(macro, data) MRECURSION134( macro, DEC_(data)) macro(data, 134) -#define MRECURSION136(macro, data) MRECURSION135( macro, DEC_(data)) macro(data, 135) -#define MRECURSION137(macro, data) MRECURSION136( macro, DEC_(data)) macro(data, 136) -#define MRECURSION138(macro, data) MRECURSION137( macro, DEC_(data)) macro(data, 137) -#define MRECURSION139(macro, data) MRECURSION138( macro, DEC_(data)) macro(data, 138) -#define MRECURSION140(macro, data) MRECURSION139( macro, DEC_(data)) macro(data, 139) -#define MRECURSION141(macro, data) MRECURSION140( macro, DEC_(data)) macro(data, 140) -#define MRECURSION142(macro, data) MRECURSION141( macro, DEC_(data)) macro(data, 141) -#define MRECURSION143(macro, data) MRECURSION142( macro, DEC_(data)) macro(data, 142) -#define MRECURSION144(macro, data) MRECURSION143( macro, DEC_(data)) macro(data, 143) -#define MRECURSION145(macro, data) MRECURSION144( macro, DEC_(data)) macro(data, 144) -#define MRECURSION146(macro, data) MRECURSION145( macro, DEC_(data)) macro(data, 145) -#define MRECURSION147(macro, data) MRECURSION146( macro, DEC_(data)) macro(data, 146) -#define MRECURSION148(macro, data) MRECURSION147( macro, DEC_(data)) macro(data, 147) -#define MRECURSION149(macro, data) MRECURSION148( macro, DEC_(data)) macro(data, 148) -#define MRECURSION150(macro, data) MRECURSION149( macro, DEC_(data)) macro(data, 149) -#define MRECURSION151(macro, data) MRECURSION150( macro, DEC_(data)) macro(data, 150) -#define MRECURSION152(macro, data) MRECURSION151( macro, DEC_(data)) macro(data, 151) -#define MRECURSION153(macro, data) MRECURSION152( macro, DEC_(data)) macro(data, 152) -#define MRECURSION154(macro, data) MRECURSION153( macro, DEC_(data)) macro(data, 153) -#define MRECURSION155(macro, data) MRECURSION154( macro, DEC_(data)) macro(data, 154) -#define MRECURSION156(macro, data) MRECURSION155( macro, DEC_(data)) macro(data, 155) -#define MRECURSION157(macro, data) MRECURSION156( macro, DEC_(data)) macro(data, 156) -#define MRECURSION158(macro, data) MRECURSION157( macro, DEC_(data)) macro(data, 157) -#define MRECURSION159(macro, data) MRECURSION158( macro, DEC_(data)) macro(data, 158) -#define MRECURSION160(macro, data) MRECURSION159( macro, DEC_(data)) macro(data, 159) -#define MRECURSION161(macro, data) MRECURSION160( macro, DEC_(data)) macro(data, 160) -#define MRECURSION162(macro, data) MRECURSION161( macro, DEC_(data)) macro(data, 161) -#define MRECURSION163(macro, data) MRECURSION162( macro, DEC_(data)) macro(data, 162) -#define MRECURSION164(macro, data) MRECURSION163( macro, DEC_(data)) macro(data, 163) -#define MRECURSION165(macro, data) MRECURSION164( macro, DEC_(data)) macro(data, 164) -#define MRECURSION166(macro, data) MRECURSION165( macro, DEC_(data)) macro(data, 165) -#define MRECURSION167(macro, data) MRECURSION166( macro, DEC_(data)) macro(data, 166) -#define MRECURSION168(macro, data) MRECURSION167( macro, DEC_(data)) macro(data, 167) -#define MRECURSION169(macro, data) MRECURSION168( macro, DEC_(data)) macro(data, 168) -#define MRECURSION170(macro, data) MRECURSION169( macro, DEC_(data)) macro(data, 169) -#define MRECURSION171(macro, data) MRECURSION170( macro, DEC_(data)) macro(data, 170) -#define MRECURSION172(macro, data) MRECURSION171( macro, DEC_(data)) macro(data, 171) -#define MRECURSION173(macro, data) MRECURSION172( macro, DEC_(data)) macro(data, 172) -#define MRECURSION174(macro, data) MRECURSION173( macro, DEC_(data)) macro(data, 173) -#define MRECURSION175(macro, data) MRECURSION174( macro, DEC_(data)) macro(data, 174) -#define MRECURSION176(macro, data) MRECURSION175( macro, DEC_(data)) macro(data, 175) -#define MRECURSION177(macro, data) MRECURSION176( macro, DEC_(data)) macro(data, 176) -#define MRECURSION178(macro, data) MRECURSION177( macro, DEC_(data)) macro(data, 177) -#define MRECURSION179(macro, data) MRECURSION178( macro, DEC_(data)) macro(data, 178) -#define MRECURSION180(macro, data) MRECURSION179( macro, DEC_(data)) macro(data, 179) -#define MRECURSION181(macro, data) MRECURSION180( macro, DEC_(data)) macro(data, 180) -#define MRECURSION182(macro, data) MRECURSION181( macro, DEC_(data)) macro(data, 181) -#define MRECURSION183(macro, data) MRECURSION182( macro, DEC_(data)) macro(data, 182) -#define MRECURSION184(macro, data) MRECURSION183( macro, DEC_(data)) macro(data, 183) -#define MRECURSION185(macro, data) MRECURSION184( macro, DEC_(data)) macro(data, 184) -#define MRECURSION186(macro, data) MRECURSION185( macro, DEC_(data)) macro(data, 185) -#define MRECURSION187(macro, data) MRECURSION186( macro, DEC_(data)) macro(data, 186) -#define MRECURSION188(macro, data) MRECURSION187( macro, DEC_(data)) macro(data, 187) -#define MRECURSION189(macro, data) MRECURSION188( macro, DEC_(data)) macro(data, 188) -#define MRECURSION190(macro, data) MRECURSION189( macro, DEC_(data)) macro(data, 189) -#define MRECURSION191(macro, data) MRECURSION190( macro, DEC_(data)) macro(data, 190) -#define MRECURSION192(macro, data) MRECURSION191( macro, DEC_(data)) macro(data, 191) -#define MRECURSION193(macro, data) MRECURSION192( macro, DEC_(data)) macro(data, 192) -#define MRECURSION194(macro, data) MRECURSION193( macro, DEC_(data)) macro(data, 193) -#define MRECURSION195(macro, data) MRECURSION194( macro, DEC_(data)) macro(data, 194) -#define MRECURSION196(macro, data) MRECURSION195( macro, DEC_(data)) macro(data, 195) -#define MRECURSION197(macro, data) MRECURSION196( macro, DEC_(data)) macro(data, 196) -#define MRECURSION198(macro, data) MRECURSION197( macro, DEC_(data)) macro(data, 197) -#define MRECURSION199(macro, data) MRECURSION198( macro, DEC_(data)) macro(data, 198) -#define MRECURSION200(macro, data) MRECURSION199( macro, DEC_(data)) macro(data, 199) -#define MRECURSION201(macro, data) MRECURSION200( macro, DEC_(data)) macro(data, 200) -#define MRECURSION202(macro, data) MRECURSION201( macro, DEC_(data)) macro(data, 201) -#define MRECURSION203(macro, data) MRECURSION202( macro, DEC_(data)) macro(data, 202) -#define MRECURSION204(macro, data) MRECURSION203( macro, DEC_(data)) macro(data, 203) -#define MRECURSION205(macro, data) MRECURSION204( macro, DEC_(data)) macro(data, 204) -#define MRECURSION206(macro, data) MRECURSION205( macro, DEC_(data)) macro(data, 205) -#define MRECURSION207(macro, data) MRECURSION206( macro, DEC_(data)) macro(data, 206) -#define MRECURSION208(macro, data) MRECURSION207( macro, DEC_(data)) macro(data, 207) -#define MRECURSION209(macro, data) MRECURSION208( macro, DEC_(data)) macro(data, 208) -#define MRECURSION210(macro, data) MRECURSION209( macro, DEC_(data)) macro(data, 209) -#define MRECURSION211(macro, data) MRECURSION210( macro, DEC_(data)) macro(data, 210) -#define MRECURSION212(macro, data) MRECURSION211( macro, DEC_(data)) macro(data, 211) -#define MRECURSION213(macro, data) MRECURSION212( macro, DEC_(data)) macro(data, 212) -#define MRECURSION214(macro, data) MRECURSION213( macro, DEC_(data)) macro(data, 213) -#define MRECURSION215(macro, data) MRECURSION214( macro, DEC_(data)) macro(data, 214) -#define MRECURSION216(macro, data) MRECURSION215( macro, DEC_(data)) macro(data, 215) -#define MRECURSION217(macro, data) MRECURSION216( macro, DEC_(data)) macro(data, 216) -#define MRECURSION218(macro, data) MRECURSION217( macro, DEC_(data)) macro(data, 217) -#define MRECURSION219(macro, data) MRECURSION218( macro, DEC_(data)) macro(data, 218) -#define MRECURSION220(macro, data) MRECURSION219( macro, DEC_(data)) macro(data, 219) -#define MRECURSION221(macro, data) MRECURSION220( macro, DEC_(data)) macro(data, 220) -#define MRECURSION222(macro, data) MRECURSION221( macro, DEC_(data)) macro(data, 221) -#define MRECURSION223(macro, data) MRECURSION222( macro, DEC_(data)) macro(data, 222) -#define MRECURSION224(macro, data) MRECURSION223( macro, DEC_(data)) macro(data, 223) -#define MRECURSION225(macro, data) MRECURSION224( macro, DEC_(data)) macro(data, 224) -#define MRECURSION226(macro, data) MRECURSION225( macro, DEC_(data)) macro(data, 225) -#define MRECURSION227(macro, data) MRECURSION226( macro, DEC_(data)) macro(data, 226) -#define MRECURSION228(macro, data) MRECURSION227( macro, DEC_(data)) macro(data, 227) -#define MRECURSION229(macro, data) MRECURSION228( macro, DEC_(data)) macro(data, 228) -#define MRECURSION230(macro, data) MRECURSION229( macro, DEC_(data)) macro(data, 229) -#define MRECURSION231(macro, data) MRECURSION230( macro, DEC_(data)) macro(data, 230) -#define MRECURSION232(macro, data) MRECURSION231( macro, DEC_(data)) macro(data, 231) -#define MRECURSION233(macro, data) MRECURSION232( macro, DEC_(data)) macro(data, 232) -#define MRECURSION234(macro, data) MRECURSION233( macro, DEC_(data)) macro(data, 233) -#define MRECURSION235(macro, data) MRECURSION234( macro, DEC_(data)) macro(data, 234) -#define MRECURSION236(macro, data) MRECURSION235( macro, DEC_(data)) macro(data, 235) -#define MRECURSION237(macro, data) MRECURSION236( macro, DEC_(data)) macro(data, 236) -#define MRECURSION238(macro, data) MRECURSION237( macro, DEC_(data)) macro(data, 237) -#define MRECURSION239(macro, data) MRECURSION238( macro, DEC_(data)) macro(data, 238) -#define MRECURSION240(macro, data) MRECURSION239( macro, DEC_(data)) macro(data, 239) -#define MRECURSION241(macro, data) MRECURSION240( macro, DEC_(data)) macro(data, 240) -#define MRECURSION242(macro, data) MRECURSION241( macro, DEC_(data)) macro(data, 241) -#define MRECURSION243(macro, data) MRECURSION242( macro, DEC_(data)) macro(data, 242) -#define MRECURSION244(macro, data) MRECURSION243( macro, DEC_(data)) macro(data, 243) -#define MRECURSION245(macro, data) MRECURSION244( macro, DEC_(data)) macro(data, 244) -#define MRECURSION246(macro, data) MRECURSION245( macro, DEC_(data)) macro(data, 245) -#define MRECURSION247(macro, data) MRECURSION246( macro, DEC_(data)) macro(data, 246) -#define MRECURSION248(macro, data) MRECURSION247( macro, DEC_(data)) macro(data, 247) -#define MRECURSION249(macro, data) MRECURSION248( macro, DEC_(data)) macro(data, 248) -#define MRECURSION250(macro, data) MRECURSION249( macro, DEC_(data)) macro(data, 249) -#define MRECURSION251(macro, data) MRECURSION250( macro, DEC_(data)) macro(data, 250) -#define MRECURSION252(macro, data) MRECURSION251( macro, DEC_(data)) macro(data, 251) -#define MRECURSION253(macro, data) MRECURSION252( macro, DEC_(data)) macro(data, 252) -#define MRECURSION254(macro, data) MRECURSION253( macro, DEC_(data)) macro(data, 253) -#define MRECURSION255(macro, data) MRECURSION254( macro, DEC_(data)) macro(data, 254) -#define MRECURSION256(macro, data) MRECURSION255( macro, DEC_(data)) macro(data, 255) - -/** @} */ - -#endif /* _MRECURSION_H_ */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h deleted file mode 100644 index fb820d5..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h +++ /dev/null @@ -1,321 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef _MREPEAT_H_ -#define _MREPEAT_H_ - -/** - * \defgroup group_sam0_utils_mrepeat Preprocessor - Macro Repeat - * - * \ingroup group_sam0_utils - * - * @{ - */ - -#include "preprocessor.h" - -/** Maximal number of repetitions supported by MREPEAT. */ -#define MREPEAT_LIMIT 256 - -/** \brief Macro repeat. - * - * This macro represents a horizontal repetition construct. - * - * \param[in] count The number of repetitious calls to macro. Valid values - * range from 0 to MREPEAT_LIMIT. - * \param[in] macro A binary operation of the form macro(n, data). This macro - * is expanded by MREPEAT with the current repetition number - * and the auxiliary data argument. - * \param[in] data Auxiliary data passed to macro. - * - * \return macro(0, data) macro(1, data) ... macro(count - 1, data) - */ -#define MREPEAT(count, macro, data) TPASTE2(MREPEAT, count) (macro, data) - -#define MREPEAT0( macro, data) -#define MREPEAT1( macro, data) MREPEAT0( macro, data) macro( 0, data) -#define MREPEAT2( macro, data) MREPEAT1( macro, data) macro( 1, data) -#define MREPEAT3( macro, data) MREPEAT2( macro, data) macro( 2, data) -#define MREPEAT4( macro, data) MREPEAT3( macro, data) macro( 3, data) -#define MREPEAT5( macro, data) MREPEAT4( macro, data) macro( 4, data) -#define MREPEAT6( macro, data) MREPEAT5( macro, data) macro( 5, data) -#define MREPEAT7( macro, data) MREPEAT6( macro, data) macro( 6, data) -#define MREPEAT8( macro, data) MREPEAT7( macro, data) macro( 7, data) -#define MREPEAT9( macro, data) MREPEAT8( macro, data) macro( 8, data) -#define MREPEAT10( macro, data) MREPEAT9( macro, data) macro( 9, data) -#define MREPEAT11( macro, data) MREPEAT10( macro, data) macro( 10, data) -#define MREPEAT12( macro, data) MREPEAT11( macro, data) macro( 11, data) -#define MREPEAT13( macro, data) MREPEAT12( macro, data) macro( 12, data) -#define MREPEAT14( macro, data) MREPEAT13( macro, data) macro( 13, data) -#define MREPEAT15( macro, data) MREPEAT14( macro, data) macro( 14, data) -#define MREPEAT16( macro, data) MREPEAT15( macro, data) macro( 15, data) -#define MREPEAT17( macro, data) MREPEAT16( macro, data) macro( 16, data) -#define MREPEAT18( macro, data) MREPEAT17( macro, data) macro( 17, data) -#define MREPEAT19( macro, data) MREPEAT18( macro, data) macro( 18, data) -#define MREPEAT20( macro, data) MREPEAT19( macro, data) macro( 19, data) -#define MREPEAT21( macro, data) MREPEAT20( macro, data) macro( 20, data) -#define MREPEAT22( macro, data) MREPEAT21( macro, data) macro( 21, data) -#define MREPEAT23( macro, data) MREPEAT22( macro, data) macro( 22, data) -#define MREPEAT24( macro, data) MREPEAT23( macro, data) macro( 23, data) -#define MREPEAT25( macro, data) MREPEAT24( macro, data) macro( 24, data) -#define MREPEAT26( macro, data) MREPEAT25( macro, data) macro( 25, data) -#define MREPEAT27( macro, data) MREPEAT26( macro, data) macro( 26, data) -#define MREPEAT28( macro, data) MREPEAT27( macro, data) macro( 27, data) -#define MREPEAT29( macro, data) MREPEAT28( macro, data) macro( 28, data) -#define MREPEAT30( macro, data) MREPEAT29( macro, data) macro( 29, data) -#define MREPEAT31( macro, data) MREPEAT30( macro, data) macro( 30, data) -#define MREPEAT32( macro, data) MREPEAT31( macro, data) macro( 31, data) -#define MREPEAT33( macro, data) MREPEAT32( macro, data) macro( 32, data) -#define MREPEAT34( macro, data) MREPEAT33( macro, data) macro( 33, data) -#define MREPEAT35( macro, data) MREPEAT34( macro, data) macro( 34, data) -#define MREPEAT36( macro, data) MREPEAT35( macro, data) macro( 35, data) -#define MREPEAT37( macro, data) MREPEAT36( macro, data) macro( 36, data) -#define MREPEAT38( macro, data) MREPEAT37( macro, data) macro( 37, data) -#define MREPEAT39( macro, data) MREPEAT38( macro, data) macro( 38, data) -#define MREPEAT40( macro, data) MREPEAT39( macro, data) macro( 39, data) -#define MREPEAT41( macro, data) MREPEAT40( macro, data) macro( 40, data) -#define MREPEAT42( macro, data) MREPEAT41( macro, data) macro( 41, data) -#define MREPEAT43( macro, data) MREPEAT42( macro, data) macro( 42, data) -#define MREPEAT44( macro, data) MREPEAT43( macro, data) macro( 43, data) -#define MREPEAT45( macro, data) MREPEAT44( macro, data) macro( 44, data) -#define MREPEAT46( macro, data) MREPEAT45( macro, data) macro( 45, data) -#define MREPEAT47( macro, data) MREPEAT46( macro, data) macro( 46, data) -#define MREPEAT48( macro, data) MREPEAT47( macro, data) macro( 47, data) -#define MREPEAT49( macro, data) MREPEAT48( macro, data) macro( 48, data) -#define MREPEAT50( macro, data) MREPEAT49( macro, data) macro( 49, data) -#define MREPEAT51( macro, data) MREPEAT50( macro, data) macro( 50, data) -#define MREPEAT52( macro, data) MREPEAT51( macro, data) macro( 51, data) -#define MREPEAT53( macro, data) MREPEAT52( macro, data) macro( 52, data) -#define MREPEAT54( macro, data) MREPEAT53( macro, data) macro( 53, data) -#define MREPEAT55( macro, data) MREPEAT54( macro, data) macro( 54, data) -#define MREPEAT56( macro, data) MREPEAT55( macro, data) macro( 55, data) -#define MREPEAT57( macro, data) MREPEAT56( macro, data) macro( 56, data) -#define MREPEAT58( macro, data) MREPEAT57( macro, data) macro( 57, data) -#define MREPEAT59( macro, data) MREPEAT58( macro, data) macro( 58, data) -#define MREPEAT60( macro, data) MREPEAT59( macro, data) macro( 59, data) -#define MREPEAT61( macro, data) MREPEAT60( macro, data) macro( 60, data) -#define MREPEAT62( macro, data) MREPEAT61( macro, data) macro( 61, data) -#define MREPEAT63( macro, data) MREPEAT62( macro, data) macro( 62, data) -#define MREPEAT64( macro, data) MREPEAT63( macro, data) macro( 63, data) -#define MREPEAT65( macro, data) MREPEAT64( macro, data) macro( 64, data) -#define MREPEAT66( macro, data) MREPEAT65( macro, data) macro( 65, data) -#define MREPEAT67( macro, data) MREPEAT66( macro, data) macro( 66, data) -#define MREPEAT68( macro, data) MREPEAT67( macro, data) macro( 67, data) -#define MREPEAT69( macro, data) MREPEAT68( macro, data) macro( 68, data) -#define MREPEAT70( macro, data) MREPEAT69( macro, data) macro( 69, data) -#define MREPEAT71( macro, data) MREPEAT70( macro, data) macro( 70, data) -#define MREPEAT72( macro, data) MREPEAT71( macro, data) macro( 71, data) -#define MREPEAT73( macro, data) MREPEAT72( macro, data) macro( 72, data) -#define MREPEAT74( macro, data) MREPEAT73( macro, data) macro( 73, data) -#define MREPEAT75( macro, data) MREPEAT74( macro, data) macro( 74, data) -#define MREPEAT76( macro, data) MREPEAT75( macro, data) macro( 75, data) -#define MREPEAT77( macro, data) MREPEAT76( macro, data) macro( 76, data) -#define MREPEAT78( macro, data) MREPEAT77( macro, data) macro( 77, data) -#define MREPEAT79( macro, data) MREPEAT78( macro, data) macro( 78, data) -#define MREPEAT80( macro, data) MREPEAT79( macro, data) macro( 79, data) -#define MREPEAT81( macro, data) MREPEAT80( macro, data) macro( 80, data) -#define MREPEAT82( macro, data) MREPEAT81( macro, data) macro( 81, data) -#define MREPEAT83( macro, data) MREPEAT82( macro, data) macro( 82, data) -#define MREPEAT84( macro, data) MREPEAT83( macro, data) macro( 83, data) -#define MREPEAT85( macro, data) MREPEAT84( macro, data) macro( 84, data) -#define MREPEAT86( macro, data) MREPEAT85( macro, data) macro( 85, data) -#define MREPEAT87( macro, data) MREPEAT86( macro, data) macro( 86, data) -#define MREPEAT88( macro, data) MREPEAT87( macro, data) macro( 87, data) -#define MREPEAT89( macro, data) MREPEAT88( macro, data) macro( 88, data) -#define MREPEAT90( macro, data) MREPEAT89( macro, data) macro( 89, data) -#define MREPEAT91( macro, data) MREPEAT90( macro, data) macro( 90, data) -#define MREPEAT92( macro, data) MREPEAT91( macro, data) macro( 91, data) -#define MREPEAT93( macro, data) MREPEAT92( macro, data) macro( 92, data) -#define MREPEAT94( macro, data) MREPEAT93( macro, data) macro( 93, data) -#define MREPEAT95( macro, data) MREPEAT94( macro, data) macro( 94, data) -#define MREPEAT96( macro, data) MREPEAT95( macro, data) macro( 95, data) -#define MREPEAT97( macro, data) MREPEAT96( macro, data) macro( 96, data) -#define MREPEAT98( macro, data) MREPEAT97( macro, data) macro( 97, data) -#define MREPEAT99( macro, data) MREPEAT98( macro, data) macro( 98, data) -#define MREPEAT100(macro, data) MREPEAT99( macro, data) macro( 99, data) -#define MREPEAT101(macro, data) MREPEAT100(macro, data) macro(100, data) -#define MREPEAT102(macro, data) MREPEAT101(macro, data) macro(101, data) -#define MREPEAT103(macro, data) MREPEAT102(macro, data) macro(102, data) -#define MREPEAT104(macro, data) MREPEAT103(macro, data) macro(103, data) -#define MREPEAT105(macro, data) MREPEAT104(macro, data) macro(104, data) -#define MREPEAT106(macro, data) MREPEAT105(macro, data) macro(105, data) -#define MREPEAT107(macro, data) MREPEAT106(macro, data) macro(106, data) -#define MREPEAT108(macro, data) MREPEAT107(macro, data) macro(107, data) -#define MREPEAT109(macro, data) MREPEAT108(macro, data) macro(108, data) -#define MREPEAT110(macro, data) MREPEAT109(macro, data) macro(109, data) -#define MREPEAT111(macro, data) MREPEAT110(macro, data) macro(110, data) -#define MREPEAT112(macro, data) MREPEAT111(macro, data) macro(111, data) -#define MREPEAT113(macro, data) MREPEAT112(macro, data) macro(112, data) -#define MREPEAT114(macro, data) MREPEAT113(macro, data) macro(113, data) -#define MREPEAT115(macro, data) MREPEAT114(macro, data) macro(114, data) -#define MREPEAT116(macro, data) MREPEAT115(macro, data) macro(115, data) -#define MREPEAT117(macro, data) MREPEAT116(macro, data) macro(116, data) -#define MREPEAT118(macro, data) MREPEAT117(macro, data) macro(117, data) -#define MREPEAT119(macro, data) MREPEAT118(macro, data) macro(118, data) -#define MREPEAT120(macro, data) MREPEAT119(macro, data) macro(119, data) -#define MREPEAT121(macro, data) MREPEAT120(macro, data) macro(120, data) -#define MREPEAT122(macro, data) MREPEAT121(macro, data) macro(121, data) -#define MREPEAT123(macro, data) MREPEAT122(macro, data) macro(122, data) -#define MREPEAT124(macro, data) MREPEAT123(macro, data) macro(123, data) -#define MREPEAT125(macro, data) MREPEAT124(macro, data) macro(124, data) -#define MREPEAT126(macro, data) MREPEAT125(macro, data) macro(125, data) -#define MREPEAT127(macro, data) MREPEAT126(macro, data) macro(126, data) -#define MREPEAT128(macro, data) MREPEAT127(macro, data) macro(127, data) -#define MREPEAT129(macro, data) MREPEAT128(macro, data) macro(128, data) -#define MREPEAT130(macro, data) MREPEAT129(macro, data) macro(129, data) -#define MREPEAT131(macro, data) MREPEAT130(macro, data) macro(130, data) -#define MREPEAT132(macro, data) MREPEAT131(macro, data) macro(131, data) -#define MREPEAT133(macro, data) MREPEAT132(macro, data) macro(132, data) -#define MREPEAT134(macro, data) MREPEAT133(macro, data) macro(133, data) -#define MREPEAT135(macro, data) MREPEAT134(macro, data) macro(134, data) -#define MREPEAT136(macro, data) MREPEAT135(macro, data) macro(135, data) -#define MREPEAT137(macro, data) MREPEAT136(macro, data) macro(136, data) -#define MREPEAT138(macro, data) MREPEAT137(macro, data) macro(137, data) -#define MREPEAT139(macro, data) MREPEAT138(macro, data) macro(138, data) -#define MREPEAT140(macro, data) MREPEAT139(macro, data) macro(139, data) -#define MREPEAT141(macro, data) MREPEAT140(macro, data) macro(140, data) -#define MREPEAT142(macro, data) MREPEAT141(macro, data) macro(141, data) -#define MREPEAT143(macro, data) MREPEAT142(macro, data) macro(142, data) -#define MREPEAT144(macro, data) MREPEAT143(macro, data) macro(143, data) -#define MREPEAT145(macro, data) MREPEAT144(macro, data) macro(144, data) -#define MREPEAT146(macro, data) MREPEAT145(macro, data) macro(145, data) -#define MREPEAT147(macro, data) MREPEAT146(macro, data) macro(146, data) -#define MREPEAT148(macro, data) MREPEAT147(macro, data) macro(147, data) -#define MREPEAT149(macro, data) MREPEAT148(macro, data) macro(148, data) -#define MREPEAT150(macro, data) MREPEAT149(macro, data) macro(149, data) -#define MREPEAT151(macro, data) MREPEAT150(macro, data) macro(150, data) -#define MREPEAT152(macro, data) MREPEAT151(macro, data) macro(151, data) -#define MREPEAT153(macro, data) MREPEAT152(macro, data) macro(152, data) -#define MREPEAT154(macro, data) MREPEAT153(macro, data) macro(153, data) -#define MREPEAT155(macro, data) MREPEAT154(macro, data) macro(154, data) -#define MREPEAT156(macro, data) MREPEAT155(macro, data) macro(155, data) -#define MREPEAT157(macro, data) MREPEAT156(macro, data) macro(156, data) -#define MREPEAT158(macro, data) MREPEAT157(macro, data) macro(157, data) -#define MREPEAT159(macro, data) MREPEAT158(macro, data) macro(158, data) -#define MREPEAT160(macro, data) MREPEAT159(macro, data) macro(159, data) -#define MREPEAT161(macro, data) MREPEAT160(macro, data) macro(160, data) -#define MREPEAT162(macro, data) MREPEAT161(macro, data) macro(161, data) -#define MREPEAT163(macro, data) MREPEAT162(macro, data) macro(162, data) -#define MREPEAT164(macro, data) MREPEAT163(macro, data) macro(163, data) -#define MREPEAT165(macro, data) MREPEAT164(macro, data) macro(164, data) -#define MREPEAT166(macro, data) MREPEAT165(macro, data) macro(165, data) -#define MREPEAT167(macro, data) MREPEAT166(macro, data) macro(166, data) -#define MREPEAT168(macro, data) MREPEAT167(macro, data) macro(167, data) -#define MREPEAT169(macro, data) MREPEAT168(macro, data) macro(168, data) -#define MREPEAT170(macro, data) MREPEAT169(macro, data) macro(169, data) -#define MREPEAT171(macro, data) MREPEAT170(macro, data) macro(170, data) -#define MREPEAT172(macro, data) MREPEAT171(macro, data) macro(171, data) -#define MREPEAT173(macro, data) MREPEAT172(macro, data) macro(172, data) -#define MREPEAT174(macro, data) MREPEAT173(macro, data) macro(173, data) -#define MREPEAT175(macro, data) MREPEAT174(macro, data) macro(174, data) -#define MREPEAT176(macro, data) MREPEAT175(macro, data) macro(175, data) -#define MREPEAT177(macro, data) MREPEAT176(macro, data) macro(176, data) -#define MREPEAT178(macro, data) MREPEAT177(macro, data) macro(177, data) -#define MREPEAT179(macro, data) MREPEAT178(macro, data) macro(178, data) -#define MREPEAT180(macro, data) MREPEAT179(macro, data) macro(179, data) -#define MREPEAT181(macro, data) MREPEAT180(macro, data) macro(180, data) -#define MREPEAT182(macro, data) MREPEAT181(macro, data) macro(181, data) -#define MREPEAT183(macro, data) MREPEAT182(macro, data) macro(182, data) -#define MREPEAT184(macro, data) MREPEAT183(macro, data) macro(183, data) -#define MREPEAT185(macro, data) MREPEAT184(macro, data) macro(184, data) -#define MREPEAT186(macro, data) MREPEAT185(macro, data) macro(185, data) -#define MREPEAT187(macro, data) MREPEAT186(macro, data) macro(186, data) -#define MREPEAT188(macro, data) MREPEAT187(macro, data) macro(187, data) -#define MREPEAT189(macro, data) MREPEAT188(macro, data) macro(188, data) -#define MREPEAT190(macro, data) MREPEAT189(macro, data) macro(189, data) -#define MREPEAT191(macro, data) MREPEAT190(macro, data) macro(190, data) -#define MREPEAT192(macro, data) MREPEAT191(macro, data) macro(191, data) -#define MREPEAT193(macro, data) MREPEAT192(macro, data) macro(192, data) -#define MREPEAT194(macro, data) MREPEAT193(macro, data) macro(193, data) -#define MREPEAT195(macro, data) MREPEAT194(macro, data) macro(194, data) -#define MREPEAT196(macro, data) MREPEAT195(macro, data) macro(195, data) -#define MREPEAT197(macro, data) MREPEAT196(macro, data) macro(196, data) -#define MREPEAT198(macro, data) MREPEAT197(macro, data) macro(197, data) -#define MREPEAT199(macro, data) MREPEAT198(macro, data) macro(198, data) -#define MREPEAT200(macro, data) MREPEAT199(macro, data) macro(199, data) -#define MREPEAT201(macro, data) MREPEAT200(macro, data) macro(200, data) -#define MREPEAT202(macro, data) MREPEAT201(macro, data) macro(201, data) -#define MREPEAT203(macro, data) MREPEAT202(macro, data) macro(202, data) -#define MREPEAT204(macro, data) MREPEAT203(macro, data) macro(203, data) -#define MREPEAT205(macro, data) MREPEAT204(macro, data) macro(204, data) -#define MREPEAT206(macro, data) MREPEAT205(macro, data) macro(205, data) -#define MREPEAT207(macro, data) MREPEAT206(macro, data) macro(206, data) -#define MREPEAT208(macro, data) MREPEAT207(macro, data) macro(207, data) -#define MREPEAT209(macro, data) MREPEAT208(macro, data) macro(208, data) -#define MREPEAT210(macro, data) MREPEAT209(macro, data) macro(209, data) -#define MREPEAT211(macro, data) MREPEAT210(macro, data) macro(210, data) -#define MREPEAT212(macro, data) MREPEAT211(macro, data) macro(211, data) -#define MREPEAT213(macro, data) MREPEAT212(macro, data) macro(212, data) -#define MREPEAT214(macro, data) MREPEAT213(macro, data) macro(213, data) -#define MREPEAT215(macro, data) MREPEAT214(macro, data) macro(214, data) -#define MREPEAT216(macro, data) MREPEAT215(macro, data) macro(215, data) -#define MREPEAT217(macro, data) MREPEAT216(macro, data) macro(216, data) -#define MREPEAT218(macro, data) MREPEAT217(macro, data) macro(217, data) -#define MREPEAT219(macro, data) MREPEAT218(macro, data) macro(218, data) -#define MREPEAT220(macro, data) MREPEAT219(macro, data) macro(219, data) -#define MREPEAT221(macro, data) MREPEAT220(macro, data) macro(220, data) -#define MREPEAT222(macro, data) MREPEAT221(macro, data) macro(221, data) -#define MREPEAT223(macro, data) MREPEAT222(macro, data) macro(222, data) -#define MREPEAT224(macro, data) MREPEAT223(macro, data) macro(223, data) -#define MREPEAT225(macro, data) MREPEAT224(macro, data) macro(224, data) -#define MREPEAT226(macro, data) MREPEAT225(macro, data) macro(225, data) -#define MREPEAT227(macro, data) MREPEAT226(macro, data) macro(226, data) -#define MREPEAT228(macro, data) MREPEAT227(macro, data) macro(227, data) -#define MREPEAT229(macro, data) MREPEAT228(macro, data) macro(228, data) -#define MREPEAT230(macro, data) MREPEAT229(macro, data) macro(229, data) -#define MREPEAT231(macro, data) MREPEAT230(macro, data) macro(230, data) -#define MREPEAT232(macro, data) MREPEAT231(macro, data) macro(231, data) -#define MREPEAT233(macro, data) MREPEAT232(macro, data) macro(232, data) -#define MREPEAT234(macro, data) MREPEAT233(macro, data) macro(233, data) -#define MREPEAT235(macro, data) MREPEAT234(macro, data) macro(234, data) -#define MREPEAT236(macro, data) MREPEAT235(macro, data) macro(235, data) -#define MREPEAT237(macro, data) MREPEAT236(macro, data) macro(236, data) -#define MREPEAT238(macro, data) MREPEAT237(macro, data) macro(237, data) -#define MREPEAT239(macro, data) MREPEAT238(macro, data) macro(238, data) -#define MREPEAT240(macro, data) MREPEAT239(macro, data) macro(239, data) -#define MREPEAT241(macro, data) MREPEAT240(macro, data) macro(240, data) -#define MREPEAT242(macro, data) MREPEAT241(macro, data) macro(241, data) -#define MREPEAT243(macro, data) MREPEAT242(macro, data) macro(242, data) -#define MREPEAT244(macro, data) MREPEAT243(macro, data) macro(243, data) -#define MREPEAT245(macro, data) MREPEAT244(macro, data) macro(244, data) -#define MREPEAT246(macro, data) MREPEAT245(macro, data) macro(245, data) -#define MREPEAT247(macro, data) MREPEAT246(macro, data) macro(246, data) -#define MREPEAT248(macro, data) MREPEAT247(macro, data) macro(247, data) -#define MREPEAT249(macro, data) MREPEAT248(macro, data) macro(248, data) -#define MREPEAT250(macro, data) MREPEAT249(macro, data) macro(249, data) -#define MREPEAT251(macro, data) MREPEAT250(macro, data) macro(250, data) -#define MREPEAT252(macro, data) MREPEAT251(macro, data) macro(251, data) -#define MREPEAT253(macro, data) MREPEAT252(macro, data) macro(252, data) -#define MREPEAT254(macro, data) MREPEAT253(macro, data) macro(253, data) -#define MREPEAT255(macro, data) MREPEAT254(macro, data) macro(254, data) -#define MREPEAT256(macro, data) MREPEAT255(macro, data) macro(255, data) - -/** @} */ - -#endif /* _MREPEAT_H_ */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h deleted file mode 100644 index 7f67d8a..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h +++ /dev/null @@ -1,38 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef _PREPROCESSOR_H_ -#define _PREPROCESSOR_H_ - -#include "tpaste.h" -#include "stringz.h" -#include "mrepeat.h" -#include "mrecursion.h" - -#endif // _PREPROCESSOR_H_ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/stringz.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/stringz.h deleted file mode 100644 index 70937c4..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/stringz.h +++ /dev/null @@ -1,67 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef _STRINGZ_H_ -#define _STRINGZ_H_ - -/** - * \defgroup group_sam0_utils_stringz Preprocessor - Stringize - * - * \ingroup group_sam0_utils - * - * @{ - */ - -/** \brief Stringize. - * - * Stringize a preprocessing token, this token being allowed to be \#defined. - * - * May be used only within macros with the token passed as an argument if the - * token is \#defined. - * - * For example, writing STRINGZ(PIN) within a macro \#defined by PIN_NAME(PIN) - * and invoked as PIN_NAME(PIN0) with PIN0 \#defined as A0 is equivalent to - * writing "A0". - */ -#define STRINGZ(x) #x - -/** \brief Absolute stringize. - * - * Stringize a preprocessing token, this token being allowed to be \#defined. - * - * No restriction of use if the token is \#defined. - * - * For example, writing ASTRINGZ(PIN0) anywhere with PIN0 \#defined as A0 is - * equivalent to writing "A0". - */ -#define ASTRINGZ(x) STRINGZ(x) - -/** @} */ - -#endif // _STRINGZ_H_ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/tpaste.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/tpaste.h deleted file mode 100644 index 9108183..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/preprocessor/tpaste.h +++ /dev/null @@ -1,85 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ -#ifndef _TPASTE_H_ -#define _TPASTE_H_ - -/** - * \defgroup group_sam0_utils_tpaste Preprocessor - Token Paste - * - * \ingroup group_sam0_utils - * - * @{ - */ - -/** \name Token Paste - * - * Paste N preprocessing tokens together, these tokens being allowed to be \#defined. - * - * May be used only within macros with the tokens passed as arguments if the tokens are \#defined. - * - * For example, writing TPASTE2(U, WIDTH) within a macro \#defined by - * UTYPE(WIDTH) and invoked as UTYPE(UL_WIDTH) with UL_WIDTH \#defined as 32 is - * equivalent to writing U32. - * - * @{ */ -#define TPASTE2( a, b) a##b -#define TPASTE3( a, b, c) a##b##c -#define TPASTE4( a, b, c, d) a##b##c##d -#define TPASTE5( a, b, c, d, e) a##b##c##d##e -#define TPASTE6( a, b, c, d, e, f) a##b##c##d##e##f -#define TPASTE7( a, b, c, d, e, f, g) a##b##c##d##e##f##g -#define TPASTE8( a, b, c, d, e, f, g, h) a##b##c##d##e##f##g##h -#define TPASTE9( a, b, c, d, e, f, g, h, i) a##b##c##d##e##f##g##h##i -#define TPASTE10(a, b, c, d, e, f, g, h, i, j) a##b##c##d##e##f##g##h##i##j -/** @} */ - -/** \name Absolute Token Paste - * - * Paste N preprocessing tokens together, these tokens being allowed to be \#defined. - * - * No restriction of use if the tokens are \#defined. - * - * For example, writing ATPASTE2(U, UL_WIDTH) anywhere with UL_WIDTH \#defined - * as 32 is equivalent to writing U32. - * - * @{ */ -#define ATPASTE2( a, b) TPASTE2( a, b) -#define ATPASTE3( a, b, c) TPASTE3( a, b, c) -#define ATPASTE4( a, b, c, d) TPASTE4( a, b, c, d) -#define ATPASTE5( a, b, c, d, e) TPASTE5( a, b, c, d, e) -#define ATPASTE6( a, b, c, d, e, f) TPASTE6( a, b, c, d, e, f) -#define ATPASTE7( a, b, c, d, e, f, g) TPASTE7( a, b, c, d, e, f, g) -#define ATPASTE8( a, b, c, d, e, f, g, h) TPASTE8( a, b, c, d, e, f, g, h) -#define ATPASTE9( a, b, c, d, e, f, g, h, i) TPASTE9( a, b, c, d, e, f, g, h, i) -#define ATPASTE10(a, b, c, d, e, f, g, h, i, j) TPASTE10(a, b, c, d, e, f, g, h, i, j) -/** @} */ - -/** @} */ - -#endif // _TPASTE_H_ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/reset.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/reset.h deleted file mode 100644 index ae1eb5a..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/reset.h +++ /dev/null @@ -1,119 +0,0 @@ -/** - * \file - * - * \brief SAM Reset related functionality - * - * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef RESET_H_INCLUDED -#define RESET_H_INCLUDED - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \addtogroup asfdoc_sam0_system_group - * @{ - */ - -/** - * \brief Reset causes of the system. - * - * List of possible reset causes of the system. - */ -enum system_reset_cause { - /** The system was last reset by a software reset. */ - SYSTEM_RESET_CAUSE_SOFTWARE = PM_RCAUSE_SYST, - /** The system was last reset by the watchdog timer. */ - SYSTEM_RESET_CAUSE_WDT = PM_RCAUSE_WDT, - /** The system was last reset because the external reset line was pulled low. */ - SYSTEM_RESET_CAUSE_EXTERNAL_RESET = PM_RCAUSE_EXT, - /** The system was last reset by the BOD33. */ - SYSTEM_RESET_CAUSE_BOD33 = PM_RCAUSE_BOD33, - /** The system was last reset by the BOD12. */ - SYSTEM_RESET_CAUSE_BOD12 = PM_RCAUSE_BOD12, - /** The system was last reset by the POR (Power on reset). */ - SYSTEM_RESET_CAUSE_POR = PM_RCAUSE_POR, -}; - - -/** - * \name Reset Control - * @{ - */ - -/** - * \brief Reset the MCU. - * - * Resets the MCU and all associated peripherals and registers, except RTC, all 32KHz sources, - * WDT (if ALWAYSON is set) and GCLK (if WRTLOCK is set). - * - */ -static inline void system_reset(void) -{ - NVIC_SystemReset(); -} - -/** - * \brief Return the reset cause. - * - * Retrieves the cause of the last system reset. - * - * \return An enum value indicating the cause of the last system reset. - */ -static inline enum system_reset_cause system_get_reset_cause(void) -{ - return (enum system_reset_cause)PM->RCAUSE.reg; -} - -/** - * @} - */ - -/** @} */ -#ifdef __cplusplus -} -#endif - -#endif /* RESET_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/status_codes.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/status_codes.h deleted file mode 100644 index 29bbf41..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/status_codes.h +++ /dev/null @@ -1,138 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef STATUS_CODES_H_INCLUDED -#define STATUS_CODES_H_INCLUDED - -#include - -/** - * \defgroup group_sam0_utils_status_codes Status Codes - * - * \ingroup group_sam0_utils - * - * @{ - */ - -/** Mask to retrieve the error category of a status code. */ -#define STATUS_CATEGORY_MASK 0xF0 - -/** Mask to retrieve the error code within the category of a status code. */ -#define STATUS_ERROR_MASK 0x0F - -/** Status code error categories. */ -enum status_categories { - STATUS_CATEGORY_OK = 0x00, - STATUS_CATEGORY_COMMON = 0x10, - STATUS_CATEGORY_ANALOG = 0x30, - STATUS_CATEGORY_COM = 0x40, - STATUS_CATEGORY_IO = 0x50, -}; - -/** - * Status code that may be returned by shell commands and protocol - * implementations. - * - * \note Any change to these status codes and the corresponding - * message strings is strictly forbidden. New codes can be added, - * however, but make sure that any message string tables are updated - * at the same time. - */ -enum status_code { - STATUS_OK = STATUS_CATEGORY_OK | 0x00, - STATUS_VALID_DATA = STATUS_CATEGORY_OK | 0x01, - STATUS_NO_CHANGE = STATUS_CATEGORY_OK | 0x02, - STATUS_ABORTED = STATUS_CATEGORY_OK | 0x04, - STATUS_BUSY = STATUS_CATEGORY_OK | 0x05, - STATUS_SUSPEND = STATUS_CATEGORY_OK | 0x06, - - STATUS_ERR_IO = STATUS_CATEGORY_COMMON | 0x00, - STATUS_ERR_REQ_FLUSHED = STATUS_CATEGORY_COMMON | 0x01, - STATUS_ERR_TIMEOUT = STATUS_CATEGORY_COMMON | 0x02, - STATUS_ERR_BAD_DATA = STATUS_CATEGORY_COMMON | 0x03, - STATUS_ERR_NOT_FOUND = STATUS_CATEGORY_COMMON | 0x04, - STATUS_ERR_UNSUPPORTED_DEV = STATUS_CATEGORY_COMMON | 0x05, - STATUS_ERR_NO_MEMORY = STATUS_CATEGORY_COMMON | 0x06, - STATUS_ERR_INVALID_ARG = STATUS_CATEGORY_COMMON | 0x07, - STATUS_ERR_BAD_ADDRESS = STATUS_CATEGORY_COMMON | 0x08, - STATUS_ERR_BAD_FORMAT = STATUS_CATEGORY_COMMON | 0x0A, - STATUS_ERR_BAD_FRQ = STATUS_CATEGORY_COMMON | 0x0B, - STATUS_ERR_DENIED = STATUS_CATEGORY_COMMON | 0x0c, - STATUS_ERR_ALREADY_INITIALIZED = STATUS_CATEGORY_COMMON | 0x0d, - STATUS_ERR_OVERFLOW = STATUS_CATEGORY_COMMON | 0x0e, - STATUS_ERR_NOT_INITIALIZED = STATUS_CATEGORY_COMMON | 0x0f, - - STATUS_ERR_SAMPLERATE_UNAVAILABLE = STATUS_CATEGORY_ANALOG | 0x00, - STATUS_ERR_RESOLUTION_UNAVAILABLE = STATUS_CATEGORY_ANALOG | 0x01, - - STATUS_ERR_BAUDRATE_UNAVAILABLE = STATUS_CATEGORY_COM | 0x00, - STATUS_ERR_PACKET_COLLISION = STATUS_CATEGORY_COM | 0x01, - STATUS_ERR_PROTOCOL = STATUS_CATEGORY_COM | 0x02, - - STATUS_ERR_PIN_MUX_INVALID = STATUS_CATEGORY_IO | 0x00, -}; -typedef enum status_code status_code_genare_t; - -/** - Status codes used by MAC stack. - */ -enum status_code_wireless { - //STATUS_OK = 0, //!< Success - ERR_IO_ERROR = -1, //!< I/O error - ERR_FLUSHED = -2, //!< Request flushed from queue - ERR_TIMEOUT = -3, //!< Operation timed out - ERR_BAD_DATA = -4, //!< Data integrity check failed - ERR_PROTOCOL = -5, //!< Protocol error - ERR_UNSUPPORTED_DEV = -6, //!< Unsupported device - ERR_NO_MEMORY = -7, //!< Insufficient memory - ERR_INVALID_ARG = -8, //!< Invalid argument - ERR_BAD_ADDRESS = -9, //!< Bad address - ERR_BUSY = -10, //!< Resource is busy - ERR_BAD_FORMAT = -11, //!< Data format not recognized - ERR_NO_TIMER = -12, //!< No timer available - ERR_TIMER_ALREADY_RUNNING = -13, //!< Timer already running - ERR_TIMER_NOT_RUNNING = -14, //!< Timer not running - - /** - * \brief Operation in progress - * - * This status code is for driver-internal use when an operation - * is currently being performed. - * - * \note Drivers should never return this status code to any - * callers. It is strictly for internal use. - */ - OPERATION_IN_PROGRESS = -128, -}; - -typedef enum status_code_wireless status_code_t; - -/** @} */ - -#endif /* STATUS_CODES_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/system.c b/feather_sensor_lte/libraries/Adafruit_ASFcore/system.c deleted file mode 100644 index 0121588..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/system.c +++ /dev/null @@ -1,111 +0,0 @@ -/** - * \file - * - * \brief SAM System related functionality - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#include - -/** - * \internal - * Dummy initialization function, used as a weak alias target for the various - * init functions called by \ref system_init(). - */ -void _system_dummy_init(void); -void _system_dummy_init(void) -{ - return; -} - -#if !defined(__DOXYGEN__) -# if defined(__GNUC__) -void system_clock_init(void) WEAK __attribute__((alias("_system_dummy_init"))); -void system_board_init(void) WEAK __attribute__((alias("_system_dummy_init"))); -void _system_events_init(void) WEAK __attribute__((alias("_system_dummy_init"))); -void _system_extint_init(void) WEAK __attribute__((alias("_system_dummy_init"))); -void _system_divas_init(void) WEAK __attribute__((alias("_system_dummy_init"))); -# elif defined(__ICCARM__) -void system_clock_init(void); -void system_board_init(void); -void _system_events_init(void); -void _system_extint_init(void); -void _system_divas_init(void); -# pragma weak system_clock_init=_system_dummy_init -# pragma weak system_board_init=_system_dummy_init -# pragma weak _system_events_init=_system_dummy_init -# pragma weak _system_extint_init=_system_dummy_init -# pragma weak _system_divas_init=_system_dummy_init -# endif -#endif - -/** - * \brief Initialize system - * - * This function will call the various initialization functions within the - * system namespace. If a given optional system module is not available, the - * associated call will effectively be a NOP (No Operation). - * - * Currently the following initialization functions are supported: - * - System clock initialization (via the SYSTEM CLOCK sub-module) - * - Board hardware initialization (via the Board module) - * - Event system driver initialization (via the EVSYS module) - * - External Interrupt driver initialization (via the EXTINT module) - */ -void system_init(void) -{ - /* Configure GCLK and clock sources according to conf_clocks.h */ - system_clock_init(); - - /* Initialize board hardware */ - system_board_init(); - - /* Initialize EVSYS hardware */ - _system_events_init(); - - /* Initialize External hardware */ - _system_extint_init(); - - /* Initialize DIVAS hardware */ - _system_divas_init(); -} - diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/system.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/system.h deleted file mode 100644 index 7b7bc00..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/system.h +++ /dev/null @@ -1,726 +0,0 @@ -/** - * \file - * - * \brief SAM System related functionality - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef SYSTEM_H_INCLUDED -#define SYSTEM_H_INCLUDED - -#include -#include -#include -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \defgroup asfdoc_sam0_system_group SAM System (SYSTEM) Driver - * - * This driver for Atmel® | SMART ARM®-based microcontrollers provides an interface for the configuration - * and management of the device's system relation functionality, necessary for - * the basic device operation. This is not limited to a single peripheral, but - * extends across multiple hardware peripherals. - * - * The following peripherals are used by this module: - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - PM (Power Manager) - * - RSTC(Reset Controller) - * - SUPC(Supply Controller) - * \endif - * \if DEVICE_SAMC21_SYSTEM_SUPPORT - * - PM (Power Manager) - * - RSTC(Reset Controller) - * - SUPC(Supply Controller) - * \endif - * \if DEVICE_SAMD21_SYSTEM_SUPPORT - * - SYSCTRL (System Control) - * - PM (Power Manager) - * \endif - * - * The following devices can use this module: - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - Atmel | SMART SAM L21 - * \endif - * \if DEVICE_SAMC21_SYSTEM_SUPPORT - * - Atmel | SMART SAM C20/C21 - * \endif - * \if DEVICE_SAMD21_SYSTEM_SUPPORT - * - Atmel | SMART SAM D20/D21 - * - Atmel | SMART SAM R21 - * - Atmel | SMART SAM D09/D10/D11 - * - Atmel | SMART SAM DAx - * \endif - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_system_prerequisites - * - \ref asfdoc_sam0_system_module_overview - * - \ref asfdoc_sam0_system_special_considerations - * - \ref asfdoc_sam0_system_extra_info - * - \ref asfdoc_sam0_system_examples - * - \ref asfdoc_sam0_system_api_overview - * - * - * \section asfdoc_sam0_system_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * - * \section asfdoc_sam0_system_module_overview Module Overview - * - * The System driver provides a collection of interfaces between the user - * application logic, and the core device functionality (such as clocks, reset - * cause determination, etc.) that is required for all applications. It contains - * a number of sub-modules that control one specific aspect of the device: - * - * - System Core (this module) - * - \ref asfdoc_sam0_system_clock_group "System Clock Control" (sub-module) - * - \ref asfdoc_sam0_system_interrupt_group "System Interrupt Control" (sub-module) - * - \ref asfdoc_sam0_system_pinmux_group "System Pin Multiplexer Control" (sub-module) - * - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * \subsection asfdoc_sam0_system_module_overview_vreg_l21 Voltage Regulator - * The SAM device controls the voltage regulators for the core (VDDCORE) and - * backup (VDDBU) domains. It sets the voltage regulators according to the sleep - * modes, the performance level, or the user configuration. - * - * In active mode, the voltage regulator can be chosen on the fly between a LDO - * or a Buck converter. In standby mode, the low power voltage regulator is used - * to supply VDDCORE. - * - * \subsection asfdoc_sam0_system_module_overview_bbps Battery Backup Power Switch - * The SAM device supports connection of a battery backup to the VBAT power pin. - * It includes functionality that enables automatic power switching between main - * power and battery backup power. This will ensure power to the backup domain, - * when the main battery or power source is unavailable. - * \endif - * - * \if DEVICE_SAMC21_SYSTEM_SUPPORT - * \subsection asfdoc_sam0_system_module_overview_vreg_c21 Voltage Regulator - * The SAM device controls the voltage regulators for the core (VDDCORE). It sets - * the voltage regulators according to the sleep modes. - * - * There are a selectable reference voltage and voltage dependent on the temperature - * which can be used by analog modules like the ADC. - * \endif - * - * \subsection asfdoc_sam0_system_module_overview_vref Voltage References - * The various analog modules within the SAM devices (such as AC, ADC, and - * DAC) require a voltage reference to be configured to act as a reference point - * for comparisons and conversions. - * - * The SAM devices contain multiple references, including an internal - * temperature sensor and a fixed band-gap voltage source. When enabled, the - * associated voltage reference can be selected within the desired peripheral - * where applicable. - * - * \subsection asfdoc_sam0_system_module_overview_reset_cause System Reset Cause - * In some applications there may be a need to execute a different program - * flow based on how the device was reset. For example, if the cause of reset - * was the Watchdog timer (WDT), this might indicate an error in the application, - * and a form of error handling or error logging might be needed. - * - * For this reason, an API is provided to retrieve the cause of the last system - * reset, so that appropriate action can be taken. - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * There are three groups of reset sources: - * - Power supply reset: Resets caused by an electrical issue. It covers POR and BOD reset. - * - User reset: Resets caused by the application. It covers external reset, - * system reset, and watchdog reset. - * - Backup reset: Resets caused by a backup mode exit condition. - * - * \subsection asfdoc_sam0_system_module_overview_performance_level Performance Level - * Performance level allows the user to adjust the regulator output voltage to reduce - * power consumption. The user can on the fly select the most suitable performance - * level, depending on the application demands. - * - * The SAM device can operate at two different performance levels (PL0 and PL2). - * When operating at PL0, the voltage applied on the full logic area is reduced - * by voltage scaling. This voltage scaling technique allows to reduce the active - * power consumption while decreasing the maximum frequency of the device. When - * operating at PL2, the voltage regulator supplies the highest voltage, allowing - * the device to run at higher clock speeds. - * - * Performance level transition is possible only when the device is in active - * mode. After a reset, the device starts at the lowest performance level - * (lowest power consumption and lowest max. frequency). The application can then - * switch to another performance level at any time without any stop in the code - * execution. As shown in \ref asfdoc_sam0_system_performance_level_transition_figure. - * - * \note When scaling down the performance level, the bus frequency should first be - * scaled down in order to not exceed the maximum frequency allowed for the - * low performance level. - * When scaling up the performance level (e.g. from PL0 to PL2), check the performance - * level status before increasing the bus frequency. It can be increased only - * when the performance level transition is completed. - * - * \anchor asfdoc_sam0_system_performance_level_transition_figure - * \image html performance_level_transition.svg "Performance Level Transition" - * - * \subsection asfdoc_sam0_system_module_overview_power_domain Power Domain Gating - * Power domain gating allows power saving by reducing the voltage in logic - * areas in the device to a low-power supply. The feature is available in - * Standby sleep mode and will reduce the voltage in domains where all peripherals - * are idle. Internal logic will maintain its content, meaning the corresponding - * peripherals will not need to be reconfigured when normal operating voltage - * is returned. Most power domains can be in the following three states: - * - * - Active state: The power domain is powered on. - * - Retention state: The main voltage supply for the power domain is switched off, - * while maintaining a secondary low-power supply for the sequential cells. The - * logic context is restored when waking up. - * - Off state: The power domain is entirely powered off. The logic context is lost. - * - * The SAM L21 device contains three power domains which can be controlled using - * power domain gating, namely PD0, PD1, and PD2. These power domains can be - * configured to the following cases: - * - Default with no sleepwalking peripherals: A power domain is automatically set - * to retention state in standby sleep mode if no activity require it. The application - * can force all power domains to remain in active state during standby sleep mode - * in order to accelerate wakeup time. - * - Default with sleepwalking peripherals: If one or more peripherals are enabled - * to perform sleepwalking tasks in standby sleep mode, the corresponding power - * domain (PDn) remains in active state as well as all inferior power domains (PDn) in order - * to perform a sleepwalking task. The superior power domain is then automatically - * set to active state. At the end of the sleepwalking task, the device can either - * be woken up or the superior power domain can return to retention state. - * - * Power domains can be linked to each other, it allows a power domain (PDn) to be kept - * in active state if the inferior power domain (PDn-1) is in active state too. - * - * \ref asfdoc_sam0_system_power_domain_overview_table illustrates the - * four cases to consider in standby mode. - * - * \anchor asfdoc_sam0_system_power_domain_overview_table - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Sleep Mode versus Power Domain State Overview
Sleep modePD0PD1PD2PDTOPPDBACKUP
Idleactiveactiveactiveactiveactive
Standby - Case 1activeactiveactiveactiveactive
Standby - Case 2activeactiveretentionactiveactive
Standby - Case 3activeretentionretentionactiveactive
Standby - Case 4retentionretentionretentionactiveactive
Backupoffoffoffoffactive
Offoffoffoffoffoff
- * - * \subsection asfdoc_sam0_system_module_overview_ram_state RAMs Low Power Mode - * By default, in standby sleep mode, RAM is in low power mode (back biased) - * if its power domain is in retention state. - * \ref asfdoc_sam0_system_power_ram_state_table lists RAMs low power mode. - * - * \anchor asfdoc_sam0_system_power_ram_state_table - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
RAM Back-biasing Mode
RAM modeDescription
Retention Back-biasing modeRAM is back-biased if its power domain is in retention mode
Standby Back-biasing modeRAM is back-biased if the device is in standby mode
Standby OFF modeRAM is OFF if the device is in standby mode
Always OFF modeRAM is OFF if the device is in RET mode
- * - * \endif - * - * \subsection asfdoc_sam0_system_module_overview_sleep_mode Sleep Modes - * The SAM devices have several sleep modes. The sleep mode controls - * which clock systems on the device will remain enabled or disabled when the - * device enters a low power sleep mode. - * \ref asfdoc_sam0_system_module_sleep_mode_table "The table below" lists the - * clock settings of the different sleep modes. - * - * \anchor asfdoc_sam0_system_module_sleep_mode_table - * - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * \else - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * \endif - *
SAM Device Sleep Modes
Sleep modeSystem clockCPU clockAHB/AHB clockGCLK clocksOscillators (ONDEMAND = 0)Oscillators (ONDEMAND = 1)Regulator modeRAM mode
IdleRunStopRun if requestedRunRunRun if requestedNormalNormal
StandbyStopStopRun if requestedRun if requestedRun if requested or RUNSTDBY = 1Run if requestedLow pwerLow pwer
BackupStopStopStopStopStopStopBackupOff
OffOffOffOffOffOffOffOffOff
Sleep modeCPU clockAHB clockAPB clocksClock sourcesSystem clock32KHzReg modeRAM mode
Idle 0StopRunRunRunRunRunNormalNormal
Idle 1StopStopRunRunRunRunNormalNormal
Idle 2StopStopStopRunRunRunNormalNormal
StandbyStopStopStopStopStopStopLow PowerSource/Drain biasing
- * - * Before entering device sleep, one of the available sleep modes must be set. - * The device will automatically wake up in response to an interrupt being - * generated or upon any other sleep mode exit condition. - * - * Some peripheral clocks will remain enabled during sleep, depending on their - * configuration. If desired, the modules can remain clocked during sleep to allow - * them continue to operate while other parts of the system are powered down - * to save power. - * - * - * \section asfdoc_sam0_system_special_considerations Special Considerations - * - * Most of the functions in this driver have device specific restrictions and - * caveats; refer to your device datasheet. - * - * - * \section asfdoc_sam0_system_extra_info Extra Information - * - * For extra information, see \ref asfdoc_sam0_system_extra. This includes: - * - \ref asfdoc_sam0_system_extra_acronyms - * - \ref asfdoc_sam0_system_extra_dependencies - * - \ref asfdoc_sam0_system_extra_errata - * - \ref asfdoc_sam0_system_extra_history - * - * - * \section asfdoc_sam0_system_examples Examples - * - * For SYSTEM module related examples, refer to the sub-modules listed in - * the \ref asfdoc_sam0_system_module_overview "system module overview". - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_drivers_power_exqsg. - * - * - * \section asfdoc_sam0_system_api_overview API Overview - * @{ - */ - -/** - * \name System Debugger - * @{ - */ - -/** - * \brief Check if debugger is present. - * - * Check if debugger is connected to the onboard debug system (DAP). - * - * \return A bool identifying if a debugger is present. - * - * \retval true Debugger is connected to the system - * \retval false Debugger is not connected to the system - * - */ -static inline bool system_is_debugger_present(void) -{ - return DSU->STATUSB.reg & DSU_STATUSB_DBGPRES; -} - -/** - * @} - */ - -/** - * \name System Identification - * @{ - */ - -/** - * \brief Retrieve the device identification signature. - * - * Retrieves the signature of the current device. - * - * \return Device ID signature as a 32-bit integer. - */ -static inline uint32_t system_get_device_id(void) -{ - return DSU->DID.reg; -} - -/** - * @} - */ - -/** - * \name System Initialization - * @{ - */ - -void system_init(void); - -/** - * @} - */ - - -/** - * @} - */ - -/** - -* \page asfdoc_sam0_drivers_power_exqsg Examples for Power Driver - * - * This is a list of the available Quick Start Guides (QSGs) and example - * applications. QSGs are simple examples with step-by-step instructions to - * configure and use this driver in a selection of - * use cases. Note that a QSG can be compiled as a standalone application or be - * added to the user application. - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - \subpage asfdoc_sam0_power_basic_use_case - * \endif - * - * \page asfdoc_sam0_system_extra Extra Information for SYSTEM Driver - * - * \section asfdoc_sam0_system_extra_acronyms Acronyms - * Below is a table listing the acronyms used in this module, along with their - * intended meanings. - * - * - * - * - * - * - * - * - * - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - * - * - * - * - * - * - * - * \endif - * \if DEVICE_SAMC21_SYSTEM_SUPPORT - * - * - * - * - * - * - * - * - * \endif - * \if DEVICE_SAMD21_SYSTEM_SUPPORT - * - * - * - * - * \endif - *
AcronymDefinition
PMPower Manager
SUPCSupply Controller
RSTCReset Controller
SUPCSupply Controller
RSTCReset Controller
SYSCTRLSystem control interface
- * - * - * \section asfdoc_sam0_system_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - None - * - * - * \section asfdoc_sam0_system_extra_errata Errata - * There are no errata related to this driver. - * - * - * \section asfdoc_sam0_system_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - * - * - * \endif - * \if DEVICE_SAMC21_SYSTEM_SUPPORT - * - * - * - * \endif - * \if DEVICE_SAMD21_SYSTEM_SUPPORT - * - * - * - * - * - * - * - * - * - * \endif - *
Changelog
Initial Release
Initial Release
Added new \c system_reset() to reset the complete MCU with some exceptions
Added new \c system_get_device_id() function to retrieved the device - * ID.
Initial Release
- * - * \page asfdoc_sam0_system_document_revision_history Document Revision History - * - * - * - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - * - * - * - * - * \endif - * \if DEVICE_SAMC21_SYSTEM_SUPPORT - * - * - * - * - * - * \endif - * \if DEVICE_SAMD21_SYSTEM_SUPPORT - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * \endif - *
Doc. Rev. - * Date - * Comments - *
42449A07/2015Initial document release
42484A08/2015Initial document release.
42120E04/2015Added support for SAMDAx
42120D12/2014Added support for SAMR21 and SAMD10/D11
42120C01/2014Added support for SAMD21
42120B06/2013Corrected documentation typos
42120A06/2013Initial document release
- */ - -#ifdef __cplusplus -} -#endif - -#endif /* SYSTEM_H_INCLUDED */ - diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/system_interrupt.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/system_interrupt.h deleted file mode 100644 index 93a542d..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/system_interrupt.h +++ /dev/null @@ -1,429 +0,0 @@ -/** - * \file - * - * \brief SAM System Interrupt Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef SYSTEM_INTERRUPT_H_INCLUDED -#define SYSTEM_INTERRUPT_H_INCLUDED - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \defgroup asfdoc_sam0_system_interrupt_group SAM System Interrupt (SYSTEM INTERRUPT) Driver - * - * This driver for Atmel® | SMART ARM®-based microcontrollers provides - * an interface for the configuration and management of internal software and - * hardware interrupts/exceptions. - * - * The following peripheral is used by this module: - * - NVIC (Nested Vector Interrupt Controller) - * - * The following devices can use this module: - * - Atmel | SMART SAM D20/D21 - * - Atmel | SMART SAM R21 - * - Atmel | SMART SAM D09/D10/D11 - * - Atmel | SMART SAM L21/L22 - * - Atmel | SMART SAM DA1 - * - Atmel | SMART SAM C20/C21 - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_system_interrupt_prerequisites - * - \ref asfdoc_sam0_system_interrupt_module_overview - * - \ref asfdoc_sam0_system_interrupt_special_considerations - * - \ref asfdoc_sam0_system_interrupt_extra_info - * - \ref asfdoc_sam0_system_interrupt_examples - * - \ref asfdoc_sam0_system_interrupt_api_overview - * - * - * \section asfdoc_sam0_system_interrupt_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * - * \section asfdoc_sam0_system_interrupt_module_overview Module Overview - * - * The ARM® Cortex® M0+ core contains an interrupt and exception vector table, which - * can be used to configure the device's interrupt handlers; individual - * interrupts and exceptions can be enabled and disabled, as well as configured - * with a variable priority. - * - * This driver provides a set of wrappers around the core interrupt functions, - * to expose a simple API for the management of global and individual interrupts - * within the device. - * - * \subsection asfdoc_sam0_system_interrupt_module_overview_criticalsec Critical Sections - * In some applications it is important to ensure that no interrupts may be - * executed by the system whilst a critical portion of code is being run; for - * example, a buffer may be copied from one context to another - during which - * interrupts must be disabled to avoid corruption of the source buffer contents - * until the copy has completed. This driver provides a basic API to enter and - * exit nested critical sections, so that global interrupts can be kept disabled - * for as long as necessary to complete a critical application code section. - * - * \subsection asfdoc_sam0_system_interrupt_module_overview_softints Software Interrupts - * For some applications, it may be desirable to raise a module or core - * interrupt via software. For this reason, a set of APIs to set an interrupt or - * exception as pending are provided to the user application. - * - * \section asfdoc_sam0_system_interrupt_special_considerations Special Considerations - * - * Interrupts from peripherals in the SAM devices are on a per-module basis; - * an interrupt raised from any source within a module will cause a single, - * module-common handler to execute. It is the user application or driver's - * responsibility to de-multiplex the module-common interrupt to determine the - * exact interrupt cause. - * - * \section asfdoc_sam0_system_interrupt_extra_info Extra Information - * - * For extra information, see \ref asfdoc_sam0_system_interrupt_extra. This includes: - * - \ref asfdoc_sam0_system_interrupt_extra_acronyms - * - \ref asfdoc_sam0_system_interrupt_extra_dependencies - * - \ref asfdoc_sam0_system_interrupt_extra_errata - * - \ref asfdoc_sam0_system_interrupt_extra_history - * - * - * \section asfdoc_sam0_system_interrupt_examples Examples - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_system_interrupt_exqsg. - * - * \section asfdoc_sam0_system_interrupt_api_overview API Overview - * @{ - */ - -#include "compiler.h" -#include -#include "system_interrupt_features.h" - -/** - * \brief Table of possible system interrupt/exception vector priorities. - * - * Table of all possible interrupt and exception vector priorities within the - * device. - */ -enum system_interrupt_priority_level { - /** Priority level 0, the highest possible interrupt priority */ - SYSTEM_INTERRUPT_PRIORITY_LEVEL_0 = 0, - /** Priority level 1 */ - SYSTEM_INTERRUPT_PRIORITY_LEVEL_1 = 1, - /** Priority level 2 */ - SYSTEM_INTERRUPT_PRIORITY_LEVEL_2 = 2, - /** Priority level 3, the lowest possible interrupt priority */ - SYSTEM_INTERRUPT_PRIORITY_LEVEL_3 = 3, -}; - -/** - * \name Critical Section Management - * @{ - */ - -/** - * \brief Enters a critical section. - * - * Disables global interrupts. To support nested critical sections, an internal - * count of the critical section nesting will be kept, so that global interrupts - * are only re-enabled upon leaving the outermost nested critical section. - * - */ -static inline void system_interrupt_enter_critical_section(void) -{ - cpu_irq_enter_critical(); -} - -/** - * \brief Leaves a critical section. - * - * Enables global interrupts. To support nested critical sections, an internal - * count of the critical section nesting will be kept, so that global interrupts - * are only re-enabled upon leaving the outermost nested critical section. - * - */ -static inline void system_interrupt_leave_critical_section(void) -{ - cpu_irq_leave_critical(); -} - -/** @} */ - -/** - * \name Interrupt Enabling/Disabling - * @{ - */ - -/** - * \brief Check if global interrupts are enabled. - * - * Checks if global interrupts are currently enabled. - * - * \returns A boolean that identifies if the global interrupts are enabled or not. - * - * \retval true Global interrupts are currently enabled - * \retval false Global interrupts are currently disabled - * - */ -static inline bool system_interrupt_is_global_enabled(void) -{ - return cpu_irq_is_enabled(); -} - -/** - * \brief Enables global interrupts. - * - * Enables global interrupts in the device to fire any enabled interrupt handlers. - */ -static inline void system_interrupt_enable_global(void) -{ - cpu_irq_enable(); -} - -/** - * \brief Disables global interrupts. - * - * Disabled global interrupts in the device, preventing any enabled interrupt - * handlers from executing. - */ -static inline void system_interrupt_disable_global(void) -{ - cpu_irq_disable(); -} - -/** - * \brief Checks if an interrupt vector is enabled or not. - * - * Checks if a specific interrupt vector is currently enabled. - * - * \param[in] vector Interrupt vector number to check - * - * \returns A variable identifying if the requested interrupt vector is enabled. - * - * \retval true Specified interrupt vector is currently enabled - * \retval false Specified interrupt vector is currently disabled - * - */ -static inline bool system_interrupt_is_enabled( - const enum system_interrupt_vector vector) -{ - return (bool)((NVIC->ISER[0] >> (uint32_t)vector) & 0x00000001); -} - -/** - * \brief Enable interrupt vector. - * - * Enables execution of the software handler for the requested interrupt vector. - * - * \param[in] vector Interrupt vector to enable - */ -static inline void system_interrupt_enable( - const enum system_interrupt_vector vector) -{ - NVIC->ISER[0] = (uint32_t)(1 << ((uint32_t)vector & 0x0000001f)); -} - -/** - * \brief Disable interrupt vector. - * - * Disables execution of the software handler for the requested interrupt vector. - * - * \param[in] vector Interrupt vector to disable - */ -static inline void system_interrupt_disable( - const enum system_interrupt_vector vector) -{ - NVIC->ICER[0] = (uint32_t)(1 << ((uint32_t)vector & 0x0000001f)); -} - -/** @} */ - -/** - * \name Interrupt State Management - * @{ - */ - -/** - * \brief Get active interrupt (if any). - * - * Return the vector number for the current executing software handler, if any. - * - * \return Interrupt number that is currently executing. - */ -static inline enum system_interrupt_vector system_interrupt_get_active(void) -{ - uint32_t IPSR = __get_IPSR(); - /* The IPSR returns the Exception number, which with an offset 16 to IRQ number. */ - return (enum system_interrupt_vector)((IPSR & _SYSTEM_INTERRUPT_IPSR_MASK) - 16); -} - -bool system_interrupt_is_pending( - const enum system_interrupt_vector vector); - -enum status_code system_interrupt_set_pending( - const enum system_interrupt_vector vector); - -enum status_code system_interrupt_clear_pending( - const enum system_interrupt_vector vector); - -/** @} */ - -/** - * \name Interrupt Priority Management - * @{ - */ - -enum status_code system_interrupt_set_priority( - const enum system_interrupt_vector vector, - const enum system_interrupt_priority_level priority_level); - -enum system_interrupt_priority_level system_interrupt_get_priority( - const enum system_interrupt_vector vector); - -/** @} */ - -/** @} */ - -/** - * \page asfdoc_sam0_system_interrupt_extra Extra Information for SYSTEM INTERRUPT Driver - * - * \section asfdoc_sam0_system_interrupt_extra_acronyms Acronyms - * The table below presents the acronyms used in this module: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
AcronymDescription
ISRInterrupt Service Routine
NMINon-maskable Interrupt
SERCOMSerial Communication Interface
- * - * - * \section asfdoc_sam0_system_interrupt_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - None - * - * - * \section asfdoc_sam0_system_interrupt_extra_errata Errata - * There are no errata related to this driver. - * - * - * \section asfdoc_sam0_system_interrupt_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * - * - * - *
Changelog
Initial Release
- */ - -/** - * \page asfdoc_sam0_system_interrupt_exqsg Examples for SYSTEM INTERRUPT Driver - * - * This is a list of the available Quick Start guides (QSGs) and example - * applications for \ref asfdoc_sam0_system_interrupt_group. QSGs are simple examples with - * step-by-step instructions to configure and use this driver in a selection of - * use cases. Note that a QSG can be compiled as a standalone application or be - * added to the user application. - * - * - \subpage asfdoc_sam0_system_interrupt_critsec_use_case - * - \subpage asfdoc_sam0_system_interrupt_enablemodint_use_case - * - * \page asfdoc_sam0_system_interrupt_document_revision_history Document Revision History - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Doc. Rev. - * Date - * Comments - *
42122E08/2015Added support for SAM L21/L22, SAM DA1, and SAM C20/C21
42122D12/2014Added support for SAM R21 and SAM D10/D11
42122C01/2014Added support for SAM D21
42122B06/2013Corrected documentation typos
42122A06/2013Initial release
- */ - -#ifdef __cplusplus -} -#endif - -#endif // #ifndef SYSTEM_INTERRUPT_H_INCLUDED diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/system_interrupt_features.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/system_interrupt_features.h deleted file mode 100644 index 25dfa83..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/system_interrupt_features.h +++ /dev/null @@ -1,195 +0,0 @@ -/** - * \file - * - * \brief SAM D21 System Interrupt Driver - * - * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#ifndef SYSTEM_INTERRUPT_FEATURES_H_INCLUDED -#define SYSTEM_INTERRUPT_FEATURES_H_INCLUDED - -#if !defined(__DOXYGEN__) - -/* Generates a interrupt vector table enum list entry for a given module type - and index (e.g. "SYSTEM_INTERRUPT_MODULE_TC0 = TC0_IRQn,"). */ -# define _MODULE_IRQn(n, module) \ - SYSTEM_INTERRUPT_MODULE_##module##n = module##n##_IRQn, - -/* Generates interrupt vector table enum list entries for all instances of a - given module type on the selected device. */ -# define _SYSTEM_INTERRUPT_MODULES(name) \ - MREPEAT(name##_INST_NUM, _MODULE_IRQn, name) - -# define _SYSTEM_INTERRUPT_IPSR_MASK 0x0000003f -# define _SYSTEM_INTERRUPT_PRIORITY_MASK 0x00000003 - -# define _SYSTEM_INTERRUPT_EXTERNAL_VECTOR_START 0 - -# define _SYSTEM_INTERRUPT_SYSTICK_PRI_POS 30 -#endif - -/** - * \addtogroup asfdoc_sam0_system_interrupt_group - * @{ - */ - -/** - * \brief Table of possible system interrupt/exception vector numbers. - * - * Table of all possible interrupt and exception vector indexes within the - * SAM D21 device. Check peripherals configuration in SAM D21 datasheet for - * available vector index for specific device. - * - */ -#if defined(__DOXYGEN__) -/** \note The actual enumeration name is "system_interrupt_vector". */ -enum system_interrupt_vector_samd21 { -#else -enum system_interrupt_vector { -#endif - /** Interrupt vector index for a NMI interrupt */ - SYSTEM_INTERRUPT_NON_MASKABLE = NonMaskableInt_IRQn, - /** Interrupt vector index for a Hard Fault memory access exception */ - SYSTEM_INTERRUPT_HARD_FAULT = HardFault_IRQn, - /** Interrupt vector index for a Supervisor Call exception */ - SYSTEM_INTERRUPT_SV_CALL = SVCall_IRQn, - /** Interrupt vector index for a Pending Supervisor interrupt */ - SYSTEM_INTERRUPT_PENDING_SV = PendSV_IRQn, - /** Interrupt vector index for a System Tick interrupt */ - SYSTEM_INTERRUPT_SYSTICK = SysTick_IRQn, - - /** Interrupt vector index for a Power Manager peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_PM = PM_IRQn, - /** Interrupt vector index for a System Control peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_SYSCTRL = SYSCTRL_IRQn, - /** Interrupt vector index for a Watch Dog peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_WDT = WDT_IRQn, - /** Interrupt vector index for a Real Time Clock peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_RTC = RTC_IRQn, - /** Interrupt vector index for an External Interrupt peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_EIC = EIC_IRQn, - /** Interrupt vector index for a Non Volatile Memory Controller interrupt */ - SYSTEM_INTERRUPT_MODULE_NVMCTRL = NVMCTRL_IRQn, - /** Interrupt vector index for a Direct Memory Access interrupt */ - SYSTEM_INTERRUPT_MODULE_DMA = DMAC_IRQn, -#if defined(__DOXYGEN__) || defined(ID_USB) - /** Interrupt vector index for a Universal Serial Bus interrupt */ - SYSTEM_INTERRUPT_MODULE_USB = USB_IRQn, -#endif - /** Interrupt vector index for an Event System interrupt */ - SYSTEM_INTERRUPT_MODULE_EVSYS = EVSYS_IRQn, -#if defined(__DOXYGEN__) - /** Interrupt vector index for a SERCOM peripheral interrupt. - * - * Each specific device may contain several SERCOM peripherals; each module - * instance will have its own entry in the table, with the instance number - * substituted for "n" in the entry name (e.g. - * \c SYSTEM_INTERRUPT_MODULE_SERCOM0). - */ - SYSTEM_INTERRUPT_MODULE_SERCOMn = SERCOMn_IRQn, - - /** Interrupt vector index for a Timer/Counter Control peripheral interrupt. - * - * Each specific device may contain several TCC peripherals; each module - * instance will have its own entry in the table, with the instance number - * substituted for "n" in the entry name (e.g. - * \c SYSTEM_INTERRUPT_MODULE_TCC0). - */ - SYSTEM_INTERRUPT_MODULE_TCCn = TCCn_IRQn, - - /** Interrupt vector index for a Timer/Counter peripheral interrupt. - * - * Each specific device may contain several TC peripherals; each module - * instance will have its own entry in the table, with the instance number - * substituted for "n" in the entry name (e.g. - * \c SYSTEM_INTERRUPT_MODULE_TC3). - */ - SYSTEM_INTERRUPT_MODULE_TCn = TCn_IRQn, -#else - _SYSTEM_INTERRUPT_MODULES(SERCOM) - - _SYSTEM_INTERRUPT_MODULES(TCC) - - SYSTEM_INTERRUPT_MODULE_TC3 = TC3_IRQn, - SYSTEM_INTERRUPT_MODULE_TC4 = TC4_IRQn, - SYSTEM_INTERRUPT_MODULE_TC5 = TC5_IRQn, -# if defined(ID_TC6) - SYSTEM_INTERRUPT_MODULE_TC6 = TC6_IRQn, -# endif -# if defined(ID_TC7) - SYSTEM_INTERRUPT_MODULE_TC7 = TC7_IRQn, -# endif -#endif - -#if defined(__DOXYGEN__) || defined(ID_ADC) - /** Interrupt vector index for an Analog-to-Digital peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_ADC = ADC_IRQn, -#endif - -#if defined(__DOXYGEN__) || defined(ID_AC) - /** Interrupt vector index for an Analog Comparator peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_AC = AC_IRQn, -#endif - -#if defined(__DOXYGEN__) || defined(ID_DAC) - /** Interrupt vector index for a Digital-to-Analog peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_DAC = DAC_IRQn, -#endif -#if defined(__DOXYGEN__) || defined(ID_PTC) - /** Interrupt vector index for a Peripheral Touch Controller peripheral - * interrupt */ - SYSTEM_INTERRUPT_MODULE_PTC = PTC_IRQn, -#endif -#if defined(__DOXYGEN__) || defined(ID_I2S) - /** Interrupt vector index for a Inter-IC Sound Interface peripheral - * interrupt */ - SYSTEM_INTERRUPT_MODULE_I2S = I2S_IRQn, -#endif -#if defined(__DOXYGEN__) || defined(ID_AC1) - /** Interrupt vector index for an Analog Comparator 1 peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_AC1 = AC1_IRQn, -#endif -}; - -/** @} */ - -#endif diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/tc.c b/feather_sensor_lte/libraries/Adafruit_ASFcore/tc.c deleted file mode 100644 index 23e2703..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/tc.c +++ /dev/null @@ -1,685 +0,0 @@ -/** - * \file - * - * \brief SAM TC - Timer Counter Driver - * - * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#include "tc.h" - -#if TC_ASYNC == true -# include "tc_interrupt.h" -# include - -/** \internal - * Converts a given TC index to its interrupt vector index. - */ -# define _TC_INTERRUPT_VECT_NUM(n, unused) \ - SYSTEM_INTERRUPT_MODULE_TC##n, -#endif - -#if !defined(__DOXYGEN__) -# define _TC_GCLK_ID(n,unused) TPASTE3(TC,n,_GCLK_ID) , -# define _TC_PM_APBCMASK(n,unused) TPASTE2(PM_APBCMASK_TC,n) , - -# define TC_INST_GCLK_ID { MRECURSION(TC_INST_NUM, _TC_GCLK_ID, TC_INST_MAX_ID) } -# define TC_INST_PM_APBCMASK { MRECURSION(TC_INST_NUM, _TC_PM_APBCMASK, TC_INST_MAX_ID) } - -#endif - -/** - * \internal Find the index of given TC module instance. - * - * \param[in] TC module instance pointer. - * - * \return Index of the given TC module instance. - */ -uint8_t _tc_get_inst_index( - Tc *const hw) -{ - /* List of available TC modules. */ - Tc *const tc_modules[TC_INST_NUM] = TC_INSTS; - - /* Find index for TC instance. */ - for (uint32_t i = 0; i < TC_INST_NUM; i++) { - if (hw == tc_modules[i]) { - return i; - } - } - - /* Invalid data given. */ - Assert(false); - return 0; -} - - -/** - * \brief Initializes a hardware TC module instance. - * - * Enables the clock and initializes the TC module, based on the given - * configuration values. - * - * \param[in,out] module_inst Pointer to the software module instance struct - * \param[in] hw Pointer to the TC hardware module - * \param[in] config Pointer to the TC configuration options struct - * - * \return Status of the initialization procedure. - * - * \retval STATUS_OK The module was initialized successfully - * \retval STATUS_BUSY Hardware module was busy when the - * initialization procedure was attempted - * \retval STATUS_INVALID_ARG An invalid configuration option or argument - * was supplied - * \retval STATUS_ERR_DENIED Hardware module was already enabled, or the - * hardware module is configured in 32-bit - * slave mode - */ -enum status_code tc_init( - struct tc_module *const module_inst, - Tc *const hw, - const struct tc_config *const config) -{ - /* Sanity check arguments */ - Assert(hw); - Assert(module_inst); - Assert(config); - - /* Temporary variable to hold all updates to the CTRLA - * register before they are written to it */ - uint16_t ctrla_tmp = 0; - /* Temporary variable to hold all updates to the CTRLBSET - * register before they are written to it */ - uint8_t ctrlbset_tmp = 0; - /* Temporary variable to hold all updates to the CTRLC - * register before they are written to it */ - uint8_t ctrlc_tmp = 0; - /* Temporary variable to hold TC instance number */ - uint8_t instance = _tc_get_inst_index(hw); - - /* Array of GLCK ID for different TC instances */ - uint8_t inst_gclk_id[] = TC_INST_GCLK_ID; - /* Array of PM APBC mask bit position for different TC instances */ - uint16_t inst_pm_apbmask[] = TC_INST_PM_APBCMASK; - - struct system_pinmux_config pin_config; - struct system_gclk_chan_config gclk_chan_config; - -#if TC_ASYNC == true - /* Initialize parameters */ - for (uint8_t i = 0; i < TC_CALLBACK_N; i++) { - module_inst->callback[i] = NULL; - } - module_inst->register_callback_mask = 0x00; - module_inst->enable_callback_mask = 0x00; - - /* Register this instance for callbacks*/ - _tc_instances[instance] = module_inst; -#endif - - /* Associate the given device instance with the hardware module */ - module_inst->hw = hw; - -#if SAMD09 || SAMD10 || SAMD11 - /* Check if even numbered TC modules are being configured in 32-bit - * counter size. Only odd numbered counters are allowed to be - * configured in 32-bit counter size. - */ - if ((config->counter_size == TC_COUNTER_SIZE_32BIT) && - !((instance + TC_INSTANCE_OFFSET) & 0x01)) { - Assert(false); - return STATUS_ERR_INVALID_ARG; - } -#else - /* Check if odd numbered TC modules are being configured in 32-bit - * counter size. Only even numbered counters are allowed to be - * configured in 32-bit counter size. - */ - if ((config->counter_size == TC_COUNTER_SIZE_32BIT) && - ((instance + TC_INSTANCE_OFFSET) & 0x01)) { - Assert(false); - return STATUS_ERR_INVALID_ARG; - } -#endif - - /* Make the counter size variable in the module_inst struct reflect - * the counter size in the module - */ - module_inst->counter_size = config->counter_size; - - if (hw->COUNT8.CTRLA.reg & TC_CTRLA_SWRST) { - /* We are in the middle of a reset. Abort. */ - return STATUS_BUSY; - } - - if (hw->COUNT8.STATUS.reg & TC_STATUS_SLAVE) { - /* Module is used as a slave */ - return STATUS_ERR_DENIED; - } - - if (hw->COUNT8.CTRLA.reg & TC_CTRLA_ENABLE) { - /* Module must be disabled before initialization. Abort. */ - return STATUS_ERR_DENIED; - } - - /* Set up the TC PWM out pin for channel 0 */ - if (config->pwm_channel[0].enabled) { - system_pinmux_get_config_defaults(&pin_config); - pin_config.mux_position = config->pwm_channel[0].pin_mux; - pin_config.direction = SYSTEM_PINMUX_PIN_DIR_OUTPUT; - system_pinmux_pin_set_config( - config->pwm_channel[0].pin_out, &pin_config); - } - - /* Set up the TC PWM out pin for channel 1 */ - if (config->pwm_channel[1].enabled) { - system_pinmux_get_config_defaults(&pin_config); - pin_config.mux_position = config->pwm_channel[1].pin_mux; - pin_config.direction = SYSTEM_PINMUX_PIN_DIR_OUTPUT; - system_pinmux_pin_set_config( - config->pwm_channel[1].pin_out, &pin_config); - } - - /* Enable the user interface clock in the PM */ - system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, - inst_pm_apbmask[instance]); - - /* Enable the slave counter if counter_size is 32-bit */ - if ((config->counter_size == TC_COUNTER_SIZE_32BIT)) - { - /* Enable the user interface clock in the PM */ - system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, - inst_pm_apbmask[instance + 1]); - } - - /* Setup clock for module */ - system_gclk_chan_get_config_defaults(&gclk_chan_config); - gclk_chan_config.source_generator = config->clock_source; - system_gclk_chan_set_config(inst_gclk_id[instance], &gclk_chan_config); - system_gclk_chan_enable(inst_gclk_id[instance]); - - /* Set ctrla register */ - ctrla_tmp = - (uint32_t)config->counter_size | - (uint32_t)config->wave_generation | - (uint32_t)config->reload_action | - (uint32_t)config->clock_prescaler; - - if (config->run_in_standby) { - ctrla_tmp |= TC_CTRLA_RUNSTDBY; - } - - /* Write configuration to register */ - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - hw->COUNT8.CTRLA.reg = ctrla_tmp; - - /* Set ctrlb register */ - if (config->oneshot) { - ctrlbset_tmp = TC_CTRLBSET_ONESHOT; - } - - if (config->count_direction) { - ctrlbset_tmp |= TC_CTRLBSET_DIR; - } - - /* Clear old ctrlb configuration */ - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - hw->COUNT8.CTRLBCLR.reg = 0xFF; - - /* Check if we actually need to go into a wait state. */ - if (ctrlbset_tmp) { - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - /* Write configuration to register */ - hw->COUNT8.CTRLBSET.reg = ctrlbset_tmp; - } - - /* Set ctrlc register*/ - ctrlc_tmp = config->waveform_invert_output; - for (uint8_t i = 0; i < NUMBER_OF_COMPARE_CAPTURE_CHANNELS; i++) { - if (config->enable_capture_on_channel[i] == true) { - ctrlc_tmp |= (TC_CTRLC_CPTEN(1) << i); - } - } - - /* Write configuration to register */ - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - hw->COUNT8.CTRLC.reg = ctrlc_tmp; - - /* Write configuration to register */ - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Switch for TC counter size */ - switch (module_inst->counter_size) { - case TC_COUNTER_SIZE_8BIT: - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT8.COUNT.reg = - config->counter_8_bit.value; - - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT8.PER.reg = - config->counter_8_bit.period; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT8.CC[0].reg = - config->counter_8_bit.compare_capture_channel[0]; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT8.CC[1].reg = - config->counter_8_bit.compare_capture_channel[1]; - - return STATUS_OK; - - case TC_COUNTER_SIZE_16BIT: - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT16.COUNT.reg - = config->counter_16_bit.value; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT16.CC[0].reg = - config->counter_16_bit.compare_capture_channel[0]; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT16.CC[1].reg = - config->counter_16_bit.compare_capture_channel[1]; - - return STATUS_OK; - - case TC_COUNTER_SIZE_32BIT: - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT32.COUNT.reg - = config->counter_32_bit.value; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT32.CC[0].reg = - config->counter_32_bit.compare_capture_channel[0]; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT32.CC[1].reg = - config->counter_32_bit.compare_capture_channel[1]; - - return STATUS_OK; - } - - Assert(false); - return STATUS_ERR_INVALID_ARG; -} - -/** - * \brief Sets TC module count value. - * - * Sets the current timer count value of a initialized TC module. The - * specified TC module may be started or stopped. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] count New timer count value to set - * - * \return Status of the count update procedure. - * - * \retval STATUS_OK The timer count was updated successfully - * \retval STATUS_ERR_INVALID_ARG An invalid timer counter size was specified - */ -enum status_code tc_set_count_value( - const struct tc_module *const module_inst, - const uint32_t count) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance*/ - Tc *const tc_module = module_inst->hw; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Write to based on the TC counter_size */ - switch (module_inst->counter_size) { - case TC_COUNTER_SIZE_8BIT: - tc_module->COUNT8.COUNT.reg = (uint8_t)count; - return STATUS_OK; - - case TC_COUNTER_SIZE_16BIT: - tc_module->COUNT16.COUNT.reg = (uint16_t)count; - return STATUS_OK; - - case TC_COUNTER_SIZE_32BIT: - tc_module->COUNT32.COUNT.reg = (uint32_t)count; - return STATUS_OK; - - default: - return STATUS_ERR_INVALID_ARG; - } -} - -/** - * \brief Get TC module count value. - * - * Retrieves the current count value of a TC module. The specified TC module - * may be started or stopped. - * - * \param[in] module_inst Pointer to the software module instance struct - * - * \return Count value of the specified TC module. - */ -uint32_t tc_get_count_value( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - Tc *const tc_module = module_inst->hw; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Read from based on the TC counter size */ - switch (module_inst->counter_size) { - case TC_COUNTER_SIZE_8BIT: - return (uint32_t)tc_module->COUNT8.COUNT.reg; - - case TC_COUNTER_SIZE_16BIT: - return (uint32_t)tc_module->COUNT16.COUNT.reg; - - case TC_COUNTER_SIZE_32BIT: - return tc_module->COUNT32.COUNT.reg; - } - - Assert(false); - return 0; -} - -/** - * \brief Gets the TC module capture value. - * - * Retrieves the capture value in the indicated TC module capture channel. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] channel_index Index of the Compare Capture channel to read - * - * \return Capture value stored in the specified timer channel. - */ -uint32_t tc_get_capture_value( - const struct tc_module *const module_inst, - const enum tc_compare_capture_channel channel_index) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - Tc *const tc_module = module_inst->hw; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Read out based on the TC counter size */ - switch (module_inst->counter_size) { - case TC_COUNTER_SIZE_8BIT: - if (channel_index < - NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { - return tc_module->COUNT8.CC[channel_index].reg; - } - - case TC_COUNTER_SIZE_16BIT: - if (channel_index < - NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { - return tc_module->COUNT16.CC[channel_index].reg; - } - - case TC_COUNTER_SIZE_32BIT: - if (channel_index < - NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { - return tc_module->COUNT32.CC[channel_index].reg; - } - } - - Assert(false); - return 0; -} - -/** - * \brief Sets a TC module compare value. - * - * Writes a compare value to the given TC module compare/capture channel. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] channel_index Index of the compare channel to write to - * \param[in] compare New compare value to set - * - * \return Status of the compare update procedure. - * - * \retval STATUS_OK The compare value was updated successfully - * \retval STATUS_ERR_INVALID_ARG An invalid channel index was supplied - */ -enum status_code tc_set_compare_value( - const struct tc_module *const module_inst, - const enum tc_compare_capture_channel channel_index, - const uint32_t compare) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - Tc *const tc_module = module_inst->hw; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Read out based on the TC counter size */ - switch (module_inst->counter_size) { - case TC_COUNTER_SIZE_8BIT: - if (channel_index < - NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { - tc_module->COUNT8.CC[channel_index].reg = - (uint8_t)compare; - return STATUS_OK; - } - - case TC_COUNTER_SIZE_16BIT: - if (channel_index < - NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { - tc_module->COUNT16.CC[channel_index].reg = - (uint16_t)compare; - return STATUS_OK; - } - - case TC_COUNTER_SIZE_32BIT: - if (channel_index < - NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { - tc_module->COUNT32.CC[channel_index].reg = - (uint32_t)compare; - return STATUS_OK; - } - } - - return STATUS_ERR_INVALID_ARG; -} - -/** - * \brief Resets the TC module. - * - * Resets the TC module, restoring all hardware module registers to their - * default values and disabling the module. The TC module will not be - * accessible while the reset is being performed. - * - * \note When resetting a 32-bit counter only the master TC module's instance - * structure should be passed to the function. - * - * \param[in] module_inst Pointer to the software module instance struct - * - * \return Status of the procedure. - * \retval STATUS_OK The module was reset successfully - * \retval STATUS_ERR_UNSUPPORTED_DEV A 32-bit slave TC module was passed to - * the function. Only use reset on master - * TC - */ -enum status_code tc_reset( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - if (tc_module->STATUS.reg & TC_STATUS_SLAVE) { - return STATUS_ERR_UNSUPPORTED_DEV; - } - - /* Disable this module if it is running */ - if (tc_module->CTRLA.reg & TC_CTRLA_ENABLE) { - tc_disable(module_inst); - while (tc_is_syncing(module_inst)) { - /* wait while module is disabling */ - } - } - - /* Reset this TC module */ - tc_module->CTRLA.reg |= TC_CTRLA_SWRST; - - return STATUS_OK; -} - -/** - * \brief Set the timer TOP/period value. - * - * For 8-bit counter size this function writes the top value to the period - * register. - * - * For 16- and 32-bit counter size this function writes the top value to - * Capture Compare register 0. The value in this register can not be used for - * any other purpose. - * - * \note This function is designed to be used in PWM or frequency - * match modes only. When the counter is set to 16- or 32-bit counter - * size. In 8-bit counter size it will always be possible to change the - * top value even in normal mode. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] top_value New timer TOP value to set - * - * \return Status of the TOP set procedure. - * - * \retval STATUS_OK The timer TOP value was updated successfully - * \retval STATUS_ERR_INVALID_ARG The configured TC module counter size in the - * module instance is invalid - */ -enum status_code tc_set_top_value ( - const struct tc_module *const module_inst, - const uint32_t top_value) -{ - Assert(module_inst); - Assert(module_inst->hw); - Assert(top_value); - - Tc *const tc_module = module_inst->hw; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - switch (module_inst->counter_size) { - case TC_COUNTER_SIZE_8BIT: - tc_module->COUNT8.PER.reg = (uint8_t)top_value; - return STATUS_OK; - - case TC_COUNTER_SIZE_16BIT: - tc_module->COUNT16.CC[0].reg = (uint16_t)top_value; - return STATUS_OK; - - case TC_COUNTER_SIZE_32BIT: - tc_module->COUNT32.CC[0].reg = (uint32_t)top_value; - return STATUS_OK; - - default: - Assert(false); - return STATUS_ERR_INVALID_ARG; - } -} diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/tc.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/tc.h deleted file mode 100644 index 0ee7006..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/tc.h +++ /dev/null @@ -1,1783 +0,0 @@ -/** - * \file - * - * \brief SAM TC - Timer Counter Driver - * - * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#ifndef TC_H_INCLUDED -#define TC_H_INCLUDED - -/** - * \defgroup asfdoc_sam0_tc_group SAM Timer/Counter Driver (TC) - * - * This driver for Atmel® | SMART ARM®-based microcontrollers provides an interface for the configuration - * and management of the timer modules within the device, for waveform - * generation and timing operations. The following driver API modes are covered - * by this manual: - * - * - Polled APIs - * \if TC_CALLBACK_MODE - * - Callback APIs - * \endif - * - * - * The following peripherals are used by this module: - * - TC (Timer/Counter) - * - * The following devices can use this module: - * - Atmel | SMART SAM D20/D21 - * - Atmel | SMART SAM R21 - * - Atmel | SMART SAM D09/D10/D11 - * - Atmel | SMART SAM L21/L22 - * - Atmel | SMART SAM DA1 - * - Atmel | SMART SAM C20/C21 - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_tc_prerequisites - * - \ref asfdoc_sam0_tc_module_overview - * - \ref asfdoc_sam0_tc_special_considerations - * - \ref asfdoc_sam0_tc_extra_info - * - \ref asfdoc_sam0_tc_examples - * - \ref asfdoc_sam0_tc_api_overview - * - * - * \section asfdoc_sam0_tc_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * - * \section asfdoc_sam0_tc_module_overview Module Overview - * - * The Timer/Counter (TC) module provides a set of timing and counting related - * functionality, such as the generation of periodic waveforms, the capturing - * of a periodic waveform's frequency/duty cycle, and software timekeeping for - * periodic operations. TC modules can be configured to use an 8-, 16-, or - * 32-bit counter size. - * - * This TC module for the SAM is capable of the following functions: - * - * - Generation of PWM signals - * - Generation of timestamps for events - * - General time counting - * - Waveform period capture - * - Waveform frequency capture - * - * \ref asfdoc_sam0_tc_block_diagram "The diagram below" shows the overview - * of the TC module design. - * - * \anchor asfdoc_sam0_tc_block_diagram - * \image html overview.svg "Basic Overview of the TC Module" - * - * - * \subsection asfdoc_sam0_tc_features Driver Feature Macro Definition - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Driver Feature MacroSupported devices
FEATURE_TC_DOUBLE_BUFFEREDSAM L21/L22/C20/C21
FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2SAM L21/L22/C20/C21
FEATURE_TC_STAMP_PW_CAPTURESAM L21/L22/C20/C21
FEATURE_TC_READ_SYNCSAM L21/L22/C20/C21
FEATURE_TC_IO_CAPTURESAM L21/L22/C20/C21
FEATURE_TC_GENERATE_DMA_TRIGGERSAM L21/L22
- * \note The specific features are only available in the driver when the - * selected device supports those features. - * - * \subsection asfdoc_sam0_tc_module_overview_func_desc Functional Description - * Independent of the configured counter size, each TC module can be set up - * in one of two different modes; capture and compare. - * - * In capture mode, the counter value is stored when a configurable event - * occurs. This mode can be used to generate timestamps used in event capture, - * or it can be used for the measurement of a periodic input signal's - * frequency/duty cycle. - * - * In compare mode, the counter value is compared against one or more of the - * configured channel compare values. When the counter value coincides with a - * compare value an action can be taken automatically by the module, such as - * generating an output event or toggling a pin when used for frequency or PWM - * signal generation. - * - * \note The connection of events between modules requires the use of the - * \ref asfdoc_sam0_events_group "SAM Event System Driver (EVENTS)" - * to route output event of one module to the input event of another. - * For more information on event routing, refer to the event driver - * documentation. - * - * \subsection asfdoc_sam0_tc_module_overview_tc_size Timer/Counter Size - * Each timer module can be configured in one of three different counter - * sizes; 8-, 16-, and 32-bit. The size of the counter determines the maximum - * value it can count to before an overflow occurs and the count is reset back - * to zero. \ref asfdoc_sam0_tc_count_size_vs_top "The table below" shows the - * maximum values for each of the possible counter sizes. - * - * \anchor asfdoc_sam0_tc_count_size_vs_top - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Timer Counter Sizes and Their Maximum Count Values
Counter sizeMax. (hexadecimal)Max. (decimal)
8-bit0xFF255
16-bit0xFFFF65,535
32-bit0xFFFFFFFF4,294,967,295
- * - * When using the counter in 16- or 32-bit count mode, Compare Capture - * register 0 (CC0) is used to store the period value when running in PWM - * generation match mode. - * - * When using 32-bit counter size, two 16-bit counters are chained together - * in a cascade formation. Except in SAM D09/D10/D11, Even numbered TC modules - * (e.g. TC0, TC2) can be configured as 32-bit counters. The odd numbered - * counters will act as slaves to the even numbered masters, and will not - * be reconfigurable until the master timer is disabled. The pairing of timer - * modules for 32-bit mode is shown in \ref asfdoc_sam0_tc_module_ms_pairs - * "the table below". - * - * \anchor asfdoc_sam0_tc_module_ms_pairs - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
TC Master and Slave Module Pairings
Master TC ModuleSlave TC Module
TC0TC1
TC2TC3
......
TCn-1TCn
- * - * In SAM D09/D10/D11, odd numbered TC modules (e.g. TC1) can be configured as 32-bit - * counters. The even numbered(e.g. TC2) counters will act as slaves to the odd - * numbered masters. - * - * \subsection asfdoc_sam0_tc_module_overview_clock Clock Settings - * - * \subsubsection asfdoc_sam0_tc_module_overview_clock_selection Clock Selection - * Each TC peripheral is clocked asynchronously to the system clock by a GCLK - * (Generic Clock) channel. The GCLK channel connects to any of the GCLK - * generators. The GCLK generators are configured to use one of the available - * clock sources on the system such as internal oscillator, external crystals, - * etc. see the \ref asfdoc_sam0_system_clock_group "Generic Clock driver" - *for - * more information. - * - * \subsubsection asfdoc_sam0_tc_module_overview_clock_prescaler Prescaler - * Each TC module in the SAM has its own individual clock prescaler, which - * can be used to divide the input clock frequency used in the counter. This - * prescaler only scales the clock used to provide clock pulses for the counter - * to count, and does not affect the digital register interface portion of - * the module, thus the timer registers will synchronize to the raw GCLK - * frequency input to the module. - * - * As a result of this, when selecting a GCLK frequency and timer prescaler - * value the user application should consider both the timer resolution - * required and the synchronization frequency, to avoid lengthy - * synchronization times of the module if a very slow GCLK frequency is fed - * into the TC module. It is preferable to use a higher module GCLK frequency - * as the input to the timer, and prescale this down as much as possible to - * obtain a suitable counter frequency in latency-sensitive applications. - * - * \subsubsection asfdoc_sam0_tc_module_overview_clock_reloading Reloading - * Timer modules also contain a configurable reload action, used when a - * re-trigger event occurs. Examples of a re-trigger event are the counter - * reaching the maximum value when counting up, or when an event from the event - * system tells the counter to re-trigger. The reload action determines if the - * prescaler should be reset, and when this should happen. The counter will - * always be reloaded with the value it is set to start counting from. The user - * can choose between three different reload actions, described in - * \ref asfdoc_sam0_tc_module_reload_act "the table below". - * - * \anchor asfdoc_sam0_tc_module_reload_act - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
TC Module Reload Actions
Reload actionDescription
\ref TC_RELOAD_ACTION_GCLK Reload TC counter value on next GCLK cycle. Leave prescaler - * as-is.
\ref TC_RELOAD_ACTION_PRESC Reloads TC counter value on next prescaler clock. Leave prescaler - * as-is.
\ref TC_RELOAD_ACTION_RESYNC Reload TC counter value on next GCLK cycle. Clear prescaler to - * zero.
- * - * The reload action to use will depend on the specific application being - * implemented. One example is when an external trigger for a reload occurs; if - * the TC uses the prescaler, the counter in the prescaler should not have a - * value between zero and the division factor. The TC counter and the counter - * in the prescaler should both start at zero. When the counter is set to - * re-trigger when it reaches the maximum value on the other hand, this is not the - * right option to use. In such a case it would be better if the prescaler is - * left unaltered when the re-trigger happens, letting the counter reset on the - * next GCLK cycle. - * - * \subsection asfdoc_sam0_tc_module_overview_compare_match Compare Match Operations - * In compare match operation, Compare/Capture registers are used in comparison - * with the counter value. When the timer's count value matches the value of a - * compare channel, a user defined action can be taken. - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_timer Basic Timer - * - * A Basic Timer is a simple application where compare match operations is used - * to determine when a specific period has elapsed. In Basic Timer operations, - * one or more values in the module's Compare/Capture registers are used to - * specify the time (as a number of prescaled GCLK cycles) when an action should - * be taken by the microcontroller. This can be an Interrupt Service Routine - * (ISR), event generator via the event system, or a software flag that is - * polled via the user application. - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_wg Waveform Generation - * - * Waveform generation enables the TC module to generate square waves, or if - * combined with an external passive low-pass filter; analog waveforms. - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_wg_pwm Waveform Generation - PWM - * - * Pulse width modulation is a form of waveform generation and a signalling - * technique that can be useful in many situations. When PWM mode is used, - * a digital pulse train with a configurable frequency and duty cycle can be - * generated by the TC module and output to a GPIO pin of the device. - * - * Often PWM is used to communicate a control or information parameter to an - * external circuit or component. Differing impedances of the source generator - * and sink receiver circuits is less of an issue when using PWM compared to - * using an analog voltage value, as noise will not generally affect the - * signal's integrity to a meaningful extent. - * - * \ref asfdoc_sam0_tc_module_pwm_normal_diag "The figure below" illustrates - * operations and different states of the counter and its output when running - * the counter in PWM normal mode. As can be seen, the TOP value is unchanged - * and is set to MAX. The compare match value is changed at several points to - * illustrate the resulting waveform output changes. The PWM output is set to - * normal (i.e. non-inverted) output mode. - * - * \anchor asfdoc_sam0_tc_module_pwm_normal_diag - * \image html pwm_normal_ex.svg "Example of PWM in Normal Mode, and Different Counter Operations" - * - * - * In \ref asfdoc_sam0_tc_module_pwm_match_diag "the figure below", the - * counter is set to generate PWM in Match mode. The PWM output is inverted via - * the appropriate configuration option in the TC driver configuration - * structure. In this example, the counter value is changed once, but the - * compare match value is kept unchanged. As can be seen, it is possible to - * change the TOP value when running in PWM match mode. - * - * \anchor asfdoc_sam0_tc_module_pwm_match_diag - * \image html pwm_match_ex.svg "Example of PWM in Match Mode, and Different Counter Operations" - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_wg_freq Waveform Generation - Frequency - * - * Frequency Generation mode is in many ways identical to PWM - * generation. However, in Frequency Generation a toggle only occurs - * on the output when a match on a capture channels occurs. When the - * match is made, the timer value is reset, resulting in a variable - * frequency square wave with a fixed 50% duty cycle. - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_capt Capture Operations - * - * In capture operations, any event from the event system or a pin change can - * trigger a capture of the counter value. This captured counter value can be - * used as a timestamp for the event, or it can be used in frequency and pulse - * width capture. - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_capt_event_capture Capture Operations - Event - * - * Event capture is a simple use of the capture functionality, - * designed to create timestamps for specific events. When the TC - * module's input capture pin is externally toggled, the current timer - * count value is copied into a buffered register which can then be - * read out by the user application. - * - * Note that when performing any capture operation, there is a risk that the - * counter reaches its top value (MAX) when counting up, or the bottom value - * (zero) when counting down, before the capture event occurs. This can distort - * the result, making event timestamps to appear shorter than reality; the - * user application should check for timer overflow when reading a capture - * result in order to detect this situation and perform an appropriate - * adjustment. - * - * Before checking for a new capture, \ref TC_STATUS_COUNT_OVERFLOW - * should be checked. The response to an overflow error is left to the user - * application, however it may be necessary to clear both the capture overflow - * flag and the capture flag upon each capture reading. - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_capt_pwc Capture Operations - Pulse Width - * - * Pulse Width Capture mode makes it possible to measure the pulse width and - * period of PWM signals. This mode uses two capture channels of the counter. - * This means that the counter module used for Pulse Width Capture can not be - * used for any other purpose. There are two modes for pulse width capture; - * Pulse Width Period (PWP) and Period Pulse Width (PPW). In PWP mode, capture - * channel 0 is used for storing the pulse width and capture channel 1 stores - * the observed period. While in PPW mode, the roles of the two capture channels - * is reversed. - * - * As in the above example it is necessary to poll on interrupt flags to see - * if a new capture has happened and check that a capture overflow error has - * not occurred. - * - * \subsection asfdoc_sam0_tc_module_overview_oneshot One-shot Mode - * - * TC modules can be configured into a one-shot mode. When configured in this - * manner, starting the timer will cause it to count until the next overflow - * or underflow condition before automatically halting, waiting to be manually - * triggered by the user application software or an event signal from the event - * system. - * - * \subsubsection asfdoc_sam0_tc_module_overview_inversion Wave Generation Output Inversion - * - * The output of the wave generation can be inverted by hardware if desired, - * resulting in the logically inverted value being output to the configured - * device GPIO pin. - * - * - * \section asfdoc_sam0_tc_special_considerations Special Considerations - * - * The number of capture compare registers in each TC module is dependent on - * the specific SAM device being used, and in some cases the counter size. - * - * The maximum amount of capture compare registers available in any SAM - * device is two when running in 32-bit mode and four in 8- and 16-bit modes. - * - * - * \section asfdoc_sam0_tc_extra_info Extra Information - * - * For extra information, see \ref asfdoc_sam0_tc_extra. This includes: - * - \ref asfdoc_sam0_tc_extra_acronyms - * - \ref asfdoc_sam0_tc_extra_dependencies - * - \ref asfdoc_sam0_tc_extra_errata - * - \ref asfdoc_sam0_tc_extra_history - * - * - * \section asfdoc_sam0_tc_examples Examples - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_tc_exqsg. - * - * \section asfdoc_sam0_tc_api_overview API Overview - * @{ - */ - -#include "compiler.h" -#include "clock.h" -#include "gclk.h" -#include "pinmux.h" - -// fix for Arduino zero -#if defined(__SAMD21G18A__) - #define SAMD21 1 - #define SAMD21G 1 - #define TC_ASYNC 1 -#endif - -// fix for Trinket/Gemma M0 -#if defined(__SAMD21E18A__) - #define SAMD21 1 - #define SAMD21E 1 - #define TC_ASYNC 1 -#endif - -/** - * Define port features set according to different device family - * @{ -*/ -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) || defined(__DOXYGEN__) -/** TC double buffered. */ -# define FEATURE_TC_DOUBLE_BUFFERED -/** SYNCBUSY scheme version 2. */ -# define FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2 -/** TC time stamp capture and pulse width capture. */ -# define FEATURE_TC_STAMP_PW_CAPTURE -/** Read synchronization of COUNT. */ -# define FEATURE_TC_READ_SYNC -/** IO pin edge capture. */ -# define FEATURE_TC_IO_CAPTURE -#endif - -#if (SAML21XXXB) || defined(__DOXYGEN__) -/** Generate DMA triggers*/ -# define FEATURE_TC_GENERATE_DMA_TRIGGER -#endif -/*@}*/ - -#if !defined(__DOXYGEN__) -#if SAMD20 || SAML21 || SAML22 || SAMC20 || SAMC21 -# define TC_INSTANCE_OFFSET 0 -#endif -#if SAMD21 || SAMR21 || SAMDA1 -# define TC_INSTANCE_OFFSET 3 -#endif -#if SAMD09 || SAMD10 || SAMD11 -# define TC_INSTANCE_OFFSET 1 -#endif - -#if SAMD20 -# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC0_CC8_NUM -#elif SAML21 || SAML22 || SAMC20 || SAMC21 -# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC0_CC_NUM -#elif SAMD09 || SAMD10 || SAMD11 -# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC1_CC8_NUM -#else -# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC3_CC8_NUM - /* Same number for 8-, 16- and 32-bit TC and all TC instances */ -#endif - -/** TC Instance MAX ID Number. */ -#if SAMD20E || SAMD21G || SAMD21E || SAMR21 -# if SAMD21GXXL -# define TC_INST_MAX_ID 7 -# else -# define TC_INST_MAX_ID 5 -# endif -#elif SAML21 || SAMC20 || SAMC21 -# define TC_INST_MAX_ID 4 -#elif SAML22 -# define TC_INST_MAX_ID 3 -#elif SAMD09 || SAMD10 || SAMD11 -# define TC_INST_MAX_ID 2 -#else -# define TC_INST_MAX_ID 7 -#endif - -#endif - -#if TC_ASYNC == true -# include "system_interrupt.h" -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#if TC_ASYNC == true -/** Enum for the possible callback types for the TC module. */ -enum tc_callback { - /** Callback for TC overflow. */ - TC_CALLBACK_OVERFLOW, - /** Callback for capture overflow error. */ - TC_CALLBACK_ERROR, - /** Callback for capture compare channel 0. */ - TC_CALLBACK_CC_CHANNEL0, - /** Callback for capture compare channel 1. */ - TC_CALLBACK_CC_CHANNEL1, -# if !defined(__DOXYGEN__) - /** Number of available callbacks. */ - TC_CALLBACK_N, -# endif -}; -#endif - -/** - * \name Module Status Flags - * - * TC status flags, returned by \ref tc_get_status() and cleared by - * \ref tc_clear_status(). - * - * @{ - */ - -/** Timer channel 0 has matched against its compare value, or has captured a - * new value. - */ -#define TC_STATUS_CHANNEL_0_MATCH (1UL << 0) - -/** Timer channel 1 has matched against its compare value, or has captured a - * new value. - */ -#define TC_STATUS_CHANNEL_1_MATCH (1UL << 1) - -/** Timer register synchronization has completed, and the synchronized count - * value may be read. - */ -#define TC_STATUS_SYNC_READY (1UL << 2) - -/** A new value was captured before the previous value was read, resulting in - * lost data. - */ -#define TC_STATUS_CAPTURE_OVERFLOW (1UL << 3) - -/** The timer count value has overflowed from its maximum value to its minimum - * when counting upward, or from its minimum value to its maximum when - * counting downward. - */ -#define TC_STATUS_COUNT_OVERFLOW (1UL << 4) - -#ifdef FEATURE_TC_DOUBLE_BUFFERED -/** Channel 0 compare or capture buffer valid. */ -#define TC_STATUS_CHN0_BUFFER_VALID (1UL << 5) -/** Channel 1 compare or capture buffer valid. */ -#define TC_STATUS_CHN1_BUFFER_VALID (1UL << 6) -/** Period buffer valid. */ -#define TC_STATUS_PERIOD_BUFFER_VALID (1UL << 7) -#endif -/** @} */ - -/** - * \brief Index of the compare capture channels. - * - * This enum is used to specify which capture/compare channel to do - * operations on. - */ -enum tc_compare_capture_channel { - /** Index of compare capture channel 0. */ - TC_COMPARE_CAPTURE_CHANNEL_0, - /** Index of compare capture channel 1. */ - TC_COMPARE_CAPTURE_CHANNEL_1, -}; - -/** TC wave generation mode. */ -#if SAML21 || SAML22 || SAMC20 || SAMC21 -#define TC_WAVE_GENERATION_NORMAL_FREQ_MODE TC_WAVE_WAVEGEN_NFRQ -#define TC_WAVE_GENERATION_MATCH_FREQ_MODE TC_WAVE_WAVEGEN_MFRQ -#define TC_WAVE_GENERATION_NORMAL_PWM_MODE TC_WAVE_WAVEGEN_NPWM -#define TC_WAVE_GENERATION_MATCH_PWM_MODE TC_WAVE_WAVEGEN_MPWM -#else -#define TC_WAVE_GENERATION_NORMAL_FREQ_MODE TC_CTRLA_WAVEGEN_NFRQ -#define TC_WAVE_GENERATION_MATCH_FREQ_MODE TC_CTRLA_WAVEGEN_MFRQ -#define TC_WAVE_GENERATION_NORMAL_PWM_MODE TC_CTRLA_WAVEGEN_NPWM -#define TC_WAVE_GENERATION_MATCH_PWM_MODE TC_CTRLA_WAVEGEN_MPWM -#endif - -/** - * \brief TC wave generation mode enum. - * - * This enum is used to select which mode to run the wave - * generation in. - * - */ -enum tc_wave_generation { - /** Top is maximum, except in 8-bit counter size where it is the PER - * register. - */ - TC_WAVE_GENERATION_NORMAL_FREQ = TC_WAVE_GENERATION_NORMAL_FREQ_MODE, - - /** Top is CC0, except in 8-bit counter size where it is the PER - * register. - */ - TC_WAVE_GENERATION_MATCH_FREQ = TC_WAVE_GENERATION_MATCH_FREQ_MODE, - - /** Top is maximum, except in 8-bit counter size where it is the PER - * register. - */ - TC_WAVE_GENERATION_NORMAL_PWM = TC_WAVE_GENERATION_NORMAL_PWM_MODE, - - /** Top is CC0, except in 8-bit counter size where it is the PER - * register. - */ - TC_WAVE_GENERATION_MATCH_PWM = TC_WAVE_GENERATION_MATCH_PWM_MODE, -}; - -/** - * \brief Specifies if the counter is 8-, 16-, or 32-bit. - * - * This enum specifies the maximum value it is possible to count to. - */ -enum tc_counter_size { - /** The counter's maximum value is 0xFF, the period register is - * available to be used as top value. - */ - TC_COUNTER_SIZE_8BIT = TC_CTRLA_MODE_COUNT8, - - /** The counter's maximum value is 0xFFFF. There is no separate - * period register, to modify top one of the capture compare - * registers has to be used. This limits the amount of - * available channels. - */ - TC_COUNTER_SIZE_16BIT = TC_CTRLA_MODE_COUNT16, - - /** The counter's maximum value is 0xFFFFFFFF. There is no separate - * period register, to modify top one of the capture compare - * registers has to be used. This limits the amount of - * available channels. - */ - TC_COUNTER_SIZE_32BIT = TC_CTRLA_MODE_COUNT32, -}; - -/** - * \brief TC Counter reload action enum. - * - * This enum specify how the counter and prescaler should reload. - */ -enum tc_reload_action { - /** The counter is reloaded/reset on the next GCLK and starts - * counting on the prescaler clock. - */ - TC_RELOAD_ACTION_GCLK = TC_CTRLA_PRESCSYNC_GCLK, - - /** The counter is reloaded/reset on the next prescaler clock. - */ - TC_RELOAD_ACTION_PRESC = TC_CTRLA_PRESCSYNC_PRESC, - - /** The counter is reloaded/reset on the next GCLK, and the - * prescaler is restarted as well. - */ - TC_RELOAD_ACTION_RESYNC = TC_CTRLA_PRESCSYNC_RESYNC, -}; - -/** - * \brief TC clock prescaler values. - * - * This enum is used to choose the clock prescaler - * configuration. The prescaler divides the clock frequency of the TC - * module to make the counter count slower. - */ -enum tc_clock_prescaler { - /** Divide clock by 1. */ - TC_CLOCK_PRESCALER_DIV1 = TC_CTRLA_PRESCALER(0), - /** Divide clock by 2. */ - TC_CLOCK_PRESCALER_DIV2 = TC_CTRLA_PRESCALER(1), - /** Divide clock by 4. */ - TC_CLOCK_PRESCALER_DIV4 = TC_CTRLA_PRESCALER(2), - /** Divide clock by 8. */ - TC_CLOCK_PRESCALER_DIV8 = TC_CTRLA_PRESCALER(3), - /** Divide clock by 16. */ - TC_CLOCK_PRESCALER_DIV16 = TC_CTRLA_PRESCALER(4), - /** Divide clock by 64. */ - TC_CLOCK_PRESCALER_DIV64 = TC_CTRLA_PRESCALER(5), - /** Divide clock by 256. */ - TC_CLOCK_PRESCALER_DIV256 = TC_CTRLA_PRESCALER(6), - /** Divide clock by 1024. */ - TC_CLOCK_PRESCALER_DIV1024 = TC_CTRLA_PRESCALER(7), -}; - -/** - * \brief TC module count direction. - * - * Timer/Counter count direction. - */ -enum tc_count_direction { - /** Timer should count upward from zero to MAX. */ - TC_COUNT_DIRECTION_UP, - - /** Timer should count downward to zero from MAX. */ - TC_COUNT_DIRECTION_DOWN, -}; - -/** Waveform inversion mode. */ -#if SAML21 || SAML22 || SAMC20 || SAMC21 -#define TC_WAVEFORM_INVERT_CC0_MODE TC_DRVCTRL_INVEN(1) -#define TC_WAVEFORM_INVERT_CC1_MODE TC_DRVCTRL_INVEN(2) -#else -#define TC_WAVEFORM_INVERT_CC0_MODE TC_CTRLC_INVEN(1) -#define TC_WAVEFORM_INVERT_CC1_MODE TC_CTRLC_INVEN(2) -#endif - -/** - * \brief Waveform inversion mode. - * - * Output waveform inversion mode. - */ -enum tc_waveform_invert_output { - /** No inversion of the waveform output. */ - TC_WAVEFORM_INVERT_OUTPUT_NONE = 0, - /** Invert output from compare channel 0. */ - TC_WAVEFORM_INVERT_OUTPUT_CHANNEL_0 = TC_WAVEFORM_INVERT_CC0_MODE, - /** Invert output from compare channel 1. */ - TC_WAVEFORM_INVERT_OUTPUT_CHANNEL_1 = TC_WAVEFORM_INVERT_CC1_MODE, -}; - -/** - * \brief Action to perform when the TC module is triggered by an event. - * - * Event action to perform when the module is triggered by an event. - */ -enum tc_event_action { - /** No event action. */ - TC_EVENT_ACTION_OFF = TC_EVCTRL_EVACT_OFF, - /** Re-trigger on event. */ - TC_EVENT_ACTION_RETRIGGER = TC_EVCTRL_EVACT_RETRIGGER, - /** Increment counter on event. */ - TC_EVENT_ACTION_INCREMENT_COUNTER = TC_EVCTRL_EVACT_COUNT, - /** Start counter on event. */ - TC_EVENT_ACTION_START = TC_EVCTRL_EVACT_START, - - /** Store period in capture register 0, pulse width in capture - * register 1. - */ - TC_EVENT_ACTION_PPW = TC_EVCTRL_EVACT_PPW, - - /** Store pulse width in capture register 0, period in capture - * register 1. - */ - TC_EVENT_ACTION_PWP = TC_EVCTRL_EVACT_PWP, -#ifdef FEATURE_TC_STAMP_PW_CAPTURE - /** Time stamp capture. */ - TC_EVENT_ACTION_STAMP = TC_EVCTRL_EVACT_STAMP, - /** Pulse width capture. */ - TC_EVENT_ACTION_PW = TC_EVCTRL_EVACT_PW, -#endif -}; - -/** - * \brief TC event enable/disable structure. - * - * Event flags for the \ref tc_enable_events() and \ref tc_disable_events(). - */ -struct tc_events { - /** Generate an output event on a compare channel match. */ - bool generate_event_on_compare_channel - [NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; - /** Generate an output event on counter overflow. */ - bool generate_event_on_overflow; - /** Perform the configured event action when an incoming event is signalled. */ - bool on_event_perform_action; - /** Specifies if the input event source is inverted, when used in PWP or - * PPW event action modes. - */ - bool invert_event_input; - /** Specifies which event to trigger if an event is triggered. */ - enum tc_event_action event_action; -}; - -/** - * \brief Configuration struct for TC module in 8-bit size counter mode. - */ -struct tc_8bit_config { - /** Initial timer count value. */ - uint8_t value; - /** Where to count to or from depending on the direction on the counter. */ - uint8_t period; - /** Value to be used for compare match on each channel. */ - uint8_t compare_capture_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; -}; - -/** - * \brief Configuration struct for TC module in 16-bit size counter mode. - */ -struct tc_16bit_config { - /** Initial timer count value. */ - uint16_t value; - /** Value to be used for compare match on each channel. */ - uint16_t compare_capture_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; -}; - -/** - * \brief Configuration struct for TC module in 32-bit size counter mode. - */ -struct tc_32bit_config { - /** Initial timer count value. */ - uint32_t value; - /** Value to be used for compare match on each channel. */ - uint32_t compare_capture_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; -}; - -/** - * \brief Configuration struct for TC module in 32-bit size counter mode. - */ -struct tc_pwm_channel { - /** When \c true, PWM output for the given channel is enabled. */ - bool enabled; - /** Specifies pin output for each channel. */ - uint32_t pin_out; - /** Specifies MUX setting for each output channel pin. */ - uint32_t pin_mux; -}; - -/** - * \brief TC configuration structure. - * - * Configuration struct for a TC instance. This structure should be - * initialized by the \ref tc_get_config_defaults function before being - * modified by the user application. - */ -struct tc_config { - /** GCLK generator used to clock the peripheral. */ - enum gclk_generator clock_source; - - /** When \c true the module is enabled during standby. */ - bool run_in_standby; -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) - /** Run on demand. */ - bool on_demand; -#endif - /** Specifies either 8-, 16-, or 32-bit counter size. */ - enum tc_counter_size counter_size; - /** Specifies the prescaler value for GCLK_TC. */ - enum tc_clock_prescaler clock_prescaler; - /** Specifies which waveform generation mode to use. */ - enum tc_wave_generation wave_generation; - - /** Specifies the reload or reset time of the counter and prescaler - * resynchronization on a re-trigger event for the TC. - */ - enum tc_reload_action reload_action; - - /** Specifies which channel(s) to invert the waveform on. - For SAM L21/L22/C20/C21, it's also used to invert IO input pin. */ - uint8_t waveform_invert_output; - - /** Specifies which channel(s) to enable channel capture - * operation on. - */ - bool enable_capture_on_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; -#ifdef FEATURE_TC_IO_CAPTURE - /** Specifies which channel(s) to enable I/O capture - * operation on. - */ - bool enable_capture_on_IO[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; -#endif - - /** When \c true, one-shot will stop the TC on next hardware or software - * re-trigger event or overflow/underflow. - */ - bool oneshot; - - /** Specifies the direction for the TC to count. */ - enum tc_count_direction count_direction; - - /** Specifies the PWM channel for TC. */ - struct tc_pwm_channel pwm_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; - - /** Access the different counter size settings though this configuration member. */ - union { - /** Struct for 8-bit specific timer configuration. */ - struct tc_8bit_config counter_8_bit; - /** Struct for 16-bit specific timer configuration. */ - struct tc_16bit_config counter_16_bit; - /** Struct for 32-bit specific timer configuration. */ - struct tc_32bit_config counter_32_bit; - }; - -#ifdef FEATURE_TC_DOUBLE_BUFFERED - /** Set to \c true to enable double buffering write. When enabled any write - * through \ref tc_set_top_value(), \ref tc_set_compare_value() and - * will direct to the buffer register as buffered - * value, and the buffered value will be committed to effective register - * on UPDATE condition, if update is not locked. - */ - bool double_buffering_enabled; -#endif -}; - -#if TC_ASYNC == true -/* Forward Declaration for the device instance. */ -struct tc_module; - -/* Type of the callback functions. */ -typedef void (*tc_callback_t)(struct tc_module *const module); -#endif - -/** - * \brief TC software device instance structure. - * - * TC software instance structure, used to retain software state information - * of an associated hardware module instance. - * - * \note The fields of this structure should not be altered by the user - * application; they are reserved for module-internal use only. - */ -struct tc_module { -#if !defined(__DOXYGEN__) - /** Hardware module pointer of the associated Timer/Counter peripheral. */ - Tc *hw; - - /** Size of the initialized Timer/Counter module configuration. */ - enum tc_counter_size counter_size; -# if TC_ASYNC == true - /** Array of callbacks. */ - tc_callback_t callback[TC_CALLBACK_N]; - /** Bit mask for callbacks registered. */ - uint8_t register_callback_mask; - /** Bit mask for callbacks enabled. */ - uint8_t enable_callback_mask; -# endif -#ifdef FEATURE_TC_DOUBLE_BUFFERED - /** Set to \c true to enable double buffering write. */ - bool double_buffering_enabled; -#endif -#endif -}; - -#if !defined(__DOXYGEN__) -uint8_t _tc_get_inst_index( - Tc *const hw); -#endif - -/** - * \name Driver Initialization and Configuration - * @{ - */ - -/** - * \brief Determines if the hardware module(s) are currently synchronizing to - *the bus. - * - * Checks to see if the underlying hardware peripheral module(s) are currently - * synchronizing across multiple clock domains to the hardware bus. This - * function can be used to delay further operations on a module until such time - * that it is ready, to prevent blocking delays for synchronization in the - * user application. - * - * \param[in] module_inst Pointer to the software module instance struct - * - * \return Synchronization status of the underlying hardware module(s). - * - * \retval false If the module has completed synchronization - * \retval true If the module synchronization is ongoing - */ -static inline bool tc_is_syncing( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) - return (tc_module->SYNCBUSY.reg); -#else - return (tc_module->STATUS.reg & TC_STATUS_SYNCBUSY); -#endif -} - -/** - * \brief Initializes config with predefined default values. - * - * This function will initialize a given TC configuration structure to - * a set of known default values. This function should be called on - * any new instance of the configuration structures before being - * modified by the user application. - * - * The default configuration is as follows: - * \li GCLK generator 0 (GCLK main) clock source - * \li 16-bit counter size on the counter - * \li No prescaler - * \li Normal frequency wave generation - * \li GCLK reload action - * \li Don't run in standby - * \li Don't run on demand for SAM L21/L22/C20/C21 - * \li No inversion of waveform output - * \li No capture enabled - * \li No I/O capture enabled for SAM L21/L22/C20/C21 - * \li No event input enabled - * \li Count upward - * \li Don't perform one-shot operations - * \li No event action - * \li No channel 0 PWM output - * \li No channel 1 PWM output - * \li Counter starts on 0 - * \li Capture compare channel 0 set to 0 - * \li Capture compare channel 1 set to 0 - * \li No PWM pin output enabled - * \li Pin and MUX configuration not set - * \li Double buffer disabled (if have this feature) - * - * \param[out] config Pointer to a TC module configuration structure to set - */ -static inline void tc_get_config_defaults( - struct tc_config *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Write default config to config struct */ - config->clock_source = GCLK_GENERATOR_0; - config->counter_size = TC_COUNTER_SIZE_16BIT; - config->clock_prescaler = TC_CLOCK_PRESCALER_DIV1; - config->wave_generation = TC_WAVE_GENERATION_NORMAL_FREQ; - config->reload_action = TC_RELOAD_ACTION_GCLK; - config->run_in_standby = false; -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) - config->on_demand = false; -#endif - config->waveform_invert_output = TC_WAVEFORM_INVERT_OUTPUT_NONE; - config->enable_capture_on_channel[TC_COMPARE_CAPTURE_CHANNEL_0] = false; - config->enable_capture_on_channel[TC_COMPARE_CAPTURE_CHANNEL_1] = false; -#ifdef FEATURE_TC_IO_CAPTURE - config->enable_capture_on_IO[TC_COMPARE_CAPTURE_CHANNEL_0] = false; - config->enable_capture_on_IO[TC_COMPARE_CAPTURE_CHANNEL_1] = false; -#endif - - config->count_direction = TC_COUNT_DIRECTION_UP; - config->oneshot = false; - - config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_0].enabled = false; - config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_0].pin_out = 0; - config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_0].pin_mux = 0; - - config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_1].enabled = false; - config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_1].pin_out = 0; - config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_1].pin_mux = 0; - - config->counter_16_bit.value = 0x0000; - config->counter_16_bit.compare_capture_channel\ - [TC_COMPARE_CAPTURE_CHANNEL_0] = 0x0000; - config->counter_16_bit.compare_capture_channel\ - [TC_COMPARE_CAPTURE_CHANNEL_1] = 0x0000; -#ifdef FEATURE_TC_DOUBLE_BUFFERED - config->double_buffering_enabled = false; -#endif - -} - -enum status_code tc_init( - struct tc_module *const module_inst, - Tc *const hw, - const struct tc_config *const config); - -/** @} */ - -/** - * \name Event Management - * @{ - */ - -/** - * \brief Enables a TC module event input or output. - * - * Enables one or more input or output events to or from the TC module. - * See \ref tc_events for a list of events this module supports. - * - * \note Events cannot be altered while the module is enabled. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] events Struct containing flags of events to enable - */ -static inline void tc_enable_events( - struct tc_module *const module_inst, - struct tc_events *const events) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - Assert(events); - - Tc *const tc_module = module_inst->hw; - - uint32_t event_mask = 0; - - if (events->invert_event_input == true) { - event_mask |= TC_EVCTRL_TCINV; - } - - if (events->on_event_perform_action == true) { - event_mask |= TC_EVCTRL_TCEI; - } - - if (events->generate_event_on_overflow == true) { - event_mask |= TC_EVCTRL_OVFEO; - } - - for (uint8_t i = 0; i < NUMBER_OF_COMPARE_CAPTURE_CHANNELS; i++) { - if (events->generate_event_on_compare_channel[i] == true) { - event_mask |= (TC_EVCTRL_MCEO(1) << i); - } - } - - tc_module->COUNT8.EVCTRL.reg |= event_mask | events->event_action; -} - -/** - * \brief Disables a TC module event input or output. - * - * Disables one or more input or output events to or from the TC module. - * See \ref tc_events for a list of events this module supports. - * - * \note Events cannot be altered while the module is enabled. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] events Struct containing flags of events to disable - */ -static inline void tc_disable_events( - struct tc_module *const module_inst, - struct tc_events *const events) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - Assert(events); - - Tc *const tc_module = module_inst->hw; - - uint32_t event_mask = 0; - - if (events->invert_event_input == true) { - event_mask |= TC_EVCTRL_TCINV; - } - - if (events->on_event_perform_action == true) { - event_mask |= TC_EVCTRL_TCEI; - } - - if (events->generate_event_on_overflow == true) { - event_mask |= TC_EVCTRL_OVFEO; - } - - for (uint8_t i = 0; i < NUMBER_OF_COMPARE_CAPTURE_CHANNELS; i++) { - if (events->generate_event_on_compare_channel[i] == true) { - event_mask |= (TC_EVCTRL_MCEO(1) << i); - } - } - - tc_module->COUNT8.EVCTRL.reg &= ~event_mask; -} - -/** @} */ - -/** - * \name Enable/Disable/Reset - * @{ - */ - -enum status_code tc_reset( - const struct tc_module *const module_inst); - -/** - * \brief Enable the TC module. - * - * Enables a TC module that has been previously initialized. The counter will - * start when the counter is enabled. - * - * \note When the counter is configured to re-trigger on an event, the counter - * will not start until the start function is used. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_enable( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Enable TC module */ - tc_module->CTRLA.reg |= TC_CTRLA_ENABLE; -} - -/** - * \brief Disables the TC module. - * - * Disables a TC module and stops the counter. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_disable( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Disable TC module */ - tc_module->CTRLA.reg &= ~TC_CTRLA_ENABLE; -} - -/** @} */ - -/** - * \name Get/Set Count Value - * @{ - */ - -uint32_t tc_get_count_value( - const struct tc_module *const module_inst); - -enum status_code tc_set_count_value( - const struct tc_module *const module_inst, - const uint32_t count); - -/** @} */ - -/** - * \name Start/Stop Counter - * @{ - */ - -/** - * \brief Stops the counter. - * - * This function will stop the counter. When the counter is stopped - * the value in the count value is set to 0 if the counter was - * counting up, or maximum if the counter was counting - * down when stopped. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_stop_counter( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Write command to execute */ - tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_STOP_Val); -} - -/** - * \brief Starts the counter. - * - * Starts or restarts an initialized TC module's counter. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_start_counter( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Make certain that there are no conflicting commands in the register */ - tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Write command to execute */ - tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_RETRIGGER_Val); -} - -/** @} */ - -#ifdef FEATURE_TC_DOUBLE_BUFFERED -/** - * \name Double Buffering - * @{ - */ - -/** - * \brief Update double buffer. - * - * Update double buffer. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_update_double_buffer( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Make certain that there are no conflicting commands in the register */ - tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Write command to execute */ - tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_UPDATE_Val); -} -/** @} */ -#endif - -#ifdef FEATURE_TC_READ_SYNC -/** - * \name Count Read Synchronization - * @{ - */ - -/** - * \brief Read synchronization of COUNT. - * - * Read synchronization of COUNT. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_sync_read_count( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Make certain that there are no conflicting commands in the register */ - tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Write command to execute */ - tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_READSYNC_Val); -} -/** @} */ -#endif - -#ifdef FEATURE_TC_GENERATE_DMA_TRIGGER -/** - * \name Generate TC DMA Triggers command - * @{ - */ - -/** - * \brief TC DMA Trigger. - * - * TC DMA trigger command. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_dma_trigger_command( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Make certain that there are no conflicting commands in the register */ - tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - -#if (SAMC20) || (SAMC21) || (SAML22) || (SAML21XXXB) - /* Write command to execute */ - tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_DMAOS_Val); -#endif -} -/** @} */ -#endif - -/** - * \name Get Capture Set Compare - * @{ - */ - -uint32_t tc_get_capture_value( - const struct tc_module *const module_inst, - const enum tc_compare_capture_channel channel_index); - -enum status_code tc_set_compare_value( - const struct tc_module *const module_inst, - const enum tc_compare_capture_channel channel_index, - const uint32_t compare_value); - -/** @} */ - -/** - * \name Set Top Value - * @{ - */ - -enum status_code tc_set_top_value( - const struct tc_module *const module_inst, - const uint32_t top_value); - -/** @} */ - -/** - * \name Status Management - * @{ - */ - -/** - * \brief Retrieves the current module status. - * - * Retrieves the status of the module, giving overall state information. - * - * \param[in] module_inst Pointer to the TC software instance struct - * - * \return Bitmask of \c TC_STATUS_* flags. - * - * \retval TC_STATUS_CHANNEL_0_MATCH Timer channel 0 compare/capture match - * \retval TC_STATUS_CHANNEL_1_MATCH Timer channel 1 compare/capture match - * \retval TC_STATUS_SYNC_READY Timer read synchronization has completed - * \retval TC_STATUS_CAPTURE_OVERFLOW Timer capture data has overflowed - * \retval TC_STATUS_COUNT_OVERFLOW Timer count value has overflowed - * \retval TC_STATUS_CHN0_BUFFER_VALID Timer count channel 0 compare/capture buffer valid - * \retval TC_STATUS_CHN1_BUFFER_VALID Timer count channel 1 compare/capture buffer valid - * \retval TC_STATUS_PERIOD_BUFFER_VALID Timer count period buffer valid - */ -static inline uint32_t tc_get_status( - struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - uint32_t int_flags = tc_module->INTFLAG.reg; - - uint32_t status_flags = 0; - - /* Check for TC channel 0 match */ - if (int_flags & TC_INTFLAG_MC(1)) { - status_flags |= TC_STATUS_CHANNEL_0_MATCH; - } - - /* Check for TC channel 1 match */ - if (int_flags & TC_INTFLAG_MC(2)) { - status_flags |= TC_STATUS_CHANNEL_1_MATCH; - } - -#if !defined(FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2) - /* Check for TC read synchronization ready */ - if (int_flags & TC_INTFLAG_SYNCRDY) { - status_flags |= TC_STATUS_SYNC_READY; - } -#endif - - /* Check for TC capture overflow */ - if (int_flags & TC_INTFLAG_ERR) { - status_flags |= TC_STATUS_CAPTURE_OVERFLOW; - } - - /* Check for TC count overflow */ - if (int_flags & TC_INTFLAG_OVF) { - status_flags |= TC_STATUS_COUNT_OVERFLOW; - } -#ifdef FEATURE_TC_DOUBLE_BUFFERED - uint8_t double_buffer_valid_status = tc_module->STATUS.reg; - - /* Check channel 0 compare or capture buffer valid */ - if (double_buffer_valid_status & TC_STATUS_CCBUFV0) { - status_flags |= TC_STATUS_CHN0_BUFFER_VALID; - } - /* Check channel 0 compare or capture buffer valid */ - if (double_buffer_valid_status & TC_STATUS_CCBUFV1) { - status_flags |= TC_STATUS_CHN1_BUFFER_VALID; - } - /* Check period buffer valid */ - if (double_buffer_valid_status & TC_STATUS_PERBUFV) { - status_flags |= TC_STATUS_PERIOD_BUFFER_VALID; - } -#endif - - return status_flags; -} - -/** - * \brief Clears a module status flag. - * - * Clears the given status flag of the module. - * - * \param[in] module_inst Pointer to the TC software instance struct - * \param[in] status_flags Bitmask of \c TC_STATUS_* flags to clear - */ -static inline void tc_clear_status( - struct tc_module *const module_inst, - const uint32_t status_flags) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - uint32_t int_flags = 0; - - /* Check for TC channel 0 match */ - if (status_flags & TC_STATUS_CHANNEL_0_MATCH) { - int_flags |= TC_INTFLAG_MC(1); - } - - /* Check for TC channel 1 match */ - if (status_flags & TC_STATUS_CHANNEL_1_MATCH) { - int_flags |= TC_INTFLAG_MC(2); - } - -#if !defined(FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2) - /* Check for TC read synchronization ready */ - if (status_flags & TC_STATUS_SYNC_READY) { - int_flags |= TC_INTFLAG_SYNCRDY; - } -#endif - - /* Check for TC capture overflow */ - if (status_flags & TC_STATUS_CAPTURE_OVERFLOW) { - int_flags |= TC_INTFLAG_ERR; - } - - /* Check for TC count overflow */ - if (status_flags & TC_STATUS_COUNT_OVERFLOW) { - int_flags |= TC_INTFLAG_OVF; - } - - /* Clear interrupt flag */ - tc_module->INTFLAG.reg = int_flags; -} - -/** @} */ - -/** @} */ - -#ifdef __cplusplus -} -#endif - -/** - * \page asfdoc_sam0_tc_extra Extra Information for TC Driver - * - * \section asfdoc_sam0_tc_extra_acronyms Acronyms - * The table below presents the acronyms used in this module: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
AcronymDescription
DMADirect Memory Access
TCTimer Counter
PWMPulse Width Modulation
PWPPulse Width Period
PPWPeriod Pulse Width
- * - * - * \section asfdoc_sam0_tc_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - \ref asfdoc_sam0_system_pinmux_group "System Pin Multiplexer Driver" - * - * - * \section asfdoc_sam0_tc_extra_errata Errata - * There are no errata related to this driver. - * - * - * \section asfdoc_sam0_tc_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Changelog
Added support for SAMD21 and do some modifications as below: - * \li Clean up in the configuration structure, the counter size - * setting specific registers is accessed through the counter_8_bit, - * counter_16_bit and counter_32_bit structures - * \li All event related settings moved into the tc_event structure
Added automatic digital clock interface enable for the slave TC - * module when a timer is initialized in 32-bit mode
Initial Release
- */ - -/** - * \page asfdoc_sam0_tc_exqsg Examples for TC Driver - * - * This is a list of the available Quick Start guides (QSGs) and example - * applications for \ref asfdoc_sam0_tc_group. QSGs are simple examples with - * step-by-step instructions to configure and use this driver in a selection of - * use cases. Note that QSGs can be compiled as a standalone application or be - * added to the user application. - * - * - \subpage asfdoc_sam0_tc_basic_use_case - * - \subpage asfdoc_sam0_tc_macth_freq_use_case - * \if TC_CALLBACK_MODE - * - \subpage asfdoc_sam0_tc_timer_use_case - * - \subpage asfdoc_sam0_tc_callback_use_case - * \endif - * - \subpage asfdoc_sam0_tc_dma_use_case - * - * \page asfdoc_sam0_tc_document_revision_history Document Revision History - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Doc. Rev. - * Date - * Comments - *
F08/2015Added support for SAM C21 and SAM L22
E04/2015Added support for SAM L21 and SAM DA1
D12/2014Added timer use case. - * Added support for SAM R21 and SAM D10/D11
C01/2014Added support for SAM D21
B06/2013Corrected documentation typos
A06/2013Initial release
- */ - -#endif /* TC_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/tc_interrupt.c b/feather_sensor_lte/libraries/Adafruit_ASFcore/tc_interrupt.c deleted file mode 100644 index 032be2f..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/tc_interrupt.c +++ /dev/null @@ -1,199 +0,0 @@ -/** - * \file - * - * \brief SAM TC - Timer Counter Callback Driver - * - * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/* - * Support and FAQ: visit Atmel Support - */ - -#include "tc_interrupt.h" - -void *_tc_instances[TC_INST_NUM]; - -void _tc_interrupt_handler(uint8_t instance); - -/** - * \brief Registers a callback. - * - * Registers a callback function which is implemented by the user. - * - * \note The callback must be enabled by \ref tc_enable_callback, - * in order for the interrupt handler to call it when the conditions for the - * callback type is met. - * - * \param[in] module Pointer to TC software instance struct - * \param[in] callback_func Pointer to callback function - * \param[in] callback_type Callback type given by an enum - */ -enum status_code tc_register_callback( - struct tc_module *const module, - tc_callback_t callback_func, - const enum tc_callback callback_type) -{ - /* Sanity check arguments */ - Assert(module); - Assert(callback_func); - - /* Register callback function */ - module->callback[callback_type] = callback_func; - - /* Set the bit corresponding to the callback_type */ - if (callback_type == TC_CALLBACK_CC_CHANNEL0) { - module->register_callback_mask |= TC_INTFLAG_MC(1); - } - else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { - module->register_callback_mask |= TC_INTFLAG_MC(2); - } - else { - module->register_callback_mask |= (1 << callback_type); - } - return STATUS_OK; -} - -/** - * \brief Unregisters a callback. - * - * Unregisters a callback function implemented by the user. The callback should be - * disabled before it is unregistered. - * - * \param[in] module Pointer to TC software instance struct - * \param[in] callback_type Callback type given by an enum - */ -enum status_code tc_unregister_callback( - struct tc_module *const module, - const enum tc_callback callback_type) -{ - /* Sanity check arguments */ - Assert(module); - - /* Unregister callback function */ - module->callback[callback_type] = NULL; - - /* Clear the bit corresponding to the callback_type */ - if (callback_type == TC_CALLBACK_CC_CHANNEL0) { - module->register_callback_mask &= ~TC_INTFLAG_MC(1); - } - else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { - module->register_callback_mask &= ~TC_INTFLAG_MC(2); - } - else { - module->register_callback_mask &= ~(1 << callback_type); - } - return STATUS_OK; -} - -/** - * \internal ISR handler for TC - * - * Auto-generate a set of interrupt handlers for each TC in the device. - */ -#define _TC_INTERRUPT_HANDLER(n, m) \ - void TC##n##_Handler(void) \ - { \ - _tc_interrupt_handler(m); \ - } - -#if (SAML21E) || (SAML21G) - _TC_INTERRUPT_HANDLER(0,0) - _TC_INTERRUPT_HANDLER(1,1) - _TC_INTERRUPT_HANDLER(4,2) -#else - MRECURSION(TC_INST_NUM, _TC_INTERRUPT_HANDLER, TC_INST_MAX_ID) -#endif - - -/** - * \internal Interrupt Handler for TC module - * - * Handles interrupts as they occur, it will run the callback functions - * that are registered and enabled. - * - * \param[in] instance ID of the TC instance calling the interrupt - * handler. - */ -void _tc_interrupt_handler( - uint8_t instance) -{ - /* Temporary variable */ - uint8_t interrupt_and_callback_status_mask; - - /* Get device instance from the look-up table */ - struct tc_module *module - = (struct tc_module *)_tc_instances[instance]; - - /* Read and mask interrupt flag register */ - interrupt_and_callback_status_mask = module->hw->COUNT8.INTFLAG.reg & - module->register_callback_mask & - module->enable_callback_mask; - - /* Check if an Overflow interrupt has occurred */ - if (interrupt_and_callback_status_mask & TC_INTFLAG_OVF) { - /* Invoke registered and enabled callback function */ - (module->callback[TC_CALLBACK_OVERFLOW])(module); - /* Clear interrupt flag */ - module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_OVF; - } - - /* Check if an Error interrupt has occurred */ - if (interrupt_and_callback_status_mask & TC_INTFLAG_ERR) { - /* Invoke registered and enabled callback function */ - (module->callback[TC_CALLBACK_ERROR])(module); - /* Clear interrupt flag */ - module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_ERR; - } - - /* Check if an Match/Capture Channel 0 interrupt has occurred */ - if (interrupt_and_callback_status_mask & TC_INTFLAG_MC(1)) { - /* Invoke registered and enabled callback function */ - (module->callback[TC_CALLBACK_CC_CHANNEL0])(module); - /* Clear interrupt flag */ - module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_MC(1); - } - - /* Check if an Match/Capture Channel 1 interrupt has occurred */ - if (interrupt_and_callback_status_mask & TC_INTFLAG_MC(2)) { - /* Invoke registered and enabled callback function */ - (module->callback[TC_CALLBACK_CC_CHANNEL1])(module); - /* Clear interrupt flag */ - module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_MC(2); - } -} diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/tc_interrupt.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/tc_interrupt.h deleted file mode 100644 index 4e1fd8e..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/tc_interrupt.h +++ /dev/null @@ -1,179 +0,0 @@ -/** - * \file - * - * \brief SAM TC - Timer Counter Callback Driver - * - * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/* - * Support and FAQ: visit Atmel Support - */ - -#ifndef TC_INTERRUPT_H_INCLUDED -#define TC_INTERRUPT_H_INCLUDED - -#include "tc.h" -#include "system_interrupt.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#if !defined(__DOXYGEN__) -extern void *_tc_instances[TC_INST_NUM]; - -# define _TC_INTERRUPT_VECT_NUM(n, unused) \ - SYSTEM_INTERRUPT_MODULE_TC##n, -/** - * \internal Get the interrupt vector for the given device instance - * - * \param[in] TC module instance number. - * - * \return Interrupt vector for of the given TC module instance. - */ -static enum system_interrupt_vector _tc_interrupt_get_interrupt_vector( - uint32_t inst_num) -{ - static uint8_t tc_interrupt_vectors[TC_INST_NUM] = - { -#if (SAML21E) || (SAML21G) - SYSTEM_INTERRUPT_MODULE_TC0, - SYSTEM_INTERRUPT_MODULE_TC1, - SYSTEM_INTERRUPT_MODULE_TC4 -#else - MRECURSION(TC_INST_NUM, _TC_INTERRUPT_VECT_NUM, TC_INST_MAX_ID) -#endif - }; - - return (enum system_interrupt_vector)tc_interrupt_vectors[inst_num]; -} -#endif /* !defined(__DOXYGEN__) */ - -/** - * \name Callback Management - * {@ - */ - -enum status_code tc_register_callback( - struct tc_module *const module, - tc_callback_t callback_func, - const enum tc_callback callback_type); - -enum status_code tc_unregister_callback( - struct tc_module *const module, - const enum tc_callback callback_type); - -/** - * \brief Enables callback. - * - * Enables the callback function registered by the \ref - * tc_register_callback. The callback function will be called from the - * interrupt handler when the conditions for the callback type are - * met. This function will also enable the appropriate interrupts. - * - * \param[in] module Pointer to TC software instance struct - * \param[in] callback_type Callback type given by an enum - */ -static inline void tc_enable_callback( - struct tc_module *const module, - const enum tc_callback callback_type) -{ - /* Sanity check arguments */ - Assert(module); - - - /* Enable interrupts for this TC module */ - system_interrupt_enable(_tc_interrupt_get_interrupt_vector(_tc_get_inst_index(module->hw))); - - /* Enable callback */ - if (callback_type == TC_CALLBACK_CC_CHANNEL0) { - module->enable_callback_mask |= TC_INTFLAG_MC(1); - module->hw->COUNT8.INTENSET.reg = TC_INTFLAG_MC(1); - } - else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { - module->enable_callback_mask |= TC_INTFLAG_MC(2); - module->hw->COUNT8.INTENSET.reg = TC_INTFLAG_MC(2); - } - else { - module->enable_callback_mask |= (1 << callback_type); - module->hw->COUNT8.INTENSET.reg = (1 << callback_type); - } -} - -/** - * \brief Disables callback. - * - * Disables the callback function registered by the \ref - * tc_register_callback, and the callback will not be called from the - * interrupt routine. The function will also disable the appropriate - * interrupts. - * - * \param[in] module Pointer to TC software instance struct - * \param[in] callback_type Callback type given by an enum - */ -static inline void tc_disable_callback( - struct tc_module *const module, - const enum tc_callback callback_type){ - /* Sanity check arguments */ - Assert(module); - - /* Disable callback */ - if (callback_type == TC_CALLBACK_CC_CHANNEL0) { - module->hw->COUNT8.INTENCLR.reg = TC_INTFLAG_MC(1); - module->enable_callback_mask &= ~TC_INTFLAG_MC(1); - } - else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { - module->hw->COUNT8.INTENCLR.reg = TC_INTFLAG_MC(2); - module->enable_callback_mask &= ~TC_INTFLAG_MC(2); - } - else { - module->hw->COUNT8.INTENCLR.reg = (1 << callback_type); - module->enable_callback_mask &= ~(1 << callback_type); - } -} - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* TC_INTERRUPT_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/wdt.c b/feather_sensor_lte/libraries/Adafruit_ASFcore/wdt.c deleted file mode 100644 index c5b0895..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/wdt.c +++ /dev/null @@ -1,264 +0,0 @@ -/** - * \file - * - * \brief SAM Watchdog Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#include "wdt.h" -#include - -/** - * \brief Sets up the WDT hardware module based on the configuration. - * - * Writes a given configuration of a WDT configuration to the - * hardware module, and initializes the internal device struct. - * - * \param[in] config Pointer to the configuration struct - * - * \return Status of the configuration procedure. - * - * \retval STATUS_OK If the module was configured correctly - * \retval STATUS_ERR_INVALID_ARG If invalid argument(s) were supplied - * \retval STATUS_ERR_IO If the Watchdog module is locked to be always on - */ -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) -enum status_code wdt_set_config( - const struct wdt_conf *const config) -{ - /* Sanity check arguments */ - Assert(config); - - Wdt *const WDT_module = WDT; - - /* Turn on the digital interface clock */ - system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBA, MCLK_APBAMASK_WDT); - - /* Check of the Watchdog has been locked to be always on, if so, abort */ - if (wdt_is_locked()) { - return STATUS_ERR_IO; - } - - /* Check for an invalid timeout period, abort if found */ - if (config->timeout_period == WDT_PERIOD_NONE) { - return STATUS_ERR_INVALID_ARG; - } - - /* Make sure the Window and Early Warning periods are not more than the - * reset period, abort if either is invalid */ - if ((config->timeout_period < config->window_period) || - (config->timeout_period < config->early_warning_period)) { - return STATUS_ERR_INVALID_ARG; - } - - /* Disable the Watchdog module */ - WDT_module->CTRLA.reg &= ~WDT_CTRLA_ENABLE; - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - if(config->enable == false) { - return STATUS_OK; - } - - uint32_t new_config = 0; - - /* Update the timeout period value with the requested period */ - new_config |= (config->timeout_period - 1) << WDT_CONFIG_PER_Pos; - - /* Check if the user has requested a reset window period */ - if (config->window_period != WDT_PERIOD_NONE) { - WDT_module->CTRLA.reg |= WDT_CTRLA_WEN; - - /* Update and enable the timeout period value */ - new_config |= (config->window_period - 1) << WDT_CONFIG_WINDOW_Pos; - } else { - /* Ensure the window enable control flag is cleared */ - WDT_module->CTRLA.reg &= ~WDT_CTRLA_WEN; - } - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - /* Write the new Watchdog configuration */ - WDT_module->CONFIG.reg = new_config; - - /* Check if the user has requested an early warning period */ - if (config->early_warning_period != WDT_PERIOD_NONE) { - /* Set the Early Warning period */ - WDT_module->EWCTRL.reg - = (config->early_warning_period - 1) << WDT_EWCTRL_EWOFFSET_Pos; - } - - /* Either enable or lock-enable the Watchdog timer depending on the user - * settings */ - if (config->always_on) { - WDT_module->CTRLA.reg |= WDT_CTRLA_ALWAYSON; - } else { - WDT_module->CTRLA.reg |= WDT_CTRLA_ENABLE; - } - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - return STATUS_OK; -} -#else -enum status_code wdt_set_config( - const struct wdt_conf *const config) -{ - /* Sanity check arguments */ - Assert(config); - - Wdt *const WDT_module = WDT; - - /* Turn on the digital interface clock */ - system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBA, PM_APBAMASK_WDT); - - /* Check of the Watchdog has been locked to be always on, if so, abort */ - if (wdt_is_locked()) { - return STATUS_ERR_IO; - } - - /* Check for an invalid timeout period, abort if found */ - if (config->timeout_period == WDT_PERIOD_NONE) { - return STATUS_ERR_INVALID_ARG; - } - - /* Make sure the Window and Early Warning periods are not more than the - * reset period, abort if either is invalid */ - if ((config->timeout_period < config->window_period) || - (config->timeout_period < config->early_warning_period)) { - return STATUS_ERR_INVALID_ARG; - } - - /* Disable the Watchdog module */ - WDT_module->CTRL.reg &= ~WDT_CTRL_ENABLE; - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - if(config->enable == false) { - return STATUS_OK; - } - - /* Configure GCLK channel and enable clock */ - struct system_gclk_chan_config gclk_chan_conf; - gclk_chan_conf.source_generator = config->clock_source; - system_gclk_chan_set_config(WDT_GCLK_ID, &gclk_chan_conf); - system_gclk_chan_enable(WDT_GCLK_ID); - if (config->always_on) { - system_gclk_chan_lock(WDT_GCLK_ID); - } - - uint32_t new_config = 0; - - /* Update the timeout period value with the requested period */ - new_config |= (config->timeout_period - 1) << WDT_CONFIG_PER_Pos; - - /* Check if the user has requested a reset window period */ - if (config->window_period != WDT_PERIOD_NONE) { - WDT_module->CTRL.reg |= WDT_CTRL_WEN; - - /* Update and enable the timeout period value */ - new_config |= (config->window_period - 1) << WDT_CONFIG_WINDOW_Pos; - } else { - /* Ensure the window enable control flag is cleared */ - WDT_module->CTRL.reg &= ~WDT_CTRL_WEN; - } - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - /* Write the new Watchdog configuration */ - WDT_module->CONFIG.reg = new_config; - - /* Check if the user has requested an early warning period */ - if (config->early_warning_period != WDT_PERIOD_NONE) { - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - /* Set the Early Warning period */ - WDT_module->EWCTRL.reg - = (config->early_warning_period - 1) << WDT_EWCTRL_EWOFFSET_Pos; - } - - /* Either enable or lock-enable the Watchdog timer depending on the user - * settings */ - if (config->always_on) { - WDT_module->CTRL.reg |= WDT_CTRL_ALWAYSON; - } else { - WDT_module->CTRL.reg |= WDT_CTRL_ENABLE; - } - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - return STATUS_OK; -} -#endif - -/** - * \brief Resets the count of the running Watchdog Timer that was previously enabled. - * - * Resets the current count of the Watchdog Timer, restarting the timeout - * period count elapsed. This function should be called after the window - * period (if one was set in the module configuration) but before the timeout - * period to prevent a reset of the system. - */ -void wdt_reset_count(void) -{ - Wdt *const WDT_module = WDT; - - /* Disable the Watchdog module */ - WDT_module->CLEAR.reg = WDT_CLEAR_CLEAR_KEY; - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } -} diff --git a/feather_sensor_lte/libraries/Adafruit_ASFcore/wdt.h b/feather_sensor_lte/libraries/Adafruit_ASFcore/wdt.h deleted file mode 100644 index c4c37cf..0000000 --- a/feather_sensor_lte/libraries/Adafruit_ASFcore/wdt.h +++ /dev/null @@ -1,501 +0,0 @@ -/** - * \file - * - * \brief SAM Watchdog Driver - * - * Copyright (c) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef WDT_H_INCLUDED -#define WDT_H_INCLUDED - -/** - * \defgroup asfdoc_sam0_wdt_group SAM Watchdog Driver (WDT) - * - * This driver for Atmel® | SMART SAM devices provides an interface for the configuration - * and management of the device's Watchdog Timer module, including the enabling, - * disabling, and kicking within the device. The following driver API modes are - * covered by this manual: - * - * - Polled APIs - * \if WDT_CALLBACK_MODE - * - Callback APIs - * \endif - * - * The following peripherals are used by this module: - * - WDT (Watchdog Timer) - * - * The following devices can use this module: - * - Atmel | SMART SAM D20/D21 - * - Atmel | SMART SAM R21 - * - Atmel | SMART SAM D09/D10/D11 - * - Atmel | SMART SAM L21/L22 - * - Atmel | SMART SAM DA1 - * - Atmel | SMART SAM C20/C21 - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_wdt_prerequisites - * - \ref asfdoc_sam0_wdt_module_overview - * - \ref asfdoc_sam0_wdt_special_considerations - * - \ref asfdoc_sam0_wdt_extra_info - * - \ref asfdoc_sam0_wdt_examples - * - \ref asfdoc_sam0_wdt_api_overview - * - * - * \section asfdoc_sam0_wdt_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * - * \section asfdoc_sam0_wdt_module_overview Module Overview - * - * The Watchdog module (WDT) is designed to give an added level of safety in - * critical systems, to ensure a system reset is triggered in the case of a - * deadlock or other software malfunction that prevents normal device operation. - * - * At a basic level, the Watchdog is a system timer with a fixed period; once - * enabled, it will continue to count ticks of its asynchronous clock until - * it is periodically reset, or the timeout period is reached. In the event of a - * Watchdog timeout, the module will trigger a system reset identical to a pulse - * of the device's reset pin, resetting all peripherals to their power-on - * default states and restarting the application software from the reset vector. - * - * In many systems, there is an obvious upper bound to the amount of time each - * iteration of the main application loop can be expected to run, before a - * malfunction can be assumed (either due to a deadlock waiting on hardware or - * software, or due to other means). When the Watchdog is configured with a - * timeout period equal to this upper bound, a malfunction in the system will - * force a full system reset to allow for a graceful recovery. - * - * \subsection asfdoc_sam0_wdt_module_locked_mode Locked Mode - * The Watchdog configuration can be set in the device fuses and locked in - * hardware, so that no software changes can be made to the Watchdog - * configuration. Additionally, the Watchdog can be locked on in software if it - * is not already locked, so that the module configuration cannot be modified - * until a power on reset of the device. - * - * The locked configuration can be used to ensure that faulty software does not - * cause the Watchdog configuration to be changed, preserving the level of - * safety given by the module. - * - * \subsection asfdoc_sam0_wdt_module_window_mode Window Mode - * Just as there is a reasonable upper bound to the time the main program loop - * should take for each iteration, there is also in many applications a lower - * bound, i.e. a \a minimum time for which each loop iteration should run for - * under normal circumstances. To guard against a system failure resetting the - * Watchdog in a tight loop (or a failure in the system application causing the - * main loop to run faster than expected) a "Window" mode can be enabled to - * disallow resetting of the Watchdog counter before a certain period of time. - * If the Watchdog is not reset \a after the window opens but not \a before the - * Watchdog expires, the system will reset. - * - * \subsection asfdoc_sam0_wdt_module_early_warning Early Warning - * In some cases it is desirable to receive an early warning that the Watchdog is - * about to expire, so that some system action (such as saving any system - * configuration data for failure analysis purposes) can be performed before the - * system reset occurs. The Early Warning feature of the Watchdog module allows - * such a notification to be requested; after the configured early warning time - * (but before the expiry of the Watchdog counter) the Early Warning flag will - * become set, so that the user application can take an appropriate action. - * - * \note It is important to note that the purpose of the Early Warning feature - * is \a not to allow the user application to reset the Watchdog; doing - * so will defeat the safety the module gives to the user application. - * Instead, this feature should be used purely to perform any tasks that - * need to be undertaken before the system reset occurs. - * - * \subsection asfdoc_sam0_wdt_module_overview_physical Physical Connection - * - * \ref asfdoc_sam0_wdt_module_int_connections "The figure below" shows how - * this module is interconnected within the device. - * - * \anchor asfdoc_sam0_wdt_module_int_connections - * \dot - * digraph overview { - * rankdir=LR; - * node [label="GCLK*\nGeneric Clock" shape=square] wdt_clock; - * - * subgraph driver { - * node [label=" WDT | Watchdog Counter" shape=record] wdt_module; - * node [label="System Reset Logic" shape=ellipse style=filled fillcolor=lightgray] sys_reset; - * } - * - * wdt_clock -> wdt_module:f1; - * wdt_module:f1 -> sys_reset; - * } - * \enddot - * - * \note Watchdog Counter of SAM L21/L22 is \a not provided by GCLK, but it uses an - * internal 1KHz OSCULP32K output clock. - * - * \section asfdoc_sam0_wdt_special_considerations Special Considerations - * - * On some devices the Watchdog configuration can be fused to be always on in - * a particular configuration; if this mode is enabled the Watchdog is not - * software configurable and can have its count reset and early warning state - * checked/cleared only. - * - * \section asfdoc_sam0_wdt_extra_info Extra Information - * - * For extra information, see \ref asfdoc_sam0_wdt_extra. This includes: - * - \ref asfdoc_sam0_wdt_extra_acronyms - * - \ref asfdoc_sam0_wdt_extra_dependencies - * - \ref asfdoc_sam0_wdt_extra_errata - * - \ref asfdoc_sam0_wdt_extra_history - * - * - * \section asfdoc_sam0_wdt_examples Examples - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_wdt_exqsg. - * - * \section asfdoc_sam0_wdt_api_overview API Overview - * @{ - */ - -#include -#include -#include - -#if WDT_CALLBACK_MODE == true -# include "wdt_callback.h" -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief Watchdog Timer period configuration enum. - * - * Enum for the possible period settings of the Watchdog timer module, for - * values requiring a period as a number of Watchdog timer clock ticks. - */ -enum wdt_period { - /** No Watchdog period. This value can only be used when setting the - * Window and Early Warning periods; its use as the Watchdog Reset - * Period is invalid. */ - WDT_PERIOD_NONE = 0, - /** Watchdog period of 8 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_8CLK = 1, - /** Watchdog period of 16 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_16CLK = 2, - /** Watchdog period of 32 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_32CLK = 3, - /** Watchdog period of 64 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_64CLK = 4, - /** Watchdog period of 128 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_128CLK = 5, - /** Watchdog period of 256 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_256CLK = 6, - /** Watchdog period of 512 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_512CLK = 7, - /** Watchdog period of 1024 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_1024CLK = 8, - /** Watchdog period of 2048 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_2048CLK = 9, - /** Watchdog period of 4096 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_4096CLK = 10, - /** Watchdog period of 8192 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_8192CLK = 11, - /** Watchdog period of 16384 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_16384CLK = 12, -}; - -/** - * \brief Watchdog Timer configuration structure. - * - * Configuration structure for a Watchdog Timer instance. This - * structure should be initialized by the \ref wdt_get_config_defaults() - * function before being modified by the user application. - */ -struct wdt_conf { - /** If \c true, the Watchdog will be locked to the current configuration - * settings when the Watchdog is enabled. */ - bool always_on; - /** Enable/Disable the Watchdog Timer. */ - bool enable; -#if !(SAML21) && !(SAML22) && !(SAMC20) && !(SAMC21) - /** GCLK generator used to clock the peripheral except SAM L21/L22/C21/C20.*/ - enum gclk_generator clock_source; -#endif - /** Number of Watchdog timer clock ticks until the Watchdog expires. */ - enum wdt_period timeout_period; - /** Number of Watchdog timer clock ticks until the reset window opens. */ - enum wdt_period window_period; - /** Number of Watchdog timer clock ticks until the early warning flag is - * set. */ - enum wdt_period early_warning_period; -}; - -/** \name Configuration and Initialization - * @{ - */ - -/** - * \brief Determines if the hardware module(s) are currently synchronizing to the bus. - * - * Checks to see if the underlying hardware peripheral module(s) are currently - * synchronizing across multiple clock domains to the hardware bus. This - * function can be used to delay further operations on a module until such time - * that it is ready, to prevent blocking delays for synchronization in the - * user application. - * - * \return Synchronization status of the underlying hardware module(s). - * - * \retval false If the module has completed synchronization - * \retval true If the module synchronization is ongoing - */ -static inline bool wdt_is_syncing(void) -{ - Wdt *const WDT_module = WDT; - -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) - if (WDT_module->SYNCBUSY.reg) { -#else - if (WDT_module->STATUS.reg & WDT_STATUS_SYNCBUSY) { -#endif - return true; - } - - return false; -} - -/** - * \brief Initializes a Watchdog Timer configuration structure to defaults. - * - * Initializes a given Watchdog Timer configuration structure to a set of - * known default values. This function should be called on all new - * instances of these configuration structures before being modified by the - * user application. - * - * The default configuration is as follows: - * \li Not locked, to allow for further (re-)configuration - * \li Enable WDT - * \li Watchdog timer sourced from Generic Clock Channel 4 - * \li A timeout period of 16384 clocks of the Watchdog module clock - * \li No window period, so that the Watchdog count can be reset at any time - * \li No early warning period to indicate the Watchdog will soon expire - * - * \param[out] config Configuration structure to initialize to default values - */ -static inline void wdt_get_config_defaults( - struct wdt_conf *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Default configuration values */ - config->always_on = false; - config->enable = true; -#if !(SAML21) && !(SAML22) && !(SAMC20) && !(SAMC21) - config->clock_source = GCLK_GENERATOR_4; -#endif - config->timeout_period = WDT_PERIOD_16384CLK; - config->window_period = WDT_PERIOD_NONE; - config->early_warning_period = WDT_PERIOD_NONE; -} - -enum status_code wdt_set_config( - const struct wdt_conf *const config); - -/** \brief Determines if the Watchdog timer is currently locked in an enabled state. - * - * Determines if the Watchdog timer is currently enabled and locked, so that - * it cannot be disabled or otherwise reconfigured. - * - * \return Current Watchdog lock state. - */ -static inline bool wdt_is_locked(void) -{ - Wdt *const WDT_module = WDT; - -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) - return (WDT_module->CTRLA.reg & WDT_CTRLA_ALWAYSON); -#else - return (WDT_module->CTRL.reg & WDT_CTRL_ALWAYSON); -#endif -} - -/** @} */ - -/** \name Timeout and Early Warning Management - * @{ - */ - -/** \brief Clears the Watchdog timer early warning period elapsed flag. - * - * Clears the Watchdog timer early warning period elapsed flag, so that a new - * early warning period can be detected. - */ -static inline void wdt_clear_early_warning(void) -{ - Wdt *const WDT_module = WDT; - - WDT_module->INTFLAG.reg = WDT_INTFLAG_EW; -} - -/** \brief Determines if the Watchdog timer early warning period has elapsed. - * - * Determines if the Watchdog timer early warning period has elapsed. - * - * \note If no early warning period was configured, the value returned by this - * function is invalid. - * - * \return Current Watchdog Early Warning state. - */ -static inline bool wdt_is_early_warning(void) -{ - Wdt *const WDT_module = WDT; - - return (WDT_module->INTFLAG.reg & WDT_INTFLAG_EW); -} - -void wdt_reset_count(void); - -/** @} */ - -#ifdef __cplusplus -} -#endif - -/** @} */ - -/** - * \page asfdoc_sam0_wdt_extra Extra Information for WDT Driver - * - * \section asfdoc_sam0_wdt_extra_acronyms Acronyms - * The table below presents the acronyms used in this module: - * - * - * - * - * - * - * - * - * - * - *
AcronymDescription
WDTWatchdog Timer
- * - * - * \section asfdoc_sam0_wdt_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - \ref asfdoc_sam0_system_clock_group "System Clock Driver" - * - * - * \section asfdoc_sam0_wdt_extra_errata Errata - * There are no errata related to this driver. - * - * - * \section asfdoc_sam0_wdt_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * - * - * - * - * - * - *
Changelog
Driver updated to follow driver type convention: - * \li wdt_init, wdt_enable, wdt_disable functions removed - * \li wdt_set_config function added - * \li WDT module enable state moved inside the configuration struct
Initial Release
- */ - -/** - * \page asfdoc_sam0_wdt_exqsg Examples for WDT Driver - * - * This is a list of the available Quick Start guides (QSGs) and example - * applications for \ref asfdoc_sam0_wdt_group. QSGs are simple examples with - * step-by-step instructions to configure and use this driver in a selection of - * use cases. Note that QSGs can be compiled as a standalone application or be - * added to the user application. - * - * - \subpage asfdoc_sam0_wdt_basic_use_case - * \if WDT_CALLBACK_MODE - * - \subpage asfdoc_sam0_wdt_callback_use_case - * \endif - * - * \page asfdoc_sam0_wdt_document_revision_history Document Revision History - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Doc. Rev. - * Date - * Comments - *
E08/2015Added support for SAM L21/L22, SAM DA1, and SAM C20/C2
D12/2014Added SAMR21 and SAMD10/D11 support
C01/2014Add SAMD21 support
B06/2013Corrected documentation typos
A06/2013Initial release
- */ - -#endif /* WDT_H_INCLUDED */ diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp b/feather_sensor_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp deleted file mode 100644 index fe721be..0000000 --- a/feather_sensor_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp +++ /dev/null @@ -1,2079 +0,0 @@ -/*************************************************** - This is a library for our Adafruit FONA Cellular Module - - Designed specifically to work with the Adafruit FONA - ----> http://www.adafruit.com/products/1946 - ----> http://www.adafruit.com/products/1963 - - These displays use TTL Serial to communicate, 2 pins are required to - interface - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - BSD license, all text above must be included in any redistribution - ****************************************************/ - // next line per http://postwarrior.com/arduino-ethershield-error-prog_char-does-not-name-a-type/ - -#include "Adafruit_FONA.h" - - - - -Adafruit_FONA::Adafruit_FONA(int8_t rst) -{ - _rstpin = rst; - - apn = F("FONAnet"); - apnusername = 0; - apnpassword = 0; - mySerial = 0; - httpsredirect = false; - useragent = F("FONA"); - ok_reply = F("OK"); -} - -uint8_t Adafruit_FONA::type(void) { - return _type; -} - -boolean Adafruit_FONA::begin(Stream &port) { - mySerial = &port; - - pinMode(_rstpin, OUTPUT); - digitalWrite(_rstpin, HIGH); - delay(10); - digitalWrite(_rstpin, LOW); - delay(100); - digitalWrite(_rstpin, HIGH); - - DEBUG_PRINTLN(F("Attempting to open comm with ATs")); - // give 7 seconds to reboot - int16_t timeout = 7000; - - while (timeout > 0) { - while (mySerial->available()) mySerial->read(); - if (sendCheckReply(F("AT"), ok_reply)) - break; - while (mySerial->available()) mySerial->read(); - if (sendCheckReply(F("AT"), F("AT"))) - break; - delay(500); - timeout-=500; - } - -#ifdef ADAFRUIT_FONA_DEBUG - if (timeout <= 0) - DEBUG_PRINTLN(F("Timeout: No response to AT... last ditch attempt.")); -#endif - - sendCheckReply(F("AT"), ok_reply); - delay(100); - sendCheckReply(F("AT"), ok_reply); - delay(100); - sendCheckReply(F("AT"), ok_reply); - delay(100); - - // turn off Echo! - sendCheckReply(F("ATE0"), ok_reply); - delay(100); - - if (! sendCheckReply(F("ATE0"), ok_reply)) { - return false; - } - - // turn on hangupitude - sendCheckReply(F("AT+CVHU=0"), ok_reply); - - delay(100); - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN("ATI"); - - mySerial->println("ATI"); - readline(500, true); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - - - if (prog_char_strstr(replybuffer, (prog_char *)F("SIM808 R14")) != 0) { - _type = FONA808_V2; - } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIM808 R13")) != 0) { - _type = FONA808_V1; - } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIM800 R14")) != 0) { - _type = FONA800L; - } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIMCOM_SIM5320A")) != 0) { - _type = FONA3G_A; - } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIMCOM_SIM5320E")) != 0) { - _type = FONA3G_E; - } - - if (_type == FONA800L) { - // determine if L or H - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN("AT+GMM"); - - mySerial->println("AT+GMM"); - readline(500, true); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - - if (prog_char_strstr(replybuffer, (prog_char *)F("SIM800H")) != 0) { - _type = FONA800H; - } - } - -#if defined(FONA_PREF_SMS_STORAGE) - sendCheckReply(F("AT+CPMS=\"" FONA_PREF_SMS_STORAGE "\""), ok_reply); -#endif - - return true; -} - - -/********* Serial port ********************************************/ -boolean Adafruit_FONA::setBaudrate(uint16_t baud) { - return sendCheckReply(F("AT+IPREX="), baud, ok_reply); -} - -/********* Real Time Clock ********************************************/ - -boolean Adafruit_FONA::readRTC(uint8_t *year, uint8_t *month, uint8_t *date, uint8_t *hr, uint8_t *min, uint8_t *sec) { - uint16_t v; - sendParseReply(F("AT+CCLK?"), F("+CCLK: "), &v, '/', 0); - *year = v; - - DEBUG_PRINTLN(*year); -} - -boolean Adafruit_FONA::enableRTC(uint8_t i) { - if (! sendCheckReply(F("AT+CLTS="), i, ok_reply)) - return false; - return sendCheckReply(F("AT&W"), ok_reply); -} - - -/********* BATTERY & ADC ********************************************/ - -/* returns value in mV (uint16_t) */ -boolean Adafruit_FONA::getBattVoltage(uint16_t *v) { - return sendParseReply(F("AT+CBC"), F("+CBC: "), v, ',', 2); -} - -/* returns value in mV (uint16_t) */ -boolean Adafruit_FONA_3G::getBattVoltage(uint16_t *v) { - float f; - boolean b = sendParseReply(F("AT+CBC"), F("+CBC: "), &f, ',', 2); - *v = f*1000; - return b; -} - - -/* returns the percentage charge of battery as reported by sim800 */ -boolean Adafruit_FONA::getBattPercent(uint16_t *p) { - return sendParseReply(F("AT+CBC"), F("+CBC: "), p, ',', 1); -} - -boolean Adafruit_FONA::getADCVoltage(uint16_t *v) { - return sendParseReply(F("AT+CADC?"), F("+CADC: 1,"), v); -} - -/********* SIM ***********************************************************/ - -uint8_t Adafruit_FONA::unlockSIM(char *pin) -{ - char sendbuff[14] = "AT+CPIN="; - sendbuff[8] = pin[0]; - sendbuff[9] = pin[1]; - sendbuff[10] = pin[2]; - sendbuff[11] = pin[3]; - sendbuff[12] = '\0'; - - return sendCheckReply(sendbuff, ok_reply); -} - -uint8_t Adafruit_FONA::getSIMCCID(char *ccid) { - getReply(F("AT+CCID")); - // up to 28 chars for reply, 20 char total ccid - if (replybuffer[0] == '+') { - // fona 3g? - strncpy(ccid, replybuffer+8, 20); - } else { - // fona 800 or 800 - strncpy(ccid, replybuffer, 20); - } - ccid[20] = 0; - - readline(); // eat 'OK' - - return strlen(ccid); -} - -/********* IMEI **********************************************************/ - -uint8_t Adafruit_FONA::getIMEI(char *imei) { - getReply(F("AT+GSN")); - - // up to 15 chars - strncpy(imei, replybuffer, 15); - imei[15] = 0; - - readline(); // eat 'OK' - - return strlen(imei); -} - -/********* NETWORK *******************************************************/ - -uint8_t Adafruit_FONA::getNetworkStatus(void) { - uint16_t status; - - if (! sendParseReply(F("AT+CREG?"), F("+CREG: "), &status, ',', 1)) return 0; - - return status; -} - - -uint8_t Adafruit_FONA::getRSSI(void) { - uint16_t reply; - - if (! sendParseReply(F("AT+CSQ"), F("+CSQ: "), &reply) ) return 0; - - return reply; -} - -/********* AUDIO *******************************************************/ - -boolean Adafruit_FONA::setAudio(uint8_t a) { - // 0 is headset, 1 is external audio - if (a > 1) return false; - - return sendCheckReply(F("AT+CHFA="), a, ok_reply); -} - -uint8_t Adafruit_FONA::getVolume(void) { - uint16_t reply; - - if (! sendParseReply(F("AT+CLVL?"), F("+CLVL: "), &reply) ) return 0; - - return reply; -} - -boolean Adafruit_FONA::setVolume(uint8_t i) { - return sendCheckReply(F("AT+CLVL="), i, ok_reply); -} - - -boolean Adafruit_FONA::playDTMF(char dtmf) { - char str[4]; - str[0] = '\"'; - str[1] = dtmf; - str[2] = '\"'; - str[3] = 0; - return sendCheckReply(F("AT+CLDTMF=3,"), str, ok_reply); -} - -boolean Adafruit_FONA::playToolkitTone(uint8_t t, uint16_t len) { - return sendCheckReply(F("AT+STTONE=1,"), t, len, ok_reply); -} - -boolean Adafruit_FONA_3G::playToolkitTone(uint8_t t, uint16_t len) { - if (! sendCheckReply(F("AT+CPTONE="), t, ok_reply)) - return false; - delay(len); - return sendCheckReply(F("AT+CPTONE=0"), ok_reply); -} - -boolean Adafruit_FONA::setMicVolume(uint8_t a, uint8_t level) { - // 0 is headset, 1 is external audio - if (a > 1) return false; - - return sendCheckReply(F("AT+CMIC="), a, level, ok_reply); -} - -/********* FM RADIO *******************************************************/ - - -boolean Adafruit_FONA::FMradio(boolean onoff, uint8_t a) { - if (! onoff) { - return sendCheckReply(F("AT+FMCLOSE"), ok_reply); - } - - // 0 is headset, 1 is external audio - if (a > 1) return false; - - return sendCheckReply(F("AT+FMOPEN="), a, ok_reply); -} - -boolean Adafruit_FONA::tuneFMradio(uint16_t station) { - // Fail if FM station is outside allowed range. - if ((station < 870) || (station > 1090)) - return false; - - return sendCheckReply(F("AT+FMFREQ="), station, ok_reply); -} - -boolean Adafruit_FONA::setFMVolume(uint8_t i) { - // Fail if volume is outside allowed range (0-6). - if (i > 6) { - return false; - } - // Send FM volume command and verify response. - return sendCheckReply(F("AT+FMVOLUME="), i, ok_reply); -} - -int8_t Adafruit_FONA::getFMVolume() { - uint16_t level; - - if (! sendParseReply(F("AT+FMVOLUME?"), F("+FMVOLUME: "), &level) ) return 0; - - return level; -} - -int8_t Adafruit_FONA::getFMSignalLevel(uint16_t station) { - // Fail if FM station is outside allowed range. - if ((station < 875) || (station > 1080)) { - return -1; - } - - // Send FM signal level query command. - // Note, need to explicitly send timeout so right overload is chosen. - getReply(F("AT+FMSIGNAL="), station, FONA_DEFAULT_TIMEOUT_MS); - // Check response starts with expected value. - char *p = prog_char_strstr(replybuffer, PSTR("+FMSIGNAL: ")); - if (p == 0) return -1; - p+=11; - // Find second colon to get start of signal quality. - p = strchr(p, ':'); - if (p == 0) return -1; - p+=1; - // Parse signal quality. - int8_t level = atoi(p); - readline(); // eat the "OK" - return level; -} - -/********* PWM/BUZZER **************************************************/ - -boolean Adafruit_FONA::setPWM(uint16_t period, uint8_t duty) { - if (period > 2000) return false; - if (duty > 100) return false; - - return sendCheckReply(F("AT+SPWM=0,"), period, duty, ok_reply); -} - -/********* CALL PHONES **************************************************/ -boolean Adafruit_FONA::callPhone(char *number) { - char sendbuff[35] = "ATD"; - strncpy(sendbuff+3, number, min(30, strlen(number))); - uint8_t x = strlen(sendbuff); - sendbuff[x] = ';'; - sendbuff[x+1] = 0; - //DEBUG_PRINTLN(sendbuff); - - return sendCheckReply(sendbuff, ok_reply); -} - - -uint8_t Adafruit_FONA::getCallStatus(void) { - uint16_t phoneStatus; - - if (! sendParseReply(F("AT+CPAS"), F("+CPAS: "), &phoneStatus)) - return FONA_CALL_FAILED; // 1, since 0 is actually a known, good reply - - return phoneStatus; // 0 ready, 2 unkown, 3 ringing, 4 call in progress -} - -boolean Adafruit_FONA::hangUp(void) { - return sendCheckReply(F("ATH0"), ok_reply); -} - -boolean Adafruit_FONA_3G::hangUp(void) { - getReply(F("ATH")); - - return (prog_char_strstr(replybuffer, (prog_char *)F("VOICE CALL: END")) != 0); -} - -boolean Adafruit_FONA::pickUp(void) { - return sendCheckReply(F("ATA"), ok_reply); -} - -boolean Adafruit_FONA_3G::pickUp(void) { - return sendCheckReply(F("ATA"), F("VOICE CALL: BEGIN")); -} - - -void Adafruit_FONA::onIncomingCall() { - - DEBUG_PRINT(F("> ")); DEBUG_PRINTLN(F("Incoming call...")); - - Adafruit_FONA::_incomingCall = true; -} - -boolean Adafruit_FONA::_incomingCall = false; - -boolean Adafruit_FONA::callerIdNotification(boolean enable, uint8_t interrupt) { - if(enable){ - attachInterrupt(interrupt, onIncomingCall, FALLING); - return sendCheckReply(F("AT+CLIP=1"), ok_reply); - } - - detachInterrupt(interrupt); - return sendCheckReply(F("AT+CLIP=0"), ok_reply); -} - -boolean Adafruit_FONA::incomingCallNumber(char* phonenum) { - //+CLIP: "",145,"",0,"",0 - if(!Adafruit_FONA::_incomingCall) - return false; - - readline(); - while(!prog_char_strcmp(replybuffer, (prog_char*)F("RING")) == 0) { - flushInput(); - readline(); - } - - readline(); //reads incoming phone number line - - parseReply(F("+CLIP: \""), phonenum, '"'); - - - DEBUG_PRINT(F("Phone Number: ")); - DEBUG_PRINTLN(replybuffer); - - - Adafruit_FONA::_incomingCall = false; - return true; -} - -/********* SMS **********************************************************/ - -uint8_t Adafruit_FONA::getSMSInterrupt(void) { - uint16_t reply; - - if (! sendParseReply(F("AT+CFGRI?"), F("+CFGRI: "), &reply) ) return 0; - - return reply; -} - -boolean Adafruit_FONA::setSMSInterrupt(uint8_t i) { - return sendCheckReply(F("AT+CFGRI="), i, ok_reply); -} - -int8_t Adafruit_FONA::getNumSMS(void) { - uint16_t numsms; - - // get into text mode - if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return -1; - - // ask how many sms are stored - if (sendParseReply(F("AT+CPMS?"), F("\"SM\","), &numsms)) - return numsms; - if (sendParseReply(F("AT+CPMS?"), F("\"SM_P\","), &numsms)) - return numsms; - return -1; -} - -// Reading SMS's is a bit involved so we don't use helpers that may cause delays or debug -// printouts! -boolean Adafruit_FONA::readSMS(uint8_t i, char *smsbuff, - uint16_t maxlen, uint16_t *readlen) { - // text mode - if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return false; - - // show all text mode parameters - if (! sendCheckReply(F("AT+CSDH=1"), ok_reply)) return false; - - // parse out the SMS len - uint16_t thesmslen = 0; - - - DEBUG_PRINT(F("AT+CMGR=")); - DEBUG_PRINTLN(i); - - - //getReply(F("AT+CMGR="), i, 1000); // do not print debug! - mySerial->print(F("AT+CMGR=")); - mySerial->println(i); - readline(1000); // timeout - - //DEBUG_PRINT(F("Reply: ")); DEBUG_PRINTLN(replybuffer); - // parse it out... - - - DEBUG_PRINTLN(replybuffer); - - - if (! parseReply(F("+CMGR:"), &thesmslen, ',', 11)) { - *readlen = 0; - return false; - } - - readRaw(thesmslen); - - flushInput(); - - uint16_t thelen = min(maxlen, strlen(replybuffer)); - strncpy(smsbuff, replybuffer, thelen); - smsbuff[thelen] = 0; // end the string - - - DEBUG_PRINTLN(replybuffer); - - *readlen = thelen; - return true; -} - -// Retrieve the sender of the specified SMS message and copy it as a string to -// the sender buffer. Up to senderlen characters of the sender will be copied -// and a null terminator will be added if less than senderlen charactesr are -// copied to the result. Returns true if a result was successfully retrieved, -// otherwise false. -boolean Adafruit_FONA::getSMSSender(uint8_t i, char *sender, int senderlen) { - // Ensure text mode and all text mode parameters are sent. - if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return false; - if (! sendCheckReply(F("AT+CSDH=1"), ok_reply)) return false; - - - DEBUG_PRINT(F("AT+CMGR=")); - DEBUG_PRINTLN(i); - - - // Send command to retrieve SMS message and parse a line of response. - mySerial->print(F("AT+CMGR=")); - mySerial->println(i); - readline(1000); - - - DEBUG_PRINTLN(replybuffer); - - - // Parse the second field in the response. - boolean result = parseReplyQuoted(F("+CMGR:"), sender, senderlen, ',', 1); - // Drop any remaining data from the response. - flushInput(); - return result; -} - -boolean Adafruit_FONA::sendSMS(char *smsaddr, char *smsmsg) { - if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return -1; - - char sendcmd[30] = "AT+CMGS=\""; - strncpy(sendcmd+9, smsaddr, 30-9-2); // 9 bytes beginning, 2 bytes for close quote + null - sendcmd[strlen(sendcmd)] = '\"'; - - if (! sendCheckReply(sendcmd, F("> "))) return false; - - DEBUG_PRINT(F("> ")); DEBUG_PRINTLN(smsmsg); - - mySerial->println(smsmsg); - mySerial->println(); - mySerial->write(0x1A); - - DEBUG_PRINTLN("^Z"); - - if ( (_type == FONA3G_A) || (_type == FONA3G_E) ) { - // Eat two sets of CRLF - readline(200); - //DEBUG_PRINT("Line 1: "); DEBUG_PRINTLN(strlen(replybuffer)); - readline(200); - //DEBUG_PRINT("Line 2: "); DEBUG_PRINTLN(strlen(replybuffer)); - } - readline(10000); // read the +CMGS reply, wait up to 10 seconds!!! - //DEBUG_PRINT("Line 3: "); DEBUG_PRINTLN(strlen(replybuffer)); - if (strstr(replybuffer, "+CMGS") == 0) { - return false; - } - readline(1000); // read OK - //DEBUG_PRINT("* "); DEBUG_PRINTLN(replybuffer); - - if (strcmp(replybuffer, "OK") != 0) { - return false; - } - - return true; -} - - -boolean Adafruit_FONA::deleteSMS(uint8_t i) { - if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return -1; - // read an sms - char sendbuff[12] = "AT+CMGD=000"; - sendbuff[8] = (i / 100) + '0'; - i %= 100; - sendbuff[9] = (i / 10) + '0'; - i %= 10; - sendbuff[10] = i + '0'; - - return sendCheckReply(sendbuff, ok_reply, 2000); -} - -/********* USSD *********************************************************/ - -boolean Adafruit_FONA::sendUSSD(char *ussdmsg, char *ussdbuff, uint16_t maxlen, uint16_t *readlen) { - if (! sendCheckReply(F("AT+CUSD=1"), ok_reply)) return -1; - - char sendcmd[30] = "AT+CUSD=1,\""; - strncpy(sendcmd+11, ussdmsg, 30-11-2); // 11 bytes beginning, 2 bytes for close quote + null - sendcmd[strlen(sendcmd)] = '\"'; - - if (! sendCheckReply(sendcmd, ok_reply)) { - *readlen = 0; - return false; - } else { - readline(10000); // read the +CUSD reply, wait up to 10 seconds!!! - //DEBUG_PRINT("* "); DEBUG_PRINTLN(replybuffer); - char *p = prog_char_strstr(replybuffer, PSTR("+CUSD: ")); - if (p == 0) { - *readlen = 0; - return false; - } - p+=7; //+CUSD - // Find " to get start of ussd message. - p = strchr(p, '\"'); - if (p == 0) { - *readlen = 0; - return false; - } - p+=1; //" - // Find " to get end of ussd message. - char *strend = strchr(p, '\"'); - - uint16_t lentocopy = min(maxlen-1, strend - p); - strncpy(ussdbuff, p, lentocopy+1); - ussdbuff[lentocopy] = 0; - *readlen = lentocopy; - } - return true; -} - - -/********* TIME **********************************************************/ - -boolean Adafruit_FONA::enableNetworkTimeSync(boolean onoff) { - if (onoff) { - if (! sendCheckReply(F("AT+CLTS=1"), ok_reply)) - return false; - } else { - if (! sendCheckReply(F("AT+CLTS=0"), ok_reply)) - return false; - } - - flushInput(); // eat any 'Unsolicted Result Code' - - return true; -} - -boolean Adafruit_FONA::enableNTPTimeSync(boolean onoff, FONAFlashStringPtr ntpserver) { - if (onoff) { - if (! sendCheckReply(F("AT+CNTPCID=1"), ok_reply)) - return false; - - mySerial->print(F("AT+CNTP=\"")); - if (ntpserver != 0) { - mySerial->print(ntpserver); - } else { - mySerial->print(F("pool.ntp.org")); - } - mySerial->println(F("\",0")); - readline(FONA_DEFAULT_TIMEOUT_MS); - if (strcmp(replybuffer, "OK") != 0) - return false; - - if (! sendCheckReply(F("AT+CNTP"), ok_reply, 10000)) - return false; - - uint16_t status; - readline(10000); - if (! parseReply(F("+CNTP:"), &status)) - return false; - } else { - if (! sendCheckReply(F("AT+CNTPCID=0"), ok_reply)) - return false; - } - - return true; -} - -boolean Adafruit_FONA::getTime(char *buff, uint16_t maxlen) { - getReply(F("AT+CCLK?"), (uint16_t) 10000); - if (strncmp(replybuffer, "+CCLK: ", 7) != 0) - return false; - - char *p = replybuffer+7; - uint16_t lentocopy = min(maxlen-1, strlen(p)); - strncpy(buff, p, lentocopy+1); - buff[lentocopy] = 0; - - readline(); // eat OK - - return true; -} - -/********* GPS **********************************************************/ - - -boolean Adafruit_FONA::enableGPS(boolean onoff) { - uint16_t state; - - // first check if its already on or off - - if (_type == FONA808_V2) { - if (! sendParseReply(F("AT+CGNSPWR?"), F("+CGNSPWR: "), &state) ) - return false; - } else { - if (! sendParseReply(F("AT+CGPSPWR?"), F("+CGPSPWR: "), &state)) - return false; - } - - if (onoff && !state) { - if (_type == FONA808_V2) { - if (! sendCheckReply(F("AT+CGNSPWR=1"), ok_reply)) // try GNS command - return false; - } else { - if (! sendCheckReply(F("AT+CGPSPWR=1"), ok_reply)) - return false; - } - } else if (!onoff && state) { - if (_type == FONA808_V2) { - if (! sendCheckReply(F("AT+CGNSPWR=0"), ok_reply)) // try GNS command - return false; - } else { - if (! sendCheckReply(F("AT+CGPSPWR=0"), ok_reply)) - return false; - } - } - return true; -} - - - -boolean Adafruit_FONA_3G::enableGPS(boolean onoff) { - uint16_t state; - - // first check if its already on or off - if (! Adafruit_FONA::sendParseReply(F("AT+CGPS?"), F("+CGPS: "), &state) ) - return false; - - if (onoff && !state) { - if (! sendCheckReply(F("AT+CGPS=1"), ok_reply)) - return false; - } else if (!onoff && state) { - if (! sendCheckReply(F("AT+CGPS=0"), ok_reply)) - return false; - // this takes a little time - readline(2000); // eat '+CGPS: 0' - } - return true; -} - -int8_t Adafruit_FONA::GPSstatus(void) { - if (_type == FONA808_V2) { - // 808 V2 uses GNS commands and doesn't have an explicit 2D/3D fix status. - // Instead just look for a fix and if found assume it's a 3D fix. - getReply(F("AT+CGNSINF")); - char *p = prog_char_strstr(replybuffer, (prog_char*)F("+CGNSINF: ")); - if (p == 0) return -1; - p+=12; // Skip to second value, fix status. - readline(); // eat 'OK' - //DEBUG_PRINTLN(p); - // Assume if the fix status is '1' then we have a 3D fix, otherwise no fix. - if (p[0] == '1') return 3; - else return 0; - } - if (_type == FONA3G_A || _type == FONA3G_E) { - // FONA 3G doesn't have an explicit 2D/3D fix status. - // Instead just look for a fix and if found assume it's a 3D fix. - getReply(F("AT+CGPSINFO")); - char *p = prog_char_strstr(replybuffer, (prog_char*)F("+CGPSINFO:")); - if (p == 0) return -1; - if (p[10] != ',') return 3; // if you get anything, its 3D fix - return 0; - } - else { - // 808 V1 looks for specific 2D or 3D fix state. - getReply(F("AT+CGPSSTATUS?")); - char *p = prog_char_strstr(replybuffer, (prog_char*)F("SSTATUS: Location ")); - if (p == 0) return -1; - p+=18; - readline(); // eat 'OK' - //DEBUG_PRINTLN(p); - if (p[0] == 'U') return 0; - if (p[0] == 'N') return 1; - if (p[0] == '2') return 2; - if (p[0] == '3') return 3; - } - // else - return 0; -} - -uint8_t Adafruit_FONA::getGPS(uint8_t arg, char *buffer, uint8_t maxbuff) { - int32_t x = arg; - - if ( (_type == FONA3G_A) || (_type == FONA3G_E) ) { - getReply(F("AT+CGPSINFO")); - } else if (_type == FONA808_V1) { - getReply(F("AT+CGPSINF="), x); - } else { - getReply(F("AT+CGNSINF")); - } - - char *p = prog_char_strstr(replybuffer, (prog_char*)F("SINF")); - if (p == 0) { - buffer[0] = 0; - return 0; - } - - p+=6; - - uint8_t len = max(maxbuff-1, strlen(p)); - strncpy(buffer, p, len); - buffer[len] = 0; - - readline(); // eat 'OK' - return len; -} - -boolean Adafruit_FONA::getGPS(float *lat, float *lon, float *speed_kph, float *heading, float *altitude) { - - char gpsbuffer[120]; - - // we need at least a 2D fix - if (GPSstatus() < 2) - return false; - - // grab the mode 2^5 gps csv from the sim808 - uint8_t res_len = getGPS(32, gpsbuffer, 120); - - // make sure we have a response - if (res_len == 0) - return false; - - if (_type == FONA3G_A || _type == FONA3G_E) { - // Parse 3G respose - // +CGPSINFO:4043.000000,N,07400.000000,W,151015,203802.1,-12.0,0.0,0 - // skip beginning - char *tok; - - // grab the latitude - char *latp = strtok(gpsbuffer, ","); - if (! latp) return false; - - // grab latitude direction - char *latdir = strtok(NULL, ","); - if (! latdir) return false; - - // grab longitude - char *longp = strtok(NULL, ","); - if (! longp) return false; - - // grab longitude direction - char *longdir = strtok(NULL, ","); - if (! longdir) return false; - - // skip date & time - tok = strtok(NULL, ","); - tok = strtok(NULL, ","); - - // only grab altitude if needed - if (altitude != NULL) { - // grab altitude - char *altp = strtok(NULL, ","); - if (! altp) return false; - *altitude = atof(altp); - } - - // only grab speed if needed - if (speed_kph != NULL) { - // grab the speed in km/h - char *speedp = strtok(NULL, ","); - if (! speedp) return false; - - *speed_kph = atof(speedp); - } - - // only grab heading if needed - if (heading != NULL) { - - // grab the speed in knots - char *coursep = strtok(NULL, ","); - if (! coursep) return false; - - *heading = atof(coursep); - } - - double latitude = atof(latp); - double longitude = atof(longp); - - // convert latitude from minutes to decimal - float degrees = floor(latitude / 100); - double minutes = latitude - (100 * degrees); - minutes /= 60; - degrees += minutes; - - // turn direction into + or - - if (latdir[0] == 'S') degrees *= -1; - - *lat = degrees; - - // convert longitude from minutes to decimal - degrees = floor(longitude / 100); - minutes = longitude - (100 * degrees); - minutes /= 60; - degrees += minutes; - - // turn direction into + or - - if (longdir[0] == 'W') degrees *= -1; - - *lon = degrees; - - } else if (_type == FONA808_V2) { - // Parse 808 V2 response. See table 2-3 from here for format: - // http://www.adafruit.com/datasheets/SIM800%20Series_GNSS_Application%20Note%20V1.00.pdf - - // skip GPS run status - char *tok = strtok(gpsbuffer, ","); - if (! tok) return false; - - // skip fix status - tok = strtok(NULL, ","); - if (! tok) return false; - - // skip date - tok = strtok(NULL, ","); - if (! tok) return false; - - // grab the latitude - char *latp = strtok(NULL, ","); - if (! latp) return false; - - // grab longitude - char *longp = strtok(NULL, ","); - if (! longp) return false; - - *lat = atof(latp); - *lon = atof(longp); - - // only grab altitude if needed - if (altitude != NULL) { - // grab altitude - char *altp = strtok(NULL, ","); - if (! altp) return false; - - *altitude = atof(altp); - } - - // only grab speed if needed - if (speed_kph != NULL) { - // grab the speed in km/h - char *speedp = strtok(NULL, ","); - if (! speedp) return false; - - *speed_kph = atof(speedp); - } - - // only grab heading if needed - if (heading != NULL) { - - // grab the speed in knots - char *coursep = strtok(NULL, ","); - if (! coursep) return false; - - *heading = atof(coursep); - } - } - else { - // Parse 808 V1 response. - - // skip mode - char *tok = strtok(gpsbuffer, ","); - if (! tok) return false; - - // skip date - tok = strtok(NULL, ","); - if (! tok) return false; - - // skip fix - tok = strtok(NULL, ","); - if (! tok) return false; - - // grab the latitude - char *latp = strtok(NULL, ","); - if (! latp) return false; - - // grab latitude direction - char *latdir = strtok(NULL, ","); - if (! latdir) return false; - - // grab longitude - char *longp = strtok(NULL, ","); - if (! longp) return false; - - // grab longitude direction - char *longdir = strtok(NULL, ","); - if (! longdir) return false; - - double latitude = atof(latp); - double longitude = atof(longp); - - // convert latitude from minutes to decimal - float degrees = floor(latitude / 100); - double minutes = latitude - (100 * degrees); - minutes /= 60; - degrees += minutes; - - // turn direction into + or - - if (latdir[0] == 'S') degrees *= -1; - - *lat = degrees; - - // convert longitude from minutes to decimal - degrees = floor(longitude / 100); - minutes = longitude - (100 * degrees); - minutes /= 60; - degrees += minutes; - - // turn direction into + or - - if (longdir[0] == 'W') degrees *= -1; - - *lon = degrees; - - // only grab speed if needed - if (speed_kph != NULL) { - - // grab the speed in knots - char *speedp = strtok(NULL, ","); - if (! speedp) return false; - - // convert to kph - *speed_kph = atof(speedp) * 1.852; - - } - - // only grab heading if needed - if (heading != NULL) { - - // grab the speed in knots - char *coursep = strtok(NULL, ","); - if (! coursep) return false; - - *heading = atof(coursep); - - } - - // no need to continue - if (altitude == NULL) - return true; - - // we need at least a 3D fix for altitude - if (GPSstatus() < 3) - return false; - - // grab the mode 0 gps csv from the sim808 - res_len = getGPS(0, gpsbuffer, 120); - - // make sure we have a response - if (res_len == 0) - return false; - - // skip mode - tok = strtok(gpsbuffer, ","); - if (! tok) return false; - - // skip lat - tok = strtok(NULL, ","); - if (! tok) return false; - - // skip long - tok = strtok(NULL, ","); - if (! tok) return false; - - // grab altitude - char *altp = strtok(NULL, ","); - if (! altp) return false; - - *altitude = atof(altp); - } - - return true; - -} - -boolean Adafruit_FONA::enableGPSNMEA(uint8_t i) { - - char sendbuff[15] = "AT+CGPSOUT=000"; - sendbuff[11] = (i / 100) + '0'; - i %= 100; - sendbuff[12] = (i / 10) + '0'; - i %= 10; - sendbuff[13] = i + '0'; - - if (_type == FONA808_V2) { - if (i) - return sendCheckReply(F("AT+CGNSTST=1"), ok_reply); - else - return sendCheckReply(F("AT+CGNSTST=0"), ok_reply); - } else { - return sendCheckReply(sendbuff, ok_reply, 2000); - } -} - - -/********* GPRS **********************************************************/ - - -boolean Adafruit_FONA::enableGPRS(boolean onoff) { - - if (onoff) { - // disconnect all sockets - sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 20000); - - if (! sendCheckReply(F("AT+CGATT=1"), ok_reply, 10000)) - return false; - - // set bearer profile! connection type GPRS - if (! sendCheckReply(F("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\""), - ok_reply, 10000)) - return false; - - // set bearer profile access point name - if (apn) { - // Send command AT+SAPBR=3,1,"APN","" where is the configured APN value. - if (! sendCheckReplyQuoted(F("AT+SAPBR=3,1,\"APN\","), apn, ok_reply, 10000)) - return false; - - // send AT+CSTT,"apn","user","pass" - flushInput(); - - mySerial->print(F("AT+CSTT=\"")); - mySerial->print(apn); - if (apnusername) { - mySerial->print("\",\""); - mySerial->print(apnusername); - } - if (apnpassword) { - mySerial->print("\",\""); - mySerial->print(apnpassword); - } - mySerial->println("\""); - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(F("AT+CSTT=\"")); - DEBUG_PRINT(apn); - - if (apnusername) { - DEBUG_PRINT("\",\""); - DEBUG_PRINT(apnusername); - } - if (apnpassword) { - DEBUG_PRINT("\",\""); - DEBUG_PRINT(apnpassword); - } - DEBUG_PRINTLN("\""); - - if (! expectReply(ok_reply)) return false; - - // set username/password - if (apnusername) { - // Send command AT+SAPBR=3,1,"USER","" where is the configured APN username. - if (! sendCheckReplyQuoted(F("AT+SAPBR=3,1,\"USER\","), apnusername, ok_reply, 10000)) - return false; - } - if (apnpassword) { - // Send command AT+SAPBR=3,1,"PWD","" where is the configured APN password. - if (! sendCheckReplyQuoted(F("AT+SAPBR=3,1,\"PWD\","), apnpassword, ok_reply, 10000)) - return false; - } - } - - // open GPRS context - if (! sendCheckReply(F("AT+SAPBR=1,1"), ok_reply, 30000)) - return false; - - // bring up wireless connection - if (! sendCheckReply(F("AT+CIICR"), ok_reply, 10000)) - return false; - - } else { - // disconnect all sockets - if (! sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 20000)) - return false; - - // close GPRS context - if (! sendCheckReply(F("AT+SAPBR=0,1"), ok_reply, 10000)) - return false; - - if (! sendCheckReply(F("AT+CGATT=0"), ok_reply, 10000)) - return false; - - } - return true; -} - -boolean Adafruit_FONA_3G::enableGPRS(boolean onoff) { - - if (onoff) { - // disconnect all sockets - //sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 5000); - - if (! sendCheckReply(F("AT+CGATT=1"), ok_reply, 10000)) - return false; - - - // set bearer profile access point name - if (apn) { - // Send command AT+CGSOCKCONT=1,"IP","" where is the configured APN name. - if (! sendCheckReplyQuoted(F("AT+CGSOCKCONT=1,\"IP\","), apn, ok_reply, 10000)) - return false; - - // set username/password - if (apnusername) { - char authstring[100] = "AT+CGAUTH=1,1,\""; - char *strp = authstring + strlen(authstring); - prog_char_strcpy(strp, (prog_char *)apnusername); - strp+=prog_char_strlen((prog_char *)apnusername); - strp[0] = '\"'; - strp++; - strp[0] = 0; - - if (apnpassword) { - strp[0] = ','; strp++; - strp[0] = '\"'; strp++; - prog_char_strcpy(strp, (prog_char *)apnpassword); - strp+=prog_char_strlen((prog_char *)apnpassword); - strp[0] = '\"'; - strp++; - strp[0] = 0; - } - - if (! sendCheckReply(authstring, ok_reply, 10000)) - return false; - } - } - - // connect in transparent - if (! sendCheckReply(F("AT+CIPMODE=1"), ok_reply, 10000)) - return false; - // open network (?) - if (! sendCheckReply(F("AT+NETOPEN=,,1"), F("Network opened"), 10000)) - return false; - - readline(); // eat 'OK' - } else { - // close GPRS context - if (! sendCheckReply(F("AT+NETCLOSE"), F("Network closed"), 10000)) - return false; - - readline(); // eat 'OK' - } - - return true; -} - -uint8_t Adafruit_FONA::GPRSstate(void) { - uint16_t state; - - if (! sendParseReply(F("AT+CGATT?"), F("+CGATT: "), &state) ) - return -1; - - return state; -} - -void Adafruit_FONA::setGPRSNetworkSettings(FONAFlashStringPtr apn, - FONAFlashStringPtr username, FONAFlashStringPtr password) { - this->apn = apn; - this->apnusername = username; - this->apnpassword = password; -} - -boolean Adafruit_FONA::getGSMLoc(uint16_t *errorcode, char *buff, uint16_t maxlen) { - - getReply(F("AT+CIPGSMLOC=1,1"), (uint16_t)10000); - - if (! parseReply(F("+CIPGSMLOC: "), errorcode)) - return false; - - char *p = replybuffer+14; - uint16_t lentocopy = min(maxlen-1, strlen(p)); - strncpy(buff, p, lentocopy+1); - - readline(); // eat OK - - return true; -} - -boolean Adafruit_FONA::getGSMLoc(float *lat, float *lon) { - - uint16_t returncode; - char gpsbuffer[120]; - - // make sure we could get a response - if (! getGSMLoc(&returncode, gpsbuffer, 120)) - return false; - - // make sure we have a valid return code - if (returncode != 0) - return false; - - // +CIPGSMLOC: 0,-74.007729,40.730160,2015/10/15,19:24:55 - // tokenize the gps buffer to locate the lat & long - char *longp = strtok(gpsbuffer, ","); - if (! longp) return false; - - char *latp = strtok(NULL, ","); - if (! latp) return false; - - *lat = atof(latp); - *lon = atof(longp); - - return true; - -} -/********* TCP FUNCTIONS ************************************/ - - -boolean Adafruit_FONA::TCPconnect(char *server, uint16_t port) { - flushInput(); - - // close all old connections - if (! sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 20000) ) return false; - - // single connection at a time - if (! sendCheckReply(F("AT+CIPMUX=0"), ok_reply) ) return false; - - // manually read data - if (! sendCheckReply(F("AT+CIPRXGET=1"), ok_reply) ) return false; - - - DEBUG_PRINT(F("AT+CIPSTART=\"TCP\",\"")); - DEBUG_PRINT(server); - DEBUG_PRINT(F("\",\"")); - DEBUG_PRINT(port); - DEBUG_PRINTLN(F("\"")); - - - mySerial->print(F("AT+CIPSTART=\"TCP\",\"")); - mySerial->print(server); - mySerial->print(F("\",\"")); - mySerial->print(port); - mySerial->println(F("\"")); - - if (! expectReply(ok_reply)) return false; - if (! expectReply(F("CONNECT OK"))) return false; - - // looks like it was a success (?) - return true; -} - -boolean Adafruit_FONA::TCPclose(void) { - return sendCheckReply(F("AT+CIPCLOSE"), ok_reply); -} - -boolean Adafruit_FONA::TCPconnected(void) { - if (! sendCheckReply(F("AT+CIPSTATUS"), ok_reply, 100) ) return false; - readline(100); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return (strcmp(replybuffer, "STATE: CONNECT OK") == 0); -} - -boolean Adafruit_FONA::TCPsend(char *packet, uint8_t len) { - - DEBUG_PRINT(F("AT+CIPSEND=")); - DEBUG_PRINTLN(len); -#ifdef ADAFRUIT_FONA_DEBUG - for (uint16_t i=0; iprint(F("AT+CIPSEND=")); - mySerial->println(len); - readline(); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - if (replybuffer[0] != '>') return false; - - mySerial->write(packet, len); - readline(3000); // wait up to 3 seconds to send the data - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - - return (strcmp(replybuffer, "SEND OK") == 0); -} - -uint16_t Adafruit_FONA::TCPavailable(void) { - uint16_t avail; - - if (! sendParseReply(F("AT+CIPRXGET=4"), F("+CIPRXGET: 4,"), &avail, ',', 0) ) return false; - - - DEBUG_PRINT (avail); DEBUG_PRINTLN(F(" bytes available")); - - - return avail; -} - - -uint16_t Adafruit_FONA::TCPread(uint8_t *buff, uint8_t len) { - uint16_t avail; - - mySerial->print(F("AT+CIPRXGET=2,")); - mySerial->println(len); - readline(); - if (! parseReply(F("+CIPRXGET: 2,"), &avail, ',', 0)) return false; - - readRaw(avail); - -#ifdef ADAFRUIT_FONA_DEBUG - DEBUG_PRINT (avail); DEBUG_PRINTLN(F(" bytes read")); - for (uint8_t i=0;i ")); - DEBUG_PRINT(F("AT+HTTPPARA=\"")); - DEBUG_PRINT(parameter); - DEBUG_PRINTLN('"'); - - - mySerial->print(F("AT+HTTPPARA=\"")); - mySerial->print(parameter); - if (quoted) - mySerial->print(F("\",\"")); - else - mySerial->print(F("\",")); -} - -boolean Adafruit_FONA::HTTP_para_end(boolean quoted) { - if (quoted) - mySerial->println('"'); - else - mySerial->println(); - - return expectReply(ok_reply); -} - -boolean Adafruit_FONA::HTTP_para(FONAFlashStringPtr parameter, - const char *value) { - HTTP_para_start(parameter, true); - mySerial->print(value); - return HTTP_para_end(true); -} - -boolean Adafruit_FONA::HTTP_para(FONAFlashStringPtr parameter, - FONAFlashStringPtr value) { - HTTP_para_start(parameter, true); - mySerial->print(value); - return HTTP_para_end(true); -} - -boolean Adafruit_FONA::HTTP_para(FONAFlashStringPtr parameter, - int32_t value) { - HTTP_para_start(parameter, false); - mySerial->print(value); - return HTTP_para_end(false); -} - -boolean Adafruit_FONA::HTTP_data(uint32_t size, uint32_t maxTime) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); - DEBUG_PRINT(F("AT+HTTPDATA=")); - DEBUG_PRINT(size); - DEBUG_PRINT(','); - DEBUG_PRINTLN(maxTime); - - - mySerial->print(F("AT+HTTPDATA=")); - mySerial->print(size); - mySerial->print(","); - mySerial->println(maxTime); - - return expectReply(F("DOWNLOAD")); -} - -boolean Adafruit_FONA::HTTP_action(uint8_t method, uint16_t *status, - uint16_t *datalen, int32_t timeout) { - // Send request. - if (! sendCheckReply(F("AT+HTTPACTION="), method, ok_reply)) - return false; - - // Parse response status and size. - readline(timeout); - if (! parseReply(F("+HTTPACTION:"), status, ',', 1)) - return false; - if (! parseReply(F("+HTTPACTION:"), datalen, ',', 2)) - return false; - - return true; -} - -boolean Adafruit_FONA::HTTP_readall(uint16_t *datalen) { - getReply(F("AT+HTTPREAD")); - if (! parseReply(F("+HTTPREAD:"), datalen, ',', 0)) - return false; - - return true; -} - -boolean Adafruit_FONA::HTTP_ssl(boolean onoff) { - return sendCheckReply(F("AT+HTTPSSL="), onoff ? 1 : 0, ok_reply); -} - -/********* HTTP HIGH LEVEL FUNCTIONS ***************************/ - -boolean Adafruit_FONA::HTTP_GET_start(char *url, - uint16_t *status, uint16_t *datalen){ - if (! HTTP_setup(url)) - return false; - - // HTTP GET - if (! HTTP_action(FONA_HTTP_GET, status, datalen, 30000)) - return false; - - DEBUG_PRINT(F("Status: ")); DEBUG_PRINTLN(*status); - DEBUG_PRINT(F("Len: ")); DEBUG_PRINTLN(*datalen); - - // HTTP response data - if (! HTTP_readall(datalen)) - return false; - - return true; -} - -/* -boolean Adafruit_FONA_3G::HTTP_GET_start(char *ipaddr, char *path, uint16_t port - uint16_t *status, uint16_t *datalen){ - char send[100] = "AT+CHTTPACT=\""; - char *sendp = send + strlen(send); - memset(sendp, 0, 100 - strlen(send)); - - strcpy(sendp, ipaddr); - sendp+=strlen(ipaddr); - sendp[0] = '\"'; - sendp++; - sendp[0] = ','; - itoa(sendp, port); - getReply(send, 500); - - return; - - if (! HTTP_setup(url)) - - return false; - - // HTTP GET - if (! HTTP_action(FONA_HTTP_GET, status, datalen)) - return false; - - DEBUG_PRINT("Status: "); DEBUG_PRINTLN(*status); - DEBUG_PRINT("Len: "); DEBUG_PRINTLN(*datalen); - - // HTTP response data - if (! HTTP_readall(datalen)) - return false; - - return true; -} -*/ - -void Adafruit_FONA::HTTP_GET_end(void) { - HTTP_term(); -} - -boolean Adafruit_FONA::HTTP_POST_start(char *url, - FONAFlashStringPtr contenttype, - const uint8_t *postdata, uint16_t postdatalen, - uint16_t *status, uint16_t *datalen){ - if (! HTTP_setup(url)) - return false; - - if (! HTTP_para(F("CONTENT"), contenttype)) { - return false; - } - - // HTTP POST data - if (! HTTP_data(postdatalen, 10000)) - return false; - mySerial->write(postdata, postdatalen); - if (! expectReply(ok_reply)) - return false; - - // HTTP POST - if (! HTTP_action(FONA_HTTP_POST, status, datalen)) - return false; - - DEBUG_PRINT(F("Status: ")); DEBUG_PRINTLN(*status); - DEBUG_PRINT(F("Len: ")); DEBUG_PRINTLN(*datalen); - - // HTTP response data - if (! HTTP_readall(datalen)) - return false; - - return true; -} - -void Adafruit_FONA::HTTP_POST_end(void) { - HTTP_term(); -} - -void Adafruit_FONA::setUserAgent(FONAFlashStringPtr useragent) { - this->useragent = useragent; -} - -void Adafruit_FONA::setHTTPSRedirect(boolean onoff) { - httpsredirect = onoff; -} - -/********* HTTP HELPERS ****************************************/ - -boolean Adafruit_FONA::HTTP_setup(char *url) { - // Handle any pending - HTTP_term(); - - // Initialize and set parameters - if (! HTTP_init()) - return false; - if (! HTTP_para(F("CID"), 1)) - return false; - if (! HTTP_para(F("UA"), useragent)) - return false; - if (! HTTP_para(F("URL"), url)) - return false; - - // HTTPS redirect - if (httpsredirect) { - if (! HTTP_para(F("REDIR"),1)) - return false; - - if (! HTTP_ssl(true)) - return false; - } - - return true; -} - -/********* HELPERS *********************************************/ - -boolean Adafruit_FONA::expectReply(FONAFlashStringPtr reply, - uint16_t timeout) { - readline(timeout); - - DEBUG_PRINT(F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return (prog_char_strcmp(replybuffer, (prog_char*)reply) == 0); -} - -/********* LOW LEVEL *******************************************/ - -inline int Adafruit_FONA::available(void) { - return mySerial->available(); -} - -inline size_t Adafruit_FONA::write(uint8_t x) { - return mySerial->write(x); -} - -inline int Adafruit_FONA::read(void) { - return mySerial->read(); -} - -inline int Adafruit_FONA::peek(void) { - return mySerial->peek(); -} - -inline void Adafruit_FONA::flush() { - mySerial->flush(); -} - -void Adafruit_FONA::flushInput() { - // Read all available serial input to flush pending data. - uint16_t timeoutloop = 0; - while (timeoutloop++ < 40) { - while(available()) { - read(); - timeoutloop = 0; // If char was received reset the timer - } - delay(1); - } -} - -uint16_t Adafruit_FONA::readRaw(uint16_t b) { - uint16_t idx = 0; - - while (b && (idx < sizeof(replybuffer)-1)) { - if (mySerial->available()) { - replybuffer[idx] = mySerial->read(); - idx++; - b--; - } - } - replybuffer[idx] = 0; - - return idx; -} - -uint8_t Adafruit_FONA::readline(uint16_t timeout, boolean multiline) { - uint16_t replyidx = 0; - - while (timeout--) { - if (replyidx >= 254) { - //DEBUG_PRINTLN(F("SPACE")); - break; - } - - while(mySerial->available()) { - char c = mySerial->read(); - if (c == '\r') continue; - if (c == 0xA) { - if (replyidx == 0) // the first 0x0A is ignored - continue; - - if (!multiline) { - timeout = 0; // the second 0x0A is the end of the line - break; - } - } - replybuffer[replyidx] = c; - //DEBUG_PRINT(c, HEX); DEBUG_PRINT("#"); DEBUG_PRINTLN(c); - replyidx++; - } - - if (timeout == 0) { - //DEBUG_PRINTLN(F("TIMEOUT")); - break; - } - delay(1); - } - replybuffer[replyidx] = 0; // null term - return replyidx; -} - -uint8_t Adafruit_FONA::getReply(char *send, uint16_t timeout) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN(send); - - - mySerial->println(send); - - uint8_t l = readline(timeout); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return l; -} - -uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr send, uint16_t timeout) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN(send); - - - mySerial->println(send); - - uint8_t l = readline(timeout); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return l; -} - -// Send prefix, suffix, and newline. Return response (and also set replybuffer with response). -uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr prefix, char *suffix, uint16_t timeout) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); DEBUG_PRINTLN(suffix); - - - mySerial->print(prefix); - mySerial->println(suffix); - - uint8_t l = readline(timeout); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return l; -} - -// Send prefix, suffix, and newline. Return response (and also set replybuffer with response). -uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr prefix, int32_t suffix, uint16_t timeout) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); DEBUG_PRINTLN(suffix, DEC); - - - mySerial->print(prefix); - mySerial->println(suffix, DEC); - - uint8_t l = readline(timeout); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return l; -} - -// Send prefix, suffix, suffix2, and newline. Return response (and also set replybuffer with response). -uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr prefix, int32_t suffix1, int32_t suffix2, uint16_t timeout) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); - DEBUG_PRINT(suffix1, DEC); DEBUG_PRINT(','); DEBUG_PRINTLN(suffix2, DEC); - - - mySerial->print(prefix); - mySerial->print(suffix1); - mySerial->print(','); - mySerial->println(suffix2, DEC); - - uint8_t l = readline(timeout); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return l; -} - -// Send prefix, ", suffix, ", and newline. Return response (and also set replybuffer with response). -uint8_t Adafruit_FONA::getReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, uint16_t timeout) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); - DEBUG_PRINT('"'); DEBUG_PRINT(suffix); DEBUG_PRINTLN('"'); - - - mySerial->print(prefix); - mySerial->print('"'); - mySerial->print(suffix); - mySerial->println('"'); - - uint8_t l = readline(timeout); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return l; -} - -boolean Adafruit_FONA::sendCheckReply(char *send, char *reply, uint16_t timeout) { - if (! getReply(send, timeout) ) - return false; -/* - for (uint8_t i=0; i http://www.adafruit.com/products/1946 - ----> http://www.adafruit.com/products/1963 - - These displays use TTL Serial to communicate, 2 pins are required to - interface - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - BSD license, all text above must be included in any redistribution - ****************************************************/ -#ifndef ADAFRUIT_FONA_H -#define ADAFRUIT_FONA_H - -#include "includes/FONAConfig.h" -#include "includes/FONAExtIncludes.h" -#include "includes/platform/FONAPlatform.h" - - - -#define FONA800L 1 -#define FONA800H 6 - -#define FONA808_V1 2 -#define FONA808_V2 3 - -#define FONA3G_A 4 -#define FONA3G_E 5 - -// Uncomment to changed the preferred SMS storage -//#define FONA_PREF_SMS_STORAGE "SM" - -#define FONA_HEADSETAUDIO 0 -#define FONA_EXTAUDIO 1 - -#define FONA_STTONE_DIALTONE 1 -#define FONA_STTONE_BUSY 2 -#define FONA_STTONE_CONGESTION 3 -#define FONA_STTONE_PATHACK 4 -#define FONA_STTONE_DROPPED 5 -#define FONA_STTONE_ERROR 6 -#define FONA_STTONE_CALLWAIT 7 -#define FONA_STTONE_RINGING 8 -#define FONA_STTONE_BEEP 16 -#define FONA_STTONE_POSTONE 17 -#define FONA_STTONE_ERRTONE 18 -#define FONA_STTONE_INDIANDIALTONE 19 -#define FONA_STTONE_USADIALTONE 20 - -#define FONA_DEFAULT_TIMEOUT_MS 500 - -#define FONA_HTTP_GET 0 -#define FONA_HTTP_POST 1 -#define FONA_HTTP_HEAD 2 - -#define FONA_CALL_READY 0 -#define FONA_CALL_FAILED 1 -#define FONA_CALL_UNKNOWN 2 -#define FONA_CALL_RINGING 3 -#define FONA_CALL_INPROGRESS 4 - -class Adafruit_FONA : public FONAStreamType { - public: - Adafruit_FONA(int8_t r); - boolean begin(FONAStreamType &port); - uint8_t type(); - - // Stream - int available(void); - size_t write(uint8_t x); - int read(void); - int peek(void); - void flush(); - - // FONA 3G requirements - boolean setBaudrate(uint16_t baud); - - // RTC - boolean enableRTC(uint8_t i); - boolean readRTC(uint8_t *year, uint8_t *month, uint8_t *date, uint8_t *hr, uint8_t *min, uint8_t *sec); - - // Battery and ADC - boolean getADCVoltage(uint16_t *v); - boolean getBattPercent(uint16_t *p); - boolean getBattVoltage(uint16_t *v); - - // SIM query - uint8_t unlockSIM(char *pin); - uint8_t getSIMCCID(char *ccid); - uint8_t getNetworkStatus(void); - uint8_t getRSSI(void); - - // IMEI - uint8_t getIMEI(char *imei); - - // set Audio output - boolean setAudio(uint8_t a); - boolean setVolume(uint8_t i); - uint8_t getVolume(void); - boolean playToolkitTone(uint8_t t, uint16_t len); - boolean setMicVolume(uint8_t a, uint8_t level); - boolean playDTMF(char tone); - - // FM radio functions. - boolean tuneFMradio(uint16_t station); - boolean FMradio(boolean onoff, uint8_t a = FONA_HEADSETAUDIO); - boolean setFMVolume(uint8_t i); - int8_t getFMVolume(); - int8_t getFMSignalLevel(uint16_t station); - - // SMS handling - boolean setSMSInterrupt(uint8_t i); - uint8_t getSMSInterrupt(void); - int8_t getNumSMS(void); - boolean readSMS(uint8_t i, char *smsbuff, uint16_t max, uint16_t *readsize); - boolean sendSMS(char *smsaddr, char *smsmsg); - boolean deleteSMS(uint8_t i); - boolean getSMSSender(uint8_t i, char *sender, int senderlen); - boolean sendUSSD(char *ussdmsg, char *ussdbuff, uint16_t maxlen, uint16_t *readlen); - - // Time - boolean enableNetworkTimeSync(boolean onoff); - boolean enableNTPTimeSync(boolean onoff, FONAFlashStringPtr ntpserver=0); - boolean getTime(char *buff, uint16_t maxlen); - - // GPRS handling - boolean enableGPRS(boolean onoff); - uint8_t GPRSstate(void); - boolean getGSMLoc(uint16_t *replycode, char *buff, uint16_t maxlen); - boolean getGSMLoc(float *lat, float *lon); - void setGPRSNetworkSettings(FONAFlashStringPtr apn, FONAFlashStringPtr username=0, FONAFlashStringPtr password=0); - - // GPS handling - boolean enableGPS(boolean onoff); - int8_t GPSstatus(void); - uint8_t getGPS(uint8_t arg, char *buffer, uint8_t maxbuff); - boolean getGPS(float *lat, float *lon, float *speed_kph=0, float *heading=0, float *altitude=0); - boolean enableGPSNMEA(uint8_t nmea); - - // TCP raw connections - boolean TCPconnect(char *server, uint16_t port); - boolean TCPclose(void); - boolean TCPconnected(void); - boolean TCPsend(char *packet, uint8_t len); - uint16_t TCPavailable(void); - uint16_t TCPread(uint8_t *buff, uint8_t len); - - // HTTP low level interface (maps directly to SIM800 commands). - boolean HTTP_init(); - boolean HTTP_term(); - void HTTP_para_start(FONAFlashStringPtr parameter, boolean quoted = true); - boolean HTTP_para_end(boolean quoted = true); - boolean HTTP_para(FONAFlashStringPtr parameter, const char *value); - boolean HTTP_para(FONAFlashStringPtr parameter, FONAFlashStringPtr value); - boolean HTTP_para(FONAFlashStringPtr parameter, int32_t value); - boolean HTTP_data(uint32_t size, uint32_t maxTime=10000); - boolean HTTP_action(uint8_t method, uint16_t *status, uint16_t *datalen, int32_t timeout = 10000); - boolean HTTP_readall(uint16_t *datalen); - boolean HTTP_ssl(boolean onoff); - - // HTTP high level interface (easier to use, less flexible). - boolean HTTP_GET_start(char *url, uint16_t *status, uint16_t *datalen); - void HTTP_GET_end(void); - boolean HTTP_POST_start(char *url, FONAFlashStringPtr contenttype, const uint8_t *postdata, uint16_t postdatalen, uint16_t *status, uint16_t *datalen); - void HTTP_POST_end(void); - void setUserAgent(FONAFlashStringPtr useragent); - - // HTTPS - void setHTTPSRedirect(boolean onoff); - - // PWM (buzzer) - boolean setPWM(uint16_t period, uint8_t duty = 50); - - // Phone calls - boolean callPhone(char *phonenum); - uint8_t getCallStatus(void); - boolean hangUp(void); - boolean pickUp(void); - boolean callerIdNotification(boolean enable, uint8_t interrupt = 0); - boolean incomingCallNumber(char* phonenum); - - // Helper functions to verify responses. - boolean expectReply(FONAFlashStringPtr reply, uint16_t timeout = 10000); - boolean sendCheckReply(char *send, char *reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - boolean sendCheckReply(FONAFlashStringPtr send, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - boolean sendCheckReply(char* send, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - - - protected: - int8_t _rstpin; - uint8_t _type; - - char replybuffer[255]; - FONAFlashStringPtr apn; - FONAFlashStringPtr apnusername; - FONAFlashStringPtr apnpassword; - boolean httpsredirect; - FONAFlashStringPtr useragent; - FONAFlashStringPtr ok_reply; - - // HTTP helpers - boolean HTTP_setup(char *url); - - void flushInput(); - uint16_t readRaw(uint16_t b); - uint8_t readline(uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS, boolean multiline = false); - uint8_t getReply(char *send, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - uint8_t getReply(FONAFlashStringPtr send, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - uint8_t getReply(FONAFlashStringPtr prefix, char *suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - uint8_t getReply(FONAFlashStringPtr prefix, int32_t suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - uint8_t getReply(FONAFlashStringPtr prefix, int32_t suffix1, int32_t suffix2, uint16_t timeout); // Don't set default value or else function call is ambiguous. - uint8_t getReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - - boolean sendCheckReply(FONAFlashStringPtr prefix, char *suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - boolean sendCheckReply(FONAFlashStringPtr prefix, int32_t suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - boolean sendCheckReply(FONAFlashStringPtr prefix, int32_t suffix, int32_t suffix2, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - boolean sendCheckReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - - - boolean parseReply(FONAFlashStringPtr toreply, - uint16_t *v, char divider = ',', uint8_t index=0); - boolean parseReply(FONAFlashStringPtr toreply, - char *v, char divider = ',', uint8_t index=0); - boolean parseReplyQuoted(FONAFlashStringPtr toreply, - char *v, int maxlen, char divider, uint8_t index); - - boolean sendParseReply(FONAFlashStringPtr tosend, - FONAFlashStringPtr toreply, - uint16_t *v, char divider = ',', uint8_t index=0); - - static boolean _incomingCall; - static void onIncomingCall(); - - FONAStreamType *mySerial; -}; - -class Adafruit_FONA_3G : public Adafruit_FONA { - - public: - Adafruit_FONA_3G (int8_t r) : Adafruit_FONA(r) { _type = FONA3G_A; } - - boolean getBattVoltage(uint16_t *v); - boolean playToolkitTone(uint8_t t, uint16_t len); - boolean hangUp(void); - boolean pickUp(void); - boolean enableGPRS(boolean onoff); - boolean enableGPS(boolean onoff); - - protected: - boolean parseReply(FONAFlashStringPtr toreply, - float *f, char divider, uint8_t index); - - boolean sendParseReply(FONAFlashStringPtr tosend, - FONAFlashStringPtr toreply, - float *f, char divider = ',', uint8_t index=0); -}; - -#endif diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/README.md b/feather_sensor_lte/libraries/Adafruit_FONA_Library/README.md deleted file mode 100644 index 73452ca..0000000 --- a/feather_sensor_lte/libraries/Adafruit_FONA_Library/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Adafruit FONA Library [![Build Status](https://secure.travis-ci.org/adafruit/Adafruit_FONA_Library.svg?branch=master)](https://travis-ci.org/adafruit/Adafruit_FONA_Library) - -**This library requires Arduino v1.0.6 or higher** - -This is a library for the Adafruit FONA Cellular GSM Breakouts etc - -Designed specifically to work with the Adafruit FONA Breakout - * https://www.adafruit.com/products/1946 - * https://www.adafruit.com/products/1963 - * http://www.adafruit.com/products/2468 - * http://www.adafruit.com/products/2542 - -These modules use TTL Serial to communicate, 2 pins are required to interface - -Adafruit invests time and resources providing this open source code, -please support Adafruit and open-source hardware by purchasing -products from Adafruit! - -Check out the links above for our tutorials and wiring diagrams - -Written by Limor Fried/Ladyada for Adafruit Industries. -BSD license, all text above must be included in any redistribution -With updates from Samy Kamkar - -To download. click the DOWNLOADS button in the top right corner, rename the uncompressed folder Adafruit_FONA -Check that the Adafruit_FONA folder contains Adafruit_FONA.cpp and Adafruit_FONA.h - -Place the Adafruit_FONA library folder your *arduinosketchfolder*/libraries/ folder. -You may need to create the libraries subfolder if its your first library. Restart the IDE. diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/.esp8266.test.skip b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/.esp8266.test.skip deleted file mode 100644 index e69de29..0000000 diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino deleted file mode 100644 index b0be4c5..0000000 --- a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino +++ /dev/null @@ -1,77 +0,0 @@ -/*************************************************** - This is an example for our Adafruit FONA Cellular Module - since the FONA 3G does not do auto-baud very well, this demo - fixes the baud rate to 4800 from the default 115200 - - Designed specifically to work with the Adafruit FONA 3G - ----> http://www.adafruit.com/products/2691 - ----> http://www.adafruit.com/products/2687 - - These cellular modules use TTL Serial to communicate, 2 pins are - required to interface - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - BSD license, all text above must be included in any redistribution - ****************************************************/ - -#include "Adafruit_FONA.h" - -#define FONA_RX 2 -#define FONA_TX 3 -#define FONA_RST 4 - -// this is a large buffer for replies -char replybuffer[255]; - -// We default to using software serial. If you want to use hardware serial -// (because softserial isnt supported) comment out the following three lines -// and uncomment the HardwareSerial line -#include -SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); -SoftwareSerial *fonaSerial = &fonaSS; - -// Hardware serial is also possible! -// HardwareSerial *fonaSerial = &Serial1; - -Adafruit_FONA fona = Adafruit_FONA(FONA_RST); - -uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); - -void setup() { - while (!Serial); - - Serial.begin(115200); - Serial.println(F("FONA set baudrate")); - - Serial.println(F("First trying 115200 baud")); - // start at 115200 baud - fonaSerial->begin(115200); - fona.begin(*fonaSerial); - - // send the command to reset the baud rate to 4800 - fona.setBaudrate(4800); - - // restart with 4800 baud - fonaSerial->begin(4800); - Serial.println(F("Initializing @ 4800 baud...")); - - if (! fona.begin(*fonaSerial)) { - Serial.println(F("Couldn't find FONA")); - while(1); - } - Serial.println(F("FONA is OK")); - - // Print module IMEI number. - char imei[15] = {0}; // MUST use a 16 character buffer for IMEI! - uint8_t imeiLen = fona.getIMEI(imei); - if (imeiLen > 0) { - Serial.print("Module IMEI: "); Serial.println(imei); - } - -} - -void loop() { -} \ No newline at end of file diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/.esp8266.test.skip b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/.esp8266.test.skip deleted file mode 100644 index e69de29..0000000 diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino deleted file mode 100644 index 7201641..0000000 --- a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino +++ /dev/null @@ -1,131 +0,0 @@ -/*************************************************** - This is an example for our Adafruit FONA Cellular Module - - Designed specifically to work with the Adafruit FONA - ----> http://www.adafruit.com/products/1946 - ----> http://www.adafruit.com/products/1963 - ----> http://www.adafruit.com/products/2468 - ----> http://www.adafruit.com/products/2542 - - These cellular modules use TTL Serial to communicate, 2 pins are - required to interface - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - BSD license, all text above must be included in any redistribution - ****************************************************/ - -/* -THIS CODE IS STILL IN PROGRESS! - -Open up the serial console on the Arduino at 115200 baud to interact with FONA - - -This code will receive an SMS, identify the sender's phone number, and automatically send a response - -For use with FONA 800 & 808, not 3G -*/ - -#include "Adafruit_FONA.h" - -#define FONA_RX 2 -#define FONA_TX 3 -#define FONA_RST 4 - -// this is a large buffer for replies -char replybuffer[255]; - -// We default to using software serial. If you want to use hardware serial -// (because softserial isnt supported) comment out the following three lines -// and uncomment the HardwareSerial line -#include -SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); -SoftwareSerial *fonaSerial = &fonaSS; - -// Hardware serial is also possible! -// HardwareSerial *fonaSerial = &Serial1; - -Adafruit_FONA fona = Adafruit_FONA(FONA_RST); - -uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); - -void setup() { - while (!Serial); - - Serial.begin(115200); - Serial.println(F("FONA SMS caller ID test")); - Serial.println(F("Initializing....(May take 3 seconds)")); - - // make it slow so its easy to read! - fonaSerial->begin(4800); - if (! fona.begin(*fonaSerial)) { - Serial.println(F("Couldn't find FONA")); - while(1); - } - Serial.println(F("FONA is OK")); - - // Print SIM card IMEI number. - char imei[15] = {0}; // MUST use a 16 character buffer for IMEI! - uint8_t imeiLen = fona.getIMEI(imei); - if (imeiLen > 0) { - Serial.print("SIM card IMEI: "); Serial.println(imei); - } - - Serial.println("FONA Ready"); -} - - -char fonaInBuffer[64]; //for notifications from the FONA - -void loop() { - - char* bufPtr = fonaInBuffer; //handy buffer pointer - - if (fona.available()) //any data available from the FONA? - { - int slot = 0; //this will be the slot number of the SMS - int charCount = 0; - //Read the notification into fonaInBuffer - do { - *bufPtr = fona.read(); - Serial.write(*bufPtr); - delay(1); - } while ((*bufPtr++ != '\n') && (fona.available()) && (++charCount < (sizeof(fonaInBuffer)-1))); - - //Add a terminal NULL to the notification string - *bufPtr = 0; - - //Scan the notification string for an SMS received notification. - // If it's an SMS message, we'll get the slot number in 'slot' - if (1 == sscanf(fonaInBuffer, "+CMTI: \"SM\",%d", &slot)) { - Serial.print("slot: "); Serial.println(slot); - - char callerIDbuffer[32]; //we'll store the SMS sender number in here - - // Retrieve SMS sender address/phone number. - if (! fona.getSMSSender(slot, callerIDbuffer, 31)) { - Serial.println("Didn't find SMS message in slot!"); - } - Serial.print(F("FROM: ")); Serial.println(callerIDbuffer); - - //Send back an automatic response - Serial.println("Sending reponse..."); - if (!fona.sendSMS(callerIDbuffer, "Hey, I got your text!")) { - Serial.println(F("Failed")); - } else { - Serial.println(F("Sent!")); - } - - // delete the original msg after it is processed - // otherwise, we will fill up all the slots - // and then we won't be able to receive SMS anymore - if (fona.deleteSMS(slot)) { - Serial.println(F("OK!")); - } else { - Serial.println(F("Couldn't delete")); - } - } - } -} diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/.esp8266.test.skip b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/.esp8266.test.skip deleted file mode 100644 index e69de29..0000000 diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino deleted file mode 100644 index 1b27732..0000000 --- a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino +++ /dev/null @@ -1,886 +0,0 @@ -/*************************************************** - This is an example for our Adafruit FONA Cellular Module - - Designed specifically to work with the Adafruit FONA - ----> http://www.adafruit.com/products/1946 - ----> http://www.adafruit.com/products/1963 - ----> http://www.adafruit.com/products/2468 - ----> http://www.adafruit.com/products/2542 - - These cellular modules use TTL Serial to communicate, 2 pins are - required to interface - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - BSD license, all text above must be included in any redistribution - ****************************************************/ - -/* -THIS CODE IS STILL IN PROGRESS! - -Open up the serial console on the Arduino at 115200 baud to interact with FONA - -Note that if you need to set a GPRS APN, username, and password scroll down to -the commented section below at the end of the setup() function. -*/ -#include "Adafruit_FONA.h" - -#define FONA_RX 2 -#define FONA_TX 3 -#define FONA_RST 4 - -// this is a large buffer for replies -char replybuffer[255]; - -// We default to using software serial. If you want to use hardware serial -// (because softserial isnt supported) comment out the following three lines -// and uncomment the HardwareSerial line -#include -SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); -SoftwareSerial *fonaSerial = &fonaSS; - -// Hardware serial is also possible! -// HardwareSerial *fonaSerial = &Serial1; - -// Use this for FONA 800 and 808s -Adafruit_FONA fona = Adafruit_FONA(FONA_RST); -// Use this one for FONA 3G -//Adafruit_FONA_3G fona = Adafruit_FONA_3G(FONA_RST); - -uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); - -uint8_t type; - -void setup() { - while (!Serial); - - Serial.begin(115200); - Serial.println(F("FONA basic test")); - Serial.println(F("Initializing....(May take 3 seconds)")); - - fonaSerial->begin(4800); - if (! fona.begin(*fonaSerial)) { - Serial.println(F("Couldn't find FONA")); - while (1); - } - type = fona.type(); - Serial.println(F("FONA is OK")); - Serial.print(F("Found ")); - switch (type) { - case FONA800L: - Serial.println(F("FONA 800L")); break; - case FONA800H: - Serial.println(F("FONA 800H")); break; - case FONA808_V1: - Serial.println(F("FONA 808 (v1)")); break; - case FONA808_V2: - Serial.println(F("FONA 808 (v2)")); break; - case FONA3G_A: - Serial.println(F("FONA 3G (American)")); break; - case FONA3G_E: - Serial.println(F("FONA 3G (European)")); break; - default: - Serial.println(F("???")); break; - } - - // Print module IMEI number. - char imei[15] = {0}; // MUST use a 16 character buffer for IMEI! - uint8_t imeiLen = fona.getIMEI(imei); - if (imeiLen > 0) { - Serial.print("Module IMEI: "); Serial.println(imei); - } - - // Optionally configure a GPRS APN, username, and password. - // You might need to do this to access your network's GPRS/data - // network. Contact your provider for the exact APN, username, - // and password values. Username and password are optional and - // can be removed, but APN is required. - //fona.setGPRSNetworkSettings(F("your APN"), F("your username"), F("your password")); - - // Optionally configure HTTP gets to follow redirects over SSL. - // Default is not to follow SSL redirects, however if you uncomment - // the following line then redirects over SSL will be followed. - //fona.setHTTPSRedirect(true); - - printMenu(); -} - -void printMenu(void) { - Serial.println(F("-------------------------------------")); - Serial.println(F("[?] Print this menu")); - Serial.println(F("[a] read the ADC 2.8V max (FONA800 & 808)")); - Serial.println(F("[b] read the Battery V and % charged")); - Serial.println(F("[C] read the SIM CCID")); - Serial.println(F("[U] Unlock SIM with PIN code")); - Serial.println(F("[i] read RSSI")); - Serial.println(F("[n] get Network status")); - Serial.println(F("[v] set audio Volume")); - Serial.println(F("[V] get Volume")); - Serial.println(F("[H] set Headphone audio (FONA800 & 808)")); - Serial.println(F("[e] set External audio (FONA800 & 808)")); - Serial.println(F("[T] play audio Tone")); - Serial.println(F("[P] PWM/Buzzer out (FONA800 & 808)")); - - // FM (SIM800 only!) - Serial.println(F("[f] tune FM radio (FONA800)")); - Serial.println(F("[F] turn off FM (FONA800)")); - Serial.println(F("[m] set FM volume (FONA800)")); - Serial.println(F("[M] get FM volume (FONA800)")); - Serial.println(F("[q] get FM station signal level (FONA800)")); - - // Phone - Serial.println(F("[c] make phone Call")); - Serial.println(F("[A] get call status")); - Serial.println(F("[h] Hang up phone")); - Serial.println(F("[p] Pick up phone")); - - // SMS - Serial.println(F("[N] Number of SMSs")); - Serial.println(F("[r] Read SMS #")); - Serial.println(F("[R] Read All SMS")); - Serial.println(F("[d] Delete SMS #")); - Serial.println(F("[s] Send SMS")); - Serial.println(F("[u] Send USSD")); - - // Time - Serial.println(F("[y] Enable network time sync (FONA 800 & 808)")); - Serial.println(F("[Y] Enable NTP time sync (GPRS FONA 800 & 808)")); - Serial.println(F("[t] Get network time")); - - // GPRS - Serial.println(F("[G] Enable GPRS")); - Serial.println(F("[g] Disable GPRS")); - Serial.println(F("[l] Query GSMLOC (GPRS)")); - Serial.println(F("[w] Read webpage (GPRS)")); - Serial.println(F("[W] Post to website (GPRS)")); - - // GPS - if ((type == FONA3G_A) || (type == FONA3G_E) || (type == FONA808_V1) || (type == FONA808_V2)) { - Serial.println(F("[O] Turn GPS on (FONA 808 & 3G)")); - Serial.println(F("[o] Turn GPS off (FONA 808 & 3G)")); - Serial.println(F("[L] Query GPS location (FONA 808 & 3G)")); - if (type == FONA808_V1) { - Serial.println(F("[x] GPS fix status (FONA808 v1 only)")); - } - Serial.println(F("[E] Raw NMEA out (FONA808)")); - } - - Serial.println(F("[S] create Serial passthru tunnel")); - Serial.println(F("-------------------------------------")); - Serial.println(F("")); - -} -void loop() { - Serial.print(F("FONA> ")); - while (! Serial.available() ) { - if (fona.available()) { - Serial.write(fona.read()); - } - } - - char command = Serial.read(); - Serial.println(command); - - - switch (command) { - case '?': { - printMenu(); - break; - } - - case 'a': { - // read the ADC - uint16_t adc; - if (! fona.getADCVoltage(&adc)) { - Serial.println(F("Failed to read ADC")); - } else { - Serial.print(F("ADC = ")); Serial.print(adc); Serial.println(F(" mV")); - } - break; - } - - case 'b': { - // read the battery voltage and percentage - uint16_t vbat; - if (! fona.getBattVoltage(&vbat)) { - Serial.println(F("Failed to read Batt")); - } else { - Serial.print(F("VBat = ")); Serial.print(vbat); Serial.println(F(" mV")); - } - - - if (! fona.getBattPercent(&vbat)) { - Serial.println(F("Failed to read Batt")); - } else { - Serial.print(F("VPct = ")); Serial.print(vbat); Serial.println(F("%")); - } - - break; - } - - case 'U': { - // Unlock the SIM with a PIN code - char PIN[5]; - flushSerial(); - Serial.println(F("Enter 4-digit PIN")); - readline(PIN, 3); - Serial.println(PIN); - Serial.print(F("Unlocking SIM card: ")); - if (! fona.unlockSIM(PIN)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - - case 'C': { - // read the CCID - fona.getSIMCCID(replybuffer); // make sure replybuffer is at least 21 bytes! - Serial.print(F("SIM CCID = ")); Serial.println(replybuffer); - break; - } - - case 'i': { - // read the RSSI - uint8_t n = fona.getRSSI(); - int8_t r; - - Serial.print(F("RSSI = ")); Serial.print(n); Serial.print(": "); - if (n == 0) r = -115; - if (n == 1) r = -111; - if (n == 31) r = -52; - if ((n >= 2) && (n <= 30)) { - r = map(n, 2, 30, -110, -54); - } - Serial.print(r); Serial.println(F(" dBm")); - - break; - } - - case 'n': { - // read the network/cellular status - uint8_t n = fona.getNetworkStatus(); - Serial.print(F("Network status ")); - Serial.print(n); - Serial.print(F(": ")); - if (n == 0) Serial.println(F("Not registered")); - if (n == 1) Serial.println(F("Registered (home)")); - if (n == 2) Serial.println(F("Not registered (searching)")); - if (n == 3) Serial.println(F("Denied")); - if (n == 4) Serial.println(F("Unknown")); - if (n == 5) Serial.println(F("Registered roaming")); - break; - } - - /*** Audio ***/ - case 'v': { - // set volume - flushSerial(); - if ( (type == FONA3G_A) || (type == FONA3G_E) ) { - Serial.print(F("Set Vol [0-8] ")); - } else { - Serial.print(F("Set Vol % [0-100] ")); - } - uint8_t vol = readnumber(); - Serial.println(); - if (! fona.setVolume(vol)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - - case 'V': { - uint8_t v = fona.getVolume(); - Serial.print(v); - if ( (type == FONA3G_A) || (type == FONA3G_E) ) { - Serial.println(" / 8"); - } else { - Serial.println("%"); - } - break; - } - - case 'H': { - // Set Headphone output - if (! fona.setAudio(FONA_HEADSETAUDIO)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - fona.setMicVolume(FONA_HEADSETAUDIO, 15); - break; - } - case 'e': { - // Set External output - if (! fona.setAudio(FONA_EXTAUDIO)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - - fona.setMicVolume(FONA_EXTAUDIO, 10); - break; - } - - case 'T': { - // play tone - flushSerial(); - Serial.print(F("Play tone #")); - uint8_t kittone = readnumber(); - Serial.println(); - // play for 1 second (1000 ms) - if (! fona.playToolkitTone(kittone, 1000)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - - /*** FM Radio ***/ - - case 'f': { - // get freq - flushSerial(); - Serial.print(F("FM Freq (eg 1011 == 101.1 MHz): ")); - uint16_t station = readnumber(); - Serial.println(); - // FM radio ON using headset - if (fona.FMradio(true, FONA_HEADSETAUDIO)) { - Serial.println(F("Opened")); - } - if (! fona.tuneFMradio(station)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("Tuned")); - } - break; - } - case 'F': { - // FM radio off - if (! fona.FMradio(false)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - case 'm': { - // Set FM volume. - flushSerial(); - Serial.print(F("Set FM Vol [0-6]:")); - uint8_t vol = readnumber(); - Serial.println(); - if (!fona.setFMVolume(vol)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - case 'M': { - // Get FM volume. - uint8_t fmvol = fona.getFMVolume(); - if (fmvol < 0) { - Serial.println(F("Failed")); - } else { - Serial.print(F("FM volume: ")); - Serial.println(fmvol, DEC); - } - break; - } - case 'q': { - // Get FM station signal level (in decibels). - flushSerial(); - Serial.print(F("FM Freq (eg 1011 == 101.1 MHz): ")); - uint16_t station = readnumber(); - Serial.println(); - int8_t level = fona.getFMSignalLevel(station); - if (level < 0) { - Serial.println(F("Failed! Make sure FM radio is on (tuned to station).")); - } else { - Serial.print(F("Signal level (dB): ")); - Serial.println(level, DEC); - } - break; - } - - /*** PWM ***/ - - case 'P': { - // PWM Buzzer output @ 2KHz max - flushSerial(); - Serial.print(F("PWM Freq, 0 = Off, (1-2000): ")); - uint16_t freq = readnumber(); - Serial.println(); - if (! fona.setPWM(freq)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - - /*** Call ***/ - case 'c': { - // call a phone! - char number[30]; - flushSerial(); - Serial.print(F("Call #")); - readline(number, 30); - Serial.println(); - Serial.print(F("Calling ")); Serial.println(number); - if (!fona.callPhone(number)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("Sent!")); - } - - break; - } - case 'A': { - // get call status - int8_t callstat = fona.getCallStatus(); - switch (callstat) { - case 0: Serial.println(F("Ready")); break; - case 1: Serial.println(F("Could not get status")); break; - case 3: Serial.println(F("Ringing (incoming)")); break; - case 4: Serial.println(F("Ringing/in progress (outgoing)")); break; - default: Serial.println(F("Unknown")); break; - } - break; - } - - case 'h': { - // hang up! - if (! fona.hangUp()) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - - case 'p': { - // pick up! - if (! fona.pickUp()) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - - /*** SMS ***/ - - case 'N': { - // read the number of SMS's! - int8_t smsnum = fona.getNumSMS(); - if (smsnum < 0) { - Serial.println(F("Could not read # SMS")); - } else { - Serial.print(smsnum); - Serial.println(F(" SMS's on SIM card!")); - } - break; - } - case 'r': { - // read an SMS - flushSerial(); - Serial.print(F("Read #")); - uint8_t smsn = readnumber(); - Serial.print(F("\n\rReading SMS #")); Serial.println(smsn); - - // Retrieve SMS sender address/phone number. - if (! fona.getSMSSender(smsn, replybuffer, 250)) { - Serial.println("Failed!"); - break; - } - Serial.print(F("FROM: ")); Serial.println(replybuffer); - - // Retrieve SMS value. - uint16_t smslen; - if (! fona.readSMS(smsn, replybuffer, 250, &smslen)) { // pass in buffer and max len! - Serial.println("Failed!"); - break; - } - Serial.print(F("***** SMS #")); Serial.print(smsn); - Serial.print(" ("); Serial.print(smslen); Serial.println(F(") bytes *****")); - Serial.println(replybuffer); - Serial.println(F("*****")); - - break; - } - case 'R': { - // read all SMS - int8_t smsnum = fona.getNumSMS(); - uint16_t smslen; - int8_t smsn; - - if ( (type == FONA3G_A) || (type == FONA3G_E) ) { - smsn = 0; // zero indexed - smsnum--; - } else { - smsn = 1; // 1 indexed - } - - for ( ; smsn <= smsnum; smsn++) { - Serial.print(F("\n\rReading SMS #")); Serial.println(smsn); - if (!fona.readSMS(smsn, replybuffer, 250, &smslen)) { // pass in buffer and max len! - Serial.println(F("Failed!")); - break; - } - // if the length is zero, its a special case where the index number is higher - // so increase the max we'll look at! - if (smslen == 0) { - Serial.println(F("[empty slot]")); - smsnum++; - continue; - } - - Serial.print(F("***** SMS #")); Serial.print(smsn); - Serial.print(" ("); Serial.print(smslen); Serial.println(F(") bytes *****")); - Serial.println(replybuffer); - Serial.println(F("*****")); - } - break; - } - - case 'd': { - // delete an SMS - flushSerial(); - Serial.print(F("Delete #")); - uint8_t smsn = readnumber(); - - Serial.print(F("\n\rDeleting SMS #")); Serial.println(smsn); - if (fona.deleteSMS(smsn)) { - Serial.println(F("OK!")); - } else { - Serial.println(F("Couldn't delete")); - } - break; - } - - case 's': { - // send an SMS! - char sendto[21], message[141]; - flushSerial(); - Serial.print(F("Send to #")); - readline(sendto, 20); - Serial.println(sendto); - Serial.print(F("Type out one-line message (140 char): ")); - readline(message, 140); - Serial.println(message); - if (!fona.sendSMS(sendto, message)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("Sent!")); - } - - break; - } - - case 'u': { - // send a USSD! - char message[141]; - flushSerial(); - Serial.print(F("Type out one-line message (140 char): ")); - readline(message, 140); - Serial.println(message); - - uint16_t ussdlen; - if (!fona.sendUSSD(message, replybuffer, 250, &ussdlen)) { // pass in buffer and max len! - Serial.println(F("Failed")); - } else { - Serial.println(F("Sent!")); - Serial.print(F("***** USSD Reply")); - Serial.print(" ("); Serial.print(ussdlen); Serial.println(F(") bytes *****")); - Serial.println(replybuffer); - Serial.println(F("*****")); - } - } - - /*** Time ***/ - - case 'y': { - // enable network time sync - if (!fona.enableNetworkTimeSync(true)) - Serial.println(F("Failed to enable")); - break; - } - - case 'Y': { - // enable NTP time sync - if (!fona.enableNTPTimeSync(true, F("pool.ntp.org"))) - Serial.println(F("Failed to enable")); - break; - } - - case 't': { - // read the time - char buffer[23]; - - fona.getTime(buffer, 23); // make sure replybuffer is at least 23 bytes! - Serial.print(F("Time = ")); Serial.println(buffer); - break; - } - - - /*********************************** GPS (SIM808 only) */ - - case 'o': { - // turn GPS off - if (!fona.enableGPS(false)) - Serial.println(F("Failed to turn off")); - break; - } - case 'O': { - // turn GPS on - if (!fona.enableGPS(true)) - Serial.println(F("Failed to turn on")); - break; - } - case 'x': { - int8_t stat; - // check GPS fix - stat = fona.GPSstatus(); - if (stat < 0) - Serial.println(F("Failed to query")); - if (stat == 0) Serial.println(F("GPS off")); - if (stat == 1) Serial.println(F("No fix")); - if (stat == 2) Serial.println(F("2D fix")); - if (stat == 3) Serial.println(F("3D fix")); - break; - } - - case 'L': { - // check for GPS location - char gpsdata[120]; - fona.getGPS(0, gpsdata, 120); - if (type == FONA808_V1) - Serial.println(F("Reply in format: mode,longitude,latitude,altitude,utctime(yyyymmddHHMMSS),ttff,satellites,speed,course")); - else - Serial.println(F("Reply in format: mode,fixstatus,utctime(yyyymmddHHMMSS),latitude,longitude,altitude,speed,course,fixmode,reserved1,HDOP,PDOP,VDOP,reserved2,view_satellites,used_satellites,reserved3,C/N0max,HPA,VPA")); - Serial.println(gpsdata); - - break; - } - - case 'E': { - flushSerial(); - if (type == FONA808_V1) { - Serial.print(F("GPS NMEA output sentences (0 = off, 34 = RMC+GGA, 255 = all)")); - } else { - Serial.print(F("On (1) or Off (0)? ")); - } - uint8_t nmeaout = readnumber(); - - // turn on NMEA output - fona.enableGPSNMEA(nmeaout); - - break; - } - - /*********************************** GPRS */ - - case 'g': { - // turn GPRS off - if (!fona.enableGPRS(false)) - Serial.println(F("Failed to turn off")); - break; - } - case 'G': { - // turn GPRS on - if (!fona.enableGPRS(true)) - Serial.println(F("Failed to turn on")); - break; - } - case 'l': { - // check for GSMLOC (requires GPRS) - uint16_t returncode; - - if (!fona.getGSMLoc(&returncode, replybuffer, 250)) - Serial.println(F("Failed!")); - if (returncode == 0) { - Serial.println(replybuffer); - } else { - Serial.print(F("Fail code #")); Serial.println(returncode); - } - - break; - } - case 'w': { - // read website URL - uint16_t statuscode; - int16_t length; - char url[80]; - - flushSerial(); - Serial.println(F("NOTE: in beta! Use small webpages to read!")); - Serial.println(F("URL to read (e.g. www.adafruit.com/testwifi/index.html):")); - Serial.print(F("http://")); readline(url, 79); - Serial.println(url); - - Serial.println(F("****")); - if (!fona.HTTP_GET_start(url, &statuscode, (uint16_t *)&length)) { - Serial.println("Failed!"); - break; - } - while (length > 0) { - while (fona.available()) { - char c = fona.read(); - - // Serial.write is too slow, we'll write directly to Serial register! -#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) - loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data register empty. */ - UDR0 = c; -#else - Serial.write(c); -#endif - length--; - if (! length) break; - } - } - Serial.println(F("\n****")); - fona.HTTP_GET_end(); - break; - } - - case 'W': { - // Post data to website - uint16_t statuscode; - int16_t length; - char url[80]; - char data[80]; - - flushSerial(); - Serial.println(F("NOTE: in beta! Use simple websites to post!")); - Serial.println(F("URL to post (e.g. httpbin.org/post):")); - Serial.print(F("http://")); readline(url, 79); - Serial.println(url); - Serial.println(F("Data to post (e.g. \"foo\" or \"{\"simple\":\"json\"}\"):")); - readline(data, 79); - Serial.println(data); - - Serial.println(F("****")); - if (!fona.HTTP_POST_start(url, F("text/plain"), (uint8_t *) data, strlen(data), &statuscode, (uint16_t *)&length)) { - Serial.println("Failed!"); - break; - } - while (length > 0) { - while (fona.available()) { - char c = fona.read(); - -#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) - loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data register empty. */ - UDR0 = c; -#else - Serial.write(c); -#endif - - length--; - if (! length) break; - } - } - Serial.println(F("\n****")); - fona.HTTP_POST_end(); - break; - } - /*****************************************/ - - case 'S': { - Serial.println(F("Creating SERIAL TUBE")); - while (1) { - while (Serial.available()) { - delay(1); - fona.write(Serial.read()); - } - if (fona.available()) { - Serial.write(fona.read()); - } - } - break; - } - - default: { - Serial.println(F("Unknown command")); - printMenu(); - break; - } - } - // flush input - flushSerial(); - while (fona.available()) { - Serial.write(fona.read()); - } - -} - -void flushSerial() { - while (Serial.available()) - Serial.read(); -} - -char readBlocking() { - while (!Serial.available()); - return Serial.read(); -} -uint16_t readnumber() { - uint16_t x = 0; - char c; - while (! isdigit(c = readBlocking())) { - //Serial.print(c); - } - Serial.print(c); - x = c - '0'; - while (isdigit(c = readBlocking())) { - Serial.print(c); - x *= 10; - x += c - '0'; - } - return x; -} - -uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout) { - uint16_t buffidx = 0; - boolean timeoutvalid = true; - if (timeout == 0) timeoutvalid = false; - - while (true) { - if (buffidx > maxbuff) { - //Serial.println(F("SPACE")); - break; - } - - while (Serial.available()) { - char c = Serial.read(); - - //Serial.print(c, HEX); Serial.print("#"); Serial.println(c); - - if (c == '\r') continue; - if (c == 0xA) { - if (buffidx == 0) // the first 0x0A is ignored - continue; - - timeout = 0; // the second 0x0A is the end of the line - timeoutvalid = true; - break; - } - buff[buffidx] = c; - buffidx++; - } - - if (timeoutvalid && timeout == 0) { - //Serial.println(F("TIMEOUT")); - break; - } - delay(1); - } - buff[buffidx] = 0; // null term - return buffidx; -} diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/GPS/.esp8266.test.skip b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/GPS/.esp8266.test.skip deleted file mode 100644 index e69de29..0000000 diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino deleted file mode 100644 index cce63d5..0000000 --- a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino +++ /dev/null @@ -1,112 +0,0 @@ -/** - * ___ ___ _ _ _ ___ __ ___ ___ ___ ___ - * | __/ _ \| \| | /_\ ( _ )/ \( _ ) / __| _ \/ __| - * | _| (_) | .` |/ _ \ / _ \ () / _ \ | (_ | _/\__ \ - * |_| \___/|_|\_/_/ \_\ \___/\__/\___/ \___|_| |___/ - * - * This example is meant to work with the Adafruit - * FONA 808 or 3G Shield or Breakout - * - * Copyright: 2015 Adafruit - * Author: Todd Treece - * Licence: MIT - * - */ -#include "Adafruit_FONA.h" - -// standard pins for the shield, adjust as necessary -#define FONA_RX 2 -#define FONA_TX 3 -#define FONA_RST 4 - -// We default to using software serial. If you want to use hardware serial -// (because softserial isnt supported) comment out the following three lines -// and uncomment the HardwareSerial line -#include -SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); -SoftwareSerial *fonaSerial = &fonaSS; - -// Hardware serial is also possible! -// HardwareSerial *fonaSerial = &Serial1; - -Adafruit_FONA fona = Adafruit_FONA(FONA_RST); - -// Have a FONA 3G? use this object type instead -//Adafruit_FONA_3G fona = Adafruit_FONA_3G(FONA_RST); - - -void setup() { - - while (! Serial); - - Serial.begin(115200); - Serial.println(F("Adafruit FONA 808 & 3G GPS demo")); - Serial.println(F("Initializing FONA... (May take a few seconds)")); - - fonaSerial->begin(4800); - if (! fona.begin(*fonaSerial)) { - Serial.println(F("Couldn't find FONA")); - while(1); - } - Serial.println(F("FONA is OK")); - // Try to enable GPRS - - - Serial.println(F("Enabling GPS...")); - fona.enableGPS(true); -} - -void loop() { - delay(2000); - - float latitude, longitude, speed_kph, heading, speed_mph, altitude; - - // if you ask for an altitude reading, getGPS will return false if there isn't a 3D fix - boolean gps_success = fona.getGPS(&latitude, &longitude, &speed_kph, &heading, &altitude); - - if (gps_success) { - - Serial.print("GPS lat:"); - Serial.println(latitude, 6); - Serial.print("GPS long:"); - Serial.println(longitude, 6); - Serial.print("GPS speed KPH:"); - Serial.println(speed_kph); - Serial.print("GPS speed MPH:"); - speed_mph = speed_kph * 0.621371192; - Serial.println(speed_mph); - Serial.print("GPS heading:"); - Serial.println(heading); - Serial.print("GPS altitude:"); - Serial.println(altitude); - - } else { - Serial.println("Waiting for FONA GPS 3D fix..."); - } - - // Fona 3G doesnt have GPRSlocation :/ - if ((fona.type() == FONA3G_A) || (fona.type() == FONA3G_E)) - return; - // Check for network, then GPRS - Serial.println(F("Checking for Cell network...")); - if (fona.getNetworkStatus() == 1) { - // network & GPRS? Great! Print out the GSM location to compare - boolean gsmloc_success = fona.getGSMLoc(&latitude, &longitude); - - if (gsmloc_success) { - Serial.print("GSMLoc lat:"); - Serial.println(latitude, 6); - Serial.print("GSMLoc long:"); - Serial.println(longitude, 6); - } else { - Serial.println("GSM location failed..."); - Serial.println(F("Disabling GPRS")); - fona.enableGPRS(false); - Serial.println(F("Enabling GPRS")); - if (!fona.enableGPRS(true)) { - Serial.println(F("Failed to turn GPRS on")); - } - } - } -} - diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/.esp8266.test.skip b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/.esp8266.test.skip deleted file mode 100644 index e69de29..0000000 diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino b/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino deleted file mode 100644 index 8dba308..0000000 --- a/feather_sensor_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino +++ /dev/null @@ -1,62 +0,0 @@ -// FONA Incoming Call Number Example -// Listens for a call and displays the phone number of the caller (if available). -// Use this example to add phone call detection to your own FONA sketch. -#include "Adafruit_FONA.h" - -// Pins which are connected to the FONA. -// Note that this is different from FONAtest! -#define FONA_RX 3 -#define FONA_TX 4 -#define FONA_RST 5 - -// Note you need to map interrupt number to pin number -// for your board. On an Uno & Mega interrupt 0 is -// digital pin 2, and on a Leonardo interrupt 0 is -// digital pin 3. See this page for a complete table: -// http://arduino.cc/en/Reference/attachInterrupt -// Make sure this interrupt pin is connected to FONA RI! -#define FONA_RI_INTERRUPT 0 - -// We default to using software serial. If you want to use hardware serial -// (because softserial isnt supported) comment out the following three lines -// and uncomment the HardwareSerial line -#include -SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); -SoftwareSerial *fonaSerial = &fonaSS; - -// Hardware serial is also possible! -// HardwareSerial *fonaSerial = &Serial1; - -Adafruit_FONA fona = Adafruit_FONA(FONA_RST); - -void setup() { - Serial.begin(115200); - Serial.println(F("FONA incoming call example")); - Serial.println(F("Initializing....(May take 3 seconds)")); - - fonaSerial->begin(4800); - if (! fona.begin(*fonaSerial)) { - Serial.println(F("Couldn't find FONA")); - while(1); - } - Serial.println(F("FONA is OK")); - - // Enable incoming call notification. - if(fona.callerIdNotification(true, FONA_RI_INTERRUPT)) { - Serial.println(F("Caller id notification enabled.")); - } - else { - Serial.println(F("Caller id notification disabled")); - } -} - -void loop(){ - // Create a small string buffer to hold incoming call number. - char phone[32] = {0}; - // Check for an incoming call. Will return true if a call is incoming. - if(fona.incomingCallNumber(phone)){ - Serial.println(F("RING!")); - Serial.print(F("Phone Number: ")); - Serial.println(phone); - } -} diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/FONAConfig.h b/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/FONAConfig.h deleted file mode 100644 index 5fa3e13..0000000 --- a/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/FONAConfig.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * FONAConfig.h -- compile-time configuration - * This is part of the library for the Adafruit FONA Cellular Module - * - * Designed specifically to work with the Adafruit FONA - * ----> https://www.adafruit.com/products/1946 - * ----> https://www.adafruit.com/products/1963 - * ----> http://www.adafruit.com/products/2468 - * ----> http://www.adafruit.com/products/2542 - * - * Adafruit invests time and resources providing this open source code, - * please support Adafruit and open-source hardware by purchasing - * products from Adafruit! - * - * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in - * the Adafruit_FONA_Library and released under the - * BSD license, all text above must be included in any redistribution. - * - * Created on: Jan 16, 2016 - * Author: Pat Deegan - */ - -#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONACONFIG_H_ -#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONACONFIG_H_ - -/* ADAFRUIT_FONA_DEBUG - * When defined, will cause extensive debug output on the - * DebugStream set in the appropriate platform/ header. - */ - -#define ADAFRUIT_FONA_DEBUG - - -#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONACONFIG_H_ */ diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h b/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h deleted file mode 100644 index f8fe878..0000000 --- a/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * FONAExtIncludes.h -- system-wide includes - * This is part of the library for the Adafruit FONA Cellular Module - * - * Designed specifically to work with the Adafruit FONA - * ----> https://www.adafruit.com/products/1946 - * ----> https://www.adafruit.com/products/1963 - * ----> http://www.adafruit.com/products/2468 - * ----> http://www.adafruit.com/products/2542 - * - * Adafruit invests time and resources providing this open source code, - * please support Adafruit and open-source hardware by purchasing - * products from Adafruit! - * - * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in - * the Adafruit_FONA_Library and released under the - * BSD license, all text above must be included in any redistribution. - * - * Created on: Jan 16, 2016 - * Author: Pat Deegan - */ - - -#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONAEXTINCLUDES_H_ -#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONAEXTINCLUDES_H_ - - -#include "FONAConfig.h" -// include any system-wide includes required here - - - -#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONAEXTINCLUDES_H_ */ diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h b/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h deleted file mode 100644 index 85bc8fe..0000000 --- a/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * FONAPlatStd.h -- standard AVR/Arduino platform. - * - * This is part of the library for the Adafruit FONA Cellular Module - * - * Designed specifically to work with the Adafruit FONA - * ----> https://www.adafruit.com/products/1946 - * ----> https://www.adafruit.com/products/1963 - * ----> http://www.adafruit.com/products/2468 - * ----> http://www.adafruit.com/products/2542 - * - * Adafruit invests time and resources providing this open source code, - * please support Adafruit and open-source hardware by purchasing - * products from Adafruit! - * - * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in - * the Adafruit_FONA_Library and released under the - * BSD license, all text above must be included in any redistribution. - * - * Created on: Jan 16, 2016 - * Author: Pat Deegan - */ - - -#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATSTD_H_ -#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATSTD_H_ - -#include "../FONAConfig.h" - - -#if (ARDUINO >= 100) - #include "Arduino.h" - #if !defined(__SAM3X8E__) && !defined(ARDUINO_ARCH_SAMD) // Arduino Due doesn't support #include - #endif -#else - #include "WProgram.h" - #include -#endif - -#include - - -// DebugStream sets the Stream output to use -// for debug (only applies when ADAFRUIT_FONA_DEBUG -// is defined in config) -#define DebugStream Serial - -#ifdef ADAFRUIT_FONA_DEBUG -// need to do some debugging... -#define DEBUG_PRINT(...) DebugStream.print(__VA_ARGS__) -#define DEBUG_PRINTLN(...) DebugStream.println(__VA_ARGS__) -#endif - -// a few typedefs to keep things portable -typedef Stream FONAStreamType; -typedef const __FlashStringHelper * FONAFlashStringPtr; - -#define prog_char char PROGMEM - -#define prog_char_strcmp(a, b) strcmp_P((a), (b)) -// define prog_char_strncmp(a, b, c) strncmp_P((a), (b), (c)) -#define prog_char_strstr(a, b) strstr_P((a), (b)) -#define prog_char_strlen(a) strlen_P((a)) -#define prog_char_strcpy(to, fromprogmem) strcpy_P((to), (fromprogmem)) -//define prog_char_strncpy(to, from, len) strncpy_P((to), (fromprogmem), (len)) - -#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATSTD_H_ */ diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h b/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h deleted file mode 100644 index 0bf98d0..0000000 --- a/feather_sensor_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * FONAPlatform.h -- platform definitions includes. - * - * This is part of the library for the Adafruit FONA Cellular Module - * - * Designed specifically to work with the Adafruit FONA - * ----> https://www.adafruit.com/products/1946 - * ----> https://www.adafruit.com/products/1963 - * ----> http://www.adafruit.com/products/2468 - * ----> http://www.adafruit.com/products/2542 - * - * Adafruit invests time and resources providing this open source code, - * please support Adafruit and open-source hardware by purchasing - * products from Adafruit! - * - * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in - * the Adafruit_FONA_Library and released under the - * BSD license, all text above must be included in any redistribution. - * - * Created on: Jan 16, 2016 - * Author: Pat Deegan - */ - - -#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATFORM_H_ -#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATFORM_H_ - -#include "../FONAConfig.h" - -// only "standard" config supported in this release -- namely AVR-based arduino type affairs -#include "FONAPlatStd.h" - - - -#ifndef DEBUG_PRINT -// debug is disabled - -#define DEBUG_PRINT(...) -#define DEBUG_PRINTLN(...) - -#endif - - -#ifndef prog_char_strcmp -#define prog_char_strcmp(a, b) strcmp((a), (b)) -#endif - -#ifndef prog_char_strstr -#define prog_char_strstr(a, b) strstr((a), (b)) -#endif - -#ifndef prog_char_strlen -#define prog_char_strlen(a) strlen((a)) -#endif - - -#ifndef prog_char_strcpy -#define prog_char_strcpy(to, fromprogmem) strcpy((to), (fromprogmem)) -#endif - - -#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATFORM_H_ */ diff --git a/feather_sensor_lte/libraries/Adafruit_FONA_Library/library.properties b/feather_sensor_lte/libraries/Adafruit_FONA_Library/library.properties deleted file mode 100644 index bb7099c..0000000 --- a/feather_sensor_lte/libraries/Adafruit_FONA_Library/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=Adafruit FONA Library -version=1.3.2 -author=Adafruit -maintainer=Adafruit -sentence=Arduino library for the Adafruit FONA -paragraph=Arduino library for the Adafruit FONA -category=Communication -url=https://github.com/adafruit/Adafruit_FONA_Library -architectures=* diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp deleted file mode 100644 index 9448278..0000000 --- a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp +++ /dev/null @@ -1,4 +0,0 @@ -#include "Adafruit_SleepyDog.h" - -// Global instance of the main class for sketches to use. -WatchdogType Watchdog; diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h deleted file mode 100644 index 4cdf4b4..0000000 --- a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef ADAFRUIT_SLEEPYDOG_H -#define ADAFRUIT_SLEEPYDOG_H - -// Platform-specific code goes below. Each #ifdef should check for the presence -// of their platform and pull in the appropriate watchdog implementation type, -// then typedef it to WatchdogType so the .cpp file can create a global instance. -#if defined(ARDUINO_ARCH_AVR) || defined(__AVR__) - #include "utility/WatchdogAVR.h" - typedef WatchdogAVR WatchdogType; -#elif defined(ARDUINO_ARCH_SAMD) - // Arduino Zero / ATSAMD series CPU watchdog support. - #include "utility/WatchdogSAMD.h" - typedef WatchdogSAMD WatchdogType; -#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) - // Teensy 3.x watchdog support. - #include "utility/WatchdogKinetisK.h" - typedef WatchdogKinetisKseries WatchdogType; -#elif defined(__MKL26Z64__) - // Teensy LC watchdog support. - #include "utility/WatchdogKinetisL.h" - typedef WatchdogKinetisLseries WatchdogType; -#else - #error Unsupported platform for the Adafruit Watchdog library! -#endif - -extern WatchdogType Watchdog; - -#endif diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/LICENSE b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/LICENSE deleted file mode 100644 index 04ebb92..0000000 --- a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Adafruit Industries - -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/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/README.md b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/README.md deleted file mode 100644 index 3aa268a..0000000 --- a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# Adafruit SleepyDog Arduino Library - -Arduino library to use the watchdog timer for system reset and low power sleep. - -Currently supports the following hardware: -* Arduino Uno or compatible (ATmega328P). diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino deleted file mode 100644 index 8d47041..0000000 --- a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino +++ /dev/null @@ -1,62 +0,0 @@ -// Adafruit Watchdog Library Basic Usage Example -// -// Simple example of how to use the watchdog library. -// -// Author: Tony DiCola - -#include - -void setup() { - Serial.begin(115200); - while (!Serial) ; // wait for Arduino Serial Monitor (native USB boards) - Serial.println("Adafruit Watchdog Library Demo!"); - Serial.println(); - - // First a normal example of using the watchdog timer. - // Enable the watchdog by calling Watchdog.enable() as below. This will turn - // on the watchdog timer with a ~4 second timeout before reseting the Arduino. - // The estimated actual milliseconds before reset (in milliseconds) is returned. - // Make sure to reset the watchdog before the countdown expires or the Arduino - // will reset! - int countdownMS = Watchdog.enable(4000); - Serial.print("Enabled the watchdog with max countdown of "); - Serial.print(countdownMS, DEC); - Serial.println(" milliseconds!"); - Serial.println(); - - // Now loop a few times and periodically reset the watchdog. - Serial.println("Looping ten times while resetting the watchdog..."); - for (int i = 1; i <= 10; ++i) { - Serial.print("Loop #"); Serial.println(i, DEC); - delay(1000); - // Reset the watchdog with every loop to make sure the sketch keeps running. - // If you comment out this call watch what happens after about 4 iterations! - Watchdog.reset(); - } - Serial.println(); - - // Disable the watchdog entirely by calling Watchdog.disable(); - Watchdog.disable(); - - // Finally demonstrate the watchdog resetting by enabling it for a shorter - // period of time and waiting a long time without a reset. Notice you can pass - // a _maximum_ countdown time (in milliseconds) to the enable call. The library - // will try to use that value as the countdown, but it might pick a smaller - // value if the hardware doesn't support it. The actual countdown value will - // be returned so you can see what it is. - countdownMS = Watchdog.enable(4000); - Serial.print("Get ready, the watchdog will reset in "); - Serial.print(countdownMS, DEC); - Serial.println(" milliseconds!"); - Serial.println(); - delay(countdownMS+1000); - - // Execution will never get here because the watchdog resets the Arduino! -} - -void loop() { - // We'll never actually get to the loop because the watchdog will reset in - // the setup function. - Serial.println("You shouldn't see this message."); - delay(1000); -} diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino deleted file mode 100644 index d8eab80..0000000 --- a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino +++ /dev/null @@ -1,37 +0,0 @@ -// Adafruit Watchdog Library Sleep Example -// -// Simple example of how to do low power sleep with the watchdog timer. -// -// Author: Tony DiCola - -#include - -void setup() { - Serial.begin(115200); - while (!Serial) ; // wait for Arduino Serial Monitor (native USB boards) - Serial.println("Adafruit Watchdog Library Sleep Demo!"); - Serial.println(); -} - -void loop() { - Serial.println("Going to sleep in one second..."); - delay(1000); - - // To enter low power sleep mode call Watchdog.sleep() like below - // and the watchdog will allow low power sleep for as long as possible. - // The actual amount of time spent in sleep will be returned (in - // milliseconds). - int sleepMS = Watchdog.sleep(); - - // Alternatively you can provide a millisecond value to specify - // how long you'd like the chip to sleep, but the hardware only - // supports a limited range of values so the actual sleep time might - // be smaller. The time spent in sleep will be returned (in - // milliseconds). - // int sleepMS = Watchdog.sleep(1000); // Sleep for up to 1 second. - - Serial.print("I'm awake now! I slept for "); - Serial.print(sleepMS, DEC); - Serial.println(" milliseconds."); - Serial.println(); -} diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/library.properties b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/library.properties deleted file mode 100644 index c41d74b..0000000 --- a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=Adafruit SleepyDog Library -version=1.1.1 -author=Adafruit -maintainer=Adafruit -sentence=Arduino library to use the watchdog timer for system reset and low power sleep. -paragraph=Arduino library to use the watchdog timer for system reset and low power sleep. -category=Other -url=https://github.com/adafruit/Adafruit_SleepyDog -architectures=* diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp deleted file mode 100644 index 3355c13..0000000 --- a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp +++ /dev/null @@ -1,137 +0,0 @@ -// Be careful to use a platform-specific conditional include to only make the -// code visible for the appropriate platform. Arduino will try to compile and -// link all .cpp files regardless of platform. -#if defined(ARDUINO_ARCH_AVR) || defined(__AVR__) - -#include -#include -#include -#include - -#include "WatchdogAVR.h" - -// Define watchdog timer interrupt. -ISR(WDT_vect) -{ - // Nothing needs to be done, however interrupt handler must be defined to - // prevent a reset. -} - -int WatchdogAVR::enable(int maxPeriodMS) { - // Pick the closest appropriate watchdog timer value. - int actualMS; - _setPeriod(maxPeriodMS, _wdto, actualMS); - // Enable the watchdog and return the actual countdown value. - wdt_enable(_wdto); - return actualMS; -} - -void WatchdogAVR::reset() { - // Reset the watchdog. - wdt_reset(); -} - -void WatchdogAVR::disable() { - // Disable the watchdog and clear any saved watchdog timer value. - wdt_disable(); - _wdto = -1; -} - -int WatchdogAVR::sleep(int maxPeriodMS) { - // Pick the closest appropriate watchdog timer value. - int sleepWDTO, actualMS; - _setPeriod(maxPeriodMS, sleepWDTO, actualMS); - - // Build watchdog prescaler register value before timing critical code. - uint8_t wdps = ((sleepWDTO & 0x08 ? 1 : 0) << WDP3) | - ((sleepWDTO & 0x04 ? 1 : 0) << WDP2) | - ((sleepWDTO & 0x02 ? 1 : 0) << WDP1) | - ((sleepWDTO & 0x01 ? 1 : 0) << WDP0); - - // The next section is timing critical so interrupts are disabled. - cli(); - // First clear any previous watchdog reset. - MCUSR &= ~(1<= 8000) || (maxMS == 0)) { - wdto = WDTO_8S; - actualMS = 8000; - } - else if (maxMS >= 4000) { - wdto = WDTO_4S; - actualMS = 4000; - } - else if (maxMS >= 2000) { - wdto = WDTO_2S; - actualMS = 2000; - } - else if (maxMS >= 1000) { - wdto = WDTO_1S; - actualMS = 1000; - } - else if (maxMS >= 500) { - wdto = WDTO_500MS; - actualMS = 500; - } - else if (maxMS >= 250) { - wdto = WDTO_250MS; - actualMS = 250; - } - else if (maxMS >= 120) { - wdto = WDTO_120MS; - actualMS = 120; - } - else if (maxMS >= 60) { - wdto = WDTO_60MS; - actualMS = 60; - } - else if (maxMS >= 30) { - wdto = WDTO_30MS; - actualMS = 30; - } - else { - wdto = WDTO_15MS; - actualMS = 15; - } -} - -#endif diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h deleted file mode 100644 index 9753b08..0000000 --- a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef WATCHDOGAVR_H -#define WATCHDOGAVR_H - -class WatchdogAVR { -public: - WatchdogAVR(): - _wdto(-1) - {} - - // Enable the watchdog timer to reset the machine after a period of time - // without any calls to reset(). The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware does - // not support the exact desired value. - // - // The actual period (in milliseconds) before a watchdog timer reset is - // returned. - int enable(int maxPeriodMS = 0); - - // Reset or 'kick' the watchdog timer to prevent a reset of the device. - void reset(); - - // Completely disable the watchdog timer. - void disable(); - - // Enter the lowest power sleep mode (using the watchdog timer) for the - // desired period of time. The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware does - // not support the exact desired value - // - // The actual period (in milliseconds) that the hardware was asleep will be - // returned. - int sleep(int maxPeriodMS = 0); - -private: - // Pick the closest (but not higher) watchdog timer value from the provided - // maximum period. Sets wdto to the chosen period value suitable for - // passing to wdt_enable(), and actualMS to the chosen period value in - // milliseconds. A max value of 0 will pick the longest value possible. - void _setPeriod(int maxMS, int &wdto, int &actualMS); - - // Keep the last selected watchdog timer period so that the watchdog can be - // re-enabled at that rate after sleep. A value of -1 means no watchdog - // timer was enabled. - int _wdto; -}; - -#endif \ No newline at end of file diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp deleted file mode 100644 index 9705859..0000000 --- a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp +++ /dev/null @@ -1,104 +0,0 @@ -// Be careful to use a platform-specific conditional include to only make the -// code visible for the appropriate platform. Arduino will try to compile and -// link all .cpp files regardless of platform. -#if defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) - -#include -#include "WatchdogKinetisK.h" - -static void one_bus_cycle(void) __attribute__((always_inline)); -static void watchdog_config(int cfg, int val); - -// Enable the watchdog timer to reset the machine after a period of time -// without any calls to reset(). The passed in period (in milliseconds) is -// just a suggestion and a lower value might be picked if the hardware does -// not support the exact desired value. -// -// The actual period (in milliseconds) before a watchdog timer reset is -// returned. -int WatchdogKinetisKseries::enable(int maxPeriodMS) -{ - if (maxPeriodMS < 4) { - maxPeriodMS = 8000; // default is 8 seconds - } - if (setting != maxPeriodMS) { - watchdog_config(WDOG_STCTRLH_WDOGEN, maxPeriodMS); - setting = maxPeriodMS; - } - return maxPeriodMS; -} - -// Reset or 'kick' the watchdog timer to prevent a reset of the device. -void WatchdogKinetisKseries::reset() -{ - __disable_irq(); - WDOG_REFRESH = 0xA602; - WDOG_REFRESH = 0xB480; - __enable_irq(); -} - -// Completely disable the watchdog timer. -void WatchdogKinetisKseries::disable() -{ - if (setting > 0) { - watchdog_config(0, 4); - setting = 0; - } -} - -// Enter the lowest power sleep mode for the desired period of time. The -// passed in period (in milliseconds) is just a suggestion and a lower value -// might be picked if the hardware does not support the exact desired value -// -// The actual period (in milliseconds) that the hardware was asleep will be -// returned. -int WatchdogKinetisKseries::sleep(int maxPeriodMS) -{ - if (maxPeriodMS <= 0) return 0; - // TODO.... - return 0; -} - -static void watchdog_config(int cfg, int val) -{ - __disable_irq(); - WDOG_UNLOCK = WDOG_UNLOCK_SEQ1; - WDOG_UNLOCK = WDOG_UNLOCK_SEQ2; - one_bus_cycle(); - WDOG_STCTRLH = cfg | WDOG_STCTRLH_ALLOWUPDATE; - WDOG_TOVALH = val >> 16; - WDOG_TOVALL = val; - WDOG_PRESC = 0; - __enable_irq(); - for (int i=0; i < 256; i++) { - one_bus_cycle(); - } -} - -static void one_bus_cycle(void) -{ - __asm__ volatile ("nop"); - #if (F_CPU / F_BUS) > 1 - __asm__ volatile ("nop"); - #endif - #if (F_CPU / F_BUS) > 2 - __asm__ volatile ("nop"); - #endif - #if (F_CPU / F_BUS) > 3 - __asm__ volatile ("nop"); - #endif - #if (F_CPU / F_BUS) > 4 - __asm__ volatile ("nop"); - #endif - #if (F_CPU / F_BUS) > 5 - __asm__ volatile ("nop"); - #endif - #if (F_CPU / F_BUS) > 6 - __asm__ volatile ("nop"); - #endif - #if (F_CPU / F_BUS) > 7 - __asm__ volatile ("nop"); - #endif -} - -#endif diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h deleted file mode 100644 index e09a0c2..0000000 --- a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef WATCHDOGKINETISK_H -#define WATCHDOGKINETISK_H - -class WatchdogKinetisKseries { -public: - WatchdogKinetisKseries(): setting(0) {} - - // Enable the watchdog timer to reset the machine after a period of time - // without any calls to reset(). The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware does - // not support the exact desired value. - // - // The actual period (in milliseconds) before a watchdog timer reset is - // returned. - int enable(int maxPeriodMS = 0); - - // Reset or 'kick' the watchdog timer to prevent a reset of the device. - void reset(); - - // Completely disable the watchdog timer. - void disable(); - - // Enter the lowest power sleep mode (using the watchdog timer) for the - // desired period of time. The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware does - // not support the exact desired value - // - // The actual period (in milliseconds) that the hardware was asleep will be - // returned. - // - // NOTE: This is currently not implemented on the SAMD21! - int sleep(int maxPeriodMS = 0); - -private: - int setting; -}; - -#endif diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp deleted file mode 100644 index 501e9c0..0000000 --- a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp +++ /dev/null @@ -1,74 +0,0 @@ -// Be careful to use a platform-specific conditional include to only make the -// code visible for the appropriate platform. Arduino will try to compile and -// link all .cpp files regardless of platform. -#if defined(__MKL26Z64__) - -#include -#include "WatchdogKinetisL.h" - -// Normally the watchdog is disabled at startup. This removes the startup -// code. The watchdog will be active with 1024 ms timeout. Hopefully the -// user will configure the watchdog and begin resetting it before it causes -// a reboot. There is no way to start up without the watchdog and then -// enable it later... -extern "C" void startup_early_hook(void) {} - - -// Enable the watchdog timer to reset the machine after a period of time -// without any calls to reset(). The passed in period (in milliseconds) is -// just a suggestion and a lower value might be picked if the hardware does -// not support the exact desired value. -// -// The actual period (in milliseconds) before a watchdog timer reset is -// returned. -int WatchdogKinetisLseries::enable(int maxPeriodMS) -{ - // The watchdog can only be programmed once. Then it's forever - // locked to this setting (until the chip reboots). - if (maxPeriodMS <= 0 || maxPeriodMS > 256) { - SIM_COPC = 12; - } else if (maxPeriodMS > 32) { - SIM_COPC = 8; - } else { - SIM_COPC = 4; - } - // Read the actual setting. - int val = SIM_COPC & 12; - if (val == 12) return 1024; - if (val == 8) return 256; - return 32; -} - -// Reset or 'kick' the watchdog timer to prevent a reset of the device. -void WatchdogKinetisLseries::reset() -{ - __disable_irq(); - SIM_SRVCOP = 0x55; - SIM_SRVCOP = 0xAA; - __enable_irq(); -} - -// Completely disable the watchdog timer. -void WatchdogKinetisLseries::disable() -{ - // no can do.... - // The watchdog timer in this chip is write-once. - // The chip boots up with the watchdog at 1024 ms. - // You only get to configure it once. Then it - // remains locked to that setting, until a reboot. -} - -// Enter the lowest power sleep mode for the desired period of time. The -// passed in period (in milliseconds) is just a suggestion and a lower value -// might be picked if the hardware does not support the exact desired value -// -// The actual period (in milliseconds) that the hardware was asleep will be -// returned. -int WatchdogKinetisLseries::sleep(int maxPeriodMS) -{ - if (maxPeriodMS <= 0) return 0; - // TODO.... - return 0; -} - -#endif diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h deleted file mode 100644 index 3c68d5e..0000000 --- a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef WATCHDOGKINETISL_H -#define WATCHDOGKINETISL_H - -class WatchdogKinetisLseries { -public: - WatchdogKinetisLseries() {} - - // Enable the watchdog timer to reset the machine after a period of time - // without any calls to reset(). The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware does - // not support the exact desired value. - // - // The actual period (in milliseconds) before a watchdog timer reset is - // returned. - int enable(int maxPeriodMS = 0); - - // Reset or 'kick' the watchdog timer to prevent a reset of the device. - void reset(); - - // Completely disable the watchdog timer. - void disable(); - - // Enter the lowest power sleep mode (using the watchdog timer) for the - // desired period of time. The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware does - // not support the exact desired value - // - // The actual period (in milliseconds) that the hardware was asleep will be - // returned. - // - // NOTE: This is currently not implemented on the SAMD21! - int sleep(int maxPeriodMS = 0); -}; - -#endif diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp deleted file mode 100644 index d21d9a9..0000000 --- a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp +++ /dev/null @@ -1,175 +0,0 @@ -// Requires Adafruit_ASFcore library! - -// Be careful to use a platform-specific conditional include to only make the -// code visible for the appropriate platform. Arduino will try to compile and -// link all .cpp files regardless of platform. -#if defined(ARDUINO_ARCH_SAMD) - -#include -#include -#include -#include "WatchdogSAMD.h" - -int WatchdogSAMD::enable(int maxPeriodMS, bool isForSleep) { - // Enable the watchdog with a period up to the specified max period in - // milliseconds. - - // Review the watchdog section from the SAMD21 datasheet section 17: - // http://www.atmel.com/images/atmel-42181-sam-d21_datasheet.pdf - - int cycles, actualMS; - uint8_t bits; - - if(!_initialized) _initialize_wdt(); - - WDT->CTRL.reg = 0; // Disable watchdog for config - while(WDT->STATUS.bit.SYNCBUSY); - - // You'll see some occasional conversion here compensating between - // milliseconds (1000 Hz) and WDT clock cycles (~1024 Hz). The low- - // power oscillator used by the WDT ostensibly runs at 32,768 Hz with - // a 1:32 prescale, thus 1024 Hz, though probably not super precise. - - if((maxPeriodMS >= 16000) || !maxPeriodMS) { - cycles = 16384; - bits = 0xB; - } else { - cycles = (maxPeriodMS * 1024L + 500) / 1000; // ms -> WDT cycles - if(cycles >= 8192) { - cycles = 8192; - bits = 0xA; - } else if(cycles >= 4096) { - cycles = 4096; - bits = 0x9; - } else if(cycles >= 2048) { - cycles = 2048; - bits = 0x8; - } else if(cycles >= 1024) { - cycles = 1024; - bits = 0x7; - } else if(cycles >= 512) { - cycles = 512; - bits = 0x6; - } else if(cycles >= 256) { - cycles = 256; - bits = 0x5; - } else if(cycles >= 128) { - cycles = 128; - bits = 0x4; - } else if(cycles >= 64) { - cycles = 64; - bits = 0x3; - } else if(cycles >= 32) { - cycles = 32; - bits = 0x2; - } else if(cycles >= 16) { - cycles = 16; - bits = 0x1; - } else { - cycles = 8; - bits = 0x0; - } - } - - // Watchdog timer on SAMD is a slightly different animal than on AVR. - // On AVR, the WTD timeout is configured in one register and then an - // interrupt can optionally be enabled to handle the timeout in code - // (as in waking from sleep) vs resetting the chip. Easy. - // On SAMD, when the WDT fires, that's it, the chip's getting reset. - // Instead, it has an "early warning interrupt" with a different set - // interval prior to the reset. For equivalent behavior to the AVR - // library, this requires a slightly different configuration depending - // whether we're coming from the sleep() function (which needs the - // interrupt), or just enable() (no interrupt, we want the chip reset - // unless the WDT is cleared first). In the sleep case, 'windowed' - // mode is used in order to allow access to the longest available - // sleep interval (about 16 sec); the WDT 'period' (when a reset - // occurs) follows this and is always just set to the max, since the - // interrupt will trigger first. In the enable case, windowed mode - // is not used, the WDT period is set and that's that. - // The 'isForSleep' argument determines which behavior is used; - // this isn't present in the AVR code, just here. It defaults to - // 'false' so existing Arduino code works as normal, while the sleep() - // function (later in this file) explicitly passes 'true' to get the - // alternate behavior. - - if(isForSleep) { - WDT->INTENSET.bit.EW = 1; // Enable early warning interrupt - WDT->CONFIG.bit.PER = 0xB; // Period = max - WDT->CONFIG.bit.WINDOW = bits; // Set time of interrupt - WDT->CTRL.bit.WEN = 1; // Enable window mode - while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write - } else { - WDT->INTENCLR.bit.EW = 1; // Disable early warning interrupt - WDT->CONFIG.bit.PER = bits; // Set period for chip reset - WDT->CTRL.bit.WEN = 0; // Disable window mode - while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write - } - - actualMS = (cycles * 1000L + 512) / 1024; // WDT cycles -> ms - - reset(); // Clear watchdog interval - WDT->CTRL.bit.ENABLE = 1; // Start watchdog now! - while(WDT->STATUS.bit.SYNCBUSY); - - return actualMS; -} - -void WatchdogSAMD::reset() { - // Write the watchdog clear key value (0xA5) to the watchdog - // clear register to clear the watchdog timer and reset it. - WDT->CLEAR.reg = WDT_CLEAR_CLEAR_KEY; - while(WDT->STATUS.bit.SYNCBUSY); -} - -void WatchdogSAMD::disable() { - WDT->CTRL.bit.ENABLE = 0; - while(WDT->STATUS.bit.SYNCBUSY); -} - -void WDT_Handler(void) { - // ISR for watchdog early warning, DO NOT RENAME! - WDT->CTRL.bit.ENABLE = 0; // Disable watchdog - while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write - WDT->INTFLAG.bit.EW = 1; // Clear interrupt flag -} - -int WatchdogSAMD::sleep(int maxPeriodMS) { - - int actualPeriodMS = enable(maxPeriodMS, true); // true = for sleep - - system_set_sleepmode(SYSTEM_SLEEPMODE_STANDBY); // Deepest sleep - system_sleep(); - // Code resumes here on wake (WDT early warning interrupt) - - return actualPeriodMS; -} - -void WatchdogSAMD::_initialize_wdt() { - // One-time initialization of watchdog timer. - // Insights from rickrlh and rbrucemtl in Arduino forum! - - // Generic clock generator 2, divisor = 32 (2^(DIV+1)) - GCLK->GENDIV.reg = GCLK_GENDIV_ID(2) | GCLK_GENDIV_DIV(4); - // Enable clock generator 2 using low-power 32KHz oscillator. - // With /32 divisor above, this yields 1024Hz(ish) clock. - GCLK->GENCTRL.reg = GCLK_GENCTRL_ID(2) | - GCLK_GENCTRL_GENEN | - GCLK_GENCTRL_SRC_OSCULP32K | - GCLK_GENCTRL_DIVSEL; - while(GCLK->STATUS.bit.SYNCBUSY); - // WDT clock = clock gen 2 - GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID_WDT | - GCLK_CLKCTRL_CLKEN | - GCLK_CLKCTRL_GEN_GCLK2; - - // Enable WDT early-warning interrupt - NVIC_DisableIRQ(WDT_IRQn); - NVIC_ClearPendingIRQ(WDT_IRQn); - NVIC_SetPriority(WDT_IRQn, 0); // Top priority - NVIC_EnableIRQ(WDT_IRQn); - - _initialized = true; -} - -#endif diff --git a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h b/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h deleted file mode 100644 index 8b03c27..0000000 --- a/feather_sensor_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef WATCHDOGSAMD_H -#define WATCHDOGSAMD_H - -class WatchdogSAMD { -public: - WatchdogSAMD(): - _initialized(false) - {} - - // Enable the watchdog timer to reset the machine after a period of time - // without any calls to reset(). The passed in period (in milliseconds) - // is just a suggestion and a lower value might be picked if the hardware - // does not support the exact desired value. - // User code should NOT set the 'isForSleep' argument either way -- - // it's used internally by the library, but your sketch should leave this - // out when calling enable(), just let the default have its way. - // - // The actual period (in milliseconds) before a watchdog timer reset is - // returned. - int enable(int maxPeriodMS = 0, bool isForSleep = false); - - // Reset or 'kick' the watchdog timer to prevent a reset of the device. - void reset(); - - // Completely disable the watchdog timer. - void disable(); - - // Enter the lowest power sleep mode (using the watchdog timer) for the - // desired period of time. The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware - // does not support the exact desired value - // - // The actual period (in milliseconds) that the hardware was asleep will be - // returned. - int sleep(int maxPeriodMS = 0); - -private: - void _initialize_wdt(); - - bool _initialized; -}; - -#endif diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/.gitignore b/feather_sensor_lte/libraries/ArduinoHttpClient/.gitignore deleted file mode 100644 index 89d225a..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.development -examples/node_test_server/node_modules/ diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/CHANGELOG.md b/feather_sensor_lte/libraries/ArduinoHttpClient/CHANGELOG.md deleted file mode 100644 index 5645508..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/CHANGELOG.md +++ /dev/null @@ -1,25 +0,0 @@ -## ArduinoHttpClient 0.3.1 - 2017.09.25 - -* Changed examples to support Arduino Create secret tabs -* Increase WebSocket secrect-key length to 24 characters - -## ArduinoHttpClient 0.3.0 - 2017.04.20 - -* Added support for PATCH operations -* Added support for chunked response bodies -* Added new beginBody API - -## ArduinoHttpClient 0.2.0 - 2017.01.12 - -* Added PATCH method -* Added basic auth example -* Added custom header example - -## ArduinoHttpClient 0.1.1 - 2016.12.16 - -* More robust response parser - -## ArduinoHttpClient 0.1.0 - 2016.07.05 - -* Initial release - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/README.md b/feather_sensor_lte/libraries/ArduinoHttpClient/README.md deleted file mode 100644 index 655b618..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# ArduinoHttpClient - -ArduinoHttpClient is a library to make it easier to interact with web servers from Arduino. - -Derived from [Adrian McEwen's HttpClient library](https://github.com/amcewen/HttpClient) - -## Dependencies - -- Requires a networking hardware and a library that provides transport specific `Client` instance, such as: - - [WiFi101](https://github.com/arduino-libraries/WiFi101) - - [Ethernet](https://github.com/arduino-libraries/Ethernet) - - [WiFi](https://github.com/arduino-libraries/WiFi) - - [GSM](https://github.com/arduino-libraries/GSM) - -## Usage - -In normal usage, handles the outgoing request and Host header. The returned status code is parsed for you, as is the Content-Length header (if present). - -Because it expects an object of type Client, you can use it with any of the networking classes that derive from that. Which means it will work with WiFiClient, EthernetClient and GSMClient. - -See the examples for more detail on how the library is used. - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino deleted file mode 100644 index e793d47..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino +++ /dev/null @@ -1,69 +0,0 @@ -/* - GET client with HTTP basic authentication for ArduinoHttpClient library - Connects to server once every five seconds, sends a GET request - - - - created 14 Feb 2016 - by Tom Igoe - modified 3 Jan 2017 to add HTTP basic authentication - by Sandeep Mistry - - this example is in the public domain - */ -#include -#include -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("making GET request with HTTP basic authentication"); - client.beginRequest(); - client.get("/secure"); - client.sendBasicAuth("username", "password"); // send the username and password for authentication - client.endRequest(); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - Serial.println("Wait five seconds"); - delay(5000); -} - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino deleted file mode 100644 index fa44aca..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino +++ /dev/null @@ -1,96 +0,0 @@ -/* - Custom request header example for the ArduinoHttpClient - library. This example sends a GET and a POST request with a custom header every 5 seconds. - - note: WiFi SSID and password are stored in config.h file. - If it is not present, add a new tab, call it "config.h" - and add the following variables: - char ssid[] = "ssid"; // your network SSID (name) - char pass[] = "password"; // your network password - - based on SimpleGet example by Tom Igoe - header modifications by Todd Treece - - this example is in the public domain - */ - -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - - Serial.println("making GET request"); - client.beginRequest(); - client.get("/"); - client.sendHeader("X-CUSTOM-HEADER", "custom_value"); - client.endRequest(); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("GET Status code: "); - Serial.println(statusCode); - Serial.print("GET Response: "); - Serial.println(response); - - Serial.println("Wait five seconds"); - delay(5000); - - Serial.println("making POST request"); - String postData = "name=Alice&age=12"; - client.beginRequest(); - client.post("/"); - client.sendHeader(HTTP_HEADER_CONTENT_TYPE, "application/x-www-form-urlencoded"); - client.sendHeader(HTTP_HEADER_CONTENT_LENGTH, postData.length()); - client.sendHeader("X-CUSTOM-HEADER", "custom_value"); - client.endRequest(); - client.write((const byte*)postData.c_str(), postData.length()); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("POST Status code: "); - Serial.println(statusCode); - Serial.print("POST Response: "); - Serial.println(response); - - Serial.println("Wait five seconds"); - delay(5000); -} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino deleted file mode 100644 index 51abd3f..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino +++ /dev/null @@ -1,107 +0,0 @@ -/* - Dweet.io GET client for ArduinoHttpClient library - Connects to dweet.io once every ten seconds, - sends a GET request and a request body. Uses SSL - - Shows how to use Strings to assemble path and parse content - from response. dweet.io expects: - https://dweet.io/get/latest/dweet/for/thingName - - For more on dweet.io, see https://dweet.io/play/ - - - - created 15 Feb 2016 - updated 16 Feb 2016 - by Tom Igoe - - this example is in the public domain -*/ -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - -const char serverAddress[] = "dweet.io"; // server address -int port = 80; -String dweetName = "scandalous-cheese-hoarder"; // use your own thing name here - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -int statusCode = 0; -String response; - -void setup() { - Serial.begin(9600); - while (!Serial); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - // assemble the path for the GET message: - String path = "/get/latest/dweet/for/" + dweetName; - - // send the GET request - Serial.println("making GET request"); - client.get(path); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - /* - Typical response is: - {"this":"succeeded", - "by":"getting", - "the":"dweets", - "with":[{"thing":"my-thing-name", - "created":"2016-02-16T05:10:36.589Z", - "content":{"sensorValue":456}}]} - - You want "content": numberValue - */ - // now parse the response looking for "content": - int labelStart = response.indexOf("content\":"); - // find the first { after "content": - int contentStart = response.indexOf("{", labelStart); - // find the following } and get what's between the braces: - int contentEnd = response.indexOf("}", labelStart); - String content = response.substring(contentStart + 1, contentEnd); - Serial.println(content); - - // now get the value after the colon, and convert to an int: - int valueStart = content.indexOf(":"); - String valueString = content.substring(valueStart + 1); - int number = valueString.toInt(); - Serial.print("Value string: "); - Serial.println(valueString); - Serial.print("Actual value: "); - Serial.println(number); - - Serial.println("Wait ten seconds\n"); - delay(10000); -} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino deleted file mode 100644 index 41c6f2f..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino +++ /dev/null @@ -1,87 +0,0 @@ -/* - Dweet.io POST client for ArduinoHttpClient library - Connects to dweet.io once every ten seconds, - sends a POST request and a request body. - - Shows how to use Strings to assemble path and body - - note: WiFi SSID and password are stored in config.h file. - If it is not present, add a new tab, call it "config.h" - and add the following variables: - char ssid[] = "ssid"; // your network SSID (name) - char pass[] = "password"; // your network password - - created 15 Feb 2016 - by Tom Igoe - - this example is in the public domain -*/ -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - -const char serverAddress[] = "dweet.io"; // server address -int port = 80; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -int statusCode = 0; -String response; - -void setup() { - Serial.begin(9600); - while(!Serial); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - // assemble the path for the POST message: - String dweetName = "scandalous-cheese-hoarder"; - String path = "/dweet/for/" + dweetName; - - String contentType = "application/json"; - - // assemble the body of the POST message: - int sensorValue = analogRead(A0); - String postData = "{\"sensorValue\":\""; - postData += sensorValue; - postData += "\"}"; - - Serial.println("making POST request"); - - // send the POST request - client.post(path, contentType, postData); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - Serial.println("Wait ten seconds\n"); - delay(10000); -} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino deleted file mode 100644 index c18ae47..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino +++ /dev/null @@ -1,102 +0,0 @@ -/* HueBlink example for ArduinoHttpClient library - - Uses ArduinoHttpClient library to control Philips Hue - For more on Hue developer API see http://developer.meethue.com - - To control a light, the Hue expects a HTTP PUT request to: - - http://hue.hub.address/api/hueUserName/lights/lightNumber/state - - The body of the PUT request looks like this: - {"on": true} or {"on":false} - - This example shows how to concatenate Strings to assemble the - PUT request and the body of the request. - - - - modified 15 Feb 2016 - by Tom Igoe (tigoe) to match new API -*/ - -#include -#include -#include -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - -int status = WL_IDLE_STATUS; // the Wifi radio's status - -char hueHubIP[] = "192.168.0.3"; // IP address of the HUE bridge -String hueUserName = "huebridgeusername"; // hue bridge username - -// make a wifi instance and a HttpClient instance: -WiFiClient wifi; -HttpClient httpClient = HttpClient(wifi, hueHubIP); - - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial); // wait for serial port to connect. - - // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to WPA SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // you're connected now, so print out the data: - Serial.print("You're connected to the network IP = "); - IPAddress ip = WiFi.localIP(); - Serial.println(ip); -} - -void loop() { - sendRequest(3, "on", "true"); // turn light on - delay(2000); // wait 2 seconds - sendRequest(3, "on", "false"); // turn light off - delay(2000); // wait 2 seconds -} - -void sendRequest(int light, String cmd, String value) { - // make a String for the HTTP request path: - String request = "/api/" + hueUserName; - request += "/lights/"; - request += light; - request += "/state/"; - - String contentType = "application/json"; - - // make a string for the JSON command: - String hueCmd = "{\"" + cmd; - hueCmd += "\":"; - hueCmd += value; - hueCmd += "}"; - // see what you assembled to send: - Serial.print("PUT request to server: "); - Serial.println(request); - Serial.print("JSON command to server: "); - - // make the PUT request to the hub: - httpClient.put(request, contentType, hueCmd); - - // read the status code and body of the response - int statusCode = httpClient.responseStatusCode(); - String response = httpClient.responseBody(); - - Serial.println(hueCmd); - Serial.print("Status code from server: "); - Serial.println(statusCode); - Serial.print("Server response: "); - Serial.println(response); - Serial.println(); -} - - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino deleted file mode 100644 index 835a26f..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino +++ /dev/null @@ -1,79 +0,0 @@ -/* - POST with headers client for ArduinoHttpClient library - Connects to server once every five seconds, sends a POST request - with custome headers and a request body - - - - created 14 Feb 2016 - by Tom Igoe - modified 18 Mar 2017 - by Sandeep Mistry - - this example is in the public domain - */ -#include -#include - -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("making POST request"); - String postData = "name=Alice&age=12"; - - client.beginRequest(); - client.post("/"); - client.sendHeader("Content-Type", "application/x-www-form-urlencoded"); - client.sendHeader("Content-Length", postData.length()); - client.sendHeader("X-Custom-Header", "custom-header-value"); - client.beginBody(); - client.print(postData); - client.endRequest(); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - Serial.println("Wait five seconds"); - delay(5000); -} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino deleted file mode 100644 index 374a145..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino +++ /dev/null @@ -1,71 +0,0 @@ -/* - Simple DELETE client for ArduinoHttpClient library - Connects to server once every five seconds, sends a DELETE request - and a request body - - - - created 14 Feb 2016 - by Tom Igoe - - this example is in the public domain - */ -#include -#include - -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("making DELETE request"); - String contentType = "application/x-www-form-urlencoded"; - String delData = "name=light&age=46"; - - client.del("/", contentType, delData); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - Serial.println("Wait five seconds"); - delay(5000); -} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino deleted file mode 100644 index 75db9a7..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino +++ /dev/null @@ -1,66 +0,0 @@ -/* - Simple GET client for ArduinoHttpClient library - Connects to server once every five seconds, sends a GET request - - - - created 14 Feb 2016 - by Tom Igoe - - this example is in the public domain - */ -#include -#include - -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("making GET request"); - client.get("/"); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - Serial.println("Wait five seconds"); - delay(5000); -} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino deleted file mode 100644 index f64b9ba..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino +++ /dev/null @@ -1,133 +0,0 @@ -// (c) Copyright 2010-2012 MCQN Ltd. -// Released under Apache License, version 2.0 -// -// Simple example to show how to use the HttpClient library -// Get's the web page given at http:// and -// outputs the content to the serial port - -#include -#include -#include - -// This example downloads the URL "http://arduino.cc/" - -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - - - -// Name of the server we want to connect to -const char kHostname[] = "arduino.cc"; -// Path to download (this is the bit after the hostname in the URL -// that you want to download -const char kPath[] = "/"; - -// Number of milliseconds to wait without receiving any data before we give up -const int kNetworkTimeout = 30*1000; -// Number of milliseconds to wait if no data is available before trying again -const int kNetworkDelay = 1000; - -WiFiClient c; -HttpClient http(c, kHostname); - -void setup() -{ - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // attempt to connect to Wifi network: - Serial.print("Attempting to connect to WPA SSID: "); - Serial.println(ssid); - while (WiFi.begin(ssid, pass) != WL_CONNECTED) { - // unsuccessful, retry in 4 seconds - Serial.print("failed ... "); - delay(4000); - Serial.print("retrying ... "); - } - - Serial.println("connected"); -} - -void loop() -{ - int err =0; - - err = http.get(kPath); - if (err == 0) - { - Serial.println("startedRequest ok"); - - err = http.responseStatusCode(); - if (err >= 0) - { - Serial.print("Got status code: "); - Serial.println(err); - - // Usually you'd check that the response code is 200 or a - // similar "success" code (200-299) before carrying on, - // but we'll print out whatever response we get - - // If you are interesting in the response headers, you - // can read them here: - //while(http.headerAvailable()) - //{ - // String headerName = http.readHeaderName(); - // String headerValue = http.readHeaderValue(); - //} - - int bodyLen = http.contentLength(); - Serial.print("Content length is: "); - Serial.println(bodyLen); - Serial.println(); - Serial.println("Body returned follows:"); - - // Now we've got to the body, so we can print it out - unsigned long timeoutStart = millis(); - char c; - // Whilst we haven't timed out & haven't reached the end of the body - while ( (http.connected() || http.available()) && - (!http.endOfBodyReached()) && - ((millis() - timeoutStart) < kNetworkTimeout) ) - { - if (http.available()) - { - c = http.read(); - // Print out this character - Serial.print(c); - - // We read something, reset the timeout counter - timeoutStart = millis(); - } - else - { - // We haven't got any data, so let's pause to allow some to - // arrive - delay(kNetworkDelay); - } - } - } - else - { - Serial.print("Getting response failed: "); - Serial.println(err); - } - } - else - { - Serial.print("Connect failed: "); - Serial.println(err); - } - http.stop(); - - // And just stop, now that we've tried a download - while(1); -} - - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino deleted file mode 100644 index 6cc3517..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino +++ /dev/null @@ -1,70 +0,0 @@ -/* - Simple POST client for ArduinoHttpClient library - Connects to server once every five seconds, sends a POST request - and a request body - - - - created 14 Feb 2016 - by Tom Igoe - - this example is in the public domain - */ -#include -#include -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("making POST request"); - String contentType = "application/x-www-form-urlencoded"; - String postData = "name=Alice&age=12"; - - client.post("/", contentType, postData); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - Serial.println("Wait five seconds"); - delay(5000); -} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino deleted file mode 100644 index 1b06105..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino +++ /dev/null @@ -1,70 +0,0 @@ -/* - Simple PUT client for ArduinoHttpClient library - Connects to server once every five seconds, sends a PUT request - and a request body - - - - created 14 Feb 2016 - by Tom Igoe - - this example is in the public domain - */ -#include -#include -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("making PUT request"); - String contentType = "application/x-www-form-urlencoded"; - String putData = "name=light&age=46"; - - client.put("/", contentType, putData); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - Serial.println("Wait five seconds"); - delay(5000); -} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino deleted file mode 100644 index baac12f..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino +++ /dev/null @@ -1,80 +0,0 @@ -/* - Simple WebSocket client for ArduinoHttpClient library - Connects to the WebSocket server, and sends a hello - message every 5 seconds - - - created 28 Jun 2016 - by Sandeep Mistry - - this example is in the public domain -*/ -#include -#include -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - -char serverAddress[] = "echo.websocket.org"; // server address -int port = 80; - -WiFiClient wifi; -WebSocketClient client = WebSocketClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -int count = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("starting WebSocket client"); - client.begin(); - - while (client.connected()) { - Serial.print("Sending hello "); - Serial.println(count); - - // send a hello # - client.beginMessage(TYPE_TEXT); - client.print("hello "); - client.print(count); - client.endMessage(); - - // increment count for next message - count++; - - // check if a message is available to be received - int messageSize = client.parseMessage(); - - if (messageSize > 0) { - Serial.println("Received a message:"); - Serial.println(client.readString()); - } - - // wait 5 seconds - delay(5000); - } - - Serial.println("disconnected"); -} - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js deleted file mode 100644 index f3dd4d8..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js +++ /dev/null @@ -1,102 +0,0 @@ -/* - Express.js GET/POST example - Shows how handle GET, POST, PUT, DELETE - in Express.js 4.0 - - created 14 Feb 2016 - by Tom Igoe -*/ - -var express = require('express'); // include express.js -var app = express(); // a local instance of it -var bodyParser = require('body-parser'); // include body-parser -var WebSocketServer = require('ws').Server // include Web Socket server - -// you need a body parser: -app.use(bodyParser.urlencoded({extended: false})); // for application/x-www-form-urlencoded - -// this runs after the server successfully starts: -function serverStart() { - var port = server.address().port; - console.log('Server listening on port '+ port); -} - -app.get('/chunked', function(request, response) { - response.write('\n'); - response.write(' `:;;;,` .:;;:. \n'); - response.write(' .;;;;;;;;;;;` :;;;;;;;;;;: TM \n'); - response.write(' `;;;;;;;;;;;;;;;` :;;;;;;;;;;;;;;; \n'); - response.write(' :;;;;;;;;;;;;;;;;;; `;;;;;;;;;;;;;;;;;; \n'); - response.write(' ;;;;;;;;;;;;;;;;;;;;; .;;;;;;;;;;;;;;;;;;;; \n'); - response.write(' ;;;;;;;;:` `;;;;;;;;; ,;;;;;;;;.` .;;;;;;;; \n'); - response.write(' .;;;;;;, :;;;;;;; .;;;;;;; ;;;;;;; \n'); - response.write(' ;;;;;; ;;;;;;; ;;;;;;, ;;;;;;. \n'); - response.write(' ,;;;;; ;;;;;;.;;;;;;` ;;;;;; \n'); - response.write(' ;;;;;. ;;;;;;;;;;;` ``` ;;;;;`\n'); - response.write(' ;;;;; ;;;;;;;;;, ;;; .;;;;;\n'); - response.write('`;;;;: `;;;;;;;; ;;; ;;;;;\n'); - response.write(',;;;;` `,,,,,,,, ;;;;;;; .,,;;;,,, ;;;;;\n'); - response.write(':;;;;` .;;;;;;;; ;;;;;, :;;;;;;;; ;;;;;\n'); - response.write(':;;;;` .;;;;;;;; `;;;;;; :;;;;;;;; ;;;;;\n'); - response.write('.;;;;. ;;;;;;;. ;;; ;;;;;\n'); - response.write(' ;;;;; ;;;;;;;;; ;;; ;;;;;\n'); - response.write(' ;;;;; .;;;;;;;;;; ;;; ;;;;;,\n'); - response.write(' ;;;;;; `;;;;;;;;;;;; ;;;;; \n'); - response.write(' `;;;;;, .;;;;;; ;;;;;;; ;;;;;; \n'); - response.write(' ;;;;;;: :;;;;;;. ;;;;;;; ;;;;;; \n'); - response.write(' ;;;;;;;` .;;;;;;;, ;;;;;;;; ;;;;;;;: \n'); - response.write(' ;;;;;;;;;:,:;;;;;;;;;: ;;;;;;;;;;:,;;;;;;;;;; \n'); - response.write(' `;;;;;;;;;;;;;;;;;;;. ;;;;;;;;;;;;;;;;;;;; \n'); - response.write(' ;;;;;;;;;;;;;;;;; :;;;;;;;;;;;;;;;;: \n'); - response.write(' ,;;;;;;;;;;;;;, ;;;;;;;;;;;;;; \n'); - response.write(' .;;;;;;;;;` ,;;;;;;;;: \n'); - response.write(' \n'); - response.write(' \n'); - response.write(' \n'); - response.write(' \n'); - response.write(' ;;; ;;;;;` ;;;;: .;; ;; ,;;;;;, ;;. `;, ;;;; \n'); - response.write(' ;;; ;;:;;; ;;;;;; .;; ;; ,;;;;;: ;;; `;, ;;;:;; \n'); - response.write(' ,;:; ;; ;; ;; ;; .;; ;; ,;, ;;;,`;, ;; ;; \n'); - response.write(' ;; ;: ;; ;; ;; ;; .;; ;; ,;, ;;;;`;, ;; ;;. \n'); - response.write(' ;: ;; ;;;;;: ;; ;; .;; ;; ,;, ;;`;;;, ;; ;;` \n'); - response.write(' ,;;;;; ;;`;; ;; ;; .;; ;; ,;, ;; ;;;, ;; ;; \n'); - response.write(' ;; ,;, ;; .;; ;;;;;: ;;;;;: ,;;;;;: ;; ;;, ;;;;;; \n'); - response.write(' ;; ;; ;; ;;` ;;;;. `;;;: ,;;;;;, ;; ;;, ;;;; \n'); - response.write('\n'); - response.end(); -}); - -// this is the POST handler: -app.all('/*', function (request, response) { - console.log('Got a ' + request.method + ' request'); - // the parameters of a GET request are passed in - // request.body. Pass that to formatResponse() - // for formatting: - console.log(request.headers); - if (request.method == 'GET') { - console.log(request.query); - } else { - console.log(request.body); - } - - // send the response: - response.send('OK'); - response.end(); -}); - -// start the server: -var server = app.listen(8080, serverStart); - -// create a WebSocket server and attach it to the server -var wss = new WebSocketServer({server: server}); - -wss.on('connection', function connection(ws) { - // new connection, add message listener - ws.on('message', function incoming(message) { - // received a message - console.log('received: %s', message); - - // echo it back - ws.send(message); - }); -}); diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/node_test_server/package.json b/feather_sensor_lte/libraries/ArduinoHttpClient/examples/node_test_server/package.json deleted file mode 100644 index 09f2d8b..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/examples/node_test_server/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "node_test_server", - "version": "0.0.1", - "author": { - "name": "Tom Igoe" - }, - "dependencies": { - "body-parser": ">=1.11.0", - "express": ">=4.0.0", - "multer": "*", - "ws": "^1.1.1" - } -} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/keywords.txt b/feather_sensor_lte/libraries/ArduinoHttpClient/keywords.txt deleted file mode 100644 index 27cd516..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/keywords.txt +++ /dev/null @@ -1,64 +0,0 @@ -####################################### -# Syntax Coloring Map For HttpClient -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -ArduinoHttpClient KEYWORD1 -HttpClient KEYWORD1 -WebSocketClient KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -get KEYWORD2 -post KEYWORD2 -put KEYWORD2 -patch KEYWORD2 -startRequest KEYWORD2 -beginRequest KEYWORD2 -beginBody KEYWORD2 -sendHeader KEYWORD2 -sendBasicAuth KEYWORD2 -endRequest KEYWORD2 -responseStatusCode KEYWORD2 -readHeader KEYWORD2 -skipResponseHeaders KEYWORD2 -endOfHeadersReached KEYWORD2 -endOfBodyReached KEYWORD2 -completed KEYWORD2 -contentLength KEYWORD2 -isResponseChunked KEYWORD2 -connectionKeepAlive KEYWORD2 -noDefaultRequestHeaders KEYWORD2 -headerAvailable KEYWORD2 -readHeaderName KEYWORD2 -readHeaderValue KEYWORD2 -responseBody KEYWORD2 - -beginMessage KEYWORD2 -endMessage KEYWORD2 -parseMessage KEYWORD2 -messageType KEYWORD2 -isFinal KEYWORD2 -readString KEYWORD2 -ping KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### -HTTP_SUCCESS LITERAL1 -HTTP_ERROR_CONNECTION_FAILED LITERAL1 -HTTP_ERROR_API LITERAL1 -HTTP_ERROR_TIMED_OUT LITERAL1 -HTTP_ERROR_INVALID_RESPONSE LITERAL1 - -TYPE_CONTINUATION LITERAL1 -TYPE_TEXT LITERAL1 -TYPE_BINARY LITERAL1 -TYPE_CONNECTION_CLOSE LITERAL1 -TYPE_PING LITERAL1 -TYPE_PONG LITERAL1 diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/library.json b/feather_sensor_lte/libraries/ArduinoHttpClient/library.json deleted file mode 100644 index 6bbda24..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/library.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "ArduinoHttpClient", - "keywords": "http, web, client, ethernet, wifi, GSM", - "description": "Easily interact with web servers from Arduino, using HTTP and WebSocket's.", - "repository": - { - "type": "git", - "url": "https://github.com/arduino-libraries/ArduinoHttpClient.git" - }, - "frameworks": "arduino", - "platforms": "*" -} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/library.properties b/feather_sensor_lte/libraries/ArduinoHttpClient/library.properties deleted file mode 100644 index 2ac5bb5..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/library.properties +++ /dev/null @@ -1,10 +0,0 @@ -name=ArduinoHttpClient -version=0.3.1 -author=Arduino -maintainer=Arduino -sentence=[EXPERIMENTAL] Easily interact with web servers from Arduino, using HTTP and WebSocket's. -paragraph=This library can be used for HTTP (GET, POST, PUT, DELETE) requests to a web server. It also supports exchanging messages with WebSocket servers. Based on Adrian McEwen's HttpClient library. -category=Communication -url=https://github.com/arduino-libraries/ArduinoHttpClient -architectures=* -includes=ArduinoHttpClient.h diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h b/feather_sensor_lte/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h deleted file mode 100644 index 578733f..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h +++ /dev/null @@ -1,11 +0,0 @@ -// Library to simplify HTTP fetching on Arduino -// (c) Copyright Arduino. 2016 -// Released under Apache License, version 2.0 - -#ifndef ArduinoHttpClient_h -#define ArduinoHttpClient_h - -#include "HttpClient.h" -#include "WebSocketClient.h" - -#endif diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/src/HttpClient.cpp b/feather_sensor_lte/libraries/ArduinoHttpClient/src/HttpClient.cpp deleted file mode 100644 index 7517eea..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/src/HttpClient.cpp +++ /dev/null @@ -1,862 +0,0 @@ -// Class to simplify HTTP fetching on Arduino -// (c) Copyright 2010-2011 MCQN Ltd -// Released under Apache License, version 2.0 - -#include "HttpClient.h" -#include "b64.h" - -// Initialize constants -const char* HttpClient::kUserAgent = "Arduino/2.2.0"; -const char* HttpClient::kContentLengthPrefix = HTTP_HEADER_CONTENT_LENGTH ": "; -const char* HttpClient::kTransferEncodingChunked = HTTP_HEADER_TRANSFER_ENCODING ": " HTTP_HEADER_VALUE_CHUNKED; - -HttpClient::HttpClient(Client& aClient, const char* aServerName, uint16_t aServerPort) - : iClient(&aClient), iServerName(aServerName), iServerAddress(), iServerPort(aServerPort), - iConnectionClose(true), iSendDefaultRequestHeaders(true) -{ - resetState(); -} - -HttpClient::HttpClient(Client& aClient, const String& aServerName, uint16_t aServerPort) - : HttpClient(aClient, aServerName.c_str(), aServerPort) -{ -} - -HttpClient::HttpClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort) - : iClient(&aClient), iServerName(NULL), iServerAddress(aServerAddress), iServerPort(aServerPort), - iConnectionClose(true), iSendDefaultRequestHeaders(true) -{ - resetState(); -} - -void HttpClient::resetState() -{ - iState = eIdle; - iStatusCode = 0; - iContentLength = kNoContentLengthHeader; - iBodyLengthConsumed = 0; - iContentLengthPtr = kContentLengthPrefix; - iTransferEncodingChunkedPtr = kTransferEncodingChunked; - iIsChunked = false; - iChunkLength = 0; - iHttpResponseTimeout = kHttpResponseTimeout; -} - -void HttpClient::stop() -{ - iClient->stop(); - resetState(); -} - -void HttpClient::connectionKeepAlive() -{ - iConnectionClose = false; -} - -void HttpClient::noDefaultRequestHeaders() -{ - iSendDefaultRequestHeaders = false; -} - -void HttpClient::beginRequest() -{ - iState = eRequestStarted; -} - -int HttpClient::startRequest(const char* aURLPath, const char* aHttpMethod, - const char* aContentType, int aContentLength, const byte aBody[]) -{ - if (iState == eReadingBody || iState == eReadingChunkLength || iState == eReadingBodyChunk) - { - flushClientRx(); - - resetState(); - } - - tHttpState initialState = iState; - - if ((eIdle != iState) && (eRequestStarted != iState)) - { - return HTTP_ERROR_API; - } - - if (iConnectionClose || !iClient->connected()) - { - if (iServerName) - { - if (!iClient->connect(iServerName, iServerPort) > 0) - { -#ifdef LOGGING - Serial.println("Connection failed"); -#endif - return HTTP_ERROR_CONNECTION_FAILED; - } - } - else - { - if (!iClient->connect(iServerAddress, iServerPort) > 0) - { -#ifdef LOGGING - Serial.println("Connection failed"); -#endif - return HTTP_ERROR_CONNECTION_FAILED; - } - } - } - else - { -#ifdef LOGGING - Serial.println("Connection already open"); -#endif - } - - // Now we're connected, send the first part of the request - int ret = sendInitialHeaders(aURLPath, aHttpMethod); - - if (HTTP_SUCCESS == ret) - { - if (aContentType) - { - sendHeader(HTTP_HEADER_CONTENT_TYPE, aContentType); - } - - if (aContentLength > 0) - { - sendHeader(HTTP_HEADER_CONTENT_LENGTH, aContentLength); - } - - bool hasBody = (aBody && aContentLength > 0); - - if (initialState == eIdle || hasBody) - { - // This was a simple version of the API, so terminate the headers now - finishHeaders(); - } - // else we'll call it in endRequest or in the first call to print, etc. - - if (hasBody) - { - write(aBody, aContentLength); - } - } - - return ret; -} - -int HttpClient::sendInitialHeaders(const char* aURLPath, const char* aHttpMethod) -{ -#ifdef LOGGING - Serial.println("Connected"); -#endif - // Send the HTTP command, i.e. "GET /somepath/ HTTP/1.0" - iClient->print(aHttpMethod); - iClient->print(" "); - - iClient->print(aURLPath); - iClient->println(" HTTP/1.1"); - if (iSendDefaultRequestHeaders) - { - // The host header, if required - if (iServerName) - { - iClient->print("Host: "); - iClient->print(iServerName); - if (iServerPort != kHttpPort) - { - iClient->print(":"); - iClient->print(iServerPort); - } - iClient->println(); - } - // And user-agent string - sendHeader(HTTP_HEADER_USER_AGENT, kUserAgent); - } - - if (iConnectionClose) - { - // Tell the server to - // close this connection after we're done - sendHeader(HTTP_HEADER_CONNECTION, "close"); - } - - // Everything has gone well - iState = eRequestStarted; - return HTTP_SUCCESS; -} - -void HttpClient::sendHeader(const char* aHeader) -{ - iClient->println(aHeader); -} - -void HttpClient::sendHeader(const char* aHeaderName, const char* aHeaderValue) -{ - iClient->print(aHeaderName); - iClient->print(": "); - iClient->println(aHeaderValue); -} - -void HttpClient::sendHeader(const char* aHeaderName, const int aHeaderValue) -{ - iClient->print(aHeaderName); - iClient->print(": "); - iClient->println(aHeaderValue); -} - -void HttpClient::sendBasicAuth(const char* aUser, const char* aPassword) -{ - // Send the initial part of this header line - iClient->print("Authorization: Basic "); - // Now Base64 encode "aUser:aPassword" and send that - // This seems trickier than it should be but it's mostly to avoid either - // (a) some arbitrarily sized buffer which hopes to be big enough, or - // (b) allocating and freeing memory - // ...so we'll loop through 3 bytes at a time, outputting the results as we - // go. - // In Base64, each 3 bytes of unencoded data become 4 bytes of encoded data - unsigned char input[3]; - unsigned char output[5]; // Leave space for a '\0' terminator so we can easily print - int userLen = strlen(aUser); - int passwordLen = strlen(aPassword); - int inputOffset = 0; - for (int i = 0; i < (userLen+1+passwordLen); i++) - { - // Copy the relevant input byte into the input - if (i < userLen) - { - input[inputOffset++] = aUser[i]; - } - else if (i == userLen) - { - input[inputOffset++] = ':'; - } - else - { - input[inputOffset++] = aPassword[i-(userLen+1)]; - } - // See if we've got a chunk to encode - if ( (inputOffset == 3) || (i == userLen+passwordLen) ) - { - // We've either got to a 3-byte boundary, or we've reached then end - b64_encode(input, inputOffset, output, 4); - // NUL-terminate the output string - output[4] = '\0'; - // And write it out - iClient->print((char*)output); -// FIXME We might want to fill output with '=' characters if b64_encode doesn't -// FIXME do it for us when we're encoding the final chunk - inputOffset = 0; - } - } - // And end the header we've sent - iClient->println(); -} - -void HttpClient::finishHeaders() -{ - iClient->println(); - iState = eRequestSent; -} - -void HttpClient::flushClientRx() -{ - while (iClient->available()) - { - iClient->read(); - } -} - -void HttpClient::endRequest() -{ - beginBody(); -} - -void HttpClient::beginBody() -{ - if (iState < eRequestSent) - { - // We still need to finish off the headers - finishHeaders(); - } - // else the end of headers has already been sent, so nothing to do here -} - -int HttpClient::get(const char* aURLPath) -{ - return startRequest(aURLPath, HTTP_METHOD_GET); -} - -int HttpClient::get(const String& aURLPath) -{ - return get(aURLPath.c_str()); -} - -int HttpClient::post(const char* aURLPath) -{ - return startRequest(aURLPath, HTTP_METHOD_POST); -} - -int HttpClient::post(const String& aURLPath) -{ - return post(aURLPath.c_str()); -} - -int HttpClient::post(const char* aURLPath, const char* aContentType, const char* aBody) -{ - return post(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); -} - -int HttpClient::post(const String& aURLPath, const String& aContentType, const String& aBody) -{ - return post(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); -} - -int HttpClient::post(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) -{ - return startRequest(aURLPath, HTTP_METHOD_POST, aContentType, aContentLength, aBody); -} - -int HttpClient::put(const char* aURLPath) -{ - return startRequest(aURLPath, HTTP_METHOD_PUT); -} - -int HttpClient::put(const String& aURLPath) -{ - return put(aURLPath.c_str()); -} - -int HttpClient::put(const char* aURLPath, const char* aContentType, const char* aBody) -{ - return put(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); -} - -int HttpClient::put(const String& aURLPath, const String& aContentType, const String& aBody) -{ - return put(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); -} - -int HttpClient::put(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) -{ - return startRequest(aURLPath, HTTP_METHOD_PUT, aContentType, aContentLength, aBody); -} - -int HttpClient::patch(const char* aURLPath) -{ - return startRequest(aURLPath, HTTP_METHOD_PATCH); -} - -int HttpClient::patch(const String& aURLPath) -{ - return patch(aURLPath.c_str()); -} - -int HttpClient::patch(const char* aURLPath, const char* aContentType, const char* aBody) -{ - return patch(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); -} - -int HttpClient::patch(const String& aURLPath, const String& aContentType, const String& aBody) -{ - return patch(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); -} - -int HttpClient::patch(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) -{ - return startRequest(aURLPath, HTTP_METHOD_PATCH, aContentType, aContentLength, aBody); -} - -int HttpClient::del(const char* aURLPath) -{ - return startRequest(aURLPath, HTTP_METHOD_DELETE); -} - -int HttpClient::del(const String& aURLPath) -{ - return del(aURLPath.c_str()); -} - -int HttpClient::del(const char* aURLPath, const char* aContentType, const char* aBody) -{ - return del(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); -} - -int HttpClient::del(const String& aURLPath, const String& aContentType, const String& aBody) -{ - return del(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); -} - -int HttpClient::del(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) -{ - return startRequest(aURLPath, HTTP_METHOD_DELETE, aContentType, aContentLength, aBody); -} - -int HttpClient::responseStatusCode() -{ - if (iState < eRequestSent) - { - return HTTP_ERROR_API; - } - // The first line will be of the form Status-Line: - // HTTP-Version SP Status-Code SP Reason-Phrase CRLF - // Where HTTP-Version is of the form: - // HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT - - int c = '\0'; - do - { - // Make sure the status code is reset, and likewise the state. This - // lets us easily cope with 1xx informational responses by just - // ignoring them really, and reading the next line for a proper response - iStatusCode = 0; - iState = eRequestSent; - - unsigned long timeoutStart = millis(); - // Psuedo-regexp we're expecting before the status-code - const char* statusPrefix = "HTTP/*.* "; - const char* statusPtr = statusPrefix; - // Whilst we haven't timed out & haven't reached the end of the headers - while ((c != '\n') && - ( (millis() - timeoutStart) < iHttpResponseTimeout )) - { - if (available()) - { - c = read(); - if (c != -1) - { - switch(iState) - { - case eRequestSent: - // We haven't reached the status code yet - if ( (*statusPtr == '*') || (*statusPtr == c) ) - { - // This character matches, just move along - statusPtr++; - if (*statusPtr == '\0') - { - // We've reached the end of the prefix - iState = eReadingStatusCode; - } - } - else - { - return HTTP_ERROR_INVALID_RESPONSE; - } - break; - case eReadingStatusCode: - if (isdigit(c)) - { - // This assumes we won't get more than the 3 digits we - // want - iStatusCode = iStatusCode*10 + (c - '0'); - } - else - { - // We've reached the end of the status code - // We could sanity check it here or double-check for ' ' - // rather than anything else, but let's be lenient - iState = eStatusCodeRead; - } - break; - case eStatusCodeRead: - // We're just waiting for the end of the line now - break; - - default: - break; - }; - // We read something, reset the timeout counter - timeoutStart = millis(); - } - } - else - { - // We haven't got any data, so let's pause to allow some to - // arrive - delay(kHttpWaitForDataDelay); - } - } - if ( (c == '\n') && (iStatusCode < 200 && iStatusCode != 101) ) - { - // We've reached the end of an informational status line - c = '\0'; // Clear c so we'll go back into the data reading loop - } - } - // If we've read a status code successfully but it's informational (1xx) - // loop back to the start - while ( (iState == eStatusCodeRead) && (iStatusCode < 200 && iStatusCode != 101) ); - - if ( (c == '\n') && (iState == eStatusCodeRead) ) - { - // We've read the status-line successfully - return iStatusCode; - } - else if (c != '\n') - { - // We must've timed out before we reached the end of the line - return HTTP_ERROR_TIMED_OUT; - } - else - { - // This wasn't a properly formed status line, or at least not one we - // could understand - return HTTP_ERROR_INVALID_RESPONSE; - } -} - -int HttpClient::skipResponseHeaders() -{ - // Just keep reading until we finish reading the headers or time out - unsigned long timeoutStart = millis(); - // Whilst we haven't timed out & haven't reached the end of the headers - while ((!endOfHeadersReached()) && - ( (millis() - timeoutStart) < iHttpResponseTimeout )) - { - if (available()) - { - (void)readHeader(); - // We read something, reset the timeout counter - timeoutStart = millis(); - } - else - { - // We haven't got any data, so let's pause to allow some to - // arrive - delay(kHttpWaitForDataDelay); - } - } - if (endOfHeadersReached()) - { - // Success - return HTTP_SUCCESS; - } - else - { - // We must've timed out - return HTTP_ERROR_TIMED_OUT; - } -} - -bool HttpClient::endOfHeadersReached() -{ - return (iState == eReadingBody || iState == eReadingChunkLength || iState == eReadingBodyChunk); -}; - -int HttpClient::contentLength() -{ - // skip the response headers, if they haven't been read already - if (!endOfHeadersReached()) - { - skipResponseHeaders(); - } - - return iContentLength; -} - -String HttpClient::responseBody() -{ - int bodyLength = contentLength(); - String response; - - if (bodyLength > 0) - { - // try to reserve bodyLength bytes - if (response.reserve(bodyLength) == 0) { - // String reserve failed - return String((const char*)NULL); - } - } - - // keep on timedRead'ing, until: - // - we have a content length: body length equals consumed or no bytes - // available - // - no content length: no bytes are available - while (iBodyLengthConsumed != bodyLength) - { - int c = timedRead(); - - if (c == -1) { - // read timed out, done - break; - } - - if (!response.concat((char)c)) { - // adding char failed - return String((const char*)NULL); - } - } - - if (bodyLength > 0 && (unsigned int)bodyLength != response.length()) { - // failure, we did not read in reponse content length bytes - return String((const char*)NULL); - } - - return response; -} - -bool HttpClient::endOfBodyReached() -{ - if (endOfHeadersReached() && (contentLength() != kNoContentLengthHeader)) - { - // We've got to the body and we know how long it will be - return (iBodyLengthConsumed >= contentLength()); - } - return false; -} - -int HttpClient::available() -{ - if (iState == eReadingChunkLength) - { - while (iClient->available()) - { - char c = iClient->read(); - - if (c == '\n') - { - iState = eReadingBodyChunk; - break; - } - else if (c == '\r') - { - // no-op - } - else if (isHexadecimalDigit(c)) - { - char digit[2] = {c, '\0'}; - - iChunkLength = (iChunkLength * 16) + strtol(digit, NULL, 16); - } - } - } - - if (iState == eReadingBodyChunk && iChunkLength == 0) - { - iState = eReadingChunkLength; - } - - if (iState == eReadingChunkLength) - { - return 0; - } - - int clientAvailable = iClient->available(); - - if (iState == eReadingBodyChunk) - { - return min(clientAvailable, iChunkLength); - } - else - { - return clientAvailable; - } -} - - -int HttpClient::read() -{ - if (iIsChunked && !available()) - { - return -1; - } - - int ret = iClient->read(); - if (ret >= 0) - { - if (endOfHeadersReached() && iContentLength > 0) - { - // We're outputting the body now and we've seen a Content-Length header - // So keep track of how many bytes are left - iBodyLengthConsumed++; - } - - if (iState == eReadingBodyChunk) - { - iChunkLength--; - - if (iChunkLength == 0) - { - iState = eReadingChunkLength; - } - } - } - return ret; -} - -bool HttpClient::headerAvailable() -{ - // clear the currently store header line - iHeaderLine = ""; - - while (!endOfHeadersReached()) - { - // read a byte from the header - int c = readHeader(); - - if (c == '\r' || c == '\n') - { - if (iHeaderLine.length()) - { - // end of the line, all done - break; - } - else - { - // ignore any CR or LF characters - continue; - } - } - - // append byte to header line - iHeaderLine += (char)c; - } - - return (iHeaderLine.length() > 0); -} - -String HttpClient::readHeaderName() -{ - int colonIndex = iHeaderLine.indexOf(':'); - - if (colonIndex == -1) - { - return ""; - } - - return iHeaderLine.substring(0, colonIndex); -} - -String HttpClient::readHeaderValue() -{ - int colonIndex = iHeaderLine.indexOf(':'); - int startIndex = colonIndex + 1; - - if (colonIndex == -1) - { - return ""; - } - - // trim any leading whitespace - while (startIndex < (int)iHeaderLine.length() && isSpace(iHeaderLine[startIndex])) - { - startIndex++; - } - - return iHeaderLine.substring(startIndex); -} - -int HttpClient::read(uint8_t *buf, size_t size) -{ - int ret =iClient->read(buf, size); - if (endOfHeadersReached() && iContentLength > 0) - { - // We're outputting the body now and we've seen a Content-Length header - // So keep track of how many bytes are left - if (ret >= 0) - { - iBodyLengthConsumed += ret; - } - } - return ret; -} - -int HttpClient::readHeader() -{ - char c = read(); - - if (endOfHeadersReached()) - { - // We've passed the headers, but rather than return an error, we'll just - // act as a slightly less efficient version of read() - return c; - } - - // Whilst reading out the headers to whoever wants them, we'll keep an - // eye out for the "Content-Length" header - switch(iState) - { - case eStatusCodeRead: - // We're at the start of a line, or somewhere in the middle of reading - // the Content-Length prefix - if (*iContentLengthPtr == c) - { - // This character matches, just move along - iContentLengthPtr++; - if (*iContentLengthPtr == '\0') - { - // We've reached the end of the prefix - iState = eReadingContentLength; - // Just in case we get multiple Content-Length headers, this - // will ensure we just get the value of the last one - iContentLength = 0; - iBodyLengthConsumed = 0; - } - } - else if (*iTransferEncodingChunkedPtr == c) - { - // This character matches, just move along - iTransferEncodingChunkedPtr++; - if (*iTransferEncodingChunkedPtr == '\0') - { - // We've reached the end of the Transfer Encoding: chunked header - iIsChunked = true; - iState = eSkipToEndOfHeader; - } - } - else if (((iContentLengthPtr == kContentLengthPrefix) && (iTransferEncodingChunkedPtr == kTransferEncodingChunked)) && (c == '\r')) - { - // We've found a '\r' at the start of a line, so this is probably - // the end of the headers - iState = eLineStartingCRFound; - } - else - { - // This isn't the Content-Length or Transfer Encoding chunked header, skip to the end of the line - iState = eSkipToEndOfHeader; - } - break; - case eReadingContentLength: - if (isdigit(c)) - { - iContentLength = iContentLength*10 + (c - '0'); - } - else - { - // We've reached the end of the content length - // We could sanity check it here or double-check for "\r\n" - // rather than anything else, but let's be lenient - iState = eSkipToEndOfHeader; - } - break; - case eLineStartingCRFound: - if (c == '\n') - { - if (iIsChunked) - { - iState = eReadingChunkLength; - iChunkLength = 0; - } - else - { - iState = eReadingBody; - } - } - break; - default: - // We're just waiting for the end of the line now - break; - }; - - if ( (c == '\n') && !endOfHeadersReached() ) - { - // We've got to the end of this line, start processing again - iState = eStatusCodeRead; - iContentLengthPtr = kContentLengthPrefix; - iTransferEncodingChunkedPtr = kTransferEncodingChunked; - } - // And return the character read to whoever wants it - return c; -} - - - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/src/HttpClient.h b/feather_sensor_lte/libraries/ArduinoHttpClient/src/HttpClient.h deleted file mode 100644 index c954872..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/src/HttpClient.h +++ /dev/null @@ -1,392 +0,0 @@ -// Class to simplify HTTP fetching on Arduino -// (c) Copyright MCQN Ltd. 2010-2012 -// Released under Apache License, version 2.0 - -#ifndef HttpClient_h -#define HttpClient_h - -#include -#include -#include "Client.h" - -static const int HTTP_SUCCESS =0; -// The end of the headers has been reached. This consumes the '\n' -// Could not connect to the server -static const int HTTP_ERROR_CONNECTION_FAILED =-1; -// This call was made when the HttpClient class wasn't expecting it -// to be called. Usually indicates your code is using the class -// incorrectly -static const int HTTP_ERROR_API =-2; -// Spent too long waiting for a reply -static const int HTTP_ERROR_TIMED_OUT =-3; -// The response from the server is invalid, is it definitely an HTTP -// server? -static const int HTTP_ERROR_INVALID_RESPONSE =-4; - -// Define some of the common methods and headers here -// That lets other code reuse them without having to declare another copy -// of them, so saves code space and RAM -#define HTTP_METHOD_GET "GET" -#define HTTP_METHOD_POST "POST" -#define HTTP_METHOD_PUT "PUT" -#define HTTP_METHOD_PATCH "PATCH" -#define HTTP_METHOD_DELETE "DELETE" -#define HTTP_HEADER_CONTENT_LENGTH "Content-Length" -#define HTTP_HEADER_CONTENT_TYPE "Content-Type" -#define HTTP_HEADER_CONNECTION "Connection" -#define HTTP_HEADER_TRANSFER_ENCODING "Transfer-Encoding" -#define HTTP_HEADER_USER_AGENT "User-Agent" -#define HTTP_HEADER_VALUE_CHUNKED "chunked" - -class HttpClient : public Client -{ -public: - static const int kNoContentLengthHeader =-1; - static const int kHttpPort =80; - static const char* kUserAgent; - -// FIXME Write longer API request, using port and user-agent, example -// FIXME Update tempToPachube example to calculate Content-Length correctly - - HttpClient(Client& aClient, const char* aServerName, uint16_t aServerPort = kHttpPort); - HttpClient(Client& aClient, const String& aServerName, uint16_t aServerPort = kHttpPort); - HttpClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort = kHttpPort); - - /** Start a more complex request. - Use this when you need to send additional headers in the request, - but you will also need to call endRequest() when you are finished. - */ - void beginRequest(); - - /** End a more complex request. - Use this when you need to have sent additional headers in the request, - but you will also need to call beginRequest() at the start. - */ - void endRequest(); - - /** Start the body of a more complex request. - Use this when you need to send the body after additional headers - in the request, but can optionally call endRequest() when - you are finished. - */ - void beginBody(); - - /** Connect to the server and start to send a GET request. - @param aURLPath Url to request - @return 0 if successful, else error - */ - int get(const char* aURLPath); - int get(const String& aURLPath); - - /** Connect to the server and start to send a POST request. - @param aURLPath Url to request - @return 0 if successful, else error - */ - int post(const char* aURLPath); - int post(const String& aURLPath); - - /** Connect to the server and send a POST request - with body and content type - @param aURLPath Url to request - @param aContentType Content type of request body - @param aBody Body of the request - @return 0 if successful, else error - */ - int post(const char* aURLPath, const char* aContentType, const char* aBody); - int post(const String& aURLPath, const String& aContentType, const String& aBody); - int post(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); - - /** Connect to the server and start to send a PUT request. - @param aURLPath Url to request - @return 0 if successful, else error - */ - int put(const char* aURLPath); - int put(const String& aURLPath); - - /** Connect to the server and send a PUT request - with body and content type - @param aURLPath Url to request - @param aContentType Content type of request body - @param aBody Body of the request - @return 0 if successful, else error - */ - int put(const char* aURLPath, const char* aContentType, const char* aBody); - int put(const String& aURLPath, const String& aContentType, const String& aBody); - int put(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); - - /** Connect to the server and start to send a PATCH request. - @param aURLPath Url to request - @return 0 if successful, else error - */ - int patch(const char* aURLPath); - int patch(const String& aURLPath); - - /** Connect to the server and send a PATCH request - with body and content type - @param aURLPath Url to request - @param aContentType Content type of request body - @param aBody Body of the request - @return 0 if successful, else error - */ - int patch(const char* aURLPath, const char* aContentType, const char* aBody); - int patch(const String& aURLPath, const String& aContentType, const String& aBody); - int patch(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); - - /** Connect to the server and start to send a DELETE request. - @param aURLPath Url to request - @return 0 if successful, else error - */ - int del(const char* aURLPath); - int del(const String& aURLPath); - - /** Connect to the server and send a DELETE request - with body and content type - @param aURLPath Url to request - @param aContentType Content type of request body - @param aBody Body of the request - @return 0 if successful, else error - */ - int del(const char* aURLPath, const char* aContentType, const char* aBody); - int del(const String& aURLPath, const String& aContentType, const String& aBody); - int del(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); - - /** Connect to the server and start to send the request. - If a body is provided, the entire request (including headers and body) will be sent - @param aURLPath Url to request - @param aHttpMethod Type of HTTP request to make, e.g. "GET", "POST", etc. - @param aContentType Content type of request body (optional) - @param aContentLength Length of request body (optional) - @param aBody Body of request (optional) - @return 0 if successful, else error - */ - int startRequest(const char* aURLPath, - const char* aHttpMethod, - const char* aContentType = NULL, - int aContentLength = -1, - const byte aBody[] = NULL); - - /** Send an additional header line. This can only be called in between the - calls to startRequest and finishRequest. - @param aHeader Header line to send, in its entirety (but without the - trailing CRLF. E.g. "Authorization: Basic YQDDCAIGES" - */ - void sendHeader(const char* aHeader); - - void sendHeader(const String& aHeader) - { sendHeader(aHeader.c_str()); } - - /** Send an additional header line. This is an alternate form of - sendHeader() which takes the header name and content as separate strings. - The call will add the ": " to separate the header, so for example, to - send a XXXXXX header call sendHeader("XXXXX", "Something") - @param aHeaderName Type of header being sent - @param aHeaderValue Value for that header - */ - void sendHeader(const char* aHeaderName, const char* aHeaderValue); - - void sendHeader(const String& aHeaderName, const String& aHeaderValue) - { sendHeader(aHeaderName.c_str(), aHeaderValue.c_str()); } - - /** Send an additional header line. This is an alternate form of - sendHeader() which takes the header name and content separately but where - the value is provided as an integer. - The call will add the ": " to separate the header, so for example, to - send a XXXXXX header call sendHeader("XXXXX", 123) - @param aHeaderName Type of header being sent - @param aHeaderValue Value for that header - */ - void sendHeader(const char* aHeaderName, const int aHeaderValue); - - void sendHeader(const String& aHeaderName, const int aHeaderValue) - { sendHeader(aHeaderName.c_str(), aHeaderValue); } - - /** Send a basic authentication header. This will encode the given username - and password, and send them in suitable header line for doing Basic - Authentication. - @param aUser Username for the authorization - @param aPassword Password for the user aUser - */ - void sendBasicAuth(const char* aUser, const char* aPassword); - - void sendBasicAuth(const String& aUser, const String& aPassword) - { sendBasicAuth(aUser.c_str(), aPassword.c_str()); } - - /** Get the HTTP status code contained in the response. - For example, 200 for successful request, 404 for file not found, etc. - */ - int responseStatusCode(); - - /** Check if a header is available to be read. - Use readHeaderName() to read header name, and readHeaderValue() to - read the header value - MUST be called after responseStatusCode() and before contentLength() - */ - bool headerAvailable(); - - /** Read the name of the current response header. - Returns empty string if a header is not available. - */ - String readHeaderName(); - - /** Read the vallue of the current response header. - Returns empty string if a header is not available. - */ - String readHeaderValue(); - - /** Read the next character of the response headers. - This functions in the same way as read() but to be used when reading - through the headers. Check whether or not the end of the headers has - been reached by calling endOfHeadersReached(), although after that point - this will still return data as read() would, but slightly less efficiently - MUST be called after responseStatusCode() and before contentLength() - @return The next character of the response headers - */ - int readHeader(); - - /** Skip any response headers to get to the body. - Use this if you don't want to do any special processing of the headers - returned in the response. You can also use it after you've found all of - the headers you're interested in, and just want to get on with processing - the body. - MUST be called after responseStatusCode() - @return HTTP_SUCCESS if successful, else an error code - */ - int skipResponseHeaders(); - - /** Test whether all of the response headers have been consumed. - @return true if we are now processing the response body, else false - */ - bool endOfHeadersReached(); - - /** Test whether the end of the body has been reached. - Only works if the Content-Length header was returned by the server - @return true if we are now at the end of the body, else false - */ - bool endOfBodyReached(); - virtual bool endOfStream() { return endOfBodyReached(); }; - virtual bool completed() { return endOfBodyReached(); }; - - /** Return the length of the body. - Also skips response headers if they have not been read already - MUST be called after responseStatusCode() - @return Length of the body, in bytes, or kNoContentLengthHeader if no - Content-Length header was returned by the server - */ - int contentLength(); - - /** Returns if the response body is chunked - @return true if response body is chunked, false otherwise - */ - int isResponseChunked() { return iIsChunked; } - - /** Return the response body as a String - Also skips response headers if they have not been read already - MUST be called after responseStatusCode() - @return response body of request as a String - */ - String responseBody(); - - /** Enables connection keep-alive mode - */ - void connectionKeepAlive(); - - /** Disables sending the default request headers (Host and User Agent) - */ - void noDefaultRequestHeaders(); - - // Inherited from Print - // Note: 1st call to these indicates the user is sending the body, so if need - // Note: be we should finish the header first - virtual size_t write(uint8_t aByte) { if (iState < eRequestSent) { finishHeaders(); }; return iClient-> write(aByte); }; - virtual size_t write(const uint8_t *aBuffer, size_t aSize) { if (iState < eRequestSent) { finishHeaders(); }; return iClient->write(aBuffer, aSize); }; - // Inherited from Stream - virtual int available(); - /** Read the next byte from the server. - @return Byte read or -1 if there are no bytes available. - */ - virtual int read(); - virtual int read(uint8_t *buf, size_t size); - virtual int peek() { return iClient->peek(); }; - virtual void flush() { return iClient->flush(); }; - - // Inherited from Client - virtual int connect(IPAddress ip, uint16_t port) { return iClient->connect(ip, port); }; - virtual int connect(const char *host, uint16_t port) { return iClient->connect(host, port); }; - virtual void stop(); - virtual uint8_t connected() { return iClient->connected(); }; - virtual operator bool() { return bool(iClient); }; - virtual uint32_t httpResponseTimeout() { return iHttpResponseTimeout; }; - virtual void setHttpResponseTimeout(uint32_t timeout) { iHttpResponseTimeout = timeout; }; -protected: - /** Reset internal state data back to the "just initialised" state - */ - void resetState(); - - /** Send the first part of the request and the initial headers. - @param aURLPath Url to request - @param aHttpMethod Type of HTTP request to make, e.g. "GET", "POST", etc. - @return 0 if successful, else error - */ - int sendInitialHeaders(const char* aURLPath, - const char* aHttpMethod); - - /* Let the server know that we've reached the end of the headers - */ - void finishHeaders(); - - /** Reading any pending data from the client (used in connection keep alive mode) - */ - void flushClientRx(); - - // Number of milliseconds that we wait each time there isn't any data - // available to be read (during status code and header processing) - static const int kHttpWaitForDataDelay = 1000; - // Number of milliseconds that we'll wait in total without receiveing any - // data before returning HTTP_ERROR_TIMED_OUT (during status code and header - // processing) - static const int kHttpResponseTimeout = 30*1000; - static const char* kContentLengthPrefix; - static const char* kTransferEncodingChunked; - typedef enum { - eIdle, - eRequestStarted, - eRequestSent, - eReadingStatusCode, - eStatusCodeRead, - eReadingContentLength, - eSkipToEndOfHeader, - eLineStartingCRFound, - eReadingBody, - eReadingChunkLength, - eReadingBodyChunk - } tHttpState; - // Client we're using - Client* iClient; - // Server we are connecting to - const char* iServerName; - IPAddress iServerAddress; - // Port of server we are connecting to - uint16_t iServerPort; - // Current state of the finite-state-machine - tHttpState iState; - // Stores the status code for the response, once known - int iStatusCode; - // Stores the value of the Content-Length header, if present - int iContentLength; - // How many bytes of the response body have been read by the user - int iBodyLengthConsumed; - // How far through a Content-Length header prefix we are - const char* iContentLengthPtr; - // How far through a Transfer-Encoding chunked header we are - const char* iTransferEncodingChunkedPtr; - // Stores if the response body is chunked - bool iIsChunked; - // Stores the value of the current chunk length, if present - int iChunkLength; - uint32_t iHttpResponseTimeout; - bool iConnectionClose; - bool iSendDefaultRequestHeaders; - String iHeaderLine; -}; - -#endif diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/src/WebSocketClient.cpp b/feather_sensor_lte/libraries/ArduinoHttpClient/src/WebSocketClient.cpp deleted file mode 100644 index ab41b0a..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/src/WebSocketClient.cpp +++ /dev/null @@ -1,372 +0,0 @@ -// (c) Copyright Arduino. 2016 -// Released under Apache License, version 2.0 - -#include "b64.h" - -#include "WebSocketClient.h" - -WebSocketClient::WebSocketClient(Client& aClient, const char* aServerName, uint16_t aServerPort) - : HttpClient(aClient, aServerName, aServerPort), - iTxStarted(false), - iRxSize(0) -{ -} - -WebSocketClient::WebSocketClient(Client& aClient, const String& aServerName, uint16_t aServerPort) - : HttpClient(aClient, aServerName, aServerPort), - iTxStarted(false), - iRxSize(0) -{ -} - -WebSocketClient::WebSocketClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort) - : HttpClient(aClient, aServerAddress, aServerPort), - iTxStarted(false), - iRxSize(0) -{ -} - -int WebSocketClient::begin(const char* aPath) -{ - // start the GET request - beginRequest(); - connectionKeepAlive(); - int status = get(aPath); - - if (status == 0) - { - uint8_t randomKey[16]; - char base64RandomKey[25]; - - // create a random key for the connection upgrade - for (int i = 0; i < (int)sizeof(randomKey); i++) - { - randomKey[i] = random(0x01, 0xff); - } - memset(base64RandomKey, 0x00, sizeof(base64RandomKey)); - b64_encode(randomKey, sizeof(randomKey), (unsigned char*)base64RandomKey, sizeof(base64RandomKey)); - - // start the connection upgrade sequence - sendHeader("Upgrade", "websocket"); - sendHeader("Connection", "Upgrade"); - sendHeader("Sec-WebSocket-Key", base64RandomKey); - sendHeader("Sec-WebSocket-Version", "13"); - endRequest(); - - status = responseStatusCode(); - - if (status > 0) - { - skipResponseHeaders(); - } - } - - iRxSize = 0; - - // status code of 101 means success - return (status == 101) ? 0 : status; -} - -int WebSocketClient::begin(const String& aPath) -{ - return begin(aPath.c_str()); -} - -int WebSocketClient::beginMessage(int aType) -{ - if (iTxStarted) - { - // fail TX already started - return 1; - } - - iTxStarted = true; - iTxMessageType = (aType & 0xf); - iTxSize = 0; - - return 0; -} - -int WebSocketClient::endMessage() -{ - if (!iTxStarted) - { - // fail TX not started - return 1; - } - - // send FIN + the message type (opcode) - HttpClient::write(0x80 | iTxMessageType); - - // the message is masked (0x80) - // send the length - if (iTxSize < 126) - { - HttpClient::write(0x80 | (uint8_t)iTxSize); - } - else if (iTxSize < 0xffff) - { - HttpClient::write(0x80 | 126); - HttpClient::write((iTxSize >> 8) & 0xff); - HttpClient::write((iTxSize >> 0) & 0xff); - } - else - { - HttpClient::write(0x80 | 127); - HttpClient::write((iTxSize >> 56) & 0xff); - HttpClient::write((iTxSize >> 48) & 0xff); - HttpClient::write((iTxSize >> 40) & 0xff); - HttpClient::write((iTxSize >> 32) & 0xff); - HttpClient::write((iTxSize >> 24) & 0xff); - HttpClient::write((iTxSize >> 16) & 0xff); - HttpClient::write((iTxSize >> 8) & 0xff); - HttpClient::write((iTxSize >> 0) & 0xff); - } - - uint8_t maskKey[4]; - - // create a random mask for the data and send - for (int i = 0; i < (int)sizeof(maskKey); i++) - { - maskKey[i] = random(0xff); - } - HttpClient::write(maskKey, sizeof(maskKey)); - - // mask the data and send - for (int i = 0; i < (int)iTxSize; i++) { - iTxBuffer[i] ^= maskKey[i % sizeof(maskKey)]; - } - - size_t txSize = iTxSize; - - iTxStarted = false; - iTxSize = 0; - - return (HttpClient::write(iTxBuffer, txSize) == txSize) ? 0 : 1; -} - -size_t WebSocketClient::write(uint8_t aByte) -{ - return write(&aByte, sizeof(aByte)); -} - -size_t WebSocketClient::write(const uint8_t *aBuffer, size_t aSize) -{ - if (iState < eReadingBody) - { - // have not upgraded the connection yet - return HttpClient::write(aBuffer, aSize); - } - - if (!iTxStarted) - { - // fail TX not started - return 0; - } - - // check if the write size, fits in the buffer - if ((iTxSize + aSize) > sizeof(iTxBuffer)) - { - aSize = sizeof(iTxSize) - iTxSize; - } - - // copy data into the buffer - memcpy(iTxBuffer + iTxSize, aBuffer, aSize); - - iTxSize += aSize; - - return aSize; -} - -int WebSocketClient::parseMessage() -{ - flushRx(); - - // make sure 2 bytes (opcode + length) - // are available - if (HttpClient::available() < 2) - { - return 0; - } - - // read open code and length - uint8_t opcode = HttpClient::read(); - int length = HttpClient::read(); - - if ((opcode & 0x0f) == 0) - { - // continuation, use previous opcode and update flags - iRxOpCode |= opcode; - } - else - { - iRxOpCode = opcode; - } - - iRxMasked = (length & 0x80); - length &= 0x7f; - - // read the RX size - if (length < 126) - { - iRxSize = length; - } - else if (length == 126) - { - iRxSize = (HttpClient::read() << 8) | HttpClient::read(); - } - else - { - iRxSize = ((uint64_t)HttpClient::read() << 56) | - ((uint64_t)HttpClient::read() << 48) | - ((uint64_t)HttpClient::read() << 40) | - ((uint64_t)HttpClient::read() << 32) | - ((uint64_t)HttpClient::read() << 24) | - ((uint64_t)HttpClient::read() << 16) | - ((uint64_t)HttpClient::read() << 8) | - (uint64_t)HttpClient::read(); - } - - // read in the mask, if present - if (iRxMasked) - { - for (int i = 0; i < (int)sizeof(iRxMaskKey); i++) - { - iRxMaskKey[i] = HttpClient::read(); - } - } - - iRxMaskIndex = 0; - - if (TYPE_CONNECTION_CLOSE == messageType()) - { - flushRx(); - stop(); - iRxSize = 0; - } - else if (TYPE_PING == messageType()) - { - beginMessage(TYPE_PONG); - while(available()) - { - write(read()); - } - endMessage(); - - iRxSize = 0; - } - else if (TYPE_PONG == messageType()) - { - flushRx(); - iRxSize = 0; - } - - return iRxSize; -} - -int WebSocketClient::messageType() -{ - return (iRxOpCode & 0x0f); -} - -bool WebSocketClient::isFinal() -{ - return ((iRxOpCode & 0x80) != 0); -} - -String WebSocketClient::readString() -{ - int avail = available(); - String s; - - if (avail > 0) - { - s.reserve(avail); - - for (int i = 0; i < avail; i++) - { - s += (char)read(); - } - } - - return s; -} - -int WebSocketClient::ping() -{ - uint8_t pingData[16]; - - // create random data for the ping - for (int i = 0; i < (int)sizeof(pingData); i++) - { - pingData[i] = random(0xff); - } - - beginMessage(TYPE_PING); - write(pingData, sizeof(pingData)); - return endMessage(); -} - -int WebSocketClient::available() -{ - if (iState < eReadingBody) - { - return HttpClient::available(); - } - - return iRxSize; -} - -int WebSocketClient::read() -{ - byte b; - - if (read(&b, sizeof(b))) - { - return b; - } - - return -1; -} - -int WebSocketClient::read(uint8_t *aBuffer, size_t aSize) -{ - int readCount = HttpClient::read(aBuffer, aSize); - - if (readCount > 0) - { - iRxSize -= readCount; - - // unmask the RX data if needed - if (iRxMasked) - { - for (int i = 0; i < (int)aSize; i++, iRxMaskIndex++) - { - aBuffer[i] ^= iRxMaskKey[iRxMaskIndex % sizeof(iRxMaskKey)]; - } - } - } - - return readCount; -} - -int WebSocketClient::peek() -{ - int p = HttpClient::peek(); - - if (p != -1 && iRxMasked) - { - // unmask the RX data if needed - p = (uint8_t)p ^ iRxMaskKey[iRxMaskIndex % sizeof(iRxMaskKey)]; - } - - return p; -} - -void WebSocketClient::flushRx() -{ - while(available()) - { - read(); - } -} diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/src/WebSocketClient.h b/feather_sensor_lte/libraries/ArduinoHttpClient/src/WebSocketClient.h deleted file mode 100644 index 4b009e6..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/src/WebSocketClient.h +++ /dev/null @@ -1,99 +0,0 @@ -// (c) Copyright Arduino. 2016 -// Released under Apache License, version 2.0 - -#ifndef WebSocketClient_h -#define WebSocketClient_h - -#include - -#include "HttpClient.h" - -static const int TYPE_CONTINUATION = 0x0; -static const int TYPE_TEXT = 0x1; -static const int TYPE_BINARY = 0x2; -static const int TYPE_CONNECTION_CLOSE = 0x8; -static const int TYPE_PING = 0x9; -static const int TYPE_PONG = 0xa; - -class WebSocketClient : public HttpClient -{ -public: - WebSocketClient(Client& aClient, const char* aServerName, uint16_t aServerPort = HttpClient::kHttpPort); - WebSocketClient(Client& aClient, const String& aServerName, uint16_t aServerPort = HttpClient::kHttpPort); - WebSocketClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort = HttpClient::kHttpPort); - - /** Start the Web Socket connection to the specified path - @param aURLPath Path to use in request (optional, "/" is used by default) - @return 0 if successful, else error - */ - int begin(const char* aPath = "/"); - int begin(const String& aPath); - - /** Begin to send a message of type (TYPE_TEXT or TYPE_BINARY) - Use the write or Stream API's to set message content, followed by endMessage - to complete the message. - @param aURLPath Path to use in request - @return 0 if successful, else error - */ - int beginMessage(int aType); - - /** Completes sending of a message started by beginMessage - @return 0 if successful, else error - */ - int endMessage(); - - /** Try to parse an incoming messages - @return 0 if no message available, else size of parsed message - */ - int parseMessage(); - - /** Returns type of current parsed message - @return type of current parsedMessage (TYPE_TEXT or TYPE_BINARY) - */ - int messageType(); - - /** Returns if the current message is the final chunk of a split - message - @return true for final message, false otherwise - */ - bool isFinal(); - - /** Read the current messages as a string - @return current message as a string - */ - String readString(); - - /** Send a ping - @return 0 if successful, else error - */ - int ping(); - - // Inherited from Print - virtual size_t write(uint8_t aByte); - virtual size_t write(const uint8_t *aBuffer, size_t aSize); - // Inherited from Stream - virtual int available(); - /** Read the next byte from the server. - @return Byte read or -1 if there are no bytes available. - */ - virtual int read(); - virtual int read(uint8_t *buf, size_t size); - virtual int peek(); - -private: - void flushRx(); - -private: - bool iTxStarted; - uint8_t iTxMessageType; - uint8_t iTxBuffer[128]; - uint64_t iTxSize; - - uint8_t iRxOpCode; - uint64_t iRxSize; - bool iRxMasked; - int iRxMaskIndex; - uint8_t iRxMaskKey[4]; -}; - -#endif diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/src/b64.cpp b/feather_sensor_lte/libraries/ArduinoHttpClient/src/b64.cpp deleted file mode 100644 index 683d60a..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/src/b64.cpp +++ /dev/null @@ -1,72 +0,0 @@ -// Simple Base64 code -// (c) Copyright 2010 MCQN Ltd. -// Released under Apache License, version 2.0 - -#include "b64.h" - -/* Simple test program -#include -void main() -{ - char* in = "amcewen"; - char out[22]; - - b64_encode(in, 15, out, 22); - out[21] = '\0'; - - printf(out); -} -*/ - -int b64_encode(const unsigned char* aInput, int aInputLen, unsigned char* aOutput, int aOutputLen) -{ - // Work out if we've got enough space to encode the input - // Every 6 bits of input becomes a byte of output - if (aOutputLen < (aInputLen*8)/6) - { - // FIXME Should we return an error here, or just the length - return (aInputLen*8)/6; - } - - // If we get here we've got enough space to do the encoding - - const char* b64_dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - if (aInputLen == 3) - { - aOutput[0] = b64_dictionary[aInput[0] >> 2]; - aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4|(aInput[1]>>4)]; - aOutput[2] = b64_dictionary[(aInput[1]&0x0F)<<2|(aInput[2]>>6)]; - aOutput[3] = b64_dictionary[aInput[2]&0x3F]; - } - else if (aInputLen == 2) - { - aOutput[0] = b64_dictionary[aInput[0] >> 2]; - aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4|(aInput[1]>>4)]; - aOutput[2] = b64_dictionary[(aInput[1]&0x0F)<<2]; - aOutput[3] = '='; - } - else if (aInputLen == 1) - { - aOutput[0] = b64_dictionary[aInput[0] >> 2]; - aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4]; - aOutput[2] = '='; - aOutput[3] = '='; - } - else - { - // Break the input into 3-byte chunks and process each of them - int i; - for (i = 0; i < aInputLen/3; i++) - { - b64_encode(&aInput[i*3], 3, &aOutput[i*4], 4); - } - if (aInputLen % 3 > 0) - { - // It doesn't fit neatly into a 3-byte chunk, so process what's left - b64_encode(&aInput[i*3], aInputLen % 3, &aOutput[i*4], aOutputLen - (i*4)); - } - } - - return ((aInputLen+2)/3)*4; -} - diff --git a/feather_sensor_lte/libraries/ArduinoHttpClient/src/b64.h b/feather_sensor_lte/libraries/ArduinoHttpClient/src/b64.h deleted file mode 100644 index cdb1226..0000000 --- a/feather_sensor_lte/libraries/ArduinoHttpClient/src/b64.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef b64_h -#define b64_h - -int b64_encode(const unsigned char* aInput, int aInputLen, unsigned char* aOutput, int aOutputLen); - -#endif diff --git a/feather_sensor_lte/libraries/DHT/.github/ISSUE_TEMPLATE.md b/feather_sensor_lte/libraries/DHT/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index f0e2614..0000000 --- a/feather_sensor_lte/libraries/DHT/.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/feather_sensor_lte/libraries/DHT/.github/PULL_REQUEST_TEMPLATE.md b/feather_sensor_lte/libraries/DHT/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 7b641eb..0000000 --- a/feather_sensor_lte/libraries/DHT/.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/feather_sensor_lte/libraries/DHT/DHT.cpp b/feather_sensor_lte/libraries/DHT/DHT.cpp deleted file mode 100644 index 86ad91c..0000000 --- a/feather_sensor_lte/libraries/DHT/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/feather_sensor_lte/libraries/DHT/DHT.h b/feather_sensor_lte/libraries/DHT/DHT.h deleted file mode 100644 index d81f6db..0000000 --- a/feather_sensor_lte/libraries/DHT/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/feather_sensor_lte/libraries/DHT/DHT_U.cpp b/feather_sensor_lte/libraries/DHT/DHT_U.cpp deleted file mode 100644 index efc7963..0000000 --- a/feather_sensor_lte/libraries/DHT/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/feather_sensor_lte/libraries/DHT/DHT_U.h b/feather_sensor_lte/libraries/DHT/DHT_U.h deleted file mode 100644 index d9ee709..0000000 --- a/feather_sensor_lte/libraries/DHT/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/feather_sensor_lte/libraries/DHT/README.md b/feather_sensor_lte/libraries/DHT/README.md deleted file mode 100644 index d32afdc..0000000 --- a/feather_sensor_lte/libraries/DHT/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/feather_sensor_lte/libraries/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino b/feather_sensor_lte/libraries/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino deleted file mode 100644 index 4820f2e..0000000 --- a/feather_sensor_lte/libraries/DHT/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/feather_sensor_lte/libraries/DHT/examples/DHTtester/DHTtester.ino b/feather_sensor_lte/libraries/DHT/examples/DHTtester/DHTtester.ino deleted file mode 100644 index ae6c41a..0000000 --- a/feather_sensor_lte/libraries/DHT/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/feather_sensor_lte/libraries/DHT/keywords.txt b/feather_sensor_lte/libraries/DHT/keywords.txt deleted file mode 100644 index 146d4fa..0000000 --- a/feather_sensor_lte/libraries/DHT/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/feather_sensor_lte/libraries/DHT/library.properties b/feather_sensor_lte/libraries/DHT/library.properties deleted file mode 100644 index a54c1dc..0000000 --- a/feather_sensor_lte/libraries/DHT/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/feather_sensor_lte/libraries/RTClib/.github/ISSUE_TEMPLATE.md b/feather_sensor_lte/libraries/RTClib/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index f0e2614..0000000 --- a/feather_sensor_lte/libraries/RTClib/.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/feather_sensor_lte/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md b/feather_sensor_lte/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 7b641eb..0000000 --- a/feather_sensor_lte/libraries/RTClib/.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/feather_sensor_lte/libraries/RTClib/README.md b/feather_sensor_lte/libraries/RTClib/README.md deleted file mode 100644 index 661e18d..0000000 --- a/feather_sensor_lte/libraries/RTClib/README.md +++ /dev/null @@ -1,42 +0,0 @@ -This is a fork of JeeLab's fantastic real time clock library for Arduino. - -For details on using this library with an RTC module like the DS1307, PCF8523, or DS3231, see the guide at: https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/overview - -To download. click the DOWNLOADS button to the right, and rename the uncompressed folder RTClib. - -Place the RTClib folder in your *arduinosketchfolder*/libraries/ folder. -You may need to create the libraries subfolder if its your first library. Restart the IDE. - -Please note that dayOfTheWeek() ranges from 0 to 6 inclusive with 0 being 'Sunday' - - - -## Compatibility - -MCU | Tested Works | Doesn't Work | Not Tested | Notes ------------------- | :----------: | :----------: | :---------: | ----- -Atmega328 @ 16MHz | X | | | -Atmega328 @ 12MHz | X | | | -Atmega32u4 @ 16MHz | X | | | Use SDA/SCL on pins D3 & D2 -Atmega32u4 @ 8MHz | X | | | Use SDA/SCL on pins D3 & D2 -ESP8266 | X | | | SDA/SCL default to pins 4 & 5 but any two pins can be assigned as SDA/SCL using Wire.begin(SDA,SCL) -Atmega2560 @ 16MHz | X | | | Use SDA/SCL on Pins 20 & 21 -ATSAM3X8E | X | | | Use SDA1 and SCL1 -ATSAM21D | X | | | -ATtiny85 @ 16MHz | X | | | -ATtiny85 @ 8MHz | X | | | -Intel Curie @ 32MHz | | | X | -STM32F2 | | | X | - - * ATmega328 @ 16MHz : Arduino UNO, Adafruit Pro Trinket 5V, Adafruit Metro 328, Adafruit Metro Mini - * ATmega328 @ 12MHz : Adafruit Pro Trinket 3V - * ATmega32u4 @ 16MHz : Arduino Leonardo, Arduino Micro, Arduino Yun, Teensy 2.0 - * ATmega32u4 @ 8MHz : Adafruit Flora, Bluefruit Micro - * ESP8266 : Adafruit Huzzah - * ATmega2560 @ 16MHz : Arduino Mega - * ATSAM3X8E : Arduino Due - * ATSAM21D : Arduino Zero, M0 Pro - * ATtiny85 @ 16MHz : Adafruit Trinket 5V - * ATtiny85 @ 8MHz : Adafruit Gemma, Arduino Gemma, Adafruit Trinket 3V - - diff --git a/feather_sensor_lte/libraries/RTClib/RTClib.cpp b/feather_sensor_lte/libraries/RTClib/RTClib.cpp deleted file mode 100644 index a08dfe9..0000000 --- a/feather_sensor_lte/libraries/RTClib/RTClib.cpp +++ /dev/null @@ -1,506 +0,0 @@ -// Code by JeeLabs http://news.jeelabs.org/code/ -// Released to the public domain! Enjoy! - -#include -#include "RTClib.h" -#ifdef __AVR__ - #include -#elif defined(ESP8266) - #include -#elif defined(ARDUINO_ARCH_SAMD) -// nothing special needed -#elif defined(ARDUINO_SAM_DUE) - #define PROGMEM - #define pgm_read_byte(addr) (*(const unsigned char *)(addr)) - #define Wire Wire1 -#endif - - - -#if (ARDUINO >= 100) - #include // capital A so it is error prone on case-sensitive filesystems - // Macro to deal with the difference in I2C write functions from old and new Arduino versions. - #define _I2C_WRITE write - #define _I2C_READ read -#else - #include - #define _I2C_WRITE send - #define _I2C_READ receive -#endif - - -static uint8_t read_i2c_register(uint8_t addr, uint8_t reg) { - Wire.beginTransmission(addr); - Wire._I2C_WRITE((byte)reg); - Wire.endTransmission(); - - Wire.requestFrom(addr, (byte)1); - return Wire._I2C_READ(); -} - -static void write_i2c_register(uint8_t addr, uint8_t reg, uint8_t val) { - Wire.beginTransmission(addr); - Wire._I2C_WRITE((byte)reg); - Wire._I2C_WRITE((byte)val); - Wire.endTransmission(); -} - - -//////////////////////////////////////////////////////////////////////////////// -// utility code, some of this could be exposed in the DateTime API if needed - -const uint8_t daysInMonth [] PROGMEM = { 31,28,31,30,31,30,31,31,30,31,30,31 }; - -// number of days since 2000/01/01, valid for 2001..2099 -static uint16_t date2days(uint16_t y, uint8_t m, uint8_t d) { - if (y >= 2000) - y -= 2000; - uint16_t days = d; - for (uint8_t i = 1; i < m; ++i) - days += pgm_read_byte(daysInMonth + i - 1); - if (m > 2 && y % 4 == 0) - ++days; - return days + 365 * y + (y + 3) / 4 - 1; -} - -static long time2long(uint16_t days, uint8_t h, uint8_t m, uint8_t s) { - return ((days * 24L + h) * 60 + m) * 60 + s; -} - -//////////////////////////////////////////////////////////////////////////////// -// DateTime implementation - ignores time zones and DST changes -// NOTE: also ignores leap seconds, see http://en.wikipedia.org/wiki/Leap_second - -DateTime::DateTime (uint32_t t) { - t -= SECONDS_FROM_1970_TO_2000; // bring to 2000 timestamp from 1970 - - ss = t % 60; - t /= 60; - mm = t % 60; - t /= 60; - hh = t % 24; - uint16_t days = t / 24; - uint8_t leap; - for (yOff = 0; ; ++yOff) { - leap = yOff % 4 == 0; - if (days < 365 + leap) - break; - days -= 365 + leap; - } - for (m = 1; ; ++m) { - uint8_t daysPerMonth = pgm_read_byte(daysInMonth + m - 1); - if (leap && m == 2) - ++daysPerMonth; - if (days < daysPerMonth) - break; - days -= daysPerMonth; - } - d = days + 1; -} - -DateTime::DateTime (uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t min, uint8_t sec) { - if (year >= 2000) - year -= 2000; - yOff = year; - m = month; - d = day; - hh = hour; - mm = min; - ss = sec; -} - -DateTime::DateTime (const DateTime& copy): - yOff(copy.yOff), - m(copy.m), - d(copy.d), - hh(copy.hh), - mm(copy.mm), - ss(copy.ss) -{} - -static uint8_t conv2d(const char* p) { - uint8_t v = 0; - if ('0' <= *p && *p <= '9') - v = *p - '0'; - return 10 * v + *++p - '0'; -} - -// A convenient constructor for using "the compiler's time": -// DateTime now (__DATE__, __TIME__); -// NOTE: using F() would further reduce the RAM footprint, see below. -DateTime::DateTime (const char* date, const char* time) { - // sample input: date = "Dec 26 2009", time = "12:34:56" - yOff = conv2d(date + 9); - // Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec - switch (date[0]) { - case 'J': m = (date[1] == 'a') ? 1 : ((date[2] == 'n') ? 6 : 7); break; - case 'F': m = 2; break; - case 'A': m = date[2] == 'r' ? 4 : 8; break; - case 'M': m = date[2] == 'r' ? 3 : 5; break; - case 'S': m = 9; break; - case 'O': m = 10; break; - case 'N': m = 11; break; - case 'D': m = 12; break; - } - d = conv2d(date + 4); - hh = conv2d(time); - mm = conv2d(time + 3); - ss = conv2d(time + 6); -} - -// A convenient constructor for using "the compiler's time": -// This version will save RAM by using PROGMEM to store it by using the F macro. -// DateTime now (F(__DATE__), F(__TIME__)); -DateTime::DateTime (const __FlashStringHelper* date, const __FlashStringHelper* time) { - // sample input: date = "Dec 26 2009", time = "12:34:56" - char buff[11]; - memcpy_P(buff, date, 11); - yOff = conv2d(buff + 9); - // Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec - switch (buff[0]) { - case 'J': m = (buff[1] == 'a') ? 1 : ((buff[2] == 'n') ? 6 : 7); break; - case 'F': m = 2; break; - case 'A': m = buff[2] == 'r' ? 4 : 8; break; - case 'M': m = buff[2] == 'r' ? 3 : 5; break; - case 'S': m = 9; break; - case 'O': m = 10; break; - case 'N': m = 11; break; - case 'D': m = 12; break; - } - d = conv2d(buff + 4); - memcpy_P(buff, time, 8); - hh = conv2d(buff); - mm = conv2d(buff + 3); - ss = conv2d(buff + 6); -} - -uint8_t DateTime::dayOfTheWeek() const { - uint16_t day = date2days(yOff, m, d); - return (day + 6) % 7; // Jan 1, 2000 is a Saturday, i.e. returns 6 -} - -uint32_t DateTime::unixtime(void) const { - uint32_t t; - uint16_t days = date2days(yOff, m, d); - t = time2long(days, hh, mm, ss); - t += SECONDS_FROM_1970_TO_2000; // seconds from 1970 to 2000 - - return t; -} - -long DateTime::secondstime(void) const { - long t; - uint16_t days = date2days(yOff, m, d); - t = time2long(days, hh, mm, ss); - return t; -} - -DateTime DateTime::operator+(const TimeSpan& span) { - return DateTime(unixtime()+span.totalseconds()); -} - -DateTime DateTime::operator-(const TimeSpan& span) { - return DateTime(unixtime()-span.totalseconds()); -} - -TimeSpan DateTime::operator-(const DateTime& right) { - return TimeSpan(unixtime()-right.unixtime()); -} - -//////////////////////////////////////////////////////////////////////////////// -// TimeSpan implementation - -TimeSpan::TimeSpan (int32_t seconds): - _seconds(seconds) -{} - -TimeSpan::TimeSpan (int16_t days, int8_t hours, int8_t minutes, int8_t seconds): - _seconds((int32_t)days*86400L + (int32_t)hours*3600 + (int32_t)minutes*60 + seconds) -{} - -TimeSpan::TimeSpan (const TimeSpan& copy): - _seconds(copy._seconds) -{} - -TimeSpan TimeSpan::operator+(const TimeSpan& right) { - return TimeSpan(_seconds+right._seconds); -} - -TimeSpan TimeSpan::operator-(const TimeSpan& right) { - return TimeSpan(_seconds-right._seconds); -} - -//////////////////////////////////////////////////////////////////////////////// -// RTC_DS1307 implementation - -static uint8_t bcd2bin (uint8_t val) { return val - 6 * (val >> 4); } -static uint8_t bin2bcd (uint8_t val) { return val + 6 * (val / 10); } - -boolean RTC_DS1307::begin(void) { - Wire.begin(); - return true; -} - -uint8_t RTC_DS1307::isrunning(void) { - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE((byte)0); - Wire.endTransmission(); - - Wire.requestFrom(DS1307_ADDRESS, 1); - uint8_t ss = Wire._I2C_READ(); - return !(ss>>7); -} - -void RTC_DS1307::adjust(const DateTime& dt) { - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE((byte)0); // start at location 0 - Wire._I2C_WRITE(bin2bcd(dt.second())); - Wire._I2C_WRITE(bin2bcd(dt.minute())); - Wire._I2C_WRITE(bin2bcd(dt.hour())); - Wire._I2C_WRITE(bin2bcd(0)); - Wire._I2C_WRITE(bin2bcd(dt.day())); - Wire._I2C_WRITE(bin2bcd(dt.month())); - Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); - Wire.endTransmission(); -} - -DateTime RTC_DS1307::now() { - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE((byte)0); - Wire.endTransmission(); - - Wire.requestFrom(DS1307_ADDRESS, 7); - uint8_t ss = bcd2bin(Wire._I2C_READ() & 0x7F); - uint8_t mm = bcd2bin(Wire._I2C_READ()); - uint8_t hh = bcd2bin(Wire._I2C_READ()); - Wire._I2C_READ(); - uint8_t d = bcd2bin(Wire._I2C_READ()); - uint8_t m = bcd2bin(Wire._I2C_READ()); - uint16_t y = bcd2bin(Wire._I2C_READ()) + 2000; - - return DateTime (y, m, d, hh, mm, ss); -} - -Ds1307SqwPinMode RTC_DS1307::readSqwPinMode() { - int mode; - - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE(DS1307_CONTROL); - Wire.endTransmission(); - - Wire.requestFrom((uint8_t)DS1307_ADDRESS, (uint8_t)1); - mode = Wire._I2C_READ(); - - mode &= 0x93; - return static_cast(mode); -} - -void RTC_DS1307::writeSqwPinMode(Ds1307SqwPinMode mode) { - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE(DS1307_CONTROL); - Wire._I2C_WRITE(mode); - Wire.endTransmission(); -} - -void RTC_DS1307::readnvram(uint8_t* buf, uint8_t size, uint8_t address) { - int addrByte = DS1307_NVRAM + address; - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE(addrByte); - Wire.endTransmission(); - - Wire.requestFrom((uint8_t) DS1307_ADDRESS, size); - for (uint8_t pos = 0; pos < size; ++pos) { - buf[pos] = Wire._I2C_READ(); - } -} - -void RTC_DS1307::writenvram(uint8_t address, uint8_t* buf, uint8_t size) { - int addrByte = DS1307_NVRAM + address; - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE(addrByte); - for (uint8_t pos = 0; pos < size; ++pos) { - Wire._I2C_WRITE(buf[pos]); - } - Wire.endTransmission(); -} - -uint8_t RTC_DS1307::readnvram(uint8_t address) { - uint8_t data; - readnvram(&data, 1, address); - return data; -} - -void RTC_DS1307::writenvram(uint8_t address, uint8_t data) { - writenvram(address, &data, 1); -} - -//////////////////////////////////////////////////////////////////////////////// -// RTC_Millis implementation - -long RTC_Millis::offset = 0; - -void RTC_Millis::adjust(const DateTime& dt) { - offset = dt.unixtime() - millis() / 1000; -} - -DateTime RTC_Millis::now() { - return (uint32_t)(offset + millis() / 1000); -} - -//////////////////////////////////////////////////////////////////////////////// - -//////////////////////////////////////////////////////////////////////////////// -// RTC_PCF8563 implementation - -boolean RTC_PCF8523::begin(void) { - Wire.begin(); - return true; -} - -boolean RTC_PCF8523::initialized(void) { - Wire.beginTransmission(PCF8523_ADDRESS); - Wire._I2C_WRITE((byte)PCF8523_CONTROL_3); - Wire.endTransmission(); - - Wire.requestFrom(PCF8523_ADDRESS, 1); - uint8_t ss = Wire._I2C_READ(); - return ((ss & 0xE0) != 0xE0); -} - -void RTC_PCF8523::adjust(const DateTime& dt) { - Wire.beginTransmission(PCF8523_ADDRESS); - Wire._I2C_WRITE((byte)3); // start at location 3 - Wire._I2C_WRITE(bin2bcd(dt.second())); - Wire._I2C_WRITE(bin2bcd(dt.minute())); - Wire._I2C_WRITE(bin2bcd(dt.hour())); - Wire._I2C_WRITE(bin2bcd(dt.day())); - Wire._I2C_WRITE(bin2bcd(0)); // skip weekdays - Wire._I2C_WRITE(bin2bcd(dt.month())); - Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); - Wire.endTransmission(); - - // set to battery switchover mode - Wire.beginTransmission(PCF8523_ADDRESS); - Wire._I2C_WRITE((byte)PCF8523_CONTROL_3); - Wire._I2C_WRITE((byte)0x00); - Wire.endTransmission(); -} - -DateTime RTC_PCF8523::now() { - Wire.beginTransmission(PCF8523_ADDRESS); - Wire._I2C_WRITE((byte)3); - Wire.endTransmission(); - - Wire.requestFrom(PCF8523_ADDRESS, 7); - uint8_t ss = bcd2bin(Wire._I2C_READ() & 0x7F); - uint8_t mm = bcd2bin(Wire._I2C_READ()); - uint8_t hh = bcd2bin(Wire._I2C_READ()); - uint8_t d = bcd2bin(Wire._I2C_READ()); - Wire._I2C_READ(); // skip 'weekdays' - uint8_t m = bcd2bin(Wire._I2C_READ()); - uint16_t y = bcd2bin(Wire._I2C_READ()) + 2000; - - return DateTime (y, m, d, hh, mm, ss); -} - -Pcf8523SqwPinMode RTC_PCF8523::readSqwPinMode() { - int mode; - - Wire.beginTransmission(PCF8523_ADDRESS); - Wire._I2C_WRITE(PCF8523_CLKOUTCONTROL); - Wire.endTransmission(); - - Wire.requestFrom((uint8_t)PCF8523_ADDRESS, (uint8_t)1); - mode = Wire._I2C_READ(); - - mode >>= 3; - mode &= 0x7; - return static_cast(mode); -} - -void RTC_PCF8523::writeSqwPinMode(Pcf8523SqwPinMode mode) { - Wire.beginTransmission(PCF8523_ADDRESS); - Wire._I2C_WRITE(PCF8523_CLKOUTCONTROL); - Wire._I2C_WRITE(mode << 3); - Wire.endTransmission(); -} - - - - -//////////////////////////////////////////////////////////////////////////////// -// RTC_DS3231 implementation - -boolean RTC_DS3231::begin(void) { - Wire.begin(); - return true; -} - -bool RTC_DS3231::lostPower(void) { - return (read_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG) >> 7); -} - -void RTC_DS3231::adjust(const DateTime& dt) { - Wire.beginTransmission(DS3231_ADDRESS); - Wire._I2C_WRITE((byte)0); // start at location 0 - Wire._I2C_WRITE(bin2bcd(dt.second())); - Wire._I2C_WRITE(bin2bcd(dt.minute())); - Wire._I2C_WRITE(bin2bcd(dt.hour())); - Wire._I2C_WRITE(bin2bcd(0)); - Wire._I2C_WRITE(bin2bcd(dt.day())); - Wire._I2C_WRITE(bin2bcd(dt.month())); - Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); - Wire.endTransmission(); - - uint8_t statreg = read_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG); - statreg &= ~0x80; // flip OSF bit - write_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG, statreg); -} - -DateTime RTC_DS3231::now() { - Wire.beginTransmission(DS3231_ADDRESS); - Wire._I2C_WRITE((byte)0); - Wire.endTransmission(); - - Wire.requestFrom(DS3231_ADDRESS, 7); - uint8_t ss = bcd2bin(Wire._I2C_READ() & 0x7F); - uint8_t mm = bcd2bin(Wire._I2C_READ()); - uint8_t hh = bcd2bin(Wire._I2C_READ()); - Wire._I2C_READ(); - uint8_t d = bcd2bin(Wire._I2C_READ()); - uint8_t m = bcd2bin(Wire._I2C_READ()); - uint16_t y = bcd2bin(Wire._I2C_READ()) + 2000; - - return DateTime (y, m, d, hh, mm, ss); -} - -Ds3231SqwPinMode RTC_DS3231::readSqwPinMode() { - int mode; - - Wire.beginTransmission(DS3231_ADDRESS); - Wire._I2C_WRITE(DS3231_CONTROL); - Wire.endTransmission(); - - Wire.requestFrom((uint8_t)DS3231_ADDRESS, (uint8_t)1); - mode = Wire._I2C_READ(); - - mode &= 0x93; - return static_cast(mode); -} - -void RTC_DS3231::writeSqwPinMode(Ds3231SqwPinMode mode) { - uint8_t ctrl; - ctrl = read_i2c_register(DS3231_ADDRESS, DS3231_CONTROL); - - ctrl &= ~0x04; // turn off INTCON - ctrl &= ~0x18; // set freq bits to 0 - - if (mode == DS3231_OFF) { - ctrl |= 0x04; // turn on INTCN - } else { - ctrl |= mode; - } - write_i2c_register(DS3231_ADDRESS, DS3231_CONTROL, ctrl); - - //Serial.println( read_i2c_register(DS3231_ADDRESS, DS3231_CONTROL), HEX); -} diff --git a/feather_sensor_lte/libraries/RTClib/RTClib.h b/feather_sensor_lte/libraries/RTClib/RTClib.h deleted file mode 100644 index abf5d9b..0000000 --- a/feather_sensor_lte/libraries/RTClib/RTClib.h +++ /dev/null @@ -1,135 +0,0 @@ -// Code by JeeLabs http://news.jeelabs.org/code/ -// Released to the public domain! Enjoy! - -#ifndef _RTCLIB_H_ -#define _RTCLIB_H_ - -#include -class TimeSpan; - - -#define PCF8523_ADDRESS 0x68 -#define PCF8523_CLKOUTCONTROL 0x0F -#define PCF8523_CONTROL_3 0x02 - -#define DS1307_ADDRESS 0x68 -#define DS1307_CONTROL 0x07 -#define DS1307_NVRAM 0x08 - -#define DS3231_ADDRESS 0x68 -#define DS3231_CONTROL 0x0E -#define DS3231_STATUSREG 0x0F - -#define SECONDS_PER_DAY 86400L - -#define SECONDS_FROM_1970_TO_2000 946684800 - - - -// Simple general-purpose date/time class (no TZ / DST / leap second handling!) -class DateTime { -public: - DateTime (uint32_t t =0); - DateTime (uint16_t year, uint8_t month, uint8_t day, - uint8_t hour =0, uint8_t min =0, uint8_t sec =0); - DateTime (const DateTime& copy); - DateTime (const char* date, const char* time); - DateTime (const __FlashStringHelper* date, const __FlashStringHelper* time); - uint16_t year() const { return 2000 + yOff; } - uint8_t month() const { return m; } - uint8_t day() const { return d; } - uint8_t hour() const { return hh; } - uint8_t minute() const { return mm; } - uint8_t second() const { return ss; } - uint8_t dayOfTheWeek() const; - - // 32-bit times as seconds since 1/1/2000 - long secondstime() const; - // 32-bit times as seconds since 1/1/1970 - uint32_t unixtime(void) const; - - DateTime operator+(const TimeSpan& span); - DateTime operator-(const TimeSpan& span); - TimeSpan operator-(const DateTime& right); - -protected: - uint8_t yOff, m, d, hh, mm, ss; -}; - -// Timespan which can represent changes in time with seconds accuracy. -class TimeSpan { -public: - TimeSpan (int32_t seconds = 0); - TimeSpan (int16_t days, int8_t hours, int8_t minutes, int8_t seconds); - TimeSpan (const TimeSpan& copy); - int16_t days() const { return _seconds / 86400L; } - int8_t hours() const { return _seconds / 3600 % 24; } - int8_t minutes() const { return _seconds / 60 % 60; } - int8_t seconds() const { return _seconds % 60; } - int32_t totalseconds() const { return _seconds; } - - TimeSpan operator+(const TimeSpan& right); - TimeSpan operator-(const TimeSpan& right); - -protected: - int32_t _seconds; -}; - -// RTC based on the DS1307 chip connected via I2C and the Wire library -enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 }; - -class RTC_DS1307 { -public: - boolean begin(void); - static void adjust(const DateTime& dt); - uint8_t isrunning(void); - static DateTime now(); - static Ds1307SqwPinMode readSqwPinMode(); - static void writeSqwPinMode(Ds1307SqwPinMode mode); - uint8_t readnvram(uint8_t address); - void readnvram(uint8_t* buf, uint8_t size, uint8_t address); - void writenvram(uint8_t address, uint8_t data); - void writenvram(uint8_t address, uint8_t* buf, uint8_t size); -}; - -// RTC based on the DS3231 chip connected via I2C and the Wire library -enum Ds3231SqwPinMode { DS3231_OFF = 0x01, DS3231_SquareWave1Hz = 0x00, DS3231_SquareWave1kHz = 0x08, DS3231_SquareWave4kHz = 0x10, DS3231_SquareWave8kHz = 0x18 }; - -class RTC_DS3231 { -public: - boolean begin(void); - static void adjust(const DateTime& dt); - bool lostPower(void); - static DateTime now(); - static Ds3231SqwPinMode readSqwPinMode(); - static void writeSqwPinMode(Ds3231SqwPinMode mode); -}; - - -// RTC based on the PCF8523 chip connected via I2C and the Wire library -enum Pcf8523SqwPinMode { PCF8523_OFF = 7, PCF8523_SquareWave1HZ = 6, PCF8523_SquareWave32HZ = 5, PCF8523_SquareWave1kHz = 4, PCF8523_SquareWave4kHz = 3, PCF8523_SquareWave8kHz = 2, PCF8523_SquareWave16kHz = 1, PCF8523_SquareWave32kHz = 0 }; - -class RTC_PCF8523 { -public: - boolean begin(void); - void adjust(const DateTime& dt); - boolean initialized(void); - static DateTime now(); - - Pcf8523SqwPinMode readSqwPinMode(); - void writeSqwPinMode(Pcf8523SqwPinMode mode); -}; - -// RTC using the internal millis() clock, has to be initialized before use -// NOTE: this clock won't be correct once the millis() timer rolls over (>49d?) -class RTC_Millis { -public: - static void begin(const DateTime& dt) { adjust(dt); } - static void adjust(const DateTime& dt); - static DateTime now(); - -protected: - static long offset; -}; - -#endif // _RTCLIB_H_ diff --git a/feather_sensor_lte/libraries/RTClib/examples/datecalc/datecalc.ino b/feather_sensor_lte/libraries/RTClib/examples/datecalc/datecalc.ino deleted file mode 100644 index 771dacd..0000000 --- a/feather_sensor_lte/libraries/RTClib/examples/datecalc/datecalc.ino +++ /dev/null @@ -1,111 +0,0 @@ -// Simple date conversions and calculations - -#include -#include "RTClib.h" - -#if defined(ARDUINO_ARCH_SAMD) -// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! - #define Serial SerialUSB -#endif - -void showDate(const char* txt, const DateTime& dt) { - Serial.print(txt); - Serial.print(' '); - Serial.print(dt.year(), DEC); - Serial.print('/'); - Serial.print(dt.month(), DEC); - Serial.print('/'); - Serial.print(dt.day(), DEC); - Serial.print(' '); - Serial.print(dt.hour(), DEC); - Serial.print(':'); - Serial.print(dt.minute(), DEC); - Serial.print(':'); - Serial.print(dt.second(), DEC); - - Serial.print(" = "); - Serial.print(dt.unixtime()); - Serial.print("s / "); - Serial.print(dt.unixtime() / 86400L); - Serial.print("d since 1970"); - - Serial.println(); -} - -void showTimeSpan(const char* txt, const TimeSpan& ts) { - Serial.print(txt); - Serial.print(" "); - Serial.print(ts.days(), DEC); - Serial.print(" days "); - Serial.print(ts.hours(), DEC); - Serial.print(" hours "); - Serial.print(ts.minutes(), DEC); - Serial.print(" minutes "); - Serial.print(ts.seconds(), DEC); - Serial.print(" seconds ("); - Serial.print(ts.totalseconds(), DEC); - Serial.print(" total seconds)"); - Serial.println(); -} - -void setup () { - -#ifndef ESP8266 - while (!Serial); // for Leonardo/Micro/Zero -#endif - Serial.begin(57600); - - DateTime dt0 (0, 1, 1, 0, 0, 0); - showDate("dt0", dt0); - - DateTime dt1 (1, 1, 1, 0, 0, 0); - showDate("dt1", dt1); - - DateTime dt2 (2009, 1, 1, 0, 0, 0); - showDate("dt2", dt2); - - DateTime dt3 (2009, 1, 2, 0, 0, 0); - showDate("dt3", dt3); - - DateTime dt4 (2009, 1, 27, 0, 0, 0); - showDate("dt4", dt4); - - DateTime dt5 (2009, 2, 27, 0, 0, 0); - showDate("dt5", dt5); - - DateTime dt6 (2009, 12, 27, 0, 0, 0); - showDate("dt6", dt6); - - DateTime dt7 (dt6.unixtime() + 3600); // One hour later. - showDate("dt7", dt7); - - DateTime dt75 = dt6 + TimeSpan(0, 1, 0, 0); // One hour later with TimeSpan addition. - showDate("dt7.5", dt75); - - DateTime dt8 (dt6.unixtime() + 86400L); // One day later. - showDate("dt8", dt8); - - DateTime dt85 = dt6 + TimeSpan(1, 0, 0, 0); // One day later with TimeSpan addition. - showDate("dt8.5", dt85); - - DateTime dt9 (dt6.unixtime() + 7 * 86400L); // One week later. - showDate("dt9", dt9); - - DateTime dt95 = dt6 + TimeSpan(7, 0, 0, 0); // One week later with TimeSpan addition. - showDate("dt9.5", dt95); - - DateTime dt10 = dt6 + TimeSpan(0, 0, 42, 42); // Fourty two minutes and fourty two seconds later. - showDate("dt10", dt10); - - DateTime dt11 = dt6 - TimeSpan(7, 0, 0, 0); // One week ago. - showDate("dt11", dt11); - - TimeSpan ts1 = dt6 - dt5; - showTimeSpan("dt6-dt5", ts1); - - TimeSpan ts2 = dt10 - dt6; - showTimeSpan("dt10-dt6", ts2); -} - -void loop () { -} diff --git a/feather_sensor_lte/libraries/RTClib/examples/ds1307/ds1307.ino b/feather_sensor_lte/libraries/RTClib/examples/ds1307/ds1307.ino deleted file mode 100644 index 7d9162f..0000000 --- a/feather_sensor_lte/libraries/RTClib/examples/ds1307/ds1307.ino +++ /dev/null @@ -1,71 +0,0 @@ -// Date and time functions using a DS1307 RTC connected via I2C and Wire lib -#include -#include "RTClib.h" - -RTC_DS1307 rtc; - -char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; - -void setup () { - while (!Serial); // for Leonardo/Micro/Zero - - Serial.begin(57600); - if (! rtc.begin()) { - Serial.println("Couldn't find RTC"); - while (1); - } - - if (! rtc.isrunning()) { - Serial.println("RTC is NOT running!"); - // following line sets the RTC to the date & time this sketch was compiled - // rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); - // This line sets the RTC with an explicit date & time, for example to set - // January 21, 2014 at 3am you would call: - // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); - } -} - -void loop () { - DateTime now = rtc.now(); - - Serial.print(now.year(), DEC); - Serial.print('/'); - Serial.print(now.month(), DEC); - Serial.print('/'); - Serial.print(now.day(), DEC); - Serial.print(" ("); - Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); - Serial.print(") "); - Serial.print(now.hour(), DEC); - Serial.print(':'); - Serial.print(now.minute(), DEC); - Serial.print(':'); - Serial.print(now.second(), DEC); - Serial.println(); - - Serial.print(" since midnight 1/1/1970 = "); - Serial.print(now.unixtime()); - Serial.print("s = "); - Serial.print(now.unixtime() / 86400L); - Serial.println("d"); - - // calculate a date which is 7 days and 30 seconds into the future - DateTime future (now + TimeSpan(7,12,30,6)); - - Serial.print(" now + 7d + 30s: "); - Serial.print(future.year(), DEC); - Serial.print('/'); - Serial.print(future.month(), DEC); - Serial.print('/'); - Serial.print(future.day(), DEC); - Serial.print(' '); - Serial.print(future.hour(), DEC); - Serial.print(':'); - Serial.print(future.minute(), DEC); - Serial.print(':'); - Serial.print(future.second(), DEC); - Serial.println(); - - Serial.println(); - delay(3000); -} \ No newline at end of file diff --git a/feather_sensor_lte/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino b/feather_sensor_lte/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino deleted file mode 100644 index c12c26c..0000000 --- a/feather_sensor_lte/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino +++ /dev/null @@ -1,68 +0,0 @@ -// SQW/OUT pin mode using a DS1307 RTC connected via I2C. -// -// According to the data sheet (http://datasheets.maxim-ic.com/en/ds/DS1307.pdf), the -// DS1307's SQW/OUT pin can be set to low, high, 1Hz, 4.096kHz, 8.192kHz, or 32.768kHz. -// -// This sketch reads the state of the pin, then iterates through the possible values at -// 5 second intervals. -// - -// NOTE: -// You must connect a pull up resistor (~10kohm) from the SQW pin up to VCC. Without -// this pull up the wave output will not work! - -#include -#include "RTClib.h" - -#if defined(ARDUINO_ARCH_SAMD) -// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! - #define Serial SerialUSB -#endif - -RTC_DS1307 rtc; - -int mode_index = 0; - -Ds1307SqwPinMode modes[] = {OFF, ON, SquareWave1HZ, SquareWave4kHz, SquareWave8kHz, SquareWave32kHz}; - - -void print_mode() { - Ds1307SqwPinMode mode = rtc.readSqwPinMode(); - - Serial.print("Sqw Pin Mode: "); - switch(mode) { - case OFF: Serial.println("OFF"); break; - case ON: Serial.println("ON"); break; - case SquareWave1HZ: Serial.println("1Hz"); break; - case SquareWave4kHz: Serial.println("4.096kHz"); break; - case SquareWave8kHz: Serial.println("8.192kHz"); break; - case SquareWave32kHz: Serial.println("32.768kHz"); break; - default: Serial.println("UNKNOWN"); break; - } -} - -void setup () { - -#ifndef ESP8266 - while (!Serial); // for Leonardo/Micro/Zero -#endif - - Serial.begin(57600); - if (! rtc.begin()) { - Serial.println("Couldn't find RTC"); - while (1); - } - - print_mode(); -} - -void loop () { - rtc.writeSqwPinMode(modes[mode_index++]); - print_mode(); - - if (mode_index > 5) { - mode_index = 0; - } - - delay(5000); -} diff --git a/feather_sensor_lte/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino b/feather_sensor_lte/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino deleted file mode 100644 index 0acd0cf..0000000 --- a/feather_sensor_lte/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino +++ /dev/null @@ -1,63 +0,0 @@ -// Example of using the non-volatile RAM storage on the DS1307. -// You can write up to 56 bytes from address 0 to 55. -// Data will be persisted as long as the DS1307 has battery power. - -#include -#include "RTClib.h" - -#if defined(ARDUINO_ARCH_SAMD) -// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! - #define Serial SerialUSB -#endif - -RTC_DS1307 rtc; - -void printnvram(uint8_t address) { - Serial.print("Address 0x"); - Serial.print(address, HEX); - Serial.print(" = 0x"); - Serial.println(rtc.readnvram(address), HEX); -} - -void setup () { - -#ifndef ESP8266 - while (!Serial); // for Leonardo/Micro/Zero -#endif - Serial.begin(57600); - rtc.begin(); - - // Print old RAM contents on startup. - Serial.println("Current NVRAM values:"); - for (int i = 0; i < 6; ++i) { - printnvram(i); - } - - // Write some bytes to non-volatile RAM storage. - // NOTE: You can only read and write from addresses 0 to 55 (i.e. 56 byte values). - Serial.println("Writing NVRAM values."); - // Example writing one byte at a time: - rtc.writenvram(0, 0xFE); - rtc.writenvram(1, 0xED); - // Example writing multiple bytes: - uint8_t writeData[4] = { 0xBE, 0xEF, 0x01, 0x02 }; - rtc.writenvram(2, writeData, 4); - - // Read bytes from non-volatile RAM storage. - Serial.println("Reading NVRAM values:"); - // Example reading one byte at a time. - Serial.println(rtc.readnvram(0), HEX); - Serial.println(rtc.readnvram(1), HEX); - // Example reading multiple bytes: - uint8_t readData[4] = {0}; - rtc.readnvram(readData, 4, 2); - Serial.println(readData[0], HEX); - Serial.println(readData[1], HEX); - Serial.println(readData[2], HEX); - Serial.println(readData[3], HEX); - -} - -void loop () { - // Do nothing in the loop. -} diff --git a/feather_sensor_lte/libraries/RTClib/examples/ds3231/ds3231.ino b/feather_sensor_lte/libraries/RTClib/examples/ds3231/ds3231.ino deleted file mode 100644 index b62d510..0000000 --- a/feather_sensor_lte/libraries/RTClib/examples/ds3231/ds3231.ino +++ /dev/null @@ -1,77 +0,0 @@ -// Date and time functions using a DS3231 RTC connected via I2C and Wire lib -#include -#include "RTClib.h" - -RTC_DS3231 rtc; - -char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; - -void setup () { - -#ifndef ESP8266 - while (!Serial); // for Leonardo/Micro/Zero -#endif - - Serial.begin(9600); - - delay(3000); // wait for console opening - - if (! rtc.begin()) { - Serial.println("Couldn't find RTC"); - while (1); - } - - if (rtc.lostPower()) { - Serial.println("RTC lost power, lets set the time!"); - // following line sets the RTC to the date & time this sketch was compiled - rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); - // This line sets the RTC with an explicit date & time, for example to set - // January 21, 2014 at 3am you would call: - // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); - } -} - -void loop () { - DateTime now = rtc.now(); - - Serial.print(now.year(), DEC); - Serial.print('/'); - Serial.print(now.month(), DEC); - Serial.print('/'); - Serial.print(now.day(), DEC); - Serial.print(" ("); - Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); - Serial.print(") "); - Serial.print(now.hour(), DEC); - Serial.print(':'); - Serial.print(now.minute(), DEC); - Serial.print(':'); - Serial.print(now.second(), DEC); - Serial.println(); - - Serial.print(" since midnight 1/1/1970 = "); - Serial.print(now.unixtime()); - Serial.print("s = "); - Serial.print(now.unixtime() / 86400L); - Serial.println("d"); - - // calculate a date which is 7 days and 30 seconds into the future - DateTime future (now + TimeSpan(7,12,30,6)); - - Serial.print(" now + 7d + 30s: "); - Serial.print(future.year(), DEC); - Serial.print('/'); - Serial.print(future.month(), DEC); - Serial.print('/'); - Serial.print(future.day(), DEC); - Serial.print(' '); - Serial.print(future.hour(), DEC); - Serial.print(':'); - Serial.print(future.minute(), DEC); - Serial.print(':'); - Serial.print(future.second(), DEC); - Serial.println(); - - Serial.println(); - delay(3000); -} diff --git a/feather_sensor_lte/libraries/RTClib/examples/pcf8523/pcf8523.ino b/feather_sensor_lte/libraries/RTClib/examples/pcf8523/pcf8523.ino deleted file mode 100644 index fc7dfe8..0000000 --- a/feather_sensor_lte/libraries/RTClib/examples/pcf8523/pcf8523.ino +++ /dev/null @@ -1,74 +0,0 @@ -// Date and time functions using a DS1307 RTC connected via I2C and Wire lib -#include -#include "RTClib.h" - -RTC_PCF8523 rtc; - -char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; - -void setup () { - - while (!Serial) { - delay(1); // for Leonardo/Micro/Zero - } - - Serial.begin(57600); - if (! rtc.begin()) { - Serial.println("Couldn't find RTC"); - while (1); - } - - if (! rtc.initialized()) { - Serial.println("RTC is NOT running!"); - // following line sets the RTC to the date & time this sketch was compiled - // rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); - // This line sets the RTC with an explicit date & time, for example to set - // January 21, 2014 at 3am you would call: - // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); - } -} - -void loop () { - DateTime now = rtc.now(); - - Serial.print(now.year(), DEC); - Serial.print('/'); - Serial.print(now.month(), DEC); - Serial.print('/'); - Serial.print(now.day(), DEC); - Serial.print(" ("); - Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); - Serial.print(") "); - Serial.print(now.hour(), DEC); - Serial.print(':'); - Serial.print(now.minute(), DEC); - Serial.print(':'); - Serial.print(now.second(), DEC); - Serial.println(); - - Serial.print(" since midnight 1/1/1970 = "); - Serial.print(now.unixtime()); - Serial.print("s = "); - Serial.print(now.unixtime() / 86400L); - Serial.println("d"); - - // calculate a date which is 7 days and 30 seconds into the future - DateTime future (now + TimeSpan(7,12,30,6)); - - Serial.print(" now + 7d + 30s: "); - Serial.print(future.year(), DEC); - Serial.print('/'); - Serial.print(future.month(), DEC); - Serial.print('/'); - Serial.print(future.day(), DEC); - Serial.print(' '); - Serial.print(future.hour(), DEC); - Serial.print(':'); - Serial.print(future.minute(), DEC); - Serial.print(':'); - Serial.print(future.second(), DEC); - Serial.println(); - - Serial.println(); - delay(3000); -} \ No newline at end of file diff --git a/feather_sensor_lte/libraries/RTClib/examples/softrtc/softrtc.ino b/feather_sensor_lte/libraries/RTClib/examples/softrtc/softrtc.ino deleted file mode 100644 index 80f1886..0000000 --- a/feather_sensor_lte/libraries/RTClib/examples/softrtc/softrtc.ino +++ /dev/null @@ -1,61 +0,0 @@ -// Date and time functions using just software, based on millis() & timer - -#include -#include // this #include still required because the RTClib depends on it -#include "RTClib.h" - -#if defined(ARDUINO_ARCH_SAMD) -// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! - #define Serial SerialUSB -#endif - -RTC_Millis rtc; - -void setup () { - Serial.begin(57600); - // following line sets the RTC to the date & time this sketch was compiled - rtc.begin(DateTime(F(__DATE__), F(__TIME__))); - // This line sets the RTC with an explicit date & time, for example to set - // January 21, 2014 at 3am you would call: - // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); -} - -void loop () { - DateTime now = rtc.now(); - - Serial.print(now.year(), DEC); - Serial.print('/'); - Serial.print(now.month(), DEC); - Serial.print('/'); - Serial.print(now.day(), DEC); - Serial.print(' '); - Serial.print(now.hour(), DEC); - Serial.print(':'); - Serial.print(now.minute(), DEC); - Serial.print(':'); - Serial.print(now.second(), DEC); - Serial.println(); - - Serial.print(" seconds since 1970: "); - Serial.println(now.unixtime()); - - // calculate a date which is 7 days and 30 seconds into the future - DateTime future (now.unixtime() + 7 * 86400L + 30); - - Serial.print(" now + 7d + 30s: "); - Serial.print(future.year(), DEC); - Serial.print('/'); - Serial.print(future.month(), DEC); - Serial.print('/'); - Serial.print(future.day(), DEC); - Serial.print(' '); - Serial.print(future.hour(), DEC); - Serial.print(':'); - Serial.print(future.minute(), DEC); - Serial.print(':'); - Serial.print(future.second(), DEC); - Serial.println(); - - Serial.println(); - delay(3000); -} diff --git a/feather_sensor_lte/libraries/RTClib/keywords.txt b/feather_sensor_lte/libraries/RTClib/keywords.txt deleted file mode 100644 index 26cdc1e..0000000 --- a/feather_sensor_lte/libraries/RTClib/keywords.txt +++ /dev/null @@ -1,37 +0,0 @@ -####################################### -# Syntax Coloring Map For RTC -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -DateTime KEYWORD1 -RTC_DS1307 KEYWORD1 -RTC_Millis KEYWORD1 -Ds1307SqwPinMode KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -year KEYWORD2 -month KEYWORD2 -day KEYWORD2 -hour KEYWORD2 -minute KEYWORD2 -second KEYWORD2 -dayOfWeek KEYWORD2 -secondstime KEYWORD2 -unixtime KEYWORD2 -begin KEYWORD2 -adjust KEYWORD2 -isrunning KEYWORD2 -now KEYWORD2 -readSqwPinMode KEYWORD2 -writeSqwPinMode KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### - diff --git a/feather_sensor_lte/libraries/RTClib/library.properties b/feather_sensor_lte/libraries/RTClib/library.properties deleted file mode 100644 index 13d6177..0000000 --- a/feather_sensor_lte/libraries/RTClib/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=RTClib -version=1.2.1 -author=Adafruit -maintainer=Adafruit -sentence=A fork of Jeelab's fantastic RTC library -paragraph=A fork of Jeelab's fantastic RTC library -category=Timing -url=https://github.com/adafruit/RTClib -architectures=* diff --git a/feather_sensor_lte/libraries/WiFi101/.travis.yml b/feather_sensor_lte/libraries/WiFi101/.travis.yml deleted file mode 100644 index 465c761..0000000 --- a/feather_sensor_lte/libraries/WiFi101/.travis.yml +++ /dev/null @@ -1,48 +0,0 @@ -language: generic -env: - global: - - IDE_VERSION=1.8.2 - matrix: - - BOARD="arduino:avr:uno" - - BOARD="arduino:avr:mega:cpu=atmega2560" - - BOARD="arduino:sam:arduino_due_x_dbg" - - BOARD="arduino:samd:arduino_zero_edbg" - - BOARD="arduino:samd:mkr1000" - - BOARD="Intel:arc32:arduino_101" -before_install: - - wget http://downloads.arduino.cc/arduino-$IDE_VERSION-linux64.tar.xz - - tar xf arduino-$IDE_VERSION-linux64.tar.xz - - mv arduino-$IDE_VERSION $HOME/arduino-ide - - export PATH=$PATH:$HOME/arduino-ide - - if [[ "$BOARD" =~ "arduino:sam:" ]]; then - arduino --install-boards arduino:sam; - fi - - if [[ "$BOARD" =~ "arduino:samd:" ]]; then - arduino --install-boards arduino:samd; - fi - - if [[ "$BOARD" =~ "Intel:arc32" ]]; then - arduino --install-boards Intel:arc32; - fi - - buildExampleSketch() { arduino --verbose-build --verify --board $BOARD $PWD/examples/$1/$1.ino; } -install: - - mkdir -p $HOME/Arduino/libraries - - ln -s $PWD $HOME/Arduino/libraries/. -script: - - buildExampleSketch AP_SimpleWebServer - - buildExampleSketch CheckWifi101FirmwareVersion - - buildExampleSketch ConnectNoEncryption - - buildExampleSketch ConnectWithWEP - - buildExampleSketch ConnectWithWPA - - buildExampleSketch FirmwareUpdater - - buildExampleSketch MDNS_WiFiWebServer - - buildExampleSketch ScanNetworks - - buildExampleSketch SimpleWebServerWiFi - - buildExampleSketch WiFiChatServer - - buildExampleSketch WiFiPing - - buildExampleSketch WiFiSSLClient - - buildExampleSketch WiFiUdpNtpClient - - buildExampleSketch WiFiUdpSendReceiveString - - buildExampleSketch WiFiWebClient - - buildExampleSketch WiFiWebClientRepeating - - buildExampleSketch WiFiWebServer - diff --git a/feather_sensor_lte/libraries/WiFi101/CHANGELOG b/feather_sensor_lte/libraries/WiFi101/CHANGELOG deleted file mode 100644 index fbe1643..0000000 --- a/feather_sensor_lte/libraries/WiFi101/CHANGELOG +++ /dev/null @@ -1,122 +0,0 @@ -WiFi101 ?.?.? - ????.??.?? - -WiFi101 0.14.3 - 2017.06.01 - -* Fixed issues with WiFiMDNSResponder and large request packets -* Fixed issues with WiFiClient and sending data after the socket is closed - -WiFi101 0.14.2 - 2017.05.08 - -* Fixed issues with WiFiServer::write not working - -WiFi101 0.14.1 - 2017.04.20 - -* Fixed issues with WiFiMDNSResponder and Windows using Bonjour -* Correct cast of buffer size when processing received data - -WiFi101 0.14.0 - 2017.03.22 - -* Added support for firmware 19.5.2 -* Add ability to create Access Point with WPA security (f/w 19.5.2 or higher) -* Add WiFi.hostname(name) method to set custom host name for DHCP (f/w 19.5.2 or higher) -* Enables support for AES-256 Ciphers (f/w 19.5.2 or higher) -* Make provisioning mode backwards compatible with f/w 19.4.4 and older - -WiFi101 0.13.0 - 2017.03.01 - -* Added WiFi.channel() and WiFi.BSSID() - -WiFi101 0.12.1 - 2017.01.19 - -* Fixed tomorrow day issue in WiFi.getTime() - -WiFi101 0.12.0 - 2017.01.05 - -* Made provisioning mode easier and added example sketch -* Fixed WiFi.getTime() not returning 0, if time has not been synced via NTP -* Fixed crashing when connecting after scanning -* Fixed WiFiServer::available() returning valid client on outbound client connection -* Added WiFiUdp::beginMulticast(port) function for compatiblity with EthernetUdp, as beginMulti was inconsistent - -WiFi101 0.11.2 - 2016.12.15 - -* Fixed value of WiFi.getTime() being off by one day -* Fixed calling WiFi.RSSI() causing lockups - -WiFi101 0.11.1 - 2016.11.29 - -* Fixed regression for non-AVR boards that resulted in corrupt with data over than 1400 bytes was received - -WiFi101 0.11.0 - 2016.11.14 - -* Changed WiFi.ping(...) to return round trip time on success, negative value on error. Thanks @PKGeorgiev -* WiFi.end() now powers down the WiFi module -* WiFi.config(ip) can now be used to set a static IP for WiFi.begin(...) -* Fixed WiFi.BSSID(bssid) returning reversed MAC address -* Added WiFi.APClientMacAddress() API to get MAC address of AP client in AP mode -* Added WiFi.getTime() API to get epoch from NTP - -WiFi101 0.10.0 - 2016.09.08 - -* Added WiFi.end() to disconnect from the AP or end AP mode -* Added new WiFi.ping(...) functionality. Thanks @PKGeorgiev -* Added WiFi.setPins(...) to customize the CS, INTN, RESET and CHIPEN pins -* Add new WL_AP_LISTENING, WL_AP_CONNECTED, and WL_AP_FAILED status types for AP mode -* Fixed return value of WiFiUDP::beginPacket(host, port) when host is successfully resolved -* Added power management methods: WiFi.lowPowerMode(), WiFi.maxLowPowerMode(), WiFi.noLowPowerMode() -* Close TCP sockets when physical link is disconnected -* Fixed WiFi.RSSI() returning 0 when there was pending socket data - -WiFi101 0.9.1 - 2016.04.19 - -* Increased compatibility with 3rd party boards and architectures. -* Rename WiFiMdnsResponder.h/cpp to WiFiMDNSResponder.h/cpp -* Fixed buffering of UDP packet - -WiFi101 0.9.0 - 2016.03.21 - -* Fixed WiFi.status() hanging when shield is not present -* Fixed MAC address returning 00:00:00:00:00:00 with firmware version 19.3.0 -* Fixed SSL write functionality with firmware version 19.3.0 -* Fixed previous version of the library not working on the Uno and other boards that used PCINT's -* Added beginAP(...) API's to create access point with WEP passwords -* Fixed beginAP(...) channel off by one error -* Fixed WiFi.status() always returning WL_CONNECTED once connected, even if access point is disconnected later -* Added beginMulti API for Multicast UDP support -* Added WiFiMDNSResponder class and MDNS Web server example - -WiFi101 0.8.0 - 2016.02.15 - -* Added example for Access Point web server (thanks @ladyada) -* Fixed MAC Address printed in reverse order -* Allow another library to override PCINT ISR (fix issues when using the WiFi101 - library with other libraries like SoftwareSerial) - -WiFi101 0.7.0 - 2015.01.11 - -* Added support for WiFi Firmware 19.4.4 -* WiFi.hostByName(...) will not try resolve the domain name if it's already a numeric IP -* Fixed manual IP configuration (no DHCP) -* Fixed WiFiServer.available(), now follows API specification -* Fixed WEP key connection -* Fixed WiFiClient copy constructor and assignment operator. This improves stability when - Client objects are assigned or returned from functions. -* Control pins are now configurable through defines from variant. - -WiFi101 0.6.0 - 2015.11.27 - -* Fixed bug with AVR boards when Web Server is used -* Fixed UDP read bug on AVR Boards -* Added missing inlcude for SSL Client -* Fixed peek() function -* Fixed some examples - -WiFi101 0.5.1 - 2015.10.06 - -* Improved support for AVR Boards (Uno, Mega, Leonardo, etc.) and - ARM based boards (Due and Zero). - -WiFi101 0.5.0 - 2015.10.01 - -* Initial release - diff --git a/feather_sensor_lte/libraries/WiFi101/README.adoc b/feather_sensor_lte/libraries/WiFi101/README.adoc deleted file mode 100644 index 8eb6924..0000000 --- a/feather_sensor_lte/libraries/WiFi101/README.adoc +++ /dev/null @@ -1,27 +0,0 @@ -= WiFi library for the Arduino WiFi Shield 101 and MKR1000 board = - -image:https://travis-ci.org/arduino-libraries/WiFi101.svg?branch=master["Build Status", link="https://travis-ci.org/arduino-libraries/WiFi101"] - -This library implements a network driver for devices based -on the ATMEL WINC1500 WiFi module. - -For more information about this library please visit us at -https://www.arduino.cc/en/Reference/WiFi101 - -== License == - -Copyright (c) Arduino LLC. All right reserved. - -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 2.1 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 Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA diff --git a/feather_sensor_lte/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino b/feather_sensor_lte/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino deleted file mode 100644 index b5caf7a..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino +++ /dev/null @@ -1,176 +0,0 @@ -/* - WiFi Web Server LED Blink - - A simple web server that lets you blink an LED via the web. - This sketch will create a new access point (with no password). - It will then launch a new server and print out the IP address - to the Serial monitor. From there, you can open that address in a web browser - to turn on and off the LED on pin 13. - - If the IP address of your shield is yourAddress: - http://yourAddress/H turns the LED on - http://yourAddress/L turns it off - - created 25 Nov 2012 - by Tom Igoe - adapted to WiFi AP by Adafruit - */ - -#include -#include -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int led = LED_BUILTIN; -int status = WL_IDLE_STATUS; -WiFiServer server(80); - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - Serial.println("Access Point Web Server"); - - pinMode(led, OUTPUT); // set the LED pin mode - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue - while (true); - } - - // by default the local IP address of will be 192.168.1.1 - // you can override it with the following: - // WiFi.config(IPAddress(10, 0, 0, 1)); - - // print the network name (SSID); - Serial.print("Creating access point named: "); - Serial.println(ssid); - - // Create open network. Change this line if you want to create an WEP network: - status = WiFi.beginAP(ssid); - if (status != WL_AP_LISTENING) { - Serial.println("Creating access point failed"); - // don't continue - while (true); - } - - // wait 10 seconds for connection: - delay(10000); - - // start the web server on port 80 - server.begin(); - - // you're connected now, so print out the status - printWiFiStatus(); -} - - -void loop() { - // compare the previous status to the current status - if (status != WiFi.status()) { - // it has changed update the variable - status = WiFi.status(); - - if (status == WL_AP_CONNECTED) { - byte remoteMac[6]; - - // a device has connected to the AP - Serial.print("Device connected to AP, MAC address: "); - WiFi.APClientMacAddress(remoteMac); - Serial.print(remoteMac[5], HEX); - Serial.print(":"); - Serial.print(remoteMac[4], HEX); - Serial.print(":"); - Serial.print(remoteMac[3], HEX); - Serial.print(":"); - Serial.print(remoteMac[2], HEX); - Serial.print(":"); - Serial.print(remoteMac[1], HEX); - Serial.print(":"); - Serial.println(remoteMac[0], HEX); - } else { - // a device has disconnected from the AP, and we are back in listening mode - Serial.println("Device disconnected from AP"); - } - } - - WiFiClient client = server.available(); // listen for incoming clients - - if (client) { // if you get a client, - Serial.println("new client"); // print a message out the serial port - String currentLine = ""; // make a String to hold incoming data from the client - while (client.connected()) { // loop while the client's connected - if (client.available()) { // if there's bytes to read from the client, - char c = client.read(); // read a byte, then - Serial.write(c); // print it out the serial monitor - if (c == '\n') { // if the byte is a newline character - - // if the current line is blank, you got two newline characters in a row. - // that's the end of the client HTTP request, so send a response: - if (currentLine.length() == 0) { - // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) - // and a content-type so the client knows what's coming, then a blank line: - client.println("HTTP/1.1 200 OK"); - client.println("Content-type:text/html"); - client.println(); - - // the content of the HTTP response follows the header: - client.print("Click here turn the LED on
"); - client.print("Click here turn the LED off
"); - - // The HTTP response ends with another blank line: - client.println(); - // break out of the while loop: - break; - } - else { // if you got a newline, then clear currentLine: - currentLine = ""; - } - } - else if (c != '\r') { // if you got anything else but a carriage return character, - currentLine += c; // add it to the end of the currentLine - } - - // Check to see if the client request was "GET /H" or "GET /L": - if (currentLine.endsWith("GET /H")) { - digitalWrite(led, HIGH); // GET /H turns the LED on - } - if (currentLine.endsWith("GET /L")) { - digitalWrite(led, LOW); // GET /L turns the LED off - } - } - } - // close the connection: - client.stop(); - Serial.println("client disconnected"); - } -} - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); - // print where to go in a browser: - Serial.print("To see this page in action, open a browser to http://"); - Serial.println(ip); - -} diff --git a/feather_sensor_lte/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino b/feather_sensor_lte/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino deleted file mode 100644 index 8cd312e..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino +++ /dev/null @@ -1,67 +0,0 @@ -/* - * This example check if the firmware loaded on the WiFi101 - * shield is updated. - * - * Circuit: - * - WiFi101 Shield attached - * - * Created 29 July 2015 by Cristian Maglie - * This code is in the public domain. - */ -#include -#include -#include - -void setup() { - // Initialize serial - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // Print a welcome message - Serial.println("WiFi101 firmware check."); - Serial.println(); - - // Check for the presence of the shield - Serial.print("WiFi101 shield: "); - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("NOT PRESENT"); - return; // don't continue - } - Serial.println("DETECTED"); - - // Print firmware version on the shield - String fv = WiFi.firmwareVersion(); - String latestFv; - Serial.print("Firmware version installed: "); - Serial.println(fv); - - if (REV(GET_CHIPID()) >= REV_3A0) { - // model B - latestFv = WIFI_FIRMWARE_LATEST_MODEL_B; - } else { - // model A - latestFv = WIFI_FIRMWARE_LATEST_MODEL_A; - } - - // Print required firmware version - Serial.print("Latest firmware version available : "); - Serial.println(latestFv); - - // Check if the latest version is installed - Serial.println(); - if (fv == latestFv) { - Serial.println("Check result: PASSED"); - } else { - Serial.println("Check result: NOT PASSED"); - Serial.println(" - The firmware version on the shield do not match the"); - Serial.println(" version required by the library, you may experience"); - Serial.println(" issues or failures."); - } -} - -void loop() { - // do nothing -} - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino b/feather_sensor_lte/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino deleted file mode 100644 index f43a232..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino +++ /dev/null @@ -1,123 +0,0 @@ -/* - - This example connects to an unencrypted WiFi network. - Then it prints the MAC address of the WiFi shield, - the IP address obtained, and other network details. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - */ -#include -#include -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -int status = WL_IDLE_STATUS; // the WiFi radio's status - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to open SSID: "); - Serial.println(ssid); - status = WiFi.begin(ssid); - - // wait 10 seconds for connection: - delay(10000); - } - - // you're connected now, so print out the data: - Serial.print("You're connected to the network"); - printCurrentNet(); - printWiFiData(); -} - -void loop() { - // check the network connection once every 10 seconds: - delay(10000); - printCurrentNet(); -} - -void printWiFiData() { - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - Serial.println(ip); - - // print your MAC address: - byte mac[6]; - WiFi.macAddress(mac); - Serial.print("MAC address: "); - Serial.print(mac[5], HEX); - Serial.print(":"); - Serial.print(mac[4], HEX); - Serial.print(":"); - Serial.print(mac[3], HEX); - Serial.print(":"); - Serial.print(mac[2], HEX); - Serial.print(":"); - Serial.print(mac[1], HEX); - Serial.print(":"); - Serial.println(mac[0], HEX); - - // print your subnet mask: - IPAddress subnet = WiFi.subnetMask(); - Serial.print("NetMask: "); - Serial.println(subnet); - - // print your gateway address: - IPAddress gateway = WiFi.gatewayIP(); - Serial.print("Gateway: "); - Serial.println(gateway); -} - -void printCurrentNet() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print the MAC address of the router you're attached to: - byte bssid[6]; - WiFi.BSSID(bssid); - Serial.print("BSSID: "); - Serial.print(bssid[5], HEX); - Serial.print(":"); - Serial.print(bssid[4], HEX); - Serial.print(":"); - Serial.print(bssid[3], HEX); - Serial.print(":"); - Serial.print(bssid[2], HEX); - Serial.print(":"); - Serial.print(bssid[1], HEX); - Serial.print(":"); - Serial.println(bssid[0], HEX); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.println(rssi); - - // print the encryption type: - byte encryption = WiFi.encryptionType(); - Serial.print("Encryption Type:"); - Serial.println(encryption, HEX); -} - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h deleted file mode 100644 index 07c1148..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h +++ /dev/null @@ -1 +0,0 @@ -#define SECRET_SSID "" diff --git a/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino b/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino deleted file mode 100644 index c226fa7..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino +++ /dev/null @@ -1,129 +0,0 @@ -/* - - This example connects to a WEP-encrypted WiFi network. - Then it prints the MAC address of the WiFi shield, - the IP address obtained, and other network details. - - If you use 40-bit WEP, you need a key that is 10 characters long, - and the characters must be hexadecimal (0-9 or A-F). - e.g. for 40-bit, ABBADEAF01 will work, but ABBADEAF won't work - (too short) and ABBAISDEAF won't work (I and S are not - hexadecimal characters). - - For 128-bit, you need a string that is 26 characters long. - D0D0DEADF00DABBADEAFBEADED will work because it's 26 characters, - all in the 0-9, A-F range. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - */ -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char key[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number -int status = WL_IDLE_STATUS; // the WiFi radio's status - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to WEP network, SSID: "); - Serial.println(ssid); - status = WiFi.begin(ssid, keyIndex, key); - - // wait 10 seconds for connection: - delay(10000); - } - - // once you are connected : - Serial.print("You're connected to the network"); - printCurrentNet(); - printWiFiData(); -} - -void loop() { - // check the network connection once every 10 seconds: - delay(10000); - printCurrentNet(); -} - -void printWiFiData() { - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - Serial.println(ip); - - // print your MAC address: - byte mac[6]; - WiFi.macAddress(mac); - Serial.print("MAC address: "); - Serial.print(mac[5], HEX); - Serial.print(":"); - Serial.print(mac[4], HEX); - Serial.print(":"); - Serial.print(mac[3], HEX); - Serial.print(":"); - Serial.print(mac[2], HEX); - Serial.print(":"); - Serial.print(mac[1], HEX); - Serial.print(":"); - Serial.println(mac[0], HEX); -} - -void printCurrentNet() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print the MAC address of the router you're attached to: - byte bssid[6]; - WiFi.BSSID(bssid); - Serial.print("BSSID: "); - Serial.print(bssid[5], HEX); - Serial.print(":"); - Serial.print(bssid[4], HEX); - Serial.print(":"); - Serial.print(bssid[3], HEX); - Serial.print(":"); - Serial.print(bssid[2], HEX); - Serial.print(":"); - Serial.print(bssid[1], HEX); - Serial.print(":"); - Serial.println(bssid[0], HEX); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.println(rssi); - - // print the encryption type: - byte encryption = WiFi.encryptionType(); - Serial.print("Encryption Type:"); - Serial.println(encryption, HEX); - Serial.println(); -} - - - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino b/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino deleted file mode 100644 index b98af65..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino +++ /dev/null @@ -1,119 +0,0 @@ -/* - - This example connects to an unencrypted WiFi network. - Then it prints the MAC address of the WiFi shield, - the IP address obtained, and other network details. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - */ -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int status = WL_IDLE_STATUS; // the WiFi radio's status - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to WPA SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - - // you're connected now, so print out the data: - Serial.print("You're connected to the network"); - printCurrentNet(); - printWiFiData(); - -} - -void loop() { - // check the network connection once every 10 seconds: - delay(10000); - printCurrentNet(); -} - -void printWiFiData() { - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - Serial.println(ip); - - // print your MAC address: - byte mac[6]; - WiFi.macAddress(mac); - Serial.print("MAC address: "); - Serial.print(mac[5], HEX); - Serial.print(":"); - Serial.print(mac[4], HEX); - Serial.print(":"); - Serial.print(mac[3], HEX); - Serial.print(":"); - Serial.print(mac[2], HEX); - Serial.print(":"); - Serial.print(mac[1], HEX); - Serial.print(":"); - Serial.println(mac[0], HEX); - -} - -void printCurrentNet() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print the MAC address of the router you're attached to: - byte bssid[6]; - WiFi.BSSID(bssid); - Serial.print("BSSID: "); - Serial.print(bssid[5], HEX); - Serial.print(":"); - Serial.print(bssid[4], HEX); - Serial.print(":"); - Serial.print(bssid[3], HEX); - Serial.print(":"); - Serial.print(bssid[2], HEX); - Serial.print(":"); - Serial.print(bssid[1], HEX); - Serial.print(":"); - Serial.println(bssid[0], HEX); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.println(rssi); - - // print the encryption type: - byte encryption = WiFi.encryptionType(); - Serial.print("Encryption Type:"); - Serial.println(encryption, HEX); - Serial.println(); -} - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino b/feather_sensor_lte/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino deleted file mode 100644 index 897c770..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino +++ /dev/null @@ -1,62 +0,0 @@ -/* - Endianess.ino - Network byte order conversion functions. - Copyright (c) 2015 Arduino LLC. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - - -bool isBigEndian() { - uint32_t test = 0x11223344; - uint8_t *pTest = reinterpret_cast(&test); - return pTest[0] == 0x11; -} - -uint32_t fromNetwork32(uint32_t from) { - static const bool be = isBigEndian(); - if (be) { - return from; - } else { - uint8_t *pFrom = reinterpret_cast(&from); - uint32_t to; - to = pFrom[0]; to <<= 8; - to |= pFrom[1]; to <<= 8; - to |= pFrom[2]; to <<= 8; - to |= pFrom[3]; - return to; - } -} - -uint16_t fromNetwork16(uint16_t from) { - static bool be = isBigEndian(); - if (be) { - return from; - } else { - uint8_t *pFrom = reinterpret_cast(&from); - uint16_t to; - to = pFrom[0]; to <<= 8; - to |= pFrom[1]; - return to; - } -} - -uint32_t toNetwork32(uint32_t to) { - return fromNetwork32(to); -} - -uint16_t toNetwork16(uint16_t to) { - return fromNetwork16(to); -} - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino b/feather_sensor_lte/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino deleted file mode 100644 index 1bbd6b9..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino +++ /dev/null @@ -1,129 +0,0 @@ -/* - FirmwareUpdate.h - Firmware Updater for WiFi101 / WINC1500. - Copyright (c) 2015 Arduino LLC. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include -#include - -typedef struct __attribute__((__packed__)) { - uint8_t command; - uint32_t address; - uint32_t arg1; - uint16_t payloadLength; - - // payloadLenght bytes of data follows... -} UartPacket; - -static const int MAX_PAYLOAD_SIZE = 1024; - -#define CMD_READ_FLASH 0x01 -#define CMD_WRITE_FLASH 0x02 -#define CMD_ERASE_FLASH 0x03 -#define CMD_MAX_PAYLOAD_SIZE 0x50 -#define CMD_HELLO 0x99 - -void setup() { - Serial.begin(115200); - - nm_bsp_init(); - if (m2m_wifi_download_mode() != M2M_SUCCESS) { - Serial.println(F("Failed to put the WiFi module in download mode")); - while (true) - ; - } -} - -void receivePacket(UartPacket *pkt, uint8_t *payload) { - // Read command - uint8_t *p = reinterpret_cast(pkt); - uint16_t l = sizeof(UartPacket); - while (l > 0) { - int c = Serial.read(); - if (c == -1) - continue; - *p++ = c; - l--; - } - - // Convert parameters from network byte order to cpu byte order - pkt->address = fromNetwork32(pkt->address); - pkt->arg1 = fromNetwork32(pkt->arg1); - pkt->payloadLength = fromNetwork16(pkt->payloadLength); - - // Read payload - l = pkt->payloadLength; - while (l > 0) { - int c = Serial.read(); - if (c == -1) - continue; - *payload++ = c; - l--; - } -} - -// Allocated statically so the compiler can tell us -// about the amount of used RAM -static UartPacket pkt; -static uint8_t payload[MAX_PAYLOAD_SIZE]; - -void loop() { - receivePacket(&pkt, payload); - - if (pkt.command == CMD_HELLO) { - if (pkt.address == 0x11223344 && pkt.arg1 == 0x55667788) - Serial.print("v10000"); - } - - if (pkt.command == CMD_MAX_PAYLOAD_SIZE) { - uint16_t res = toNetwork16(MAX_PAYLOAD_SIZE); - Serial.write(reinterpret_cast(&res), sizeof(res)); - } - - if (pkt.command == CMD_READ_FLASH) { - uint32_t address = pkt.address; - uint32_t len = pkt.arg1; - if (spi_flash_read(payload, address, len) != M2M_SUCCESS) { - Serial.println("ER"); - } else { - Serial.write(payload, len); - Serial.print("OK"); - } - } - - if (pkt.command == CMD_WRITE_FLASH) { - uint32_t address = pkt.address; - uint32_t len = pkt.payloadLength; - if (spi_flash_write(payload, address, len) != M2M_SUCCESS) { - Serial.print("ER"); - } else { - Serial.print("OK"); - } - } - - if (pkt.command == CMD_ERASE_FLASH) { - uint32_t address = pkt.address; - uint32_t len = pkt.arg1; - if (spi_flash_erase(address, len) != M2M_SUCCESS) { - Serial.print("ER"); - } else { - Serial.print("OK"); - } - } -} - - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino b/feather_sensor_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino deleted file mode 100644 index f62ac62..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino +++ /dev/null @@ -1,170 +0,0 @@ -/* - MDNS WiFi Web Server - - A simple web server that shows the value of the analog input pins, - and exposes itself on the MDNS name 'wifi101.local'. - - On Linux (like Ubuntu 15.04) or OSX you can access the web page - on the device in a browser at 'http://wifi101.local/'. - - On Windows you'll first need to install the Bonjour Printer Services - from: - https://support.apple.com/kb/dl999?locale=en_US - Then you can access the device in a browser at 'http://wifi101.local/'. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the WiFi.begin() call accordingly. - - Circuit: - * WiFi shield attached - * Analog inputs attached to pins A0 through A5 (optional) - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - modified 27 January 2016 - by Tony DiCola - -*/ - -#include -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -char mdnsName[] = "wifi101"; // the MDNS name that the board will respond to -// Note that the actual MDNS name will have '.local' after -// the name above, so "wifi101" will be accessible on -// the MDNS name "wifi101.local". - -int status = WL_IDLE_STATUS; - -// Create a MDNS responder to listen and respond to MDNS name requests. -WiFiMDNSResponder mdnsResponder; - -WiFiServer server(80); - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - // you're connected now, so print out the status: - printWiFiStatus(); - - server.begin(); - - // Setup the MDNS responder to listen to the configured name. - // NOTE: You _must_ call this _after_ connecting to the WiFi network and - // being assigned an IP address. - if (!mdnsResponder.begin(mdnsName)) { - Serial.println("Failed to start MDNS responder!"); - while(1); - } - - Serial.print("Server listening at http://"); - Serial.print(mdnsName); - Serial.println(".local/"); -} - - -void loop() { - // Call the update() function on the MDNS responder every loop iteration to - // make sure it can detect and respond to name requests. - mdnsResponder.poll(); - - // listen for incoming clients - WiFiClient client = server.available(); - if (client) { - Serial.println("new client"); - // an http request ends with a blank line - boolean currentLineIsBlank = true; - while (client.connected()) { - if (client.available()) { - char c = client.read(); - Serial.write(c); - // if you've gotten to the end of the line (received a newline - // character) and the line is blank, the http request has ended, - // so you can send a reply - if (c == '\n' && currentLineIsBlank) { - // send a standard http response header - client.println("HTTP/1.1 200 OK"); - client.println("Content-Type: text/html"); - client.println("Connection: close"); // the connection will be closed after completion of the response - client.println("Refresh: 5"); // refresh the page automatically every 5 sec - client.println(); - client.println(""); - client.println(""); - // output the value of each analog input pin - for (int analogChannel = 0; analogChannel < 6; analogChannel++) { - int sensorReading = analogRead(analogChannel); - client.print("analog input "); - client.print(analogChannel); - client.print(" is "); - client.print(sensorReading); - client.println("
"); - } - client.println(""); - break; - } - if (c == '\n') { - // you're starting a new line - currentLineIsBlank = true; - } - else if (c != '\r') { - // you've gotten a character on the current line - currentLineIsBlank = false; - } - } - } - // give the web browser time to receive the data - delay(1); - - // close the connection: - client.stop(); - Serial.println("client disconnected"); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} diff --git a/feather_sensor_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino b/feather_sensor_lte/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino deleted file mode 100644 index 0297707..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino +++ /dev/null @@ -1,167 +0,0 @@ -/* - WiFi Web Server - - A simple web server that shows the value of the analog input pins. - using a WiFi shield. - - This example is written to configure the WiFi settings using provisioning mode. - It also sets up an mDNS server so the IP address of the board doesn't have to - be obtained via the serial monitor. - - Circuit: - WiFi shield attached - Analog inputs attached to pins A0 through A5 (optional) - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - -*/ - -#include -#include -#include - -const int ledPin = 6; // LED pin for connectivity status indicator - -char mdnsName[] = "wifi101"; // the MDNS name that the board will respond to - // after WiFi settings have been provisioned -// Note that the actual MDNS name will have '.local' after -// the name above, so "wifi101" will be accessible on -// the MDNS name "wifi101.local". - -WiFiServer server(80); - -// Create a MDNS responder to listen and respond to MDNS name requests. -WiFiMDNSResponder mdnsResponder; - -void setup() { - //Initialize serial: - Serial.begin(9600); - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // configure the LED pin for output mode - pinMode(ledPin, OUTPUT); - - // Start in provisioning mode: - // 1) This will try to connect to a previously associated access point. - // 2) If this fails, an access point named "wifi101-XXXX" will be created, where XXXX - // is the last 4 digits of the boards MAC address. Once you are connected to the access point, - // you can configure an SSID and password by visiting http://wifi101/ - WiFi.beginProvision(); - - while (WiFi.status() != WL_CONNECTED) { - // wait while not connected - - // blink the led to show an unconnected status - digitalWrite(ledPin, HIGH); - delay(500); - digitalWrite(ledPin, LOW); - delay(500); - } - - // connected, make the LED stay on - digitalWrite(ledPin, HIGH); - - server.begin(); - - // Setup the MDNS responder to listen to the configured name. - // NOTE: You _must_ call this _after_ connecting to the WiFi network and - // being assigned an IP address. - if (!mdnsResponder.begin(mdnsName)) { - Serial.println("Failed to start MDNS responder!"); - while(1); - } - - Serial.print("Server listening at http://"); - Serial.print(mdnsName); - Serial.println(".local/"); - - // you're connected now, so print out the status: - printWiFiStatus(); -} - - -void loop() { - // Call the update() function on the MDNS responder every loop iteration to - // make sure it can detect and respond to name requests. - mdnsResponder.poll(); - - // listen for incoming clients - WiFiClient client = server.available(); - if (client) { - Serial.println("new client"); - // an http request ends with a blank line - boolean currentLineIsBlank = true; - while (client.connected()) { - if (client.available()) { - char c = client.read(); - Serial.write(c); - // if you've gotten to the end of the line (received a newline - // character) and the line is blank, the http request has ended, - // so you can send a reply - if (c == '\n' && currentLineIsBlank) { - // send a standard http response header - client.println("HTTP/1.1 200 OK"); - client.println("Content-Type: text/html"); - client.println("Connection: close"); // the connection will be closed after completion of the response - client.println("Refresh: 5"); // refresh the page automatically every 5 sec - client.println(); - client.println(""); - client.println(""); - // output the value of each analog input pin - for (int analogChannel = 0; analogChannel < 6; analogChannel++) { - int sensorReading = analogRead(analogChannel); - client.print("analog input "); - client.print(analogChannel); - client.print(" is "); - client.print(sensorReading); - client.println("
"); - } - client.println(""); - break; - } - if (c == '\n') { - // you're starting a new line - currentLineIsBlank = true; - } - else if (c != '\r') { - // you've gotten a character on the current line - currentLineIsBlank = false; - } - } - } - // give the web browser time to receive the data - delay(1); - - // close the connection: - client.stop(); - Serial.println("client disonnected"); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino b/feather_sensor_lte/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino deleted file mode 100644 index 45b908e..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino +++ /dev/null @@ -1,120 +0,0 @@ -/* - - This example prints the WiFi shield's MAC address, and - scans for available WiFi networks using the WiFi shield. - Every ten seconds, it scans again. It doesn't actually - connect to any network, so no encryption scheme is specified. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 21 Junn 2012 - by Tom Igoe and Jaymes Dec - */ - - -#include -#include - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // Print WiFi MAC address: - printMacAddress(); - - // scan for existing networks: - Serial.println("Scanning available networks..."); - listNetworks(); -} - -void loop() { - delay(10000); - // scan for existing networks: - Serial.println("Scanning available networks..."); - listNetworks(); -} - -void printMacAddress() { - // the MAC address of your WiFi shield - byte mac[6]; - - // print your MAC address: - WiFi.macAddress(mac); - Serial.print("MAC: "); - Serial.print(mac[5], HEX); - Serial.print(":"); - Serial.print(mac[4], HEX); - Serial.print(":"); - Serial.print(mac[3], HEX); - Serial.print(":"); - Serial.print(mac[2], HEX); - Serial.print(":"); - Serial.print(mac[1], HEX); - Serial.print(":"); - Serial.println(mac[0], HEX); -} - -void listNetworks() { - // scan for nearby networks: - Serial.println("** Scan Networks **"); - int numSsid = WiFi.scanNetworks(); - if (numSsid == -1) - { - Serial.println("Couldn't get a wifi connection"); - while (true); - } - - // print the list of networks seen: - Serial.print("number of available networks:"); - Serial.println(numSsid); - - // print the network number and name for each network found: - for (int thisNet = 0; thisNet < numSsid; thisNet++) { - Serial.print(thisNet); - Serial.print(") "); - Serial.print(WiFi.SSID(thisNet)); - Serial.print("\tSignal: "); - Serial.print(WiFi.RSSI(thisNet)); - Serial.print(" dBm"); - Serial.print("\tEncryption: "); - printEncryptionType(WiFi.encryptionType(thisNet)); - Serial.flush(); - } -} - -void printEncryptionType(int thisType) { - // read the encryption type and print out the name: - switch (thisType) { - case ENC_TYPE_WEP: - Serial.println("WEP"); - break; - case ENC_TYPE_TKIP: - Serial.println("WPA"); - break; - case ENC_TYPE_CCMP: - Serial.println("WPA2"); - break; - case ENC_TYPE_NONE: - Serial.println("None"); - break; - case ENC_TYPE_AUTO: - Serial.println("Auto"); - break; - } -} - - - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino b/feather_sensor_lte/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino deleted file mode 100644 index 2afb544..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino +++ /dev/null @@ -1,149 +0,0 @@ -/* - - This example prints the WiFi 101 shield or MKR1000 MAC address, and - scans for available WiFi networks using the WiFi 101 shield or MKR1000 board. - Every ten seconds, it scans again. It doesn't actually - connect to any network, so no encryption scheme is specified. - BSSID and WiFi channel are printed - - Circuit: - WiFi 101 shield attached or MKR1000 board - - This example is based on ScanNetworks - - created 1 Mar 2017 - by Arturo Guadalupi -*/ - - -#include -#include - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // Print WiFi MAC address: - printMacAddress(); - - // scan for existing networks: - Serial.println(); - Serial.println("Scanning available networks..."); - listNetworks(); -} - -void loop() { - delay(10000); - // scan for existing networks: - Serial.println("Scanning available networks..."); - listNetworks(); -} - -void printMacAddress() { - // the MAC address of your WiFi shield - byte mac[6]; - - // print your MAC address: - WiFi.macAddress(mac); - Serial.print("MAC: "); - print2Digits(mac[5]); - Serial.print(":"); - print2Digits(mac[4]); - Serial.print(":"); - print2Digits(mac[3]); - Serial.print(":"); - print2Digits(mac[2]); - Serial.print(":"); - print2Digits(mac[1]); - Serial.print(":"); - print2Digits(mac[0]); -} - -void listNetworks() { - // scan for nearby networks: - Serial.println("** Scan Networks **"); - int numSsid = WiFi.scanNetworks(); - if (numSsid == -1) - { - Serial.println("Couldn't get a WiFi connection"); - while (true); - } - - // print the list of networks seen: - Serial.print("number of available networks: "); - Serial.println(numSsid); - - // print the network number and name for each network found: - for (int thisNet = 0; thisNet < numSsid; thisNet++) { - Serial.print(thisNet + 1); - Serial.print(") "); - Serial.print("Signal: "); - Serial.print(WiFi.RSSI(thisNet)); - Serial.print(" dBm"); - Serial.print("\tChannel: "); - Serial.print(WiFi.channel(thisNet)); - byte bssid[6]; - Serial.print("\t\tBSSID: "); - printBSSID(WiFi.BSSID(thisNet, bssid)); - Serial.print("\tEncryption: "); - printEncryptionType(WiFi.encryptionType(thisNet)); - Serial.print("\t\tSSID: "); - Serial.println(WiFi.SSID(thisNet)); - Serial.flush(); - } - Serial.println(); -} - -void printBSSID(byte bssid[]) { - print2Digits(bssid[5]); - Serial.print(":"); - print2Digits(bssid[4]); - Serial.print(":"); - print2Digits(bssid[3]); - Serial.print(":"); - print2Digits(bssid[2]); - Serial.print(":"); - print2Digits(bssid[1]); - Serial.print(":"); - print2Digits(bssid[0]); -} - -void printEncryptionType(int thisType) { - // read the encryption type and print out the name: - switch (thisType) { - case ENC_TYPE_WEP: - Serial.print("WEP"); - break; - case ENC_TYPE_TKIP: - Serial.print("WPA"); - break; - case ENC_TYPE_CCMP: - Serial.print("WPA2"); - break; - case ENC_TYPE_NONE: - Serial.print("None"); - break; - case ENC_TYPE_AUTO: - Serial.print("Auto"); - break; - } -} - -void print2Digits(byte thisByte) { - if (thisByte < 0xF) { - Serial.print("0"); - } - Serial.print(thisByte, HEX); -} - - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino b/feather_sensor_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino deleted file mode 100644 index aeaf0c6..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino +++ /dev/null @@ -1,131 +0,0 @@ -/* - WiFi Web Server LED Blink - - A simple web server that lets you blink an LED via the web. - This sketch will print the IP address of your WiFi Shield (once connected) - to the Serial monitor. From there, you can open that address in a web browser - to turn on and off the LED on pin 9. - - If the IP address of your shield is yourAddress: - http://yourAddress/H turns the LED on - http://yourAddress/L turns it off - - This example is written for a network using WPA encryption. For - WEP or WPA, change the WiFi.begin() call accordingly. - - Circuit: - * WiFi shield attached - * LED attached to pin 9 - - created 25 Nov 2012 - by Tom Igoe - */ -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; -WiFiServer server(80); - -void setup() { - Serial.begin(9600); // initialize serial communication - pinMode(9, OUTPUT); // set the LED pin mode - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - while (true); // don't continue - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - // wait 10 seconds for connection: - delay(10000); - } - server.begin(); // start the web server on port 80 - printWiFiStatus(); // you're connected now, so print out the status -} - - -void loop() { - WiFiClient client = server.available(); // listen for incoming clients - - if (client) { // if you get a client, - Serial.println("new client"); // print a message out the serial port - String currentLine = ""; // make a String to hold incoming data from the client - while (client.connected()) { // loop while the client's connected - if (client.available()) { // if there's bytes to read from the client, - char c = client.read(); // read a byte, then - Serial.write(c); // print it out the serial monitor - if (c == '\n') { // if the byte is a newline character - - // if the current line is blank, you got two newline characters in a row. - // that's the end of the client HTTP request, so send a response: - if (currentLine.length() == 0) { - // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) - // and a content-type so the client knows what's coming, then a blank line: - client.println("HTTP/1.1 200 OK"); - client.println("Content-type:text/html"); - client.println(); - - // the content of the HTTP response follows the header: - client.print("Click here turn the LED on pin 9 on
"); - client.print("Click here turn the LED on pin 9 off
"); - - // The HTTP response ends with another blank line: - client.println(); - // break out of the while loop: - break; - } - else { // if you got a newline, then clear currentLine: - currentLine = ""; - } - } - else if (c != '\r') { // if you got anything else but a carriage return character, - currentLine += c; // add it to the end of the currentLine - } - - // Check to see if the client request was "GET /H" or "GET /L": - if (currentLine.endsWith("GET /H")) { - digitalWrite(9, HIGH); // GET /H turns the LED on - } - if (currentLine.endsWith("GET /L")) { - digitalWrite(9, LOW); // GET /L turns the LED off - } - } - } - // close the connection: - client.stop(); - Serial.println("client disonnected"); - } -} - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); - // print where to go in a browser: - Serial.print("To see this page in action, open a browser to http://"); - Serial.println(ip); -} diff --git a/feather_sensor_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino b/feather_sensor_lte/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino deleted file mode 100644 index ac7bd76..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino +++ /dev/null @@ -1,114 +0,0 @@ -/* - Chat Server - - A simple server that distributes any incoming messages to all - connected clients. To use telnet to your device's IP address and type. - You can see the client's input in the serial monitor as well. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the WiFi.begin() call accordingly. - - - Circuit: - * WiFi shield attached - - created 18 Dec 2009 - by David A. Mellis - modified 31 May 2012 - by Tom Igoe - - */ - -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) - -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; - -WiFiServer server(23); - -boolean alreadyConnected = false; // whether or not the client was connected previously - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - - // start the server: - server.begin(); - // you're connected now, so print out the status: - printWiFiStatus(); -} - - -void loop() { - // wait for a new client: - WiFiClient client = server.available(); - - - // when the client sends the first byte, say hello: - if (client) { - if (!alreadyConnected) { - // clead out the input buffer: - client.flush(); - Serial.println("We have a new client"); - client.println("Hello, client!"); - alreadyConnected = true; - } - - if (client.available() > 0) { - // read the bytes incoming from the client: - char thisChar = client.read(); - // echo the bytes back to the client: - server.write(thisChar); - // echo the bytes to the server as well: - Serial.write(thisChar); - } - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino b/feather_sensor_lte/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino deleted file mode 100644 index 9a51c19..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino +++ /dev/null @@ -1,140 +0,0 @@ -/* - - This example connects to a encrypted WiFi network (WPA/WPA2). - Then it prints the MAC address of the WiFi shield, - the IP address obtained, and other network details. - Then it continuously pings given host specified by IP Address or name. - - Circuit: - WiFi shield attached / MKR1000 - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 09 June 2016 - by Petar Georgiev -*/ -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int status = WL_IDLE_STATUS; // the WiFi radio's status - -// Specify IP address or hostname -String hostName = "www.google.com"; -int pingResult; - -void setup() { - // Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to WPA SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - - // wait 5 seconds for connection: - delay(5000); - } - - // you're connected now, so print out the data: - Serial.println("You're connected to the network"); - printCurrentNet(); - printWiFiData(); -} - -void loop() { - Serial.print("Pinging "); - Serial.print(hostName); - Serial.print(": "); - - pingResult = WiFi.ping(hostName); - - if (pingResult >= 0) { - Serial.print("SUCCESS! RTT = "); - Serial.print(pingResult); - Serial.println(" ms"); - } else { - Serial.print("FAILED! Error code: "); - Serial.println(pingResult); - } - - delay(5000); -} - -void printWiFiData() { - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP address : "); - Serial.println(ip); - - Serial.print("Subnet mask: "); - Serial.println((IPAddress)WiFi.subnetMask()); - - Serial.print("Gateway IP : "); - Serial.println((IPAddress)WiFi.gatewayIP()); - - // print your MAC address: - byte mac[6]; - WiFi.macAddress(mac); - Serial.print("MAC address: "); - Serial.print(mac[5], HEX); - Serial.print(":"); - Serial.print(mac[4], HEX); - Serial.print(":"); - Serial.print(mac[3], HEX); - Serial.print(":"); - Serial.print(mac[2], HEX); - Serial.print(":"); - Serial.print(mac[1], HEX); - Serial.print(":"); - Serial.println(mac[0], HEX); - Serial.println(); -} - -void printCurrentNet() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print the MAC address of the router you're attached to: - byte bssid[6]; - WiFi.BSSID(bssid); - Serial.print("BSSID: "); - Serial.print(bssid[5], HEX); - Serial.print(":"); - Serial.print(bssid[4], HEX); - Serial.print(":"); - Serial.print(bssid[3], HEX); - Serial.print(":"); - Serial.print(bssid[2], HEX); - Serial.print(":"); - Serial.print(bssid[1], HEX); - Serial.print(":"); - Serial.println(bssid[0], HEX); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI): "); - Serial.println(rssi); - - // print the encryption type: - byte encryption = WiFi.encryptionType(); - Serial.print("Encryption Type: "); - Serial.println(encryption, HEX); - Serial.println(); -} diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino b/feather_sensor_lte/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino deleted file mode 100644 index a436902..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino +++ /dev/null @@ -1,107 +0,0 @@ -/* -This example creates a client object that connects and transfers -data using always SSL. - -It is compatible with the methods normally related to plain -connections, like client.connect(host, port). - -Written by Arturo Guadalupi -last revision November 2015 - -*/ - -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; -// if you don't want to use DNS (and reduce your sketch size) -// use the numeric IP instead of the name for the server: -//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) -char server[] = "www.google.com"; // name address for Google (using DNS) - -// Initialize the Ethernet client library -// with the IP address and port of the server -// that you want to connect to (port 80 is default for HTTP): -WiFiSSLClient client; - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while (status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - Serial.println("Connected to wifi"); - printWiFiStatus(); - - Serial.println("\nStarting connection to server..."); - // if you get a connection, report back via serial: - if (client.connect(server, 443)) { - Serial.println("connected to server"); - // Make a HTTP request: - client.println("GET /search?q=arduino HTTP/1.1"); - client.println("Host: www.google.com"); - client.println("Connection: close"); - client.println(); - } -} - -void loop() { - // if there are incoming bytes available - // from the server, read them and print them: - while (client.available()) { - char c = client.read(); - Serial.write(c); - } - - // if the server's disconnected, stop the client: - if (!client.connected()) { - Serial.println(); - Serial.println("disconnecting from server."); - client.stop(); - - // do nothing forevermore: - while (true); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino b/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino deleted file mode 100644 index e82fbaa..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino +++ /dev/null @@ -1,182 +0,0 @@ -/* - - Udp NTP Client - - Get the time from a Network Time Protocol (NTP) time server - Demonstrates use of UDP sendPacket and ReceivePacket - For more on NTP time servers and the messages needed to communicate with them, - see http://en.wikipedia.org/wiki/Network_Time_Protocol - - created 4 Sep 2010 - by Michael Margolis - modified 9 Apr 2012 - by Tom Igoe - - This code is in the public domain. - - */ - -#include -#include -#include - -int status = WL_IDLE_STATUS; -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -unsigned int localPort = 2390; // local port to listen for UDP packets - -IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server - -const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message - -byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets - -// A UDP instance to let us send and receive packets over UDP -WiFiUDP Udp; - -void setup() -{ - // Open serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - - Serial.println("Connected to wifi"); - printWiFiStatus(); - - Serial.println("\nStarting connection to server..."); - Udp.begin(localPort); -} - -void loop() -{ - sendNTPpacket(timeServer); // send an NTP packet to a time server - // wait to see if a reply is available - delay(1000); - if ( Udp.parsePacket() ) { - Serial.println("packet received"); - // We've received a packet, read the data from it - Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer - - //the timestamp starts at byte 40 of the received packet and is four bytes, - // or two words, long. First, esxtract the two words: - - unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); - unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); - // combine the four bytes (two words) into a long integer - // this is NTP time (seconds since Jan 1 1900): - unsigned long secsSince1900 = highWord << 16 | lowWord; - Serial.print("Seconds since Jan 1 1900 = " ); - Serial.println(secsSince1900); - - // now convert NTP time into everyday time: - Serial.print("Unix time = "); - // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: - const unsigned long seventyYears = 2208988800UL; - // subtract seventy years: - unsigned long epoch = secsSince1900 - seventyYears; - // print Unix time: - Serial.println(epoch); - - - // print the hour, minute and second: - Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) - Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) - Serial.print(':'); - if ( ((epoch % 3600) / 60) < 10 ) { - // In the first 10 minutes of each hour, we'll want a leading '0' - Serial.print('0'); - } - Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) - Serial.print(':'); - if ( (epoch % 60) < 10 ) { - // In the first 10 seconds of each minute, we'll want a leading '0' - Serial.print('0'); - } - Serial.println(epoch % 60); // print the second - } - // wait ten seconds before asking for the time again - delay(10000); -} - -// send an NTP request to the time server at the given address -unsigned long sendNTPpacket(IPAddress& address) -{ - //Serial.println("1"); - // set all bytes in the buffer to 0 - memset(packetBuffer, 0, NTP_PACKET_SIZE); - // Initialize values needed to form NTP request - // (see URL above for details on the packets) - //Serial.println("2"); - packetBuffer[0] = 0b11100011; // LI, Version, Mode - packetBuffer[1] = 0; // Stratum, or type of clock - packetBuffer[2] = 6; // Polling Interval - packetBuffer[3] = 0xEC; // Peer Clock Precision - // 8 bytes of zero for Root Delay & Root Dispersion - packetBuffer[12] = 49; - packetBuffer[13] = 0x4E; - packetBuffer[14] = 49; - packetBuffer[15] = 52; - - //Serial.println("3"); - - // all NTP fields have been given values, now - // you can send a packet requesting a timestamp: - Udp.beginPacket(address, 123); //NTP requests are to port 123 - //Serial.println("4"); - Udp.write(packetBuffer, NTP_PACKET_SIZE); - //Serial.println("5"); - Udp.endPacket(); - //Serial.println("6"); -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - - - - - - - - - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino b/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino deleted file mode 100644 index cbc9f7f..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino +++ /dev/null @@ -1,113 +0,0 @@ -/* - WiFi UDP Send and Receive String - - This sketch wait an UDP packet on localPort using a WiFi shield. - When a packet is received an Acknowledge packet is sent to the client on port remotePort - - Circuit: - * WiFi shield attached - - created 30 December 2012 - by dlf (Metodo2 srl) - - */ - - -#include -#include -#include - -int status = WL_IDLE_STATUS; -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -unsigned int localPort = 2390; // local port to listen on - -char packetBuffer[255]; //buffer to hold incoming packet -char ReplyBuffer[] = "acknowledged"; // a string to send back - -WiFiUDP Udp; - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - Serial.println("Connected to wifi"); - printWiFiStatus(); - - Serial.println("\nStarting connection to server..."); - // if you get a connection, report back via serial: - Udp.begin(localPort); -} - -void loop() { - - // if there's data available, read a packet - int packetSize = Udp.parsePacket(); - if (packetSize) - { - Serial.print("Received packet of size "); - Serial.println(packetSize); - Serial.print("From "); - IPAddress remoteIp = Udp.remoteIP(); - Serial.print(remoteIp); - Serial.print(", port "); - Serial.println(Udp.remotePort()); - - // read the packet into packetBufffer - int len = Udp.read(packetBuffer, 255); - if (len > 0) packetBuffer[len] = 0; - Serial.println("Contents:"); - Serial.println(packetBuffer); - - // send a reply, to the IP address and port that sent us the packet we received - Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); - Udp.write(ReplyBuffer); - Udp.endPacket(); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - - - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino b/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino deleted file mode 100644 index 5faa779..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino +++ /dev/null @@ -1,121 +0,0 @@ -/* - Web client - - This sketch connects to a website (http://www.google.com) - using a WiFi shield. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the WiFi.begin() call accordingly. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the WiFi.begin() call accordingly. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - */ - - -#include -#include -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; -// if you don't want to use DNS (and reduce your sketch size) -// use the numeric IP instead of the name for the server: -//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) -char server[] = "www.google.com"; // name address for Google (using DNS) - -// Initialize the Ethernet client library -// with the IP address and port of the server -// that you want to connect to (port 80 is default for HTTP): -WiFiClient client; - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while (status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - Serial.println("Connected to wifi"); - printWiFiStatus(); - - Serial.println("\nStarting connection to server..."); - // if you get a connection, report back via serial: - if (client.connect(server, 80)) { - Serial.println("connected to server"); - // Make a HTTP request: - client.println("GET /search?q=arduino HTTP/1.1"); - client.println("Host: www.google.com"); - client.println("Connection: close"); - client.println(); - } -} - -void loop() { - // if there are incoming bytes available - // from the server, read them and print them: - while (client.available()) { - char c = client.read(); - Serial.write(c); - } - - // if the server's disconnected, stop the client: - if (!client.connected()) { - Serial.println(); - Serial.println("disconnecting from server."); - client.stop(); - - // do nothing forevermore: - while (true); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - - - - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino b/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino deleted file mode 100644 index ac8b4e5..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino +++ /dev/null @@ -1,127 +0,0 @@ -/* - Repeating WiFi Web Client - - This sketch connects to a a web server and makes a request - using an Arduino WiFi shield. - - Circuit: - * WiFi shield attached to pins SPI pins and pin 7 - - created 23 April 2012 - modified 31 May 2012 - by Tom Igoe - modified 13 Jan 2014 - by Federico Vanzati - - http://arduino.cc/en/Tutorial/WiFiWebClientRepeating - This code is in the public domain. - */ - -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; - -// Initialize the WiFi client library -WiFiClient client; - -// server address: -char server[] = "www.arduino.cc"; -//IPAddress server(64,131,82,241); - -unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds -const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - // you're connected now, so print out the status: - printWiFiStatus(); -} - -void loop() { - // if there's incoming data from the net connection. - // send it out the serial port. This is for debugging - // purposes only: - while (client.available()) { - char c = client.read(); - Serial.write(c); - } - - // if ten seconds have passed since your last connection, - // then connect again and send data: - if (millis() - lastConnectionTime > postingInterval) { - httpRequest(); - } - -} - -// this method makes a HTTP connection to the server: -void httpRequest() { - // close any connection before send a new request. - // This will free the socket on the WiFi shield - client.stop(); - - // if there's a successful connection: - if (client.connect(server, 80)) { - Serial.println("connecting..."); - // send the HTTP PUT request: - client.println("GET /latest.txt HTTP/1.1"); - client.println("Host: www.arduino.cc"); - client.println("User-Agent: ArduinoWiFi/1.1"); - client.println("Connection: close"); - client.println(); - - // note the time that the connection was made: - lastConnectionTime = millis(); - } - else { - // if you couldn't make a connection: - Serial.println("connection failed"); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino b/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino deleted file mode 100644 index 24d0083..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino +++ /dev/null @@ -1,135 +0,0 @@ -/* - WiFi Web Server - - A simple web server that shows the value of the analog input pins. - using a WiFi shield. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the WiFi.begin() call accordingly. - - Circuit: - * WiFi shield attached - * Analog inputs attached to pins A0 through A5 (optional) - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - - */ - -#include -#include - - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; - -WiFiServer server(80); - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while (status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - server.begin(); - // you're connected now, so print out the status: - printWiFiStatus(); -} - - -void loop() { - // listen for incoming clients - WiFiClient client = server.available(); - if (client) { - Serial.println("new client"); - // an http request ends with a blank line - boolean currentLineIsBlank = true; - while (client.connected()) { - if (client.available()) { - char c = client.read(); - Serial.write(c); - // if you've gotten to the end of the line (received a newline - // character) and the line is blank, the http request has ended, - // so you can send a reply - if (c == '\n' && currentLineIsBlank) { - // send a standard http response header - client.println("HTTP/1.1 200 OK"); - client.println("Content-Type: text/html"); - client.println("Connection: close"); // the connection will be closed after completion of the response - client.println("Refresh: 5"); // refresh the page automatically every 5 sec - client.println(); - client.println(""); - client.println(""); - // output the value of each analog input pin - for (int analogChannel = 0; analogChannel < 6; analogChannel++) { - int sensorReading = analogRead(analogChannel); - client.print("analog input "); - client.print(analogChannel); - client.print(" is "); - client.print(sensorReading); - client.println("
"); - } - client.println(""); - break; - } - if (c == '\n') { - // you're starting a new line - currentLineIsBlank = true; - } - else if (c != '\r') { - // you've gotten a character on the current line - currentLineIsBlank = false; - } - } - } - // give the web browser time to receive the data - delay(1); - - // close the connection: - client.stop(); - Serial.println("client disconnected"); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} diff --git a/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h b/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_lte/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_lte/libraries/WiFi101/keywords.txt b/feather_sensor_lte/libraries/WiFi101/keywords.txt deleted file mode 100644 index 498954d..0000000 --- a/feather_sensor_lte/libraries/WiFi101/keywords.txt +++ /dev/null @@ -1,61 +0,0 @@ -####################################### -# Syntax Coloring Map For WiFi -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -WiFi KEYWORD1 -WiFi101 KEYWORD1 -Client KEYWORD1 -Server KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -setPins KEYWORD2 -status KEYWORD2 -connect KEYWORD2 -connectSSL KEYWORD2 -write KEYWORD2 -available KEYWORD2 -read KEYWORD2 -flush KEYWORD2 -stop KEYWORD2 -connected KEYWORD2 -begin KEYWORD2 -beginProvision KEYWORD2 -beginOrProvision KEYWORD2 -beginMulticast KEYWORD2 -disconnect KEYWORD2 -macAddress KEYWORD2 -localIP KEYWORD2 -subnetMask KEYWORD2 -gatewayIP KEYWORD2 -SSID KEYWORD2 -BSSID KEYWORD2 -APClientMacAddress KEYWORD2 -RSSI KEYWORD2 -encryptionType KEYWORD2 -channel KEYWORD2 -provisioned KEYWORD2 -getResult KEYWORD2 -getSocket KEYWORD2 -poll KEYWORD2 -getTime KEYWORD2 -hostname KEYWORD2 -WiFiClient KEYWORD2 -WiFiServer KEYWORD2 -WiFiSSLClient KEYWORD2 -WiFiMDNSResponder KEYWORD2 - -lowPowerMode KEYWORD2 -maxLowPowerMode KEYWORD2 -noLowPowerMode KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### - diff --git a/feather_sensor_lte/libraries/WiFi101/library.properties b/feather_sensor_lte/libraries/WiFi101/library.properties deleted file mode 100644 index f6d0b6d..0000000 --- a/feather_sensor_lte/libraries/WiFi101/library.properties +++ /dev/null @@ -1,10 +0,0 @@ -name=WiFi101 -version=0.14.4 -author=Arduino -maintainer=Arduino -sentence=Network driver for ATMEL WINC1500 module (used on Arduino/Genuino Wifi Shield 101 and MKR1000 boards) -paragraph=This library implements a network driver for devices based on the ATMEL WINC1500 wifi module -category=Communication -url=http://www.arduino.cc/en/Reference/WiFi101 -architectures=* -includes=WiFi101.h diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFi.cpp b/feather_sensor_lte/libraries/WiFi101/src/WiFi.cpp deleted file mode 100644 index 0c71ffc..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/WiFi.cpp +++ /dev/null @@ -1,1106 +0,0 @@ -/* - WiFi.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifdef ARDUINO_ARCH_AVR -#include -#if (__AVR_LIBC_MAJOR__ < 2) -#define WIFI_101_NO_TIME_H -#endif -#endif - -#ifndef WIFI_101_NO_TIME_H -#include -#endif - -#if !defined(_TIME_H_) && !defined(TIME_H) -// another library overrided the time.h header -#define WIFI_101_NO_TIME_H -#endif - -#include "WiFi101.h" - -extern "C" { - #include "bsp/include/nm_bsp.h" - #include "bsp/include/nm_bsp_arduino.h" - #include "socket/include/socket_buffer.h" - #include "socket/include/m2m_socket_host_if.h" - #include "driver/source/nmasic.h" - #include "driver/include/m2m_periph.h" - #include "driver/include/m2m_ssl.h" -} - -static void wifi_cb(uint8_t u8MsgType, void *pvMsg) -{ - switch (u8MsgType) { - case M2M_WIFI_RESP_DEFAULT_CONNECT: - { - tstrM2MDefaultConnResp *pstrDefaultConnResp = (tstrM2MDefaultConnResp *)pvMsg; - if (pstrDefaultConnResp->s8ErrorCode) { - WiFi._status = WL_DISCONNECTED; - } - } - break; - - case M2M_WIFI_RESP_CON_STATE_CHANGED: - { - tstrM2mWifiStateChanged *pstrWifiState = (tstrM2mWifiStateChanged *)pvMsg; - if (pstrWifiState->u8CurrState == M2M_WIFI_CONNECTED) { - //SERIAL_PORT_MONITOR.println("wifi_cb: M2M_WIFI_RESP_CON_STATE_CHANGED: CONNECTED"); - if (WiFi._mode == WL_STA_MODE && !WiFi._dhcp) { - WiFi._status = WL_CONNECTED; - - // WiFi led ON. - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); - } else if (WiFi._mode == WL_AP_MODE) { - WiFi._status = WL_AP_CONNECTED; - } - } else if (pstrWifiState->u8CurrState == M2M_WIFI_DISCONNECTED) { - //SERIAL_PORT_MONITOR.println("wifi_cb: M2M_WIFI_RESP_CON_STATE_CHANGED: DISCONNECTED"); - if (WiFi._mode == WL_STA_MODE) { - WiFi._status = WL_DISCONNECTED; - if (WiFi._dhcp) { - WiFi._localip = 0; - WiFi._submask = 0; - WiFi._gateway = 0; - } - // Close sockets to clean state - // Clients will need to reconnect once the physical link will be re-established - for (int i=0; i < TCP_SOCK_MAX; i++) { - if (WiFi._client[i]) - WiFi._client[i]->stop(); - } - } else if (WiFi._mode == WL_AP_MODE) { - WiFi._status = WL_AP_LISTENING; - } - // WiFi led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); - } - } - break; - - case M2M_WIFI_REQ_DHCP_CONF: - { - if (WiFi._mode == WL_STA_MODE) { - tstrM2MIPConfig *pstrIPCfg = (tstrM2MIPConfig *)pvMsg; - WiFi._localip = pstrIPCfg->u32StaticIP; - WiFi._submask = pstrIPCfg->u32SubnetMask; - WiFi._gateway = pstrIPCfg->u32Gateway; - - WiFi._status = WL_CONNECTED; - - // WiFi led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0); - } - /*uint8_t *pu8IPAddress = (uint8_t *)pvMsg; - SERIAL_PORT_MONITOR.print("wifi_cb: M2M_WIFI_REQ_DHCP_CONF: IP is "); - SERIAL_PORT_MONITOR.print(pu8IPAddress[0], 10); - SERIAL_PORT_MONITOR.print("."); - SERIAL_PORT_MONITOR.print(pu8IPAddress[1], 10); - SERIAL_PORT_MONITOR.print("."); - SERIAL_PORT_MONITOR.print(pu8IPAddress[2], 10); - SERIAL_PORT_MONITOR.print("."); - SERIAL_PORT_MONITOR.print(pu8IPAddress[3], 10); - SERIAL_PORT_MONITOR.println("");*/ - } - break; - - case M2M_WIFI_RESP_CURRENT_RSSI: - { - WiFi._resolve = *((int8_t *)pvMsg); - } - break; - - case M2M_WIFI_RESP_PROVISION_INFO: - { - tstrM2MProvisionInfo *pstrProvInfo = (tstrM2MProvisionInfo *)pvMsg; - //SERIAL_PORT_MONITOR.println("wifi_cb: M2M_WIFI_RESP_PROVISION_INFO"); - - if (pstrProvInfo->u8Status == M2M_SUCCESS) { - memset(WiFi._ssid, 0, M2M_MAX_SSID_LEN); - memcpy(WiFi._ssid, (char *)pstrProvInfo->au8SSID, strlen((char *)pstrProvInfo->au8SSID)); - WiFi._mode = WL_STA_MODE; - WiFi._localip = 0; - WiFi._submask = 0; - WiFi._gateway = 0; - m2m_wifi_connect((char *)pstrProvInfo->au8SSID, strlen((char *)pstrProvInfo->au8SSID), - pstrProvInfo->u8SecType, pstrProvInfo->au8Password, M2M_WIFI_CH_ALL); - } else { - WiFi._status = WL_PROVISIONING_FAILED; - //SERIAL_PORT_MONITOR.println("wifi_cb: Provision failed.\r\n"); - WiFi.beginProvision(); - } - } - break; - - case M2M_WIFI_RESP_SCAN_DONE: - { - tstrM2mScanDone *pstrInfo = (tstrM2mScanDone *)pvMsg; - if (pstrInfo->u8NumofCh >= 1) { - WiFi._status = WL_SCAN_COMPLETED; - } - } - break; - - case M2M_WIFI_RESP_SCAN_RESULT: - { - tstrM2mWifiscanResult *pstrScanResult = (tstrM2mWifiscanResult *)pvMsg; - uint16_t scan_ssid_len = strlen((const char *)pstrScanResult->au8SSID); - memset(WiFi._scan_ssid, 0, M2M_MAX_SSID_LEN); - if (scan_ssid_len) { - memcpy(WiFi._scan_ssid, (const char *)pstrScanResult->au8SSID, scan_ssid_len); - } - if (WiFi._remoteMacAddress) { - // reverse copy the remote MAC - for(int i = 0; i < 6; i++) { - WiFi._remoteMacAddress[i] = pstrScanResult->au8BSSID[5-i]; - } - } - WiFi._resolve = pstrScanResult->s8rssi; - WiFi._scan_auth = pstrScanResult->u8AuthType; - WiFi._scan_channel = pstrScanResult->u8ch; - WiFi._status = WL_SCAN_COMPLETED; - } - break; - - case M2M_WIFI_RESP_CONN_INFO: - { - tstrM2MConnInfo *pstrConnInfo = (tstrM2MConnInfo*)pvMsg; - - if (WiFi._remoteMacAddress) { - // reverse copy the remote MAC - for(int i = 0; i < 6; i++) { - WiFi._remoteMacAddress[i] = pstrConnInfo->au8MACAddress[5-i]; - } - WiFi._remoteMacAddress = 0; - } - - strcpy((char *)WiFi._ssid, pstrConnInfo->acSSID); - } - break; - - case M2M_WIFI_RESP_GET_SYS_TIME: - { - if (WiFi._resolve != 0) { - memcpy((tstrSystemTime *)WiFi._resolve, pvMsg, sizeof(tstrSystemTime)); - - WiFi._resolve = 0; - } - } - break; - - default: - break; - } -} - -static void resolve_cb(uint8_t * /* hostName */, uint32_t hostIp) -{ - WiFi._resolve = hostIp; -} - -static void ping_cb(uint32 u32IPAddr, uint32 u32RTT, uint8 u8ErrorCode) -{ - if (PING_ERR_SUCCESS == u8ErrorCode) { - // Ensure this ICMP reply comes from requested IP address - if (WiFi._resolve == u32IPAddr) { - WiFi._resolve = (uint32_t)u32RTT; - } else { - // Another network device replied to the our ICMP request - WiFi._resolve = (uint32_t)WL_PING_DEST_UNREACHABLE; - } - } else if (PING_ERR_DEST_UNREACH == u8ErrorCode) { - WiFi._resolve = (uint32_t)WL_PING_DEST_UNREACHABLE; - } else if (PING_ERR_TIMEOUT == u8ErrorCode) { - WiFi._resolve = (uint32_t)WL_PING_TIMEOUT; - } else { - WiFi._resolve = (uint32_t)WL_PING_ERROR; - } -} - -WiFiClass::WiFiClass() -{ - _mode = WL_RESET_MODE; - _status = WL_NO_SHIELD; - _init = 0; -} - -void WiFiClass::setPins(int8_t cs, int8_t irq, int8_t rst, int8_t en) -{ - gi8Winc1501CsPin = cs; - gi8Winc1501IntnPin = irq; - gi8Winc1501ResetPin = rst; - gi8Winc1501ChipEnPin = en; -} - -int WiFiClass::init() -{ - tstrWifiInitParam param; - int8_t ret; - - // Initialize the WiFi BSP: - nm_bsp_init(); - - // Initialize WiFi module and register status callback: - param.pfAppWifiCb = wifi_cb; - ret = m2m_wifi_init(¶m); - if (M2M_SUCCESS != ret && M2M_ERR_FW_VER_MISMATCH != ret) { - // Error led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO18, 0); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO6, 1); - return ret; - } - - // Initialize socket API and register socket callback: - socketInit(); - socketBufferInit(); - registerSocketCallback(socketBufferCb, resolve_cb); - _init = 1; - _status = WL_IDLE_STATUS; - _localip = 0; - _submask = 0; - _gateway = 0; - _dhcp = 1; - _resolve = 0; - _remoteMacAddress = 0; - memset(_client, 0, sizeof(WiFiClient *) * TCP_SOCK_MAX); - - extern uint32 nmdrv_firm_ver; - - if (nmdrv_firm_ver >= M2M_MAKE_VERSION(19, 5, 0)) { - // enable AES-128 and AES-256 Ciphers, if firmware is 19.5.0 or higher - m2m_ssl_set_active_ciphersuites(SSL_NON_ECC_CIPHERS_AES_128 | SSL_NON_ECC_CIPHERS_AES_256); - } - - // Initialize IO expander LED control (rev A then rev B).. - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO18, 1); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO15, 1); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO18, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO6, 1); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO4, 1); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO5, 1); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO6, 1); - - return ret; -} - -extern "C" { - sint8 nm_get_firmware_info(tstrM2mRev* M2mRev); -} - -char* WiFiClass::firmwareVersion() -{ - tstrM2mRev rev; - - if (!_init) { - init(); - } - nm_get_firmware_info(&rev); - memset(_version, 0, 9); - if (rev.u8FirmwareMajor != rev.u8DriverMajor && rev.u8FirmwareMinor != rev.u8DriverMinor) { - sprintf(_version, "-Err-"); - } - else { - sprintf(_version, "%d.%d.%d", rev.u8FirmwareMajor, rev.u8FirmwareMinor, rev.u8FirmwarePatch); - } - return _version; -} - -uint8_t WiFiClass::begin() -{ - if (!_init) { - init(); - } - - // Connect to router: - if (_dhcp) { - _localip = 0; - _submask = 0; - _gateway = 0; - } - if (m2m_wifi_default_connect() < 0) { - _status = WL_CONNECT_FAILED; - return _status; - } - _status = WL_IDLE_STATUS; - _mode = WL_STA_MODE; - - // Wait for connection or timeout: - unsigned long start = millis(); - while (!(_status & WL_CONNECTED) && - !(_status & WL_DISCONNECTED) && - millis() - start < 60000) { - m2m_wifi_handle_events(NULL); - } - - memset(_ssid, 0, M2M_MAX_SSID_LEN); - - if (!(_status & WL_CONNECTED)) { - _mode = WL_RESET_MODE; - } else { - m2m_wifi_get_connection_info(); - - m2m_wifi_handle_events(NULL); - } - - return _status; -} - -uint8_t WiFiClass::begin(const char *ssid) -{ - return startConnect(ssid, M2M_WIFI_SEC_OPEN, (void *)0); -} - -uint8_t WiFiClass::begin(const char *ssid, uint8_t key_idx, const char* key) -{ - tstrM2mWifiWepParams wep_params; - - memset(&wep_params, 0, sizeof(tstrM2mWifiWepParams)); - wep_params.u8KeyIndx = key_idx; - wep_params.u8KeySz = strlen(key); - strcpy((char *)&wep_params.au8WepKey[0], key); - return startConnect(ssid, M2M_WIFI_SEC_WEP, &wep_params); -} - -uint8_t WiFiClass::begin(const char *ssid, const char *key) -{ - return startConnect(ssid, M2M_WIFI_SEC_WPA_PSK, key); -} - -uint8_t WiFiClass::startConnect(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo) -{ - if (!_init) { - init(); - } - - // Connect to router: - if (_dhcp) { - _localip = 0; - _submask = 0; - _gateway = 0; - } - if (m2m_wifi_connect((char*)ssid, strlen(ssid), u8SecType, (void*)pvAuthInfo, M2M_WIFI_CH_ALL) < 0) { - _status = WL_CONNECT_FAILED; - return _status; - } - _status = WL_IDLE_STATUS; - _mode = WL_STA_MODE; - - // Wait for connection or timeout: - unsigned long start = millis(); - while (!(_status & WL_CONNECTED) && - !(_status & WL_DISCONNECTED) && - millis() - start < 60000) { - m2m_wifi_handle_events(NULL); - } - if (!(_status & WL_CONNECTED)) { - _mode = WL_RESET_MODE; - } - - memset(_ssid, 0, M2M_MAX_SSID_LEN); - memcpy(_ssid, ssid, strlen(ssid)); - return _status; -} - -uint8_t WiFiClass::beginAP(const char *ssid) -{ - return beginAP(ssid, 1); -} - -uint8_t WiFiClass::beginAP(const char *ssid, uint8_t channel) -{ - return startAP(ssid, M2M_WIFI_SEC_OPEN, NULL, channel); -} - -uint8_t WiFiClass::beginAP(const char *ssid, uint8_t key_idx, const char* key) -{ - return beginAP(ssid, key_idx, key, 1); -} - -uint8_t WiFiClass::beginAP(const char *ssid, uint8_t key_idx, const char* key, uint8_t channel) -{ - tstrM2mWifiWepParams wep_params; - - if (key_idx == 0) { - key_idx = 1; // 1 is the minimum key index - } - - memset(&wep_params, 0, sizeof(tstrM2mWifiWepParams)); - wep_params.u8KeyIndx = key_idx; - wep_params.u8KeySz = strlen(key); - strcpy((char *)&wep_params.au8WepKey[0], key); - - return startAP(ssid, M2M_WIFI_SEC_WEP, &wep_params, channel); -} - -uint8_t WiFiClass::beginAP(const char *ssid, const char* key) -{ - return beginAP(ssid, key, 1); -} - -uint8_t WiFiClass::beginAP(const char *ssid, const char* key, uint8_t channel) -{ - return startAP(ssid, M2M_WIFI_SEC_WPA_PSK, key, channel); -} - -uint8_t WiFiClass::startAP(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo, uint8_t channel) -{ - tstrM2MAPConfig strM2MAPConfig; - - if (!_init) { - init(); - } - - if (channel == 0) { - channel = 1; // channel 1 is the minium channel - } - - // Enter Access Point mode: - memset(&strM2MAPConfig, 0x00, sizeof(tstrM2MAPConfig)); - strcpy((char *)&strM2MAPConfig.au8SSID, ssid); - strM2MAPConfig.u8ListenChannel = channel; - strM2MAPConfig.u8SecType = u8SecType; - if (_localip == 0) { - strM2MAPConfig.au8DHCPServerIP[0] = 192; - strM2MAPConfig.au8DHCPServerIP[1] = 168; - strM2MAPConfig.au8DHCPServerIP[2] = 1; - strM2MAPConfig.au8DHCPServerIP[3] = 1; - } else { - memcpy(strM2MAPConfig.au8DHCPServerIP, &_localip, sizeof(_localip)); - if (strM2MAPConfig.au8DHCPServerIP[3] == 100) { - // limitation of WINC1500 firmware, IP address of client is always x.x.x.100 - _status = WL_AP_FAILED; - return _status; - } - } - - if (u8SecType == M2M_WIFI_SEC_WEP) { - tstrM2mWifiWepParams* wep_params = (tstrM2mWifiWepParams*)pvAuthInfo; - - strM2MAPConfig.u8KeyIndx = wep_params->u8KeyIndx; - strM2MAPConfig.u8KeySz = wep_params->u8KeySz; - strcpy((char*)strM2MAPConfig.au8WepKey, (char *)wep_params->au8WepKey); - } - - if (u8SecType == M2M_WIFI_SEC_WPA_PSK) { - strM2MAPConfig.u8KeySz = strlen((char*)pvAuthInfo); - strcpy((char*)strM2MAPConfig.au8Key, (char *)pvAuthInfo); - } - - if (m2m_wifi_enable_ap(&strM2MAPConfig) < 0) { - _status = WL_AP_FAILED; - return _status; - } - _status = WL_AP_LISTENING; - _mode = WL_AP_MODE; - - memset(_ssid, 0, M2M_MAX_SSID_LEN); - memcpy(_ssid, ssid, strlen(ssid)); - m2m_memcpy((uint8 *)&_localip, (uint8 *)&strM2MAPConfig.au8DHCPServerIP[0], 4); - _submask = 0x00FFFFFF; - _gateway = _localip; - - // WiFi led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0); - - return _status; -} - -uint8_t WiFiClass::beginProvision() -{ - return beginProvision(1); -} - -uint8_t WiFiClass::beginProvision(uint8_t channel) -{ - // try to connect using begin - if (begin() != WL_CONNECTED) { - // failed, enter provisioning mode - - uint8_t mac[6]; - char provSsid[13]; - - // get MAC address for provisioning SSID - macAddress(mac); - sprintf(provSsid, "wifi101-%.2X%2X", mac[1], mac[0]); - - // start provisioning mode - startProvision(provSsid, "wifi101", channel); - } - - return status(); -} - -uint8_t WiFiClass::startProvision(const char *ssid, const char *url, uint8_t channel) -{ - tstrM2MAPConfig strM2MAPConfig; - - if (!_init) { - init(); - } - - // Enter Provision mode: - memset(&strM2MAPConfig, 0x00, sizeof(tstrM2MAPConfig)); - strcpy((char *)&strM2MAPConfig.au8SSID, ssid); - strM2MAPConfig.u8ListenChannel = channel; - strM2MAPConfig.u8SecType = M2M_WIFI_SEC_OPEN; - strM2MAPConfig.u8SsidHide = SSID_MODE_VISIBLE; - strM2MAPConfig.au8DHCPServerIP[0] = 192; - strM2MAPConfig.au8DHCPServerIP[1] = 168; - strM2MAPConfig.au8DHCPServerIP[2] = 1; - strM2MAPConfig.au8DHCPServerIP[3] = 1; - - if (m2m_wifi_start_provision_mode((tstrM2MAPConfig *)&strM2MAPConfig, (char*)url, 1) < 0) { - _status = WL_PROVISIONING_FAILED; - return _status; - } - _status = WL_PROVISIONING; - _mode = WL_PROV_MODE; - - memset(_ssid, 0, M2M_MAX_SSID_LEN); - memcpy(_ssid, ssid, strlen(ssid)); - m2m_memcpy((uint8 *)&_localip, (uint8 *)&strM2MAPConfig.au8DHCPServerIP[0], 4); - _submask = 0x00FFFFFF; - _gateway = _localip; - - // WiFi led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0); - - return _status; -} - -uint32_t WiFiClass::provisioned() -{ - m2m_wifi_handle_events(NULL); - - if (_mode == WL_STA_MODE) { - return 1; - } - else { - return 0; - } -} - -void WiFiClass::config(IPAddress local_ip) -{ - config(local_ip, (uint32_t)0); -} - -void WiFiClass::config(IPAddress local_ip, IPAddress dns_server) -{ - config(local_ip, dns_server, (uint32_t)0); -} - -void WiFiClass::config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway) -{ - config(local_ip, dns_server, gateway, (uint32_t)0); -} - -void WiFiClass::config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet) -{ - tstrM2MIPConfig conf; - - if (!_init) { - init(); - } - - conf.u32DNS = (uint32_t)dns_server; - conf.u32Gateway = (uint32_t)gateway; - conf.u32StaticIP = (uint32_t)local_ip; - conf.u32SubnetMask = (uint32_t)subnet; - _dhcp = 0; - m2m_wifi_enable_dhcp(0); // disable DHCP - m2m_wifi_set_static_ip(&conf); - _localip = conf.u32StaticIP; - _submask = conf.u32SubnetMask; - _gateway = conf.u32Gateway; -} - -void WiFiClass::hostname(const char* name) -{ - if (!_init) { - init(); - } - - m2m_wifi_set_device_name((uint8 *)name, strlen(name)); -} - -void WiFiClass::disconnect() -{ - m2m_wifi_disconnect(); - - // WiFi led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); -} - -void WiFiClass::end() -{ - if (_mode == WL_AP_MODE) { - m2m_wifi_disable_ap(); - } else { - if (_mode == WL_PROV_MODE) { - m2m_wifi_stop_provision_mode(); - } - - m2m_wifi_disconnect(); - } - - // WiFi led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); - - socketDeinit(); - - m2m_wifi_deinit(NULL); - - nm_bsp_deinit(); - - _mode = WL_RESET_MODE; - _status = WL_NO_SHIELD; - _init = 0; -} - -uint8_t *WiFiClass::macAddress(uint8_t *mac) -{ - m2m_wifi_get_mac_address(mac); - byte tmpMac[6], i; - - m2m_wifi_get_mac_address(tmpMac); - - for(i = 0; i < 6; i++) - mac[i] = tmpMac[5-i]; - - return mac; -} - -uint32_t WiFiClass::localIP() -{ - return _localip; -} - -uint32_t WiFiClass::subnetMask() -{ - return _submask; -} - -uint32_t WiFiClass::gatewayIP() -{ - return _gateway; -} - -char* WiFiClass::SSID() -{ - if (_status == WL_CONNECTED || _status == WL_AP_LISTENING || _status == WL_AP_CONNECTED) { - return _ssid; - } - else { - return 0; - } -} - -uint8_t* WiFiClass::BSSID(uint8_t* bssid) -{ - if (_mode == WL_AP_MODE) { - return macAddress(bssid); - } else { - return remoteMacAddress(bssid); - } -} - -uint8_t* WiFiClass::APClientMacAddress(uint8_t* mac) -{ - if (_mode == WL_AP_MODE) { - return remoteMacAddress(mac); - } else { - memset(mac, 0, 6); - return mac; - } -} - -uint8_t* WiFiClass::remoteMacAddress(uint8_t* remoteMacAddress) -{ - _remoteMacAddress = remoteMacAddress; - memset(remoteMacAddress, 0, 6); - - m2m_wifi_get_connection_info(); - - // Wait for connection or timeout: - unsigned long start = millis(); - while (_remoteMacAddress != 0 && millis() - start < 1000) { - m2m_wifi_handle_events(NULL); - } - - _remoteMacAddress = 0; - return remoteMacAddress; -} - -int32_t WiFiClass::RSSI() -{ - // Clear pending events: - m2m_wifi_handle_events(NULL); - - // Send RSSI request: - _resolve = 0; - if (m2m_wifi_req_curr_rssi() < 0) { - return 0; - } - - // Wait for connection or timeout: - unsigned long start = millis(); - while (_resolve == 0 && millis() - start < 1000) { - m2m_wifi_handle_events(NULL); - } - - int32_t rssi = _resolve; - - _resolve = 0; - - return rssi; -} - -int8_t WiFiClass::scanNetworks() -{ - wl_status_t tmp = _status; - - if (!_init) { - init(); - } - - // Start scan: - if (m2m_wifi_request_scan(M2M_WIFI_CH_ALL) < 0) { - return 0; - } - - // Wait for scan result or timeout: - _status = WL_IDLE_STATUS; - unsigned long start = millis(); - while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 5000) { - m2m_wifi_handle_events(NULL); - } - _status = tmp; - return m2m_wifi_get_num_ap_found(); -} - -char* WiFiClass::SSID(uint8_t pos) -{ - wl_status_t tmp = _status; - - // Get scan SSID result: - memset(_scan_ssid, 0, M2M_MAX_SSID_LEN); - if (m2m_wifi_req_scan_result(pos) < 0) { - return 0; - } - - // Wait for connection or timeout: - _status = WL_IDLE_STATUS; - unsigned long start = millis(); - while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - - _status = tmp; - _resolve = 0; - - return _scan_ssid; -} - -int32_t WiFiClass::RSSI(uint8_t pos) -{ - wl_status_t tmp = _status; - - // Get scan RSSI result: - if (m2m_wifi_req_scan_result(pos) < 0) { - return 0; - } - - // Wait for connection or timeout: - _status = WL_IDLE_STATUS; - unsigned long start = millis(); - while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - - _status = tmp; - - int32_t rssi = _resolve; - - _resolve = 0; - - return rssi; -} - -uint8_t WiFiClass::encryptionType() -{ - int8_t net = scanNetworks(); - - for (uint8_t i = 0; i < net; ++i) { - SSID(i); - if (strcmp(_scan_ssid, _ssid) == 0) { - break; - } - } - - return _scan_auth; -} - -uint8_t WiFiClass::encryptionType(uint8_t pos) -{ - wl_status_t tmp = _status; - - // Get scan auth result: - if (m2m_wifi_req_scan_result(pos) < 0) { - return 0; - } - - // Wait for connection or timeout: - _status = WL_IDLE_STATUS; - unsigned long start = millis(); - while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - - _status = tmp; - _resolve = 0; - - return _scan_auth; -} - -uint8_t* WiFiClass::BSSID(uint8_t pos, uint8_t* bssid) -{ - wl_status_t tmp = _status; - - _remoteMacAddress = bssid; - - // Get scan auth result: - if (m2m_wifi_req_scan_result(pos) < 0) { - return 0; - } - - // Wait for connection or timeout: - _status = WL_IDLE_STATUS; - unsigned long start = millis(); - while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - - _status = tmp; - _resolve = 0; - _remoteMacAddress = 0; - - return bssid; -} - -uint8_t WiFiClass::channel(uint8_t pos) -{ - wl_status_t tmp = _status; - - // Get scan auth result: - if (m2m_wifi_req_scan_result(pos) < 0) { - return 0; - } - - // Wait for connection or timeout: - _status = WL_IDLE_STATUS; - unsigned long start = millis(); - while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - - _status = tmp; - _resolve = 0; - - return _scan_channel; -} - -uint8_t WiFiClass::status() -{ - if (!_init) { - init(); - } - - m2m_wifi_handle_events(NULL); - - return _status; -} - -int WiFiClass::hostByName(const char* aHostname, IPAddress& aResult) -{ - - // check if aHostname is already an ipaddress - if (aResult.fromString(aHostname)) { - // if fromString returns true we have an IP address ready - return 1; - - } else { - // Network led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); - - // Send DNS request: - _resolve = 0; - if (gethostbyname((uint8 *)aHostname) < 0) { - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - return 0; - } - - // Wait for connection or timeout: - unsigned long start = millis(); - while (_resolve == 0 && millis() - start < 20000) { - m2m_wifi_handle_events(NULL); - } - - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - - if (_resolve == 0) { - return 0; - } - - aResult = _resolve; - _resolve = 0; - return 1; - } -} - -void WiFiClass::refresh(void) -{ - // Update state machine: - m2m_wifi_handle_events(NULL); -} - -void WiFiClass::lowPowerMode(void) -{ - m2m_wifi_set_sleep_mode(M2M_PS_H_AUTOMATIC, true); -} - -void WiFiClass::maxLowPowerMode(void) -{ - m2m_wifi_set_sleep_mode(M2M_PS_DEEP_AUTOMATIC, true); -} - -void WiFiClass::noLowPowerMode(void) -{ - m2m_wifi_set_sleep_mode(M2M_NO_PS, false); -} - -int WiFiClass::ping(const char* hostname, uint8_t ttl) -{ - IPAddress ip; - - if (hostByName(hostname, ip) > 0) { - return ping(ip, ttl); - } else { - return WL_PING_UNKNOWN_HOST; - } -} - -int WiFiClass::ping(const String &hostname, uint8_t ttl) -{ - return ping(hostname.c_str(), ttl); -} - -int WiFiClass::ping(IPAddress host, uint8_t ttl) -{ - // Network led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); - - uint32_t dstHost = (uint32_t)host; - _resolve = dstHost; - - if (m2m_ping_req((uint32_t)host, ttl, &ping_cb) < 0) { - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - // Error sending ping request - return WL_PING_ERROR; - } - - // Wait for success or timeout: - unsigned long start = millis(); - while (_resolve == dstHost && millis() - start < 5000) { - m2m_wifi_handle_events(NULL); - } - - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - - if (_resolve == dstHost) { - _resolve = 0; - return WL_PING_TIMEOUT; - } else { - int rtt = (int)_resolve; - _resolve = 0; - return rtt; - } -} - -uint32_t WiFiClass::getTime() -{ -#ifdef WIFI_101_NO_TIME_H - #warning "No system header included, WiFi.getTime() will always return 0" - return 0; -#else - tstrSystemTime systemTime; - - _resolve = (uint32_t)&systemTime; - - m2m_wifi_get_sytem_time(); - - unsigned long start = millis(); - while (_resolve != 0 && millis() - start < 5000) { - m2m_wifi_handle_events(NULL); - } - - time_t t = 0; - - if (_resolve == 0 && systemTime.u16Year > 0) { - struct tm tm; - - tm.tm_year = systemTime.u16Year - 1900; - tm.tm_mon = systemTime.u8Month - 1; - tm.tm_mday = systemTime.u8Day; - tm.tm_hour = systemTime.u8Hour; - tm.tm_min = systemTime.u8Minute; - tm.tm_sec = systemTime.u8Second; - tm.tm_isdst = -1; - - t = mktime(&tm); - } - - _resolve = 0; - - return t; -#endif -} - -WiFiClass WiFi; diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFi101.h b/feather_sensor_lte/libraries/WiFi101/src/WiFi101.h deleted file mode 100644 index 6e46fab..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/WiFi101.h +++ /dev/null @@ -1,193 +0,0 @@ -/* - WiFi.h - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef WIFI_H -#define WIFI_H - -#define WIFI_FIRMWARE_LATEST_MODEL_A "19.4.4" -#define WIFI_FIRMWARE_LATEST_MODEL_B "19.5.2" - -// for backwards compatibility -#define WIFI_FIRMWARE_REQUIRED WIFI_FIRMWARE_LATEST_MODEL_B - -#include - -extern "C" { - #include "driver/include/m2m_wifi.h" - #include "socket/include/socket.h" -} - -#include "WiFiClient.h" -#include "WiFiSSLClient.h" -#include "WiFiServer.h" - -typedef enum { - WL_NO_SHIELD = 255, - WL_IDLE_STATUS = 0, - WL_NO_SSID_AVAIL, - WL_SCAN_COMPLETED, - WL_CONNECTED, - WL_CONNECT_FAILED, - WL_CONNECTION_LOST, - WL_DISCONNECTED, - WL_AP_LISTENING, - WL_AP_CONNECTED, - WL_AP_FAILED, - WL_PROVISIONING, - WL_PROVISIONING_FAILED -} wl_status_t; - -/* Encryption modes */ -enum wl_enc_type { /* Values map to 802.11 encryption suites... */ - ENC_TYPE_WEP = M2M_WIFI_SEC_WEP, - ENC_TYPE_TKIP = M2M_WIFI_SEC_WPA_PSK, - ENC_TYPE_CCMP = M2M_WIFI_SEC_802_1X, - /* ... except these two, 7 and 8 are reserved in 802.11-2007 */ - ENC_TYPE_NONE = M2M_WIFI_SEC_OPEN, - ENC_TYPE_AUTO = M2M_WIFI_SEC_INVALID -}; - -typedef enum { - WL_RESET_MODE = 0, - WL_STA_MODE, - WL_PROV_MODE, - WL_AP_MODE -} wl_mode_t; - -typedef enum { - WL_PING_DEST_UNREACHABLE = -1, - WL_PING_TIMEOUT = -2, - WL_PING_UNKNOWN_HOST = -3, - WL_PING_ERROR = -4 -} wl_ping_result_t; - -class WiFiClass -{ -public: - uint32_t _localip; - uint32_t _submask; - uint32_t _gateway; - int _dhcp; - uint32_t _resolve; - byte *_remoteMacAddress; - wl_mode_t _mode; - wl_status_t _status; - char _scan_ssid[M2M_MAX_SSID_LEN]; - uint8_t _scan_auth; - uint8_t _scan_channel; - char _ssid[M2M_MAX_SSID_LEN]; - WiFiClient *_client[TCP_SOCK_MAX]; - - WiFiClass(); - - void setPins(int8_t cs, int8_t irq, int8_t rst, int8_t en = -1); - - int init(); - - char* firmwareVersion(); - - /* Start Wifi connection with WPA/WPA2 encryption. - * - * param ssid: Pointer to the SSID string. - * param key: Key input buffer. - */ - uint8_t begin(); - uint8_t begin(const char *ssid); - uint8_t begin(const char *ssid, uint8_t key_idx, const char* key); - uint8_t begin(const char *ssid, const char *key); - uint8_t begin(const String &ssid) { return begin(ssid.c_str()); } - uint8_t begin(const String &ssid, uint8_t key_idx, const String &key) { return begin(ssid.c_str(), key_idx, key.c_str()); } - uint8_t begin(const String &ssid, const String &key) { return begin(ssid.c_str(), key.c_str()); } - - /* Start Wifi in Access Point, with open security. - * Only one client can connect to the AP at a time. - * - * param ssid: Pointer to the SSID string. - * param channel: Wifi channel to use. Valid values are 1-12. - */ - uint8_t beginAP(const char *ssid); - uint8_t beginAP(const char *ssid, uint8_t channel); - uint8_t beginAP(const char *ssid, uint8_t key_idx, const char* key); - uint8_t beginAP(const char *ssid, uint8_t key_idx, const char* key, uint8_t channel); - uint8_t beginAP(const char *ssid, const char* key); - uint8_t beginAP(const char *ssid, const char* key, uint8_t channel); - - uint8_t beginProvision(); - uint8_t beginProvision(uint8_t channel); - - uint32_t provisioned(); - - void config(IPAddress local_ip); - void config(IPAddress local_ip, IPAddress dns_server); - void config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway); - void config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet); - - void hostname(const char* name); - - void disconnect(); - void end(); - - uint8_t *macAddress(uint8_t *mac); - - uint32_t localIP(); - uint32_t subnetMask(); - uint32_t gatewayIP(); - char* SSID(); - int32_t RSSI(); - uint8_t encryptionType(); - uint8_t* BSSID(uint8_t* bssid); - uint8_t* APClientMacAddress(uint8_t* mac); - int8_t scanNetworks(); - char* SSID(uint8_t pos); - int32_t RSSI(uint8_t pos); - uint8_t encryptionType(uint8_t pos); - uint8_t* BSSID(uint8_t pos, uint8_t* bssid); - uint8_t channel(uint8_t pos); - - uint8_t status(); - - int hostByName(const char* hostname, IPAddress& result); - int hostByName(const String &hostname, IPAddress& result) { return hostByName(hostname.c_str(), result); } - - int ping(const char* hostname, uint8_t ttl = 128); - int ping(const String &hostname, uint8_t ttl = 128); - int ping(IPAddress host, uint8_t ttl = 128); - - unsigned long getTime(); - - void refresh(void); - - void lowPowerMode(void); - void maxLowPowerMode(void); - void noLowPowerMode(void); - -private: - int _init; - char _version[9]; - - uint8_t startConnect(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo); - uint8_t startAP(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo, uint8_t channel); - uint8_t* remoteMacAddress(uint8_t* remoteMacAddress); - - uint8_t startProvision(const char *ssid, const char *url, uint8_t channel); -}; - -extern WiFiClass WiFi; - -#endif /* WIFI_H */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiClient.cpp b/feather_sensor_lte/libraries/WiFi101/src/WiFiClient.cpp deleted file mode 100644 index 8298618..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/WiFiClient.cpp +++ /dev/null @@ -1,308 +0,0 @@ -/* - WiFiClient.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -extern "C" { - #include "socket/include/socket.h" - #include "driver/include/m2m_periph.h" -} - -#include "WiFi101.h" -#include "WiFiClient.h" - -#define IS_CONNECTED (_flag & SOCKET_BUFFER_FLAG_CONNECTED) - -WiFiClient::WiFiClient() -{ - _socket = -1; - _flag = 0; - _head = 0; - _tail = 0; -} - -WiFiClient::WiFiClient(uint8_t sock, uint8_t parentsock) -{ - // Spawn connected TCP client from TCP server socket: - _socket = sock; - _flag = SOCKET_BUFFER_FLAG_CONNECTED; - if (parentsock) { - _flag |= ((uint32_t)parentsock) << SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS; - } - _head = 0; - _tail = 0; - for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { - if (WiFi._client[sock] == this) - WiFi._client[sock] = 0; - } - WiFi._client[_socket] = this; - - // Add socket buffer handler: - socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_buffer); - - // Enable receive buffer: - recv(_socket, _buffer, SOCKET_BUFFER_MTU, 0); - - m2m_wifi_handle_events(NULL); -} - -WiFiClient::WiFiClient(const WiFiClient& other) -{ - copyFrom(other); -} - -void WiFiClient::copyFrom(const WiFiClient& other) -{ - _socket = other._socket; - _flag = other._flag; - _head = other._head; - _tail = other._tail; - if (_head > _tail) { - memcpy(_buffer + _tail, other._buffer + _tail, (_head - _tail)); - } - - for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { - if (WiFi._client[sock] == this) - WiFi._client[sock] = 0; - } - - if (_socket > -1) { - WiFi._client[_socket] = this; - - // Add socket buffer handler: - socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_buffer); - - // Enable receive buffer: - recv(_socket, _buffer, SOCKET_BUFFER_MTU, 0); - } - - m2m_wifi_handle_events(NULL); -} - -int WiFiClient::connectSSL(const char* host, uint16_t port) -{ - return connect(host, port, SOCKET_FLAGS_SSL); -} - -int WiFiClient::connectSSL(IPAddress ip, uint16_t port) -{ - return connect(ip, port, SOCKET_FLAGS_SSL, 0); -} - -int WiFiClient::connect(const char* host, uint16_t port) -{ - return connect(host, port, 0); -} - -int WiFiClient::connect(IPAddress ip, uint16_t port) -{ - return connect(ip, port, 0, 0); -} - -int WiFiClient::connect(const char* host, uint16_t port, uint8_t opt) -{ - IPAddress remote_addr; - if (WiFi.hostByName(host, remote_addr)) { - return connect(remote_addr, port, opt, (const uint8_t *)host); - } - return 0; -} - -int WiFiClient::connect(IPAddress ip, uint16_t port, uint8_t opt, const uint8_t *hostname) -{ - struct sockaddr_in addr; - - // Initialize socket address structure: - addr.sin_family = AF_INET; - addr.sin_port = _htons(port); - addr.sin_addr.s_addr = ip; - - // Create TCP socket: - _flag = 0; - _head = 0; - _tail = 0; - if ((_socket = socket(AF_INET, SOCK_STREAM, opt)) < 0) { - return 0; - } - - if (opt & SOCKET_FLAGS_SSL && hostname) { - setsockopt(_socket, SOL_SSL_SOCKET, SO_SSL_SNI, hostname, m2m_strlen((uint8_t *)hostname)); - } - - // Add socket buffer handler: - socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_buffer); - - // Connect to remote host: - if (connectSocket(_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { - close(_socket); - _socket = -1; - return 0; - } - - // Wait for connection or timeout: - unsigned long start = millis(); - while (!IS_CONNECTED && millis() - start < 20000) { - m2m_wifi_handle_events(NULL); - } - if (!IS_CONNECTED) { - close(_socket); - _socket = -1; - return 0; - } - - WiFi._client[_socket] = this; - - return 1; -} - -size_t WiFiClient::write(uint8_t b) -{ - return write(&b, 1); -} - -size_t WiFiClient::write(const uint8_t *buf, size_t size) -{ - sint16 err; - - if (_socket < 0 || size == 0 || !IS_CONNECTED) { - setWriteError(); - return 0; - } - - // Network led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); - - m2m_wifi_handle_events(NULL); - - while ((err = send(_socket, (void *)buf, size, 0)) < 0) { - // Exit on fatal error, retry if buffer not ready. - if (err != SOCK_ERR_BUFFER_FULL) { - setWriteError(); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - return 0; - } - m2m_wifi_handle_events(NULL); - } - - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - - return size; -} - -int WiFiClient::available() -{ - m2m_wifi_handle_events(NULL); - - if (_socket != -1) { - return _head - _tail; - } - return 0; -} - -int WiFiClient::read() -{ - uint8_t b; - - if (read(&b, sizeof(b)) == -1) { - return -1; - } - - return b; -} - -int WiFiClient::read(uint8_t* buf, size_t size) -{ - // sizeof(size_t) is architecture dependent - // but we need a 16 bit data type here - uint16_t size_tmp = available(); - - if (size_tmp == 0) { - return -1; - } - - if (size < size_tmp) { - size_tmp = size; - } - - for (uint32_t i = 0; i < size_tmp; ++i) { - buf[i] = _buffer[_tail++]; - } - - if (_tail == _head) { - _tail = _head = 0; - _flag &= ~SOCKET_BUFFER_FLAG_FULL; - recv(_socket, _buffer, SOCKET_BUFFER_MTU, 0); - m2m_wifi_handle_events(NULL); - } - - return size_tmp; -} - -int WiFiClient::peek() -{ - if (!available()) - return -1; - - return _buffer[_tail]; -} - -void WiFiClient::flush() -{ - while (available()) - read(); -} - -void WiFiClient::stop() -{ - if (_socket < 0) - return; - - socketBufferUnregister(_socket); - close(_socket); - _socket = -1; - _flag = 0; -} - -uint8_t WiFiClient::connected() -{ - m2m_wifi_handle_events(NULL); - if (available()) - return 1; - return IS_CONNECTED; -} - -uint8_t WiFiClient::status() -{ - // Deprecated. - return 0; -} - -WiFiClient::operator bool() -{ - return _socket != -1; -} - -WiFiClient& WiFiClient::operator =(const WiFiClient& other) -{ - copyFrom(other); - - return *this; -} diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiClient.h b/feather_sensor_lte/libraries/WiFi101/src/WiFiClient.h deleted file mode 100644 index bef171d..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/WiFiClient.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - WiFiClient.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef WIFICLIENT_H -#define WIFICLIENT_H - -#include -#include -#include -#include "socket/include/socket_buffer.h" - -class WiFiClient : public Client { - -public: - WiFiClient(); - WiFiClient(uint8_t sock, uint8_t parentsock = 0); - WiFiClient(const WiFiClient& other); - - uint8_t status(); - - int connectSSL(IPAddress ip, uint16_t port); - int connectSSL(const char* host, uint16_t port); - virtual int connect(IPAddress ip, uint16_t port); - virtual int connect(const char* host, uint16_t port); - virtual size_t write(uint8_t); - virtual size_t write(const uint8_t *buf, size_t size); - virtual int available(); - virtual int read(); - virtual int read(uint8_t *buf, size_t size); - virtual int peek(); - virtual void flush(); - virtual void stop(); - virtual uint8_t connected(); - virtual operator bool(); - virtual WiFiClient& operator =(const WiFiClient& other); - - using Print::write; - - uint32_t _flag; - -private: - SOCKET _socket; - uint32_t _head; - uint32_t _tail; - uint8_t _buffer[SOCKET_BUFFER_TCP_SIZE]; - int connect(const char* host, uint16_t port, uint8_t opt); - int connect(IPAddress ip, uint16_t port, uint8_t opt, const uint8_t *hostname); - void copyFrom(const WiFiClient& other); - -}; - -#endif /* WIFICLIENT_H */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiMDNSResponder.cpp b/feather_sensor_lte/libraries/WiFi101/src/WiFiMDNSResponder.cpp deleted file mode 100644 index a192113..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/WiFiMDNSResponder.cpp +++ /dev/null @@ -1,220 +0,0 @@ -// Port of CC3000 MDNS Responder to WINC1500. -// Author: Tony DiCola -// -// This MDNSResponder class implements just enough MDNS functionality to respond -// to name requests, for example 'foo.local'. This does not implement any other -// MDNS or Bonjour functionality like services, etc. -// -// Copyright (c) 2016 Adafruit Industries. All right reserved. -// -// 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 2.1 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 Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -#include -#ifndef ARDUINO_ARCH_AVR -#include -#endif - -#include "Arduino.h" -#include "WiFiMDNSResponder.h" - -// Important RFC's for reference: -// - DNS request and response: http://www.ietf.org/rfc/rfc1035.txt -// - Multicast DNS: http://www.ietf.org/rfc/rfc6762.txt - -#define HEADER_SIZE 12 -#define TTL_OFFSET 4 -#define IP_OFFSET 10 - -const uint8_t expectedRequestHeader[HEADER_SIZE] PROGMEM = { - 0x00, 0x00, - 0x00, 0x00, - 0x00, 0x01, // questions (these 2 bytes are ignored) - 0x00, 0x00, - 0x00, 0x00, - 0x00, 0x00 -}; - -const uint8_t responseHeader[] PROGMEM = { - 0x00, 0x00, // ID = 0 - 0x84, 0x00, // Flags = response + authoritative answer - 0x00, 0x00, // Question count = 0 - 0x00, 0x01, // Answer count = 1 - 0x00, 0x00, // Name server records = 0 - 0x00, 0x01 // Additional records = 1 -}; - -// Generate positive response for IPV4 address -const uint8_t aRecord[] PROGMEM = { - 0x00, 0x01, // Type = 1, A record/IPV4 address - 0x80, 0x01, // Class = Internet, with cache flush bit - 0x00, 0x00, 0x00, 0x00, // TTL in seconds, to be filled in later - 0x00, 0x04, // Length of record - 0x00, 0x00, 0x00, 0x00 // IP address, to be filled in later -}; - -// Generate negative response for IPV6 address (CC3000 doesn't support IPV6) -const uint8_t nsecRecord[] PROGMEM = { - 0xC0, 0x0C, // Name offset - 0x00, 0x2F, // Type = 47, NSEC (overloaded by MDNS) - 0x80, 0x01, // Class = Internet, with cache flush bit - 0x00, 0x00, 0x00, 0x00, // TTL in seconds, to be filled in later - 0x00, 0x08, // Length of record - 0xC0, 0x0C, // Next domain = offset to FQDN - 0x00, // Block number = 0 - 0x04, // Length of bitmap = 4 bytes - 0x40, 0x00, 0x00, 0x00 // Bitmap value = Only first bit (A record/IPV4) is set -}; - -const uint8_t domain[] PROGMEM = { 'l', 'o', 'c', 'a', 'l' }; - -WiFiMDNSResponder::WiFiMDNSResponder() : - minimumExpectedRequestLength(0) -{ -} - -WiFiMDNSResponder::~WiFiMDNSResponder() -{ -} - -bool WiFiMDNSResponder::begin(const char* _name, uint32_t _ttlSeconds) -{ - int nameLength = strlen(_name); - - if (nameLength > 255) { - // Can only handle domains that are upto 255 chars in length. - minimumExpectedRequestLength = 0; - return false; - } - - name = _name; - ttlSeconds = _ttlSeconds; - - name.toLowerCase(); - minimumExpectedRequestLength = HEADER_SIZE + 1 + nameLength + 1 + sizeof(domain) + 5; - - // Open the MDNS UDP listening socket on port 5353 with multicast address - // 224.0.0.251 (0xE00000FB) - if (!udpSocket.beginMulticast(IPAddress(224, 0, 0, 251), 5353)) { - return false; - } - - return true; -} - -void WiFiMDNSResponder::poll() -{ - if (parseRequest()) { - replyToRequest(); - } -} - -bool WiFiMDNSResponder::parseRequest() -{ - int packetLength = udpSocket.parsePacket(); - - if (packetLength) { - // check if parsed packet matches expected request length - if (packetLength < minimumExpectedRequestLength) { - // it does not, read the full packet in and drop data - while(udpSocket.available()) { - udpSocket.read(); - } - - return false; - } - - // read up to the min expect request length - uint8_t request[minimumExpectedRequestLength]; - udpSocket.read(request, minimumExpectedRequestLength); - - // discard the rest - while(udpSocket.available()) { - udpSocket.read(); - } - - // parse request - uint8_t requestNameLength = request[HEADER_SIZE]; - uint8_t* requestName = &request[HEADER_SIZE + 1]; - uint8_t requestDomainLength = request[HEADER_SIZE + 1 + requestNameLength]; - uint8_t* requestDomain = &request[HEADER_SIZE + 1 + requestNameLength + 1]; - uint16_t requestQtype; - uint16_t requestQclass; - - memcpy(&requestQtype, &request[minimumExpectedRequestLength - 4], sizeof(requestQtype)); - memcpy(&requestQclass, &request[minimumExpectedRequestLength - 2], sizeof(requestQclass)); - - requestQtype = _ntohs(requestQtype); - requestQclass = _ntohs(requestQclass); - - // compare request - if (memcmp_P(request, expectedRequestHeader, 4) == 0 && // request header start match - memcmp_P(&request[6], &expectedRequestHeader[6], 6) == 0 && // request header end match - requestNameLength == name.length() && // name length match - strncasecmp(name.c_str(), (char*)requestName, requestNameLength) == 0 && // name match - requestDomainLength == sizeof(domain) && // domain length match - memcmp_P(requestDomain, domain, requestDomainLength) == 0 && // suffix match - requestQtype == 0x0001 && // request QType match - requestQclass == 0x0001) { // request QClass match - - return true; - } - } - - return false; -} - -void WiFiMDNSResponder::replyToRequest() -{ - int nameLength = name.length(); - int domainLength = sizeof(domain); - uint32_t ipAddress = WiFi.localIP(); - uint32_t ttl = _htonl(ttlSeconds); - - int responseSize = sizeof(responseHeader) + 1 + nameLength + 1 + domainLength + 1 + sizeof(aRecord) + sizeof(nsecRecord); - uint8_t response[responseSize]; - uint8_t* r = response; - - // copy header - memcpy_P(r, responseHeader, sizeof(responseHeader)); - r += sizeof(responseHeader); - - // copy name - *r = nameLength; - memcpy(r + 1, name.c_str(), nameLength); - r += (1 + nameLength); - - // copy domain - *r = domainLength; - memcpy_P(r + 1, domain, domainLength); - r += (1 + domainLength); - - // terminator - *r = 0x00; - r++; - - // copy A record - memcpy_P(r, aRecord, sizeof(aRecord)); - memcpy(r + TTL_OFFSET, &ttl, sizeof(ttl)); // replace TTL value - memcpy(r + IP_OFFSET, &ipAddress, sizeof(ipAddress)); // replace IP address value - r += sizeof(aRecord); - - // copy NSEC record - memcpy_P(r, nsecRecord, sizeof(nsecRecord)); - r += sizeof(nsecRecord); - - udpSocket.beginPacket(IPAddress(224, 0, 0, 251), 5353); - udpSocket.write(response, responseSize); - udpSocket.endPacket(); -} diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiMDNSResponder.h b/feather_sensor_lte/libraries/WiFi101/src/WiFiMDNSResponder.h deleted file mode 100644 index d7e3d43..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/WiFiMDNSResponder.h +++ /dev/null @@ -1,51 +0,0 @@ -// Port of CC3000 MDNS Responder to WINC1500. -// Author: Tony DiCola -// -// This MDNSResponder class implements just enough MDNS functionality to respond -// to name requests, for example 'foo.local'. This does not implement any other -// MDNS or Bonjour functionality like services, etc. -// -// Copyright (c) 2016 Adafruit Industries. All right reserved. -// -// 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 2.1 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 Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -#ifndef WIFIMDNSRESPONDER_H -#define WIFIMDNSRESPONDER_H - -#include "WiFi101.h" -#include "WiFiUdp.h" - -class WiFiMDNSResponder { -public: - WiFiMDNSResponder(); - ~WiFiMDNSResponder(); - bool begin(const char* _name, uint32_t _ttlSeconds = 3600); - void poll(); - -private: - bool parseRequest(); - void replyToRequest(); - -private: - String name; - uint32_t ttlSeconds; - - int minimumExpectedRequestLength; - - // UDP socket for receiving/sending MDNS data. - WiFiUDP udpSocket; -}; - -#endif diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiSSLClient.cpp b/feather_sensor_lte/libraries/WiFi101/src/WiFiSSLClient.cpp deleted file mode 100644 index e7be43c..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/WiFiSSLClient.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/* - WiFiSSLClient.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "WiFiSSLClient.h" - -WiFiSSLClient::WiFiSSLClient() : - WiFiClient() -{ -} - -WiFiSSLClient::WiFiSSLClient(uint8_t sock, uint8_t parentsock) : - WiFiClient(sock, parentsock) -{ -} - -WiFiSSLClient::WiFiSSLClient(const WiFiSSLClient& other) : - WiFiClient(other) -{ -} - -int WiFiSSLClient::connect(IPAddress ip, uint16_t port) -{ - return WiFiClient::connectSSL(ip, port); -} - -int WiFiSSLClient::connect(const char* host, uint16_t port) -{ - return WiFiClient::connectSSL(host, port); -} diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiSSLClient.h b/feather_sensor_lte/libraries/WiFi101/src/WiFiSSLClient.h deleted file mode 100644 index c5851e5..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/WiFiSSLClient.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - WiFiSSLClient.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef WIFISSLCLIENT_H -#define WIFISSLCLIENT_H - -#include "WiFiClient.h" - -class WiFiSSLClient : public WiFiClient { - -public: - WiFiSSLClient(); - WiFiSSLClient(uint8_t sock, uint8_t parentsock = 0); - WiFiSSLClient(const WiFiSSLClient& other); - - virtual int connect(IPAddress ip, uint16_t port); - virtual int connect(const char* host, uint16_t port); -}; - -#endif /* WIFISSLCLIENT_H */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiServer.cpp b/feather_sensor_lte/libraries/WiFi101/src/WiFiServer.cpp deleted file mode 100644 index 5f330ba..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/WiFiServer.cpp +++ /dev/null @@ -1,140 +0,0 @@ -/* - WiFiClient.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -extern "C" { - #include "socket/include/socket.h" -} - -#include "WiFi101.h" -#include "WiFiClient.h" -#include "WiFiServer.h" - -#define READY (_flag & SOCKET_BUFFER_FLAG_BIND) - -WiFiServer::WiFiServer(uint16_t port) -{ - _port = port; - _flag = 0; -} - -void WiFiServer::begin() -{ - begin(0); -} - -uint8_t WiFiServer::beginSSL() -{ - return begin(SOCKET_FLAGS_SSL); -} - -uint8_t WiFiServer::begin(uint8_t opt) -{ - struct sockaddr_in addr; - - _flag = 0; - - // Initialize socket address structure. - addr.sin_family = AF_INET; - addr.sin_port = _htons(_port); - addr.sin_addr.s_addr = 0; - - // Open TCP server socket. - if ((_socket = socket(AF_INET, SOCK_STREAM, opt)) < 0) { - return 0; - } - - // Add socket buffer handler: - socketBufferRegister(_socket, &_flag, 0, 0, 0); - - // Bind socket: - if (bind(_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { - close(_socket); - _socket = -1; - return 0; - } - - // Wait for connection or timeout: - unsigned long start = millis(); - while (!READY && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - if (!READY) { - close(_socket); - _socket = -1; - return 0; - } - _flag &= ~SOCKET_BUFFER_FLAG_BIND; - - return 1; -} - -WiFiClient WiFiServer::available(uint8_t* status) -{ - uint32_t flag; - - m2m_wifi_handle_events(NULL); - if (_flag & SOCKET_BUFFER_FLAG_SPAWN) { - flag = _flag; - _flag &= ~SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK; - _flag &= ~SOCKET_BUFFER_FLAG_SPAWN; - if (status != NULL) { - *status = 0; - } - return WiFiClient(((flag & SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK) >> SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS), _socket + 1); - } else { - WiFiClient *client; - - for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { - client = WiFi._client[sock]; - if (client && client->_flag & SOCKET_BUFFER_FLAG_CONNECTED) { - if (((client->_flag >> SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS) & 0xff) == (uint8)(_socket + 1)) { - return *client; - } - } - } - } - - return WiFiClient(); -} - -uint8_t WiFiServer::status() { - // Deprecated. - return 0; -} - -size_t WiFiServer::write(uint8_t b) -{ - return write(&b, 1); -} - -size_t WiFiServer::write(const uint8_t *buffer, size_t size) -{ - size_t n = 0; - WiFiClient *client; - - for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { - client = WiFi._client[sock]; - if (client && client->_flag & SOCKET_BUFFER_FLAG_CONNECTED) { - if (((client->_flag >> SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS) & 0xff) == (uint8)(_socket + 1)) { - n += client->write(buffer, size); - } - } - } - return n; -} diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiServer.h b/feather_sensor_lte/libraries/WiFi101/src/WiFiServer.h deleted file mode 100644 index d658b2f..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/WiFiServer.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - WiFiClient.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef WIFISERVER_H -#define WIFISERVER_H - -#include -#include - -class WiFiClient; - -class WiFiServer : public Server { - -private: - SOCKET _socket; - uint32_t _flag; - uint16_t _port; - uint8_t begin(uint8_t opt); - -public: - WiFiServer(uint16_t); - WiFiClient available(uint8_t* status = NULL); - void begin(); - uint8_t beginSSL(); - virtual size_t write(uint8_t); - virtual size_t write(const uint8_t *buf, size_t size); - uint8_t status(); - - using Print::write; - -}; - -#endif /* WIFISERVER_H */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiUdp.cpp b/feather_sensor_lte/libraries/WiFi101/src/WiFiUdp.cpp deleted file mode 100644 index e55c965..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/WiFiUdp.cpp +++ /dev/null @@ -1,289 +0,0 @@ -/* - WiFiUdp.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -extern "C" { - #include "socket/include/socket.h" - #include "driver/include/m2m_periph.h" - extern uint8 hif_small_xfer; -} - -#include -#include "WiFi101.h" -#include "WiFiUdp.h" -#include "WiFiClient.h" -#include "WiFiServer.h" - -#define READY (_flag & SOCKET_BUFFER_FLAG_BIND) - -/* Constructor. */ -WiFiUDP::WiFiUDP() -{ - _socket = -1; - _flag = 0; - _head = 0; - _tail = 0; - _rcvSize = 0; - _rcvPort = 0; - _rcvIP = 0; - _sndSize = 0; -} - -/* Start WiFiUDP socket, listening at local port PORT */ -uint8_t WiFiUDP::begin(uint16_t port) -{ - struct sockaddr_in addr; - uint32 u32EnableCallbacks = 0; - - _flag = 0; - _head = 0; - _tail = 0; - _rcvSize = 0; - _rcvPort = 0; - _rcvIP = 0; - _sndSize = 0; - - // Initialize socket address structure. - addr.sin_family = AF_INET; - addr.sin_port = _htons(port); - addr.sin_addr.s_addr = 0; - - // Open TCP server socket. - if ((_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { - return 0; - } - - // Add socket buffer handler: - socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_recvBuffer); - setsockopt(_socket, SOL_SOCKET, SO_SET_UDP_SEND_CALLBACK, &u32EnableCallbacks, 0); - - // Bind socket: - if (bind(_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { - close(_socket); - _socket = -1; - return 0; - } - - // Wait for connection or timeout: - unsigned long start = millis(); - while (!READY && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - if (!READY) { - close(_socket); - _socket = -1; - return 0; - } - _flag &= ~SOCKET_BUFFER_FLAG_BIND; - - return 1; -} - -uint8_t WiFiUDP::beginMulticast(IPAddress ip, uint16_t port) -{ - uint32_t multiIp = ip; - - if (!begin(port)) { - return 0; - } - - setsockopt(_socket, SOL_SOCKET, IP_ADD_MEMBERSHIP, &multiIp, sizeof(multiIp)); - - return 1; -} - -/* return number of bytes available in the current packet, - will return zero if parsePacket hasn't been called yet */ -int WiFiUDP::available() -{ - m2m_wifi_handle_events(NULL); - - if (_socket != -1) { - return _rcvSize; - } - return 0; - } - -/* Release any resources being used by this WiFiUDP instance */ -void WiFiUDP::stop() -{ - if (_socket < 0) - return; - - socketBufferUnregister(_socket); - close(_socket); - _socket = -1; -} - -int WiFiUDP::beginPacket(const char *host, uint16_t port) -{ - IPAddress ip; - if (WiFi.hostByName(host, ip)) { - return beginPacket(ip, port); - } - - return 0; -} - -int WiFiUDP::beginPacket(IPAddress ip, uint16_t port) -{ - _sndIP = ip; - _sndPort = port; - _sndSize = 0; - - return 1; -} - -int WiFiUDP::endPacket() -{ - struct sockaddr_in addr; - - // Network led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); - - addr.sin_family = AF_INET; - addr.sin_port = _htons(_sndPort); - addr.sin_addr.s_addr = _sndIP; - - if (sendto(_socket, (void *)_sndBuffer, _sndSize, 0, - (struct sockaddr *)&addr, sizeof(addr)) < 0) { - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - return 0; - } - - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - - return 1; -} - -size_t WiFiUDP::write(uint8_t byte) -{ - return write(&byte, 1); -} - -size_t WiFiUDP::write(const uint8_t *buffer, size_t size) -{ - if ((size + _sndSize) > sizeof(_sndBuffer)) { - size = sizeof(_sndBuffer) - _sndSize; - } - - memcpy(_sndBuffer + _sndSize, buffer, size); - - _sndSize += size; - - return size; -} - -int WiFiUDP::parsePacket() -{ - m2m_wifi_handle_events(NULL); - - if (_socket != -1) { - if (_rcvSize != 0) { - return _rcvSize; - } - if (_head != _tail) { - _rcvSize = ((uint16_t)_recvBuffer[_tail] << 8) + (uint16_t)_recvBuffer[_tail + 1]; - _rcvPort = ((uint16_t)_recvBuffer[_tail + 2] << 8) + (uint16_t)_recvBuffer[_tail + 3]; - _rcvIP = ((uint32_t)_recvBuffer[_tail + 4] << 24) + ((uint32_t)_recvBuffer[_tail + 5] << 16) + - ((uint32_t)_recvBuffer[_tail + 6] << 8) + (uint32_t)_recvBuffer[_tail + 7]; - _tail += SOCKET_BUFFER_UDP_HEADER_SIZE; - return _rcvSize; - } - } - return 0; -} - -int WiFiUDP::read() -{ - uint8_t b; - - if (read(&b, sizeof(b)) == -1) { - return -1; - } - - return b; -} - -int WiFiUDP::read(unsigned char* buf, size_t size) -{ - // sizeof(size_t) is architecture dependent - // but we need a 16 bit data type here - uint16_t size_tmp = available(); - - if (size_tmp == 0) { - return -1; - } - - if (size < size_tmp) { - size_tmp = size; - } - - for (uint32_t i = 0; i < size_tmp; ++i) { - buf[i] = _recvBuffer[_tail++]; - _rcvSize--; - - if (_tail == _head) { - // the full buffered data has been read, reset head and tail for next transfer - _tail = _head = 0; - - // clear the buffer full flag - _flag &= ~SOCKET_BUFFER_FLAG_FULL; - - // setup buffer and buffer size to transfer the remainder of the current packet - // or next received packet - if (hif_small_xfer) { - recvfrom(_socket, _recvBuffer, SOCKET_BUFFER_MTU, 0); - } else { - recvfrom(_socket, _recvBuffer + SOCKET_BUFFER_UDP_HEADER_SIZE, SOCKET_BUFFER_MTU, 0); - } - m2m_wifi_handle_events(NULL); - } - } - - return size_tmp; -} - -int WiFiUDP::peek() -{ - if (!available()) - return -1; - - return _recvBuffer[_tail]; -} - -void WiFiUDP::flush() -{ - while (available()) - read(); -} - -IPAddress WiFiUDP::remoteIP() -{ - return _rcvIP; -} - -uint16_t WiFiUDP::remotePort() -{ - return _rcvPort; -} diff --git a/feather_sensor_lte/libraries/WiFi101/src/WiFiUdp.h b/feather_sensor_lte/libraries/WiFi101/src/WiFiUdp.h deleted file mode 100644 index d961682..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/WiFiUdp.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - WiFiUdp.h - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef WIFIUDP_H -#define WIFIUDP_H - -#include - -class WiFiUDP : public UDP { -private: - SOCKET _socket; - uint32_t _flag; - uint32_t _head; - uint32_t _tail; - uint8_t _recvBuffer[SOCKET_BUFFER_UDP_SIZE]; - uint16_t _rcvSize; - uint16_t _rcvPort; - uint32_t _rcvIP; - uint8_t _sndBuffer[SOCKET_BUFFER_UDP_SIZE]; - uint16_t _sndSize; - uint16_t _sndPort; - uint32_t _sndIP; - -public: - WiFiUDP(); // Constructor - virtual uint8_t begin(uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use - virtual uint8_t beginMulticast(IPAddress, uint16_t); // initialize, start listening on specified multicast IP address and port. Returns 1 if successful, 0 if there are no sockets available to use - virtual uint8_t beginMulti(IPAddress ip, uint16_t port) { return beginMulticast(ip, port); } - virtual void stop(); // Finish with the UDP socket - - // Sending UDP packets - - // Start building up a packet to send to the remote host specific in ip and port - // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port - virtual int beginPacket(IPAddress ip, uint16_t port); - // Start building up a packet to send to the remote host specific in host and port - // Returns 1 if successful, 0 if there was a problem resolving the hostname or port - virtual int beginPacket(const char *host, uint16_t port); - // Finish off this packet and send it - // Returns 1 if the packet was sent successfully, 0 if there was an error - virtual int endPacket(); - // Write a single byte into the packet - virtual size_t write(uint8_t); - // Write size bytes from buffer into the packet - virtual size_t write(const uint8_t *buffer, size_t size); - - using Print::write; - - // Start processing the next available incoming packet - // Returns the size of the packet in bytes, or 0 if no packets are available - virtual int parsePacket(); - // Number of bytes remaining in the current packet - virtual int available(); - // Read a single byte from the current packet - virtual int read(); - // Read up to len bytes from the current packet and place them into buffer - // Returns the number of bytes read, or 0 if none are available - virtual int read(unsigned char* buffer, size_t len); - // Read up to len characters from the current packet and place them into buffer - // Returns the number of characters read, or 0 if none are available - virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; - // Return the next byte from the current packet without moving on to the next byte - virtual int peek(); - virtual void flush(); // Finish reading the current packet - - // Return the IP address of the host who sent the current incoming packet - virtual IPAddress remoteIP(); - // Return the port of the host who sent the current incoming packet - virtual uint16_t remotePort(); - -}; - -#endif /* WIFIUDP_H */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp.h b/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp.h deleted file mode 100644 index 5527bab..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp.h +++ /dev/null @@ -1,283 +0,0 @@ -/** - * - * \file - * - * \brief WINC BSP API Declarations. - * - * Copyright (c) 2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/** \defgroup nm_bsp BSP - */ -/**@defgroup BSPDefine Defines - * @ingroup nm_bsp - * @{ - */ -#ifndef _NM_BSP_H_ -#define _NM_BSP_H_ - -#define NMI_API -/*!< -* Attribute used to define memory section to map Functions in host memory. -*/ -#define CONST const - -/*!< -* Used for code portability. -*/ - -/*! - * @typedef void (*tpfNmBspIsr) (void); - * @brief Pointer to function.\n - * Used as a data type of ISR function registered by \ref nm_bsp_register_isr - * @return None - */ -typedef void (*tpfNmBspIsr)(void); - - - -#ifndef NULL -#define NULL ((void*)0) -#endif -/*!< -* Void Pointer to '0' in case of NULL is not defined. -*/ - - -#define BSP_MIN(x,y) ((x)>(y)?(y):(x)) -/*!< -* Computes the minimum of \b x and \b y. -*/ - - //@} - -/**@defgroup DataT DataTypes - * @ingroup nm_bsp - * @{ - */ - - /*! - * @ingroup DataTypes - * @typedef unsigned char uint8; - * @brief Range of values between 0 to 255 - */ -typedef unsigned char uint8; - - /*! - * @ingroup DataTypes - * @typedef unsigned short uint16; - * @brief Range of values between 0 to 65535 - */ -typedef unsigned short uint16; - - /*! - * @ingroup Data Types - * @typedef unsigned long uint32; - * @brief Range of values between 0 to 4294967295 - */ -typedef unsigned long uint32; - - - /*! - * @ingroup Data Types - * @typedef signed char sint8; - * @brief Range of values between -128 to 127 - */ -typedef signed char sint8; - - /*! - * @ingroup DataTypes - * @typedef signed short sint16; - * @brief Range of values between -32768 to 32767 - */ -typedef signed short sint16; - - /*! - * @ingroup DataTypes - * @typedef signed long sint32; - * @brief Range of values between -2147483648 to 2147483647 - */ - -typedef signed long sint32; - //@} - -#ifndef CORTUS_APP - - -#ifdef __cplusplus -extern "C"{ -#endif - -/** \defgroup BSPAPI Function - * @ingroup nm_bsp - */ - - -/** @defgroup NmBspInitFn nm_bsp_init - * @ingroup BSPAPI - * Initialization for BSP such as Reset and Chip Enable Pins for WINC, delays, register ISR, enable/disable IRQ for WINC, ...etc. You must use this function in the head of your application to - * enable WINC and Host Driver communicate each other. - */ - /**@{*/ -/*! - * @fn sint8 nm_bsp_init(void); - * @note Implementation of this function is host dependent. - * @warning Missing use will lead to unavailability of host communication.\n - * - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - - */ -sint8 nm_bsp_init(void); - /**@}*/ - - - /** @defgroup NmBspDeinitFn nm_bsp_deinit - * @ingroup BSPAPI - * De-initialization for BSP (\e Board \e Support \e Package) - */ - /**@{*/ -/*! - * @fn sint8 nm_bsp_deinit(void); - * @pre Initialize \ref nm_bsp_init first - * @note Implementation of this function is host dependent. - * @warning Missing use may lead to unknown behavior in case of soft reset.\n - * @see nm_bsp_init - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - - */ -sint8 nm_bsp_deinit(void); - /**@}*/ - - -/** @defgroup NmBspResetFn nm_bsp_reset -* @ingroup BSPAPI -* Resetting NMC1500 SoC by setting CHIP_EN and RESET_N signals low, then after specific delay the function will put CHIP_EN high then RESET_N high, -* for the timing between signals please review the WINC data-sheet -*/ -/**@{*/ - /*! - * @fn void nm_bsp_reset(void); - * @param [in] None - * @pre Initialize \ref nm_bsp_init first - * @note Implementation of this function is host dependent and called by HIF layer. - * @see nm_bsp_init - * @return None - - */ -void nm_bsp_reset(void); - /**@}*/ - - -/** @defgroup NmBspSleepFn nm_bsp_sleep -* @ingroup BSPAPI -* Sleep in units of milliseconds.\n -* This function used by HIF Layer according to different situations. -*/ -/**@{*/ -/*! - * @fn void nm_bsp_sleep(uint32); - * @brief - * @param [in] u32TimeMsec - * Time unit in milliseconds - * @pre Initialize \ref nm_bsp_init first - * @warning Maximum value must nor exceed 4294967295 milliseconds which is equal to 4294967.295 seconds.\n - * @note Implementation of this function is host dependent. - * @see nm_bsp_init - * @return None - */ -void nm_bsp_sleep(uint32 u32TimeMsec); -/**@}*/ - - -/** @defgroup NmBspRegisterFn nm_bsp_register_isr -* @ingroup BSPAPI -* Register ISR (Interrupt Service Routine) in the initialization of HIF (Host Interface) Layer. -* When the interrupt trigger the BSP layer should call the pfisr function once inside the interrupt. -*/ -/**@{*/ -/*! - * @fn void nm_bsp_register_isr(tpfNmBspIsr); - * @param [in] tpfNmBspIsr pfIsr - * Pointer to ISR handler in HIF - * @warning Make sure that ISR for IRQ pin for WINC is disabled by default in your implementation. - * @note Implementation of this function is host dependent and called by HIF layer. - * @see tpfNmBspIsr - * @return None - - */ -void nm_bsp_register_isr(tpfNmBspIsr pfIsr); -/**@}*/ - - -/** @defgroup NmBspInterruptCtrl nm_bsp_interrupt_ctrl -* @ingroup BSPAPI -* Synchronous enable/disable interrupts function -*/ -/**@{*/ -/*! - * @fn void nm_bsp_interrupt_ctrl(uint8); - * @brief Enable/Disable interrupts - * @param [in] u8Enable - * '0' disable interrupts. '1' enable interrupts - * @see tpfNmBspIsr - * @note Implementation of this function is host dependent and called by HIF layer. - * @return None - - */ -void nm_bsp_interrupt_ctrl(uint8 u8Enable); - /**@}*/ - -#ifdef __cplusplus -} -#endif - -#endif - -#ifdef _NM_BSP_BIG_END -#define NM_BSP_B_L_32(x) \ -((((x) & 0x000000FF) << 24) + \ -(((x) & 0x0000FF00) << 8) + \ -(((x) & 0x00FF0000) >> 8) + \ -(((x) & 0xFF000000) >> 24)) -#define NM_BSP_B_L_16(x) \ -((((x) & 0x00FF) << 8) + \ -(((x) & 0xFF00) >> 8)) -#else -#define NM_BSP_B_L_32(x) (x) -#define NM_BSP_B_L_16(x) (x) -#endif - - -#endif /*_NM_BSP_H_*/ diff --git a/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h b/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h deleted file mode 100644 index 77417e8..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h +++ /dev/null @@ -1,74 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 BSP APIs definitions. - * - * Copyright (c) 2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NM_BSP_ARDUINO_H_ -#define _NM_BSP_ARDUINO_H_ - -#include - -#include - -/* - * Arduino variants may redefine those pins. - * If no pins are specified the following defaults are used: - * WINC1501_RESET_PIN - pin 5 - * WINC1501_INTN_PIN - pin 7 - * WINC1501_CHIP_EN_PIN - not connected (tied to VCC) - */ -#if !defined(WINC1501_RESET_PIN) - #define WINC1501_RESET_PIN 5 -#endif -#if !defined(WINC1501_INTN_PIN) - #define WINC1501_INTN_PIN 7 -#endif -#if !defined(WINC1501_SPI_CS_PIN) - #define WINC1501_SPI_CS_PIN 10 -#endif -#if !defined(WINC1501_CHIP_EN_PIN) - #define WINC1501_CHIP_EN_PIN -1 -#endif - -extern int8_t gi8Winc1501CsPin; -extern int8_t gi8Winc1501ResetPin; -extern int8_t gi8Winc1501IntnPin; -extern int8_t gi8Winc1501ChipEnPin; - -#endif /* _NM_BSP_ARDUINO_H_ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h b/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h deleted file mode 100644 index c5991f2..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h +++ /dev/null @@ -1,54 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 BSP APIs definitions. - * - * Copyright (c) 2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NM_BSP_AVR_H_ -#define _NM_BSP_AVR_H_ - -#pragma once - -#define NM_DEBUG 0 -#define NM_BSP_PRINTF - -#define CONF_WINC_USE_SPI 1 - -#define NM_EDGE_INTERRUPT 1 - -#endif /* _NM_BSP_AVR_H_ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h b/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h deleted file mode 100644 index 45d3ff2..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h +++ /dev/null @@ -1,59 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 BSP APIs declarations. - * - * Copyright (c) 2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/**@defgroup BSPDefine Defines - * @ingroup nm_bsp - * @{ - */ -#ifndef _NM_BSP_INTERNAL_H_ -#define _NM_BSP_INTERNAL_H_ - -#ifdef ARDUINO_ARCH_AVR -#define LIMITED_RAM_DEVICE -#include "bsp/include/nm_bsp_avr.h" -#else -#include "bsp/include/nm_bsp_samd21.h" -#endif - -#ifdef ARDUINO -#define CONF_PERIPH -#endif - -#endif //_NM_BSP_INTERNAL_H_ \ No newline at end of file diff --git a/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h b/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h deleted file mode 100644 index 296cd20..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h +++ /dev/null @@ -1,52 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 BSP APIs definitions. - * - * Copyright (c) 2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NM_BSP_SAMD21_H_ -#define _NM_BSP_SAMD21_H_ - -#define NM_DEBUG 0 -#define NM_BSP_PRINTF - -#define CONF_WINC_USE_SPI 1 - -#define NM_EDGE_INTERRUPT 1 - -#endif /* _NM_BSP_SAMD21_H_ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c b/feather_sensor_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c deleted file mode 100644 index e27be14..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c +++ /dev/null @@ -1,205 +0,0 @@ -/** - * - * \file - * - * \brief This module contains SAMD21 BSP APIs implementation. - * - * Copyright (c) 2014 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "bsp/include/nm_bsp.h" -#include "bsp/include/nm_bsp_arduino.h" -#include "common/include/nm_common.h" - -int8_t gi8Winc1501CsPin = WINC1501_SPI_CS_PIN; -int8_t gi8Winc1501ResetPin = WINC1501_RESET_PIN; -int8_t gi8Winc1501IntnPin = WINC1501_INTN_PIN; -int8_t gi8Winc1501ChipEnPin = WINC1501_CHIP_EN_PIN; - -static tpfNmBspIsr gpfIsr; - -void __attribute__((weak)) attachInterruptMultiArch(uint32_t pin, void *chip_isr, uint32_t mode) -{ - attachInterrupt(pin, chip_isr, mode); -} - -void __attribute__((weak)) detachInterruptMultiArch(uint32_t pin) -{ - detachInterrupt(pin); -} - -static void chip_isr(void) -{ - if (gpfIsr) { - gpfIsr(); - } -} - -/* - * @fn init_chip_pins - * @brief Initialize reset, chip enable and wake pin - * @author M.S.M - * @date 11 July 2012 - * @version 1.0 - */ -static void init_chip_pins(void) -{ - /* Configure RESETN pin as output. */ - pinMode(gi8Winc1501ResetPin, OUTPUT); - digitalWrite(gi8Winc1501ResetPin, HIGH); - - /* Configure INTN pins as input. */ - pinMode(gi8Winc1501IntnPin, INPUT); - - if (gi8Winc1501ChipEnPin > -1) - { - /* Configure CHIP_EN as pull-up */ - pinMode(gi8Winc1501ChipEnPin, INPUT_PULLUP); - } -} - -static void deinit_chip_pins(void) -{ - digitalWrite(gi8Winc1501ResetPin, LOW); - pinMode(gi8Winc1501ResetPin, INPUT); - - if (gi8Winc1501ChipEnPin > -1) - { - pinMode(gi8Winc1501ChipEnPin, INPUT); - } -} - -/* - * @fn nm_bsp_init - * @brief Initialize BSP - * @return 0 in case of success and -1 in case of failure - * @author M.S.M - * @date 11 July 2012 - * @version 1.0 - */ -sint8 nm_bsp_init(void) -{ - gpfIsr = NULL; - - init_chip_pins(); - - nm_bsp_reset(); - - return M2M_SUCCESS; -} - -/** - * @fn nm_bsp_deinit - * @brief De-iInitialize BSP - * @return 0 in case of success and -1 in case of failure - * @author M. Abdelmawla - * @date 11 July 2012 - * @version 1.0 - */ -sint8 nm_bsp_deinit(void) -{ - deinit_chip_pins(); - - return M2M_SUCCESS; -} - -/** - * @fn nm_bsp_reset - * @brief Reset NMC1500 SoC by setting CHIP_EN and RESET_N signals low, - * CHIP_EN high then RESET_N high - * @author M. Abdelmawla - * @date 11 July 2012 - * @version 1.0 - */ -void nm_bsp_reset(void) -{ - digitalWrite(gi8Winc1501ResetPin, LOW); - nm_bsp_sleep(100); - digitalWrite(gi8Winc1501ResetPin, HIGH); - nm_bsp_sleep(100); -} - -/* - * @fn nm_bsp_sleep - * @brief Sleep in units of mSec - * @param[IN] u32TimeMsec - * Time in milliseconds - * @author M.S.M - * @date 28 OCT 2013 - * @version 1.0 - */ -void nm_bsp_sleep(uint32 u32TimeMsec) -{ - while (u32TimeMsec--) { - delay(1); - } -} - -/* - * @fn nm_bsp_register_isr - * @brief Register interrupt service routine - * @param[IN] pfIsr - * Pointer to ISR handler - * @author M.S.M - * @date 28 OCT 2013 - * @sa tpfNmBspIsr - * @version 1.0 - */ -void nm_bsp_register_isr(tpfNmBspIsr pfIsr) -{ - gpfIsr = pfIsr; - attachInterruptMultiArch(gi8Winc1501IntnPin, chip_isr, FALLING); -} - -/* - * @fn nm_bsp_interrupt_ctrl - * @brief Enable/Disable interrupts - * @param[IN] u8Enable - * '0' disable interrupts. '1' enable interrupts - * @author M.S.M - * @date 28 OCT 2013 - * @version 1.0 - */ -void nm_bsp_interrupt_ctrl(uint8 u8Enable) -{ - if (u8Enable) { - attachInterruptMultiArch(gi8Winc1501IntnPin, chip_isr, FALLING); - } else { - detachInterruptMultiArch(gi8Winc1501IntnPin); - } -} diff --git a/feather_sensor_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c b/feather_sensor_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c deleted file mode 100644 index 050d5d5..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c +++ /dev/null @@ -1,164 +0,0 @@ -/** - * - * \file - * - * \brief This module contains SAMD21 BSP APIs implementation. - * - * Copyright (c) 2014 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifdef ARDUINO_ARCH_AVR - -#include "bsp/include/nm_bsp.h" -#include "bsp/include/nm_bsp_arduino.h" -#include "common/include/nm_common.h" - -#define IS_MEGA (defined(ARDUINO_AVR_MEGA) || defined(ARDUINO_AVR_MEGA2560)) - -static tpfNmBspIsr gpfIsr; - -volatile uint8_t *_receivePortRegister; -volatile uint8_t *_pcint_maskreg; -uint8_t _receiveBitMask; -volatile uint8_t prev_pin_read = 1; - -uint8_t rx_pin_read() -{ - return *_receivePortRegister & _receiveBitMask; -} - -#if !IS_MEGA - -#if defined(PCINT0_vect) -ISR(PCINT0_vect) -{ - if (!rx_pin_read() && gpfIsr) - { - gpfIsr(); - } -} -#endif - -#if defined(PCINT1_vect) -ISR(PCINT1_vect, ISR_ALIASOF(PCINT0_vect)); -#endif - -#if defined(PCINT2_vect) -ISR(PCINT2_vect, ISR_ALIASOF(PCINT0_vect)); -#endif - -#if defined(PCINT3_vect) -ISR(PCINT3_vect, ISR_ALIASOF(PCINT0_vect)); -#endif - -#endif // !IS_MEGA - -#if defined(TIMER4_OVF_vect) -ISR(TIMER4_OVF_vect) { - uint8_t curr_pin_read = rx_pin_read(); - if ((curr_pin_read != prev_pin_read) && !curr_pin_read && gpfIsr) - { - gpfIsr(); - } - prev_pin_read = curr_pin_read; -} - -// stategy 3 - start a timer and perform a sort of polling -void attachFakeInterruptToTimer(void) { - TCCR4B = (1< I2C/UART. Parameter:tstrNmI2cDefault/tstrNmUartDefault */ -#define NM_BUS_IOCTL_W ((uint8)1) /*!< Write only ==> I2C/UART. Parameter type tstrNmI2cDefault/tstrNmUartDefault*/ -#define NM_BUS_IOCTL_W_SPECIAL ((uint8)2) /*!< Write two buffers within the same transaction - (same start/stop conditions) ==> I2C only. Parameter:tstrNmI2cSpecial */ -#define NM_BUS_IOCTL_RW ((uint8)3) /*!< Read/Write at the same time ==> SPI only. Parameter:tstrNmSpiRw */ - -#define NM_BUS_IOCTL_WR_RESTART ((uint8)4) /*!< Write buffer then made restart condition then read ==> I2C only. parameter:tstrNmI2cSpecial */ -/** -* @struct tstrNmBusCapabilities -* @brief Structure holding bus capabilities information -* @sa NM_BUS_TYPE_I2C, NM_BUS_TYPE_SPI -*/ -typedef struct -{ - uint16 u16MaxTrxSz; /*!< Maximum transfer size. Must be >= 16 bytes*/ -} tstrNmBusCapabilities; - -/** -* @struct tstrNmI2cDefault -* @brief Structure holding I2C default operation parameters -* @sa NM_BUS_IOCTL_R, NM_BUS_IOCTL_W -*/ -typedef struct -{ - uint8 u8SlaveAdr; - uint8 *pu8Buf; /*!< Operation buffer */ - uint16 u16Sz; /*!< Operation size */ -} tstrNmI2cDefault; - -/** -* @struct tstrNmI2cSpecial -* @brief Structure holding I2C special operation parameters -* @sa NM_BUS_IOCTL_W_SPECIAL -*/ -typedef struct -{ - uint8 u8SlaveAdr; - uint8 *pu8Buf1; /*!< pointer to the 1st buffer */ - uint8 *pu8Buf2; /*!< pointer to the 2nd buffer */ - uint16 u16Sz1; /*!< 1st buffer size */ - uint16 u16Sz2; /*!< 2nd buffer size */ -} tstrNmI2cSpecial; - -/** -* @struct tstrNmSpiRw -* @brief Structure holding SPI R/W parameters -* @sa NM_BUS_IOCTL_RW -*/ -typedef struct -{ - uint8 *pu8InBuf; /*!< pointer to input buffer. - Can be set to null and in this case zeros should be sent at MOSI */ - uint8 *pu8OutBuf; /*!< pointer to output buffer. - Can be set to null and in this case data from MISO can be ignored */ - uint16 u16Sz; /*!< Transfere size */ -} tstrNmSpiRw; - - -/** -* @struct tstrNmUartDefault -* @brief Structure holding UART default operation parameters -* @sa NM_BUS_IOCTL_R, NM_BUS_IOCTL_W -*/ -typedef struct -{ - uint8 *pu8Buf; /*!< Operation buffer */ - uint16 u16Sz; /*!< Operation size */ -} tstrNmUartDefault; -/*!< Bus capabilities. This structure must be declared at platform specific bus wrapper */ -extern tstrNmBusCapabilities egstrNmBusCapabilities; - - -#ifdef __cplusplus - extern "C" { - #endif -/** -* @fn nm_bus_init -* @brief Initialize the bus wrapper -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_bus_init(void *); - -/** -* @fn nm_bus_ioctl -* @brief send/receive from the bus -* @param [in] u8Cmd -* IOCTL command for the operation -* @param [in] pvParameter -* Arbitrary parameter depending on IOCTL -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -* @note For SPI only, it's important to be able to send/receive at the same time -*/ -sint8 nm_bus_ioctl(uint8 u8Cmd, void* pvParameter); - -/** -* @fn nm_bus_deinit -* @brief De-initialize the bus wrapper -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_bus_deinit(void); - -/* -* @fn nm_bus_reinit -* @brief re-initialize the bus wrapper -* @param [in] void *config -* re-init configuration data -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_bus_reinit(void *); -/* -* @fn nm_bus_get_chip_type -* @brief get chip type -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -#ifdef CONF_WINC_USE_UART -uint8 nm_bus_get_chip_type(void); -#endif -#ifdef __cplusplus - } - #endif - -#endif /*_NM_BUS_WRAPPER_H_*/ diff --git a/feather_sensor_lte/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp b/feather_sensor_lte/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp deleted file mode 100644 index 22a7473..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp +++ /dev/null @@ -1,200 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 bus wrapper APIs implementation. - * - * Copyright (c) 2014 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include -#include - -/* - * Variants may define an alternative SPI instace to use for WiFi101. - * If not defined the following defaults are used: - * WINC1501_SPI - SPI - */ -#if !defined(WINC1501_SPI) - #define WINC1501_SPI SPI -#endif - -extern "C" { - -#include "bsp/include/nm_bsp.h" -#include "bsp/include/nm_bsp_arduino.h" -#include "common/include/nm_common.h" -#include "bus_wrapper/include/nm_bus_wrapper.h" - -} - -#define NM_BUS_MAX_TRX_SZ 256 - -tstrNmBusCapabilities egstrNmBusCapabilities = -{ - NM_BUS_MAX_TRX_SZ -}; - -static const SPISettings wifi_SPISettings(12000000L, MSBFIRST, SPI_MODE0); - -static sint8 spi_rw(uint8* pu8Mosi, uint8* pu8Miso, uint16 u16Sz) -{ - uint8 u8Dummy = 0; - uint8 u8SkipMosi = 0, u8SkipMiso = 0; - - if (!pu8Mosi) { - pu8Mosi = &u8Dummy; - u8SkipMosi = 1; - } - else if(!pu8Miso) { - pu8Miso = &u8Dummy; - u8SkipMiso = 1; - } - else { - return M2M_ERR_BUS_FAIL; - } - - WINC1501_SPI.beginTransaction(wifi_SPISettings); - digitalWrite(gi8Winc1501CsPin, LOW); - - while (u16Sz) { - *pu8Miso = WINC1501_SPI.transfer(*pu8Mosi); - - u16Sz--; - if (!u8SkipMiso) - pu8Miso++; - if (!u8SkipMosi) - pu8Mosi++; - } - - digitalWrite(gi8Winc1501CsPin, HIGH); - WINC1501_SPI.endTransaction(); - - return M2M_SUCCESS; -} - -extern "C" { - -/* -* @fn nm_bus_init -* @brief Initialize the bus wrapper -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M.S.M -* @date 28 oct 2013 -* @version 1.0 -*/ -sint8 nm_bus_init(void * /* pvInitValue */) -{ - sint8 result = M2M_SUCCESS; - - /* Configure SPI peripheral. */ - WINC1501_SPI.begin(); - - /* Configure CS PIN. */ - pinMode(gi8Winc1501CsPin, OUTPUT); - digitalWrite(gi8Winc1501CsPin, HIGH); - - /* Reset WINC1500. */ - nm_bsp_reset(); - nm_bsp_sleep(1); - - return result; -} - -/* -* @fn nm_bus_ioctl -* @brief send/receive from the bus -* @param[IN] u8Cmd -* IOCTL command for the operation -* @param[IN] pvParameter -* Arbitrary parameter depenging on IOCTL -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M.S.M -* @date 28 oct 2013 -* @note For SPI only, it's important to be able to send/receive at the same time -* @version 1.0 -*/ -sint8 nm_bus_ioctl(uint8 u8Cmd, void* pvParameter) -{ - sint8 s8Ret = 0; - switch(u8Cmd) - { - case NM_BUS_IOCTL_RW: { - tstrNmSpiRw *pstrParam = (tstrNmSpiRw *)pvParameter; - s8Ret = spi_rw(pstrParam->pu8InBuf, pstrParam->pu8OutBuf, pstrParam->u16Sz); - } - break; - default: - s8Ret = -1; - M2M_ERR("invalide ioclt cmd\n"); - break; - } - - return s8Ret; -} - -/* -* @fn nm_bus_deinit -* @brief De-initialize the bus wrapper -* @author M.S.M -* @date 28 oct 2013 -* @version 1.0 -*/ -sint8 nm_bus_deinit(void) -{ - WINC1501_SPI.end(); - return 0; -} - -/* -* @fn nm_bus_reinit -* @brief re-initialize the bus wrapper -* @param [in] void *config -* re-init configuration data -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Dina El Sissy -* @date 19 Sept 2012 -* @version 1.0 -*/ -sint8 nm_bus_reinit(void* /* config */) -{ - return M2M_SUCCESS; -} - -} // extern "C" - diff --git a/feather_sensor_lte/libraries/WiFi101/src/common/include/nm_common.h b/feather_sensor_lte/libraries/WiFi101/src/common/include/nm_common.h deleted file mode 100644 index d66fbdb..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/common/include/nm_common.h +++ /dev/null @@ -1,153 +0,0 @@ -/** - * - * \file - * - * \brief WINC Driver Common API Declarations. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NM_COMMON_H_ -#define _NM_COMMON_H_ - -#include "bsp/include/nm_bsp.h" -#include "common/include/nm_debug.h" - -/**@defgroup CommonDefines CommonDefines - * @ingroup WlanDefines - */ -/**@{*/ -#define M2M_TIME_OUT_DELAY 10000 - -/*states*/ -#define M2M_SUCCESS ((sint8)0) -#define M2M_ERR_SEND ((sint8)-1) -#define M2M_ERR_RCV ((sint8)-2) -#define M2M_ERR_MEM_ALLOC ((sint8)-3) -#define M2M_ERR_TIME_OUT ((sint8)-4) -#define M2M_ERR_INIT ((sint8)-5) -#define M2M_ERR_BUS_FAIL ((sint8)-6) -#define M2M_NOT_YET ((sint8)-7) -#define M2M_ERR_FIRMWARE ((sint8)-8) -#define M2M_SPI_FAIL ((sint8)-9) -#define M2M_ERR_FIRMWARE_bURN ((sint8)-10) -#define M2M_ACK ((sint8)-11) -#define M2M_ERR_FAIL ((sint8)-12) -#define M2M_ERR_FW_VER_MISMATCH ((sint8)-13) -#define M2M_ERR_SCAN_IN_PROGRESS ((sint8)-14) -#define M2M_ERR_INVALID_ARG ((sint8)-15) -#define M2M_ERR_INVALID ((sint8)-16) - -/*i2c MAASTER ERR*/ -#define I2C_ERR_LARGE_ADDRESS 0xE1UL /*the address exceed the max addressing mode in i2c flash*/ -#define I2C_ERR_TX_ABRT 0xE2UL /*NO ACK from slave*/ -#define I2C_ERR_OVER_SIZE 0xE3UL /**/ -#define ERR_PREFIX_NMIS 0xE4UL /*wrong first four byte in flash NMIS*/ -#define ERR_FIRMEWARE_EXCEED_SIZE 0xE5UL /*Total size of firmware exceed the max size 256k*/ -/**/ -#define PROGRAM_START 0x26961735UL -#define BOOT_SUCCESS 0x10add09eUL -#define BOOT_START 0x12345678UL - - -#define NBIT31 (0x80000000) -#define NBIT30 (0x40000000) -#define NBIT29 (0x20000000) -#define NBIT28 (0x10000000) -#define NBIT27 (0x08000000) -#define NBIT26 (0x04000000) -#define NBIT25 (0x02000000) -#define NBIT24 (0x01000000) -#define NBIT23 (0x00800000) -#define NBIT22 (0x00400000) -#define NBIT21 (0x00200000) -#define NBIT20 (0x00100000) -#define NBIT19 (0x00080000) -#define NBIT18 (0x00040000) -#define NBIT17 (0x00020000) -#define NBIT16 (0x00010000) -#define NBIT15 (0x00008000) -#define NBIT14 (0x00004000) -#define NBIT13 (0x00002000) -#define NBIT12 (0x00001000) -#define NBIT11 (0x00000800) -#define NBIT10 (0x00000400) -#define NBIT9 (0x00000200) -#define NBIT8 (0x00000100) -#define NBIT7 (0x00000080) -#define NBIT6 (0x00000040) -#define NBIT5 (0x00000020) -#define NBIT4 (0x00000010) -#define NBIT3 (0x00000008) -#define NBIT2 (0x00000004) -#define NBIT1 (0x00000002) -#define NBIT0 (0x00000001) - -#define M2M_MAX(A,B) ((A) > (B) ? (A) : (B)) -#define M2M_SEL(x,m1,m2,m3) ((x>1)?((x>2)?(m3):(m2)):(m1)) -#define WORD_ALIGN(val) (((val) & 0x03) ? ((val) + 4 - ((val) & 0x03)) : (val)) - - - -#define DATA_PKT_OFFSET 4 - -#ifndef BIG_ENDIAN -#define BYTE_0(word) ((uint8)(((word) >> 0 ) & 0x000000FFUL)) -#define BYTE_1(word) ((uint8)(((word) >> 8 ) & 0x000000FFUL)) -#define BYTE_2(word) ((uint8)(((word) >> 16) & 0x000000FFUL)) -#define BYTE_3(word) ((uint8)(((word) >> 24) & 0x000000FFUL)) -#else -#define BYTE_0(word) ((uint8)(((word) >> 24) & 0x000000FFUL)) -#define BYTE_1(word) ((uint8)(((word) >> 16) & 0x000000FFUL)) -#define BYTE_2(word) ((uint8)(((word) >> 8 ) & 0x000000FFUL)) -#define BYTE_3(word) ((uint8)(((word) >> 0 ) & 0x000000FFUL)) -#endif - -/**@}*/ -#ifdef __cplusplus - extern "C" { - #endif -NMI_API void m2m_memcpy(uint8* pDst,uint8* pSrc,uint32 sz); -NMI_API void m2m_memset(uint8* pBuf,uint8 val,uint32 sz); -NMI_API uint16 m2m_strlen(uint8 * pcStr); -NMI_API sint8 m2m_memcmp(uint8 *pu8Buff1,uint8 *pu8Buff2 ,uint32 u32Size); -NMI_API uint8 m2m_strncmp(uint8 *pcS1, uint8 *pcS2, uint16 u16Len); -NMI_API uint8 * m2m_strstr(uint8 *pcIn, uint8 *pcStr); -NMI_API uint8 m2m_checksum(uint8* buf, int sz); - -#ifdef __cplusplus -} - #endif -#endif /*_NM_COMMON_H_*/ diff --git a/feather_sensor_lte/libraries/WiFi101/src/common/include/nm_debug.h b/feather_sensor_lte/libraries/WiFi101/src/common/include/nm_debug.h deleted file mode 100644 index a710f6c..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/common/include/nm_debug.h +++ /dev/null @@ -1,95 +0,0 @@ -/** - * - * \file - * - * \brief This module contains debug APIs declarations. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NM_DEBUG_H_ -#define _NM_DEBUG_H_ - -#include "bsp/include/nm_bsp.h" -#include "bsp/include/nm_bsp_internal.h" - -/**@defgroup DebugDefines DebugDefines - * @ingroup WlanDefines - */ -/**@{*/ - - -#define M2M_LOG_NONE 0 -#define M2M_LOG_ERROR 1 -#define M2M_LOG_INFO 2 -#define M2M_LOG_REQ 3 -#define M2M_LOG_DBG 4 - -#if (defined __APS3_CORTUS__) -#define M2M_LOG_LEVEL M2M_LOG_INFO -#else -#define M2M_LOG_LEVEL M2M_LOG_REQ -#endif - - -#define M2M_ERR(...) -#define M2M_INFO(...) -#define M2M_REQ(...) -#define M2M_DBG(...) -#define M2M_PRINT(...) - -#if (CONF_WINC_DEBUG == 1) -#undef M2M_PRINT -#define M2M_PRINT(...) do{CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) -#if (M2M_LOG_LEVEL >= M2M_LOG_ERROR) -#undef M2M_ERR -#define M2M_ERR(...) do{CONF_WINC_PRINTF("(APP)(ERR)[%s][%d]",__FUNCTION__,__LINE__); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) -#if (M2M_LOG_LEVEL >= M2M_LOG_INFO) -#undef M2M_INFO -#define M2M_INFO(...) do{CONF_WINC_PRINTF("(APP)(INFO)"); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) -#if (M2M_LOG_LEVEL >= M2M_LOG_REQ) -#undef M2M_REQ -#define M2M_REQ(...) do{CONF_WINC_PRINTF("(APP)(R)"); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) -#if (M2M_LOG_LEVEL >= M2M_LOG_DBG) -#undef M2M_DBG -#define M2M_DBG(...) do{CONF_WINC_PRINTF("(APP)(DBG)[%s][%d]",__FUNCTION__,__LINE__); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) -#endif /*M2M_LOG_DBG*/ -#endif /*M2M_LOG_REQ*/ -#endif /*M2M_LOG_INFO*/ -#endif /*M2M_LOG_ERROR*/ -#endif /*CONF_WINC_DEBUG */ - -/**@}*/ -#endif /* _NM_DEBUG_H_ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/common/source/nm_common.c b/feather_sensor_lte/libraries/WiFi101/src/common/source/nm_common.c deleted file mode 100644 index 8b3c941..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/common/source/nm_common.c +++ /dev/null @@ -1,136 +0,0 @@ -/** - * - * \file - * - * \brief This module contains common APIs declarations. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -#include "common/include/nm_common.h" - -void m2m_memcpy(uint8* pDst,uint8* pSrc,uint32 sz) -{ - if(sz == 0) return; - do - { - *pDst = *pSrc; - pDst++; - pSrc++; - }while(--sz); -} -uint8 m2m_checksum(uint8* buf, int sz) -{ - uint8 cs = 0; - while(--sz) - { - cs ^= *buf; - buf++; - } - - return cs; -} - -void m2m_memset(uint8* pBuf,uint8 val,uint32 sz) -{ - if(sz == 0) return; - do - { - *pBuf = val; - pBuf++; - }while(--sz); -} - -uint16 m2m_strlen(uint8 * pcStr) -{ - uint16 u16StrLen = 0; - while(*pcStr) - { - u16StrLen ++; - pcStr++; - } - return u16StrLen; -} - -uint8 m2m_strncmp(uint8 *pcS1, uint8 *pcS2, uint16 u16Len) -{ - for ( ; u16Len > 0; pcS1++, pcS2++, --u16Len) - if (*pcS1 != *pcS2) - return ((*(uint8 *)pcS1 < *(uint8 *)pcS2) ? -1 : +1); - else if (*pcS1 == '\0') - return 0; - return 0; -} - -/* Finds the occurance of pcStr in pcIn. -If pcStr is part of pcIn it returns a valid pointer to the start of pcStr within pcIn. -Otherwise a NULL Pointer is returned. -*/ -uint8 * m2m_strstr(uint8 *pcIn, uint8 *pcStr) -{ - uint8 u8c; - uint16 u16StrLen; - - u8c = *pcStr++; - if (!u8c) - return (uint8 *) pcIn; // Trivial empty string case - - u16StrLen = m2m_strlen(pcStr); - do { - uint8 u8Sc; - - do { - u8Sc = *pcIn++; - if (!u8Sc) - return (uint8 *) 0; - } while (u8Sc != u8c); - } while (m2m_strncmp(pcIn, pcStr, u16StrLen) != 0); - - return (uint8 *) (pcIn - 1); -} - -sint8 m2m_memcmp(uint8 *pu8Buff1,uint8 *pu8Buff2 ,uint32 u32Size) -{ - uint32 i; - sint8 s8Result = 0; - for(i = 0 ; i < u32Size ; i++) - { - if(pu8Buff1[i] != pu8Buff2[i]) - { - s8Result = 1; - break; - } - } - return s8Result; -} diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/include/ecc_types.h b/feather_sensor_lte/libraries/WiFi101/src/driver/include/ecc_types.h deleted file mode 100644 index 764c3b9..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/include/ecc_types.h +++ /dev/null @@ -1,245 +0,0 @@ -/** - * - * \file - * - * \brief WINC Application Interface Internal Types. - * - * Copyright (c) 2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef __ECC_TYPES_H__ -#define __ECC_TYPES_H__ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "m2m_types.h" - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - - -#define ECC_LARGEST_CURVE_SIZE (32) -/*!< - The size of the the largest supported EC. For now, assuming - the 256-bit EC is the largest supported curve type. -*/ - - -#define ECC_POINT_MAX_SIZE ECC_LARGEST_CURVE_SIZE -/*!< - Maximum size of one coordinate of an EC point. -*/ - - -#define ECC_POINT_MAX_SIZE_WORDS (ECC_POINT_MAX_SIZE / 4) -/*!< - SIZE in 32-bit words. -*/ - -#if 0 -#define ECC_NUM_SUPP_CURVES ((sizeof(gastrECCSuppList)) / (sizeof(tstrEllipticCurve))) -#endif -/*!< -*/ - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -/*! -@enum \ - tenuEcNamedCurve - -@brief EC Named Curves - - Defines a list of supported ECC named curves. -*/ -typedef enum EcNamedCurve{ - EC_SECP192R1 = 19, - /*!< - It is defined by NIST as P192 and by the SEC Group as secp192r1. - */ - EC_SECP256R1 = 23, - /*!< - It is defined by NIST as P256 and by the SEC Group as secp256r1. - */ - EC_SECP384R1 = 24, - /*!< - It is defined by NIST as P384 and by the SEC Group as secp384r1. - */ - EC_SECP521R1 = 25, - /*!< - It is defined by NIST as P521 and by the SEC Group as secp521r1. - */ - EC_UNKNOWN = 255 -}tenuEcNamedCurve; - - -/*! -@struct \ - tstrECPoint - -@brief Elliptic Curve point representation -*/ -typedef struct EcPoint{ - uint8 X[ECC_POINT_MAX_SIZE]; - /*!< - The X-coordinate of the ec point. - */ - uint8 Y[ECC_POINT_MAX_SIZE]; - /*!< - The Y-coordinate of the ec point. - */ - uint16 u16Size; - /*!< - Point size in bytes (for each of the coordinates). - */ - uint16 u16PrivKeyID; - /*!< - ID for the corresponding private key. - */ -}tstrECPoint; - - -/*! -@struct \ - tstrECDomainParam - -@brief ECC Curve Domain Parameters - - The structure defines the ECC domain parameters for curves defined over prime finite fields. -*/ -typedef struct EcDomainParam{ - uint32 p[ECC_POINT_MAX_SIZE_WORDS]; - uint32 a[ECC_POINT_MAX_SIZE_WORDS]; - uint32 b[ECC_POINT_MAX_SIZE_WORDS]; - tstrECPoint G; -}tstrECDomainParam; - - -/*! -@struct \ - tstrEllipticCurve - -@brief - Definition of an elliptic curve -*/ -typedef struct{ - tenuEcNamedCurve enuType; - tstrECDomainParam strParam; -}tstrEllipticCurve; - - -typedef enum{ - ECC_REQ_NONE, - ECC_REQ_CLIENT_ECDH, - ECC_REQ_SERVER_ECDH, - ECC_REQ_GEN_KEY, - ECC_REQ_SIGN_GEN, - ECC_REQ_SIGN_VERIFY -}tenuEccREQ; - - -typedef struct{ - tstrECPoint strPubKey; - uint8 au8Key[ECC_POINT_MAX_SIZE]; -}tstrEcdhReqInfo; - - -typedef struct{ - uint32 u32nSig; -}tstrEcdsaVerifyReqInfo; - - -typedef struct{ - uint16 u16CurveType; - uint16 u16HashSz; -}tstrEcdsaSignReqInfo; - - -typedef struct{ - uint16 u16REQ; - uint16 u16Status; - uint32 u32UserData; - uint32 u32SeqNo; - union{ - tstrEcdhReqInfo strEcdhREQ; - tstrEcdsaSignReqInfo strEcdsaSignREQ; - tstrEcdsaVerifyReqInfo strEcdsaVerifyREQ; - }; -}tstrEccReqInfo; - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -GLOBALS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#if 0 -static tstrEllipticCurve gastrECCSuppList[] = { - { - EC_SECP256R1, - { - {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF}, - {0xFFFFFFFC, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF}, - {0x27D2604B, 0x3BCE3C3E, 0xCC53B0F6, 0x651D06B0, 0x769886BC, 0xB3EBBD55, 0xAA3A93E7, 0x5AC635D8}, - { - { - 0x6B, 0x17, 0xD1, 0xF2, 0xE1, 0x2C, 0x42, 0x47, 0xF8, 0xBC, 0xE6, 0xE5, 0x63, 0xA4, 0x40, 0xF2, - 0x77, 0x03, 0x7D, 0x81, 0x2D, 0xEB, 0x33, 0xA0, 0xF4, 0xA1, 0x39, 0x45, 0xD8, 0x98, 0xC2, 0x96 - }, - { - 0x4F, 0xE3, 0x42, 0xE2, 0xFE, 0x1A, 0x7F, 0x9B, 0x8E, 0xE7, 0xEB, 0x4A, 0x7C, 0x0F, 0x9E, 0x16, - 0x2B, 0xCE, 0x33, 0x57, 0x6B, 0x31, 0x5E, 0xCE, 0xCB, 0xB6, 0x40, 0x68, 0x37, 0xBF, 0x51, 0xF5 - }, - 32 - } - } - } -}; -#endif - -/*!< - List of supported Elliptic Curves ordered by security level (most secure curve is at index ZERO). -*/ - - - -#endif /* __ECC_TYPES_H__ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_ate_mode.h b/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_ate_mode.h deleted file mode 100644 index a17d298..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_ate_mode.h +++ /dev/null @@ -1,732 +0,0 @@ -/** - * - * \file - * - * \brief WINC ATE Test Driver Interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifdef _M2M_ATE_FW_ - -#ifndef _M2M_ATE_MODE_H_ -#define _M2M_ATE_MODE_H_ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#include "common/include/nm_common.h" -#include "driver/include/m2m_types.h" - -/** \defgroup m2m_ate ATE -*/ -/**@defgroup ATEDefine Defines - * @ingroup m2m_ate - * @{ - */ -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#define M2M_ATE_MAX_NUM_OF_RATES (20) -/*!< -Maximum number of all rates (b,g and n) - */ -#define M2M_ATE_MAX_FRAME_LENGTH (1024) -/*!< Maximum number of length for each frame - */ -#define M2M_ATE_MIN_FRAME_LENGTH (1) -/*!< Minimum number of length for each frame - */ -#define M2M_ATE_SUCCESS (M2M_SUCCESS) -/*!< No Error and operation has been completed successfully. -*/ -#define M2M_ATE_ERR_VALIDATE (M2M_ERR_FAIL) -/*!< Error in parameters passed to functions. - */ -#define M2M_ATE_ERR_TX_ALREADY_RUNNING (-1) -/*!< Error in starting a transmission test. Another test is already running and its not allowed to start another ATE test. - */ -#define M2M_ATE_ERR_RX_ALREADY_RUNNING (-2) -/*!< Error in starting a reception test. Another test is already running and its not allowed to start another ATE test. - */ -#define M2M_ATE_ERR_UNHANDLED_CASE (-3) -/*!< Invalid case. - */ -#define M2M_ATE_RX_DISABLE_DA 0x0 -/*!< Filter selection for received frames: Disable filtering received frames by the destination address. - */ -#define M2M_ATE_RX_ENABLE_DA 0x1 -/*!< Filter selection for received frames: Enable filtering received frames by the destination address. - */ -#define M2M_ATE_RX_DISABLE_SA 0x0 -/*!< Filter selection for received frames: Disable filtering received frames by the source address. - */ -#define M2M_ATE_RX_ENABLE_SA 0x1 -/*!< Filter selection for received frames: Enable filtering received frames by the source address. - */ -#define M2M_ATE_DISABLE_SELF_MACADDR 0x0 -/*!\n",ret); - while(1); - } - //Initialize the OTA module - m2m_ota_init(OtaUpdateCb,NULL); - //connect to AP that provide connection to the OTA server - m2m_wifi_default_connect(); - - while(1) - { - - //Handle the app state machine plus the WINC event handler - while(m2m_wifi_handle_events(NULL) != M2M_SUCCESS) { - - } - - } -} -@endcode - -*/ -NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl); - /**@}*/ -/** @defgroup OtaStartUpdatefn m2m_ota_start_update_crt -* @ingroup WLANAPI -* Request OTA start for cortus application image using the downloaded URL, the OTA module will download the OTA image and ensure integrity of the image, -* and update the validity of the image in control structure. Switching to that image requires calling @ref m2m_ota_switch_crt API. -* As a prerequisite @ref m2m_ota_init should be called before using @ref m2m_ota_start_update_crt(). -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl); - -@param [in] u8DownloadUrl - The cortus application image url. -@warning - Calling this API does not guarantee cortus application image update, It depends on the connection with the download server and the validity of the image. - If the API response is failure this may invalidate the roll-back image if it was previously valid, since the WINC does not have any internal memory - except the flash roll-back image location to validate the downloaded image from - -@see - m2m_ota_init - tpfOtaUpdateCb - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl); - /**@}*/ -/** @defgroup OtaRollbackfn m2m_ota_rollback -* @ingroup WLANAPI - Request OTA Roll-back to the old (other) WINC image, the WINC firmware will check the validation of the Roll-back image - and switch to it if it is valid. - If the API response is success, system restart is required (re-initialize the driver with hardware rest) update the host driver version may - be required if it is did not match the minimum version supported by the WINC firmware. - -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ota_rollback(void); - -@sa - m2m_ota_init - m2m_ota_start_update - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_rollback(void); - /**@}*/ -/** @defgroup OtaRollbackfn m2m_ota_rollback_crt -* @ingroup WLANAPI - Request Cortus application OTA Roll-back to the old (other) cortus application image, the WINC firmware will check the validation of the Roll-back image - and switch to it if it is valid. - If the API response is success, system restart is required (re-initialize the driver with hardware rest) update the host driver version may - be required. - -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ota_rollback_crt(void); - -@sa - m2m_ota_init - m2m_ota_start_update_crt - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_rollback_crt(void); - /**@}*/ -/** @defgroup OtaAbortfn m2m_ota_abort -* @ingroup WLANAPI - Request abort of current OTA download. - The WINC firmware will terminate the OTA download if one is in progress. - If no download is in progress, the API will respond with failure. -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ota_abort(void); - -@return - The function returns @ref M2M_SUCCESS for successful operation and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_abort(void); - /**@}*/ - /**@}*/ -/** @defgroup OtaSwitchFirmware m2m_ota_switch_firmware -* @ingroup WLANAPI -* Switch to the upgraded Firmware, that API will update the control structure working image to the upgraded image - take effect will be on the next system restart -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ota_switch_firmware(void); - -@warning - It is important to note that if the API succeeds, system restart is required (re-initializing the driver with hardware reset) updating the host driver version may be required - if it does not match the minimum driver version supported by the WINC's firmware. -@sa - m2m_ota_init - m2m_ota_start_update - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_switch_firmware(void); - /**@}*/ - /**@}*/ -/** @defgroup OtaSwitchFirmware m2m_ota_switch_crt -* @ingroup WLANAPI -* Switch to the upgraded cortus application, that API will update the control structure working image to the upgraded image - take effect will be on the next system restart -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ota_switch_firmware(void); - -@warning - It is important to note that if the API succeeds, system restart is required (re-initializing the driver with hardware reset) updating the host driver version may be required - if it does not match the minimum driver version supported by the WINC's firmware. -@sa - m2m_ota_init - m2m_ota_start_update_crt - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_switch_crt(void); -/*! -@fn \ - NMI_API sint8 m2m_ota_get_firmware_version(void); - -@brief - Get the OTA Firmware version. - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_get_firmware_version(tstrM2mRev *pstrRev); - /**@}*/ -NMI_API sint8 m2m_ota_test(void); - -#ifdef __cplusplus -} -#endif -#endif /* __M2M_OTA_H__ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_periph.h b/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_periph.h deleted file mode 100644 index 1012882..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_periph.h +++ /dev/null @@ -1,411 +0,0 @@ -/** - * - * \file - * - * \brief WINC Peripherals Application Interface. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _M2M_PERIPH_H_ -#define _M2M_PERIPH_H_ - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -#include "common/include/nm_common.h" -#include "driver/include/m2m_types.h" - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*! -@struct \ - tstrPerphInitParam - -@brief - Peripheral module initialization parameters. -*/ -typedef struct { - void * arg; -} tstrPerphInitParam; - - -/*! -@enum \ - tenuGpioNum - -@brief - A list of GPIO numbers configurable through the m2m_periph module. -*/ -typedef enum { - M2M_PERIPH_GPIO3, /*!< GPIO15 pad */ - M2M_PERIPH_GPIO4, /*!< GPIO16 pad */ - M2M_PERIPH_GPIO5, /*!< GPIO18 pad */ - M2M_PERIPH_GPIO6, /*!< GPIO18 pad */ - M2M_PERIPH_GPIO15, /*!< GPIO15 pad */ - M2M_PERIPH_GPIO16, /*!< GPIO16 pad */ - M2M_PERIPH_GPIO18, /*!< GPIO18 pad */ - M2M_PERIPH_GPIO_MAX -} tenuGpioNum; - - -/*! -@enum \ - tenuI2cMasterSclMuxOpt - -@brief - Allowed pin multiplexing options for I2C master SCL signal. -*/ -typedef enum { - M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_HOST_WAKEUP, /*!< I2C master SCL is avaiable on HOST_WAKEUP. */ - M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_SD_DAT3, /*!< I2C master SCL is avaiable on SD_DAT3 (GPIO 7). */ - M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_GPIO13, /*!< I2C master SCL is avaiable on GPIO 13. */ - M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_GPIO4, /*!< I2C master SCL is avaiable on GPIO 4.*/ - M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_I2C_SCL, /*!< I2C master SCL is avaiable on I2C slave SCL. */ - M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_NUM -} tenuI2cMasterSclMuxOpt; - -/*! -@enum \ - tenuI2cMasterSdaMuxOpt - -@brief - Allowed pin multiplexing options for I2C master SDA signal. -*/ -typedef enum { - M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_RTC_CLK , /*!< I2C master SDA is avaiable on RTC_CLK. */ - M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_SD_CLK, /*!< I2C master SDA is avaiable on SD_CLK (GPIO 8). */ - M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_GPIO14, /*!< I2C master SDA is avaiable on GPIO 14. */ - M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_GPIO6, /*!< I2C master SDA is avaiable on GPIO 6.*/ - M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_I2C_SDA, /*!< I2C master SDA is avaiable on I2C slave SDA. */ - M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_NUM -} tenuI2cMasterSdaMuxOpt; - - -/*! -@struct \ - tstrI2cMasterInitParam - -@brief - I2C master configuration parameters. -@sa - tenuI2cMasterSclMuxOpt - tenuI2cMasterSdaMuxOpt -*/ -typedef struct { - uint8 enuSclMuxOpt; /*!< SCL multiplexing option. Allowed value are defined in tenuI2cMasterSclMuxOpt */ - uint8 enuSdaMuxOpt; /*!< SDA multiplexing option. Allowed value are defined in tenuI2cMasterSdaMuxOpt */ - uint8 u8ClkSpeedKHz; /*!< I2C master clock speed in KHz. */ -} tstrI2cMasterInitParam; - -/*! -@enum \ - tenuI2cMasterFlags - -@brief - Bitwise-ORed flags for use in m2m_periph_i2c_master_write and m2m_periph_i2c_master_read -@sa - m2m_periph_i2c_master_write - m2m_periph_i2c_master_read -*/ -typedef enum { - I2C_MASTER_NO_FLAGS = 0x00, - /*!< No flags. */ - I2C_MASTER_NO_STOP = 0x01, - /*!< No stop bit after this transaction. Useful for scattered buffer read/write operations. */ - I2C_MASTER_NO_START = 0x02, - /*!< No start bit at the beginning of this transaction. Useful for scattered buffer read/write operations.*/ -} tenuI2cMasterFlags; - -/*! -@enum \ - tenuPullupMask - -@brief - Bitwise-ORed flags for use in m2m_perph_pullup_ctrl. -@sa - m2m_periph_pullup_ctrl - -*/ -typedef enum { - M2M_PERIPH_PULLUP_DIS_HOST_WAKEUP = (1ul << 0), - M2M_PERIPH_PULLUP_DIS_RTC_CLK = (1ul << 1), - M2M_PERIPH_PULLUP_DIS_IRQN = (1ul << 2), - M2M_PERIPH_PULLUP_DIS_GPIO_3 = (1ul << 3), - M2M_PERIPH_PULLUP_DIS_GPIO_4 = (1ul << 4), - M2M_PERIPH_PULLUP_DIS_GPIO_5 = (1ul << 5), - M2M_PERIPH_PULLUP_DIS_SD_DAT3 = (1ul << 6), - M2M_PERIPH_PULLUP_DIS_SD_DAT2_SPI_RXD = (1ul << 7), - M2M_PERIPH_PULLUP_DIS_SD_DAT1_SPI_SSN = (1ul << 9), - M2M_PERIPH_PULLUP_DIS_SD_CMD_SPI_SCK = (1ul << 10), - M2M_PERIPH_PULLUP_DIS_SD_DAT0_SPI_TXD = (1ul << 11), - M2M_PERIPH_PULLUP_DIS_GPIO_6 = (1ul << 12), - M2M_PERIPH_PULLUP_DIS_SD_CLK = (1ul << 13), - M2M_PERIPH_PULLUP_DIS_I2C_SCL = (1ul << 14), - M2M_PERIPH_PULLUP_DIS_I2C_SDA = (1ul << 15), - M2M_PERIPH_PULLUP_DIS_GPIO_11 = (1ul << 16), - M2M_PERIPH_PULLUP_DIS_GPIO_12 = (1ul << 17), - M2M_PERIPH_PULLUP_DIS_GPIO_13 = (1ul << 18), - M2M_PERIPH_PULLUP_DIS_GPIO_14 = (1ul << 19), - M2M_PERIPH_PULLUP_DIS_GPIO_15 = (1ul << 20), - M2M_PERIPH_PULLUP_DIS_GPIO_16 = (1ul << 21), - M2M_PERIPH_PULLUP_DIS_GPIO_17 = (1ul << 22), - M2M_PERIPH_PULLUP_DIS_GPIO_18 = (1ul << 23), - M2M_PERIPH_PULLUP_DIS_GPIO_19 = (1ul << 24), - M2M_PERIPH_PULLUP_DIS_GPIO_20 = (1ul << 25), - M2M_PERIPH_PULLUP_DIS_GPIO_21 = (1ul << 26), - M2M_PERIPH_PULLUP_DIS_GPIO_22 = (1ul << 27), - M2M_PERIPH_PULLUP_DIS_GPIO_23 = (1ul << 28), - M2M_PERIPH_PULLUP_DIS_GPIO_24 = (1ul << 29), -} tenuPullupMask; - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -#ifdef __cplusplus - extern "C" { -#endif - -/*! -@fn \ - NMI_API sint8 m2m_periph_init(tstrPerphInitParam * param); - -@brief - Initialize the NMC1500 peripheral driver module. - -@param [in] param - Peripheral module initialization structure. See members of tstrPerphInitParam. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tstrPerphInitParam -*/ -NMI_API sint8 m2m_periph_init(tstrPerphInitParam * param); - -/*! -@fn \ - NMI_API sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir); - -@brief - Configure a specific NMC1500 pad as a GPIO and sets its direction (input or output). - -@param [in] u8GpioNum - GPIO number. Allowed values are defined in tenuGpioNum. - -@param [in] u8GpioDir - GPIO direction: Zero = input. Non-zero = output. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuGpioNum -*/ -NMI_API sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir); - -/*! -@fn \ - NMI_API sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal); - -@brief - Set an NMC1500 GPIO output level high or low. - -@param [in] u8GpioNum - GPIO number. Allowed values are defined in tenuGpioNum. - -@param [in] u8GpioVal - GPIO output value. Zero = low, non-zero = high. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuGpioNum -*/ -NMI_API sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal); - -/*! -@fn \ - NMI_API sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal); - -@brief - Read an NMC1500 GPIO input level. - -@param [in] u8GpioNum - GPIO number. Allowed values are defined in tenuGpioNum. - -@param [out] pu8GpioVal - GPIO input value. Zero = low, non-zero = high. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuGpioNum -*/ -NMI_API sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal); - -/*! -@fn \ - NMI_API sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn); - -@brief - Set an NMC1500 GPIO pullup resisitor enable or disable. - -@param [in] u8GpioNum - GPIO number. Allowed values are defined in tenuGpioNum. - -@param [in] u8PullupEn - Zero: pullup disabled. Non-zero: pullup enabled. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuGpioNum -*/ -NMI_API sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn); - -/*! -@fn \ - NMI_API sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param); - -@brief - Initialize and configure the NMC1500 I2C master peripheral. - -@param [in] param - I2C master initialization structure. See members of tstrI2cMasterInitParam. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tstrI2cMasterInitParam -*/ -NMI_API sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param); - -/*! -@fn \ - NMI_API sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags); - -@brief - Write a stream of bytes to the I2C slave device. - -@param [in] u8SlaveAddr - 7-bit I2C slave address. -@param [in] pu8Buf - A pointer to an input buffer which contains a stream of bytes. -@param [in] u16BufLen - Input buffer length in bytes. -@param [in] flags - Write operation bitwise-ORed flags. See tenuI2cMasterFlags. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuI2cMasterFlags -*/ -NMI_API sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags); - - -/*! -@fn \ - NMI_API sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags); - -@brief - Write a stream of bytes to the I2C slave device. - -@param [in] u8SlaveAddr - 7-bit I2C slave address. -@param [out] pu8Buf - A pointer to an output buffer in which a stream of bytes are received. -@param [in] u16BufLen - Max output buffer length in bytes. -@param [out] pu16ReadLen - Actual number of bytes received. -@param [in] flags - Write operation bitwise-ORed flags. See tenuI2cMasterFlags. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuI2cMasterFlags -*/ -NMI_API sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags); - - -/*! -@fn \ - NMI_API sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable); - -@brief - Control the programmable pull-up resistor on the chip pads . - - -@param [in] pinmask - Write operation bitwise-ORed mask for which pads to control. Allowed values are defined in tenuPullupMask. - -@param [in] enable - Set to 0 to disable pull-up resistor. Non-zero will enable the pull-up. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuPullupMask -*/ -NMI_API sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable); - -#ifdef __cplusplus -} -#endif - - -#endif /* _M2M_PERIPH_H_ */ \ No newline at end of file diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_ssl.h b/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_ssl.h deleted file mode 100644 index f5271f0..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_ssl.h +++ /dev/null @@ -1,182 +0,0 @@ -/** - * - * \file - * - * \brief WINC Application Interface Internal Types. - * - * Copyright (c) 2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/**@defgroup SSLAPI SSL -*/ - -#ifndef __M2M_SSL_H__ -#define __M2M_SSL_H__ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "common/include/nm_common.h" -#include "driver/include/m2m_types.h" -#include "driver/source/nmdrv.h" -#include "ecc_types.h" -#include "socket/include/socket.h" - -/**@defgroup SSLEnums Enumeration/Typedefs - * @ingroup SSLAPI - * @{*/ - -/*! -@typedef \ - void (*tpfAppSslCb) (uint8 u8MsgType, void * pvMsg); - -@brief A callback to get SSL notifications. - -@param[in] u8MsgType -@param[in] pvMsg A structure to provide notification payload. -*/ -typedef void (*tpfAppSSLCb) (uint8 u8MsgType, void * pvMsg); - -/**@} -*/ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/** \defgroup SSLFUNCTIONS Functions -* @ingroup SSLAPI -*/ - -/**@{*/ -/*! - @fn \ m2m_ssl_init(tpfAppSslCb pfAppSslCb); - @brief Initializes the SSL layer. - @param [in] pfAppSslCb - Application SSL callback function. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_init(tpfAppSSLCb pfAppSSLCb); - -/*! - @fn \ NMI_API sint8 m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz) - @brief Sends ECC responses to the WINC - @param [in] strECCResp - ECC Response struct. - @param [in] pu8RspDataBuffe - Pointer of the response data to be sent. - @param [in] u16RspDataSz - Response data size. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz); - -/*! - @fn \ NMI_API sint8 m2m_ssl_send_certs_to_winc(uint8* pu8Buffer, uint32 u32BufferSz) - @brief Sends certificates to the WINC - @param [in] pu8Buffer - Pointer to the certificates. - @param [in] u32BufferSz - Size of the certificates. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_send_certs_to_winc(uint8* pu8Buffer, uint32 u32BufferSz); - -/*! - @fn \ NMI_API sint8 m2m_ssl_retrieve_cert(uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key) - @brief Retrieve the certificate to be verified from the WINC - @param [in] pu16CurveType - Pointer to the certificate curve type. - @param [in] pu8Hash - Pointer to the certificate hash. - @param [in] pu8Sig - Pointer to the certificate signature. - @param [in] pu8Key - Pointer to the certificate Key. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_retrieve_cert(uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key); - -/*! - @fn \ NMI_API sint8 m2m_ssl_retrieve_hash(uint8* pu8Hash, uint16 u16HashSz) - @brief Retrieve the certificate hash - @param [in] pu8Hash - Pointer to the certificate hash. - @param [in] u16HashSz - Hash size. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_retrieve_hash(uint8* pu8Hash, uint16 u16HashSz); - -/*! - @fn \ NMI_API void m2m_ssl_stop_processing_certs(void) - @brief Allow ssl driver to tidy up in case application does not read all available certificates. - @warning This API must only be called if some certificates are left unread. - @return None. -*/ -NMI_API void m2m_ssl_stop_processing_certs(void); - -/*! - @fn \ NMI_API void m2m_ssl_ecc_process_done(void) - @brief Allow ssl driver to tidy up after application has finished processing ecc message. - @warning This API must be called after receiving a SSL callback with type @ref M2M_SSL_REQ_ECC - @return None. -*/ -NMI_API void m2m_ssl_ecc_process_done(void); - -/*! -@fn \ - NMI_API sint8 m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP); - Override the default Active SSL ciphers in the SSL module with a certain combination selected by the caller in the form of - a bitmap containing the required ciphers to be on. - There is no need to call this function if the application will not change the default ciphersuites. - -@param [in] u32SslCsBMP - Bitmap containing the desired ciphers to be enabled for the SSL module. The ciphersuites are defined in - @ref SSLCipherSuiteID. - The default ciphersuites are all ciphersuites supported by the firmware with the exception of ECC ciphersuites. - The caller can override the default with any desired combination, except for combinations involving both RSA - and ECC; if any RSA ciphersuite is enabled, then firmware will disable all ECC ciphersuites. - If u32SslCsBMP does not contain any ciphersuites supported by firmware, then the current active list will not - be changed. - -@return - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) -*/ -sint8 m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP); - - /**@}*/ -#endif /* __M2M_SSL_H__ */ \ No newline at end of file diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_types.h b/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_types.h deleted file mode 100644 index a847f3f..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_types.h +++ /dev/null @@ -1,2383 +0,0 @@ -/** - * - * \file - * - * \brief WINC Application Interface Internal Types. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef __M2M_WIFI_TYPES_H__ -#define __M2M_WIFI_TYPES_H__ - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#ifndef _BOOT_ -#ifndef _FIRMWARE_ -#include "common/include/nm_common.h" -#else -#include "m2m_common.h" -#endif -#endif - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/**@defgroup WlanDefines Defines - * @ingroup m2m_wifi - */ -/**@{*/ -#define M2M_MAJOR_SHIFT (8) -#define M2M_MINOR_SHIFT (4) -#define M2M_PATCH_SHIFT (0) - -#define M2M_DRV_VERSION_SHIFT (16) -#define M2M_FW_VERSION_SHIFT (0) - -#define M2M_GET_MAJOR(ver_info_hword) ((uint8)((ver_info_hword) >> M2M_MAJOR_SHIFT) & 0xff) -#define M2M_GET_MINOR(ver_info_hword) ((uint8)((ver_info_hword) >> M2M_MINOR_SHIFT) & 0x0f) -#define M2M_GET_PATCH(ver_info_hword) ((uint8)((ver_info_hword) >> M2M_PATCH_SHIFT) & 0x0f) - -#define M2M_GET_FW_VER(ver_info_word) ((uint16) ((ver_info_word) >> M2M_FW_VERSION_SHIFT)) -#define M2M_GET_DRV_VER(ver_info_word) ((uint16) ((ver_info_word) >> M2M_DRV_VERSION_SHIFT)) - -#define M2M_GET_DRV_MAJOR(ver_info_word) M2M_GET_MAJOR(M2M_GET_DRV_VER(ver_info_word)) -#define M2M_GET_DRV_MINOR(ver_info_word) M2M_GET_MINOR(M2M_GET_DRV_VER(ver_info_word)) -#define M2M_GET_DRV_PATCH(ver_info_word) M2M_GET_PATCH(M2M_GET_DRV_VER(ver_info_word)) - -#define M2M_GET_FW_MAJOR(ver_info_word) M2M_GET_MAJOR(M2M_GET_FW_VER(ver_info_word)) -#define M2M_GET_FW_MINOR(ver_info_word) M2M_GET_MINOR(M2M_GET_FW_VER(ver_info_word)) -#define M2M_GET_FW_PATCH(ver_info_word) M2M_GET_PATCH(M2M_GET_FW_VER(ver_info_word)) - -#define M2M_MAKE_VERSION(major, minor, patch) ( \ - ((uint16)((major) & 0xff) << M2M_MAJOR_SHIFT) | \ - ((uint16)((minor) & 0x0f) << M2M_MINOR_SHIFT) | \ - ((uint16)((patch) & 0x0f) << M2M_PATCH_SHIFT)) - -#define M2M_MAKE_VERSION_INFO(fw_major, fw_minor, fw_patch, drv_major, drv_minor, drv_patch) \ - ( \ - ( ((uint32)M2M_MAKE_VERSION((fw_major), (fw_minor), (fw_patch))) << M2M_FW_VERSION_SHIFT) | \ - ( ((uint32)M2M_MAKE_VERSION((drv_major), (drv_minor), (drv_patch))) << M2M_DRV_VERSION_SHIFT)) - -#define REL_19_5_2_VER M2M_MAKE_VERSION_INFO(19,5,2,19,3,0) -#define REL_19_5_1_VER M2M_MAKE_VERSION_INFO(19,5,1,19,3,0) -#define REL_19_5_0_VER M2M_MAKE_VERSION_INFO(19,5,0,19,3,0) -#define REL_19_4_6_VER M2M_MAKE_VERSION_INFO(19,4,6,19,3,0) -#define REL_19_4_5_VER M2M_MAKE_VERSION_INFO(19,4,5,19,3,0) -#define REL_19_4_4_VER M2M_MAKE_VERSION_INFO(19,4,4,19,3,0) -#define REL_19_4_3_VER M2M_MAKE_VERSION_INFO(19,4,3,19,3,0) -#define REL_19_4_2_VER M2M_MAKE_VERSION_INFO(19,4,2,19,3,0) -#define REL_19_4_1_VER M2M_MAKE_VERSION_INFO(19,4,1,19,3,0) -#define REL_19_4_0_VER M2M_MAKE_VERSION_INFO(19,4,0,19,3,0) -#define REL_19_3_1_VER M2M_MAKE_VERSION_INFO(19,3,1,19,3,0) -#define REL_19_3_0_VER M2M_MAKE_VERSION_INFO(19,3,0,19,3,0) -#define REL_19_2_2_VER M2M_MAKE_VERSION_INFO(19,2,2,19,2,0) -#define REL_19_2_1_VER M2M_MAKE_VERSION_INFO(19,2,1,19,2,0) -#define REL_19_2_0_VER M2M_MAKE_VERSION_INFO(19,2,0,19,2,0) -#define REL_19_1_0_VER M2M_MAKE_VERSION_INFO(19,1,0,18,2,0) -#define REL_19_0_0_VER M2M_MAKE_VERSION_INFO(19,0,0,18,1,1) - -/*======*======*======*======* - FIRMWARE VERSION NO INFO - *======*======*======*======*/ - -#define M2M_RELEASE_VERSION_MAJOR_NO (19) -/*!< Firmware Major release version number. -*/ - - -#define M2M_RELEASE_VERSION_MINOR_NO (5) -/*!< Firmware Minor release version number. -*/ - -#define M2M_RELEASE_VERSION_PATCH_NO (2) -/*!< Firmware patch release version number. -*/ - -/*======*======*======*======* - SUPPORTED DRIVER VERSION NO INFO - *======*======*======*======*/ - -#define M2M_MIN_REQ_DRV_VERSION_MAJOR_NO (19) -/*!< Driver Major release version number. -*/ - - -#define M2M_MIN_REQ_DRV_VERSION_MINOR_NO (3) -/*!< Driver Minor release version number. -*/ - -#define M2M_MIN_REQ_DRV_VERSION_PATCH_NO (0) -/*!< Driver patch release version number. -*/ - -#define M2M_MIN_REQ_DRV_SVN_VERSION (0) -/*!< Driver svn version. -*/ - - - -#if !defined(M2M_RELEASE_VERSION_MAJOR_NO) || !defined(M2M_RELEASE_VERSION_MINOR_NO) -#error Undefined version number -#endif - -#define M2M_BUFFER_MAX_SIZE (1600UL - 4) -/*!< Maximum size for the shared packet buffer. - */ - - -#define M2M_MAC_ADDRES_LEN 6 -/*!< The size fo 802 MAC address. - */ - -#define M2M_ETHERNET_HDR_OFFSET 34 -/*!< The offset of the Ethernet header within the WLAN Tx Buffer. - */ - - -#define M2M_ETHERNET_HDR_LEN 14 -/*!< Length of the Etherenet header in bytes. -*/ - - -#define M2M_MAX_SSID_LEN 33 -/*!< Maximum size for the Wi-Fi SSID including the NULL termination. - */ - - -#define M2M_MAX_PSK_LEN 65 -/*!< Maximum size for the WPA PSK including the NULL termination. - */ - -#define M2M_MIN_PSK_LEN 9 -/*!< Maximum size for the WPA PSK including the NULL termination. - */ - -#define M2M_DEVICE_NAME_MAX 48 -/*!< Maximum Size for the device name including the NULL termination. - */ - - -#define M2M_LISTEN_INTERVAL 1 -/*!< The STA uses the Listen Interval parameter to indicate to the AP how - many beacon intervals it shall sleep before it retrieves the queued frames - from the AP. -*/ - -#define MAX_HIDDEN_SITES 4 -/*!< - max number of hidden SSID suuported by scan request -*/ - - -#define M2M_1X_USR_NAME_MAX 21 -/*!< The maximum size of the user name including the NULL termination. - It is used for RADIUS authentication in case of connecting the device to - an AP secured with WPA-Enterprise. -*/ - - -#define M2M_1X_PWD_MAX 41 -/*!< The maximum size of the password including the NULL termination. - It is used for RADIUS authentication in case of connecting the device to - an AP secured with WPA-Enterprise. -*/ - -#define M2M_CUST_IE_LEN_MAX 252 -/*!< The maximum size of IE (Information Element). -*/ - -#define PWR_DEFAULT PWR_HIGH -/********************* - * - * WIFI GROUP requests - */ - -#define M2M_CONFIG_CMD_BASE 1 -/*!< The base value of all the host configuration commands opcodes. -*/ -#define M2M_STA_CMD_BASE 40 -/*!< The base value of all the station mode host commands opcodes. -*/ -#define M2M_AP_CMD_BASE 70 -/*!< The base value of all the Access Point mode host commands opcodes. -*/ -#define M2M_P2P_CMD_BASE 90 -/*!< The base value of all the P2P mode host commands opcodes. -*/ -#define M2M_SERVER_CMD_BASE 100 -/*!< The base value of all the power save mode host commands codes. -*/ -/********************** - * OTA GROUP requests - */ -#define M2M_OTA_CMD_BASE 100 -/*!< The base value of all the OTA mode host commands opcodes. - * The OTA Have special group so can extended from 1-M2M_MAX_GRP_NUM_REQ -*/ -/*********************** - * - * CRYPTO group requests - */ -#define M2M_CRYPTO_CMD_BASE 1 -/*!< The base value of all the crypto mode host commands opcodes. - * The crypto Have special group so can extended from 1-M2M_MAX_GRP_NUM_REQ -*/ - -#define M2M_MAX_GRP_NUM_REQ (127) -/*!< max number of request in one group equal to 127 as the last bit reserved for config or data pkt -*/ - -#define WEP_40_KEY_STRING_SIZE ((uint8)10) -/*!< Indicate the wep key size in bytes for 40 bit string passphrase. -*/ - -#define WEP_104_KEY_STRING_SIZE ((uint8)26) -/*!< Indicate the wep key size in bytes for 104 bit string passphrase. -*/ -#define WEP_KEY_MAX_INDEX ((uint8)4) -/*!< Indicate the max key index value for WEP authentication -*/ -#define M2M_SHA256_CONTEXT_BUFF_LEN (128) -/*!< sha256 context size -*/ -#define M2M_SCAN_DEFAULT_NUM_SLOTS (2) -/*!< The default. number of scan slots performed by the WINC board. -*/ -#define M2M_SCAN_DEFAULT_SLOT_TIME (30) -/*!< The default. duration in miliseconds of a scan slots performed by the WINC board. -*/ -#define M2M_SCAN_DEFAULT_NUM_PROBE (2) -/*!< The default. number of scan slots performed by the WINC board. -*/ - - -/*======*======*======*======* - CONNECTION ERROR DEFINITIONS - *======*======*======*======*/ -typedef enum { - M2M_DEFAULT_CONN_INPROGRESS = ((sint8)-23), - /*!< - A failure that indicates that a default connection or forced connection is in progress - */ - M2M_DEFAULT_CONN_FAIL, - /*!< - A failure response that indicates that the winc failed to connect to the cached network - */ - M2M_DEFAULT_CONN_SCAN_MISMATCH, - /*!< - A failure response that indicates that no one of the cached networks - was found in the scan results, as a result to the function call m2m_default_connect. - */ - M2M_DEFAULT_CONN_EMPTY_LIST - /*!< - A failure response that indicates an empty network list as - a result to the function call m2m_default_connect. - */ - -}tenuM2mDefaultConnErrcode; - - - -/*======*======*======*======* - TLS DEFINITIONS - *======*======*======*======*/ -#define TLS_FILE_NAME_MAX 48 -/*!< Maximum length for each TLS certificate file name including null terminator. -*/ -#define TLS_SRV_SEC_MAX_FILES 8 -/*!< Maximum number of certificates allowed in TLS_SRV section. -*/ -#define TLS_SRV_SEC_START_PATTERN_LEN 8 -/*!< Length of certificate struct start pattern. -*/ -/*======*======*======*======* - OTA DEFINITIONS - *======*======*======*======*/ - -#define OTA_STATUS_VALID (0x12526285) -/*!< - Magic value updated in the Control structure in case of ROLLACK image Valid -*/ -#define OTA_STATUS_INVALID (0x23987718) -/*!< - Magic value updated in the Control structure in case of ROLLACK image InValid -*/ -#define OTA_MAGIC_VALUE (0x1ABCDEF9) -/*!< - Magic value set at the beginning of the OTA image header -*/ -#define M2M_MAGIC_APP (0xef522f61UL) -/*!< - Magic value set at the beginning of the Cortus OTA image header -*/ - -#define OTA_FORMAT_VER_0 (0) /*Till 19.2.2 format*/ -#define OTA_FORMAT_VER_1 (1) /*starting from 19.3.0 CRC is used and sequence number is used*/ -/*!< - Control structure format version -*/ -#define OTA_SHA256_DIGEST_SIZE (32) -/*!< - Sha256 digest size in the OTA image, - the sha256 digest is set at the beginning of image before the OTA header - */ - -/*======*======*======*======* - SSL DEFINITIONS - *======*======*======*======*/ - -#define TLS_CRL_DATA_MAX_LEN 64 -/* Every bit have 3dB gain control each. - for example: - 1 ->3db - 3 ->6db - 7 ->9db - */ - uint16 u8PPAGFor11GN; - /*!< PPA gain for 11GN (as the RF document represented) - PPA_AGC<0:2> Every bit have 3dB gain control each. - for example: - 1 ->3db - 3 ->6db - 7 ->9db - */ -}tstrM2mWifiGainsParams; - -/*! -@struct \ - tstrM2mWifiWepParams - -@brief - WEP security key parameters. -*/ -typedef struct{ - uint8 u8KeyIndx; - /*!< Wep key Index. - */ - uint8 u8KeySz; - /*!< Wep key Size. - */ - uint8 au8WepKey[WEP_104_KEY_STRING_SIZE + 1]; - /*!< WEP Key represented as a NULL terminated ASCII string. - */ - uint8 __PAD24__[3]; - /*!< Padding bytes to keep the structure word alligned. - */ -}tstrM2mWifiWepParams; - - -/*! -@struct \ - tstr1xAuthCredentials - -@brief - Credentials for the user to authenticate with the AAA server (WPA-Enterprise Mode IEEE802.1x). -*/ -typedef struct{ - uint8 au8UserName[M2M_1X_USR_NAME_MAX]; - /*!< User Name. It must be Null terminated string. - */ - uint8 au8Passwd[M2M_1X_PWD_MAX]; - /*!< Password corresponding to the user name. It must be Null terminated string. - */ -}tstr1xAuthCredentials; - - -/*! -@union \ - tuniM2MWifiAuth - -@brief - Wi-Fi Security Parameters for all supported security modes. -*/ -typedef union{ - uint8 au8PSK[M2M_MAX_PSK_LEN]; - /*!< Pre-Shared Key in case of WPA-Personal security. - */ - tstr1xAuthCredentials strCred1x; - /*!< Credentials for RADIUS server authentication in case of WPA-Enterprise security. - */ - tstrM2mWifiWepParams strWepInfo; - /*!< WEP key parameters in case of WEP security. - */ -}tuniM2MWifiAuth; - - -/*! -@struct \ - tstrM2MWifiSecInfo - -@brief - Authentication credentials to connect to a Wi-Fi network. -*/ -typedef struct{ - tuniM2MWifiAuth uniAuth; - /*!< Union holding all possible authentication parameters corresponding the current security types. - */ - uint8 u8SecType; - /*!< Wi-Fi network security type. See tenuM2mSecType for supported security types. - */ -#define __PADDING__ (4 - ((sizeof(tuniM2MWifiAuth) + 1) % 4)) - uint8 __PAD__[__PADDING__]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2MWifiSecInfo; - - -/*! -@struct \ - tstrM2mWifiConnect - -@brief - Wi-Fi Connect Request -*/ -typedef struct{ - tstrM2MWifiSecInfo strSec; - /*!< Security parameters for authenticating with the AP. - */ - uint16 u16Ch; - /*!< RF Channel for the target SSID. - */ - uint8 au8SSID[M2M_MAX_SSID_LEN]; - /*!< SSID of the desired AP. It must be NULL terminated string. - */ - uint8 u8NoSaveCred; -#define __CONN_PAD_SIZE__ (4 - ((sizeof(tstrM2MWifiSecInfo) + M2M_MAX_SSID_LEN + 3) % 4)) - uint8 __PAD__[__CONN_PAD_SIZE__]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mWifiConnect; - - -/*! -@struct \ - tstrM2MWPSConnect - -@brief - WPS Configuration parameters - -@sa - tenuWPSTrigger -*/ -typedef struct { - uint8 u8TriggerType; - /*!< WPS triggering method (Push button or PIN) - */ - char acPinNumber[8]; - /*!< WPS PIN No (for PIN method) - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2MWPSConnect; - - -/*! -@struct \ - tstrM2MWPSInfo - -@brief WPS Result - - This structure is passed to the application in response to a WPS request. If the WPS session is completed successfully, the - structure will have Non-ZERO authentication type. If the WPS Session fails (due to error or timeout) the authentication type - is set to ZERO. - -@sa - tenuM2mSecType -*/ -typedef struct{ - uint8 u8AuthType; - /*!< Network authentication type. - */ - uint8 u8Ch; - /*!< RF Channel for the AP. - */ - uint8 au8SSID[M2M_MAX_SSID_LEN]; - /*!< SSID obtained from WPS. - */ - uint8 au8PSK[M2M_MAX_PSK_LEN]; - /*!< PSK for the network obtained from WPS. - */ -}tstrM2MWPSInfo; - - -/*! -@struct \ - tstrM2MDefaultConnResp - -@brief - Response error of the m2m_default_connect - -@sa - M2M_DEFAULT_CONN_SCAN_MISMATCH - M2M_DEFAULT_CONN_EMPTY_LIST -*/ -typedef struct{ - sint8 s8ErrorCode; - /*!< - Default connect error code. possible values are: - - M2M_DEFAULT_CONN_EMPTY_LIST - - M2M_DEFAULT_CONN_SCAN_MISMATCH - */ - uint8 __PAD24__[3]; -}tstrM2MDefaultConnResp; - -/*! -@struct \ - tstrM2MScanOption - -@brief - Scan options and configurations. - -@sa - tenuM2mScanCh - tstrM2MScan -*/ -typedef struct { - uint8 u8NumOfSlot; - /*|< The min number of slots is 2 for every channel, - every slot the soc will send Probe Request on air, and wait/listen for PROBE RESP/BEACONS for the u16slotTime - */ - uint8 u8SlotTime; - /*|< the time that the Soc will wait on every channel listening to the frames on air - when that time increaseed number of AP will increased in the scan results - min time is 10 ms and the max is 250 ms - */ - uint8 u8ProbesPerSlot; - /*!< Number of probe requests to be sent per channel scan slot. - */ - sint8 s8RssiThresh; - /*! < The RSSI threshold of the AP which will be connected to directly. - */ - -}tstrM2MScanOption; - -/*! -@struct \ - tstrM2MScanRegion - -@brief - Wi-Fi channel regulation region information. - -@sa - tenuM2mScanRegion -*/ -typedef struct { - uint16 u16ScanRegion; - /*|< Specifies the number of channels allowed in the region (e.g. North America = 11 ... etc.). - */ - uint8 __PAD16__[2]; - -}tstrM2MScanRegion; - -/*! -@struct \ - tstrM2MScan - -@brief - Wi-Fi Scan Request - -@sa - tenuM2mScanCh - tstrM2MScanOption -*/ -typedef struct { - uint8 u8ChNum; - /*!< The Wi-Fi RF Channel number - */ - uint8 __RSVD8__[1]; - /*!< Reserved for future use. - */ - uint16 u16PassiveScanTime; - /*!< Passive Scan Timeout in ms. The field is ignored for active scan. - */ -}tstrM2MScan; - -/*! -@struct \ - tstrCyptoResp - -@brief - crypto response -*/ -typedef struct { - sint8 s8Resp; - /***/ - uint8 __PAD24__[3]; - /* - */ -}tstrCyptoResp; - - -/*! -@struct \ - tstrM2mScanDone - -@brief - Wi-Fi Scan Result -*/ -typedef struct{ - uint8 u8NumofCh; - /*!< Number of found APs - */ - sint8 s8ScanState; - /*!< Scan status - */ - uint8 __PAD16__[2]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mScanDone; - - -/*! -@struct \ - tstrM2mReqScanResult - -@brief Scan Result Request - - The Wi-Fi Scan results list is stored in Firmware. The application can request a certain scan result by its index. -*/ -typedef struct { - uint8 u8Index; - /*!< Index of the desired scan result - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mReqScanResult; - - -/*! -@struct \ - tstrM2mWifiscanResult - -@brief Wi-Fi Scan Result - - Information corresponding to an AP in the Scan Result list identified by its order (index) in the list. -*/ -typedef struct { - uint8 u8index; - /*!< AP index in the scan result list. - */ - sint8 s8rssi; - /*!< AP signal strength. - */ - uint8 u8AuthType; - /*!< AP authentication type. - */ - uint8 u8ch; - /*!< AP RF channel. - */ - uint8 au8BSSID[6]; - /*!< BSSID of the AP. - */ - uint8 au8SSID[M2M_MAX_SSID_LEN]; - /*!< AP ssid. - */ - uint8 _PAD8_; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mWifiscanResult; - - -/*! -@struct \ - tstrM2mWifiStateChanged - -@brief - Wi-Fi Connection State - -@sa - M2M_WIFI_DISCONNECTED, M2M_WIFI_CONNECTED, M2M_WIFI_REQ_CON_STATE_CHANGED,tenuM2mConnChangedErrcode -*/ -typedef struct { - uint8 u8CurrState; - /*!< Current Wi-Fi connection state - */ - uint8 u8ErrCode; - /*!< Error type review tenuM2mConnChangedErrcode - */ - uint8 __PAD16__[2]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mWifiStateChanged; - - -/*! -@struct \ - tstrM2mPsType - -@brief - Power Save Configuration - -@sa - tenuPowerSaveModes -*/ -typedef struct{ - uint8 u8PsType; - /*!< Power save operating mode - */ - uint8 u8BcastEn; - /*!< - */ - uint8 __PAD16__[2]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mPsType; - -/*! -@struct \ - tstrM2mSlpReqTime - -@brief - Manual power save request sleep time - -*/ -typedef struct { - /*!< Sleep time in ms - */ - uint32 u32SleepTime; - -} tstrM2mSlpReqTime; - -/*! -@struct \ - tstrM2mLsnInt - -@brief Listen interval - - It is the value of the Wi-Fi STA listen interval for power saving. It is given in units of Beacon period. - Periodically after the listen interval fires, the WINC is wakeup and listen to the beacon and check for any buffered frames for it from the AP. -*/ -typedef struct { - uint16 u16LsnInt; - /*!< Listen interval in Beacon period count. - */ - uint8 __PAD16__[2]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mLsnInt; - - -/*! -@struct \ - tstrM2MWifiMonitorModeCtrl - -@brief Wi-Fi Monitor Mode Filter - - This structure sets the filtering criteria for WLAN packets when monitoring mode is enable. - The received packets matching the filtering parameters, are passed directly to the application. -*/ -typedef struct{ - uint8 u8ChannelID; - /* !< RF Channel ID. It must use values from tenuM2mScanCh - */ - uint8 u8FrameType; - /*!< It must use values from tenuWifiFrameType. - */ - uint8 u8FrameSubtype; - /*!< It must use values from tenuSubTypes. - */ - uint8 au8SrcMacAddress[6]; - /* ZERO means DO NOT FILTER Source address. - */ - uint8 au8DstMacAddress[6]; - /* ZERO means DO NOT FILTER Destination address. - */ - uint8 au8BSSID[6]; - /* ZERO means DO NOT FILTER BSSID. - */ - uint8 u8EnRecvHdr; - /* - Enable recv the full hder before the payload - */ - uint8 __PAD16__[2]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2MWifiMonitorModeCtrl; - - -/*! -@struct \ - tstrM2MWifiRxPacketInfo - -@brief Wi-Fi RX Frame Header - - The M2M application has the ability to allow Wi-Fi monitoring mode for receiving all Wi-Fi Raw frames matching a well defined filtering criteria. - When a target Wi-Fi packet is received, the header information are extracted and assigned in this structure. -*/ -typedef struct{ - uint8 u8FrameType; - /*!< It must use values from tenuWifiFrameType. - */ - uint8 u8FrameSubtype; - /*!< It must use values from tenuSubTypes. - */ - uint8 u8ServiceClass; - /*!< Service class from Wi-Fi header. - */ - uint8 u8Priority; - /*!< Priority from Wi-Fi header. - */ - uint8 u8HeaderLength; - /*!< Frame Header length. - */ - uint8 u8CipherType; - /*!< Encryption type for the rx packet. - */ - uint8 au8SrcMacAddress[6]; - /* ZERO means DO NOT FILTER Source address. - */ - uint8 au8DstMacAddress[6]; - /* ZERO means DO NOT FILTER Destination address. - */ - uint8 au8BSSID[6]; - /* ZERO means DO NOT FILTER BSSID. - */ - uint16 u16DataLength; - /*!< Data payload length (Header excluded). - */ - uint16 u16FrameLength; - /*!< Total frame length (Header + Data). - */ - uint32 u32DataRateKbps; - /*!< Data Rate in Kbps. - */ - sint8 s8RSSI; - /*!< RSSI. - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2MWifiRxPacketInfo; - - -/*! -@struct \ - tstrM2MWifiTxPacketInfo - -@brief Wi-Fi TX Packet Info - - The M2M Application has the ability to compose a RAW Wi-Fi frames (under the application responsibility). - When transmitting a Wi-Fi packet, the application must supply the firmware with this structure for sending the target frame. -*/ -typedef struct{ - uint16 u16PacketSize; - /*!< Wlan frame length. - */ - uint16 u16HeaderLength; - /*!< Wlan frame header length. - */ -}tstrM2MWifiTxPacketInfo; - - -/*! - @struct \ - tstrM2MP2PConnect - - @brief - Set the device to operate in the Wi-Fi Direct (P2P) mode. -*/ -typedef struct { - uint8 u8ListenChannel; - /*!< P2P Listen Channel (1, 6 or 11) - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2MP2PConnect; - -/*! -@struct \ - tstrM2MAPConfig - -@brief AP Configuration - - This structure holds the configuration parameters for the M2M AP mode. It should be set by the application when - it requests to enable the M2M AP operation mode. The M2M AP mode currently supports only WEP security (with - the NO Security option available of course). -*/ -typedef struct { - /*!< - Configuration parameters for the WiFi AP. - */ - uint8 au8SSID[M2M_MAX_SSID_LEN]; - /*!< AP SSID - */ - uint8 u8ListenChannel; - /*!< Wi-Fi RF Channel which the AP will operate on - */ - uint8 u8KeyIndx; - /*!< Wep key Index - */ - uint8 u8KeySz; - /*!< Wep/WPA key Size - */ - uint8 au8WepKey[WEP_104_KEY_STRING_SIZE + 1]; - /*!< Wep key - */ - uint8 u8SecType; - /*!< Security type: Open or WEP or WPA in the current implementation - */ - uint8 u8SsidHide; - /*!< SSID Status "Hidden(1)/Visible(0)" - */ - uint8 au8DHCPServerIP[4]; - /*!< Ap IP server address - */ - uint8 au8Key[M2M_MAX_PSK_LEN]; - /*!< WPA key - */ - uint8 __PAD24__[2]; - /*!< Padding bytes for forcing alignment - */ -}tstrM2MAPConfig; - - -/*! -@struct \ - tstrM2mServerInit - -@brief - PS Server initialization. -*/ -typedef struct { - uint8 u8Channel; - /*!< Server Listen channel - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mServerInit; - - -/*! -@struct \ - tstrM2mClientState - -@brief - PS Client State. -*/ -typedef struct { - uint8 u8State; - /*!< PS Client State - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mClientState; - - -/*! -@struct \ - tstrM2Mservercmd - -@brief - PS Server CMD -*/ -typedef struct { - uint8 u8cmd; - /*!< PS Server Cmd - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2Mservercmd; - - -/*! -@struct \ - tstrM2mSetMacAddress - -@brief - Sets the MAC address from application. The WINC load the mac address from the effuse by default to the WINC configuration memory, - but that function is used to let the application overwrite the configuration memory with the mac address from the host. - -@note - It's recommended to call this only once before calling connect request and after the m2m_wifi_init -*/ -typedef struct { - uint8 au8Mac[6]; - /*!< MAC address array - */ - uint8 __PAD16__[2]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mSetMacAddress; - - -/*! -@struct \ - tstrM2MDeviceNameConfig - -@brief Device name - - It is assigned by the application. It is used mainly for Wi-Fi Direct device - discovery and WPS device information. -*/ -typedef struct { - uint8 au8DeviceName[M2M_DEVICE_NAME_MAX]; - /*!< NULL terminated device name - */ -}tstrM2MDeviceNameConfig; - - -/*! -@struct \ - tstrM2MIPConfig - -@brief - Static IP configuration. - -@note - All member IP addresses are expressed in Network Byte Order (eg. "192.168.10.1" will be expressed as 0x010AA8C0). - */ -typedef struct { - uint32 u32StaticIP; - /*!< The static IP assigned to the device. - */ - uint32 u32Gateway; - /*!< IP of the Default internet gateway. - */ - uint32 u32DNS; - /*!< IP for the DNS server. - */ - uint32 u32SubnetMask; - /*!< Subnet mask for the local area network. - */ - uint32 u32DhcpLeaseTime; - /*!< Dhcp Lease Time in sec - */ -} tstrM2MIPConfig; - -/*! -@struct \ - tstrM2mIpRsvdPkt - -@brief - Received Packet Size and Data Offset - - */ -typedef struct{ - uint16 u16PktSz; - uint16 u16PktOffset; -} tstrM2mIpRsvdPkt; - - -/*! -@struct \ - tstrM2MProvisionModeConfig - -@brief - M2M Provisioning Mode Configuration - */ - -typedef struct { - tstrM2MAPConfig strApConfig; - /*!< - Configuration parameters for the WiFi AP. - */ - char acHttpServerDomainName[64]; - /*!< - The device domain name for HTTP provisioning. - */ - uint8 u8EnableRedirect; - /*!< - A flag to enable/disable HTTP redirect feature for the HTTP Provisioning server. If the Redirect is enabled, - all HTTP traffic (http://URL) from the device associated with WINC AP will be redirected to the HTTP Provisioning Web page. - - 0 : Disable HTTP Redirect. - - 1 : Enable HTTP Redirect. - */ - uint8 __PAD24__[3]; -}tstrM2MProvisionModeConfig; - - -/*! -@struct \ - tstrM2MProvisionInfo - -@brief - M2M Provisioning Information obtained from the HTTP Provisioning server. - */ -typedef struct{ - uint8 au8SSID[M2M_MAX_SSID_LEN]; - /*!< - Provisioned SSID. - */ - uint8 au8Password[M2M_MAX_PSK_LEN]; - /*!< - Provisioned Password. - */ - uint8 u8SecType; - /*!< - Wifi Security type. - */ - uint8 u8Status; - /*!< - Provisioning status. It must be checked before reading the provisioning information. It may be - - M2M_SUCCESS : Provision successful. - - M2M_FAIL : Provision Failed. - */ -}tstrM2MProvisionInfo; - - -/*! -@struct \ - tstrM2MConnInfo - -@brief - M2M Provisioning Information obtained from the HTTP Provisioning server. - */ -typedef struct{ - char acSSID[M2M_MAX_SSID_LEN]; - /*!< AP connection SSID name */ - uint8 u8SecType; - /*!< Security type */ - uint8 au8IPAddr[4]; - /*!< Connection IP address */ - uint8 au8MACAddress[6]; - /*!< MAC address of the peer Wi-Fi station */ - sint8 s8RSSI; - /*!< Connection RSSI signal */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment */ -}tstrM2MConnInfo; - -/*! -@struct \ - tstrOtaInitHdr - -@brief - OTA Image Header - */ - -typedef struct{ - uint32 u32OtaMagicValue; - /*!< Magic value kept in the OTA image after the - sha256 Digest buffer to define the Start of OTA Header */ - uint32 u32OtaPayloadSzie; - /*!< - The Total OTA image payload size, include the sha256 key size - */ - -}tstrOtaInitHdr; - - -/*! -@struct \ - tstrOtaControlSec - -@brief - Control section structure is used to define the working image and - the validity of the roll-back image and its offset, also both firmware versions is kept in that structure. - */ - -typedef struct { - uint32 u32OtaMagicValue; -/*!< - Magic value used to ensure the structure is valid or not -*/ - uint32 u32OtaFormatVersion; -/*!< - NA NA NA Flash version cs struct version - 00 00 00 00 00 - Control structure format version, the value will be incremented in case of structure changed or updated -*/ - uint32 u32OtaSequenceNumber; -/*!< - Sequence number is used while update the control structure to keep track of how many times that section updated -*/ - uint32 u32OtaLastCheckTime; -/*!< - Last time OTA check for update -*/ - uint32 u32OtaCurrentworkingImagOffset; -/*!< - Current working offset in flash -*/ - uint32 u32OtaCurrentworkingImagFirmwareVer; -/*!< - current working image version ex 18.0.1 -*/ - uint32 u32OtaRollbackImageOffset; -/*!< - Roll-back image offset in flash -*/ - uint32 u32OtaRollbackImageValidStatus; -/*!< - roll-back image valid status -*/ - uint32 u32OtaRollbackImagFirmwareVer; -/*!< - Roll-back image version (ex 18.0.3) -*/ - uint32 u32OtaCortusAppWorkingOffset; -/*!< - cortus app working offset in flash -*/ - uint32 u32OtaCortusAppWorkingValidSts; -/*!< - Working Cortus app valid status -*/ - uint32 u32OtaCortusAppWorkingVer; -/*!< - Working cortus app version (ex 18.0.3) -*/ - uint32 u32OtaCortusAppRollbackOffset; -/*!< - cortus app rollback offset in flash -*/ - uint32 u32OtaCortusAppRollbackValidSts; -/*!< - roll-back cortus app valid status -*/ - uint32 u32OtaCortusAppRollbackVer; -/*!< - Roll-back cortus app version (ex 18.0.3) -*/ - uint32 u32OtaControlSecCrc; -/*!< - CRC for the control structure to ensure validity -*/ -} tstrOtaControlSec; - -/*! -@enum \ - tenuOtaUpdateStatus - -@brief - OTA return status -*/ -typedef enum { - OTA_STATUS_SUCSESS = 0, - /*!< OTA Success with not errors. */ - OTA_STATUS_FAIL = 1, - /*!< OTA generic fail. */ - OTA_STATUS_INVAILD_ARG = 2, - /*!< Invalid or malformed download URL. */ - OTA_STATUS_INVAILD_RB_IMAGE = 3, - /*!< Invalid rollback image. */ - OTA_STATUS_INVAILD_FLASH_SIZE = 4, - /*!< Flash size on device is not enough for OTA. */ - OTA_STATUS_AlREADY_ENABLED = 5, - /*!< An OTA operation is already enabled. */ - OTA_STATUS_UPDATE_INPROGRESS = 6, - /*!< An OTA operation update is in progress */ - OTA_STATUS_IMAGE_VERIF_FAILED = 7, - /*!< OTA Verfication failed */ - OTA_STATUS_CONNECTION_ERROR = 8, - /*!< OTA connection error */ - OTA_STATUS_SERVER_ERROR = 9, - /*!< OTA server Error (file not found or else ...) */ - OTA_STATUS_ABORTED = 10 - /*!< OTA download has been aborted by the application. */ -} tenuOtaUpdateStatus; -/*! -@enum \ - tenuOtaUpdateStatusType - -@brief - OTA update Status type -*/ -typedef enum { - - DL_STATUS = 1, - /*!< Download OTA file status - */ - SW_STATUS = 2, - /*!< Switching to the upgrade firmware status - */ - RB_STATUS = 3, - /*!< Roll-back status - */ - AB_STATUS = 4 - /*!< Abort status - */ -}tenuOtaUpdateStatusType; - - -/*! -@struct \ - tstrOtaUpdateStatusResp - -@brief - OTA Update Information - -@sa - tenuWPSTrigger -*/ -typedef struct { - uint8 u8OtaUpdateStatusType; - /*!< - Status type tenuOtaUpdateStatusType - */ - uint8 u8OtaUpdateStatus; - /*!< - OTA_SUCCESS - OTA_ERR_WORKING_IMAGE_LOAD_FAIL - OTA_ERR_INVAILD_CONTROL_SEC - M2M_ERR_OTA_SWITCH_FAIL - M2M_ERR_OTA_START_UPDATE_FAIL - M2M_ERR_OTA_ROLLBACK_FAIL - M2M_ERR_OTA_INVAILD_FLASH_SIZE - M2M_ERR_OTA_INVAILD_ARG - */ - uint8 _PAD16_[2]; -}tstrOtaUpdateStatusResp; - -/*! -@struct \ - tstrOtaUpdateInfo - -@brief - OTA Update Information - -@sa - tenuWPSTrigger -*/ -typedef struct { - uint32 u8NcfUpgradeVersion; - /*!< NCF OTA Upgrade Version - */ - uint32 u8NcfCurrentVersion; - /*!< NCF OTA Current firmware version - */ - uint32 u8NcdUpgradeVersion; - /*!< NCD (host) upgraded version (if the u8NcdRequiredUpgrade == true) - */ - uint8 u8NcdRequiredUpgrade; - /*!< NCD Required upgrade to the above version - */ - uint8 u8DownloadUrlOffset; - /*!< Download URL offset in the received packet - */ - uint8 u8DownloadUrlSize; - /*!< Download URL size in the received packet - */ - uint8 __PAD8__; - /*!< Padding bytes for forcing 4-byte alignment - */ -} tstrOtaUpdateInfo; - -/*! -@struct \ - tstrSystemTime - -@brief - Used for time storage. -*/ -typedef struct{ - uint16 u16Year; - uint8 u8Month; - uint8 u8Day; - uint8 u8Hour; - uint8 u8Minute; - uint8 u8Second; - uint8 __PAD8__; -}tstrSystemTime; - -/*! -@struct \ - tstrM2MMulticastMac - -@brief - M2M add/remove multi-cast mac address - */ - typedef struct { - uint8 au8macaddress[M2M_MAC_ADDRES_LEN]; - /*!< - Mac address needed to be added or removed from filter. - */ - uint8 u8AddRemove; - /*!< - set by 1 to add or 0 to remove from filter. - */ - uint8 __PAD8__; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2MMulticastMac; - -/*! -@struct \ - tstrPrng - -@brief - M2M Request PRNG - */ - typedef struct { - /*!< - return buffer address - */ - uint8 *pu8RngBuff; - /*!< - PRNG size requested - */ - uint16 u16PrngSize; - /*!< - PRNG pads - */ - uint8 __PAD16__[2]; -}tstrPrng; - -/* - * TLS certificate revocation list - * Typedefs common between fw and host - */ - -/*! -@struct \ - tstrTlsCrlEntry - -@brief - Certificate data for inclusion in a revocation list (CRL) -*/ -typedef struct { - uint8 u8DataLen; - /*!< - Length of certificate data (maximum possible is @ref TLS_CRL_DATA_MAX_LEN) - */ - uint8 au8Data[TLS_CRL_DATA_MAX_LEN]; - /*!< - Certificate data - */ - uint8 __PAD24__[3]; - /*!< - Padding bytes for forcing 4-byte alignment - */ -}tstrTlsCrlEntry; - -/*! -@struct \ - tstrTlsCrlInfo - -@brief - Certificate revocation list details -*/ -typedef struct { - uint8 u8CrlType; - /*!< - Type of certificate data contained in list - */ - uint8 u8Rsv1; - /*!< - Reserved for future use - */ - uint8 u8Rsv2; - /*!< - Reserved for future use - */ - uint8 u8Rsv3; - /*!< - Reserved for future use - */ - tstrTlsCrlEntry astrTlsCrl[TLS_CRL_MAX_ENTRIES]; - /*!< - List entries - */ -}tstrTlsCrlInfo; - - /*! -@enum\ - tenuSslCertExpSettings - -@brief SSL Certificate Expiry Validation Options -*/ -typedef enum{ - SSL_CERT_EXP_CHECK_DISABLE, - /*!< - ALWAYS OFF. - Ignore certificate expiration date validation. If a certificate is - expired or there is no configured system time, the SSL connection SUCCEEDs. - */ - SSL_CERT_EXP_CHECK_ENABLE, - /*!< - ALWAYS ON. - Validate certificate expiration date. If a certificate is expired or - there is no configured system time, the SSL connection FAILs. - */ - SSL_CERT_EXP_CHECK_EN_IF_SYS_TIME - /*!< - CONDITIONAL VALIDATION (Default setting at startup). - Validate the certificate expiration date only if there is a configured system time. - If there is no configured system time, the certificate expiration is bypassed and the - SSL connection SUCCEEDs. - */ -}tenuSslCertExpSettings; - - -/*! -@struct \ - tstrTlsSrvSecFileEntry - -@brief - This struct contains a TLS certificate. - */ -typedef struct{ - char acFileName[TLS_FILE_NAME_MAX]; - /*!< Name of the certificate. */ - uint32 u32FileSize; - /*!< Size of the certificate. */ - uint32 u32FileAddr; - /*!< Error Code. */ -}tstrTlsSrvSecFileEntry; - -/*! -@struct \ - tstrTlsSrvSecHdr - -@brief - This struct contains a set of TLS certificates. - */ -typedef struct{ - uint8 au8SecStartPattern[TLS_SRV_SEC_START_PATTERN_LEN]; - /*!< Start pattern. */ - uint32 u32nEntries; - /*!< Number of certificates stored in the struct. */ - uint32 u32NextWriteAddr; - /*!< TLS Certificates. */ - tstrTlsSrvSecFileEntry astrEntries[TLS_SRV_SEC_MAX_FILES]; -}tstrTlsSrvSecHdr; - -typedef struct{ - uint32 u32CsBMP; -}tstrSslSetActiveCsList; - - - /**@}*/ - -#endif diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_wifi.h b/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_wifi.h deleted file mode 100644 index 3477196..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/include/m2m_wifi.h +++ /dev/null @@ -1,2882 +0,0 @@ -/** - * - * \file - * - * \brief WINC WLAN Application Interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef __M2M_WIFI_H__ -#define __M2M_WIFI_H__ - -/** \defgroup m2m_wifi WLAN - * - */ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "common/include/nm_common.h" -#include "driver/include/m2m_types.h" -#include "driver/source/nmdrv.h" - -#ifdef CONF_MGMT - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/**@defgroup WlanEnums DataTypes - * @ingroup m2m_wifi - * @{*/ -/*! -@enum \ - tenuWifiFrameType - -@brief - Enumeration for Wi-Fi MAC frame type codes (2-bit) - The following types are used to identify the type of frame sent or received. - Each frame type constitutes a number of frame subtypes as defined in @ref tenuSubTypes to specify the exact type of frame. - Values are defined as per the IEEE 802.11 standard. - -@remarks - The following frame types are useful for advanced user usage when monitoring mode is used (defining @ref CONF_MGMT) - and the user application requires to monitor the frame transmission and reception. -@see - tenuSubTypes -*/ -typedef enum { - MANAGEMENT = 0x00, - /*!< Wi-Fi Management frame (Probe Req/Resp, Beacon, Association Req/Resp ...etc). - */ - CONTROL = 0x04, - /*!< Wi-Fi Control frame (eg. ACK frame). - */ - DATA_BASICTYPE = 0x08, - /*!< Wi-Fi Data frame. - */ - RESERVED = 0x0C, - - M2M_WIFI_FRAME_TYPE_ANY = 0xFF -/*!< Set monitor mode to receive any of the frames types -*/ -}tenuWifiFrameType; - - -/*! -@enum \ - tenuSubTypes - -@brief - Enumeration for Wi-Fi MAC Frame subtype code (6-bit). - The frame subtypes fall into one of the three frame type groups as defined in @ref tenuWifiFrameType - (MANAGEMENT, CONTROL & DATA). - Values are defined as per the IEEE 802.11 standard. -@remarks - The following sub-frame types are useful for advanced user usage when @ref CONF_MGMT is defined - and the application developer requires to monitor the frame transmission and reception. -@see - tenuWifiFrameType - tstrM2MWifiMonitorModeCtrl -*/ -typedef enum { - /*!< Sub-Types related to Management Sub-Types */ - ASSOC_REQ = 0x00, - ASSOC_RSP = 0x10, - REASSOC_REQ = 0x20, - REASSOC_RSP = 0x30, - PROBE_REQ = 0x40, - PROBE_RSP = 0x50, - BEACON = 0x80, - ATIM = 0x90, - DISASOC = 0xA0, - AUTH = 0xB0, - DEAUTH = 0xC0, - ACTION = 0xD0, -/**@{*/ - /* Sub-Types related to Control */ - PS_POLL = 0xA4, - RTS = 0xB4, - CTS = 0xC4, - ACK = 0xD4, - CFEND = 0xE4, - CFEND_ACK = 0xF4, - BLOCKACK_REQ = 0x84, - BLOCKACK = 0x94, -/**@{*/ - /* Sub-Types related to Data */ - DATA = 0x08, - DATA_ACK = 0x18, - DATA_POLL = 0x28, - DATA_POLL_ACK = 0x38, - NULL_FRAME = 0x48, - CFACK = 0x58, - CFPOLL = 0x68, - CFPOLL_ACK = 0x78, - QOS_DATA = 0x88, - QOS_DATA_ACK = 0x98, - QOS_DATA_POLL = 0xA8, - QOS_DATA_POLL_ACK = 0xB8, - QOS_NULL_FRAME = 0xC8, - QOS_CFPOLL = 0xE8, - QOS_CFPOLL_ACK = 0xF8, - M2M_WIFI_FRAME_SUB_TYPE_ANY = 0xFF - /*!< Set monitor mode to receive any of the frames types - */ -}tenuSubTypes; - - -/*! -@enum \ - tenuInfoElementId - -@brief - Enumeration for the Wi-Fi Information Element(IE) IDs, which indicates the specific type of IEs. - IEs are management frame information included in management frames. - Values are defined as per the IEEE 802.11 standard. - -*/ -typedef enum { - ISSID = 0, - /*!< Service Set Identifier (SSID) - */ - ISUPRATES = 1, - /*!< Supported Rates - */ - IFHPARMS = 2, - /*!< FH parameter set - */ - IDSPARMS = 3, - /*!< DS parameter set - */ - ICFPARMS = 4, - /*!< CF parameter set - */ - ITIM = 5, - /*!< Traffic Information Map - */ - IIBPARMS = 6, - /*!< IBSS parameter set - */ - ICOUNTRY = 7, - /*!< Country element. - */ - IEDCAPARAMS = 12, - /*!< EDCA parameter set - */ - ITSPEC = 13, - /*!< Traffic Specification - */ - ITCLAS = 14, - /*!< Traffic Classification - */ - ISCHED = 15, - /*!< Schedule. - */ - ICTEXT = 16, - /*!< Challenge Text - */ - IPOWERCONSTRAINT = 32, - /*!< Power Constraint. - */ - IPOWERCAPABILITY = 33, - /*!< Power Capability - */ - ITPCREQUEST = 34, - /*!< TPC Request - */ - ITPCREPORT = 35, - /*!< TPC Report - */ - ISUPCHANNEL = 36, - /* Supported channel list - */ - ICHSWANNOUNC = 37, - /*!< Channel Switch Announcement - */ - IMEASUREMENTREQUEST = 38, - /*!< Measurement request - */ - IMEASUREMENTREPORT = 39, - /*!< Measurement report - */ - IQUIET = 40, - /*!< Quiet element Info - */ - IIBSSDFS = 41, - /*!< IBSS DFS - */ - IERPINFO = 42, - /*!< ERP Information - */ - ITSDELAY = 43, - /*!< TS Delay - */ - ITCLASPROCESS = 44, - /*!< TCLAS Processing - */ - IHTCAP = 45, - /*!< HT Capabilities - */ - IQOSCAP = 46, - /*!< QoS Capability - */ - IRSNELEMENT = 48, - /*!< RSN Information Element - */ - IEXSUPRATES = 50, - /*!< Extended Supported Rates - */ - IEXCHSWANNOUNC = 60, - /*!< Extended Ch Switch Announcement - */ - IHTOPERATION = 61, - /*!< HT Information - */ - ISECCHOFF = 62, - /*!< Secondary Channel Offset - */ - I2040COEX = 72, - /*!< 20/40 Coexistence IE - */ - I2040INTOLCHREPORT = 73, - /*!< 20/40 Intolerant channel report - */ - IOBSSSCAN = 74, - /*!< OBSS Scan parameters - */ - IEXTCAP = 127, - /*!< Extended capability - */ - IWMM = 221, - /*!< WMM parameters - */ - IWPAELEMENT = 221 - /*!< WPA Information Element - */ -}tenuInfoElementId; - - -/*! -@struct \ - tenuWifiCapability - -@brief - Enumeration for capability Information field bit. - The value of the capability information field from the 802.11 management frames received by the wireless LAN interface. - Defining the capabilities of the Wi-Fi system. Values are defined as per the IEEE 802.11 standard. - -@details - Capabilities:- - ESS/IBSS : Defines whether a frame is coming from an AP or not. - POLLABLE : CF Poll-able - POLLREQ : Request to be polled - PRIVACY : WEP encryption supported - SHORTPREAMBLE : Short Preamble is supported - SHORTSLOT : Short Slot is supported - PBCC :PBCC - CHANNELAGILITY :Channel Agility - SPECTRUM_MGMT :Spectrum Management - DSSS_OFDM : DSSS-OFDM -*/ -typedef enum{ - ESS = 0x01, - /*!< ESS capability - */ - IBSS = 0x02, - /*!< IBSS mode - */ - POLLABLE = 0x04, - /*!< CF Pollable - */ - POLLREQ = 0x08, - /*!< Request to be polled - */ - PRIVACY = 0x10, - /*!< WEP encryption supported - */ - SHORTPREAMBLE = 0x20, - /*!< Short Preamble is supported - */ - SHORTSLOT = 0x400, - /*!< Short Slot is supported - */ - PBCC = 0x40, - /*!< PBCC - */ - CHANNELAGILITY = 0x80, - /*!< Channel Agility - */ - SPECTRUM_MGMT = 0x100, - /*!< Spectrum Management - */ - DSSS_OFDM = 0x2000 - /*!< DSSS-OFDM - */ -}tenuWifiCapability; - - -#endif - -/*! -@typedef \ - tpfAppWifiCb - -@brief - Wi-Fi's main callback function handler, for handling the M2M_WIFI events received on the Wi-Fi interface. - Such notifications are received in response to Wi-Fi/P2P operations such as @ref m2m_wifi_request_scan, - @ref m2m_wifi_connect. - Wi-Fi/P2P operations are implemented in an asynchronous mode, and all incoming information/status - are to be handled through this callback function when the corresponding notification is received. - Applications are expected to assign this wi-fi callback function by calling @ref m2m_wifi_init -@param [in] u8MsgType - Type of notifications. Possible types are: - /ref M2M_WIFI_RESP_CON_STATE_CHANGED - /ref M2M_WIFI_RESP_CONN_INFO - /ref M2M_WIFI_REQ_DHCP_CONF - /ref M2M_WIFI_REQ_WPS - /ref M2M_WIFI_RESP_IP_CONFLICT - /ref M2M_WIFI_RESP_SCAN_DONE - /ref M2M_WIFI_RESP_SCAN_RESULT - /ref M2M_WIFI_RESP_CURRENT_RSSI - /ref M2M_WIFI_RESP_CLIENT_INFO - /ref M2M_WIFI_RESP_PROVISION_INFO - /ref M2M_WIFI_RESP_DEFAULT_CONNECT - - In case Ethernet/Bypass mode is defined : - @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET - - In case monitoring mode is used: - @ref M2M_WIFI_RESP_WIFI_RX_PACKET - -@param [in] pvMsg - A pointer to a buffer containing the notification parameters (if any). It should be - casted to the correct data type corresponding to the notification type. - -@see - tstrM2mWifiStateChanged - tstrM2MWPSInfo - tstrM2mScanDone - tstrM2mWifiscanResult -*/ -typedef void (*tpfAppWifiCb) (uint8 u8MsgType, void * pvMsg); - -/*! -@typedef \ - tpfAppEthCb - -@brief - ETHERNET (bypass mode) notification callback function receiving Bypass mode events as defined in - the Wi-Fi responses enumeration @ref tenuM2mStaCmd. - -@param [in] u8MsgType - Type of notification. Possible types are: - - [M2M_WIFI_RESP_ETHERNET_RX_PACKET](@ref M2M_WIFI_RESP_ETHERNET_RX_PACKET) - -@param [in] pvMsg - A pointer to a buffer containing the notification parameters (if any). It should be - casted to the correct data type corresponding to the notification type. - For example, it could be a pointer to the buffer holding the received frame in case of @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET - event. - -@param [in] pvControlBuf - A pointer to control buffer describing the accompanied message. - To be casted to @ref tstrM2mIpCtrlBuf in case of @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET event. - -@warning - Make sure that the application defines @ref ETH_MODE. - -@see - m2m_wifi_init - -*/ -typedef void (*tpfAppEthCb) (uint8 u8MsgType, void * pvMsg,void * pvCtrlBuf); - -/*! -@typedef \ - tpfAppMonCb - -@brief - Wi-Fi monitoring mode callback function. This function delivers all received wi-Fi packets through the Wi-Fi interface. - Applications requiring to operate in the monitoring should call the asynchronous function m2m_wifi_enable_monitoring_mode - and expect to receive the Wi-Fi packets through this callback function, when the event is received. - To disable the monitoring mode a call to @ref m2m_wifi_disable_monitoring_mode should be made. -@param [in] pstrWifiRxPacket - Pointer to a structure holding the Wi-Fi packet header parameters. - -@param [in] pu8Payload - Pointer to the buffer holding the Wi-Fi packet payload information required by the application starting from the - defined OFFSET by the application (when calling m2m_wifi_enable_monitoring_mode). - Could hold a value of NULL, if the application does not need any data from the payload. - -@param [in] u16PayloadSize - The size of the payload in bytes. - -@see - m2m_wifi_enable_monitoring_mode,m2m_wifi_init - -@warning - u16PayloadSize should not exceed the buffer size given through m2m_wifi_enable_monitoring_mode. - -*/ -typedef void (*tpfAppMonCb) (tstrM2MWifiRxPacketInfo *pstrWifiRxPacket, uint8 * pu8Payload, uint16 u16PayloadSize); - -/** -@struct \ - tstrEthInitParam - -@brief - Structure to hold Ethernet interface parameters. - Structure is to be defined and have its attributes set,based on the application's functionality before - a call is made to initialize the Wi-Fi operations by calling the @ref m2m_wifi_init function. - This structure is part of the Wi-Fi configuration structure @ref tstrWifiInitParam. - Applications shouldn't need to define this structure, if the bypass mode is not defined. - -@see - tpfAppEthCb - tpfAppWifiCb - m2m_wifi_init - -@warning - Make sure that application defines @ref ETH_MODE before using @ref tstrEthInitParam. - -*/ -typedef struct { - tpfAppWifiCb pfAppWifiCb; - /*!< - Callback for wifi notifications. - */ - tpfAppEthCb pfAppEthCb; - /*!< - Callback for Ethernet interface. - */ - uint8 * au8ethRcvBuf; - /*!< - Pointer to Receive Buffer of Ethernet Packet - */ - uint16 u16ethRcvBufSize; - /*!< - Size of Receive Buffer for Ethernet Packet - */ - uint8 u8EthernetEnable; - /*!< - Enable Ethernet mode flag - */ - uint8 __PAD8__; - /*!< - Padding - */ -} tstrEthInitParam; -/*! -@struct \ - tstrM2mIpCtrlBuf - -@brief - Structure holding the incoming buffer's data size information, indicating the data size of the buffer and the remaining buffer's data size . - The data of the buffer which holds the packet sent to the host when in the bypass mode, is placed in the @ref tstrEthInitParam structure in the - @ref au8ethRcvBuf attribute. This following information is retrieved in the host when an event @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET is received in - the Wi-Fi callback function @ref tpfAppWifiCb. - - The application is expected to use this structure's information to determine if there is still incoming data to be received from the firmware. - - @see - tpfAppEthCb - tstrEthInitParam - - @warning - Make sure that ETHERNET/bypass mode is defined before using @ref tstrM2mIpCtrlBuf - - */ -typedef struct{ - uint16 u16DataSize; - /*!< - Size of the received data in bytes. - */ - uint16 u16RemainigDataSize; - /*!< - Size of the remaining data bytes to be delivered to host. - */ -} tstrM2mIpCtrlBuf; - - -/** -@struct \ - tstrWifiInitParam - -@brief - Structure, holding the Wi-fi configuration attributes such as the wi-fi callback , monitoring mode callback and Ethernet parameter initialization structure. - Such configuration parameters are required to be set before calling the wi-fi initialization function @ref m2m_wifi_init. - @ref pfAppWifiCb attribute must be set to handle the wi-fi callback operations. - @ref pfAppMonCb attribute, is optional based on whether the application requires the monitoring mode configuration, and can there not - be set before the initialization. - @ref strEthInitParam structure, is another optional configuration based on whether the bypass mode is set. - - @see - tpfAppEthCb - tpfAppMonCb - tstrEthInitParam - -*/ -typedef struct { - tpfAppWifiCb pfAppWifiCb; - /*!< - Callback for Wi-Fi notifications. - */ - tpfAppMonCb pfAppMonCb; - /*!< - Callback for monitoring interface. - */ - tstrEthInitParam strEthInitParam ; - /*!< - Structure to hold Ethernet interface parameters. - */ - -} tstrWifiInitParam; - //@} -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/** \defgroup WLANAPI Function - * @ingroup m2m_wifi - */ -#ifdef __cplusplus - extern "C" { -#endif - /** @defgroup WiFiDownloadFn m2m_wifi_download_mode - * @ingroup WLANAPI - * Synchronous download mode entry function that prepares the WINC board to enter the download mode, ready for the firmware or certificate download. -* The WINC board is prepared for download, through initializations for the WINC driver including bus initializations and interrupt enabling, it also halts the chip, to allow for the firmware downloads. -* Firmware can be downloaded through a number of interfaces, UART, I2C and SPI. - */ - /**@{*/ -/*! -@fn \ - NMI_API void m2m_wifi_download_mode(void); -@brief Prepares the WINC broard before downloading any data (Firmware, Certificates .. etc) - - This function should called before starting to download any data to the WINC board. The WINC board is prepared for download, through initializations for the WINC driver including bus initializations - and interrupt enabling, it also halts the chip, to allow for the firmware downloads Firmware can be downloaded through a number of interfaces, UART, I2C and SPI. - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_download_mode(void); - - /**@}*/ - /** @defgroup WifiInitFn m2m_wifi_init - * @ingroup WLANAPI - * Synchronous initialization function for the WINC driver. This function initializes the driver by, registering the call back function for M2M_WIFI layer(also the call back function for bypass mode/monitoring mode if defined), - * initializing the host interface layer and the bus interfaces. - * Wi-Fi callback registering is essential to allow the handling of the events received, in response to the asynchronous Wi-Fi operations. - -Following are the possible Wi-Fi events that are expected to be received through the call back function(provided by the application) to the M2M_WIFI layer are : - - @ref M2M_WIFI_RESP_CON_STATE_CHANGED \n - @ref M2M_WIFI_RESP_CONN_INFO \n - @ref M2M_WIFI_REQ_DHCP_CONF \n - @ref M2M_WIFI_REQ_WPS \n - @ref M2M_WIFI_RESP_IP_CONFLICT \n - @ref M2M_WIFI_RESP_SCAN_DONE \n - @ref M2M_WIFI_RESP_SCAN_RESULT \n - @ref M2M_WIFI_RESP_CURRENT_RSSI \n - @ref M2M_WIFI_RESP_CLIENT_INFO \n - @ref M2M_WIFI_RESP_PROVISION_INFO \n - @ref M2M_WIFI_RESP_DEFAULT_CONNECT \n - Example: \n - In case Bypass mode is defined : \n - @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET - - In case Monitoring mode is used: \n - @ref M2M_WIFI_RESP_WIFI_RX_PACKET - - Any application using the WINC driver must call this function at the start of its main function. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_init(tstrWifiInitParam * pWifiInitParam); - -@param [in] pWifiInitParam - This is a pointer to the @ref tstrWifiInitParam structure which holds the pointer to the application WIFI layer call back function, - monitoring mode call back and @ref tstrEthInitParam structure containing bypass mode parameters. - -@brief Initialize the WINC host driver. - This function initializes the driver by, registering the call back function for M2M_WIFI layer(also the call back function for bypass mode/monitoring mode if defined), - initializing the host interface layer and the bus interfaces. - -@pre - Prior to this function call, The application should initialize the BSP using "nm_bsp_init". - Also,application users must provide a call back function responsible for receiving all the WI-FI events that are received on the M2M_WIFI layer. - -@warning - Failure to successfully complete function indicates that the driver couldn't be initialized and a fatal error will prevent the application from proceeding. - -@see - nm_bsp_init - m2m_wifi_deinit - tenuM2mStaCmd - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_init(tstrWifiInitParam * pWifiInitParam); - /**@}*/ - /** @defgroup WifiDeinitFn m2m_wifi_deinit - * @ingroup WLANAPI - * Synchronous de-initialization function to the WINC1500 driver. De-initializes the host interface and frees any resources used by the M2M_WIFI layer. - * This function must be called in the application closing phase to ensure that all resources have been correctly released. No arguments are expected to be passed in. - */ -/**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_deinit(void * arg); - -@param [in] arg - Generic argument. Not used in the current implementation. -@brief Deinitilize the WINC driver and host enterface. - This function must be called at the De-initilization stage of the application. Generally This function should be the last function before switching off the chip - and it should be followed only by "nm_bsp_deinit" function call. Every function call of "nm_wifi_init" should be matched with a call to nm_wifi_deinit. -@see - nm_bsp_deinit - nm_wifi_init - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_deinit(void * arg); - - /**@}*/ -/** @defgroup WifiHandleEventsFn m2m_wifi_handle_events -* @ingroup WLANAPI -* Synchronous M2M event handler function, responsible for handling interrupts received from the WINC firmware. -* Application developers should call this function periodically in-order to receive the events that are to be handled by the -* callback functions implemented by the application. - - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_handle_events(void * arg); - -@pre - Prior to receiving events, the WINC driver should have been successfully initialized by calling the @ref m2m_wifi_init function. - -@brief Handle the varios events received from the WINC board. - Whenever an event happen in the WINC board (e.g. Connection, Disconnection , DHCP .. etc), WINC will interrupt the host to let it know that a new - event has occured. The host driver will attempt to handle these events whenever the host driver decides to do that by calling the "m2m_wifi_handle_events" function. - It's mandatory to call this function periodically and independantly of any other condition. It's ideal to include this function in the main and the most frequent loop of the - host application. -@warning - Failure to successfully complete this function indicates bus errors and hence a fatal error that will prevent the application from proceeding. - -@return - The function returns @ref M2M_SUCCESS for successful interrupt handling and a negative value otherwise. -*/ - -NMI_API sint8 m2m_wifi_handle_events(void * arg); - - /**@}*/ -/** @defgroup WifiSendCRLFn m2m_wifi_send_crl -* @ingroup WLANAPI -* Asynchronous API that notifies the WINC with the Certificate Revocation List to be used for TLS. - - */ - /**@{*/ -/*! -@fn \ - sint8 m2m_wifi_send_crl(tstrTlsCrlInfo* pCRL); - -@brief - Asynchronous API that notifies the WINC with the Certificate Revocation List. - -@param [in] pCRL - Pointer to the structure containing certificate revocation list details. - -@return - The function returns @ref M2M_SUCCESS if the command has been successfully queued to the WINC, - and a negative value otherwise. -*/ - -sint8 m2m_wifi_send_crl(tstrTlsCrlInfo* pCRL); - - /**@}*/ -/** @defgroup WifiDefaultConnectFn m2m_wifi_default_connect - * @ingroup WLANAPI - * Asynchronous Wi-Fi connection function. An application calling this function will cause the firmware to correspondingly connect to the last successfully connected AP from the cached connections. - * A failure to connect will result in a response of @ref M2M_WIFI_RESP_DEFAULT_CONNECT indicating the connection error as defined in the structure @ref tstrM2MDefaultConnResp. - * Possible errors are: - * The connection list is empty @ref M2M_DEFAULT_CONN_EMPTY_LIST or a mismatch for the saved AP name @ref M2M_DEFAULT_CONN_SCAN_MISMATCH. - * only difference between this function and @ref m2m_wifi_connect, is the connection parameters. - * Connection using this function is expected to connect using cached connection parameters. - - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_default_connect(void); - -@pre - Prior to connecting, the WINC driver should have been successfully initialized by calling the @ref m2m_wifi_init function. - -@brief Connect to the last successfully connected AP from the cached connections. - -@warning - This function must be called in station mode only. - It's important to note that successful completion of a call to m2m_wifi_default_connect() does not guarantee success of the WIFI connection, - and a negative return value indicates only locally-detected errors. - -@see - m2m_wifi_connect - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_default_connect(void); - /**@}*/ -/** @defgroup WifiConnectFn m2m_wifi_connect - * @ingroup WLANAPI - * Asynchronous wi-fi connection function to a specific AP. Prior to a successful connection, the application must define the SSID of the AP, the security type, - * the authentication information parameters and the channel number to which the connection will be established. - * The connection status is known when a response of @ref M2M_WIFI_RESP_CON_STATE_CHANGED is received based on the states defined in @ref tenuM2mConnState, - * successful connection is defined by @ref M2M_WIFI_CONNECTED -* - * The only difference between this function and @ref m2m_wifi_default_connect, is the connection parameters. - * Connection using this function is expected to be made to a specific AP and to a specified channel. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_connect(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch); - -@param [in] pcSsid - A buffer holding the SSID corresponding to the requested AP. - -@param [in] u8SsidLen - Length of the given SSID (not including the NULL termination). - A length less than ZERO or greater than the maximum defined SSID @ref M2M_MAX_SSID_LEN will result in a negative error - @ref M2M_ERR_FAIL. - -@param [in] u8SecType - Wi-Fi security type security for the network. It can be one of the following types: - -@ref M2M_WIFI_SEC_OPEN - -@ref M2M_WIFI_SEC_WEP - -@ref M2M_WIFI_SEC_WPA_PSK - -@ref M2M_WIFI_SEC_802_1X - A value outside these possible values will result in a negative return error @ref M2M_ERR_FAIL. - -@param [in] pvAuthInfo - Authentication parameters required for completing the connection. It is type is based on the Security type. - If the authentication parameters are NULL or are greater than the maximum length of the authentication parameters length as defined by - @ref M2M_MAX_PSK_LEN a negative error will return @ref M2M_ERR_FAIL(-12) indicating connection failure. - -@param [in] u16Ch - Wi-Fi channel number as defined in @ref tenuM2mScanCh enumeration. - Channel number greater than @ref M2M_WIFI_CH_14 returns a negative error @ref M2M_ERR_FAIL(-12). - Except if the value is M2M_WIFI_CH_ALL(255), since this indicates that the firmware should scan all channels to find the SSID requested to connect to. - Failure to find the connection match will return a negative error @ref M2M_DEFAULT_CONN_SCAN_MISMATCH. -@pre - Prior to a successful connection request, the Wi-Fi driver must have been successfully initialized through the call of the @ref @m2m_wifi_init function -@see - tuniM2MWifiAuth - tstr1xAuthCredentials - tstrM2mWifiWepParams - -@warning - -This function must be called in station mode only. - -Successful completion of this function does not guarantee success of the WIFI connection, and - a negative return value indicates only locally-detected errors. - -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_connect(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch); - /**@}*/ -/** @defgroup WifiConnectFn m2m_wifi_connect_sc - * @ingroup WLANAPI - * Asynchronous wi-fi connection function to a specific AP. Prior to a successful connection, the application developers must know the SSID of the AP, the security type, - * the authentication information parameters and the channel number to which the connection will be established.this API allows the user to choose - * whether to - * The connection status is known when a response of @ref M2M_WIFI_RESP_CON_STATE_CHANGED is received based on the states defined in @ref tenuM2mConnState, - * successful connection is defined by @ref M2M_WIFI_CONNECTED - * The only difference between this function and @ref m2m_wifi_connect, is the option to save the acess point info ( SSID, password...etc) or not. - * Connection using this function is expected to be made to a specific AP and to a specified channel. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_connect_sc(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch,uint8 u8SaveCred); - -@param [in] pcSsid - A buffer holding the SSID corresponding to the requested AP. - -@param [in] u8SsidLen - Length of the given SSID (not including the NULL termination). - A length less than ZERO or greater than the maximum defined SSID @ref M2M_MAX_SSID_LEN will result in a negative error - @ref M2M_ERR_FAIL. - -@param [in] u8SecType - Wi-Fi security type security for the network. It can be one of the following types: - -@ref M2M_WIFI_SEC_OPEN - -@ref M2M_WIFI_SEC_WEP - -@ref M2M_WIFI_SEC_WPA_PSK - -@ref M2M_WIFI_SEC_802_1X - A value outside these possible values will result in a negative return error @ref M2M_ERR_FAIL. - -@param [in] pvAuthInfo - Authentication parameters required for completing the connection. It is type is based on the Security type. - If the authentication parameters are NULL or are greater than the maximum length of the authentication parameters length as defined by - @ref M2M_MAX_PSK_LEN a negative error will return @ref M2M_ERR_FAIL(-12) indicating connection failure. - -@param [in] u16Ch - Wi-Fi channel number as defined in @ref tenuM2mScanCh enumeration. - Channel number greater than @ref M2M_WIFI_CH_14 returns a negative error @ref M2M_ERR_FAIL(-12). - Except if the value is M2M_WIFI_CH_ALL(255), since this indicates that the firmware should scan all channels to find the SSID requested to connect to. - Failure to find the connection match will return a negative error @ref M2M_DEFAULT_CONN_SCAN_MISMATCH. - -@param [in] u8NoSaveCred - Option to store the acess point SSID and password into the WINC flash memory or not. - -@pre - Prior to a successful connection request, the wi-fi driver must have been successfully initialized through the call of the @ref @m2m_wifi_init function -@see - tuniM2MWifiAuth - tstr1xAuthCredentials - tstrM2mWifiWepParams - -@warning - -This function must be called in station mode only. - -Successful completion of this function does not guarantee success of the WIFI connection, and - a negative return value indicates only locally-detected errors. - -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ - NMI_API sint8 m2m_wifi_connect_sc(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch, uint8 u8SaveCred); - /**@}*/ -/** @defgroup WifiDisconnectFn m2m_wifi_disconnect - * @ingroup WLANAPI - * Synchronous wi-fi disconnection function, requesting a Wi-Fi disconnection from the currently connected AP. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_disconnect(void); - -@pre - Disconnection request must be made to a successfully connected AP. If the WINC is not in the connected state, a call to this function will hold insignificant. - -@brief Request a Wi-Fi disconnect from the currently connected AP. - After the Disconnect is complete the driver should recieve a response of @ref M2M_WIFI_RESP_CON_STATE_CHANGED based on the states defined - in @ref tenuM2mConnState, successful disconnection is defined by @ref M2M_WIFI_DISCONNECTED . -@warning - This function must be called in station mode only. - -@see - m2m_wifi_connect - m2m_wifi_default_connect - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_disconnect(void); - - /**@}*/ -/** @defgroup StartProvisionModeFn m2m_wifi_start_provision_mode - * @ingroup WLANAPI - * Asynchronous Wi-Fi provisioning function, which starts the WINC HTTP PROVISIONING mode. - The function triggers the WINC to activate the Wi-Fi AP (HOTSPOT) mode with the passed configuration parameters and then starts the - HTTP Provision WEB Server. - The provisioning status is returned in an event @ref M2M_WIFI_RESP_PROVISION_INFO - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_start_provision_mode(tstrM2MAPConfig *pstrAPConfig, char *pcHttpServerDomainName, uint8 bEnableHttpRedirect); - -@param [in] pstrAPConfig - AP configuration parameters as defined in @ref tstrM2MAPConfig configuration structure. - A NULL value passed in, will result in a negative error @ref M2M_ERR_FAIL. - -@param [in] pcHttpServerDomainName - Domain name of the HTTP Provision WEB server which others will use to load the provisioning Home page. - The domain name can have one of the following 3 forms: - 1- "wincprov.com" - 2- "http://wincprov.com" - 3- "https://wincprov.com" - The forms 1 and 2 are equivalent, they both will start a plain http server, while form 3 - will start a secure HTTP provisioning Session (HTTP over SSL connection). - -@param [in] bEnableHttpRedirect - A flag to enable/disable the HTTP redirect feature. If Secure provisioning is enabled (i.e. the server - domain name uses "https" prefix) this flag is ignored (no meaning for redirect in HTTPS). - Possible values are: - - ZERO DO NOT Use HTTP Redirect. In this case the associated device could open the provisioning page ONLY when - the HTTP Provision URL of the WINC HTTP Server is correctly written on the browser. - - Non-Zero value Use HTTP Redirect. In this case, all http traffic (http://URL) from the associated - device (Phone, PC, ...etc) will be redirected to the WINC HTTP Provisioning Home page. - -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback - is done through passing it to the initialization @ref m2m_wifi_init function. - - The event @ref M2M_WIFI_RESP_CONN_INFO must be handled in the callback to receive the requested connection info. - -@see - tpfAppWifiCb - m2m_wifi_init - M2M_WIFI_RESP_PROVISION_INFO - m2m_wifi_stop_provision_mode - tstrM2MAPConfig - -@warning - DO Not use ".local" in the pcHttpServerDomainName. - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -\section Example - The example demonstrates a code snippet for how provisioning is triggered and the response event received accordingly. -@code - #include "m2m_wifi.h" - #include "m2m_types.h" - - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_PROVISION_INFO: - { - tstrM2MProvisionInfo *pstrProvInfo = (tstrM2MProvisionInfo*)pvMsg; - if(pstrProvInfo->u8Status == M2M_SUCCESS) - { - m2m_wifi_connect((char*)pstrProvInfo->au8SSID, (uint8)strlen(pstrProvInfo->au8SSID), pstrProvInfo->u8SecType, - pstrProvInfo->au8Password, M2M_WIFI_CH_ALL); - - printf("PROV SSID : %s\n",pstrProvInfo->au8SSID); - printf("PROV PSK : %s\n",pstrProvInfo->au8Password); - } - else - { - printf("(ERR) Provisioning Failed\n"); - } - } - break; - - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - tstrM2MAPConfig apConfig; - uint8 bEnableRedirect = 1; - - strcpy(apConfig.au8SSID, "WINC_SSID"); - apConfig.u8ListenChannel = 1; - apConfig.u8SecType = M2M_WIFI_SEC_OPEN; - apConfig.u8SsidHide = 0; - - // IP Address - apConfig.au8DHCPServerIP[0] = 192; - apConfig.au8DHCPServerIP[1] = 168; - apConfig.au8DHCPServerIP[2] = 1; - apConfig.au8DHCPServerIP[0] = 1; - - m2m_wifi_start_provision_mode(&apConfig, "atmelwincconf.com", bEnableRedirect); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API sint8 m2m_wifi_start_provision_mode(tstrM2MAPConfig *pstrAPConfig, char *pcHttpServerDomainName, uint8 bEnableHttpRedirect); - /**@}*/ -/** @defgroup StopProvisioningModeFn m2m_wifi_stop_provision_mode - * @ingroup WLANAPI - * Synchronous provision termination function which stops the provision mode if it is active. - */ - /**@{*/ -/*! -@fn \ - sint8 m2m_wifi_stop_provision_mode(void); - -@pre - An active provisioning session must be active before it is terminated through this function. -@see - m2m_wifi_start_provision_mode - -@return - The function returns ZERO for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_stop_provision_mode(void); - /**@}*/ -/** @defgroup GetConnectionInfoFn m2m_wifi_get_connection_info - * @ingroup WLANAPI - * Asynchronous connection status retrieval function, retrieves the status information of the currently connected AP. The result is passed to the Wi-Fi notification callback -* through the event @ref M2M_WIFI_RESP_CONN_INFO. Connection information is retrieved from the structure @ref tstrM2MConnInfo. - */ - /**@{*/ -/*! -@fn \ - sint8 m2m_wifi_get_connection_info(void); - -@brief - Retrieve the current Connection information. The result is passed to the Wi-Fi notification callback - with [M2M_WIFI_RESP_CONN_INFO](@ref M2M_WIFI_RESP_CONN_INFO). -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback - is done through passing it to the initialization @ref m2m_wifi_init function. - - The event @ref M2M_WIFI_RESP_CONN_INFO must be handled in the callback to receive the requested connection info. - - Connection Information retrieved: - - - -Connection Security - -Connection RSSI - -Remote MAC address - -Remote IP address - - and in case of WINC station mode the SSID of the AP is also retrieved. -@warning - -In case of WINC AP mode or P2P mode, ignore the SSID field (NULL string). -@sa - M2M_WIFI_RESP_CONN_INFO, - tstrM2MConnInfo -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet shows an example of how wi-fi connection information is retrieved . -@code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_CONN_INFO: - { - tstrM2MConnInfo *pstrConnInfo = (tstrM2MConnInfo*)pvMsg; - - printf("CONNECTED AP INFO\n"); - printf("SSID : %s\n",pstrConnInfo->acSSID); - printf("SEC TYPE : %d\n",pstrConnInfo->u8SecType); - printf("Signal Strength : %d\n", pstrConnInfo->s8RSSI); - printf("Local IP Address : %d.%d.%d.%d\n", - pstrConnInfo->au8IPAddr[0] , pstrConnInfo->au8IPAddr[1], pstrConnInfo->au8IPAddr[2], pstrConnInfo->au8IPAddr[3]); - } - break; - - case M2M_WIFI_REQ_DHCP_CONF: - { - // Get the current AP information. - m2m_wifi_get_connection_info(); - } - break; - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // connect to the default AP - m2m_wifi_default_connect(); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API sint8 m2m_wifi_get_connection_info(void); - /**@}*/ -/** @defgroup WifiSetMacAddFn m2m_wifi_set_mac_address - * @ingroup WLANAPI - * Synchronous MAC address assigning to the NMC1500. It is used for non-production SW. Assign MAC address to the WINC device. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_set_mac_address(uint8 au8MacAddress[6]); - -@brief Assign a MAC address to the WINC board. - This function override the already assigned MAC address of the WINC board with a user provided one. This is for experimental - use only and should never be used in the production SW. - -@param [in] au8MacAddress - MAC Address to be set to the WINC. - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_set_mac_address(uint8 au8MacAddress[6]); - - /**@}*/ -/** @defgroup WifiWpsFn m2m_wifi_wps - * @ingroup WLANAPI - * Asynchronous WPS triggering function. - * This function is called for the WINC to enter the WPS (Wi-Fi Protected Setup) mode. The result is passed to the Wi-Fi notification callback -* with the event @ref M2M_WIFI_REQ_WPS. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_wps(uint8 u8TriggerType,const char * pcPinNumber); - -@param [in] u8TriggerType - WPS Trigger method. Could be: - - [WPS_PIN_TRIGGER](@ref WPS_PIN_TRIGGER) Push button method - - [WPS_PBC_TRIGGER](@ref WPS_PBC_TRIGGER) Pin method - -@param [in] pcPinNumber - PIN number for WPS PIN method. It is not used if the trigger type is WPS_PBC_TRIGGER. It must follow the rules - stated by the WPS standard. - -@warning - This function is not allowed in AP or P2P modes. - -@pre - - A Wi-Fi notification callback of type (@ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback - is done through passing it to the [m2m_wifi_init](@ref m2m_wifi_init). - - The event [M2M_WIFI_REQ_WPS](@ref M2M_WIFI_REQ_WPS) must be handled in the callback to receive the WPS status. - - The WINC device MUST be in IDLE or STA mode. If AP or P2P mode is active, the WPS will not be performed. - - The [m2m_wifi_handle_events](@ref m2m_wifi_handle_events) MUST be called periodically to receive the responses in the callback. -@see - tpfAppWifiCb - m2m_wifi_init - M2M_WIFI_REQ_WPS - tenuWPSTrigger - tstrM2MWPSInfo - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet shows an example of how Wi-Fi WPS is triggered . -@code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - switch(u8WiFiEvent) - { - case M2M_WIFI_REQ_WPS: - { - tstrM2MWPSInfo *pstrWPS = (tstrM2MWPSInfo*)pvMsg; - if(pstrWPS->u8AuthType != 0) - { - printf("WPS SSID : %s\n",pstrWPS->au8SSID); - printf("WPS PSK : %s\n",pstrWPS->au8PSK); - printf("WPS SSID Auth Type : %s\n",pstrWPS->u8AuthType == M2M_WIFI_SEC_OPEN ? "OPEN" : "WPA/WPA2"); - printf("WPS Channel : %d\n",pstrWPS->u8Ch + 1); - - // establish Wi-Fi connection - m2m_wifi_connect((char*)pstrWPS->au8SSID, (uint8)m2m_strlen(pstrWPS->au8SSID), - pstrWPS->u8AuthType, pstrWPS->au8PSK, pstrWPS->u8Ch); - } - else - { - printf("(ERR) WPS Is not enabled OR Timed out\n"); - } - } - break; - - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // Trigger WPS in Push button mode. - m2m_wifi_wps(WPS_PBC_TRIGGER, NULL); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API sint8 m2m_wifi_wps(uint8 u8TriggerType,const char *pcPinNumber); - /**@}*/ -/** @defgroup WifiWpsDisableFn m2m_wifi_wps_disable - * @ingroup WLANAPI - * Disable the WINC1500 WPS operation. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_wps_disable(void); - -@pre WINC should be already in WPS mode using @ref m2m_wifi_wps - -@brief Stops the WPS ongoing session. - -@see - m2m_wifi_wps - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_wps_disable(void); - - /**@}*/ -/** @defgroup WifiP2PFn m2m_wifi_p2p - * @ingroup WLANAPI - * Asynchronous Wi-Fi direct (P2P) enabling mode function. - The WINC supports P2P in device listening mode ONLY (intent is ZERO). - The WINC P2P implementation does not support P2P GO (Group Owner) mode. - Active P2P devices (e.g. phones) could find the WINC in the search list. When a device is connected to WINC, a Wi-Fi notification event - @ref M2M_WIFI_RESP_CON_STATE_CHANGED is triggered. After a short while, the DHCP IP Address is obtained - and an event @ref M2M_WIFI_REQ_DHCP_CONF is triggered. Refer to the code examples for a more illustrative example. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_p2p(uint8 u8Channel); - -@param [in] u8Channel - P2P Listen RF channel. According to the P2P standard It must hold only one of the following values 1, 6 or 11. - -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback - is done through passing it to the @ref m2m_wifi_init. - - The events @ref M2M_WIFI_RESP_CON_STATE_CHANGED and @ref M2M_WIFI_REQ_DHCP_CONF - must be handled in the callback. - - The @ref m2m_wifi_handle_events MUST be called to receive the responses in the callback. - -@warning - This function is not allowed in AP or STA modes. - -@see - tpfAppWifiCb - m2m_wifi_init - M2M_WIFI_RESP_CON_STATE_CHANGED - M2M_WIFI_REQ_DHCP_CONF - tstrM2mWifiStateChanged - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet shown an example of how the p2p mode operates. -@code - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_CON_STATE_CHANGED: - { - tstrM2mWifiStateChanged *pstrWifiState = (tstrM2mWifiStateChanged*)pvMsg; - M2M_INFO("Wifi State :: %s :: ErrCode %d\n", pstrWifiState->u8CurrState? "CONNECTED":"DISCONNECTED",pstrWifiState->u8ErrCode); - - // Do something - } - break; - - case M2M_WIFI_REQ_DHCP_CONF: - { - uint8 *pu8IPAddress = (uint8*)pvMsg; - - printf("P2P IP Address \"%u.%u.%u.%u\"\n",pu8IPAddress[0],pu8IPAddress[1],pu8IPAddress[2],pu8IPAddress[3]); - } - break; - - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // Trigger P2P - m2m_wifi_p2p(M2M_WIFI_CH_1); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode - -*/ -NMI_API sint8 m2m_wifi_p2p(uint8 u8Channel); - /**@}*/ -/** @defgroup WifiP2PDisconnectFn m2m_wifi_p2p_disconnect - * @ingroup WLANAPI - * Disable the WINC1500 device Wi-Fi direct mode (P2P). - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_p2p_disconnect(void); -@pre - The p2p mode must have be enabled and active before a disconnect can be called. - -@see - m2m_wifi_p2p -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_p2p_disconnect(void); - /**@}*/ -/** @defgroup WifiEnableApFn m2m_wifi_enable_ap - * @ingroup WLANAPI - * Asynchronous Wi-FI hot-spot enabling function. - * The WINC supports AP mode operation with the following limitations: - - Only 1 STA could be associated at a time. - - Open and WEP are the only supported security types - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_enable_ap(CONST tstrM2MAPConfig* pstrM2MAPConfig); - -@param [in] pstrM2MAPConfig - A structure holding the AP configurations. - -@warning - This function is not allowed in P2P or STA modes. - -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback - is done through passing it to the [m2m_wifi_init](@ref m2m_wifi_init). - - The event @ref M2M_WIFI_REQ_DHCP_CONF must be handled in the callback. - - The @ref m2m_wifi_handle_events MUST be called to receive the responses in the callback. - -@see - tpfAppWifiCb - tenuM2mSecType - m2m_wifi_init - M2M_WIFI_REQ_DHCP_CONF - tstrM2mWifiStateChanged - tstrM2MAPConfig - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet demonstrates how the AP mode is enabled after the driver is initialized in the application's main function and the handling - of the event @ref M2M_WIFI_REQ_DHCP_CONF, to indicate successful connection. -@code - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - switch(u8WiFiEvent) - { - case M2M_WIFI_REQ_DHCP_CONF: - { - uint8 *pu8IPAddress = (uint8*)pvMsg; - - printf("Associated STA has IP Address \"%u.%u.%u.%u\"\n",pu8IPAddress[0],pu8IPAddress[1],pu8IPAddress[2],pu8IPAddress[3]); - } - break; - - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - tstrM2MAPConfig apConfig; - - strcpy(apConfig.au8SSID, "WINC_SSID"); - apConfig.u8ListenChannel = 1; - apConfig.u8SecType = M2M_WIFI_SEC_OPEN; - apConfig.u8SsidHide = 0; - - // IP Address - apConfig.au8DHCPServerIP[0] = 192; - apConfig.au8DHCPServerIP[1] = 168; - apConfig.au8DHCPServerIP[2] = 1; - apConfig.au8DHCPServerIP[0] = 1; - - // Trigger AP - m2m_wifi_enable_ap(&apConfig); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode - -*/ -NMI_API sint8 m2m_wifi_enable_ap(CONST tstrM2MAPConfig* pstrM2MAPConfig); - /**@}*/ -/** @defgroup WifiDisableApFn m2m_wifi_disable_ap - * @ingroup WLANAPI - * Synchronous Wi-Fi hot-spot disabling function. Must be called only when the AP is enabled through the @ref m2m_wifi_enable_ap - * function. Otherwise the call to this function will not be useful. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_disable_ap(void); -@see - m2m_wifi_enable_ap -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_disable_ap(void); - /**@}*/ -/** @defgroup SetStaticIPFn m2m_wifi_set_static_ip - * @ingroup WLANAPI - * Synchronous static IP Address configuration function. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_set_static_ip(tstrM2MIPConfig * pstrStaticIPConf); - -@param [in] pstrStaticIPConf - Pointer to a structure holding the static IP Configurations (IP, - Gateway, subnet mask and DNS address). - -@pre The application must disable auto DHCP using @ref m2m_wifi_enable_dhcp before assigning a static IP address. - -@brief Assign a static IP address to the WINC board. - This function assigns a static IP address in case the AP doesn't have a DHCP server or in case the application wants to assign - a predefined known IP address. The user must take in mind that assigning a static IP address might result in an IP address - conflict. In case of an IP address conflict observed by the WINC board the user will get a response of @ref M2M_WIFI_RESP_IP_CONFLICT - in the wifi callback. The application is then responsible to either solve the conflict or assign another IP address. -@warning - Normally this function normally should not be used. DHCP configuration is requested automatically after successful Wi-Fi connection is established. - -@see - tstrM2MIPConfig - - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_set_static_ip(tstrM2MIPConfig * pstrStaticIPConf); - - /**@}*/ -/** @defgroup RequestDHCPClientFn m2m_wifi_request_dhcp_client - * @ingroup WLANAPI - * Starts the DHCP client operation(DHCP requested by the firmware automatically in STA/AP/P2P mode). - * - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_request_dhcp_client(void); - -@warning - This function is legacy and exists only for compatability with older applications. DHCP configuration is requested automatically after successful Wi-Fi connection is established. - -@return - The function returns @ref M2M_SUCCESS always. -*/ -NMI_API sint8 m2m_wifi_request_dhcp_client(void); - /**@}*/ -/** @defgroup RequestDHCPServerFn m2m_wifi_request_dhcp_server - * @ingroup WLANAPI - * Dhcp requested by the firmware automatically in STA/AP/P2P mode). - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_request_dhcp_server(uint8* addr); - -@warning - This function is legacy and exists only for compatability with older applications. DHCP server is started automatically when enabling the AP mode. - - -@return - The function returns @ref M2M_SUCCESS always. -*/ -NMI_API sint8 m2m_wifi_request_dhcp_server(uint8* addr); - /**@}*/ -/** @defgroup WifiDHCPEnableFn m2m_wifi_enable_dhcp - * @ingroup WLANAPI - * Synchronous Wi-Fi DHCP enable function. This function Enable/Disable DHCP protocol. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_enable_dhcp(uint8 u8DhcpEn ); - -@brief - Enable/Disable the DHCP client after connection. - -@param [in] u8DhcpEn - Possible values: - 1: Enable DHCP client after connection. - 0: Disable DHCP client after connection. -@warnings - -DHCP client is enabled by default - -This Function should be called before using m2m_wifi_set_static_ip() - - -@sa - m2m_wifi_set_static_ip() - -@return - The function SHALL return @ref M2M_SUCCESS for successful operation and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_enable_dhcp(uint8 u8DhcpEn ); - /**@}*/ -/** @defgroup WifiSetScanOptionFn m2m_wifi_set_scan_options - * @ingroup WLANAPI - * Synchronous Wi-Fi scan settings function. This function sets the time configuration parameters for the scan operation. - */ - -/*! -@fn \ - sint8 m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption) - -@param [in] ptstrM2MScanOption; - Pointer to the structure holding the Scan Parameters. - -@see - tenuM2mScanCh - m2m_wifi_request_scan - tstrM2MScanOption - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption); - /**@}*/ -/** @defgroup WifiSetScanRegionFn m2m_wifi_set_scan_region - * @ingroup WLANAPI - * Synchronous wi-fi scan region setting function. - * This function sets the scan region, which will affect the range of possible scan channels. - * For 2.5GHz supported in the current release, the requested scan region can't exceed the maximum number of channels (14). - *@{*/ -/*! -@fn \ - sint8 m2m_wifi_set_scan_region(uint16 ScanRegion) - -@param [in] ScanRegion; - ASIA - NORTH_AMERICA -@see - tenuM2mScanCh - m2m_wifi_request_scan - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_set_scan_region(uint16 ScanRegion); - /**@}*/ -/** @defgroup WifiRequestScanFn m2m_wifi_request_scan -* @ingroup WLANAPI -* Asynchronous Wi-FI scan request on the given channel. The scan status is delivered in the wifi event callback and then the application -* is supposed to read the scan results sequentially. -* The number of APs found (N) is returned in event @ref M2M_WIFI_RESP_SCAN_DONE with the number of found -* APs. -* The application reads the list of APs by calling the function @ref m2m_wifi_req_scan_result N times. -* -*@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_request_scan(uint8 ch); - -@param [in] ch - RF Channel ID for SCAN operation. It should be set according to tenuM2mScanCh. - With a value of M2M_WIFI_CH_ALL(255)), means to scan all channels. - -@warning - This function is not allowed in P2P or AP modes. It works only for STA mode (both connected or disconnected states). - -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback - is done through passing it to the @ref m2m_wifi_init. - - The events @ref M2M_WIFI_RESP_SCAN_DONE and @ref M2M_WIFI_RESP_SCAN_RESULT. - must be handled in the callback. - - The @ref m2m_wifi_handle_events function MUST be called to receive the responses in the callback. - -@see - M2M_WIFI_RESP_SCAN_DONE - M2M_WIFI_RESP_SCAN_RESULT - tpfAppWifiCb - tstrM2mWifiscanResult - tenuM2mScanCh - m2m_wifi_init - m2m_wifi_handle_events - m2m_wifi_req_scan_result - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of - the events received in response. -@code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - static uint8 u8ScanResultIdx = 0; - - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_SCAN_DONE: - { - tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; - - printf("Num of AP found %d\n",pstrInfo->u8NumofCh); - if(pstrInfo->s8ScanState == M2M_SUCCESS) - { - u8ScanResultIdx = 0; - if(pstrInfo->u8NumofCh >= 1) - { - m2m_wifi_req_scan_result(u8ScanResultIdx); - u8ScanResultIdx ++; - } - else - { - printf("No AP Found Rescan\n"); - m2m_wifi_request_scan(M2M_WIFI_CH_ALL); - } - } - else - { - printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); - } - } - break; - - case M2M_WIFI_RESP_SCAN_RESULT: - { - tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; - uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); - - printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", - pstrScanResult->u8index,pstrScanResult->s8rssi, - pstrScanResult->u8AuthType, - pstrScanResult->u8ch, - pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], - pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], - pstrScanResult->au8SSID); - - if(u8ScanResultIdx < u8NumFoundAPs) - { - // Read the next scan result - m2m_wifi_req_scan_result(index); - u8ScanResultIdx ++; - } - } - break; - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // Scan all channels - m2m_wifi_request_scan(M2M_WIFI_CH_ALL); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API sint8 m2m_wifi_request_scan(uint8 ch); - - /**@}*/ -/** @defgroup WifiRequestScanFn m2m_wifi_request_scan_passive -* @ingroup WLANAPI -* Same as m2m_wifi_request_scan but perform passive scanning while the other one perform active scanning. - -* -*@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_request_scan_passive(uint8 ch, uint16 scan_time); - -@param [in] ch - RF Channel ID for SCAN operation. It should be set according to tenuM2mScanCh. - With a value of M2M_WIFI_CH_ALL(255)), means to scan all channels. - -@param [in] scan_time - The time in ms that passive scan is listening to beacons on each channel per one slot, enter 0 for deafult setting. - -@warning - This function is not allowed in P2P or AP modes. It works only for STA mode (both connected or disconnected states). - -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback - is done through passing it to the @ref m2m_wifi_init. - - The events @ref M2M_WIFI_RESP_SCAN_DONE and @ref M2M_WIFI_RESP_SCAN_RESULT. - must be handled in the callback. - - The @ref m2m_wifi_handle_events function MUST be called to receive the responses in the callback. - -@see - m2m_wifi_request_scan - M2M_WIFI_RESP_SCAN_DONE - M2M_WIFI_RESP_SCAN_RESULT - tpfAppWifiCb - tstrM2mWifiscanResult - tenuM2mScanCh - m2m_wifi_init - m2m_wifi_handle_events - m2m_wifi_req_scan_result - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_request_scan_passive(uint8 ch, uint16 scan_time); - - - /**@}*/ -/** @defgroup WifiRequestScanFn m2m_wifi_request_scan_ssid_list -* @ingroup WLANAPI -* Asynchronous wi-fi scan request on the given channel and the hidden scan list. The scan status is delivered in the wi-fi event callback and then the application -* is to read the scan results sequentially. -* The number of APs found (N) is returned in event @ref M2M_WIFI_RESP_SCAN_DONE with the number of found -* APs. -* The application could read the list of APs by calling the function @ref m2m_wifi_req_scan_result N times. -* -*@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_request_scan_ssid_list(uint8 ch,uint8 * u8SsidList); - -@param [in] ch - RF Channel ID for SCAN operation. It should be set according to tenuM2mScanCh. - With a value of M2M_WIFI_CH_ALL(255)), means to scan all channels. -@param [in] u8SsidList - u8SsidList is a buffer containing a list of hidden SSIDs to - include during the scan. The first byte in the buffer, u8SsidList[0], - is the number of SSIDs encoded in the string. The number of hidden SSIDs - cannot exceed MAX_HIDDEN_SITES. All SSIDs are concatenated in the following - bytes and each SSID is prefixed with a one-byte header containing its length. - The total number of bytes in u8SsidList buffer, including length byte, cannot - exceed 133 bytes (MAX_HIDDEN_SITES SSIDs x 32 bytes each, which is max SSID length). - For instance, encoding the two hidden SSIDs "DEMO_AP" and "TEST" - results in the following buffer content: -@code - uint8 u8SsidList[14]; - u8SsidList[0] = 2; // Number of SSIDs is 2 - u8SsidList[1] = 7; // Length of the string "DEMO_AP" without NULL termination - memcpy(&u8SsidList[2], "DEMO_AP", 7); // Bytes index 2-9 containing the string DEMO_AP - u8SsidList[9] = 4; // Length of the string "TEST" without NULL termination - memcpy(&u8SsidList[10], "TEST", 4); // Bytes index 10-13 containing the string TEST -@endcode - -@warning - This function is not allowed in P2P. It works only for STA/AP mode (connected or disconnected). - -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback - is done through passing it to the @ref m2m_wifi_init. - - The events @ref M2M_WIFI_RESP_SCAN_DONE and @ref M2M_WIFI_RESP_SCAN_RESULT. - must be handled in the callback. - - The @ref m2m_wifi_handle_events function MUST be called to receive the responses in the callback. - -@see - M2M_WIFI_RESP_SCAN_DONE - M2M_WIFI_RESP_SCAN_RESULT - tpfAppWifiCb - tstrM2mWifiscanResult - tenuM2mScanCh - m2m_wifi_init - m2m_wifi_handle_events - m2m_wifi_req_scan_result - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of - the events received in response. -@code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - static void request_scan_hidden_demo_ap(void); - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - static uint8 u8ScanResultIdx = 0; - - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_SCAN_DONE: - { - tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; - - printf("Num of AP found %d\n",pstrInfo->u8NumofCh); - if(pstrInfo->s8ScanState == M2M_SUCCESS) - { - u8ScanResultIdx = 0; - if(pstrInfo->u8NumofCh >= 1) - { - m2m_wifi_req_scan_result(u8ScanResultIdx); - u8ScanResultIdx ++; - } - else - { - printf("No AP Found Rescan\n"); - request_scan_hidden_demo_ap(); - } - } - else - { - printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); - } - } - break; - - case M2M_WIFI_RESP_SCAN_RESULT: - { - tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; - uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); - - printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", - pstrScanResult->u8index,pstrScanResult->s8rssi, - pstrScanResult->u8AuthType, - pstrScanResult->u8ch, - pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], - pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], - pstrScanResult->au8SSID); - - if(u8ScanResultIdx < u8NumFoundAPs) - { - // Read the next scan result - m2m_wifi_req_scan_result(index); - u8ScanResultIdx ++; - } - } - break; - default: - break; - } - } - - static void request_scan_hidden_demo_ap(void) - { - uint8 list[9]; - char ssid[] = "DEMO_AP"; - uint8 len = (uint8)(sizeof(ssid)-1); - - list[0] = 1; - list[1] = len; - memcpy(&list[2], ssid, len); // copy 7 bytes - // Scan all channels - m2m_wifi_request_scan_ssid_list(M2M_WIFI_CH_ALL, list); - } - - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - request_scan_hidden_demo_ap(); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API sint8 m2m_wifi_request_scan_ssid_list(uint8 ch,uint8 * u8Ssidlist); - -/**@}*/ -/** @defgroup WifiGetNumAPFoundFn m2m_wifi_get_num_ap_found - * @ingroup WLANAPI -* Synchronous function to retrieve the number of AP's found in the last scan request, The function reads the number of APs from global variable which was updated in the Wi-Fi callback function through the M2M_WIFI_RESP_SCAN_DONE event. -* Function used only in STA mode only. - */ - /**@{*/ -/*! -@fn NMI_API uint8 m2m_wifi_get_num_ap_found(void); - -@see m2m_wifi_request_scan - M2M_WIFI_RESP_SCAN_DONE - M2M_WIFI_RESP_SCAN_RESULT -@pre m2m_wifi_request_scan need to be called first - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback - is done through passing it to the @ref m2m_wifi_init. - - The event @ref M2M_WIFI_RESP_SCAN_DONE must be handled in the callback to receive the requested scan information. -@warning This function must be called only in the wi-fi callback function when the events @ref M2M_WIFI_RESP_SCAN_DONE or @ref M2M_WIFI_RESP_SCAN_RESULT - are received. - Calling this function in any other place will result in undefined/outdated numbers. -@return Return the number of AP's found in the last Scan Request. - -\section Example - The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of - the events received in response. -@code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - static uint8 u8ScanResultIdx = 0; - - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_SCAN_DONE: - { - tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; - - printf("Num of AP found %d\n",pstrInfo->u8NumofCh); - if(pstrInfo->s8ScanState == M2M_SUCCESS) - { - u8ScanResultIdx = 0; - if(pstrInfo->u8NumofCh >= 1) - { - m2m_wifi_req_scan_result(u8ScanResultIdx); - u8ScanResultIdx ++; - } - else - { - printf("No AP Found Rescan\n"); - m2m_wifi_request_scan(M2M_WIFI_CH_ALL); - } - } - else - { - printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); - } - } - break; - - case M2M_WIFI_RESP_SCAN_RESULT: - { - tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; - uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); - - printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", - pstrScanResult->u8index,pstrScanResult->s8rssi, - pstrScanResult->u8AuthType, - pstrScanResult->u8ch, - pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], - pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], - pstrScanResult->au8SSID); - - if(u8ScanResultIdx < u8NumFoundAPs) - { - // Read the next scan result - m2m_wifi_req_scan_result(index); - u8ScanResultIdx ++; - } - } - break; - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // Scan all channels - m2m_wifi_request_scan(M2M_WIFI_CH_ALL); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API uint8 m2m_wifi_get_num_ap_found(void); -/**@}*/ -/** @defgroup WifiReqScanResult m2m_wifi_req_scan_result -* @ingroup WLANAPI -* Synchronous call to read the AP information from the SCAN Result list with the given index. -* This function is expected to be called when the response events M2M_WIFI_RESP_SCAN_RESULT or -* M2M_WIFI_RESP_SCAN_DONE are received in the wi-fi callback function. -* The response information received can be obtained through the casting to the @ref tstrM2mWifiscanResult structure - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_req_scan_result(uint8 index); -@param [in] index - Index for the requested result, the index range start from 0 till number of AP's found - -@see tstrM2mWifiscanResult - m2m_wifi_get_num_ap_found - m2m_wifi_request_scan - -@pre @ref m2m_wifi_request_scan needs to be called first, then m2m_wifi_get_num_ap_found - to get the number of AP's found - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback - is done through passing it to the @ref m2m_wifi_init function. - - The event @ref M2M_WIFI_RESP_SCAN_RESULT must be handled in the callback to receive the requested scan information. -@warning Function used in STA mode only. the scan results are updated only if the scan request is called. - Calling this function only without a scan request will lead to firmware errors. - Refrain from introducing a large delay between the scan request and the scan result request, to prevent - errors occurring. - -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of - the events received in response. -@code - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - static uint8 u8ScanResultIdx = 0; - - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_SCAN_DONE: - { - tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; - - printf("Num of AP found %d\n",pstrInfo->u8NumofCh); - if(pstrInfo->s8ScanState == M2M_SUCCESS) - { - u8ScanResultIdx = 0; - if(pstrInfo->u8NumofCh >= 1) - { - m2m_wifi_req_scan_result(u8ScanResultIdx); - u8ScanResultIdx ++; - } - else - { - printf("No AP Found Rescan\n"); - m2m_wifi_request_scan(M2M_WIFI_CH_ALL); - } - } - else - { - printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); - } - } - break; - - case M2M_WIFI_RESP_SCAN_RESULT: - { - tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; - uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); - - printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", - pstrScanResult->u8index,pstrScanResult->s8rssi, - pstrScanResult->u8AuthType, - pstrScanResult->u8ch, - pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], - pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], - pstrScanResult->au8SSID); - - if(u8ScanResultIdx < u8NumFoundAPs) - { - // Read the next scan result - m2m_wifi_req_scan_result(index); - u8ScanResultIdx ++; - } - } - break; - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // Scan all channels - m2m_wifi_request_scan(M2M_WIFI_CH_ALL); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API sint8 m2m_wifi_req_scan_result(uint8 index); -/**@}*/ -/** @defgroup WifiReqCurrentRssiFn m2m_wifi_req_curr_rssi - * @ingroup WLANAPI - * Asynchronous request for the current RSSI of the connected AP. - * The response received in through the @ref M2M_WIFI_RESP_CURRENT_RSSI event. - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_req_curr_rssi(void); -@pre - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered before initialization. Registering the callback - is done through passing it to the [m2m_wifi_init](@ref m2m_wifi_init) through the @ref tstrWifiInitParam initialization structure. - - The event @ref M2M_WIFI_RESP_CURRENT_RSSI must be handled in the callback to receive the requested Rssi information. -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet demonstrates how the RSSI request is called in the application's main function and the handling of the event received in the callback. -@code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - static uint8 u8ScanResultIdx = 0; - - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_CURRENT_RSSI: - { - sint8 *rssi = (sint8*)pvMsg; - M2M_INFO("ch rssi %d\n",*rssi); - } - break; - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // Scan all channels - m2m_wifi_req_curr_rssi(); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode - -*/ -NMI_API sint8 m2m_wifi_req_curr_rssi(void); -/**@}*/ -/** @defgroup WifiGetOtpMacAddFn m2m_wifi_get_otp_mac_address -* @ingroup WLANAPI -* Request the MAC address stored on the One Time Programmable(OTP) memory of the device. -* The function is blocking until the response is received. -*/ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); - -@param [out] pu8MacAddr - Output MAC address buffer of 6 bytes size. Valid only if *pu8Valid=1. -@param [out] pu8IsValid - Output boolean value to indicate the validity of pu8MacAddr in OTP. - Output zero if the OTP memory is not programmed, non-zero otherwise. -@pre m2m_wifi_init required to be called before any WIFI/socket function -@see m2m_wifi_get_mac_address - -@return The function returns @ref M2M_SUCCESS for success and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); -/**@}*/ -/** @defgroup WifiGetMacAddFn m2m_wifi_get_mac_address -* @ingroup WLANAPI -* Function to retrieve the current MAC address. The function is blocking until the response is received. -*/ -/**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr) -@param [out] pu8MacAddr - Output MAC address buffer of 6 bytes size. -@pre m2m_wifi_init required to be called before any WIFI/socket function -@see m2m_wifi_get_otp_mac_address -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr); -/**@}*/ -/** @defgroup SetSleepModeFn m2m_wifi_set_sleep_mode - * @ingroup WLANAPI - * This is one of the two synchronous power-save setting functions that - * allow the host MCU application to tweak the system power consumption. Such tweaking can be done through one of two ways: -* 1) Changing the power save mode, to one of the allowed power save modes @ref tenuPowerSaveModes. This is done by setting the first parameter -* 2) Configuring DTIM monitoring: Configuring beacon monitoring parameters by enabling or disabling the reception of broadcast/multicast data. -* this is done by setting the second parameter. - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn); -@param [in] PsTyp - Desired power saving mode. Supported types are enumerated in @ref tenuPowerSaveModes. -@param [in] BcastEn - Broadcast reception enable flag. - If it is 1, the WINC1500 will be awake each DTIM beacon for receiving broadcast traffic. - If it is 0, the WINC1500: disable broadcast traffic. Through this flag the WINC1500 will not wakeup at the DTIM beacon, but it will wakeup depends only - on the the configured Listen Interval. - -@warning The function called once after initialization. - -@see tenuPowerSaveModes - m2m_wifi_get_sleep_mode - m2m_wifi_set_lsn_int - -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn); -/**@}*/ -/** @defgroup WifiRequestSleepFn m2m_wifi_request_sleep - * @ingroup WLANAPI - * Synchronous power-save sleep request function, which requests from the WINC1500 device to sleep in the currenlty configured power save mode as defined - * by the @ref m2m_wifi_set_sleep_mode, for a specific time as defined by the passed in parameter. - * This function should be used in the @ref M2M_PS_MANUAL power save mode only. - * A wake up request is automatically performed by the WINC1500 device when any host driver API function, e.g. Wi-Fi or socket operation is called. - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_request_sleep(uint32 u32SlpReqTime); -@param [in] u32SlpReqTime - Request sleep time in ms - The best recommended sleep duration is left to be determined by the application. Taking into account that if the application sends notifications very rarely, - sleeping for a long time can be a power-efficient decision. In contrast applications that are senstive for long periods of absence can experience - performance degradation in the connection if long sleeping times are used. -@warning The function should be called in @ref M2M_PS_MANUAL power save mode only. As enumerated in @ref tenuPowerSaveModes - It's also important to note that during the sleeping time while in the M2M_PS_MANUAL mode, AP beacon monitoring is bypassed and the wifi-connection may drop if - the sleep period is enlongated. -@see tenuPowerSaveModes - m2m_wifi_set_sleep_mode - -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_request_sleep(uint32 u32SlpReqTime); -/**@}*/ -/** @defgroup GetSleepModeFn m2m_wifi_get_sleep_mode - * @ingroup WLANAPI - * Synchronous power save mode retrieval function. - */ - /**@{*/ -/*! -@fn NMI_API uint8 m2m_wifi_get_sleep_mode(void); -@see tenuPowerSaveModes - m2m_wifi_set_sleep_mode -@return The current operating power saving mode based on the enumerated sleep modes @ref tenuPowerSaveModes. -*/ -NMI_API uint8 m2m_wifi_get_sleep_mode(void); -/**@}*/ -/** @defgroup WifiReqClientCtrlFn m2m_wifi_req_client_ctrl - * @ingroup WLANAPI - * Asynchronous command sending function to the PS Client (An WINC1500 board running the ps_firmware) -* if the PS client send any command it will be received through the @ref M2M_WIFI_RESP_CLIENT_INFO event - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_req_client_ctrl(uint8 cmd); -@brief -@param [in] cmd - Control command sent from PS Server to PS Client (command values defined by the application) -@pre @ref m2m_wifi_req_server_init should be called first -@warning This mode is not supported in the current release. -@see m2m_wifi_req_server_init - M2M_WIFI_RESP_CLIENT_INFO -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_req_client_ctrl(uint8 cmd); -/**@}*/ -/** @defgroup WifiReqServerInit m2m_wifi_req_server_init - * @ingroup WLANAPI - * Synchronous function to initialize the PS Server. - * The WINC1500 supports non secure communication with another WINC1500, -* (SERVER/CLIENT) through one byte command (probe request and probe response) without any connection setup. -* The server mode can't be used with any other modes (STA/P2P/AP) -*/ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_req_server_init(uint8 ch); -@param [in] ch - Server listening channel -@see m2m_wifi_req_client_ctrl -@warning This mode is not supported in the current release. -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_req_server_init(uint8 ch); -/**@}*/ -/** @defgroup WifiSetDeviceNameFn m2m_wifi_set_device_name - * @ingroup WLANAPI - * Sets the WINC device name. The name string is used as a device name in both (P2P) WiFi-Direct mode as well as DHCP hostname (option 12). - * For P2P devices to communicate a device name must be present. If it is not set through this function a default name is assigned. - * The default name is WINC-XX-YY, where XX and YY are the last 2 octets of the OTP MAC address. If OTP (eFuse) is programmed, - * then the default name is WINC-00-00. - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength); -@param [in] pu8DeviceName - A Buffer holding the device name. Device name is a null terminated C string. -@param [in] u8DeviceNameLength - The length of the device name. Should not exceed the maximum device name's length @ref M2M_DEVICE_NAME_MAX (including null character). -@warning The function called once after initialization. - Used for the Wi-Fi Direct (P2P) as well as DHCP client hostname option (12). -@warning Device name shall contain only characters allowed in valid internet host name as defined in RFC 952 and 1123. -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength); -/**@}*/ -/** @defgroup WifiSetLsnIntFn m2m_wifi_set_lsn_int - * @ingroup WLANAPI -* This is one of the two synchronous power-save setting functions that -* allow the host MCU application to tweak the system power consumption. Such tweaking can be done by modifying the -* the Wi-Fi listen interval. The listen interval is how many beacon periods the station can sleep before it wakes up to receive data buffer in AP. -* It is represented in units of AP beacon periods(100ms). -*/ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt * pstrM2mLsnInt); - -@param [in] pstrM2mLsnInt - Structure holding the listen interval configurations. -@pre Function @m2m_wifi_set_sleep_mode shall be called first, to set the power saving mode required. -@warning The function should be called once after initialization. -@see tstrM2mLsnInt - m2m_wifi_set_sleep_mode -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt *pstrM2mLsnInt); -/**@}*/ -/** @defgroup WifiEnableMonitorModeFn m2m_wifi_enable_monitoring_mode - * @ingroup WLANAPI - * Asynchronous Wi-Fi monitoring mode (Promiscuous mode) enabling function. This function enables the monitoring mode, thus allowing two operations to be performed: - * 1) Transmission of manually configured frames, through using the @ref m2m_wifi_send_wlan_pkt function. - * 2) Reception of frames based on a defined filtering criteria - * When the monitoring mode is enabled, reception of all frames that satisfy the filter criteria passed in as a parameter is allowed, on the current wireless channel \n. - * All packets that meet the filtering criteria are passed to the application layer, to be handled by the assigned monitoring callback function \n. - * The monitoring callback function must be implemented before starting the monitoring mode, in-order to handle the packets received \n. - * Registering of the implemented callback function is through the callback pointer @ref tpfAppMonCb in the @ref tstrWifiInitParam structure\n. - * passed to @ref m2m_wifi_init function at initialization. - * - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_enable_monitoring_mode(tstrM2MWifiMonitorModeCtrl *, uint8 *, uint16 , uint16); - * @param [in] pstrMtrCtrl - * Pointer to @ref tstrM2MWifiMonitorModeCtrl structure holding the filtering parameters. - * @param [in] pu8PayloadBuffer - * Pointer to a buffer allocated by the application. The buffer SHALL hold the Data field of - * the WIFI RX Packet (Or a part from it). If it is set to NULL, the WIFI data payload will - * be discarded by the monitoring driver. - * @param [in] u16BufferSize - * The total size of the pu8PayloadBuffer in bytes. - * @param [in] u16DataOffset - * Starting offset in the DATA FIELD of the received WIFI packet. The application may be interested - * in reading specific information from the received packet. It must assign the offset to the starting - * position of it relative to the DATA payload start.\n - * \e Example, \e if \e the \e SSID \e is \e needed \e to \e be \e read \e from \e a \e PROBE \e REQ \e packet, \e the \e u16Offset \e MUST \e be \e set \e to \e 0. - * @warning When This mode is enabled, you can not be connected in any mode (Station, Access Point, or P2P).\n - * @see tstrM2MWifiMonitorModeCtrl - tstrM2MWifiRxPacketInfo - tstrWifiInitParam - tenuM2mScanCh - m2m_wifi_disable_monitoring_mode - m2m_wifi_send_wlan_pkt - m2m_wifi_send_ethernet_pkt - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*\section Example -* The example demonstrates the main function where-by the monitoring enable function is called after the initialization of the driver and the packets are -* handled in the callback function. -* @code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - //Declare receive buffer - uint8 gmgmt[1600]; - - //Callback functions - void wifi_cb(uint8 u8WiFiEvent, void * pvMsg) - { - ; - } - void wifi_monitoring_cb(tstrM2MWifiRxPacketInfo *pstrWifiRxPacket, uint8 *pu8Payload, uint16 u16PayloadSize) - { - if((NULL != pstrWifiRxPacket) && (0 != u16PayloadSize)) { - if(MANAGEMENT == pstrWifiRxPacket->u8FrameType) { - M2M_INFO("***# MGMT PACKET #***\n"); - } else if(DATA_BASICTYPE == pstrWifiRxPacket->u8FrameType) { - M2M_INFO("***# DATA PACKET #***\n"); - } else if(CONTROL == pstrWifiRxPacket->u8FrameType) { - M2M_INFO("***# CONTROL PACKET #***\n"); - } - } - } - - int main() - { - //Register wifi_monitoring_cb - tstrWifiInitParam param; - param.pfAppWifiCb = wifi_cb; - param.pfAppMonCb = wifi_monitoring_cb; - - nm_bsp_init(); - - if(!m2m_wifi_init(¶m)) { - //Enable Monitor Mode with filter to receive all data frames on channel 1 - tstrM2MWifiMonitorModeCtrl strMonitorCtrl = {0}; - strMonitorCtrl.u8ChannelID = M2M_WIFI_CH_1; - strMonitorCtrl.u8FrameType = DATA_BASICTYPE; - strMonitorCtrl.u8FrameSubtype = M2M_WIFI_FRAME_SUB_TYPE_ANY; //Receive any subtype of data frame - m2m_wifi_enable_monitoring_mode(&strMonitorCtrl, gmgmt, sizeof(gmgmt), 0); - - while(1) { - m2m_wifi_handle_events(NULL); - } - } - return 0; - } - * @endcode - */ -NMI_API sint8 m2m_wifi_enable_monitoring_mode(tstrM2MWifiMonitorModeCtrl *pstrMtrCtrl, uint8 *pu8PayloadBuffer, - uint16 u16BufferSize, uint16 u16DataOffset); -/**@}*/ -/** @defgroup WifiDisableMonitorModeFn m2m_wifi_disable_monitoring_mode - * @ingroup WLANAPI - * Synchronous function to disable Wi-Fi monitoring mode (Promiscuous mode). Expected to be called, if the enable monitoring mode is set, but if it was called without enabling - * no negative impact will reside. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_disable_monitoring_mode(void); - * @see m2m_wifi_enable_monitoring_mode - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_disable_monitoring_mode(void); - /**@}*/ - /** @defgroup SendWlanPktFn m2m_wifi_send_wlan_pkt - * @ingroup WLANAPI - * Synchronous function to transmit a WIFI RAW packet while the implementation of this packet is left to the application developer. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_send_wlan_pkt(uint8 *, uint16, uint16); - - * @param [in] pu8WlanPacket - * Pointer to a buffer holding the whole WIFI frame. - * @param [in] u16WlanHeaderLength - * The size of the WIFI packet header ONLY. - * @param [in] u16WlanPktSize - * The size of the whole bytes in packet. - * @see m2m_wifi_enable_monitoring_mode - m2m_wifi_disable_monitoring_mode - * @pre Enable Monitoring mode first using @ref m2m_wifi_enable_monitoring_mode - * @warning This function available in monitoring mode ONLY.\n - * @note Packets are user's responsibility. - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_send_wlan_pkt(uint8 *pu8WlanPacket, uint16 u16WlanHeaderLength, uint16 u16WlanPktSize); -/**@}*/ -/** @defgroup WifiSendEthernetPktFn m2m_wifi_send_ethernet_pkt - * @ingroup WLANAPI - * Synchronous function to transmit an Ethernet packet. Transmit a packet directly in ETHERNET/bypass mode where the TCP/IP stack is disabled and the implementation of this packet is left to the application developer. - * The Ethernet packet composition is left to the application developer. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_send_ethernet_pkt(uint8* pu8Packet,uint16 u16PacketSize) - * @param [in] pu8Packet - * Pointer to a buffer holding the whole Ethernet frame. - * @param [in] u16PacketSize - * The size of the whole bytes in packet. - * @warning This function available in ETHERNET/Bypass mode ONLY. Make sure that application defines @ref ETH_MODE.\n - * @note Packets are the user's responsibility. - * @sa m2m_wifi_enable_mac_mcast,m2m_wifi_set_receive_buffer - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - - */ -NMI_API sint8 m2m_wifi_send_ethernet_pkt(uint8* pu8Packet,uint16 u16PacketSize); -/**@}*/ -/** @defgroup WifiEnableSntpFn m2m_wifi_enable_sntp - * @ingroup WLANAPI - * Synchronous function to enable/disable the native Simple Network Time Protocol(SNTP) client in the WINC1500 firmware.\n - * The SNTP is enabled by default at start-up.The SNTP client at firmware is used to synchronize the system clock to the UTC time from the well known time - * servers (e.g. "time-c.nist.gov"). The SNTP client uses a default update cycle of 1 day. - * The UTC is important for checking the expiration date of X509 certificates used while establishing - * TLS (Transport Layer Security) connections. - * It is highly recommended to use it if there is no other means to get the UTC time. If there is a RTC - * on the host MCU, the SNTP could be disabled and the host should set the system time to the firmware - * using the @ref m2m_wifi_set_system_time function. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_enable_sntp(uint8); - * @param [in] bEnable -* Enabling/Disabling flag - * '0' :disable SNTP - * '1' :enable SNTP - * @see m2m_wifi_set_sytem_time - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_enable_sntp(uint8 bEnable); -/**@}*/ -/** @defgroup WifiSetSystemTime m2m_wifi_set_sytem_time - * @ingroup WLANAPI - * Synchronous function for setting the system time in time/date format (@ref uint32).\n - * The @ref tstrSystemTime structure can be used as a reference to the time values that should be set and pass its value as @ref uint32 - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_set_sytem_time(uint32); - * @param [in] u32UTCSeconds - * Seconds elapsed since January 1, 1900 (NTP Timestamp). - * @see m2m_wifi_enable_sntp - * tstrSystemTime - * @note If there is an RTC on the host MCU, the SNTP could be disabled and the host should set the system time to the firmware - * using the API @ref m2m_wifi_set_sytem_time. - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_set_sytem_time(uint32 u32UTCSeconds); -/**@}*/ -/** @defgroup WifiGetSystemTime m2m_wifi_get_sytem_time - * @ingroup WLANAPI - * Asynchronous function used to retrieve the system time through the use of the response @ref M2M_WIFI_RESP_GET_SYS_TIME. - * Response time retrieved is parsed into the members defined in the structure @ref tstrSystemTime. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_get_sytem_time(void); - * @see m2m_wifi_enable_sntp - tstrSystemTime - * @note Get the system time from the SNTP client - * using the API @ref m2m_wifi_get_sytem_time. - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_get_sytem_time(void); -/**@}*/ -/** @defgroup WifiSetCustInfoElementFn m2m_wifi_set_cust_InfoElement - * @ingroup WLANAPI - * Synchronous function to Add/Remove user-defined Information Element to the WIFIBeacon and Probe Response frames while chip mode is Access Point Mode.\n - * According to the information element layout shown bellow, if it is required to set new data for the information elements, pass in the buffer with the - * information according to the sizes and ordering defined bellow. However, if it's required to delete these IEs, fill the buffer with zeros. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_set_cust_InfoElement(uint8*); - * @param [in] pau8M2mCustInfoElement - * Pointer to Buffer containing the IE to be sent. It is the application developer's responsibility to ensure on the correctness of the information element's ordering passed in. - * @warning - Size of All elements combined must not exceed 255 byte.\n - * - Used in Access Point Mode \n - * @note IEs Format will be follow the following layout:\n - * @verbatim - --------------- ---------- ---------- ------------------- -------- -------- ----------- ---------------------- - | Byte[0] | Byte[1] | Byte[2] | Byte[3:length1+2] | ..... | Byte[n] | Byte[n+1] | Byte[n+2:lengthx+2] | - |---------------|----------|----------|-------------------|-------- --------|-----------|------------------| - | #of all Bytes | IE1 ID | Length1 | Data1(Hex Coded) | ..... | IEx ID | Lengthx | Datax(Hex Coded) | - --------------- ---------- ---------- ------------------- -------- -------- ----------- ---------------------- - * @endverbatim - * @see m2m_wifi_enable_sntp - * tstrSystemTime - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - \section Example - The example demonstrates how the information elements are set using this function. - *@code - * - char elementData[21]; - static char state = 0; // To Add, Append, and Delete - if(0 == state) { //Add 3 IEs - state = 1; - //Total Number of Bytes - elementData[0]=12; - //First IE - elementData[1]=200; elementData[2]=1; elementData[3]='A'; - //Second IE - elementData[4]=201; elementData[5]=2; elementData[6]='B'; elementData[7]='C'; - //Third IE - elementData[8]=202; elementData[9]=3; elementData[10]='D'; elementData[11]=0; elementData[12]='F'; - } else if(1 == state) { - //Append 2 IEs to others, Notice that we keep old data in array starting with\n - //element 13 and total number of bytes increased to 20 - state = 2; - //Total Number of Bytes - elementData[0]=20; - //Fourth IE - elementData[13]=203; elementData[14]=1; elementData[15]='G'; - //Fifth IE - elementData[16]=204; elementData[17]=3; elementData[18]='X'; elementData[19]=5; elementData[20]='Z'; - } else if(2 == state) { //Delete All IEs - state = 0; - //Total Number of Bytes - elementData[0]=0; - } - m2m_wifi_set_cust_InfoElement(elementData); - * @endcode - */ -NMI_API sint8 m2m_wifi_set_cust_InfoElement(uint8* pau8M2mCustInfoElement); - /**@}*/ -/** @defgroup WifiSetPowerProfile m2m_wifi_set_power_profile - * @ingroup WLANAPI - * Change the power profile mode - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode); -@brief -@param [in] u8PwrMode - Change the WINC1500 power profile to different mode based on the enumeration - @ref tenuM2mPwrMode -@pre Must be called after the initializations and before any connection request and can't be changed in run time. -@sa tenuM2mPwrMode - m2m_wifi_init -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode); - /**@}*/ - /** @defgroup WifiSetTxPower m2m_wifi_set_tx_power - * @ingroup WLANAPI - * Set the TX power tenuM2mTxPwrLevel - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel); -@param [in] u8TxPwrLevel - change the TX power based on the enumeration tenuM2mTxPwrLevel -@pre Must be called after the initialization and before any connection request and can't be changed in runtime. -@sa tenuM2mTxPwrLevel - m2m_wifi_init -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel); - /**@}*/ -/** @defgroup WifiEnableFirmware m2m_wifi_enable_firmware_logs -* @ingroup WLANAPI -* Enable or Disable logs in run time (Disabling Firmware logs will -* enhance the firmware start-up time and performance) -*/ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable); -@param [in] u8Enable - Set 1 to enable the logs, 0 for disable -@pre Must be called after intialization through the following function @ref m2m_wifi_init -@sa __DISABLE_FIRMWARE_LOGS__ (build option to disable logs from initializations) - m2m_wifi_init -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable); - /**@}*/ - /** @defgroup WifiSetBatteryVoltage m2m_wifi_set_battery_voltage -* @ingroup WLANAPI -* Set the battery voltage to update the firmware calculations -*/ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_set_battery_voltage(uint8 u8BattVolt) -@brief Set the battery voltage to update the firmware calculations -@param [in] dbBattVolt - Battery Volt in double -@pre Must be called after intialization through the following function @ref m2m_wifi_init -@sa m2m_wifi_init -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -sint8 m2m_wifi_set_battery_voltage(uint16 u16BattVoltx100); - /**@}*/ - /** @defgroup WifiSetGains m2m_wifi_set_gains -* @ingroup WLANAPI -* Set the chip gains mainly (PPA for 11b/11gn) -*/ - /**@{*/ -/*! -@fn sint8 m2m_wifi_set_gains(tstrM2mWifiGainsParams* pstrM2mGain); -@brief Set the chip PPA gain for 11b/11gn -@param [in] pstrM2mGain - tstrM2mWifiGainsParams contain gain parmaters as implemnted in rf document -@pre Must be called after intialization through the following function @ref m2m_wifi_init -@sa m2m_wifi_init -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -sint8 m2m_wifi_set_gains(tstrM2mWifiGainsParams* pstrM2mGain); - /**@}*/ -/** @defgroup WifiGetFirmwareVersion m2m_wifi_get_firmware_version -* @ingroup WLANAPI -* Get Firmware version info as defined in the structure @ref tstrM2mRev. -*/ - /**@{*/ -/*! -@fn m2m_wifi_get_firmware_version(tstrM2mRev* pstrRev) -@param [out] M2mRev - Pointer to the structure @ref tstrM2mRev that contains the firmware version parameters -@pre Must be called after intialization through the following function @ref m2m_wifi_init -@sa m2m_wifi_init -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -sint8 m2m_wifi_get_firmware_version(tstrM2mRev *pstrRev); -/**@}*/ -#ifdef ETH_MODE -/** @defgroup WifiEnableMacMcastFn m2m_wifi_enable_mac_mcast - * @ingroup WLANAPI - * Synchronous function for filtering received MAC addresses from certain MAC address groups. - * This function allows the addtion/removal of certain MAC addresses, used in the multicast filter. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8 *, uint8); - * @brief - * @param [in] pu8MulticastMacAddress - * Pointer to MAC address - * @param [in] u8AddRemove - * A flag to add or remove the MAC ADDRESS, based on the following values: - * - 0 : remove MAC address - * - 1 : add MAC address - * @warning This function is available in ETHERNET/bypass mode ONLY. Make sure that the application defines @ref ETH_MODE.\n - * @note Maximum number of MAC addresses that could be added is 8. - * @sa m2m_wifi_set_receive_buffer, m2m_wifi_send_ethernet_pkt - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8* pu8MulticastMacAddress, uint8 u8AddRemove); -/**@}*/ -/** @defgroup SetReceiveBufferFn m2m_wifi_set_receive_buffer - * @ingroup WLANAPI - * Synchronous function for setting or modifying the receiver buffer's length. - * In the ETHERNET/bypass mode the application should define a callback of type @ref tpfAppEthCb, through which the application handles the received - * ethernet frames. It is through this callback function that the user can dynamically modify the length of the currently used receiver buffer. - *@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_set_receive_buffer(void *, uint16); - - * @param [in] pvBuffer - * Pointer to Buffer to receive data. - * NULL pointer causes a negative error @ref M2M_ERR_FAIL. - * - * @param [in] u16BufferLen - * Length of data to be received. Maximum length of data should not exceed the size defined by TCP/IP - * defined as @ref SOCKET_BUFFER_MAX_LENGTH - * - * @warning This function is available in the Ethernet/bypass mode ONLY. Make sure that the application defines @ref ETH_MODE.\n - * @sa m2m_wifi_enable_mac_mcast,m2m_wifi_send_ethernet_pkt - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_set_receive_buffer(void* pvBuffer,uint16 u16BufferLen); -/**@}*/ -#endif /* ETH_MODE */ -/** @defgroup GetPrngBytes m2m_wifi_prng_get_random_bytes - * @ingroup WLANAPI - * Asynchronous function for retrieving from the firmware a pseudo-random set of bytes as specifed in the size passed in as a parameter. - * The registered wifi-cb function retrieves the random bytes through the response @ref M2M_WIFI_RESP_GET_PRNG - *@{*/ -/*! - * @fn sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PRNGBuff,uint16 u16PRNGSize) - * @param [out] pu8PrngBuff - * Pointer to a buffer to receive data. - * @param [in] u16PrngSize - * Request size in bytes - *@warning Size greater than the maximum specified (@ref M2M_BUFFER_MAX_SIZE - sizeof(tstrPrng)) - * causes a negative error @ref M2M_ERR_FAIL. - *@see tstrPrng - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PrngBuff,uint16 u16PrngSize); -/**@}*/ -#ifdef __cplusplus -} -#endif -#endif /* __M2M_WIFI_H__ */ - diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ate_mode.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ate_mode.c deleted file mode 100644 index beb1af8..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ate_mode.c +++ /dev/null @@ -1,826 +0,0 @@ -/** - * - * \file - * - * \brief NMC1500 Peripherials Application Interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifdef _M2M_ATE_FW_ -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#include "driver/include/m2m_ate_mode.h" -#include "driver/source/nmasic.h" -#include "driver/source/nmdrv.h" -#include "m2m_hif.h" -#include "driver/source/nmbus.h" -#include "bsp/include/nm_bsp.h" - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#define rInterrupt_CORTUS_0 (0x10a8) -#define rInterrupt_CORTUS_1 (0x10ac) -#define rInterrupt_CORTUS_2 (0x10b0) - -#define rBurstTx_NMI_TX_RATE (0x161d00) -#define rBurstTx_NMI_NUM_TX_FRAMES (0x161d04) -#define rBurstTx_NMI_TX_FRAME_LEN (0x161d08) -#define rBurstTx_NMI_TX_CW_PARAM (0x161d0c) -#define rBurstTx_NMI_TX_GAIN (0x161d10) -#define rBurstTx_NMI_TX_DPD_CTRL (0x161d14) -#define rBurstTx_NMI_USE_PMU (0x161d18) -#define rBurstTx_NMI_TEST_CH (0x161d1c) -#define rBurstTx_NMI_TX_PHY_CONT (0x161d20) -#define rBurstTx_NMI_TX_CW_MODE (0x161d24) -#define rBurstTx_NMI_TEST_XO_OFF (0x161d28) -#define rBurstTx_NMI_USE_EFUSE_XO_OFF (0x161d2c) - -#define rBurstTx_NMI_MAC_FILTER_ENABLE_DA (0x161d30) -#define rBurstTx_NMI_MAC_ADDR_LO_PEER (0x161d34) -#define rBurstTx_NMI_MAC_ADDR_LO_SELF (0x161d38) -#define rBurstTx_NMI_MAC_ADDR_HI_PEER (0x161d3c) -#define rBurstTx_NMI_MAC_ADDR_HI_SELF (0x161d40) -#define rBurstTx_NMI_RX_PKT_CNT_SUCCESS (0x161d44) -#define rBurstTx_NMI_RX_PKT_CNT_FAIL (0x161d48) -#define rBurstTx_NMI_SET_SELF_MAC_ADDR (0x161d4c) -#define rBurstTx_NMI_MAC_ADDR_LO_SA (0x161d50) -#define rBurstTx_NMI_MAC_ADDR_HI_SA (0x161d54) -#define rBurstTx_NMI_MAC_FILTER_ENABLE_SA (0x161d58) - -#define rBurstRx_NMI_RX_ALL_PKTS_CONT (0x9898) -#define rBurstRx_NMI_RX_ERR_PKTS_CONT (0x988c) - -#define TX_DGAIN_MAX_NUM_REGS (4) -#define TX_DGAIN_REG_BASE_ADDRESS (0x1240) -#define TX_GAIN_CODE_MAX_NUM_REGS (3) -#define TX_GAIN_CODE_BASE_ADDRESS (0x1250) -#define TX_PA_MAX_NUM_REGS (3) -#define TX_PA_BASE_ADDRESS (0x1e58) -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -VARIABLES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -volatile static uint8 gu8AteIsRunning = 0; /*!< ATE firmware status, 1 means ATE is running otherwise stopped */ -volatile static uint8 gu8RxState = 0; /*!< RX status, 1 means Rx is running otherwise stopped */ -volatile static uint8 gu8TxState = 0; /*!< TX status, 1 means Tx is running otherwise stopped */ -volatile static uint32 gaAteFwTxRates[M2M_ATE_MAX_NUM_OF_RATES] = -{ - 0x01, 0x02, 0x05, 0x0B, /*B-Rats*/ - 0x06, 0x09, 0x0C, 0x12, 0x18, 0x24, 0x30, 0x36, /*G-Rats*/ - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87 /*N-Rats*/ -}; - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -STATIC FUNCTIONS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -static void m2m_ate_set_rx_status(uint8 u8Value) -{ - gu8RxState = u8Value; -} - -static void m2m_ate_set_tx_status(uint8 u8Value) -{ - gu8TxState = u8Value; -} - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION IMPLEMENTATION -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/*! -@fn \ - sint8 m2m_ate_init(void); - -@brief - This function used to download ATE firmware from flash and start it - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_init(void) -{ - sint8 s8Ret = M2M_SUCCESS; - uint8 u8WifiMode = M2M_WIFI_MODE_ATE_HIGH; - - s8Ret = nm_drv_init(&u8WifiMode); - - return s8Ret; -} - -/*! -@fn \ - sint8 m2m_ate_init(tstrM2mAteInit *pstrInit); - -@brief - This function used to download ATE firmware from flash and start it - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_init_param(tstrM2mAteInit *pstrInit) -{ - sint8 s8Ret = M2M_SUCCESS; - - s8Ret = nm_drv_init((void*)&pstrInit->u8RxPwrMode); - - return s8Ret; -} - -/*! -@fn \ - sint8 m2m_ate_deinit(void); - -@brief - De-Initialization of ATE firmware mode - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_deinit(void) -{ - return nm_drv_deinit(NULL); -} - -/*! -@fn \ - sint8 m2m_ate_set_fw_state(uint8); - -@brief - This function used to change ATE firmware status from running to stopped or vice versa. - -@param [in] u8State - Required state of ATE firmware, one of \ref tenuM2mAteFwState enumeration values. -@return - The function SHALL return 0 for success and a negative value otherwise. -\sa - m2m_ate_init -*/ -sint8 m2m_ate_set_fw_state(uint8 u8State) -{ - sint8 s8Ret = M2M_SUCCESS; - uint32_t u32Val = 0; - - if((M2M_ATE_FW_STATE_STOP == u8State) && (M2M_ATE_FW_STATE_STOP != gu8AteIsRunning)) - { - u32Val = nm_read_reg(rNMI_GLB_RESET); - u32Val &= ~(1 << 10); - s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val); - gu8AteIsRunning = M2M_ATE_FW_STATE_STOP; - } - else if((M2M_ATE_FW_STATE_RUN == u8State) && (M2M_ATE_FW_STATE_RUN != gu8AteIsRunning)) - { - /* 0x1118[0]=0 at power-on-reset: pad-based control. */ - /* Switch cortus reset register to register control. 0x1118[0]=1. */ - u32Val = nm_read_reg(rNMI_BOOT_RESET_MUX); - u32Val |= (1 << 0); - s8Ret = nm_write_reg(rNMI_BOOT_RESET_MUX, u32Val); - if(M2M_SUCCESS != s8Ret) - { - goto __EXIT; - } - /** - Write the firmware download complete magic value 0x10ADD09E at - location 0xFFFF000C (Cortus map) or C000C (AHB map). - This will let the boot-rom code execute from RAM. - **/ - s8Ret = nm_write_reg(0xc0000, 0x71); - if(M2M_SUCCESS != s8Ret) - { - goto __EXIT; - } - - u32Val = nm_read_reg(rNMI_GLB_RESET); - if((u32Val & (1ul << 10)) == (1ul << 10)) - { - u32Val &= ~(1ul << 10); - s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val); - if(M2M_SUCCESS != s8Ret) - { - goto __EXIT; - } - } - - u32Val |= (1ul << 10); - s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val); - if(M2M_SUCCESS != s8Ret) - { - goto __EXIT; - } - gu8AteIsRunning = M2M_ATE_FW_STATE_RUN; - } - else - { - s8Ret = M2M_ATE_ERR_UNHANDLED_CASE; - } - -__EXIT: - if((M2M_SUCCESS == s8Ret) && (M2M_ATE_FW_STATE_RUN == gu8AteIsRunning)) - { - nm_bsp_sleep(500); /*wait for ATE firmware start up*/ - } - return s8Ret; -} - -/*! -@fn \ - sint8 m2m_ate_get_fw_state(uint8); - -@brief - This function used to return status of ATE firmware. - -@return - The function SHALL return status of ATE firmware, one of \ref tenuM2mAteFwState enumeration values. -\sa - m2m_ate_init, m2m_ate_set_fw_state -*/ -sint8 m2m_ate_get_fw_state(void) -{ - return gu8AteIsRunning; -} - -/*! -@fn \ - uint32 m2m_ate_get_tx_rate(uint8); - -@brief - This function used to return value of TX rate required by application developer. - -@param [in] u8Index - Index of required rate , one of \ref tenuM2mAteTxIndexOfRates enumeration values. -@return - The function SHALL return 0 for in case of failure otherwise selected rate value. -\sa - tenuM2mAteTxIndexOfRates -*/ -uint32 m2m_ate_get_tx_rate(uint8 u8Index) -{ - if(M2M_ATE_MAX_NUM_OF_RATES <= u8Index) - { - return 0; - } - return gaAteFwTxRates[u8Index]; -} - -/*! -@fn \ - sint8 m2m_ate_get_tx_status(void); - -@brief - This function used to return status of TX test case either running or stopped. - -@return - The function SHALL return status of ATE firmware, 1 if TX is running otherwise 0. -\sa - m2m_ate_start_tx, m2m_ate_stop_tx -*/ -sint8 m2m_ate_get_tx_status(void) -{ - return gu8TxState; -} - -/*! -@fn \ - sint8 m2m_ate_start_tx(tstrM2mAteTx *) - -@brief - This function used to start TX test case. - -@param [in] strM2mAteTx - Type of \ref tstrM2mAteTx, with the values required to enable TX test case. You must use \ref m2m_ate_init first. -@return - The function SHALL return 0 for success and a negative value otherwise. -\sa - m2m_ate_init, m2m_ate_stop_tx, m2m_ate_get_tx_status -*/ -sint8 m2m_ate_start_tx(tstrM2mAteTx * strM2mAteTx) -{ - sint8 s8Ret = M2M_SUCCESS; - uint8 u8LoopCntr = 0; - uint32_t val32; - - - if(NULL == strM2mAteTx) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - if(0 != m2m_ate_get_tx_status()) - { - s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING; - goto __EXIT; - } - - if(0 != m2m_ate_get_rx_status()) - { - s8Ret = M2M_ATE_ERR_RX_ALREADY_RUNNING; - goto __EXIT; - } - - if( (strM2mAteTx->channel_num < M2M_ATE_CHANNEL_1) || - (strM2mAteTx->channel_num > M2M_ATE_CHANNEL_14) || - (strM2mAteTx->tx_gain_sel < M2M_ATE_TX_GAIN_DYNAMIC) || - (strM2mAteTx->tx_gain_sel > M2M_ATE_TX_GAIN_TELEC) || - (strM2mAteTx->frame_len > M2M_ATE_MAX_FRAME_LENGTH) || - (strM2mAteTx->frame_len < M2M_ATE_MIN_FRAME_LENGTH) - ) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - if( (strM2mAteTx->duty_cycle < M2M_ATE_TX_DUTY_MAX_VALUE /*1*/) || - (strM2mAteTx->duty_cycle > M2M_ATE_TX_DUTY_MIN_VALUE /*10*/ ) || - (strM2mAteTx->dpd_ctrl < M2M_ATE_TX_DPD_DYNAMIC) || - (strM2mAteTx->dpd_ctrl > M2M_ATE_TX_DPD_ENABLED) || - (strM2mAteTx->use_pmu > M2M_ATE_PMU_ENABLE) || - (strM2mAteTx->phy_burst_tx < M2M_ATE_TX_SRC_MAC) || - (strM2mAteTx->phy_burst_tx > M2M_ATE_TX_SRC_PHY) || - (strM2mAteTx->cw_tx < M2M_ATE_TX_MODE_NORM) || - (strM2mAteTx->cw_tx > M2M_ATE_TX_MODE_CW) - ) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - for(u8LoopCntr=0; u8LoopCntrdata_rate) - { - break; - } - } - - if(M2M_ATE_MAX_NUM_OF_RATES == u8LoopCntr) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - - - s8Ret += nm_write_reg(rBurstTx_NMI_USE_PMU, strM2mAteTx->use_pmu); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_PHY_CONT, strM2mAteTx->phy_burst_tx); - s8Ret += nm_write_reg(rBurstTx_NMI_NUM_TX_FRAMES, strM2mAteTx->num_frames); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_GAIN, strM2mAteTx->tx_gain_sel); - s8Ret += nm_write_reg(rBurstTx_NMI_TEST_CH, strM2mAteTx->channel_num); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_FRAME_LEN, strM2mAteTx->frame_len); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_CW_PARAM, strM2mAteTx->duty_cycle); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_DPD_CTRL, strM2mAteTx->dpd_ctrl); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_RATE, strM2mAteTx->data_rate); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_CW_MODE, strM2mAteTx->cw_tx); - s8Ret += nm_write_reg(rBurstTx_NMI_TEST_XO_OFF, strM2mAteTx->xo_offset_x1000); - s8Ret += nm_write_reg(rBurstTx_NMI_USE_EFUSE_XO_OFF, strM2mAteTx->use_efuse_xo_offset); - - val32 = strM2mAteTx->peer_mac_addr[5] << 0; - val32 |= strM2mAteTx->peer_mac_addr[4] << 8; - val32 |= strM2mAteTx->peer_mac_addr[3] << 16; - nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_PEER, val32 ); - - val32 = strM2mAteTx->peer_mac_addr[2] << 0; - val32 |= strM2mAteTx->peer_mac_addr[1] << 8; - val32 |= strM2mAteTx->peer_mac_addr[0] << 16; - nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_PEER, val32 ); - - if(M2M_SUCCESS == s8Ret) - { - s8Ret += nm_write_reg(rInterrupt_CORTUS_0, 1); /*Interrupt Cortus*/ - m2m_ate_set_tx_status(1); - nm_bsp_sleep(200); /*Recommended*/ - } - -__EXIT: - return s8Ret; -} - -/*! -@fn \ - sint8 m2m_ate_stop_tx(void) - -@brief - This function used to stop TX test case. - -@return - The function SHALL return 0 for success and a negative value otherwise. -\sa - m2m_ate_init, m2m_ate_start_tx, m2m_ate_get_tx_status -*/ -sint8 m2m_ate_stop_tx(void) -{ - sint8 s8Ret = M2M_SUCCESS; - - s8Ret = nm_write_reg(rInterrupt_CORTUS_1, 1); - if(M2M_SUCCESS == s8Ret) - { - m2m_ate_set_tx_status(0); - } - - return s8Ret; -} - -/*! -@fn \ - sint8 m2m_ate_get_rx_status(uint8); - -@brief - This function used to return status of RX test case either running or stopped. - -@return - The function SHALL return status of ATE firmware, 1 if RX is running otherwise 0. -\sa - m2m_ate_start_rx, m2m_ate_stop_rx -*/ -sint8 m2m_ate_get_rx_status(void) -{ - return gu8RxState; -} - -/*! -@fn \ - sint8 m2m_ate_start_rx(tstrM2mAteRx *) - -@brief - This function used to start RX test case. - -@param [in] strM2mAteRx - Type of \ref tstrM2mAteRx, with the values required to enable RX test case. You must use \ref m2m_ate_init first. -@return - The function SHALL return 0 for success and a negative value otherwise. -\sa - m2m_ate_init, m2m_ate_stop_rx, m2m_ate_get_rx_status -*/ -sint8 m2m_ate_start_rx(tstrM2mAteRx * strM2mAteRxStr) -{ - sint8 s8Ret = M2M_SUCCESS; - uint32 val32; - if(NULL == strM2mAteRxStr) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - if(0 != m2m_ate_get_tx_status()) - { - s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING; - goto __EXIT; - } - - if(0 != m2m_ate_get_rx_status()) - { - s8Ret = M2M_ATE_ERR_RX_ALREADY_RUNNING; - goto __EXIT; - } - - if( (strM2mAteRxStr->channel_num < M2M_ATE_CHANNEL_1) || - (strM2mAteRxStr->channel_num > M2M_ATE_CHANNEL_14)|| - (strM2mAteRxStr->use_pmu > M2M_ATE_PMU_ENABLE) - ) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - s8Ret += nm_write_reg(rBurstTx_NMI_TEST_CH, strM2mAteRxStr->channel_num); - s8Ret += nm_write_reg(rBurstTx_NMI_USE_PMU, strM2mAteRxStr->use_pmu); - s8Ret += nm_write_reg(rBurstTx_NMI_TEST_XO_OFF, strM2mAteRxStr->xo_offset_x1000); - s8Ret += nm_write_reg(rBurstTx_NMI_USE_EFUSE_XO_OFF, strM2mAteRxStr->use_efuse_xo_offset); - - if(strM2mAteRxStr->override_self_mac_addr) - { - val32 = strM2mAteRxStr->self_mac_addr[5] << 0; - val32 |= strM2mAteRxStr->self_mac_addr[4] << 8; - val32 |= strM2mAteRxStr->self_mac_addr[3] << 16; - nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_SELF, val32 ); - - val32 = strM2mAteRxStr->self_mac_addr[2] << 0; - val32 |= strM2mAteRxStr->self_mac_addr[1] << 8; - val32 |= strM2mAteRxStr->self_mac_addr[0] << 16; - nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_SELF, val32 ); - } - - if(strM2mAteRxStr->mac_filter_en_sa) - { - val32 = strM2mAteRxStr->peer_mac_addr[5] << 0; - val32 |= strM2mAteRxStr->peer_mac_addr[4] << 8; - val32 |= strM2mAteRxStr->peer_mac_addr[3] << 16; - nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_SA, val32 ); - - val32 = strM2mAteRxStr->peer_mac_addr[2] << 0; - val32 |= strM2mAteRxStr->peer_mac_addr[1] << 8; - val32 |= strM2mAteRxStr->peer_mac_addr[0] << 16; - nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_SA, val32 ); - } - - nm_write_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_DA, strM2mAteRxStr->mac_filter_en_da); - nm_write_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_SA, strM2mAteRxStr->mac_filter_en_sa); - nm_write_reg(rBurstTx_NMI_SET_SELF_MAC_ADDR, strM2mAteRxStr->override_self_mac_addr); - - if(M2M_SUCCESS == s8Ret) - { - s8Ret += nm_write_reg(rInterrupt_CORTUS_2, 1); /*Interrupt Cortus*/ - m2m_ate_set_rx_status(1); - nm_bsp_sleep(10); /*Recommended*/ - } - -__EXIT: - return s8Ret; -} - -/*! -@fn \ - sint8 m2m_ate_stop_rx(void) - -@brief - This function used to stop RX test case. - -@return - The function SHALL return 0 for success and a negative value otherwise. -\sa - m2m_ate_init, m2m_ate_start_rx, m2m_ate_get_rx_status -*/ -sint8 m2m_ate_stop_rx(void) -{ - m2m_ate_set_rx_status(0); - nm_bsp_sleep(200); /*Recommended*/ - return M2M_SUCCESS; -} - -/*! -@fn \ - sint8 m2m_ate_read_rx_status(tstrM2mAteRxStatus *) - -@brief - This function used to read RX statistics from ATE firmware. - -@param [out] strM2mAteRxStatus - Type of \ref tstrM2mAteRxStatus used to save statistics of RX test case. You must use \ref m2m_ate_start_rx first. -@return - The function SHALL return 0 for success and a negative value otherwise. -\sa - m2m_ate_init, m2m_ate_start_rx -*/ -sint8 m2m_ate_read_rx_status(tstrM2mAteRxStatus *strM2mAteRxStatus) -{ - sint8 s8Ret = M2M_SUCCESS; - - if(NULL == strM2mAteRxStatus) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - if(0 != m2m_ate_get_tx_status()) - { - s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING; - goto __EXIT; - } - - if (nm_read_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_DA) || nm_read_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_SA)) - { - strM2mAteRxStatus->num_rx_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_SUCCESS) + nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_FAIL); - strM2mAteRxStatus->num_good_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_SUCCESS); - strM2mAteRxStatus->num_err_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_FAIL); - } - else - { - strM2mAteRxStatus->num_rx_pkts = nm_read_reg(rBurstRx_NMI_RX_ALL_PKTS_CONT) + nm_read_reg(0x989c); - strM2mAteRxStatus->num_err_pkts = nm_read_reg(rBurstRx_NMI_RX_ERR_PKTS_CONT); - strM2mAteRxStatus->num_good_pkts = strM2mAteRxStatus->num_rx_pkts - strM2mAteRxStatus->num_err_pkts; - } - -__EXIT: - return s8Ret; -} -/*! -@fn \ - sint8 m2m_ate_set_dig_gain(double dGaindB) - -@brief - This function is used to set the digital gain - -@param [in] double dGaindB - The digital gain value required to be set. -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_set_dig_gain(double dGaindB) -{ - uint32_t dGain, val32; - dGain = (uint32_t)(pow(10, dGaindB/20.0) * 1024.0); - - val32 = nm_read_reg(0x160cd0); - val32 &= ~(0x1ffful << 0); - val32 |= (((uint32_t)dGain) << 0); - nm_write_reg(0x160cd0, val32); - return M2M_SUCCESS; -} -/*! -@fn \ - sint8 m2m_ate_get_dig_gain(double * dGaindB) - -@brief - This function is used to get the digital gain - -@param [out] double * dGaindB - The retrieved digital gain value obtained from HW registers in dB. -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_get_dig_gain(double * dGaindB) -{ - uint32 dGain, val32; - - if(!dGaindB) return M2M_ERR_INVALID_ARG; - - val32 = nm_read_reg(0x160cd0); - - dGain = (val32 >> 0) & 0x1ffful; - *dGaindB = 20.0*log10((double)dGain / 1024.0); - - return M2M_SUCCESS; -} -/*! -@fn \ - void m2m_ate_set_pa_gain(uint8 gain_db) - -@brief - This function is used to set the PA gain (18/15/12/9/6/3/0 only) - -@param [in] uint8 gain_db - PA gain level allowed (18/15/12/9/6/3/0 only) - -*/ -void m2m_ate_set_pa_gain(uint8 gain_db) -{ - uint32 PA_1e9c; - uint8 aGain[] = { - /* "0 dB" */ 0x00, - /* "3 dB" */ 0x01, - /* "6 dB" */ 0x03, - /* "9 dB" */ 0x07, - /* "12 dB" */ 0x0f, - /* "15 dB" */ 0x1f, - /* "18 dB" */ 0x3f }; - /* The variable PA gain is valid only for High power mode */ - PA_1e9c = nm_read_reg(0x1e9c); - /* TX bank 0. */ - PA_1e9c &= ~(0x3ful << 8); - PA_1e9c |= (((uint32)aGain[gain_db/3] & 0x3f) << 8); - nm_write_reg(0x1e9c, PA_1e9c); -} -/*! -@fn \ - sint8 m2m_ate_get_pa_gain(double *paGaindB) - -@brief - This function is used to get the PA gain - -@param [out] double *paGaindB - The retrieved PA gain value obtained from HW registers in dB. -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_get_pa_gain(double *paGaindB) -{ - uint32 val32, paGain; - uint32 m_cmbPAGainStep; - - if(!paGaindB) - return M2M_ERR_INVALID_ARG; - - val32 = nm_read_reg(0x1e9c); - - paGain = (val32 >> 8) & 0x3f; - - switch(paGain){ - case 0x1: - m_cmbPAGainStep = 5; - break; - case 0x3: - m_cmbPAGainStep = 4; - break; - case 0x7: - m_cmbPAGainStep = 3; - break; - case 0xf: - m_cmbPAGainStep = 2; - break; - case 0x1f: - m_cmbPAGainStep = 1; - break; - case 0x3f: - m_cmbPAGainStep = 0; - break; - default: - m_cmbPAGainStep = 0; - break; - } - - *paGaindB = 18 - m_cmbPAGainStep*3; - - return M2M_SUCCESS; -} -/*! -@fn \ - sint8 m2m_ate_get_ppa_gain(double * ppaGaindB) - -@brief - This function is used to get the PPA gain - -@param [out] uint32 * ppaGaindB - The retrieved PPA gain value obtained from HW registers in dB. -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_get_ppa_gain(double * ppaGaindB) -{ - uint32 val32, ppaGain, m_cmbPPAGainStep; - - if(!ppaGaindB) return M2M_ERR_INVALID_ARG; - - val32 = nm_read_reg(0x1ea0); - - ppaGain = (val32 >> 5) & 0x7; - - switch(ppaGain){ - case 0x1: - m_cmbPPAGainStep = 2; - break; - case 0x3: - m_cmbPPAGainStep = 1; - break; - case 0x7: - m_cmbPPAGainStep = 0; - break; - default: - m_cmbPPAGainStep = 3; - break; - } - - *ppaGaindB = 9 - m_cmbPPAGainStep*3; - - - return M2M_SUCCESS; -} -/*! -@fn \ - sint8 m2m_ate_get_tot_gain(double * totGaindB) - -@brief - This function is used to calculate the total gain - -@param [out] double * totGaindB - The retrieved total gain value obtained from calculations made based on the digital gain, PA and PPA gain values. -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_get_tot_gain(double * totGaindB) -{ - double dGaindB, paGaindB, ppaGaindB; - - if(!totGaindB) return M2M_ERR_INVALID_ARG; - - m2m_ate_get_pa_gain(&paGaindB); - m2m_ate_get_ppa_gain(&ppaGaindB); - m2m_ate_get_dig_gain(&dGaindB); - - *totGaindB = dGaindB + paGaindB + ppaGaindB; - - return M2M_SUCCESS; -} - -#endif //_M2M_ATE_FW_ \ No newline at end of file diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_crypto.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_crypto.c deleted file mode 100644 index 9ac7711..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_crypto.c +++ /dev/null @@ -1,1010 +0,0 @@ -/** - * - * \file - * - * \brief WINC Crypto module. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "driver/include/m2m_crypto.h" -#include "driver/source/nmbus.h" -#include "driver/source/nmasic.h" - -#ifdef CONF_CRYPTO_HW - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*======*======*======*======*======*=======* -* WINC SHA256 HW Engine Register Definition * -*======*======*======*======*======*========*/ - -#define SHA_BLOCK_SIZE (64) - -#define SHARED_MEM_BASE (0xd0000) - - -#define SHA256_MEM_BASE (0x180000UL) -#define SHA256_ENGINE_ADDR (0x180000ul) - -/* SHA256 Registers */ -#define SHA256_CTRL (SHA256_MEM_BASE+0x00) -#define SHA256_CTRL_START_CALC_MASK (NBIT0) -#define SHA256_CTRL_START_CALC_SHIFT (0) -#define SHA256_CTRL_PREPROCESS_MASK (NBIT1) -#define SHA256_CTRL_PREPROCESS_SHIFT (1) -#define SHA256_CTRL_HASH_HASH_MASK (NBIT2) -#define SHA256_CTRL_HASH_HASH_SHIFT (2) -#define SHA256_CTRL_INIT_SHA256_STATE_MASK (NBIT3) -#define SHA256_CTRL_INIT_SHA256_STATE_SHIFT (3) -#define SHA256_CTRL_WR_BACK_HASH_VALUE_MASK (NBIT4) -#define SHA256_CTRL_WR_BACK_HASH_VALUE_SHIFT (4) -#define SHA256_CTRL_FORCE_SHA256_QUIT_MASK (NBIT5) -#define SHA256_CTRL_FORCE_SHA256_QUIT_SHIFT (5) - -#define SHA256_REGS_SHA256_CTRL_AHB_BYTE_REV_EN (NBIT6) -#define SHA256_REGS_SHA256_CTRL_RESERVED (NBIT7) -#define SHA256_REGS_SHA256_CTRL_CORE_TO_AHB_CLK_RATIO (NBIT8+ NBIT9+ NBIT10) -#define SHA256_REGS_SHA256_CTRL_CORE_TO_AHB_CLK_RATIO_MASK (NBIT2+ NBIT1+ NBIT0) -#define SHA256_REGS_SHA256_CTRL_CORE_TO_AHB_CLK_RATIO_SHIFT (8) -#define SHA256_REGS_SHA256_CTRL_RESERVED_11 (NBIT11) -#define SHA256_REGS_SHA256_CTRL_SHA1_CALC (NBIT12) -#define SHA256_REGS_SHA256_CTRL_PBKDF2_SHA1_CALC (NBIT13) - - -#define SHA256_START_RD_ADDR (SHA256_MEM_BASE+0x04UL) -#define SHA256_DATA_LENGTH (SHA256_MEM_BASE+0x08UL) -#define SHA256_START_WR_ADDR (SHA256_MEM_BASE+0x0cUL) -#define SHA256_COND_CHK_CTRL (SHA256_MEM_BASE+0x10) -#define SHA256_COND_CHK_CTRL_HASH_VAL_COND_CHK_MASK (NBIT1 | NBIT0) -#define SHA256_COND_CHK_CTRL_HASH_VAL_COND_CHK_SHIFT (0) -#define SHA256_COND_CHK_CTRL_STEP_VAL_MASK (NBIT6 | NBIT5 | NBIT4 | NBIT3 | NBIT2) -#define SHA256_COND_CHK_CTRL_STEP_VAL_SHIFT (2) -#define SHA256_COND_CHK_CTRL_COND_CHK_RESULT_MASK (NBIT7) -#define SHA256_COND_CHK_CTRL_COND_CHK_RESULT_SHIFT (7) - -#define SHA256_MOD_DATA_RANGE (SHA256_MEM_BASE+0x14) -#define SHA256_MOD_DATA_RANGE_ST_BYTE_2_ADD_STP_MASK (NBIT24-1) -#define SHA256_MOD_DATA_RANGE_ST_BYTE_2_ADD_STP_SHIFT (0) -#define SHA256_MOD_DATA_RANGE_MOD_DATA_LEN_MASK (NBIT24 | NBIT25| NBIT26) -#define SHA256_MOD_DATA_RANGE_MOD_DATA_LEN_SHIFT (24) - - -#define SHA256_COND_CHK_STS_1 (SHA256_MEM_BASE+0x18) -#define SHA256_COND_CHK_STS_2 (SHA256_MEM_BASE+0x1c) -#define SHA256_DONE_INTR_ENABLE (SHA256_MEM_BASE+0x20) -#define SHA256_DONE_INTR_STS (SHA256_MEM_BASE+0x24) -#define SHA256_TARGET_HASH_H1 (SHA256_MEM_BASE+0x28) -#define SHA256_TARGET_HASH_H2 (SHA256_MEM_BASE+0x2c) -#define SHA256_TARGET_HASH_H3 (SHA256_MEM_BASE+0x30) -#define SHA256_TARGET_HASH_H4 (SHA256_MEM_BASE+0x34) -#define SHA256_TARGET_HASH_H5 (SHA256_MEM_BASE+0x38) -#define SHA256_TARGET_HASH_H6 (SHA256_MEM_BASE+0x3c) -#define SHA256_TARGET_HASH_H7 (SHA256_MEM_BASE+0x40) -#define SHA256_TARGET_HASH_H8 (SHA256_MEM_BASE+0x44) - -/*======*======*======*======*======*=======* -* WINC BIGINT HW Engine Register Definition * -*======*======*======*======*======*========*/ - - -#define BIGINT_ENGINE_ADDR (0x180080ul) -#define BIGINT_VERSION (BIGINT_ENGINE_ADDR + 0x00) - -#define BIGINT_MISC_CTRL (BIGINT_ENGINE_ADDR + 0x04) -#define BIGINT_MISC_CTRL_CTL_START (NBIT0) -#define BIGINT_MISC_CTRL_CTL_RESET (NBIT1) -#define BIGINT_MISC_CTRL_CTL_MSW_FIRST (NBIT2) -#define BIGINT_MISC_CTRL_CTL_SWAP_BYTE_ORDER (NBIT3) -#define BIGINT_MISC_CTRL_CTL_FORCE_BARRETT (NBIT4) -#define BIGINT_MISC_CTRL_CTL_M_PRIME_VALID (NBIT5) - -#define BIGINT_M_PRIME (BIGINT_ENGINE_ADDR + 0x08) - -#define BIGINT_STATUS (BIGINT_ENGINE_ADDR + 0x0C) -#define BIGINT_STATUS_STS_DONE (NBIT0) - -#define BIGINT_CLK_COUNT (BIGINT_ENGINE_ADDR + 0x10) -#define BIGINT_ADDR_X (BIGINT_ENGINE_ADDR + 0x14) -#define BIGINT_ADDR_E (BIGINT_ENGINE_ADDR + 0x18) -#define BIGINT_ADDR_M (BIGINT_ENGINE_ADDR + 0x1C) -#define BIGINT_ADDR_R (BIGINT_ENGINE_ADDR + 0x20) -#define BIGINT_LENGTH (BIGINT_ENGINE_ADDR + 0x24) - -#define BIGINT_IRQ_STS (BIGINT_ENGINE_ADDR + 0x28) -#define BIGINT_IRQ_STS_DONE (NBIT0) -#define BIGINT_IRQ_STS_CHOOSE_MONT (NBIT1) -#define BIGINT_IRQ_STS_M_READ (NBIT2) -#define BIGINT_IRQ_STS_X_READ (NBIT3) -#define BIGINT_IRQ_STS_START (NBIT4) -#define BIGINT_IRQ_STS_PRECOMP_FINISH (NBIT5) - -#define BIGINT_IRQ_MASK (BIGINT_ENGINE_ADDR + 0x2C) -#define BIGINT_IRQ_MASK_CTL_IRQ_MASK_START (NBIT4) - -#define ENABLE_FLIPPING 1 - - - - -#define GET_UINT32(BUF,OFFSET) (((uint32)((BUF)[OFFSET])) | ((uint32)(((BUF)[OFFSET + 1]) << 8)) | \ -((uint32)(((BUF)[OFFSET + 2]) << 16)) | ((uint32)(((BUF)[OFFSET + 3]) << 24))) - -#define PUTU32(VAL32,BUF,OFFSET) \ -do \ -{ \ - (BUF)[OFFSET ] = BYTE_3((VAL32)); \ - (BUF)[OFFSET +1 ] = BYTE_2((VAL32)); \ - (BUF)[OFFSET +2 ] = BYTE_1((VAL32)); \ - (BUF)[OFFSET +3 ] = BYTE_0((VAL32)); \ -}while(0) - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*! -@struct \ - tstrHashContext - -@brief -*/ -typedef struct{ - uint32 au32HashState[M2M_SHA256_DIGEST_LEN/4]; - uint8 au8CurrentBlock[64]; - uint32 u32TotalLength; - uint8 u8InitHashFlag; -}tstrSHA256HashCtxt; - - - -/*======*======*======*======*======*=======* -* SHA256 IMPLEMENTATION * -*======*======*======*======*======*========*/ - -sint8 m2m_crypto_sha256_hash_init(tstrM2mSha256Ctxt *pstrSha256Ctxt) -{ - tstrSHA256HashCtxt *pstrSHA256 = (tstrSHA256HashCtxt*)pstrSha256Ctxt; - if(pstrSHA256 != NULL) - { - m2m_memset((uint8*)pstrSha256Ctxt, 0, sizeof(tstrM2mSha256Ctxt)); - pstrSHA256->u8InitHashFlag = 1; - } - return 0; -} - -sint8 m2m_crypto_sha256_hash_update(tstrM2mSha256Ctxt *pstrSha256Ctxt, uint8 *pu8Data, uint16 u16DataLength) -{ - sint8 s8Ret = M2M_ERR_FAIL; - tstrSHA256HashCtxt *pstrSHA256 = (tstrSHA256HashCtxt*)pstrSha256Ctxt; - if(pstrSHA256 != NULL) - { - uint32 u32ReadAddr; - uint32 u32WriteAddr = SHARED_MEM_BASE; - uint32 u32Addr = u32WriteAddr; - uint32 u32ResidualBytes; - uint32 u32NBlocks; - uint32 u32Offset; - uint32 u32CurrentBlock = 0; - uint8 u8IsDone = 0; - - /* Get the remaining bytes from the previous update (if the length is not block aligned). */ - u32ResidualBytes = pstrSHA256->u32TotalLength % SHA_BLOCK_SIZE; - - /* Update the total data length. */ - pstrSHA256->u32TotalLength += u16DataLength; - - if(u32ResidualBytes != 0) - { - if((u32ResidualBytes + u16DataLength) >= SHA_BLOCK_SIZE) - { - u32Offset = SHA_BLOCK_SIZE - u32ResidualBytes; - m2m_memcpy(&pstrSHA256->au8CurrentBlock[u32ResidualBytes], pu8Data, u32Offset); - pu8Data += u32Offset; - u16DataLength -= u32Offset; - - nm_write_block(u32Addr, pstrSHA256->au8CurrentBlock, SHA_BLOCK_SIZE); - u32Addr += SHA_BLOCK_SIZE; - u32CurrentBlock = 1; - } - else - { - m2m_memcpy(&pstrSHA256->au8CurrentBlock[u32ResidualBytes], pu8Data, u16DataLength); - u16DataLength = 0; - } - } - - /* Get the number of HASH BLOCKs and the residual bytes. */ - u32NBlocks = u16DataLength / SHA_BLOCK_SIZE; - u32ResidualBytes = u16DataLength % SHA_BLOCK_SIZE; - - if(u32NBlocks != 0) - { - nm_write_block(u32Addr, pu8Data, (uint16)(u32NBlocks * SHA_BLOCK_SIZE)); - pu8Data += (u32NBlocks * SHA_BLOCK_SIZE); - } - - u32NBlocks += u32CurrentBlock; - if(u32NBlocks != 0) - { - uint32 u32RegVal = 0; - - nm_write_reg(SHA256_CTRL, u32RegVal); - u32RegVal |= SHA256_CTRL_FORCE_SHA256_QUIT_MASK; - nm_write_reg(SHA256_CTRL, u32RegVal); - - if(pstrSHA256->u8InitHashFlag) - { - pstrSHA256->u8InitHashFlag = 0; - u32RegVal |= SHA256_CTRL_INIT_SHA256_STATE_MASK; - } - - u32ReadAddr = u32WriteAddr + (u32NBlocks * SHA_BLOCK_SIZE); - nm_write_reg(SHA256_DATA_LENGTH, (u32NBlocks * SHA_BLOCK_SIZE)); - nm_write_reg(SHA256_START_RD_ADDR, u32WriteAddr); - nm_write_reg(SHA256_START_WR_ADDR, u32ReadAddr); - - u32RegVal |= SHA256_CTRL_START_CALC_MASK; - - u32RegVal &= ~(0x7 << 8); - u32RegVal |= (2 << 8); - - nm_write_reg(SHA256_CTRL, u32RegVal); - - /* 5. Wait for done_intr */ - while(!u8IsDone) - { - u32RegVal = nm_read_reg(SHA256_DONE_INTR_STS); - u8IsDone = u32RegVal & NBIT0; - } - } - if(u32ResidualBytes != 0) - { - m2m_memcpy(pstrSHA256->au8CurrentBlock, pu8Data, u32ResidualBytes); - } - s8Ret = M2M_SUCCESS; - } - return s8Ret; -} - - -sint8 m2m_crypto_sha256_hash_finish(tstrM2mSha256Ctxt *pstrSha256Ctxt, uint8 *pu8Sha256Digest) -{ - sint8 s8Ret = M2M_ERR_FAIL; - tstrSHA256HashCtxt *pstrSHA256 = (tstrSHA256HashCtxt*)pstrSha256Ctxt; - if(pstrSHA256 != NULL) - { - uint32 u32ReadAddr; - uint32 u32WriteAddr = SHARED_MEM_BASE; - uint32 u32Addr = u32WriteAddr; - uint16 u16Offset; - uint16 u16PaddingLength; - uint16 u16NBlocks = 1; - uint32 u32RegVal = 0; - uint32 u32Idx,u32ByteIdx; - uint32 au32Digest[M2M_SHA256_DIGEST_LEN / 4]; - uint8 u8IsDone = 0; - - nm_write_reg(SHA256_CTRL,u32RegVal); - u32RegVal |= SHA256_CTRL_FORCE_SHA256_QUIT_MASK; - nm_write_reg(SHA256_CTRL,u32RegVal); - - if(pstrSHA256->u8InitHashFlag) - { - pstrSHA256->u8InitHashFlag = 0; - u32RegVal |= SHA256_CTRL_INIT_SHA256_STATE_MASK; - } - - /* Calculate the offset of the last data byte in the current block. */ - u16Offset = (uint16)(pstrSHA256->u32TotalLength % SHA_BLOCK_SIZE); - - /* Add the padding byte 0x80. */ - pstrSHA256->au8CurrentBlock[u16Offset ++] = 0x80; - - /* Calculate the required padding to complete - one Hash Block Size. - */ - u16PaddingLength = SHA_BLOCK_SIZE - u16Offset; - m2m_memset(&pstrSHA256->au8CurrentBlock[u16Offset], 0, u16PaddingLength); - - /* If the padding count is not enough to hold 64-bit representation of - the total input message length, one padding block is required. - */ - if(u16PaddingLength < 8) - { - nm_write_block(u32Addr, pstrSHA256->au8CurrentBlock, SHA_BLOCK_SIZE); - u32Addr += SHA_BLOCK_SIZE; - m2m_memset(pstrSHA256->au8CurrentBlock, 0, SHA_BLOCK_SIZE); - u16NBlocks ++; - } - - /* pack the length at the end of the padding block */ - PUTU32(pstrSHA256->u32TotalLength << 3, pstrSHA256->au8CurrentBlock, (SHA_BLOCK_SIZE - 4)); - - u32ReadAddr = u32WriteAddr + (u16NBlocks * SHA_BLOCK_SIZE); - nm_write_block(u32Addr, pstrSHA256->au8CurrentBlock, SHA_BLOCK_SIZE); - nm_write_reg(SHA256_DATA_LENGTH, (u16NBlocks * SHA_BLOCK_SIZE)); - nm_write_reg(SHA256_START_RD_ADDR, u32WriteAddr); - nm_write_reg(SHA256_START_WR_ADDR, u32ReadAddr); - - u32RegVal |= SHA256_CTRL_START_CALC_MASK; - u32RegVal |= SHA256_CTRL_WR_BACK_HASH_VALUE_MASK; - u32RegVal &= ~(0x7UL << 8); - u32RegVal |= (0x2UL << 8); - - nm_write_reg(SHA256_CTRL,u32RegVal); - - - /* 5. Wait for done_intr */ - while(!u8IsDone) - { - u32RegVal = nm_read_reg(SHA256_DONE_INTR_STS); - u8IsDone = u32RegVal & NBIT0; - } - nm_read_block(u32ReadAddr, (uint8*)au32Digest, 32); - - /* Convert the output words to an array of bytes. - */ - u32ByteIdx = 0; - for(u32Idx = 0; u32Idx < (M2M_SHA256_DIGEST_LEN / 4); u32Idx ++) - { - pu8Sha256Digest[u32ByteIdx ++] = BYTE_3(au32Digest[u32Idx]); - pu8Sha256Digest[u32ByteIdx ++] = BYTE_2(au32Digest[u32Idx]); - pu8Sha256Digest[u32ByteIdx ++] = BYTE_1(au32Digest[u32Idx]); - pu8Sha256Digest[u32ByteIdx ++] = BYTE_0(au32Digest[u32Idx]); - } - s8Ret = M2M_SUCCESS; - } - return s8Ret; -} - - -/*======*======*======*======*======*=======* -* RSA IMPLEMENTATION * -*======*======*======*======*======*========*/ - -static void FlipBuffer(uint8 *pu8InBuffer, uint8 *pu8OutBuffer, uint16 u16BufferSize) -{ - uint16 u16Idx; - for(u16Idx = 0; u16Idx < u16BufferSize; u16Idx ++) - { -#if ENABLE_FLIPPING == 1 - pu8OutBuffer[u16Idx] = pu8InBuffer[u16BufferSize - u16Idx - 1]; -#else - pu8OutBuffer[u16Idx] = pu8InBuffer[u16Idx]; -#endif - } -} - -void BigInt_ModExp -( - uint8 *pu8X, uint16 u16XSize, - uint8 *pu8E, uint16 u16ESize, - uint8 *pu8M, uint16 u16MSize, - uint8 *pu8R, uint16 u16RSize - ) -{ - uint32 u32Reg; - uint8 au8Tmp[780] = {0}; - uint32 u32XAddr = SHARED_MEM_BASE; - uint32 u32MAddr; - uint32 u32EAddr; - uint32 u32RAddr; - uint8 u8EMswBits = 32; - uint32 u32Mprime = 0x7F; - uint16 u16XSizeWords,u16ESizeWords; - uint32 u32Exponent; - - u16XSizeWords = (u16XSize + 3) / 4; - u16ESizeWords = (u16ESize + 3) / 4; - - u32MAddr = u32XAddr + (u16XSizeWords * 4); - u32EAddr = u32MAddr + (u16XSizeWords * 4); - u32RAddr = u32EAddr + (u16ESizeWords * 4); - - /* Reset the core. - */ - u32Reg = 0; - u32Reg |= BIGINT_MISC_CTRL_CTL_RESET; - u32Reg = nm_read_reg(BIGINT_MISC_CTRL); - u32Reg &= ~BIGINT_MISC_CTRL_CTL_RESET; - u32Reg = nm_read_reg(BIGINT_MISC_CTRL); - - nm_write_block(u32RAddr,au8Tmp, u16RSize); - - /* Write Input Operands to Chip Memory. - */ - /*------- X -------*/ - FlipBuffer(pu8X,au8Tmp,u16XSize); - nm_write_block(u32XAddr,au8Tmp,u16XSizeWords * 4); - - /*------- E -------*/ - m2m_memset(au8Tmp, 0, sizeof(au8Tmp)); - FlipBuffer(pu8E, au8Tmp, u16ESize); - nm_write_block(u32EAddr, au8Tmp, u16ESizeWords * 4); - u32Exponent = GET_UINT32(au8Tmp, (u16ESizeWords * 4) - 4); - while((u32Exponent & NBIT31)== 0) - { - u32Exponent <<= 1; - u8EMswBits --; - } - - /*------- M -------*/ - m2m_memset(au8Tmp, 0, sizeof(au8Tmp)); - FlipBuffer(pu8M, au8Tmp, u16XSize); - nm_write_block(u32MAddr, au8Tmp, u16XSizeWords * 4); - - /* Program the addresses of the input operands. - */ - nm_write_reg(BIGINT_ADDR_X, u32XAddr); - nm_write_reg(BIGINT_ADDR_E, u32EAddr); - nm_write_reg(BIGINT_ADDR_M, u32MAddr); - nm_write_reg(BIGINT_ADDR_R, u32RAddr); - - /* Mprime. - */ - nm_write_reg(BIGINT_M_PRIME,u32Mprime); - - /* Length. - */ - u32Reg = (u16XSizeWords & 0xFF); - u32Reg += ((u16ESizeWords & 0xFF) << 8); - u32Reg += (u8EMswBits << 16); - nm_write_reg(BIGINT_LENGTH,u32Reg); - - /* CTRL Register. - */ - u32Reg = nm_read_reg(BIGINT_MISC_CTRL); - u32Reg ^= BIGINT_MISC_CTRL_CTL_START; - u32Reg |= BIGINT_MISC_CTRL_CTL_FORCE_BARRETT; - //u32Reg |= BIGINT_MISC_CTRL_CTL_M_PRIME_VALID; -#if ENABLE_FLIPPING == 0 - u32Reg |= BIGINT_MISC_CTRL_CTL_MSW_FIRST; -#endif - nm_write_reg(BIGINT_MISC_CTRL,u32Reg); - - /* Wait for computation to complete. */ - while(1) - { - u32Reg = nm_read_reg(BIGINT_IRQ_STS); - if(u32Reg & BIGINT_IRQ_STS_DONE) - { - break; - } - } - nm_write_reg(BIGINT_IRQ_STS,0); - m2m_memset(au8Tmp, 0, sizeof(au8Tmp)); - nm_read_block(u32RAddr, au8Tmp, u16RSize); - FlipBuffer(au8Tmp, pu8R, u16RSize); -} - - - -#define MD5_DIGEST_SIZE (16) -#define SHA1_DIGEST_SIZE (20) - -static const uint8 au8TEncodingMD5[] = -{ - 0x30, 0x20, 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86, - 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05, 0x05, 0x00, - 0x04 -}; -/*!< Fixed part of the Encoding T for the MD5 hash algorithm. -*/ - - -static const uint8 au8TEncodingSHA1[] = -{ - 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, - 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04 -}; -/*!< Fixed part of the Encoding T for the SHA-1 hash algorithm. -*/ - - -static const uint8 au8TEncodingSHA2[] = -{ - 0x30, 0x31, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, - 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, - 0x00, 0x04 -}; -/*!< Fixed part of the Encoding T for the SHA-2 hash algorithm. -*/ - - -sint8 m2m_crypto_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash, - uint16 u16HashLength, uint8 *pu8RsaSignature) -{ - sint8 s8Ret = M2M_RSA_SIGN_FAIL; - - if((pu8N != NULL) && (pu8E != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL)) - { - uint16 u16TLength, u16TEncodingLength; - uint8 *pu8T; - uint8 au8EM[512]; - - /* Selection of correct T Encoding based on the hash size. - */ - if(u16HashLength == MD5_DIGEST_SIZE) - { - pu8T = (uint8*)au8TEncodingMD5; - u16TEncodingLength = sizeof(au8TEncodingMD5); - } - else if(u16HashLength == SHA1_DIGEST_SIZE) - { - pu8T = (uint8*)au8TEncodingSHA1; - u16TEncodingLength = sizeof(au8TEncodingSHA1); - } - else - { - pu8T = (uint8*)au8TEncodingSHA2; - u16TEncodingLength = sizeof(au8TEncodingSHA2); - } - u16TLength = u16TEncodingLength + 1 + u16HashLength; - - /* If emLen < tLen + 11. - */ - if(u16NSize >= (u16TLength + 11)) - { - uint32 u32PSLength,u32Idx = 0; - - /* - RSA verification - */ - BigInt_ModExp(pu8RsaSignature, u16NSize, pu8E, u16ESize, pu8N, u16NSize, au8EM, u16NSize); - - u32PSLength = u16NSize - u16TLength - 3; - - /* - The calculated EM must match the following pattern. - *======*======*======*======*======* - * 0x00 || 0x01 || PS || 0x00 || T * - *======*======*======*======*======* - Where PS is all 0xFF - T is defined based on the hash algorithm. - */ - if((au8EM[0] == 0x00) && (au8EM[1] == 0x01)) - { - for(u32Idx = 2; au8EM[u32Idx] == 0xFF; u32Idx ++); - if(u32Idx == (u32PSLength + 2)) - { - if(au8EM[u32Idx ++] == 0x00) - { - if(!m2m_memcmp(&au8EM[u32Idx], pu8T, u16TEncodingLength)) - { - u32Idx += u16TEncodingLength; - if(au8EM[u32Idx ++] == u16HashLength) - s8Ret = m2m_memcmp(&au8EM[u32Idx], pu8SignedMsgHash, u16HashLength); - } - } - } - } - } - } - return s8Ret; -} - - -sint8 m2m_crypto_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash, - uint16 u16HashLength, uint8 *pu8RsaSignature) -{ - sint8 s8Ret = M2M_RSA_SIGN_FAIL; - - if((pu8N != NULL) && (pu8d != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL)) - { - uint16 u16TLength, u16TEncodingLength; - uint8 *pu8T; - uint8 au8EM[512]; - - /* Selection of correct T Encoding based on the hash size. - */ - if(u16HashLength == MD5_DIGEST_SIZE) - { - pu8T = (uint8*)au8TEncodingMD5; - u16TEncodingLength = sizeof(au8TEncodingMD5); - } - else if(u16HashLength == SHA1_DIGEST_SIZE) - { - pu8T = (uint8*)au8TEncodingSHA1; - u16TEncodingLength = sizeof(au8TEncodingSHA1); - } - else - { - pu8T = (uint8*)au8TEncodingSHA2; - u16TEncodingLength = sizeof(au8TEncodingSHA2); - } - u16TLength = u16TEncodingLength + 1 + u16HashLength; - - /* If emLen < tLen + 11. - */ - if(u16NSize >= (u16TLength + 11)) - { - uint16 u16PSLength = 0; - uint16 u16Offset = 0; - - /* - The calculated EM must match the following pattern. - *======*======*======*======*======* - * 0x00 || 0x01 || PS || 0x00 || T * - *======*======*======*======*======* - Where PS is all 0xFF - T is defined based on the hash algorithm. - */ - au8EM[u16Offset ++] = 0; - au8EM[u16Offset ++] = 1; - u16PSLength = u16NSize - u16TLength - 3; - m2m_memset(&au8EM[u16Offset], 0xFF, u16PSLength); - u16Offset += u16PSLength; - au8EM[u16Offset ++] = 0; - m2m_memcpy(&au8EM[u16Offset], pu8T, u16TEncodingLength); - u16Offset += u16TEncodingLength; - au8EM[u16Offset ++] = u16HashLength; - m2m_memcpy(&au8EM[u16Offset], pu8SignedMsgHash, u16HashLength); - - /* - RSA Signature Generation - */ - BigInt_ModExp(au8EM, u16NSize, pu8d, u16dSize, pu8N, u16NSize, pu8RsaSignature, u16NSize); - s8Ret = M2M_RSA_SIGN_OK; - } - } - return s8Ret; -} - -#endif /* CONF_CRYPTO */ - -#ifdef CONF_CRYPTO_SOFT - -typedef struct { - tpfAppCryproCb pfAppCryptoCb; - uint8 * pu8Digest; - uint8 * pu8Rsa; - uint8 u8CryptoBusy; -}tstrCryptoCtxt; - -typedef struct { - uint8 au8N[M2M_MAX_RSA_LEN]; - uint8 au8E[M2M_MAX_RSA_LEN]; - uint8 au8Hash[M2M_SHA256_DIGEST_LEN]; - uint16 u16Nsz; - uint16 u16Esz; - uint16 u16Hsz; - uint8 _pad16_[2]; -}tstrRsaPayload; - -static tstrCryptoCtxt gstrCryptoCtxt; - - -/** -* @fn m2m_crypto_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -* @brief WiFi call back function -* @param [in] u8OpCode -* HIF Opcode type. -* @param [in] u16DataSize -* HIF data length. -* @param [in] u32Addr -* HIF address. -* @author -* @date -* @version 1.0 -*/ -static void m2m_crypto_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -{ - sint8 ret = M2M_SUCCESS; - gstrCryptoCtxt.u8CryptoBusy = 0; - if(u8OpCode == M2M_CRYPTO_RESP_SHA256_INIT) - { - tstrM2mSha256Ctxt strCtxt; - if (hif_receive(u32Addr, (uint8*) &strCtxt,sizeof(tstrM2mSha256Ctxt), 0) == M2M_SUCCESS) - { - tstrCyptoResp strResp; - if(hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt), (uint8*) &strResp,sizeof(tstrCyptoResp), 1) == M2M_SUCCESS) - { - if (gstrCryptoCtxt.pfAppCryptoCb) - gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,&strCtxt); - } - } - } - else if(u8OpCode == M2M_CRYPTO_RESP_SHA256_UPDATE) - { - tstrM2mSha256Ctxt strCtxt; - if (hif_receive(u32Addr, (uint8*) &strCtxt,sizeof(tstrM2mSha256Ctxt), 0) == M2M_SUCCESS) - { - tstrCyptoResp strResp; - if (hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt), (uint8*) &strResp,sizeof(tstrCyptoResp), 1) == M2M_SUCCESS) - { - if (gstrCryptoCtxt.pfAppCryptoCb) - gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,&strCtxt); - } - } - - } - else if(u8OpCode == M2M_CRYPTO_RESP_SHA256_FINSIH) - { - tstrCyptoResp strResp; - if (hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt), (uint8*) &strResp,sizeof(tstrCyptoResp), 0) == M2M_SUCCESS) - { - if (hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt) + sizeof(tstrCyptoResp), (uint8*)gstrCryptoCtxt.pu8Digest,M2M_SHA256_DIGEST_LEN, 1) == M2M_SUCCESS) - { - if (gstrCryptoCtxt.pfAppCryptoCb) - gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,gstrCryptoCtxt.pu8Digest); - - } - } - } - else if(u8OpCode == M2M_CRYPTO_RESP_RSA_SIGN_GEN) - { - tstrCyptoResp strResp; - if (hif_receive(u32Addr + sizeof(tstrRsaPayload), (uint8*)&strResp,sizeof(tstrCyptoResp), 0) == M2M_SUCCESS) - { - if (hif_receive(u32Addr + sizeof(tstrRsaPayload) + sizeof(tstrCyptoResp), (uint8*)gstrCryptoCtxt.pu8Rsa,M2M_MAX_RSA_LEN, 0) == M2M_SUCCESS) - { - if (gstrCryptoCtxt.pfAppCryptoCb) - gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,gstrCryptoCtxt.pu8Rsa); - } - } - } - else if(u8OpCode == M2M_CRYPTO_RESP_RSA_SIGN_VERIFY) - { - tstrCyptoResp strResp; - if (hif_receive(u32Addr + sizeof(tstrRsaPayload), (uint8*)&strResp,sizeof(tstrCyptoResp), 1) == M2M_SUCCESS) - { - if (gstrCryptoCtxt.pfAppCryptoCb) - gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,NULL); - } - } - else - { - M2M_ERR("u8Code %d ??\n",u8OpCode); - } - -} -/*! -@fn \ - sint8 m2m_crypto_init(); - -@brief crypto initialization - -@param[in] pfAppCryproCb - -*/ -sint8 m2m_crypto_init(tpfAppCryproCb pfAppCryproCb) -{ - sint8 ret = M2M_ERR_FAIL; - m2m_memset((uint8*)&gstrCryptoCtxt,0,sizeof(tstrCryptoCtxt)); - if(pfAppCryproCb != NULL) - { - gstrCryptoCtxt.pfAppCryptoCb = pfAppCryproCb; - ret = hif_register_cb(M2M_REQ_GROUP_CRYPTO,m2m_crypto_cb); - } - return ret; -} -/*! -@fn \ - sint8 m2m_sha256_hash_init(tstrM2mSha256Ctxt *psha256Ctxt); - -@brief SHA256 hash initialization - -@param[in] psha256Ctxt - Pointer to a sha256 context allocated by the caller. -*/ -sint8 m2m_crypto_sha256_hash_init(tstrM2mSha256Ctxt *psha256Ctxt) -{ - sint8 ret = M2M_ERR_FAIL; - if((psha256Ctxt != NULL)&&(!gstrCryptoCtxt.u8CryptoBusy)) - { - ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_SHA256_INIT|M2M_REQ_DATA_PKT,(uint8*)psha256Ctxt,sizeof(tstrM2mSha256Ctxt),NULL,0,0); - } - return ret; -} - - -/*! -@fn \ - sint8 m2m_sha256_hash_update(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Data, uint16 u16DataLength); - -@brief SHA256 hash update - -@param [in] psha256Ctxt - Pointer to the sha256 context. - -@param [in] pu8Data - Buffer holding the data submitted to the hash. - -@param [in] u16DataLength - Size of the data bufefr in bytes. -*/ -sint8 m2m_crypto_sha256_hash_update(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Data, uint16 u16DataLength) -{ - sint8 ret = M2M_ERR_FAIL; - if((!gstrCryptoCtxt.u8CryptoBusy) && (psha256Ctxt != NULL) && (pu8Data != NULL) && (u16DataLength < M2M_SHA256_MAX_DATA)) - { - ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_SHA256_UPDATE|M2M_REQ_DATA_PKT,(uint8*)psha256Ctxt,sizeof(tstrM2mSha256Ctxt),pu8Data,u16DataLength,sizeof(tstrM2mSha256Ctxt) + sizeof(tstrCyptoResp)); - } - return ret; - -} - - -/*! -@fn \ - sint8 m2m_sha256_hash_finish(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Sha256Digest); - -@brief SHA256 hash finalization - -@param[in] psha256Ctxt - Pointer to a sha256 context allocated by the caller. - -@param [in] pu8Sha256Digest - Buffer allocated by the caller which will hold the resultant SHA256 Digest. It must be allocated no less than M2M_SHA256_DIGEST_LEN. -*/ -sint8 m2m_crypto_sha256_hash_finish(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Sha256Digest) -{ - sint8 ret = M2M_ERR_FAIL; - if((!gstrCryptoCtxt.u8CryptoBusy) && (psha256Ctxt != NULL) && (pu8Sha256Digest != NULL)) - { - gstrCryptoCtxt.pu8Digest = pu8Sha256Digest; - ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_SHA256_FINSIH|M2M_REQ_DATA_PKT,(uint8*)psha256Ctxt,sizeof(tstrM2mSha256Ctxt),NULL,0,0); - } - return ret; -} - - - - -/*! -@fn \ - sint8 m2m_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash, \ - uint16 u16HashLength, uint8 *pu8RsaSignature); - -@brief RSA Signature Verification - - The function shall request the RSA Signature verification from the WINC Firmware for the given message. The signed message shall be - compressed to the corresponding hash algorithm before calling this function. - The hash type is identified by the given hash length. For example, if the hash length is 32 bytes, then it is SHA256. - -@param[in] pu8N - RSA Key modulus n. - -@param[in] u16NSize - Size of the RSA modulus n in bytes. - -@param[in] pu8E - RSA public exponent. - -@param[in] u16ESize - Size of the RSA public exponent in bytes. - -@param[in] pu8SignedMsgHash - The hash digest of the signed message. - -@param[in] u16HashLength - The length of the hash digest. - -@param[out] pu8RsaSignature - Signature value to be verified. -*/ - - -sint8 m2m_crypto_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash, - uint16 u16HashLength, uint8 *pu8RsaSignature) -{ - sint8 ret = M2M_ERR_FAIL; - if((!gstrCryptoCtxt.u8CryptoBusy) && (pu8N != NULL) && (pu8E != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL) - && (u16NSize != 0) && (u16ESize != 0) && (u16HashLength != 0) && (pu8RsaSignature != NULL) ) - - { - tstrRsaPayload strRsa = {0}; - - m2m_memcpy(strRsa.au8N,pu8N,u16NSize); - m2m_memcpy(strRsa.au8E,pu8E,u16ESize); - m2m_memcpy(strRsa.au8Hash,pu8SignedMsgHash,u16HashLength); - - strRsa.u16Esz = u16ESize; - strRsa.u16Hsz = u16HashLength; - strRsa.u16Nsz = u16NSize; - - ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_RSA_SIGN_VERIFY|M2M_REQ_DATA_PKT,(uint8*)&strRsa,sizeof(tstrRsaPayload),NULL,0,0); - - } - return ret; -} - - -/*! -@fn \ - sint8 m2m_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash, \ - uint16 u16HashLength, uint8 *pu8RsaSignature); - -@brief RSA Signature Generation - - The function shall request the RSA Signature generation from the WINC Firmware for the given message. The signed message shall be - compressed to the corresponding hash algorithm before calling this function. - The hash type is identified by the given hash length. For example, if the hash length is 32 bytes, then it is SHA256. - -@param[in] pu8N - RSA Key modulus n. - -@param[in] u16NSize - Size of the RSA modulus n in bytes. - -@param[in] pu8d - RSA private exponent. - -@param[in] u16dSize - Size of the RSA private exponent in bytes. - -@param[in] pu8SignedMsgHash - The hash digest of the signed message. - -@param[in] u16HashLength - The length of the hash digest. - -@param[out] pu8RsaSignature - Pointer to a user buffer allocated by teh caller shall hold the generated signature. -*/ -sint8 m2m_crypto_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash, - uint16 u16HashLength, uint8 *pu8RsaSignature) -{ - sint8 ret = M2M_ERR_FAIL; - if((!gstrCryptoCtxt.u8CryptoBusy) && (pu8N != NULL) && (pu8d != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL) - && (u16NSize != 0) && (u16dSize != 0) && (u16HashLength != 0) && (pu8RsaSignature != NULL)) - - { - tstrRsaPayload strRsa = {0}; - - m2m_memcpy(strRsa.au8N,pu8N,u16NSize); - m2m_memcpy(strRsa.au8E,pu8d,u16dSize); - m2m_memcpy(strRsa.au8Hash,pu8SignedMsgHash,u16HashLength); - - strRsa.u16Esz = u16dSize; - strRsa.u16Hsz = u16HashLength; - strRsa.u16Nsz = u16NSize; - - gstrCryptoCtxt.pu8Rsa = pu8RsaSignature; - ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_RSA_SIGN_GEN|M2M_REQ_DATA_PKT,(uint8*)&strRsa,sizeof(tstrRsaPayload),NULL,0,0); - - } - return ret; -} - -#endif \ No newline at end of file diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_hif.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_hif.c deleted file mode 100644 index f0ed93a..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_hif.c +++ /dev/null @@ -1,767 +0,0 @@ -/** - * - * \file - * - * \brief This module contains M2M host interface APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "common/include/nm_common.h" -#include "driver/source/nmbus.h" -#include "bsp/include/nm_bsp.h" -#include "m2m_hif.h" -#include "driver/include/m2m_types.h" -#include "driver/source/nmasic.h" -#include "driver/include/m2m_periph.h" - -#if (defined NM_EDGE_INTERRUPT)&&(defined NM_LEVEL_INTERRUPT) -#error "only one type of interrupt NM_EDGE_INTERRUPT,NM_LEVEL_INTERRUPT" -#endif - -#if !((defined NM_EDGE_INTERRUPT)||(defined NM_LEVEL_INTERRUPT)) -#error "define interrupt type NM_EDGE_INTERRUPT,NM_LEVEL_INTERRUPT" -#endif - -#ifndef CORTUS_APP -#define NMI_AHB_DATA_MEM_BASE 0x30000 -#define NMI_AHB_SHARE_MEM_BASE 0xd0000 - -#define WIFI_HOST_RCV_CTRL_0 (0x1070) -#define WIFI_HOST_RCV_CTRL_1 (0x1084) -#define WIFI_HOST_RCV_CTRL_2 (0x1078) -#define WIFI_HOST_RCV_CTRL_3 (0x106c) -#define WIFI_HOST_RCV_CTRL_4 (0x150400) -#define WIFI_HOST_RCV_CTRL_5 (0x1088) - -typedef struct { - uint8 u8ChipMode; - uint8 u8ChipSleep; - uint8 u8HifRXDone; - uint8 u8Interrupt; - uint32 u32RxAddr; - uint32 u32RxSize; - tpfHifCallBack pfWifiCb; - tpfHifCallBack pfIpCb; - tpfHifCallBack pfOtaCb; - tpfHifCallBack pfSigmaCb; - tpfHifCallBack pfHifCb; - tpfHifCallBack pfCryptoCb; - tpfHifCallBack pfSslCb; -}tstrHifContext; - -volatile tstrHifContext gstrHifCxt; - -static void isr(void) -{ - gstrHifCxt.u8Interrupt++; -#ifdef NM_LEVEL_INTERRUPT - nm_bsp_interrupt_ctrl(0); -#endif -} -static sint8 hif_set_rx_done(void) -{ - uint32 reg; - sint8 ret = M2M_SUCCESS; - - gstrHifCxt.u8HifRXDone = 0; -#ifdef NM_EDGE_INTERRUPT - nm_bsp_interrupt_ctrl(1); -#endif - ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0,®); - if(ret != M2M_SUCCESS)goto ERR1; - /* Set RX Done */ - reg |= NBIT1; - ret = nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg); - if(ret != M2M_SUCCESS)goto ERR1; -#ifdef NM_LEVEL_INTERRUPT - nm_bsp_interrupt_ctrl(1); -#endif -ERR1: - return ret; - -} -/** -* @fn static void m2m_hif_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -* @brief WiFi call back function -* @param [in] u8OpCode -* HIF Opcode type. -* @param [in] u16DataSize -* HIF data length. -* @param [in] u32Addr -* HIF address. -* @param [in] grp -* HIF group type. -* @author -* @date -* @version 1.0 -*/ -static void m2m_hif_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)u8OpCode; - (void)u16DataSize; - (void)u32Addr; -#endif -} -/** -* @fn NMI_API sint8 hif_chip_wake(void); -* @brief To Wakeup the chip. -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -sint8 hif_chip_wake(void) -{ - sint8 ret = M2M_SUCCESS; - if(gstrHifCxt.u8HifRXDone) - { - /*chip already wake for the rx not done no need to send wake request*/ - return ret; - } - if(gstrHifCxt.u8ChipSleep == 0) - { - if(gstrHifCxt.u8ChipMode != M2M_NO_PS) - { - ret = chip_wake(); - if(ret != M2M_SUCCESS)goto ERR1; - } - else - { - } - } - gstrHifCxt.u8ChipSleep++; -ERR1: - return ret; -} -/*! -@fn \ - NMI_API void hif_set_sleep_mode(uint8 u8Pstype); - -@brief - Set the sleep mode of the HIF layer. - -@param [in] u8Pstype - Sleep mode. - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ - -void hif_set_sleep_mode(uint8 u8Pstype) -{ - gstrHifCxt.u8ChipMode = u8Pstype; -} -/*! -@fn \ - NMI_API uint8 hif_get_sleep_mode(void); - -@brief - Get the sleep mode of the HIF layer. - -@return - The function SHALL return the sleep mode of the HIF layer. -*/ - -uint8 hif_get_sleep_mode(void) -{ - return gstrHifCxt.u8ChipMode; -} - -/** -* @fn NMI_API sint8 hif_chip_sleep_sc(void); -* @brief To clear the chip sleep but keep the chip sleep -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -sint8 hif_chip_sleep_sc(void) -{ - if(gstrHifCxt.u8ChipSleep >= 1) - { - gstrHifCxt.u8ChipSleep--; - } - return M2M_SUCCESS; -} -/** -* @fn NMI_API sint8 hif_chip_sleep(void); -* @brief To make the chip sleep. -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -sint8 hif_chip_sleep(void) -{ - sint8 ret = M2M_SUCCESS; - - if(gstrHifCxt.u8ChipSleep >= 1) - { - gstrHifCxt.u8ChipSleep--; - } - - if(gstrHifCxt.u8ChipSleep == 0) - { - if(gstrHifCxt.u8ChipMode != M2M_NO_PS) - { - ret = chip_sleep(); - if(ret != M2M_SUCCESS)goto ERR1; - - } - else - { - } - } -ERR1: - return ret; -} -/** -* @fn NMI_API sint8 hif_init(void * arg); -* @brief To initialize HIF layer. -* @param [in] arg -* Pointer to the arguments. -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -sint8 hif_init(void * arg) -{ -#ifdef ARDUINO - (void)arg; // Silence "unused" warning -#endif - m2m_memset((uint8*)&gstrHifCxt,0,sizeof(tstrHifContext)); - nm_bsp_register_isr(isr); - hif_register_cb(M2M_REQ_GROUP_HIF,m2m_hif_cb); - return M2M_SUCCESS; -} -/** -* @fn NMI_API sint8 hif_deinit(void * arg); -* @brief To De-initialize HIF layer. -* @param [in] arg -* Pointer to the arguments. -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ -sint8 hif_deinit(void * arg) -{ -#ifdef ARDUINO - (void)arg; // Silence "unused" warning -#endif - sint8 ret = M2M_SUCCESS; - ret = hif_chip_wake(); - m2m_memset((uint8*)&gstrHifCxt,0,sizeof(tstrHifContext)); - return ret; -} -/** -* @fn NMI_API sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, - uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) -* @brief Send packet using host interface. - -* @param [in] u8Gid -* Group ID. -* @param [in] u8Opcode -* Operation ID. -* @param [in] pu8CtrlBuf -* Pointer to the Control buffer. -* @param [in] u16CtrlBufSize - Control buffer size. -* @param [in] u16DataOffset - Packet Data offset. -* @param [in] pu8DataBuf -* Packet buffer Allocated by the caller. -* @param [in] u16DataSize - Packet buffer size (including the HIF header). -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, - uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) -{ - sint8 ret = M2M_ERR_SEND; - volatile tstrHifHdr strHif; - - strHif.u8Opcode = u8Opcode&(~NBIT7); - strHif.u8Gid = u8Gid; - strHif.u16Length = M2M_HIF_HDR_OFFSET; - if(pu8DataBuf != NULL) - { - strHif.u16Length += u16DataOffset + u16DataSize; - } - else - { - strHif.u16Length += u16CtrlBufSize; - } - ret = hif_chip_wake(); - if(ret == M2M_SUCCESS) - { - volatile uint32 reg, dma_addr = 0; - volatile uint16 cnt = 0; -//#define OPTIMIZE_BUS -/*please define in firmware also*/ -#ifndef OPTIMIZE_BUS - reg = 0UL; - reg |= (uint32)u8Gid; - reg |= ((uint32)u8Opcode<<8); - reg |= ((uint32)strHif.u16Length<<16); - ret = nm_write_reg(NMI_STATE_REG,reg); - if(M2M_SUCCESS != ret) goto ERR1; - - reg = 0UL; - reg |= NBIT1; - ret = nm_write_reg(WIFI_HOST_RCV_CTRL_2, reg); - if(M2M_SUCCESS != ret) goto ERR1; -#else - reg = 0UL; - reg |= NBIT1; - reg |= ((u8Opcode & NBIT7) ? (NBIT2):(0)); /*Data = 1 or config*/ - reg |= (u8Gid == M2M_REQ_GROUP_IP) ? (NBIT3):(0); /*IP = 1 or non IP*/ - reg |= ((uint32)strHif.u16Length << 4); /*length of pkt max = 4096*/ - ret = nm_write_reg(WIFI_HOST_RCV_CTRL_2, reg); - if(M2M_SUCCESS != ret) goto ERR1; -#endif - dma_addr = 0; - - for(cnt = 0; cnt < 1000; cnt ++) - { - ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_2,(uint32 *)®); - if(ret != M2M_SUCCESS) break; - /* - * If it takes too long to get a response, the slow down to - * avoid back-to-back register read operations. - */ - if(cnt >= 500) { - if(cnt < 501) { - M2M_INFO("Slowing down...\n"); - } - nm_bsp_sleep(1); - } - if (!(reg & NBIT1)) - { - ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_4,(uint32 *)&dma_addr); - if(ret != M2M_SUCCESS) { - /*in case of read error clear the DMA address and return error*/ - dma_addr = 0; - goto ERR1; - } - /*in case of success break */ - break; - } - } - - if (dma_addr != 0) - { - volatile uint32 u32CurrAddr; - u32CurrAddr = dma_addr; - strHif.u16Length=NM_BSP_B_L_16(strHif.u16Length); - ret = nm_write_block(u32CurrAddr, (uint8*)&strHif, M2M_HIF_HDR_OFFSET); - if(M2M_SUCCESS != ret) goto ERR1; - u32CurrAddr += M2M_HIF_HDR_OFFSET; - if(pu8CtrlBuf != NULL) - { - ret = nm_write_block(u32CurrAddr, pu8CtrlBuf, u16CtrlBufSize); - if(M2M_SUCCESS != ret) goto ERR1; - u32CurrAddr += u16CtrlBufSize; - } - if(pu8DataBuf != NULL) - { - u32CurrAddr += (u16DataOffset - u16CtrlBufSize); - ret = nm_write_block(u32CurrAddr, pu8DataBuf, u16DataSize); - if(M2M_SUCCESS != ret) goto ERR1; - u32CurrAddr += u16DataSize; - } - - reg = dma_addr << 2; - reg |= NBIT1; - ret = nm_write_reg(WIFI_HOST_RCV_CTRL_3, reg); - if(M2M_SUCCESS != ret) goto ERR1; - } - else - { - ret = hif_chip_sleep(); - M2M_DBG("Failed to alloc rx size %d\r",ret); - ret = M2M_ERR_MEM_ALLOC; - goto ERR2; - } - - } - else - { - M2M_ERR("(HIF)Fail to wakup the chip\n"); - goto ERR2; - } - /*actual sleep ret = M2M_SUCCESS*/ - ret = hif_chip_sleep(); - return ret; -ERR1: - /*reset the count but no actual sleep as it already bus error*/ - hif_chip_sleep_sc(); -ERR2: - /*logical error*/ - return ret; -} - -#ifdef ARDUINO -volatile uint8 hif_small_xfer = 0; -#endif - -/** -* @fn hif_isr -* @brief Host interface interrupt service routine -* @author M. Abdelmawla -* @date 15 July 2012 -* @return 1 in case of interrupt received else 0 will be returned -* @version 1.0 -*/ -static sint8 hif_isr(void) -{ - sint8 ret = M2M_SUCCESS; - volatile uint32 reg; - volatile tstrHifHdr strHif; - -#ifdef ARDUINO - ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, (uint32*)®); -#else - ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, ®); -#endif - if(M2M_SUCCESS == ret) - { - if(reg & 0x1) /* New interrupt has been received */ - { - uint16 size; - - nm_bsp_interrupt_ctrl(0); - /*Clearing RX interrupt*/ - reg &= ~NBIT0; - ret = nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg); - if(ret != M2M_SUCCESS)goto ERR1; - gstrHifCxt.u8HifRXDone = 1; - size = (uint16)((reg >> 2) & 0xfff); - if (size > 0) { - uint32 address = 0; - /** - start bus transfer - **/ - ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_1, &address); - if(M2M_SUCCESS != ret) - { - M2M_ERR("(hif) WIFI_HOST_RCV_CTRL_1 bus fail\n"); - nm_bsp_interrupt_ctrl(1); - goto ERR1; - } - gstrHifCxt.u32RxAddr = address; - gstrHifCxt.u32RxSize = size; - ret = nm_read_block(address, (uint8*)&strHif, sizeof(tstrHifHdr)); - strHif.u16Length = NM_BSP_B_L_16(strHif.u16Length); - if(M2M_SUCCESS != ret) - { - M2M_ERR("(hif) address bus fail\n"); - nm_bsp_interrupt_ctrl(1); - goto ERR1; - } - if(strHif.u16Length != size) - { - if((size - strHif.u16Length) > 4) - { - M2M_ERR("(hif) Corrupted packet Size = %u \n", - size, strHif.u16Length, strHif.u8Gid, strHif.u8Opcode); - nm_bsp_interrupt_ctrl(1); - ret = M2M_ERR_BUS_FAIL; - goto ERR1; - } - } - - if(M2M_REQ_GROUP_WIFI == strHif.u8Gid) - { - if(gstrHifCxt.pfWifiCb) - gstrHifCxt.pfWifiCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); - else -#ifdef ARDUINO - { -#endif - M2M_ERR("WIFI callback is not registered\n"); -#ifdef ARDUINO - } -#endif - } - else if(M2M_REQ_GROUP_IP == strHif.u8Gid) - { - if(gstrHifCxt.pfIpCb) - gstrHifCxt.pfIpCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); - else -#ifdef ARDUINO - { -#endif - M2M_ERR("Scoket callback is not registered\n"); -#ifdef ARDUINO - } -#endif - } - else if(M2M_REQ_GROUP_OTA == strHif.u8Gid) - { - if(gstrHifCxt.pfOtaCb) - gstrHifCxt.pfOtaCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); - else -#ifdef ARDUINO - { -#endif - M2M_ERR("Ota callback is not registered\n"); -#ifdef ARDUINO - } -#endif - } - else if(M2M_REQ_GROUP_CRYPTO == strHif.u8Gid) - { - if(gstrHifCxt.pfCryptoCb) - gstrHifCxt.pfCryptoCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); - - else -#ifdef ARDUINO - { -#endif - M2M_ERR("Crypto callback is not registered\n"); -#ifdef ARDUINO - } -#endif - } - else if(M2M_REQ_GROUP_SIGMA == strHif.u8Gid) - { - if(gstrHifCxt.pfSigmaCb) - gstrHifCxt.pfSigmaCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); - else -#ifdef ARDUINO - { -#endif - M2M_ERR("Sigma callback is not registered\n"); -#ifdef ARDUINO - } -#endif - } - else if(M2M_REQ_GROUP_SSL == strHif.u8Gid) - { - if(gstrHifCxt.pfSslCb) - gstrHifCxt.pfSslCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); - } - else - { - M2M_ERR("(hif) invalid group ID\n"); - ret = M2M_ERR_BUS_FAIL; - goto ERR1; - } -#ifdef ARDUINO - if(hif_small_xfer) - { - /*Pause SPI transfer*/ - return ret; - } -#endif - if(gstrHifCxt.u8HifRXDone) - { - M2M_ERR("(hif) host app didn't set RX Done <%u><%X>\n", strHif.u8Gid, strHif.u8Opcode); - ret = hif_set_rx_done(); - if(ret != M2M_SUCCESS) goto ERR1; - } - } - else - { - M2M_ERR("(hif) Wrong Size\n"); - ret = M2M_ERR_RCV; - goto ERR1; - } - } - else - { -#ifndef WIN32 - M2M_ERR("(hif) False interrupt %lx",reg); - ret = M2M_ERR_FAIL; - goto ERR1; -#else -#endif - } - } - else - { - M2M_ERR("(hif) Fail to Read interrupt reg\n"); - goto ERR1; - } - -ERR1: - return ret; -} - -#ifdef ARDUINO -void Socket_ReadSocketData_Small(void); -#endif - -/** -* @fn hif_handle_isr(void) -* @brief Handle interrupt received from NMC1500 firmware. -* @return The function SHALL return 0 for success and a negative value otherwise. -*/ - -sint8 hif_handle_isr(void) -{ - sint8 ret = M2M_SUCCESS; - -#ifdef ARDUINO - if(hif_small_xfer) { - /*SPI protocol paused to allow small transfer*/ - Socket_ReadSocketData_Small(); - return ret; - } -#endif - - while (gstrHifCxt.u8Interrupt) { - /*must be at that place because of the race of interrupt increment and that decrement*/ - /*when the interrupt enabled*/ - gstrHifCxt.u8Interrupt--; - while(1) - { - ret = hif_isr(); -#ifdef ARDUINO - if(hif_small_xfer) { - return ret; - } -#endif - if(ret == M2M_SUCCESS) { - /*we will try forever untill we get that interrupt*/ - /*Fail return errors here due to bus errors (reading expected values)*/ - break; - } else { - M2M_ERR("(HIF) Fail to handle interrupt %d try Again..\n",ret); - } - } - } - - return ret; -} -/* -* @fn hif_receive -* @brief Host interface interrupt serviece routine -* @param [in] u32Addr -* Receive start address -* @param [out] pu8Buf -* Pointer to receive buffer. Allocated by the caller -* @param [in] u16Sz -* Receive buffer size -* @param [in] isDone -* If you don't need any more packets send True otherwise send false -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ -sint8 hif_receive(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz, uint8 isDone) -{ - sint8 ret = M2M_SUCCESS; - if((u32Addr == 0)||(pu8Buf == NULL) || (u16Sz == 0)) - { - if(isDone) - { - /* set RX done */ - ret = hif_set_rx_done(); - } - else - { - ret = M2M_ERR_FAIL; - M2M_ERR(" hif_receive: Invalid argument\n"); - } - goto ERR1; - } - - if(u16Sz > gstrHifCxt.u32RxSize) - { - ret = M2M_ERR_FAIL; - M2M_ERR("APP Requested Size is larger than the recived buffer size <%u><%lu>\n",u16Sz, gstrHifCxt.u32RxSize); - goto ERR1; - } - if((u32Addr < gstrHifCxt.u32RxAddr)||((u32Addr + u16Sz)>(gstrHifCxt.u32RxAddr + gstrHifCxt.u32RxSize))) - { - ret = M2M_ERR_FAIL; - M2M_ERR("APP Requested Address beyond the recived buffer address and length\n"); - goto ERR1; - } - - /* Receive the payload */ - ret = nm_read_block(u32Addr, pu8Buf, u16Sz); - if(ret != M2M_SUCCESS)goto ERR1; - - /* check if this is the last packet */ - if((((gstrHifCxt.u32RxAddr + gstrHifCxt.u32RxSize) - (u32Addr + u16Sz)) <= 0) || isDone) - { - /* set RX done */ - ret = hif_set_rx_done(); - } - -ERR1: - return ret; -} - -/** -* @fn hif_register_cb -* @brief To set Callback function for every compantent Component -* @param [in] u8Grp -* Group to which the Callback function should be set. -* @param [in] fn -* function to be set -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -sint8 hif_register_cb(uint8 u8Grp,tpfHifCallBack fn) -{ - sint8 ret = M2M_SUCCESS; - switch(u8Grp) - { - case M2M_REQ_GROUP_IP: - gstrHifCxt.pfIpCb = fn; - break; - case M2M_REQ_GROUP_WIFI: - gstrHifCxt.pfWifiCb = fn; - break; - case M2M_REQ_GROUP_OTA: - gstrHifCxt.pfOtaCb = fn; - break; - case M2M_REQ_GROUP_HIF: - gstrHifCxt.pfHifCb = fn; - break; - case M2M_REQ_GROUP_CRYPTO: - gstrHifCxt.pfCryptoCb = fn; - break; - case M2M_REQ_GROUP_SIGMA: - gstrHifCxt.pfSigmaCb = fn; - break; - case M2M_REQ_GROUP_SSL: - gstrHifCxt.pfSslCb = fn; - break; - default: - M2M_ERR("GRp ? %d\n",u8Grp); - ret = M2M_ERR_FAIL; - break; - } - return ret; -} - -#endif diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_hif.h b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_hif.h deleted file mode 100644 index 1187183..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_hif.h +++ /dev/null @@ -1,249 +0,0 @@ -/** - * - * \file - * - * \brief This module contains M2M host interface APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _M2M_HIF_ -#define _M2M_HIF_ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "common/include/nm_common.h" -/*!< Include depends on UNO Board is used or not*/ -#ifdef ENABLE_UNO_BOARD -#include "m2m_uno_hif.h" -#endif - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#define M2M_HIF_MAX_PACKET_SIZE (1600 - 4) -/*!< Maximum size of the buffer could be transferred between Host and Firmware. -*/ - -#define M2M_HIF_HDR_OFFSET (sizeof(tstrHifHdr) + 4) - -/** -* @struct tstrHifHdr -* @brief Structure to hold HIF header -*/ -typedef struct -{ - uint8 u8Gid; /*!< Group ID */ - uint8 u8Opcode; /*!< OP code */ - uint16 u16Length; /*!< Payload length */ -}tstrHifHdr; - -#ifdef __cplusplus - extern "C" { -#endif - -/*! -@typedef typedef void (*tpfHifCallBack)(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr); -@brief used to point to Wi-Fi call back function depend on Arduino project or other projects. -@param [in] u8OpCode - HIF Opcode type. -@param [in] u16DataSize - HIF data length. -@param [in] u32Addr - HIF address. -@param [in] grp - HIF group type. -*/ -typedef void (*tpfHifCallBack)(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr); -/** -* @fn NMI_API sint8 hif_init(void * arg); -* @brief - To initialize HIF layer. -* @param [in] arg -* Pointer to the arguments. -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 hif_init(void * arg); -/** -* @fn NMI_API sint8 hif_deinit(void * arg); -* @brief - To Deinitialize HIF layer. -* @param [in] arg -* Pointer to the arguments. -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 hif_deinit(void * arg); -/** -* @fn NMI_API sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, - uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) -* @brief Send packet using host interface. - -* @param [in] u8Gid -* Group ID. -* @param [in] u8Opcode -* Operation ID. -* @param [in] pu8CtrlBuf -* Pointer to the Control buffer. -* @param [in] u16CtrlBufSize - Control buffer size. -* @param [in] u16DataOffset - Packet Data offset. -* @param [in] pu8DataBuf -* Packet buffer Allocated by the caller. -* @param [in] u16DataSize - Packet buffer size (including the HIF header). -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, - uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset); -/* -* @fn hif_receive -* @brief Host interface interrupt serviece routine -* @param [in] u32Addr -* Receive start address -* @param [out] pu8Buf -* Pointer to receive buffer. Allocated by the caller -* @param [in] u16Sz -* Receive buffer size -* @param [in] isDone -* If you don't need any more packets send True otherwise send false -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -NMI_API sint8 hif_receive(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz, uint8 isDone); -/** -* @fn hif_register_cb -* @brief - To set Callback function for every Component. - -* @param [in] u8Grp -* Group to which the Callback function should be set. - -* @param [in] fn -* function to be set to the specified group. -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 hif_register_cb(uint8 u8Grp,tpfHifCallBack fn); -/** -* @fn NMI_API sint8 hif_chip_sleep(void); -* @brief - To make the chip sleep. -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 hif_chip_sleep(void); -/** -* @fn NMI_API sint8 hif_chip_sleep_sc(void); -* @brief - To clear the chip count only but keep the chip awake -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 hif_chip_sleep_sc(void); -/** -* @fn NMI_API sint8 hif_chip_wake(void); -* @brief - To Wakeup the chip. -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -NMI_API sint8 hif_chip_wake(void); -/*! -@fn \ - NMI_API void hif_set_sleep_mode(uint8 u8Pstype); - -@brief - Set the sleep mode of the HIF layer. - -@param [in] u8Pstype - Sleep mode. - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ - -NMI_API void hif_set_sleep_mode(uint8 u8Pstype); -/*! -@fn \ - NMI_API uint8 hif_get_sleep_mode(void); - -@brief - Get the sleep mode of the HIF layer. - -@return - The function SHALL return the sleep mode of the HIF layer. -*/ - -NMI_API uint8 hif_get_sleep_mode(void); - -#ifdef CORTUS_APP -/** -* @fn hif_Resp_handler(uint8 *pu8Buffer, uint16 u16BufferSize) -* @brief - Response handler for HIF layer. - -* @param [in] pu8Buffer - Pointer to the buffer. - -* @param [in] u16BufferSize - Buffer size. - -* @return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 hif_Resp_handler(uint8 *pu8Buffer, uint16 u16BufferSize); -#endif - -/** -* @fn hif_handle_isr(void) -* @brief - Handle interrupt received from NMC1500 firmware. -* @return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 hif_handle_isr(void); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ota.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ota.c deleted file mode 100644 index cf4a30f..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ota.c +++ /dev/null @@ -1,417 +0,0 @@ -/** - * - * \file - * - * \brief NMC1500 IoT OTA Interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#include "common/include/nm_common.h" -#include "driver/include/m2m_types.h" -#include "driver/include/m2m_ota.h" -#include "driver/source/m2m_hif.h" -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -static tpfOtaUpdateCb gpfOtaUpdateCb = NULL; -static tpfOtaNotifCb gpfOtaNotifCb = NULL; - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/** -* @fn m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr, uint8 grp) -* @brief WiFi call back function -* @param [in] u8OpCode -* HIF Opcode type. -* @param [in] u16DataSize -* HIF data length. -* @param [in] u32Addr -* HIF address. -* @param [in] grp -* HIF group type. -* @author -* @date -* @version 1.0 -*/ -static void m2m_ota_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -{ -#ifdef ARDUINO - (void)u16DataSize; // Silence "unused" warning -#endif - sint8 ret = M2M_SUCCESS; - if(u8OpCode == M2M_OTA_RESP_NOTIF_UPDATE_INFO) - { - tstrOtaUpdateInfo strOtaUpdateInfo; - m2m_memset((uint8*)&strOtaUpdateInfo,0,sizeof(tstrOtaUpdateInfo)); - ret = hif_receive(u32Addr,(uint8*)&strOtaUpdateInfo,sizeof(tstrOtaUpdateInfo),0); - if(ret == M2M_SUCCESS) - { - if(gpfOtaNotifCb) - gpfOtaNotifCb(&strOtaUpdateInfo); - } - } - else if (u8OpCode == M2M_OTA_RESP_UPDATE_STATUS) - { - tstrOtaUpdateStatusResp strOtaUpdateStatusResp; - m2m_memset((uint8*)&strOtaUpdateStatusResp,0,sizeof(tstrOtaUpdateStatusResp)); - ret = hif_receive(u32Addr, (uint8*) &strOtaUpdateStatusResp,sizeof(tstrOtaUpdateStatusResp), 0); - if(ret == M2M_SUCCESS) - { - if(gpfOtaUpdateCb) - gpfOtaUpdateCb(strOtaUpdateStatusResp.u8OtaUpdateStatusType,strOtaUpdateStatusResp.u8OtaUpdateStatus); - } - } - else - { - M2M_ERR("Invaild OTA resp %d ?\n",u8OpCode); - } - -} -/*! -@fn \ - NMI_API sint8 m2m_ota_init(tpfOtaUpdateCb pfOtaUpdateCb, tpfOtaNotifCb pfOtaNotifCb); - -@brief - Initialize the OTA layer. - -@param [in] pfOtaUpdateCb - OTA Update callback function - -@param [in] pfOtaNotifCb - OTA notify callback function - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_init(tpfOtaUpdateCb pfOtaUpdateCb, tpfOtaNotifCb pfOtaNotifCb) -{ - sint8 ret = M2M_SUCCESS; - - if(pfOtaUpdateCb){ - gpfOtaUpdateCb = pfOtaUpdateCb; - }else{ - M2M_ERR("Invaild Ota update cb\n"); - } - if(pfOtaNotifCb){ - gpfOtaNotifCb = pfOtaNotifCb; - }else{ - M2M_ERR("Invaild Ota notify cb\n"); - } - - hif_register_cb(M2M_REQ_GROUP_OTA,m2m_ota_cb); - - return ret; -} -/*! -@fn \ - NMI_API sint8 m2m_ota_notif_set_url(uint8 * u8Url); - -@brief - Set the OTA url - -@param [in] u8Url - The url server address - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_notif_set_url(uint8 * u8Url) -{ - sint8 ret = M2M_SUCCESS; - uint16 u16UrlSize = m2m_strlen(u8Url) + 1; - /*Todo: we may change it to data pkt but we need to give it higer priority - but the priorty is not implemnted yet in data pkt - */ - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_NOTIF_SET_URL,u8Url,u16UrlSize,NULL,0,0); - return ret; - -} - -/*! -@fn \ - NMI_API sint8 m2m_ota_notif_check_for_update(void); - -@brief - check for ota update - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_notif_check_for_update(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_NOTIF_CHECK_FOR_UPDATE,NULL,0,NULL,0,0); - return ret; -} - -/*! -@fn \ - NMI_API sint8 m2m_ota_notif_sched(uint32 u32Period); - -@brief - Schedule OTA update - -@param [in] u32Period - Period in days - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_notif_sched(uint32 u32Period) -{ -#ifdef ARDUINO - (void)u32Period; // Silence "unused" warning -#endif - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_NOTIF_CHECK_FOR_UPDATE,NULL,0,NULL,0,0); - return ret; -} - -/*! -@fn \ - NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl); - -@brief - Request OTA start update using the downloaded url - -@param [in] u8DownloadUrl - The download firmware url, you get it from device info - -@return - The function SHALL return 0 for success and a negative value otherwise. - -*/ -NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl) -{ - sint8 ret = M2M_SUCCESS; - uint16 u16DurlSize = m2m_strlen(u8DownloadUrl) + 1; - /*Todo: we may change it to data pkt but we need to give it higer priority - but the priorty is not implemnted yet in data pkt - */ - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_START_FW_UPDATE,u8DownloadUrl,u16DurlSize,NULL,0,0); - return ret; -} -/*! -@fn \ - NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl); - -@brief - Request OTA start for the Cortus app image. - -@param [in] u8DownloadUrl - The cortus application image url. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -*/ -NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl) -{ - sint8 ret = M2M_SUCCESS; - uint16 u16DurlSize = m2m_strlen(u8DownloadUrl) + 1; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_START_CRT_UPDATE,u8DownloadUrl,u16DurlSize,NULL,0,0); - return ret; -} - - -/*! -@fn \ - NMI_API sint8 m2m_ota_rollback(void); - -@brief - Request OTA Rollback image - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_rollback(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_ROLLBACK_FW,NULL,0,NULL,0,0); - return ret; -} -/*! -@fn \ - NMI_API sint8 m2m_ota_rollback_crt(void); - -@brief - Request Cortus application OTA Rollback image - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_rollback_crt(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_ROLLBACK_CRT,NULL,0,NULL,0,0); - return ret; -} - -/*! -@fn \ - NMI_API sint8 m2m_ota_abort(void); - -@brief - Request OTA Abort - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_abort(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_ABORT,NULL,0,NULL,0,0); - return ret; -} - - -/*! -@fn \ - NMI_API sint8 m2m_ota_switch_firmware(void); - -@brief - Switch to the upgraded Firmware - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_switch_firmware(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_SWITCH_FIRMWARE,NULL,0,NULL,0,0); - return ret; -} -/*! -@fn \ - NMI_API sint8 m2m_ota_switch_crt(void); - -@brief - Switch to the upgraded cortus application. - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_switch_crt(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_SWITCH_CRT_IMG,NULL,0,NULL,0,0); - return ret; -} - -/*! -@fn \ - NMI_API sint8 m2m_ota_get_firmware_version(tstrM2mRev * pstrRev); - -@brief - Get the OTA Firmware version. - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_get_firmware_version(tstrM2mRev * pstrRev) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_chip_wake(); - if(ret == M2M_SUCCESS) - { - ret = nm_get_ota_firmware_info(pstrRev); - hif_chip_sleep(); - } - return ret; -} -#if 0 -#define M2M_OTA_FILE "../../../m2m_ota.dat" -NMI_API sint8 m2m_ota_test(void) -{ - uint32 page = 0; - uint8 buffer[1500]; - uint32 u32Sz = 0; - sint8 ret = M2M_SUCCESS; - FILE *fp =NULL; - fp = fopen(M2M_OTA_FILE,"rb"); - if(fp) - { - fseek(fp, 0L, SEEK_END); - u32Sz = ftell(fp); - fseek(fp, 0L, SEEK_SET); - - while(u32Sz > 0) - { - { - page = (rand()%1400); - - if((page<100)||(page>1400)) page = 1400; - } - - if(u32Sz>page) - { - u32Sz-=page; - } - else - { - page = u32Sz; - u32Sz = 0; - } - printf("page %d\n", (int)page); - fread(buffer,page,1,fp); - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_TEST|M2M_REQ_DATA_PKT,NULL,0,(uint8*)&buffer,page,0); - if(ret != M2M_SUCCESS) - { - M2M_ERR("\n"); - } - nm_bsp_sleep(1); - } - - } - else - { - M2M_ERR("nO err\n"); - } - return ret; -} -#endif - diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_periph.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_periph.c deleted file mode 100644 index 0f8890b..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_periph.c +++ /dev/null @@ -1,187 +0,0 @@ -/** - * - * \file - * - * \brief NMC1500 Peripherials Application Interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "driver/include/m2m_periph.h" -#include "driver/source/nmasic.h" -#include "m2m_hif.h" - -#ifdef CONF_PERIPH - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#define GPIO_OP_DIR 0 -#define GPIO_OP_SET 1 -#define GPIO_OP_GET 2 -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -STATIC FUNCTIONS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -static sint8 get_gpio_idx(uint8 u8GpioNum) -{ - if(u8GpioNum >= M2M_PERIPH_GPIO_MAX) return -1; - if(u8GpioNum == M2M_PERIPH_GPIO15) { return 15; - } else if(u8GpioNum == M2M_PERIPH_GPIO16) { return 16; - } else if(u8GpioNum == M2M_PERIPH_GPIO18) { return 18; - } else if(u8GpioNum == M2M_PERIPH_GPIO3) { return 3; - } else if(u8GpioNum == M2M_PERIPH_GPIO4) { return 4; - } else if(u8GpioNum == M2M_PERIPH_GPIO5) { return 5; - } else if(u8GpioNum == M2M_PERIPH_GPIO6) { return 6; - } else { - return -2; - } -} -/* - * GPIO read/write skeleton with wakeup/sleep capability. - */ -static sint8 gpio_ioctl(uint8 op, uint8 u8GpioNum, uint8 u8InVal, uint8 * pu8OutVal) -{ - sint8 ret, gpio; - - ret = hif_chip_wake(); - if(ret != M2M_SUCCESS) goto _EXIT; - - gpio = get_gpio_idx(u8GpioNum); - if(gpio < 0) goto _EXIT1; - - if(op == GPIO_OP_DIR) { - ret = set_gpio_dir((uint8)gpio, u8InVal); - } else if(op == GPIO_OP_SET) { - ret = set_gpio_val((uint8)gpio, u8InVal); - } else if(op == GPIO_OP_GET) { - ret = get_gpio_val((uint8)gpio, pu8OutVal); - } - if(ret != M2M_SUCCESS) goto _EXIT1; - -_EXIT1: - ret = hif_chip_sleep(); -_EXIT: - return ret; -} -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION IMPLEMENTATION -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -sint8 m2m_periph_init(tstrPerphInitParam * param) -{ -#ifdef ARDUINO - (void)param; // Silence "unused" warning -#endif - return M2M_SUCCESS; -} - -sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir) -{ - return gpio_ioctl(GPIO_OP_DIR, u8GpioNum, u8GpioDir, NULL); -} - -sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal) -{ - return gpio_ioctl(GPIO_OP_SET, u8GpioNum, u8GpioVal, NULL); -} - -sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal) -{ - return gpio_ioctl(GPIO_OP_GET, u8GpioNum, 0, pu8GpioVal); -} - -sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn) -{ -#ifdef ARDUINO - (void)u8GpioNum; // Silence "unused" warning - (void)u8PullupEn; -#endif - /* TBD */ - return M2M_SUCCESS; -} - -sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)param; -#endif - /* TBD */ - return M2M_SUCCESS; -} - -sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)u8SlaveAddr; - (void)pu8Buf; - (void)u16BufLen; - (void)flags; -#endif - /* TBD */ - return M2M_SUCCESS; -} - -sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)u8SlaveAddr; - (void)pu8Buf; - (void)u16BufLen; - (void)pu16ReadLen; - (void)flags; -#endif - /* TBD */ - return M2M_SUCCESS; -} - - -sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable) -{ - return pullup_ctrl(pinmask, enable); -} -#endif /* CONF_PERIPH */ \ No newline at end of file diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ssl.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ssl.c deleted file mode 100644 index 07513f7..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_ssl.c +++ /dev/null @@ -1,309 +0,0 @@ -/** - * - * \file - * - * \brief This module contains M2M Wi-Fi APIs implementation. - * - * Copyright (c) 2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "driver/include/m2m_ssl.h" -#include "driver/source/m2m_hif.h" -#include "driver/source/nmasic.h" - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -static tpfAppSSLCb gpfAppSSLCb = NULL; -static uint32 gu32HIFAddr = 0; - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*! - @fn \ m2m_ssl_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) - @brief SSL callback function - @param [in] u8OpCode - HIF Opcode type. - @param [in] u16DataSize - HIF data length. - @param [in] u32Addr - HIF address. -*/ -static void m2m_ssl_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -{ -#ifdef ARDUINO - (void)u16DataSize; // Silence "unused" warning -#endif - sint8 s8tmp = M2M_SUCCESS; - switch(u8OpCode) - { - case M2M_SSL_REQ_ECC: - { - tstrEccReqInfo strEccREQ; - s8tmp = hif_receive(u32Addr, (uint8*)&strEccREQ, sizeof(tstrEccReqInfo), 0); - if(s8tmp == M2M_SUCCESS) - { - if (gpfAppSSLCb) - { - gu32HIFAddr = u32Addr + sizeof(tstrEccReqInfo); - gpfAppSSLCb(M2M_SSL_REQ_ECC, &strEccREQ); - } - } - } - break; - case M2M_SSL_RESP_SET_CS_LIST: - { - tstrSslSetActiveCsList strCsList; - s8tmp = hif_receive(u32Addr, (uint8*)&strCsList, sizeof(tstrSslSetActiveCsList), 0); - if(s8tmp == M2M_SUCCESS) - { - if (gpfAppSSLCb) - gpfAppSSLCb(M2M_SSL_RESP_SET_CS_LIST, &strCsList); - } - } - break; - } - if(s8tmp != M2M_SUCCESS) - { - M2M_ERR("Error receiving SSL from the HIF\n"); - } -} - - -/*! - @fn \ m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz) - @brief Sends ECC responses to the WINC - @param [in] strECCResp - ECC Response struct. - @param [in] pu8RspDataBuffe - Pointer of the response data to be sent. - @param [in] u16RspDataSz - Response data size. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz) -{ - sint8 s8Ret = M2M_SUCCESS; - - s8Ret = hif_send(M2M_REQ_GROUP_SSL, (M2M_SSL_RESP_ECC | M2M_REQ_DATA_PKT), (uint8*)strECCResp, sizeof(tstrEccReqInfo), pu8RspDataBuff, u16RspDataSz, sizeof(tstrEccReqInfo)); - - return s8Ret; -} - -/*! - @fn \ m2m_ssl_send_certs_to_winc(uint8* sector_buffer, uint32 sector_size) - @brief Sends certificates to the WINC - @param [in] pu8Buffer - Pointer to the certificates. - @param [in] u32BufferSz - Size of the certificates. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_send_certs_to_winc(uint8* pu8Buffer, uint32 u32BufferSz) -{ - sint8 s8Ret = M2M_SUCCESS; - - s8Ret = hif_send(M2M_REQ_GROUP_SSL, (M2M_SSL_IND_CERTS_ECC | M2M_REQ_DATA_PKT), NULL, 0, pu8Buffer, u32BufferSz, 0); - - return s8Ret; -} - -/*! - @fn \ m2m_ssl_retrieve_cert(uint32 u32ReadAddr, uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key) - @brief Retrieve the certificate to be verified from the WINC - @param [in] pu16CurveType - Pointer to the certificate curve type. - @param [in] pu8Hash - Pointer to the certificate hash. - @param [in] pu8Sig - Pointer to the certificate signature. - @param [in] pu8Key - Pointer to the certificate Key. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_retrieve_cert(uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key) -{ - uint8 bSetRxDone = 1; - uint16 u16HashSz, u16SigSz, u16KeySz; - sint8 s8Ret = M2M_SUCCESS; - - if(gu32HIFAddr == 0) return M2M_ERR_FAIL; - - if(hif_receive(gu32HIFAddr, (uint8*)pu16CurveType, 2, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += 2; - - if(hif_receive(gu32HIFAddr, (uint8*)&u16KeySz, 2, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += 2; - - if(hif_receive(gu32HIFAddr, (uint8*)&u16HashSz, 2, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += 2; - - if(hif_receive(gu32HIFAddr, (uint8*)&u16SigSz, 2, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += 2; - - (*pu16CurveType)= _htons((*pu16CurveType)); - pu8Key->u16Size = _htons(u16KeySz); - u16HashSz = _htons(u16HashSz); - u16SigSz = _htons(u16SigSz); - - if(hif_receive(gu32HIFAddr, pu8Key->X, pu8Key->u16Size * 2, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += (pu8Key->u16Size * 2); - - if(hif_receive(gu32HIFAddr, pu8Hash, u16HashSz, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += u16HashSz; - - if(hif_receive(gu32HIFAddr, pu8Sig, u16SigSz, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += u16SigSz; - - bSetRxDone = 0; - -__ERR: - if(bSetRxDone) - { - s8Ret = M2M_ERR_FAIL; - hif_receive(0, NULL, 0, 1); - } - return s8Ret; -} - -/*! - @fn \ m2m_ssl_retrieve_hash(uint32 u32ReadAddr, uint8* pu8Hash, uint16 u16HashSz) - @brief Retrieve the certificate hash - @param [in] pu8Hash - Pointer to the certificate hash. - @param [in] u16HashSz - Hash size. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_retrieve_hash(uint8* pu8Hash, uint16 u16HashSz) -{ - uint8 bSetRxDone = 1; - sint8 s8Ret = M2M_SUCCESS; - - if(gu32HIFAddr == 0) return M2M_ERR_FAIL; - - if(hif_receive(gu32HIFAddr, pu8Hash, u16HashSz, 0) != M2M_SUCCESS) goto __ERR; - - bSetRxDone = 0; - -__ERR: - if(bSetRxDone) - { - s8Ret = M2M_ERR_FAIL; - hif_receive(0, NULL, 0, 1); - } - return s8Ret; -} - -/*! - @fn \ m2m_ssl_stop_processing_certs(void) - @brief Stops receiving from the HIF -*/ -NMI_API void m2m_ssl_stop_processing_certs(void) -{ - hif_receive(0, NULL, 0, 1); -} - -/*! - @fn \ m2m_ssl_ecc_process_done(void) - @brief Stops receiving from the HIF -*/ -NMI_API void m2m_ssl_ecc_process_done(void) -{ - gu32HIFAddr = 0; -} - -/*! -@fn \ - m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP); - Override the default Active SSL ciphers in the SSL module with a certain combination selected by the caller in the form of - a bitmap containing the required ciphers to be on. - There is no need to call this function if the application will not change the default ciphersuites. - -@param [in] u32SslCsBMP - Bitmap containing the desired ciphers to be enabled for the SSL module. The ciphersuites are defined in - @ref SSLCipherSuiteID. - The default ciphersuites are all ciphersuites supported by the firmware with the exception of ECC ciphersuites. - The caller can override the default with any desired combination, except for combinations involving both RSA - and ECC; if any RSA ciphersuite is enabled, then firmware will disable all ECC ciphersuites. - If u32SslCsBMP does not contain any ciphersuites supported by firmware, then the current active list will not - be changed. - -@return - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) -*/ -sint8 m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP) -{ - sint8 s8Ret = M2M_SUCCESS; - tstrSslSetActiveCsList strCsList; - - strCsList.u32CsBMP = u32SslCsBMP; - s8Ret = hif_send(M2M_REQ_GROUP_SSL, M2M_SSL_REQ_SET_CS_LIST, (uint8*)&strCsList, sizeof(tstrSslSetActiveCsList), NULL, 0, 0); - - return s8Ret; -} - -/*! - @fn \ m2m_ssl_init(tpfAppSslCb pfAppSslCb); - @brief Initializes the SSL layer. - @param [in] pfAppSslCb - Application SSL callback function. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_init(tpfAppSSLCb pfAppSSLCb) -{ - sint8 s8Ret = M2M_SUCCESS; - - gpfAppSSLCb = pfAppSSLCb; - gu32HIFAddr = 0; - - s8Ret = hif_register_cb(M2M_REQ_GROUP_SSL,m2m_ssl_cb); - if (s8Ret != M2M_SUCCESS) - { - M2M_ERR("hif_register_cb() failed with ret=%d", s8Ret); - } - return s8Ret; -} \ No newline at end of file diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_wifi.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_wifi.c deleted file mode 100644 index 7998623..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/m2m_wifi.c +++ /dev/null @@ -1,1522 +0,0 @@ -/** - * - * \file - * - * \brief This module contains M2M Wi-Fi APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "driver/include/m2m_wifi.h" -#include "driver/source/m2m_hif.h" -#include "driver/source/nmasic.h" - -static volatile uint8 gu8ChNum; -static volatile uint8 gu8scanInProgress = 0; -static tpfAppWifiCb gpfAppWifiCb = NULL; - - -#ifdef ETH_MODE -static tpfAppEthCb gpfAppEthCb = NULL; -static uint8* gau8ethRcvBuf=NULL; -static uint16 gu16ethRcvBufSize ; -#endif - - -//#define CONF_MGMT -#ifdef CONF_MGMT -static tpfAppMonCb gpfAppMonCb = NULL; -static struct _tstrMgmtCtrl -{ - uint8* pu8Buf; - uint16 u16Offset; - uint16 u16Sz; -} -gstrMgmtCtrl = {NULL, 0 , 0}; -#endif -/** -* @fn m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr, uint8 grp) -* @brief WiFi call back function -* @param [in] u8OpCode -* HIF Opcode type. -* @param [in] u16DataSize -* HIF data length. -* @param [in] u32Addr -* HIF address. -* @param [in] grp -* HIF group type. -* @author -* @date -* @version 1.0 -*/ -static void m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -{ -#ifdef ARDUINO - (void)u16DataSize; // Silence "unused" warning -#endif - uint8 rx_buf[8]; - if (u8OpCode == M2M_WIFI_RESP_CON_STATE_CHANGED) - { - tstrM2mWifiStateChanged strState; - if (hif_receive(u32Addr, (uint8*) &strState,sizeof(tstrM2mWifiStateChanged), 0) == M2M_SUCCESS) - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_CON_STATE_CHANGED, &strState); - } - } - else if (u8OpCode == M2M_WIFI_RESP_GET_SYS_TIME) - { - tstrSystemTime strSysTime; - if (hif_receive(u32Addr, (uint8*) &strSysTime,sizeof(tstrSystemTime), 0) == M2M_SUCCESS) - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_GET_SYS_TIME, &strSysTime); - } - } - else if(u8OpCode == M2M_WIFI_RESP_CONN_INFO) - { - tstrM2MConnInfo strConnInfo; - if(hif_receive(u32Addr, (uint8*)&strConnInfo, sizeof(tstrM2MConnInfo), 1) == M2M_SUCCESS) - { - if(gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_CONN_INFO, &strConnInfo); - } - } - else if (u8OpCode == M2M_WIFI_RESP_MEMORY_RECOVER) - { -#if 0 - if (hif_receive(u32Addr, rx_buf, 4, 1) == M2M_SUCCESS) - { - tstrM2mWifiStateChanged strState; - m2m_memcpy((uint8*) &strState, rx_buf,sizeof(tstrM2mWifiStateChanged)); - if (app_wifi_recover_cb) - app_wifi_recover_cb(strState.u8CurrState); - } -#endif - } - else if (u8OpCode == M2M_WIFI_REQ_DHCP_CONF) - { - tstrM2MIPConfig strIpConfig; -#ifdef ARDUINO - extern uint32 nmdrv_firm_ver; - uint16 rxSize = sizeof(tstrM2MIPConfig); - - if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 5, 0)) { - // for backwards compatibility with firmware 19.4.4 and older, - // the old tstrM2MIPConfig does not contain the u32DhcpLeaseTime field - rxSize -= sizeof(strIpConfig.u32DhcpLeaseTime); - } - - if (hif_receive(u32Addr, (uint8 *)&strIpConfig, rxSize, 0) == M2M_SUCCESS) -#else - if (hif_receive(u32Addr, (uint8 *)&strIpConfig, sizeof(tstrM2MIPConfig), 0) == M2M_SUCCESS) -#endif - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_REQ_DHCP_CONF, (uint8 *)&strIpConfig); - } - } - else if (u8OpCode == M2M_WIFI_REQ_WPS) - { - tstrM2MWPSInfo strWps; - m2m_memset((uint8*)&strWps,0,sizeof(tstrM2MWPSInfo)); - if(hif_receive(u32Addr, (uint8*)&strWps, sizeof(tstrM2MWPSInfo), 0) == M2M_SUCCESS) - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_REQ_WPS, &strWps); - } - } - else if (u8OpCode == M2M_WIFI_RESP_IP_CONFLICT) - { - uint32 u32ConflictedIP; - if(hif_receive(u32Addr, (uint8 *)&u32ConflictedIP, sizeof(u32ConflictedIP), 0) == M2M_SUCCESS) - { - M2M_INFO("Conflicted IP \" %u.%u.%u.%u \" \n", - BYTE_0(u32ConflictedIP),BYTE_1(u32ConflictedIP),BYTE_2(u32ConflictedIP),BYTE_3(u32ConflictedIP)); - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_IP_CONFLICT, NULL); - - } - } - else if (u8OpCode == M2M_WIFI_RESP_SCAN_DONE) - { - tstrM2mScanDone strState; - gu8scanInProgress = 0; - if(hif_receive(u32Addr, (uint8*)&strState, sizeof(tstrM2mScanDone), 0) == M2M_SUCCESS) - { - gu8ChNum = strState.u8NumofCh; - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_SCAN_DONE, &strState); - } - } - else if (u8OpCode == M2M_WIFI_RESP_SCAN_RESULT) - { - tstrM2mWifiscanResult strScanResult; - if(hif_receive(u32Addr, (uint8*)&strScanResult, sizeof(tstrM2mWifiscanResult), 0) == M2M_SUCCESS) - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_SCAN_RESULT, &strScanResult); - } - } - else if (u8OpCode == M2M_WIFI_RESP_CURRENT_RSSI) - { - if (hif_receive(u32Addr, rx_buf, 4, 0) == M2M_SUCCESS) - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_CURRENT_RSSI, rx_buf); - } - } - else if (u8OpCode == M2M_WIFI_RESP_CLIENT_INFO) - { - if (hif_receive(u32Addr, rx_buf, 4, 0) == M2M_SUCCESS) - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_CLIENT_INFO, rx_buf); - } - } - else if(u8OpCode == M2M_WIFI_RESP_PROVISION_INFO) - { - tstrM2MProvisionInfo strProvInfo; - if(hif_receive(u32Addr, (uint8*)&strProvInfo, sizeof(tstrM2MProvisionInfo), 1) == M2M_SUCCESS) - { - if(gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_PROVISION_INFO, &strProvInfo); - } - } - else if(u8OpCode == M2M_WIFI_RESP_DEFAULT_CONNECT) - { - tstrM2MDefaultConnResp strResp; - if(hif_receive(u32Addr, (uint8*)&strResp, sizeof(tstrM2MDefaultConnResp), 1) == M2M_SUCCESS) - { - if(gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_DEFAULT_CONNECT, &strResp); - } - } - - else if(u8OpCode == M2M_WIFI_RESP_GET_PRNG) - { - tstrPrng strPrng; - if(hif_receive(u32Addr, (uint8*)&strPrng,sizeof(tstrPrng), 0) == M2M_SUCCESS) - { - if(hif_receive(u32Addr + sizeof(tstrPrng),strPrng.pu8RngBuff,strPrng.u16PrngSize, 1) == M2M_SUCCESS) - { - if(gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_GET_PRNG,&strPrng); - } - } - } -#ifdef ETH_MODE - else if(u8OpCode == M2M_WIFI_RESP_ETHERNET_RX_PACKET) - { - uint8 u8SetRxDone; - tstrM2mIpRsvdPkt strM2mRsvd; - if(hif_receive(u32Addr, &strM2mRsvd ,sizeof(tstrM2mIpRsvdPkt), 0) == M2M_SUCCESS) - { - tstrM2mIpCtrlBuf strM2mIpCtrlBuf; - uint16 u16Offset = strM2mRsvd.u16PktOffset; - strM2mIpCtrlBuf.u16RemainigDataSize = strM2mRsvd.u16PktSz; - if((gpfAppEthCb) && (gau8ethRcvBuf) && (gu16ethRcvBufSize > 0)) - { - do - { - u8SetRxDone = 1; - if(strM2mIpCtrlBuf.u16RemainigDataSize > gu16ethRcvBufSize) - { - u8SetRxDone = 0; - strM2mIpCtrlBuf.u16DataSize = gu16ethRcvBufSize; - } - else - { - strM2mIpCtrlBuf.u16DataSize = strM2mIpCtrlBuf.u16RemainigDataSize; - } - - if(hif_receive(u32Addr + u16Offset, gau8ethRcvBuf, strM2mIpCtrlBuf.u16DataSize, u8SetRxDone) == M2M_SUCCESS) - { - strM2mIpCtrlBuf.u16RemainigDataSize -= strM2mIpCtrlBuf.u16DataSize; - u16Offset += strM2mIpCtrlBuf.u16DataSize; - gpfAppEthCb(M2M_WIFI_RESP_ETHERNET_RX_PACKET, gau8ethRcvBuf, &(strM2mIpCtrlBuf)); - } - else - { - break; - } - }while (strM2mIpCtrlBuf.u16RemainigDataSize > 0); - } - } - } -#endif /* ETH_MODE */ -#ifdef CONF_MGMT - else if(u8OpCode == M2M_WIFI_RESP_WIFI_RX_PACKET) - { - - tstrM2MWifiRxPacketInfo strRxPacketInfo; - if(u16DataSize >= sizeof(tstrM2MWifiRxPacketInfo)) { - if(hif_receive(u32Addr, (uint8*)&strRxPacketInfo, sizeof(tstrM2MWifiRxPacketInfo), 0) == M2M_SUCCESS) - { - u16DataSize -= sizeof(tstrM2MWifiRxPacketInfo); - if(u16DataSize > 0 && gstrMgmtCtrl.pu8Buf != NULL) - { - if(u16DataSize > (gstrMgmtCtrl.u16Sz + gstrMgmtCtrl.u16Offset)) - { - u16DataSize = gstrMgmtCtrl.u16Sz; - } - u32Addr += sizeof(tstrM2MWifiRxPacketInfo) + gstrMgmtCtrl.u16Offset; - if(hif_receive(u32Addr , gstrMgmtCtrl.pu8Buf, u16DataSize, 1) != M2M_SUCCESS) return; - } - if(gpfAppMonCb) - gpfAppMonCb(&strRxPacketInfo, gstrMgmtCtrl.pu8Buf,u16DataSize); - } - } else { - M2M_ERR("Incorrect mon data size %u\n", u16DataSize); - } - } -#endif - else - { - M2M_ERR("REQ Not defined %d\n",u8OpCode); - } -} - -sint8 m2m_wifi_download_mode() -{ - sint8 ret = M2M_SUCCESS; - /* Apply device specific initialization. */ - ret = nm_drv_init_download_mode(); - if(ret != M2M_SUCCESS) goto _EXIT0; - - - - enable_interrupts(); - -_EXIT0: - return ret; -} - -static sint8 m2m_validate_ap_parameters(CONST tstrM2MAPConfig* pstrM2MAPConfig) -{ - sint8 s8Ret = M2M_SUCCESS; - /* Check for incoming pointer */ - if(pstrM2MAPConfig == NULL) - { - M2M_ERR("INVALID POINTER\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - /* Check for SSID */ - if((m2m_strlen((uint8 *)pstrM2MAPConfig->au8SSID) <= 0) || (m2m_strlen((uint8 *)pstrM2MAPConfig->au8SSID) >= M2M_MAX_SSID_LEN)) - { - M2M_ERR("INVALID SSID\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - /* Check for Channel */ - if(pstrM2MAPConfig->u8ListenChannel > M2M_WIFI_CH_14 || pstrM2MAPConfig->u8ListenChannel < M2M_WIFI_CH_1) - { - M2M_ERR("INVALID CH\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - /* Check for DHCP Server IP address */ - if(!(pstrM2MAPConfig->au8DHCPServerIP[0] || pstrM2MAPConfig->au8DHCPServerIP[1])) - { - if(!(pstrM2MAPConfig->au8DHCPServerIP[2])) - { - M2M_ERR("INVALID DHCP SERVER IP\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - } - /* Check for Security */ - if(pstrM2MAPConfig->u8SecType == M2M_WIFI_SEC_OPEN) - { - goto ERR1; - } - else if(pstrM2MAPConfig->u8SecType == M2M_WIFI_SEC_WEP) - { - /* Check for WEP Key index */ - if((pstrM2MAPConfig->u8KeyIndx <= 0) || (pstrM2MAPConfig->u8KeyIndx > WEP_KEY_MAX_INDEX)) - { - M2M_ERR("INVALID KEY INDEX\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - /* Check for WEP Key size */ - if( (pstrM2MAPConfig->u8KeySz != WEP_40_KEY_STRING_SIZE) && - (pstrM2MAPConfig->u8KeySz != WEP_104_KEY_STRING_SIZE) - ) - { - M2M_ERR("INVALID KEY STRING SIZE\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - - if((m2m_strlen((uint8 *)pstrM2MAPConfig->au8WepKey) <= 0) || (m2m_strlen((uint8 *)pstrM2MAPConfig->au8WepKey) > WEP_104_KEY_STRING_SIZE)) - { - M2M_ERR("INVALID KEY SIZE\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - } - else if(pstrM2MAPConfig->u8SecType == M2M_WIFI_SEC_WPA_PSK) - { - /* Check for WPA Key size */ - if( ((pstrM2MAPConfig->u8KeySz + 1) < M2M_MIN_PSK_LEN) || ((pstrM2MAPConfig->u8KeySz + 1) > M2M_MAX_PSK_LEN)) - { - M2M_ERR("INVALID WPA KEY SIZE\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - } - else - { - M2M_ERR("INVALID AUTHENTICATION MODE\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - -ERR1: - return s8Ret; -} -static sint8 m2m_validate_scan_options(tstrM2MScanOption* ptstrM2MScanOption) -{ - sint8 s8Ret = M2M_SUCCESS; - /* Check for incoming pointer */ - if(ptstrM2MScanOption == NULL) - { - M2M_ERR("INVALID POINTER\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR; - } - /* Check for valid No of slots */ - if(ptstrM2MScanOption->u8NumOfSlot == 0) - { - M2M_ERR("INVALID No of scan slots! %d\n",ptstrM2MScanOption->u8NumOfSlot); - s8Ret = M2M_ERR_FAIL; - goto ERR; - } - /* Check for valid time of slots */ - if(ptstrM2MScanOption->u8SlotTime < 10 || ptstrM2MScanOption->u8SlotTime > 250) - { - M2M_ERR("INVALID scan slot time! %d\n",ptstrM2MScanOption->u8SlotTime); - s8Ret = M2M_ERR_FAIL; - goto ERR; - } - /* Check for valid No of probe requests per slot */ - if((ptstrM2MScanOption->u8ProbesPerSlot == 0)||(ptstrM2MScanOption->u8ProbesPerSlot > M2M_SCAN_DEFAULT_NUM_PROBE)) - { - M2M_ERR("INVALID No of probe requests per scan slot %d\n",ptstrM2MScanOption->u8ProbesPerSlot); - s8Ret = M2M_ERR_FAIL; - goto ERR; - } - /* Check for valid RSSI threshold */ - if((ptstrM2MScanOption->s8RssiThresh < -99) || (ptstrM2MScanOption->s8RssiThresh >= 0)) - { - M2M_ERR("INVALID RSSI threshold %d \n",ptstrM2MScanOption->s8RssiThresh); - s8Ret = M2M_ERR_FAIL; - } - -ERR: - return s8Ret; -} - -sint8 m2m_wifi_send_crl(tstrTlsCrlInfo* pCRL) -{ - sint8 s8Ret = M2M_ERR_FAIL; - s8Ret = hif_send(M2M_REQ_GROUP_SSL, M2M_SSL_IND_CRL|M2M_REQ_DATA_PKT, NULL, 0, (uint8*)pCRL, sizeof(tstrTlsCrlInfo), 0); - return s8Ret; -} - -sint8 m2m_wifi_init(tstrWifiInitParam * param) -{ - tstrM2mRev strtmp; - sint8 ret = M2M_SUCCESS; - uint8 u8WifiMode = M2M_WIFI_MODE_NORMAL; - - if(param == NULL) { - ret = M2M_ERR_FAIL; - goto _EXIT0; - } - - gpfAppWifiCb = param->pfAppWifiCb; - -#ifdef ETH_MODE - gpfAppEthCb = param->strEthInitParam.pfAppEthCb; - gau8ethRcvBuf = param->strEthInitParam.au8ethRcvBuf; - gu16ethRcvBufSize = param->strEthInitParam.u16ethRcvBufSize; - u8WifiMode = param->strEthInitParam.u8EthernetEnable; -#endif /* ETH_MODE */ - -#ifdef CONF_MGMT - gpfAppMonCb = param->pfAppMonCb; -#endif - gu8scanInProgress = 0; - /* Apply device specific initialization. */ - ret = nm_drv_init(&u8WifiMode); - if(ret != M2M_SUCCESS) goto _EXIT0; - /* Initialize host interface module */ - ret = hif_init(NULL); - if(ret != M2M_SUCCESS) goto _EXIT1; - - hif_register_cb(M2M_REQ_GROUP_WIFI,m2m_wifi_cb); - - ret = nm_get_firmware_full_info(&strtmp); - -#ifdef ARDUINO - if (M2M_ERR_FAIL == ret) - { - // for compatibility with firmware version 19.3.0 - ret = nm_get_firmware_info(&strtmp); - } -#endif - M2M_INFO("Firmware ver : %u.%u.%u Svnrev %u\n", strtmp.u8FirmwareMajor, strtmp.u8FirmwareMinor, strtmp.u8FirmwarePatch,strtmp.u16FirmwareSvnNum); - M2M_INFO("Firmware Build %s Time %s\n",strtmp.BuildDate,strtmp.BuildTime); - M2M_INFO("Firmware Min driver ver : %u.%u.%u\n", strtmp.u8DriverMajor, strtmp.u8DriverMinor, strtmp.u8DriverPatch); - M2M_INFO("Driver ver: %u.%u.%u\n", M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); - M2M_INFO("Driver built at %s\t%s\n",__DATE__,__TIME__); - if(M2M_ERR_FW_VER_MISMATCH == ret) - { - M2M_ERR("Mismatch Firmawre Version\n"); - } - - goto _EXIT0; - -_EXIT1: - nm_drv_deinit(NULL); -_EXIT0: - return ret; -} - -sint8 m2m_wifi_deinit(void * arg) -{ -#ifdef ARDUINO - (void)arg; // Silence "unused" warning -#endif - hif_deinit(NULL); - - nm_drv_deinit(NULL); - - return M2M_SUCCESS; -} - - -#ifdef ARDUINO -#include "socket/include/socket_buffer.h" -extern tstrSocketBuffer gastrSocketBuffer[]; -#endif - -sint8 m2m_wifi_handle_events(void * arg) -{ -#ifdef ARDUINO - (void)arg; // Silence "unused" warning - - uint8 i; - - /* Arduino API LIMITATION: */ - /* To be compliant with the standard Arduino WiFi API socket must be buffered. */ - /* WiFi101 shield does not have this ability and automatically pushes incoming */ - /* data to the Arduino MCU. Function m2m_wifi_handle_events() is taking care of */ - /* this transfer. Hence by ensuring that all the MCU socket buffers are available */ - /* we can perform the transfer. */ - /* However, if one socket buffer is full, we have to delay this transfer by */ - /* returning an error value, as we have no way of knowing which socket is about */ - /* to be used. */ - /* Consequently, the Arduino sketch must NOT block on reading only one socket if */ - /* several sockets are to be used. Instead, application must carefully read for */ - /* all sockets, anytime. */ - for (i = 0; i < MAX_SOCKET; ++i) { - if (gastrSocketBuffer[i].flag && (*(gastrSocketBuffer[i].flag) & SOCKET_BUFFER_FLAG_FULL)) { - return M2M_ERR_FAIL; - } - } -#endif - return hif_handle_isr(); -} - -sint8 m2m_wifi_default_connect(void) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DEFAULT_CONNECT, NULL, 0,NULL, 0,0); -} - -sint8 m2m_wifi_connect(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch) -{ - return m2m_wifi_connect_sc(pcSsid, u8SsidLen, u8SecType, pvAuthInfo, u16Ch,0); -} -sint8 m2m_wifi_connect_sc(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch, uint8 u8NoSaveCred) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mWifiConnect strConnect; - tstrM2MWifiSecInfo *pstrAuthInfo; - - if(u8SecType != M2M_WIFI_SEC_OPEN) - { - if(pvAuthInfo == NULL) - { - M2M_ERR("Key is not valid\n"); - ret = M2M_ERR_FAIL; - goto ERR1; - } - if((u8SecType == M2M_WIFI_SEC_WPA_PSK) && (m2m_strlen(pvAuthInfo) == (M2M_MAX_PSK_LEN-1))) - { - uint8 i = 0; - uint8* pu8Psk = (uint8*)pvAuthInfo; - while(i < (M2M_MAX_PSK_LEN-1)) - { - if(pu8Psk[i]<'0' || (pu8Psk[i]>'9' && pu8Psk[i] < 'A')|| (pu8Psk[i]>'F' && pu8Psk[i] < 'a') || pu8Psk[i] > 'f') - { - M2M_ERR("Invalid Key\n"); - ret = M2M_ERR_FAIL; - goto ERR1; - } - i++; - } - } - } - if((u8SsidLen<=0)||(u8SsidLen>=M2M_MAX_SSID_LEN)) - { - M2M_ERR("SSID LEN INVALID\n"); - ret = M2M_ERR_FAIL; - goto ERR1; - } - - if(u16Ch < M2M_WIFI_CH_1|| u16Ch > M2M_WIFI_CH_14) - { - if(u16Ch!=M2M_WIFI_CH_ALL) - { - M2M_ERR("CH INVALID\n"); - ret = M2M_ERR_FAIL; - goto ERR1; - } - } - - - m2m_memcpy(strConnect.au8SSID, (uint8*)pcSsid, u8SsidLen); - strConnect.au8SSID[u8SsidLen] = 0; - strConnect.u16Ch = NM_BSP_B_L_16(u16Ch); - /* Credentials will be Not be saved if u8NoSaveCred is set */ - strConnect.u8NoSaveCred = u8NoSaveCred ? 1:0; - pstrAuthInfo = &strConnect.strSec; - pstrAuthInfo->u8SecType = u8SecType; - - if(u8SecType == M2M_WIFI_SEC_WEP) - { - tstrM2mWifiWepParams * pstrWepParams = (tstrM2mWifiWepParams*)pvAuthInfo; - tstrM2mWifiWepParams *pstrWep = &pstrAuthInfo->uniAuth.strWepInfo; -#ifdef ARDUINO - pstrWep->u8KeyIndx =pstrWepParams->u8KeyIndx; -#else - pstrWep->u8KeyIndx =pstrWepParams->u8KeyIndx-1; -#endif - - if(pstrWep->u8KeyIndx >= WEP_KEY_MAX_INDEX) - { - M2M_ERR("Invalid Wep key index %d\n", pstrWep->u8KeyIndx); - ret = M2M_ERR_FAIL; - goto ERR1; - } -#ifdef ARDUINO - pstrWep->u8KeySz = pstrWepParams->u8KeySz; -#else - pstrWep->u8KeySz = pstrWepParams->u8KeySz-1; -#endif - if ((pstrWep->u8KeySz != WEP_40_KEY_STRING_SIZE)&& (pstrWep->u8KeySz != WEP_104_KEY_STRING_SIZE)) - { - M2M_ERR("Invalid Wep key length %d\n", pstrWep->u8KeySz); - ret = M2M_ERR_FAIL; - goto ERR1; - } - m2m_memcpy((uint8*)pstrWep->au8WepKey,(uint8*)pstrWepParams->au8WepKey, pstrWepParams->u8KeySz); - pstrWep->au8WepKey[pstrWepParams->u8KeySz] = 0; - - } - - - else if(u8SecType == M2M_WIFI_SEC_WPA_PSK) - { - uint16 u16KeyLen = m2m_strlen((uint8*)pvAuthInfo); - if((u16KeyLen <= 0)||(u16KeyLen >= M2M_MAX_PSK_LEN)) - { - M2M_ERR("Incorrect PSK key length\n"); - ret = M2M_ERR_FAIL; - goto ERR1; - } - m2m_memcpy(pstrAuthInfo->uniAuth.au8PSK, (uint8*)pvAuthInfo, u16KeyLen + 1); - } - else if(u8SecType == M2M_WIFI_SEC_802_1X) - { - m2m_memcpy((uint8*)&pstrAuthInfo->uniAuth.strCred1x, (uint8*)pvAuthInfo, sizeof(tstr1xAuthCredentials)); - } - else if(u8SecType == M2M_WIFI_SEC_OPEN) - { - - } - else - { - M2M_ERR("undefined sec type\n"); - ret = M2M_ERR_FAIL; - goto ERR1; - } - - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CONNECT, (uint8*)&strConnect, sizeof(tstrM2mWifiConnect),NULL, 0,0); - -ERR1: - return ret; -} - -sint8 m2m_wifi_disconnect(void) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISCONNECT, NULL, 0, NULL, 0,0); -} -sint8 m2m_wifi_set_mac_address(uint8 au8MacAddress[6]) -{ - tstrM2mSetMacAddress strTmp; - m2m_memcpy((uint8*) strTmp.au8Mac, (uint8*) au8MacAddress, 6); - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_MAC_ADDRESS, - (uint8*) &strTmp, sizeof(tstrM2mSetMacAddress), NULL, 0,0); -} - -sint8 m2m_wifi_set_static_ip(tstrM2MIPConfig * pstrStaticIPConf) -{ - pstrStaticIPConf->u32DNS = NM_BSP_B_L_32(pstrStaticIPConf->u32DNS); - pstrStaticIPConf->u32Gateway = NM_BSP_B_L_32(pstrStaticIPConf->u32Gateway); - pstrStaticIPConf->u32StaticIP = NM_BSP_B_L_32( - pstrStaticIPConf->u32StaticIP); - pstrStaticIPConf->u32SubnetMask = NM_BSP_B_L_32( - pstrStaticIPConf->u32SubnetMask); - return hif_send(M2M_REQ_GROUP_IP, M2M_IP_REQ_STATIC_IP_CONF, - (uint8*) pstrStaticIPConf, sizeof(tstrM2MIPConfig), NULL, 0,0); -} - -sint8 m2m_wifi_request_dhcp_client(void) -{ - /*legacy API should be removed */ - return 0; -} -sint8 m2m_wifi_request_dhcp_server(uint8* addr) -{ -#ifdef ARDUINO - (void)addr; // Silence "unused" warning -#endif - /*legacy API should be removed */ - return 0; -} -/*! -@fn NMI_API sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt * pstrM2mLsnInt); -@brief Set the Wi-Fi listen interval for power save operation. It is represented in units - of AP Beacon periods. -@param [in] pstrM2mLsnInt - Structure holding the listen interval configurations. -@return The function SHALL return 0 for success and a negative value otherwise. -@sa tstrM2mLsnInt , m2m_wifi_set_sleep_mode -@pre m2m_wifi_set_sleep_mode shall be called first -@warning The Function called once after initialization. -*/ -sint8 m2m_wifi_enable_dhcp(uint8 u8DhcpEn ) -{ - - uint8 u8Req; - u8Req = u8DhcpEn ? M2M_IP_REQ_ENABLE_DHCP : M2M_IP_REQ_DISABLE_DHCP; - return hif_send(M2M_REQ_GROUP_IP, u8Req, NULL, 0, NULL, 0, 0); - - -} - -sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt* pstrM2mLsnInt) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_LSN_INT, (uint8*)pstrM2mLsnInt, sizeof(tstrM2mLsnInt), NULL, 0, 0); -} - -sint8 m2m_wifi_set_cust_InfoElement(uint8* pau8M2mCustInfoElement) -{ - - sint8 ret = M2M_ERR_FAIL; - if(pau8M2mCustInfoElement != NULL) - { - if((pau8M2mCustInfoElement[0] + 1) < M2M_CUST_IE_LEN_MAX) - { - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CUST_INFO_ELEMENT|M2M_REQ_DATA_PKT, (uint8*)pau8M2mCustInfoElement, pau8M2mCustInfoElement[0]+1, NULL, 0, 0); - } - } - return ret; -} - -sint8 m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption) -{ - sint8 s8Ret = M2M_ERR_FAIL; - if(m2m_validate_scan_options (ptstrM2MScanOption) == M2M_SUCCESS) - { - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_SCAN_OPTION, (uint8*)ptstrM2MScanOption, sizeof(tstrM2MScanOption),NULL, 0,0); - } - return s8Ret; -} -sint8 m2m_wifi_set_scan_region(uint16 ScanRegion) -{ - sint8 s8Ret = M2M_ERR_FAIL; - tstrM2MScanRegion strScanRegion; - strScanRegion.u16ScanRegion = ScanRegion; - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_SCAN_REGION, (uint8*)&strScanRegion, sizeof(tstrM2MScanRegion),NULL, 0,0); - return s8Ret; -} -sint8 m2m_wifi_request_scan(uint8 ch) -{ - sint8 s8Ret = M2M_SUCCESS; - - if(!gu8scanInProgress) - { - if(((ch >= M2M_WIFI_CH_1) && (ch <= M2M_WIFI_CH_14)) || (ch == M2M_WIFI_CH_ALL)) - { - tstrM2MScan strtmp; - strtmp.u8ChNum = ch; - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SCAN, (uint8*)&strtmp, sizeof(tstrM2MScan),NULL, 0,0); - if(s8Ret == M2M_SUCCESS) - { - gu8scanInProgress = 1; - } - } - else - { - s8Ret = M2M_ERR_INVALID_ARG; - } - } - else - { - s8Ret = M2M_ERR_SCAN_IN_PROGRESS; - } - return s8Ret; -} - -sint8 m2m_wifi_request_scan_passive(uint8 ch, uint16 scan_time) -{ - sint8 s8Ret = M2M_SUCCESS; - - if(!gu8scanInProgress) - { - if(((ch >= M2M_WIFI_CH_1) && (ch <= M2M_WIFI_CH_14)) || (ch == M2M_WIFI_CH_ALL)) - { - tstrM2MScan strtmp; - strtmp.u8ChNum = ch; - - strtmp.u16PassiveScanTime = scan_time; - - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_PASSIVE_SCAN, (uint8*)&strtmp, sizeof(tstrM2MScan),NULL, 0,0); - if(s8Ret == M2M_SUCCESS) - { - gu8scanInProgress = 1; - } - } - else - { - s8Ret = M2M_ERR_INVALID_ARG; - } - } - else - { - s8Ret = M2M_ERR_SCAN_IN_PROGRESS; - } - return s8Ret; -} - -sint8 m2m_wifi_request_scan_ssid_list(uint8 ch,uint8 * u8Ssidlist) -{ - sint8 s8Ret = M2M_ERR_INVALID_ARG; - - if(!gu8scanInProgress) - { - if((((ch >= M2M_WIFI_CH_1) && (ch <= M2M_WIFI_CH_14)) || (ch == M2M_WIFI_CH_ALL))&&(u8Ssidlist != NULL)) - { - tstrM2MScan strtmp; - uint16 u16Lsize = 0; - uint8 u8Apnum = u8Ssidlist[u16Lsize]; - if(u8Apnum <= MAX_HIDDEN_SITES) - { - u16Lsize++; - while(u8Apnum) - { - if(u8Ssidlist[u16Lsize] >= M2M_MAX_SSID_LEN){ - goto EXIT; - }else { - u16Lsize += u8Ssidlist[u16Lsize] + 1; - u8Apnum--; - } - } - strtmp.u8ChNum = ch; - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SCAN_SSID_LIST|M2M_REQ_DATA_PKT, (uint8*)&strtmp, sizeof(tstrM2MScan),u8Ssidlist, u16Lsize,sizeof(tstrM2MScan)); - if(s8Ret == M2M_SUCCESS) - { - gu8scanInProgress = 1; - } - } - } - } - else - { - s8Ret = M2M_ERR_SCAN_IN_PROGRESS; - } -EXIT: - return s8Ret; -} -sint8 m2m_wifi_wps(uint8 u8TriggerType,const char *pcPinNumber) -{ - tstrM2MWPSConnect strtmp; - - /* Stop Scan if it is ongoing. - */ - gu8scanInProgress = 0; - strtmp.u8TriggerType = u8TriggerType; - /*If WPS is using PIN METHOD*/ - if (u8TriggerType == WPS_PIN_TRIGGER) - m2m_memcpy ((uint8*)strtmp.acPinNumber,(uint8*) pcPinNumber,8); - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_WPS, (uint8*)&strtmp,sizeof(tstrM2MWPSConnect), NULL, 0,0); -} -sint8 m2m_wifi_wps_disable(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_WPS, NULL,0, NULL, 0, 0); - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_req_client_ctrl(uint8 cmd); -@brief Send a command to the PS Client (An WINC1500 board running the ps_firmware), - if the PS client send any commands it will be received in wifi_cb M2M_WIFI_RESP_CLIENT_INFO -@param [in] cmd - Control command sent from PS Server to PS Client (command values defined by the application) -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. -@sa m2m_wifi_req_server_init, M2M_WIFI_RESP_CLIENT_INFO -@pre m2m_wifi_req_server_init should be called first -@warning -*/ -sint8 m2m_wifi_req_client_ctrl(uint8 u8Cmd) -{ - - sint8 ret = M2M_SUCCESS; -#ifdef _PS_SERVER_ - tstrM2Mservercmd strCmd; - strCmd.u8cmd = u8Cmd; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CLIENT_CTRL, (uint8*)&strCmd, sizeof(tstrM2Mservercmd), NULL, 0, 0); -#else -#ifdef ARDUINO - (void)u8Cmd; // Silence "unused" warning -#endif - M2M_ERR("_PS_SERVER_ is not defined\n"); -#endif - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_req_server_init(uint8 ch); -@brief Initialize the PS Server, The WINC1500 support Non secure communication with another WINC1500, - (SERVER/CLIENT) through one byte command (probe request and probe response) without any connection setup -@param [in] ch - Server listening channel -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise -@sa m2m_wifi_req_client_ctrl -@warning The server mode can't be used with any other modes (STA/P2P/AP) -*/ -sint8 m2m_wifi_req_server_init(uint8 ch) -{ - sint8 ret = M2M_SUCCESS; -#ifdef _PS_SERVER_ - tstrM2mServerInit strServer; - strServer.u8Channel = ch; - ret = hif_send(M2M_REQ_GROUP_WIFI,M2M_WIFI_REQ_SERVER_INIT, (uint8*)&strServer, sizeof(tstrM2mServerInit), NULL, 0, 0); -#else -#ifdef ARDUINO - (void)ch; // Silence "unused" warning -#endif - M2M_ERR("_PS_SERVER_ is not defined\n"); -#endif - return ret; -} -sint8 m2m_wifi_p2p(uint8 u8Channel) -{ - sint8 ret = M2M_SUCCESS; - if((u8Channel == M2M_WIFI_CH_1) || (u8Channel == M2M_WIFI_CH_6) || (u8Channel == M2M_WIFI_CH_11)) - { - tstrM2MP2PConnect strtmp; - strtmp.u8ListenChannel = u8Channel; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_P2P, (uint8*)&strtmp, sizeof(tstrM2MP2PConnect), NULL, 0,0); - } - else - { - M2M_ERR("Listen channel should only be M2M_WIFI_CH_1/6/11 \n"); - ret = M2M_ERR_FAIL; - } - return ret; -} -sint8 m2m_wifi_p2p_disconnect(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_P2P, NULL, 0, NULL, 0, 0); - return ret; -} -sint8 m2m_wifi_enable_ap(CONST tstrM2MAPConfig* pstrM2MAPConfig) -{ - sint8 ret = M2M_ERR_FAIL; - if(M2M_SUCCESS == m2m_validate_ap_parameters(pstrM2MAPConfig)) - { -#ifdef ARDUINO - extern uint32 nmdrv_firm_ver; - uint16 txSize = sizeof(tstrM2MAPConfig); - - if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 5, 0)) { - // for backwards compat with firmwware 19.4.x and older - // (listen channel is 0 based, there is no au8Key field) - ((tstrM2MAPConfig*)pstrM2MAPConfig)->u8ListenChannel--; - txSize -= sizeof(pstrM2MAPConfig->au8Key) + 1; - } - - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_AP, (uint8 *)pstrM2MAPConfig, txSize, NULL, 0, 0); -#else - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_AP, (uint8 *)pstrM2MAPConfig, sizeof(tstrM2MAPConfig), NULL, 0, 0); -#endif - } - return ret; -} - -sint8 m2m_wifi_set_gains(tstrM2mWifiGainsParams* pstrM2mGain) -{ - sint8 ret = M2M_ERR_FAIL; - if(pstrM2mGain != NULL) - { - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_GAINS, (uint8 *)pstrM2mGain, sizeof(tstrM2mWifiGainsParams), NULL, 0, 0); - } - return ret; -} -sint8 m2m_wifi_disable_ap(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_AP, NULL, 0, NULL, 0, 0); - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_req_curr_rssi(void); -@brief Request the current RSSI for the current connected AP, - the response received in wifi_cb M2M_WIFI_RESP_CURRENT_RSSI -@sa M2M_WIFI_RESP_CURRENT_RSSI -@return The function shall return M2M_SUCCESS for success and a negative value otherwise. -*/ -sint8 m2m_wifi_req_curr_rssi(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CURRENT_RSSI, NULL, 0, NULL,0, 0); - return ret; -} -sint8 m2m_wifi_send_ethernet_pkt(uint8* pu8Packet,uint16 u16PacketSize) -{ - sint8 s8Ret = -1; - if((pu8Packet != NULL)&&(u16PacketSize>0)) - { - tstrM2MWifiTxPacketInfo strTxPkt; - - strTxPkt.u16PacketSize = u16PacketSize; - strTxPkt.u16HeaderLength = M2M_ETHERNET_HDR_LEN; - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SEND_ETHERNET_PACKET | M2M_REQ_DATA_PKT, - (uint8*)&strTxPkt, sizeof(tstrM2MWifiTxPacketInfo), pu8Packet, u16PacketSize, M2M_ETHERNET_HDR_OFFSET - M2M_HIF_HDR_OFFSET); - } - return s8Ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); -@brief Request the MAC address stored on the OTP (one time programmable) memory of the device. - (the function is Blocking until response received) -@param [out] pu8MacAddr - Output MAC address buffer of 6 bytes size. Valid only if *pu8Valid=1. -@param [out] pu8IsValid - A output boolean value to indicate the validity of pu8MacAddr in OTP. - Output zero if the OTP memory is not programmed, non-zero otherwise. -@return The function shall return M2M_SUCCESS for success and a negative value otherwise. -@sa m2m_wifi_get_mac_address -@pre m2m_wifi_init required to call any WIFI/socket function -*/ -sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8* pu8IsValid) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_chip_wake(); - if(ret == M2M_SUCCESS) - { - ret = nmi_get_otp_mac_address(pu8MacAddr, pu8IsValid); - if(ret == M2M_SUCCESS) - { - ret = hif_chip_sleep(); - } - } - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr) -@brief Request the current MAC address of the device (the working mac address). - (the function is Blocking until response received) -@param [out] pu8MacAddr - Output MAC address buffer of 6 bytes size. -@return The function shall return M2M_SUCCESS for success and a negative value otherwise. -@sa m2m_wifi_get_otp_mac_address -@pre m2m_wifi_init required to call any WIFI/socket function -*/ -sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_chip_wake(); - if(ret == M2M_SUCCESS) - { - ret = nmi_get_mac_address(pu8MacAddr); - if(ret == M2M_SUCCESS) - { - ret = hif_chip_sleep(); - } - } - - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_req_scan_result(uint8 index); -@brief Reads the AP information from the Scan Result list with the given index, - the response received in wifi_cb M2M_WIFI_RESP_SCAN_RESULT, - the response pointer should be casted with tstrM2mWifiscanResult structure -@param [in] index - Index for the requested result, the index range start from 0 till number of AP's found -@sa tstrM2mWifiscanResult,m2m_wifi_get_num_ap_found,m2m_wifi_request_scan -@return The function shall return M2M_SUCCESE for success and a negative value otherwise -@pre m2m_wifi_request_scan need to be called first, then m2m_wifi_get_num_ap_found - to get the number of AP's found -@warning Function used only in STA mode only. the scan result updated only if scan request called, - else it will be cashed in firmware for the host scan request result, - which mean if large delay occur between the scan request and the scan result request, - the result will not be up-to-date -*/ - -sint8 m2m_wifi_req_scan_result(uint8 index) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mReqScanResult strReqScanRlt; - strReqScanRlt.u8Index = index; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SCAN_RESULT, (uint8*) &strReqScanRlt, sizeof(tstrM2mReqScanResult), NULL, 0, 0); - return ret; -} -/*! -@fn NMI_API uint8 m2m_wifi_get_num_ap_found(void); -@brief Reads the number of AP's found in the last Scan Request, - The function read the number of AP's from global variable which updated in the - wifi_cb in M2M_WIFI_RESP_SCAN_DONE. -@sa m2m_wifi_request_scan -@return Return the number of AP's found in the last Scan Request. -@pre m2m_wifi_request_scan need to be called first -@warning That function need to be called in the wifi_cb in M2M_WIFI_RESP_SCAN_DONE, - calling that function in any other place will return undefined/undated numbers. - Function used only in STA mode only. -*/ -uint8 m2m_wifi_get_num_ap_found(void) -{ - return gu8ChNum; -} -/*! -@fn NMI_API uint8 m2m_wifi_get_sleep_mode(void); -@brief Get the current Power save mode. -@return The current operating power saving mode. -@sa tenuPowerSaveModes , m2m_wifi_set_sleep_mode -*/ -uint8 m2m_wifi_get_sleep_mode(void) -{ - return hif_get_sleep_mode(); -} -/*! -@fn NMI_API sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn); -@brief Set the power saving mode for the WINC1500. -@param [in] PsTyp - Desired power saving mode. Supported types are defined in tenuPowerSaveModes. -@param [in] BcastEn - Broadcast reception enable flag. - If it is 1, the WINC1500 must be awake each DTIM Beacon for receiving Broadcast traffic. - If it is 0, the WINC1500 will not wakeup at the DTIM Beacon, but its wakeup depends only - on the the configured Listen Interval. -@return The function SHALL return 0 for success and a negative value otherwise. -@sa tenuPowerSaveModes -@warning The function called once after initialization. -*/ -sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mPsType strPs; - strPs.u8PsType = PsTyp; - strPs.u8BcastEn = BcastEn; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SLEEP, (uint8*) &strPs,sizeof(tstrM2mPsType), NULL, 0, 0); - M2M_INFO("POWER SAVE %d\n",PsTyp); - hif_set_sleep_mode(PsTyp); - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_request_sleep(void) -@brief Request from WINC1500 device to Sleep for specific time in the M2M_PS_MANUAL Power save mode (only). -@param [in] u32SlpReqTime - Request Sleep in ms -@return The function SHALL return M2M_SUCCESS for success and a negative value otherwise. -@sa tenuPowerSaveModes , m2m_wifi_set_sleep_mode -@warning the Function should be called in M2M_PS_MANUAL power save only -*/ -sint8 m2m_wifi_request_sleep(uint32 u32SlpReqTime) -{ - sint8 ret = M2M_SUCCESS; - uint8 psType; - psType = hif_get_sleep_mode(); - if(psType == M2M_PS_MANUAL) - { - tstrM2mSlpReqTime strPs; - strPs.u32SleepTime = u32SlpReqTime; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DOZE, (uint8*) &strPs,sizeof(tstrM2mSlpReqTime), NULL, 0, 0); - } - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength); -@brief Set the WINC1500 device name which is used as P2P device name. -@param [in] pu8DeviceName - Buffer holding the device name. -@param [in] u8DeviceNameLength - Length of the device name. -@return The function SHALL return M2M_SUCCESS for success and a negative value otherwise. -@warning The Function called once after initialization. -*/ -sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength) -{ - tstrM2MDeviceNameConfig strDeviceName; - if(u8DeviceNameLength >= M2M_DEVICE_NAME_MAX) - { - u8DeviceNameLength = M2M_DEVICE_NAME_MAX; - } - //pu8DeviceName[u8DeviceNameLength] = '\0'; - u8DeviceNameLength ++; - m2m_memcpy(strDeviceName.au8DeviceName, pu8DeviceName, u8DeviceNameLength); - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_DEVICE_NAME, - (uint8*)&strDeviceName, sizeof(tstrM2MDeviceNameConfig), NULL, 0,0); -} -sint8 m2m_wifi_get_firmware_version(tstrM2mRev *pstrRev) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_chip_wake(); - if(ret == M2M_SUCCESS) - { - ret = nm_get_firmware_full_info(pstrRev); - hif_chip_sleep(); - } - return ret; -} -#ifdef CONF_MGMT -sint8 m2m_wifi_enable_monitoring_mode(tstrM2MWifiMonitorModeCtrl *pstrMtrCtrl, uint8 *pu8PayloadBuffer, - uint16 u16BufferSize, uint16 u16DataOffset) -{ - sint8 s8Ret = -1; - if((pstrMtrCtrl->u8ChannelID >= M2M_WIFI_CH_1) && (pstrMtrCtrl->u8ChannelID <= M2M_WIFI_CH_14)) - { - gstrMgmtCtrl.pu8Buf = pu8PayloadBuffer; - gstrMgmtCtrl.u16Sz = u16BufferSize; - gstrMgmtCtrl.u16Offset = u16DataOffset; - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_MONITORING, - (uint8*)pstrMtrCtrl, sizeof(tstrM2MWifiMonitorModeCtrl), NULL, 0,0); - } - return s8Ret; -} - -sint8 m2m_wifi_disable_monitoring_mode(void) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_MONITORING, NULL, 0, NULL, 0,0); -} - -sint8 m2m_wifi_send_wlan_pkt(uint8 *pu8WlanPacket, uint16 u16WlanHeaderLength, uint16 u16WlanPktSize) -{ - sint8 s8Ret = -1; - if(pu8WlanPacket != NULL) - { - tstrM2MWifiTxPacketInfo strTxPkt; - - strTxPkt.u16PacketSize = u16WlanPktSize; - strTxPkt.u16HeaderLength = u16WlanHeaderLength; - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SEND_WIFI_PACKET | M2M_REQ_DATA_PKT, - (uint8*)&strTxPkt, sizeof(tstrM2MWifiTxPacketInfo), pu8WlanPacket, u16WlanPktSize, sizeof(tstrM2MWifiTxPacketInfo)); - } - return s8Ret; -} -#endif - -sint8 m2m_wifi_start_provision_mode(tstrM2MAPConfig *pstrAPConfig, char *pcHttpServerDomainName, uint8 bEnableHttpRedirect) -{ - sint8 s8Ret = M2M_ERR_FAIL; - - if((pstrAPConfig != NULL)) - { - tstrM2MProvisionModeConfig strProvConfig; - if(M2M_SUCCESS == m2m_validate_ap_parameters(pstrAPConfig)) - { - m2m_memcpy((uint8*)&strProvConfig.strApConfig, (uint8*)pstrAPConfig, sizeof(tstrM2MAPConfig)); - if((m2m_strlen((uint8 *)pcHttpServerDomainName) <= 0) || (NULL == pcHttpServerDomainName)) - { - M2M_ERR("INVALID DOMAIN NAME\n"); - goto ERR1; - } - m2m_memcpy((uint8*)strProvConfig.acHttpServerDomainName, (uint8*)pcHttpServerDomainName, 64); - strProvConfig.u8EnableRedirect = bEnableHttpRedirect; - - /* Stop Scan if it is ongoing. - */ - gu8scanInProgress = 0; -#ifdef ARDUINO - extern uint32 nmdrv_firm_ver; - uint16 txSize = sizeof(tstrM2MProvisionModeConfig); - - if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 5, 0)) { - // for backwards compat with firmwware 19.4.x and older - // (listen channel is 0 based, there is no au8Key field) - strProvConfig.strApConfig.u8ListenChannel--; - txSize -= sizeof(strProvConfig.strApConfig.au8Key) + 1; - m2m_memcpy((uint8*)&strProvConfig.strApConfig.au8Key[3], (uint8*)pcHttpServerDomainName, 64); - uint8* pu8EnableRedirect = (uint8*)strProvConfig.strApConfig.au8Key; - pu8EnableRedirect[3 + 64] = bEnableHttpRedirect; - } - - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_START_PROVISION_MODE | M2M_REQ_DATA_PKT, - (uint8*)&strProvConfig, txSize, NULL, 0, 0); -#else - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_START_PROVISION_MODE | M2M_REQ_DATA_PKT, - (uint8*)&strProvConfig, sizeof(tstrM2MProvisionModeConfig), NULL, 0, 0); -#endif - } - else - { - /*goto ERR1;*/ - } - } -ERR1: - return s8Ret; -} - -sint8 m2m_wifi_stop_provision_mode(void) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_STOP_PROVISION_MODE, NULL, 0, NULL, 0, 0); -} - -sint8 m2m_wifi_get_connection_info(void) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_GET_CONN_INFO, NULL, 0, NULL, 0, 0); -} - -sint8 m2m_wifi_set_sytem_time(uint32 u32UTCSeconds) -{ - /* - The firmware accepts timestamps relative to 1900 like NTP Timestamp. - */ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_SYS_TIME, (uint8*)&u32UTCSeconds, sizeof(tstrSystemTime), NULL, 0, 0); -} -/*! - * @fn NMI_API sint8 m2m_wifi_get_sytem_time(void); - * @see m2m_wifi_enable_sntp - tstrSystemTime - * @note get the system time from the sntp client - * using the API \ref m2m_wifi_get_sytem_time. - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -sint8 m2m_wifi_get_sytem_time(void) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_GET_SYS_TIME, NULL,0, NULL, 0, 0); -} - -sint8 m2m_wifi_enable_sntp(uint8 bEnable) -{ - uint8 u8Req; - - u8Req = bEnable ? M2M_WIFI_REQ_ENABLE_SNTP_CLIENT : M2M_WIFI_REQ_DISABLE_SNTP_CLIENT; - return hif_send(M2M_REQ_GROUP_WIFI, u8Req, NULL, 0, NULL, 0, 0); -} -/*! -@fn NMI_API sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode); -@brief Change the power profile mode -@param [in] u8PwrMode - Change the WINC power profile to different mode - PWR_LOW1/PWR_LOW2/PWR_HIGH/PWR_AUTO (tenuM2mPwrMode) -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. -@sa tenuM2mPwrMode -@pre m2m_wifi_init -@warning must be called after the initializations and before any connection request and can't be changed in run time, -*/ -sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mPwrMode strM2mPwrMode; - strM2mPwrMode.u8PwrMode = u8PwrMode; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_POWER_PROFILE, (uint8*)&strM2mPwrMode,sizeof(tstrM2mPwrMode), NULL, 0, 0); - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel); -@brief set the TX power tenuM2mTxPwrLevel -@param [in] u8TxPwrLevel - change the TX power tenuM2mTxPwrLevel -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. -@sa tenuM2mTxPwrLevel -@pre m2m_wifi_init -@warning -*/ -sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mTxPwrLevel strM2mTxPwrLevel; - strM2mTxPwrLevel.u8TxPwrLevel = u8TxPwrLevel; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_TX_POWER, (uint8*)&strM2mTxPwrLevel,sizeof(tstrM2mTxPwrLevel), NULL, 0, 0); - return ret; -} - -/*! -@fn NMI_API sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable); -@brief Enable or Disable logs in run time (Disable Firmware logs will - enhance the firmware start-up time and performance) -@param [in] u8Enable - Set 1 to enable the logs 0 for disable -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. -@sa __DISABLE_FIRMWARE_LOGS__ (build option to disable logs from initializations) -@pre m2m_wifi_init -@warning -*/ -sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mEnableLogs strM2mEnableLogs; - strM2mEnableLogs.u8Enable = u8Enable; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_ENABLE_LOGS, (uint8*)&strM2mEnableLogs,sizeof(tstrM2mEnableLogs), NULL, 0, 0); - return ret; -} - -/*! -@fn NMI_API sint8 m2m_wifi_set_battery_voltage(uint16 u16BattVoltx100); -@brief Enable or Disable logs in run time (Disable Firmware logs will - enhance the firmware start-up time and performance) -@param [in] u16BattVoltx100 - battery voltage multiplied by 100 -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. -@sa __DISABLE_FIRMWARE_LOGS__ (build option to disable logs from initializations) -@pre m2m_wifi_init -@warning -*/ -sint8 m2m_wifi_set_battery_voltage(uint16 u16BattVoltx100) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mBatteryVoltage strM2mBattVol = {0}; - strM2mBattVol.u16BattVolt = u16BattVoltx100; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_BATTERY_VOLTAGE, (uint8*)&strM2mBattVol,sizeof(tstrM2mBatteryVoltage), NULL, 0, 0); - return ret; -} -/*! -@fn sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PrngBuff,uint16 u16PrngSize) -@brief Get random bytes using the PRNG bytes. -@param [in] u16PrngSize - Size of the required random bytes to be generated. -@param [in] pu8PrngBuff - Pointer to user allocated buffer. -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. -*/ -sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PrngBuff,uint16 u16PrngSize) -{ - sint8 ret = M2M_ERR_FAIL; - tstrPrng strRng = {0}; - if((u16PrngSize < (M2M_BUFFER_MAX_SIZE - sizeof(tstrPrng)))&&(pu8PrngBuff != NULL)) - { - strRng.u16PrngSize = u16PrngSize; - strRng.pu8RngBuff = pu8PrngBuff; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_GET_PRNG|M2M_REQ_DATA_PKT,(uint8 *)&strRng, sizeof(tstrPrng),NULL,0, 0); - } - else - { - M2M_ERR("PRNG Buffer exceeded maximum size %d or NULL Buffer\n",u16PrngSize); - } - return ret; -} -#ifdef ETH_MODE -/*! -@fn \ - NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8* pu8MulticastMacAddress, uint8 u8AddRemove) - -@brief - Add MAC filter to receive Multicast packets. - -@param [in] pu8MulticastMacAddress - Pointer to the MAC address. -@param [in] u8AddRemove - Flag to Add/Remove MAC address. -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ - -NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8* pu8MulticastMacAddress, uint8 u8AddRemove) -{ - sint8 s8ret = M2M_ERR_FAIL; - tstrM2MMulticastMac strMulticastMac; - - if(pu8MulticastMacAddress != NULL ) - { - strMulticastMac.u8AddRemove = u8AddRemove; - m2m_memcpy(strMulticastMac.au8macaddress,pu8MulticastMacAddress,M2M_MAC_ADDRES_LEN); - M2M_DBG("mac multicast: %x:%x:%x:%x:%x:%x\r\n",strMulticastMac.au8macaddress[0],strMulticastMac.au8macaddress[1],strMulticastMac.au8macaddress[2],strMulticastMac.au8macaddress[3],strMulticastMac.au8macaddress[4],strMulticastMac.au8macaddress[5]); - s8ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_MAC_MCAST, (uint8 *)&strMulticastMac,sizeof(tstrM2MMulticastMac),NULL,0,0); - } - - return s8ret; - -} - -/*! -@fn \ - NMI_API sint8 m2m_wifi_set_receive_buffer(void* pvBuffer,uint16 u16BufferLen); - -@brief - set the ethernet receive buffer, should be called in the receive call back. - -@param [in] pvBuffer - Pointer to the ethernet receive buffer. -@param [in] u16BufferLen - Length of the buffer. - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_set_receive_buffer(void* pvBuffer,uint16 u16BufferLen) -{ - sint8 s8ret = M2M_SUCCESS; - if(pvBuffer != NULL) - { - gau8ethRcvBuf = pvBuffer; - gu16ethRcvBufSize= u16BufferLen; - } - else - { - s8ret = M2M_ERR_FAIL; - M2M_ERR("Buffer NULL pointer\r\n"); - } - return s8ret; -} -#endif /* ETH_MODE */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmasic.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmasic.c deleted file mode 100644 index 91c0e5a..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmasic.c +++ /dev/null @@ -1,688 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 ASIC specific internal APIs. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "common/include/nm_common.h" -#include "driver/source/nmbus.h" -#include "bsp/include/nm_bsp.h" -#include "driver/source/nmasic.h" -#include "driver/include/m2m_types.h" - -#define NMI_GLB_RESET_0 (NMI_PERIPH_REG_BASE + 0x400) -#define NMI_INTR_REG_BASE (NMI_PERIPH_REG_BASE + 0xa00) -#define NMI_PIN_MUX_0 (NMI_PERIPH_REG_BASE + 0x408) -#define NMI_INTR_ENABLE (NMI_INTR_REG_BASE) -#define GET_UINT32(X,Y) (X[0+Y] + ((uint32)X[1+Y]<<8) + ((uint32)X[2+Y]<<16) +((uint32)X[3+Y]<<24)) - -/*SPI and I2C only*/ -#define CORT_HOST_COMM (0x10) -#define HOST_CORT_COMM (0x0b) -#define WAKE_CLK_REG (0x1) -#define CLOCKS_EN_REG (0xf) - - - -#ifdef ARDUINO -#define TIMEOUT (2000) -#else -#define TIMEOUT (0xfffffffful) -#endif -#define WAKUP_TRAILS_TIMEOUT (4) - -sint8 chip_apply_conf(uint32 u32Conf) -{ - sint8 ret = M2M_SUCCESS; - uint32 val32 = u32Conf; - -#if (defined __ENABLE_PMU__) || (defined CONF_WINC_INT_PMU) - val32 |= rHAVE_USE_PMU_BIT; -#endif -#ifdef __ENABLE_SLEEP_CLK_SRC_RTC__ - val32 |= rHAVE_SLEEP_CLK_SRC_RTC_BIT; -#elif defined __ENABLE_SLEEP_CLK_SRC_XO__ - val32 |= rHAVE_SLEEP_CLK_SRC_XO_BIT; -#endif -#ifdef __ENABLE_EXT_PA_INV_TX_RX__ - val32 |= rHAVE_EXT_PA_INV_TX_RX; -#endif -#ifdef __ENABLE_LEGACY_RF_SETTINGS__ - val32 |= rHAVE_LEGACY_RF_SETTINGS; -#endif -#ifdef __DISABLE_FIRMWARE_LOGS__ - val32 |= rHAVE_LOGS_DISABLED_BIT; -#endif - - val32 |= rHAVE_RESERVED1_BIT; - do { - nm_write_reg(rNMI_GP_REG_1, val32); - if(val32 != 0) { - uint32 reg = 0; - ret = nm_read_reg_with_ret(rNMI_GP_REG_1, ®); - if(ret == M2M_SUCCESS) { - if(reg == val32) - break; - } - } else { - break; - } - } while(1); - - return M2M_SUCCESS; -} -void chip_idle(void) -{ - uint32 reg = 0; - nm_read_reg_with_ret(WAKE_CLK_REG, ®); - if(reg & NBIT1) - { - reg &=~ NBIT1; - nm_write_reg(WAKE_CLK_REG, reg); - } -} - -sint8 enable_interrupts(void) -{ - uint32 reg = 0; - sint8 ret = M2M_SUCCESS; - /** - interrupt pin mux select - **/ - ret = nm_read_reg_with_ret(NMI_PIN_MUX_0, ®); - if (M2M_SUCCESS != ret) goto ERR1; - - reg |= ((uint32) 1 << 8); - ret = nm_write_reg(NMI_PIN_MUX_0, reg); - if (M2M_SUCCESS != ret) goto ERR1; - - /** - interrupt enable - **/ - ret = nm_read_reg_with_ret(NMI_INTR_ENABLE, ®); - if (M2M_SUCCESS != ret) goto ERR1; - - reg |= ((uint32) 1 << 16); - ret = nm_write_reg(NMI_INTR_ENABLE, reg); - if (M2M_SUCCESS != ret) goto ERR1; -ERR1: - return ret; -} - -sint8 cpu_start(void) { - uint32 reg = 0; - sint8 ret; - - /** - reset regs - */ - ret = nm_write_reg(BOOTROM_REG,0); - ret += nm_write_reg(NMI_STATE_REG,0); - ret += nm_write_reg(NMI_REV_REG,0); - /** - Go... - **/ - ret += nm_read_reg_with_ret(0x1118, ®); - reg |= (1 << 0); - ret += nm_write_reg(0x1118, reg); - ret += nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); - if ((reg & (1ul << 10)) == (1ul << 10)) { - reg &= ~(1ul << 10); - ret += nm_write_reg(NMI_GLB_RESET_0, reg); - } - reg |= (1ul << 10); - ret += nm_write_reg(NMI_GLB_RESET_0, reg); - nm_bsp_sleep(1); - return ret; -} - -uint32 nmi_get_chipid(void) -{ - static uint32 chipid = 0; - - if (chipid == 0) { - uint32 rfrevid; - - if((nm_read_reg_with_ret(0x1000, &chipid)) != M2M_SUCCESS) { - chipid = 0; - return 0; - } - //if((ret = nm_read_reg_with_ret(0x11fc, &revid)) != M2M_SUCCESS) { - // return 0; - //} - if((nm_read_reg_with_ret(0x13f4, &rfrevid)) != M2M_SUCCESS) { - chipid = 0; - return 0; - } - - if (chipid == 0x1002a0) { - if (rfrevid == 0x1) { /* 1002A0 */ - } else /* if (rfrevid == 0x2) */ { /* 1002A1 */ - chipid = 0x1002a1; - } - } else if(chipid == 0x1002b0) { - if(rfrevid == 3) { /* 1002B0 */ - } else if(rfrevid == 4) { /* 1002B1 */ - chipid = 0x1002b1; - } else /* if(rfrevid == 5) */ { /* 1002B2 */ - chipid = 0x1002b2; - } - }else if(chipid == 0x1000F0) { - if((nm_read_reg_with_ret(0x3B0000, &chipid)) != M2M_SUCCESS) { - chipid = 0; - return 0; - } - }else { - - } -//#define PROBE_FLASH -#ifdef PROBE_FLASH - if(chipid) { - UWORD32 flashid; - - flashid = probe_spi_flash(); - if(flashid == 0x1230ef) { - chipid &= ~(0x0f0000); - chipid |= 0x050000; - } - if(flashid == 0xc21320c2) { - chipid &= ~(0x0f0000); - chipid |= 0x050000; - } - } -#else - /*M2M is by default have SPI flash*/ - chipid &= ~(0x0f0000); - chipid |= 0x050000; -#endif /* PROBE_FLASH */ - } - return chipid; -} - -uint32 nmi_get_rfrevid(void) -{ - uint32 rfrevid; - if((nm_read_reg_with_ret(0x13f4, &rfrevid)) != M2M_SUCCESS) { - rfrevid = 0; - return 0; - } - return rfrevid; -} - -void restore_pmu_settings_after_global_reset(void) -{ - /* - * Must restore PMU register value after - * global reset if PMU toggle is done at - * least once since the last hard reset. - */ - if(REV(nmi_get_chipid()) >= REV_2B0) { - nm_write_reg(0x1e48, 0xb78469ce); - } -} - -void nmi_update_pll(void) -{ - uint32 pll; - - pll = nm_read_reg(0x1428); - pll &= ~0x1ul; - nm_write_reg(0x1428, pll); - pll |= 0x1ul; - nm_write_reg(0x1428, pll); - -} -void nmi_set_sys_clk_src_to_xo(void) -{ - uint32 val32; - - /* Switch system clock source to XO. This will take effect after nmi_update_pll(). */ - val32 = nm_read_reg(0x141c); - val32 |= (1 << 2); - nm_write_reg(0x141c, val32); - - /* Do PLL update */ - nmi_update_pll(); -} -sint8 chip_sleep(void) -{ - uint32 reg; - sint8 ret = M2M_SUCCESS; - - while(1) - { - ret = nm_read_reg_with_ret(CORT_HOST_COMM,®); - if(ret != M2M_SUCCESS) goto ERR1; - if((reg & NBIT0) == 0) break; - } - - /* Clear bit 1 */ - ret = nm_read_reg_with_ret(WAKE_CLK_REG, ®); - if(ret != M2M_SUCCESS)goto ERR1; - if(reg & NBIT1) - { - reg &=~NBIT1; - ret = nm_write_reg(WAKE_CLK_REG, reg); - if(ret != M2M_SUCCESS)goto ERR1; - } - - ret = nm_read_reg_with_ret(HOST_CORT_COMM, ®); - if(ret != M2M_SUCCESS)goto ERR1; - if(reg & NBIT0) - { - reg &= ~NBIT0; - ret = nm_write_reg(HOST_CORT_COMM, reg); - if(ret != M2M_SUCCESS)goto ERR1; - } - -ERR1: - return ret; -} -sint8 chip_wake(void) -{ - sint8 ret = M2M_SUCCESS; - uint32 reg = 0, clk_status_reg = 0,trials = 0; - - ret = nm_read_reg_with_ret(HOST_CORT_COMM, ®); - if(ret != M2M_SUCCESS)goto _WAKE_EXIT; - - if(!(reg & NBIT0)) - { - /*USE bit 0 to indicate host wakeup*/ - ret = nm_write_reg(HOST_CORT_COMM, reg|NBIT0); - if(ret != M2M_SUCCESS)goto _WAKE_EXIT; - } - - ret = nm_read_reg_with_ret(WAKE_CLK_REG, ®); - if(ret != M2M_SUCCESS)goto _WAKE_EXIT; - /* Set bit 1 */ - if(!(reg & NBIT1)) - { - ret = nm_write_reg(WAKE_CLK_REG, reg | NBIT1); - if(ret != M2M_SUCCESS) goto _WAKE_EXIT; - } - - do - { - ret = nm_read_reg_with_ret(CLOCKS_EN_REG, &clk_status_reg); - if(ret != M2M_SUCCESS) { - M2M_ERR("Bus error (5).%d %lx\n",ret,clk_status_reg); - goto _WAKE_EXIT; - } - if(clk_status_reg & NBIT2) { - break; - } - nm_bsp_sleep(2); - trials++; - if(trials > WAKUP_TRAILS_TIMEOUT) - { - M2M_ERR("Failed to wakup the chip\n"); - ret = M2M_ERR_TIME_OUT; - goto _WAKE_EXIT; - } - }while(1); - - /*workaround sometimes spi fail to read clock regs after reading/writing clockless registers*/ - nm_bus_reset(); - -_WAKE_EXIT: - return ret; -} -sint8 cpu_halt(void) -{ - sint8 ret; - uint32 reg = 0; - ret = nm_read_reg_with_ret(0x1118, ®); - reg |= (1 << 0); - ret += nm_write_reg(0x1118, reg); - ret += nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); - if ((reg & (1ul << 10)) == (1ul << 10)) { - reg &= ~(1ul << 10); - ret += nm_write_reg(NMI_GLB_RESET_0, reg); - ret += nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); - } - return ret; -} -sint8 chip_reset_and_cpu_halt(void) -{ - sint8 ret = M2M_SUCCESS; - - /*Wakeup needed only for I2C interface*/ - ret = chip_wake(); - if(ret != M2M_SUCCESS) goto ERR1; - /*Reset and CPU halt need for no wait board only*/ - ret = chip_reset(); - if(ret != M2M_SUCCESS) goto ERR1; - ret = cpu_halt(); - if(ret != M2M_SUCCESS) goto ERR1; -ERR1: - return ret; -} -sint8 chip_reset(void) -{ - sint8 ret = M2M_SUCCESS; - ret = nm_write_reg(NMI_GLB_RESET_0, 0); - nm_bsp_sleep(50); - return ret; -} - -sint8 wait_for_bootrom(uint8 arg) -{ - sint8 ret = M2M_SUCCESS; - uint32 reg = 0, cnt = 0; - uint32 u32GpReg1 = 0; - uint32 u32DriverVerInfo = M2M_MAKE_VERSION_INFO(M2M_RELEASE_VERSION_MAJOR_NO,\ - M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO,\ - M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO,\ - M2M_RELEASE_VERSION_PATCH_NO); - - - reg = 0; - while(1) { - reg = nm_read_reg(0x1014); /* wait for efuse loading done */ - if (reg & 0x80000000) { - break; - } - nm_bsp_sleep(1); /* TODO: Why bus error if this delay is not here. */ - } - reg = nm_read_reg(M2M_WAIT_FOR_HOST_REG); - reg &= 0x1; - - /* check if waiting for the host will be skipped or not */ - if(reg == 0) - { - reg = 0; - while(reg != M2M_FINISH_BOOT_ROM) - { - nm_bsp_sleep(1); - reg = nm_read_reg(BOOTROM_REG); - - if(++cnt > TIMEOUT) - { - M2M_DBG("failed to load firmware from flash.\n"); - ret = M2M_ERR_INIT; - goto ERR2; - } - } - } - - if(M2M_WIFI_MODE_ATE_HIGH == arg) { - nm_write_reg(NMI_REV_REG, M2M_ATE_FW_START_VALUE); - nm_write_reg(NMI_STATE_REG, NBIT20); - }else if(M2M_WIFI_MODE_ATE_LOW == arg) { - nm_write_reg(NMI_REV_REG, M2M_ATE_FW_START_VALUE); - nm_write_reg(NMI_STATE_REG, 0); - }else if(M2M_WIFI_MODE_ETHERNET == arg){ - u32GpReg1 = rHAVE_ETHERNET_MODE_BIT; - nm_write_reg(NMI_STATE_REG, u32DriverVerInfo); - } else { - /*bypass this step*/ - nm_write_reg(NMI_STATE_REG, u32DriverVerInfo); - } - - if(REV(nmi_get_chipid()) >= REV_3A0){ - chip_apply_conf(u32GpReg1 | rHAVE_USE_PMU_BIT); - } else { - chip_apply_conf(u32GpReg1); - } - M2M_INFO("DriverVerInfo: 0x%08lx\n",u32DriverVerInfo); - - nm_write_reg(BOOTROM_REG,M2M_START_FIRMWARE); - -#ifdef __ROM_TEST__ - rom_test(); -#endif /* __ROM_TEST__ */ - -ERR2: - return ret; -} - -sint8 wait_for_firmware_start(uint8 arg) -{ - sint8 ret = M2M_SUCCESS; - uint32 reg = 0, cnt = 0; - uint32 u32Timeout = TIMEOUT; - volatile uint32 regAddress = NMI_STATE_REG; - volatile uint32 checkValue = M2M_FINISH_INIT_STATE; - - if((M2M_WIFI_MODE_ATE_HIGH == arg)||(M2M_WIFI_MODE_ATE_LOW == arg)) { - regAddress = NMI_REV_REG; - checkValue = M2M_ATE_FW_IS_UP_VALUE; - } else { - /*bypass this step*/ - } - - - while (checkValue != reg) - { - nm_bsp_sleep(2); /* TODO: Why bus error if this delay is not here. */ - M2M_DBG("%x %x %x\n",(unsigned int)nm_read_reg(0x108c),(unsigned int)nm_read_reg(0x108c),(unsigned int)nm_read_reg(0x14A0)); - reg = nm_read_reg(regAddress); - if(++cnt >= u32Timeout) - { - M2M_DBG("Time out for wait firmware Run\n"); - ret = M2M_ERR_INIT; - goto ERR; - } - } - if(M2M_FINISH_INIT_STATE == checkValue) - { - nm_write_reg(NMI_STATE_REG, 0); - } -ERR: - return ret; -} - -sint8 chip_deinit(void) -{ - uint32 reg = 0; - sint8 ret; - - /** - stop the firmware, need a re-download - **/ - ret = nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); - if (ret != M2M_SUCCESS) { - M2M_ERR("failed to de-initialize\n"); - goto ERR1; - } - reg &= ~(1 << 10); - ret = nm_write_reg(NMI_GLB_RESET_0, reg); - if (ret != M2M_SUCCESS) { - M2M_ERR("failed to de-initialize\n"); - goto ERR1; - } - -ERR1: - return ret; -} - -#ifdef CONF_PERIPH - -sint8 set_gpio_dir(uint8 gpio, uint8 dir) -{ - uint32 val32; - sint8 ret; - - ret = nm_read_reg_with_ret(0x20108, &val32); - if(ret != M2M_SUCCESS) goto _EXIT; - - if(dir) { - val32 |= (1ul << gpio); - } else { - val32 &= ~(1ul << gpio); - } - - ret = nm_write_reg(0x20108, val32); - -_EXIT: - return ret; -} -sint8 set_gpio_val(uint8 gpio, uint8 val) -{ - uint32 val32; - sint8 ret; - - ret = nm_read_reg_with_ret(0x20100, &val32); - if(ret != M2M_SUCCESS) goto _EXIT; - - if(val) { - val32 |= (1ul << gpio); - } else { - val32 &= ~(1ul << gpio); - } - - ret = nm_write_reg(0x20100, val32); - -_EXIT: - return ret; -} - -sint8 get_gpio_val(uint8 gpio, uint8* val) -{ - uint32 val32; - sint8 ret; - - ret = nm_read_reg_with_ret(0x20104, &val32); - if(ret != M2M_SUCCESS) goto _EXIT; - - *val = (uint8)((val32 >> gpio) & 0x01); - -_EXIT: - return ret; -} - -sint8 pullup_ctrl(uint32 pinmask, uint8 enable) -{ - sint8 s8Ret; - uint32 val32; - s8Ret = nm_read_reg_with_ret(0x142c, &val32); - if(s8Ret != M2M_SUCCESS) { - M2M_ERR("[pullup_ctrl]: failed to read\n"); - goto _EXIT; - } - if(enable) { - val32 &= ~pinmask; - } else { - val32 |= pinmask; - } - s8Ret = nm_write_reg(0x142c, val32); - if(s8Ret != M2M_SUCCESS) { - M2M_ERR("[pullup_ctrl]: failed to write\n"); - goto _EXIT; - } -_EXIT: - return s8Ret; -} -#endif /* CONF_PERIPH */ - -sint8 nmi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid) -{ - sint8 ret; - uint32 u32RegValue; - uint8 mac[6]; - tstrGpRegs strgp = {0}; - - ret = nm_read_reg_with_ret(rNMI_GP_REG_2, &u32RegValue); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; -#ifdef ARDUINO - if (u32RegValue) { - ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; - u32RegValue = strgp.u32Mac_efuse_mib; - } else { - // firmware version 19.3.0 - ret = nm_read_reg_with_ret(rNMI_GP_REG_0, &u32RegValue); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; - } -#else - ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; - u32RegValue = strgp.u32Mac_efuse_mib; -#endif - if(!EFUSED_MAC(u32RegValue)) { - M2M_DBG("Default MAC\n"); - m2m_memset(pu8MacAddr, 0, 6); - goto _EXIT_ERR; - } - - M2M_DBG("OTP MAC\n"); - u32RegValue >>=16; - ret = nm_read_block(u32RegValue|0x30000, mac, 6); - m2m_memcpy(pu8MacAddr,mac,6); - if(pu8IsValid) *pu8IsValid = 1; - return ret; - -_EXIT_ERR: - if(pu8IsValid) *pu8IsValid = 0; - return ret; -} - -sint8 nmi_get_mac_address(uint8 *pu8MacAddr) -{ - sint8 ret; - uint32 u32RegValue; - uint8 mac[6]; - tstrGpRegs strgp = {0}; - - ret = nm_read_reg_with_ret(rNMI_GP_REG_2, &u32RegValue); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; -#ifdef ARDUINO - if (u32RegValue) { - ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; - u32RegValue = strgp.u32Mac_efuse_mib; - } else { - // firmware version 19.3.0 - ret = nm_read_reg_with_ret(rNMI_GP_REG_0, &u32RegValue); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; - } -#else - ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; - u32RegValue = strgp.u32Mac_efuse_mib; -#endif - u32RegValue &=0x0000ffff; - ret = nm_read_block(u32RegValue|0x30000, mac, 6); - m2m_memcpy(pu8MacAddr, mac, 6); - - return ret; - -_EXIT_ERR: - return ret; -} diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmasic.h b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmasic.h deleted file mode 100644 index 84a395b..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmasic.h +++ /dev/null @@ -1,215 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 ASIC specific internal APIs. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -#ifndef _NMASIC_H_ -#define _NMASIC_H_ - -#include "common/include/nm_common.h" - -#define NMI_PERIPH_REG_BASE 0x1000 -#define NMI_CHIPID (NMI_PERIPH_REG_BASE) -#define rNMI_GP_REG_0 (0x149c) -#define rNMI_GP_REG_1 (0x14A0) -#define rNMI_GP_REG_2 (0xc0008) -#define rNMI_GLB_RESET (0x1400) -#define rNMI_BOOT_RESET_MUX (0x1118) -#define NMI_STATE_REG (0x108c) -#define BOOTROM_REG (0xc000c) -#define NMI_REV_REG (0x207ac) /*Also, Used to load ATE firmware from SPI Flash and to ensure that it is running too*/ -#define NMI_REV_REG_ATE (0x1048) /*Revision info register in case of ATE FW*/ -#define M2M_WAIT_FOR_HOST_REG (0x207bc) -#define M2M_FINISH_INIT_STATE 0x02532636UL -#define M2M_FINISH_BOOT_ROM 0x10add09eUL -#define M2M_START_FIRMWARE 0xef522f61UL -#define M2M_START_PS_FIRMWARE 0x94992610UL - -#define M2M_ATE_FW_START_VALUE (0x3C1CD57D) /*Also, Change this value in boot_firmware if it will be changed here*/ -#define M2M_ATE_FW_IS_UP_VALUE (0xD75DC1C3) /*Also, Change this value in ATE (Burst) firmware if it will be changed here*/ - -#define REV_2B0 (0x2B0) -#define REV_B0 (0x2B0) -#define REV_3A0 (0x3A0) -#define GET_CHIPID() nmi_get_chipid() -#define ISNMC1000(id) ((((id) & 0xfffff000) == 0x100000) ? 1 : 0) -#define ISNMC1500(id) ((((id) & 0xfffff000) == 0x150000) ? 1 : 0) -#define ISNMC3000(id) ((((id) & 0xfff00000) == 0x300000) ? 1 : 0) -#define REV(id) (((id) & 0x00000fff )) -#define EFUSED_MAC(value) (value & 0xffff0000) - -#define rHAVE_SDIO_IRQ_GPIO_BIT (NBIT0) -#define rHAVE_USE_PMU_BIT (NBIT1) -#define rHAVE_SLEEP_CLK_SRC_RTC_BIT (NBIT2) -#define rHAVE_SLEEP_CLK_SRC_XO_BIT (NBIT3) -#define rHAVE_EXT_PA_INV_TX_RX (NBIT4) -#define rHAVE_LEGACY_RF_SETTINGS (NBIT5) -#define rHAVE_LOGS_DISABLED_BIT (NBIT6) -#define rHAVE_ETHERNET_MODE_BIT (NBIT7) -#define rHAVE_RESERVED1_BIT (NBIT8) - -typedef struct{ - uint32 u32Mac_efuse_mib; - uint32 u32Firmware_Ota_rev; -}tstrGpRegs; - -#ifdef __cplusplus - extern "C" { -#endif - -/* -* @fn cpu_halt -* @brief -*/ -sint8 cpu_halt(void); -/* -* @fn chip_sleep -* @brief -*/ -sint8 chip_sleep(void); -/* -* @fn chip_wake -* @brief -*/ -sint8 chip_wake(void); -/* -* @fn chip_idle -* @brief -*/ -void chip_idle(void); -/* -* @fn enable_interrupts -* @brief -*/ -sint8 enable_interrupts(void); -/* -* @fn cpu_start -* @brief -*/ -sint8 cpu_start(void); -/* -* @fn nmi_get_chipid -* @brief -*/ -uint32 nmi_get_chipid(void); -/* -* @fn nmi_get_rfrevid -* @brief -*/ -uint32 nmi_get_rfrevid(void); -/* -* @fn restore_pmu_settings_after_global_reset -* @brief -*/ -void restore_pmu_settings_after_global_reset(void); -/* -* @fn nmi_update_pll -* @brief -*/ -void nmi_update_pll(void); -/* -* @fn nmi_set_sys_clk_src_to_xo -* @brief -*/ -void nmi_set_sys_clk_src_to_xo(void); -/* -* @fn chip_reset -* @brief -*/ -sint8 chip_reset(void); -/* -* @fn wait_for_bootrom -* @brief -*/ -sint8 wait_for_bootrom(uint8); -/* -* @fn wait_for_firmware_start -* @brief -*/ -sint8 wait_for_firmware_start(uint8); -/* -* @fn chip_deinit -* @brief -*/ -sint8 chip_deinit(void); -/* -* @fn chip_reset_and_cpu_halt -* @brief -*/ -sint8 chip_reset_and_cpu_halt(void); -/* -* @fn set_gpio_dir -* @brief -*/ -sint8 set_gpio_dir(uint8 gpio, uint8 dir); -/* -* @fn set_gpio_val -* @brief -*/ -sint8 set_gpio_val(uint8 gpio, uint8 val); -/* -* @fn get_gpio_val -* @brief -*/ -sint8 get_gpio_val(uint8 gpio, uint8* val); -/* -* @fn pullup_ctrl -* @brief -*/ -sint8 pullup_ctrl(uint32 pinmask, uint8 enable); -/* -* @fn nmi_get_otp_mac_address -* @brief -*/ -sint8 nmi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); -/* -* @fn nmi_get_mac_address -* @brief -*/ -sint8 nmi_get_mac_address(uint8 *pu8MacAddr); -/* -* @fn chip_apply_conf -* @brief -*/ -sint8 chip_apply_conf(uint32 u32conf); - -#ifdef __cplusplus - } -#endif - -#endif /*_NMASIC_H_*/ diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmbus.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmbus.c deleted file mode 100644 index d001d72..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmbus.c +++ /dev/null @@ -1,301 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 bus APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -#ifndef CORTUS_APP - -#include "nmbus.h" -#include "nmi2c.h" -#include "nmspi.h" -#include "nmuart.h" - -#define MAX_TRX_CFG_SZ 8 - -/** -* @fn nm_bus_iface_init -* @brief Initialize bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_bus_iface_init(void *pvInitVal) -{ - sint8 ret = M2M_SUCCESS; - ret = nm_bus_init(pvInitVal); - return ret; -} - -/** -* @fn nm_bus_iface_deinit -* @brief Deinitialize bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Samer Sarhan -* @date 07 April 2014 -* @version 1.0 -*/ -sint8 nm_bus_iface_deinit(void) -{ - sint8 ret = M2M_SUCCESS; - ret = nm_bus_deinit(); - - return ret; -} - -/** -* @fn nm_bus_reset -* @brief reset bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @version 1.0 -*/ -sint8 nm_bus_reset(void) -{ - sint8 ret = M2M_SUCCESS; -#ifdef CONF_WINC_USE_UART -#elif defined (CONF_WINC_USE_SPI) - return nm_spi_reset(); -#elif defined (CONF_WINC_USE_I2C) -#else -#error "Plesae define bus usage" -#endif - - return ret; -} - -/** -* @fn nm_bus_iface_reconfigure -* @brief reconfigure bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Viswanathan Murugesan -* @date 22 Oct 2014 -* @version 1.0 -*/ -sint8 nm_bus_iface_reconfigure(void *ptr) -{ -#ifdef ARDUINO - (void)ptr; // Silence "unused" warning -#endif - sint8 ret = M2M_SUCCESS; -#ifdef CONF_WINC_USE_UART - ret = nm_uart_reconfigure(ptr); -#endif - return ret; -} -/* -* @fn nm_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -uint32 nm_read_reg(uint32 u32Addr) -{ -#ifdef CONF_WINC_USE_UART - return nm_uart_read_reg(u32Addr); -#elif defined (CONF_WINC_USE_SPI) - return nm_spi_read_reg(u32Addr); -#elif defined (CONF_WINC_USE_I2C) - return nm_i2c_read_reg(u32Addr); -#else -#error "Plesae define bus usage" -#endif - -} - -/* -* @fn nm_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) -{ -#ifdef CONF_WINC_USE_UART - return nm_uart_read_reg_with_ret(u32Addr,pu32RetVal); -#elif defined (CONF_WINC_USE_SPI) - return nm_spi_read_reg_with_ret(u32Addr,pu32RetVal); -#elif defined (CONF_WINC_USE_I2C) - return nm_i2c_read_reg_with_ret(u32Addr,pu32RetVal); -#else -#error "Plesae define bus usage" -#endif -} - -/* -* @fn nm_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_write_reg(uint32 u32Addr, uint32 u32Val) -{ -#ifdef CONF_WINC_USE_UART - return nm_uart_write_reg(u32Addr,u32Val); -#elif defined (CONF_WINC_USE_SPI) - return nm_spi_write_reg(u32Addr,u32Val); -#elif defined (CONF_WINC_USE_I2C) - return nm_i2c_write_reg(u32Addr,u32Val); -#else -#error "Plesae define bus usage" -#endif -} - -static sint8 p_nm_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) -{ -#ifdef CONF_WINC_USE_UART - return nm_uart_read_block(u32Addr,puBuf,u16Sz); -#elif defined (CONF_WINC_USE_SPI) - return nm_spi_read_block(u32Addr,puBuf,u16Sz); -#elif defined (CONF_WINC_USE_I2C) - return nm_i2c_read_block(u32Addr,puBuf,u16Sz); -#else -#error "Plesae define bus usage" -#endif - -} -/* -* @fn nm_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u32Sz -* Number of bytes to read. The buffer size must be >= u32Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_read_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz) -{ - uint16 u16MaxTrxSz = egstrNmBusCapabilities.u16MaxTrxSz - MAX_TRX_CFG_SZ; - uint32 off = 0; - sint8 s8Ret = M2M_SUCCESS; - - for(;;) - { - if(u32Sz <= u16MaxTrxSz) - { - s8Ret += p_nm_read_block(u32Addr, &puBuf[off], (uint16)u32Sz); - break; - } - else - { - s8Ret += p_nm_read_block(u32Addr, &puBuf[off], u16MaxTrxSz); - if(M2M_SUCCESS != s8Ret) break; - u32Sz -= u16MaxTrxSz; - off += u16MaxTrxSz; - u32Addr += u16MaxTrxSz; - } - } - - return s8Ret; -} - -static sint8 p_nm_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) -{ -#ifdef CONF_WINC_USE_UART - return nm_uart_write_block(u32Addr,puBuf,u16Sz); -#elif defined (CONF_WINC_USE_SPI) - return nm_spi_write_block(u32Addr,puBuf,u16Sz); -#elif defined (CONF_WINC_USE_I2C) - return nm_i2c_write_block(u32Addr,puBuf,u16Sz); -#else -#error "Plesae define bus usage" -#endif - -} -/** -* @fn nm_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u32Sz -* Number of bytes to write. The buffer size must be >= u32Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_write_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz) -{ - uint16 u16MaxTrxSz = egstrNmBusCapabilities.u16MaxTrxSz - MAX_TRX_CFG_SZ; - uint32 off = 0; - sint8 s8Ret = M2M_SUCCESS; - - for(;;) - { - if(u32Sz <= u16MaxTrxSz) - { - s8Ret += p_nm_write_block(u32Addr, &puBuf[off], (uint16)u32Sz); - break; - } - else - { - s8Ret += p_nm_write_block(u32Addr, &puBuf[off], u16MaxTrxSz); - if(M2M_SUCCESS != s8Ret) break; - u32Sz -= u16MaxTrxSz; - off += u16MaxTrxSz; - u32Addr += u16MaxTrxSz; - } - } - - return s8Ret; -} - -#endif - diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmbus.h b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmbus.h deleted file mode 100644 index 2ea7838..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmbus.h +++ /dev/null @@ -1,147 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 bus APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NMBUS_H_ -#define _NMBUS_H_ - -#include "common/include/nm_common.h" -#include "bus_wrapper/include/nm_bus_wrapper.h" - - - -#ifdef __cplusplus -extern "C"{ -#endif -/** -* @fn nm_bus_iface_init -* @brief Initialize bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_bus_iface_init(void *); - - -/** -* @fn nm_bus_iface_deinit -* @brief Deinitialize bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_bus_iface_deinit(void); - -/** -* @fn nm_bus_reset -* @brief reset bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @version 1.0 -*/ -sint8 nm_bus_reset(void); - -/** -* @fn nm_bus_iface_reconfigure -* @brief reconfigure bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_bus_iface_reconfigure(void *ptr); - -/** -* @fn nm_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -*/ -uint32 nm_read_reg(uint32 u32Addr); - -/** -* @fn nm_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); - -/** -* @fn nm_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_write_reg(uint32 u32Addr, uint32 u32Val); - -/** -* @fn nm_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u32Sz -* Number of bytes to read. The buffer size must be >= u32Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_read_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz); - -/** -* @fn nm_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u32Sz -* Number of bytes to write. The buffer size must be >= u32Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_write_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz); - - - - -#ifdef __cplusplus -} -#endif - -#endif /* _NMBUS_H_ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmdrv.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmdrv.c deleted file mode 100644 index b3f2a8a..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmdrv.c +++ /dev/null @@ -1,402 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 M2M driver APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "common/include/nm_common.h" -#include "driver/source/nmbus.h" -#include "bsp/include/nm_bsp.h" -#include "driver/source/nmdrv.h" -#include "driver/source/nmasic.h" -#include "driver/include/m2m_types.h" -#include "spi_flash/include/spi_flash.h" - -#ifdef CONF_WINC_USE_SPI -#include "driver/source/nmspi.h" -#endif - -#ifdef ARDUINO - uint32 nmdrv_firm_ver = 0; -#endif - -/** -* @fn nm_get_firmware_info(tstrM2mRev* M2mRev) -* @brief Get Firmware version info -* @param [out] M2mRev -* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters -* @version 1.0 -*/ -sint8 nm_get_firmware_info(tstrM2mRev* M2mRev) -{ - uint16 curr_drv_ver, min_req_drv_ver,curr_firm_ver; - uint32 reg = 0; - sint8 ret = M2M_SUCCESS; - - ret = nm_read_reg_with_ret(NMI_REV_REG, ®); - //In case the Firmware running is ATE fw - if(M2M_ATE_FW_IS_UP_VALUE == reg) - { - //Read FW info again from the register specified for ATE - ret = nm_read_reg_with_ret(NMI_REV_REG_ATE, ®); - } - M2mRev->u8DriverMajor = M2M_GET_DRV_MAJOR(reg); - M2mRev->u8DriverMinor = M2M_GET_DRV_MINOR(reg); - M2mRev->u8DriverPatch = M2M_GET_DRV_PATCH(reg); - M2mRev->u8FirmwareMajor = M2M_GET_FW_MAJOR(reg); - M2mRev->u8FirmwareMinor = M2M_GET_FW_MINOR(reg); - M2mRev->u8FirmwarePatch = M2M_GET_FW_PATCH(reg); - M2mRev->u32Chipid = nmi_get_chipid(); - M2mRev->u16FirmwareSvnNum = 0; - - curr_firm_ver = M2M_MAKE_VERSION(M2mRev->u8FirmwareMajor, M2mRev->u8FirmwareMinor,M2mRev->u8FirmwarePatch); -#ifdef ARDUINO - nmdrv_firm_ver = curr_firm_ver; -#endif - curr_drv_ver = M2M_MAKE_VERSION(M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); - min_req_drv_ver = M2M_MAKE_VERSION(M2mRev->u8DriverMajor, M2mRev->u8DriverMinor,M2mRev->u8DriverPatch); - if(curr_drv_ver < min_req_drv_ver) { - /*The current driver version should be larger or equal - than the min driver that the current firmware support */ - ret = M2M_ERR_FW_VER_MISMATCH; - } - if(curr_drv_ver > curr_firm_ver) { - /*The current driver should be equal or less than the firmware version*/ - ret = M2M_ERR_FW_VER_MISMATCH; - } - return ret; -} -/** -* @fn nm_get_firmware_info(tstrM2mRev* M2mRev) -* @brief Get Firmware version info -* @param [out] M2mRev -* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters -* @version 1.0 -*/ -sint8 nm_get_firmware_full_info(tstrM2mRev* pstrRev) -{ - uint16 curr_drv_ver, min_req_drv_ver,curr_firm_ver; - uint32 reg = 0; - sint8 ret = M2M_SUCCESS; - tstrGpRegs strgp = {0}; - if (pstrRev != NULL) - { - m2m_memset((uint8*)pstrRev,0,sizeof(tstrM2mRev)); - ret = nm_read_reg_with_ret(rNMI_GP_REG_2, ®); - if(ret == M2M_SUCCESS) - { - if(reg != 0) - { - ret = nm_read_block(reg|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); - if(ret == M2M_SUCCESS) - { - reg = strgp.u32Firmware_Ota_rev; - reg &= 0x0000ffff; - if(reg != 0) - { - ret = nm_read_block(reg|0x30000,(uint8*)pstrRev,sizeof(tstrM2mRev)); - if(ret == M2M_SUCCESS) - { - curr_firm_ver = M2M_MAKE_VERSION(pstrRev->u8FirmwareMajor, pstrRev->u8FirmwareMinor,pstrRev->u8FirmwarePatch); -#ifdef ARDUINO - nmdrv_firm_ver = curr_firm_ver; -#endif - curr_drv_ver = M2M_MAKE_VERSION(M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); - min_req_drv_ver = M2M_MAKE_VERSION(pstrRev->u8DriverMajor, pstrRev->u8DriverMinor,pstrRev->u8DriverPatch); - if((curr_firm_ver == 0)||(min_req_drv_ver == 0)||(min_req_drv_ver == 0)){ - ret = M2M_ERR_FAIL; - goto EXIT; - } - if(curr_drv_ver < min_req_drv_ver) { - /*The current driver version should be larger or equal - than the min driver that the current firmware support */ - ret = M2M_ERR_FW_VER_MISMATCH; - goto EXIT; - } - if(curr_drv_ver > curr_firm_ver) { - /*The current driver should be equal or less than the firmware version*/ - ret = M2M_ERR_FW_VER_MISMATCH; - goto EXIT; - } - } - }else { - ret = M2M_ERR_FAIL; - } - } - }else{ - ret = M2M_ERR_FAIL; - } - } - } -EXIT: - return ret; -} -/** -* @fn nm_get_ota_firmware_info(tstrM2mRev* pstrRev) -* @brief Get Firmware version info -* @param [out] M2mRev -* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters - -* @version 1.0 -*/ -sint8 nm_get_ota_firmware_info(tstrM2mRev* pstrRev) -{ - uint16 curr_drv_ver, min_req_drv_ver,curr_firm_ver; - uint32 reg = 0; - sint8 ret; - tstrGpRegs strgp = {0}; - - if (pstrRev != NULL) - { - m2m_memset((uint8*)pstrRev,0,sizeof(tstrM2mRev)); - ret = nm_read_reg_with_ret(rNMI_GP_REG_2, ®); - if(ret == M2M_SUCCESS) - { - if(reg != 0) - { - ret = nm_read_block(reg|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); - if(ret == M2M_SUCCESS) - { - reg = strgp.u32Firmware_Ota_rev; - reg >>= 16; - if(reg != 0) - { - ret = nm_read_block(reg|0x30000,(uint8*)pstrRev,sizeof(tstrM2mRev)); - if(ret == M2M_SUCCESS) - { - curr_firm_ver = M2M_MAKE_VERSION(pstrRev->u8FirmwareMajor, pstrRev->u8FirmwareMinor,pstrRev->u8FirmwarePatch); - curr_drv_ver = M2M_MAKE_VERSION(M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); - min_req_drv_ver = M2M_MAKE_VERSION(pstrRev->u8DriverMajor, pstrRev->u8DriverMinor,pstrRev->u8DriverPatch); - if((curr_firm_ver == 0)||(min_req_drv_ver == 0)||(min_req_drv_ver == 0)){ - ret = M2M_ERR_FAIL; - goto EXIT; - } - if(curr_drv_ver < min_req_drv_ver) { - /*The current driver version should be larger or equal - than the min driver that the current firmware support */ - ret = M2M_ERR_FW_VER_MISMATCH; - } - if(curr_drv_ver > curr_firm_ver) { - /*The current driver should be equal or less than the firmware version*/ - ret = M2M_ERR_FW_VER_MISMATCH; - } - } - }else{ - ret = M2M_ERR_INVALID; - } - } - }else{ - ret = M2M_ERR_FAIL; - } - } - } else { - ret = M2M_ERR_INVALID_ARG; - } -EXIT: - return ret; -} - - - -/* -* @fn nm_drv_init_download_mode -* @brief Initialize NMC1000 driver -* @return M2M_SUCCESS in case of success and Negative error code in case of failure -* @param [in] arg -* Generic argument -* @author Viswanathan Murugesan -* @date 10 Oct 2014 -* @version 1.0 -*/ -sint8 nm_drv_init_download_mode() -{ - sint8 ret = M2M_SUCCESS; - - ret = nm_bus_iface_init(NULL); - if (M2M_SUCCESS != ret) { - M2M_ERR("[nmi start]: fail init bus\n"); - goto ERR1; - } - - /** - TODO:reset the chip and halt the cpu in case of no wait efuse is set (add the no wait effuse check) - */ - if(!ISNMC3000(GET_CHIPID())) - { - /*Execuate that function only for 1500A/B, no room in 3000, but it may be needed in 3400 no wait*/ - chip_reset_and_cpu_halt(); - } - -#ifdef CONF_WINC_USE_SPI - /* Must do this after global reset to set SPI data packet size. */ - nm_spi_init(); -#endif - - M2M_INFO("Chip ID %lx\n", nmi_get_chipid()); - - /*disable all interrupt in ROM (to disable uart) in 2b0 chip*/ - nm_write_reg(0x20300,0); - -ERR1: - return ret; -} - -/* -* @fn nm_drv_init -* @brief Initialize NMC1000 driver -* @return M2M_SUCCESS in case of success and Negative error code in case of failure -* @param [in] arg -* Generic argument -* @author M. Abdelmawla -* @date 15 July 2012 -* @version 1.0 -*/ -sint8 nm_drv_init(void * arg) -{ - sint8 ret = M2M_SUCCESS; - uint8 u8Mode; - - if(NULL != arg) { - u8Mode = *((uint8 *)arg); - if((u8Mode < M2M_WIFI_MODE_NORMAL)||(u8Mode >= M2M_WIFI_MODE_MAX)) { - u8Mode = M2M_WIFI_MODE_NORMAL; - } - } else { - u8Mode = M2M_WIFI_MODE_NORMAL; - } - - ret = nm_bus_iface_init(NULL); - if (M2M_SUCCESS != ret) { - M2M_ERR("[nmi start]: fail init bus\n"); - goto ERR1; - } - -#ifdef BUS_ONLY - return; -#endif - - -#ifdef NO_HW_CHIP_EN - ret = chip_wake(); - if (M2M_SUCCESS != ret) { - M2M_ERR("[nmi start]: fail chip_wakeup\n"); - goto ERR2; - } - /** - Go... - **/ - ret = chip_reset(); - if (M2M_SUCCESS != ret) { - goto ERR2; - } -#endif - M2M_INFO("Chip ID %lx\n", nmi_get_chipid()); -#ifdef CONF_WINC_USE_SPI - /* Must do this after global reset to set SPI data packet size. */ - nm_spi_init(); -#endif - ret = wait_for_bootrom(u8Mode); - if (M2M_SUCCESS != ret) { - goto ERR2; - } - - ret = wait_for_firmware_start(u8Mode); - if (M2M_SUCCESS != ret) { - goto ERR2; - } - - if((M2M_WIFI_MODE_ATE_HIGH == u8Mode)||(M2M_WIFI_MODE_ATE_LOW == u8Mode)) { - goto ERR1; - } else { - /*continue running*/ - } - - ret = enable_interrupts(); - if (M2M_SUCCESS != ret) { - M2M_ERR("failed to enable interrupts..\n"); - goto ERR2; - } - return ret; -ERR2: - nm_bus_iface_deinit(); -ERR1: - return ret; -} - -/* -* @fn nm_drv_deinit -* @brief Deinitialize NMC1000 driver -* @author M. Abdelmawla -* @date 17 July 2012 -* @version 1.0 -*/ -sint8 nm_drv_deinit(void * arg) -{ -#ifdef ARDUINO - (void)arg; // Silence "unused" warning -#endif - sint8 ret; - - ret = chip_deinit(); - if (M2M_SUCCESS != ret) { - M2M_ERR("[nmi stop]: chip_deinit fail\n"); - goto ERR1; - } - - /* Disable SPI flash to save power when the chip is off */ - ret = spi_flash_enable(0); - if (M2M_SUCCESS != ret) { - M2M_ERR("[nmi stop]: SPI flash disable fail\n"); - goto ERR1; - } - - ret = nm_bus_iface_deinit(); - if (M2M_SUCCESS != ret) { - M2M_ERR("[nmi stop]: fail init bus\n"); - goto ERR1; - } -#ifdef CONF_WINC_USE_SPI - /* Must do this after global reset to set SPI data packet size. */ - nm_spi_deinit(); -#endif - -ERR1: - return ret; -} - - diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmdrv.h b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmdrv.h deleted file mode 100644 index 6a416b2..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmdrv.h +++ /dev/null @@ -1,138 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 M2M driver APIs declarations. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NMDRV_H_ -#define _NMDRV_H_ - -#include "common/include/nm_common.h" - -/** -* @struct tstrM2mRev -* @brief Structure holding firmware version parameters and build date/time -*/ -typedef struct { - uint32 u32Chipid; /* HW revision which will be basically the chip ID */ - uint8 u8FirmwareMajor; /* Version Major Number which represents the official release base */ - uint8 u8FirmwareMinor; /* Version Minor Number which represents the engineering release base */ - uint8 u8FirmwarePatch; /* Version pathc Number which represents the pathces release base */ - uint8 u8DriverMajor; /* Version Major Number which represents the official release base */ - uint8 u8DriverMinor; /* Version Minor Number which represents the engineering release base */ - uint8 u8DriverPatch; /* Version Patch Number which represents the pathces release base */ - uint8 BuildDate[sizeof(__DATE__)]; - uint8 BuildTime[sizeof(__TIME__)]; - uint8 _PAD8_; - uint16 u16FirmwareSvnNum; - uint16 _PAD16_[2]; -} tstrM2mRev; - -/** -* @struct tstrM2mBinaryHeader -* @brief Structure holding compatibility version info for firmware binaries -*/ -typedef struct { - tstrM2mRev binVerInfo; - uint32 flashOffset; - uint32 payloadSize; -} tstrM2mBinaryHeader; - -#ifdef __cplusplus - extern "C" { - #endif -/** -* @fn nm_get_firmware_info(tstrM2mRev* M2mRev) -* @brief Get Firmware version info -* @param [out] M2mRev -* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters -* @version 1.0 -*/ -sint8 nm_get_firmware_info(tstrM2mRev* M2mRev); -/** -* @fn nm_get_firmware_full_info(tstrM2mRev* pstrRev) -* @brief Get Firmware version info -* @param [out] M2mRev -* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters -* @version 1.0 -*/ -sint8 nm_get_firmware_full_info(tstrM2mRev* pstrRev); -/** -* @fn nm_get_ota_firmware_info(tstrM2mRev* pstrRev) -* @brief Get Firmware version info -* @param [out] M2mRev -* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters - -* @version 1.0 -*/ -sint8 nm_get_ota_firmware_info(tstrM2mRev* pstrRev); -/* -* @fn nm_drv_init -* @brief Initialize NMC1000 driver -* @return ZERO in case of success and Negative error code in case of failure -*/ -sint8 nm_drv_init_download_mode(void); - -/* -* @fn nm_drv_init -* @brief Initialize NMC1000 driver -* @return M2M_SUCCESS in case of success and Negative error code in case of failure -* @param [in] arg -* Generic argument TBD -* @return ZERO in case of success and Negative error code in case of failure - -*/ -sint8 nm_drv_init(void * arg); - -/** -* @fn nm_drv_deinit -* @brief Deinitialize NMC1000 driver -* @author M. Abdelmawla -* @param [in] arg -* Generic argument TBD -* @return ZERO in case of success and Negative error code in case of failure -*/ -sint8 nm_drv_deinit(void * arg); - -#ifdef __cplusplus - } - #endif - -#endif /*_NMDRV_H_*/ - - diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmi2c.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmi2c.c deleted file mode 100644 index e11d2f7..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmi2c.c +++ /dev/null @@ -1,269 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 I2C protocol bus APIs implementation. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "common/include/nm_common.h" - -#ifdef CONF_WINC_USE_I2C - -#include "nmi2c.h" -#include "bus_wrapper/include/nm_bus_wrapper.h" - - -/* -* @fn nm_i2c_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ - sint8 nm_i2c_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) -{ - uint8 b[6]; - uint8 rsz; - tstrNmI2cDefault strI2c; - sint8 s8Ret = M2M_SUCCESS; - - if(u32Addr < 0xff) { /* clockless i2c */ - b[0] = 0x09; - b[1] = (uint8)(u32Addr); - rsz = 1; - strI2c.u16Sz = 2; - } else { - b[0] = 0x80; - b[1] = (uint8)(u32Addr >> 24); - b[2] = (uint8)(u32Addr >> 16); - b[3] = (uint8)(u32Addr >> 8); - b[4] = (uint8)(u32Addr); - b[5] = 0x04; - rsz = 4; - strI2c.u16Sz = 6; - } - - strI2c.pu8Buf = b; - - if(M2M_SUCCESS == nm_bus_ioctl(NM_BUS_IOCTL_W, &strI2c)) - { - strI2c.u16Sz = rsz; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strI2c)) - { - //M2M_ERR("read error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - M2M_ERR("failed to send cfg bytes\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - - if (rsz == 1) { - *pu32RetVal = b[0]; - } else { - *pu32RetVal = b[0] | ((uint32)b[1] << 8) | ((uint32)b[2] << 16) | ((uint32)b[3] << 24); - } - return s8Ret; -} - -/* -* @fn nm_i2c_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -uint32 nm_i2c_read_reg(uint32 u32Addr) -{ - uint32 val; - nm_i2c_read_reg_with_ret(u32Addr, &val); - return val; -} - -/* -* @fn nm_i2c_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_i2c_write_reg(uint32 u32Addr, uint32 u32Val) -{ - tstrNmI2cDefault strI2c; - uint8 b[16]; - sint8 s8Ret = M2M_SUCCESS; - - if(u32Addr < 0xff) { /* clockless i2c */ - b[0] = 0x19; - b[1] = (uint8)(u32Addr); - b[2] = (uint8)(u32Val); - strI2c.u16Sz = 3; - } else { - b[0] = 0x90; - b[1] = (uint8)(u32Addr >> 24); - b[2] = (uint8)(u32Addr >> 16); - b[3] = (uint8)(u32Addr >> 8); - b[4] = (uint8)u32Addr; - b[5] = 0x04; - b[6] = (uint8)u32Val; - b[7] = (uint8)(u32Val >> 8); - b[8] = (uint8)(u32Val >> 16); - b[9] = (uint8)(u32Val >> 24); - strI2c.u16Sz = 10; - } - - strI2c.pu8Buf = b; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strI2c)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - - return s8Ret; -} - -/* -* @fn nm_i2c_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u16Sz -* Number of bytes to read. The buffer size must be >= u16Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_i2c_read_block(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz) -{ - tstrNmI2cDefault strI2c; - uint8 au8Buf[7]; - sint8 s8Ret = M2M_SUCCESS; - - au8Buf[0] = 0x02; - au8Buf[1] = (uint8)(u32Addr >> 24); - au8Buf[2] = (uint8)(u32Addr >> 16); - au8Buf[3] = (uint8)(u32Addr >> 8); - au8Buf[4] = (uint8)(u32Addr >> 0); - au8Buf[5] = (uint8)(u16Sz >> 8); - au8Buf[6] = (uint8)(u16Sz); - - strI2c.pu8Buf = au8Buf; - strI2c.u16Sz = sizeof(au8Buf); - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strI2c)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - else - { - strI2c.pu8Buf = pu8Buf; - strI2c.u16Sz = u16Sz; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strI2c)) - { - M2M_ERR("read error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - - return s8Ret; -} - -/* -* @fn nm_i2c_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u16Sz -* Number of bytes to write. The buffer size must be >= u16Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_i2c_write_block(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz) -{ - uint8 au8Buf[7]; - tstrNmI2cSpecial strI2c; - sint8 s8Ret = M2M_SUCCESS; - - au8Buf[0] = 0x12; - au8Buf[1] = (uint8)(u32Addr >> 24); - au8Buf[2] = (uint8)(u32Addr >> 16); - au8Buf[3] = (uint8)(u32Addr >> 8); - au8Buf[4] = (uint8)(u32Addr); - au8Buf[5] = (uint8)(u16Sz >> 8); - au8Buf[6] = (uint8)(u16Sz); - - strI2c.pu8Buf1 = au8Buf; - strI2c.pu8Buf2 = pu8Buf; - strI2c.u16Sz1 = sizeof(au8Buf); - strI2c.u16Sz2 = u16Sz; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W_SPECIAL, &strI2c)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - - return s8Ret; -} - -#endif -/* EOF */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmi2c.h b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmi2c.h deleted file mode 100644 index fea85e6..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmi2c.h +++ /dev/null @@ -1,104 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 I2C protocol bus APIs implementation. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NMI2C_H_ -#define _NMI2C_H_ - -#include "common/include/nm_common.h" - -/** -* @fn nm_i2c_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -*/ -uint32 nm_i2c_read_reg(uint32 u32Addr); - -/** -* @fn nm_i2c_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_i2c_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); - -/** -* @fn nm_i2c_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_i2c_write_reg(uint32 u32Addr, uint32 u32Val); - -/** -* @fn nm_i2c_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u16Sz -* Number of bytes to read. The buffer size must be >= u16Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_i2c_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); - -/** -* @fn nm_i2c_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u16Sz -* Number of bytes to write. The buffer size must be >= u16Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_i2c_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); - -#endif /* _NMI2C_H_ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmspi.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmspi.c deleted file mode 100644 index 9483ab7..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmspi.c +++ /dev/null @@ -1,1401 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 SPI protocol bus APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -#include "common/include/nm_common.h" - -#ifdef CONF_WINC_USE_SPI - -#define USE_OLD_SPI_SW - -#include "bus_wrapper/include/nm_bus_wrapper.h" -#include "nmspi.h" - -#define NMI_PERIPH_REG_BASE 0x1000 -#define NMI_INTR_REG_BASE (NMI_PERIPH_REG_BASE+0xa00) -#define NMI_CHIPID (NMI_PERIPH_REG_BASE) -#define NMI_PIN_MUX_0 (NMI_PERIPH_REG_BASE + 0x408) -#define NMI_INTR_ENABLE (NMI_INTR_REG_BASE) - -#define NMI_SPI_REG_BASE 0xe800 -#define NMI_SPI_CTL (NMI_SPI_REG_BASE) -#define NMI_SPI_MASTER_DMA_ADDR (NMI_SPI_REG_BASE+0x4) -#define NMI_SPI_MASTER_DMA_COUNT (NMI_SPI_REG_BASE+0x8) -#define NMI_SPI_SLAVE_DMA_ADDR (NMI_SPI_REG_BASE+0xc) -#define NMI_SPI_SLAVE_DMA_COUNT (NMI_SPI_REG_BASE+0x10) -#define NMI_SPI_TX_MODE (NMI_SPI_REG_BASE+0x20) -#define NMI_SPI_PROTOCOL_CONFIG (NMI_SPI_REG_BASE+0x24) -#define NMI_SPI_INTR_CTL (NMI_SPI_REG_BASE+0x2c) -#define NMI_SPI_MISC_CTRL (NMI_SPI_REG_BASE+0x48) - -#define NMI_SPI_PROTOCOL_OFFSET (NMI_SPI_PROTOCOL_CONFIG-NMI_SPI_REG_BASE) - -#define SPI_BASE NMI_SPI_REG_BASE - -#define CMD_DMA_WRITE 0xc1 -#define CMD_DMA_READ 0xc2 -#define CMD_INTERNAL_WRITE 0xc3 -#define CMD_INTERNAL_READ 0xc4 -#define CMD_TERMINATE 0xc5 -#define CMD_REPEAT 0xc6 -#define CMD_DMA_EXT_WRITE 0xc7 -#define CMD_DMA_EXT_READ 0xc8 -#define CMD_SINGLE_WRITE 0xc9 -#define CMD_SINGLE_READ 0xca -#define CMD_RESET 0xcf - -#define N_OK 1 -#define N_FAIL 0 -#define N_RESET -1 -#define N_RETRY -2 - -#define SPI_RESP_RETRY_COUNT (10) -#define SPI_RETRY_COUNT (10) -#define DATA_PKT_SZ_256 256 -#define DATA_PKT_SZ_512 512 -#define DATA_PKT_SZ_1K 1024 -#define DATA_PKT_SZ_4K (4 * 1024) -#define DATA_PKT_SZ_8K (8 * 1024) -#define DATA_PKT_SZ DATA_PKT_SZ_8K - -static uint8 gu8Crc_off = 0; - -static sint8 nmi_spi_read(uint8* b, uint16 sz) -{ - tstrNmSpiRw spi; - spi.pu8InBuf = NULL; - spi.pu8OutBuf = b; - spi.u16Sz = sz; - return nm_bus_ioctl(NM_BUS_IOCTL_RW, &spi); -} - -static sint8 nmi_spi_write(uint8* b, uint16 sz) -{ - tstrNmSpiRw spi; - spi.pu8InBuf = b; - spi.pu8OutBuf = NULL; - spi.u16Sz = sz; - return nm_bus_ioctl(NM_BUS_IOCTL_RW, &spi); -} -#ifndef USE_OLD_SPI_SW -static sint8 nmi_spi_rw(uint8 *bin,uint8* bout,uint16 sz) -{ - tstrNmSpiRw spi; - spi.pu8InBuf = bin; - spi.pu8OutBuf = bout; - spi.u16Sz = sz; - return nm_bus_ioctl(NM_BUS_IOCTL_RW, &spi); -} -#endif -/******************************************** - - Crc7 - -********************************************/ -#if (defined ARDUINO_ARCH_AVR) -#include -static PROGMEM const uint8 crc7_syndrome_table[256] = { -#else -static const uint8 crc7_syndrome_table[256] = { -#endif - 0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f, - 0x48, 0x41, 0x5a, 0x53, 0x6c, 0x65, 0x7e, 0x77, - 0x19, 0x10, 0x0b, 0x02, 0x3d, 0x34, 0x2f, 0x26, - 0x51, 0x58, 0x43, 0x4a, 0x75, 0x7c, 0x67, 0x6e, - 0x32, 0x3b, 0x20, 0x29, 0x16, 0x1f, 0x04, 0x0d, - 0x7a, 0x73, 0x68, 0x61, 0x5e, 0x57, 0x4c, 0x45, - 0x2b, 0x22, 0x39, 0x30, 0x0f, 0x06, 0x1d, 0x14, - 0x63, 0x6a, 0x71, 0x78, 0x47, 0x4e, 0x55, 0x5c, - 0x64, 0x6d, 0x76, 0x7f, 0x40, 0x49, 0x52, 0x5b, - 0x2c, 0x25, 0x3e, 0x37, 0x08, 0x01, 0x1a, 0x13, - 0x7d, 0x74, 0x6f, 0x66, 0x59, 0x50, 0x4b, 0x42, - 0x35, 0x3c, 0x27, 0x2e, 0x11, 0x18, 0x03, 0x0a, - 0x56, 0x5f, 0x44, 0x4d, 0x72, 0x7b, 0x60, 0x69, - 0x1e, 0x17, 0x0c, 0x05, 0x3a, 0x33, 0x28, 0x21, - 0x4f, 0x46, 0x5d, 0x54, 0x6b, 0x62, 0x79, 0x70, - 0x07, 0x0e, 0x15, 0x1c, 0x23, 0x2a, 0x31, 0x38, - 0x41, 0x48, 0x53, 0x5a, 0x65, 0x6c, 0x77, 0x7e, - 0x09, 0x00, 0x1b, 0x12, 0x2d, 0x24, 0x3f, 0x36, - 0x58, 0x51, 0x4a, 0x43, 0x7c, 0x75, 0x6e, 0x67, - 0x10, 0x19, 0x02, 0x0b, 0x34, 0x3d, 0x26, 0x2f, - 0x73, 0x7a, 0x61, 0x68, 0x57, 0x5e, 0x45, 0x4c, - 0x3b, 0x32, 0x29, 0x20, 0x1f, 0x16, 0x0d, 0x04, - 0x6a, 0x63, 0x78, 0x71, 0x4e, 0x47, 0x5c, 0x55, - 0x22, 0x2b, 0x30, 0x39, 0x06, 0x0f, 0x14, 0x1d, - 0x25, 0x2c, 0x37, 0x3e, 0x01, 0x08, 0x13, 0x1a, - 0x6d, 0x64, 0x7f, 0x76, 0x49, 0x40, 0x5b, 0x52, - 0x3c, 0x35, 0x2e, 0x27, 0x18, 0x11, 0x0a, 0x03, - 0x74, 0x7d, 0x66, 0x6f, 0x50, 0x59, 0x42, 0x4b, - 0x17, 0x1e, 0x05, 0x0c, 0x33, 0x3a, 0x21, 0x28, - 0x5f, 0x56, 0x4d, 0x44, 0x7b, 0x72, 0x69, 0x60, - 0x0e, 0x07, 0x1c, 0x15, 0x2a, 0x23, 0x38, 0x31, - 0x46, 0x4f, 0x54, 0x5d, 0x62, 0x6b, 0x70, 0x79 -}; - - -static uint8 crc7_byte(uint8 crc, uint8 data) -{ -#if (defined ARDUINO_ARCH_AVR) - return pgm_read_byte_near(crc7_syndrome_table + ((crc << 1) ^ data)); -#else - return crc7_syndrome_table[(crc << 1) ^ data]; -#endif -} - -static uint8 crc7(uint8 crc, const uint8 *buffer, uint32 len) -{ - while (len--) - crc = crc7_byte(crc, *buffer++); - return crc; -} - -/******************************************** - - Spi protocol Function - -********************************************/ - -#define CMD_DMA_WRITE 0xc1 -#define CMD_DMA_READ 0xc2 -#define CMD_INTERNAL_WRITE 0xc3 -#define CMD_INTERNAL_READ 0xc4 -#define CMD_TERMINATE 0xc5 -#define CMD_REPEAT 0xc6 -#define CMD_DMA_EXT_WRITE 0xc7 -#define CMD_DMA_EXT_READ 0xc8 -#define CMD_SINGLE_WRITE 0xc9 -#define CMD_SINGLE_READ 0xca -#define CMD_RESET 0xcf - -#define DATA_PKT_SZ_256 256 -#define DATA_PKT_SZ_512 512 -#define DATA_PKT_SZ_1K 1024 -#define DATA_PKT_SZ_4K (4 * 1024) -#define DATA_PKT_SZ_8K (8 * 1024) -#define DATA_PKT_SZ DATA_PKT_SZ_8K - -static sint8 spi_cmd(uint8 cmd, uint32 adr, uint32 u32data, uint32 sz,uint8 clockless) -{ - uint8 bc[9]; - uint8 len = 5; - sint8 result = N_OK; - - bc[0] = cmd; - switch (cmd) { - case CMD_SINGLE_READ: /* single word (4 bytes) read */ - bc[1] = (uint8)(adr >> 16); - bc[2] = (uint8)(adr >> 8); - bc[3] = (uint8)adr; - len = 5; - break; - case CMD_INTERNAL_READ: /* internal register read */ - bc[1] = (uint8)(adr >> 8); - if(clockless) bc[1] |= (1 << 7); - bc[2] = (uint8)adr; - bc[3] = 0x00; - len = 5; - break; - case CMD_TERMINATE: /* termination */ - bc[1] = 0x00; - bc[2] = 0x00; - bc[3] = 0x00; - len = 5; - break; - case CMD_REPEAT: /* repeat */ - bc[1] = 0x00; - bc[2] = 0x00; - bc[3] = 0x00; - len = 5; - break; - case CMD_RESET: /* reset */ - bc[1] = 0xff; - bc[2] = 0xff; - bc[3] = 0xff; - len = 5; - break; - case CMD_DMA_WRITE: /* dma write */ - case CMD_DMA_READ: /* dma read */ - bc[1] = (uint8)(adr >> 16); - bc[2] = (uint8)(adr >> 8); - bc[3] = (uint8)adr; - bc[4] = (uint8)(sz >> 8); - bc[5] = (uint8)(sz); - len = 7; - break; - case CMD_DMA_EXT_WRITE: /* dma extended write */ - case CMD_DMA_EXT_READ: /* dma extended read */ - bc[1] = (uint8)(adr >> 16); - bc[2] = (uint8)(adr >> 8); - bc[3] = (uint8)adr; - bc[4] = (uint8)(sz >> 16); - bc[5] = (uint8)(sz >> 8); - bc[6] = (uint8)(sz); - len = 8; - break; - case CMD_INTERNAL_WRITE: /* internal register write */ - bc[1] = (uint8)(adr >> 8); - if(clockless) bc[1] |= (1 << 7); - bc[2] = (uint8)(adr); - bc[3] = (uint8)(u32data >> 24); - bc[4] = (uint8)(u32data >> 16); - bc[5] = (uint8)(u32data >> 8); - bc[6] = (uint8)(u32data); - len = 8; - break; - case CMD_SINGLE_WRITE: /* single word write */ - bc[1] = (uint8)(adr >> 16); - bc[2] = (uint8)(adr >> 8); - bc[3] = (uint8)(adr); - bc[4] = (uint8)(u32data >> 24); - bc[5] = (uint8)(u32data >> 16); - bc[6] = (uint8)(u32data >> 8); - bc[7] = (uint8)(u32data); - len = 9; - break; - default: - result = N_FAIL; - break; - } - - if (result) { - if (!gu8Crc_off) - bc[len-1] = (crc7(0x7f, (const uint8 *)&bc[0], len-1)) << 1; - else - len-=1; - - if (M2M_SUCCESS != nmi_spi_write(bc, len)) { - M2M_ERR("[nmi spi]: Failed cmd write, bus error...\n"); - result = N_FAIL; - } - } - - return result; -} - -static sint8 spi_data_rsp(uint8 cmd) -{ -#ifdef ARDUINO - (void)cmd; // Silence "unused" warning -#endif - uint8 len; - uint8 rsp[3]; - sint8 result = N_OK; - - if (!gu8Crc_off) - len = 2; - else - len = 3; - - if (M2M_SUCCESS != nmi_spi_read(&rsp[0], len)) { - M2M_ERR("[nmi spi]: Failed bus error...\n"); - result = N_FAIL; - goto _fail_; - } - - if((rsp[len-1] != 0)||(rsp[len-2] != 0xC3)) - { - M2M_ERR("[nmi spi]: Failed data response read, %x %x %x\n",rsp[0],rsp[1],rsp[2]); - result = N_FAIL; - goto _fail_; - } -_fail_: - - return result; -} - -static sint8 spi_cmd_rsp(uint8 cmd) -{ - uint8 rsp; - sint8 result = N_OK; - sint8 s8RetryCnt; - - /** - Command/Control response - **/ - if ((cmd == CMD_RESET) || - (cmd == CMD_TERMINATE) || - (cmd == CMD_REPEAT)) { - if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { - result = N_FAIL; - goto _fail_; - } - } - - /* wait for response */ - s8RetryCnt = SPI_RESP_RETRY_COUNT; - do - { - if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { - M2M_ERR("[nmi spi]: Failed cmd response read, bus error...\n"); - result = N_FAIL; - goto _fail_; - } - } while((rsp != cmd) && (s8RetryCnt-- >0)); - - /** - State response - **/ - /* wait for response */ - s8RetryCnt = SPI_RESP_RETRY_COUNT; - do - { - if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { - M2M_ERR("[nmi spi]: Failed cmd response read, bus error...\n"); - result = N_FAIL; - goto _fail_; - } - } while((rsp != 0x00) && (s8RetryCnt-- >0)); - -_fail_: - - return result; -} -#ifndef USE_OLD_SPI_SW -static int spi_cmd_complete(uint8_t cmd, uint32_t adr, uint8_t *b, uint32_t sz, uint8_t clockless) -{ - uint8_t wb[32], rb[32]; - uint8_t wix, rix; - uint32_t len2; - uint8_t rsp; - int len = 0; - int result = N_OK; - - wb[0] = cmd; - switch (cmd) { - case CMD_SINGLE_READ: /* single word (4 bytes) read */ - wb[1] = (uint8_t)(adr >> 16); - wb[2] = (uint8_t)(adr >> 8); - wb[3] = (uint8_t)adr; - len = 5; - break; - case CMD_INTERNAL_READ: /* internal register read */ - wb[1] = (uint8_t)(adr >> 8); - if(clockless == 1) wb[1] |= (1 << 7); - wb[2] = (uint8_t)adr; - wb[3] = 0x00; - len = 5; - break; - case CMD_TERMINATE: /* termination */ - wb[1] = 0x00; - wb[2] = 0x00; - wb[3] = 0x00; - len = 5; - break; - case CMD_REPEAT: /* repeat */ - wb[1] = 0x00; - wb[2] = 0x00; - wb[3] = 0x00; - len = 5; - break; - case CMD_RESET: /* reset */ - wb[1] = 0xff; - wb[2] = 0xff; - wb[3] = 0xff; - len = 5; - break; - case CMD_DMA_WRITE: /* dma write */ - case CMD_DMA_READ: /* dma read */ - wb[1] = (uint8_t)(adr >> 16); - wb[2] = (uint8_t)(adr >> 8); - wb[3] = (uint8_t)adr; - wb[4] = (uint8_t)(sz >> 8); - wb[5] = (uint8_t)(sz); - len = 7; - break; - case CMD_DMA_EXT_WRITE: /* dma extended write */ - case CMD_DMA_EXT_READ: /* dma extended read */ - wb[1] = (uint8_t)(adr >> 16); - wb[2] = (uint8_t)(adr >> 8); - wb[3] = (uint8_t)adr; - wb[4] = (uint8_t)(sz >> 16); - wb[5] = (uint8_t)(sz >> 8); - wb[6] = (uint8_t)(sz); - len = 8; - break; - case CMD_INTERNAL_WRITE: /* internal register write */ - wb[1] = (uint8_t)(adr >> 8); - if(clockless == 1) wb[1] |= (1 << 7); - wb[2] = (uint8_t)(adr); - wb[3] = b[3]; - wb[4] = b[2]; - wb[5] = b[1]; - wb[6] = b[0]; - len = 8; - break; - case CMD_SINGLE_WRITE: /* single word write */ - wb[1] = (uint8_t)(adr >> 16); - wb[2] = (uint8_t)(adr >> 8); - wb[3] = (uint8_t)(adr); - wb[4] = b[3]; - wb[5] = b[2]; - wb[6] = b[1]; - wb[7] = b[0]; - len = 9; - break; - default: - result = N_FAIL; - break; - } - - if (result != N_OK) { - return result; - } - - if (!gu8Crc_off) { - wb[len-1] = (crc7(0x7f, (const uint8_t *)&wb[0], len-1)) << 1; - } else { - len -=1; - } - -#define NUM_SKIP_BYTES (1) -#define NUM_RSP_BYTES (2) -#define NUM_DATA_HDR_BYTES (1) -#define NUM_DATA_BYTES (4) -#define NUM_CRC_BYTES (2) -#define NUM_DUMMY_BYTES (3) - - if ((cmd == CMD_RESET) || - (cmd == CMD_TERMINATE) || - (cmd == CMD_REPEAT)) { - len2 = len + (NUM_SKIP_BYTES + NUM_RSP_BYTES + NUM_DUMMY_BYTES); - } else if ((cmd == CMD_INTERNAL_READ) || (cmd == CMD_SINGLE_READ)) { - if (!gu8Crc_off) { - len2 = len + (NUM_RSP_BYTES + NUM_DATA_HDR_BYTES + NUM_DATA_BYTES - + NUM_CRC_BYTES + NUM_DUMMY_BYTES); - } else { - len2 = len + (NUM_RSP_BYTES + NUM_DATA_HDR_BYTES + NUM_DATA_BYTES - + NUM_DUMMY_BYTES); - } - } else { - len2 = len + (NUM_RSP_BYTES + NUM_DUMMY_BYTES); - } -#undef NUM_DUMMY_BYTES - - if(len2 > (sizeof(wb)/sizeof(wb[0]))) { - M2M_ERR("[nmi spi]: spi buffer size too small (%d) (%d)\n", - len2, (sizeof(wb)/sizeof(wb[0]))); - result = N_FAIL; - return result; - } - /* zero spi write buffers. */ - for(wix = len; wix< len2; wix++) { - wb[wix] = 0; - } - rix = len; - - if (nmi_spi_rw(wb, rb, len2) != M2M_SUCCESS) { - M2M_ERR("[nmi spi]: Failed cmd write, bus error...\n"); - result = N_FAIL; - return result; - } - -#if 0 - { - int jj; - printk("--- cnd = %x, len=%d, len2=%d\n", cmd, len, len2); - for(jj=0; jj= len2) break; - if(((jj+1)%16) != 0) { - if((jj%16) == 0) { - printk("wb[%02x]: %02x ", jj, wb[jj]); - } else { - printk("%02x ", wb[jj]); - } - } else { - printk("%02x\n", wb[jj]); - } - } - printk("\n"); - - for(jj=0; jj= len2) break; - if(((jj+1)%16) != 0) { - if((jj%16) == 0) { - printk("rb[%02x]: %02x ", jj, rb[jj]); - } else { - printk("%02x ", rb[jj]); - } - } else { - printk("%02x\n", rb[jj]); - } - } - printk("\n"); - } -#endif - - /** - Command/Control response - **/ - if ((cmd == CMD_RESET) || - (cmd == CMD_TERMINATE) || - (cmd == CMD_REPEAT)) { - rix++; /* skip 1 byte */ - } - - rsp = rb[rix++]; - - - if (rsp != cmd) { - M2M_ERR("[nmi spi]: Failed cmd response, cmd (%02x), resp (%02x)\n", cmd, rsp); - result = N_FAIL; - return result; - } - - /** - State response - **/ - rsp = rb[rix++]; - if (rsp != 0x00) { - M2M_ERR("[nmi spi]: Failed cmd state response state (%02x)\n", rsp); - result = N_FAIL; - return result; - } - - if ((cmd == CMD_INTERNAL_READ) || (cmd == CMD_SINGLE_READ) - || (cmd == CMD_DMA_READ) || (cmd == CMD_DMA_EXT_READ)) { - int retry; - //uint16_t crc1, crc2; - uint8_t crc[2]; - /** - Data Respnose header - **/ - retry = SPI_RESP_RETRY_COUNT; - do { - /* ensure there is room in buffer later to read data and crc */ - if(rix < len2) { - rsp = rb[rix++]; - } else { - retry = 0; - break; - } - if (((rsp >> 4) & 0xf) == 0xf) - break; - } while (retry--); - - if (retry <= 0) { - M2M_ERR("[nmi spi]: Error, data read response (%02x)\n", rsp); - result = N_RESET; - return result; - } - - if ((cmd == CMD_INTERNAL_READ) || (cmd == CMD_SINGLE_READ)) { - /** - Read bytes - **/ - if((rix+3) < len2) { - b[0] = rb[rix++]; - b[1] = rb[rix++]; - b[2] = rb[rix++]; - b[3] = rb[rix++]; - } else { - M2M_ERR("[nmi spi]: buffer overrun when reading data.\n"); - result = N_FAIL; - return result; - } - - if (!gu8Crc_off) { - /** - Read Crc - **/ - if((rix+1) < len2) { - crc[0] = rb[rix++]; - crc[1] = rb[rix++]; - } else { - M2M_ERR("[nmi spi]: buffer overrun when reading crc.\n"); - result = N_FAIL; - return result; - } - } - } else if((cmd == CMD_DMA_READ) || (cmd == CMD_DMA_EXT_READ)) { - int ix; - - /* some data may be read in response to dummy bytes. */ - for(ix=0; (rix < len2) && (ix < sz);) { - b[ix++] = rb[rix++]; - } -#if 0 - if(ix) M2M_INFO("ttt %d %d\n", sz, ix); -#endif - sz -= ix; - - if(sz > 0) { - int nbytes; - - if (sz <= (DATA_PKT_SZ-ix)) { - nbytes = sz; - } else { - nbytes = DATA_PKT_SZ-ix; - } - - /** - Read bytes - **/ - if (nmi_spi_read(&b[ix], nbytes) != M2M_SUCCESS) { - M2M_ERR("[nmi spi]: Failed data block read, bus error...\n"); - result = N_FAIL; - goto _error_; - } - - /** - Read Crc - **/ - if (!gu8Crc_off) { - if (nmi_spi_read(crc, 2) != M2M_SUCCESS) { - M2M_ERR("[nmi spi]: Failed data block crc read, bus error...\n"); - result = N_FAIL; - goto _error_; - } - } - - - ix += nbytes; - sz -= nbytes; - } - - /* if any data in left unread, then read the rest using normal DMA code.*/ - while(sz > 0) { - int nbytes; - - if (sz <= DATA_PKT_SZ) { - nbytes = sz; - } else { - nbytes = DATA_PKT_SZ; - } - - /** - read data response only on the next DMA cycles not - the first DMA since data response header is already - handled above for the first DMA. - **/ - /** - Data Respnose header - **/ - retry = SPI_RESP_RETRY_COUNT; - do { - if (nmi_spi_read(&rsp, 1) != M2M_SUCCESS) { - M2M_ERR("[nmi spi]: Failed data response read, bus error...\n"); - result = N_FAIL; - break; - } - if (((rsp >> 4) & 0xf) == 0xf) - break; - } while (retry--); - - if (result == N_FAIL) - break; - - - /** - Read bytes - **/ - if (nmi_spi_read(&b[ix], nbytes) != M2M_SUCCESS) { - M2M_ERR("[nmi spi]: Failed data block read, bus error...\n"); - result = N_FAIL; - break; - } - - /** - Read Crc - **/ - if (!gu8Crc_off) { - if (nmi_spi_read(crc, 2) != M2M_SUCCESS) { - M2M_ERR("[nmi spi]: Failed data block crc read, bus error...\n"); - result = N_FAIL; - break; - } - } - - ix += nbytes; - sz -= nbytes; - } - } - } -_error_: - return result; -} -#endif -static sint8 spi_data_read(uint8 *b, uint16 sz,uint8 clockless) -{ - sint16 retry, ix, nbytes; - sint8 result = N_OK; - uint8 crc[2]; - uint8 rsp; - - /** - Data - **/ - ix = 0; - do { - if (sz <= DATA_PKT_SZ) - nbytes = sz; - else - nbytes = DATA_PKT_SZ; - - /** - Data Respnose header - **/ - retry = SPI_RESP_RETRY_COUNT; - do { - if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { - M2M_ERR("[nmi spi]: Failed data response read, bus error...\n"); - result = N_FAIL; - break; - } - if (((rsp >> 4) & 0xf) == 0xf) - break; - } while (retry--); - - if (result == N_FAIL) - break; - - if (retry <= 0) { - M2M_ERR("[nmi spi]: Failed data response read...(%02x)\n", rsp); - result = N_FAIL; - break; - } - - /** - Read bytes - **/ - if (M2M_SUCCESS != nmi_spi_read(&b[ix], nbytes)) { - M2M_ERR("[nmi spi]: Failed data block read, bus error...\n"); - result = N_FAIL; - break; - } - if(!clockless) - { - /** - Read Crc - **/ - if (!gu8Crc_off) { - if (M2M_SUCCESS != nmi_spi_read(crc, 2)) { - M2M_ERR("[nmi spi]: Failed data block crc read, bus error...\n"); - result = N_FAIL; - break; - } - } - } - ix += nbytes; - sz -= nbytes; - - } while (sz); - - return result; -} - -static sint8 spi_data_write(uint8 *b, uint16 sz) -{ - sint16 ix; - uint16 nbytes; - sint8 result = 1; - uint8 cmd, order, crc[2] = {0}; - //uint8 rsp; - - /** - Data - **/ - ix = 0; - do { - if (sz <= DATA_PKT_SZ) - nbytes = sz; - else - nbytes = DATA_PKT_SZ; - - /** - Write command - **/ - cmd = 0xf0; - if (ix == 0) { - if (sz <= DATA_PKT_SZ) - order = 0x3; - else - order = 0x1; - } else { - if (sz <= DATA_PKT_SZ) - order = 0x3; - else - order = 0x2; - } - cmd |= order; - if (M2M_SUCCESS != nmi_spi_write(&cmd, 1)) { - M2M_ERR("[nmi spi]: Failed data block cmd write, bus error...\n"); - result = N_FAIL; - break; - } - - /** - Write data - **/ - if (M2M_SUCCESS != nmi_spi_write(&b[ix], nbytes)) { - M2M_ERR("[nmi spi]: Failed data block write, bus error...\n"); - result = N_FAIL; - break; - } - - /** - Write Crc - **/ - if (!gu8Crc_off) { - if (M2M_SUCCESS != nmi_spi_write(crc, 2)) { - M2M_ERR("[nmi spi]: Failed data block crc write, bus error...\n"); - result = N_FAIL; - break; - } - } - - ix += nbytes; - sz -= nbytes; - } while (sz); - - - return result; -} - -/******************************************** - - Spi Internal Read/Write Function - -********************************************/ - -/******************************************** - - Spi interfaces - -********************************************/ - -static sint8 spi_write_reg(uint32 addr, uint32 u32data) -{ - uint8 retry = SPI_RETRY_COUNT; - sint8 result = N_OK; - uint8 cmd = CMD_SINGLE_WRITE; - uint8 clockless = 0; - -_RETRY_: - if (addr <= 0x30) - { - /** - NMC1000 clockless registers. - **/ - cmd = CMD_INTERNAL_WRITE; - clockless = 1; - } - else - { - cmd = CMD_SINGLE_WRITE; - clockless = 0; - } - -#if defined USE_OLD_SPI_SW - result = spi_cmd(cmd, addr, u32data, 4, clockless); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd, write reg (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - - result = spi_cmd_rsp(cmd); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd response, write reg (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - -#else - - result = spi_cmd_complete(cmd, addr, (uint8*)&u32data, 4, clockless); - if (result != N_OK) { - M2M_ERR( "[nmi spi]: Failed cmd, write reg (%08x)...\n", addr); - goto _FAIL_; - } - -#endif -_FAIL_: - if(result != N_OK) - { - nm_bsp_sleep(1); - spi_cmd(CMD_RESET, 0, 0, 0, 0); - spi_cmd_rsp(CMD_RESET); - M2M_ERR("Reset and retry %d %lx %lx\n",retry,addr,u32data); - nm_bsp_sleep(1); - retry--; - if(retry) goto _RETRY_; - } - - return result; -} - -static sint8 nm_spi_write(uint32 addr, uint8 *buf, uint16 size) -{ - sint8 result; - uint8 retry = SPI_RETRY_COUNT; - uint8 cmd = CMD_DMA_EXT_WRITE; - - -_RETRY_: - /** - Command - **/ -#if defined USE_OLD_SPI_SW - //Workaround hardware problem with single byte transfers over SPI bus - if (size == 1) - size = 2; - - result = spi_cmd(cmd, addr, 0, size,0); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd, write block (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - - result = spi_cmd_rsp(cmd); - if (result != N_OK) { - M2M_ERR("[nmi spi ]: Failed cmd response, write block (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } -#else - result = spi_cmd_complete(cmd, addr, NULL, size, 0); - if (result != N_OK) { - M2M_ERR( "[nmi spi]: Failed cmd, write block (%08x)...\n", addr); - goto _FAIL_; - } -#endif - - /** - Data - **/ - result = spi_data_write(buf, size); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed block data write...\n"); - goto _FAIL_; - } - /** - Data RESP - **/ - result = spi_data_rsp(cmd); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed block data write...\n"); - goto _FAIL_; - } - -_FAIL_: - if(result != N_OK) - { - nm_bsp_sleep(1); - spi_cmd(CMD_RESET, 0, 0, 0, 0); - spi_cmd_rsp(CMD_RESET); - M2M_ERR("Reset and retry %d %lx %d\n",retry,addr,size); - nm_bsp_sleep(1); - retry--; - if(retry) goto _RETRY_; - } - - - return result; -} - -static sint8 spi_read_reg(uint32 addr, uint32 *u32data) -{ - uint8 retry = SPI_RETRY_COUNT; - sint8 result = N_OK; - uint8 cmd = CMD_SINGLE_READ; - uint8 tmp[4]; - uint8 clockless = 0; - -_RETRY_: - - if (addr <= 0xff) - { - /** - NMC1000 clockless registers. - **/ - cmd = CMD_INTERNAL_READ; - clockless = 1; - } - else - { - cmd = CMD_SINGLE_READ; - clockless = 0; - } - -#if defined USE_OLD_SPI_SW - result = spi_cmd(cmd, addr, 0, 4, clockless); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd, read reg (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - - result = spi_cmd_rsp(cmd); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd response, read reg (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - - /* to avoid endianess issues */ - result = spi_data_read(&tmp[0], 4, clockless); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed data read...\n"); - goto _FAIL_; - } -#else - result = spi_cmd_complete(cmd, addr, (uint8*)&tmp[0], 4, clockless); - if (result != N_OK) { - M2M_ERR( "[nmi spi]: Failed cmd, read reg (%08x)...\n", addr); - goto _FAIL_; - } - -#endif - - *u32data = tmp[0] | - ((uint32)tmp[1] << 8) | - ((uint32)tmp[2] << 16) | - ((uint32)tmp[3] << 24); - -_FAIL_: - if(result != N_OK) - { - - nm_bsp_sleep(1); - spi_cmd(CMD_RESET, 0, 0, 0, 0); - spi_cmd_rsp(CMD_RESET); - M2M_ERR("Reset and retry %d %lx\n",retry,addr); - nm_bsp_sleep(1); - retry--; - if(retry) goto _RETRY_; - } - - return result; -} - -static sint8 nm_spi_read(uint32 addr, uint8 *buf, uint16 size) -{ - uint8 cmd = CMD_DMA_EXT_READ; - sint8 result; - uint8 retry = SPI_RETRY_COUNT; -#if defined USE_OLD_SPI_SW - uint8 tmp[2]; - uint8 single_byte_workaround = 0; -#endif - -_RETRY_: - - /** - Command - **/ -#if defined USE_OLD_SPI_SW - if (size == 1) - { - //Workaround hardware problem with single byte transfers over SPI bus - size = 2; - single_byte_workaround = 1; - } - result = spi_cmd(cmd, addr, 0, size,0); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd, read block (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - - result = spi_cmd_rsp(cmd); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd response, read block (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - - /** - Data - **/ - if (single_byte_workaround) - { - result = spi_data_read(tmp, size,0); - buf[0] = tmp[0]; - } - else - result = spi_data_read(buf, size,0); - - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed block data read...\n"); - goto _FAIL_; - } -#else - result = spi_cmd_complete(cmd, addr, buf, size, 0); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd, read block (%08x)...\n", addr); - goto _FAIL_; - } -#endif - -_FAIL_: - if(result != N_OK) - { - nm_bsp_sleep(1); - spi_cmd(CMD_RESET, 0, 0, 0, 0); - spi_cmd_rsp(CMD_RESET); - M2M_ERR("Reset and retry %d %lx %d\n",retry,addr,size); - nm_bsp_sleep(1); - retry--; - if(retry) goto _RETRY_; - } - - return result; -} - -/******************************************** - - Bus interfaces - -********************************************/ - -static void spi_init_pkt_sz(void) -{ - uint32 val32; - - /* Make sure SPI max. packet size fits the defined DATA_PKT_SZ. */ - val32 = nm_spi_read_reg(SPI_BASE+0x24); - val32 &= ~(0x7 << 4); - switch(DATA_PKT_SZ) - { - case 256: val32 |= (0 << 4); break; - case 512: val32 |= (1 << 4); break; - case 1024: val32 |= (2 << 4); break; - case 2048: val32 |= (3 << 4); break; - case 4096: val32 |= (4 << 4); break; - case 8192: val32 |= (5 << 4); break; - - } - nm_spi_write_reg(SPI_BASE+0x24, val32); -} - -sint8 nm_spi_reset(void) -{ - spi_cmd(CMD_RESET, 0, 0, 0, 0); - spi_cmd_rsp(CMD_RESET); - return M2M_SUCCESS; -} - -/* -* @fn nm_spi_init -* @brief Initialize the SPI -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_spi_init(void) -{ - uint32 chipid; - uint32 reg = 0; - - - /** - configure protocol - **/ - gu8Crc_off = 0; - - // TODO: We can remove the CRC trials if there is a definite way to reset - // the SPI to it's initial value. - if (!spi_read_reg(NMI_SPI_PROTOCOL_CONFIG, ®)) { - /* Read failed. Try with CRC off. This might happen when module - is removed but chip isn't reset*/ - gu8Crc_off = 1; - M2M_ERR("[nmi spi]: Failed internal read protocol with CRC on, retyring with CRC off...\n"); - if (!spi_read_reg(NMI_SPI_PROTOCOL_CONFIG, ®)){ - // Reaad failed with both CRC on and off, something went bad - M2M_ERR( "[nmi spi]: Failed internal read protocol...\n"); - return 0; - } - } - if(gu8Crc_off == 0) - { - reg &= ~0xc; /* disable crc checking */ - reg &= ~0x70; - reg |= (0x5 << 4); - if (!spi_write_reg(NMI_SPI_PROTOCOL_CONFIG, reg)) { - M2M_ERR( "[nmi spi]: Failed internal write protocol reg...\n"); - return 0; - } - gu8Crc_off = 1; - } - - /** - make sure can read back chip id correctly - **/ - if (!spi_read_reg(0x1000, &chipid)) { - M2M_ERR("[nmi spi]: Fail cmd read chip id...\n"); - return M2M_ERR_BUS_FAIL; - } - - M2M_DBG("[nmi spi]: chipid (%08x)\n", (unsigned int)chipid); - spi_init_pkt_sz(); - - - return M2M_SUCCESS; -} - -/* -* @fn nm_spi_init -* @brief DeInitialize the SPI -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Samer Sarhan -* @date 27 Feb 2015 -* @version 1.0 -*/ -sint8 nm_spi_deinit(void) -{ - gu8Crc_off = 0; - return M2M_SUCCESS; -} - -/* -* @fn nm_spi_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -uint32 nm_spi_read_reg(uint32 u32Addr) -{ - uint32 u32Val; - - spi_read_reg(u32Addr, &u32Val); - - return u32Val; -} - -/* -* @fn nm_spi_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_spi_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) -{ - sint8 s8Ret; - - s8Ret = spi_read_reg(u32Addr,pu32RetVal); - - if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; - else s8Ret = M2M_ERR_BUS_FAIL; - - return s8Ret; -} - -/* -* @fn nm_spi_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_spi_write_reg(uint32 u32Addr, uint32 u32Val) -{ - sint8 s8Ret; - - s8Ret = spi_write_reg(u32Addr, u32Val); - - if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; - else s8Ret = M2M_ERR_BUS_FAIL; - - return s8Ret; -} - -/* -* @fn nm_spi_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u16Sz -* Number of bytes to read. The buffer size must be >= u16Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_spi_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) -{ - sint8 s8Ret; - - s8Ret = nm_spi_read(u32Addr, puBuf, u16Sz); - - if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; - else s8Ret = M2M_ERR_BUS_FAIL; - - return s8Ret; -} - -/* -* @fn nm_spi_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u16Sz -* Number of bytes to write. The buffer size must be >= u16Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_spi_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) -{ - sint8 s8Ret; - - s8Ret = nm_spi_write(u32Addr, puBuf, u16Sz); - - if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; - else s8Ret = M2M_ERR_BUS_FAIL; - - return s8Ret; -} - -#endif diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmspi.h b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmspi.h deleted file mode 100644 index a1bd4a9..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmspi.h +++ /dev/null @@ -1,132 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 SPI protocol bus APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NMSPI_H_ -#define _NMSPI_H_ - -#include "common/include/nm_common.h" - -#ifdef __cplusplus - extern "C" { -#endif - -/** -* @fn nm_spi_init -* @brief Initialize the SPI -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_init(void); -/** -* @fn nm_spi_reset -* @brief reset the SPI -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_reset(void); - -/** -* @fn nm_spi_deinit -* @brief DeInitialize the SPI -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_deinit(void); - -/** -* @fn nm_spi_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -*/ -uint32 nm_spi_read_reg(uint32 u32Addr); - -/** -* @fn nm_spi_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); - -/** -* @fn nm_spi_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_write_reg(uint32 u32Addr, uint32 u32Val); - -/** -* @fn nm_spi_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u16Sz -* Number of bytes to read. The buffer size must be >= u16Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); - -/** -* @fn nm_spi_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u16Sz -* Number of bytes to write. The buffer size must be >= u16Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); - -#ifdef __cplusplus - } -#endif - -#endif /* _NMSPI_H_ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmuart.c b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmuart.c deleted file mode 100644 index 63541cf..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmuart.c +++ /dev/null @@ -1,536 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 UART protocol bus APIs implementation. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "common/include/nm_common.h" - -#ifdef CONF_WINC_USE_UART - -#include "driver/source/nmuart.h" -#include "bus_wrapper/include/nm_bus_wrapper.h" - -#define HDR_SZ 12 - -static uint8 get_cs(uint8* b, uint8 sz){ - int i; - uint8 cs = 0; - for(i = 0; i < sz; i++) - cs ^= b[i]; - return cs; -} - -/* -* @fn nm_uart_sync_cmd -* @brief Check COM Port -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Dina El Sissy -* @date 13 AUG 2012 -* @version 1.0 -*/ -sint8 nm_uart_sync_cmd(void) -{ - tstrNmUartDefault strUart; - sint8 s8Ret = -1; - uint8 b [HDR_SZ+1]; - uint8 rsz; - uint8 onchip = 0; - - /*read reg*/ - b[0] = 0x12; - - rsz = 1; - strUart.pu8Buf = b; - strUart.u16Sz = 1; - - if(M2M_SUCCESS == nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - strUart.u16Sz = rsz; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - M2M_ERR("failed to send cfg bytes\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - if (b[0] == 0x5a) - { - s8Ret = 0; - onchip = 1; - M2M_INFO("Built-in WINC1500 UART Found\n"); - } - else if(b[0] == 0x5b) - { - s8Ret = 0; - onchip = 0; - M2M_INFO("WINC1500 Serial Bridge Found\n"); - } - /*TODO: this should be the way we read the register since the cortus is little endian*/ - /**pu32RetVal = b[0] | ((uint32)b[1] << 8) | ((uint32)b[2] << 16) | ((uint32)b[3] << 24);*/ - if(s8Ret == M2M_SUCCESS) - s8Ret = (sint8)onchip; - return s8Ret; -} - sint8 nm_uart_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) -{ - tstrNmUartDefault strUart; - sint8 s8Ret = M2M_SUCCESS; - uint8 b [HDR_SZ+1]; - uint8 rsz; - - /*read reg*/ - b[0] = 0xa5; - b[1] = 0; - b[2] = 0; - b[3] = 0; - b[4] = 0; - b[5] = (uint8)(u32Addr & 0x000000ff); - b[6] = (uint8)((u32Addr & 0x0000ff00)>>8); - b[7] = (uint8)((u32Addr & 0x00ff0000)>>16); - b[8] = (uint8)((u32Addr & 0xff000000)>>24); - b[9] = 0; - b[10] = 0; - b[11] = 0; - b[12] = 0; - - b[2] = get_cs(&b[1],HDR_SZ); - - rsz = 4; - strUart.pu8Buf = b; - strUart.u16Sz = sizeof(b); - - if(M2M_SUCCESS == nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - if(!nm_bus_get_chip_type()) - { - strUart.u16Sz = 1; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - if(b[0] == 0xAC) - { - M2M_DBG("Successfully sent the command\n"); - strUart.u16Sz = rsz; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - strUart.u16Sz = rsz; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - } - } - else - { - M2M_ERR("failed to send cfg bytes\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - /*TODO: this should be the way we read the register since the cortus is little endian*/ - /**pu32RetVal = b[0] | ((uint32)b[1] << 8) | ((uint32)b[2] << 16) | ((uint32)b[3] << 24);*/ - - *pu32RetVal = ((uint32)b[0] << 24) | ((uint32)b[1] << 16) | ((uint32)b[2] << 8) | b[3]; - - return s8Ret; -} - -/* -* @fn nm_uart_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -* @author Dina El Sissy -* @date 13 AUG 2012 -* @version 1.0 -*/ -uint32 nm_uart_read_reg(uint32 u32Addr) -{ - uint32 val; - nm_uart_read_reg_with_ret(u32Addr , &val); - return val; -} - -/* -* @fn nm_uart_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Dina El Sissy -* @date 13 AUG 2012 -* @version 1.0 -*/ -sint8 nm_uart_write_reg(uint32 u32Addr, uint32 u32Val) -{ - tstrNmUartDefault strUart; - sint8 s8Ret = M2M_SUCCESS; - uint8 b[HDR_SZ+1]; - - /*write reg*/ - b[0] = 0xa5; - b[1] = 1; - b[2] = 0; - b[3] = 0; - b[4] = 0; - b[5] = (uint8)(u32Addr & 0x000000ff); - b[6] = (uint8)((u32Addr & 0x0000ff00)>>8); - b[7] = (uint8)((u32Addr & 0x00ff0000)>>16); - b[8] = (uint8)((u32Addr & 0xff000000)>>24); - b[9] = (uint8)(u32Val & 0x000000ff); - b[10] = (uint8)((u32Val & 0x0000ff00)>>8); - b[11] = (uint8)((u32Val & 0x00ff0000)>>16); - b[12] = (uint8)((u32Val & 0xff000000)>>24); - - b[2] = get_cs(&b[1],HDR_SZ); - - get_cs(&b[1],HDR_SZ); - - strUart.pu8Buf = b; - strUart.u16Sz = sizeof(b); - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - else - { - if(!nm_bus_get_chip_type()) - { - //check for the ack from the SAMD21 for the packet reception. - strUart.u16Sz = 1; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - if(b[0] == 0xAC) - { - M2M_DBG("Successfully sent the reg write command\n"); - } - else - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - } - - return s8Ret; -} - - -/** -* @fn nm_uart_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u16Sz -* Number of bytes to read. The buffer size must be >= u16Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Dina El Sissy -* @date 13 AUG 2012 -* @version 1.0 -*/ -sint8 nm_uart_read_block(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz) -{ - tstrNmUartDefault strUart; - sint8 s8Ret = M2M_SUCCESS; - uint8 au8Buf[HDR_SZ+1]; - - au8Buf[0] = 0xa5; - au8Buf[1] = 2; - au8Buf[2] = 0; - au8Buf[3] = (uint8)(u16Sz & 0x00ff); - au8Buf[4] = (uint8)((u16Sz & 0xff00)>>8); - au8Buf[5] = (uint8)(u32Addr & 0x000000ff); - au8Buf[6] = (uint8)((u32Addr & 0x0000ff00)>>8); - au8Buf[7] = (uint8)((u32Addr & 0x00ff0000)>>16); - au8Buf[8] = (uint8)((u32Addr & 0xff000000)>>24); - au8Buf[9] = 0; - au8Buf[10] = 0; - au8Buf[11] = 0; - au8Buf[12] = 0; - - au8Buf[2] = get_cs(&au8Buf[1],HDR_SZ); - - strUart.pu8Buf = au8Buf; - strUart.u16Sz = sizeof(au8Buf); - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - else - { - if(!nm_bus_get_chip_type()) - { - //check for the ack from the SAMD21 for the packet reception. - strUart.u16Sz = 1; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - if(au8Buf[0] == 0xAC) - { - M2M_DBG("Successfully sent the block read command\n"); - strUart.pu8Buf = pu8Buf; - strUart.u16Sz = u16Sz; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - M2M_ERR("read error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - M2M_ERR("write error (Error sending the block read command)\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - strUart.pu8Buf = pu8Buf; - strUart.u16Sz = u16Sz; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - M2M_ERR("read error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - } - - return s8Ret; -} - -/** -* @fn nm_uart_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u16Sz -* Number of bytes to write. The buffer size must be >= u16Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Dina El Sissy -* @date 13 AUG 2012 -* @version 1.0 -*/ -sint8 nm_uart_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) -{ - tstrNmUartDefault strUart; - sint8 s8Ret = M2M_SUCCESS; - static uint8 au8Buf[HDR_SZ+1]; - - au8Buf[0] = 0xa5; - au8Buf[1] = 3; - au8Buf[2] = 0; - au8Buf[3] = (uint8)(u16Sz & 0x00ff); - au8Buf[4] = (uint8)((u16Sz & 0xff00)>>8); - au8Buf[5] = (uint8)(u32Addr & 0x000000ff); - au8Buf[6] = (uint8)((u32Addr & 0x0000ff00)>>8); - au8Buf[7] = (uint8)((u32Addr & 0x00ff0000)>>16); - au8Buf[8] = (uint8)((u32Addr & 0xff000000)>>24); - au8Buf[9] = 0; - au8Buf[10] = 0; - au8Buf[11] = 0; - au8Buf[12] = 0; - - au8Buf[2] = get_cs(&au8Buf[1],HDR_SZ); - - strUart.pu8Buf = au8Buf; - strUart.u16Sz = sizeof(au8Buf); - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - else - { - if(!nm_bus_get_chip_type()) - { - //check for the ack from the SAMD21 for the packet reception. - strUart.u16Sz = 1; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - if(au8Buf[0] == 0xAC) - { - M2M_DBG("Successfully sent the block Write command\n"); - strUart.pu8Buf = puBuf; - strUart.u16Sz = u16Sz; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - else - { - //check for the ack from the SAMD21 for the payload reception. - strUart.pu8Buf = au8Buf; - strUart.u16Sz = 1; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - if(au8Buf[0] == 0xAC) - { - M2M_DBG("Successfully sent the data payload\n"); - } - else - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - } - else - { - M2M_ERR("write error (Error sending the block write command)\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - strUart.pu8Buf = puBuf; - strUart.u16Sz = u16Sz; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - } - return s8Ret; -} - -/** -* @fn nm_uart_reconfigure -* @brief Reconfigures the UART interface -* @param [in] ptr -* Pointer to a DWORD containing baudrate at this moment. -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Viswanathan Murugesan -* @date 22 OCT 2014 -* @version 1.0 -*/ -sint8 nm_uart_reconfigure(void *ptr) -{ - tstrNmUartDefault strUart; - sint8 s8Ret = M2M_SUCCESS; - uint8 b[HDR_SZ+1]; - - /*write reg*/ - b[0] = 0xa5; - b[1] = 5; - b[2] = 0; - b[3] = 0; - b[4] = 0; - b[5] = 0; - b[6] = 0; - b[7] = 0; - b[8] = 0; - b[9] = (uint8)((*(unsigned long *)ptr) & 0x000000ff); - b[10] = (uint8)(((*(unsigned long *)ptr) & 0x0000ff00)>>8); - b[11] = (uint8)(((*(unsigned long *)ptr) & 0x00ff0000)>>16); - b[12] = (uint8)(((*(unsigned long *)ptr) & 0xff000000)>>24); - - b[2] = get_cs(&b[1],HDR_SZ); - - get_cs(&b[1],HDR_SZ); - - strUart.pu8Buf = b; - strUart.u16Sz = sizeof(b); - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - else - { - if(!nm_bus_get_chip_type()) - { - //check for the ack from the SAMD21 for the packet reception. - strUart.u16Sz = 1; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - if(b[0] == 0xAC) - { - M2M_DBG("Successfully sent the UART reconfigure command\n"); - } - else - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - } - - return s8Ret; -} -#endif -/* EOF */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmuart.h b/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmuart.h deleted file mode 100644 index 8f07d39..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/driver/source/nmuart.h +++ /dev/null @@ -1,118 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 UART protocol bus APIs implementation. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NMUART_H_ -#define _NMUART_H_ - -#include "common/include/nm_common.h" - -/* -* @fn nm_uart_sync_cmd -* @brief Check COM Port -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_uart_sync_cmd(void); -/** -* @fn nm_uart_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -*/ -uint32 nm_uart_read_reg(uint32 u32Addr); - -/** -* @fn nm_uart_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_uart_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); - -/** -* @fn nm_uart_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_uart_write_reg(uint32 u32Addr, uint32 u32Val); - -/** -* @fn nm_uart_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u16Sz -* Number of bytes to read. The buffer size must be >= u16Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_uart_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); - -/** -* @fn nm_uart_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u16Sz -* Number of bytes to write. The buffer size must be >= u16Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_uart_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); - -/** -* @fn nm_uart_reconfigure -* @brief Reconfigures the UART interface -* @param [in] ptr -* Pointer to a DWORD containing baudrate at this moment. -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_uart_reconfigure(void *ptr); -#endif /* _NMI2C_H_ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h b/feather_sensor_lte/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h deleted file mode 100644 index 933ad67..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h +++ /dev/null @@ -1,461 +0,0 @@ -/** - * - * \file - * - * \brief BSD compatible socket interface internal types. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -#ifndef __M2M_SOCKET_HOST_IF_H__ -#define __M2M_SOCKET_HOST_IF_H__ - - -#ifdef __cplusplus -extern "C" { -#endif - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#ifndef _BOOT_ -#ifndef _FIRMWARE_ -#include "socket/include/socket.h" -#else -#include "m2m_types.h" -#endif -#endif - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/* - * HOSTNAME_MAX_SIZE is defined here and also in host_drv/socket/include/socket.h - * The two definitions must match. -*/ -#ifdef _FIRMWARE_ -#define HOSTNAME_MAX_SIZE (64) -#endif - -#define SSL_MAX_OPT_LEN HOSTNAME_MAX_SIZE - - - -#define SOCKET_CMD_INVALID 0x00 -/*!< - Invlaid Socket command value. -*/ - - -#define SOCKET_CMD_BIND 0x41 -/*!< - Socket Binding command value. -*/ - - -#define SOCKET_CMD_LISTEN 0x42 -/*!< - Socket Listening command value. -*/ - - -#define SOCKET_CMD_ACCEPT 0x43 -/*!< - Socket Accepting command value. -*/ - - -#define SOCKET_CMD_CONNECT 0x44 -/*!< - Socket Connecting command value. -*/ - - -#define SOCKET_CMD_SEND 0x45 -/*!< - Socket send command value. -*/ - - -#define SOCKET_CMD_RECV 0x46 -/*!< - Socket Recieve command value. -*/ - - -#define SOCKET_CMD_SENDTO 0x47 -/*!< - Socket sendTo command value. -*/ - - -#define SOCKET_CMD_RECVFROM 0x48 -/*!< - Socket RecieveFrom command value. -*/ - - -#define SOCKET_CMD_CLOSE 0x49 -/*!< - Socket Close command value. -*/ - - -#define SOCKET_CMD_DNS_RESOLVE 0x4A -/*!< - Socket DNS Resolve command value. -*/ - - -#define SOCKET_CMD_SSL_CONNECT 0x4B -/*!< - SSL-Socket Connect command value. -*/ - - -#define SOCKET_CMD_SSL_SEND 0x4C -/*!< - SSL-Socket Send command value. -*/ - - -#define SOCKET_CMD_SSL_RECV 0x4D -/*!< - SSL-Socket Recieve command value. -*/ - - -#define SOCKET_CMD_SSL_CLOSE 0x4E -/*!< - SSL-Socket Close command value. -*/ - - -#define SOCKET_CMD_SET_SOCKET_OPTION 0x4F -/*!< - Set Socket Option command value. -*/ - - -#define SOCKET_CMD_SSL_CREATE 0x50 -/*!< -*/ - - -#define SOCKET_CMD_SSL_SET_SOCK_OPT 0x51 -/*!< -*/ - - -#define SOCKET_CMD_PING 0x52 -/*!< -*/ - - -#define SOCKET_CMD_SSL_SET_CS_LIST 0x53 -/*!< - Recommend instead using @ref M2M_SSL_REQ_SET_CS_LIST and - associated response @ref M2M_SSL_RESP_SET_CS_LIST -*/ - - -#define SOCKET_CMD_SSL_BIND 0x54 -/*!< -*/ - - -#define SOCKET_CMD_SSL_EXP_CHECK 0x55 -/*!< -*/ - - - -#define PING_ERR_SUCCESS 0 -#define PING_ERR_DEST_UNREACH 1 -#define PING_ERR_TIMEOUT 2 - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -/*! -* @brief -*/ -typedef struct{ - uint16 u16Family; - uint16 u16Port; - uint32 u32IPAddr; -}tstrSockAddr; - - -typedef sint8 SOCKET; -typedef tstrSockAddr tstrUIPSockAddr; - - - -/*! -@struct \ - tstrDnsReply - -@brief - DNS Reply, contains hostName and HostIP. -*/ -typedef struct{ - char acHostName[HOSTNAME_MAX_SIZE]; - uint32 u32HostIP; -}tstrDnsReply; - - -/*! -@brief -*/ -typedef struct{ - tstrSockAddr strAddr; - SOCKET sock; - uint8 u8Void; - uint16 u16SessionID; -}tstrBindCmd; - - -/*! -@brief -*/ -typedef struct{ - SOCKET sock; - sint8 s8Status; - uint16 u16SessionID; -}tstrBindReply; - - -/*! -* @brief -*/ -typedef struct{ - SOCKET sock; - uint8 u8BackLog; - uint16 u16SessionID; -}tstrListenCmd; - - -/*! -@struct \ - tstrSocketRecvMsg - -@brief Socket recv status. - - It is passed to the APPSocketEventHandler with SOCKET_MSG_RECV or SOCKET_MSG_RECVFROM message type - in a response to a user call to the recv or recvfrom. - If the received data from the remote peer is larger than the USER Buffer size (given at recv call), the data is - delivered to the user in a number of consecutive chunks according to the USER Buffer size. -*/ -typedef struct{ - SOCKET sock; - sint8 s8Status; - uint16 u16SessionID; -}tstrListenReply; - - -/*! -* @brief -*/ -typedef struct{ - tstrSockAddr strAddr; - SOCKET sListenSock; - SOCKET sConnectedSock; - uint16 u16AppDataOffset; - /*!< - In further packet send requests the host interface should put the user application - data at this offset in the allocated shared data packet. - */ -}tstrAcceptReply; - - -/*! -* @brief -*/ -typedef struct{ - tstrSockAddr strAddr; - SOCKET sock; - uint8 u8SslFlags; - uint16 u16SessionID; -}tstrConnectCmd; - - -/*! -@struct \ - tstrConnectReply - -@brief - Connect Reply, contains sock number and error value -*/ -typedef struct{ - SOCKET sock; - sint8 s8Error; - uint16 u16AppDataOffset; - /*!< - In further packet send requests the host interface should put the user application - data at this offset in the allocated shared data packet. - */ -}tstrConnectReply; - - -/*! -@brief -*/ -typedef struct{ - SOCKET sock; - uint8 u8Void; - uint16 u16DataSize; - tstrSockAddr strAddr; - uint16 u16SessionID; - uint16 u16Void; -}tstrSendCmd; - - -/*! -@struct \ - tstrSendReply - -@brief - Send Reply, contains socket number and number of sent bytes. -*/ -typedef struct{ - SOCKET sock; - uint8 u8Void; - sint16 s16SentBytes; - uint16 u16SessionID; - uint16 u16Void; -}tstrSendReply; - - -/*! -* @brief -*/ -typedef struct{ - uint32 u32Timeoutmsec; - SOCKET sock; - uint8 u8Void; - uint16 u16SessionID; -}tstrRecvCmd; - - -/*! -@struct -@brief -*/ -typedef struct{ - tstrSockAddr strRemoteAddr; - sint16 s16RecvStatus; - uint16 u16DataOffset; - SOCKET sock; - uint8 u8Void; - uint16 u16SessionID; -}tstrRecvReply; - - -/*! -* @brief -*/ -typedef struct{ - uint32 u32OptionValue; - SOCKET sock; - uint8 u8Option; - uint16 u16SessionID; -}tstrSetSocketOptCmd; - - -typedef struct{ - SOCKET sslSock; - uint8 __PAD24__[3]; -}tstrSSLSocketCreateCmd; - - -/*! -* @brief -*/ -typedef struct{ - SOCKET sock; - uint8 u8Option; - uint16 u16SessionID; - uint32 u32OptLen; - uint8 au8OptVal[SSL_MAX_OPT_LEN]; -}tstrSSLSetSockOptCmd; - - -/*! -*/ -typedef struct{ - uint32 u32DestIPAddr; - uint32 u32CmdPrivate; - uint16 u16PingCount; - uint8 u8TTL; - uint8 __PAD8__; -}tstrPingCmd; - - -typedef struct{ - uint32 u32IPAddr; - uint32 u32CmdPrivate; - uint32 u32RTT; - uint16 u16Success; - uint16 u16Fail; - uint8 u8ErrorCode; - uint8 __PAD24__[3]; -}tstrPingReply; - - -/*! -@struct\ - tstrSslCertExpSettings - -@brief SSL Certificate Expiry Validation Settings - -@sa tenuSslCertExpSettings -*/ -typedef struct{ - uint32 u32CertExpValidationOpt; - /*!< - See @tenuSslCertExpSettings for possible values. - */ -}tstrSslCertExpSettings; - - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __M2M_SOCKET_HOST_IF_H__ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/socket/include/socket.h b/feather_sensor_lte/libraries/WiFi101/src/socket/include/socket.h deleted file mode 100644 index 837959a..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/socket/include/socket.h +++ /dev/null @@ -1,2065 +0,0 @@ -/** - * - * \file - * - * \brief WINC BSD compatible Socket Interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef __SOCKET_H__ -#define __SOCKET_H__ - -#ifdef __cplusplus -extern "C" { -#endif - -/** \defgroup SocketHeader Socket - * BSD compatible socket interface beftween the host layer and the network - * protocol stacks in the firmware. - * These functions are used by the host application to send or receive - * packets and to do other socket operations. - */ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "common/include/nm_common.h" -#include "driver/include/m2m_types.h" - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/** - * @defgroup SocketDefines Defines - * @ingroup SocketHeader - */ - -/** @defgroup IPDefines TCP/IP Defines - * @ingroup SocketDefines - * The following list of macros are used to define constants used throughout the socket layer. - * @{ - */ - -/* - * HOSTNAME_MAX_SIZE is defined here and also in host_drv/socket/include/m2m_socket_host_if.h - * The two definitions must match. -*/ -#define HOSTNAME_MAX_SIZE 64 -/*!< - Maximum allowed size for a host domain name passed to the function gethostbyname @ref gethostbyname. - command value. Used with the setsockopt function. - -*/ - -#define SOCKET_BUFFER_MAX_LENGTH 1400 -/*!< - Maximum allowed size for a socket data buffer. Used with @ref send socket - function to ensure that the buffer sent is within the allowed range. -*/ - -#define AF_INET 2 -/*!< - The AF_INET is the address family used for IPv4. An IPv4 transport address is specified with the @ref sockaddr_in structure. - (It is the only supported type for the current implementation.) -*/ - - -#define SOCK_STREAM 1 -/*!< - One of the IPv4 supported socket types for reliable connection-oriented stream connection. - Passed to the @ref socket function for the socket creation operation. -*/ - -#define SOCK_DGRAM 2 -/*!< - One of the IPv4 supported socket types for unreliable connectionless datagram connection. - Passed to the @ref socket function for the socket creation operation. -*/ - - -#define SOCKET_FLAGS_SSL 0x01 -/*!< - This flag shall be passed to the socket API for SSL session. -*/ - -#define TCP_SOCK_MAX (7) -/*!< - Maximum number of simultaneous TCP sockets. -*/ - -#define UDP_SOCK_MAX 4 -/*!< - Maximum number of simultaneous UDP sockets. -*/ - -#define MAX_SOCKET (TCP_SOCK_MAX + UDP_SOCK_MAX) -/*!< - Maximum number of Sockets. -*/ - -#define SOL_SOCKET 1 -/*!< - Socket option. - Used with the @ref setsockopt function -*/ - -#define SOL_SSL_SOCKET 2 -/*!< - SSL Socket option level. - Used with the @ref setsockopt function -*/ - -#define SO_SET_UDP_SEND_CALLBACK 0x00 -/*!< - Socket option used by the application to enable/disable - the use of UDP send callbacks. - Used with the @ref setsockopt function. -*/ - -#define IP_ADD_MEMBERSHIP 0x01 -/*!< - Set Socket Option Add Membership command value (to join a multicast group). - Used with the @ref setsockopt function. -*/ - - -#define IP_DROP_MEMBERSHIP 0x02 -/*!< - Set Socket Option Drop Membership command value (to leave a multicast group). - Used with the @ref setsockopt function. -*/ - //@} - - - -/** - * @defgroup TLSDefines TLS Defines - * @ingroup SocketDefines - */ - - - -/** @defgroup SSLSocketOptions TLS Socket Options - * @ingroup TLSDefines - * The following list of macros are used to define SSL Socket options. - * @{ - * @sa setsockopt - */ - -#define SO_SSL_BYPASS_X509_VERIF 0x01 -/*!< - Allow an opened SSL socket to bypass the X509 certificate - verification process. - It is highly required NOT to use this socket option in production - software applications. It is supported for debugging and testing - purposes. - The option value should be casted to int type and it is handled - as a boolean flag. -*/ - - -#define SO_SSL_SNI 0x02 -/*!< - Set the Server Name Indicator (SNI) for an SSL socket. The - SNI is a NULL terminated string containing the server name - associated with the connection. It must not exceed the size - of HOSTNAME_MAX_SIZE. -*/ - - -#define SO_SSL_ENABLE_SESSION_CACHING 0x03 -/*!< - This option allow the TLS to cache the session information for fast - TLS session establishment in future connections using the - TLS Protocol session resume features. -*/ - - -#define SO_SSL_ENABLE_SNI_VALIDATION 0x04 -/*!< - Enable SNI validation against the server's certificate subject - common name. If there is no SNI provided (via the SO_SSL_SNI - option), setting this option does nothing. -*/ - - -//@} - - - -/** @defgroup LegacySSLCipherSuite Legacy names for TLS Cipher Suite IDs - * @ingroup TLSDefines - * The following list of macros MUST NOT be used. Instead use the new names under SSLCipherSuiteID - * @sa sslSetActiveCipherSuites - * @{ - */ - -#define SSL_ENABLE_RSA_SHA_SUITES 0x01 -/*!< - Enable RSA Hmac_SHA based Cipher suites. For example, - TLS_RSA_WITH_AES_128_CBC_SHA -*/ - - -#define SSL_ENABLE_RSA_SHA256_SUITES 0x02 -/*!< - Enable RSA Hmac_SHA256 based Cipher suites. For example, - TLS_RSA_WITH_AES_128_CBC_SHA256 -*/ - - -#define SSL_ENABLE_DHE_SHA_SUITES 0x04 -/*!< - Enable DHE Hmac_SHA based Cipher suites. For example, - TLS_DHE_RSA_WITH_AES_128_CBC_SHA -*/ - - -#define SSL_ENABLE_DHE_SHA256_SUITES 0x08 -/*!< - Enable DHE Hmac_SHA256 based Cipher suites. For example, - TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 -*/ - - -#define SSL_ENABLE_RSA_GCM_SUITES 0x10 -/*!< - Enable RSA AEAD based Cipher suites. For example, - TLS_RSA_WITH_AES_128_GCM_SHA256 -*/ - - -#define SSL_ENABLE_DHE_GCM_SUITES 0x20 -/*!< - Enable DHE AEAD based Cipher suites. For example, - TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 -*/ - - -#define SSL_ENABLE_ALL_SUITES 0x0000003F -/*!< - Enable all possible supported cipher suites. -*/ - -//@} - - - -/** @defgroup SSLCipherSuiteID TLS Cipher Suite IDs - * @ingroup TLSDefines - * The following list of macros defined the list of supported TLS Cipher suites. - * Each MACRO defines a single Cipher suite. - * @sa m2m_ssl_set_active_ciphersuites - * @{ - */ - -#define SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA NBIT0 -#define SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 NBIT1 -#define SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA NBIT2 -#define SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 NBIT3 -#define SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 NBIT4 -#define SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 NBIT5 -#define SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA NBIT6 -#define SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 NBIT7 -#define SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA NBIT8 -#define SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 NBIT9 -#define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA NBIT10 -#define SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA NBIT11 -#define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 NBIT12 -#define SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 NBIT13 -#define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 NBIT14 -#define SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 NBIT15 - - - -#define SSL_ECC_ONLY_CIPHERS \ -(\ - SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 \ -) -/*!< - All ciphers that use ECC crypto only. This execuldes ciphers that use RSA. They use ECDSA instead. - These ciphers are turned off by default at startup. - The application may enable them if it has an ECC math engine (like ATECC508). -*/ -#define SSL_ECC_ALL_CIPHERS \ -(\ - SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA | \ - SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 | \ - SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 \ -) -/*!< - All supported ECC Ciphers including those ciphers that depend on RSA and ECC. - These ciphers are turned off by default at startup. - The application may enable them if it has an ECC math engine (like ATECC508). -*/ - -#define SSL_NON_ECC_CIPHERS_AES_128 \ -(\ - SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA | \ - SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA | \ - SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 | \ - SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 \ -) -/*!< - All supported AES-128 Ciphers (ECC ciphers are not counted). This is the default active group after startup. -*/ - - -#define SSL_ECC_CIPHERS_AES_256 \ -(\ - SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA \ -) -/*!< - ECC AES-256 supported ciphers. -*/ - - -#define SSL_NON_ECC_CIPHERS_AES_256 \ -(\ - SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA | \ - SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 | \ - SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA | \ - SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 \ -) -/*!< - AES-256 Ciphers. - This group is disabled by default at startup because the WINC1500 HW Accelerator - supports only AES-128. If the application needs to force AES-256 cipher support, - it could enable them (or any of them) explicitly by calling sslSetActiveCipherSuites. -*/ - - -#define SSL_CIPHER_ALL \ -(\ - SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA | \ - SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA | \ - SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 | \ - SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 | \ - SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA | \ - SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 | \ - SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA | \ - SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 | \ - SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA | \ - SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 | \ - SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 | \ - SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA \ -) -/*!< - Turn On All TLS Ciphers. -*/ - - - //@} - - - - -/************** -Socket Errors -**************/ -/**@defgroup SocketErrorCode Error Codes - * @ingroup SocketHeader - * The following list of macros are used to define the possible error codes returned as a result of a call to a socket function. - * Errors are listed in numerical order with the error macro name. - * @{ - */ -#define SOCK_ERR_NO_ERROR 0 -/*!< - Successful socket operation -*/ - - -#define SOCK_ERR_INVALID_ADDRESS -1 -/*!< - Socket address is invalid. The socket operation cannot be completed successfully without specifying a specific address - For example: bind is called without specifying a port number -*/ - - -#define SOCK_ERR_ADDR_ALREADY_IN_USE -2 -/*!< - Socket operation cannot bind on the given address. With socket operations, only one IP address per socket is permitted. - Any attempt for a new socket to bind with an IP address already bound to another open socket, - will return the following error code. States that bind operation failed. -*/ - - -#define SOCK_ERR_MAX_TCP_SOCK -3 -/*!< - Exceeded the maximum number of TCP sockets. A maximum number of TCP sockets opened simultaneously is defined through TCP_SOCK_MAX. - It is not permitted to exceed that number at socket creation. Identifies that @ref socket operation failed. -*/ - - -#define SOCK_ERR_MAX_UDP_SOCK -4 -/*!< - Exceeded the maximum number of UDP sockets. A maximum number of UDP sockets opened simultaneously is defined through UDP_SOCK_MAX. - It is not permitted to exceed that number at socket creation. Identifies that @ref socket operation failed -*/ - - -#define SOCK_ERR_INVALID_ARG -6 -/*!< - An invalid argument is passed to a function. -*/ - - -#define SOCK_ERR_MAX_LISTEN_SOCK -7 -/*!< - Exceeded the maximum number of TCP passive listening sockets. - Identifies Identifies that @ref listen operation failed. -*/ - - -#define SOCK_ERR_INVALID -9 -/*!< - The requested socket operation is not valid in the - current socket state. - For example: @ref accept is called on a TCP socket before @ref bind or @ref listen. -*/ - - -#define SOCK_ERR_ADDR_IS_REQUIRED -11 -/*!< - Destination address is required. Failure to provide the socket address required for the socket operation to be completed. - It is generated as an error to the @ref sendto function when the address required to send the data to is not known. -*/ - - -#define SOCK_ERR_CONN_ABORTED -12 -/*!< - The socket is closed by the peer. The local socket is - closed also. -*/ - - -#define SOCK_ERR_TIMEOUT -13 -/*!< - The socket pending operation has Timedout. -*/ - - -#define SOCK_ERR_BUFFER_FULL -14 -/*!< - No buffer space available to be used for the requested socket operation. -*/ - -#ifdef _NM_BSP_BIG_END - -#define _htonl(m) (m) -#define _htons(A) (A) - -#else - -#define _htonl(m) \ - (uint32)(((uint32)(m << 24)) | ((uint32)((m & 0x0000FF00) << 8)) | ((uint32)((m & 0x00FF0000) >> 8)) | ((uint32)(m >> 24))) -/*!< - Convert a 4-byte integer from the host representation to the Network byte order representation. -*/ - - -#define _htons(A) (uint16)((((uint16) (A)) << 8) | (((uint16) (A)) >> 8)) -/*!< - Convert a 2-byte integer (short) from the host representation to the Network byte order representation. -*/ - - -#endif - - -#define _ntohl _htonl -/*!< - Convert a 4-byte integer from the Network byte order representation to the host representation . -*/ - - -#define _ntohs _htons -/*!< - Convert a 2-byte integer from the Network byte order representation to the host representation . -*/ - //@} - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/** @defgroup SocketEnums DataTypes - * @ingroup SocketHeader - * Specific Enumeration-typedefs used for socket operations - * @{ */ - -/*! -@typedef \ - SOCKET - -@brief - Definition for socket handler data type. - Socket ID,used with all socket operations to uniquely identify the socket handler. - Such an ID is uniquely assigned at socket creation when calling @ref socket operation. -*/ -typedef sint8 SOCKET; - - - -/*! -@struct \ - in_addr - -@brief - IPv4 address representation. - - This structure is used as a placeholder for IPV4 address in other structures. -@see - sockaddr_in -*/ -typedef struct{ - uint32 s_addr; - /*!< - Network Byte Order representation of the IPv4 address. For example, - the address "192.168.0.10" is represented as 0x0A00A8C0. - */ -}in_addr; - - -/*! -@struct \ - sockaddr - -@brief - Generic socket address structure. - -@see - sockaddr_in -*/ -struct sockaddr{ - uint16 sa_family; - /*!< -Socket address family. - */ - uint8 sa_data[14]; - /*!< - Maximum size of all the different socket address structures. - */ -}; - - -/*! -@struct \ - sockaddr_in - -@brief - Socket address structure for IPV4 addresses. Used to specify socket address information to which to connect to. - Can be cast to @ref sockaddr structure. -*/ -struct sockaddr_in{ - uint16 sin_family; - /*!< - Specifies the address family(AF). - Members of AF_INET address family are IPv4 addresses. - Hence,the only supported value for this is AF_INET. - */ - uint16 sin_port; - /*!< - Port number of the socket. - Network sockets are identified by a pair of IP addresses and port number. - It must be set in the Network Byte Order format , @ref _htons (e.g. _htons(80)). - Can NOT have zero value. - */ - in_addr sin_addr; - /*!< - IP Address of the socket. - The IP address is of type @ref in_addr structure. - Can be set to "0" to accept any IP address for server operation. non zero otherwise. - */ - uint8 sin_zero[8]; - /*!< - Padding to make structure the same size as @ref sockaddr. - */ -}; - //@} -/**@defgroup AsyncCalback Asynchronous Events - * @ingroup SocketEnums - * Specific Enumeration used for asynchronous operations - * @{ */ -/*! -@enum \ - tenuSocketCallbackMsgType - -@brief - Asynchronous APIs, make use of callback functions, in-order to return back the results once the corresponding socket operation is completed. - Hence resuming the normal execution of the application code while the socket operation returns the results. - Callback functions expect event messages to be passed in, in-order to identify the operation they're returning the results for. - The following enum identifies the type of events that are received in the callback function. - - Application Use: - In order for application developers to handle the pending events from the network controller through the callback functions. - A function call must be made to the function @ref m2m_wifi_handle_events at least once for each socket operation. - -@see - bind - listen - accept - connect - send - recv - -*/ -typedef enum{ - SOCKET_MSG_BIND = 1, - /*!< - Bind socket event. - */ - SOCKET_MSG_LISTEN, - /*!< - Listen socket event. - */ - SOCKET_MSG_DNS_RESOLVE, - /*!< - DNS Resolution event. - */ - SOCKET_MSG_ACCEPT, - /*!< - Accept socket event. - */ - SOCKET_MSG_CONNECT, - /*!< - Connect socket event. - */ - SOCKET_MSG_RECV, - /*!< - Receive socket event. - */ - SOCKET_MSG_SEND, - /*!< - Send socket event. - */ - SOCKET_MSG_SENDTO, - /*!< - sendto socket event. - */ - SOCKET_MSG_RECVFROM - /*!< - Recvfrom socket event. - */ -}tenuSocketCallbackMsgType; - - -/*! -@struct \ - tstrSocketBindMsg - -@brief Socket bind status. - - An asynchronous call to the @ref bind socket operation, returns information through this structure in response. - This structure together with the event @ref SOCKET_MSG_BIND are passed in paramters to the callback function. -@see - bind - -*/ -typedef struct{ - sint8 status; - /*!< - The result of the bind operation. - Holding a value of ZERO for a successful bind or otherwise a negative - error code corresponding to the type of error. - */ -}tstrSocketBindMsg; - - -/*! -@struct \ - tstrSocketListenMsg - -@brief Socket listen status. - - Socket listen information is returned through this structure in response to the asynchronous call to the @ref listen function. - This structure together with the event @ref SOCKET_MSG_LISTEN are passed-in parameters to the callback function. -@see - listen -*/ -typedef struct{ - sint8 status; - /*!< - Holding a value of ZERO for a successful listen or otherwise a negative - error code corresponding to the type of error. - */ -}tstrSocketListenMsg; - - - -/*! -@struct \ - tstrSocketAcceptMsg - -@brief Socket accept status. - - Socket accept information is returned through this structure in response to the asynchronous call to the @ref accept function. - This structure together with the event @ref SOCKET_MSG_ACCEPT are passed-in parameters to the callback function. -*/ -typedef struct{ - SOCKET sock; - /*!< - On a successful @ref accept operation, the return information is the socket ID for the accepted connection with the remote peer. - Otherwise a negative error code is returned to indicate failure of the accept operation. - */ - struct sockaddr_in strAddr; - /*!< - Socket address structure for the remote peer. - */ -}tstrSocketAcceptMsg; - - -/*! -@struct \ - tstrSocketConnectMsg - -@brief Socket connect status. - - Socket connect information is returned through this structure in response to the asynchronous call to the @ref connect socket function. - This structure together with the event @ref SOCKET_MSG_CONNECT are passed-in parameters to the callback function. -*/ -typedef struct{ - SOCKET sock; - /*!< - Socket ID referring to the socket passed to the connect function call. - */ - sint8 s8Error; - /*!< - Connect error code. - Holding a value of ZERO for a successful connect or otherwise a negative - error code corresponding to the type of error. - */ -}tstrSocketConnectMsg; - - -/*! -@struct \ - tstrSocketRecvMsg - -@brief Socket recv status. - - Socket receive information is returned through this structure in response to the asynchronous call to the recv or recvfrom socket functions. - This structure together with the events @ref SOCKET_MSG_RECV or @ref SOCKET_MSG_RECVFROM are passed-in parameters to the callback function. -@remark - In case the received data from the remote peer is larger than the USER buffer size defined during the asynchronous call to the @ref recv function, the data is - delivered to the user in a number of consecutive chunks according to the USER Buffer size. - a negative or zero buffer size indicates an error with the following code: - @ref SOCK_ERR_NO_ERROR : Socket connection closed - @ref SOCK_ERR_CONN_ABORTED : Socket connection aborted - @SOCK_ERR_TIMEOUT : Socket receive timed out -*/ -typedef struct{ - uint8 *pu8Buffer; - /*!< - Pointer to the USER buffer (passed to @ref recv and @ref recvfrom function) containing the received data chunk. - */ - sint16 s16BufferSize; - /*!< - The received data chunk size. - Holds a negative value if there is a receive error or ZERO on success upon reception of close socket message. - */ - uint16 u16RemainingSize; - /*!< - The number of bytes remaining in the current @ref recv operation. - */ - struct sockaddr_in strRemoteAddr; - /*!< - Socket address structure for the remote peer. It is valid for @ref SOCKET_MSG_RECVFROM event. - */ -}tstrSocketRecvMsg; - - -/*! -@typedef \ - tpfAppSocketCb - -@brief - The main socket application callback function. Applications register their main socket application callback through this function by calling @ref registerSocketCallback. - In response to events received, the following callback function is called to handle the corresponding asynchronous function called. Example: @ref bind, @ref connect,...etc. - -@param [in] sock - Socket ID for the callback. - - The socket callback function is called whenever a new event is recived in response - to socket operations. - -@param [in] u8Msg - Socket event type. Possible values are: - - @ref SOCKET_MSG_BIND - - @ref SOCKET_MSG_LISTEN - - @ref SOCKET_MSG_ACCEPT - - @ref SOCKET_MSG_CONNECT - - @ref SOCKET_MSG_RECV - - @ref SOCKET_MSG_SEND - - @ref SOCKET_MSG_SENDTO - - @ref SOCKET_MSG_RECVFROM - -@param [in] pvMsg - Pointer to message structure. Existing types are: - - tstrSocketBindMsg - - tstrSocketListenMsg - - tstrSocketAcceptMsg - - tstrSocketConnectMsg - - tstrSocketRecvMsg - -@see - tenuSocketCallbackMsgType - tstrSocketRecvMsg - tstrSocketConnectMsg - tstrSocketAcceptMsg - tstrSocketListenMsg - tstrSocketBindMsg -*/ -typedef void (*tpfAppSocketCb) (SOCKET sock, uint8 u8Msg, void * pvMsg); - - -/*! -@typedef \ - tpfAppResolveCb - -@brief - DNS resolution callback function. - Applications requiring DNS resolution should register their callback through this function by calling @ref registerSocketCallback. - The following callback is triggered in response to asynchronous call to the @ref gethostbyname function (DNS Resolution callback). - -@param [in] pu8DomainName - Domain name of the host. - -@param [in] u32ServerIP - Server IPv4 address encoded in NW byte order format. If it is Zero, then the DNS resolution failed. -*/ -typedef void (*tpfAppResolveCb) (uint8* pu8DomainName, uint32 u32ServerIP); - -/*! -@typedef \ - tpfPingCb - -@brief PING Callback - - The function delivers the ping statistics for the sent ping triggered by calling - m2m_ping_req. - -@param [in] u32IPAddr - Destination IP. - -@param [in] u32RTT - Round Trip Time. - -@param [in] u8ErrorCode - Ping error code. It may be one of: - - PING_ERR_SUCCESS - - PING_ERR_DEST_UNREACH - - PING_ERR_TIMEOUT -*/ -typedef void (*tpfPingCb)(uint32 u32IPAddr, uint32 u32RTT, uint8 u8ErrorCode); - - /**@}*/ -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/** \defgroup SocketAPI Function - * @ingroup SocketHeader - */ - -/** @defgroup SocketInitalizationFn socketInit - * @ingroup SocketAPI - * The function performs the necessary initializations for the socket library through the following steps: - - A check made by the global variable gbSocketInit, ensuring that initialization for sockets is performed only once, - in-order to prevent reseting the socket instances already created in the global socket array (gastrSockets). - - Zero initializations to the global socket array (gastrSockets), which holds the list of TCP sockets. - - Registers the socket (Host Interface)hif callback function through the call to the hif_register_cb function. - This facilitates handling all of the socket related functions received through interrupts from the firmware. - - */ - /**@{*/ -/*! -@fn \ - NMI_API void socketInit(void); - -@param [in] void - -@return void - -@remarks - This initialization function must be invoked before any socket operation is performed. - No error codes from this initialization function since the socket array is statically allocated based in the maximum number of - sockets @ref MAX_SOCKET based on the systems capability. -\section Example -This example demonstrates the use of the socketinit for socket initialization for an mqtt chat application. - \code - tstrWifiInitParam param; - int8_t ret; - char topic[strlen(MAIN_CHAT_TOPIC) + MAIN_CHAT_USER_NAME_SIZE + 1]; - - //Initialize the board. - system_init(); - - //Initialize the UART console. - configure_console(); - - // Initialize the BSP. - nm_bsp_init(); - - ---------- - - // Initialize socket interface. - socketInit(); - registerSocketCallback(socket_event_handler, socket_resolve_handler); - - // Connect to router. - m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), - MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); - -\endcode -*/ -NMI_API void socketInit(void); - - -/*! -@fn \ - NMI_API void socketDeinit(void); - -@brief Socket Layer De-initialization - - The function performs the necessary cleanup for the socket library static data - It must be invoked as the last any socket operation is performed on any active sockets. -*/ -NMI_API void socketDeinit(void); - - -/** @} */ -/** @defgroup SocketCallbackFn registerSocketCallback - * @ingroup SocketAPI - Register two callback functions one for asynchronous socket events and the other one for DNS callback registering function. - The registered callback functions are used to retrieve information in response to the asynchronous socket functions called. - */ - /**@{*/ - - -/*! -@fn \ - NMI_API void registerSocketCallback(tpfAppSocketCb socket_cb, tpfAppResolveCb resolve_cb); - -@param [in] tpfAppSocketCb - Assignment of callback function to the global callback @ref tpfAppSocketCb gpfAppSocketCb. Delivers - socket messages to the host application. In response to the asynchronous function calls, such as @ref bind - @ref listen @ref accept @ref connect - -@param [in] tpfAppResolveCb - Assignment of callback function to the global callback @ref tpfAppResolveCb gpfAppResolveCb. - Used for DNS resolving functionalities. The DNS resolving technique is determined by the application - registering the callback. - NULL is assigned when, DNS resolution is not required. - -@return void -@remarks - If any of the socket functionalities is not to be used, NULL is passed in as a parameter. - It must be invoked after socketinit and before other socket layer operations. - -\section Example - This example demonstrates the use of the registerSocketCallback to register a socket callback function with DNS resolution CB set to null - for a simple UDP server example. - \code - tstrWifiInitParam param; - int8_t ret; - struct sockaddr_in addr; - - // Initialize the board - system_init(); - - //Initialize the UART console. - configure_console(); - - // Initialize the BSP. - nm_bsp_init(); - - // Initialize socket address structure. - addr.sin_family = AF_INET; - addr.sin_port = _htons(MAIN_WIFI_M2M_SERVER_PORT); - addr.sin_addr.s_addr = _htonl(MAIN_WIFI_M2M_SERVER_IP); - - // Initialize Wi-Fi parameters structure. - memset((uint8_t *)¶m, 0, sizeof(tstrWifiInitParam)); - - // Initialize Wi-Fi driver with data and status callbacks. - param.pfAppWifiCb = wifi_cb; - ret = m2m_wifi_init(¶m); - if (M2M_SUCCESS != ret) { - printf("main: m2m_wifi_init call error!(%d)\r\n", ret); - while (1) { - } - } - - // Initialize socket module - socketInit(); - registerSocketCallback(socket_cb, NULL); - - // Connect to router. - m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); - \endcode -*/ -NMI_API void registerSocketCallback(tpfAppSocketCb socket_cb, tpfAppResolveCb resolve_cb); - - -/** @} */ - -/** @defgroup SocketFn socket - * @ingroup SocketAPI - * Synchronous socket allocation function based on the specified socket type. Created sockets are non-blocking and their possible types are either TCP or a UDP sockets. - * The maximum allowed number of TCP sockets is @ref TCP_SOCK_MAX sockets while the maximum number of UDP sockets that can be created simultaneously is @ref UDP_SOCK_MAX sockets. - * -*/ - /**@{*/ -/*! -@fn \ - NMI_API SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags); - - -@param [in] u16Domain - Socket family. The only allowed value is AF_INET (IPv4.0) for TCP/UDP sockets. - -@param [in] u8Type - Socket type. Allowed values are: - - [SOCK_STREAM](@ref SOCK_STREAM) - - [SOCK_DGRAM](@ref SOCK_DGRAM) - -@param [in] u8Flags - Used to specify the socket creation flags. It shall be set to zero for normal TCP/UDP sockets. - It could be @ref SOCKET_FLAGS_SSL if the socket is used for SSL session. The use of the flag - @ref SOCKET_FLAGS_SSL has no meaning in case of UDP sockets. - -@pre - The @ref socketInit function must be called once at the beginning of the application to initialize the socket handler. - before any call to the socket function can be made. - -@see - connect - bind - listen - accept - recv - recvfrom - send - sendto - close - setsockopt - getsockopt - -@return - On successful socket creation, a non-blocking socket type is created and a socket ID is returned - In case of failure the function returns a negative value, identifying one of the socket error codes defined. - For example: @ref SOCK_ERR_INVALID for invalid argument or - @ref SOCK_ERR_MAX_TCP_SOCK if the number of TCP allocated sockets exceeds the number of available sockets. - -@remarks - The socket function must be called a priori to any other related socket functions "e.g. send, recv, close ..etc" -\section Example - This example demonstrates the use of the socket function to allocate the socket, returning the socket handler to be used for other -socket operations. Socket creation is dependent on the socket type. -\subsection sub1 UDP example -@code - SOCKET UdpServerSocket = -1; - - UdpServerSocket = socket(AF_INET, SOCK_DGRAM, 0); - -@endcode -\subsection sub2 TCP example -@code - static SOCKET tcp_client_socket = -1; - - tcp_client_socket = socket(AF_INET, SOCK_STREAM, 0)); -@endcode -\subsection sub3 SSL example -@code -static SOCKET ssl_socket = -1; - -ssl_socket = socket(AF_INET, SOCK_STREAM, SOCK_FLAGS_SSL)); -@endcode -*/ -NMI_API SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags); - - -/** @} */ -/** @defgroup BindFn bind - * @ingroup SocketAPI -* Asynchronous bind function associates the provided address and local port to the socket. -* The function can be used with both TCP and UDP sockets it's mandatory to call the @ref bind function before starting any UDP or TCP server operation. -* Upon socket bind completion, the application will receive a @ref SOCKET_MSG_BIND message in the socket callback. -*/ - /**@{*/ -/*! -\fn \ - NMI_API sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); - - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] pstrAddr - Pointer to socket address structure "sockaddr_in" - [sockaddr_in](@ref sockaddr_in) - - -@param [in] u8AddrLen - Size of the given socket address structure in bytes. - -@pre - The socket function must be called to allocate a socket before passing the socket ID to the bind function. - -@see - socket - connect - listen - accept - recv - recvfrom - send - sendto - -@return - The function returns ZERO for successful operations and a negative value otherwise. - The possible error values are: - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - Indicating that the operation was successful. - - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) - Indicating passing invalid arguments such as negative socket ID or NULL socket address structure. - - - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID) - Indicate socket bind failure. -\section Example - This example demonstrates the call of the bind socket operation after a successful socket operation. -@code - struct sockaddr_in addr; - SOCKET udpServerSocket =-1; - int ret = -1; - - if(udpServerSocket == -1) - { - udpServerSocket = socket(AF_INET, SOCK_DGRAM, 0); - if(udpServerSocket >= 0) - { - addr.sin_family = AF_INET; - addr.sin_port = _htons(1234); - addr.sin_addr.s_addr = 0; - ret = bind(udpServerSocket,(struct sockaddr*)&addr,sizeof(addr)); - - if(ret != 0) - { - printf("Bind Failed. Error code = %d\n",ret); - close(udpServerSocket); - } - } - else - { - printf("UDP Server Socket Creation Failed\n"); - return; - } - } -@endcode -*/ -NMI_API sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); - - -/** @} */ - -/** @defgroup ListenFn listen - * @ingroup SocketAPI - * After successful socket binding to an IP address and port on the system, start listening on a passive socket for incoming connections. - The socket must be bound on a local port or the listen operation fails. - Upon the call to the asynchronous listen function, response is received through the event [SOCKET_MSG_BIND](@ref SOCKET_MSG_BIND) - in the socket callback. - A successful listen means the TCP server operation is active. If a connection is accepted, then the application socket callback function is - notified with the new connected socket through the event @ref SOCKET_MSG_ACCEPT. Hence there is no need to call the @ref accept function - after calling @ref listen. - - After a connection is accepted, the user is then required to call the @ref recv to receive any packets transmitted by the remote host or to receive notification of socket connection - termination. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 listen(SOCKET sock, uint8 backlog); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] backlog - Not used by the current implementation. - -@pre - The bind function must be called to assign the port number and IP address to the socket before the listen operation. - -@see - bind - accept - recv - recvfrom - send - sendto - -@return - The function returns ZERO for successful operations and a negative value otherwise. - The possible error values are: - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - Indicating that the operation was successful. - - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) - Indicating passing invalid arguments such as negative socket ID. - - - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID) - Indicate socket listen failure. -\section Example -This example demonstrates the call of the listen socket operation after a successful socket operation. -@code - static void TCP_Socketcallback(SOCKET sock, uint8 u8Msg, void * pvMsg) - { - int ret =-1; - - switch(u8Msg) - { - case SOCKET_MSG_BIND: - { - tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg; - if(pstrBind != NULL) - { - if(pstrBind->status == 0) - { - ret = listen(sock, 0); - - if(ret <0) - printf("Listen failure! Error = %d\n",ret); - } - else - { - M2M_ERR("bind Failure!\n"); - close(sock); - } - } - } - break; - - case SOCKET_MSG_LISTEN: - { - - tstrSocketListenMsg *pstrListen = (tstrSocketListenMsg*)pvMsg; - if(pstrListen != NULL) - { - if(pstrListen->status == 0) - { - ret = accept(sock,NULL,0); - } - else - { - M2M_ERR("listen Failure!\n"); - close(sock); - } - } - } - break; - - case SOCKET_MSG_ACCEPT: - { - tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg*)pvMsg; - - if(pstrAccept->sock >= 0) - { - TcpNotificationSocket = pstrAccept->sock; - recv(pstrAccept->sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT); - } - else - { - M2M_ERR("accept failure\n"); - } - } - break; - - default: - break; - } - } - -@endcode -*/ -NMI_API sint8 listen(SOCKET sock, uint8 backlog); -/** @} */ -/** @defgroup AcceptFn accept - * @ingroup SocketAPI - * The function has no current implementation. An empty deceleration is used to prevent errors when legacy application code is used. - * For recent application use, the accept function can be safer as it has no effect and could be safely removed from any application using it. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. -@param [in] addr - Not used in the current implementation. - -@param [in] addrlen - Not used in the current implementation. - -@return - The function returns ZERO for successful operations and a negative value otherwise. - The possible error values are: - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - Indicating that the operation was successful. - - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) - Indicating passing invalid arguments such as negative socket ID. -*/ -NMI_API sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen); -/** @} */ -/** @defgroup ConnectFn connect - * @ingroup SocketAPI - * Establishes a TCP connection with a remote server. - The asynchronous connect function must be called after receiving a valid socket ID from the @ref socket function. - The application socket callback function is notified of a successful new socket connection through the event @ref SOCKET_MSG_CONNECT. - A successful connect means the TCP session is active. The application is then required to make a call to the @ref recv - to receive any packets transmitted by the remote server, unless the application is interrupted by a notification of socket connection - termination. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] pstrAddr - Address of the remote server. -@param [in] pstrAddr - Pointer to socket address structure "sockaddr_in" - [sockaddr_in](@ref sockaddr_in) - -@param [in] u8AddrLen - Size of the given socket address structure in bytes. - Not currently used, implemented for BSD compatibility only. -@pre - The socket function must be called to allocate a TCP socket before passing the socket ID to the bind function. - If the socket is not bound, you do NOT have to call bind before the "connect" function. - -@see - socket - recv - send - close - -@return - The function returns ZERO for successful operations and a negative value otherwise. - The possible error values are: - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - Indicating that the operation was successful. - - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) - Indicating passing invalid arguments such as negative socket ID or NULL socket address structure. - - - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID) - Indicate socket connect failure. -\section Example - The example demonstrates a TCP application, showing how the asynchronous call to the connect function is made through the main function and how the - callback function handles the @ref SOCKET_MSG_CONNECT event. -\subsection sub1 Main Function -@code - struct sockaddr_in Serv_Addr; - SOCKET TcpClientSocket =-1; - int ret = -1 - - TcpClientSocket = socket(AF_INET,SOCK_STREAM,0); - Serv_Addr.sin_family = AF_INET; - Serv_Addr.sin_port = _htons(1234); - Serv_Addr.sin_addr.s_addr = inet_addr(SERVER); - printf("Connected to server via socket %u\n",TcpClientSocket); - - do - { - ret = connect(TcpClientSocket,(sockaddr_in*)&Serv_Addr,sizeof(Serv_Addr)); - if(ret != 0) - { - printf("Connection Error\n"); - } - else - { - printf("Connection successful.\n"); - break; - } - }while(1) -@endcode -\subsection sub2 Socket Callback -@code - if(u8Msg == SOCKET_MSG_CONNECT) - { - tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg*)pvMsg; - if(pstrConnect->s8Error == 0) - { - uint8 acBuffer[GROWL_MSG_SIZE]; - uint16 u16MsgSize; - - printf("Connect success!\n"); - - u16MsgSize = FormatMsg(u8ClientID, acBuffer); - send(sock, acBuffer, u16MsgSize, 0); - recv(pstrNotification->Socket, (void*)au8Msg,GROWL_DESCRIPTION_MAX_LENGTH, GROWL_RX_TIMEOUT); - u8Retry = GROWL_CONNECT_RETRY; - } - else - { - M2M_DBG("Connection Failed, Error: %d\n",pstrConnect->s8Error"); - close(pstrNotification->Socket); - } - } -@endcode -*/ -#ifdef ARDUINO -NMI_API sint8 connectSocket(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); -#else -NMI_API sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); -#endif -/** @} */ -/** @defgroup ReceiveFn recv - * @ingroup SocketAPI - * An asynchronous receive function, used to retrieve data from a TCP stream. - Before calling the recv function, a successful socket connection status must have been received through any of the two socket events - [SOCKET_MSG_CONNECT] or [SOCKET_MSG_ACCEPT], from the socket callback. Hence, indicating that the socket is already connected to a remote - host. - The application receives the required data in response to this asynchronous call through the reception of the event @ref SOCKET_MSG_RECV in the - socket callback. - - Receiving the SOCKET_MSG_RECV message in the callback with zero or negative buffer length indicates the following: - - SOCK_ERR_NO_ERROR : Socket connection closed - - SOCK_ERR_CONN_ABORTED : Socket connection aborted - - SOCK_ERR_TIMEOUT : Socket receive timed out - The application code is expected to close the socket through the call to the @ref close function upon the appearance of the above mentioned errors. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - - -@param [in] pvRecvBuf - Pointer to a buffer that will hold the received data. The buffer is used - in the recv callback to deliver the received data to the caller. The buffer must - be resident in memory (heap or global buffer). - -@param [in] u16BufLen - The buffer size in bytes. - -@param [in] u32Timeoutmsec - Timeout for the recv function in milli-seconds. If the value is set to ZERO, the timeout - will be set to infinite (the recv function waits forever). If the timeout period is - elapsed with no data received, the socket will get a timeout error. -@pre - - The socket function must be called to allocate a TCP socket before passing the socket ID to the recv function. - - The socket in a connected state is expected to receive data through the socket interface. - -@see - socket - connect - bind - listen - recvfrom - close - - -@return - The function returns ZERO for successful operations and a negative value otherwise. - The possible error values are: - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - Indicating that the operation was successful. - - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) - Indicating passing invalid arguments such as negative socket ID or NULL Recieve buffer. - - - [SOCK_ERR_BUFFER_FULL](@ref SOCK_ERR_BUFFER_FULL) - Indicate socket receive failure. -\section Example - The example demonstrates a code snippet for the calling of the recv function in the socket callback upon notification of the accept or connect events, and the parsing of the - received data when the SOCKET_MSG_RECV event is received. -@code - - switch(u8Msg) - { - - case SOCKET_MSG_ACCEPT: - { - tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg*)pvMsg; - - if(pstrAccept->sock >= 0) - { - recv(pstrAccept->sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT); - } - else - { - M2M_ERR("accept\n"); - } - } - break; - - - case SOCKET_MSG_RECV: - { - tstrSocketRecvMsg *pstrRx = (tstrSocketRecvMsg*)pvMsg; - - if(pstrRx->s16BufferSize > 0) - { - - recv(sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT); - } - else - { - printf("Socet recv Error: %d\n",pstrRx->s16BufferSize); - close(sock); - } - } - break; - - default: - break; - } -} -@endcode -*/ -NMI_API sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec); -/** @} */ -/** @defgroup ReceiveFromSocketFn recvfrom - * @ingroup SocketAPI - * Receives data from a UDP Socket. -* -* The asynchronous recvfrom function is used to retrieve data from a UDP socket. The socket must already be bound to -* a local port before a call to the recvfrom function is made (i.e message @ref SOCKET_MSG_BIND is received -* with successful status in the socket callback). -* -* Upon calling the recvfrom function with a successful return code, the application is expected to receive a notification -* in the socket callback whenever a message is received through the @ref SOCKET_MSG_RECVFROM event. -* -* Receiving the SOCKET_MSG_RECVFROM message in the callback with zero, indicates that the socket is closed. -* Whereby a negative buffer length indicates one of the socket error codes such as socket timeout error @SOCK_ERR_TIMEOUT: -* -* The recvfrom callback can also be used to show the IP address of the remote host that sent the frame by -* using the "strRemoteAddr" element in the @ref tstrSocketRecvMsg structure. (refer to the code example) - */ - /**@{*/ -/*! -@fn \ - NMI_API sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32TimeoutSeconds); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] pvRecvBuf - Pointer to a buffer that will hold the received data. The buffer shall be used - in the recv callback to deliver the received data to the caller. The buffer must - be resident in memory (heap or global buffer). - -@param [in] u16BufLen - The buffer size in bytes. - -@param [in] u32TimeoutSeconds - Timeout for the recv function in milli-seconds. If the value is set to ZERO, the timeout - will be set to infinite (the recv function waits forever). - -@pre - - The socket function must be called to allocate a UDP socket before passing the socket ID to the recvfrom function. - - The socket corresponding to the socket ID must be successfully bound to a local port through the call to a @ref bind function. - -@see - socket - bind - close - -@return - The function returns ZERO for successful operations and a negative value otherwise. - The possible error values are: - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - Indicating that the operation was successful. - - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) - Indicating passing invalid arguments such as negative socket ID or NULL Receive buffer. - - - [SOCK_ERR_BUFFER_FULL](@ref SOCK_ERR_BUFFER_FULL) - Indicate socket receive failure. -\section Example - The example demonstrates a code snippet for the calling of the recvfrom function in the socket callback upon notification of a successful bind event, and the parsing of the - received data when the SOCKET_MSG_RECVFROM event is received. -@code - switch(u8Msg) - { - - case SOCKET_MSG_BIND: - { - tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg; - - if(pstrBind != NULL) - { - if(pstrBind->status == 0) - { - recvfrom(sock, gau8SocketTestBuffer, TEST_BUFFER_SIZE, 0); - } - else - { - M2M_ERR("bind\n"); - } - } - } - break; - - - case SOCKET_MSG_RECVFROM: - { - tstrSocketRecvMsg *pstrRx = (tstrSocketRecvMsg*)pvMsg; - - if(pstrRx->s16BufferSize > 0) - { - //get the remote host address and port number - uint16 u16port = pstrRx->strRemoteAddr.sin_port; - uint32 strRemoteHostAddr = pstrRx->strRemoteAddr.sin_addr.s_addr; - - printf("Recieved frame with size = %d.\tHost address=%x, Port number = %d\n\n",pstrRx->s16BufferSize,strRemoteHostAddr, u16port); - - ret = recvfrom(sock,gau8SocketTestBuffer,sizeof(gau8SocketTestBuffer),TEST_RECV_TIMEOUT); - } - else - { - printf("Socet recv Error: %d\n",pstrRx->s16BufferSize); - ret = close(sock); - } - } - break; - - default: - break; - } -} -@endcode -*/ -NMI_API sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec); -/** @} */ -/** @defgroup SendFn send - * @ingroup SocketAPI -* Asynchronous sending function, used to send data on a TCP/UDP socket. - -* Called by the application code when there is outgoing data available required to be sent on a specific socket handler. -* The only difference between this function and the similar @ref sendto function, is the type of socket the data is sent on and the parameters passed in. -* @ref send function is most commonly called for sockets in a connected state. -* After the data is sent, the socket callback function registered using registerSocketCallback(), is expected to receive an event of type -* @ref SOCKET_MSG_SEND holding information containing the number of data bytes sent. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 u16Flags); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] pvSendBuffer - Pointer to a buffer holding data to be transmitted. - -@param [in] u16SendLength - The buffer size in bytes. - -@param [in] u16Flags - Not used in the current implementation. - -@pre - Sockets must be initialized using socketInit. \n - - For TCP Socket:\n - Must use a successfully connected Socket (so that the intended recipient address is known ahead of sending the data). - Hence this function is expected to be called after a successful socket connect operation(in client case or accept in the - the server case).\n - - For UDP Socket:\n - UDP sockets most commonly use @ref sendto function, where the destination address is defined. However, in-order to send outgoing data - using the @ref send function, at least one successful call must be made to the @ref sendto function a priori the consecutive calls to the @ref send function, - to ensure that the destination address is saved in the firmware. - -@see - socketInit - recv - sendto - socket - connect - accept - sendto - -@warning - u16SendLength must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. \n - Use a valid socket identifier through the a prior call to the @ref socket function. - Must use a valid buffer pointer. - Successful completion of a call to send() does not guarantee delivery of the message, - A negative return value indicates only locally-detected errors - - -@return - The function shall return @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise. -*/ -NMI_API sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 u16Flags); -/** @} */ -/** @defgroup SendToSocketFn sendto - * @ingroup SocketAPI -* Asynchronous sending function, used to send data on a UDP socket. -* Called by the application code when there is data required to be sent on a UDP socket handler. -* The application code is expected to receive data from a successful bounded socket node. -* The only difference between this function and the similar @ref send function, is the type of socket the data is received on. This function works -* only with UDP sockets. -* After the data is sent, the socket callback function registered using registerSocketCallback(), is expected to receive an event of type -* @ref SOCKET_MSG_SENDTO. -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] pvSendBuffer - Pointer to a buffer holding data to be transmitted. - A NULL value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] u16SendLength - The buffer size in bytes. It must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. - -@param [in] flags - Not used in the current implementation - -@param [in] pstrDestAddr - The destination address. - -@param [in] u8AddrLen - Destination address length in bytes. - Not used in the current implementation, only included for BSD compatibility. -@pre - Sockets must be initialized using socketInit. - -@see - socketInit - recvfrom - sendto - socket - connect - accept - send - -@warning - u16SendLength must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. \n - Use a valid socket (returned from socket ). - A valid buffer pointer must be used (not NULL). \n - Successful completion of a call to sendto() does not guarantee delivery of the message, - A negative return value indicates only locally-detected errors - -@return - The function returns @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise. -*/ -NMI_API sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen); -/** @} */ -/** @defgroup CloseSocketFn close - * @ingroup SocketAPI - * Synchronous close function, releases all the socket assigned resources. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 close(SOCKET sock); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@pre - Sockets must be initialized through the call of the socketInit function. - @ref close is called only for valid socket identifiers created through the @ref socket function. - -@warning - If @ref close is called while there are still pending messages (sent or received ) they will be discarded. - -@see - socketInit - socket - -@return - The function returned @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise. -*/ -NMI_API sint8 close(SOCKET sock); - - -/** @} */ -/** @defgroup InetAddressFn nmi_inet_addr -* @ingroup SocketAPI -* Synchronous function which returns a BSD socket compliant Internet Protocol (IPv4) socket address. -* This IPv4 address in the input string parameter could either be specified as a host name, or as a numeric string representation like n.n.n.n known as the IPv4 dotted-decimal format -* (i.e. "192.168.10.1"). -* This function is used whenever an ip address needs to be set in the proper format -* (i.e. for the @ref tstrM2MIPConfig structure). -*/ - /**@{*/ -/*! -@fn \ - NMI_API uint32 nmi_inet_addr(char *pcIpAddr); - -@param [in] pcIpAddr - A null terminated string containing the IP address in IPv4 dotted-decimal address. - -@return - Unsigned 32-bit integer representing the IP address in Network byte order - (eg. "192.168.10.1" will be expressed as 0x010AA8C0). - -*/ -NMI_API uint32 nmi_inet_addr(char *pcIpAddr); - - -/** @} */ -/** @defgroup gethostbynameFn gethostbyname - * @ingroup SocketAPI -* Asynchronous DNS resolving function. This function use DNS to resolve a domain name into the corresponding IP address. -* A call to this function will cause a DNS request to be sent and the response will be delivered to the DNS callback function registered using registerSocketCallback() - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 gethostbyname(uint8 * pcHostName); - -@param [in] pcHostName - NULL terminated string containing the domain name for the remote host. - Its size must not exceed [HOSTNAME_MAX_SIZE](@ref HOSTNAME_MAX_SIZE). - -@see - registerSocketCallback - -@warning - Successful completion of a call to gethostbyname() does not guarantee success of the DNS request, - a negative return value indicates only locally-detected errors - -@return - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) -*/ -NMI_API sint8 gethostbyname(uint8 * pcHostName); - - -/** @} */ -/** @defgroup sslEnableCertExpirationCheckFn sslEnableCertExpirationCheck - * @ingroup SocketAPI -* Configure the behavior of the SSL Library for Certificate Expiry Validation. - */ - /**@{*/ -/*! -@fn \ -NMI_API sint8 sslEnableCertExpirationCheck(tenuSslCertExpSettings enuValidationSetting); - -@param [in] enuValidationSetting - See @ref tenuSslCertExpSettings for details. - -@return - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) for successful operation and negative error code otherwise. - -@sa tenuSslCertExpSettings -*/ -NMI_API sint8 sslEnableCertExpirationCheck(tenuSslCertExpSettings enuValidationSetting); - - -/** @} */ - -/** @defgroup SetSocketOptionFn setsockopt - * @ingroup SocketAPI -*The setsockopt() function shall set the option specified by the option_name -* argument, at the protocol level specified by the level argument, to the value -* pointed to by the option_value argument for the socket specified by the socket argument. -* -*

Possible protocol level values supported are @ref SOL_SOCKET and @ref SOL_SSL_SOCKET. -* Possible options when the protocol level is @ref SOL_SOCKET :

-* -* -* -* -* -* -* -* -* -* -* -* -* -*
@ref SO_SET_UDP_SEND_CALLBACKEnable/Disable callback messages for sendto(). -* Since UDP is unreliable by default the user maybe interested (or not) in -* receiving a message of @ref SOCKET_MSG_SENDTO for each call of sendto(). -* Enabled if option value equals @ref TRUE, disabled otherwise.
@ref IP_ADD_MEMBERSHIPValid for UDP sockets. This option is used to receive frames sent to -* a multicast group. option_value shall be a pointer to Unsigned 32-bit -* integer containing the multicast IPv4 address.
@ref IP_DROP_MEMBERSHIPValid for UDP sockets. This option is used to stop receiving frames -* sent to a multicast group. option_value shall be a pointer to Unsigned -* 32-bit integer containing the multicast IPv4 address.
-*

Possible options when the protcol leve  is @ref SOL_SSL_SOCKET

-* -* -* -* -* -* -* -* -* -* -* -* -* -*
-* @ref SO_SSL_BYPASS_X509_VERIFAllow an opened SSL socket to bypass the X509 -* certificate verification process. It is highly recommended NOT to use -* this socket option in production software applications. The option is -* supported for debugging and testing purposes. The option value should be -* casted to int type and it is handled as a boolean flag.
@ref SO_SSL_SNISet the Server Name Indicator (SNI) for an SSL socket. The SNI is a -* null terminated string containing the server name associated with the -* connection. It must not exceed the size of @ref HOSTNAME_MAX_SIZE.
@ref SO_SSL_ENABLE_SESSION_CACHINGThis option allow the TLS to cache the session information for fast -* TLS session establishment in future connections using the TLS Protocol -* session resume features.
- */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 setsockopt(SOCKET socket, uint8 u8Level, uint8 option_name, - const void *option_value, uint16 u16OptionLen); - -@param [in] sock - Socket handler. - -@param [in] level - protocol level. See description above. - -@param [in] option_name - option to be set. See description above. - -@param [in] option_value - pointer to user provided value. - -@param [in] option_len - length of the option value in bytes. -@return - The function shall return \ref SOCK_ERR_NO_ERROR for successful operation - and a negative value (indicating the error) otherwise. -@sa SOL_SOCKET, SOL_SSL_SOCKET, IP_ADD_MEMBERSHIP, IP_DROP_MEMBERSHIP -*/ -NMI_API sint8 setsockopt(SOCKET socket, uint8 u8Level, uint8 option_name, - const void *option_value, uint16 u16OptionLen); - - -/** @} */ -/** @defgroup GetSocketOptionsFn getsockopt - * @ingroup SocketAPI - * Get socket options retrieves -* This Function isn't implemented yet but this is the form that will be released later. - */ - /**@{*/ -/*! -@fn \ - sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8 * pu8OptLen); - -@brief - -@param [in] sock - Socket Identifie. -@param [in] u8Level - The protocol level of the option. -@param [in] u8OptName - The u8OptName argument specifies a single option to get. -@param [out] pvOptValue - The pvOptValue argument contains pointer to a buffer containing the option value. -@param [out] pu8OptLen - Option value buffer length. -@return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8* pu8OptLen); -/** @} */ - -/**@}*/ -/** @defgroup PingFn m2m_ping_req - * @ingroup SocketAPI - * The function sends ping request to the given IP Address. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb); - -@param [in] u32DstIP - Target Destination IP Address for the ping request. It must be represented in Network byte order. - The function nmi_inet_addr could be used to translate the dotted decimal notation IP - to its Network bytes order integer represntative. - -@param [in] u8TTL - IP TTL value for the ping request. If set to ZERO, the dfault value SHALL be used. - -@param [in] fpPingCb - Callback will be called to deliver the ping statistics. - -@see nmi_inet_addr -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb); -/**@}*/ - - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __SOCKET_H__ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/socket/include/socket_buffer.h b/feather_sensor_lte/libraries/WiFi101/src/socket/include/socket_buffer.h deleted file mode 100644 index d93a7c8..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/socket/include/socket_buffer.h +++ /dev/null @@ -1,94 +0,0 @@ -/** - * - * \file - * - * \brief BSD compatible socket interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef __SOCKET_BUFFER_H__ -#define __SOCKET_BUFFER_H__ - -#include "socket/include/socket.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define SOCKET_BUFFER_UDP_HEADER_SIZE (8) - -#if defined LIMITED_RAM_DEVICE -#define SOCKET_BUFFER_MTU (16u) -#define SOCKET_BUFFER_UDP_SIZE (SOCKET_BUFFER_UDP_HEADER_SIZE + 64u) -#define SOCKET_BUFFER_TCP_SIZE (64u) -#else -#ifdef ARDUINO -#define SOCKET_BUFFER_MTU (1446u) -#else -#define SOCKET_BUFFER_MTU (1400u) -#endif -#define SOCKET_BUFFER_UDP_SIZE (SOCKET_BUFFER_UDP_HEADER_SIZE + SOCKET_BUFFER_MTU) -#define SOCKET_BUFFER_TCP_SIZE (SOCKET_BUFFER_MTU) -#endif - -#define SOCKET_BUFFER_FLAG_CONNECTED (0x1 << 0) -#define SOCKET_BUFFER_FLAG_FULL (0x1 << 1) -#define SOCKET_BUFFER_FLAG_BIND (0x1 << 2) -#define SOCKET_BUFFER_FLAG_SPAWN (0x1 << 3) -#define SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS (16) -#define SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK (((uint32)0xFF) << SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS) -#define SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS (24) -#define SOCKET_BUFFER_FLAG_PARENT_SOCKET_MSK (((uint32)0xFF) << SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS) - -/* Parent stored as parent+1, as socket 1 ID is 0. */ - -typedef struct{ - uint8 *buffer; - uint32 *flag; - uint32 *head; - uint32 *tail; -}tstrSocketBuffer; - -void socketBufferInit(void); -void socketBufferRegister(SOCKET socket, uint32 *flag, uint32 *head, uint32 *tail, uint8 *buffer); -void socketBufferUnregister(SOCKET socket); -void socketBufferCb(SOCKET sock, uint8 u8Msg, void *pvMsg); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __SOCKET_BUFFER_H__ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/socket/source/socket.c b/feather_sensor_lte/libraries/WiFi101/src/socket/source/socket.c deleted file mode 100644 index 877cc1a..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/socket/source/socket.c +++ /dev/null @@ -1,1445 +0,0 @@ -/** - * - * \file - * - * \brief BSD compatible socket interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#include - -#include "bsp/include/nm_bsp.h" -#include "socket/include/socket.h" -#include "driver/source/m2m_hif.h" -#include "socket/source/socket_internal.h" -#include "driver/include/m2m_types.h" - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -#define TLS_RECORD_HEADER_LENGTH (5) -#define ETHERNET_HEADER_OFFSET (34) -#define ETHERNET_HEADER_LENGTH (14) -#define TCP_IP_HEADER_LENGTH (40) -#define UDP_IP_HEADER_LENGTH (28) - -#define IP_PACKET_OFFSET (ETHERNET_HEADER_LENGTH + ETHERNET_HEADER_OFFSET - M2M_HIF_HDR_OFFSET) - -#define TCP_TX_PACKET_OFFSET (IP_PACKET_OFFSET + TCP_IP_HEADER_LENGTH) -#define UDP_TX_PACKET_OFFSET (IP_PACKET_OFFSET + UDP_IP_HEADER_LENGTH) -#define SSL_TX_PACKET_OFFSET (TCP_TX_PACKET_OFFSET + TLS_RECORD_HEADER_LENGTH) - -#define SOCKET_REQUEST(reqID, reqArgs, reqSize, reqPayload, reqPayloadSize, reqPayloadOffset) \ - hif_send(M2M_REQ_GROUP_IP, reqID, reqArgs, reqSize, reqPayload, reqPayloadSize, reqPayloadOffset) - - -#define SSL_FLAGS_ACTIVE NBIT0 -#define SSL_FLAGS_BYPASS_X509 NBIT1 -#define SSL_FLAGS_2_RESERVD NBIT2 -#define SSL_FLAGS_3_RESERVD NBIT3 -#define SSL_FLAGS_CACHE_SESSION NBIT4 -#define SSL_FLAGS_NO_TX_COPY NBIT5 -#define SSL_FLAGS_CHECK_SNI NBIT6 - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -PRIVATE DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -/*! -* @brief -*/ -typedef struct{ - SOCKET sock; - uint8 u8Dummy; - uint16 u16SessionID; -}tstrCloseCmd; - - -/*! -* @brief -*/ -typedef struct{ - uint8 *pu8UserBuffer; - uint16 u16UserBufferSize; - uint16 u16SessionID; - uint16 u16DataOffset; - uint8 bIsUsed; - uint8 u8SSLFlags; - uint8 bIsRecvPending; -}tstrSocket; - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -GLOBALS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -volatile sint8 gsockerrno; -volatile tstrSocket gastrSockets[MAX_SOCKET]; -volatile uint8 gu8OpCode; -volatile uint16 gu16BufferSize; -volatile uint16 gu16SessionID = 0; - -volatile tpfAppSocketCb gpfAppSocketCb; -volatile tpfAppResolveCb gpfAppResolveCb; -volatile uint8 gbSocketInit = 0; -volatile tpfPingCb gfpPingCb; - -/********************************************************************* -Function - Socket_ReadSocketData - -Description - Callback function used by the NMC1500 driver to deliver messages - for socket layer. - -Return - None. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 17 July 2012 -*********************************************************************/ -#ifdef ARDUINO -extern uint8 hif_small_xfer; -static uint32 u32Address; -static SOCKET sock_xfer; -static uint8 type_xfer; -static tstrSocketRecvMsg msg_xfer; -#endif -NMI_API void Socket_ReadSocketData(SOCKET sock, tstrSocketRecvMsg *pstrRecv,uint8 u8SocketMsg, - uint32 u32StartAddress,uint16 u16ReadCount) -{ - if((u16ReadCount > 0) && (gastrSockets[sock].pu8UserBuffer != NULL) && (gastrSockets[sock].u16UserBufferSize > 0) && (gastrSockets[sock].bIsUsed == 1)) - { -#ifdef ARDUINO - u32Address = u32StartAddress; -#else - uint32 u32Address = u32StartAddress; -#endif - uint16 u16Read; - sint16 s16Diff; - uint8 u8SetRxDone; -#ifdef ARDUINO - m2m_memcpy((uint8 *)&msg_xfer, (uint8 *)pstrRecv, sizeof(tstrSocketRecvMsg)); - msg_xfer.u16RemainingSize = u16ReadCount; -#else - pstrRecv->u16RemainingSize = u16ReadCount; -#endif - do - { - u8SetRxDone = 1; - u16Read = u16ReadCount; - s16Diff = u16Read - gastrSockets[sock].u16UserBufferSize; - if(s16Diff > 0) - { - u8SetRxDone = 0; - u16Read = gastrSockets[sock].u16UserBufferSize; -#ifdef ARDUINO - hif_small_xfer = 1; - sock_xfer = sock; - type_xfer = u8SocketMsg; -#endif - } - - if(hif_receive(u32Address, gastrSockets[sock].pu8UserBuffer, u16Read, u8SetRxDone) == M2M_SUCCESS) - { -#ifdef ARDUINO - msg_xfer.pu8Buffer = gastrSockets[sock].pu8UserBuffer; - msg_xfer.s16BufferSize = u16Read; - msg_xfer.u16RemainingSize -= u16Read; - - if (gpfAppSocketCb) - gpfAppSocketCb(sock,u8SocketMsg, &msg_xfer); - - u32Address += u16Read; -#else - pstrRecv->pu8Buffer = gastrSockets[sock].pu8UserBuffer; - pstrRecv->s16BufferSize = u16Read; - pstrRecv->u16RemainingSize -= u16Read; - - if (gpfAppSocketCb) - gpfAppSocketCb(sock,u8SocketMsg, pstrRecv); - - u16ReadCount -= u16Read; - u32Address += u16Read; - - if((!gastrSockets[sock].bIsUsed) && (u16ReadCount)) - { - M2M_DBG("Application Closed Socket While Rx Is not Complete\n"); - if(hif_receive(0, NULL, 0, 1) == M2M_SUCCESS) - M2M_DBG("hif_receive Success\n"); - else - M2M_DBG("hif_receive Fail\n"); - break; - } -#endif - } - else - { - M2M_INFO("(ERRR)Current <%d>\n", u16ReadCount); - break; - } -#ifdef ARDUINO - }while(0); -#else - }while(u16ReadCount != 0); -#endif - } -} -#ifdef ARDUINO -NMI_API void Socket_ReadSocketData_Small(void) -{ - if((msg_xfer.u16RemainingSize > 0) && (gastrSockets[sock_xfer].pu8UserBuffer != NULL) && (gastrSockets[sock_xfer].u16UserBufferSize > 0) && (gastrSockets[sock_xfer].bIsUsed == 1)) - { - uint16 u16Read; - sint16 s16Diff; - uint8 u8SetRxDone; - - //do - //{ - u8SetRxDone = 1; - u16Read = msg_xfer.u16RemainingSize; - s16Diff = u16Read - gastrSockets[sock_xfer].u16UserBufferSize; - if(s16Diff > 0) - { - /*Has to be subsequent transfer*/ - hif_small_xfer = 2; - u8SetRxDone = 0; - u16Read = gastrSockets[sock_xfer].u16UserBufferSize; - } - else - { - /*Last xfer, needed for UDP*/ - hif_small_xfer = 3; - } - if(hif_receive(u32Address, gastrSockets[sock_xfer].pu8UserBuffer, u16Read, u8SetRxDone) == M2M_SUCCESS) - { - msg_xfer.pu8Buffer = gastrSockets[sock_xfer].pu8UserBuffer; - msg_xfer.s16BufferSize = u16Read; - msg_xfer.u16RemainingSize -= u16Read; - - if (gpfAppSocketCb) - gpfAppSocketCb(sock_xfer,type_xfer, &msg_xfer); - - u32Address += u16Read; - } - else - { - M2M_INFO("(ERRR)Current <%d>\n", u16Read); - //break; - } - - if (hif_small_xfer == 3) - { - hif_small_xfer = 0; - hif_chip_sleep(); - } - - //}while(u16ReadCount != 0); - } -} -#endif -/********************************************************************* -Function - m2m_ip_cb - -Description - Callback function used by the NMC1000 driver to deliver messages - for socket layer. - -Return - None. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 17 July 2012 -*********************************************************************/ -static void m2m_ip_cb(uint8 u8OpCode, uint16 u16BufferSize,uint32 u32Address) -{ - if((u8OpCode == SOCKET_CMD_BIND) || (u8OpCode == SOCKET_CMD_SSL_BIND)) - { - tstrBindReply strBindReply; - tstrSocketBindMsg strBind; - - if(hif_receive(u32Address, (uint8*)&strBindReply, sizeof(tstrBindReply), 0) == M2M_SUCCESS) - { - strBind.status = strBindReply.s8Status; - if(gpfAppSocketCb) - gpfAppSocketCb(strBindReply.sock,SOCKET_MSG_BIND,&strBind); - } - } - else if(u8OpCode == SOCKET_CMD_LISTEN) - { - tstrListenReply strListenReply; - tstrSocketListenMsg strListen; - if(hif_receive(u32Address, (uint8*)&strListenReply, sizeof(tstrListenReply), 0) == M2M_SUCCESS) - { - strListen.status = strListenReply.s8Status; - if(gpfAppSocketCb) - gpfAppSocketCb(strListenReply.sock,SOCKET_MSG_LISTEN, &strListen); - } - } - else if(u8OpCode == SOCKET_CMD_ACCEPT) - { - tstrAcceptReply strAcceptReply; - tstrSocketAcceptMsg strAccept; - if(hif_receive(u32Address, (uint8*)&strAcceptReply, sizeof(tstrAcceptReply), 0) == M2M_SUCCESS) - { - if(strAcceptReply.sConnectedSock >= 0) - { - gastrSockets[strAcceptReply.sConnectedSock].u8SSLFlags = gastrSockets[strAcceptReply.sListenSock].u8SSLFlags; - gastrSockets[strAcceptReply.sConnectedSock].bIsUsed = 1; - gastrSockets[strAcceptReply.sConnectedSock].u16DataOffset = strAcceptReply.u16AppDataOffset - M2M_HIF_HDR_OFFSET; - - /* The session ID is used to distinguish different socket connections - by comparing the assigned session ID to the one reported by the firmware*/ - ++gu16SessionID; - if(gu16SessionID == 0) - ++gu16SessionID; - - gastrSockets[strAcceptReply.sConnectedSock].u16SessionID = gu16SessionID; - M2M_DBG("Socket %d session ID = %d\r\n",strAcceptReply.sConnectedSock , gu16SessionID ); - } - strAccept.sock = strAcceptReply.sConnectedSock; - strAccept.strAddr.sin_family = AF_INET; - strAccept.strAddr.sin_port = strAcceptReply.strAddr.u16Port; - strAccept.strAddr.sin_addr.s_addr = strAcceptReply.strAddr.u32IPAddr; - if(gpfAppSocketCb) - gpfAppSocketCb(strAcceptReply.sListenSock, SOCKET_MSG_ACCEPT, &strAccept); - } - } - else if((u8OpCode == SOCKET_CMD_CONNECT) || (u8OpCode == SOCKET_CMD_SSL_CONNECT)) - { - tstrConnectReply strConnectReply; - tstrSocketConnectMsg strConnMsg; - if(hif_receive(u32Address, (uint8*)&strConnectReply, sizeof(tstrConnectReply), 0) == M2M_SUCCESS) - { - strConnMsg.sock = strConnectReply.sock; - strConnMsg.s8Error = strConnectReply.s8Error; - if(strConnectReply.s8Error == SOCK_ERR_NO_ERROR) - { - gastrSockets[strConnectReply.sock].u16DataOffset = strConnectReply.u16AppDataOffset - M2M_HIF_HDR_OFFSET; - } - if(gpfAppSocketCb) - gpfAppSocketCb(strConnectReply.sock,SOCKET_MSG_CONNECT, &strConnMsg); - } - } - else if(u8OpCode == SOCKET_CMD_DNS_RESOLVE) - { - tstrDnsReply strDnsReply; - if(hif_receive(u32Address, (uint8*)&strDnsReply, sizeof(tstrDnsReply), 0) == M2M_SUCCESS) - { - if(gpfAppResolveCb) - gpfAppResolveCb((uint8*)strDnsReply.acHostName, strDnsReply.u32HostIP); - } - } - else if((u8OpCode == SOCKET_CMD_RECV) || (u8OpCode == SOCKET_CMD_RECVFROM) || (u8OpCode == SOCKET_CMD_SSL_RECV)) - { - SOCKET sock; - sint16 s16RecvStatus; - tstrRecvReply strRecvReply; - uint16 u16ReadSize; - tstrSocketRecvMsg strRecvMsg; - uint8 u8CallbackMsgID = SOCKET_MSG_RECV; - uint16 u16DataOffset; - - if(u8OpCode == SOCKET_CMD_RECVFROM) - u8CallbackMsgID = SOCKET_MSG_RECVFROM; - - /* Read RECV REPLY data structure. - */ - u16ReadSize = sizeof(tstrRecvReply); - if(hif_receive(u32Address, (uint8*)&strRecvReply, u16ReadSize, 0) == M2M_SUCCESS) - { - uint16 u16SessionID = 0; - - sock = strRecvReply.sock; - u16SessionID = strRecvReply.u16SessionID; - M2M_DBG("recv callback session ID = %d\r\n",u16SessionID); - - /* Reset the Socket RX Pending Flag. - */ - gastrSockets[sock].bIsRecvPending = 0; - - s16RecvStatus = NM_BSP_B_L_16(strRecvReply.s16RecvStatus); - u16DataOffset = NM_BSP_B_L_16(strRecvReply.u16DataOffset); - strRecvMsg.strRemoteAddr.sin_port = strRecvReply.strRemoteAddr.u16Port; - strRecvMsg.strRemoteAddr.sin_addr.s_addr = strRecvReply.strRemoteAddr.u32IPAddr; - - if(u16SessionID == gastrSockets[sock].u16SessionID) - { -#ifdef ARDUINO - if((s16RecvStatus > 0) && (s16RecvStatus < (sint32)u16BufferSize)) -#else - if((s16RecvStatus > 0) && (s16RecvStatus < u16BufferSize)) -#endif - { - /* Skip incoming bytes until reaching the Start of Application Data. - */ - u32Address += u16DataOffset; - - /* Read the Application data and deliver it to the application callback in - the given application buffer. If the buffer is smaller than the received data, - the data is passed to the application in chunks according to its buffer size. - */ - u16ReadSize = (uint16)s16RecvStatus; - Socket_ReadSocketData(sock, &strRecvMsg, u8CallbackMsgID, u32Address, u16ReadSize); - } - else - { - strRecvMsg.s16BufferSize = s16RecvStatus; - strRecvMsg.pu8Buffer = NULL; - if(gpfAppSocketCb) - gpfAppSocketCb(sock,u8CallbackMsgID, &strRecvMsg); - } - } - else - { - M2M_DBG("Discard recv callback %d %d \r\n",u16SessionID , gastrSockets[sock].u16SessionID); - if(u16ReadSize < u16BufferSize) - { - if(hif_receive(0, NULL, 0, 1) == M2M_SUCCESS) - M2M_DBG("hif_receive Success\n"); - else -#ifdef ARDUINO - { -#endif - M2M_DBG("hif_receive Fail\n"); -#ifdef ARDUINO - } -#endif - } - } - } - } - else if((u8OpCode == SOCKET_CMD_SEND) || (u8OpCode == SOCKET_CMD_SENDTO) || (u8OpCode == SOCKET_CMD_SSL_SEND)) - { - SOCKET sock; - sint16 s16Rcvd; - tstrSendReply strReply; - uint8 u8CallbackMsgID = SOCKET_MSG_SEND; - - if(u8OpCode == SOCKET_CMD_SENDTO) - u8CallbackMsgID = SOCKET_MSG_SENDTO; - - if(hif_receive(u32Address, (uint8*)&strReply, sizeof(tstrSendReply), 0) == M2M_SUCCESS) - { - uint16 u16SessionID = 0; - - sock = strReply.sock; - u16SessionID = strReply.u16SessionID; - M2M_DBG("send callback session ID = %d\r\n",u16SessionID); - - s16Rcvd = NM_BSP_B_L_16(strReply.s16SentBytes); - - if(u16SessionID == gastrSockets[sock].u16SessionID) - { - if(gpfAppSocketCb) - gpfAppSocketCb(sock,u8CallbackMsgID, &s16Rcvd); - } - else - { - M2M_DBG("Discard send callback %d %d \r\n",u16SessionID , gastrSockets[sock].u16SessionID); - } - } - } - else if(u8OpCode == SOCKET_CMD_PING) - { - tstrPingReply strPingReply; - if(hif_receive(u32Address, (uint8*)&strPingReply, sizeof(tstrPingReply), 1) == M2M_SUCCESS) - { - gfpPingCb = (void (*)(uint32 , uint32 , uint8))(uintptr_t)strPingReply.u32CmdPrivate; - if(gfpPingCb != NULL) - { - gfpPingCb(strPingReply.u32IPAddr, strPingReply.u32RTT, strPingReply.u8ErrorCode); - } - } - } -} -/********************************************************************* -Function - socketInit - -Description - -Return - None. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -void socketInit(void) -{ - if(gbSocketInit == 0) - { - m2m_memset((uint8*)gastrSockets, 0, MAX_SOCKET * sizeof(tstrSocket)); - hif_register_cb(M2M_REQ_GROUP_IP,m2m_ip_cb); - gbSocketInit = 1; - gu16SessionID = 0; - } -} -/********************************************************************* -Function - socketDeinit - -Description - -Return - None. - -Author - Samer Sarhan - -Version - 1.0 - -Date - 27 Feb 2015 -*********************************************************************/ -void socketDeinit(void) -{ - m2m_memset((uint8*)gastrSockets, 0, MAX_SOCKET * sizeof(tstrSocket)); - hif_register_cb(M2M_REQ_GROUP_IP, NULL); - gpfAppSocketCb = NULL; - gpfAppResolveCb = NULL; - gbSocketInit = 0; -} -/********************************************************************* -Function - registerSocketCallback - -Description - -Return - None. - -Author - Ahmed Ezzat - -Versio - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -void registerSocketCallback(tpfAppSocketCb pfAppSocketCb, tpfAppResolveCb pfAppResolveCb) -{ - gpfAppSocketCb = pfAppSocketCb; - gpfAppResolveCb = pfAppResolveCb; -} - -/********************************************************************* -Function - socket - -Description - Creates a socket. - -Return - - Negative value for error. - - ZERO or positive value as a socket ID if successful. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags) -{ - SOCKET sock = -1; - uint8 u8SockID; - uint8 u8Count; - volatile tstrSocket *pstrSock; - static volatile uint8 u8NextTcpSock = 0; - static volatile uint8 u8NextUdpSock = 0; - - /* The only supported family is the AF_INET for UDP and TCP transport layer protocols. */ - if(u16Domain == AF_INET) - { - if(u8Type == SOCK_STREAM) - { - for(u8Count = 0; u8Count < TCP_SOCK_MAX; u8Count ++) - { - u8SockID = u8NextTcpSock; - pstrSock = &gastrSockets[u8NextTcpSock]; - u8NextTcpSock = (u8NextTcpSock + 1) % TCP_SOCK_MAX; - if(!pstrSock->bIsUsed) - { - sock = (SOCKET)u8SockID; - break; - } - } - } - else if(u8Type == SOCK_DGRAM) - { - volatile tstrSocket *pastrUDPSockets = &gastrSockets[TCP_SOCK_MAX]; - for(u8Count = 0; u8Count < UDP_SOCK_MAX; u8Count ++) - { - u8SockID = u8NextUdpSock; - pstrSock = &pastrUDPSockets[u8NextUdpSock]; - u8NextUdpSock = (u8NextUdpSock + 1) % UDP_SOCK_MAX; - if(!pstrSock->bIsUsed) - { - sock = (SOCKET)(u8SockID + TCP_SOCK_MAX); - break; - } - } - } - - if(sock >= 0) - { - m2m_memset((uint8*)pstrSock, 0, sizeof(tstrSocket)); - pstrSock->bIsUsed = 1; - - /* The session ID is used to distinguish different socket connections - by comparing the assigned session ID to the one reported by the firmware*/ - ++gu16SessionID; - if(gu16SessionID == 0) - ++gu16SessionID; - - pstrSock->u16SessionID = gu16SessionID; - M2M_INFO("Socket %d session ID = %d\r\n",sock, gu16SessionID ); - - if(u8Flags & SOCKET_FLAGS_SSL) - { - tstrSSLSocketCreateCmd strSSLCreate; - strSSLCreate.sslSock = sock; - pstrSock->u8SSLFlags = SSL_FLAGS_ACTIVE | SSL_FLAGS_NO_TX_COPY; - SOCKET_REQUEST(SOCKET_CMD_SSL_CREATE, (uint8*)&strSSLCreate, sizeof(tstrSSLSocketCreateCmd), 0, 0, 0); - } - } - } - return sock; -} -/********************************************************************* -Function - bind - -Description - Request to bind a socket on a local address. - -Return - - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 5 June 2012 -*********************************************************************/ -sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen) -{ - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - if((pstrAddr != NULL) && (sock >= 0) && (gastrSockets[sock].bIsUsed == 1) && (u8AddrLen != 0)) - { - tstrBindCmd strBind; - uint8 u8CMD = SOCKET_CMD_BIND; - if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) - { - u8CMD = SOCKET_CMD_SSL_BIND; - } - - /* Build the bind request. */ - strBind.sock = sock; - m2m_memcpy((uint8 *)&strBind.strAddr, (uint8 *)pstrAddr, sizeof(tstrSockAddr)); - strBind.u16SessionID = gastrSockets[sock].u16SessionID; - - /* Send the request. */ - s8Ret = SOCKET_REQUEST(u8CMD, (uint8*)&strBind,sizeof(tstrBindCmd) , NULL , 0, 0); - if(s8Ret != SOCK_ERR_NO_ERROR) - { - s8Ret = SOCK_ERR_INVALID; - } - } - return s8Ret; -} -/********************************************************************* -Function - listen - -Description - - -Return - - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 5 June 2012 -*********************************************************************/ -sint8 listen(SOCKET sock, uint8 backlog) -{ - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - - if(sock >= 0 && (gastrSockets[sock].bIsUsed == 1)) - { - tstrListenCmd strListen; - - strListen.sock = sock; - strListen.u8BackLog = backlog; - strListen.u16SessionID = gastrSockets[sock].u16SessionID; - - s8Ret = SOCKET_REQUEST(SOCKET_CMD_LISTEN, (uint8*)&strListen, sizeof(tstrListenCmd), NULL, 0, 0); - if(s8Ret != SOCK_ERR_NO_ERROR) - { - s8Ret = SOCK_ERR_INVALID; - } - } - return s8Ret; -} -/********************************************************************* -Function - accept - -Description - -Return - - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 5 June 2012 -*********************************************************************/ -sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)addr; - (void)addrlen; -#endif - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - - if(sock >= 0 && (gastrSockets[sock].bIsUsed == 1) ) - { - s8Ret = SOCK_ERR_NO_ERROR; - } - return s8Ret; -} -/********************************************************************* -Function - connect - -Description - Connect to a remote TCP Server. - -Return - - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 5 June 2012 -*********************************************************************/ -#ifdef ARDUINO -sint8 connectSocket(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen) -#else -sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen) -#endif -{ - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - if((sock >= 0) && (pstrAddr != NULL) && (gastrSockets[sock].bIsUsed == 1) && (u8AddrLen != 0)) - { - tstrConnectCmd strConnect; - uint8 u8Cmd = SOCKET_CMD_CONNECT; - if((gastrSockets[sock].u8SSLFlags) & SSL_FLAGS_ACTIVE) - { - u8Cmd = SOCKET_CMD_SSL_CONNECT; - strConnect.u8SslFlags = gastrSockets[sock].u8SSLFlags; - } - strConnect.sock = sock; - m2m_memcpy((uint8 *)&strConnect.strAddr, (uint8 *)pstrAddr, sizeof(tstrSockAddr)); - - strConnect.u16SessionID = gastrSockets[sock].u16SessionID; - s8Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strConnect,sizeof(tstrConnectCmd), NULL, 0, 0); - if(s8Ret != SOCK_ERR_NO_ERROR) - { - s8Ret = SOCK_ERR_INVALID; - } - } - return s8Ret; -} -/********************************************************************* -Function - send - -Description - -Return - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 5 June 2012 -*********************************************************************/ -sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags) -{ -#ifdef ARDUINO - (void)flags; // Silence "unused" warning -#endif - sint16 s16Ret = SOCK_ERR_INVALID_ARG; - - if((sock >= 0) && (pvSendBuffer != NULL) && (u16SendLength <= SOCKET_BUFFER_MAX_LENGTH) && (gastrSockets[sock].bIsUsed == 1)) - { - uint16 u16DataOffset; - tstrSendCmd strSend; - uint8 u8Cmd; - - u8Cmd = SOCKET_CMD_SEND; - u16DataOffset = TCP_TX_PACKET_OFFSET; - - strSend.sock = sock; - strSend.u16DataSize = NM_BSP_B_L_16(u16SendLength); - strSend.u16SessionID = gastrSockets[sock].u16SessionID; - - if(sock >= TCP_SOCK_MAX) - { - u16DataOffset = UDP_TX_PACKET_OFFSET; - } - if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) - { - u8Cmd = SOCKET_CMD_SSL_SEND; - u16DataOffset = gastrSockets[sock].u16DataOffset; -#ifdef ARDUINO - extern uint32 nmdrv_firm_ver; - - if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 4, 0)) { - // firmware 19.3.0 and older only works with this specific offset - u16DataOffset = SSL_TX_PACKET_OFFSET; - } -#endif - } - - s16Ret = SOCKET_REQUEST(u8Cmd|M2M_REQ_DATA_PKT, (uint8*)&strSend, sizeof(tstrSendCmd), pvSendBuffer, u16SendLength, u16DataOffset); - if(s16Ret != SOCK_ERR_NO_ERROR) - { - s16Ret = SOCK_ERR_BUFFER_FULL; - } - } - return s16Ret; -} -/********************************************************************* -Function - sendto - -Description - -Return - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)flags; - (void)u8AddrLen; -#endif - sint16 s16Ret = SOCK_ERR_INVALID_ARG; - - if((sock >= 0) && (pvSendBuffer != NULL) && (u16SendLength <= SOCKET_BUFFER_MAX_LENGTH) && (gastrSockets[sock].bIsUsed == 1)) - { - if(gastrSockets[sock].bIsUsed) - { - tstrSendCmd strSendTo; - - m2m_memset((uint8*)&strSendTo, 0, sizeof(tstrSendCmd)); - - strSendTo.sock = sock; - strSendTo.u16DataSize = NM_BSP_B_L_16(u16SendLength); - strSendTo.u16SessionID = gastrSockets[sock].u16SessionID; - - if(pstrDestAddr != NULL) - { - struct sockaddr_in *pstrAddr; - pstrAddr = (void*)pstrDestAddr; - - strSendTo.strAddr.u16Family = pstrAddr->sin_family; - strSendTo.strAddr.u16Port = pstrAddr->sin_port; - strSendTo.strAddr.u32IPAddr = pstrAddr->sin_addr.s_addr; - } - s16Ret = SOCKET_REQUEST(SOCKET_CMD_SENDTO|M2M_REQ_DATA_PKT, (uint8*)&strSendTo, sizeof(tstrSendCmd), - pvSendBuffer, u16SendLength, UDP_TX_PACKET_OFFSET); - - if(s16Ret != SOCK_ERR_NO_ERROR) - { - s16Ret = SOCK_ERR_BUFFER_FULL; - } - } - } - return s16Ret; -} -/********************************************************************* -Function - recv - -Description - -Return - - -Author - Ahmed Ezzat - -Version - 1.0 - 2.0 9 April 2013 --> Add timeout for recv operation. - -Date - 5 June 2012 -*********************************************************************/ -sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec) -{ - sint16 s16Ret = SOCK_ERR_INVALID_ARG; - - if((sock >= 0) && (pvRecvBuf != NULL) && (u16BufLen != 0) && (gastrSockets[sock].bIsUsed == 1)) - { - s16Ret = SOCK_ERR_NO_ERROR; - gastrSockets[sock].pu8UserBuffer = (uint8*)pvRecvBuf; - gastrSockets[sock].u16UserBufferSize = u16BufLen; - - if(!gastrSockets[sock].bIsRecvPending) - { - tstrRecvCmd strRecv; - uint8 u8Cmd = SOCKET_CMD_RECV; - - gastrSockets[sock].bIsRecvPending = 1; - if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) - { - u8Cmd = SOCKET_CMD_SSL_RECV; - } - - /* Check the timeout value. */ - if(u32Timeoutmsec == 0) - strRecv.u32Timeoutmsec = 0xFFFFFFFF; - else - strRecv.u32Timeoutmsec = NM_BSP_B_L_32(u32Timeoutmsec); - strRecv.sock = sock; - strRecv.u16SessionID = gastrSockets[sock].u16SessionID; - - s16Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strRecv, sizeof(tstrRecvCmd), NULL , 0, 0); - if(s16Ret != SOCK_ERR_NO_ERROR) - { - s16Ret = SOCK_ERR_BUFFER_FULL; - } - } - } - return s16Ret; -} -/********************************************************************* -Function - close - -Description - -Return - None. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -sint8 close(SOCKET sock) -{ - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - M2M_INFO("Sock to delete <%d>\n", sock); - if(sock >= 0 && (gastrSockets[sock].bIsUsed == 1)) - { - uint8 u8Cmd = SOCKET_CMD_CLOSE; - tstrCloseCmd strclose; - strclose.sock = sock; - strclose.u16SessionID = gastrSockets[sock].u16SessionID; - - gastrSockets[sock].bIsUsed = 0; - gastrSockets[sock].u16SessionID =0; - - if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) - { - u8Cmd = SOCKET_CMD_SSL_CLOSE; - } - s8Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strclose, sizeof(tstrCloseCmd), NULL,0, 0); - if(s8Ret != SOCK_ERR_NO_ERROR) - { - s8Ret = SOCK_ERR_INVALID; - } - m2m_memset((uint8*)&gastrSockets[sock], 0, sizeof(tstrSocket)); - } - return s8Ret; -} -/********************************************************************* -Function - recvfrom - -Description - -Return - - -Author - Ahmed Ezzat - -Version - 1.0 - 2.0 9 April 2013 --> Add timeout for recv operation. - -Date - 5 June 2012 -*********************************************************************/ -sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec) -{ - sint16 s16Ret = SOCK_ERR_NO_ERROR; - if((sock >= 0) && (pvRecvBuf != NULL) && (u16BufLen != 0) && (gastrSockets[sock].bIsUsed == 1)) - { - if(gastrSockets[sock].bIsUsed) - { - s16Ret = SOCK_ERR_NO_ERROR; - gastrSockets[sock].pu8UserBuffer = (uint8*)pvRecvBuf; - gastrSockets[sock].u16UserBufferSize = u16BufLen; - - if(!gastrSockets[sock].bIsRecvPending) - { - tstrRecvCmd strRecv; - - gastrSockets[sock].bIsRecvPending = 1; - - /* Check the timeout value. */ - if(u32Timeoutmsec == 0) - strRecv.u32Timeoutmsec = 0xFFFFFFFF; - else - strRecv.u32Timeoutmsec = NM_BSP_B_L_32(u32Timeoutmsec); - strRecv.sock = sock; - strRecv.u16SessionID = gastrSockets[sock].u16SessionID; - - s16Ret = SOCKET_REQUEST(SOCKET_CMD_RECVFROM, (uint8*)&strRecv, sizeof(tstrRecvCmd), NULL , 0, 0); - if(s16Ret != SOCK_ERR_NO_ERROR) - { - s16Ret = SOCK_ERR_BUFFER_FULL; - } - } - } - } - else - { - s16Ret = SOCK_ERR_INVALID_ARG; - } - return s16Ret; -} -/********************************************************************* -Function - nmi_inet_addr - -Description - -Return - Unsigned 32-bit integer representing the IP address in Network - byte order. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -uint32 nmi_inet_addr(char *pcIpAddr) -{ - uint8 tmp; - uint32 u32IP = 0; - uint8 au8IP[4]; - uint8 c; - uint8 i, j; - - tmp = 0; - - for(i = 0; i < 4; ++i) - { - j = 0; - do - { - c = *pcIpAddr; - ++j; - if(j > 4) - { - return 0; - } - if(c == '.' || c == 0) - { - au8IP[i] = tmp; - tmp = 0; - } - else if(c >= '0' && c <= '9') - { - tmp = (tmp * 10) + (c - '0'); - } - else - { - return 0; - } - ++pcIpAddr; - } while(c != '.' && c != 0); - } - m2m_memcpy((uint8*)&u32IP, au8IP, 4); - return u32IP; -} -/********************************************************************* -Function - gethostbyname - -Description - -Return - None. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -sint8 gethostbyname(uint8 * pcHostName) -{ - sint8 s8Err = SOCK_ERR_INVALID_ARG; - uint8 u8HostNameSize = (uint8)m2m_strlen(pcHostName); - if(u8HostNameSize <= HOSTNAME_MAX_SIZE) - { - s8Err = SOCKET_REQUEST(SOCKET_CMD_DNS_RESOLVE, (uint8*)pcHostName, u8HostNameSize + 1, NULL,0, 0); - } - return s8Err; -} -/********************************************************************* -Function - setsockopt - -Description - -Return - None. - -Author - Abdelrahman Diab - -Version - 1.0 - -Date - 9 September 2014 -*********************************************************************/ -static sint8 sslSetSockOpt(SOCKET sock, uint8 u8Opt, const void *pvOptVal, uint16 u16OptLen) -{ - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - if(sock < TCP_SOCK_MAX) - { - if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) - { - if(u8Opt == SO_SSL_BYPASS_X509_VERIF) - { - int optVal = *((int*)pvOptVal); - if(optVal) - { - gastrSockets[sock].u8SSLFlags |= SSL_FLAGS_BYPASS_X509; - } - else - { - gastrSockets[sock].u8SSLFlags &= ~SSL_FLAGS_BYPASS_X509; - } - s8Ret = SOCK_ERR_NO_ERROR; - } - else if(u8Opt == SO_SSL_ENABLE_SESSION_CACHING) - { - int optVal = *((int*)pvOptVal); - if(optVal) - { - gastrSockets[sock].u8SSLFlags |= SSL_FLAGS_CACHE_SESSION; - } - else - { - gastrSockets[sock].u8SSLFlags &= ~SSL_FLAGS_CACHE_SESSION; - } - s8Ret = SOCK_ERR_NO_ERROR; - } - else if(u8Opt == SO_SSL_ENABLE_SNI_VALIDATION) - { - int optVal = *((int*)pvOptVal); - if(optVal) - { - gastrSockets[sock].u8SSLFlags |= SSL_FLAGS_CHECK_SNI; - } - else - { - gastrSockets[sock].u8SSLFlags &= ~SSL_FLAGS_CHECK_SNI; - } - s8Ret = SOCK_ERR_NO_ERROR; - } - else if(u8Opt == SO_SSL_SNI) - { - if(u16OptLen < HOSTNAME_MAX_SIZE) - { - uint8 *pu8SNI = (uint8*)pvOptVal; - tstrSSLSetSockOptCmd strCmd; - - strCmd.sock = sock; - strCmd.u16SessionID = gastrSockets[sock].u16SessionID; - strCmd.u8Option = u8Opt; - strCmd.u32OptLen = u16OptLen; - m2m_memcpy(strCmd.au8OptVal, pu8SNI, HOSTNAME_MAX_SIZE); - - if(SOCKET_REQUEST(SOCKET_CMD_SSL_SET_SOCK_OPT, (uint8*)&strCmd, sizeof(tstrSSLSetSockOptCmd), - 0, 0, 0) == M2M_ERR_MEM_ALLOC) - { - s8Ret = SOCKET_REQUEST(SOCKET_CMD_SSL_SET_SOCK_OPT | M2M_REQ_DATA_PKT, - (uint8*)&strCmd, sizeof(tstrSSLSetSockOptCmd), 0, 0, 0); - } - s8Ret = SOCK_ERR_NO_ERROR; - } - else - { - M2M_ERR("SNI Exceeds Max Length\n"); - } - } - else - { - M2M_ERR("Unknown SSL Socket Option %d\n",u8Opt); - } - } - else - { - M2M_ERR("Not SSL Socket\n"); - } - } - return s8Ret; -} -/********************************************************************* -Function - setsockopt - -Description - -Return - None. - -Author - Abdelrahman Diab - -Version - 1.0 - -Date - 9 September 2014 -*********************************************************************/ -sint8 setsockopt(SOCKET sock, uint8 u8Level, uint8 option_name, - const void *option_value, uint16 u16OptionLen) -{ - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - if((sock >= 0) && (option_value != NULL) && (gastrSockets[sock].bIsUsed == 1)) - { - if(u8Level == SOL_SSL_SOCKET) - { - s8Ret = sslSetSockOpt(sock, option_name, option_value, u16OptionLen); - } - else - { - uint8 u8Cmd = SOCKET_CMD_SET_SOCKET_OPTION; - tstrSetSocketOptCmd strSetSockOpt; - strSetSockOpt.u8Option=option_name; - strSetSockOpt.sock = sock; - strSetSockOpt.u32OptionValue = *(uint32*)option_value; - strSetSockOpt.u16SessionID = gastrSockets[sock].u16SessionID; - - s8Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strSetSockOpt, sizeof(tstrSetSocketOptCmd), NULL,0, 0); - if(s8Ret != SOCK_ERR_NO_ERROR) - { - s8Ret = SOCK_ERR_INVALID; - } - } - } - return s8Ret; -} -/********************************************************************* -Function - getsockopt - -Description - -Return - None. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 24 August 2014 -*********************************************************************/ -sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8* pu8OptLen) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)sock; - (void)u8Level; - (void)u8OptName; - (void)pvOptValue; - (void)pu8OptLen; -#endif - /* TBD */ - return M2M_SUCCESS; -} -/********************************************************************* -Function - m2m_ping_req - -Description - Send Ping request. - -Return - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2015 -*********************************************************************/ -sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb) -{ - sint8 s8Ret = M2M_ERR_INVALID_ARG; - - if((u32DstIP != 0) && (fpPingCb != NULL)) - { - tstrPingCmd strPingCmd; - - strPingCmd.u16PingCount = 1; - strPingCmd.u32DestIPAddr = u32DstIP; -#ifdef ARDUINO - strPingCmd.u32CmdPrivate = (uint32)(uintptr_t)(fpPingCb); -#else - strPingCmd.u32CmdPrivate = (uint32)(fpPingCb); -#endif - strPingCmd.u8TTL = u8TTL; - - s8Ret = SOCKET_REQUEST(SOCKET_CMD_PING, (uint8*)&strPingCmd, sizeof(tstrPingCmd), NULL, 0, 0); - } - return s8Ret; -} -/********************************************************************* -Function - sslEnableCertExpirationCheck - -Description - Enable/Disable TLS Certificate Expiration Check. - -Return - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - -*********************************************************************/ -sint8 sslEnableCertExpirationCheck(tenuSslCertExpSettings enuValidationSetting) -{ - tstrSslCertExpSettings strSettings; - strSettings.u32CertExpValidationOpt = (uint32)enuValidationSetting; - return SOCKET_REQUEST(SOCKET_CMD_SSL_EXP_CHECK, (uint8*)&strSettings, sizeof(tstrSslCertExpSettings), NULL, 0, 0); -} \ No newline at end of file diff --git a/feather_sensor_lte/libraries/WiFi101/src/socket/source/socket_buffer.c b/feather_sensor_lte/libraries/WiFi101/src/socket/source/socket_buffer.c deleted file mode 100644 index d100558..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/socket/source/socket_buffer.c +++ /dev/null @@ -1,232 +0,0 @@ -/** - * - * \file - * - * \brief BSD compatible socket interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include -#include "socket/include/socket.h" -#include "driver/source/m2m_hif.h" -#include "socket/source/socket_internal.h" -#include "socket/include/socket_buffer.h" -#include "driver/include/m2m_periph.h" - -tstrSocketBuffer gastrSocketBuffer[MAX_SOCKET]; - -extern uint8 hif_small_xfer; - -void socketBufferInit(void) -{ - memset(gastrSocketBuffer, 0, sizeof(gastrSocketBuffer)); -} - -void socketBufferRegister(SOCKET socket, uint32 *flag, uint32 *head, uint32 *tail, uint8 *buffer) -{ - gastrSocketBuffer[socket].flag = flag; - gastrSocketBuffer[socket].head = head; - gastrSocketBuffer[socket].tail = tail; - gastrSocketBuffer[socket].buffer = buffer; -} - -void socketBufferUnregister(SOCKET socket) -{ - gastrSocketBuffer[socket].flag = 0; - gastrSocketBuffer[socket].head = 0; - gastrSocketBuffer[socket].tail = 0; - gastrSocketBuffer[socket].buffer = 0; -} - -void socketBufferCb(SOCKET sock, uint8 u8Msg, void *pvMsg) -{ - switch (u8Msg) { - /* Socket connected. */ - case SOCKET_MSG_CONNECT: - { - tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg *)pvMsg; - if (pstrConnect && pstrConnect->s8Error >= 0) { - recv(sock, gastrSocketBuffer[sock].buffer, SOCKET_BUFFER_MTU, 0); - *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_CONNECTED; - } else { - close(sock); - } - } - break; - - /* TCP Data receive. */ - case SOCKET_MSG_RECV: - { - // Network led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); - - tstrSocketRecvMsg *pstrRecv = (tstrSocketRecvMsg *)pvMsg; - if (pstrRecv && pstrRecv->s16BufferSize > 0) { - /* Protect against overflow. */ - if (*(gastrSocketBuffer[sock].head) + pstrRecv->s16BufferSize > SOCKET_BUFFER_TCP_SIZE) { - *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_FULL; - break; - } - - /* Add data size. */ - *(gastrSocketBuffer[sock].head) += pstrRecv->s16BufferSize; - - /* Buffer full, stop reception. */ - if (SOCKET_BUFFER_TCP_SIZE - *(gastrSocketBuffer[sock].head) < SOCKET_BUFFER_MTU) { - if (pstrRecv->u16RemainingSize != 0) { - *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_FULL; - } - } - else { - recv(sock, gastrSocketBuffer[sock].buffer + *(gastrSocketBuffer[sock].head), - SOCKET_BUFFER_MTU, 0); - } - } - /* Test EOF (Socket closed) condition for TCP socket. */ - else { - *(gastrSocketBuffer[sock].flag) &= ~SOCKET_BUFFER_FLAG_CONNECTED; - close(sock); - } - - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - } - break; - - /* UDP Data receive. */ - case SOCKET_MSG_RECVFROM: - { - // Network led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); - - tstrSocketRecvMsg *pstrRecv = (tstrSocketRecvMsg *)pvMsg; - if (pstrRecv && pstrRecv->s16BufferSize > 0) { - - if (hif_small_xfer < 2) { - uint32 h = *(gastrSocketBuffer[sock].head); - uint8 *buf = gastrSocketBuffer[sock].buffer; - uint16 sz = pstrRecv->s16BufferSize + pstrRecv->u16RemainingSize; - - /* Store packet size. */ - buf[h++] = sz >> 8; - buf[h++] = sz; - - /* Store remote host port. */ - buf[h++] = pstrRecv->strRemoteAddr.sin_port; - buf[h++] = pstrRecv->strRemoteAddr.sin_port >> 8; - - /* Store remote host IP. */ - buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr >> 24; - buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr >> 16; - buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr >> 8; - buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr; - - /* Data received. */ - *(gastrSocketBuffer[sock].head) = h + pstrRecv->s16BufferSize; - } - else { - /* Data received. */ - *(gastrSocketBuffer[sock].head) += pstrRecv->s16BufferSize; - } - - /* Buffer full, stop reception. */ - if (SOCKET_BUFFER_UDP_SIZE - *(gastrSocketBuffer[sock].head) < SOCKET_BUFFER_MTU + SOCKET_BUFFER_UDP_HEADER_SIZE) { - if (pstrRecv->u16RemainingSize != 0) { - *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_FULL; - } - } - else { - if (hif_small_xfer && hif_small_xfer != 3) { - recvfrom(sock, gastrSocketBuffer[sock].buffer + *(gastrSocketBuffer[sock].head), - SOCKET_BUFFER_MTU, 0); - } - else { - recvfrom(sock, gastrSocketBuffer[sock].buffer + *(gastrSocketBuffer[sock].head) + SOCKET_BUFFER_UDP_HEADER_SIZE, - SOCKET_BUFFER_MTU, 0); - } - } - } - - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - } - break; - - /* Socket bind. */ - case SOCKET_MSG_BIND: - { - tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg *)pvMsg; - if (pstrBind && pstrBind->status == 0) { - *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_BIND; - /* TCP socket needs to enter Listen state. */ - if (sock < TCP_SOCK_MAX) { - listen(sock, 0); - } - /* UDP socket only needs to supply the receive buffer. */ - /* +8 is used to store size, port and IP of incoming data. */ - else { - recvfrom(sock, gastrSocketBuffer[sock].buffer + SOCKET_BUFFER_UDP_HEADER_SIZE, - SOCKET_BUFFER_MTU, 0); - } - } - } - break; - - /* Connect accept. */ - case SOCKET_MSG_ACCEPT: - { - tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg *)pvMsg; - if (pstrAccept && pstrAccept->sock >= 0) { - if (*(gastrSocketBuffer[sock].flag) & SOCKET_BUFFER_FLAG_SPAWN) { - /* One spawn connection already waiting, discard current one. */ - close(pstrAccept->sock); - } - else { - /* Use flag to store spawn TCP descriptor. */ - *(gastrSocketBuffer[sock].flag) &= ~SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK; - *(gastrSocketBuffer[sock].flag) |= (((uint32)pstrAccept->sock) << SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS); - *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_SPAWN; - } - } - } - break; - - } -} diff --git a/feather_sensor_lte/libraries/WiFi101/src/socket/source/socket_internal.h b/feather_sensor_lte/libraries/WiFi101/src/socket/source/socket_internal.h deleted file mode 100644 index 1904c23..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/socket/source/socket_internal.h +++ /dev/null @@ -1,71 +0,0 @@ -/** - * - * \file - * - * \brief BSD compatible socket interface internal types. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -#ifndef __SOCKET_INTERNAL_H__ -#define __SOCKET_INTERNAL_H__ - - -#ifdef __cplusplus -extern "C" { -#endif - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "socket/include/socket.h" -#include "socket/include/m2m_socket_host_if.h" - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -NMI_API void Socket_ReadSocketData(SOCKET sock, tstrSocketRecvMsg *pstrRecv,uint8 u8SocketMsg, - uint32 u32StartAddress,uint16 u16ReadCount); -#ifdef ARDUINO -NMI_API void Socket_ReadSocketData_Small(void); -#endif - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __SOCKET_H__ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/spi_flash/include/spi_flash.h b/feather_sensor_lte/libraries/WiFi101/src/spi_flash/include/spi_flash.h deleted file mode 100644 index a85aa72..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/spi_flash/include/spi_flash.h +++ /dev/null @@ -1,233 +0,0 @@ -/** - * - * \file - * - * \brief WINC1500 SPI Flash. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/** \defgroup SPIFLASH Spi Flash - * @file spi_flash.h - * @brief This file describe SPI flash APIs, how to use it and limitations with each one. - * @section Example - * This example illustrates a complete guide of how to use these APIs. - * @code{.c} - #include "spi_flash.h" - - #define DATA_TO_REPLACE "THIS IS A NEW SECTOR IN FLASH" - - int main() - { - uint8 au8FlashContent[FLASH_SECTOR_SZ] = {0}; - uint32 u32FlashTotalSize = 0; - uint32 u32FlashOffset = 0; - - ret = m2m_wifi_download_mode(); - if(M2M_SUCCESS != ret) - { - printf("Unable to enter download mode\r\n"); - } - else - { - u32FlashTotalSize = spi_flash_get_size(); - } - - while((u32FlashTotalSize > u32FlashOffset) && (M2M_SUCCESS == ret)) - { - ret = spi_flash_read(au8FlashContent, u32FlashOffset, FLASH_SECTOR_SZ); - if(M2M_SUCCESS != ret) - { - printf("Unable to read SPI sector\r\n"); - break; - } - memcpy(au8FlashContent, DATA_TO_REPLACE, strlen(DATA_TO_REPLACE)); - - ret = spi_flash_erase(u32FlashOffset, FLASH_SECTOR_SZ); - if(M2M_SUCCESS != ret) - { - printf("Unable to erase SPI sector\r\n"); - break; - } - - ret = spi_flash_write(au8FlashContent, u32FlashOffset, FLASH_SECTOR_SZ); - if(M2M_SUCCESS != ret) - { - printf("Unable to write SPI sector\r\n"); - break; - } - u32FlashOffset += FLASH_SECTOR_SZ; - } - - if(M2M_SUCCESS == ret) - { - printf("Successful operations\r\n"); - } - else - { - printf("Failed operations\r\n"); - } - - while(1); - return M2M_SUCCESS; - } - * @endcode - */ - -#ifndef __SPI_FLASH_H__ -#define __SPI_FLASH_H__ -#include "common/include/nm_common.h" -#include "bus_wrapper/include/nm_bus_wrapper.h" -#include "driver/source/nmbus.h" -#include "driver/source/nmasic.h" - -#ifdef ARDUINO -#ifdef __cplusplus -extern "C" { -#endif -#endif - -/** - * @fn spi_flash_enable - * @brief Enable spi flash operations - * @version 1.0 - */ -sint8 spi_flash_enable(uint8 enable); -/** \defgroup SPIFLASHAPI Function - * @ingroup SPIFLASH - */ - - /** @defgroup SPiFlashGetFn spi_flash_get_size - * @ingroup SPIFLASHAPI - */ - /**@{*/ -/*! - * @fn uint32 spi_flash_get_size(void); - * @brief Returns with \ref uint32 value which is total flash size\n - * @note Returned value in Mb (Mega Bit). - * @return SPI flash size in case of success and a ZERO value in case of failure. - */ -uint32 spi_flash_get_size(void); - /**@}*/ - - /** @defgroup SPiFlashRead spi_flash_read - * @ingroup SPIFLASHAPI - */ - /**@{*/ -/*! - * @fn sint8 spi_flash_read(uint8 *, uint32, uint32); - * @brief Read a specified portion of data from SPI Flash.\n - * @param [out] pu8Buf - * Pointer to data buffer which will fill in with data in case of successful operation. - * @param [in] u32Addr - * Address (Offset) to read from at the SPI flash. - * @param [in] u32Sz - * Total size of data to be read in bytes - * @warning - * - Address (offset) plus size of data must not exceed flash size.\n - * - No firmware is required for reading from SPI flash.\n - * - In case of there is a running firmware, it is required to pause your firmware first - * before any trial to access SPI flash to avoid any racing between host and running firmware on bus using - * @ref m2m_wifi_download_mode - * @note - * - It is blocking function\n - * @sa m2m_wifi_download_mode, spi_flash_get_size - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -sint8 spi_flash_read(uint8 *pu8Buf, uint32 u32Addr, uint32 u32Sz); - /**@}*/ - - /** @defgroup SPiFlashWrite spi_flash_write - * @ingroup SPIFLASHAPI - */ - /**@{*/ -/*! - * @fn sint8 spi_flash_write(uint8 *, uint32, uint32); - * @brief Write a specified portion of data to SPI Flash.\n - * @param [in] pu8Buf - * Pointer to data buffer which contains the required to be written. - * @param [in] u32Offset - * Address (Offset) to write at the SPI flash. - * @param [in] u32Sz - * Total number of size of data bytes - * @note - * - It is blocking function\n - * - It is user's responsibility to verify that data has been written successfully - * by reading data again and compare it with the original. - * @warning - * - Address (offset) plus size of data must not exceed flash size.\n - * - No firmware is required for writing to SPI flash.\n - * - In case of there is a running firmware, it is required to pause your firmware first - * before any trial to access SPI flash to avoid any racing between host and running firmware on bus using - * @ref m2m_wifi_download_mode. - * - Before writing to any section, it is required to erase it first. - * @sa m2m_wifi_download_mode, spi_flash_get_size, spi_flash_erase - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - - */ -sint8 spi_flash_write(uint8* pu8Buf, uint32 u32Offset, uint32 u32Sz); - /**@}*/ - - /** @defgroup SPiFlashErase spi_flash_erase - * @ingroup SPIFLASHAPI - */ - /**@{*/ -/*! - * @fn sint8 spi_flash_erase(uint32, uint32); - * @brief Erase a specified portion of SPI Flash.\n - * @param [in] u32Offset - * Address (Offset) to erase from the SPI flash. - * @param [in] u32Sz - * Size of SPI flash required to be erased. - * @note It is blocking function \n -* @warning -* - Address (offset) plus size of data must not exceed flash size.\n -* - No firmware is required for writing to SPI flash.\n - * - In case of there is a running firmware, it is required to pause your firmware first - * before any trial to access SPI flash to avoid any racing between host and running firmware on bus using - * @ref m2m_wifi_download_mode - * - It is blocking function\n - * @sa m2m_wifi_download_mode, spi_flash_get_size - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - - */ -sint8 spi_flash_erase(uint32 u32Offset, uint32 u32Sz); - /**@}*/ -#ifdef ARDUINO -#ifdef __cplusplus -} -#endif -#endif -#endif //__SPI_FLASH_H__ diff --git a/feather_sensor_lte/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h b/feather_sensor_lte/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h deleted file mode 100644 index 3b0da53..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h +++ /dev/null @@ -1,245 +0,0 @@ -/** - * - * \file - * - * \brief WINC1500 SPI Flash. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/** -* @file spi_flash_map.h -* @brief This module contains spi flash CONTENT -* @author M.S.M -* @date 17 SEPT 2013 -* @version 1.0 -*/ -#ifndef __SPI_FLASH_MAP_H__ -#define __SPI_FLASH_MAP_H__ - -#define FLASH_MAP_VER_0 (0) -#define FLASH_MAP_VER_1 (1) -#define FLASH_MAP_VER_2 (2) -#define FLASH_MAP_VER_3 (3) - -#define FLASH_MAP_VERSION FLASH_MAP_VER_3 - -//#define DOWNLOAD_ROLLBACK -//#define OTA_GEN -#define _PROGRAM_POWER_SAVE_ - -/* =======*=======*=======*=======*======= - * General Sizes for Flash Memory - * =======*=======*=======*=======*======= - */ - -#define FLASH_START_ADDR (0UL) -/*! location :xxxK - * "S:xxxK" -means-> Size is :xxxK - */ - -/* - * Boot Firmware: which used to select which firmware to run - * - */ -#define M2M_BOOT_FIRMWARE_STARTING_ADDR (FLASH_START_ADDR) -#define M2M_BOOT_FIRMWARE_FLASH_SZ (FLASH_SECTOR_SZ) - -/* - * Control Section: which used by Boot firmware - * - */ -#define M2M_CONTROL_FLASH_OFFSET (M2M_BOOT_FIRMWARE_STARTING_ADDR + M2M_BOOT_FIRMWARE_FLASH_SZ) -#define M2M_CONTROL_FLASH_BKP_OFFSET (M2M_CONTROL_FLASH_OFFSET + FLASH_SECTOR_SZ) -#define M2M_CONTROL_FLASH_SEC_SZ (FLASH_SECTOR_SZ) -#define M2M_CONTROL_FLASH_TOTAL_SZ (FLASH_SECTOR_SZ * 2) - -/* - * LUT for PLL and TX Gain settings: - * - */ -#define M2M_PLL_FLASH_OFFSET (M2M_CONTROL_FLASH_OFFSET + M2M_CONTROL_FLASH_TOTAL_SZ) -#define M2M_PLL_FLASH_SZ (1024 * 1) -#define M2M_GAIN_FLASH_OFFSET (M2M_PLL_FLASH_OFFSET + M2M_PLL_FLASH_SZ) -#define M2M_GAIN_FLASH_SZ (M2M_CONFIG_SECT_TOTAL_SZ - M2M_PLL_FLASH_SZ) -#define M2M_CONFIG_SECT_TOTAL_SZ (FLASH_SECTOR_SZ) - -/* - * Certificate: - * - */ -#define M2M_TLS_ROOTCER_FLASH_OFFSET (M2M_PLL_FLASH_OFFSET + M2M_CONFIG_SECT_TOTAL_SZ) -#define M2M_TLS_ROOTCER_FLASH_SIZE (FLASH_SECTOR_SZ * 1) - -/* - * TLS Server Key Files - * - */ -#define M2M_TLS_SERVER_FLASH_OFFSET (M2M_TLS_ROOTCER_FLASH_OFFSET + M2M_TLS_ROOTCER_FLASH_SIZE) -#define M2M_TLS_SERVER_FLASH_SIZE (FLASH_SECTOR_SZ * 2) - -/* - * HTTP Files - * - */ -#define M2M_HTTP_MEM_FLASH_OFFSET (M2M_TLS_SERVER_FLASH_OFFSET + M2M_TLS_SERVER_FLASH_SIZE) -#define M2M_HTTP_MEM_FLASH_SZ (FLASH_SECTOR_SZ * 2) - -/* - * Saved Connection Parameters: - * - */ -#define M2M_CACHED_CONNS_FLASH_OFFSET (M2M_HTTP_MEM_FLASH_OFFSET + M2M_HTTP_MEM_FLASH_SZ) -#define M2M_CACHED_CONNS_FLASH_SZ (FLASH_SECTOR_SZ * 1) - -/* - * - * Common section size - */ - -#define M2M_COMMON_DATA_SEC \ - (\ - M2M_BOOT_FIRMWARE_FLASH_SZ + \ - M2M_CONTROL_FLASH_TOTAL_SZ + \ - M2M_CONFIG_SECT_TOTAL_SZ + \ - M2M_TLS_ROOTCER_FLASH_SIZE + \ - M2M_TLS_SERVER_FLASH_SIZE + \ - M2M_HTTP_MEM_FLASH_SZ + \ - M2M_CACHED_CONNS_FLASH_SZ \ - ) - -/* - * - * OTA image1 Offset - */ - -#define M2M_OTA_IMAGE1_OFFSET (M2M_CACHED_CONNS_FLASH_OFFSET + M2M_CACHED_CONNS_FLASH_SZ) -/* - * Firmware Offset - * - */ -#if (defined _FIRMWARE_)||(defined OTA_GEN) -#define M2M_FIRMWARE_FLASH_OFFSET (0UL) -#else -#if (defined DOWNLOAD_ROLLBACK) -#define M2M_FIRMWARE_FLASH_OFFSET (M2M_OTA_IMAGE2_OFFSET) -#else -#define M2M_FIRMWARE_FLASH_OFFSET (M2M_OTA_IMAGE1_OFFSET) -#endif -#endif -/* - * - * Firmware - */ -#define M2M_FIRMWARE_FLASH_SZ (236 * 1024UL) -/** - * - * OTA image Size - */ -#define OTA_IMAGE_SIZE (M2M_FIRMWARE_FLASH_SZ) -/** - * - * Flash Total size - */ -#define FLASH_IMAGE1_CONTENT_SZ (M2M_COMMON_DATA_SEC + OTA_IMAGE_SIZE) - -/** - * - * OTA image 2 offset - */ -#define M2M_OTA_IMAGE2_OFFSET (FLASH_IMAGE1_CONTENT_SZ) - -/* - * App(Cortus App 4M): App. which runs over firmware - * - */ -#define M2M_APP_4M_MEM_FLASH_SZ (FLASH_SECTOR_SZ * 16) -#define M2M_APP_4M_MEM_FLASH_OFFSET (FLASH_4M_TOTAL_SZ - M2M_APP_4M_MEM_FLASH_SZ) -#define M2M_APP_8M_MEM_FLASH_OFFSET (M2M_OTA_IMAGE2_OFFSET + OTA_IMAGE_SIZE) -#define M2M_APP_8M_MEM_FLASH_SZ (FLASH_SECTOR_SZ * 32) -#define M2M_APP_OTA_MEM_FLASH_OFFSET (M2M_APP_8M_MEM_FLASH_OFFSET + M2M_APP_8M_MEM_FLASH_SZ) - -/* Check if total size of content - * don't exceed total size of memory allowed - **/ -#if (M2M_COMMON_DATA_SEC + (OTA_IMAGE_SIZE *2)> FLASH_4M_TOTAL_SZ) -#error "Excced 4M Flash Size" -#endif /* (FLASH_CONTENT_SZ > FLASH_TOTAL_SZ) */ - - -#endif /* __SPI_FLASH_MAP_H__ */ diff --git a/feather_sensor_lte/libraries/WiFi101/src/spi_flash/source/spi_flash.c b/feather_sensor_lte/libraries/WiFi101/src/spi_flash/source/spi_flash.c deleted file mode 100644 index 12eff59..0000000 --- a/feather_sensor_lte/libraries/WiFi101/src/spi_flash/source/spi_flash.c +++ /dev/null @@ -1,770 +0,0 @@ -/** - * - * \file - * - * \brief WINC1500 SPI Flash. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifdef PROFILING -#include "windows.h" -#endif -#include "spi_flash/include/spi_flash.h" -#define DUMMY_REGISTER (0x1084) - -#ifdef ARDUINO -#define u32(x) ((uint32)x) -#endif - -#define TIMEOUT (-1) /*MS*/ - -//#define DISABLE_UNSED_FLASH_FUNCTIONS - -#define FLASH_BLOCK_SIZE (32UL * 1024) -/*!> 16); - cmd[2] = (uint8)(u32FlashAdr >> 8); - cmd[3] = (uint8)(u32FlashAdr); - cmd[4] = 0xA5; - - ret += nm_write_reg(SPI_FLASH_DATA_CNT, u32Sz); -#ifdef ARDUINO - ret += nm_write_reg(SPI_FLASH_BUF1, u32(cmd[0])|u32(cmd[1]<<8)|u32(cmd[2]<<16)|u32(cmd[3]<<24)); -#else - ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]|(cmd[1]<<8)|(cmd[2]<<16)|(cmd[3]<<24)); -#endif - ret += nm_write_reg(SPI_FLASH_BUF2, cmd[4]); - ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x1f); - ret += nm_write_reg(SPI_FLASH_DMA_ADDR, u32MemAdr); - ret += nm_write_reg(SPI_FLASH_CMD_CNT, 5 | (1<<7)); - do - { - ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); - if(M2M_SUCCESS != ret) break; - } - while(val != 1); - - return ret; -} - -/** -* @fn spi_flash_sector_erase -* @brief Erase sector (4KB) -* @param[IN] u32FlashAdr -* Any memory address within the sector -* @return Status of execution -* @note Compatible with MX25L6465E and should be working with other types -* @author M. Abdelmawla -* @version 1.0 -*/ -static sint8 spi_flash_sector_erase(uint32 u32FlashAdr) -{ - uint8 cmd[4]; - uint32 val = 0; - sint8 ret = M2M_SUCCESS; - - cmd[0] = 0x20; - cmd[1] = (uint8)(u32FlashAdr >> 16); - cmd[2] = (uint8)(u32FlashAdr >> 8); - cmd[3] = (uint8)(u32FlashAdr); - - ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); -#ifdef ARDUINO - ret += nm_write_reg(SPI_FLASH_BUF1, u32(cmd[0])|u32(cmd[1]<<8)|u32(cmd[2]<<16)|u32(cmd[3]<<24)); -#else - ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]|(cmd[1]<<8)|(cmd[2]<<16)|(cmd[3]<<24)); -#endif - ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x0f); - ret += nm_write_reg(SPI_FLASH_DMA_ADDR, 0); - ret += nm_write_reg(SPI_FLASH_CMD_CNT, 4 | (1<<7)); - do - { - ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); - if(M2M_SUCCESS != ret) break; - } - while(val != 1); - - return ret; -} - -/** -* @fn spi_flash_write_enable -* @brief Send write enable command to SPI flash -* @return Status of execution -* @note Compatible with MX25L6465E and should be working with other types -* @author M. Abdelmawla -* @version 1.0 -*/ -static sint8 spi_flash_write_enable(void) -{ - uint8 cmd[1]; - uint32 val = 0; - sint8 ret = M2M_SUCCESS; - - cmd[0] = 0x06; - - ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); - ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]); - ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x01); - ret += nm_write_reg(SPI_FLASH_DMA_ADDR, 0); - ret += nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1<<7)); - do - { - ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); - if(M2M_SUCCESS != ret) break; - } - while(val != 1); - - return ret; -} - -/** -* @fn spi_flash_write_disable -* @brief Send write disable command to SPI flash -* @note Compatible with MX25L6465E and should be working with other types -* @author M. Abdelmawla -* @version 1.0 -*/ -static sint8 spi_flash_write_disable(void) -{ - uint8 cmd[1]; - uint32 val = 0; - sint8 ret = M2M_SUCCESS; - cmd[0] = 0x04; - - ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); - ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]); - ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x01); - ret += nm_write_reg(SPI_FLASH_DMA_ADDR, 0); - ret += nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1<<7)); - do - { - ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); - if(M2M_SUCCESS != ret) break; - } - while(val != 1); - - return ret; -} - -/** -* @fn spi_flash_page_program -* @brief Write data (less than page size) from cortus memory to SPI flash -* @param[IN] u32MemAdr -* Cortus data address. It must be set to its AHB access address -* @param[IN] u32FlashAdr -* Address to write to at the SPI flash -* @param[IN] u32Sz -* Data size -* @note Compatible with MX25L6465E and should be working with other types -* @author M. Abdelmawla -* @version 1.0 -*/ -static sint8 spi_flash_page_program(uint32 u32MemAdr, uint32 u32FlashAdr, uint32 u32Sz) -{ - uint8 cmd[4]; - uint32 val = 0; - sint8 ret = M2M_SUCCESS; - - cmd[0] = 0x02; - cmd[1] = (uint8)(u32FlashAdr >> 16); - cmd[2] = (uint8)(u32FlashAdr >> 8); - cmd[3] = (uint8)(u32FlashAdr); - - ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); -#ifdef ARDUINO - ret += nm_write_reg(SPI_FLASH_BUF1, u32(cmd[0])|u32(cmd[1]<<8)|u32(cmd[2]<<16)|u32(cmd[3]<<24)); -#else - ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]|(cmd[1]<<8)|(cmd[2]<<16)|(cmd[3]<<24)); -#endif - ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x0f); - ret += nm_write_reg(SPI_FLASH_DMA_ADDR, u32MemAdr); - ret += nm_write_reg(SPI_FLASH_CMD_CNT, 4 | (1<<7) | ((u32Sz & 0xfffff) << 8)); - do - { - ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); - if(M2M_SUCCESS != ret) break; - } - while(val != 1); - - return ret; -} - -/** -* @fn spi_flash_read_internal -* @brief Read from data from SPI flash -* @param[OUT] pu8Buf -* Pointer to data buffer -* @param[IN] u32Addr -* Address to read from at the SPI flash -* @param[IN] u32Sz -* Data size -* @note Data size must be < 64KB (limitation imposed by the bus wrapper) -* @author M. Abdelmawla -* @version 1.0 -*/ -static sint8 spi_flash_read_internal(uint8 *pu8Buf, uint32 u32Addr, uint32 u32Sz) -{ - sint8 ret = M2M_SUCCESS; - /* read size must be < 64KB */ - ret = spi_flash_load_to_cortus_mem(HOST_SHARE_MEM_BASE, u32Addr, u32Sz); - if(M2M_SUCCESS != ret) goto ERR; - ret = nm_read_block(HOST_SHARE_MEM_BASE, pu8Buf, u32Sz); -ERR: - return ret; -} - -/** -* @fn spi_flash_pp -* @brief Program data of size less than a page (256 bytes) at the SPI flash -* @param[IN] u32Offset -* Address to write to at the SPI flash -* @param[IN] pu8Buf -* Pointer to data buffer -* @param[IN] u32Sz -* Data size -* @return Status of execution -* @author M. Abdelmawla -* @version 1.0 -*/ -static sint8 spi_flash_pp(uint32 u32Offset, uint8 *pu8Buf, uint16 u16Sz) -{ - sint8 ret = M2M_SUCCESS; - uint8 tmp; - spi_flash_write_enable(); - /* use shared packet memory as temp mem */ - ret += nm_write_block(HOST_SHARE_MEM_BASE, pu8Buf, u16Sz); - ret += spi_flash_page_program(HOST_SHARE_MEM_BASE, u32Offset, u16Sz); - ret += spi_flash_read_status_reg(&tmp); - do - { - if(ret != M2M_SUCCESS) goto ERR; - ret += spi_flash_read_status_reg(&tmp); - }while(tmp & 0x01); - ret += spi_flash_write_disable(); -ERR: - return ret; -} - -/** -* @fn spi_flash_rdid -* @brief Read SPI Flash ID -* @return SPI FLash ID -* @author M.S.M -* @version 1.0 -*/ -static uint32 spi_flash_rdid(void) -{ - unsigned char cmd[1]; - uint32 reg = 0; - uint32 cnt = 0; - sint8 ret = M2M_SUCCESS; - - cmd[0] = 0x9f; - - ret += nm_write_reg(SPI_FLASH_DATA_CNT, 4); - ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]); - ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x1); - ret += nm_write_reg(SPI_FLASH_DMA_ADDR, DUMMY_REGISTER); - ret += nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1<<7)); - do - { - ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)®); - if(M2M_SUCCESS != ret) break; - if(++cnt > 500) - { - ret = M2M_ERR_INIT; - break; - } - } - while(reg != 1); - reg = (M2M_SUCCESS == ret)?(nm_read_reg(DUMMY_REGISTER)):(0); - M2M_PRINT("Flash ID %x \n",(unsigned int)reg); - return reg; -} - -/** -* @fn spi_flash_unlock -* @brief Unlock SPI Flash -* @author M.S.M -* @version 1.0 -*/ -#if 0 -static void spi_flash_unlock(void) -{ - uint8 tmp; - tmp = spi_flash_read_security_reg(); - spi_flash_clear_security_flags(); - if(tmp & 0x80) - { - spi_flash_write_enable(); - spi_flash_gang_unblock(); - } -} -#endif -static void spi_flash_enter_low_power_mode(void) { - volatile unsigned long tmp; - unsigned char* cmd = (unsigned char*) &tmp; - - cmd[0] = 0xb9; - - nm_write_reg(SPI_FLASH_DATA_CNT, 0); - nm_write_reg(SPI_FLASH_BUF1, cmd[0]); - nm_write_reg(SPI_FLASH_BUF_DIR, 0x1); - nm_write_reg(SPI_FLASH_DMA_ADDR, 0); - nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1 << 7)); - while(nm_read_reg(SPI_FLASH_TR_DONE) != 1); -} - - -static void spi_flash_leave_low_power_mode(void) { - volatile unsigned long tmp; - unsigned char* cmd = (unsigned char*) &tmp; - - cmd[0] = 0xab; - - nm_write_reg(SPI_FLASH_DATA_CNT, 0); - nm_write_reg(SPI_FLASH_BUF1, cmd[0]); - nm_write_reg(SPI_FLASH_BUF_DIR, 0x1); - nm_write_reg(SPI_FLASH_DMA_ADDR, 0); - nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1 << 7)); - while(nm_read_reg(SPI_FLASH_TR_DONE) != 1); -} -/*********************************************/ -/* GLOBAL FUNCTIONS */ -/*********************************************/ -/** - * @fn spi_flash_enable - * @brief Enable spi flash operations - * @author M. Abdelmawla - * @version 1.0 - */ -sint8 spi_flash_enable(uint8 enable) -{ - sint8 s8Ret = M2M_SUCCESS; - if(REV(nmi_get_chipid()) >= REV_3A0) { - uint32 u32Val; - - /* Enable pinmux to SPI flash. */ - s8Ret = nm_read_reg_with_ret(0x1410, &u32Val); - if(s8Ret != M2M_SUCCESS) { - goto ERR1; - } - /* GPIO15/16/17/18 */ - u32Val &= ~((0x7777ul) << 12); - u32Val |= ((0x1111ul) << 12); - nm_write_reg(0x1410, u32Val); - if(enable) { - spi_flash_leave_low_power_mode(); - } else { - spi_flash_enter_low_power_mode(); - } - /* Disable pinmux to SPI flash to minimize leakage. */ - u32Val &= ~((0x7777ul) << 12); - u32Val |= ((0x0010ul) << 12); - nm_write_reg(0x1410, u32Val); - } -ERR1: - return s8Ret; -} -/** -* @fn spi_flash_read -* @brief Read from data from SPI flash -* @param[OUT] pu8Buf -* Pointer to data buffer -* @param[IN] u32offset -* Address to read from at the SPI flash -* @param[IN] u32Sz -* Data size -* @return Status of execution -* @note Data size is limited by the SPI flash size only -* @author M. Abdelmawla -* @version 1.0 -*/ -sint8 spi_flash_read(uint8 *pu8Buf, uint32 u32offset, uint32 u32Sz) -{ - sint8 ret = M2M_SUCCESS; - if(u32Sz > FLASH_BLOCK_SIZE) - { - do - { - ret = spi_flash_read_internal(pu8Buf, u32offset, FLASH_BLOCK_SIZE); - if(M2M_SUCCESS != ret) goto ERR; - u32Sz -= FLASH_BLOCK_SIZE; - u32offset += FLASH_BLOCK_SIZE; - pu8Buf += FLASH_BLOCK_SIZE; - } while(u32Sz > FLASH_BLOCK_SIZE); - } - - ret = spi_flash_read_internal(pu8Buf, u32offset, u32Sz); - -ERR: - return ret; -} - -/** -* @fn spi_flash_write -* @brief Proram SPI flash -* @param[IN] pu8Buf -* Pointer to data buffer -* @param[IN] u32Offset -* Address to write to at the SPI flash -* @param[IN] u32Sz -* Data size -* @return Status of execution -* @author M. Abdelmawla -* @version 1.0 -*/ -sint8 spi_flash_write(uint8* pu8Buf, uint32 u32Offset, uint32 u32Sz) -{ -#ifdef PROFILING - uint32 t1 = 0; - uint32 percent =0; - uint32 tpercent =0; -#endif - sint8 ret = M2M_SUCCESS; - uint32 u32wsz; - uint32 u32off; - uint32 u32Blksz; - u32Blksz = FLASH_PAGE_SZ; - u32off = u32Offset % u32Blksz; -#ifdef PROFILING - tpercent = (u32Sz/u32Blksz)+((u32Sz%u32Blksz)>0); - t1 = GetTickCount(); - M2M_PRINT(">Start programming...\r\n"); -#endif - if(u32Sz<=0) - { - M2M_ERR("Data size = %d",(int)u32Sz); - ret = M2M_ERR_FAIL; - goto ERR; - } - - if (u32off)/*first part of data in the address page*/ - { - u32wsz = u32Blksz - u32off; - if(spi_flash_pp(u32Offset, pu8Buf, (uint16)BSP_MIN(u32Sz, u32wsz))!=M2M_SUCCESS) - { - ret = M2M_ERR_FAIL; - goto ERR; - } - if (u32Sz < u32wsz) goto EXIT; - pu8Buf += u32wsz; - u32Offset += u32wsz; - u32Sz -= u32wsz; - } - while (u32Sz > 0) - { - u32wsz = BSP_MIN(u32Sz, u32Blksz); - - /*write complete page or the remaining data*/ - if(spi_flash_pp(u32Offset, pu8Buf, (uint16)u32wsz)!=M2M_SUCCESS) - { - ret = M2M_ERR_FAIL; - goto ERR; - } - pu8Buf += u32wsz; - u32Offset += u32wsz; - u32Sz -= u32wsz; -#ifdef PROFILING - percent++; - printf("\r>Complete Percentage = %d%%.\r",((percent*100)/tpercent)); -#endif - } -EXIT: -#ifdef PROFILING - M2M_PRINT("\rDone\t\t\t\t\t\t"); - M2M_PRINT("\n#Programming time = %f sec\n\r",(GetTickCount() - t1)/1000.0); -#endif -ERR: - return ret; -} - -/** -* @fn spi_flash_erase -* @brief Erase from data from SPI flash -* @param[IN] u32Offset -* Address to write to at the SPI flash -* @param[IN] u32Sz -* Data size -* @return Status of execution -* @note Data size is limited by the SPI flash size only -* @author M. Abdelmawla -* @version 1.0 -*/ -sint8 spi_flash_erase(uint32 u32Offset, uint32 u32Sz) -{ - uint32 i = 0; - sint8 ret = M2M_SUCCESS; - uint8 tmp = 0; -#ifdef PROFILING - uint32 t; - t = GetTickCount(); -#endif - M2M_PRINT("\r\n>Start erasing...\r\n"); - for(i = u32Offset; i < (u32Sz +u32Offset); i += (16*FLASH_PAGE_SZ)) - { - ret += spi_flash_write_enable(); - ret += spi_flash_read_status_reg(&tmp); - ret += spi_flash_sector_erase(i + 10); - ret += spi_flash_read_status_reg(&tmp); - do - { - if(ret != M2M_SUCCESS) goto ERR; - ret += spi_flash_read_status_reg(&tmp); - }while(tmp & 0x01); - - } - M2M_PRINT("Done\r\n"); -#ifdef PROFILING - M2M_PRINT("#Erase time = %f sec\n", (GetTickCount()-t)/1000.0); -#endif -ERR: - return ret; -} - -/** -* @fn spi_flash_get_size -* @brief Get size of SPI Flash -* @return Size of Flash -* @author M.S.M -* @version 1.0 -*/ -uint32 spi_flash_get_size(void) -{ - uint32 u32FlashId = 0, u32FlashPwr = 0; - static uint32 gu32InernalFlashSize= 0; - - if(!gu32InernalFlashSize) - { - u32FlashId = spi_flash_rdid();//spi_flash_probe(); - if(u32FlashId != 0xffffffff) - { - /*flash size is the third byte from the FLASH RDID*/ - u32FlashPwr = ((u32FlashId>>16)&0xff) - 0x11; /*2MBIT is the min*/ - /*That number power 2 to get the flash size*/ - gu32InernalFlashSize = 1< - -// First, we're going to make some variables. -// This is our "shorthand" that we'll use throughout the program: - -int led1 = D0; // Instead of writing D0 over and over again, we'll write led1 -// You'll need to wire an LED to this one to see it blink. -// You'll need to wire an LED to this one to see it blink. - -int led2 = D7; // Instead of writing D7 over and over again, we'll write led2 -// This one is the little blue LED on your board. On the Photon it is next to D7, and on the Core it is next to the USB jack. - -// Having declared these variables, let's move on to the setup function. -// The setup function is a standard part of any microcontroller program. -// It runs only once when the device boots up or is reset. - -void setup() { - - // We are going to tell our device that D0 and D7 (which we named led1 and led2 respectively) are going to be output - // (That means that we will be sending voltage to them, rather than monitoring voltage that comes from them) - - // It's important you do this here, inside the setup() function rather than outside it or in the loop function. - - pinMode(led1, OUTPUT); - pinMode(led2, OUTPUT); - -} - -// Next we have the loop function, the other essential part of a microcontroller program. -// This routine gets repeated over and over, as quickly as possible and as many times as possible, after the setup function is called. -// Note: Code that blocks for too long (like more than 5 seconds), can make weird things happen (like dropping the network connection). The built-in delay function shown below safely interleaves required background activity, so arbitrarily long delays can safely be done if you need them. - -void loop() { - // To blink the LED, first we'll turn it on... - digitalWrite(led1, HIGH); - digitalWrite(led2, HIGH); - - // We'll leave it on for 1 second... - delay(1000); - - // Then we'll turn it off... - digitalWrite(led1, LOW); - digitalWrite(led2, LOW); - - // Wait 1 second... - delay(1000); - - // And repeat! -} - diff --git a/feather_sensor_transmit/.vscode/c_cpp_properties.json b/feather_sensor_transmit/.vscode/c_cpp_properties.json deleted file mode 100644 index c16b552..0000000 --- a/feather_sensor_transmit/.vscode/c_cpp_properties.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "configurations": [ - { - "name": "Win32", - "includePath": [ - "${workspaceFolder}/**" - ], - "defines": [ - "_DEBUG", - "UNICODE", - "_UNICODE" - ], - "intelliSenseMode": "msvc-x64", - "configurationProvider": "particle.particle-vscode-core" - } - ], - "version": 4 -} \ No newline at end of file diff --git a/feather_sensor_transmit/.vscode/launch.json b/feather_sensor_transmit/.vscode/launch.json deleted file mode 100644 index 4532e35..0000000 --- a/feather_sensor_transmit/.vscode/launch.json +++ /dev/null @@ -1,92 +0,0 @@ -{ - "version": "0.1.0", - "configurations": [ - { - "type": "cortex-debug", - "request": "attach", - "name": "Particle Debugger (photon, p1, electron)", - "servertype": "openocd", - "interface": "swd", - "device": "STM32F205RG", - "cwd": "${workspaceRoot}", - "executable": "${command:particle.getDebuggerExecutable}", - "preLaunchTask": "Particle: Flash application for debug (local)", - "armToolchainPath": "${command:particle.getDebuggerCompilerDir}", - "svdFile": "${command:particle.getDebuggerSVDFile}", - "searchDir": [ - "${command:particle.getDebuggerSearchDir}" - ], - "configFiles": [ - "interface/cmsis-dap.cfg", - "target/stm32f2x.cfg" - ], - "postAttachCommands": [ - "monitor reset halt" - ], - "windows": { - "configFiles": [ - "interface\\cmsis-dap.cfg", - "target\\stm32f2x.cfg" - ] - } - }, - { - "type": "cortex-debug", - "request": "attach", - "name": "Particle Debugger (argon, boron / bsom, xenon)", - "servertype": "openocd", - "interface": "swd", - "device": "nRF52840_xxAA", - "cwd": "${workspaceRoot}", - "executable": "${command:particle.getDebuggerExecutable}", - "preLaunchTask": "Particle: Flash application for debug (local)", - "armToolchainPath": "${command:particle.getDebuggerCompilerDir}", - "svdFile": "${command:particle.getDebuggerSVDFile}", - "searchDir": [ - "${command:particle.getDebuggerSearchDir}" - ], - "configFiles": [ - "interface/cmsis-dap.cfg", - "target/nrf52-particle.cfg" - ], - "postAttachCommands": [ - "monitor reset halt" - ], - "windows": { - "configFiles": [ - "interface\\cmsis-dap.cfg", - "target\\nrf52-particle.cfg" - ] - } - }, - { - "type": "cortex-debug", - "request": "attach", - "name": "Particle Programmer Shield v1.0 (photon, p1, electron)", - "servertype": "openocd", - "interface": "swd", - "device": "STM32F205RG", - "cwd": "${workspaceRoot}", - "executable": "${command:particle.getDebuggerExecutable}", - "preLaunchTask": "Particle: Flash application for debug (local)", - "armToolchainPath": "${command:particle.getDebuggerCompilerDir}", - "svdFile": "${command:particle.getDebuggerSVDFile}", - "searchDir": [ - "${command:particle.getDebuggerSearchDir}" - ], - "configFiles": [ - "interface/particle-ftdi.cfg", - "target/stm32f2x.cfg" - ], - "postAttachCommands": [ - "monitor reset halt" - ], - "windows": { - "configFiles": [ - "interface\\particle-ftdi.cfg", - "target\\stm32f2x.cfg" - ] - } - } - ] -} \ No newline at end of file diff --git a/feather_sensor_transmit/.vscode/settings.json b/feather_sensor_transmit/.vscode/settings.json deleted file mode 100644 index 5d5f015..0000000 --- a/feather_sensor_transmit/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "extensions.ignoreRecommendations": true, - "cortex-debug.openocdPath": "${command:particle.getDebuggerOpenocdPath}", - "files.associations": { - "*.ino": "cpp" - }, - "particle.targetDevice": "e00fce684c6a4946ca9fecd1", - "particle.firmwareVersion": "1.1.0", - "particle.targetPlatform": "boron", - "git.ignoreLimitWarning": true -} \ No newline at end of file diff --git a/feather_sensor_transmit/boron_firmware_1574447345899.bin b/feather_sensor_transmit/boron_firmware_1574447345899.bin deleted file mode 100644 index 544964835a60d84338704d5bd1234e633fc8cef4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5592 zcmd5=e{d9c6@PoXm%IEpxKOBP0?ghmXAchWXj;9NIunv~6LJX@soEAh-ZeSgND{6g zv1!FINUL;er>&(UE!JrT9O{V8)t*Cu?Ku{m))u|AD0ILPwKcS~y1|xP@@xHkckdS& z$G;rMo%!7Nz3;yFzVF9(-}jqPy^BtM&P7CJ!Uh zK!cF^yzUR}Y38oi#}d%H4mwk}Vr^~yVJGAzT|MutCvA&L+6N<~T^OOk;fW!wzC6*) zNqi#FOyo?JML4f#7ioW(5lqU``Q1yD9>m(rmvCxM`<%AGF3wBZ$r;WoLOL_E{=@qc zq&+_!*hQFsWd^etkDK%A`7qXf7Cz-|kfy^YTclR0Rk+8UYMYJ6+9uz1CBJDFzjqdY zW)@%jl`HivK2Wf~$$Ver_s-(a%;IaeFndM$O|$sg?knG0@!V8c?~EB=k*_uVE%H`; zMc#_9$XoFhc`KeGZ~0&3Eqk4X_4k_Vw-oqVbNwQ3$rpJm-Xg!rjIV?@?Rg6JEd3&X z#QL z%y|`9Tw~b0L$Xh1^lF2CutWCBwDP(PExmShn_>&vG8Mt{%(8Qb$7$|0nY+8fvapJ@ zHz&k%BbZs7>F=ucaR*7OnkkbW*5`+~L&CU|_gv>uZdaDc{4bq#`x+L=*-`GfvV)F8 zqB#rFv3{i1ne9aJLH}+LHRT<%263uJ+adyJ?r&RV^ zY5sc5Uzhn?le67u+D@cy-Y&>aDr4KVdU}gLmt7BFBQl(nsgz8aNHTRT~bheg9%3HkP z{$N(Ja>~)_SZi+~%{|Gtgw^-o!F>WyfLj4plXsendwl@evpU721!^xSwo@O$nBVpH zs>NN8`$eI9+*#172W9Q`M)N(huu_H3Z2|u>nY;xY#Z4>O>$z`tj}MLTD9Lc$*Rj}k~&!4x9yACvCBEhDSP`n`m14OzbUhD zql?_B`94U(uTgU@gnQAqhq;6Jf()w;ZnF+;lhGviW3TLJF|wm(6f1Zho_A8@OmPPqmj8f+bWb&wugiX6UY@QB%++KH}p6*?Se z_BYmxoT;iv9eU912Cvk1?P;b!`B`VA12d1#v5(~Q^Uyq zY?6z3qE2-=?#Yf6N%VM)yj8o0GqTYse)vvZm?Uzf8h2F$otayL<)h^|WmhN7Hy1q3 zM)n<}>|CkV%{i^}sE-?Kd~Fg{*Un8iB3C6vnfZVYf!d}g$;-E>=iT^EN@H0ZwKgVdfGcDlU(A5M^lPdI*wMo)`IuXRa@X7(~ z4c2XNcBs6v7iUN)_0Vu7_VUB}5;wPOPrAbA8kdBhOsculLH$*Y!yG!fQVn?~DgkD+D@)oEnP*$IrYf3U(6Gw2K z<1DvwS%r1GkxQI=xqdm<{7wfi-?=KsZJvGI65odM+fB$^pFr`B|eLwW;L9@Lv7klT) zsX%i7cqMNOa;Hgjt44MhJNdU$&Lp?|(pyHhdK%}-v}zTQO6h4oUbN&HRv~T^nB2n96hf@#$6&ar$nZzM5dxdhVA)oi5*{w9kImD;u4vKB{DT7GAx$7&n%XFTr8G+Tr8Hn42vZ%!(z$H zFrU8gmd?fwiT|wHng?x)*cf`VK0zHA3uhO|7 zEt?$m)NtWM^CJB3=XT%$;6b4Dd7#Nfj{r{s`+!5h2=FUl6nG2xEARo3e}cFxdx4Ju zE`S3*y4gkV0)GZh0VjY`9oA>AVfVS*!}``C-~k{GJPbSmJPjNG^3OY<%UfKu0QdsV zrg8AoKo;OJH-_;7kbgdgJBth8ff2mV0vCWk0jGcyz{^0XZ|t7)9Iz8$YkVE!mw~Oo zKHwf82IQaSRu|m>tOo8Ne=tfOAR z?uqsFQoOHkYabTw?dqUdcXvKH7{Af(q5)tF5Cc93tOY&;Tn_{RFHl;867~No*$8VN zUxU4X{rDF4sTXyuMvYehYk+e2@gVR=;MH|5YG04{x47u{KIr~kO#?Ku+fSs8q`McqAq MGC(&!fBm2T1#!eoE&u=k diff --git a/feather_sensor_transmit/boron_firmware_1574729317031.bin b/feather_sensor_transmit/boron_firmware_1574729317031.bin deleted file mode 100644 index 544964835a60d84338704d5bd1234e633fc8cef4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5592 zcmd5=e{d9c6@PoXm%IEpxKOBP0?ghmXAchWXj;9NIunv~6LJX@soEAh-ZeSgND{6g zv1!FINUL;er>&(UE!JrT9O{V8)t*Cu?Ku{m))u|AD0ILPwKcS~y1|xP@@xHkckdS& z$G;rMo%!7Nz3;yFzVF9(-}jqPy^BtM&P7CJ!Uh zK!cF^yzUR}Y38oi#}d%H4mwk}Vr^~yVJGAzT|MutCvA&L+6N<~T^OOk;fW!wzC6*) zNqi#FOyo?JML4f#7ioW(5lqU``Q1yD9>m(rmvCxM`<%AGF3wBZ$r;WoLOL_E{=@qc zq&+_!*hQFsWd^etkDK%A`7qXf7Cz-|kfy^YTclR0Rk+8UYMYJ6+9uz1CBJDFzjqdY zW)@%jl`HivK2Wf~$$Ver_s-(a%;IaeFndM$O|$sg?knG0@!V8c?~EB=k*_uVE%H`; zMc#_9$XoFhc`KeGZ~0&3Eqk4X_4k_Vw-oqVbNwQ3$rpJm-Xg!rjIV?@?Rg6JEd3&X z#QL z%y|`9Tw~b0L$Xh1^lF2CutWCBwDP(PExmShn_>&vG8Mt{%(8Qb$7$|0nY+8fvapJ@ zHz&k%BbZs7>F=ucaR*7OnkkbW*5`+~L&CU|_gv>uZdaDc{4bq#`x+L=*-`GfvV)F8 zqB#rFv3{i1ne9aJLH}+LHRT<%263uJ+adyJ?r&RV^ zY5sc5Uzhn?le67u+D@cy-Y&>aDr4KVdU}gLmt7BFBQl(nsgz8aNHTRT~bheg9%3HkP z{$N(Ja>~)_SZi+~%{|Gtgw^-o!F>WyfLj4plXsendwl@evpU721!^xSwo@O$nBVpH zs>NN8`$eI9+*#172W9Q`M)N(huu_H3Z2|u>nY;xY#Z4>O>$z`tj}MLTD9Lc$*Rj}k~&!4x9yACvCBEhDSP`n`m14OzbUhD zql?_B`94U(uTgU@gnQAqhq;6Jf()w;ZnF+;lhGviW3TLJF|wm(6f1Zho_A8@OmPPqmj8f+bWb&wugiX6UY@QB%++KH}p6*?Se z_BYmxoT;iv9eU912Cvk1?P;b!`B`VA12d1#v5(~Q^Uyq zY?6z3qE2-=?#Yf6N%VM)yj8o0GqTYse)vvZm?Uzf8h2F$otayL<)h^|WmhN7Hy1q3 zM)n<}>|CkV%{i^}sE-?Kd~Fg{*Un8iB3C6vnfZVYf!d}g$;-E>=iT^EN@H0ZwKgVdfGcDlU(A5M^lPdI*wMo)`IuXRa@X7(~ z4c2XNcBs6v7iUN)_0Vu7_VUB}5;wPOPrAbA8kdBhOsculLH$*Y!yG!fQVn?~DgkD+D@)oEnP*$IrYf3U(6Gw2K z<1DvwS%r1GkxQI=xqdm<{7wfi-?=KsZJvGI65odM+fB$^pFr`B|eLwW;L9@Lv7klT) zsX%i7cqMNOa;Hgjt44MhJNdU$&Lp?|(pyHhdK%}-v}zTQO6h4oUbN&HRv~T^nB2n96hf@#$6&ar$nZzM5dxdhVA)oi5*{w9kImD;u4vKB{DT7GAx$7&n%XFTr8G+Tr8Hn42vZ%!(z$H zFrU8gmd?fwiT|wHng?x)*cf`VK0zHA3uhO|7 zEt?$m)NtWM^CJB3=XT%$;6b4Dd7#Nfj{r{s`+!5h2=FUl6nG2xEARo3e}cFxdx4Ju zE`S3*y4gkV0)GZh0VjY`9oA>AVfVS*!}``C-~k{GJPbSmJPjNG^3OY<%UfKu0QdsV zrg8AoKo;OJH-_;7kbgdgJBth8ff2mV0vCWk0jGcyz{^0XZ|t7)9Iz8$YkVE!mw~Oo zKHwf82IQaSRu|m>tOo8Ne=tfOAR z?uqsFQoOHkYabTw?dqUdcXvKH7{Af(q5)tF5Cc93tOY&;Tn_{RFHl;867~No*$8VN zUxU4X{rDF4sTXyuMvYehYk+e2@gVR=;MH|5YG04{x47u{KIr~kO#?Ku+fSs8q`McqAq MGC(&!fBm2T1#!eoE&u=k diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/Adafruit_ASFcore.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/Adafruit_ASFcore.h deleted file mode 100644 index e69de29..0000000 diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/README.md b/feather_sensor_transmit/libraries/Adafruit_ASFcore/README.md deleted file mode 100644 index 8de73c7..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# ASF (Atmel Software Framework) for Arduino Zero / Adafruit Feather M0 (SAMD21) - -Copy of ASF (Atmel Software Framework) excerpts for the SAMD21 processor used in the Arduino Zero / Adafruit Feather M0 boards. -You typically won't use this library directly, instead other libraries will depend on this library and use the code -within it to simplify their implementation. - -All code is taken directly from Atmel's ASF: http://www.atmel.com/tools/avrsoftwareframework.aspx?tab=overview - -The code is copyright Atmel and released by them under the following license: - - 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. The name of Atmel may not be used to endorse or promote products derived from this software without specific - prior written permission. - - 4. This software may only be redistributed and used in connection with an Atmel microcontroller product. - - THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A - PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN - NO EVENT SHALL ATMEL 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. diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/clock.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/clock.h deleted file mode 100644 index 549e3e9..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/clock.h +++ /dev/null @@ -1,53 +0,0 @@ -/** - * \file - * - * \brief SAM Clock Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef SYSTEM_CLOCK_H_INCLUDED -#define SYSTEM_CLOCK_H_INCLUDED - -#include "compiler.h" -#include "gclk.h" -#include "clock_feature.h" - -#endif /* SYSTEM_CLOCK_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/clock_feature.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/clock_feature.h deleted file mode 100644 index be63c7c..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/clock_feature.h +++ /dev/null @@ -1,1492 +0,0 @@ -/** - * \file - * - * \brief SAM Clock Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef SYSTEM_CLOCK_FEATURE_H_INCLUDED -#define SYSTEM_CLOCK_FEATURE_H_INCLUDED - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \defgroup asfdoc_sam0_system_clock_group SAM System Clock Management Driver (SYSTEM CLOCK) - * - * This driver for Atmel® | SMART ARM®-based microcontrollers provides an interface for the configuration - * and management of the device's clocking related functions. This includes - * the various clock sources, bus clocks, and generic clocks within the device, - * with functions to manage the enabling, disabling, source selection, and - * prescaling of clocks to various internal peripherals. - * - * The following peripherals are used by this module: - * - * - GCLK (Generic Clock Management) - * - PM (Power Management) - * - SYSCTRL (Clock Source Control) - * - * The following devices can use this module: - * - Atmel | SMART SAM D20/D21 - * - Atmel | SMART SAM R21 - * - Atmel | SMART SAM D10/D11 - * - Atmel | SMART SAM DA0/DA1 - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_system_clock_prerequisites - * - \ref asfdoc_sam0_system_clock_module_overview - * - \ref asfdoc_sam0_system_clock_special_considerations - * - \ref asfdoc_sam0_system_clock_extra_info - * - \ref asfdoc_sam0_system_clock_examples - * - \ref asfdoc_sam0_system_clock_api_overview - * - * - * \section asfdoc_sam0_system_clock_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * - * \section asfdoc_sam0_system_clock_module_overview Module Overview - * The SAM devices contain a sophisticated clocking system, which is designed - * to give the maximum flexibility to the user application. This system allows - * a system designer to tune the performance and power consumption of the device - * in a dynamic manner, to achieve the best trade-off between the two for a - * particular application. - * - * This driver provides a set of functions for the configuration and management - * of the various clock related functionality within the device. - * - * \subsection asfdoc_sam0_system_clock_module_features Driver Feature Macro Definition - * - * - * - * - * - * - * - * - * - *
Driver Feature MacroSupported devices
FEATURE_SYSTEM_CLOCK_DPLLSAMD21, SAMR21, SAMD10, SAMD11, SAMDAx
- * \note The specific features are only available in the driver when the - * selected device supports those features. - * - * \subsection asfdoc_sam0_system_clock_module_overview_clock_sources Clock Sources - * The SAM devices have a number of master clock source modules, each of - * which being capable of producing a stabilized output frequency, which can then - * be fed into the various peripherals and modules within the device. - * - * Possible clock source modules include internal R/C oscillators, internal - * DFLL modules, as well as external crystal oscillators and/or clock inputs. - * - * \subsection asfdoc_sam0_system_clock_module_overview_cpu_clock CPU / Bus Clocks - * The CPU and AHB/APBx buses are clocked by the same physical clock source - * (referred in this module as the Main Clock), however the APBx buses may - * have additional prescaler division ratios set to give each peripheral bus a - * different clock speed. - * - * The general main clock tree for the CPU and associated buses is shown in - * \ref asfdoc_sam0_system_clock_module_clock_tree "the figure below". - * - * \anchor asfdoc_sam0_system_clock_module_clock_tree - * \dot - * digraph overview { - * rankdir=LR; - * clk_src [label="Clock Sources", shape=none, height=0]; - * node [label="CPU Bus" shape=ellipse] cpu_bus; - * node [label="AHB Bus" shape=ellipse] ahb_bus; - * node [label="APBA Bus" shape=ellipse] apb_a_bus; - * node [label="APBB Bus" shape=ellipse] apb_b_bus; - * node [label="APBC Bus" shape=ellipse] apb_c_bus; - * node [label="Main Bus\nPrescaler" shape=square] main_prescaler; - * node [label="APBA Bus\nPrescaler" shape=square] apb_a_prescaler; - * node [label="APBB Bus\nPrescaler" shape=square] apb_b_prescaler; - * node [label="APBC Bus\nPrescaler" shape=square] apb_c_prescaler; - * node [label="", shape=polygon, sides=4, distortion=0.6, orientation=90, style=filled, fillcolor=black, height=0.9, width=0.2] main_clock_mux; - * - * clk_src -> main_clock_mux; - * main_clock_mux -> main_prescaler; - * main_prescaler -> cpu_bus; - * main_prescaler -> ahb_bus; - * main_prescaler -> apb_a_prescaler; - * main_prescaler -> apb_b_prescaler; - * main_prescaler -> apb_c_prescaler; - * apb_a_prescaler -> apb_a_bus; - * apb_b_prescaler -> apb_b_bus; - * apb_c_prescaler -> apb_c_bus; - * } - * \enddot - * - * \subsection asfdoc_sam0_system_clock_module_overview_clock_masking Clock Masking - * To save power, the input clock to one or more peripherals on the AHB and APBx - * buses can be masked away - when masked, no clock is passed into the module. - * Disabling of clocks of unused modules will prevent all access to the masked - * module, but will reduce the overall device power consumption. - * - * \subsection asfdoc_sam0_system_clock_module_overview_gclk Generic Clocks - * Within the SAM devices there are a number of Generic Clocks; these are used to - * provide clocks to the various peripheral clock domains in the device in a - * standardized manner. One or more master source clocks can be selected as the - * input clock to a Generic Clock Generator, which can prescale down the input - * frequency to a slower rate for use in a peripheral. - * - * Additionally, a number of individually selectable Generic Clock Channels are - * provided, which multiplex and gate the various generator outputs for one or - * more peripherals within the device. This setup allows for a single common - * generator to feed one or more channels, which can then be enabled or disabled - * individually as required. - * - * \anchor asfdoc_sam0_system_clock_module_chain_overview - * \dot - * digraph overview { - * rankdir=LR; - * node [label="Clock\nSource a" shape=square] system_clock_source; - * node [label="Generator 1" shape=square] clock_gen; - * node [label="Channel x" shape=square] clock_chan0; - * node [label="Channel y" shape=square] clock_chan1; - * node [label="Peripheral x" shape=ellipse style=filled fillcolor=lightgray] peripheral0; - * node [label="Peripheral y" shape=ellipse style=filled fillcolor=lightgray] peripheral1; - * - * system_clock_source -> clock_gen; - * clock_gen -> clock_chan0; - * clock_chan0 -> peripheral0; - * clock_gen -> clock_chan1; - * clock_chan1 -> peripheral1; - * } - * \enddot - * - * \subsubsection asfdoc_sam0_system_clock_module_chain_example Clock Chain Example - * An example setup of a complete clock chain within the device is shown in - * \ref asfdoc_sam0_system_clock_module_chain_example_fig "the figure below". - * - * \anchor asfdoc_sam0_system_clock_module_chain_example_fig - * \dot - * digraph overview { - * rankdir=LR; - * node [label="External\nOscillator" shape=square] system_clock_source0; - * node [label="Generator 0" shape=square] clock_gen0; - * node [label="Channel x" shape=square] clock_chan0; - * node [label="Core CPU" shape=ellipse style=filled fillcolor=lightgray] peripheral0; - * - * system_clock_source0 -> clock_gen0; - * clock_gen0 -> clock_chan0; - * clock_chan0 -> peripheral0; - * node [label="8MHz R/C\nOscillator (OSC8M)" shape=square fillcolor=white] system_clock_source1; - * node [label="Generator 1" shape=square] clock_gen1; - * node [label="Channel y" shape=square] clock_chan1; - * node [label="Channel z" shape=square] clock_chan2; - * node [label="SERCOM\nModule" shape=ellipse style=filled fillcolor=lightgray] peripheral1; - * node [label="Timer\nModule" shape=ellipse style=filled fillcolor=lightgray] peripheral2; - * - * system_clock_source1 -> clock_gen1; - * clock_gen1 -> clock_chan1; - * clock_gen1 -> clock_chan2; - * clock_chan1 -> peripheral1; - * clock_chan2 -> peripheral2; - * } - * \enddot - * - * \subsubsection asfdoc_sam0_system_clock_module_overview_gclk_generators Generic Clock Generators - * Each Generic Clock generator within the device can source its input clock - * from one of the provided Source Clocks, and prescale the output for one or - * more Generic Clock Channels in a one-to-many relationship. The generators - * thus allow for several clocks to be generated of different frequencies, - * power usages, and accuracies, which can be turned on and off individually to - * disable the clocks to multiple peripherals as a group. - * - * \subsubsection asfdoc_sam0_system_clock_module_overview_gclk_channels Generic Clock Channels - * To connect a Generic Clock Generator to a peripheral within the - * device, a Generic Clock Channel is used. Each peripheral or - * peripheral group has an associated Generic Clock Channel, which serves as the - * clock input for the peripheral(s). To supply a clock to the peripheral - * module(s), the associated channel must be connected to a running Generic - * Clock Generator and the channel enabled. - * - * \section asfdoc_sam0_system_clock_special_considerations Special Considerations - * - * There are no special considerations for this module. - * - * - * \section asfdoc_sam0_system_clock_extra_info Extra Information - * - * For extra information, see \ref asfdoc_sam0_system_clock_extra. This includes: - * - \ref asfdoc_sam0_system_clock_extra_acronyms - * - \ref asfdoc_sam0_system_clock_extra_dependencies - * - \ref asfdoc_sam0_system_clock_extra_errata - * - \ref asfdoc_sam0_system_clock_extra_history - * - * - * \section asfdoc_sam0_system_clock_examples Examples - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_system_clock_exqsg. - * - * - * \section asfdoc_sam0_system_clock_api_overview API Overview - * @{ - */ - -#include "compiler.h" -#include "gclk.h" - -/** - * \name Driver Feature Definition - * Define system clock features set according to different device family. - * @{ - */ -#if (SAMD21) || (SAMR21) || (SAMD11) || (SAMD10) || (SAMDA1) || defined(__DOXYGEN__) -/** Digital Phase Locked Loop (DPLL) feature support. */ -# define FEATURE_SYSTEM_CLOCK_DPLL -#endif -/*@}*/ - -/** - * \brief Available start-up times for the XOSC32K. - * - * Available external 32KHz oscillator start-up times, as a number of external - * clock cycles. - */ -enum system_xosc32k_startup { - /** Wait zero clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_0, - /** Wait 32 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_32, - /** Wait 2048 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_2048, - /** Wait 4096 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_4096, - /** Wait 16384 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_16384, - /** Wait 32768 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_32768, - /** Wait 65536 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_65536, - /** Wait 131072 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_131072, -}; - -/** - * \brief Available start-up times for the XOSC. - * - * Available external oscillator start-up times, as a number of external clock - * cycles. - */ -enum system_xosc_startup { - /** Wait one clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_1, - /** Wait two clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_2, - /** Wait four clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_4, - /** Wait eight clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_8, - /** Wait 16 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_16, - /** Wait 32 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_32, - /** Wait 64 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_64, - /** Wait 128 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_128, - /** Wait 256 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_256, - /** Wait 512 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_512, - /** Wait 1024 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_1024, - /** Wait 2048 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_2048, - /** Wait 4096 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_4096, - /** Wait 8192 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_8192, - /** Wait 16384 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_16384, - /** Wait 32768 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_32768, -}; - -/** - * \brief Available start-up times for the OSC32K. - * - * Available internal 32KHz oscillator start-up times, as a number of internal - * OSC32K clock cycles. - */ -enum system_osc32k_startup { - /** Wait three clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_3, - /** Wait four clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_4, - /** Wait six clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_6, - /** Wait ten clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_10, - /** Wait 18 clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_18, - /** Wait 34 clock cycles until the clock source is considered stable */ - SYSTEM_OSC32K_STARTUP_34, - /** Wait 66 clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_66, - /** Wait 130 clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_130, -}; - -/** - * \brief Division prescalers for the internal 8MHz system clock. - * - * Available prescalers for the internal 8MHz (nominal) system clock. - */ -enum system_osc8m_div { - /** Do not divide the 8MHz RC oscillator output. */ - SYSTEM_OSC8M_DIV_1, - /** Divide the 8MHz RC oscillator output by two. */ - SYSTEM_OSC8M_DIV_2, - /** Divide the 8MHz RC oscillator output by four. */ - SYSTEM_OSC8M_DIV_4, - /** Divide the 8MHz RC oscillator output by eight. */ - SYSTEM_OSC8M_DIV_8, -}; - -/** - * \brief Frequency range for the internal 8MHz RC oscillator. - * - * Internal 8MHz RC oscillator frequency range setting - */ -enum system_osc8m_frequency_range { - /** Frequency range 4MHz to 6MHz. */ - SYSTEM_OSC8M_FREQUENCY_RANGE_4_TO_6, - /** Frequency range 6MHz to 8MHz. */ - SYSTEM_OSC8M_FREQUENCY_RANGE_6_TO_8, - /** Frequency range 8MHz to 11MHz. */ - SYSTEM_OSC8M_FREQUENCY_RANGE_8_TO_11, - /** Frequency range 11MHz to 15MHz. */ - SYSTEM_OSC8M_FREQUENCY_RANGE_11_TO_15, -}; - -/** - * \brief Main CPU and APB/AHB bus clock source prescaler values. - * - * Available division ratios for the CPU and APB/AHB bus clocks. - */ -enum system_main_clock_div { - /** Divide Main clock by one. */ - SYSTEM_MAIN_CLOCK_DIV_1, - /** Divide Main clock by two. */ - SYSTEM_MAIN_CLOCK_DIV_2, - /** Divide Main clock by four. */ - SYSTEM_MAIN_CLOCK_DIV_4, - /** Divide Main clock by eight. */ - SYSTEM_MAIN_CLOCK_DIV_8, - /** Divide Main clock by 16. */ - SYSTEM_MAIN_CLOCK_DIV_16, - /** Divide Main clock by 32. */ - SYSTEM_MAIN_CLOCK_DIV_32, - /** Divide Main clock by 64. */ - SYSTEM_MAIN_CLOCK_DIV_64, - /** Divide Main clock by 128. */ - SYSTEM_MAIN_CLOCK_DIV_128, -}; - -/** - * \brief External clock source types. - * - * Available external clock source types. - */ -enum system_clock_external { - /** The external clock source is a crystal oscillator. */ - SYSTEM_CLOCK_EXTERNAL_CRYSTAL, - /** The connected clock source is an external logic level clock signal. */ - SYSTEM_CLOCK_EXTERNAL_CLOCK, -}; - -/** - * \brief Operating modes of the DFLL clock source. - * - * Available operating modes of the DFLL clock source module. - */ -enum system_clock_dfll_loop_mode { - /** The DFLL is operating in open loop mode with no feedback. */ - SYSTEM_CLOCK_DFLL_LOOP_MODE_OPEN, - /** The DFLL is operating in closed loop mode with frequency feedback from - * a low frequency reference clock. - */ - SYSTEM_CLOCK_DFLL_LOOP_MODE_CLOSED = SYSCTRL_DFLLCTRL_MODE, - -#ifdef SYSCTRL_DFLLCTRL_USBCRM - /** The DFLL is operating in USB recovery mode with frequency feedback - * from USB SOF. - */ - SYSTEM_CLOCK_DFLL_LOOP_MODE_USB_RECOVERY = SYSCTRL_DFLLCTRL_USBCRM, -#endif -}; - -/** - * \brief Locking behavior for the DFLL during device wake-up. - * - * DFLL lock behavior modes on device wake-up from sleep. - */ -enum system_clock_dfll_wakeup_lock { - /** Keep DFLL lock when the device wakes from sleep. */ - SYSTEM_CLOCK_DFLL_WAKEUP_LOCK_KEEP, - /** Lose DFLL lock when the devices wakes from sleep. */ - SYSTEM_CLOCK_DFLL_WAKEUP_LOCK_LOSE = SYSCTRL_DFLLCTRL_LLAW, -}; - -/** - * \brief Fine tracking behavior for the DFLL once a lock has been acquired. - * - * DFLL fine tracking behavior modes after a lock has been acquired. - */ -enum system_clock_dfll_stable_tracking { - /** Keep tracking after the DFLL has gotten a fine lock. */ - SYSTEM_CLOCK_DFLL_STABLE_TRACKING_TRACK_AFTER_LOCK, - /** Stop tracking after the DFLL has gotten a fine lock. */ - SYSTEM_CLOCK_DFLL_STABLE_TRACKING_FIX_AFTER_LOCK = SYSCTRL_DFLLCTRL_STABLE, -}; - -/** - * \brief Chill-cycle behavior of the DFLL module. - * - * DFLL chill-cycle behavior modes of the DFLL module. A chill cycle is a period - * of time when the DFLL output frequency is not measured by the unit, to allow - * the output to stabilize after a change in the input clock source. - */ -enum system_clock_dfll_chill_cycle { - /** Enable a chill cycle, where the DFLL output frequency is not measured. */ - SYSTEM_CLOCK_DFLL_CHILL_CYCLE_ENABLE, - /** Disable a chill cycle, where the DFLL output frequency is not measured. */ - SYSTEM_CLOCK_DFLL_CHILL_CYCLE_DISABLE = SYSCTRL_DFLLCTRL_CCDIS, -}; - -/** - * \brief QuickLock settings for the DFLL module. - * - * DFLL QuickLock settings for the DFLL module, to allow for a faster lock of - * the DFLL output frequency at the expense of accuracy. - */ -enum system_clock_dfll_quick_lock { - /** Enable the QuickLock feature for looser lock requirements on the DFLL. */ - SYSTEM_CLOCK_DFLL_QUICK_LOCK_ENABLE, - /** Disable the QuickLock feature for strict lock requirements on the DFLL. */ - SYSTEM_CLOCK_DFLL_QUICK_LOCK_DISABLE = SYSCTRL_DFLLCTRL_QLDIS, -}; - -/** - * \brief Available clock sources in the system. - * - * Clock sources available to the GCLK generators. - */ -enum system_clock_source { - /** Internal 8MHz RC oscillator. */ - SYSTEM_CLOCK_SOURCE_OSC8M = GCLK_SOURCE_OSC8M, - /** Internal 32KHz RC oscillator. */ - SYSTEM_CLOCK_SOURCE_OSC32K = GCLK_SOURCE_OSC32K, - /** External oscillator. */ - SYSTEM_CLOCK_SOURCE_XOSC = GCLK_SOURCE_XOSC , - /** External 32KHz oscillator. */ - SYSTEM_CLOCK_SOURCE_XOSC32K = GCLK_SOURCE_XOSC32K, - /** Digital Frequency Locked Loop (DFLL). */ - SYSTEM_CLOCK_SOURCE_DFLL = GCLK_SOURCE_DFLL48M, - /** Internal Ultra Low Power 32KHz oscillator. */ - SYSTEM_CLOCK_SOURCE_ULP32K = GCLK_SOURCE_OSCULP32K, - /** Generator input pad. */ - SYSTEM_CLOCK_SOURCE_GCLKIN = GCLK_SOURCE_GCLKIN, - /** Generic clock generator one output. */ - SYSTEM_CLOCK_SOURCE_GCLKGEN1 = GCLK_SOURCE_GCLKGEN1, -#ifdef FEATURE_SYSTEM_CLOCK_DPLL - /** Digital Phase Locked Loop (DPLL). - * Check \c FEATURE_SYSTEM_CLOCK_DPLL for which device support it. - */ - SYSTEM_CLOCK_SOURCE_DPLL = GCLK_SOURCE_FDPLL, -#endif -}; - -/** - * \brief List of APB peripheral buses. - * - * Available bus clock domains on the APB bus. - */ -enum system_clock_apb_bus { - /** Peripheral bus A on the APB bus. */ - SYSTEM_CLOCK_APB_APBA, - /** Peripheral bus B on the APB bus. */ - SYSTEM_CLOCK_APB_APBB, - /** Peripheral bus C on the APB bus. */ - SYSTEM_CLOCK_APB_APBC, -}; - -/** - * \brief Configuration structure for XOSC. - * - * External oscillator clock configuration structure. - */ -struct system_clock_source_xosc_config { - /** External clock type. */ - enum system_clock_external external_clock; - /** Crystal oscillator start-up time. */ - enum system_xosc_startup startup_time; - /** Enable automatic amplitude gain control. */ - bool auto_gain_control; - /** External clock/crystal frequency. */ - uint32_t frequency; - /** Keep the XOSC enabled in standby sleep mode. */ - bool run_in_standby; - /** Run On Demand. If this is set the XOSC won't run - * until requested by a peripheral. */ - bool on_demand; -}; - -/** - * \brief Configuration structure for XOSC32K. - * - * External 32KHz oscillator clock configuration structure. - */ -struct system_clock_source_xosc32k_config { - /** External clock type. */ - enum system_clock_external external_clock; - /** Crystal oscillator start-up time. */ - enum system_xosc32k_startup startup_time; - /** Enable automatic amplitude control. */ - bool auto_gain_control; - /** Enable 1KHz output. */ - bool enable_1khz_output; - /** Enable 32KHz output. */ - bool enable_32khz_output; - /** External clock/crystal frequency. */ - uint32_t frequency; - /** Keep the XOSC32K enabled in standby sleep mode. */ - bool run_in_standby; - /** Run On Demand. If this is set the XOSC32K won't run - * until requested by a peripheral. */ - bool on_demand; - /** Lock configuration after it has been written, - * a device reset will release the lock. */ - bool write_once; -}; - -/** - * \brief Configuration structure for OSC8M. - * - * Internal 8MHz (nominal) oscillator configuration structure. - */ -struct system_clock_source_osc8m_config { - /** Internal 8MHz RC oscillator prescaler. */ - enum system_osc8m_div prescaler; - /** Keep the OSC8M enabled in standby sleep mode. */ - bool run_in_standby; - /** Run On Demand. If this is set the OSC8M won't run - * until requested by a peripheral. */ - bool on_demand; -}; - -/** - * \brief Configuration structure for OSC32K. - * - * Internal 32KHz (nominal) oscillator configuration structure. - */ -struct system_clock_source_osc32k_config { - /** Startup time. */ - enum system_osc32k_startup startup_time; - /** Enable 1KHz output. */ - bool enable_1khz_output; - /** Enable 32KHz output. */ - bool enable_32khz_output; - /** Keep the OSC32K enabled in standby sleep mode. */ - bool run_in_standby; - /** Run On Demand. If this is set the OSC32K won't run - * until requested by a peripheral. */ - bool on_demand; - /** Lock configuration after it has been written, - * a device reset will release the lock. */ - bool write_once; -}; - -/** - * \brief Configuration structure for DFLL. - * - * DFLL oscillator configuration structure. - */ -struct system_clock_source_dfll_config { - /** Loop mode. */ - enum system_clock_dfll_loop_mode loop_mode; - /** Run On Demand. If this is set the DFLL won't run - * until requested by a peripheral. */ - bool on_demand; - /** Enable Quick Lock. */ - enum system_clock_dfll_quick_lock quick_lock; - /** Enable Chill Cycle. */ - enum system_clock_dfll_chill_cycle chill_cycle; - /** DFLL lock state on wakeup. */ - enum system_clock_dfll_wakeup_lock wakeup_lock; - /** DFLL tracking after fine lock. */ - enum system_clock_dfll_stable_tracking stable_tracking; - /** Coarse calibration value (Open loop mode). */ - uint8_t coarse_value; - /** Fine calibration value (Open loop mode). */ - uint16_t fine_value; - /** Coarse adjustment maximum step size (Closed loop mode). */ - uint8_t coarse_max_step; - /** Fine adjustment maximum step size (Closed loop mode). */ - uint16_t fine_max_step; - /** DFLL multiply factor (Closed loop mode. */ - uint16_t multiply_factor; -}; - -/** - * \name External Oscillator Management - * @{ - */ - -/** - * \brief Retrieve the default configuration for XOSC. - * - * Fills a configuration structure with the default configuration for an - * external oscillator module: - * - External Crystal - * - Start-up time of 16384 external clock cycles - * - Automatic crystal gain control mode enabled - * - Frequency of 12MHz - * - Don't run in STANDBY sleep mode - * - Run only when requested by peripheral (on demand) - * - * \param[out] config Configuration structure to fill with default values - */ -static inline void system_clock_source_xosc_get_config_defaults( - struct system_clock_source_xosc_config *const config) -{ - Assert(config); - - config->external_clock = SYSTEM_CLOCK_EXTERNAL_CRYSTAL; - config->startup_time = SYSTEM_XOSC_STARTUP_16384; - config->auto_gain_control = true; - config->frequency = 12000000UL; - config->run_in_standby = false; - config->on_demand = true; -} - -void system_clock_source_xosc_set_config( - struct system_clock_source_xosc_config *const config); - -/** - * @} - */ - - -/** - * \name External 32KHz Oscillator Management - * @{ - */ - -/** - * \brief Retrieve the default configuration for XOSC32K. - * - * Fills a configuration structure with the default configuration for an - * external 32KHz oscillator module: - * - External Crystal - * - Start-up time of 16384 external clock cycles - * - Automatic crystal gain control mode disabled - * - Frequency of 32.768KHz - * - 1KHz clock output disabled - * - 32KHz clock output enabled - * - Don't run in STANDBY sleep mode - * - Run only when requested by peripheral (on demand) - * - Don't lock registers after configuration has been written - * - * \param[out] config Configuration structure to fill with default values - */ -static inline void system_clock_source_xosc32k_get_config_defaults( - struct system_clock_source_xosc32k_config *const config) -{ - Assert(config); - - config->external_clock = SYSTEM_CLOCK_EXTERNAL_CRYSTAL; - config->startup_time = SYSTEM_XOSC32K_STARTUP_16384; - config->auto_gain_control = false; - config->frequency = 32768UL; - config->enable_1khz_output = false; - config->enable_32khz_output = true; - config->run_in_standby = false; - config->on_demand = true; - config->write_once = false; -} - -void system_clock_source_xosc32k_set_config( - struct system_clock_source_xosc32k_config *const config); -/** - * @} - */ - - -/** - * \name Internal 32KHz Oscillator Management - * @{ - */ - -/** - * \brief Retrieve the default configuration for OSC32K. - * - * Fills a configuration structure with the default configuration for an - * internal 32KHz oscillator module: - * - 1KHz clock output enabled - * - 32KHz clock output enabled - * - Don't run in STANDBY sleep mode - * - Run only when requested by peripheral (on demand) - * - Set startup time to 130 cycles - * - Don't lock registers after configuration has been written - * - * \param[out] config Configuration structure to fill with default values - */ -static inline void system_clock_source_osc32k_get_config_defaults( - struct system_clock_source_osc32k_config *const config) -{ - Assert(config); - - config->enable_1khz_output = true; - config->enable_32khz_output = true; - config->run_in_standby = false; - config->on_demand = true; - config->startup_time = SYSTEM_OSC32K_STARTUP_130; - config->write_once = false; -} - -void system_clock_source_osc32k_set_config( - struct system_clock_source_osc32k_config *const config); - -/** - * @} - */ - - -/** - * \name Internal 8MHz Oscillator Management - * @{ - */ - -/** - * \brief Retrieve the default configuration for OSC8M. - * - * Fills a configuration structure with the default configuration for an - * internal 8MHz (nominal) oscillator module: - * - Clock output frequency divided by a factor of eight - * - Don't run in STANDBY sleep mode - * - Run only when requested by peripheral (on demand) - * - * \param[out] config Configuration structure to fill with default values - */ -static inline void system_clock_source_osc8m_get_config_defaults( - struct system_clock_source_osc8m_config *const config) -{ - Assert(config); - - config->prescaler = SYSTEM_OSC8M_DIV_8; - config->run_in_standby = false; - config->on_demand = true; -} - -void system_clock_source_osc8m_set_config( - struct system_clock_source_osc8m_config *const config); - -/** - * @} - */ - - -/** - * \name Internal DFLL Management - * @{ - */ - -/** - * \brief Retrieve the default configuration for DFLL. - * - * Fills a configuration structure with the default configuration for a - * DFLL oscillator module: - * - Open loop mode - * - QuickLock mode enabled - * - Chill cycle enabled - * - Output frequency lock maintained during device wake-up - * - Continuous tracking of the output frequency - * - Default tracking values at the mid-points for both coarse and fine - * tracking parameters - * - Don't run in STANDBY sleep mode - * - Run only when requested by peripheral (on demand) - * - * \param[out] config Configuration structure to fill with default values - */ -static inline void system_clock_source_dfll_get_config_defaults( - struct system_clock_source_dfll_config *const config) -{ - Assert(config); - - config->loop_mode = SYSTEM_CLOCK_DFLL_LOOP_MODE_OPEN; - config->quick_lock = SYSTEM_CLOCK_DFLL_QUICK_LOCK_ENABLE; - config->chill_cycle = SYSTEM_CLOCK_DFLL_CHILL_CYCLE_ENABLE; - config->wakeup_lock = SYSTEM_CLOCK_DFLL_WAKEUP_LOCK_KEEP; - config->stable_tracking = SYSTEM_CLOCK_DFLL_STABLE_TRACKING_TRACK_AFTER_LOCK; - config->on_demand = true; - - /* Open loop mode calibration value */ - config->coarse_value = 0x1f / 4; /* Midpoint */ - config->fine_value = 0xff / 4; /* Midpoint */ - - /* Closed loop mode */ - config->coarse_max_step = 1; - config->fine_max_step = 1; - config->multiply_factor = 6; /* Multiply 8MHz by 6 to get 48MHz */ -} - -void system_clock_source_dfll_set_config( - struct system_clock_source_dfll_config *const config); - -/** - * @} - */ - -/** - * \name Clock Source Management - * @{ - */ -enum status_code system_clock_source_write_calibration( - const enum system_clock_source system_clock_source, - const uint16_t calibration_value, - const uint8_t freq_range); - -enum status_code system_clock_source_enable( - const enum system_clock_source system_clock_source); - -enum status_code system_clock_source_disable( - const enum system_clock_source clk_source); - -bool system_clock_source_is_ready( - const enum system_clock_source clk_source); - -uint32_t system_clock_source_get_hz( - const enum system_clock_source clk_source); - -/** - * @} - */ - -/** - * \name Main Clock Management - * @{ - */ - -/** - * \brief Set main CPU clock divider. - * - * Sets the clock divider used on the main clock to provide the CPU clock. - * - * \param[in] divider CPU clock divider to set - */ -static inline void system_cpu_clock_set_divider( - const enum system_main_clock_div divider) -{ - Assert(((uint32_t)divider & PM_CPUSEL_CPUDIV_Msk) == divider); - PM->CPUSEL.reg = (uint32_t)divider; -} - -/** - * \brief Retrieves the current frequency of the CPU core. - * - * Retrieves the operating frequency of the CPU core, obtained from the main - * generic clock and the set CPU bus divider. - * - * \return Current CPU frequency in Hz. - */ -static inline uint32_t system_cpu_clock_get_hz(void) -{ - return (system_gclk_gen_get_hz(GCLK_GENERATOR_0) >> PM->CPUSEL.reg); -} - -/** - * \brief Set APBx clock divider. - * - * Set the clock divider used on the main clock to provide the clock for the - * given APBx bus. - * - * \param[in] divider APBx bus divider to set - * \param[in] bus APBx bus to set divider - * - * \returns Status of the clock division change operation. - * - * \retval STATUS_ERR_INVALID_ARG Invalid bus ID was given - * \retval STATUS_OK The APBx clock was set successfully - */ -static inline enum status_code system_apb_clock_set_divider( - const enum system_clock_apb_bus bus, - const enum system_main_clock_div divider) -{ - switch (bus) { - case SYSTEM_CLOCK_APB_APBA: - PM->APBASEL.reg = (uint32_t)divider; - break; - case SYSTEM_CLOCK_APB_APBB: - PM->APBBSEL.reg = (uint32_t)divider; - break; - case SYSTEM_CLOCK_APB_APBC: - PM->APBCSEL.reg = (uint32_t)divider; - break; - default: - Assert(false); - return STATUS_ERR_INVALID_ARG; - } - - return STATUS_OK; -} - -/** - * \brief Retrieves the current frequency of a ABPx. - * - * Retrieves the operating frequency of an APBx bus, obtained from the main - * generic clock and the set APBx bus divider. - * - * \return Current APBx bus frequency in Hz. - */ -static inline uint32_t system_apb_clock_get_hz( - const enum system_clock_apb_bus bus) -{ - uint16_t bus_divider = 0; - - switch (bus) { - case SYSTEM_CLOCK_APB_APBA: - bus_divider = PM->APBASEL.reg; - break; - case SYSTEM_CLOCK_APB_APBB: - bus_divider = PM->APBBSEL.reg; - break; - case SYSTEM_CLOCK_APB_APBC: - bus_divider = PM->APBCSEL.reg; - break; - default: - Assert(false); - return 0; - } - - return (system_gclk_gen_get_hz(GCLK_GENERATOR_0) >> bus_divider); -} - - -/** - * @} - */ - -/** - * \name Bus Clock Masking - * @{ - */ - -/** - * \brief Set bits in the clock mask for the AHB bus. - * - * This function will set bits in the clock mask for the AHB bus. - * Any bits set to 1 will enable that clock, 0 bits in the mask - * will be ignored. - * - * \param[in] ahb_mask AHB clock mask to enable - */ -static inline void system_ahb_clock_set_mask( - const uint32_t ahb_mask) -{ - PM->AHBMASK.reg |= ahb_mask; -} - -/** - * \brief Clear bits in the clock mask for the AHB bus. - * - * This function will clear bits in the clock mask for the AHB bus. - * Any bits set to 1 will disable that clock, 0 bits in the mask - * will be ignored. - * - * \param[in] ahb_mask AHB clock mask to disable - */ -static inline void system_ahb_clock_clear_mask( - const uint32_t ahb_mask) -{ - PM->AHBMASK.reg &= ~ahb_mask; -} - -/** - * \brief Set bits in the clock mask for an APBx bus. - * - * This function will set bits in the clock mask for an APBx bus. - * Any bits set to 1 will enable the corresponding module clock, zero bits in - * the mask will be ignored. - * - * \param[in] mask APBx clock mask, a \c SYSTEM_CLOCK_APB_APBx constant from - * the device header files - * \param[in] bus Bus to set clock mask bits for, a mask of \c PM_APBxMASK_* - * constants from the device header files - * - * \returns Status indicating the result of the clock mask change operation. - * - * \retval STATUS_ERR_INVALID_ARG Invalid bus given - * \retval STATUS_OK The clock mask was set successfully - */ -static inline enum status_code system_apb_clock_set_mask( - const enum system_clock_apb_bus bus, - const uint32_t mask) -{ - switch (bus) { - case SYSTEM_CLOCK_APB_APBA: - PM->APBAMASK.reg |= mask; - break; - - case SYSTEM_CLOCK_APB_APBB: - PM->APBBMASK.reg |= mask; - break; - - case SYSTEM_CLOCK_APB_APBC: - PM->APBCMASK.reg |= mask; - break; - - default: - Assert(false); - return STATUS_ERR_INVALID_ARG; - - } - - return STATUS_OK; -} - -/** - * \brief Clear bits in the clock mask for an APBx bus. - * - * This function will clear bits in the clock mask for an APBx bus. - * Any bits set to 1 will disable the corresponding module clock, zero bits in - * the mask will be ignored. - * - * \param[in] mask APBx clock mask, a \c SYSTEM_CLOCK_APB_APBx constant from - * the device header files - * \param[in] bus Bus to clear clock mask bits - * - * \returns Status indicating the result of the clock mask change operation. - * - * \retval STATUS_ERR_INVALID_ARG Invalid bus ID was given - * \retval STATUS_OK The clock mask was changed successfully - */ -static inline enum status_code system_apb_clock_clear_mask( - const enum system_clock_apb_bus bus, - const uint32_t mask) -{ - switch (bus) { - case SYSTEM_CLOCK_APB_APBA: - PM->APBAMASK.reg &= ~mask; - break; - - case SYSTEM_CLOCK_APB_APBB: - PM->APBBMASK.reg &= ~mask; - break; - - case SYSTEM_CLOCK_APB_APBC: - PM->APBCMASK.reg &= ~mask; - break; - - default: - Assert(false); - return STATUS_ERR_INVALID_ARG; - } - - return STATUS_OK; -} - -/** - * @} - */ - -#ifdef FEATURE_SYSTEM_CLOCK_DPLL -/** - * \brief Reference clock source of the DPLL module. - */ -enum system_clock_source_dpll_reference_clock { - /** Select XOSC32K as clock reference. */ - SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_XOSC32K, - /** Select XOSC as clock reference. */ - SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_XOSC, - /** Select GCLK as clock reference. */ - SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_GCLK, -}; - -/** - * \brief Lock time-out value of the DPLL module. - */ -enum system_clock_source_dpll_lock_time { - /** Set no time-out as default. */ - SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_DEFAULT, - /** Set time-out if no lock within 8ms. */ - SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_8MS = 0x04, - /** Set time-out if no lock within 9ms. */ - SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_9MS, - /** Set time-out if no lock within 10ms. */ - SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_10MS, - /** Set time-out if no lock within 11ms. */ - SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_11MS, -}; - -/** - * \brief Filter type of the DPLL module. - */ -enum system_clock_source_dpll_filter { - /** Default filter mode. */ - SYSTEM_CLOCK_SOURCE_DPLL_FILTER_DEFAULT, - /** Low bandwidth filter. */ - SYSTEM_CLOCK_SOURCE_DPLL_FILTER_LOW_BANDWIDTH_FILTER, - /** High bandwidth filter. */ - SYSTEM_CLOCK_SOURCE_DPLL_FILTER_HIGH_BANDWIDTH_FILTER, - /** High damping filter. */ - SYSTEM_CLOCK_SOURCE_DPLL_FILTER_HIGH_DAMPING_FILTER, -}; - -/** - * \brief Configuration structure for DPLL. - * - * DPLL oscillator configuration structure. - */ -struct system_clock_source_dpll_config { - /** Run On Demand. If this is set the DPLL won't run - * until requested by a peripheral. */ - bool on_demand; - /** Keep the DPLL enabled in standby sleep mode. */ - bool run_in_standby; - /** Bypass lock signal. */ - bool lock_bypass; - /** Wake up fast. If this is set DPLL output clock is enabled after - * the startup time. */ - bool wake_up_fast; - /** Enable low power mode. */ - bool low_power_enable; - - /** Output frequency of the clock. */ - uint32_t output_frequency; - /** Reference frequency of the clock. */ - uint32_t reference_frequency; - /** Devider of reference clock. */ - uint16_t reference_divider; - - /** Filter type of the DPLL module. */ - enum system_clock_source_dpll_filter filter; - /** Lock time-out value of the DPLL module. */ - enum system_clock_source_dpll_lock_time lock_time; - /** Reference clock source of the DPLL module. */ - enum system_clock_source_dpll_reference_clock reference_clock; -}; - -/** - * \name Internal DPLL Management - * @{ - */ - -/** - * \brief Retrieve the default configuration for DPLL. - * - * Fills a configuration structure with the default configuration for a - * DPLL oscillator module: - * - Run only when requested by peripheral (on demand) - * - Don't run in STANDBY sleep mode - * - Lock bypass disabled - * - Fast wake up disabled - * - Low power mode disabled - * - Output frequency is 48MHz - * - Reference clock frequency is 32768Hz - * - Not divide reference clock - * - Select REF0 as reference clock - * - Set lock time to default mode - * - Use default filter - * - * \param[out] config Configuration structure to fill with default values - */ -static inline void system_clock_source_dpll_get_config_defaults( - struct system_clock_source_dpll_config *const config) -{ - config->on_demand = true; - config->run_in_standby = false; - config->lock_bypass = false; - config->wake_up_fast = false; - config->low_power_enable = false; - - config->output_frequency = 48000000; - config->reference_frequency = 32768; - config->reference_divider = 1; - config->reference_clock = SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_XOSC32K; - - config->lock_time = SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_DEFAULT; - config->filter = SYSTEM_CLOCK_SOURCE_DPLL_FILTER_DEFAULT; -}; - -void system_clock_source_dpll_set_config( - struct system_clock_source_dpll_config *const config); - -/* @} */ -#endif - -/** - * \name System Clock Initialization - * @{ - */ - -void system_clock_init(void); - -/** - * @} - */ - -/** - * \name System Flash Wait States - * @{ - */ - -/** - * \brief Set flash controller wait states. - * - * Will set the number of wait states that are used by the onboard - * flash memory. The number of wait states depend on both device - * supply voltage and CPU speed. The required number of wait states - * can be found in the electrical characteristics of the device. - * - * \param[in] wait_states Number of wait states to use for internal flash - */ -static inline void system_flash_set_waitstates(uint8_t wait_states) -{ - Assert(NVMCTRL_CTRLB_RWS((uint32_t)wait_states) == - ((uint32_t)wait_states << NVMCTRL_CTRLB_RWS_Pos)); - - NVMCTRL->CTRLB.bit.RWS = wait_states; -} -/** - * @} - */ - -/** - * @} - */ - -/** - * \page asfdoc_sam0_system_clock_extra Extra Information for SYSTEM CLOCK Driver - * - * \section asfdoc_sam0_system_clock_extra_acronyms Acronyms - * Below is a table listing the acronyms used in this module, along with their - * intended meanings. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
AcronymDescription
DFLLDigital Frequency Locked Loop
MUXMultiplexer
OSC32KInternal 32KHz Oscillator
OSC8MInternal 8MHz Oscillator
PLLPhase Locked Loop
OSCOscillator
XOSCExternal Oscillator
XOSC32KExternal 32KHz Oscillator
AHBAdvanced High-performance Bus
APBAdvanced Peripheral Bus
DPLLDigital Phase Locked Loop
- * - * - * \section asfdoc_sam0_system_clock_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - None - * - * - * \section asfdoc_sam0_system_clock_extra_errata Errata - * - * - This driver implements experimental workaround for errata 9905 - * - * "The DFLL clock must be requested before being configured otherwise a - * write access to a DFLL register can freeze the device." - * This driver will enable and configure the DFLL before the ONDEMAND bit is set. - * - * - * \section asfdoc_sam0_system_clock_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Changelog
- * \li Corrected OSC32K startup time definitions - * \li Support locking of OSC32K and XOSC32K config register (default: false) - * \li Added DPLL support, functions added: - * \c system_clock_source_dpll_get_config_defaults() and - * \c system_clock_source_dpll_set_config() - * \li Moved gclk channel locking feature out of the config struct - * functions added: - * \c system_gclk_chan_lock(), - * \c system_gclk_chan_is_locked() - * \c system_gclk_chan_is_enabled() and - * \c system_gclk_gen_is_enabled() - *
Fixed \c system_gclk_chan_disable() deadlocking if a channel is enabled - * and configured to a failed/not running clock generator
- * \li Changed default value for CONF_CLOCK_DFLL_ON_DEMAND from \c true to \c false - * \li Fixed system_flash_set_waitstates() failing with an assertion - * if an odd number of wait states provided - *
- * \li Updated dfll configuration function to implement workaround for - * errata 9905 in the DFLL module - * \li Updated \c system_clock_init() to reset interrupt flags before - * they are used - * \li Fixed \c system_clock_source_get_hz() to return correcy DFLL - * frequency number - *
\li Fixed \c system_clock_source_is_ready not returning the correct - * state for \c SYSTEM_CLOCK_SOURCE_OSC8M - * \li Renamed the various \c system_clock_source_*_get_default_config() - * functions to \c system_clock_source_*_get_config_defaults() to - * match the remainder of ASF - * \li Added OSC8M calibration constant loading from the device signature - * row when the oscillator is initialized - * \li Updated default configuration of the XOSC32 to disable Automatic - * Gain Control due to silicon errata - *
Initial Release
- */ - -/** - * \page asfdoc_sam0_system_clock_exqsg Examples for System Clock Driver - * - * This is a list of the available Quick Start guides (QSGs) and example - * applications for \ref asfdoc_sam0_system_clock_group. QSGs are simple - * examples with step-by-step instructions to configure and use this driver in - * a selection of use cases. Note that QSGs can be compiled as a standalone - * application or be added to the user application. - * - * - \subpage asfdoc_sam0_system_clock_basic_use_case - * - \subpage asfdoc_sam0_system_gclk_basic_use_case - * - * \page asfdoc_sam0_system_clock_document_revision_history Document Revision History - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Doc. Rev. - * Date - * Comments - *
E04/2015Added support for SAMDAx.
D12/2014Added support for SAMR21 and SAMD10/D11.
C01/2014Added support for SAMD21.
B06/2013Corrected documentation typos. Fixed missing steps in the Basic - * Use Case Quick Start Guide.
A06/2013Initial release
- */ - -#ifdef __cplusplus -} -#endif - -#endif /* SYSTEM_CLOCK_FEATURE_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/compiler.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/compiler.h deleted file mode 100644 index 2d95f97..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/compiler.h +++ /dev/null @@ -1,1157 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef UTILS_COMPILER_H_INCLUDED -#define UTILS_COMPILER_H_INCLUDED - -/** - * \defgroup group_sam0_utils Compiler abstraction layer and code utilities - * - * Compiler abstraction layer and code utilities for Cortex-M0+ based Atmel SAM devices. - * This module provides various abstraction layers and utilities to make code compatible between different compilers. - * - * @{ - */ - -#if (defined __ICCARM__) -# include -#endif - -#include -//#include -#include "status_codes.h" -#include "preprocessor/preprocessor.h" -#include - -#ifndef __ASSEMBLY__ - -#include -#include -#include -#include - -/** - * \def UNUSED - * \brief Marking \a v as a unused parameter or value. - */ -#define UNUSED(v) (void)(v) - -/** - * \def barrier - * \brief Memory barrier - */ -#ifdef __GNUC__ -# define barrier() asm volatile("" ::: "memory") -#else -# define barrier() asm ("") -#endif - -/** - * \brief Emit the compiler pragma \a arg. - * - * \param[in] arg The pragma directive as it would appear after \e \#pragma - * (i.e. not stringified). - */ -#define COMPILER_PRAGMA(arg) _Pragma(#arg) - -/** - * \def COMPILER_PACK_SET(alignment) - * \brief Set maximum alignment for subsequent struct and union definitions to \a alignment. - */ -#define COMPILER_PACK_SET(alignment) COMPILER_PRAGMA(pack(alignment)) - -/** - * \def COMPILER_PACK_RESET() - * \brief Set default alignment for subsequent struct and union definitions. - */ -#define COMPILER_PACK_RESET() COMPILER_PRAGMA(pack()) - - -/** - * \brief Set aligned boundary. - */ -#if (defined __GNUC__) || (defined __CC_ARM) -# define COMPILER_ALIGNED(a) __attribute__((__aligned__(a))) -#elif (defined __ICCARM__) -# define COMPILER_ALIGNED(a) COMPILER_PRAGMA(data_alignment = a) -#endif - -/** - * \brief Set word-aligned boundary. - */ -#if (defined __GNUC__) || defined(__CC_ARM) -#define COMPILER_WORD_ALIGNED __attribute__((__aligned__(4))) -#elif (defined __ICCARM__) -#define COMPILER_WORD_ALIGNED COMPILER_PRAGMA(data_alignment = 4) -#endif - -/** - * \def __always_inline - * \brief The function should always be inlined. - * - * This annotation instructs the compiler to ignore its inlining - * heuristics and inline the function no matter how big it thinks it - * becomes. - */ -#if defined(__CC_ARM) -# define __always_inline __forceinline -#elif (defined __GNUC__) -# define __always_inline __attribute__((__always_inline__)) -#elif (defined __ICCARM__) -# define __always_inline _Pragma("inline=forced") -#endif - -/** - * \def __no_inline - * \brief The function should never be inlined - * - * This annotation instructs the compiler to ignore its inlining - * heuristics and not inline the function no matter how small it thinks it - * becomes. - */ -#if defined(__CC_ARM) -# define __no_inline __attribute__((noinline)) -#elif (defined __GNUC__) -# define __no_inline __attribute__((noinline)) -#elif (defined __ICCARM__) -# define __no_inline _Pragma("inline=never") -#endif - - -/** \brief This macro is used to test fatal errors. - * - * The macro tests if the expression is false. If it is, a fatal error is - * detected and the application hangs up. If \c TEST_SUITE_DEFINE_ASSERT_MACRO - * is defined, a unit test version of the macro is used, to allow execution - * of further tests after a false expression. - * - * \param[in] expr Expression to evaluate and supposed to be nonzero. - */ -#if defined(_ASSERT_ENABLE_) -# if defined(TEST_SUITE_DEFINE_ASSERT_MACRO) -# include "unit_test/suite.h" -# else -# undef TEST_SUITE_DEFINE_ASSERT_MACRO -# define Assert(expr) \ - {\ - if (!(expr)) asm("BKPT #0");\ - } -# endif -#else -# define Assert(expr) ((void) 0) -#endif - -/* Define WEAK attribute */ -#if defined ( __CC_ARM ) -# define WEAK __attribute__ ((weak)) -#elif defined ( __ICCARM__ ) -# define WEAK __weak -#elif defined ( __GNUC__ ) -# define WEAK __attribute__ ((weak)) -#endif - -/* Define NO_INIT attribute */ -#if defined ( __CC_ARM ) -# define NO_INIT __attribute__((zero_init)) -#elif defined ( __ICCARM__ ) -# define NO_INIT __no_init -#elif defined ( __GNUC__ ) -# define NO_INIT __attribute__((section(".no_init"))) -#endif - -#include "interrupt.h" - -/** \name Usual Types - * @{ */ -#ifndef __cplusplus -# if !defined(__bool_true_false_are_defined) -typedef unsigned char bool; -# endif -#endif -typedef uint16_t le16_t; -typedef uint16_t be16_t; -typedef uint32_t le32_t; -typedef uint32_t be32_t; -typedef uint32_t iram_size_t; -/** @} */ - -/** \name Aliasing Aggregate Types - * @{ */ - -/** 16-bit union. */ -typedef union -{ - int16_t s16; - uint16_t u16; - int8_t s8[2]; - uint8_t u8[2]; -} Union16; - -/** 32-bit union. */ -typedef union -{ - int32_t s32; - uint32_t u32; - int16_t s16[2]; - uint16_t u16[2]; - int8_t s8[4]; - uint8_t u8[4]; -} Union32; - -/** 64-bit union. */ -typedef union -{ - int64_t s64; - uint64_t u64; - int32_t s32[2]; - uint32_t u32[2]; - int16_t s16[4]; - uint16_t u16[4]; - int8_t s8[8]; - uint8_t u8[8]; -} Union64; - -/** Union of pointers to 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef union -{ - int64_t *s64ptr; - uint64_t *u64ptr; - int32_t *s32ptr; - uint32_t *u32ptr; - int16_t *s16ptr; - uint16_t *u16ptr; - int8_t *s8ptr; - uint8_t *u8ptr; -} UnionPtr; - -/** Union of pointers to volatile 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef union -{ - volatile int64_t *s64ptr; - volatile uint64_t *u64ptr; - volatile int32_t *s32ptr; - volatile uint32_t *u32ptr; - volatile int16_t *s16ptr; - volatile uint16_t *u16ptr; - volatile int8_t *s8ptr; - volatile uint8_t *u8ptr; -} UnionVPtr; - -/** Union of pointers to constant 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef union -{ - const int64_t *s64ptr; - const uint64_t *u64ptr; - const int32_t *s32ptr; - const uint32_t *u32ptr; - const int16_t *s16ptr; - const uint16_t *u16ptr; - const int8_t *s8ptr; - const uint8_t *u8ptr; -} UnionCPtr; - -/** Union of pointers to constant volatile 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef union -{ - const volatile int64_t *s64ptr; - const volatile uint64_t *u64ptr; - const volatile int32_t *s32ptr; - const volatile uint32_t *u32ptr; - const volatile int16_t *s16ptr; - const volatile uint16_t *u16ptr; - const volatile int8_t *s8ptr; - const volatile uint8_t *u8ptr; -} UnionCVPtr; - -/** Structure of pointers to 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef struct -{ - int64_t *s64ptr; - uint64_t *u64ptr; - int32_t *s32ptr; - uint32_t *u32ptr; - int16_t *s16ptr; - uint16_t *u16ptr; - int8_t *s8ptr; - uint8_t *u8ptr; -} StructPtr; - -/** Structure of pointers to volatile 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef struct -{ - volatile int64_t *s64ptr; - volatile uint64_t *u64ptr; - volatile int32_t *s32ptr; - volatile uint32_t *u32ptr; - volatile int16_t *s16ptr; - volatile uint16_t *u16ptr; - volatile int8_t *s8ptr; - volatile uint8_t *u8ptr; -} StructVPtr; - -/** Structure of pointers to constant 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef struct -{ - const int64_t *s64ptr; - const uint64_t *u64ptr; - const int32_t *s32ptr; - const uint32_t *u32ptr; - const int16_t *s16ptr; - const uint16_t *u16ptr; - const int8_t *s8ptr; - const uint8_t *u8ptr; -} StructCPtr; - -/** Structure of pointers to constant volatile 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef struct -{ - const volatile int64_t *s64ptr; - const volatile uint64_t *u64ptr; - const volatile int32_t *s32ptr; - const volatile uint32_t *u32ptr; - const volatile int16_t *s16ptr; - const volatile uint16_t *u16ptr; - const volatile int8_t *s8ptr; - const volatile uint8_t *u8ptr; -} StructCVPtr; - -/** @} */ - -#endif /* #ifndef __ASSEMBLY__ */ - -/** \name Usual Constants - * @{ */ -#define DISABLE 0 -//#define ENABLE 1 - -#ifndef __cplusplus -# if !defined(__bool_true_false_are_defined) -# define false 0 -# define true 1 -# endif -#endif -/** @} */ - -#ifndef __ASSEMBLY__ - -/** \name Optimization Control - * @{ */ - -/** - * \def likely(exp) - * \brief The expression \a exp is likely to be true - */ -#if !defined(likely) || defined(__DOXYGEN__) -# define likely(exp) (exp) -#endif - -/** - * \def unlikely(exp) - * \brief The expression \a exp is unlikely to be true - */ -#if !defined(unlikely) || defined(__DOXYGEN__) -# define unlikely(exp) (exp) -#endif - -/** - * \def is_constant(exp) - * \brief Determine if an expression evaluates to a constant value. - * - * \param[in] exp Any expression - * - * \return true if \a exp is constant, false otherwise. - */ -#if (defined __GNUC__) || (defined __CC_ARM) -# define is_constant(exp) __builtin_constant_p(exp) -#else -# define is_constant(exp) (0) -#endif - -/** @} */ - -/** \name Bit-Field Handling - * @{ */ - -/** \brief Reads the bits of a value specified by a given bit-mask. - * - * \param[in] value Value to read bits from. - * \param[in] mask Bit-mask indicating bits to read. - * - * \return Read bits. - */ -#define Rd_bits( value, mask) ((value) & (mask)) - -/** \brief Writes the bits of a C lvalue specified by a given bit-mask. - * - * \param[in] lvalue C lvalue to write bits to. - * \param[in] mask Bit-mask indicating bits to write. - * \param[in] bits Bits to write. - * - * \return Resulting value with written bits. - */ -#define Wr_bits(lvalue, mask, bits) ((lvalue) = ((lvalue) & ~(mask)) |\ - ((bits ) & (mask))) - -/** \brief Tests the bits of a value specified by a given bit-mask. - * - * \param[in] value Value of which to test bits. - * \param[in] mask Bit-mask indicating bits to test. - * - * \return \c 1 if at least one of the tested bits is set, else \c 0. - */ -#define Tst_bits( value, mask) (Rd_bits(value, mask) != 0) - -/** \brief Clears the bits of a C lvalue specified by a given bit-mask. - * - * \param[in] lvalue C lvalue of which to clear bits. - * \param[in] mask Bit-mask indicating bits to clear. - * - * \return Resulting value with cleared bits. - */ -#define Clr_bits(lvalue, mask) ((lvalue) &= ~(mask)) - -/** \brief Sets the bits of a C lvalue specified by a given bit-mask. - * - * \param[in] lvalue C lvalue of which to set bits. - * \param[in] mask Bit-mask indicating bits to set. - * - * \return Resulting value with set bits. - */ -#define Set_bits(lvalue, mask) ((lvalue) |= (mask)) - -/** \brief Toggles the bits of a C lvalue specified by a given bit-mask. - * - * \param[in] lvalue C lvalue of which to toggle bits. - * \param[in] mask Bit-mask indicating bits to toggle. - * - * \return Resulting value with toggled bits. - */ -#define Tgl_bits(lvalue, mask) ((lvalue) ^= (mask)) - -/** \brief Reads the bit-field of a value specified by a given bit-mask. - * - * \param[in] value Value to read a bit-field from. - * \param[in] mask Bit-mask indicating the bit-field to read. - * - * \return Read bit-field. - */ -#define Rd_bitfield( value, mask) (Rd_bits( value, mask) >> ctz(mask)) - -/** \brief Writes the bit-field of a C lvalue specified by a given bit-mask. - * - * \param[in] lvalue C lvalue to write a bit-field to. - * \param[in] mask Bit-mask indicating the bit-field to write. - * \param[in] bitfield Bit-field to write. - * - * \return Resulting value with written bit-field. - */ -#define Wr_bitfield(lvalue, mask, bitfield) (Wr_bits(lvalue, mask, (uint32_t)(bitfield) << ctz(mask))) - -/** @} */ - - -/** \name Zero-Bit Counting - * - * Under GCC, __builtin_clz and __builtin_ctz behave like macros when - * applied to constant expressions (values known at compile time), so they are - * more optimized than the use of the corresponding assembly instructions and - * they can be used as constant expressions e.g. to initialize objects having - * static storage duration, and like the corresponding assembly instructions - * when applied to non-constant expressions (values unknown at compile time), so - * they are more optimized than an assembly periphrasis. Hence, clz and ctz - * ensure a possible and optimized behavior for both constant and non-constant - * expressions. - * - * @{ */ - -/** \brief Counts the leading zero bits of the given value considered as a 32-bit integer. - * - * \param[in] u Value of which to count the leading zero bits. - * - * \return The count of leading zero bits in \a u. - */ -#if (defined __GNUC__) || (defined __CC_ARM) -# define clz(u) __builtin_clz(u) -#else -# define clz(u) (((u) == 0) ? 32 : \ - ((u) & (1ul << 31)) ? 0 : \ - ((u) & (1ul << 30)) ? 1 : \ - ((u) & (1ul << 29)) ? 2 : \ - ((u) & (1ul << 28)) ? 3 : \ - ((u) & (1ul << 27)) ? 4 : \ - ((u) & (1ul << 26)) ? 5 : \ - ((u) & (1ul << 25)) ? 6 : \ - ((u) & (1ul << 24)) ? 7 : \ - ((u) & (1ul << 23)) ? 8 : \ - ((u) & (1ul << 22)) ? 9 : \ - ((u) & (1ul << 21)) ? 10 : \ - ((u) & (1ul << 20)) ? 11 : \ - ((u) & (1ul << 19)) ? 12 : \ - ((u) & (1ul << 18)) ? 13 : \ - ((u) & (1ul << 17)) ? 14 : \ - ((u) & (1ul << 16)) ? 15 : \ - ((u) & (1ul << 15)) ? 16 : \ - ((u) & (1ul << 14)) ? 17 : \ - ((u) & (1ul << 13)) ? 18 : \ - ((u) & (1ul << 12)) ? 19 : \ - ((u) & (1ul << 11)) ? 20 : \ - ((u) & (1ul << 10)) ? 21 : \ - ((u) & (1ul << 9)) ? 22 : \ - ((u) & (1ul << 8)) ? 23 : \ - ((u) & (1ul << 7)) ? 24 : \ - ((u) & (1ul << 6)) ? 25 : \ - ((u) & (1ul << 5)) ? 26 : \ - ((u) & (1ul << 4)) ? 27 : \ - ((u) & (1ul << 3)) ? 28 : \ - ((u) & (1ul << 2)) ? 29 : \ - ((u) & (1ul << 1)) ? 30 : \ - 31) -#endif - -/** \brief Counts the trailing zero bits of the given value considered as a 32-bit integer. - * - * \param[in] u Value of which to count the trailing zero bits. - * - * \return The count of trailing zero bits in \a u. - */ -#if (defined __GNUC__) || (defined __CC_ARM) -# define ctz(u) __builtin_ctz(u) -#else -# define ctz(u) ((u) & (1ul << 0) ? 0 : \ - (u) & (1ul << 1) ? 1 : \ - (u) & (1ul << 2) ? 2 : \ - (u) & (1ul << 3) ? 3 : \ - (u) & (1ul << 4) ? 4 : \ - (u) & (1ul << 5) ? 5 : \ - (u) & (1ul << 6) ? 6 : \ - (u) & (1ul << 7) ? 7 : \ - (u) & (1ul << 8) ? 8 : \ - (u) & (1ul << 9) ? 9 : \ - (u) & (1ul << 10) ? 10 : \ - (u) & (1ul << 11) ? 11 : \ - (u) & (1ul << 12) ? 12 : \ - (u) & (1ul << 13) ? 13 : \ - (u) & (1ul << 14) ? 14 : \ - (u) & (1ul << 15) ? 15 : \ - (u) & (1ul << 16) ? 16 : \ - (u) & (1ul << 17) ? 17 : \ - (u) & (1ul << 18) ? 18 : \ - (u) & (1ul << 19) ? 19 : \ - (u) & (1ul << 20) ? 20 : \ - (u) & (1ul << 21) ? 21 : \ - (u) & (1ul << 22) ? 22 : \ - (u) & (1ul << 23) ? 23 : \ - (u) & (1ul << 24) ? 24 : \ - (u) & (1ul << 25) ? 25 : \ - (u) & (1ul << 26) ? 26 : \ - (u) & (1ul << 27) ? 27 : \ - (u) & (1ul << 28) ? 28 : \ - (u) & (1ul << 29) ? 29 : \ - (u) & (1ul << 30) ? 30 : \ - (u) & (1ul << 31) ? 31 : \ - 32) -#endif - -/** @} */ - - -/** \name Bit Reversing - * @{ */ - -/** \brief Reverses the bits of \a u8. - * - * \param[in] u8 U8 of which to reverse the bits. - * - * \return Value resulting from \a u8 with reversed bits. - */ -#define bit_reverse8(u8) ((U8)(bit_reverse32((U8)(u8)) >> 24)) - -/** \brief Reverses the bits of \a u16. - * - * \param[in] u16 U16 of which to reverse the bits. - * - * \return Value resulting from \a u16 with reversed bits. - */ -#define bit_reverse16(u16) ((uint16_t)(bit_reverse32((uint16_t)(u16)) >> 16)) - -/** \brief Reverses the bits of \a u32. - * - * \param[in] u32 U32 of which to reverse the bits. - * - * \return Value resulting from \a u32 with reversed bits. - */ -#define bit_reverse32(u32) __RBIT(u32) - -/** \brief Reverses the bits of \a u64. - * - * \param[in] u64 U64 of which to reverse the bits. - * - * \return Value resulting from \a u64 with reversed bits. - */ -#define bit_reverse64(u64) ((uint64_t)(((uint64_t)bit_reverse32((uint64_t)(u64) >> 32)) |\ - ((uint64_t)bit_reverse32((uint64_t)(u64)) << 32))) - -/** @} */ - - -/** \name Alignment - * @{ */ - -/** \brief Tests alignment of the number \a val with the \a n boundary. - * - * \param[in] val Input value. - * \param[in] n Boundary. - * - * \return \c 1 if the number \a val is aligned with the \a n boundary, else \c 0. - */ -#define Test_align(val, n) (!Tst_bits( val, (n) - 1 ) ) - -/** \brief Gets alignment of the number \a val with respect to the \a n boundary. - * - * \param[in] val Input value. - * \param[in] n Boundary. - * - * \return Alignment of the number \a val with respect to the \a n boundary. - */ -#define Get_align(val, n) ( Rd_bits( val, (n) - 1 ) ) - -/** \brief Sets alignment of the lvalue number \a lval to \a alg with respect to the \a n boundary. - * - * \param[in] lval Input/output lvalue. - * \param[in] n Boundary. - * \param[in] alg Alignment. - * - * \return New value of \a lval resulting from its alignment set to \a alg with respect to the \a n boundary. - */ -#define Set_align(lval, n, alg) ( Wr_bits(lval, (n) - 1, alg) ) - -/** \brief Aligns the number \a val with the upper \a n boundary. - * - * \param[in] val Input value. - * \param[in] n Boundary. - * - * \return Value resulting from the number \a val aligned with the upper \a n boundary. - */ -#define Align_up( val, n) (((val) + ((n) - 1)) & ~((n) - 1)) - -/** \brief Aligns the number \a val with the lower \a n boundary. - * - * \param[in] val Input value. - * \param[in] n Boundary. - * - * \return Value resulting from the number \a val aligned with the lower \a n boundary. - */ -#define Align_down(val, n) ( (val) & ~((n) - 1)) - -/** @} */ - - -/** \name Mathematics - * - * The same considerations as for clz and ctz apply here but GCC does not - * provide built-in functions to access the assembly instructions abs, min and - * max and it does not produce them by itself in most cases, so two sets of - * macros are defined here: - * - Abs, Min and Max to apply to constant expressions (values known at - * compile time); - * - abs, min and max to apply to non-constant expressions (values unknown at - * compile time), abs is found in stdlib.h. - * - * @{ */ - -/** \brief Takes the absolute value of \a a. - * - * \param[in] a Input value. - * - * \return Absolute value of \a a. - * - * \note More optimized if only used with values known at compile time. - */ -#define Abs(a) (((a) < 0 ) ? -(a) : (a)) - -/** \brief Takes the minimal value of \a a and \a b. - * - * \param[in] a Input value. - * \param[in] b Input value. - * - * \return Minimal value of \a a and \a b. - * - * \note More optimized if only used with values known at compile time. - */ -#define Min(a, b) (((a) < (b)) ? (a) : (b)) - -/** \brief Takes the maximal value of \a a and \a b. - * - * \param[in] a Input value. - * \param[in] b Input value. - * - * \return Maximal value of \a a and \a b. - * - * \note More optimized if only used with values known at compile time. - */ -#define Max(a, b) (((a) > (b)) ? (a) : (b)) - -/** \brief Takes the minimal value of \a a and \a b. - * - * \param[in] a Input value. - * \param[in] b Input value. - * - * \return Minimal value of \a a and \a b. - * - * \note More optimized if only used with values unknown at compile time. - */ -#define min(a, b) Min(a, b) - -/** \brief Takes the maximal value of \a a and \a b. - * - * \param[in] a Input value. - * \param[in] b Input value. - * - * \return Maximal value of \a a and \a b. - * - * \note More optimized if only used with values unknown at compile time. - */ -#define max(a, b) Max(a, b) - -/** @} */ - - -/** \brief Calls the routine at address \a addr. - * - * It generates a long call opcode. - * - * For example, `Long_call(0x80000000)' generates a software reset on a UC3 if - * it is invoked from the CPU supervisor mode. - * - * \param[in] addr Address of the routine to call. - * - * \note It may be used as a long jump opcode in some special cases. - */ -#define Long_call(addr) ((*(void (*)(void))(addr))()) - - -/** \name MCU Endianism Handling - * ARM is MCU little endian. - * - * @{ */ -#define BE16(x) Swap16(x) -#define LE16(x) (x) - -#define le16_to_cpu(x) (x) -#define cpu_to_le16(x) (x) -#define LE16_TO_CPU(x) (x) -#define CPU_TO_LE16(x) (x) - -#define be16_to_cpu(x) Swap16(x) -#define cpu_to_be16(x) Swap16(x) -#define BE16_TO_CPU(x) Swap16(x) -#define CPU_TO_BE16(x) Swap16(x) - -#define le32_to_cpu(x) (x) -#define cpu_to_le32(x) (x) -#define LE32_TO_CPU(x) (x) -#define CPU_TO_LE32(x) (x) - -#define be32_to_cpu(x) swap32(x) -#define cpu_to_be32(x) swap32(x) -#define BE32_TO_CPU(x) swap32(x) -#define CPU_TO_BE32(x) swap32(x) -/** @} */ - - -/** \name Endianism Conversion - * - * The same considerations as for clz and ctz apply here but GCC's - * __builtin_bswap_32 and __builtin_bswap_64 do not behave like macros when - * applied to constant expressions, so two sets of macros are defined here: - * - Swap16, Swap32 and Swap64 to apply to constant expressions (values known - * at compile time); - * - swap16, swap32 and swap64 to apply to non-constant expressions (values - * unknown at compile time). - * - * @{ */ - -/** \brief Toggles the endianism of \a u16 (by swapping its bytes). - * - * \param[in] u16 U16 of which to toggle the endianism. - * - * \return Value resulting from \a u16 with toggled endianism. - * - * \note More optimized if only used with values known at compile time. - */ -#define Swap16(u16) ((uint16_t)(((uint16_t)(u16) >> 8) |\ - ((uint16_t)(u16) << 8))) - -/** \brief Toggles the endianism of \a u32 (by swapping its bytes). - * - * \param[in] u32 U32 of which to toggle the endianism. - * - * \return Value resulting from \a u32 with toggled endianism. - * - * \note More optimized if only used with values known at compile time. - */ -#define Swap32(u32) ((uint32_t)(((uint32_t)Swap16((uint32_t)(u32) >> 16)) |\ - ((uint32_t)Swap16((uint32_t)(u32)) << 16))) - -/** \brief Toggles the endianism of \a u64 (by swapping its bytes). - * - * \param[in] u64 U64 of which to toggle the endianism. - * - * \return Value resulting from \a u64 with toggled endianism. - * - * \note More optimized if only used with values known at compile time. - */ -#define Swap64(u64) ((uint64_t)(((uint64_t)Swap32((uint64_t)(u64) >> 32)) |\ - ((uint64_t)Swap32((uint64_t)(u64)) << 32))) - -/** \brief Toggles the endianism of \a u16 (by swapping its bytes). - * - * \param[in] u16 U16 of which to toggle the endianism. - * - * \return Value resulting from \a u16 with toggled endianism. - * - * \note More optimized if only used with values unknown at compile time. - */ -#define swap16(u16) Swap16(u16) - -/** \brief Toggles the endianism of \a u32 (by swapping its bytes). - * - * \param[in] u32 U32 of which to toggle the endianism. - * - * \return Value resulting from \a u32 with toggled endianism. - * - * \note More optimized if only used with values unknown at compile time. - */ -#if (defined __GNUC__) -# define swap32(u32) ((uint32_t)__builtin_bswap32((uint32_t)(u32))) -#else -# define swap32(u32) Swap32(u32) -#endif - -/** \brief Toggles the endianism of \a u64 (by swapping its bytes). - * - * \param[in] u64 U64 of which to toggle the endianism. - * - * \return Value resulting from \a u64 with toggled endianism. - * - * \note More optimized if only used with values unknown at compile time. - */ -#if (defined __GNUC__) -# define swap64(u64) ((uint64_t)__builtin_bswap64((uint64_t)(u64))) -#else -# define swap64(u64) ((uint64_t)(((uint64_t)swap32((uint64_t)(u64) >> 32)) |\ - ((uint64_t)swap32((uint64_t)(u64)) << 32))) -#endif - -/** @} */ - - -/** \name Target Abstraction - * - * @{ */ - -#define _GLOBEXT_ extern /**< extern storage-class specifier. */ -#define _CONST_TYPE_ const /**< const type qualifier. */ -#define _MEM_TYPE_SLOW_ /**< Slow memory type. */ -#define _MEM_TYPE_MEDFAST_ /**< Fairly fast memory type. */ -#define _MEM_TYPE_FAST_ /**< Fast memory type. */ - -#define memcmp_ram2ram memcmp /**< Target-specific memcmp of RAM to RAM. */ -#define memcmp_code2ram memcmp /**< Target-specific memcmp of RAM to NVRAM. */ -#define memcpy_ram2ram memcpy /**< Target-specific memcpy from RAM to RAM. */ -#define memcpy_code2ram memcpy /**< Target-specific memcpy from NVRAM to RAM. */ - -/** @} */ - -/** - * \brief Calculate \f$ \left\lceil \frac{a}{b} \right\rceil \f$ using - * integer arithmetic. - * - * \param[in] a An integer - * \param[in] b Another integer - * - * \return (\a a / \a b) rounded up to the nearest integer. - */ -#define div_ceil(a, b) (((a) + (b) - 1) / (b)) - -#endif /* #ifndef __ASSEMBLY__ */ -#ifdef __ICCARM__ -/** \name Compiler Keywords - * - * Port of some keywords from GCC to IAR Embedded Workbench. - * - * @{ */ - -#define __asm__ asm -#define __inline__ inline -#define __volatile__ - -/** @} */ - -#endif - -#define FUNC_PTR void * -/** - * \def unused - * \brief Marking \a v as a unused parameter or value. - */ -#define unused(v) do { (void)(v); } while(0) - -/* Define RAMFUNC attribute */ -#if defined ( __CC_ARM ) /* Keil uVision 4 */ -# define RAMFUNC __attribute__ ((section(".ramfunc"))) -#elif defined ( __ICCARM__ ) /* IAR Ewarm 5.41+ */ -# define RAMFUNC __ramfunc -#elif defined ( __GNUC__ ) /* GCC CS3 2009q3-68 */ -# define RAMFUNC __attribute__ ((section(".ramfunc"))) -#endif - -/* Define OPTIMIZE_HIGH attribute */ -#if defined ( __CC_ARM ) /* Keil uVision 4 */ -# define OPTIMIZE_HIGH _Pragma("O3") -#elif defined ( __ICCARM__ ) /* IAR Ewarm 5.41+ */ -# define OPTIMIZE_HIGH _Pragma("optimize=high") -#elif defined ( __GNUC__ ) /* GCC CS3 2009q3-68 */ -# define OPTIMIZE_HIGH __attribute__((optimize(s))) -#endif -#define PASS 0 -#define FAIL 1 -#define LOW 0 -#define HIGH 1 - -typedef int8_t S8 ; //!< 8-bit signed integer. -typedef uint8_t U8 ; //!< 8-bit unsigned integer. -typedef int16_t S16; //!< 16-bit signed integer. -typedef uint16_t U16; //!< 16-bit unsigned integer. -typedef int32_t S32; //!< 32-bit signed integer. -typedef uint32_t U32; //!< 32-bit unsigned integer. -typedef int64_t S64; //!< 64-bit signed integer. -typedef uint64_t U64; //!< 64-bit unsigned integer. -typedef float F32; //!< 32-bit floating-point number. -typedef double F64; //!< 64-bit floating-point number. - -#define MSB(u16) (((U8 *)&(u16))[1]) //!< Most significant byte of \a u16. -#define LSB(u16) (((U8 *)&(u16))[0]) //!< Least significant byte of \a u16. - -#define MSH(u32) (((U16 *)&(u32))[1]) //!< Most significant half-word of \a u32. -#define LSH(u32) (((U16 *)&(u32))[0]) //!< Least significant half-word of \a u32. -#define MSB0W(u32) (((U8 *)&(u32))[3]) //!< Most significant byte of 1st rank of \a u32. -#define MSB1W(u32) (((U8 *)&(u32))[2]) //!< Most significant byte of 2nd rank of \a u32. -#define MSB2W(u32) (((U8 *)&(u32))[1]) //!< Most significant byte of 3rd rank of \a u32. -#define MSB3W(u32) (((U8 *)&(u32))[0]) //!< Most significant byte of 4th rank of \a u32. -#define LSB3W(u32) MSB0W(u32) //!< Least significant byte of 4th rank of \a u32. -#define LSB2W(u32) MSB1W(u32) //!< Least significant byte of 3rd rank of \a u32. -#define LSB1W(u32) MSB2W(u32) //!< Least significant byte of 2nd rank of \a u32. -#define LSB0W(u32) MSB3W(u32) //!< Least significant byte of 1st rank of \a u32. - -#define MSW(u64) (((U32 *)&(u64))[1]) //!< Most significant word of \a u64. -#define LSW(u64) (((U32 *)&(u64))[0]) //!< Least significant word of \a u64. -#define MSH0(u64) (((U16 *)&(u64))[3]) //!< Most significant half-word of 1st rank of \a u64. -#define MSH1(u64) (((U16 *)&(u64))[2]) //!< Most significant half-word of 2nd rank of \a u64. -#define MSH2(u64) (((U16 *)&(u64))[1]) //!< Most significant half-word of 3rd rank of \a u64. -#define MSH3(u64) (((U16 *)&(u64))[0]) //!< Most significant half-word of 4th rank of \a u64. -#define LSH3(u64) MSH0(u64) //!< Least significant half-word of 4th rank of \a u64. -#define LSH2(u64) MSH1(u64) //!< Least significant half-word of 3rd rank of \a u64. -#define LSH1(u64) MSH2(u64) //!< Least significant half-word of 2nd rank of \a u64. -#define LSH0(u64) MSH3(u64) //!< Least significant half-word of 1st rank of \a u64. -#define MSB0D(u64) (((U8 *)&(u64))[7]) //!< Most significant byte of 1st rank of \a u64. -#define MSB1D(u64) (((U8 *)&(u64))[6]) //!< Most significant byte of 2nd rank of \a u64. -#define MSB2D(u64) (((U8 *)&(u64))[5]) //!< Most significant byte of 3rd rank of \a u64. -#define MSB3D(u64) (((U8 *)&(u64))[4]) //!< Most significant byte of 4th rank of \a u64. -#define MSB4D(u64) (((U8 *)&(u64))[3]) //!< Most significant byte of 5th rank of \a u64. -#define MSB5D(u64) (((U8 *)&(u64))[2]) //!< Most significant byte of 6th rank of \a u64. -#define MSB6D(u64) (((U8 *)&(u64))[1]) //!< Most significant byte of 7th rank of \a u64. -#define MSB7D(u64) (((U8 *)&(u64))[0]) //!< Most significant byte of 8th rank of \a u64. -#define LSB7D(u64) MSB0D(u64) //!< Least significant byte of 8th rank of \a u64. -#define LSB6D(u64) MSB1D(u64) //!< Least significant byte of 7th rank of \a u64. -#define LSB5D(u64) MSB2D(u64) //!< Least significant byte of 6th rank of \a u64. -#define LSB4D(u64) MSB3D(u64) //!< Least significant byte of 5th rank of \a u64. -#define LSB3D(u64) MSB4D(u64) //!< Least significant byte of 4th rank of \a u64. -#define LSB2D(u64) MSB5D(u64) //!< Least significant byte of 3rd rank of \a u64. -#define LSB1D(u64) MSB6D(u64) //!< Least significant byte of 2nd rank of \a u64. -#define LSB0D(u64) MSB7D(u64) //!< Least significant byte of 1st rank of \a u64. - -#define LSB0(u32) LSB0W(u32) //!< Least significant byte of 1st rank of \a u32. -#define LSB1(u32) LSB1W(u32) //!< Least significant byte of 2nd rank of \a u32. -#define LSB2(u32) LSB2W(u32) //!< Least significant byte of 3rd rank of \a u32. -#define LSB3(u32) LSB3W(u32) //!< Least significant byte of 4th rank of \a u32. -#define MSB3(u32) MSB3W(u32) //!< Most significant byte of 4th rank of \a u32. -#define MSB2(u32) MSB2W(u32) //!< Most significant byte of 3rd rank of \a u32. -#define MSB1(u32) MSB1W(u32) //!< Most significant byte of 2nd rank of \a u32. -#define MSB0(u32) MSB0W(u32) //!< Most significant byte of 1st rank of \a u32. - -#if defined(__ICCARM__) -#define SHORTENUM __packed -#elif defined(__GNUC__) -#define SHORTENUM __attribute__((packed)) -#endif - -/* No operation */ -#if defined(__ICCARM__) -#define nop() __no_operation() -#elif defined(__GNUC__) -#define nop() (__NOP()) -#endif - -#define FLASH_DECLARE(x) const x -#define FLASH_EXTERN(x) extern const x -#define PGM_READ_BYTE(x) *(x) -#define PGM_READ_WORD(x) *(x) -#define MEMCPY_ENDIAN memcpy -#define PGM_READ_BLOCK(dst, src, len) memcpy((dst), (src), (len)) - -/*Defines the Flash Storage for the request and response of MAC*/ -#define CMD_ID_OCTET (0) - -/* Converting of values from CPU endian to little endian. */ -#define CPU_ENDIAN_TO_LE16(x) (x) -#define CPU_ENDIAN_TO_LE32(x) (x) -#define CPU_ENDIAN_TO_LE64(x) (x) - -/* Converting of values from little endian to CPU endian. */ -#define LE16_TO_CPU_ENDIAN(x) (x) -#define LE32_TO_CPU_ENDIAN(x) (x) -#define LE64_TO_CPU_ENDIAN(x) (x) - -/* Converting of constants from little endian to CPU endian. */ -#define CLE16_TO_CPU_ENDIAN(x) (x) -#define CLE32_TO_CPU_ENDIAN(x) (x) -#define CLE64_TO_CPU_ENDIAN(x) (x) - -/* Converting of constants from CPU endian to little endian. */ -#define CCPU_ENDIAN_TO_LE16(x) (x) -#define CCPU_ENDIAN_TO_LE32(x) (x) -#define CCPU_ENDIAN_TO_LE64(x) (x) - -#define ADDR_COPY_DST_SRC_16(dst, src) ((dst) = (src)) -#define ADDR_COPY_DST_SRC_64(dst, src) ((dst) = (src)) - -/** - * @brief Converts a 64-Bit value into a 8 Byte array - * - * @param[in] value 64-Bit value - * @param[out] data Pointer to the 8 Byte array to be updated with 64-Bit value - * @ingroup apiPalApi - */ -static inline void convert_64_bit_to_byte_array(uint64_t value, uint8_t *data) -{ - uint8_t index = 0; - - while (index < 8) - { - data[index++] = value & 0xFF; - value = value >> 8; - } -} - -/** - * @brief Converts a 16-Bit value into a 2 Byte array - * - * @param[in] value 16-Bit value - * @param[out] data Pointer to the 2 Byte array to be updated with 16-Bit value - * @ingroup apiPalApi - */ -static inline void convert_16_bit_to_byte_array(uint16_t value, uint8_t *data) -{ - data[0] = value & 0xFF; - data[1] = (value >> 8) & 0xFF; -} - -/* Converts a 16-Bit value into a 2 Byte array */ -static inline void convert_spec_16_bit_to_byte_array(uint16_t value, uint8_t *data) -{ - data[0] = value & 0xFF; - data[1] = (value >> 8) & 0xFF; -} - -/* Converts a 16-Bit value into a 2 Byte array */ -static inline void convert_16_bit_to_byte_address(uint16_t value, uint8_t *data) -{ - data[0] = value & 0xFF; - data[1] = (value >> 8) & 0xFF; -} - -/* - * @brief Converts a 2 Byte array into a 16-Bit value - * - * @param data Specifies the pointer to the 2 Byte array - * - * @return 16-Bit value - * @ingroup apiPalApi - */ -static inline uint16_t convert_byte_array_to_16_bit(uint8_t *data) -{ - return (data[0] | ((uint16_t)data[1] << 8)); -} - -/* Converts a 4 Byte array into a 32-Bit value */ -static inline uint32_t convert_byte_array_to_32_bit(uint8_t *data) -{ - union - { - uint32_t u32; - uint8_t u8[4]; - }long_addr; - uint8_t index; - for (index = 0; index < 4; index++) - { - long_addr.u8[index] = *data++; - } - return long_addr.u32; -} - -/** - * @brief Converts a 8 Byte array into a 64-Bit value - * - * @param data Specifies the pointer to the 8 Byte array - * - * @return 64-Bit value - * @ingroup apiPalApi - */ -static inline uint64_t convert_byte_array_to_64_bit(uint8_t *data) -{ - union - { - uint64_t u64; - uint8_t u8[8]; - } long_addr; - - uint8_t index; - - for (index = 0; index < 8; index++) - { - long_addr.u8[index] = *data++; - } - - return long_addr.u64; -} - -/** @} */ - -#endif /* UTILS_COMPILER_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/gclk.c b/feather_sensor_transmit/libraries/Adafruit_ASFcore/gclk.c deleted file mode 100644 index 1199a19..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/gclk.c +++ /dev/null @@ -1,522 +0,0 @@ -/** - * \file - * - * \brief SAM D21/R21/DA0/DA1 Generic Clock Driver - * - * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#include -#include -#include - -/** - * \brief Determines if the hardware module(s) are currently synchronizing to the bus. - * - * Checks to see if the underlying hardware peripheral module(s) are currently - * synchronizing across multiple clock domains to the hardware bus, This - * function can be used to delay further operations on a module until such time - * that it is ready, to prevent blocking delays for synchronization in the - * user application. - * - * \return Synchronization status of the underlying hardware module(s). - * - * \retval false if the module has completed synchronization - * \retval true if the module synchronization is ongoing - */ -static inline bool system_gclk_is_syncing(void) -{ - if (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY){ - return true; - } - - return false; -} - -/** - * \brief Initializes the GCLK driver. - * - * Initializes the Generic Clock module, disabling and resetting all active - * Generic Clock Generators and Channels to their power-on default values. - */ -void system_gclk_init(void) -{ - /* Turn on the digital interface clock */ - system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBA, PM_APBAMASK_GCLK); - - /* Software reset the module to ensure it is re-initialized correctly */ - GCLK->CTRL.reg = GCLK_CTRL_SWRST; - while (GCLK->CTRL.reg & GCLK_CTRL_SWRST) { - /* Wait for reset to complete */ - } -} - -/** - * \brief Writes a Generic Clock Generator configuration to the hardware module. - * - * Writes out a given configuration of a Generic Clock Generator configuration - * to the hardware module. - * - * \note Changing the clock source on the fly (on a running - * generator) can take additional time if the clock source is configured - * to only run on-demand (ONDEMAND bit is set) and it is not currently - * running (no peripheral is requesting the clock source). In this case - * the GCLK will request the new clock while still keeping a request to - * the old clock source until the new clock source is ready. - * - * \note This function will not start a generator that is not already running; - * to start the generator, call \ref system_gclk_gen_enable() - * after configuring a generator. - * - * \param[in] generator Generic Clock Generator index to configure - * \param[in] config Configuration settings for the generator - */ -void system_gclk_gen_set_config( - const uint8_t generator, - struct system_gclk_gen_config *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Cache new register configurations to minimize sync requirements. */ - uint32_t new_genctrl_config = (generator << GCLK_GENCTRL_ID_Pos); - uint32_t new_gendiv_config = (generator << GCLK_GENDIV_ID_Pos); - - /* Select the requested source clock for the generator */ - new_genctrl_config |= config->source_clock << GCLK_GENCTRL_SRC_Pos; - - /* Configure the clock to be either high or low when disabled */ - if (config->high_when_disabled) { - new_genctrl_config |= GCLK_GENCTRL_OOV; - } - - /* Configure if the clock output to I/O pin should be enabled. */ - if (config->output_enable) { - new_genctrl_config |= GCLK_GENCTRL_OE; - } - - /* Set division factor */ - if (config->division_factor > 1) { - /* Check if division is a power of two */ - if (((config->division_factor & (config->division_factor - 1)) == 0)) { - /* Determine the index of the highest bit set to get the - * division factor that must be loaded into the division - * register */ - - uint32_t div2_count = 0; - - uint32_t mask; - for (mask = (1UL << 1); mask < config->division_factor; - mask <<= 1) { - div2_count++; - } - - /* Set binary divider power of 2 division factor */ - new_gendiv_config |= div2_count << GCLK_GENDIV_DIV_Pos; - new_genctrl_config |= GCLK_GENCTRL_DIVSEL; - } else { - /* Set integer division factor */ - - new_gendiv_config |= - (config->division_factor) << GCLK_GENDIV_DIV_Pos; - - /* Enable non-binary division with increased duty cycle accuracy */ - new_genctrl_config |= GCLK_GENCTRL_IDC; - } - - } - - /* Enable or disable the clock in standby mode */ - if (config->run_in_standby) { - new_genctrl_config |= GCLK_GENCTRL_RUNSTDBY; - } - - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - system_interrupt_enter_critical_section(); - - /* Select the correct generator */ - *((uint8_t*)&GCLK->GENDIV.reg) = generator; - - /* Write the new generator configuration */ - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - GCLK->GENDIV.reg = new_gendiv_config; - - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - GCLK->GENCTRL.reg = new_genctrl_config | (GCLK->GENCTRL.reg & GCLK_GENCTRL_GENEN); - - system_interrupt_leave_critical_section(); -} - -/** - * \brief Enables a Generic Clock Generator that was previously configured. - * - * Starts the clock generation of a Generic Clock Generator that was previously - * configured via a call to \ref system_gclk_gen_set_config(). - * - * \param[in] generator Generic Clock Generator index to enable - */ -void system_gclk_gen_enable( - const uint8_t generator) -{ - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - system_interrupt_enter_critical_section(); - - /* Select the requested generator */ - *((uint8_t*)&GCLK->GENCTRL.reg) = generator; - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - /* Enable generator */ - GCLK->GENCTRL.reg |= GCLK_GENCTRL_GENEN; - - system_interrupt_leave_critical_section(); -} - -/** - * \brief Disables a Generic Clock Generator that was previously enabled. - * - * Stops the clock generation of a Generic Clock Generator that was previously - * started via a call to \ref system_gclk_gen_enable(). - * - * \param[in] generator Generic Clock Generator index to disable - */ -void system_gclk_gen_disable( - const uint8_t generator) -{ - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - system_interrupt_enter_critical_section(); - - /* Select the requested generator */ - *((uint8_t*)&GCLK->GENCTRL.reg) = generator; - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - /* Disable generator */ - GCLK->GENCTRL.reg &= ~GCLK_GENCTRL_GENEN; - while (GCLK->GENCTRL.reg & GCLK_GENCTRL_GENEN) { - /* Wait for clock to become disabled */ - } - - system_interrupt_leave_critical_section(); -} - -/** - * \brief Determins if the specified Generic Clock Generator is enabled. - * - * \param[in] generator Generic Clock Generator index to check - * - * \return The enabled status. - * \retval true The Generic Clock Generator is enabled - * \retval false The Generic Clock Generator is disabled - */ -bool system_gclk_gen_is_enabled( - const uint8_t generator) -{ - bool enabled; - - system_interrupt_enter_critical_section(); - - /* Select the requested generator */ - *((uint8_t*)&GCLK->GENCTRL.reg) = generator; - /* Obtain the enabled status */ - enabled = (GCLK->GENCTRL.reg & GCLK_GENCTRL_GENEN); - - system_interrupt_leave_critical_section(); - - return enabled; -} - -/** - * \brief Retrieves the clock frequency of a Generic Clock generator. - * - * Determines the clock frequency (in Hz) of a specified Generic Clock - * generator, used as a source to a Generic Clock Channel module. - * - * \param[in] generator Generic Clock Generator index - * - * \return The frequency of the generic clock generator, in Hz. - */ -uint32_t system_gclk_gen_get_hz( - const uint8_t generator) -{ - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - system_interrupt_enter_critical_section(); - - /* Select the appropriate generator */ - *((uint8_t*)&GCLK->GENCTRL.reg) = generator; - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - /* Get the frequency of the source connected to the GCLK generator */ - uint32_t gen_input_hz = system_clock_source_get_hz( - (enum system_clock_source)GCLK->GENCTRL.bit.SRC); - - *((uint8_t*)&GCLK->GENCTRL.reg) = generator; - - uint8_t divsel = GCLK->GENCTRL.bit.DIVSEL; - - /* Select the appropriate generator division register */ - *((uint8_t*)&GCLK->GENDIV.reg) = generator; - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - uint32_t divider = GCLK->GENDIV.bit.DIV; - - system_interrupt_leave_critical_section(); - - /* Check if the generator is using fractional or binary division */ - if (!divsel && divider > 1) { - gen_input_hz /= divider; - } else if (divsel) { - gen_input_hz >>= (divider+1); - } - - return gen_input_hz; -} - -/** - * \brief Writes a Generic Clock configuration to the hardware module. - * - * Writes out a given configuration of a Generic Clock configuration to the - * hardware module. If the clock is currently running, it will be stopped. - * - * \note Once called the clock will not be running; to start the clock, - * call \ref system_gclk_chan_enable() after configuring a clock channel. - * - * \param[in] channel Generic Clock channel to configure - * \param[in] config Configuration settings for the clock - * - */ -void system_gclk_chan_set_config( - const uint8_t channel, - struct system_gclk_chan_config *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Cache the new config to reduce sync requirements */ - uint32_t new_clkctrl_config = (channel << GCLK_CLKCTRL_ID_Pos); - - /* Select the desired generic clock generator */ - new_clkctrl_config |= config->source_generator << GCLK_CLKCTRL_GEN_Pos; - - /* Disable generic clock channel */ - system_gclk_chan_disable(channel); - - /* Write the new configuration */ - GCLK->CLKCTRL.reg = new_clkctrl_config; -} - -/** - * \brief Enables a Generic Clock that was previously configured. - * - * Starts the clock generation of a Generic Clock that was previously - * configured via a call to \ref system_gclk_chan_set_config(). - * - * \param[in] channel Generic Clock channel to enable - */ -void system_gclk_chan_enable( - const uint8_t channel) -{ - system_interrupt_enter_critical_section(); - - /* Select the requested generator channel */ - *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; - - /* Enable the generic clock */ - GCLK->CLKCTRL.reg |= GCLK_CLKCTRL_CLKEN; - - system_interrupt_leave_critical_section(); -} - -/** - * \brief Disables a Generic Clock that was previously enabled. - * - * Stops the clock generation of a Generic Clock that was previously started - * via a call to \ref system_gclk_chan_enable(). - * - * \param[in] channel Generic Clock channel to disable - */ -void system_gclk_chan_disable( - const uint8_t channel) -{ - system_interrupt_enter_critical_section(); - - /* Select the requested generator channel */ - *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; - - /* Sanity check WRTLOCK */ - Assert(!GCLK->CLKCTRL.bit.WRTLOCK); - - /* Switch to known-working source so that the channel can be disabled */ - uint32_t prev_gen_id = GCLK->CLKCTRL.bit.GEN; - GCLK->CLKCTRL.bit.GEN = 0; - - /* Disable the generic clock */ - GCLK->CLKCTRL.reg &= ~GCLK_CLKCTRL_CLKEN; - while (GCLK->CLKCTRL.reg & GCLK_CLKCTRL_CLKEN) { - /* Wait for clock to become disabled */ - } - - /* Restore previous configured clock generator */ - GCLK->CLKCTRL.bit.GEN = prev_gen_id; - - system_interrupt_leave_critical_section(); -} - -/** - * \brief Determins if the specified Generic Clock channel is enabled. - * - * \param[in] channel Generic Clock Channel index - * - * \return The enabled status. - * \retval true The Generic Clock channel is enabled - * \retval false The Generic Clock channel is disabled - */ -bool system_gclk_chan_is_enabled( - const uint8_t channel) -{ - bool enabled; - - system_interrupt_enter_critical_section(); - - /* Select the requested generic clock channel */ - *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; - enabled = GCLK->CLKCTRL.bit.CLKEN; - - system_interrupt_leave_critical_section(); - - return enabled; -} - -/** - * \brief Locks a Generic Clock channel from further configuration writes. - * - * Locks a generic clock channel from further configuration writes. It is only - * possible to unlock the channel configuration through a power on reset. - * - * \param[in] channel Generic Clock channel to enable - */ -void system_gclk_chan_lock( - const uint8_t channel) -{ - system_interrupt_enter_critical_section(); - - /* Select the requested generator channel */ - *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; - - /* Lock the generic clock */ - GCLK->CLKCTRL.reg |= GCLK_CLKCTRL_WRTLOCK; - - system_interrupt_leave_critical_section(); -} - -/** - * \brief Determins if the specified Generic Clock channel is locked. - * - * \param[in] channel Generic Clock Channel index - * - * \return The lock status. - * \retval true The Generic Clock channel is locked - * \retval false The Generic Clock channel is not locked - */ -bool system_gclk_chan_is_locked( - const uint8_t channel) -{ - bool locked; - - system_interrupt_enter_critical_section(); - - /* Select the requested generic clock channel */ - *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; - locked = GCLK->CLKCTRL.bit.WRTLOCK; - - system_interrupt_leave_critical_section(); - - return locked; -} - -/** - * \brief Retrieves the clock frequency of a Generic Clock channel. - * - * Determines the clock frequency (in Hz) of a specified Generic Clock - * channel, used as a source to a device peripheral module. - * - * \param[in] channel Generic Clock Channel index - * - * \return The frequency of the generic clock channel, in Hz. - */ -uint32_t system_gclk_chan_get_hz( - const uint8_t channel) -{ - uint8_t gen_id; - - system_interrupt_enter_critical_section(); - - /* Select the requested generic clock channel */ - *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; - gen_id = GCLK->CLKCTRL.bit.GEN; - - system_interrupt_leave_critical_section(); - - /* Return the clock speed of the associated GCLK generator */ - return system_gclk_gen_get_hz(gen_id); -} diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/gclk.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/gclk.h deleted file mode 100644 index 1e3caf3..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/gclk.h +++ /dev/null @@ -1,307 +0,0 @@ -/** - * \file - * - * \brief SAM Generic Clock Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef SYSTEM_CLOCK_GCLK_H_INCLUDED -#define SYSTEM_CLOCK_GCLK_H_INCLUDED - -/** - * \addtogroup asfdoc_sam0_system_clock_group - * - * @{ - */ - -#include "compiler.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief List of available GCLK generators. - * - * List of Available GCLK generators. This enum is used in the peripheral - * device drivers to select the GCLK generator to be used for its operation. - * - * The number of GCLK generators available is device dependent. - */ -enum gclk_generator { - /** GCLK generator channel 0 */ - GCLK_GENERATOR_0, -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 0) - /** GCLK generator channel 1 */ - GCLK_GENERATOR_1, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 1) - /** GCLK generator channel 2 */ - GCLK_GENERATOR_2, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 2) - /** GCLK generator channel 3 */ - GCLK_GENERATOR_3, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 3) - /** GCLK generator channel 4 */ - GCLK_GENERATOR_4, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 4) - /** GCLK generator channel 5 */ - GCLK_GENERATOR_5, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 5) - /** GCLK generator channel 6 */ - GCLK_GENERATOR_6, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 6) - /** GCLK generator channel 7 */ - GCLK_GENERATOR_7, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 7) - /** GCLK generator channel 8 */ - GCLK_GENERATOR_8, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 8) - /** GCLK generator channel 9 */ - GCLK_GENERATOR_9, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 9) - /** GCLK generator channel 10 */ - GCLK_GENERATOR_10, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 10) - /** GCLK generator channel 11 */ - GCLK_GENERATOR_11, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 11) - /** GCLK generator channel 12 */ - GCLK_GENERATOR_12, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 12) - /** GCLK generator channel 13 */ - GCLK_GENERATOR_13, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 13) - /** GCLK generator channel 14 */ - GCLK_GENERATOR_14, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 14) - /** GCLK generator channel 15 */ - GCLK_GENERATOR_15, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 15) - /** GCLK generator channel 16 */ - GCLK_GENERATOR_16, -#endif -}; - -/** - * \brief Generic Clock Generator configuration structure. - * - * Configuration structure for a Generic Clock Generator channel. This - * structure should be initialized by the - * \ref system_gclk_gen_get_config_defaults() function before being modified by - * the user application. - */ -struct system_gclk_gen_config { - /** Source clock input channel index, see the \ref system_clock_source */ - uint8_t source_clock; - /** If \c true, the generator output level is high when disabled */ - bool high_when_disabled; - /** Integer division factor of the clock output compared to the input */ - uint32_t division_factor; - /** If \c true, the clock is kept enabled during device standby mode */ - bool run_in_standby; - /** If \c true, enables GCLK generator clock output to a GPIO pin */ - bool output_enable; -}; - -/** - * \brief Generic Clock configuration structure. - * - * Configuration structure for a Generic Clock channel. This structure - * should be initialized by the \ref system_gclk_chan_get_config_defaults() - * function before being modified by the user application. - */ -struct system_gclk_chan_config { - /** Generic Clock Generator source channel */ - enum gclk_generator source_generator; -}; - -/** \name Generic Clock Management - * @{ - */ -void system_gclk_init(void); - -/** @} */ - - -/** - * \name Generic Clock Management (Generators) - * @{ - */ - -/** - * \brief Initializes a Generic Clock Generator configuration structure to defaults. - * - * Initializes a given Generic Clock Generator configuration structure to - * a set of known default values. This function should be called on all - * new instances of these configuration structures before being modified - * by the user application. - * - * The default configuration is: - * \li Clock is generated undivided from the source frequency - * \li Clock generator output is low when the generator is disabled - * \li The input clock is sourced from input clock channel 0 - * \li Clock will be disabled during sleep - * \li The clock output will not be routed to a physical GPIO pin - * - * \param[out] config Configuration structure to initialize to default values - */ -static inline void system_gclk_gen_get_config_defaults( - struct system_gclk_gen_config *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Default configuration values */ - config->division_factor = 1; - config->high_when_disabled = false; -#if SAML21 || SAML22 - config->source_clock = GCLK_SOURCE_OSC16M; -#elif (SAMC20) || (SAMC21) - config->source_clock = GCLK_SOURCE_OSC48M; -#else - config->source_clock = GCLK_SOURCE_OSC8M; -#endif - config->run_in_standby = false; - config->output_enable = false; -} - -void system_gclk_gen_set_config( - const uint8_t generator, - struct system_gclk_gen_config *const config); - -void system_gclk_gen_enable( - const uint8_t generator); - -void system_gclk_gen_disable( - const uint8_t generator); - -bool system_gclk_gen_is_enabled( - const uint8_t generator); - -/** @} */ - - -/** - * \name Generic Clock Management (Channels) - * @{ - */ - -/** - * \brief Initializes a Generic Clock configuration structure to defaults. - * - * Initializes a given Generic Clock configuration structure to a set of - * known default values. This function should be called on all new - * instances of these configuration structures before being modified by the - * user application. - * - * The default configuration is as follows: - * \li Clock is sourced from the Generic Clock Generator channel 0 - * \li Clock configuration will not be write-locked when set - * - * \param[out] config Configuration structure to initialize to default values - */ -static inline void system_gclk_chan_get_config_defaults( - struct system_gclk_chan_config *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Default configuration values */ - config->source_generator = GCLK_GENERATOR_0; -} - -void system_gclk_chan_set_config( - const uint8_t channel, - struct system_gclk_chan_config *const config); - -void system_gclk_chan_enable( - const uint8_t channel); - -void system_gclk_chan_disable( - const uint8_t channel); - -bool system_gclk_chan_is_enabled( - const uint8_t channel); - -void system_gclk_chan_lock( - const uint8_t channel); - -bool system_gclk_chan_is_locked( - const uint8_t channel); - -/** @} */ - - -/** - * \name Generic Clock Frequency Retrieval - * @{ - */ - -uint32_t system_gclk_gen_get_hz( - const uint8_t generator); - -uint32_t system_gclk_chan_get_hz( - const uint8_t channel); - -/** @} */ - -#ifdef __cplusplus -} -#endif - -/** @} */ - -#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/i2s.c b/feather_sensor_transmit/libraries/Adafruit_ASFcore/i2s.c deleted file mode 100644 index 31fe2d9..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/i2s.c +++ /dev/null @@ -1,750 +0,0 @@ -/** - * \file - * - * \brief SAM I2S - Inter-IC Sound Controller - * - * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#include "i2s.h" - -/** - * \brief Initializes a hardware I2S module instance - * - * Enables the clock and initialize the I2S module. - * - * \param[in,out] module_inst Pointer to the software module instance struct - * \param[in] hw Pointer to the TCC hardware module - * - * \return Status of the initialization procedure. - * - * \retval STATUS_OK The module was initialized successfully - * \retval STATUS_BUSY Hardware module was busy when the - * initialization procedure was attempted - * \retval STATUS_ERR_DENIED Hardware module was already enabled - */ -enum status_code i2s_init( - struct i2s_module *const module_inst, - I2s *hw) -{ - Assert(module_inst); - Assert(hw); - - /* Enable the user interface clock in the PM */ - system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, PM_APBCMASK_I2S); - - /* Status check */ - uint32_t ctrla; - ctrla = module_inst->hw->CTRLA.reg; - if (ctrla & I2S_CTRLA_ENABLE) { - if (ctrla & (I2S_CTRLA_SEREN1 | - I2S_CTRLA_SEREN0 | I2S_CTRLA_CKEN1 | I2S_CTRLA_CKEN0)) { - return STATUS_BUSY; - } else { - return STATUS_ERR_DENIED; - } - } - - /* Initialize module */ - module_inst->hw = hw; - - /* Initialize serializers */ -#if I2S_CALLBACK_MODE == true - int i, j; - for (i = 0; i < 2; i ++) { - for (j = 0; j < I2S_SERIALIZER_CALLBACK_N; j ++) { - module_inst->serializer[i].callback[j] = NULL; - } - module_inst->serializer[i].registered_callback_mask = 0; - module_inst->serializer[i].enabled_callback_mask = 0; - - module_inst->serializer[i].job_buffer = NULL; - module_inst->serializer[i].job_status = STATUS_OK; - module_inst->serializer[i].requested_words = 0; - module_inst->serializer[i].transferred_words = 0; - - module_inst->serializer[i].mode = I2S_SERIALIZER_RECEIVE; - module_inst->serializer[i].data_size = I2S_DATA_SIZE_32BIT; - } - - _i2s_instances[0] = module_inst; - - system_interrupt_enable(SYSTEM_INTERRUPT_MODULE_I2S); -#endif - - return STATUS_OK; -} - - -/** - * \brief Configure specified I2S clock unit - * - * Enables the clock and initialize the clock unit, based on the given - * configurations. - * - * \param[in,out] module_inst Pointer to the software module instance struct - * \param[in] clock_unit I2S clock unit to initialize and configure - * \param[in] config Pointer to the I2S clock unit configuration - * options struct - * - * \return Status of the configuration procedure. - * - * \retval STATUS_OK The module was initialized successfully - * \retval STATUS_BUSY Hardware module was busy when the - * configuration procedure was attempted - * \retval STATUS_ERR_DENIED Hardware module was already enabled - * \retval STATUS_ERR_INVALID_ARG Invalid divider value or - * MCK direction setting conflict - */ -enum status_code i2s_clock_unit_set_config( - struct i2s_module *const module_inst, - const enum i2s_clock_unit clock_unit, - const struct i2s_clock_unit_config *config) -{ - Assert(module_inst); - Assert(module_inst->hw); - Assert(clock_unit < I2S_CLOCK_UNIT_N); - Assert(config); - - /* Status check */ - uint32_t ctrla, syncbusy; - syncbusy = module_inst->hw->SYNCBUSY.reg; - ctrla = module_inst->hw->CTRLA.reg; - - /* Busy ? */ - if (syncbusy & (I2S_SYNCBUSY_CKEN0 << clock_unit)) { - return STATUS_BUSY; - } - /* Already enabled ? */ - if (ctrla & (I2S_CTRLA_CKEN0 << clock_unit)) { - return STATUS_ERR_DENIED; - } - /* Parameter check */ - if (config->clock.mck_src && config->clock.mck_out_enable) { - return STATUS_ERR_INVALID_ARG; - } - - /* Initialize Clock Unit */ - uint32_t clkctrl = - (config->clock.mck_out_invert ? I2S_CLKCTRL_MCKOUTINV : 0) | - (config->clock.sck_out_invert ? I2S_CLKCTRL_SCKOUTINV : 0) | - (config->frame.frame_sync.invert_out ? I2S_CLKCTRL_FSOUTINV : 0) | - (config->clock.mck_out_enable ? I2S_CLKCTRL_MCKEN : 0) | - (config->clock.mck_src ? I2S_CLKCTRL_MCKSEL : 0) | - (config->clock.sck_src ? I2S_CLKCTRL_SCKSEL : 0) | - (config->frame.frame_sync.invert_use ? I2S_CLKCTRL_FSINV : 0) | - (config->frame.frame_sync.source ? I2S_CLKCTRL_FSSEL : 0) | - (config->frame.data_delay ? I2S_CLKCTRL_BITDELAY : 0); - - uint8_t div_val = config->clock.mck_out_div; - if ((div_val > 0x21) || (div_val == 0)) { - return STATUS_ERR_INVALID_ARG; - } else { - div_val --; - } - clkctrl |= I2S_CLKCTRL_MCKOUTDIV(div_val); - - div_val = config->clock.sck_div; - if ((div_val > 0x21) || (div_val == 0)) { - return STATUS_ERR_INVALID_ARG; - } else { - div_val --; - } - clkctrl |= I2S_CLKCTRL_MCKDIV(div_val); - - uint8_t number_slots = config->frame.number_slots; - if (number_slots > 8) { - return STATUS_ERR_INVALID_ARG; - } else if (number_slots > 0) { - number_slots --; - } - clkctrl |= - I2S_CLKCTRL_NBSLOTS(number_slots) | - I2S_CLKCTRL_FSWIDTH(config->frame.frame_sync.width) | - I2S_CLKCTRL_SLOTSIZE(config->frame.slot_size); - - /* Write clock unit configurations */ - module_inst->hw->CLKCTRL[clock_unit].reg = clkctrl; - - /* Select general clock source */ - const uint8_t i2s_gclk_ids[2] = {I2S_GCLK_ID_0, I2S_GCLK_ID_1}; - struct system_gclk_chan_config gclk_chan_config; - system_gclk_chan_get_config_defaults(&gclk_chan_config); - gclk_chan_config.source_generator = config->clock.gclk_src; - system_gclk_chan_set_config(i2s_gclk_ids[clock_unit], &gclk_chan_config); - system_gclk_chan_enable(i2s_gclk_ids[clock_unit]); - - /* Initialize pins */ - struct system_pinmux_config pin_config; - system_pinmux_get_config_defaults(&pin_config); - if (config->mck_pin.enable) { - pin_config.mux_position = config->mck_pin.mux; - system_pinmux_pin_set_config(config->mck_pin.gpio, &pin_config); - } - if (config->sck_pin.enable) { - pin_config.mux_position = config->sck_pin.mux; - system_pinmux_pin_set_config(config->sck_pin.gpio, &pin_config); - } - if (config->fs_pin.enable) { - pin_config.mux_position = config->fs_pin.mux; - system_pinmux_pin_set_config(config->fs_pin.gpio, &pin_config); - } - - return STATUS_OK; -} - - -/** - * \brief Configure specified I2S serializer - * - * Enables the clock and initialize the serializer, based on the given - * configurations. - * - * \param[in,out] module_inst Pointer to the software module instance struct - * \param[in] serializer I2S serializer to initialize and configure - * \param[in] config Pointer to the I2S serializer configuration - * options struct - * - * \return Status of the configuration procedure. - * - * \retval STATUS_OK The module was initialized successfully - * \retval STATUS_BUSY Hardware module was busy when the - * configuration procedure was attempted - * \retval STATUS_ERR_DENIED Hardware module was already enabled - */ -enum status_code i2s_serializer_set_config( - struct i2s_module *const module_inst, - const enum i2s_serializer serializer, - const struct i2s_serializer_config *config) -{ - Assert(module_inst); - Assert(module_inst->hw); - Assert(serializer < I2S_SERIALIZER_N); - Assert(config); - - /* Status check */ - uint32_t ctrla, syncbusy; - syncbusy = module_inst->hw->SYNCBUSY.reg; - ctrla = module_inst->hw->CTRLA.reg; - - /* Busy ? */ - if (syncbusy & ((I2S_SYNCBUSY_SEREN0 | I2S_SYNCBUSY_DATA0) << serializer)) { - return STATUS_BUSY; - } - /* Already enabled ? */ - if (ctrla & (I2S_CTRLA_CKEN0 << serializer)) { - return STATUS_ERR_DENIED; - } - - /* Initialize Serializer */ - uint32_t serctrl = - (config->loop_back ? I2S_SERCTRL_RXLOOP : 0) | - (config->dma_usage ? I2S_SERCTRL_DMA : 0) | - (config->mono_mode ? I2S_SERCTRL_MONO : 0) | - (config->disable_data_slot[7] ? I2S_SERCTRL_SLOTDIS7 : 0) | - (config->disable_data_slot[6] ? I2S_SERCTRL_SLOTDIS6 : 0) | - (config->disable_data_slot[5] ? I2S_SERCTRL_SLOTDIS5 : 0) | - (config->disable_data_slot[4] ? I2S_SERCTRL_SLOTDIS4 : 0) | - (config->disable_data_slot[3] ? I2S_SERCTRL_SLOTDIS3 : 0) | - (config->disable_data_slot[2] ? I2S_SERCTRL_SLOTDIS2 : 0) | - (config->disable_data_slot[1] ? I2S_SERCTRL_SLOTDIS1 : 0) | - (config->disable_data_slot[0] ? I2S_SERCTRL_SLOTDIS0 : 0) | - (config->transfer_lsb_first ? I2S_SERCTRL_BITREV : 0) | - (config->data_adjust_left_in_word ? I2S_SERCTRL_WORDADJ : 0) | - (config->data_adjust_left_in_slot ? I2S_SERCTRL_SLOTADJ : 0) | - (config->data_padding ? I2S_SERCTRL_TXSAME : 0); - - if (config->clock_unit < I2S_CLOCK_UNIT_N) { - serctrl |= (config->clock_unit ? I2S_SERCTRL_CLKSEL : 0); - } else { - return STATUS_ERR_INVALID_ARG; - } - - serctrl |= - I2S_SERCTRL_SERMODE(config->mode) | - I2S_SERCTRL_TXDEFAULT(config->line_default_state) | - I2S_SERCTRL_DATASIZE(config->data_size) | - I2S_SERCTRL_EXTEND(config->bit_padding); - - /* Write Serializer configuration */ - module_inst->hw->SERCTRL[serializer].reg = serctrl; - - /* Initialize pins */ - struct system_pinmux_config pin_config; - system_pinmux_get_config_defaults(&pin_config); - if (config->data_pin.enable) { - pin_config.mux_position = config->data_pin.mux; - system_pinmux_pin_set_config(config->data_pin.gpio, &pin_config); - } - - /* Save configure */ - module_inst->serializer[serializer].mode = config->mode; - module_inst->serializer[serializer].data_size = config->data_size; - - return STATUS_OK; -} - - - -/** - * \brief Retrieves the current module status. - * - * Retrieves the status of the module, giving overall state information. - * - * \param[in] module_inst Pointer to the I2S software instance struct - * - * \return Bitmask of \c I2S_STATUS_* flags - * - * \retval I2S_STATUS_SYNC_BUSY Module is busy synchronization - * \retval I2S_STATUS_TRANSMIT_UNDERRUN(x) Serializer x (0~1) is underrun - * \retval I2S_STATUS_TRANSMIT_READY(x) Serializer x (0~1) is ready to - * transmit new data word - * \retval I2S_STATUS_RECEIVE_OVERRUN(x) Serializer x (0~1) is overrun - * \retval I2S_STATUS_RECEIVE_READY(x) Serializer x (0~1) has data ready to - * read - */ -uint32_t i2s_get_status( - const struct i2s_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - uint32_t intflag = module_inst->hw->INTFLAG.reg; - uint32_t status; - if (module_inst->hw->SYNCBUSY.reg) { - status = I2S_STATUS_SYNC_BUSY; - } else { - status = 0; - } - if (intflag & I2S_INTFLAG_TXUR0) { - status |= I2S_STATUS_TRANSMIT_UNDERRUN(0); - } - if (intflag & I2S_INTFLAG_TXUR1) { - status |= I2S_STATUS_TRANSMIT_UNDERRUN(1); - } - if ((intflag & I2S_INTFLAG_TXRDY0) && - !module_inst->hw->SYNCBUSY.bit.DATA0) { - status |= I2S_STATUS_TRANSMIT_READY(0); - } - if ((intflag & I2S_INTFLAG_TXRDY1) && - !module_inst->hw->SYNCBUSY.bit.DATA1) { - status |= I2S_STATUS_TRANSMIT_READY(1); - } - if (intflag & I2S_INTFLAG_RXOR0) { - status |= I2S_STATUS_RECEIVE_OVERRUN(0); - } - if (intflag & I2S_INTFLAG_RXOR1) { - status |= I2S_STATUS_RECEIVE_OVERRUN(1); - } - if (intflag & I2S_INTFLAG_RXRDY0) { - status |= I2S_STATUS_RECEIVE_READY(0); - } - if (intflag & I2S_INTFLAG_RXRDY1) { - status |= I2S_STATUS_RECEIVE_READY(1); - } - return status; -} - -/** - * \brief Clears a module status flags. - * - * Clears the given status flags of the module. - * - * \param[in] module_inst Pointer to the I2S software instance struct - * \param[in] status Bitmask of \c I2S_STATUS_* flags to clear - */ -void i2s_clear_status( - const struct i2s_module *const module_inst, - uint32_t status) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - uint32_t intflag = 0; - - if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { - intflag = I2S_INTFLAG_TXUR0; - } - if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { - intflag = I2S_INTFLAG_TXUR1; - } - if (status & I2S_STATUS_TRANSMIT_READY(0)) { - intflag = I2S_INTFLAG_TXRDY0; - } - if (status & I2S_STATUS_TRANSMIT_READY(1)) { - intflag = I2S_INTFLAG_TXRDY1; - } - if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { - intflag = I2S_INTFLAG_RXOR0; - } - if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { - intflag = I2S_INTFLAG_RXOR1; - } - if (status & I2S_STATUS_RECEIVE_READY(0)) { - intflag = I2S_INTFLAG_RXRDY0; - } - if (status & I2S_STATUS_RECEIVE_READY(1)) { - intflag = I2S_INTFLAG_RXRDY1; - } - module_inst->hw->INTFLAG.reg = intflag; -} - -/** - * \brief Enable interrupts on status set - * - * Enable the given status interrupt request from the I2S module. - * - * \param[in] module_inst Pointer to the I2S software instance struct - * \param[in] status Status interrupts to enable - * - * \return Status of enable procedure - * - * \retval STATUS_OK Interrupt is enabled successfully - * \retval STATUS_ERR_INVALID_ARG Status with no interrupt is passed - */ -enum status_code i2s_enable_status_interrupt( - struct i2s_module *const module_inst, - uint32_t status) -{ - /* Sanity check arguments */ - Assert(module_inst); - - /* No sync busy interrupt */ - if (status & I2S_STATUS_SYNC_BUSY) { - return STATUS_ERR_INVALID_ARG; - } - Assert(module_inst->hw); - - uint32_t intflag = 0; - if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { - intflag = I2S_INTFLAG_TXUR0; - } - if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { - intflag = I2S_INTFLAG_TXUR1; - } - if (status & I2S_STATUS_TRANSMIT_READY(0)) { - intflag = I2S_INTFLAG_TXRDY0; - } - if (status & I2S_STATUS_TRANSMIT_READY(1)) { - intflag = I2S_INTFLAG_TXRDY1; - } - if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { - intflag = I2S_INTFLAG_RXOR0; - } - if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { - intflag = I2S_INTFLAG_RXOR1; - } - if (status & I2S_STATUS_RECEIVE_READY(0)) { - intflag = I2S_INTFLAG_RXRDY0; - } - if (status & I2S_STATUS_RECEIVE_READY(1)) { - intflag = I2S_INTFLAG_RXRDY1; - } - module_inst->hw->INTENSET.reg = intflag; - return STATUS_OK; -} - -/** - * \brief Disable interrupts on status set - * - * Disable the given status interrupt request from the I2S module. - * - * \param[in] module_inst Pointer to the I2S software instance struct - * \param[in] status Status interrupts to disable - */ -void i2s_disable_status_interrupt( - struct i2s_module *const module_inst, - uint32_t status) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - uint32_t intflag = 0; - if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { - intflag = I2S_INTFLAG_TXUR0; - } - if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { - intflag = I2S_INTFLAG_TXUR1; - } - if (status & I2S_STATUS_TRANSMIT_READY(0)) { - intflag = I2S_INTFLAG_TXRDY0; - } - if (status & I2S_STATUS_TRANSMIT_READY(1)) { - intflag = I2S_INTFLAG_TXRDY1; - } - if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { - intflag = I2S_INTFLAG_RXOR0; - } - if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { - intflag = I2S_INTFLAG_RXOR1; - } - if (status & I2S_STATUS_RECEIVE_READY(0)) { - intflag = I2S_INTFLAG_RXRDY0; - } - if (status & I2S_STATUS_RECEIVE_READY(1)) { - intflag = I2S_INTFLAG_RXRDY1; - } - module_inst->hw->INTENCLR.reg = intflag; -} - - -/** - * \brief Write buffer to the specified Serializer of I2S module - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer The serializer to write to - * \param[in] buffer The data buffer to write - * \param[in] size Number of data words to write - * - * \return Status of the initialization procedure. - * - * \retval STATUS_OK The data was sent successfully - * \retval STATUS_ERR_DENIED The module or serializer is disabled - * \retval STATUS_ERR_INVALID_ARG An invalid buffer pointer was supplied - */ -enum status_code i2s_serializer_write_buffer_wait( - const struct i2s_module *const module_inst, - enum i2s_serializer serializer, - void *buffer, uint32_t size) -{ - Assert(module_inst); - Assert(module_inst->hw); - Assert(serializer < I2S_SERIALIZER_N); - Assert(buffer); - - if (size == 0) { - return STATUS_OK; - } - - uint8_t data_size = 1; /* number of bytes */ - struct i2s_serializer_module *data_module = (struct i2s_serializer_module *) - &module_inst->serializer[serializer]; - - /* Check buffer */ - switch(data_module->data_size) { - case I2S_DATA_SIZE_32BIT: - case I2S_DATA_SIZE_24BIT: - case I2S_DATA_SIZE_20BIT: - case I2S_DATA_SIZE_18BIT: - if ((uint32_t)buffer & 0x3) { - return STATUS_ERR_INVALID_ARG; - } - data_size = 4; - break; - case I2S_DATA_SIZE_16BIT: - case I2S_DATA_SIZE_16BIT_COMPACT: - if ((uint32_t)buffer & 0x1) { - return STATUS_ERR_INVALID_ARG; - } - data_size = 2; - break; - default: - break; - } - - /* Check status */ - if (!(module_inst->hw->CTRLA.reg & - (I2S_CTRLA_ENABLE | (I2S_CTRLA_SEREN0 << serializer)))) { - return STATUS_ERR_DENIED; - } - - /* Write */ - uint32_t i; - uint32_t sync_bit = I2S_SYNCBUSY_DATA0 << serializer; - uint32_t ready_bit = I2S_INTFLAG_TXRDY0 << serializer; - if (4 == data_size) { - uint32_t *p32 = (uint32_t*)buffer; - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Tx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - module_inst->hw->DATA[serializer].reg = p32[i]; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } else if (2 == data_size) { - uint16_t *p16 = (uint16_t*)buffer; - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Tx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - module_inst->hw->DATA[serializer].reg = p16[i]; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } else { - uint8_t *p8 = (uint8_t*)buffer; - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Tx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - module_inst->hw->DATA[serializer].reg = p8[i]; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } - - return STATUS_OK; -} - -/** - * \brief Read from the specified Serializer of I2S module to a buffer - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer The serializer to write to - * \param[in] buffer The buffer to fill read data (NULL to discard) - * \param[in] size Number of data words to read - * - * \return Status of the initialization procedure. - * - * \retval STATUS_OK The data was sent successfully - * \retval STATUS_ERR_DENIED The module or serializer is disabled - * \retval STATUS_ERR_INVALID_ARG An invalid buffer pointer was supplied - */ -enum status_code i2s_serializer_read_buffer_wait( - const struct i2s_module *const module_inst, - enum i2s_serializer serializer, - void *buffer, uint32_t size) -{ - Assert(module_inst); - Assert(module_inst->hw); - - if (size == 0) { - return STATUS_OK; - } - - uint8_t data_size = 1; /* number of bytes */ - struct i2s_serializer_module *data_module = (struct i2s_serializer_module *) - &module_inst->serializer[serializer]; - - /* Check buffer */ - switch(data_module->data_size) { - case I2S_DATA_SIZE_32BIT: - case I2S_DATA_SIZE_24BIT: - case I2S_DATA_SIZE_20BIT: - case I2S_DATA_SIZE_18BIT: - if ((uint32_t)buffer & 0x3) { - return STATUS_ERR_INVALID_ARG; - } - data_size = 4; - break; - case I2S_DATA_SIZE_16BIT: - case I2S_DATA_SIZE_16BIT_COMPACT: - if ((uint32_t)buffer & 0x1) { - return STATUS_ERR_INVALID_ARG; - } - data_size = 2; - break; - default: - break; - } - - /* Check status */ - if (!(module_inst->hw->CTRLA.reg & - (I2S_CTRLA_ENABLE | (I2S_CTRLA_SEREN0 << serializer)))) { - return STATUS_ERR_DENIED; - } - - /* Read */ - uint32_t i; - uint32_t sync_bit = I2S_SYNCBUSY_DATA0 << serializer; - uint32_t ready_bit = I2S_INTFLAG_RXRDY0 << serializer; - if (buffer == NULL) { - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Rx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - module_inst->hw->DATA[serializer].reg; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } - else if (4 == data_size) { - uint32_t *p32 = (uint32_t*)buffer; - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Rx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - p32[i] = module_inst->hw->DATA[serializer].reg; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } else if (2 == data_size) { - uint16_t *p16 = (uint16_t*)buffer; - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Rx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - p16[i] = module_inst->hw->DATA[serializer].reg; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } else { - uint8_t *p8 = (uint8_t*)buffer; - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Tx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - p8[i] = module_inst->hw->DATA[serializer].reg; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } - - return STATUS_OK; -} diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/i2s.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/i2s.h deleted file mode 100644 index 9911e6d..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/i2s.h +++ /dev/null @@ -1,1404 +0,0 @@ -/** - * \file - * - * \brief SAM I2S - Inter-IC Sound Controller - * - * Copyright (c) 2014-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#ifndef I2S_H_INCLUDED -#define I2S_H_INCLUDED - -/** - * \defgroup asfdoc_sam0_i2s_group SAM Inter-IC Sound Controller Driver (I2S) - * - * This driver for Atmel® | SMART SAM devices provides an interface for the configuration - * and management of the device's Inter-IC Sound Controller functionality. - * - * The following driver API modes are covered by this manual: - * - Polled APIs - * \if I2S_CALLBACK_MODE - * - Callback APIs - * \endif - * - * The following peripherals are used by this module: - * - I2S (Inter-IC Sound Controller) - * - * The following devices can use this module: - * - Atmel | SMART SAM D21 - * - Atmel | SMART SAM DA1 - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_i2s_prerequisites - * - \ref asfdoc_sam0_i2s_module_overview - * - \ref asfdoc_sam0_i2s_special_considerations - * - \ref asfdoc_sam0_i2s_extra_info - * - \ref asfdoc_sam0_i2s_examples - * - \ref asfdoc_sam0_i2s_api_overview - * - * \section asfdoc_sam0_i2s_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * \section asfdoc_sam0_i2s_module_overview Module Overview - * - * The I2S provides bidirectional, synchronous, digital audio link with external - * audio devices through these signal pins: - * - Serial Data (SDm) - * - Frame Sync (FSn) - * - Serial Clock (SCKn) - * - Master Clock (MCKn) - * - * The I2S consists of 2 Clock Units and 2 Serializers, which can be separately - * configured and enabled, to provide varies functionalities as follow: - * - Communicate to Audio CODECs as Master or Slave, or provides clock and - * frame sync signals as Controller - * - Communicate to DAC or ADC through dedicated I2S serial interface - * - Communicate to multi-slot or multiple stereo DACs or ADCs, via - * Time Division Multiplexed (TDM) format - * - Reading mono or stereo MEMS microphones, using the Pulse Density - * Modulation (PDM) interface - * - * The I2S supports compact stereo data word, where left channel data bits are - * in lower half and right channel data bits are in upper half. It reduces the - * number of data words for stereo audio data and the DMA bandwidth. - * - * In master mode, the frame is configured by number of slots and slot size, and - * allows range covering 16fs to 1024fs MCK, to provide oversampling clock to an - * external audio CODEC or digital signal processor (DSP). - * - * A block diagram of the I2S can be seen in - * \ref asfdoc_sam0_i2s_module_block_diagram "the figure below". - * - * \anchor asfdoc_sam0_i2s_module_block_diagram - * \image html i2s_blocks.svg "I2S Block Diagram" - * - * This driver for I2S module provides an interface to - * - initialize and control I2S module - * - configure and control the I2S Clock Unit and Serializer - * - transmit/receive data through I2S Serializer - * - * \subsection asfdoc_sam0_i2s_module_overview_clocks Clocks - * - * To use I2S module, the I2S bus interface clock (clk_i2s) must be enabled via - * Power Manager. - * - * For each I2S Clock Unit, a generic clock (gclk_i2s_n) is connnected. When I2S - * works in master mode the generic clock is used. It should be prepared before - * clock unit is used. In master mode the input generic clock will be used as - * MCK for SCKn and FSn generation, in addition, the MCK could be devided and - * output to I2S MCKn pin, as oversampling clock to external audio device. - * - * The I2S Serializer uses clock and control signal from Clock Unit to handle - * transfer. Select different clock unit with different configurations allows - * the I2S to work as master or slave, to work on non-related clocks. - * - * When using the driver with ASF, enabling the register interface is normally - * done by the \c init function. - * The gclk source for the asynchronous domain is normally configured and set - * through the _configuration struct_ / _init_ function. - * If gclk source != 0 is used, this source has to be configured and enabled - * through invoking the system_gclk driver function when needed, or modifying - * conf_clock.h to enable it at the beginning. - * - * \subsection asfdoc_sam0_i2s_module_overview_frame Audio Frame Generation - * - * Audio sample data for all channels are sent in frames, one frame can consist - * 1 - 8 slots where each slot can be configured to a size 8-bit, 16-bit, 24-bit - * or 32-bit. The audio frame synch clock is generated by the I2S Clock unit in - * the master/controller mode. The frame rate (or frame sync frequency) is - * calculated as follow: - * - * FS = SCK / number_of_slots / number_of_bits_in_slot - * - * The serial clock (SCK) source is either an external source (slave mode) or - * generated by the I2S clock unit (controller or master mode) using the MCK as - * source. - * - * SCK = MCK / sck_div - * \note SCK generation division value is MCKDIV in register. - * - * MCK is either an external source or generated using the gclk input from a - * generic clock generator. - * - * \subsection asfdoc_sam0_i2s_module_overview_mode Master, Controller and Slave modes - * - * The i2s module has three modes: master, controller and slave. - * - * \subsubsection asfdoc_sam0_i2s_module_overview_mode_mst Master - * In master mode the module will control the data flow on the i2s bus and can - * be responsible for clock generation. The Serializers are enabled and will - * transmit/receive data. On a bus with only master and slave the SCK and FS - * clock signal will be outputted on the SCK and FS pin on the master module. - * MCK can optionally be outputted on the MCK pin, if there is a controller - * module on the bus the SCK, FS and optionally the MCK clock is sourced from - * the same pins. Serial data will be trancieved on the SD pin in both - * scenarios. - * - * \subsubsection asfdoc_sam0_i2s_module_overview_mode_ctl Controller - * In controller mode the module will generate the clock signals, but the - * Serializers are disabled and no data will be transmitted/received by the - * module in this mode. The clock signals is outputted on the SCK, FS and - * optionally the MCK pin. - * - * \subsubsection asfdoc_sam0_i2s_module_overview_mode_slv Slave - * In slave mode the module will use the SCK and FS clock source from the master - * or the controller which is received on the SCK and FS pin. The MCK can - * optionally be sourced externally on the MCK pin. The Serializers are enabled - * and will tranceive data on the SD pin. All data flow is controlled by the - * master. - * - * \subsubsection asfdoc_sam0_i2s_module_overview_mode_chg Switch modes - * The mode switching between master, controller and slave modes are actually - * done by modifying the source mode of I2S pins. - * The source mode of I2S pins are selected by writing corresponding bits in - * CLKCTRLn. - * Since source mode switching changes the direction of pin, the mode must be - * changed when the I2S Clock Unit is stopped. - * - * \subsection asfdoc_sam0_i2s_module_overview_data Data Stream Reception/Transmission - * - * The I2S module support several data stream formats: - * - I2S format - * - Time Division Multiplexed (TDM) format - * - Pulse Density Modulation (PDM) format (reception only) - * - * Basically the I2S module can send several words within each frame, it's more - * like TDM format. With adjust to the number of data words in a frame, the FS - * width, the FS to data bits delay, etc., the module is able to handle I2S - * compliant data stream. - * - * Also the Serializer can receive PDM format data stream, which allows the I2S - * module receive 1 PDM data on each SCK edge. - * - * \subsubsection asfdoc_sam0_i2s_module_overview_data_i2s I2S Stream Reception/Transmission - * - * For 2-channel I2S compliant data stream format the i2s module uses the FS - * line as word select (WS) signal and will send left channel data word on low - * WS level and right channel data word on high WS level as specified in the I2S - * standard. The supported word sizes are 8-, 16-, 18-, 20-, 24- and 32- bit. - * - * Thus for I2S stream, the following settings should be applied to the module: - * - Data starting delay after FS transition : one SCK period - * - FS width : half of frame - * - Data bits adjust in word : left-adjusted - * - Bit transmitting order : MSB first - * - * Following is an example for I2S application connections and waveforms. See - * \ref asfdoc_sam0_i2s_module_i2s_example_diagram "the figure below". - * - * \anchor asfdoc_sam0_i2s_module_i2s_example_diagram - * \image html i2s_example.svg "I2S Example Diagram" - * - * \subsubsection asfdoc_sam0_i2s_module_overview_data_tdm TDM Stream Reception/Transmission - * In TDM format, the module sends several data words in each frame. For this - * data stream format most of the configurations could be adjusted: - * - Main Frame related settings are as follow: - * - Frame Sync (FS) options: - * - the active edge of the FS (or if FS is inverted before use) - * - the width of the FS - * - the delay between FS to first data bit - * - Data alignment in slot - * - The number of slots and slot size can be adjusted, it has been mentioned - * in \ref asfdoc_sam0_i2s_module_overview_frame - * - The data word size is controlled by Serializer, it can be chosen among - * 8, 16, 18, 20, 24 and 32 bits. - * - * The general TDM waveform generation is as follow: - * - * \anchor asfdoc_sam0_i2s_module_tdm_wave_diagram - * \image html tdm_wave.svg "TDM Waveform generation" - * - * Some other settings could also be found to set up clock, data formatting and - * pin mux. - * refer to \ref i2s_clock_unit_config "Clock Unit Configurations" - * and \ref i2s_serializer_config "Serializer Configurations" for more - * details. - * - * Following is examples for different application use cases. - * - * See \ref asfdoc_sam0_i2s_module_tdm_timeslot_example_diagram "here" for - * the Time Slot Application connection and waveform example. - * - * \anchor asfdoc_sam0_i2s_module_tdm_timeslot_example_diagram - * \image html tdm_timeslot_example.svg "Codec Example Diagram" - * - * See \ref asfdoc_sam0_i2s_module_tdm_codec_example_diagram "here" for the - * Codec Application connection and waveform example. - * - * \anchor asfdoc_sam0_i2s_module_tdm_codec_example_diagram - * \image html tdm_codec_example.svg "Time Slot Example Diagram" - * - * \subsubsection asfdoc_sam0_i2s_module_overview_data_pdm PDM Reception - * The I2S Serializer integrates PDM reception feature, to use this feature, - * simply select PDM2 mode in Serializer configuration. In PDM2 mode, it assumes - * two microphones are input for stereo stream. The left microphone bits will - * be stored in lower half and right microphone bits in upper half of the data - * word, like in compact stereo format. - * - * See \ref asfdoc_sam0_i2s_module_pdm_example_diagram "following figure" for an - * example of PDM Microphones Application with both left and right channel - * microphone connected. - * - * \anchor asfdoc_sam0_i2s_module_pdm_example_diagram - * \image html pdm_example.svg "Time PDM2 Example Diagram" - * - * \subsubsection asfdoc_sam0_i2s_module_overview_data_fmt MONO and Compact Data - * The I2S Serializer can accept some pre-defined data format and generates - * the data stream in specified way. - * - * When transmitting data, the Serializer can work in MONO mode: assum input - * is single channel mono data on left channel and copy it to right channel - * automatically. - * - * Also the I2S Serializer can support compact stereo data word. The data word - * size of the Serializer can be set to \ref I2S_DATA_SIZE_16BIT_COMPACT - * "16-bit compact" or \ref I2S_DATA_SIZE_8BIT_COMPACT "8-bit compact", with - * these option I2S Serializer will compact left channel data and right channel - * data together, the left channel data will take lower bytes and right channel - * data take higher bytes. - * - * \subsection asfdoc_sam0_i2s_module_overview_loop Loop-back Mode - * The I2S can be configured to loop back the Transmitter to Receiver. In this - * mode Serializer's input will be connected to another Serializer's output - * internally. - * - * \subsection asfdoc_sam0_i2s_module_overview_sleep Sleep Modes - * The I2S will continue to operate in any sleep mode, where the selected source - * clocks are running. - * - * \section asfdoc_sam0_i2s_special_considerations Special Considerations - * - * There is no special considerations for I2S module. - * - * \section asfdoc_sam0_i2s_extra_info Extra Information - * - * For extra information see \ref asfdoc_sam0_i2s_extra. This includes: - * - \ref asfdoc_sam0_i2s_extra_acronyms - * - \ref asfdoc_sam0_i2s_extra_dependencies - * - \ref asfdoc_sam0_i2s_extra_errata - * - \ref asfdoc_sam0_i2s_extra_history - * - * \section asfdoc_sam0_i2s_examples Examples - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_i2s_exqsg. - * - * - * \section asfdoc_sam0_i2s_api_overview API Overview - * @{ - */ - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include - -#if I2S_CALLBACK_MODE == true -# include - -#if !defined(__DOXYGEN__) -extern struct i2s_module *_i2s_instances[I2S_INST_NUM]; -#endif - -/** Forward definition of the device instance */ -struct i2s_module; - -/** Type of the callback functions */ -typedef void (*i2s_serializer_callback_t) - (struct i2s_module *const module); - -/** - * \brief I2S Serializer Callback enum - */ -enum i2s_serializer_callback { - /** Callback for buffer read/write finished */ - I2S_SERIALIZER_CALLBACK_BUFFER_DONE, - /** Callback for Serializer overrun/underrun */ - I2S_SERIALIZER_CALLBACK_OVER_UNDER_RUN, -# if !defined(__DOXYGEN__) - I2S_SERIALIZER_CALLBACK_N -# endif -}; - -#endif /* #if I2S_CALLBACK_MODE == true */ - -/** - * \name Module status flags - * - * I2S status flags, returned by \ref i2s_get_status() and cleared by - * \ref i2s_clear_status(). - * - * @{ - */ - -/** Module Serializer x (0~1) Transmit Underrun */ -#define I2S_STATUS_TRANSMIT_UNDERRUN(x) (1u << ((x)+0)) -/** Module Serializer x (0~1) is ready to accept new data to be transmitted */ -#define I2S_STATUS_TRANSMIT_READY(x) (1u << ((x)+2)) -/** Module Serializer x (0~1) Receive Overrun */ -#define I2S_STATUS_RECEIVE_OVERRUN(x) (1u << ((x)+4)) -/** Module Serializer x (0~1) has received a new data */ -#define I2S_STATUS_RECEIVE_READY(x) (1u << ((x)+6)) -/** Module is busy on synchronization */ -#define I2S_STATUS_SYNC_BUSY (1u << 8) - -/** @} */ - -/** - * Master Clock (MCK) source selection - */ -enum i2s_master_clock_source { - /** Master Clock (MCK) is from general clock */ - I2S_MASTER_CLOCK_SOURCE_GCLK, - /** Master Clock (MCK) is from MCK input pin */ - I2S_MASTER_CLOCK_SOURCE_MCKPIN -}; - -/** - * Serial Clock (SCK) source selection - */ -enum i2s_serial_clock_source { - /** Serial Clock (SCK) is divided from Master Clock */ - I2S_SERIAL_CLOCK_SOURCE_MCKDIV, - /** Serial Clock (SCK) is input from SCK input pin */ - I2S_SERIAL_CLOCK_SOURCE_SCKPIN -}; - -/** - * Data delay from Frame Sync (FS) - */ -enum i2s_data_delay { - /** Left Justified (no delay) */ - I2S_DATA_DELAY_0, - /** I2S data delay (1-bit delay) */ - I2S_DATA_DELAY_1, - /** Left Justified (no delay) */ - I2S_DATA_DELAY_LEFT_JUSTIFIED = I2S_DATA_DELAY_0, - /** I2S data delay (1-bit delay) */ - I2S_DATA_DELAY_I2S = I2S_DATA_DELAY_1 -}; - -/** - * Frame Sync (FS) source - */ -enum i2s_frame_sync_source { - /** Frame Sync (FS) is divided from I2S Serial Clock */ - I2S_FRAME_SYNC_SOURCE_SCKDIV, - /** Frame Sync (FS) is input from FS input pin */ - I2S_FRAME_SYNC_SOURCE_FSPIN -}; - -/** - * Frame Sync (FS) output pulse width - */ -enum i2s_frame_sync_width { - /** Frame Sync (FS) Pulse is 1 Slot width */ - I2S_FRAME_SYNC_WIDTH_SLOT, - /** Frame Sync (FS) Pulse is half a Frame width */ - I2S_FRAME_SYNC_WIDTH_HALF_FRAME, - /** Frame Sync (FS) Pulse is 1 Bit width */ - I2S_FRAME_SYNC_WIDTH_BIT, - /** 1-bit wide Frame Sync (FS) per Data sample, only used when Data transfer - * is requested */ - I2S_FRAME_SYNC_WIDTH_BURST -}; - -/** - * Time Slot Size in number of I2S serial clocks (bits) - */ -enum i2s_slot_size { - /** 8-bit slot */ - I2S_SLOT_SIZE_8_BIT, - /** 16-bit slot */ - I2S_SLOT_SIZE_16_BIT, - /** 24-bit slot */ - I2S_SLOT_SIZE_24_BIT, - /** 32-bit slot */ - I2S_SLOT_SIZE_32_BIT -}; - -/** - * DMA channels usage for I2S - */ -enum i2s_dma_usage { - /** Single DMA channel for all I2S channels */ - I2S_DMA_USE_SINGLE_CHANNEL_FOR_ALL, - /** One DMA channel per data channel */ - I2S_DMA_USE_ONE_CHANNEL_PER_DATA_CHANNEL -}; - -/** - * I2S data format, to extend mono data to 2 channels - */ -enum i2s_data_format { - /** Normal mode, keep data to its right channel */ - I2S_DATA_FORMAT_STEREO, - /** Assume input is mono data for left channel, the data is duplicated to - * right channel */ - I2S_DATA_FORMAT_MONO -}; - -/** - * I2S data bit order - */ -enum i2s_bit_order { - /** Transfer Data Most Significant Bit first (Default for I2S protocol) */ - I2S_BIT_ORDER_MSB_FIRST, - /** Transfer Data Least Significant Bit first */ - I2S_BIT_ORDER_LSB_FIRST -}; - -/** - * I2S data bit padding - */ -enum i2s_bit_padding { - /** Padding with 0 */ - I2S_BIT_PADDING_0, - /** Padding with 1 */ - I2S_BIT_PADDING_1, - /** Padding with MSBit */ - I2S_BIT_PADDING_MSB, - /** Padding with LSBit */ - I2S_BIT_PADDING_LSB, -}; - -/** - * I2S data word adjust - */ -enum i2s_data_adjust { - /** Data is right adjusted in word */ - I2S_DATA_ADJUST_RIGHT, - /** Data is left adjusted in word */ - I2S_DATA_ADJUST_LEFT -}; - -/** - * I2S data word size - */ -enum i2s_data_size { - /** 32-bit */ - I2S_DATA_SIZE_32BIT, - /** 24-bit */ - I2S_DATA_SIZE_24BIT, - /** 20-bit */ - I2S_DATA_SIZE_20BIT, - /** 18-bit */ - I2S_DATA_SIZE_18BIT, - /** 16-bit */ - I2S_DATA_SIZE_16BIT, - /** 16-bit compact stereo */ - I2S_DATA_SIZE_16BIT_COMPACT, - /** 8-bit */ - I2S_DATA_SIZE_8BIT, - /** 8-bit compact stereo */ - I2S_DATA_SIZE_8BIT_COMPACT -}; - -/** - * I2S data slot adjust - */ -enum i2s_slot_adjust { - /** Data is right adjusted in slot */ - I2S_SLOT_ADJUST_RIGHT, - /** Data is left adjusted in slot */ - I2S_SLOT_ADJUST_LEFT -}; - -/** - * I2S data padding - */ -enum i2s_data_padding { - /** Padding 0 in case of under-run */ - I2S_DATA_PADDING_0, - /** Padding last data in case of under-run */ - I2S_DATA_PADDING_SAME_AS_LAST, - /** Padding last data in case of under-run - * (abbr. \c I2S_DATA_PADDING_SAME_AS_LAST) */ - I2S_DATA_PADDING_LAST = I2S_DATA_PADDING_SAME_AS_LAST, - /** Padding last data in case of under-run - * (abbr. \c I2S_DATA_PADDING_SAME_AS_LAST) */ - I2S_DATA_PADDING_SAME = I2S_DATA_PADDING_SAME_AS_LAST -}; - -/** - * I2S line default value when slot disabled - */ -enum i2s_line_default_state { - /** Output default value is 0 */ - I2S_LINE_DEFAULT_0, - /** Output default value is 1 */ - I2S_LINE_DEFAULT_1, - /** Output default value is high impedance */ - I2S_LINE_DEFAULT_HIGH_IMPEDANCE = 3, - /** Output default value is high impedance - * (abbr. \c I2S_LINE_DEFAULT_HIGH_IMPEDANCE) */ - I2S_LINE_DEFAULT_HIZ = I2S_LINE_DEFAULT_HIGH_IMPEDANCE -}; - -/** - * I2S Serializer mode - */ -enum i2s_serializer_mode { - /** Serializer is used to receive data */ - I2S_SERIALIZER_RECEIVE, - /** Serializer is used to transmit data */ - I2S_SERIALIZER_TRANSMIT, - /** Serializer is used to receive PDM data on each clock edge */ - I2S_SERIALIZER_PDM2 -}; - -/** - * I2S clock unit selection - */ -enum i2s_clock_unit { - /** Clock Unit channel 0 */ - I2S_CLOCK_UNIT_0, - /** Clock Unit channel 1 */ - I2S_CLOCK_UNIT_1, - /** Number of Clock Unit channels */ - I2S_CLOCK_UNIT_N -}; - -/** - * I2S Serializer selection - */ -enum i2s_serializer { - /** Serializer channel 0 */ - I2S_SERIALIZER_0, - /** Serializer channel 1 */ - I2S_SERIALIZER_1, - /** Number of Serializer channels */ - I2S_SERIALIZER_N -}; - - -/** - * Configure for I2S pin - */ -struct i2s_pin_config { - /** GPIO index to access the pin */ - uint8_t gpio; - /** Pin function MUX */ - uint8_t mux; - /** Enable this pin for I2S module */ - bool enable; -}; - -/** - * Configure for I2S clock (SCK) - */ -struct i2s_clock_config { - /** Divide generic clock to master clock output (1~32, 0,1 means no div) */ - uint8_t mck_out_div; - /** Divide generic clock to serial clock (1~32, 0,1 means no div) */ - uint8_t sck_div; - /** Clock source selection */ - enum gclk_generator gclk_src; - /** Master clock source selection: generated or input from pin */ - enum i2s_master_clock_source mck_src; - /** Serial clock source selection: generated or input from pin */ - enum i2s_serial_clock_source sck_src; - /** Invert master clock output */ - bool mck_out_invert; - /** Invert serial clock output */ - bool sck_out_invert; - /** Generate MCK clock output */ - bool mck_out_enable; -}; - -/** - * Configure fir I2S frame sync (FS) - */ -struct i2s_frame_sync_config { - /** Frame Sync (FS) generated or input from pin */ - enum i2s_frame_sync_source source; - /** Frame Sync (FS) width */ - enum i2s_frame_sync_width width; - /** Invert Frame Sync (FS) signal before use */ - bool invert_use; - /** Invert Frame Sync (FS) signal before output */ - bool invert_out; -}; - -/** - * Configure fir I2S frame - */ -struct i2s_frame_config { - /** Number of slots in a frame (1~8, 0,1 means minimum 1) */ - uint8_t number_slots; - /** Size of each slot in frame */ - enum i2s_slot_size slot_size; - /** Data delay from Frame Sync (FS) to first data bit */ - enum i2s_data_delay data_delay; - /** Frame sync (FS) */ - struct i2s_frame_sync_config frame_sync; -}; - -/** - * Configure for I2S clock unit - */ -struct i2s_clock_unit_config { - /** Configure clock generation */ - struct i2s_clock_config clock; - /** Configure frame generation */ - struct i2s_frame_config frame; - - /** Configure master clock pin */ - struct i2s_pin_config mck_pin; - /** Configure serial clock pin */ - struct i2s_pin_config sck_pin; - /** Configure frame sync pin */ - struct i2s_pin_config fs_pin; -}; - -/** - * Configure for I2S Serializer - */ -struct i2s_serializer_config { - /** Configure Serializer data pin */ - struct i2s_pin_config data_pin; - - /** Set to \c true to loop-back output to input pin for test */ - bool loop_back; - - /** Set to \c true to assumes mono input and duplicate it (left channel) to - * right channel */ - bool mono_mode; - - /** Disable data slot */ - bool disable_data_slot[8]; - - /** Set to \c true to transfer LSB first, \c false to transfer MSB first */ - bool transfer_lsb_first; - /** Data Word Formatting Adjust, - * set to \c true to adjust bits in word to left */ - bool data_adjust_left_in_word; - /** Data Slot Formatting Adjust, - * set to \c true to adjust words in slot to left */ - bool data_adjust_left_in_slot; - - /** Data Word Size */ - enum i2s_data_size data_size; - /** Data Formatting Bit Extension */ - enum i2s_bit_padding bit_padding; - /** Data padding when under-run */ - enum i2s_data_padding data_padding; - - /** DMA usage */ - enum i2s_dma_usage dma_usage; - - /** Clock unit selection */ - enum i2s_clock_unit clock_unit; - - /** Line default state where slot is disabled */ - enum i2s_line_default_state line_default_state; - - /** Serializer Mode */ - enum i2s_serializer_mode mode; -}; - -/** - * \brief I2S Serializer instance struct - */ -struct i2s_serializer_module { - -#if I2S_CALLBACK_MODE == true - /** Callbacks list for Serializer */ - i2s_serializer_callback_t callback[I2S_SERIALIZER_CALLBACK_N]; - - /** Job buffer */ - void *job_buffer; - /** Requested data words to read/write */ - uint32_t requested_words; - /** Transferred data words for read/write */ - uint32_t transferred_words; - - /** Callback mask for registered callbacks */ - uint8_t registered_callback_mask; - /** Callback mask for enabled callbacks */ - uint8_t enabled_callback_mask; - - /** Status of the ongoing or last transfer job */ - enum status_code job_status; -#endif - - /** Serializer mode */ - enum i2s_serializer_mode mode; - /** Serializer data word size */ - enum i2s_data_size data_size; -}; - -/** - * \brief I2S Software Module instance struct - */ -struct i2s_module { - /** Module HW register access base */ - I2s *hw; - - /** Module Serializer used */ - struct i2s_serializer_module serializer[2]; -}; - -/** - * \brief Determines if the hardware module(s) are currently synchronizing to the bus. - * - * Checks to see if the underlying hardware peripheral module(s) are currently - * synchronizing across multiple clock domains to the hardware bus, This - * function can be used to delay further operations on a module until such time - * that it is ready, to prevent blocking delays for synchronization in the - * user application. - * - * \param[in] module_inst Pointer to the software module instance struct - * - * \return Synchronization status of the underlying hardware module(s). - * - * \retval false If the module has completed synchronization - * \retval true If the module synchronization is ongoing - */ -static inline bool i2s_is_syncing( - const struct i2s_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - return (module_inst->hw->SYNCBUSY.reg > 0); -} - -/** - * \name Driver Initialization - * @{ - */ - -enum status_code i2s_init( - struct i2s_module *const module_inst, - I2s *hw); - -/** @} */ - -/** - * \name Enable/Disable/Reset - * @{ - */ - -/** - * \brief Enable the I2S module. - * - * Enables a I2S module that has been previously initialized. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void i2s_enable(const struct i2s_module *const module_inst) -{ - Assert(module_inst); - Assert(module_inst->hw); - - while (module_inst->hw->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE) { - /* Sync wait */ - } - module_inst->hw->CTRLA.reg |= I2S_SYNCBUSY_ENABLE; -} - -/** - * \brief Disables the I2S module. - * - * Disables a I2S module. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void i2s_disable(const struct i2s_module *const module_inst) -{ - Assert(module_inst); - Assert(module_inst->hw); - - while (module_inst->hw->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE) { - /* Sync wait */ - } - module_inst->hw->CTRLA.reg &= ~I2S_SYNCBUSY_ENABLE; -} - -/** - * \brief Resets the I2S module. - * - * Resets the I2S module, restoring all hardware module registers to their - * default values and disabling the module. The I2S module will not be - * accessible while the reset is being performed. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void i2s_reset(const struct i2s_module *const module_inst) -{ - Assert(module_inst); - Assert(module_inst->hw); - - /* Disable the module if it is running */ - if (module_inst->hw->CTRLA.reg & I2S_CTRLA_ENABLE) { - i2s_disable(module_inst); - while (i2s_is_syncing(module_inst)) { - /* Sync wait */ - } - } - /* Reset the HW module */ - module_inst->hw->CTRLA.reg = I2S_CTRLA_SWRST; -} - -/** @} */ - -/** - * \name Clock Unit Initialization and Configuration - * @{ - */ - -/** - * \brief Initializes config with predefined default values for I2S clock unit. - * - * This function will initialize a given I2S Clock Unit configuration structure - * to a set of known default values. This function should be called on any new - * instance of the configuration structures before being modified by the user - * application. - * - * The default configuration is as follow: - * - The clock unit does not generate output clocks (MCK, SCK and FS) - * - The pins (MCK, SCK and FS) and Mux configurations are not set - * - * \param[out] config Pointer to a I2S module clock unit configuration struct - * to set - */ -static inline void i2s_clock_unit_get_config_defaults( - struct i2s_clock_unit_config *const config) -{ - Assert(config); - - config->clock.mck_out_enable = false; - config->clock.gclk_src = GCLK_GENERATOR_0; - - config->clock.mck_src = I2S_MASTER_CLOCK_SOURCE_GCLK; - config->clock.mck_out_div = 1; - config->clock.mck_out_invert = false; - - config->clock.sck_src = I2S_SERIAL_CLOCK_SOURCE_MCKDIV; - config->clock.sck_div = 1; - config->clock.sck_out_invert = false; - - config->frame.number_slots = 1; - config->frame.slot_size = I2S_SLOT_SIZE_32_BIT; - config->frame.data_delay = I2S_DATA_DELAY_I2S; - - config->frame.frame_sync.source = I2S_FRAME_SYNC_SOURCE_SCKDIV; - config->frame.frame_sync.width = I2S_FRAME_SYNC_WIDTH_HALF_FRAME; - config->frame.frame_sync.invert_use = false; - config->frame.frame_sync.invert_out = false; - - config->mck_pin.enable = false; - config->mck_pin.mux = 0; - config->mck_pin.gpio = 0; - - config->sck_pin.enable = false; - config->sck_pin.mux = 0; - config->sck_pin.gpio = 0; - - config->fs_pin.enable = false; - config->fs_pin.mux = 0; - config->fs_pin.gpio = 0; -} - -enum status_code i2s_clock_unit_set_config( - struct i2s_module *const module_inst, - const enum i2s_clock_unit clock_unit, - const struct i2s_clock_unit_config *config); - -/** @} */ - - -/** - * \name Clock Unit Enable/Disable - * @{ - */ - -/** - * \brief Enable the Specified Clock Unit of I2S module. - * - * Enables a Clock Unit in I2S module that has been previously initialized. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] clock_unit I2S Clock Unit to enable - */ -static inline void i2s_clock_unit_enable( - const struct i2s_module *const module_inst, - const enum i2s_clock_unit clock_unit) -{ - uint32_t cken_bit; - - Assert(module_inst); - Assert(module_inst->hw); - - cken_bit = I2S_CTRLA_CKEN0 << clock_unit; - - while (module_inst->hw->SYNCBUSY.reg & cken_bit) { - /* Sync wait */ - } - module_inst->hw->CTRLA.reg |= cken_bit; -} - -/** - * \brief Disable the Specified Clock Unit of I2S module. - * - * Disables a Clock Unit in I2S module that has been previously initialized. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] clock_unit I2S Clock Unit to disable - */ -static inline void i2s_clock_unit_disable( - const struct i2s_module *const module_inst, - const enum i2s_clock_unit clock_unit) -{ - uint32_t cken_bit; - - Assert(module_inst); - Assert(module_inst->hw); - - cken_bit = I2S_CTRLA_CKEN0 << clock_unit; - - while (module_inst->hw->SYNCBUSY.reg & cken_bit) { - /* Sync wait */ - } - module_inst->hw->CTRLA.reg &= ~cken_bit; -} - -/** @} */ - - -/** - * \name Serializer Initialization and Configuration - * @{ - */ - -/** - * \brief Initializes config with predefined default values for I2S Serializer. - * - * This function will initialize a given I2S Clock Unit configuration structure - * to a set of known default values. This function should be called on any new - * instance of the configuration structures before being modified by the user - * application. - * - * The default configuration is as follow: - * - Output data does not internally loopback to input line - * - Does not extend mono data (left channel) to right channel - * - None of the data slot is disabled - * - MSB of I2S data is transferred first - * - In data word data is adjusted right - * - In slot data word is adjusted left - * - The data size is 16-bit width - * - I2S will padd 0 to not defined bits - * - I2S will padd 0 to not defined words - * - I2S will use single DMA channel for all data channels - * - I2S will use clock unit 0 to serve as clock - * - The default data line state is 0, when there is no data - * - I2S will transmit data to output line - * - The data pin and Mux configuration are not set - * - * \param[out] config Pointer to a I2S module Serializer configuration struct - * to set - */ -static inline void i2s_serializer_get_config_defaults( - struct i2s_serializer_config *const config) -{ - config->loop_back = false; - - config->mono_mode = false; - - config->disable_data_slot[0] = false; - config->disable_data_slot[1] = false; - config->disable_data_slot[2] = false; - config->disable_data_slot[3] = false; - config->disable_data_slot[4] = false; - config->disable_data_slot[5] = false; - config->disable_data_slot[6] = false; - config->disable_data_slot[7] = false; - - config->transfer_lsb_first = false; - config->data_adjust_left_in_word = false; - config->data_adjust_left_in_slot = true; - - config->data_size = I2S_DATA_SIZE_16BIT; - - config->bit_padding = I2S_BIT_PADDING_0; - config->data_padding = I2S_DATA_PADDING_0; - - config->dma_usage = I2S_DMA_USE_SINGLE_CHANNEL_FOR_ALL; - - config->clock_unit = I2S_CLOCK_UNIT_0; - - config->line_default_state = I2S_LINE_DEFAULT_0; - - config->mode = I2S_SERIALIZER_TRANSMIT; - - config->data_pin.enable = false; - config->data_pin.gpio = 0; - config->data_pin.mux = 0; -} - -enum status_code i2s_serializer_set_config( - struct i2s_module *const module_inst, - const enum i2s_serializer serializer, - const struct i2s_serializer_config *config); -/** @} */ - -/** - * \name Serializer Enable/Disable - * @{ - */ - -/** - * \brief Enable the Specified Serializer of I2S module. - * - * Enables a Serializer in I2S module that has been previously initialized. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer I2S Serializer to enable - */ -static inline void i2s_serializer_enable( - const struct i2s_module *const module_inst, - const enum i2s_serializer serializer) -{ - uint32_t seren_bit; - - Assert(module_inst); - Assert(module_inst->hw); - - seren_bit = I2S_CTRLA_SEREN0 << serializer; - - while (module_inst->hw->SYNCBUSY.reg & seren_bit) { - /* Sync wait */ - } - module_inst->hw->CTRLA.reg |= seren_bit; -} - -/** - * \brief Disable the Specified Serializer of I2S module. - * - * Disables a Serializer in I2S module that has been previously initialized. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer I2S Serializer to disable - */ -static inline void i2s_serializer_disable( - const struct i2s_module *const module_inst, - const enum i2s_serializer serializer) -{ - uint32_t seren_bit; - - Assert(module_inst); - Assert(module_inst->hw); - - seren_bit = I2S_CTRLA_SEREN0 << serializer; - - while (module_inst->hw->SYNCBUSY.reg & seren_bit) { - /* Sync wait */ - } - module_inst->hw->CTRLA.reg &= ~seren_bit; -} -/** @} */ - -/** - * \name Status Management - * @{ - */ - -uint32_t i2s_get_status( - const struct i2s_module *const module_inst); - -void i2s_clear_status( - const struct i2s_module *const module_inst, - uint32_t status); - - -enum status_code i2s_enable_status_interrupt( - struct i2s_module *const module_inst, - uint32_t status); - -void i2s_disable_status_interrupt( - struct i2s_module *const module_inst, - uint32_t status); - -/** @}*/ - -/** - * \name Data read/write - * @{ - */ - -/** - * \brief Write a data word to the specified Serializer of I2S module - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer The Serializer to write to - * \param[in] data The data to write - * - */ -static inline void i2s_serializer_write_wait( - const struct i2s_module *const module_inst, - enum i2s_serializer serializer, - uint32_t data) -{ - uint32_t sync_bit, ready_bit; - - Assert(module_inst); - Assert(module_inst->hw); - - ready_bit = I2S_INTFLAG_TXRDY0 << serializer; - while (!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait until ready to transmit */ - } - sync_bit = I2S_SYNCBUSY_DATA0 << serializer; - while (module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait sync */ - } - /* Write data */ - module_inst->hw->DATA[serializer].reg = data; - module_inst->hw->INTFLAG.reg = ready_bit; -} - -/** - * \brief Read a data word from the specified Serializer of I2S module - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer The Serializer to read - */ -static inline uint32_t i2s_serializer_read_wait( - const struct i2s_module *const module_inst, - enum i2s_serializer serializer) -{ - uint32_t sync_bit, ready_bit; - uint32_t data; - - Assert(module_inst); - Assert(module_inst->hw); - - ready_bit = I2S_INTFLAG_RXRDY0 << serializer; - while (!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait until ready to transmit */ - } - sync_bit = I2S_SYNCBUSY_DATA0 << serializer; - while (module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait sync */ - } - /* Read data */ - data = module_inst->hw->DATA[serializer].reg; - module_inst->hw->INTFLAG.reg = ready_bit; - return data; -} - - -/** - * \brief Write buffer to the specified Serializer of I2S module - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer The Serializer to write to - * \param[in] buffer The data buffer to write - * \param[in] size Number of data words to write - * - * \return Status of the initialization procedure. - * - * \retval STATUS_OK The data was sent successfully - * \retval STATUS_INVALID_ARG An invalid buffer pointer was supplied - */ -enum status_code i2s_serializer_write_buffer_wait( - const struct i2s_module *const module_inst, - enum i2s_serializer serializer, - void *buffer, uint32_t size); - -/** - * \brief Read from the specified Serializer of I2S module to a buffer - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer The Serializer to write to - * \param[in] buffer The buffer to fill read data - * \param[in] size Number of data words to read - * - * \return Status of the initialization procedure. - * - * \retval STATUS_OK The data was sent successfully - * \retval STATUS_INVALID_ARG An invalid buffer pointer was supplied - */ -enum status_code i2s_serializer_read_buffer_wait( - const struct i2s_module *const module_inst, - enum i2s_serializer serializer, - void *buffer, uint32_t size); - -/** @} */ - -#ifdef __cplusplus -} -#endif - -/** @} */ - - -/** - * \page asfdoc_sam0_i2s_extra Extra Information for I2S Driver - * - * \section asfdoc_sam0_i2s_extra_acronyms Acronyms - * Below is a table listing the acronyms used in this module, along with their - * intended meanings. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
AcronymDescription
I2S, IISInter-IC Sound Controller
MCKMaster Clock
SCKSerial Clock
FSFrame Sync
SDSerial Data
ADCAnalog-to-Digital Converter
DACDigital-to-Analog Converter
TDMTime Division Multiplexed
PDMPulse Density Modulation
LSBLeast Significant Bit
MSBMost Significant Bit
DSPDigital Signal Processor
- * - * - * \section asfdoc_sam0_i2s_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - \ref asfdoc_sam0_system_pinmux_group "System Pin Multiplexer Driver" - * - * - * \section asfdoc_sam0_i2s_extra_errata Errata - * There are no errata related to this driver. - * - * - * \section asfdoc_sam0_i2s_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * - * - * - *
Changelog
Initial Release
- */ - -/** - * \page asfdoc_sam0_i2s_exqsg Examples for I2S Driver - * - * This is a list of the available Quick Start guides (QSGs) and example - * applications for \ref asfdoc_sam0_i2s_group. QSGs are simple examples with - * step-by-step instructions to configure and use this driver in a selection of - * use cases. Note that QSGs can be compiled as a standalone application or be - * added to the user application. - * - * - \subpage asfdoc_sam0_i2s_basic_use_case - * \if I2S_CALLBACK_MODE - * - \subpage asfdoc_sam0_i2s_callback_use_case - * \endif - * - \subpage asfdoc_sam0_i2s_dma_use_case - * - * \page asfdoc_sam0_i2s_document_revision_history Document Revision History - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Doc. Rev. - * Date - * Comments - *
B04/2015Added support for SAMDA1.
A01/2014Initial release
- */ - -#endif /* #ifndef I2S_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt.h deleted file mode 100644 index fa4878e..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt.h +++ /dev/null @@ -1,117 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ -#ifndef UTILS_INTERRUPT_H -#define UTILS_INTERRUPT_H - -//#include - -#include "interrupt/interrupt_sam_nvic.h" - -/** - * \defgroup interrupt_group Global interrupt management - * - * This is a driver for global enabling and disabling of interrupts. - * - * @{ - */ - -#if defined(__DOXYGEN__) -/** - * \def CONFIG_INTERRUPT_FORCE_INTC - * \brief Force usage of the ASF INTC driver - * - * Predefine this symbol when preprocessing to force the use of the ASF INTC driver. - * This is useful to ensure compatibility across compilers and shall be used only when required - * by the application needs. - */ -# define CONFIG_INTERRUPT_FORCE_INTC -#endif - -//! \name Global interrupt flags -//@{ -/** - * \typedef irqflags_t - * \brief Type used for holding state of interrupt flag - */ - -/** - * \def cpu_irq_enable - * \brief Enable interrupts globally - */ - -/** - * \def cpu_irq_disable - * \brief Disable interrupts globally - */ - -/** - * \fn irqflags_t cpu_irq_save(void) - * \brief Get and clear the global interrupt flags - * - * Use in conjunction with \ref cpu_irq_restore. - * - * \return Current state of interrupt flags. - * - * \note This function leaves interrupts disabled. - */ - -/** - * \fn void cpu_irq_restore(irqflags_t flags) - * \brief Restore global interrupt flags - * - * Use in conjunction with \ref cpu_irq_save. - * - * \param flags State to set interrupt flag to. - */ - -/** - * \fn bool cpu_irq_is_enabled_flags(irqflags_t flags) - * \brief Check if interrupts are globally enabled in supplied flags - * - * \param flags Currents state of interrupt flags. - * - * \return True if interrupts are enabled. - */ - -/** - * \def cpu_irq_is_enabled - * \brief Check if interrupts are globally enabled - * - * \return True if interrupts are enabled. - */ -//@} - -//! @} - -/** - * \ingroup interrupt_group - * \defgroup interrupt_deprecated_group Deprecated interrupt definitions - */ - -#endif /* UTILS_INTERRUPT_H */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c b/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c deleted file mode 100644 index d813485..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c +++ /dev/null @@ -1,69 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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 "interrupt_sam_nvic.h" - -#if !defined(__DOXYGEN__) -/* Deprecated - global flag to determine the global interrupt state. Required by - * QTouch library, however new applications should use cpu_irq_is_enabled() - * which probes the true global interrupt state from the CPU special registers. - */ -volatile bool g_interrupt_enabled = true; -#endif - -void cpu_irq_enter_critical(void) -{ - if (cpu_irq_critical_section_counter == 0) { - if (cpu_irq_is_enabled()) { - cpu_irq_disable(); - cpu_irq_prev_interrupt_state = true; - } else { - /* Make sure the to save the prev state as false */ - cpu_irq_prev_interrupt_state = false; - } - - } - - cpu_irq_critical_section_counter++; -} - -void cpu_irq_leave_critical(void) -{ - /* Check if the user is trying to leave a critical section when not in a critical section */ - Assert(cpu_irq_critical_section_counter > 0); - - cpu_irq_critical_section_counter--; - - /* Only enable global interrupts when the counter reaches 0 and the state of the global interrupt flag - was enabled when entering critical state */ - if ((cpu_irq_critical_section_counter == 0) && (cpu_irq_prev_interrupt_state)) { - cpu_irq_enable(); - } -} - diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h deleted file mode 100644 index 9b5645b..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h +++ /dev/null @@ -1,172 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef UTILS_INTERRUPT_INTERRUPT_H -#define UTILS_INTERRUPT_INTERRUPT_H - -#include -//#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \weakgroup interrupt_group - * - * @{ - */ - -/** - * \name Interrupt Service Routine definition - * - * @{ - */ - -/** - * \brief Define service routine - * - * \note For NVIC devices the interrupt service routines are predefined to - * add to vector table in binary generation, so there is no service - * register at run time. The routine collections are in exceptions.h. - * - * Usage: - * \code - ISR(foo_irq_handler) - { - // Function definition - ... - } -\endcode - * - * \param func Name for the function. - */ -# define ISR(func) \ - void func (void) - -/** - * \brief Initialize interrupt vectors - * - * For NVIC the interrupt vectors are put in vector table. So nothing - * to do to initialize them, except defined the vector function with - * right name. - * - * This must be called prior to \ref irq_register_handler. - */ -# define irq_initialize_vectors() \ - do { \ - } while(0) - -/** - * \brief Register handler for interrupt - * - * For NVIC the interrupt vectors are put in vector table. So nothing - * to do to register them, except defined the vector function with - * right name. - * - * Usage: - * \code - irq_initialize_vectors(); - irq_register_handler(foo_irq_handler); -\endcode - * - * \note The function \a func must be defined with the \ref ISR macro. - * \note The functions prototypes can be found in the device exception header - * files (exceptions.h). - */ -# define irq_register_handler(int_num, int_prio) \ - NVIC_ClearPendingIRQ( (IRQn_Type)int_num); \ - NVIC_SetPriority( (IRQn_Type)int_num, int_prio); \ - NVIC_EnableIRQ( (IRQn_Type)int_num); \ - -//@} - -# define cpu_irq_enable() \ - do { \ - g_interrupt_enabled = true; \ - __DMB(); \ - __enable_irq(); \ - } while (0) -# define cpu_irq_disable() \ - do { \ - __disable_irq(); \ - __DMB(); \ - g_interrupt_enabled = false; \ - } while (0) - -typedef uint32_t irqflags_t; - -#if !defined(__DOXYGEN__) -extern volatile bool g_interrupt_enabled; -#endif - -#define cpu_irq_is_enabled() (__get_PRIMASK() == 0) - -static volatile uint32_t cpu_irq_critical_section_counter; -static volatile bool cpu_irq_prev_interrupt_state; - -static inline irqflags_t cpu_irq_save(void) -{ - irqflags_t flags = cpu_irq_is_enabled(); - cpu_irq_disable(); - return flags; -} - -static inline bool cpu_irq_is_enabled_flags(irqflags_t flags) -{ - return (flags); -} - -static inline void cpu_irq_restore(irqflags_t flags) -{ - if (cpu_irq_is_enabled_flags(flags)) - cpu_irq_enable(); -} - -void cpu_irq_enter_critical(void); -void cpu_irq_leave_critical(void); - -/** - * \weakgroup interrupt_deprecated_group - * @{ - */ - -#define Enable_global_interrupt() cpu_irq_enable() -#define Disable_global_interrupt() cpu_irq_disable() -#define Is_global_interrupt_enabled() cpu_irq_is_enabled() - -//@} - -//@} - -#ifdef __cplusplus -} -#endif - -#endif /* UTILS_INTERRUPT_INTERRUPT_H */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c b/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c deleted file mode 100644 index 26dcc91..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c +++ /dev/null @@ -1,86 +0,0 @@ -/** - * \file - * - * \brief Global interrupt management for SAM D20, SAM3 and SAM4 (NVIC based) - * - * Copyright (c) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#include "interrupt_sam_nvic.h" - -#if !defined(__DOXYGEN__) -/* Deprecated - global flag to determine the global interrupt state. Required by - * QTouch library, however new applications should use cpu_irq_is_enabled() - * which probes the true global interrupt state from the CPU special registers. - */ -volatile bool g_interrupt_enabled = true; -#endif - -void cpu_irq_enter_critical(void) -{ - if (cpu_irq_critical_section_counter == 0) { - if (cpu_irq_is_enabled()) { - cpu_irq_disable(); - cpu_irq_prev_interrupt_state = true; - } else { - /* Make sure the to save the prev state as false */ - cpu_irq_prev_interrupt_state = false; - } - - } - - cpu_irq_critical_section_counter++; -} - -void cpu_irq_leave_critical(void) -{ - /* Check if the user is trying to leave a critical section when not in a critical section */ - Assert(cpu_irq_critical_section_counter > 0); - - cpu_irq_critical_section_counter--; - - /* Only enable global interrupts when the counter reaches 0 and the state of the global interrupt flag - was enabled when entering critical state */ - if ((cpu_irq_critical_section_counter == 0) && (cpu_irq_prev_interrupt_state)) { - cpu_irq_enable(); - } -} - diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h deleted file mode 100644 index f996e92..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h +++ /dev/null @@ -1,189 +0,0 @@ -/** - * \file - * - * \brief Global interrupt management for SAM D20, SAM3 and SAM4 (NVIC based) - * - * Copyright (c) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#ifndef UTILS_INTERRUPT_INTERRUPT_H -#define UTILS_INTERRUPT_INTERRUPT_H - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \weakgroup interrupt_group - * - * @{ - */ - -/** - * \name Interrupt Service Routine definition - * - * @{ - */ - -/** - * \brief Define service routine - * - * \note For NVIC devices the interrupt service routines are predefined to - * add to vector table in binary generation, so there is no service - * register at run time. The routine collections are in exceptions.h. - * - * Usage: - * \code - ISR(foo_irq_handler) - { - // Function definition - ... - } -\endcode - * - * \param func Name for the function. - */ -# define ISR(func) \ - void func (void) - -/** - * \brief Initialize interrupt vectors - * - * For NVIC the interrupt vectors are put in vector table. So nothing - * to do to initialize them, except defined the vector function with - * right name. - * - * This must be called prior to \ref irq_register_handler. - */ -# define irq_initialize_vectors() \ - do { \ - } while(0) - -/** - * \brief Register handler for interrupt - * - * For NVIC the interrupt vectors are put in vector table. So nothing - * to do to register them, except defined the vector function with - * right name. - * - * Usage: - * \code - irq_initialize_vectors(); - irq_register_handler(foo_irq_handler); -\endcode - * - * \note The function \a func must be defined with the \ref ISR macro. - * \note The functions prototypes can be found in the device exception header - * files (exceptions.h). - */ -# define irq_register_handler(int_num, int_prio) \ - NVIC_ClearPendingIRQ( (IRQn_Type)int_num); \ - NVIC_SetPriority( (IRQn_Type)int_num, int_prio); \ - NVIC_EnableIRQ( (IRQn_Type)int_num); \ - -//@} - -# define cpu_irq_enable() \ - do { \ - g_interrupt_enabled = true; \ - __DMB(); \ - __enable_irq(); \ - } while (0) -# define cpu_irq_disable() \ - do { \ - __disable_irq(); \ - __DMB(); \ - g_interrupt_enabled = false; \ - } while (0) - -typedef uint32_t irqflags_t; - -#if !defined(__DOXYGEN__) -extern volatile bool g_interrupt_enabled; -#endif - -#define cpu_irq_is_enabled() (__get_PRIMASK() == 0) - -static volatile uint32_t cpu_irq_critical_section_counter; -static volatile bool cpu_irq_prev_interrupt_state; - -static inline irqflags_t cpu_irq_save(void) -{ - irqflags_t flags = cpu_irq_is_enabled(); - cpu_irq_disable(); - return flags; -} - -static inline bool cpu_irq_is_enabled_flags(irqflags_t flags) -{ - return (flags); -} - -static inline void cpu_irq_restore(irqflags_t flags) -{ - if (cpu_irq_is_enabled_flags(flags)) - cpu_irq_enable(); -} - -void cpu_irq_enter_critical(void); -void cpu_irq_leave_critical(void); - -/** - * \weakgroup interrupt_deprecated_group - * @{ - */ - -#define Enable_global_interrupt() cpu_irq_enable() -#define Disable_global_interrupt() cpu_irq_disable() -#define Is_global_interrupt_enabled() cpu_irq_is_enabled() - -//@} - -//@} - -#ifdef __cplusplus -} -#endif - -#endif /* UTILS_INTERRUPT_INTERRUPT_H */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/library.properties b/feather_sensor_transmit/libraries/Adafruit_ASFcore/library.properties deleted file mode 100644 index e2af108..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=Adafruit Arduino Zero ASF Core Library -version=1.0.0 -author=Adafruit -maintainer=Adafruit -sentence=ASF (Atmel Software Framework) files used by Adafruit's Arduino Zero/SAMD21 libraries. -paragraph=ASF (Atmel Software Framework) files used by Adafruit's Arduino Zero/SAMD21 libraries. This is a dependency of other libraries like Adafruit_ZeroTimer. -category=Other -url=https://github.com/adafruit/Adafruit_ASFcore -architectures=* diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/parts.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/parts.h deleted file mode 100644 index 40be022..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/parts.h +++ /dev/null @@ -1,1601 +0,0 @@ -/** - * \file - * - * \brief Atmel part identification macros - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#ifndef ATMEL_PARTS_H -#define ATMEL_PARTS_H - -/** - * \defgroup part_macros_group Atmel part identification macros - * - * This collection of macros identify which series and families that the various - * Atmel parts belong to. These can be used to select part-dependent sections of - * code at compile time. - * - * @{ - */ - -/** - * \name Convenience macros for part checking - * @{ - */ -/* ! Check GCC and IAR part definition for 8-bit AVR */ -#define AVR8_PART_IS_DEFINED(part) \ - (defined(__ ## part ## __) || defined(__AVR_ ## part ## __)) - -/* ! Check GCC and IAR part definition for 32-bit AVR */ -#define AVR32_PART_IS_DEFINED(part) \ - (defined(__AT32 ## part ## __) || defined(__AVR32_ ## part ## __)) - -/* ! Check GCC and IAR part definition for SAM */ -#define SAM_PART_IS_DEFINED(part) (defined(__ ## part ## __)) -/** @} */ - -/** - * \defgroup uc3_part_macros_group AVR UC3 parts - * @{ - */ - -/** - * \name AVR UC3 A series - * @{ - */ -#define UC3A0 ( \ - AVR32_PART_IS_DEFINED(UC3A0128) || \ - AVR32_PART_IS_DEFINED(UC3A0256) || \ - AVR32_PART_IS_DEFINED(UC3A0512) \ - ) - -#define UC3A1 ( \ - AVR32_PART_IS_DEFINED(UC3A1128) || \ - AVR32_PART_IS_DEFINED(UC3A1256) || \ - AVR32_PART_IS_DEFINED(UC3A1512) \ - ) - -#define UC3A3 ( \ - AVR32_PART_IS_DEFINED(UC3A364) || \ - AVR32_PART_IS_DEFINED(UC3A364S) || \ - AVR32_PART_IS_DEFINED(UC3A3128) || \ - AVR32_PART_IS_DEFINED(UC3A3128S) || \ - AVR32_PART_IS_DEFINED(UC3A3256) || \ - AVR32_PART_IS_DEFINED(UC3A3256S) \ - ) - -#define UC3A4 ( \ - AVR32_PART_IS_DEFINED(UC3A464) || \ - AVR32_PART_IS_DEFINED(UC3A464S) || \ - AVR32_PART_IS_DEFINED(UC3A4128) || \ - AVR32_PART_IS_DEFINED(UC3A4128S) || \ - AVR32_PART_IS_DEFINED(UC3A4256) || \ - AVR32_PART_IS_DEFINED(UC3A4256S) \ - ) -/** @} */ - -/** - * \name AVR UC3 B series - * @{ - */ -#define UC3B0 ( \ - AVR32_PART_IS_DEFINED(UC3B064) || \ - AVR32_PART_IS_DEFINED(UC3B0128) || \ - AVR32_PART_IS_DEFINED(UC3B0256) || \ - AVR32_PART_IS_DEFINED(UC3B0512) \ - ) - -#define UC3B1 ( \ - AVR32_PART_IS_DEFINED(UC3B164) || \ - AVR32_PART_IS_DEFINED(UC3B1128) || \ - AVR32_PART_IS_DEFINED(UC3B1256) || \ - AVR32_PART_IS_DEFINED(UC3B1512) \ - ) -/** @} */ - -/** - * \name AVR UC3 C series - * @{ - */ -#define UC3C0 ( \ - AVR32_PART_IS_DEFINED(UC3C064C) || \ - AVR32_PART_IS_DEFINED(UC3C0128C) || \ - AVR32_PART_IS_DEFINED(UC3C0256C) || \ - AVR32_PART_IS_DEFINED(UC3C0512C) \ - ) - -#define UC3C1 ( \ - AVR32_PART_IS_DEFINED(UC3C164C) || \ - AVR32_PART_IS_DEFINED(UC3C1128C) || \ - AVR32_PART_IS_DEFINED(UC3C1256C) || \ - AVR32_PART_IS_DEFINED(UC3C1512C) \ - ) - -#define UC3C2 ( \ - AVR32_PART_IS_DEFINED(UC3C264C) || \ - AVR32_PART_IS_DEFINED(UC3C2128C) || \ - AVR32_PART_IS_DEFINED(UC3C2256C) || \ - AVR32_PART_IS_DEFINED(UC3C2512C) \ - ) -/** @} */ - -/** - * \name AVR UC3 D series - * @{ - */ -#define UC3D3 ( \ - AVR32_PART_IS_DEFINED(UC64D3) || \ - AVR32_PART_IS_DEFINED(UC128D3) \ - ) - -#define UC3D4 ( \ - AVR32_PART_IS_DEFINED(UC64D4) || \ - AVR32_PART_IS_DEFINED(UC128D4) \ - ) -/** @} */ - -/** - * \name AVR UC3 L series - * @{ - */ -#define UC3L0 ( \ - AVR32_PART_IS_DEFINED(UC3L016) || \ - AVR32_PART_IS_DEFINED(UC3L032) || \ - AVR32_PART_IS_DEFINED(UC3L064) \ - ) - -#define UC3L0128 ( \ - AVR32_PART_IS_DEFINED(UC3L0128) \ - ) - -#define UC3L0256 ( \ - AVR32_PART_IS_DEFINED(UC3L0256) \ - ) - -#define UC3L3 ( \ - AVR32_PART_IS_DEFINED(UC64L3U) || \ - AVR32_PART_IS_DEFINED(UC128L3U) || \ - AVR32_PART_IS_DEFINED(UC256L3U) \ - ) - -#define UC3L4 ( \ - AVR32_PART_IS_DEFINED(UC64L4U) || \ - AVR32_PART_IS_DEFINED(UC128L4U) || \ - AVR32_PART_IS_DEFINED(UC256L4U) \ - ) - -#define UC3L3_L4 (UC3L3 || UC3L4) -/** @} */ - -/** - * \name AVR UC3 families - * @{ - */ -/** AVR UC3 A family */ -#define UC3A (UC3A0 || UC3A1 || UC3A3 || UC3A4) - -/** AVR UC3 B family */ -#define UC3B (UC3B0 || UC3B1) - -/** AVR UC3 C family */ -#define UC3C (UC3C0 || UC3C1 || UC3C2) - -/** AVR UC3 D family */ -#define UC3D (UC3D3 || UC3D4) - -/** AVR UC3 L family */ -#define UC3L (UC3L0 || UC3L0128 || UC3L0256 || UC3L3_L4) -/** @} */ - -/** AVR UC3 product line */ -#define UC3 (UC3A || UC3B || UC3C || UC3D || UC3L) - -/** @} */ - -/** - * \defgroup xmega_part_macros_group AVR XMEGA parts - * @{ - */ - -/** - * \name AVR XMEGA A series - * @{ - */ -#define XMEGA_A1 ( \ - AVR8_PART_IS_DEFINED(ATxmega64A1) || \ - AVR8_PART_IS_DEFINED(ATxmega128A1) \ - ) - -#define XMEGA_A3 ( \ - AVR8_PART_IS_DEFINED(ATxmega64A3) || \ - AVR8_PART_IS_DEFINED(ATxmega128A3) || \ - AVR8_PART_IS_DEFINED(ATxmega192A3) || \ - AVR8_PART_IS_DEFINED(ATxmega256A3) \ - ) - -#define XMEGA_A3B ( \ - AVR8_PART_IS_DEFINED(ATxmega256A3B) \ - ) - -#define XMEGA_A4 ( \ - AVR8_PART_IS_DEFINED(ATxmega16A4) || \ - AVR8_PART_IS_DEFINED(ATxmega32A4) \ - ) -/** @} */ - -/** - * \name AVR XMEGA AU series - * @{ - */ -#define XMEGA_A1U ( \ - AVR8_PART_IS_DEFINED(ATxmega64A1U) || \ - AVR8_PART_IS_DEFINED(ATxmega128A1U) \ - ) - -#define XMEGA_A3U ( \ - AVR8_PART_IS_DEFINED(ATxmega64A3U) || \ - AVR8_PART_IS_DEFINED(ATxmega128A3U) || \ - AVR8_PART_IS_DEFINED(ATxmega192A3U) || \ - AVR8_PART_IS_DEFINED(ATxmega256A3U) \ - ) - -#define XMEGA_A3BU ( \ - AVR8_PART_IS_DEFINED(ATxmega256A3BU) \ - ) - -#define XMEGA_A4U ( \ - AVR8_PART_IS_DEFINED(ATxmega16A4U) || \ - AVR8_PART_IS_DEFINED(ATxmega32A4U) || \ - AVR8_PART_IS_DEFINED(ATxmega64A4U) || \ - AVR8_PART_IS_DEFINED(ATxmega128A4U) \ - ) -/** @} */ - -/** - * \name AVR XMEGA B series - * @{ - */ -#define XMEGA_B1 ( \ - AVR8_PART_IS_DEFINED(ATxmega64B1) || \ - AVR8_PART_IS_DEFINED(ATxmega128B1) \ - ) - -#define XMEGA_B3 ( \ - AVR8_PART_IS_DEFINED(ATxmega64B3) || \ - AVR8_PART_IS_DEFINED(ATxmega128B3) \ - ) -/** @} */ - -/** - * \name AVR XMEGA C series - * @{ - */ -#define XMEGA_C3 ( \ - AVR8_PART_IS_DEFINED(ATxmega384C3) || \ - AVR8_PART_IS_DEFINED(ATxmega256C3) || \ - AVR8_PART_IS_DEFINED(ATxmega192C3) || \ - AVR8_PART_IS_DEFINED(ATxmega128C3) || \ - AVR8_PART_IS_DEFINED(ATxmega64C3) || \ - AVR8_PART_IS_DEFINED(ATxmega32C3) \ - ) - -#define XMEGA_C4 ( \ - AVR8_PART_IS_DEFINED(ATxmega32C4) || \ - AVR8_PART_IS_DEFINED(ATxmega16C4) \ - ) -/** @} */ - -/** - * \name AVR XMEGA D series - * @{ - */ -#define XMEGA_D3 ( \ - AVR8_PART_IS_DEFINED(ATxmega32D3) || \ - AVR8_PART_IS_DEFINED(ATxmega64D3) || \ - AVR8_PART_IS_DEFINED(ATxmega128D3) || \ - AVR8_PART_IS_DEFINED(ATxmega192D3) || \ - AVR8_PART_IS_DEFINED(ATxmega256D3) || \ - AVR8_PART_IS_DEFINED(ATxmega384D3) \ - ) - -#define XMEGA_D4 ( \ - AVR8_PART_IS_DEFINED(ATxmega16D4) || \ - AVR8_PART_IS_DEFINED(ATxmega32D4) || \ - AVR8_PART_IS_DEFINED(ATxmega64D4) || \ - AVR8_PART_IS_DEFINED(ATxmega128D4) \ - ) -/** @} */ - -/** - * \name AVR XMEGA E series - * @{ - */ -#define XMEGA_E5 ( \ - AVR8_PART_IS_DEFINED(ATxmega8E5) || \ - AVR8_PART_IS_DEFINED(ATxmega16E5) || \ - AVR8_PART_IS_DEFINED(ATxmega32E5) \ - ) -/** @} */ - - -/** - * \name AVR XMEGA families - * @{ - */ -/** AVR XMEGA A family */ -#define XMEGA_A (XMEGA_A1 || XMEGA_A3 || XMEGA_A3B || XMEGA_A4) - -/** AVR XMEGA AU family */ -#define XMEGA_AU (XMEGA_A1U || XMEGA_A3U || XMEGA_A3BU || XMEGA_A4U) - -/** AVR XMEGA B family */ -#define XMEGA_B (XMEGA_B1 || XMEGA_B3) - -/** AVR XMEGA C family */ -#define XMEGA_C (XMEGA_C3 || XMEGA_C4) - -/** AVR XMEGA D family */ -#define XMEGA_D (XMEGA_D3 || XMEGA_D4) - -/** AVR XMEGA E family */ -#define XMEGA_E (XMEGA_E5) -/** @} */ - - -/** AVR XMEGA product line */ -#define XMEGA (XMEGA_A || XMEGA_AU || XMEGA_B || XMEGA_C || XMEGA_D || XMEGA_E) - -/** @} */ - -/** - * \defgroup mega_part_macros_group megaAVR parts - * - * \note These megaAVR groupings are based on the groups in AVR Libc for the - * part header files. They are not names of official megaAVR device series or - * families. - * - * @{ - */ - -/** - * \name ATmegaxx0/xx1 subgroups - * @{ - */ -#define MEGA_XX0 ( \ - AVR8_PART_IS_DEFINED(ATmega640) || \ - AVR8_PART_IS_DEFINED(ATmega1280) || \ - AVR8_PART_IS_DEFINED(ATmega2560) \ - ) - -#define MEGA_XX1 ( \ - AVR8_PART_IS_DEFINED(ATmega1281) || \ - AVR8_PART_IS_DEFINED(ATmega2561) \ - ) -/** @} */ - -/** - * \name megaAVR groups - * @{ - */ -/** ATmegaxx0/xx1 group */ -#define MEGA_XX0_1 (MEGA_XX0 || MEGA_XX1) - -/** ATmegaxx4 group */ -#define MEGA_XX4 ( \ - AVR8_PART_IS_DEFINED(ATmega164A) || \ - AVR8_PART_IS_DEFINED(ATmega164PA) || \ - AVR8_PART_IS_DEFINED(ATmega324A) || \ - AVR8_PART_IS_DEFINED(ATmega324PA) || \ - AVR8_PART_IS_DEFINED(ATmega644) || \ - AVR8_PART_IS_DEFINED(ATmega644A) || \ - AVR8_PART_IS_DEFINED(ATmega644PA) || \ - AVR8_PART_IS_DEFINED(ATmega1284P) || \ - AVR8_PART_IS_DEFINED(ATmega128RFA1) \ - ) - -/** ATmegaxx4 group */ -#define MEGA_XX4_A ( \ - AVR8_PART_IS_DEFINED(ATmega164A) || \ - AVR8_PART_IS_DEFINED(ATmega164PA) || \ - AVR8_PART_IS_DEFINED(ATmega324A) || \ - AVR8_PART_IS_DEFINED(ATmega324PA) || \ - AVR8_PART_IS_DEFINED(ATmega644A) || \ - AVR8_PART_IS_DEFINED(ATmega644PA) || \ - AVR8_PART_IS_DEFINED(ATmega1284P) \ - ) - -/** ATmegaxx8 group */ -#define MEGA_XX8 ( \ - AVR8_PART_IS_DEFINED(ATmega48) || \ - AVR8_PART_IS_DEFINED(ATmega48A) || \ - AVR8_PART_IS_DEFINED(ATmega48PA) || \ - AVR8_PART_IS_DEFINED(ATmega88) || \ - AVR8_PART_IS_DEFINED(ATmega88A) || \ - AVR8_PART_IS_DEFINED(ATmega88PA) || \ - AVR8_PART_IS_DEFINED(ATmega168) || \ - AVR8_PART_IS_DEFINED(ATmega168A) || \ - AVR8_PART_IS_DEFINED(ATmega168PA) || \ - AVR8_PART_IS_DEFINED(ATmega328) || \ - AVR8_PART_IS_DEFINED(ATmega328P) \ - ) - -/** ATmegaxx8A/P/PA group */ -#define MEGA_XX8_A ( \ - AVR8_PART_IS_DEFINED(ATmega48A) || \ - AVR8_PART_IS_DEFINED(ATmega48PA) || \ - AVR8_PART_IS_DEFINED(ATmega88A) || \ - AVR8_PART_IS_DEFINED(ATmega88PA) || \ - AVR8_PART_IS_DEFINED(ATmega168A) || \ - AVR8_PART_IS_DEFINED(ATmega168PA) || \ - AVR8_PART_IS_DEFINED(ATmega328P) \ - ) - -/** ATmegaxx group */ -#define MEGA_XX ( \ - AVR8_PART_IS_DEFINED(ATmega16) || \ - AVR8_PART_IS_DEFINED(ATmega16A) || \ - AVR8_PART_IS_DEFINED(ATmega32) || \ - AVR8_PART_IS_DEFINED(ATmega32A) || \ - AVR8_PART_IS_DEFINED(ATmega64) || \ - AVR8_PART_IS_DEFINED(ATmega64A) || \ - AVR8_PART_IS_DEFINED(ATmega128) || \ - AVR8_PART_IS_DEFINED(ATmega128A) \ - ) - -/** ATmegaxxA/P/PA group */ -#define MEGA_XX_A ( \ - AVR8_PART_IS_DEFINED(ATmega16A) || \ - AVR8_PART_IS_DEFINED(ATmega32A) || \ - AVR8_PART_IS_DEFINED(ATmega64A) || \ - AVR8_PART_IS_DEFINED(ATmega128A) \ - ) -/** ATmegaxxRFA1 group */ -#define MEGA_RFA1 ( \ - AVR8_PART_IS_DEFINED(ATmega128RFA1) \ - ) - -/** ATmegaxxRFR2 group */ -#define MEGA_RFR2 ( \ - AVR8_PART_IS_DEFINED(ATmega64RFR2) || \ - AVR8_PART_IS_DEFINED(ATmega128RFR2) || \ - AVR8_PART_IS_DEFINED(ATmega256RFR2) || \ - AVR8_PART_IS_DEFINED(ATmega644RFR2) || \ - AVR8_PART_IS_DEFINED(ATmega1284RFR2) || \ - AVR8_PART_IS_DEFINED(ATmega2564RFR2) \ - ) - - -/** ATmegaxxRFxx group */ -#define MEGA_RF (MEGA_RFA1 || MEGA_RFR2) - -/** - * \name ATmegaxx_un0/un1/un2 subgroups - * @{ - */ -#define MEGA_XX_UN0 ( \ - AVR8_PART_IS_DEFINED(ATmega16) || \ - AVR8_PART_IS_DEFINED(ATmega16A) || \ - AVR8_PART_IS_DEFINED(ATmega32) || \ - AVR8_PART_IS_DEFINED(ATmega32A) \ - ) - -/** ATmegaxx group without power reduction and - * And interrupt sense register. - */ -#define MEGA_XX_UN1 ( \ - AVR8_PART_IS_DEFINED(ATmega64) || \ - AVR8_PART_IS_DEFINED(ATmega64A) || \ - AVR8_PART_IS_DEFINED(ATmega128) || \ - AVR8_PART_IS_DEFINED(ATmega128A) \ - ) - -/** ATmegaxx group without power reduction and - * And interrupt sense register. - */ -#define MEGA_XX_UN2 ( \ - AVR8_PART_IS_DEFINED(ATmega169P) || \ - AVR8_PART_IS_DEFINED(ATmega169PA) || \ - AVR8_PART_IS_DEFINED(ATmega329P) || \ - AVR8_PART_IS_DEFINED(ATmega329PA) \ - ) - -/** Devices added to complete megaAVR offering. - * Please do not use this group symbol as it is not intended - * to be permanent: the devices should be regrouped. - */ -#define MEGA_UNCATEGORIZED ( \ - AVR8_PART_IS_DEFINED(AT90CAN128) || \ - AVR8_PART_IS_DEFINED(AT90CAN32) || \ - AVR8_PART_IS_DEFINED(AT90CAN64) || \ - AVR8_PART_IS_DEFINED(AT90PWM1) || \ - AVR8_PART_IS_DEFINED(AT90PWM216) || \ - AVR8_PART_IS_DEFINED(AT90PWM2B) || \ - AVR8_PART_IS_DEFINED(AT90PWM316) || \ - AVR8_PART_IS_DEFINED(AT90PWM3B) || \ - AVR8_PART_IS_DEFINED(AT90PWM81) || \ - AVR8_PART_IS_DEFINED(AT90USB1286) || \ - AVR8_PART_IS_DEFINED(AT90USB1287) || \ - AVR8_PART_IS_DEFINED(AT90USB162) || \ - AVR8_PART_IS_DEFINED(AT90USB646) || \ - AVR8_PART_IS_DEFINED(AT90USB647) || \ - AVR8_PART_IS_DEFINED(AT90USB82) || \ - AVR8_PART_IS_DEFINED(ATmega1284) || \ - AVR8_PART_IS_DEFINED(ATmega162) || \ - AVR8_PART_IS_DEFINED(ATmega164P) || \ - AVR8_PART_IS_DEFINED(ATmega165A) || \ - AVR8_PART_IS_DEFINED(ATmega165P) || \ - AVR8_PART_IS_DEFINED(ATmega165PA) || \ - AVR8_PART_IS_DEFINED(ATmega168P) || \ - AVR8_PART_IS_DEFINED(ATmega169A) || \ - AVR8_PART_IS_DEFINED(ATmega16M1) || \ - AVR8_PART_IS_DEFINED(ATmega16U2) || \ - AVR8_PART_IS_DEFINED(ATmega16U4) || \ - AVR8_PART_IS_DEFINED(ATmega256RFA2) || \ - AVR8_PART_IS_DEFINED(ATmega324P) || \ - AVR8_PART_IS_DEFINED(ATmega325) || \ - AVR8_PART_IS_DEFINED(ATmega3250) || \ - AVR8_PART_IS_DEFINED(ATmega3250A) || \ - AVR8_PART_IS_DEFINED(ATmega3250P) || \ - AVR8_PART_IS_DEFINED(ATmega3250PA) || \ - AVR8_PART_IS_DEFINED(ATmega325A) || \ - AVR8_PART_IS_DEFINED(ATmega325P) || \ - AVR8_PART_IS_DEFINED(ATmega325PA) || \ - AVR8_PART_IS_DEFINED(ATmega329) || \ - AVR8_PART_IS_DEFINED(ATmega3290) || \ - AVR8_PART_IS_DEFINED(ATmega3290A) || \ - AVR8_PART_IS_DEFINED(ATmega3290P) || \ - AVR8_PART_IS_DEFINED(ATmega3290PA) || \ - AVR8_PART_IS_DEFINED(ATmega329A) || \ - AVR8_PART_IS_DEFINED(ATmega32M1) || \ - AVR8_PART_IS_DEFINED(ATmega32U2) || \ - AVR8_PART_IS_DEFINED(ATmega32U4) || \ - AVR8_PART_IS_DEFINED(ATmega48P) || \ - AVR8_PART_IS_DEFINED(ATmega644P) || \ - AVR8_PART_IS_DEFINED(ATmega645) || \ - AVR8_PART_IS_DEFINED(ATmega6450) || \ - AVR8_PART_IS_DEFINED(ATmega6450A) || \ - AVR8_PART_IS_DEFINED(ATmega6450P) || \ - AVR8_PART_IS_DEFINED(ATmega645A) || \ - AVR8_PART_IS_DEFINED(ATmega645P) || \ - AVR8_PART_IS_DEFINED(ATmega649) || \ - AVR8_PART_IS_DEFINED(ATmega6490) || \ - AVR8_PART_IS_DEFINED(ATmega6490A) || \ - AVR8_PART_IS_DEFINED(ATmega6490P) || \ - AVR8_PART_IS_DEFINED(ATmega649A) || \ - AVR8_PART_IS_DEFINED(ATmega649P) || \ - AVR8_PART_IS_DEFINED(ATmega64M1) || \ - AVR8_PART_IS_DEFINED(ATmega64RFA2) || \ - AVR8_PART_IS_DEFINED(ATmega8) || \ - AVR8_PART_IS_DEFINED(ATmega8515) || \ - AVR8_PART_IS_DEFINED(ATmega8535) || \ - AVR8_PART_IS_DEFINED(ATmega88P) || \ - AVR8_PART_IS_DEFINED(ATmega8A) || \ - AVR8_PART_IS_DEFINED(ATmega8U2) \ - ) - -/** Unspecified group */ -#define MEGA_UNSPECIFIED (MEGA_XX_UN0 || MEGA_XX_UN1 || MEGA_XX_UN2 || \ - MEGA_UNCATEGORIZED) - -/** @} */ - -/** megaAVR product line */ -#define MEGA (MEGA_XX0_1 || MEGA_XX4 || MEGA_XX8 || MEGA_XX || MEGA_RF || \ - MEGA_UNSPECIFIED) - -/** @} */ - -/** - * \defgroup tiny_part_macros_group tinyAVR parts - * - * @{ - */ - -/** - * \name tinyAVR groups - * @{ - */ - -/** Devices added to complete tinyAVR offering. - * Please do not use this group symbol as it is not intended - * to be permanent: the devices should be regrouped. - */ -#define TINY_UNCATEGORIZED ( \ - AVR8_PART_IS_DEFINED(ATtiny10) || \ - AVR8_PART_IS_DEFINED(ATtiny13) || \ - AVR8_PART_IS_DEFINED(ATtiny13A) || \ - AVR8_PART_IS_DEFINED(ATtiny1634) || \ - AVR8_PART_IS_DEFINED(ATtiny167) || \ - AVR8_PART_IS_DEFINED(ATtiny20) || \ - AVR8_PART_IS_DEFINED(ATtiny2313) || \ - AVR8_PART_IS_DEFINED(ATtiny2313A) || \ - AVR8_PART_IS_DEFINED(ATtiny24) || \ - AVR8_PART_IS_DEFINED(ATtiny24A) || \ - AVR8_PART_IS_DEFINED(ATtiny25) || \ - AVR8_PART_IS_DEFINED(ATtiny26) || \ - AVR8_PART_IS_DEFINED(ATtiny261) || \ - AVR8_PART_IS_DEFINED(ATtiny261A) || \ - AVR8_PART_IS_DEFINED(ATtiny4) || \ - AVR8_PART_IS_DEFINED(ATtiny40) || \ - AVR8_PART_IS_DEFINED(ATtiny4313) || \ - AVR8_PART_IS_DEFINED(ATtiny43U) || \ - AVR8_PART_IS_DEFINED(ATtiny44) || \ - AVR8_PART_IS_DEFINED(ATtiny44A) || \ - AVR8_PART_IS_DEFINED(ATtiny45) || \ - AVR8_PART_IS_DEFINED(ATtiny461) || \ - AVR8_PART_IS_DEFINED(ATtiny461A) || \ - AVR8_PART_IS_DEFINED(ATtiny48) || \ - AVR8_PART_IS_DEFINED(ATtiny5) || \ - AVR8_PART_IS_DEFINED(ATtiny828) || \ - AVR8_PART_IS_DEFINED(ATtiny84) || \ - AVR8_PART_IS_DEFINED(ATtiny84A) || \ - AVR8_PART_IS_DEFINED(ATtiny85) || \ - AVR8_PART_IS_DEFINED(ATtiny861) || \ - AVR8_PART_IS_DEFINED(ATtiny861A) || \ - AVR8_PART_IS_DEFINED(ATtiny87) || \ - AVR8_PART_IS_DEFINED(ATtiny88) || \ - AVR8_PART_IS_DEFINED(ATtiny9) \ - ) - -/** @} */ - -/** tinyAVR product line */ -#define TINY (TINY_UNCATEGORIZED) - -/** @} */ - -/** - * \defgroup sam_part_macros_group SAM parts - * @{ - */ - -/** - * \name SAM3S series - * @{ - */ -#define SAM3S1 ( \ - SAM_PART_IS_DEFINED(SAM3S1A) || \ - SAM_PART_IS_DEFINED(SAM3S1B) || \ - SAM_PART_IS_DEFINED(SAM3S1C) \ - ) - -#define SAM3S2 ( \ - SAM_PART_IS_DEFINED(SAM3S2A) || \ - SAM_PART_IS_DEFINED(SAM3S2B) || \ - SAM_PART_IS_DEFINED(SAM3S2C) \ - ) - -#define SAM3S4 ( \ - SAM_PART_IS_DEFINED(SAM3S4A) || \ - SAM_PART_IS_DEFINED(SAM3S4B) || \ - SAM_PART_IS_DEFINED(SAM3S4C) \ - ) - -#define SAM3S8 ( \ - SAM_PART_IS_DEFINED(SAM3S8B) || \ - SAM_PART_IS_DEFINED(SAM3S8C) \ - ) - -#define SAM3SD8 ( \ - SAM_PART_IS_DEFINED(SAM3SD8B) || \ - SAM_PART_IS_DEFINED(SAM3SD8C) \ - ) -/** @} */ - -/** - * \name SAM3U series - * @{ - */ -#define SAM3U1 ( \ - SAM_PART_IS_DEFINED(SAM3U1C) || \ - SAM_PART_IS_DEFINED(SAM3U1E) \ - ) - -#define SAM3U2 ( \ - SAM_PART_IS_DEFINED(SAM3U2C) || \ - SAM_PART_IS_DEFINED(SAM3U2E) \ - ) - -#define SAM3U4 ( \ - SAM_PART_IS_DEFINED(SAM3U4C) || \ - SAM_PART_IS_DEFINED(SAM3U4E) \ - ) -/** @} */ - -/** - * \name SAM3N series - * @{ - */ -#define SAM3N00 ( \ - SAM_PART_IS_DEFINED(SAM3N00A) || \ - SAM_PART_IS_DEFINED(SAM3N00B) \ - ) - -#define SAM3N0 ( \ - SAM_PART_IS_DEFINED(SAM3N0A) || \ - SAM_PART_IS_DEFINED(SAM3N0B) || \ - SAM_PART_IS_DEFINED(SAM3N0C) \ - ) - -#define SAM3N1 ( \ - SAM_PART_IS_DEFINED(SAM3N1A) || \ - SAM_PART_IS_DEFINED(SAM3N1B) || \ - SAM_PART_IS_DEFINED(SAM3N1C) \ - ) - -#define SAM3N2 ( \ - SAM_PART_IS_DEFINED(SAM3N2A) || \ - SAM_PART_IS_DEFINED(SAM3N2B) || \ - SAM_PART_IS_DEFINED(SAM3N2C) \ - ) - -#define SAM3N4 ( \ - SAM_PART_IS_DEFINED(SAM3N4A) || \ - SAM_PART_IS_DEFINED(SAM3N4B) || \ - SAM_PART_IS_DEFINED(SAM3N4C) \ - ) -/** @} */ - -/** - * \name SAM3X series - * @{ - */ -#define SAM3X4 ( \ - SAM_PART_IS_DEFINED(SAM3X4C) || \ - SAM_PART_IS_DEFINED(SAM3X4E) \ - ) - -#define SAM3X8 ( \ - SAM_PART_IS_DEFINED(SAM3X8C) || \ - SAM_PART_IS_DEFINED(SAM3X8E) || \ - SAM_PART_IS_DEFINED(SAM3X8H) \ - ) -/** @} */ - -/** - * \name SAM3A series - * @{ - */ -#define SAM3A4 ( \ - SAM_PART_IS_DEFINED(SAM3A4C) \ - ) - -#define SAM3A8 ( \ - SAM_PART_IS_DEFINED(SAM3A8C) \ - ) -/** @} */ - -/** - * \name SAM4S series - * @{ - */ -#define SAM4S2 ( \ - SAM_PART_IS_DEFINED(SAM4S2A) || \ - SAM_PART_IS_DEFINED(SAM4S2B) || \ - SAM_PART_IS_DEFINED(SAM4S2C) \ - ) - -#define SAM4S4 ( \ - SAM_PART_IS_DEFINED(SAM4S4A) || \ - SAM_PART_IS_DEFINED(SAM4S4B) || \ - SAM_PART_IS_DEFINED(SAM4S4C) \ - ) - -#define SAM4S8 ( \ - SAM_PART_IS_DEFINED(SAM4S8B) || \ - SAM_PART_IS_DEFINED(SAM4S8C) \ - ) - -#define SAM4S16 ( \ - SAM_PART_IS_DEFINED(SAM4S16B) || \ - SAM_PART_IS_DEFINED(SAM4S16C) \ - ) - -#define SAM4SA16 ( \ - SAM_PART_IS_DEFINED(SAM4SA16B) || \ - SAM_PART_IS_DEFINED(SAM4SA16C) \ - ) - -#define SAM4SD16 ( \ - SAM_PART_IS_DEFINED(SAM4SD16B) || \ - SAM_PART_IS_DEFINED(SAM4SD16C) \ - ) - -#define SAM4SD32 ( \ - SAM_PART_IS_DEFINED(SAM4SD32B) || \ - SAM_PART_IS_DEFINED(SAM4SD32C) \ - ) -/** @} */ - -/** - * \name SAM4L series - * @{ - */ -#define SAM4LS ( \ - SAM_PART_IS_DEFINED(SAM4LS2A) || \ - SAM_PART_IS_DEFINED(SAM4LS2B) || \ - SAM_PART_IS_DEFINED(SAM4LS2C) || \ - SAM_PART_IS_DEFINED(SAM4LS4A) || \ - SAM_PART_IS_DEFINED(SAM4LS4B) || \ - SAM_PART_IS_DEFINED(SAM4LS4C) || \ - SAM_PART_IS_DEFINED(SAM4LS8A) || \ - SAM_PART_IS_DEFINED(SAM4LS8B) || \ - SAM_PART_IS_DEFINED(SAM4LS8C) \ - ) - -#define SAM4LC ( \ - SAM_PART_IS_DEFINED(SAM4LC2A) || \ - SAM_PART_IS_DEFINED(SAM4LC2B) || \ - SAM_PART_IS_DEFINED(SAM4LC2C) || \ - SAM_PART_IS_DEFINED(SAM4LC4A) || \ - SAM_PART_IS_DEFINED(SAM4LC4B) || \ - SAM_PART_IS_DEFINED(SAM4LC4C) || \ - SAM_PART_IS_DEFINED(SAM4LC8A) || \ - SAM_PART_IS_DEFINED(SAM4LC8B) || \ - SAM_PART_IS_DEFINED(SAM4LC8C) \ - ) -/** @} */ - -/** - * \name SAMD20 series - * @{ - */ -#define SAMD20J ( \ - SAM_PART_IS_DEFINED(SAMD20J14) || \ - SAM_PART_IS_DEFINED(SAMD20J15) || \ - SAM_PART_IS_DEFINED(SAMD20J16) || \ - SAM_PART_IS_DEFINED(SAMD20J17) || \ - SAM_PART_IS_DEFINED(SAMD20J18) \ - ) - -#define SAMD20G ( \ - SAM_PART_IS_DEFINED(SAMD20G14) || \ - SAM_PART_IS_DEFINED(SAMD20G15) || \ - SAM_PART_IS_DEFINED(SAMD20G16) || \ - SAM_PART_IS_DEFINED(SAMD20G17) || \ - SAM_PART_IS_DEFINED(SAMD20G17U) || \ - SAM_PART_IS_DEFINED(SAMD20G18) || \ - SAM_PART_IS_DEFINED(SAMD20G18U) \ - ) - -#define SAMD20E ( \ - SAM_PART_IS_DEFINED(SAMD20E14) || \ - SAM_PART_IS_DEFINED(SAMD20E15) || \ - SAM_PART_IS_DEFINED(SAMD20E16) || \ - SAM_PART_IS_DEFINED(SAMD20E17) || \ - SAM_PART_IS_DEFINED(SAMD20E18) \ - ) -/** @} */ - -/** - * \name SAMD21 series - * @{ - */ -#define SAMD21J ( \ - SAM_PART_IS_DEFINED(SAMD21J15A) || \ - SAM_PART_IS_DEFINED(SAMD21J16A) || \ - SAM_PART_IS_DEFINED(SAMD21J17A) || \ - SAM_PART_IS_DEFINED(SAMD21J18A) || \ - SAM_PART_IS_DEFINED(SAMD21J15B) || \ - SAM_PART_IS_DEFINED(SAMD21J16B) \ - ) - -#define SAMD21G ( \ - SAM_PART_IS_DEFINED(SAMD21G15A) || \ - SAM_PART_IS_DEFINED(SAMD21G16A) || \ - SAM_PART_IS_DEFINED(SAMD21G17A) || \ - SAM_PART_IS_DEFINED(SAMD21G17AU) || \ - SAM_PART_IS_DEFINED(SAMD21G18A) || \ - SAM_PART_IS_DEFINED(SAMD21G18AU) || \ - SAM_PART_IS_DEFINED(SAMD21G15B) || \ - SAM_PART_IS_DEFINED(SAMD21G16B) || \ - SAM_PART_IS_DEFINED(SAMD21G15L) || \ - SAM_PART_IS_DEFINED(SAMD21G16L) \ - ) - -#define SAMD21GXXL ( \ - SAM_PART_IS_DEFINED(SAMD21G15L) || \ - SAM_PART_IS_DEFINED(SAMD21G16L) \ - ) - -#define SAMD21E ( \ - SAM_PART_IS_DEFINED(SAMD21E15A) || \ - SAM_PART_IS_DEFINED(SAMD21E16A) || \ - SAM_PART_IS_DEFINED(SAMD21E17A) || \ - SAM_PART_IS_DEFINED(SAMD21E18A) || \ - SAM_PART_IS_DEFINED(SAMD21E15B) || \ - SAM_PART_IS_DEFINED(SAMD21E15BU) || \ - SAM_PART_IS_DEFINED(SAMD21E16B) || \ - SAM_PART_IS_DEFINED(SAMD21E16BU) || \ - SAM_PART_IS_DEFINED(SAMD21E15L) || \ - SAM_PART_IS_DEFINED(SAMD21E16L) \ - ) - -#define SAMD21EXXL ( \ - SAM_PART_IS_DEFINED(SAMD21E15L) || \ - SAM_PART_IS_DEFINED(SAMD21E16L) \ - ) - -/** @} */ - -/** - * \name SAMR21 series - * @{ - */ -#define SAMR21G ( \ - SAM_PART_IS_DEFINED(SAMR21G16A) || \ - SAM_PART_IS_DEFINED(SAMR21G17A) || \ - SAM_PART_IS_DEFINED(SAMR21G18A) \ - ) - -#define SAMR21E ( \ - SAM_PART_IS_DEFINED(SAMR21E16A) || \ - SAM_PART_IS_DEFINED(SAMR21E17A) || \ - SAM_PART_IS_DEFINED(SAMR21E18A) || \ - SAM_PART_IS_DEFINED(SAMR21E19A) \ - ) -/** @} */ - -/** - * \name SAMD09 series - * @{ - */ -#define SAMD09C ( \ - SAM_PART_IS_DEFINED(SAMD09C13A) \ - ) - -#define SAMD09D ( \ - SAM_PART_IS_DEFINED(SAMD09D14A) \ - ) -/** @} */ - -/** - * \name SAMD10 series - * @{ - */ -#define SAMD10C ( \ - SAM_PART_IS_DEFINED(SAMD10C12A) || \ - SAM_PART_IS_DEFINED(SAMD10C13A) || \ - SAM_PART_IS_DEFINED(SAMD10C14A) \ - ) - -#define SAMD10DS ( \ - SAM_PART_IS_DEFINED(SAMD10D12AS) || \ - SAM_PART_IS_DEFINED(SAMD10D13AS) || \ - SAM_PART_IS_DEFINED(SAMD10D14AS) \ - ) - -#define SAMD10DM ( \ - SAM_PART_IS_DEFINED(SAMD10D12AM) || \ - SAM_PART_IS_DEFINED(SAMD10D13AM) || \ - SAM_PART_IS_DEFINED(SAMD10D14AM) \ - ) -/** @} */ - -/** - * \name SAMD11 series - * @{ - */ -#define SAMD11C ( \ - SAM_PART_IS_DEFINED(SAMD11C14A) \ - ) - -#define SAMD11DS ( \ - SAM_PART_IS_DEFINED(SAMD11D14AS) \ - ) - -#define SAMD11DM ( \ - SAM_PART_IS_DEFINED(SAMD11D14AM) \ - ) -/** @} */ - -/** - * \name SAML21 series - * @{ - */ -#define SAML21E ( \ - SAM_PART_IS_DEFINED(SAML21E18A) || \ - SAM_PART_IS_DEFINED(SAML21E15B) || \ - SAM_PART_IS_DEFINED(SAML21E16B) || \ - SAM_PART_IS_DEFINED(SAML21E17B) || \ - SAM_PART_IS_DEFINED(SAML21E18B) \ - ) - -#define SAML21G ( \ - SAM_PART_IS_DEFINED(SAML21G18A) || \ - SAM_PART_IS_DEFINED(SAML21G16B) || \ - SAM_PART_IS_DEFINED(SAML21G17B) || \ - SAM_PART_IS_DEFINED(SAML21G18B) \ - ) - -#define SAML21J ( \ - SAM_PART_IS_DEFINED(SAML21J18A) || \ - SAM_PART_IS_DEFINED(SAML21J16B) || \ - SAM_PART_IS_DEFINED(SAML21J17B) || \ - SAM_PART_IS_DEFINED(SAML21J18B) \ - ) - -/* Group for SAML21 A variant: SAML21[E/G/J][18]A */ -#define SAML21XXXA ( \ - SAM_PART_IS_DEFINED(SAML21E18A) || \ - SAM_PART_IS_DEFINED(SAML21G18A) || \ - SAM_PART_IS_DEFINED(SAML21J18A) \ - ) - -/* Group for SAML21 B variant: SAML21[E/G/J][15/16/1718]B */ -#define SAML21XXXB ( \ - SAM_PART_IS_DEFINED(SAML21E15B) || \ - SAM_PART_IS_DEFINED(SAML21E16B) || \ - SAM_PART_IS_DEFINED(SAML21E17B) || \ - SAM_PART_IS_DEFINED(SAML21E18B) || \ - SAM_PART_IS_DEFINED(SAML21G16B) || \ - SAM_PART_IS_DEFINED(SAML21G17B) || \ - SAM_PART_IS_DEFINED(SAML21G18B) || \ - SAM_PART_IS_DEFINED(SAML21J16B) || \ - SAM_PART_IS_DEFINED(SAML21J17B) || \ - SAM_PART_IS_DEFINED(SAML21J18B) \ - ) - -/** @} */ - -/** - * \name SAML22 series - * @{ - */ -#define SAML22N ( \ - SAM_PART_IS_DEFINED(SAML22N16A) || \ - SAM_PART_IS_DEFINED(SAML22N17A) || \ - SAM_PART_IS_DEFINED(SAML22N18A) \ - ) - -#define SAML22G ( \ - SAM_PART_IS_DEFINED(SAML22G16A) || \ - SAM_PART_IS_DEFINED(SAML22G17A) || \ - SAM_PART_IS_DEFINED(SAML22G18A) \ - ) - -#define SAML22J ( \ - SAM_PART_IS_DEFINED(SAML22J16A) || \ - SAM_PART_IS_DEFINED(SAML22J17A) || \ - SAM_PART_IS_DEFINED(SAML22J18A) \ - ) -/** @} */ - -/** - * \name SAMDA0 series - * @{ - */ -#define SAMDA0J ( \ - SAM_PART_IS_DEFINED(SAMDA0J14A) || \ - SAM_PART_IS_DEFINED(SAMDA0J15A) || \ - SAM_PART_IS_DEFINED(SAMDA0J16A) \ - ) - -#define SAMDA0G ( \ - SAM_PART_IS_DEFINED(SAMDA0G14A) || \ - SAM_PART_IS_DEFINED(SAMDA0G15A) || \ - SAM_PART_IS_DEFINED(SAMDA0G16A) \ - ) - -#define SAMDA0E ( \ - SAM_PART_IS_DEFINED(SAMDA0E14A) || \ - SAM_PART_IS_DEFINED(SAMDA0E15A) || \ - SAM_PART_IS_DEFINED(SAMDA0E16A) \ - ) -/** @} */ - -/** - * \name SAMDA1 series - * @{ - */ -#define SAMDA1J ( \ - SAM_PART_IS_DEFINED(SAMDA1J14A) || \ - SAM_PART_IS_DEFINED(SAMDA1J15A) || \ - SAM_PART_IS_DEFINED(SAMDA1J16A) \ - ) - -#define SAMDA1G ( \ - SAM_PART_IS_DEFINED(SAMDA1G14A) || \ - SAM_PART_IS_DEFINED(SAMDA1G15A) || \ - SAM_PART_IS_DEFINED(SAMDA1G16A) \ - ) - -#define SAMDA1E ( \ - SAM_PART_IS_DEFINED(SAMDA1E14A) || \ - SAM_PART_IS_DEFINED(SAMDA1E15A) || \ - SAM_PART_IS_DEFINED(SAMDA1E16A) \ - ) -/** @} */ - -/** - * \name SAMC20 series - * @{ - */ -#define SAMC20E ( \ - SAM_PART_IS_DEFINED(SAMC20E15A) || \ - SAM_PART_IS_DEFINED(SAMC20E16A) || \ - SAM_PART_IS_DEFINED(SAMC20E17A) || \ - SAM_PART_IS_DEFINED(SAMC20E18A) \ - ) - -#define SAMC20G ( \ - SAM_PART_IS_DEFINED(SAMC20G15A) || \ - SAM_PART_IS_DEFINED(SAMC20G16A) || \ - SAM_PART_IS_DEFINED(SAMC20G17A) || \ - SAM_PART_IS_DEFINED(SAMC20G18A) \ - ) - -#define SAMC20J ( \ - SAM_PART_IS_DEFINED(SAMC20J15A) || \ - SAM_PART_IS_DEFINED(SAMC20J16A) || \ - SAM_PART_IS_DEFINED(SAMC20J17A) || \ - SAM_PART_IS_DEFINED(SAMC20J18A) \ - ) -/** @} */ - -/** - * \name SAMC21 series - * @{ - */ -#define SAMC21E ( \ - SAM_PART_IS_DEFINED(SAMC21E15A) || \ - SAM_PART_IS_DEFINED(SAMC21E16A) || \ - SAM_PART_IS_DEFINED(SAMC21E17A) || \ - SAM_PART_IS_DEFINED(SAMC21E18A) \ - ) - -#define SAMC21G ( \ - SAM_PART_IS_DEFINED(SAMC21G15A) || \ - SAM_PART_IS_DEFINED(SAMC21G16A) || \ - SAM_PART_IS_DEFINED(SAMC21G17A) || \ - SAM_PART_IS_DEFINED(SAMC21G18A) \ - ) - -#define SAMC21J ( \ - SAM_PART_IS_DEFINED(SAMC21J15A) || \ - SAM_PART_IS_DEFINED(SAMC21J16A) || \ - SAM_PART_IS_DEFINED(SAMC21J17A) || \ - SAM_PART_IS_DEFINED(SAMC21J18A) \ - ) -/** @} */ - -/** - * \name SAM4E series - * @{ - */ -#define SAM4E8 ( \ - SAM_PART_IS_DEFINED(SAM4E8C) || \ - SAM_PART_IS_DEFINED(SAM4E8E) \ - ) - -#define SAM4E16 ( \ - SAM_PART_IS_DEFINED(SAM4E16C) || \ - SAM_PART_IS_DEFINED(SAM4E16E) \ - ) -/** @} */ - -/** - * \name SAM4N series - * @{ - */ -#define SAM4N8 ( \ - SAM_PART_IS_DEFINED(SAM4N8A) || \ - SAM_PART_IS_DEFINED(SAM4N8B) || \ - SAM_PART_IS_DEFINED(SAM4N8C) \ - ) - -#define SAM4N16 ( \ - SAM_PART_IS_DEFINED(SAM4N16B) || \ - SAM_PART_IS_DEFINED(SAM4N16C) \ - ) -/** @} */ - -/** - * \name SAM4C series - * @{ - */ -#define SAM4C4_0 ( \ - SAM_PART_IS_DEFINED(SAM4C4C_0) \ - ) - -#define SAM4C4_1 ( \ - SAM_PART_IS_DEFINED(SAM4C4C_1) \ - ) - -#define SAM4C4 (SAM4C4_0 || SAM4C4_1) - -#define SAM4C8_0 ( \ - SAM_PART_IS_DEFINED(SAM4C8C_0) \ - ) - -#define SAM4C8_1 ( \ - SAM_PART_IS_DEFINED(SAM4C8C_1) \ - ) - -#define SAM4C8 (SAM4C8_0 || SAM4C8_1) - -#define SAM4C16_0 ( \ - SAM_PART_IS_DEFINED(SAM4C16C_0) \ - ) - -#define SAM4C16_1 ( \ - SAM_PART_IS_DEFINED(SAM4C16C_1) \ - ) - -#define SAM4C16 (SAM4C16_0 || SAM4C16_1) - -#define SAM4C32_0 ( \ - SAM_PART_IS_DEFINED(SAM4C32C_0) ||\ - SAM_PART_IS_DEFINED(SAM4C32E_0) \ - ) - -#define SAM4C32_1 ( \ - SAM_PART_IS_DEFINED(SAM4C32C_1) ||\ - SAM_PART_IS_DEFINED(SAM4C32E_1) \ - ) - - -#define SAM4C32 (SAM4C32_0 || SAM4C32_1) - -/** @} */ - -/** - * \name SAM4CM series - * @{ - */ -#define SAM4CMP8_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMP8C_0) \ - ) - -#define SAM4CMP8_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMP8C_1) \ - ) - -#define SAM4CMP8 (SAM4CMP8_0 || SAM4CMP8_1) - -#define SAM4CMP16_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMP16C_0) \ - ) - -#define SAM4CMP16_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMP16C_1) \ - ) - -#define SAM4CMP16 (SAM4CMP16_0 || SAM4CMP16_1) - -#define SAM4CMP32_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMP32C_0) \ - ) - -#define SAM4CMP32_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMP32C_1) \ - ) - -#define SAM4CMP32 (SAM4CMP32_0 || SAM4CMP32_1) - -#define SAM4CMS4_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMS4C_0) \ - ) - -#define SAM4CMS4_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMS4C_1) \ - ) - -#define SAM4CMS4 (SAM4CMS4_0 || SAM4CMS4_1) - -#define SAM4CMS8_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMS8C_0) \ - ) - -#define SAM4CMS8_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMS8C_1) \ - ) - -#define SAM4CMS8 (SAM4CMS8_0 || SAM4CMS8_1) - -#define SAM4CMS16_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMS16C_0) \ - ) - -#define SAM4CMS16_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMS16C_1) \ - ) - -#define SAM4CMS16 (SAM4CMS16_0 || SAM4CMS16_1) - -#define SAM4CMS32_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMS32C_0) \ - ) - -#define SAM4CMS32_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMS32C_1) \ - ) - -#define SAM4CMS32 (SAM4CMS32_0 || SAM4CMS32_1) - -/** @} */ - -/** - * \name SAM4CP series - * @{ - */ -#define SAM4CP16_0 ( \ - SAM_PART_IS_DEFINED(SAM4CP16B_0) \ - ) - -#define SAM4CP16_1 ( \ - SAM_PART_IS_DEFINED(SAM4CP16B_1) \ - ) - -#define SAM4CP16 (SAM4CP16_0 || SAM4CP16_1) -/** @} */ - -/** - * \name SAMG series - * @{ - */ -#define SAMG51 ( \ - SAM_PART_IS_DEFINED(SAMG51G18) \ - ) - -#define SAMG53 ( \ - SAM_PART_IS_DEFINED(SAMG53G19) ||\ - SAM_PART_IS_DEFINED(SAMG53N19) \ - ) - -#define SAMG54 ( \ - SAM_PART_IS_DEFINED(SAMG54G19) ||\ - SAM_PART_IS_DEFINED(SAMG54J19) ||\ - SAM_PART_IS_DEFINED(SAMG54N19) \ - ) - -#define SAMG55 ( \ - SAM_PART_IS_DEFINED(SAMG55G18) ||\ - SAM_PART_IS_DEFINED(SAMG55G19) ||\ - SAM_PART_IS_DEFINED(SAMG55J18) ||\ - SAM_PART_IS_DEFINED(SAMG55J19) ||\ - SAM_PART_IS_DEFINED(SAMG55N19) \ - ) -/** @} */ - -/** - * \name SAMV71 series - * @{ - */ -#define SAMV71J ( \ - SAM_PART_IS_DEFINED(SAMV71J19) || \ - SAM_PART_IS_DEFINED(SAMV71J20) || \ - SAM_PART_IS_DEFINED(SAMV71J21) \ - ) - -#define SAMV71N ( \ - SAM_PART_IS_DEFINED(SAMV71N19) || \ - SAM_PART_IS_DEFINED(SAMV71N20) || \ - SAM_PART_IS_DEFINED(SAMV71N21) \ - ) - -#define SAMV71Q ( \ - SAM_PART_IS_DEFINED(SAMV71Q19) || \ - SAM_PART_IS_DEFINED(SAMV71Q20) || \ - SAM_PART_IS_DEFINED(SAMV71Q21) \ - ) -/** @} */ - -/** - * \name SAMV70 series - * @{ - */ -#define SAMV70J ( \ - SAM_PART_IS_DEFINED(SAMV70J19) || \ - SAM_PART_IS_DEFINED(SAMV70J20) \ - ) - -#define SAMV70N ( \ - SAM_PART_IS_DEFINED(SAMV70N19) || \ - SAM_PART_IS_DEFINED(SAMV70N20) \ - ) - -#define SAMV70Q ( \ - SAM_PART_IS_DEFINED(SAMV70Q19) || \ - SAM_PART_IS_DEFINED(SAMV70Q20) \ - ) -/** @} */ - -/** - * \name SAMS70 series - * @{ - */ -#define SAMS70J ( \ - SAM_PART_IS_DEFINED(SAMS70J19) || \ - SAM_PART_IS_DEFINED(SAMS70J20) || \ - SAM_PART_IS_DEFINED(SAMS70J21) \ - ) - -#define SAMS70N ( \ - SAM_PART_IS_DEFINED(SAMS70N19) || \ - SAM_PART_IS_DEFINED(SAMS70N20) || \ - SAM_PART_IS_DEFINED(SAMS70N21) \ - ) - -#define SAMS70Q ( \ - SAM_PART_IS_DEFINED(SAMS70Q19) || \ - SAM_PART_IS_DEFINED(SAMS70Q20) || \ - SAM_PART_IS_DEFINED(SAMS70Q21) \ - ) -/** @} */ - -/** - * \name SAME70 series - * @{ - */ -#define SAME70J ( \ - SAM_PART_IS_DEFINED(SAME70J19) || \ - SAM_PART_IS_DEFINED(SAME70J20) || \ - SAM_PART_IS_DEFINED(SAME70J21) \ - ) - -#define SAME70N ( \ - SAM_PART_IS_DEFINED(SAME70N19) || \ - SAM_PART_IS_DEFINED(SAME70N20) || \ - SAM_PART_IS_DEFINED(SAME70N21) \ - ) - -#define SAME70Q ( \ - SAM_PART_IS_DEFINED(SAME70Q19) || \ - SAM_PART_IS_DEFINED(SAME70Q20) || \ - SAM_PART_IS_DEFINED(SAME70Q21) \ - ) -/** @} */ - -/** - * \name SAM families - * @{ - */ -/** SAM3S Family */ -#define SAM3S (SAM3S1 || SAM3S2 || SAM3S4 || SAM3S8 || SAM3SD8) - -/** SAM3U Family */ -#define SAM3U (SAM3U1 || SAM3U2 || SAM3U4) - -/** SAM3N Family */ -#define SAM3N (SAM3N00 || SAM3N0 || SAM3N1 || SAM3N2 || SAM3N4) - -/** SAM3XA Family */ -#define SAM3XA (SAM3X4 || SAM3X8 || SAM3A4 || SAM3A8) - -/** SAM4S Family */ -#define SAM4S (SAM4S2 || SAM4S4 || SAM4S8 || SAM4S16 || SAM4SA16 || SAM4SD16 || SAM4SD32) - -/** SAM4L Family */ -#define SAM4L (SAM4LS || SAM4LC) - -/** SAMD20 Family */ -#define SAMD20 (SAMD20J || SAMD20G || SAMD20E) - -/** SAMD21 Family */ -#define SAMD21 (SAMD21J || SAMD21G || SAMD21E) - -/** SAMD09 Family */ -#define SAMD09 (SAMD09C || SAMD09D) - -/** SAMD10 Family */ -#define SAMD10 (SAMD10C || SAMD10DS || SAMD10DM) - -/** SAMD11 Family */ -#define SAMD11 (SAMD11C || SAMD11DS || SAMD11DM) - -/** SAMDA1 Family */ -#define SAMDA1 (SAMDA1J || SAMDA1G || SAMDA1E) - -/** SAMD Family */ -#define SAMD (SAMD20 || SAMD21 || SAMD09 || SAMD10 || SAMD11 || SAMDA1) - -/** SAMR21 Family */ -#define SAMR21 (SAMR21G || SAMR21E) - -/** SAML21 Family */ -#define SAML21 (SAML21J || SAML21G || SAML21E) - -/** SAML22 Family */ -#define SAML22 (SAML22J || SAML22G || SAML22N) -/** SAMC20 Family */ -#define SAMC20 (SAMC20J || SAMC20G || SAMC20E) - -/** SAMC21 Family */ -#define SAMC21 (SAMC21J || SAMC21G || SAMC21E) - -/** SAM4E Family */ -#define SAM4E (SAM4E8 || SAM4E16) - -/** SAM4N Family */ -#define SAM4N (SAM4N8 || SAM4N16) - -/** SAM4C Family */ -#define SAM4C_0 (SAM4C4_0 || SAM4C8_0 || SAM4C16_0 || SAM4C32_0) -#define SAM4C_1 (SAM4C4_1 || SAM4C8_1 || SAM4C16_1 || SAM4C32_1) -#define SAM4C (SAM4C4 || SAM4C8 || SAM4C16 || SAM4C32) - -/** SAM4CM Family */ -#define SAM4CM_0 (SAM4CMP8_0 || SAM4CMP16_0 || SAM4CMP32_0 || \ - SAM4CMS4_0 || SAM4CMS8_0 || SAM4CMS16_0 || SAM4CMS32_0) -#define SAM4CM_1 (SAM4CMP8_1 || SAM4CMP16_1 || SAM4CMP32_1 || \ - SAM4CMS4_1 || SAM4CMS8_1 || SAM4CMS16_1 || SAM4CMS32_1) -#define SAM4CM (SAM4CMP8 || SAM4CMP16 || SAM4CMP32 || \ - SAM4CMS4 || SAM4CMS8 || SAM4CMS16 || SAM4CMS32) - -/** SAM4CP Family */ -#define SAM4CP_0 (SAM4CP16_0) -#define SAM4CP_1 (SAM4CP16_1) -#define SAM4CP (SAM4CP16) - -/** SAMG Family */ -#define SAMG (SAMG51 || SAMG53 || SAMG54 || SAMG55) - -/** SAMV71 Family */ -#define SAMV71 (SAMV71J || SAMV71N || SAMV71Q) - -/** SAMV70 Family */ -#define SAMV70 (SAMV70J || SAMV70N || SAMV70Q) - -/** SAME70 Family */ -#define SAME70 (SAME70J || SAME70N || SAME70Q) - -/** SAMS70 Family */ -#define SAMS70 (SAMS70J || SAMS70N || SAMS70Q) - -/** SAM0 product line (cortex-m0+) */ -#define SAM0 (SAMD20 || SAMD21 || SAMR21 || SAMD10 || SAMD11 || SAML21 ||\ - SAMDA1 || SAMC20 || SAMC21 || SAML22 || SAMD09) - -/** @} */ - -/** SAM product line */ -#define SAM (SAM3S || SAM3U || SAM3N || SAM3XA || SAM4S || SAM4L || SAM4E || \ - SAM0 || SAM4N || SAM4C || SAM4CM || SAM4CP || SAMG || SAMV71 || SAMV70 || SAME70 || SAMS70) - -/** @} */ - -/** @} */ - -/** @} */ - -#endif /* ATMEL_PARTS_H */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/pinmux.c b/feather_sensor_transmit/libraries/Adafruit_ASFcore/pinmux.c deleted file mode 100644 index a2c9c7c..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/pinmux.c +++ /dev/null @@ -1,311 +0,0 @@ -/** - * \file - * - * \brief SAM Pin Multiplexer Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#include - -/** - * \internal - * Writes out a given configuration of a Port pin configuration to the - * hardware module. - * - * \note If the pin direction is set as an output, the pull-up/pull-down input - * configuration setting is ignored. - * - * \param[in] port Base of the PORT module to configure - * \param[in] pin_mask Mask of the port pin to configure - * \param[in] config Configuration settings for the pin - */ -static void _system_pinmux_config( - PortGroup *const port, - const uint32_t pin_mask, - const struct system_pinmux_config *const config) -{ - Assert(port); - Assert(config); - - /* Track the configuration bits into a temporary variable before writing */ - uint32_t pin_cfg = 0; - - /* Enabled powersave mode, don't create configuration */ - if (!config->powersave) { - /* Enable the pin peripheral MUX flag if non-GPIO selected (pinmux will - * be written later) and store the new MUX mask */ - if (config->mux_position != SYSTEM_PINMUX_GPIO) { - pin_cfg |= PORT_WRCONFIG_PMUXEN; - pin_cfg |= (config->mux_position << PORT_WRCONFIG_PMUX_Pos); - } - - /* Check if the user has requested that the input buffer be enabled */ - if ((config->direction == SYSTEM_PINMUX_PIN_DIR_INPUT) || - (config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK)) { - /* Enable input buffer flag */ - pin_cfg |= PORT_WRCONFIG_INEN; - - /* Enable pull-up/pull-down control flag if requested */ - if (config->input_pull != SYSTEM_PINMUX_PIN_PULL_NONE) { - pin_cfg |= PORT_WRCONFIG_PULLEN; - } - - /* Clear the port DIR bits to disable the output buffer */ - port->DIRCLR.reg = pin_mask; - } - - /* Check if the user has requested that the output buffer be enabled */ - if ((config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT) || - (config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK)) { - /* Cannot use a pull-up if the output driver is enabled, - * if requested the input buffer can only sample the current - * output state */ - pin_cfg &= ~PORT_WRCONFIG_PULLEN; - } - } else { - port->DIRCLR.reg = pin_mask; - } - - /* The Write Configuration register (WRCONFIG) requires the - * pins to to grouped into two 16-bit half-words - split them out here */ - uint32_t lower_pin_mask = (pin_mask & 0xFFFF); - uint32_t upper_pin_mask = (pin_mask >> 16); - - /* Configure the lower 16-bits of the port to the desired configuration, - * including the pin peripheral multiplexer just in case it is enabled */ - port->WRCONFIG.reg - = (lower_pin_mask << PORT_WRCONFIG_PINMASK_Pos) | - pin_cfg | PORT_WRCONFIG_WRPMUX | PORT_WRCONFIG_WRPINCFG; - - /* Configure the upper 16-bits of the port to the desired configuration, - * including the pin peripheral multiplexer just in case it is enabled */ - port->WRCONFIG.reg - = (upper_pin_mask << PORT_WRCONFIG_PINMASK_Pos) | - pin_cfg | PORT_WRCONFIG_WRPMUX | PORT_WRCONFIG_WRPINCFG | - PORT_WRCONFIG_HWSEL; - - if(!config->powersave) { - /* Set the pull-up state once the port pins are configured if one was - * requested and it does not violate the valid set of port - * configurations */ - if (pin_cfg & PORT_WRCONFIG_PULLEN) { - /* Set the OUT register bits to enable the pull-up if requested, - * clear to enable pull-down */ - if (config->input_pull == SYSTEM_PINMUX_PIN_PULL_UP) { - port->OUTSET.reg = pin_mask; - } else { - port->OUTCLR.reg = pin_mask; - } - } - - /* Check if the user has requested that the output buffer be enabled */ - if ((config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT) || - (config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK)) { - /* Set the port DIR bits to enable the output buffer */ - port->DIRSET.reg = pin_mask; - } - } -} - -/** - * \brief Writes a Port pin configuration to the hardware module. - * - * Writes out a given configuration of a Port pin configuration to the hardware - * module. - * - * \note If the pin direction is set as an output, the pull-up/pull-down input - * configuration setting is ignored. - * - * \param[in] gpio_pin Index of the GPIO pin to configure - * \param[in] config Configuration settings for the pin - */ -void system_pinmux_pin_set_config( - const uint8_t gpio_pin, - const struct system_pinmux_config *const config) -{ - PortGroup *const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); - uint32_t pin_mask = (1UL << (gpio_pin % 32)); - - _system_pinmux_config(port, pin_mask, config); -} - -/** - * \brief Writes a Port pin group configuration to the hardware module. - * - * Writes out a given configuration of a Port pin group configuration to the - * hardware module. - * - * \note If the pin direction is set as an output, the pull-up/pull-down input - * configuration setting is ignored. - * - * \param[in] port Base of the PORT module to configure - * \param[in] mask Mask of the port pin(s) to configure - * \param[in] config Configuration settings for the pin - */ -void system_pinmux_group_set_config( - PortGroup *const port, - const uint32_t mask, - const struct system_pinmux_config *const config) -{ - Assert(port); - - for (int i = 0; i < 32; i++) { - if (mask & (1UL << i)) { - _system_pinmux_config(port, (1UL << i), config); - } - } -} - -/** - * \brief Configures the input sampling mode for a group of pins. - * - * Configures the input sampling mode for a group of pins, to - * control when the physical I/O pin value is sampled and - * stored inside the microcontroller. - * - * \param[in] port Base of the PORT module to configure - * \param[in] mask Mask of the port pin(s) to configure - * \param[in] mode New pin sampling mode to configure - */ -void system_pinmux_group_set_input_sample_mode( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_sample mode) -{ - Assert(port); - - if (mode == SYSTEM_PINMUX_PIN_SAMPLE_ONDEMAND) { - port->CTRL.reg |= mask; - } else { - port->CTRL.reg &= ~mask; - } -} - -#ifdef FEATURE_SYSTEM_PINMUX_SLEWRATE_LIMITER -/** - * \brief Configures the output slew rate mode for a group of pins. - * - * Configures the output slew rate mode for a group of pins, to - * control the speed at which the physical output pin can react to - * logical changes of the I/O pin value. - * - * \param[in] port Base of the PORT module to configure - * \param[in] mask Mask of the port pin(s) to configure - * \param[in] mode New pin slew rate mode to configure - */ -void system_pinmux_group_set_output_slew_rate( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_slew_rate mode) -{ - Assert(port); - - for (int i = 0; i < 32; i++) { - if (mask & (1UL << i)) { - if (mode == SYSTEM_PINMUX_PIN_SLEW_RATE_LIMITED) { - port->PINCFG[i].reg |= PORT_PINCFG_SLEWLIM; - } else { - port->PINCFG[i].reg &= ~PORT_PINCFG_SLEWLIM; - } - } - } -} -#endif - -#ifdef FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTH -/** - * \brief Configures the output driver strength mode for a group of pins. - * - * Configures the output drive strength for a group of pins, to - * control the amount of current the pad is able to sink/source. - * - * \param[in] port Base of the PORT module to configure - * \param[in] mask Mask of the port pin(s) to configure - * \param[in] mode New output driver strength mode to configure - */ -void system_pinmux_group_set_output_strength( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_strength mode) -{ - Assert(port); - - for (int i = 0; i < 32; i++) { - if (mask & (1UL << i)) { - if (mode == SYSTEM_PINMUX_PIN_STRENGTH_HIGH) { - port->PINCFG[i].reg |= PORT_PINCFG_DRVSTR; - } else { - port->PINCFG[i].reg &= ~PORT_PINCFG_DRVSTR; - } - } - } -} -#endif - -#ifdef FEATURE_SYSTEM_PINMUX_OPEN_DRAIN -/** - * \brief Configures the output driver mode for a group of pins. - * - * Configures the output driver mode for a group of pins, to - * control the pad behavior. - * - * \param[in] port Base of the PORT module to configure - * \param[in] mask Mask of the port pin(s) to configure - * \param[in] mode New pad output driver mode to configure - */ -void system_pinmux_group_set_output_drive( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_drive mode) -{ - Assert(port); - - for (int i = 0; i < 32; i++) { - if (mask & (1UL << i)) { - if (mode == SYSTEM_PINMUX_PIN_DRIVE_OPEN_DRAIN) { - port->PINCFG[i].reg |= PORT_PINCFG_ODRAIN; - } else { - port->PINCFG[i].reg &= ~PORT_PINCFG_ODRAIN; - } - } - } -} -#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/pinmux.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/pinmux.h deleted file mode 100644 index 7a441cc..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/pinmux.h +++ /dev/null @@ -1,678 +0,0 @@ -/** - * \file - * - * \brief SAM Pin Multiplexer Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef PINMUX_H_INCLUDED -#define PINMUX_H_INCLUDED - -/** - * \defgroup asfdoc_sam0_system_pinmux_group SAM System Pin Multiplexer (SYSTEM PINMUX) Driver - * - * This driver for Atmel® | SMART ARM®-based microcontrollers provides - * an interface for the configuration and management of the device's physical - * I/O Pins, to alter the direction and input/drive characteristics as well as - * to configure the pin peripheral multiplexer selection. - * - * The following peripheral is used by this module: - * - PORT (Port I/O Management) - * - * The following devices can use this module: - * - Atmel | SMART SAM D20/D21 - * - Atmel | SMART SAM R21 - * - Atmel | SMART SAM D09/D10/D11 - * - Atmel | SMART SAM L21/L22 - * - Atmel | SMART SAM DA1 - * - Atmel | SMART SAM C20/C21 - * - * Physically, the modules are interconnected within the device as shown in the - * following diagram: - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_system_pinmux_prerequisites - * - \ref asfdoc_sam0_system_pinmux_module_overview - * - \ref asfdoc_sam0_system_pinmux_special_considerations - * - \ref asfdoc_sam0_system_pinmux_extra_info - * - \ref asfdoc_sam0_system_pinmux_examples - * - \ref asfdoc_sam0_system_pinmux_api_overview - * - * - * \section asfdoc_sam0_system_pinmux_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * - * \section asfdoc_sam0_system_pinmux_module_overview Module Overview - * - * The SAM devices contain a number of General Purpose I/O pins, used to - * interface the user application logic and internal hardware peripherals to - * an external system. The Pin Multiplexer (PINMUX) driver provides a method - * of configuring the individual pin peripheral multiplexers to select - * alternate pin functions. - * - * \subsection asfdoc_sam0_system_pinmux_features Driver Feature Macro Definition - * - * - * - * - * - * - * - * - * - *
Driver Feature MacroSupported devices
FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTHSAM L21, SAM C20/C21
- * \note The specific features are only available in the driver when the - * selected device supports those features. - * - * \subsection asfdoc_sam0_system_pinmux_physical_logical_pins Physical and Logical GPIO Pins - * SAM devices use two naming conventions for the I/O pins in the device; one - * physical and one logical. Each physical pin on a device package is assigned - * both a physical port and pin identifier (e.g. "PORTA.0") as well as a - * monotonically incrementing logical GPIO number (e.g. "GPIO0"). While the - * former is used to map physical pins to their physical internal device module - * counterparts, for simplicity the design of this driver uses the logical GPIO - * numbers instead. - * - * \subsection asfdoc_sam0_system_pinmux_peripheral_muxing Peripheral Multiplexing - * SAM devices contain a peripheral MUX, which is individually controllable - * for each I/O pin of the device. The peripheral MUX allows you to select the - * function of a physical package pin - whether it will be controlled as a user - * controllable GPIO pin, or whether it will be connected internally to one of - * several peripheral modules (such as an I2C module). When a pin is - * configured in GPIO mode, other peripherals connected to the same pin will be - * disabled. - * - * \subsection asfdoc_sam0_system_pinmux_pad_characteristics Special Pad Characteristics - * There are several special modes that can be selected on one or more I/O pins - * of the device, which alter the input and output characteristics of the pad. - * - * \subsubsection asfdoc_sam0_system_pinmux_drive_strength Drive Strength - * The Drive Strength configures the strength of the output driver on the - * pad. Normally, there is a fixed current limit that each I/O pin can safely - * drive, however some I/O pads offer a higher drive mode which increases this - * limit for that I/O pin at the expense of an increased power consumption. - * - * \subsubsection asfdoc_sam0_system_pinmux_slew_rate Slew Rate - * The Slew Rate configures the slew rate of the output driver, limiting the - * rate at which the pad output voltage can change with time. - * - * \subsubsection asfdoc_sam0_system_pinmux_input_sample_mode Input Sample Mode - * The Input Sample Mode configures the input sampler buffer of the pad. By - * default, the input buffer is only sampled "on-demand", i.e. when the user - * application attempts to read from the input buffer. This mode is the most - * power efficient, but increases the latency of the input sample by two clock - * cycles of the port clock. To reduce latency, the input sampler can instead - * be configured to always sample the input buffer on each port clock cycle, at - * the expense of an increased power consumption. - * - * \subsection asfdoc_sam0_system_pinmux_module_overview_physical Physical Connection - * - * \ref asfdoc_sam0_system_pinmux_intconnections "The diagram below" shows - * how this module is interconnected within the device: - * - * \anchor asfdoc_sam0_system_pinmux_intconnections - * \dot - * digraph overview { - * node [label="Port Pad" shape=square] pad; - * - * subgraph driver { - * node [label="Peripheral MUX" shape=trapezium] pinmux; - * node [label="GPIO Module" shape=ellipse shape=ellipse style=filled fillcolor=lightgray] gpio; - * node [label="Other Peripheral Modules" shape=ellipse style=filled fillcolor=lightgray] peripherals; - * } - * - * pinmux -> gpio; - * pad -> pinmux; - * pinmux -> peripherals; - * } - * \enddot - * - * \section asfdoc_sam0_system_pinmux_special_considerations Special Considerations - * - * The SAM port pin input sampling mode is set in groups of four physical - * pins; setting the sampling mode of any pin in a sub-group of eight I/O pins - * will configure the sampling mode of the entire sub-group. - * - * High Drive Strength output driver mode is not available on all device pins - - * refer to your device specific datasheet. - * - * - * \section asfdoc_sam0_system_pinmux_extra_info Extra Information - * - * For extra information, see \ref asfdoc_sam0_system_pinmux_extra. This includes: - * - \ref asfdoc_sam0_system_pinmux_extra_acronyms - * - \ref asfdoc_sam0_system_pinmux_extra_dependencies - * - \ref asfdoc_sam0_system_pinmux_extra_errata - * - \ref asfdoc_sam0_system_pinmux_extra_history - * - * - * \section asfdoc_sam0_system_pinmux_examples Examples - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_system_pinmux_exqsg. - * - * - * \section asfdoc_sam0_system_pinmux_api_overview API Overview - * @{ - */ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/*@{*/ -#if (SAML21) || (SAMC20) || (SAMC21) || defined(__DOXYGEN__) -/** Output Driver Strength Selection feature support */ -# define FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTH -#endif -/*@}*/ - -/** Peripheral multiplexer index to select GPIO mode for a pin */ -#define SYSTEM_PINMUX_GPIO (1 << 7) - -/** - * \brief Port pin direction configuration enum. - * - * Enum for the possible pin direction settings of the port pin configuration - * structure, to indicate the direction the pin should use. - */ -enum system_pinmux_pin_dir { - /** The pin's input buffer should be enabled, so that the pin state can - * be read */ - SYSTEM_PINMUX_PIN_DIR_INPUT, - /** The pin's output buffer should be enabled, so that the pin state can - * be set (but not read back) */ - SYSTEM_PINMUX_PIN_DIR_OUTPUT, - /** The pin's output and input buffers should both be enabled, so that the - * pin state can be set and read back */ - SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK, -}; - -/** - * \brief Port pin input pull configuration enum. - * - * Enum for the possible pin pull settings of the port pin configuration - * structure, to indicate the type of logic level pull the pin should use. - */ -enum system_pinmux_pin_pull { - /** No logical pull should be applied to the pin */ - SYSTEM_PINMUX_PIN_PULL_NONE, - /** Pin should be pulled up when idle */ - SYSTEM_PINMUX_PIN_PULL_UP, - /** Pin should be pulled down when idle */ - SYSTEM_PINMUX_PIN_PULL_DOWN, -}; - -/** - * \brief Port pin digital input sampling mode enum. - * - * Enum for the possible input sampling modes for the port pin configuration - * structure, to indicate the type of sampling a port pin should use. - */ -enum system_pinmux_pin_sample { - /** Pin input buffer should continuously sample the pin state */ - SYSTEM_PINMUX_PIN_SAMPLE_CONTINUOUS, - /** Pin input buffer should be enabled when the IN register is read */ - SYSTEM_PINMUX_PIN_SAMPLE_ONDEMAND, -}; - -/** - * \brief Port pin configuration structure. - * - * Configuration structure for a port pin instance. This structure should - * be initialized by the \ref system_pinmux_get_config_defaults() function - * before being modified by the user application. - */ -struct system_pinmux_config { - /** MUX index of the peripheral that should control the pin, if peripheral - * control is desired. For GPIO use, this should be set to - * \ref SYSTEM_PINMUX_GPIO. */ - uint8_t mux_position; - - /** Port buffer input/output direction */ - enum system_pinmux_pin_dir direction; - - /** Logic level pull of the input buffer */ - enum system_pinmux_pin_pull input_pull; - - /** Enable lowest possible powerstate on the pin. - * - * \note All other configurations will be ignored, the pin will be disabled. - */ - bool powersave; -}; - -/** \name Configuration and Initialization - * @{ - */ - -/** - * \brief Initializes a Port pin configuration structure to defaults. - * - * Initializes a given Port pin configuration structure to a set of - * known default values. This function should be called on all new - * instances of these configuration structures before being modified by the - * user application. - * - * The default configuration is as follows: - * \li Non peripheral (i.e. GPIO) controlled - * \li Input mode with internal pull-up enabled - * - * \param[out] config Configuration structure to initialize to default values - */ -static inline void system_pinmux_get_config_defaults( - struct system_pinmux_config *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Default configuration values */ - config->mux_position = SYSTEM_PINMUX_GPIO; - config->direction = SYSTEM_PINMUX_PIN_DIR_INPUT; - config->input_pull = SYSTEM_PINMUX_PIN_PULL_UP; - config->powersave = false; -} - -void system_pinmux_pin_set_config( - const uint8_t gpio_pin, - const struct system_pinmux_config *const config); - -void system_pinmux_group_set_config( - PortGroup *const port, - const uint32_t mask, - const struct system_pinmux_config *const config); - -/** @} */ - -/** \name Special Mode Configuration (Physical Group Orientated) - * @{ - */ - -/** - * \brief Retrieves the PORT module group instance from a given GPIO pin number. - * - * Retrieves the PORT module group instance associated with a given logical - * GPIO pin number. - * - * \param[in] gpio_pin Index of the GPIO pin to convert - * - * \return Base address of the associated PORT module. - */ -static inline PortGroup* system_pinmux_get_group_from_gpio_pin( - const uint8_t gpio_pin) -{ - uint8_t port_index = (gpio_pin / 128); - uint8_t group_index = (gpio_pin / 32); - - /* Array of available ports */ - Port *const ports[PORT_INST_NUM] = PORT_INSTS; - - if (port_index < PORT_INST_NUM) { - return &(ports[port_index]->Group[group_index]); - } else { - Assert(false); - return NULL; - } -} - -void system_pinmux_group_set_input_sample_mode( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_sample mode); - -/** @} */ - -/** \name Special Mode Configuration (Logical Pin Orientated) - * @{ - */ - -/** - * \brief Retrieves the currently selected MUX position of a logical pin. - * - * Retrieves the selected MUX peripheral on a given logical GPIO pin. - * - * \param[in] gpio_pin Index of the GPIO pin to configure - * - * \return Currently selected peripheral index on the specified pin. - */ -static inline uint8_t system_pinmux_pin_get_mux_position( - const uint8_t gpio_pin) -{ - PortGroup *const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); - uint32_t pin_index = (gpio_pin % 32); - - if (!(port->PINCFG[pin_index].reg & PORT_PINCFG_PMUXEN)) { - return SYSTEM_PINMUX_GPIO; - } - - uint32_t pmux_reg = port->PMUX[pin_index / 2].reg; - - if (pin_index & 1) { - return (pmux_reg & PORT_PMUX_PMUXO_Msk) >> PORT_PMUX_PMUXO_Pos; - } - else { - return (pmux_reg & PORT_PMUX_PMUXE_Msk) >> PORT_PMUX_PMUXE_Pos; - } -} - -/** - * \brief Configures the input sampling mode for a GPIO pin. - * - * Configures the input sampling mode for a GPIO input, to - * control when the physical I/O pin value is sampled and - * stored inside the microcontroller. - * - * \param[in] gpio_pin Index of the GPIO pin to configure - * \param[in] mode New pin sampling mode to configure - */ -static inline void system_pinmux_pin_set_input_sample_mode( - const uint8_t gpio_pin, - const enum system_pinmux_pin_sample mode) -{ - PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); - uint32_t pin_index = (gpio_pin % 32); - - if (mode == SYSTEM_PINMUX_PIN_SAMPLE_ONDEMAND) { - port->CTRL.reg |= (1 << pin_index); - } else { - port->CTRL.reg &= ~(1 << pin_index); - } -} - -/** @} */ - -#ifdef FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTH -/** - * \brief Port pin drive output strength enum. - * - * Enum for the possible output drive strengths for the port pin - * configuration structure, to indicate the driver strength the pin should - * use. - */ -enum system_pinmux_pin_strength { - /** Normal output driver strength */ - SYSTEM_PINMUX_PIN_STRENGTH_NORMAL, - /** High current output driver strength */ - SYSTEM_PINMUX_PIN_STRENGTH_HIGH, -}; - -/** - * \brief Configures the output driver strength mode for a GPIO pin. - * - * Configures the output drive strength for a GPIO output, to - * control the amount of current the pad is able to sink/source. - * - * \param[in] gpio_pin Index of the GPIO pin to configure - * \param[in] mode New output driver strength mode to configure - */ -static inline void system_pinmux_pin_set_output_strength( - const uint8_t gpio_pin, - const enum system_pinmux_pin_strength mode) -{ - PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); - uint32_t pin_index = (gpio_pin % 32); - - if (mode == SYSTEM_PINMUX_PIN_STRENGTH_HIGH) { - port->PINCFG[pin_index].reg |= PORT_PINCFG_DRVSTR; - } - else { - port->PINCFG[pin_index].reg &= ~PORT_PINCFG_DRVSTR; - } -} - -void system_pinmux_group_set_output_strength( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_strength mode); -#endif - -#ifdef FEATURE_SYSTEM_PINMUX_SLEWRATE_LIMITER -/** - * \brief Port pin output slew rate enum. - * - * Enum for the possible output drive slew rates for the port pin - * configuration structure, to indicate the driver slew rate the pin should - * use. - */ -enum system_pinmux_pin_slew_rate { - /** Normal pin output slew rate */ - SYSTEM_PINMUX_PIN_SLEW_RATE_NORMAL, - /** Enable slew rate limiter on the pin */ - SYSTEM_PINMUX_PIN_SLEW_RATE_LIMITED, -}; - -/** - * \brief Configures the output slew rate mode for a GPIO pin. - * - * Configures the output slew rate mode for a GPIO output, to - * control the speed at which the physical output pin can react to - * logical changes of the I/O pin value. - * - * \param[in] gpio_pin Index of the GPIO pin to configure - * \param[in] mode New pin slew rate mode to configure - */ -static inline void system_pinmux_pin_set_output_slew_rate( - const uint8_t gpio_pin, - const enum system_pinmux_pin_slew_rate mode) -{ - PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); - uint32_t pin_index = (gpio_pin % 32); - - if (mode == SYSTEM_PINMUX_PIN_SLEW_RATE_LIMITED) { - port->PINCFG[pin_index].reg |= PORT_PINCFG_SLEWLIM; - } - else { - port->PINCFG[pin_index].reg &= ~PORT_PINCFG_SLEWLIM; - } -} - -void system_pinmux_group_set_output_slew_rate( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_slew_rate mode); -#endif - -#ifdef FEATURE_SYSTEM_PINMUX_OPEN_DRAIN -/** - * \brief Port pin output drive mode enum. - * - * Enum for the possible output drive modes for the port pin configuration - * structure, to indicate the output mode the pin should use. - */ -enum system_pinmux_pin_drive { - /** Use totem pole output drive mode */ - SYSTEM_PINMUX_PIN_DRIVE_TOTEM, - /** Use open drain output drive mode */ - SYSTEM_PINMUX_PIN_DRIVE_OPEN_DRAIN, -}; - -/** - * \brief Configures the output driver mode for a GPIO pin. - * - * Configures the output driver mode for a GPIO output, to - * control the pad behavior. - * - * \param[in] gpio_pin Index of the GPIO pin to configure - * \param[in] mode New pad output driver mode to configure - */ -static inline void system_pinmux_pin_set_output_drive( - const uint8_t gpio_pin, - const enum system_pinmux_pin_drive mode) -{ - PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); - uint32_t pin_index = (gpio_pin % 32); - - if (mode == SYSTEM_PINMUX_PIN_DRIVE_OPEN_DRAIN) { - port->PINCFG[pin_index].reg |= PORT_PINCFG_ODRAIN; - } - else { - port->PINCFG[pin_index].reg &= ~PORT_PINCFG_ODRAIN; - } -} - -void system_pinmux_group_set_output_drive( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_drive mode); -#endif - -#ifdef __cplusplus -} -#endif - -/** @} */ - -/** - * \page asfdoc_sam0_system_pinmux_extra Extra Information for SYSTEM PINMUX Driver - * - * \section asfdoc_sam0_system_pinmux_extra_acronyms Acronyms - * The table below presents the acronyms used in this module: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
AcronymDescription
GPIOGeneral Purpose Input/Output
MUXMultiplexer
- * - * - * \section asfdoc_sam0_system_pinmux_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - None - * - * - * \section asfdoc_sam0_system_pinmux_extra_errata Errata - * There are no errata related to this driver. - * - * - * \section asfdoc_sam0_system_pinmux_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Changelog
Removed code of open drain, slew limit and drive strength - * features
Fixed broken sampling mode function implementations, which wrote - * corrupt configuration values to the device registers
Added missing NULL pointer asserts to the PORT driver functions
Initial Release
- */ - -/** - * \page asfdoc_sam0_system_pinmux_exqsg Examples for SYSTEM PINMUX Driver - * - * This is a list of the available Quick Start guides (QSGs) and example - * applications for \ref asfdoc_sam0_system_pinmux_group. QSGs are simple - * examples with step-by-step instructions to configure and use this driver in a - * selection of use cases. Note that a QSG can be compiled as a standalone - * application or be added to the user application. - * - * - \subpage asfdoc_sam0_system_pinmux_basic_use_case - * - * \page asfdoc_sam0_system_pinmux_document_revision_history Document Revision History - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Doc. Rev. - * Date - * Comments - *
42121F08/2015Added support for SAM L21/L22, SAM DA1, and SAM C20/C21
42121E12/2014Added support for SAM R21 and SAM D10/D11
42121D01/2014Added support for SAM D21
42121C09/2013Fixed incorrect documentation for the device pin sampling mode
42121B06/2013Corrected documentation typos
42121A06/2013Initial release
- */ - -#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/power.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/power.h deleted file mode 100644 index 5e90585..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/power.h +++ /dev/null @@ -1,224 +0,0 @@ -/** - * \file - * - * \brief SAM Power related functionality - * - * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef POWER_H_INCLUDED -#define POWER_H_INCLUDED - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \addtogroup asfdoc_sam0_system_group - * @{ - */ - -/** - * \brief Voltage references within the device. - * - * List of available voltage references (VREF) that may be used within the - * device. - */ -enum system_voltage_reference { - /** Temperature sensor voltage reference. */ - SYSTEM_VOLTAGE_REFERENCE_TEMPSENSE, - /** Bandgap voltage reference. */ - SYSTEM_VOLTAGE_REFERENCE_BANDGAP, -}; - -/** - * \brief Device sleep modes. - * - * List of available sleep modes in the device. A table of clocks available in - * different sleep modes can be found in \ref asfdoc_sam0_system_module_overview_sleep_mode. - */ -enum system_sleepmode { - /** IDLE 0 sleep mode. */ - SYSTEM_SLEEPMODE_IDLE_0, - /** IDLE 1 sleep mode. */ - SYSTEM_SLEEPMODE_IDLE_1, - /** IDLE 2 sleep mode. */ - SYSTEM_SLEEPMODE_IDLE_2, - /** Standby sleep mode. */ - SYSTEM_SLEEPMODE_STANDBY, -}; - - - -/** - * \name Voltage References - * @{ - */ - -/** - * \brief Enable the selected voltage reference - * - * Enables the selected voltage reference source, making the voltage reference - * available on a pin as well as an input source to the analog peripherals. - * - * \param[in] vref Voltage reference to enable - */ -static inline void system_voltage_reference_enable( - const enum system_voltage_reference vref) -{ - switch (vref) { - case SYSTEM_VOLTAGE_REFERENCE_TEMPSENSE: - SYSCTRL->VREF.reg |= SYSCTRL_VREF_TSEN; - break; - - case SYSTEM_VOLTAGE_REFERENCE_BANDGAP: - SYSCTRL->VREF.reg |= SYSCTRL_VREF_BGOUTEN; - break; - - default: - Assert(false); - return; - } -} - -/** - * \brief Disable the selected voltage reference - * - * Disables the selected voltage reference source. - * - * \param[in] vref Voltage reference to disable - */ -static inline void system_voltage_reference_disable( - const enum system_voltage_reference vref) -{ - switch (vref) { - case SYSTEM_VOLTAGE_REFERENCE_TEMPSENSE: - SYSCTRL->VREF.reg &= ~SYSCTRL_VREF_TSEN; - break; - - case SYSTEM_VOLTAGE_REFERENCE_BANDGAP: - SYSCTRL->VREF.reg &= ~SYSCTRL_VREF_BGOUTEN; - break; - - default: - Assert(false); - return; - } -} - -/** - * @} - */ - - -/** - * \name Device Sleep Control - * @{ - */ - -/** - * \brief Set the sleep mode of the device - * - * Sets the sleep mode of the device; the configured sleep mode will be entered - * upon the next call of the \ref system_sleep() function. - * - * For an overview of which systems are disabled in sleep for the different - * sleep modes, see \ref asfdoc_sam0_system_module_overview_sleep_mode. - * - * \param[in] sleep_mode Sleep mode to configure for the next sleep operation - * - * \retval STATUS_OK Operation completed successfully - * \retval STATUS_ERR_INVALID_ARG The requested sleep mode was invalid or not - * available - */ -static inline enum status_code system_set_sleepmode( - const enum system_sleepmode sleep_mode) -{ -#if (SAMD20 || SAMD21) - /* Errata: Make sure that the Flash does not power all the way down - * when in sleep mode. */ - NVMCTRL->CTRLB.bit.SLEEPPRM = NVMCTRL_CTRLB_SLEEPPRM_DISABLED_Val; -#endif - - switch (sleep_mode) { - case SYSTEM_SLEEPMODE_IDLE_0: - case SYSTEM_SLEEPMODE_IDLE_1: - case SYSTEM_SLEEPMODE_IDLE_2: - SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk; - PM->SLEEP.reg = sleep_mode; - break; - - case SYSTEM_SLEEPMODE_STANDBY: - SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; - break; - - default: - return STATUS_ERR_INVALID_ARG; - } - - return STATUS_OK; -} - -/** - * \brief Put the system to sleep waiting for interrupt - * - * Executes a device DSB (Data Synchronization Barrier) instruction to ensure - * all ongoing memory accesses have completed, then a WFI (Wait For Interrupt) - * instruction to place the device into the sleep mode specified by - * \ref system_set_sleepmode until woken by an interrupt. - */ -static inline void system_sleep(void) -{ - __DSB(); - __WFI(); -} - -/** - * @} - */ - -/** @} */ -#ifdef __cplusplus -} -#endif - -#endif /* POWER_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h deleted file mode 100644 index 4447927..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h +++ /dev/null @@ -1,581 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef _MRECURSION_H_ -#define _MRECURSION_H_ - -/** - * \defgroup group_sam0_utils_mrecursion Preprocessor - Macro Recursion - * - * \ingroup group_sam0_utils - * - * @{ - */ - -#include "preprocessor.h" - -#define DEC_256 255 -#define DEC_255 254 -#define DEC_254 253 -#define DEC_253 252 -#define DEC_252 251 -#define DEC_251 250 -#define DEC_250 249 -#define DEC_249 248 -#define DEC_248 247 -#define DEC_247 246 -#define DEC_246 245 -#define DEC_245 244 -#define DEC_244 243 -#define DEC_243 242 -#define DEC_242 241 -#define DEC_241 240 -#define DEC_240 239 -#define DEC_239 238 -#define DEC_238 237 -#define DEC_237 236 -#define DEC_236 235 -#define DEC_235 234 -#define DEC_234 233 -#define DEC_233 232 -#define DEC_232 231 -#define DEC_231 230 -#define DEC_230 229 -#define DEC_229 228 -#define DEC_228 227 -#define DEC_227 226 -#define DEC_226 225 -#define DEC_225 224 -#define DEC_224 223 -#define DEC_223 222 -#define DEC_222 221 -#define DEC_221 220 -#define DEC_220 219 -#define DEC_219 218 -#define DEC_218 217 -#define DEC_217 216 -#define DEC_216 215 -#define DEC_215 214 -#define DEC_214 213 -#define DEC_213 212 -#define DEC_212 211 -#define DEC_211 210 -#define DEC_210 209 -#define DEC_209 208 -#define DEC_208 207 -#define DEC_207 206 -#define DEC_206 205 -#define DEC_205 204 -#define DEC_204 203 -#define DEC_203 202 -#define DEC_202 201 -#define DEC_201 200 -#define DEC_200 199 -#define DEC_199 198 -#define DEC_198 197 -#define DEC_197 196 -#define DEC_196 195 -#define DEC_195 194 -#define DEC_194 193 -#define DEC_193 192 -#define DEC_192 191 -#define DEC_191 190 -#define DEC_190 189 -#define DEC_189 188 -#define DEC_188 187 -#define DEC_187 186 -#define DEC_186 185 -#define DEC_185 184 -#define DEC_184 183 -#define DEC_183 182 -#define DEC_182 181 -#define DEC_181 180 -#define DEC_180 179 -#define DEC_179 178 -#define DEC_178 177 -#define DEC_177 176 -#define DEC_176 175 -#define DEC_175 174 -#define DEC_174 173 -#define DEC_173 172 -#define DEC_172 171 -#define DEC_171 170 -#define DEC_170 169 -#define DEC_169 168 -#define DEC_168 167 -#define DEC_167 166 -#define DEC_166 165 -#define DEC_165 164 -#define DEC_164 163 -#define DEC_163 162 -#define DEC_162 161 -#define DEC_161 160 -#define DEC_160 159 -#define DEC_159 158 -#define DEC_158 157 -#define DEC_157 156 -#define DEC_156 155 -#define DEC_155 154 -#define DEC_154 153 -#define DEC_153 152 -#define DEC_152 151 -#define DEC_151 150 -#define DEC_150 149 -#define DEC_149 148 -#define DEC_148 147 -#define DEC_147 146 -#define DEC_146 145 -#define DEC_145 144 -#define DEC_144 143 -#define DEC_143 142 -#define DEC_142 141 -#define DEC_141 140 -#define DEC_140 139 -#define DEC_139 138 -#define DEC_138 137 -#define DEC_137 136 -#define DEC_136 135 -#define DEC_135 134 -#define DEC_134 133 -#define DEC_133 132 -#define DEC_132 131 -#define DEC_131 130 -#define DEC_130 129 -#define DEC_129 128 -#define DEC_128 127 -#define DEC_127 126 -#define DEC_126 125 -#define DEC_125 124 -#define DEC_124 123 -#define DEC_123 122 -#define DEC_122 121 -#define DEC_121 120 -#define DEC_120 119 -#define DEC_119 118 -#define DEC_118 117 -#define DEC_117 116 -#define DEC_116 115 -#define DEC_115 114 -#define DEC_114 113 -#define DEC_113 112 -#define DEC_112 111 -#define DEC_111 110 -#define DEC_110 109 -#define DEC_109 108 -#define DEC_108 107 -#define DEC_107 106 -#define DEC_106 105 -#define DEC_105 104 -#define DEC_104 103 -#define DEC_103 102 -#define DEC_102 101 -#define DEC_101 100 -#define DEC_100 99 -#define DEC_99 98 -#define DEC_98 97 -#define DEC_97 96 -#define DEC_96 95 -#define DEC_95 94 -#define DEC_94 93 -#define DEC_93 92 -#define DEC_92 91 -#define DEC_91 90 -#define DEC_90 89 -#define DEC_89 88 -#define DEC_88 87 -#define DEC_87 86 -#define DEC_86 85 -#define DEC_85 84 -#define DEC_84 83 -#define DEC_83 82 -#define DEC_82 81 -#define DEC_81 80 -#define DEC_80 79 -#define DEC_79 78 -#define DEC_78 77 -#define DEC_77 76 -#define DEC_76 75 -#define DEC_75 74 -#define DEC_74 73 -#define DEC_73 72 -#define DEC_72 71 -#define DEC_71 70 -#define DEC_70 69 -#define DEC_69 68 -#define DEC_68 67 -#define DEC_67 66 -#define DEC_66 65 -#define DEC_65 64 -#define DEC_64 63 -#define DEC_63 62 -#define DEC_62 61 -#define DEC_61 60 -#define DEC_60 59 -#define DEC_59 58 -#define DEC_58 57 -#define DEC_57 56 -#define DEC_56 55 -#define DEC_55 54 -#define DEC_54 53 -#define DEC_53 52 -#define DEC_52 51 -#define DEC_51 50 -#define DEC_50 49 -#define DEC_49 48 -#define DEC_48 47 -#define DEC_47 46 -#define DEC_46 45 -#define DEC_45 44 -#define DEC_44 43 -#define DEC_43 42 -#define DEC_42 41 -#define DEC_41 40 -#define DEC_40 39 -#define DEC_39 38 -#define DEC_38 37 -#define DEC_37 36 -#define DEC_36 35 -#define DEC_35 34 -#define DEC_34 33 -#define DEC_33 32 -#define DEC_32 31 -#define DEC_31 30 -#define DEC_30 29 -#define DEC_29 28 -#define DEC_28 27 -#define DEC_27 26 -#define DEC_26 25 -#define DEC_25 24 -#define DEC_24 23 -#define DEC_23 22 -#define DEC_22 21 -#define DEC_21 20 -#define DEC_20 19 -#define DEC_19 18 -#define DEC_18 17 -#define DEC_17 16 -#define DEC_16 15 -#define DEC_15 14 -#define DEC_14 13 -#define DEC_13 12 -#define DEC_12 11 -#define DEC_11 10 -#define DEC_10 9 -#define DEC_9 8 -#define DEC_8 7 -#define DEC_7 6 -#define DEC_6 5 -#define DEC_5 4 -#define DEC_4 3 -#define DEC_3 2 -#define DEC_2 1 -#define DEC_1 0 -#define DEC_(n) DEC_##n - - -/** Maximal number of repetitions supported by MRECURSION. */ -#define MRECURSION_LIMIT 256 - -/** \brief Macro recursion. - * - * This macro represents a horizontal repetition construct. - * - * \param[in] count The number of repetitious calls to macro. Valid values - * range from 0 to MRECURSION_LIMIT. - * \param[in] macro A binary operation of the form macro(data, n). This macro - * is expanded by MRECURSION with the current repetition number - * and the auxiliary data argument. - * \param[in] data A recursive threshold, building on this to decline by times - * defined with param count. - * - * \return macro(data-count+1,0) macro(data-count+2,1)...macro(data,count-1) - */ -#define MRECURSION(count, macro, data) TPASTE2(MRECURSION, count) (macro, data) - -#define MRECURSION0( macro, data) -#define MRECURSION1( macro, data) MRECURSION0( macro, DEC_(data)) macro(data, 0) -#define MRECURSION2( macro, data) MRECURSION1( macro, DEC_(data)) macro(data, 1) -#define MRECURSION3( macro, data) MRECURSION2( macro, DEC_(data)) macro(data, 2) -#define MRECURSION4( macro, data) MRECURSION3( macro, DEC_(data)) macro(data, 3) -#define MRECURSION5( macro, data) MRECURSION4( macro, DEC_(data)) macro(data, 4) -#define MRECURSION6( macro, data) MRECURSION5( macro, DEC_(data)) macro(data, 5) -#define MRECURSION7( macro, data) MRECURSION6( macro, DEC_(data)) macro(data, 6) -#define MRECURSION8( macro, data) MRECURSION7( macro, DEC_(data)) macro(data, 7) -#define MRECURSION9( macro, data) MRECURSION8( macro, DEC_(data)) macro(data, 8) -#define MRECURSION10( macro, data) MRECURSION9( macro, DEC_(data)) macro(data, 9) -#define MRECURSION11( macro, data) MRECURSION10( macro, DEC_(data)) macro(data, 10) -#define MRECURSION12( macro, data) MRECURSION11( macro, DEC_(data)) macro(data, 11) -#define MRECURSION13( macro, data) MRECURSION12( macro, DEC_(data)) macro(data, 12) -#define MRECURSION14( macro, data) MRECURSION13( macro, DEC_(data)) macro(data, 13) -#define MRECURSION15( macro, data) MRECURSION14( macro, DEC_(data)) macro(data, 14) -#define MRECURSION16( macro, data) MRECURSION15( macro, DEC_(data)) macro(data, 15) -#define MRECURSION17( macro, data) MRECURSION16( macro, DEC_(data)) macro(data, 16) -#define MRECURSION18( macro, data) MRECURSION17( macro, DEC_(data)) macro(data, 17) -#define MRECURSION19( macro, data) MRECURSION18( macro, DEC_(data)) macro(data, 18) -#define MRECURSION20( macro, data) MRECURSION19( macro, DEC_(data)) macro(data, 19) -#define MRECURSION21( macro, data) MRECURSION20( macro, DEC_(data)) macro(data, 20) -#define MRECURSION22( macro, data) MRECURSION21( macro, DEC_(data)) macro(data, 21) -#define MRECURSION23( macro, data) MRECURSION22( macro, DEC_(data)) macro(data, 22) -#define MRECURSION24( macro, data) MRECURSION23( macro, DEC_(data)) macro(data, 23) -#define MRECURSION25( macro, data) MRECURSION24( macro, DEC_(data)) macro(data, 24) -#define MRECURSION26( macro, data) MRECURSION25( macro, DEC_(data)) macro(data, 25) -#define MRECURSION27( macro, data) MRECURSION26( macro, DEC_(data)) macro(data, 26) -#define MRECURSION28( macro, data) MRECURSION27( macro, DEC_(data)) macro(data, 27) -#define MRECURSION29( macro, data) MRECURSION28( macro, DEC_(data)) macro(data, 28) -#define MRECURSION30( macro, data) MRECURSION29( macro, DEC_(data)) macro(data, 29) -#define MRECURSION31( macro, data) MRECURSION30( macro, DEC_(data)) macro(data, 30) -#define MRECURSION32( macro, data) MRECURSION31( macro, DEC_(data)) macro(data, 31) -#define MRECURSION33( macro, data) MRECURSION32( macro, DEC_(data)) macro(data, 32) -#define MRECURSION34( macro, data) MRECURSION33( macro, DEC_(data)) macro(data, 33) -#define MRECURSION35( macro, data) MRECURSION34( macro, DEC_(data)) macro(data, 34) -#define MRECURSION36( macro, data) MRECURSION35( macro, DEC_(data)) macro(data, 35) -#define MRECURSION37( macro, data) MRECURSION36( macro, DEC_(data)) macro(data, 36) -#define MRECURSION38( macro, data) MRECURSION37( macro, DEC_(data)) macro(data, 37) -#define MRECURSION39( macro, data) MRECURSION38( macro, DEC_(data)) macro(data, 38) -#define MRECURSION40( macro, data) MRECURSION39( macro, DEC_(data)) macro(data, 39) -#define MRECURSION41( macro, data) MRECURSION40( macro, DEC_(data)) macro(data, 40) -#define MRECURSION42( macro, data) MRECURSION41( macro, DEC_(data)) macro(data, 41) -#define MRECURSION43( macro, data) MRECURSION42( macro, DEC_(data)) macro(data, 42) -#define MRECURSION44( macro, data) MRECURSION43( macro, DEC_(data)) macro(data, 43) -#define MRECURSION45( macro, data) MRECURSION44( macro, DEC_(data)) macro(data, 44) -#define MRECURSION46( macro, data) MRECURSION45( macro, DEC_(data)) macro(data, 45) -#define MRECURSION47( macro, data) MRECURSION46( macro, DEC_(data)) macro(data, 46) -#define MRECURSION48( macro, data) MRECURSION47( macro, DEC_(data)) macro(data, 47) -#define MRECURSION49( macro, data) MRECURSION48( macro, DEC_(data)) macro(data, 48) -#define MRECURSION50( macro, data) MRECURSION49( macro, DEC_(data)) macro(data, 49) -#define MRECURSION51( macro, data) MRECURSION50( macro, DEC_(data)) macro(data, 50) -#define MRECURSION52( macro, data) MRECURSION51( macro, DEC_(data)) macro(data, 51) -#define MRECURSION53( macro, data) MRECURSION52( macro, DEC_(data)) macro(data, 52) -#define MRECURSION54( macro, data) MRECURSION53( macro, DEC_(data)) macro(data, 53) -#define MRECURSION55( macro, data) MRECURSION54( macro, DEC_(data)) macro(data, 54) -#define MRECURSION56( macro, data) MRECURSION55( macro, DEC_(data)) macro(data, 55) -#define MRECURSION57( macro, data) MRECURSION56( macro, DEC_(data)) macro(data, 56) -#define MRECURSION58( macro, data) MRECURSION57( macro, DEC_(data)) macro(data, 57) -#define MRECURSION59( macro, data) MRECURSION58( macro, DEC_(data)) macro(data, 58) -#define MRECURSION60( macro, data) MRECURSION59( macro, DEC_(data)) macro(data, 59) -#define MRECURSION61( macro, data) MRECURSION60( macro, DEC_(data)) macro(data, 60) -#define MRECURSION62( macro, data) MRECURSION61( macro, DEC_(data)) macro(data, 61) -#define MRECURSION63( macro, data) MRECURSION62( macro, DEC_(data)) macro(data, 62) -#define MRECURSION64( macro, data) MRECURSION63( macro, DEC_(data)) macro(data, 63) -#define MRECURSION65( macro, data) MRECURSION64( macro, DEC_(data)) macro(data, 64) -#define MRECURSION66( macro, data) MRECURSION65( macro, DEC_(data)) macro(data, 65) -#define MRECURSION67( macro, data) MRECURSION66( macro, DEC_(data)) macro(data, 66) -#define MRECURSION68( macro, data) MRECURSION67( macro, DEC_(data)) macro(data, 67) -#define MRECURSION69( macro, data) MRECURSION68( macro, DEC_(data)) macro(data, 68) -#define MRECURSION70( macro, data) MRECURSION69( macro, DEC_(data)) macro(data, 69) -#define MRECURSION71( macro, data) MRECURSION70( macro, DEC_(data)) macro(data, 70) -#define MRECURSION72( macro, data) MRECURSION71( macro, DEC_(data)) macro(data, 71) -#define MRECURSION73( macro, data) MRECURSION72( macro, DEC_(data)) macro(data, 72) -#define MRECURSION74( macro, data) MRECURSION73( macro, DEC_(data)) macro(data, 73) -#define MRECURSION75( macro, data) MRECURSION74( macro, DEC_(data)) macro(data, 74) -#define MRECURSION76( macro, data) MRECURSION75( macro, DEC_(data)) macro(data, 75) -#define MRECURSION77( macro, data) MRECURSION76( macro, DEC_(data)) macro(data, 76) -#define MRECURSION78( macro, data) MRECURSION77( macro, DEC_(data)) macro(data, 77) -#define MRECURSION79( macro, data) MRECURSION78( macro, DEC_(data)) macro(data, 78) -#define MRECURSION80( macro, data) MRECURSION79( macro, DEC_(data)) macro(data, 79) -#define MRECURSION81( macro, data) MRECURSION80( macro, DEC_(data)) macro(data, 80) -#define MRECURSION82( macro, data) MRECURSION81( macro, DEC_(data)) macro(data, 81) -#define MRECURSION83( macro, data) MRECURSION82( macro, DEC_(data)) macro(data, 82) -#define MRECURSION84( macro, data) MRECURSION83( macro, DEC_(data)) macro(data, 83) -#define MRECURSION85( macro, data) MRECURSION84( macro, DEC_(data)) macro(data, 84) -#define MRECURSION86( macro, data) MRECURSION85( macro, DEC_(data)) macro(data, 85) -#define MRECURSION87( macro, data) MRECURSION86( macro, DEC_(data)) macro(data, 86) -#define MRECURSION88( macro, data) MRECURSION87( macro, DEC_(data)) macro(data, 87) -#define MRECURSION89( macro, data) MRECURSION88( macro, DEC_(data)) macro(data, 88) -#define MRECURSION90( macro, data) MRECURSION89( macro, DEC_(data)) macro(data, 89) -#define MRECURSION91( macro, data) MRECURSION90( macro, DEC_(data)) macro(data, 90) -#define MRECURSION92( macro, data) MRECURSION91( macro, DEC_(data)) macro(data, 91) -#define MRECURSION93( macro, data) MRECURSION92( macro, DEC_(data)) macro(data, 92) -#define MRECURSION94( macro, data) MRECURSION93( macro, DEC_(data)) macro(data, 93) -#define MRECURSION95( macro, data) MRECURSION94( macro, DEC_(data)) macro(data, 94) -#define MRECURSION96( macro, data) MRECURSION95( macro, DEC_(data)) macro(data, 95) -#define MRECURSION97( macro, data) MRECURSION96( macro, DEC_(data)) macro(data, 96) -#define MRECURSION98( macro, data) MRECURSION97( macro, DEC_(data)) macro(data, 97) -#define MRECURSION99( macro, data) MRECURSION98( macro, DEC_(data)) macro(data, 98) -#define MRECURSION100(macro, data) MRECURSION99( macro, DEC_(data)) macro(data, 99) -#define MRECURSION101(macro, data) MRECURSION100( macro, DEC_(data)) macro(data, 100) -#define MRECURSION102(macro, data) MRECURSION101( macro, DEC_(data)) macro(data, 101) -#define MRECURSION103(macro, data) MRECURSION102( macro, DEC_(data)) macro(data, 102) -#define MRECURSION104(macro, data) MRECURSION103( macro, DEC_(data)) macro(data, 103) -#define MRECURSION105(macro, data) MRECURSION104( macro, DEC_(data)) macro(data, 104) -#define MRECURSION106(macro, data) MRECURSION105( macro, DEC_(data)) macro(data, 105) -#define MRECURSION107(macro, data) MRECURSION106( macro, DEC_(data)) macro(data, 106) -#define MRECURSION108(macro, data) MRECURSION107( macro, DEC_(data)) macro(data, 107) -#define MRECURSION109(macro, data) MRECURSION108( macro, DEC_(data)) macro(data, 108) -#define MRECURSION110(macro, data) MRECURSION109( macro, DEC_(data)) macro(data, 109) -#define MRECURSION111(macro, data) MRECURSION110( macro, DEC_(data)) macro(data, 110) -#define MRECURSION112(macro, data) MRECURSION111( macro, DEC_(data)) macro(data, 111) -#define MRECURSION113(macro, data) MRECURSION112( macro, DEC_(data)) macro(data, 112) -#define MRECURSION114(macro, data) MRECURSION113( macro, DEC_(data)) macro(data, 113) -#define MRECURSION115(macro, data) MRECURSION114( macro, DEC_(data)) macro(data, 114) -#define MRECURSION116(macro, data) MRECURSION115( macro, DEC_(data)) macro(data, 115) -#define MRECURSION117(macro, data) MRECURSION116( macro, DEC_(data)) macro(data, 116) -#define MRECURSION118(macro, data) MRECURSION117( macro, DEC_(data)) macro(data, 117) -#define MRECURSION119(macro, data) MRECURSION118( macro, DEC_(data)) macro(data, 118) -#define MRECURSION120(macro, data) MRECURSION119( macro, DEC_(data)) macro(data, 119) -#define MRECURSION121(macro, data) MRECURSION120( macro, DEC_(data)) macro(data, 120) -#define MRECURSION122(macro, data) MRECURSION121( macro, DEC_(data)) macro(data, 121) -#define MRECURSION123(macro, data) MRECURSION122( macro, DEC_(data)) macro(data, 122) -#define MRECURSION124(macro, data) MRECURSION123( macro, DEC_(data)) macro(data, 123) -#define MRECURSION125(macro, data) MRECURSION124( macro, DEC_(data)) macro(data, 124) -#define MRECURSION126(macro, data) MRECURSION125( macro, DEC_(data)) macro(data, 125) -#define MRECURSION127(macro, data) MRECURSION126( macro, DEC_(data)) macro(data, 126) -#define MRECURSION128(macro, data) MRECURSION127( macro, DEC_(data)) macro(data, 127) -#define MRECURSION129(macro, data) MRECURSION128( macro, DEC_(data)) macro(data, 128) -#define MRECURSION130(macro, data) MRECURSION129( macro, DEC_(data)) macro(data, 129) -#define MRECURSION131(macro, data) MRECURSION130( macro, DEC_(data)) macro(data, 130) -#define MRECURSION132(macro, data) MRECURSION131( macro, DEC_(data)) macro(data, 131) -#define MRECURSION133(macro, data) MRECURSION132( macro, DEC_(data)) macro(data, 132) -#define MRECURSION134(macro, data) MRECURSION133( macro, DEC_(data)) macro(data, 133) -#define MRECURSION135(macro, data) MRECURSION134( macro, DEC_(data)) macro(data, 134) -#define MRECURSION136(macro, data) MRECURSION135( macro, DEC_(data)) macro(data, 135) -#define MRECURSION137(macro, data) MRECURSION136( macro, DEC_(data)) macro(data, 136) -#define MRECURSION138(macro, data) MRECURSION137( macro, DEC_(data)) macro(data, 137) -#define MRECURSION139(macro, data) MRECURSION138( macro, DEC_(data)) macro(data, 138) -#define MRECURSION140(macro, data) MRECURSION139( macro, DEC_(data)) macro(data, 139) -#define MRECURSION141(macro, data) MRECURSION140( macro, DEC_(data)) macro(data, 140) -#define MRECURSION142(macro, data) MRECURSION141( macro, DEC_(data)) macro(data, 141) -#define MRECURSION143(macro, data) MRECURSION142( macro, DEC_(data)) macro(data, 142) -#define MRECURSION144(macro, data) MRECURSION143( macro, DEC_(data)) macro(data, 143) -#define MRECURSION145(macro, data) MRECURSION144( macro, DEC_(data)) macro(data, 144) -#define MRECURSION146(macro, data) MRECURSION145( macro, DEC_(data)) macro(data, 145) -#define MRECURSION147(macro, data) MRECURSION146( macro, DEC_(data)) macro(data, 146) -#define MRECURSION148(macro, data) MRECURSION147( macro, DEC_(data)) macro(data, 147) -#define MRECURSION149(macro, data) MRECURSION148( macro, DEC_(data)) macro(data, 148) -#define MRECURSION150(macro, data) MRECURSION149( macro, DEC_(data)) macro(data, 149) -#define MRECURSION151(macro, data) MRECURSION150( macro, DEC_(data)) macro(data, 150) -#define MRECURSION152(macro, data) MRECURSION151( macro, DEC_(data)) macro(data, 151) -#define MRECURSION153(macro, data) MRECURSION152( macro, DEC_(data)) macro(data, 152) -#define MRECURSION154(macro, data) MRECURSION153( macro, DEC_(data)) macro(data, 153) -#define MRECURSION155(macro, data) MRECURSION154( macro, DEC_(data)) macro(data, 154) -#define MRECURSION156(macro, data) MRECURSION155( macro, DEC_(data)) macro(data, 155) -#define MRECURSION157(macro, data) MRECURSION156( macro, DEC_(data)) macro(data, 156) -#define MRECURSION158(macro, data) MRECURSION157( macro, DEC_(data)) macro(data, 157) -#define MRECURSION159(macro, data) MRECURSION158( macro, DEC_(data)) macro(data, 158) -#define MRECURSION160(macro, data) MRECURSION159( macro, DEC_(data)) macro(data, 159) -#define MRECURSION161(macro, data) MRECURSION160( macro, DEC_(data)) macro(data, 160) -#define MRECURSION162(macro, data) MRECURSION161( macro, DEC_(data)) macro(data, 161) -#define MRECURSION163(macro, data) MRECURSION162( macro, DEC_(data)) macro(data, 162) -#define MRECURSION164(macro, data) MRECURSION163( macro, DEC_(data)) macro(data, 163) -#define MRECURSION165(macro, data) MRECURSION164( macro, DEC_(data)) macro(data, 164) -#define MRECURSION166(macro, data) MRECURSION165( macro, DEC_(data)) macro(data, 165) -#define MRECURSION167(macro, data) MRECURSION166( macro, DEC_(data)) macro(data, 166) -#define MRECURSION168(macro, data) MRECURSION167( macro, DEC_(data)) macro(data, 167) -#define MRECURSION169(macro, data) MRECURSION168( macro, DEC_(data)) macro(data, 168) -#define MRECURSION170(macro, data) MRECURSION169( macro, DEC_(data)) macro(data, 169) -#define MRECURSION171(macro, data) MRECURSION170( macro, DEC_(data)) macro(data, 170) -#define MRECURSION172(macro, data) MRECURSION171( macro, DEC_(data)) macro(data, 171) -#define MRECURSION173(macro, data) MRECURSION172( macro, DEC_(data)) macro(data, 172) -#define MRECURSION174(macro, data) MRECURSION173( macro, DEC_(data)) macro(data, 173) -#define MRECURSION175(macro, data) MRECURSION174( macro, DEC_(data)) macro(data, 174) -#define MRECURSION176(macro, data) MRECURSION175( macro, DEC_(data)) macro(data, 175) -#define MRECURSION177(macro, data) MRECURSION176( macro, DEC_(data)) macro(data, 176) -#define MRECURSION178(macro, data) MRECURSION177( macro, DEC_(data)) macro(data, 177) -#define MRECURSION179(macro, data) MRECURSION178( macro, DEC_(data)) macro(data, 178) -#define MRECURSION180(macro, data) MRECURSION179( macro, DEC_(data)) macro(data, 179) -#define MRECURSION181(macro, data) MRECURSION180( macro, DEC_(data)) macro(data, 180) -#define MRECURSION182(macro, data) MRECURSION181( macro, DEC_(data)) macro(data, 181) -#define MRECURSION183(macro, data) MRECURSION182( macro, DEC_(data)) macro(data, 182) -#define MRECURSION184(macro, data) MRECURSION183( macro, DEC_(data)) macro(data, 183) -#define MRECURSION185(macro, data) MRECURSION184( macro, DEC_(data)) macro(data, 184) -#define MRECURSION186(macro, data) MRECURSION185( macro, DEC_(data)) macro(data, 185) -#define MRECURSION187(macro, data) MRECURSION186( macro, DEC_(data)) macro(data, 186) -#define MRECURSION188(macro, data) MRECURSION187( macro, DEC_(data)) macro(data, 187) -#define MRECURSION189(macro, data) MRECURSION188( macro, DEC_(data)) macro(data, 188) -#define MRECURSION190(macro, data) MRECURSION189( macro, DEC_(data)) macro(data, 189) -#define MRECURSION191(macro, data) MRECURSION190( macro, DEC_(data)) macro(data, 190) -#define MRECURSION192(macro, data) MRECURSION191( macro, DEC_(data)) macro(data, 191) -#define MRECURSION193(macro, data) MRECURSION192( macro, DEC_(data)) macro(data, 192) -#define MRECURSION194(macro, data) MRECURSION193( macro, DEC_(data)) macro(data, 193) -#define MRECURSION195(macro, data) MRECURSION194( macro, DEC_(data)) macro(data, 194) -#define MRECURSION196(macro, data) MRECURSION195( macro, DEC_(data)) macro(data, 195) -#define MRECURSION197(macro, data) MRECURSION196( macro, DEC_(data)) macro(data, 196) -#define MRECURSION198(macro, data) MRECURSION197( macro, DEC_(data)) macro(data, 197) -#define MRECURSION199(macro, data) MRECURSION198( macro, DEC_(data)) macro(data, 198) -#define MRECURSION200(macro, data) MRECURSION199( macro, DEC_(data)) macro(data, 199) -#define MRECURSION201(macro, data) MRECURSION200( macro, DEC_(data)) macro(data, 200) -#define MRECURSION202(macro, data) MRECURSION201( macro, DEC_(data)) macro(data, 201) -#define MRECURSION203(macro, data) MRECURSION202( macro, DEC_(data)) macro(data, 202) -#define MRECURSION204(macro, data) MRECURSION203( macro, DEC_(data)) macro(data, 203) -#define MRECURSION205(macro, data) MRECURSION204( macro, DEC_(data)) macro(data, 204) -#define MRECURSION206(macro, data) MRECURSION205( macro, DEC_(data)) macro(data, 205) -#define MRECURSION207(macro, data) MRECURSION206( macro, DEC_(data)) macro(data, 206) -#define MRECURSION208(macro, data) MRECURSION207( macro, DEC_(data)) macro(data, 207) -#define MRECURSION209(macro, data) MRECURSION208( macro, DEC_(data)) macro(data, 208) -#define MRECURSION210(macro, data) MRECURSION209( macro, DEC_(data)) macro(data, 209) -#define MRECURSION211(macro, data) MRECURSION210( macro, DEC_(data)) macro(data, 210) -#define MRECURSION212(macro, data) MRECURSION211( macro, DEC_(data)) macro(data, 211) -#define MRECURSION213(macro, data) MRECURSION212( macro, DEC_(data)) macro(data, 212) -#define MRECURSION214(macro, data) MRECURSION213( macro, DEC_(data)) macro(data, 213) -#define MRECURSION215(macro, data) MRECURSION214( macro, DEC_(data)) macro(data, 214) -#define MRECURSION216(macro, data) MRECURSION215( macro, DEC_(data)) macro(data, 215) -#define MRECURSION217(macro, data) MRECURSION216( macro, DEC_(data)) macro(data, 216) -#define MRECURSION218(macro, data) MRECURSION217( macro, DEC_(data)) macro(data, 217) -#define MRECURSION219(macro, data) MRECURSION218( macro, DEC_(data)) macro(data, 218) -#define MRECURSION220(macro, data) MRECURSION219( macro, DEC_(data)) macro(data, 219) -#define MRECURSION221(macro, data) MRECURSION220( macro, DEC_(data)) macro(data, 220) -#define MRECURSION222(macro, data) MRECURSION221( macro, DEC_(data)) macro(data, 221) -#define MRECURSION223(macro, data) MRECURSION222( macro, DEC_(data)) macro(data, 222) -#define MRECURSION224(macro, data) MRECURSION223( macro, DEC_(data)) macro(data, 223) -#define MRECURSION225(macro, data) MRECURSION224( macro, DEC_(data)) macro(data, 224) -#define MRECURSION226(macro, data) MRECURSION225( macro, DEC_(data)) macro(data, 225) -#define MRECURSION227(macro, data) MRECURSION226( macro, DEC_(data)) macro(data, 226) -#define MRECURSION228(macro, data) MRECURSION227( macro, DEC_(data)) macro(data, 227) -#define MRECURSION229(macro, data) MRECURSION228( macro, DEC_(data)) macro(data, 228) -#define MRECURSION230(macro, data) MRECURSION229( macro, DEC_(data)) macro(data, 229) -#define MRECURSION231(macro, data) MRECURSION230( macro, DEC_(data)) macro(data, 230) -#define MRECURSION232(macro, data) MRECURSION231( macro, DEC_(data)) macro(data, 231) -#define MRECURSION233(macro, data) MRECURSION232( macro, DEC_(data)) macro(data, 232) -#define MRECURSION234(macro, data) MRECURSION233( macro, DEC_(data)) macro(data, 233) -#define MRECURSION235(macro, data) MRECURSION234( macro, DEC_(data)) macro(data, 234) -#define MRECURSION236(macro, data) MRECURSION235( macro, DEC_(data)) macro(data, 235) -#define MRECURSION237(macro, data) MRECURSION236( macro, DEC_(data)) macro(data, 236) -#define MRECURSION238(macro, data) MRECURSION237( macro, DEC_(data)) macro(data, 237) -#define MRECURSION239(macro, data) MRECURSION238( macro, DEC_(data)) macro(data, 238) -#define MRECURSION240(macro, data) MRECURSION239( macro, DEC_(data)) macro(data, 239) -#define MRECURSION241(macro, data) MRECURSION240( macro, DEC_(data)) macro(data, 240) -#define MRECURSION242(macro, data) MRECURSION241( macro, DEC_(data)) macro(data, 241) -#define MRECURSION243(macro, data) MRECURSION242( macro, DEC_(data)) macro(data, 242) -#define MRECURSION244(macro, data) MRECURSION243( macro, DEC_(data)) macro(data, 243) -#define MRECURSION245(macro, data) MRECURSION244( macro, DEC_(data)) macro(data, 244) -#define MRECURSION246(macro, data) MRECURSION245( macro, DEC_(data)) macro(data, 245) -#define MRECURSION247(macro, data) MRECURSION246( macro, DEC_(data)) macro(data, 246) -#define MRECURSION248(macro, data) MRECURSION247( macro, DEC_(data)) macro(data, 247) -#define MRECURSION249(macro, data) MRECURSION248( macro, DEC_(data)) macro(data, 248) -#define MRECURSION250(macro, data) MRECURSION249( macro, DEC_(data)) macro(data, 249) -#define MRECURSION251(macro, data) MRECURSION250( macro, DEC_(data)) macro(data, 250) -#define MRECURSION252(macro, data) MRECURSION251( macro, DEC_(data)) macro(data, 251) -#define MRECURSION253(macro, data) MRECURSION252( macro, DEC_(data)) macro(data, 252) -#define MRECURSION254(macro, data) MRECURSION253( macro, DEC_(data)) macro(data, 253) -#define MRECURSION255(macro, data) MRECURSION254( macro, DEC_(data)) macro(data, 254) -#define MRECURSION256(macro, data) MRECURSION255( macro, DEC_(data)) macro(data, 255) - -/** @} */ - -#endif /* _MRECURSION_H_ */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h deleted file mode 100644 index fb820d5..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h +++ /dev/null @@ -1,321 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef _MREPEAT_H_ -#define _MREPEAT_H_ - -/** - * \defgroup group_sam0_utils_mrepeat Preprocessor - Macro Repeat - * - * \ingroup group_sam0_utils - * - * @{ - */ - -#include "preprocessor.h" - -/** Maximal number of repetitions supported by MREPEAT. */ -#define MREPEAT_LIMIT 256 - -/** \brief Macro repeat. - * - * This macro represents a horizontal repetition construct. - * - * \param[in] count The number of repetitious calls to macro. Valid values - * range from 0 to MREPEAT_LIMIT. - * \param[in] macro A binary operation of the form macro(n, data). This macro - * is expanded by MREPEAT with the current repetition number - * and the auxiliary data argument. - * \param[in] data Auxiliary data passed to macro. - * - * \return macro(0, data) macro(1, data) ... macro(count - 1, data) - */ -#define MREPEAT(count, macro, data) TPASTE2(MREPEAT, count) (macro, data) - -#define MREPEAT0( macro, data) -#define MREPEAT1( macro, data) MREPEAT0( macro, data) macro( 0, data) -#define MREPEAT2( macro, data) MREPEAT1( macro, data) macro( 1, data) -#define MREPEAT3( macro, data) MREPEAT2( macro, data) macro( 2, data) -#define MREPEAT4( macro, data) MREPEAT3( macro, data) macro( 3, data) -#define MREPEAT5( macro, data) MREPEAT4( macro, data) macro( 4, data) -#define MREPEAT6( macro, data) MREPEAT5( macro, data) macro( 5, data) -#define MREPEAT7( macro, data) MREPEAT6( macro, data) macro( 6, data) -#define MREPEAT8( macro, data) MREPEAT7( macro, data) macro( 7, data) -#define MREPEAT9( macro, data) MREPEAT8( macro, data) macro( 8, data) -#define MREPEAT10( macro, data) MREPEAT9( macro, data) macro( 9, data) -#define MREPEAT11( macro, data) MREPEAT10( macro, data) macro( 10, data) -#define MREPEAT12( macro, data) MREPEAT11( macro, data) macro( 11, data) -#define MREPEAT13( macro, data) MREPEAT12( macro, data) macro( 12, data) -#define MREPEAT14( macro, data) MREPEAT13( macro, data) macro( 13, data) -#define MREPEAT15( macro, data) MREPEAT14( macro, data) macro( 14, data) -#define MREPEAT16( macro, data) MREPEAT15( macro, data) macro( 15, data) -#define MREPEAT17( macro, data) MREPEAT16( macro, data) macro( 16, data) -#define MREPEAT18( macro, data) MREPEAT17( macro, data) macro( 17, data) -#define MREPEAT19( macro, data) MREPEAT18( macro, data) macro( 18, data) -#define MREPEAT20( macro, data) MREPEAT19( macro, data) macro( 19, data) -#define MREPEAT21( macro, data) MREPEAT20( macro, data) macro( 20, data) -#define MREPEAT22( macro, data) MREPEAT21( macro, data) macro( 21, data) -#define MREPEAT23( macro, data) MREPEAT22( macro, data) macro( 22, data) -#define MREPEAT24( macro, data) MREPEAT23( macro, data) macro( 23, data) -#define MREPEAT25( macro, data) MREPEAT24( macro, data) macro( 24, data) -#define MREPEAT26( macro, data) MREPEAT25( macro, data) macro( 25, data) -#define MREPEAT27( macro, data) MREPEAT26( macro, data) macro( 26, data) -#define MREPEAT28( macro, data) MREPEAT27( macro, data) macro( 27, data) -#define MREPEAT29( macro, data) MREPEAT28( macro, data) macro( 28, data) -#define MREPEAT30( macro, data) MREPEAT29( macro, data) macro( 29, data) -#define MREPEAT31( macro, data) MREPEAT30( macro, data) macro( 30, data) -#define MREPEAT32( macro, data) MREPEAT31( macro, data) macro( 31, data) -#define MREPEAT33( macro, data) MREPEAT32( macro, data) macro( 32, data) -#define MREPEAT34( macro, data) MREPEAT33( macro, data) macro( 33, data) -#define MREPEAT35( macro, data) MREPEAT34( macro, data) macro( 34, data) -#define MREPEAT36( macro, data) MREPEAT35( macro, data) macro( 35, data) -#define MREPEAT37( macro, data) MREPEAT36( macro, data) macro( 36, data) -#define MREPEAT38( macro, data) MREPEAT37( macro, data) macro( 37, data) -#define MREPEAT39( macro, data) MREPEAT38( macro, data) macro( 38, data) -#define MREPEAT40( macro, data) MREPEAT39( macro, data) macro( 39, data) -#define MREPEAT41( macro, data) MREPEAT40( macro, data) macro( 40, data) -#define MREPEAT42( macro, data) MREPEAT41( macro, data) macro( 41, data) -#define MREPEAT43( macro, data) MREPEAT42( macro, data) macro( 42, data) -#define MREPEAT44( macro, data) MREPEAT43( macro, data) macro( 43, data) -#define MREPEAT45( macro, data) MREPEAT44( macro, data) macro( 44, data) -#define MREPEAT46( macro, data) MREPEAT45( macro, data) macro( 45, data) -#define MREPEAT47( macro, data) MREPEAT46( macro, data) macro( 46, data) -#define MREPEAT48( macro, data) MREPEAT47( macro, data) macro( 47, data) -#define MREPEAT49( macro, data) MREPEAT48( macro, data) macro( 48, data) -#define MREPEAT50( macro, data) MREPEAT49( macro, data) macro( 49, data) -#define MREPEAT51( macro, data) MREPEAT50( macro, data) macro( 50, data) -#define MREPEAT52( macro, data) MREPEAT51( macro, data) macro( 51, data) -#define MREPEAT53( macro, data) MREPEAT52( macro, data) macro( 52, data) -#define MREPEAT54( macro, data) MREPEAT53( macro, data) macro( 53, data) -#define MREPEAT55( macro, data) MREPEAT54( macro, data) macro( 54, data) -#define MREPEAT56( macro, data) MREPEAT55( macro, data) macro( 55, data) -#define MREPEAT57( macro, data) MREPEAT56( macro, data) macro( 56, data) -#define MREPEAT58( macro, data) MREPEAT57( macro, data) macro( 57, data) -#define MREPEAT59( macro, data) MREPEAT58( macro, data) macro( 58, data) -#define MREPEAT60( macro, data) MREPEAT59( macro, data) macro( 59, data) -#define MREPEAT61( macro, data) MREPEAT60( macro, data) macro( 60, data) -#define MREPEAT62( macro, data) MREPEAT61( macro, data) macro( 61, data) -#define MREPEAT63( macro, data) MREPEAT62( macro, data) macro( 62, data) -#define MREPEAT64( macro, data) MREPEAT63( macro, data) macro( 63, data) -#define MREPEAT65( macro, data) MREPEAT64( macro, data) macro( 64, data) -#define MREPEAT66( macro, data) MREPEAT65( macro, data) macro( 65, data) -#define MREPEAT67( macro, data) MREPEAT66( macro, data) macro( 66, data) -#define MREPEAT68( macro, data) MREPEAT67( macro, data) macro( 67, data) -#define MREPEAT69( macro, data) MREPEAT68( macro, data) macro( 68, data) -#define MREPEAT70( macro, data) MREPEAT69( macro, data) macro( 69, data) -#define MREPEAT71( macro, data) MREPEAT70( macro, data) macro( 70, data) -#define MREPEAT72( macro, data) MREPEAT71( macro, data) macro( 71, data) -#define MREPEAT73( macro, data) MREPEAT72( macro, data) macro( 72, data) -#define MREPEAT74( macro, data) MREPEAT73( macro, data) macro( 73, data) -#define MREPEAT75( macro, data) MREPEAT74( macro, data) macro( 74, data) -#define MREPEAT76( macro, data) MREPEAT75( macro, data) macro( 75, data) -#define MREPEAT77( macro, data) MREPEAT76( macro, data) macro( 76, data) -#define MREPEAT78( macro, data) MREPEAT77( macro, data) macro( 77, data) -#define MREPEAT79( macro, data) MREPEAT78( macro, data) macro( 78, data) -#define MREPEAT80( macro, data) MREPEAT79( macro, data) macro( 79, data) -#define MREPEAT81( macro, data) MREPEAT80( macro, data) macro( 80, data) -#define MREPEAT82( macro, data) MREPEAT81( macro, data) macro( 81, data) -#define MREPEAT83( macro, data) MREPEAT82( macro, data) macro( 82, data) -#define MREPEAT84( macro, data) MREPEAT83( macro, data) macro( 83, data) -#define MREPEAT85( macro, data) MREPEAT84( macro, data) macro( 84, data) -#define MREPEAT86( macro, data) MREPEAT85( macro, data) macro( 85, data) -#define MREPEAT87( macro, data) MREPEAT86( macro, data) macro( 86, data) -#define MREPEAT88( macro, data) MREPEAT87( macro, data) macro( 87, data) -#define MREPEAT89( macro, data) MREPEAT88( macro, data) macro( 88, data) -#define MREPEAT90( macro, data) MREPEAT89( macro, data) macro( 89, data) -#define MREPEAT91( macro, data) MREPEAT90( macro, data) macro( 90, data) -#define MREPEAT92( macro, data) MREPEAT91( macro, data) macro( 91, data) -#define MREPEAT93( macro, data) MREPEAT92( macro, data) macro( 92, data) -#define MREPEAT94( macro, data) MREPEAT93( macro, data) macro( 93, data) -#define MREPEAT95( macro, data) MREPEAT94( macro, data) macro( 94, data) -#define MREPEAT96( macro, data) MREPEAT95( macro, data) macro( 95, data) -#define MREPEAT97( macro, data) MREPEAT96( macro, data) macro( 96, data) -#define MREPEAT98( macro, data) MREPEAT97( macro, data) macro( 97, data) -#define MREPEAT99( macro, data) MREPEAT98( macro, data) macro( 98, data) -#define MREPEAT100(macro, data) MREPEAT99( macro, data) macro( 99, data) -#define MREPEAT101(macro, data) MREPEAT100(macro, data) macro(100, data) -#define MREPEAT102(macro, data) MREPEAT101(macro, data) macro(101, data) -#define MREPEAT103(macro, data) MREPEAT102(macro, data) macro(102, data) -#define MREPEAT104(macro, data) MREPEAT103(macro, data) macro(103, data) -#define MREPEAT105(macro, data) MREPEAT104(macro, data) macro(104, data) -#define MREPEAT106(macro, data) MREPEAT105(macro, data) macro(105, data) -#define MREPEAT107(macro, data) MREPEAT106(macro, data) macro(106, data) -#define MREPEAT108(macro, data) MREPEAT107(macro, data) macro(107, data) -#define MREPEAT109(macro, data) MREPEAT108(macro, data) macro(108, data) -#define MREPEAT110(macro, data) MREPEAT109(macro, data) macro(109, data) -#define MREPEAT111(macro, data) MREPEAT110(macro, data) macro(110, data) -#define MREPEAT112(macro, data) MREPEAT111(macro, data) macro(111, data) -#define MREPEAT113(macro, data) MREPEAT112(macro, data) macro(112, data) -#define MREPEAT114(macro, data) MREPEAT113(macro, data) macro(113, data) -#define MREPEAT115(macro, data) MREPEAT114(macro, data) macro(114, data) -#define MREPEAT116(macro, data) MREPEAT115(macro, data) macro(115, data) -#define MREPEAT117(macro, data) MREPEAT116(macro, data) macro(116, data) -#define MREPEAT118(macro, data) MREPEAT117(macro, data) macro(117, data) -#define MREPEAT119(macro, data) MREPEAT118(macro, data) macro(118, data) -#define MREPEAT120(macro, data) MREPEAT119(macro, data) macro(119, data) -#define MREPEAT121(macro, data) MREPEAT120(macro, data) macro(120, data) -#define MREPEAT122(macro, data) MREPEAT121(macro, data) macro(121, data) -#define MREPEAT123(macro, data) MREPEAT122(macro, data) macro(122, data) -#define MREPEAT124(macro, data) MREPEAT123(macro, data) macro(123, data) -#define MREPEAT125(macro, data) MREPEAT124(macro, data) macro(124, data) -#define MREPEAT126(macro, data) MREPEAT125(macro, data) macro(125, data) -#define MREPEAT127(macro, data) MREPEAT126(macro, data) macro(126, data) -#define MREPEAT128(macro, data) MREPEAT127(macro, data) macro(127, data) -#define MREPEAT129(macro, data) MREPEAT128(macro, data) macro(128, data) -#define MREPEAT130(macro, data) MREPEAT129(macro, data) macro(129, data) -#define MREPEAT131(macro, data) MREPEAT130(macro, data) macro(130, data) -#define MREPEAT132(macro, data) MREPEAT131(macro, data) macro(131, data) -#define MREPEAT133(macro, data) MREPEAT132(macro, data) macro(132, data) -#define MREPEAT134(macro, data) MREPEAT133(macro, data) macro(133, data) -#define MREPEAT135(macro, data) MREPEAT134(macro, data) macro(134, data) -#define MREPEAT136(macro, data) MREPEAT135(macro, data) macro(135, data) -#define MREPEAT137(macro, data) MREPEAT136(macro, data) macro(136, data) -#define MREPEAT138(macro, data) MREPEAT137(macro, data) macro(137, data) -#define MREPEAT139(macro, data) MREPEAT138(macro, data) macro(138, data) -#define MREPEAT140(macro, data) MREPEAT139(macro, data) macro(139, data) -#define MREPEAT141(macro, data) MREPEAT140(macro, data) macro(140, data) -#define MREPEAT142(macro, data) MREPEAT141(macro, data) macro(141, data) -#define MREPEAT143(macro, data) MREPEAT142(macro, data) macro(142, data) -#define MREPEAT144(macro, data) MREPEAT143(macro, data) macro(143, data) -#define MREPEAT145(macro, data) MREPEAT144(macro, data) macro(144, data) -#define MREPEAT146(macro, data) MREPEAT145(macro, data) macro(145, data) -#define MREPEAT147(macro, data) MREPEAT146(macro, data) macro(146, data) -#define MREPEAT148(macro, data) MREPEAT147(macro, data) macro(147, data) -#define MREPEAT149(macro, data) MREPEAT148(macro, data) macro(148, data) -#define MREPEAT150(macro, data) MREPEAT149(macro, data) macro(149, data) -#define MREPEAT151(macro, data) MREPEAT150(macro, data) macro(150, data) -#define MREPEAT152(macro, data) MREPEAT151(macro, data) macro(151, data) -#define MREPEAT153(macro, data) MREPEAT152(macro, data) macro(152, data) -#define MREPEAT154(macro, data) MREPEAT153(macro, data) macro(153, data) -#define MREPEAT155(macro, data) MREPEAT154(macro, data) macro(154, data) -#define MREPEAT156(macro, data) MREPEAT155(macro, data) macro(155, data) -#define MREPEAT157(macro, data) MREPEAT156(macro, data) macro(156, data) -#define MREPEAT158(macro, data) MREPEAT157(macro, data) macro(157, data) -#define MREPEAT159(macro, data) MREPEAT158(macro, data) macro(158, data) -#define MREPEAT160(macro, data) MREPEAT159(macro, data) macro(159, data) -#define MREPEAT161(macro, data) MREPEAT160(macro, data) macro(160, data) -#define MREPEAT162(macro, data) MREPEAT161(macro, data) macro(161, data) -#define MREPEAT163(macro, data) MREPEAT162(macro, data) macro(162, data) -#define MREPEAT164(macro, data) MREPEAT163(macro, data) macro(163, data) -#define MREPEAT165(macro, data) MREPEAT164(macro, data) macro(164, data) -#define MREPEAT166(macro, data) MREPEAT165(macro, data) macro(165, data) -#define MREPEAT167(macro, data) MREPEAT166(macro, data) macro(166, data) -#define MREPEAT168(macro, data) MREPEAT167(macro, data) macro(167, data) -#define MREPEAT169(macro, data) MREPEAT168(macro, data) macro(168, data) -#define MREPEAT170(macro, data) MREPEAT169(macro, data) macro(169, data) -#define MREPEAT171(macro, data) MREPEAT170(macro, data) macro(170, data) -#define MREPEAT172(macro, data) MREPEAT171(macro, data) macro(171, data) -#define MREPEAT173(macro, data) MREPEAT172(macro, data) macro(172, data) -#define MREPEAT174(macro, data) MREPEAT173(macro, data) macro(173, data) -#define MREPEAT175(macro, data) MREPEAT174(macro, data) macro(174, data) -#define MREPEAT176(macro, data) MREPEAT175(macro, data) macro(175, data) -#define MREPEAT177(macro, data) MREPEAT176(macro, data) macro(176, data) -#define MREPEAT178(macro, data) MREPEAT177(macro, data) macro(177, data) -#define MREPEAT179(macro, data) MREPEAT178(macro, data) macro(178, data) -#define MREPEAT180(macro, data) MREPEAT179(macro, data) macro(179, data) -#define MREPEAT181(macro, data) MREPEAT180(macro, data) macro(180, data) -#define MREPEAT182(macro, data) MREPEAT181(macro, data) macro(181, data) -#define MREPEAT183(macro, data) MREPEAT182(macro, data) macro(182, data) -#define MREPEAT184(macro, data) MREPEAT183(macro, data) macro(183, data) -#define MREPEAT185(macro, data) MREPEAT184(macro, data) macro(184, data) -#define MREPEAT186(macro, data) MREPEAT185(macro, data) macro(185, data) -#define MREPEAT187(macro, data) MREPEAT186(macro, data) macro(186, data) -#define MREPEAT188(macro, data) MREPEAT187(macro, data) macro(187, data) -#define MREPEAT189(macro, data) MREPEAT188(macro, data) macro(188, data) -#define MREPEAT190(macro, data) MREPEAT189(macro, data) macro(189, data) -#define MREPEAT191(macro, data) MREPEAT190(macro, data) macro(190, data) -#define MREPEAT192(macro, data) MREPEAT191(macro, data) macro(191, data) -#define MREPEAT193(macro, data) MREPEAT192(macro, data) macro(192, data) -#define MREPEAT194(macro, data) MREPEAT193(macro, data) macro(193, data) -#define MREPEAT195(macro, data) MREPEAT194(macro, data) macro(194, data) -#define MREPEAT196(macro, data) MREPEAT195(macro, data) macro(195, data) -#define MREPEAT197(macro, data) MREPEAT196(macro, data) macro(196, data) -#define MREPEAT198(macro, data) MREPEAT197(macro, data) macro(197, data) -#define MREPEAT199(macro, data) MREPEAT198(macro, data) macro(198, data) -#define MREPEAT200(macro, data) MREPEAT199(macro, data) macro(199, data) -#define MREPEAT201(macro, data) MREPEAT200(macro, data) macro(200, data) -#define MREPEAT202(macro, data) MREPEAT201(macro, data) macro(201, data) -#define MREPEAT203(macro, data) MREPEAT202(macro, data) macro(202, data) -#define MREPEAT204(macro, data) MREPEAT203(macro, data) macro(203, data) -#define MREPEAT205(macro, data) MREPEAT204(macro, data) macro(204, data) -#define MREPEAT206(macro, data) MREPEAT205(macro, data) macro(205, data) -#define MREPEAT207(macro, data) MREPEAT206(macro, data) macro(206, data) -#define MREPEAT208(macro, data) MREPEAT207(macro, data) macro(207, data) -#define MREPEAT209(macro, data) MREPEAT208(macro, data) macro(208, data) -#define MREPEAT210(macro, data) MREPEAT209(macro, data) macro(209, data) -#define MREPEAT211(macro, data) MREPEAT210(macro, data) macro(210, data) -#define MREPEAT212(macro, data) MREPEAT211(macro, data) macro(211, data) -#define MREPEAT213(macro, data) MREPEAT212(macro, data) macro(212, data) -#define MREPEAT214(macro, data) MREPEAT213(macro, data) macro(213, data) -#define MREPEAT215(macro, data) MREPEAT214(macro, data) macro(214, data) -#define MREPEAT216(macro, data) MREPEAT215(macro, data) macro(215, data) -#define MREPEAT217(macro, data) MREPEAT216(macro, data) macro(216, data) -#define MREPEAT218(macro, data) MREPEAT217(macro, data) macro(217, data) -#define MREPEAT219(macro, data) MREPEAT218(macro, data) macro(218, data) -#define MREPEAT220(macro, data) MREPEAT219(macro, data) macro(219, data) -#define MREPEAT221(macro, data) MREPEAT220(macro, data) macro(220, data) -#define MREPEAT222(macro, data) MREPEAT221(macro, data) macro(221, data) -#define MREPEAT223(macro, data) MREPEAT222(macro, data) macro(222, data) -#define MREPEAT224(macro, data) MREPEAT223(macro, data) macro(223, data) -#define MREPEAT225(macro, data) MREPEAT224(macro, data) macro(224, data) -#define MREPEAT226(macro, data) MREPEAT225(macro, data) macro(225, data) -#define MREPEAT227(macro, data) MREPEAT226(macro, data) macro(226, data) -#define MREPEAT228(macro, data) MREPEAT227(macro, data) macro(227, data) -#define MREPEAT229(macro, data) MREPEAT228(macro, data) macro(228, data) -#define MREPEAT230(macro, data) MREPEAT229(macro, data) macro(229, data) -#define MREPEAT231(macro, data) MREPEAT230(macro, data) macro(230, data) -#define MREPEAT232(macro, data) MREPEAT231(macro, data) macro(231, data) -#define MREPEAT233(macro, data) MREPEAT232(macro, data) macro(232, data) -#define MREPEAT234(macro, data) MREPEAT233(macro, data) macro(233, data) -#define MREPEAT235(macro, data) MREPEAT234(macro, data) macro(234, data) -#define MREPEAT236(macro, data) MREPEAT235(macro, data) macro(235, data) -#define MREPEAT237(macro, data) MREPEAT236(macro, data) macro(236, data) -#define MREPEAT238(macro, data) MREPEAT237(macro, data) macro(237, data) -#define MREPEAT239(macro, data) MREPEAT238(macro, data) macro(238, data) -#define MREPEAT240(macro, data) MREPEAT239(macro, data) macro(239, data) -#define MREPEAT241(macro, data) MREPEAT240(macro, data) macro(240, data) -#define MREPEAT242(macro, data) MREPEAT241(macro, data) macro(241, data) -#define MREPEAT243(macro, data) MREPEAT242(macro, data) macro(242, data) -#define MREPEAT244(macro, data) MREPEAT243(macro, data) macro(243, data) -#define MREPEAT245(macro, data) MREPEAT244(macro, data) macro(244, data) -#define MREPEAT246(macro, data) MREPEAT245(macro, data) macro(245, data) -#define MREPEAT247(macro, data) MREPEAT246(macro, data) macro(246, data) -#define MREPEAT248(macro, data) MREPEAT247(macro, data) macro(247, data) -#define MREPEAT249(macro, data) MREPEAT248(macro, data) macro(248, data) -#define MREPEAT250(macro, data) MREPEAT249(macro, data) macro(249, data) -#define MREPEAT251(macro, data) MREPEAT250(macro, data) macro(250, data) -#define MREPEAT252(macro, data) MREPEAT251(macro, data) macro(251, data) -#define MREPEAT253(macro, data) MREPEAT252(macro, data) macro(252, data) -#define MREPEAT254(macro, data) MREPEAT253(macro, data) macro(253, data) -#define MREPEAT255(macro, data) MREPEAT254(macro, data) macro(254, data) -#define MREPEAT256(macro, data) MREPEAT255(macro, data) macro(255, data) - -/** @} */ - -#endif /* _MREPEAT_H_ */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h deleted file mode 100644 index 7f67d8a..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h +++ /dev/null @@ -1,38 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef _PREPROCESSOR_H_ -#define _PREPROCESSOR_H_ - -#include "tpaste.h" -#include "stringz.h" -#include "mrepeat.h" -#include "mrecursion.h" - -#endif // _PREPROCESSOR_H_ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/stringz.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/stringz.h deleted file mode 100644 index 70937c4..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/stringz.h +++ /dev/null @@ -1,67 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef _STRINGZ_H_ -#define _STRINGZ_H_ - -/** - * \defgroup group_sam0_utils_stringz Preprocessor - Stringize - * - * \ingroup group_sam0_utils - * - * @{ - */ - -/** \brief Stringize. - * - * Stringize a preprocessing token, this token being allowed to be \#defined. - * - * May be used only within macros with the token passed as an argument if the - * token is \#defined. - * - * For example, writing STRINGZ(PIN) within a macro \#defined by PIN_NAME(PIN) - * and invoked as PIN_NAME(PIN0) with PIN0 \#defined as A0 is equivalent to - * writing "A0". - */ -#define STRINGZ(x) #x - -/** \brief Absolute stringize. - * - * Stringize a preprocessing token, this token being allowed to be \#defined. - * - * No restriction of use if the token is \#defined. - * - * For example, writing ASTRINGZ(PIN0) anywhere with PIN0 \#defined as A0 is - * equivalent to writing "A0". - */ -#define ASTRINGZ(x) STRINGZ(x) - -/** @} */ - -#endif // _STRINGZ_H_ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/tpaste.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/tpaste.h deleted file mode 100644 index 9108183..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/preprocessor/tpaste.h +++ /dev/null @@ -1,85 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ -#ifndef _TPASTE_H_ -#define _TPASTE_H_ - -/** - * \defgroup group_sam0_utils_tpaste Preprocessor - Token Paste - * - * \ingroup group_sam0_utils - * - * @{ - */ - -/** \name Token Paste - * - * Paste N preprocessing tokens together, these tokens being allowed to be \#defined. - * - * May be used only within macros with the tokens passed as arguments if the tokens are \#defined. - * - * For example, writing TPASTE2(U, WIDTH) within a macro \#defined by - * UTYPE(WIDTH) and invoked as UTYPE(UL_WIDTH) with UL_WIDTH \#defined as 32 is - * equivalent to writing U32. - * - * @{ */ -#define TPASTE2( a, b) a##b -#define TPASTE3( a, b, c) a##b##c -#define TPASTE4( a, b, c, d) a##b##c##d -#define TPASTE5( a, b, c, d, e) a##b##c##d##e -#define TPASTE6( a, b, c, d, e, f) a##b##c##d##e##f -#define TPASTE7( a, b, c, d, e, f, g) a##b##c##d##e##f##g -#define TPASTE8( a, b, c, d, e, f, g, h) a##b##c##d##e##f##g##h -#define TPASTE9( a, b, c, d, e, f, g, h, i) a##b##c##d##e##f##g##h##i -#define TPASTE10(a, b, c, d, e, f, g, h, i, j) a##b##c##d##e##f##g##h##i##j -/** @} */ - -/** \name Absolute Token Paste - * - * Paste N preprocessing tokens together, these tokens being allowed to be \#defined. - * - * No restriction of use if the tokens are \#defined. - * - * For example, writing ATPASTE2(U, UL_WIDTH) anywhere with UL_WIDTH \#defined - * as 32 is equivalent to writing U32. - * - * @{ */ -#define ATPASTE2( a, b) TPASTE2( a, b) -#define ATPASTE3( a, b, c) TPASTE3( a, b, c) -#define ATPASTE4( a, b, c, d) TPASTE4( a, b, c, d) -#define ATPASTE5( a, b, c, d, e) TPASTE5( a, b, c, d, e) -#define ATPASTE6( a, b, c, d, e, f) TPASTE6( a, b, c, d, e, f) -#define ATPASTE7( a, b, c, d, e, f, g) TPASTE7( a, b, c, d, e, f, g) -#define ATPASTE8( a, b, c, d, e, f, g, h) TPASTE8( a, b, c, d, e, f, g, h) -#define ATPASTE9( a, b, c, d, e, f, g, h, i) TPASTE9( a, b, c, d, e, f, g, h, i) -#define ATPASTE10(a, b, c, d, e, f, g, h, i, j) TPASTE10(a, b, c, d, e, f, g, h, i, j) -/** @} */ - -/** @} */ - -#endif // _TPASTE_H_ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/reset.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/reset.h deleted file mode 100644 index ae1eb5a..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/reset.h +++ /dev/null @@ -1,119 +0,0 @@ -/** - * \file - * - * \brief SAM Reset related functionality - * - * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef RESET_H_INCLUDED -#define RESET_H_INCLUDED - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \addtogroup asfdoc_sam0_system_group - * @{ - */ - -/** - * \brief Reset causes of the system. - * - * List of possible reset causes of the system. - */ -enum system_reset_cause { - /** The system was last reset by a software reset. */ - SYSTEM_RESET_CAUSE_SOFTWARE = PM_RCAUSE_SYST, - /** The system was last reset by the watchdog timer. */ - SYSTEM_RESET_CAUSE_WDT = PM_RCAUSE_WDT, - /** The system was last reset because the external reset line was pulled low. */ - SYSTEM_RESET_CAUSE_EXTERNAL_RESET = PM_RCAUSE_EXT, - /** The system was last reset by the BOD33. */ - SYSTEM_RESET_CAUSE_BOD33 = PM_RCAUSE_BOD33, - /** The system was last reset by the BOD12. */ - SYSTEM_RESET_CAUSE_BOD12 = PM_RCAUSE_BOD12, - /** The system was last reset by the POR (Power on reset). */ - SYSTEM_RESET_CAUSE_POR = PM_RCAUSE_POR, -}; - - -/** - * \name Reset Control - * @{ - */ - -/** - * \brief Reset the MCU. - * - * Resets the MCU and all associated peripherals and registers, except RTC, all 32KHz sources, - * WDT (if ALWAYSON is set) and GCLK (if WRTLOCK is set). - * - */ -static inline void system_reset(void) -{ - NVIC_SystemReset(); -} - -/** - * \brief Return the reset cause. - * - * Retrieves the cause of the last system reset. - * - * \return An enum value indicating the cause of the last system reset. - */ -static inline enum system_reset_cause system_get_reset_cause(void) -{ - return (enum system_reset_cause)PM->RCAUSE.reg; -} - -/** - * @} - */ - -/** @} */ -#ifdef __cplusplus -} -#endif - -#endif /* RESET_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/status_codes.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/status_codes.h deleted file mode 100644 index 29bbf41..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/status_codes.h +++ /dev/null @@ -1,138 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef STATUS_CODES_H_INCLUDED -#define STATUS_CODES_H_INCLUDED - -#include - -/** - * \defgroup group_sam0_utils_status_codes Status Codes - * - * \ingroup group_sam0_utils - * - * @{ - */ - -/** Mask to retrieve the error category of a status code. */ -#define STATUS_CATEGORY_MASK 0xF0 - -/** Mask to retrieve the error code within the category of a status code. */ -#define STATUS_ERROR_MASK 0x0F - -/** Status code error categories. */ -enum status_categories { - STATUS_CATEGORY_OK = 0x00, - STATUS_CATEGORY_COMMON = 0x10, - STATUS_CATEGORY_ANALOG = 0x30, - STATUS_CATEGORY_COM = 0x40, - STATUS_CATEGORY_IO = 0x50, -}; - -/** - * Status code that may be returned by shell commands and protocol - * implementations. - * - * \note Any change to these status codes and the corresponding - * message strings is strictly forbidden. New codes can be added, - * however, but make sure that any message string tables are updated - * at the same time. - */ -enum status_code { - STATUS_OK = STATUS_CATEGORY_OK | 0x00, - STATUS_VALID_DATA = STATUS_CATEGORY_OK | 0x01, - STATUS_NO_CHANGE = STATUS_CATEGORY_OK | 0x02, - STATUS_ABORTED = STATUS_CATEGORY_OK | 0x04, - STATUS_BUSY = STATUS_CATEGORY_OK | 0x05, - STATUS_SUSPEND = STATUS_CATEGORY_OK | 0x06, - - STATUS_ERR_IO = STATUS_CATEGORY_COMMON | 0x00, - STATUS_ERR_REQ_FLUSHED = STATUS_CATEGORY_COMMON | 0x01, - STATUS_ERR_TIMEOUT = STATUS_CATEGORY_COMMON | 0x02, - STATUS_ERR_BAD_DATA = STATUS_CATEGORY_COMMON | 0x03, - STATUS_ERR_NOT_FOUND = STATUS_CATEGORY_COMMON | 0x04, - STATUS_ERR_UNSUPPORTED_DEV = STATUS_CATEGORY_COMMON | 0x05, - STATUS_ERR_NO_MEMORY = STATUS_CATEGORY_COMMON | 0x06, - STATUS_ERR_INVALID_ARG = STATUS_CATEGORY_COMMON | 0x07, - STATUS_ERR_BAD_ADDRESS = STATUS_CATEGORY_COMMON | 0x08, - STATUS_ERR_BAD_FORMAT = STATUS_CATEGORY_COMMON | 0x0A, - STATUS_ERR_BAD_FRQ = STATUS_CATEGORY_COMMON | 0x0B, - STATUS_ERR_DENIED = STATUS_CATEGORY_COMMON | 0x0c, - STATUS_ERR_ALREADY_INITIALIZED = STATUS_CATEGORY_COMMON | 0x0d, - STATUS_ERR_OVERFLOW = STATUS_CATEGORY_COMMON | 0x0e, - STATUS_ERR_NOT_INITIALIZED = STATUS_CATEGORY_COMMON | 0x0f, - - STATUS_ERR_SAMPLERATE_UNAVAILABLE = STATUS_CATEGORY_ANALOG | 0x00, - STATUS_ERR_RESOLUTION_UNAVAILABLE = STATUS_CATEGORY_ANALOG | 0x01, - - STATUS_ERR_BAUDRATE_UNAVAILABLE = STATUS_CATEGORY_COM | 0x00, - STATUS_ERR_PACKET_COLLISION = STATUS_CATEGORY_COM | 0x01, - STATUS_ERR_PROTOCOL = STATUS_CATEGORY_COM | 0x02, - - STATUS_ERR_PIN_MUX_INVALID = STATUS_CATEGORY_IO | 0x00, -}; -typedef enum status_code status_code_genare_t; - -/** - Status codes used by MAC stack. - */ -enum status_code_wireless { - //STATUS_OK = 0, //!< Success - ERR_IO_ERROR = -1, //!< I/O error - ERR_FLUSHED = -2, //!< Request flushed from queue - ERR_TIMEOUT = -3, //!< Operation timed out - ERR_BAD_DATA = -4, //!< Data integrity check failed - ERR_PROTOCOL = -5, //!< Protocol error - ERR_UNSUPPORTED_DEV = -6, //!< Unsupported device - ERR_NO_MEMORY = -7, //!< Insufficient memory - ERR_INVALID_ARG = -8, //!< Invalid argument - ERR_BAD_ADDRESS = -9, //!< Bad address - ERR_BUSY = -10, //!< Resource is busy - ERR_BAD_FORMAT = -11, //!< Data format not recognized - ERR_NO_TIMER = -12, //!< No timer available - ERR_TIMER_ALREADY_RUNNING = -13, //!< Timer already running - ERR_TIMER_NOT_RUNNING = -14, //!< Timer not running - - /** - * \brief Operation in progress - * - * This status code is for driver-internal use when an operation - * is currently being performed. - * - * \note Drivers should never return this status code to any - * callers. It is strictly for internal use. - */ - OPERATION_IN_PROGRESS = -128, -}; - -typedef enum status_code_wireless status_code_t; - -/** @} */ - -#endif /* STATUS_CODES_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/system.c b/feather_sensor_transmit/libraries/Adafruit_ASFcore/system.c deleted file mode 100644 index 0121588..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/system.c +++ /dev/null @@ -1,111 +0,0 @@ -/** - * \file - * - * \brief SAM System related functionality - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#include - -/** - * \internal - * Dummy initialization function, used as a weak alias target for the various - * init functions called by \ref system_init(). - */ -void _system_dummy_init(void); -void _system_dummy_init(void) -{ - return; -} - -#if !defined(__DOXYGEN__) -# if defined(__GNUC__) -void system_clock_init(void) WEAK __attribute__((alias("_system_dummy_init"))); -void system_board_init(void) WEAK __attribute__((alias("_system_dummy_init"))); -void _system_events_init(void) WEAK __attribute__((alias("_system_dummy_init"))); -void _system_extint_init(void) WEAK __attribute__((alias("_system_dummy_init"))); -void _system_divas_init(void) WEAK __attribute__((alias("_system_dummy_init"))); -# elif defined(__ICCARM__) -void system_clock_init(void); -void system_board_init(void); -void _system_events_init(void); -void _system_extint_init(void); -void _system_divas_init(void); -# pragma weak system_clock_init=_system_dummy_init -# pragma weak system_board_init=_system_dummy_init -# pragma weak _system_events_init=_system_dummy_init -# pragma weak _system_extint_init=_system_dummy_init -# pragma weak _system_divas_init=_system_dummy_init -# endif -#endif - -/** - * \brief Initialize system - * - * This function will call the various initialization functions within the - * system namespace. If a given optional system module is not available, the - * associated call will effectively be a NOP (No Operation). - * - * Currently the following initialization functions are supported: - * - System clock initialization (via the SYSTEM CLOCK sub-module) - * - Board hardware initialization (via the Board module) - * - Event system driver initialization (via the EVSYS module) - * - External Interrupt driver initialization (via the EXTINT module) - */ -void system_init(void) -{ - /* Configure GCLK and clock sources according to conf_clocks.h */ - system_clock_init(); - - /* Initialize board hardware */ - system_board_init(); - - /* Initialize EVSYS hardware */ - _system_events_init(); - - /* Initialize External hardware */ - _system_extint_init(); - - /* Initialize DIVAS hardware */ - _system_divas_init(); -} - diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/system.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/system.h deleted file mode 100644 index 7b7bc00..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/system.h +++ /dev/null @@ -1,726 +0,0 @@ -/** - * \file - * - * \brief SAM System related functionality - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef SYSTEM_H_INCLUDED -#define SYSTEM_H_INCLUDED - -#include -#include -#include -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \defgroup asfdoc_sam0_system_group SAM System (SYSTEM) Driver - * - * This driver for Atmel® | SMART ARM®-based microcontrollers provides an interface for the configuration - * and management of the device's system relation functionality, necessary for - * the basic device operation. This is not limited to a single peripheral, but - * extends across multiple hardware peripherals. - * - * The following peripherals are used by this module: - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - PM (Power Manager) - * - RSTC(Reset Controller) - * - SUPC(Supply Controller) - * \endif - * \if DEVICE_SAMC21_SYSTEM_SUPPORT - * - PM (Power Manager) - * - RSTC(Reset Controller) - * - SUPC(Supply Controller) - * \endif - * \if DEVICE_SAMD21_SYSTEM_SUPPORT - * - SYSCTRL (System Control) - * - PM (Power Manager) - * \endif - * - * The following devices can use this module: - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - Atmel | SMART SAM L21 - * \endif - * \if DEVICE_SAMC21_SYSTEM_SUPPORT - * - Atmel | SMART SAM C20/C21 - * \endif - * \if DEVICE_SAMD21_SYSTEM_SUPPORT - * - Atmel | SMART SAM D20/D21 - * - Atmel | SMART SAM R21 - * - Atmel | SMART SAM D09/D10/D11 - * - Atmel | SMART SAM DAx - * \endif - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_system_prerequisites - * - \ref asfdoc_sam0_system_module_overview - * - \ref asfdoc_sam0_system_special_considerations - * - \ref asfdoc_sam0_system_extra_info - * - \ref asfdoc_sam0_system_examples - * - \ref asfdoc_sam0_system_api_overview - * - * - * \section asfdoc_sam0_system_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * - * \section asfdoc_sam0_system_module_overview Module Overview - * - * The System driver provides a collection of interfaces between the user - * application logic, and the core device functionality (such as clocks, reset - * cause determination, etc.) that is required for all applications. It contains - * a number of sub-modules that control one specific aspect of the device: - * - * - System Core (this module) - * - \ref asfdoc_sam0_system_clock_group "System Clock Control" (sub-module) - * - \ref asfdoc_sam0_system_interrupt_group "System Interrupt Control" (sub-module) - * - \ref asfdoc_sam0_system_pinmux_group "System Pin Multiplexer Control" (sub-module) - * - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * \subsection asfdoc_sam0_system_module_overview_vreg_l21 Voltage Regulator - * The SAM device controls the voltage regulators for the core (VDDCORE) and - * backup (VDDBU) domains. It sets the voltage regulators according to the sleep - * modes, the performance level, or the user configuration. - * - * In active mode, the voltage regulator can be chosen on the fly between a LDO - * or a Buck converter. In standby mode, the low power voltage regulator is used - * to supply VDDCORE. - * - * \subsection asfdoc_sam0_system_module_overview_bbps Battery Backup Power Switch - * The SAM device supports connection of a battery backup to the VBAT power pin. - * It includes functionality that enables automatic power switching between main - * power and battery backup power. This will ensure power to the backup domain, - * when the main battery or power source is unavailable. - * \endif - * - * \if DEVICE_SAMC21_SYSTEM_SUPPORT - * \subsection asfdoc_sam0_system_module_overview_vreg_c21 Voltage Regulator - * The SAM device controls the voltage regulators for the core (VDDCORE). It sets - * the voltage regulators according to the sleep modes. - * - * There are a selectable reference voltage and voltage dependent on the temperature - * which can be used by analog modules like the ADC. - * \endif - * - * \subsection asfdoc_sam0_system_module_overview_vref Voltage References - * The various analog modules within the SAM devices (such as AC, ADC, and - * DAC) require a voltage reference to be configured to act as a reference point - * for comparisons and conversions. - * - * The SAM devices contain multiple references, including an internal - * temperature sensor and a fixed band-gap voltage source. When enabled, the - * associated voltage reference can be selected within the desired peripheral - * where applicable. - * - * \subsection asfdoc_sam0_system_module_overview_reset_cause System Reset Cause - * In some applications there may be a need to execute a different program - * flow based on how the device was reset. For example, if the cause of reset - * was the Watchdog timer (WDT), this might indicate an error in the application, - * and a form of error handling or error logging might be needed. - * - * For this reason, an API is provided to retrieve the cause of the last system - * reset, so that appropriate action can be taken. - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * There are three groups of reset sources: - * - Power supply reset: Resets caused by an electrical issue. It covers POR and BOD reset. - * - User reset: Resets caused by the application. It covers external reset, - * system reset, and watchdog reset. - * - Backup reset: Resets caused by a backup mode exit condition. - * - * \subsection asfdoc_sam0_system_module_overview_performance_level Performance Level - * Performance level allows the user to adjust the regulator output voltage to reduce - * power consumption. The user can on the fly select the most suitable performance - * level, depending on the application demands. - * - * The SAM device can operate at two different performance levels (PL0 and PL2). - * When operating at PL0, the voltage applied on the full logic area is reduced - * by voltage scaling. This voltage scaling technique allows to reduce the active - * power consumption while decreasing the maximum frequency of the device. When - * operating at PL2, the voltage regulator supplies the highest voltage, allowing - * the device to run at higher clock speeds. - * - * Performance level transition is possible only when the device is in active - * mode. After a reset, the device starts at the lowest performance level - * (lowest power consumption and lowest max. frequency). The application can then - * switch to another performance level at any time without any stop in the code - * execution. As shown in \ref asfdoc_sam0_system_performance_level_transition_figure. - * - * \note When scaling down the performance level, the bus frequency should first be - * scaled down in order to not exceed the maximum frequency allowed for the - * low performance level. - * When scaling up the performance level (e.g. from PL0 to PL2), check the performance - * level status before increasing the bus frequency. It can be increased only - * when the performance level transition is completed. - * - * \anchor asfdoc_sam0_system_performance_level_transition_figure - * \image html performance_level_transition.svg "Performance Level Transition" - * - * \subsection asfdoc_sam0_system_module_overview_power_domain Power Domain Gating - * Power domain gating allows power saving by reducing the voltage in logic - * areas in the device to a low-power supply. The feature is available in - * Standby sleep mode and will reduce the voltage in domains where all peripherals - * are idle. Internal logic will maintain its content, meaning the corresponding - * peripherals will not need to be reconfigured when normal operating voltage - * is returned. Most power domains can be in the following three states: - * - * - Active state: The power domain is powered on. - * - Retention state: The main voltage supply for the power domain is switched off, - * while maintaining a secondary low-power supply for the sequential cells. The - * logic context is restored when waking up. - * - Off state: The power domain is entirely powered off. The logic context is lost. - * - * The SAM L21 device contains three power domains which can be controlled using - * power domain gating, namely PD0, PD1, and PD2. These power domains can be - * configured to the following cases: - * - Default with no sleepwalking peripherals: A power domain is automatically set - * to retention state in standby sleep mode if no activity require it. The application - * can force all power domains to remain in active state during standby sleep mode - * in order to accelerate wakeup time. - * - Default with sleepwalking peripherals: If one or more peripherals are enabled - * to perform sleepwalking tasks in standby sleep mode, the corresponding power - * domain (PDn) remains in active state as well as all inferior power domains (PDn) in order - * to perform a sleepwalking task. The superior power domain is then automatically - * set to active state. At the end of the sleepwalking task, the device can either - * be woken up or the superior power domain can return to retention state. - * - * Power domains can be linked to each other, it allows a power domain (PDn) to be kept - * in active state if the inferior power domain (PDn-1) is in active state too. - * - * \ref asfdoc_sam0_system_power_domain_overview_table illustrates the - * four cases to consider in standby mode. - * - * \anchor asfdoc_sam0_system_power_domain_overview_table - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Sleep Mode versus Power Domain State Overview
Sleep modePD0PD1PD2PDTOPPDBACKUP
Idleactiveactiveactiveactiveactive
Standby - Case 1activeactiveactiveactiveactive
Standby - Case 2activeactiveretentionactiveactive
Standby - Case 3activeretentionretentionactiveactive
Standby - Case 4retentionretentionretentionactiveactive
Backupoffoffoffoffactive
Offoffoffoffoffoff
- * - * \subsection asfdoc_sam0_system_module_overview_ram_state RAMs Low Power Mode - * By default, in standby sleep mode, RAM is in low power mode (back biased) - * if its power domain is in retention state. - * \ref asfdoc_sam0_system_power_ram_state_table lists RAMs low power mode. - * - * \anchor asfdoc_sam0_system_power_ram_state_table - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
RAM Back-biasing Mode
RAM modeDescription
Retention Back-biasing modeRAM is back-biased if its power domain is in retention mode
Standby Back-biasing modeRAM is back-biased if the device is in standby mode
Standby OFF modeRAM is OFF if the device is in standby mode
Always OFF modeRAM is OFF if the device is in RET mode
- * - * \endif - * - * \subsection asfdoc_sam0_system_module_overview_sleep_mode Sleep Modes - * The SAM devices have several sleep modes. The sleep mode controls - * which clock systems on the device will remain enabled or disabled when the - * device enters a low power sleep mode. - * \ref asfdoc_sam0_system_module_sleep_mode_table "The table below" lists the - * clock settings of the different sleep modes. - * - * \anchor asfdoc_sam0_system_module_sleep_mode_table - * - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * \else - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * \endif - *
SAM Device Sleep Modes
Sleep modeSystem clockCPU clockAHB/AHB clockGCLK clocksOscillators (ONDEMAND = 0)Oscillators (ONDEMAND = 1)Regulator modeRAM mode
IdleRunStopRun if requestedRunRunRun if requestedNormalNormal
StandbyStopStopRun if requestedRun if requestedRun if requested or RUNSTDBY = 1Run if requestedLow pwerLow pwer
BackupStopStopStopStopStopStopBackupOff
OffOffOffOffOffOffOffOffOff
Sleep modeCPU clockAHB clockAPB clocksClock sourcesSystem clock32KHzReg modeRAM mode
Idle 0StopRunRunRunRunRunNormalNormal
Idle 1StopStopRunRunRunRunNormalNormal
Idle 2StopStopStopRunRunRunNormalNormal
StandbyStopStopStopStopStopStopLow PowerSource/Drain biasing
- * - * Before entering device sleep, one of the available sleep modes must be set. - * The device will automatically wake up in response to an interrupt being - * generated or upon any other sleep mode exit condition. - * - * Some peripheral clocks will remain enabled during sleep, depending on their - * configuration. If desired, the modules can remain clocked during sleep to allow - * them continue to operate while other parts of the system are powered down - * to save power. - * - * - * \section asfdoc_sam0_system_special_considerations Special Considerations - * - * Most of the functions in this driver have device specific restrictions and - * caveats; refer to your device datasheet. - * - * - * \section asfdoc_sam0_system_extra_info Extra Information - * - * For extra information, see \ref asfdoc_sam0_system_extra. This includes: - * - \ref asfdoc_sam0_system_extra_acronyms - * - \ref asfdoc_sam0_system_extra_dependencies - * - \ref asfdoc_sam0_system_extra_errata - * - \ref asfdoc_sam0_system_extra_history - * - * - * \section asfdoc_sam0_system_examples Examples - * - * For SYSTEM module related examples, refer to the sub-modules listed in - * the \ref asfdoc_sam0_system_module_overview "system module overview". - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_drivers_power_exqsg. - * - * - * \section asfdoc_sam0_system_api_overview API Overview - * @{ - */ - -/** - * \name System Debugger - * @{ - */ - -/** - * \brief Check if debugger is present. - * - * Check if debugger is connected to the onboard debug system (DAP). - * - * \return A bool identifying if a debugger is present. - * - * \retval true Debugger is connected to the system - * \retval false Debugger is not connected to the system - * - */ -static inline bool system_is_debugger_present(void) -{ - return DSU->STATUSB.reg & DSU_STATUSB_DBGPRES; -} - -/** - * @} - */ - -/** - * \name System Identification - * @{ - */ - -/** - * \brief Retrieve the device identification signature. - * - * Retrieves the signature of the current device. - * - * \return Device ID signature as a 32-bit integer. - */ -static inline uint32_t system_get_device_id(void) -{ - return DSU->DID.reg; -} - -/** - * @} - */ - -/** - * \name System Initialization - * @{ - */ - -void system_init(void); - -/** - * @} - */ - - -/** - * @} - */ - -/** - -* \page asfdoc_sam0_drivers_power_exqsg Examples for Power Driver - * - * This is a list of the available Quick Start Guides (QSGs) and example - * applications. QSGs are simple examples with step-by-step instructions to - * configure and use this driver in a selection of - * use cases. Note that a QSG can be compiled as a standalone application or be - * added to the user application. - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - \subpage asfdoc_sam0_power_basic_use_case - * \endif - * - * \page asfdoc_sam0_system_extra Extra Information for SYSTEM Driver - * - * \section asfdoc_sam0_system_extra_acronyms Acronyms - * Below is a table listing the acronyms used in this module, along with their - * intended meanings. - * - * - * - * - * - * - * - * - * - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - * - * - * - * - * - * - * - * \endif - * \if DEVICE_SAMC21_SYSTEM_SUPPORT - * - * - * - * - * - * - * - * - * \endif - * \if DEVICE_SAMD21_SYSTEM_SUPPORT - * - * - * - * - * \endif - *
AcronymDefinition
PMPower Manager
SUPCSupply Controller
RSTCReset Controller
SUPCSupply Controller
RSTCReset Controller
SYSCTRLSystem control interface
- * - * - * \section asfdoc_sam0_system_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - None - * - * - * \section asfdoc_sam0_system_extra_errata Errata - * There are no errata related to this driver. - * - * - * \section asfdoc_sam0_system_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - * - * - * \endif - * \if DEVICE_SAMC21_SYSTEM_SUPPORT - * - * - * - * \endif - * \if DEVICE_SAMD21_SYSTEM_SUPPORT - * - * - * - * - * - * - * - * - * - * \endif - *
Changelog
Initial Release
Initial Release
Added new \c system_reset() to reset the complete MCU with some exceptions
Added new \c system_get_device_id() function to retrieved the device - * ID.
Initial Release
- * - * \page asfdoc_sam0_system_document_revision_history Document Revision History - * - * - * - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - * - * - * - * - * \endif - * \if DEVICE_SAMC21_SYSTEM_SUPPORT - * - * - * - * - * - * \endif - * \if DEVICE_SAMD21_SYSTEM_SUPPORT - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * \endif - *
Doc. Rev. - * Date - * Comments - *
42449A07/2015Initial document release
42484A08/2015Initial document release.
42120E04/2015Added support for SAMDAx
42120D12/2014Added support for SAMR21 and SAMD10/D11
42120C01/2014Added support for SAMD21
42120B06/2013Corrected documentation typos
42120A06/2013Initial document release
- */ - -#ifdef __cplusplus -} -#endif - -#endif /* SYSTEM_H_INCLUDED */ - diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/system_interrupt.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/system_interrupt.h deleted file mode 100644 index 93a542d..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/system_interrupt.h +++ /dev/null @@ -1,429 +0,0 @@ -/** - * \file - * - * \brief SAM System Interrupt Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef SYSTEM_INTERRUPT_H_INCLUDED -#define SYSTEM_INTERRUPT_H_INCLUDED - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \defgroup asfdoc_sam0_system_interrupt_group SAM System Interrupt (SYSTEM INTERRUPT) Driver - * - * This driver for Atmel® | SMART ARM®-based microcontrollers provides - * an interface for the configuration and management of internal software and - * hardware interrupts/exceptions. - * - * The following peripheral is used by this module: - * - NVIC (Nested Vector Interrupt Controller) - * - * The following devices can use this module: - * - Atmel | SMART SAM D20/D21 - * - Atmel | SMART SAM R21 - * - Atmel | SMART SAM D09/D10/D11 - * - Atmel | SMART SAM L21/L22 - * - Atmel | SMART SAM DA1 - * - Atmel | SMART SAM C20/C21 - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_system_interrupt_prerequisites - * - \ref asfdoc_sam0_system_interrupt_module_overview - * - \ref asfdoc_sam0_system_interrupt_special_considerations - * - \ref asfdoc_sam0_system_interrupt_extra_info - * - \ref asfdoc_sam0_system_interrupt_examples - * - \ref asfdoc_sam0_system_interrupt_api_overview - * - * - * \section asfdoc_sam0_system_interrupt_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * - * \section asfdoc_sam0_system_interrupt_module_overview Module Overview - * - * The ARM® Cortex® M0+ core contains an interrupt and exception vector table, which - * can be used to configure the device's interrupt handlers; individual - * interrupts and exceptions can be enabled and disabled, as well as configured - * with a variable priority. - * - * This driver provides a set of wrappers around the core interrupt functions, - * to expose a simple API for the management of global and individual interrupts - * within the device. - * - * \subsection asfdoc_sam0_system_interrupt_module_overview_criticalsec Critical Sections - * In some applications it is important to ensure that no interrupts may be - * executed by the system whilst a critical portion of code is being run; for - * example, a buffer may be copied from one context to another - during which - * interrupts must be disabled to avoid corruption of the source buffer contents - * until the copy has completed. This driver provides a basic API to enter and - * exit nested critical sections, so that global interrupts can be kept disabled - * for as long as necessary to complete a critical application code section. - * - * \subsection asfdoc_sam0_system_interrupt_module_overview_softints Software Interrupts - * For some applications, it may be desirable to raise a module or core - * interrupt via software. For this reason, a set of APIs to set an interrupt or - * exception as pending are provided to the user application. - * - * \section asfdoc_sam0_system_interrupt_special_considerations Special Considerations - * - * Interrupts from peripherals in the SAM devices are on a per-module basis; - * an interrupt raised from any source within a module will cause a single, - * module-common handler to execute. It is the user application or driver's - * responsibility to de-multiplex the module-common interrupt to determine the - * exact interrupt cause. - * - * \section asfdoc_sam0_system_interrupt_extra_info Extra Information - * - * For extra information, see \ref asfdoc_sam0_system_interrupt_extra. This includes: - * - \ref asfdoc_sam0_system_interrupt_extra_acronyms - * - \ref asfdoc_sam0_system_interrupt_extra_dependencies - * - \ref asfdoc_sam0_system_interrupt_extra_errata - * - \ref asfdoc_sam0_system_interrupt_extra_history - * - * - * \section asfdoc_sam0_system_interrupt_examples Examples - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_system_interrupt_exqsg. - * - * \section asfdoc_sam0_system_interrupt_api_overview API Overview - * @{ - */ - -#include "compiler.h" -#include -#include "system_interrupt_features.h" - -/** - * \brief Table of possible system interrupt/exception vector priorities. - * - * Table of all possible interrupt and exception vector priorities within the - * device. - */ -enum system_interrupt_priority_level { - /** Priority level 0, the highest possible interrupt priority */ - SYSTEM_INTERRUPT_PRIORITY_LEVEL_0 = 0, - /** Priority level 1 */ - SYSTEM_INTERRUPT_PRIORITY_LEVEL_1 = 1, - /** Priority level 2 */ - SYSTEM_INTERRUPT_PRIORITY_LEVEL_2 = 2, - /** Priority level 3, the lowest possible interrupt priority */ - SYSTEM_INTERRUPT_PRIORITY_LEVEL_3 = 3, -}; - -/** - * \name Critical Section Management - * @{ - */ - -/** - * \brief Enters a critical section. - * - * Disables global interrupts. To support nested critical sections, an internal - * count of the critical section nesting will be kept, so that global interrupts - * are only re-enabled upon leaving the outermost nested critical section. - * - */ -static inline void system_interrupt_enter_critical_section(void) -{ - cpu_irq_enter_critical(); -} - -/** - * \brief Leaves a critical section. - * - * Enables global interrupts. To support nested critical sections, an internal - * count of the critical section nesting will be kept, so that global interrupts - * are only re-enabled upon leaving the outermost nested critical section. - * - */ -static inline void system_interrupt_leave_critical_section(void) -{ - cpu_irq_leave_critical(); -} - -/** @} */ - -/** - * \name Interrupt Enabling/Disabling - * @{ - */ - -/** - * \brief Check if global interrupts are enabled. - * - * Checks if global interrupts are currently enabled. - * - * \returns A boolean that identifies if the global interrupts are enabled or not. - * - * \retval true Global interrupts are currently enabled - * \retval false Global interrupts are currently disabled - * - */ -static inline bool system_interrupt_is_global_enabled(void) -{ - return cpu_irq_is_enabled(); -} - -/** - * \brief Enables global interrupts. - * - * Enables global interrupts in the device to fire any enabled interrupt handlers. - */ -static inline void system_interrupt_enable_global(void) -{ - cpu_irq_enable(); -} - -/** - * \brief Disables global interrupts. - * - * Disabled global interrupts in the device, preventing any enabled interrupt - * handlers from executing. - */ -static inline void system_interrupt_disable_global(void) -{ - cpu_irq_disable(); -} - -/** - * \brief Checks if an interrupt vector is enabled or not. - * - * Checks if a specific interrupt vector is currently enabled. - * - * \param[in] vector Interrupt vector number to check - * - * \returns A variable identifying if the requested interrupt vector is enabled. - * - * \retval true Specified interrupt vector is currently enabled - * \retval false Specified interrupt vector is currently disabled - * - */ -static inline bool system_interrupt_is_enabled( - const enum system_interrupt_vector vector) -{ - return (bool)((NVIC->ISER[0] >> (uint32_t)vector) & 0x00000001); -} - -/** - * \brief Enable interrupt vector. - * - * Enables execution of the software handler for the requested interrupt vector. - * - * \param[in] vector Interrupt vector to enable - */ -static inline void system_interrupt_enable( - const enum system_interrupt_vector vector) -{ - NVIC->ISER[0] = (uint32_t)(1 << ((uint32_t)vector & 0x0000001f)); -} - -/** - * \brief Disable interrupt vector. - * - * Disables execution of the software handler for the requested interrupt vector. - * - * \param[in] vector Interrupt vector to disable - */ -static inline void system_interrupt_disable( - const enum system_interrupt_vector vector) -{ - NVIC->ICER[0] = (uint32_t)(1 << ((uint32_t)vector & 0x0000001f)); -} - -/** @} */ - -/** - * \name Interrupt State Management - * @{ - */ - -/** - * \brief Get active interrupt (if any). - * - * Return the vector number for the current executing software handler, if any. - * - * \return Interrupt number that is currently executing. - */ -static inline enum system_interrupt_vector system_interrupt_get_active(void) -{ - uint32_t IPSR = __get_IPSR(); - /* The IPSR returns the Exception number, which with an offset 16 to IRQ number. */ - return (enum system_interrupt_vector)((IPSR & _SYSTEM_INTERRUPT_IPSR_MASK) - 16); -} - -bool system_interrupt_is_pending( - const enum system_interrupt_vector vector); - -enum status_code system_interrupt_set_pending( - const enum system_interrupt_vector vector); - -enum status_code system_interrupt_clear_pending( - const enum system_interrupt_vector vector); - -/** @} */ - -/** - * \name Interrupt Priority Management - * @{ - */ - -enum status_code system_interrupt_set_priority( - const enum system_interrupt_vector vector, - const enum system_interrupt_priority_level priority_level); - -enum system_interrupt_priority_level system_interrupt_get_priority( - const enum system_interrupt_vector vector); - -/** @} */ - -/** @} */ - -/** - * \page asfdoc_sam0_system_interrupt_extra Extra Information for SYSTEM INTERRUPT Driver - * - * \section asfdoc_sam0_system_interrupt_extra_acronyms Acronyms - * The table below presents the acronyms used in this module: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
AcronymDescription
ISRInterrupt Service Routine
NMINon-maskable Interrupt
SERCOMSerial Communication Interface
- * - * - * \section asfdoc_sam0_system_interrupt_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - None - * - * - * \section asfdoc_sam0_system_interrupt_extra_errata Errata - * There are no errata related to this driver. - * - * - * \section asfdoc_sam0_system_interrupt_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * - * - * - *
Changelog
Initial Release
- */ - -/** - * \page asfdoc_sam0_system_interrupt_exqsg Examples for SYSTEM INTERRUPT Driver - * - * This is a list of the available Quick Start guides (QSGs) and example - * applications for \ref asfdoc_sam0_system_interrupt_group. QSGs are simple examples with - * step-by-step instructions to configure and use this driver in a selection of - * use cases. Note that a QSG can be compiled as a standalone application or be - * added to the user application. - * - * - \subpage asfdoc_sam0_system_interrupt_critsec_use_case - * - \subpage asfdoc_sam0_system_interrupt_enablemodint_use_case - * - * \page asfdoc_sam0_system_interrupt_document_revision_history Document Revision History - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Doc. Rev. - * Date - * Comments - *
42122E08/2015Added support for SAM L21/L22, SAM DA1, and SAM C20/C21
42122D12/2014Added support for SAM R21 and SAM D10/D11
42122C01/2014Added support for SAM D21
42122B06/2013Corrected documentation typos
42122A06/2013Initial release
- */ - -#ifdef __cplusplus -} -#endif - -#endif // #ifndef SYSTEM_INTERRUPT_H_INCLUDED diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/system_interrupt_features.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/system_interrupt_features.h deleted file mode 100644 index 25dfa83..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/system_interrupt_features.h +++ /dev/null @@ -1,195 +0,0 @@ -/** - * \file - * - * \brief SAM D21 System Interrupt Driver - * - * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#ifndef SYSTEM_INTERRUPT_FEATURES_H_INCLUDED -#define SYSTEM_INTERRUPT_FEATURES_H_INCLUDED - -#if !defined(__DOXYGEN__) - -/* Generates a interrupt vector table enum list entry for a given module type - and index (e.g. "SYSTEM_INTERRUPT_MODULE_TC0 = TC0_IRQn,"). */ -# define _MODULE_IRQn(n, module) \ - SYSTEM_INTERRUPT_MODULE_##module##n = module##n##_IRQn, - -/* Generates interrupt vector table enum list entries for all instances of a - given module type on the selected device. */ -# define _SYSTEM_INTERRUPT_MODULES(name) \ - MREPEAT(name##_INST_NUM, _MODULE_IRQn, name) - -# define _SYSTEM_INTERRUPT_IPSR_MASK 0x0000003f -# define _SYSTEM_INTERRUPT_PRIORITY_MASK 0x00000003 - -# define _SYSTEM_INTERRUPT_EXTERNAL_VECTOR_START 0 - -# define _SYSTEM_INTERRUPT_SYSTICK_PRI_POS 30 -#endif - -/** - * \addtogroup asfdoc_sam0_system_interrupt_group - * @{ - */ - -/** - * \brief Table of possible system interrupt/exception vector numbers. - * - * Table of all possible interrupt and exception vector indexes within the - * SAM D21 device. Check peripherals configuration in SAM D21 datasheet for - * available vector index for specific device. - * - */ -#if defined(__DOXYGEN__) -/** \note The actual enumeration name is "system_interrupt_vector". */ -enum system_interrupt_vector_samd21 { -#else -enum system_interrupt_vector { -#endif - /** Interrupt vector index for a NMI interrupt */ - SYSTEM_INTERRUPT_NON_MASKABLE = NonMaskableInt_IRQn, - /** Interrupt vector index for a Hard Fault memory access exception */ - SYSTEM_INTERRUPT_HARD_FAULT = HardFault_IRQn, - /** Interrupt vector index for a Supervisor Call exception */ - SYSTEM_INTERRUPT_SV_CALL = SVCall_IRQn, - /** Interrupt vector index for a Pending Supervisor interrupt */ - SYSTEM_INTERRUPT_PENDING_SV = PendSV_IRQn, - /** Interrupt vector index for a System Tick interrupt */ - SYSTEM_INTERRUPT_SYSTICK = SysTick_IRQn, - - /** Interrupt vector index for a Power Manager peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_PM = PM_IRQn, - /** Interrupt vector index for a System Control peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_SYSCTRL = SYSCTRL_IRQn, - /** Interrupt vector index for a Watch Dog peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_WDT = WDT_IRQn, - /** Interrupt vector index for a Real Time Clock peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_RTC = RTC_IRQn, - /** Interrupt vector index for an External Interrupt peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_EIC = EIC_IRQn, - /** Interrupt vector index for a Non Volatile Memory Controller interrupt */ - SYSTEM_INTERRUPT_MODULE_NVMCTRL = NVMCTRL_IRQn, - /** Interrupt vector index for a Direct Memory Access interrupt */ - SYSTEM_INTERRUPT_MODULE_DMA = DMAC_IRQn, -#if defined(__DOXYGEN__) || defined(ID_USB) - /** Interrupt vector index for a Universal Serial Bus interrupt */ - SYSTEM_INTERRUPT_MODULE_USB = USB_IRQn, -#endif - /** Interrupt vector index for an Event System interrupt */ - SYSTEM_INTERRUPT_MODULE_EVSYS = EVSYS_IRQn, -#if defined(__DOXYGEN__) - /** Interrupt vector index for a SERCOM peripheral interrupt. - * - * Each specific device may contain several SERCOM peripherals; each module - * instance will have its own entry in the table, with the instance number - * substituted for "n" in the entry name (e.g. - * \c SYSTEM_INTERRUPT_MODULE_SERCOM0). - */ - SYSTEM_INTERRUPT_MODULE_SERCOMn = SERCOMn_IRQn, - - /** Interrupt vector index for a Timer/Counter Control peripheral interrupt. - * - * Each specific device may contain several TCC peripherals; each module - * instance will have its own entry in the table, with the instance number - * substituted for "n" in the entry name (e.g. - * \c SYSTEM_INTERRUPT_MODULE_TCC0). - */ - SYSTEM_INTERRUPT_MODULE_TCCn = TCCn_IRQn, - - /** Interrupt vector index for a Timer/Counter peripheral interrupt. - * - * Each specific device may contain several TC peripherals; each module - * instance will have its own entry in the table, with the instance number - * substituted for "n" in the entry name (e.g. - * \c SYSTEM_INTERRUPT_MODULE_TC3). - */ - SYSTEM_INTERRUPT_MODULE_TCn = TCn_IRQn, -#else - _SYSTEM_INTERRUPT_MODULES(SERCOM) - - _SYSTEM_INTERRUPT_MODULES(TCC) - - SYSTEM_INTERRUPT_MODULE_TC3 = TC3_IRQn, - SYSTEM_INTERRUPT_MODULE_TC4 = TC4_IRQn, - SYSTEM_INTERRUPT_MODULE_TC5 = TC5_IRQn, -# if defined(ID_TC6) - SYSTEM_INTERRUPT_MODULE_TC6 = TC6_IRQn, -# endif -# if defined(ID_TC7) - SYSTEM_INTERRUPT_MODULE_TC7 = TC7_IRQn, -# endif -#endif - -#if defined(__DOXYGEN__) || defined(ID_ADC) - /** Interrupt vector index for an Analog-to-Digital peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_ADC = ADC_IRQn, -#endif - -#if defined(__DOXYGEN__) || defined(ID_AC) - /** Interrupt vector index for an Analog Comparator peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_AC = AC_IRQn, -#endif - -#if defined(__DOXYGEN__) || defined(ID_DAC) - /** Interrupt vector index for a Digital-to-Analog peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_DAC = DAC_IRQn, -#endif -#if defined(__DOXYGEN__) || defined(ID_PTC) - /** Interrupt vector index for a Peripheral Touch Controller peripheral - * interrupt */ - SYSTEM_INTERRUPT_MODULE_PTC = PTC_IRQn, -#endif -#if defined(__DOXYGEN__) || defined(ID_I2S) - /** Interrupt vector index for a Inter-IC Sound Interface peripheral - * interrupt */ - SYSTEM_INTERRUPT_MODULE_I2S = I2S_IRQn, -#endif -#if defined(__DOXYGEN__) || defined(ID_AC1) - /** Interrupt vector index for an Analog Comparator 1 peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_AC1 = AC1_IRQn, -#endif -}; - -/** @} */ - -#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc.c b/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc.c deleted file mode 100644 index 23e2703..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc.c +++ /dev/null @@ -1,685 +0,0 @@ -/** - * \file - * - * \brief SAM TC - Timer Counter Driver - * - * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#include "tc.h" - -#if TC_ASYNC == true -# include "tc_interrupt.h" -# include - -/** \internal - * Converts a given TC index to its interrupt vector index. - */ -# define _TC_INTERRUPT_VECT_NUM(n, unused) \ - SYSTEM_INTERRUPT_MODULE_TC##n, -#endif - -#if !defined(__DOXYGEN__) -# define _TC_GCLK_ID(n,unused) TPASTE3(TC,n,_GCLK_ID) , -# define _TC_PM_APBCMASK(n,unused) TPASTE2(PM_APBCMASK_TC,n) , - -# define TC_INST_GCLK_ID { MRECURSION(TC_INST_NUM, _TC_GCLK_ID, TC_INST_MAX_ID) } -# define TC_INST_PM_APBCMASK { MRECURSION(TC_INST_NUM, _TC_PM_APBCMASK, TC_INST_MAX_ID) } - -#endif - -/** - * \internal Find the index of given TC module instance. - * - * \param[in] TC module instance pointer. - * - * \return Index of the given TC module instance. - */ -uint8_t _tc_get_inst_index( - Tc *const hw) -{ - /* List of available TC modules. */ - Tc *const tc_modules[TC_INST_NUM] = TC_INSTS; - - /* Find index for TC instance. */ - for (uint32_t i = 0; i < TC_INST_NUM; i++) { - if (hw == tc_modules[i]) { - return i; - } - } - - /* Invalid data given. */ - Assert(false); - return 0; -} - - -/** - * \brief Initializes a hardware TC module instance. - * - * Enables the clock and initializes the TC module, based on the given - * configuration values. - * - * \param[in,out] module_inst Pointer to the software module instance struct - * \param[in] hw Pointer to the TC hardware module - * \param[in] config Pointer to the TC configuration options struct - * - * \return Status of the initialization procedure. - * - * \retval STATUS_OK The module was initialized successfully - * \retval STATUS_BUSY Hardware module was busy when the - * initialization procedure was attempted - * \retval STATUS_INVALID_ARG An invalid configuration option or argument - * was supplied - * \retval STATUS_ERR_DENIED Hardware module was already enabled, or the - * hardware module is configured in 32-bit - * slave mode - */ -enum status_code tc_init( - struct tc_module *const module_inst, - Tc *const hw, - const struct tc_config *const config) -{ - /* Sanity check arguments */ - Assert(hw); - Assert(module_inst); - Assert(config); - - /* Temporary variable to hold all updates to the CTRLA - * register before they are written to it */ - uint16_t ctrla_tmp = 0; - /* Temporary variable to hold all updates to the CTRLBSET - * register before they are written to it */ - uint8_t ctrlbset_tmp = 0; - /* Temporary variable to hold all updates to the CTRLC - * register before they are written to it */ - uint8_t ctrlc_tmp = 0; - /* Temporary variable to hold TC instance number */ - uint8_t instance = _tc_get_inst_index(hw); - - /* Array of GLCK ID for different TC instances */ - uint8_t inst_gclk_id[] = TC_INST_GCLK_ID; - /* Array of PM APBC mask bit position for different TC instances */ - uint16_t inst_pm_apbmask[] = TC_INST_PM_APBCMASK; - - struct system_pinmux_config pin_config; - struct system_gclk_chan_config gclk_chan_config; - -#if TC_ASYNC == true - /* Initialize parameters */ - for (uint8_t i = 0; i < TC_CALLBACK_N; i++) { - module_inst->callback[i] = NULL; - } - module_inst->register_callback_mask = 0x00; - module_inst->enable_callback_mask = 0x00; - - /* Register this instance for callbacks*/ - _tc_instances[instance] = module_inst; -#endif - - /* Associate the given device instance with the hardware module */ - module_inst->hw = hw; - -#if SAMD09 || SAMD10 || SAMD11 - /* Check if even numbered TC modules are being configured in 32-bit - * counter size. Only odd numbered counters are allowed to be - * configured in 32-bit counter size. - */ - if ((config->counter_size == TC_COUNTER_SIZE_32BIT) && - !((instance + TC_INSTANCE_OFFSET) & 0x01)) { - Assert(false); - return STATUS_ERR_INVALID_ARG; - } -#else - /* Check if odd numbered TC modules are being configured in 32-bit - * counter size. Only even numbered counters are allowed to be - * configured in 32-bit counter size. - */ - if ((config->counter_size == TC_COUNTER_SIZE_32BIT) && - ((instance + TC_INSTANCE_OFFSET) & 0x01)) { - Assert(false); - return STATUS_ERR_INVALID_ARG; - } -#endif - - /* Make the counter size variable in the module_inst struct reflect - * the counter size in the module - */ - module_inst->counter_size = config->counter_size; - - if (hw->COUNT8.CTRLA.reg & TC_CTRLA_SWRST) { - /* We are in the middle of a reset. Abort. */ - return STATUS_BUSY; - } - - if (hw->COUNT8.STATUS.reg & TC_STATUS_SLAVE) { - /* Module is used as a slave */ - return STATUS_ERR_DENIED; - } - - if (hw->COUNT8.CTRLA.reg & TC_CTRLA_ENABLE) { - /* Module must be disabled before initialization. Abort. */ - return STATUS_ERR_DENIED; - } - - /* Set up the TC PWM out pin for channel 0 */ - if (config->pwm_channel[0].enabled) { - system_pinmux_get_config_defaults(&pin_config); - pin_config.mux_position = config->pwm_channel[0].pin_mux; - pin_config.direction = SYSTEM_PINMUX_PIN_DIR_OUTPUT; - system_pinmux_pin_set_config( - config->pwm_channel[0].pin_out, &pin_config); - } - - /* Set up the TC PWM out pin for channel 1 */ - if (config->pwm_channel[1].enabled) { - system_pinmux_get_config_defaults(&pin_config); - pin_config.mux_position = config->pwm_channel[1].pin_mux; - pin_config.direction = SYSTEM_PINMUX_PIN_DIR_OUTPUT; - system_pinmux_pin_set_config( - config->pwm_channel[1].pin_out, &pin_config); - } - - /* Enable the user interface clock in the PM */ - system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, - inst_pm_apbmask[instance]); - - /* Enable the slave counter if counter_size is 32-bit */ - if ((config->counter_size == TC_COUNTER_SIZE_32BIT)) - { - /* Enable the user interface clock in the PM */ - system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, - inst_pm_apbmask[instance + 1]); - } - - /* Setup clock for module */ - system_gclk_chan_get_config_defaults(&gclk_chan_config); - gclk_chan_config.source_generator = config->clock_source; - system_gclk_chan_set_config(inst_gclk_id[instance], &gclk_chan_config); - system_gclk_chan_enable(inst_gclk_id[instance]); - - /* Set ctrla register */ - ctrla_tmp = - (uint32_t)config->counter_size | - (uint32_t)config->wave_generation | - (uint32_t)config->reload_action | - (uint32_t)config->clock_prescaler; - - if (config->run_in_standby) { - ctrla_tmp |= TC_CTRLA_RUNSTDBY; - } - - /* Write configuration to register */ - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - hw->COUNT8.CTRLA.reg = ctrla_tmp; - - /* Set ctrlb register */ - if (config->oneshot) { - ctrlbset_tmp = TC_CTRLBSET_ONESHOT; - } - - if (config->count_direction) { - ctrlbset_tmp |= TC_CTRLBSET_DIR; - } - - /* Clear old ctrlb configuration */ - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - hw->COUNT8.CTRLBCLR.reg = 0xFF; - - /* Check if we actually need to go into a wait state. */ - if (ctrlbset_tmp) { - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - /* Write configuration to register */ - hw->COUNT8.CTRLBSET.reg = ctrlbset_tmp; - } - - /* Set ctrlc register*/ - ctrlc_tmp = config->waveform_invert_output; - for (uint8_t i = 0; i < NUMBER_OF_COMPARE_CAPTURE_CHANNELS; i++) { - if (config->enable_capture_on_channel[i] == true) { - ctrlc_tmp |= (TC_CTRLC_CPTEN(1) << i); - } - } - - /* Write configuration to register */ - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - hw->COUNT8.CTRLC.reg = ctrlc_tmp; - - /* Write configuration to register */ - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Switch for TC counter size */ - switch (module_inst->counter_size) { - case TC_COUNTER_SIZE_8BIT: - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT8.COUNT.reg = - config->counter_8_bit.value; - - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT8.PER.reg = - config->counter_8_bit.period; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT8.CC[0].reg = - config->counter_8_bit.compare_capture_channel[0]; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT8.CC[1].reg = - config->counter_8_bit.compare_capture_channel[1]; - - return STATUS_OK; - - case TC_COUNTER_SIZE_16BIT: - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT16.COUNT.reg - = config->counter_16_bit.value; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT16.CC[0].reg = - config->counter_16_bit.compare_capture_channel[0]; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT16.CC[1].reg = - config->counter_16_bit.compare_capture_channel[1]; - - return STATUS_OK; - - case TC_COUNTER_SIZE_32BIT: - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT32.COUNT.reg - = config->counter_32_bit.value; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT32.CC[0].reg = - config->counter_32_bit.compare_capture_channel[0]; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT32.CC[1].reg = - config->counter_32_bit.compare_capture_channel[1]; - - return STATUS_OK; - } - - Assert(false); - return STATUS_ERR_INVALID_ARG; -} - -/** - * \brief Sets TC module count value. - * - * Sets the current timer count value of a initialized TC module. The - * specified TC module may be started or stopped. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] count New timer count value to set - * - * \return Status of the count update procedure. - * - * \retval STATUS_OK The timer count was updated successfully - * \retval STATUS_ERR_INVALID_ARG An invalid timer counter size was specified - */ -enum status_code tc_set_count_value( - const struct tc_module *const module_inst, - const uint32_t count) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance*/ - Tc *const tc_module = module_inst->hw; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Write to based on the TC counter_size */ - switch (module_inst->counter_size) { - case TC_COUNTER_SIZE_8BIT: - tc_module->COUNT8.COUNT.reg = (uint8_t)count; - return STATUS_OK; - - case TC_COUNTER_SIZE_16BIT: - tc_module->COUNT16.COUNT.reg = (uint16_t)count; - return STATUS_OK; - - case TC_COUNTER_SIZE_32BIT: - tc_module->COUNT32.COUNT.reg = (uint32_t)count; - return STATUS_OK; - - default: - return STATUS_ERR_INVALID_ARG; - } -} - -/** - * \brief Get TC module count value. - * - * Retrieves the current count value of a TC module. The specified TC module - * may be started or stopped. - * - * \param[in] module_inst Pointer to the software module instance struct - * - * \return Count value of the specified TC module. - */ -uint32_t tc_get_count_value( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - Tc *const tc_module = module_inst->hw; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Read from based on the TC counter size */ - switch (module_inst->counter_size) { - case TC_COUNTER_SIZE_8BIT: - return (uint32_t)tc_module->COUNT8.COUNT.reg; - - case TC_COUNTER_SIZE_16BIT: - return (uint32_t)tc_module->COUNT16.COUNT.reg; - - case TC_COUNTER_SIZE_32BIT: - return tc_module->COUNT32.COUNT.reg; - } - - Assert(false); - return 0; -} - -/** - * \brief Gets the TC module capture value. - * - * Retrieves the capture value in the indicated TC module capture channel. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] channel_index Index of the Compare Capture channel to read - * - * \return Capture value stored in the specified timer channel. - */ -uint32_t tc_get_capture_value( - const struct tc_module *const module_inst, - const enum tc_compare_capture_channel channel_index) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - Tc *const tc_module = module_inst->hw; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Read out based on the TC counter size */ - switch (module_inst->counter_size) { - case TC_COUNTER_SIZE_8BIT: - if (channel_index < - NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { - return tc_module->COUNT8.CC[channel_index].reg; - } - - case TC_COUNTER_SIZE_16BIT: - if (channel_index < - NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { - return tc_module->COUNT16.CC[channel_index].reg; - } - - case TC_COUNTER_SIZE_32BIT: - if (channel_index < - NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { - return tc_module->COUNT32.CC[channel_index].reg; - } - } - - Assert(false); - return 0; -} - -/** - * \brief Sets a TC module compare value. - * - * Writes a compare value to the given TC module compare/capture channel. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] channel_index Index of the compare channel to write to - * \param[in] compare New compare value to set - * - * \return Status of the compare update procedure. - * - * \retval STATUS_OK The compare value was updated successfully - * \retval STATUS_ERR_INVALID_ARG An invalid channel index was supplied - */ -enum status_code tc_set_compare_value( - const struct tc_module *const module_inst, - const enum tc_compare_capture_channel channel_index, - const uint32_t compare) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - Tc *const tc_module = module_inst->hw; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Read out based on the TC counter size */ - switch (module_inst->counter_size) { - case TC_COUNTER_SIZE_8BIT: - if (channel_index < - NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { - tc_module->COUNT8.CC[channel_index].reg = - (uint8_t)compare; - return STATUS_OK; - } - - case TC_COUNTER_SIZE_16BIT: - if (channel_index < - NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { - tc_module->COUNT16.CC[channel_index].reg = - (uint16_t)compare; - return STATUS_OK; - } - - case TC_COUNTER_SIZE_32BIT: - if (channel_index < - NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { - tc_module->COUNT32.CC[channel_index].reg = - (uint32_t)compare; - return STATUS_OK; - } - } - - return STATUS_ERR_INVALID_ARG; -} - -/** - * \brief Resets the TC module. - * - * Resets the TC module, restoring all hardware module registers to their - * default values and disabling the module. The TC module will not be - * accessible while the reset is being performed. - * - * \note When resetting a 32-bit counter only the master TC module's instance - * structure should be passed to the function. - * - * \param[in] module_inst Pointer to the software module instance struct - * - * \return Status of the procedure. - * \retval STATUS_OK The module was reset successfully - * \retval STATUS_ERR_UNSUPPORTED_DEV A 32-bit slave TC module was passed to - * the function. Only use reset on master - * TC - */ -enum status_code tc_reset( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - if (tc_module->STATUS.reg & TC_STATUS_SLAVE) { - return STATUS_ERR_UNSUPPORTED_DEV; - } - - /* Disable this module if it is running */ - if (tc_module->CTRLA.reg & TC_CTRLA_ENABLE) { - tc_disable(module_inst); - while (tc_is_syncing(module_inst)) { - /* wait while module is disabling */ - } - } - - /* Reset this TC module */ - tc_module->CTRLA.reg |= TC_CTRLA_SWRST; - - return STATUS_OK; -} - -/** - * \brief Set the timer TOP/period value. - * - * For 8-bit counter size this function writes the top value to the period - * register. - * - * For 16- and 32-bit counter size this function writes the top value to - * Capture Compare register 0. The value in this register can not be used for - * any other purpose. - * - * \note This function is designed to be used in PWM or frequency - * match modes only. When the counter is set to 16- or 32-bit counter - * size. In 8-bit counter size it will always be possible to change the - * top value even in normal mode. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] top_value New timer TOP value to set - * - * \return Status of the TOP set procedure. - * - * \retval STATUS_OK The timer TOP value was updated successfully - * \retval STATUS_ERR_INVALID_ARG The configured TC module counter size in the - * module instance is invalid - */ -enum status_code tc_set_top_value ( - const struct tc_module *const module_inst, - const uint32_t top_value) -{ - Assert(module_inst); - Assert(module_inst->hw); - Assert(top_value); - - Tc *const tc_module = module_inst->hw; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - switch (module_inst->counter_size) { - case TC_COUNTER_SIZE_8BIT: - tc_module->COUNT8.PER.reg = (uint8_t)top_value; - return STATUS_OK; - - case TC_COUNTER_SIZE_16BIT: - tc_module->COUNT16.CC[0].reg = (uint16_t)top_value; - return STATUS_OK; - - case TC_COUNTER_SIZE_32BIT: - tc_module->COUNT32.CC[0].reg = (uint32_t)top_value; - return STATUS_OK; - - default: - Assert(false); - return STATUS_ERR_INVALID_ARG; - } -} diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc.h deleted file mode 100644 index 0ee7006..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc.h +++ /dev/null @@ -1,1783 +0,0 @@ -/** - * \file - * - * \brief SAM TC - Timer Counter Driver - * - * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#ifndef TC_H_INCLUDED -#define TC_H_INCLUDED - -/** - * \defgroup asfdoc_sam0_tc_group SAM Timer/Counter Driver (TC) - * - * This driver for Atmel® | SMART ARM®-based microcontrollers provides an interface for the configuration - * and management of the timer modules within the device, for waveform - * generation and timing operations. The following driver API modes are covered - * by this manual: - * - * - Polled APIs - * \if TC_CALLBACK_MODE - * - Callback APIs - * \endif - * - * - * The following peripherals are used by this module: - * - TC (Timer/Counter) - * - * The following devices can use this module: - * - Atmel | SMART SAM D20/D21 - * - Atmel | SMART SAM R21 - * - Atmel | SMART SAM D09/D10/D11 - * - Atmel | SMART SAM L21/L22 - * - Atmel | SMART SAM DA1 - * - Atmel | SMART SAM C20/C21 - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_tc_prerequisites - * - \ref asfdoc_sam0_tc_module_overview - * - \ref asfdoc_sam0_tc_special_considerations - * - \ref asfdoc_sam0_tc_extra_info - * - \ref asfdoc_sam0_tc_examples - * - \ref asfdoc_sam0_tc_api_overview - * - * - * \section asfdoc_sam0_tc_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * - * \section asfdoc_sam0_tc_module_overview Module Overview - * - * The Timer/Counter (TC) module provides a set of timing and counting related - * functionality, such as the generation of periodic waveforms, the capturing - * of a periodic waveform's frequency/duty cycle, and software timekeeping for - * periodic operations. TC modules can be configured to use an 8-, 16-, or - * 32-bit counter size. - * - * This TC module for the SAM is capable of the following functions: - * - * - Generation of PWM signals - * - Generation of timestamps for events - * - General time counting - * - Waveform period capture - * - Waveform frequency capture - * - * \ref asfdoc_sam0_tc_block_diagram "The diagram below" shows the overview - * of the TC module design. - * - * \anchor asfdoc_sam0_tc_block_diagram - * \image html overview.svg "Basic Overview of the TC Module" - * - * - * \subsection asfdoc_sam0_tc_features Driver Feature Macro Definition - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Driver Feature MacroSupported devices
FEATURE_TC_DOUBLE_BUFFEREDSAM L21/L22/C20/C21
FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2SAM L21/L22/C20/C21
FEATURE_TC_STAMP_PW_CAPTURESAM L21/L22/C20/C21
FEATURE_TC_READ_SYNCSAM L21/L22/C20/C21
FEATURE_TC_IO_CAPTURESAM L21/L22/C20/C21
FEATURE_TC_GENERATE_DMA_TRIGGERSAM L21/L22
- * \note The specific features are only available in the driver when the - * selected device supports those features. - * - * \subsection asfdoc_sam0_tc_module_overview_func_desc Functional Description - * Independent of the configured counter size, each TC module can be set up - * in one of two different modes; capture and compare. - * - * In capture mode, the counter value is stored when a configurable event - * occurs. This mode can be used to generate timestamps used in event capture, - * or it can be used for the measurement of a periodic input signal's - * frequency/duty cycle. - * - * In compare mode, the counter value is compared against one or more of the - * configured channel compare values. When the counter value coincides with a - * compare value an action can be taken automatically by the module, such as - * generating an output event or toggling a pin when used for frequency or PWM - * signal generation. - * - * \note The connection of events between modules requires the use of the - * \ref asfdoc_sam0_events_group "SAM Event System Driver (EVENTS)" - * to route output event of one module to the input event of another. - * For more information on event routing, refer to the event driver - * documentation. - * - * \subsection asfdoc_sam0_tc_module_overview_tc_size Timer/Counter Size - * Each timer module can be configured in one of three different counter - * sizes; 8-, 16-, and 32-bit. The size of the counter determines the maximum - * value it can count to before an overflow occurs and the count is reset back - * to zero. \ref asfdoc_sam0_tc_count_size_vs_top "The table below" shows the - * maximum values for each of the possible counter sizes. - * - * \anchor asfdoc_sam0_tc_count_size_vs_top - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Timer Counter Sizes and Their Maximum Count Values
Counter sizeMax. (hexadecimal)Max. (decimal)
8-bit0xFF255
16-bit0xFFFF65,535
32-bit0xFFFFFFFF4,294,967,295
- * - * When using the counter in 16- or 32-bit count mode, Compare Capture - * register 0 (CC0) is used to store the period value when running in PWM - * generation match mode. - * - * When using 32-bit counter size, two 16-bit counters are chained together - * in a cascade formation. Except in SAM D09/D10/D11, Even numbered TC modules - * (e.g. TC0, TC2) can be configured as 32-bit counters. The odd numbered - * counters will act as slaves to the even numbered masters, and will not - * be reconfigurable until the master timer is disabled. The pairing of timer - * modules for 32-bit mode is shown in \ref asfdoc_sam0_tc_module_ms_pairs - * "the table below". - * - * \anchor asfdoc_sam0_tc_module_ms_pairs - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
TC Master and Slave Module Pairings
Master TC ModuleSlave TC Module
TC0TC1
TC2TC3
......
TCn-1TCn
- * - * In SAM D09/D10/D11, odd numbered TC modules (e.g. TC1) can be configured as 32-bit - * counters. The even numbered(e.g. TC2) counters will act as slaves to the odd - * numbered masters. - * - * \subsection asfdoc_sam0_tc_module_overview_clock Clock Settings - * - * \subsubsection asfdoc_sam0_tc_module_overview_clock_selection Clock Selection - * Each TC peripheral is clocked asynchronously to the system clock by a GCLK - * (Generic Clock) channel. The GCLK channel connects to any of the GCLK - * generators. The GCLK generators are configured to use one of the available - * clock sources on the system such as internal oscillator, external crystals, - * etc. see the \ref asfdoc_sam0_system_clock_group "Generic Clock driver" - *for - * more information. - * - * \subsubsection asfdoc_sam0_tc_module_overview_clock_prescaler Prescaler - * Each TC module in the SAM has its own individual clock prescaler, which - * can be used to divide the input clock frequency used in the counter. This - * prescaler only scales the clock used to provide clock pulses for the counter - * to count, and does not affect the digital register interface portion of - * the module, thus the timer registers will synchronize to the raw GCLK - * frequency input to the module. - * - * As a result of this, when selecting a GCLK frequency and timer prescaler - * value the user application should consider both the timer resolution - * required and the synchronization frequency, to avoid lengthy - * synchronization times of the module if a very slow GCLK frequency is fed - * into the TC module. It is preferable to use a higher module GCLK frequency - * as the input to the timer, and prescale this down as much as possible to - * obtain a suitable counter frequency in latency-sensitive applications. - * - * \subsubsection asfdoc_sam0_tc_module_overview_clock_reloading Reloading - * Timer modules also contain a configurable reload action, used when a - * re-trigger event occurs. Examples of a re-trigger event are the counter - * reaching the maximum value when counting up, or when an event from the event - * system tells the counter to re-trigger. The reload action determines if the - * prescaler should be reset, and when this should happen. The counter will - * always be reloaded with the value it is set to start counting from. The user - * can choose between three different reload actions, described in - * \ref asfdoc_sam0_tc_module_reload_act "the table below". - * - * \anchor asfdoc_sam0_tc_module_reload_act - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
TC Module Reload Actions
Reload actionDescription
\ref TC_RELOAD_ACTION_GCLK Reload TC counter value on next GCLK cycle. Leave prescaler - * as-is.
\ref TC_RELOAD_ACTION_PRESC Reloads TC counter value on next prescaler clock. Leave prescaler - * as-is.
\ref TC_RELOAD_ACTION_RESYNC Reload TC counter value on next GCLK cycle. Clear prescaler to - * zero.
- * - * The reload action to use will depend on the specific application being - * implemented. One example is when an external trigger for a reload occurs; if - * the TC uses the prescaler, the counter in the prescaler should not have a - * value between zero and the division factor. The TC counter and the counter - * in the prescaler should both start at zero. When the counter is set to - * re-trigger when it reaches the maximum value on the other hand, this is not the - * right option to use. In such a case it would be better if the prescaler is - * left unaltered when the re-trigger happens, letting the counter reset on the - * next GCLK cycle. - * - * \subsection asfdoc_sam0_tc_module_overview_compare_match Compare Match Operations - * In compare match operation, Compare/Capture registers are used in comparison - * with the counter value. When the timer's count value matches the value of a - * compare channel, a user defined action can be taken. - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_timer Basic Timer - * - * A Basic Timer is a simple application where compare match operations is used - * to determine when a specific period has elapsed. In Basic Timer operations, - * one or more values in the module's Compare/Capture registers are used to - * specify the time (as a number of prescaled GCLK cycles) when an action should - * be taken by the microcontroller. This can be an Interrupt Service Routine - * (ISR), event generator via the event system, or a software flag that is - * polled via the user application. - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_wg Waveform Generation - * - * Waveform generation enables the TC module to generate square waves, or if - * combined with an external passive low-pass filter; analog waveforms. - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_wg_pwm Waveform Generation - PWM - * - * Pulse width modulation is a form of waveform generation and a signalling - * technique that can be useful in many situations. When PWM mode is used, - * a digital pulse train with a configurable frequency and duty cycle can be - * generated by the TC module and output to a GPIO pin of the device. - * - * Often PWM is used to communicate a control or information parameter to an - * external circuit or component. Differing impedances of the source generator - * and sink receiver circuits is less of an issue when using PWM compared to - * using an analog voltage value, as noise will not generally affect the - * signal's integrity to a meaningful extent. - * - * \ref asfdoc_sam0_tc_module_pwm_normal_diag "The figure below" illustrates - * operations and different states of the counter and its output when running - * the counter in PWM normal mode. As can be seen, the TOP value is unchanged - * and is set to MAX. The compare match value is changed at several points to - * illustrate the resulting waveform output changes. The PWM output is set to - * normal (i.e. non-inverted) output mode. - * - * \anchor asfdoc_sam0_tc_module_pwm_normal_diag - * \image html pwm_normal_ex.svg "Example of PWM in Normal Mode, and Different Counter Operations" - * - * - * In \ref asfdoc_sam0_tc_module_pwm_match_diag "the figure below", the - * counter is set to generate PWM in Match mode. The PWM output is inverted via - * the appropriate configuration option in the TC driver configuration - * structure. In this example, the counter value is changed once, but the - * compare match value is kept unchanged. As can be seen, it is possible to - * change the TOP value when running in PWM match mode. - * - * \anchor asfdoc_sam0_tc_module_pwm_match_diag - * \image html pwm_match_ex.svg "Example of PWM in Match Mode, and Different Counter Operations" - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_wg_freq Waveform Generation - Frequency - * - * Frequency Generation mode is in many ways identical to PWM - * generation. However, in Frequency Generation a toggle only occurs - * on the output when a match on a capture channels occurs. When the - * match is made, the timer value is reset, resulting in a variable - * frequency square wave with a fixed 50% duty cycle. - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_capt Capture Operations - * - * In capture operations, any event from the event system or a pin change can - * trigger a capture of the counter value. This captured counter value can be - * used as a timestamp for the event, or it can be used in frequency and pulse - * width capture. - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_capt_event_capture Capture Operations - Event - * - * Event capture is a simple use of the capture functionality, - * designed to create timestamps for specific events. When the TC - * module's input capture pin is externally toggled, the current timer - * count value is copied into a buffered register which can then be - * read out by the user application. - * - * Note that when performing any capture operation, there is a risk that the - * counter reaches its top value (MAX) when counting up, or the bottom value - * (zero) when counting down, before the capture event occurs. This can distort - * the result, making event timestamps to appear shorter than reality; the - * user application should check for timer overflow when reading a capture - * result in order to detect this situation and perform an appropriate - * adjustment. - * - * Before checking for a new capture, \ref TC_STATUS_COUNT_OVERFLOW - * should be checked. The response to an overflow error is left to the user - * application, however it may be necessary to clear both the capture overflow - * flag and the capture flag upon each capture reading. - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_capt_pwc Capture Operations - Pulse Width - * - * Pulse Width Capture mode makes it possible to measure the pulse width and - * period of PWM signals. This mode uses two capture channels of the counter. - * This means that the counter module used for Pulse Width Capture can not be - * used for any other purpose. There are two modes for pulse width capture; - * Pulse Width Period (PWP) and Period Pulse Width (PPW). In PWP mode, capture - * channel 0 is used for storing the pulse width and capture channel 1 stores - * the observed period. While in PPW mode, the roles of the two capture channels - * is reversed. - * - * As in the above example it is necessary to poll on interrupt flags to see - * if a new capture has happened and check that a capture overflow error has - * not occurred. - * - * \subsection asfdoc_sam0_tc_module_overview_oneshot One-shot Mode - * - * TC modules can be configured into a one-shot mode. When configured in this - * manner, starting the timer will cause it to count until the next overflow - * or underflow condition before automatically halting, waiting to be manually - * triggered by the user application software or an event signal from the event - * system. - * - * \subsubsection asfdoc_sam0_tc_module_overview_inversion Wave Generation Output Inversion - * - * The output of the wave generation can be inverted by hardware if desired, - * resulting in the logically inverted value being output to the configured - * device GPIO pin. - * - * - * \section asfdoc_sam0_tc_special_considerations Special Considerations - * - * The number of capture compare registers in each TC module is dependent on - * the specific SAM device being used, and in some cases the counter size. - * - * The maximum amount of capture compare registers available in any SAM - * device is two when running in 32-bit mode and four in 8- and 16-bit modes. - * - * - * \section asfdoc_sam0_tc_extra_info Extra Information - * - * For extra information, see \ref asfdoc_sam0_tc_extra. This includes: - * - \ref asfdoc_sam0_tc_extra_acronyms - * - \ref asfdoc_sam0_tc_extra_dependencies - * - \ref asfdoc_sam0_tc_extra_errata - * - \ref asfdoc_sam0_tc_extra_history - * - * - * \section asfdoc_sam0_tc_examples Examples - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_tc_exqsg. - * - * \section asfdoc_sam0_tc_api_overview API Overview - * @{ - */ - -#include "compiler.h" -#include "clock.h" -#include "gclk.h" -#include "pinmux.h" - -// fix for Arduino zero -#if defined(__SAMD21G18A__) - #define SAMD21 1 - #define SAMD21G 1 - #define TC_ASYNC 1 -#endif - -// fix for Trinket/Gemma M0 -#if defined(__SAMD21E18A__) - #define SAMD21 1 - #define SAMD21E 1 - #define TC_ASYNC 1 -#endif - -/** - * Define port features set according to different device family - * @{ -*/ -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) || defined(__DOXYGEN__) -/** TC double buffered. */ -# define FEATURE_TC_DOUBLE_BUFFERED -/** SYNCBUSY scheme version 2. */ -# define FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2 -/** TC time stamp capture and pulse width capture. */ -# define FEATURE_TC_STAMP_PW_CAPTURE -/** Read synchronization of COUNT. */ -# define FEATURE_TC_READ_SYNC -/** IO pin edge capture. */ -# define FEATURE_TC_IO_CAPTURE -#endif - -#if (SAML21XXXB) || defined(__DOXYGEN__) -/** Generate DMA triggers*/ -# define FEATURE_TC_GENERATE_DMA_TRIGGER -#endif -/*@}*/ - -#if !defined(__DOXYGEN__) -#if SAMD20 || SAML21 || SAML22 || SAMC20 || SAMC21 -# define TC_INSTANCE_OFFSET 0 -#endif -#if SAMD21 || SAMR21 || SAMDA1 -# define TC_INSTANCE_OFFSET 3 -#endif -#if SAMD09 || SAMD10 || SAMD11 -# define TC_INSTANCE_OFFSET 1 -#endif - -#if SAMD20 -# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC0_CC8_NUM -#elif SAML21 || SAML22 || SAMC20 || SAMC21 -# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC0_CC_NUM -#elif SAMD09 || SAMD10 || SAMD11 -# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC1_CC8_NUM -#else -# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC3_CC8_NUM - /* Same number for 8-, 16- and 32-bit TC and all TC instances */ -#endif - -/** TC Instance MAX ID Number. */ -#if SAMD20E || SAMD21G || SAMD21E || SAMR21 -# if SAMD21GXXL -# define TC_INST_MAX_ID 7 -# else -# define TC_INST_MAX_ID 5 -# endif -#elif SAML21 || SAMC20 || SAMC21 -# define TC_INST_MAX_ID 4 -#elif SAML22 -# define TC_INST_MAX_ID 3 -#elif SAMD09 || SAMD10 || SAMD11 -# define TC_INST_MAX_ID 2 -#else -# define TC_INST_MAX_ID 7 -#endif - -#endif - -#if TC_ASYNC == true -# include "system_interrupt.h" -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#if TC_ASYNC == true -/** Enum for the possible callback types for the TC module. */ -enum tc_callback { - /** Callback for TC overflow. */ - TC_CALLBACK_OVERFLOW, - /** Callback for capture overflow error. */ - TC_CALLBACK_ERROR, - /** Callback for capture compare channel 0. */ - TC_CALLBACK_CC_CHANNEL0, - /** Callback for capture compare channel 1. */ - TC_CALLBACK_CC_CHANNEL1, -# if !defined(__DOXYGEN__) - /** Number of available callbacks. */ - TC_CALLBACK_N, -# endif -}; -#endif - -/** - * \name Module Status Flags - * - * TC status flags, returned by \ref tc_get_status() and cleared by - * \ref tc_clear_status(). - * - * @{ - */ - -/** Timer channel 0 has matched against its compare value, or has captured a - * new value. - */ -#define TC_STATUS_CHANNEL_0_MATCH (1UL << 0) - -/** Timer channel 1 has matched against its compare value, or has captured a - * new value. - */ -#define TC_STATUS_CHANNEL_1_MATCH (1UL << 1) - -/** Timer register synchronization has completed, and the synchronized count - * value may be read. - */ -#define TC_STATUS_SYNC_READY (1UL << 2) - -/** A new value was captured before the previous value was read, resulting in - * lost data. - */ -#define TC_STATUS_CAPTURE_OVERFLOW (1UL << 3) - -/** The timer count value has overflowed from its maximum value to its minimum - * when counting upward, or from its minimum value to its maximum when - * counting downward. - */ -#define TC_STATUS_COUNT_OVERFLOW (1UL << 4) - -#ifdef FEATURE_TC_DOUBLE_BUFFERED -/** Channel 0 compare or capture buffer valid. */ -#define TC_STATUS_CHN0_BUFFER_VALID (1UL << 5) -/** Channel 1 compare or capture buffer valid. */ -#define TC_STATUS_CHN1_BUFFER_VALID (1UL << 6) -/** Period buffer valid. */ -#define TC_STATUS_PERIOD_BUFFER_VALID (1UL << 7) -#endif -/** @} */ - -/** - * \brief Index of the compare capture channels. - * - * This enum is used to specify which capture/compare channel to do - * operations on. - */ -enum tc_compare_capture_channel { - /** Index of compare capture channel 0. */ - TC_COMPARE_CAPTURE_CHANNEL_0, - /** Index of compare capture channel 1. */ - TC_COMPARE_CAPTURE_CHANNEL_1, -}; - -/** TC wave generation mode. */ -#if SAML21 || SAML22 || SAMC20 || SAMC21 -#define TC_WAVE_GENERATION_NORMAL_FREQ_MODE TC_WAVE_WAVEGEN_NFRQ -#define TC_WAVE_GENERATION_MATCH_FREQ_MODE TC_WAVE_WAVEGEN_MFRQ -#define TC_WAVE_GENERATION_NORMAL_PWM_MODE TC_WAVE_WAVEGEN_NPWM -#define TC_WAVE_GENERATION_MATCH_PWM_MODE TC_WAVE_WAVEGEN_MPWM -#else -#define TC_WAVE_GENERATION_NORMAL_FREQ_MODE TC_CTRLA_WAVEGEN_NFRQ -#define TC_WAVE_GENERATION_MATCH_FREQ_MODE TC_CTRLA_WAVEGEN_MFRQ -#define TC_WAVE_GENERATION_NORMAL_PWM_MODE TC_CTRLA_WAVEGEN_NPWM -#define TC_WAVE_GENERATION_MATCH_PWM_MODE TC_CTRLA_WAVEGEN_MPWM -#endif - -/** - * \brief TC wave generation mode enum. - * - * This enum is used to select which mode to run the wave - * generation in. - * - */ -enum tc_wave_generation { - /** Top is maximum, except in 8-bit counter size where it is the PER - * register. - */ - TC_WAVE_GENERATION_NORMAL_FREQ = TC_WAVE_GENERATION_NORMAL_FREQ_MODE, - - /** Top is CC0, except in 8-bit counter size where it is the PER - * register. - */ - TC_WAVE_GENERATION_MATCH_FREQ = TC_WAVE_GENERATION_MATCH_FREQ_MODE, - - /** Top is maximum, except in 8-bit counter size where it is the PER - * register. - */ - TC_WAVE_GENERATION_NORMAL_PWM = TC_WAVE_GENERATION_NORMAL_PWM_MODE, - - /** Top is CC0, except in 8-bit counter size where it is the PER - * register. - */ - TC_WAVE_GENERATION_MATCH_PWM = TC_WAVE_GENERATION_MATCH_PWM_MODE, -}; - -/** - * \brief Specifies if the counter is 8-, 16-, or 32-bit. - * - * This enum specifies the maximum value it is possible to count to. - */ -enum tc_counter_size { - /** The counter's maximum value is 0xFF, the period register is - * available to be used as top value. - */ - TC_COUNTER_SIZE_8BIT = TC_CTRLA_MODE_COUNT8, - - /** The counter's maximum value is 0xFFFF. There is no separate - * period register, to modify top one of the capture compare - * registers has to be used. This limits the amount of - * available channels. - */ - TC_COUNTER_SIZE_16BIT = TC_CTRLA_MODE_COUNT16, - - /** The counter's maximum value is 0xFFFFFFFF. There is no separate - * period register, to modify top one of the capture compare - * registers has to be used. This limits the amount of - * available channels. - */ - TC_COUNTER_SIZE_32BIT = TC_CTRLA_MODE_COUNT32, -}; - -/** - * \brief TC Counter reload action enum. - * - * This enum specify how the counter and prescaler should reload. - */ -enum tc_reload_action { - /** The counter is reloaded/reset on the next GCLK and starts - * counting on the prescaler clock. - */ - TC_RELOAD_ACTION_GCLK = TC_CTRLA_PRESCSYNC_GCLK, - - /** The counter is reloaded/reset on the next prescaler clock. - */ - TC_RELOAD_ACTION_PRESC = TC_CTRLA_PRESCSYNC_PRESC, - - /** The counter is reloaded/reset on the next GCLK, and the - * prescaler is restarted as well. - */ - TC_RELOAD_ACTION_RESYNC = TC_CTRLA_PRESCSYNC_RESYNC, -}; - -/** - * \brief TC clock prescaler values. - * - * This enum is used to choose the clock prescaler - * configuration. The prescaler divides the clock frequency of the TC - * module to make the counter count slower. - */ -enum tc_clock_prescaler { - /** Divide clock by 1. */ - TC_CLOCK_PRESCALER_DIV1 = TC_CTRLA_PRESCALER(0), - /** Divide clock by 2. */ - TC_CLOCK_PRESCALER_DIV2 = TC_CTRLA_PRESCALER(1), - /** Divide clock by 4. */ - TC_CLOCK_PRESCALER_DIV4 = TC_CTRLA_PRESCALER(2), - /** Divide clock by 8. */ - TC_CLOCK_PRESCALER_DIV8 = TC_CTRLA_PRESCALER(3), - /** Divide clock by 16. */ - TC_CLOCK_PRESCALER_DIV16 = TC_CTRLA_PRESCALER(4), - /** Divide clock by 64. */ - TC_CLOCK_PRESCALER_DIV64 = TC_CTRLA_PRESCALER(5), - /** Divide clock by 256. */ - TC_CLOCK_PRESCALER_DIV256 = TC_CTRLA_PRESCALER(6), - /** Divide clock by 1024. */ - TC_CLOCK_PRESCALER_DIV1024 = TC_CTRLA_PRESCALER(7), -}; - -/** - * \brief TC module count direction. - * - * Timer/Counter count direction. - */ -enum tc_count_direction { - /** Timer should count upward from zero to MAX. */ - TC_COUNT_DIRECTION_UP, - - /** Timer should count downward to zero from MAX. */ - TC_COUNT_DIRECTION_DOWN, -}; - -/** Waveform inversion mode. */ -#if SAML21 || SAML22 || SAMC20 || SAMC21 -#define TC_WAVEFORM_INVERT_CC0_MODE TC_DRVCTRL_INVEN(1) -#define TC_WAVEFORM_INVERT_CC1_MODE TC_DRVCTRL_INVEN(2) -#else -#define TC_WAVEFORM_INVERT_CC0_MODE TC_CTRLC_INVEN(1) -#define TC_WAVEFORM_INVERT_CC1_MODE TC_CTRLC_INVEN(2) -#endif - -/** - * \brief Waveform inversion mode. - * - * Output waveform inversion mode. - */ -enum tc_waveform_invert_output { - /** No inversion of the waveform output. */ - TC_WAVEFORM_INVERT_OUTPUT_NONE = 0, - /** Invert output from compare channel 0. */ - TC_WAVEFORM_INVERT_OUTPUT_CHANNEL_0 = TC_WAVEFORM_INVERT_CC0_MODE, - /** Invert output from compare channel 1. */ - TC_WAVEFORM_INVERT_OUTPUT_CHANNEL_1 = TC_WAVEFORM_INVERT_CC1_MODE, -}; - -/** - * \brief Action to perform when the TC module is triggered by an event. - * - * Event action to perform when the module is triggered by an event. - */ -enum tc_event_action { - /** No event action. */ - TC_EVENT_ACTION_OFF = TC_EVCTRL_EVACT_OFF, - /** Re-trigger on event. */ - TC_EVENT_ACTION_RETRIGGER = TC_EVCTRL_EVACT_RETRIGGER, - /** Increment counter on event. */ - TC_EVENT_ACTION_INCREMENT_COUNTER = TC_EVCTRL_EVACT_COUNT, - /** Start counter on event. */ - TC_EVENT_ACTION_START = TC_EVCTRL_EVACT_START, - - /** Store period in capture register 0, pulse width in capture - * register 1. - */ - TC_EVENT_ACTION_PPW = TC_EVCTRL_EVACT_PPW, - - /** Store pulse width in capture register 0, period in capture - * register 1. - */ - TC_EVENT_ACTION_PWP = TC_EVCTRL_EVACT_PWP, -#ifdef FEATURE_TC_STAMP_PW_CAPTURE - /** Time stamp capture. */ - TC_EVENT_ACTION_STAMP = TC_EVCTRL_EVACT_STAMP, - /** Pulse width capture. */ - TC_EVENT_ACTION_PW = TC_EVCTRL_EVACT_PW, -#endif -}; - -/** - * \brief TC event enable/disable structure. - * - * Event flags for the \ref tc_enable_events() and \ref tc_disable_events(). - */ -struct tc_events { - /** Generate an output event on a compare channel match. */ - bool generate_event_on_compare_channel - [NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; - /** Generate an output event on counter overflow. */ - bool generate_event_on_overflow; - /** Perform the configured event action when an incoming event is signalled. */ - bool on_event_perform_action; - /** Specifies if the input event source is inverted, when used in PWP or - * PPW event action modes. - */ - bool invert_event_input; - /** Specifies which event to trigger if an event is triggered. */ - enum tc_event_action event_action; -}; - -/** - * \brief Configuration struct for TC module in 8-bit size counter mode. - */ -struct tc_8bit_config { - /** Initial timer count value. */ - uint8_t value; - /** Where to count to or from depending on the direction on the counter. */ - uint8_t period; - /** Value to be used for compare match on each channel. */ - uint8_t compare_capture_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; -}; - -/** - * \brief Configuration struct for TC module in 16-bit size counter mode. - */ -struct tc_16bit_config { - /** Initial timer count value. */ - uint16_t value; - /** Value to be used for compare match on each channel. */ - uint16_t compare_capture_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; -}; - -/** - * \brief Configuration struct for TC module in 32-bit size counter mode. - */ -struct tc_32bit_config { - /** Initial timer count value. */ - uint32_t value; - /** Value to be used for compare match on each channel. */ - uint32_t compare_capture_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; -}; - -/** - * \brief Configuration struct for TC module in 32-bit size counter mode. - */ -struct tc_pwm_channel { - /** When \c true, PWM output for the given channel is enabled. */ - bool enabled; - /** Specifies pin output for each channel. */ - uint32_t pin_out; - /** Specifies MUX setting for each output channel pin. */ - uint32_t pin_mux; -}; - -/** - * \brief TC configuration structure. - * - * Configuration struct for a TC instance. This structure should be - * initialized by the \ref tc_get_config_defaults function before being - * modified by the user application. - */ -struct tc_config { - /** GCLK generator used to clock the peripheral. */ - enum gclk_generator clock_source; - - /** When \c true the module is enabled during standby. */ - bool run_in_standby; -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) - /** Run on demand. */ - bool on_demand; -#endif - /** Specifies either 8-, 16-, or 32-bit counter size. */ - enum tc_counter_size counter_size; - /** Specifies the prescaler value for GCLK_TC. */ - enum tc_clock_prescaler clock_prescaler; - /** Specifies which waveform generation mode to use. */ - enum tc_wave_generation wave_generation; - - /** Specifies the reload or reset time of the counter and prescaler - * resynchronization on a re-trigger event for the TC. - */ - enum tc_reload_action reload_action; - - /** Specifies which channel(s) to invert the waveform on. - For SAM L21/L22/C20/C21, it's also used to invert IO input pin. */ - uint8_t waveform_invert_output; - - /** Specifies which channel(s) to enable channel capture - * operation on. - */ - bool enable_capture_on_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; -#ifdef FEATURE_TC_IO_CAPTURE - /** Specifies which channel(s) to enable I/O capture - * operation on. - */ - bool enable_capture_on_IO[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; -#endif - - /** When \c true, one-shot will stop the TC on next hardware or software - * re-trigger event or overflow/underflow. - */ - bool oneshot; - - /** Specifies the direction for the TC to count. */ - enum tc_count_direction count_direction; - - /** Specifies the PWM channel for TC. */ - struct tc_pwm_channel pwm_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; - - /** Access the different counter size settings though this configuration member. */ - union { - /** Struct for 8-bit specific timer configuration. */ - struct tc_8bit_config counter_8_bit; - /** Struct for 16-bit specific timer configuration. */ - struct tc_16bit_config counter_16_bit; - /** Struct for 32-bit specific timer configuration. */ - struct tc_32bit_config counter_32_bit; - }; - -#ifdef FEATURE_TC_DOUBLE_BUFFERED - /** Set to \c true to enable double buffering write. When enabled any write - * through \ref tc_set_top_value(), \ref tc_set_compare_value() and - * will direct to the buffer register as buffered - * value, and the buffered value will be committed to effective register - * on UPDATE condition, if update is not locked. - */ - bool double_buffering_enabled; -#endif -}; - -#if TC_ASYNC == true -/* Forward Declaration for the device instance. */ -struct tc_module; - -/* Type of the callback functions. */ -typedef void (*tc_callback_t)(struct tc_module *const module); -#endif - -/** - * \brief TC software device instance structure. - * - * TC software instance structure, used to retain software state information - * of an associated hardware module instance. - * - * \note The fields of this structure should not be altered by the user - * application; they are reserved for module-internal use only. - */ -struct tc_module { -#if !defined(__DOXYGEN__) - /** Hardware module pointer of the associated Timer/Counter peripheral. */ - Tc *hw; - - /** Size of the initialized Timer/Counter module configuration. */ - enum tc_counter_size counter_size; -# if TC_ASYNC == true - /** Array of callbacks. */ - tc_callback_t callback[TC_CALLBACK_N]; - /** Bit mask for callbacks registered. */ - uint8_t register_callback_mask; - /** Bit mask for callbacks enabled. */ - uint8_t enable_callback_mask; -# endif -#ifdef FEATURE_TC_DOUBLE_BUFFERED - /** Set to \c true to enable double buffering write. */ - bool double_buffering_enabled; -#endif -#endif -}; - -#if !defined(__DOXYGEN__) -uint8_t _tc_get_inst_index( - Tc *const hw); -#endif - -/** - * \name Driver Initialization and Configuration - * @{ - */ - -/** - * \brief Determines if the hardware module(s) are currently synchronizing to - *the bus. - * - * Checks to see if the underlying hardware peripheral module(s) are currently - * synchronizing across multiple clock domains to the hardware bus. This - * function can be used to delay further operations on a module until such time - * that it is ready, to prevent blocking delays for synchronization in the - * user application. - * - * \param[in] module_inst Pointer to the software module instance struct - * - * \return Synchronization status of the underlying hardware module(s). - * - * \retval false If the module has completed synchronization - * \retval true If the module synchronization is ongoing - */ -static inline bool tc_is_syncing( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) - return (tc_module->SYNCBUSY.reg); -#else - return (tc_module->STATUS.reg & TC_STATUS_SYNCBUSY); -#endif -} - -/** - * \brief Initializes config with predefined default values. - * - * This function will initialize a given TC configuration structure to - * a set of known default values. This function should be called on - * any new instance of the configuration structures before being - * modified by the user application. - * - * The default configuration is as follows: - * \li GCLK generator 0 (GCLK main) clock source - * \li 16-bit counter size on the counter - * \li No prescaler - * \li Normal frequency wave generation - * \li GCLK reload action - * \li Don't run in standby - * \li Don't run on demand for SAM L21/L22/C20/C21 - * \li No inversion of waveform output - * \li No capture enabled - * \li No I/O capture enabled for SAM L21/L22/C20/C21 - * \li No event input enabled - * \li Count upward - * \li Don't perform one-shot operations - * \li No event action - * \li No channel 0 PWM output - * \li No channel 1 PWM output - * \li Counter starts on 0 - * \li Capture compare channel 0 set to 0 - * \li Capture compare channel 1 set to 0 - * \li No PWM pin output enabled - * \li Pin and MUX configuration not set - * \li Double buffer disabled (if have this feature) - * - * \param[out] config Pointer to a TC module configuration structure to set - */ -static inline void tc_get_config_defaults( - struct tc_config *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Write default config to config struct */ - config->clock_source = GCLK_GENERATOR_0; - config->counter_size = TC_COUNTER_SIZE_16BIT; - config->clock_prescaler = TC_CLOCK_PRESCALER_DIV1; - config->wave_generation = TC_WAVE_GENERATION_NORMAL_FREQ; - config->reload_action = TC_RELOAD_ACTION_GCLK; - config->run_in_standby = false; -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) - config->on_demand = false; -#endif - config->waveform_invert_output = TC_WAVEFORM_INVERT_OUTPUT_NONE; - config->enable_capture_on_channel[TC_COMPARE_CAPTURE_CHANNEL_0] = false; - config->enable_capture_on_channel[TC_COMPARE_CAPTURE_CHANNEL_1] = false; -#ifdef FEATURE_TC_IO_CAPTURE - config->enable_capture_on_IO[TC_COMPARE_CAPTURE_CHANNEL_0] = false; - config->enable_capture_on_IO[TC_COMPARE_CAPTURE_CHANNEL_1] = false; -#endif - - config->count_direction = TC_COUNT_DIRECTION_UP; - config->oneshot = false; - - config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_0].enabled = false; - config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_0].pin_out = 0; - config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_0].pin_mux = 0; - - config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_1].enabled = false; - config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_1].pin_out = 0; - config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_1].pin_mux = 0; - - config->counter_16_bit.value = 0x0000; - config->counter_16_bit.compare_capture_channel\ - [TC_COMPARE_CAPTURE_CHANNEL_0] = 0x0000; - config->counter_16_bit.compare_capture_channel\ - [TC_COMPARE_CAPTURE_CHANNEL_1] = 0x0000; -#ifdef FEATURE_TC_DOUBLE_BUFFERED - config->double_buffering_enabled = false; -#endif - -} - -enum status_code tc_init( - struct tc_module *const module_inst, - Tc *const hw, - const struct tc_config *const config); - -/** @} */ - -/** - * \name Event Management - * @{ - */ - -/** - * \brief Enables a TC module event input or output. - * - * Enables one or more input or output events to or from the TC module. - * See \ref tc_events for a list of events this module supports. - * - * \note Events cannot be altered while the module is enabled. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] events Struct containing flags of events to enable - */ -static inline void tc_enable_events( - struct tc_module *const module_inst, - struct tc_events *const events) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - Assert(events); - - Tc *const tc_module = module_inst->hw; - - uint32_t event_mask = 0; - - if (events->invert_event_input == true) { - event_mask |= TC_EVCTRL_TCINV; - } - - if (events->on_event_perform_action == true) { - event_mask |= TC_EVCTRL_TCEI; - } - - if (events->generate_event_on_overflow == true) { - event_mask |= TC_EVCTRL_OVFEO; - } - - for (uint8_t i = 0; i < NUMBER_OF_COMPARE_CAPTURE_CHANNELS; i++) { - if (events->generate_event_on_compare_channel[i] == true) { - event_mask |= (TC_EVCTRL_MCEO(1) << i); - } - } - - tc_module->COUNT8.EVCTRL.reg |= event_mask | events->event_action; -} - -/** - * \brief Disables a TC module event input or output. - * - * Disables one or more input or output events to or from the TC module. - * See \ref tc_events for a list of events this module supports. - * - * \note Events cannot be altered while the module is enabled. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] events Struct containing flags of events to disable - */ -static inline void tc_disable_events( - struct tc_module *const module_inst, - struct tc_events *const events) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - Assert(events); - - Tc *const tc_module = module_inst->hw; - - uint32_t event_mask = 0; - - if (events->invert_event_input == true) { - event_mask |= TC_EVCTRL_TCINV; - } - - if (events->on_event_perform_action == true) { - event_mask |= TC_EVCTRL_TCEI; - } - - if (events->generate_event_on_overflow == true) { - event_mask |= TC_EVCTRL_OVFEO; - } - - for (uint8_t i = 0; i < NUMBER_OF_COMPARE_CAPTURE_CHANNELS; i++) { - if (events->generate_event_on_compare_channel[i] == true) { - event_mask |= (TC_EVCTRL_MCEO(1) << i); - } - } - - tc_module->COUNT8.EVCTRL.reg &= ~event_mask; -} - -/** @} */ - -/** - * \name Enable/Disable/Reset - * @{ - */ - -enum status_code tc_reset( - const struct tc_module *const module_inst); - -/** - * \brief Enable the TC module. - * - * Enables a TC module that has been previously initialized. The counter will - * start when the counter is enabled. - * - * \note When the counter is configured to re-trigger on an event, the counter - * will not start until the start function is used. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_enable( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Enable TC module */ - tc_module->CTRLA.reg |= TC_CTRLA_ENABLE; -} - -/** - * \brief Disables the TC module. - * - * Disables a TC module and stops the counter. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_disable( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Disable TC module */ - tc_module->CTRLA.reg &= ~TC_CTRLA_ENABLE; -} - -/** @} */ - -/** - * \name Get/Set Count Value - * @{ - */ - -uint32_t tc_get_count_value( - const struct tc_module *const module_inst); - -enum status_code tc_set_count_value( - const struct tc_module *const module_inst, - const uint32_t count); - -/** @} */ - -/** - * \name Start/Stop Counter - * @{ - */ - -/** - * \brief Stops the counter. - * - * This function will stop the counter. When the counter is stopped - * the value in the count value is set to 0 if the counter was - * counting up, or maximum if the counter was counting - * down when stopped. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_stop_counter( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Write command to execute */ - tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_STOP_Val); -} - -/** - * \brief Starts the counter. - * - * Starts or restarts an initialized TC module's counter. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_start_counter( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Make certain that there are no conflicting commands in the register */ - tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Write command to execute */ - tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_RETRIGGER_Val); -} - -/** @} */ - -#ifdef FEATURE_TC_DOUBLE_BUFFERED -/** - * \name Double Buffering - * @{ - */ - -/** - * \brief Update double buffer. - * - * Update double buffer. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_update_double_buffer( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Make certain that there are no conflicting commands in the register */ - tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Write command to execute */ - tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_UPDATE_Val); -} -/** @} */ -#endif - -#ifdef FEATURE_TC_READ_SYNC -/** - * \name Count Read Synchronization - * @{ - */ - -/** - * \brief Read synchronization of COUNT. - * - * Read synchronization of COUNT. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_sync_read_count( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Make certain that there are no conflicting commands in the register */ - tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Write command to execute */ - tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_READSYNC_Val); -} -/** @} */ -#endif - -#ifdef FEATURE_TC_GENERATE_DMA_TRIGGER -/** - * \name Generate TC DMA Triggers command - * @{ - */ - -/** - * \brief TC DMA Trigger. - * - * TC DMA trigger command. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_dma_trigger_command( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Make certain that there are no conflicting commands in the register */ - tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - -#if (SAMC20) || (SAMC21) || (SAML22) || (SAML21XXXB) - /* Write command to execute */ - tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_DMAOS_Val); -#endif -} -/** @} */ -#endif - -/** - * \name Get Capture Set Compare - * @{ - */ - -uint32_t tc_get_capture_value( - const struct tc_module *const module_inst, - const enum tc_compare_capture_channel channel_index); - -enum status_code tc_set_compare_value( - const struct tc_module *const module_inst, - const enum tc_compare_capture_channel channel_index, - const uint32_t compare_value); - -/** @} */ - -/** - * \name Set Top Value - * @{ - */ - -enum status_code tc_set_top_value( - const struct tc_module *const module_inst, - const uint32_t top_value); - -/** @} */ - -/** - * \name Status Management - * @{ - */ - -/** - * \brief Retrieves the current module status. - * - * Retrieves the status of the module, giving overall state information. - * - * \param[in] module_inst Pointer to the TC software instance struct - * - * \return Bitmask of \c TC_STATUS_* flags. - * - * \retval TC_STATUS_CHANNEL_0_MATCH Timer channel 0 compare/capture match - * \retval TC_STATUS_CHANNEL_1_MATCH Timer channel 1 compare/capture match - * \retval TC_STATUS_SYNC_READY Timer read synchronization has completed - * \retval TC_STATUS_CAPTURE_OVERFLOW Timer capture data has overflowed - * \retval TC_STATUS_COUNT_OVERFLOW Timer count value has overflowed - * \retval TC_STATUS_CHN0_BUFFER_VALID Timer count channel 0 compare/capture buffer valid - * \retval TC_STATUS_CHN1_BUFFER_VALID Timer count channel 1 compare/capture buffer valid - * \retval TC_STATUS_PERIOD_BUFFER_VALID Timer count period buffer valid - */ -static inline uint32_t tc_get_status( - struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - uint32_t int_flags = tc_module->INTFLAG.reg; - - uint32_t status_flags = 0; - - /* Check for TC channel 0 match */ - if (int_flags & TC_INTFLAG_MC(1)) { - status_flags |= TC_STATUS_CHANNEL_0_MATCH; - } - - /* Check for TC channel 1 match */ - if (int_flags & TC_INTFLAG_MC(2)) { - status_flags |= TC_STATUS_CHANNEL_1_MATCH; - } - -#if !defined(FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2) - /* Check for TC read synchronization ready */ - if (int_flags & TC_INTFLAG_SYNCRDY) { - status_flags |= TC_STATUS_SYNC_READY; - } -#endif - - /* Check for TC capture overflow */ - if (int_flags & TC_INTFLAG_ERR) { - status_flags |= TC_STATUS_CAPTURE_OVERFLOW; - } - - /* Check for TC count overflow */ - if (int_flags & TC_INTFLAG_OVF) { - status_flags |= TC_STATUS_COUNT_OVERFLOW; - } -#ifdef FEATURE_TC_DOUBLE_BUFFERED - uint8_t double_buffer_valid_status = tc_module->STATUS.reg; - - /* Check channel 0 compare or capture buffer valid */ - if (double_buffer_valid_status & TC_STATUS_CCBUFV0) { - status_flags |= TC_STATUS_CHN0_BUFFER_VALID; - } - /* Check channel 0 compare or capture buffer valid */ - if (double_buffer_valid_status & TC_STATUS_CCBUFV1) { - status_flags |= TC_STATUS_CHN1_BUFFER_VALID; - } - /* Check period buffer valid */ - if (double_buffer_valid_status & TC_STATUS_PERBUFV) { - status_flags |= TC_STATUS_PERIOD_BUFFER_VALID; - } -#endif - - return status_flags; -} - -/** - * \brief Clears a module status flag. - * - * Clears the given status flag of the module. - * - * \param[in] module_inst Pointer to the TC software instance struct - * \param[in] status_flags Bitmask of \c TC_STATUS_* flags to clear - */ -static inline void tc_clear_status( - struct tc_module *const module_inst, - const uint32_t status_flags) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - uint32_t int_flags = 0; - - /* Check for TC channel 0 match */ - if (status_flags & TC_STATUS_CHANNEL_0_MATCH) { - int_flags |= TC_INTFLAG_MC(1); - } - - /* Check for TC channel 1 match */ - if (status_flags & TC_STATUS_CHANNEL_1_MATCH) { - int_flags |= TC_INTFLAG_MC(2); - } - -#if !defined(FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2) - /* Check for TC read synchronization ready */ - if (status_flags & TC_STATUS_SYNC_READY) { - int_flags |= TC_INTFLAG_SYNCRDY; - } -#endif - - /* Check for TC capture overflow */ - if (status_flags & TC_STATUS_CAPTURE_OVERFLOW) { - int_flags |= TC_INTFLAG_ERR; - } - - /* Check for TC count overflow */ - if (status_flags & TC_STATUS_COUNT_OVERFLOW) { - int_flags |= TC_INTFLAG_OVF; - } - - /* Clear interrupt flag */ - tc_module->INTFLAG.reg = int_flags; -} - -/** @} */ - -/** @} */ - -#ifdef __cplusplus -} -#endif - -/** - * \page asfdoc_sam0_tc_extra Extra Information for TC Driver - * - * \section asfdoc_sam0_tc_extra_acronyms Acronyms - * The table below presents the acronyms used in this module: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
AcronymDescription
DMADirect Memory Access
TCTimer Counter
PWMPulse Width Modulation
PWPPulse Width Period
PPWPeriod Pulse Width
- * - * - * \section asfdoc_sam0_tc_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - \ref asfdoc_sam0_system_pinmux_group "System Pin Multiplexer Driver" - * - * - * \section asfdoc_sam0_tc_extra_errata Errata - * There are no errata related to this driver. - * - * - * \section asfdoc_sam0_tc_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Changelog
Added support for SAMD21 and do some modifications as below: - * \li Clean up in the configuration structure, the counter size - * setting specific registers is accessed through the counter_8_bit, - * counter_16_bit and counter_32_bit structures - * \li All event related settings moved into the tc_event structure
Added automatic digital clock interface enable for the slave TC - * module when a timer is initialized in 32-bit mode
Initial Release
- */ - -/** - * \page asfdoc_sam0_tc_exqsg Examples for TC Driver - * - * This is a list of the available Quick Start guides (QSGs) and example - * applications for \ref asfdoc_sam0_tc_group. QSGs are simple examples with - * step-by-step instructions to configure and use this driver in a selection of - * use cases. Note that QSGs can be compiled as a standalone application or be - * added to the user application. - * - * - \subpage asfdoc_sam0_tc_basic_use_case - * - \subpage asfdoc_sam0_tc_macth_freq_use_case - * \if TC_CALLBACK_MODE - * - \subpage asfdoc_sam0_tc_timer_use_case - * - \subpage asfdoc_sam0_tc_callback_use_case - * \endif - * - \subpage asfdoc_sam0_tc_dma_use_case - * - * \page asfdoc_sam0_tc_document_revision_history Document Revision History - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Doc. Rev. - * Date - * Comments - *
F08/2015Added support for SAM C21 and SAM L22
E04/2015Added support for SAM L21 and SAM DA1
D12/2014Added timer use case. - * Added support for SAM R21 and SAM D10/D11
C01/2014Added support for SAM D21
B06/2013Corrected documentation typos
A06/2013Initial release
- */ - -#endif /* TC_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc_interrupt.c b/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc_interrupt.c deleted file mode 100644 index 032be2f..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc_interrupt.c +++ /dev/null @@ -1,199 +0,0 @@ -/** - * \file - * - * \brief SAM TC - Timer Counter Callback Driver - * - * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/* - * Support and FAQ: visit Atmel Support - */ - -#include "tc_interrupt.h" - -void *_tc_instances[TC_INST_NUM]; - -void _tc_interrupt_handler(uint8_t instance); - -/** - * \brief Registers a callback. - * - * Registers a callback function which is implemented by the user. - * - * \note The callback must be enabled by \ref tc_enable_callback, - * in order for the interrupt handler to call it when the conditions for the - * callback type is met. - * - * \param[in] module Pointer to TC software instance struct - * \param[in] callback_func Pointer to callback function - * \param[in] callback_type Callback type given by an enum - */ -enum status_code tc_register_callback( - struct tc_module *const module, - tc_callback_t callback_func, - const enum tc_callback callback_type) -{ - /* Sanity check arguments */ - Assert(module); - Assert(callback_func); - - /* Register callback function */ - module->callback[callback_type] = callback_func; - - /* Set the bit corresponding to the callback_type */ - if (callback_type == TC_CALLBACK_CC_CHANNEL0) { - module->register_callback_mask |= TC_INTFLAG_MC(1); - } - else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { - module->register_callback_mask |= TC_INTFLAG_MC(2); - } - else { - module->register_callback_mask |= (1 << callback_type); - } - return STATUS_OK; -} - -/** - * \brief Unregisters a callback. - * - * Unregisters a callback function implemented by the user. The callback should be - * disabled before it is unregistered. - * - * \param[in] module Pointer to TC software instance struct - * \param[in] callback_type Callback type given by an enum - */ -enum status_code tc_unregister_callback( - struct tc_module *const module, - const enum tc_callback callback_type) -{ - /* Sanity check arguments */ - Assert(module); - - /* Unregister callback function */ - module->callback[callback_type] = NULL; - - /* Clear the bit corresponding to the callback_type */ - if (callback_type == TC_CALLBACK_CC_CHANNEL0) { - module->register_callback_mask &= ~TC_INTFLAG_MC(1); - } - else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { - module->register_callback_mask &= ~TC_INTFLAG_MC(2); - } - else { - module->register_callback_mask &= ~(1 << callback_type); - } - return STATUS_OK; -} - -/** - * \internal ISR handler for TC - * - * Auto-generate a set of interrupt handlers for each TC in the device. - */ -#define _TC_INTERRUPT_HANDLER(n, m) \ - void TC##n##_Handler(void) \ - { \ - _tc_interrupt_handler(m); \ - } - -#if (SAML21E) || (SAML21G) - _TC_INTERRUPT_HANDLER(0,0) - _TC_INTERRUPT_HANDLER(1,1) - _TC_INTERRUPT_HANDLER(4,2) -#else - MRECURSION(TC_INST_NUM, _TC_INTERRUPT_HANDLER, TC_INST_MAX_ID) -#endif - - -/** - * \internal Interrupt Handler for TC module - * - * Handles interrupts as they occur, it will run the callback functions - * that are registered and enabled. - * - * \param[in] instance ID of the TC instance calling the interrupt - * handler. - */ -void _tc_interrupt_handler( - uint8_t instance) -{ - /* Temporary variable */ - uint8_t interrupt_and_callback_status_mask; - - /* Get device instance from the look-up table */ - struct tc_module *module - = (struct tc_module *)_tc_instances[instance]; - - /* Read and mask interrupt flag register */ - interrupt_and_callback_status_mask = module->hw->COUNT8.INTFLAG.reg & - module->register_callback_mask & - module->enable_callback_mask; - - /* Check if an Overflow interrupt has occurred */ - if (interrupt_and_callback_status_mask & TC_INTFLAG_OVF) { - /* Invoke registered and enabled callback function */ - (module->callback[TC_CALLBACK_OVERFLOW])(module); - /* Clear interrupt flag */ - module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_OVF; - } - - /* Check if an Error interrupt has occurred */ - if (interrupt_and_callback_status_mask & TC_INTFLAG_ERR) { - /* Invoke registered and enabled callback function */ - (module->callback[TC_CALLBACK_ERROR])(module); - /* Clear interrupt flag */ - module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_ERR; - } - - /* Check if an Match/Capture Channel 0 interrupt has occurred */ - if (interrupt_and_callback_status_mask & TC_INTFLAG_MC(1)) { - /* Invoke registered and enabled callback function */ - (module->callback[TC_CALLBACK_CC_CHANNEL0])(module); - /* Clear interrupt flag */ - module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_MC(1); - } - - /* Check if an Match/Capture Channel 1 interrupt has occurred */ - if (interrupt_and_callback_status_mask & TC_INTFLAG_MC(2)) { - /* Invoke registered and enabled callback function */ - (module->callback[TC_CALLBACK_CC_CHANNEL1])(module); - /* Clear interrupt flag */ - module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_MC(2); - } -} diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc_interrupt.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc_interrupt.h deleted file mode 100644 index 4e1fd8e..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/tc_interrupt.h +++ /dev/null @@ -1,179 +0,0 @@ -/** - * \file - * - * \brief SAM TC - Timer Counter Callback Driver - * - * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/* - * Support and FAQ: visit Atmel Support - */ - -#ifndef TC_INTERRUPT_H_INCLUDED -#define TC_INTERRUPT_H_INCLUDED - -#include "tc.h" -#include "system_interrupt.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#if !defined(__DOXYGEN__) -extern void *_tc_instances[TC_INST_NUM]; - -# define _TC_INTERRUPT_VECT_NUM(n, unused) \ - SYSTEM_INTERRUPT_MODULE_TC##n, -/** - * \internal Get the interrupt vector for the given device instance - * - * \param[in] TC module instance number. - * - * \return Interrupt vector for of the given TC module instance. - */ -static enum system_interrupt_vector _tc_interrupt_get_interrupt_vector( - uint32_t inst_num) -{ - static uint8_t tc_interrupt_vectors[TC_INST_NUM] = - { -#if (SAML21E) || (SAML21G) - SYSTEM_INTERRUPT_MODULE_TC0, - SYSTEM_INTERRUPT_MODULE_TC1, - SYSTEM_INTERRUPT_MODULE_TC4 -#else - MRECURSION(TC_INST_NUM, _TC_INTERRUPT_VECT_NUM, TC_INST_MAX_ID) -#endif - }; - - return (enum system_interrupt_vector)tc_interrupt_vectors[inst_num]; -} -#endif /* !defined(__DOXYGEN__) */ - -/** - * \name Callback Management - * {@ - */ - -enum status_code tc_register_callback( - struct tc_module *const module, - tc_callback_t callback_func, - const enum tc_callback callback_type); - -enum status_code tc_unregister_callback( - struct tc_module *const module, - const enum tc_callback callback_type); - -/** - * \brief Enables callback. - * - * Enables the callback function registered by the \ref - * tc_register_callback. The callback function will be called from the - * interrupt handler when the conditions for the callback type are - * met. This function will also enable the appropriate interrupts. - * - * \param[in] module Pointer to TC software instance struct - * \param[in] callback_type Callback type given by an enum - */ -static inline void tc_enable_callback( - struct tc_module *const module, - const enum tc_callback callback_type) -{ - /* Sanity check arguments */ - Assert(module); - - - /* Enable interrupts for this TC module */ - system_interrupt_enable(_tc_interrupt_get_interrupt_vector(_tc_get_inst_index(module->hw))); - - /* Enable callback */ - if (callback_type == TC_CALLBACK_CC_CHANNEL0) { - module->enable_callback_mask |= TC_INTFLAG_MC(1); - module->hw->COUNT8.INTENSET.reg = TC_INTFLAG_MC(1); - } - else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { - module->enable_callback_mask |= TC_INTFLAG_MC(2); - module->hw->COUNT8.INTENSET.reg = TC_INTFLAG_MC(2); - } - else { - module->enable_callback_mask |= (1 << callback_type); - module->hw->COUNT8.INTENSET.reg = (1 << callback_type); - } -} - -/** - * \brief Disables callback. - * - * Disables the callback function registered by the \ref - * tc_register_callback, and the callback will not be called from the - * interrupt routine. The function will also disable the appropriate - * interrupts. - * - * \param[in] module Pointer to TC software instance struct - * \param[in] callback_type Callback type given by an enum - */ -static inline void tc_disable_callback( - struct tc_module *const module, - const enum tc_callback callback_type){ - /* Sanity check arguments */ - Assert(module); - - /* Disable callback */ - if (callback_type == TC_CALLBACK_CC_CHANNEL0) { - module->hw->COUNT8.INTENCLR.reg = TC_INTFLAG_MC(1); - module->enable_callback_mask &= ~TC_INTFLAG_MC(1); - } - else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { - module->hw->COUNT8.INTENCLR.reg = TC_INTFLAG_MC(2); - module->enable_callback_mask &= ~TC_INTFLAG_MC(2); - } - else { - module->hw->COUNT8.INTENCLR.reg = (1 << callback_type); - module->enable_callback_mask &= ~(1 << callback_type); - } -} - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* TC_INTERRUPT_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/wdt.c b/feather_sensor_transmit/libraries/Adafruit_ASFcore/wdt.c deleted file mode 100644 index c5b0895..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/wdt.c +++ /dev/null @@ -1,264 +0,0 @@ -/** - * \file - * - * \brief SAM Watchdog Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#include "wdt.h" -#include - -/** - * \brief Sets up the WDT hardware module based on the configuration. - * - * Writes a given configuration of a WDT configuration to the - * hardware module, and initializes the internal device struct. - * - * \param[in] config Pointer to the configuration struct - * - * \return Status of the configuration procedure. - * - * \retval STATUS_OK If the module was configured correctly - * \retval STATUS_ERR_INVALID_ARG If invalid argument(s) were supplied - * \retval STATUS_ERR_IO If the Watchdog module is locked to be always on - */ -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) -enum status_code wdt_set_config( - const struct wdt_conf *const config) -{ - /* Sanity check arguments */ - Assert(config); - - Wdt *const WDT_module = WDT; - - /* Turn on the digital interface clock */ - system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBA, MCLK_APBAMASK_WDT); - - /* Check of the Watchdog has been locked to be always on, if so, abort */ - if (wdt_is_locked()) { - return STATUS_ERR_IO; - } - - /* Check for an invalid timeout period, abort if found */ - if (config->timeout_period == WDT_PERIOD_NONE) { - return STATUS_ERR_INVALID_ARG; - } - - /* Make sure the Window and Early Warning periods are not more than the - * reset period, abort if either is invalid */ - if ((config->timeout_period < config->window_period) || - (config->timeout_period < config->early_warning_period)) { - return STATUS_ERR_INVALID_ARG; - } - - /* Disable the Watchdog module */ - WDT_module->CTRLA.reg &= ~WDT_CTRLA_ENABLE; - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - if(config->enable == false) { - return STATUS_OK; - } - - uint32_t new_config = 0; - - /* Update the timeout period value with the requested period */ - new_config |= (config->timeout_period - 1) << WDT_CONFIG_PER_Pos; - - /* Check if the user has requested a reset window period */ - if (config->window_period != WDT_PERIOD_NONE) { - WDT_module->CTRLA.reg |= WDT_CTRLA_WEN; - - /* Update and enable the timeout period value */ - new_config |= (config->window_period - 1) << WDT_CONFIG_WINDOW_Pos; - } else { - /* Ensure the window enable control flag is cleared */ - WDT_module->CTRLA.reg &= ~WDT_CTRLA_WEN; - } - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - /* Write the new Watchdog configuration */ - WDT_module->CONFIG.reg = new_config; - - /* Check if the user has requested an early warning period */ - if (config->early_warning_period != WDT_PERIOD_NONE) { - /* Set the Early Warning period */ - WDT_module->EWCTRL.reg - = (config->early_warning_period - 1) << WDT_EWCTRL_EWOFFSET_Pos; - } - - /* Either enable or lock-enable the Watchdog timer depending on the user - * settings */ - if (config->always_on) { - WDT_module->CTRLA.reg |= WDT_CTRLA_ALWAYSON; - } else { - WDT_module->CTRLA.reg |= WDT_CTRLA_ENABLE; - } - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - return STATUS_OK; -} -#else -enum status_code wdt_set_config( - const struct wdt_conf *const config) -{ - /* Sanity check arguments */ - Assert(config); - - Wdt *const WDT_module = WDT; - - /* Turn on the digital interface clock */ - system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBA, PM_APBAMASK_WDT); - - /* Check of the Watchdog has been locked to be always on, if so, abort */ - if (wdt_is_locked()) { - return STATUS_ERR_IO; - } - - /* Check for an invalid timeout period, abort if found */ - if (config->timeout_period == WDT_PERIOD_NONE) { - return STATUS_ERR_INVALID_ARG; - } - - /* Make sure the Window and Early Warning periods are not more than the - * reset period, abort if either is invalid */ - if ((config->timeout_period < config->window_period) || - (config->timeout_period < config->early_warning_period)) { - return STATUS_ERR_INVALID_ARG; - } - - /* Disable the Watchdog module */ - WDT_module->CTRL.reg &= ~WDT_CTRL_ENABLE; - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - if(config->enable == false) { - return STATUS_OK; - } - - /* Configure GCLK channel and enable clock */ - struct system_gclk_chan_config gclk_chan_conf; - gclk_chan_conf.source_generator = config->clock_source; - system_gclk_chan_set_config(WDT_GCLK_ID, &gclk_chan_conf); - system_gclk_chan_enable(WDT_GCLK_ID); - if (config->always_on) { - system_gclk_chan_lock(WDT_GCLK_ID); - } - - uint32_t new_config = 0; - - /* Update the timeout period value with the requested period */ - new_config |= (config->timeout_period - 1) << WDT_CONFIG_PER_Pos; - - /* Check if the user has requested a reset window period */ - if (config->window_period != WDT_PERIOD_NONE) { - WDT_module->CTRL.reg |= WDT_CTRL_WEN; - - /* Update and enable the timeout period value */ - new_config |= (config->window_period - 1) << WDT_CONFIG_WINDOW_Pos; - } else { - /* Ensure the window enable control flag is cleared */ - WDT_module->CTRL.reg &= ~WDT_CTRL_WEN; - } - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - /* Write the new Watchdog configuration */ - WDT_module->CONFIG.reg = new_config; - - /* Check if the user has requested an early warning period */ - if (config->early_warning_period != WDT_PERIOD_NONE) { - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - /* Set the Early Warning period */ - WDT_module->EWCTRL.reg - = (config->early_warning_period - 1) << WDT_EWCTRL_EWOFFSET_Pos; - } - - /* Either enable or lock-enable the Watchdog timer depending on the user - * settings */ - if (config->always_on) { - WDT_module->CTRL.reg |= WDT_CTRL_ALWAYSON; - } else { - WDT_module->CTRL.reg |= WDT_CTRL_ENABLE; - } - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - return STATUS_OK; -} -#endif - -/** - * \brief Resets the count of the running Watchdog Timer that was previously enabled. - * - * Resets the current count of the Watchdog Timer, restarting the timeout - * period count elapsed. This function should be called after the window - * period (if one was set in the module configuration) but before the timeout - * period to prevent a reset of the system. - */ -void wdt_reset_count(void) -{ - Wdt *const WDT_module = WDT; - - /* Disable the Watchdog module */ - WDT_module->CLEAR.reg = WDT_CLEAR_CLEAR_KEY; - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } -} diff --git a/feather_sensor_transmit/libraries/Adafruit_ASFcore/wdt.h b/feather_sensor_transmit/libraries/Adafruit_ASFcore/wdt.h deleted file mode 100644 index c4c37cf..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_ASFcore/wdt.h +++ /dev/null @@ -1,501 +0,0 @@ -/** - * \file - * - * \brief SAM Watchdog Driver - * - * Copyright (c) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef WDT_H_INCLUDED -#define WDT_H_INCLUDED - -/** - * \defgroup asfdoc_sam0_wdt_group SAM Watchdog Driver (WDT) - * - * This driver for Atmel® | SMART SAM devices provides an interface for the configuration - * and management of the device's Watchdog Timer module, including the enabling, - * disabling, and kicking within the device. The following driver API modes are - * covered by this manual: - * - * - Polled APIs - * \if WDT_CALLBACK_MODE - * - Callback APIs - * \endif - * - * The following peripherals are used by this module: - * - WDT (Watchdog Timer) - * - * The following devices can use this module: - * - Atmel | SMART SAM D20/D21 - * - Atmel | SMART SAM R21 - * - Atmel | SMART SAM D09/D10/D11 - * - Atmel | SMART SAM L21/L22 - * - Atmel | SMART SAM DA1 - * - Atmel | SMART SAM C20/C21 - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_wdt_prerequisites - * - \ref asfdoc_sam0_wdt_module_overview - * - \ref asfdoc_sam0_wdt_special_considerations - * - \ref asfdoc_sam0_wdt_extra_info - * - \ref asfdoc_sam0_wdt_examples - * - \ref asfdoc_sam0_wdt_api_overview - * - * - * \section asfdoc_sam0_wdt_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * - * \section asfdoc_sam0_wdt_module_overview Module Overview - * - * The Watchdog module (WDT) is designed to give an added level of safety in - * critical systems, to ensure a system reset is triggered in the case of a - * deadlock or other software malfunction that prevents normal device operation. - * - * At a basic level, the Watchdog is a system timer with a fixed period; once - * enabled, it will continue to count ticks of its asynchronous clock until - * it is periodically reset, or the timeout period is reached. In the event of a - * Watchdog timeout, the module will trigger a system reset identical to a pulse - * of the device's reset pin, resetting all peripherals to their power-on - * default states and restarting the application software from the reset vector. - * - * In many systems, there is an obvious upper bound to the amount of time each - * iteration of the main application loop can be expected to run, before a - * malfunction can be assumed (either due to a deadlock waiting on hardware or - * software, or due to other means). When the Watchdog is configured with a - * timeout period equal to this upper bound, a malfunction in the system will - * force a full system reset to allow for a graceful recovery. - * - * \subsection asfdoc_sam0_wdt_module_locked_mode Locked Mode - * The Watchdog configuration can be set in the device fuses and locked in - * hardware, so that no software changes can be made to the Watchdog - * configuration. Additionally, the Watchdog can be locked on in software if it - * is not already locked, so that the module configuration cannot be modified - * until a power on reset of the device. - * - * The locked configuration can be used to ensure that faulty software does not - * cause the Watchdog configuration to be changed, preserving the level of - * safety given by the module. - * - * \subsection asfdoc_sam0_wdt_module_window_mode Window Mode - * Just as there is a reasonable upper bound to the time the main program loop - * should take for each iteration, there is also in many applications a lower - * bound, i.e. a \a minimum time for which each loop iteration should run for - * under normal circumstances. To guard against a system failure resetting the - * Watchdog in a tight loop (or a failure in the system application causing the - * main loop to run faster than expected) a "Window" mode can be enabled to - * disallow resetting of the Watchdog counter before a certain period of time. - * If the Watchdog is not reset \a after the window opens but not \a before the - * Watchdog expires, the system will reset. - * - * \subsection asfdoc_sam0_wdt_module_early_warning Early Warning - * In some cases it is desirable to receive an early warning that the Watchdog is - * about to expire, so that some system action (such as saving any system - * configuration data for failure analysis purposes) can be performed before the - * system reset occurs. The Early Warning feature of the Watchdog module allows - * such a notification to be requested; after the configured early warning time - * (but before the expiry of the Watchdog counter) the Early Warning flag will - * become set, so that the user application can take an appropriate action. - * - * \note It is important to note that the purpose of the Early Warning feature - * is \a not to allow the user application to reset the Watchdog; doing - * so will defeat the safety the module gives to the user application. - * Instead, this feature should be used purely to perform any tasks that - * need to be undertaken before the system reset occurs. - * - * \subsection asfdoc_sam0_wdt_module_overview_physical Physical Connection - * - * \ref asfdoc_sam0_wdt_module_int_connections "The figure below" shows how - * this module is interconnected within the device. - * - * \anchor asfdoc_sam0_wdt_module_int_connections - * \dot - * digraph overview { - * rankdir=LR; - * node [label="GCLK*\nGeneric Clock" shape=square] wdt_clock; - * - * subgraph driver { - * node [label=" WDT | Watchdog Counter" shape=record] wdt_module; - * node [label="System Reset Logic" shape=ellipse style=filled fillcolor=lightgray] sys_reset; - * } - * - * wdt_clock -> wdt_module:f1; - * wdt_module:f1 -> sys_reset; - * } - * \enddot - * - * \note Watchdog Counter of SAM L21/L22 is \a not provided by GCLK, but it uses an - * internal 1KHz OSCULP32K output clock. - * - * \section asfdoc_sam0_wdt_special_considerations Special Considerations - * - * On some devices the Watchdog configuration can be fused to be always on in - * a particular configuration; if this mode is enabled the Watchdog is not - * software configurable and can have its count reset and early warning state - * checked/cleared only. - * - * \section asfdoc_sam0_wdt_extra_info Extra Information - * - * For extra information, see \ref asfdoc_sam0_wdt_extra. This includes: - * - \ref asfdoc_sam0_wdt_extra_acronyms - * - \ref asfdoc_sam0_wdt_extra_dependencies - * - \ref asfdoc_sam0_wdt_extra_errata - * - \ref asfdoc_sam0_wdt_extra_history - * - * - * \section asfdoc_sam0_wdt_examples Examples - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_wdt_exqsg. - * - * \section asfdoc_sam0_wdt_api_overview API Overview - * @{ - */ - -#include -#include -#include - -#if WDT_CALLBACK_MODE == true -# include "wdt_callback.h" -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief Watchdog Timer period configuration enum. - * - * Enum for the possible period settings of the Watchdog timer module, for - * values requiring a period as a number of Watchdog timer clock ticks. - */ -enum wdt_period { - /** No Watchdog period. This value can only be used when setting the - * Window and Early Warning periods; its use as the Watchdog Reset - * Period is invalid. */ - WDT_PERIOD_NONE = 0, - /** Watchdog period of 8 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_8CLK = 1, - /** Watchdog period of 16 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_16CLK = 2, - /** Watchdog period of 32 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_32CLK = 3, - /** Watchdog period of 64 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_64CLK = 4, - /** Watchdog period of 128 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_128CLK = 5, - /** Watchdog period of 256 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_256CLK = 6, - /** Watchdog period of 512 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_512CLK = 7, - /** Watchdog period of 1024 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_1024CLK = 8, - /** Watchdog period of 2048 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_2048CLK = 9, - /** Watchdog period of 4096 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_4096CLK = 10, - /** Watchdog period of 8192 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_8192CLK = 11, - /** Watchdog period of 16384 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_16384CLK = 12, -}; - -/** - * \brief Watchdog Timer configuration structure. - * - * Configuration structure for a Watchdog Timer instance. This - * structure should be initialized by the \ref wdt_get_config_defaults() - * function before being modified by the user application. - */ -struct wdt_conf { - /** If \c true, the Watchdog will be locked to the current configuration - * settings when the Watchdog is enabled. */ - bool always_on; - /** Enable/Disable the Watchdog Timer. */ - bool enable; -#if !(SAML21) && !(SAML22) && !(SAMC20) && !(SAMC21) - /** GCLK generator used to clock the peripheral except SAM L21/L22/C21/C20.*/ - enum gclk_generator clock_source; -#endif - /** Number of Watchdog timer clock ticks until the Watchdog expires. */ - enum wdt_period timeout_period; - /** Number of Watchdog timer clock ticks until the reset window opens. */ - enum wdt_period window_period; - /** Number of Watchdog timer clock ticks until the early warning flag is - * set. */ - enum wdt_period early_warning_period; -}; - -/** \name Configuration and Initialization - * @{ - */ - -/** - * \brief Determines if the hardware module(s) are currently synchronizing to the bus. - * - * Checks to see if the underlying hardware peripheral module(s) are currently - * synchronizing across multiple clock domains to the hardware bus. This - * function can be used to delay further operations on a module until such time - * that it is ready, to prevent blocking delays for synchronization in the - * user application. - * - * \return Synchronization status of the underlying hardware module(s). - * - * \retval false If the module has completed synchronization - * \retval true If the module synchronization is ongoing - */ -static inline bool wdt_is_syncing(void) -{ - Wdt *const WDT_module = WDT; - -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) - if (WDT_module->SYNCBUSY.reg) { -#else - if (WDT_module->STATUS.reg & WDT_STATUS_SYNCBUSY) { -#endif - return true; - } - - return false; -} - -/** - * \brief Initializes a Watchdog Timer configuration structure to defaults. - * - * Initializes a given Watchdog Timer configuration structure to a set of - * known default values. This function should be called on all new - * instances of these configuration structures before being modified by the - * user application. - * - * The default configuration is as follows: - * \li Not locked, to allow for further (re-)configuration - * \li Enable WDT - * \li Watchdog timer sourced from Generic Clock Channel 4 - * \li A timeout period of 16384 clocks of the Watchdog module clock - * \li No window period, so that the Watchdog count can be reset at any time - * \li No early warning period to indicate the Watchdog will soon expire - * - * \param[out] config Configuration structure to initialize to default values - */ -static inline void wdt_get_config_defaults( - struct wdt_conf *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Default configuration values */ - config->always_on = false; - config->enable = true; -#if !(SAML21) && !(SAML22) && !(SAMC20) && !(SAMC21) - config->clock_source = GCLK_GENERATOR_4; -#endif - config->timeout_period = WDT_PERIOD_16384CLK; - config->window_period = WDT_PERIOD_NONE; - config->early_warning_period = WDT_PERIOD_NONE; -} - -enum status_code wdt_set_config( - const struct wdt_conf *const config); - -/** \brief Determines if the Watchdog timer is currently locked in an enabled state. - * - * Determines if the Watchdog timer is currently enabled and locked, so that - * it cannot be disabled or otherwise reconfigured. - * - * \return Current Watchdog lock state. - */ -static inline bool wdt_is_locked(void) -{ - Wdt *const WDT_module = WDT; - -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) - return (WDT_module->CTRLA.reg & WDT_CTRLA_ALWAYSON); -#else - return (WDT_module->CTRL.reg & WDT_CTRL_ALWAYSON); -#endif -} - -/** @} */ - -/** \name Timeout and Early Warning Management - * @{ - */ - -/** \brief Clears the Watchdog timer early warning period elapsed flag. - * - * Clears the Watchdog timer early warning period elapsed flag, so that a new - * early warning period can be detected. - */ -static inline void wdt_clear_early_warning(void) -{ - Wdt *const WDT_module = WDT; - - WDT_module->INTFLAG.reg = WDT_INTFLAG_EW; -} - -/** \brief Determines if the Watchdog timer early warning period has elapsed. - * - * Determines if the Watchdog timer early warning period has elapsed. - * - * \note If no early warning period was configured, the value returned by this - * function is invalid. - * - * \return Current Watchdog Early Warning state. - */ -static inline bool wdt_is_early_warning(void) -{ - Wdt *const WDT_module = WDT; - - return (WDT_module->INTFLAG.reg & WDT_INTFLAG_EW); -} - -void wdt_reset_count(void); - -/** @} */ - -#ifdef __cplusplus -} -#endif - -/** @} */ - -/** - * \page asfdoc_sam0_wdt_extra Extra Information for WDT Driver - * - * \section asfdoc_sam0_wdt_extra_acronyms Acronyms - * The table below presents the acronyms used in this module: - * - * - * - * - * - * - * - * - * - * - *
AcronymDescription
WDTWatchdog Timer
- * - * - * \section asfdoc_sam0_wdt_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - \ref asfdoc_sam0_system_clock_group "System Clock Driver" - * - * - * \section asfdoc_sam0_wdt_extra_errata Errata - * There are no errata related to this driver. - * - * - * \section asfdoc_sam0_wdt_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * - * - * - * - * - * - *
Changelog
Driver updated to follow driver type convention: - * \li wdt_init, wdt_enable, wdt_disable functions removed - * \li wdt_set_config function added - * \li WDT module enable state moved inside the configuration struct
Initial Release
- */ - -/** - * \page asfdoc_sam0_wdt_exqsg Examples for WDT Driver - * - * This is a list of the available Quick Start guides (QSGs) and example - * applications for \ref asfdoc_sam0_wdt_group. QSGs are simple examples with - * step-by-step instructions to configure and use this driver in a selection of - * use cases. Note that QSGs can be compiled as a standalone application or be - * added to the user application. - * - * - \subpage asfdoc_sam0_wdt_basic_use_case - * \if WDT_CALLBACK_MODE - * - \subpage asfdoc_sam0_wdt_callback_use_case - * \endif - * - * \page asfdoc_sam0_wdt_document_revision_history Document Revision History - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Doc. Rev. - * Date - * Comments - *
E08/2015Added support for SAM L21/L22, SAM DA1, and SAM C20/C2
D12/2014Added SAMR21 and SAMD10/D11 support
C01/2014Add SAMD21 support
B06/2013Corrected documentation typos
A06/2013Initial release
- */ - -#endif /* WDT_H_INCLUDED */ diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp deleted file mode 100644 index fe721be..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp +++ /dev/null @@ -1,2079 +0,0 @@ -/*************************************************** - This is a library for our Adafruit FONA Cellular Module - - Designed specifically to work with the Adafruit FONA - ----> http://www.adafruit.com/products/1946 - ----> http://www.adafruit.com/products/1963 - - These displays use TTL Serial to communicate, 2 pins are required to - interface - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - BSD license, all text above must be included in any redistribution - ****************************************************/ - // next line per http://postwarrior.com/arduino-ethershield-error-prog_char-does-not-name-a-type/ - -#include "Adafruit_FONA.h" - - - - -Adafruit_FONA::Adafruit_FONA(int8_t rst) -{ - _rstpin = rst; - - apn = F("FONAnet"); - apnusername = 0; - apnpassword = 0; - mySerial = 0; - httpsredirect = false; - useragent = F("FONA"); - ok_reply = F("OK"); -} - -uint8_t Adafruit_FONA::type(void) { - return _type; -} - -boolean Adafruit_FONA::begin(Stream &port) { - mySerial = &port; - - pinMode(_rstpin, OUTPUT); - digitalWrite(_rstpin, HIGH); - delay(10); - digitalWrite(_rstpin, LOW); - delay(100); - digitalWrite(_rstpin, HIGH); - - DEBUG_PRINTLN(F("Attempting to open comm with ATs")); - // give 7 seconds to reboot - int16_t timeout = 7000; - - while (timeout > 0) { - while (mySerial->available()) mySerial->read(); - if (sendCheckReply(F("AT"), ok_reply)) - break; - while (mySerial->available()) mySerial->read(); - if (sendCheckReply(F("AT"), F("AT"))) - break; - delay(500); - timeout-=500; - } - -#ifdef ADAFRUIT_FONA_DEBUG - if (timeout <= 0) - DEBUG_PRINTLN(F("Timeout: No response to AT... last ditch attempt.")); -#endif - - sendCheckReply(F("AT"), ok_reply); - delay(100); - sendCheckReply(F("AT"), ok_reply); - delay(100); - sendCheckReply(F("AT"), ok_reply); - delay(100); - - // turn off Echo! - sendCheckReply(F("ATE0"), ok_reply); - delay(100); - - if (! sendCheckReply(F("ATE0"), ok_reply)) { - return false; - } - - // turn on hangupitude - sendCheckReply(F("AT+CVHU=0"), ok_reply); - - delay(100); - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN("ATI"); - - mySerial->println("ATI"); - readline(500, true); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - - - if (prog_char_strstr(replybuffer, (prog_char *)F("SIM808 R14")) != 0) { - _type = FONA808_V2; - } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIM808 R13")) != 0) { - _type = FONA808_V1; - } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIM800 R14")) != 0) { - _type = FONA800L; - } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIMCOM_SIM5320A")) != 0) { - _type = FONA3G_A; - } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIMCOM_SIM5320E")) != 0) { - _type = FONA3G_E; - } - - if (_type == FONA800L) { - // determine if L or H - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN("AT+GMM"); - - mySerial->println("AT+GMM"); - readline(500, true); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - - if (prog_char_strstr(replybuffer, (prog_char *)F("SIM800H")) != 0) { - _type = FONA800H; - } - } - -#if defined(FONA_PREF_SMS_STORAGE) - sendCheckReply(F("AT+CPMS=\"" FONA_PREF_SMS_STORAGE "\""), ok_reply); -#endif - - return true; -} - - -/********* Serial port ********************************************/ -boolean Adafruit_FONA::setBaudrate(uint16_t baud) { - return sendCheckReply(F("AT+IPREX="), baud, ok_reply); -} - -/********* Real Time Clock ********************************************/ - -boolean Adafruit_FONA::readRTC(uint8_t *year, uint8_t *month, uint8_t *date, uint8_t *hr, uint8_t *min, uint8_t *sec) { - uint16_t v; - sendParseReply(F("AT+CCLK?"), F("+CCLK: "), &v, '/', 0); - *year = v; - - DEBUG_PRINTLN(*year); -} - -boolean Adafruit_FONA::enableRTC(uint8_t i) { - if (! sendCheckReply(F("AT+CLTS="), i, ok_reply)) - return false; - return sendCheckReply(F("AT&W"), ok_reply); -} - - -/********* BATTERY & ADC ********************************************/ - -/* returns value in mV (uint16_t) */ -boolean Adafruit_FONA::getBattVoltage(uint16_t *v) { - return sendParseReply(F("AT+CBC"), F("+CBC: "), v, ',', 2); -} - -/* returns value in mV (uint16_t) */ -boolean Adafruit_FONA_3G::getBattVoltage(uint16_t *v) { - float f; - boolean b = sendParseReply(F("AT+CBC"), F("+CBC: "), &f, ',', 2); - *v = f*1000; - return b; -} - - -/* returns the percentage charge of battery as reported by sim800 */ -boolean Adafruit_FONA::getBattPercent(uint16_t *p) { - return sendParseReply(F("AT+CBC"), F("+CBC: "), p, ',', 1); -} - -boolean Adafruit_FONA::getADCVoltage(uint16_t *v) { - return sendParseReply(F("AT+CADC?"), F("+CADC: 1,"), v); -} - -/********* SIM ***********************************************************/ - -uint8_t Adafruit_FONA::unlockSIM(char *pin) -{ - char sendbuff[14] = "AT+CPIN="; - sendbuff[8] = pin[0]; - sendbuff[9] = pin[1]; - sendbuff[10] = pin[2]; - sendbuff[11] = pin[3]; - sendbuff[12] = '\0'; - - return sendCheckReply(sendbuff, ok_reply); -} - -uint8_t Adafruit_FONA::getSIMCCID(char *ccid) { - getReply(F("AT+CCID")); - // up to 28 chars for reply, 20 char total ccid - if (replybuffer[0] == '+') { - // fona 3g? - strncpy(ccid, replybuffer+8, 20); - } else { - // fona 800 or 800 - strncpy(ccid, replybuffer, 20); - } - ccid[20] = 0; - - readline(); // eat 'OK' - - return strlen(ccid); -} - -/********* IMEI **********************************************************/ - -uint8_t Adafruit_FONA::getIMEI(char *imei) { - getReply(F("AT+GSN")); - - // up to 15 chars - strncpy(imei, replybuffer, 15); - imei[15] = 0; - - readline(); // eat 'OK' - - return strlen(imei); -} - -/********* NETWORK *******************************************************/ - -uint8_t Adafruit_FONA::getNetworkStatus(void) { - uint16_t status; - - if (! sendParseReply(F("AT+CREG?"), F("+CREG: "), &status, ',', 1)) return 0; - - return status; -} - - -uint8_t Adafruit_FONA::getRSSI(void) { - uint16_t reply; - - if (! sendParseReply(F("AT+CSQ"), F("+CSQ: "), &reply) ) return 0; - - return reply; -} - -/********* AUDIO *******************************************************/ - -boolean Adafruit_FONA::setAudio(uint8_t a) { - // 0 is headset, 1 is external audio - if (a > 1) return false; - - return sendCheckReply(F("AT+CHFA="), a, ok_reply); -} - -uint8_t Adafruit_FONA::getVolume(void) { - uint16_t reply; - - if (! sendParseReply(F("AT+CLVL?"), F("+CLVL: "), &reply) ) return 0; - - return reply; -} - -boolean Adafruit_FONA::setVolume(uint8_t i) { - return sendCheckReply(F("AT+CLVL="), i, ok_reply); -} - - -boolean Adafruit_FONA::playDTMF(char dtmf) { - char str[4]; - str[0] = '\"'; - str[1] = dtmf; - str[2] = '\"'; - str[3] = 0; - return sendCheckReply(F("AT+CLDTMF=3,"), str, ok_reply); -} - -boolean Adafruit_FONA::playToolkitTone(uint8_t t, uint16_t len) { - return sendCheckReply(F("AT+STTONE=1,"), t, len, ok_reply); -} - -boolean Adafruit_FONA_3G::playToolkitTone(uint8_t t, uint16_t len) { - if (! sendCheckReply(F("AT+CPTONE="), t, ok_reply)) - return false; - delay(len); - return sendCheckReply(F("AT+CPTONE=0"), ok_reply); -} - -boolean Adafruit_FONA::setMicVolume(uint8_t a, uint8_t level) { - // 0 is headset, 1 is external audio - if (a > 1) return false; - - return sendCheckReply(F("AT+CMIC="), a, level, ok_reply); -} - -/********* FM RADIO *******************************************************/ - - -boolean Adafruit_FONA::FMradio(boolean onoff, uint8_t a) { - if (! onoff) { - return sendCheckReply(F("AT+FMCLOSE"), ok_reply); - } - - // 0 is headset, 1 is external audio - if (a > 1) return false; - - return sendCheckReply(F("AT+FMOPEN="), a, ok_reply); -} - -boolean Adafruit_FONA::tuneFMradio(uint16_t station) { - // Fail if FM station is outside allowed range. - if ((station < 870) || (station > 1090)) - return false; - - return sendCheckReply(F("AT+FMFREQ="), station, ok_reply); -} - -boolean Adafruit_FONA::setFMVolume(uint8_t i) { - // Fail if volume is outside allowed range (0-6). - if (i > 6) { - return false; - } - // Send FM volume command and verify response. - return sendCheckReply(F("AT+FMVOLUME="), i, ok_reply); -} - -int8_t Adafruit_FONA::getFMVolume() { - uint16_t level; - - if (! sendParseReply(F("AT+FMVOLUME?"), F("+FMVOLUME: "), &level) ) return 0; - - return level; -} - -int8_t Adafruit_FONA::getFMSignalLevel(uint16_t station) { - // Fail if FM station is outside allowed range. - if ((station < 875) || (station > 1080)) { - return -1; - } - - // Send FM signal level query command. - // Note, need to explicitly send timeout so right overload is chosen. - getReply(F("AT+FMSIGNAL="), station, FONA_DEFAULT_TIMEOUT_MS); - // Check response starts with expected value. - char *p = prog_char_strstr(replybuffer, PSTR("+FMSIGNAL: ")); - if (p == 0) return -1; - p+=11; - // Find second colon to get start of signal quality. - p = strchr(p, ':'); - if (p == 0) return -1; - p+=1; - // Parse signal quality. - int8_t level = atoi(p); - readline(); // eat the "OK" - return level; -} - -/********* PWM/BUZZER **************************************************/ - -boolean Adafruit_FONA::setPWM(uint16_t period, uint8_t duty) { - if (period > 2000) return false; - if (duty > 100) return false; - - return sendCheckReply(F("AT+SPWM=0,"), period, duty, ok_reply); -} - -/********* CALL PHONES **************************************************/ -boolean Adafruit_FONA::callPhone(char *number) { - char sendbuff[35] = "ATD"; - strncpy(sendbuff+3, number, min(30, strlen(number))); - uint8_t x = strlen(sendbuff); - sendbuff[x] = ';'; - sendbuff[x+1] = 0; - //DEBUG_PRINTLN(sendbuff); - - return sendCheckReply(sendbuff, ok_reply); -} - - -uint8_t Adafruit_FONA::getCallStatus(void) { - uint16_t phoneStatus; - - if (! sendParseReply(F("AT+CPAS"), F("+CPAS: "), &phoneStatus)) - return FONA_CALL_FAILED; // 1, since 0 is actually a known, good reply - - return phoneStatus; // 0 ready, 2 unkown, 3 ringing, 4 call in progress -} - -boolean Adafruit_FONA::hangUp(void) { - return sendCheckReply(F("ATH0"), ok_reply); -} - -boolean Adafruit_FONA_3G::hangUp(void) { - getReply(F("ATH")); - - return (prog_char_strstr(replybuffer, (prog_char *)F("VOICE CALL: END")) != 0); -} - -boolean Adafruit_FONA::pickUp(void) { - return sendCheckReply(F("ATA"), ok_reply); -} - -boolean Adafruit_FONA_3G::pickUp(void) { - return sendCheckReply(F("ATA"), F("VOICE CALL: BEGIN")); -} - - -void Adafruit_FONA::onIncomingCall() { - - DEBUG_PRINT(F("> ")); DEBUG_PRINTLN(F("Incoming call...")); - - Adafruit_FONA::_incomingCall = true; -} - -boolean Adafruit_FONA::_incomingCall = false; - -boolean Adafruit_FONA::callerIdNotification(boolean enable, uint8_t interrupt) { - if(enable){ - attachInterrupt(interrupt, onIncomingCall, FALLING); - return sendCheckReply(F("AT+CLIP=1"), ok_reply); - } - - detachInterrupt(interrupt); - return sendCheckReply(F("AT+CLIP=0"), ok_reply); -} - -boolean Adafruit_FONA::incomingCallNumber(char* phonenum) { - //+CLIP: "",145,"",0,"",0 - if(!Adafruit_FONA::_incomingCall) - return false; - - readline(); - while(!prog_char_strcmp(replybuffer, (prog_char*)F("RING")) == 0) { - flushInput(); - readline(); - } - - readline(); //reads incoming phone number line - - parseReply(F("+CLIP: \""), phonenum, '"'); - - - DEBUG_PRINT(F("Phone Number: ")); - DEBUG_PRINTLN(replybuffer); - - - Adafruit_FONA::_incomingCall = false; - return true; -} - -/********* SMS **********************************************************/ - -uint8_t Adafruit_FONA::getSMSInterrupt(void) { - uint16_t reply; - - if (! sendParseReply(F("AT+CFGRI?"), F("+CFGRI: "), &reply) ) return 0; - - return reply; -} - -boolean Adafruit_FONA::setSMSInterrupt(uint8_t i) { - return sendCheckReply(F("AT+CFGRI="), i, ok_reply); -} - -int8_t Adafruit_FONA::getNumSMS(void) { - uint16_t numsms; - - // get into text mode - if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return -1; - - // ask how many sms are stored - if (sendParseReply(F("AT+CPMS?"), F("\"SM\","), &numsms)) - return numsms; - if (sendParseReply(F("AT+CPMS?"), F("\"SM_P\","), &numsms)) - return numsms; - return -1; -} - -// Reading SMS's is a bit involved so we don't use helpers that may cause delays or debug -// printouts! -boolean Adafruit_FONA::readSMS(uint8_t i, char *smsbuff, - uint16_t maxlen, uint16_t *readlen) { - // text mode - if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return false; - - // show all text mode parameters - if (! sendCheckReply(F("AT+CSDH=1"), ok_reply)) return false; - - // parse out the SMS len - uint16_t thesmslen = 0; - - - DEBUG_PRINT(F("AT+CMGR=")); - DEBUG_PRINTLN(i); - - - //getReply(F("AT+CMGR="), i, 1000); // do not print debug! - mySerial->print(F("AT+CMGR=")); - mySerial->println(i); - readline(1000); // timeout - - //DEBUG_PRINT(F("Reply: ")); DEBUG_PRINTLN(replybuffer); - // parse it out... - - - DEBUG_PRINTLN(replybuffer); - - - if (! parseReply(F("+CMGR:"), &thesmslen, ',', 11)) { - *readlen = 0; - return false; - } - - readRaw(thesmslen); - - flushInput(); - - uint16_t thelen = min(maxlen, strlen(replybuffer)); - strncpy(smsbuff, replybuffer, thelen); - smsbuff[thelen] = 0; // end the string - - - DEBUG_PRINTLN(replybuffer); - - *readlen = thelen; - return true; -} - -// Retrieve the sender of the specified SMS message and copy it as a string to -// the sender buffer. Up to senderlen characters of the sender will be copied -// and a null terminator will be added if less than senderlen charactesr are -// copied to the result. Returns true if a result was successfully retrieved, -// otherwise false. -boolean Adafruit_FONA::getSMSSender(uint8_t i, char *sender, int senderlen) { - // Ensure text mode and all text mode parameters are sent. - if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return false; - if (! sendCheckReply(F("AT+CSDH=1"), ok_reply)) return false; - - - DEBUG_PRINT(F("AT+CMGR=")); - DEBUG_PRINTLN(i); - - - // Send command to retrieve SMS message and parse a line of response. - mySerial->print(F("AT+CMGR=")); - mySerial->println(i); - readline(1000); - - - DEBUG_PRINTLN(replybuffer); - - - // Parse the second field in the response. - boolean result = parseReplyQuoted(F("+CMGR:"), sender, senderlen, ',', 1); - // Drop any remaining data from the response. - flushInput(); - return result; -} - -boolean Adafruit_FONA::sendSMS(char *smsaddr, char *smsmsg) { - if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return -1; - - char sendcmd[30] = "AT+CMGS=\""; - strncpy(sendcmd+9, smsaddr, 30-9-2); // 9 bytes beginning, 2 bytes for close quote + null - sendcmd[strlen(sendcmd)] = '\"'; - - if (! sendCheckReply(sendcmd, F("> "))) return false; - - DEBUG_PRINT(F("> ")); DEBUG_PRINTLN(smsmsg); - - mySerial->println(smsmsg); - mySerial->println(); - mySerial->write(0x1A); - - DEBUG_PRINTLN("^Z"); - - if ( (_type == FONA3G_A) || (_type == FONA3G_E) ) { - // Eat two sets of CRLF - readline(200); - //DEBUG_PRINT("Line 1: "); DEBUG_PRINTLN(strlen(replybuffer)); - readline(200); - //DEBUG_PRINT("Line 2: "); DEBUG_PRINTLN(strlen(replybuffer)); - } - readline(10000); // read the +CMGS reply, wait up to 10 seconds!!! - //DEBUG_PRINT("Line 3: "); DEBUG_PRINTLN(strlen(replybuffer)); - if (strstr(replybuffer, "+CMGS") == 0) { - return false; - } - readline(1000); // read OK - //DEBUG_PRINT("* "); DEBUG_PRINTLN(replybuffer); - - if (strcmp(replybuffer, "OK") != 0) { - return false; - } - - return true; -} - - -boolean Adafruit_FONA::deleteSMS(uint8_t i) { - if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return -1; - // read an sms - char sendbuff[12] = "AT+CMGD=000"; - sendbuff[8] = (i / 100) + '0'; - i %= 100; - sendbuff[9] = (i / 10) + '0'; - i %= 10; - sendbuff[10] = i + '0'; - - return sendCheckReply(sendbuff, ok_reply, 2000); -} - -/********* USSD *********************************************************/ - -boolean Adafruit_FONA::sendUSSD(char *ussdmsg, char *ussdbuff, uint16_t maxlen, uint16_t *readlen) { - if (! sendCheckReply(F("AT+CUSD=1"), ok_reply)) return -1; - - char sendcmd[30] = "AT+CUSD=1,\""; - strncpy(sendcmd+11, ussdmsg, 30-11-2); // 11 bytes beginning, 2 bytes for close quote + null - sendcmd[strlen(sendcmd)] = '\"'; - - if (! sendCheckReply(sendcmd, ok_reply)) { - *readlen = 0; - return false; - } else { - readline(10000); // read the +CUSD reply, wait up to 10 seconds!!! - //DEBUG_PRINT("* "); DEBUG_PRINTLN(replybuffer); - char *p = prog_char_strstr(replybuffer, PSTR("+CUSD: ")); - if (p == 0) { - *readlen = 0; - return false; - } - p+=7; //+CUSD - // Find " to get start of ussd message. - p = strchr(p, '\"'); - if (p == 0) { - *readlen = 0; - return false; - } - p+=1; //" - // Find " to get end of ussd message. - char *strend = strchr(p, '\"'); - - uint16_t lentocopy = min(maxlen-1, strend - p); - strncpy(ussdbuff, p, lentocopy+1); - ussdbuff[lentocopy] = 0; - *readlen = lentocopy; - } - return true; -} - - -/********* TIME **********************************************************/ - -boolean Adafruit_FONA::enableNetworkTimeSync(boolean onoff) { - if (onoff) { - if (! sendCheckReply(F("AT+CLTS=1"), ok_reply)) - return false; - } else { - if (! sendCheckReply(F("AT+CLTS=0"), ok_reply)) - return false; - } - - flushInput(); // eat any 'Unsolicted Result Code' - - return true; -} - -boolean Adafruit_FONA::enableNTPTimeSync(boolean onoff, FONAFlashStringPtr ntpserver) { - if (onoff) { - if (! sendCheckReply(F("AT+CNTPCID=1"), ok_reply)) - return false; - - mySerial->print(F("AT+CNTP=\"")); - if (ntpserver != 0) { - mySerial->print(ntpserver); - } else { - mySerial->print(F("pool.ntp.org")); - } - mySerial->println(F("\",0")); - readline(FONA_DEFAULT_TIMEOUT_MS); - if (strcmp(replybuffer, "OK") != 0) - return false; - - if (! sendCheckReply(F("AT+CNTP"), ok_reply, 10000)) - return false; - - uint16_t status; - readline(10000); - if (! parseReply(F("+CNTP:"), &status)) - return false; - } else { - if (! sendCheckReply(F("AT+CNTPCID=0"), ok_reply)) - return false; - } - - return true; -} - -boolean Adafruit_FONA::getTime(char *buff, uint16_t maxlen) { - getReply(F("AT+CCLK?"), (uint16_t) 10000); - if (strncmp(replybuffer, "+CCLK: ", 7) != 0) - return false; - - char *p = replybuffer+7; - uint16_t lentocopy = min(maxlen-1, strlen(p)); - strncpy(buff, p, lentocopy+1); - buff[lentocopy] = 0; - - readline(); // eat OK - - return true; -} - -/********* GPS **********************************************************/ - - -boolean Adafruit_FONA::enableGPS(boolean onoff) { - uint16_t state; - - // first check if its already on or off - - if (_type == FONA808_V2) { - if (! sendParseReply(F("AT+CGNSPWR?"), F("+CGNSPWR: "), &state) ) - return false; - } else { - if (! sendParseReply(F("AT+CGPSPWR?"), F("+CGPSPWR: "), &state)) - return false; - } - - if (onoff && !state) { - if (_type == FONA808_V2) { - if (! sendCheckReply(F("AT+CGNSPWR=1"), ok_reply)) // try GNS command - return false; - } else { - if (! sendCheckReply(F("AT+CGPSPWR=1"), ok_reply)) - return false; - } - } else if (!onoff && state) { - if (_type == FONA808_V2) { - if (! sendCheckReply(F("AT+CGNSPWR=0"), ok_reply)) // try GNS command - return false; - } else { - if (! sendCheckReply(F("AT+CGPSPWR=0"), ok_reply)) - return false; - } - } - return true; -} - - - -boolean Adafruit_FONA_3G::enableGPS(boolean onoff) { - uint16_t state; - - // first check if its already on or off - if (! Adafruit_FONA::sendParseReply(F("AT+CGPS?"), F("+CGPS: "), &state) ) - return false; - - if (onoff && !state) { - if (! sendCheckReply(F("AT+CGPS=1"), ok_reply)) - return false; - } else if (!onoff && state) { - if (! sendCheckReply(F("AT+CGPS=0"), ok_reply)) - return false; - // this takes a little time - readline(2000); // eat '+CGPS: 0' - } - return true; -} - -int8_t Adafruit_FONA::GPSstatus(void) { - if (_type == FONA808_V2) { - // 808 V2 uses GNS commands and doesn't have an explicit 2D/3D fix status. - // Instead just look for a fix and if found assume it's a 3D fix. - getReply(F("AT+CGNSINF")); - char *p = prog_char_strstr(replybuffer, (prog_char*)F("+CGNSINF: ")); - if (p == 0) return -1; - p+=12; // Skip to second value, fix status. - readline(); // eat 'OK' - //DEBUG_PRINTLN(p); - // Assume if the fix status is '1' then we have a 3D fix, otherwise no fix. - if (p[0] == '1') return 3; - else return 0; - } - if (_type == FONA3G_A || _type == FONA3G_E) { - // FONA 3G doesn't have an explicit 2D/3D fix status. - // Instead just look for a fix and if found assume it's a 3D fix. - getReply(F("AT+CGPSINFO")); - char *p = prog_char_strstr(replybuffer, (prog_char*)F("+CGPSINFO:")); - if (p == 0) return -1; - if (p[10] != ',') return 3; // if you get anything, its 3D fix - return 0; - } - else { - // 808 V1 looks for specific 2D or 3D fix state. - getReply(F("AT+CGPSSTATUS?")); - char *p = prog_char_strstr(replybuffer, (prog_char*)F("SSTATUS: Location ")); - if (p == 0) return -1; - p+=18; - readline(); // eat 'OK' - //DEBUG_PRINTLN(p); - if (p[0] == 'U') return 0; - if (p[0] == 'N') return 1; - if (p[0] == '2') return 2; - if (p[0] == '3') return 3; - } - // else - return 0; -} - -uint8_t Adafruit_FONA::getGPS(uint8_t arg, char *buffer, uint8_t maxbuff) { - int32_t x = arg; - - if ( (_type == FONA3G_A) || (_type == FONA3G_E) ) { - getReply(F("AT+CGPSINFO")); - } else if (_type == FONA808_V1) { - getReply(F("AT+CGPSINF="), x); - } else { - getReply(F("AT+CGNSINF")); - } - - char *p = prog_char_strstr(replybuffer, (prog_char*)F("SINF")); - if (p == 0) { - buffer[0] = 0; - return 0; - } - - p+=6; - - uint8_t len = max(maxbuff-1, strlen(p)); - strncpy(buffer, p, len); - buffer[len] = 0; - - readline(); // eat 'OK' - return len; -} - -boolean Adafruit_FONA::getGPS(float *lat, float *lon, float *speed_kph, float *heading, float *altitude) { - - char gpsbuffer[120]; - - // we need at least a 2D fix - if (GPSstatus() < 2) - return false; - - // grab the mode 2^5 gps csv from the sim808 - uint8_t res_len = getGPS(32, gpsbuffer, 120); - - // make sure we have a response - if (res_len == 0) - return false; - - if (_type == FONA3G_A || _type == FONA3G_E) { - // Parse 3G respose - // +CGPSINFO:4043.000000,N,07400.000000,W,151015,203802.1,-12.0,0.0,0 - // skip beginning - char *tok; - - // grab the latitude - char *latp = strtok(gpsbuffer, ","); - if (! latp) return false; - - // grab latitude direction - char *latdir = strtok(NULL, ","); - if (! latdir) return false; - - // grab longitude - char *longp = strtok(NULL, ","); - if (! longp) return false; - - // grab longitude direction - char *longdir = strtok(NULL, ","); - if (! longdir) return false; - - // skip date & time - tok = strtok(NULL, ","); - tok = strtok(NULL, ","); - - // only grab altitude if needed - if (altitude != NULL) { - // grab altitude - char *altp = strtok(NULL, ","); - if (! altp) return false; - *altitude = atof(altp); - } - - // only grab speed if needed - if (speed_kph != NULL) { - // grab the speed in km/h - char *speedp = strtok(NULL, ","); - if (! speedp) return false; - - *speed_kph = atof(speedp); - } - - // only grab heading if needed - if (heading != NULL) { - - // grab the speed in knots - char *coursep = strtok(NULL, ","); - if (! coursep) return false; - - *heading = atof(coursep); - } - - double latitude = atof(latp); - double longitude = atof(longp); - - // convert latitude from minutes to decimal - float degrees = floor(latitude / 100); - double minutes = latitude - (100 * degrees); - minutes /= 60; - degrees += minutes; - - // turn direction into + or - - if (latdir[0] == 'S') degrees *= -1; - - *lat = degrees; - - // convert longitude from minutes to decimal - degrees = floor(longitude / 100); - minutes = longitude - (100 * degrees); - minutes /= 60; - degrees += minutes; - - // turn direction into + or - - if (longdir[0] == 'W') degrees *= -1; - - *lon = degrees; - - } else if (_type == FONA808_V2) { - // Parse 808 V2 response. See table 2-3 from here for format: - // http://www.adafruit.com/datasheets/SIM800%20Series_GNSS_Application%20Note%20V1.00.pdf - - // skip GPS run status - char *tok = strtok(gpsbuffer, ","); - if (! tok) return false; - - // skip fix status - tok = strtok(NULL, ","); - if (! tok) return false; - - // skip date - tok = strtok(NULL, ","); - if (! tok) return false; - - // grab the latitude - char *latp = strtok(NULL, ","); - if (! latp) return false; - - // grab longitude - char *longp = strtok(NULL, ","); - if (! longp) return false; - - *lat = atof(latp); - *lon = atof(longp); - - // only grab altitude if needed - if (altitude != NULL) { - // grab altitude - char *altp = strtok(NULL, ","); - if (! altp) return false; - - *altitude = atof(altp); - } - - // only grab speed if needed - if (speed_kph != NULL) { - // grab the speed in km/h - char *speedp = strtok(NULL, ","); - if (! speedp) return false; - - *speed_kph = atof(speedp); - } - - // only grab heading if needed - if (heading != NULL) { - - // grab the speed in knots - char *coursep = strtok(NULL, ","); - if (! coursep) return false; - - *heading = atof(coursep); - } - } - else { - // Parse 808 V1 response. - - // skip mode - char *tok = strtok(gpsbuffer, ","); - if (! tok) return false; - - // skip date - tok = strtok(NULL, ","); - if (! tok) return false; - - // skip fix - tok = strtok(NULL, ","); - if (! tok) return false; - - // grab the latitude - char *latp = strtok(NULL, ","); - if (! latp) return false; - - // grab latitude direction - char *latdir = strtok(NULL, ","); - if (! latdir) return false; - - // grab longitude - char *longp = strtok(NULL, ","); - if (! longp) return false; - - // grab longitude direction - char *longdir = strtok(NULL, ","); - if (! longdir) return false; - - double latitude = atof(latp); - double longitude = atof(longp); - - // convert latitude from minutes to decimal - float degrees = floor(latitude / 100); - double minutes = latitude - (100 * degrees); - minutes /= 60; - degrees += minutes; - - // turn direction into + or - - if (latdir[0] == 'S') degrees *= -1; - - *lat = degrees; - - // convert longitude from minutes to decimal - degrees = floor(longitude / 100); - minutes = longitude - (100 * degrees); - minutes /= 60; - degrees += minutes; - - // turn direction into + or - - if (longdir[0] == 'W') degrees *= -1; - - *lon = degrees; - - // only grab speed if needed - if (speed_kph != NULL) { - - // grab the speed in knots - char *speedp = strtok(NULL, ","); - if (! speedp) return false; - - // convert to kph - *speed_kph = atof(speedp) * 1.852; - - } - - // only grab heading if needed - if (heading != NULL) { - - // grab the speed in knots - char *coursep = strtok(NULL, ","); - if (! coursep) return false; - - *heading = atof(coursep); - - } - - // no need to continue - if (altitude == NULL) - return true; - - // we need at least a 3D fix for altitude - if (GPSstatus() < 3) - return false; - - // grab the mode 0 gps csv from the sim808 - res_len = getGPS(0, gpsbuffer, 120); - - // make sure we have a response - if (res_len == 0) - return false; - - // skip mode - tok = strtok(gpsbuffer, ","); - if (! tok) return false; - - // skip lat - tok = strtok(NULL, ","); - if (! tok) return false; - - // skip long - tok = strtok(NULL, ","); - if (! tok) return false; - - // grab altitude - char *altp = strtok(NULL, ","); - if (! altp) return false; - - *altitude = atof(altp); - } - - return true; - -} - -boolean Adafruit_FONA::enableGPSNMEA(uint8_t i) { - - char sendbuff[15] = "AT+CGPSOUT=000"; - sendbuff[11] = (i / 100) + '0'; - i %= 100; - sendbuff[12] = (i / 10) + '0'; - i %= 10; - sendbuff[13] = i + '0'; - - if (_type == FONA808_V2) { - if (i) - return sendCheckReply(F("AT+CGNSTST=1"), ok_reply); - else - return sendCheckReply(F("AT+CGNSTST=0"), ok_reply); - } else { - return sendCheckReply(sendbuff, ok_reply, 2000); - } -} - - -/********* GPRS **********************************************************/ - - -boolean Adafruit_FONA::enableGPRS(boolean onoff) { - - if (onoff) { - // disconnect all sockets - sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 20000); - - if (! sendCheckReply(F("AT+CGATT=1"), ok_reply, 10000)) - return false; - - // set bearer profile! connection type GPRS - if (! sendCheckReply(F("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\""), - ok_reply, 10000)) - return false; - - // set bearer profile access point name - if (apn) { - // Send command AT+SAPBR=3,1,"APN","" where is the configured APN value. - if (! sendCheckReplyQuoted(F("AT+SAPBR=3,1,\"APN\","), apn, ok_reply, 10000)) - return false; - - // send AT+CSTT,"apn","user","pass" - flushInput(); - - mySerial->print(F("AT+CSTT=\"")); - mySerial->print(apn); - if (apnusername) { - mySerial->print("\",\""); - mySerial->print(apnusername); - } - if (apnpassword) { - mySerial->print("\",\""); - mySerial->print(apnpassword); - } - mySerial->println("\""); - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(F("AT+CSTT=\"")); - DEBUG_PRINT(apn); - - if (apnusername) { - DEBUG_PRINT("\",\""); - DEBUG_PRINT(apnusername); - } - if (apnpassword) { - DEBUG_PRINT("\",\""); - DEBUG_PRINT(apnpassword); - } - DEBUG_PRINTLN("\""); - - if (! expectReply(ok_reply)) return false; - - // set username/password - if (apnusername) { - // Send command AT+SAPBR=3,1,"USER","" where is the configured APN username. - if (! sendCheckReplyQuoted(F("AT+SAPBR=3,1,\"USER\","), apnusername, ok_reply, 10000)) - return false; - } - if (apnpassword) { - // Send command AT+SAPBR=3,1,"PWD","" where is the configured APN password. - if (! sendCheckReplyQuoted(F("AT+SAPBR=3,1,\"PWD\","), apnpassword, ok_reply, 10000)) - return false; - } - } - - // open GPRS context - if (! sendCheckReply(F("AT+SAPBR=1,1"), ok_reply, 30000)) - return false; - - // bring up wireless connection - if (! sendCheckReply(F("AT+CIICR"), ok_reply, 10000)) - return false; - - } else { - // disconnect all sockets - if (! sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 20000)) - return false; - - // close GPRS context - if (! sendCheckReply(F("AT+SAPBR=0,1"), ok_reply, 10000)) - return false; - - if (! sendCheckReply(F("AT+CGATT=0"), ok_reply, 10000)) - return false; - - } - return true; -} - -boolean Adafruit_FONA_3G::enableGPRS(boolean onoff) { - - if (onoff) { - // disconnect all sockets - //sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 5000); - - if (! sendCheckReply(F("AT+CGATT=1"), ok_reply, 10000)) - return false; - - - // set bearer profile access point name - if (apn) { - // Send command AT+CGSOCKCONT=1,"IP","" where is the configured APN name. - if (! sendCheckReplyQuoted(F("AT+CGSOCKCONT=1,\"IP\","), apn, ok_reply, 10000)) - return false; - - // set username/password - if (apnusername) { - char authstring[100] = "AT+CGAUTH=1,1,\""; - char *strp = authstring + strlen(authstring); - prog_char_strcpy(strp, (prog_char *)apnusername); - strp+=prog_char_strlen((prog_char *)apnusername); - strp[0] = '\"'; - strp++; - strp[0] = 0; - - if (apnpassword) { - strp[0] = ','; strp++; - strp[0] = '\"'; strp++; - prog_char_strcpy(strp, (prog_char *)apnpassword); - strp+=prog_char_strlen((prog_char *)apnpassword); - strp[0] = '\"'; - strp++; - strp[0] = 0; - } - - if (! sendCheckReply(authstring, ok_reply, 10000)) - return false; - } - } - - // connect in transparent - if (! sendCheckReply(F("AT+CIPMODE=1"), ok_reply, 10000)) - return false; - // open network (?) - if (! sendCheckReply(F("AT+NETOPEN=,,1"), F("Network opened"), 10000)) - return false; - - readline(); // eat 'OK' - } else { - // close GPRS context - if (! sendCheckReply(F("AT+NETCLOSE"), F("Network closed"), 10000)) - return false; - - readline(); // eat 'OK' - } - - return true; -} - -uint8_t Adafruit_FONA::GPRSstate(void) { - uint16_t state; - - if (! sendParseReply(F("AT+CGATT?"), F("+CGATT: "), &state) ) - return -1; - - return state; -} - -void Adafruit_FONA::setGPRSNetworkSettings(FONAFlashStringPtr apn, - FONAFlashStringPtr username, FONAFlashStringPtr password) { - this->apn = apn; - this->apnusername = username; - this->apnpassword = password; -} - -boolean Adafruit_FONA::getGSMLoc(uint16_t *errorcode, char *buff, uint16_t maxlen) { - - getReply(F("AT+CIPGSMLOC=1,1"), (uint16_t)10000); - - if (! parseReply(F("+CIPGSMLOC: "), errorcode)) - return false; - - char *p = replybuffer+14; - uint16_t lentocopy = min(maxlen-1, strlen(p)); - strncpy(buff, p, lentocopy+1); - - readline(); // eat OK - - return true; -} - -boolean Adafruit_FONA::getGSMLoc(float *lat, float *lon) { - - uint16_t returncode; - char gpsbuffer[120]; - - // make sure we could get a response - if (! getGSMLoc(&returncode, gpsbuffer, 120)) - return false; - - // make sure we have a valid return code - if (returncode != 0) - return false; - - // +CIPGSMLOC: 0,-74.007729,40.730160,2015/10/15,19:24:55 - // tokenize the gps buffer to locate the lat & long - char *longp = strtok(gpsbuffer, ","); - if (! longp) return false; - - char *latp = strtok(NULL, ","); - if (! latp) return false; - - *lat = atof(latp); - *lon = atof(longp); - - return true; - -} -/********* TCP FUNCTIONS ************************************/ - - -boolean Adafruit_FONA::TCPconnect(char *server, uint16_t port) { - flushInput(); - - // close all old connections - if (! sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 20000) ) return false; - - // single connection at a time - if (! sendCheckReply(F("AT+CIPMUX=0"), ok_reply) ) return false; - - // manually read data - if (! sendCheckReply(F("AT+CIPRXGET=1"), ok_reply) ) return false; - - - DEBUG_PRINT(F("AT+CIPSTART=\"TCP\",\"")); - DEBUG_PRINT(server); - DEBUG_PRINT(F("\",\"")); - DEBUG_PRINT(port); - DEBUG_PRINTLN(F("\"")); - - - mySerial->print(F("AT+CIPSTART=\"TCP\",\"")); - mySerial->print(server); - mySerial->print(F("\",\"")); - mySerial->print(port); - mySerial->println(F("\"")); - - if (! expectReply(ok_reply)) return false; - if (! expectReply(F("CONNECT OK"))) return false; - - // looks like it was a success (?) - return true; -} - -boolean Adafruit_FONA::TCPclose(void) { - return sendCheckReply(F("AT+CIPCLOSE"), ok_reply); -} - -boolean Adafruit_FONA::TCPconnected(void) { - if (! sendCheckReply(F("AT+CIPSTATUS"), ok_reply, 100) ) return false; - readline(100); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return (strcmp(replybuffer, "STATE: CONNECT OK") == 0); -} - -boolean Adafruit_FONA::TCPsend(char *packet, uint8_t len) { - - DEBUG_PRINT(F("AT+CIPSEND=")); - DEBUG_PRINTLN(len); -#ifdef ADAFRUIT_FONA_DEBUG - for (uint16_t i=0; iprint(F("AT+CIPSEND=")); - mySerial->println(len); - readline(); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - if (replybuffer[0] != '>') return false; - - mySerial->write(packet, len); - readline(3000); // wait up to 3 seconds to send the data - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - - return (strcmp(replybuffer, "SEND OK") == 0); -} - -uint16_t Adafruit_FONA::TCPavailable(void) { - uint16_t avail; - - if (! sendParseReply(F("AT+CIPRXGET=4"), F("+CIPRXGET: 4,"), &avail, ',', 0) ) return false; - - - DEBUG_PRINT (avail); DEBUG_PRINTLN(F(" bytes available")); - - - return avail; -} - - -uint16_t Adafruit_FONA::TCPread(uint8_t *buff, uint8_t len) { - uint16_t avail; - - mySerial->print(F("AT+CIPRXGET=2,")); - mySerial->println(len); - readline(); - if (! parseReply(F("+CIPRXGET: 2,"), &avail, ',', 0)) return false; - - readRaw(avail); - -#ifdef ADAFRUIT_FONA_DEBUG - DEBUG_PRINT (avail); DEBUG_PRINTLN(F(" bytes read")); - for (uint8_t i=0;i ")); - DEBUG_PRINT(F("AT+HTTPPARA=\"")); - DEBUG_PRINT(parameter); - DEBUG_PRINTLN('"'); - - - mySerial->print(F("AT+HTTPPARA=\"")); - mySerial->print(parameter); - if (quoted) - mySerial->print(F("\",\"")); - else - mySerial->print(F("\",")); -} - -boolean Adafruit_FONA::HTTP_para_end(boolean quoted) { - if (quoted) - mySerial->println('"'); - else - mySerial->println(); - - return expectReply(ok_reply); -} - -boolean Adafruit_FONA::HTTP_para(FONAFlashStringPtr parameter, - const char *value) { - HTTP_para_start(parameter, true); - mySerial->print(value); - return HTTP_para_end(true); -} - -boolean Adafruit_FONA::HTTP_para(FONAFlashStringPtr parameter, - FONAFlashStringPtr value) { - HTTP_para_start(parameter, true); - mySerial->print(value); - return HTTP_para_end(true); -} - -boolean Adafruit_FONA::HTTP_para(FONAFlashStringPtr parameter, - int32_t value) { - HTTP_para_start(parameter, false); - mySerial->print(value); - return HTTP_para_end(false); -} - -boolean Adafruit_FONA::HTTP_data(uint32_t size, uint32_t maxTime) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); - DEBUG_PRINT(F("AT+HTTPDATA=")); - DEBUG_PRINT(size); - DEBUG_PRINT(','); - DEBUG_PRINTLN(maxTime); - - - mySerial->print(F("AT+HTTPDATA=")); - mySerial->print(size); - mySerial->print(","); - mySerial->println(maxTime); - - return expectReply(F("DOWNLOAD")); -} - -boolean Adafruit_FONA::HTTP_action(uint8_t method, uint16_t *status, - uint16_t *datalen, int32_t timeout) { - // Send request. - if (! sendCheckReply(F("AT+HTTPACTION="), method, ok_reply)) - return false; - - // Parse response status and size. - readline(timeout); - if (! parseReply(F("+HTTPACTION:"), status, ',', 1)) - return false; - if (! parseReply(F("+HTTPACTION:"), datalen, ',', 2)) - return false; - - return true; -} - -boolean Adafruit_FONA::HTTP_readall(uint16_t *datalen) { - getReply(F("AT+HTTPREAD")); - if (! parseReply(F("+HTTPREAD:"), datalen, ',', 0)) - return false; - - return true; -} - -boolean Adafruit_FONA::HTTP_ssl(boolean onoff) { - return sendCheckReply(F("AT+HTTPSSL="), onoff ? 1 : 0, ok_reply); -} - -/********* HTTP HIGH LEVEL FUNCTIONS ***************************/ - -boolean Adafruit_FONA::HTTP_GET_start(char *url, - uint16_t *status, uint16_t *datalen){ - if (! HTTP_setup(url)) - return false; - - // HTTP GET - if (! HTTP_action(FONA_HTTP_GET, status, datalen, 30000)) - return false; - - DEBUG_PRINT(F("Status: ")); DEBUG_PRINTLN(*status); - DEBUG_PRINT(F("Len: ")); DEBUG_PRINTLN(*datalen); - - // HTTP response data - if (! HTTP_readall(datalen)) - return false; - - return true; -} - -/* -boolean Adafruit_FONA_3G::HTTP_GET_start(char *ipaddr, char *path, uint16_t port - uint16_t *status, uint16_t *datalen){ - char send[100] = "AT+CHTTPACT=\""; - char *sendp = send + strlen(send); - memset(sendp, 0, 100 - strlen(send)); - - strcpy(sendp, ipaddr); - sendp+=strlen(ipaddr); - sendp[0] = '\"'; - sendp++; - sendp[0] = ','; - itoa(sendp, port); - getReply(send, 500); - - return; - - if (! HTTP_setup(url)) - - return false; - - // HTTP GET - if (! HTTP_action(FONA_HTTP_GET, status, datalen)) - return false; - - DEBUG_PRINT("Status: "); DEBUG_PRINTLN(*status); - DEBUG_PRINT("Len: "); DEBUG_PRINTLN(*datalen); - - // HTTP response data - if (! HTTP_readall(datalen)) - return false; - - return true; -} -*/ - -void Adafruit_FONA::HTTP_GET_end(void) { - HTTP_term(); -} - -boolean Adafruit_FONA::HTTP_POST_start(char *url, - FONAFlashStringPtr contenttype, - const uint8_t *postdata, uint16_t postdatalen, - uint16_t *status, uint16_t *datalen){ - if (! HTTP_setup(url)) - return false; - - if (! HTTP_para(F("CONTENT"), contenttype)) { - return false; - } - - // HTTP POST data - if (! HTTP_data(postdatalen, 10000)) - return false; - mySerial->write(postdata, postdatalen); - if (! expectReply(ok_reply)) - return false; - - // HTTP POST - if (! HTTP_action(FONA_HTTP_POST, status, datalen)) - return false; - - DEBUG_PRINT(F("Status: ")); DEBUG_PRINTLN(*status); - DEBUG_PRINT(F("Len: ")); DEBUG_PRINTLN(*datalen); - - // HTTP response data - if (! HTTP_readall(datalen)) - return false; - - return true; -} - -void Adafruit_FONA::HTTP_POST_end(void) { - HTTP_term(); -} - -void Adafruit_FONA::setUserAgent(FONAFlashStringPtr useragent) { - this->useragent = useragent; -} - -void Adafruit_FONA::setHTTPSRedirect(boolean onoff) { - httpsredirect = onoff; -} - -/********* HTTP HELPERS ****************************************/ - -boolean Adafruit_FONA::HTTP_setup(char *url) { - // Handle any pending - HTTP_term(); - - // Initialize and set parameters - if (! HTTP_init()) - return false; - if (! HTTP_para(F("CID"), 1)) - return false; - if (! HTTP_para(F("UA"), useragent)) - return false; - if (! HTTP_para(F("URL"), url)) - return false; - - // HTTPS redirect - if (httpsredirect) { - if (! HTTP_para(F("REDIR"),1)) - return false; - - if (! HTTP_ssl(true)) - return false; - } - - return true; -} - -/********* HELPERS *********************************************/ - -boolean Adafruit_FONA::expectReply(FONAFlashStringPtr reply, - uint16_t timeout) { - readline(timeout); - - DEBUG_PRINT(F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return (prog_char_strcmp(replybuffer, (prog_char*)reply) == 0); -} - -/********* LOW LEVEL *******************************************/ - -inline int Adafruit_FONA::available(void) { - return mySerial->available(); -} - -inline size_t Adafruit_FONA::write(uint8_t x) { - return mySerial->write(x); -} - -inline int Adafruit_FONA::read(void) { - return mySerial->read(); -} - -inline int Adafruit_FONA::peek(void) { - return mySerial->peek(); -} - -inline void Adafruit_FONA::flush() { - mySerial->flush(); -} - -void Adafruit_FONA::flushInput() { - // Read all available serial input to flush pending data. - uint16_t timeoutloop = 0; - while (timeoutloop++ < 40) { - while(available()) { - read(); - timeoutloop = 0; // If char was received reset the timer - } - delay(1); - } -} - -uint16_t Adafruit_FONA::readRaw(uint16_t b) { - uint16_t idx = 0; - - while (b && (idx < sizeof(replybuffer)-1)) { - if (mySerial->available()) { - replybuffer[idx] = mySerial->read(); - idx++; - b--; - } - } - replybuffer[idx] = 0; - - return idx; -} - -uint8_t Adafruit_FONA::readline(uint16_t timeout, boolean multiline) { - uint16_t replyidx = 0; - - while (timeout--) { - if (replyidx >= 254) { - //DEBUG_PRINTLN(F("SPACE")); - break; - } - - while(mySerial->available()) { - char c = mySerial->read(); - if (c == '\r') continue; - if (c == 0xA) { - if (replyidx == 0) // the first 0x0A is ignored - continue; - - if (!multiline) { - timeout = 0; // the second 0x0A is the end of the line - break; - } - } - replybuffer[replyidx] = c; - //DEBUG_PRINT(c, HEX); DEBUG_PRINT("#"); DEBUG_PRINTLN(c); - replyidx++; - } - - if (timeout == 0) { - //DEBUG_PRINTLN(F("TIMEOUT")); - break; - } - delay(1); - } - replybuffer[replyidx] = 0; // null term - return replyidx; -} - -uint8_t Adafruit_FONA::getReply(char *send, uint16_t timeout) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN(send); - - - mySerial->println(send); - - uint8_t l = readline(timeout); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return l; -} - -uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr send, uint16_t timeout) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN(send); - - - mySerial->println(send); - - uint8_t l = readline(timeout); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return l; -} - -// Send prefix, suffix, and newline. Return response (and also set replybuffer with response). -uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr prefix, char *suffix, uint16_t timeout) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); DEBUG_PRINTLN(suffix); - - - mySerial->print(prefix); - mySerial->println(suffix); - - uint8_t l = readline(timeout); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return l; -} - -// Send prefix, suffix, and newline. Return response (and also set replybuffer with response). -uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr prefix, int32_t suffix, uint16_t timeout) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); DEBUG_PRINTLN(suffix, DEC); - - - mySerial->print(prefix); - mySerial->println(suffix, DEC); - - uint8_t l = readline(timeout); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return l; -} - -// Send prefix, suffix, suffix2, and newline. Return response (and also set replybuffer with response). -uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr prefix, int32_t suffix1, int32_t suffix2, uint16_t timeout) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); - DEBUG_PRINT(suffix1, DEC); DEBUG_PRINT(','); DEBUG_PRINTLN(suffix2, DEC); - - - mySerial->print(prefix); - mySerial->print(suffix1); - mySerial->print(','); - mySerial->println(suffix2, DEC); - - uint8_t l = readline(timeout); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return l; -} - -// Send prefix, ", suffix, ", and newline. Return response (and also set replybuffer with response). -uint8_t Adafruit_FONA::getReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, uint16_t timeout) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); - DEBUG_PRINT('"'); DEBUG_PRINT(suffix); DEBUG_PRINTLN('"'); - - - mySerial->print(prefix); - mySerial->print('"'); - mySerial->print(suffix); - mySerial->println('"'); - - uint8_t l = readline(timeout); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return l; -} - -boolean Adafruit_FONA::sendCheckReply(char *send, char *reply, uint16_t timeout) { - if (! getReply(send, timeout) ) - return false; -/* - for (uint8_t i=0; i http://www.adafruit.com/products/1946 - ----> http://www.adafruit.com/products/1963 - - These displays use TTL Serial to communicate, 2 pins are required to - interface - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - BSD license, all text above must be included in any redistribution - ****************************************************/ -#ifndef ADAFRUIT_FONA_H -#define ADAFRUIT_FONA_H - -#include "includes/FONAConfig.h" -#include "includes/FONAExtIncludes.h" -#include "includes/platform/FONAPlatform.h" - - - -#define FONA800L 1 -#define FONA800H 6 - -#define FONA808_V1 2 -#define FONA808_V2 3 - -#define FONA3G_A 4 -#define FONA3G_E 5 - -// Uncomment to changed the preferred SMS storage -//#define FONA_PREF_SMS_STORAGE "SM" - -#define FONA_HEADSETAUDIO 0 -#define FONA_EXTAUDIO 1 - -#define FONA_STTONE_DIALTONE 1 -#define FONA_STTONE_BUSY 2 -#define FONA_STTONE_CONGESTION 3 -#define FONA_STTONE_PATHACK 4 -#define FONA_STTONE_DROPPED 5 -#define FONA_STTONE_ERROR 6 -#define FONA_STTONE_CALLWAIT 7 -#define FONA_STTONE_RINGING 8 -#define FONA_STTONE_BEEP 16 -#define FONA_STTONE_POSTONE 17 -#define FONA_STTONE_ERRTONE 18 -#define FONA_STTONE_INDIANDIALTONE 19 -#define FONA_STTONE_USADIALTONE 20 - -#define FONA_DEFAULT_TIMEOUT_MS 500 - -#define FONA_HTTP_GET 0 -#define FONA_HTTP_POST 1 -#define FONA_HTTP_HEAD 2 - -#define FONA_CALL_READY 0 -#define FONA_CALL_FAILED 1 -#define FONA_CALL_UNKNOWN 2 -#define FONA_CALL_RINGING 3 -#define FONA_CALL_INPROGRESS 4 - -class Adafruit_FONA : public FONAStreamType { - public: - Adafruit_FONA(int8_t r); - boolean begin(FONAStreamType &port); - uint8_t type(); - - // Stream - int available(void); - size_t write(uint8_t x); - int read(void); - int peek(void); - void flush(); - - // FONA 3G requirements - boolean setBaudrate(uint16_t baud); - - // RTC - boolean enableRTC(uint8_t i); - boolean readRTC(uint8_t *year, uint8_t *month, uint8_t *date, uint8_t *hr, uint8_t *min, uint8_t *sec); - - // Battery and ADC - boolean getADCVoltage(uint16_t *v); - boolean getBattPercent(uint16_t *p); - boolean getBattVoltage(uint16_t *v); - - // SIM query - uint8_t unlockSIM(char *pin); - uint8_t getSIMCCID(char *ccid); - uint8_t getNetworkStatus(void); - uint8_t getRSSI(void); - - // IMEI - uint8_t getIMEI(char *imei); - - // set Audio output - boolean setAudio(uint8_t a); - boolean setVolume(uint8_t i); - uint8_t getVolume(void); - boolean playToolkitTone(uint8_t t, uint16_t len); - boolean setMicVolume(uint8_t a, uint8_t level); - boolean playDTMF(char tone); - - // FM radio functions. - boolean tuneFMradio(uint16_t station); - boolean FMradio(boolean onoff, uint8_t a = FONA_HEADSETAUDIO); - boolean setFMVolume(uint8_t i); - int8_t getFMVolume(); - int8_t getFMSignalLevel(uint16_t station); - - // SMS handling - boolean setSMSInterrupt(uint8_t i); - uint8_t getSMSInterrupt(void); - int8_t getNumSMS(void); - boolean readSMS(uint8_t i, char *smsbuff, uint16_t max, uint16_t *readsize); - boolean sendSMS(char *smsaddr, char *smsmsg); - boolean deleteSMS(uint8_t i); - boolean getSMSSender(uint8_t i, char *sender, int senderlen); - boolean sendUSSD(char *ussdmsg, char *ussdbuff, uint16_t maxlen, uint16_t *readlen); - - // Time - boolean enableNetworkTimeSync(boolean onoff); - boolean enableNTPTimeSync(boolean onoff, FONAFlashStringPtr ntpserver=0); - boolean getTime(char *buff, uint16_t maxlen); - - // GPRS handling - boolean enableGPRS(boolean onoff); - uint8_t GPRSstate(void); - boolean getGSMLoc(uint16_t *replycode, char *buff, uint16_t maxlen); - boolean getGSMLoc(float *lat, float *lon); - void setGPRSNetworkSettings(FONAFlashStringPtr apn, FONAFlashStringPtr username=0, FONAFlashStringPtr password=0); - - // GPS handling - boolean enableGPS(boolean onoff); - int8_t GPSstatus(void); - uint8_t getGPS(uint8_t arg, char *buffer, uint8_t maxbuff); - boolean getGPS(float *lat, float *lon, float *speed_kph=0, float *heading=0, float *altitude=0); - boolean enableGPSNMEA(uint8_t nmea); - - // TCP raw connections - boolean TCPconnect(char *server, uint16_t port); - boolean TCPclose(void); - boolean TCPconnected(void); - boolean TCPsend(char *packet, uint8_t len); - uint16_t TCPavailable(void); - uint16_t TCPread(uint8_t *buff, uint8_t len); - - // HTTP low level interface (maps directly to SIM800 commands). - boolean HTTP_init(); - boolean HTTP_term(); - void HTTP_para_start(FONAFlashStringPtr parameter, boolean quoted = true); - boolean HTTP_para_end(boolean quoted = true); - boolean HTTP_para(FONAFlashStringPtr parameter, const char *value); - boolean HTTP_para(FONAFlashStringPtr parameter, FONAFlashStringPtr value); - boolean HTTP_para(FONAFlashStringPtr parameter, int32_t value); - boolean HTTP_data(uint32_t size, uint32_t maxTime=10000); - boolean HTTP_action(uint8_t method, uint16_t *status, uint16_t *datalen, int32_t timeout = 10000); - boolean HTTP_readall(uint16_t *datalen); - boolean HTTP_ssl(boolean onoff); - - // HTTP high level interface (easier to use, less flexible). - boolean HTTP_GET_start(char *url, uint16_t *status, uint16_t *datalen); - void HTTP_GET_end(void); - boolean HTTP_POST_start(char *url, FONAFlashStringPtr contenttype, const uint8_t *postdata, uint16_t postdatalen, uint16_t *status, uint16_t *datalen); - void HTTP_POST_end(void); - void setUserAgent(FONAFlashStringPtr useragent); - - // HTTPS - void setHTTPSRedirect(boolean onoff); - - // PWM (buzzer) - boolean setPWM(uint16_t period, uint8_t duty = 50); - - // Phone calls - boolean callPhone(char *phonenum); - uint8_t getCallStatus(void); - boolean hangUp(void); - boolean pickUp(void); - boolean callerIdNotification(boolean enable, uint8_t interrupt = 0); - boolean incomingCallNumber(char* phonenum); - - // Helper functions to verify responses. - boolean expectReply(FONAFlashStringPtr reply, uint16_t timeout = 10000); - boolean sendCheckReply(char *send, char *reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - boolean sendCheckReply(FONAFlashStringPtr send, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - boolean sendCheckReply(char* send, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - - - protected: - int8_t _rstpin; - uint8_t _type; - - char replybuffer[255]; - FONAFlashStringPtr apn; - FONAFlashStringPtr apnusername; - FONAFlashStringPtr apnpassword; - boolean httpsredirect; - FONAFlashStringPtr useragent; - FONAFlashStringPtr ok_reply; - - // HTTP helpers - boolean HTTP_setup(char *url); - - void flushInput(); - uint16_t readRaw(uint16_t b); - uint8_t readline(uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS, boolean multiline = false); - uint8_t getReply(char *send, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - uint8_t getReply(FONAFlashStringPtr send, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - uint8_t getReply(FONAFlashStringPtr prefix, char *suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - uint8_t getReply(FONAFlashStringPtr prefix, int32_t suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - uint8_t getReply(FONAFlashStringPtr prefix, int32_t suffix1, int32_t suffix2, uint16_t timeout); // Don't set default value or else function call is ambiguous. - uint8_t getReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - - boolean sendCheckReply(FONAFlashStringPtr prefix, char *suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - boolean sendCheckReply(FONAFlashStringPtr prefix, int32_t suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - boolean sendCheckReply(FONAFlashStringPtr prefix, int32_t suffix, int32_t suffix2, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - boolean sendCheckReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - - - boolean parseReply(FONAFlashStringPtr toreply, - uint16_t *v, char divider = ',', uint8_t index=0); - boolean parseReply(FONAFlashStringPtr toreply, - char *v, char divider = ',', uint8_t index=0); - boolean parseReplyQuoted(FONAFlashStringPtr toreply, - char *v, int maxlen, char divider, uint8_t index); - - boolean sendParseReply(FONAFlashStringPtr tosend, - FONAFlashStringPtr toreply, - uint16_t *v, char divider = ',', uint8_t index=0); - - static boolean _incomingCall; - static void onIncomingCall(); - - FONAStreamType *mySerial; -}; - -class Adafruit_FONA_3G : public Adafruit_FONA { - - public: - Adafruit_FONA_3G (int8_t r) : Adafruit_FONA(r) { _type = FONA3G_A; } - - boolean getBattVoltage(uint16_t *v); - boolean playToolkitTone(uint8_t t, uint16_t len); - boolean hangUp(void); - boolean pickUp(void); - boolean enableGPRS(boolean onoff); - boolean enableGPS(boolean onoff); - - protected: - boolean parseReply(FONAFlashStringPtr toreply, - float *f, char divider, uint8_t index); - - boolean sendParseReply(FONAFlashStringPtr tosend, - FONAFlashStringPtr toreply, - float *f, char divider = ',', uint8_t index=0); -}; - -#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/README.md b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/README.md deleted file mode 100644 index 73452ca..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Adafruit FONA Library [![Build Status](https://secure.travis-ci.org/adafruit/Adafruit_FONA_Library.svg?branch=master)](https://travis-ci.org/adafruit/Adafruit_FONA_Library) - -**This library requires Arduino v1.0.6 or higher** - -This is a library for the Adafruit FONA Cellular GSM Breakouts etc - -Designed specifically to work with the Adafruit FONA Breakout - * https://www.adafruit.com/products/1946 - * https://www.adafruit.com/products/1963 - * http://www.adafruit.com/products/2468 - * http://www.adafruit.com/products/2542 - -These modules use TTL Serial to communicate, 2 pins are required to interface - -Adafruit invests time and resources providing this open source code, -please support Adafruit and open-source hardware by purchasing -products from Adafruit! - -Check out the links above for our tutorials and wiring diagrams - -Written by Limor Fried/Ladyada for Adafruit Industries. -BSD license, all text above must be included in any redistribution -With updates from Samy Kamkar - -To download. click the DOWNLOADS button in the top right corner, rename the uncompressed folder Adafruit_FONA -Check that the Adafruit_FONA folder contains Adafruit_FONA.cpp and Adafruit_FONA.h - -Place the Adafruit_FONA library folder your *arduinosketchfolder*/libraries/ folder. -You may need to create the libraries subfolder if its your first library. Restart the IDE. diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/.esp8266.test.skip b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/.esp8266.test.skip deleted file mode 100644 index e69de29..0000000 diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino deleted file mode 100644 index b0be4c5..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino +++ /dev/null @@ -1,77 +0,0 @@ -/*************************************************** - This is an example for our Adafruit FONA Cellular Module - since the FONA 3G does not do auto-baud very well, this demo - fixes the baud rate to 4800 from the default 115200 - - Designed specifically to work with the Adafruit FONA 3G - ----> http://www.adafruit.com/products/2691 - ----> http://www.adafruit.com/products/2687 - - These cellular modules use TTL Serial to communicate, 2 pins are - required to interface - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - BSD license, all text above must be included in any redistribution - ****************************************************/ - -#include "Adafruit_FONA.h" - -#define FONA_RX 2 -#define FONA_TX 3 -#define FONA_RST 4 - -// this is a large buffer for replies -char replybuffer[255]; - -// We default to using software serial. If you want to use hardware serial -// (because softserial isnt supported) comment out the following three lines -// and uncomment the HardwareSerial line -#include -SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); -SoftwareSerial *fonaSerial = &fonaSS; - -// Hardware serial is also possible! -// HardwareSerial *fonaSerial = &Serial1; - -Adafruit_FONA fona = Adafruit_FONA(FONA_RST); - -uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); - -void setup() { - while (!Serial); - - Serial.begin(115200); - Serial.println(F("FONA set baudrate")); - - Serial.println(F("First trying 115200 baud")); - // start at 115200 baud - fonaSerial->begin(115200); - fona.begin(*fonaSerial); - - // send the command to reset the baud rate to 4800 - fona.setBaudrate(4800); - - // restart with 4800 baud - fonaSerial->begin(4800); - Serial.println(F("Initializing @ 4800 baud...")); - - if (! fona.begin(*fonaSerial)) { - Serial.println(F("Couldn't find FONA")); - while(1); - } - Serial.println(F("FONA is OK")); - - // Print module IMEI number. - char imei[15] = {0}; // MUST use a 16 character buffer for IMEI! - uint8_t imeiLen = fona.getIMEI(imei); - if (imeiLen > 0) { - Serial.print("Module IMEI: "); Serial.println(imei); - } - -} - -void loop() { -} \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/.esp8266.test.skip b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/.esp8266.test.skip deleted file mode 100644 index e69de29..0000000 diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino deleted file mode 100644 index 7201641..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino +++ /dev/null @@ -1,131 +0,0 @@ -/*************************************************** - This is an example for our Adafruit FONA Cellular Module - - Designed specifically to work with the Adafruit FONA - ----> http://www.adafruit.com/products/1946 - ----> http://www.adafruit.com/products/1963 - ----> http://www.adafruit.com/products/2468 - ----> http://www.adafruit.com/products/2542 - - These cellular modules use TTL Serial to communicate, 2 pins are - required to interface - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - BSD license, all text above must be included in any redistribution - ****************************************************/ - -/* -THIS CODE IS STILL IN PROGRESS! - -Open up the serial console on the Arduino at 115200 baud to interact with FONA - - -This code will receive an SMS, identify the sender's phone number, and automatically send a response - -For use with FONA 800 & 808, not 3G -*/ - -#include "Adafruit_FONA.h" - -#define FONA_RX 2 -#define FONA_TX 3 -#define FONA_RST 4 - -// this is a large buffer for replies -char replybuffer[255]; - -// We default to using software serial. If you want to use hardware serial -// (because softserial isnt supported) comment out the following three lines -// and uncomment the HardwareSerial line -#include -SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); -SoftwareSerial *fonaSerial = &fonaSS; - -// Hardware serial is also possible! -// HardwareSerial *fonaSerial = &Serial1; - -Adafruit_FONA fona = Adafruit_FONA(FONA_RST); - -uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); - -void setup() { - while (!Serial); - - Serial.begin(115200); - Serial.println(F("FONA SMS caller ID test")); - Serial.println(F("Initializing....(May take 3 seconds)")); - - // make it slow so its easy to read! - fonaSerial->begin(4800); - if (! fona.begin(*fonaSerial)) { - Serial.println(F("Couldn't find FONA")); - while(1); - } - Serial.println(F("FONA is OK")); - - // Print SIM card IMEI number. - char imei[15] = {0}; // MUST use a 16 character buffer for IMEI! - uint8_t imeiLen = fona.getIMEI(imei); - if (imeiLen > 0) { - Serial.print("SIM card IMEI: "); Serial.println(imei); - } - - Serial.println("FONA Ready"); -} - - -char fonaInBuffer[64]; //for notifications from the FONA - -void loop() { - - char* bufPtr = fonaInBuffer; //handy buffer pointer - - if (fona.available()) //any data available from the FONA? - { - int slot = 0; //this will be the slot number of the SMS - int charCount = 0; - //Read the notification into fonaInBuffer - do { - *bufPtr = fona.read(); - Serial.write(*bufPtr); - delay(1); - } while ((*bufPtr++ != '\n') && (fona.available()) && (++charCount < (sizeof(fonaInBuffer)-1))); - - //Add a terminal NULL to the notification string - *bufPtr = 0; - - //Scan the notification string for an SMS received notification. - // If it's an SMS message, we'll get the slot number in 'slot' - if (1 == sscanf(fonaInBuffer, "+CMTI: \"SM\",%d", &slot)) { - Serial.print("slot: "); Serial.println(slot); - - char callerIDbuffer[32]; //we'll store the SMS sender number in here - - // Retrieve SMS sender address/phone number. - if (! fona.getSMSSender(slot, callerIDbuffer, 31)) { - Serial.println("Didn't find SMS message in slot!"); - } - Serial.print(F("FROM: ")); Serial.println(callerIDbuffer); - - //Send back an automatic response - Serial.println("Sending reponse..."); - if (!fona.sendSMS(callerIDbuffer, "Hey, I got your text!")) { - Serial.println(F("Failed")); - } else { - Serial.println(F("Sent!")); - } - - // delete the original msg after it is processed - // otherwise, we will fill up all the slots - // and then we won't be able to receive SMS anymore - if (fona.deleteSMS(slot)) { - Serial.println(F("OK!")); - } else { - Serial.println(F("Couldn't delete")); - } - } - } -} diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONAtest/.esp8266.test.skip b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONAtest/.esp8266.test.skip deleted file mode 100644 index e69de29..0000000 diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino deleted file mode 100644 index 1b27732..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino +++ /dev/null @@ -1,886 +0,0 @@ -/*************************************************** - This is an example for our Adafruit FONA Cellular Module - - Designed specifically to work with the Adafruit FONA - ----> http://www.adafruit.com/products/1946 - ----> http://www.adafruit.com/products/1963 - ----> http://www.adafruit.com/products/2468 - ----> http://www.adafruit.com/products/2542 - - These cellular modules use TTL Serial to communicate, 2 pins are - required to interface - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - BSD license, all text above must be included in any redistribution - ****************************************************/ - -/* -THIS CODE IS STILL IN PROGRESS! - -Open up the serial console on the Arduino at 115200 baud to interact with FONA - -Note that if you need to set a GPRS APN, username, and password scroll down to -the commented section below at the end of the setup() function. -*/ -#include "Adafruit_FONA.h" - -#define FONA_RX 2 -#define FONA_TX 3 -#define FONA_RST 4 - -// this is a large buffer for replies -char replybuffer[255]; - -// We default to using software serial. If you want to use hardware serial -// (because softserial isnt supported) comment out the following three lines -// and uncomment the HardwareSerial line -#include -SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); -SoftwareSerial *fonaSerial = &fonaSS; - -// Hardware serial is also possible! -// HardwareSerial *fonaSerial = &Serial1; - -// Use this for FONA 800 and 808s -Adafruit_FONA fona = Adafruit_FONA(FONA_RST); -// Use this one for FONA 3G -//Adafruit_FONA_3G fona = Adafruit_FONA_3G(FONA_RST); - -uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); - -uint8_t type; - -void setup() { - while (!Serial); - - Serial.begin(115200); - Serial.println(F("FONA basic test")); - Serial.println(F("Initializing....(May take 3 seconds)")); - - fonaSerial->begin(4800); - if (! fona.begin(*fonaSerial)) { - Serial.println(F("Couldn't find FONA")); - while (1); - } - type = fona.type(); - Serial.println(F("FONA is OK")); - Serial.print(F("Found ")); - switch (type) { - case FONA800L: - Serial.println(F("FONA 800L")); break; - case FONA800H: - Serial.println(F("FONA 800H")); break; - case FONA808_V1: - Serial.println(F("FONA 808 (v1)")); break; - case FONA808_V2: - Serial.println(F("FONA 808 (v2)")); break; - case FONA3G_A: - Serial.println(F("FONA 3G (American)")); break; - case FONA3G_E: - Serial.println(F("FONA 3G (European)")); break; - default: - Serial.println(F("???")); break; - } - - // Print module IMEI number. - char imei[15] = {0}; // MUST use a 16 character buffer for IMEI! - uint8_t imeiLen = fona.getIMEI(imei); - if (imeiLen > 0) { - Serial.print("Module IMEI: "); Serial.println(imei); - } - - // Optionally configure a GPRS APN, username, and password. - // You might need to do this to access your network's GPRS/data - // network. Contact your provider for the exact APN, username, - // and password values. Username and password are optional and - // can be removed, but APN is required. - //fona.setGPRSNetworkSettings(F("your APN"), F("your username"), F("your password")); - - // Optionally configure HTTP gets to follow redirects over SSL. - // Default is not to follow SSL redirects, however if you uncomment - // the following line then redirects over SSL will be followed. - //fona.setHTTPSRedirect(true); - - printMenu(); -} - -void printMenu(void) { - Serial.println(F("-------------------------------------")); - Serial.println(F("[?] Print this menu")); - Serial.println(F("[a] read the ADC 2.8V max (FONA800 & 808)")); - Serial.println(F("[b] read the Battery V and % charged")); - Serial.println(F("[C] read the SIM CCID")); - Serial.println(F("[U] Unlock SIM with PIN code")); - Serial.println(F("[i] read RSSI")); - Serial.println(F("[n] get Network status")); - Serial.println(F("[v] set audio Volume")); - Serial.println(F("[V] get Volume")); - Serial.println(F("[H] set Headphone audio (FONA800 & 808)")); - Serial.println(F("[e] set External audio (FONA800 & 808)")); - Serial.println(F("[T] play audio Tone")); - Serial.println(F("[P] PWM/Buzzer out (FONA800 & 808)")); - - // FM (SIM800 only!) - Serial.println(F("[f] tune FM radio (FONA800)")); - Serial.println(F("[F] turn off FM (FONA800)")); - Serial.println(F("[m] set FM volume (FONA800)")); - Serial.println(F("[M] get FM volume (FONA800)")); - Serial.println(F("[q] get FM station signal level (FONA800)")); - - // Phone - Serial.println(F("[c] make phone Call")); - Serial.println(F("[A] get call status")); - Serial.println(F("[h] Hang up phone")); - Serial.println(F("[p] Pick up phone")); - - // SMS - Serial.println(F("[N] Number of SMSs")); - Serial.println(F("[r] Read SMS #")); - Serial.println(F("[R] Read All SMS")); - Serial.println(F("[d] Delete SMS #")); - Serial.println(F("[s] Send SMS")); - Serial.println(F("[u] Send USSD")); - - // Time - Serial.println(F("[y] Enable network time sync (FONA 800 & 808)")); - Serial.println(F("[Y] Enable NTP time sync (GPRS FONA 800 & 808)")); - Serial.println(F("[t] Get network time")); - - // GPRS - Serial.println(F("[G] Enable GPRS")); - Serial.println(F("[g] Disable GPRS")); - Serial.println(F("[l] Query GSMLOC (GPRS)")); - Serial.println(F("[w] Read webpage (GPRS)")); - Serial.println(F("[W] Post to website (GPRS)")); - - // GPS - if ((type == FONA3G_A) || (type == FONA3G_E) || (type == FONA808_V1) || (type == FONA808_V2)) { - Serial.println(F("[O] Turn GPS on (FONA 808 & 3G)")); - Serial.println(F("[o] Turn GPS off (FONA 808 & 3G)")); - Serial.println(F("[L] Query GPS location (FONA 808 & 3G)")); - if (type == FONA808_V1) { - Serial.println(F("[x] GPS fix status (FONA808 v1 only)")); - } - Serial.println(F("[E] Raw NMEA out (FONA808)")); - } - - Serial.println(F("[S] create Serial passthru tunnel")); - Serial.println(F("-------------------------------------")); - Serial.println(F("")); - -} -void loop() { - Serial.print(F("FONA> ")); - while (! Serial.available() ) { - if (fona.available()) { - Serial.write(fona.read()); - } - } - - char command = Serial.read(); - Serial.println(command); - - - switch (command) { - case '?': { - printMenu(); - break; - } - - case 'a': { - // read the ADC - uint16_t adc; - if (! fona.getADCVoltage(&adc)) { - Serial.println(F("Failed to read ADC")); - } else { - Serial.print(F("ADC = ")); Serial.print(adc); Serial.println(F(" mV")); - } - break; - } - - case 'b': { - // read the battery voltage and percentage - uint16_t vbat; - if (! fona.getBattVoltage(&vbat)) { - Serial.println(F("Failed to read Batt")); - } else { - Serial.print(F("VBat = ")); Serial.print(vbat); Serial.println(F(" mV")); - } - - - if (! fona.getBattPercent(&vbat)) { - Serial.println(F("Failed to read Batt")); - } else { - Serial.print(F("VPct = ")); Serial.print(vbat); Serial.println(F("%")); - } - - break; - } - - case 'U': { - // Unlock the SIM with a PIN code - char PIN[5]; - flushSerial(); - Serial.println(F("Enter 4-digit PIN")); - readline(PIN, 3); - Serial.println(PIN); - Serial.print(F("Unlocking SIM card: ")); - if (! fona.unlockSIM(PIN)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - - case 'C': { - // read the CCID - fona.getSIMCCID(replybuffer); // make sure replybuffer is at least 21 bytes! - Serial.print(F("SIM CCID = ")); Serial.println(replybuffer); - break; - } - - case 'i': { - // read the RSSI - uint8_t n = fona.getRSSI(); - int8_t r; - - Serial.print(F("RSSI = ")); Serial.print(n); Serial.print(": "); - if (n == 0) r = -115; - if (n == 1) r = -111; - if (n == 31) r = -52; - if ((n >= 2) && (n <= 30)) { - r = map(n, 2, 30, -110, -54); - } - Serial.print(r); Serial.println(F(" dBm")); - - break; - } - - case 'n': { - // read the network/cellular status - uint8_t n = fona.getNetworkStatus(); - Serial.print(F("Network status ")); - Serial.print(n); - Serial.print(F(": ")); - if (n == 0) Serial.println(F("Not registered")); - if (n == 1) Serial.println(F("Registered (home)")); - if (n == 2) Serial.println(F("Not registered (searching)")); - if (n == 3) Serial.println(F("Denied")); - if (n == 4) Serial.println(F("Unknown")); - if (n == 5) Serial.println(F("Registered roaming")); - break; - } - - /*** Audio ***/ - case 'v': { - // set volume - flushSerial(); - if ( (type == FONA3G_A) || (type == FONA3G_E) ) { - Serial.print(F("Set Vol [0-8] ")); - } else { - Serial.print(F("Set Vol % [0-100] ")); - } - uint8_t vol = readnumber(); - Serial.println(); - if (! fona.setVolume(vol)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - - case 'V': { - uint8_t v = fona.getVolume(); - Serial.print(v); - if ( (type == FONA3G_A) || (type == FONA3G_E) ) { - Serial.println(" / 8"); - } else { - Serial.println("%"); - } - break; - } - - case 'H': { - // Set Headphone output - if (! fona.setAudio(FONA_HEADSETAUDIO)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - fona.setMicVolume(FONA_HEADSETAUDIO, 15); - break; - } - case 'e': { - // Set External output - if (! fona.setAudio(FONA_EXTAUDIO)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - - fona.setMicVolume(FONA_EXTAUDIO, 10); - break; - } - - case 'T': { - // play tone - flushSerial(); - Serial.print(F("Play tone #")); - uint8_t kittone = readnumber(); - Serial.println(); - // play for 1 second (1000 ms) - if (! fona.playToolkitTone(kittone, 1000)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - - /*** FM Radio ***/ - - case 'f': { - // get freq - flushSerial(); - Serial.print(F("FM Freq (eg 1011 == 101.1 MHz): ")); - uint16_t station = readnumber(); - Serial.println(); - // FM radio ON using headset - if (fona.FMradio(true, FONA_HEADSETAUDIO)) { - Serial.println(F("Opened")); - } - if (! fona.tuneFMradio(station)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("Tuned")); - } - break; - } - case 'F': { - // FM radio off - if (! fona.FMradio(false)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - case 'm': { - // Set FM volume. - flushSerial(); - Serial.print(F("Set FM Vol [0-6]:")); - uint8_t vol = readnumber(); - Serial.println(); - if (!fona.setFMVolume(vol)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - case 'M': { - // Get FM volume. - uint8_t fmvol = fona.getFMVolume(); - if (fmvol < 0) { - Serial.println(F("Failed")); - } else { - Serial.print(F("FM volume: ")); - Serial.println(fmvol, DEC); - } - break; - } - case 'q': { - // Get FM station signal level (in decibels). - flushSerial(); - Serial.print(F("FM Freq (eg 1011 == 101.1 MHz): ")); - uint16_t station = readnumber(); - Serial.println(); - int8_t level = fona.getFMSignalLevel(station); - if (level < 0) { - Serial.println(F("Failed! Make sure FM radio is on (tuned to station).")); - } else { - Serial.print(F("Signal level (dB): ")); - Serial.println(level, DEC); - } - break; - } - - /*** PWM ***/ - - case 'P': { - // PWM Buzzer output @ 2KHz max - flushSerial(); - Serial.print(F("PWM Freq, 0 = Off, (1-2000): ")); - uint16_t freq = readnumber(); - Serial.println(); - if (! fona.setPWM(freq)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - - /*** Call ***/ - case 'c': { - // call a phone! - char number[30]; - flushSerial(); - Serial.print(F("Call #")); - readline(number, 30); - Serial.println(); - Serial.print(F("Calling ")); Serial.println(number); - if (!fona.callPhone(number)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("Sent!")); - } - - break; - } - case 'A': { - // get call status - int8_t callstat = fona.getCallStatus(); - switch (callstat) { - case 0: Serial.println(F("Ready")); break; - case 1: Serial.println(F("Could not get status")); break; - case 3: Serial.println(F("Ringing (incoming)")); break; - case 4: Serial.println(F("Ringing/in progress (outgoing)")); break; - default: Serial.println(F("Unknown")); break; - } - break; - } - - case 'h': { - // hang up! - if (! fona.hangUp()) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - - case 'p': { - // pick up! - if (! fona.pickUp()) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - - /*** SMS ***/ - - case 'N': { - // read the number of SMS's! - int8_t smsnum = fona.getNumSMS(); - if (smsnum < 0) { - Serial.println(F("Could not read # SMS")); - } else { - Serial.print(smsnum); - Serial.println(F(" SMS's on SIM card!")); - } - break; - } - case 'r': { - // read an SMS - flushSerial(); - Serial.print(F("Read #")); - uint8_t smsn = readnumber(); - Serial.print(F("\n\rReading SMS #")); Serial.println(smsn); - - // Retrieve SMS sender address/phone number. - if (! fona.getSMSSender(smsn, replybuffer, 250)) { - Serial.println("Failed!"); - break; - } - Serial.print(F("FROM: ")); Serial.println(replybuffer); - - // Retrieve SMS value. - uint16_t smslen; - if (! fona.readSMS(smsn, replybuffer, 250, &smslen)) { // pass in buffer and max len! - Serial.println("Failed!"); - break; - } - Serial.print(F("***** SMS #")); Serial.print(smsn); - Serial.print(" ("); Serial.print(smslen); Serial.println(F(") bytes *****")); - Serial.println(replybuffer); - Serial.println(F("*****")); - - break; - } - case 'R': { - // read all SMS - int8_t smsnum = fona.getNumSMS(); - uint16_t smslen; - int8_t smsn; - - if ( (type == FONA3G_A) || (type == FONA3G_E) ) { - smsn = 0; // zero indexed - smsnum--; - } else { - smsn = 1; // 1 indexed - } - - for ( ; smsn <= smsnum; smsn++) { - Serial.print(F("\n\rReading SMS #")); Serial.println(smsn); - if (!fona.readSMS(smsn, replybuffer, 250, &smslen)) { // pass in buffer and max len! - Serial.println(F("Failed!")); - break; - } - // if the length is zero, its a special case where the index number is higher - // so increase the max we'll look at! - if (smslen == 0) { - Serial.println(F("[empty slot]")); - smsnum++; - continue; - } - - Serial.print(F("***** SMS #")); Serial.print(smsn); - Serial.print(" ("); Serial.print(smslen); Serial.println(F(") bytes *****")); - Serial.println(replybuffer); - Serial.println(F("*****")); - } - break; - } - - case 'd': { - // delete an SMS - flushSerial(); - Serial.print(F("Delete #")); - uint8_t smsn = readnumber(); - - Serial.print(F("\n\rDeleting SMS #")); Serial.println(smsn); - if (fona.deleteSMS(smsn)) { - Serial.println(F("OK!")); - } else { - Serial.println(F("Couldn't delete")); - } - break; - } - - case 's': { - // send an SMS! - char sendto[21], message[141]; - flushSerial(); - Serial.print(F("Send to #")); - readline(sendto, 20); - Serial.println(sendto); - Serial.print(F("Type out one-line message (140 char): ")); - readline(message, 140); - Serial.println(message); - if (!fona.sendSMS(sendto, message)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("Sent!")); - } - - break; - } - - case 'u': { - // send a USSD! - char message[141]; - flushSerial(); - Serial.print(F("Type out one-line message (140 char): ")); - readline(message, 140); - Serial.println(message); - - uint16_t ussdlen; - if (!fona.sendUSSD(message, replybuffer, 250, &ussdlen)) { // pass in buffer and max len! - Serial.println(F("Failed")); - } else { - Serial.println(F("Sent!")); - Serial.print(F("***** USSD Reply")); - Serial.print(" ("); Serial.print(ussdlen); Serial.println(F(") bytes *****")); - Serial.println(replybuffer); - Serial.println(F("*****")); - } - } - - /*** Time ***/ - - case 'y': { - // enable network time sync - if (!fona.enableNetworkTimeSync(true)) - Serial.println(F("Failed to enable")); - break; - } - - case 'Y': { - // enable NTP time sync - if (!fona.enableNTPTimeSync(true, F("pool.ntp.org"))) - Serial.println(F("Failed to enable")); - break; - } - - case 't': { - // read the time - char buffer[23]; - - fona.getTime(buffer, 23); // make sure replybuffer is at least 23 bytes! - Serial.print(F("Time = ")); Serial.println(buffer); - break; - } - - - /*********************************** GPS (SIM808 only) */ - - case 'o': { - // turn GPS off - if (!fona.enableGPS(false)) - Serial.println(F("Failed to turn off")); - break; - } - case 'O': { - // turn GPS on - if (!fona.enableGPS(true)) - Serial.println(F("Failed to turn on")); - break; - } - case 'x': { - int8_t stat; - // check GPS fix - stat = fona.GPSstatus(); - if (stat < 0) - Serial.println(F("Failed to query")); - if (stat == 0) Serial.println(F("GPS off")); - if (stat == 1) Serial.println(F("No fix")); - if (stat == 2) Serial.println(F("2D fix")); - if (stat == 3) Serial.println(F("3D fix")); - break; - } - - case 'L': { - // check for GPS location - char gpsdata[120]; - fona.getGPS(0, gpsdata, 120); - if (type == FONA808_V1) - Serial.println(F("Reply in format: mode,longitude,latitude,altitude,utctime(yyyymmddHHMMSS),ttff,satellites,speed,course")); - else - Serial.println(F("Reply in format: mode,fixstatus,utctime(yyyymmddHHMMSS),latitude,longitude,altitude,speed,course,fixmode,reserved1,HDOP,PDOP,VDOP,reserved2,view_satellites,used_satellites,reserved3,C/N0max,HPA,VPA")); - Serial.println(gpsdata); - - break; - } - - case 'E': { - flushSerial(); - if (type == FONA808_V1) { - Serial.print(F("GPS NMEA output sentences (0 = off, 34 = RMC+GGA, 255 = all)")); - } else { - Serial.print(F("On (1) or Off (0)? ")); - } - uint8_t nmeaout = readnumber(); - - // turn on NMEA output - fona.enableGPSNMEA(nmeaout); - - break; - } - - /*********************************** GPRS */ - - case 'g': { - // turn GPRS off - if (!fona.enableGPRS(false)) - Serial.println(F("Failed to turn off")); - break; - } - case 'G': { - // turn GPRS on - if (!fona.enableGPRS(true)) - Serial.println(F("Failed to turn on")); - break; - } - case 'l': { - // check for GSMLOC (requires GPRS) - uint16_t returncode; - - if (!fona.getGSMLoc(&returncode, replybuffer, 250)) - Serial.println(F("Failed!")); - if (returncode == 0) { - Serial.println(replybuffer); - } else { - Serial.print(F("Fail code #")); Serial.println(returncode); - } - - break; - } - case 'w': { - // read website URL - uint16_t statuscode; - int16_t length; - char url[80]; - - flushSerial(); - Serial.println(F("NOTE: in beta! Use small webpages to read!")); - Serial.println(F("URL to read (e.g. www.adafruit.com/testwifi/index.html):")); - Serial.print(F("http://")); readline(url, 79); - Serial.println(url); - - Serial.println(F("****")); - if (!fona.HTTP_GET_start(url, &statuscode, (uint16_t *)&length)) { - Serial.println("Failed!"); - break; - } - while (length > 0) { - while (fona.available()) { - char c = fona.read(); - - // Serial.write is too slow, we'll write directly to Serial register! -#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) - loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data register empty. */ - UDR0 = c; -#else - Serial.write(c); -#endif - length--; - if (! length) break; - } - } - Serial.println(F("\n****")); - fona.HTTP_GET_end(); - break; - } - - case 'W': { - // Post data to website - uint16_t statuscode; - int16_t length; - char url[80]; - char data[80]; - - flushSerial(); - Serial.println(F("NOTE: in beta! Use simple websites to post!")); - Serial.println(F("URL to post (e.g. httpbin.org/post):")); - Serial.print(F("http://")); readline(url, 79); - Serial.println(url); - Serial.println(F("Data to post (e.g. \"foo\" or \"{\"simple\":\"json\"}\"):")); - readline(data, 79); - Serial.println(data); - - Serial.println(F("****")); - if (!fona.HTTP_POST_start(url, F("text/plain"), (uint8_t *) data, strlen(data), &statuscode, (uint16_t *)&length)) { - Serial.println("Failed!"); - break; - } - while (length > 0) { - while (fona.available()) { - char c = fona.read(); - -#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) - loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data register empty. */ - UDR0 = c; -#else - Serial.write(c); -#endif - - length--; - if (! length) break; - } - } - Serial.println(F("\n****")); - fona.HTTP_POST_end(); - break; - } - /*****************************************/ - - case 'S': { - Serial.println(F("Creating SERIAL TUBE")); - while (1) { - while (Serial.available()) { - delay(1); - fona.write(Serial.read()); - } - if (fona.available()) { - Serial.write(fona.read()); - } - } - break; - } - - default: { - Serial.println(F("Unknown command")); - printMenu(); - break; - } - } - // flush input - flushSerial(); - while (fona.available()) { - Serial.write(fona.read()); - } - -} - -void flushSerial() { - while (Serial.available()) - Serial.read(); -} - -char readBlocking() { - while (!Serial.available()); - return Serial.read(); -} -uint16_t readnumber() { - uint16_t x = 0; - char c; - while (! isdigit(c = readBlocking())) { - //Serial.print(c); - } - Serial.print(c); - x = c - '0'; - while (isdigit(c = readBlocking())) { - Serial.print(c); - x *= 10; - x += c - '0'; - } - return x; -} - -uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout) { - uint16_t buffidx = 0; - boolean timeoutvalid = true; - if (timeout == 0) timeoutvalid = false; - - while (true) { - if (buffidx > maxbuff) { - //Serial.println(F("SPACE")); - break; - } - - while (Serial.available()) { - char c = Serial.read(); - - //Serial.print(c, HEX); Serial.print("#"); Serial.println(c); - - if (c == '\r') continue; - if (c == 0xA) { - if (buffidx == 0) // the first 0x0A is ignored - continue; - - timeout = 0; // the second 0x0A is the end of the line - timeoutvalid = true; - break; - } - buff[buffidx] = c; - buffidx++; - } - - if (timeoutvalid && timeout == 0) { - //Serial.println(F("TIMEOUT")); - break; - } - delay(1); - } - buff[buffidx] = 0; // null term - return buffidx; -} diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/GPS/.esp8266.test.skip b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/GPS/.esp8266.test.skip deleted file mode 100644 index e69de29..0000000 diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino deleted file mode 100644 index cce63d5..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino +++ /dev/null @@ -1,112 +0,0 @@ -/** - * ___ ___ _ _ _ ___ __ ___ ___ ___ ___ - * | __/ _ \| \| | /_\ ( _ )/ \( _ ) / __| _ \/ __| - * | _| (_) | .` |/ _ \ / _ \ () / _ \ | (_ | _/\__ \ - * |_| \___/|_|\_/_/ \_\ \___/\__/\___/ \___|_| |___/ - * - * This example is meant to work with the Adafruit - * FONA 808 or 3G Shield or Breakout - * - * Copyright: 2015 Adafruit - * Author: Todd Treece - * Licence: MIT - * - */ -#include "Adafruit_FONA.h" - -// standard pins for the shield, adjust as necessary -#define FONA_RX 2 -#define FONA_TX 3 -#define FONA_RST 4 - -// We default to using software serial. If you want to use hardware serial -// (because softserial isnt supported) comment out the following three lines -// and uncomment the HardwareSerial line -#include -SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); -SoftwareSerial *fonaSerial = &fonaSS; - -// Hardware serial is also possible! -// HardwareSerial *fonaSerial = &Serial1; - -Adafruit_FONA fona = Adafruit_FONA(FONA_RST); - -// Have a FONA 3G? use this object type instead -//Adafruit_FONA_3G fona = Adafruit_FONA_3G(FONA_RST); - - -void setup() { - - while (! Serial); - - Serial.begin(115200); - Serial.println(F("Adafruit FONA 808 & 3G GPS demo")); - Serial.println(F("Initializing FONA... (May take a few seconds)")); - - fonaSerial->begin(4800); - if (! fona.begin(*fonaSerial)) { - Serial.println(F("Couldn't find FONA")); - while(1); - } - Serial.println(F("FONA is OK")); - // Try to enable GPRS - - - Serial.println(F("Enabling GPS...")); - fona.enableGPS(true); -} - -void loop() { - delay(2000); - - float latitude, longitude, speed_kph, heading, speed_mph, altitude; - - // if you ask for an altitude reading, getGPS will return false if there isn't a 3D fix - boolean gps_success = fona.getGPS(&latitude, &longitude, &speed_kph, &heading, &altitude); - - if (gps_success) { - - Serial.print("GPS lat:"); - Serial.println(latitude, 6); - Serial.print("GPS long:"); - Serial.println(longitude, 6); - Serial.print("GPS speed KPH:"); - Serial.println(speed_kph); - Serial.print("GPS speed MPH:"); - speed_mph = speed_kph * 0.621371192; - Serial.println(speed_mph); - Serial.print("GPS heading:"); - Serial.println(heading); - Serial.print("GPS altitude:"); - Serial.println(altitude); - - } else { - Serial.println("Waiting for FONA GPS 3D fix..."); - } - - // Fona 3G doesnt have GPRSlocation :/ - if ((fona.type() == FONA3G_A) || (fona.type() == FONA3G_E)) - return; - // Check for network, then GPRS - Serial.println(F("Checking for Cell network...")); - if (fona.getNetworkStatus() == 1) { - // network & GPRS? Great! Print out the GSM location to compare - boolean gsmloc_success = fona.getGSMLoc(&latitude, &longitude); - - if (gsmloc_success) { - Serial.print("GSMLoc lat:"); - Serial.println(latitude, 6); - Serial.print("GSMLoc long:"); - Serial.println(longitude, 6); - } else { - Serial.println("GSM location failed..."); - Serial.println(F("Disabling GPRS")); - fona.enableGPRS(false); - Serial.println(F("Enabling GPRS")); - if (!fona.enableGPRS(true)) { - Serial.println(F("Failed to turn GPRS on")); - } - } - } -} - diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/IncomingCall/.esp8266.test.skip b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/IncomingCall/.esp8266.test.skip deleted file mode 100644 index e69de29..0000000 diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino deleted file mode 100644 index 8dba308..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino +++ /dev/null @@ -1,62 +0,0 @@ -// FONA Incoming Call Number Example -// Listens for a call and displays the phone number of the caller (if available). -// Use this example to add phone call detection to your own FONA sketch. -#include "Adafruit_FONA.h" - -// Pins which are connected to the FONA. -// Note that this is different from FONAtest! -#define FONA_RX 3 -#define FONA_TX 4 -#define FONA_RST 5 - -// Note you need to map interrupt number to pin number -// for your board. On an Uno & Mega interrupt 0 is -// digital pin 2, and on a Leonardo interrupt 0 is -// digital pin 3. See this page for a complete table: -// http://arduino.cc/en/Reference/attachInterrupt -// Make sure this interrupt pin is connected to FONA RI! -#define FONA_RI_INTERRUPT 0 - -// We default to using software serial. If you want to use hardware serial -// (because softserial isnt supported) comment out the following three lines -// and uncomment the HardwareSerial line -#include -SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); -SoftwareSerial *fonaSerial = &fonaSS; - -// Hardware serial is also possible! -// HardwareSerial *fonaSerial = &Serial1; - -Adafruit_FONA fona = Adafruit_FONA(FONA_RST); - -void setup() { - Serial.begin(115200); - Serial.println(F("FONA incoming call example")); - Serial.println(F("Initializing....(May take 3 seconds)")); - - fonaSerial->begin(4800); - if (! fona.begin(*fonaSerial)) { - Serial.println(F("Couldn't find FONA")); - while(1); - } - Serial.println(F("FONA is OK")); - - // Enable incoming call notification. - if(fona.callerIdNotification(true, FONA_RI_INTERRUPT)) { - Serial.println(F("Caller id notification enabled.")); - } - else { - Serial.println(F("Caller id notification disabled")); - } -} - -void loop(){ - // Create a small string buffer to hold incoming call number. - char phone[32] = {0}; - // Check for an incoming call. Will return true if a call is incoming. - if(fona.incomingCallNumber(phone)){ - Serial.println(F("RING!")); - Serial.print(F("Phone Number: ")); - Serial.println(phone); - } -} diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/FONAConfig.h b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/FONAConfig.h deleted file mode 100644 index 5fa3e13..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/FONAConfig.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * FONAConfig.h -- compile-time configuration - * This is part of the library for the Adafruit FONA Cellular Module - * - * Designed specifically to work with the Adafruit FONA - * ----> https://www.adafruit.com/products/1946 - * ----> https://www.adafruit.com/products/1963 - * ----> http://www.adafruit.com/products/2468 - * ----> http://www.adafruit.com/products/2542 - * - * Adafruit invests time and resources providing this open source code, - * please support Adafruit and open-source hardware by purchasing - * products from Adafruit! - * - * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in - * the Adafruit_FONA_Library and released under the - * BSD license, all text above must be included in any redistribution. - * - * Created on: Jan 16, 2016 - * Author: Pat Deegan - */ - -#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONACONFIG_H_ -#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONACONFIG_H_ - -/* ADAFRUIT_FONA_DEBUG - * When defined, will cause extensive debug output on the - * DebugStream set in the appropriate platform/ header. - */ - -#define ADAFRUIT_FONA_DEBUG - - -#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONACONFIG_H_ */ diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h deleted file mode 100644 index f8fe878..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * FONAExtIncludes.h -- system-wide includes - * This is part of the library for the Adafruit FONA Cellular Module - * - * Designed specifically to work with the Adafruit FONA - * ----> https://www.adafruit.com/products/1946 - * ----> https://www.adafruit.com/products/1963 - * ----> http://www.adafruit.com/products/2468 - * ----> http://www.adafruit.com/products/2542 - * - * Adafruit invests time and resources providing this open source code, - * please support Adafruit and open-source hardware by purchasing - * products from Adafruit! - * - * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in - * the Adafruit_FONA_Library and released under the - * BSD license, all text above must be included in any redistribution. - * - * Created on: Jan 16, 2016 - * Author: Pat Deegan - */ - - -#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONAEXTINCLUDES_H_ -#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONAEXTINCLUDES_H_ - - -#include "FONAConfig.h" -// include any system-wide includes required here - - - -#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONAEXTINCLUDES_H_ */ diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h deleted file mode 100644 index 85bc8fe..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * FONAPlatStd.h -- standard AVR/Arduino platform. - * - * This is part of the library for the Adafruit FONA Cellular Module - * - * Designed specifically to work with the Adafruit FONA - * ----> https://www.adafruit.com/products/1946 - * ----> https://www.adafruit.com/products/1963 - * ----> http://www.adafruit.com/products/2468 - * ----> http://www.adafruit.com/products/2542 - * - * Adafruit invests time and resources providing this open source code, - * please support Adafruit and open-source hardware by purchasing - * products from Adafruit! - * - * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in - * the Adafruit_FONA_Library and released under the - * BSD license, all text above must be included in any redistribution. - * - * Created on: Jan 16, 2016 - * Author: Pat Deegan - */ - - -#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATSTD_H_ -#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATSTD_H_ - -#include "../FONAConfig.h" - - -#if (ARDUINO >= 100) - #include "Arduino.h" - #if !defined(__SAM3X8E__) && !defined(ARDUINO_ARCH_SAMD) // Arduino Due doesn't support #include - #endif -#else - #include "WProgram.h" - #include -#endif - -#include - - -// DebugStream sets the Stream output to use -// for debug (only applies when ADAFRUIT_FONA_DEBUG -// is defined in config) -#define DebugStream Serial - -#ifdef ADAFRUIT_FONA_DEBUG -// need to do some debugging... -#define DEBUG_PRINT(...) DebugStream.print(__VA_ARGS__) -#define DEBUG_PRINTLN(...) DebugStream.println(__VA_ARGS__) -#endif - -// a few typedefs to keep things portable -typedef Stream FONAStreamType; -typedef const __FlashStringHelper * FONAFlashStringPtr; - -#define prog_char char PROGMEM - -#define prog_char_strcmp(a, b) strcmp_P((a), (b)) -// define prog_char_strncmp(a, b, c) strncmp_P((a), (b), (c)) -#define prog_char_strstr(a, b) strstr_P((a), (b)) -#define prog_char_strlen(a) strlen_P((a)) -#define prog_char_strcpy(to, fromprogmem) strcpy_P((to), (fromprogmem)) -//define prog_char_strncpy(to, from, len) strncpy_P((to), (fromprogmem), (len)) - -#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATSTD_H_ */ diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h deleted file mode 100644 index 0bf98d0..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * FONAPlatform.h -- platform definitions includes. - * - * This is part of the library for the Adafruit FONA Cellular Module - * - * Designed specifically to work with the Adafruit FONA - * ----> https://www.adafruit.com/products/1946 - * ----> https://www.adafruit.com/products/1963 - * ----> http://www.adafruit.com/products/2468 - * ----> http://www.adafruit.com/products/2542 - * - * Adafruit invests time and resources providing this open source code, - * please support Adafruit and open-source hardware by purchasing - * products from Adafruit! - * - * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in - * the Adafruit_FONA_Library and released under the - * BSD license, all text above must be included in any redistribution. - * - * Created on: Jan 16, 2016 - * Author: Pat Deegan - */ - - -#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATFORM_H_ -#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATFORM_H_ - -#include "../FONAConfig.h" - -// only "standard" config supported in this release -- namely AVR-based arduino type affairs -#include "FONAPlatStd.h" - - - -#ifndef DEBUG_PRINT -// debug is disabled - -#define DEBUG_PRINT(...) -#define DEBUG_PRINTLN(...) - -#endif - - -#ifndef prog_char_strcmp -#define prog_char_strcmp(a, b) strcmp((a), (b)) -#endif - -#ifndef prog_char_strstr -#define prog_char_strstr(a, b) strstr((a), (b)) -#endif - -#ifndef prog_char_strlen -#define prog_char_strlen(a) strlen((a)) -#endif - - -#ifndef prog_char_strcpy -#define prog_char_strcpy(to, fromprogmem) strcpy((to), (fromprogmem)) -#endif - - -#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATFORM_H_ */ diff --git a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/library.properties b/feather_sensor_transmit/libraries/Adafruit_FONA_Library/library.properties deleted file mode 100644 index bb7099c..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_FONA_Library/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=Adafruit FONA Library -version=1.3.2 -author=Adafruit -maintainer=Adafruit -sentence=Arduino library for the Adafruit FONA -paragraph=Arduino library for the Adafruit FONA -category=Communication -url=https://github.com/adafruit/Adafruit_FONA_Library -architectures=* diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp deleted file mode 100644 index 9448278..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp +++ /dev/null @@ -1,4 +0,0 @@ -#include "Adafruit_SleepyDog.h" - -// Global instance of the main class for sketches to use. -WatchdogType Watchdog; diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h deleted file mode 100644 index 4cdf4b4..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef ADAFRUIT_SLEEPYDOG_H -#define ADAFRUIT_SLEEPYDOG_H - -// Platform-specific code goes below. Each #ifdef should check for the presence -// of their platform and pull in the appropriate watchdog implementation type, -// then typedef it to WatchdogType so the .cpp file can create a global instance. -#if defined(ARDUINO_ARCH_AVR) || defined(__AVR__) - #include "utility/WatchdogAVR.h" - typedef WatchdogAVR WatchdogType; -#elif defined(ARDUINO_ARCH_SAMD) - // Arduino Zero / ATSAMD series CPU watchdog support. - #include "utility/WatchdogSAMD.h" - typedef WatchdogSAMD WatchdogType; -#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) - // Teensy 3.x watchdog support. - #include "utility/WatchdogKinetisK.h" - typedef WatchdogKinetisKseries WatchdogType; -#elif defined(__MKL26Z64__) - // Teensy LC watchdog support. - #include "utility/WatchdogKinetisL.h" - typedef WatchdogKinetisLseries WatchdogType; -#else - #error Unsupported platform for the Adafruit Watchdog library! -#endif - -extern WatchdogType Watchdog; - -#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/LICENSE b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/LICENSE deleted file mode 100644 index 04ebb92..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Adafruit Industries - -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/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/README.md b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/README.md deleted file mode 100644 index 3aa268a..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# Adafruit SleepyDog Arduino Library - -Arduino library to use the watchdog timer for system reset and low power sleep. - -Currently supports the following hardware: -* Arduino Uno or compatible (ATmega328P). diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino deleted file mode 100644 index 8d47041..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino +++ /dev/null @@ -1,62 +0,0 @@ -// Adafruit Watchdog Library Basic Usage Example -// -// Simple example of how to use the watchdog library. -// -// Author: Tony DiCola - -#include - -void setup() { - Serial.begin(115200); - while (!Serial) ; // wait for Arduino Serial Monitor (native USB boards) - Serial.println("Adafruit Watchdog Library Demo!"); - Serial.println(); - - // First a normal example of using the watchdog timer. - // Enable the watchdog by calling Watchdog.enable() as below. This will turn - // on the watchdog timer with a ~4 second timeout before reseting the Arduino. - // The estimated actual milliseconds before reset (in milliseconds) is returned. - // Make sure to reset the watchdog before the countdown expires or the Arduino - // will reset! - int countdownMS = Watchdog.enable(4000); - Serial.print("Enabled the watchdog with max countdown of "); - Serial.print(countdownMS, DEC); - Serial.println(" milliseconds!"); - Serial.println(); - - // Now loop a few times and periodically reset the watchdog. - Serial.println("Looping ten times while resetting the watchdog..."); - for (int i = 1; i <= 10; ++i) { - Serial.print("Loop #"); Serial.println(i, DEC); - delay(1000); - // Reset the watchdog with every loop to make sure the sketch keeps running. - // If you comment out this call watch what happens after about 4 iterations! - Watchdog.reset(); - } - Serial.println(); - - // Disable the watchdog entirely by calling Watchdog.disable(); - Watchdog.disable(); - - // Finally demonstrate the watchdog resetting by enabling it for a shorter - // period of time and waiting a long time without a reset. Notice you can pass - // a _maximum_ countdown time (in milliseconds) to the enable call. The library - // will try to use that value as the countdown, but it might pick a smaller - // value if the hardware doesn't support it. The actual countdown value will - // be returned so you can see what it is. - countdownMS = Watchdog.enable(4000); - Serial.print("Get ready, the watchdog will reset in "); - Serial.print(countdownMS, DEC); - Serial.println(" milliseconds!"); - Serial.println(); - delay(countdownMS+1000); - - // Execution will never get here because the watchdog resets the Arduino! -} - -void loop() { - // We'll never actually get to the loop because the watchdog will reset in - // the setup function. - Serial.println("You shouldn't see this message."); - delay(1000); -} diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino deleted file mode 100644 index d8eab80..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino +++ /dev/null @@ -1,37 +0,0 @@ -// Adafruit Watchdog Library Sleep Example -// -// Simple example of how to do low power sleep with the watchdog timer. -// -// Author: Tony DiCola - -#include - -void setup() { - Serial.begin(115200); - while (!Serial) ; // wait for Arduino Serial Monitor (native USB boards) - Serial.println("Adafruit Watchdog Library Sleep Demo!"); - Serial.println(); -} - -void loop() { - Serial.println("Going to sleep in one second..."); - delay(1000); - - // To enter low power sleep mode call Watchdog.sleep() like below - // and the watchdog will allow low power sleep for as long as possible. - // The actual amount of time spent in sleep will be returned (in - // milliseconds). - int sleepMS = Watchdog.sleep(); - - // Alternatively you can provide a millisecond value to specify - // how long you'd like the chip to sleep, but the hardware only - // supports a limited range of values so the actual sleep time might - // be smaller. The time spent in sleep will be returned (in - // milliseconds). - // int sleepMS = Watchdog.sleep(1000); // Sleep for up to 1 second. - - Serial.print("I'm awake now! I slept for "); - Serial.print(sleepMS, DEC); - Serial.println(" milliseconds."); - Serial.println(); -} diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/library.properties b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/library.properties deleted file mode 100644 index c41d74b..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=Adafruit SleepyDog Library -version=1.1.1 -author=Adafruit -maintainer=Adafruit -sentence=Arduino library to use the watchdog timer for system reset and low power sleep. -paragraph=Arduino library to use the watchdog timer for system reset and low power sleep. -category=Other -url=https://github.com/adafruit/Adafruit_SleepyDog -architectures=* diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp deleted file mode 100644 index 3355c13..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp +++ /dev/null @@ -1,137 +0,0 @@ -// Be careful to use a platform-specific conditional include to only make the -// code visible for the appropriate platform. Arduino will try to compile and -// link all .cpp files regardless of platform. -#if defined(ARDUINO_ARCH_AVR) || defined(__AVR__) - -#include -#include -#include -#include - -#include "WatchdogAVR.h" - -// Define watchdog timer interrupt. -ISR(WDT_vect) -{ - // Nothing needs to be done, however interrupt handler must be defined to - // prevent a reset. -} - -int WatchdogAVR::enable(int maxPeriodMS) { - // Pick the closest appropriate watchdog timer value. - int actualMS; - _setPeriod(maxPeriodMS, _wdto, actualMS); - // Enable the watchdog and return the actual countdown value. - wdt_enable(_wdto); - return actualMS; -} - -void WatchdogAVR::reset() { - // Reset the watchdog. - wdt_reset(); -} - -void WatchdogAVR::disable() { - // Disable the watchdog and clear any saved watchdog timer value. - wdt_disable(); - _wdto = -1; -} - -int WatchdogAVR::sleep(int maxPeriodMS) { - // Pick the closest appropriate watchdog timer value. - int sleepWDTO, actualMS; - _setPeriod(maxPeriodMS, sleepWDTO, actualMS); - - // Build watchdog prescaler register value before timing critical code. - uint8_t wdps = ((sleepWDTO & 0x08 ? 1 : 0) << WDP3) | - ((sleepWDTO & 0x04 ? 1 : 0) << WDP2) | - ((sleepWDTO & 0x02 ? 1 : 0) << WDP1) | - ((sleepWDTO & 0x01 ? 1 : 0) << WDP0); - - // The next section is timing critical so interrupts are disabled. - cli(); - // First clear any previous watchdog reset. - MCUSR &= ~(1<= 8000) || (maxMS == 0)) { - wdto = WDTO_8S; - actualMS = 8000; - } - else if (maxMS >= 4000) { - wdto = WDTO_4S; - actualMS = 4000; - } - else if (maxMS >= 2000) { - wdto = WDTO_2S; - actualMS = 2000; - } - else if (maxMS >= 1000) { - wdto = WDTO_1S; - actualMS = 1000; - } - else if (maxMS >= 500) { - wdto = WDTO_500MS; - actualMS = 500; - } - else if (maxMS >= 250) { - wdto = WDTO_250MS; - actualMS = 250; - } - else if (maxMS >= 120) { - wdto = WDTO_120MS; - actualMS = 120; - } - else if (maxMS >= 60) { - wdto = WDTO_60MS; - actualMS = 60; - } - else if (maxMS >= 30) { - wdto = WDTO_30MS; - actualMS = 30; - } - else { - wdto = WDTO_15MS; - actualMS = 15; - } -} - -#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h deleted file mode 100644 index 9753b08..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef WATCHDOGAVR_H -#define WATCHDOGAVR_H - -class WatchdogAVR { -public: - WatchdogAVR(): - _wdto(-1) - {} - - // Enable the watchdog timer to reset the machine after a period of time - // without any calls to reset(). The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware does - // not support the exact desired value. - // - // The actual period (in milliseconds) before a watchdog timer reset is - // returned. - int enable(int maxPeriodMS = 0); - - // Reset or 'kick' the watchdog timer to prevent a reset of the device. - void reset(); - - // Completely disable the watchdog timer. - void disable(); - - // Enter the lowest power sleep mode (using the watchdog timer) for the - // desired period of time. The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware does - // not support the exact desired value - // - // The actual period (in milliseconds) that the hardware was asleep will be - // returned. - int sleep(int maxPeriodMS = 0); - -private: - // Pick the closest (but not higher) watchdog timer value from the provided - // maximum period. Sets wdto to the chosen period value suitable for - // passing to wdt_enable(), and actualMS to the chosen period value in - // milliseconds. A max value of 0 will pick the longest value possible. - void _setPeriod(int maxMS, int &wdto, int &actualMS); - - // Keep the last selected watchdog timer period so that the watchdog can be - // re-enabled at that rate after sleep. A value of -1 means no watchdog - // timer was enabled. - int _wdto; -}; - -#endif \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp deleted file mode 100644 index 9705859..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp +++ /dev/null @@ -1,104 +0,0 @@ -// Be careful to use a platform-specific conditional include to only make the -// code visible for the appropriate platform. Arduino will try to compile and -// link all .cpp files regardless of platform. -#if defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) - -#include -#include "WatchdogKinetisK.h" - -static void one_bus_cycle(void) __attribute__((always_inline)); -static void watchdog_config(int cfg, int val); - -// Enable the watchdog timer to reset the machine after a period of time -// without any calls to reset(). The passed in period (in milliseconds) is -// just a suggestion and a lower value might be picked if the hardware does -// not support the exact desired value. -// -// The actual period (in milliseconds) before a watchdog timer reset is -// returned. -int WatchdogKinetisKseries::enable(int maxPeriodMS) -{ - if (maxPeriodMS < 4) { - maxPeriodMS = 8000; // default is 8 seconds - } - if (setting != maxPeriodMS) { - watchdog_config(WDOG_STCTRLH_WDOGEN, maxPeriodMS); - setting = maxPeriodMS; - } - return maxPeriodMS; -} - -// Reset or 'kick' the watchdog timer to prevent a reset of the device. -void WatchdogKinetisKseries::reset() -{ - __disable_irq(); - WDOG_REFRESH = 0xA602; - WDOG_REFRESH = 0xB480; - __enable_irq(); -} - -// Completely disable the watchdog timer. -void WatchdogKinetisKseries::disable() -{ - if (setting > 0) { - watchdog_config(0, 4); - setting = 0; - } -} - -// Enter the lowest power sleep mode for the desired period of time. The -// passed in period (in milliseconds) is just a suggestion and a lower value -// might be picked if the hardware does not support the exact desired value -// -// The actual period (in milliseconds) that the hardware was asleep will be -// returned. -int WatchdogKinetisKseries::sleep(int maxPeriodMS) -{ - if (maxPeriodMS <= 0) return 0; - // TODO.... - return 0; -} - -static void watchdog_config(int cfg, int val) -{ - __disable_irq(); - WDOG_UNLOCK = WDOG_UNLOCK_SEQ1; - WDOG_UNLOCK = WDOG_UNLOCK_SEQ2; - one_bus_cycle(); - WDOG_STCTRLH = cfg | WDOG_STCTRLH_ALLOWUPDATE; - WDOG_TOVALH = val >> 16; - WDOG_TOVALL = val; - WDOG_PRESC = 0; - __enable_irq(); - for (int i=0; i < 256; i++) { - one_bus_cycle(); - } -} - -static void one_bus_cycle(void) -{ - __asm__ volatile ("nop"); - #if (F_CPU / F_BUS) > 1 - __asm__ volatile ("nop"); - #endif - #if (F_CPU / F_BUS) > 2 - __asm__ volatile ("nop"); - #endif - #if (F_CPU / F_BUS) > 3 - __asm__ volatile ("nop"); - #endif - #if (F_CPU / F_BUS) > 4 - __asm__ volatile ("nop"); - #endif - #if (F_CPU / F_BUS) > 5 - __asm__ volatile ("nop"); - #endif - #if (F_CPU / F_BUS) > 6 - __asm__ volatile ("nop"); - #endif - #if (F_CPU / F_BUS) > 7 - __asm__ volatile ("nop"); - #endif -} - -#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h deleted file mode 100644 index e09a0c2..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef WATCHDOGKINETISK_H -#define WATCHDOGKINETISK_H - -class WatchdogKinetisKseries { -public: - WatchdogKinetisKseries(): setting(0) {} - - // Enable the watchdog timer to reset the machine after a period of time - // without any calls to reset(). The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware does - // not support the exact desired value. - // - // The actual period (in milliseconds) before a watchdog timer reset is - // returned. - int enable(int maxPeriodMS = 0); - - // Reset or 'kick' the watchdog timer to prevent a reset of the device. - void reset(); - - // Completely disable the watchdog timer. - void disable(); - - // Enter the lowest power sleep mode (using the watchdog timer) for the - // desired period of time. The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware does - // not support the exact desired value - // - // The actual period (in milliseconds) that the hardware was asleep will be - // returned. - // - // NOTE: This is currently not implemented on the SAMD21! - int sleep(int maxPeriodMS = 0); - -private: - int setting; -}; - -#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp deleted file mode 100644 index 501e9c0..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp +++ /dev/null @@ -1,74 +0,0 @@ -// Be careful to use a platform-specific conditional include to only make the -// code visible for the appropriate platform. Arduino will try to compile and -// link all .cpp files regardless of platform. -#if defined(__MKL26Z64__) - -#include -#include "WatchdogKinetisL.h" - -// Normally the watchdog is disabled at startup. This removes the startup -// code. The watchdog will be active with 1024 ms timeout. Hopefully the -// user will configure the watchdog and begin resetting it before it causes -// a reboot. There is no way to start up without the watchdog and then -// enable it later... -extern "C" void startup_early_hook(void) {} - - -// Enable the watchdog timer to reset the machine after a period of time -// without any calls to reset(). The passed in period (in milliseconds) is -// just a suggestion and a lower value might be picked if the hardware does -// not support the exact desired value. -// -// The actual period (in milliseconds) before a watchdog timer reset is -// returned. -int WatchdogKinetisLseries::enable(int maxPeriodMS) -{ - // The watchdog can only be programmed once. Then it's forever - // locked to this setting (until the chip reboots). - if (maxPeriodMS <= 0 || maxPeriodMS > 256) { - SIM_COPC = 12; - } else if (maxPeriodMS > 32) { - SIM_COPC = 8; - } else { - SIM_COPC = 4; - } - // Read the actual setting. - int val = SIM_COPC & 12; - if (val == 12) return 1024; - if (val == 8) return 256; - return 32; -} - -// Reset or 'kick' the watchdog timer to prevent a reset of the device. -void WatchdogKinetisLseries::reset() -{ - __disable_irq(); - SIM_SRVCOP = 0x55; - SIM_SRVCOP = 0xAA; - __enable_irq(); -} - -// Completely disable the watchdog timer. -void WatchdogKinetisLseries::disable() -{ - // no can do.... - // The watchdog timer in this chip is write-once. - // The chip boots up with the watchdog at 1024 ms. - // You only get to configure it once. Then it - // remains locked to that setting, until a reboot. -} - -// Enter the lowest power sleep mode for the desired period of time. The -// passed in period (in milliseconds) is just a suggestion and a lower value -// might be picked if the hardware does not support the exact desired value -// -// The actual period (in milliseconds) that the hardware was asleep will be -// returned. -int WatchdogKinetisLseries::sleep(int maxPeriodMS) -{ - if (maxPeriodMS <= 0) return 0; - // TODO.... - return 0; -} - -#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h deleted file mode 100644 index 3c68d5e..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef WATCHDOGKINETISL_H -#define WATCHDOGKINETISL_H - -class WatchdogKinetisLseries { -public: - WatchdogKinetisLseries() {} - - // Enable the watchdog timer to reset the machine after a period of time - // without any calls to reset(). The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware does - // not support the exact desired value. - // - // The actual period (in milliseconds) before a watchdog timer reset is - // returned. - int enable(int maxPeriodMS = 0); - - // Reset or 'kick' the watchdog timer to prevent a reset of the device. - void reset(); - - // Completely disable the watchdog timer. - void disable(); - - // Enter the lowest power sleep mode (using the watchdog timer) for the - // desired period of time. The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware does - // not support the exact desired value - // - // The actual period (in milliseconds) that the hardware was asleep will be - // returned. - // - // NOTE: This is currently not implemented on the SAMD21! - int sleep(int maxPeriodMS = 0); -}; - -#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp deleted file mode 100644 index d21d9a9..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp +++ /dev/null @@ -1,175 +0,0 @@ -// Requires Adafruit_ASFcore library! - -// Be careful to use a platform-specific conditional include to only make the -// code visible for the appropriate platform. Arduino will try to compile and -// link all .cpp files regardless of platform. -#if defined(ARDUINO_ARCH_SAMD) - -#include -#include -#include -#include "WatchdogSAMD.h" - -int WatchdogSAMD::enable(int maxPeriodMS, bool isForSleep) { - // Enable the watchdog with a period up to the specified max period in - // milliseconds. - - // Review the watchdog section from the SAMD21 datasheet section 17: - // http://www.atmel.com/images/atmel-42181-sam-d21_datasheet.pdf - - int cycles, actualMS; - uint8_t bits; - - if(!_initialized) _initialize_wdt(); - - WDT->CTRL.reg = 0; // Disable watchdog for config - while(WDT->STATUS.bit.SYNCBUSY); - - // You'll see some occasional conversion here compensating between - // milliseconds (1000 Hz) and WDT clock cycles (~1024 Hz). The low- - // power oscillator used by the WDT ostensibly runs at 32,768 Hz with - // a 1:32 prescale, thus 1024 Hz, though probably not super precise. - - if((maxPeriodMS >= 16000) || !maxPeriodMS) { - cycles = 16384; - bits = 0xB; - } else { - cycles = (maxPeriodMS * 1024L + 500) / 1000; // ms -> WDT cycles - if(cycles >= 8192) { - cycles = 8192; - bits = 0xA; - } else if(cycles >= 4096) { - cycles = 4096; - bits = 0x9; - } else if(cycles >= 2048) { - cycles = 2048; - bits = 0x8; - } else if(cycles >= 1024) { - cycles = 1024; - bits = 0x7; - } else if(cycles >= 512) { - cycles = 512; - bits = 0x6; - } else if(cycles >= 256) { - cycles = 256; - bits = 0x5; - } else if(cycles >= 128) { - cycles = 128; - bits = 0x4; - } else if(cycles >= 64) { - cycles = 64; - bits = 0x3; - } else if(cycles >= 32) { - cycles = 32; - bits = 0x2; - } else if(cycles >= 16) { - cycles = 16; - bits = 0x1; - } else { - cycles = 8; - bits = 0x0; - } - } - - // Watchdog timer on SAMD is a slightly different animal than on AVR. - // On AVR, the WTD timeout is configured in one register and then an - // interrupt can optionally be enabled to handle the timeout in code - // (as in waking from sleep) vs resetting the chip. Easy. - // On SAMD, when the WDT fires, that's it, the chip's getting reset. - // Instead, it has an "early warning interrupt" with a different set - // interval prior to the reset. For equivalent behavior to the AVR - // library, this requires a slightly different configuration depending - // whether we're coming from the sleep() function (which needs the - // interrupt), or just enable() (no interrupt, we want the chip reset - // unless the WDT is cleared first). In the sleep case, 'windowed' - // mode is used in order to allow access to the longest available - // sleep interval (about 16 sec); the WDT 'period' (when a reset - // occurs) follows this and is always just set to the max, since the - // interrupt will trigger first. In the enable case, windowed mode - // is not used, the WDT period is set and that's that. - // The 'isForSleep' argument determines which behavior is used; - // this isn't present in the AVR code, just here. It defaults to - // 'false' so existing Arduino code works as normal, while the sleep() - // function (later in this file) explicitly passes 'true' to get the - // alternate behavior. - - if(isForSleep) { - WDT->INTENSET.bit.EW = 1; // Enable early warning interrupt - WDT->CONFIG.bit.PER = 0xB; // Period = max - WDT->CONFIG.bit.WINDOW = bits; // Set time of interrupt - WDT->CTRL.bit.WEN = 1; // Enable window mode - while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write - } else { - WDT->INTENCLR.bit.EW = 1; // Disable early warning interrupt - WDT->CONFIG.bit.PER = bits; // Set period for chip reset - WDT->CTRL.bit.WEN = 0; // Disable window mode - while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write - } - - actualMS = (cycles * 1000L + 512) / 1024; // WDT cycles -> ms - - reset(); // Clear watchdog interval - WDT->CTRL.bit.ENABLE = 1; // Start watchdog now! - while(WDT->STATUS.bit.SYNCBUSY); - - return actualMS; -} - -void WatchdogSAMD::reset() { - // Write the watchdog clear key value (0xA5) to the watchdog - // clear register to clear the watchdog timer and reset it. - WDT->CLEAR.reg = WDT_CLEAR_CLEAR_KEY; - while(WDT->STATUS.bit.SYNCBUSY); -} - -void WatchdogSAMD::disable() { - WDT->CTRL.bit.ENABLE = 0; - while(WDT->STATUS.bit.SYNCBUSY); -} - -void WDT_Handler(void) { - // ISR for watchdog early warning, DO NOT RENAME! - WDT->CTRL.bit.ENABLE = 0; // Disable watchdog - while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write - WDT->INTFLAG.bit.EW = 1; // Clear interrupt flag -} - -int WatchdogSAMD::sleep(int maxPeriodMS) { - - int actualPeriodMS = enable(maxPeriodMS, true); // true = for sleep - - system_set_sleepmode(SYSTEM_SLEEPMODE_STANDBY); // Deepest sleep - system_sleep(); - // Code resumes here on wake (WDT early warning interrupt) - - return actualPeriodMS; -} - -void WatchdogSAMD::_initialize_wdt() { - // One-time initialization of watchdog timer. - // Insights from rickrlh and rbrucemtl in Arduino forum! - - // Generic clock generator 2, divisor = 32 (2^(DIV+1)) - GCLK->GENDIV.reg = GCLK_GENDIV_ID(2) | GCLK_GENDIV_DIV(4); - // Enable clock generator 2 using low-power 32KHz oscillator. - // With /32 divisor above, this yields 1024Hz(ish) clock. - GCLK->GENCTRL.reg = GCLK_GENCTRL_ID(2) | - GCLK_GENCTRL_GENEN | - GCLK_GENCTRL_SRC_OSCULP32K | - GCLK_GENCTRL_DIVSEL; - while(GCLK->STATUS.bit.SYNCBUSY); - // WDT clock = clock gen 2 - GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID_WDT | - GCLK_CLKCTRL_CLKEN | - GCLK_CLKCTRL_GEN_GCLK2; - - // Enable WDT early-warning interrupt - NVIC_DisableIRQ(WDT_IRQn); - NVIC_ClearPendingIRQ(WDT_IRQn); - NVIC_SetPriority(WDT_IRQn, 0); // Top priority - NVIC_EnableIRQ(WDT_IRQn); - - _initialized = true; -} - -#endif diff --git a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h b/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h deleted file mode 100644 index 8b03c27..0000000 --- a/feather_sensor_transmit/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef WATCHDOGSAMD_H -#define WATCHDOGSAMD_H - -class WatchdogSAMD { -public: - WatchdogSAMD(): - _initialized(false) - {} - - // Enable the watchdog timer to reset the machine after a period of time - // without any calls to reset(). The passed in period (in milliseconds) - // is just a suggestion and a lower value might be picked if the hardware - // does not support the exact desired value. - // User code should NOT set the 'isForSleep' argument either way -- - // it's used internally by the library, but your sketch should leave this - // out when calling enable(), just let the default have its way. - // - // The actual period (in milliseconds) before a watchdog timer reset is - // returned. - int enable(int maxPeriodMS = 0, bool isForSleep = false); - - // Reset or 'kick' the watchdog timer to prevent a reset of the device. - void reset(); - - // Completely disable the watchdog timer. - void disable(); - - // Enter the lowest power sleep mode (using the watchdog timer) for the - // desired period of time. The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware - // does not support the exact desired value - // - // The actual period (in milliseconds) that the hardware was asleep will be - // returned. - int sleep(int maxPeriodMS = 0); - -private: - void _initialize_wdt(); - - bool _initialized; -}; - -#endif diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/.gitignore b/feather_sensor_transmit/libraries/ArduinoHttpClient/.gitignore deleted file mode 100644 index 89d225a..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.development -examples/node_test_server/node_modules/ diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/CHANGELOG.md b/feather_sensor_transmit/libraries/ArduinoHttpClient/CHANGELOG.md deleted file mode 100644 index 5645508..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/CHANGELOG.md +++ /dev/null @@ -1,25 +0,0 @@ -## ArduinoHttpClient 0.3.1 - 2017.09.25 - -* Changed examples to support Arduino Create secret tabs -* Increase WebSocket secrect-key length to 24 characters - -## ArduinoHttpClient 0.3.0 - 2017.04.20 - -* Added support for PATCH operations -* Added support for chunked response bodies -* Added new beginBody API - -## ArduinoHttpClient 0.2.0 - 2017.01.12 - -* Added PATCH method -* Added basic auth example -* Added custom header example - -## ArduinoHttpClient 0.1.1 - 2016.12.16 - -* More robust response parser - -## ArduinoHttpClient 0.1.0 - 2016.07.05 - -* Initial release - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/README.md b/feather_sensor_transmit/libraries/ArduinoHttpClient/README.md deleted file mode 100644 index 655b618..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# ArduinoHttpClient - -ArduinoHttpClient is a library to make it easier to interact with web servers from Arduino. - -Derived from [Adrian McEwen's HttpClient library](https://github.com/amcewen/HttpClient) - -## Dependencies - -- Requires a networking hardware and a library that provides transport specific `Client` instance, such as: - - [WiFi101](https://github.com/arduino-libraries/WiFi101) - - [Ethernet](https://github.com/arduino-libraries/Ethernet) - - [WiFi](https://github.com/arduino-libraries/WiFi) - - [GSM](https://github.com/arduino-libraries/GSM) - -## Usage - -In normal usage, handles the outgoing request and Host header. The returned status code is parsed for you, as is the Content-Length header (if present). - -Because it expects an object of type Client, you can use it with any of the networking classes that derive from that. Which means it will work with WiFiClient, EthernetClient and GSMClient. - -See the examples for more detail on how the library is used. - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino deleted file mode 100644 index e793d47..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino +++ /dev/null @@ -1,69 +0,0 @@ -/* - GET client with HTTP basic authentication for ArduinoHttpClient library - Connects to server once every five seconds, sends a GET request - - - - created 14 Feb 2016 - by Tom Igoe - modified 3 Jan 2017 to add HTTP basic authentication - by Sandeep Mistry - - this example is in the public domain - */ -#include -#include -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("making GET request with HTTP basic authentication"); - client.beginRequest(); - client.get("/secure"); - client.sendBasicAuth("username", "password"); // send the username and password for authentication - client.endRequest(); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - Serial.println("Wait five seconds"); - delay(5000); -} - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino deleted file mode 100644 index fa44aca..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino +++ /dev/null @@ -1,96 +0,0 @@ -/* - Custom request header example for the ArduinoHttpClient - library. This example sends a GET and a POST request with a custom header every 5 seconds. - - note: WiFi SSID and password are stored in config.h file. - If it is not present, add a new tab, call it "config.h" - and add the following variables: - char ssid[] = "ssid"; // your network SSID (name) - char pass[] = "password"; // your network password - - based on SimpleGet example by Tom Igoe - header modifications by Todd Treece - - this example is in the public domain - */ - -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - - Serial.println("making GET request"); - client.beginRequest(); - client.get("/"); - client.sendHeader("X-CUSTOM-HEADER", "custom_value"); - client.endRequest(); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("GET Status code: "); - Serial.println(statusCode); - Serial.print("GET Response: "); - Serial.println(response); - - Serial.println("Wait five seconds"); - delay(5000); - - Serial.println("making POST request"); - String postData = "name=Alice&age=12"; - client.beginRequest(); - client.post("/"); - client.sendHeader(HTTP_HEADER_CONTENT_TYPE, "application/x-www-form-urlencoded"); - client.sendHeader(HTTP_HEADER_CONTENT_LENGTH, postData.length()); - client.sendHeader("X-CUSTOM-HEADER", "custom_value"); - client.endRequest(); - client.write((const byte*)postData.c_str(), postData.length()); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("POST Status code: "); - Serial.println(statusCode); - Serial.print("POST Response: "); - Serial.println(response); - - Serial.println("Wait five seconds"); - delay(5000); -} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino deleted file mode 100644 index 51abd3f..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino +++ /dev/null @@ -1,107 +0,0 @@ -/* - Dweet.io GET client for ArduinoHttpClient library - Connects to dweet.io once every ten seconds, - sends a GET request and a request body. Uses SSL - - Shows how to use Strings to assemble path and parse content - from response. dweet.io expects: - https://dweet.io/get/latest/dweet/for/thingName - - For more on dweet.io, see https://dweet.io/play/ - - - - created 15 Feb 2016 - updated 16 Feb 2016 - by Tom Igoe - - this example is in the public domain -*/ -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - -const char serverAddress[] = "dweet.io"; // server address -int port = 80; -String dweetName = "scandalous-cheese-hoarder"; // use your own thing name here - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -int statusCode = 0; -String response; - -void setup() { - Serial.begin(9600); - while (!Serial); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - // assemble the path for the GET message: - String path = "/get/latest/dweet/for/" + dweetName; - - // send the GET request - Serial.println("making GET request"); - client.get(path); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - /* - Typical response is: - {"this":"succeeded", - "by":"getting", - "the":"dweets", - "with":[{"thing":"my-thing-name", - "created":"2016-02-16T05:10:36.589Z", - "content":{"sensorValue":456}}]} - - You want "content": numberValue - */ - // now parse the response looking for "content": - int labelStart = response.indexOf("content\":"); - // find the first { after "content": - int contentStart = response.indexOf("{", labelStart); - // find the following } and get what's between the braces: - int contentEnd = response.indexOf("}", labelStart); - String content = response.substring(contentStart + 1, contentEnd); - Serial.println(content); - - // now get the value after the colon, and convert to an int: - int valueStart = content.indexOf(":"); - String valueString = content.substring(valueStart + 1); - int number = valueString.toInt(); - Serial.print("Value string: "); - Serial.println(valueString); - Serial.print("Actual value: "); - Serial.println(number); - - Serial.println("Wait ten seconds\n"); - delay(10000); -} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino deleted file mode 100644 index 41c6f2f..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino +++ /dev/null @@ -1,87 +0,0 @@ -/* - Dweet.io POST client for ArduinoHttpClient library - Connects to dweet.io once every ten seconds, - sends a POST request and a request body. - - Shows how to use Strings to assemble path and body - - note: WiFi SSID and password are stored in config.h file. - If it is not present, add a new tab, call it "config.h" - and add the following variables: - char ssid[] = "ssid"; // your network SSID (name) - char pass[] = "password"; // your network password - - created 15 Feb 2016 - by Tom Igoe - - this example is in the public domain -*/ -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - -const char serverAddress[] = "dweet.io"; // server address -int port = 80; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -int statusCode = 0; -String response; - -void setup() { - Serial.begin(9600); - while(!Serial); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - // assemble the path for the POST message: - String dweetName = "scandalous-cheese-hoarder"; - String path = "/dweet/for/" + dweetName; - - String contentType = "application/json"; - - // assemble the body of the POST message: - int sensorValue = analogRead(A0); - String postData = "{\"sensorValue\":\""; - postData += sensorValue; - postData += "\"}"; - - Serial.println("making POST request"); - - // send the POST request - client.post(path, contentType, postData); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - Serial.println("Wait ten seconds\n"); - delay(10000); -} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino deleted file mode 100644 index c18ae47..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino +++ /dev/null @@ -1,102 +0,0 @@ -/* HueBlink example for ArduinoHttpClient library - - Uses ArduinoHttpClient library to control Philips Hue - For more on Hue developer API see http://developer.meethue.com - - To control a light, the Hue expects a HTTP PUT request to: - - http://hue.hub.address/api/hueUserName/lights/lightNumber/state - - The body of the PUT request looks like this: - {"on": true} or {"on":false} - - This example shows how to concatenate Strings to assemble the - PUT request and the body of the request. - - - - modified 15 Feb 2016 - by Tom Igoe (tigoe) to match new API -*/ - -#include -#include -#include -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - -int status = WL_IDLE_STATUS; // the Wifi radio's status - -char hueHubIP[] = "192.168.0.3"; // IP address of the HUE bridge -String hueUserName = "huebridgeusername"; // hue bridge username - -// make a wifi instance and a HttpClient instance: -WiFiClient wifi; -HttpClient httpClient = HttpClient(wifi, hueHubIP); - - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial); // wait for serial port to connect. - - // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to WPA SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // you're connected now, so print out the data: - Serial.print("You're connected to the network IP = "); - IPAddress ip = WiFi.localIP(); - Serial.println(ip); -} - -void loop() { - sendRequest(3, "on", "true"); // turn light on - delay(2000); // wait 2 seconds - sendRequest(3, "on", "false"); // turn light off - delay(2000); // wait 2 seconds -} - -void sendRequest(int light, String cmd, String value) { - // make a String for the HTTP request path: - String request = "/api/" + hueUserName; - request += "/lights/"; - request += light; - request += "/state/"; - - String contentType = "application/json"; - - // make a string for the JSON command: - String hueCmd = "{\"" + cmd; - hueCmd += "\":"; - hueCmd += value; - hueCmd += "}"; - // see what you assembled to send: - Serial.print("PUT request to server: "); - Serial.println(request); - Serial.print("JSON command to server: "); - - // make the PUT request to the hub: - httpClient.put(request, contentType, hueCmd); - - // read the status code and body of the response - int statusCode = httpClient.responseStatusCode(); - String response = httpClient.responseBody(); - - Serial.println(hueCmd); - Serial.print("Status code from server: "); - Serial.println(statusCode); - Serial.print("Server response: "); - Serial.println(response); - Serial.println(); -} - - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino deleted file mode 100644 index 835a26f..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino +++ /dev/null @@ -1,79 +0,0 @@ -/* - POST with headers client for ArduinoHttpClient library - Connects to server once every five seconds, sends a POST request - with custome headers and a request body - - - - created 14 Feb 2016 - by Tom Igoe - modified 18 Mar 2017 - by Sandeep Mistry - - this example is in the public domain - */ -#include -#include - -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("making POST request"); - String postData = "name=Alice&age=12"; - - client.beginRequest(); - client.post("/"); - client.sendHeader("Content-Type", "application/x-www-form-urlencoded"); - client.sendHeader("Content-Length", postData.length()); - client.sendHeader("X-Custom-Header", "custom-header-value"); - client.beginBody(); - client.print(postData); - client.endRequest(); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - Serial.println("Wait five seconds"); - delay(5000); -} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino deleted file mode 100644 index 374a145..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino +++ /dev/null @@ -1,71 +0,0 @@ -/* - Simple DELETE client for ArduinoHttpClient library - Connects to server once every five seconds, sends a DELETE request - and a request body - - - - created 14 Feb 2016 - by Tom Igoe - - this example is in the public domain - */ -#include -#include - -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("making DELETE request"); - String contentType = "application/x-www-form-urlencoded"; - String delData = "name=light&age=46"; - - client.del("/", contentType, delData); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - Serial.println("Wait five seconds"); - delay(5000); -} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino deleted file mode 100644 index 75db9a7..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino +++ /dev/null @@ -1,66 +0,0 @@ -/* - Simple GET client for ArduinoHttpClient library - Connects to server once every five seconds, sends a GET request - - - - created 14 Feb 2016 - by Tom Igoe - - this example is in the public domain - */ -#include -#include - -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("making GET request"); - client.get("/"); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - Serial.println("Wait five seconds"); - delay(5000); -} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino deleted file mode 100644 index f64b9ba..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino +++ /dev/null @@ -1,133 +0,0 @@ -// (c) Copyright 2010-2012 MCQN Ltd. -// Released under Apache License, version 2.0 -// -// Simple example to show how to use the HttpClient library -// Get's the web page given at http:// and -// outputs the content to the serial port - -#include -#include -#include - -// This example downloads the URL "http://arduino.cc/" - -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - - - -// Name of the server we want to connect to -const char kHostname[] = "arduino.cc"; -// Path to download (this is the bit after the hostname in the URL -// that you want to download -const char kPath[] = "/"; - -// Number of milliseconds to wait without receiving any data before we give up -const int kNetworkTimeout = 30*1000; -// Number of milliseconds to wait if no data is available before trying again -const int kNetworkDelay = 1000; - -WiFiClient c; -HttpClient http(c, kHostname); - -void setup() -{ - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // attempt to connect to Wifi network: - Serial.print("Attempting to connect to WPA SSID: "); - Serial.println(ssid); - while (WiFi.begin(ssid, pass) != WL_CONNECTED) { - // unsuccessful, retry in 4 seconds - Serial.print("failed ... "); - delay(4000); - Serial.print("retrying ... "); - } - - Serial.println("connected"); -} - -void loop() -{ - int err =0; - - err = http.get(kPath); - if (err == 0) - { - Serial.println("startedRequest ok"); - - err = http.responseStatusCode(); - if (err >= 0) - { - Serial.print("Got status code: "); - Serial.println(err); - - // Usually you'd check that the response code is 200 or a - // similar "success" code (200-299) before carrying on, - // but we'll print out whatever response we get - - // If you are interesting in the response headers, you - // can read them here: - //while(http.headerAvailable()) - //{ - // String headerName = http.readHeaderName(); - // String headerValue = http.readHeaderValue(); - //} - - int bodyLen = http.contentLength(); - Serial.print("Content length is: "); - Serial.println(bodyLen); - Serial.println(); - Serial.println("Body returned follows:"); - - // Now we've got to the body, so we can print it out - unsigned long timeoutStart = millis(); - char c; - // Whilst we haven't timed out & haven't reached the end of the body - while ( (http.connected() || http.available()) && - (!http.endOfBodyReached()) && - ((millis() - timeoutStart) < kNetworkTimeout) ) - { - if (http.available()) - { - c = http.read(); - // Print out this character - Serial.print(c); - - // We read something, reset the timeout counter - timeoutStart = millis(); - } - else - { - // We haven't got any data, so let's pause to allow some to - // arrive - delay(kNetworkDelay); - } - } - } - else - { - Serial.print("Getting response failed: "); - Serial.println(err); - } - } - else - { - Serial.print("Connect failed: "); - Serial.println(err); - } - http.stop(); - - // And just stop, now that we've tried a download - while(1); -} - - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino deleted file mode 100644 index 6cc3517..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino +++ /dev/null @@ -1,70 +0,0 @@ -/* - Simple POST client for ArduinoHttpClient library - Connects to server once every five seconds, sends a POST request - and a request body - - - - created 14 Feb 2016 - by Tom Igoe - - this example is in the public domain - */ -#include -#include -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("making POST request"); - String contentType = "application/x-www-form-urlencoded"; - String postData = "name=Alice&age=12"; - - client.post("/", contentType, postData); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - Serial.println("Wait five seconds"); - delay(5000); -} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino deleted file mode 100644 index 1b06105..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino +++ /dev/null @@ -1,70 +0,0 @@ -/* - Simple PUT client for ArduinoHttpClient library - Connects to server once every five seconds, sends a PUT request - and a request body - - - - created 14 Feb 2016 - by Tom Igoe - - this example is in the public domain - */ -#include -#include -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("making PUT request"); - String contentType = "application/x-www-form-urlencoded"; - String putData = "name=light&age=46"; - - client.put("/", contentType, putData); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - Serial.println("Wait five seconds"); - delay(5000); -} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino deleted file mode 100644 index baac12f..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino +++ /dev/null @@ -1,80 +0,0 @@ -/* - Simple WebSocket client for ArduinoHttpClient library - Connects to the WebSocket server, and sends a hello - message every 5 seconds - - - created 28 Jun 2016 - by Sandeep Mistry - - this example is in the public domain -*/ -#include -#include -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - -char serverAddress[] = "echo.websocket.org"; // server address -int port = 80; - -WiFiClient wifi; -WebSocketClient client = WebSocketClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -int count = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("starting WebSocket client"); - client.begin(); - - while (client.connected()) { - Serial.print("Sending hello "); - Serial.println(count); - - // send a hello # - client.beginMessage(TYPE_TEXT); - client.print("hello "); - client.print(count); - client.endMessage(); - - // increment count for next message - count++; - - // check if a message is available to be received - int messageSize = client.parseMessage(); - - if (messageSize > 0) { - Serial.println("Received a message:"); - Serial.println(client.readString()); - } - - // wait 5 seconds - delay(5000); - } - - Serial.println("disconnected"); -} - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js deleted file mode 100644 index f3dd4d8..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js +++ /dev/null @@ -1,102 +0,0 @@ -/* - Express.js GET/POST example - Shows how handle GET, POST, PUT, DELETE - in Express.js 4.0 - - created 14 Feb 2016 - by Tom Igoe -*/ - -var express = require('express'); // include express.js -var app = express(); // a local instance of it -var bodyParser = require('body-parser'); // include body-parser -var WebSocketServer = require('ws').Server // include Web Socket server - -// you need a body parser: -app.use(bodyParser.urlencoded({extended: false})); // for application/x-www-form-urlencoded - -// this runs after the server successfully starts: -function serverStart() { - var port = server.address().port; - console.log('Server listening on port '+ port); -} - -app.get('/chunked', function(request, response) { - response.write('\n'); - response.write(' `:;;;,` .:;;:. \n'); - response.write(' .;;;;;;;;;;;` :;;;;;;;;;;: TM \n'); - response.write(' `;;;;;;;;;;;;;;;` :;;;;;;;;;;;;;;; \n'); - response.write(' :;;;;;;;;;;;;;;;;;; `;;;;;;;;;;;;;;;;;; \n'); - response.write(' ;;;;;;;;;;;;;;;;;;;;; .;;;;;;;;;;;;;;;;;;;; \n'); - response.write(' ;;;;;;;;:` `;;;;;;;;; ,;;;;;;;;.` .;;;;;;;; \n'); - response.write(' .;;;;;;, :;;;;;;; .;;;;;;; ;;;;;;; \n'); - response.write(' ;;;;;; ;;;;;;; ;;;;;;, ;;;;;;. \n'); - response.write(' ,;;;;; ;;;;;;.;;;;;;` ;;;;;; \n'); - response.write(' ;;;;;. ;;;;;;;;;;;` ``` ;;;;;`\n'); - response.write(' ;;;;; ;;;;;;;;;, ;;; .;;;;;\n'); - response.write('`;;;;: `;;;;;;;; ;;; ;;;;;\n'); - response.write(',;;;;` `,,,,,,,, ;;;;;;; .,,;;;,,, ;;;;;\n'); - response.write(':;;;;` .;;;;;;;; ;;;;;, :;;;;;;;; ;;;;;\n'); - response.write(':;;;;` .;;;;;;;; `;;;;;; :;;;;;;;; ;;;;;\n'); - response.write('.;;;;. ;;;;;;;. ;;; ;;;;;\n'); - response.write(' ;;;;; ;;;;;;;;; ;;; ;;;;;\n'); - response.write(' ;;;;; .;;;;;;;;;; ;;; ;;;;;,\n'); - response.write(' ;;;;;; `;;;;;;;;;;;; ;;;;; \n'); - response.write(' `;;;;;, .;;;;;; ;;;;;;; ;;;;;; \n'); - response.write(' ;;;;;;: :;;;;;;. ;;;;;;; ;;;;;; \n'); - response.write(' ;;;;;;;` .;;;;;;;, ;;;;;;;; ;;;;;;;: \n'); - response.write(' ;;;;;;;;;:,:;;;;;;;;;: ;;;;;;;;;;:,;;;;;;;;;; \n'); - response.write(' `;;;;;;;;;;;;;;;;;;;. ;;;;;;;;;;;;;;;;;;;; \n'); - response.write(' ;;;;;;;;;;;;;;;;; :;;;;;;;;;;;;;;;;: \n'); - response.write(' ,;;;;;;;;;;;;;, ;;;;;;;;;;;;;; \n'); - response.write(' .;;;;;;;;;` ,;;;;;;;;: \n'); - response.write(' \n'); - response.write(' \n'); - response.write(' \n'); - response.write(' \n'); - response.write(' ;;; ;;;;;` ;;;;: .;; ;; ,;;;;;, ;;. `;, ;;;; \n'); - response.write(' ;;; ;;:;;; ;;;;;; .;; ;; ,;;;;;: ;;; `;, ;;;:;; \n'); - response.write(' ,;:; ;; ;; ;; ;; .;; ;; ,;, ;;;,`;, ;; ;; \n'); - response.write(' ;; ;: ;; ;; ;; ;; .;; ;; ,;, ;;;;`;, ;; ;;. \n'); - response.write(' ;: ;; ;;;;;: ;; ;; .;; ;; ,;, ;;`;;;, ;; ;;` \n'); - response.write(' ,;;;;; ;;`;; ;; ;; .;; ;; ,;, ;; ;;;, ;; ;; \n'); - response.write(' ;; ,;, ;; .;; ;;;;;: ;;;;;: ,;;;;;: ;; ;;, ;;;;;; \n'); - response.write(' ;; ;; ;; ;;` ;;;;. `;;;: ,;;;;;, ;; ;;, ;;;; \n'); - response.write('\n'); - response.end(); -}); - -// this is the POST handler: -app.all('/*', function (request, response) { - console.log('Got a ' + request.method + ' request'); - // the parameters of a GET request are passed in - // request.body. Pass that to formatResponse() - // for formatting: - console.log(request.headers); - if (request.method == 'GET') { - console.log(request.query); - } else { - console.log(request.body); - } - - // send the response: - response.send('OK'); - response.end(); -}); - -// start the server: -var server = app.listen(8080, serverStart); - -// create a WebSocket server and attach it to the server -var wss = new WebSocketServer({server: server}); - -wss.on('connection', function connection(ws) { - // new connection, add message listener - ws.on('message', function incoming(message) { - // received a message - console.log('received: %s', message); - - // echo it back - ws.send(message); - }); -}); diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/node_test_server/package.json b/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/node_test_server/package.json deleted file mode 100644 index 09f2d8b..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/examples/node_test_server/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "node_test_server", - "version": "0.0.1", - "author": { - "name": "Tom Igoe" - }, - "dependencies": { - "body-parser": ">=1.11.0", - "express": ">=4.0.0", - "multer": "*", - "ws": "^1.1.1" - } -} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/keywords.txt b/feather_sensor_transmit/libraries/ArduinoHttpClient/keywords.txt deleted file mode 100644 index 27cd516..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/keywords.txt +++ /dev/null @@ -1,64 +0,0 @@ -####################################### -# Syntax Coloring Map For HttpClient -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -ArduinoHttpClient KEYWORD1 -HttpClient KEYWORD1 -WebSocketClient KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -get KEYWORD2 -post KEYWORD2 -put KEYWORD2 -patch KEYWORD2 -startRequest KEYWORD2 -beginRequest KEYWORD2 -beginBody KEYWORD2 -sendHeader KEYWORD2 -sendBasicAuth KEYWORD2 -endRequest KEYWORD2 -responseStatusCode KEYWORD2 -readHeader KEYWORD2 -skipResponseHeaders KEYWORD2 -endOfHeadersReached KEYWORD2 -endOfBodyReached KEYWORD2 -completed KEYWORD2 -contentLength KEYWORD2 -isResponseChunked KEYWORD2 -connectionKeepAlive KEYWORD2 -noDefaultRequestHeaders KEYWORD2 -headerAvailable KEYWORD2 -readHeaderName KEYWORD2 -readHeaderValue KEYWORD2 -responseBody KEYWORD2 - -beginMessage KEYWORD2 -endMessage KEYWORD2 -parseMessage KEYWORD2 -messageType KEYWORD2 -isFinal KEYWORD2 -readString KEYWORD2 -ping KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### -HTTP_SUCCESS LITERAL1 -HTTP_ERROR_CONNECTION_FAILED LITERAL1 -HTTP_ERROR_API LITERAL1 -HTTP_ERROR_TIMED_OUT LITERAL1 -HTTP_ERROR_INVALID_RESPONSE LITERAL1 - -TYPE_CONTINUATION LITERAL1 -TYPE_TEXT LITERAL1 -TYPE_BINARY LITERAL1 -TYPE_CONNECTION_CLOSE LITERAL1 -TYPE_PING LITERAL1 -TYPE_PONG LITERAL1 diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/library.json b/feather_sensor_transmit/libraries/ArduinoHttpClient/library.json deleted file mode 100644 index 6bbda24..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/library.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "ArduinoHttpClient", - "keywords": "http, web, client, ethernet, wifi, GSM", - "description": "Easily interact with web servers from Arduino, using HTTP and WebSocket's.", - "repository": - { - "type": "git", - "url": "https://github.com/arduino-libraries/ArduinoHttpClient.git" - }, - "frameworks": "arduino", - "platforms": "*" -} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/library.properties b/feather_sensor_transmit/libraries/ArduinoHttpClient/library.properties deleted file mode 100644 index 2ac5bb5..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/library.properties +++ /dev/null @@ -1,10 +0,0 @@ -name=ArduinoHttpClient -version=0.3.1 -author=Arduino -maintainer=Arduino -sentence=[EXPERIMENTAL] Easily interact with web servers from Arduino, using HTTP and WebSocket's. -paragraph=This library can be used for HTTP (GET, POST, PUT, DELETE) requests to a web server. It also supports exchanging messages with WebSocket servers. Based on Adrian McEwen's HttpClient library. -category=Communication -url=https://github.com/arduino-libraries/ArduinoHttpClient -architectures=* -includes=ArduinoHttpClient.h diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h deleted file mode 100644 index 578733f..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h +++ /dev/null @@ -1,11 +0,0 @@ -// Library to simplify HTTP fetching on Arduino -// (c) Copyright Arduino. 2016 -// Released under Apache License, version 2.0 - -#ifndef ArduinoHttpClient_h -#define ArduinoHttpClient_h - -#include "HttpClient.h" -#include "WebSocketClient.h" - -#endif diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/HttpClient.cpp b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/HttpClient.cpp deleted file mode 100644 index 7517eea..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/HttpClient.cpp +++ /dev/null @@ -1,862 +0,0 @@ -// Class to simplify HTTP fetching on Arduino -// (c) Copyright 2010-2011 MCQN Ltd -// Released under Apache License, version 2.0 - -#include "HttpClient.h" -#include "b64.h" - -// Initialize constants -const char* HttpClient::kUserAgent = "Arduino/2.2.0"; -const char* HttpClient::kContentLengthPrefix = HTTP_HEADER_CONTENT_LENGTH ": "; -const char* HttpClient::kTransferEncodingChunked = HTTP_HEADER_TRANSFER_ENCODING ": " HTTP_HEADER_VALUE_CHUNKED; - -HttpClient::HttpClient(Client& aClient, const char* aServerName, uint16_t aServerPort) - : iClient(&aClient), iServerName(aServerName), iServerAddress(), iServerPort(aServerPort), - iConnectionClose(true), iSendDefaultRequestHeaders(true) -{ - resetState(); -} - -HttpClient::HttpClient(Client& aClient, const String& aServerName, uint16_t aServerPort) - : HttpClient(aClient, aServerName.c_str(), aServerPort) -{ -} - -HttpClient::HttpClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort) - : iClient(&aClient), iServerName(NULL), iServerAddress(aServerAddress), iServerPort(aServerPort), - iConnectionClose(true), iSendDefaultRequestHeaders(true) -{ - resetState(); -} - -void HttpClient::resetState() -{ - iState = eIdle; - iStatusCode = 0; - iContentLength = kNoContentLengthHeader; - iBodyLengthConsumed = 0; - iContentLengthPtr = kContentLengthPrefix; - iTransferEncodingChunkedPtr = kTransferEncodingChunked; - iIsChunked = false; - iChunkLength = 0; - iHttpResponseTimeout = kHttpResponseTimeout; -} - -void HttpClient::stop() -{ - iClient->stop(); - resetState(); -} - -void HttpClient::connectionKeepAlive() -{ - iConnectionClose = false; -} - -void HttpClient::noDefaultRequestHeaders() -{ - iSendDefaultRequestHeaders = false; -} - -void HttpClient::beginRequest() -{ - iState = eRequestStarted; -} - -int HttpClient::startRequest(const char* aURLPath, const char* aHttpMethod, - const char* aContentType, int aContentLength, const byte aBody[]) -{ - if (iState == eReadingBody || iState == eReadingChunkLength || iState == eReadingBodyChunk) - { - flushClientRx(); - - resetState(); - } - - tHttpState initialState = iState; - - if ((eIdle != iState) && (eRequestStarted != iState)) - { - return HTTP_ERROR_API; - } - - if (iConnectionClose || !iClient->connected()) - { - if (iServerName) - { - if (!iClient->connect(iServerName, iServerPort) > 0) - { -#ifdef LOGGING - Serial.println("Connection failed"); -#endif - return HTTP_ERROR_CONNECTION_FAILED; - } - } - else - { - if (!iClient->connect(iServerAddress, iServerPort) > 0) - { -#ifdef LOGGING - Serial.println("Connection failed"); -#endif - return HTTP_ERROR_CONNECTION_FAILED; - } - } - } - else - { -#ifdef LOGGING - Serial.println("Connection already open"); -#endif - } - - // Now we're connected, send the first part of the request - int ret = sendInitialHeaders(aURLPath, aHttpMethod); - - if (HTTP_SUCCESS == ret) - { - if (aContentType) - { - sendHeader(HTTP_HEADER_CONTENT_TYPE, aContentType); - } - - if (aContentLength > 0) - { - sendHeader(HTTP_HEADER_CONTENT_LENGTH, aContentLength); - } - - bool hasBody = (aBody && aContentLength > 0); - - if (initialState == eIdle || hasBody) - { - // This was a simple version of the API, so terminate the headers now - finishHeaders(); - } - // else we'll call it in endRequest or in the first call to print, etc. - - if (hasBody) - { - write(aBody, aContentLength); - } - } - - return ret; -} - -int HttpClient::sendInitialHeaders(const char* aURLPath, const char* aHttpMethod) -{ -#ifdef LOGGING - Serial.println("Connected"); -#endif - // Send the HTTP command, i.e. "GET /somepath/ HTTP/1.0" - iClient->print(aHttpMethod); - iClient->print(" "); - - iClient->print(aURLPath); - iClient->println(" HTTP/1.1"); - if (iSendDefaultRequestHeaders) - { - // The host header, if required - if (iServerName) - { - iClient->print("Host: "); - iClient->print(iServerName); - if (iServerPort != kHttpPort) - { - iClient->print(":"); - iClient->print(iServerPort); - } - iClient->println(); - } - // And user-agent string - sendHeader(HTTP_HEADER_USER_AGENT, kUserAgent); - } - - if (iConnectionClose) - { - // Tell the server to - // close this connection after we're done - sendHeader(HTTP_HEADER_CONNECTION, "close"); - } - - // Everything has gone well - iState = eRequestStarted; - return HTTP_SUCCESS; -} - -void HttpClient::sendHeader(const char* aHeader) -{ - iClient->println(aHeader); -} - -void HttpClient::sendHeader(const char* aHeaderName, const char* aHeaderValue) -{ - iClient->print(aHeaderName); - iClient->print(": "); - iClient->println(aHeaderValue); -} - -void HttpClient::sendHeader(const char* aHeaderName, const int aHeaderValue) -{ - iClient->print(aHeaderName); - iClient->print(": "); - iClient->println(aHeaderValue); -} - -void HttpClient::sendBasicAuth(const char* aUser, const char* aPassword) -{ - // Send the initial part of this header line - iClient->print("Authorization: Basic "); - // Now Base64 encode "aUser:aPassword" and send that - // This seems trickier than it should be but it's mostly to avoid either - // (a) some arbitrarily sized buffer which hopes to be big enough, or - // (b) allocating and freeing memory - // ...so we'll loop through 3 bytes at a time, outputting the results as we - // go. - // In Base64, each 3 bytes of unencoded data become 4 bytes of encoded data - unsigned char input[3]; - unsigned char output[5]; // Leave space for a '\0' terminator so we can easily print - int userLen = strlen(aUser); - int passwordLen = strlen(aPassword); - int inputOffset = 0; - for (int i = 0; i < (userLen+1+passwordLen); i++) - { - // Copy the relevant input byte into the input - if (i < userLen) - { - input[inputOffset++] = aUser[i]; - } - else if (i == userLen) - { - input[inputOffset++] = ':'; - } - else - { - input[inputOffset++] = aPassword[i-(userLen+1)]; - } - // See if we've got a chunk to encode - if ( (inputOffset == 3) || (i == userLen+passwordLen) ) - { - // We've either got to a 3-byte boundary, or we've reached then end - b64_encode(input, inputOffset, output, 4); - // NUL-terminate the output string - output[4] = '\0'; - // And write it out - iClient->print((char*)output); -// FIXME We might want to fill output with '=' characters if b64_encode doesn't -// FIXME do it for us when we're encoding the final chunk - inputOffset = 0; - } - } - // And end the header we've sent - iClient->println(); -} - -void HttpClient::finishHeaders() -{ - iClient->println(); - iState = eRequestSent; -} - -void HttpClient::flushClientRx() -{ - while (iClient->available()) - { - iClient->read(); - } -} - -void HttpClient::endRequest() -{ - beginBody(); -} - -void HttpClient::beginBody() -{ - if (iState < eRequestSent) - { - // We still need to finish off the headers - finishHeaders(); - } - // else the end of headers has already been sent, so nothing to do here -} - -int HttpClient::get(const char* aURLPath) -{ - return startRequest(aURLPath, HTTP_METHOD_GET); -} - -int HttpClient::get(const String& aURLPath) -{ - return get(aURLPath.c_str()); -} - -int HttpClient::post(const char* aURLPath) -{ - return startRequest(aURLPath, HTTP_METHOD_POST); -} - -int HttpClient::post(const String& aURLPath) -{ - return post(aURLPath.c_str()); -} - -int HttpClient::post(const char* aURLPath, const char* aContentType, const char* aBody) -{ - return post(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); -} - -int HttpClient::post(const String& aURLPath, const String& aContentType, const String& aBody) -{ - return post(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); -} - -int HttpClient::post(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) -{ - return startRequest(aURLPath, HTTP_METHOD_POST, aContentType, aContentLength, aBody); -} - -int HttpClient::put(const char* aURLPath) -{ - return startRequest(aURLPath, HTTP_METHOD_PUT); -} - -int HttpClient::put(const String& aURLPath) -{ - return put(aURLPath.c_str()); -} - -int HttpClient::put(const char* aURLPath, const char* aContentType, const char* aBody) -{ - return put(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); -} - -int HttpClient::put(const String& aURLPath, const String& aContentType, const String& aBody) -{ - return put(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); -} - -int HttpClient::put(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) -{ - return startRequest(aURLPath, HTTP_METHOD_PUT, aContentType, aContentLength, aBody); -} - -int HttpClient::patch(const char* aURLPath) -{ - return startRequest(aURLPath, HTTP_METHOD_PATCH); -} - -int HttpClient::patch(const String& aURLPath) -{ - return patch(aURLPath.c_str()); -} - -int HttpClient::patch(const char* aURLPath, const char* aContentType, const char* aBody) -{ - return patch(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); -} - -int HttpClient::patch(const String& aURLPath, const String& aContentType, const String& aBody) -{ - return patch(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); -} - -int HttpClient::patch(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) -{ - return startRequest(aURLPath, HTTP_METHOD_PATCH, aContentType, aContentLength, aBody); -} - -int HttpClient::del(const char* aURLPath) -{ - return startRequest(aURLPath, HTTP_METHOD_DELETE); -} - -int HttpClient::del(const String& aURLPath) -{ - return del(aURLPath.c_str()); -} - -int HttpClient::del(const char* aURLPath, const char* aContentType, const char* aBody) -{ - return del(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); -} - -int HttpClient::del(const String& aURLPath, const String& aContentType, const String& aBody) -{ - return del(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); -} - -int HttpClient::del(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) -{ - return startRequest(aURLPath, HTTP_METHOD_DELETE, aContentType, aContentLength, aBody); -} - -int HttpClient::responseStatusCode() -{ - if (iState < eRequestSent) - { - return HTTP_ERROR_API; - } - // The first line will be of the form Status-Line: - // HTTP-Version SP Status-Code SP Reason-Phrase CRLF - // Where HTTP-Version is of the form: - // HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT - - int c = '\0'; - do - { - // Make sure the status code is reset, and likewise the state. This - // lets us easily cope with 1xx informational responses by just - // ignoring them really, and reading the next line for a proper response - iStatusCode = 0; - iState = eRequestSent; - - unsigned long timeoutStart = millis(); - // Psuedo-regexp we're expecting before the status-code - const char* statusPrefix = "HTTP/*.* "; - const char* statusPtr = statusPrefix; - // Whilst we haven't timed out & haven't reached the end of the headers - while ((c != '\n') && - ( (millis() - timeoutStart) < iHttpResponseTimeout )) - { - if (available()) - { - c = read(); - if (c != -1) - { - switch(iState) - { - case eRequestSent: - // We haven't reached the status code yet - if ( (*statusPtr == '*') || (*statusPtr == c) ) - { - // This character matches, just move along - statusPtr++; - if (*statusPtr == '\0') - { - // We've reached the end of the prefix - iState = eReadingStatusCode; - } - } - else - { - return HTTP_ERROR_INVALID_RESPONSE; - } - break; - case eReadingStatusCode: - if (isdigit(c)) - { - // This assumes we won't get more than the 3 digits we - // want - iStatusCode = iStatusCode*10 + (c - '0'); - } - else - { - // We've reached the end of the status code - // We could sanity check it here or double-check for ' ' - // rather than anything else, but let's be lenient - iState = eStatusCodeRead; - } - break; - case eStatusCodeRead: - // We're just waiting for the end of the line now - break; - - default: - break; - }; - // We read something, reset the timeout counter - timeoutStart = millis(); - } - } - else - { - // We haven't got any data, so let's pause to allow some to - // arrive - delay(kHttpWaitForDataDelay); - } - } - if ( (c == '\n') && (iStatusCode < 200 && iStatusCode != 101) ) - { - // We've reached the end of an informational status line - c = '\0'; // Clear c so we'll go back into the data reading loop - } - } - // If we've read a status code successfully but it's informational (1xx) - // loop back to the start - while ( (iState == eStatusCodeRead) && (iStatusCode < 200 && iStatusCode != 101) ); - - if ( (c == '\n') && (iState == eStatusCodeRead) ) - { - // We've read the status-line successfully - return iStatusCode; - } - else if (c != '\n') - { - // We must've timed out before we reached the end of the line - return HTTP_ERROR_TIMED_OUT; - } - else - { - // This wasn't a properly formed status line, or at least not one we - // could understand - return HTTP_ERROR_INVALID_RESPONSE; - } -} - -int HttpClient::skipResponseHeaders() -{ - // Just keep reading until we finish reading the headers or time out - unsigned long timeoutStart = millis(); - // Whilst we haven't timed out & haven't reached the end of the headers - while ((!endOfHeadersReached()) && - ( (millis() - timeoutStart) < iHttpResponseTimeout )) - { - if (available()) - { - (void)readHeader(); - // We read something, reset the timeout counter - timeoutStart = millis(); - } - else - { - // We haven't got any data, so let's pause to allow some to - // arrive - delay(kHttpWaitForDataDelay); - } - } - if (endOfHeadersReached()) - { - // Success - return HTTP_SUCCESS; - } - else - { - // We must've timed out - return HTTP_ERROR_TIMED_OUT; - } -} - -bool HttpClient::endOfHeadersReached() -{ - return (iState == eReadingBody || iState == eReadingChunkLength || iState == eReadingBodyChunk); -}; - -int HttpClient::contentLength() -{ - // skip the response headers, if they haven't been read already - if (!endOfHeadersReached()) - { - skipResponseHeaders(); - } - - return iContentLength; -} - -String HttpClient::responseBody() -{ - int bodyLength = contentLength(); - String response; - - if (bodyLength > 0) - { - // try to reserve bodyLength bytes - if (response.reserve(bodyLength) == 0) { - // String reserve failed - return String((const char*)NULL); - } - } - - // keep on timedRead'ing, until: - // - we have a content length: body length equals consumed or no bytes - // available - // - no content length: no bytes are available - while (iBodyLengthConsumed != bodyLength) - { - int c = timedRead(); - - if (c == -1) { - // read timed out, done - break; - } - - if (!response.concat((char)c)) { - // adding char failed - return String((const char*)NULL); - } - } - - if (bodyLength > 0 && (unsigned int)bodyLength != response.length()) { - // failure, we did not read in reponse content length bytes - return String((const char*)NULL); - } - - return response; -} - -bool HttpClient::endOfBodyReached() -{ - if (endOfHeadersReached() && (contentLength() != kNoContentLengthHeader)) - { - // We've got to the body and we know how long it will be - return (iBodyLengthConsumed >= contentLength()); - } - return false; -} - -int HttpClient::available() -{ - if (iState == eReadingChunkLength) - { - while (iClient->available()) - { - char c = iClient->read(); - - if (c == '\n') - { - iState = eReadingBodyChunk; - break; - } - else if (c == '\r') - { - // no-op - } - else if (isHexadecimalDigit(c)) - { - char digit[2] = {c, '\0'}; - - iChunkLength = (iChunkLength * 16) + strtol(digit, NULL, 16); - } - } - } - - if (iState == eReadingBodyChunk && iChunkLength == 0) - { - iState = eReadingChunkLength; - } - - if (iState == eReadingChunkLength) - { - return 0; - } - - int clientAvailable = iClient->available(); - - if (iState == eReadingBodyChunk) - { - return min(clientAvailable, iChunkLength); - } - else - { - return clientAvailable; - } -} - - -int HttpClient::read() -{ - if (iIsChunked && !available()) - { - return -1; - } - - int ret = iClient->read(); - if (ret >= 0) - { - if (endOfHeadersReached() && iContentLength > 0) - { - // We're outputting the body now and we've seen a Content-Length header - // So keep track of how many bytes are left - iBodyLengthConsumed++; - } - - if (iState == eReadingBodyChunk) - { - iChunkLength--; - - if (iChunkLength == 0) - { - iState = eReadingChunkLength; - } - } - } - return ret; -} - -bool HttpClient::headerAvailable() -{ - // clear the currently store header line - iHeaderLine = ""; - - while (!endOfHeadersReached()) - { - // read a byte from the header - int c = readHeader(); - - if (c == '\r' || c == '\n') - { - if (iHeaderLine.length()) - { - // end of the line, all done - break; - } - else - { - // ignore any CR or LF characters - continue; - } - } - - // append byte to header line - iHeaderLine += (char)c; - } - - return (iHeaderLine.length() > 0); -} - -String HttpClient::readHeaderName() -{ - int colonIndex = iHeaderLine.indexOf(':'); - - if (colonIndex == -1) - { - return ""; - } - - return iHeaderLine.substring(0, colonIndex); -} - -String HttpClient::readHeaderValue() -{ - int colonIndex = iHeaderLine.indexOf(':'); - int startIndex = colonIndex + 1; - - if (colonIndex == -1) - { - return ""; - } - - // trim any leading whitespace - while (startIndex < (int)iHeaderLine.length() && isSpace(iHeaderLine[startIndex])) - { - startIndex++; - } - - return iHeaderLine.substring(startIndex); -} - -int HttpClient::read(uint8_t *buf, size_t size) -{ - int ret =iClient->read(buf, size); - if (endOfHeadersReached() && iContentLength > 0) - { - // We're outputting the body now and we've seen a Content-Length header - // So keep track of how many bytes are left - if (ret >= 0) - { - iBodyLengthConsumed += ret; - } - } - return ret; -} - -int HttpClient::readHeader() -{ - char c = read(); - - if (endOfHeadersReached()) - { - // We've passed the headers, but rather than return an error, we'll just - // act as a slightly less efficient version of read() - return c; - } - - // Whilst reading out the headers to whoever wants them, we'll keep an - // eye out for the "Content-Length" header - switch(iState) - { - case eStatusCodeRead: - // We're at the start of a line, or somewhere in the middle of reading - // the Content-Length prefix - if (*iContentLengthPtr == c) - { - // This character matches, just move along - iContentLengthPtr++; - if (*iContentLengthPtr == '\0') - { - // We've reached the end of the prefix - iState = eReadingContentLength; - // Just in case we get multiple Content-Length headers, this - // will ensure we just get the value of the last one - iContentLength = 0; - iBodyLengthConsumed = 0; - } - } - else if (*iTransferEncodingChunkedPtr == c) - { - // This character matches, just move along - iTransferEncodingChunkedPtr++; - if (*iTransferEncodingChunkedPtr == '\0') - { - // We've reached the end of the Transfer Encoding: chunked header - iIsChunked = true; - iState = eSkipToEndOfHeader; - } - } - else if (((iContentLengthPtr == kContentLengthPrefix) && (iTransferEncodingChunkedPtr == kTransferEncodingChunked)) && (c == '\r')) - { - // We've found a '\r' at the start of a line, so this is probably - // the end of the headers - iState = eLineStartingCRFound; - } - else - { - // This isn't the Content-Length or Transfer Encoding chunked header, skip to the end of the line - iState = eSkipToEndOfHeader; - } - break; - case eReadingContentLength: - if (isdigit(c)) - { - iContentLength = iContentLength*10 + (c - '0'); - } - else - { - // We've reached the end of the content length - // We could sanity check it here or double-check for "\r\n" - // rather than anything else, but let's be lenient - iState = eSkipToEndOfHeader; - } - break; - case eLineStartingCRFound: - if (c == '\n') - { - if (iIsChunked) - { - iState = eReadingChunkLength; - iChunkLength = 0; - } - else - { - iState = eReadingBody; - } - } - break; - default: - // We're just waiting for the end of the line now - break; - }; - - if ( (c == '\n') && !endOfHeadersReached() ) - { - // We've got to the end of this line, start processing again - iState = eStatusCodeRead; - iContentLengthPtr = kContentLengthPrefix; - iTransferEncodingChunkedPtr = kTransferEncodingChunked; - } - // And return the character read to whoever wants it - return c; -} - - - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/HttpClient.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/HttpClient.h deleted file mode 100644 index c954872..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/HttpClient.h +++ /dev/null @@ -1,392 +0,0 @@ -// Class to simplify HTTP fetching on Arduino -// (c) Copyright MCQN Ltd. 2010-2012 -// Released under Apache License, version 2.0 - -#ifndef HttpClient_h -#define HttpClient_h - -#include -#include -#include "Client.h" - -static const int HTTP_SUCCESS =0; -// The end of the headers has been reached. This consumes the '\n' -// Could not connect to the server -static const int HTTP_ERROR_CONNECTION_FAILED =-1; -// This call was made when the HttpClient class wasn't expecting it -// to be called. Usually indicates your code is using the class -// incorrectly -static const int HTTP_ERROR_API =-2; -// Spent too long waiting for a reply -static const int HTTP_ERROR_TIMED_OUT =-3; -// The response from the server is invalid, is it definitely an HTTP -// server? -static const int HTTP_ERROR_INVALID_RESPONSE =-4; - -// Define some of the common methods and headers here -// That lets other code reuse them without having to declare another copy -// of them, so saves code space and RAM -#define HTTP_METHOD_GET "GET" -#define HTTP_METHOD_POST "POST" -#define HTTP_METHOD_PUT "PUT" -#define HTTP_METHOD_PATCH "PATCH" -#define HTTP_METHOD_DELETE "DELETE" -#define HTTP_HEADER_CONTENT_LENGTH "Content-Length" -#define HTTP_HEADER_CONTENT_TYPE "Content-Type" -#define HTTP_HEADER_CONNECTION "Connection" -#define HTTP_HEADER_TRANSFER_ENCODING "Transfer-Encoding" -#define HTTP_HEADER_USER_AGENT "User-Agent" -#define HTTP_HEADER_VALUE_CHUNKED "chunked" - -class HttpClient : public Client -{ -public: - static const int kNoContentLengthHeader =-1; - static const int kHttpPort =80; - static const char* kUserAgent; - -// FIXME Write longer API request, using port and user-agent, example -// FIXME Update tempToPachube example to calculate Content-Length correctly - - HttpClient(Client& aClient, const char* aServerName, uint16_t aServerPort = kHttpPort); - HttpClient(Client& aClient, const String& aServerName, uint16_t aServerPort = kHttpPort); - HttpClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort = kHttpPort); - - /** Start a more complex request. - Use this when you need to send additional headers in the request, - but you will also need to call endRequest() when you are finished. - */ - void beginRequest(); - - /** End a more complex request. - Use this when you need to have sent additional headers in the request, - but you will also need to call beginRequest() at the start. - */ - void endRequest(); - - /** Start the body of a more complex request. - Use this when you need to send the body after additional headers - in the request, but can optionally call endRequest() when - you are finished. - */ - void beginBody(); - - /** Connect to the server and start to send a GET request. - @param aURLPath Url to request - @return 0 if successful, else error - */ - int get(const char* aURLPath); - int get(const String& aURLPath); - - /** Connect to the server and start to send a POST request. - @param aURLPath Url to request - @return 0 if successful, else error - */ - int post(const char* aURLPath); - int post(const String& aURLPath); - - /** Connect to the server and send a POST request - with body and content type - @param aURLPath Url to request - @param aContentType Content type of request body - @param aBody Body of the request - @return 0 if successful, else error - */ - int post(const char* aURLPath, const char* aContentType, const char* aBody); - int post(const String& aURLPath, const String& aContentType, const String& aBody); - int post(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); - - /** Connect to the server and start to send a PUT request. - @param aURLPath Url to request - @return 0 if successful, else error - */ - int put(const char* aURLPath); - int put(const String& aURLPath); - - /** Connect to the server and send a PUT request - with body and content type - @param aURLPath Url to request - @param aContentType Content type of request body - @param aBody Body of the request - @return 0 if successful, else error - */ - int put(const char* aURLPath, const char* aContentType, const char* aBody); - int put(const String& aURLPath, const String& aContentType, const String& aBody); - int put(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); - - /** Connect to the server and start to send a PATCH request. - @param aURLPath Url to request - @return 0 if successful, else error - */ - int patch(const char* aURLPath); - int patch(const String& aURLPath); - - /** Connect to the server and send a PATCH request - with body and content type - @param aURLPath Url to request - @param aContentType Content type of request body - @param aBody Body of the request - @return 0 if successful, else error - */ - int patch(const char* aURLPath, const char* aContentType, const char* aBody); - int patch(const String& aURLPath, const String& aContentType, const String& aBody); - int patch(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); - - /** Connect to the server and start to send a DELETE request. - @param aURLPath Url to request - @return 0 if successful, else error - */ - int del(const char* aURLPath); - int del(const String& aURLPath); - - /** Connect to the server and send a DELETE request - with body and content type - @param aURLPath Url to request - @param aContentType Content type of request body - @param aBody Body of the request - @return 0 if successful, else error - */ - int del(const char* aURLPath, const char* aContentType, const char* aBody); - int del(const String& aURLPath, const String& aContentType, const String& aBody); - int del(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); - - /** Connect to the server and start to send the request. - If a body is provided, the entire request (including headers and body) will be sent - @param aURLPath Url to request - @param aHttpMethod Type of HTTP request to make, e.g. "GET", "POST", etc. - @param aContentType Content type of request body (optional) - @param aContentLength Length of request body (optional) - @param aBody Body of request (optional) - @return 0 if successful, else error - */ - int startRequest(const char* aURLPath, - const char* aHttpMethod, - const char* aContentType = NULL, - int aContentLength = -1, - const byte aBody[] = NULL); - - /** Send an additional header line. This can only be called in between the - calls to startRequest and finishRequest. - @param aHeader Header line to send, in its entirety (but without the - trailing CRLF. E.g. "Authorization: Basic YQDDCAIGES" - */ - void sendHeader(const char* aHeader); - - void sendHeader(const String& aHeader) - { sendHeader(aHeader.c_str()); } - - /** Send an additional header line. This is an alternate form of - sendHeader() which takes the header name and content as separate strings. - The call will add the ": " to separate the header, so for example, to - send a XXXXXX header call sendHeader("XXXXX", "Something") - @param aHeaderName Type of header being sent - @param aHeaderValue Value for that header - */ - void sendHeader(const char* aHeaderName, const char* aHeaderValue); - - void sendHeader(const String& aHeaderName, const String& aHeaderValue) - { sendHeader(aHeaderName.c_str(), aHeaderValue.c_str()); } - - /** Send an additional header line. This is an alternate form of - sendHeader() which takes the header name and content separately but where - the value is provided as an integer. - The call will add the ": " to separate the header, so for example, to - send a XXXXXX header call sendHeader("XXXXX", 123) - @param aHeaderName Type of header being sent - @param aHeaderValue Value for that header - */ - void sendHeader(const char* aHeaderName, const int aHeaderValue); - - void sendHeader(const String& aHeaderName, const int aHeaderValue) - { sendHeader(aHeaderName.c_str(), aHeaderValue); } - - /** Send a basic authentication header. This will encode the given username - and password, and send them in suitable header line for doing Basic - Authentication. - @param aUser Username for the authorization - @param aPassword Password for the user aUser - */ - void sendBasicAuth(const char* aUser, const char* aPassword); - - void sendBasicAuth(const String& aUser, const String& aPassword) - { sendBasicAuth(aUser.c_str(), aPassword.c_str()); } - - /** Get the HTTP status code contained in the response. - For example, 200 for successful request, 404 for file not found, etc. - */ - int responseStatusCode(); - - /** Check if a header is available to be read. - Use readHeaderName() to read header name, and readHeaderValue() to - read the header value - MUST be called after responseStatusCode() and before contentLength() - */ - bool headerAvailable(); - - /** Read the name of the current response header. - Returns empty string if a header is not available. - */ - String readHeaderName(); - - /** Read the vallue of the current response header. - Returns empty string if a header is not available. - */ - String readHeaderValue(); - - /** Read the next character of the response headers. - This functions in the same way as read() but to be used when reading - through the headers. Check whether or not the end of the headers has - been reached by calling endOfHeadersReached(), although after that point - this will still return data as read() would, but slightly less efficiently - MUST be called after responseStatusCode() and before contentLength() - @return The next character of the response headers - */ - int readHeader(); - - /** Skip any response headers to get to the body. - Use this if you don't want to do any special processing of the headers - returned in the response. You can also use it after you've found all of - the headers you're interested in, and just want to get on with processing - the body. - MUST be called after responseStatusCode() - @return HTTP_SUCCESS if successful, else an error code - */ - int skipResponseHeaders(); - - /** Test whether all of the response headers have been consumed. - @return true if we are now processing the response body, else false - */ - bool endOfHeadersReached(); - - /** Test whether the end of the body has been reached. - Only works if the Content-Length header was returned by the server - @return true if we are now at the end of the body, else false - */ - bool endOfBodyReached(); - virtual bool endOfStream() { return endOfBodyReached(); }; - virtual bool completed() { return endOfBodyReached(); }; - - /** Return the length of the body. - Also skips response headers if they have not been read already - MUST be called after responseStatusCode() - @return Length of the body, in bytes, or kNoContentLengthHeader if no - Content-Length header was returned by the server - */ - int contentLength(); - - /** Returns if the response body is chunked - @return true if response body is chunked, false otherwise - */ - int isResponseChunked() { return iIsChunked; } - - /** Return the response body as a String - Also skips response headers if they have not been read already - MUST be called after responseStatusCode() - @return response body of request as a String - */ - String responseBody(); - - /** Enables connection keep-alive mode - */ - void connectionKeepAlive(); - - /** Disables sending the default request headers (Host and User Agent) - */ - void noDefaultRequestHeaders(); - - // Inherited from Print - // Note: 1st call to these indicates the user is sending the body, so if need - // Note: be we should finish the header first - virtual size_t write(uint8_t aByte) { if (iState < eRequestSent) { finishHeaders(); }; return iClient-> write(aByte); }; - virtual size_t write(const uint8_t *aBuffer, size_t aSize) { if (iState < eRequestSent) { finishHeaders(); }; return iClient->write(aBuffer, aSize); }; - // Inherited from Stream - virtual int available(); - /** Read the next byte from the server. - @return Byte read or -1 if there are no bytes available. - */ - virtual int read(); - virtual int read(uint8_t *buf, size_t size); - virtual int peek() { return iClient->peek(); }; - virtual void flush() { return iClient->flush(); }; - - // Inherited from Client - virtual int connect(IPAddress ip, uint16_t port) { return iClient->connect(ip, port); }; - virtual int connect(const char *host, uint16_t port) { return iClient->connect(host, port); }; - virtual void stop(); - virtual uint8_t connected() { return iClient->connected(); }; - virtual operator bool() { return bool(iClient); }; - virtual uint32_t httpResponseTimeout() { return iHttpResponseTimeout; }; - virtual void setHttpResponseTimeout(uint32_t timeout) { iHttpResponseTimeout = timeout; }; -protected: - /** Reset internal state data back to the "just initialised" state - */ - void resetState(); - - /** Send the first part of the request and the initial headers. - @param aURLPath Url to request - @param aHttpMethod Type of HTTP request to make, e.g. "GET", "POST", etc. - @return 0 if successful, else error - */ - int sendInitialHeaders(const char* aURLPath, - const char* aHttpMethod); - - /* Let the server know that we've reached the end of the headers - */ - void finishHeaders(); - - /** Reading any pending data from the client (used in connection keep alive mode) - */ - void flushClientRx(); - - // Number of milliseconds that we wait each time there isn't any data - // available to be read (during status code and header processing) - static const int kHttpWaitForDataDelay = 1000; - // Number of milliseconds that we'll wait in total without receiveing any - // data before returning HTTP_ERROR_TIMED_OUT (during status code and header - // processing) - static const int kHttpResponseTimeout = 30*1000; - static const char* kContentLengthPrefix; - static const char* kTransferEncodingChunked; - typedef enum { - eIdle, - eRequestStarted, - eRequestSent, - eReadingStatusCode, - eStatusCodeRead, - eReadingContentLength, - eSkipToEndOfHeader, - eLineStartingCRFound, - eReadingBody, - eReadingChunkLength, - eReadingBodyChunk - } tHttpState; - // Client we're using - Client* iClient; - // Server we are connecting to - const char* iServerName; - IPAddress iServerAddress; - // Port of server we are connecting to - uint16_t iServerPort; - // Current state of the finite-state-machine - tHttpState iState; - // Stores the status code for the response, once known - int iStatusCode; - // Stores the value of the Content-Length header, if present - int iContentLength; - // How many bytes of the response body have been read by the user - int iBodyLengthConsumed; - // How far through a Content-Length header prefix we are - const char* iContentLengthPtr; - // How far through a Transfer-Encoding chunked header we are - const char* iTransferEncodingChunkedPtr; - // Stores if the response body is chunked - bool iIsChunked; - // Stores the value of the current chunk length, if present - int iChunkLength; - uint32_t iHttpResponseTimeout; - bool iConnectionClose; - bool iSendDefaultRequestHeaders; - String iHeaderLine; -}; - -#endif diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/WebSocketClient.cpp b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/WebSocketClient.cpp deleted file mode 100644 index ab41b0a..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/WebSocketClient.cpp +++ /dev/null @@ -1,372 +0,0 @@ -// (c) Copyright Arduino. 2016 -// Released under Apache License, version 2.0 - -#include "b64.h" - -#include "WebSocketClient.h" - -WebSocketClient::WebSocketClient(Client& aClient, const char* aServerName, uint16_t aServerPort) - : HttpClient(aClient, aServerName, aServerPort), - iTxStarted(false), - iRxSize(0) -{ -} - -WebSocketClient::WebSocketClient(Client& aClient, const String& aServerName, uint16_t aServerPort) - : HttpClient(aClient, aServerName, aServerPort), - iTxStarted(false), - iRxSize(0) -{ -} - -WebSocketClient::WebSocketClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort) - : HttpClient(aClient, aServerAddress, aServerPort), - iTxStarted(false), - iRxSize(0) -{ -} - -int WebSocketClient::begin(const char* aPath) -{ - // start the GET request - beginRequest(); - connectionKeepAlive(); - int status = get(aPath); - - if (status == 0) - { - uint8_t randomKey[16]; - char base64RandomKey[25]; - - // create a random key for the connection upgrade - for (int i = 0; i < (int)sizeof(randomKey); i++) - { - randomKey[i] = random(0x01, 0xff); - } - memset(base64RandomKey, 0x00, sizeof(base64RandomKey)); - b64_encode(randomKey, sizeof(randomKey), (unsigned char*)base64RandomKey, sizeof(base64RandomKey)); - - // start the connection upgrade sequence - sendHeader("Upgrade", "websocket"); - sendHeader("Connection", "Upgrade"); - sendHeader("Sec-WebSocket-Key", base64RandomKey); - sendHeader("Sec-WebSocket-Version", "13"); - endRequest(); - - status = responseStatusCode(); - - if (status > 0) - { - skipResponseHeaders(); - } - } - - iRxSize = 0; - - // status code of 101 means success - return (status == 101) ? 0 : status; -} - -int WebSocketClient::begin(const String& aPath) -{ - return begin(aPath.c_str()); -} - -int WebSocketClient::beginMessage(int aType) -{ - if (iTxStarted) - { - // fail TX already started - return 1; - } - - iTxStarted = true; - iTxMessageType = (aType & 0xf); - iTxSize = 0; - - return 0; -} - -int WebSocketClient::endMessage() -{ - if (!iTxStarted) - { - // fail TX not started - return 1; - } - - // send FIN + the message type (opcode) - HttpClient::write(0x80 | iTxMessageType); - - // the message is masked (0x80) - // send the length - if (iTxSize < 126) - { - HttpClient::write(0x80 | (uint8_t)iTxSize); - } - else if (iTxSize < 0xffff) - { - HttpClient::write(0x80 | 126); - HttpClient::write((iTxSize >> 8) & 0xff); - HttpClient::write((iTxSize >> 0) & 0xff); - } - else - { - HttpClient::write(0x80 | 127); - HttpClient::write((iTxSize >> 56) & 0xff); - HttpClient::write((iTxSize >> 48) & 0xff); - HttpClient::write((iTxSize >> 40) & 0xff); - HttpClient::write((iTxSize >> 32) & 0xff); - HttpClient::write((iTxSize >> 24) & 0xff); - HttpClient::write((iTxSize >> 16) & 0xff); - HttpClient::write((iTxSize >> 8) & 0xff); - HttpClient::write((iTxSize >> 0) & 0xff); - } - - uint8_t maskKey[4]; - - // create a random mask for the data and send - for (int i = 0; i < (int)sizeof(maskKey); i++) - { - maskKey[i] = random(0xff); - } - HttpClient::write(maskKey, sizeof(maskKey)); - - // mask the data and send - for (int i = 0; i < (int)iTxSize; i++) { - iTxBuffer[i] ^= maskKey[i % sizeof(maskKey)]; - } - - size_t txSize = iTxSize; - - iTxStarted = false; - iTxSize = 0; - - return (HttpClient::write(iTxBuffer, txSize) == txSize) ? 0 : 1; -} - -size_t WebSocketClient::write(uint8_t aByte) -{ - return write(&aByte, sizeof(aByte)); -} - -size_t WebSocketClient::write(const uint8_t *aBuffer, size_t aSize) -{ - if (iState < eReadingBody) - { - // have not upgraded the connection yet - return HttpClient::write(aBuffer, aSize); - } - - if (!iTxStarted) - { - // fail TX not started - return 0; - } - - // check if the write size, fits in the buffer - if ((iTxSize + aSize) > sizeof(iTxBuffer)) - { - aSize = sizeof(iTxSize) - iTxSize; - } - - // copy data into the buffer - memcpy(iTxBuffer + iTxSize, aBuffer, aSize); - - iTxSize += aSize; - - return aSize; -} - -int WebSocketClient::parseMessage() -{ - flushRx(); - - // make sure 2 bytes (opcode + length) - // are available - if (HttpClient::available() < 2) - { - return 0; - } - - // read open code and length - uint8_t opcode = HttpClient::read(); - int length = HttpClient::read(); - - if ((opcode & 0x0f) == 0) - { - // continuation, use previous opcode and update flags - iRxOpCode |= opcode; - } - else - { - iRxOpCode = opcode; - } - - iRxMasked = (length & 0x80); - length &= 0x7f; - - // read the RX size - if (length < 126) - { - iRxSize = length; - } - else if (length == 126) - { - iRxSize = (HttpClient::read() << 8) | HttpClient::read(); - } - else - { - iRxSize = ((uint64_t)HttpClient::read() << 56) | - ((uint64_t)HttpClient::read() << 48) | - ((uint64_t)HttpClient::read() << 40) | - ((uint64_t)HttpClient::read() << 32) | - ((uint64_t)HttpClient::read() << 24) | - ((uint64_t)HttpClient::read() << 16) | - ((uint64_t)HttpClient::read() << 8) | - (uint64_t)HttpClient::read(); - } - - // read in the mask, if present - if (iRxMasked) - { - for (int i = 0; i < (int)sizeof(iRxMaskKey); i++) - { - iRxMaskKey[i] = HttpClient::read(); - } - } - - iRxMaskIndex = 0; - - if (TYPE_CONNECTION_CLOSE == messageType()) - { - flushRx(); - stop(); - iRxSize = 0; - } - else if (TYPE_PING == messageType()) - { - beginMessage(TYPE_PONG); - while(available()) - { - write(read()); - } - endMessage(); - - iRxSize = 0; - } - else if (TYPE_PONG == messageType()) - { - flushRx(); - iRxSize = 0; - } - - return iRxSize; -} - -int WebSocketClient::messageType() -{ - return (iRxOpCode & 0x0f); -} - -bool WebSocketClient::isFinal() -{ - return ((iRxOpCode & 0x80) != 0); -} - -String WebSocketClient::readString() -{ - int avail = available(); - String s; - - if (avail > 0) - { - s.reserve(avail); - - for (int i = 0; i < avail; i++) - { - s += (char)read(); - } - } - - return s; -} - -int WebSocketClient::ping() -{ - uint8_t pingData[16]; - - // create random data for the ping - for (int i = 0; i < (int)sizeof(pingData); i++) - { - pingData[i] = random(0xff); - } - - beginMessage(TYPE_PING); - write(pingData, sizeof(pingData)); - return endMessage(); -} - -int WebSocketClient::available() -{ - if (iState < eReadingBody) - { - return HttpClient::available(); - } - - return iRxSize; -} - -int WebSocketClient::read() -{ - byte b; - - if (read(&b, sizeof(b))) - { - return b; - } - - return -1; -} - -int WebSocketClient::read(uint8_t *aBuffer, size_t aSize) -{ - int readCount = HttpClient::read(aBuffer, aSize); - - if (readCount > 0) - { - iRxSize -= readCount; - - // unmask the RX data if needed - if (iRxMasked) - { - for (int i = 0; i < (int)aSize; i++, iRxMaskIndex++) - { - aBuffer[i] ^= iRxMaskKey[iRxMaskIndex % sizeof(iRxMaskKey)]; - } - } - } - - return readCount; -} - -int WebSocketClient::peek() -{ - int p = HttpClient::peek(); - - if (p != -1 && iRxMasked) - { - // unmask the RX data if needed - p = (uint8_t)p ^ iRxMaskKey[iRxMaskIndex % sizeof(iRxMaskKey)]; - } - - return p; -} - -void WebSocketClient::flushRx() -{ - while(available()) - { - read(); - } -} diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/WebSocketClient.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/WebSocketClient.h deleted file mode 100644 index 4b009e6..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/WebSocketClient.h +++ /dev/null @@ -1,99 +0,0 @@ -// (c) Copyright Arduino. 2016 -// Released under Apache License, version 2.0 - -#ifndef WebSocketClient_h -#define WebSocketClient_h - -#include - -#include "HttpClient.h" - -static const int TYPE_CONTINUATION = 0x0; -static const int TYPE_TEXT = 0x1; -static const int TYPE_BINARY = 0x2; -static const int TYPE_CONNECTION_CLOSE = 0x8; -static const int TYPE_PING = 0x9; -static const int TYPE_PONG = 0xa; - -class WebSocketClient : public HttpClient -{ -public: - WebSocketClient(Client& aClient, const char* aServerName, uint16_t aServerPort = HttpClient::kHttpPort); - WebSocketClient(Client& aClient, const String& aServerName, uint16_t aServerPort = HttpClient::kHttpPort); - WebSocketClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort = HttpClient::kHttpPort); - - /** Start the Web Socket connection to the specified path - @param aURLPath Path to use in request (optional, "/" is used by default) - @return 0 if successful, else error - */ - int begin(const char* aPath = "/"); - int begin(const String& aPath); - - /** Begin to send a message of type (TYPE_TEXT or TYPE_BINARY) - Use the write or Stream API's to set message content, followed by endMessage - to complete the message. - @param aURLPath Path to use in request - @return 0 if successful, else error - */ - int beginMessage(int aType); - - /** Completes sending of a message started by beginMessage - @return 0 if successful, else error - */ - int endMessage(); - - /** Try to parse an incoming messages - @return 0 if no message available, else size of parsed message - */ - int parseMessage(); - - /** Returns type of current parsed message - @return type of current parsedMessage (TYPE_TEXT or TYPE_BINARY) - */ - int messageType(); - - /** Returns if the current message is the final chunk of a split - message - @return true for final message, false otherwise - */ - bool isFinal(); - - /** Read the current messages as a string - @return current message as a string - */ - String readString(); - - /** Send a ping - @return 0 if successful, else error - */ - int ping(); - - // Inherited from Print - virtual size_t write(uint8_t aByte); - virtual size_t write(const uint8_t *aBuffer, size_t aSize); - // Inherited from Stream - virtual int available(); - /** Read the next byte from the server. - @return Byte read or -1 if there are no bytes available. - */ - virtual int read(); - virtual int read(uint8_t *buf, size_t size); - virtual int peek(); - -private: - void flushRx(); - -private: - bool iTxStarted; - uint8_t iTxMessageType; - uint8_t iTxBuffer[128]; - uint64_t iTxSize; - - uint8_t iRxOpCode; - uint64_t iRxSize; - bool iRxMasked; - int iRxMaskIndex; - uint8_t iRxMaskKey[4]; -}; - -#endif diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/b64.cpp b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/b64.cpp deleted file mode 100644 index 683d60a..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/b64.cpp +++ /dev/null @@ -1,72 +0,0 @@ -// Simple Base64 code -// (c) Copyright 2010 MCQN Ltd. -// Released under Apache License, version 2.0 - -#include "b64.h" - -/* Simple test program -#include -void main() -{ - char* in = "amcewen"; - char out[22]; - - b64_encode(in, 15, out, 22); - out[21] = '\0'; - - printf(out); -} -*/ - -int b64_encode(const unsigned char* aInput, int aInputLen, unsigned char* aOutput, int aOutputLen) -{ - // Work out if we've got enough space to encode the input - // Every 6 bits of input becomes a byte of output - if (aOutputLen < (aInputLen*8)/6) - { - // FIXME Should we return an error here, or just the length - return (aInputLen*8)/6; - } - - // If we get here we've got enough space to do the encoding - - const char* b64_dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - if (aInputLen == 3) - { - aOutput[0] = b64_dictionary[aInput[0] >> 2]; - aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4|(aInput[1]>>4)]; - aOutput[2] = b64_dictionary[(aInput[1]&0x0F)<<2|(aInput[2]>>6)]; - aOutput[3] = b64_dictionary[aInput[2]&0x3F]; - } - else if (aInputLen == 2) - { - aOutput[0] = b64_dictionary[aInput[0] >> 2]; - aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4|(aInput[1]>>4)]; - aOutput[2] = b64_dictionary[(aInput[1]&0x0F)<<2]; - aOutput[3] = '='; - } - else if (aInputLen == 1) - { - aOutput[0] = b64_dictionary[aInput[0] >> 2]; - aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4]; - aOutput[2] = '='; - aOutput[3] = '='; - } - else - { - // Break the input into 3-byte chunks and process each of them - int i; - for (i = 0; i < aInputLen/3; i++) - { - b64_encode(&aInput[i*3], 3, &aOutput[i*4], 4); - } - if (aInputLen % 3 > 0) - { - // It doesn't fit neatly into a 3-byte chunk, so process what's left - b64_encode(&aInput[i*3], aInputLen % 3, &aOutput[i*4], aOutputLen - (i*4)); - } - } - - return ((aInputLen+2)/3)*4; -} - diff --git a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/b64.h b/feather_sensor_transmit/libraries/ArduinoHttpClient/src/b64.h deleted file mode 100644 index cdb1226..0000000 --- a/feather_sensor_transmit/libraries/ArduinoHttpClient/src/b64.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef b64_h -#define b64_h - -int b64_encode(const unsigned char* aInput, int aInputLen, unsigned char* aOutput, int aOutputLen); - -#endif diff --git a/feather_sensor_transmit/libraries/DHT/.github/ISSUE_TEMPLATE.md b/feather_sensor_transmit/libraries/DHT/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index f0e2614..0000000 --- a/feather_sensor_transmit/libraries/DHT/.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/feather_sensor_transmit/libraries/DHT/.github/PULL_REQUEST_TEMPLATE.md b/feather_sensor_transmit/libraries/DHT/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 7b641eb..0000000 --- a/feather_sensor_transmit/libraries/DHT/.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/feather_sensor_transmit/libraries/DHT/DHT.cpp b/feather_sensor_transmit/libraries/DHT/DHT.cpp deleted file mode 100644 index 86ad91c..0000000 --- a/feather_sensor_transmit/libraries/DHT/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/feather_sensor_transmit/libraries/DHT/DHT.h b/feather_sensor_transmit/libraries/DHT/DHT.h deleted file mode 100644 index d81f6db..0000000 --- a/feather_sensor_transmit/libraries/DHT/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/feather_sensor_transmit/libraries/DHT/DHT_U.cpp b/feather_sensor_transmit/libraries/DHT/DHT_U.cpp deleted file mode 100644 index efc7963..0000000 --- a/feather_sensor_transmit/libraries/DHT/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/feather_sensor_transmit/libraries/DHT/DHT_U.h b/feather_sensor_transmit/libraries/DHT/DHT_U.h deleted file mode 100644 index d9ee709..0000000 --- a/feather_sensor_transmit/libraries/DHT/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/feather_sensor_transmit/libraries/DHT/README.md b/feather_sensor_transmit/libraries/DHT/README.md deleted file mode 100644 index d32afdc..0000000 --- a/feather_sensor_transmit/libraries/DHT/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/feather_sensor_transmit/libraries/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino b/feather_sensor_transmit/libraries/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino deleted file mode 100644 index 4820f2e..0000000 --- a/feather_sensor_transmit/libraries/DHT/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/feather_sensor_transmit/libraries/DHT/examples/DHTtester/DHTtester.ino b/feather_sensor_transmit/libraries/DHT/examples/DHTtester/DHTtester.ino deleted file mode 100644 index ae6c41a..0000000 --- a/feather_sensor_transmit/libraries/DHT/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/feather_sensor_transmit/libraries/DHT/keywords.txt b/feather_sensor_transmit/libraries/DHT/keywords.txt deleted file mode 100644 index 146d4fa..0000000 --- a/feather_sensor_transmit/libraries/DHT/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/feather_sensor_transmit/libraries/DHT/library.properties b/feather_sensor_transmit/libraries/DHT/library.properties deleted file mode 100644 index a54c1dc..0000000 --- a/feather_sensor_transmit/libraries/DHT/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/feather_sensor_transmit/libraries/RTClib/.github/ISSUE_TEMPLATE.md b/feather_sensor_transmit/libraries/RTClib/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index f0e2614..0000000 --- a/feather_sensor_transmit/libraries/RTClib/.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/feather_sensor_transmit/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md b/feather_sensor_transmit/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 7b641eb..0000000 --- a/feather_sensor_transmit/libraries/RTClib/.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/feather_sensor_transmit/libraries/RTClib/README.md b/feather_sensor_transmit/libraries/RTClib/README.md deleted file mode 100644 index 661e18d..0000000 --- a/feather_sensor_transmit/libraries/RTClib/README.md +++ /dev/null @@ -1,42 +0,0 @@ -This is a fork of JeeLab's fantastic real time clock library for Arduino. - -For details on using this library with an RTC module like the DS1307, PCF8523, or DS3231, see the guide at: https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/overview - -To download. click the DOWNLOADS button to the right, and rename the uncompressed folder RTClib. - -Place the RTClib folder in your *arduinosketchfolder*/libraries/ folder. -You may need to create the libraries subfolder if its your first library. Restart the IDE. - -Please note that dayOfTheWeek() ranges from 0 to 6 inclusive with 0 being 'Sunday' - - - -## Compatibility - -MCU | Tested Works | Doesn't Work | Not Tested | Notes ------------------- | :----------: | :----------: | :---------: | ----- -Atmega328 @ 16MHz | X | | | -Atmega328 @ 12MHz | X | | | -Atmega32u4 @ 16MHz | X | | | Use SDA/SCL on pins D3 & D2 -Atmega32u4 @ 8MHz | X | | | Use SDA/SCL on pins D3 & D2 -ESP8266 | X | | | SDA/SCL default to pins 4 & 5 but any two pins can be assigned as SDA/SCL using Wire.begin(SDA,SCL) -Atmega2560 @ 16MHz | X | | | Use SDA/SCL on Pins 20 & 21 -ATSAM3X8E | X | | | Use SDA1 and SCL1 -ATSAM21D | X | | | -ATtiny85 @ 16MHz | X | | | -ATtiny85 @ 8MHz | X | | | -Intel Curie @ 32MHz | | | X | -STM32F2 | | | X | - - * ATmega328 @ 16MHz : Arduino UNO, Adafruit Pro Trinket 5V, Adafruit Metro 328, Adafruit Metro Mini - * ATmega328 @ 12MHz : Adafruit Pro Trinket 3V - * ATmega32u4 @ 16MHz : Arduino Leonardo, Arduino Micro, Arduino Yun, Teensy 2.0 - * ATmega32u4 @ 8MHz : Adafruit Flora, Bluefruit Micro - * ESP8266 : Adafruit Huzzah - * ATmega2560 @ 16MHz : Arduino Mega - * ATSAM3X8E : Arduino Due - * ATSAM21D : Arduino Zero, M0 Pro - * ATtiny85 @ 16MHz : Adafruit Trinket 5V - * ATtiny85 @ 8MHz : Adafruit Gemma, Arduino Gemma, Adafruit Trinket 3V - - diff --git a/feather_sensor_transmit/libraries/RTClib/RTClib.cpp b/feather_sensor_transmit/libraries/RTClib/RTClib.cpp deleted file mode 100644 index a08dfe9..0000000 --- a/feather_sensor_transmit/libraries/RTClib/RTClib.cpp +++ /dev/null @@ -1,506 +0,0 @@ -// Code by JeeLabs http://news.jeelabs.org/code/ -// Released to the public domain! Enjoy! - -#include -#include "RTClib.h" -#ifdef __AVR__ - #include -#elif defined(ESP8266) - #include -#elif defined(ARDUINO_ARCH_SAMD) -// nothing special needed -#elif defined(ARDUINO_SAM_DUE) - #define PROGMEM - #define pgm_read_byte(addr) (*(const unsigned char *)(addr)) - #define Wire Wire1 -#endif - - - -#if (ARDUINO >= 100) - #include // capital A so it is error prone on case-sensitive filesystems - // Macro to deal with the difference in I2C write functions from old and new Arduino versions. - #define _I2C_WRITE write - #define _I2C_READ read -#else - #include - #define _I2C_WRITE send - #define _I2C_READ receive -#endif - - -static uint8_t read_i2c_register(uint8_t addr, uint8_t reg) { - Wire.beginTransmission(addr); - Wire._I2C_WRITE((byte)reg); - Wire.endTransmission(); - - Wire.requestFrom(addr, (byte)1); - return Wire._I2C_READ(); -} - -static void write_i2c_register(uint8_t addr, uint8_t reg, uint8_t val) { - Wire.beginTransmission(addr); - Wire._I2C_WRITE((byte)reg); - Wire._I2C_WRITE((byte)val); - Wire.endTransmission(); -} - - -//////////////////////////////////////////////////////////////////////////////// -// utility code, some of this could be exposed in the DateTime API if needed - -const uint8_t daysInMonth [] PROGMEM = { 31,28,31,30,31,30,31,31,30,31,30,31 }; - -// number of days since 2000/01/01, valid for 2001..2099 -static uint16_t date2days(uint16_t y, uint8_t m, uint8_t d) { - if (y >= 2000) - y -= 2000; - uint16_t days = d; - for (uint8_t i = 1; i < m; ++i) - days += pgm_read_byte(daysInMonth + i - 1); - if (m > 2 && y % 4 == 0) - ++days; - return days + 365 * y + (y + 3) / 4 - 1; -} - -static long time2long(uint16_t days, uint8_t h, uint8_t m, uint8_t s) { - return ((days * 24L + h) * 60 + m) * 60 + s; -} - -//////////////////////////////////////////////////////////////////////////////// -// DateTime implementation - ignores time zones and DST changes -// NOTE: also ignores leap seconds, see http://en.wikipedia.org/wiki/Leap_second - -DateTime::DateTime (uint32_t t) { - t -= SECONDS_FROM_1970_TO_2000; // bring to 2000 timestamp from 1970 - - ss = t % 60; - t /= 60; - mm = t % 60; - t /= 60; - hh = t % 24; - uint16_t days = t / 24; - uint8_t leap; - for (yOff = 0; ; ++yOff) { - leap = yOff % 4 == 0; - if (days < 365 + leap) - break; - days -= 365 + leap; - } - for (m = 1; ; ++m) { - uint8_t daysPerMonth = pgm_read_byte(daysInMonth + m - 1); - if (leap && m == 2) - ++daysPerMonth; - if (days < daysPerMonth) - break; - days -= daysPerMonth; - } - d = days + 1; -} - -DateTime::DateTime (uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t min, uint8_t sec) { - if (year >= 2000) - year -= 2000; - yOff = year; - m = month; - d = day; - hh = hour; - mm = min; - ss = sec; -} - -DateTime::DateTime (const DateTime& copy): - yOff(copy.yOff), - m(copy.m), - d(copy.d), - hh(copy.hh), - mm(copy.mm), - ss(copy.ss) -{} - -static uint8_t conv2d(const char* p) { - uint8_t v = 0; - if ('0' <= *p && *p <= '9') - v = *p - '0'; - return 10 * v + *++p - '0'; -} - -// A convenient constructor for using "the compiler's time": -// DateTime now (__DATE__, __TIME__); -// NOTE: using F() would further reduce the RAM footprint, see below. -DateTime::DateTime (const char* date, const char* time) { - // sample input: date = "Dec 26 2009", time = "12:34:56" - yOff = conv2d(date + 9); - // Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec - switch (date[0]) { - case 'J': m = (date[1] == 'a') ? 1 : ((date[2] == 'n') ? 6 : 7); break; - case 'F': m = 2; break; - case 'A': m = date[2] == 'r' ? 4 : 8; break; - case 'M': m = date[2] == 'r' ? 3 : 5; break; - case 'S': m = 9; break; - case 'O': m = 10; break; - case 'N': m = 11; break; - case 'D': m = 12; break; - } - d = conv2d(date + 4); - hh = conv2d(time); - mm = conv2d(time + 3); - ss = conv2d(time + 6); -} - -// A convenient constructor for using "the compiler's time": -// This version will save RAM by using PROGMEM to store it by using the F macro. -// DateTime now (F(__DATE__), F(__TIME__)); -DateTime::DateTime (const __FlashStringHelper* date, const __FlashStringHelper* time) { - // sample input: date = "Dec 26 2009", time = "12:34:56" - char buff[11]; - memcpy_P(buff, date, 11); - yOff = conv2d(buff + 9); - // Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec - switch (buff[0]) { - case 'J': m = (buff[1] == 'a') ? 1 : ((buff[2] == 'n') ? 6 : 7); break; - case 'F': m = 2; break; - case 'A': m = buff[2] == 'r' ? 4 : 8; break; - case 'M': m = buff[2] == 'r' ? 3 : 5; break; - case 'S': m = 9; break; - case 'O': m = 10; break; - case 'N': m = 11; break; - case 'D': m = 12; break; - } - d = conv2d(buff + 4); - memcpy_P(buff, time, 8); - hh = conv2d(buff); - mm = conv2d(buff + 3); - ss = conv2d(buff + 6); -} - -uint8_t DateTime::dayOfTheWeek() const { - uint16_t day = date2days(yOff, m, d); - return (day + 6) % 7; // Jan 1, 2000 is a Saturday, i.e. returns 6 -} - -uint32_t DateTime::unixtime(void) const { - uint32_t t; - uint16_t days = date2days(yOff, m, d); - t = time2long(days, hh, mm, ss); - t += SECONDS_FROM_1970_TO_2000; // seconds from 1970 to 2000 - - return t; -} - -long DateTime::secondstime(void) const { - long t; - uint16_t days = date2days(yOff, m, d); - t = time2long(days, hh, mm, ss); - return t; -} - -DateTime DateTime::operator+(const TimeSpan& span) { - return DateTime(unixtime()+span.totalseconds()); -} - -DateTime DateTime::operator-(const TimeSpan& span) { - return DateTime(unixtime()-span.totalseconds()); -} - -TimeSpan DateTime::operator-(const DateTime& right) { - return TimeSpan(unixtime()-right.unixtime()); -} - -//////////////////////////////////////////////////////////////////////////////// -// TimeSpan implementation - -TimeSpan::TimeSpan (int32_t seconds): - _seconds(seconds) -{} - -TimeSpan::TimeSpan (int16_t days, int8_t hours, int8_t minutes, int8_t seconds): - _seconds((int32_t)days*86400L + (int32_t)hours*3600 + (int32_t)minutes*60 + seconds) -{} - -TimeSpan::TimeSpan (const TimeSpan& copy): - _seconds(copy._seconds) -{} - -TimeSpan TimeSpan::operator+(const TimeSpan& right) { - return TimeSpan(_seconds+right._seconds); -} - -TimeSpan TimeSpan::operator-(const TimeSpan& right) { - return TimeSpan(_seconds-right._seconds); -} - -//////////////////////////////////////////////////////////////////////////////// -// RTC_DS1307 implementation - -static uint8_t bcd2bin (uint8_t val) { return val - 6 * (val >> 4); } -static uint8_t bin2bcd (uint8_t val) { return val + 6 * (val / 10); } - -boolean RTC_DS1307::begin(void) { - Wire.begin(); - return true; -} - -uint8_t RTC_DS1307::isrunning(void) { - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE((byte)0); - Wire.endTransmission(); - - Wire.requestFrom(DS1307_ADDRESS, 1); - uint8_t ss = Wire._I2C_READ(); - return !(ss>>7); -} - -void RTC_DS1307::adjust(const DateTime& dt) { - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE((byte)0); // start at location 0 - Wire._I2C_WRITE(bin2bcd(dt.second())); - Wire._I2C_WRITE(bin2bcd(dt.minute())); - Wire._I2C_WRITE(bin2bcd(dt.hour())); - Wire._I2C_WRITE(bin2bcd(0)); - Wire._I2C_WRITE(bin2bcd(dt.day())); - Wire._I2C_WRITE(bin2bcd(dt.month())); - Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); - Wire.endTransmission(); -} - -DateTime RTC_DS1307::now() { - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE((byte)0); - Wire.endTransmission(); - - Wire.requestFrom(DS1307_ADDRESS, 7); - uint8_t ss = bcd2bin(Wire._I2C_READ() & 0x7F); - uint8_t mm = bcd2bin(Wire._I2C_READ()); - uint8_t hh = bcd2bin(Wire._I2C_READ()); - Wire._I2C_READ(); - uint8_t d = bcd2bin(Wire._I2C_READ()); - uint8_t m = bcd2bin(Wire._I2C_READ()); - uint16_t y = bcd2bin(Wire._I2C_READ()) + 2000; - - return DateTime (y, m, d, hh, mm, ss); -} - -Ds1307SqwPinMode RTC_DS1307::readSqwPinMode() { - int mode; - - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE(DS1307_CONTROL); - Wire.endTransmission(); - - Wire.requestFrom((uint8_t)DS1307_ADDRESS, (uint8_t)1); - mode = Wire._I2C_READ(); - - mode &= 0x93; - return static_cast(mode); -} - -void RTC_DS1307::writeSqwPinMode(Ds1307SqwPinMode mode) { - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE(DS1307_CONTROL); - Wire._I2C_WRITE(mode); - Wire.endTransmission(); -} - -void RTC_DS1307::readnvram(uint8_t* buf, uint8_t size, uint8_t address) { - int addrByte = DS1307_NVRAM + address; - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE(addrByte); - Wire.endTransmission(); - - Wire.requestFrom((uint8_t) DS1307_ADDRESS, size); - for (uint8_t pos = 0; pos < size; ++pos) { - buf[pos] = Wire._I2C_READ(); - } -} - -void RTC_DS1307::writenvram(uint8_t address, uint8_t* buf, uint8_t size) { - int addrByte = DS1307_NVRAM + address; - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE(addrByte); - for (uint8_t pos = 0; pos < size; ++pos) { - Wire._I2C_WRITE(buf[pos]); - } - Wire.endTransmission(); -} - -uint8_t RTC_DS1307::readnvram(uint8_t address) { - uint8_t data; - readnvram(&data, 1, address); - return data; -} - -void RTC_DS1307::writenvram(uint8_t address, uint8_t data) { - writenvram(address, &data, 1); -} - -//////////////////////////////////////////////////////////////////////////////// -// RTC_Millis implementation - -long RTC_Millis::offset = 0; - -void RTC_Millis::adjust(const DateTime& dt) { - offset = dt.unixtime() - millis() / 1000; -} - -DateTime RTC_Millis::now() { - return (uint32_t)(offset + millis() / 1000); -} - -//////////////////////////////////////////////////////////////////////////////// - -//////////////////////////////////////////////////////////////////////////////// -// RTC_PCF8563 implementation - -boolean RTC_PCF8523::begin(void) { - Wire.begin(); - return true; -} - -boolean RTC_PCF8523::initialized(void) { - Wire.beginTransmission(PCF8523_ADDRESS); - Wire._I2C_WRITE((byte)PCF8523_CONTROL_3); - Wire.endTransmission(); - - Wire.requestFrom(PCF8523_ADDRESS, 1); - uint8_t ss = Wire._I2C_READ(); - return ((ss & 0xE0) != 0xE0); -} - -void RTC_PCF8523::adjust(const DateTime& dt) { - Wire.beginTransmission(PCF8523_ADDRESS); - Wire._I2C_WRITE((byte)3); // start at location 3 - Wire._I2C_WRITE(bin2bcd(dt.second())); - Wire._I2C_WRITE(bin2bcd(dt.minute())); - Wire._I2C_WRITE(bin2bcd(dt.hour())); - Wire._I2C_WRITE(bin2bcd(dt.day())); - Wire._I2C_WRITE(bin2bcd(0)); // skip weekdays - Wire._I2C_WRITE(bin2bcd(dt.month())); - Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); - Wire.endTransmission(); - - // set to battery switchover mode - Wire.beginTransmission(PCF8523_ADDRESS); - Wire._I2C_WRITE((byte)PCF8523_CONTROL_3); - Wire._I2C_WRITE((byte)0x00); - Wire.endTransmission(); -} - -DateTime RTC_PCF8523::now() { - Wire.beginTransmission(PCF8523_ADDRESS); - Wire._I2C_WRITE((byte)3); - Wire.endTransmission(); - - Wire.requestFrom(PCF8523_ADDRESS, 7); - uint8_t ss = bcd2bin(Wire._I2C_READ() & 0x7F); - uint8_t mm = bcd2bin(Wire._I2C_READ()); - uint8_t hh = bcd2bin(Wire._I2C_READ()); - uint8_t d = bcd2bin(Wire._I2C_READ()); - Wire._I2C_READ(); // skip 'weekdays' - uint8_t m = bcd2bin(Wire._I2C_READ()); - uint16_t y = bcd2bin(Wire._I2C_READ()) + 2000; - - return DateTime (y, m, d, hh, mm, ss); -} - -Pcf8523SqwPinMode RTC_PCF8523::readSqwPinMode() { - int mode; - - Wire.beginTransmission(PCF8523_ADDRESS); - Wire._I2C_WRITE(PCF8523_CLKOUTCONTROL); - Wire.endTransmission(); - - Wire.requestFrom((uint8_t)PCF8523_ADDRESS, (uint8_t)1); - mode = Wire._I2C_READ(); - - mode >>= 3; - mode &= 0x7; - return static_cast(mode); -} - -void RTC_PCF8523::writeSqwPinMode(Pcf8523SqwPinMode mode) { - Wire.beginTransmission(PCF8523_ADDRESS); - Wire._I2C_WRITE(PCF8523_CLKOUTCONTROL); - Wire._I2C_WRITE(mode << 3); - Wire.endTransmission(); -} - - - - -//////////////////////////////////////////////////////////////////////////////// -// RTC_DS3231 implementation - -boolean RTC_DS3231::begin(void) { - Wire.begin(); - return true; -} - -bool RTC_DS3231::lostPower(void) { - return (read_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG) >> 7); -} - -void RTC_DS3231::adjust(const DateTime& dt) { - Wire.beginTransmission(DS3231_ADDRESS); - Wire._I2C_WRITE((byte)0); // start at location 0 - Wire._I2C_WRITE(bin2bcd(dt.second())); - Wire._I2C_WRITE(bin2bcd(dt.minute())); - Wire._I2C_WRITE(bin2bcd(dt.hour())); - Wire._I2C_WRITE(bin2bcd(0)); - Wire._I2C_WRITE(bin2bcd(dt.day())); - Wire._I2C_WRITE(bin2bcd(dt.month())); - Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); - Wire.endTransmission(); - - uint8_t statreg = read_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG); - statreg &= ~0x80; // flip OSF bit - write_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG, statreg); -} - -DateTime RTC_DS3231::now() { - Wire.beginTransmission(DS3231_ADDRESS); - Wire._I2C_WRITE((byte)0); - Wire.endTransmission(); - - Wire.requestFrom(DS3231_ADDRESS, 7); - uint8_t ss = bcd2bin(Wire._I2C_READ() & 0x7F); - uint8_t mm = bcd2bin(Wire._I2C_READ()); - uint8_t hh = bcd2bin(Wire._I2C_READ()); - Wire._I2C_READ(); - uint8_t d = bcd2bin(Wire._I2C_READ()); - uint8_t m = bcd2bin(Wire._I2C_READ()); - uint16_t y = bcd2bin(Wire._I2C_READ()) + 2000; - - return DateTime (y, m, d, hh, mm, ss); -} - -Ds3231SqwPinMode RTC_DS3231::readSqwPinMode() { - int mode; - - Wire.beginTransmission(DS3231_ADDRESS); - Wire._I2C_WRITE(DS3231_CONTROL); - Wire.endTransmission(); - - Wire.requestFrom((uint8_t)DS3231_ADDRESS, (uint8_t)1); - mode = Wire._I2C_READ(); - - mode &= 0x93; - return static_cast(mode); -} - -void RTC_DS3231::writeSqwPinMode(Ds3231SqwPinMode mode) { - uint8_t ctrl; - ctrl = read_i2c_register(DS3231_ADDRESS, DS3231_CONTROL); - - ctrl &= ~0x04; // turn off INTCON - ctrl &= ~0x18; // set freq bits to 0 - - if (mode == DS3231_OFF) { - ctrl |= 0x04; // turn on INTCN - } else { - ctrl |= mode; - } - write_i2c_register(DS3231_ADDRESS, DS3231_CONTROL, ctrl); - - //Serial.println( read_i2c_register(DS3231_ADDRESS, DS3231_CONTROL), HEX); -} diff --git a/feather_sensor_transmit/libraries/RTClib/RTClib.h b/feather_sensor_transmit/libraries/RTClib/RTClib.h deleted file mode 100644 index abf5d9b..0000000 --- a/feather_sensor_transmit/libraries/RTClib/RTClib.h +++ /dev/null @@ -1,135 +0,0 @@ -// Code by JeeLabs http://news.jeelabs.org/code/ -// Released to the public domain! Enjoy! - -#ifndef _RTCLIB_H_ -#define _RTCLIB_H_ - -#include -class TimeSpan; - - -#define PCF8523_ADDRESS 0x68 -#define PCF8523_CLKOUTCONTROL 0x0F -#define PCF8523_CONTROL_3 0x02 - -#define DS1307_ADDRESS 0x68 -#define DS1307_CONTROL 0x07 -#define DS1307_NVRAM 0x08 - -#define DS3231_ADDRESS 0x68 -#define DS3231_CONTROL 0x0E -#define DS3231_STATUSREG 0x0F - -#define SECONDS_PER_DAY 86400L - -#define SECONDS_FROM_1970_TO_2000 946684800 - - - -// Simple general-purpose date/time class (no TZ / DST / leap second handling!) -class DateTime { -public: - DateTime (uint32_t t =0); - DateTime (uint16_t year, uint8_t month, uint8_t day, - uint8_t hour =0, uint8_t min =0, uint8_t sec =0); - DateTime (const DateTime& copy); - DateTime (const char* date, const char* time); - DateTime (const __FlashStringHelper* date, const __FlashStringHelper* time); - uint16_t year() const { return 2000 + yOff; } - uint8_t month() const { return m; } - uint8_t day() const { return d; } - uint8_t hour() const { return hh; } - uint8_t minute() const { return mm; } - uint8_t second() const { return ss; } - uint8_t dayOfTheWeek() const; - - // 32-bit times as seconds since 1/1/2000 - long secondstime() const; - // 32-bit times as seconds since 1/1/1970 - uint32_t unixtime(void) const; - - DateTime operator+(const TimeSpan& span); - DateTime operator-(const TimeSpan& span); - TimeSpan operator-(const DateTime& right); - -protected: - uint8_t yOff, m, d, hh, mm, ss; -}; - -// Timespan which can represent changes in time with seconds accuracy. -class TimeSpan { -public: - TimeSpan (int32_t seconds = 0); - TimeSpan (int16_t days, int8_t hours, int8_t minutes, int8_t seconds); - TimeSpan (const TimeSpan& copy); - int16_t days() const { return _seconds / 86400L; } - int8_t hours() const { return _seconds / 3600 % 24; } - int8_t minutes() const { return _seconds / 60 % 60; } - int8_t seconds() const { return _seconds % 60; } - int32_t totalseconds() const { return _seconds; } - - TimeSpan operator+(const TimeSpan& right); - TimeSpan operator-(const TimeSpan& right); - -protected: - int32_t _seconds; -}; - -// RTC based on the DS1307 chip connected via I2C and the Wire library -enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 }; - -class RTC_DS1307 { -public: - boolean begin(void); - static void adjust(const DateTime& dt); - uint8_t isrunning(void); - static DateTime now(); - static Ds1307SqwPinMode readSqwPinMode(); - static void writeSqwPinMode(Ds1307SqwPinMode mode); - uint8_t readnvram(uint8_t address); - void readnvram(uint8_t* buf, uint8_t size, uint8_t address); - void writenvram(uint8_t address, uint8_t data); - void writenvram(uint8_t address, uint8_t* buf, uint8_t size); -}; - -// RTC based on the DS3231 chip connected via I2C and the Wire library -enum Ds3231SqwPinMode { DS3231_OFF = 0x01, DS3231_SquareWave1Hz = 0x00, DS3231_SquareWave1kHz = 0x08, DS3231_SquareWave4kHz = 0x10, DS3231_SquareWave8kHz = 0x18 }; - -class RTC_DS3231 { -public: - boolean begin(void); - static void adjust(const DateTime& dt); - bool lostPower(void); - static DateTime now(); - static Ds3231SqwPinMode readSqwPinMode(); - static void writeSqwPinMode(Ds3231SqwPinMode mode); -}; - - -// RTC based on the PCF8523 chip connected via I2C and the Wire library -enum Pcf8523SqwPinMode { PCF8523_OFF = 7, PCF8523_SquareWave1HZ = 6, PCF8523_SquareWave32HZ = 5, PCF8523_SquareWave1kHz = 4, PCF8523_SquareWave4kHz = 3, PCF8523_SquareWave8kHz = 2, PCF8523_SquareWave16kHz = 1, PCF8523_SquareWave32kHz = 0 }; - -class RTC_PCF8523 { -public: - boolean begin(void); - void adjust(const DateTime& dt); - boolean initialized(void); - static DateTime now(); - - Pcf8523SqwPinMode readSqwPinMode(); - void writeSqwPinMode(Pcf8523SqwPinMode mode); -}; - -// RTC using the internal millis() clock, has to be initialized before use -// NOTE: this clock won't be correct once the millis() timer rolls over (>49d?) -class RTC_Millis { -public: - static void begin(const DateTime& dt) { adjust(dt); } - static void adjust(const DateTime& dt); - static DateTime now(); - -protected: - static long offset; -}; - -#endif // _RTCLIB_H_ diff --git a/feather_sensor_transmit/libraries/RTClib/examples/datecalc/datecalc.ino b/feather_sensor_transmit/libraries/RTClib/examples/datecalc/datecalc.ino deleted file mode 100644 index 771dacd..0000000 --- a/feather_sensor_transmit/libraries/RTClib/examples/datecalc/datecalc.ino +++ /dev/null @@ -1,111 +0,0 @@ -// Simple date conversions and calculations - -#include -#include "RTClib.h" - -#if defined(ARDUINO_ARCH_SAMD) -// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! - #define Serial SerialUSB -#endif - -void showDate(const char* txt, const DateTime& dt) { - Serial.print(txt); - Serial.print(' '); - Serial.print(dt.year(), DEC); - Serial.print('/'); - Serial.print(dt.month(), DEC); - Serial.print('/'); - Serial.print(dt.day(), DEC); - Serial.print(' '); - Serial.print(dt.hour(), DEC); - Serial.print(':'); - Serial.print(dt.minute(), DEC); - Serial.print(':'); - Serial.print(dt.second(), DEC); - - Serial.print(" = "); - Serial.print(dt.unixtime()); - Serial.print("s / "); - Serial.print(dt.unixtime() / 86400L); - Serial.print("d since 1970"); - - Serial.println(); -} - -void showTimeSpan(const char* txt, const TimeSpan& ts) { - Serial.print(txt); - Serial.print(" "); - Serial.print(ts.days(), DEC); - Serial.print(" days "); - Serial.print(ts.hours(), DEC); - Serial.print(" hours "); - Serial.print(ts.minutes(), DEC); - Serial.print(" minutes "); - Serial.print(ts.seconds(), DEC); - Serial.print(" seconds ("); - Serial.print(ts.totalseconds(), DEC); - Serial.print(" total seconds)"); - Serial.println(); -} - -void setup () { - -#ifndef ESP8266 - while (!Serial); // for Leonardo/Micro/Zero -#endif - Serial.begin(57600); - - DateTime dt0 (0, 1, 1, 0, 0, 0); - showDate("dt0", dt0); - - DateTime dt1 (1, 1, 1, 0, 0, 0); - showDate("dt1", dt1); - - DateTime dt2 (2009, 1, 1, 0, 0, 0); - showDate("dt2", dt2); - - DateTime dt3 (2009, 1, 2, 0, 0, 0); - showDate("dt3", dt3); - - DateTime dt4 (2009, 1, 27, 0, 0, 0); - showDate("dt4", dt4); - - DateTime dt5 (2009, 2, 27, 0, 0, 0); - showDate("dt5", dt5); - - DateTime dt6 (2009, 12, 27, 0, 0, 0); - showDate("dt6", dt6); - - DateTime dt7 (dt6.unixtime() + 3600); // One hour later. - showDate("dt7", dt7); - - DateTime dt75 = dt6 + TimeSpan(0, 1, 0, 0); // One hour later with TimeSpan addition. - showDate("dt7.5", dt75); - - DateTime dt8 (dt6.unixtime() + 86400L); // One day later. - showDate("dt8", dt8); - - DateTime dt85 = dt6 + TimeSpan(1, 0, 0, 0); // One day later with TimeSpan addition. - showDate("dt8.5", dt85); - - DateTime dt9 (dt6.unixtime() + 7 * 86400L); // One week later. - showDate("dt9", dt9); - - DateTime dt95 = dt6 + TimeSpan(7, 0, 0, 0); // One week later with TimeSpan addition. - showDate("dt9.5", dt95); - - DateTime dt10 = dt6 + TimeSpan(0, 0, 42, 42); // Fourty two minutes and fourty two seconds later. - showDate("dt10", dt10); - - DateTime dt11 = dt6 - TimeSpan(7, 0, 0, 0); // One week ago. - showDate("dt11", dt11); - - TimeSpan ts1 = dt6 - dt5; - showTimeSpan("dt6-dt5", ts1); - - TimeSpan ts2 = dt10 - dt6; - showTimeSpan("dt10-dt6", ts2); -} - -void loop () { -} diff --git a/feather_sensor_transmit/libraries/RTClib/examples/ds1307/ds1307.ino b/feather_sensor_transmit/libraries/RTClib/examples/ds1307/ds1307.ino deleted file mode 100644 index 7d9162f..0000000 --- a/feather_sensor_transmit/libraries/RTClib/examples/ds1307/ds1307.ino +++ /dev/null @@ -1,71 +0,0 @@ -// Date and time functions using a DS1307 RTC connected via I2C and Wire lib -#include -#include "RTClib.h" - -RTC_DS1307 rtc; - -char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; - -void setup () { - while (!Serial); // for Leonardo/Micro/Zero - - Serial.begin(57600); - if (! rtc.begin()) { - Serial.println("Couldn't find RTC"); - while (1); - } - - if (! rtc.isrunning()) { - Serial.println("RTC is NOT running!"); - // following line sets the RTC to the date & time this sketch was compiled - // rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); - // This line sets the RTC with an explicit date & time, for example to set - // January 21, 2014 at 3am you would call: - // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); - } -} - -void loop () { - DateTime now = rtc.now(); - - Serial.print(now.year(), DEC); - Serial.print('/'); - Serial.print(now.month(), DEC); - Serial.print('/'); - Serial.print(now.day(), DEC); - Serial.print(" ("); - Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); - Serial.print(") "); - Serial.print(now.hour(), DEC); - Serial.print(':'); - Serial.print(now.minute(), DEC); - Serial.print(':'); - Serial.print(now.second(), DEC); - Serial.println(); - - Serial.print(" since midnight 1/1/1970 = "); - Serial.print(now.unixtime()); - Serial.print("s = "); - Serial.print(now.unixtime() / 86400L); - Serial.println("d"); - - // calculate a date which is 7 days and 30 seconds into the future - DateTime future (now + TimeSpan(7,12,30,6)); - - Serial.print(" now + 7d + 30s: "); - Serial.print(future.year(), DEC); - Serial.print('/'); - Serial.print(future.month(), DEC); - Serial.print('/'); - Serial.print(future.day(), DEC); - Serial.print(' '); - Serial.print(future.hour(), DEC); - Serial.print(':'); - Serial.print(future.minute(), DEC); - Serial.print(':'); - Serial.print(future.second(), DEC); - Serial.println(); - - Serial.println(); - delay(3000); -} \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino b/feather_sensor_transmit/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino deleted file mode 100644 index c12c26c..0000000 --- a/feather_sensor_transmit/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino +++ /dev/null @@ -1,68 +0,0 @@ -// SQW/OUT pin mode using a DS1307 RTC connected via I2C. -// -// According to the data sheet (http://datasheets.maxim-ic.com/en/ds/DS1307.pdf), the -// DS1307's SQW/OUT pin can be set to low, high, 1Hz, 4.096kHz, 8.192kHz, or 32.768kHz. -// -// This sketch reads the state of the pin, then iterates through the possible values at -// 5 second intervals. -// - -// NOTE: -// You must connect a pull up resistor (~10kohm) from the SQW pin up to VCC. Without -// this pull up the wave output will not work! - -#include -#include "RTClib.h" - -#if defined(ARDUINO_ARCH_SAMD) -// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! - #define Serial SerialUSB -#endif - -RTC_DS1307 rtc; - -int mode_index = 0; - -Ds1307SqwPinMode modes[] = {OFF, ON, SquareWave1HZ, SquareWave4kHz, SquareWave8kHz, SquareWave32kHz}; - - -void print_mode() { - Ds1307SqwPinMode mode = rtc.readSqwPinMode(); - - Serial.print("Sqw Pin Mode: "); - switch(mode) { - case OFF: Serial.println("OFF"); break; - case ON: Serial.println("ON"); break; - case SquareWave1HZ: Serial.println("1Hz"); break; - case SquareWave4kHz: Serial.println("4.096kHz"); break; - case SquareWave8kHz: Serial.println("8.192kHz"); break; - case SquareWave32kHz: Serial.println("32.768kHz"); break; - default: Serial.println("UNKNOWN"); break; - } -} - -void setup () { - -#ifndef ESP8266 - while (!Serial); // for Leonardo/Micro/Zero -#endif - - Serial.begin(57600); - if (! rtc.begin()) { - Serial.println("Couldn't find RTC"); - while (1); - } - - print_mode(); -} - -void loop () { - rtc.writeSqwPinMode(modes[mode_index++]); - print_mode(); - - if (mode_index > 5) { - mode_index = 0; - } - - delay(5000); -} diff --git a/feather_sensor_transmit/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino b/feather_sensor_transmit/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino deleted file mode 100644 index 0acd0cf..0000000 --- a/feather_sensor_transmit/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino +++ /dev/null @@ -1,63 +0,0 @@ -// Example of using the non-volatile RAM storage on the DS1307. -// You can write up to 56 bytes from address 0 to 55. -// Data will be persisted as long as the DS1307 has battery power. - -#include -#include "RTClib.h" - -#if defined(ARDUINO_ARCH_SAMD) -// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! - #define Serial SerialUSB -#endif - -RTC_DS1307 rtc; - -void printnvram(uint8_t address) { - Serial.print("Address 0x"); - Serial.print(address, HEX); - Serial.print(" = 0x"); - Serial.println(rtc.readnvram(address), HEX); -} - -void setup () { - -#ifndef ESP8266 - while (!Serial); // for Leonardo/Micro/Zero -#endif - Serial.begin(57600); - rtc.begin(); - - // Print old RAM contents on startup. - Serial.println("Current NVRAM values:"); - for (int i = 0; i < 6; ++i) { - printnvram(i); - } - - // Write some bytes to non-volatile RAM storage. - // NOTE: You can only read and write from addresses 0 to 55 (i.e. 56 byte values). - Serial.println("Writing NVRAM values."); - // Example writing one byte at a time: - rtc.writenvram(0, 0xFE); - rtc.writenvram(1, 0xED); - // Example writing multiple bytes: - uint8_t writeData[4] = { 0xBE, 0xEF, 0x01, 0x02 }; - rtc.writenvram(2, writeData, 4); - - // Read bytes from non-volatile RAM storage. - Serial.println("Reading NVRAM values:"); - // Example reading one byte at a time. - Serial.println(rtc.readnvram(0), HEX); - Serial.println(rtc.readnvram(1), HEX); - // Example reading multiple bytes: - uint8_t readData[4] = {0}; - rtc.readnvram(readData, 4, 2); - Serial.println(readData[0], HEX); - Serial.println(readData[1], HEX); - Serial.println(readData[2], HEX); - Serial.println(readData[3], HEX); - -} - -void loop () { - // Do nothing in the loop. -} diff --git a/feather_sensor_transmit/libraries/RTClib/examples/ds3231/ds3231.ino b/feather_sensor_transmit/libraries/RTClib/examples/ds3231/ds3231.ino deleted file mode 100644 index b62d510..0000000 --- a/feather_sensor_transmit/libraries/RTClib/examples/ds3231/ds3231.ino +++ /dev/null @@ -1,77 +0,0 @@ -// Date and time functions using a DS3231 RTC connected via I2C and Wire lib -#include -#include "RTClib.h" - -RTC_DS3231 rtc; - -char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; - -void setup () { - -#ifndef ESP8266 - while (!Serial); // for Leonardo/Micro/Zero -#endif - - Serial.begin(9600); - - delay(3000); // wait for console opening - - if (! rtc.begin()) { - Serial.println("Couldn't find RTC"); - while (1); - } - - if (rtc.lostPower()) { - Serial.println("RTC lost power, lets set the time!"); - // following line sets the RTC to the date & time this sketch was compiled - rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); - // This line sets the RTC with an explicit date & time, for example to set - // January 21, 2014 at 3am you would call: - // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); - } -} - -void loop () { - DateTime now = rtc.now(); - - Serial.print(now.year(), DEC); - Serial.print('/'); - Serial.print(now.month(), DEC); - Serial.print('/'); - Serial.print(now.day(), DEC); - Serial.print(" ("); - Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); - Serial.print(") "); - Serial.print(now.hour(), DEC); - Serial.print(':'); - Serial.print(now.minute(), DEC); - Serial.print(':'); - Serial.print(now.second(), DEC); - Serial.println(); - - Serial.print(" since midnight 1/1/1970 = "); - Serial.print(now.unixtime()); - Serial.print("s = "); - Serial.print(now.unixtime() / 86400L); - Serial.println("d"); - - // calculate a date which is 7 days and 30 seconds into the future - DateTime future (now + TimeSpan(7,12,30,6)); - - Serial.print(" now + 7d + 30s: "); - Serial.print(future.year(), DEC); - Serial.print('/'); - Serial.print(future.month(), DEC); - Serial.print('/'); - Serial.print(future.day(), DEC); - Serial.print(' '); - Serial.print(future.hour(), DEC); - Serial.print(':'); - Serial.print(future.minute(), DEC); - Serial.print(':'); - Serial.print(future.second(), DEC); - Serial.println(); - - Serial.println(); - delay(3000); -} diff --git a/feather_sensor_transmit/libraries/RTClib/examples/pcf8523/pcf8523.ino b/feather_sensor_transmit/libraries/RTClib/examples/pcf8523/pcf8523.ino deleted file mode 100644 index fc7dfe8..0000000 --- a/feather_sensor_transmit/libraries/RTClib/examples/pcf8523/pcf8523.ino +++ /dev/null @@ -1,74 +0,0 @@ -// Date and time functions using a DS1307 RTC connected via I2C and Wire lib -#include -#include "RTClib.h" - -RTC_PCF8523 rtc; - -char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; - -void setup () { - - while (!Serial) { - delay(1); // for Leonardo/Micro/Zero - } - - Serial.begin(57600); - if (! rtc.begin()) { - Serial.println("Couldn't find RTC"); - while (1); - } - - if (! rtc.initialized()) { - Serial.println("RTC is NOT running!"); - // following line sets the RTC to the date & time this sketch was compiled - // rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); - // This line sets the RTC with an explicit date & time, for example to set - // January 21, 2014 at 3am you would call: - // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); - } -} - -void loop () { - DateTime now = rtc.now(); - - Serial.print(now.year(), DEC); - Serial.print('/'); - Serial.print(now.month(), DEC); - Serial.print('/'); - Serial.print(now.day(), DEC); - Serial.print(" ("); - Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); - Serial.print(") "); - Serial.print(now.hour(), DEC); - Serial.print(':'); - Serial.print(now.minute(), DEC); - Serial.print(':'); - Serial.print(now.second(), DEC); - Serial.println(); - - Serial.print(" since midnight 1/1/1970 = "); - Serial.print(now.unixtime()); - Serial.print("s = "); - Serial.print(now.unixtime() / 86400L); - Serial.println("d"); - - // calculate a date which is 7 days and 30 seconds into the future - DateTime future (now + TimeSpan(7,12,30,6)); - - Serial.print(" now + 7d + 30s: "); - Serial.print(future.year(), DEC); - Serial.print('/'); - Serial.print(future.month(), DEC); - Serial.print('/'); - Serial.print(future.day(), DEC); - Serial.print(' '); - Serial.print(future.hour(), DEC); - Serial.print(':'); - Serial.print(future.minute(), DEC); - Serial.print(':'); - Serial.print(future.second(), DEC); - Serial.println(); - - Serial.println(); - delay(3000); -} \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/RTClib/examples/softrtc/softrtc.ino b/feather_sensor_transmit/libraries/RTClib/examples/softrtc/softrtc.ino deleted file mode 100644 index 80f1886..0000000 --- a/feather_sensor_transmit/libraries/RTClib/examples/softrtc/softrtc.ino +++ /dev/null @@ -1,61 +0,0 @@ -// Date and time functions using just software, based on millis() & timer - -#include -#include // this #include still required because the RTClib depends on it -#include "RTClib.h" - -#if defined(ARDUINO_ARCH_SAMD) -// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! - #define Serial SerialUSB -#endif - -RTC_Millis rtc; - -void setup () { - Serial.begin(57600); - // following line sets the RTC to the date & time this sketch was compiled - rtc.begin(DateTime(F(__DATE__), F(__TIME__))); - // This line sets the RTC with an explicit date & time, for example to set - // January 21, 2014 at 3am you would call: - // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); -} - -void loop () { - DateTime now = rtc.now(); - - Serial.print(now.year(), DEC); - Serial.print('/'); - Serial.print(now.month(), DEC); - Serial.print('/'); - Serial.print(now.day(), DEC); - Serial.print(' '); - Serial.print(now.hour(), DEC); - Serial.print(':'); - Serial.print(now.minute(), DEC); - Serial.print(':'); - Serial.print(now.second(), DEC); - Serial.println(); - - Serial.print(" seconds since 1970: "); - Serial.println(now.unixtime()); - - // calculate a date which is 7 days and 30 seconds into the future - DateTime future (now.unixtime() + 7 * 86400L + 30); - - Serial.print(" now + 7d + 30s: "); - Serial.print(future.year(), DEC); - Serial.print('/'); - Serial.print(future.month(), DEC); - Serial.print('/'); - Serial.print(future.day(), DEC); - Serial.print(' '); - Serial.print(future.hour(), DEC); - Serial.print(':'); - Serial.print(future.minute(), DEC); - Serial.print(':'); - Serial.print(future.second(), DEC); - Serial.println(); - - Serial.println(); - delay(3000); -} diff --git a/feather_sensor_transmit/libraries/RTClib/keywords.txt b/feather_sensor_transmit/libraries/RTClib/keywords.txt deleted file mode 100644 index 26cdc1e..0000000 --- a/feather_sensor_transmit/libraries/RTClib/keywords.txt +++ /dev/null @@ -1,37 +0,0 @@ -####################################### -# Syntax Coloring Map For RTC -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -DateTime KEYWORD1 -RTC_DS1307 KEYWORD1 -RTC_Millis KEYWORD1 -Ds1307SqwPinMode KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -year KEYWORD2 -month KEYWORD2 -day KEYWORD2 -hour KEYWORD2 -minute KEYWORD2 -second KEYWORD2 -dayOfWeek KEYWORD2 -secondstime KEYWORD2 -unixtime KEYWORD2 -begin KEYWORD2 -adjust KEYWORD2 -isrunning KEYWORD2 -now KEYWORD2 -readSqwPinMode KEYWORD2 -writeSqwPinMode KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### - diff --git a/feather_sensor_transmit/libraries/RTClib/library.properties b/feather_sensor_transmit/libraries/RTClib/library.properties deleted file mode 100644 index 13d6177..0000000 --- a/feather_sensor_transmit/libraries/RTClib/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=RTClib -version=1.2.1 -author=Adafruit -maintainer=Adafruit -sentence=A fork of Jeelab's fantastic RTC library -paragraph=A fork of Jeelab's fantastic RTC library -category=Timing -url=https://github.com/adafruit/RTClib -architectures=* diff --git a/feather_sensor_transmit/libraries/WiFi101/.travis.yml b/feather_sensor_transmit/libraries/WiFi101/.travis.yml deleted file mode 100644 index 465c761..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/.travis.yml +++ /dev/null @@ -1,48 +0,0 @@ -language: generic -env: - global: - - IDE_VERSION=1.8.2 - matrix: - - BOARD="arduino:avr:uno" - - BOARD="arduino:avr:mega:cpu=atmega2560" - - BOARD="arduino:sam:arduino_due_x_dbg" - - BOARD="arduino:samd:arduino_zero_edbg" - - BOARD="arduino:samd:mkr1000" - - BOARD="Intel:arc32:arduino_101" -before_install: - - wget http://downloads.arduino.cc/arduino-$IDE_VERSION-linux64.tar.xz - - tar xf arduino-$IDE_VERSION-linux64.tar.xz - - mv arduino-$IDE_VERSION $HOME/arduino-ide - - export PATH=$PATH:$HOME/arduino-ide - - if [[ "$BOARD" =~ "arduino:sam:" ]]; then - arduino --install-boards arduino:sam; - fi - - if [[ "$BOARD" =~ "arduino:samd:" ]]; then - arduino --install-boards arduino:samd; - fi - - if [[ "$BOARD" =~ "Intel:arc32" ]]; then - arduino --install-boards Intel:arc32; - fi - - buildExampleSketch() { arduino --verbose-build --verify --board $BOARD $PWD/examples/$1/$1.ino; } -install: - - mkdir -p $HOME/Arduino/libraries - - ln -s $PWD $HOME/Arduino/libraries/. -script: - - buildExampleSketch AP_SimpleWebServer - - buildExampleSketch CheckWifi101FirmwareVersion - - buildExampleSketch ConnectNoEncryption - - buildExampleSketch ConnectWithWEP - - buildExampleSketch ConnectWithWPA - - buildExampleSketch FirmwareUpdater - - buildExampleSketch MDNS_WiFiWebServer - - buildExampleSketch ScanNetworks - - buildExampleSketch SimpleWebServerWiFi - - buildExampleSketch WiFiChatServer - - buildExampleSketch WiFiPing - - buildExampleSketch WiFiSSLClient - - buildExampleSketch WiFiUdpNtpClient - - buildExampleSketch WiFiUdpSendReceiveString - - buildExampleSketch WiFiWebClient - - buildExampleSketch WiFiWebClientRepeating - - buildExampleSketch WiFiWebServer - diff --git a/feather_sensor_transmit/libraries/WiFi101/CHANGELOG b/feather_sensor_transmit/libraries/WiFi101/CHANGELOG deleted file mode 100644 index fbe1643..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/CHANGELOG +++ /dev/null @@ -1,122 +0,0 @@ -WiFi101 ?.?.? - ????.??.?? - -WiFi101 0.14.3 - 2017.06.01 - -* Fixed issues with WiFiMDNSResponder and large request packets -* Fixed issues with WiFiClient and sending data after the socket is closed - -WiFi101 0.14.2 - 2017.05.08 - -* Fixed issues with WiFiServer::write not working - -WiFi101 0.14.1 - 2017.04.20 - -* Fixed issues with WiFiMDNSResponder and Windows using Bonjour -* Correct cast of buffer size when processing received data - -WiFi101 0.14.0 - 2017.03.22 - -* Added support for firmware 19.5.2 -* Add ability to create Access Point with WPA security (f/w 19.5.2 or higher) -* Add WiFi.hostname(name) method to set custom host name for DHCP (f/w 19.5.2 or higher) -* Enables support for AES-256 Ciphers (f/w 19.5.2 or higher) -* Make provisioning mode backwards compatible with f/w 19.4.4 and older - -WiFi101 0.13.0 - 2017.03.01 - -* Added WiFi.channel() and WiFi.BSSID() - -WiFi101 0.12.1 - 2017.01.19 - -* Fixed tomorrow day issue in WiFi.getTime() - -WiFi101 0.12.0 - 2017.01.05 - -* Made provisioning mode easier and added example sketch -* Fixed WiFi.getTime() not returning 0, if time has not been synced via NTP -* Fixed crashing when connecting after scanning -* Fixed WiFiServer::available() returning valid client on outbound client connection -* Added WiFiUdp::beginMulticast(port) function for compatiblity with EthernetUdp, as beginMulti was inconsistent - -WiFi101 0.11.2 - 2016.12.15 - -* Fixed value of WiFi.getTime() being off by one day -* Fixed calling WiFi.RSSI() causing lockups - -WiFi101 0.11.1 - 2016.11.29 - -* Fixed regression for non-AVR boards that resulted in corrupt with data over than 1400 bytes was received - -WiFi101 0.11.0 - 2016.11.14 - -* Changed WiFi.ping(...) to return round trip time on success, negative value on error. Thanks @PKGeorgiev -* WiFi.end() now powers down the WiFi module -* WiFi.config(ip) can now be used to set a static IP for WiFi.begin(...) -* Fixed WiFi.BSSID(bssid) returning reversed MAC address -* Added WiFi.APClientMacAddress() API to get MAC address of AP client in AP mode -* Added WiFi.getTime() API to get epoch from NTP - -WiFi101 0.10.0 - 2016.09.08 - -* Added WiFi.end() to disconnect from the AP or end AP mode -* Added new WiFi.ping(...) functionality. Thanks @PKGeorgiev -* Added WiFi.setPins(...) to customize the CS, INTN, RESET and CHIPEN pins -* Add new WL_AP_LISTENING, WL_AP_CONNECTED, and WL_AP_FAILED status types for AP mode -* Fixed return value of WiFiUDP::beginPacket(host, port) when host is successfully resolved -* Added power management methods: WiFi.lowPowerMode(), WiFi.maxLowPowerMode(), WiFi.noLowPowerMode() -* Close TCP sockets when physical link is disconnected -* Fixed WiFi.RSSI() returning 0 when there was pending socket data - -WiFi101 0.9.1 - 2016.04.19 - -* Increased compatibility with 3rd party boards and architectures. -* Rename WiFiMdnsResponder.h/cpp to WiFiMDNSResponder.h/cpp -* Fixed buffering of UDP packet - -WiFi101 0.9.0 - 2016.03.21 - -* Fixed WiFi.status() hanging when shield is not present -* Fixed MAC address returning 00:00:00:00:00:00 with firmware version 19.3.0 -* Fixed SSL write functionality with firmware version 19.3.0 -* Fixed previous version of the library not working on the Uno and other boards that used PCINT's -* Added beginAP(...) API's to create access point with WEP passwords -* Fixed beginAP(...) channel off by one error -* Fixed WiFi.status() always returning WL_CONNECTED once connected, even if access point is disconnected later -* Added beginMulti API for Multicast UDP support -* Added WiFiMDNSResponder class and MDNS Web server example - -WiFi101 0.8.0 - 2016.02.15 - -* Added example for Access Point web server (thanks @ladyada) -* Fixed MAC Address printed in reverse order -* Allow another library to override PCINT ISR (fix issues when using the WiFi101 - library with other libraries like SoftwareSerial) - -WiFi101 0.7.0 - 2015.01.11 - -* Added support for WiFi Firmware 19.4.4 -* WiFi.hostByName(...) will not try resolve the domain name if it's already a numeric IP -* Fixed manual IP configuration (no DHCP) -* Fixed WiFiServer.available(), now follows API specification -* Fixed WEP key connection -* Fixed WiFiClient copy constructor and assignment operator. This improves stability when - Client objects are assigned or returned from functions. -* Control pins are now configurable through defines from variant. - -WiFi101 0.6.0 - 2015.11.27 - -* Fixed bug with AVR boards when Web Server is used -* Fixed UDP read bug on AVR Boards -* Added missing inlcude for SSL Client -* Fixed peek() function -* Fixed some examples - -WiFi101 0.5.1 - 2015.10.06 - -* Improved support for AVR Boards (Uno, Mega, Leonardo, etc.) and - ARM based boards (Due and Zero). - -WiFi101 0.5.0 - 2015.10.01 - -* Initial release - diff --git a/feather_sensor_transmit/libraries/WiFi101/README.adoc b/feather_sensor_transmit/libraries/WiFi101/README.adoc deleted file mode 100644 index 8eb6924..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/README.adoc +++ /dev/null @@ -1,27 +0,0 @@ -= WiFi library for the Arduino WiFi Shield 101 and MKR1000 board = - -image:https://travis-ci.org/arduino-libraries/WiFi101.svg?branch=master["Build Status", link="https://travis-ci.org/arduino-libraries/WiFi101"] - -This library implements a network driver for devices based -on the ATMEL WINC1500 WiFi module. - -For more information about this library please visit us at -https://www.arduino.cc/en/Reference/WiFi101 - -== License == - -Copyright (c) Arduino LLC. All right reserved. - -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 2.1 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 Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino b/feather_sensor_transmit/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino deleted file mode 100644 index b5caf7a..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino +++ /dev/null @@ -1,176 +0,0 @@ -/* - WiFi Web Server LED Blink - - A simple web server that lets you blink an LED via the web. - This sketch will create a new access point (with no password). - It will then launch a new server and print out the IP address - to the Serial monitor. From there, you can open that address in a web browser - to turn on and off the LED on pin 13. - - If the IP address of your shield is yourAddress: - http://yourAddress/H turns the LED on - http://yourAddress/L turns it off - - created 25 Nov 2012 - by Tom Igoe - adapted to WiFi AP by Adafruit - */ - -#include -#include -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int led = LED_BUILTIN; -int status = WL_IDLE_STATUS; -WiFiServer server(80); - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - Serial.println("Access Point Web Server"); - - pinMode(led, OUTPUT); // set the LED pin mode - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue - while (true); - } - - // by default the local IP address of will be 192.168.1.1 - // you can override it with the following: - // WiFi.config(IPAddress(10, 0, 0, 1)); - - // print the network name (SSID); - Serial.print("Creating access point named: "); - Serial.println(ssid); - - // Create open network. Change this line if you want to create an WEP network: - status = WiFi.beginAP(ssid); - if (status != WL_AP_LISTENING) { - Serial.println("Creating access point failed"); - // don't continue - while (true); - } - - // wait 10 seconds for connection: - delay(10000); - - // start the web server on port 80 - server.begin(); - - // you're connected now, so print out the status - printWiFiStatus(); -} - - -void loop() { - // compare the previous status to the current status - if (status != WiFi.status()) { - // it has changed update the variable - status = WiFi.status(); - - if (status == WL_AP_CONNECTED) { - byte remoteMac[6]; - - // a device has connected to the AP - Serial.print("Device connected to AP, MAC address: "); - WiFi.APClientMacAddress(remoteMac); - Serial.print(remoteMac[5], HEX); - Serial.print(":"); - Serial.print(remoteMac[4], HEX); - Serial.print(":"); - Serial.print(remoteMac[3], HEX); - Serial.print(":"); - Serial.print(remoteMac[2], HEX); - Serial.print(":"); - Serial.print(remoteMac[1], HEX); - Serial.print(":"); - Serial.println(remoteMac[0], HEX); - } else { - // a device has disconnected from the AP, and we are back in listening mode - Serial.println("Device disconnected from AP"); - } - } - - WiFiClient client = server.available(); // listen for incoming clients - - if (client) { // if you get a client, - Serial.println("new client"); // print a message out the serial port - String currentLine = ""; // make a String to hold incoming data from the client - while (client.connected()) { // loop while the client's connected - if (client.available()) { // if there's bytes to read from the client, - char c = client.read(); // read a byte, then - Serial.write(c); // print it out the serial monitor - if (c == '\n') { // if the byte is a newline character - - // if the current line is blank, you got two newline characters in a row. - // that's the end of the client HTTP request, so send a response: - if (currentLine.length() == 0) { - // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) - // and a content-type so the client knows what's coming, then a blank line: - client.println("HTTP/1.1 200 OK"); - client.println("Content-type:text/html"); - client.println(); - - // the content of the HTTP response follows the header: - client.print("Click here turn the LED on
"); - client.print("Click here turn the LED off
"); - - // The HTTP response ends with another blank line: - client.println(); - // break out of the while loop: - break; - } - else { // if you got a newline, then clear currentLine: - currentLine = ""; - } - } - else if (c != '\r') { // if you got anything else but a carriage return character, - currentLine += c; // add it to the end of the currentLine - } - - // Check to see if the client request was "GET /H" or "GET /L": - if (currentLine.endsWith("GET /H")) { - digitalWrite(led, HIGH); // GET /H turns the LED on - } - if (currentLine.endsWith("GET /L")) { - digitalWrite(led, LOW); // GET /L turns the LED off - } - } - } - // close the connection: - client.stop(); - Serial.println("client disconnected"); - } -} - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); - // print where to go in a browser: - Serial.print("To see this page in action, open a browser to http://"); - Serial.println(ip); - -} diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino b/feather_sensor_transmit/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino deleted file mode 100644 index 8cd312e..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino +++ /dev/null @@ -1,67 +0,0 @@ -/* - * This example check if the firmware loaded on the WiFi101 - * shield is updated. - * - * Circuit: - * - WiFi101 Shield attached - * - * Created 29 July 2015 by Cristian Maglie - * This code is in the public domain. - */ -#include -#include -#include - -void setup() { - // Initialize serial - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // Print a welcome message - Serial.println("WiFi101 firmware check."); - Serial.println(); - - // Check for the presence of the shield - Serial.print("WiFi101 shield: "); - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("NOT PRESENT"); - return; // don't continue - } - Serial.println("DETECTED"); - - // Print firmware version on the shield - String fv = WiFi.firmwareVersion(); - String latestFv; - Serial.print("Firmware version installed: "); - Serial.println(fv); - - if (REV(GET_CHIPID()) >= REV_3A0) { - // model B - latestFv = WIFI_FIRMWARE_LATEST_MODEL_B; - } else { - // model A - latestFv = WIFI_FIRMWARE_LATEST_MODEL_A; - } - - // Print required firmware version - Serial.print("Latest firmware version available : "); - Serial.println(latestFv); - - // Check if the latest version is installed - Serial.println(); - if (fv == latestFv) { - Serial.println("Check result: PASSED"); - } else { - Serial.println("Check result: NOT PASSED"); - Serial.println(" - The firmware version on the shield do not match the"); - Serial.println(" version required by the library, you may experience"); - Serial.println(" issues or failures."); - } -} - -void loop() { - // do nothing -} - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino b/feather_sensor_transmit/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino deleted file mode 100644 index f43a232..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino +++ /dev/null @@ -1,123 +0,0 @@ -/* - - This example connects to an unencrypted WiFi network. - Then it prints the MAC address of the WiFi shield, - the IP address obtained, and other network details. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - */ -#include -#include -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -int status = WL_IDLE_STATUS; // the WiFi radio's status - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to open SSID: "); - Serial.println(ssid); - status = WiFi.begin(ssid); - - // wait 10 seconds for connection: - delay(10000); - } - - // you're connected now, so print out the data: - Serial.print("You're connected to the network"); - printCurrentNet(); - printWiFiData(); -} - -void loop() { - // check the network connection once every 10 seconds: - delay(10000); - printCurrentNet(); -} - -void printWiFiData() { - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - Serial.println(ip); - - // print your MAC address: - byte mac[6]; - WiFi.macAddress(mac); - Serial.print("MAC address: "); - Serial.print(mac[5], HEX); - Serial.print(":"); - Serial.print(mac[4], HEX); - Serial.print(":"); - Serial.print(mac[3], HEX); - Serial.print(":"); - Serial.print(mac[2], HEX); - Serial.print(":"); - Serial.print(mac[1], HEX); - Serial.print(":"); - Serial.println(mac[0], HEX); - - // print your subnet mask: - IPAddress subnet = WiFi.subnetMask(); - Serial.print("NetMask: "); - Serial.println(subnet); - - // print your gateway address: - IPAddress gateway = WiFi.gatewayIP(); - Serial.print("Gateway: "); - Serial.println(gateway); -} - -void printCurrentNet() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print the MAC address of the router you're attached to: - byte bssid[6]; - WiFi.BSSID(bssid); - Serial.print("BSSID: "); - Serial.print(bssid[5], HEX); - Serial.print(":"); - Serial.print(bssid[4], HEX); - Serial.print(":"); - Serial.print(bssid[3], HEX); - Serial.print(":"); - Serial.print(bssid[2], HEX); - Serial.print(":"); - Serial.print(bssid[1], HEX); - Serial.print(":"); - Serial.println(bssid[0], HEX); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.println(rssi); - - // print the encryption type: - byte encryption = WiFi.encryptionType(); - Serial.print("Encryption Type:"); - Serial.println(encryption, HEX); -} - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h deleted file mode 100644 index 07c1148..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h +++ /dev/null @@ -1 +0,0 @@ -#define SECRET_SSID "" diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino b/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino deleted file mode 100644 index c226fa7..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino +++ /dev/null @@ -1,129 +0,0 @@ -/* - - This example connects to a WEP-encrypted WiFi network. - Then it prints the MAC address of the WiFi shield, - the IP address obtained, and other network details. - - If you use 40-bit WEP, you need a key that is 10 characters long, - and the characters must be hexadecimal (0-9 or A-F). - e.g. for 40-bit, ABBADEAF01 will work, but ABBADEAF won't work - (too short) and ABBAISDEAF won't work (I and S are not - hexadecimal characters). - - For 128-bit, you need a string that is 26 characters long. - D0D0DEADF00DABBADEAFBEADED will work because it's 26 characters, - all in the 0-9, A-F range. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - */ -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char key[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number -int status = WL_IDLE_STATUS; // the WiFi radio's status - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to WEP network, SSID: "); - Serial.println(ssid); - status = WiFi.begin(ssid, keyIndex, key); - - // wait 10 seconds for connection: - delay(10000); - } - - // once you are connected : - Serial.print("You're connected to the network"); - printCurrentNet(); - printWiFiData(); -} - -void loop() { - // check the network connection once every 10 seconds: - delay(10000); - printCurrentNet(); -} - -void printWiFiData() { - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - Serial.println(ip); - - // print your MAC address: - byte mac[6]; - WiFi.macAddress(mac); - Serial.print("MAC address: "); - Serial.print(mac[5], HEX); - Serial.print(":"); - Serial.print(mac[4], HEX); - Serial.print(":"); - Serial.print(mac[3], HEX); - Serial.print(":"); - Serial.print(mac[2], HEX); - Serial.print(":"); - Serial.print(mac[1], HEX); - Serial.print(":"); - Serial.println(mac[0], HEX); -} - -void printCurrentNet() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print the MAC address of the router you're attached to: - byte bssid[6]; - WiFi.BSSID(bssid); - Serial.print("BSSID: "); - Serial.print(bssid[5], HEX); - Serial.print(":"); - Serial.print(bssid[4], HEX); - Serial.print(":"); - Serial.print(bssid[3], HEX); - Serial.print(":"); - Serial.print(bssid[2], HEX); - Serial.print(":"); - Serial.print(bssid[1], HEX); - Serial.print(":"); - Serial.println(bssid[0], HEX); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.println(rssi); - - // print the encryption type: - byte encryption = WiFi.encryptionType(); - Serial.print("Encryption Type:"); - Serial.println(encryption, HEX); - Serial.println(); -} - - - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino b/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino deleted file mode 100644 index b98af65..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino +++ /dev/null @@ -1,119 +0,0 @@ -/* - - This example connects to an unencrypted WiFi network. - Then it prints the MAC address of the WiFi shield, - the IP address obtained, and other network details. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - */ -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int status = WL_IDLE_STATUS; // the WiFi radio's status - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to WPA SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - - // you're connected now, so print out the data: - Serial.print("You're connected to the network"); - printCurrentNet(); - printWiFiData(); - -} - -void loop() { - // check the network connection once every 10 seconds: - delay(10000); - printCurrentNet(); -} - -void printWiFiData() { - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - Serial.println(ip); - - // print your MAC address: - byte mac[6]; - WiFi.macAddress(mac); - Serial.print("MAC address: "); - Serial.print(mac[5], HEX); - Serial.print(":"); - Serial.print(mac[4], HEX); - Serial.print(":"); - Serial.print(mac[3], HEX); - Serial.print(":"); - Serial.print(mac[2], HEX); - Serial.print(":"); - Serial.print(mac[1], HEX); - Serial.print(":"); - Serial.println(mac[0], HEX); - -} - -void printCurrentNet() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print the MAC address of the router you're attached to: - byte bssid[6]; - WiFi.BSSID(bssid); - Serial.print("BSSID: "); - Serial.print(bssid[5], HEX); - Serial.print(":"); - Serial.print(bssid[4], HEX); - Serial.print(":"); - Serial.print(bssid[3], HEX); - Serial.print(":"); - Serial.print(bssid[2], HEX); - Serial.print(":"); - Serial.print(bssid[1], HEX); - Serial.print(":"); - Serial.println(bssid[0], HEX); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.println(rssi); - - // print the encryption type: - byte encryption = WiFi.encryptionType(); - Serial.print("Encryption Type:"); - Serial.println(encryption, HEX); - Serial.println(); -} - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino b/feather_sensor_transmit/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino deleted file mode 100644 index 897c770..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino +++ /dev/null @@ -1,62 +0,0 @@ -/* - Endianess.ino - Network byte order conversion functions. - Copyright (c) 2015 Arduino LLC. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - - -bool isBigEndian() { - uint32_t test = 0x11223344; - uint8_t *pTest = reinterpret_cast(&test); - return pTest[0] == 0x11; -} - -uint32_t fromNetwork32(uint32_t from) { - static const bool be = isBigEndian(); - if (be) { - return from; - } else { - uint8_t *pFrom = reinterpret_cast(&from); - uint32_t to; - to = pFrom[0]; to <<= 8; - to |= pFrom[1]; to <<= 8; - to |= pFrom[2]; to <<= 8; - to |= pFrom[3]; - return to; - } -} - -uint16_t fromNetwork16(uint16_t from) { - static bool be = isBigEndian(); - if (be) { - return from; - } else { - uint8_t *pFrom = reinterpret_cast(&from); - uint16_t to; - to = pFrom[0]; to <<= 8; - to |= pFrom[1]; - return to; - } -} - -uint32_t toNetwork32(uint32_t to) { - return fromNetwork32(to); -} - -uint16_t toNetwork16(uint16_t to) { - return fromNetwork16(to); -} - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino b/feather_sensor_transmit/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino deleted file mode 100644 index 1bbd6b9..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino +++ /dev/null @@ -1,129 +0,0 @@ -/* - FirmwareUpdate.h - Firmware Updater for WiFi101 / WINC1500. - Copyright (c) 2015 Arduino LLC. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include -#include - -typedef struct __attribute__((__packed__)) { - uint8_t command; - uint32_t address; - uint32_t arg1; - uint16_t payloadLength; - - // payloadLenght bytes of data follows... -} UartPacket; - -static const int MAX_PAYLOAD_SIZE = 1024; - -#define CMD_READ_FLASH 0x01 -#define CMD_WRITE_FLASH 0x02 -#define CMD_ERASE_FLASH 0x03 -#define CMD_MAX_PAYLOAD_SIZE 0x50 -#define CMD_HELLO 0x99 - -void setup() { - Serial.begin(115200); - - nm_bsp_init(); - if (m2m_wifi_download_mode() != M2M_SUCCESS) { - Serial.println(F("Failed to put the WiFi module in download mode")); - while (true) - ; - } -} - -void receivePacket(UartPacket *pkt, uint8_t *payload) { - // Read command - uint8_t *p = reinterpret_cast(pkt); - uint16_t l = sizeof(UartPacket); - while (l > 0) { - int c = Serial.read(); - if (c == -1) - continue; - *p++ = c; - l--; - } - - // Convert parameters from network byte order to cpu byte order - pkt->address = fromNetwork32(pkt->address); - pkt->arg1 = fromNetwork32(pkt->arg1); - pkt->payloadLength = fromNetwork16(pkt->payloadLength); - - // Read payload - l = pkt->payloadLength; - while (l > 0) { - int c = Serial.read(); - if (c == -1) - continue; - *payload++ = c; - l--; - } -} - -// Allocated statically so the compiler can tell us -// about the amount of used RAM -static UartPacket pkt; -static uint8_t payload[MAX_PAYLOAD_SIZE]; - -void loop() { - receivePacket(&pkt, payload); - - if (pkt.command == CMD_HELLO) { - if (pkt.address == 0x11223344 && pkt.arg1 == 0x55667788) - Serial.print("v10000"); - } - - if (pkt.command == CMD_MAX_PAYLOAD_SIZE) { - uint16_t res = toNetwork16(MAX_PAYLOAD_SIZE); - Serial.write(reinterpret_cast(&res), sizeof(res)); - } - - if (pkt.command == CMD_READ_FLASH) { - uint32_t address = pkt.address; - uint32_t len = pkt.arg1; - if (spi_flash_read(payload, address, len) != M2M_SUCCESS) { - Serial.println("ER"); - } else { - Serial.write(payload, len); - Serial.print("OK"); - } - } - - if (pkt.command == CMD_WRITE_FLASH) { - uint32_t address = pkt.address; - uint32_t len = pkt.payloadLength; - if (spi_flash_write(payload, address, len) != M2M_SUCCESS) { - Serial.print("ER"); - } else { - Serial.print("OK"); - } - } - - if (pkt.command == CMD_ERASE_FLASH) { - uint32_t address = pkt.address; - uint32_t len = pkt.arg1; - if (spi_flash_erase(address, len) != M2M_SUCCESS) { - Serial.print("ER"); - } else { - Serial.print("OK"); - } - } -} - - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino b/feather_sensor_transmit/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino deleted file mode 100644 index f62ac62..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino +++ /dev/null @@ -1,170 +0,0 @@ -/* - MDNS WiFi Web Server - - A simple web server that shows the value of the analog input pins, - and exposes itself on the MDNS name 'wifi101.local'. - - On Linux (like Ubuntu 15.04) or OSX you can access the web page - on the device in a browser at 'http://wifi101.local/'. - - On Windows you'll first need to install the Bonjour Printer Services - from: - https://support.apple.com/kb/dl999?locale=en_US - Then you can access the device in a browser at 'http://wifi101.local/'. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the WiFi.begin() call accordingly. - - Circuit: - * WiFi shield attached - * Analog inputs attached to pins A0 through A5 (optional) - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - modified 27 January 2016 - by Tony DiCola - -*/ - -#include -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -char mdnsName[] = "wifi101"; // the MDNS name that the board will respond to -// Note that the actual MDNS name will have '.local' after -// the name above, so "wifi101" will be accessible on -// the MDNS name "wifi101.local". - -int status = WL_IDLE_STATUS; - -// Create a MDNS responder to listen and respond to MDNS name requests. -WiFiMDNSResponder mdnsResponder; - -WiFiServer server(80); - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - // you're connected now, so print out the status: - printWiFiStatus(); - - server.begin(); - - // Setup the MDNS responder to listen to the configured name. - // NOTE: You _must_ call this _after_ connecting to the WiFi network and - // being assigned an IP address. - if (!mdnsResponder.begin(mdnsName)) { - Serial.println("Failed to start MDNS responder!"); - while(1); - } - - Serial.print("Server listening at http://"); - Serial.print(mdnsName); - Serial.println(".local/"); -} - - -void loop() { - // Call the update() function on the MDNS responder every loop iteration to - // make sure it can detect and respond to name requests. - mdnsResponder.poll(); - - // listen for incoming clients - WiFiClient client = server.available(); - if (client) { - Serial.println("new client"); - // an http request ends with a blank line - boolean currentLineIsBlank = true; - while (client.connected()) { - if (client.available()) { - char c = client.read(); - Serial.write(c); - // if you've gotten to the end of the line (received a newline - // character) and the line is blank, the http request has ended, - // so you can send a reply - if (c == '\n' && currentLineIsBlank) { - // send a standard http response header - client.println("HTTP/1.1 200 OK"); - client.println("Content-Type: text/html"); - client.println("Connection: close"); // the connection will be closed after completion of the response - client.println("Refresh: 5"); // refresh the page automatically every 5 sec - client.println(); - client.println(""); - client.println(""); - // output the value of each analog input pin - for (int analogChannel = 0; analogChannel < 6; analogChannel++) { - int sensorReading = analogRead(analogChannel); - client.print("analog input "); - client.print(analogChannel); - client.print(" is "); - client.print(sensorReading); - client.println("
"); - } - client.println(""); - break; - } - if (c == '\n') { - // you're starting a new line - currentLineIsBlank = true; - } - else if (c != '\r') { - // you've gotten a character on the current line - currentLineIsBlank = false; - } - } - } - // give the web browser time to receive the data - delay(1); - - // close the connection: - client.stop(); - Serial.println("client disconnected"); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino b/feather_sensor_transmit/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino deleted file mode 100644 index 0297707..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino +++ /dev/null @@ -1,167 +0,0 @@ -/* - WiFi Web Server - - A simple web server that shows the value of the analog input pins. - using a WiFi shield. - - This example is written to configure the WiFi settings using provisioning mode. - It also sets up an mDNS server so the IP address of the board doesn't have to - be obtained via the serial monitor. - - Circuit: - WiFi shield attached - Analog inputs attached to pins A0 through A5 (optional) - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - -*/ - -#include -#include -#include - -const int ledPin = 6; // LED pin for connectivity status indicator - -char mdnsName[] = "wifi101"; // the MDNS name that the board will respond to - // after WiFi settings have been provisioned -// Note that the actual MDNS name will have '.local' after -// the name above, so "wifi101" will be accessible on -// the MDNS name "wifi101.local". - -WiFiServer server(80); - -// Create a MDNS responder to listen and respond to MDNS name requests. -WiFiMDNSResponder mdnsResponder; - -void setup() { - //Initialize serial: - Serial.begin(9600); - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // configure the LED pin for output mode - pinMode(ledPin, OUTPUT); - - // Start in provisioning mode: - // 1) This will try to connect to a previously associated access point. - // 2) If this fails, an access point named "wifi101-XXXX" will be created, where XXXX - // is the last 4 digits of the boards MAC address. Once you are connected to the access point, - // you can configure an SSID and password by visiting http://wifi101/ - WiFi.beginProvision(); - - while (WiFi.status() != WL_CONNECTED) { - // wait while not connected - - // blink the led to show an unconnected status - digitalWrite(ledPin, HIGH); - delay(500); - digitalWrite(ledPin, LOW); - delay(500); - } - - // connected, make the LED stay on - digitalWrite(ledPin, HIGH); - - server.begin(); - - // Setup the MDNS responder to listen to the configured name. - // NOTE: You _must_ call this _after_ connecting to the WiFi network and - // being assigned an IP address. - if (!mdnsResponder.begin(mdnsName)) { - Serial.println("Failed to start MDNS responder!"); - while(1); - } - - Serial.print("Server listening at http://"); - Serial.print(mdnsName); - Serial.println(".local/"); - - // you're connected now, so print out the status: - printWiFiStatus(); -} - - -void loop() { - // Call the update() function on the MDNS responder every loop iteration to - // make sure it can detect and respond to name requests. - mdnsResponder.poll(); - - // listen for incoming clients - WiFiClient client = server.available(); - if (client) { - Serial.println("new client"); - // an http request ends with a blank line - boolean currentLineIsBlank = true; - while (client.connected()) { - if (client.available()) { - char c = client.read(); - Serial.write(c); - // if you've gotten to the end of the line (received a newline - // character) and the line is blank, the http request has ended, - // so you can send a reply - if (c == '\n' && currentLineIsBlank) { - // send a standard http response header - client.println("HTTP/1.1 200 OK"); - client.println("Content-Type: text/html"); - client.println("Connection: close"); // the connection will be closed after completion of the response - client.println("Refresh: 5"); // refresh the page automatically every 5 sec - client.println(); - client.println(""); - client.println(""); - // output the value of each analog input pin - for (int analogChannel = 0; analogChannel < 6; analogChannel++) { - int sensorReading = analogRead(analogChannel); - client.print("analog input "); - client.print(analogChannel); - client.print(" is "); - client.print(sensorReading); - client.println("
"); - } - client.println(""); - break; - } - if (c == '\n') { - // you're starting a new line - currentLineIsBlank = true; - } - else if (c != '\r') { - // you've gotten a character on the current line - currentLineIsBlank = false; - } - } - } - // give the web browser time to receive the data - delay(1); - - // close the connection: - client.stop(); - Serial.println("client disonnected"); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino b/feather_sensor_transmit/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino deleted file mode 100644 index 45b908e..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino +++ /dev/null @@ -1,120 +0,0 @@ -/* - - This example prints the WiFi shield's MAC address, and - scans for available WiFi networks using the WiFi shield. - Every ten seconds, it scans again. It doesn't actually - connect to any network, so no encryption scheme is specified. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 21 Junn 2012 - by Tom Igoe and Jaymes Dec - */ - - -#include -#include - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // Print WiFi MAC address: - printMacAddress(); - - // scan for existing networks: - Serial.println("Scanning available networks..."); - listNetworks(); -} - -void loop() { - delay(10000); - // scan for existing networks: - Serial.println("Scanning available networks..."); - listNetworks(); -} - -void printMacAddress() { - // the MAC address of your WiFi shield - byte mac[6]; - - // print your MAC address: - WiFi.macAddress(mac); - Serial.print("MAC: "); - Serial.print(mac[5], HEX); - Serial.print(":"); - Serial.print(mac[4], HEX); - Serial.print(":"); - Serial.print(mac[3], HEX); - Serial.print(":"); - Serial.print(mac[2], HEX); - Serial.print(":"); - Serial.print(mac[1], HEX); - Serial.print(":"); - Serial.println(mac[0], HEX); -} - -void listNetworks() { - // scan for nearby networks: - Serial.println("** Scan Networks **"); - int numSsid = WiFi.scanNetworks(); - if (numSsid == -1) - { - Serial.println("Couldn't get a wifi connection"); - while (true); - } - - // print the list of networks seen: - Serial.print("number of available networks:"); - Serial.println(numSsid); - - // print the network number and name for each network found: - for (int thisNet = 0; thisNet < numSsid; thisNet++) { - Serial.print(thisNet); - Serial.print(") "); - Serial.print(WiFi.SSID(thisNet)); - Serial.print("\tSignal: "); - Serial.print(WiFi.RSSI(thisNet)); - Serial.print(" dBm"); - Serial.print("\tEncryption: "); - printEncryptionType(WiFi.encryptionType(thisNet)); - Serial.flush(); - } -} - -void printEncryptionType(int thisType) { - // read the encryption type and print out the name: - switch (thisType) { - case ENC_TYPE_WEP: - Serial.println("WEP"); - break; - case ENC_TYPE_TKIP: - Serial.println("WPA"); - break; - case ENC_TYPE_CCMP: - Serial.println("WPA2"); - break; - case ENC_TYPE_NONE: - Serial.println("None"); - break; - case ENC_TYPE_AUTO: - Serial.println("Auto"); - break; - } -} - - - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino b/feather_sensor_transmit/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino deleted file mode 100644 index 2afb544..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino +++ /dev/null @@ -1,149 +0,0 @@ -/* - - This example prints the WiFi 101 shield or MKR1000 MAC address, and - scans for available WiFi networks using the WiFi 101 shield or MKR1000 board. - Every ten seconds, it scans again. It doesn't actually - connect to any network, so no encryption scheme is specified. - BSSID and WiFi channel are printed - - Circuit: - WiFi 101 shield attached or MKR1000 board - - This example is based on ScanNetworks - - created 1 Mar 2017 - by Arturo Guadalupi -*/ - - -#include -#include - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // Print WiFi MAC address: - printMacAddress(); - - // scan for existing networks: - Serial.println(); - Serial.println("Scanning available networks..."); - listNetworks(); -} - -void loop() { - delay(10000); - // scan for existing networks: - Serial.println("Scanning available networks..."); - listNetworks(); -} - -void printMacAddress() { - // the MAC address of your WiFi shield - byte mac[6]; - - // print your MAC address: - WiFi.macAddress(mac); - Serial.print("MAC: "); - print2Digits(mac[5]); - Serial.print(":"); - print2Digits(mac[4]); - Serial.print(":"); - print2Digits(mac[3]); - Serial.print(":"); - print2Digits(mac[2]); - Serial.print(":"); - print2Digits(mac[1]); - Serial.print(":"); - print2Digits(mac[0]); -} - -void listNetworks() { - // scan for nearby networks: - Serial.println("** Scan Networks **"); - int numSsid = WiFi.scanNetworks(); - if (numSsid == -1) - { - Serial.println("Couldn't get a WiFi connection"); - while (true); - } - - // print the list of networks seen: - Serial.print("number of available networks: "); - Serial.println(numSsid); - - // print the network number and name for each network found: - for (int thisNet = 0; thisNet < numSsid; thisNet++) { - Serial.print(thisNet + 1); - Serial.print(") "); - Serial.print("Signal: "); - Serial.print(WiFi.RSSI(thisNet)); - Serial.print(" dBm"); - Serial.print("\tChannel: "); - Serial.print(WiFi.channel(thisNet)); - byte bssid[6]; - Serial.print("\t\tBSSID: "); - printBSSID(WiFi.BSSID(thisNet, bssid)); - Serial.print("\tEncryption: "); - printEncryptionType(WiFi.encryptionType(thisNet)); - Serial.print("\t\tSSID: "); - Serial.println(WiFi.SSID(thisNet)); - Serial.flush(); - } - Serial.println(); -} - -void printBSSID(byte bssid[]) { - print2Digits(bssid[5]); - Serial.print(":"); - print2Digits(bssid[4]); - Serial.print(":"); - print2Digits(bssid[3]); - Serial.print(":"); - print2Digits(bssid[2]); - Serial.print(":"); - print2Digits(bssid[1]); - Serial.print(":"); - print2Digits(bssid[0]); -} - -void printEncryptionType(int thisType) { - // read the encryption type and print out the name: - switch (thisType) { - case ENC_TYPE_WEP: - Serial.print("WEP"); - break; - case ENC_TYPE_TKIP: - Serial.print("WPA"); - break; - case ENC_TYPE_CCMP: - Serial.print("WPA2"); - break; - case ENC_TYPE_NONE: - Serial.print("None"); - break; - case ENC_TYPE_AUTO: - Serial.print("Auto"); - break; - } -} - -void print2Digits(byte thisByte) { - if (thisByte < 0xF) { - Serial.print("0"); - } - Serial.print(thisByte, HEX); -} - - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino b/feather_sensor_transmit/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino deleted file mode 100644 index aeaf0c6..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino +++ /dev/null @@ -1,131 +0,0 @@ -/* - WiFi Web Server LED Blink - - A simple web server that lets you blink an LED via the web. - This sketch will print the IP address of your WiFi Shield (once connected) - to the Serial monitor. From there, you can open that address in a web browser - to turn on and off the LED on pin 9. - - If the IP address of your shield is yourAddress: - http://yourAddress/H turns the LED on - http://yourAddress/L turns it off - - This example is written for a network using WPA encryption. For - WEP or WPA, change the WiFi.begin() call accordingly. - - Circuit: - * WiFi shield attached - * LED attached to pin 9 - - created 25 Nov 2012 - by Tom Igoe - */ -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; -WiFiServer server(80); - -void setup() { - Serial.begin(9600); // initialize serial communication - pinMode(9, OUTPUT); // set the LED pin mode - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - while (true); // don't continue - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - // wait 10 seconds for connection: - delay(10000); - } - server.begin(); // start the web server on port 80 - printWiFiStatus(); // you're connected now, so print out the status -} - - -void loop() { - WiFiClient client = server.available(); // listen for incoming clients - - if (client) { // if you get a client, - Serial.println("new client"); // print a message out the serial port - String currentLine = ""; // make a String to hold incoming data from the client - while (client.connected()) { // loop while the client's connected - if (client.available()) { // if there's bytes to read from the client, - char c = client.read(); // read a byte, then - Serial.write(c); // print it out the serial monitor - if (c == '\n') { // if the byte is a newline character - - // if the current line is blank, you got two newline characters in a row. - // that's the end of the client HTTP request, so send a response: - if (currentLine.length() == 0) { - // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) - // and a content-type so the client knows what's coming, then a blank line: - client.println("HTTP/1.1 200 OK"); - client.println("Content-type:text/html"); - client.println(); - - // the content of the HTTP response follows the header: - client.print("Click here turn the LED on pin 9 on
"); - client.print("Click here turn the LED on pin 9 off
"); - - // The HTTP response ends with another blank line: - client.println(); - // break out of the while loop: - break; - } - else { // if you got a newline, then clear currentLine: - currentLine = ""; - } - } - else if (c != '\r') { // if you got anything else but a carriage return character, - currentLine += c; // add it to the end of the currentLine - } - - // Check to see if the client request was "GET /H" or "GET /L": - if (currentLine.endsWith("GET /H")) { - digitalWrite(9, HIGH); // GET /H turns the LED on - } - if (currentLine.endsWith("GET /L")) { - digitalWrite(9, LOW); // GET /L turns the LED off - } - } - } - // close the connection: - client.stop(); - Serial.println("client disonnected"); - } -} - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); - // print where to go in a browser: - Serial.print("To see this page in action, open a browser to http://"); - Serial.println(ip); -} diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino deleted file mode 100644 index ac7bd76..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino +++ /dev/null @@ -1,114 +0,0 @@ -/* - Chat Server - - A simple server that distributes any incoming messages to all - connected clients. To use telnet to your device's IP address and type. - You can see the client's input in the serial monitor as well. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the WiFi.begin() call accordingly. - - - Circuit: - * WiFi shield attached - - created 18 Dec 2009 - by David A. Mellis - modified 31 May 2012 - by Tom Igoe - - */ - -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) - -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; - -WiFiServer server(23); - -boolean alreadyConnected = false; // whether or not the client was connected previously - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - - // start the server: - server.begin(); - // you're connected now, so print out the status: - printWiFiStatus(); -} - - -void loop() { - // wait for a new client: - WiFiClient client = server.available(); - - - // when the client sends the first byte, say hello: - if (client) { - if (!alreadyConnected) { - // clead out the input buffer: - client.flush(); - Serial.println("We have a new client"); - client.println("Hello, client!"); - alreadyConnected = true; - } - - if (client.available() > 0) { - // read the bytes incoming from the client: - char thisChar = client.read(); - // echo the bytes back to the client: - server.write(thisChar); - // echo the bytes to the server as well: - Serial.write(thisChar); - } - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino deleted file mode 100644 index 9a51c19..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino +++ /dev/null @@ -1,140 +0,0 @@ -/* - - This example connects to a encrypted WiFi network (WPA/WPA2). - Then it prints the MAC address of the WiFi shield, - the IP address obtained, and other network details. - Then it continuously pings given host specified by IP Address or name. - - Circuit: - WiFi shield attached / MKR1000 - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 09 June 2016 - by Petar Georgiev -*/ -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int status = WL_IDLE_STATUS; // the WiFi radio's status - -// Specify IP address or hostname -String hostName = "www.google.com"; -int pingResult; - -void setup() { - // Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to WPA SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - - // wait 5 seconds for connection: - delay(5000); - } - - // you're connected now, so print out the data: - Serial.println("You're connected to the network"); - printCurrentNet(); - printWiFiData(); -} - -void loop() { - Serial.print("Pinging "); - Serial.print(hostName); - Serial.print(": "); - - pingResult = WiFi.ping(hostName); - - if (pingResult >= 0) { - Serial.print("SUCCESS! RTT = "); - Serial.print(pingResult); - Serial.println(" ms"); - } else { - Serial.print("FAILED! Error code: "); - Serial.println(pingResult); - } - - delay(5000); -} - -void printWiFiData() { - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP address : "); - Serial.println(ip); - - Serial.print("Subnet mask: "); - Serial.println((IPAddress)WiFi.subnetMask()); - - Serial.print("Gateway IP : "); - Serial.println((IPAddress)WiFi.gatewayIP()); - - // print your MAC address: - byte mac[6]; - WiFi.macAddress(mac); - Serial.print("MAC address: "); - Serial.print(mac[5], HEX); - Serial.print(":"); - Serial.print(mac[4], HEX); - Serial.print(":"); - Serial.print(mac[3], HEX); - Serial.print(":"); - Serial.print(mac[2], HEX); - Serial.print(":"); - Serial.print(mac[1], HEX); - Serial.print(":"); - Serial.println(mac[0], HEX); - Serial.println(); -} - -void printCurrentNet() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print the MAC address of the router you're attached to: - byte bssid[6]; - WiFi.BSSID(bssid); - Serial.print("BSSID: "); - Serial.print(bssid[5], HEX); - Serial.print(":"); - Serial.print(bssid[4], HEX); - Serial.print(":"); - Serial.print(bssid[3], HEX); - Serial.print(":"); - Serial.print(bssid[2], HEX); - Serial.print(":"); - Serial.print(bssid[1], HEX); - Serial.print(":"); - Serial.println(bssid[0], HEX); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI): "); - Serial.println(rssi); - - // print the encryption type: - byte encryption = WiFi.encryptionType(); - Serial.print("Encryption Type: "); - Serial.println(encryption, HEX); - Serial.println(); -} diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino deleted file mode 100644 index a436902..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino +++ /dev/null @@ -1,107 +0,0 @@ -/* -This example creates a client object that connects and transfers -data using always SSL. - -It is compatible with the methods normally related to plain -connections, like client.connect(host, port). - -Written by Arturo Guadalupi -last revision November 2015 - -*/ - -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; -// if you don't want to use DNS (and reduce your sketch size) -// use the numeric IP instead of the name for the server: -//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) -char server[] = "www.google.com"; // name address for Google (using DNS) - -// Initialize the Ethernet client library -// with the IP address and port of the server -// that you want to connect to (port 80 is default for HTTP): -WiFiSSLClient client; - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while (status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - Serial.println("Connected to wifi"); - printWiFiStatus(); - - Serial.println("\nStarting connection to server..."); - // if you get a connection, report back via serial: - if (client.connect(server, 443)) { - Serial.println("connected to server"); - // Make a HTTP request: - client.println("GET /search?q=arduino HTTP/1.1"); - client.println("Host: www.google.com"); - client.println("Connection: close"); - client.println(); - } -} - -void loop() { - // if there are incoming bytes available - // from the server, read them and print them: - while (client.available()) { - char c = client.read(); - Serial.write(c); - } - - // if the server's disconnected, stop the client: - if (!client.connected()) { - Serial.println(); - Serial.println("disconnecting from server."); - client.stop(); - - // do nothing forevermore: - while (true); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino deleted file mode 100644 index e82fbaa..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino +++ /dev/null @@ -1,182 +0,0 @@ -/* - - Udp NTP Client - - Get the time from a Network Time Protocol (NTP) time server - Demonstrates use of UDP sendPacket and ReceivePacket - For more on NTP time servers and the messages needed to communicate with them, - see http://en.wikipedia.org/wiki/Network_Time_Protocol - - created 4 Sep 2010 - by Michael Margolis - modified 9 Apr 2012 - by Tom Igoe - - This code is in the public domain. - - */ - -#include -#include -#include - -int status = WL_IDLE_STATUS; -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -unsigned int localPort = 2390; // local port to listen for UDP packets - -IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server - -const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message - -byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets - -// A UDP instance to let us send and receive packets over UDP -WiFiUDP Udp; - -void setup() -{ - // Open serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - - Serial.println("Connected to wifi"); - printWiFiStatus(); - - Serial.println("\nStarting connection to server..."); - Udp.begin(localPort); -} - -void loop() -{ - sendNTPpacket(timeServer); // send an NTP packet to a time server - // wait to see if a reply is available - delay(1000); - if ( Udp.parsePacket() ) { - Serial.println("packet received"); - // We've received a packet, read the data from it - Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer - - //the timestamp starts at byte 40 of the received packet and is four bytes, - // or two words, long. First, esxtract the two words: - - unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); - unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); - // combine the four bytes (two words) into a long integer - // this is NTP time (seconds since Jan 1 1900): - unsigned long secsSince1900 = highWord << 16 | lowWord; - Serial.print("Seconds since Jan 1 1900 = " ); - Serial.println(secsSince1900); - - // now convert NTP time into everyday time: - Serial.print("Unix time = "); - // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: - const unsigned long seventyYears = 2208988800UL; - // subtract seventy years: - unsigned long epoch = secsSince1900 - seventyYears; - // print Unix time: - Serial.println(epoch); - - - // print the hour, minute and second: - Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) - Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) - Serial.print(':'); - if ( ((epoch % 3600) / 60) < 10 ) { - // In the first 10 minutes of each hour, we'll want a leading '0' - Serial.print('0'); - } - Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) - Serial.print(':'); - if ( (epoch % 60) < 10 ) { - // In the first 10 seconds of each minute, we'll want a leading '0' - Serial.print('0'); - } - Serial.println(epoch % 60); // print the second - } - // wait ten seconds before asking for the time again - delay(10000); -} - -// send an NTP request to the time server at the given address -unsigned long sendNTPpacket(IPAddress& address) -{ - //Serial.println("1"); - // set all bytes in the buffer to 0 - memset(packetBuffer, 0, NTP_PACKET_SIZE); - // Initialize values needed to form NTP request - // (see URL above for details on the packets) - //Serial.println("2"); - packetBuffer[0] = 0b11100011; // LI, Version, Mode - packetBuffer[1] = 0; // Stratum, or type of clock - packetBuffer[2] = 6; // Polling Interval - packetBuffer[3] = 0xEC; // Peer Clock Precision - // 8 bytes of zero for Root Delay & Root Dispersion - packetBuffer[12] = 49; - packetBuffer[13] = 0x4E; - packetBuffer[14] = 49; - packetBuffer[15] = 52; - - //Serial.println("3"); - - // all NTP fields have been given values, now - // you can send a packet requesting a timestamp: - Udp.beginPacket(address, 123); //NTP requests are to port 123 - //Serial.println("4"); - Udp.write(packetBuffer, NTP_PACKET_SIZE); - //Serial.println("5"); - Udp.endPacket(); - //Serial.println("6"); -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - - - - - - - - - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino deleted file mode 100644 index cbc9f7f..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino +++ /dev/null @@ -1,113 +0,0 @@ -/* - WiFi UDP Send and Receive String - - This sketch wait an UDP packet on localPort using a WiFi shield. - When a packet is received an Acknowledge packet is sent to the client on port remotePort - - Circuit: - * WiFi shield attached - - created 30 December 2012 - by dlf (Metodo2 srl) - - */ - - -#include -#include -#include - -int status = WL_IDLE_STATUS; -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -unsigned int localPort = 2390; // local port to listen on - -char packetBuffer[255]; //buffer to hold incoming packet -char ReplyBuffer[] = "acknowledged"; // a string to send back - -WiFiUDP Udp; - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - Serial.println("Connected to wifi"); - printWiFiStatus(); - - Serial.println("\nStarting connection to server..."); - // if you get a connection, report back via serial: - Udp.begin(localPort); -} - -void loop() { - - // if there's data available, read a packet - int packetSize = Udp.parsePacket(); - if (packetSize) - { - Serial.print("Received packet of size "); - Serial.println(packetSize); - Serial.print("From "); - IPAddress remoteIp = Udp.remoteIP(); - Serial.print(remoteIp); - Serial.print(", port "); - Serial.println(Udp.remotePort()); - - // read the packet into packetBufffer - int len = Udp.read(packetBuffer, 255); - if (len > 0) packetBuffer[len] = 0; - Serial.println("Contents:"); - Serial.println(packetBuffer); - - // send a reply, to the IP address and port that sent us the packet we received - Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); - Udp.write(ReplyBuffer); - Udp.endPacket(); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - - - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino deleted file mode 100644 index 5faa779..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino +++ /dev/null @@ -1,121 +0,0 @@ -/* - Web client - - This sketch connects to a website (http://www.google.com) - using a WiFi shield. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the WiFi.begin() call accordingly. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the WiFi.begin() call accordingly. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - */ - - -#include -#include -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; -// if you don't want to use DNS (and reduce your sketch size) -// use the numeric IP instead of the name for the server: -//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) -char server[] = "www.google.com"; // name address for Google (using DNS) - -// Initialize the Ethernet client library -// with the IP address and port of the server -// that you want to connect to (port 80 is default for HTTP): -WiFiClient client; - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while (status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - Serial.println("Connected to wifi"); - printWiFiStatus(); - - Serial.println("\nStarting connection to server..."); - // if you get a connection, report back via serial: - if (client.connect(server, 80)) { - Serial.println("connected to server"); - // Make a HTTP request: - client.println("GET /search?q=arduino HTTP/1.1"); - client.println("Host: www.google.com"); - client.println("Connection: close"); - client.println(); - } -} - -void loop() { - // if there are incoming bytes available - // from the server, read them and print them: - while (client.available()) { - char c = client.read(); - Serial.write(c); - } - - // if the server's disconnected, stop the client: - if (!client.connected()) { - Serial.println(); - Serial.println("disconnecting from server."); - client.stop(); - - // do nothing forevermore: - while (true); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - - - - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino deleted file mode 100644 index ac8b4e5..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino +++ /dev/null @@ -1,127 +0,0 @@ -/* - Repeating WiFi Web Client - - This sketch connects to a a web server and makes a request - using an Arduino WiFi shield. - - Circuit: - * WiFi shield attached to pins SPI pins and pin 7 - - created 23 April 2012 - modified 31 May 2012 - by Tom Igoe - modified 13 Jan 2014 - by Federico Vanzati - - http://arduino.cc/en/Tutorial/WiFiWebClientRepeating - This code is in the public domain. - */ - -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; - -// Initialize the WiFi client library -WiFiClient client; - -// server address: -char server[] = "www.arduino.cc"; -//IPAddress server(64,131,82,241); - -unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds -const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - // you're connected now, so print out the status: - printWiFiStatus(); -} - -void loop() { - // if there's incoming data from the net connection. - // send it out the serial port. This is for debugging - // purposes only: - while (client.available()) { - char c = client.read(); - Serial.write(c); - } - - // if ten seconds have passed since your last connection, - // then connect again and send data: - if (millis() - lastConnectionTime > postingInterval) { - httpRequest(); - } - -} - -// this method makes a HTTP connection to the server: -void httpRequest() { - // close any connection before send a new request. - // This will free the socket on the WiFi shield - client.stop(); - - // if there's a successful connection: - if (client.connect(server, 80)) { - Serial.println("connecting..."); - // send the HTTP PUT request: - client.println("GET /latest.txt HTTP/1.1"); - client.println("Host: www.arduino.cc"); - client.println("User-Agent: ArduinoWiFi/1.1"); - client.println("Connection: close"); - client.println(); - - // note the time that the connection was made: - lastConnectionTime = millis(); - } - else { - // if you couldn't make a connection: - Serial.println("connection failed"); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino deleted file mode 100644 index 24d0083..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino +++ /dev/null @@ -1,135 +0,0 @@ -/* - WiFi Web Server - - A simple web server that shows the value of the analog input pins. - using a WiFi shield. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the WiFi.begin() call accordingly. - - Circuit: - * WiFi shield attached - * Analog inputs attached to pins A0 through A5 (optional) - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - - */ - -#include -#include - - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; - -WiFiServer server(80); - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while (status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - server.begin(); - // you're connected now, so print out the status: - printWiFiStatus(); -} - - -void loop() { - // listen for incoming clients - WiFiClient client = server.available(); - if (client) { - Serial.println("new client"); - // an http request ends with a blank line - boolean currentLineIsBlank = true; - while (client.connected()) { - if (client.available()) { - char c = client.read(); - Serial.write(c); - // if you've gotten to the end of the line (received a newline - // character) and the line is blank, the http request has ended, - // so you can send a reply - if (c == '\n' && currentLineIsBlank) { - // send a standard http response header - client.println("HTTP/1.1 200 OK"); - client.println("Content-Type: text/html"); - client.println("Connection: close"); // the connection will be closed after completion of the response - client.println("Refresh: 5"); // refresh the page automatically every 5 sec - client.println(); - client.println(""); - client.println(""); - // output the value of each analog input pin - for (int analogChannel = 0; analogChannel < 6; analogChannel++) { - int sensorReading = analogRead(analogChannel); - client.print("analog input "); - client.print(analogChannel); - client.print(" is "); - client.print(sensorReading); - client.println("
"); - } - client.println(""); - break; - } - if (c == '\n') { - // you're starting a new line - currentLineIsBlank = true; - } - else if (c != '\r') { - // you've gotten a character on the current line - currentLineIsBlank = false; - } - } - } - // give the web browser time to receive the data - delay(1); - - // close the connection: - client.stop(); - Serial.println("client disconnected"); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} diff --git a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h b/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit/libraries/WiFi101/keywords.txt b/feather_sensor_transmit/libraries/WiFi101/keywords.txt deleted file mode 100644 index 498954d..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/keywords.txt +++ /dev/null @@ -1,61 +0,0 @@ -####################################### -# Syntax Coloring Map For WiFi -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -WiFi KEYWORD1 -WiFi101 KEYWORD1 -Client KEYWORD1 -Server KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -setPins KEYWORD2 -status KEYWORD2 -connect KEYWORD2 -connectSSL KEYWORD2 -write KEYWORD2 -available KEYWORD2 -read KEYWORD2 -flush KEYWORD2 -stop KEYWORD2 -connected KEYWORD2 -begin KEYWORD2 -beginProvision KEYWORD2 -beginOrProvision KEYWORD2 -beginMulticast KEYWORD2 -disconnect KEYWORD2 -macAddress KEYWORD2 -localIP KEYWORD2 -subnetMask KEYWORD2 -gatewayIP KEYWORD2 -SSID KEYWORD2 -BSSID KEYWORD2 -APClientMacAddress KEYWORD2 -RSSI KEYWORD2 -encryptionType KEYWORD2 -channel KEYWORD2 -provisioned KEYWORD2 -getResult KEYWORD2 -getSocket KEYWORD2 -poll KEYWORD2 -getTime KEYWORD2 -hostname KEYWORD2 -WiFiClient KEYWORD2 -WiFiServer KEYWORD2 -WiFiSSLClient KEYWORD2 -WiFiMDNSResponder KEYWORD2 - -lowPowerMode KEYWORD2 -maxLowPowerMode KEYWORD2 -noLowPowerMode KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### - diff --git a/feather_sensor_transmit/libraries/WiFi101/library.properties b/feather_sensor_transmit/libraries/WiFi101/library.properties deleted file mode 100644 index f6d0b6d..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/library.properties +++ /dev/null @@ -1,10 +0,0 @@ -name=WiFi101 -version=0.14.4 -author=Arduino -maintainer=Arduino -sentence=Network driver for ATMEL WINC1500 module (used on Arduino/Genuino Wifi Shield 101 and MKR1000 boards) -paragraph=This library implements a network driver for devices based on the ATMEL WINC1500 wifi module -category=Communication -url=http://www.arduino.cc/en/Reference/WiFi101 -architectures=* -includes=WiFi101.h diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFi.cpp b/feather_sensor_transmit/libraries/WiFi101/src/WiFi.cpp deleted file mode 100644 index 0c71ffc..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/WiFi.cpp +++ /dev/null @@ -1,1106 +0,0 @@ -/* - WiFi.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifdef ARDUINO_ARCH_AVR -#include -#if (__AVR_LIBC_MAJOR__ < 2) -#define WIFI_101_NO_TIME_H -#endif -#endif - -#ifndef WIFI_101_NO_TIME_H -#include -#endif - -#if !defined(_TIME_H_) && !defined(TIME_H) -// another library overrided the time.h header -#define WIFI_101_NO_TIME_H -#endif - -#include "WiFi101.h" - -extern "C" { - #include "bsp/include/nm_bsp.h" - #include "bsp/include/nm_bsp_arduino.h" - #include "socket/include/socket_buffer.h" - #include "socket/include/m2m_socket_host_if.h" - #include "driver/source/nmasic.h" - #include "driver/include/m2m_periph.h" - #include "driver/include/m2m_ssl.h" -} - -static void wifi_cb(uint8_t u8MsgType, void *pvMsg) -{ - switch (u8MsgType) { - case M2M_WIFI_RESP_DEFAULT_CONNECT: - { - tstrM2MDefaultConnResp *pstrDefaultConnResp = (tstrM2MDefaultConnResp *)pvMsg; - if (pstrDefaultConnResp->s8ErrorCode) { - WiFi._status = WL_DISCONNECTED; - } - } - break; - - case M2M_WIFI_RESP_CON_STATE_CHANGED: - { - tstrM2mWifiStateChanged *pstrWifiState = (tstrM2mWifiStateChanged *)pvMsg; - if (pstrWifiState->u8CurrState == M2M_WIFI_CONNECTED) { - //SERIAL_PORT_MONITOR.println("wifi_cb: M2M_WIFI_RESP_CON_STATE_CHANGED: CONNECTED"); - if (WiFi._mode == WL_STA_MODE && !WiFi._dhcp) { - WiFi._status = WL_CONNECTED; - - // WiFi led ON. - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); - } else if (WiFi._mode == WL_AP_MODE) { - WiFi._status = WL_AP_CONNECTED; - } - } else if (pstrWifiState->u8CurrState == M2M_WIFI_DISCONNECTED) { - //SERIAL_PORT_MONITOR.println("wifi_cb: M2M_WIFI_RESP_CON_STATE_CHANGED: DISCONNECTED"); - if (WiFi._mode == WL_STA_MODE) { - WiFi._status = WL_DISCONNECTED; - if (WiFi._dhcp) { - WiFi._localip = 0; - WiFi._submask = 0; - WiFi._gateway = 0; - } - // Close sockets to clean state - // Clients will need to reconnect once the physical link will be re-established - for (int i=0; i < TCP_SOCK_MAX; i++) { - if (WiFi._client[i]) - WiFi._client[i]->stop(); - } - } else if (WiFi._mode == WL_AP_MODE) { - WiFi._status = WL_AP_LISTENING; - } - // WiFi led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); - } - } - break; - - case M2M_WIFI_REQ_DHCP_CONF: - { - if (WiFi._mode == WL_STA_MODE) { - tstrM2MIPConfig *pstrIPCfg = (tstrM2MIPConfig *)pvMsg; - WiFi._localip = pstrIPCfg->u32StaticIP; - WiFi._submask = pstrIPCfg->u32SubnetMask; - WiFi._gateway = pstrIPCfg->u32Gateway; - - WiFi._status = WL_CONNECTED; - - // WiFi led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0); - } - /*uint8_t *pu8IPAddress = (uint8_t *)pvMsg; - SERIAL_PORT_MONITOR.print("wifi_cb: M2M_WIFI_REQ_DHCP_CONF: IP is "); - SERIAL_PORT_MONITOR.print(pu8IPAddress[0], 10); - SERIAL_PORT_MONITOR.print("."); - SERIAL_PORT_MONITOR.print(pu8IPAddress[1], 10); - SERIAL_PORT_MONITOR.print("."); - SERIAL_PORT_MONITOR.print(pu8IPAddress[2], 10); - SERIAL_PORT_MONITOR.print("."); - SERIAL_PORT_MONITOR.print(pu8IPAddress[3], 10); - SERIAL_PORT_MONITOR.println("");*/ - } - break; - - case M2M_WIFI_RESP_CURRENT_RSSI: - { - WiFi._resolve = *((int8_t *)pvMsg); - } - break; - - case M2M_WIFI_RESP_PROVISION_INFO: - { - tstrM2MProvisionInfo *pstrProvInfo = (tstrM2MProvisionInfo *)pvMsg; - //SERIAL_PORT_MONITOR.println("wifi_cb: M2M_WIFI_RESP_PROVISION_INFO"); - - if (pstrProvInfo->u8Status == M2M_SUCCESS) { - memset(WiFi._ssid, 0, M2M_MAX_SSID_LEN); - memcpy(WiFi._ssid, (char *)pstrProvInfo->au8SSID, strlen((char *)pstrProvInfo->au8SSID)); - WiFi._mode = WL_STA_MODE; - WiFi._localip = 0; - WiFi._submask = 0; - WiFi._gateway = 0; - m2m_wifi_connect((char *)pstrProvInfo->au8SSID, strlen((char *)pstrProvInfo->au8SSID), - pstrProvInfo->u8SecType, pstrProvInfo->au8Password, M2M_WIFI_CH_ALL); - } else { - WiFi._status = WL_PROVISIONING_FAILED; - //SERIAL_PORT_MONITOR.println("wifi_cb: Provision failed.\r\n"); - WiFi.beginProvision(); - } - } - break; - - case M2M_WIFI_RESP_SCAN_DONE: - { - tstrM2mScanDone *pstrInfo = (tstrM2mScanDone *)pvMsg; - if (pstrInfo->u8NumofCh >= 1) { - WiFi._status = WL_SCAN_COMPLETED; - } - } - break; - - case M2M_WIFI_RESP_SCAN_RESULT: - { - tstrM2mWifiscanResult *pstrScanResult = (tstrM2mWifiscanResult *)pvMsg; - uint16_t scan_ssid_len = strlen((const char *)pstrScanResult->au8SSID); - memset(WiFi._scan_ssid, 0, M2M_MAX_SSID_LEN); - if (scan_ssid_len) { - memcpy(WiFi._scan_ssid, (const char *)pstrScanResult->au8SSID, scan_ssid_len); - } - if (WiFi._remoteMacAddress) { - // reverse copy the remote MAC - for(int i = 0; i < 6; i++) { - WiFi._remoteMacAddress[i] = pstrScanResult->au8BSSID[5-i]; - } - } - WiFi._resolve = pstrScanResult->s8rssi; - WiFi._scan_auth = pstrScanResult->u8AuthType; - WiFi._scan_channel = pstrScanResult->u8ch; - WiFi._status = WL_SCAN_COMPLETED; - } - break; - - case M2M_WIFI_RESP_CONN_INFO: - { - tstrM2MConnInfo *pstrConnInfo = (tstrM2MConnInfo*)pvMsg; - - if (WiFi._remoteMacAddress) { - // reverse copy the remote MAC - for(int i = 0; i < 6; i++) { - WiFi._remoteMacAddress[i] = pstrConnInfo->au8MACAddress[5-i]; - } - WiFi._remoteMacAddress = 0; - } - - strcpy((char *)WiFi._ssid, pstrConnInfo->acSSID); - } - break; - - case M2M_WIFI_RESP_GET_SYS_TIME: - { - if (WiFi._resolve != 0) { - memcpy((tstrSystemTime *)WiFi._resolve, pvMsg, sizeof(tstrSystemTime)); - - WiFi._resolve = 0; - } - } - break; - - default: - break; - } -} - -static void resolve_cb(uint8_t * /* hostName */, uint32_t hostIp) -{ - WiFi._resolve = hostIp; -} - -static void ping_cb(uint32 u32IPAddr, uint32 u32RTT, uint8 u8ErrorCode) -{ - if (PING_ERR_SUCCESS == u8ErrorCode) { - // Ensure this ICMP reply comes from requested IP address - if (WiFi._resolve == u32IPAddr) { - WiFi._resolve = (uint32_t)u32RTT; - } else { - // Another network device replied to the our ICMP request - WiFi._resolve = (uint32_t)WL_PING_DEST_UNREACHABLE; - } - } else if (PING_ERR_DEST_UNREACH == u8ErrorCode) { - WiFi._resolve = (uint32_t)WL_PING_DEST_UNREACHABLE; - } else if (PING_ERR_TIMEOUT == u8ErrorCode) { - WiFi._resolve = (uint32_t)WL_PING_TIMEOUT; - } else { - WiFi._resolve = (uint32_t)WL_PING_ERROR; - } -} - -WiFiClass::WiFiClass() -{ - _mode = WL_RESET_MODE; - _status = WL_NO_SHIELD; - _init = 0; -} - -void WiFiClass::setPins(int8_t cs, int8_t irq, int8_t rst, int8_t en) -{ - gi8Winc1501CsPin = cs; - gi8Winc1501IntnPin = irq; - gi8Winc1501ResetPin = rst; - gi8Winc1501ChipEnPin = en; -} - -int WiFiClass::init() -{ - tstrWifiInitParam param; - int8_t ret; - - // Initialize the WiFi BSP: - nm_bsp_init(); - - // Initialize WiFi module and register status callback: - param.pfAppWifiCb = wifi_cb; - ret = m2m_wifi_init(¶m); - if (M2M_SUCCESS != ret && M2M_ERR_FW_VER_MISMATCH != ret) { - // Error led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO18, 0); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO6, 1); - return ret; - } - - // Initialize socket API and register socket callback: - socketInit(); - socketBufferInit(); - registerSocketCallback(socketBufferCb, resolve_cb); - _init = 1; - _status = WL_IDLE_STATUS; - _localip = 0; - _submask = 0; - _gateway = 0; - _dhcp = 1; - _resolve = 0; - _remoteMacAddress = 0; - memset(_client, 0, sizeof(WiFiClient *) * TCP_SOCK_MAX); - - extern uint32 nmdrv_firm_ver; - - if (nmdrv_firm_ver >= M2M_MAKE_VERSION(19, 5, 0)) { - // enable AES-128 and AES-256 Ciphers, if firmware is 19.5.0 or higher - m2m_ssl_set_active_ciphersuites(SSL_NON_ECC_CIPHERS_AES_128 | SSL_NON_ECC_CIPHERS_AES_256); - } - - // Initialize IO expander LED control (rev A then rev B).. - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO18, 1); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO15, 1); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO18, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO6, 1); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO4, 1); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO5, 1); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO6, 1); - - return ret; -} - -extern "C" { - sint8 nm_get_firmware_info(tstrM2mRev* M2mRev); -} - -char* WiFiClass::firmwareVersion() -{ - tstrM2mRev rev; - - if (!_init) { - init(); - } - nm_get_firmware_info(&rev); - memset(_version, 0, 9); - if (rev.u8FirmwareMajor != rev.u8DriverMajor && rev.u8FirmwareMinor != rev.u8DriverMinor) { - sprintf(_version, "-Err-"); - } - else { - sprintf(_version, "%d.%d.%d", rev.u8FirmwareMajor, rev.u8FirmwareMinor, rev.u8FirmwarePatch); - } - return _version; -} - -uint8_t WiFiClass::begin() -{ - if (!_init) { - init(); - } - - // Connect to router: - if (_dhcp) { - _localip = 0; - _submask = 0; - _gateway = 0; - } - if (m2m_wifi_default_connect() < 0) { - _status = WL_CONNECT_FAILED; - return _status; - } - _status = WL_IDLE_STATUS; - _mode = WL_STA_MODE; - - // Wait for connection or timeout: - unsigned long start = millis(); - while (!(_status & WL_CONNECTED) && - !(_status & WL_DISCONNECTED) && - millis() - start < 60000) { - m2m_wifi_handle_events(NULL); - } - - memset(_ssid, 0, M2M_MAX_SSID_LEN); - - if (!(_status & WL_CONNECTED)) { - _mode = WL_RESET_MODE; - } else { - m2m_wifi_get_connection_info(); - - m2m_wifi_handle_events(NULL); - } - - return _status; -} - -uint8_t WiFiClass::begin(const char *ssid) -{ - return startConnect(ssid, M2M_WIFI_SEC_OPEN, (void *)0); -} - -uint8_t WiFiClass::begin(const char *ssid, uint8_t key_idx, const char* key) -{ - tstrM2mWifiWepParams wep_params; - - memset(&wep_params, 0, sizeof(tstrM2mWifiWepParams)); - wep_params.u8KeyIndx = key_idx; - wep_params.u8KeySz = strlen(key); - strcpy((char *)&wep_params.au8WepKey[0], key); - return startConnect(ssid, M2M_WIFI_SEC_WEP, &wep_params); -} - -uint8_t WiFiClass::begin(const char *ssid, const char *key) -{ - return startConnect(ssid, M2M_WIFI_SEC_WPA_PSK, key); -} - -uint8_t WiFiClass::startConnect(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo) -{ - if (!_init) { - init(); - } - - // Connect to router: - if (_dhcp) { - _localip = 0; - _submask = 0; - _gateway = 0; - } - if (m2m_wifi_connect((char*)ssid, strlen(ssid), u8SecType, (void*)pvAuthInfo, M2M_WIFI_CH_ALL) < 0) { - _status = WL_CONNECT_FAILED; - return _status; - } - _status = WL_IDLE_STATUS; - _mode = WL_STA_MODE; - - // Wait for connection or timeout: - unsigned long start = millis(); - while (!(_status & WL_CONNECTED) && - !(_status & WL_DISCONNECTED) && - millis() - start < 60000) { - m2m_wifi_handle_events(NULL); - } - if (!(_status & WL_CONNECTED)) { - _mode = WL_RESET_MODE; - } - - memset(_ssid, 0, M2M_MAX_SSID_LEN); - memcpy(_ssid, ssid, strlen(ssid)); - return _status; -} - -uint8_t WiFiClass::beginAP(const char *ssid) -{ - return beginAP(ssid, 1); -} - -uint8_t WiFiClass::beginAP(const char *ssid, uint8_t channel) -{ - return startAP(ssid, M2M_WIFI_SEC_OPEN, NULL, channel); -} - -uint8_t WiFiClass::beginAP(const char *ssid, uint8_t key_idx, const char* key) -{ - return beginAP(ssid, key_idx, key, 1); -} - -uint8_t WiFiClass::beginAP(const char *ssid, uint8_t key_idx, const char* key, uint8_t channel) -{ - tstrM2mWifiWepParams wep_params; - - if (key_idx == 0) { - key_idx = 1; // 1 is the minimum key index - } - - memset(&wep_params, 0, sizeof(tstrM2mWifiWepParams)); - wep_params.u8KeyIndx = key_idx; - wep_params.u8KeySz = strlen(key); - strcpy((char *)&wep_params.au8WepKey[0], key); - - return startAP(ssid, M2M_WIFI_SEC_WEP, &wep_params, channel); -} - -uint8_t WiFiClass::beginAP(const char *ssid, const char* key) -{ - return beginAP(ssid, key, 1); -} - -uint8_t WiFiClass::beginAP(const char *ssid, const char* key, uint8_t channel) -{ - return startAP(ssid, M2M_WIFI_SEC_WPA_PSK, key, channel); -} - -uint8_t WiFiClass::startAP(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo, uint8_t channel) -{ - tstrM2MAPConfig strM2MAPConfig; - - if (!_init) { - init(); - } - - if (channel == 0) { - channel = 1; // channel 1 is the minium channel - } - - // Enter Access Point mode: - memset(&strM2MAPConfig, 0x00, sizeof(tstrM2MAPConfig)); - strcpy((char *)&strM2MAPConfig.au8SSID, ssid); - strM2MAPConfig.u8ListenChannel = channel; - strM2MAPConfig.u8SecType = u8SecType; - if (_localip == 0) { - strM2MAPConfig.au8DHCPServerIP[0] = 192; - strM2MAPConfig.au8DHCPServerIP[1] = 168; - strM2MAPConfig.au8DHCPServerIP[2] = 1; - strM2MAPConfig.au8DHCPServerIP[3] = 1; - } else { - memcpy(strM2MAPConfig.au8DHCPServerIP, &_localip, sizeof(_localip)); - if (strM2MAPConfig.au8DHCPServerIP[3] == 100) { - // limitation of WINC1500 firmware, IP address of client is always x.x.x.100 - _status = WL_AP_FAILED; - return _status; - } - } - - if (u8SecType == M2M_WIFI_SEC_WEP) { - tstrM2mWifiWepParams* wep_params = (tstrM2mWifiWepParams*)pvAuthInfo; - - strM2MAPConfig.u8KeyIndx = wep_params->u8KeyIndx; - strM2MAPConfig.u8KeySz = wep_params->u8KeySz; - strcpy((char*)strM2MAPConfig.au8WepKey, (char *)wep_params->au8WepKey); - } - - if (u8SecType == M2M_WIFI_SEC_WPA_PSK) { - strM2MAPConfig.u8KeySz = strlen((char*)pvAuthInfo); - strcpy((char*)strM2MAPConfig.au8Key, (char *)pvAuthInfo); - } - - if (m2m_wifi_enable_ap(&strM2MAPConfig) < 0) { - _status = WL_AP_FAILED; - return _status; - } - _status = WL_AP_LISTENING; - _mode = WL_AP_MODE; - - memset(_ssid, 0, M2M_MAX_SSID_LEN); - memcpy(_ssid, ssid, strlen(ssid)); - m2m_memcpy((uint8 *)&_localip, (uint8 *)&strM2MAPConfig.au8DHCPServerIP[0], 4); - _submask = 0x00FFFFFF; - _gateway = _localip; - - // WiFi led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0); - - return _status; -} - -uint8_t WiFiClass::beginProvision() -{ - return beginProvision(1); -} - -uint8_t WiFiClass::beginProvision(uint8_t channel) -{ - // try to connect using begin - if (begin() != WL_CONNECTED) { - // failed, enter provisioning mode - - uint8_t mac[6]; - char provSsid[13]; - - // get MAC address for provisioning SSID - macAddress(mac); - sprintf(provSsid, "wifi101-%.2X%2X", mac[1], mac[0]); - - // start provisioning mode - startProvision(provSsid, "wifi101", channel); - } - - return status(); -} - -uint8_t WiFiClass::startProvision(const char *ssid, const char *url, uint8_t channel) -{ - tstrM2MAPConfig strM2MAPConfig; - - if (!_init) { - init(); - } - - // Enter Provision mode: - memset(&strM2MAPConfig, 0x00, sizeof(tstrM2MAPConfig)); - strcpy((char *)&strM2MAPConfig.au8SSID, ssid); - strM2MAPConfig.u8ListenChannel = channel; - strM2MAPConfig.u8SecType = M2M_WIFI_SEC_OPEN; - strM2MAPConfig.u8SsidHide = SSID_MODE_VISIBLE; - strM2MAPConfig.au8DHCPServerIP[0] = 192; - strM2MAPConfig.au8DHCPServerIP[1] = 168; - strM2MAPConfig.au8DHCPServerIP[2] = 1; - strM2MAPConfig.au8DHCPServerIP[3] = 1; - - if (m2m_wifi_start_provision_mode((tstrM2MAPConfig *)&strM2MAPConfig, (char*)url, 1) < 0) { - _status = WL_PROVISIONING_FAILED; - return _status; - } - _status = WL_PROVISIONING; - _mode = WL_PROV_MODE; - - memset(_ssid, 0, M2M_MAX_SSID_LEN); - memcpy(_ssid, ssid, strlen(ssid)); - m2m_memcpy((uint8 *)&_localip, (uint8 *)&strM2MAPConfig.au8DHCPServerIP[0], 4); - _submask = 0x00FFFFFF; - _gateway = _localip; - - // WiFi led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0); - - return _status; -} - -uint32_t WiFiClass::provisioned() -{ - m2m_wifi_handle_events(NULL); - - if (_mode == WL_STA_MODE) { - return 1; - } - else { - return 0; - } -} - -void WiFiClass::config(IPAddress local_ip) -{ - config(local_ip, (uint32_t)0); -} - -void WiFiClass::config(IPAddress local_ip, IPAddress dns_server) -{ - config(local_ip, dns_server, (uint32_t)0); -} - -void WiFiClass::config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway) -{ - config(local_ip, dns_server, gateway, (uint32_t)0); -} - -void WiFiClass::config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet) -{ - tstrM2MIPConfig conf; - - if (!_init) { - init(); - } - - conf.u32DNS = (uint32_t)dns_server; - conf.u32Gateway = (uint32_t)gateway; - conf.u32StaticIP = (uint32_t)local_ip; - conf.u32SubnetMask = (uint32_t)subnet; - _dhcp = 0; - m2m_wifi_enable_dhcp(0); // disable DHCP - m2m_wifi_set_static_ip(&conf); - _localip = conf.u32StaticIP; - _submask = conf.u32SubnetMask; - _gateway = conf.u32Gateway; -} - -void WiFiClass::hostname(const char* name) -{ - if (!_init) { - init(); - } - - m2m_wifi_set_device_name((uint8 *)name, strlen(name)); -} - -void WiFiClass::disconnect() -{ - m2m_wifi_disconnect(); - - // WiFi led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); -} - -void WiFiClass::end() -{ - if (_mode == WL_AP_MODE) { - m2m_wifi_disable_ap(); - } else { - if (_mode == WL_PROV_MODE) { - m2m_wifi_stop_provision_mode(); - } - - m2m_wifi_disconnect(); - } - - // WiFi led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); - - socketDeinit(); - - m2m_wifi_deinit(NULL); - - nm_bsp_deinit(); - - _mode = WL_RESET_MODE; - _status = WL_NO_SHIELD; - _init = 0; -} - -uint8_t *WiFiClass::macAddress(uint8_t *mac) -{ - m2m_wifi_get_mac_address(mac); - byte tmpMac[6], i; - - m2m_wifi_get_mac_address(tmpMac); - - for(i = 0; i < 6; i++) - mac[i] = tmpMac[5-i]; - - return mac; -} - -uint32_t WiFiClass::localIP() -{ - return _localip; -} - -uint32_t WiFiClass::subnetMask() -{ - return _submask; -} - -uint32_t WiFiClass::gatewayIP() -{ - return _gateway; -} - -char* WiFiClass::SSID() -{ - if (_status == WL_CONNECTED || _status == WL_AP_LISTENING || _status == WL_AP_CONNECTED) { - return _ssid; - } - else { - return 0; - } -} - -uint8_t* WiFiClass::BSSID(uint8_t* bssid) -{ - if (_mode == WL_AP_MODE) { - return macAddress(bssid); - } else { - return remoteMacAddress(bssid); - } -} - -uint8_t* WiFiClass::APClientMacAddress(uint8_t* mac) -{ - if (_mode == WL_AP_MODE) { - return remoteMacAddress(mac); - } else { - memset(mac, 0, 6); - return mac; - } -} - -uint8_t* WiFiClass::remoteMacAddress(uint8_t* remoteMacAddress) -{ - _remoteMacAddress = remoteMacAddress; - memset(remoteMacAddress, 0, 6); - - m2m_wifi_get_connection_info(); - - // Wait for connection or timeout: - unsigned long start = millis(); - while (_remoteMacAddress != 0 && millis() - start < 1000) { - m2m_wifi_handle_events(NULL); - } - - _remoteMacAddress = 0; - return remoteMacAddress; -} - -int32_t WiFiClass::RSSI() -{ - // Clear pending events: - m2m_wifi_handle_events(NULL); - - // Send RSSI request: - _resolve = 0; - if (m2m_wifi_req_curr_rssi() < 0) { - return 0; - } - - // Wait for connection or timeout: - unsigned long start = millis(); - while (_resolve == 0 && millis() - start < 1000) { - m2m_wifi_handle_events(NULL); - } - - int32_t rssi = _resolve; - - _resolve = 0; - - return rssi; -} - -int8_t WiFiClass::scanNetworks() -{ - wl_status_t tmp = _status; - - if (!_init) { - init(); - } - - // Start scan: - if (m2m_wifi_request_scan(M2M_WIFI_CH_ALL) < 0) { - return 0; - } - - // Wait for scan result or timeout: - _status = WL_IDLE_STATUS; - unsigned long start = millis(); - while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 5000) { - m2m_wifi_handle_events(NULL); - } - _status = tmp; - return m2m_wifi_get_num_ap_found(); -} - -char* WiFiClass::SSID(uint8_t pos) -{ - wl_status_t tmp = _status; - - // Get scan SSID result: - memset(_scan_ssid, 0, M2M_MAX_SSID_LEN); - if (m2m_wifi_req_scan_result(pos) < 0) { - return 0; - } - - // Wait for connection or timeout: - _status = WL_IDLE_STATUS; - unsigned long start = millis(); - while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - - _status = tmp; - _resolve = 0; - - return _scan_ssid; -} - -int32_t WiFiClass::RSSI(uint8_t pos) -{ - wl_status_t tmp = _status; - - // Get scan RSSI result: - if (m2m_wifi_req_scan_result(pos) < 0) { - return 0; - } - - // Wait for connection or timeout: - _status = WL_IDLE_STATUS; - unsigned long start = millis(); - while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - - _status = tmp; - - int32_t rssi = _resolve; - - _resolve = 0; - - return rssi; -} - -uint8_t WiFiClass::encryptionType() -{ - int8_t net = scanNetworks(); - - for (uint8_t i = 0; i < net; ++i) { - SSID(i); - if (strcmp(_scan_ssid, _ssid) == 0) { - break; - } - } - - return _scan_auth; -} - -uint8_t WiFiClass::encryptionType(uint8_t pos) -{ - wl_status_t tmp = _status; - - // Get scan auth result: - if (m2m_wifi_req_scan_result(pos) < 0) { - return 0; - } - - // Wait for connection or timeout: - _status = WL_IDLE_STATUS; - unsigned long start = millis(); - while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - - _status = tmp; - _resolve = 0; - - return _scan_auth; -} - -uint8_t* WiFiClass::BSSID(uint8_t pos, uint8_t* bssid) -{ - wl_status_t tmp = _status; - - _remoteMacAddress = bssid; - - // Get scan auth result: - if (m2m_wifi_req_scan_result(pos) < 0) { - return 0; - } - - // Wait for connection or timeout: - _status = WL_IDLE_STATUS; - unsigned long start = millis(); - while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - - _status = tmp; - _resolve = 0; - _remoteMacAddress = 0; - - return bssid; -} - -uint8_t WiFiClass::channel(uint8_t pos) -{ - wl_status_t tmp = _status; - - // Get scan auth result: - if (m2m_wifi_req_scan_result(pos) < 0) { - return 0; - } - - // Wait for connection or timeout: - _status = WL_IDLE_STATUS; - unsigned long start = millis(); - while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - - _status = tmp; - _resolve = 0; - - return _scan_channel; -} - -uint8_t WiFiClass::status() -{ - if (!_init) { - init(); - } - - m2m_wifi_handle_events(NULL); - - return _status; -} - -int WiFiClass::hostByName(const char* aHostname, IPAddress& aResult) -{ - - // check if aHostname is already an ipaddress - if (aResult.fromString(aHostname)) { - // if fromString returns true we have an IP address ready - return 1; - - } else { - // Network led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); - - // Send DNS request: - _resolve = 0; - if (gethostbyname((uint8 *)aHostname) < 0) { - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - return 0; - } - - // Wait for connection or timeout: - unsigned long start = millis(); - while (_resolve == 0 && millis() - start < 20000) { - m2m_wifi_handle_events(NULL); - } - - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - - if (_resolve == 0) { - return 0; - } - - aResult = _resolve; - _resolve = 0; - return 1; - } -} - -void WiFiClass::refresh(void) -{ - // Update state machine: - m2m_wifi_handle_events(NULL); -} - -void WiFiClass::lowPowerMode(void) -{ - m2m_wifi_set_sleep_mode(M2M_PS_H_AUTOMATIC, true); -} - -void WiFiClass::maxLowPowerMode(void) -{ - m2m_wifi_set_sleep_mode(M2M_PS_DEEP_AUTOMATIC, true); -} - -void WiFiClass::noLowPowerMode(void) -{ - m2m_wifi_set_sleep_mode(M2M_NO_PS, false); -} - -int WiFiClass::ping(const char* hostname, uint8_t ttl) -{ - IPAddress ip; - - if (hostByName(hostname, ip) > 0) { - return ping(ip, ttl); - } else { - return WL_PING_UNKNOWN_HOST; - } -} - -int WiFiClass::ping(const String &hostname, uint8_t ttl) -{ - return ping(hostname.c_str(), ttl); -} - -int WiFiClass::ping(IPAddress host, uint8_t ttl) -{ - // Network led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); - - uint32_t dstHost = (uint32_t)host; - _resolve = dstHost; - - if (m2m_ping_req((uint32_t)host, ttl, &ping_cb) < 0) { - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - // Error sending ping request - return WL_PING_ERROR; - } - - // Wait for success or timeout: - unsigned long start = millis(); - while (_resolve == dstHost && millis() - start < 5000) { - m2m_wifi_handle_events(NULL); - } - - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - - if (_resolve == dstHost) { - _resolve = 0; - return WL_PING_TIMEOUT; - } else { - int rtt = (int)_resolve; - _resolve = 0; - return rtt; - } -} - -uint32_t WiFiClass::getTime() -{ -#ifdef WIFI_101_NO_TIME_H - #warning "No system header included, WiFi.getTime() will always return 0" - return 0; -#else - tstrSystemTime systemTime; - - _resolve = (uint32_t)&systemTime; - - m2m_wifi_get_sytem_time(); - - unsigned long start = millis(); - while (_resolve != 0 && millis() - start < 5000) { - m2m_wifi_handle_events(NULL); - } - - time_t t = 0; - - if (_resolve == 0 && systemTime.u16Year > 0) { - struct tm tm; - - tm.tm_year = systemTime.u16Year - 1900; - tm.tm_mon = systemTime.u8Month - 1; - tm.tm_mday = systemTime.u8Day; - tm.tm_hour = systemTime.u8Hour; - tm.tm_min = systemTime.u8Minute; - tm.tm_sec = systemTime.u8Second; - tm.tm_isdst = -1; - - t = mktime(&tm); - } - - _resolve = 0; - - return t; -#endif -} - -WiFiClass WiFi; diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFi101.h b/feather_sensor_transmit/libraries/WiFi101/src/WiFi101.h deleted file mode 100644 index 6e46fab..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/WiFi101.h +++ /dev/null @@ -1,193 +0,0 @@ -/* - WiFi.h - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef WIFI_H -#define WIFI_H - -#define WIFI_FIRMWARE_LATEST_MODEL_A "19.4.4" -#define WIFI_FIRMWARE_LATEST_MODEL_B "19.5.2" - -// for backwards compatibility -#define WIFI_FIRMWARE_REQUIRED WIFI_FIRMWARE_LATEST_MODEL_B - -#include - -extern "C" { - #include "driver/include/m2m_wifi.h" - #include "socket/include/socket.h" -} - -#include "WiFiClient.h" -#include "WiFiSSLClient.h" -#include "WiFiServer.h" - -typedef enum { - WL_NO_SHIELD = 255, - WL_IDLE_STATUS = 0, - WL_NO_SSID_AVAIL, - WL_SCAN_COMPLETED, - WL_CONNECTED, - WL_CONNECT_FAILED, - WL_CONNECTION_LOST, - WL_DISCONNECTED, - WL_AP_LISTENING, - WL_AP_CONNECTED, - WL_AP_FAILED, - WL_PROVISIONING, - WL_PROVISIONING_FAILED -} wl_status_t; - -/* Encryption modes */ -enum wl_enc_type { /* Values map to 802.11 encryption suites... */ - ENC_TYPE_WEP = M2M_WIFI_SEC_WEP, - ENC_TYPE_TKIP = M2M_WIFI_SEC_WPA_PSK, - ENC_TYPE_CCMP = M2M_WIFI_SEC_802_1X, - /* ... except these two, 7 and 8 are reserved in 802.11-2007 */ - ENC_TYPE_NONE = M2M_WIFI_SEC_OPEN, - ENC_TYPE_AUTO = M2M_WIFI_SEC_INVALID -}; - -typedef enum { - WL_RESET_MODE = 0, - WL_STA_MODE, - WL_PROV_MODE, - WL_AP_MODE -} wl_mode_t; - -typedef enum { - WL_PING_DEST_UNREACHABLE = -1, - WL_PING_TIMEOUT = -2, - WL_PING_UNKNOWN_HOST = -3, - WL_PING_ERROR = -4 -} wl_ping_result_t; - -class WiFiClass -{ -public: - uint32_t _localip; - uint32_t _submask; - uint32_t _gateway; - int _dhcp; - uint32_t _resolve; - byte *_remoteMacAddress; - wl_mode_t _mode; - wl_status_t _status; - char _scan_ssid[M2M_MAX_SSID_LEN]; - uint8_t _scan_auth; - uint8_t _scan_channel; - char _ssid[M2M_MAX_SSID_LEN]; - WiFiClient *_client[TCP_SOCK_MAX]; - - WiFiClass(); - - void setPins(int8_t cs, int8_t irq, int8_t rst, int8_t en = -1); - - int init(); - - char* firmwareVersion(); - - /* Start Wifi connection with WPA/WPA2 encryption. - * - * param ssid: Pointer to the SSID string. - * param key: Key input buffer. - */ - uint8_t begin(); - uint8_t begin(const char *ssid); - uint8_t begin(const char *ssid, uint8_t key_idx, const char* key); - uint8_t begin(const char *ssid, const char *key); - uint8_t begin(const String &ssid) { return begin(ssid.c_str()); } - uint8_t begin(const String &ssid, uint8_t key_idx, const String &key) { return begin(ssid.c_str(), key_idx, key.c_str()); } - uint8_t begin(const String &ssid, const String &key) { return begin(ssid.c_str(), key.c_str()); } - - /* Start Wifi in Access Point, with open security. - * Only one client can connect to the AP at a time. - * - * param ssid: Pointer to the SSID string. - * param channel: Wifi channel to use. Valid values are 1-12. - */ - uint8_t beginAP(const char *ssid); - uint8_t beginAP(const char *ssid, uint8_t channel); - uint8_t beginAP(const char *ssid, uint8_t key_idx, const char* key); - uint8_t beginAP(const char *ssid, uint8_t key_idx, const char* key, uint8_t channel); - uint8_t beginAP(const char *ssid, const char* key); - uint8_t beginAP(const char *ssid, const char* key, uint8_t channel); - - uint8_t beginProvision(); - uint8_t beginProvision(uint8_t channel); - - uint32_t provisioned(); - - void config(IPAddress local_ip); - void config(IPAddress local_ip, IPAddress dns_server); - void config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway); - void config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet); - - void hostname(const char* name); - - void disconnect(); - void end(); - - uint8_t *macAddress(uint8_t *mac); - - uint32_t localIP(); - uint32_t subnetMask(); - uint32_t gatewayIP(); - char* SSID(); - int32_t RSSI(); - uint8_t encryptionType(); - uint8_t* BSSID(uint8_t* bssid); - uint8_t* APClientMacAddress(uint8_t* mac); - int8_t scanNetworks(); - char* SSID(uint8_t pos); - int32_t RSSI(uint8_t pos); - uint8_t encryptionType(uint8_t pos); - uint8_t* BSSID(uint8_t pos, uint8_t* bssid); - uint8_t channel(uint8_t pos); - - uint8_t status(); - - int hostByName(const char* hostname, IPAddress& result); - int hostByName(const String &hostname, IPAddress& result) { return hostByName(hostname.c_str(), result); } - - int ping(const char* hostname, uint8_t ttl = 128); - int ping(const String &hostname, uint8_t ttl = 128); - int ping(IPAddress host, uint8_t ttl = 128); - - unsigned long getTime(); - - void refresh(void); - - void lowPowerMode(void); - void maxLowPowerMode(void); - void noLowPowerMode(void); - -private: - int _init; - char _version[9]; - - uint8_t startConnect(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo); - uint8_t startAP(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo, uint8_t channel); - uint8_t* remoteMacAddress(uint8_t* remoteMacAddress); - - uint8_t startProvision(const char *ssid, const char *url, uint8_t channel); -}; - -extern WiFiClass WiFi; - -#endif /* WIFI_H */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiClient.cpp b/feather_sensor_transmit/libraries/WiFi101/src/WiFiClient.cpp deleted file mode 100644 index 8298618..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/WiFiClient.cpp +++ /dev/null @@ -1,308 +0,0 @@ -/* - WiFiClient.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -extern "C" { - #include "socket/include/socket.h" - #include "driver/include/m2m_periph.h" -} - -#include "WiFi101.h" -#include "WiFiClient.h" - -#define IS_CONNECTED (_flag & SOCKET_BUFFER_FLAG_CONNECTED) - -WiFiClient::WiFiClient() -{ - _socket = -1; - _flag = 0; - _head = 0; - _tail = 0; -} - -WiFiClient::WiFiClient(uint8_t sock, uint8_t parentsock) -{ - // Spawn connected TCP client from TCP server socket: - _socket = sock; - _flag = SOCKET_BUFFER_FLAG_CONNECTED; - if (parentsock) { - _flag |= ((uint32_t)parentsock) << SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS; - } - _head = 0; - _tail = 0; - for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { - if (WiFi._client[sock] == this) - WiFi._client[sock] = 0; - } - WiFi._client[_socket] = this; - - // Add socket buffer handler: - socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_buffer); - - // Enable receive buffer: - recv(_socket, _buffer, SOCKET_BUFFER_MTU, 0); - - m2m_wifi_handle_events(NULL); -} - -WiFiClient::WiFiClient(const WiFiClient& other) -{ - copyFrom(other); -} - -void WiFiClient::copyFrom(const WiFiClient& other) -{ - _socket = other._socket; - _flag = other._flag; - _head = other._head; - _tail = other._tail; - if (_head > _tail) { - memcpy(_buffer + _tail, other._buffer + _tail, (_head - _tail)); - } - - for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { - if (WiFi._client[sock] == this) - WiFi._client[sock] = 0; - } - - if (_socket > -1) { - WiFi._client[_socket] = this; - - // Add socket buffer handler: - socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_buffer); - - // Enable receive buffer: - recv(_socket, _buffer, SOCKET_BUFFER_MTU, 0); - } - - m2m_wifi_handle_events(NULL); -} - -int WiFiClient::connectSSL(const char* host, uint16_t port) -{ - return connect(host, port, SOCKET_FLAGS_SSL); -} - -int WiFiClient::connectSSL(IPAddress ip, uint16_t port) -{ - return connect(ip, port, SOCKET_FLAGS_SSL, 0); -} - -int WiFiClient::connect(const char* host, uint16_t port) -{ - return connect(host, port, 0); -} - -int WiFiClient::connect(IPAddress ip, uint16_t port) -{ - return connect(ip, port, 0, 0); -} - -int WiFiClient::connect(const char* host, uint16_t port, uint8_t opt) -{ - IPAddress remote_addr; - if (WiFi.hostByName(host, remote_addr)) { - return connect(remote_addr, port, opt, (const uint8_t *)host); - } - return 0; -} - -int WiFiClient::connect(IPAddress ip, uint16_t port, uint8_t opt, const uint8_t *hostname) -{ - struct sockaddr_in addr; - - // Initialize socket address structure: - addr.sin_family = AF_INET; - addr.sin_port = _htons(port); - addr.sin_addr.s_addr = ip; - - // Create TCP socket: - _flag = 0; - _head = 0; - _tail = 0; - if ((_socket = socket(AF_INET, SOCK_STREAM, opt)) < 0) { - return 0; - } - - if (opt & SOCKET_FLAGS_SSL && hostname) { - setsockopt(_socket, SOL_SSL_SOCKET, SO_SSL_SNI, hostname, m2m_strlen((uint8_t *)hostname)); - } - - // Add socket buffer handler: - socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_buffer); - - // Connect to remote host: - if (connectSocket(_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { - close(_socket); - _socket = -1; - return 0; - } - - // Wait for connection or timeout: - unsigned long start = millis(); - while (!IS_CONNECTED && millis() - start < 20000) { - m2m_wifi_handle_events(NULL); - } - if (!IS_CONNECTED) { - close(_socket); - _socket = -1; - return 0; - } - - WiFi._client[_socket] = this; - - return 1; -} - -size_t WiFiClient::write(uint8_t b) -{ - return write(&b, 1); -} - -size_t WiFiClient::write(const uint8_t *buf, size_t size) -{ - sint16 err; - - if (_socket < 0 || size == 0 || !IS_CONNECTED) { - setWriteError(); - return 0; - } - - // Network led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); - - m2m_wifi_handle_events(NULL); - - while ((err = send(_socket, (void *)buf, size, 0)) < 0) { - // Exit on fatal error, retry if buffer not ready. - if (err != SOCK_ERR_BUFFER_FULL) { - setWriteError(); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - return 0; - } - m2m_wifi_handle_events(NULL); - } - - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - - return size; -} - -int WiFiClient::available() -{ - m2m_wifi_handle_events(NULL); - - if (_socket != -1) { - return _head - _tail; - } - return 0; -} - -int WiFiClient::read() -{ - uint8_t b; - - if (read(&b, sizeof(b)) == -1) { - return -1; - } - - return b; -} - -int WiFiClient::read(uint8_t* buf, size_t size) -{ - // sizeof(size_t) is architecture dependent - // but we need a 16 bit data type here - uint16_t size_tmp = available(); - - if (size_tmp == 0) { - return -1; - } - - if (size < size_tmp) { - size_tmp = size; - } - - for (uint32_t i = 0; i < size_tmp; ++i) { - buf[i] = _buffer[_tail++]; - } - - if (_tail == _head) { - _tail = _head = 0; - _flag &= ~SOCKET_BUFFER_FLAG_FULL; - recv(_socket, _buffer, SOCKET_BUFFER_MTU, 0); - m2m_wifi_handle_events(NULL); - } - - return size_tmp; -} - -int WiFiClient::peek() -{ - if (!available()) - return -1; - - return _buffer[_tail]; -} - -void WiFiClient::flush() -{ - while (available()) - read(); -} - -void WiFiClient::stop() -{ - if (_socket < 0) - return; - - socketBufferUnregister(_socket); - close(_socket); - _socket = -1; - _flag = 0; -} - -uint8_t WiFiClient::connected() -{ - m2m_wifi_handle_events(NULL); - if (available()) - return 1; - return IS_CONNECTED; -} - -uint8_t WiFiClient::status() -{ - // Deprecated. - return 0; -} - -WiFiClient::operator bool() -{ - return _socket != -1; -} - -WiFiClient& WiFiClient::operator =(const WiFiClient& other) -{ - copyFrom(other); - - return *this; -} diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiClient.h b/feather_sensor_transmit/libraries/WiFi101/src/WiFiClient.h deleted file mode 100644 index bef171d..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/WiFiClient.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - WiFiClient.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef WIFICLIENT_H -#define WIFICLIENT_H - -#include -#include -#include -#include "socket/include/socket_buffer.h" - -class WiFiClient : public Client { - -public: - WiFiClient(); - WiFiClient(uint8_t sock, uint8_t parentsock = 0); - WiFiClient(const WiFiClient& other); - - uint8_t status(); - - int connectSSL(IPAddress ip, uint16_t port); - int connectSSL(const char* host, uint16_t port); - virtual int connect(IPAddress ip, uint16_t port); - virtual int connect(const char* host, uint16_t port); - virtual size_t write(uint8_t); - virtual size_t write(const uint8_t *buf, size_t size); - virtual int available(); - virtual int read(); - virtual int read(uint8_t *buf, size_t size); - virtual int peek(); - virtual void flush(); - virtual void stop(); - virtual uint8_t connected(); - virtual operator bool(); - virtual WiFiClient& operator =(const WiFiClient& other); - - using Print::write; - - uint32_t _flag; - -private: - SOCKET _socket; - uint32_t _head; - uint32_t _tail; - uint8_t _buffer[SOCKET_BUFFER_TCP_SIZE]; - int connect(const char* host, uint16_t port, uint8_t opt); - int connect(IPAddress ip, uint16_t port, uint8_t opt, const uint8_t *hostname); - void copyFrom(const WiFiClient& other); - -}; - -#endif /* WIFICLIENT_H */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiMDNSResponder.cpp b/feather_sensor_transmit/libraries/WiFi101/src/WiFiMDNSResponder.cpp deleted file mode 100644 index a192113..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/WiFiMDNSResponder.cpp +++ /dev/null @@ -1,220 +0,0 @@ -// Port of CC3000 MDNS Responder to WINC1500. -// Author: Tony DiCola -// -// This MDNSResponder class implements just enough MDNS functionality to respond -// to name requests, for example 'foo.local'. This does not implement any other -// MDNS or Bonjour functionality like services, etc. -// -// Copyright (c) 2016 Adafruit Industries. All right reserved. -// -// 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 2.1 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 Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -#include -#ifndef ARDUINO_ARCH_AVR -#include -#endif - -#include "Arduino.h" -#include "WiFiMDNSResponder.h" - -// Important RFC's for reference: -// - DNS request and response: http://www.ietf.org/rfc/rfc1035.txt -// - Multicast DNS: http://www.ietf.org/rfc/rfc6762.txt - -#define HEADER_SIZE 12 -#define TTL_OFFSET 4 -#define IP_OFFSET 10 - -const uint8_t expectedRequestHeader[HEADER_SIZE] PROGMEM = { - 0x00, 0x00, - 0x00, 0x00, - 0x00, 0x01, // questions (these 2 bytes are ignored) - 0x00, 0x00, - 0x00, 0x00, - 0x00, 0x00 -}; - -const uint8_t responseHeader[] PROGMEM = { - 0x00, 0x00, // ID = 0 - 0x84, 0x00, // Flags = response + authoritative answer - 0x00, 0x00, // Question count = 0 - 0x00, 0x01, // Answer count = 1 - 0x00, 0x00, // Name server records = 0 - 0x00, 0x01 // Additional records = 1 -}; - -// Generate positive response for IPV4 address -const uint8_t aRecord[] PROGMEM = { - 0x00, 0x01, // Type = 1, A record/IPV4 address - 0x80, 0x01, // Class = Internet, with cache flush bit - 0x00, 0x00, 0x00, 0x00, // TTL in seconds, to be filled in later - 0x00, 0x04, // Length of record - 0x00, 0x00, 0x00, 0x00 // IP address, to be filled in later -}; - -// Generate negative response for IPV6 address (CC3000 doesn't support IPV6) -const uint8_t nsecRecord[] PROGMEM = { - 0xC0, 0x0C, // Name offset - 0x00, 0x2F, // Type = 47, NSEC (overloaded by MDNS) - 0x80, 0x01, // Class = Internet, with cache flush bit - 0x00, 0x00, 0x00, 0x00, // TTL in seconds, to be filled in later - 0x00, 0x08, // Length of record - 0xC0, 0x0C, // Next domain = offset to FQDN - 0x00, // Block number = 0 - 0x04, // Length of bitmap = 4 bytes - 0x40, 0x00, 0x00, 0x00 // Bitmap value = Only first bit (A record/IPV4) is set -}; - -const uint8_t domain[] PROGMEM = { 'l', 'o', 'c', 'a', 'l' }; - -WiFiMDNSResponder::WiFiMDNSResponder() : - minimumExpectedRequestLength(0) -{ -} - -WiFiMDNSResponder::~WiFiMDNSResponder() -{ -} - -bool WiFiMDNSResponder::begin(const char* _name, uint32_t _ttlSeconds) -{ - int nameLength = strlen(_name); - - if (nameLength > 255) { - // Can only handle domains that are upto 255 chars in length. - minimumExpectedRequestLength = 0; - return false; - } - - name = _name; - ttlSeconds = _ttlSeconds; - - name.toLowerCase(); - minimumExpectedRequestLength = HEADER_SIZE + 1 + nameLength + 1 + sizeof(domain) + 5; - - // Open the MDNS UDP listening socket on port 5353 with multicast address - // 224.0.0.251 (0xE00000FB) - if (!udpSocket.beginMulticast(IPAddress(224, 0, 0, 251), 5353)) { - return false; - } - - return true; -} - -void WiFiMDNSResponder::poll() -{ - if (parseRequest()) { - replyToRequest(); - } -} - -bool WiFiMDNSResponder::parseRequest() -{ - int packetLength = udpSocket.parsePacket(); - - if (packetLength) { - // check if parsed packet matches expected request length - if (packetLength < minimumExpectedRequestLength) { - // it does not, read the full packet in and drop data - while(udpSocket.available()) { - udpSocket.read(); - } - - return false; - } - - // read up to the min expect request length - uint8_t request[minimumExpectedRequestLength]; - udpSocket.read(request, minimumExpectedRequestLength); - - // discard the rest - while(udpSocket.available()) { - udpSocket.read(); - } - - // parse request - uint8_t requestNameLength = request[HEADER_SIZE]; - uint8_t* requestName = &request[HEADER_SIZE + 1]; - uint8_t requestDomainLength = request[HEADER_SIZE + 1 + requestNameLength]; - uint8_t* requestDomain = &request[HEADER_SIZE + 1 + requestNameLength + 1]; - uint16_t requestQtype; - uint16_t requestQclass; - - memcpy(&requestQtype, &request[minimumExpectedRequestLength - 4], sizeof(requestQtype)); - memcpy(&requestQclass, &request[minimumExpectedRequestLength - 2], sizeof(requestQclass)); - - requestQtype = _ntohs(requestQtype); - requestQclass = _ntohs(requestQclass); - - // compare request - if (memcmp_P(request, expectedRequestHeader, 4) == 0 && // request header start match - memcmp_P(&request[6], &expectedRequestHeader[6], 6) == 0 && // request header end match - requestNameLength == name.length() && // name length match - strncasecmp(name.c_str(), (char*)requestName, requestNameLength) == 0 && // name match - requestDomainLength == sizeof(domain) && // domain length match - memcmp_P(requestDomain, domain, requestDomainLength) == 0 && // suffix match - requestQtype == 0x0001 && // request QType match - requestQclass == 0x0001) { // request QClass match - - return true; - } - } - - return false; -} - -void WiFiMDNSResponder::replyToRequest() -{ - int nameLength = name.length(); - int domainLength = sizeof(domain); - uint32_t ipAddress = WiFi.localIP(); - uint32_t ttl = _htonl(ttlSeconds); - - int responseSize = sizeof(responseHeader) + 1 + nameLength + 1 + domainLength + 1 + sizeof(aRecord) + sizeof(nsecRecord); - uint8_t response[responseSize]; - uint8_t* r = response; - - // copy header - memcpy_P(r, responseHeader, sizeof(responseHeader)); - r += sizeof(responseHeader); - - // copy name - *r = nameLength; - memcpy(r + 1, name.c_str(), nameLength); - r += (1 + nameLength); - - // copy domain - *r = domainLength; - memcpy_P(r + 1, domain, domainLength); - r += (1 + domainLength); - - // terminator - *r = 0x00; - r++; - - // copy A record - memcpy_P(r, aRecord, sizeof(aRecord)); - memcpy(r + TTL_OFFSET, &ttl, sizeof(ttl)); // replace TTL value - memcpy(r + IP_OFFSET, &ipAddress, sizeof(ipAddress)); // replace IP address value - r += sizeof(aRecord); - - // copy NSEC record - memcpy_P(r, nsecRecord, sizeof(nsecRecord)); - r += sizeof(nsecRecord); - - udpSocket.beginPacket(IPAddress(224, 0, 0, 251), 5353); - udpSocket.write(response, responseSize); - udpSocket.endPacket(); -} diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiMDNSResponder.h b/feather_sensor_transmit/libraries/WiFi101/src/WiFiMDNSResponder.h deleted file mode 100644 index d7e3d43..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/WiFiMDNSResponder.h +++ /dev/null @@ -1,51 +0,0 @@ -// Port of CC3000 MDNS Responder to WINC1500. -// Author: Tony DiCola -// -// This MDNSResponder class implements just enough MDNS functionality to respond -// to name requests, for example 'foo.local'. This does not implement any other -// MDNS or Bonjour functionality like services, etc. -// -// Copyright (c) 2016 Adafruit Industries. All right reserved. -// -// 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 2.1 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 Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -#ifndef WIFIMDNSRESPONDER_H -#define WIFIMDNSRESPONDER_H - -#include "WiFi101.h" -#include "WiFiUdp.h" - -class WiFiMDNSResponder { -public: - WiFiMDNSResponder(); - ~WiFiMDNSResponder(); - bool begin(const char* _name, uint32_t _ttlSeconds = 3600); - void poll(); - -private: - bool parseRequest(); - void replyToRequest(); - -private: - String name; - uint32_t ttlSeconds; - - int minimumExpectedRequestLength; - - // UDP socket for receiving/sending MDNS data. - WiFiUDP udpSocket; -}; - -#endif diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiSSLClient.cpp b/feather_sensor_transmit/libraries/WiFi101/src/WiFiSSLClient.cpp deleted file mode 100644 index e7be43c..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/WiFiSSLClient.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/* - WiFiSSLClient.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "WiFiSSLClient.h" - -WiFiSSLClient::WiFiSSLClient() : - WiFiClient() -{ -} - -WiFiSSLClient::WiFiSSLClient(uint8_t sock, uint8_t parentsock) : - WiFiClient(sock, parentsock) -{ -} - -WiFiSSLClient::WiFiSSLClient(const WiFiSSLClient& other) : - WiFiClient(other) -{ -} - -int WiFiSSLClient::connect(IPAddress ip, uint16_t port) -{ - return WiFiClient::connectSSL(ip, port); -} - -int WiFiSSLClient::connect(const char* host, uint16_t port) -{ - return WiFiClient::connectSSL(host, port); -} diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiSSLClient.h b/feather_sensor_transmit/libraries/WiFi101/src/WiFiSSLClient.h deleted file mode 100644 index c5851e5..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/WiFiSSLClient.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - WiFiSSLClient.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef WIFISSLCLIENT_H -#define WIFISSLCLIENT_H - -#include "WiFiClient.h" - -class WiFiSSLClient : public WiFiClient { - -public: - WiFiSSLClient(); - WiFiSSLClient(uint8_t sock, uint8_t parentsock = 0); - WiFiSSLClient(const WiFiSSLClient& other); - - virtual int connect(IPAddress ip, uint16_t port); - virtual int connect(const char* host, uint16_t port); -}; - -#endif /* WIFISSLCLIENT_H */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiServer.cpp b/feather_sensor_transmit/libraries/WiFi101/src/WiFiServer.cpp deleted file mode 100644 index 5f330ba..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/WiFiServer.cpp +++ /dev/null @@ -1,140 +0,0 @@ -/* - WiFiClient.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -extern "C" { - #include "socket/include/socket.h" -} - -#include "WiFi101.h" -#include "WiFiClient.h" -#include "WiFiServer.h" - -#define READY (_flag & SOCKET_BUFFER_FLAG_BIND) - -WiFiServer::WiFiServer(uint16_t port) -{ - _port = port; - _flag = 0; -} - -void WiFiServer::begin() -{ - begin(0); -} - -uint8_t WiFiServer::beginSSL() -{ - return begin(SOCKET_FLAGS_SSL); -} - -uint8_t WiFiServer::begin(uint8_t opt) -{ - struct sockaddr_in addr; - - _flag = 0; - - // Initialize socket address structure. - addr.sin_family = AF_INET; - addr.sin_port = _htons(_port); - addr.sin_addr.s_addr = 0; - - // Open TCP server socket. - if ((_socket = socket(AF_INET, SOCK_STREAM, opt)) < 0) { - return 0; - } - - // Add socket buffer handler: - socketBufferRegister(_socket, &_flag, 0, 0, 0); - - // Bind socket: - if (bind(_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { - close(_socket); - _socket = -1; - return 0; - } - - // Wait for connection or timeout: - unsigned long start = millis(); - while (!READY && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - if (!READY) { - close(_socket); - _socket = -1; - return 0; - } - _flag &= ~SOCKET_BUFFER_FLAG_BIND; - - return 1; -} - -WiFiClient WiFiServer::available(uint8_t* status) -{ - uint32_t flag; - - m2m_wifi_handle_events(NULL); - if (_flag & SOCKET_BUFFER_FLAG_SPAWN) { - flag = _flag; - _flag &= ~SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK; - _flag &= ~SOCKET_BUFFER_FLAG_SPAWN; - if (status != NULL) { - *status = 0; - } - return WiFiClient(((flag & SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK) >> SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS), _socket + 1); - } else { - WiFiClient *client; - - for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { - client = WiFi._client[sock]; - if (client && client->_flag & SOCKET_BUFFER_FLAG_CONNECTED) { - if (((client->_flag >> SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS) & 0xff) == (uint8)(_socket + 1)) { - return *client; - } - } - } - } - - return WiFiClient(); -} - -uint8_t WiFiServer::status() { - // Deprecated. - return 0; -} - -size_t WiFiServer::write(uint8_t b) -{ - return write(&b, 1); -} - -size_t WiFiServer::write(const uint8_t *buffer, size_t size) -{ - size_t n = 0; - WiFiClient *client; - - for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { - client = WiFi._client[sock]; - if (client && client->_flag & SOCKET_BUFFER_FLAG_CONNECTED) { - if (((client->_flag >> SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS) & 0xff) == (uint8)(_socket + 1)) { - n += client->write(buffer, size); - } - } - } - return n; -} diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiServer.h b/feather_sensor_transmit/libraries/WiFi101/src/WiFiServer.h deleted file mode 100644 index d658b2f..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/WiFiServer.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - WiFiClient.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef WIFISERVER_H -#define WIFISERVER_H - -#include -#include - -class WiFiClient; - -class WiFiServer : public Server { - -private: - SOCKET _socket; - uint32_t _flag; - uint16_t _port; - uint8_t begin(uint8_t opt); - -public: - WiFiServer(uint16_t); - WiFiClient available(uint8_t* status = NULL); - void begin(); - uint8_t beginSSL(); - virtual size_t write(uint8_t); - virtual size_t write(const uint8_t *buf, size_t size); - uint8_t status(); - - using Print::write; - -}; - -#endif /* WIFISERVER_H */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiUdp.cpp b/feather_sensor_transmit/libraries/WiFi101/src/WiFiUdp.cpp deleted file mode 100644 index e55c965..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/WiFiUdp.cpp +++ /dev/null @@ -1,289 +0,0 @@ -/* - WiFiUdp.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -extern "C" { - #include "socket/include/socket.h" - #include "driver/include/m2m_periph.h" - extern uint8 hif_small_xfer; -} - -#include -#include "WiFi101.h" -#include "WiFiUdp.h" -#include "WiFiClient.h" -#include "WiFiServer.h" - -#define READY (_flag & SOCKET_BUFFER_FLAG_BIND) - -/* Constructor. */ -WiFiUDP::WiFiUDP() -{ - _socket = -1; - _flag = 0; - _head = 0; - _tail = 0; - _rcvSize = 0; - _rcvPort = 0; - _rcvIP = 0; - _sndSize = 0; -} - -/* Start WiFiUDP socket, listening at local port PORT */ -uint8_t WiFiUDP::begin(uint16_t port) -{ - struct sockaddr_in addr; - uint32 u32EnableCallbacks = 0; - - _flag = 0; - _head = 0; - _tail = 0; - _rcvSize = 0; - _rcvPort = 0; - _rcvIP = 0; - _sndSize = 0; - - // Initialize socket address structure. - addr.sin_family = AF_INET; - addr.sin_port = _htons(port); - addr.sin_addr.s_addr = 0; - - // Open TCP server socket. - if ((_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { - return 0; - } - - // Add socket buffer handler: - socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_recvBuffer); - setsockopt(_socket, SOL_SOCKET, SO_SET_UDP_SEND_CALLBACK, &u32EnableCallbacks, 0); - - // Bind socket: - if (bind(_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { - close(_socket); - _socket = -1; - return 0; - } - - // Wait for connection or timeout: - unsigned long start = millis(); - while (!READY && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - if (!READY) { - close(_socket); - _socket = -1; - return 0; - } - _flag &= ~SOCKET_BUFFER_FLAG_BIND; - - return 1; -} - -uint8_t WiFiUDP::beginMulticast(IPAddress ip, uint16_t port) -{ - uint32_t multiIp = ip; - - if (!begin(port)) { - return 0; - } - - setsockopt(_socket, SOL_SOCKET, IP_ADD_MEMBERSHIP, &multiIp, sizeof(multiIp)); - - return 1; -} - -/* return number of bytes available in the current packet, - will return zero if parsePacket hasn't been called yet */ -int WiFiUDP::available() -{ - m2m_wifi_handle_events(NULL); - - if (_socket != -1) { - return _rcvSize; - } - return 0; - } - -/* Release any resources being used by this WiFiUDP instance */ -void WiFiUDP::stop() -{ - if (_socket < 0) - return; - - socketBufferUnregister(_socket); - close(_socket); - _socket = -1; -} - -int WiFiUDP::beginPacket(const char *host, uint16_t port) -{ - IPAddress ip; - if (WiFi.hostByName(host, ip)) { - return beginPacket(ip, port); - } - - return 0; -} - -int WiFiUDP::beginPacket(IPAddress ip, uint16_t port) -{ - _sndIP = ip; - _sndPort = port; - _sndSize = 0; - - return 1; -} - -int WiFiUDP::endPacket() -{ - struct sockaddr_in addr; - - // Network led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); - - addr.sin_family = AF_INET; - addr.sin_port = _htons(_sndPort); - addr.sin_addr.s_addr = _sndIP; - - if (sendto(_socket, (void *)_sndBuffer, _sndSize, 0, - (struct sockaddr *)&addr, sizeof(addr)) < 0) { - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - return 0; - } - - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - - return 1; -} - -size_t WiFiUDP::write(uint8_t byte) -{ - return write(&byte, 1); -} - -size_t WiFiUDP::write(const uint8_t *buffer, size_t size) -{ - if ((size + _sndSize) > sizeof(_sndBuffer)) { - size = sizeof(_sndBuffer) - _sndSize; - } - - memcpy(_sndBuffer + _sndSize, buffer, size); - - _sndSize += size; - - return size; -} - -int WiFiUDP::parsePacket() -{ - m2m_wifi_handle_events(NULL); - - if (_socket != -1) { - if (_rcvSize != 0) { - return _rcvSize; - } - if (_head != _tail) { - _rcvSize = ((uint16_t)_recvBuffer[_tail] << 8) + (uint16_t)_recvBuffer[_tail + 1]; - _rcvPort = ((uint16_t)_recvBuffer[_tail + 2] << 8) + (uint16_t)_recvBuffer[_tail + 3]; - _rcvIP = ((uint32_t)_recvBuffer[_tail + 4] << 24) + ((uint32_t)_recvBuffer[_tail + 5] << 16) + - ((uint32_t)_recvBuffer[_tail + 6] << 8) + (uint32_t)_recvBuffer[_tail + 7]; - _tail += SOCKET_BUFFER_UDP_HEADER_SIZE; - return _rcvSize; - } - } - return 0; -} - -int WiFiUDP::read() -{ - uint8_t b; - - if (read(&b, sizeof(b)) == -1) { - return -1; - } - - return b; -} - -int WiFiUDP::read(unsigned char* buf, size_t size) -{ - // sizeof(size_t) is architecture dependent - // but we need a 16 bit data type here - uint16_t size_tmp = available(); - - if (size_tmp == 0) { - return -1; - } - - if (size < size_tmp) { - size_tmp = size; - } - - for (uint32_t i = 0; i < size_tmp; ++i) { - buf[i] = _recvBuffer[_tail++]; - _rcvSize--; - - if (_tail == _head) { - // the full buffered data has been read, reset head and tail for next transfer - _tail = _head = 0; - - // clear the buffer full flag - _flag &= ~SOCKET_BUFFER_FLAG_FULL; - - // setup buffer and buffer size to transfer the remainder of the current packet - // or next received packet - if (hif_small_xfer) { - recvfrom(_socket, _recvBuffer, SOCKET_BUFFER_MTU, 0); - } else { - recvfrom(_socket, _recvBuffer + SOCKET_BUFFER_UDP_HEADER_SIZE, SOCKET_BUFFER_MTU, 0); - } - m2m_wifi_handle_events(NULL); - } - } - - return size_tmp; -} - -int WiFiUDP::peek() -{ - if (!available()) - return -1; - - return _recvBuffer[_tail]; -} - -void WiFiUDP::flush() -{ - while (available()) - read(); -} - -IPAddress WiFiUDP::remoteIP() -{ - return _rcvIP; -} - -uint16_t WiFiUDP::remotePort() -{ - return _rcvPort; -} diff --git a/feather_sensor_transmit/libraries/WiFi101/src/WiFiUdp.h b/feather_sensor_transmit/libraries/WiFi101/src/WiFiUdp.h deleted file mode 100644 index d961682..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/WiFiUdp.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - WiFiUdp.h - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef WIFIUDP_H -#define WIFIUDP_H - -#include - -class WiFiUDP : public UDP { -private: - SOCKET _socket; - uint32_t _flag; - uint32_t _head; - uint32_t _tail; - uint8_t _recvBuffer[SOCKET_BUFFER_UDP_SIZE]; - uint16_t _rcvSize; - uint16_t _rcvPort; - uint32_t _rcvIP; - uint8_t _sndBuffer[SOCKET_BUFFER_UDP_SIZE]; - uint16_t _sndSize; - uint16_t _sndPort; - uint32_t _sndIP; - -public: - WiFiUDP(); // Constructor - virtual uint8_t begin(uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use - virtual uint8_t beginMulticast(IPAddress, uint16_t); // initialize, start listening on specified multicast IP address and port. Returns 1 if successful, 0 if there are no sockets available to use - virtual uint8_t beginMulti(IPAddress ip, uint16_t port) { return beginMulticast(ip, port); } - virtual void stop(); // Finish with the UDP socket - - // Sending UDP packets - - // Start building up a packet to send to the remote host specific in ip and port - // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port - virtual int beginPacket(IPAddress ip, uint16_t port); - // Start building up a packet to send to the remote host specific in host and port - // Returns 1 if successful, 0 if there was a problem resolving the hostname or port - virtual int beginPacket(const char *host, uint16_t port); - // Finish off this packet and send it - // Returns 1 if the packet was sent successfully, 0 if there was an error - virtual int endPacket(); - // Write a single byte into the packet - virtual size_t write(uint8_t); - // Write size bytes from buffer into the packet - virtual size_t write(const uint8_t *buffer, size_t size); - - using Print::write; - - // Start processing the next available incoming packet - // Returns the size of the packet in bytes, or 0 if no packets are available - virtual int parsePacket(); - // Number of bytes remaining in the current packet - virtual int available(); - // Read a single byte from the current packet - virtual int read(); - // Read up to len bytes from the current packet and place them into buffer - // Returns the number of bytes read, or 0 if none are available - virtual int read(unsigned char* buffer, size_t len); - // Read up to len characters from the current packet and place them into buffer - // Returns the number of characters read, or 0 if none are available - virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; - // Return the next byte from the current packet without moving on to the next byte - virtual int peek(); - virtual void flush(); // Finish reading the current packet - - // Return the IP address of the host who sent the current incoming packet - virtual IPAddress remoteIP(); - // Return the port of the host who sent the current incoming packet - virtual uint16_t remotePort(); - -}; - -#endif /* WIFIUDP_H */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp.h b/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp.h deleted file mode 100644 index 5527bab..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp.h +++ /dev/null @@ -1,283 +0,0 @@ -/** - * - * \file - * - * \brief WINC BSP API Declarations. - * - * Copyright (c) 2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/** \defgroup nm_bsp BSP - */ -/**@defgroup BSPDefine Defines - * @ingroup nm_bsp - * @{ - */ -#ifndef _NM_BSP_H_ -#define _NM_BSP_H_ - -#define NMI_API -/*!< -* Attribute used to define memory section to map Functions in host memory. -*/ -#define CONST const - -/*!< -* Used for code portability. -*/ - -/*! - * @typedef void (*tpfNmBspIsr) (void); - * @brief Pointer to function.\n - * Used as a data type of ISR function registered by \ref nm_bsp_register_isr - * @return None - */ -typedef void (*tpfNmBspIsr)(void); - - - -#ifndef NULL -#define NULL ((void*)0) -#endif -/*!< -* Void Pointer to '0' in case of NULL is not defined. -*/ - - -#define BSP_MIN(x,y) ((x)>(y)?(y):(x)) -/*!< -* Computes the minimum of \b x and \b y. -*/ - - //@} - -/**@defgroup DataT DataTypes - * @ingroup nm_bsp - * @{ - */ - - /*! - * @ingroup DataTypes - * @typedef unsigned char uint8; - * @brief Range of values between 0 to 255 - */ -typedef unsigned char uint8; - - /*! - * @ingroup DataTypes - * @typedef unsigned short uint16; - * @brief Range of values between 0 to 65535 - */ -typedef unsigned short uint16; - - /*! - * @ingroup Data Types - * @typedef unsigned long uint32; - * @brief Range of values between 0 to 4294967295 - */ -typedef unsigned long uint32; - - - /*! - * @ingroup Data Types - * @typedef signed char sint8; - * @brief Range of values between -128 to 127 - */ -typedef signed char sint8; - - /*! - * @ingroup DataTypes - * @typedef signed short sint16; - * @brief Range of values between -32768 to 32767 - */ -typedef signed short sint16; - - /*! - * @ingroup DataTypes - * @typedef signed long sint32; - * @brief Range of values between -2147483648 to 2147483647 - */ - -typedef signed long sint32; - //@} - -#ifndef CORTUS_APP - - -#ifdef __cplusplus -extern "C"{ -#endif - -/** \defgroup BSPAPI Function - * @ingroup nm_bsp - */ - - -/** @defgroup NmBspInitFn nm_bsp_init - * @ingroup BSPAPI - * Initialization for BSP such as Reset and Chip Enable Pins for WINC, delays, register ISR, enable/disable IRQ for WINC, ...etc. You must use this function in the head of your application to - * enable WINC and Host Driver communicate each other. - */ - /**@{*/ -/*! - * @fn sint8 nm_bsp_init(void); - * @note Implementation of this function is host dependent. - * @warning Missing use will lead to unavailability of host communication.\n - * - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - - */ -sint8 nm_bsp_init(void); - /**@}*/ - - - /** @defgroup NmBspDeinitFn nm_bsp_deinit - * @ingroup BSPAPI - * De-initialization for BSP (\e Board \e Support \e Package) - */ - /**@{*/ -/*! - * @fn sint8 nm_bsp_deinit(void); - * @pre Initialize \ref nm_bsp_init first - * @note Implementation of this function is host dependent. - * @warning Missing use may lead to unknown behavior in case of soft reset.\n - * @see nm_bsp_init - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - - */ -sint8 nm_bsp_deinit(void); - /**@}*/ - - -/** @defgroup NmBspResetFn nm_bsp_reset -* @ingroup BSPAPI -* Resetting NMC1500 SoC by setting CHIP_EN and RESET_N signals low, then after specific delay the function will put CHIP_EN high then RESET_N high, -* for the timing between signals please review the WINC data-sheet -*/ -/**@{*/ - /*! - * @fn void nm_bsp_reset(void); - * @param [in] None - * @pre Initialize \ref nm_bsp_init first - * @note Implementation of this function is host dependent and called by HIF layer. - * @see nm_bsp_init - * @return None - - */ -void nm_bsp_reset(void); - /**@}*/ - - -/** @defgroup NmBspSleepFn nm_bsp_sleep -* @ingroup BSPAPI -* Sleep in units of milliseconds.\n -* This function used by HIF Layer according to different situations. -*/ -/**@{*/ -/*! - * @fn void nm_bsp_sleep(uint32); - * @brief - * @param [in] u32TimeMsec - * Time unit in milliseconds - * @pre Initialize \ref nm_bsp_init first - * @warning Maximum value must nor exceed 4294967295 milliseconds which is equal to 4294967.295 seconds.\n - * @note Implementation of this function is host dependent. - * @see nm_bsp_init - * @return None - */ -void nm_bsp_sleep(uint32 u32TimeMsec); -/**@}*/ - - -/** @defgroup NmBspRegisterFn nm_bsp_register_isr -* @ingroup BSPAPI -* Register ISR (Interrupt Service Routine) in the initialization of HIF (Host Interface) Layer. -* When the interrupt trigger the BSP layer should call the pfisr function once inside the interrupt. -*/ -/**@{*/ -/*! - * @fn void nm_bsp_register_isr(tpfNmBspIsr); - * @param [in] tpfNmBspIsr pfIsr - * Pointer to ISR handler in HIF - * @warning Make sure that ISR for IRQ pin for WINC is disabled by default in your implementation. - * @note Implementation of this function is host dependent and called by HIF layer. - * @see tpfNmBspIsr - * @return None - - */ -void nm_bsp_register_isr(tpfNmBspIsr pfIsr); -/**@}*/ - - -/** @defgroup NmBspInterruptCtrl nm_bsp_interrupt_ctrl -* @ingroup BSPAPI -* Synchronous enable/disable interrupts function -*/ -/**@{*/ -/*! - * @fn void nm_bsp_interrupt_ctrl(uint8); - * @brief Enable/Disable interrupts - * @param [in] u8Enable - * '0' disable interrupts. '1' enable interrupts - * @see tpfNmBspIsr - * @note Implementation of this function is host dependent and called by HIF layer. - * @return None - - */ -void nm_bsp_interrupt_ctrl(uint8 u8Enable); - /**@}*/ - -#ifdef __cplusplus -} -#endif - -#endif - -#ifdef _NM_BSP_BIG_END -#define NM_BSP_B_L_32(x) \ -((((x) & 0x000000FF) << 24) + \ -(((x) & 0x0000FF00) << 8) + \ -(((x) & 0x00FF0000) >> 8) + \ -(((x) & 0xFF000000) >> 24)) -#define NM_BSP_B_L_16(x) \ -((((x) & 0x00FF) << 8) + \ -(((x) & 0xFF00) >> 8)) -#else -#define NM_BSP_B_L_32(x) (x) -#define NM_BSP_B_L_16(x) (x) -#endif - - -#endif /*_NM_BSP_H_*/ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h b/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h deleted file mode 100644 index 77417e8..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h +++ /dev/null @@ -1,74 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 BSP APIs definitions. - * - * Copyright (c) 2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NM_BSP_ARDUINO_H_ -#define _NM_BSP_ARDUINO_H_ - -#include - -#include - -/* - * Arduino variants may redefine those pins. - * If no pins are specified the following defaults are used: - * WINC1501_RESET_PIN - pin 5 - * WINC1501_INTN_PIN - pin 7 - * WINC1501_CHIP_EN_PIN - not connected (tied to VCC) - */ -#if !defined(WINC1501_RESET_PIN) - #define WINC1501_RESET_PIN 5 -#endif -#if !defined(WINC1501_INTN_PIN) - #define WINC1501_INTN_PIN 7 -#endif -#if !defined(WINC1501_SPI_CS_PIN) - #define WINC1501_SPI_CS_PIN 10 -#endif -#if !defined(WINC1501_CHIP_EN_PIN) - #define WINC1501_CHIP_EN_PIN -1 -#endif - -extern int8_t gi8Winc1501CsPin; -extern int8_t gi8Winc1501ResetPin; -extern int8_t gi8Winc1501IntnPin; -extern int8_t gi8Winc1501ChipEnPin; - -#endif /* _NM_BSP_ARDUINO_H_ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h b/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h deleted file mode 100644 index c5991f2..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h +++ /dev/null @@ -1,54 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 BSP APIs definitions. - * - * Copyright (c) 2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NM_BSP_AVR_H_ -#define _NM_BSP_AVR_H_ - -#pragma once - -#define NM_DEBUG 0 -#define NM_BSP_PRINTF - -#define CONF_WINC_USE_SPI 1 - -#define NM_EDGE_INTERRUPT 1 - -#endif /* _NM_BSP_AVR_H_ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h b/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h deleted file mode 100644 index 45d3ff2..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h +++ /dev/null @@ -1,59 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 BSP APIs declarations. - * - * Copyright (c) 2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/**@defgroup BSPDefine Defines - * @ingroup nm_bsp - * @{ - */ -#ifndef _NM_BSP_INTERNAL_H_ -#define _NM_BSP_INTERNAL_H_ - -#ifdef ARDUINO_ARCH_AVR -#define LIMITED_RAM_DEVICE -#include "bsp/include/nm_bsp_avr.h" -#else -#include "bsp/include/nm_bsp_samd21.h" -#endif - -#ifdef ARDUINO -#define CONF_PERIPH -#endif - -#endif //_NM_BSP_INTERNAL_H_ \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h b/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h deleted file mode 100644 index 296cd20..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h +++ /dev/null @@ -1,52 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 BSP APIs definitions. - * - * Copyright (c) 2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NM_BSP_SAMD21_H_ -#define _NM_BSP_SAMD21_H_ - -#define NM_DEBUG 0 -#define NM_BSP_PRINTF - -#define CONF_WINC_USE_SPI 1 - -#define NM_EDGE_INTERRUPT 1 - -#endif /* _NM_BSP_SAMD21_H_ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c b/feather_sensor_transmit/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c deleted file mode 100644 index e27be14..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c +++ /dev/null @@ -1,205 +0,0 @@ -/** - * - * \file - * - * \brief This module contains SAMD21 BSP APIs implementation. - * - * Copyright (c) 2014 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "bsp/include/nm_bsp.h" -#include "bsp/include/nm_bsp_arduino.h" -#include "common/include/nm_common.h" - -int8_t gi8Winc1501CsPin = WINC1501_SPI_CS_PIN; -int8_t gi8Winc1501ResetPin = WINC1501_RESET_PIN; -int8_t gi8Winc1501IntnPin = WINC1501_INTN_PIN; -int8_t gi8Winc1501ChipEnPin = WINC1501_CHIP_EN_PIN; - -static tpfNmBspIsr gpfIsr; - -void __attribute__((weak)) attachInterruptMultiArch(uint32_t pin, void *chip_isr, uint32_t mode) -{ - attachInterrupt(pin, chip_isr, mode); -} - -void __attribute__((weak)) detachInterruptMultiArch(uint32_t pin) -{ - detachInterrupt(pin); -} - -static void chip_isr(void) -{ - if (gpfIsr) { - gpfIsr(); - } -} - -/* - * @fn init_chip_pins - * @brief Initialize reset, chip enable and wake pin - * @author M.S.M - * @date 11 July 2012 - * @version 1.0 - */ -static void init_chip_pins(void) -{ - /* Configure RESETN pin as output. */ - pinMode(gi8Winc1501ResetPin, OUTPUT); - digitalWrite(gi8Winc1501ResetPin, HIGH); - - /* Configure INTN pins as input. */ - pinMode(gi8Winc1501IntnPin, INPUT); - - if (gi8Winc1501ChipEnPin > -1) - { - /* Configure CHIP_EN as pull-up */ - pinMode(gi8Winc1501ChipEnPin, INPUT_PULLUP); - } -} - -static void deinit_chip_pins(void) -{ - digitalWrite(gi8Winc1501ResetPin, LOW); - pinMode(gi8Winc1501ResetPin, INPUT); - - if (gi8Winc1501ChipEnPin > -1) - { - pinMode(gi8Winc1501ChipEnPin, INPUT); - } -} - -/* - * @fn nm_bsp_init - * @brief Initialize BSP - * @return 0 in case of success and -1 in case of failure - * @author M.S.M - * @date 11 July 2012 - * @version 1.0 - */ -sint8 nm_bsp_init(void) -{ - gpfIsr = NULL; - - init_chip_pins(); - - nm_bsp_reset(); - - return M2M_SUCCESS; -} - -/** - * @fn nm_bsp_deinit - * @brief De-iInitialize BSP - * @return 0 in case of success and -1 in case of failure - * @author M. Abdelmawla - * @date 11 July 2012 - * @version 1.0 - */ -sint8 nm_bsp_deinit(void) -{ - deinit_chip_pins(); - - return M2M_SUCCESS; -} - -/** - * @fn nm_bsp_reset - * @brief Reset NMC1500 SoC by setting CHIP_EN and RESET_N signals low, - * CHIP_EN high then RESET_N high - * @author M. Abdelmawla - * @date 11 July 2012 - * @version 1.0 - */ -void nm_bsp_reset(void) -{ - digitalWrite(gi8Winc1501ResetPin, LOW); - nm_bsp_sleep(100); - digitalWrite(gi8Winc1501ResetPin, HIGH); - nm_bsp_sleep(100); -} - -/* - * @fn nm_bsp_sleep - * @brief Sleep in units of mSec - * @param[IN] u32TimeMsec - * Time in milliseconds - * @author M.S.M - * @date 28 OCT 2013 - * @version 1.0 - */ -void nm_bsp_sleep(uint32 u32TimeMsec) -{ - while (u32TimeMsec--) { - delay(1); - } -} - -/* - * @fn nm_bsp_register_isr - * @brief Register interrupt service routine - * @param[IN] pfIsr - * Pointer to ISR handler - * @author M.S.M - * @date 28 OCT 2013 - * @sa tpfNmBspIsr - * @version 1.0 - */ -void nm_bsp_register_isr(tpfNmBspIsr pfIsr) -{ - gpfIsr = pfIsr; - attachInterruptMultiArch(gi8Winc1501IntnPin, chip_isr, FALLING); -} - -/* - * @fn nm_bsp_interrupt_ctrl - * @brief Enable/Disable interrupts - * @param[IN] u8Enable - * '0' disable interrupts. '1' enable interrupts - * @author M.S.M - * @date 28 OCT 2013 - * @version 1.0 - */ -void nm_bsp_interrupt_ctrl(uint8 u8Enable) -{ - if (u8Enable) { - attachInterruptMultiArch(gi8Winc1501IntnPin, chip_isr, FALLING); - } else { - detachInterruptMultiArch(gi8Winc1501IntnPin); - } -} diff --git a/feather_sensor_transmit/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c b/feather_sensor_transmit/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c deleted file mode 100644 index 050d5d5..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c +++ /dev/null @@ -1,164 +0,0 @@ -/** - * - * \file - * - * \brief This module contains SAMD21 BSP APIs implementation. - * - * Copyright (c) 2014 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifdef ARDUINO_ARCH_AVR - -#include "bsp/include/nm_bsp.h" -#include "bsp/include/nm_bsp_arduino.h" -#include "common/include/nm_common.h" - -#define IS_MEGA (defined(ARDUINO_AVR_MEGA) || defined(ARDUINO_AVR_MEGA2560)) - -static tpfNmBspIsr gpfIsr; - -volatile uint8_t *_receivePortRegister; -volatile uint8_t *_pcint_maskreg; -uint8_t _receiveBitMask; -volatile uint8_t prev_pin_read = 1; - -uint8_t rx_pin_read() -{ - return *_receivePortRegister & _receiveBitMask; -} - -#if !IS_MEGA - -#if defined(PCINT0_vect) -ISR(PCINT0_vect) -{ - if (!rx_pin_read() && gpfIsr) - { - gpfIsr(); - } -} -#endif - -#if defined(PCINT1_vect) -ISR(PCINT1_vect, ISR_ALIASOF(PCINT0_vect)); -#endif - -#if defined(PCINT2_vect) -ISR(PCINT2_vect, ISR_ALIASOF(PCINT0_vect)); -#endif - -#if defined(PCINT3_vect) -ISR(PCINT3_vect, ISR_ALIASOF(PCINT0_vect)); -#endif - -#endif // !IS_MEGA - -#if defined(TIMER4_OVF_vect) -ISR(TIMER4_OVF_vect) { - uint8_t curr_pin_read = rx_pin_read(); - if ((curr_pin_read != prev_pin_read) && !curr_pin_read && gpfIsr) - { - gpfIsr(); - } - prev_pin_read = curr_pin_read; -} - -// stategy 3 - start a timer and perform a sort of polling -void attachFakeInterruptToTimer(void) { - TCCR4B = (1< I2C/UART. Parameter:tstrNmI2cDefault/tstrNmUartDefault */ -#define NM_BUS_IOCTL_W ((uint8)1) /*!< Write only ==> I2C/UART. Parameter type tstrNmI2cDefault/tstrNmUartDefault*/ -#define NM_BUS_IOCTL_W_SPECIAL ((uint8)2) /*!< Write two buffers within the same transaction - (same start/stop conditions) ==> I2C only. Parameter:tstrNmI2cSpecial */ -#define NM_BUS_IOCTL_RW ((uint8)3) /*!< Read/Write at the same time ==> SPI only. Parameter:tstrNmSpiRw */ - -#define NM_BUS_IOCTL_WR_RESTART ((uint8)4) /*!< Write buffer then made restart condition then read ==> I2C only. parameter:tstrNmI2cSpecial */ -/** -* @struct tstrNmBusCapabilities -* @brief Structure holding bus capabilities information -* @sa NM_BUS_TYPE_I2C, NM_BUS_TYPE_SPI -*/ -typedef struct -{ - uint16 u16MaxTrxSz; /*!< Maximum transfer size. Must be >= 16 bytes*/ -} tstrNmBusCapabilities; - -/** -* @struct tstrNmI2cDefault -* @brief Structure holding I2C default operation parameters -* @sa NM_BUS_IOCTL_R, NM_BUS_IOCTL_W -*/ -typedef struct -{ - uint8 u8SlaveAdr; - uint8 *pu8Buf; /*!< Operation buffer */ - uint16 u16Sz; /*!< Operation size */ -} tstrNmI2cDefault; - -/** -* @struct tstrNmI2cSpecial -* @brief Structure holding I2C special operation parameters -* @sa NM_BUS_IOCTL_W_SPECIAL -*/ -typedef struct -{ - uint8 u8SlaveAdr; - uint8 *pu8Buf1; /*!< pointer to the 1st buffer */ - uint8 *pu8Buf2; /*!< pointer to the 2nd buffer */ - uint16 u16Sz1; /*!< 1st buffer size */ - uint16 u16Sz2; /*!< 2nd buffer size */ -} tstrNmI2cSpecial; - -/** -* @struct tstrNmSpiRw -* @brief Structure holding SPI R/W parameters -* @sa NM_BUS_IOCTL_RW -*/ -typedef struct -{ - uint8 *pu8InBuf; /*!< pointer to input buffer. - Can be set to null and in this case zeros should be sent at MOSI */ - uint8 *pu8OutBuf; /*!< pointer to output buffer. - Can be set to null and in this case data from MISO can be ignored */ - uint16 u16Sz; /*!< Transfere size */ -} tstrNmSpiRw; - - -/** -* @struct tstrNmUartDefault -* @brief Structure holding UART default operation parameters -* @sa NM_BUS_IOCTL_R, NM_BUS_IOCTL_W -*/ -typedef struct -{ - uint8 *pu8Buf; /*!< Operation buffer */ - uint16 u16Sz; /*!< Operation size */ -} tstrNmUartDefault; -/*!< Bus capabilities. This structure must be declared at platform specific bus wrapper */ -extern tstrNmBusCapabilities egstrNmBusCapabilities; - - -#ifdef __cplusplus - extern "C" { - #endif -/** -* @fn nm_bus_init -* @brief Initialize the bus wrapper -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_bus_init(void *); - -/** -* @fn nm_bus_ioctl -* @brief send/receive from the bus -* @param [in] u8Cmd -* IOCTL command for the operation -* @param [in] pvParameter -* Arbitrary parameter depending on IOCTL -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -* @note For SPI only, it's important to be able to send/receive at the same time -*/ -sint8 nm_bus_ioctl(uint8 u8Cmd, void* pvParameter); - -/** -* @fn nm_bus_deinit -* @brief De-initialize the bus wrapper -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_bus_deinit(void); - -/* -* @fn nm_bus_reinit -* @brief re-initialize the bus wrapper -* @param [in] void *config -* re-init configuration data -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_bus_reinit(void *); -/* -* @fn nm_bus_get_chip_type -* @brief get chip type -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -#ifdef CONF_WINC_USE_UART -uint8 nm_bus_get_chip_type(void); -#endif -#ifdef __cplusplus - } - #endif - -#endif /*_NM_BUS_WRAPPER_H_*/ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp b/feather_sensor_transmit/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp deleted file mode 100644 index 22a7473..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp +++ /dev/null @@ -1,200 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 bus wrapper APIs implementation. - * - * Copyright (c) 2014 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include -#include - -/* - * Variants may define an alternative SPI instace to use for WiFi101. - * If not defined the following defaults are used: - * WINC1501_SPI - SPI - */ -#if !defined(WINC1501_SPI) - #define WINC1501_SPI SPI -#endif - -extern "C" { - -#include "bsp/include/nm_bsp.h" -#include "bsp/include/nm_bsp_arduino.h" -#include "common/include/nm_common.h" -#include "bus_wrapper/include/nm_bus_wrapper.h" - -} - -#define NM_BUS_MAX_TRX_SZ 256 - -tstrNmBusCapabilities egstrNmBusCapabilities = -{ - NM_BUS_MAX_TRX_SZ -}; - -static const SPISettings wifi_SPISettings(12000000L, MSBFIRST, SPI_MODE0); - -static sint8 spi_rw(uint8* pu8Mosi, uint8* pu8Miso, uint16 u16Sz) -{ - uint8 u8Dummy = 0; - uint8 u8SkipMosi = 0, u8SkipMiso = 0; - - if (!pu8Mosi) { - pu8Mosi = &u8Dummy; - u8SkipMosi = 1; - } - else if(!pu8Miso) { - pu8Miso = &u8Dummy; - u8SkipMiso = 1; - } - else { - return M2M_ERR_BUS_FAIL; - } - - WINC1501_SPI.beginTransaction(wifi_SPISettings); - digitalWrite(gi8Winc1501CsPin, LOW); - - while (u16Sz) { - *pu8Miso = WINC1501_SPI.transfer(*pu8Mosi); - - u16Sz--; - if (!u8SkipMiso) - pu8Miso++; - if (!u8SkipMosi) - pu8Mosi++; - } - - digitalWrite(gi8Winc1501CsPin, HIGH); - WINC1501_SPI.endTransaction(); - - return M2M_SUCCESS; -} - -extern "C" { - -/* -* @fn nm_bus_init -* @brief Initialize the bus wrapper -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M.S.M -* @date 28 oct 2013 -* @version 1.0 -*/ -sint8 nm_bus_init(void * /* pvInitValue */) -{ - sint8 result = M2M_SUCCESS; - - /* Configure SPI peripheral. */ - WINC1501_SPI.begin(); - - /* Configure CS PIN. */ - pinMode(gi8Winc1501CsPin, OUTPUT); - digitalWrite(gi8Winc1501CsPin, HIGH); - - /* Reset WINC1500. */ - nm_bsp_reset(); - nm_bsp_sleep(1); - - return result; -} - -/* -* @fn nm_bus_ioctl -* @brief send/receive from the bus -* @param[IN] u8Cmd -* IOCTL command for the operation -* @param[IN] pvParameter -* Arbitrary parameter depenging on IOCTL -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M.S.M -* @date 28 oct 2013 -* @note For SPI only, it's important to be able to send/receive at the same time -* @version 1.0 -*/ -sint8 nm_bus_ioctl(uint8 u8Cmd, void* pvParameter) -{ - sint8 s8Ret = 0; - switch(u8Cmd) - { - case NM_BUS_IOCTL_RW: { - tstrNmSpiRw *pstrParam = (tstrNmSpiRw *)pvParameter; - s8Ret = spi_rw(pstrParam->pu8InBuf, pstrParam->pu8OutBuf, pstrParam->u16Sz); - } - break; - default: - s8Ret = -1; - M2M_ERR("invalide ioclt cmd\n"); - break; - } - - return s8Ret; -} - -/* -* @fn nm_bus_deinit -* @brief De-initialize the bus wrapper -* @author M.S.M -* @date 28 oct 2013 -* @version 1.0 -*/ -sint8 nm_bus_deinit(void) -{ - WINC1501_SPI.end(); - return 0; -} - -/* -* @fn nm_bus_reinit -* @brief re-initialize the bus wrapper -* @param [in] void *config -* re-init configuration data -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Dina El Sissy -* @date 19 Sept 2012 -* @version 1.0 -*/ -sint8 nm_bus_reinit(void* /* config */) -{ - return M2M_SUCCESS; -} - -} // extern "C" - diff --git a/feather_sensor_transmit/libraries/WiFi101/src/common/include/nm_common.h b/feather_sensor_transmit/libraries/WiFi101/src/common/include/nm_common.h deleted file mode 100644 index d66fbdb..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/common/include/nm_common.h +++ /dev/null @@ -1,153 +0,0 @@ -/** - * - * \file - * - * \brief WINC Driver Common API Declarations. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NM_COMMON_H_ -#define _NM_COMMON_H_ - -#include "bsp/include/nm_bsp.h" -#include "common/include/nm_debug.h" - -/**@defgroup CommonDefines CommonDefines - * @ingroup WlanDefines - */ -/**@{*/ -#define M2M_TIME_OUT_DELAY 10000 - -/*states*/ -#define M2M_SUCCESS ((sint8)0) -#define M2M_ERR_SEND ((sint8)-1) -#define M2M_ERR_RCV ((sint8)-2) -#define M2M_ERR_MEM_ALLOC ((sint8)-3) -#define M2M_ERR_TIME_OUT ((sint8)-4) -#define M2M_ERR_INIT ((sint8)-5) -#define M2M_ERR_BUS_FAIL ((sint8)-6) -#define M2M_NOT_YET ((sint8)-7) -#define M2M_ERR_FIRMWARE ((sint8)-8) -#define M2M_SPI_FAIL ((sint8)-9) -#define M2M_ERR_FIRMWARE_bURN ((sint8)-10) -#define M2M_ACK ((sint8)-11) -#define M2M_ERR_FAIL ((sint8)-12) -#define M2M_ERR_FW_VER_MISMATCH ((sint8)-13) -#define M2M_ERR_SCAN_IN_PROGRESS ((sint8)-14) -#define M2M_ERR_INVALID_ARG ((sint8)-15) -#define M2M_ERR_INVALID ((sint8)-16) - -/*i2c MAASTER ERR*/ -#define I2C_ERR_LARGE_ADDRESS 0xE1UL /*the address exceed the max addressing mode in i2c flash*/ -#define I2C_ERR_TX_ABRT 0xE2UL /*NO ACK from slave*/ -#define I2C_ERR_OVER_SIZE 0xE3UL /**/ -#define ERR_PREFIX_NMIS 0xE4UL /*wrong first four byte in flash NMIS*/ -#define ERR_FIRMEWARE_EXCEED_SIZE 0xE5UL /*Total size of firmware exceed the max size 256k*/ -/**/ -#define PROGRAM_START 0x26961735UL -#define BOOT_SUCCESS 0x10add09eUL -#define BOOT_START 0x12345678UL - - -#define NBIT31 (0x80000000) -#define NBIT30 (0x40000000) -#define NBIT29 (0x20000000) -#define NBIT28 (0x10000000) -#define NBIT27 (0x08000000) -#define NBIT26 (0x04000000) -#define NBIT25 (0x02000000) -#define NBIT24 (0x01000000) -#define NBIT23 (0x00800000) -#define NBIT22 (0x00400000) -#define NBIT21 (0x00200000) -#define NBIT20 (0x00100000) -#define NBIT19 (0x00080000) -#define NBIT18 (0x00040000) -#define NBIT17 (0x00020000) -#define NBIT16 (0x00010000) -#define NBIT15 (0x00008000) -#define NBIT14 (0x00004000) -#define NBIT13 (0x00002000) -#define NBIT12 (0x00001000) -#define NBIT11 (0x00000800) -#define NBIT10 (0x00000400) -#define NBIT9 (0x00000200) -#define NBIT8 (0x00000100) -#define NBIT7 (0x00000080) -#define NBIT6 (0x00000040) -#define NBIT5 (0x00000020) -#define NBIT4 (0x00000010) -#define NBIT3 (0x00000008) -#define NBIT2 (0x00000004) -#define NBIT1 (0x00000002) -#define NBIT0 (0x00000001) - -#define M2M_MAX(A,B) ((A) > (B) ? (A) : (B)) -#define M2M_SEL(x,m1,m2,m3) ((x>1)?((x>2)?(m3):(m2)):(m1)) -#define WORD_ALIGN(val) (((val) & 0x03) ? ((val) + 4 - ((val) & 0x03)) : (val)) - - - -#define DATA_PKT_OFFSET 4 - -#ifndef BIG_ENDIAN -#define BYTE_0(word) ((uint8)(((word) >> 0 ) & 0x000000FFUL)) -#define BYTE_1(word) ((uint8)(((word) >> 8 ) & 0x000000FFUL)) -#define BYTE_2(word) ((uint8)(((word) >> 16) & 0x000000FFUL)) -#define BYTE_3(word) ((uint8)(((word) >> 24) & 0x000000FFUL)) -#else -#define BYTE_0(word) ((uint8)(((word) >> 24) & 0x000000FFUL)) -#define BYTE_1(word) ((uint8)(((word) >> 16) & 0x000000FFUL)) -#define BYTE_2(word) ((uint8)(((word) >> 8 ) & 0x000000FFUL)) -#define BYTE_3(word) ((uint8)(((word) >> 0 ) & 0x000000FFUL)) -#endif - -/**@}*/ -#ifdef __cplusplus - extern "C" { - #endif -NMI_API void m2m_memcpy(uint8* pDst,uint8* pSrc,uint32 sz); -NMI_API void m2m_memset(uint8* pBuf,uint8 val,uint32 sz); -NMI_API uint16 m2m_strlen(uint8 * pcStr); -NMI_API sint8 m2m_memcmp(uint8 *pu8Buff1,uint8 *pu8Buff2 ,uint32 u32Size); -NMI_API uint8 m2m_strncmp(uint8 *pcS1, uint8 *pcS2, uint16 u16Len); -NMI_API uint8 * m2m_strstr(uint8 *pcIn, uint8 *pcStr); -NMI_API uint8 m2m_checksum(uint8* buf, int sz); - -#ifdef __cplusplus -} - #endif -#endif /*_NM_COMMON_H_*/ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/common/include/nm_debug.h b/feather_sensor_transmit/libraries/WiFi101/src/common/include/nm_debug.h deleted file mode 100644 index a710f6c..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/common/include/nm_debug.h +++ /dev/null @@ -1,95 +0,0 @@ -/** - * - * \file - * - * \brief This module contains debug APIs declarations. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NM_DEBUG_H_ -#define _NM_DEBUG_H_ - -#include "bsp/include/nm_bsp.h" -#include "bsp/include/nm_bsp_internal.h" - -/**@defgroup DebugDefines DebugDefines - * @ingroup WlanDefines - */ -/**@{*/ - - -#define M2M_LOG_NONE 0 -#define M2M_LOG_ERROR 1 -#define M2M_LOG_INFO 2 -#define M2M_LOG_REQ 3 -#define M2M_LOG_DBG 4 - -#if (defined __APS3_CORTUS__) -#define M2M_LOG_LEVEL M2M_LOG_INFO -#else -#define M2M_LOG_LEVEL M2M_LOG_REQ -#endif - - -#define M2M_ERR(...) -#define M2M_INFO(...) -#define M2M_REQ(...) -#define M2M_DBG(...) -#define M2M_PRINT(...) - -#if (CONF_WINC_DEBUG == 1) -#undef M2M_PRINT -#define M2M_PRINT(...) do{CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) -#if (M2M_LOG_LEVEL >= M2M_LOG_ERROR) -#undef M2M_ERR -#define M2M_ERR(...) do{CONF_WINC_PRINTF("(APP)(ERR)[%s][%d]",__FUNCTION__,__LINE__); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) -#if (M2M_LOG_LEVEL >= M2M_LOG_INFO) -#undef M2M_INFO -#define M2M_INFO(...) do{CONF_WINC_PRINTF("(APP)(INFO)"); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) -#if (M2M_LOG_LEVEL >= M2M_LOG_REQ) -#undef M2M_REQ -#define M2M_REQ(...) do{CONF_WINC_PRINTF("(APP)(R)"); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) -#if (M2M_LOG_LEVEL >= M2M_LOG_DBG) -#undef M2M_DBG -#define M2M_DBG(...) do{CONF_WINC_PRINTF("(APP)(DBG)[%s][%d]",__FUNCTION__,__LINE__); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) -#endif /*M2M_LOG_DBG*/ -#endif /*M2M_LOG_REQ*/ -#endif /*M2M_LOG_INFO*/ -#endif /*M2M_LOG_ERROR*/ -#endif /*CONF_WINC_DEBUG */ - -/**@}*/ -#endif /* _NM_DEBUG_H_ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/common/source/nm_common.c b/feather_sensor_transmit/libraries/WiFi101/src/common/source/nm_common.c deleted file mode 100644 index 8b3c941..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/common/source/nm_common.c +++ /dev/null @@ -1,136 +0,0 @@ -/** - * - * \file - * - * \brief This module contains common APIs declarations. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -#include "common/include/nm_common.h" - -void m2m_memcpy(uint8* pDst,uint8* pSrc,uint32 sz) -{ - if(sz == 0) return; - do - { - *pDst = *pSrc; - pDst++; - pSrc++; - }while(--sz); -} -uint8 m2m_checksum(uint8* buf, int sz) -{ - uint8 cs = 0; - while(--sz) - { - cs ^= *buf; - buf++; - } - - return cs; -} - -void m2m_memset(uint8* pBuf,uint8 val,uint32 sz) -{ - if(sz == 0) return; - do - { - *pBuf = val; - pBuf++; - }while(--sz); -} - -uint16 m2m_strlen(uint8 * pcStr) -{ - uint16 u16StrLen = 0; - while(*pcStr) - { - u16StrLen ++; - pcStr++; - } - return u16StrLen; -} - -uint8 m2m_strncmp(uint8 *pcS1, uint8 *pcS2, uint16 u16Len) -{ - for ( ; u16Len > 0; pcS1++, pcS2++, --u16Len) - if (*pcS1 != *pcS2) - return ((*(uint8 *)pcS1 < *(uint8 *)pcS2) ? -1 : +1); - else if (*pcS1 == '\0') - return 0; - return 0; -} - -/* Finds the occurance of pcStr in pcIn. -If pcStr is part of pcIn it returns a valid pointer to the start of pcStr within pcIn. -Otherwise a NULL Pointer is returned. -*/ -uint8 * m2m_strstr(uint8 *pcIn, uint8 *pcStr) -{ - uint8 u8c; - uint16 u16StrLen; - - u8c = *pcStr++; - if (!u8c) - return (uint8 *) pcIn; // Trivial empty string case - - u16StrLen = m2m_strlen(pcStr); - do { - uint8 u8Sc; - - do { - u8Sc = *pcIn++; - if (!u8Sc) - return (uint8 *) 0; - } while (u8Sc != u8c); - } while (m2m_strncmp(pcIn, pcStr, u16StrLen) != 0); - - return (uint8 *) (pcIn - 1); -} - -sint8 m2m_memcmp(uint8 *pu8Buff1,uint8 *pu8Buff2 ,uint32 u32Size) -{ - uint32 i; - sint8 s8Result = 0; - for(i = 0 ; i < u32Size ; i++) - { - if(pu8Buff1[i] != pu8Buff2[i]) - { - s8Result = 1; - break; - } - } - return s8Result; -} diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/include/ecc_types.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/include/ecc_types.h deleted file mode 100644 index 764c3b9..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/include/ecc_types.h +++ /dev/null @@ -1,245 +0,0 @@ -/** - * - * \file - * - * \brief WINC Application Interface Internal Types. - * - * Copyright (c) 2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef __ECC_TYPES_H__ -#define __ECC_TYPES_H__ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "m2m_types.h" - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - - -#define ECC_LARGEST_CURVE_SIZE (32) -/*!< - The size of the the largest supported EC. For now, assuming - the 256-bit EC is the largest supported curve type. -*/ - - -#define ECC_POINT_MAX_SIZE ECC_LARGEST_CURVE_SIZE -/*!< - Maximum size of one coordinate of an EC point. -*/ - - -#define ECC_POINT_MAX_SIZE_WORDS (ECC_POINT_MAX_SIZE / 4) -/*!< - SIZE in 32-bit words. -*/ - -#if 0 -#define ECC_NUM_SUPP_CURVES ((sizeof(gastrECCSuppList)) / (sizeof(tstrEllipticCurve))) -#endif -/*!< -*/ - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -/*! -@enum \ - tenuEcNamedCurve - -@brief EC Named Curves - - Defines a list of supported ECC named curves. -*/ -typedef enum EcNamedCurve{ - EC_SECP192R1 = 19, - /*!< - It is defined by NIST as P192 and by the SEC Group as secp192r1. - */ - EC_SECP256R1 = 23, - /*!< - It is defined by NIST as P256 and by the SEC Group as secp256r1. - */ - EC_SECP384R1 = 24, - /*!< - It is defined by NIST as P384 and by the SEC Group as secp384r1. - */ - EC_SECP521R1 = 25, - /*!< - It is defined by NIST as P521 and by the SEC Group as secp521r1. - */ - EC_UNKNOWN = 255 -}tenuEcNamedCurve; - - -/*! -@struct \ - tstrECPoint - -@brief Elliptic Curve point representation -*/ -typedef struct EcPoint{ - uint8 X[ECC_POINT_MAX_SIZE]; - /*!< - The X-coordinate of the ec point. - */ - uint8 Y[ECC_POINT_MAX_SIZE]; - /*!< - The Y-coordinate of the ec point. - */ - uint16 u16Size; - /*!< - Point size in bytes (for each of the coordinates). - */ - uint16 u16PrivKeyID; - /*!< - ID for the corresponding private key. - */ -}tstrECPoint; - - -/*! -@struct \ - tstrECDomainParam - -@brief ECC Curve Domain Parameters - - The structure defines the ECC domain parameters for curves defined over prime finite fields. -*/ -typedef struct EcDomainParam{ - uint32 p[ECC_POINT_MAX_SIZE_WORDS]; - uint32 a[ECC_POINT_MAX_SIZE_WORDS]; - uint32 b[ECC_POINT_MAX_SIZE_WORDS]; - tstrECPoint G; -}tstrECDomainParam; - - -/*! -@struct \ - tstrEllipticCurve - -@brief - Definition of an elliptic curve -*/ -typedef struct{ - tenuEcNamedCurve enuType; - tstrECDomainParam strParam; -}tstrEllipticCurve; - - -typedef enum{ - ECC_REQ_NONE, - ECC_REQ_CLIENT_ECDH, - ECC_REQ_SERVER_ECDH, - ECC_REQ_GEN_KEY, - ECC_REQ_SIGN_GEN, - ECC_REQ_SIGN_VERIFY -}tenuEccREQ; - - -typedef struct{ - tstrECPoint strPubKey; - uint8 au8Key[ECC_POINT_MAX_SIZE]; -}tstrEcdhReqInfo; - - -typedef struct{ - uint32 u32nSig; -}tstrEcdsaVerifyReqInfo; - - -typedef struct{ - uint16 u16CurveType; - uint16 u16HashSz; -}tstrEcdsaSignReqInfo; - - -typedef struct{ - uint16 u16REQ; - uint16 u16Status; - uint32 u32UserData; - uint32 u32SeqNo; - union{ - tstrEcdhReqInfo strEcdhREQ; - tstrEcdsaSignReqInfo strEcdsaSignREQ; - tstrEcdsaVerifyReqInfo strEcdsaVerifyREQ; - }; -}tstrEccReqInfo; - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -GLOBALS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#if 0 -static tstrEllipticCurve gastrECCSuppList[] = { - { - EC_SECP256R1, - { - {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF}, - {0xFFFFFFFC, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF}, - {0x27D2604B, 0x3BCE3C3E, 0xCC53B0F6, 0x651D06B0, 0x769886BC, 0xB3EBBD55, 0xAA3A93E7, 0x5AC635D8}, - { - { - 0x6B, 0x17, 0xD1, 0xF2, 0xE1, 0x2C, 0x42, 0x47, 0xF8, 0xBC, 0xE6, 0xE5, 0x63, 0xA4, 0x40, 0xF2, - 0x77, 0x03, 0x7D, 0x81, 0x2D, 0xEB, 0x33, 0xA0, 0xF4, 0xA1, 0x39, 0x45, 0xD8, 0x98, 0xC2, 0x96 - }, - { - 0x4F, 0xE3, 0x42, 0xE2, 0xFE, 0x1A, 0x7F, 0x9B, 0x8E, 0xE7, 0xEB, 0x4A, 0x7C, 0x0F, 0x9E, 0x16, - 0x2B, 0xCE, 0x33, 0x57, 0x6B, 0x31, 0x5E, 0xCE, 0xCB, 0xB6, 0x40, 0x68, 0x37, 0xBF, 0x51, 0xF5 - }, - 32 - } - } - } -}; -#endif - -/*!< - List of supported Elliptic Curves ordered by security level (most secure curve is at index ZERO). -*/ - - - -#endif /* __ECC_TYPES_H__ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_ate_mode.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_ate_mode.h deleted file mode 100644 index a17d298..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_ate_mode.h +++ /dev/null @@ -1,732 +0,0 @@ -/** - * - * \file - * - * \brief WINC ATE Test Driver Interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifdef _M2M_ATE_FW_ - -#ifndef _M2M_ATE_MODE_H_ -#define _M2M_ATE_MODE_H_ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#include "common/include/nm_common.h" -#include "driver/include/m2m_types.h" - -/** \defgroup m2m_ate ATE -*/ -/**@defgroup ATEDefine Defines - * @ingroup m2m_ate - * @{ - */ -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#define M2M_ATE_MAX_NUM_OF_RATES (20) -/*!< -Maximum number of all rates (b,g and n) - */ -#define M2M_ATE_MAX_FRAME_LENGTH (1024) -/*!< Maximum number of length for each frame - */ -#define M2M_ATE_MIN_FRAME_LENGTH (1) -/*!< Minimum number of length for each frame - */ -#define M2M_ATE_SUCCESS (M2M_SUCCESS) -/*!< No Error and operation has been completed successfully. -*/ -#define M2M_ATE_ERR_VALIDATE (M2M_ERR_FAIL) -/*!< Error in parameters passed to functions. - */ -#define M2M_ATE_ERR_TX_ALREADY_RUNNING (-1) -/*!< Error in starting a transmission test. Another test is already running and its not allowed to start another ATE test. - */ -#define M2M_ATE_ERR_RX_ALREADY_RUNNING (-2) -/*!< Error in starting a reception test. Another test is already running and its not allowed to start another ATE test. - */ -#define M2M_ATE_ERR_UNHANDLED_CASE (-3) -/*!< Invalid case. - */ -#define M2M_ATE_RX_DISABLE_DA 0x0 -/*!< Filter selection for received frames: Disable filtering received frames by the destination address. - */ -#define M2M_ATE_RX_ENABLE_DA 0x1 -/*!< Filter selection for received frames: Enable filtering received frames by the destination address. - */ -#define M2M_ATE_RX_DISABLE_SA 0x0 -/*!< Filter selection for received frames: Disable filtering received frames by the source address. - */ -#define M2M_ATE_RX_ENABLE_SA 0x1 -/*!< Filter selection for received frames: Enable filtering received frames by the source address. - */ -#define M2M_ATE_DISABLE_SELF_MACADDR 0x0 -/*!\n",ret); - while(1); - } - //Initialize the OTA module - m2m_ota_init(OtaUpdateCb,NULL); - //connect to AP that provide connection to the OTA server - m2m_wifi_default_connect(); - - while(1) - { - - //Handle the app state machine plus the WINC event handler - while(m2m_wifi_handle_events(NULL) != M2M_SUCCESS) { - - } - - } -} -@endcode - -*/ -NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl); - /**@}*/ -/** @defgroup OtaStartUpdatefn m2m_ota_start_update_crt -* @ingroup WLANAPI -* Request OTA start for cortus application image using the downloaded URL, the OTA module will download the OTA image and ensure integrity of the image, -* and update the validity of the image in control structure. Switching to that image requires calling @ref m2m_ota_switch_crt API. -* As a prerequisite @ref m2m_ota_init should be called before using @ref m2m_ota_start_update_crt(). -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl); - -@param [in] u8DownloadUrl - The cortus application image url. -@warning - Calling this API does not guarantee cortus application image update, It depends on the connection with the download server and the validity of the image. - If the API response is failure this may invalidate the roll-back image if it was previously valid, since the WINC does not have any internal memory - except the flash roll-back image location to validate the downloaded image from - -@see - m2m_ota_init - tpfOtaUpdateCb - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl); - /**@}*/ -/** @defgroup OtaRollbackfn m2m_ota_rollback -* @ingroup WLANAPI - Request OTA Roll-back to the old (other) WINC image, the WINC firmware will check the validation of the Roll-back image - and switch to it if it is valid. - If the API response is success, system restart is required (re-initialize the driver with hardware rest) update the host driver version may - be required if it is did not match the minimum version supported by the WINC firmware. - -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ota_rollback(void); - -@sa - m2m_ota_init - m2m_ota_start_update - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_rollback(void); - /**@}*/ -/** @defgroup OtaRollbackfn m2m_ota_rollback_crt -* @ingroup WLANAPI - Request Cortus application OTA Roll-back to the old (other) cortus application image, the WINC firmware will check the validation of the Roll-back image - and switch to it if it is valid. - If the API response is success, system restart is required (re-initialize the driver with hardware rest) update the host driver version may - be required. - -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ota_rollback_crt(void); - -@sa - m2m_ota_init - m2m_ota_start_update_crt - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_rollback_crt(void); - /**@}*/ -/** @defgroup OtaAbortfn m2m_ota_abort -* @ingroup WLANAPI - Request abort of current OTA download. - The WINC firmware will terminate the OTA download if one is in progress. - If no download is in progress, the API will respond with failure. -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ota_abort(void); - -@return - The function returns @ref M2M_SUCCESS for successful operation and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_abort(void); - /**@}*/ - /**@}*/ -/** @defgroup OtaSwitchFirmware m2m_ota_switch_firmware -* @ingroup WLANAPI -* Switch to the upgraded Firmware, that API will update the control structure working image to the upgraded image - take effect will be on the next system restart -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ota_switch_firmware(void); - -@warning - It is important to note that if the API succeeds, system restart is required (re-initializing the driver with hardware reset) updating the host driver version may be required - if it does not match the minimum driver version supported by the WINC's firmware. -@sa - m2m_ota_init - m2m_ota_start_update - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_switch_firmware(void); - /**@}*/ - /**@}*/ -/** @defgroup OtaSwitchFirmware m2m_ota_switch_crt -* @ingroup WLANAPI -* Switch to the upgraded cortus application, that API will update the control structure working image to the upgraded image - take effect will be on the next system restart -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ota_switch_firmware(void); - -@warning - It is important to note that if the API succeeds, system restart is required (re-initializing the driver with hardware reset) updating the host driver version may be required - if it does not match the minimum driver version supported by the WINC's firmware. -@sa - m2m_ota_init - m2m_ota_start_update_crt - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_switch_crt(void); -/*! -@fn \ - NMI_API sint8 m2m_ota_get_firmware_version(void); - -@brief - Get the OTA Firmware version. - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_get_firmware_version(tstrM2mRev *pstrRev); - /**@}*/ -NMI_API sint8 m2m_ota_test(void); - -#ifdef __cplusplus -} -#endif -#endif /* __M2M_OTA_H__ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_periph.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_periph.h deleted file mode 100644 index 1012882..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_periph.h +++ /dev/null @@ -1,411 +0,0 @@ -/** - * - * \file - * - * \brief WINC Peripherals Application Interface. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _M2M_PERIPH_H_ -#define _M2M_PERIPH_H_ - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -#include "common/include/nm_common.h" -#include "driver/include/m2m_types.h" - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*! -@struct \ - tstrPerphInitParam - -@brief - Peripheral module initialization parameters. -*/ -typedef struct { - void * arg; -} tstrPerphInitParam; - - -/*! -@enum \ - tenuGpioNum - -@brief - A list of GPIO numbers configurable through the m2m_periph module. -*/ -typedef enum { - M2M_PERIPH_GPIO3, /*!< GPIO15 pad */ - M2M_PERIPH_GPIO4, /*!< GPIO16 pad */ - M2M_PERIPH_GPIO5, /*!< GPIO18 pad */ - M2M_PERIPH_GPIO6, /*!< GPIO18 pad */ - M2M_PERIPH_GPIO15, /*!< GPIO15 pad */ - M2M_PERIPH_GPIO16, /*!< GPIO16 pad */ - M2M_PERIPH_GPIO18, /*!< GPIO18 pad */ - M2M_PERIPH_GPIO_MAX -} tenuGpioNum; - - -/*! -@enum \ - tenuI2cMasterSclMuxOpt - -@brief - Allowed pin multiplexing options for I2C master SCL signal. -*/ -typedef enum { - M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_HOST_WAKEUP, /*!< I2C master SCL is avaiable on HOST_WAKEUP. */ - M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_SD_DAT3, /*!< I2C master SCL is avaiable on SD_DAT3 (GPIO 7). */ - M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_GPIO13, /*!< I2C master SCL is avaiable on GPIO 13. */ - M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_GPIO4, /*!< I2C master SCL is avaiable on GPIO 4.*/ - M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_I2C_SCL, /*!< I2C master SCL is avaiable on I2C slave SCL. */ - M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_NUM -} tenuI2cMasterSclMuxOpt; - -/*! -@enum \ - tenuI2cMasterSdaMuxOpt - -@brief - Allowed pin multiplexing options for I2C master SDA signal. -*/ -typedef enum { - M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_RTC_CLK , /*!< I2C master SDA is avaiable on RTC_CLK. */ - M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_SD_CLK, /*!< I2C master SDA is avaiable on SD_CLK (GPIO 8). */ - M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_GPIO14, /*!< I2C master SDA is avaiable on GPIO 14. */ - M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_GPIO6, /*!< I2C master SDA is avaiable on GPIO 6.*/ - M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_I2C_SDA, /*!< I2C master SDA is avaiable on I2C slave SDA. */ - M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_NUM -} tenuI2cMasterSdaMuxOpt; - - -/*! -@struct \ - tstrI2cMasterInitParam - -@brief - I2C master configuration parameters. -@sa - tenuI2cMasterSclMuxOpt - tenuI2cMasterSdaMuxOpt -*/ -typedef struct { - uint8 enuSclMuxOpt; /*!< SCL multiplexing option. Allowed value are defined in tenuI2cMasterSclMuxOpt */ - uint8 enuSdaMuxOpt; /*!< SDA multiplexing option. Allowed value are defined in tenuI2cMasterSdaMuxOpt */ - uint8 u8ClkSpeedKHz; /*!< I2C master clock speed in KHz. */ -} tstrI2cMasterInitParam; - -/*! -@enum \ - tenuI2cMasterFlags - -@brief - Bitwise-ORed flags for use in m2m_periph_i2c_master_write and m2m_periph_i2c_master_read -@sa - m2m_periph_i2c_master_write - m2m_periph_i2c_master_read -*/ -typedef enum { - I2C_MASTER_NO_FLAGS = 0x00, - /*!< No flags. */ - I2C_MASTER_NO_STOP = 0x01, - /*!< No stop bit after this transaction. Useful for scattered buffer read/write operations. */ - I2C_MASTER_NO_START = 0x02, - /*!< No start bit at the beginning of this transaction. Useful for scattered buffer read/write operations.*/ -} tenuI2cMasterFlags; - -/*! -@enum \ - tenuPullupMask - -@brief - Bitwise-ORed flags for use in m2m_perph_pullup_ctrl. -@sa - m2m_periph_pullup_ctrl - -*/ -typedef enum { - M2M_PERIPH_PULLUP_DIS_HOST_WAKEUP = (1ul << 0), - M2M_PERIPH_PULLUP_DIS_RTC_CLK = (1ul << 1), - M2M_PERIPH_PULLUP_DIS_IRQN = (1ul << 2), - M2M_PERIPH_PULLUP_DIS_GPIO_3 = (1ul << 3), - M2M_PERIPH_PULLUP_DIS_GPIO_4 = (1ul << 4), - M2M_PERIPH_PULLUP_DIS_GPIO_5 = (1ul << 5), - M2M_PERIPH_PULLUP_DIS_SD_DAT3 = (1ul << 6), - M2M_PERIPH_PULLUP_DIS_SD_DAT2_SPI_RXD = (1ul << 7), - M2M_PERIPH_PULLUP_DIS_SD_DAT1_SPI_SSN = (1ul << 9), - M2M_PERIPH_PULLUP_DIS_SD_CMD_SPI_SCK = (1ul << 10), - M2M_PERIPH_PULLUP_DIS_SD_DAT0_SPI_TXD = (1ul << 11), - M2M_PERIPH_PULLUP_DIS_GPIO_6 = (1ul << 12), - M2M_PERIPH_PULLUP_DIS_SD_CLK = (1ul << 13), - M2M_PERIPH_PULLUP_DIS_I2C_SCL = (1ul << 14), - M2M_PERIPH_PULLUP_DIS_I2C_SDA = (1ul << 15), - M2M_PERIPH_PULLUP_DIS_GPIO_11 = (1ul << 16), - M2M_PERIPH_PULLUP_DIS_GPIO_12 = (1ul << 17), - M2M_PERIPH_PULLUP_DIS_GPIO_13 = (1ul << 18), - M2M_PERIPH_PULLUP_DIS_GPIO_14 = (1ul << 19), - M2M_PERIPH_PULLUP_DIS_GPIO_15 = (1ul << 20), - M2M_PERIPH_PULLUP_DIS_GPIO_16 = (1ul << 21), - M2M_PERIPH_PULLUP_DIS_GPIO_17 = (1ul << 22), - M2M_PERIPH_PULLUP_DIS_GPIO_18 = (1ul << 23), - M2M_PERIPH_PULLUP_DIS_GPIO_19 = (1ul << 24), - M2M_PERIPH_PULLUP_DIS_GPIO_20 = (1ul << 25), - M2M_PERIPH_PULLUP_DIS_GPIO_21 = (1ul << 26), - M2M_PERIPH_PULLUP_DIS_GPIO_22 = (1ul << 27), - M2M_PERIPH_PULLUP_DIS_GPIO_23 = (1ul << 28), - M2M_PERIPH_PULLUP_DIS_GPIO_24 = (1ul << 29), -} tenuPullupMask; - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -#ifdef __cplusplus - extern "C" { -#endif - -/*! -@fn \ - NMI_API sint8 m2m_periph_init(tstrPerphInitParam * param); - -@brief - Initialize the NMC1500 peripheral driver module. - -@param [in] param - Peripheral module initialization structure. See members of tstrPerphInitParam. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tstrPerphInitParam -*/ -NMI_API sint8 m2m_periph_init(tstrPerphInitParam * param); - -/*! -@fn \ - NMI_API sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir); - -@brief - Configure a specific NMC1500 pad as a GPIO and sets its direction (input or output). - -@param [in] u8GpioNum - GPIO number. Allowed values are defined in tenuGpioNum. - -@param [in] u8GpioDir - GPIO direction: Zero = input. Non-zero = output. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuGpioNum -*/ -NMI_API sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir); - -/*! -@fn \ - NMI_API sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal); - -@brief - Set an NMC1500 GPIO output level high or low. - -@param [in] u8GpioNum - GPIO number. Allowed values are defined in tenuGpioNum. - -@param [in] u8GpioVal - GPIO output value. Zero = low, non-zero = high. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuGpioNum -*/ -NMI_API sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal); - -/*! -@fn \ - NMI_API sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal); - -@brief - Read an NMC1500 GPIO input level. - -@param [in] u8GpioNum - GPIO number. Allowed values are defined in tenuGpioNum. - -@param [out] pu8GpioVal - GPIO input value. Zero = low, non-zero = high. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuGpioNum -*/ -NMI_API sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal); - -/*! -@fn \ - NMI_API sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn); - -@brief - Set an NMC1500 GPIO pullup resisitor enable or disable. - -@param [in] u8GpioNum - GPIO number. Allowed values are defined in tenuGpioNum. - -@param [in] u8PullupEn - Zero: pullup disabled. Non-zero: pullup enabled. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuGpioNum -*/ -NMI_API sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn); - -/*! -@fn \ - NMI_API sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param); - -@brief - Initialize and configure the NMC1500 I2C master peripheral. - -@param [in] param - I2C master initialization structure. See members of tstrI2cMasterInitParam. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tstrI2cMasterInitParam -*/ -NMI_API sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param); - -/*! -@fn \ - NMI_API sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags); - -@brief - Write a stream of bytes to the I2C slave device. - -@param [in] u8SlaveAddr - 7-bit I2C slave address. -@param [in] pu8Buf - A pointer to an input buffer which contains a stream of bytes. -@param [in] u16BufLen - Input buffer length in bytes. -@param [in] flags - Write operation bitwise-ORed flags. See tenuI2cMasterFlags. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuI2cMasterFlags -*/ -NMI_API sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags); - - -/*! -@fn \ - NMI_API sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags); - -@brief - Write a stream of bytes to the I2C slave device. - -@param [in] u8SlaveAddr - 7-bit I2C slave address. -@param [out] pu8Buf - A pointer to an output buffer in which a stream of bytes are received. -@param [in] u16BufLen - Max output buffer length in bytes. -@param [out] pu16ReadLen - Actual number of bytes received. -@param [in] flags - Write operation bitwise-ORed flags. See tenuI2cMasterFlags. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuI2cMasterFlags -*/ -NMI_API sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags); - - -/*! -@fn \ - NMI_API sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable); - -@brief - Control the programmable pull-up resistor on the chip pads . - - -@param [in] pinmask - Write operation bitwise-ORed mask for which pads to control. Allowed values are defined in tenuPullupMask. - -@param [in] enable - Set to 0 to disable pull-up resistor. Non-zero will enable the pull-up. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuPullupMask -*/ -NMI_API sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable); - -#ifdef __cplusplus -} -#endif - - -#endif /* _M2M_PERIPH_H_ */ \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_ssl.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_ssl.h deleted file mode 100644 index f5271f0..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_ssl.h +++ /dev/null @@ -1,182 +0,0 @@ -/** - * - * \file - * - * \brief WINC Application Interface Internal Types. - * - * Copyright (c) 2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/**@defgroup SSLAPI SSL -*/ - -#ifndef __M2M_SSL_H__ -#define __M2M_SSL_H__ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "common/include/nm_common.h" -#include "driver/include/m2m_types.h" -#include "driver/source/nmdrv.h" -#include "ecc_types.h" -#include "socket/include/socket.h" - -/**@defgroup SSLEnums Enumeration/Typedefs - * @ingroup SSLAPI - * @{*/ - -/*! -@typedef \ - void (*tpfAppSslCb) (uint8 u8MsgType, void * pvMsg); - -@brief A callback to get SSL notifications. - -@param[in] u8MsgType -@param[in] pvMsg A structure to provide notification payload. -*/ -typedef void (*tpfAppSSLCb) (uint8 u8MsgType, void * pvMsg); - -/**@} -*/ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/** \defgroup SSLFUNCTIONS Functions -* @ingroup SSLAPI -*/ - -/**@{*/ -/*! - @fn \ m2m_ssl_init(tpfAppSslCb pfAppSslCb); - @brief Initializes the SSL layer. - @param [in] pfAppSslCb - Application SSL callback function. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_init(tpfAppSSLCb pfAppSSLCb); - -/*! - @fn \ NMI_API sint8 m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz) - @brief Sends ECC responses to the WINC - @param [in] strECCResp - ECC Response struct. - @param [in] pu8RspDataBuffe - Pointer of the response data to be sent. - @param [in] u16RspDataSz - Response data size. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz); - -/*! - @fn \ NMI_API sint8 m2m_ssl_send_certs_to_winc(uint8* pu8Buffer, uint32 u32BufferSz) - @brief Sends certificates to the WINC - @param [in] pu8Buffer - Pointer to the certificates. - @param [in] u32BufferSz - Size of the certificates. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_send_certs_to_winc(uint8* pu8Buffer, uint32 u32BufferSz); - -/*! - @fn \ NMI_API sint8 m2m_ssl_retrieve_cert(uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key) - @brief Retrieve the certificate to be verified from the WINC - @param [in] pu16CurveType - Pointer to the certificate curve type. - @param [in] pu8Hash - Pointer to the certificate hash. - @param [in] pu8Sig - Pointer to the certificate signature. - @param [in] pu8Key - Pointer to the certificate Key. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_retrieve_cert(uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key); - -/*! - @fn \ NMI_API sint8 m2m_ssl_retrieve_hash(uint8* pu8Hash, uint16 u16HashSz) - @brief Retrieve the certificate hash - @param [in] pu8Hash - Pointer to the certificate hash. - @param [in] u16HashSz - Hash size. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_retrieve_hash(uint8* pu8Hash, uint16 u16HashSz); - -/*! - @fn \ NMI_API void m2m_ssl_stop_processing_certs(void) - @brief Allow ssl driver to tidy up in case application does not read all available certificates. - @warning This API must only be called if some certificates are left unread. - @return None. -*/ -NMI_API void m2m_ssl_stop_processing_certs(void); - -/*! - @fn \ NMI_API void m2m_ssl_ecc_process_done(void) - @brief Allow ssl driver to tidy up after application has finished processing ecc message. - @warning This API must be called after receiving a SSL callback with type @ref M2M_SSL_REQ_ECC - @return None. -*/ -NMI_API void m2m_ssl_ecc_process_done(void); - -/*! -@fn \ - NMI_API sint8 m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP); - Override the default Active SSL ciphers in the SSL module with a certain combination selected by the caller in the form of - a bitmap containing the required ciphers to be on. - There is no need to call this function if the application will not change the default ciphersuites. - -@param [in] u32SslCsBMP - Bitmap containing the desired ciphers to be enabled for the SSL module. The ciphersuites are defined in - @ref SSLCipherSuiteID. - The default ciphersuites are all ciphersuites supported by the firmware with the exception of ECC ciphersuites. - The caller can override the default with any desired combination, except for combinations involving both RSA - and ECC; if any RSA ciphersuite is enabled, then firmware will disable all ECC ciphersuites. - If u32SslCsBMP does not contain any ciphersuites supported by firmware, then the current active list will not - be changed. - -@return - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) -*/ -sint8 m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP); - - /**@}*/ -#endif /* __M2M_SSL_H__ */ \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_types.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_types.h deleted file mode 100644 index a847f3f..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_types.h +++ /dev/null @@ -1,2383 +0,0 @@ -/** - * - * \file - * - * \brief WINC Application Interface Internal Types. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef __M2M_WIFI_TYPES_H__ -#define __M2M_WIFI_TYPES_H__ - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#ifndef _BOOT_ -#ifndef _FIRMWARE_ -#include "common/include/nm_common.h" -#else -#include "m2m_common.h" -#endif -#endif - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/**@defgroup WlanDefines Defines - * @ingroup m2m_wifi - */ -/**@{*/ -#define M2M_MAJOR_SHIFT (8) -#define M2M_MINOR_SHIFT (4) -#define M2M_PATCH_SHIFT (0) - -#define M2M_DRV_VERSION_SHIFT (16) -#define M2M_FW_VERSION_SHIFT (0) - -#define M2M_GET_MAJOR(ver_info_hword) ((uint8)((ver_info_hword) >> M2M_MAJOR_SHIFT) & 0xff) -#define M2M_GET_MINOR(ver_info_hword) ((uint8)((ver_info_hword) >> M2M_MINOR_SHIFT) & 0x0f) -#define M2M_GET_PATCH(ver_info_hword) ((uint8)((ver_info_hword) >> M2M_PATCH_SHIFT) & 0x0f) - -#define M2M_GET_FW_VER(ver_info_word) ((uint16) ((ver_info_word) >> M2M_FW_VERSION_SHIFT)) -#define M2M_GET_DRV_VER(ver_info_word) ((uint16) ((ver_info_word) >> M2M_DRV_VERSION_SHIFT)) - -#define M2M_GET_DRV_MAJOR(ver_info_word) M2M_GET_MAJOR(M2M_GET_DRV_VER(ver_info_word)) -#define M2M_GET_DRV_MINOR(ver_info_word) M2M_GET_MINOR(M2M_GET_DRV_VER(ver_info_word)) -#define M2M_GET_DRV_PATCH(ver_info_word) M2M_GET_PATCH(M2M_GET_DRV_VER(ver_info_word)) - -#define M2M_GET_FW_MAJOR(ver_info_word) M2M_GET_MAJOR(M2M_GET_FW_VER(ver_info_word)) -#define M2M_GET_FW_MINOR(ver_info_word) M2M_GET_MINOR(M2M_GET_FW_VER(ver_info_word)) -#define M2M_GET_FW_PATCH(ver_info_word) M2M_GET_PATCH(M2M_GET_FW_VER(ver_info_word)) - -#define M2M_MAKE_VERSION(major, minor, patch) ( \ - ((uint16)((major) & 0xff) << M2M_MAJOR_SHIFT) | \ - ((uint16)((minor) & 0x0f) << M2M_MINOR_SHIFT) | \ - ((uint16)((patch) & 0x0f) << M2M_PATCH_SHIFT)) - -#define M2M_MAKE_VERSION_INFO(fw_major, fw_minor, fw_patch, drv_major, drv_minor, drv_patch) \ - ( \ - ( ((uint32)M2M_MAKE_VERSION((fw_major), (fw_minor), (fw_patch))) << M2M_FW_VERSION_SHIFT) | \ - ( ((uint32)M2M_MAKE_VERSION((drv_major), (drv_minor), (drv_patch))) << M2M_DRV_VERSION_SHIFT)) - -#define REL_19_5_2_VER M2M_MAKE_VERSION_INFO(19,5,2,19,3,0) -#define REL_19_5_1_VER M2M_MAKE_VERSION_INFO(19,5,1,19,3,0) -#define REL_19_5_0_VER M2M_MAKE_VERSION_INFO(19,5,0,19,3,0) -#define REL_19_4_6_VER M2M_MAKE_VERSION_INFO(19,4,6,19,3,0) -#define REL_19_4_5_VER M2M_MAKE_VERSION_INFO(19,4,5,19,3,0) -#define REL_19_4_4_VER M2M_MAKE_VERSION_INFO(19,4,4,19,3,0) -#define REL_19_4_3_VER M2M_MAKE_VERSION_INFO(19,4,3,19,3,0) -#define REL_19_4_2_VER M2M_MAKE_VERSION_INFO(19,4,2,19,3,0) -#define REL_19_4_1_VER M2M_MAKE_VERSION_INFO(19,4,1,19,3,0) -#define REL_19_4_0_VER M2M_MAKE_VERSION_INFO(19,4,0,19,3,0) -#define REL_19_3_1_VER M2M_MAKE_VERSION_INFO(19,3,1,19,3,0) -#define REL_19_3_0_VER M2M_MAKE_VERSION_INFO(19,3,0,19,3,0) -#define REL_19_2_2_VER M2M_MAKE_VERSION_INFO(19,2,2,19,2,0) -#define REL_19_2_1_VER M2M_MAKE_VERSION_INFO(19,2,1,19,2,0) -#define REL_19_2_0_VER M2M_MAKE_VERSION_INFO(19,2,0,19,2,0) -#define REL_19_1_0_VER M2M_MAKE_VERSION_INFO(19,1,0,18,2,0) -#define REL_19_0_0_VER M2M_MAKE_VERSION_INFO(19,0,0,18,1,1) - -/*======*======*======*======* - FIRMWARE VERSION NO INFO - *======*======*======*======*/ - -#define M2M_RELEASE_VERSION_MAJOR_NO (19) -/*!< Firmware Major release version number. -*/ - - -#define M2M_RELEASE_VERSION_MINOR_NO (5) -/*!< Firmware Minor release version number. -*/ - -#define M2M_RELEASE_VERSION_PATCH_NO (2) -/*!< Firmware patch release version number. -*/ - -/*======*======*======*======* - SUPPORTED DRIVER VERSION NO INFO - *======*======*======*======*/ - -#define M2M_MIN_REQ_DRV_VERSION_MAJOR_NO (19) -/*!< Driver Major release version number. -*/ - - -#define M2M_MIN_REQ_DRV_VERSION_MINOR_NO (3) -/*!< Driver Minor release version number. -*/ - -#define M2M_MIN_REQ_DRV_VERSION_PATCH_NO (0) -/*!< Driver patch release version number. -*/ - -#define M2M_MIN_REQ_DRV_SVN_VERSION (0) -/*!< Driver svn version. -*/ - - - -#if !defined(M2M_RELEASE_VERSION_MAJOR_NO) || !defined(M2M_RELEASE_VERSION_MINOR_NO) -#error Undefined version number -#endif - -#define M2M_BUFFER_MAX_SIZE (1600UL - 4) -/*!< Maximum size for the shared packet buffer. - */ - - -#define M2M_MAC_ADDRES_LEN 6 -/*!< The size fo 802 MAC address. - */ - -#define M2M_ETHERNET_HDR_OFFSET 34 -/*!< The offset of the Ethernet header within the WLAN Tx Buffer. - */ - - -#define M2M_ETHERNET_HDR_LEN 14 -/*!< Length of the Etherenet header in bytes. -*/ - - -#define M2M_MAX_SSID_LEN 33 -/*!< Maximum size for the Wi-Fi SSID including the NULL termination. - */ - - -#define M2M_MAX_PSK_LEN 65 -/*!< Maximum size for the WPA PSK including the NULL termination. - */ - -#define M2M_MIN_PSK_LEN 9 -/*!< Maximum size for the WPA PSK including the NULL termination. - */ - -#define M2M_DEVICE_NAME_MAX 48 -/*!< Maximum Size for the device name including the NULL termination. - */ - - -#define M2M_LISTEN_INTERVAL 1 -/*!< The STA uses the Listen Interval parameter to indicate to the AP how - many beacon intervals it shall sleep before it retrieves the queued frames - from the AP. -*/ - -#define MAX_HIDDEN_SITES 4 -/*!< - max number of hidden SSID suuported by scan request -*/ - - -#define M2M_1X_USR_NAME_MAX 21 -/*!< The maximum size of the user name including the NULL termination. - It is used for RADIUS authentication in case of connecting the device to - an AP secured with WPA-Enterprise. -*/ - - -#define M2M_1X_PWD_MAX 41 -/*!< The maximum size of the password including the NULL termination. - It is used for RADIUS authentication in case of connecting the device to - an AP secured with WPA-Enterprise. -*/ - -#define M2M_CUST_IE_LEN_MAX 252 -/*!< The maximum size of IE (Information Element). -*/ - -#define PWR_DEFAULT PWR_HIGH -/********************* - * - * WIFI GROUP requests - */ - -#define M2M_CONFIG_CMD_BASE 1 -/*!< The base value of all the host configuration commands opcodes. -*/ -#define M2M_STA_CMD_BASE 40 -/*!< The base value of all the station mode host commands opcodes. -*/ -#define M2M_AP_CMD_BASE 70 -/*!< The base value of all the Access Point mode host commands opcodes. -*/ -#define M2M_P2P_CMD_BASE 90 -/*!< The base value of all the P2P mode host commands opcodes. -*/ -#define M2M_SERVER_CMD_BASE 100 -/*!< The base value of all the power save mode host commands codes. -*/ -/********************** - * OTA GROUP requests - */ -#define M2M_OTA_CMD_BASE 100 -/*!< The base value of all the OTA mode host commands opcodes. - * The OTA Have special group so can extended from 1-M2M_MAX_GRP_NUM_REQ -*/ -/*********************** - * - * CRYPTO group requests - */ -#define M2M_CRYPTO_CMD_BASE 1 -/*!< The base value of all the crypto mode host commands opcodes. - * The crypto Have special group so can extended from 1-M2M_MAX_GRP_NUM_REQ -*/ - -#define M2M_MAX_GRP_NUM_REQ (127) -/*!< max number of request in one group equal to 127 as the last bit reserved for config or data pkt -*/ - -#define WEP_40_KEY_STRING_SIZE ((uint8)10) -/*!< Indicate the wep key size in bytes for 40 bit string passphrase. -*/ - -#define WEP_104_KEY_STRING_SIZE ((uint8)26) -/*!< Indicate the wep key size in bytes for 104 bit string passphrase. -*/ -#define WEP_KEY_MAX_INDEX ((uint8)4) -/*!< Indicate the max key index value for WEP authentication -*/ -#define M2M_SHA256_CONTEXT_BUFF_LEN (128) -/*!< sha256 context size -*/ -#define M2M_SCAN_DEFAULT_NUM_SLOTS (2) -/*!< The default. number of scan slots performed by the WINC board. -*/ -#define M2M_SCAN_DEFAULT_SLOT_TIME (30) -/*!< The default. duration in miliseconds of a scan slots performed by the WINC board. -*/ -#define M2M_SCAN_DEFAULT_NUM_PROBE (2) -/*!< The default. number of scan slots performed by the WINC board. -*/ - - -/*======*======*======*======* - CONNECTION ERROR DEFINITIONS - *======*======*======*======*/ -typedef enum { - M2M_DEFAULT_CONN_INPROGRESS = ((sint8)-23), - /*!< - A failure that indicates that a default connection or forced connection is in progress - */ - M2M_DEFAULT_CONN_FAIL, - /*!< - A failure response that indicates that the winc failed to connect to the cached network - */ - M2M_DEFAULT_CONN_SCAN_MISMATCH, - /*!< - A failure response that indicates that no one of the cached networks - was found in the scan results, as a result to the function call m2m_default_connect. - */ - M2M_DEFAULT_CONN_EMPTY_LIST - /*!< - A failure response that indicates an empty network list as - a result to the function call m2m_default_connect. - */ - -}tenuM2mDefaultConnErrcode; - - - -/*======*======*======*======* - TLS DEFINITIONS - *======*======*======*======*/ -#define TLS_FILE_NAME_MAX 48 -/*!< Maximum length for each TLS certificate file name including null terminator. -*/ -#define TLS_SRV_SEC_MAX_FILES 8 -/*!< Maximum number of certificates allowed in TLS_SRV section. -*/ -#define TLS_SRV_SEC_START_PATTERN_LEN 8 -/*!< Length of certificate struct start pattern. -*/ -/*======*======*======*======* - OTA DEFINITIONS - *======*======*======*======*/ - -#define OTA_STATUS_VALID (0x12526285) -/*!< - Magic value updated in the Control structure in case of ROLLACK image Valid -*/ -#define OTA_STATUS_INVALID (0x23987718) -/*!< - Magic value updated in the Control structure in case of ROLLACK image InValid -*/ -#define OTA_MAGIC_VALUE (0x1ABCDEF9) -/*!< - Magic value set at the beginning of the OTA image header -*/ -#define M2M_MAGIC_APP (0xef522f61UL) -/*!< - Magic value set at the beginning of the Cortus OTA image header -*/ - -#define OTA_FORMAT_VER_0 (0) /*Till 19.2.2 format*/ -#define OTA_FORMAT_VER_1 (1) /*starting from 19.3.0 CRC is used and sequence number is used*/ -/*!< - Control structure format version -*/ -#define OTA_SHA256_DIGEST_SIZE (32) -/*!< - Sha256 digest size in the OTA image, - the sha256 digest is set at the beginning of image before the OTA header - */ - -/*======*======*======*======* - SSL DEFINITIONS - *======*======*======*======*/ - -#define TLS_CRL_DATA_MAX_LEN 64 -/* Every bit have 3dB gain control each. - for example: - 1 ->3db - 3 ->6db - 7 ->9db - */ - uint16 u8PPAGFor11GN; - /*!< PPA gain for 11GN (as the RF document represented) - PPA_AGC<0:2> Every bit have 3dB gain control each. - for example: - 1 ->3db - 3 ->6db - 7 ->9db - */ -}tstrM2mWifiGainsParams; - -/*! -@struct \ - tstrM2mWifiWepParams - -@brief - WEP security key parameters. -*/ -typedef struct{ - uint8 u8KeyIndx; - /*!< Wep key Index. - */ - uint8 u8KeySz; - /*!< Wep key Size. - */ - uint8 au8WepKey[WEP_104_KEY_STRING_SIZE + 1]; - /*!< WEP Key represented as a NULL terminated ASCII string. - */ - uint8 __PAD24__[3]; - /*!< Padding bytes to keep the structure word alligned. - */ -}tstrM2mWifiWepParams; - - -/*! -@struct \ - tstr1xAuthCredentials - -@brief - Credentials for the user to authenticate with the AAA server (WPA-Enterprise Mode IEEE802.1x). -*/ -typedef struct{ - uint8 au8UserName[M2M_1X_USR_NAME_MAX]; - /*!< User Name. It must be Null terminated string. - */ - uint8 au8Passwd[M2M_1X_PWD_MAX]; - /*!< Password corresponding to the user name. It must be Null terminated string. - */ -}tstr1xAuthCredentials; - - -/*! -@union \ - tuniM2MWifiAuth - -@brief - Wi-Fi Security Parameters for all supported security modes. -*/ -typedef union{ - uint8 au8PSK[M2M_MAX_PSK_LEN]; - /*!< Pre-Shared Key in case of WPA-Personal security. - */ - tstr1xAuthCredentials strCred1x; - /*!< Credentials for RADIUS server authentication in case of WPA-Enterprise security. - */ - tstrM2mWifiWepParams strWepInfo; - /*!< WEP key parameters in case of WEP security. - */ -}tuniM2MWifiAuth; - - -/*! -@struct \ - tstrM2MWifiSecInfo - -@brief - Authentication credentials to connect to a Wi-Fi network. -*/ -typedef struct{ - tuniM2MWifiAuth uniAuth; - /*!< Union holding all possible authentication parameters corresponding the current security types. - */ - uint8 u8SecType; - /*!< Wi-Fi network security type. See tenuM2mSecType for supported security types. - */ -#define __PADDING__ (4 - ((sizeof(tuniM2MWifiAuth) + 1) % 4)) - uint8 __PAD__[__PADDING__]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2MWifiSecInfo; - - -/*! -@struct \ - tstrM2mWifiConnect - -@brief - Wi-Fi Connect Request -*/ -typedef struct{ - tstrM2MWifiSecInfo strSec; - /*!< Security parameters for authenticating with the AP. - */ - uint16 u16Ch; - /*!< RF Channel for the target SSID. - */ - uint8 au8SSID[M2M_MAX_SSID_LEN]; - /*!< SSID of the desired AP. It must be NULL terminated string. - */ - uint8 u8NoSaveCred; -#define __CONN_PAD_SIZE__ (4 - ((sizeof(tstrM2MWifiSecInfo) + M2M_MAX_SSID_LEN + 3) % 4)) - uint8 __PAD__[__CONN_PAD_SIZE__]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mWifiConnect; - - -/*! -@struct \ - tstrM2MWPSConnect - -@brief - WPS Configuration parameters - -@sa - tenuWPSTrigger -*/ -typedef struct { - uint8 u8TriggerType; - /*!< WPS triggering method (Push button or PIN) - */ - char acPinNumber[8]; - /*!< WPS PIN No (for PIN method) - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2MWPSConnect; - - -/*! -@struct \ - tstrM2MWPSInfo - -@brief WPS Result - - This structure is passed to the application in response to a WPS request. If the WPS session is completed successfully, the - structure will have Non-ZERO authentication type. If the WPS Session fails (due to error or timeout) the authentication type - is set to ZERO. - -@sa - tenuM2mSecType -*/ -typedef struct{ - uint8 u8AuthType; - /*!< Network authentication type. - */ - uint8 u8Ch; - /*!< RF Channel for the AP. - */ - uint8 au8SSID[M2M_MAX_SSID_LEN]; - /*!< SSID obtained from WPS. - */ - uint8 au8PSK[M2M_MAX_PSK_LEN]; - /*!< PSK for the network obtained from WPS. - */ -}tstrM2MWPSInfo; - - -/*! -@struct \ - tstrM2MDefaultConnResp - -@brief - Response error of the m2m_default_connect - -@sa - M2M_DEFAULT_CONN_SCAN_MISMATCH - M2M_DEFAULT_CONN_EMPTY_LIST -*/ -typedef struct{ - sint8 s8ErrorCode; - /*!< - Default connect error code. possible values are: - - M2M_DEFAULT_CONN_EMPTY_LIST - - M2M_DEFAULT_CONN_SCAN_MISMATCH - */ - uint8 __PAD24__[3]; -}tstrM2MDefaultConnResp; - -/*! -@struct \ - tstrM2MScanOption - -@brief - Scan options and configurations. - -@sa - tenuM2mScanCh - tstrM2MScan -*/ -typedef struct { - uint8 u8NumOfSlot; - /*|< The min number of slots is 2 for every channel, - every slot the soc will send Probe Request on air, and wait/listen for PROBE RESP/BEACONS for the u16slotTime - */ - uint8 u8SlotTime; - /*|< the time that the Soc will wait on every channel listening to the frames on air - when that time increaseed number of AP will increased in the scan results - min time is 10 ms and the max is 250 ms - */ - uint8 u8ProbesPerSlot; - /*!< Number of probe requests to be sent per channel scan slot. - */ - sint8 s8RssiThresh; - /*! < The RSSI threshold of the AP which will be connected to directly. - */ - -}tstrM2MScanOption; - -/*! -@struct \ - tstrM2MScanRegion - -@brief - Wi-Fi channel regulation region information. - -@sa - tenuM2mScanRegion -*/ -typedef struct { - uint16 u16ScanRegion; - /*|< Specifies the number of channels allowed in the region (e.g. North America = 11 ... etc.). - */ - uint8 __PAD16__[2]; - -}tstrM2MScanRegion; - -/*! -@struct \ - tstrM2MScan - -@brief - Wi-Fi Scan Request - -@sa - tenuM2mScanCh - tstrM2MScanOption -*/ -typedef struct { - uint8 u8ChNum; - /*!< The Wi-Fi RF Channel number - */ - uint8 __RSVD8__[1]; - /*!< Reserved for future use. - */ - uint16 u16PassiveScanTime; - /*!< Passive Scan Timeout in ms. The field is ignored for active scan. - */ -}tstrM2MScan; - -/*! -@struct \ - tstrCyptoResp - -@brief - crypto response -*/ -typedef struct { - sint8 s8Resp; - /***/ - uint8 __PAD24__[3]; - /* - */ -}tstrCyptoResp; - - -/*! -@struct \ - tstrM2mScanDone - -@brief - Wi-Fi Scan Result -*/ -typedef struct{ - uint8 u8NumofCh; - /*!< Number of found APs - */ - sint8 s8ScanState; - /*!< Scan status - */ - uint8 __PAD16__[2]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mScanDone; - - -/*! -@struct \ - tstrM2mReqScanResult - -@brief Scan Result Request - - The Wi-Fi Scan results list is stored in Firmware. The application can request a certain scan result by its index. -*/ -typedef struct { - uint8 u8Index; - /*!< Index of the desired scan result - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mReqScanResult; - - -/*! -@struct \ - tstrM2mWifiscanResult - -@brief Wi-Fi Scan Result - - Information corresponding to an AP in the Scan Result list identified by its order (index) in the list. -*/ -typedef struct { - uint8 u8index; - /*!< AP index in the scan result list. - */ - sint8 s8rssi; - /*!< AP signal strength. - */ - uint8 u8AuthType; - /*!< AP authentication type. - */ - uint8 u8ch; - /*!< AP RF channel. - */ - uint8 au8BSSID[6]; - /*!< BSSID of the AP. - */ - uint8 au8SSID[M2M_MAX_SSID_LEN]; - /*!< AP ssid. - */ - uint8 _PAD8_; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mWifiscanResult; - - -/*! -@struct \ - tstrM2mWifiStateChanged - -@brief - Wi-Fi Connection State - -@sa - M2M_WIFI_DISCONNECTED, M2M_WIFI_CONNECTED, M2M_WIFI_REQ_CON_STATE_CHANGED,tenuM2mConnChangedErrcode -*/ -typedef struct { - uint8 u8CurrState; - /*!< Current Wi-Fi connection state - */ - uint8 u8ErrCode; - /*!< Error type review tenuM2mConnChangedErrcode - */ - uint8 __PAD16__[2]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mWifiStateChanged; - - -/*! -@struct \ - tstrM2mPsType - -@brief - Power Save Configuration - -@sa - tenuPowerSaveModes -*/ -typedef struct{ - uint8 u8PsType; - /*!< Power save operating mode - */ - uint8 u8BcastEn; - /*!< - */ - uint8 __PAD16__[2]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mPsType; - -/*! -@struct \ - tstrM2mSlpReqTime - -@brief - Manual power save request sleep time - -*/ -typedef struct { - /*!< Sleep time in ms - */ - uint32 u32SleepTime; - -} tstrM2mSlpReqTime; - -/*! -@struct \ - tstrM2mLsnInt - -@brief Listen interval - - It is the value of the Wi-Fi STA listen interval for power saving. It is given in units of Beacon period. - Periodically after the listen interval fires, the WINC is wakeup and listen to the beacon and check for any buffered frames for it from the AP. -*/ -typedef struct { - uint16 u16LsnInt; - /*!< Listen interval in Beacon period count. - */ - uint8 __PAD16__[2]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mLsnInt; - - -/*! -@struct \ - tstrM2MWifiMonitorModeCtrl - -@brief Wi-Fi Monitor Mode Filter - - This structure sets the filtering criteria for WLAN packets when monitoring mode is enable. - The received packets matching the filtering parameters, are passed directly to the application. -*/ -typedef struct{ - uint8 u8ChannelID; - /* !< RF Channel ID. It must use values from tenuM2mScanCh - */ - uint8 u8FrameType; - /*!< It must use values from tenuWifiFrameType. - */ - uint8 u8FrameSubtype; - /*!< It must use values from tenuSubTypes. - */ - uint8 au8SrcMacAddress[6]; - /* ZERO means DO NOT FILTER Source address. - */ - uint8 au8DstMacAddress[6]; - /* ZERO means DO NOT FILTER Destination address. - */ - uint8 au8BSSID[6]; - /* ZERO means DO NOT FILTER BSSID. - */ - uint8 u8EnRecvHdr; - /* - Enable recv the full hder before the payload - */ - uint8 __PAD16__[2]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2MWifiMonitorModeCtrl; - - -/*! -@struct \ - tstrM2MWifiRxPacketInfo - -@brief Wi-Fi RX Frame Header - - The M2M application has the ability to allow Wi-Fi monitoring mode for receiving all Wi-Fi Raw frames matching a well defined filtering criteria. - When a target Wi-Fi packet is received, the header information are extracted and assigned in this structure. -*/ -typedef struct{ - uint8 u8FrameType; - /*!< It must use values from tenuWifiFrameType. - */ - uint8 u8FrameSubtype; - /*!< It must use values from tenuSubTypes. - */ - uint8 u8ServiceClass; - /*!< Service class from Wi-Fi header. - */ - uint8 u8Priority; - /*!< Priority from Wi-Fi header. - */ - uint8 u8HeaderLength; - /*!< Frame Header length. - */ - uint8 u8CipherType; - /*!< Encryption type for the rx packet. - */ - uint8 au8SrcMacAddress[6]; - /* ZERO means DO NOT FILTER Source address. - */ - uint8 au8DstMacAddress[6]; - /* ZERO means DO NOT FILTER Destination address. - */ - uint8 au8BSSID[6]; - /* ZERO means DO NOT FILTER BSSID. - */ - uint16 u16DataLength; - /*!< Data payload length (Header excluded). - */ - uint16 u16FrameLength; - /*!< Total frame length (Header + Data). - */ - uint32 u32DataRateKbps; - /*!< Data Rate in Kbps. - */ - sint8 s8RSSI; - /*!< RSSI. - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2MWifiRxPacketInfo; - - -/*! -@struct \ - tstrM2MWifiTxPacketInfo - -@brief Wi-Fi TX Packet Info - - The M2M Application has the ability to compose a RAW Wi-Fi frames (under the application responsibility). - When transmitting a Wi-Fi packet, the application must supply the firmware with this structure for sending the target frame. -*/ -typedef struct{ - uint16 u16PacketSize; - /*!< Wlan frame length. - */ - uint16 u16HeaderLength; - /*!< Wlan frame header length. - */ -}tstrM2MWifiTxPacketInfo; - - -/*! - @struct \ - tstrM2MP2PConnect - - @brief - Set the device to operate in the Wi-Fi Direct (P2P) mode. -*/ -typedef struct { - uint8 u8ListenChannel; - /*!< P2P Listen Channel (1, 6 or 11) - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2MP2PConnect; - -/*! -@struct \ - tstrM2MAPConfig - -@brief AP Configuration - - This structure holds the configuration parameters for the M2M AP mode. It should be set by the application when - it requests to enable the M2M AP operation mode. The M2M AP mode currently supports only WEP security (with - the NO Security option available of course). -*/ -typedef struct { - /*!< - Configuration parameters for the WiFi AP. - */ - uint8 au8SSID[M2M_MAX_SSID_LEN]; - /*!< AP SSID - */ - uint8 u8ListenChannel; - /*!< Wi-Fi RF Channel which the AP will operate on - */ - uint8 u8KeyIndx; - /*!< Wep key Index - */ - uint8 u8KeySz; - /*!< Wep/WPA key Size - */ - uint8 au8WepKey[WEP_104_KEY_STRING_SIZE + 1]; - /*!< Wep key - */ - uint8 u8SecType; - /*!< Security type: Open or WEP or WPA in the current implementation - */ - uint8 u8SsidHide; - /*!< SSID Status "Hidden(1)/Visible(0)" - */ - uint8 au8DHCPServerIP[4]; - /*!< Ap IP server address - */ - uint8 au8Key[M2M_MAX_PSK_LEN]; - /*!< WPA key - */ - uint8 __PAD24__[2]; - /*!< Padding bytes for forcing alignment - */ -}tstrM2MAPConfig; - - -/*! -@struct \ - tstrM2mServerInit - -@brief - PS Server initialization. -*/ -typedef struct { - uint8 u8Channel; - /*!< Server Listen channel - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mServerInit; - - -/*! -@struct \ - tstrM2mClientState - -@brief - PS Client State. -*/ -typedef struct { - uint8 u8State; - /*!< PS Client State - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mClientState; - - -/*! -@struct \ - tstrM2Mservercmd - -@brief - PS Server CMD -*/ -typedef struct { - uint8 u8cmd; - /*!< PS Server Cmd - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2Mservercmd; - - -/*! -@struct \ - tstrM2mSetMacAddress - -@brief - Sets the MAC address from application. The WINC load the mac address from the effuse by default to the WINC configuration memory, - but that function is used to let the application overwrite the configuration memory with the mac address from the host. - -@note - It's recommended to call this only once before calling connect request and after the m2m_wifi_init -*/ -typedef struct { - uint8 au8Mac[6]; - /*!< MAC address array - */ - uint8 __PAD16__[2]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mSetMacAddress; - - -/*! -@struct \ - tstrM2MDeviceNameConfig - -@brief Device name - - It is assigned by the application. It is used mainly for Wi-Fi Direct device - discovery and WPS device information. -*/ -typedef struct { - uint8 au8DeviceName[M2M_DEVICE_NAME_MAX]; - /*!< NULL terminated device name - */ -}tstrM2MDeviceNameConfig; - - -/*! -@struct \ - tstrM2MIPConfig - -@brief - Static IP configuration. - -@note - All member IP addresses are expressed in Network Byte Order (eg. "192.168.10.1" will be expressed as 0x010AA8C0). - */ -typedef struct { - uint32 u32StaticIP; - /*!< The static IP assigned to the device. - */ - uint32 u32Gateway; - /*!< IP of the Default internet gateway. - */ - uint32 u32DNS; - /*!< IP for the DNS server. - */ - uint32 u32SubnetMask; - /*!< Subnet mask for the local area network. - */ - uint32 u32DhcpLeaseTime; - /*!< Dhcp Lease Time in sec - */ -} tstrM2MIPConfig; - -/*! -@struct \ - tstrM2mIpRsvdPkt - -@brief - Received Packet Size and Data Offset - - */ -typedef struct{ - uint16 u16PktSz; - uint16 u16PktOffset; -} tstrM2mIpRsvdPkt; - - -/*! -@struct \ - tstrM2MProvisionModeConfig - -@brief - M2M Provisioning Mode Configuration - */ - -typedef struct { - tstrM2MAPConfig strApConfig; - /*!< - Configuration parameters for the WiFi AP. - */ - char acHttpServerDomainName[64]; - /*!< - The device domain name for HTTP provisioning. - */ - uint8 u8EnableRedirect; - /*!< - A flag to enable/disable HTTP redirect feature for the HTTP Provisioning server. If the Redirect is enabled, - all HTTP traffic (http://URL) from the device associated with WINC AP will be redirected to the HTTP Provisioning Web page. - - 0 : Disable HTTP Redirect. - - 1 : Enable HTTP Redirect. - */ - uint8 __PAD24__[3]; -}tstrM2MProvisionModeConfig; - - -/*! -@struct \ - tstrM2MProvisionInfo - -@brief - M2M Provisioning Information obtained from the HTTP Provisioning server. - */ -typedef struct{ - uint8 au8SSID[M2M_MAX_SSID_LEN]; - /*!< - Provisioned SSID. - */ - uint8 au8Password[M2M_MAX_PSK_LEN]; - /*!< - Provisioned Password. - */ - uint8 u8SecType; - /*!< - Wifi Security type. - */ - uint8 u8Status; - /*!< - Provisioning status. It must be checked before reading the provisioning information. It may be - - M2M_SUCCESS : Provision successful. - - M2M_FAIL : Provision Failed. - */ -}tstrM2MProvisionInfo; - - -/*! -@struct \ - tstrM2MConnInfo - -@brief - M2M Provisioning Information obtained from the HTTP Provisioning server. - */ -typedef struct{ - char acSSID[M2M_MAX_SSID_LEN]; - /*!< AP connection SSID name */ - uint8 u8SecType; - /*!< Security type */ - uint8 au8IPAddr[4]; - /*!< Connection IP address */ - uint8 au8MACAddress[6]; - /*!< MAC address of the peer Wi-Fi station */ - sint8 s8RSSI; - /*!< Connection RSSI signal */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment */ -}tstrM2MConnInfo; - -/*! -@struct \ - tstrOtaInitHdr - -@brief - OTA Image Header - */ - -typedef struct{ - uint32 u32OtaMagicValue; - /*!< Magic value kept in the OTA image after the - sha256 Digest buffer to define the Start of OTA Header */ - uint32 u32OtaPayloadSzie; - /*!< - The Total OTA image payload size, include the sha256 key size - */ - -}tstrOtaInitHdr; - - -/*! -@struct \ - tstrOtaControlSec - -@brief - Control section structure is used to define the working image and - the validity of the roll-back image and its offset, also both firmware versions is kept in that structure. - */ - -typedef struct { - uint32 u32OtaMagicValue; -/*!< - Magic value used to ensure the structure is valid or not -*/ - uint32 u32OtaFormatVersion; -/*!< - NA NA NA Flash version cs struct version - 00 00 00 00 00 - Control structure format version, the value will be incremented in case of structure changed or updated -*/ - uint32 u32OtaSequenceNumber; -/*!< - Sequence number is used while update the control structure to keep track of how many times that section updated -*/ - uint32 u32OtaLastCheckTime; -/*!< - Last time OTA check for update -*/ - uint32 u32OtaCurrentworkingImagOffset; -/*!< - Current working offset in flash -*/ - uint32 u32OtaCurrentworkingImagFirmwareVer; -/*!< - current working image version ex 18.0.1 -*/ - uint32 u32OtaRollbackImageOffset; -/*!< - Roll-back image offset in flash -*/ - uint32 u32OtaRollbackImageValidStatus; -/*!< - roll-back image valid status -*/ - uint32 u32OtaRollbackImagFirmwareVer; -/*!< - Roll-back image version (ex 18.0.3) -*/ - uint32 u32OtaCortusAppWorkingOffset; -/*!< - cortus app working offset in flash -*/ - uint32 u32OtaCortusAppWorkingValidSts; -/*!< - Working Cortus app valid status -*/ - uint32 u32OtaCortusAppWorkingVer; -/*!< - Working cortus app version (ex 18.0.3) -*/ - uint32 u32OtaCortusAppRollbackOffset; -/*!< - cortus app rollback offset in flash -*/ - uint32 u32OtaCortusAppRollbackValidSts; -/*!< - roll-back cortus app valid status -*/ - uint32 u32OtaCortusAppRollbackVer; -/*!< - Roll-back cortus app version (ex 18.0.3) -*/ - uint32 u32OtaControlSecCrc; -/*!< - CRC for the control structure to ensure validity -*/ -} tstrOtaControlSec; - -/*! -@enum \ - tenuOtaUpdateStatus - -@brief - OTA return status -*/ -typedef enum { - OTA_STATUS_SUCSESS = 0, - /*!< OTA Success with not errors. */ - OTA_STATUS_FAIL = 1, - /*!< OTA generic fail. */ - OTA_STATUS_INVAILD_ARG = 2, - /*!< Invalid or malformed download URL. */ - OTA_STATUS_INVAILD_RB_IMAGE = 3, - /*!< Invalid rollback image. */ - OTA_STATUS_INVAILD_FLASH_SIZE = 4, - /*!< Flash size on device is not enough for OTA. */ - OTA_STATUS_AlREADY_ENABLED = 5, - /*!< An OTA operation is already enabled. */ - OTA_STATUS_UPDATE_INPROGRESS = 6, - /*!< An OTA operation update is in progress */ - OTA_STATUS_IMAGE_VERIF_FAILED = 7, - /*!< OTA Verfication failed */ - OTA_STATUS_CONNECTION_ERROR = 8, - /*!< OTA connection error */ - OTA_STATUS_SERVER_ERROR = 9, - /*!< OTA server Error (file not found or else ...) */ - OTA_STATUS_ABORTED = 10 - /*!< OTA download has been aborted by the application. */ -} tenuOtaUpdateStatus; -/*! -@enum \ - tenuOtaUpdateStatusType - -@brief - OTA update Status type -*/ -typedef enum { - - DL_STATUS = 1, - /*!< Download OTA file status - */ - SW_STATUS = 2, - /*!< Switching to the upgrade firmware status - */ - RB_STATUS = 3, - /*!< Roll-back status - */ - AB_STATUS = 4 - /*!< Abort status - */ -}tenuOtaUpdateStatusType; - - -/*! -@struct \ - tstrOtaUpdateStatusResp - -@brief - OTA Update Information - -@sa - tenuWPSTrigger -*/ -typedef struct { - uint8 u8OtaUpdateStatusType; - /*!< - Status type tenuOtaUpdateStatusType - */ - uint8 u8OtaUpdateStatus; - /*!< - OTA_SUCCESS - OTA_ERR_WORKING_IMAGE_LOAD_FAIL - OTA_ERR_INVAILD_CONTROL_SEC - M2M_ERR_OTA_SWITCH_FAIL - M2M_ERR_OTA_START_UPDATE_FAIL - M2M_ERR_OTA_ROLLBACK_FAIL - M2M_ERR_OTA_INVAILD_FLASH_SIZE - M2M_ERR_OTA_INVAILD_ARG - */ - uint8 _PAD16_[2]; -}tstrOtaUpdateStatusResp; - -/*! -@struct \ - tstrOtaUpdateInfo - -@brief - OTA Update Information - -@sa - tenuWPSTrigger -*/ -typedef struct { - uint32 u8NcfUpgradeVersion; - /*!< NCF OTA Upgrade Version - */ - uint32 u8NcfCurrentVersion; - /*!< NCF OTA Current firmware version - */ - uint32 u8NcdUpgradeVersion; - /*!< NCD (host) upgraded version (if the u8NcdRequiredUpgrade == true) - */ - uint8 u8NcdRequiredUpgrade; - /*!< NCD Required upgrade to the above version - */ - uint8 u8DownloadUrlOffset; - /*!< Download URL offset in the received packet - */ - uint8 u8DownloadUrlSize; - /*!< Download URL size in the received packet - */ - uint8 __PAD8__; - /*!< Padding bytes for forcing 4-byte alignment - */ -} tstrOtaUpdateInfo; - -/*! -@struct \ - tstrSystemTime - -@brief - Used for time storage. -*/ -typedef struct{ - uint16 u16Year; - uint8 u8Month; - uint8 u8Day; - uint8 u8Hour; - uint8 u8Minute; - uint8 u8Second; - uint8 __PAD8__; -}tstrSystemTime; - -/*! -@struct \ - tstrM2MMulticastMac - -@brief - M2M add/remove multi-cast mac address - */ - typedef struct { - uint8 au8macaddress[M2M_MAC_ADDRES_LEN]; - /*!< - Mac address needed to be added or removed from filter. - */ - uint8 u8AddRemove; - /*!< - set by 1 to add or 0 to remove from filter. - */ - uint8 __PAD8__; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2MMulticastMac; - -/*! -@struct \ - tstrPrng - -@brief - M2M Request PRNG - */ - typedef struct { - /*!< - return buffer address - */ - uint8 *pu8RngBuff; - /*!< - PRNG size requested - */ - uint16 u16PrngSize; - /*!< - PRNG pads - */ - uint8 __PAD16__[2]; -}tstrPrng; - -/* - * TLS certificate revocation list - * Typedefs common between fw and host - */ - -/*! -@struct \ - tstrTlsCrlEntry - -@brief - Certificate data for inclusion in a revocation list (CRL) -*/ -typedef struct { - uint8 u8DataLen; - /*!< - Length of certificate data (maximum possible is @ref TLS_CRL_DATA_MAX_LEN) - */ - uint8 au8Data[TLS_CRL_DATA_MAX_LEN]; - /*!< - Certificate data - */ - uint8 __PAD24__[3]; - /*!< - Padding bytes for forcing 4-byte alignment - */ -}tstrTlsCrlEntry; - -/*! -@struct \ - tstrTlsCrlInfo - -@brief - Certificate revocation list details -*/ -typedef struct { - uint8 u8CrlType; - /*!< - Type of certificate data contained in list - */ - uint8 u8Rsv1; - /*!< - Reserved for future use - */ - uint8 u8Rsv2; - /*!< - Reserved for future use - */ - uint8 u8Rsv3; - /*!< - Reserved for future use - */ - tstrTlsCrlEntry astrTlsCrl[TLS_CRL_MAX_ENTRIES]; - /*!< - List entries - */ -}tstrTlsCrlInfo; - - /*! -@enum\ - tenuSslCertExpSettings - -@brief SSL Certificate Expiry Validation Options -*/ -typedef enum{ - SSL_CERT_EXP_CHECK_DISABLE, - /*!< - ALWAYS OFF. - Ignore certificate expiration date validation. If a certificate is - expired or there is no configured system time, the SSL connection SUCCEEDs. - */ - SSL_CERT_EXP_CHECK_ENABLE, - /*!< - ALWAYS ON. - Validate certificate expiration date. If a certificate is expired or - there is no configured system time, the SSL connection FAILs. - */ - SSL_CERT_EXP_CHECK_EN_IF_SYS_TIME - /*!< - CONDITIONAL VALIDATION (Default setting at startup). - Validate the certificate expiration date only if there is a configured system time. - If there is no configured system time, the certificate expiration is bypassed and the - SSL connection SUCCEEDs. - */ -}tenuSslCertExpSettings; - - -/*! -@struct \ - tstrTlsSrvSecFileEntry - -@brief - This struct contains a TLS certificate. - */ -typedef struct{ - char acFileName[TLS_FILE_NAME_MAX]; - /*!< Name of the certificate. */ - uint32 u32FileSize; - /*!< Size of the certificate. */ - uint32 u32FileAddr; - /*!< Error Code. */ -}tstrTlsSrvSecFileEntry; - -/*! -@struct \ - tstrTlsSrvSecHdr - -@brief - This struct contains a set of TLS certificates. - */ -typedef struct{ - uint8 au8SecStartPattern[TLS_SRV_SEC_START_PATTERN_LEN]; - /*!< Start pattern. */ - uint32 u32nEntries; - /*!< Number of certificates stored in the struct. */ - uint32 u32NextWriteAddr; - /*!< TLS Certificates. */ - tstrTlsSrvSecFileEntry astrEntries[TLS_SRV_SEC_MAX_FILES]; -}tstrTlsSrvSecHdr; - -typedef struct{ - uint32 u32CsBMP; -}tstrSslSetActiveCsList; - - - /**@}*/ - -#endif diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_wifi.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_wifi.h deleted file mode 100644 index 3477196..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/include/m2m_wifi.h +++ /dev/null @@ -1,2882 +0,0 @@ -/** - * - * \file - * - * \brief WINC WLAN Application Interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef __M2M_WIFI_H__ -#define __M2M_WIFI_H__ - -/** \defgroup m2m_wifi WLAN - * - */ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "common/include/nm_common.h" -#include "driver/include/m2m_types.h" -#include "driver/source/nmdrv.h" - -#ifdef CONF_MGMT - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/**@defgroup WlanEnums DataTypes - * @ingroup m2m_wifi - * @{*/ -/*! -@enum \ - tenuWifiFrameType - -@brief - Enumeration for Wi-Fi MAC frame type codes (2-bit) - The following types are used to identify the type of frame sent or received. - Each frame type constitutes a number of frame subtypes as defined in @ref tenuSubTypes to specify the exact type of frame. - Values are defined as per the IEEE 802.11 standard. - -@remarks - The following frame types are useful for advanced user usage when monitoring mode is used (defining @ref CONF_MGMT) - and the user application requires to monitor the frame transmission and reception. -@see - tenuSubTypes -*/ -typedef enum { - MANAGEMENT = 0x00, - /*!< Wi-Fi Management frame (Probe Req/Resp, Beacon, Association Req/Resp ...etc). - */ - CONTROL = 0x04, - /*!< Wi-Fi Control frame (eg. ACK frame). - */ - DATA_BASICTYPE = 0x08, - /*!< Wi-Fi Data frame. - */ - RESERVED = 0x0C, - - M2M_WIFI_FRAME_TYPE_ANY = 0xFF -/*!< Set monitor mode to receive any of the frames types -*/ -}tenuWifiFrameType; - - -/*! -@enum \ - tenuSubTypes - -@brief - Enumeration for Wi-Fi MAC Frame subtype code (6-bit). - The frame subtypes fall into one of the three frame type groups as defined in @ref tenuWifiFrameType - (MANAGEMENT, CONTROL & DATA). - Values are defined as per the IEEE 802.11 standard. -@remarks - The following sub-frame types are useful for advanced user usage when @ref CONF_MGMT is defined - and the application developer requires to monitor the frame transmission and reception. -@see - tenuWifiFrameType - tstrM2MWifiMonitorModeCtrl -*/ -typedef enum { - /*!< Sub-Types related to Management Sub-Types */ - ASSOC_REQ = 0x00, - ASSOC_RSP = 0x10, - REASSOC_REQ = 0x20, - REASSOC_RSP = 0x30, - PROBE_REQ = 0x40, - PROBE_RSP = 0x50, - BEACON = 0x80, - ATIM = 0x90, - DISASOC = 0xA0, - AUTH = 0xB0, - DEAUTH = 0xC0, - ACTION = 0xD0, -/**@{*/ - /* Sub-Types related to Control */ - PS_POLL = 0xA4, - RTS = 0xB4, - CTS = 0xC4, - ACK = 0xD4, - CFEND = 0xE4, - CFEND_ACK = 0xF4, - BLOCKACK_REQ = 0x84, - BLOCKACK = 0x94, -/**@{*/ - /* Sub-Types related to Data */ - DATA = 0x08, - DATA_ACK = 0x18, - DATA_POLL = 0x28, - DATA_POLL_ACK = 0x38, - NULL_FRAME = 0x48, - CFACK = 0x58, - CFPOLL = 0x68, - CFPOLL_ACK = 0x78, - QOS_DATA = 0x88, - QOS_DATA_ACK = 0x98, - QOS_DATA_POLL = 0xA8, - QOS_DATA_POLL_ACK = 0xB8, - QOS_NULL_FRAME = 0xC8, - QOS_CFPOLL = 0xE8, - QOS_CFPOLL_ACK = 0xF8, - M2M_WIFI_FRAME_SUB_TYPE_ANY = 0xFF - /*!< Set monitor mode to receive any of the frames types - */ -}tenuSubTypes; - - -/*! -@enum \ - tenuInfoElementId - -@brief - Enumeration for the Wi-Fi Information Element(IE) IDs, which indicates the specific type of IEs. - IEs are management frame information included in management frames. - Values are defined as per the IEEE 802.11 standard. - -*/ -typedef enum { - ISSID = 0, - /*!< Service Set Identifier (SSID) - */ - ISUPRATES = 1, - /*!< Supported Rates - */ - IFHPARMS = 2, - /*!< FH parameter set - */ - IDSPARMS = 3, - /*!< DS parameter set - */ - ICFPARMS = 4, - /*!< CF parameter set - */ - ITIM = 5, - /*!< Traffic Information Map - */ - IIBPARMS = 6, - /*!< IBSS parameter set - */ - ICOUNTRY = 7, - /*!< Country element. - */ - IEDCAPARAMS = 12, - /*!< EDCA parameter set - */ - ITSPEC = 13, - /*!< Traffic Specification - */ - ITCLAS = 14, - /*!< Traffic Classification - */ - ISCHED = 15, - /*!< Schedule. - */ - ICTEXT = 16, - /*!< Challenge Text - */ - IPOWERCONSTRAINT = 32, - /*!< Power Constraint. - */ - IPOWERCAPABILITY = 33, - /*!< Power Capability - */ - ITPCREQUEST = 34, - /*!< TPC Request - */ - ITPCREPORT = 35, - /*!< TPC Report - */ - ISUPCHANNEL = 36, - /* Supported channel list - */ - ICHSWANNOUNC = 37, - /*!< Channel Switch Announcement - */ - IMEASUREMENTREQUEST = 38, - /*!< Measurement request - */ - IMEASUREMENTREPORT = 39, - /*!< Measurement report - */ - IQUIET = 40, - /*!< Quiet element Info - */ - IIBSSDFS = 41, - /*!< IBSS DFS - */ - IERPINFO = 42, - /*!< ERP Information - */ - ITSDELAY = 43, - /*!< TS Delay - */ - ITCLASPROCESS = 44, - /*!< TCLAS Processing - */ - IHTCAP = 45, - /*!< HT Capabilities - */ - IQOSCAP = 46, - /*!< QoS Capability - */ - IRSNELEMENT = 48, - /*!< RSN Information Element - */ - IEXSUPRATES = 50, - /*!< Extended Supported Rates - */ - IEXCHSWANNOUNC = 60, - /*!< Extended Ch Switch Announcement - */ - IHTOPERATION = 61, - /*!< HT Information - */ - ISECCHOFF = 62, - /*!< Secondary Channel Offset - */ - I2040COEX = 72, - /*!< 20/40 Coexistence IE - */ - I2040INTOLCHREPORT = 73, - /*!< 20/40 Intolerant channel report - */ - IOBSSSCAN = 74, - /*!< OBSS Scan parameters - */ - IEXTCAP = 127, - /*!< Extended capability - */ - IWMM = 221, - /*!< WMM parameters - */ - IWPAELEMENT = 221 - /*!< WPA Information Element - */ -}tenuInfoElementId; - - -/*! -@struct \ - tenuWifiCapability - -@brief - Enumeration for capability Information field bit. - The value of the capability information field from the 802.11 management frames received by the wireless LAN interface. - Defining the capabilities of the Wi-Fi system. Values are defined as per the IEEE 802.11 standard. - -@details - Capabilities:- - ESS/IBSS : Defines whether a frame is coming from an AP or not. - POLLABLE : CF Poll-able - POLLREQ : Request to be polled - PRIVACY : WEP encryption supported - SHORTPREAMBLE : Short Preamble is supported - SHORTSLOT : Short Slot is supported - PBCC :PBCC - CHANNELAGILITY :Channel Agility - SPECTRUM_MGMT :Spectrum Management - DSSS_OFDM : DSSS-OFDM -*/ -typedef enum{ - ESS = 0x01, - /*!< ESS capability - */ - IBSS = 0x02, - /*!< IBSS mode - */ - POLLABLE = 0x04, - /*!< CF Pollable - */ - POLLREQ = 0x08, - /*!< Request to be polled - */ - PRIVACY = 0x10, - /*!< WEP encryption supported - */ - SHORTPREAMBLE = 0x20, - /*!< Short Preamble is supported - */ - SHORTSLOT = 0x400, - /*!< Short Slot is supported - */ - PBCC = 0x40, - /*!< PBCC - */ - CHANNELAGILITY = 0x80, - /*!< Channel Agility - */ - SPECTRUM_MGMT = 0x100, - /*!< Spectrum Management - */ - DSSS_OFDM = 0x2000 - /*!< DSSS-OFDM - */ -}tenuWifiCapability; - - -#endif - -/*! -@typedef \ - tpfAppWifiCb - -@brief - Wi-Fi's main callback function handler, for handling the M2M_WIFI events received on the Wi-Fi interface. - Such notifications are received in response to Wi-Fi/P2P operations such as @ref m2m_wifi_request_scan, - @ref m2m_wifi_connect. - Wi-Fi/P2P operations are implemented in an asynchronous mode, and all incoming information/status - are to be handled through this callback function when the corresponding notification is received. - Applications are expected to assign this wi-fi callback function by calling @ref m2m_wifi_init -@param [in] u8MsgType - Type of notifications. Possible types are: - /ref M2M_WIFI_RESP_CON_STATE_CHANGED - /ref M2M_WIFI_RESP_CONN_INFO - /ref M2M_WIFI_REQ_DHCP_CONF - /ref M2M_WIFI_REQ_WPS - /ref M2M_WIFI_RESP_IP_CONFLICT - /ref M2M_WIFI_RESP_SCAN_DONE - /ref M2M_WIFI_RESP_SCAN_RESULT - /ref M2M_WIFI_RESP_CURRENT_RSSI - /ref M2M_WIFI_RESP_CLIENT_INFO - /ref M2M_WIFI_RESP_PROVISION_INFO - /ref M2M_WIFI_RESP_DEFAULT_CONNECT - - In case Ethernet/Bypass mode is defined : - @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET - - In case monitoring mode is used: - @ref M2M_WIFI_RESP_WIFI_RX_PACKET - -@param [in] pvMsg - A pointer to a buffer containing the notification parameters (if any). It should be - casted to the correct data type corresponding to the notification type. - -@see - tstrM2mWifiStateChanged - tstrM2MWPSInfo - tstrM2mScanDone - tstrM2mWifiscanResult -*/ -typedef void (*tpfAppWifiCb) (uint8 u8MsgType, void * pvMsg); - -/*! -@typedef \ - tpfAppEthCb - -@brief - ETHERNET (bypass mode) notification callback function receiving Bypass mode events as defined in - the Wi-Fi responses enumeration @ref tenuM2mStaCmd. - -@param [in] u8MsgType - Type of notification. Possible types are: - - [M2M_WIFI_RESP_ETHERNET_RX_PACKET](@ref M2M_WIFI_RESP_ETHERNET_RX_PACKET) - -@param [in] pvMsg - A pointer to a buffer containing the notification parameters (if any). It should be - casted to the correct data type corresponding to the notification type. - For example, it could be a pointer to the buffer holding the received frame in case of @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET - event. - -@param [in] pvControlBuf - A pointer to control buffer describing the accompanied message. - To be casted to @ref tstrM2mIpCtrlBuf in case of @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET event. - -@warning - Make sure that the application defines @ref ETH_MODE. - -@see - m2m_wifi_init - -*/ -typedef void (*tpfAppEthCb) (uint8 u8MsgType, void * pvMsg,void * pvCtrlBuf); - -/*! -@typedef \ - tpfAppMonCb - -@brief - Wi-Fi monitoring mode callback function. This function delivers all received wi-Fi packets through the Wi-Fi interface. - Applications requiring to operate in the monitoring should call the asynchronous function m2m_wifi_enable_monitoring_mode - and expect to receive the Wi-Fi packets through this callback function, when the event is received. - To disable the monitoring mode a call to @ref m2m_wifi_disable_monitoring_mode should be made. -@param [in] pstrWifiRxPacket - Pointer to a structure holding the Wi-Fi packet header parameters. - -@param [in] pu8Payload - Pointer to the buffer holding the Wi-Fi packet payload information required by the application starting from the - defined OFFSET by the application (when calling m2m_wifi_enable_monitoring_mode). - Could hold a value of NULL, if the application does not need any data from the payload. - -@param [in] u16PayloadSize - The size of the payload in bytes. - -@see - m2m_wifi_enable_monitoring_mode,m2m_wifi_init - -@warning - u16PayloadSize should not exceed the buffer size given through m2m_wifi_enable_monitoring_mode. - -*/ -typedef void (*tpfAppMonCb) (tstrM2MWifiRxPacketInfo *pstrWifiRxPacket, uint8 * pu8Payload, uint16 u16PayloadSize); - -/** -@struct \ - tstrEthInitParam - -@brief - Structure to hold Ethernet interface parameters. - Structure is to be defined and have its attributes set,based on the application's functionality before - a call is made to initialize the Wi-Fi operations by calling the @ref m2m_wifi_init function. - This structure is part of the Wi-Fi configuration structure @ref tstrWifiInitParam. - Applications shouldn't need to define this structure, if the bypass mode is not defined. - -@see - tpfAppEthCb - tpfAppWifiCb - m2m_wifi_init - -@warning - Make sure that application defines @ref ETH_MODE before using @ref tstrEthInitParam. - -*/ -typedef struct { - tpfAppWifiCb pfAppWifiCb; - /*!< - Callback for wifi notifications. - */ - tpfAppEthCb pfAppEthCb; - /*!< - Callback for Ethernet interface. - */ - uint8 * au8ethRcvBuf; - /*!< - Pointer to Receive Buffer of Ethernet Packet - */ - uint16 u16ethRcvBufSize; - /*!< - Size of Receive Buffer for Ethernet Packet - */ - uint8 u8EthernetEnable; - /*!< - Enable Ethernet mode flag - */ - uint8 __PAD8__; - /*!< - Padding - */ -} tstrEthInitParam; -/*! -@struct \ - tstrM2mIpCtrlBuf - -@brief - Structure holding the incoming buffer's data size information, indicating the data size of the buffer and the remaining buffer's data size . - The data of the buffer which holds the packet sent to the host when in the bypass mode, is placed in the @ref tstrEthInitParam structure in the - @ref au8ethRcvBuf attribute. This following information is retrieved in the host when an event @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET is received in - the Wi-Fi callback function @ref tpfAppWifiCb. - - The application is expected to use this structure's information to determine if there is still incoming data to be received from the firmware. - - @see - tpfAppEthCb - tstrEthInitParam - - @warning - Make sure that ETHERNET/bypass mode is defined before using @ref tstrM2mIpCtrlBuf - - */ -typedef struct{ - uint16 u16DataSize; - /*!< - Size of the received data in bytes. - */ - uint16 u16RemainigDataSize; - /*!< - Size of the remaining data bytes to be delivered to host. - */ -} tstrM2mIpCtrlBuf; - - -/** -@struct \ - tstrWifiInitParam - -@brief - Structure, holding the Wi-fi configuration attributes such as the wi-fi callback , monitoring mode callback and Ethernet parameter initialization structure. - Such configuration parameters are required to be set before calling the wi-fi initialization function @ref m2m_wifi_init. - @ref pfAppWifiCb attribute must be set to handle the wi-fi callback operations. - @ref pfAppMonCb attribute, is optional based on whether the application requires the monitoring mode configuration, and can there not - be set before the initialization. - @ref strEthInitParam structure, is another optional configuration based on whether the bypass mode is set. - - @see - tpfAppEthCb - tpfAppMonCb - tstrEthInitParam - -*/ -typedef struct { - tpfAppWifiCb pfAppWifiCb; - /*!< - Callback for Wi-Fi notifications. - */ - tpfAppMonCb pfAppMonCb; - /*!< - Callback for monitoring interface. - */ - tstrEthInitParam strEthInitParam ; - /*!< - Structure to hold Ethernet interface parameters. - */ - -} tstrWifiInitParam; - //@} -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/** \defgroup WLANAPI Function - * @ingroup m2m_wifi - */ -#ifdef __cplusplus - extern "C" { -#endif - /** @defgroup WiFiDownloadFn m2m_wifi_download_mode - * @ingroup WLANAPI - * Synchronous download mode entry function that prepares the WINC board to enter the download mode, ready for the firmware or certificate download. -* The WINC board is prepared for download, through initializations for the WINC driver including bus initializations and interrupt enabling, it also halts the chip, to allow for the firmware downloads. -* Firmware can be downloaded through a number of interfaces, UART, I2C and SPI. - */ - /**@{*/ -/*! -@fn \ - NMI_API void m2m_wifi_download_mode(void); -@brief Prepares the WINC broard before downloading any data (Firmware, Certificates .. etc) - - This function should called before starting to download any data to the WINC board. The WINC board is prepared for download, through initializations for the WINC driver including bus initializations - and interrupt enabling, it also halts the chip, to allow for the firmware downloads Firmware can be downloaded through a number of interfaces, UART, I2C and SPI. - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_download_mode(void); - - /**@}*/ - /** @defgroup WifiInitFn m2m_wifi_init - * @ingroup WLANAPI - * Synchronous initialization function for the WINC driver. This function initializes the driver by, registering the call back function for M2M_WIFI layer(also the call back function for bypass mode/monitoring mode if defined), - * initializing the host interface layer and the bus interfaces. - * Wi-Fi callback registering is essential to allow the handling of the events received, in response to the asynchronous Wi-Fi operations. - -Following are the possible Wi-Fi events that are expected to be received through the call back function(provided by the application) to the M2M_WIFI layer are : - - @ref M2M_WIFI_RESP_CON_STATE_CHANGED \n - @ref M2M_WIFI_RESP_CONN_INFO \n - @ref M2M_WIFI_REQ_DHCP_CONF \n - @ref M2M_WIFI_REQ_WPS \n - @ref M2M_WIFI_RESP_IP_CONFLICT \n - @ref M2M_WIFI_RESP_SCAN_DONE \n - @ref M2M_WIFI_RESP_SCAN_RESULT \n - @ref M2M_WIFI_RESP_CURRENT_RSSI \n - @ref M2M_WIFI_RESP_CLIENT_INFO \n - @ref M2M_WIFI_RESP_PROVISION_INFO \n - @ref M2M_WIFI_RESP_DEFAULT_CONNECT \n - Example: \n - In case Bypass mode is defined : \n - @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET - - In case Monitoring mode is used: \n - @ref M2M_WIFI_RESP_WIFI_RX_PACKET - - Any application using the WINC driver must call this function at the start of its main function. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_init(tstrWifiInitParam * pWifiInitParam); - -@param [in] pWifiInitParam - This is a pointer to the @ref tstrWifiInitParam structure which holds the pointer to the application WIFI layer call back function, - monitoring mode call back and @ref tstrEthInitParam structure containing bypass mode parameters. - -@brief Initialize the WINC host driver. - This function initializes the driver by, registering the call back function for M2M_WIFI layer(also the call back function for bypass mode/monitoring mode if defined), - initializing the host interface layer and the bus interfaces. - -@pre - Prior to this function call, The application should initialize the BSP using "nm_bsp_init". - Also,application users must provide a call back function responsible for receiving all the WI-FI events that are received on the M2M_WIFI layer. - -@warning - Failure to successfully complete function indicates that the driver couldn't be initialized and a fatal error will prevent the application from proceeding. - -@see - nm_bsp_init - m2m_wifi_deinit - tenuM2mStaCmd - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_init(tstrWifiInitParam * pWifiInitParam); - /**@}*/ - /** @defgroup WifiDeinitFn m2m_wifi_deinit - * @ingroup WLANAPI - * Synchronous de-initialization function to the WINC1500 driver. De-initializes the host interface and frees any resources used by the M2M_WIFI layer. - * This function must be called in the application closing phase to ensure that all resources have been correctly released. No arguments are expected to be passed in. - */ -/**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_deinit(void * arg); - -@param [in] arg - Generic argument. Not used in the current implementation. -@brief Deinitilize the WINC driver and host enterface. - This function must be called at the De-initilization stage of the application. Generally This function should be the last function before switching off the chip - and it should be followed only by "nm_bsp_deinit" function call. Every function call of "nm_wifi_init" should be matched with a call to nm_wifi_deinit. -@see - nm_bsp_deinit - nm_wifi_init - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_deinit(void * arg); - - /**@}*/ -/** @defgroup WifiHandleEventsFn m2m_wifi_handle_events -* @ingroup WLANAPI -* Synchronous M2M event handler function, responsible for handling interrupts received from the WINC firmware. -* Application developers should call this function periodically in-order to receive the events that are to be handled by the -* callback functions implemented by the application. - - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_handle_events(void * arg); - -@pre - Prior to receiving events, the WINC driver should have been successfully initialized by calling the @ref m2m_wifi_init function. - -@brief Handle the varios events received from the WINC board. - Whenever an event happen in the WINC board (e.g. Connection, Disconnection , DHCP .. etc), WINC will interrupt the host to let it know that a new - event has occured. The host driver will attempt to handle these events whenever the host driver decides to do that by calling the "m2m_wifi_handle_events" function. - It's mandatory to call this function periodically and independantly of any other condition. It's ideal to include this function in the main and the most frequent loop of the - host application. -@warning - Failure to successfully complete this function indicates bus errors and hence a fatal error that will prevent the application from proceeding. - -@return - The function returns @ref M2M_SUCCESS for successful interrupt handling and a negative value otherwise. -*/ - -NMI_API sint8 m2m_wifi_handle_events(void * arg); - - /**@}*/ -/** @defgroup WifiSendCRLFn m2m_wifi_send_crl -* @ingroup WLANAPI -* Asynchronous API that notifies the WINC with the Certificate Revocation List to be used for TLS. - - */ - /**@{*/ -/*! -@fn \ - sint8 m2m_wifi_send_crl(tstrTlsCrlInfo* pCRL); - -@brief - Asynchronous API that notifies the WINC with the Certificate Revocation List. - -@param [in] pCRL - Pointer to the structure containing certificate revocation list details. - -@return - The function returns @ref M2M_SUCCESS if the command has been successfully queued to the WINC, - and a negative value otherwise. -*/ - -sint8 m2m_wifi_send_crl(tstrTlsCrlInfo* pCRL); - - /**@}*/ -/** @defgroup WifiDefaultConnectFn m2m_wifi_default_connect - * @ingroup WLANAPI - * Asynchronous Wi-Fi connection function. An application calling this function will cause the firmware to correspondingly connect to the last successfully connected AP from the cached connections. - * A failure to connect will result in a response of @ref M2M_WIFI_RESP_DEFAULT_CONNECT indicating the connection error as defined in the structure @ref tstrM2MDefaultConnResp. - * Possible errors are: - * The connection list is empty @ref M2M_DEFAULT_CONN_EMPTY_LIST or a mismatch for the saved AP name @ref M2M_DEFAULT_CONN_SCAN_MISMATCH. - * only difference between this function and @ref m2m_wifi_connect, is the connection parameters. - * Connection using this function is expected to connect using cached connection parameters. - - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_default_connect(void); - -@pre - Prior to connecting, the WINC driver should have been successfully initialized by calling the @ref m2m_wifi_init function. - -@brief Connect to the last successfully connected AP from the cached connections. - -@warning - This function must be called in station mode only. - It's important to note that successful completion of a call to m2m_wifi_default_connect() does not guarantee success of the WIFI connection, - and a negative return value indicates only locally-detected errors. - -@see - m2m_wifi_connect - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_default_connect(void); - /**@}*/ -/** @defgroup WifiConnectFn m2m_wifi_connect - * @ingroup WLANAPI - * Asynchronous wi-fi connection function to a specific AP. Prior to a successful connection, the application must define the SSID of the AP, the security type, - * the authentication information parameters and the channel number to which the connection will be established. - * The connection status is known when a response of @ref M2M_WIFI_RESP_CON_STATE_CHANGED is received based on the states defined in @ref tenuM2mConnState, - * successful connection is defined by @ref M2M_WIFI_CONNECTED -* - * The only difference between this function and @ref m2m_wifi_default_connect, is the connection parameters. - * Connection using this function is expected to be made to a specific AP and to a specified channel. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_connect(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch); - -@param [in] pcSsid - A buffer holding the SSID corresponding to the requested AP. - -@param [in] u8SsidLen - Length of the given SSID (not including the NULL termination). - A length less than ZERO or greater than the maximum defined SSID @ref M2M_MAX_SSID_LEN will result in a negative error - @ref M2M_ERR_FAIL. - -@param [in] u8SecType - Wi-Fi security type security for the network. It can be one of the following types: - -@ref M2M_WIFI_SEC_OPEN - -@ref M2M_WIFI_SEC_WEP - -@ref M2M_WIFI_SEC_WPA_PSK - -@ref M2M_WIFI_SEC_802_1X - A value outside these possible values will result in a negative return error @ref M2M_ERR_FAIL. - -@param [in] pvAuthInfo - Authentication parameters required for completing the connection. It is type is based on the Security type. - If the authentication parameters are NULL or are greater than the maximum length of the authentication parameters length as defined by - @ref M2M_MAX_PSK_LEN a negative error will return @ref M2M_ERR_FAIL(-12) indicating connection failure. - -@param [in] u16Ch - Wi-Fi channel number as defined in @ref tenuM2mScanCh enumeration. - Channel number greater than @ref M2M_WIFI_CH_14 returns a negative error @ref M2M_ERR_FAIL(-12). - Except if the value is M2M_WIFI_CH_ALL(255), since this indicates that the firmware should scan all channels to find the SSID requested to connect to. - Failure to find the connection match will return a negative error @ref M2M_DEFAULT_CONN_SCAN_MISMATCH. -@pre - Prior to a successful connection request, the Wi-Fi driver must have been successfully initialized through the call of the @ref @m2m_wifi_init function -@see - tuniM2MWifiAuth - tstr1xAuthCredentials - tstrM2mWifiWepParams - -@warning - -This function must be called in station mode only. - -Successful completion of this function does not guarantee success of the WIFI connection, and - a negative return value indicates only locally-detected errors. - -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_connect(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch); - /**@}*/ -/** @defgroup WifiConnectFn m2m_wifi_connect_sc - * @ingroup WLANAPI - * Asynchronous wi-fi connection function to a specific AP. Prior to a successful connection, the application developers must know the SSID of the AP, the security type, - * the authentication information parameters and the channel number to which the connection will be established.this API allows the user to choose - * whether to - * The connection status is known when a response of @ref M2M_WIFI_RESP_CON_STATE_CHANGED is received based on the states defined in @ref tenuM2mConnState, - * successful connection is defined by @ref M2M_WIFI_CONNECTED - * The only difference between this function and @ref m2m_wifi_connect, is the option to save the acess point info ( SSID, password...etc) or not. - * Connection using this function is expected to be made to a specific AP and to a specified channel. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_connect_sc(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch,uint8 u8SaveCred); - -@param [in] pcSsid - A buffer holding the SSID corresponding to the requested AP. - -@param [in] u8SsidLen - Length of the given SSID (not including the NULL termination). - A length less than ZERO or greater than the maximum defined SSID @ref M2M_MAX_SSID_LEN will result in a negative error - @ref M2M_ERR_FAIL. - -@param [in] u8SecType - Wi-Fi security type security for the network. It can be one of the following types: - -@ref M2M_WIFI_SEC_OPEN - -@ref M2M_WIFI_SEC_WEP - -@ref M2M_WIFI_SEC_WPA_PSK - -@ref M2M_WIFI_SEC_802_1X - A value outside these possible values will result in a negative return error @ref M2M_ERR_FAIL. - -@param [in] pvAuthInfo - Authentication parameters required for completing the connection. It is type is based on the Security type. - If the authentication parameters are NULL or are greater than the maximum length of the authentication parameters length as defined by - @ref M2M_MAX_PSK_LEN a negative error will return @ref M2M_ERR_FAIL(-12) indicating connection failure. - -@param [in] u16Ch - Wi-Fi channel number as defined in @ref tenuM2mScanCh enumeration. - Channel number greater than @ref M2M_WIFI_CH_14 returns a negative error @ref M2M_ERR_FAIL(-12). - Except if the value is M2M_WIFI_CH_ALL(255), since this indicates that the firmware should scan all channels to find the SSID requested to connect to. - Failure to find the connection match will return a negative error @ref M2M_DEFAULT_CONN_SCAN_MISMATCH. - -@param [in] u8NoSaveCred - Option to store the acess point SSID and password into the WINC flash memory or not. - -@pre - Prior to a successful connection request, the wi-fi driver must have been successfully initialized through the call of the @ref @m2m_wifi_init function -@see - tuniM2MWifiAuth - tstr1xAuthCredentials - tstrM2mWifiWepParams - -@warning - -This function must be called in station mode only. - -Successful completion of this function does not guarantee success of the WIFI connection, and - a negative return value indicates only locally-detected errors. - -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ - NMI_API sint8 m2m_wifi_connect_sc(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch, uint8 u8SaveCred); - /**@}*/ -/** @defgroup WifiDisconnectFn m2m_wifi_disconnect - * @ingroup WLANAPI - * Synchronous wi-fi disconnection function, requesting a Wi-Fi disconnection from the currently connected AP. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_disconnect(void); - -@pre - Disconnection request must be made to a successfully connected AP. If the WINC is not in the connected state, a call to this function will hold insignificant. - -@brief Request a Wi-Fi disconnect from the currently connected AP. - After the Disconnect is complete the driver should recieve a response of @ref M2M_WIFI_RESP_CON_STATE_CHANGED based on the states defined - in @ref tenuM2mConnState, successful disconnection is defined by @ref M2M_WIFI_DISCONNECTED . -@warning - This function must be called in station mode only. - -@see - m2m_wifi_connect - m2m_wifi_default_connect - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_disconnect(void); - - /**@}*/ -/** @defgroup StartProvisionModeFn m2m_wifi_start_provision_mode - * @ingroup WLANAPI - * Asynchronous Wi-Fi provisioning function, which starts the WINC HTTP PROVISIONING mode. - The function triggers the WINC to activate the Wi-Fi AP (HOTSPOT) mode with the passed configuration parameters and then starts the - HTTP Provision WEB Server. - The provisioning status is returned in an event @ref M2M_WIFI_RESP_PROVISION_INFO - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_start_provision_mode(tstrM2MAPConfig *pstrAPConfig, char *pcHttpServerDomainName, uint8 bEnableHttpRedirect); - -@param [in] pstrAPConfig - AP configuration parameters as defined in @ref tstrM2MAPConfig configuration structure. - A NULL value passed in, will result in a negative error @ref M2M_ERR_FAIL. - -@param [in] pcHttpServerDomainName - Domain name of the HTTP Provision WEB server which others will use to load the provisioning Home page. - The domain name can have one of the following 3 forms: - 1- "wincprov.com" - 2- "http://wincprov.com" - 3- "https://wincprov.com" - The forms 1 and 2 are equivalent, they both will start a plain http server, while form 3 - will start a secure HTTP provisioning Session (HTTP over SSL connection). - -@param [in] bEnableHttpRedirect - A flag to enable/disable the HTTP redirect feature. If Secure provisioning is enabled (i.e. the server - domain name uses "https" prefix) this flag is ignored (no meaning for redirect in HTTPS). - Possible values are: - - ZERO DO NOT Use HTTP Redirect. In this case the associated device could open the provisioning page ONLY when - the HTTP Provision URL of the WINC HTTP Server is correctly written on the browser. - - Non-Zero value Use HTTP Redirect. In this case, all http traffic (http://URL) from the associated - device (Phone, PC, ...etc) will be redirected to the WINC HTTP Provisioning Home page. - -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback - is done through passing it to the initialization @ref m2m_wifi_init function. - - The event @ref M2M_WIFI_RESP_CONN_INFO must be handled in the callback to receive the requested connection info. - -@see - tpfAppWifiCb - m2m_wifi_init - M2M_WIFI_RESP_PROVISION_INFO - m2m_wifi_stop_provision_mode - tstrM2MAPConfig - -@warning - DO Not use ".local" in the pcHttpServerDomainName. - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -\section Example - The example demonstrates a code snippet for how provisioning is triggered and the response event received accordingly. -@code - #include "m2m_wifi.h" - #include "m2m_types.h" - - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_PROVISION_INFO: - { - tstrM2MProvisionInfo *pstrProvInfo = (tstrM2MProvisionInfo*)pvMsg; - if(pstrProvInfo->u8Status == M2M_SUCCESS) - { - m2m_wifi_connect((char*)pstrProvInfo->au8SSID, (uint8)strlen(pstrProvInfo->au8SSID), pstrProvInfo->u8SecType, - pstrProvInfo->au8Password, M2M_WIFI_CH_ALL); - - printf("PROV SSID : %s\n",pstrProvInfo->au8SSID); - printf("PROV PSK : %s\n",pstrProvInfo->au8Password); - } - else - { - printf("(ERR) Provisioning Failed\n"); - } - } - break; - - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - tstrM2MAPConfig apConfig; - uint8 bEnableRedirect = 1; - - strcpy(apConfig.au8SSID, "WINC_SSID"); - apConfig.u8ListenChannel = 1; - apConfig.u8SecType = M2M_WIFI_SEC_OPEN; - apConfig.u8SsidHide = 0; - - // IP Address - apConfig.au8DHCPServerIP[0] = 192; - apConfig.au8DHCPServerIP[1] = 168; - apConfig.au8DHCPServerIP[2] = 1; - apConfig.au8DHCPServerIP[0] = 1; - - m2m_wifi_start_provision_mode(&apConfig, "atmelwincconf.com", bEnableRedirect); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API sint8 m2m_wifi_start_provision_mode(tstrM2MAPConfig *pstrAPConfig, char *pcHttpServerDomainName, uint8 bEnableHttpRedirect); - /**@}*/ -/** @defgroup StopProvisioningModeFn m2m_wifi_stop_provision_mode - * @ingroup WLANAPI - * Synchronous provision termination function which stops the provision mode if it is active. - */ - /**@{*/ -/*! -@fn \ - sint8 m2m_wifi_stop_provision_mode(void); - -@pre - An active provisioning session must be active before it is terminated through this function. -@see - m2m_wifi_start_provision_mode - -@return - The function returns ZERO for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_stop_provision_mode(void); - /**@}*/ -/** @defgroup GetConnectionInfoFn m2m_wifi_get_connection_info - * @ingroup WLANAPI - * Asynchronous connection status retrieval function, retrieves the status information of the currently connected AP. The result is passed to the Wi-Fi notification callback -* through the event @ref M2M_WIFI_RESP_CONN_INFO. Connection information is retrieved from the structure @ref tstrM2MConnInfo. - */ - /**@{*/ -/*! -@fn \ - sint8 m2m_wifi_get_connection_info(void); - -@brief - Retrieve the current Connection information. The result is passed to the Wi-Fi notification callback - with [M2M_WIFI_RESP_CONN_INFO](@ref M2M_WIFI_RESP_CONN_INFO). -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback - is done through passing it to the initialization @ref m2m_wifi_init function. - - The event @ref M2M_WIFI_RESP_CONN_INFO must be handled in the callback to receive the requested connection info. - - Connection Information retrieved: - - - -Connection Security - -Connection RSSI - -Remote MAC address - -Remote IP address - - and in case of WINC station mode the SSID of the AP is also retrieved. -@warning - -In case of WINC AP mode or P2P mode, ignore the SSID field (NULL string). -@sa - M2M_WIFI_RESP_CONN_INFO, - tstrM2MConnInfo -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet shows an example of how wi-fi connection information is retrieved . -@code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_CONN_INFO: - { - tstrM2MConnInfo *pstrConnInfo = (tstrM2MConnInfo*)pvMsg; - - printf("CONNECTED AP INFO\n"); - printf("SSID : %s\n",pstrConnInfo->acSSID); - printf("SEC TYPE : %d\n",pstrConnInfo->u8SecType); - printf("Signal Strength : %d\n", pstrConnInfo->s8RSSI); - printf("Local IP Address : %d.%d.%d.%d\n", - pstrConnInfo->au8IPAddr[0] , pstrConnInfo->au8IPAddr[1], pstrConnInfo->au8IPAddr[2], pstrConnInfo->au8IPAddr[3]); - } - break; - - case M2M_WIFI_REQ_DHCP_CONF: - { - // Get the current AP information. - m2m_wifi_get_connection_info(); - } - break; - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // connect to the default AP - m2m_wifi_default_connect(); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API sint8 m2m_wifi_get_connection_info(void); - /**@}*/ -/** @defgroup WifiSetMacAddFn m2m_wifi_set_mac_address - * @ingroup WLANAPI - * Synchronous MAC address assigning to the NMC1500. It is used for non-production SW. Assign MAC address to the WINC device. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_set_mac_address(uint8 au8MacAddress[6]); - -@brief Assign a MAC address to the WINC board. - This function override the already assigned MAC address of the WINC board with a user provided one. This is for experimental - use only and should never be used in the production SW. - -@param [in] au8MacAddress - MAC Address to be set to the WINC. - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_set_mac_address(uint8 au8MacAddress[6]); - - /**@}*/ -/** @defgroup WifiWpsFn m2m_wifi_wps - * @ingroup WLANAPI - * Asynchronous WPS triggering function. - * This function is called for the WINC to enter the WPS (Wi-Fi Protected Setup) mode. The result is passed to the Wi-Fi notification callback -* with the event @ref M2M_WIFI_REQ_WPS. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_wps(uint8 u8TriggerType,const char * pcPinNumber); - -@param [in] u8TriggerType - WPS Trigger method. Could be: - - [WPS_PIN_TRIGGER](@ref WPS_PIN_TRIGGER) Push button method - - [WPS_PBC_TRIGGER](@ref WPS_PBC_TRIGGER) Pin method - -@param [in] pcPinNumber - PIN number for WPS PIN method. It is not used if the trigger type is WPS_PBC_TRIGGER. It must follow the rules - stated by the WPS standard. - -@warning - This function is not allowed in AP or P2P modes. - -@pre - - A Wi-Fi notification callback of type (@ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback - is done through passing it to the [m2m_wifi_init](@ref m2m_wifi_init). - - The event [M2M_WIFI_REQ_WPS](@ref M2M_WIFI_REQ_WPS) must be handled in the callback to receive the WPS status. - - The WINC device MUST be in IDLE or STA mode. If AP or P2P mode is active, the WPS will not be performed. - - The [m2m_wifi_handle_events](@ref m2m_wifi_handle_events) MUST be called periodically to receive the responses in the callback. -@see - tpfAppWifiCb - m2m_wifi_init - M2M_WIFI_REQ_WPS - tenuWPSTrigger - tstrM2MWPSInfo - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet shows an example of how Wi-Fi WPS is triggered . -@code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - switch(u8WiFiEvent) - { - case M2M_WIFI_REQ_WPS: - { - tstrM2MWPSInfo *pstrWPS = (tstrM2MWPSInfo*)pvMsg; - if(pstrWPS->u8AuthType != 0) - { - printf("WPS SSID : %s\n",pstrWPS->au8SSID); - printf("WPS PSK : %s\n",pstrWPS->au8PSK); - printf("WPS SSID Auth Type : %s\n",pstrWPS->u8AuthType == M2M_WIFI_SEC_OPEN ? "OPEN" : "WPA/WPA2"); - printf("WPS Channel : %d\n",pstrWPS->u8Ch + 1); - - // establish Wi-Fi connection - m2m_wifi_connect((char*)pstrWPS->au8SSID, (uint8)m2m_strlen(pstrWPS->au8SSID), - pstrWPS->u8AuthType, pstrWPS->au8PSK, pstrWPS->u8Ch); - } - else - { - printf("(ERR) WPS Is not enabled OR Timed out\n"); - } - } - break; - - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // Trigger WPS in Push button mode. - m2m_wifi_wps(WPS_PBC_TRIGGER, NULL); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API sint8 m2m_wifi_wps(uint8 u8TriggerType,const char *pcPinNumber); - /**@}*/ -/** @defgroup WifiWpsDisableFn m2m_wifi_wps_disable - * @ingroup WLANAPI - * Disable the WINC1500 WPS operation. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_wps_disable(void); - -@pre WINC should be already in WPS mode using @ref m2m_wifi_wps - -@brief Stops the WPS ongoing session. - -@see - m2m_wifi_wps - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_wps_disable(void); - - /**@}*/ -/** @defgroup WifiP2PFn m2m_wifi_p2p - * @ingroup WLANAPI - * Asynchronous Wi-Fi direct (P2P) enabling mode function. - The WINC supports P2P in device listening mode ONLY (intent is ZERO). - The WINC P2P implementation does not support P2P GO (Group Owner) mode. - Active P2P devices (e.g. phones) could find the WINC in the search list. When a device is connected to WINC, a Wi-Fi notification event - @ref M2M_WIFI_RESP_CON_STATE_CHANGED is triggered. After a short while, the DHCP IP Address is obtained - and an event @ref M2M_WIFI_REQ_DHCP_CONF is triggered. Refer to the code examples for a more illustrative example. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_p2p(uint8 u8Channel); - -@param [in] u8Channel - P2P Listen RF channel. According to the P2P standard It must hold only one of the following values 1, 6 or 11. - -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback - is done through passing it to the @ref m2m_wifi_init. - - The events @ref M2M_WIFI_RESP_CON_STATE_CHANGED and @ref M2M_WIFI_REQ_DHCP_CONF - must be handled in the callback. - - The @ref m2m_wifi_handle_events MUST be called to receive the responses in the callback. - -@warning - This function is not allowed in AP or STA modes. - -@see - tpfAppWifiCb - m2m_wifi_init - M2M_WIFI_RESP_CON_STATE_CHANGED - M2M_WIFI_REQ_DHCP_CONF - tstrM2mWifiStateChanged - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet shown an example of how the p2p mode operates. -@code - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_CON_STATE_CHANGED: - { - tstrM2mWifiStateChanged *pstrWifiState = (tstrM2mWifiStateChanged*)pvMsg; - M2M_INFO("Wifi State :: %s :: ErrCode %d\n", pstrWifiState->u8CurrState? "CONNECTED":"DISCONNECTED",pstrWifiState->u8ErrCode); - - // Do something - } - break; - - case M2M_WIFI_REQ_DHCP_CONF: - { - uint8 *pu8IPAddress = (uint8*)pvMsg; - - printf("P2P IP Address \"%u.%u.%u.%u\"\n",pu8IPAddress[0],pu8IPAddress[1],pu8IPAddress[2],pu8IPAddress[3]); - } - break; - - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // Trigger P2P - m2m_wifi_p2p(M2M_WIFI_CH_1); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode - -*/ -NMI_API sint8 m2m_wifi_p2p(uint8 u8Channel); - /**@}*/ -/** @defgroup WifiP2PDisconnectFn m2m_wifi_p2p_disconnect - * @ingroup WLANAPI - * Disable the WINC1500 device Wi-Fi direct mode (P2P). - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_p2p_disconnect(void); -@pre - The p2p mode must have be enabled and active before a disconnect can be called. - -@see - m2m_wifi_p2p -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_p2p_disconnect(void); - /**@}*/ -/** @defgroup WifiEnableApFn m2m_wifi_enable_ap - * @ingroup WLANAPI - * Asynchronous Wi-FI hot-spot enabling function. - * The WINC supports AP mode operation with the following limitations: - - Only 1 STA could be associated at a time. - - Open and WEP are the only supported security types - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_enable_ap(CONST tstrM2MAPConfig* pstrM2MAPConfig); - -@param [in] pstrM2MAPConfig - A structure holding the AP configurations. - -@warning - This function is not allowed in P2P or STA modes. - -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback - is done through passing it to the [m2m_wifi_init](@ref m2m_wifi_init). - - The event @ref M2M_WIFI_REQ_DHCP_CONF must be handled in the callback. - - The @ref m2m_wifi_handle_events MUST be called to receive the responses in the callback. - -@see - tpfAppWifiCb - tenuM2mSecType - m2m_wifi_init - M2M_WIFI_REQ_DHCP_CONF - tstrM2mWifiStateChanged - tstrM2MAPConfig - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet demonstrates how the AP mode is enabled after the driver is initialized in the application's main function and the handling - of the event @ref M2M_WIFI_REQ_DHCP_CONF, to indicate successful connection. -@code - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - switch(u8WiFiEvent) - { - case M2M_WIFI_REQ_DHCP_CONF: - { - uint8 *pu8IPAddress = (uint8*)pvMsg; - - printf("Associated STA has IP Address \"%u.%u.%u.%u\"\n",pu8IPAddress[0],pu8IPAddress[1],pu8IPAddress[2],pu8IPAddress[3]); - } - break; - - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - tstrM2MAPConfig apConfig; - - strcpy(apConfig.au8SSID, "WINC_SSID"); - apConfig.u8ListenChannel = 1; - apConfig.u8SecType = M2M_WIFI_SEC_OPEN; - apConfig.u8SsidHide = 0; - - // IP Address - apConfig.au8DHCPServerIP[0] = 192; - apConfig.au8DHCPServerIP[1] = 168; - apConfig.au8DHCPServerIP[2] = 1; - apConfig.au8DHCPServerIP[0] = 1; - - // Trigger AP - m2m_wifi_enable_ap(&apConfig); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode - -*/ -NMI_API sint8 m2m_wifi_enable_ap(CONST tstrM2MAPConfig* pstrM2MAPConfig); - /**@}*/ -/** @defgroup WifiDisableApFn m2m_wifi_disable_ap - * @ingroup WLANAPI - * Synchronous Wi-Fi hot-spot disabling function. Must be called only when the AP is enabled through the @ref m2m_wifi_enable_ap - * function. Otherwise the call to this function will not be useful. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_disable_ap(void); -@see - m2m_wifi_enable_ap -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_disable_ap(void); - /**@}*/ -/** @defgroup SetStaticIPFn m2m_wifi_set_static_ip - * @ingroup WLANAPI - * Synchronous static IP Address configuration function. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_set_static_ip(tstrM2MIPConfig * pstrStaticIPConf); - -@param [in] pstrStaticIPConf - Pointer to a structure holding the static IP Configurations (IP, - Gateway, subnet mask and DNS address). - -@pre The application must disable auto DHCP using @ref m2m_wifi_enable_dhcp before assigning a static IP address. - -@brief Assign a static IP address to the WINC board. - This function assigns a static IP address in case the AP doesn't have a DHCP server or in case the application wants to assign - a predefined known IP address. The user must take in mind that assigning a static IP address might result in an IP address - conflict. In case of an IP address conflict observed by the WINC board the user will get a response of @ref M2M_WIFI_RESP_IP_CONFLICT - in the wifi callback. The application is then responsible to either solve the conflict or assign another IP address. -@warning - Normally this function normally should not be used. DHCP configuration is requested automatically after successful Wi-Fi connection is established. - -@see - tstrM2MIPConfig - - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_set_static_ip(tstrM2MIPConfig * pstrStaticIPConf); - - /**@}*/ -/** @defgroup RequestDHCPClientFn m2m_wifi_request_dhcp_client - * @ingroup WLANAPI - * Starts the DHCP client operation(DHCP requested by the firmware automatically in STA/AP/P2P mode). - * - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_request_dhcp_client(void); - -@warning - This function is legacy and exists only for compatability with older applications. DHCP configuration is requested automatically after successful Wi-Fi connection is established. - -@return - The function returns @ref M2M_SUCCESS always. -*/ -NMI_API sint8 m2m_wifi_request_dhcp_client(void); - /**@}*/ -/** @defgroup RequestDHCPServerFn m2m_wifi_request_dhcp_server - * @ingroup WLANAPI - * Dhcp requested by the firmware automatically in STA/AP/P2P mode). - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_request_dhcp_server(uint8* addr); - -@warning - This function is legacy and exists only for compatability with older applications. DHCP server is started automatically when enabling the AP mode. - - -@return - The function returns @ref M2M_SUCCESS always. -*/ -NMI_API sint8 m2m_wifi_request_dhcp_server(uint8* addr); - /**@}*/ -/** @defgroup WifiDHCPEnableFn m2m_wifi_enable_dhcp - * @ingroup WLANAPI - * Synchronous Wi-Fi DHCP enable function. This function Enable/Disable DHCP protocol. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_enable_dhcp(uint8 u8DhcpEn ); - -@brief - Enable/Disable the DHCP client after connection. - -@param [in] u8DhcpEn - Possible values: - 1: Enable DHCP client after connection. - 0: Disable DHCP client after connection. -@warnings - -DHCP client is enabled by default - -This Function should be called before using m2m_wifi_set_static_ip() - - -@sa - m2m_wifi_set_static_ip() - -@return - The function SHALL return @ref M2M_SUCCESS for successful operation and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_enable_dhcp(uint8 u8DhcpEn ); - /**@}*/ -/** @defgroup WifiSetScanOptionFn m2m_wifi_set_scan_options - * @ingroup WLANAPI - * Synchronous Wi-Fi scan settings function. This function sets the time configuration parameters for the scan operation. - */ - -/*! -@fn \ - sint8 m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption) - -@param [in] ptstrM2MScanOption; - Pointer to the structure holding the Scan Parameters. - -@see - tenuM2mScanCh - m2m_wifi_request_scan - tstrM2MScanOption - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption); - /**@}*/ -/** @defgroup WifiSetScanRegionFn m2m_wifi_set_scan_region - * @ingroup WLANAPI - * Synchronous wi-fi scan region setting function. - * This function sets the scan region, which will affect the range of possible scan channels. - * For 2.5GHz supported in the current release, the requested scan region can't exceed the maximum number of channels (14). - *@{*/ -/*! -@fn \ - sint8 m2m_wifi_set_scan_region(uint16 ScanRegion) - -@param [in] ScanRegion; - ASIA - NORTH_AMERICA -@see - tenuM2mScanCh - m2m_wifi_request_scan - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_set_scan_region(uint16 ScanRegion); - /**@}*/ -/** @defgroup WifiRequestScanFn m2m_wifi_request_scan -* @ingroup WLANAPI -* Asynchronous Wi-FI scan request on the given channel. The scan status is delivered in the wifi event callback and then the application -* is supposed to read the scan results sequentially. -* The number of APs found (N) is returned in event @ref M2M_WIFI_RESP_SCAN_DONE with the number of found -* APs. -* The application reads the list of APs by calling the function @ref m2m_wifi_req_scan_result N times. -* -*@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_request_scan(uint8 ch); - -@param [in] ch - RF Channel ID for SCAN operation. It should be set according to tenuM2mScanCh. - With a value of M2M_WIFI_CH_ALL(255)), means to scan all channels. - -@warning - This function is not allowed in P2P or AP modes. It works only for STA mode (both connected or disconnected states). - -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback - is done through passing it to the @ref m2m_wifi_init. - - The events @ref M2M_WIFI_RESP_SCAN_DONE and @ref M2M_WIFI_RESP_SCAN_RESULT. - must be handled in the callback. - - The @ref m2m_wifi_handle_events function MUST be called to receive the responses in the callback. - -@see - M2M_WIFI_RESP_SCAN_DONE - M2M_WIFI_RESP_SCAN_RESULT - tpfAppWifiCb - tstrM2mWifiscanResult - tenuM2mScanCh - m2m_wifi_init - m2m_wifi_handle_events - m2m_wifi_req_scan_result - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of - the events received in response. -@code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - static uint8 u8ScanResultIdx = 0; - - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_SCAN_DONE: - { - tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; - - printf("Num of AP found %d\n",pstrInfo->u8NumofCh); - if(pstrInfo->s8ScanState == M2M_SUCCESS) - { - u8ScanResultIdx = 0; - if(pstrInfo->u8NumofCh >= 1) - { - m2m_wifi_req_scan_result(u8ScanResultIdx); - u8ScanResultIdx ++; - } - else - { - printf("No AP Found Rescan\n"); - m2m_wifi_request_scan(M2M_WIFI_CH_ALL); - } - } - else - { - printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); - } - } - break; - - case M2M_WIFI_RESP_SCAN_RESULT: - { - tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; - uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); - - printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", - pstrScanResult->u8index,pstrScanResult->s8rssi, - pstrScanResult->u8AuthType, - pstrScanResult->u8ch, - pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], - pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], - pstrScanResult->au8SSID); - - if(u8ScanResultIdx < u8NumFoundAPs) - { - // Read the next scan result - m2m_wifi_req_scan_result(index); - u8ScanResultIdx ++; - } - } - break; - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // Scan all channels - m2m_wifi_request_scan(M2M_WIFI_CH_ALL); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API sint8 m2m_wifi_request_scan(uint8 ch); - - /**@}*/ -/** @defgroup WifiRequestScanFn m2m_wifi_request_scan_passive -* @ingroup WLANAPI -* Same as m2m_wifi_request_scan but perform passive scanning while the other one perform active scanning. - -* -*@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_request_scan_passive(uint8 ch, uint16 scan_time); - -@param [in] ch - RF Channel ID for SCAN operation. It should be set according to tenuM2mScanCh. - With a value of M2M_WIFI_CH_ALL(255)), means to scan all channels. - -@param [in] scan_time - The time in ms that passive scan is listening to beacons on each channel per one slot, enter 0 for deafult setting. - -@warning - This function is not allowed in P2P or AP modes. It works only for STA mode (both connected or disconnected states). - -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback - is done through passing it to the @ref m2m_wifi_init. - - The events @ref M2M_WIFI_RESP_SCAN_DONE and @ref M2M_WIFI_RESP_SCAN_RESULT. - must be handled in the callback. - - The @ref m2m_wifi_handle_events function MUST be called to receive the responses in the callback. - -@see - m2m_wifi_request_scan - M2M_WIFI_RESP_SCAN_DONE - M2M_WIFI_RESP_SCAN_RESULT - tpfAppWifiCb - tstrM2mWifiscanResult - tenuM2mScanCh - m2m_wifi_init - m2m_wifi_handle_events - m2m_wifi_req_scan_result - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_request_scan_passive(uint8 ch, uint16 scan_time); - - - /**@}*/ -/** @defgroup WifiRequestScanFn m2m_wifi_request_scan_ssid_list -* @ingroup WLANAPI -* Asynchronous wi-fi scan request on the given channel and the hidden scan list. The scan status is delivered in the wi-fi event callback and then the application -* is to read the scan results sequentially. -* The number of APs found (N) is returned in event @ref M2M_WIFI_RESP_SCAN_DONE with the number of found -* APs. -* The application could read the list of APs by calling the function @ref m2m_wifi_req_scan_result N times. -* -*@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_request_scan_ssid_list(uint8 ch,uint8 * u8SsidList); - -@param [in] ch - RF Channel ID for SCAN operation. It should be set according to tenuM2mScanCh. - With a value of M2M_WIFI_CH_ALL(255)), means to scan all channels. -@param [in] u8SsidList - u8SsidList is a buffer containing a list of hidden SSIDs to - include during the scan. The first byte in the buffer, u8SsidList[0], - is the number of SSIDs encoded in the string. The number of hidden SSIDs - cannot exceed MAX_HIDDEN_SITES. All SSIDs are concatenated in the following - bytes and each SSID is prefixed with a one-byte header containing its length. - The total number of bytes in u8SsidList buffer, including length byte, cannot - exceed 133 bytes (MAX_HIDDEN_SITES SSIDs x 32 bytes each, which is max SSID length). - For instance, encoding the two hidden SSIDs "DEMO_AP" and "TEST" - results in the following buffer content: -@code - uint8 u8SsidList[14]; - u8SsidList[0] = 2; // Number of SSIDs is 2 - u8SsidList[1] = 7; // Length of the string "DEMO_AP" without NULL termination - memcpy(&u8SsidList[2], "DEMO_AP", 7); // Bytes index 2-9 containing the string DEMO_AP - u8SsidList[9] = 4; // Length of the string "TEST" without NULL termination - memcpy(&u8SsidList[10], "TEST", 4); // Bytes index 10-13 containing the string TEST -@endcode - -@warning - This function is not allowed in P2P. It works only for STA/AP mode (connected or disconnected). - -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback - is done through passing it to the @ref m2m_wifi_init. - - The events @ref M2M_WIFI_RESP_SCAN_DONE and @ref M2M_WIFI_RESP_SCAN_RESULT. - must be handled in the callback. - - The @ref m2m_wifi_handle_events function MUST be called to receive the responses in the callback. - -@see - M2M_WIFI_RESP_SCAN_DONE - M2M_WIFI_RESP_SCAN_RESULT - tpfAppWifiCb - tstrM2mWifiscanResult - tenuM2mScanCh - m2m_wifi_init - m2m_wifi_handle_events - m2m_wifi_req_scan_result - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of - the events received in response. -@code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - static void request_scan_hidden_demo_ap(void); - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - static uint8 u8ScanResultIdx = 0; - - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_SCAN_DONE: - { - tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; - - printf("Num of AP found %d\n",pstrInfo->u8NumofCh); - if(pstrInfo->s8ScanState == M2M_SUCCESS) - { - u8ScanResultIdx = 0; - if(pstrInfo->u8NumofCh >= 1) - { - m2m_wifi_req_scan_result(u8ScanResultIdx); - u8ScanResultIdx ++; - } - else - { - printf("No AP Found Rescan\n"); - request_scan_hidden_demo_ap(); - } - } - else - { - printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); - } - } - break; - - case M2M_WIFI_RESP_SCAN_RESULT: - { - tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; - uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); - - printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", - pstrScanResult->u8index,pstrScanResult->s8rssi, - pstrScanResult->u8AuthType, - pstrScanResult->u8ch, - pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], - pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], - pstrScanResult->au8SSID); - - if(u8ScanResultIdx < u8NumFoundAPs) - { - // Read the next scan result - m2m_wifi_req_scan_result(index); - u8ScanResultIdx ++; - } - } - break; - default: - break; - } - } - - static void request_scan_hidden_demo_ap(void) - { - uint8 list[9]; - char ssid[] = "DEMO_AP"; - uint8 len = (uint8)(sizeof(ssid)-1); - - list[0] = 1; - list[1] = len; - memcpy(&list[2], ssid, len); // copy 7 bytes - // Scan all channels - m2m_wifi_request_scan_ssid_list(M2M_WIFI_CH_ALL, list); - } - - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - request_scan_hidden_demo_ap(); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API sint8 m2m_wifi_request_scan_ssid_list(uint8 ch,uint8 * u8Ssidlist); - -/**@}*/ -/** @defgroup WifiGetNumAPFoundFn m2m_wifi_get_num_ap_found - * @ingroup WLANAPI -* Synchronous function to retrieve the number of AP's found in the last scan request, The function reads the number of APs from global variable which was updated in the Wi-Fi callback function through the M2M_WIFI_RESP_SCAN_DONE event. -* Function used only in STA mode only. - */ - /**@{*/ -/*! -@fn NMI_API uint8 m2m_wifi_get_num_ap_found(void); - -@see m2m_wifi_request_scan - M2M_WIFI_RESP_SCAN_DONE - M2M_WIFI_RESP_SCAN_RESULT -@pre m2m_wifi_request_scan need to be called first - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback - is done through passing it to the @ref m2m_wifi_init. - - The event @ref M2M_WIFI_RESP_SCAN_DONE must be handled in the callback to receive the requested scan information. -@warning This function must be called only in the wi-fi callback function when the events @ref M2M_WIFI_RESP_SCAN_DONE or @ref M2M_WIFI_RESP_SCAN_RESULT - are received. - Calling this function in any other place will result in undefined/outdated numbers. -@return Return the number of AP's found in the last Scan Request. - -\section Example - The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of - the events received in response. -@code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - static uint8 u8ScanResultIdx = 0; - - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_SCAN_DONE: - { - tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; - - printf("Num of AP found %d\n",pstrInfo->u8NumofCh); - if(pstrInfo->s8ScanState == M2M_SUCCESS) - { - u8ScanResultIdx = 0; - if(pstrInfo->u8NumofCh >= 1) - { - m2m_wifi_req_scan_result(u8ScanResultIdx); - u8ScanResultIdx ++; - } - else - { - printf("No AP Found Rescan\n"); - m2m_wifi_request_scan(M2M_WIFI_CH_ALL); - } - } - else - { - printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); - } - } - break; - - case M2M_WIFI_RESP_SCAN_RESULT: - { - tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; - uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); - - printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", - pstrScanResult->u8index,pstrScanResult->s8rssi, - pstrScanResult->u8AuthType, - pstrScanResult->u8ch, - pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], - pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], - pstrScanResult->au8SSID); - - if(u8ScanResultIdx < u8NumFoundAPs) - { - // Read the next scan result - m2m_wifi_req_scan_result(index); - u8ScanResultIdx ++; - } - } - break; - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // Scan all channels - m2m_wifi_request_scan(M2M_WIFI_CH_ALL); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API uint8 m2m_wifi_get_num_ap_found(void); -/**@}*/ -/** @defgroup WifiReqScanResult m2m_wifi_req_scan_result -* @ingroup WLANAPI -* Synchronous call to read the AP information from the SCAN Result list with the given index. -* This function is expected to be called when the response events M2M_WIFI_RESP_SCAN_RESULT or -* M2M_WIFI_RESP_SCAN_DONE are received in the wi-fi callback function. -* The response information received can be obtained through the casting to the @ref tstrM2mWifiscanResult structure - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_req_scan_result(uint8 index); -@param [in] index - Index for the requested result, the index range start from 0 till number of AP's found - -@see tstrM2mWifiscanResult - m2m_wifi_get_num_ap_found - m2m_wifi_request_scan - -@pre @ref m2m_wifi_request_scan needs to be called first, then m2m_wifi_get_num_ap_found - to get the number of AP's found - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback - is done through passing it to the @ref m2m_wifi_init function. - - The event @ref M2M_WIFI_RESP_SCAN_RESULT must be handled in the callback to receive the requested scan information. -@warning Function used in STA mode only. the scan results are updated only if the scan request is called. - Calling this function only without a scan request will lead to firmware errors. - Refrain from introducing a large delay between the scan request and the scan result request, to prevent - errors occurring. - -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of - the events received in response. -@code - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - static uint8 u8ScanResultIdx = 0; - - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_SCAN_DONE: - { - tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; - - printf("Num of AP found %d\n",pstrInfo->u8NumofCh); - if(pstrInfo->s8ScanState == M2M_SUCCESS) - { - u8ScanResultIdx = 0; - if(pstrInfo->u8NumofCh >= 1) - { - m2m_wifi_req_scan_result(u8ScanResultIdx); - u8ScanResultIdx ++; - } - else - { - printf("No AP Found Rescan\n"); - m2m_wifi_request_scan(M2M_WIFI_CH_ALL); - } - } - else - { - printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); - } - } - break; - - case M2M_WIFI_RESP_SCAN_RESULT: - { - tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; - uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); - - printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", - pstrScanResult->u8index,pstrScanResult->s8rssi, - pstrScanResult->u8AuthType, - pstrScanResult->u8ch, - pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], - pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], - pstrScanResult->au8SSID); - - if(u8ScanResultIdx < u8NumFoundAPs) - { - // Read the next scan result - m2m_wifi_req_scan_result(index); - u8ScanResultIdx ++; - } - } - break; - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // Scan all channels - m2m_wifi_request_scan(M2M_WIFI_CH_ALL); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API sint8 m2m_wifi_req_scan_result(uint8 index); -/**@}*/ -/** @defgroup WifiReqCurrentRssiFn m2m_wifi_req_curr_rssi - * @ingroup WLANAPI - * Asynchronous request for the current RSSI of the connected AP. - * The response received in through the @ref M2M_WIFI_RESP_CURRENT_RSSI event. - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_req_curr_rssi(void); -@pre - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered before initialization. Registering the callback - is done through passing it to the [m2m_wifi_init](@ref m2m_wifi_init) through the @ref tstrWifiInitParam initialization structure. - - The event @ref M2M_WIFI_RESP_CURRENT_RSSI must be handled in the callback to receive the requested Rssi information. -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet demonstrates how the RSSI request is called in the application's main function and the handling of the event received in the callback. -@code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - static uint8 u8ScanResultIdx = 0; - - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_CURRENT_RSSI: - { - sint8 *rssi = (sint8*)pvMsg; - M2M_INFO("ch rssi %d\n",*rssi); - } - break; - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // Scan all channels - m2m_wifi_req_curr_rssi(); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode - -*/ -NMI_API sint8 m2m_wifi_req_curr_rssi(void); -/**@}*/ -/** @defgroup WifiGetOtpMacAddFn m2m_wifi_get_otp_mac_address -* @ingroup WLANAPI -* Request the MAC address stored on the One Time Programmable(OTP) memory of the device. -* The function is blocking until the response is received. -*/ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); - -@param [out] pu8MacAddr - Output MAC address buffer of 6 bytes size. Valid only if *pu8Valid=1. -@param [out] pu8IsValid - Output boolean value to indicate the validity of pu8MacAddr in OTP. - Output zero if the OTP memory is not programmed, non-zero otherwise. -@pre m2m_wifi_init required to be called before any WIFI/socket function -@see m2m_wifi_get_mac_address - -@return The function returns @ref M2M_SUCCESS for success and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); -/**@}*/ -/** @defgroup WifiGetMacAddFn m2m_wifi_get_mac_address -* @ingroup WLANAPI -* Function to retrieve the current MAC address. The function is blocking until the response is received. -*/ -/**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr) -@param [out] pu8MacAddr - Output MAC address buffer of 6 bytes size. -@pre m2m_wifi_init required to be called before any WIFI/socket function -@see m2m_wifi_get_otp_mac_address -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr); -/**@}*/ -/** @defgroup SetSleepModeFn m2m_wifi_set_sleep_mode - * @ingroup WLANAPI - * This is one of the two synchronous power-save setting functions that - * allow the host MCU application to tweak the system power consumption. Such tweaking can be done through one of two ways: -* 1) Changing the power save mode, to one of the allowed power save modes @ref tenuPowerSaveModes. This is done by setting the first parameter -* 2) Configuring DTIM monitoring: Configuring beacon monitoring parameters by enabling or disabling the reception of broadcast/multicast data. -* this is done by setting the second parameter. - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn); -@param [in] PsTyp - Desired power saving mode. Supported types are enumerated in @ref tenuPowerSaveModes. -@param [in] BcastEn - Broadcast reception enable flag. - If it is 1, the WINC1500 will be awake each DTIM beacon for receiving broadcast traffic. - If it is 0, the WINC1500: disable broadcast traffic. Through this flag the WINC1500 will not wakeup at the DTIM beacon, but it will wakeup depends only - on the the configured Listen Interval. - -@warning The function called once after initialization. - -@see tenuPowerSaveModes - m2m_wifi_get_sleep_mode - m2m_wifi_set_lsn_int - -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn); -/**@}*/ -/** @defgroup WifiRequestSleepFn m2m_wifi_request_sleep - * @ingroup WLANAPI - * Synchronous power-save sleep request function, which requests from the WINC1500 device to sleep in the currenlty configured power save mode as defined - * by the @ref m2m_wifi_set_sleep_mode, for a specific time as defined by the passed in parameter. - * This function should be used in the @ref M2M_PS_MANUAL power save mode only. - * A wake up request is automatically performed by the WINC1500 device when any host driver API function, e.g. Wi-Fi or socket operation is called. - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_request_sleep(uint32 u32SlpReqTime); -@param [in] u32SlpReqTime - Request sleep time in ms - The best recommended sleep duration is left to be determined by the application. Taking into account that if the application sends notifications very rarely, - sleeping for a long time can be a power-efficient decision. In contrast applications that are senstive for long periods of absence can experience - performance degradation in the connection if long sleeping times are used. -@warning The function should be called in @ref M2M_PS_MANUAL power save mode only. As enumerated in @ref tenuPowerSaveModes - It's also important to note that during the sleeping time while in the M2M_PS_MANUAL mode, AP beacon monitoring is bypassed and the wifi-connection may drop if - the sleep period is enlongated. -@see tenuPowerSaveModes - m2m_wifi_set_sleep_mode - -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_request_sleep(uint32 u32SlpReqTime); -/**@}*/ -/** @defgroup GetSleepModeFn m2m_wifi_get_sleep_mode - * @ingroup WLANAPI - * Synchronous power save mode retrieval function. - */ - /**@{*/ -/*! -@fn NMI_API uint8 m2m_wifi_get_sleep_mode(void); -@see tenuPowerSaveModes - m2m_wifi_set_sleep_mode -@return The current operating power saving mode based on the enumerated sleep modes @ref tenuPowerSaveModes. -*/ -NMI_API uint8 m2m_wifi_get_sleep_mode(void); -/**@}*/ -/** @defgroup WifiReqClientCtrlFn m2m_wifi_req_client_ctrl - * @ingroup WLANAPI - * Asynchronous command sending function to the PS Client (An WINC1500 board running the ps_firmware) -* if the PS client send any command it will be received through the @ref M2M_WIFI_RESP_CLIENT_INFO event - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_req_client_ctrl(uint8 cmd); -@brief -@param [in] cmd - Control command sent from PS Server to PS Client (command values defined by the application) -@pre @ref m2m_wifi_req_server_init should be called first -@warning This mode is not supported in the current release. -@see m2m_wifi_req_server_init - M2M_WIFI_RESP_CLIENT_INFO -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_req_client_ctrl(uint8 cmd); -/**@}*/ -/** @defgroup WifiReqServerInit m2m_wifi_req_server_init - * @ingroup WLANAPI - * Synchronous function to initialize the PS Server. - * The WINC1500 supports non secure communication with another WINC1500, -* (SERVER/CLIENT) through one byte command (probe request and probe response) without any connection setup. -* The server mode can't be used with any other modes (STA/P2P/AP) -*/ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_req_server_init(uint8 ch); -@param [in] ch - Server listening channel -@see m2m_wifi_req_client_ctrl -@warning This mode is not supported in the current release. -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_req_server_init(uint8 ch); -/**@}*/ -/** @defgroup WifiSetDeviceNameFn m2m_wifi_set_device_name - * @ingroup WLANAPI - * Sets the WINC device name. The name string is used as a device name in both (P2P) WiFi-Direct mode as well as DHCP hostname (option 12). - * For P2P devices to communicate a device name must be present. If it is not set through this function a default name is assigned. - * The default name is WINC-XX-YY, where XX and YY are the last 2 octets of the OTP MAC address. If OTP (eFuse) is programmed, - * then the default name is WINC-00-00. - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength); -@param [in] pu8DeviceName - A Buffer holding the device name. Device name is a null terminated C string. -@param [in] u8DeviceNameLength - The length of the device name. Should not exceed the maximum device name's length @ref M2M_DEVICE_NAME_MAX (including null character). -@warning The function called once after initialization. - Used for the Wi-Fi Direct (P2P) as well as DHCP client hostname option (12). -@warning Device name shall contain only characters allowed in valid internet host name as defined in RFC 952 and 1123. -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength); -/**@}*/ -/** @defgroup WifiSetLsnIntFn m2m_wifi_set_lsn_int - * @ingroup WLANAPI -* This is one of the two synchronous power-save setting functions that -* allow the host MCU application to tweak the system power consumption. Such tweaking can be done by modifying the -* the Wi-Fi listen interval. The listen interval is how many beacon periods the station can sleep before it wakes up to receive data buffer in AP. -* It is represented in units of AP beacon periods(100ms). -*/ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt * pstrM2mLsnInt); - -@param [in] pstrM2mLsnInt - Structure holding the listen interval configurations. -@pre Function @m2m_wifi_set_sleep_mode shall be called first, to set the power saving mode required. -@warning The function should be called once after initialization. -@see tstrM2mLsnInt - m2m_wifi_set_sleep_mode -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt *pstrM2mLsnInt); -/**@}*/ -/** @defgroup WifiEnableMonitorModeFn m2m_wifi_enable_monitoring_mode - * @ingroup WLANAPI - * Asynchronous Wi-Fi monitoring mode (Promiscuous mode) enabling function. This function enables the monitoring mode, thus allowing two operations to be performed: - * 1) Transmission of manually configured frames, through using the @ref m2m_wifi_send_wlan_pkt function. - * 2) Reception of frames based on a defined filtering criteria - * When the monitoring mode is enabled, reception of all frames that satisfy the filter criteria passed in as a parameter is allowed, on the current wireless channel \n. - * All packets that meet the filtering criteria are passed to the application layer, to be handled by the assigned monitoring callback function \n. - * The monitoring callback function must be implemented before starting the monitoring mode, in-order to handle the packets received \n. - * Registering of the implemented callback function is through the callback pointer @ref tpfAppMonCb in the @ref tstrWifiInitParam structure\n. - * passed to @ref m2m_wifi_init function at initialization. - * - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_enable_monitoring_mode(tstrM2MWifiMonitorModeCtrl *, uint8 *, uint16 , uint16); - * @param [in] pstrMtrCtrl - * Pointer to @ref tstrM2MWifiMonitorModeCtrl structure holding the filtering parameters. - * @param [in] pu8PayloadBuffer - * Pointer to a buffer allocated by the application. The buffer SHALL hold the Data field of - * the WIFI RX Packet (Or a part from it). If it is set to NULL, the WIFI data payload will - * be discarded by the monitoring driver. - * @param [in] u16BufferSize - * The total size of the pu8PayloadBuffer in bytes. - * @param [in] u16DataOffset - * Starting offset in the DATA FIELD of the received WIFI packet. The application may be interested - * in reading specific information from the received packet. It must assign the offset to the starting - * position of it relative to the DATA payload start.\n - * \e Example, \e if \e the \e SSID \e is \e needed \e to \e be \e read \e from \e a \e PROBE \e REQ \e packet, \e the \e u16Offset \e MUST \e be \e set \e to \e 0. - * @warning When This mode is enabled, you can not be connected in any mode (Station, Access Point, or P2P).\n - * @see tstrM2MWifiMonitorModeCtrl - tstrM2MWifiRxPacketInfo - tstrWifiInitParam - tenuM2mScanCh - m2m_wifi_disable_monitoring_mode - m2m_wifi_send_wlan_pkt - m2m_wifi_send_ethernet_pkt - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*\section Example -* The example demonstrates the main function where-by the monitoring enable function is called after the initialization of the driver and the packets are -* handled in the callback function. -* @code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - //Declare receive buffer - uint8 gmgmt[1600]; - - //Callback functions - void wifi_cb(uint8 u8WiFiEvent, void * pvMsg) - { - ; - } - void wifi_monitoring_cb(tstrM2MWifiRxPacketInfo *pstrWifiRxPacket, uint8 *pu8Payload, uint16 u16PayloadSize) - { - if((NULL != pstrWifiRxPacket) && (0 != u16PayloadSize)) { - if(MANAGEMENT == pstrWifiRxPacket->u8FrameType) { - M2M_INFO("***# MGMT PACKET #***\n"); - } else if(DATA_BASICTYPE == pstrWifiRxPacket->u8FrameType) { - M2M_INFO("***# DATA PACKET #***\n"); - } else if(CONTROL == pstrWifiRxPacket->u8FrameType) { - M2M_INFO("***# CONTROL PACKET #***\n"); - } - } - } - - int main() - { - //Register wifi_monitoring_cb - tstrWifiInitParam param; - param.pfAppWifiCb = wifi_cb; - param.pfAppMonCb = wifi_monitoring_cb; - - nm_bsp_init(); - - if(!m2m_wifi_init(¶m)) { - //Enable Monitor Mode with filter to receive all data frames on channel 1 - tstrM2MWifiMonitorModeCtrl strMonitorCtrl = {0}; - strMonitorCtrl.u8ChannelID = M2M_WIFI_CH_1; - strMonitorCtrl.u8FrameType = DATA_BASICTYPE; - strMonitorCtrl.u8FrameSubtype = M2M_WIFI_FRAME_SUB_TYPE_ANY; //Receive any subtype of data frame - m2m_wifi_enable_monitoring_mode(&strMonitorCtrl, gmgmt, sizeof(gmgmt), 0); - - while(1) { - m2m_wifi_handle_events(NULL); - } - } - return 0; - } - * @endcode - */ -NMI_API sint8 m2m_wifi_enable_monitoring_mode(tstrM2MWifiMonitorModeCtrl *pstrMtrCtrl, uint8 *pu8PayloadBuffer, - uint16 u16BufferSize, uint16 u16DataOffset); -/**@}*/ -/** @defgroup WifiDisableMonitorModeFn m2m_wifi_disable_monitoring_mode - * @ingroup WLANAPI - * Synchronous function to disable Wi-Fi monitoring mode (Promiscuous mode). Expected to be called, if the enable monitoring mode is set, but if it was called without enabling - * no negative impact will reside. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_disable_monitoring_mode(void); - * @see m2m_wifi_enable_monitoring_mode - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_disable_monitoring_mode(void); - /**@}*/ - /** @defgroup SendWlanPktFn m2m_wifi_send_wlan_pkt - * @ingroup WLANAPI - * Synchronous function to transmit a WIFI RAW packet while the implementation of this packet is left to the application developer. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_send_wlan_pkt(uint8 *, uint16, uint16); - - * @param [in] pu8WlanPacket - * Pointer to a buffer holding the whole WIFI frame. - * @param [in] u16WlanHeaderLength - * The size of the WIFI packet header ONLY. - * @param [in] u16WlanPktSize - * The size of the whole bytes in packet. - * @see m2m_wifi_enable_monitoring_mode - m2m_wifi_disable_monitoring_mode - * @pre Enable Monitoring mode first using @ref m2m_wifi_enable_monitoring_mode - * @warning This function available in monitoring mode ONLY.\n - * @note Packets are user's responsibility. - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_send_wlan_pkt(uint8 *pu8WlanPacket, uint16 u16WlanHeaderLength, uint16 u16WlanPktSize); -/**@}*/ -/** @defgroup WifiSendEthernetPktFn m2m_wifi_send_ethernet_pkt - * @ingroup WLANAPI - * Synchronous function to transmit an Ethernet packet. Transmit a packet directly in ETHERNET/bypass mode where the TCP/IP stack is disabled and the implementation of this packet is left to the application developer. - * The Ethernet packet composition is left to the application developer. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_send_ethernet_pkt(uint8* pu8Packet,uint16 u16PacketSize) - * @param [in] pu8Packet - * Pointer to a buffer holding the whole Ethernet frame. - * @param [in] u16PacketSize - * The size of the whole bytes in packet. - * @warning This function available in ETHERNET/Bypass mode ONLY. Make sure that application defines @ref ETH_MODE.\n - * @note Packets are the user's responsibility. - * @sa m2m_wifi_enable_mac_mcast,m2m_wifi_set_receive_buffer - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - - */ -NMI_API sint8 m2m_wifi_send_ethernet_pkt(uint8* pu8Packet,uint16 u16PacketSize); -/**@}*/ -/** @defgroup WifiEnableSntpFn m2m_wifi_enable_sntp - * @ingroup WLANAPI - * Synchronous function to enable/disable the native Simple Network Time Protocol(SNTP) client in the WINC1500 firmware.\n - * The SNTP is enabled by default at start-up.The SNTP client at firmware is used to synchronize the system clock to the UTC time from the well known time - * servers (e.g. "time-c.nist.gov"). The SNTP client uses a default update cycle of 1 day. - * The UTC is important for checking the expiration date of X509 certificates used while establishing - * TLS (Transport Layer Security) connections. - * It is highly recommended to use it if there is no other means to get the UTC time. If there is a RTC - * on the host MCU, the SNTP could be disabled and the host should set the system time to the firmware - * using the @ref m2m_wifi_set_system_time function. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_enable_sntp(uint8); - * @param [in] bEnable -* Enabling/Disabling flag - * '0' :disable SNTP - * '1' :enable SNTP - * @see m2m_wifi_set_sytem_time - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_enable_sntp(uint8 bEnable); -/**@}*/ -/** @defgroup WifiSetSystemTime m2m_wifi_set_sytem_time - * @ingroup WLANAPI - * Synchronous function for setting the system time in time/date format (@ref uint32).\n - * The @ref tstrSystemTime structure can be used as a reference to the time values that should be set and pass its value as @ref uint32 - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_set_sytem_time(uint32); - * @param [in] u32UTCSeconds - * Seconds elapsed since January 1, 1900 (NTP Timestamp). - * @see m2m_wifi_enable_sntp - * tstrSystemTime - * @note If there is an RTC on the host MCU, the SNTP could be disabled and the host should set the system time to the firmware - * using the API @ref m2m_wifi_set_sytem_time. - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_set_sytem_time(uint32 u32UTCSeconds); -/**@}*/ -/** @defgroup WifiGetSystemTime m2m_wifi_get_sytem_time - * @ingroup WLANAPI - * Asynchronous function used to retrieve the system time through the use of the response @ref M2M_WIFI_RESP_GET_SYS_TIME. - * Response time retrieved is parsed into the members defined in the structure @ref tstrSystemTime. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_get_sytem_time(void); - * @see m2m_wifi_enable_sntp - tstrSystemTime - * @note Get the system time from the SNTP client - * using the API @ref m2m_wifi_get_sytem_time. - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_get_sytem_time(void); -/**@}*/ -/** @defgroup WifiSetCustInfoElementFn m2m_wifi_set_cust_InfoElement - * @ingroup WLANAPI - * Synchronous function to Add/Remove user-defined Information Element to the WIFIBeacon and Probe Response frames while chip mode is Access Point Mode.\n - * According to the information element layout shown bellow, if it is required to set new data for the information elements, pass in the buffer with the - * information according to the sizes and ordering defined bellow. However, if it's required to delete these IEs, fill the buffer with zeros. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_set_cust_InfoElement(uint8*); - * @param [in] pau8M2mCustInfoElement - * Pointer to Buffer containing the IE to be sent. It is the application developer's responsibility to ensure on the correctness of the information element's ordering passed in. - * @warning - Size of All elements combined must not exceed 255 byte.\n - * - Used in Access Point Mode \n - * @note IEs Format will be follow the following layout:\n - * @verbatim - --------------- ---------- ---------- ------------------- -------- -------- ----------- ---------------------- - | Byte[0] | Byte[1] | Byte[2] | Byte[3:length1+2] | ..... | Byte[n] | Byte[n+1] | Byte[n+2:lengthx+2] | - |---------------|----------|----------|-------------------|-------- --------|-----------|------------------| - | #of all Bytes | IE1 ID | Length1 | Data1(Hex Coded) | ..... | IEx ID | Lengthx | Datax(Hex Coded) | - --------------- ---------- ---------- ------------------- -------- -------- ----------- ---------------------- - * @endverbatim - * @see m2m_wifi_enable_sntp - * tstrSystemTime - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - \section Example - The example demonstrates how the information elements are set using this function. - *@code - * - char elementData[21]; - static char state = 0; // To Add, Append, and Delete - if(0 == state) { //Add 3 IEs - state = 1; - //Total Number of Bytes - elementData[0]=12; - //First IE - elementData[1]=200; elementData[2]=1; elementData[3]='A'; - //Second IE - elementData[4]=201; elementData[5]=2; elementData[6]='B'; elementData[7]='C'; - //Third IE - elementData[8]=202; elementData[9]=3; elementData[10]='D'; elementData[11]=0; elementData[12]='F'; - } else if(1 == state) { - //Append 2 IEs to others, Notice that we keep old data in array starting with\n - //element 13 and total number of bytes increased to 20 - state = 2; - //Total Number of Bytes - elementData[0]=20; - //Fourth IE - elementData[13]=203; elementData[14]=1; elementData[15]='G'; - //Fifth IE - elementData[16]=204; elementData[17]=3; elementData[18]='X'; elementData[19]=5; elementData[20]='Z'; - } else if(2 == state) { //Delete All IEs - state = 0; - //Total Number of Bytes - elementData[0]=0; - } - m2m_wifi_set_cust_InfoElement(elementData); - * @endcode - */ -NMI_API sint8 m2m_wifi_set_cust_InfoElement(uint8* pau8M2mCustInfoElement); - /**@}*/ -/** @defgroup WifiSetPowerProfile m2m_wifi_set_power_profile - * @ingroup WLANAPI - * Change the power profile mode - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode); -@brief -@param [in] u8PwrMode - Change the WINC1500 power profile to different mode based on the enumeration - @ref tenuM2mPwrMode -@pre Must be called after the initializations and before any connection request and can't be changed in run time. -@sa tenuM2mPwrMode - m2m_wifi_init -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode); - /**@}*/ - /** @defgroup WifiSetTxPower m2m_wifi_set_tx_power - * @ingroup WLANAPI - * Set the TX power tenuM2mTxPwrLevel - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel); -@param [in] u8TxPwrLevel - change the TX power based on the enumeration tenuM2mTxPwrLevel -@pre Must be called after the initialization and before any connection request and can't be changed in runtime. -@sa tenuM2mTxPwrLevel - m2m_wifi_init -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel); - /**@}*/ -/** @defgroup WifiEnableFirmware m2m_wifi_enable_firmware_logs -* @ingroup WLANAPI -* Enable or Disable logs in run time (Disabling Firmware logs will -* enhance the firmware start-up time and performance) -*/ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable); -@param [in] u8Enable - Set 1 to enable the logs, 0 for disable -@pre Must be called after intialization through the following function @ref m2m_wifi_init -@sa __DISABLE_FIRMWARE_LOGS__ (build option to disable logs from initializations) - m2m_wifi_init -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable); - /**@}*/ - /** @defgroup WifiSetBatteryVoltage m2m_wifi_set_battery_voltage -* @ingroup WLANAPI -* Set the battery voltage to update the firmware calculations -*/ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_set_battery_voltage(uint8 u8BattVolt) -@brief Set the battery voltage to update the firmware calculations -@param [in] dbBattVolt - Battery Volt in double -@pre Must be called after intialization through the following function @ref m2m_wifi_init -@sa m2m_wifi_init -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -sint8 m2m_wifi_set_battery_voltage(uint16 u16BattVoltx100); - /**@}*/ - /** @defgroup WifiSetGains m2m_wifi_set_gains -* @ingroup WLANAPI -* Set the chip gains mainly (PPA for 11b/11gn) -*/ - /**@{*/ -/*! -@fn sint8 m2m_wifi_set_gains(tstrM2mWifiGainsParams* pstrM2mGain); -@brief Set the chip PPA gain for 11b/11gn -@param [in] pstrM2mGain - tstrM2mWifiGainsParams contain gain parmaters as implemnted in rf document -@pre Must be called after intialization through the following function @ref m2m_wifi_init -@sa m2m_wifi_init -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -sint8 m2m_wifi_set_gains(tstrM2mWifiGainsParams* pstrM2mGain); - /**@}*/ -/** @defgroup WifiGetFirmwareVersion m2m_wifi_get_firmware_version -* @ingroup WLANAPI -* Get Firmware version info as defined in the structure @ref tstrM2mRev. -*/ - /**@{*/ -/*! -@fn m2m_wifi_get_firmware_version(tstrM2mRev* pstrRev) -@param [out] M2mRev - Pointer to the structure @ref tstrM2mRev that contains the firmware version parameters -@pre Must be called after intialization through the following function @ref m2m_wifi_init -@sa m2m_wifi_init -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -sint8 m2m_wifi_get_firmware_version(tstrM2mRev *pstrRev); -/**@}*/ -#ifdef ETH_MODE -/** @defgroup WifiEnableMacMcastFn m2m_wifi_enable_mac_mcast - * @ingroup WLANAPI - * Synchronous function for filtering received MAC addresses from certain MAC address groups. - * This function allows the addtion/removal of certain MAC addresses, used in the multicast filter. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8 *, uint8); - * @brief - * @param [in] pu8MulticastMacAddress - * Pointer to MAC address - * @param [in] u8AddRemove - * A flag to add or remove the MAC ADDRESS, based on the following values: - * - 0 : remove MAC address - * - 1 : add MAC address - * @warning This function is available in ETHERNET/bypass mode ONLY. Make sure that the application defines @ref ETH_MODE.\n - * @note Maximum number of MAC addresses that could be added is 8. - * @sa m2m_wifi_set_receive_buffer, m2m_wifi_send_ethernet_pkt - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8* pu8MulticastMacAddress, uint8 u8AddRemove); -/**@}*/ -/** @defgroup SetReceiveBufferFn m2m_wifi_set_receive_buffer - * @ingroup WLANAPI - * Synchronous function for setting or modifying the receiver buffer's length. - * In the ETHERNET/bypass mode the application should define a callback of type @ref tpfAppEthCb, through which the application handles the received - * ethernet frames. It is through this callback function that the user can dynamically modify the length of the currently used receiver buffer. - *@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_set_receive_buffer(void *, uint16); - - * @param [in] pvBuffer - * Pointer to Buffer to receive data. - * NULL pointer causes a negative error @ref M2M_ERR_FAIL. - * - * @param [in] u16BufferLen - * Length of data to be received. Maximum length of data should not exceed the size defined by TCP/IP - * defined as @ref SOCKET_BUFFER_MAX_LENGTH - * - * @warning This function is available in the Ethernet/bypass mode ONLY. Make sure that the application defines @ref ETH_MODE.\n - * @sa m2m_wifi_enable_mac_mcast,m2m_wifi_send_ethernet_pkt - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_set_receive_buffer(void* pvBuffer,uint16 u16BufferLen); -/**@}*/ -#endif /* ETH_MODE */ -/** @defgroup GetPrngBytes m2m_wifi_prng_get_random_bytes - * @ingroup WLANAPI - * Asynchronous function for retrieving from the firmware a pseudo-random set of bytes as specifed in the size passed in as a parameter. - * The registered wifi-cb function retrieves the random bytes through the response @ref M2M_WIFI_RESP_GET_PRNG - *@{*/ -/*! - * @fn sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PRNGBuff,uint16 u16PRNGSize) - * @param [out] pu8PrngBuff - * Pointer to a buffer to receive data. - * @param [in] u16PrngSize - * Request size in bytes - *@warning Size greater than the maximum specified (@ref M2M_BUFFER_MAX_SIZE - sizeof(tstrPrng)) - * causes a negative error @ref M2M_ERR_FAIL. - *@see tstrPrng - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PrngBuff,uint16 u16PrngSize); -/**@}*/ -#ifdef __cplusplus -} -#endif -#endif /* __M2M_WIFI_H__ */ - diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ate_mode.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ate_mode.c deleted file mode 100644 index beb1af8..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ate_mode.c +++ /dev/null @@ -1,826 +0,0 @@ -/** - * - * \file - * - * \brief NMC1500 Peripherials Application Interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifdef _M2M_ATE_FW_ -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#include "driver/include/m2m_ate_mode.h" -#include "driver/source/nmasic.h" -#include "driver/source/nmdrv.h" -#include "m2m_hif.h" -#include "driver/source/nmbus.h" -#include "bsp/include/nm_bsp.h" - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#define rInterrupt_CORTUS_0 (0x10a8) -#define rInterrupt_CORTUS_1 (0x10ac) -#define rInterrupt_CORTUS_2 (0x10b0) - -#define rBurstTx_NMI_TX_RATE (0x161d00) -#define rBurstTx_NMI_NUM_TX_FRAMES (0x161d04) -#define rBurstTx_NMI_TX_FRAME_LEN (0x161d08) -#define rBurstTx_NMI_TX_CW_PARAM (0x161d0c) -#define rBurstTx_NMI_TX_GAIN (0x161d10) -#define rBurstTx_NMI_TX_DPD_CTRL (0x161d14) -#define rBurstTx_NMI_USE_PMU (0x161d18) -#define rBurstTx_NMI_TEST_CH (0x161d1c) -#define rBurstTx_NMI_TX_PHY_CONT (0x161d20) -#define rBurstTx_NMI_TX_CW_MODE (0x161d24) -#define rBurstTx_NMI_TEST_XO_OFF (0x161d28) -#define rBurstTx_NMI_USE_EFUSE_XO_OFF (0x161d2c) - -#define rBurstTx_NMI_MAC_FILTER_ENABLE_DA (0x161d30) -#define rBurstTx_NMI_MAC_ADDR_LO_PEER (0x161d34) -#define rBurstTx_NMI_MAC_ADDR_LO_SELF (0x161d38) -#define rBurstTx_NMI_MAC_ADDR_HI_PEER (0x161d3c) -#define rBurstTx_NMI_MAC_ADDR_HI_SELF (0x161d40) -#define rBurstTx_NMI_RX_PKT_CNT_SUCCESS (0x161d44) -#define rBurstTx_NMI_RX_PKT_CNT_FAIL (0x161d48) -#define rBurstTx_NMI_SET_SELF_MAC_ADDR (0x161d4c) -#define rBurstTx_NMI_MAC_ADDR_LO_SA (0x161d50) -#define rBurstTx_NMI_MAC_ADDR_HI_SA (0x161d54) -#define rBurstTx_NMI_MAC_FILTER_ENABLE_SA (0x161d58) - -#define rBurstRx_NMI_RX_ALL_PKTS_CONT (0x9898) -#define rBurstRx_NMI_RX_ERR_PKTS_CONT (0x988c) - -#define TX_DGAIN_MAX_NUM_REGS (4) -#define TX_DGAIN_REG_BASE_ADDRESS (0x1240) -#define TX_GAIN_CODE_MAX_NUM_REGS (3) -#define TX_GAIN_CODE_BASE_ADDRESS (0x1250) -#define TX_PA_MAX_NUM_REGS (3) -#define TX_PA_BASE_ADDRESS (0x1e58) -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -VARIABLES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -volatile static uint8 gu8AteIsRunning = 0; /*!< ATE firmware status, 1 means ATE is running otherwise stopped */ -volatile static uint8 gu8RxState = 0; /*!< RX status, 1 means Rx is running otherwise stopped */ -volatile static uint8 gu8TxState = 0; /*!< TX status, 1 means Tx is running otherwise stopped */ -volatile static uint32 gaAteFwTxRates[M2M_ATE_MAX_NUM_OF_RATES] = -{ - 0x01, 0x02, 0x05, 0x0B, /*B-Rats*/ - 0x06, 0x09, 0x0C, 0x12, 0x18, 0x24, 0x30, 0x36, /*G-Rats*/ - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87 /*N-Rats*/ -}; - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -STATIC FUNCTIONS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -static void m2m_ate_set_rx_status(uint8 u8Value) -{ - gu8RxState = u8Value; -} - -static void m2m_ate_set_tx_status(uint8 u8Value) -{ - gu8TxState = u8Value; -} - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION IMPLEMENTATION -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/*! -@fn \ - sint8 m2m_ate_init(void); - -@brief - This function used to download ATE firmware from flash and start it - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_init(void) -{ - sint8 s8Ret = M2M_SUCCESS; - uint8 u8WifiMode = M2M_WIFI_MODE_ATE_HIGH; - - s8Ret = nm_drv_init(&u8WifiMode); - - return s8Ret; -} - -/*! -@fn \ - sint8 m2m_ate_init(tstrM2mAteInit *pstrInit); - -@brief - This function used to download ATE firmware from flash and start it - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_init_param(tstrM2mAteInit *pstrInit) -{ - sint8 s8Ret = M2M_SUCCESS; - - s8Ret = nm_drv_init((void*)&pstrInit->u8RxPwrMode); - - return s8Ret; -} - -/*! -@fn \ - sint8 m2m_ate_deinit(void); - -@brief - De-Initialization of ATE firmware mode - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_deinit(void) -{ - return nm_drv_deinit(NULL); -} - -/*! -@fn \ - sint8 m2m_ate_set_fw_state(uint8); - -@brief - This function used to change ATE firmware status from running to stopped or vice versa. - -@param [in] u8State - Required state of ATE firmware, one of \ref tenuM2mAteFwState enumeration values. -@return - The function SHALL return 0 for success and a negative value otherwise. -\sa - m2m_ate_init -*/ -sint8 m2m_ate_set_fw_state(uint8 u8State) -{ - sint8 s8Ret = M2M_SUCCESS; - uint32_t u32Val = 0; - - if((M2M_ATE_FW_STATE_STOP == u8State) && (M2M_ATE_FW_STATE_STOP != gu8AteIsRunning)) - { - u32Val = nm_read_reg(rNMI_GLB_RESET); - u32Val &= ~(1 << 10); - s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val); - gu8AteIsRunning = M2M_ATE_FW_STATE_STOP; - } - else if((M2M_ATE_FW_STATE_RUN == u8State) && (M2M_ATE_FW_STATE_RUN != gu8AteIsRunning)) - { - /* 0x1118[0]=0 at power-on-reset: pad-based control. */ - /* Switch cortus reset register to register control. 0x1118[0]=1. */ - u32Val = nm_read_reg(rNMI_BOOT_RESET_MUX); - u32Val |= (1 << 0); - s8Ret = nm_write_reg(rNMI_BOOT_RESET_MUX, u32Val); - if(M2M_SUCCESS != s8Ret) - { - goto __EXIT; - } - /** - Write the firmware download complete magic value 0x10ADD09E at - location 0xFFFF000C (Cortus map) or C000C (AHB map). - This will let the boot-rom code execute from RAM. - **/ - s8Ret = nm_write_reg(0xc0000, 0x71); - if(M2M_SUCCESS != s8Ret) - { - goto __EXIT; - } - - u32Val = nm_read_reg(rNMI_GLB_RESET); - if((u32Val & (1ul << 10)) == (1ul << 10)) - { - u32Val &= ~(1ul << 10); - s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val); - if(M2M_SUCCESS != s8Ret) - { - goto __EXIT; - } - } - - u32Val |= (1ul << 10); - s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val); - if(M2M_SUCCESS != s8Ret) - { - goto __EXIT; - } - gu8AteIsRunning = M2M_ATE_FW_STATE_RUN; - } - else - { - s8Ret = M2M_ATE_ERR_UNHANDLED_CASE; - } - -__EXIT: - if((M2M_SUCCESS == s8Ret) && (M2M_ATE_FW_STATE_RUN == gu8AteIsRunning)) - { - nm_bsp_sleep(500); /*wait for ATE firmware start up*/ - } - return s8Ret; -} - -/*! -@fn \ - sint8 m2m_ate_get_fw_state(uint8); - -@brief - This function used to return status of ATE firmware. - -@return - The function SHALL return status of ATE firmware, one of \ref tenuM2mAteFwState enumeration values. -\sa - m2m_ate_init, m2m_ate_set_fw_state -*/ -sint8 m2m_ate_get_fw_state(void) -{ - return gu8AteIsRunning; -} - -/*! -@fn \ - uint32 m2m_ate_get_tx_rate(uint8); - -@brief - This function used to return value of TX rate required by application developer. - -@param [in] u8Index - Index of required rate , one of \ref tenuM2mAteTxIndexOfRates enumeration values. -@return - The function SHALL return 0 for in case of failure otherwise selected rate value. -\sa - tenuM2mAteTxIndexOfRates -*/ -uint32 m2m_ate_get_tx_rate(uint8 u8Index) -{ - if(M2M_ATE_MAX_NUM_OF_RATES <= u8Index) - { - return 0; - } - return gaAteFwTxRates[u8Index]; -} - -/*! -@fn \ - sint8 m2m_ate_get_tx_status(void); - -@brief - This function used to return status of TX test case either running or stopped. - -@return - The function SHALL return status of ATE firmware, 1 if TX is running otherwise 0. -\sa - m2m_ate_start_tx, m2m_ate_stop_tx -*/ -sint8 m2m_ate_get_tx_status(void) -{ - return gu8TxState; -} - -/*! -@fn \ - sint8 m2m_ate_start_tx(tstrM2mAteTx *) - -@brief - This function used to start TX test case. - -@param [in] strM2mAteTx - Type of \ref tstrM2mAteTx, with the values required to enable TX test case. You must use \ref m2m_ate_init first. -@return - The function SHALL return 0 for success and a negative value otherwise. -\sa - m2m_ate_init, m2m_ate_stop_tx, m2m_ate_get_tx_status -*/ -sint8 m2m_ate_start_tx(tstrM2mAteTx * strM2mAteTx) -{ - sint8 s8Ret = M2M_SUCCESS; - uint8 u8LoopCntr = 0; - uint32_t val32; - - - if(NULL == strM2mAteTx) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - if(0 != m2m_ate_get_tx_status()) - { - s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING; - goto __EXIT; - } - - if(0 != m2m_ate_get_rx_status()) - { - s8Ret = M2M_ATE_ERR_RX_ALREADY_RUNNING; - goto __EXIT; - } - - if( (strM2mAteTx->channel_num < M2M_ATE_CHANNEL_1) || - (strM2mAteTx->channel_num > M2M_ATE_CHANNEL_14) || - (strM2mAteTx->tx_gain_sel < M2M_ATE_TX_GAIN_DYNAMIC) || - (strM2mAteTx->tx_gain_sel > M2M_ATE_TX_GAIN_TELEC) || - (strM2mAteTx->frame_len > M2M_ATE_MAX_FRAME_LENGTH) || - (strM2mAteTx->frame_len < M2M_ATE_MIN_FRAME_LENGTH) - ) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - if( (strM2mAteTx->duty_cycle < M2M_ATE_TX_DUTY_MAX_VALUE /*1*/) || - (strM2mAteTx->duty_cycle > M2M_ATE_TX_DUTY_MIN_VALUE /*10*/ ) || - (strM2mAteTx->dpd_ctrl < M2M_ATE_TX_DPD_DYNAMIC) || - (strM2mAteTx->dpd_ctrl > M2M_ATE_TX_DPD_ENABLED) || - (strM2mAteTx->use_pmu > M2M_ATE_PMU_ENABLE) || - (strM2mAteTx->phy_burst_tx < M2M_ATE_TX_SRC_MAC) || - (strM2mAteTx->phy_burst_tx > M2M_ATE_TX_SRC_PHY) || - (strM2mAteTx->cw_tx < M2M_ATE_TX_MODE_NORM) || - (strM2mAteTx->cw_tx > M2M_ATE_TX_MODE_CW) - ) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - for(u8LoopCntr=0; u8LoopCntrdata_rate) - { - break; - } - } - - if(M2M_ATE_MAX_NUM_OF_RATES == u8LoopCntr) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - - - s8Ret += nm_write_reg(rBurstTx_NMI_USE_PMU, strM2mAteTx->use_pmu); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_PHY_CONT, strM2mAteTx->phy_burst_tx); - s8Ret += nm_write_reg(rBurstTx_NMI_NUM_TX_FRAMES, strM2mAteTx->num_frames); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_GAIN, strM2mAteTx->tx_gain_sel); - s8Ret += nm_write_reg(rBurstTx_NMI_TEST_CH, strM2mAteTx->channel_num); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_FRAME_LEN, strM2mAteTx->frame_len); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_CW_PARAM, strM2mAteTx->duty_cycle); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_DPD_CTRL, strM2mAteTx->dpd_ctrl); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_RATE, strM2mAteTx->data_rate); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_CW_MODE, strM2mAteTx->cw_tx); - s8Ret += nm_write_reg(rBurstTx_NMI_TEST_XO_OFF, strM2mAteTx->xo_offset_x1000); - s8Ret += nm_write_reg(rBurstTx_NMI_USE_EFUSE_XO_OFF, strM2mAteTx->use_efuse_xo_offset); - - val32 = strM2mAteTx->peer_mac_addr[5] << 0; - val32 |= strM2mAteTx->peer_mac_addr[4] << 8; - val32 |= strM2mAteTx->peer_mac_addr[3] << 16; - nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_PEER, val32 ); - - val32 = strM2mAteTx->peer_mac_addr[2] << 0; - val32 |= strM2mAteTx->peer_mac_addr[1] << 8; - val32 |= strM2mAteTx->peer_mac_addr[0] << 16; - nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_PEER, val32 ); - - if(M2M_SUCCESS == s8Ret) - { - s8Ret += nm_write_reg(rInterrupt_CORTUS_0, 1); /*Interrupt Cortus*/ - m2m_ate_set_tx_status(1); - nm_bsp_sleep(200); /*Recommended*/ - } - -__EXIT: - return s8Ret; -} - -/*! -@fn \ - sint8 m2m_ate_stop_tx(void) - -@brief - This function used to stop TX test case. - -@return - The function SHALL return 0 for success and a negative value otherwise. -\sa - m2m_ate_init, m2m_ate_start_tx, m2m_ate_get_tx_status -*/ -sint8 m2m_ate_stop_tx(void) -{ - sint8 s8Ret = M2M_SUCCESS; - - s8Ret = nm_write_reg(rInterrupt_CORTUS_1, 1); - if(M2M_SUCCESS == s8Ret) - { - m2m_ate_set_tx_status(0); - } - - return s8Ret; -} - -/*! -@fn \ - sint8 m2m_ate_get_rx_status(uint8); - -@brief - This function used to return status of RX test case either running or stopped. - -@return - The function SHALL return status of ATE firmware, 1 if RX is running otherwise 0. -\sa - m2m_ate_start_rx, m2m_ate_stop_rx -*/ -sint8 m2m_ate_get_rx_status(void) -{ - return gu8RxState; -} - -/*! -@fn \ - sint8 m2m_ate_start_rx(tstrM2mAteRx *) - -@brief - This function used to start RX test case. - -@param [in] strM2mAteRx - Type of \ref tstrM2mAteRx, with the values required to enable RX test case. You must use \ref m2m_ate_init first. -@return - The function SHALL return 0 for success and a negative value otherwise. -\sa - m2m_ate_init, m2m_ate_stop_rx, m2m_ate_get_rx_status -*/ -sint8 m2m_ate_start_rx(tstrM2mAteRx * strM2mAteRxStr) -{ - sint8 s8Ret = M2M_SUCCESS; - uint32 val32; - if(NULL == strM2mAteRxStr) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - if(0 != m2m_ate_get_tx_status()) - { - s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING; - goto __EXIT; - } - - if(0 != m2m_ate_get_rx_status()) - { - s8Ret = M2M_ATE_ERR_RX_ALREADY_RUNNING; - goto __EXIT; - } - - if( (strM2mAteRxStr->channel_num < M2M_ATE_CHANNEL_1) || - (strM2mAteRxStr->channel_num > M2M_ATE_CHANNEL_14)|| - (strM2mAteRxStr->use_pmu > M2M_ATE_PMU_ENABLE) - ) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - s8Ret += nm_write_reg(rBurstTx_NMI_TEST_CH, strM2mAteRxStr->channel_num); - s8Ret += nm_write_reg(rBurstTx_NMI_USE_PMU, strM2mAteRxStr->use_pmu); - s8Ret += nm_write_reg(rBurstTx_NMI_TEST_XO_OFF, strM2mAteRxStr->xo_offset_x1000); - s8Ret += nm_write_reg(rBurstTx_NMI_USE_EFUSE_XO_OFF, strM2mAteRxStr->use_efuse_xo_offset); - - if(strM2mAteRxStr->override_self_mac_addr) - { - val32 = strM2mAteRxStr->self_mac_addr[5] << 0; - val32 |= strM2mAteRxStr->self_mac_addr[4] << 8; - val32 |= strM2mAteRxStr->self_mac_addr[3] << 16; - nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_SELF, val32 ); - - val32 = strM2mAteRxStr->self_mac_addr[2] << 0; - val32 |= strM2mAteRxStr->self_mac_addr[1] << 8; - val32 |= strM2mAteRxStr->self_mac_addr[0] << 16; - nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_SELF, val32 ); - } - - if(strM2mAteRxStr->mac_filter_en_sa) - { - val32 = strM2mAteRxStr->peer_mac_addr[5] << 0; - val32 |= strM2mAteRxStr->peer_mac_addr[4] << 8; - val32 |= strM2mAteRxStr->peer_mac_addr[3] << 16; - nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_SA, val32 ); - - val32 = strM2mAteRxStr->peer_mac_addr[2] << 0; - val32 |= strM2mAteRxStr->peer_mac_addr[1] << 8; - val32 |= strM2mAteRxStr->peer_mac_addr[0] << 16; - nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_SA, val32 ); - } - - nm_write_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_DA, strM2mAteRxStr->mac_filter_en_da); - nm_write_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_SA, strM2mAteRxStr->mac_filter_en_sa); - nm_write_reg(rBurstTx_NMI_SET_SELF_MAC_ADDR, strM2mAteRxStr->override_self_mac_addr); - - if(M2M_SUCCESS == s8Ret) - { - s8Ret += nm_write_reg(rInterrupt_CORTUS_2, 1); /*Interrupt Cortus*/ - m2m_ate_set_rx_status(1); - nm_bsp_sleep(10); /*Recommended*/ - } - -__EXIT: - return s8Ret; -} - -/*! -@fn \ - sint8 m2m_ate_stop_rx(void) - -@brief - This function used to stop RX test case. - -@return - The function SHALL return 0 for success and a negative value otherwise. -\sa - m2m_ate_init, m2m_ate_start_rx, m2m_ate_get_rx_status -*/ -sint8 m2m_ate_stop_rx(void) -{ - m2m_ate_set_rx_status(0); - nm_bsp_sleep(200); /*Recommended*/ - return M2M_SUCCESS; -} - -/*! -@fn \ - sint8 m2m_ate_read_rx_status(tstrM2mAteRxStatus *) - -@brief - This function used to read RX statistics from ATE firmware. - -@param [out] strM2mAteRxStatus - Type of \ref tstrM2mAteRxStatus used to save statistics of RX test case. You must use \ref m2m_ate_start_rx first. -@return - The function SHALL return 0 for success and a negative value otherwise. -\sa - m2m_ate_init, m2m_ate_start_rx -*/ -sint8 m2m_ate_read_rx_status(tstrM2mAteRxStatus *strM2mAteRxStatus) -{ - sint8 s8Ret = M2M_SUCCESS; - - if(NULL == strM2mAteRxStatus) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - if(0 != m2m_ate_get_tx_status()) - { - s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING; - goto __EXIT; - } - - if (nm_read_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_DA) || nm_read_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_SA)) - { - strM2mAteRxStatus->num_rx_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_SUCCESS) + nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_FAIL); - strM2mAteRxStatus->num_good_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_SUCCESS); - strM2mAteRxStatus->num_err_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_FAIL); - } - else - { - strM2mAteRxStatus->num_rx_pkts = nm_read_reg(rBurstRx_NMI_RX_ALL_PKTS_CONT) + nm_read_reg(0x989c); - strM2mAteRxStatus->num_err_pkts = nm_read_reg(rBurstRx_NMI_RX_ERR_PKTS_CONT); - strM2mAteRxStatus->num_good_pkts = strM2mAteRxStatus->num_rx_pkts - strM2mAteRxStatus->num_err_pkts; - } - -__EXIT: - return s8Ret; -} -/*! -@fn \ - sint8 m2m_ate_set_dig_gain(double dGaindB) - -@brief - This function is used to set the digital gain - -@param [in] double dGaindB - The digital gain value required to be set. -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_set_dig_gain(double dGaindB) -{ - uint32_t dGain, val32; - dGain = (uint32_t)(pow(10, dGaindB/20.0) * 1024.0); - - val32 = nm_read_reg(0x160cd0); - val32 &= ~(0x1ffful << 0); - val32 |= (((uint32_t)dGain) << 0); - nm_write_reg(0x160cd0, val32); - return M2M_SUCCESS; -} -/*! -@fn \ - sint8 m2m_ate_get_dig_gain(double * dGaindB) - -@brief - This function is used to get the digital gain - -@param [out] double * dGaindB - The retrieved digital gain value obtained from HW registers in dB. -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_get_dig_gain(double * dGaindB) -{ - uint32 dGain, val32; - - if(!dGaindB) return M2M_ERR_INVALID_ARG; - - val32 = nm_read_reg(0x160cd0); - - dGain = (val32 >> 0) & 0x1ffful; - *dGaindB = 20.0*log10((double)dGain / 1024.0); - - return M2M_SUCCESS; -} -/*! -@fn \ - void m2m_ate_set_pa_gain(uint8 gain_db) - -@brief - This function is used to set the PA gain (18/15/12/9/6/3/0 only) - -@param [in] uint8 gain_db - PA gain level allowed (18/15/12/9/6/3/0 only) - -*/ -void m2m_ate_set_pa_gain(uint8 gain_db) -{ - uint32 PA_1e9c; - uint8 aGain[] = { - /* "0 dB" */ 0x00, - /* "3 dB" */ 0x01, - /* "6 dB" */ 0x03, - /* "9 dB" */ 0x07, - /* "12 dB" */ 0x0f, - /* "15 dB" */ 0x1f, - /* "18 dB" */ 0x3f }; - /* The variable PA gain is valid only for High power mode */ - PA_1e9c = nm_read_reg(0x1e9c); - /* TX bank 0. */ - PA_1e9c &= ~(0x3ful << 8); - PA_1e9c |= (((uint32)aGain[gain_db/3] & 0x3f) << 8); - nm_write_reg(0x1e9c, PA_1e9c); -} -/*! -@fn \ - sint8 m2m_ate_get_pa_gain(double *paGaindB) - -@brief - This function is used to get the PA gain - -@param [out] double *paGaindB - The retrieved PA gain value obtained from HW registers in dB. -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_get_pa_gain(double *paGaindB) -{ - uint32 val32, paGain; - uint32 m_cmbPAGainStep; - - if(!paGaindB) - return M2M_ERR_INVALID_ARG; - - val32 = nm_read_reg(0x1e9c); - - paGain = (val32 >> 8) & 0x3f; - - switch(paGain){ - case 0x1: - m_cmbPAGainStep = 5; - break; - case 0x3: - m_cmbPAGainStep = 4; - break; - case 0x7: - m_cmbPAGainStep = 3; - break; - case 0xf: - m_cmbPAGainStep = 2; - break; - case 0x1f: - m_cmbPAGainStep = 1; - break; - case 0x3f: - m_cmbPAGainStep = 0; - break; - default: - m_cmbPAGainStep = 0; - break; - } - - *paGaindB = 18 - m_cmbPAGainStep*3; - - return M2M_SUCCESS; -} -/*! -@fn \ - sint8 m2m_ate_get_ppa_gain(double * ppaGaindB) - -@brief - This function is used to get the PPA gain - -@param [out] uint32 * ppaGaindB - The retrieved PPA gain value obtained from HW registers in dB. -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_get_ppa_gain(double * ppaGaindB) -{ - uint32 val32, ppaGain, m_cmbPPAGainStep; - - if(!ppaGaindB) return M2M_ERR_INVALID_ARG; - - val32 = nm_read_reg(0x1ea0); - - ppaGain = (val32 >> 5) & 0x7; - - switch(ppaGain){ - case 0x1: - m_cmbPPAGainStep = 2; - break; - case 0x3: - m_cmbPPAGainStep = 1; - break; - case 0x7: - m_cmbPPAGainStep = 0; - break; - default: - m_cmbPPAGainStep = 3; - break; - } - - *ppaGaindB = 9 - m_cmbPPAGainStep*3; - - - return M2M_SUCCESS; -} -/*! -@fn \ - sint8 m2m_ate_get_tot_gain(double * totGaindB) - -@brief - This function is used to calculate the total gain - -@param [out] double * totGaindB - The retrieved total gain value obtained from calculations made based on the digital gain, PA and PPA gain values. -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_get_tot_gain(double * totGaindB) -{ - double dGaindB, paGaindB, ppaGaindB; - - if(!totGaindB) return M2M_ERR_INVALID_ARG; - - m2m_ate_get_pa_gain(&paGaindB); - m2m_ate_get_ppa_gain(&ppaGaindB); - m2m_ate_get_dig_gain(&dGaindB); - - *totGaindB = dGaindB + paGaindB + ppaGaindB; - - return M2M_SUCCESS; -} - -#endif //_M2M_ATE_FW_ \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_crypto.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_crypto.c deleted file mode 100644 index 9ac7711..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_crypto.c +++ /dev/null @@ -1,1010 +0,0 @@ -/** - * - * \file - * - * \brief WINC Crypto module. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "driver/include/m2m_crypto.h" -#include "driver/source/nmbus.h" -#include "driver/source/nmasic.h" - -#ifdef CONF_CRYPTO_HW - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*======*======*======*======*======*=======* -* WINC SHA256 HW Engine Register Definition * -*======*======*======*======*======*========*/ - -#define SHA_BLOCK_SIZE (64) - -#define SHARED_MEM_BASE (0xd0000) - - -#define SHA256_MEM_BASE (0x180000UL) -#define SHA256_ENGINE_ADDR (0x180000ul) - -/* SHA256 Registers */ -#define SHA256_CTRL (SHA256_MEM_BASE+0x00) -#define SHA256_CTRL_START_CALC_MASK (NBIT0) -#define SHA256_CTRL_START_CALC_SHIFT (0) -#define SHA256_CTRL_PREPROCESS_MASK (NBIT1) -#define SHA256_CTRL_PREPROCESS_SHIFT (1) -#define SHA256_CTRL_HASH_HASH_MASK (NBIT2) -#define SHA256_CTRL_HASH_HASH_SHIFT (2) -#define SHA256_CTRL_INIT_SHA256_STATE_MASK (NBIT3) -#define SHA256_CTRL_INIT_SHA256_STATE_SHIFT (3) -#define SHA256_CTRL_WR_BACK_HASH_VALUE_MASK (NBIT4) -#define SHA256_CTRL_WR_BACK_HASH_VALUE_SHIFT (4) -#define SHA256_CTRL_FORCE_SHA256_QUIT_MASK (NBIT5) -#define SHA256_CTRL_FORCE_SHA256_QUIT_SHIFT (5) - -#define SHA256_REGS_SHA256_CTRL_AHB_BYTE_REV_EN (NBIT6) -#define SHA256_REGS_SHA256_CTRL_RESERVED (NBIT7) -#define SHA256_REGS_SHA256_CTRL_CORE_TO_AHB_CLK_RATIO (NBIT8+ NBIT9+ NBIT10) -#define SHA256_REGS_SHA256_CTRL_CORE_TO_AHB_CLK_RATIO_MASK (NBIT2+ NBIT1+ NBIT0) -#define SHA256_REGS_SHA256_CTRL_CORE_TO_AHB_CLK_RATIO_SHIFT (8) -#define SHA256_REGS_SHA256_CTRL_RESERVED_11 (NBIT11) -#define SHA256_REGS_SHA256_CTRL_SHA1_CALC (NBIT12) -#define SHA256_REGS_SHA256_CTRL_PBKDF2_SHA1_CALC (NBIT13) - - -#define SHA256_START_RD_ADDR (SHA256_MEM_BASE+0x04UL) -#define SHA256_DATA_LENGTH (SHA256_MEM_BASE+0x08UL) -#define SHA256_START_WR_ADDR (SHA256_MEM_BASE+0x0cUL) -#define SHA256_COND_CHK_CTRL (SHA256_MEM_BASE+0x10) -#define SHA256_COND_CHK_CTRL_HASH_VAL_COND_CHK_MASK (NBIT1 | NBIT0) -#define SHA256_COND_CHK_CTRL_HASH_VAL_COND_CHK_SHIFT (0) -#define SHA256_COND_CHK_CTRL_STEP_VAL_MASK (NBIT6 | NBIT5 | NBIT4 | NBIT3 | NBIT2) -#define SHA256_COND_CHK_CTRL_STEP_VAL_SHIFT (2) -#define SHA256_COND_CHK_CTRL_COND_CHK_RESULT_MASK (NBIT7) -#define SHA256_COND_CHK_CTRL_COND_CHK_RESULT_SHIFT (7) - -#define SHA256_MOD_DATA_RANGE (SHA256_MEM_BASE+0x14) -#define SHA256_MOD_DATA_RANGE_ST_BYTE_2_ADD_STP_MASK (NBIT24-1) -#define SHA256_MOD_DATA_RANGE_ST_BYTE_2_ADD_STP_SHIFT (0) -#define SHA256_MOD_DATA_RANGE_MOD_DATA_LEN_MASK (NBIT24 | NBIT25| NBIT26) -#define SHA256_MOD_DATA_RANGE_MOD_DATA_LEN_SHIFT (24) - - -#define SHA256_COND_CHK_STS_1 (SHA256_MEM_BASE+0x18) -#define SHA256_COND_CHK_STS_2 (SHA256_MEM_BASE+0x1c) -#define SHA256_DONE_INTR_ENABLE (SHA256_MEM_BASE+0x20) -#define SHA256_DONE_INTR_STS (SHA256_MEM_BASE+0x24) -#define SHA256_TARGET_HASH_H1 (SHA256_MEM_BASE+0x28) -#define SHA256_TARGET_HASH_H2 (SHA256_MEM_BASE+0x2c) -#define SHA256_TARGET_HASH_H3 (SHA256_MEM_BASE+0x30) -#define SHA256_TARGET_HASH_H4 (SHA256_MEM_BASE+0x34) -#define SHA256_TARGET_HASH_H5 (SHA256_MEM_BASE+0x38) -#define SHA256_TARGET_HASH_H6 (SHA256_MEM_BASE+0x3c) -#define SHA256_TARGET_HASH_H7 (SHA256_MEM_BASE+0x40) -#define SHA256_TARGET_HASH_H8 (SHA256_MEM_BASE+0x44) - -/*======*======*======*======*======*=======* -* WINC BIGINT HW Engine Register Definition * -*======*======*======*======*======*========*/ - - -#define BIGINT_ENGINE_ADDR (0x180080ul) -#define BIGINT_VERSION (BIGINT_ENGINE_ADDR + 0x00) - -#define BIGINT_MISC_CTRL (BIGINT_ENGINE_ADDR + 0x04) -#define BIGINT_MISC_CTRL_CTL_START (NBIT0) -#define BIGINT_MISC_CTRL_CTL_RESET (NBIT1) -#define BIGINT_MISC_CTRL_CTL_MSW_FIRST (NBIT2) -#define BIGINT_MISC_CTRL_CTL_SWAP_BYTE_ORDER (NBIT3) -#define BIGINT_MISC_CTRL_CTL_FORCE_BARRETT (NBIT4) -#define BIGINT_MISC_CTRL_CTL_M_PRIME_VALID (NBIT5) - -#define BIGINT_M_PRIME (BIGINT_ENGINE_ADDR + 0x08) - -#define BIGINT_STATUS (BIGINT_ENGINE_ADDR + 0x0C) -#define BIGINT_STATUS_STS_DONE (NBIT0) - -#define BIGINT_CLK_COUNT (BIGINT_ENGINE_ADDR + 0x10) -#define BIGINT_ADDR_X (BIGINT_ENGINE_ADDR + 0x14) -#define BIGINT_ADDR_E (BIGINT_ENGINE_ADDR + 0x18) -#define BIGINT_ADDR_M (BIGINT_ENGINE_ADDR + 0x1C) -#define BIGINT_ADDR_R (BIGINT_ENGINE_ADDR + 0x20) -#define BIGINT_LENGTH (BIGINT_ENGINE_ADDR + 0x24) - -#define BIGINT_IRQ_STS (BIGINT_ENGINE_ADDR + 0x28) -#define BIGINT_IRQ_STS_DONE (NBIT0) -#define BIGINT_IRQ_STS_CHOOSE_MONT (NBIT1) -#define BIGINT_IRQ_STS_M_READ (NBIT2) -#define BIGINT_IRQ_STS_X_READ (NBIT3) -#define BIGINT_IRQ_STS_START (NBIT4) -#define BIGINT_IRQ_STS_PRECOMP_FINISH (NBIT5) - -#define BIGINT_IRQ_MASK (BIGINT_ENGINE_ADDR + 0x2C) -#define BIGINT_IRQ_MASK_CTL_IRQ_MASK_START (NBIT4) - -#define ENABLE_FLIPPING 1 - - - - -#define GET_UINT32(BUF,OFFSET) (((uint32)((BUF)[OFFSET])) | ((uint32)(((BUF)[OFFSET + 1]) << 8)) | \ -((uint32)(((BUF)[OFFSET + 2]) << 16)) | ((uint32)(((BUF)[OFFSET + 3]) << 24))) - -#define PUTU32(VAL32,BUF,OFFSET) \ -do \ -{ \ - (BUF)[OFFSET ] = BYTE_3((VAL32)); \ - (BUF)[OFFSET +1 ] = BYTE_2((VAL32)); \ - (BUF)[OFFSET +2 ] = BYTE_1((VAL32)); \ - (BUF)[OFFSET +3 ] = BYTE_0((VAL32)); \ -}while(0) - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*! -@struct \ - tstrHashContext - -@brief -*/ -typedef struct{ - uint32 au32HashState[M2M_SHA256_DIGEST_LEN/4]; - uint8 au8CurrentBlock[64]; - uint32 u32TotalLength; - uint8 u8InitHashFlag; -}tstrSHA256HashCtxt; - - - -/*======*======*======*======*======*=======* -* SHA256 IMPLEMENTATION * -*======*======*======*======*======*========*/ - -sint8 m2m_crypto_sha256_hash_init(tstrM2mSha256Ctxt *pstrSha256Ctxt) -{ - tstrSHA256HashCtxt *pstrSHA256 = (tstrSHA256HashCtxt*)pstrSha256Ctxt; - if(pstrSHA256 != NULL) - { - m2m_memset((uint8*)pstrSha256Ctxt, 0, sizeof(tstrM2mSha256Ctxt)); - pstrSHA256->u8InitHashFlag = 1; - } - return 0; -} - -sint8 m2m_crypto_sha256_hash_update(tstrM2mSha256Ctxt *pstrSha256Ctxt, uint8 *pu8Data, uint16 u16DataLength) -{ - sint8 s8Ret = M2M_ERR_FAIL; - tstrSHA256HashCtxt *pstrSHA256 = (tstrSHA256HashCtxt*)pstrSha256Ctxt; - if(pstrSHA256 != NULL) - { - uint32 u32ReadAddr; - uint32 u32WriteAddr = SHARED_MEM_BASE; - uint32 u32Addr = u32WriteAddr; - uint32 u32ResidualBytes; - uint32 u32NBlocks; - uint32 u32Offset; - uint32 u32CurrentBlock = 0; - uint8 u8IsDone = 0; - - /* Get the remaining bytes from the previous update (if the length is not block aligned). */ - u32ResidualBytes = pstrSHA256->u32TotalLength % SHA_BLOCK_SIZE; - - /* Update the total data length. */ - pstrSHA256->u32TotalLength += u16DataLength; - - if(u32ResidualBytes != 0) - { - if((u32ResidualBytes + u16DataLength) >= SHA_BLOCK_SIZE) - { - u32Offset = SHA_BLOCK_SIZE - u32ResidualBytes; - m2m_memcpy(&pstrSHA256->au8CurrentBlock[u32ResidualBytes], pu8Data, u32Offset); - pu8Data += u32Offset; - u16DataLength -= u32Offset; - - nm_write_block(u32Addr, pstrSHA256->au8CurrentBlock, SHA_BLOCK_SIZE); - u32Addr += SHA_BLOCK_SIZE; - u32CurrentBlock = 1; - } - else - { - m2m_memcpy(&pstrSHA256->au8CurrentBlock[u32ResidualBytes], pu8Data, u16DataLength); - u16DataLength = 0; - } - } - - /* Get the number of HASH BLOCKs and the residual bytes. */ - u32NBlocks = u16DataLength / SHA_BLOCK_SIZE; - u32ResidualBytes = u16DataLength % SHA_BLOCK_SIZE; - - if(u32NBlocks != 0) - { - nm_write_block(u32Addr, pu8Data, (uint16)(u32NBlocks * SHA_BLOCK_SIZE)); - pu8Data += (u32NBlocks * SHA_BLOCK_SIZE); - } - - u32NBlocks += u32CurrentBlock; - if(u32NBlocks != 0) - { - uint32 u32RegVal = 0; - - nm_write_reg(SHA256_CTRL, u32RegVal); - u32RegVal |= SHA256_CTRL_FORCE_SHA256_QUIT_MASK; - nm_write_reg(SHA256_CTRL, u32RegVal); - - if(pstrSHA256->u8InitHashFlag) - { - pstrSHA256->u8InitHashFlag = 0; - u32RegVal |= SHA256_CTRL_INIT_SHA256_STATE_MASK; - } - - u32ReadAddr = u32WriteAddr + (u32NBlocks * SHA_BLOCK_SIZE); - nm_write_reg(SHA256_DATA_LENGTH, (u32NBlocks * SHA_BLOCK_SIZE)); - nm_write_reg(SHA256_START_RD_ADDR, u32WriteAddr); - nm_write_reg(SHA256_START_WR_ADDR, u32ReadAddr); - - u32RegVal |= SHA256_CTRL_START_CALC_MASK; - - u32RegVal &= ~(0x7 << 8); - u32RegVal |= (2 << 8); - - nm_write_reg(SHA256_CTRL, u32RegVal); - - /* 5. Wait for done_intr */ - while(!u8IsDone) - { - u32RegVal = nm_read_reg(SHA256_DONE_INTR_STS); - u8IsDone = u32RegVal & NBIT0; - } - } - if(u32ResidualBytes != 0) - { - m2m_memcpy(pstrSHA256->au8CurrentBlock, pu8Data, u32ResidualBytes); - } - s8Ret = M2M_SUCCESS; - } - return s8Ret; -} - - -sint8 m2m_crypto_sha256_hash_finish(tstrM2mSha256Ctxt *pstrSha256Ctxt, uint8 *pu8Sha256Digest) -{ - sint8 s8Ret = M2M_ERR_FAIL; - tstrSHA256HashCtxt *pstrSHA256 = (tstrSHA256HashCtxt*)pstrSha256Ctxt; - if(pstrSHA256 != NULL) - { - uint32 u32ReadAddr; - uint32 u32WriteAddr = SHARED_MEM_BASE; - uint32 u32Addr = u32WriteAddr; - uint16 u16Offset; - uint16 u16PaddingLength; - uint16 u16NBlocks = 1; - uint32 u32RegVal = 0; - uint32 u32Idx,u32ByteIdx; - uint32 au32Digest[M2M_SHA256_DIGEST_LEN / 4]; - uint8 u8IsDone = 0; - - nm_write_reg(SHA256_CTRL,u32RegVal); - u32RegVal |= SHA256_CTRL_FORCE_SHA256_QUIT_MASK; - nm_write_reg(SHA256_CTRL,u32RegVal); - - if(pstrSHA256->u8InitHashFlag) - { - pstrSHA256->u8InitHashFlag = 0; - u32RegVal |= SHA256_CTRL_INIT_SHA256_STATE_MASK; - } - - /* Calculate the offset of the last data byte in the current block. */ - u16Offset = (uint16)(pstrSHA256->u32TotalLength % SHA_BLOCK_SIZE); - - /* Add the padding byte 0x80. */ - pstrSHA256->au8CurrentBlock[u16Offset ++] = 0x80; - - /* Calculate the required padding to complete - one Hash Block Size. - */ - u16PaddingLength = SHA_BLOCK_SIZE - u16Offset; - m2m_memset(&pstrSHA256->au8CurrentBlock[u16Offset], 0, u16PaddingLength); - - /* If the padding count is not enough to hold 64-bit representation of - the total input message length, one padding block is required. - */ - if(u16PaddingLength < 8) - { - nm_write_block(u32Addr, pstrSHA256->au8CurrentBlock, SHA_BLOCK_SIZE); - u32Addr += SHA_BLOCK_SIZE; - m2m_memset(pstrSHA256->au8CurrentBlock, 0, SHA_BLOCK_SIZE); - u16NBlocks ++; - } - - /* pack the length at the end of the padding block */ - PUTU32(pstrSHA256->u32TotalLength << 3, pstrSHA256->au8CurrentBlock, (SHA_BLOCK_SIZE - 4)); - - u32ReadAddr = u32WriteAddr + (u16NBlocks * SHA_BLOCK_SIZE); - nm_write_block(u32Addr, pstrSHA256->au8CurrentBlock, SHA_BLOCK_SIZE); - nm_write_reg(SHA256_DATA_LENGTH, (u16NBlocks * SHA_BLOCK_SIZE)); - nm_write_reg(SHA256_START_RD_ADDR, u32WriteAddr); - nm_write_reg(SHA256_START_WR_ADDR, u32ReadAddr); - - u32RegVal |= SHA256_CTRL_START_CALC_MASK; - u32RegVal |= SHA256_CTRL_WR_BACK_HASH_VALUE_MASK; - u32RegVal &= ~(0x7UL << 8); - u32RegVal |= (0x2UL << 8); - - nm_write_reg(SHA256_CTRL,u32RegVal); - - - /* 5. Wait for done_intr */ - while(!u8IsDone) - { - u32RegVal = nm_read_reg(SHA256_DONE_INTR_STS); - u8IsDone = u32RegVal & NBIT0; - } - nm_read_block(u32ReadAddr, (uint8*)au32Digest, 32); - - /* Convert the output words to an array of bytes. - */ - u32ByteIdx = 0; - for(u32Idx = 0; u32Idx < (M2M_SHA256_DIGEST_LEN / 4); u32Idx ++) - { - pu8Sha256Digest[u32ByteIdx ++] = BYTE_3(au32Digest[u32Idx]); - pu8Sha256Digest[u32ByteIdx ++] = BYTE_2(au32Digest[u32Idx]); - pu8Sha256Digest[u32ByteIdx ++] = BYTE_1(au32Digest[u32Idx]); - pu8Sha256Digest[u32ByteIdx ++] = BYTE_0(au32Digest[u32Idx]); - } - s8Ret = M2M_SUCCESS; - } - return s8Ret; -} - - -/*======*======*======*======*======*=======* -* RSA IMPLEMENTATION * -*======*======*======*======*======*========*/ - -static void FlipBuffer(uint8 *pu8InBuffer, uint8 *pu8OutBuffer, uint16 u16BufferSize) -{ - uint16 u16Idx; - for(u16Idx = 0; u16Idx < u16BufferSize; u16Idx ++) - { -#if ENABLE_FLIPPING == 1 - pu8OutBuffer[u16Idx] = pu8InBuffer[u16BufferSize - u16Idx - 1]; -#else - pu8OutBuffer[u16Idx] = pu8InBuffer[u16Idx]; -#endif - } -} - -void BigInt_ModExp -( - uint8 *pu8X, uint16 u16XSize, - uint8 *pu8E, uint16 u16ESize, - uint8 *pu8M, uint16 u16MSize, - uint8 *pu8R, uint16 u16RSize - ) -{ - uint32 u32Reg; - uint8 au8Tmp[780] = {0}; - uint32 u32XAddr = SHARED_MEM_BASE; - uint32 u32MAddr; - uint32 u32EAddr; - uint32 u32RAddr; - uint8 u8EMswBits = 32; - uint32 u32Mprime = 0x7F; - uint16 u16XSizeWords,u16ESizeWords; - uint32 u32Exponent; - - u16XSizeWords = (u16XSize + 3) / 4; - u16ESizeWords = (u16ESize + 3) / 4; - - u32MAddr = u32XAddr + (u16XSizeWords * 4); - u32EAddr = u32MAddr + (u16XSizeWords * 4); - u32RAddr = u32EAddr + (u16ESizeWords * 4); - - /* Reset the core. - */ - u32Reg = 0; - u32Reg |= BIGINT_MISC_CTRL_CTL_RESET; - u32Reg = nm_read_reg(BIGINT_MISC_CTRL); - u32Reg &= ~BIGINT_MISC_CTRL_CTL_RESET; - u32Reg = nm_read_reg(BIGINT_MISC_CTRL); - - nm_write_block(u32RAddr,au8Tmp, u16RSize); - - /* Write Input Operands to Chip Memory. - */ - /*------- X -------*/ - FlipBuffer(pu8X,au8Tmp,u16XSize); - nm_write_block(u32XAddr,au8Tmp,u16XSizeWords * 4); - - /*------- E -------*/ - m2m_memset(au8Tmp, 0, sizeof(au8Tmp)); - FlipBuffer(pu8E, au8Tmp, u16ESize); - nm_write_block(u32EAddr, au8Tmp, u16ESizeWords * 4); - u32Exponent = GET_UINT32(au8Tmp, (u16ESizeWords * 4) - 4); - while((u32Exponent & NBIT31)== 0) - { - u32Exponent <<= 1; - u8EMswBits --; - } - - /*------- M -------*/ - m2m_memset(au8Tmp, 0, sizeof(au8Tmp)); - FlipBuffer(pu8M, au8Tmp, u16XSize); - nm_write_block(u32MAddr, au8Tmp, u16XSizeWords * 4); - - /* Program the addresses of the input operands. - */ - nm_write_reg(BIGINT_ADDR_X, u32XAddr); - nm_write_reg(BIGINT_ADDR_E, u32EAddr); - nm_write_reg(BIGINT_ADDR_M, u32MAddr); - nm_write_reg(BIGINT_ADDR_R, u32RAddr); - - /* Mprime. - */ - nm_write_reg(BIGINT_M_PRIME,u32Mprime); - - /* Length. - */ - u32Reg = (u16XSizeWords & 0xFF); - u32Reg += ((u16ESizeWords & 0xFF) << 8); - u32Reg += (u8EMswBits << 16); - nm_write_reg(BIGINT_LENGTH,u32Reg); - - /* CTRL Register. - */ - u32Reg = nm_read_reg(BIGINT_MISC_CTRL); - u32Reg ^= BIGINT_MISC_CTRL_CTL_START; - u32Reg |= BIGINT_MISC_CTRL_CTL_FORCE_BARRETT; - //u32Reg |= BIGINT_MISC_CTRL_CTL_M_PRIME_VALID; -#if ENABLE_FLIPPING == 0 - u32Reg |= BIGINT_MISC_CTRL_CTL_MSW_FIRST; -#endif - nm_write_reg(BIGINT_MISC_CTRL,u32Reg); - - /* Wait for computation to complete. */ - while(1) - { - u32Reg = nm_read_reg(BIGINT_IRQ_STS); - if(u32Reg & BIGINT_IRQ_STS_DONE) - { - break; - } - } - nm_write_reg(BIGINT_IRQ_STS,0); - m2m_memset(au8Tmp, 0, sizeof(au8Tmp)); - nm_read_block(u32RAddr, au8Tmp, u16RSize); - FlipBuffer(au8Tmp, pu8R, u16RSize); -} - - - -#define MD5_DIGEST_SIZE (16) -#define SHA1_DIGEST_SIZE (20) - -static const uint8 au8TEncodingMD5[] = -{ - 0x30, 0x20, 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86, - 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05, 0x05, 0x00, - 0x04 -}; -/*!< Fixed part of the Encoding T for the MD5 hash algorithm. -*/ - - -static const uint8 au8TEncodingSHA1[] = -{ - 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, - 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04 -}; -/*!< Fixed part of the Encoding T for the SHA-1 hash algorithm. -*/ - - -static const uint8 au8TEncodingSHA2[] = -{ - 0x30, 0x31, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, - 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, - 0x00, 0x04 -}; -/*!< Fixed part of the Encoding T for the SHA-2 hash algorithm. -*/ - - -sint8 m2m_crypto_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash, - uint16 u16HashLength, uint8 *pu8RsaSignature) -{ - sint8 s8Ret = M2M_RSA_SIGN_FAIL; - - if((pu8N != NULL) && (pu8E != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL)) - { - uint16 u16TLength, u16TEncodingLength; - uint8 *pu8T; - uint8 au8EM[512]; - - /* Selection of correct T Encoding based on the hash size. - */ - if(u16HashLength == MD5_DIGEST_SIZE) - { - pu8T = (uint8*)au8TEncodingMD5; - u16TEncodingLength = sizeof(au8TEncodingMD5); - } - else if(u16HashLength == SHA1_DIGEST_SIZE) - { - pu8T = (uint8*)au8TEncodingSHA1; - u16TEncodingLength = sizeof(au8TEncodingSHA1); - } - else - { - pu8T = (uint8*)au8TEncodingSHA2; - u16TEncodingLength = sizeof(au8TEncodingSHA2); - } - u16TLength = u16TEncodingLength + 1 + u16HashLength; - - /* If emLen < tLen + 11. - */ - if(u16NSize >= (u16TLength + 11)) - { - uint32 u32PSLength,u32Idx = 0; - - /* - RSA verification - */ - BigInt_ModExp(pu8RsaSignature, u16NSize, pu8E, u16ESize, pu8N, u16NSize, au8EM, u16NSize); - - u32PSLength = u16NSize - u16TLength - 3; - - /* - The calculated EM must match the following pattern. - *======*======*======*======*======* - * 0x00 || 0x01 || PS || 0x00 || T * - *======*======*======*======*======* - Where PS is all 0xFF - T is defined based on the hash algorithm. - */ - if((au8EM[0] == 0x00) && (au8EM[1] == 0x01)) - { - for(u32Idx = 2; au8EM[u32Idx] == 0xFF; u32Idx ++); - if(u32Idx == (u32PSLength + 2)) - { - if(au8EM[u32Idx ++] == 0x00) - { - if(!m2m_memcmp(&au8EM[u32Idx], pu8T, u16TEncodingLength)) - { - u32Idx += u16TEncodingLength; - if(au8EM[u32Idx ++] == u16HashLength) - s8Ret = m2m_memcmp(&au8EM[u32Idx], pu8SignedMsgHash, u16HashLength); - } - } - } - } - } - } - return s8Ret; -} - - -sint8 m2m_crypto_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash, - uint16 u16HashLength, uint8 *pu8RsaSignature) -{ - sint8 s8Ret = M2M_RSA_SIGN_FAIL; - - if((pu8N != NULL) && (pu8d != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL)) - { - uint16 u16TLength, u16TEncodingLength; - uint8 *pu8T; - uint8 au8EM[512]; - - /* Selection of correct T Encoding based on the hash size. - */ - if(u16HashLength == MD5_DIGEST_SIZE) - { - pu8T = (uint8*)au8TEncodingMD5; - u16TEncodingLength = sizeof(au8TEncodingMD5); - } - else if(u16HashLength == SHA1_DIGEST_SIZE) - { - pu8T = (uint8*)au8TEncodingSHA1; - u16TEncodingLength = sizeof(au8TEncodingSHA1); - } - else - { - pu8T = (uint8*)au8TEncodingSHA2; - u16TEncodingLength = sizeof(au8TEncodingSHA2); - } - u16TLength = u16TEncodingLength + 1 + u16HashLength; - - /* If emLen < tLen + 11. - */ - if(u16NSize >= (u16TLength + 11)) - { - uint16 u16PSLength = 0; - uint16 u16Offset = 0; - - /* - The calculated EM must match the following pattern. - *======*======*======*======*======* - * 0x00 || 0x01 || PS || 0x00 || T * - *======*======*======*======*======* - Where PS is all 0xFF - T is defined based on the hash algorithm. - */ - au8EM[u16Offset ++] = 0; - au8EM[u16Offset ++] = 1; - u16PSLength = u16NSize - u16TLength - 3; - m2m_memset(&au8EM[u16Offset], 0xFF, u16PSLength); - u16Offset += u16PSLength; - au8EM[u16Offset ++] = 0; - m2m_memcpy(&au8EM[u16Offset], pu8T, u16TEncodingLength); - u16Offset += u16TEncodingLength; - au8EM[u16Offset ++] = u16HashLength; - m2m_memcpy(&au8EM[u16Offset], pu8SignedMsgHash, u16HashLength); - - /* - RSA Signature Generation - */ - BigInt_ModExp(au8EM, u16NSize, pu8d, u16dSize, pu8N, u16NSize, pu8RsaSignature, u16NSize); - s8Ret = M2M_RSA_SIGN_OK; - } - } - return s8Ret; -} - -#endif /* CONF_CRYPTO */ - -#ifdef CONF_CRYPTO_SOFT - -typedef struct { - tpfAppCryproCb pfAppCryptoCb; - uint8 * pu8Digest; - uint8 * pu8Rsa; - uint8 u8CryptoBusy; -}tstrCryptoCtxt; - -typedef struct { - uint8 au8N[M2M_MAX_RSA_LEN]; - uint8 au8E[M2M_MAX_RSA_LEN]; - uint8 au8Hash[M2M_SHA256_DIGEST_LEN]; - uint16 u16Nsz; - uint16 u16Esz; - uint16 u16Hsz; - uint8 _pad16_[2]; -}tstrRsaPayload; - -static tstrCryptoCtxt gstrCryptoCtxt; - - -/** -* @fn m2m_crypto_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -* @brief WiFi call back function -* @param [in] u8OpCode -* HIF Opcode type. -* @param [in] u16DataSize -* HIF data length. -* @param [in] u32Addr -* HIF address. -* @author -* @date -* @version 1.0 -*/ -static void m2m_crypto_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -{ - sint8 ret = M2M_SUCCESS; - gstrCryptoCtxt.u8CryptoBusy = 0; - if(u8OpCode == M2M_CRYPTO_RESP_SHA256_INIT) - { - tstrM2mSha256Ctxt strCtxt; - if (hif_receive(u32Addr, (uint8*) &strCtxt,sizeof(tstrM2mSha256Ctxt), 0) == M2M_SUCCESS) - { - tstrCyptoResp strResp; - if(hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt), (uint8*) &strResp,sizeof(tstrCyptoResp), 1) == M2M_SUCCESS) - { - if (gstrCryptoCtxt.pfAppCryptoCb) - gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,&strCtxt); - } - } - } - else if(u8OpCode == M2M_CRYPTO_RESP_SHA256_UPDATE) - { - tstrM2mSha256Ctxt strCtxt; - if (hif_receive(u32Addr, (uint8*) &strCtxt,sizeof(tstrM2mSha256Ctxt), 0) == M2M_SUCCESS) - { - tstrCyptoResp strResp; - if (hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt), (uint8*) &strResp,sizeof(tstrCyptoResp), 1) == M2M_SUCCESS) - { - if (gstrCryptoCtxt.pfAppCryptoCb) - gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,&strCtxt); - } - } - - } - else if(u8OpCode == M2M_CRYPTO_RESP_SHA256_FINSIH) - { - tstrCyptoResp strResp; - if (hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt), (uint8*) &strResp,sizeof(tstrCyptoResp), 0) == M2M_SUCCESS) - { - if (hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt) + sizeof(tstrCyptoResp), (uint8*)gstrCryptoCtxt.pu8Digest,M2M_SHA256_DIGEST_LEN, 1) == M2M_SUCCESS) - { - if (gstrCryptoCtxt.pfAppCryptoCb) - gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,gstrCryptoCtxt.pu8Digest); - - } - } - } - else if(u8OpCode == M2M_CRYPTO_RESP_RSA_SIGN_GEN) - { - tstrCyptoResp strResp; - if (hif_receive(u32Addr + sizeof(tstrRsaPayload), (uint8*)&strResp,sizeof(tstrCyptoResp), 0) == M2M_SUCCESS) - { - if (hif_receive(u32Addr + sizeof(tstrRsaPayload) + sizeof(tstrCyptoResp), (uint8*)gstrCryptoCtxt.pu8Rsa,M2M_MAX_RSA_LEN, 0) == M2M_SUCCESS) - { - if (gstrCryptoCtxt.pfAppCryptoCb) - gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,gstrCryptoCtxt.pu8Rsa); - } - } - } - else if(u8OpCode == M2M_CRYPTO_RESP_RSA_SIGN_VERIFY) - { - tstrCyptoResp strResp; - if (hif_receive(u32Addr + sizeof(tstrRsaPayload), (uint8*)&strResp,sizeof(tstrCyptoResp), 1) == M2M_SUCCESS) - { - if (gstrCryptoCtxt.pfAppCryptoCb) - gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,NULL); - } - } - else - { - M2M_ERR("u8Code %d ??\n",u8OpCode); - } - -} -/*! -@fn \ - sint8 m2m_crypto_init(); - -@brief crypto initialization - -@param[in] pfAppCryproCb - -*/ -sint8 m2m_crypto_init(tpfAppCryproCb pfAppCryproCb) -{ - sint8 ret = M2M_ERR_FAIL; - m2m_memset((uint8*)&gstrCryptoCtxt,0,sizeof(tstrCryptoCtxt)); - if(pfAppCryproCb != NULL) - { - gstrCryptoCtxt.pfAppCryptoCb = pfAppCryproCb; - ret = hif_register_cb(M2M_REQ_GROUP_CRYPTO,m2m_crypto_cb); - } - return ret; -} -/*! -@fn \ - sint8 m2m_sha256_hash_init(tstrM2mSha256Ctxt *psha256Ctxt); - -@brief SHA256 hash initialization - -@param[in] psha256Ctxt - Pointer to a sha256 context allocated by the caller. -*/ -sint8 m2m_crypto_sha256_hash_init(tstrM2mSha256Ctxt *psha256Ctxt) -{ - sint8 ret = M2M_ERR_FAIL; - if((psha256Ctxt != NULL)&&(!gstrCryptoCtxt.u8CryptoBusy)) - { - ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_SHA256_INIT|M2M_REQ_DATA_PKT,(uint8*)psha256Ctxt,sizeof(tstrM2mSha256Ctxt),NULL,0,0); - } - return ret; -} - - -/*! -@fn \ - sint8 m2m_sha256_hash_update(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Data, uint16 u16DataLength); - -@brief SHA256 hash update - -@param [in] psha256Ctxt - Pointer to the sha256 context. - -@param [in] pu8Data - Buffer holding the data submitted to the hash. - -@param [in] u16DataLength - Size of the data bufefr in bytes. -*/ -sint8 m2m_crypto_sha256_hash_update(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Data, uint16 u16DataLength) -{ - sint8 ret = M2M_ERR_FAIL; - if((!gstrCryptoCtxt.u8CryptoBusy) && (psha256Ctxt != NULL) && (pu8Data != NULL) && (u16DataLength < M2M_SHA256_MAX_DATA)) - { - ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_SHA256_UPDATE|M2M_REQ_DATA_PKT,(uint8*)psha256Ctxt,sizeof(tstrM2mSha256Ctxt),pu8Data,u16DataLength,sizeof(tstrM2mSha256Ctxt) + sizeof(tstrCyptoResp)); - } - return ret; - -} - - -/*! -@fn \ - sint8 m2m_sha256_hash_finish(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Sha256Digest); - -@brief SHA256 hash finalization - -@param[in] psha256Ctxt - Pointer to a sha256 context allocated by the caller. - -@param [in] pu8Sha256Digest - Buffer allocated by the caller which will hold the resultant SHA256 Digest. It must be allocated no less than M2M_SHA256_DIGEST_LEN. -*/ -sint8 m2m_crypto_sha256_hash_finish(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Sha256Digest) -{ - sint8 ret = M2M_ERR_FAIL; - if((!gstrCryptoCtxt.u8CryptoBusy) && (psha256Ctxt != NULL) && (pu8Sha256Digest != NULL)) - { - gstrCryptoCtxt.pu8Digest = pu8Sha256Digest; - ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_SHA256_FINSIH|M2M_REQ_DATA_PKT,(uint8*)psha256Ctxt,sizeof(tstrM2mSha256Ctxt),NULL,0,0); - } - return ret; -} - - - - -/*! -@fn \ - sint8 m2m_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash, \ - uint16 u16HashLength, uint8 *pu8RsaSignature); - -@brief RSA Signature Verification - - The function shall request the RSA Signature verification from the WINC Firmware for the given message. The signed message shall be - compressed to the corresponding hash algorithm before calling this function. - The hash type is identified by the given hash length. For example, if the hash length is 32 bytes, then it is SHA256. - -@param[in] pu8N - RSA Key modulus n. - -@param[in] u16NSize - Size of the RSA modulus n in bytes. - -@param[in] pu8E - RSA public exponent. - -@param[in] u16ESize - Size of the RSA public exponent in bytes. - -@param[in] pu8SignedMsgHash - The hash digest of the signed message. - -@param[in] u16HashLength - The length of the hash digest. - -@param[out] pu8RsaSignature - Signature value to be verified. -*/ - - -sint8 m2m_crypto_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash, - uint16 u16HashLength, uint8 *pu8RsaSignature) -{ - sint8 ret = M2M_ERR_FAIL; - if((!gstrCryptoCtxt.u8CryptoBusy) && (pu8N != NULL) && (pu8E != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL) - && (u16NSize != 0) && (u16ESize != 0) && (u16HashLength != 0) && (pu8RsaSignature != NULL) ) - - { - tstrRsaPayload strRsa = {0}; - - m2m_memcpy(strRsa.au8N,pu8N,u16NSize); - m2m_memcpy(strRsa.au8E,pu8E,u16ESize); - m2m_memcpy(strRsa.au8Hash,pu8SignedMsgHash,u16HashLength); - - strRsa.u16Esz = u16ESize; - strRsa.u16Hsz = u16HashLength; - strRsa.u16Nsz = u16NSize; - - ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_RSA_SIGN_VERIFY|M2M_REQ_DATA_PKT,(uint8*)&strRsa,sizeof(tstrRsaPayload),NULL,0,0); - - } - return ret; -} - - -/*! -@fn \ - sint8 m2m_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash, \ - uint16 u16HashLength, uint8 *pu8RsaSignature); - -@brief RSA Signature Generation - - The function shall request the RSA Signature generation from the WINC Firmware for the given message. The signed message shall be - compressed to the corresponding hash algorithm before calling this function. - The hash type is identified by the given hash length. For example, if the hash length is 32 bytes, then it is SHA256. - -@param[in] pu8N - RSA Key modulus n. - -@param[in] u16NSize - Size of the RSA modulus n in bytes. - -@param[in] pu8d - RSA private exponent. - -@param[in] u16dSize - Size of the RSA private exponent in bytes. - -@param[in] pu8SignedMsgHash - The hash digest of the signed message. - -@param[in] u16HashLength - The length of the hash digest. - -@param[out] pu8RsaSignature - Pointer to a user buffer allocated by teh caller shall hold the generated signature. -*/ -sint8 m2m_crypto_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash, - uint16 u16HashLength, uint8 *pu8RsaSignature) -{ - sint8 ret = M2M_ERR_FAIL; - if((!gstrCryptoCtxt.u8CryptoBusy) && (pu8N != NULL) && (pu8d != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL) - && (u16NSize != 0) && (u16dSize != 0) && (u16HashLength != 0) && (pu8RsaSignature != NULL)) - - { - tstrRsaPayload strRsa = {0}; - - m2m_memcpy(strRsa.au8N,pu8N,u16NSize); - m2m_memcpy(strRsa.au8E,pu8d,u16dSize); - m2m_memcpy(strRsa.au8Hash,pu8SignedMsgHash,u16HashLength); - - strRsa.u16Esz = u16dSize; - strRsa.u16Hsz = u16HashLength; - strRsa.u16Nsz = u16NSize; - - gstrCryptoCtxt.pu8Rsa = pu8RsaSignature; - ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_RSA_SIGN_GEN|M2M_REQ_DATA_PKT,(uint8*)&strRsa,sizeof(tstrRsaPayload),NULL,0,0); - - } - return ret; -} - -#endif \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_hif.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_hif.c deleted file mode 100644 index f0ed93a..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_hif.c +++ /dev/null @@ -1,767 +0,0 @@ -/** - * - * \file - * - * \brief This module contains M2M host interface APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "common/include/nm_common.h" -#include "driver/source/nmbus.h" -#include "bsp/include/nm_bsp.h" -#include "m2m_hif.h" -#include "driver/include/m2m_types.h" -#include "driver/source/nmasic.h" -#include "driver/include/m2m_periph.h" - -#if (defined NM_EDGE_INTERRUPT)&&(defined NM_LEVEL_INTERRUPT) -#error "only one type of interrupt NM_EDGE_INTERRUPT,NM_LEVEL_INTERRUPT" -#endif - -#if !((defined NM_EDGE_INTERRUPT)||(defined NM_LEVEL_INTERRUPT)) -#error "define interrupt type NM_EDGE_INTERRUPT,NM_LEVEL_INTERRUPT" -#endif - -#ifndef CORTUS_APP -#define NMI_AHB_DATA_MEM_BASE 0x30000 -#define NMI_AHB_SHARE_MEM_BASE 0xd0000 - -#define WIFI_HOST_RCV_CTRL_0 (0x1070) -#define WIFI_HOST_RCV_CTRL_1 (0x1084) -#define WIFI_HOST_RCV_CTRL_2 (0x1078) -#define WIFI_HOST_RCV_CTRL_3 (0x106c) -#define WIFI_HOST_RCV_CTRL_4 (0x150400) -#define WIFI_HOST_RCV_CTRL_5 (0x1088) - -typedef struct { - uint8 u8ChipMode; - uint8 u8ChipSleep; - uint8 u8HifRXDone; - uint8 u8Interrupt; - uint32 u32RxAddr; - uint32 u32RxSize; - tpfHifCallBack pfWifiCb; - tpfHifCallBack pfIpCb; - tpfHifCallBack pfOtaCb; - tpfHifCallBack pfSigmaCb; - tpfHifCallBack pfHifCb; - tpfHifCallBack pfCryptoCb; - tpfHifCallBack pfSslCb; -}tstrHifContext; - -volatile tstrHifContext gstrHifCxt; - -static void isr(void) -{ - gstrHifCxt.u8Interrupt++; -#ifdef NM_LEVEL_INTERRUPT - nm_bsp_interrupt_ctrl(0); -#endif -} -static sint8 hif_set_rx_done(void) -{ - uint32 reg; - sint8 ret = M2M_SUCCESS; - - gstrHifCxt.u8HifRXDone = 0; -#ifdef NM_EDGE_INTERRUPT - nm_bsp_interrupt_ctrl(1); -#endif - ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0,®); - if(ret != M2M_SUCCESS)goto ERR1; - /* Set RX Done */ - reg |= NBIT1; - ret = nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg); - if(ret != M2M_SUCCESS)goto ERR1; -#ifdef NM_LEVEL_INTERRUPT - nm_bsp_interrupt_ctrl(1); -#endif -ERR1: - return ret; - -} -/** -* @fn static void m2m_hif_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -* @brief WiFi call back function -* @param [in] u8OpCode -* HIF Opcode type. -* @param [in] u16DataSize -* HIF data length. -* @param [in] u32Addr -* HIF address. -* @param [in] grp -* HIF group type. -* @author -* @date -* @version 1.0 -*/ -static void m2m_hif_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)u8OpCode; - (void)u16DataSize; - (void)u32Addr; -#endif -} -/** -* @fn NMI_API sint8 hif_chip_wake(void); -* @brief To Wakeup the chip. -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -sint8 hif_chip_wake(void) -{ - sint8 ret = M2M_SUCCESS; - if(gstrHifCxt.u8HifRXDone) - { - /*chip already wake for the rx not done no need to send wake request*/ - return ret; - } - if(gstrHifCxt.u8ChipSleep == 0) - { - if(gstrHifCxt.u8ChipMode != M2M_NO_PS) - { - ret = chip_wake(); - if(ret != M2M_SUCCESS)goto ERR1; - } - else - { - } - } - gstrHifCxt.u8ChipSleep++; -ERR1: - return ret; -} -/*! -@fn \ - NMI_API void hif_set_sleep_mode(uint8 u8Pstype); - -@brief - Set the sleep mode of the HIF layer. - -@param [in] u8Pstype - Sleep mode. - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ - -void hif_set_sleep_mode(uint8 u8Pstype) -{ - gstrHifCxt.u8ChipMode = u8Pstype; -} -/*! -@fn \ - NMI_API uint8 hif_get_sleep_mode(void); - -@brief - Get the sleep mode of the HIF layer. - -@return - The function SHALL return the sleep mode of the HIF layer. -*/ - -uint8 hif_get_sleep_mode(void) -{ - return gstrHifCxt.u8ChipMode; -} - -/** -* @fn NMI_API sint8 hif_chip_sleep_sc(void); -* @brief To clear the chip sleep but keep the chip sleep -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -sint8 hif_chip_sleep_sc(void) -{ - if(gstrHifCxt.u8ChipSleep >= 1) - { - gstrHifCxt.u8ChipSleep--; - } - return M2M_SUCCESS; -} -/** -* @fn NMI_API sint8 hif_chip_sleep(void); -* @brief To make the chip sleep. -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -sint8 hif_chip_sleep(void) -{ - sint8 ret = M2M_SUCCESS; - - if(gstrHifCxt.u8ChipSleep >= 1) - { - gstrHifCxt.u8ChipSleep--; - } - - if(gstrHifCxt.u8ChipSleep == 0) - { - if(gstrHifCxt.u8ChipMode != M2M_NO_PS) - { - ret = chip_sleep(); - if(ret != M2M_SUCCESS)goto ERR1; - - } - else - { - } - } -ERR1: - return ret; -} -/** -* @fn NMI_API sint8 hif_init(void * arg); -* @brief To initialize HIF layer. -* @param [in] arg -* Pointer to the arguments. -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -sint8 hif_init(void * arg) -{ -#ifdef ARDUINO - (void)arg; // Silence "unused" warning -#endif - m2m_memset((uint8*)&gstrHifCxt,0,sizeof(tstrHifContext)); - nm_bsp_register_isr(isr); - hif_register_cb(M2M_REQ_GROUP_HIF,m2m_hif_cb); - return M2M_SUCCESS; -} -/** -* @fn NMI_API sint8 hif_deinit(void * arg); -* @brief To De-initialize HIF layer. -* @param [in] arg -* Pointer to the arguments. -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ -sint8 hif_deinit(void * arg) -{ -#ifdef ARDUINO - (void)arg; // Silence "unused" warning -#endif - sint8 ret = M2M_SUCCESS; - ret = hif_chip_wake(); - m2m_memset((uint8*)&gstrHifCxt,0,sizeof(tstrHifContext)); - return ret; -} -/** -* @fn NMI_API sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, - uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) -* @brief Send packet using host interface. - -* @param [in] u8Gid -* Group ID. -* @param [in] u8Opcode -* Operation ID. -* @param [in] pu8CtrlBuf -* Pointer to the Control buffer. -* @param [in] u16CtrlBufSize - Control buffer size. -* @param [in] u16DataOffset - Packet Data offset. -* @param [in] pu8DataBuf -* Packet buffer Allocated by the caller. -* @param [in] u16DataSize - Packet buffer size (including the HIF header). -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, - uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) -{ - sint8 ret = M2M_ERR_SEND; - volatile tstrHifHdr strHif; - - strHif.u8Opcode = u8Opcode&(~NBIT7); - strHif.u8Gid = u8Gid; - strHif.u16Length = M2M_HIF_HDR_OFFSET; - if(pu8DataBuf != NULL) - { - strHif.u16Length += u16DataOffset + u16DataSize; - } - else - { - strHif.u16Length += u16CtrlBufSize; - } - ret = hif_chip_wake(); - if(ret == M2M_SUCCESS) - { - volatile uint32 reg, dma_addr = 0; - volatile uint16 cnt = 0; -//#define OPTIMIZE_BUS -/*please define in firmware also*/ -#ifndef OPTIMIZE_BUS - reg = 0UL; - reg |= (uint32)u8Gid; - reg |= ((uint32)u8Opcode<<8); - reg |= ((uint32)strHif.u16Length<<16); - ret = nm_write_reg(NMI_STATE_REG,reg); - if(M2M_SUCCESS != ret) goto ERR1; - - reg = 0UL; - reg |= NBIT1; - ret = nm_write_reg(WIFI_HOST_RCV_CTRL_2, reg); - if(M2M_SUCCESS != ret) goto ERR1; -#else - reg = 0UL; - reg |= NBIT1; - reg |= ((u8Opcode & NBIT7) ? (NBIT2):(0)); /*Data = 1 or config*/ - reg |= (u8Gid == M2M_REQ_GROUP_IP) ? (NBIT3):(0); /*IP = 1 or non IP*/ - reg |= ((uint32)strHif.u16Length << 4); /*length of pkt max = 4096*/ - ret = nm_write_reg(WIFI_HOST_RCV_CTRL_2, reg); - if(M2M_SUCCESS != ret) goto ERR1; -#endif - dma_addr = 0; - - for(cnt = 0; cnt < 1000; cnt ++) - { - ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_2,(uint32 *)®); - if(ret != M2M_SUCCESS) break; - /* - * If it takes too long to get a response, the slow down to - * avoid back-to-back register read operations. - */ - if(cnt >= 500) { - if(cnt < 501) { - M2M_INFO("Slowing down...\n"); - } - nm_bsp_sleep(1); - } - if (!(reg & NBIT1)) - { - ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_4,(uint32 *)&dma_addr); - if(ret != M2M_SUCCESS) { - /*in case of read error clear the DMA address and return error*/ - dma_addr = 0; - goto ERR1; - } - /*in case of success break */ - break; - } - } - - if (dma_addr != 0) - { - volatile uint32 u32CurrAddr; - u32CurrAddr = dma_addr; - strHif.u16Length=NM_BSP_B_L_16(strHif.u16Length); - ret = nm_write_block(u32CurrAddr, (uint8*)&strHif, M2M_HIF_HDR_OFFSET); - if(M2M_SUCCESS != ret) goto ERR1; - u32CurrAddr += M2M_HIF_HDR_OFFSET; - if(pu8CtrlBuf != NULL) - { - ret = nm_write_block(u32CurrAddr, pu8CtrlBuf, u16CtrlBufSize); - if(M2M_SUCCESS != ret) goto ERR1; - u32CurrAddr += u16CtrlBufSize; - } - if(pu8DataBuf != NULL) - { - u32CurrAddr += (u16DataOffset - u16CtrlBufSize); - ret = nm_write_block(u32CurrAddr, pu8DataBuf, u16DataSize); - if(M2M_SUCCESS != ret) goto ERR1; - u32CurrAddr += u16DataSize; - } - - reg = dma_addr << 2; - reg |= NBIT1; - ret = nm_write_reg(WIFI_HOST_RCV_CTRL_3, reg); - if(M2M_SUCCESS != ret) goto ERR1; - } - else - { - ret = hif_chip_sleep(); - M2M_DBG("Failed to alloc rx size %d\r",ret); - ret = M2M_ERR_MEM_ALLOC; - goto ERR2; - } - - } - else - { - M2M_ERR("(HIF)Fail to wakup the chip\n"); - goto ERR2; - } - /*actual sleep ret = M2M_SUCCESS*/ - ret = hif_chip_sleep(); - return ret; -ERR1: - /*reset the count but no actual sleep as it already bus error*/ - hif_chip_sleep_sc(); -ERR2: - /*logical error*/ - return ret; -} - -#ifdef ARDUINO -volatile uint8 hif_small_xfer = 0; -#endif - -/** -* @fn hif_isr -* @brief Host interface interrupt service routine -* @author M. Abdelmawla -* @date 15 July 2012 -* @return 1 in case of interrupt received else 0 will be returned -* @version 1.0 -*/ -static sint8 hif_isr(void) -{ - sint8 ret = M2M_SUCCESS; - volatile uint32 reg; - volatile tstrHifHdr strHif; - -#ifdef ARDUINO - ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, (uint32*)®); -#else - ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, ®); -#endif - if(M2M_SUCCESS == ret) - { - if(reg & 0x1) /* New interrupt has been received */ - { - uint16 size; - - nm_bsp_interrupt_ctrl(0); - /*Clearing RX interrupt*/ - reg &= ~NBIT0; - ret = nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg); - if(ret != M2M_SUCCESS)goto ERR1; - gstrHifCxt.u8HifRXDone = 1; - size = (uint16)((reg >> 2) & 0xfff); - if (size > 0) { - uint32 address = 0; - /** - start bus transfer - **/ - ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_1, &address); - if(M2M_SUCCESS != ret) - { - M2M_ERR("(hif) WIFI_HOST_RCV_CTRL_1 bus fail\n"); - nm_bsp_interrupt_ctrl(1); - goto ERR1; - } - gstrHifCxt.u32RxAddr = address; - gstrHifCxt.u32RxSize = size; - ret = nm_read_block(address, (uint8*)&strHif, sizeof(tstrHifHdr)); - strHif.u16Length = NM_BSP_B_L_16(strHif.u16Length); - if(M2M_SUCCESS != ret) - { - M2M_ERR("(hif) address bus fail\n"); - nm_bsp_interrupt_ctrl(1); - goto ERR1; - } - if(strHif.u16Length != size) - { - if((size - strHif.u16Length) > 4) - { - M2M_ERR("(hif) Corrupted packet Size = %u \n", - size, strHif.u16Length, strHif.u8Gid, strHif.u8Opcode); - nm_bsp_interrupt_ctrl(1); - ret = M2M_ERR_BUS_FAIL; - goto ERR1; - } - } - - if(M2M_REQ_GROUP_WIFI == strHif.u8Gid) - { - if(gstrHifCxt.pfWifiCb) - gstrHifCxt.pfWifiCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); - else -#ifdef ARDUINO - { -#endif - M2M_ERR("WIFI callback is not registered\n"); -#ifdef ARDUINO - } -#endif - } - else if(M2M_REQ_GROUP_IP == strHif.u8Gid) - { - if(gstrHifCxt.pfIpCb) - gstrHifCxt.pfIpCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); - else -#ifdef ARDUINO - { -#endif - M2M_ERR("Scoket callback is not registered\n"); -#ifdef ARDUINO - } -#endif - } - else if(M2M_REQ_GROUP_OTA == strHif.u8Gid) - { - if(gstrHifCxt.pfOtaCb) - gstrHifCxt.pfOtaCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); - else -#ifdef ARDUINO - { -#endif - M2M_ERR("Ota callback is not registered\n"); -#ifdef ARDUINO - } -#endif - } - else if(M2M_REQ_GROUP_CRYPTO == strHif.u8Gid) - { - if(gstrHifCxt.pfCryptoCb) - gstrHifCxt.pfCryptoCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); - - else -#ifdef ARDUINO - { -#endif - M2M_ERR("Crypto callback is not registered\n"); -#ifdef ARDUINO - } -#endif - } - else if(M2M_REQ_GROUP_SIGMA == strHif.u8Gid) - { - if(gstrHifCxt.pfSigmaCb) - gstrHifCxt.pfSigmaCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); - else -#ifdef ARDUINO - { -#endif - M2M_ERR("Sigma callback is not registered\n"); -#ifdef ARDUINO - } -#endif - } - else if(M2M_REQ_GROUP_SSL == strHif.u8Gid) - { - if(gstrHifCxt.pfSslCb) - gstrHifCxt.pfSslCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); - } - else - { - M2M_ERR("(hif) invalid group ID\n"); - ret = M2M_ERR_BUS_FAIL; - goto ERR1; - } -#ifdef ARDUINO - if(hif_small_xfer) - { - /*Pause SPI transfer*/ - return ret; - } -#endif - if(gstrHifCxt.u8HifRXDone) - { - M2M_ERR("(hif) host app didn't set RX Done <%u><%X>\n", strHif.u8Gid, strHif.u8Opcode); - ret = hif_set_rx_done(); - if(ret != M2M_SUCCESS) goto ERR1; - } - } - else - { - M2M_ERR("(hif) Wrong Size\n"); - ret = M2M_ERR_RCV; - goto ERR1; - } - } - else - { -#ifndef WIN32 - M2M_ERR("(hif) False interrupt %lx",reg); - ret = M2M_ERR_FAIL; - goto ERR1; -#else -#endif - } - } - else - { - M2M_ERR("(hif) Fail to Read interrupt reg\n"); - goto ERR1; - } - -ERR1: - return ret; -} - -#ifdef ARDUINO -void Socket_ReadSocketData_Small(void); -#endif - -/** -* @fn hif_handle_isr(void) -* @brief Handle interrupt received from NMC1500 firmware. -* @return The function SHALL return 0 for success and a negative value otherwise. -*/ - -sint8 hif_handle_isr(void) -{ - sint8 ret = M2M_SUCCESS; - -#ifdef ARDUINO - if(hif_small_xfer) { - /*SPI protocol paused to allow small transfer*/ - Socket_ReadSocketData_Small(); - return ret; - } -#endif - - while (gstrHifCxt.u8Interrupt) { - /*must be at that place because of the race of interrupt increment and that decrement*/ - /*when the interrupt enabled*/ - gstrHifCxt.u8Interrupt--; - while(1) - { - ret = hif_isr(); -#ifdef ARDUINO - if(hif_small_xfer) { - return ret; - } -#endif - if(ret == M2M_SUCCESS) { - /*we will try forever untill we get that interrupt*/ - /*Fail return errors here due to bus errors (reading expected values)*/ - break; - } else { - M2M_ERR("(HIF) Fail to handle interrupt %d try Again..\n",ret); - } - } - } - - return ret; -} -/* -* @fn hif_receive -* @brief Host interface interrupt serviece routine -* @param [in] u32Addr -* Receive start address -* @param [out] pu8Buf -* Pointer to receive buffer. Allocated by the caller -* @param [in] u16Sz -* Receive buffer size -* @param [in] isDone -* If you don't need any more packets send True otherwise send false -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ -sint8 hif_receive(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz, uint8 isDone) -{ - sint8 ret = M2M_SUCCESS; - if((u32Addr == 0)||(pu8Buf == NULL) || (u16Sz == 0)) - { - if(isDone) - { - /* set RX done */ - ret = hif_set_rx_done(); - } - else - { - ret = M2M_ERR_FAIL; - M2M_ERR(" hif_receive: Invalid argument\n"); - } - goto ERR1; - } - - if(u16Sz > gstrHifCxt.u32RxSize) - { - ret = M2M_ERR_FAIL; - M2M_ERR("APP Requested Size is larger than the recived buffer size <%u><%lu>\n",u16Sz, gstrHifCxt.u32RxSize); - goto ERR1; - } - if((u32Addr < gstrHifCxt.u32RxAddr)||((u32Addr + u16Sz)>(gstrHifCxt.u32RxAddr + gstrHifCxt.u32RxSize))) - { - ret = M2M_ERR_FAIL; - M2M_ERR("APP Requested Address beyond the recived buffer address and length\n"); - goto ERR1; - } - - /* Receive the payload */ - ret = nm_read_block(u32Addr, pu8Buf, u16Sz); - if(ret != M2M_SUCCESS)goto ERR1; - - /* check if this is the last packet */ - if((((gstrHifCxt.u32RxAddr + gstrHifCxt.u32RxSize) - (u32Addr + u16Sz)) <= 0) || isDone) - { - /* set RX done */ - ret = hif_set_rx_done(); - } - -ERR1: - return ret; -} - -/** -* @fn hif_register_cb -* @brief To set Callback function for every compantent Component -* @param [in] u8Grp -* Group to which the Callback function should be set. -* @param [in] fn -* function to be set -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -sint8 hif_register_cb(uint8 u8Grp,tpfHifCallBack fn) -{ - sint8 ret = M2M_SUCCESS; - switch(u8Grp) - { - case M2M_REQ_GROUP_IP: - gstrHifCxt.pfIpCb = fn; - break; - case M2M_REQ_GROUP_WIFI: - gstrHifCxt.pfWifiCb = fn; - break; - case M2M_REQ_GROUP_OTA: - gstrHifCxt.pfOtaCb = fn; - break; - case M2M_REQ_GROUP_HIF: - gstrHifCxt.pfHifCb = fn; - break; - case M2M_REQ_GROUP_CRYPTO: - gstrHifCxt.pfCryptoCb = fn; - break; - case M2M_REQ_GROUP_SIGMA: - gstrHifCxt.pfSigmaCb = fn; - break; - case M2M_REQ_GROUP_SSL: - gstrHifCxt.pfSslCb = fn; - break; - default: - M2M_ERR("GRp ? %d\n",u8Grp); - ret = M2M_ERR_FAIL; - break; - } - return ret; -} - -#endif diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_hif.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_hif.h deleted file mode 100644 index 1187183..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_hif.h +++ /dev/null @@ -1,249 +0,0 @@ -/** - * - * \file - * - * \brief This module contains M2M host interface APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _M2M_HIF_ -#define _M2M_HIF_ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "common/include/nm_common.h" -/*!< Include depends on UNO Board is used or not*/ -#ifdef ENABLE_UNO_BOARD -#include "m2m_uno_hif.h" -#endif - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#define M2M_HIF_MAX_PACKET_SIZE (1600 - 4) -/*!< Maximum size of the buffer could be transferred between Host and Firmware. -*/ - -#define M2M_HIF_HDR_OFFSET (sizeof(tstrHifHdr) + 4) - -/** -* @struct tstrHifHdr -* @brief Structure to hold HIF header -*/ -typedef struct -{ - uint8 u8Gid; /*!< Group ID */ - uint8 u8Opcode; /*!< OP code */ - uint16 u16Length; /*!< Payload length */ -}tstrHifHdr; - -#ifdef __cplusplus - extern "C" { -#endif - -/*! -@typedef typedef void (*tpfHifCallBack)(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr); -@brief used to point to Wi-Fi call back function depend on Arduino project or other projects. -@param [in] u8OpCode - HIF Opcode type. -@param [in] u16DataSize - HIF data length. -@param [in] u32Addr - HIF address. -@param [in] grp - HIF group type. -*/ -typedef void (*tpfHifCallBack)(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr); -/** -* @fn NMI_API sint8 hif_init(void * arg); -* @brief - To initialize HIF layer. -* @param [in] arg -* Pointer to the arguments. -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 hif_init(void * arg); -/** -* @fn NMI_API sint8 hif_deinit(void * arg); -* @brief - To Deinitialize HIF layer. -* @param [in] arg -* Pointer to the arguments. -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 hif_deinit(void * arg); -/** -* @fn NMI_API sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, - uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) -* @brief Send packet using host interface. - -* @param [in] u8Gid -* Group ID. -* @param [in] u8Opcode -* Operation ID. -* @param [in] pu8CtrlBuf -* Pointer to the Control buffer. -* @param [in] u16CtrlBufSize - Control buffer size. -* @param [in] u16DataOffset - Packet Data offset. -* @param [in] pu8DataBuf -* Packet buffer Allocated by the caller. -* @param [in] u16DataSize - Packet buffer size (including the HIF header). -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, - uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset); -/* -* @fn hif_receive -* @brief Host interface interrupt serviece routine -* @param [in] u32Addr -* Receive start address -* @param [out] pu8Buf -* Pointer to receive buffer. Allocated by the caller -* @param [in] u16Sz -* Receive buffer size -* @param [in] isDone -* If you don't need any more packets send True otherwise send false -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -NMI_API sint8 hif_receive(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz, uint8 isDone); -/** -* @fn hif_register_cb -* @brief - To set Callback function for every Component. - -* @param [in] u8Grp -* Group to which the Callback function should be set. - -* @param [in] fn -* function to be set to the specified group. -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 hif_register_cb(uint8 u8Grp,tpfHifCallBack fn); -/** -* @fn NMI_API sint8 hif_chip_sleep(void); -* @brief - To make the chip sleep. -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 hif_chip_sleep(void); -/** -* @fn NMI_API sint8 hif_chip_sleep_sc(void); -* @brief - To clear the chip count only but keep the chip awake -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 hif_chip_sleep_sc(void); -/** -* @fn NMI_API sint8 hif_chip_wake(void); -* @brief - To Wakeup the chip. -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -NMI_API sint8 hif_chip_wake(void); -/*! -@fn \ - NMI_API void hif_set_sleep_mode(uint8 u8Pstype); - -@brief - Set the sleep mode of the HIF layer. - -@param [in] u8Pstype - Sleep mode. - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ - -NMI_API void hif_set_sleep_mode(uint8 u8Pstype); -/*! -@fn \ - NMI_API uint8 hif_get_sleep_mode(void); - -@brief - Get the sleep mode of the HIF layer. - -@return - The function SHALL return the sleep mode of the HIF layer. -*/ - -NMI_API uint8 hif_get_sleep_mode(void); - -#ifdef CORTUS_APP -/** -* @fn hif_Resp_handler(uint8 *pu8Buffer, uint16 u16BufferSize) -* @brief - Response handler for HIF layer. - -* @param [in] pu8Buffer - Pointer to the buffer. - -* @param [in] u16BufferSize - Buffer size. - -* @return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 hif_Resp_handler(uint8 *pu8Buffer, uint16 u16BufferSize); -#endif - -/** -* @fn hif_handle_isr(void) -* @brief - Handle interrupt received from NMC1500 firmware. -* @return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 hif_handle_isr(void); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ota.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ota.c deleted file mode 100644 index cf4a30f..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ota.c +++ /dev/null @@ -1,417 +0,0 @@ -/** - * - * \file - * - * \brief NMC1500 IoT OTA Interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#include "common/include/nm_common.h" -#include "driver/include/m2m_types.h" -#include "driver/include/m2m_ota.h" -#include "driver/source/m2m_hif.h" -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -static tpfOtaUpdateCb gpfOtaUpdateCb = NULL; -static tpfOtaNotifCb gpfOtaNotifCb = NULL; - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/** -* @fn m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr, uint8 grp) -* @brief WiFi call back function -* @param [in] u8OpCode -* HIF Opcode type. -* @param [in] u16DataSize -* HIF data length. -* @param [in] u32Addr -* HIF address. -* @param [in] grp -* HIF group type. -* @author -* @date -* @version 1.0 -*/ -static void m2m_ota_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -{ -#ifdef ARDUINO - (void)u16DataSize; // Silence "unused" warning -#endif - sint8 ret = M2M_SUCCESS; - if(u8OpCode == M2M_OTA_RESP_NOTIF_UPDATE_INFO) - { - tstrOtaUpdateInfo strOtaUpdateInfo; - m2m_memset((uint8*)&strOtaUpdateInfo,0,sizeof(tstrOtaUpdateInfo)); - ret = hif_receive(u32Addr,(uint8*)&strOtaUpdateInfo,sizeof(tstrOtaUpdateInfo),0); - if(ret == M2M_SUCCESS) - { - if(gpfOtaNotifCb) - gpfOtaNotifCb(&strOtaUpdateInfo); - } - } - else if (u8OpCode == M2M_OTA_RESP_UPDATE_STATUS) - { - tstrOtaUpdateStatusResp strOtaUpdateStatusResp; - m2m_memset((uint8*)&strOtaUpdateStatusResp,0,sizeof(tstrOtaUpdateStatusResp)); - ret = hif_receive(u32Addr, (uint8*) &strOtaUpdateStatusResp,sizeof(tstrOtaUpdateStatusResp), 0); - if(ret == M2M_SUCCESS) - { - if(gpfOtaUpdateCb) - gpfOtaUpdateCb(strOtaUpdateStatusResp.u8OtaUpdateStatusType,strOtaUpdateStatusResp.u8OtaUpdateStatus); - } - } - else - { - M2M_ERR("Invaild OTA resp %d ?\n",u8OpCode); - } - -} -/*! -@fn \ - NMI_API sint8 m2m_ota_init(tpfOtaUpdateCb pfOtaUpdateCb, tpfOtaNotifCb pfOtaNotifCb); - -@brief - Initialize the OTA layer. - -@param [in] pfOtaUpdateCb - OTA Update callback function - -@param [in] pfOtaNotifCb - OTA notify callback function - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_init(tpfOtaUpdateCb pfOtaUpdateCb, tpfOtaNotifCb pfOtaNotifCb) -{ - sint8 ret = M2M_SUCCESS; - - if(pfOtaUpdateCb){ - gpfOtaUpdateCb = pfOtaUpdateCb; - }else{ - M2M_ERR("Invaild Ota update cb\n"); - } - if(pfOtaNotifCb){ - gpfOtaNotifCb = pfOtaNotifCb; - }else{ - M2M_ERR("Invaild Ota notify cb\n"); - } - - hif_register_cb(M2M_REQ_GROUP_OTA,m2m_ota_cb); - - return ret; -} -/*! -@fn \ - NMI_API sint8 m2m_ota_notif_set_url(uint8 * u8Url); - -@brief - Set the OTA url - -@param [in] u8Url - The url server address - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_notif_set_url(uint8 * u8Url) -{ - sint8 ret = M2M_SUCCESS; - uint16 u16UrlSize = m2m_strlen(u8Url) + 1; - /*Todo: we may change it to data pkt but we need to give it higer priority - but the priorty is not implemnted yet in data pkt - */ - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_NOTIF_SET_URL,u8Url,u16UrlSize,NULL,0,0); - return ret; - -} - -/*! -@fn \ - NMI_API sint8 m2m_ota_notif_check_for_update(void); - -@brief - check for ota update - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_notif_check_for_update(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_NOTIF_CHECK_FOR_UPDATE,NULL,0,NULL,0,0); - return ret; -} - -/*! -@fn \ - NMI_API sint8 m2m_ota_notif_sched(uint32 u32Period); - -@brief - Schedule OTA update - -@param [in] u32Period - Period in days - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_notif_sched(uint32 u32Period) -{ -#ifdef ARDUINO - (void)u32Period; // Silence "unused" warning -#endif - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_NOTIF_CHECK_FOR_UPDATE,NULL,0,NULL,0,0); - return ret; -} - -/*! -@fn \ - NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl); - -@brief - Request OTA start update using the downloaded url - -@param [in] u8DownloadUrl - The download firmware url, you get it from device info - -@return - The function SHALL return 0 for success and a negative value otherwise. - -*/ -NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl) -{ - sint8 ret = M2M_SUCCESS; - uint16 u16DurlSize = m2m_strlen(u8DownloadUrl) + 1; - /*Todo: we may change it to data pkt but we need to give it higer priority - but the priorty is not implemnted yet in data pkt - */ - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_START_FW_UPDATE,u8DownloadUrl,u16DurlSize,NULL,0,0); - return ret; -} -/*! -@fn \ - NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl); - -@brief - Request OTA start for the Cortus app image. - -@param [in] u8DownloadUrl - The cortus application image url. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -*/ -NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl) -{ - sint8 ret = M2M_SUCCESS; - uint16 u16DurlSize = m2m_strlen(u8DownloadUrl) + 1; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_START_CRT_UPDATE,u8DownloadUrl,u16DurlSize,NULL,0,0); - return ret; -} - - -/*! -@fn \ - NMI_API sint8 m2m_ota_rollback(void); - -@brief - Request OTA Rollback image - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_rollback(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_ROLLBACK_FW,NULL,0,NULL,0,0); - return ret; -} -/*! -@fn \ - NMI_API sint8 m2m_ota_rollback_crt(void); - -@brief - Request Cortus application OTA Rollback image - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_rollback_crt(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_ROLLBACK_CRT,NULL,0,NULL,0,0); - return ret; -} - -/*! -@fn \ - NMI_API sint8 m2m_ota_abort(void); - -@brief - Request OTA Abort - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_abort(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_ABORT,NULL,0,NULL,0,0); - return ret; -} - - -/*! -@fn \ - NMI_API sint8 m2m_ota_switch_firmware(void); - -@brief - Switch to the upgraded Firmware - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_switch_firmware(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_SWITCH_FIRMWARE,NULL,0,NULL,0,0); - return ret; -} -/*! -@fn \ - NMI_API sint8 m2m_ota_switch_crt(void); - -@brief - Switch to the upgraded cortus application. - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_switch_crt(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_SWITCH_CRT_IMG,NULL,0,NULL,0,0); - return ret; -} - -/*! -@fn \ - NMI_API sint8 m2m_ota_get_firmware_version(tstrM2mRev * pstrRev); - -@brief - Get the OTA Firmware version. - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_get_firmware_version(tstrM2mRev * pstrRev) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_chip_wake(); - if(ret == M2M_SUCCESS) - { - ret = nm_get_ota_firmware_info(pstrRev); - hif_chip_sleep(); - } - return ret; -} -#if 0 -#define M2M_OTA_FILE "../../../m2m_ota.dat" -NMI_API sint8 m2m_ota_test(void) -{ - uint32 page = 0; - uint8 buffer[1500]; - uint32 u32Sz = 0; - sint8 ret = M2M_SUCCESS; - FILE *fp =NULL; - fp = fopen(M2M_OTA_FILE,"rb"); - if(fp) - { - fseek(fp, 0L, SEEK_END); - u32Sz = ftell(fp); - fseek(fp, 0L, SEEK_SET); - - while(u32Sz > 0) - { - { - page = (rand()%1400); - - if((page<100)||(page>1400)) page = 1400; - } - - if(u32Sz>page) - { - u32Sz-=page; - } - else - { - page = u32Sz; - u32Sz = 0; - } - printf("page %d\n", (int)page); - fread(buffer,page,1,fp); - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_TEST|M2M_REQ_DATA_PKT,NULL,0,(uint8*)&buffer,page,0); - if(ret != M2M_SUCCESS) - { - M2M_ERR("\n"); - } - nm_bsp_sleep(1); - } - - } - else - { - M2M_ERR("nO err\n"); - } - return ret; -} -#endif - diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_periph.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_periph.c deleted file mode 100644 index 0f8890b..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_periph.c +++ /dev/null @@ -1,187 +0,0 @@ -/** - * - * \file - * - * \brief NMC1500 Peripherials Application Interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "driver/include/m2m_periph.h" -#include "driver/source/nmasic.h" -#include "m2m_hif.h" - -#ifdef CONF_PERIPH - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#define GPIO_OP_DIR 0 -#define GPIO_OP_SET 1 -#define GPIO_OP_GET 2 -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -STATIC FUNCTIONS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -static sint8 get_gpio_idx(uint8 u8GpioNum) -{ - if(u8GpioNum >= M2M_PERIPH_GPIO_MAX) return -1; - if(u8GpioNum == M2M_PERIPH_GPIO15) { return 15; - } else if(u8GpioNum == M2M_PERIPH_GPIO16) { return 16; - } else if(u8GpioNum == M2M_PERIPH_GPIO18) { return 18; - } else if(u8GpioNum == M2M_PERIPH_GPIO3) { return 3; - } else if(u8GpioNum == M2M_PERIPH_GPIO4) { return 4; - } else if(u8GpioNum == M2M_PERIPH_GPIO5) { return 5; - } else if(u8GpioNum == M2M_PERIPH_GPIO6) { return 6; - } else { - return -2; - } -} -/* - * GPIO read/write skeleton with wakeup/sleep capability. - */ -static sint8 gpio_ioctl(uint8 op, uint8 u8GpioNum, uint8 u8InVal, uint8 * pu8OutVal) -{ - sint8 ret, gpio; - - ret = hif_chip_wake(); - if(ret != M2M_SUCCESS) goto _EXIT; - - gpio = get_gpio_idx(u8GpioNum); - if(gpio < 0) goto _EXIT1; - - if(op == GPIO_OP_DIR) { - ret = set_gpio_dir((uint8)gpio, u8InVal); - } else if(op == GPIO_OP_SET) { - ret = set_gpio_val((uint8)gpio, u8InVal); - } else if(op == GPIO_OP_GET) { - ret = get_gpio_val((uint8)gpio, pu8OutVal); - } - if(ret != M2M_SUCCESS) goto _EXIT1; - -_EXIT1: - ret = hif_chip_sleep(); -_EXIT: - return ret; -} -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION IMPLEMENTATION -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -sint8 m2m_periph_init(tstrPerphInitParam * param) -{ -#ifdef ARDUINO - (void)param; // Silence "unused" warning -#endif - return M2M_SUCCESS; -} - -sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir) -{ - return gpio_ioctl(GPIO_OP_DIR, u8GpioNum, u8GpioDir, NULL); -} - -sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal) -{ - return gpio_ioctl(GPIO_OP_SET, u8GpioNum, u8GpioVal, NULL); -} - -sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal) -{ - return gpio_ioctl(GPIO_OP_GET, u8GpioNum, 0, pu8GpioVal); -} - -sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn) -{ -#ifdef ARDUINO - (void)u8GpioNum; // Silence "unused" warning - (void)u8PullupEn; -#endif - /* TBD */ - return M2M_SUCCESS; -} - -sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)param; -#endif - /* TBD */ - return M2M_SUCCESS; -} - -sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)u8SlaveAddr; - (void)pu8Buf; - (void)u16BufLen; - (void)flags; -#endif - /* TBD */ - return M2M_SUCCESS; -} - -sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)u8SlaveAddr; - (void)pu8Buf; - (void)u16BufLen; - (void)pu16ReadLen; - (void)flags; -#endif - /* TBD */ - return M2M_SUCCESS; -} - - -sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable) -{ - return pullup_ctrl(pinmask, enable); -} -#endif /* CONF_PERIPH */ \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ssl.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ssl.c deleted file mode 100644 index 07513f7..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_ssl.c +++ /dev/null @@ -1,309 +0,0 @@ -/** - * - * \file - * - * \brief This module contains M2M Wi-Fi APIs implementation. - * - * Copyright (c) 2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "driver/include/m2m_ssl.h" -#include "driver/source/m2m_hif.h" -#include "driver/source/nmasic.h" - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -static tpfAppSSLCb gpfAppSSLCb = NULL; -static uint32 gu32HIFAddr = 0; - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*! - @fn \ m2m_ssl_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) - @brief SSL callback function - @param [in] u8OpCode - HIF Opcode type. - @param [in] u16DataSize - HIF data length. - @param [in] u32Addr - HIF address. -*/ -static void m2m_ssl_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -{ -#ifdef ARDUINO - (void)u16DataSize; // Silence "unused" warning -#endif - sint8 s8tmp = M2M_SUCCESS; - switch(u8OpCode) - { - case M2M_SSL_REQ_ECC: - { - tstrEccReqInfo strEccREQ; - s8tmp = hif_receive(u32Addr, (uint8*)&strEccREQ, sizeof(tstrEccReqInfo), 0); - if(s8tmp == M2M_SUCCESS) - { - if (gpfAppSSLCb) - { - gu32HIFAddr = u32Addr + sizeof(tstrEccReqInfo); - gpfAppSSLCb(M2M_SSL_REQ_ECC, &strEccREQ); - } - } - } - break; - case M2M_SSL_RESP_SET_CS_LIST: - { - tstrSslSetActiveCsList strCsList; - s8tmp = hif_receive(u32Addr, (uint8*)&strCsList, sizeof(tstrSslSetActiveCsList), 0); - if(s8tmp == M2M_SUCCESS) - { - if (gpfAppSSLCb) - gpfAppSSLCb(M2M_SSL_RESP_SET_CS_LIST, &strCsList); - } - } - break; - } - if(s8tmp != M2M_SUCCESS) - { - M2M_ERR("Error receiving SSL from the HIF\n"); - } -} - - -/*! - @fn \ m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz) - @brief Sends ECC responses to the WINC - @param [in] strECCResp - ECC Response struct. - @param [in] pu8RspDataBuffe - Pointer of the response data to be sent. - @param [in] u16RspDataSz - Response data size. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz) -{ - sint8 s8Ret = M2M_SUCCESS; - - s8Ret = hif_send(M2M_REQ_GROUP_SSL, (M2M_SSL_RESP_ECC | M2M_REQ_DATA_PKT), (uint8*)strECCResp, sizeof(tstrEccReqInfo), pu8RspDataBuff, u16RspDataSz, sizeof(tstrEccReqInfo)); - - return s8Ret; -} - -/*! - @fn \ m2m_ssl_send_certs_to_winc(uint8* sector_buffer, uint32 sector_size) - @brief Sends certificates to the WINC - @param [in] pu8Buffer - Pointer to the certificates. - @param [in] u32BufferSz - Size of the certificates. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_send_certs_to_winc(uint8* pu8Buffer, uint32 u32BufferSz) -{ - sint8 s8Ret = M2M_SUCCESS; - - s8Ret = hif_send(M2M_REQ_GROUP_SSL, (M2M_SSL_IND_CERTS_ECC | M2M_REQ_DATA_PKT), NULL, 0, pu8Buffer, u32BufferSz, 0); - - return s8Ret; -} - -/*! - @fn \ m2m_ssl_retrieve_cert(uint32 u32ReadAddr, uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key) - @brief Retrieve the certificate to be verified from the WINC - @param [in] pu16CurveType - Pointer to the certificate curve type. - @param [in] pu8Hash - Pointer to the certificate hash. - @param [in] pu8Sig - Pointer to the certificate signature. - @param [in] pu8Key - Pointer to the certificate Key. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_retrieve_cert(uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key) -{ - uint8 bSetRxDone = 1; - uint16 u16HashSz, u16SigSz, u16KeySz; - sint8 s8Ret = M2M_SUCCESS; - - if(gu32HIFAddr == 0) return M2M_ERR_FAIL; - - if(hif_receive(gu32HIFAddr, (uint8*)pu16CurveType, 2, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += 2; - - if(hif_receive(gu32HIFAddr, (uint8*)&u16KeySz, 2, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += 2; - - if(hif_receive(gu32HIFAddr, (uint8*)&u16HashSz, 2, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += 2; - - if(hif_receive(gu32HIFAddr, (uint8*)&u16SigSz, 2, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += 2; - - (*pu16CurveType)= _htons((*pu16CurveType)); - pu8Key->u16Size = _htons(u16KeySz); - u16HashSz = _htons(u16HashSz); - u16SigSz = _htons(u16SigSz); - - if(hif_receive(gu32HIFAddr, pu8Key->X, pu8Key->u16Size * 2, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += (pu8Key->u16Size * 2); - - if(hif_receive(gu32HIFAddr, pu8Hash, u16HashSz, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += u16HashSz; - - if(hif_receive(gu32HIFAddr, pu8Sig, u16SigSz, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += u16SigSz; - - bSetRxDone = 0; - -__ERR: - if(bSetRxDone) - { - s8Ret = M2M_ERR_FAIL; - hif_receive(0, NULL, 0, 1); - } - return s8Ret; -} - -/*! - @fn \ m2m_ssl_retrieve_hash(uint32 u32ReadAddr, uint8* pu8Hash, uint16 u16HashSz) - @brief Retrieve the certificate hash - @param [in] pu8Hash - Pointer to the certificate hash. - @param [in] u16HashSz - Hash size. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_retrieve_hash(uint8* pu8Hash, uint16 u16HashSz) -{ - uint8 bSetRxDone = 1; - sint8 s8Ret = M2M_SUCCESS; - - if(gu32HIFAddr == 0) return M2M_ERR_FAIL; - - if(hif_receive(gu32HIFAddr, pu8Hash, u16HashSz, 0) != M2M_SUCCESS) goto __ERR; - - bSetRxDone = 0; - -__ERR: - if(bSetRxDone) - { - s8Ret = M2M_ERR_FAIL; - hif_receive(0, NULL, 0, 1); - } - return s8Ret; -} - -/*! - @fn \ m2m_ssl_stop_processing_certs(void) - @brief Stops receiving from the HIF -*/ -NMI_API void m2m_ssl_stop_processing_certs(void) -{ - hif_receive(0, NULL, 0, 1); -} - -/*! - @fn \ m2m_ssl_ecc_process_done(void) - @brief Stops receiving from the HIF -*/ -NMI_API void m2m_ssl_ecc_process_done(void) -{ - gu32HIFAddr = 0; -} - -/*! -@fn \ - m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP); - Override the default Active SSL ciphers in the SSL module with a certain combination selected by the caller in the form of - a bitmap containing the required ciphers to be on. - There is no need to call this function if the application will not change the default ciphersuites. - -@param [in] u32SslCsBMP - Bitmap containing the desired ciphers to be enabled for the SSL module. The ciphersuites are defined in - @ref SSLCipherSuiteID. - The default ciphersuites are all ciphersuites supported by the firmware with the exception of ECC ciphersuites. - The caller can override the default with any desired combination, except for combinations involving both RSA - and ECC; if any RSA ciphersuite is enabled, then firmware will disable all ECC ciphersuites. - If u32SslCsBMP does not contain any ciphersuites supported by firmware, then the current active list will not - be changed. - -@return - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) -*/ -sint8 m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP) -{ - sint8 s8Ret = M2M_SUCCESS; - tstrSslSetActiveCsList strCsList; - - strCsList.u32CsBMP = u32SslCsBMP; - s8Ret = hif_send(M2M_REQ_GROUP_SSL, M2M_SSL_REQ_SET_CS_LIST, (uint8*)&strCsList, sizeof(tstrSslSetActiveCsList), NULL, 0, 0); - - return s8Ret; -} - -/*! - @fn \ m2m_ssl_init(tpfAppSslCb pfAppSslCb); - @brief Initializes the SSL layer. - @param [in] pfAppSslCb - Application SSL callback function. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_init(tpfAppSSLCb pfAppSSLCb) -{ - sint8 s8Ret = M2M_SUCCESS; - - gpfAppSSLCb = pfAppSSLCb; - gu32HIFAddr = 0; - - s8Ret = hif_register_cb(M2M_REQ_GROUP_SSL,m2m_ssl_cb); - if (s8Ret != M2M_SUCCESS) - { - M2M_ERR("hif_register_cb() failed with ret=%d", s8Ret); - } - return s8Ret; -} \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_wifi.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_wifi.c deleted file mode 100644 index 7998623..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/m2m_wifi.c +++ /dev/null @@ -1,1522 +0,0 @@ -/** - * - * \file - * - * \brief This module contains M2M Wi-Fi APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "driver/include/m2m_wifi.h" -#include "driver/source/m2m_hif.h" -#include "driver/source/nmasic.h" - -static volatile uint8 gu8ChNum; -static volatile uint8 gu8scanInProgress = 0; -static tpfAppWifiCb gpfAppWifiCb = NULL; - - -#ifdef ETH_MODE -static tpfAppEthCb gpfAppEthCb = NULL; -static uint8* gau8ethRcvBuf=NULL; -static uint16 gu16ethRcvBufSize ; -#endif - - -//#define CONF_MGMT -#ifdef CONF_MGMT -static tpfAppMonCb gpfAppMonCb = NULL; -static struct _tstrMgmtCtrl -{ - uint8* pu8Buf; - uint16 u16Offset; - uint16 u16Sz; -} -gstrMgmtCtrl = {NULL, 0 , 0}; -#endif -/** -* @fn m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr, uint8 grp) -* @brief WiFi call back function -* @param [in] u8OpCode -* HIF Opcode type. -* @param [in] u16DataSize -* HIF data length. -* @param [in] u32Addr -* HIF address. -* @param [in] grp -* HIF group type. -* @author -* @date -* @version 1.0 -*/ -static void m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -{ -#ifdef ARDUINO - (void)u16DataSize; // Silence "unused" warning -#endif - uint8 rx_buf[8]; - if (u8OpCode == M2M_WIFI_RESP_CON_STATE_CHANGED) - { - tstrM2mWifiStateChanged strState; - if (hif_receive(u32Addr, (uint8*) &strState,sizeof(tstrM2mWifiStateChanged), 0) == M2M_SUCCESS) - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_CON_STATE_CHANGED, &strState); - } - } - else if (u8OpCode == M2M_WIFI_RESP_GET_SYS_TIME) - { - tstrSystemTime strSysTime; - if (hif_receive(u32Addr, (uint8*) &strSysTime,sizeof(tstrSystemTime), 0) == M2M_SUCCESS) - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_GET_SYS_TIME, &strSysTime); - } - } - else if(u8OpCode == M2M_WIFI_RESP_CONN_INFO) - { - tstrM2MConnInfo strConnInfo; - if(hif_receive(u32Addr, (uint8*)&strConnInfo, sizeof(tstrM2MConnInfo), 1) == M2M_SUCCESS) - { - if(gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_CONN_INFO, &strConnInfo); - } - } - else if (u8OpCode == M2M_WIFI_RESP_MEMORY_RECOVER) - { -#if 0 - if (hif_receive(u32Addr, rx_buf, 4, 1) == M2M_SUCCESS) - { - tstrM2mWifiStateChanged strState; - m2m_memcpy((uint8*) &strState, rx_buf,sizeof(tstrM2mWifiStateChanged)); - if (app_wifi_recover_cb) - app_wifi_recover_cb(strState.u8CurrState); - } -#endif - } - else if (u8OpCode == M2M_WIFI_REQ_DHCP_CONF) - { - tstrM2MIPConfig strIpConfig; -#ifdef ARDUINO - extern uint32 nmdrv_firm_ver; - uint16 rxSize = sizeof(tstrM2MIPConfig); - - if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 5, 0)) { - // for backwards compatibility with firmware 19.4.4 and older, - // the old tstrM2MIPConfig does not contain the u32DhcpLeaseTime field - rxSize -= sizeof(strIpConfig.u32DhcpLeaseTime); - } - - if (hif_receive(u32Addr, (uint8 *)&strIpConfig, rxSize, 0) == M2M_SUCCESS) -#else - if (hif_receive(u32Addr, (uint8 *)&strIpConfig, sizeof(tstrM2MIPConfig), 0) == M2M_SUCCESS) -#endif - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_REQ_DHCP_CONF, (uint8 *)&strIpConfig); - } - } - else if (u8OpCode == M2M_WIFI_REQ_WPS) - { - tstrM2MWPSInfo strWps; - m2m_memset((uint8*)&strWps,0,sizeof(tstrM2MWPSInfo)); - if(hif_receive(u32Addr, (uint8*)&strWps, sizeof(tstrM2MWPSInfo), 0) == M2M_SUCCESS) - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_REQ_WPS, &strWps); - } - } - else if (u8OpCode == M2M_WIFI_RESP_IP_CONFLICT) - { - uint32 u32ConflictedIP; - if(hif_receive(u32Addr, (uint8 *)&u32ConflictedIP, sizeof(u32ConflictedIP), 0) == M2M_SUCCESS) - { - M2M_INFO("Conflicted IP \" %u.%u.%u.%u \" \n", - BYTE_0(u32ConflictedIP),BYTE_1(u32ConflictedIP),BYTE_2(u32ConflictedIP),BYTE_3(u32ConflictedIP)); - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_IP_CONFLICT, NULL); - - } - } - else if (u8OpCode == M2M_WIFI_RESP_SCAN_DONE) - { - tstrM2mScanDone strState; - gu8scanInProgress = 0; - if(hif_receive(u32Addr, (uint8*)&strState, sizeof(tstrM2mScanDone), 0) == M2M_SUCCESS) - { - gu8ChNum = strState.u8NumofCh; - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_SCAN_DONE, &strState); - } - } - else if (u8OpCode == M2M_WIFI_RESP_SCAN_RESULT) - { - tstrM2mWifiscanResult strScanResult; - if(hif_receive(u32Addr, (uint8*)&strScanResult, sizeof(tstrM2mWifiscanResult), 0) == M2M_SUCCESS) - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_SCAN_RESULT, &strScanResult); - } - } - else if (u8OpCode == M2M_WIFI_RESP_CURRENT_RSSI) - { - if (hif_receive(u32Addr, rx_buf, 4, 0) == M2M_SUCCESS) - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_CURRENT_RSSI, rx_buf); - } - } - else if (u8OpCode == M2M_WIFI_RESP_CLIENT_INFO) - { - if (hif_receive(u32Addr, rx_buf, 4, 0) == M2M_SUCCESS) - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_CLIENT_INFO, rx_buf); - } - } - else if(u8OpCode == M2M_WIFI_RESP_PROVISION_INFO) - { - tstrM2MProvisionInfo strProvInfo; - if(hif_receive(u32Addr, (uint8*)&strProvInfo, sizeof(tstrM2MProvisionInfo), 1) == M2M_SUCCESS) - { - if(gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_PROVISION_INFO, &strProvInfo); - } - } - else if(u8OpCode == M2M_WIFI_RESP_DEFAULT_CONNECT) - { - tstrM2MDefaultConnResp strResp; - if(hif_receive(u32Addr, (uint8*)&strResp, sizeof(tstrM2MDefaultConnResp), 1) == M2M_SUCCESS) - { - if(gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_DEFAULT_CONNECT, &strResp); - } - } - - else if(u8OpCode == M2M_WIFI_RESP_GET_PRNG) - { - tstrPrng strPrng; - if(hif_receive(u32Addr, (uint8*)&strPrng,sizeof(tstrPrng), 0) == M2M_SUCCESS) - { - if(hif_receive(u32Addr + sizeof(tstrPrng),strPrng.pu8RngBuff,strPrng.u16PrngSize, 1) == M2M_SUCCESS) - { - if(gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_GET_PRNG,&strPrng); - } - } - } -#ifdef ETH_MODE - else if(u8OpCode == M2M_WIFI_RESP_ETHERNET_RX_PACKET) - { - uint8 u8SetRxDone; - tstrM2mIpRsvdPkt strM2mRsvd; - if(hif_receive(u32Addr, &strM2mRsvd ,sizeof(tstrM2mIpRsvdPkt), 0) == M2M_SUCCESS) - { - tstrM2mIpCtrlBuf strM2mIpCtrlBuf; - uint16 u16Offset = strM2mRsvd.u16PktOffset; - strM2mIpCtrlBuf.u16RemainigDataSize = strM2mRsvd.u16PktSz; - if((gpfAppEthCb) && (gau8ethRcvBuf) && (gu16ethRcvBufSize > 0)) - { - do - { - u8SetRxDone = 1; - if(strM2mIpCtrlBuf.u16RemainigDataSize > gu16ethRcvBufSize) - { - u8SetRxDone = 0; - strM2mIpCtrlBuf.u16DataSize = gu16ethRcvBufSize; - } - else - { - strM2mIpCtrlBuf.u16DataSize = strM2mIpCtrlBuf.u16RemainigDataSize; - } - - if(hif_receive(u32Addr + u16Offset, gau8ethRcvBuf, strM2mIpCtrlBuf.u16DataSize, u8SetRxDone) == M2M_SUCCESS) - { - strM2mIpCtrlBuf.u16RemainigDataSize -= strM2mIpCtrlBuf.u16DataSize; - u16Offset += strM2mIpCtrlBuf.u16DataSize; - gpfAppEthCb(M2M_WIFI_RESP_ETHERNET_RX_PACKET, gau8ethRcvBuf, &(strM2mIpCtrlBuf)); - } - else - { - break; - } - }while (strM2mIpCtrlBuf.u16RemainigDataSize > 0); - } - } - } -#endif /* ETH_MODE */ -#ifdef CONF_MGMT - else if(u8OpCode == M2M_WIFI_RESP_WIFI_RX_PACKET) - { - - tstrM2MWifiRxPacketInfo strRxPacketInfo; - if(u16DataSize >= sizeof(tstrM2MWifiRxPacketInfo)) { - if(hif_receive(u32Addr, (uint8*)&strRxPacketInfo, sizeof(tstrM2MWifiRxPacketInfo), 0) == M2M_SUCCESS) - { - u16DataSize -= sizeof(tstrM2MWifiRxPacketInfo); - if(u16DataSize > 0 && gstrMgmtCtrl.pu8Buf != NULL) - { - if(u16DataSize > (gstrMgmtCtrl.u16Sz + gstrMgmtCtrl.u16Offset)) - { - u16DataSize = gstrMgmtCtrl.u16Sz; - } - u32Addr += sizeof(tstrM2MWifiRxPacketInfo) + gstrMgmtCtrl.u16Offset; - if(hif_receive(u32Addr , gstrMgmtCtrl.pu8Buf, u16DataSize, 1) != M2M_SUCCESS) return; - } - if(gpfAppMonCb) - gpfAppMonCb(&strRxPacketInfo, gstrMgmtCtrl.pu8Buf,u16DataSize); - } - } else { - M2M_ERR("Incorrect mon data size %u\n", u16DataSize); - } - } -#endif - else - { - M2M_ERR("REQ Not defined %d\n",u8OpCode); - } -} - -sint8 m2m_wifi_download_mode() -{ - sint8 ret = M2M_SUCCESS; - /* Apply device specific initialization. */ - ret = nm_drv_init_download_mode(); - if(ret != M2M_SUCCESS) goto _EXIT0; - - - - enable_interrupts(); - -_EXIT0: - return ret; -} - -static sint8 m2m_validate_ap_parameters(CONST tstrM2MAPConfig* pstrM2MAPConfig) -{ - sint8 s8Ret = M2M_SUCCESS; - /* Check for incoming pointer */ - if(pstrM2MAPConfig == NULL) - { - M2M_ERR("INVALID POINTER\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - /* Check for SSID */ - if((m2m_strlen((uint8 *)pstrM2MAPConfig->au8SSID) <= 0) || (m2m_strlen((uint8 *)pstrM2MAPConfig->au8SSID) >= M2M_MAX_SSID_LEN)) - { - M2M_ERR("INVALID SSID\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - /* Check for Channel */ - if(pstrM2MAPConfig->u8ListenChannel > M2M_WIFI_CH_14 || pstrM2MAPConfig->u8ListenChannel < M2M_WIFI_CH_1) - { - M2M_ERR("INVALID CH\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - /* Check for DHCP Server IP address */ - if(!(pstrM2MAPConfig->au8DHCPServerIP[0] || pstrM2MAPConfig->au8DHCPServerIP[1])) - { - if(!(pstrM2MAPConfig->au8DHCPServerIP[2])) - { - M2M_ERR("INVALID DHCP SERVER IP\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - } - /* Check for Security */ - if(pstrM2MAPConfig->u8SecType == M2M_WIFI_SEC_OPEN) - { - goto ERR1; - } - else if(pstrM2MAPConfig->u8SecType == M2M_WIFI_SEC_WEP) - { - /* Check for WEP Key index */ - if((pstrM2MAPConfig->u8KeyIndx <= 0) || (pstrM2MAPConfig->u8KeyIndx > WEP_KEY_MAX_INDEX)) - { - M2M_ERR("INVALID KEY INDEX\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - /* Check for WEP Key size */ - if( (pstrM2MAPConfig->u8KeySz != WEP_40_KEY_STRING_SIZE) && - (pstrM2MAPConfig->u8KeySz != WEP_104_KEY_STRING_SIZE) - ) - { - M2M_ERR("INVALID KEY STRING SIZE\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - - if((m2m_strlen((uint8 *)pstrM2MAPConfig->au8WepKey) <= 0) || (m2m_strlen((uint8 *)pstrM2MAPConfig->au8WepKey) > WEP_104_KEY_STRING_SIZE)) - { - M2M_ERR("INVALID KEY SIZE\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - } - else if(pstrM2MAPConfig->u8SecType == M2M_WIFI_SEC_WPA_PSK) - { - /* Check for WPA Key size */ - if( ((pstrM2MAPConfig->u8KeySz + 1) < M2M_MIN_PSK_LEN) || ((pstrM2MAPConfig->u8KeySz + 1) > M2M_MAX_PSK_LEN)) - { - M2M_ERR("INVALID WPA KEY SIZE\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - } - else - { - M2M_ERR("INVALID AUTHENTICATION MODE\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - -ERR1: - return s8Ret; -} -static sint8 m2m_validate_scan_options(tstrM2MScanOption* ptstrM2MScanOption) -{ - sint8 s8Ret = M2M_SUCCESS; - /* Check for incoming pointer */ - if(ptstrM2MScanOption == NULL) - { - M2M_ERR("INVALID POINTER\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR; - } - /* Check for valid No of slots */ - if(ptstrM2MScanOption->u8NumOfSlot == 0) - { - M2M_ERR("INVALID No of scan slots! %d\n",ptstrM2MScanOption->u8NumOfSlot); - s8Ret = M2M_ERR_FAIL; - goto ERR; - } - /* Check for valid time of slots */ - if(ptstrM2MScanOption->u8SlotTime < 10 || ptstrM2MScanOption->u8SlotTime > 250) - { - M2M_ERR("INVALID scan slot time! %d\n",ptstrM2MScanOption->u8SlotTime); - s8Ret = M2M_ERR_FAIL; - goto ERR; - } - /* Check for valid No of probe requests per slot */ - if((ptstrM2MScanOption->u8ProbesPerSlot == 0)||(ptstrM2MScanOption->u8ProbesPerSlot > M2M_SCAN_DEFAULT_NUM_PROBE)) - { - M2M_ERR("INVALID No of probe requests per scan slot %d\n",ptstrM2MScanOption->u8ProbesPerSlot); - s8Ret = M2M_ERR_FAIL; - goto ERR; - } - /* Check for valid RSSI threshold */ - if((ptstrM2MScanOption->s8RssiThresh < -99) || (ptstrM2MScanOption->s8RssiThresh >= 0)) - { - M2M_ERR("INVALID RSSI threshold %d \n",ptstrM2MScanOption->s8RssiThresh); - s8Ret = M2M_ERR_FAIL; - } - -ERR: - return s8Ret; -} - -sint8 m2m_wifi_send_crl(tstrTlsCrlInfo* pCRL) -{ - sint8 s8Ret = M2M_ERR_FAIL; - s8Ret = hif_send(M2M_REQ_GROUP_SSL, M2M_SSL_IND_CRL|M2M_REQ_DATA_PKT, NULL, 0, (uint8*)pCRL, sizeof(tstrTlsCrlInfo), 0); - return s8Ret; -} - -sint8 m2m_wifi_init(tstrWifiInitParam * param) -{ - tstrM2mRev strtmp; - sint8 ret = M2M_SUCCESS; - uint8 u8WifiMode = M2M_WIFI_MODE_NORMAL; - - if(param == NULL) { - ret = M2M_ERR_FAIL; - goto _EXIT0; - } - - gpfAppWifiCb = param->pfAppWifiCb; - -#ifdef ETH_MODE - gpfAppEthCb = param->strEthInitParam.pfAppEthCb; - gau8ethRcvBuf = param->strEthInitParam.au8ethRcvBuf; - gu16ethRcvBufSize = param->strEthInitParam.u16ethRcvBufSize; - u8WifiMode = param->strEthInitParam.u8EthernetEnable; -#endif /* ETH_MODE */ - -#ifdef CONF_MGMT - gpfAppMonCb = param->pfAppMonCb; -#endif - gu8scanInProgress = 0; - /* Apply device specific initialization. */ - ret = nm_drv_init(&u8WifiMode); - if(ret != M2M_SUCCESS) goto _EXIT0; - /* Initialize host interface module */ - ret = hif_init(NULL); - if(ret != M2M_SUCCESS) goto _EXIT1; - - hif_register_cb(M2M_REQ_GROUP_WIFI,m2m_wifi_cb); - - ret = nm_get_firmware_full_info(&strtmp); - -#ifdef ARDUINO - if (M2M_ERR_FAIL == ret) - { - // for compatibility with firmware version 19.3.0 - ret = nm_get_firmware_info(&strtmp); - } -#endif - M2M_INFO("Firmware ver : %u.%u.%u Svnrev %u\n", strtmp.u8FirmwareMajor, strtmp.u8FirmwareMinor, strtmp.u8FirmwarePatch,strtmp.u16FirmwareSvnNum); - M2M_INFO("Firmware Build %s Time %s\n",strtmp.BuildDate,strtmp.BuildTime); - M2M_INFO("Firmware Min driver ver : %u.%u.%u\n", strtmp.u8DriverMajor, strtmp.u8DriverMinor, strtmp.u8DriverPatch); - M2M_INFO("Driver ver: %u.%u.%u\n", M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); - M2M_INFO("Driver built at %s\t%s\n",__DATE__,__TIME__); - if(M2M_ERR_FW_VER_MISMATCH == ret) - { - M2M_ERR("Mismatch Firmawre Version\n"); - } - - goto _EXIT0; - -_EXIT1: - nm_drv_deinit(NULL); -_EXIT0: - return ret; -} - -sint8 m2m_wifi_deinit(void * arg) -{ -#ifdef ARDUINO - (void)arg; // Silence "unused" warning -#endif - hif_deinit(NULL); - - nm_drv_deinit(NULL); - - return M2M_SUCCESS; -} - - -#ifdef ARDUINO -#include "socket/include/socket_buffer.h" -extern tstrSocketBuffer gastrSocketBuffer[]; -#endif - -sint8 m2m_wifi_handle_events(void * arg) -{ -#ifdef ARDUINO - (void)arg; // Silence "unused" warning - - uint8 i; - - /* Arduino API LIMITATION: */ - /* To be compliant with the standard Arduino WiFi API socket must be buffered. */ - /* WiFi101 shield does not have this ability and automatically pushes incoming */ - /* data to the Arduino MCU. Function m2m_wifi_handle_events() is taking care of */ - /* this transfer. Hence by ensuring that all the MCU socket buffers are available */ - /* we can perform the transfer. */ - /* However, if one socket buffer is full, we have to delay this transfer by */ - /* returning an error value, as we have no way of knowing which socket is about */ - /* to be used. */ - /* Consequently, the Arduino sketch must NOT block on reading only one socket if */ - /* several sockets are to be used. Instead, application must carefully read for */ - /* all sockets, anytime. */ - for (i = 0; i < MAX_SOCKET; ++i) { - if (gastrSocketBuffer[i].flag && (*(gastrSocketBuffer[i].flag) & SOCKET_BUFFER_FLAG_FULL)) { - return M2M_ERR_FAIL; - } - } -#endif - return hif_handle_isr(); -} - -sint8 m2m_wifi_default_connect(void) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DEFAULT_CONNECT, NULL, 0,NULL, 0,0); -} - -sint8 m2m_wifi_connect(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch) -{ - return m2m_wifi_connect_sc(pcSsid, u8SsidLen, u8SecType, pvAuthInfo, u16Ch,0); -} -sint8 m2m_wifi_connect_sc(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch, uint8 u8NoSaveCred) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mWifiConnect strConnect; - tstrM2MWifiSecInfo *pstrAuthInfo; - - if(u8SecType != M2M_WIFI_SEC_OPEN) - { - if(pvAuthInfo == NULL) - { - M2M_ERR("Key is not valid\n"); - ret = M2M_ERR_FAIL; - goto ERR1; - } - if((u8SecType == M2M_WIFI_SEC_WPA_PSK) && (m2m_strlen(pvAuthInfo) == (M2M_MAX_PSK_LEN-1))) - { - uint8 i = 0; - uint8* pu8Psk = (uint8*)pvAuthInfo; - while(i < (M2M_MAX_PSK_LEN-1)) - { - if(pu8Psk[i]<'0' || (pu8Psk[i]>'9' && pu8Psk[i] < 'A')|| (pu8Psk[i]>'F' && pu8Psk[i] < 'a') || pu8Psk[i] > 'f') - { - M2M_ERR("Invalid Key\n"); - ret = M2M_ERR_FAIL; - goto ERR1; - } - i++; - } - } - } - if((u8SsidLen<=0)||(u8SsidLen>=M2M_MAX_SSID_LEN)) - { - M2M_ERR("SSID LEN INVALID\n"); - ret = M2M_ERR_FAIL; - goto ERR1; - } - - if(u16Ch < M2M_WIFI_CH_1|| u16Ch > M2M_WIFI_CH_14) - { - if(u16Ch!=M2M_WIFI_CH_ALL) - { - M2M_ERR("CH INVALID\n"); - ret = M2M_ERR_FAIL; - goto ERR1; - } - } - - - m2m_memcpy(strConnect.au8SSID, (uint8*)pcSsid, u8SsidLen); - strConnect.au8SSID[u8SsidLen] = 0; - strConnect.u16Ch = NM_BSP_B_L_16(u16Ch); - /* Credentials will be Not be saved if u8NoSaveCred is set */ - strConnect.u8NoSaveCred = u8NoSaveCred ? 1:0; - pstrAuthInfo = &strConnect.strSec; - pstrAuthInfo->u8SecType = u8SecType; - - if(u8SecType == M2M_WIFI_SEC_WEP) - { - tstrM2mWifiWepParams * pstrWepParams = (tstrM2mWifiWepParams*)pvAuthInfo; - tstrM2mWifiWepParams *pstrWep = &pstrAuthInfo->uniAuth.strWepInfo; -#ifdef ARDUINO - pstrWep->u8KeyIndx =pstrWepParams->u8KeyIndx; -#else - pstrWep->u8KeyIndx =pstrWepParams->u8KeyIndx-1; -#endif - - if(pstrWep->u8KeyIndx >= WEP_KEY_MAX_INDEX) - { - M2M_ERR("Invalid Wep key index %d\n", pstrWep->u8KeyIndx); - ret = M2M_ERR_FAIL; - goto ERR1; - } -#ifdef ARDUINO - pstrWep->u8KeySz = pstrWepParams->u8KeySz; -#else - pstrWep->u8KeySz = pstrWepParams->u8KeySz-1; -#endif - if ((pstrWep->u8KeySz != WEP_40_KEY_STRING_SIZE)&& (pstrWep->u8KeySz != WEP_104_KEY_STRING_SIZE)) - { - M2M_ERR("Invalid Wep key length %d\n", pstrWep->u8KeySz); - ret = M2M_ERR_FAIL; - goto ERR1; - } - m2m_memcpy((uint8*)pstrWep->au8WepKey,(uint8*)pstrWepParams->au8WepKey, pstrWepParams->u8KeySz); - pstrWep->au8WepKey[pstrWepParams->u8KeySz] = 0; - - } - - - else if(u8SecType == M2M_WIFI_SEC_WPA_PSK) - { - uint16 u16KeyLen = m2m_strlen((uint8*)pvAuthInfo); - if((u16KeyLen <= 0)||(u16KeyLen >= M2M_MAX_PSK_LEN)) - { - M2M_ERR("Incorrect PSK key length\n"); - ret = M2M_ERR_FAIL; - goto ERR1; - } - m2m_memcpy(pstrAuthInfo->uniAuth.au8PSK, (uint8*)pvAuthInfo, u16KeyLen + 1); - } - else if(u8SecType == M2M_WIFI_SEC_802_1X) - { - m2m_memcpy((uint8*)&pstrAuthInfo->uniAuth.strCred1x, (uint8*)pvAuthInfo, sizeof(tstr1xAuthCredentials)); - } - else if(u8SecType == M2M_WIFI_SEC_OPEN) - { - - } - else - { - M2M_ERR("undefined sec type\n"); - ret = M2M_ERR_FAIL; - goto ERR1; - } - - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CONNECT, (uint8*)&strConnect, sizeof(tstrM2mWifiConnect),NULL, 0,0); - -ERR1: - return ret; -} - -sint8 m2m_wifi_disconnect(void) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISCONNECT, NULL, 0, NULL, 0,0); -} -sint8 m2m_wifi_set_mac_address(uint8 au8MacAddress[6]) -{ - tstrM2mSetMacAddress strTmp; - m2m_memcpy((uint8*) strTmp.au8Mac, (uint8*) au8MacAddress, 6); - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_MAC_ADDRESS, - (uint8*) &strTmp, sizeof(tstrM2mSetMacAddress), NULL, 0,0); -} - -sint8 m2m_wifi_set_static_ip(tstrM2MIPConfig * pstrStaticIPConf) -{ - pstrStaticIPConf->u32DNS = NM_BSP_B_L_32(pstrStaticIPConf->u32DNS); - pstrStaticIPConf->u32Gateway = NM_BSP_B_L_32(pstrStaticIPConf->u32Gateway); - pstrStaticIPConf->u32StaticIP = NM_BSP_B_L_32( - pstrStaticIPConf->u32StaticIP); - pstrStaticIPConf->u32SubnetMask = NM_BSP_B_L_32( - pstrStaticIPConf->u32SubnetMask); - return hif_send(M2M_REQ_GROUP_IP, M2M_IP_REQ_STATIC_IP_CONF, - (uint8*) pstrStaticIPConf, sizeof(tstrM2MIPConfig), NULL, 0,0); -} - -sint8 m2m_wifi_request_dhcp_client(void) -{ - /*legacy API should be removed */ - return 0; -} -sint8 m2m_wifi_request_dhcp_server(uint8* addr) -{ -#ifdef ARDUINO - (void)addr; // Silence "unused" warning -#endif - /*legacy API should be removed */ - return 0; -} -/*! -@fn NMI_API sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt * pstrM2mLsnInt); -@brief Set the Wi-Fi listen interval for power save operation. It is represented in units - of AP Beacon periods. -@param [in] pstrM2mLsnInt - Structure holding the listen interval configurations. -@return The function SHALL return 0 for success and a negative value otherwise. -@sa tstrM2mLsnInt , m2m_wifi_set_sleep_mode -@pre m2m_wifi_set_sleep_mode shall be called first -@warning The Function called once after initialization. -*/ -sint8 m2m_wifi_enable_dhcp(uint8 u8DhcpEn ) -{ - - uint8 u8Req; - u8Req = u8DhcpEn ? M2M_IP_REQ_ENABLE_DHCP : M2M_IP_REQ_DISABLE_DHCP; - return hif_send(M2M_REQ_GROUP_IP, u8Req, NULL, 0, NULL, 0, 0); - - -} - -sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt* pstrM2mLsnInt) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_LSN_INT, (uint8*)pstrM2mLsnInt, sizeof(tstrM2mLsnInt), NULL, 0, 0); -} - -sint8 m2m_wifi_set_cust_InfoElement(uint8* pau8M2mCustInfoElement) -{ - - sint8 ret = M2M_ERR_FAIL; - if(pau8M2mCustInfoElement != NULL) - { - if((pau8M2mCustInfoElement[0] + 1) < M2M_CUST_IE_LEN_MAX) - { - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CUST_INFO_ELEMENT|M2M_REQ_DATA_PKT, (uint8*)pau8M2mCustInfoElement, pau8M2mCustInfoElement[0]+1, NULL, 0, 0); - } - } - return ret; -} - -sint8 m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption) -{ - sint8 s8Ret = M2M_ERR_FAIL; - if(m2m_validate_scan_options (ptstrM2MScanOption) == M2M_SUCCESS) - { - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_SCAN_OPTION, (uint8*)ptstrM2MScanOption, sizeof(tstrM2MScanOption),NULL, 0,0); - } - return s8Ret; -} -sint8 m2m_wifi_set_scan_region(uint16 ScanRegion) -{ - sint8 s8Ret = M2M_ERR_FAIL; - tstrM2MScanRegion strScanRegion; - strScanRegion.u16ScanRegion = ScanRegion; - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_SCAN_REGION, (uint8*)&strScanRegion, sizeof(tstrM2MScanRegion),NULL, 0,0); - return s8Ret; -} -sint8 m2m_wifi_request_scan(uint8 ch) -{ - sint8 s8Ret = M2M_SUCCESS; - - if(!gu8scanInProgress) - { - if(((ch >= M2M_WIFI_CH_1) && (ch <= M2M_WIFI_CH_14)) || (ch == M2M_WIFI_CH_ALL)) - { - tstrM2MScan strtmp; - strtmp.u8ChNum = ch; - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SCAN, (uint8*)&strtmp, sizeof(tstrM2MScan),NULL, 0,0); - if(s8Ret == M2M_SUCCESS) - { - gu8scanInProgress = 1; - } - } - else - { - s8Ret = M2M_ERR_INVALID_ARG; - } - } - else - { - s8Ret = M2M_ERR_SCAN_IN_PROGRESS; - } - return s8Ret; -} - -sint8 m2m_wifi_request_scan_passive(uint8 ch, uint16 scan_time) -{ - sint8 s8Ret = M2M_SUCCESS; - - if(!gu8scanInProgress) - { - if(((ch >= M2M_WIFI_CH_1) && (ch <= M2M_WIFI_CH_14)) || (ch == M2M_WIFI_CH_ALL)) - { - tstrM2MScan strtmp; - strtmp.u8ChNum = ch; - - strtmp.u16PassiveScanTime = scan_time; - - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_PASSIVE_SCAN, (uint8*)&strtmp, sizeof(tstrM2MScan),NULL, 0,0); - if(s8Ret == M2M_SUCCESS) - { - gu8scanInProgress = 1; - } - } - else - { - s8Ret = M2M_ERR_INVALID_ARG; - } - } - else - { - s8Ret = M2M_ERR_SCAN_IN_PROGRESS; - } - return s8Ret; -} - -sint8 m2m_wifi_request_scan_ssid_list(uint8 ch,uint8 * u8Ssidlist) -{ - sint8 s8Ret = M2M_ERR_INVALID_ARG; - - if(!gu8scanInProgress) - { - if((((ch >= M2M_WIFI_CH_1) && (ch <= M2M_WIFI_CH_14)) || (ch == M2M_WIFI_CH_ALL))&&(u8Ssidlist != NULL)) - { - tstrM2MScan strtmp; - uint16 u16Lsize = 0; - uint8 u8Apnum = u8Ssidlist[u16Lsize]; - if(u8Apnum <= MAX_HIDDEN_SITES) - { - u16Lsize++; - while(u8Apnum) - { - if(u8Ssidlist[u16Lsize] >= M2M_MAX_SSID_LEN){ - goto EXIT; - }else { - u16Lsize += u8Ssidlist[u16Lsize] + 1; - u8Apnum--; - } - } - strtmp.u8ChNum = ch; - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SCAN_SSID_LIST|M2M_REQ_DATA_PKT, (uint8*)&strtmp, sizeof(tstrM2MScan),u8Ssidlist, u16Lsize,sizeof(tstrM2MScan)); - if(s8Ret == M2M_SUCCESS) - { - gu8scanInProgress = 1; - } - } - } - } - else - { - s8Ret = M2M_ERR_SCAN_IN_PROGRESS; - } -EXIT: - return s8Ret; -} -sint8 m2m_wifi_wps(uint8 u8TriggerType,const char *pcPinNumber) -{ - tstrM2MWPSConnect strtmp; - - /* Stop Scan if it is ongoing. - */ - gu8scanInProgress = 0; - strtmp.u8TriggerType = u8TriggerType; - /*If WPS is using PIN METHOD*/ - if (u8TriggerType == WPS_PIN_TRIGGER) - m2m_memcpy ((uint8*)strtmp.acPinNumber,(uint8*) pcPinNumber,8); - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_WPS, (uint8*)&strtmp,sizeof(tstrM2MWPSConnect), NULL, 0,0); -} -sint8 m2m_wifi_wps_disable(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_WPS, NULL,0, NULL, 0, 0); - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_req_client_ctrl(uint8 cmd); -@brief Send a command to the PS Client (An WINC1500 board running the ps_firmware), - if the PS client send any commands it will be received in wifi_cb M2M_WIFI_RESP_CLIENT_INFO -@param [in] cmd - Control command sent from PS Server to PS Client (command values defined by the application) -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. -@sa m2m_wifi_req_server_init, M2M_WIFI_RESP_CLIENT_INFO -@pre m2m_wifi_req_server_init should be called first -@warning -*/ -sint8 m2m_wifi_req_client_ctrl(uint8 u8Cmd) -{ - - sint8 ret = M2M_SUCCESS; -#ifdef _PS_SERVER_ - tstrM2Mservercmd strCmd; - strCmd.u8cmd = u8Cmd; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CLIENT_CTRL, (uint8*)&strCmd, sizeof(tstrM2Mservercmd), NULL, 0, 0); -#else -#ifdef ARDUINO - (void)u8Cmd; // Silence "unused" warning -#endif - M2M_ERR("_PS_SERVER_ is not defined\n"); -#endif - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_req_server_init(uint8 ch); -@brief Initialize the PS Server, The WINC1500 support Non secure communication with another WINC1500, - (SERVER/CLIENT) through one byte command (probe request and probe response) without any connection setup -@param [in] ch - Server listening channel -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise -@sa m2m_wifi_req_client_ctrl -@warning The server mode can't be used with any other modes (STA/P2P/AP) -*/ -sint8 m2m_wifi_req_server_init(uint8 ch) -{ - sint8 ret = M2M_SUCCESS; -#ifdef _PS_SERVER_ - tstrM2mServerInit strServer; - strServer.u8Channel = ch; - ret = hif_send(M2M_REQ_GROUP_WIFI,M2M_WIFI_REQ_SERVER_INIT, (uint8*)&strServer, sizeof(tstrM2mServerInit), NULL, 0, 0); -#else -#ifdef ARDUINO - (void)ch; // Silence "unused" warning -#endif - M2M_ERR("_PS_SERVER_ is not defined\n"); -#endif - return ret; -} -sint8 m2m_wifi_p2p(uint8 u8Channel) -{ - sint8 ret = M2M_SUCCESS; - if((u8Channel == M2M_WIFI_CH_1) || (u8Channel == M2M_WIFI_CH_6) || (u8Channel == M2M_WIFI_CH_11)) - { - tstrM2MP2PConnect strtmp; - strtmp.u8ListenChannel = u8Channel; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_P2P, (uint8*)&strtmp, sizeof(tstrM2MP2PConnect), NULL, 0,0); - } - else - { - M2M_ERR("Listen channel should only be M2M_WIFI_CH_1/6/11 \n"); - ret = M2M_ERR_FAIL; - } - return ret; -} -sint8 m2m_wifi_p2p_disconnect(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_P2P, NULL, 0, NULL, 0, 0); - return ret; -} -sint8 m2m_wifi_enable_ap(CONST tstrM2MAPConfig* pstrM2MAPConfig) -{ - sint8 ret = M2M_ERR_FAIL; - if(M2M_SUCCESS == m2m_validate_ap_parameters(pstrM2MAPConfig)) - { -#ifdef ARDUINO - extern uint32 nmdrv_firm_ver; - uint16 txSize = sizeof(tstrM2MAPConfig); - - if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 5, 0)) { - // for backwards compat with firmwware 19.4.x and older - // (listen channel is 0 based, there is no au8Key field) - ((tstrM2MAPConfig*)pstrM2MAPConfig)->u8ListenChannel--; - txSize -= sizeof(pstrM2MAPConfig->au8Key) + 1; - } - - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_AP, (uint8 *)pstrM2MAPConfig, txSize, NULL, 0, 0); -#else - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_AP, (uint8 *)pstrM2MAPConfig, sizeof(tstrM2MAPConfig), NULL, 0, 0); -#endif - } - return ret; -} - -sint8 m2m_wifi_set_gains(tstrM2mWifiGainsParams* pstrM2mGain) -{ - sint8 ret = M2M_ERR_FAIL; - if(pstrM2mGain != NULL) - { - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_GAINS, (uint8 *)pstrM2mGain, sizeof(tstrM2mWifiGainsParams), NULL, 0, 0); - } - return ret; -} -sint8 m2m_wifi_disable_ap(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_AP, NULL, 0, NULL, 0, 0); - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_req_curr_rssi(void); -@brief Request the current RSSI for the current connected AP, - the response received in wifi_cb M2M_WIFI_RESP_CURRENT_RSSI -@sa M2M_WIFI_RESP_CURRENT_RSSI -@return The function shall return M2M_SUCCESS for success and a negative value otherwise. -*/ -sint8 m2m_wifi_req_curr_rssi(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CURRENT_RSSI, NULL, 0, NULL,0, 0); - return ret; -} -sint8 m2m_wifi_send_ethernet_pkt(uint8* pu8Packet,uint16 u16PacketSize) -{ - sint8 s8Ret = -1; - if((pu8Packet != NULL)&&(u16PacketSize>0)) - { - tstrM2MWifiTxPacketInfo strTxPkt; - - strTxPkt.u16PacketSize = u16PacketSize; - strTxPkt.u16HeaderLength = M2M_ETHERNET_HDR_LEN; - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SEND_ETHERNET_PACKET | M2M_REQ_DATA_PKT, - (uint8*)&strTxPkt, sizeof(tstrM2MWifiTxPacketInfo), pu8Packet, u16PacketSize, M2M_ETHERNET_HDR_OFFSET - M2M_HIF_HDR_OFFSET); - } - return s8Ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); -@brief Request the MAC address stored on the OTP (one time programmable) memory of the device. - (the function is Blocking until response received) -@param [out] pu8MacAddr - Output MAC address buffer of 6 bytes size. Valid only if *pu8Valid=1. -@param [out] pu8IsValid - A output boolean value to indicate the validity of pu8MacAddr in OTP. - Output zero if the OTP memory is not programmed, non-zero otherwise. -@return The function shall return M2M_SUCCESS for success and a negative value otherwise. -@sa m2m_wifi_get_mac_address -@pre m2m_wifi_init required to call any WIFI/socket function -*/ -sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8* pu8IsValid) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_chip_wake(); - if(ret == M2M_SUCCESS) - { - ret = nmi_get_otp_mac_address(pu8MacAddr, pu8IsValid); - if(ret == M2M_SUCCESS) - { - ret = hif_chip_sleep(); - } - } - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr) -@brief Request the current MAC address of the device (the working mac address). - (the function is Blocking until response received) -@param [out] pu8MacAddr - Output MAC address buffer of 6 bytes size. -@return The function shall return M2M_SUCCESS for success and a negative value otherwise. -@sa m2m_wifi_get_otp_mac_address -@pre m2m_wifi_init required to call any WIFI/socket function -*/ -sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_chip_wake(); - if(ret == M2M_SUCCESS) - { - ret = nmi_get_mac_address(pu8MacAddr); - if(ret == M2M_SUCCESS) - { - ret = hif_chip_sleep(); - } - } - - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_req_scan_result(uint8 index); -@brief Reads the AP information from the Scan Result list with the given index, - the response received in wifi_cb M2M_WIFI_RESP_SCAN_RESULT, - the response pointer should be casted with tstrM2mWifiscanResult structure -@param [in] index - Index for the requested result, the index range start from 0 till number of AP's found -@sa tstrM2mWifiscanResult,m2m_wifi_get_num_ap_found,m2m_wifi_request_scan -@return The function shall return M2M_SUCCESE for success and a negative value otherwise -@pre m2m_wifi_request_scan need to be called first, then m2m_wifi_get_num_ap_found - to get the number of AP's found -@warning Function used only in STA mode only. the scan result updated only if scan request called, - else it will be cashed in firmware for the host scan request result, - which mean if large delay occur between the scan request and the scan result request, - the result will not be up-to-date -*/ - -sint8 m2m_wifi_req_scan_result(uint8 index) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mReqScanResult strReqScanRlt; - strReqScanRlt.u8Index = index; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SCAN_RESULT, (uint8*) &strReqScanRlt, sizeof(tstrM2mReqScanResult), NULL, 0, 0); - return ret; -} -/*! -@fn NMI_API uint8 m2m_wifi_get_num_ap_found(void); -@brief Reads the number of AP's found in the last Scan Request, - The function read the number of AP's from global variable which updated in the - wifi_cb in M2M_WIFI_RESP_SCAN_DONE. -@sa m2m_wifi_request_scan -@return Return the number of AP's found in the last Scan Request. -@pre m2m_wifi_request_scan need to be called first -@warning That function need to be called in the wifi_cb in M2M_WIFI_RESP_SCAN_DONE, - calling that function in any other place will return undefined/undated numbers. - Function used only in STA mode only. -*/ -uint8 m2m_wifi_get_num_ap_found(void) -{ - return gu8ChNum; -} -/*! -@fn NMI_API uint8 m2m_wifi_get_sleep_mode(void); -@brief Get the current Power save mode. -@return The current operating power saving mode. -@sa tenuPowerSaveModes , m2m_wifi_set_sleep_mode -*/ -uint8 m2m_wifi_get_sleep_mode(void) -{ - return hif_get_sleep_mode(); -} -/*! -@fn NMI_API sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn); -@brief Set the power saving mode for the WINC1500. -@param [in] PsTyp - Desired power saving mode. Supported types are defined in tenuPowerSaveModes. -@param [in] BcastEn - Broadcast reception enable flag. - If it is 1, the WINC1500 must be awake each DTIM Beacon for receiving Broadcast traffic. - If it is 0, the WINC1500 will not wakeup at the DTIM Beacon, but its wakeup depends only - on the the configured Listen Interval. -@return The function SHALL return 0 for success and a negative value otherwise. -@sa tenuPowerSaveModes -@warning The function called once after initialization. -*/ -sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mPsType strPs; - strPs.u8PsType = PsTyp; - strPs.u8BcastEn = BcastEn; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SLEEP, (uint8*) &strPs,sizeof(tstrM2mPsType), NULL, 0, 0); - M2M_INFO("POWER SAVE %d\n",PsTyp); - hif_set_sleep_mode(PsTyp); - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_request_sleep(void) -@brief Request from WINC1500 device to Sleep for specific time in the M2M_PS_MANUAL Power save mode (only). -@param [in] u32SlpReqTime - Request Sleep in ms -@return The function SHALL return M2M_SUCCESS for success and a negative value otherwise. -@sa tenuPowerSaveModes , m2m_wifi_set_sleep_mode -@warning the Function should be called in M2M_PS_MANUAL power save only -*/ -sint8 m2m_wifi_request_sleep(uint32 u32SlpReqTime) -{ - sint8 ret = M2M_SUCCESS; - uint8 psType; - psType = hif_get_sleep_mode(); - if(psType == M2M_PS_MANUAL) - { - tstrM2mSlpReqTime strPs; - strPs.u32SleepTime = u32SlpReqTime; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DOZE, (uint8*) &strPs,sizeof(tstrM2mSlpReqTime), NULL, 0, 0); - } - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength); -@brief Set the WINC1500 device name which is used as P2P device name. -@param [in] pu8DeviceName - Buffer holding the device name. -@param [in] u8DeviceNameLength - Length of the device name. -@return The function SHALL return M2M_SUCCESS for success and a negative value otherwise. -@warning The Function called once after initialization. -*/ -sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength) -{ - tstrM2MDeviceNameConfig strDeviceName; - if(u8DeviceNameLength >= M2M_DEVICE_NAME_MAX) - { - u8DeviceNameLength = M2M_DEVICE_NAME_MAX; - } - //pu8DeviceName[u8DeviceNameLength] = '\0'; - u8DeviceNameLength ++; - m2m_memcpy(strDeviceName.au8DeviceName, pu8DeviceName, u8DeviceNameLength); - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_DEVICE_NAME, - (uint8*)&strDeviceName, sizeof(tstrM2MDeviceNameConfig), NULL, 0,0); -} -sint8 m2m_wifi_get_firmware_version(tstrM2mRev *pstrRev) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_chip_wake(); - if(ret == M2M_SUCCESS) - { - ret = nm_get_firmware_full_info(pstrRev); - hif_chip_sleep(); - } - return ret; -} -#ifdef CONF_MGMT -sint8 m2m_wifi_enable_monitoring_mode(tstrM2MWifiMonitorModeCtrl *pstrMtrCtrl, uint8 *pu8PayloadBuffer, - uint16 u16BufferSize, uint16 u16DataOffset) -{ - sint8 s8Ret = -1; - if((pstrMtrCtrl->u8ChannelID >= M2M_WIFI_CH_1) && (pstrMtrCtrl->u8ChannelID <= M2M_WIFI_CH_14)) - { - gstrMgmtCtrl.pu8Buf = pu8PayloadBuffer; - gstrMgmtCtrl.u16Sz = u16BufferSize; - gstrMgmtCtrl.u16Offset = u16DataOffset; - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_MONITORING, - (uint8*)pstrMtrCtrl, sizeof(tstrM2MWifiMonitorModeCtrl), NULL, 0,0); - } - return s8Ret; -} - -sint8 m2m_wifi_disable_monitoring_mode(void) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_MONITORING, NULL, 0, NULL, 0,0); -} - -sint8 m2m_wifi_send_wlan_pkt(uint8 *pu8WlanPacket, uint16 u16WlanHeaderLength, uint16 u16WlanPktSize) -{ - sint8 s8Ret = -1; - if(pu8WlanPacket != NULL) - { - tstrM2MWifiTxPacketInfo strTxPkt; - - strTxPkt.u16PacketSize = u16WlanPktSize; - strTxPkt.u16HeaderLength = u16WlanHeaderLength; - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SEND_WIFI_PACKET | M2M_REQ_DATA_PKT, - (uint8*)&strTxPkt, sizeof(tstrM2MWifiTxPacketInfo), pu8WlanPacket, u16WlanPktSize, sizeof(tstrM2MWifiTxPacketInfo)); - } - return s8Ret; -} -#endif - -sint8 m2m_wifi_start_provision_mode(tstrM2MAPConfig *pstrAPConfig, char *pcHttpServerDomainName, uint8 bEnableHttpRedirect) -{ - sint8 s8Ret = M2M_ERR_FAIL; - - if((pstrAPConfig != NULL)) - { - tstrM2MProvisionModeConfig strProvConfig; - if(M2M_SUCCESS == m2m_validate_ap_parameters(pstrAPConfig)) - { - m2m_memcpy((uint8*)&strProvConfig.strApConfig, (uint8*)pstrAPConfig, sizeof(tstrM2MAPConfig)); - if((m2m_strlen((uint8 *)pcHttpServerDomainName) <= 0) || (NULL == pcHttpServerDomainName)) - { - M2M_ERR("INVALID DOMAIN NAME\n"); - goto ERR1; - } - m2m_memcpy((uint8*)strProvConfig.acHttpServerDomainName, (uint8*)pcHttpServerDomainName, 64); - strProvConfig.u8EnableRedirect = bEnableHttpRedirect; - - /* Stop Scan if it is ongoing. - */ - gu8scanInProgress = 0; -#ifdef ARDUINO - extern uint32 nmdrv_firm_ver; - uint16 txSize = sizeof(tstrM2MProvisionModeConfig); - - if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 5, 0)) { - // for backwards compat with firmwware 19.4.x and older - // (listen channel is 0 based, there is no au8Key field) - strProvConfig.strApConfig.u8ListenChannel--; - txSize -= sizeof(strProvConfig.strApConfig.au8Key) + 1; - m2m_memcpy((uint8*)&strProvConfig.strApConfig.au8Key[3], (uint8*)pcHttpServerDomainName, 64); - uint8* pu8EnableRedirect = (uint8*)strProvConfig.strApConfig.au8Key; - pu8EnableRedirect[3 + 64] = bEnableHttpRedirect; - } - - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_START_PROVISION_MODE | M2M_REQ_DATA_PKT, - (uint8*)&strProvConfig, txSize, NULL, 0, 0); -#else - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_START_PROVISION_MODE | M2M_REQ_DATA_PKT, - (uint8*)&strProvConfig, sizeof(tstrM2MProvisionModeConfig), NULL, 0, 0); -#endif - } - else - { - /*goto ERR1;*/ - } - } -ERR1: - return s8Ret; -} - -sint8 m2m_wifi_stop_provision_mode(void) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_STOP_PROVISION_MODE, NULL, 0, NULL, 0, 0); -} - -sint8 m2m_wifi_get_connection_info(void) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_GET_CONN_INFO, NULL, 0, NULL, 0, 0); -} - -sint8 m2m_wifi_set_sytem_time(uint32 u32UTCSeconds) -{ - /* - The firmware accepts timestamps relative to 1900 like NTP Timestamp. - */ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_SYS_TIME, (uint8*)&u32UTCSeconds, sizeof(tstrSystemTime), NULL, 0, 0); -} -/*! - * @fn NMI_API sint8 m2m_wifi_get_sytem_time(void); - * @see m2m_wifi_enable_sntp - tstrSystemTime - * @note get the system time from the sntp client - * using the API \ref m2m_wifi_get_sytem_time. - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -sint8 m2m_wifi_get_sytem_time(void) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_GET_SYS_TIME, NULL,0, NULL, 0, 0); -} - -sint8 m2m_wifi_enable_sntp(uint8 bEnable) -{ - uint8 u8Req; - - u8Req = bEnable ? M2M_WIFI_REQ_ENABLE_SNTP_CLIENT : M2M_WIFI_REQ_DISABLE_SNTP_CLIENT; - return hif_send(M2M_REQ_GROUP_WIFI, u8Req, NULL, 0, NULL, 0, 0); -} -/*! -@fn NMI_API sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode); -@brief Change the power profile mode -@param [in] u8PwrMode - Change the WINC power profile to different mode - PWR_LOW1/PWR_LOW2/PWR_HIGH/PWR_AUTO (tenuM2mPwrMode) -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. -@sa tenuM2mPwrMode -@pre m2m_wifi_init -@warning must be called after the initializations and before any connection request and can't be changed in run time, -*/ -sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mPwrMode strM2mPwrMode; - strM2mPwrMode.u8PwrMode = u8PwrMode; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_POWER_PROFILE, (uint8*)&strM2mPwrMode,sizeof(tstrM2mPwrMode), NULL, 0, 0); - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel); -@brief set the TX power tenuM2mTxPwrLevel -@param [in] u8TxPwrLevel - change the TX power tenuM2mTxPwrLevel -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. -@sa tenuM2mTxPwrLevel -@pre m2m_wifi_init -@warning -*/ -sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mTxPwrLevel strM2mTxPwrLevel; - strM2mTxPwrLevel.u8TxPwrLevel = u8TxPwrLevel; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_TX_POWER, (uint8*)&strM2mTxPwrLevel,sizeof(tstrM2mTxPwrLevel), NULL, 0, 0); - return ret; -} - -/*! -@fn NMI_API sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable); -@brief Enable or Disable logs in run time (Disable Firmware logs will - enhance the firmware start-up time and performance) -@param [in] u8Enable - Set 1 to enable the logs 0 for disable -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. -@sa __DISABLE_FIRMWARE_LOGS__ (build option to disable logs from initializations) -@pre m2m_wifi_init -@warning -*/ -sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mEnableLogs strM2mEnableLogs; - strM2mEnableLogs.u8Enable = u8Enable; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_ENABLE_LOGS, (uint8*)&strM2mEnableLogs,sizeof(tstrM2mEnableLogs), NULL, 0, 0); - return ret; -} - -/*! -@fn NMI_API sint8 m2m_wifi_set_battery_voltage(uint16 u16BattVoltx100); -@brief Enable or Disable logs in run time (Disable Firmware logs will - enhance the firmware start-up time and performance) -@param [in] u16BattVoltx100 - battery voltage multiplied by 100 -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. -@sa __DISABLE_FIRMWARE_LOGS__ (build option to disable logs from initializations) -@pre m2m_wifi_init -@warning -*/ -sint8 m2m_wifi_set_battery_voltage(uint16 u16BattVoltx100) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mBatteryVoltage strM2mBattVol = {0}; - strM2mBattVol.u16BattVolt = u16BattVoltx100; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_BATTERY_VOLTAGE, (uint8*)&strM2mBattVol,sizeof(tstrM2mBatteryVoltage), NULL, 0, 0); - return ret; -} -/*! -@fn sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PrngBuff,uint16 u16PrngSize) -@brief Get random bytes using the PRNG bytes. -@param [in] u16PrngSize - Size of the required random bytes to be generated. -@param [in] pu8PrngBuff - Pointer to user allocated buffer. -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. -*/ -sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PrngBuff,uint16 u16PrngSize) -{ - sint8 ret = M2M_ERR_FAIL; - tstrPrng strRng = {0}; - if((u16PrngSize < (M2M_BUFFER_MAX_SIZE - sizeof(tstrPrng)))&&(pu8PrngBuff != NULL)) - { - strRng.u16PrngSize = u16PrngSize; - strRng.pu8RngBuff = pu8PrngBuff; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_GET_PRNG|M2M_REQ_DATA_PKT,(uint8 *)&strRng, sizeof(tstrPrng),NULL,0, 0); - } - else - { - M2M_ERR("PRNG Buffer exceeded maximum size %d or NULL Buffer\n",u16PrngSize); - } - return ret; -} -#ifdef ETH_MODE -/*! -@fn \ - NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8* pu8MulticastMacAddress, uint8 u8AddRemove) - -@brief - Add MAC filter to receive Multicast packets. - -@param [in] pu8MulticastMacAddress - Pointer to the MAC address. -@param [in] u8AddRemove - Flag to Add/Remove MAC address. -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ - -NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8* pu8MulticastMacAddress, uint8 u8AddRemove) -{ - sint8 s8ret = M2M_ERR_FAIL; - tstrM2MMulticastMac strMulticastMac; - - if(pu8MulticastMacAddress != NULL ) - { - strMulticastMac.u8AddRemove = u8AddRemove; - m2m_memcpy(strMulticastMac.au8macaddress,pu8MulticastMacAddress,M2M_MAC_ADDRES_LEN); - M2M_DBG("mac multicast: %x:%x:%x:%x:%x:%x\r\n",strMulticastMac.au8macaddress[0],strMulticastMac.au8macaddress[1],strMulticastMac.au8macaddress[2],strMulticastMac.au8macaddress[3],strMulticastMac.au8macaddress[4],strMulticastMac.au8macaddress[5]); - s8ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_MAC_MCAST, (uint8 *)&strMulticastMac,sizeof(tstrM2MMulticastMac),NULL,0,0); - } - - return s8ret; - -} - -/*! -@fn \ - NMI_API sint8 m2m_wifi_set_receive_buffer(void* pvBuffer,uint16 u16BufferLen); - -@brief - set the ethernet receive buffer, should be called in the receive call back. - -@param [in] pvBuffer - Pointer to the ethernet receive buffer. -@param [in] u16BufferLen - Length of the buffer. - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_set_receive_buffer(void* pvBuffer,uint16 u16BufferLen) -{ - sint8 s8ret = M2M_SUCCESS; - if(pvBuffer != NULL) - { - gau8ethRcvBuf = pvBuffer; - gu16ethRcvBufSize= u16BufferLen; - } - else - { - s8ret = M2M_ERR_FAIL; - M2M_ERR("Buffer NULL pointer\r\n"); - } - return s8ret; -} -#endif /* ETH_MODE */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmasic.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmasic.c deleted file mode 100644 index 91c0e5a..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmasic.c +++ /dev/null @@ -1,688 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 ASIC specific internal APIs. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "common/include/nm_common.h" -#include "driver/source/nmbus.h" -#include "bsp/include/nm_bsp.h" -#include "driver/source/nmasic.h" -#include "driver/include/m2m_types.h" - -#define NMI_GLB_RESET_0 (NMI_PERIPH_REG_BASE + 0x400) -#define NMI_INTR_REG_BASE (NMI_PERIPH_REG_BASE + 0xa00) -#define NMI_PIN_MUX_0 (NMI_PERIPH_REG_BASE + 0x408) -#define NMI_INTR_ENABLE (NMI_INTR_REG_BASE) -#define GET_UINT32(X,Y) (X[0+Y] + ((uint32)X[1+Y]<<8) + ((uint32)X[2+Y]<<16) +((uint32)X[3+Y]<<24)) - -/*SPI and I2C only*/ -#define CORT_HOST_COMM (0x10) -#define HOST_CORT_COMM (0x0b) -#define WAKE_CLK_REG (0x1) -#define CLOCKS_EN_REG (0xf) - - - -#ifdef ARDUINO -#define TIMEOUT (2000) -#else -#define TIMEOUT (0xfffffffful) -#endif -#define WAKUP_TRAILS_TIMEOUT (4) - -sint8 chip_apply_conf(uint32 u32Conf) -{ - sint8 ret = M2M_SUCCESS; - uint32 val32 = u32Conf; - -#if (defined __ENABLE_PMU__) || (defined CONF_WINC_INT_PMU) - val32 |= rHAVE_USE_PMU_BIT; -#endif -#ifdef __ENABLE_SLEEP_CLK_SRC_RTC__ - val32 |= rHAVE_SLEEP_CLK_SRC_RTC_BIT; -#elif defined __ENABLE_SLEEP_CLK_SRC_XO__ - val32 |= rHAVE_SLEEP_CLK_SRC_XO_BIT; -#endif -#ifdef __ENABLE_EXT_PA_INV_TX_RX__ - val32 |= rHAVE_EXT_PA_INV_TX_RX; -#endif -#ifdef __ENABLE_LEGACY_RF_SETTINGS__ - val32 |= rHAVE_LEGACY_RF_SETTINGS; -#endif -#ifdef __DISABLE_FIRMWARE_LOGS__ - val32 |= rHAVE_LOGS_DISABLED_BIT; -#endif - - val32 |= rHAVE_RESERVED1_BIT; - do { - nm_write_reg(rNMI_GP_REG_1, val32); - if(val32 != 0) { - uint32 reg = 0; - ret = nm_read_reg_with_ret(rNMI_GP_REG_1, ®); - if(ret == M2M_SUCCESS) { - if(reg == val32) - break; - } - } else { - break; - } - } while(1); - - return M2M_SUCCESS; -} -void chip_idle(void) -{ - uint32 reg = 0; - nm_read_reg_with_ret(WAKE_CLK_REG, ®); - if(reg & NBIT1) - { - reg &=~ NBIT1; - nm_write_reg(WAKE_CLK_REG, reg); - } -} - -sint8 enable_interrupts(void) -{ - uint32 reg = 0; - sint8 ret = M2M_SUCCESS; - /** - interrupt pin mux select - **/ - ret = nm_read_reg_with_ret(NMI_PIN_MUX_0, ®); - if (M2M_SUCCESS != ret) goto ERR1; - - reg |= ((uint32) 1 << 8); - ret = nm_write_reg(NMI_PIN_MUX_0, reg); - if (M2M_SUCCESS != ret) goto ERR1; - - /** - interrupt enable - **/ - ret = nm_read_reg_with_ret(NMI_INTR_ENABLE, ®); - if (M2M_SUCCESS != ret) goto ERR1; - - reg |= ((uint32) 1 << 16); - ret = nm_write_reg(NMI_INTR_ENABLE, reg); - if (M2M_SUCCESS != ret) goto ERR1; -ERR1: - return ret; -} - -sint8 cpu_start(void) { - uint32 reg = 0; - sint8 ret; - - /** - reset regs - */ - ret = nm_write_reg(BOOTROM_REG,0); - ret += nm_write_reg(NMI_STATE_REG,0); - ret += nm_write_reg(NMI_REV_REG,0); - /** - Go... - **/ - ret += nm_read_reg_with_ret(0x1118, ®); - reg |= (1 << 0); - ret += nm_write_reg(0x1118, reg); - ret += nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); - if ((reg & (1ul << 10)) == (1ul << 10)) { - reg &= ~(1ul << 10); - ret += nm_write_reg(NMI_GLB_RESET_0, reg); - } - reg |= (1ul << 10); - ret += nm_write_reg(NMI_GLB_RESET_0, reg); - nm_bsp_sleep(1); - return ret; -} - -uint32 nmi_get_chipid(void) -{ - static uint32 chipid = 0; - - if (chipid == 0) { - uint32 rfrevid; - - if((nm_read_reg_with_ret(0x1000, &chipid)) != M2M_SUCCESS) { - chipid = 0; - return 0; - } - //if((ret = nm_read_reg_with_ret(0x11fc, &revid)) != M2M_SUCCESS) { - // return 0; - //} - if((nm_read_reg_with_ret(0x13f4, &rfrevid)) != M2M_SUCCESS) { - chipid = 0; - return 0; - } - - if (chipid == 0x1002a0) { - if (rfrevid == 0x1) { /* 1002A0 */ - } else /* if (rfrevid == 0x2) */ { /* 1002A1 */ - chipid = 0x1002a1; - } - } else if(chipid == 0x1002b0) { - if(rfrevid == 3) { /* 1002B0 */ - } else if(rfrevid == 4) { /* 1002B1 */ - chipid = 0x1002b1; - } else /* if(rfrevid == 5) */ { /* 1002B2 */ - chipid = 0x1002b2; - } - }else if(chipid == 0x1000F0) { - if((nm_read_reg_with_ret(0x3B0000, &chipid)) != M2M_SUCCESS) { - chipid = 0; - return 0; - } - }else { - - } -//#define PROBE_FLASH -#ifdef PROBE_FLASH - if(chipid) { - UWORD32 flashid; - - flashid = probe_spi_flash(); - if(flashid == 0x1230ef) { - chipid &= ~(0x0f0000); - chipid |= 0x050000; - } - if(flashid == 0xc21320c2) { - chipid &= ~(0x0f0000); - chipid |= 0x050000; - } - } -#else - /*M2M is by default have SPI flash*/ - chipid &= ~(0x0f0000); - chipid |= 0x050000; -#endif /* PROBE_FLASH */ - } - return chipid; -} - -uint32 nmi_get_rfrevid(void) -{ - uint32 rfrevid; - if((nm_read_reg_with_ret(0x13f4, &rfrevid)) != M2M_SUCCESS) { - rfrevid = 0; - return 0; - } - return rfrevid; -} - -void restore_pmu_settings_after_global_reset(void) -{ - /* - * Must restore PMU register value after - * global reset if PMU toggle is done at - * least once since the last hard reset. - */ - if(REV(nmi_get_chipid()) >= REV_2B0) { - nm_write_reg(0x1e48, 0xb78469ce); - } -} - -void nmi_update_pll(void) -{ - uint32 pll; - - pll = nm_read_reg(0x1428); - pll &= ~0x1ul; - nm_write_reg(0x1428, pll); - pll |= 0x1ul; - nm_write_reg(0x1428, pll); - -} -void nmi_set_sys_clk_src_to_xo(void) -{ - uint32 val32; - - /* Switch system clock source to XO. This will take effect after nmi_update_pll(). */ - val32 = nm_read_reg(0x141c); - val32 |= (1 << 2); - nm_write_reg(0x141c, val32); - - /* Do PLL update */ - nmi_update_pll(); -} -sint8 chip_sleep(void) -{ - uint32 reg; - sint8 ret = M2M_SUCCESS; - - while(1) - { - ret = nm_read_reg_with_ret(CORT_HOST_COMM,®); - if(ret != M2M_SUCCESS) goto ERR1; - if((reg & NBIT0) == 0) break; - } - - /* Clear bit 1 */ - ret = nm_read_reg_with_ret(WAKE_CLK_REG, ®); - if(ret != M2M_SUCCESS)goto ERR1; - if(reg & NBIT1) - { - reg &=~NBIT1; - ret = nm_write_reg(WAKE_CLK_REG, reg); - if(ret != M2M_SUCCESS)goto ERR1; - } - - ret = nm_read_reg_with_ret(HOST_CORT_COMM, ®); - if(ret != M2M_SUCCESS)goto ERR1; - if(reg & NBIT0) - { - reg &= ~NBIT0; - ret = nm_write_reg(HOST_CORT_COMM, reg); - if(ret != M2M_SUCCESS)goto ERR1; - } - -ERR1: - return ret; -} -sint8 chip_wake(void) -{ - sint8 ret = M2M_SUCCESS; - uint32 reg = 0, clk_status_reg = 0,trials = 0; - - ret = nm_read_reg_with_ret(HOST_CORT_COMM, ®); - if(ret != M2M_SUCCESS)goto _WAKE_EXIT; - - if(!(reg & NBIT0)) - { - /*USE bit 0 to indicate host wakeup*/ - ret = nm_write_reg(HOST_CORT_COMM, reg|NBIT0); - if(ret != M2M_SUCCESS)goto _WAKE_EXIT; - } - - ret = nm_read_reg_with_ret(WAKE_CLK_REG, ®); - if(ret != M2M_SUCCESS)goto _WAKE_EXIT; - /* Set bit 1 */ - if(!(reg & NBIT1)) - { - ret = nm_write_reg(WAKE_CLK_REG, reg | NBIT1); - if(ret != M2M_SUCCESS) goto _WAKE_EXIT; - } - - do - { - ret = nm_read_reg_with_ret(CLOCKS_EN_REG, &clk_status_reg); - if(ret != M2M_SUCCESS) { - M2M_ERR("Bus error (5).%d %lx\n",ret,clk_status_reg); - goto _WAKE_EXIT; - } - if(clk_status_reg & NBIT2) { - break; - } - nm_bsp_sleep(2); - trials++; - if(trials > WAKUP_TRAILS_TIMEOUT) - { - M2M_ERR("Failed to wakup the chip\n"); - ret = M2M_ERR_TIME_OUT; - goto _WAKE_EXIT; - } - }while(1); - - /*workaround sometimes spi fail to read clock regs after reading/writing clockless registers*/ - nm_bus_reset(); - -_WAKE_EXIT: - return ret; -} -sint8 cpu_halt(void) -{ - sint8 ret; - uint32 reg = 0; - ret = nm_read_reg_with_ret(0x1118, ®); - reg |= (1 << 0); - ret += nm_write_reg(0x1118, reg); - ret += nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); - if ((reg & (1ul << 10)) == (1ul << 10)) { - reg &= ~(1ul << 10); - ret += nm_write_reg(NMI_GLB_RESET_0, reg); - ret += nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); - } - return ret; -} -sint8 chip_reset_and_cpu_halt(void) -{ - sint8 ret = M2M_SUCCESS; - - /*Wakeup needed only for I2C interface*/ - ret = chip_wake(); - if(ret != M2M_SUCCESS) goto ERR1; - /*Reset and CPU halt need for no wait board only*/ - ret = chip_reset(); - if(ret != M2M_SUCCESS) goto ERR1; - ret = cpu_halt(); - if(ret != M2M_SUCCESS) goto ERR1; -ERR1: - return ret; -} -sint8 chip_reset(void) -{ - sint8 ret = M2M_SUCCESS; - ret = nm_write_reg(NMI_GLB_RESET_0, 0); - nm_bsp_sleep(50); - return ret; -} - -sint8 wait_for_bootrom(uint8 arg) -{ - sint8 ret = M2M_SUCCESS; - uint32 reg = 0, cnt = 0; - uint32 u32GpReg1 = 0; - uint32 u32DriverVerInfo = M2M_MAKE_VERSION_INFO(M2M_RELEASE_VERSION_MAJOR_NO,\ - M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO,\ - M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO,\ - M2M_RELEASE_VERSION_PATCH_NO); - - - reg = 0; - while(1) { - reg = nm_read_reg(0x1014); /* wait for efuse loading done */ - if (reg & 0x80000000) { - break; - } - nm_bsp_sleep(1); /* TODO: Why bus error if this delay is not here. */ - } - reg = nm_read_reg(M2M_WAIT_FOR_HOST_REG); - reg &= 0x1; - - /* check if waiting for the host will be skipped or not */ - if(reg == 0) - { - reg = 0; - while(reg != M2M_FINISH_BOOT_ROM) - { - nm_bsp_sleep(1); - reg = nm_read_reg(BOOTROM_REG); - - if(++cnt > TIMEOUT) - { - M2M_DBG("failed to load firmware from flash.\n"); - ret = M2M_ERR_INIT; - goto ERR2; - } - } - } - - if(M2M_WIFI_MODE_ATE_HIGH == arg) { - nm_write_reg(NMI_REV_REG, M2M_ATE_FW_START_VALUE); - nm_write_reg(NMI_STATE_REG, NBIT20); - }else if(M2M_WIFI_MODE_ATE_LOW == arg) { - nm_write_reg(NMI_REV_REG, M2M_ATE_FW_START_VALUE); - nm_write_reg(NMI_STATE_REG, 0); - }else if(M2M_WIFI_MODE_ETHERNET == arg){ - u32GpReg1 = rHAVE_ETHERNET_MODE_BIT; - nm_write_reg(NMI_STATE_REG, u32DriverVerInfo); - } else { - /*bypass this step*/ - nm_write_reg(NMI_STATE_REG, u32DriverVerInfo); - } - - if(REV(nmi_get_chipid()) >= REV_3A0){ - chip_apply_conf(u32GpReg1 | rHAVE_USE_PMU_BIT); - } else { - chip_apply_conf(u32GpReg1); - } - M2M_INFO("DriverVerInfo: 0x%08lx\n",u32DriverVerInfo); - - nm_write_reg(BOOTROM_REG,M2M_START_FIRMWARE); - -#ifdef __ROM_TEST__ - rom_test(); -#endif /* __ROM_TEST__ */ - -ERR2: - return ret; -} - -sint8 wait_for_firmware_start(uint8 arg) -{ - sint8 ret = M2M_SUCCESS; - uint32 reg = 0, cnt = 0; - uint32 u32Timeout = TIMEOUT; - volatile uint32 regAddress = NMI_STATE_REG; - volatile uint32 checkValue = M2M_FINISH_INIT_STATE; - - if((M2M_WIFI_MODE_ATE_HIGH == arg)||(M2M_WIFI_MODE_ATE_LOW == arg)) { - regAddress = NMI_REV_REG; - checkValue = M2M_ATE_FW_IS_UP_VALUE; - } else { - /*bypass this step*/ - } - - - while (checkValue != reg) - { - nm_bsp_sleep(2); /* TODO: Why bus error if this delay is not here. */ - M2M_DBG("%x %x %x\n",(unsigned int)nm_read_reg(0x108c),(unsigned int)nm_read_reg(0x108c),(unsigned int)nm_read_reg(0x14A0)); - reg = nm_read_reg(regAddress); - if(++cnt >= u32Timeout) - { - M2M_DBG("Time out for wait firmware Run\n"); - ret = M2M_ERR_INIT; - goto ERR; - } - } - if(M2M_FINISH_INIT_STATE == checkValue) - { - nm_write_reg(NMI_STATE_REG, 0); - } -ERR: - return ret; -} - -sint8 chip_deinit(void) -{ - uint32 reg = 0; - sint8 ret; - - /** - stop the firmware, need a re-download - **/ - ret = nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); - if (ret != M2M_SUCCESS) { - M2M_ERR("failed to de-initialize\n"); - goto ERR1; - } - reg &= ~(1 << 10); - ret = nm_write_reg(NMI_GLB_RESET_0, reg); - if (ret != M2M_SUCCESS) { - M2M_ERR("failed to de-initialize\n"); - goto ERR1; - } - -ERR1: - return ret; -} - -#ifdef CONF_PERIPH - -sint8 set_gpio_dir(uint8 gpio, uint8 dir) -{ - uint32 val32; - sint8 ret; - - ret = nm_read_reg_with_ret(0x20108, &val32); - if(ret != M2M_SUCCESS) goto _EXIT; - - if(dir) { - val32 |= (1ul << gpio); - } else { - val32 &= ~(1ul << gpio); - } - - ret = nm_write_reg(0x20108, val32); - -_EXIT: - return ret; -} -sint8 set_gpio_val(uint8 gpio, uint8 val) -{ - uint32 val32; - sint8 ret; - - ret = nm_read_reg_with_ret(0x20100, &val32); - if(ret != M2M_SUCCESS) goto _EXIT; - - if(val) { - val32 |= (1ul << gpio); - } else { - val32 &= ~(1ul << gpio); - } - - ret = nm_write_reg(0x20100, val32); - -_EXIT: - return ret; -} - -sint8 get_gpio_val(uint8 gpio, uint8* val) -{ - uint32 val32; - sint8 ret; - - ret = nm_read_reg_with_ret(0x20104, &val32); - if(ret != M2M_SUCCESS) goto _EXIT; - - *val = (uint8)((val32 >> gpio) & 0x01); - -_EXIT: - return ret; -} - -sint8 pullup_ctrl(uint32 pinmask, uint8 enable) -{ - sint8 s8Ret; - uint32 val32; - s8Ret = nm_read_reg_with_ret(0x142c, &val32); - if(s8Ret != M2M_SUCCESS) { - M2M_ERR("[pullup_ctrl]: failed to read\n"); - goto _EXIT; - } - if(enable) { - val32 &= ~pinmask; - } else { - val32 |= pinmask; - } - s8Ret = nm_write_reg(0x142c, val32); - if(s8Ret != M2M_SUCCESS) { - M2M_ERR("[pullup_ctrl]: failed to write\n"); - goto _EXIT; - } -_EXIT: - return s8Ret; -} -#endif /* CONF_PERIPH */ - -sint8 nmi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid) -{ - sint8 ret; - uint32 u32RegValue; - uint8 mac[6]; - tstrGpRegs strgp = {0}; - - ret = nm_read_reg_with_ret(rNMI_GP_REG_2, &u32RegValue); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; -#ifdef ARDUINO - if (u32RegValue) { - ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; - u32RegValue = strgp.u32Mac_efuse_mib; - } else { - // firmware version 19.3.0 - ret = nm_read_reg_with_ret(rNMI_GP_REG_0, &u32RegValue); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; - } -#else - ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; - u32RegValue = strgp.u32Mac_efuse_mib; -#endif - if(!EFUSED_MAC(u32RegValue)) { - M2M_DBG("Default MAC\n"); - m2m_memset(pu8MacAddr, 0, 6); - goto _EXIT_ERR; - } - - M2M_DBG("OTP MAC\n"); - u32RegValue >>=16; - ret = nm_read_block(u32RegValue|0x30000, mac, 6); - m2m_memcpy(pu8MacAddr,mac,6); - if(pu8IsValid) *pu8IsValid = 1; - return ret; - -_EXIT_ERR: - if(pu8IsValid) *pu8IsValid = 0; - return ret; -} - -sint8 nmi_get_mac_address(uint8 *pu8MacAddr) -{ - sint8 ret; - uint32 u32RegValue; - uint8 mac[6]; - tstrGpRegs strgp = {0}; - - ret = nm_read_reg_with_ret(rNMI_GP_REG_2, &u32RegValue); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; -#ifdef ARDUINO - if (u32RegValue) { - ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; - u32RegValue = strgp.u32Mac_efuse_mib; - } else { - // firmware version 19.3.0 - ret = nm_read_reg_with_ret(rNMI_GP_REG_0, &u32RegValue); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; - } -#else - ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; - u32RegValue = strgp.u32Mac_efuse_mib; -#endif - u32RegValue &=0x0000ffff; - ret = nm_read_block(u32RegValue|0x30000, mac, 6); - m2m_memcpy(pu8MacAddr, mac, 6); - - return ret; - -_EXIT_ERR: - return ret; -} diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmasic.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmasic.h deleted file mode 100644 index 84a395b..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmasic.h +++ /dev/null @@ -1,215 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 ASIC specific internal APIs. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -#ifndef _NMASIC_H_ -#define _NMASIC_H_ - -#include "common/include/nm_common.h" - -#define NMI_PERIPH_REG_BASE 0x1000 -#define NMI_CHIPID (NMI_PERIPH_REG_BASE) -#define rNMI_GP_REG_0 (0x149c) -#define rNMI_GP_REG_1 (0x14A0) -#define rNMI_GP_REG_2 (0xc0008) -#define rNMI_GLB_RESET (0x1400) -#define rNMI_BOOT_RESET_MUX (0x1118) -#define NMI_STATE_REG (0x108c) -#define BOOTROM_REG (0xc000c) -#define NMI_REV_REG (0x207ac) /*Also, Used to load ATE firmware from SPI Flash and to ensure that it is running too*/ -#define NMI_REV_REG_ATE (0x1048) /*Revision info register in case of ATE FW*/ -#define M2M_WAIT_FOR_HOST_REG (0x207bc) -#define M2M_FINISH_INIT_STATE 0x02532636UL -#define M2M_FINISH_BOOT_ROM 0x10add09eUL -#define M2M_START_FIRMWARE 0xef522f61UL -#define M2M_START_PS_FIRMWARE 0x94992610UL - -#define M2M_ATE_FW_START_VALUE (0x3C1CD57D) /*Also, Change this value in boot_firmware if it will be changed here*/ -#define M2M_ATE_FW_IS_UP_VALUE (0xD75DC1C3) /*Also, Change this value in ATE (Burst) firmware if it will be changed here*/ - -#define REV_2B0 (0x2B0) -#define REV_B0 (0x2B0) -#define REV_3A0 (0x3A0) -#define GET_CHIPID() nmi_get_chipid() -#define ISNMC1000(id) ((((id) & 0xfffff000) == 0x100000) ? 1 : 0) -#define ISNMC1500(id) ((((id) & 0xfffff000) == 0x150000) ? 1 : 0) -#define ISNMC3000(id) ((((id) & 0xfff00000) == 0x300000) ? 1 : 0) -#define REV(id) (((id) & 0x00000fff )) -#define EFUSED_MAC(value) (value & 0xffff0000) - -#define rHAVE_SDIO_IRQ_GPIO_BIT (NBIT0) -#define rHAVE_USE_PMU_BIT (NBIT1) -#define rHAVE_SLEEP_CLK_SRC_RTC_BIT (NBIT2) -#define rHAVE_SLEEP_CLK_SRC_XO_BIT (NBIT3) -#define rHAVE_EXT_PA_INV_TX_RX (NBIT4) -#define rHAVE_LEGACY_RF_SETTINGS (NBIT5) -#define rHAVE_LOGS_DISABLED_BIT (NBIT6) -#define rHAVE_ETHERNET_MODE_BIT (NBIT7) -#define rHAVE_RESERVED1_BIT (NBIT8) - -typedef struct{ - uint32 u32Mac_efuse_mib; - uint32 u32Firmware_Ota_rev; -}tstrGpRegs; - -#ifdef __cplusplus - extern "C" { -#endif - -/* -* @fn cpu_halt -* @brief -*/ -sint8 cpu_halt(void); -/* -* @fn chip_sleep -* @brief -*/ -sint8 chip_sleep(void); -/* -* @fn chip_wake -* @brief -*/ -sint8 chip_wake(void); -/* -* @fn chip_idle -* @brief -*/ -void chip_idle(void); -/* -* @fn enable_interrupts -* @brief -*/ -sint8 enable_interrupts(void); -/* -* @fn cpu_start -* @brief -*/ -sint8 cpu_start(void); -/* -* @fn nmi_get_chipid -* @brief -*/ -uint32 nmi_get_chipid(void); -/* -* @fn nmi_get_rfrevid -* @brief -*/ -uint32 nmi_get_rfrevid(void); -/* -* @fn restore_pmu_settings_after_global_reset -* @brief -*/ -void restore_pmu_settings_after_global_reset(void); -/* -* @fn nmi_update_pll -* @brief -*/ -void nmi_update_pll(void); -/* -* @fn nmi_set_sys_clk_src_to_xo -* @brief -*/ -void nmi_set_sys_clk_src_to_xo(void); -/* -* @fn chip_reset -* @brief -*/ -sint8 chip_reset(void); -/* -* @fn wait_for_bootrom -* @brief -*/ -sint8 wait_for_bootrom(uint8); -/* -* @fn wait_for_firmware_start -* @brief -*/ -sint8 wait_for_firmware_start(uint8); -/* -* @fn chip_deinit -* @brief -*/ -sint8 chip_deinit(void); -/* -* @fn chip_reset_and_cpu_halt -* @brief -*/ -sint8 chip_reset_and_cpu_halt(void); -/* -* @fn set_gpio_dir -* @brief -*/ -sint8 set_gpio_dir(uint8 gpio, uint8 dir); -/* -* @fn set_gpio_val -* @brief -*/ -sint8 set_gpio_val(uint8 gpio, uint8 val); -/* -* @fn get_gpio_val -* @brief -*/ -sint8 get_gpio_val(uint8 gpio, uint8* val); -/* -* @fn pullup_ctrl -* @brief -*/ -sint8 pullup_ctrl(uint32 pinmask, uint8 enable); -/* -* @fn nmi_get_otp_mac_address -* @brief -*/ -sint8 nmi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); -/* -* @fn nmi_get_mac_address -* @brief -*/ -sint8 nmi_get_mac_address(uint8 *pu8MacAddr); -/* -* @fn chip_apply_conf -* @brief -*/ -sint8 chip_apply_conf(uint32 u32conf); - -#ifdef __cplusplus - } -#endif - -#endif /*_NMASIC_H_*/ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmbus.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmbus.c deleted file mode 100644 index d001d72..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmbus.c +++ /dev/null @@ -1,301 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 bus APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -#ifndef CORTUS_APP - -#include "nmbus.h" -#include "nmi2c.h" -#include "nmspi.h" -#include "nmuart.h" - -#define MAX_TRX_CFG_SZ 8 - -/** -* @fn nm_bus_iface_init -* @brief Initialize bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_bus_iface_init(void *pvInitVal) -{ - sint8 ret = M2M_SUCCESS; - ret = nm_bus_init(pvInitVal); - return ret; -} - -/** -* @fn nm_bus_iface_deinit -* @brief Deinitialize bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Samer Sarhan -* @date 07 April 2014 -* @version 1.0 -*/ -sint8 nm_bus_iface_deinit(void) -{ - sint8 ret = M2M_SUCCESS; - ret = nm_bus_deinit(); - - return ret; -} - -/** -* @fn nm_bus_reset -* @brief reset bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @version 1.0 -*/ -sint8 nm_bus_reset(void) -{ - sint8 ret = M2M_SUCCESS; -#ifdef CONF_WINC_USE_UART -#elif defined (CONF_WINC_USE_SPI) - return nm_spi_reset(); -#elif defined (CONF_WINC_USE_I2C) -#else -#error "Plesae define bus usage" -#endif - - return ret; -} - -/** -* @fn nm_bus_iface_reconfigure -* @brief reconfigure bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Viswanathan Murugesan -* @date 22 Oct 2014 -* @version 1.0 -*/ -sint8 nm_bus_iface_reconfigure(void *ptr) -{ -#ifdef ARDUINO - (void)ptr; // Silence "unused" warning -#endif - sint8 ret = M2M_SUCCESS; -#ifdef CONF_WINC_USE_UART - ret = nm_uart_reconfigure(ptr); -#endif - return ret; -} -/* -* @fn nm_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -uint32 nm_read_reg(uint32 u32Addr) -{ -#ifdef CONF_WINC_USE_UART - return nm_uart_read_reg(u32Addr); -#elif defined (CONF_WINC_USE_SPI) - return nm_spi_read_reg(u32Addr); -#elif defined (CONF_WINC_USE_I2C) - return nm_i2c_read_reg(u32Addr); -#else -#error "Plesae define bus usage" -#endif - -} - -/* -* @fn nm_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) -{ -#ifdef CONF_WINC_USE_UART - return nm_uart_read_reg_with_ret(u32Addr,pu32RetVal); -#elif defined (CONF_WINC_USE_SPI) - return nm_spi_read_reg_with_ret(u32Addr,pu32RetVal); -#elif defined (CONF_WINC_USE_I2C) - return nm_i2c_read_reg_with_ret(u32Addr,pu32RetVal); -#else -#error "Plesae define bus usage" -#endif -} - -/* -* @fn nm_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_write_reg(uint32 u32Addr, uint32 u32Val) -{ -#ifdef CONF_WINC_USE_UART - return nm_uart_write_reg(u32Addr,u32Val); -#elif defined (CONF_WINC_USE_SPI) - return nm_spi_write_reg(u32Addr,u32Val); -#elif defined (CONF_WINC_USE_I2C) - return nm_i2c_write_reg(u32Addr,u32Val); -#else -#error "Plesae define bus usage" -#endif -} - -static sint8 p_nm_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) -{ -#ifdef CONF_WINC_USE_UART - return nm_uart_read_block(u32Addr,puBuf,u16Sz); -#elif defined (CONF_WINC_USE_SPI) - return nm_spi_read_block(u32Addr,puBuf,u16Sz); -#elif defined (CONF_WINC_USE_I2C) - return nm_i2c_read_block(u32Addr,puBuf,u16Sz); -#else -#error "Plesae define bus usage" -#endif - -} -/* -* @fn nm_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u32Sz -* Number of bytes to read. The buffer size must be >= u32Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_read_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz) -{ - uint16 u16MaxTrxSz = egstrNmBusCapabilities.u16MaxTrxSz - MAX_TRX_CFG_SZ; - uint32 off = 0; - sint8 s8Ret = M2M_SUCCESS; - - for(;;) - { - if(u32Sz <= u16MaxTrxSz) - { - s8Ret += p_nm_read_block(u32Addr, &puBuf[off], (uint16)u32Sz); - break; - } - else - { - s8Ret += p_nm_read_block(u32Addr, &puBuf[off], u16MaxTrxSz); - if(M2M_SUCCESS != s8Ret) break; - u32Sz -= u16MaxTrxSz; - off += u16MaxTrxSz; - u32Addr += u16MaxTrxSz; - } - } - - return s8Ret; -} - -static sint8 p_nm_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) -{ -#ifdef CONF_WINC_USE_UART - return nm_uart_write_block(u32Addr,puBuf,u16Sz); -#elif defined (CONF_WINC_USE_SPI) - return nm_spi_write_block(u32Addr,puBuf,u16Sz); -#elif defined (CONF_WINC_USE_I2C) - return nm_i2c_write_block(u32Addr,puBuf,u16Sz); -#else -#error "Plesae define bus usage" -#endif - -} -/** -* @fn nm_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u32Sz -* Number of bytes to write. The buffer size must be >= u32Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_write_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz) -{ - uint16 u16MaxTrxSz = egstrNmBusCapabilities.u16MaxTrxSz - MAX_TRX_CFG_SZ; - uint32 off = 0; - sint8 s8Ret = M2M_SUCCESS; - - for(;;) - { - if(u32Sz <= u16MaxTrxSz) - { - s8Ret += p_nm_write_block(u32Addr, &puBuf[off], (uint16)u32Sz); - break; - } - else - { - s8Ret += p_nm_write_block(u32Addr, &puBuf[off], u16MaxTrxSz); - if(M2M_SUCCESS != s8Ret) break; - u32Sz -= u16MaxTrxSz; - off += u16MaxTrxSz; - u32Addr += u16MaxTrxSz; - } - } - - return s8Ret; -} - -#endif - diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmbus.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmbus.h deleted file mode 100644 index 2ea7838..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmbus.h +++ /dev/null @@ -1,147 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 bus APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NMBUS_H_ -#define _NMBUS_H_ - -#include "common/include/nm_common.h" -#include "bus_wrapper/include/nm_bus_wrapper.h" - - - -#ifdef __cplusplus -extern "C"{ -#endif -/** -* @fn nm_bus_iface_init -* @brief Initialize bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_bus_iface_init(void *); - - -/** -* @fn nm_bus_iface_deinit -* @brief Deinitialize bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_bus_iface_deinit(void); - -/** -* @fn nm_bus_reset -* @brief reset bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @version 1.0 -*/ -sint8 nm_bus_reset(void); - -/** -* @fn nm_bus_iface_reconfigure -* @brief reconfigure bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_bus_iface_reconfigure(void *ptr); - -/** -* @fn nm_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -*/ -uint32 nm_read_reg(uint32 u32Addr); - -/** -* @fn nm_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); - -/** -* @fn nm_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_write_reg(uint32 u32Addr, uint32 u32Val); - -/** -* @fn nm_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u32Sz -* Number of bytes to read. The buffer size must be >= u32Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_read_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz); - -/** -* @fn nm_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u32Sz -* Number of bytes to write. The buffer size must be >= u32Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_write_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz); - - - - -#ifdef __cplusplus -} -#endif - -#endif /* _NMBUS_H_ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmdrv.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmdrv.c deleted file mode 100644 index b3f2a8a..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmdrv.c +++ /dev/null @@ -1,402 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 M2M driver APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "common/include/nm_common.h" -#include "driver/source/nmbus.h" -#include "bsp/include/nm_bsp.h" -#include "driver/source/nmdrv.h" -#include "driver/source/nmasic.h" -#include "driver/include/m2m_types.h" -#include "spi_flash/include/spi_flash.h" - -#ifdef CONF_WINC_USE_SPI -#include "driver/source/nmspi.h" -#endif - -#ifdef ARDUINO - uint32 nmdrv_firm_ver = 0; -#endif - -/** -* @fn nm_get_firmware_info(tstrM2mRev* M2mRev) -* @brief Get Firmware version info -* @param [out] M2mRev -* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters -* @version 1.0 -*/ -sint8 nm_get_firmware_info(tstrM2mRev* M2mRev) -{ - uint16 curr_drv_ver, min_req_drv_ver,curr_firm_ver; - uint32 reg = 0; - sint8 ret = M2M_SUCCESS; - - ret = nm_read_reg_with_ret(NMI_REV_REG, ®); - //In case the Firmware running is ATE fw - if(M2M_ATE_FW_IS_UP_VALUE == reg) - { - //Read FW info again from the register specified for ATE - ret = nm_read_reg_with_ret(NMI_REV_REG_ATE, ®); - } - M2mRev->u8DriverMajor = M2M_GET_DRV_MAJOR(reg); - M2mRev->u8DriverMinor = M2M_GET_DRV_MINOR(reg); - M2mRev->u8DriverPatch = M2M_GET_DRV_PATCH(reg); - M2mRev->u8FirmwareMajor = M2M_GET_FW_MAJOR(reg); - M2mRev->u8FirmwareMinor = M2M_GET_FW_MINOR(reg); - M2mRev->u8FirmwarePatch = M2M_GET_FW_PATCH(reg); - M2mRev->u32Chipid = nmi_get_chipid(); - M2mRev->u16FirmwareSvnNum = 0; - - curr_firm_ver = M2M_MAKE_VERSION(M2mRev->u8FirmwareMajor, M2mRev->u8FirmwareMinor,M2mRev->u8FirmwarePatch); -#ifdef ARDUINO - nmdrv_firm_ver = curr_firm_ver; -#endif - curr_drv_ver = M2M_MAKE_VERSION(M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); - min_req_drv_ver = M2M_MAKE_VERSION(M2mRev->u8DriverMajor, M2mRev->u8DriverMinor,M2mRev->u8DriverPatch); - if(curr_drv_ver < min_req_drv_ver) { - /*The current driver version should be larger or equal - than the min driver that the current firmware support */ - ret = M2M_ERR_FW_VER_MISMATCH; - } - if(curr_drv_ver > curr_firm_ver) { - /*The current driver should be equal or less than the firmware version*/ - ret = M2M_ERR_FW_VER_MISMATCH; - } - return ret; -} -/** -* @fn nm_get_firmware_info(tstrM2mRev* M2mRev) -* @brief Get Firmware version info -* @param [out] M2mRev -* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters -* @version 1.0 -*/ -sint8 nm_get_firmware_full_info(tstrM2mRev* pstrRev) -{ - uint16 curr_drv_ver, min_req_drv_ver,curr_firm_ver; - uint32 reg = 0; - sint8 ret = M2M_SUCCESS; - tstrGpRegs strgp = {0}; - if (pstrRev != NULL) - { - m2m_memset((uint8*)pstrRev,0,sizeof(tstrM2mRev)); - ret = nm_read_reg_with_ret(rNMI_GP_REG_2, ®); - if(ret == M2M_SUCCESS) - { - if(reg != 0) - { - ret = nm_read_block(reg|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); - if(ret == M2M_SUCCESS) - { - reg = strgp.u32Firmware_Ota_rev; - reg &= 0x0000ffff; - if(reg != 0) - { - ret = nm_read_block(reg|0x30000,(uint8*)pstrRev,sizeof(tstrM2mRev)); - if(ret == M2M_SUCCESS) - { - curr_firm_ver = M2M_MAKE_VERSION(pstrRev->u8FirmwareMajor, pstrRev->u8FirmwareMinor,pstrRev->u8FirmwarePatch); -#ifdef ARDUINO - nmdrv_firm_ver = curr_firm_ver; -#endif - curr_drv_ver = M2M_MAKE_VERSION(M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); - min_req_drv_ver = M2M_MAKE_VERSION(pstrRev->u8DriverMajor, pstrRev->u8DriverMinor,pstrRev->u8DriverPatch); - if((curr_firm_ver == 0)||(min_req_drv_ver == 0)||(min_req_drv_ver == 0)){ - ret = M2M_ERR_FAIL; - goto EXIT; - } - if(curr_drv_ver < min_req_drv_ver) { - /*The current driver version should be larger or equal - than the min driver that the current firmware support */ - ret = M2M_ERR_FW_VER_MISMATCH; - goto EXIT; - } - if(curr_drv_ver > curr_firm_ver) { - /*The current driver should be equal or less than the firmware version*/ - ret = M2M_ERR_FW_VER_MISMATCH; - goto EXIT; - } - } - }else { - ret = M2M_ERR_FAIL; - } - } - }else{ - ret = M2M_ERR_FAIL; - } - } - } -EXIT: - return ret; -} -/** -* @fn nm_get_ota_firmware_info(tstrM2mRev* pstrRev) -* @brief Get Firmware version info -* @param [out] M2mRev -* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters - -* @version 1.0 -*/ -sint8 nm_get_ota_firmware_info(tstrM2mRev* pstrRev) -{ - uint16 curr_drv_ver, min_req_drv_ver,curr_firm_ver; - uint32 reg = 0; - sint8 ret; - tstrGpRegs strgp = {0}; - - if (pstrRev != NULL) - { - m2m_memset((uint8*)pstrRev,0,sizeof(tstrM2mRev)); - ret = nm_read_reg_with_ret(rNMI_GP_REG_2, ®); - if(ret == M2M_SUCCESS) - { - if(reg != 0) - { - ret = nm_read_block(reg|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); - if(ret == M2M_SUCCESS) - { - reg = strgp.u32Firmware_Ota_rev; - reg >>= 16; - if(reg != 0) - { - ret = nm_read_block(reg|0x30000,(uint8*)pstrRev,sizeof(tstrM2mRev)); - if(ret == M2M_SUCCESS) - { - curr_firm_ver = M2M_MAKE_VERSION(pstrRev->u8FirmwareMajor, pstrRev->u8FirmwareMinor,pstrRev->u8FirmwarePatch); - curr_drv_ver = M2M_MAKE_VERSION(M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); - min_req_drv_ver = M2M_MAKE_VERSION(pstrRev->u8DriverMajor, pstrRev->u8DriverMinor,pstrRev->u8DriverPatch); - if((curr_firm_ver == 0)||(min_req_drv_ver == 0)||(min_req_drv_ver == 0)){ - ret = M2M_ERR_FAIL; - goto EXIT; - } - if(curr_drv_ver < min_req_drv_ver) { - /*The current driver version should be larger or equal - than the min driver that the current firmware support */ - ret = M2M_ERR_FW_VER_MISMATCH; - } - if(curr_drv_ver > curr_firm_ver) { - /*The current driver should be equal or less than the firmware version*/ - ret = M2M_ERR_FW_VER_MISMATCH; - } - } - }else{ - ret = M2M_ERR_INVALID; - } - } - }else{ - ret = M2M_ERR_FAIL; - } - } - } else { - ret = M2M_ERR_INVALID_ARG; - } -EXIT: - return ret; -} - - - -/* -* @fn nm_drv_init_download_mode -* @brief Initialize NMC1000 driver -* @return M2M_SUCCESS in case of success and Negative error code in case of failure -* @param [in] arg -* Generic argument -* @author Viswanathan Murugesan -* @date 10 Oct 2014 -* @version 1.0 -*/ -sint8 nm_drv_init_download_mode() -{ - sint8 ret = M2M_SUCCESS; - - ret = nm_bus_iface_init(NULL); - if (M2M_SUCCESS != ret) { - M2M_ERR("[nmi start]: fail init bus\n"); - goto ERR1; - } - - /** - TODO:reset the chip and halt the cpu in case of no wait efuse is set (add the no wait effuse check) - */ - if(!ISNMC3000(GET_CHIPID())) - { - /*Execuate that function only for 1500A/B, no room in 3000, but it may be needed in 3400 no wait*/ - chip_reset_and_cpu_halt(); - } - -#ifdef CONF_WINC_USE_SPI - /* Must do this after global reset to set SPI data packet size. */ - nm_spi_init(); -#endif - - M2M_INFO("Chip ID %lx\n", nmi_get_chipid()); - - /*disable all interrupt in ROM (to disable uart) in 2b0 chip*/ - nm_write_reg(0x20300,0); - -ERR1: - return ret; -} - -/* -* @fn nm_drv_init -* @brief Initialize NMC1000 driver -* @return M2M_SUCCESS in case of success and Negative error code in case of failure -* @param [in] arg -* Generic argument -* @author M. Abdelmawla -* @date 15 July 2012 -* @version 1.0 -*/ -sint8 nm_drv_init(void * arg) -{ - sint8 ret = M2M_SUCCESS; - uint8 u8Mode; - - if(NULL != arg) { - u8Mode = *((uint8 *)arg); - if((u8Mode < M2M_WIFI_MODE_NORMAL)||(u8Mode >= M2M_WIFI_MODE_MAX)) { - u8Mode = M2M_WIFI_MODE_NORMAL; - } - } else { - u8Mode = M2M_WIFI_MODE_NORMAL; - } - - ret = nm_bus_iface_init(NULL); - if (M2M_SUCCESS != ret) { - M2M_ERR("[nmi start]: fail init bus\n"); - goto ERR1; - } - -#ifdef BUS_ONLY - return; -#endif - - -#ifdef NO_HW_CHIP_EN - ret = chip_wake(); - if (M2M_SUCCESS != ret) { - M2M_ERR("[nmi start]: fail chip_wakeup\n"); - goto ERR2; - } - /** - Go... - **/ - ret = chip_reset(); - if (M2M_SUCCESS != ret) { - goto ERR2; - } -#endif - M2M_INFO("Chip ID %lx\n", nmi_get_chipid()); -#ifdef CONF_WINC_USE_SPI - /* Must do this after global reset to set SPI data packet size. */ - nm_spi_init(); -#endif - ret = wait_for_bootrom(u8Mode); - if (M2M_SUCCESS != ret) { - goto ERR2; - } - - ret = wait_for_firmware_start(u8Mode); - if (M2M_SUCCESS != ret) { - goto ERR2; - } - - if((M2M_WIFI_MODE_ATE_HIGH == u8Mode)||(M2M_WIFI_MODE_ATE_LOW == u8Mode)) { - goto ERR1; - } else { - /*continue running*/ - } - - ret = enable_interrupts(); - if (M2M_SUCCESS != ret) { - M2M_ERR("failed to enable interrupts..\n"); - goto ERR2; - } - return ret; -ERR2: - nm_bus_iface_deinit(); -ERR1: - return ret; -} - -/* -* @fn nm_drv_deinit -* @brief Deinitialize NMC1000 driver -* @author M. Abdelmawla -* @date 17 July 2012 -* @version 1.0 -*/ -sint8 nm_drv_deinit(void * arg) -{ -#ifdef ARDUINO - (void)arg; // Silence "unused" warning -#endif - sint8 ret; - - ret = chip_deinit(); - if (M2M_SUCCESS != ret) { - M2M_ERR("[nmi stop]: chip_deinit fail\n"); - goto ERR1; - } - - /* Disable SPI flash to save power when the chip is off */ - ret = spi_flash_enable(0); - if (M2M_SUCCESS != ret) { - M2M_ERR("[nmi stop]: SPI flash disable fail\n"); - goto ERR1; - } - - ret = nm_bus_iface_deinit(); - if (M2M_SUCCESS != ret) { - M2M_ERR("[nmi stop]: fail init bus\n"); - goto ERR1; - } -#ifdef CONF_WINC_USE_SPI - /* Must do this after global reset to set SPI data packet size. */ - nm_spi_deinit(); -#endif - -ERR1: - return ret; -} - - diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmdrv.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmdrv.h deleted file mode 100644 index 6a416b2..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmdrv.h +++ /dev/null @@ -1,138 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 M2M driver APIs declarations. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NMDRV_H_ -#define _NMDRV_H_ - -#include "common/include/nm_common.h" - -/** -* @struct tstrM2mRev -* @brief Structure holding firmware version parameters and build date/time -*/ -typedef struct { - uint32 u32Chipid; /* HW revision which will be basically the chip ID */ - uint8 u8FirmwareMajor; /* Version Major Number which represents the official release base */ - uint8 u8FirmwareMinor; /* Version Minor Number which represents the engineering release base */ - uint8 u8FirmwarePatch; /* Version pathc Number which represents the pathces release base */ - uint8 u8DriverMajor; /* Version Major Number which represents the official release base */ - uint8 u8DriverMinor; /* Version Minor Number which represents the engineering release base */ - uint8 u8DriverPatch; /* Version Patch Number which represents the pathces release base */ - uint8 BuildDate[sizeof(__DATE__)]; - uint8 BuildTime[sizeof(__TIME__)]; - uint8 _PAD8_; - uint16 u16FirmwareSvnNum; - uint16 _PAD16_[2]; -} tstrM2mRev; - -/** -* @struct tstrM2mBinaryHeader -* @brief Structure holding compatibility version info for firmware binaries -*/ -typedef struct { - tstrM2mRev binVerInfo; - uint32 flashOffset; - uint32 payloadSize; -} tstrM2mBinaryHeader; - -#ifdef __cplusplus - extern "C" { - #endif -/** -* @fn nm_get_firmware_info(tstrM2mRev* M2mRev) -* @brief Get Firmware version info -* @param [out] M2mRev -* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters -* @version 1.0 -*/ -sint8 nm_get_firmware_info(tstrM2mRev* M2mRev); -/** -* @fn nm_get_firmware_full_info(tstrM2mRev* pstrRev) -* @brief Get Firmware version info -* @param [out] M2mRev -* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters -* @version 1.0 -*/ -sint8 nm_get_firmware_full_info(tstrM2mRev* pstrRev); -/** -* @fn nm_get_ota_firmware_info(tstrM2mRev* pstrRev) -* @brief Get Firmware version info -* @param [out] M2mRev -* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters - -* @version 1.0 -*/ -sint8 nm_get_ota_firmware_info(tstrM2mRev* pstrRev); -/* -* @fn nm_drv_init -* @brief Initialize NMC1000 driver -* @return ZERO in case of success and Negative error code in case of failure -*/ -sint8 nm_drv_init_download_mode(void); - -/* -* @fn nm_drv_init -* @brief Initialize NMC1000 driver -* @return M2M_SUCCESS in case of success and Negative error code in case of failure -* @param [in] arg -* Generic argument TBD -* @return ZERO in case of success and Negative error code in case of failure - -*/ -sint8 nm_drv_init(void * arg); - -/** -* @fn nm_drv_deinit -* @brief Deinitialize NMC1000 driver -* @author M. Abdelmawla -* @param [in] arg -* Generic argument TBD -* @return ZERO in case of success and Negative error code in case of failure -*/ -sint8 nm_drv_deinit(void * arg); - -#ifdef __cplusplus - } - #endif - -#endif /*_NMDRV_H_*/ - - diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmi2c.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmi2c.c deleted file mode 100644 index e11d2f7..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmi2c.c +++ /dev/null @@ -1,269 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 I2C protocol bus APIs implementation. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "common/include/nm_common.h" - -#ifdef CONF_WINC_USE_I2C - -#include "nmi2c.h" -#include "bus_wrapper/include/nm_bus_wrapper.h" - - -/* -* @fn nm_i2c_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ - sint8 nm_i2c_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) -{ - uint8 b[6]; - uint8 rsz; - tstrNmI2cDefault strI2c; - sint8 s8Ret = M2M_SUCCESS; - - if(u32Addr < 0xff) { /* clockless i2c */ - b[0] = 0x09; - b[1] = (uint8)(u32Addr); - rsz = 1; - strI2c.u16Sz = 2; - } else { - b[0] = 0x80; - b[1] = (uint8)(u32Addr >> 24); - b[2] = (uint8)(u32Addr >> 16); - b[3] = (uint8)(u32Addr >> 8); - b[4] = (uint8)(u32Addr); - b[5] = 0x04; - rsz = 4; - strI2c.u16Sz = 6; - } - - strI2c.pu8Buf = b; - - if(M2M_SUCCESS == nm_bus_ioctl(NM_BUS_IOCTL_W, &strI2c)) - { - strI2c.u16Sz = rsz; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strI2c)) - { - //M2M_ERR("read error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - M2M_ERR("failed to send cfg bytes\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - - if (rsz == 1) { - *pu32RetVal = b[0]; - } else { - *pu32RetVal = b[0] | ((uint32)b[1] << 8) | ((uint32)b[2] << 16) | ((uint32)b[3] << 24); - } - return s8Ret; -} - -/* -* @fn nm_i2c_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -uint32 nm_i2c_read_reg(uint32 u32Addr) -{ - uint32 val; - nm_i2c_read_reg_with_ret(u32Addr, &val); - return val; -} - -/* -* @fn nm_i2c_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_i2c_write_reg(uint32 u32Addr, uint32 u32Val) -{ - tstrNmI2cDefault strI2c; - uint8 b[16]; - sint8 s8Ret = M2M_SUCCESS; - - if(u32Addr < 0xff) { /* clockless i2c */ - b[0] = 0x19; - b[1] = (uint8)(u32Addr); - b[2] = (uint8)(u32Val); - strI2c.u16Sz = 3; - } else { - b[0] = 0x90; - b[1] = (uint8)(u32Addr >> 24); - b[2] = (uint8)(u32Addr >> 16); - b[3] = (uint8)(u32Addr >> 8); - b[4] = (uint8)u32Addr; - b[5] = 0x04; - b[6] = (uint8)u32Val; - b[7] = (uint8)(u32Val >> 8); - b[8] = (uint8)(u32Val >> 16); - b[9] = (uint8)(u32Val >> 24); - strI2c.u16Sz = 10; - } - - strI2c.pu8Buf = b; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strI2c)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - - return s8Ret; -} - -/* -* @fn nm_i2c_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u16Sz -* Number of bytes to read. The buffer size must be >= u16Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_i2c_read_block(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz) -{ - tstrNmI2cDefault strI2c; - uint8 au8Buf[7]; - sint8 s8Ret = M2M_SUCCESS; - - au8Buf[0] = 0x02; - au8Buf[1] = (uint8)(u32Addr >> 24); - au8Buf[2] = (uint8)(u32Addr >> 16); - au8Buf[3] = (uint8)(u32Addr >> 8); - au8Buf[4] = (uint8)(u32Addr >> 0); - au8Buf[5] = (uint8)(u16Sz >> 8); - au8Buf[6] = (uint8)(u16Sz); - - strI2c.pu8Buf = au8Buf; - strI2c.u16Sz = sizeof(au8Buf); - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strI2c)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - else - { - strI2c.pu8Buf = pu8Buf; - strI2c.u16Sz = u16Sz; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strI2c)) - { - M2M_ERR("read error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - - return s8Ret; -} - -/* -* @fn nm_i2c_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u16Sz -* Number of bytes to write. The buffer size must be >= u16Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_i2c_write_block(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz) -{ - uint8 au8Buf[7]; - tstrNmI2cSpecial strI2c; - sint8 s8Ret = M2M_SUCCESS; - - au8Buf[0] = 0x12; - au8Buf[1] = (uint8)(u32Addr >> 24); - au8Buf[2] = (uint8)(u32Addr >> 16); - au8Buf[3] = (uint8)(u32Addr >> 8); - au8Buf[4] = (uint8)(u32Addr); - au8Buf[5] = (uint8)(u16Sz >> 8); - au8Buf[6] = (uint8)(u16Sz); - - strI2c.pu8Buf1 = au8Buf; - strI2c.pu8Buf2 = pu8Buf; - strI2c.u16Sz1 = sizeof(au8Buf); - strI2c.u16Sz2 = u16Sz; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W_SPECIAL, &strI2c)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - - return s8Ret; -} - -#endif -/* EOF */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmi2c.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmi2c.h deleted file mode 100644 index fea85e6..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmi2c.h +++ /dev/null @@ -1,104 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 I2C protocol bus APIs implementation. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NMI2C_H_ -#define _NMI2C_H_ - -#include "common/include/nm_common.h" - -/** -* @fn nm_i2c_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -*/ -uint32 nm_i2c_read_reg(uint32 u32Addr); - -/** -* @fn nm_i2c_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_i2c_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); - -/** -* @fn nm_i2c_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_i2c_write_reg(uint32 u32Addr, uint32 u32Val); - -/** -* @fn nm_i2c_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u16Sz -* Number of bytes to read. The buffer size must be >= u16Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_i2c_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); - -/** -* @fn nm_i2c_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u16Sz -* Number of bytes to write. The buffer size must be >= u16Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_i2c_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); - -#endif /* _NMI2C_H_ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmspi.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmspi.c deleted file mode 100644 index 9483ab7..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmspi.c +++ /dev/null @@ -1,1401 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 SPI protocol bus APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -#include "common/include/nm_common.h" - -#ifdef CONF_WINC_USE_SPI - -#define USE_OLD_SPI_SW - -#include "bus_wrapper/include/nm_bus_wrapper.h" -#include "nmspi.h" - -#define NMI_PERIPH_REG_BASE 0x1000 -#define NMI_INTR_REG_BASE (NMI_PERIPH_REG_BASE+0xa00) -#define NMI_CHIPID (NMI_PERIPH_REG_BASE) -#define NMI_PIN_MUX_0 (NMI_PERIPH_REG_BASE + 0x408) -#define NMI_INTR_ENABLE (NMI_INTR_REG_BASE) - -#define NMI_SPI_REG_BASE 0xe800 -#define NMI_SPI_CTL (NMI_SPI_REG_BASE) -#define NMI_SPI_MASTER_DMA_ADDR (NMI_SPI_REG_BASE+0x4) -#define NMI_SPI_MASTER_DMA_COUNT (NMI_SPI_REG_BASE+0x8) -#define NMI_SPI_SLAVE_DMA_ADDR (NMI_SPI_REG_BASE+0xc) -#define NMI_SPI_SLAVE_DMA_COUNT (NMI_SPI_REG_BASE+0x10) -#define NMI_SPI_TX_MODE (NMI_SPI_REG_BASE+0x20) -#define NMI_SPI_PROTOCOL_CONFIG (NMI_SPI_REG_BASE+0x24) -#define NMI_SPI_INTR_CTL (NMI_SPI_REG_BASE+0x2c) -#define NMI_SPI_MISC_CTRL (NMI_SPI_REG_BASE+0x48) - -#define NMI_SPI_PROTOCOL_OFFSET (NMI_SPI_PROTOCOL_CONFIG-NMI_SPI_REG_BASE) - -#define SPI_BASE NMI_SPI_REG_BASE - -#define CMD_DMA_WRITE 0xc1 -#define CMD_DMA_READ 0xc2 -#define CMD_INTERNAL_WRITE 0xc3 -#define CMD_INTERNAL_READ 0xc4 -#define CMD_TERMINATE 0xc5 -#define CMD_REPEAT 0xc6 -#define CMD_DMA_EXT_WRITE 0xc7 -#define CMD_DMA_EXT_READ 0xc8 -#define CMD_SINGLE_WRITE 0xc9 -#define CMD_SINGLE_READ 0xca -#define CMD_RESET 0xcf - -#define N_OK 1 -#define N_FAIL 0 -#define N_RESET -1 -#define N_RETRY -2 - -#define SPI_RESP_RETRY_COUNT (10) -#define SPI_RETRY_COUNT (10) -#define DATA_PKT_SZ_256 256 -#define DATA_PKT_SZ_512 512 -#define DATA_PKT_SZ_1K 1024 -#define DATA_PKT_SZ_4K (4 * 1024) -#define DATA_PKT_SZ_8K (8 * 1024) -#define DATA_PKT_SZ DATA_PKT_SZ_8K - -static uint8 gu8Crc_off = 0; - -static sint8 nmi_spi_read(uint8* b, uint16 sz) -{ - tstrNmSpiRw spi; - spi.pu8InBuf = NULL; - spi.pu8OutBuf = b; - spi.u16Sz = sz; - return nm_bus_ioctl(NM_BUS_IOCTL_RW, &spi); -} - -static sint8 nmi_spi_write(uint8* b, uint16 sz) -{ - tstrNmSpiRw spi; - spi.pu8InBuf = b; - spi.pu8OutBuf = NULL; - spi.u16Sz = sz; - return nm_bus_ioctl(NM_BUS_IOCTL_RW, &spi); -} -#ifndef USE_OLD_SPI_SW -static sint8 nmi_spi_rw(uint8 *bin,uint8* bout,uint16 sz) -{ - tstrNmSpiRw spi; - spi.pu8InBuf = bin; - spi.pu8OutBuf = bout; - spi.u16Sz = sz; - return nm_bus_ioctl(NM_BUS_IOCTL_RW, &spi); -} -#endif -/******************************************** - - Crc7 - -********************************************/ -#if (defined ARDUINO_ARCH_AVR) -#include -static PROGMEM const uint8 crc7_syndrome_table[256] = { -#else -static const uint8 crc7_syndrome_table[256] = { -#endif - 0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f, - 0x48, 0x41, 0x5a, 0x53, 0x6c, 0x65, 0x7e, 0x77, - 0x19, 0x10, 0x0b, 0x02, 0x3d, 0x34, 0x2f, 0x26, - 0x51, 0x58, 0x43, 0x4a, 0x75, 0x7c, 0x67, 0x6e, - 0x32, 0x3b, 0x20, 0x29, 0x16, 0x1f, 0x04, 0x0d, - 0x7a, 0x73, 0x68, 0x61, 0x5e, 0x57, 0x4c, 0x45, - 0x2b, 0x22, 0x39, 0x30, 0x0f, 0x06, 0x1d, 0x14, - 0x63, 0x6a, 0x71, 0x78, 0x47, 0x4e, 0x55, 0x5c, - 0x64, 0x6d, 0x76, 0x7f, 0x40, 0x49, 0x52, 0x5b, - 0x2c, 0x25, 0x3e, 0x37, 0x08, 0x01, 0x1a, 0x13, - 0x7d, 0x74, 0x6f, 0x66, 0x59, 0x50, 0x4b, 0x42, - 0x35, 0x3c, 0x27, 0x2e, 0x11, 0x18, 0x03, 0x0a, - 0x56, 0x5f, 0x44, 0x4d, 0x72, 0x7b, 0x60, 0x69, - 0x1e, 0x17, 0x0c, 0x05, 0x3a, 0x33, 0x28, 0x21, - 0x4f, 0x46, 0x5d, 0x54, 0x6b, 0x62, 0x79, 0x70, - 0x07, 0x0e, 0x15, 0x1c, 0x23, 0x2a, 0x31, 0x38, - 0x41, 0x48, 0x53, 0x5a, 0x65, 0x6c, 0x77, 0x7e, - 0x09, 0x00, 0x1b, 0x12, 0x2d, 0x24, 0x3f, 0x36, - 0x58, 0x51, 0x4a, 0x43, 0x7c, 0x75, 0x6e, 0x67, - 0x10, 0x19, 0x02, 0x0b, 0x34, 0x3d, 0x26, 0x2f, - 0x73, 0x7a, 0x61, 0x68, 0x57, 0x5e, 0x45, 0x4c, - 0x3b, 0x32, 0x29, 0x20, 0x1f, 0x16, 0x0d, 0x04, - 0x6a, 0x63, 0x78, 0x71, 0x4e, 0x47, 0x5c, 0x55, - 0x22, 0x2b, 0x30, 0x39, 0x06, 0x0f, 0x14, 0x1d, - 0x25, 0x2c, 0x37, 0x3e, 0x01, 0x08, 0x13, 0x1a, - 0x6d, 0x64, 0x7f, 0x76, 0x49, 0x40, 0x5b, 0x52, - 0x3c, 0x35, 0x2e, 0x27, 0x18, 0x11, 0x0a, 0x03, - 0x74, 0x7d, 0x66, 0x6f, 0x50, 0x59, 0x42, 0x4b, - 0x17, 0x1e, 0x05, 0x0c, 0x33, 0x3a, 0x21, 0x28, - 0x5f, 0x56, 0x4d, 0x44, 0x7b, 0x72, 0x69, 0x60, - 0x0e, 0x07, 0x1c, 0x15, 0x2a, 0x23, 0x38, 0x31, - 0x46, 0x4f, 0x54, 0x5d, 0x62, 0x6b, 0x70, 0x79 -}; - - -static uint8 crc7_byte(uint8 crc, uint8 data) -{ -#if (defined ARDUINO_ARCH_AVR) - return pgm_read_byte_near(crc7_syndrome_table + ((crc << 1) ^ data)); -#else - return crc7_syndrome_table[(crc << 1) ^ data]; -#endif -} - -static uint8 crc7(uint8 crc, const uint8 *buffer, uint32 len) -{ - while (len--) - crc = crc7_byte(crc, *buffer++); - return crc; -} - -/******************************************** - - Spi protocol Function - -********************************************/ - -#define CMD_DMA_WRITE 0xc1 -#define CMD_DMA_READ 0xc2 -#define CMD_INTERNAL_WRITE 0xc3 -#define CMD_INTERNAL_READ 0xc4 -#define CMD_TERMINATE 0xc5 -#define CMD_REPEAT 0xc6 -#define CMD_DMA_EXT_WRITE 0xc7 -#define CMD_DMA_EXT_READ 0xc8 -#define CMD_SINGLE_WRITE 0xc9 -#define CMD_SINGLE_READ 0xca -#define CMD_RESET 0xcf - -#define DATA_PKT_SZ_256 256 -#define DATA_PKT_SZ_512 512 -#define DATA_PKT_SZ_1K 1024 -#define DATA_PKT_SZ_4K (4 * 1024) -#define DATA_PKT_SZ_8K (8 * 1024) -#define DATA_PKT_SZ DATA_PKT_SZ_8K - -static sint8 spi_cmd(uint8 cmd, uint32 adr, uint32 u32data, uint32 sz,uint8 clockless) -{ - uint8 bc[9]; - uint8 len = 5; - sint8 result = N_OK; - - bc[0] = cmd; - switch (cmd) { - case CMD_SINGLE_READ: /* single word (4 bytes) read */ - bc[1] = (uint8)(adr >> 16); - bc[2] = (uint8)(adr >> 8); - bc[3] = (uint8)adr; - len = 5; - break; - case CMD_INTERNAL_READ: /* internal register read */ - bc[1] = (uint8)(adr >> 8); - if(clockless) bc[1] |= (1 << 7); - bc[2] = (uint8)adr; - bc[3] = 0x00; - len = 5; - break; - case CMD_TERMINATE: /* termination */ - bc[1] = 0x00; - bc[2] = 0x00; - bc[3] = 0x00; - len = 5; - break; - case CMD_REPEAT: /* repeat */ - bc[1] = 0x00; - bc[2] = 0x00; - bc[3] = 0x00; - len = 5; - break; - case CMD_RESET: /* reset */ - bc[1] = 0xff; - bc[2] = 0xff; - bc[3] = 0xff; - len = 5; - break; - case CMD_DMA_WRITE: /* dma write */ - case CMD_DMA_READ: /* dma read */ - bc[1] = (uint8)(adr >> 16); - bc[2] = (uint8)(adr >> 8); - bc[3] = (uint8)adr; - bc[4] = (uint8)(sz >> 8); - bc[5] = (uint8)(sz); - len = 7; - break; - case CMD_DMA_EXT_WRITE: /* dma extended write */ - case CMD_DMA_EXT_READ: /* dma extended read */ - bc[1] = (uint8)(adr >> 16); - bc[2] = (uint8)(adr >> 8); - bc[3] = (uint8)adr; - bc[4] = (uint8)(sz >> 16); - bc[5] = (uint8)(sz >> 8); - bc[6] = (uint8)(sz); - len = 8; - break; - case CMD_INTERNAL_WRITE: /* internal register write */ - bc[1] = (uint8)(adr >> 8); - if(clockless) bc[1] |= (1 << 7); - bc[2] = (uint8)(adr); - bc[3] = (uint8)(u32data >> 24); - bc[4] = (uint8)(u32data >> 16); - bc[5] = (uint8)(u32data >> 8); - bc[6] = (uint8)(u32data); - len = 8; - break; - case CMD_SINGLE_WRITE: /* single word write */ - bc[1] = (uint8)(adr >> 16); - bc[2] = (uint8)(adr >> 8); - bc[3] = (uint8)(adr); - bc[4] = (uint8)(u32data >> 24); - bc[5] = (uint8)(u32data >> 16); - bc[6] = (uint8)(u32data >> 8); - bc[7] = (uint8)(u32data); - len = 9; - break; - default: - result = N_FAIL; - break; - } - - if (result) { - if (!gu8Crc_off) - bc[len-1] = (crc7(0x7f, (const uint8 *)&bc[0], len-1)) << 1; - else - len-=1; - - if (M2M_SUCCESS != nmi_spi_write(bc, len)) { - M2M_ERR("[nmi spi]: Failed cmd write, bus error...\n"); - result = N_FAIL; - } - } - - return result; -} - -static sint8 spi_data_rsp(uint8 cmd) -{ -#ifdef ARDUINO - (void)cmd; // Silence "unused" warning -#endif - uint8 len; - uint8 rsp[3]; - sint8 result = N_OK; - - if (!gu8Crc_off) - len = 2; - else - len = 3; - - if (M2M_SUCCESS != nmi_spi_read(&rsp[0], len)) { - M2M_ERR("[nmi spi]: Failed bus error...\n"); - result = N_FAIL; - goto _fail_; - } - - if((rsp[len-1] != 0)||(rsp[len-2] != 0xC3)) - { - M2M_ERR("[nmi spi]: Failed data response read, %x %x %x\n",rsp[0],rsp[1],rsp[2]); - result = N_FAIL; - goto _fail_; - } -_fail_: - - return result; -} - -static sint8 spi_cmd_rsp(uint8 cmd) -{ - uint8 rsp; - sint8 result = N_OK; - sint8 s8RetryCnt; - - /** - Command/Control response - **/ - if ((cmd == CMD_RESET) || - (cmd == CMD_TERMINATE) || - (cmd == CMD_REPEAT)) { - if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { - result = N_FAIL; - goto _fail_; - } - } - - /* wait for response */ - s8RetryCnt = SPI_RESP_RETRY_COUNT; - do - { - if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { - M2M_ERR("[nmi spi]: Failed cmd response read, bus error...\n"); - result = N_FAIL; - goto _fail_; - } - } while((rsp != cmd) && (s8RetryCnt-- >0)); - - /** - State response - **/ - /* wait for response */ - s8RetryCnt = SPI_RESP_RETRY_COUNT; - do - { - if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { - M2M_ERR("[nmi spi]: Failed cmd response read, bus error...\n"); - result = N_FAIL; - goto _fail_; - } - } while((rsp != 0x00) && (s8RetryCnt-- >0)); - -_fail_: - - return result; -} -#ifndef USE_OLD_SPI_SW -static int spi_cmd_complete(uint8_t cmd, uint32_t adr, uint8_t *b, uint32_t sz, uint8_t clockless) -{ - uint8_t wb[32], rb[32]; - uint8_t wix, rix; - uint32_t len2; - uint8_t rsp; - int len = 0; - int result = N_OK; - - wb[0] = cmd; - switch (cmd) { - case CMD_SINGLE_READ: /* single word (4 bytes) read */ - wb[1] = (uint8_t)(adr >> 16); - wb[2] = (uint8_t)(adr >> 8); - wb[3] = (uint8_t)adr; - len = 5; - break; - case CMD_INTERNAL_READ: /* internal register read */ - wb[1] = (uint8_t)(adr >> 8); - if(clockless == 1) wb[1] |= (1 << 7); - wb[2] = (uint8_t)adr; - wb[3] = 0x00; - len = 5; - break; - case CMD_TERMINATE: /* termination */ - wb[1] = 0x00; - wb[2] = 0x00; - wb[3] = 0x00; - len = 5; - break; - case CMD_REPEAT: /* repeat */ - wb[1] = 0x00; - wb[2] = 0x00; - wb[3] = 0x00; - len = 5; - break; - case CMD_RESET: /* reset */ - wb[1] = 0xff; - wb[2] = 0xff; - wb[3] = 0xff; - len = 5; - break; - case CMD_DMA_WRITE: /* dma write */ - case CMD_DMA_READ: /* dma read */ - wb[1] = (uint8_t)(adr >> 16); - wb[2] = (uint8_t)(adr >> 8); - wb[3] = (uint8_t)adr; - wb[4] = (uint8_t)(sz >> 8); - wb[5] = (uint8_t)(sz); - len = 7; - break; - case CMD_DMA_EXT_WRITE: /* dma extended write */ - case CMD_DMA_EXT_READ: /* dma extended read */ - wb[1] = (uint8_t)(adr >> 16); - wb[2] = (uint8_t)(adr >> 8); - wb[3] = (uint8_t)adr; - wb[4] = (uint8_t)(sz >> 16); - wb[5] = (uint8_t)(sz >> 8); - wb[6] = (uint8_t)(sz); - len = 8; - break; - case CMD_INTERNAL_WRITE: /* internal register write */ - wb[1] = (uint8_t)(adr >> 8); - if(clockless == 1) wb[1] |= (1 << 7); - wb[2] = (uint8_t)(adr); - wb[3] = b[3]; - wb[4] = b[2]; - wb[5] = b[1]; - wb[6] = b[0]; - len = 8; - break; - case CMD_SINGLE_WRITE: /* single word write */ - wb[1] = (uint8_t)(adr >> 16); - wb[2] = (uint8_t)(adr >> 8); - wb[3] = (uint8_t)(adr); - wb[4] = b[3]; - wb[5] = b[2]; - wb[6] = b[1]; - wb[7] = b[0]; - len = 9; - break; - default: - result = N_FAIL; - break; - } - - if (result != N_OK) { - return result; - } - - if (!gu8Crc_off) { - wb[len-1] = (crc7(0x7f, (const uint8_t *)&wb[0], len-1)) << 1; - } else { - len -=1; - } - -#define NUM_SKIP_BYTES (1) -#define NUM_RSP_BYTES (2) -#define NUM_DATA_HDR_BYTES (1) -#define NUM_DATA_BYTES (4) -#define NUM_CRC_BYTES (2) -#define NUM_DUMMY_BYTES (3) - - if ((cmd == CMD_RESET) || - (cmd == CMD_TERMINATE) || - (cmd == CMD_REPEAT)) { - len2 = len + (NUM_SKIP_BYTES + NUM_RSP_BYTES + NUM_DUMMY_BYTES); - } else if ((cmd == CMD_INTERNAL_READ) || (cmd == CMD_SINGLE_READ)) { - if (!gu8Crc_off) { - len2 = len + (NUM_RSP_BYTES + NUM_DATA_HDR_BYTES + NUM_DATA_BYTES - + NUM_CRC_BYTES + NUM_DUMMY_BYTES); - } else { - len2 = len + (NUM_RSP_BYTES + NUM_DATA_HDR_BYTES + NUM_DATA_BYTES - + NUM_DUMMY_BYTES); - } - } else { - len2 = len + (NUM_RSP_BYTES + NUM_DUMMY_BYTES); - } -#undef NUM_DUMMY_BYTES - - if(len2 > (sizeof(wb)/sizeof(wb[0]))) { - M2M_ERR("[nmi spi]: spi buffer size too small (%d) (%d)\n", - len2, (sizeof(wb)/sizeof(wb[0]))); - result = N_FAIL; - return result; - } - /* zero spi write buffers. */ - for(wix = len; wix< len2; wix++) { - wb[wix] = 0; - } - rix = len; - - if (nmi_spi_rw(wb, rb, len2) != M2M_SUCCESS) { - M2M_ERR("[nmi spi]: Failed cmd write, bus error...\n"); - result = N_FAIL; - return result; - } - -#if 0 - { - int jj; - printk("--- cnd = %x, len=%d, len2=%d\n", cmd, len, len2); - for(jj=0; jj= len2) break; - if(((jj+1)%16) != 0) { - if((jj%16) == 0) { - printk("wb[%02x]: %02x ", jj, wb[jj]); - } else { - printk("%02x ", wb[jj]); - } - } else { - printk("%02x\n", wb[jj]); - } - } - printk("\n"); - - for(jj=0; jj= len2) break; - if(((jj+1)%16) != 0) { - if((jj%16) == 0) { - printk("rb[%02x]: %02x ", jj, rb[jj]); - } else { - printk("%02x ", rb[jj]); - } - } else { - printk("%02x\n", rb[jj]); - } - } - printk("\n"); - } -#endif - - /** - Command/Control response - **/ - if ((cmd == CMD_RESET) || - (cmd == CMD_TERMINATE) || - (cmd == CMD_REPEAT)) { - rix++; /* skip 1 byte */ - } - - rsp = rb[rix++]; - - - if (rsp != cmd) { - M2M_ERR("[nmi spi]: Failed cmd response, cmd (%02x), resp (%02x)\n", cmd, rsp); - result = N_FAIL; - return result; - } - - /** - State response - **/ - rsp = rb[rix++]; - if (rsp != 0x00) { - M2M_ERR("[nmi spi]: Failed cmd state response state (%02x)\n", rsp); - result = N_FAIL; - return result; - } - - if ((cmd == CMD_INTERNAL_READ) || (cmd == CMD_SINGLE_READ) - || (cmd == CMD_DMA_READ) || (cmd == CMD_DMA_EXT_READ)) { - int retry; - //uint16_t crc1, crc2; - uint8_t crc[2]; - /** - Data Respnose header - **/ - retry = SPI_RESP_RETRY_COUNT; - do { - /* ensure there is room in buffer later to read data and crc */ - if(rix < len2) { - rsp = rb[rix++]; - } else { - retry = 0; - break; - } - if (((rsp >> 4) & 0xf) == 0xf) - break; - } while (retry--); - - if (retry <= 0) { - M2M_ERR("[nmi spi]: Error, data read response (%02x)\n", rsp); - result = N_RESET; - return result; - } - - if ((cmd == CMD_INTERNAL_READ) || (cmd == CMD_SINGLE_READ)) { - /** - Read bytes - **/ - if((rix+3) < len2) { - b[0] = rb[rix++]; - b[1] = rb[rix++]; - b[2] = rb[rix++]; - b[3] = rb[rix++]; - } else { - M2M_ERR("[nmi spi]: buffer overrun when reading data.\n"); - result = N_FAIL; - return result; - } - - if (!gu8Crc_off) { - /** - Read Crc - **/ - if((rix+1) < len2) { - crc[0] = rb[rix++]; - crc[1] = rb[rix++]; - } else { - M2M_ERR("[nmi spi]: buffer overrun when reading crc.\n"); - result = N_FAIL; - return result; - } - } - } else if((cmd == CMD_DMA_READ) || (cmd == CMD_DMA_EXT_READ)) { - int ix; - - /* some data may be read in response to dummy bytes. */ - for(ix=0; (rix < len2) && (ix < sz);) { - b[ix++] = rb[rix++]; - } -#if 0 - if(ix) M2M_INFO("ttt %d %d\n", sz, ix); -#endif - sz -= ix; - - if(sz > 0) { - int nbytes; - - if (sz <= (DATA_PKT_SZ-ix)) { - nbytes = sz; - } else { - nbytes = DATA_PKT_SZ-ix; - } - - /** - Read bytes - **/ - if (nmi_spi_read(&b[ix], nbytes) != M2M_SUCCESS) { - M2M_ERR("[nmi spi]: Failed data block read, bus error...\n"); - result = N_FAIL; - goto _error_; - } - - /** - Read Crc - **/ - if (!gu8Crc_off) { - if (nmi_spi_read(crc, 2) != M2M_SUCCESS) { - M2M_ERR("[nmi spi]: Failed data block crc read, bus error...\n"); - result = N_FAIL; - goto _error_; - } - } - - - ix += nbytes; - sz -= nbytes; - } - - /* if any data in left unread, then read the rest using normal DMA code.*/ - while(sz > 0) { - int nbytes; - - if (sz <= DATA_PKT_SZ) { - nbytes = sz; - } else { - nbytes = DATA_PKT_SZ; - } - - /** - read data response only on the next DMA cycles not - the first DMA since data response header is already - handled above for the first DMA. - **/ - /** - Data Respnose header - **/ - retry = SPI_RESP_RETRY_COUNT; - do { - if (nmi_spi_read(&rsp, 1) != M2M_SUCCESS) { - M2M_ERR("[nmi spi]: Failed data response read, bus error...\n"); - result = N_FAIL; - break; - } - if (((rsp >> 4) & 0xf) == 0xf) - break; - } while (retry--); - - if (result == N_FAIL) - break; - - - /** - Read bytes - **/ - if (nmi_spi_read(&b[ix], nbytes) != M2M_SUCCESS) { - M2M_ERR("[nmi spi]: Failed data block read, bus error...\n"); - result = N_FAIL; - break; - } - - /** - Read Crc - **/ - if (!gu8Crc_off) { - if (nmi_spi_read(crc, 2) != M2M_SUCCESS) { - M2M_ERR("[nmi spi]: Failed data block crc read, bus error...\n"); - result = N_FAIL; - break; - } - } - - ix += nbytes; - sz -= nbytes; - } - } - } -_error_: - return result; -} -#endif -static sint8 spi_data_read(uint8 *b, uint16 sz,uint8 clockless) -{ - sint16 retry, ix, nbytes; - sint8 result = N_OK; - uint8 crc[2]; - uint8 rsp; - - /** - Data - **/ - ix = 0; - do { - if (sz <= DATA_PKT_SZ) - nbytes = sz; - else - nbytes = DATA_PKT_SZ; - - /** - Data Respnose header - **/ - retry = SPI_RESP_RETRY_COUNT; - do { - if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { - M2M_ERR("[nmi spi]: Failed data response read, bus error...\n"); - result = N_FAIL; - break; - } - if (((rsp >> 4) & 0xf) == 0xf) - break; - } while (retry--); - - if (result == N_FAIL) - break; - - if (retry <= 0) { - M2M_ERR("[nmi spi]: Failed data response read...(%02x)\n", rsp); - result = N_FAIL; - break; - } - - /** - Read bytes - **/ - if (M2M_SUCCESS != nmi_spi_read(&b[ix], nbytes)) { - M2M_ERR("[nmi spi]: Failed data block read, bus error...\n"); - result = N_FAIL; - break; - } - if(!clockless) - { - /** - Read Crc - **/ - if (!gu8Crc_off) { - if (M2M_SUCCESS != nmi_spi_read(crc, 2)) { - M2M_ERR("[nmi spi]: Failed data block crc read, bus error...\n"); - result = N_FAIL; - break; - } - } - } - ix += nbytes; - sz -= nbytes; - - } while (sz); - - return result; -} - -static sint8 spi_data_write(uint8 *b, uint16 sz) -{ - sint16 ix; - uint16 nbytes; - sint8 result = 1; - uint8 cmd, order, crc[2] = {0}; - //uint8 rsp; - - /** - Data - **/ - ix = 0; - do { - if (sz <= DATA_PKT_SZ) - nbytes = sz; - else - nbytes = DATA_PKT_SZ; - - /** - Write command - **/ - cmd = 0xf0; - if (ix == 0) { - if (sz <= DATA_PKT_SZ) - order = 0x3; - else - order = 0x1; - } else { - if (sz <= DATA_PKT_SZ) - order = 0x3; - else - order = 0x2; - } - cmd |= order; - if (M2M_SUCCESS != nmi_spi_write(&cmd, 1)) { - M2M_ERR("[nmi spi]: Failed data block cmd write, bus error...\n"); - result = N_FAIL; - break; - } - - /** - Write data - **/ - if (M2M_SUCCESS != nmi_spi_write(&b[ix], nbytes)) { - M2M_ERR("[nmi spi]: Failed data block write, bus error...\n"); - result = N_FAIL; - break; - } - - /** - Write Crc - **/ - if (!gu8Crc_off) { - if (M2M_SUCCESS != nmi_spi_write(crc, 2)) { - M2M_ERR("[nmi spi]: Failed data block crc write, bus error...\n"); - result = N_FAIL; - break; - } - } - - ix += nbytes; - sz -= nbytes; - } while (sz); - - - return result; -} - -/******************************************** - - Spi Internal Read/Write Function - -********************************************/ - -/******************************************** - - Spi interfaces - -********************************************/ - -static sint8 spi_write_reg(uint32 addr, uint32 u32data) -{ - uint8 retry = SPI_RETRY_COUNT; - sint8 result = N_OK; - uint8 cmd = CMD_SINGLE_WRITE; - uint8 clockless = 0; - -_RETRY_: - if (addr <= 0x30) - { - /** - NMC1000 clockless registers. - **/ - cmd = CMD_INTERNAL_WRITE; - clockless = 1; - } - else - { - cmd = CMD_SINGLE_WRITE; - clockless = 0; - } - -#if defined USE_OLD_SPI_SW - result = spi_cmd(cmd, addr, u32data, 4, clockless); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd, write reg (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - - result = spi_cmd_rsp(cmd); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd response, write reg (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - -#else - - result = spi_cmd_complete(cmd, addr, (uint8*)&u32data, 4, clockless); - if (result != N_OK) { - M2M_ERR( "[nmi spi]: Failed cmd, write reg (%08x)...\n", addr); - goto _FAIL_; - } - -#endif -_FAIL_: - if(result != N_OK) - { - nm_bsp_sleep(1); - spi_cmd(CMD_RESET, 0, 0, 0, 0); - spi_cmd_rsp(CMD_RESET); - M2M_ERR("Reset and retry %d %lx %lx\n",retry,addr,u32data); - nm_bsp_sleep(1); - retry--; - if(retry) goto _RETRY_; - } - - return result; -} - -static sint8 nm_spi_write(uint32 addr, uint8 *buf, uint16 size) -{ - sint8 result; - uint8 retry = SPI_RETRY_COUNT; - uint8 cmd = CMD_DMA_EXT_WRITE; - - -_RETRY_: - /** - Command - **/ -#if defined USE_OLD_SPI_SW - //Workaround hardware problem with single byte transfers over SPI bus - if (size == 1) - size = 2; - - result = spi_cmd(cmd, addr, 0, size,0); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd, write block (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - - result = spi_cmd_rsp(cmd); - if (result != N_OK) { - M2M_ERR("[nmi spi ]: Failed cmd response, write block (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } -#else - result = spi_cmd_complete(cmd, addr, NULL, size, 0); - if (result != N_OK) { - M2M_ERR( "[nmi spi]: Failed cmd, write block (%08x)...\n", addr); - goto _FAIL_; - } -#endif - - /** - Data - **/ - result = spi_data_write(buf, size); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed block data write...\n"); - goto _FAIL_; - } - /** - Data RESP - **/ - result = spi_data_rsp(cmd); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed block data write...\n"); - goto _FAIL_; - } - -_FAIL_: - if(result != N_OK) - { - nm_bsp_sleep(1); - spi_cmd(CMD_RESET, 0, 0, 0, 0); - spi_cmd_rsp(CMD_RESET); - M2M_ERR("Reset and retry %d %lx %d\n",retry,addr,size); - nm_bsp_sleep(1); - retry--; - if(retry) goto _RETRY_; - } - - - return result; -} - -static sint8 spi_read_reg(uint32 addr, uint32 *u32data) -{ - uint8 retry = SPI_RETRY_COUNT; - sint8 result = N_OK; - uint8 cmd = CMD_SINGLE_READ; - uint8 tmp[4]; - uint8 clockless = 0; - -_RETRY_: - - if (addr <= 0xff) - { - /** - NMC1000 clockless registers. - **/ - cmd = CMD_INTERNAL_READ; - clockless = 1; - } - else - { - cmd = CMD_SINGLE_READ; - clockless = 0; - } - -#if defined USE_OLD_SPI_SW - result = spi_cmd(cmd, addr, 0, 4, clockless); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd, read reg (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - - result = spi_cmd_rsp(cmd); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd response, read reg (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - - /* to avoid endianess issues */ - result = spi_data_read(&tmp[0], 4, clockless); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed data read...\n"); - goto _FAIL_; - } -#else - result = spi_cmd_complete(cmd, addr, (uint8*)&tmp[0], 4, clockless); - if (result != N_OK) { - M2M_ERR( "[nmi spi]: Failed cmd, read reg (%08x)...\n", addr); - goto _FAIL_; - } - -#endif - - *u32data = tmp[0] | - ((uint32)tmp[1] << 8) | - ((uint32)tmp[2] << 16) | - ((uint32)tmp[3] << 24); - -_FAIL_: - if(result != N_OK) - { - - nm_bsp_sleep(1); - spi_cmd(CMD_RESET, 0, 0, 0, 0); - spi_cmd_rsp(CMD_RESET); - M2M_ERR("Reset and retry %d %lx\n",retry,addr); - nm_bsp_sleep(1); - retry--; - if(retry) goto _RETRY_; - } - - return result; -} - -static sint8 nm_spi_read(uint32 addr, uint8 *buf, uint16 size) -{ - uint8 cmd = CMD_DMA_EXT_READ; - sint8 result; - uint8 retry = SPI_RETRY_COUNT; -#if defined USE_OLD_SPI_SW - uint8 tmp[2]; - uint8 single_byte_workaround = 0; -#endif - -_RETRY_: - - /** - Command - **/ -#if defined USE_OLD_SPI_SW - if (size == 1) - { - //Workaround hardware problem with single byte transfers over SPI bus - size = 2; - single_byte_workaround = 1; - } - result = spi_cmd(cmd, addr, 0, size,0); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd, read block (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - - result = spi_cmd_rsp(cmd); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd response, read block (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - - /** - Data - **/ - if (single_byte_workaround) - { - result = spi_data_read(tmp, size,0); - buf[0] = tmp[0]; - } - else - result = spi_data_read(buf, size,0); - - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed block data read...\n"); - goto _FAIL_; - } -#else - result = spi_cmd_complete(cmd, addr, buf, size, 0); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd, read block (%08x)...\n", addr); - goto _FAIL_; - } -#endif - -_FAIL_: - if(result != N_OK) - { - nm_bsp_sleep(1); - spi_cmd(CMD_RESET, 0, 0, 0, 0); - spi_cmd_rsp(CMD_RESET); - M2M_ERR("Reset and retry %d %lx %d\n",retry,addr,size); - nm_bsp_sleep(1); - retry--; - if(retry) goto _RETRY_; - } - - return result; -} - -/******************************************** - - Bus interfaces - -********************************************/ - -static void spi_init_pkt_sz(void) -{ - uint32 val32; - - /* Make sure SPI max. packet size fits the defined DATA_PKT_SZ. */ - val32 = nm_spi_read_reg(SPI_BASE+0x24); - val32 &= ~(0x7 << 4); - switch(DATA_PKT_SZ) - { - case 256: val32 |= (0 << 4); break; - case 512: val32 |= (1 << 4); break; - case 1024: val32 |= (2 << 4); break; - case 2048: val32 |= (3 << 4); break; - case 4096: val32 |= (4 << 4); break; - case 8192: val32 |= (5 << 4); break; - - } - nm_spi_write_reg(SPI_BASE+0x24, val32); -} - -sint8 nm_spi_reset(void) -{ - spi_cmd(CMD_RESET, 0, 0, 0, 0); - spi_cmd_rsp(CMD_RESET); - return M2M_SUCCESS; -} - -/* -* @fn nm_spi_init -* @brief Initialize the SPI -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_spi_init(void) -{ - uint32 chipid; - uint32 reg = 0; - - - /** - configure protocol - **/ - gu8Crc_off = 0; - - // TODO: We can remove the CRC trials if there is a definite way to reset - // the SPI to it's initial value. - if (!spi_read_reg(NMI_SPI_PROTOCOL_CONFIG, ®)) { - /* Read failed. Try with CRC off. This might happen when module - is removed but chip isn't reset*/ - gu8Crc_off = 1; - M2M_ERR("[nmi spi]: Failed internal read protocol with CRC on, retyring with CRC off...\n"); - if (!spi_read_reg(NMI_SPI_PROTOCOL_CONFIG, ®)){ - // Reaad failed with both CRC on and off, something went bad - M2M_ERR( "[nmi spi]: Failed internal read protocol...\n"); - return 0; - } - } - if(gu8Crc_off == 0) - { - reg &= ~0xc; /* disable crc checking */ - reg &= ~0x70; - reg |= (0x5 << 4); - if (!spi_write_reg(NMI_SPI_PROTOCOL_CONFIG, reg)) { - M2M_ERR( "[nmi spi]: Failed internal write protocol reg...\n"); - return 0; - } - gu8Crc_off = 1; - } - - /** - make sure can read back chip id correctly - **/ - if (!spi_read_reg(0x1000, &chipid)) { - M2M_ERR("[nmi spi]: Fail cmd read chip id...\n"); - return M2M_ERR_BUS_FAIL; - } - - M2M_DBG("[nmi spi]: chipid (%08x)\n", (unsigned int)chipid); - spi_init_pkt_sz(); - - - return M2M_SUCCESS; -} - -/* -* @fn nm_spi_init -* @brief DeInitialize the SPI -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Samer Sarhan -* @date 27 Feb 2015 -* @version 1.0 -*/ -sint8 nm_spi_deinit(void) -{ - gu8Crc_off = 0; - return M2M_SUCCESS; -} - -/* -* @fn nm_spi_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -uint32 nm_spi_read_reg(uint32 u32Addr) -{ - uint32 u32Val; - - spi_read_reg(u32Addr, &u32Val); - - return u32Val; -} - -/* -* @fn nm_spi_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_spi_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) -{ - sint8 s8Ret; - - s8Ret = spi_read_reg(u32Addr,pu32RetVal); - - if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; - else s8Ret = M2M_ERR_BUS_FAIL; - - return s8Ret; -} - -/* -* @fn nm_spi_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_spi_write_reg(uint32 u32Addr, uint32 u32Val) -{ - sint8 s8Ret; - - s8Ret = spi_write_reg(u32Addr, u32Val); - - if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; - else s8Ret = M2M_ERR_BUS_FAIL; - - return s8Ret; -} - -/* -* @fn nm_spi_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u16Sz -* Number of bytes to read. The buffer size must be >= u16Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_spi_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) -{ - sint8 s8Ret; - - s8Ret = nm_spi_read(u32Addr, puBuf, u16Sz); - - if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; - else s8Ret = M2M_ERR_BUS_FAIL; - - return s8Ret; -} - -/* -* @fn nm_spi_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u16Sz -* Number of bytes to write. The buffer size must be >= u16Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_spi_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) -{ - sint8 s8Ret; - - s8Ret = nm_spi_write(u32Addr, puBuf, u16Sz); - - if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; - else s8Ret = M2M_ERR_BUS_FAIL; - - return s8Ret; -} - -#endif diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmspi.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmspi.h deleted file mode 100644 index a1bd4a9..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmspi.h +++ /dev/null @@ -1,132 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 SPI protocol bus APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NMSPI_H_ -#define _NMSPI_H_ - -#include "common/include/nm_common.h" - -#ifdef __cplusplus - extern "C" { -#endif - -/** -* @fn nm_spi_init -* @brief Initialize the SPI -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_init(void); -/** -* @fn nm_spi_reset -* @brief reset the SPI -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_reset(void); - -/** -* @fn nm_spi_deinit -* @brief DeInitialize the SPI -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_deinit(void); - -/** -* @fn nm_spi_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -*/ -uint32 nm_spi_read_reg(uint32 u32Addr); - -/** -* @fn nm_spi_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); - -/** -* @fn nm_spi_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_write_reg(uint32 u32Addr, uint32 u32Val); - -/** -* @fn nm_spi_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u16Sz -* Number of bytes to read. The buffer size must be >= u16Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); - -/** -* @fn nm_spi_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u16Sz -* Number of bytes to write. The buffer size must be >= u16Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); - -#ifdef __cplusplus - } -#endif - -#endif /* _NMSPI_H_ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmuart.c b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmuart.c deleted file mode 100644 index 63541cf..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmuart.c +++ /dev/null @@ -1,536 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 UART protocol bus APIs implementation. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "common/include/nm_common.h" - -#ifdef CONF_WINC_USE_UART - -#include "driver/source/nmuart.h" -#include "bus_wrapper/include/nm_bus_wrapper.h" - -#define HDR_SZ 12 - -static uint8 get_cs(uint8* b, uint8 sz){ - int i; - uint8 cs = 0; - for(i = 0; i < sz; i++) - cs ^= b[i]; - return cs; -} - -/* -* @fn nm_uart_sync_cmd -* @brief Check COM Port -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Dina El Sissy -* @date 13 AUG 2012 -* @version 1.0 -*/ -sint8 nm_uart_sync_cmd(void) -{ - tstrNmUartDefault strUart; - sint8 s8Ret = -1; - uint8 b [HDR_SZ+1]; - uint8 rsz; - uint8 onchip = 0; - - /*read reg*/ - b[0] = 0x12; - - rsz = 1; - strUart.pu8Buf = b; - strUart.u16Sz = 1; - - if(M2M_SUCCESS == nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - strUart.u16Sz = rsz; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - M2M_ERR("failed to send cfg bytes\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - if (b[0] == 0x5a) - { - s8Ret = 0; - onchip = 1; - M2M_INFO("Built-in WINC1500 UART Found\n"); - } - else if(b[0] == 0x5b) - { - s8Ret = 0; - onchip = 0; - M2M_INFO("WINC1500 Serial Bridge Found\n"); - } - /*TODO: this should be the way we read the register since the cortus is little endian*/ - /**pu32RetVal = b[0] | ((uint32)b[1] << 8) | ((uint32)b[2] << 16) | ((uint32)b[3] << 24);*/ - if(s8Ret == M2M_SUCCESS) - s8Ret = (sint8)onchip; - return s8Ret; -} - sint8 nm_uart_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) -{ - tstrNmUartDefault strUart; - sint8 s8Ret = M2M_SUCCESS; - uint8 b [HDR_SZ+1]; - uint8 rsz; - - /*read reg*/ - b[0] = 0xa5; - b[1] = 0; - b[2] = 0; - b[3] = 0; - b[4] = 0; - b[5] = (uint8)(u32Addr & 0x000000ff); - b[6] = (uint8)((u32Addr & 0x0000ff00)>>8); - b[7] = (uint8)((u32Addr & 0x00ff0000)>>16); - b[8] = (uint8)((u32Addr & 0xff000000)>>24); - b[9] = 0; - b[10] = 0; - b[11] = 0; - b[12] = 0; - - b[2] = get_cs(&b[1],HDR_SZ); - - rsz = 4; - strUart.pu8Buf = b; - strUart.u16Sz = sizeof(b); - - if(M2M_SUCCESS == nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - if(!nm_bus_get_chip_type()) - { - strUart.u16Sz = 1; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - if(b[0] == 0xAC) - { - M2M_DBG("Successfully sent the command\n"); - strUart.u16Sz = rsz; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - strUart.u16Sz = rsz; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - } - } - else - { - M2M_ERR("failed to send cfg bytes\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - /*TODO: this should be the way we read the register since the cortus is little endian*/ - /**pu32RetVal = b[0] | ((uint32)b[1] << 8) | ((uint32)b[2] << 16) | ((uint32)b[3] << 24);*/ - - *pu32RetVal = ((uint32)b[0] << 24) | ((uint32)b[1] << 16) | ((uint32)b[2] << 8) | b[3]; - - return s8Ret; -} - -/* -* @fn nm_uart_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -* @author Dina El Sissy -* @date 13 AUG 2012 -* @version 1.0 -*/ -uint32 nm_uart_read_reg(uint32 u32Addr) -{ - uint32 val; - nm_uart_read_reg_with_ret(u32Addr , &val); - return val; -} - -/* -* @fn nm_uart_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Dina El Sissy -* @date 13 AUG 2012 -* @version 1.0 -*/ -sint8 nm_uart_write_reg(uint32 u32Addr, uint32 u32Val) -{ - tstrNmUartDefault strUart; - sint8 s8Ret = M2M_SUCCESS; - uint8 b[HDR_SZ+1]; - - /*write reg*/ - b[0] = 0xa5; - b[1] = 1; - b[2] = 0; - b[3] = 0; - b[4] = 0; - b[5] = (uint8)(u32Addr & 0x000000ff); - b[6] = (uint8)((u32Addr & 0x0000ff00)>>8); - b[7] = (uint8)((u32Addr & 0x00ff0000)>>16); - b[8] = (uint8)((u32Addr & 0xff000000)>>24); - b[9] = (uint8)(u32Val & 0x000000ff); - b[10] = (uint8)((u32Val & 0x0000ff00)>>8); - b[11] = (uint8)((u32Val & 0x00ff0000)>>16); - b[12] = (uint8)((u32Val & 0xff000000)>>24); - - b[2] = get_cs(&b[1],HDR_SZ); - - get_cs(&b[1],HDR_SZ); - - strUart.pu8Buf = b; - strUart.u16Sz = sizeof(b); - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - else - { - if(!nm_bus_get_chip_type()) - { - //check for the ack from the SAMD21 for the packet reception. - strUart.u16Sz = 1; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - if(b[0] == 0xAC) - { - M2M_DBG("Successfully sent the reg write command\n"); - } - else - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - } - - return s8Ret; -} - - -/** -* @fn nm_uart_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u16Sz -* Number of bytes to read. The buffer size must be >= u16Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Dina El Sissy -* @date 13 AUG 2012 -* @version 1.0 -*/ -sint8 nm_uart_read_block(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz) -{ - tstrNmUartDefault strUart; - sint8 s8Ret = M2M_SUCCESS; - uint8 au8Buf[HDR_SZ+1]; - - au8Buf[0] = 0xa5; - au8Buf[1] = 2; - au8Buf[2] = 0; - au8Buf[3] = (uint8)(u16Sz & 0x00ff); - au8Buf[4] = (uint8)((u16Sz & 0xff00)>>8); - au8Buf[5] = (uint8)(u32Addr & 0x000000ff); - au8Buf[6] = (uint8)((u32Addr & 0x0000ff00)>>8); - au8Buf[7] = (uint8)((u32Addr & 0x00ff0000)>>16); - au8Buf[8] = (uint8)((u32Addr & 0xff000000)>>24); - au8Buf[9] = 0; - au8Buf[10] = 0; - au8Buf[11] = 0; - au8Buf[12] = 0; - - au8Buf[2] = get_cs(&au8Buf[1],HDR_SZ); - - strUart.pu8Buf = au8Buf; - strUart.u16Sz = sizeof(au8Buf); - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - else - { - if(!nm_bus_get_chip_type()) - { - //check for the ack from the SAMD21 for the packet reception. - strUart.u16Sz = 1; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - if(au8Buf[0] == 0xAC) - { - M2M_DBG("Successfully sent the block read command\n"); - strUart.pu8Buf = pu8Buf; - strUart.u16Sz = u16Sz; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - M2M_ERR("read error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - M2M_ERR("write error (Error sending the block read command)\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - strUart.pu8Buf = pu8Buf; - strUart.u16Sz = u16Sz; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - M2M_ERR("read error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - } - - return s8Ret; -} - -/** -* @fn nm_uart_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u16Sz -* Number of bytes to write. The buffer size must be >= u16Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Dina El Sissy -* @date 13 AUG 2012 -* @version 1.0 -*/ -sint8 nm_uart_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) -{ - tstrNmUartDefault strUart; - sint8 s8Ret = M2M_SUCCESS; - static uint8 au8Buf[HDR_SZ+1]; - - au8Buf[0] = 0xa5; - au8Buf[1] = 3; - au8Buf[2] = 0; - au8Buf[3] = (uint8)(u16Sz & 0x00ff); - au8Buf[4] = (uint8)((u16Sz & 0xff00)>>8); - au8Buf[5] = (uint8)(u32Addr & 0x000000ff); - au8Buf[6] = (uint8)((u32Addr & 0x0000ff00)>>8); - au8Buf[7] = (uint8)((u32Addr & 0x00ff0000)>>16); - au8Buf[8] = (uint8)((u32Addr & 0xff000000)>>24); - au8Buf[9] = 0; - au8Buf[10] = 0; - au8Buf[11] = 0; - au8Buf[12] = 0; - - au8Buf[2] = get_cs(&au8Buf[1],HDR_SZ); - - strUart.pu8Buf = au8Buf; - strUart.u16Sz = sizeof(au8Buf); - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - else - { - if(!nm_bus_get_chip_type()) - { - //check for the ack from the SAMD21 for the packet reception. - strUart.u16Sz = 1; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - if(au8Buf[0] == 0xAC) - { - M2M_DBG("Successfully sent the block Write command\n"); - strUart.pu8Buf = puBuf; - strUart.u16Sz = u16Sz; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - else - { - //check for the ack from the SAMD21 for the payload reception. - strUart.pu8Buf = au8Buf; - strUart.u16Sz = 1; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - if(au8Buf[0] == 0xAC) - { - M2M_DBG("Successfully sent the data payload\n"); - } - else - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - } - else - { - M2M_ERR("write error (Error sending the block write command)\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - strUart.pu8Buf = puBuf; - strUart.u16Sz = u16Sz; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - } - return s8Ret; -} - -/** -* @fn nm_uart_reconfigure -* @brief Reconfigures the UART interface -* @param [in] ptr -* Pointer to a DWORD containing baudrate at this moment. -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Viswanathan Murugesan -* @date 22 OCT 2014 -* @version 1.0 -*/ -sint8 nm_uart_reconfigure(void *ptr) -{ - tstrNmUartDefault strUart; - sint8 s8Ret = M2M_SUCCESS; - uint8 b[HDR_SZ+1]; - - /*write reg*/ - b[0] = 0xa5; - b[1] = 5; - b[2] = 0; - b[3] = 0; - b[4] = 0; - b[5] = 0; - b[6] = 0; - b[7] = 0; - b[8] = 0; - b[9] = (uint8)((*(unsigned long *)ptr) & 0x000000ff); - b[10] = (uint8)(((*(unsigned long *)ptr) & 0x0000ff00)>>8); - b[11] = (uint8)(((*(unsigned long *)ptr) & 0x00ff0000)>>16); - b[12] = (uint8)(((*(unsigned long *)ptr) & 0xff000000)>>24); - - b[2] = get_cs(&b[1],HDR_SZ); - - get_cs(&b[1],HDR_SZ); - - strUart.pu8Buf = b; - strUart.u16Sz = sizeof(b); - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - else - { - if(!nm_bus_get_chip_type()) - { - //check for the ack from the SAMD21 for the packet reception. - strUart.u16Sz = 1; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - if(b[0] == 0xAC) - { - M2M_DBG("Successfully sent the UART reconfigure command\n"); - } - else - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - } - - return s8Ret; -} -#endif -/* EOF */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmuart.h b/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmuart.h deleted file mode 100644 index 8f07d39..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/driver/source/nmuart.h +++ /dev/null @@ -1,118 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 UART protocol bus APIs implementation. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NMUART_H_ -#define _NMUART_H_ - -#include "common/include/nm_common.h" - -/* -* @fn nm_uart_sync_cmd -* @brief Check COM Port -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_uart_sync_cmd(void); -/** -* @fn nm_uart_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -*/ -uint32 nm_uart_read_reg(uint32 u32Addr); - -/** -* @fn nm_uart_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_uart_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); - -/** -* @fn nm_uart_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_uart_write_reg(uint32 u32Addr, uint32 u32Val); - -/** -* @fn nm_uart_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u16Sz -* Number of bytes to read. The buffer size must be >= u16Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_uart_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); - -/** -* @fn nm_uart_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u16Sz -* Number of bytes to write. The buffer size must be >= u16Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_uart_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); - -/** -* @fn nm_uart_reconfigure -* @brief Reconfigures the UART interface -* @param [in] ptr -* Pointer to a DWORD containing baudrate at this moment. -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_uart_reconfigure(void *ptr); -#endif /* _NMI2C_H_ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h b/feather_sensor_transmit/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h deleted file mode 100644 index 933ad67..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h +++ /dev/null @@ -1,461 +0,0 @@ -/** - * - * \file - * - * \brief BSD compatible socket interface internal types. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -#ifndef __M2M_SOCKET_HOST_IF_H__ -#define __M2M_SOCKET_HOST_IF_H__ - - -#ifdef __cplusplus -extern "C" { -#endif - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#ifndef _BOOT_ -#ifndef _FIRMWARE_ -#include "socket/include/socket.h" -#else -#include "m2m_types.h" -#endif -#endif - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/* - * HOSTNAME_MAX_SIZE is defined here and also in host_drv/socket/include/socket.h - * The two definitions must match. -*/ -#ifdef _FIRMWARE_ -#define HOSTNAME_MAX_SIZE (64) -#endif - -#define SSL_MAX_OPT_LEN HOSTNAME_MAX_SIZE - - - -#define SOCKET_CMD_INVALID 0x00 -/*!< - Invlaid Socket command value. -*/ - - -#define SOCKET_CMD_BIND 0x41 -/*!< - Socket Binding command value. -*/ - - -#define SOCKET_CMD_LISTEN 0x42 -/*!< - Socket Listening command value. -*/ - - -#define SOCKET_CMD_ACCEPT 0x43 -/*!< - Socket Accepting command value. -*/ - - -#define SOCKET_CMD_CONNECT 0x44 -/*!< - Socket Connecting command value. -*/ - - -#define SOCKET_CMD_SEND 0x45 -/*!< - Socket send command value. -*/ - - -#define SOCKET_CMD_RECV 0x46 -/*!< - Socket Recieve command value. -*/ - - -#define SOCKET_CMD_SENDTO 0x47 -/*!< - Socket sendTo command value. -*/ - - -#define SOCKET_CMD_RECVFROM 0x48 -/*!< - Socket RecieveFrom command value. -*/ - - -#define SOCKET_CMD_CLOSE 0x49 -/*!< - Socket Close command value. -*/ - - -#define SOCKET_CMD_DNS_RESOLVE 0x4A -/*!< - Socket DNS Resolve command value. -*/ - - -#define SOCKET_CMD_SSL_CONNECT 0x4B -/*!< - SSL-Socket Connect command value. -*/ - - -#define SOCKET_CMD_SSL_SEND 0x4C -/*!< - SSL-Socket Send command value. -*/ - - -#define SOCKET_CMD_SSL_RECV 0x4D -/*!< - SSL-Socket Recieve command value. -*/ - - -#define SOCKET_CMD_SSL_CLOSE 0x4E -/*!< - SSL-Socket Close command value. -*/ - - -#define SOCKET_CMD_SET_SOCKET_OPTION 0x4F -/*!< - Set Socket Option command value. -*/ - - -#define SOCKET_CMD_SSL_CREATE 0x50 -/*!< -*/ - - -#define SOCKET_CMD_SSL_SET_SOCK_OPT 0x51 -/*!< -*/ - - -#define SOCKET_CMD_PING 0x52 -/*!< -*/ - - -#define SOCKET_CMD_SSL_SET_CS_LIST 0x53 -/*!< - Recommend instead using @ref M2M_SSL_REQ_SET_CS_LIST and - associated response @ref M2M_SSL_RESP_SET_CS_LIST -*/ - - -#define SOCKET_CMD_SSL_BIND 0x54 -/*!< -*/ - - -#define SOCKET_CMD_SSL_EXP_CHECK 0x55 -/*!< -*/ - - - -#define PING_ERR_SUCCESS 0 -#define PING_ERR_DEST_UNREACH 1 -#define PING_ERR_TIMEOUT 2 - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -/*! -* @brief -*/ -typedef struct{ - uint16 u16Family; - uint16 u16Port; - uint32 u32IPAddr; -}tstrSockAddr; - - -typedef sint8 SOCKET; -typedef tstrSockAddr tstrUIPSockAddr; - - - -/*! -@struct \ - tstrDnsReply - -@brief - DNS Reply, contains hostName and HostIP. -*/ -typedef struct{ - char acHostName[HOSTNAME_MAX_SIZE]; - uint32 u32HostIP; -}tstrDnsReply; - - -/*! -@brief -*/ -typedef struct{ - tstrSockAddr strAddr; - SOCKET sock; - uint8 u8Void; - uint16 u16SessionID; -}tstrBindCmd; - - -/*! -@brief -*/ -typedef struct{ - SOCKET sock; - sint8 s8Status; - uint16 u16SessionID; -}tstrBindReply; - - -/*! -* @brief -*/ -typedef struct{ - SOCKET sock; - uint8 u8BackLog; - uint16 u16SessionID; -}tstrListenCmd; - - -/*! -@struct \ - tstrSocketRecvMsg - -@brief Socket recv status. - - It is passed to the APPSocketEventHandler with SOCKET_MSG_RECV or SOCKET_MSG_RECVFROM message type - in a response to a user call to the recv or recvfrom. - If the received data from the remote peer is larger than the USER Buffer size (given at recv call), the data is - delivered to the user in a number of consecutive chunks according to the USER Buffer size. -*/ -typedef struct{ - SOCKET sock; - sint8 s8Status; - uint16 u16SessionID; -}tstrListenReply; - - -/*! -* @brief -*/ -typedef struct{ - tstrSockAddr strAddr; - SOCKET sListenSock; - SOCKET sConnectedSock; - uint16 u16AppDataOffset; - /*!< - In further packet send requests the host interface should put the user application - data at this offset in the allocated shared data packet. - */ -}tstrAcceptReply; - - -/*! -* @brief -*/ -typedef struct{ - tstrSockAddr strAddr; - SOCKET sock; - uint8 u8SslFlags; - uint16 u16SessionID; -}tstrConnectCmd; - - -/*! -@struct \ - tstrConnectReply - -@brief - Connect Reply, contains sock number and error value -*/ -typedef struct{ - SOCKET sock; - sint8 s8Error; - uint16 u16AppDataOffset; - /*!< - In further packet send requests the host interface should put the user application - data at this offset in the allocated shared data packet. - */ -}tstrConnectReply; - - -/*! -@brief -*/ -typedef struct{ - SOCKET sock; - uint8 u8Void; - uint16 u16DataSize; - tstrSockAddr strAddr; - uint16 u16SessionID; - uint16 u16Void; -}tstrSendCmd; - - -/*! -@struct \ - tstrSendReply - -@brief - Send Reply, contains socket number and number of sent bytes. -*/ -typedef struct{ - SOCKET sock; - uint8 u8Void; - sint16 s16SentBytes; - uint16 u16SessionID; - uint16 u16Void; -}tstrSendReply; - - -/*! -* @brief -*/ -typedef struct{ - uint32 u32Timeoutmsec; - SOCKET sock; - uint8 u8Void; - uint16 u16SessionID; -}tstrRecvCmd; - - -/*! -@struct -@brief -*/ -typedef struct{ - tstrSockAddr strRemoteAddr; - sint16 s16RecvStatus; - uint16 u16DataOffset; - SOCKET sock; - uint8 u8Void; - uint16 u16SessionID; -}tstrRecvReply; - - -/*! -* @brief -*/ -typedef struct{ - uint32 u32OptionValue; - SOCKET sock; - uint8 u8Option; - uint16 u16SessionID; -}tstrSetSocketOptCmd; - - -typedef struct{ - SOCKET sslSock; - uint8 __PAD24__[3]; -}tstrSSLSocketCreateCmd; - - -/*! -* @brief -*/ -typedef struct{ - SOCKET sock; - uint8 u8Option; - uint16 u16SessionID; - uint32 u32OptLen; - uint8 au8OptVal[SSL_MAX_OPT_LEN]; -}tstrSSLSetSockOptCmd; - - -/*! -*/ -typedef struct{ - uint32 u32DestIPAddr; - uint32 u32CmdPrivate; - uint16 u16PingCount; - uint8 u8TTL; - uint8 __PAD8__; -}tstrPingCmd; - - -typedef struct{ - uint32 u32IPAddr; - uint32 u32CmdPrivate; - uint32 u32RTT; - uint16 u16Success; - uint16 u16Fail; - uint8 u8ErrorCode; - uint8 __PAD24__[3]; -}tstrPingReply; - - -/*! -@struct\ - tstrSslCertExpSettings - -@brief SSL Certificate Expiry Validation Settings - -@sa tenuSslCertExpSettings -*/ -typedef struct{ - uint32 u32CertExpValidationOpt; - /*!< - See @tenuSslCertExpSettings for possible values. - */ -}tstrSslCertExpSettings; - - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __M2M_SOCKET_HOST_IF_H__ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/socket/include/socket.h b/feather_sensor_transmit/libraries/WiFi101/src/socket/include/socket.h deleted file mode 100644 index 837959a..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/socket/include/socket.h +++ /dev/null @@ -1,2065 +0,0 @@ -/** - * - * \file - * - * \brief WINC BSD compatible Socket Interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef __SOCKET_H__ -#define __SOCKET_H__ - -#ifdef __cplusplus -extern "C" { -#endif - -/** \defgroup SocketHeader Socket - * BSD compatible socket interface beftween the host layer and the network - * protocol stacks in the firmware. - * These functions are used by the host application to send or receive - * packets and to do other socket operations. - */ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "common/include/nm_common.h" -#include "driver/include/m2m_types.h" - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/** - * @defgroup SocketDefines Defines - * @ingroup SocketHeader - */ - -/** @defgroup IPDefines TCP/IP Defines - * @ingroup SocketDefines - * The following list of macros are used to define constants used throughout the socket layer. - * @{ - */ - -/* - * HOSTNAME_MAX_SIZE is defined here and also in host_drv/socket/include/m2m_socket_host_if.h - * The two definitions must match. -*/ -#define HOSTNAME_MAX_SIZE 64 -/*!< - Maximum allowed size for a host domain name passed to the function gethostbyname @ref gethostbyname. - command value. Used with the setsockopt function. - -*/ - -#define SOCKET_BUFFER_MAX_LENGTH 1400 -/*!< - Maximum allowed size for a socket data buffer. Used with @ref send socket - function to ensure that the buffer sent is within the allowed range. -*/ - -#define AF_INET 2 -/*!< - The AF_INET is the address family used for IPv4. An IPv4 transport address is specified with the @ref sockaddr_in structure. - (It is the only supported type for the current implementation.) -*/ - - -#define SOCK_STREAM 1 -/*!< - One of the IPv4 supported socket types for reliable connection-oriented stream connection. - Passed to the @ref socket function for the socket creation operation. -*/ - -#define SOCK_DGRAM 2 -/*!< - One of the IPv4 supported socket types for unreliable connectionless datagram connection. - Passed to the @ref socket function for the socket creation operation. -*/ - - -#define SOCKET_FLAGS_SSL 0x01 -/*!< - This flag shall be passed to the socket API for SSL session. -*/ - -#define TCP_SOCK_MAX (7) -/*!< - Maximum number of simultaneous TCP sockets. -*/ - -#define UDP_SOCK_MAX 4 -/*!< - Maximum number of simultaneous UDP sockets. -*/ - -#define MAX_SOCKET (TCP_SOCK_MAX + UDP_SOCK_MAX) -/*!< - Maximum number of Sockets. -*/ - -#define SOL_SOCKET 1 -/*!< - Socket option. - Used with the @ref setsockopt function -*/ - -#define SOL_SSL_SOCKET 2 -/*!< - SSL Socket option level. - Used with the @ref setsockopt function -*/ - -#define SO_SET_UDP_SEND_CALLBACK 0x00 -/*!< - Socket option used by the application to enable/disable - the use of UDP send callbacks. - Used with the @ref setsockopt function. -*/ - -#define IP_ADD_MEMBERSHIP 0x01 -/*!< - Set Socket Option Add Membership command value (to join a multicast group). - Used with the @ref setsockopt function. -*/ - - -#define IP_DROP_MEMBERSHIP 0x02 -/*!< - Set Socket Option Drop Membership command value (to leave a multicast group). - Used with the @ref setsockopt function. -*/ - //@} - - - -/** - * @defgroup TLSDefines TLS Defines - * @ingroup SocketDefines - */ - - - -/** @defgroup SSLSocketOptions TLS Socket Options - * @ingroup TLSDefines - * The following list of macros are used to define SSL Socket options. - * @{ - * @sa setsockopt - */ - -#define SO_SSL_BYPASS_X509_VERIF 0x01 -/*!< - Allow an opened SSL socket to bypass the X509 certificate - verification process. - It is highly required NOT to use this socket option in production - software applications. It is supported for debugging and testing - purposes. - The option value should be casted to int type and it is handled - as a boolean flag. -*/ - - -#define SO_SSL_SNI 0x02 -/*!< - Set the Server Name Indicator (SNI) for an SSL socket. The - SNI is a NULL terminated string containing the server name - associated with the connection. It must not exceed the size - of HOSTNAME_MAX_SIZE. -*/ - - -#define SO_SSL_ENABLE_SESSION_CACHING 0x03 -/*!< - This option allow the TLS to cache the session information for fast - TLS session establishment in future connections using the - TLS Protocol session resume features. -*/ - - -#define SO_SSL_ENABLE_SNI_VALIDATION 0x04 -/*!< - Enable SNI validation against the server's certificate subject - common name. If there is no SNI provided (via the SO_SSL_SNI - option), setting this option does nothing. -*/ - - -//@} - - - -/** @defgroup LegacySSLCipherSuite Legacy names for TLS Cipher Suite IDs - * @ingroup TLSDefines - * The following list of macros MUST NOT be used. Instead use the new names under SSLCipherSuiteID - * @sa sslSetActiveCipherSuites - * @{ - */ - -#define SSL_ENABLE_RSA_SHA_SUITES 0x01 -/*!< - Enable RSA Hmac_SHA based Cipher suites. For example, - TLS_RSA_WITH_AES_128_CBC_SHA -*/ - - -#define SSL_ENABLE_RSA_SHA256_SUITES 0x02 -/*!< - Enable RSA Hmac_SHA256 based Cipher suites. For example, - TLS_RSA_WITH_AES_128_CBC_SHA256 -*/ - - -#define SSL_ENABLE_DHE_SHA_SUITES 0x04 -/*!< - Enable DHE Hmac_SHA based Cipher suites. For example, - TLS_DHE_RSA_WITH_AES_128_CBC_SHA -*/ - - -#define SSL_ENABLE_DHE_SHA256_SUITES 0x08 -/*!< - Enable DHE Hmac_SHA256 based Cipher suites. For example, - TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 -*/ - - -#define SSL_ENABLE_RSA_GCM_SUITES 0x10 -/*!< - Enable RSA AEAD based Cipher suites. For example, - TLS_RSA_WITH_AES_128_GCM_SHA256 -*/ - - -#define SSL_ENABLE_DHE_GCM_SUITES 0x20 -/*!< - Enable DHE AEAD based Cipher suites. For example, - TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 -*/ - - -#define SSL_ENABLE_ALL_SUITES 0x0000003F -/*!< - Enable all possible supported cipher suites. -*/ - -//@} - - - -/** @defgroup SSLCipherSuiteID TLS Cipher Suite IDs - * @ingroup TLSDefines - * The following list of macros defined the list of supported TLS Cipher suites. - * Each MACRO defines a single Cipher suite. - * @sa m2m_ssl_set_active_ciphersuites - * @{ - */ - -#define SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA NBIT0 -#define SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 NBIT1 -#define SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA NBIT2 -#define SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 NBIT3 -#define SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 NBIT4 -#define SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 NBIT5 -#define SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA NBIT6 -#define SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 NBIT7 -#define SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA NBIT8 -#define SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 NBIT9 -#define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA NBIT10 -#define SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA NBIT11 -#define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 NBIT12 -#define SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 NBIT13 -#define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 NBIT14 -#define SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 NBIT15 - - - -#define SSL_ECC_ONLY_CIPHERS \ -(\ - SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 \ -) -/*!< - All ciphers that use ECC crypto only. This execuldes ciphers that use RSA. They use ECDSA instead. - These ciphers are turned off by default at startup. - The application may enable them if it has an ECC math engine (like ATECC508). -*/ -#define SSL_ECC_ALL_CIPHERS \ -(\ - SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA | \ - SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 | \ - SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 \ -) -/*!< - All supported ECC Ciphers including those ciphers that depend on RSA and ECC. - These ciphers are turned off by default at startup. - The application may enable them if it has an ECC math engine (like ATECC508). -*/ - -#define SSL_NON_ECC_CIPHERS_AES_128 \ -(\ - SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA | \ - SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA | \ - SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 | \ - SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 \ -) -/*!< - All supported AES-128 Ciphers (ECC ciphers are not counted). This is the default active group after startup. -*/ - - -#define SSL_ECC_CIPHERS_AES_256 \ -(\ - SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA \ -) -/*!< - ECC AES-256 supported ciphers. -*/ - - -#define SSL_NON_ECC_CIPHERS_AES_256 \ -(\ - SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA | \ - SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 | \ - SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA | \ - SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 \ -) -/*!< - AES-256 Ciphers. - This group is disabled by default at startup because the WINC1500 HW Accelerator - supports only AES-128. If the application needs to force AES-256 cipher support, - it could enable them (or any of them) explicitly by calling sslSetActiveCipherSuites. -*/ - - -#define SSL_CIPHER_ALL \ -(\ - SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA | \ - SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA | \ - SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 | \ - SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 | \ - SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA | \ - SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 | \ - SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA | \ - SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 | \ - SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA | \ - SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 | \ - SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 | \ - SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA \ -) -/*!< - Turn On All TLS Ciphers. -*/ - - - //@} - - - - -/************** -Socket Errors -**************/ -/**@defgroup SocketErrorCode Error Codes - * @ingroup SocketHeader - * The following list of macros are used to define the possible error codes returned as a result of a call to a socket function. - * Errors are listed in numerical order with the error macro name. - * @{ - */ -#define SOCK_ERR_NO_ERROR 0 -/*!< - Successful socket operation -*/ - - -#define SOCK_ERR_INVALID_ADDRESS -1 -/*!< - Socket address is invalid. The socket operation cannot be completed successfully without specifying a specific address - For example: bind is called without specifying a port number -*/ - - -#define SOCK_ERR_ADDR_ALREADY_IN_USE -2 -/*!< - Socket operation cannot bind on the given address. With socket operations, only one IP address per socket is permitted. - Any attempt for a new socket to bind with an IP address already bound to another open socket, - will return the following error code. States that bind operation failed. -*/ - - -#define SOCK_ERR_MAX_TCP_SOCK -3 -/*!< - Exceeded the maximum number of TCP sockets. A maximum number of TCP sockets opened simultaneously is defined through TCP_SOCK_MAX. - It is not permitted to exceed that number at socket creation. Identifies that @ref socket operation failed. -*/ - - -#define SOCK_ERR_MAX_UDP_SOCK -4 -/*!< - Exceeded the maximum number of UDP sockets. A maximum number of UDP sockets opened simultaneously is defined through UDP_SOCK_MAX. - It is not permitted to exceed that number at socket creation. Identifies that @ref socket operation failed -*/ - - -#define SOCK_ERR_INVALID_ARG -6 -/*!< - An invalid argument is passed to a function. -*/ - - -#define SOCK_ERR_MAX_LISTEN_SOCK -7 -/*!< - Exceeded the maximum number of TCP passive listening sockets. - Identifies Identifies that @ref listen operation failed. -*/ - - -#define SOCK_ERR_INVALID -9 -/*!< - The requested socket operation is not valid in the - current socket state. - For example: @ref accept is called on a TCP socket before @ref bind or @ref listen. -*/ - - -#define SOCK_ERR_ADDR_IS_REQUIRED -11 -/*!< - Destination address is required. Failure to provide the socket address required for the socket operation to be completed. - It is generated as an error to the @ref sendto function when the address required to send the data to is not known. -*/ - - -#define SOCK_ERR_CONN_ABORTED -12 -/*!< - The socket is closed by the peer. The local socket is - closed also. -*/ - - -#define SOCK_ERR_TIMEOUT -13 -/*!< - The socket pending operation has Timedout. -*/ - - -#define SOCK_ERR_BUFFER_FULL -14 -/*!< - No buffer space available to be used for the requested socket operation. -*/ - -#ifdef _NM_BSP_BIG_END - -#define _htonl(m) (m) -#define _htons(A) (A) - -#else - -#define _htonl(m) \ - (uint32)(((uint32)(m << 24)) | ((uint32)((m & 0x0000FF00) << 8)) | ((uint32)((m & 0x00FF0000) >> 8)) | ((uint32)(m >> 24))) -/*!< - Convert a 4-byte integer from the host representation to the Network byte order representation. -*/ - - -#define _htons(A) (uint16)((((uint16) (A)) << 8) | (((uint16) (A)) >> 8)) -/*!< - Convert a 2-byte integer (short) from the host representation to the Network byte order representation. -*/ - - -#endif - - -#define _ntohl _htonl -/*!< - Convert a 4-byte integer from the Network byte order representation to the host representation . -*/ - - -#define _ntohs _htons -/*!< - Convert a 2-byte integer from the Network byte order representation to the host representation . -*/ - //@} - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/** @defgroup SocketEnums DataTypes - * @ingroup SocketHeader - * Specific Enumeration-typedefs used for socket operations - * @{ */ - -/*! -@typedef \ - SOCKET - -@brief - Definition for socket handler data type. - Socket ID,used with all socket operations to uniquely identify the socket handler. - Such an ID is uniquely assigned at socket creation when calling @ref socket operation. -*/ -typedef sint8 SOCKET; - - - -/*! -@struct \ - in_addr - -@brief - IPv4 address representation. - - This structure is used as a placeholder for IPV4 address in other structures. -@see - sockaddr_in -*/ -typedef struct{ - uint32 s_addr; - /*!< - Network Byte Order representation of the IPv4 address. For example, - the address "192.168.0.10" is represented as 0x0A00A8C0. - */ -}in_addr; - - -/*! -@struct \ - sockaddr - -@brief - Generic socket address structure. - -@see - sockaddr_in -*/ -struct sockaddr{ - uint16 sa_family; - /*!< -Socket address family. - */ - uint8 sa_data[14]; - /*!< - Maximum size of all the different socket address structures. - */ -}; - - -/*! -@struct \ - sockaddr_in - -@brief - Socket address structure for IPV4 addresses. Used to specify socket address information to which to connect to. - Can be cast to @ref sockaddr structure. -*/ -struct sockaddr_in{ - uint16 sin_family; - /*!< - Specifies the address family(AF). - Members of AF_INET address family are IPv4 addresses. - Hence,the only supported value for this is AF_INET. - */ - uint16 sin_port; - /*!< - Port number of the socket. - Network sockets are identified by a pair of IP addresses and port number. - It must be set in the Network Byte Order format , @ref _htons (e.g. _htons(80)). - Can NOT have zero value. - */ - in_addr sin_addr; - /*!< - IP Address of the socket. - The IP address is of type @ref in_addr structure. - Can be set to "0" to accept any IP address for server operation. non zero otherwise. - */ - uint8 sin_zero[8]; - /*!< - Padding to make structure the same size as @ref sockaddr. - */ -}; - //@} -/**@defgroup AsyncCalback Asynchronous Events - * @ingroup SocketEnums - * Specific Enumeration used for asynchronous operations - * @{ */ -/*! -@enum \ - tenuSocketCallbackMsgType - -@brief - Asynchronous APIs, make use of callback functions, in-order to return back the results once the corresponding socket operation is completed. - Hence resuming the normal execution of the application code while the socket operation returns the results. - Callback functions expect event messages to be passed in, in-order to identify the operation they're returning the results for. - The following enum identifies the type of events that are received in the callback function. - - Application Use: - In order for application developers to handle the pending events from the network controller through the callback functions. - A function call must be made to the function @ref m2m_wifi_handle_events at least once for each socket operation. - -@see - bind - listen - accept - connect - send - recv - -*/ -typedef enum{ - SOCKET_MSG_BIND = 1, - /*!< - Bind socket event. - */ - SOCKET_MSG_LISTEN, - /*!< - Listen socket event. - */ - SOCKET_MSG_DNS_RESOLVE, - /*!< - DNS Resolution event. - */ - SOCKET_MSG_ACCEPT, - /*!< - Accept socket event. - */ - SOCKET_MSG_CONNECT, - /*!< - Connect socket event. - */ - SOCKET_MSG_RECV, - /*!< - Receive socket event. - */ - SOCKET_MSG_SEND, - /*!< - Send socket event. - */ - SOCKET_MSG_SENDTO, - /*!< - sendto socket event. - */ - SOCKET_MSG_RECVFROM - /*!< - Recvfrom socket event. - */ -}tenuSocketCallbackMsgType; - - -/*! -@struct \ - tstrSocketBindMsg - -@brief Socket bind status. - - An asynchronous call to the @ref bind socket operation, returns information through this structure in response. - This structure together with the event @ref SOCKET_MSG_BIND are passed in paramters to the callback function. -@see - bind - -*/ -typedef struct{ - sint8 status; - /*!< - The result of the bind operation. - Holding a value of ZERO for a successful bind or otherwise a negative - error code corresponding to the type of error. - */ -}tstrSocketBindMsg; - - -/*! -@struct \ - tstrSocketListenMsg - -@brief Socket listen status. - - Socket listen information is returned through this structure in response to the asynchronous call to the @ref listen function. - This structure together with the event @ref SOCKET_MSG_LISTEN are passed-in parameters to the callback function. -@see - listen -*/ -typedef struct{ - sint8 status; - /*!< - Holding a value of ZERO for a successful listen or otherwise a negative - error code corresponding to the type of error. - */ -}tstrSocketListenMsg; - - - -/*! -@struct \ - tstrSocketAcceptMsg - -@brief Socket accept status. - - Socket accept information is returned through this structure in response to the asynchronous call to the @ref accept function. - This structure together with the event @ref SOCKET_MSG_ACCEPT are passed-in parameters to the callback function. -*/ -typedef struct{ - SOCKET sock; - /*!< - On a successful @ref accept operation, the return information is the socket ID for the accepted connection with the remote peer. - Otherwise a negative error code is returned to indicate failure of the accept operation. - */ - struct sockaddr_in strAddr; - /*!< - Socket address structure for the remote peer. - */ -}tstrSocketAcceptMsg; - - -/*! -@struct \ - tstrSocketConnectMsg - -@brief Socket connect status. - - Socket connect information is returned through this structure in response to the asynchronous call to the @ref connect socket function. - This structure together with the event @ref SOCKET_MSG_CONNECT are passed-in parameters to the callback function. -*/ -typedef struct{ - SOCKET sock; - /*!< - Socket ID referring to the socket passed to the connect function call. - */ - sint8 s8Error; - /*!< - Connect error code. - Holding a value of ZERO for a successful connect or otherwise a negative - error code corresponding to the type of error. - */ -}tstrSocketConnectMsg; - - -/*! -@struct \ - tstrSocketRecvMsg - -@brief Socket recv status. - - Socket receive information is returned through this structure in response to the asynchronous call to the recv or recvfrom socket functions. - This structure together with the events @ref SOCKET_MSG_RECV or @ref SOCKET_MSG_RECVFROM are passed-in parameters to the callback function. -@remark - In case the received data from the remote peer is larger than the USER buffer size defined during the asynchronous call to the @ref recv function, the data is - delivered to the user in a number of consecutive chunks according to the USER Buffer size. - a negative or zero buffer size indicates an error with the following code: - @ref SOCK_ERR_NO_ERROR : Socket connection closed - @ref SOCK_ERR_CONN_ABORTED : Socket connection aborted - @SOCK_ERR_TIMEOUT : Socket receive timed out -*/ -typedef struct{ - uint8 *pu8Buffer; - /*!< - Pointer to the USER buffer (passed to @ref recv and @ref recvfrom function) containing the received data chunk. - */ - sint16 s16BufferSize; - /*!< - The received data chunk size. - Holds a negative value if there is a receive error or ZERO on success upon reception of close socket message. - */ - uint16 u16RemainingSize; - /*!< - The number of bytes remaining in the current @ref recv operation. - */ - struct sockaddr_in strRemoteAddr; - /*!< - Socket address structure for the remote peer. It is valid for @ref SOCKET_MSG_RECVFROM event. - */ -}tstrSocketRecvMsg; - - -/*! -@typedef \ - tpfAppSocketCb - -@brief - The main socket application callback function. Applications register their main socket application callback through this function by calling @ref registerSocketCallback. - In response to events received, the following callback function is called to handle the corresponding asynchronous function called. Example: @ref bind, @ref connect,...etc. - -@param [in] sock - Socket ID for the callback. - - The socket callback function is called whenever a new event is recived in response - to socket operations. - -@param [in] u8Msg - Socket event type. Possible values are: - - @ref SOCKET_MSG_BIND - - @ref SOCKET_MSG_LISTEN - - @ref SOCKET_MSG_ACCEPT - - @ref SOCKET_MSG_CONNECT - - @ref SOCKET_MSG_RECV - - @ref SOCKET_MSG_SEND - - @ref SOCKET_MSG_SENDTO - - @ref SOCKET_MSG_RECVFROM - -@param [in] pvMsg - Pointer to message structure. Existing types are: - - tstrSocketBindMsg - - tstrSocketListenMsg - - tstrSocketAcceptMsg - - tstrSocketConnectMsg - - tstrSocketRecvMsg - -@see - tenuSocketCallbackMsgType - tstrSocketRecvMsg - tstrSocketConnectMsg - tstrSocketAcceptMsg - tstrSocketListenMsg - tstrSocketBindMsg -*/ -typedef void (*tpfAppSocketCb) (SOCKET sock, uint8 u8Msg, void * pvMsg); - - -/*! -@typedef \ - tpfAppResolveCb - -@brief - DNS resolution callback function. - Applications requiring DNS resolution should register their callback through this function by calling @ref registerSocketCallback. - The following callback is triggered in response to asynchronous call to the @ref gethostbyname function (DNS Resolution callback). - -@param [in] pu8DomainName - Domain name of the host. - -@param [in] u32ServerIP - Server IPv4 address encoded in NW byte order format. If it is Zero, then the DNS resolution failed. -*/ -typedef void (*tpfAppResolveCb) (uint8* pu8DomainName, uint32 u32ServerIP); - -/*! -@typedef \ - tpfPingCb - -@brief PING Callback - - The function delivers the ping statistics for the sent ping triggered by calling - m2m_ping_req. - -@param [in] u32IPAddr - Destination IP. - -@param [in] u32RTT - Round Trip Time. - -@param [in] u8ErrorCode - Ping error code. It may be one of: - - PING_ERR_SUCCESS - - PING_ERR_DEST_UNREACH - - PING_ERR_TIMEOUT -*/ -typedef void (*tpfPingCb)(uint32 u32IPAddr, uint32 u32RTT, uint8 u8ErrorCode); - - /**@}*/ -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/** \defgroup SocketAPI Function - * @ingroup SocketHeader - */ - -/** @defgroup SocketInitalizationFn socketInit - * @ingroup SocketAPI - * The function performs the necessary initializations for the socket library through the following steps: - - A check made by the global variable gbSocketInit, ensuring that initialization for sockets is performed only once, - in-order to prevent reseting the socket instances already created in the global socket array (gastrSockets). - - Zero initializations to the global socket array (gastrSockets), which holds the list of TCP sockets. - - Registers the socket (Host Interface)hif callback function through the call to the hif_register_cb function. - This facilitates handling all of the socket related functions received through interrupts from the firmware. - - */ - /**@{*/ -/*! -@fn \ - NMI_API void socketInit(void); - -@param [in] void - -@return void - -@remarks - This initialization function must be invoked before any socket operation is performed. - No error codes from this initialization function since the socket array is statically allocated based in the maximum number of - sockets @ref MAX_SOCKET based on the systems capability. -\section Example -This example demonstrates the use of the socketinit for socket initialization for an mqtt chat application. - \code - tstrWifiInitParam param; - int8_t ret; - char topic[strlen(MAIN_CHAT_TOPIC) + MAIN_CHAT_USER_NAME_SIZE + 1]; - - //Initialize the board. - system_init(); - - //Initialize the UART console. - configure_console(); - - // Initialize the BSP. - nm_bsp_init(); - - ---------- - - // Initialize socket interface. - socketInit(); - registerSocketCallback(socket_event_handler, socket_resolve_handler); - - // Connect to router. - m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), - MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); - -\endcode -*/ -NMI_API void socketInit(void); - - -/*! -@fn \ - NMI_API void socketDeinit(void); - -@brief Socket Layer De-initialization - - The function performs the necessary cleanup for the socket library static data - It must be invoked as the last any socket operation is performed on any active sockets. -*/ -NMI_API void socketDeinit(void); - - -/** @} */ -/** @defgroup SocketCallbackFn registerSocketCallback - * @ingroup SocketAPI - Register two callback functions one for asynchronous socket events and the other one for DNS callback registering function. - The registered callback functions are used to retrieve information in response to the asynchronous socket functions called. - */ - /**@{*/ - - -/*! -@fn \ - NMI_API void registerSocketCallback(tpfAppSocketCb socket_cb, tpfAppResolveCb resolve_cb); - -@param [in] tpfAppSocketCb - Assignment of callback function to the global callback @ref tpfAppSocketCb gpfAppSocketCb. Delivers - socket messages to the host application. In response to the asynchronous function calls, such as @ref bind - @ref listen @ref accept @ref connect - -@param [in] tpfAppResolveCb - Assignment of callback function to the global callback @ref tpfAppResolveCb gpfAppResolveCb. - Used for DNS resolving functionalities. The DNS resolving technique is determined by the application - registering the callback. - NULL is assigned when, DNS resolution is not required. - -@return void -@remarks - If any of the socket functionalities is not to be used, NULL is passed in as a parameter. - It must be invoked after socketinit and before other socket layer operations. - -\section Example - This example demonstrates the use of the registerSocketCallback to register a socket callback function with DNS resolution CB set to null - for a simple UDP server example. - \code - tstrWifiInitParam param; - int8_t ret; - struct sockaddr_in addr; - - // Initialize the board - system_init(); - - //Initialize the UART console. - configure_console(); - - // Initialize the BSP. - nm_bsp_init(); - - // Initialize socket address structure. - addr.sin_family = AF_INET; - addr.sin_port = _htons(MAIN_WIFI_M2M_SERVER_PORT); - addr.sin_addr.s_addr = _htonl(MAIN_WIFI_M2M_SERVER_IP); - - // Initialize Wi-Fi parameters structure. - memset((uint8_t *)¶m, 0, sizeof(tstrWifiInitParam)); - - // Initialize Wi-Fi driver with data and status callbacks. - param.pfAppWifiCb = wifi_cb; - ret = m2m_wifi_init(¶m); - if (M2M_SUCCESS != ret) { - printf("main: m2m_wifi_init call error!(%d)\r\n", ret); - while (1) { - } - } - - // Initialize socket module - socketInit(); - registerSocketCallback(socket_cb, NULL); - - // Connect to router. - m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); - \endcode -*/ -NMI_API void registerSocketCallback(tpfAppSocketCb socket_cb, tpfAppResolveCb resolve_cb); - - -/** @} */ - -/** @defgroup SocketFn socket - * @ingroup SocketAPI - * Synchronous socket allocation function based on the specified socket type. Created sockets are non-blocking and their possible types are either TCP or a UDP sockets. - * The maximum allowed number of TCP sockets is @ref TCP_SOCK_MAX sockets while the maximum number of UDP sockets that can be created simultaneously is @ref UDP_SOCK_MAX sockets. - * -*/ - /**@{*/ -/*! -@fn \ - NMI_API SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags); - - -@param [in] u16Domain - Socket family. The only allowed value is AF_INET (IPv4.0) for TCP/UDP sockets. - -@param [in] u8Type - Socket type. Allowed values are: - - [SOCK_STREAM](@ref SOCK_STREAM) - - [SOCK_DGRAM](@ref SOCK_DGRAM) - -@param [in] u8Flags - Used to specify the socket creation flags. It shall be set to zero for normal TCP/UDP sockets. - It could be @ref SOCKET_FLAGS_SSL if the socket is used for SSL session. The use of the flag - @ref SOCKET_FLAGS_SSL has no meaning in case of UDP sockets. - -@pre - The @ref socketInit function must be called once at the beginning of the application to initialize the socket handler. - before any call to the socket function can be made. - -@see - connect - bind - listen - accept - recv - recvfrom - send - sendto - close - setsockopt - getsockopt - -@return - On successful socket creation, a non-blocking socket type is created and a socket ID is returned - In case of failure the function returns a negative value, identifying one of the socket error codes defined. - For example: @ref SOCK_ERR_INVALID for invalid argument or - @ref SOCK_ERR_MAX_TCP_SOCK if the number of TCP allocated sockets exceeds the number of available sockets. - -@remarks - The socket function must be called a priori to any other related socket functions "e.g. send, recv, close ..etc" -\section Example - This example demonstrates the use of the socket function to allocate the socket, returning the socket handler to be used for other -socket operations. Socket creation is dependent on the socket type. -\subsection sub1 UDP example -@code - SOCKET UdpServerSocket = -1; - - UdpServerSocket = socket(AF_INET, SOCK_DGRAM, 0); - -@endcode -\subsection sub2 TCP example -@code - static SOCKET tcp_client_socket = -1; - - tcp_client_socket = socket(AF_INET, SOCK_STREAM, 0)); -@endcode -\subsection sub3 SSL example -@code -static SOCKET ssl_socket = -1; - -ssl_socket = socket(AF_INET, SOCK_STREAM, SOCK_FLAGS_SSL)); -@endcode -*/ -NMI_API SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags); - - -/** @} */ -/** @defgroup BindFn bind - * @ingroup SocketAPI -* Asynchronous bind function associates the provided address and local port to the socket. -* The function can be used with both TCP and UDP sockets it's mandatory to call the @ref bind function before starting any UDP or TCP server operation. -* Upon socket bind completion, the application will receive a @ref SOCKET_MSG_BIND message in the socket callback. -*/ - /**@{*/ -/*! -\fn \ - NMI_API sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); - - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] pstrAddr - Pointer to socket address structure "sockaddr_in" - [sockaddr_in](@ref sockaddr_in) - - -@param [in] u8AddrLen - Size of the given socket address structure in bytes. - -@pre - The socket function must be called to allocate a socket before passing the socket ID to the bind function. - -@see - socket - connect - listen - accept - recv - recvfrom - send - sendto - -@return - The function returns ZERO for successful operations and a negative value otherwise. - The possible error values are: - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - Indicating that the operation was successful. - - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) - Indicating passing invalid arguments such as negative socket ID or NULL socket address structure. - - - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID) - Indicate socket bind failure. -\section Example - This example demonstrates the call of the bind socket operation after a successful socket operation. -@code - struct sockaddr_in addr; - SOCKET udpServerSocket =-1; - int ret = -1; - - if(udpServerSocket == -1) - { - udpServerSocket = socket(AF_INET, SOCK_DGRAM, 0); - if(udpServerSocket >= 0) - { - addr.sin_family = AF_INET; - addr.sin_port = _htons(1234); - addr.sin_addr.s_addr = 0; - ret = bind(udpServerSocket,(struct sockaddr*)&addr,sizeof(addr)); - - if(ret != 0) - { - printf("Bind Failed. Error code = %d\n",ret); - close(udpServerSocket); - } - } - else - { - printf("UDP Server Socket Creation Failed\n"); - return; - } - } -@endcode -*/ -NMI_API sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); - - -/** @} */ - -/** @defgroup ListenFn listen - * @ingroup SocketAPI - * After successful socket binding to an IP address and port on the system, start listening on a passive socket for incoming connections. - The socket must be bound on a local port or the listen operation fails. - Upon the call to the asynchronous listen function, response is received through the event [SOCKET_MSG_BIND](@ref SOCKET_MSG_BIND) - in the socket callback. - A successful listen means the TCP server operation is active. If a connection is accepted, then the application socket callback function is - notified with the new connected socket through the event @ref SOCKET_MSG_ACCEPT. Hence there is no need to call the @ref accept function - after calling @ref listen. - - After a connection is accepted, the user is then required to call the @ref recv to receive any packets transmitted by the remote host or to receive notification of socket connection - termination. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 listen(SOCKET sock, uint8 backlog); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] backlog - Not used by the current implementation. - -@pre - The bind function must be called to assign the port number and IP address to the socket before the listen operation. - -@see - bind - accept - recv - recvfrom - send - sendto - -@return - The function returns ZERO for successful operations and a negative value otherwise. - The possible error values are: - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - Indicating that the operation was successful. - - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) - Indicating passing invalid arguments such as negative socket ID. - - - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID) - Indicate socket listen failure. -\section Example -This example demonstrates the call of the listen socket operation after a successful socket operation. -@code - static void TCP_Socketcallback(SOCKET sock, uint8 u8Msg, void * pvMsg) - { - int ret =-1; - - switch(u8Msg) - { - case SOCKET_MSG_BIND: - { - tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg; - if(pstrBind != NULL) - { - if(pstrBind->status == 0) - { - ret = listen(sock, 0); - - if(ret <0) - printf("Listen failure! Error = %d\n",ret); - } - else - { - M2M_ERR("bind Failure!\n"); - close(sock); - } - } - } - break; - - case SOCKET_MSG_LISTEN: - { - - tstrSocketListenMsg *pstrListen = (tstrSocketListenMsg*)pvMsg; - if(pstrListen != NULL) - { - if(pstrListen->status == 0) - { - ret = accept(sock,NULL,0); - } - else - { - M2M_ERR("listen Failure!\n"); - close(sock); - } - } - } - break; - - case SOCKET_MSG_ACCEPT: - { - tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg*)pvMsg; - - if(pstrAccept->sock >= 0) - { - TcpNotificationSocket = pstrAccept->sock; - recv(pstrAccept->sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT); - } - else - { - M2M_ERR("accept failure\n"); - } - } - break; - - default: - break; - } - } - -@endcode -*/ -NMI_API sint8 listen(SOCKET sock, uint8 backlog); -/** @} */ -/** @defgroup AcceptFn accept - * @ingroup SocketAPI - * The function has no current implementation. An empty deceleration is used to prevent errors when legacy application code is used. - * For recent application use, the accept function can be safer as it has no effect and could be safely removed from any application using it. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. -@param [in] addr - Not used in the current implementation. - -@param [in] addrlen - Not used in the current implementation. - -@return - The function returns ZERO for successful operations and a negative value otherwise. - The possible error values are: - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - Indicating that the operation was successful. - - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) - Indicating passing invalid arguments such as negative socket ID. -*/ -NMI_API sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen); -/** @} */ -/** @defgroup ConnectFn connect - * @ingroup SocketAPI - * Establishes a TCP connection with a remote server. - The asynchronous connect function must be called after receiving a valid socket ID from the @ref socket function. - The application socket callback function is notified of a successful new socket connection through the event @ref SOCKET_MSG_CONNECT. - A successful connect means the TCP session is active. The application is then required to make a call to the @ref recv - to receive any packets transmitted by the remote server, unless the application is interrupted by a notification of socket connection - termination. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] pstrAddr - Address of the remote server. -@param [in] pstrAddr - Pointer to socket address structure "sockaddr_in" - [sockaddr_in](@ref sockaddr_in) - -@param [in] u8AddrLen - Size of the given socket address structure in bytes. - Not currently used, implemented for BSD compatibility only. -@pre - The socket function must be called to allocate a TCP socket before passing the socket ID to the bind function. - If the socket is not bound, you do NOT have to call bind before the "connect" function. - -@see - socket - recv - send - close - -@return - The function returns ZERO for successful operations and a negative value otherwise. - The possible error values are: - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - Indicating that the operation was successful. - - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) - Indicating passing invalid arguments such as negative socket ID or NULL socket address structure. - - - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID) - Indicate socket connect failure. -\section Example - The example demonstrates a TCP application, showing how the asynchronous call to the connect function is made through the main function and how the - callback function handles the @ref SOCKET_MSG_CONNECT event. -\subsection sub1 Main Function -@code - struct sockaddr_in Serv_Addr; - SOCKET TcpClientSocket =-1; - int ret = -1 - - TcpClientSocket = socket(AF_INET,SOCK_STREAM,0); - Serv_Addr.sin_family = AF_INET; - Serv_Addr.sin_port = _htons(1234); - Serv_Addr.sin_addr.s_addr = inet_addr(SERVER); - printf("Connected to server via socket %u\n",TcpClientSocket); - - do - { - ret = connect(TcpClientSocket,(sockaddr_in*)&Serv_Addr,sizeof(Serv_Addr)); - if(ret != 0) - { - printf("Connection Error\n"); - } - else - { - printf("Connection successful.\n"); - break; - } - }while(1) -@endcode -\subsection sub2 Socket Callback -@code - if(u8Msg == SOCKET_MSG_CONNECT) - { - tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg*)pvMsg; - if(pstrConnect->s8Error == 0) - { - uint8 acBuffer[GROWL_MSG_SIZE]; - uint16 u16MsgSize; - - printf("Connect success!\n"); - - u16MsgSize = FormatMsg(u8ClientID, acBuffer); - send(sock, acBuffer, u16MsgSize, 0); - recv(pstrNotification->Socket, (void*)au8Msg,GROWL_DESCRIPTION_MAX_LENGTH, GROWL_RX_TIMEOUT); - u8Retry = GROWL_CONNECT_RETRY; - } - else - { - M2M_DBG("Connection Failed, Error: %d\n",pstrConnect->s8Error"); - close(pstrNotification->Socket); - } - } -@endcode -*/ -#ifdef ARDUINO -NMI_API sint8 connectSocket(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); -#else -NMI_API sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); -#endif -/** @} */ -/** @defgroup ReceiveFn recv - * @ingroup SocketAPI - * An asynchronous receive function, used to retrieve data from a TCP stream. - Before calling the recv function, a successful socket connection status must have been received through any of the two socket events - [SOCKET_MSG_CONNECT] or [SOCKET_MSG_ACCEPT], from the socket callback. Hence, indicating that the socket is already connected to a remote - host. - The application receives the required data in response to this asynchronous call through the reception of the event @ref SOCKET_MSG_RECV in the - socket callback. - - Receiving the SOCKET_MSG_RECV message in the callback with zero or negative buffer length indicates the following: - - SOCK_ERR_NO_ERROR : Socket connection closed - - SOCK_ERR_CONN_ABORTED : Socket connection aborted - - SOCK_ERR_TIMEOUT : Socket receive timed out - The application code is expected to close the socket through the call to the @ref close function upon the appearance of the above mentioned errors. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - - -@param [in] pvRecvBuf - Pointer to a buffer that will hold the received data. The buffer is used - in the recv callback to deliver the received data to the caller. The buffer must - be resident in memory (heap or global buffer). - -@param [in] u16BufLen - The buffer size in bytes. - -@param [in] u32Timeoutmsec - Timeout for the recv function in milli-seconds. If the value is set to ZERO, the timeout - will be set to infinite (the recv function waits forever). If the timeout period is - elapsed with no data received, the socket will get a timeout error. -@pre - - The socket function must be called to allocate a TCP socket before passing the socket ID to the recv function. - - The socket in a connected state is expected to receive data through the socket interface. - -@see - socket - connect - bind - listen - recvfrom - close - - -@return - The function returns ZERO for successful operations and a negative value otherwise. - The possible error values are: - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - Indicating that the operation was successful. - - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) - Indicating passing invalid arguments such as negative socket ID or NULL Recieve buffer. - - - [SOCK_ERR_BUFFER_FULL](@ref SOCK_ERR_BUFFER_FULL) - Indicate socket receive failure. -\section Example - The example demonstrates a code snippet for the calling of the recv function in the socket callback upon notification of the accept or connect events, and the parsing of the - received data when the SOCKET_MSG_RECV event is received. -@code - - switch(u8Msg) - { - - case SOCKET_MSG_ACCEPT: - { - tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg*)pvMsg; - - if(pstrAccept->sock >= 0) - { - recv(pstrAccept->sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT); - } - else - { - M2M_ERR("accept\n"); - } - } - break; - - - case SOCKET_MSG_RECV: - { - tstrSocketRecvMsg *pstrRx = (tstrSocketRecvMsg*)pvMsg; - - if(pstrRx->s16BufferSize > 0) - { - - recv(sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT); - } - else - { - printf("Socet recv Error: %d\n",pstrRx->s16BufferSize); - close(sock); - } - } - break; - - default: - break; - } -} -@endcode -*/ -NMI_API sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec); -/** @} */ -/** @defgroup ReceiveFromSocketFn recvfrom - * @ingroup SocketAPI - * Receives data from a UDP Socket. -* -* The asynchronous recvfrom function is used to retrieve data from a UDP socket. The socket must already be bound to -* a local port before a call to the recvfrom function is made (i.e message @ref SOCKET_MSG_BIND is received -* with successful status in the socket callback). -* -* Upon calling the recvfrom function with a successful return code, the application is expected to receive a notification -* in the socket callback whenever a message is received through the @ref SOCKET_MSG_RECVFROM event. -* -* Receiving the SOCKET_MSG_RECVFROM message in the callback with zero, indicates that the socket is closed. -* Whereby a negative buffer length indicates one of the socket error codes such as socket timeout error @SOCK_ERR_TIMEOUT: -* -* The recvfrom callback can also be used to show the IP address of the remote host that sent the frame by -* using the "strRemoteAddr" element in the @ref tstrSocketRecvMsg structure. (refer to the code example) - */ - /**@{*/ -/*! -@fn \ - NMI_API sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32TimeoutSeconds); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] pvRecvBuf - Pointer to a buffer that will hold the received data. The buffer shall be used - in the recv callback to deliver the received data to the caller. The buffer must - be resident in memory (heap or global buffer). - -@param [in] u16BufLen - The buffer size in bytes. - -@param [in] u32TimeoutSeconds - Timeout for the recv function in milli-seconds. If the value is set to ZERO, the timeout - will be set to infinite (the recv function waits forever). - -@pre - - The socket function must be called to allocate a UDP socket before passing the socket ID to the recvfrom function. - - The socket corresponding to the socket ID must be successfully bound to a local port through the call to a @ref bind function. - -@see - socket - bind - close - -@return - The function returns ZERO for successful operations and a negative value otherwise. - The possible error values are: - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - Indicating that the operation was successful. - - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) - Indicating passing invalid arguments such as negative socket ID or NULL Receive buffer. - - - [SOCK_ERR_BUFFER_FULL](@ref SOCK_ERR_BUFFER_FULL) - Indicate socket receive failure. -\section Example - The example demonstrates a code snippet for the calling of the recvfrom function in the socket callback upon notification of a successful bind event, and the parsing of the - received data when the SOCKET_MSG_RECVFROM event is received. -@code - switch(u8Msg) - { - - case SOCKET_MSG_BIND: - { - tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg; - - if(pstrBind != NULL) - { - if(pstrBind->status == 0) - { - recvfrom(sock, gau8SocketTestBuffer, TEST_BUFFER_SIZE, 0); - } - else - { - M2M_ERR("bind\n"); - } - } - } - break; - - - case SOCKET_MSG_RECVFROM: - { - tstrSocketRecvMsg *pstrRx = (tstrSocketRecvMsg*)pvMsg; - - if(pstrRx->s16BufferSize > 0) - { - //get the remote host address and port number - uint16 u16port = pstrRx->strRemoteAddr.sin_port; - uint32 strRemoteHostAddr = pstrRx->strRemoteAddr.sin_addr.s_addr; - - printf("Recieved frame with size = %d.\tHost address=%x, Port number = %d\n\n",pstrRx->s16BufferSize,strRemoteHostAddr, u16port); - - ret = recvfrom(sock,gau8SocketTestBuffer,sizeof(gau8SocketTestBuffer),TEST_RECV_TIMEOUT); - } - else - { - printf("Socet recv Error: %d\n",pstrRx->s16BufferSize); - ret = close(sock); - } - } - break; - - default: - break; - } -} -@endcode -*/ -NMI_API sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec); -/** @} */ -/** @defgroup SendFn send - * @ingroup SocketAPI -* Asynchronous sending function, used to send data on a TCP/UDP socket. - -* Called by the application code when there is outgoing data available required to be sent on a specific socket handler. -* The only difference between this function and the similar @ref sendto function, is the type of socket the data is sent on and the parameters passed in. -* @ref send function is most commonly called for sockets in a connected state. -* After the data is sent, the socket callback function registered using registerSocketCallback(), is expected to receive an event of type -* @ref SOCKET_MSG_SEND holding information containing the number of data bytes sent. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 u16Flags); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] pvSendBuffer - Pointer to a buffer holding data to be transmitted. - -@param [in] u16SendLength - The buffer size in bytes. - -@param [in] u16Flags - Not used in the current implementation. - -@pre - Sockets must be initialized using socketInit. \n - - For TCP Socket:\n - Must use a successfully connected Socket (so that the intended recipient address is known ahead of sending the data). - Hence this function is expected to be called after a successful socket connect operation(in client case or accept in the - the server case).\n - - For UDP Socket:\n - UDP sockets most commonly use @ref sendto function, where the destination address is defined. However, in-order to send outgoing data - using the @ref send function, at least one successful call must be made to the @ref sendto function a priori the consecutive calls to the @ref send function, - to ensure that the destination address is saved in the firmware. - -@see - socketInit - recv - sendto - socket - connect - accept - sendto - -@warning - u16SendLength must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. \n - Use a valid socket identifier through the a prior call to the @ref socket function. - Must use a valid buffer pointer. - Successful completion of a call to send() does not guarantee delivery of the message, - A negative return value indicates only locally-detected errors - - -@return - The function shall return @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise. -*/ -NMI_API sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 u16Flags); -/** @} */ -/** @defgroup SendToSocketFn sendto - * @ingroup SocketAPI -* Asynchronous sending function, used to send data on a UDP socket. -* Called by the application code when there is data required to be sent on a UDP socket handler. -* The application code is expected to receive data from a successful bounded socket node. -* The only difference between this function and the similar @ref send function, is the type of socket the data is received on. This function works -* only with UDP sockets. -* After the data is sent, the socket callback function registered using registerSocketCallback(), is expected to receive an event of type -* @ref SOCKET_MSG_SENDTO. -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] pvSendBuffer - Pointer to a buffer holding data to be transmitted. - A NULL value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] u16SendLength - The buffer size in bytes. It must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. - -@param [in] flags - Not used in the current implementation - -@param [in] pstrDestAddr - The destination address. - -@param [in] u8AddrLen - Destination address length in bytes. - Not used in the current implementation, only included for BSD compatibility. -@pre - Sockets must be initialized using socketInit. - -@see - socketInit - recvfrom - sendto - socket - connect - accept - send - -@warning - u16SendLength must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. \n - Use a valid socket (returned from socket ). - A valid buffer pointer must be used (not NULL). \n - Successful completion of a call to sendto() does not guarantee delivery of the message, - A negative return value indicates only locally-detected errors - -@return - The function returns @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise. -*/ -NMI_API sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen); -/** @} */ -/** @defgroup CloseSocketFn close - * @ingroup SocketAPI - * Synchronous close function, releases all the socket assigned resources. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 close(SOCKET sock); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@pre - Sockets must be initialized through the call of the socketInit function. - @ref close is called only for valid socket identifiers created through the @ref socket function. - -@warning - If @ref close is called while there are still pending messages (sent or received ) they will be discarded. - -@see - socketInit - socket - -@return - The function returned @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise. -*/ -NMI_API sint8 close(SOCKET sock); - - -/** @} */ -/** @defgroup InetAddressFn nmi_inet_addr -* @ingroup SocketAPI -* Synchronous function which returns a BSD socket compliant Internet Protocol (IPv4) socket address. -* This IPv4 address in the input string parameter could either be specified as a host name, or as a numeric string representation like n.n.n.n known as the IPv4 dotted-decimal format -* (i.e. "192.168.10.1"). -* This function is used whenever an ip address needs to be set in the proper format -* (i.e. for the @ref tstrM2MIPConfig structure). -*/ - /**@{*/ -/*! -@fn \ - NMI_API uint32 nmi_inet_addr(char *pcIpAddr); - -@param [in] pcIpAddr - A null terminated string containing the IP address in IPv4 dotted-decimal address. - -@return - Unsigned 32-bit integer representing the IP address in Network byte order - (eg. "192.168.10.1" will be expressed as 0x010AA8C0). - -*/ -NMI_API uint32 nmi_inet_addr(char *pcIpAddr); - - -/** @} */ -/** @defgroup gethostbynameFn gethostbyname - * @ingroup SocketAPI -* Asynchronous DNS resolving function. This function use DNS to resolve a domain name into the corresponding IP address. -* A call to this function will cause a DNS request to be sent and the response will be delivered to the DNS callback function registered using registerSocketCallback() - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 gethostbyname(uint8 * pcHostName); - -@param [in] pcHostName - NULL terminated string containing the domain name for the remote host. - Its size must not exceed [HOSTNAME_MAX_SIZE](@ref HOSTNAME_MAX_SIZE). - -@see - registerSocketCallback - -@warning - Successful completion of a call to gethostbyname() does not guarantee success of the DNS request, - a negative return value indicates only locally-detected errors - -@return - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) -*/ -NMI_API sint8 gethostbyname(uint8 * pcHostName); - - -/** @} */ -/** @defgroup sslEnableCertExpirationCheckFn sslEnableCertExpirationCheck - * @ingroup SocketAPI -* Configure the behavior of the SSL Library for Certificate Expiry Validation. - */ - /**@{*/ -/*! -@fn \ -NMI_API sint8 sslEnableCertExpirationCheck(tenuSslCertExpSettings enuValidationSetting); - -@param [in] enuValidationSetting - See @ref tenuSslCertExpSettings for details. - -@return - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) for successful operation and negative error code otherwise. - -@sa tenuSslCertExpSettings -*/ -NMI_API sint8 sslEnableCertExpirationCheck(tenuSslCertExpSettings enuValidationSetting); - - -/** @} */ - -/** @defgroup SetSocketOptionFn setsockopt - * @ingroup SocketAPI -*The setsockopt() function shall set the option specified by the option_name -* argument, at the protocol level specified by the level argument, to the value -* pointed to by the option_value argument for the socket specified by the socket argument. -* -*

Possible protocol level values supported are @ref SOL_SOCKET and @ref SOL_SSL_SOCKET. -* Possible options when the protocol level is @ref SOL_SOCKET :

-* -* -* -* -* -* -* -* -* -* -* -* -* -*
@ref SO_SET_UDP_SEND_CALLBACKEnable/Disable callback messages for sendto(). -* Since UDP is unreliable by default the user maybe interested (or not) in -* receiving a message of @ref SOCKET_MSG_SENDTO for each call of sendto(). -* Enabled if option value equals @ref TRUE, disabled otherwise.
@ref IP_ADD_MEMBERSHIPValid for UDP sockets. This option is used to receive frames sent to -* a multicast group. option_value shall be a pointer to Unsigned 32-bit -* integer containing the multicast IPv4 address.
@ref IP_DROP_MEMBERSHIPValid for UDP sockets. This option is used to stop receiving frames -* sent to a multicast group. option_value shall be a pointer to Unsigned -* 32-bit integer containing the multicast IPv4 address.
-*

Possible options when the protcol leve  is @ref SOL_SSL_SOCKET

-* -* -* -* -* -* -* -* -* -* -* -* -* -*
-* @ref SO_SSL_BYPASS_X509_VERIFAllow an opened SSL socket to bypass the X509 -* certificate verification process. It is highly recommended NOT to use -* this socket option in production software applications. The option is -* supported for debugging and testing purposes. The option value should be -* casted to int type and it is handled as a boolean flag.
@ref SO_SSL_SNISet the Server Name Indicator (SNI) for an SSL socket. The SNI is a -* null terminated string containing the server name associated with the -* connection. It must not exceed the size of @ref HOSTNAME_MAX_SIZE.
@ref SO_SSL_ENABLE_SESSION_CACHINGThis option allow the TLS to cache the session information for fast -* TLS session establishment in future connections using the TLS Protocol -* session resume features.
- */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 setsockopt(SOCKET socket, uint8 u8Level, uint8 option_name, - const void *option_value, uint16 u16OptionLen); - -@param [in] sock - Socket handler. - -@param [in] level - protocol level. See description above. - -@param [in] option_name - option to be set. See description above. - -@param [in] option_value - pointer to user provided value. - -@param [in] option_len - length of the option value in bytes. -@return - The function shall return \ref SOCK_ERR_NO_ERROR for successful operation - and a negative value (indicating the error) otherwise. -@sa SOL_SOCKET, SOL_SSL_SOCKET, IP_ADD_MEMBERSHIP, IP_DROP_MEMBERSHIP -*/ -NMI_API sint8 setsockopt(SOCKET socket, uint8 u8Level, uint8 option_name, - const void *option_value, uint16 u16OptionLen); - - -/** @} */ -/** @defgroup GetSocketOptionsFn getsockopt - * @ingroup SocketAPI - * Get socket options retrieves -* This Function isn't implemented yet but this is the form that will be released later. - */ - /**@{*/ -/*! -@fn \ - sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8 * pu8OptLen); - -@brief - -@param [in] sock - Socket Identifie. -@param [in] u8Level - The protocol level of the option. -@param [in] u8OptName - The u8OptName argument specifies a single option to get. -@param [out] pvOptValue - The pvOptValue argument contains pointer to a buffer containing the option value. -@param [out] pu8OptLen - Option value buffer length. -@return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8* pu8OptLen); -/** @} */ - -/**@}*/ -/** @defgroup PingFn m2m_ping_req - * @ingroup SocketAPI - * The function sends ping request to the given IP Address. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb); - -@param [in] u32DstIP - Target Destination IP Address for the ping request. It must be represented in Network byte order. - The function nmi_inet_addr could be used to translate the dotted decimal notation IP - to its Network bytes order integer represntative. - -@param [in] u8TTL - IP TTL value for the ping request. If set to ZERO, the dfault value SHALL be used. - -@param [in] fpPingCb - Callback will be called to deliver the ping statistics. - -@see nmi_inet_addr -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb); -/**@}*/ - - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __SOCKET_H__ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/socket/include/socket_buffer.h b/feather_sensor_transmit/libraries/WiFi101/src/socket/include/socket_buffer.h deleted file mode 100644 index d93a7c8..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/socket/include/socket_buffer.h +++ /dev/null @@ -1,94 +0,0 @@ -/** - * - * \file - * - * \brief BSD compatible socket interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef __SOCKET_BUFFER_H__ -#define __SOCKET_BUFFER_H__ - -#include "socket/include/socket.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define SOCKET_BUFFER_UDP_HEADER_SIZE (8) - -#if defined LIMITED_RAM_DEVICE -#define SOCKET_BUFFER_MTU (16u) -#define SOCKET_BUFFER_UDP_SIZE (SOCKET_BUFFER_UDP_HEADER_SIZE + 64u) -#define SOCKET_BUFFER_TCP_SIZE (64u) -#else -#ifdef ARDUINO -#define SOCKET_BUFFER_MTU (1446u) -#else -#define SOCKET_BUFFER_MTU (1400u) -#endif -#define SOCKET_BUFFER_UDP_SIZE (SOCKET_BUFFER_UDP_HEADER_SIZE + SOCKET_BUFFER_MTU) -#define SOCKET_BUFFER_TCP_SIZE (SOCKET_BUFFER_MTU) -#endif - -#define SOCKET_BUFFER_FLAG_CONNECTED (0x1 << 0) -#define SOCKET_BUFFER_FLAG_FULL (0x1 << 1) -#define SOCKET_BUFFER_FLAG_BIND (0x1 << 2) -#define SOCKET_BUFFER_FLAG_SPAWN (0x1 << 3) -#define SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS (16) -#define SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK (((uint32)0xFF) << SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS) -#define SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS (24) -#define SOCKET_BUFFER_FLAG_PARENT_SOCKET_MSK (((uint32)0xFF) << SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS) - -/* Parent stored as parent+1, as socket 1 ID is 0. */ - -typedef struct{ - uint8 *buffer; - uint32 *flag; - uint32 *head; - uint32 *tail; -}tstrSocketBuffer; - -void socketBufferInit(void); -void socketBufferRegister(SOCKET socket, uint32 *flag, uint32 *head, uint32 *tail, uint8 *buffer); -void socketBufferUnregister(SOCKET socket); -void socketBufferCb(SOCKET sock, uint8 u8Msg, void *pvMsg); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __SOCKET_BUFFER_H__ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket.c b/feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket.c deleted file mode 100644 index 877cc1a..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket.c +++ /dev/null @@ -1,1445 +0,0 @@ -/** - * - * \file - * - * \brief BSD compatible socket interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#include - -#include "bsp/include/nm_bsp.h" -#include "socket/include/socket.h" -#include "driver/source/m2m_hif.h" -#include "socket/source/socket_internal.h" -#include "driver/include/m2m_types.h" - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -#define TLS_RECORD_HEADER_LENGTH (5) -#define ETHERNET_HEADER_OFFSET (34) -#define ETHERNET_HEADER_LENGTH (14) -#define TCP_IP_HEADER_LENGTH (40) -#define UDP_IP_HEADER_LENGTH (28) - -#define IP_PACKET_OFFSET (ETHERNET_HEADER_LENGTH + ETHERNET_HEADER_OFFSET - M2M_HIF_HDR_OFFSET) - -#define TCP_TX_PACKET_OFFSET (IP_PACKET_OFFSET + TCP_IP_HEADER_LENGTH) -#define UDP_TX_PACKET_OFFSET (IP_PACKET_OFFSET + UDP_IP_HEADER_LENGTH) -#define SSL_TX_PACKET_OFFSET (TCP_TX_PACKET_OFFSET + TLS_RECORD_HEADER_LENGTH) - -#define SOCKET_REQUEST(reqID, reqArgs, reqSize, reqPayload, reqPayloadSize, reqPayloadOffset) \ - hif_send(M2M_REQ_GROUP_IP, reqID, reqArgs, reqSize, reqPayload, reqPayloadSize, reqPayloadOffset) - - -#define SSL_FLAGS_ACTIVE NBIT0 -#define SSL_FLAGS_BYPASS_X509 NBIT1 -#define SSL_FLAGS_2_RESERVD NBIT2 -#define SSL_FLAGS_3_RESERVD NBIT3 -#define SSL_FLAGS_CACHE_SESSION NBIT4 -#define SSL_FLAGS_NO_TX_COPY NBIT5 -#define SSL_FLAGS_CHECK_SNI NBIT6 - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -PRIVATE DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -/*! -* @brief -*/ -typedef struct{ - SOCKET sock; - uint8 u8Dummy; - uint16 u16SessionID; -}tstrCloseCmd; - - -/*! -* @brief -*/ -typedef struct{ - uint8 *pu8UserBuffer; - uint16 u16UserBufferSize; - uint16 u16SessionID; - uint16 u16DataOffset; - uint8 bIsUsed; - uint8 u8SSLFlags; - uint8 bIsRecvPending; -}tstrSocket; - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -GLOBALS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -volatile sint8 gsockerrno; -volatile tstrSocket gastrSockets[MAX_SOCKET]; -volatile uint8 gu8OpCode; -volatile uint16 gu16BufferSize; -volatile uint16 gu16SessionID = 0; - -volatile tpfAppSocketCb gpfAppSocketCb; -volatile tpfAppResolveCb gpfAppResolveCb; -volatile uint8 gbSocketInit = 0; -volatile tpfPingCb gfpPingCb; - -/********************************************************************* -Function - Socket_ReadSocketData - -Description - Callback function used by the NMC1500 driver to deliver messages - for socket layer. - -Return - None. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 17 July 2012 -*********************************************************************/ -#ifdef ARDUINO -extern uint8 hif_small_xfer; -static uint32 u32Address; -static SOCKET sock_xfer; -static uint8 type_xfer; -static tstrSocketRecvMsg msg_xfer; -#endif -NMI_API void Socket_ReadSocketData(SOCKET sock, tstrSocketRecvMsg *pstrRecv,uint8 u8SocketMsg, - uint32 u32StartAddress,uint16 u16ReadCount) -{ - if((u16ReadCount > 0) && (gastrSockets[sock].pu8UserBuffer != NULL) && (gastrSockets[sock].u16UserBufferSize > 0) && (gastrSockets[sock].bIsUsed == 1)) - { -#ifdef ARDUINO - u32Address = u32StartAddress; -#else - uint32 u32Address = u32StartAddress; -#endif - uint16 u16Read; - sint16 s16Diff; - uint8 u8SetRxDone; -#ifdef ARDUINO - m2m_memcpy((uint8 *)&msg_xfer, (uint8 *)pstrRecv, sizeof(tstrSocketRecvMsg)); - msg_xfer.u16RemainingSize = u16ReadCount; -#else - pstrRecv->u16RemainingSize = u16ReadCount; -#endif - do - { - u8SetRxDone = 1; - u16Read = u16ReadCount; - s16Diff = u16Read - gastrSockets[sock].u16UserBufferSize; - if(s16Diff > 0) - { - u8SetRxDone = 0; - u16Read = gastrSockets[sock].u16UserBufferSize; -#ifdef ARDUINO - hif_small_xfer = 1; - sock_xfer = sock; - type_xfer = u8SocketMsg; -#endif - } - - if(hif_receive(u32Address, gastrSockets[sock].pu8UserBuffer, u16Read, u8SetRxDone) == M2M_SUCCESS) - { -#ifdef ARDUINO - msg_xfer.pu8Buffer = gastrSockets[sock].pu8UserBuffer; - msg_xfer.s16BufferSize = u16Read; - msg_xfer.u16RemainingSize -= u16Read; - - if (gpfAppSocketCb) - gpfAppSocketCb(sock,u8SocketMsg, &msg_xfer); - - u32Address += u16Read; -#else - pstrRecv->pu8Buffer = gastrSockets[sock].pu8UserBuffer; - pstrRecv->s16BufferSize = u16Read; - pstrRecv->u16RemainingSize -= u16Read; - - if (gpfAppSocketCb) - gpfAppSocketCb(sock,u8SocketMsg, pstrRecv); - - u16ReadCount -= u16Read; - u32Address += u16Read; - - if((!gastrSockets[sock].bIsUsed) && (u16ReadCount)) - { - M2M_DBG("Application Closed Socket While Rx Is not Complete\n"); - if(hif_receive(0, NULL, 0, 1) == M2M_SUCCESS) - M2M_DBG("hif_receive Success\n"); - else - M2M_DBG("hif_receive Fail\n"); - break; - } -#endif - } - else - { - M2M_INFO("(ERRR)Current <%d>\n", u16ReadCount); - break; - } -#ifdef ARDUINO - }while(0); -#else - }while(u16ReadCount != 0); -#endif - } -} -#ifdef ARDUINO -NMI_API void Socket_ReadSocketData_Small(void) -{ - if((msg_xfer.u16RemainingSize > 0) && (gastrSockets[sock_xfer].pu8UserBuffer != NULL) && (gastrSockets[sock_xfer].u16UserBufferSize > 0) && (gastrSockets[sock_xfer].bIsUsed == 1)) - { - uint16 u16Read; - sint16 s16Diff; - uint8 u8SetRxDone; - - //do - //{ - u8SetRxDone = 1; - u16Read = msg_xfer.u16RemainingSize; - s16Diff = u16Read - gastrSockets[sock_xfer].u16UserBufferSize; - if(s16Diff > 0) - { - /*Has to be subsequent transfer*/ - hif_small_xfer = 2; - u8SetRxDone = 0; - u16Read = gastrSockets[sock_xfer].u16UserBufferSize; - } - else - { - /*Last xfer, needed for UDP*/ - hif_small_xfer = 3; - } - if(hif_receive(u32Address, gastrSockets[sock_xfer].pu8UserBuffer, u16Read, u8SetRxDone) == M2M_SUCCESS) - { - msg_xfer.pu8Buffer = gastrSockets[sock_xfer].pu8UserBuffer; - msg_xfer.s16BufferSize = u16Read; - msg_xfer.u16RemainingSize -= u16Read; - - if (gpfAppSocketCb) - gpfAppSocketCb(sock_xfer,type_xfer, &msg_xfer); - - u32Address += u16Read; - } - else - { - M2M_INFO("(ERRR)Current <%d>\n", u16Read); - //break; - } - - if (hif_small_xfer == 3) - { - hif_small_xfer = 0; - hif_chip_sleep(); - } - - //}while(u16ReadCount != 0); - } -} -#endif -/********************************************************************* -Function - m2m_ip_cb - -Description - Callback function used by the NMC1000 driver to deliver messages - for socket layer. - -Return - None. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 17 July 2012 -*********************************************************************/ -static void m2m_ip_cb(uint8 u8OpCode, uint16 u16BufferSize,uint32 u32Address) -{ - if((u8OpCode == SOCKET_CMD_BIND) || (u8OpCode == SOCKET_CMD_SSL_BIND)) - { - tstrBindReply strBindReply; - tstrSocketBindMsg strBind; - - if(hif_receive(u32Address, (uint8*)&strBindReply, sizeof(tstrBindReply), 0) == M2M_SUCCESS) - { - strBind.status = strBindReply.s8Status; - if(gpfAppSocketCb) - gpfAppSocketCb(strBindReply.sock,SOCKET_MSG_BIND,&strBind); - } - } - else if(u8OpCode == SOCKET_CMD_LISTEN) - { - tstrListenReply strListenReply; - tstrSocketListenMsg strListen; - if(hif_receive(u32Address, (uint8*)&strListenReply, sizeof(tstrListenReply), 0) == M2M_SUCCESS) - { - strListen.status = strListenReply.s8Status; - if(gpfAppSocketCb) - gpfAppSocketCb(strListenReply.sock,SOCKET_MSG_LISTEN, &strListen); - } - } - else if(u8OpCode == SOCKET_CMD_ACCEPT) - { - tstrAcceptReply strAcceptReply; - tstrSocketAcceptMsg strAccept; - if(hif_receive(u32Address, (uint8*)&strAcceptReply, sizeof(tstrAcceptReply), 0) == M2M_SUCCESS) - { - if(strAcceptReply.sConnectedSock >= 0) - { - gastrSockets[strAcceptReply.sConnectedSock].u8SSLFlags = gastrSockets[strAcceptReply.sListenSock].u8SSLFlags; - gastrSockets[strAcceptReply.sConnectedSock].bIsUsed = 1; - gastrSockets[strAcceptReply.sConnectedSock].u16DataOffset = strAcceptReply.u16AppDataOffset - M2M_HIF_HDR_OFFSET; - - /* The session ID is used to distinguish different socket connections - by comparing the assigned session ID to the one reported by the firmware*/ - ++gu16SessionID; - if(gu16SessionID == 0) - ++gu16SessionID; - - gastrSockets[strAcceptReply.sConnectedSock].u16SessionID = gu16SessionID; - M2M_DBG("Socket %d session ID = %d\r\n",strAcceptReply.sConnectedSock , gu16SessionID ); - } - strAccept.sock = strAcceptReply.sConnectedSock; - strAccept.strAddr.sin_family = AF_INET; - strAccept.strAddr.sin_port = strAcceptReply.strAddr.u16Port; - strAccept.strAddr.sin_addr.s_addr = strAcceptReply.strAddr.u32IPAddr; - if(gpfAppSocketCb) - gpfAppSocketCb(strAcceptReply.sListenSock, SOCKET_MSG_ACCEPT, &strAccept); - } - } - else if((u8OpCode == SOCKET_CMD_CONNECT) || (u8OpCode == SOCKET_CMD_SSL_CONNECT)) - { - tstrConnectReply strConnectReply; - tstrSocketConnectMsg strConnMsg; - if(hif_receive(u32Address, (uint8*)&strConnectReply, sizeof(tstrConnectReply), 0) == M2M_SUCCESS) - { - strConnMsg.sock = strConnectReply.sock; - strConnMsg.s8Error = strConnectReply.s8Error; - if(strConnectReply.s8Error == SOCK_ERR_NO_ERROR) - { - gastrSockets[strConnectReply.sock].u16DataOffset = strConnectReply.u16AppDataOffset - M2M_HIF_HDR_OFFSET; - } - if(gpfAppSocketCb) - gpfAppSocketCb(strConnectReply.sock,SOCKET_MSG_CONNECT, &strConnMsg); - } - } - else if(u8OpCode == SOCKET_CMD_DNS_RESOLVE) - { - tstrDnsReply strDnsReply; - if(hif_receive(u32Address, (uint8*)&strDnsReply, sizeof(tstrDnsReply), 0) == M2M_SUCCESS) - { - if(gpfAppResolveCb) - gpfAppResolveCb((uint8*)strDnsReply.acHostName, strDnsReply.u32HostIP); - } - } - else if((u8OpCode == SOCKET_CMD_RECV) || (u8OpCode == SOCKET_CMD_RECVFROM) || (u8OpCode == SOCKET_CMD_SSL_RECV)) - { - SOCKET sock; - sint16 s16RecvStatus; - tstrRecvReply strRecvReply; - uint16 u16ReadSize; - tstrSocketRecvMsg strRecvMsg; - uint8 u8CallbackMsgID = SOCKET_MSG_RECV; - uint16 u16DataOffset; - - if(u8OpCode == SOCKET_CMD_RECVFROM) - u8CallbackMsgID = SOCKET_MSG_RECVFROM; - - /* Read RECV REPLY data structure. - */ - u16ReadSize = sizeof(tstrRecvReply); - if(hif_receive(u32Address, (uint8*)&strRecvReply, u16ReadSize, 0) == M2M_SUCCESS) - { - uint16 u16SessionID = 0; - - sock = strRecvReply.sock; - u16SessionID = strRecvReply.u16SessionID; - M2M_DBG("recv callback session ID = %d\r\n",u16SessionID); - - /* Reset the Socket RX Pending Flag. - */ - gastrSockets[sock].bIsRecvPending = 0; - - s16RecvStatus = NM_BSP_B_L_16(strRecvReply.s16RecvStatus); - u16DataOffset = NM_BSP_B_L_16(strRecvReply.u16DataOffset); - strRecvMsg.strRemoteAddr.sin_port = strRecvReply.strRemoteAddr.u16Port; - strRecvMsg.strRemoteAddr.sin_addr.s_addr = strRecvReply.strRemoteAddr.u32IPAddr; - - if(u16SessionID == gastrSockets[sock].u16SessionID) - { -#ifdef ARDUINO - if((s16RecvStatus > 0) && (s16RecvStatus < (sint32)u16BufferSize)) -#else - if((s16RecvStatus > 0) && (s16RecvStatus < u16BufferSize)) -#endif - { - /* Skip incoming bytes until reaching the Start of Application Data. - */ - u32Address += u16DataOffset; - - /* Read the Application data and deliver it to the application callback in - the given application buffer. If the buffer is smaller than the received data, - the data is passed to the application in chunks according to its buffer size. - */ - u16ReadSize = (uint16)s16RecvStatus; - Socket_ReadSocketData(sock, &strRecvMsg, u8CallbackMsgID, u32Address, u16ReadSize); - } - else - { - strRecvMsg.s16BufferSize = s16RecvStatus; - strRecvMsg.pu8Buffer = NULL; - if(gpfAppSocketCb) - gpfAppSocketCb(sock,u8CallbackMsgID, &strRecvMsg); - } - } - else - { - M2M_DBG("Discard recv callback %d %d \r\n",u16SessionID , gastrSockets[sock].u16SessionID); - if(u16ReadSize < u16BufferSize) - { - if(hif_receive(0, NULL, 0, 1) == M2M_SUCCESS) - M2M_DBG("hif_receive Success\n"); - else -#ifdef ARDUINO - { -#endif - M2M_DBG("hif_receive Fail\n"); -#ifdef ARDUINO - } -#endif - } - } - } - } - else if((u8OpCode == SOCKET_CMD_SEND) || (u8OpCode == SOCKET_CMD_SENDTO) || (u8OpCode == SOCKET_CMD_SSL_SEND)) - { - SOCKET sock; - sint16 s16Rcvd; - tstrSendReply strReply; - uint8 u8CallbackMsgID = SOCKET_MSG_SEND; - - if(u8OpCode == SOCKET_CMD_SENDTO) - u8CallbackMsgID = SOCKET_MSG_SENDTO; - - if(hif_receive(u32Address, (uint8*)&strReply, sizeof(tstrSendReply), 0) == M2M_SUCCESS) - { - uint16 u16SessionID = 0; - - sock = strReply.sock; - u16SessionID = strReply.u16SessionID; - M2M_DBG("send callback session ID = %d\r\n",u16SessionID); - - s16Rcvd = NM_BSP_B_L_16(strReply.s16SentBytes); - - if(u16SessionID == gastrSockets[sock].u16SessionID) - { - if(gpfAppSocketCb) - gpfAppSocketCb(sock,u8CallbackMsgID, &s16Rcvd); - } - else - { - M2M_DBG("Discard send callback %d %d \r\n",u16SessionID , gastrSockets[sock].u16SessionID); - } - } - } - else if(u8OpCode == SOCKET_CMD_PING) - { - tstrPingReply strPingReply; - if(hif_receive(u32Address, (uint8*)&strPingReply, sizeof(tstrPingReply), 1) == M2M_SUCCESS) - { - gfpPingCb = (void (*)(uint32 , uint32 , uint8))(uintptr_t)strPingReply.u32CmdPrivate; - if(gfpPingCb != NULL) - { - gfpPingCb(strPingReply.u32IPAddr, strPingReply.u32RTT, strPingReply.u8ErrorCode); - } - } - } -} -/********************************************************************* -Function - socketInit - -Description - -Return - None. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -void socketInit(void) -{ - if(gbSocketInit == 0) - { - m2m_memset((uint8*)gastrSockets, 0, MAX_SOCKET * sizeof(tstrSocket)); - hif_register_cb(M2M_REQ_GROUP_IP,m2m_ip_cb); - gbSocketInit = 1; - gu16SessionID = 0; - } -} -/********************************************************************* -Function - socketDeinit - -Description - -Return - None. - -Author - Samer Sarhan - -Version - 1.0 - -Date - 27 Feb 2015 -*********************************************************************/ -void socketDeinit(void) -{ - m2m_memset((uint8*)gastrSockets, 0, MAX_SOCKET * sizeof(tstrSocket)); - hif_register_cb(M2M_REQ_GROUP_IP, NULL); - gpfAppSocketCb = NULL; - gpfAppResolveCb = NULL; - gbSocketInit = 0; -} -/********************************************************************* -Function - registerSocketCallback - -Description - -Return - None. - -Author - Ahmed Ezzat - -Versio - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -void registerSocketCallback(tpfAppSocketCb pfAppSocketCb, tpfAppResolveCb pfAppResolveCb) -{ - gpfAppSocketCb = pfAppSocketCb; - gpfAppResolveCb = pfAppResolveCb; -} - -/********************************************************************* -Function - socket - -Description - Creates a socket. - -Return - - Negative value for error. - - ZERO or positive value as a socket ID if successful. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags) -{ - SOCKET sock = -1; - uint8 u8SockID; - uint8 u8Count; - volatile tstrSocket *pstrSock; - static volatile uint8 u8NextTcpSock = 0; - static volatile uint8 u8NextUdpSock = 0; - - /* The only supported family is the AF_INET for UDP and TCP transport layer protocols. */ - if(u16Domain == AF_INET) - { - if(u8Type == SOCK_STREAM) - { - for(u8Count = 0; u8Count < TCP_SOCK_MAX; u8Count ++) - { - u8SockID = u8NextTcpSock; - pstrSock = &gastrSockets[u8NextTcpSock]; - u8NextTcpSock = (u8NextTcpSock + 1) % TCP_SOCK_MAX; - if(!pstrSock->bIsUsed) - { - sock = (SOCKET)u8SockID; - break; - } - } - } - else if(u8Type == SOCK_DGRAM) - { - volatile tstrSocket *pastrUDPSockets = &gastrSockets[TCP_SOCK_MAX]; - for(u8Count = 0; u8Count < UDP_SOCK_MAX; u8Count ++) - { - u8SockID = u8NextUdpSock; - pstrSock = &pastrUDPSockets[u8NextUdpSock]; - u8NextUdpSock = (u8NextUdpSock + 1) % UDP_SOCK_MAX; - if(!pstrSock->bIsUsed) - { - sock = (SOCKET)(u8SockID + TCP_SOCK_MAX); - break; - } - } - } - - if(sock >= 0) - { - m2m_memset((uint8*)pstrSock, 0, sizeof(tstrSocket)); - pstrSock->bIsUsed = 1; - - /* The session ID is used to distinguish different socket connections - by comparing the assigned session ID to the one reported by the firmware*/ - ++gu16SessionID; - if(gu16SessionID == 0) - ++gu16SessionID; - - pstrSock->u16SessionID = gu16SessionID; - M2M_INFO("Socket %d session ID = %d\r\n",sock, gu16SessionID ); - - if(u8Flags & SOCKET_FLAGS_SSL) - { - tstrSSLSocketCreateCmd strSSLCreate; - strSSLCreate.sslSock = sock; - pstrSock->u8SSLFlags = SSL_FLAGS_ACTIVE | SSL_FLAGS_NO_TX_COPY; - SOCKET_REQUEST(SOCKET_CMD_SSL_CREATE, (uint8*)&strSSLCreate, sizeof(tstrSSLSocketCreateCmd), 0, 0, 0); - } - } - } - return sock; -} -/********************************************************************* -Function - bind - -Description - Request to bind a socket on a local address. - -Return - - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 5 June 2012 -*********************************************************************/ -sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen) -{ - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - if((pstrAddr != NULL) && (sock >= 0) && (gastrSockets[sock].bIsUsed == 1) && (u8AddrLen != 0)) - { - tstrBindCmd strBind; - uint8 u8CMD = SOCKET_CMD_BIND; - if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) - { - u8CMD = SOCKET_CMD_SSL_BIND; - } - - /* Build the bind request. */ - strBind.sock = sock; - m2m_memcpy((uint8 *)&strBind.strAddr, (uint8 *)pstrAddr, sizeof(tstrSockAddr)); - strBind.u16SessionID = gastrSockets[sock].u16SessionID; - - /* Send the request. */ - s8Ret = SOCKET_REQUEST(u8CMD, (uint8*)&strBind,sizeof(tstrBindCmd) , NULL , 0, 0); - if(s8Ret != SOCK_ERR_NO_ERROR) - { - s8Ret = SOCK_ERR_INVALID; - } - } - return s8Ret; -} -/********************************************************************* -Function - listen - -Description - - -Return - - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 5 June 2012 -*********************************************************************/ -sint8 listen(SOCKET sock, uint8 backlog) -{ - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - - if(sock >= 0 && (gastrSockets[sock].bIsUsed == 1)) - { - tstrListenCmd strListen; - - strListen.sock = sock; - strListen.u8BackLog = backlog; - strListen.u16SessionID = gastrSockets[sock].u16SessionID; - - s8Ret = SOCKET_REQUEST(SOCKET_CMD_LISTEN, (uint8*)&strListen, sizeof(tstrListenCmd), NULL, 0, 0); - if(s8Ret != SOCK_ERR_NO_ERROR) - { - s8Ret = SOCK_ERR_INVALID; - } - } - return s8Ret; -} -/********************************************************************* -Function - accept - -Description - -Return - - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 5 June 2012 -*********************************************************************/ -sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)addr; - (void)addrlen; -#endif - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - - if(sock >= 0 && (gastrSockets[sock].bIsUsed == 1) ) - { - s8Ret = SOCK_ERR_NO_ERROR; - } - return s8Ret; -} -/********************************************************************* -Function - connect - -Description - Connect to a remote TCP Server. - -Return - - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 5 June 2012 -*********************************************************************/ -#ifdef ARDUINO -sint8 connectSocket(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen) -#else -sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen) -#endif -{ - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - if((sock >= 0) && (pstrAddr != NULL) && (gastrSockets[sock].bIsUsed == 1) && (u8AddrLen != 0)) - { - tstrConnectCmd strConnect; - uint8 u8Cmd = SOCKET_CMD_CONNECT; - if((gastrSockets[sock].u8SSLFlags) & SSL_FLAGS_ACTIVE) - { - u8Cmd = SOCKET_CMD_SSL_CONNECT; - strConnect.u8SslFlags = gastrSockets[sock].u8SSLFlags; - } - strConnect.sock = sock; - m2m_memcpy((uint8 *)&strConnect.strAddr, (uint8 *)pstrAddr, sizeof(tstrSockAddr)); - - strConnect.u16SessionID = gastrSockets[sock].u16SessionID; - s8Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strConnect,sizeof(tstrConnectCmd), NULL, 0, 0); - if(s8Ret != SOCK_ERR_NO_ERROR) - { - s8Ret = SOCK_ERR_INVALID; - } - } - return s8Ret; -} -/********************************************************************* -Function - send - -Description - -Return - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 5 June 2012 -*********************************************************************/ -sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags) -{ -#ifdef ARDUINO - (void)flags; // Silence "unused" warning -#endif - sint16 s16Ret = SOCK_ERR_INVALID_ARG; - - if((sock >= 0) && (pvSendBuffer != NULL) && (u16SendLength <= SOCKET_BUFFER_MAX_LENGTH) && (gastrSockets[sock].bIsUsed == 1)) - { - uint16 u16DataOffset; - tstrSendCmd strSend; - uint8 u8Cmd; - - u8Cmd = SOCKET_CMD_SEND; - u16DataOffset = TCP_TX_PACKET_OFFSET; - - strSend.sock = sock; - strSend.u16DataSize = NM_BSP_B_L_16(u16SendLength); - strSend.u16SessionID = gastrSockets[sock].u16SessionID; - - if(sock >= TCP_SOCK_MAX) - { - u16DataOffset = UDP_TX_PACKET_OFFSET; - } - if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) - { - u8Cmd = SOCKET_CMD_SSL_SEND; - u16DataOffset = gastrSockets[sock].u16DataOffset; -#ifdef ARDUINO - extern uint32 nmdrv_firm_ver; - - if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 4, 0)) { - // firmware 19.3.0 and older only works with this specific offset - u16DataOffset = SSL_TX_PACKET_OFFSET; - } -#endif - } - - s16Ret = SOCKET_REQUEST(u8Cmd|M2M_REQ_DATA_PKT, (uint8*)&strSend, sizeof(tstrSendCmd), pvSendBuffer, u16SendLength, u16DataOffset); - if(s16Ret != SOCK_ERR_NO_ERROR) - { - s16Ret = SOCK_ERR_BUFFER_FULL; - } - } - return s16Ret; -} -/********************************************************************* -Function - sendto - -Description - -Return - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)flags; - (void)u8AddrLen; -#endif - sint16 s16Ret = SOCK_ERR_INVALID_ARG; - - if((sock >= 0) && (pvSendBuffer != NULL) && (u16SendLength <= SOCKET_BUFFER_MAX_LENGTH) && (gastrSockets[sock].bIsUsed == 1)) - { - if(gastrSockets[sock].bIsUsed) - { - tstrSendCmd strSendTo; - - m2m_memset((uint8*)&strSendTo, 0, sizeof(tstrSendCmd)); - - strSendTo.sock = sock; - strSendTo.u16DataSize = NM_BSP_B_L_16(u16SendLength); - strSendTo.u16SessionID = gastrSockets[sock].u16SessionID; - - if(pstrDestAddr != NULL) - { - struct sockaddr_in *pstrAddr; - pstrAddr = (void*)pstrDestAddr; - - strSendTo.strAddr.u16Family = pstrAddr->sin_family; - strSendTo.strAddr.u16Port = pstrAddr->sin_port; - strSendTo.strAddr.u32IPAddr = pstrAddr->sin_addr.s_addr; - } - s16Ret = SOCKET_REQUEST(SOCKET_CMD_SENDTO|M2M_REQ_DATA_PKT, (uint8*)&strSendTo, sizeof(tstrSendCmd), - pvSendBuffer, u16SendLength, UDP_TX_PACKET_OFFSET); - - if(s16Ret != SOCK_ERR_NO_ERROR) - { - s16Ret = SOCK_ERR_BUFFER_FULL; - } - } - } - return s16Ret; -} -/********************************************************************* -Function - recv - -Description - -Return - - -Author - Ahmed Ezzat - -Version - 1.0 - 2.0 9 April 2013 --> Add timeout for recv operation. - -Date - 5 June 2012 -*********************************************************************/ -sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec) -{ - sint16 s16Ret = SOCK_ERR_INVALID_ARG; - - if((sock >= 0) && (pvRecvBuf != NULL) && (u16BufLen != 0) && (gastrSockets[sock].bIsUsed == 1)) - { - s16Ret = SOCK_ERR_NO_ERROR; - gastrSockets[sock].pu8UserBuffer = (uint8*)pvRecvBuf; - gastrSockets[sock].u16UserBufferSize = u16BufLen; - - if(!gastrSockets[sock].bIsRecvPending) - { - tstrRecvCmd strRecv; - uint8 u8Cmd = SOCKET_CMD_RECV; - - gastrSockets[sock].bIsRecvPending = 1; - if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) - { - u8Cmd = SOCKET_CMD_SSL_RECV; - } - - /* Check the timeout value. */ - if(u32Timeoutmsec == 0) - strRecv.u32Timeoutmsec = 0xFFFFFFFF; - else - strRecv.u32Timeoutmsec = NM_BSP_B_L_32(u32Timeoutmsec); - strRecv.sock = sock; - strRecv.u16SessionID = gastrSockets[sock].u16SessionID; - - s16Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strRecv, sizeof(tstrRecvCmd), NULL , 0, 0); - if(s16Ret != SOCK_ERR_NO_ERROR) - { - s16Ret = SOCK_ERR_BUFFER_FULL; - } - } - } - return s16Ret; -} -/********************************************************************* -Function - close - -Description - -Return - None. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -sint8 close(SOCKET sock) -{ - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - M2M_INFO("Sock to delete <%d>\n", sock); - if(sock >= 0 && (gastrSockets[sock].bIsUsed == 1)) - { - uint8 u8Cmd = SOCKET_CMD_CLOSE; - tstrCloseCmd strclose; - strclose.sock = sock; - strclose.u16SessionID = gastrSockets[sock].u16SessionID; - - gastrSockets[sock].bIsUsed = 0; - gastrSockets[sock].u16SessionID =0; - - if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) - { - u8Cmd = SOCKET_CMD_SSL_CLOSE; - } - s8Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strclose, sizeof(tstrCloseCmd), NULL,0, 0); - if(s8Ret != SOCK_ERR_NO_ERROR) - { - s8Ret = SOCK_ERR_INVALID; - } - m2m_memset((uint8*)&gastrSockets[sock], 0, sizeof(tstrSocket)); - } - return s8Ret; -} -/********************************************************************* -Function - recvfrom - -Description - -Return - - -Author - Ahmed Ezzat - -Version - 1.0 - 2.0 9 April 2013 --> Add timeout for recv operation. - -Date - 5 June 2012 -*********************************************************************/ -sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec) -{ - sint16 s16Ret = SOCK_ERR_NO_ERROR; - if((sock >= 0) && (pvRecvBuf != NULL) && (u16BufLen != 0) && (gastrSockets[sock].bIsUsed == 1)) - { - if(gastrSockets[sock].bIsUsed) - { - s16Ret = SOCK_ERR_NO_ERROR; - gastrSockets[sock].pu8UserBuffer = (uint8*)pvRecvBuf; - gastrSockets[sock].u16UserBufferSize = u16BufLen; - - if(!gastrSockets[sock].bIsRecvPending) - { - tstrRecvCmd strRecv; - - gastrSockets[sock].bIsRecvPending = 1; - - /* Check the timeout value. */ - if(u32Timeoutmsec == 0) - strRecv.u32Timeoutmsec = 0xFFFFFFFF; - else - strRecv.u32Timeoutmsec = NM_BSP_B_L_32(u32Timeoutmsec); - strRecv.sock = sock; - strRecv.u16SessionID = gastrSockets[sock].u16SessionID; - - s16Ret = SOCKET_REQUEST(SOCKET_CMD_RECVFROM, (uint8*)&strRecv, sizeof(tstrRecvCmd), NULL , 0, 0); - if(s16Ret != SOCK_ERR_NO_ERROR) - { - s16Ret = SOCK_ERR_BUFFER_FULL; - } - } - } - } - else - { - s16Ret = SOCK_ERR_INVALID_ARG; - } - return s16Ret; -} -/********************************************************************* -Function - nmi_inet_addr - -Description - -Return - Unsigned 32-bit integer representing the IP address in Network - byte order. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -uint32 nmi_inet_addr(char *pcIpAddr) -{ - uint8 tmp; - uint32 u32IP = 0; - uint8 au8IP[4]; - uint8 c; - uint8 i, j; - - tmp = 0; - - for(i = 0; i < 4; ++i) - { - j = 0; - do - { - c = *pcIpAddr; - ++j; - if(j > 4) - { - return 0; - } - if(c == '.' || c == 0) - { - au8IP[i] = tmp; - tmp = 0; - } - else if(c >= '0' && c <= '9') - { - tmp = (tmp * 10) + (c - '0'); - } - else - { - return 0; - } - ++pcIpAddr; - } while(c != '.' && c != 0); - } - m2m_memcpy((uint8*)&u32IP, au8IP, 4); - return u32IP; -} -/********************************************************************* -Function - gethostbyname - -Description - -Return - None. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -sint8 gethostbyname(uint8 * pcHostName) -{ - sint8 s8Err = SOCK_ERR_INVALID_ARG; - uint8 u8HostNameSize = (uint8)m2m_strlen(pcHostName); - if(u8HostNameSize <= HOSTNAME_MAX_SIZE) - { - s8Err = SOCKET_REQUEST(SOCKET_CMD_DNS_RESOLVE, (uint8*)pcHostName, u8HostNameSize + 1, NULL,0, 0); - } - return s8Err; -} -/********************************************************************* -Function - setsockopt - -Description - -Return - None. - -Author - Abdelrahman Diab - -Version - 1.0 - -Date - 9 September 2014 -*********************************************************************/ -static sint8 sslSetSockOpt(SOCKET sock, uint8 u8Opt, const void *pvOptVal, uint16 u16OptLen) -{ - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - if(sock < TCP_SOCK_MAX) - { - if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) - { - if(u8Opt == SO_SSL_BYPASS_X509_VERIF) - { - int optVal = *((int*)pvOptVal); - if(optVal) - { - gastrSockets[sock].u8SSLFlags |= SSL_FLAGS_BYPASS_X509; - } - else - { - gastrSockets[sock].u8SSLFlags &= ~SSL_FLAGS_BYPASS_X509; - } - s8Ret = SOCK_ERR_NO_ERROR; - } - else if(u8Opt == SO_SSL_ENABLE_SESSION_CACHING) - { - int optVal = *((int*)pvOptVal); - if(optVal) - { - gastrSockets[sock].u8SSLFlags |= SSL_FLAGS_CACHE_SESSION; - } - else - { - gastrSockets[sock].u8SSLFlags &= ~SSL_FLAGS_CACHE_SESSION; - } - s8Ret = SOCK_ERR_NO_ERROR; - } - else if(u8Opt == SO_SSL_ENABLE_SNI_VALIDATION) - { - int optVal = *((int*)pvOptVal); - if(optVal) - { - gastrSockets[sock].u8SSLFlags |= SSL_FLAGS_CHECK_SNI; - } - else - { - gastrSockets[sock].u8SSLFlags &= ~SSL_FLAGS_CHECK_SNI; - } - s8Ret = SOCK_ERR_NO_ERROR; - } - else if(u8Opt == SO_SSL_SNI) - { - if(u16OptLen < HOSTNAME_MAX_SIZE) - { - uint8 *pu8SNI = (uint8*)pvOptVal; - tstrSSLSetSockOptCmd strCmd; - - strCmd.sock = sock; - strCmd.u16SessionID = gastrSockets[sock].u16SessionID; - strCmd.u8Option = u8Opt; - strCmd.u32OptLen = u16OptLen; - m2m_memcpy(strCmd.au8OptVal, pu8SNI, HOSTNAME_MAX_SIZE); - - if(SOCKET_REQUEST(SOCKET_CMD_SSL_SET_SOCK_OPT, (uint8*)&strCmd, sizeof(tstrSSLSetSockOptCmd), - 0, 0, 0) == M2M_ERR_MEM_ALLOC) - { - s8Ret = SOCKET_REQUEST(SOCKET_CMD_SSL_SET_SOCK_OPT | M2M_REQ_DATA_PKT, - (uint8*)&strCmd, sizeof(tstrSSLSetSockOptCmd), 0, 0, 0); - } - s8Ret = SOCK_ERR_NO_ERROR; - } - else - { - M2M_ERR("SNI Exceeds Max Length\n"); - } - } - else - { - M2M_ERR("Unknown SSL Socket Option %d\n",u8Opt); - } - } - else - { - M2M_ERR("Not SSL Socket\n"); - } - } - return s8Ret; -} -/********************************************************************* -Function - setsockopt - -Description - -Return - None. - -Author - Abdelrahman Diab - -Version - 1.0 - -Date - 9 September 2014 -*********************************************************************/ -sint8 setsockopt(SOCKET sock, uint8 u8Level, uint8 option_name, - const void *option_value, uint16 u16OptionLen) -{ - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - if((sock >= 0) && (option_value != NULL) && (gastrSockets[sock].bIsUsed == 1)) - { - if(u8Level == SOL_SSL_SOCKET) - { - s8Ret = sslSetSockOpt(sock, option_name, option_value, u16OptionLen); - } - else - { - uint8 u8Cmd = SOCKET_CMD_SET_SOCKET_OPTION; - tstrSetSocketOptCmd strSetSockOpt; - strSetSockOpt.u8Option=option_name; - strSetSockOpt.sock = sock; - strSetSockOpt.u32OptionValue = *(uint32*)option_value; - strSetSockOpt.u16SessionID = gastrSockets[sock].u16SessionID; - - s8Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strSetSockOpt, sizeof(tstrSetSocketOptCmd), NULL,0, 0); - if(s8Ret != SOCK_ERR_NO_ERROR) - { - s8Ret = SOCK_ERR_INVALID; - } - } - } - return s8Ret; -} -/********************************************************************* -Function - getsockopt - -Description - -Return - None. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 24 August 2014 -*********************************************************************/ -sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8* pu8OptLen) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)sock; - (void)u8Level; - (void)u8OptName; - (void)pvOptValue; - (void)pu8OptLen; -#endif - /* TBD */ - return M2M_SUCCESS; -} -/********************************************************************* -Function - m2m_ping_req - -Description - Send Ping request. - -Return - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2015 -*********************************************************************/ -sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb) -{ - sint8 s8Ret = M2M_ERR_INVALID_ARG; - - if((u32DstIP != 0) && (fpPingCb != NULL)) - { - tstrPingCmd strPingCmd; - - strPingCmd.u16PingCount = 1; - strPingCmd.u32DestIPAddr = u32DstIP; -#ifdef ARDUINO - strPingCmd.u32CmdPrivate = (uint32)(uintptr_t)(fpPingCb); -#else - strPingCmd.u32CmdPrivate = (uint32)(fpPingCb); -#endif - strPingCmd.u8TTL = u8TTL; - - s8Ret = SOCKET_REQUEST(SOCKET_CMD_PING, (uint8*)&strPingCmd, sizeof(tstrPingCmd), NULL, 0, 0); - } - return s8Ret; -} -/********************************************************************* -Function - sslEnableCertExpirationCheck - -Description - Enable/Disable TLS Certificate Expiration Check. - -Return - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - -*********************************************************************/ -sint8 sslEnableCertExpirationCheck(tenuSslCertExpSettings enuValidationSetting) -{ - tstrSslCertExpSettings strSettings; - strSettings.u32CertExpValidationOpt = (uint32)enuValidationSetting; - return SOCKET_REQUEST(SOCKET_CMD_SSL_EXP_CHECK, (uint8*)&strSettings, sizeof(tstrSslCertExpSettings), NULL, 0, 0); -} \ No newline at end of file diff --git a/feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket_buffer.c b/feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket_buffer.c deleted file mode 100644 index d100558..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket_buffer.c +++ /dev/null @@ -1,232 +0,0 @@ -/** - * - * \file - * - * \brief BSD compatible socket interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include -#include "socket/include/socket.h" -#include "driver/source/m2m_hif.h" -#include "socket/source/socket_internal.h" -#include "socket/include/socket_buffer.h" -#include "driver/include/m2m_periph.h" - -tstrSocketBuffer gastrSocketBuffer[MAX_SOCKET]; - -extern uint8 hif_small_xfer; - -void socketBufferInit(void) -{ - memset(gastrSocketBuffer, 0, sizeof(gastrSocketBuffer)); -} - -void socketBufferRegister(SOCKET socket, uint32 *flag, uint32 *head, uint32 *tail, uint8 *buffer) -{ - gastrSocketBuffer[socket].flag = flag; - gastrSocketBuffer[socket].head = head; - gastrSocketBuffer[socket].tail = tail; - gastrSocketBuffer[socket].buffer = buffer; -} - -void socketBufferUnregister(SOCKET socket) -{ - gastrSocketBuffer[socket].flag = 0; - gastrSocketBuffer[socket].head = 0; - gastrSocketBuffer[socket].tail = 0; - gastrSocketBuffer[socket].buffer = 0; -} - -void socketBufferCb(SOCKET sock, uint8 u8Msg, void *pvMsg) -{ - switch (u8Msg) { - /* Socket connected. */ - case SOCKET_MSG_CONNECT: - { - tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg *)pvMsg; - if (pstrConnect && pstrConnect->s8Error >= 0) { - recv(sock, gastrSocketBuffer[sock].buffer, SOCKET_BUFFER_MTU, 0); - *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_CONNECTED; - } else { - close(sock); - } - } - break; - - /* TCP Data receive. */ - case SOCKET_MSG_RECV: - { - // Network led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); - - tstrSocketRecvMsg *pstrRecv = (tstrSocketRecvMsg *)pvMsg; - if (pstrRecv && pstrRecv->s16BufferSize > 0) { - /* Protect against overflow. */ - if (*(gastrSocketBuffer[sock].head) + pstrRecv->s16BufferSize > SOCKET_BUFFER_TCP_SIZE) { - *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_FULL; - break; - } - - /* Add data size. */ - *(gastrSocketBuffer[sock].head) += pstrRecv->s16BufferSize; - - /* Buffer full, stop reception. */ - if (SOCKET_BUFFER_TCP_SIZE - *(gastrSocketBuffer[sock].head) < SOCKET_BUFFER_MTU) { - if (pstrRecv->u16RemainingSize != 0) { - *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_FULL; - } - } - else { - recv(sock, gastrSocketBuffer[sock].buffer + *(gastrSocketBuffer[sock].head), - SOCKET_BUFFER_MTU, 0); - } - } - /* Test EOF (Socket closed) condition for TCP socket. */ - else { - *(gastrSocketBuffer[sock].flag) &= ~SOCKET_BUFFER_FLAG_CONNECTED; - close(sock); - } - - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - } - break; - - /* UDP Data receive. */ - case SOCKET_MSG_RECVFROM: - { - // Network led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); - - tstrSocketRecvMsg *pstrRecv = (tstrSocketRecvMsg *)pvMsg; - if (pstrRecv && pstrRecv->s16BufferSize > 0) { - - if (hif_small_xfer < 2) { - uint32 h = *(gastrSocketBuffer[sock].head); - uint8 *buf = gastrSocketBuffer[sock].buffer; - uint16 sz = pstrRecv->s16BufferSize + pstrRecv->u16RemainingSize; - - /* Store packet size. */ - buf[h++] = sz >> 8; - buf[h++] = sz; - - /* Store remote host port. */ - buf[h++] = pstrRecv->strRemoteAddr.sin_port; - buf[h++] = pstrRecv->strRemoteAddr.sin_port >> 8; - - /* Store remote host IP. */ - buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr >> 24; - buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr >> 16; - buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr >> 8; - buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr; - - /* Data received. */ - *(gastrSocketBuffer[sock].head) = h + pstrRecv->s16BufferSize; - } - else { - /* Data received. */ - *(gastrSocketBuffer[sock].head) += pstrRecv->s16BufferSize; - } - - /* Buffer full, stop reception. */ - if (SOCKET_BUFFER_UDP_SIZE - *(gastrSocketBuffer[sock].head) < SOCKET_BUFFER_MTU + SOCKET_BUFFER_UDP_HEADER_SIZE) { - if (pstrRecv->u16RemainingSize != 0) { - *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_FULL; - } - } - else { - if (hif_small_xfer && hif_small_xfer != 3) { - recvfrom(sock, gastrSocketBuffer[sock].buffer + *(gastrSocketBuffer[sock].head), - SOCKET_BUFFER_MTU, 0); - } - else { - recvfrom(sock, gastrSocketBuffer[sock].buffer + *(gastrSocketBuffer[sock].head) + SOCKET_BUFFER_UDP_HEADER_SIZE, - SOCKET_BUFFER_MTU, 0); - } - } - } - - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - } - break; - - /* Socket bind. */ - case SOCKET_MSG_BIND: - { - tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg *)pvMsg; - if (pstrBind && pstrBind->status == 0) { - *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_BIND; - /* TCP socket needs to enter Listen state. */ - if (sock < TCP_SOCK_MAX) { - listen(sock, 0); - } - /* UDP socket only needs to supply the receive buffer. */ - /* +8 is used to store size, port and IP of incoming data. */ - else { - recvfrom(sock, gastrSocketBuffer[sock].buffer + SOCKET_BUFFER_UDP_HEADER_SIZE, - SOCKET_BUFFER_MTU, 0); - } - } - } - break; - - /* Connect accept. */ - case SOCKET_MSG_ACCEPT: - { - tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg *)pvMsg; - if (pstrAccept && pstrAccept->sock >= 0) { - if (*(gastrSocketBuffer[sock].flag) & SOCKET_BUFFER_FLAG_SPAWN) { - /* One spawn connection already waiting, discard current one. */ - close(pstrAccept->sock); - } - else { - /* Use flag to store spawn TCP descriptor. */ - *(gastrSocketBuffer[sock].flag) &= ~SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK; - *(gastrSocketBuffer[sock].flag) |= (((uint32)pstrAccept->sock) << SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS); - *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_SPAWN; - } - } - } - break; - - } -} diff --git a/feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket_internal.h b/feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket_internal.h deleted file mode 100644 index 1904c23..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/socket/source/socket_internal.h +++ /dev/null @@ -1,71 +0,0 @@ -/** - * - * \file - * - * \brief BSD compatible socket interface internal types. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -#ifndef __SOCKET_INTERNAL_H__ -#define __SOCKET_INTERNAL_H__ - - -#ifdef __cplusplus -extern "C" { -#endif - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "socket/include/socket.h" -#include "socket/include/m2m_socket_host_if.h" - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -NMI_API void Socket_ReadSocketData(SOCKET sock, tstrSocketRecvMsg *pstrRecv,uint8 u8SocketMsg, - uint32 u32StartAddress,uint16 u16ReadCount); -#ifdef ARDUINO -NMI_API void Socket_ReadSocketData_Small(void); -#endif - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __SOCKET_H__ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/spi_flash/include/spi_flash.h b/feather_sensor_transmit/libraries/WiFi101/src/spi_flash/include/spi_flash.h deleted file mode 100644 index a85aa72..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/spi_flash/include/spi_flash.h +++ /dev/null @@ -1,233 +0,0 @@ -/** - * - * \file - * - * \brief WINC1500 SPI Flash. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/** \defgroup SPIFLASH Spi Flash - * @file spi_flash.h - * @brief This file describe SPI flash APIs, how to use it and limitations with each one. - * @section Example - * This example illustrates a complete guide of how to use these APIs. - * @code{.c} - #include "spi_flash.h" - - #define DATA_TO_REPLACE "THIS IS A NEW SECTOR IN FLASH" - - int main() - { - uint8 au8FlashContent[FLASH_SECTOR_SZ] = {0}; - uint32 u32FlashTotalSize = 0; - uint32 u32FlashOffset = 0; - - ret = m2m_wifi_download_mode(); - if(M2M_SUCCESS != ret) - { - printf("Unable to enter download mode\r\n"); - } - else - { - u32FlashTotalSize = spi_flash_get_size(); - } - - while((u32FlashTotalSize > u32FlashOffset) && (M2M_SUCCESS == ret)) - { - ret = spi_flash_read(au8FlashContent, u32FlashOffset, FLASH_SECTOR_SZ); - if(M2M_SUCCESS != ret) - { - printf("Unable to read SPI sector\r\n"); - break; - } - memcpy(au8FlashContent, DATA_TO_REPLACE, strlen(DATA_TO_REPLACE)); - - ret = spi_flash_erase(u32FlashOffset, FLASH_SECTOR_SZ); - if(M2M_SUCCESS != ret) - { - printf("Unable to erase SPI sector\r\n"); - break; - } - - ret = spi_flash_write(au8FlashContent, u32FlashOffset, FLASH_SECTOR_SZ); - if(M2M_SUCCESS != ret) - { - printf("Unable to write SPI sector\r\n"); - break; - } - u32FlashOffset += FLASH_SECTOR_SZ; - } - - if(M2M_SUCCESS == ret) - { - printf("Successful operations\r\n"); - } - else - { - printf("Failed operations\r\n"); - } - - while(1); - return M2M_SUCCESS; - } - * @endcode - */ - -#ifndef __SPI_FLASH_H__ -#define __SPI_FLASH_H__ -#include "common/include/nm_common.h" -#include "bus_wrapper/include/nm_bus_wrapper.h" -#include "driver/source/nmbus.h" -#include "driver/source/nmasic.h" - -#ifdef ARDUINO -#ifdef __cplusplus -extern "C" { -#endif -#endif - -/** - * @fn spi_flash_enable - * @brief Enable spi flash operations - * @version 1.0 - */ -sint8 spi_flash_enable(uint8 enable); -/** \defgroup SPIFLASHAPI Function - * @ingroup SPIFLASH - */ - - /** @defgroup SPiFlashGetFn spi_flash_get_size - * @ingroup SPIFLASHAPI - */ - /**@{*/ -/*! - * @fn uint32 spi_flash_get_size(void); - * @brief Returns with \ref uint32 value which is total flash size\n - * @note Returned value in Mb (Mega Bit). - * @return SPI flash size in case of success and a ZERO value in case of failure. - */ -uint32 spi_flash_get_size(void); - /**@}*/ - - /** @defgroup SPiFlashRead spi_flash_read - * @ingroup SPIFLASHAPI - */ - /**@{*/ -/*! - * @fn sint8 spi_flash_read(uint8 *, uint32, uint32); - * @brief Read a specified portion of data from SPI Flash.\n - * @param [out] pu8Buf - * Pointer to data buffer which will fill in with data in case of successful operation. - * @param [in] u32Addr - * Address (Offset) to read from at the SPI flash. - * @param [in] u32Sz - * Total size of data to be read in bytes - * @warning - * - Address (offset) plus size of data must not exceed flash size.\n - * - No firmware is required for reading from SPI flash.\n - * - In case of there is a running firmware, it is required to pause your firmware first - * before any trial to access SPI flash to avoid any racing between host and running firmware on bus using - * @ref m2m_wifi_download_mode - * @note - * - It is blocking function\n - * @sa m2m_wifi_download_mode, spi_flash_get_size - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -sint8 spi_flash_read(uint8 *pu8Buf, uint32 u32Addr, uint32 u32Sz); - /**@}*/ - - /** @defgroup SPiFlashWrite spi_flash_write - * @ingroup SPIFLASHAPI - */ - /**@{*/ -/*! - * @fn sint8 spi_flash_write(uint8 *, uint32, uint32); - * @brief Write a specified portion of data to SPI Flash.\n - * @param [in] pu8Buf - * Pointer to data buffer which contains the required to be written. - * @param [in] u32Offset - * Address (Offset) to write at the SPI flash. - * @param [in] u32Sz - * Total number of size of data bytes - * @note - * - It is blocking function\n - * - It is user's responsibility to verify that data has been written successfully - * by reading data again and compare it with the original. - * @warning - * - Address (offset) plus size of data must not exceed flash size.\n - * - No firmware is required for writing to SPI flash.\n - * - In case of there is a running firmware, it is required to pause your firmware first - * before any trial to access SPI flash to avoid any racing between host and running firmware on bus using - * @ref m2m_wifi_download_mode. - * - Before writing to any section, it is required to erase it first. - * @sa m2m_wifi_download_mode, spi_flash_get_size, spi_flash_erase - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - - */ -sint8 spi_flash_write(uint8* pu8Buf, uint32 u32Offset, uint32 u32Sz); - /**@}*/ - - /** @defgroup SPiFlashErase spi_flash_erase - * @ingroup SPIFLASHAPI - */ - /**@{*/ -/*! - * @fn sint8 spi_flash_erase(uint32, uint32); - * @brief Erase a specified portion of SPI Flash.\n - * @param [in] u32Offset - * Address (Offset) to erase from the SPI flash. - * @param [in] u32Sz - * Size of SPI flash required to be erased. - * @note It is blocking function \n -* @warning -* - Address (offset) plus size of data must not exceed flash size.\n -* - No firmware is required for writing to SPI flash.\n - * - In case of there is a running firmware, it is required to pause your firmware first - * before any trial to access SPI flash to avoid any racing between host and running firmware on bus using - * @ref m2m_wifi_download_mode - * - It is blocking function\n - * @sa m2m_wifi_download_mode, spi_flash_get_size - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - - */ -sint8 spi_flash_erase(uint32 u32Offset, uint32 u32Sz); - /**@}*/ -#ifdef ARDUINO -#ifdef __cplusplus -} -#endif -#endif -#endif //__SPI_FLASH_H__ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h b/feather_sensor_transmit/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h deleted file mode 100644 index 3b0da53..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h +++ /dev/null @@ -1,245 +0,0 @@ -/** - * - * \file - * - * \brief WINC1500 SPI Flash. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/** -* @file spi_flash_map.h -* @brief This module contains spi flash CONTENT -* @author M.S.M -* @date 17 SEPT 2013 -* @version 1.0 -*/ -#ifndef __SPI_FLASH_MAP_H__ -#define __SPI_FLASH_MAP_H__ - -#define FLASH_MAP_VER_0 (0) -#define FLASH_MAP_VER_1 (1) -#define FLASH_MAP_VER_2 (2) -#define FLASH_MAP_VER_3 (3) - -#define FLASH_MAP_VERSION FLASH_MAP_VER_3 - -//#define DOWNLOAD_ROLLBACK -//#define OTA_GEN -#define _PROGRAM_POWER_SAVE_ - -/* =======*=======*=======*=======*======= - * General Sizes for Flash Memory - * =======*=======*=======*=======*======= - */ - -#define FLASH_START_ADDR (0UL) -/*! location :xxxK - * "S:xxxK" -means-> Size is :xxxK - */ - -/* - * Boot Firmware: which used to select which firmware to run - * - */ -#define M2M_BOOT_FIRMWARE_STARTING_ADDR (FLASH_START_ADDR) -#define M2M_BOOT_FIRMWARE_FLASH_SZ (FLASH_SECTOR_SZ) - -/* - * Control Section: which used by Boot firmware - * - */ -#define M2M_CONTROL_FLASH_OFFSET (M2M_BOOT_FIRMWARE_STARTING_ADDR + M2M_BOOT_FIRMWARE_FLASH_SZ) -#define M2M_CONTROL_FLASH_BKP_OFFSET (M2M_CONTROL_FLASH_OFFSET + FLASH_SECTOR_SZ) -#define M2M_CONTROL_FLASH_SEC_SZ (FLASH_SECTOR_SZ) -#define M2M_CONTROL_FLASH_TOTAL_SZ (FLASH_SECTOR_SZ * 2) - -/* - * LUT for PLL and TX Gain settings: - * - */ -#define M2M_PLL_FLASH_OFFSET (M2M_CONTROL_FLASH_OFFSET + M2M_CONTROL_FLASH_TOTAL_SZ) -#define M2M_PLL_FLASH_SZ (1024 * 1) -#define M2M_GAIN_FLASH_OFFSET (M2M_PLL_FLASH_OFFSET + M2M_PLL_FLASH_SZ) -#define M2M_GAIN_FLASH_SZ (M2M_CONFIG_SECT_TOTAL_SZ - M2M_PLL_FLASH_SZ) -#define M2M_CONFIG_SECT_TOTAL_SZ (FLASH_SECTOR_SZ) - -/* - * Certificate: - * - */ -#define M2M_TLS_ROOTCER_FLASH_OFFSET (M2M_PLL_FLASH_OFFSET + M2M_CONFIG_SECT_TOTAL_SZ) -#define M2M_TLS_ROOTCER_FLASH_SIZE (FLASH_SECTOR_SZ * 1) - -/* - * TLS Server Key Files - * - */ -#define M2M_TLS_SERVER_FLASH_OFFSET (M2M_TLS_ROOTCER_FLASH_OFFSET + M2M_TLS_ROOTCER_FLASH_SIZE) -#define M2M_TLS_SERVER_FLASH_SIZE (FLASH_SECTOR_SZ * 2) - -/* - * HTTP Files - * - */ -#define M2M_HTTP_MEM_FLASH_OFFSET (M2M_TLS_SERVER_FLASH_OFFSET + M2M_TLS_SERVER_FLASH_SIZE) -#define M2M_HTTP_MEM_FLASH_SZ (FLASH_SECTOR_SZ * 2) - -/* - * Saved Connection Parameters: - * - */ -#define M2M_CACHED_CONNS_FLASH_OFFSET (M2M_HTTP_MEM_FLASH_OFFSET + M2M_HTTP_MEM_FLASH_SZ) -#define M2M_CACHED_CONNS_FLASH_SZ (FLASH_SECTOR_SZ * 1) - -/* - * - * Common section size - */ - -#define M2M_COMMON_DATA_SEC \ - (\ - M2M_BOOT_FIRMWARE_FLASH_SZ + \ - M2M_CONTROL_FLASH_TOTAL_SZ + \ - M2M_CONFIG_SECT_TOTAL_SZ + \ - M2M_TLS_ROOTCER_FLASH_SIZE + \ - M2M_TLS_SERVER_FLASH_SIZE + \ - M2M_HTTP_MEM_FLASH_SZ + \ - M2M_CACHED_CONNS_FLASH_SZ \ - ) - -/* - * - * OTA image1 Offset - */ - -#define M2M_OTA_IMAGE1_OFFSET (M2M_CACHED_CONNS_FLASH_OFFSET + M2M_CACHED_CONNS_FLASH_SZ) -/* - * Firmware Offset - * - */ -#if (defined _FIRMWARE_)||(defined OTA_GEN) -#define M2M_FIRMWARE_FLASH_OFFSET (0UL) -#else -#if (defined DOWNLOAD_ROLLBACK) -#define M2M_FIRMWARE_FLASH_OFFSET (M2M_OTA_IMAGE2_OFFSET) -#else -#define M2M_FIRMWARE_FLASH_OFFSET (M2M_OTA_IMAGE1_OFFSET) -#endif -#endif -/* - * - * Firmware - */ -#define M2M_FIRMWARE_FLASH_SZ (236 * 1024UL) -/** - * - * OTA image Size - */ -#define OTA_IMAGE_SIZE (M2M_FIRMWARE_FLASH_SZ) -/** - * - * Flash Total size - */ -#define FLASH_IMAGE1_CONTENT_SZ (M2M_COMMON_DATA_SEC + OTA_IMAGE_SIZE) - -/** - * - * OTA image 2 offset - */ -#define M2M_OTA_IMAGE2_OFFSET (FLASH_IMAGE1_CONTENT_SZ) - -/* - * App(Cortus App 4M): App. which runs over firmware - * - */ -#define M2M_APP_4M_MEM_FLASH_SZ (FLASH_SECTOR_SZ * 16) -#define M2M_APP_4M_MEM_FLASH_OFFSET (FLASH_4M_TOTAL_SZ - M2M_APP_4M_MEM_FLASH_SZ) -#define M2M_APP_8M_MEM_FLASH_OFFSET (M2M_OTA_IMAGE2_OFFSET + OTA_IMAGE_SIZE) -#define M2M_APP_8M_MEM_FLASH_SZ (FLASH_SECTOR_SZ * 32) -#define M2M_APP_OTA_MEM_FLASH_OFFSET (M2M_APP_8M_MEM_FLASH_OFFSET + M2M_APP_8M_MEM_FLASH_SZ) - -/* Check if total size of content - * don't exceed total size of memory allowed - **/ -#if (M2M_COMMON_DATA_SEC + (OTA_IMAGE_SIZE *2)> FLASH_4M_TOTAL_SZ) -#error "Excced 4M Flash Size" -#endif /* (FLASH_CONTENT_SZ > FLASH_TOTAL_SZ) */ - - -#endif /* __SPI_FLASH_MAP_H__ */ diff --git a/feather_sensor_transmit/libraries/WiFi101/src/spi_flash/source/spi_flash.c b/feather_sensor_transmit/libraries/WiFi101/src/spi_flash/source/spi_flash.c deleted file mode 100644 index 12eff59..0000000 --- a/feather_sensor_transmit/libraries/WiFi101/src/spi_flash/source/spi_flash.c +++ /dev/null @@ -1,770 +0,0 @@ -/** - * - * \file - * - * \brief WINC1500 SPI Flash. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifdef PROFILING -#include "windows.h" -#endif -#include "spi_flash/include/spi_flash.h" -#define DUMMY_REGISTER (0x1084) - -#ifdef ARDUINO -#define u32(x) ((uint32)x) -#endif - -#define TIMEOUT (-1) /*MS*/ - -//#define DISABLE_UNSED_FLASH_FUNCTIONS - -#define FLASH_BLOCK_SIZE (32UL * 1024) -/*!> 16); - cmd[2] = (uint8)(u32FlashAdr >> 8); - cmd[3] = (uint8)(u32FlashAdr); - cmd[4] = 0xA5; - - ret += nm_write_reg(SPI_FLASH_DATA_CNT, u32Sz); -#ifdef ARDUINO - ret += nm_write_reg(SPI_FLASH_BUF1, u32(cmd[0])|u32(cmd[1]<<8)|u32(cmd[2]<<16)|u32(cmd[3]<<24)); -#else - ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]|(cmd[1]<<8)|(cmd[2]<<16)|(cmd[3]<<24)); -#endif - ret += nm_write_reg(SPI_FLASH_BUF2, cmd[4]); - ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x1f); - ret += nm_write_reg(SPI_FLASH_DMA_ADDR, u32MemAdr); - ret += nm_write_reg(SPI_FLASH_CMD_CNT, 5 | (1<<7)); - do - { - ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); - if(M2M_SUCCESS != ret) break; - } - while(val != 1); - - return ret; -} - -/** -* @fn spi_flash_sector_erase -* @brief Erase sector (4KB) -* @param[IN] u32FlashAdr -* Any memory address within the sector -* @return Status of execution -* @note Compatible with MX25L6465E and should be working with other types -* @author M. Abdelmawla -* @version 1.0 -*/ -static sint8 spi_flash_sector_erase(uint32 u32FlashAdr) -{ - uint8 cmd[4]; - uint32 val = 0; - sint8 ret = M2M_SUCCESS; - - cmd[0] = 0x20; - cmd[1] = (uint8)(u32FlashAdr >> 16); - cmd[2] = (uint8)(u32FlashAdr >> 8); - cmd[3] = (uint8)(u32FlashAdr); - - ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); -#ifdef ARDUINO - ret += nm_write_reg(SPI_FLASH_BUF1, u32(cmd[0])|u32(cmd[1]<<8)|u32(cmd[2]<<16)|u32(cmd[3]<<24)); -#else - ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]|(cmd[1]<<8)|(cmd[2]<<16)|(cmd[3]<<24)); -#endif - ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x0f); - ret += nm_write_reg(SPI_FLASH_DMA_ADDR, 0); - ret += nm_write_reg(SPI_FLASH_CMD_CNT, 4 | (1<<7)); - do - { - ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); - if(M2M_SUCCESS != ret) break; - } - while(val != 1); - - return ret; -} - -/** -* @fn spi_flash_write_enable -* @brief Send write enable command to SPI flash -* @return Status of execution -* @note Compatible with MX25L6465E and should be working with other types -* @author M. Abdelmawla -* @version 1.0 -*/ -static sint8 spi_flash_write_enable(void) -{ - uint8 cmd[1]; - uint32 val = 0; - sint8 ret = M2M_SUCCESS; - - cmd[0] = 0x06; - - ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); - ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]); - ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x01); - ret += nm_write_reg(SPI_FLASH_DMA_ADDR, 0); - ret += nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1<<7)); - do - { - ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); - if(M2M_SUCCESS != ret) break; - } - while(val != 1); - - return ret; -} - -/** -* @fn spi_flash_write_disable -* @brief Send write disable command to SPI flash -* @note Compatible with MX25L6465E and should be working with other types -* @author M. Abdelmawla -* @version 1.0 -*/ -static sint8 spi_flash_write_disable(void) -{ - uint8 cmd[1]; - uint32 val = 0; - sint8 ret = M2M_SUCCESS; - cmd[0] = 0x04; - - ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); - ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]); - ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x01); - ret += nm_write_reg(SPI_FLASH_DMA_ADDR, 0); - ret += nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1<<7)); - do - { - ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); - if(M2M_SUCCESS != ret) break; - } - while(val != 1); - - return ret; -} - -/** -* @fn spi_flash_page_program -* @brief Write data (less than page size) from cortus memory to SPI flash -* @param[IN] u32MemAdr -* Cortus data address. It must be set to its AHB access address -* @param[IN] u32FlashAdr -* Address to write to at the SPI flash -* @param[IN] u32Sz -* Data size -* @note Compatible with MX25L6465E and should be working with other types -* @author M. Abdelmawla -* @version 1.0 -*/ -static sint8 spi_flash_page_program(uint32 u32MemAdr, uint32 u32FlashAdr, uint32 u32Sz) -{ - uint8 cmd[4]; - uint32 val = 0; - sint8 ret = M2M_SUCCESS; - - cmd[0] = 0x02; - cmd[1] = (uint8)(u32FlashAdr >> 16); - cmd[2] = (uint8)(u32FlashAdr >> 8); - cmd[3] = (uint8)(u32FlashAdr); - - ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); -#ifdef ARDUINO - ret += nm_write_reg(SPI_FLASH_BUF1, u32(cmd[0])|u32(cmd[1]<<8)|u32(cmd[2]<<16)|u32(cmd[3]<<24)); -#else - ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]|(cmd[1]<<8)|(cmd[2]<<16)|(cmd[3]<<24)); -#endif - ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x0f); - ret += nm_write_reg(SPI_FLASH_DMA_ADDR, u32MemAdr); - ret += nm_write_reg(SPI_FLASH_CMD_CNT, 4 | (1<<7) | ((u32Sz & 0xfffff) << 8)); - do - { - ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); - if(M2M_SUCCESS != ret) break; - } - while(val != 1); - - return ret; -} - -/** -* @fn spi_flash_read_internal -* @brief Read from data from SPI flash -* @param[OUT] pu8Buf -* Pointer to data buffer -* @param[IN] u32Addr -* Address to read from at the SPI flash -* @param[IN] u32Sz -* Data size -* @note Data size must be < 64KB (limitation imposed by the bus wrapper) -* @author M. Abdelmawla -* @version 1.0 -*/ -static sint8 spi_flash_read_internal(uint8 *pu8Buf, uint32 u32Addr, uint32 u32Sz) -{ - sint8 ret = M2M_SUCCESS; - /* read size must be < 64KB */ - ret = spi_flash_load_to_cortus_mem(HOST_SHARE_MEM_BASE, u32Addr, u32Sz); - if(M2M_SUCCESS != ret) goto ERR; - ret = nm_read_block(HOST_SHARE_MEM_BASE, pu8Buf, u32Sz); -ERR: - return ret; -} - -/** -* @fn spi_flash_pp -* @brief Program data of size less than a page (256 bytes) at the SPI flash -* @param[IN] u32Offset -* Address to write to at the SPI flash -* @param[IN] pu8Buf -* Pointer to data buffer -* @param[IN] u32Sz -* Data size -* @return Status of execution -* @author M. Abdelmawla -* @version 1.0 -*/ -static sint8 spi_flash_pp(uint32 u32Offset, uint8 *pu8Buf, uint16 u16Sz) -{ - sint8 ret = M2M_SUCCESS; - uint8 tmp; - spi_flash_write_enable(); - /* use shared packet memory as temp mem */ - ret += nm_write_block(HOST_SHARE_MEM_BASE, pu8Buf, u16Sz); - ret += spi_flash_page_program(HOST_SHARE_MEM_BASE, u32Offset, u16Sz); - ret += spi_flash_read_status_reg(&tmp); - do - { - if(ret != M2M_SUCCESS) goto ERR; - ret += spi_flash_read_status_reg(&tmp); - }while(tmp & 0x01); - ret += spi_flash_write_disable(); -ERR: - return ret; -} - -/** -* @fn spi_flash_rdid -* @brief Read SPI Flash ID -* @return SPI FLash ID -* @author M.S.M -* @version 1.0 -*/ -static uint32 spi_flash_rdid(void) -{ - unsigned char cmd[1]; - uint32 reg = 0; - uint32 cnt = 0; - sint8 ret = M2M_SUCCESS; - - cmd[0] = 0x9f; - - ret += nm_write_reg(SPI_FLASH_DATA_CNT, 4); - ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]); - ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x1); - ret += nm_write_reg(SPI_FLASH_DMA_ADDR, DUMMY_REGISTER); - ret += nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1<<7)); - do - { - ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)®); - if(M2M_SUCCESS != ret) break; - if(++cnt > 500) - { - ret = M2M_ERR_INIT; - break; - } - } - while(reg != 1); - reg = (M2M_SUCCESS == ret)?(nm_read_reg(DUMMY_REGISTER)):(0); - M2M_PRINT("Flash ID %x \n",(unsigned int)reg); - return reg; -} - -/** -* @fn spi_flash_unlock -* @brief Unlock SPI Flash -* @author M.S.M -* @version 1.0 -*/ -#if 0 -static void spi_flash_unlock(void) -{ - uint8 tmp; - tmp = spi_flash_read_security_reg(); - spi_flash_clear_security_flags(); - if(tmp & 0x80) - { - spi_flash_write_enable(); - spi_flash_gang_unblock(); - } -} -#endif -static void spi_flash_enter_low_power_mode(void) { - volatile unsigned long tmp; - unsigned char* cmd = (unsigned char*) &tmp; - - cmd[0] = 0xb9; - - nm_write_reg(SPI_FLASH_DATA_CNT, 0); - nm_write_reg(SPI_FLASH_BUF1, cmd[0]); - nm_write_reg(SPI_FLASH_BUF_DIR, 0x1); - nm_write_reg(SPI_FLASH_DMA_ADDR, 0); - nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1 << 7)); - while(nm_read_reg(SPI_FLASH_TR_DONE) != 1); -} - - -static void spi_flash_leave_low_power_mode(void) { - volatile unsigned long tmp; - unsigned char* cmd = (unsigned char*) &tmp; - - cmd[0] = 0xab; - - nm_write_reg(SPI_FLASH_DATA_CNT, 0); - nm_write_reg(SPI_FLASH_BUF1, cmd[0]); - nm_write_reg(SPI_FLASH_BUF_DIR, 0x1); - nm_write_reg(SPI_FLASH_DMA_ADDR, 0); - nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1 << 7)); - while(nm_read_reg(SPI_FLASH_TR_DONE) != 1); -} -/*********************************************/ -/* GLOBAL FUNCTIONS */ -/*********************************************/ -/** - * @fn spi_flash_enable - * @brief Enable spi flash operations - * @author M. Abdelmawla - * @version 1.0 - */ -sint8 spi_flash_enable(uint8 enable) -{ - sint8 s8Ret = M2M_SUCCESS; - if(REV(nmi_get_chipid()) >= REV_3A0) { - uint32 u32Val; - - /* Enable pinmux to SPI flash. */ - s8Ret = nm_read_reg_with_ret(0x1410, &u32Val); - if(s8Ret != M2M_SUCCESS) { - goto ERR1; - } - /* GPIO15/16/17/18 */ - u32Val &= ~((0x7777ul) << 12); - u32Val |= ((0x1111ul) << 12); - nm_write_reg(0x1410, u32Val); - if(enable) { - spi_flash_leave_low_power_mode(); - } else { - spi_flash_enter_low_power_mode(); - } - /* Disable pinmux to SPI flash to minimize leakage. */ - u32Val &= ~((0x7777ul) << 12); - u32Val |= ((0x0010ul) << 12); - nm_write_reg(0x1410, u32Val); - } -ERR1: - return s8Ret; -} -/** -* @fn spi_flash_read -* @brief Read from data from SPI flash -* @param[OUT] pu8Buf -* Pointer to data buffer -* @param[IN] u32offset -* Address to read from at the SPI flash -* @param[IN] u32Sz -* Data size -* @return Status of execution -* @note Data size is limited by the SPI flash size only -* @author M. Abdelmawla -* @version 1.0 -*/ -sint8 spi_flash_read(uint8 *pu8Buf, uint32 u32offset, uint32 u32Sz) -{ - sint8 ret = M2M_SUCCESS; - if(u32Sz > FLASH_BLOCK_SIZE) - { - do - { - ret = spi_flash_read_internal(pu8Buf, u32offset, FLASH_BLOCK_SIZE); - if(M2M_SUCCESS != ret) goto ERR; - u32Sz -= FLASH_BLOCK_SIZE; - u32offset += FLASH_BLOCK_SIZE; - pu8Buf += FLASH_BLOCK_SIZE; - } while(u32Sz > FLASH_BLOCK_SIZE); - } - - ret = spi_flash_read_internal(pu8Buf, u32offset, u32Sz); - -ERR: - return ret; -} - -/** -* @fn spi_flash_write -* @brief Proram SPI flash -* @param[IN] pu8Buf -* Pointer to data buffer -* @param[IN] u32Offset -* Address to write to at the SPI flash -* @param[IN] u32Sz -* Data size -* @return Status of execution -* @author M. Abdelmawla -* @version 1.0 -*/ -sint8 spi_flash_write(uint8* pu8Buf, uint32 u32Offset, uint32 u32Sz) -{ -#ifdef PROFILING - uint32 t1 = 0; - uint32 percent =0; - uint32 tpercent =0; -#endif - sint8 ret = M2M_SUCCESS; - uint32 u32wsz; - uint32 u32off; - uint32 u32Blksz; - u32Blksz = FLASH_PAGE_SZ; - u32off = u32Offset % u32Blksz; -#ifdef PROFILING - tpercent = (u32Sz/u32Blksz)+((u32Sz%u32Blksz)>0); - t1 = GetTickCount(); - M2M_PRINT(">Start programming...\r\n"); -#endif - if(u32Sz<=0) - { - M2M_ERR("Data size = %d",(int)u32Sz); - ret = M2M_ERR_FAIL; - goto ERR; - } - - if (u32off)/*first part of data in the address page*/ - { - u32wsz = u32Blksz - u32off; - if(spi_flash_pp(u32Offset, pu8Buf, (uint16)BSP_MIN(u32Sz, u32wsz))!=M2M_SUCCESS) - { - ret = M2M_ERR_FAIL; - goto ERR; - } - if (u32Sz < u32wsz) goto EXIT; - pu8Buf += u32wsz; - u32Offset += u32wsz; - u32Sz -= u32wsz; - } - while (u32Sz > 0) - { - u32wsz = BSP_MIN(u32Sz, u32Blksz); - - /*write complete page or the remaining data*/ - if(spi_flash_pp(u32Offset, pu8Buf, (uint16)u32wsz)!=M2M_SUCCESS) - { - ret = M2M_ERR_FAIL; - goto ERR; - } - pu8Buf += u32wsz; - u32Offset += u32wsz; - u32Sz -= u32wsz; -#ifdef PROFILING - percent++; - printf("\r>Complete Percentage = %d%%.\r",((percent*100)/tpercent)); -#endif - } -EXIT: -#ifdef PROFILING - M2M_PRINT("\rDone\t\t\t\t\t\t"); - M2M_PRINT("\n#Programming time = %f sec\n\r",(GetTickCount() - t1)/1000.0); -#endif -ERR: - return ret; -} - -/** -* @fn spi_flash_erase -* @brief Erase from data from SPI flash -* @param[IN] u32Offset -* Address to write to at the SPI flash -* @param[IN] u32Sz -* Data size -* @return Status of execution -* @note Data size is limited by the SPI flash size only -* @author M. Abdelmawla -* @version 1.0 -*/ -sint8 spi_flash_erase(uint32 u32Offset, uint32 u32Sz) -{ - uint32 i = 0; - sint8 ret = M2M_SUCCESS; - uint8 tmp = 0; -#ifdef PROFILING - uint32 t; - t = GetTickCount(); -#endif - M2M_PRINT("\r\n>Start erasing...\r\n"); - for(i = u32Offset; i < (u32Sz +u32Offset); i += (16*FLASH_PAGE_SZ)) - { - ret += spi_flash_write_enable(); - ret += spi_flash_read_status_reg(&tmp); - ret += spi_flash_sector_erase(i + 10); - ret += spi_flash_read_status_reg(&tmp); - do - { - if(ret != M2M_SUCCESS) goto ERR; - ret += spi_flash_read_status_reg(&tmp); - }while(tmp & 0x01); - - } - M2M_PRINT("Done\r\n"); -#ifdef PROFILING - M2M_PRINT("#Erase time = %f sec\n", (GetTickCount()-t)/1000.0); -#endif -ERR: - return ret; -} - -/** -* @fn spi_flash_get_size -* @brief Get size of SPI Flash -* @return Size of Flash -* @author M.S.M -* @version 1.0 -*/ -uint32 spi_flash_get_size(void) -{ - uint32 u32FlashId = 0, u32FlashPwr = 0; - static uint32 gu32InernalFlashSize= 0; - - if(!gu32InernalFlashSize) - { - u32FlashId = spi_flash_rdid();//spi_flash_probe(); - if(u32FlashId != 0xffffffff) - { - /*flash size is the third byte from the FLASH RDID*/ - u32FlashPwr = ((u32FlashId>>16)&0xff) - 0x11; /*2MBIT is the min*/ - /*That number power 2 to get the flash size*/ - gu32InernalFlashSize = 1< -#include -#include "config.h" -#include -#include "watchdog.h" -#include "rtc.h" -#include "transmit.h" - -#ifdef HEATSEEK_FEATHER_WIFI_WICED -char const* get_encryption_str(int32_t enc_type); -#endif - -CONFIG_union CONFIG; -static DHT dht(DHT_DATA, DHT22); - -void write_config() { - File config_file; - - if (config_file = SD.open("config.bin", FILE_WRITE | O_TRUNC)) { - config_file.write(CONFIG.raw, sizeof(CONFIG)); - config_file.close(); - } else { - Serial.println("unable to update config"); - while(true); // watchdog will reboot - } -} - -bool read_config() { - File config_file; - bool success = false; - - if (config_file = SD.open("config.bin", FILE_READ)) { - int read_size = config_file.read(CONFIG.raw, sizeof(CONFIG)); - - if (sizeof(CONFIG) == read_size) { - Serial.print("Version from file: "); - Serial.print(CONFIG.data.version); - Serial.print("; expected version: "); - Serial.println(CONFIG_VERSION); - if (CONFIG.data.version == CONFIG_VERSION) { - Serial.println("config loaded"); - success = true; - } else { - Serial.println("incorrect config version"); - } - } else { - Serial.print("config incorrect size - expected: "); - Serial.print(sizeof(CONFIG)); - Serial.print(", got: "); - Serial.println(read_size); - } - - config_file.close(); - } else { - Serial.println("unable to read config"); - } - - return success; -} - -void set_default_config() { - CONFIG.data.version = CONFIG_VERSION; - CONFIG.data.reading_interval_s = 5 * 60; - CONFIG.data.cell_configured = 0; - CONFIG.data.wifi_configured = 0; - CONFIG.data.temperature_offset_f = 0.0; - - strcpy(CONFIG.data.hub_id, "featherhub"); - - strcpy(CONFIG.data.endpoint_domain, "relay.heatseek.org"); - strcpy(CONFIG.data.endpoint_path, "/temperatures"); - CONFIG.data.endpoint_configured = 1; -} - -int read_input_until_newline(char *message, char *buffer) { - int i = 0; - bool reached_newline = false; - - while (true) { - Serial.println(message); - - while (Serial.available()) { - char c = Serial.read(); - if (c == '\n') { -// Serial.println("done setting"); - reached_newline = true; - break; - } else { - buffer[i++] = c; - } - } - if (reached_newline) break; - - watchdog_feed(); - delay(2000); - } - - return i; -} - -void print_menu() { - Serial.println("-------------------------------------"); - Serial.println("[?] Print this menu"); - Serial.println("[t] Set RTC"); - Serial.println("[r] Set reading interval"); - Serial.println("[q] Clear reading transmission queue"); - Serial.println("[v] Calibrate temperature sensor"); - #ifdef TRANSMITTER_WIFI - Serial.println("[w] Setup wifi"); - Serial.println("[a] List nearby access points"); - #endif - Serial.println("[i] Setup Cell ID"); - Serial.println("[e] Setup API Endpoint"); - Serial.println("[p] Print config"); - Serial.println("[d] Reset config"); - Serial.println("[s] Exit config"); -} - -void print_config_info() { - Serial.println("-------------------------------------"); - Serial.println("Current config:"); - - #ifdef TRANSMITTER_WIFI - if (CONFIG.data.wifi_configured) { - Serial.print("wifi ssid: "); - Serial.print(CONFIG.data.wifi_ssid); - Serial.print(", wifi pass: "); - Serial.print(CONFIG.data.wifi_pass); - } else { - Serial.print("Wifi not configured"); - } - - Serial.println(); - #endif - - if (CONFIG.data.cell_configured) { - Serial.print("hub id: "); - Serial.print(CONFIG.data.hub_id); - Serial.print(", cell id: "); - Serial.print(CONFIG.data.cell_id); - } else { - Serial.print("cell id not configured"); - } - Serial.println(); - - if (CONFIG.data.endpoint_configured) { - Serial.print("endpoint: "); - Serial.print(CONFIG.data.endpoint_domain); - Serial.print(CONFIG.data.endpoint_path); - } else { - Serial.print("endpoint not configured"); - } - Serial.println(); - - Serial.print("reading_interval (seconds): "); - Serial.println(CONFIG.data.reading_interval_s); -} - -void enter_configuration() { - print_menu(); - - while(true) { - char command = Serial.read(); - while(Serial.available()) { Serial.read(); } - - switch (command) { - case '?': { - print_menu(); - break; - } - case 't': { - rtc_set(); - print_menu(); - break; - } - case 'q': { - clear_queued_transmissions(); - print_menu(); - break; - } - case 'r': { - char buffer[200]; - int length; - - length = read_input_until_newline("Enter Reading interval in seconds", buffer); - buffer[length] = '\0'; - CONFIG.data.reading_interval_s = strtol(buffer, NULL, 0); - - write_config(); - - update_last_reading_time(0); // take initial reading after configuration - clear_queued_transmissions(); // clear transmission queue - - Serial.println("Reading interval Configured"); - print_config_info(); - print_menu(); - break; - } -#ifdef TRANSMITTER_WIFI - case 'w': { - char buffer[200]; - int length; - - length = read_input_until_newline("Enter WiFi SSID", buffer); - buffer[length] = '\0'; - strcpy(CONFIG.data.wifi_ssid, buffer); - - length = read_input_until_newline("Enter WiFi password", buffer); - buffer[length] = '\0'; - strcpy(CONFIG.data.wifi_pass, buffer); - - CONFIG.data.wifi_configured = 1; - write_config(); - force_wifi_reconnect(); - - Serial.println("Wifi Configured"); - print_config_info(); - print_menu(); - break; - } -#endif -#ifdef HEATSEEK_FEATHER_WIFI_WICED - case 'a': { - wl_ap_info_t ap_list[20]; - int networkCount = 0; - networkCount = Feather.scanNetworks(ap_list, 20); - - Serial.println("========="); - Serial.print("Found "); Serial.print(networkCount); Serial.println(" Networks"); - - for (int i = 0; i < networkCount; i++) { - Serial.println("========="); - wl_ap_info_t ap = ap_list[i]; - Serial.print("SSID: "); Serial.println(ap.ssid); - Serial.print("RSSI: "); Serial.println(ap.rssi); - Serial.print("max data rate: "); Serial.println(ap.max_data_rate); - Serial.print("network type: "); Serial.println(ap.network_type); - Serial.print("security: "); Serial.print(ap.security); Serial.print(" - "); Serial.println(get_encryption_str(ap.security)); - Serial.print("channel: "); Serial.println(ap.channel); - Serial.print("band_2_4ghz: "); Serial.println(ap.band_2_4ghz); - } - - break; - } -#endif -#ifdef HEATSEEK_FEATHER_WIFI_M0 - case 'a': { - int networkCount = -1; - WiFi.setPins(8, 7, 4, 2); - networkCount = WiFi.scanNetworks(); - - Serial.println("========="); - Serial.print("Found "); Serial.print(networkCount); Serial.println(" Networks"); - - for (int i = 0; i < networkCount; i++) { - Serial.println("========="); - Serial.print("SSID: "); Serial.println(WiFi.SSID(i)); - Serial.print("RSSI: "); Serial.println(WiFi.RSSI(i)); - Serial.print("security: "); - switch (WiFi.encryptionType(i)) { - case ENC_TYPE_WEP: - Serial.println("WEP"); - case ENC_TYPE_TKIP: - Serial.println("WPA"); - case ENC_TYPE_CCMP: - Serial.println("WPA2"); - case ENC_TYPE_NONE: - Serial.println("None"); - case ENC_TYPE_AUTO: - Serial.println("Auto"); - } - } - print_menu(); - break; - } -#endif - case 'i': { - char buffer[200]; - int length; - -// hub is now always set to 'featherhub' -// length = read_input_until_newline("Enter HUB ID", buffer); -// buffer[length] = '\0'; -// strcpy(CONFIG.data.hub_id, buffer); - - length = read_input_until_newline("Enter CELL ID", buffer); - buffer[length] = '\0'; - strcpy(CONFIG.data.cell_id, buffer); - - CONFIG.data.cell_configured = 1; - write_config(); - - Serial.println("Cell ID Configured"); - print_config_info(); - print_menu(); - break; - } - case 'e': { - char buffer[200]; - int length; - - length = read_input_until_newline("Enter domain of API endpoint (Example: 'heatseek.org')", buffer); - buffer[length] = '\0'; - strcpy(CONFIG.data.endpoint_domain, buffer); - - length = read_input_until_newline("Enter path of API endpoint (Example: '/readings/create')", buffer); - buffer[length] = '\0'; - strcpy(CONFIG.data.endpoint_path, buffer); - - CONFIG.data.endpoint_configured = 1; - write_config(); - - Serial.println("API Endpoint configured"); - print_config_info(); - print_menu(); - break; - } - case 'd': { - Serial.println("reseting config"); - set_default_config(); - write_config(); - - print_config_info(); - print_menu(); - break; - } - case 'p': { - Serial.println("print config info"); - print_config_info(); - break; - } - case 's': { - Serial.println("exiting config"); - return; - } - case 'v': { - char buffer[200]; - int length; - float current_temp; - int readings_taken = 0; - float temperature_f; - float average_temperature_f = 0.0; - - length = read_input_until_newline("Enter current temperature, in fahrenheit, with one decimal place. For example: '41.0'. PLEASE ENSURE THAT SENSOR IS ON FOR APPROX. 5 MINUTES BEFORE CALIBRATING!", buffer); - buffer[length] = '\0'; - current_temp = strtof(buffer, NULL); - - while (readings_taken < 5) { - watchdog_feed(); - Serial.println("Calibrating, please wait..."); - temperature_f = dht.readTemperature(true); - - if (!isnan(temperature_f)) { - if (average_temperature_f == 0.0) { - average_temperature_f = temperature_f; - } else { - average_temperature_f = (average_temperature_f + temperature_f) / 2; - } - } else { - Serial.println("Failed to read temperature sensor; reboot device and try again."); - while(true); - } - - watchdog_feed(); - readings_taken++; - delay(2000); - } - - watchdog_feed(); - - float temperature_offset = current_temp - average_temperature_f; - CONFIG.data.temperature_offset_f = temperature_offset; - write_config(); - - Serial.print("Temperature offset set to: "); - Serial.println(temperature_offset); - - print_config_info(); - print_menu(); - break; - } - } - - watchdog_feed(); - delay(50); - } -} - -uint32_t get_last_reading_time() { - File reading_time_file; - uint8_t data[4]; - - if (reading_time_file = SD.open("time.bin", FILE_READ)) { - reading_time_file.read(data, sizeof(data)); - reading_time_file.close(); - } else { - Serial.println("unable to read last reading time"); - return 0; - } - - return data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); -} - -void update_last_reading_time(uint32_t timestamp) { - uint8_t data[4]; - - data[0] = (timestamp & 0x000000ff); - data[1] = (timestamp & 0x0000ff00) >> 8; - data[2] = (timestamp & 0x00ff0000) >> 16; - data[3] = (timestamp & 0xff000000) >> 24; - - File reading_time_file; - - if (reading_time_file = SD.open("time.bin", FILE_WRITE | O_TRUNC)) { - reading_time_file.write(data, sizeof(data)); - reading_time_file.close(); - } else { - Serial.println("unable to update last reading time"); - while(true); // watchdog will reboot - } - - Serial.println("updated last reading time"); -} - -#ifdef HEATSEEK_FEATHER_WIFI_WICED -char const* get_encryption_str(int32_t enc_type) -{ - // read the encryption type and print out the name: - switch (enc_type) - { - case ENC_TYPE_AUTO: return "ENC_TYPE_AUTO"; - case ENC_TYPE_OPEN: return "ENC_TYPE_OPEN"; - case ENC_TYPE_WEP: return "ENC_TYPE_WEP"; - case ENC_TYPE_WEP_SHARED: return "ENC_TYPE_WEP_SHARED"; - case ENC_TYPE_WPA_TKIP: return "ENC_TYPE_WPA_TKIP"; - case ENC_TYPE_WPA_AES: return "ENC_TYPE_WPA_AES"; - case ENC_TYPE_WPA_MIXED: return "ENC_TYPE_WPA_MIXED"; - case ENC_TYPE_WPA2_AES: return "ENC_TYPE_WPA2_AES"; - case ENC_TYPE_WPA2_TKIP: return "ENC_TYPE_WPA2_TKIP"; - case ENC_TYPE_WPA2_MIXED: return "ENC_TYPE_WPA2_MIXED"; - case ENC_TYPE_WPA_TKIP_ENT: return "ENC_TYPE_WPA_TKIP_ENT"; - case ENC_TYPE_WPA_AES_ENT: return "ENC_TYPE_WPA_AES_ENT"; - case ENC_TYPE_WPA_MIXED_ENT: return "ENC_TYPE_WPA_MIXED_ENT"; - case ENC_TYPE_WPA2_TKIP_ENT: return "ENC_TYPE_WPA2_TKIP_ENT"; - case ENC_TYPE_WPA2_AES_ENT: return "ENC_TYPE_WPA2_AES_ENT"; - case ENC_TYPE_WPA2_MIXED_ENT: return "ENC_TYPE_WPA2_MIXED_ENT"; - case ENC_TYPE_WPS_OPEN: return "ENC_TYPE_WPS_OPEN"; - case ENC_TYPE_WPS_SECURE: return "ENC_TYPE_WPS_SECURE"; - case ENC_TYPE_IBSS_OPEN: return "ENC_TYPE_IBSS_OPEN"; - default: return "UNKNOWN"; - } -} -#endif diff --git a/feather_sensor_transmit/src/config.h b/feather_sensor_transmit/src/config.h deleted file mode 100644 index 1a10ad2..0000000 --- a/feather_sensor_transmit/src/config.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef CONFIG_H -#define CONFIG_H - -#define CONFIG_VERSION 6 - -typedef struct { - uint16_t version; - int32_t reading_interval_s; - - float temperature_offset_f; - - uint8_t cell_configured; - char hub_id[50]; - char cell_id[50]; - - uint8_t wifi_configured; - char wifi_ssid[50]; - char wifi_pass[200]; - - uint8_t endpoint_configured; - char endpoint_domain[100]; - char endpoint_path[100]; -} CONFIG_struct; - -typedef union { - CONFIG_struct data; - uint8_t raw[sizeof(CONFIG_struct)]; -} CONFIG_union; - -extern CONFIG_union CONFIG; - -void write_config(); -bool read_config(); -void set_default_config(); -void enter_configuration(); -uint32_t get_last_reading_time(); -void update_last_reading_time(uint32_t timestamp); - -#endif diff --git a/feather_sensor_transmit/src/heatseek_sensor.ino b/feather_sensor_transmit/src/heatseek_sensor.ino deleted file mode 100644 index 4f28524..0000000 --- a/feather_sensor_transmit/src/heatseek_sensor.ino +++ /dev/null @@ -1,166 +0,0 @@ -#include -#include -#include -#include -#include "user_config.h" -#include "transmit.h" -#include "config.h" -#include "watchdog.h" -#include "rtc.h" - -static DHT dht(DHT_DATA, DHT22); -uint32_t startup_millis = 0; - -void setup() { - watchdog_init(); - - Serial.begin(9600); - delay(2000); - - Serial.print("initializing heatseek data logger: "); - #ifdef TRANSMITTER_WIFI - Serial.println("WIFI"); - #else - Serial.println("cellular"); - #endif - - initialize_sd(); - rtc_initialize(); - - dht.begin(); - - if (!read_config()) set_default_config(); - - watchdog_feed(); - - startup_millis = millis(); -} - -void loop() { - float temperature_f; - float humidity; - float heat_index; - - int32_t current_time = rtc.now().unixtime(); - int32_t last_reading_time = get_last_reading_time(); - int32_t time_since_last_reading = current_time - last_reading_time; - - char command = Serial.read(); - if (command == 'C') { - enter_configuration(); - } - - Serial.print("Time since last reading: "); - Serial.print(time_since_last_reading); - Serial.print(", reading_interval: "); - Serial.print(CONFIG.data.reading_interval_s); - Serial.print(". Code version: "); - Serial.print(CODE_VERSION); - Serial.println(". Press 'C' to enter config."); - - if (millis() - startup_millis < 15000) { - Serial.println("Allowing 15 seconds to enter config mode [C] before taking first reading."); - watchdog_feed(); - delay(2000); - return; - } - - if (CONFIG.data.reading_interval_s - time_since_last_reading > SEND_SAVED_READINGS_THRESHOLD) { - Serial.println("Checking for queued temperature readings"); - watchdog_feed(); - transmit_queued_temps(); - delay(2000); - watchdog_feed(); - return; - } else if (time_since_last_reading < CONFIG.data.reading_interval_s) { - delay(2000); - watchdog_feed(); - return; - } - - watchdog_feed(); - - read_temperatures(&temperature_f, &humidity, &heat_index); - log_to_sd(temperature_f, humidity, heat_index, current_time); - - watchdog_feed(); - - update_last_reading_time(current_time); - watchdog_feed(); - - transmit(temperature_f, humidity, heat_index, current_time); - - watchdog_feed(); - - delay(2000); -} - -void read_temperatures(float *temperature_f, float *humidity, float *heat_index) { - while (true) { - bool success = true; - - *temperature_f = dht.readTemperature(true); - *humidity = dht.readHumidity(); - - if (!isnan(*temperature_f) && !isnan(*humidity)) { - Serial.print("Temperature (actual reading): "); - Serial.print(*temperature_f); - Serial.println(" *F"); - - *temperature_f = *temperature_f + CONFIG.data.temperature_offset_f; - Serial.print("Temperature (after calibration): "); - Serial.print(*temperature_f); - Serial.println(" *F"); - - Serial.print("Humidity: "); - Serial.print(*humidity); - Serial.println("%"); - - *heat_index = dht.computeHeatIndex(*temperature_f, *humidity); - - Serial.print("Heat index: "); - Serial.println(*heat_index); - - return; - - } else { - Serial.println("Error reading temperatures!"); - } - - delay(2000); - - // if we continue to fail to read a temperature, the watchdog will - // eventually cause a reboot - } -} - -void log_to_sd(float temperature_f, float humidity, float heat_index, uint32_t current_time) { - Serial.println("writing to SD card..."); - - File data_file; - - if (data_file = SD.open("data.csv", FILE_WRITE)) { - data_file.print(current_time); data_file.print(","); - data_file.print(temperature_f); data_file.print(","); - data_file.print(humidity); data_file.print(","); - data_file.print(heat_index); data_file.println(); - Serial.println("wrote to SD"); - data_file.close(); - } else { - Serial.println("unable to open data.csv"); - while(true); // watchdog will reboot - } -} - -void initialize_sd() { - // Stop LORA module from interfering with SPI - #ifdef TRANSMITTER_GSM - pinMode(LORA_CS, OUTPUT); - digitalWrite(LORA_CS, HIGH); - #endif - - while (!SD.begin(SD_CS)) { - Serial.println("failed to initialize SD card"); - delay(1000); // watchdog will reboot - } -} diff --git a/feather_sensor_transmit/src/rtc.cpp b/feather_sensor_transmit/src/rtc.cpp deleted file mode 100644 index 108127e..0000000 --- a/feather_sensor_transmit/src/rtc.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include "rtc.h" -#include "watchdog.h" -#include "config.h" - -RTC_PCF8523 rtc; - -void rtc_initialize() { - if (!rtc.begin()) { - Serial.println("Couldn't find RTC"); - while (true); // watchdog will reboot - } - - if (!rtc.initialized()) { - Serial.print("RTC is NOT running! "); - Serial.println(rtc.now().unixtime()); - // TODO - this could make a web request to set and continually update the RTC - rtc_set(); - } -} - -void rtc_set() { - char timestamp[50]; - int i = 0; - bool timestamp_input = false; - uint32_t value = 0; - - while (true) { - Serial.println("Setting RTC, enter the current unix timestamp"); - - while (Serial.available()) { - char c = Serial.read(); - timestamp[i++] = c; - if (c == '\n') { timestamp_input = true; } - } - - if (timestamp_input) { - value = strtoul(timestamp, NULL, 0); - - // sanity check - if (value < 1810148331 && value > 1494614996) { - Serial.println("done setting"); - break; - } else { - Serial.println("The value you entered looks wrong - please try again"); - timestamp_input = false; - i = 0; - } - } - watchdog_feed(); - delay(2000); - } - - Serial.print("setting timestamp to: "); - Serial.println(value); - - rtc.adjust(DateTime(value)); - update_last_reading_time(0); -} diff --git a/feather_sensor_transmit/src/rtc.h b/feather_sensor_transmit/src/rtc.h deleted file mode 100644 index 21befff..0000000 --- a/feather_sensor_transmit/src/rtc.h +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef RTC_H -#define RTC_H - -#include - -extern RTC_PCF8523 rtc; - -void rtc_initialize(); -void rtc_set(); - -#endif diff --git a/feather_sensor_transmit/src/transmit.cpp b/feather_sensor_transmit/src/transmit.cpp deleted file mode 100644 index 69bd38f..0000000 --- a/feather_sensor_transmit/src/transmit.cpp +++ /dev/null @@ -1,513 +0,0 @@ -#include "transmit.h" -#include "config.h" -#include "watchdog.h" -#include - -#ifdef HEATSEEK_BORON_LTE - TCPClient tcpClient; - Bool lteConnected = false; -#endif - -#ifdef HEATSEEK_FEATHER_WIFI_WICED - AdafruitHTTP http; - bool wifiConnected = false; - volatile bool response_received = false; - volatile bool transmit_success = false; -#endif - -#ifdef HEATSEEK_FEATHER_WIFI_M0 - WiFiClient wifiClient; - bool wifiConnected = false; -#endif - -#ifdef TRANSMITTER_GSM - #include - - HardwareSerial *fonaSerial = &Serial1; - - Adafruit_FONA fona = Adafruit_FONA(FONA_RST); - bool gsmConnected = false; -#endif - -#ifdef TRANSMITTER_GSM - bool fona_post(float temperature_f, float humidity, float heat_index, uint32_t current_time) { - fona.HTTP_POST_end(); - - uint16_t statuscode; - int16_t length; - - char url[200]; - strcpy(url, CONFIG.data.endpoint_domain); - strcat(url, CONFIG.data.endpoint_path); - - char data[200]; - - char temperature_buffer[10]; - char humidity_buffer[10]; - char heat_index_buffer[10]; - - dtostrf(temperature_f, 4, 3, temperature_buffer); - dtostrf(humidity, 4, 3, humidity_buffer); - dtostrf(heat_index, 4, 3, heat_index_buffer); - - sprintf(data, "temp=%s&humidity=%s&heat_index=%s&hub=%s&cell=%s&time=%d&sp=%d&cell_version=%s", temperature_buffer, humidity_buffer, heat_index_buffer, CONFIG.data.hub_id, CONFIG.data.cell_id, current_time, CONFIG.data.reading_interval_s, CODE_VERSION); - - Serial.print("posting to: "); Serial.println(url); - Serial.print("with data: "); Serial.println(data); - - if (!fona.HTTP_POST_start(url, F("application/x-www-form-urlencoded"), (uint8_t *) data, strlen(data), &statuscode, (uint16_t *)&length)) { - return false; - } - - Serial.println("reading status"); - - if (statuscode != 200) { - Serial.print("status not 200: "); - Serial.println(statuscode); - return false; - } - - fona.HTTP_POST_end(); - return true; - } - - void connect_to_fona() { - Serial.println('starting fona serial'); - fonaSerial->begin(4800); - - Serial.println('starting fona serial 2'); - if (!fona.begin(*fonaSerial)) { - Serial.println("Couldn't find FONA"); - while(true); // watchdog will reboot - } - - watchdog_feed(); - delay(2000); - - Serial.println('enabling FONA GPRS'); - - uint32_t start = millis(); - - while (!fona.enableGPRS(true)) { - delay(1000); - watchdog_feed(); - - if (millis() - start > 60000) { - Serial.println("failed to start FONA GPRS after 60 sec"); - while (true); - } - } - - Serial.println("Enabled FONA GRPS"); - - gsmConnected = true; - } - - bool _transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time) { - if (!CONFIG.data.cell_configured || !CONFIG.data.endpoint_configured) { - Serial.println("cannot send data - not configured"); - return false; - } - - if (!gsmConnected) connect_to_fona(); - watchdog_feed(); - - int transmit_attempts = 1; - - while (!fona_post(temperature_f, humidity, heat_index, current_time)) { - Serial.print("failed to POST, trying again... attempt #"); - Serial.println(transmit_attempts); - - if (transmit_attempts < 4) { - transmit_attempts++; - watchdog_feed(); - delay(500); - } else { - while (true); - } - } - - return true; - } -#endif - -#ifdef HEATSEEK_FEATHER_WIFI_WICED - void force_wifi_reconnect(void) { - wifiConnected = false; - } - - void receive_callback(void) { - http.respParseHeader(); - int status_received = http.respStatus(); - - Serial.printf("transmitted - received status: (%d) \n", status_received); - - http.stop(); - response_received = true; - transmit_success = (status_received == 200); - } - - void connect_to_wifi() { - Serial.print("Please wait while connecting to:"); - Serial.print(CONFIG.data.wifi_ssid); - Serial.println("... "); - - if (Feather.connect(CONFIG.data.wifi_ssid, CONFIG.data.wifi_pass)) { - Serial.println("Connected!"); - wifiConnected = true; - } else { - Serial.printf("Failed! %s (%d) \n", Feather.errstr()); - } - Serial.println(); - - if (!Feather.connected()) { return; } - - // Connected: Print network info - Feather.printNetwork(); - - // Tell the HTTP client to auto print error codes and halt on errors - http.err_actions(true, true); - - // Set HTTP client verbose - http.verbose(true); - - // Set the callback handlers - http.setReceivedCallback(receive_callback); - } - - bool _transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time) { - if (!CONFIG.data.cell_configured || !CONFIG.data.wifi_configured || !CONFIG.data.endpoint_configured) { - Serial.println("cannot send data - not configured"); - return false; - } - - while (!wifiConnected) { connect_to_wifi(); } - - http.connect(CONFIG.data.endpoint_domain, PORT); // Will halt if an error occurs - - http.addHeader("User-Agent", USER_AGENT_HEADER); - http.addHeader("Connection", "close"); - http.addHeader("Content-Type", "application/x-www-form-urlencoded"); - - char time_buffer[30]; - char temperature_buffer[30]; - char humidity_buffer[30]; - char heat_index_buffer[30]; - char reading_interval_buffer[30]; - - sprintf(time_buffer, "%d", current_time); - sprintf(reading_interval_buffer, "%d", CONFIG.data.reading_interval_s); - sprintf(temperature_buffer, "%.3f", temperature_f); - sprintf(humidity_buffer, "%.3f", humidity); - sprintf(heat_index_buffer, "%.3f", heat_index); - - const char* post_data[][2] = - { - {"hub", CONFIG.data.hub_id}, - {"cell", CONFIG.data.cell_id}, - {"time", time_buffer}, - {"temp", temperature_buffer}, - {"humidity", humidity_buffer}, - {"sp", reading_interval_buffer}, - {"heat_index", heat_index_buffer}, - {"cell_version", CODE_VERSION}, - }; - int param_count = 8; - - response_received = false; - transmit_success = false; - - http.post(CONFIG.data.endpoint_domain, CONFIG.data.endpoint_path, post_data, param_count); // Will halt if an error occurs - - while (!response_received || !transmit_success); // Hang if transmit doesn't complete or fails - - return true; - } -#endif - -#ifdef HEATSEEK_FEATHER_WIFI_M0 - void force_wifi_reconnect(void) { - if (wifiConnected) { - wifiConnected = false; - WiFi.end(); - } - } - - void connect_to_wifi() { - WiFi.setPins(8, 7, 4, 2); - - Serial.print("Please wait while connecting to:"); - Serial.print(CONFIG.data.wifi_ssid); - Serial.println("... "); - - int status = WL_IDLE_STATUS; - - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(CONFIG.data.wifi_ssid, CONFIG.data.wifi_pass); - - while (status != WL_CONNECTED) { - delay(1000); - Serial.println("Establishing connection..."); - } - - wifiConnected = true; - Serial.println("Connected to WiFi"); - - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); - - watchdog_feed(); - } - - bool _transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time) { - if (!CONFIG.data.cell_configured || !CONFIG.data.wifi_configured || !CONFIG.data.endpoint_configured) { - Serial.println("cannot send data - not configured"); - return false; - } - - if (!wifiConnected) { connect_to_wifi(); } - - HttpClient client = HttpClient(wifiClient, CONFIG.data.endpoint_domain, 80); - - String contentType = "application/x-www-form-urlencoded"; - String data = "temp=" + String(temperature_f, 3) + "&humidity=" + String(humidity, 3) + "&heat_index=" + String(heat_index, 3) + "&hub=" + CONFIG.data.hub_id + "&cell=" + CONFIG.data.cell_id + "&time=" + current_time + "&sp=" + CONFIG.data.reading_interval_s + "&cell_version=" + CODE_VERSION; - - Serial.print("Posting data: "); - Serial.println(data); - - client.post(CONFIG.data.endpoint_path, contentType, data); - - int statusCode = client.responseStatusCode(); - String response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - return statusCode == 200; - } -#endif - -#ifdef HEATSEEK_BORON_LTE - // Function to reconnect to LTE? - void force_lte_reconnect(void); - - // Function to connect to Particle Cloud - void connect_to_lte(){ - // Configure the connection here. - Serial.println(“Establishing connection...”); - // Connect to LTE network here. - Serial.println(“Connected to LTE”); - watchdog_feed(); - } - - // Function to transmit - bool _transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time){ - // If cell / API endpoint not configured, indicate error - if (!CONFIG.data.cell_configured || !CONFIG.data.endpoint_configured) { - Serial.println("cannot send data - not configured"); - return false; - } - - // If not connected, connect - if(!lteConnected){ - connect_to_lte(); - } - - // Set up TCPClient - // Do some error checking - client.connect(CONFIG.data.endpoint_domain, 80); - String contentType = "application/x-www-form-urlencoded"; - String data = "temp=" + String(temperature_f, 3) + "&humidity=" + String(humidity, 3) + "&heat_index=" + String(heat_index, 3) + "&hub=" + CONFIG.data.hub_id + "&cell=" + CONFIG.data.cell_id + "&time=" + current_time + "&sp=" + CONFIG.data.reading_interval_s + "&cell_version=" + CODE_VERSION; - Serial.print("Posting data: "); - Serial.println(data); - client.write(CONFIG.data.endpoint_path, contentType, data); - int statusCode = client.status(); - int numCharacters = client.available(); - string response = ""; - for (int i = 0; i < numCharacters; i++) - { - response.append(client.read()); - } - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - return statusCode == 200; - // Load data - // Post data via TCPClient - // Done. -} -#endif - -typedef struct { - float temperature_f; - float humidity; - float heat_index; -} temp_data_struct; - -typedef union { - temp_data_struct data; - uint8_t raw[sizeof(temp_data_struct)]; -} temp_data; - -// Create a file on the SD card representing a temperature reading -// The file name is the unix timestamp, however, due to FAT naming conventions, -// we have to place a period in it. e.g. 1500985299 -> 1500985.299 -// The content of the file is the binary reading data struct. -void queue_transmission(char *filename, temp_data temp, uint32_t current_time) { - char file_path[50]; - char timestamp[50]; - char timestamp_first_half[50]; - char timestamp_last_half[50]; - - // FAT only allows 8 character names, so we make the last 3 digits of the - // timestamp the file "extension" - sprintf(timestamp, "%d", current_time); - strncpy(timestamp_first_half, timestamp, 7); - timestamp_first_half[7] = '\0'; - strncpy(timestamp_last_half, timestamp+7, 3); - timestamp_last_half[3] = '\0'; - - sprintf(filename, "%s.%s", timestamp_first_half, timestamp_last_half); - sprintf(file_path, "pending/%s", filename); - - File temperature_file; - SD.mkdir("pending"); - if (temperature_file = SD.open(file_path, FILE_WRITE | O_TRUNC)) { - temperature_file.write(temp.raw, sizeof(temp)); - temperature_file.close(); - } else { - Serial.println("unable to write temperature"); - while(true); // watchdog will reboot - } -} - -// Take a filename for a reading, read the temperature data and -// transmit it. Then delete the file when the transfer is successful. -void transmit_queued_temp(char *filename) { - watchdog_feed(); - - File temperature_file; - temp_data temperature; - char read_time_buffer[100]; - char file_path[100]; - sprintf(file_path, "pending/%s", filename); - - Serial.print("transfering: "); - Serial.println(filename); - - strncpy(read_time_buffer, filename, 7); - strncpy(read_time_buffer+7, filename+8, 3); - read_time_buffer[10] = '\0'; - - uint32_t read_time = strtoul(read_time_buffer, NULL, 0); - - if (temperature_file = SD.open(file_path, FILE_READ)) { - int read_size = temperature_file.read(temperature.raw, sizeof(temperature)); - - if (sizeof(temperature) == read_size) { - bool transmit_success = _transmit(temperature.data.temperature_f, temperature.data.humidity, temperature.data.heat_index, read_time); - - temperature_file.close(); - delay(100); - - if (transmit_success) { - Serial.println("transferred."); - - if (SD.remove(file_path)) { - Serial.println("removed."); - } else { - Serial.println("failed to remove file"); - } - } else { - Serial.println("failed to transfer"); - } - } else { - Serial.print("file incorrect size - expected: "); - Serial.print(sizeof(temperature)); - Serial.print(", got: "); - Serial.println(read_size); - } - } else { - Serial.print("failed to open: "); - Serial.println(filename); - } - - watchdog_feed(); -} - -void transmit_queued_temps() { - char filename[100]; - File pending_dir = SD.open("pending"); - int temps_transfered_count = 0; - - while (temps_transfered_count < TRANSMITS_PER_LOOP) { - File entry = pending_dir.openNextFile(); - if (!entry) { break; } // No more files - - strcpy(filename, entry.name()); - entry.close(); - - transmit_queued_temp(filename); - temps_transfered_count += 1; - } - - pending_dir.close(); -} - -void clear_queued_transmissions() { - File pending_dir = SD.open("pending"); - - Serial.println("==== Removing queued temperature files"); - while (true) { - watchdog_feed(); - - File entry = pending_dir.openNextFile(); - if (!entry) { break; } // No more files - - char filename[100]; - strcpy(filename, entry.name()); - entry.close(); - - char file_path[100]; - sprintf(file_path, "pending/%s", filename); - - if (SD.remove(file_path)) { - Serial.println("removed queued temperature file."); - } else { - Serial.println("failed to remove queued temperature file."); - } - } - - Serial.println("===="); - - pending_dir.close(); -} - -void transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time) { - watchdog_feed(); - - temp_data temp; - temp.data.temperature_f = temperature_f; - temp.data.humidity = humidity; - temp.data.heat_index = heat_index; - - char filename[100]; - queue_transmission(filename, temp, current_time); - watchdog_feed(); - delay(1000); - - Serial.print("created file: "); - Serial.println(filename); - - transmit_queued_temp(filename); - transmit_queued_temps(); -} diff --git a/feather_sensor_transmit/src/transmit.h b/feather_sensor_transmit/src/transmit.h deleted file mode 100644 index a817d47..0000000 --- a/feather_sensor_transmit/src/transmit.h +++ /dev/null @@ -1,58 +0,0 @@ -#ifndef TRANSMIT_H -#define TRANSMIT_H - -#define CODE_VERSION "F-1.2.0" - -#include "user_config.h" - -#ifdef HEATSEEK_FEATHER_CELL_M0 - #define TRANSMITTER_GSM -#else - #define TRANSMITTER_WIFI -#endif - -#ifdef HEATSEEK_FEATHER_WIFI_WICED - #include - #include - #include - - #define DHT_DATA PC2 - #define SD_CS PB4 - - #define TRANSMITS_PER_LOOP 20 -#endif - -#ifdef HEATSEEK_FEATHER_WIFI_M0 - #include - #include - - #define DHT_DATA A2 - #define SD_CS 10 - - #define TRANSMITS_PER_LOOP 20 -#endif - -#ifdef TRANSMITTER_GSM - #include "Adafruit_FONA.h" - #include - - #define DHT_DATA A2 - #define SD_CS 10 - #define FONA_RST A4 - #define LORA_CS 8 - - #define TRANSMITS_PER_LOOP 5 -#endif - -#define SEND_SAVED_READINGS_THRESHOLD (10 * 60) -#define USER_AGENT_HEADER "curl/7.45.0" -#define PORT 80 - -void transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time); -void transmit_queued_temps(); -void clear_queued_transmissions(); -#ifdef TRANSMITTER_WIFI -void force_wifi_reconnect(); -#endif - -#endif diff --git a/feather_sensor_transmit/src/user_config.h b/feather_sensor_transmit/src/user_config.h deleted file mode 100644 index 6011268..0000000 --- a/feather_sensor_transmit/src/user_config.h +++ /dev/null @@ -1,4 +0,0 @@ -//#define HEATSEEK_FEATHER_CELL_M0 -//#define HEATSEEK_FEATHER_WIFI_M0 -#define HEATSEEK_BORON_LTE -//#define HEATSEEK_FEATHER_WIFI_WICED diff --git a/feather_sensor_transmit/src/watchdog.cpp b/feather_sensor_transmit/src/watchdog.cpp deleted file mode 100644 index 090b286..0000000 --- a/feather_sensor_transmit/src/watchdog.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "watchdog.h" - -#if defined(HEATSEEK_FEATHER_WIFI_M0) || defined(TRANSMITTER_GSM) - #include -#endif - -void watchdog_init() { - #ifdef HEATSEEK_FEATHER_WIFI_WICED - iwdg_init(IWDG_PRE_256, 3500); // 30 second watchdog, 40kHz processor - #endif - - #if defined(HEATSEEK_FEATHER_WIFI_M0) || defined(TRANSMITTER_GSM) - Watchdog.enable(16000); // 16 seconds (this is the max supported) - #endif -} - -void watchdog_feed() { - #ifdef HEATSEEK_FEATHER_WIFI_WICED - iwdg_feed(); - #endif - - #if defined(HEATSEEK_FEATHER_WIFI_M0) || defined(TRANSMITTER_GSM) - Watchdog.reset(); - #endif -} diff --git a/feather_sensor_transmit/src/watchdog.h b/feather_sensor_transmit/src/watchdog.h deleted file mode 100644 index 7acb4e3..0000000 --- a/feather_sensor_transmit/src/watchdog.h +++ /dev/null @@ -1,9 +0,0 @@ -#ifndef WATCHDOG_H -#define WATCHDOG_H - -#include "transmit.h" - -void watchdog_init(); -void watchdog_feed(); - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/c_cpp_properties.json b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/c_cpp_properties.json deleted file mode 100644 index 97a3fc5..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/c_cpp_properties.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "configurations": [ - { - "name": "Win32", - "includePath": [ - "{$workspaceFolder}/**" - ], - "defines": [ - "_DEBUG", - "UNICODE", - "_UNICODE" - ], - "intelliSenseMode": "gcc-x64", - "configurationProvider": "particle.particle-vscode-core" - } - ], - "version": 4 -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/launch.json b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/launch.json deleted file mode 100644 index 4532e35..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/launch.json +++ /dev/null @@ -1,92 +0,0 @@ -{ - "version": "0.1.0", - "configurations": [ - { - "type": "cortex-debug", - "request": "attach", - "name": "Particle Debugger (photon, p1, electron)", - "servertype": "openocd", - "interface": "swd", - "device": "STM32F205RG", - "cwd": "${workspaceRoot}", - "executable": "${command:particle.getDebuggerExecutable}", - "preLaunchTask": "Particle: Flash application for debug (local)", - "armToolchainPath": "${command:particle.getDebuggerCompilerDir}", - "svdFile": "${command:particle.getDebuggerSVDFile}", - "searchDir": [ - "${command:particle.getDebuggerSearchDir}" - ], - "configFiles": [ - "interface/cmsis-dap.cfg", - "target/stm32f2x.cfg" - ], - "postAttachCommands": [ - "monitor reset halt" - ], - "windows": { - "configFiles": [ - "interface\\cmsis-dap.cfg", - "target\\stm32f2x.cfg" - ] - } - }, - { - "type": "cortex-debug", - "request": "attach", - "name": "Particle Debugger (argon, boron / bsom, xenon)", - "servertype": "openocd", - "interface": "swd", - "device": "nRF52840_xxAA", - "cwd": "${workspaceRoot}", - "executable": "${command:particle.getDebuggerExecutable}", - "preLaunchTask": "Particle: Flash application for debug (local)", - "armToolchainPath": "${command:particle.getDebuggerCompilerDir}", - "svdFile": "${command:particle.getDebuggerSVDFile}", - "searchDir": [ - "${command:particle.getDebuggerSearchDir}" - ], - "configFiles": [ - "interface/cmsis-dap.cfg", - "target/nrf52-particle.cfg" - ], - "postAttachCommands": [ - "monitor reset halt" - ], - "windows": { - "configFiles": [ - "interface\\cmsis-dap.cfg", - "target\\nrf52-particle.cfg" - ] - } - }, - { - "type": "cortex-debug", - "request": "attach", - "name": "Particle Programmer Shield v1.0 (photon, p1, electron)", - "servertype": "openocd", - "interface": "swd", - "device": "STM32F205RG", - "cwd": "${workspaceRoot}", - "executable": "${command:particle.getDebuggerExecutable}", - "preLaunchTask": "Particle: Flash application for debug (local)", - "armToolchainPath": "${command:particle.getDebuggerCompilerDir}", - "svdFile": "${command:particle.getDebuggerSVDFile}", - "searchDir": [ - "${command:particle.getDebuggerSearchDir}" - ], - "configFiles": [ - "interface/particle-ftdi.cfg", - "target/stm32f2x.cfg" - ], - "postAttachCommands": [ - "monitor reset halt" - ], - "windows": { - "configFiles": [ - "interface\\particle-ftdi.cfg", - "target\\stm32f2x.cfg" - ] - } - } - ] -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/settings.json b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/settings.json deleted file mode 100644 index 52250e9..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "extensions.ignoreRecommendations": true, - "C_Cpp.default.configurationProvider": "particle.particle-vscode-core", - "cortex-debug.openocdPath": "${command:particle.getDebuggerOpenocdPath}", - "files.associations": { - "*.ino": "cpp" - }, - "particle.targetDevice": "e00fce684c6a4946ca9fecd1", - "particle.firmwareVersion": "1.1.0", - "particle.targetPlatform": "boron" -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/README.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/README.md deleted file mode 100644 index 2e3b0f4..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# feather_sensor_transmit_lte - -A Particle project named feather_sensor_transmit_lte - -## Welcome to your project! - -Every new Particle project is composed of 3 important elements that you'll see have been created in your project directory for feather_sensor_transmit_lte. - -#### ```/src``` folder: -This is the source folder that contains the firmware files for your project. It should *not* be renamed. -Anything that is in this folder when you compile your project will be sent to our compile service and compiled into a firmware binary for the Particle device that you have targeted. - -If your application contains multiple files, they should all be included in the `src` folder. If your firmware depends on Particle libraries, those dependencies are specified in the `project.properties` file referenced below. - -#### ```.ino``` file: -This file is the firmware that will run as the primary application on your Particle device. It contains a `setup()` and `loop()` function, and can be written in Wiring or C/C++. For more information about using the Particle firmware API to create firmware for your Particle device, refer to the [Firmware Reference](https://docs.particle.io/reference/firmware/) section of the Particle documentation. - -#### ```project.properties``` file: -This is the file that specifies the name and version number of the libraries that your project depends on. Dependencies are added automatically to your `project.properties` file when you add a library to a project using the `particle library add` command in the CLI or add a library in the Desktop IDE. - -## Adding additional files to your project - -#### Projects with multiple sources -If you would like add additional files to your application, they should be added to the `/src` folder. All files in the `/src` folder will be sent to the Particle Cloud to produce a compiled binary. - -#### Projects with external libraries -If your project includes a library that has not been registered in the Particle libraries system, you should create a new folder named `/lib//src` under `/` and add the `.h`, `.cpp` & `library.properties` files for your library there. Read the [Firmware Libraries guide](https://docs.particle.io/guide/tools-and-features/libraries/) for more details on how to develop libraries. Note that all contents of the `/lib` folder and subfolders will also be sent to the Cloud for compilation. - -## Compiling your project - -When you're ready to compile your project, make sure you have the correct Particle device target selected and run `particle compile ` in the CLI or click the Compile button in the Desktop IDE. The following files in your project folder will be sent to the compile service: - -- Everything in the `/src` folder, including your `.ino` application file -- The `project.properties` file for your project -- Any libraries stored under `lib//src` diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/boron_firmware_1574447345899.bin b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/boron_firmware_1574447345899.bin deleted file mode 100644 index 544964835a60d84338704d5bd1234e633fc8cef4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5592 zcmd5=e{d9c6@PoXm%IEpxKOBP0?ghmXAchWXj;9NIunv~6LJX@soEAh-ZeSgND{6g zv1!FINUL;er>&(UE!JrT9O{V8)t*Cu?Ku{m))u|AD0ILPwKcS~y1|xP@@xHkckdS& z$G;rMo%!7Nz3;yFzVF9(-}jqPy^BtM&P7CJ!Uh zK!cF^yzUR}Y38oi#}d%H4mwk}Vr^~yVJGAzT|MutCvA&L+6N<~T^OOk;fW!wzC6*) zNqi#FOyo?JML4f#7ioW(5lqU``Q1yD9>m(rmvCxM`<%AGF3wBZ$r;WoLOL_E{=@qc zq&+_!*hQFsWd^etkDK%A`7qXf7Cz-|kfy^YTclR0Rk+8UYMYJ6+9uz1CBJDFzjqdY zW)@%jl`HivK2Wf~$$Ver_s-(a%;IaeFndM$O|$sg?knG0@!V8c?~EB=k*_uVE%H`; zMc#_9$XoFhc`KeGZ~0&3Eqk4X_4k_Vw-oqVbNwQ3$rpJm-Xg!rjIV?@?Rg6JEd3&X z#QL z%y|`9Tw~b0L$Xh1^lF2CutWCBwDP(PExmShn_>&vG8Mt{%(8Qb$7$|0nY+8fvapJ@ zHz&k%BbZs7>F=ucaR*7OnkkbW*5`+~L&CU|_gv>uZdaDc{4bq#`x+L=*-`GfvV)F8 zqB#rFv3{i1ne9aJLH}+LHRT<%263uJ+adyJ?r&RV^ zY5sc5Uzhn?le67u+D@cy-Y&>aDr4KVdU}gLmt7BFBQl(nsgz8aNHTRT~bheg9%3HkP z{$N(Ja>~)_SZi+~%{|Gtgw^-o!F>WyfLj4plXsendwl@evpU721!^xSwo@O$nBVpH zs>NN8`$eI9+*#172W9Q`M)N(huu_H3Z2|u>nY;xY#Z4>O>$z`tj}MLTD9Lc$*Rj}k~&!4x9yACvCBEhDSP`n`m14OzbUhD zql?_B`94U(uTgU@gnQAqhq;6Jf()w;ZnF+;lhGviW3TLJF|wm(6f1Zho_A8@OmPPqmj8f+bWb&wugiX6UY@QB%++KH}p6*?Se z_BYmxoT;iv9eU912Cvk1?P;b!`B`VA12d1#v5(~Q^Uyq zY?6z3qE2-=?#Yf6N%VM)yj8o0GqTYse)vvZm?Uzf8h2F$otayL<)h^|WmhN7Hy1q3 zM)n<}>|CkV%{i^}sE-?Kd~Fg{*Un8iB3C6vnfZVYf!d}g$;-E>=iT^EN@H0ZwKgVdfGcDlU(A5M^lPdI*wMo)`IuXRa@X7(~ z4c2XNcBs6v7iUN)_0Vu7_VUB}5;wPOPrAbA8kdBhOsculLH$*Y!yG!fQVn?~DgkD+D@)oEnP*$IrYf3U(6Gw2K z<1DvwS%r1GkxQI=xqdm<{7wfi-?=KsZJvGI65odM+fB$^pFr`B|eLwW;L9@Lv7klT) zsX%i7cqMNOa;Hgjt44MhJNdU$&Lp?|(pyHhdK%}-v}zTQO6h4oUbN&HRv~T^nB2n96hf@#$6&ar$nZzM5dxdhVA)oi5*{w9kImD;u4vKB{DT7GAx$7&n%XFTr8G+Tr8Hn42vZ%!(z$H zFrU8gmd?fwiT|wHng?x)*cf`VK0zHA3uhO|7 zEt?$m)NtWM^CJB3=XT%$;6b4Dd7#Nfj{r{s`+!5h2=FUl6nG2xEARo3e}cFxdx4Ju zE`S3*y4gkV0)GZh0VjY`9oA>AVfVS*!}``C-~k{GJPbSmJPjNG^3OY<%UfKu0QdsV zrg8AoKo;OJH-_;7kbgdgJBth8ff2mV0vCWk0jGcyz{^0XZ|t7)9Iz8$YkVE!mw~Oo zKHwf82IQaSRu|m>tOo8Ne=tfOAR z?uqsFQoOHkYabTw?dqUdcXvKH7{Af(q5)tF5Cc93tOY&;Tn_{RFHl;867~No*$8VN zUxU4X{rDF4sTXyuMvYehYk+e2@gVR=;MH|5YG04{x47u{KIr~kO#?Ku+fSs8q`McqAq MGC(&!fBm2T1#!eoE&u=k diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/boron_firmware_1574729317031.bin b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/boron_firmware_1574729317031.bin deleted file mode 100644 index 544964835a60d84338704d5bd1234e633fc8cef4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5592 zcmd5=e{d9c6@PoXm%IEpxKOBP0?ghmXAchWXj;9NIunv~6LJX@soEAh-ZeSgND{6g zv1!FINUL;er>&(UE!JrT9O{V8)t*Cu?Ku{m))u|AD0ILPwKcS~y1|xP@@xHkckdS& z$G;rMo%!7Nz3;yFzVF9(-}jqPy^BtM&P7CJ!Uh zK!cF^yzUR}Y38oi#}d%H4mwk}Vr^~yVJGAzT|MutCvA&L+6N<~T^OOk;fW!wzC6*) zNqi#FOyo?JML4f#7ioW(5lqU``Q1yD9>m(rmvCxM`<%AGF3wBZ$r;WoLOL_E{=@qc zq&+_!*hQFsWd^etkDK%A`7qXf7Cz-|kfy^YTclR0Rk+8UYMYJ6+9uz1CBJDFzjqdY zW)@%jl`HivK2Wf~$$Ver_s-(a%;IaeFndM$O|$sg?knG0@!V8c?~EB=k*_uVE%H`; zMc#_9$XoFhc`KeGZ~0&3Eqk4X_4k_Vw-oqVbNwQ3$rpJm-Xg!rjIV?@?Rg6JEd3&X z#QL z%y|`9Tw~b0L$Xh1^lF2CutWCBwDP(PExmShn_>&vG8Mt{%(8Qb$7$|0nY+8fvapJ@ zHz&k%BbZs7>F=ucaR*7OnkkbW*5`+~L&CU|_gv>uZdaDc{4bq#`x+L=*-`GfvV)F8 zqB#rFv3{i1ne9aJLH}+LHRT<%263uJ+adyJ?r&RV^ zY5sc5Uzhn?le67u+D@cy-Y&>aDr4KVdU}gLmt7BFBQl(nsgz8aNHTRT~bheg9%3HkP z{$N(Ja>~)_SZi+~%{|Gtgw^-o!F>WyfLj4plXsendwl@evpU721!^xSwo@O$nBVpH zs>NN8`$eI9+*#172W9Q`M)N(huu_H3Z2|u>nY;xY#Z4>O>$z`tj}MLTD9Lc$*Rj}k~&!4x9yACvCBEhDSP`n`m14OzbUhD zql?_B`94U(uTgU@gnQAqhq;6Jf()w;ZnF+;lhGviW3TLJF|wm(6f1Zho_A8@OmPPqmj8f+bWb&wugiX6UY@QB%++KH}p6*?Se z_BYmxoT;iv9eU912Cvk1?P;b!`B`VA12d1#v5(~Q^Uyq zY?6z3qE2-=?#Yf6N%VM)yj8o0GqTYse)vvZm?Uzf8h2F$otayL<)h^|WmhN7Hy1q3 zM)n<}>|CkV%{i^}sE-?Kd~Fg{*Un8iB3C6vnfZVYf!d}g$;-E>=iT^EN@H0ZwKgVdfGcDlU(A5M^lPdI*wMo)`IuXRa@X7(~ z4c2XNcBs6v7iUN)_0Vu7_VUB}5;wPOPrAbA8kdBhOsculLH$*Y!yG!fQVn?~DgkD+D@)oEnP*$IrYf3U(6Gw2K z<1DvwS%r1GkxQI=xqdm<{7wfi-?=KsZJvGI65odM+fB$^pFr`B|eLwW;L9@Lv7klT) zsX%i7cqMNOa;Hgjt44MhJNdU$&Lp?|(pyHhdK%}-v}zTQO6h4oUbN&HRv~T^nB2n96hf@#$6&ar$nZzM5dxdhVA)oi5*{w9kImD;u4vKB{DT7GAx$7&n%XFTr8G+Tr8Hn42vZ%!(z$H zFrU8gmd?fwiT|wHng?x)*cf`VK0zHA3uhO|7 zEt?$m)NtWM^CJB3=XT%$;6b4Dd7#Nfj{r{s`+!5h2=FUl6nG2xEARo3e}cFxdx4Ju zE`S3*y4gkV0)GZh0VjY`9oA>AVfVS*!}``C-~k{GJPbSmJPjNG^3OY<%UfKu0QdsV zrg8AoKo;OJH-_;7kbgdgJBth8ff2mV0vCWk0jGcyz{^0XZ|t7)9Iz8$YkVE!mw~Oo zKHwf82IQaSRu|m>tOo8Ne=tfOAR z?uqsFQoOHkYabTw?dqUdcXvKH7{Af(q5)tF5Cc93tOY&;Tn_{RFHl;867~No*$8VN zUxU4X{rDF4sTXyuMvYehYk+e2@gVR=;MH|5YG04{x47u{KIr~kO#?Ku+fSs8q`McqAq MGC(&!fBm2T1#!eoE&u=k diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/LICENSE.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/LICENSE.txt deleted file mode 100644 index e69de29..0000000 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/README.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/README.md deleted file mode 100644 index d32afdc..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino deleted file mode 100644 index 4820f2e..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/examples/DHTtester/DHTtester.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/examples/DHTtester/DHTtester.ino deleted file mode 100644 index ae6c41a..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/keywords.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/keywords.txt deleted file mode 100644 index 146d4fa..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/library.properties b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/library.properties deleted file mode 100644 index 8c247f5..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=DHT -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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT.cpp deleted file mode 100644 index 86ad91c..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT.h deleted file mode 100644 index d81f6db..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT_U.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT_U.cpp deleted file mode 100644 index efc7963..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT_U.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/DHT_U.h deleted file mode 100644 index fcf66ad..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/DHT/src/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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/LICENSE.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/LICENSE.md deleted file mode 100644 index 557757f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2011..2017 Bill Greiman - -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. \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/README.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/README.md deleted file mode 100644 index 606fd97..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/README.md +++ /dev/null @@ -1,42 +0,0 @@ -The Arduino SdFat library provides read/write access to FAT16/FAT32 -file systems on SD/SDHC flash cards. - -SdFat requires Arduino 1.6x or greater. - -Key changes: - -Support for multiple SPI ports now uses a pointer to a SPIClass object. - -See the STM32Test example. -``` -explicit SdFat(SPIClass* spiPort); -\\ or -explicit SdFatEX(SPIClass* spiPort); -``` - -Open flags now follow POSIX conventions. O_RDONLY is the same as O_READ and O_WRONLY is the -same as O_WRITE. One and only one of of the mode flags, O_RDONLY, O_RDWR, or -O_WRONLY is required. - -Open flags for Particle Gen3 and ARM boards are now defined by fcntl.h. -See SdFatConfig.h for options. - -Support for particle Gen3 devices. - -New cluster allocation algorithm. - -Please read changes.txt and the html documentation in the extras folder for more information. - -Please report problems as issues. - -A number of configuration options can be set by editing SdFatConfig.h -define macros. See the html documentation for details - -Please read the html documentation for this library. Start with -html/index.html and read the Main Page. Next go to the Classes tab and -read the documentation for the classes SdFat, SdFatEX, SdBaseFile, -SdFile, File, StdioStream, ifstream, ofstream, and others. - -Please continue by reading the html documentation in SdFat/extras/html - -Updated 28 Dec 2018 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/AnalogLogger/AnalogLogger.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/AnalogLogger/AnalogLogger.ino deleted file mode 100644 index b65c5ab..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/AnalogLogger/AnalogLogger.ino +++ /dev/null @@ -1,197 +0,0 @@ -// A simple data logger for the Arduino analog pins with optional DS1307 -// uses RTClib from https://github.com/adafruit/RTClib -#include -#include "SdFat.h" -#include "sdios.h" -#include "FreeStack.h" - -#define SD_CHIP_SELECT SS // SD chip select pin -#define USE_DS1307 0 // set nonzero to use DS1307 RTC -#define LOG_INTERVAL 1000 // mills between entries -#define SENSOR_COUNT 3 // number of analog pins to log -#define ECHO_TO_SERIAL 1 // echo data to serial port if nonzero -#define WAIT_TO_START 1 // Wait for serial input in setup() -#define ADC_DELAY 10 // ADC delay for high impedence sensors - -// file system object -SdFat sd; - -// text file for logging -ofstream logfile; - -// Serial print stream -ArduinoOutStream cout(Serial); - -// buffer to format data - makes it eaiser to echo to Serial -char buf[80]; -//------------------------------------------------------------------------------ -#if SENSOR_COUNT > 6 -#error SENSOR_COUNT too large -#endif // SENSOR_COUNT -//------------------------------------------------------------------------------ -// store error strings in flash to save RAM -#define error(s) sd.errorHalt(F(s)) -//------------------------------------------------------------------------------ -#if USE_DS1307 -// use RTClib from Adafruit -// https://github.com/adafruit/RTClib - -// The Arduino IDE has a bug that causes Wire and RTClib to be loaded even -// if USE_DS1307 is false. - -#error remove this line and uncomment the next two lines. -//#include -//#include -RTC_DS1307 RTC; // define the Real Time Clock object -//------------------------------------------------------------------------------ -// call back for file timestamps -void dateTime(uint16_t* date, uint16_t* time) { - DateTime now = RTC.now(); - - // return date using FAT_DATE macro to format fields - *date = FAT_DATE(now.year(), now.month(), now.day()); - - // return time using FAT_TIME macro to format fields - *time = FAT_TIME(now.hour(), now.minute(), now.second()); -} -//------------------------------------------------------------------------------ -// format date/time -ostream& operator << (ostream& os, DateTime& dt) { - os << dt.year() << '/' << int(dt.month()) << '/' << int(dt.day()) << ','; - os << int(dt.hour()) << ':' << setfill('0') << setw(2) << int(dt.minute()); - os << ':' << setw(2) << int(dt.second()) << setfill(' '); - return os; -} -#endif // USE_DS1307 -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - - // Wait for USB Serial. - while (!Serial) { - SysCall::yield(); - } - // F() stores strings in flash to save RAM - cout << endl << F("FreeStack: ") << FreeStack() << endl; - -#if WAIT_TO_START - cout << F("Type any character to start\n"); - while (!Serial.available()) { - SysCall::yield(); - } - // Discard input. - do { - delay(10); - } while(Serial.available() && Serial.read() >= 0); -#endif // WAIT_TO_START - -#if USE_DS1307 - // connect to RTC - Wire.begin(); - if (!RTC.begin()) { - error("RTC failed"); - } - - // set date time callback function - SdFile::dateTimeCallback(dateTime); - DateTime now = RTC.now(); - cout << now << endl; -#endif // USE_DS1307 - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(SD_CHIP_SELECT, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } - - // create a new file in root, the current working directory - char name[] = "logger00.csv"; - - for (uint8_t i = 0; i < 100; i++) { - name[6] = i/10 + '0'; - name[7] = i%10 + '0'; - if (sd.exists(name)) { - continue; - } - logfile.open(name); - break; - } - if (!logfile.is_open()) { - error("file.open"); - } - - cout << F("Logging to: ") << name << endl; - cout << F("Type any character to stop\n\n"); - - // format header in buffer - obufstream bout(buf, sizeof(buf)); - - bout << F("millis"); - -#if USE_DS1307 - bout << F(",date,time"); -#endif // USE_DS1307 - - for (uint8_t i = 0; i < SENSOR_COUNT; i++) { - bout << F(",sens") << int(i); - } - logfile << buf << endl; - -#if ECHO_TO_SERIAL - cout << buf << endl; -#endif // ECHO_TO_SERIAL -} -//------------------------------------------------------------------------------ -void loop() { - uint32_t m; - - // wait for time to be a multiple of interval - do { - m = millis(); - } while (m % LOG_INTERVAL); - - // use buffer stream to format line - obufstream bout(buf, sizeof(buf)); - - // start with time in millis - bout << m; - -#if USE_DS1307 - DateTime now = RTC.now(); - bout << ',' << now; -#endif // USE_DS1307 - - // read analog pins and format data - for (uint8_t ia = 0; ia < SENSOR_COUNT; ia++) { -#if ADC_DELAY - analogRead(ia); - delay(ADC_DELAY); -#endif // ADC_DELAY - bout << ',' << analogRead(ia); - } - bout << endl; - - // log data and flush to SD - logfile << buf << flush; - - // check for error - if (!logfile) { - error("write data failed"); - } - -#if ECHO_TO_SERIAL - cout << buf; -#endif // ECHO_TO_SERIAL - - // don't log two points in the same millis - if (m == millis()) { - delay(1); - } - - if (!Serial.available()) { - return; - } - logfile.close(); - cout << F("Done!"); - SysCall::halt(); -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/BaseExtCaseTest/BaseExtCaseTest.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/BaseExtCaseTest/BaseExtCaseTest.ino deleted file mode 100644 index 0212d3b..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/BaseExtCaseTest/BaseExtCaseTest.ino +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Program to test Short File Name character case flags. - */ -#include -#include "SdFat.h" - -const uint8_t chipSelect = SS; - -SdFat sd; - -SdFile file; -const char* name[] = { - "low.low", "low.Mix", "low.UP", - "Mix.low", "Mix.Mix", "Mix.UP", - "UP.low", "UP.Mix", "UP.UP" -}; -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - Serial.println("type any character to start"); - while (!Serial.available()) { - SysCall::yield(); - } - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - Serial.println("begin failed"); - return; - } - for (uint8_t i = 0; i < 9; i++) { - sd.remove(name[i]); - if (!file.open(name[i], O_RDWR | O_CREAT | O_EXCL)) { - sd.errorHalt(name[i]); - } - file.println(name[i]); - - file.close(); - } - sd.ls(LS_DATE|LS_SIZE); - Serial.println("Done"); -} -//------------------------------------------------------------------------------ -void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/HelloWorld/HelloWorld.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/HelloWorld/HelloWorld.ino deleted file mode 100644 index 2540b06..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/HelloWorld/HelloWorld.ino +++ /dev/null @@ -1,20 +0,0 @@ -#include -#include "SdFat.h" -#include "sdios.h" - -// create a serial output stream -ArduinoOutStream cout(Serial); - -void setup() { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - delay(2000); - - cout << "Hello, World!\n"; -} - -void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/MiniSerial/MiniSerial.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/MiniSerial/MiniSerial.ino deleted file mode 100644 index f8270b6..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/MiniSerial/MiniSerial.ino +++ /dev/null @@ -1,29 +0,0 @@ -// This example illustrates use of SdFat's -// minimal unbuffered AVR Serial support. -// -// This is useful for debug and saves RAM -// Will not work on Due, Leonardo, or Teensy - -#include -#include "SdFat.h" -#include "FreeStack.h" -#ifdef UDR0 // Must be AVR with serial port zero. -#include "MinimumSerial.h" - -MinimumSerial MiniSerial; - -void setup() { - MiniSerial.begin(9600); - MiniSerial.println(FreeStack()); -} -void loop() { - int c; - MiniSerial.println(F("Type any Character")); - while ((c = MiniSerial.read()) < 0) {} - MiniSerial.print(F("Read: ")); - MiniSerial.println((char)c); - while (MiniSerial.read() >= 0) {} -} -#else // UDR0 -#error no AVR serial port 0 -#endif // UDR0 \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/PrintBenchmarkSD/PrintBenchmarkSD.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/PrintBenchmarkSD/PrintBenchmarkSD.ino deleted file mode 100644 index 650caeb..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/PrintBenchmarkSD/PrintBenchmarkSD.ino +++ /dev/null @@ -1,125 +0,0 @@ -/* - * This program is a simple Print benchmark. - */ -#include -#include - -// SD chip select pin -const uint8_t chipSelect = SS; - -// number of lines to print -const uint16_t N_PRINT = 20000; - - -// test file -File file; - -//------------------------------------------------------------------------------ -void error(const char* s) { - Serial.println(s); - while (1) { - yield(); - } -} -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - yield(); - } -} -//------------------------------------------------------------------------------ -void loop() { - uint32_t maxLatency; - uint32_t minLatency; - uint32_t totalLatency; - - // Read any existing Serial data. - do { - delay(10); - } while (Serial.available() && Serial.read() >= 0); - - // F() stores strings in flash to save RAM - Serial.println(F("Type any character to start")); - while (!Serial.available()) { - yield(); - } - - // initialize the SD card - if (!SD.begin(chipSelect)) { - error("begin"); - } - - Serial.println(F("Starting print test. Please wait.\n")); - - // do write test - for (int test = 0; test < 2; test++) { - file = SD.open("bench.txt", FILE_WRITE); - - if (!file) { - error("open failed"); - } - switch(test) { - case 0: - Serial.println(F("Test of println(uint16_t)")); - break; - - case 1: - Serial.println(F("Test of println(double)")); - break; - } - maxLatency = 0; - minLatency = 999999; - totalLatency = 0; - uint32_t t = millis(); - for (uint16_t i = 0; i < N_PRINT; i++) { - uint32_t m = micros(); - - switch(test) { - case 0: - file.println(i); - break; - - case 1: - file.println((double)0.01*i); - break; - } - - if (file.getWriteError()) { - error("write failed"); - } - m = micros() - m; - if (maxLatency < m) { - maxLatency = m; - } - if (minLatency > m) { - minLatency = m; - } - totalLatency += m; - } - file.flush(); - t = millis() - t; - double s = file.size(); - Serial.print(F("Time ")); - Serial.print(0.001*t); - Serial.println(F(" sec")); - Serial.print(F("File size ")); - Serial.print(0.001*s); - Serial.print(F(" KB\n")); - Serial.print(F("Write ")); - Serial.print(s/t); - Serial.print(F(" KB/sec\n")); - Serial.print(F("Maximum latency: ")); - Serial.print(maxLatency); - Serial.print(F(" usec, Minimum Latency: ")); - Serial.print(minLatency); - Serial.print(F(" usec, Avg Latency: ")); - Serial.print(totalLatency/N_PRINT); - Serial.println(F(" usec\n")); - SD.remove("bench.txt"); - } - file.close(); - Serial.println(F("Done!\n")); -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/SD_Size/SD_Size.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/SD_Size/SD_Size.ino deleted file mode 100644 index 8d27c6d..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/SD_Size/SD_Size.ino +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Program to compare size of Arduino SD library with SdFat. - * See SdFatSize.ino for SdFat program. - */ -#include -#include - -File file; -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - yield(); - } - - if (!SD.begin()) { - Serial.println("begin failed"); - return; - } - file = SD.open("TEST_SD.TXT", FILE_WRITE); - - file.println("Hello"); - - file.close(); - Serial.println("Done"); -} -//------------------------------------------------------------------------------ -void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/SdFatSize/SdFatSize.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/SdFatSize/SdFatSize.ino deleted file mode 100644 index b44d617..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/SdFatSize/SdFatSize.ino +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Program to compare size of SdFat with Arduino SD library. - * See SD_Size.ino for Arduino SD program. - * - */ -#include -#include "SdFat.h" - -SdFat sd; - -SdFile file; -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - - if (!sd.begin()) { - Serial.println("begin failed"); - return; - } - file.open("SizeTest.txt", O_RDWR | O_CREAT | O_AT_END); - - file.println("Hello"); - - file.close(); - Serial.println("Done"); -} -//------------------------------------------------------------------------------ -void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/StreamParseInt/StreamParseInt.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/StreamParseInt/StreamParseInt.ino deleted file mode 100644 index 2da1f7c..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/StreamParseInt/StreamParseInt.ino +++ /dev/null @@ -1,44 +0,0 @@ -// Simple demo of the Stream parsInt() member function. -#include -// The next two lines replace #include . -#include "SdFat.h" -SdFat SD; - -// SD card chip select pin - Modify the value of csPin for your SD module. -const uint8_t csPin = SS; - -File file; -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - // Wait for USB Serial. - while(!Serial) { - SysCall::yield(); - } - Serial.println(F("Type any character to start")); - while (!Serial.available()) { - SysCall::yield(); - } - // Initialize the SD. - if (!SD.begin(csPin)) { - Serial.println(F("begin error")); - return; - } - // Create and open the file. Use flag to truncate an existing file. - file = SD.open("stream.txt", O_RDWR|O_CREAT|O_TRUNC); - if (!file) { - Serial.println(F("open error")); - return; - } - // Write a test number to the file. - file.println("12345"); - - // Rewind the file and read the number with parseInt(). - file.seek(0); - int i = file.parseInt(); - Serial.print(F("parseInt: ")); - Serial.println(i); - file.close(); -} - -void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/append/append.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/append/append.ino deleted file mode 100644 index 291fcdc..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/append/append.ino +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Append Example - * - * This program shows how to use open for append. - * The program will append 100 line each time it opens the file. - * The program will open and close the file 100 times. - */ -#include -#include "SdFat.h" -#include "sdios.h" - -// SD chip select pin -const uint8_t chipSelect = SS; - -// file system object -SdFat sd; - -// create Serial stream -ArduinoOutStream cout(Serial); - -// store error strings in flash to save RAM -#define error(s) sd.errorHalt(F(s)) -//------------------------------------------------------------------------------ -void setup() { - // filename for this example - char name[] = "append.txt"; - - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - // F() stores strings in flash to save RAM - cout << endl << F("Type any character to start\n"); - while (!Serial.available()) { - SysCall::yield(); - } - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } - - cout << F("Appending to: ") << name; - - for (uint8_t i = 0; i < 100; i++) { - // open stream for append - ofstream sdout(name, ios::out | ios::app); - if (!sdout) { - error("open failed"); - } - - // append 100 lines to the file - for (uint8_t j = 0; j < 100; j++) { - // use int() so byte will print as decimal number - sdout << "line " << int(j) << " of pass " << int(i); - sdout << " millis = " << millis() << endl; - } - // close the stream - sdout.close(); - - if (!sdout) { - error("append data failed"); - } - - // output progress indicator - if (i % 25 == 0) { - cout << endl; - } - cout << '.'; - } - cout << endl << "Done" << endl; -} -//------------------------------------------------------------------------------ -void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/average/average.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/average/average.ino deleted file mode 100644 index 32c4c84..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/average/average.ino +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Calculate the sum and average of a list of floating point numbers - */ -#include -#include "SdFat.h" -#include "sdios.h" - -// SD chip select pin -const uint8_t chipSelect = SS; - -// object for the SD file system -SdFat sd; - -// define a serial output stream -ArduinoOutStream cout(Serial); -//------------------------------------------------------------------------------ -void writeTestFile() { - // open the output file - ofstream sdout("AvgTest.txt"); - - // write a series of float numbers - for (int16_t i = -1001; i < 2000; i += 13) { - sdout << 0.1 * i << endl; - } - if (!sdout) { - sd.errorHalt("sdout failed"); - } - - sdout.close(); -} -//------------------------------------------------------------------------------ -void calcAverage() { - uint16_t n = 0; // count of input numbers - double num; // current input number - double sum = 0; // sum of input numbers - - // open the input file - ifstream sdin("AvgTest.txt"); - - // check for an open failure - if (!sdin) { - sd.errorHalt("sdin failed"); - } - - // read and sum the numbers - while (sdin >> num) { - n++; - sum += num; - } - - // print the results - cout << "sum of " << n << " numbers = " << sum << endl; - cout << "average = " << sum/n << endl; -} -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - // F() stores strings in flash to save RAM - cout << F("Type any character to start\n"); - while (!Serial.available()) { - SysCall::yield(); - } - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } - - // write the test file - writeTestFile(); - - // read the test file and calculate the average - calcAverage(); -} -//------------------------------------------------------------------------------ -void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/benchSD/benchSD.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/benchSD/benchSD.ino deleted file mode 100644 index cffef28..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/benchSD/benchSD.ino +++ /dev/null @@ -1,149 +0,0 @@ -/* - * This program is a simple binary write/read benchmark - * for the standard Arduino SD.h library. - */ -#include -#include - -// SD chip select pin -const uint8_t chipSelect = SS; - -#define FILE_SIZE_MB 5 -#define FILE_SIZE (1000000UL*FILE_SIZE_MB) -#define BUF_SIZE 100 - -uint8_t buf[BUF_SIZE]; - -// test file -File file; - -//------------------------------------------------------------------------------ -void error(const char* s) { - Serial.println(s); - while (1) { - yield(); - } -} -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - yield(); - } -} -//------------------------------------------------------------------------------ -void loop() { - uint32_t maxLatency; - uint32_t minLatency; - uint32_t totalLatency; - - // Discard any input. - do { - delay(10); - } while (Serial.available() && Serial.read() >= 0); - - // F() stores strings in flash to save RAM - Serial.println(F("Type any character to start")); - - while (!Serial.available()) { - yield(); - } - if (!SD.begin(chipSelect)) { - error("begin"); - } - - // open or create file - truncate existing file. - file = SD.open("Bench.dat", O_RDWR | O_TRUNC | O_CREAT); - if (!file) { - error("open failed"); - } - - // fill buf with known data - for (uint16_t i = 0; i < (BUF_SIZE-2); i++) { - buf[i] = 'A' + (i % 26); - } - buf[BUF_SIZE-2] = '\r'; - buf[BUF_SIZE-1] = '\n'; - - Serial.print(F("File size ")); - Serial.print(FILE_SIZE_MB); - Serial.println(F("MB")); - Serial.print(F("Buffer size ")); - Serial.print(BUF_SIZE); - Serial.println(F(" bytes")); - Serial.println(F("Starting write test. Please wait up to a minute")); - - // do write test - uint32_t n = FILE_SIZE/sizeof(buf); - maxLatency = 0; - minLatency = 999999; - totalLatency = 0; - uint32_t t = millis(); - for (uint32_t i = 0; i < n; i++) { - uint32_t m = micros(); - if (file.write(buf, sizeof(buf)) != sizeof(buf)) { - error("write failed"); - } - m = micros() - m; - if (maxLatency < m) { - maxLatency = m; - } - if (minLatency > m) { - minLatency = m; - } - totalLatency += m; - } - file.flush(); - t = millis() - t; - double s = file.size(); - Serial.print(F("Write ")); - Serial.print(s/t); - Serial.print(F(" KB/sec\n")); - Serial.print(F("Maximum latency: ")); - Serial.print(maxLatency); - Serial.print(F(" usec, Minimum Latency: ")); - Serial.print(minLatency); - Serial.print(F(" usec, Avg Latency: ")); - Serial.print(totalLatency/n); - Serial.print(F(" usec\n\n")); - Serial.println(F("Starting read test. Please wait up to a minute")); - // do read test - file.seek(0); - maxLatency = 0; - minLatency = 99999; - totalLatency = 0; - t = millis(); - for (uint32_t i = 0; i < n; i++) { - buf[BUF_SIZE-1] = 0; - uint32_t m = micros(); - if (file.read(buf, sizeof(buf)) != sizeof(buf)) { - error("read failed"); - } - m = micros() - m; - if (maxLatency < m) { - maxLatency = m; - } - if (minLatency > m) { - minLatency = m; - } - totalLatency += m; - if (buf[BUF_SIZE-1] != '\n') { - error("data check"); - } - } - t = millis() - t; - Serial.print(F("Read ")); - Serial.print(s/t); - Serial.print(F(" KB/sec\n")); - Serial.print(F("Maximum latency: ")); - Serial.print(maxLatency); - Serial.print(F(" usec, Minimum Latency: ")); - Serial.print(minLatency); - Serial.print(F(" usec, Avg Latency: ")); - Serial.print(totalLatency/n); - Serial.print(F(" usec\n\n")); - Serial.print(F("Done\n\n")); - file.close(); -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/bufstream/bufstream.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/bufstream/bufstream.ino deleted file mode 100644 index eda0f1a..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/bufstream/bufstream.ino +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Use of ibufsteam to parse a line and obufstream to format a line - */ -#include -#include "SdFat.h" -#include "sdios.h" - -// create a serial output stream -ArduinoOutStream cout(Serial); -//------------------------------------------------------------------------------ -void setup() { - char buf[20]; // buffer for formatted line - int i, j, k; // values from parsed line - - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - delay(2000); - - // initialize input string - ibufstream bin("123 456 789"); - - // parse the string "123 456 789" - bin >> i >> j >> k; - - // initialize output buffer - obufstream bout(buf, sizeof(buf)); - - // format the output string - bout << k << ',' << j << ',' << i << endl; - - // write the string to serial - cout << buf; -} - -void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/cin_cout/cin_cout.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/cin_cout/cin_cout.ino deleted file mode 100644 index 30e49ef..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/cin_cout/cin_cout.ino +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Demo of ArduinoInStream and ArduinoOutStream - */ -#include -#include "SdFat.h" -#include "sdios.h" - -// create serial output stream -ArduinoOutStream cout(Serial); - -// input line buffer -char cinBuf[40]; - -// create serial input stream -ArduinoInStream cin(Serial, cinBuf, sizeof(cinBuf)); -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } -} -//------------------------------------------------------------------------------ -void loop() { - int32_t n = 0; - - cout << "\nenter an integer\n"; - - cin.readline(); - - if (cin >> n) { - cout << "The number is: " << n; - } else { - // will fail if no digits or not in range [-2147483648, 2147483647] - cout << "Invalid input: " << cinBuf; - } - cout << endl; -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/eventlog/eventlog.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/eventlog/eventlog.ino deleted file mode 100644 index e295a32..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/eventlog/eventlog.ino +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Append a line to a file - demo of pathnames and streams - */ -#include -#include "SdFat.h" -#include "sdios.h" -// SD chip select pin -const uint8_t chipSelect = SS; - -// file system object -SdFat sd; - -// define a serial output stream -ArduinoOutStream cout(Serial); -//------------------------------------------------------------------------------ -/* - * Append a line to logfile.txt - */ -void logEvent(const char *msg) { - // create dir if needed - sd.mkdir("logs/2014/Jan"); - - // create or open a file for append - ofstream sdlog("logs/2014/Jan/logfile.txt", ios::out | ios::app); - - // append a line to the file - sdlog << msg << endl; - - // check for errors - if (!sdlog) { - sd.errorHalt("append failed"); - } - - sdlog.close(); -} -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - // F() stores strings in flash to save RAM - cout << F("Type any character to start\n"); - while (!Serial.available()) { - SysCall::yield(); - } - delay(400); // catch Due reset problem - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } - - // append a line to the logfile - logEvent("Another line for the logfile"); - - cout << F("Done - check /logs/2014/Jan/logfile.txt on the SD") << endl; -} -//------------------------------------------------------------------------------ -void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/fgetsRewrite/fgetsRewrite.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/fgetsRewrite/fgetsRewrite.ino deleted file mode 100644 index 41a3730..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/fgetsRewrite/fgetsRewrite.ino +++ /dev/null @@ -1,111 +0,0 @@ -// Demo of rewriting a line read by fgets -#include -#include "SdFat.h" -#include "sdios.h" - -// SD card chip select pin -const uint8_t chipSelect = SS; - -// file system -SdFat sd; - -// print stream -ArduinoOutStream cout(Serial); -//------------------------------------------------------------------------------ -// store error strings in flash memory -#define error(s) sd.errorHalt(F(s)) -//------------------------------------------------------------------------------ -void demoFgets() { - char line[25]; - int c; - uint32_t pos; - - // open test file - SdFile rdfile("fgets.txt", O_RDWR); - - // check for open error - if (!rdfile.isOpen()) { - error("demoFgets"); - } - - // list file - cout << F("-----Before Rewrite\r\n"); - while ((c = rdfile.read()) >= 0) { - Serial.write(c); - } - - rdfile.rewind(); - // read lines from the file to get position - while (1) { - pos = rdfile.curPosition(); - if (rdfile.fgets(line, sizeof(line)) < 0) { - error("Line not found"); - } - // find line that contains "Line C" - if (strstr(line, "Line C")) { - break; - } - } - - // rewrite line with 'C' - if (!rdfile.seekSet(pos)) { - error("seekSet"); - } - rdfile.println("Line R"); - rdfile.rewind(); - - // list file - cout << F("\r\n-----After Rewrite\r\n"); - while ((c = rdfile.read()) >= 0) { - Serial.write(c); - } - - // close so rewrite is not lost - rdfile.close(); -} -//------------------------------------------------------------------------------ -void makeTestFile() { - // create or open test file - SdFile wrfile("fgets.txt", O_WRONLY | O_CREAT | O_TRUNC); - - // check for open error - if (!wrfile.isOpen()) { - error("MakeTestFile"); - } - - // write test file - wrfile.print(F( - "Line A\r\n" - "Line B\r\n" - "Line C\r\n" - "Line D\r\n" - "Line E\r\n" - )); - wrfile.close(); -} -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - cout << F("Type any character to start\n"); - while (!Serial.available()) { - SysCall::yield(); - } - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } - - makeTestFile(); - - demoFgets(); - - cout << F("\nDone\n"); -} -void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/readlog/readlog.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/readlog/readlog.ino deleted file mode 100644 index ca72cf9..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/readlog/readlog.ino +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Read the logfile created by the eventlog.ino example. - * Demo of pathnames and working directories - */ -#include -#include "SdFat.h" -#include "sdios.h" - -// SD chip select pin -const uint8_t chipSelect = SS; - -// file system object -SdFat sd; - -// define a serial output stream -ArduinoOutStream cout(Serial); -//------------------------------------------------------------------------------ -void setup() { - int c; - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } - - // set current working directory - if (!sd.chdir("logs/2014/Jan/")) { - sd.errorHalt("chdir failed. Did you run eventlog.ino?"); - } - // open file in current working directory - ifstream file("logfile.txt"); - - if (!file.is_open()) { - sd.errorHalt("open failed"); - } - - // copy the file to Serial - while ((c = file.get()) >= 0) { - cout << (char)c; - } - - cout << "Done" << endl; -} -//------------------------------------------------------------------------------ -void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/readme.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/readme.txt deleted file mode 100644 index 1943dcd..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/#attic/readme.txt +++ /dev/null @@ -1,34 +0,0 @@ -Old and debug examples. - -AnalogLogger - A simple data logger for one or more analog pins. - -append - This sketch creates a large file by successive - open/write/close operations. - -average - A demonstration of parsing floating point numbers. - -BaseExtCaseTest - Long file name test. - -benchSD - A read/write benchmark for the standard Arduino SD.h library. - -bufstream - ibufsteam to parse a line and obufstream to format a line. - -cin_cout - Demo of ArduinoInStream and ArduinoOutStream. - -eventlog - Append a line to a file - demo of pathnames and streams. - -fgetsRewrite - Demo of rewriting a line read by fgets. - -HelloWorld - Create a serial output stream. - -MiniSerial - SdFat minimal serial support for debug. - -PrintBenchmarkSD - Bench mark SD.h print. - -readlog - Read file. Demo of pathnames and current working directory. - -SD_Size - Determine flash used by SD.h example. - -SdFatSize - Determine flash used by SdFat. - -StreamParseInt - Simple demo of the Stream parsInt() member function. diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/AnalogBinLogger/AnalogBinLogger.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/AnalogBinLogger/AnalogBinLogger.h deleted file mode 100644 index a793e2d..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/AnalogBinLogger/AnalogBinLogger.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef AnalogBinLogger_h -#define AnalogBinLogger_h -//------------------------------------------------------------------------------ -// First block of file. -struct metadata_t { - unsigned long adcFrequency; // ADC clock frequency - unsigned long cpuFrequency; // CPU clock frequency - unsigned long sampleInterval; // Sample interval in CPU cycles. - unsigned long recordEightBits; // Size of ADC values, nonzero for 8-bits. - unsigned long pinCount; // Number of analog pins in a sample. - unsigned long pinNumber[123]; // List of pin numbers in a sample. -}; -//------------------------------------------------------------------------------ -// Data block for 8-bit ADC mode. -const size_t DATA_DIM8 = 508; -struct block8_t { - unsigned short count; // count of data values - unsigned short overrun; // count of overruns since last block - unsigned char data[DATA_DIM8]; -}; -//------------------------------------------------------------------------------ -// Data block for 10-bit ADC mode. -const size_t DATA_DIM16 = 254; -struct block16_t { - unsigned short count; // count of data values - unsigned short overrun; // count of overruns since last block - unsigned short data[DATA_DIM16]; -}; -//------------------------------------------------------------------------------ -// Data block for PC use -struct adcdata_t { - unsigned short count; // count of data values - unsigned short overrun; // count of overruns since last block - union { - unsigned char u8[DATA_DIM8]; - unsigned short u16[DATA_DIM16]; - } data; -}; -#endif // AnalogBinLogger_h \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/AnalogBinLogger/AnalogBinLogger.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/AnalogBinLogger/AnalogBinLogger.ino deleted file mode 100644 index 67cf62b..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/AnalogBinLogger/AnalogBinLogger.ino +++ /dev/null @@ -1,826 +0,0 @@ -/** - * This program logs data from the Arduino ADC to a binary file. - * - * Samples are logged at regular intervals. Each Sample consists of the ADC - * values for the analog pins defined in the PIN_LIST array. The pins numbers - * may be in any order. - * - * Edit the configuration constants below to set the sample pins, sample rate, - * and other configuration values. - * - * If your SD card has a long write latency, it may be necessary to use - * slower sample rates. Using a Mega Arduino helps overcome latency - * problems since 13 512 byte buffers will be used. - * - * Each 512 byte data block in the file has a four byte header followed by up - * to 508 bytes of data. (508 values in 8-bit mode or 254 values in 10-bit mode) - * Each block contains an integral number of samples with unused space at the - * end of the block. - * - * Data is written to the file using a SD multiple block write command. - */ -#ifdef __AVR__ -#include -#include "SdFat.h" -#include "FreeStack.h" -#include "AnalogBinLogger.h" -//------------------------------------------------------------------------------ -// Analog pin number list for a sample. Pins may be in any order and pin -// numbers may be repeated. -const uint8_t PIN_LIST[] = {0, 1, 2, 3, 4}; -//------------------------------------------------------------------------------ -// Sample rate in samples per second. -const float SAMPLE_RATE = 5000; // Must be 0.25 or greater. - -// The interval between samples in seconds, SAMPLE_INTERVAL, may be set to a -// constant instead of being calculated from SAMPLE_RATE. SAMPLE_RATE is not -// used in the code below. For example, setting SAMPLE_INTERVAL = 2.0e-4 -// will result in a 200 microsecond sample interval. -const float SAMPLE_INTERVAL = 1.0/SAMPLE_RATE; - -// Setting ROUND_SAMPLE_INTERVAL non-zero will cause the sample interval to -// be rounded to a a multiple of the ADC clock period and will reduce sample -// time jitter. -#define ROUND_SAMPLE_INTERVAL 1 -//------------------------------------------------------------------------------ -// ADC clock rate. -// The ADC clock rate is normally calculated from the pin count and sample -// interval. The calculation attempts to use the lowest possible ADC clock -// rate. -// -// You can select an ADC clock rate by defining the symbol ADC_PRESCALER to -// one of these values. You must choose an appropriate ADC clock rate for -// your sample interval. -// #define ADC_PRESCALER 7 // F_CPU/128 125 kHz on an Uno -// #define ADC_PRESCALER 6 // F_CPU/64 250 kHz on an Uno -// #define ADC_PRESCALER 5 // F_CPU/32 500 kHz on an Uno -// #define ADC_PRESCALER 4 // F_CPU/16 1000 kHz on an Uno -// #define ADC_PRESCALER 3 // F_CPU/8 2000 kHz on an Uno (8-bit mode only) -//------------------------------------------------------------------------------ -// Reference voltage. See the processor data-sheet for reference details. -// uint8_t const ADC_REF = 0; // External Reference AREF pin. -uint8_t const ADC_REF = (1 << REFS0); // Vcc Reference. -// uint8_t const ADC_REF = (1 << REFS1); // Internal 1.1 (only 644 1284P Mega) -// uint8_t const ADC_REF = (1 << REFS1) | (1 << REFS0); // Internal 1.1 or 2.56 -//------------------------------------------------------------------------------ -// File definitions. -// -// Maximum file size in blocks. -// The program creates a contiguous file with FILE_BLOCK_COUNT 512 byte blocks. -// This file is flash erased using special SD commands. The file will be -// truncated if logging is stopped early. -const uint32_t FILE_BLOCK_COUNT = 256000; - -// log file base name. Must be six characters or less. -#define FILE_BASE_NAME "analog" - -// Set RECORD_EIGHT_BITS non-zero to record only the high 8-bits of the ADC. -#define RECORD_EIGHT_BITS 0 -//------------------------------------------------------------------------------ -// Pin definitions. -// -// Digital pin to indicate an error, set to -1 if not used. -// The led blinks for fatal errors. The led goes on solid for SD write -// overrun errors and logging continues. -const int8_t ERROR_LED_PIN = 3; - -// SD chip select pin. -const uint8_t SD_CS_PIN = SS; -//------------------------------------------------------------------------------ -// Buffer definitions. -// -// The logger will use SdFat's buffer plus BUFFER_BLOCK_COUNT additional -// buffers. QUEUE_DIM must be a power of two larger than -//(BUFFER_BLOCK_COUNT + 1). -// -#if RAMEND < 0X8FF -#error Too little SRAM -// -#elif RAMEND < 0X10FF -// Use total of two 512 byte buffers. -const uint8_t BUFFER_BLOCK_COUNT = 1; -// Dimension for queues of 512 byte SD blocks. -const uint8_t QUEUE_DIM = 4; // Must be a power of two! -// -#elif RAMEND < 0X20FF -// Use total of five 512 byte buffers. -const uint8_t BUFFER_BLOCK_COUNT = 4; -// Dimension for queues of 512 byte SD blocks. -const uint8_t QUEUE_DIM = 8; // Must be a power of two! -// -#elif RAMEND < 0X40FF -// Use total of 13 512 byte buffers. -const uint8_t BUFFER_BLOCK_COUNT = 12; -// Dimension for queues of 512 byte SD blocks. -const uint8_t QUEUE_DIM = 16; // Must be a power of two! -// -#else // RAMEND -// Use total of 29 512 byte buffers. -const uint8_t BUFFER_BLOCK_COUNT = 28; -// Dimension for queues of 512 byte SD blocks. -const uint8_t QUEUE_DIM = 32; // Must be a power of two! -#endif // RAMEND -//============================================================================== -// End of configuration constants. -//============================================================================== -// Temporary log file. Will be deleted if a reset or power failure occurs. -#define TMP_FILE_NAME "tmp_log.bin" - -// Size of file base name. Must not be larger than six. -const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1; - -// Number of analog pins to log. -const uint8_t PIN_COUNT = sizeof(PIN_LIST)/sizeof(PIN_LIST[0]); - -// Minimum ADC clock cycles per sample interval -const uint16_t MIN_ADC_CYCLES = 15; - -// Extra cpu cycles to setup ADC with more than one pin per sample. -const uint16_t ISR_SETUP_ADC = PIN_COUNT > 1 ? 100 : 0; - -// Maximum cycles for timer0 system interrupt, millis, micros. -const uint16_t ISR_TIMER0 = 160; -//============================================================================== -SdFat sd; - -SdBaseFile binFile; - -char binName[13] = FILE_BASE_NAME "00.bin"; - -#if RECORD_EIGHT_BITS -const size_t SAMPLES_PER_BLOCK = DATA_DIM8/PIN_COUNT; -typedef block8_t block_t; -#else // RECORD_EIGHT_BITS -const size_t SAMPLES_PER_BLOCK = DATA_DIM16/PIN_COUNT; -typedef block16_t block_t; -#endif // RECORD_EIGHT_BITS - -block_t* emptyQueue[QUEUE_DIM]; -uint8_t emptyHead; -uint8_t emptyTail; - -block_t* fullQueue[QUEUE_DIM]; -volatile uint8_t fullHead; // volatile insures non-interrupt code sees changes. -uint8_t fullTail; - -// queueNext assumes QUEUE_DIM is a power of two -inline uint8_t queueNext(uint8_t ht) { - return (ht + 1) & (QUEUE_DIM -1); -} -//============================================================================== -// Interrupt Service Routines - -// Pointer to current buffer. -block_t* isrBuf; - -// Need new buffer if true. -bool isrBufNeeded = true; - -// overrun count -uint16_t isrOver = 0; - -// ADC configuration for each pin. -uint8_t adcmux[PIN_COUNT]; -uint8_t adcsra[PIN_COUNT]; -uint8_t adcsrb[PIN_COUNT]; -uint8_t adcindex = 1; - -// Insure no timer events are missed. -volatile bool timerError = false; -volatile bool timerFlag = false; -//------------------------------------------------------------------------------ -// ADC done interrupt. -ISR(ADC_vect) { - // Read ADC data. -#if RECORD_EIGHT_BITS - uint8_t d = ADCH; -#else // RECORD_EIGHT_BITS - // This will access ADCL first. - uint16_t d = ADC; -#endif // RECORD_EIGHT_BITS - - if (isrBufNeeded && emptyHead == emptyTail) { - // no buffers - count overrun - if (isrOver < 0XFFFF) { - isrOver++; - } - - // Avoid missed timer error. - timerFlag = false; - return; - } - // Start ADC - if (PIN_COUNT > 1) { - ADMUX = adcmux[adcindex]; - ADCSRB = adcsrb[adcindex]; - ADCSRA = adcsra[adcindex]; - if (adcindex == 0) { - timerFlag = false; - } - adcindex = adcindex < (PIN_COUNT - 1) ? adcindex + 1 : 0; - } else { - timerFlag = false; - } - // Check for buffer needed. - if (isrBufNeeded) { - // Remove buffer from empty queue. - isrBuf = emptyQueue[emptyTail]; - emptyTail = queueNext(emptyTail); - isrBuf->count = 0; - isrBuf->overrun = isrOver; - isrBufNeeded = false; - } - // Store ADC data. - isrBuf->data[isrBuf->count++] = d; - - // Check for buffer full. - if (isrBuf->count >= PIN_COUNT*SAMPLES_PER_BLOCK) { - // Put buffer isrIn full queue. - uint8_t tmp = fullHead; // Avoid extra fetch of volatile fullHead. - fullQueue[tmp] = (block_t*)isrBuf; - fullHead = queueNext(tmp); - - // Set buffer needed and clear overruns. - isrBufNeeded = true; - isrOver = 0; - } -} -//------------------------------------------------------------------------------ -// timer1 interrupt to clear OCF1B -ISR(TIMER1_COMPB_vect) { - // Make sure ADC ISR responded to timer event. - if (timerFlag) { - timerError = true; - } - timerFlag = true; -} -//============================================================================== -// Error messages stored in flash. -#define error(msg) {sd.errorPrint(F(msg));fatalBlink();} -//------------------------------------------------------------------------------ -// -void fatalBlink() { - while (true) { - if (ERROR_LED_PIN >= 0) { - digitalWrite(ERROR_LED_PIN, HIGH); - delay(200); - digitalWrite(ERROR_LED_PIN, LOW); - delay(200); - } - } -} -//============================================================================== -#if ADPS0 != 0 || ADPS1 != 1 || ADPS2 != 2 -#error unexpected ADC prescaler bits -#endif -//------------------------------------------------------------------------------ -// initialize ADC and timer1 -void adcInit(metadata_t* meta) { - uint8_t adps; // prescaler bits for ADCSRA - uint32_t ticks = F_CPU*SAMPLE_INTERVAL + 0.5; // Sample interval cpu cycles. - - if (ADC_REF & ~((1 << REFS0) | (1 << REFS1))) { - error("Invalid ADC reference"); - } -#ifdef ADC_PRESCALER - if (ADC_PRESCALER > 7 || ADC_PRESCALER < 2) { - error("Invalid ADC prescaler"); - } - adps = ADC_PRESCALER; -#else // ADC_PRESCALER - // Allow extra cpu cycles to change ADC settings if more than one pin. - int32_t adcCycles = (ticks - ISR_TIMER0)/PIN_COUNT - ISR_SETUP_ADC; - - for (adps = 7; adps > 0; adps--) { - if (adcCycles >= (MIN_ADC_CYCLES << adps)) { - break; - } - } -#endif // ADC_PRESCALER - meta->adcFrequency = F_CPU >> adps; - if (meta->adcFrequency > (RECORD_EIGHT_BITS ? 2000000 : 1000000)) { - error("Sample Rate Too High"); - } -#if ROUND_SAMPLE_INTERVAL - // Round so interval is multiple of ADC clock. - ticks += 1 << (adps - 1); - ticks >>= adps; - ticks <<= adps; -#endif // ROUND_SAMPLE_INTERVAL - - if (PIN_COUNT > sizeof(meta->pinNumber)/sizeof(meta->pinNumber[0])) { - error("Too many pins"); - } - meta->pinCount = PIN_COUNT; - meta->recordEightBits = RECORD_EIGHT_BITS; - - for (int i = 0; i < PIN_COUNT; i++) { - uint8_t pin = PIN_LIST[i]; - if (pin >= NUM_ANALOG_INPUTS) { - error("Invalid Analog pin number"); - } - meta->pinNumber[i] = pin; - - // Set ADC reference and low three bits of analog pin number. - adcmux[i] = (pin & 7) | ADC_REF; - if (RECORD_EIGHT_BITS) { - adcmux[i] |= 1 << ADLAR; - } - - // If this is the first pin, trigger on timer/counter 1 compare match B. - adcsrb[i] = i == 0 ? (1 << ADTS2) | (1 << ADTS0) : 0; -#ifdef MUX5 - if (pin > 7) { - adcsrb[i] |= (1 << MUX5); - } -#endif // MUX5 - adcsra[i] = (1 << ADEN) | (1 << ADIE) | adps; - adcsra[i] |= i == 0 ? 1 << ADATE : 1 << ADSC; - } - - // Setup timer1 - TCCR1A = 0; - uint8_t tshift; - if (ticks < 0X10000) { - // no prescale, CTC mode - TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS10); - tshift = 0; - } else if (ticks < 0X10000*8) { - // prescale 8, CTC mode - TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11); - tshift = 3; - } else if (ticks < 0X10000*64) { - // prescale 64, CTC mode - TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11) | (1 << CS10); - tshift = 6; - } else if (ticks < 0X10000*256) { - // prescale 256, CTC mode - TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12); - tshift = 8; - } else if (ticks < 0X10000*1024) { - // prescale 1024, CTC mode - TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12) | (1 << CS10); - tshift = 10; - } else { - error("Sample Rate Too Slow"); - } - // divide by prescaler - ticks >>= tshift; - // set TOP for timer reset - ICR1 = ticks - 1; - // compare for ADC start - OCR1B = 0; - - // multiply by prescaler - ticks <<= tshift; - - // Sample interval in CPU clock ticks. - meta->sampleInterval = ticks; - meta->cpuFrequency = F_CPU; - float sampleRate = (float)meta->cpuFrequency/meta->sampleInterval; - Serial.print(F("Sample pins:")); - for (uint8_t i = 0; i < meta->pinCount; i++) { - Serial.print(' '); - Serial.print(meta->pinNumber[i], DEC); - } - Serial.println(); - Serial.print(F("ADC bits: ")); - Serial.println(meta->recordEightBits ? 8 : 10); - Serial.print(F("ADC clock kHz: ")); - Serial.println(meta->adcFrequency/1000); - Serial.print(F("Sample Rate: ")); - Serial.println(sampleRate); - Serial.print(F("Sample interval usec: ")); - Serial.println(1000000.0/sampleRate, 4); -} -//------------------------------------------------------------------------------ -// enable ADC and timer1 interrupts -void adcStart() { - // initialize ISR - isrBufNeeded = true; - isrOver = 0; - adcindex = 1; - - // Clear any pending interrupt. - ADCSRA |= 1 << ADIF; - - // Setup for first pin. - ADMUX = adcmux[0]; - ADCSRB = adcsrb[0]; - ADCSRA = adcsra[0]; - - // Enable timer1 interrupts. - timerError = false; - timerFlag = false; - TCNT1 = 0; - TIFR1 = 1 << OCF1B; - TIMSK1 = 1 << OCIE1B; -} -//------------------------------------------------------------------------------ -void adcStop() { - TIMSK1 = 0; - ADCSRA = 0; -} -//------------------------------------------------------------------------------ -// Convert binary file to csv file. -void binaryToCsv() { - uint8_t lastPct = 0; - block_t buf; - metadata_t* pm; - uint32_t t0 = millis(); - char csvName[13]; - StdioStream csvStream; - - if (!binFile.isOpen()) { - Serial.println(F("No current binary file")); - return; - } - binFile.rewind(); - if (binFile.read(&buf , 512) != 512) { - error("Read metadata failed"); - } - // Create a new csv file. - strcpy(csvName, binName); - strcpy(&csvName[BASE_NAME_SIZE + 3], "csv"); - - if (!csvStream.fopen(csvName, "w")) { - error("open csvStream failed"); - } - Serial.println(); - Serial.print(F("Writing: ")); - Serial.print(csvName); - Serial.println(F(" - type any character to stop")); - pm = (metadata_t*)&buf; - csvStream.print(F("Interval,")); - float intervalMicros = 1.0e6*pm->sampleInterval/(float)pm->cpuFrequency; - csvStream.print(intervalMicros, 4); - csvStream.println(F(",usec")); - for (uint8_t i = 0; i < pm->pinCount; i++) { - if (i) { - csvStream.putc(','); - } - csvStream.print(F("pin")); - csvStream.print(pm->pinNumber[i]); - } - csvStream.println(); - uint32_t tPct = millis(); - while (!Serial.available() && binFile.read(&buf, 512) == 512) { - if (buf.count == 0) { - break; - } - if (buf.overrun) { - csvStream.print(F("OVERRUN,")); - csvStream.println(buf.overrun); - } - for (uint16_t j = 0; j < buf.count; j += PIN_COUNT) { - for (uint16_t i = 0; i < PIN_COUNT; i++) { - if (i) { - csvStream.putc(','); - } - csvStream.print(buf.data[i + j]); - } - csvStream.println(); - } - if ((millis() - tPct) > 1000) { - uint8_t pct = binFile.curPosition()/(binFile.fileSize()/100); - if (pct != lastPct) { - tPct = millis(); - lastPct = pct; - Serial.print(pct, DEC); - Serial.println('%'); - } - } - if (Serial.available()) { - break; - } - } - csvStream.fclose(); - Serial.print(F("Done: ")); - Serial.print(0.001*(millis() - t0)); - Serial.println(F(" Seconds")); -} -//------------------------------------------------------------------------------ -// read data file and check for overruns -void checkOverrun() { - bool headerPrinted = false; - block_t buf; - uint32_t bgnBlock, endBlock; - uint32_t bn = 0; - - if (!binFile.isOpen()) { - Serial.println(F("No current binary file")); - return; - } - if (!binFile.contiguousRange(&bgnBlock, &endBlock)) { - error("contiguousRange failed"); - } - binFile.rewind(); - Serial.println(); - Serial.println(F("Checking overrun errors - type any character to stop")); - if (binFile.read(&buf , 512) != 512) { - error("Read metadata failed"); - } - bn++; - while (binFile.read(&buf, 512) == 512) { - if (buf.count == 0) { - break; - } - if (buf.overrun) { - if (!headerPrinted) { - Serial.println(); - Serial.println(F("Overruns:")); - Serial.println(F("fileBlockNumber,sdBlockNumber,overrunCount")); - headerPrinted = true; - } - Serial.print(bn); - Serial.print(','); - Serial.print(bgnBlock + bn); - Serial.print(','); - Serial.println(buf.overrun); - } - bn++; - } - if (!headerPrinted) { - Serial.println(F("No errors found")); - } else { - Serial.println(F("Done")); - } -} -//------------------------------------------------------------------------------ -// dump data file to Serial -void dumpData() { - block_t buf; - if (!binFile.isOpen()) { - Serial.println(F("No current binary file")); - return; - } - binFile.rewind(); - if (binFile.read(&buf , 512) != 512) { - error("Read metadata failed"); - } - Serial.println(); - Serial.println(F("Type any character to stop")); - delay(1000); - while (!Serial.available() && binFile.read(&buf , 512) == 512) { - if (buf.count == 0) { - break; - } - if (buf.overrun) { - Serial.print(F("OVERRUN,")); - Serial.println(buf.overrun); - } - for (uint16_t i = 0; i < buf.count; i++) { - Serial.print(buf.data[i], DEC); - if ((i+1)%PIN_COUNT) { - Serial.print(','); - } else { - Serial.println(); - } - } - } - Serial.println(F("Done")); -} -//------------------------------------------------------------------------------ -// log data -// max number of blocks to erase per erase call -uint32_t const ERASE_SIZE = 262144L; -void logData() { - uint32_t bgnBlock, endBlock; - - // Allocate extra buffer space. - block_t block[BUFFER_BLOCK_COUNT]; - - Serial.println(); - - // Initialize ADC and timer1. - adcInit((metadata_t*) &block[0]); - - // Find unused file name. - if (BASE_NAME_SIZE > 6) { - error("FILE_BASE_NAME too long"); - } - while (sd.exists(binName)) { - if (binName[BASE_NAME_SIZE + 1] != '9') { - binName[BASE_NAME_SIZE + 1]++; - } else { - binName[BASE_NAME_SIZE + 1] = '0'; - if (binName[BASE_NAME_SIZE] == '9') { - error("Can't create file name"); - } - binName[BASE_NAME_SIZE]++; - } - } - // Delete old tmp file. - if (sd.exists(TMP_FILE_NAME)) { - Serial.println(F("Deleting tmp file")); - if (!sd.remove(TMP_FILE_NAME)) { - error("Can't remove tmp file"); - } - } - // Create new file. - Serial.println(F("Creating new file")); - binFile.close(); - if (!binFile.createContiguous(TMP_FILE_NAME, 512 * FILE_BLOCK_COUNT)) { - error("createContiguous failed"); - } - // Get the address of the file on the SD. - if (!binFile.contiguousRange(&bgnBlock, &endBlock)) { - error("contiguousRange failed"); - } - // Use SdFat's internal buffer. - uint8_t* cache = (uint8_t*)sd.vol()->cacheClear(); - if (cache == 0) { - error("cacheClear failed"); - } - - // Flash erase all data in the file. - Serial.println(F("Erasing all data")); - uint32_t bgnErase = bgnBlock; - uint32_t endErase; - while (bgnErase < endBlock) { - endErase = bgnErase + ERASE_SIZE; - if (endErase > endBlock) { - endErase = endBlock; - } - if (!sd.card()->erase(bgnErase, endErase)) { - error("erase failed"); - } - bgnErase = endErase + 1; - } - // Start a multiple block write. - if (!sd.card()->writeStart(bgnBlock, FILE_BLOCK_COUNT)) { - error("writeBegin failed"); - } - // Write metadata. - if (!sd.card()->writeData((uint8_t*)&block[0])) { - error("Write metadata failed"); - } - // Initialize queues. - emptyHead = emptyTail = 0; - fullHead = fullTail = 0; - - // Use SdFat buffer for one block. - emptyQueue[emptyHead] = (block_t*)cache; - emptyHead = queueNext(emptyHead); - - // Put rest of buffers in the empty queue. - for (uint8_t i = 0; i < BUFFER_BLOCK_COUNT; i++) { - emptyQueue[emptyHead] = &block[i]; - emptyHead = queueNext(emptyHead); - } - // Give SD time to prepare for big write. - delay(1000); - Serial.println(F("Logging - type any character to stop")); - // Wait for Serial Idle. - Serial.flush(); - delay(10); - uint32_t bn = 1; - uint32_t t0 = millis(); - uint32_t t1 = t0; - uint32_t overruns = 0; - uint32_t count = 0; - uint32_t maxLatency = 0; - - // Start logging interrupts. - adcStart(); - while (1) { - if (fullHead != fullTail) { - // Get address of block to write. - block_t* pBlock = fullQueue[fullTail]; - - // Write block to SD. - uint32_t usec = micros(); - if (!sd.card()->writeData((uint8_t*)pBlock)) { - error("write data failed"); - } - usec = micros() - usec; - t1 = millis(); - if (usec > maxLatency) { - maxLatency = usec; - } - count += pBlock->count; - - // Add overruns and possibly light LED. - if (pBlock->overrun) { - overruns += pBlock->overrun; - if (ERROR_LED_PIN >= 0) { - digitalWrite(ERROR_LED_PIN, HIGH); - } - } - // Move block to empty queue. - emptyQueue[emptyHead] = pBlock; - emptyHead = queueNext(emptyHead); - fullTail = queueNext(fullTail); - bn++; - if (bn == FILE_BLOCK_COUNT) { - // File full so stop ISR calls. - adcStop(); - break; - } - } - if (timerError) { - error("Missed timer event - rate too high"); - } - if (Serial.available()) { - // Stop ISR calls. - adcStop(); - if (isrBuf != 0 && isrBuf->count >= PIN_COUNT) { - // Truncate to last complete sample. - isrBuf->count = PIN_COUNT*(isrBuf->count/PIN_COUNT); - // Put buffer in full queue. - fullQueue[fullHead] = isrBuf; - fullHead = queueNext(fullHead); - isrBuf = 0; - } - if (fullHead == fullTail) { - break; - } - } - } - if (!sd.card()->writeStop()) { - error("writeStop failed"); - } - // Truncate file if recording stopped early. - if (bn != FILE_BLOCK_COUNT) { - Serial.println(F("Truncating file")); - if (!binFile.truncate(512L * bn)) { - error("Can't truncate file"); - } - } - if (!binFile.rename(binName)) { - error("Can't rename file"); - } - Serial.print(F("File renamed: ")); - Serial.println(binName); - Serial.print(F("Max block write usec: ")); - Serial.println(maxLatency); - Serial.print(F("Record time sec: ")); - Serial.println(0.001*(t1 - t0), 3); - Serial.print(F("Sample count: ")); - Serial.println(count/PIN_COUNT); - Serial.print(F("Samples/sec: ")); - Serial.println((1000.0/PIN_COUNT)*count/(t1-t0)); - Serial.print(F("Overruns: ")); - Serial.println(overruns); - Serial.println(F("Done")); -} -//------------------------------------------------------------------------------ -void setup(void) { - if (ERROR_LED_PIN >= 0) { - pinMode(ERROR_LED_PIN, OUTPUT); - } - Serial.begin(9600); - - // Read the first sample pin to init the ADC. - analogRead(PIN_LIST[0]); - - Serial.print(F("FreeStack: ")); - Serial.println(FreeStack()); - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50))) { - sd.initErrorPrint(); - fatalBlink(); - } -} -//------------------------------------------------------------------------------ -void loop(void) { - // Read any Serial data. - do { - delay(10); - } while (Serial.available() && Serial.read() >= 0); - Serial.println(); - Serial.println(F("type:")); - Serial.println(F("c - convert file to csv")); - Serial.println(F("d - dump data to Serial")); - Serial.println(F("e - overrun error details")); - Serial.println(F("r - record ADC data")); - - while(!Serial.available()) { - SysCall::yield(); - } - char c = tolower(Serial.read()); - if (ERROR_LED_PIN >= 0) { - digitalWrite(ERROR_LED_PIN, LOW); - } - // Read any Serial data. - do { - delay(10); - } while (Serial.available() && Serial.read() >= 0); - - if (c == 'c') { - binaryToCsv(); - } else if (c == 'd') { - dumpData(); - } else if (c == 'e') { - checkOverrun(); - } else if (c == 'r') { - logData(); - } else { - Serial.println(F("Invalid entry")); - } -} -#else // __AVR__ -#error This program is only for AVR. -#endif // __AVR__ \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/DirectoryFunctions/DirectoryFunctions.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/DirectoryFunctions/DirectoryFunctions.ino deleted file mode 100644 index 2c72b57..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/DirectoryFunctions/DirectoryFunctions.ino +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Example use of chdir(), ls(), mkdir(), and rmdir(). - */ -#include -#include "SdFat.h" -#include "sdios.h" -// SD card chip select pin. -const uint8_t chipSelect = SS; -//------------------------------------------------------------------------------ - -// File system object. -SdFat sd; - -// Directory file. -SdFile root; - -// Use for file creation in folders. -SdFile file; - -// Create a Serial output stream. -ArduinoOutStream cout(Serial); - -// Buffer for Serial input. -char cinBuf[40]; - -// Create a serial input stream. -ArduinoInStream cin(Serial, cinBuf, sizeof(cinBuf)); -//============================================================================== -// Error messages stored in flash. -#define error(msg) sd.errorHalt(F(msg)) -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - delay(1000); - - cout << F("Type any character to start\n"); - // Wait for input line and discard. - cin.readline(); - cout << endl; - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } - if (sd.exists("Folder1") - || sd.exists("Folder1/file1.txt") - || sd.exists("Folder1/File2.txt")) { - error("Please remove existing Folder1, file1.txt, and File2.txt"); - } - - int rootFileCount = 0; - if (!root.open("/")){ - error("open root failed"); - } - while (file.openNext(&root, O_RDONLY)) { - if (!file.isHidden()) { - rootFileCount++; - } - file.close(); - if (rootFileCount > 10) { - error("Too many files in root. Please use an empty SD."); - } - } - if (rootFileCount) { - cout << F("\nPlease use an empty SD for best results.\n\n"); - delay(1000); - } - // Create a new folder. - if (!sd.mkdir("Folder1")) { - error("Create Folder1 failed"); - } - cout << F("Created Folder1\n"); - - // Create a file in Folder1 using a path. - if (!file.open("Folder1/file1.txt", O_WRONLY | O_CREAT)) { - error("create Folder1/file1.txt failed"); - } - file.close(); - cout << F("Created Folder1/file1.txt\n"); - - // Change volume working directory to Folder1. - if (!sd.chdir("Folder1")) { - error("chdir failed for Folder1.\n"); - } - cout << F("chdir to Folder1\n"); - - // Create File2.txt in current directory. - if (!file.open("File2.txt", O_WRONLY | O_CREAT)) { - error("create File2.txt failed"); - } - file.close(); - cout << F("Created File2.txt in current directory\n"); - - cout << F("\nList of files on the SD.\n"); - sd.ls("/", LS_R); - - // Remove files from current directory. - if (!sd.remove("file1.txt") || !sd.remove("File2.txt")) { - error("remove failed"); - } - cout << F("\nfile1.txt and File2.txt removed.\n"); - - // Change current directory to root. - if (!sd.chdir()) { - error("chdir to root failed.\n"); - } - - cout << F("\nList of files on the SD.\n"); - sd.ls(LS_R); - - // Remove Folder1. - if (!sd.rmdir("Folder1")) { - error("rmdir for Folder1 failed\n"); - } - - cout << F("\nFolder1 removed.\n"); - cout << F("\nList of files on the SD.\n"); - sd.ls(LS_R); - cout << F("Done!\n"); -} -//------------------------------------------------------------------------------ -// Nothing happens in loop. -void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/LongFileName.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/LongFileName.ino deleted file mode 100644 index 92d04a0..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/LongFileName.ino +++ /dev/null @@ -1,102 +0,0 @@ -// Example use of lfnOpenNext and open by index. -// You can use test files located in -// SdFat/examples/LongFileName/testFiles. -#include -#include "SdFat.h" -#include "FreeStack.h" - -// SD card chip select pin. -const uint8_t SD_CS_PIN = SS; - -SdFat sd; -SdFile file; -SdFile dirFile; - -// Number of files found. -uint16_t n = 0; - -// Max of ten files since files are selected with a single digit. -const uint16_t nMax = 10; - -// Position of file's directory entry. -uint16_t dirIndex[nMax]; -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - while (!Serial) {} - delay(1000); - - // Print the location of some test files. - Serial.println(F("\r\n" - "You can use test files located in\r\n" - "SdFat/examples/LongFileName/testFiles")); - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } - Serial.print(F("FreeStack: ")); - Serial.println(FreeStack()); - Serial.println(); - - // List files in root directory. - if (!dirFile.open("/", O_RDONLY)) { - sd.errorHalt("open root failed"); - } - while (n < nMax && file.openNext(&dirFile, O_RDONLY)) { - - // Skip directories and hidden files. - if (!file.isSubDir() && !file.isHidden()) { - - // Save dirIndex of file in directory. - dirIndex[n] = file.dirIndex(); - - // Print the file number and name. - Serial.print(n++); - Serial.write(' '); - file.printName(&Serial); - Serial.println(); - } - file.close(); - } -} -//------------------------------------------------------------------------------ -void loop() { - int c; - - // Read any existing Serial data. - do { - delay(10); - } while (Serial.available() && Serial.read() >= 0); - Serial.print(F("\r\nEnter File Number: ")); - - while (!Serial.available()) { - SysCall::yield(); - } - c = Serial.read(); - uint8_t i = c - '0'; - if (!isdigit(c) || i >= n) { - Serial.println(F("Invald number")); - return; - } - Serial.println(i); - if (!file.open(&dirFile, dirIndex[i], O_RDONLY)) { - sd.errorHalt(F("open")); - } - Serial.println(); - - char last = 0; - - // Copy up to 500 characters to Serial. - for (int k = 0; k < 500 && (c = file.read()) > 0; k++) { - Serial.write(last = (char)c); - } - // Add new line if missing from last line. - if (last != '\n') { - Serial.println(); - } - file.close(); - Serial.flush(); - delay(100); -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/A long name can be 255 characters.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/A long name can be 255 characters.txt deleted file mode 100644 index ccccc1f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/A long name can be 255 characters.txt +++ /dev/null @@ -1,4 +0,0 @@ -This is "A long name can be 255 characters.txt" -This file has a typical Long File Name. - -The maximum length of a Long File Name is 255 characters. diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/LFN,NAME.TXT b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/LFN,NAME.TXT deleted file mode 100644 index 3fc38d6..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/LFN,NAME.TXT +++ /dev/null @@ -1 +0,0 @@ -LFN,NAME.TXT is not 8.3 since it has a comma. \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/MIXCASE.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/MIXCASE.txt deleted file mode 100644 index cd47677..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/MIXCASE.txt +++ /dev/null @@ -1,5 +0,0 @@ -MIXCASE.txt does not have a Long File Name. - -Starting with NT, file names of this form, -have the basename and extension character case -encoded in two bits of the 8.3 directory entry. diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/Not_8_3.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/Not_8_3.txt deleted file mode 100644 index acfc433..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/Not_8_3.txt +++ /dev/null @@ -1,2 +0,0 @@ -Not_8_3.txt has a Long File Name -since the basename is mixed case. \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/OK%83.TXT b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/OK%83.TXT deleted file mode 100644 index 6935e78..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/OK%83.TXT +++ /dev/null @@ -1 +0,0 @@ -OK%83.TXT is a valid 8.3 name. \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/STD_8_3.TXT b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/STD_8_3.TXT deleted file mode 100644 index e0d2234..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/STD_8_3.TXT +++ /dev/null @@ -1 +0,0 @@ -STD_8_3.TXT - a vanilla 8.3 name. \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/With Blank.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/With Blank.txt deleted file mode 100644 index 29cd8a8..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/With Blank.txt +++ /dev/null @@ -1,2 +0,0 @@ -With Blank.txt -Just another example of a Long File Name. diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/With.Two dots.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/With.Two dots.txt deleted file mode 100644 index f796ec6..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/With.Two dots.txt +++ /dev/null @@ -1,2 +0,0 @@ -"With Two.dots.txt" -Lots of reasons this is a Long File Name. diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/lower.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/lower.txt deleted file mode 100644 index 6f2fa28..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/lower.txt +++ /dev/null @@ -1,5 +0,0 @@ -lower.txt does not have a Long File Name. - -Starting with NT, file names of this form, -have the basename and extension character case -encoded in two bits of the 8.3 directory entry. diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/mixed.TXT b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/mixed.TXT deleted file mode 100644 index 8f54d9a..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LongFileName/testFiles/mixed.TXT +++ /dev/null @@ -1,5 +0,0 @@ -mixed.TXT does not have a Long File Name. - -Starting with NT, file names of this form, -have the basename and extension character case -encoded in two bits of the 8.3 directory entry. \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/LowLatencyLogger.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/LowLatencyLogger.ino deleted file mode 100644 index 40aa40d..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/LowLatencyLogger.ino +++ /dev/null @@ -1,655 +0,0 @@ -/** - * This program logs data to a binary file. Functions are included - * to convert the binary file to a csv text file. - * - * Samples are logged at regular intervals. The maximum logging rate - * depends on the quality of your SD card and the time required to - * read sensor data. This example has been tested at 500 Hz with - * good SD card on an Uno. 4000 HZ is possible on a Due. - * - * If your SD card has a long write latency, it may be necessary to use - * slower sample rates. Using a Mega Arduino helps overcome latency - * problems since 12 512 byte buffers will be used. - * - * Data is written to the file using a SD multiple block write command. - */ -#include -#include "SdFat.h" -#include "FreeStack.h" -#include "UserTypes.h" - -#ifdef __AVR_ATmega328P__ -#include "MinimumSerial.h" -MinimumSerial MinSerial; -#define Serial MinSerial -#endif // __AVR_ATmega328P__ -//============================================================================== -// Start of configuration constants. -//============================================================================== -// Abort run on an overrun. Data before the overrun will be saved. -#define ABORT_ON_OVERRUN 1 -//------------------------------------------------------------------------------ -//Interval between data records in microseconds. -const uint32_t LOG_INTERVAL_USEC = 2000; -//------------------------------------------------------------------------------ -// Set USE_SHARED_SPI non-zero for use of an SPI sensor. -// May not work for some cards. -#ifndef USE_SHARED_SPI -#define USE_SHARED_SPI 0 -#endif // USE_SHARED_SPI -//------------------------------------------------------------------------------ -// Pin definitions. -// -// SD chip select pin. -const uint8_t SD_CS_PIN = SS; -// -// Digital pin to indicate an error, set to -1 if not used. -// The led blinks for fatal errors. The led goes on solid for -// overrun errors and logging continues unless ABORT_ON_OVERRUN -// is non-zero. -#ifdef ERROR_LED_PIN -#undef ERROR_LED_PIN -#endif // ERROR_LED_PIN -const int8_t ERROR_LED_PIN = -1; -//------------------------------------------------------------------------------ -// File definitions. -// -// Maximum file size in blocks. -// The program creates a contiguous file with FILE_BLOCK_COUNT 512 byte blocks. -// This file is flash erased using special SD commands. The file will be -// truncated if logging is stopped early. -const uint32_t FILE_BLOCK_COUNT = 256000; -// -// log file base name if not defined in UserTypes.h -#ifndef FILE_BASE_NAME -#define FILE_BASE_NAME "data" -#endif // FILE_BASE_NAME -//------------------------------------------------------------------------------ -// Buffer definitions. -// -// The logger will use SdFat's buffer plus BUFFER_BLOCK_COUNT-1 additional -// buffers. -// -#ifndef RAMEND -// Assume ARM. Use total of ten 512 byte buffers. -const uint8_t BUFFER_BLOCK_COUNT = 10; -// -#elif RAMEND < 0X8FF -#error Too little SRAM -// -#elif RAMEND < 0X10FF -// Use total of two 512 byte buffers. -const uint8_t BUFFER_BLOCK_COUNT = 2; -// -#elif RAMEND < 0X20FF -// Use total of four 512 byte buffers. -const uint8_t BUFFER_BLOCK_COUNT = 4; -// -#else // RAMEND -// Use total of 12 512 byte buffers. -const uint8_t BUFFER_BLOCK_COUNT = 12; -#endif // RAMEND -//============================================================================== -// End of configuration constants. -//============================================================================== -// Temporary log file. Will be deleted if a reset or power failure occurs. -#define TMP_FILE_NAME FILE_BASE_NAME "##.bin" - -// Size of file base name. -const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1; -const uint8_t FILE_NAME_DIM = BASE_NAME_SIZE + 7; -char binName[FILE_NAME_DIM] = FILE_BASE_NAME "00.bin"; - -SdFat sd; - -SdBaseFile binFile; - -// Number of data records in a block. -const uint16_t DATA_DIM = (512 - 4)/sizeof(data_t); - -//Compute fill so block size is 512 bytes. FILL_DIM may be zero. -const uint16_t FILL_DIM = 512 - 4 - DATA_DIM*sizeof(data_t); - -struct block_t { - uint16_t count; - uint16_t overrun; - data_t data[DATA_DIM]; - uint8_t fill[FILL_DIM]; -}; -//============================================================================== -// Error messages stored in flash. -#define error(msg) {sd.errorPrint(&Serial, F(msg));fatalBlink();} -//------------------------------------------------------------------------------ -// -void fatalBlink() { - while (true) { - SysCall::yield(); - if (ERROR_LED_PIN >= 0) { - digitalWrite(ERROR_LED_PIN, HIGH); - delay(200); - digitalWrite(ERROR_LED_PIN, LOW); - delay(200); - } - } -} -//------------------------------------------------------------------------------ -// read data file and check for overruns -void checkOverrun() { - bool headerPrinted = false; - block_t block; - uint32_t bn = 0; - - if (!binFile.isOpen()) { - Serial.println(); - Serial.println(F("No current binary file")); - return; - } - binFile.rewind(); - Serial.println(); - Serial.print(F("FreeStack: ")); - Serial.println(FreeStack()); - Serial.println(F("Checking overrun errors - type any character to stop")); - while (binFile.read(&block, 512) == 512) { - if (block.count == 0) { - break; - } - if (block.overrun) { - if (!headerPrinted) { - Serial.println(); - Serial.println(F("Overruns:")); - Serial.println(F("fileBlockNumber,sdBlockNumber,overrunCount")); - headerPrinted = true; - } - Serial.print(bn); - Serial.print(','); - Serial.print(binFile.firstBlock() + bn); - Serial.print(','); - Serial.println(block.overrun); - } - bn++; - } - if (!headerPrinted) { - Serial.println(F("No errors found")); - } else { - Serial.println(F("Done")); - } -} -//----------------------------------------------------------------------------- -// Convert binary file to csv file. -void binaryToCsv() { - uint8_t lastPct = 0; - block_t block; - uint32_t t0 = millis(); - uint32_t syncCluster = 0; - SdFile csvFile; - char csvName[FILE_NAME_DIM]; - - if (!binFile.isOpen()) { - Serial.println(); - Serial.println(F("No current binary file")); - return; - } - Serial.println(); - Serial.print(F("FreeStack: ")); - Serial.println(FreeStack()); - - // Create a new csvFile. - strcpy(csvName, binName); - strcpy(&csvName[BASE_NAME_SIZE + 3], "csv"); - - if (!csvFile.open(csvName, O_WRONLY | O_CREAT | O_TRUNC)) { - error("open csvFile failed"); - } - binFile.rewind(); - Serial.print(F("Writing: ")); - Serial.print(csvName); - Serial.println(F(" - type any character to stop")); - printHeader(&csvFile); - uint32_t tPct = millis(); - while (!Serial.available() && binFile.read(&block, 512) == 512) { - uint16_t i; - if (block.count == 0 || block.count > DATA_DIM) { - break; - } - if (block.overrun) { - csvFile.print(F("OVERRUN,")); - csvFile.println(block.overrun); - } - for (i = 0; i < block.count; i++) { - printData(&csvFile, &block.data[i]); - } - if (csvFile.curCluster() != syncCluster) { - csvFile.sync(); - syncCluster = csvFile.curCluster(); - } - if ((millis() - tPct) > 1000) { - uint8_t pct = binFile.curPosition()/(binFile.fileSize()/100); - if (pct != lastPct) { - tPct = millis(); - lastPct = pct; - Serial.print(pct, DEC); - Serial.println('%'); - } - } - if (Serial.available()) { - break; - } - } - csvFile.close(); - Serial.print(F("Done: ")); - Serial.print(0.001*(millis() - t0)); - Serial.println(F(" Seconds")); -} -//----------------------------------------------------------------------------- -void createBinFile() { - // max number of blocks to erase per erase call - const uint32_t ERASE_SIZE = 262144L; - uint32_t bgnBlock, endBlock; - - // Delete old tmp file. - if (sd.exists(TMP_FILE_NAME)) { - Serial.println(F("Deleting tmp file " TMP_FILE_NAME)); - if (!sd.remove(TMP_FILE_NAME)) { - error("Can't remove tmp file"); - } - } - // Create new file. - Serial.println(F("\nCreating new file")); - binFile.close(); - if (!binFile.createContiguous(TMP_FILE_NAME, 512 * FILE_BLOCK_COUNT)) { - error("createContiguous failed"); - } - // Get the address of the file on the SD. - if (!binFile.contiguousRange(&bgnBlock, &endBlock)) { - error("contiguousRange failed"); - } - // Flash erase all data in the file. - Serial.println(F("Erasing all data")); - uint32_t bgnErase = bgnBlock; - uint32_t endErase; - while (bgnErase < endBlock) { - endErase = bgnErase + ERASE_SIZE; - if (endErase > endBlock) { - endErase = endBlock; - } - if (!sd.card()->erase(bgnErase, endErase)) { - error("erase failed"); - } - bgnErase = endErase + 1; - } -} -//------------------------------------------------------------------------------ -// dump data file to Serial -void dumpData() { - block_t block; - if (!binFile.isOpen()) { - Serial.println(); - Serial.println(F("No current binary file")); - return; - } - binFile.rewind(); - Serial.println(); - Serial.println(F("Type any character to stop")); - delay(1000); - printHeader(&Serial); - while (!Serial.available() && binFile.read(&block , 512) == 512) { - if (block.count == 0) { - break; - } - if (block.overrun) { - Serial.print(F("OVERRUN,")); - Serial.println(block.overrun); - } - for (uint16_t i = 0; i < block.count; i++) { - printData(&Serial, &block.data[i]); - } - } - Serial.println(F("Done")); -} -//------------------------------------------------------------------------------ -// log data -void logData() { - createBinFile(); - recordBinFile(); - renameBinFile(); -} -//------------------------------------------------------------------------------ -void openBinFile() { - char name[FILE_NAME_DIM]; - strcpy(name, binName); - Serial.println(F("\nEnter two digit version")); - Serial.write(name, BASE_NAME_SIZE); - for (int i = 0; i < 2; i++) { - while (!Serial.available()) { - SysCall::yield(); - } - char c = Serial.read(); - Serial.write(c); - if (c < '0' || c > '9') { - Serial.println(F("\nInvalid digit")); - return; - } - name[BASE_NAME_SIZE + i] = c; - } - Serial.println(&name[BASE_NAME_SIZE+2]); - if (!sd.exists(name)) { - Serial.println(F("File does not exist")); - return; - } - binFile.close(); - strcpy(binName, name); - if (!binFile.open(binName, O_RDONLY)) { - Serial.println(F("open failed")); - return; - } - Serial.println(F("File opened")); -} -//------------------------------------------------------------------------------ -void recordBinFile() { - const uint8_t QUEUE_DIM = BUFFER_BLOCK_COUNT + 1; - // Index of last queue location. - const uint8_t QUEUE_LAST = QUEUE_DIM - 1; - - // Allocate extra buffer space. - block_t block[BUFFER_BLOCK_COUNT - 1]; - - block_t* curBlock = 0; - - block_t* emptyStack[BUFFER_BLOCK_COUNT]; - uint8_t emptyTop; - uint8_t minTop; - - block_t* fullQueue[QUEUE_DIM]; - uint8_t fullHead = 0; - uint8_t fullTail = 0; - - // Use SdFat's internal buffer. - emptyStack[0] = (block_t*)sd.vol()->cacheClear(); - if (emptyStack[0] == 0) { - error("cacheClear failed"); - } - // Put rest of buffers on the empty stack. - for (int i = 1; i < BUFFER_BLOCK_COUNT; i++) { - emptyStack[i] = &block[i - 1]; - } - emptyTop = BUFFER_BLOCK_COUNT; - minTop = BUFFER_BLOCK_COUNT; - - // Start a multiple block write. - if (!sd.card()->writeStart(binFile.firstBlock())) { - error("writeStart failed"); - } - Serial.print(F("FreeStack: ")); - Serial.println(FreeStack()); - Serial.println(F("Logging - type any character to stop")); - bool closeFile = false; - uint32_t bn = 0; - uint32_t maxLatency = 0; - uint32_t overrun = 0; - uint32_t overrunTotal = 0; - uint32_t logTime = micros(); - while(1) { - // Time for next data record. - logTime += LOG_INTERVAL_USEC; - if (Serial.available()) { - closeFile = true; - } - if (closeFile) { - if (curBlock != 0) { - // Put buffer in full queue. - fullQueue[fullHead] = curBlock; - fullHead = fullHead < QUEUE_LAST ? fullHead + 1 : 0; - curBlock = 0; - } - } else { - if (curBlock == 0 && emptyTop != 0) { - curBlock = emptyStack[--emptyTop]; - if (emptyTop < minTop) { - minTop = emptyTop; - } - curBlock->count = 0; - curBlock->overrun = overrun; - overrun = 0; - } - if ((int32_t)(logTime - micros()) < 0) { - error("Rate too fast"); - } - int32_t delta; - do { - delta = micros() - logTime; - } while (delta < 0); - if (curBlock == 0) { - overrun++; - overrunTotal++; - if (ERROR_LED_PIN >= 0) { - digitalWrite(ERROR_LED_PIN, HIGH); - } -#if ABORT_ON_OVERRUN - Serial.println(F("Overrun abort")); - break; - #endif // ABORT_ON_OVERRUN - } else { -#if USE_SHARED_SPI - sd.card()->spiStop(); -#endif // USE_SHARED_SPI - acquireData(&curBlock->data[curBlock->count++]); -#if USE_SHARED_SPI - sd.card()->spiStart(); -#endif // USE_SHARED_SPI - if (curBlock->count == DATA_DIM) { - fullQueue[fullHead] = curBlock; - fullHead = fullHead < QUEUE_LAST ? fullHead + 1 : 0; - curBlock = 0; - } - } - } - if (fullHead == fullTail) { - // Exit loop if done. - if (closeFile) { - break; - } - } else if (!sd.card()->isBusy()) { - // Get address of block to write. - block_t* pBlock = fullQueue[fullTail]; - fullTail = fullTail < QUEUE_LAST ? fullTail + 1 : 0; - // Write block to SD. - uint32_t usec = micros(); - if (!sd.card()->writeData((uint8_t*)pBlock)) { - error("write data failed"); - } - usec = micros() - usec; - if (usec > maxLatency) { - maxLatency = usec; - } - // Move block to empty queue. - emptyStack[emptyTop++] = pBlock; - bn++; - if (bn == FILE_BLOCK_COUNT) { - // File full so stop - break; - } - } - } - if (!sd.card()->writeStop()) { - error("writeStop failed"); - } - Serial.print(F("Min Free buffers: ")); - Serial.println(minTop); - Serial.print(F("Max block write usec: ")); - Serial.println(maxLatency); - Serial.print(F("Overruns: ")); - Serial.println(overrunTotal); - // Truncate file if recording stopped early. - if (bn != FILE_BLOCK_COUNT) { - Serial.println(F("Truncating file")); - if (!binFile.truncate(512L * bn)) { - error("Can't truncate file"); - } - } -} -//------------------------------------------------------------------------------ -void recoverTmpFile() { - uint16_t count; - if (!binFile.open(TMP_FILE_NAME, O_RDWR)) { - return; - } - if (binFile.read(&count, 2) != 2 || count != DATA_DIM) { - error("Please delete existing " TMP_FILE_NAME); - } - Serial.println(F("\nRecovering data in tmp file " TMP_FILE_NAME)); - uint32_t bgnBlock = 0; - uint32_t endBlock = binFile.fileSize()/512 - 1; - // find last used block. - while (bgnBlock < endBlock) { - uint32_t midBlock = (bgnBlock + endBlock + 1)/2; - binFile.seekSet(512*midBlock); - if (binFile.read(&count, 2) != 2) error("read"); - if (count == 0 || count > DATA_DIM) { - endBlock = midBlock - 1; - } else { - bgnBlock = midBlock; - } - } - // truncate after last used block. - if (!binFile.truncate(512*(bgnBlock + 1))) { - error("Truncate " TMP_FILE_NAME " failed"); - } - renameBinFile(); -} -//----------------------------------------------------------------------------- -void renameBinFile() { - while (sd.exists(binName)) { - if (binName[BASE_NAME_SIZE + 1] != '9') { - binName[BASE_NAME_SIZE + 1]++; - } else { - binName[BASE_NAME_SIZE + 1] = '0'; - if (binName[BASE_NAME_SIZE] == '9') { - error("Can't create file name"); - } - binName[BASE_NAME_SIZE]++; - } - } - if (!binFile.rename(binName)) { - error("Can't rename file"); - } - Serial.print(F("File renamed: ")); - Serial.println(binName); - Serial.print(F("File size: ")); - Serial.print(binFile.fileSize()/512); - Serial.println(F(" blocks")); -} -//------------------------------------------------------------------------------ -void testSensor() { - const uint32_t interval = 200000; - int32_t diff; - data_t data; - Serial.println(F("\nTesting - type any character to stop\n")); - // Wait for Serial Idle. - delay(1000); - printHeader(&Serial); - uint32_t m = micros(); - while (!Serial.available()) { - m += interval; - do { - diff = m - micros(); - } while (diff > 0); - acquireData(&data); - printData(&Serial, &data); - } -} -//------------------------------------------------------------------------------ -void setup(void) { - if (ERROR_LED_PIN >= 0) { - pinMode(ERROR_LED_PIN, OUTPUT); - } - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - Serial.print(F("\nFreeStack: ")); - Serial.println(FreeStack()); - Serial.print(F("Records/block: ")); - Serial.println(DATA_DIM); - if (sizeof(block_t) != 512) { - error("Invalid block size"); - } - // Allow userSetup access to SPI bus. - pinMode(SD_CS_PIN, OUTPUT); - digitalWrite(SD_CS_PIN, HIGH); - - // Setup sensors. - userSetup(); - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50))) { - sd.initErrorPrint(&Serial); - fatalBlink(); - } - // recover existing tmp file. - if (sd.exists(TMP_FILE_NAME)) { - Serial.println(F("\nType 'Y' to recover existing tmp file " TMP_FILE_NAME)); - while (!Serial.available()) { - SysCall::yield(); - } - if (Serial.read() == 'Y') { - recoverTmpFile(); - } else { - error("'Y' not typed, please manually delete " TMP_FILE_NAME); - } - } -} -//------------------------------------------------------------------------------ -void loop(void) { - // Read any Serial data. - do { - delay(10); - } while (Serial.available() && Serial.read() >= 0); - Serial.println(); - Serial.println(F("type:")); - Serial.println(F("b - open existing bin file")); - Serial.println(F("c - convert file to csv")); - Serial.println(F("d - dump data to Serial")); - Serial.println(F("e - overrun error details")); - Serial.println(F("l - list files")); - Serial.println(F("r - record data")); - Serial.println(F("t - test without logging")); - while(!Serial.available()) { - SysCall::yield(); - } -#if WDT_YIELD_TIME_MICROS - Serial.println(F("LowLatencyLogger can not run with watchdog timer")); - SysCall::halt(); -#endif - - char c = tolower(Serial.read()); - - // Discard extra Serial data. - do { - delay(10); - } while (Serial.available() && Serial.read() >= 0); - - if (ERROR_LED_PIN >= 0) { - digitalWrite(ERROR_LED_PIN, LOW); - } - if (c == 'b') { - openBinFile(); - } else if (c == 'c') { - binaryToCsv(); - } else if (c == 'd') { - dumpData(); - } else if (c == 'e') { - checkOverrun(); - } else if (c == 'l') { - Serial.println(F("\nls:")); - sd.ls(&Serial, LS_SIZE); - } else if (c == 'r') { - logData(); - } else if (c == 't') { - testSensor(); - } else { - Serial.println(F("Invalid entry")); - } -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/UserFunctions.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/UserFunctions.cpp deleted file mode 100644 index 23be667..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/UserFunctions.cpp +++ /dev/null @@ -1,41 +0,0 @@ -#include "UserTypes.h" -// User data functions. Modify these functions for your data items. - -// Start time for data -static uint32_t startMicros; - -// Acquire a data record. -void acquireData(data_t* data) { - data->time = micros(); - for (int i = 0; i < ADC_DIM; i++) { - data->adc[i] = analogRead(i); - } -} - -// Print a data record. -void printData(Print* pr, data_t* data) { - if (startMicros == 0) { - startMicros = data->time; - } - pr->print(data->time - startMicros); - for (int i = 0; i < ADC_DIM; i++) { - pr->write(','); - pr->print(data->adc[i]); - } - pr->println(); -} - -// Print data header. -void printHeader(Print* pr) { - startMicros = 0; - pr->print(F("micros")); - for (int i = 0; i < ADC_DIM; i++) { - pr->print(F(",adc")); - pr->print(i); - } - pr->println(); -} - -// Sensor setup -void userSetup() { -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/UserTypes.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/UserTypes.h deleted file mode 100644 index 840d4c7..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLogger/UserTypes.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef UserTypes_h -#define UserTypes_h -#include "Arduino.h" -// User data types. Modify for your data items. -#define FILE_BASE_NAME "adc4pin" -const uint8_t ADC_DIM = 4; -struct data_t { - uint32_t time; - uint16_t adc[ADC_DIM]; -}; -void acquireData(data_t* data); -void printData(Print* pr, data_t* data); -void printHeader(Print* pr); -void userSetup(); -#endif // UserTypes_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/LowLatencyLogger.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/LowLatencyLogger.ino deleted file mode 100644 index 40aa40d..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/LowLatencyLogger.ino +++ /dev/null @@ -1,655 +0,0 @@ -/** - * This program logs data to a binary file. Functions are included - * to convert the binary file to a csv text file. - * - * Samples are logged at regular intervals. The maximum logging rate - * depends on the quality of your SD card and the time required to - * read sensor data. This example has been tested at 500 Hz with - * good SD card on an Uno. 4000 HZ is possible on a Due. - * - * If your SD card has a long write latency, it may be necessary to use - * slower sample rates. Using a Mega Arduino helps overcome latency - * problems since 12 512 byte buffers will be used. - * - * Data is written to the file using a SD multiple block write command. - */ -#include -#include "SdFat.h" -#include "FreeStack.h" -#include "UserTypes.h" - -#ifdef __AVR_ATmega328P__ -#include "MinimumSerial.h" -MinimumSerial MinSerial; -#define Serial MinSerial -#endif // __AVR_ATmega328P__ -//============================================================================== -// Start of configuration constants. -//============================================================================== -// Abort run on an overrun. Data before the overrun will be saved. -#define ABORT_ON_OVERRUN 1 -//------------------------------------------------------------------------------ -//Interval between data records in microseconds. -const uint32_t LOG_INTERVAL_USEC = 2000; -//------------------------------------------------------------------------------ -// Set USE_SHARED_SPI non-zero for use of an SPI sensor. -// May not work for some cards. -#ifndef USE_SHARED_SPI -#define USE_SHARED_SPI 0 -#endif // USE_SHARED_SPI -//------------------------------------------------------------------------------ -// Pin definitions. -// -// SD chip select pin. -const uint8_t SD_CS_PIN = SS; -// -// Digital pin to indicate an error, set to -1 if not used. -// The led blinks for fatal errors. The led goes on solid for -// overrun errors and logging continues unless ABORT_ON_OVERRUN -// is non-zero. -#ifdef ERROR_LED_PIN -#undef ERROR_LED_PIN -#endif // ERROR_LED_PIN -const int8_t ERROR_LED_PIN = -1; -//------------------------------------------------------------------------------ -// File definitions. -// -// Maximum file size in blocks. -// The program creates a contiguous file with FILE_BLOCK_COUNT 512 byte blocks. -// This file is flash erased using special SD commands. The file will be -// truncated if logging is stopped early. -const uint32_t FILE_BLOCK_COUNT = 256000; -// -// log file base name if not defined in UserTypes.h -#ifndef FILE_BASE_NAME -#define FILE_BASE_NAME "data" -#endif // FILE_BASE_NAME -//------------------------------------------------------------------------------ -// Buffer definitions. -// -// The logger will use SdFat's buffer plus BUFFER_BLOCK_COUNT-1 additional -// buffers. -// -#ifndef RAMEND -// Assume ARM. Use total of ten 512 byte buffers. -const uint8_t BUFFER_BLOCK_COUNT = 10; -// -#elif RAMEND < 0X8FF -#error Too little SRAM -// -#elif RAMEND < 0X10FF -// Use total of two 512 byte buffers. -const uint8_t BUFFER_BLOCK_COUNT = 2; -// -#elif RAMEND < 0X20FF -// Use total of four 512 byte buffers. -const uint8_t BUFFER_BLOCK_COUNT = 4; -// -#else // RAMEND -// Use total of 12 512 byte buffers. -const uint8_t BUFFER_BLOCK_COUNT = 12; -#endif // RAMEND -//============================================================================== -// End of configuration constants. -//============================================================================== -// Temporary log file. Will be deleted if a reset or power failure occurs. -#define TMP_FILE_NAME FILE_BASE_NAME "##.bin" - -// Size of file base name. -const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1; -const uint8_t FILE_NAME_DIM = BASE_NAME_SIZE + 7; -char binName[FILE_NAME_DIM] = FILE_BASE_NAME "00.bin"; - -SdFat sd; - -SdBaseFile binFile; - -// Number of data records in a block. -const uint16_t DATA_DIM = (512 - 4)/sizeof(data_t); - -//Compute fill so block size is 512 bytes. FILL_DIM may be zero. -const uint16_t FILL_DIM = 512 - 4 - DATA_DIM*sizeof(data_t); - -struct block_t { - uint16_t count; - uint16_t overrun; - data_t data[DATA_DIM]; - uint8_t fill[FILL_DIM]; -}; -//============================================================================== -// Error messages stored in flash. -#define error(msg) {sd.errorPrint(&Serial, F(msg));fatalBlink();} -//------------------------------------------------------------------------------ -// -void fatalBlink() { - while (true) { - SysCall::yield(); - if (ERROR_LED_PIN >= 0) { - digitalWrite(ERROR_LED_PIN, HIGH); - delay(200); - digitalWrite(ERROR_LED_PIN, LOW); - delay(200); - } - } -} -//------------------------------------------------------------------------------ -// read data file and check for overruns -void checkOverrun() { - bool headerPrinted = false; - block_t block; - uint32_t bn = 0; - - if (!binFile.isOpen()) { - Serial.println(); - Serial.println(F("No current binary file")); - return; - } - binFile.rewind(); - Serial.println(); - Serial.print(F("FreeStack: ")); - Serial.println(FreeStack()); - Serial.println(F("Checking overrun errors - type any character to stop")); - while (binFile.read(&block, 512) == 512) { - if (block.count == 0) { - break; - } - if (block.overrun) { - if (!headerPrinted) { - Serial.println(); - Serial.println(F("Overruns:")); - Serial.println(F("fileBlockNumber,sdBlockNumber,overrunCount")); - headerPrinted = true; - } - Serial.print(bn); - Serial.print(','); - Serial.print(binFile.firstBlock() + bn); - Serial.print(','); - Serial.println(block.overrun); - } - bn++; - } - if (!headerPrinted) { - Serial.println(F("No errors found")); - } else { - Serial.println(F("Done")); - } -} -//----------------------------------------------------------------------------- -// Convert binary file to csv file. -void binaryToCsv() { - uint8_t lastPct = 0; - block_t block; - uint32_t t0 = millis(); - uint32_t syncCluster = 0; - SdFile csvFile; - char csvName[FILE_NAME_DIM]; - - if (!binFile.isOpen()) { - Serial.println(); - Serial.println(F("No current binary file")); - return; - } - Serial.println(); - Serial.print(F("FreeStack: ")); - Serial.println(FreeStack()); - - // Create a new csvFile. - strcpy(csvName, binName); - strcpy(&csvName[BASE_NAME_SIZE + 3], "csv"); - - if (!csvFile.open(csvName, O_WRONLY | O_CREAT | O_TRUNC)) { - error("open csvFile failed"); - } - binFile.rewind(); - Serial.print(F("Writing: ")); - Serial.print(csvName); - Serial.println(F(" - type any character to stop")); - printHeader(&csvFile); - uint32_t tPct = millis(); - while (!Serial.available() && binFile.read(&block, 512) == 512) { - uint16_t i; - if (block.count == 0 || block.count > DATA_DIM) { - break; - } - if (block.overrun) { - csvFile.print(F("OVERRUN,")); - csvFile.println(block.overrun); - } - for (i = 0; i < block.count; i++) { - printData(&csvFile, &block.data[i]); - } - if (csvFile.curCluster() != syncCluster) { - csvFile.sync(); - syncCluster = csvFile.curCluster(); - } - if ((millis() - tPct) > 1000) { - uint8_t pct = binFile.curPosition()/(binFile.fileSize()/100); - if (pct != lastPct) { - tPct = millis(); - lastPct = pct; - Serial.print(pct, DEC); - Serial.println('%'); - } - } - if (Serial.available()) { - break; - } - } - csvFile.close(); - Serial.print(F("Done: ")); - Serial.print(0.001*(millis() - t0)); - Serial.println(F(" Seconds")); -} -//----------------------------------------------------------------------------- -void createBinFile() { - // max number of blocks to erase per erase call - const uint32_t ERASE_SIZE = 262144L; - uint32_t bgnBlock, endBlock; - - // Delete old tmp file. - if (sd.exists(TMP_FILE_NAME)) { - Serial.println(F("Deleting tmp file " TMP_FILE_NAME)); - if (!sd.remove(TMP_FILE_NAME)) { - error("Can't remove tmp file"); - } - } - // Create new file. - Serial.println(F("\nCreating new file")); - binFile.close(); - if (!binFile.createContiguous(TMP_FILE_NAME, 512 * FILE_BLOCK_COUNT)) { - error("createContiguous failed"); - } - // Get the address of the file on the SD. - if (!binFile.contiguousRange(&bgnBlock, &endBlock)) { - error("contiguousRange failed"); - } - // Flash erase all data in the file. - Serial.println(F("Erasing all data")); - uint32_t bgnErase = bgnBlock; - uint32_t endErase; - while (bgnErase < endBlock) { - endErase = bgnErase + ERASE_SIZE; - if (endErase > endBlock) { - endErase = endBlock; - } - if (!sd.card()->erase(bgnErase, endErase)) { - error("erase failed"); - } - bgnErase = endErase + 1; - } -} -//------------------------------------------------------------------------------ -// dump data file to Serial -void dumpData() { - block_t block; - if (!binFile.isOpen()) { - Serial.println(); - Serial.println(F("No current binary file")); - return; - } - binFile.rewind(); - Serial.println(); - Serial.println(F("Type any character to stop")); - delay(1000); - printHeader(&Serial); - while (!Serial.available() && binFile.read(&block , 512) == 512) { - if (block.count == 0) { - break; - } - if (block.overrun) { - Serial.print(F("OVERRUN,")); - Serial.println(block.overrun); - } - for (uint16_t i = 0; i < block.count; i++) { - printData(&Serial, &block.data[i]); - } - } - Serial.println(F("Done")); -} -//------------------------------------------------------------------------------ -// log data -void logData() { - createBinFile(); - recordBinFile(); - renameBinFile(); -} -//------------------------------------------------------------------------------ -void openBinFile() { - char name[FILE_NAME_DIM]; - strcpy(name, binName); - Serial.println(F("\nEnter two digit version")); - Serial.write(name, BASE_NAME_SIZE); - for (int i = 0; i < 2; i++) { - while (!Serial.available()) { - SysCall::yield(); - } - char c = Serial.read(); - Serial.write(c); - if (c < '0' || c > '9') { - Serial.println(F("\nInvalid digit")); - return; - } - name[BASE_NAME_SIZE + i] = c; - } - Serial.println(&name[BASE_NAME_SIZE+2]); - if (!sd.exists(name)) { - Serial.println(F("File does not exist")); - return; - } - binFile.close(); - strcpy(binName, name); - if (!binFile.open(binName, O_RDONLY)) { - Serial.println(F("open failed")); - return; - } - Serial.println(F("File opened")); -} -//------------------------------------------------------------------------------ -void recordBinFile() { - const uint8_t QUEUE_DIM = BUFFER_BLOCK_COUNT + 1; - // Index of last queue location. - const uint8_t QUEUE_LAST = QUEUE_DIM - 1; - - // Allocate extra buffer space. - block_t block[BUFFER_BLOCK_COUNT - 1]; - - block_t* curBlock = 0; - - block_t* emptyStack[BUFFER_BLOCK_COUNT]; - uint8_t emptyTop; - uint8_t minTop; - - block_t* fullQueue[QUEUE_DIM]; - uint8_t fullHead = 0; - uint8_t fullTail = 0; - - // Use SdFat's internal buffer. - emptyStack[0] = (block_t*)sd.vol()->cacheClear(); - if (emptyStack[0] == 0) { - error("cacheClear failed"); - } - // Put rest of buffers on the empty stack. - for (int i = 1; i < BUFFER_BLOCK_COUNT; i++) { - emptyStack[i] = &block[i - 1]; - } - emptyTop = BUFFER_BLOCK_COUNT; - minTop = BUFFER_BLOCK_COUNT; - - // Start a multiple block write. - if (!sd.card()->writeStart(binFile.firstBlock())) { - error("writeStart failed"); - } - Serial.print(F("FreeStack: ")); - Serial.println(FreeStack()); - Serial.println(F("Logging - type any character to stop")); - bool closeFile = false; - uint32_t bn = 0; - uint32_t maxLatency = 0; - uint32_t overrun = 0; - uint32_t overrunTotal = 0; - uint32_t logTime = micros(); - while(1) { - // Time for next data record. - logTime += LOG_INTERVAL_USEC; - if (Serial.available()) { - closeFile = true; - } - if (closeFile) { - if (curBlock != 0) { - // Put buffer in full queue. - fullQueue[fullHead] = curBlock; - fullHead = fullHead < QUEUE_LAST ? fullHead + 1 : 0; - curBlock = 0; - } - } else { - if (curBlock == 0 && emptyTop != 0) { - curBlock = emptyStack[--emptyTop]; - if (emptyTop < minTop) { - minTop = emptyTop; - } - curBlock->count = 0; - curBlock->overrun = overrun; - overrun = 0; - } - if ((int32_t)(logTime - micros()) < 0) { - error("Rate too fast"); - } - int32_t delta; - do { - delta = micros() - logTime; - } while (delta < 0); - if (curBlock == 0) { - overrun++; - overrunTotal++; - if (ERROR_LED_PIN >= 0) { - digitalWrite(ERROR_LED_PIN, HIGH); - } -#if ABORT_ON_OVERRUN - Serial.println(F("Overrun abort")); - break; - #endif // ABORT_ON_OVERRUN - } else { -#if USE_SHARED_SPI - sd.card()->spiStop(); -#endif // USE_SHARED_SPI - acquireData(&curBlock->data[curBlock->count++]); -#if USE_SHARED_SPI - sd.card()->spiStart(); -#endif // USE_SHARED_SPI - if (curBlock->count == DATA_DIM) { - fullQueue[fullHead] = curBlock; - fullHead = fullHead < QUEUE_LAST ? fullHead + 1 : 0; - curBlock = 0; - } - } - } - if (fullHead == fullTail) { - // Exit loop if done. - if (closeFile) { - break; - } - } else if (!sd.card()->isBusy()) { - // Get address of block to write. - block_t* pBlock = fullQueue[fullTail]; - fullTail = fullTail < QUEUE_LAST ? fullTail + 1 : 0; - // Write block to SD. - uint32_t usec = micros(); - if (!sd.card()->writeData((uint8_t*)pBlock)) { - error("write data failed"); - } - usec = micros() - usec; - if (usec > maxLatency) { - maxLatency = usec; - } - // Move block to empty queue. - emptyStack[emptyTop++] = pBlock; - bn++; - if (bn == FILE_BLOCK_COUNT) { - // File full so stop - break; - } - } - } - if (!sd.card()->writeStop()) { - error("writeStop failed"); - } - Serial.print(F("Min Free buffers: ")); - Serial.println(minTop); - Serial.print(F("Max block write usec: ")); - Serial.println(maxLatency); - Serial.print(F("Overruns: ")); - Serial.println(overrunTotal); - // Truncate file if recording stopped early. - if (bn != FILE_BLOCK_COUNT) { - Serial.println(F("Truncating file")); - if (!binFile.truncate(512L * bn)) { - error("Can't truncate file"); - } - } -} -//------------------------------------------------------------------------------ -void recoverTmpFile() { - uint16_t count; - if (!binFile.open(TMP_FILE_NAME, O_RDWR)) { - return; - } - if (binFile.read(&count, 2) != 2 || count != DATA_DIM) { - error("Please delete existing " TMP_FILE_NAME); - } - Serial.println(F("\nRecovering data in tmp file " TMP_FILE_NAME)); - uint32_t bgnBlock = 0; - uint32_t endBlock = binFile.fileSize()/512 - 1; - // find last used block. - while (bgnBlock < endBlock) { - uint32_t midBlock = (bgnBlock + endBlock + 1)/2; - binFile.seekSet(512*midBlock); - if (binFile.read(&count, 2) != 2) error("read"); - if (count == 0 || count > DATA_DIM) { - endBlock = midBlock - 1; - } else { - bgnBlock = midBlock; - } - } - // truncate after last used block. - if (!binFile.truncate(512*(bgnBlock + 1))) { - error("Truncate " TMP_FILE_NAME " failed"); - } - renameBinFile(); -} -//----------------------------------------------------------------------------- -void renameBinFile() { - while (sd.exists(binName)) { - if (binName[BASE_NAME_SIZE + 1] != '9') { - binName[BASE_NAME_SIZE + 1]++; - } else { - binName[BASE_NAME_SIZE + 1] = '0'; - if (binName[BASE_NAME_SIZE] == '9') { - error("Can't create file name"); - } - binName[BASE_NAME_SIZE]++; - } - } - if (!binFile.rename(binName)) { - error("Can't rename file"); - } - Serial.print(F("File renamed: ")); - Serial.println(binName); - Serial.print(F("File size: ")); - Serial.print(binFile.fileSize()/512); - Serial.println(F(" blocks")); -} -//------------------------------------------------------------------------------ -void testSensor() { - const uint32_t interval = 200000; - int32_t diff; - data_t data; - Serial.println(F("\nTesting - type any character to stop\n")); - // Wait for Serial Idle. - delay(1000); - printHeader(&Serial); - uint32_t m = micros(); - while (!Serial.available()) { - m += interval; - do { - diff = m - micros(); - } while (diff > 0); - acquireData(&data); - printData(&Serial, &data); - } -} -//------------------------------------------------------------------------------ -void setup(void) { - if (ERROR_LED_PIN >= 0) { - pinMode(ERROR_LED_PIN, OUTPUT); - } - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - Serial.print(F("\nFreeStack: ")); - Serial.println(FreeStack()); - Serial.print(F("Records/block: ")); - Serial.println(DATA_DIM); - if (sizeof(block_t) != 512) { - error("Invalid block size"); - } - // Allow userSetup access to SPI bus. - pinMode(SD_CS_PIN, OUTPUT); - digitalWrite(SD_CS_PIN, HIGH); - - // Setup sensors. - userSetup(); - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50))) { - sd.initErrorPrint(&Serial); - fatalBlink(); - } - // recover existing tmp file. - if (sd.exists(TMP_FILE_NAME)) { - Serial.println(F("\nType 'Y' to recover existing tmp file " TMP_FILE_NAME)); - while (!Serial.available()) { - SysCall::yield(); - } - if (Serial.read() == 'Y') { - recoverTmpFile(); - } else { - error("'Y' not typed, please manually delete " TMP_FILE_NAME); - } - } -} -//------------------------------------------------------------------------------ -void loop(void) { - // Read any Serial data. - do { - delay(10); - } while (Serial.available() && Serial.read() >= 0); - Serial.println(); - Serial.println(F("type:")); - Serial.println(F("b - open existing bin file")); - Serial.println(F("c - convert file to csv")); - Serial.println(F("d - dump data to Serial")); - Serial.println(F("e - overrun error details")); - Serial.println(F("l - list files")); - Serial.println(F("r - record data")); - Serial.println(F("t - test without logging")); - while(!Serial.available()) { - SysCall::yield(); - } -#if WDT_YIELD_TIME_MICROS - Serial.println(F("LowLatencyLogger can not run with watchdog timer")); - SysCall::halt(); -#endif - - char c = tolower(Serial.read()); - - // Discard extra Serial data. - do { - delay(10); - } while (Serial.available() && Serial.read() >= 0); - - if (ERROR_LED_PIN >= 0) { - digitalWrite(ERROR_LED_PIN, LOW); - } - if (c == 'b') { - openBinFile(); - } else if (c == 'c') { - binaryToCsv(); - } else if (c == 'd') { - dumpData(); - } else if (c == 'e') { - checkOverrun(); - } else if (c == 'l') { - Serial.println(F("\nls:")); - sd.ls(&Serial, LS_SIZE); - } else if (c == 'r') { - logData(); - } else if (c == 't') { - testSensor(); - } else { - Serial.println(F("Invalid entry")); - } -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/LowLatencyLoggerADXL345.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/LowLatencyLoggerADXL345.ino deleted file mode 100644 index 91c8fcc..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/LowLatencyLoggerADXL345.ino +++ /dev/null @@ -1 +0,0 @@ -// Empty file with name LowLatencyLoggerADXL345.ino to make IDE happy. \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/UserFunctions.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/UserFunctions.cpp deleted file mode 100644 index 2f1fea3..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/UserFunctions.cpp +++ /dev/null @@ -1,70 +0,0 @@ -#include "UserTypes.h" -// User data functions. Modify these functions for your data items. - -// Start time for data -static uint32_t startMicros; - -const uint8_t ADXL345_CS = 9; - -const uint8_t POWER_CTL = 0x2D; //Power Control Register -const uint8_t DATA_FORMAT = 0x31; -const uint8_t DATAX0 = 0x32; //X-Axis Data 0 -const uint8_t DATAX1 = 0x33; //X-Axis Data 1 -const uint8_t DATAY0 = 0x34; //Y-Axis Data 0 -const uint8_t DATAY1 = 0x35; //Y-Axis Data 1 -const uint8_t DATAZ0 = 0x36; //Z-Axis Data 0 -const uint8_t DATAZ1 = 0x37; //Z-Axis Data 1 - -void writeADXL345Register(const uint8_t registerAddress, const uint8_t value) { - // Max SPI clock frequency is 5 MHz with CPOL = 1 and CPHA = 1. - SPI.beginTransaction(SPISettings(5000000, MSBFIRST, SPI_MODE3)); - digitalWrite(ADXL345_CS, LOW); - SPI.transfer(registerAddress); - SPI.transfer(value); - digitalWrite(ADXL345_CS, HIGH); - SPI.endTransaction(); -} - -void userSetup() { - SPI.begin(); - pinMode(ADXL345_CS, OUTPUT); - digitalWrite(ADXL345_CS, HIGH); - //Put the ADXL345 into +/- 4G range by writing the value 0x01 to the DATA_FORMAT register. - writeADXL345Register(DATA_FORMAT, 0x01); - //Put the ADXL345 into Measurement Mode by writing 0x08 to the POWER_CTL register. - writeADXL345Register(POWER_CTL, 0x08); //Measurement mode -} - -// Acquire a data record. -void acquireData(data_t* data) { - // Max SPI clock frequency is 5 MHz with CPOL = 1 and CPHA = 1. - SPI.beginTransaction(SPISettings(5000000, MSBFIRST, SPI_MODE3)); - data->time = micros(); - digitalWrite(ADXL345_CS, LOW); - // Read multiple bytes so or 0XC0 with address. - SPI.transfer(DATAX0 | 0XC0); - data->accel[0] = SPI.transfer(0) | (SPI.transfer(0) << 8); - data->accel[1] = SPI.transfer(0) | (SPI.transfer(0) << 8); - data->accel[2] = SPI.transfer(0) | (SPI.transfer(0) << 8); - digitalWrite(ADXL345_CS, HIGH); - SPI.endTransaction(); -} - -// Print a data record. -void printData(Print* pr, data_t* data) { - if (startMicros == 0) { - startMicros = data->time; - } - pr->print(data->time - startMicros); - for (int i = 0; i < ACCEL_DIM; i++) { - pr->write(','); - pr->print(data->accel[i]); - } - pr->println(); -} - -// Print data header. -void printHeader(Print* pr) { - startMicros = 0; - pr->println(F("micros,ax,ay,az")); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/UserTypes.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/UserTypes.h deleted file mode 100644 index 56bc873..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/UserTypes.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef UserTypes_h -#define UserTypes_h -#include "Arduino.h" -#include "SPI.h" -#define USE_SHARED_SPI 1 -#define FILE_BASE_NAME "ADXL4G" -// User data types. Modify for your data items. -const uint8_t ACCEL_DIM = 3; -struct data_t { - uint32_t time; - int16_t accel[ACCEL_DIM]; -}; -void acquireData(data_t* data); -void printData(Print* pr, data_t* data); -void printHeader(Print* pr); -void userSetup(); -#endif // UserTypes_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/readme.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/readme.txt deleted file mode 100644 index a68ba78..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerADXL345/readme.txt +++ /dev/null @@ -1 +0,0 @@ -Test of shared SPI for LowLatencyLogger. \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/LowLatencyLogger.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/LowLatencyLogger.ino deleted file mode 100644 index 40aa40d..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/LowLatencyLogger.ino +++ /dev/null @@ -1,655 +0,0 @@ -/** - * This program logs data to a binary file. Functions are included - * to convert the binary file to a csv text file. - * - * Samples are logged at regular intervals. The maximum logging rate - * depends on the quality of your SD card and the time required to - * read sensor data. This example has been tested at 500 Hz with - * good SD card on an Uno. 4000 HZ is possible on a Due. - * - * If your SD card has a long write latency, it may be necessary to use - * slower sample rates. Using a Mega Arduino helps overcome latency - * problems since 12 512 byte buffers will be used. - * - * Data is written to the file using a SD multiple block write command. - */ -#include -#include "SdFat.h" -#include "FreeStack.h" -#include "UserTypes.h" - -#ifdef __AVR_ATmega328P__ -#include "MinimumSerial.h" -MinimumSerial MinSerial; -#define Serial MinSerial -#endif // __AVR_ATmega328P__ -//============================================================================== -// Start of configuration constants. -//============================================================================== -// Abort run on an overrun. Data before the overrun will be saved. -#define ABORT_ON_OVERRUN 1 -//------------------------------------------------------------------------------ -//Interval between data records in microseconds. -const uint32_t LOG_INTERVAL_USEC = 2000; -//------------------------------------------------------------------------------ -// Set USE_SHARED_SPI non-zero for use of an SPI sensor. -// May not work for some cards. -#ifndef USE_SHARED_SPI -#define USE_SHARED_SPI 0 -#endif // USE_SHARED_SPI -//------------------------------------------------------------------------------ -// Pin definitions. -// -// SD chip select pin. -const uint8_t SD_CS_PIN = SS; -// -// Digital pin to indicate an error, set to -1 if not used. -// The led blinks for fatal errors. The led goes on solid for -// overrun errors and logging continues unless ABORT_ON_OVERRUN -// is non-zero. -#ifdef ERROR_LED_PIN -#undef ERROR_LED_PIN -#endif // ERROR_LED_PIN -const int8_t ERROR_LED_PIN = -1; -//------------------------------------------------------------------------------ -// File definitions. -// -// Maximum file size in blocks. -// The program creates a contiguous file with FILE_BLOCK_COUNT 512 byte blocks. -// This file is flash erased using special SD commands. The file will be -// truncated if logging is stopped early. -const uint32_t FILE_BLOCK_COUNT = 256000; -// -// log file base name if not defined in UserTypes.h -#ifndef FILE_BASE_NAME -#define FILE_BASE_NAME "data" -#endif // FILE_BASE_NAME -//------------------------------------------------------------------------------ -// Buffer definitions. -// -// The logger will use SdFat's buffer plus BUFFER_BLOCK_COUNT-1 additional -// buffers. -// -#ifndef RAMEND -// Assume ARM. Use total of ten 512 byte buffers. -const uint8_t BUFFER_BLOCK_COUNT = 10; -// -#elif RAMEND < 0X8FF -#error Too little SRAM -// -#elif RAMEND < 0X10FF -// Use total of two 512 byte buffers. -const uint8_t BUFFER_BLOCK_COUNT = 2; -// -#elif RAMEND < 0X20FF -// Use total of four 512 byte buffers. -const uint8_t BUFFER_BLOCK_COUNT = 4; -// -#else // RAMEND -// Use total of 12 512 byte buffers. -const uint8_t BUFFER_BLOCK_COUNT = 12; -#endif // RAMEND -//============================================================================== -// End of configuration constants. -//============================================================================== -// Temporary log file. Will be deleted if a reset or power failure occurs. -#define TMP_FILE_NAME FILE_BASE_NAME "##.bin" - -// Size of file base name. -const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1; -const uint8_t FILE_NAME_DIM = BASE_NAME_SIZE + 7; -char binName[FILE_NAME_DIM] = FILE_BASE_NAME "00.bin"; - -SdFat sd; - -SdBaseFile binFile; - -// Number of data records in a block. -const uint16_t DATA_DIM = (512 - 4)/sizeof(data_t); - -//Compute fill so block size is 512 bytes. FILL_DIM may be zero. -const uint16_t FILL_DIM = 512 - 4 - DATA_DIM*sizeof(data_t); - -struct block_t { - uint16_t count; - uint16_t overrun; - data_t data[DATA_DIM]; - uint8_t fill[FILL_DIM]; -}; -//============================================================================== -// Error messages stored in flash. -#define error(msg) {sd.errorPrint(&Serial, F(msg));fatalBlink();} -//------------------------------------------------------------------------------ -// -void fatalBlink() { - while (true) { - SysCall::yield(); - if (ERROR_LED_PIN >= 0) { - digitalWrite(ERROR_LED_PIN, HIGH); - delay(200); - digitalWrite(ERROR_LED_PIN, LOW); - delay(200); - } - } -} -//------------------------------------------------------------------------------ -// read data file and check for overruns -void checkOverrun() { - bool headerPrinted = false; - block_t block; - uint32_t bn = 0; - - if (!binFile.isOpen()) { - Serial.println(); - Serial.println(F("No current binary file")); - return; - } - binFile.rewind(); - Serial.println(); - Serial.print(F("FreeStack: ")); - Serial.println(FreeStack()); - Serial.println(F("Checking overrun errors - type any character to stop")); - while (binFile.read(&block, 512) == 512) { - if (block.count == 0) { - break; - } - if (block.overrun) { - if (!headerPrinted) { - Serial.println(); - Serial.println(F("Overruns:")); - Serial.println(F("fileBlockNumber,sdBlockNumber,overrunCount")); - headerPrinted = true; - } - Serial.print(bn); - Serial.print(','); - Serial.print(binFile.firstBlock() + bn); - Serial.print(','); - Serial.println(block.overrun); - } - bn++; - } - if (!headerPrinted) { - Serial.println(F("No errors found")); - } else { - Serial.println(F("Done")); - } -} -//----------------------------------------------------------------------------- -// Convert binary file to csv file. -void binaryToCsv() { - uint8_t lastPct = 0; - block_t block; - uint32_t t0 = millis(); - uint32_t syncCluster = 0; - SdFile csvFile; - char csvName[FILE_NAME_DIM]; - - if (!binFile.isOpen()) { - Serial.println(); - Serial.println(F("No current binary file")); - return; - } - Serial.println(); - Serial.print(F("FreeStack: ")); - Serial.println(FreeStack()); - - // Create a new csvFile. - strcpy(csvName, binName); - strcpy(&csvName[BASE_NAME_SIZE + 3], "csv"); - - if (!csvFile.open(csvName, O_WRONLY | O_CREAT | O_TRUNC)) { - error("open csvFile failed"); - } - binFile.rewind(); - Serial.print(F("Writing: ")); - Serial.print(csvName); - Serial.println(F(" - type any character to stop")); - printHeader(&csvFile); - uint32_t tPct = millis(); - while (!Serial.available() && binFile.read(&block, 512) == 512) { - uint16_t i; - if (block.count == 0 || block.count > DATA_DIM) { - break; - } - if (block.overrun) { - csvFile.print(F("OVERRUN,")); - csvFile.println(block.overrun); - } - for (i = 0; i < block.count; i++) { - printData(&csvFile, &block.data[i]); - } - if (csvFile.curCluster() != syncCluster) { - csvFile.sync(); - syncCluster = csvFile.curCluster(); - } - if ((millis() - tPct) > 1000) { - uint8_t pct = binFile.curPosition()/(binFile.fileSize()/100); - if (pct != lastPct) { - tPct = millis(); - lastPct = pct; - Serial.print(pct, DEC); - Serial.println('%'); - } - } - if (Serial.available()) { - break; - } - } - csvFile.close(); - Serial.print(F("Done: ")); - Serial.print(0.001*(millis() - t0)); - Serial.println(F(" Seconds")); -} -//----------------------------------------------------------------------------- -void createBinFile() { - // max number of blocks to erase per erase call - const uint32_t ERASE_SIZE = 262144L; - uint32_t bgnBlock, endBlock; - - // Delete old tmp file. - if (sd.exists(TMP_FILE_NAME)) { - Serial.println(F("Deleting tmp file " TMP_FILE_NAME)); - if (!sd.remove(TMP_FILE_NAME)) { - error("Can't remove tmp file"); - } - } - // Create new file. - Serial.println(F("\nCreating new file")); - binFile.close(); - if (!binFile.createContiguous(TMP_FILE_NAME, 512 * FILE_BLOCK_COUNT)) { - error("createContiguous failed"); - } - // Get the address of the file on the SD. - if (!binFile.contiguousRange(&bgnBlock, &endBlock)) { - error("contiguousRange failed"); - } - // Flash erase all data in the file. - Serial.println(F("Erasing all data")); - uint32_t bgnErase = bgnBlock; - uint32_t endErase; - while (bgnErase < endBlock) { - endErase = bgnErase + ERASE_SIZE; - if (endErase > endBlock) { - endErase = endBlock; - } - if (!sd.card()->erase(bgnErase, endErase)) { - error("erase failed"); - } - bgnErase = endErase + 1; - } -} -//------------------------------------------------------------------------------ -// dump data file to Serial -void dumpData() { - block_t block; - if (!binFile.isOpen()) { - Serial.println(); - Serial.println(F("No current binary file")); - return; - } - binFile.rewind(); - Serial.println(); - Serial.println(F("Type any character to stop")); - delay(1000); - printHeader(&Serial); - while (!Serial.available() && binFile.read(&block , 512) == 512) { - if (block.count == 0) { - break; - } - if (block.overrun) { - Serial.print(F("OVERRUN,")); - Serial.println(block.overrun); - } - for (uint16_t i = 0; i < block.count; i++) { - printData(&Serial, &block.data[i]); - } - } - Serial.println(F("Done")); -} -//------------------------------------------------------------------------------ -// log data -void logData() { - createBinFile(); - recordBinFile(); - renameBinFile(); -} -//------------------------------------------------------------------------------ -void openBinFile() { - char name[FILE_NAME_DIM]; - strcpy(name, binName); - Serial.println(F("\nEnter two digit version")); - Serial.write(name, BASE_NAME_SIZE); - for (int i = 0; i < 2; i++) { - while (!Serial.available()) { - SysCall::yield(); - } - char c = Serial.read(); - Serial.write(c); - if (c < '0' || c > '9') { - Serial.println(F("\nInvalid digit")); - return; - } - name[BASE_NAME_SIZE + i] = c; - } - Serial.println(&name[BASE_NAME_SIZE+2]); - if (!sd.exists(name)) { - Serial.println(F("File does not exist")); - return; - } - binFile.close(); - strcpy(binName, name); - if (!binFile.open(binName, O_RDONLY)) { - Serial.println(F("open failed")); - return; - } - Serial.println(F("File opened")); -} -//------------------------------------------------------------------------------ -void recordBinFile() { - const uint8_t QUEUE_DIM = BUFFER_BLOCK_COUNT + 1; - // Index of last queue location. - const uint8_t QUEUE_LAST = QUEUE_DIM - 1; - - // Allocate extra buffer space. - block_t block[BUFFER_BLOCK_COUNT - 1]; - - block_t* curBlock = 0; - - block_t* emptyStack[BUFFER_BLOCK_COUNT]; - uint8_t emptyTop; - uint8_t minTop; - - block_t* fullQueue[QUEUE_DIM]; - uint8_t fullHead = 0; - uint8_t fullTail = 0; - - // Use SdFat's internal buffer. - emptyStack[0] = (block_t*)sd.vol()->cacheClear(); - if (emptyStack[0] == 0) { - error("cacheClear failed"); - } - // Put rest of buffers on the empty stack. - for (int i = 1; i < BUFFER_BLOCK_COUNT; i++) { - emptyStack[i] = &block[i - 1]; - } - emptyTop = BUFFER_BLOCK_COUNT; - minTop = BUFFER_BLOCK_COUNT; - - // Start a multiple block write. - if (!sd.card()->writeStart(binFile.firstBlock())) { - error("writeStart failed"); - } - Serial.print(F("FreeStack: ")); - Serial.println(FreeStack()); - Serial.println(F("Logging - type any character to stop")); - bool closeFile = false; - uint32_t bn = 0; - uint32_t maxLatency = 0; - uint32_t overrun = 0; - uint32_t overrunTotal = 0; - uint32_t logTime = micros(); - while(1) { - // Time for next data record. - logTime += LOG_INTERVAL_USEC; - if (Serial.available()) { - closeFile = true; - } - if (closeFile) { - if (curBlock != 0) { - // Put buffer in full queue. - fullQueue[fullHead] = curBlock; - fullHead = fullHead < QUEUE_LAST ? fullHead + 1 : 0; - curBlock = 0; - } - } else { - if (curBlock == 0 && emptyTop != 0) { - curBlock = emptyStack[--emptyTop]; - if (emptyTop < minTop) { - minTop = emptyTop; - } - curBlock->count = 0; - curBlock->overrun = overrun; - overrun = 0; - } - if ((int32_t)(logTime - micros()) < 0) { - error("Rate too fast"); - } - int32_t delta; - do { - delta = micros() - logTime; - } while (delta < 0); - if (curBlock == 0) { - overrun++; - overrunTotal++; - if (ERROR_LED_PIN >= 0) { - digitalWrite(ERROR_LED_PIN, HIGH); - } -#if ABORT_ON_OVERRUN - Serial.println(F("Overrun abort")); - break; - #endif // ABORT_ON_OVERRUN - } else { -#if USE_SHARED_SPI - sd.card()->spiStop(); -#endif // USE_SHARED_SPI - acquireData(&curBlock->data[curBlock->count++]); -#if USE_SHARED_SPI - sd.card()->spiStart(); -#endif // USE_SHARED_SPI - if (curBlock->count == DATA_DIM) { - fullQueue[fullHead] = curBlock; - fullHead = fullHead < QUEUE_LAST ? fullHead + 1 : 0; - curBlock = 0; - } - } - } - if (fullHead == fullTail) { - // Exit loop if done. - if (closeFile) { - break; - } - } else if (!sd.card()->isBusy()) { - // Get address of block to write. - block_t* pBlock = fullQueue[fullTail]; - fullTail = fullTail < QUEUE_LAST ? fullTail + 1 : 0; - // Write block to SD. - uint32_t usec = micros(); - if (!sd.card()->writeData((uint8_t*)pBlock)) { - error("write data failed"); - } - usec = micros() - usec; - if (usec > maxLatency) { - maxLatency = usec; - } - // Move block to empty queue. - emptyStack[emptyTop++] = pBlock; - bn++; - if (bn == FILE_BLOCK_COUNT) { - // File full so stop - break; - } - } - } - if (!sd.card()->writeStop()) { - error("writeStop failed"); - } - Serial.print(F("Min Free buffers: ")); - Serial.println(minTop); - Serial.print(F("Max block write usec: ")); - Serial.println(maxLatency); - Serial.print(F("Overruns: ")); - Serial.println(overrunTotal); - // Truncate file if recording stopped early. - if (bn != FILE_BLOCK_COUNT) { - Serial.println(F("Truncating file")); - if (!binFile.truncate(512L * bn)) { - error("Can't truncate file"); - } - } -} -//------------------------------------------------------------------------------ -void recoverTmpFile() { - uint16_t count; - if (!binFile.open(TMP_FILE_NAME, O_RDWR)) { - return; - } - if (binFile.read(&count, 2) != 2 || count != DATA_DIM) { - error("Please delete existing " TMP_FILE_NAME); - } - Serial.println(F("\nRecovering data in tmp file " TMP_FILE_NAME)); - uint32_t bgnBlock = 0; - uint32_t endBlock = binFile.fileSize()/512 - 1; - // find last used block. - while (bgnBlock < endBlock) { - uint32_t midBlock = (bgnBlock + endBlock + 1)/2; - binFile.seekSet(512*midBlock); - if (binFile.read(&count, 2) != 2) error("read"); - if (count == 0 || count > DATA_DIM) { - endBlock = midBlock - 1; - } else { - bgnBlock = midBlock; - } - } - // truncate after last used block. - if (!binFile.truncate(512*(bgnBlock + 1))) { - error("Truncate " TMP_FILE_NAME " failed"); - } - renameBinFile(); -} -//----------------------------------------------------------------------------- -void renameBinFile() { - while (sd.exists(binName)) { - if (binName[BASE_NAME_SIZE + 1] != '9') { - binName[BASE_NAME_SIZE + 1]++; - } else { - binName[BASE_NAME_SIZE + 1] = '0'; - if (binName[BASE_NAME_SIZE] == '9') { - error("Can't create file name"); - } - binName[BASE_NAME_SIZE]++; - } - } - if (!binFile.rename(binName)) { - error("Can't rename file"); - } - Serial.print(F("File renamed: ")); - Serial.println(binName); - Serial.print(F("File size: ")); - Serial.print(binFile.fileSize()/512); - Serial.println(F(" blocks")); -} -//------------------------------------------------------------------------------ -void testSensor() { - const uint32_t interval = 200000; - int32_t diff; - data_t data; - Serial.println(F("\nTesting - type any character to stop\n")); - // Wait for Serial Idle. - delay(1000); - printHeader(&Serial); - uint32_t m = micros(); - while (!Serial.available()) { - m += interval; - do { - diff = m - micros(); - } while (diff > 0); - acquireData(&data); - printData(&Serial, &data); - } -} -//------------------------------------------------------------------------------ -void setup(void) { - if (ERROR_LED_PIN >= 0) { - pinMode(ERROR_LED_PIN, OUTPUT); - } - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - Serial.print(F("\nFreeStack: ")); - Serial.println(FreeStack()); - Serial.print(F("Records/block: ")); - Serial.println(DATA_DIM); - if (sizeof(block_t) != 512) { - error("Invalid block size"); - } - // Allow userSetup access to SPI bus. - pinMode(SD_CS_PIN, OUTPUT); - digitalWrite(SD_CS_PIN, HIGH); - - // Setup sensors. - userSetup(); - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50))) { - sd.initErrorPrint(&Serial); - fatalBlink(); - } - // recover existing tmp file. - if (sd.exists(TMP_FILE_NAME)) { - Serial.println(F("\nType 'Y' to recover existing tmp file " TMP_FILE_NAME)); - while (!Serial.available()) { - SysCall::yield(); - } - if (Serial.read() == 'Y') { - recoverTmpFile(); - } else { - error("'Y' not typed, please manually delete " TMP_FILE_NAME); - } - } -} -//------------------------------------------------------------------------------ -void loop(void) { - // Read any Serial data. - do { - delay(10); - } while (Serial.available() && Serial.read() >= 0); - Serial.println(); - Serial.println(F("type:")); - Serial.println(F("b - open existing bin file")); - Serial.println(F("c - convert file to csv")); - Serial.println(F("d - dump data to Serial")); - Serial.println(F("e - overrun error details")); - Serial.println(F("l - list files")); - Serial.println(F("r - record data")); - Serial.println(F("t - test without logging")); - while(!Serial.available()) { - SysCall::yield(); - } -#if WDT_YIELD_TIME_MICROS - Serial.println(F("LowLatencyLogger can not run with watchdog timer")); - SysCall::halt(); -#endif - - char c = tolower(Serial.read()); - - // Discard extra Serial data. - do { - delay(10); - } while (Serial.available() && Serial.read() >= 0); - - if (ERROR_LED_PIN >= 0) { - digitalWrite(ERROR_LED_PIN, LOW); - } - if (c == 'b') { - openBinFile(); - } else if (c == 'c') { - binaryToCsv(); - } else if (c == 'd') { - dumpData(); - } else if (c == 'e') { - checkOverrun(); - } else if (c == 'l') { - Serial.println(F("\nls:")); - sd.ls(&Serial, LS_SIZE); - } else if (c == 'r') { - logData(); - } else if (c == 't') { - testSensor(); - } else { - Serial.println(F("Invalid entry")); - } -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/LowLatencyLoggerMPU6050.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/LowLatencyLoggerMPU6050.ino deleted file mode 100644 index 7c592a8..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/LowLatencyLoggerMPU6050.ino +++ /dev/null @@ -1,2 +0,0 @@ -// Empty file with name LowLatencyLoggerMPU6050.ino to make IDE happy. - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/UserFunctions.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/UserFunctions.cpp deleted file mode 100644 index 601869a..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/UserFunctions.cpp +++ /dev/null @@ -1,51 +0,0 @@ -// User data functions. Modify these functions for your data items. -#include "UserTypes.h" -#include "Wire.h" -#include "I2Cdev.h" -#include "MPU6050.h" -//------------------------------------------------------------------------------ -MPU6050 mpu; -static uint32_t startMicros; -// Acquire a data record. -void acquireData(data_t* data) { - data->time = micros(); - mpu.getMotion6(&data->ax, &data->ay, &data->az, - &data->gx, &data->gy, &data->gz); -} - -// setup AVR I2C -void userSetup() { -#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE - Wire.begin(); - Wire.setClock(400000); -#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE - Fastwire::setup(400, true); -#endif - mpu.initialize(); -} - -// Print a data record. -void printData(Print* pr, data_t* data) { - if (startMicros == 0) { - startMicros = data->time; - } - pr->print(data->time- startMicros); - pr->write(','); - pr->print(data->ax); - pr->write(','); - pr->print(data->ay); - pr->write(','); - pr->print(data->az); - pr->write(','); - pr->print(data->gx); - pr->write(','); - pr->print(data->gy); - pr->write(','); - pr->println(data->gz); -} - -// Print data header. -void printHeader(Print* pr) { - startMicros = 0; - pr->println(F("micros,ax,ay,az,gx,gy,gz")); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/UserTypes.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/UserTypes.h deleted file mode 100644 index 05f7e9f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/LowLatencyLoggerMPU6050/UserTypes.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef UserTypes_h -#define UserTypes_h -#include "Arduino.h" -#define FILE_BASE_NAME "mpuraw" -struct data_t { - unsigned long time; - int16_t ax; - int16_t ay; - int16_t az; - int16_t gx; - int16_t gy; - int16_t gz; -}; -void acquireData(data_t* data); -void printData(Print* pr, data_t* data); -void printHeader(Print* pr); -void userSetup(); -#endif // UserTypes_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/OpenNext/OpenNext.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/OpenNext/OpenNext.ino deleted file mode 100644 index ac6c4b6..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/OpenNext/OpenNext.ino +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Print size, modify date/time, and name for all files in root. - */ -#include -#include "SdFat.h" - -// SD default chip select pin. -const uint8_t chipSelect = SS; - -// file system object -SdFat sd; - -SdFile root; -SdFile file; -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - - Serial.println("Type any character to start"); - while (!Serial.available()) { - SysCall::yield(); - } - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } - if (!root.open("/")) { - sd.errorHalt("open root failed"); - } - // Open next file in root. - // Warning, openNext starts at the current directory position - // so a rewind of the directory may be required. - while (file.openNext(&root, O_RDONLY)) { - file.printFileSize(&Serial); - Serial.write(' '); - file.printModifyDateTime(&Serial); - Serial.write(' '); - file.printName(&Serial); - if (file.isDir()) { - // Indicate a directory. - Serial.write('/'); - } - Serial.println(); - file.close(); - } - if (root.getError()) { - Serial.println("openNext failed"); - } else { - Serial.println("Done!"); - } -} -//------------------------------------------------------------------------------ -void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/PrintBenchmark/PrintBenchmark.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/PrintBenchmark/PrintBenchmark.ino deleted file mode 100644 index 8556b62..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/PrintBenchmark/PrintBenchmark.ino +++ /dev/null @@ -1,152 +0,0 @@ -/* - * This program is a simple Print benchmark. - */ -#include -#include "SdFat.h" -#include "sdios.h" -#include "FreeStack.h" - -// SD chip select pin -const uint8_t chipSelect = SS; - -// number of lines to print -const uint16_t N_PRINT = 20000; - -// file system -SdFat sd; - -// test file -SdFile file; - -// Serial output stream -ArduinoOutStream cout(Serial); -//------------------------------------------------------------------------------ -// store error strings in flash to save RAM -#define error(s) sd.errorHalt(F(s)) -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } -} -//------------------------------------------------------------------------------ -void loop() { - uint32_t maxLatency; - uint32_t minLatency; - uint32_t totalLatency; - - // Read any existing Serial data. - do { - delay(10); - } while (Serial.available() && Serial.read() >= 0); - // F stores strings in flash to save RAM - cout << F("Type any character to start\n"); - while (!Serial.available()) { - SysCall::yield(); - } - delay(400); // catch Due reset problem - - cout << F("FreeStack: ") << FreeStack() << endl; - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } - - cout << F("Type is FAT") << int(sd.vol()->fatType()) << endl; - - cout << F("Starting print test. Please wait.\n\n"); - - // do write test - for (int test = 0; test < 6; test++) { - char fileName[13] = "bench0.txt"; - fileName[5] = '0' + test; - // open or create file - truncate existing file. - if (!file.open(fileName, O_RDWR | O_CREAT | O_TRUNC)) { - error("open failed"); - } - maxLatency = 0; - minLatency = 999999; - totalLatency = 0; - switch(test) { - case 0: - cout << F("Test of println(uint16_t)\n"); - break; - - case 1: - cout << F("Test of printField(uint16_t, char)\n"); - break; - - case 2: - cout << F("Test of println(uint32_t)\n"); - break; - - case 3: - cout << F("Test of printField(uint32_t, char)\n"); - break; - case 4: - cout << F("Test of println(float)\n"); - break; - - case 5: - cout << F("Test of printField(float, char)\n"); - break; - } - - uint32_t t = millis(); - for (uint16_t i = 0; i < N_PRINT; i++) { - uint32_t m = micros(); - - switch(test) { - case 0: - file.println(i); - break; - - case 1: - file.printField(i, '\n'); - break; - - case 2: - file.println(12345678UL + i); - break; - - case 3: - file.printField(12345678UL + i, '\n'); - break; - - case 4: - file.println((float)0.01*i); - break; - - case 5: - file.printField((float)0.01*i, '\n'); - break; - } - if (file.getWriteError()) { - error("write failed"); - } - m = micros() - m; - if (maxLatency < m) { - maxLatency = m; - } - if (minLatency > m) { - minLatency = m; - } - totalLatency += m; - } - file.close(); - t = millis() - t; - double s = file.fileSize(); - cout << F("Time ") << 0.001*t << F(" sec\n"); - cout << F("File size ") << 0.001*s << F(" KB\n"); - cout << F("Write ") << s/t << F(" KB/sec\n"); - cout << F("Maximum latency: ") << maxLatency; - cout << F(" usec, Minimum Latency: ") << minLatency; - cout << F(" usec, Avg Latency: "); - cout << totalLatency/N_PRINT << F(" usec\n\n"); - } - cout << F("Done!\n\n"); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/QuickStart/QuickStart.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/QuickStart/QuickStart.ino deleted file mode 100644 index a36a14b..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/QuickStart/QuickStart.ino +++ /dev/null @@ -1,161 +0,0 @@ -// Quick hardware test for SPI card access. -// -#include -#include "SdFat.h" -#include "sdios.h" -// -// Set DISABLE_CHIP_SELECT to disable a second SPI device. -// For example, with the Ethernet shield, set DISABLE_CHIP_SELECT -// to 10 to disable the Ethernet controller. -const int8_t DISABLE_CHIP_SELECT = -1; -// -// Test with reduced SPI speed for breadboards. SD_SCK_MHZ(4) will select -// the highest speed supported by the board that is not over 4 MHz. -// Change SPI_SPEED to SD_SCK_MHZ(50) for best performance. -#define SPI_SPEED SD_SCK_MHZ(4) -//------------------------------------------------------------------------------ -// File system object. -SdFat sd; - -// Serial streams -ArduinoOutStream cout(Serial); - -// input buffer for line -char cinBuf[40]; -ArduinoInStream cin(Serial, cinBuf, sizeof(cinBuf)); - -// SD card chip select -int chipSelect; - -void cardOrSpeed() { - cout << F("Try another SD card or reduce the SPI bus speed.\n"); - cout << F("Edit SPI_SPEED in this program to change it.\n"); -} - -void reformatMsg() { - cout << F("Try reformatting the card. For best results use\n"); - cout << F("the SdFormatter program in SdFat/examples or download\n"); - cout << F("and use SDFormatter from www.sdcard.org/downloads.\n"); -} - -void setup() { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - cout << F("\nSPI pins:\n"); - cout << F("MISO: ") << int(MISO) << endl; - cout << F("MOSI: ") << int(MOSI) << endl; - cout << F("SCK: ") << int(SCK) << endl; - cout << F("SS: ") << int(SS) << endl; - - if (DISABLE_CHIP_SELECT < 0) { - cout << F( - "\nBe sure to edit DISABLE_CHIP_SELECT if you have\n" - "a second SPI device. For example, with the Ethernet\n" - "shield, DISABLE_CHIP_SELECT should be set to 10\n" - "to disable the Ethernet controller.\n"); - } - cout << F( - "\nSD chip select is the key hardware option.\n" - "Common values are:\n" - "Arduino Ethernet shield, pin 4\n" - "Sparkfun SD shield, pin 8\n" - "Adafruit SD shields and modules, pin 10\n"); -} - -bool firstTry = true; -void loop() { - // Read any existing Serial data. - do { - delay(10); - } while (Serial.available() && Serial.read() >= 0); - - if (!firstTry) { - cout << F("\nRestarting\n"); - } - firstTry = false; - - cout << F("\nEnter the chip select pin number: "); - while (!Serial.available()) { - SysCall::yield(); - } - cin.readline(); - if (cin >> chipSelect) { - cout << chipSelect << endl; - } else { - cout << F("\nInvalid pin number\n"); - return; - } - if (DISABLE_CHIP_SELECT < 0) { - cout << F( - "\nAssuming the SD is the only SPI device.\n" - "Edit DISABLE_CHIP_SELECT to disable another device.\n"); - } else { - cout << F("\nDisabling SPI device on pin "); - cout << int(DISABLE_CHIP_SELECT) << endl; - pinMode(DISABLE_CHIP_SELECT, OUTPUT); - digitalWrite(DISABLE_CHIP_SELECT, HIGH); - } - if (!sd.begin(chipSelect, SPI_SPEED)) { - if (sd.card()->errorCode()) { - cout << F( - "\nSD initialization failed.\n" - "Do not reformat the card!\n" - "Is the card correctly inserted?\n" - "Is chipSelect set to the correct value?\n" - "Does another SPI device need to be disabled?\n" - "Is there a wiring/soldering problem?\n"); - cout << F("\nerrorCode: ") << hex << showbase; - cout << int(sd.card()->errorCode()); - cout << F(", errorData: ") << int(sd.card()->errorData()); - cout << dec << noshowbase << endl; - return; - } - if (sd.vol()->fatType() == 0) { - cout << F("Can't find a valid FAT16/FAT32 partition.\n"); - reformatMsg(); - return; - } - cout << F("begin failed, can't determine error type\n"); - return; - } - cout << F("\nCard successfully initialized.\n"); - cout << endl; - - uint32_t size = sd.card()->cardSize(); - if (size == 0) { - cout << F("Can't determine the card size.\n"); - cardOrSpeed(); - return; - } - uint32_t sizeMB = 0.000512 * size + 0.5; - cout << F("Card size: ") << sizeMB; - cout << F(" MB (MB = 1,000,000 bytes)\n"); - cout << endl; - cout << F("Volume is FAT") << int(sd.vol()->fatType()); - cout << F(", Cluster size (bytes): ") << 512L * sd.vol()->blocksPerCluster(); - cout << endl << endl; - - cout << F("Files found (date time size name):\n"); - sd.ls(LS_R | LS_DATE | LS_SIZE); - - if ((sizeMB > 1100 && sd.vol()->blocksPerCluster() < 64) - || (sizeMB < 2200 && sd.vol()->fatType() == 32)) { - cout << F("\nThis card should be reformatted for best performance.\n"); - cout << F("Use a cluster size of 32 KB for cards larger than 1 GB.\n"); - cout << F("Only cards larger than 2 GB should be formatted FAT32.\n"); - reformatMsg(); - return; - } - // Read any extra Serial data. - do { - delay(10); - } while (Serial.available() && Serial.read() >= 0); - cout << F("\nSuccess! Type any character to restart.\n"); - while (!Serial.available()) { - SysCall::yield(); - } -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/RawWrite/RawWrite.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/RawWrite/RawWrite.ino deleted file mode 100644 index a355f45..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/RawWrite/RawWrite.ino +++ /dev/null @@ -1,180 +0,0 @@ -/* - * This program illustrates raw write functions in SdFat that - * can be used for high speed data logging. - * - * This program simulates logging from a source that produces - * data at a constant rate of RATE_KB_PER_SEC. - * - * Note: Apps should create a very large file then truncates it - * to the length that is used for a logging. It only takes - * a few seconds to erase a 500 MB file since the card only - * marks the blocks as erased; no data transfer is required. - */ -#include -#include "SdFat.h" -#include "sdios.h" -#include "FreeStack.h" - -// SD chip select pin -const uint8_t chipSelect = SS; - -const uint32_t RATE_KB_PER_SEC = 100; - -const uint32_t TEST_TIME_SEC = 100; - -// Time between printing progress dots -const uint32_t DOT_TIME_MS = 5000UL; - -// number of blocks in the contiguous file -const uint32_t BLOCK_COUNT = (1000*RATE_KB_PER_SEC*TEST_TIME_SEC + 511)/512; - -// file system -SdFat sd; - -// test file -SdFile file; - -// file extent -uint32_t bgnBlock, endBlock; - -// Serial output stream -ArduinoOutStream cout(Serial); -//------------------------------------------------------------------------------ -// store error strings in flash to save RAM -#define error(s) sd.errorHalt(F(s)) -//------------------------------------------------------------------------------ -void setup(void) { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } -} -//------------------------------------------------------------------------------ -void loop(void) { - // Read any extra Serial data. - do { - delay(10); - } while (Serial.available() && Serial.read() >= 0); - // F stores strings in flash to save RAM - cout << F("Type any character to start\n"); - while (!Serial.available()) { - SysCall::yield(); - } - - cout << F("FreeStack: ") << FreeStack() << endl; - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } - - // delete possible existing file - sd.remove("RawWrite.txt"); - - // create a contiguous file - if (!file.createContiguous("RawWrite.txt", 512UL*BLOCK_COUNT)) { - error("createContiguous failed"); - } - // get the location of the file's blocks - if (!file.contiguousRange(&bgnBlock, &endBlock)) { - error("contiguousRange failed"); - } - //*********************NOTE************************************** - // NO SdFile calls are allowed while cache is used for raw writes - //*************************************************************** - - // clear the cache and use it as a 512 byte buffer - uint8_t* pCache = (uint8_t*)sd.vol()->cacheClear(); - - // fill cache with eight lines of 64 bytes each - memset(pCache, ' ', 512); - for (uint16_t i = 0; i < 512; i += 64) { - // put line number at end of line then CR/LF - pCache[i + 61] = '0' + (i/64); - pCache[i + 62] = '\r'; - pCache[i + 63] = '\n'; - } - - cout << F("Start raw write of ") << file.fileSize()/1000UL << F(" KB\n"); - cout << F("Target rate: ") << RATE_KB_PER_SEC << F(" KB/sec\n"); - cout << F("Target time: ") << TEST_TIME_SEC << F(" seconds\n"); - - // tell card to setup for multiple block write with pre-erase - if (!sd.card()->writeStart(bgnBlock, BLOCK_COUNT)) { - error("writeStart failed"); - } - // init stats - - delay(1000); - uint32_t dotCount = 0; - uint32_t maxQueuePrint = 0; - uint32_t maxWriteTime = 0; - uint32_t minWriteTime = 9999999; - uint32_t totalWriteTime = 0; - uint32_t maxQueueSize = 0; - uint32_t nWrite = 0; - uint32_t b = 0; - - // write data - uint32_t startTime = millis(); - while (nWrite < BLOCK_COUNT) { - uint32_t nProduced = RATE_KB_PER_SEC*(millis() - startTime)/512UL; - uint32_t queueSize = nProduced - nWrite; - if (queueSize == 0) continue; - if (queueSize > maxQueueSize) { - maxQueueSize = queueSize; - } - if ((millis() - startTime - dotCount*DOT_TIME_MS) > DOT_TIME_MS) { - if (maxQueueSize != maxQueuePrint) { - cout << F("\nQ: ") << maxQueueSize << endl; - maxQueuePrint = maxQueueSize; - } else { - cout << "."; - if (++dotCount%10 == 0) { - cout << endl; - } - } - } - // put block number at start of first line in block - uint32_t n = b++; - for (int8_t d = 5; d >= 0; d--) { - pCache[d] = n || d == 5 ? n % 10 + '0' : ' '; - n /= 10; - } - // write a 512 byte block - uint32_t tw = micros(); - if (!sd.card()->writeData(pCache)) { - error("writeData failed"); - } - tw = micros() - tw; - totalWriteTime += tw; - // check for max write time - if (tw > maxWriteTime) { - maxWriteTime = tw; - } - if (tw < minWriteTime) { - minWriteTime = tw; - } - nWrite++; - } - uint32_t endTime = millis(); - uint32_t avgWriteTime = totalWriteTime/BLOCK_COUNT; - // end multiple block write mode - if (!sd.card()->writeStop()) { - error("writeStop failed"); - } - - cout << F("\nDone\n"); - cout << F("maxQueueSize: ") << maxQueueSize << endl; - cout << F("Elapsed time: ") << setprecision(3)<< 1.e-3*(endTime - startTime); - cout << F(" seconds\n"); - cout << F("Min block write time: ") << minWriteTime << F(" micros\n"); - cout << F("Max block write time: ") << maxWriteTime << F(" micros\n"); - cout << F("Avg block write time: ") << avgWriteTime << F(" micros\n"); - // close file for next pass of loop - file.close(); - Serial.println(); -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsv/ReadCsv.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsv/ReadCsv.ino deleted file mode 100644 index d57aadf..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsv/ReadCsv.ino +++ /dev/null @@ -1,212 +0,0 @@ - -// Functions to read a CSV text file one field at a time. -// -#include -#include - -// next line for SD.h -//#include - -// next two lines for SdFat -#include -SdFat SD; - -#define CS_PIN SS - -// example can use comma or semicolon -#define CSV_DELIM ',' - -File file; - -/* - * Read a file one field at a time. - * - * file - File to read. - * - * str - Character array for the field. - * - * size - Size of str array. - * - * delim - csv delimiter. - * - * return - negative value for failure. - * delimiter, '\n' or zero(EOF) for success. - */ -int csvReadText(File* file, char* str, size_t size, char delim) { - char ch; - int rtn; - size_t n = 0; - while (true) { - // check for EOF - if (!file->available()) { - rtn = 0; - break; - } - if (file->read(&ch, 1) != 1) { - // read error - rtn = -1; - break; - } - // Delete CR. - if (ch == '\r') { - continue; - } - if (ch == delim || ch == '\n') { - rtn = ch; - break; - } - if ((n + 1) >= size) { - // string too long - rtn = -2; - n--; - break; - } - str[n++] = ch; - } - str[n] = '\0'; - return rtn; -} -//------------------------------------------------------------------------------ -int csvReadInt32(File* file, int32_t* num, char delim) { - char buf[20]; - char* ptr; - int rtn = csvReadText(file, buf, sizeof(buf), delim); - if (rtn < 0) return rtn; - *num = strtol(buf, &ptr, 10); - if (buf == ptr) return -3; - while(isspace(*ptr)) ptr++; - return *ptr == 0 ? rtn : -4; -} -//------------------------------------------------------------------------------ -int csvReadInt16(File* file, int16_t* num, char delim) { - int32_t tmp; - int rtn = csvReadInt32(file, &tmp, delim); - if (rtn < 0) return rtn; - if (tmp < INT_MIN || tmp > INT_MAX) return -5; - *num = tmp; - return rtn; -} -//------------------------------------------------------------------------------ -int csvReadUint32(File* file, uint32_t* num, char delim) { - char buf[20]; - char* ptr; - int rtn = csvReadText(file, buf, sizeof(buf), delim); - if (rtn < 0) return rtn; - *num = strtoul(buf, &ptr, 10); - if (buf == ptr) return -3; - while(isspace(*ptr)) ptr++; - return *ptr == 0 ? rtn : -4; -} -//------------------------------------------------------------------------------ -int csvReadUint16(File* file, uint16_t* num, char delim) { - uint32_t tmp; - int rtn = csvReadUint32(file, &tmp, delim); - if (rtn < 0) return rtn; - if (tmp > UINT_MAX) return -5; - *num = tmp; - return rtn; -} -//------------------------------------------------------------------------------ -int csvReadDouble(File* file, double* num, char delim) { - char buf[20]; - char* ptr; - int rtn = csvReadText(file, buf, sizeof(buf), delim); - if (rtn < 0) return rtn; - *num = strtod(buf, &ptr); - if (buf == ptr) return -3; - while(isspace(*ptr)) ptr++; - return *ptr == 0 ? rtn : -4; -} -//------------------------------------------------------------------------------ -int csvReadFloat(File* file, float* num, char delim) { - double tmp; - int rtn = csvReadDouble(file, &tmp, delim); - if (rtn < 0)return rtn; - // could test for too large. - *num = tmp; - return rtn; -} -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - yield(); - } - Serial.println("Type any character to start"); - while (!Serial.available()) { - yield(); - } - // Initialize the SD. - if (!SD.begin(CS_PIN)) { - Serial.println("begin failed"); - return; - } - // Remove existing file. - SD.remove("READTEST.TXT"); - - // Create the file. - file = SD.open("READTEST.TXT", FILE_WRITE); - if (!file) { - Serial.println("open failed"); - return; - } - // Write test data. - file.print(F( -#if CSV_DELIM == ',' - "36,23.20,20.70,57.60,79.50,01:08:14,23.06.16\r\n" - "37,23.21,20.71,57.61,79.51,02:08:14,23.07.16\r\n" -#elif CSV_DELIM == ';' - "36;23.20;20.70;57.60;79.50;01:08:14;23.06.16\r\n" - "37;23.21;20.71;57.61;79.51;02:08:14;23.07.16\r\n" -#else -#error "Bad CSV_DELIM" -#endif -)); - - // Rewind the file for read. - file.seek(0); - - // Read the file and print fields. - int16_t tcalc; - float t1, t2, h1, h2; - // Must be dim 9 to allow for zero byte. - char timeS[9], dateS[9]; - while (file.available()) { - if (csvReadInt16(&file, &tcalc, CSV_DELIM) != CSV_DELIM - || csvReadFloat(&file, &t1, CSV_DELIM) != CSV_DELIM - || csvReadFloat(&file, &t2, CSV_DELIM) != CSV_DELIM - || csvReadFloat(&file, &h1, CSV_DELIM) != CSV_DELIM - || csvReadFloat(&file, &h2, CSV_DELIM) != CSV_DELIM - || csvReadText(&file, timeS, sizeof(timeS), CSV_DELIM) != CSV_DELIM - || csvReadText(&file, dateS, sizeof(dateS), CSV_DELIM) != '\n') { - Serial.println("read error"); - int ch; - int nr = 0; - // print part of file after error. - while ((ch = file.read()) > 0 && nr++ < 100) { - Serial.write(ch); - } - break; - } - Serial.print(tcalc); - Serial.print(CSV_DELIM); - Serial.print(t1); - Serial.print(CSV_DELIM); - Serial.print(t2); - Serial.print(CSV_DELIM); - Serial.print(h1); - Serial.print(CSV_DELIM); - Serial.print(h2); - Serial.print(CSV_DELIM); - Serial.print(timeS); - Serial.print(CSV_DELIM); - Serial.println(dateS); - } - file.close(); -} -//------------------------------------------------------------------------------ -void loop() { -} - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsvArray/ReadCsvArray.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsvArray/ReadCsvArray.ino deleted file mode 100644 index b837a89..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsvArray/ReadCsvArray.ino +++ /dev/null @@ -1,139 +0,0 @@ -// Read a two dimensional array from a CSV file. -// -#include -#include -#define CS_PIN SS - -// 5 X 4 array -#define ROW_DIM 5 -#define COL_DIM 4 - -SdFat SD; -File file; - -/* - * Read a file one field at a time. - * - * file - File to read. - * - * str - Character array for the field. - * - * size - Size of str array. - * - * delim - String containing field delimiters. - * - * return - length of field including terminating delimiter. - * - * Note, the last character of str will not be a delimiter if - * a read error occurs, the field is too long, or the file - * does not end with a delimiter. Consider this an error - * if not at end-of-file. - * - */ -size_t readField(File* file, char* str, size_t size, const char* delim) { - char ch; - size_t n = 0; - while ((n + 1) < size && file->read(&ch, 1) == 1) { - // Delete CR. - if (ch == '\r') { - continue; - } - str[n++] = ch; - if (strchr(delim, ch)) { - break; - } - } - str[n] = '\0'; - return n; -} -//------------------------------------------------------------------------------ -#define errorHalt(msg) {Serial.println(F(msg)); SysCall::halt();} -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - Serial.println("Type any character to start"); - while (!Serial.available()) { - SysCall::yield(); - } - // Initialize the SD. - if (!SD.begin(CS_PIN)) { - errorHalt("begin failed"); - } - // Create or open the file. - file = SD.open("READNUM.TXT", FILE_WRITE); - if (!file) { - errorHalt("open failed"); - } - // Rewind file so test data is not appended. - file.rewind(); - - // Write test data. - file.print(F( - "11,12,13,14\r\n" - "21,22,23,24\r\n" - "31,32,33,34\r\n" - "41,42,43,44\r\n" - "51,52,53,54" // Allow missing endl at eof. - )); - - // Rewind the file for read. - file.rewind(); - - // Array for data. - int array[ROW_DIM][COL_DIM]; - int i = 0; // First array index. - int j = 0; // Second array index - size_t n; // Length of returned field with delimiter. - char str[20]; // Must hold longest field with delimiter and zero byte. - char *ptr; // Test for valid field. - - // Read the file and store the data. - - for (i = 0; i < ROW_DIM; i++) { - for (j = 0; j < COL_DIM; j++) { - n = readField(&file, str, sizeof(str), ",\n"); - if (n == 0) { - errorHalt("Too few lines"); - } - array[i][j] = strtol(str, &ptr, 10); - if (ptr == str) { - errorHalt("bad number"); - } - while (*ptr == ' ') { - ptr++; - } - if (*ptr != ',' && *ptr != '\n' && *ptr != '\0') { - errorHalt("extra characters in field"); - } - if (j < (COL_DIM-1) && str[n-1] != ',') { - errorHalt("line with too few fields"); - } - } - // Allow missing endl at eof. - if (str[n-1] != '\n' && file.available()) { - errorHalt("missing endl"); - } - } - - // Print the array. - for (i = 0; i < ROW_DIM; i++) { - for (j = 0; j < COL_DIM; j++) { - if (j) { - Serial.print(' '); - } - Serial.print(array[i][j]); - } - Serial.println(); - } - Serial.println("Done"); - file.close(); -} -//------------------------------------------------------------------------------ -void loop() { -} - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsvStream/ReadCsvStream.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsvStream/ReadCsvStream.ino deleted file mode 100644 index 022ab3e..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadCsvStream/ReadCsvStream.ino +++ /dev/null @@ -1,121 +0,0 @@ -/* - * This example reads a simple CSV, comma-separated values, file. - * Each line of the file has a label and three values, a long and two floats. - */ -#include -#include "SdFat.h" -#include "sdios.h" - -// SD chip select pin -const uint8_t chipSelect = SS; - -// file system object -SdFat sd; - -// create Serial stream -ArduinoOutStream cout(Serial); - -char fileName[] = "testfile.csv"; -//------------------------------------------------------------------------------ -// store error strings in flash to save RAM -#define error(s) sd.errorHalt(F(s)) -//------------------------------------------------------------------------------ -// read and print CSV test file -void readFile() { - long lg = 0; - float f1, f2; - char text[10]; - char c1, c2, c3; // space for commas. - - // open input file - ifstream sdin(fileName); - - // check for open error - if (!sdin.is_open()) { - error("open"); - } - - // read until input fails - while (1) { - // Get text field. - sdin.get(text, sizeof(text), ','); - - // Assume EOF if fail. - if (sdin.fail()) { - break; - } - - // Get commas and numbers. - sdin >> c1 >> lg >> c2 >> f1 >> c3 >> f2; - - // Skip CR/LF. - sdin.skipWhite(); - - if (sdin.fail()) { - error("bad input"); - } - - // error in line if not commas - if (c1 != ',' || c2 != ',' || c3 != ',') { - error("comma"); - } - - // print in six character wide columns - cout << text << setw(6) << lg << setw(6) << f1 << setw(6) << f2 << endl; - } - // Error in an input line if file is not at EOF. - if (!sdin.eof()) { - error("readFile"); - } -} -//------------------------------------------------------------------------------ -// write test file -void writeFile() { - - // create or open and truncate output file - ofstream sdout(fileName); - - // write file from string stored in flash - sdout << F( - "Line 1,1,2.3,4.5\n" - "Line 2,6,7.8,9.0\n" - "Line 3,9,8.7,6.5\n" - "Line 4,-4,-3.2,-1\n") << flush; - - // check for any errors - if (!sdout) { - error("writeFile"); - } - - sdout.close(); -} -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - cout << F("Type any character to start\n"); - while (!Serial.available()) { - SysCall::yield(); - } - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } - - // create test file - writeFile(); - - cout << endl; - - // read and print test - readFile(); - - cout << "\nDone!" << endl; -} -void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadWrite/ReadWrite.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadWrite/ReadWrite.ino deleted file mode 100644 index 15b6c98..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/ReadWrite/ReadWrite.ino +++ /dev/null @@ -1,81 +0,0 @@ -/* - SD card read/write - - This example shows how to read and write data to and from an SD card file - The circuit: - * SD card attached to SPI bus as follows: - ** MOSI - pin 11 - ** MISO - pin 12 - ** CLK - pin 13 - - created Nov 2010 - by David A. Mellis - modified 9 Apr 2012 - by Tom Igoe - - This example code is in the public domain. - - */ - -#include -//#include -#include "SdFat.h" -SdFat SD; - -#define SD_CS_PIN SS -File myFile; - -void setup() { - // Open serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - - Serial.print("Initializing SD card..."); - - if (!SD.begin(SD_CS_PIN)) { - Serial.println("initialization failed!"); - return; - } - Serial.println("initialization done."); - - // open the file. note that only one file can be open at a time, - // so you have to close this one before opening another. - myFile = SD.open("test.txt", FILE_WRITE); - - // if the file opened okay, write to it: - if (myFile) { - Serial.print("Writing to test.txt..."); - myFile.println("testing 1, 2, 3."); - // close the file: - myFile.close(); - Serial.println("done."); - } else { - // if the file didn't open, print an error: - Serial.println("error opening test.txt"); - } - - // re-open the file for reading: - myFile = SD.open("test.txt"); - if (myFile) { - Serial.println("test.txt:"); - - // read from the file until there's nothing else in it: - while (myFile.available()) { - Serial.write(myFile.read()); - } - // close the file: - myFile.close(); - } else { - // if the file didn't open, print an error: - Serial.println("error opening test.txt"); - } -} - -void loop() { - // nothing happens after setup -} - - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/STM32Test/STM32Test.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/STM32Test/STM32Test.ino deleted file mode 100644 index d01c9a5..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/STM32Test/STM32Test.ino +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Example use of two SPI ports on an STM32 board. - * Note SPI speed is limited to 18 MHz. - */ -#include -#include "SdFat.h" -#include "FreeStack.h" - -// set ENABLE_EXTENDED_TRANSFER_CLASS non-zero to use faster EX classes - -// Use first SPI port -SdFat sd1; -// SdFatEX sd1; -const uint8_t SD1_CS = PA4; // chip select for sd1 - -// Use second SPI port -SPIClass SPI_2(2); -SdFat sd2(&SPI_2); -// SdFatEX sd2(&SPI_2); - -const uint8_t SD2_CS = PB12; // chip select for sd2 - -const uint8_t BUF_DIM = 100; -uint8_t buf[BUF_DIM]; - -const uint32_t FILE_SIZE = 1000000; -const uint16_t NWRITE = FILE_SIZE/BUF_DIM; -//------------------------------------------------------------------------------ -// print error msg, any SD error codes, and halt. -// store messages in flash -#define errorExit(msg) errorHalt(F(msg)) -#define initError(msg) initErrorHalt(F(msg)) -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - // Wait for USB Serial - while (!Serial) { - } - - // fill buffer with known data - for (size_t i = 0; i < sizeof(buf); i++) { - buf[i] = i; - } - - Serial.println(F("type any character to start")); - while (!Serial.available()) { - } - Serial.print(F("FreeStack: ")); - Serial.println(FreeStack()); - - // initialize the first card - if (!sd1.begin(SD1_CS, SD_SCK_MHZ(18))) { - sd1.initError("sd1:"); - } - // create Dir1 on sd1 if it does not exist - if (!sd1.exists("/Dir1")) { - if (!sd1.mkdir("/Dir1")) { - sd1.errorExit("sd1.mkdir"); - } - } - // initialize the second card - if (!sd2.begin(SD2_CS, SD_SCK_MHZ(18))) { - sd2.initError("sd2:"); - } -// create Dir2 on sd2 if it does not exist - if (!sd2.exists("/Dir2")) { - if (!sd2.mkdir("/Dir2")) { - sd2.errorExit("sd2.mkdir"); - } - } - // list root directory on both cards - Serial.println(F("------sd1 root-------")); - sd1.ls(); - Serial.println(F("------sd2 root-------")); - sd2.ls(); - - // make /Dir1 the default directory for sd1 - if (!sd1.chdir("/Dir1")) { - sd1.errorExit("sd1.chdir"); - } - // remove test.bin from /Dir1 directory of sd1 - if (sd1.exists("test.bin")) { - if (!sd1.remove("test.bin")) { - sd2.errorExit("remove test.bin"); - } - } - // make /Dir2 the default directory for sd2 - if (!sd2.chdir("/Dir2")) { - sd2.errorExit("sd2.chdir"); - } - // remove rename.bin from /Dir2 directory of sd2 - if (sd2.exists("rename.bin")) { - if (!sd2.remove("rename.bin")) { - sd2.errorExit("remove rename.bin"); - } - } - // list current directory on both cards - Serial.println(F("------sd1 Dir1-------")); - sd1.ls(); - Serial.println(F("------sd2 Dir2-------")); - sd2.ls(); - Serial.println(F("---------------------")); - - // set the current working directory for open() to sd1 - sd1.chvol(); - - // create or open /Dir1/test.bin and truncate it to zero length - SdFile file1; - if (!file1.open("test.bin", O_RDWR | O_CREAT | O_TRUNC)) { - sd1.errorExit("file1"); - } - Serial.println(F("Writing test.bin to sd1")); - - // write data to /Dir1/test.bin on sd1 - for (uint16_t i = 0; i < NWRITE; i++) { - if (file1.write(buf, sizeof(buf)) != sizeof(buf)) { - sd1.errorExit("sd1.write"); - } - } - // set the current working directory for open() to sd2 - sd2.chvol(); - - // create or open /Dir2/copy.bin and truncate it to zero length - SdFile file2; - if (!file2.open("copy.bin", O_WRONLY | O_CREAT | O_TRUNC)) { - sd2.errorExit("file2"); - } - Serial.println(F("Copying test.bin to copy.bin")); - - // copy file1 to file2 - file1.rewind(); - uint32_t t = millis(); - - while (1) { - int n = file1.read(buf, sizeof(buf)); - if (n < 0) { - sd1.errorExit("read1"); - } - if (n == 0) { - break; - } - if ((int)file2.write(buf, n) != n) { - sd2.errorExit("write2"); - } - } - t = millis() - t; - Serial.print(F("File size: ")); - Serial.println(file2.fileSize()); - Serial.print(F("Copy time: ")); - Serial.print(t); - Serial.println(F(" millis")); - // close test.bin - file1.close(); - file2.close(); - // list current directory on both cards - Serial.println(F("------sd1 -------")); - sd1.ls("/", LS_R | LS_DATE | LS_SIZE); - Serial.println(F("------sd2 -------")); - sd2.ls("/", LS_R | LS_DATE | LS_SIZE); - Serial.println(F("---------------------")); - Serial.println(F("Renaming copy.bin")); - // rename the copy - if (!sd2.rename("copy.bin", "rename.bin")) { - sd2.errorExit("sd2.rename"); - } - // list current directory on both cards - Serial.println(F("------sd1 -------")); - sd1.ls("/", LS_R | LS_DATE | LS_SIZE); - Serial.println(F("------sd2 -------")); - sd2.ls("/", LS_R | LS_DATE | LS_SIZE); - Serial.println(F("---------------------")); - Serial.println(F("Done")); -} -//------------------------------------------------------------------------------ -void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SdFormatter/SdFormatter.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SdFormatter/SdFormatter.ino deleted file mode 100644 index 39e7850..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SdFormatter/SdFormatter.ino +++ /dev/null @@ -1,552 +0,0 @@ -/* - * This program will format an SD or SDHC card. - * Warning all data will be deleted! - * - * For SD/SDHC cards larger than 64 MB this - * program attempts to match the format - * generated by SDFormatter available here: - * - * http://www.sdcard.org/consumers/formatter/ - * - * For smaller cards this program uses FAT16 - * and SDFormatter uses FAT12. - */ - -// Set USE_SDIO to zero for SPI card access. -#define USE_SDIO 0 -// -// Change the value of chipSelect if your hardware does -// not use the default value, SS. Common values are: -// Arduino Ethernet shield: pin 4 -// Sparkfun SD shield: pin 8 -// Adafruit SD shields and modules: pin 10 -const uint8_t chipSelect = SS; - -// Initialize at highest supported speed not over 50 MHz. -// Reduce max speed if errors occur. -#define SPI_SPEED SD_SCK_MHZ(50) - -// Print extra info for debug if DEBUG_PRINT is nonzero -#define DEBUG_PRINT 0 -#include -#include "SdFat.h" -#include "sdios.h" -#if DEBUG_PRINT -#include "FreeStack.h" -#endif // DEBUG_PRINT - -// Serial output stream -ArduinoOutStream cout(Serial); - -#if USE_SDIO -// Use faster SdioCardEX -SdioCardEX card; -// SdioCard card; -#else // USE_SDIO -Sd2Card card; -#endif // USE_SDIO - -uint32_t cardSizeBlocks; -uint32_t cardCapacityMB; - -// cache for SD block -cache_t cache; - -// MBR information -uint8_t partType; -uint32_t relSector; -uint32_t partSize; - -// Fake disk geometry -uint8_t numberOfHeads; -uint8_t sectorsPerTrack; - -// FAT parameters -uint16_t reservedSectors; -uint8_t sectorsPerCluster; -uint32_t fatStart; -uint32_t fatSize; -uint32_t dataStart; - -// constants for file system structure -uint16_t const BU16 = 128; -uint16_t const BU32 = 8192; - -// strings needed in file system structures -char noName[] = "NO NAME "; -char fat16str[] = "FAT16 "; -char fat32str[] = "FAT32 "; -//------------------------------------------------------------------------------ -#define sdError(msg) {cout << F("error: ") << F(msg) << endl; sdErrorHalt();} -//------------------------------------------------------------------------------ -void sdErrorHalt() { - if (card.errorCode()) { - cout << F("SD error: ") << hex << int(card.errorCode()); - cout << ',' << int(card.errorData()) << dec << endl; - } - SysCall::halt(); -} -//------------------------------------------------------------------------------ -#if DEBUG_PRINT -void debugPrint() { - cout << F("FreeStack: ") << FreeStack() << endl; - cout << F("partStart: ") << relSector << endl; - cout << F("partSize: ") << partSize << endl; - cout << F("reserved: ") << reservedSectors << endl; - cout << F("fatStart: ") << fatStart << endl; - cout << F("fatSize: ") << fatSize << endl; - cout << F("dataStart: ") << dataStart << endl; - cout << F("clusterCount: "); - cout << ((relSector + partSize - dataStart)/sectorsPerCluster) << endl; - cout << endl; - cout << F("Heads: ") << int(numberOfHeads) << endl; - cout << F("Sectors: ") << int(sectorsPerTrack) << endl; - cout << F("Cylinders: "); - cout << cardSizeBlocks/(numberOfHeads*sectorsPerTrack) << endl; -} -#endif // DEBUG_PRINT -//------------------------------------------------------------------------------ -// write cached block to the card -uint8_t writeCache(uint32_t lbn) { - return card.writeBlock(lbn, cache.data); -} -//------------------------------------------------------------------------------ -// initialize appropriate sizes for SD capacity -void initSizes() { - if (cardCapacityMB <= 6) { - sdError("Card is too small."); - } else if (cardCapacityMB <= 16) { - sectorsPerCluster = 2; - } else if (cardCapacityMB <= 32) { - sectorsPerCluster = 4; - } else if (cardCapacityMB <= 64) { - sectorsPerCluster = 8; - } else if (cardCapacityMB <= 128) { - sectorsPerCluster = 16; - } else if (cardCapacityMB <= 1024) { - sectorsPerCluster = 32; - } else if (cardCapacityMB <= 32768) { - sectorsPerCluster = 64; - } else { - // SDXC cards - sectorsPerCluster = 128; - } - - cout << F("Blocks/Cluster: ") << int(sectorsPerCluster) << endl; - // set fake disk geometry - sectorsPerTrack = cardCapacityMB <= 256 ? 32 : 63; - - if (cardCapacityMB <= 16) { - numberOfHeads = 2; - } else if (cardCapacityMB <= 32) { - numberOfHeads = 4; - } else if (cardCapacityMB <= 128) { - numberOfHeads = 8; - } else if (cardCapacityMB <= 504) { - numberOfHeads = 16; - } else if (cardCapacityMB <= 1008) { - numberOfHeads = 32; - } else if (cardCapacityMB <= 2016) { - numberOfHeads = 64; - } else if (cardCapacityMB <= 4032) { - numberOfHeads = 128; - } else { - numberOfHeads = 255; - } -} -//------------------------------------------------------------------------------ -// zero cache and optionally set the sector signature -void clearCache(uint8_t addSig) { - memset(&cache, 0, sizeof(cache)); - if (addSig) { - cache.mbr.mbrSig0 = BOOTSIG0; - cache.mbr.mbrSig1 = BOOTSIG1; - } -} -//------------------------------------------------------------------------------ -// zero FAT and root dir area on SD -void clearFatDir(uint32_t bgn, uint32_t count) { - clearCache(false); -#if USE_SDIO - for (uint32_t i = 0; i < count; i++) { - if (!card.writeBlock(bgn + i, cache.data)) { - sdError("Clear FAT/DIR writeBlock failed"); - } - if ((i & 0XFF) == 0) { - cout << '.'; - } - } -#else // USE_SDIO - if (!card.writeStart(bgn, count)) { - sdError("Clear FAT/DIR writeStart failed"); - } - for (uint32_t i = 0; i < count; i++) { - if ((i & 0XFF) == 0) { - cout << '.'; - } - if (!card.writeData(cache.data)) { - sdError("Clear FAT/DIR writeData failed"); - } - } - if (!card.writeStop()) { - sdError("Clear FAT/DIR writeStop failed"); - } -#endif // USE_SDIO - cout << endl; -} -//------------------------------------------------------------------------------ -// return cylinder number for a logical block number -uint16_t lbnToCylinder(uint32_t lbn) { - return lbn / (numberOfHeads * sectorsPerTrack); -} -//------------------------------------------------------------------------------ -// return head number for a logical block number -uint8_t lbnToHead(uint32_t lbn) { - return (lbn % (numberOfHeads * sectorsPerTrack)) / sectorsPerTrack; -} -//------------------------------------------------------------------------------ -// return sector number for a logical block number -uint8_t lbnToSector(uint32_t lbn) { - return (lbn % sectorsPerTrack) + 1; -} -//------------------------------------------------------------------------------ -// format and write the Master Boot Record -void writeMbr() { - clearCache(true); - part_t* p = cache.mbr.part; - p->boot = 0; - uint16_t c = lbnToCylinder(relSector); - if (c > 1023) { - sdError("MBR CHS"); - } - p->beginCylinderHigh = c >> 8; - p->beginCylinderLow = c & 0XFF; - p->beginHead = lbnToHead(relSector); - p->beginSector = lbnToSector(relSector); - p->type = partType; - uint32_t endLbn = relSector + partSize - 1; - c = lbnToCylinder(endLbn); - if (c <= 1023) { - p->endCylinderHigh = c >> 8; - p->endCylinderLow = c & 0XFF; - p->endHead = lbnToHead(endLbn); - p->endSector = lbnToSector(endLbn); - } else { - // Too big flag, c = 1023, h = 254, s = 63 - p->endCylinderHigh = 3; - p->endCylinderLow = 255; - p->endHead = 254; - p->endSector = 63; - } - p->firstSector = relSector; - p->totalSectors = partSize; - if (!writeCache(0)) { - sdError("write MBR"); - } -} -//------------------------------------------------------------------------------ -// generate serial number from card size and micros since boot -uint32_t volSerialNumber() { - return (cardSizeBlocks << 8) + micros(); -} -//------------------------------------------------------------------------------ -// format the SD as FAT16 -void makeFat16() { - uint32_t nc; - for (dataStart = 2 * BU16;; dataStart += BU16) { - nc = (cardSizeBlocks - dataStart)/sectorsPerCluster; - fatSize = (nc + 2 + 255)/256; - uint32_t r = BU16 + 1 + 2 * fatSize + 32; - if (dataStart < r) { - continue; - } - relSector = dataStart - r + BU16; - break; - } - // check valid cluster count for FAT16 volume - if (nc < 4085 || nc >= 65525) { - sdError("Bad cluster count"); - } - reservedSectors = 1; - fatStart = relSector + reservedSectors; - partSize = nc * sectorsPerCluster + 2 * fatSize + reservedSectors + 32; - if (partSize < 32680) { - partType = 0X01; - } else if (partSize < 65536) { - partType = 0X04; - } else { - partType = 0X06; - } - // write MBR - writeMbr(); - clearCache(true); - fat_boot_t* pb = &cache.fbs; - pb->jump[0] = 0XEB; - pb->jump[1] = 0X00; - pb->jump[2] = 0X90; - for (uint8_t i = 0; i < sizeof(pb->oemId); i++) { - pb->oemId[i] = ' '; - } - pb->bytesPerSector = 512; - pb->sectorsPerCluster = sectorsPerCluster; - pb->reservedSectorCount = reservedSectors; - pb->fatCount = 2; - pb->rootDirEntryCount = 512; - pb->mediaType = 0XF8; - pb->sectorsPerFat16 = fatSize; - pb->sectorsPerTrack = sectorsPerTrack; - pb->headCount = numberOfHeads; - pb->hidddenSectors = relSector; - pb->totalSectors32 = partSize; - pb->driveNumber = 0X80; - pb->bootSignature = EXTENDED_BOOT_SIG; - pb->volumeSerialNumber = volSerialNumber(); - memcpy(pb->volumeLabel, noName, sizeof(pb->volumeLabel)); - memcpy(pb->fileSystemType, fat16str, sizeof(pb->fileSystemType)); - // write partition boot sector - if (!writeCache(relSector)) { - sdError("FAT16 write PBS failed"); - } - // clear FAT and root directory - clearFatDir(fatStart, dataStart - fatStart); - clearCache(false); - cache.fat16[0] = 0XFFF8; - cache.fat16[1] = 0XFFFF; - // write first block of FAT and backup for reserved clusters - if (!writeCache(fatStart) - || !writeCache(fatStart + fatSize)) { - sdError("FAT16 reserve failed"); - } -} -//------------------------------------------------------------------------------ -// format the SD as FAT32 -void makeFat32() { - uint32_t nc; - relSector = BU32; - for (dataStart = 2 * BU32;; dataStart += BU32) { - nc = (cardSizeBlocks - dataStart)/sectorsPerCluster; - fatSize = (nc + 2 + 127)/128; - uint32_t r = relSector + 9 + 2 * fatSize; - if (dataStart >= r) { - break; - } - } - // error if too few clusters in FAT32 volume - if (nc < 65525) { - sdError("Bad cluster count"); - } - reservedSectors = dataStart - relSector - 2 * fatSize; - fatStart = relSector + reservedSectors; - partSize = nc * sectorsPerCluster + dataStart - relSector; - // type depends on address of end sector - // max CHS has lbn = 16450560 = 1024*255*63 - if ((relSector + partSize) <= 16450560) { - // FAT32 - partType = 0X0B; - } else { - // FAT32 with INT 13 - partType = 0X0C; - } - writeMbr(); - clearCache(true); - - fat32_boot_t* pb = &cache.fbs32; - pb->jump[0] = 0XEB; - pb->jump[1] = 0X00; - pb->jump[2] = 0X90; - for (uint8_t i = 0; i < sizeof(pb->oemId); i++) { - pb->oemId[i] = ' '; - } - pb->bytesPerSector = 512; - pb->sectorsPerCluster = sectorsPerCluster; - pb->reservedSectorCount = reservedSectors; - pb->fatCount = 2; - pb->mediaType = 0XF8; - pb->sectorsPerTrack = sectorsPerTrack; - pb->headCount = numberOfHeads; - pb->hidddenSectors = relSector; - pb->totalSectors32 = partSize; - pb->sectorsPerFat32 = fatSize; - pb->fat32RootCluster = 2; - pb->fat32FSInfo = 1; - pb->fat32BackBootBlock = 6; - pb->driveNumber = 0X80; - pb->bootSignature = EXTENDED_BOOT_SIG; - pb->volumeSerialNumber = volSerialNumber(); - memcpy(pb->volumeLabel, noName, sizeof(pb->volumeLabel)); - memcpy(pb->fileSystemType, fat32str, sizeof(pb->fileSystemType)); - // write partition boot sector and backup - if (!writeCache(relSector) - || !writeCache(relSector + 6)) { - sdError("FAT32 write PBS failed"); - } - clearCache(true); - // write extra boot area and backup - if (!writeCache(relSector + 2) - || !writeCache(relSector + 8)) { - sdError("FAT32 PBS ext failed"); - } - fat32_fsinfo_t* pf = &cache.fsinfo; - pf->leadSignature = FSINFO_LEAD_SIG; - pf->structSignature = FSINFO_STRUCT_SIG; - pf->freeCount = 0XFFFFFFFF; - pf->nextFree = 0XFFFFFFFF; - // write FSINFO sector and backup - if (!writeCache(relSector + 1) - || !writeCache(relSector + 7)) { - sdError("FAT32 FSINFO failed"); - } - clearFatDir(fatStart, 2 * fatSize + sectorsPerCluster); - clearCache(false); - cache.fat32[0] = 0x0FFFFFF8; - cache.fat32[1] = 0x0FFFFFFF; - cache.fat32[2] = 0x0FFFFFFF; - // write first block of FAT and backup for reserved clusters - if (!writeCache(fatStart) - || !writeCache(fatStart + fatSize)) { - sdError("FAT32 reserve failed"); - } -} -//------------------------------------------------------------------------------ -// flash erase all data -uint32_t const ERASE_SIZE = 262144L; -void eraseCard() { - cout << endl << F("Erasing\n"); - uint32_t firstBlock = 0; - uint32_t lastBlock; - uint16_t n = 0; - - do { - lastBlock = firstBlock + ERASE_SIZE - 1; - if (lastBlock >= cardSizeBlocks) { - lastBlock = cardSizeBlocks - 1; - } - if (!card.erase(firstBlock, lastBlock)) { - sdError("erase failed"); - } - cout << '.'; - if ((n++)%32 == 31) { - cout << endl; - } - firstBlock += ERASE_SIZE; - } while (firstBlock < cardSizeBlocks); - cout << endl; - - if (!card.readBlock(0, cache.data)) { - sdError("readBlock"); - } - cout << hex << showbase << setfill('0') << internal; - cout << F("All data set to ") << setw(4) << int(cache.data[0]) << endl; - cout << dec << noshowbase << setfill(' ') << right; - cout << F("Erase done\n"); -} -//------------------------------------------------------------------------------ -void formatCard() { - cout << endl; - cout << F("Formatting\n"); - initSizes(); - if (card.type() != SD_CARD_TYPE_SDHC) { - cout << F("FAT16\n"); - makeFat16(); - } else { - cout << F("FAT32\n"); - makeFat32(); - } -#if DEBUG_PRINT - debugPrint(); -#endif // DEBUG_PRINT - cout << F("Format done\n"); -} -//------------------------------------------------------------------------------ -void setup() { - char c; - Serial.begin(9600); - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - cout << F("Type any character to start\n"); - while (!Serial.available()) { - SysCall::yield(); - } - // Discard any extra characters. - do { - delay(10); - } while (Serial.available() && Serial.read() >= 0); - cout << F( - "\n" - "This program can erase and/or format SD/SDHC cards.\n" - "\n" - "Erase uses the card's fast flash erase command.\n" - "Flash erase sets all data to 0X00 for most cards\n" - "and 0XFF for a few vendor's cards.\n" - "\n" - "Cards larger than 2 GB will be formatted FAT32 and\n" - "smaller cards will be formatted FAT16.\n" - "\n" - "Warning, all data on the card will be erased.\n" - "Enter 'Y' to continue: "); - while (!Serial.available()) { - SysCall::yield(); - } - - c = Serial.read(); - cout << c << endl; - if (c != 'Y') { - cout << F("Quiting, you did not enter 'Y'.\n"); - return; - } - // Read any existing Serial data. - do { - delay(10); - } while (Serial.available() && Serial.read() >= 0); - - cout << F( - "\n" - "Options are:\n" - "E - erase the card and skip formatting.\n" - "F - erase and then format the card. (recommended)\n" - "Q - quick format the card without erase.\n" - "\n" - "Enter option: "); - - while (!Serial.available()) { - SysCall::yield(); - } - c = Serial.read(); - cout << c << endl; - if (!strchr("EFQ", c)) { - cout << F("Quiting, invalid option entered.") << endl; - return; - } -#if USE_SDIO - if (!card.begin()) { - sdError("card.begin failed"); - } -#else // USE_SDIO - if (!card.begin(chipSelect, SPI_SPEED)) { - cout << F( - "\nSD initialization failure!\n" - "Is the SD card inserted correctly?\n" - "Is chip select correct at the top of this program?\n"); - sdError("card.begin failed"); - } -#endif - cardSizeBlocks = card.cardSize(); - if (cardSizeBlocks == 0) { - sdError("cardSize"); - } - cardCapacityMB = (cardSizeBlocks + 2047)/2048; - - cout << F("Card Size: ") << setprecision(0) << 1.048576*cardCapacityMB; - cout << F(" MB, (MB = 1,000,000 bytes)") << endl; - - if (c == 'E' || c == 'F') { - eraseCard(); - } - if (c == 'F' || c == 'Q') { - formatCard(); - } -} -//------------------------------------------------------------------------------ -void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SdInfo/SdInfo.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SdInfo/SdInfo.ino deleted file mode 100644 index 07f8601..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SdInfo/SdInfo.ino +++ /dev/null @@ -1,248 +0,0 @@ -/* - * This program attempts to initialize an SD card and analyze its structure. - */ -#include -#include "SdFat.h" -#include "sdios.h" - -// Set USE_SDIO to zero for SPI card access. -#define USE_SDIO 0 -/* - * SD chip select pin. Common values are: - * - * Arduino Ethernet shield, pin 4. - * SparkFun SD shield, pin 8. - * Adafruit SD shields and modules, pin 10. - * Default SD chip select is the SPI SS pin. - */ -const uint8_t SD_CHIP_SELECT = SS; -/* - * Set DISABLE_CHIP_SELECT to disable a second SPI device. - * For example, with the Ethernet shield, set DISABLE_CHIP_SELECT - * to 10 to disable the Ethernet controller. - */ -const int8_t DISABLE_CHIP_SELECT = -1; - -#if USE_SDIO -// Use faster SdioCardEX -SdFatSdioEX sd; -// SdFatSdio sd; -#else // USE_SDIO -SdFat sd; -#endif // USE_SDIO - -// serial output steam -ArduinoOutStream cout(Serial); - -// global for card size -uint32_t cardSize; - -// global for card erase size -uint32_t eraseSize; -//------------------------------------------------------------------------------ -// store error strings in flash -#define sdErrorMsg(msg) sd.errorPrint(F(msg)); -//------------------------------------------------------------------------------ -uint8_t cidDmp() { - cid_t cid; - if (!sd.card()->readCID(&cid)) { - sdErrorMsg("readCID failed"); - return false; - } - cout << F("\nManufacturer ID: "); - cout << hex << int(cid.mid) << dec << endl; - cout << F("OEM ID: ") << cid.oid[0] << cid.oid[1] << endl; - cout << F("Product: "); - for (uint8_t i = 0; i < 5; i++) { - cout << cid.pnm[i]; - } - cout << F("\nVersion: "); - cout << int(cid.prv_n) << '.' << int(cid.prv_m) << endl; - cout << F("Serial number: ") << hex << cid.psn << dec << endl; - cout << F("Manufacturing date: "); - cout << int(cid.mdt_month) << '/'; - cout << (2000 + cid.mdt_year_low + 10 * cid.mdt_year_high) << endl; - cout << endl; - return true; -} -//------------------------------------------------------------------------------ -uint8_t csdDmp() { - csd_t csd; - uint8_t eraseSingleBlock; - if (!sd.card()->readCSD(&csd)) { - sdErrorMsg("readCSD failed"); - return false; - } - if (csd.v1.csd_ver == 0) { - eraseSingleBlock = csd.v1.erase_blk_en; - eraseSize = (csd.v1.sector_size_high << 1) | csd.v1.sector_size_low; - } else if (csd.v2.csd_ver == 1) { - eraseSingleBlock = csd.v2.erase_blk_en; - eraseSize = (csd.v2.sector_size_high << 1) | csd.v2.sector_size_low; - } else { - cout << F("csd version error\n"); - return false; - } - eraseSize++; - cout << F("cardSize: ") << 0.000512*cardSize; - cout << F(" MB (MB = 1,000,000 bytes)\n"); - - cout << F("flashEraseSize: ") << int(eraseSize) << F(" blocks\n"); - cout << F("eraseSingleBlock: "); - if (eraseSingleBlock) { - cout << F("true\n"); - } else { - cout << F("false\n"); - } - return true; -} -//------------------------------------------------------------------------------ -// print partition table -uint8_t partDmp() { - mbr_t mbr; - if (!sd.card()->readBlock(0, (uint8_t*)&mbr)) { - sdErrorMsg("read MBR failed"); - return false; - } - for (uint8_t ip = 1; ip < 5; ip++) { - part_t *pt = &mbr.part[ip - 1]; - if ((pt->boot & 0X7F) != 0 || pt->firstSector > cardSize) { - cout << F("\nNo MBR. Assuming Super Floppy format.\n"); - return true; - } - } - cout << F("\nSD Partition Table\n"); - cout << F("part,boot,type,start,length\n"); - for (uint8_t ip = 1; ip < 5; ip++) { - part_t *pt = &mbr.part[ip - 1]; - cout << int(ip) << ',' << hex << int(pt->boot) << ',' << int(pt->type); - cout << dec << ',' << pt->firstSector <<',' << pt->totalSectors << endl; - } - return true; -} -//------------------------------------------------------------------------------ -void volDmp() { - cout << F("\nVolume is FAT") << int(sd.vol()->fatType()) << endl; - cout << F("blocksPerCluster: ") << int(sd.vol()->blocksPerCluster()) << endl; - cout << F("clusterCount: ") << sd.vol()->clusterCount() << endl; - cout << F("freeClusters: "); - uint32_t volFree = sd.vol()->freeClusterCount(); - cout << volFree << endl; - float fs = 0.000512*volFree*sd.vol()->blocksPerCluster(); - cout << F("freeSpace: ") << fs << F(" MB (MB = 1,000,000 bytes)\n"); - cout << F("fatStartBlock: ") << sd.vol()->fatStartBlock() << endl; - cout << F("fatCount: ") << int(sd.vol()->fatCount()) << endl; - cout << F("blocksPerFat: ") << sd.vol()->blocksPerFat() << endl; - cout << F("rootDirStart: ") << sd.vol()->rootDirStart() << endl; - cout << F("dataStartBlock: ") << sd.vol()->dataStartBlock() << endl; - if (sd.vol()->dataStartBlock() % eraseSize) { - cout << F("Data area is not aligned on flash erase boundaries!\n"); - cout << F("Download and use formatter from www.sdcard.org!\n"); - } -} -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - - // use uppercase in hex and use 0X base prefix - cout << uppercase << showbase << endl; - - // F stores strings in flash to save RAM - cout << F("SdFat version: ") << SD_FAT_VERSION << endl; -#if !USE_SDIO - if (DISABLE_CHIP_SELECT < 0) { - cout << F( - "\nAssuming the SD is the only SPI device.\n" - "Edit DISABLE_CHIP_SELECT to disable another device.\n"); - } else { - cout << F("\nDisabling SPI device on pin "); - cout << int(DISABLE_CHIP_SELECT) << endl; - pinMode(DISABLE_CHIP_SELECT, OUTPUT); - digitalWrite(DISABLE_CHIP_SELECT, HIGH); - } - cout << F("\nAssuming the SD chip select pin is: ") <= 0); - - // F stores strings in flash to save RAM - cout << F("\ntype any character to start\n"); - while (!Serial.available()) { - SysCall::yield(); - } - - uint32_t t = millis(); -#if USE_SDIO - if (!sd.cardBegin()) { - sdErrorMsg("\ncardBegin failed"); - return; - } -#else // USE_SDIO - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.cardBegin(SD_CHIP_SELECT, SD_SCK_MHZ(50))) { - sdErrorMsg("cardBegin failed"); - return; - } - #endif // USE_SDIO - t = millis() - t; - - cardSize = sd.card()->cardSize(); - if (cardSize == 0) { - sdErrorMsg("cardSize failed"); - return; - } - cout << F("\ninit time: ") << t << " ms" << endl; - cout << F("\nCard type: "); - switch (sd.card()->type()) { - case SD_CARD_TYPE_SD1: - cout << F("SD1\n"); - break; - - case SD_CARD_TYPE_SD2: - cout << F("SD2\n"); - break; - - case SD_CARD_TYPE_SDHC: - if (cardSize < 70000000) { - cout << F("SDHC\n"); - } else { - cout << F("SDXC\n"); - } - break; - - default: - cout << F("Unknown\n"); - } - if (!cidDmp()) { - return; - } - if (!csdDmp()) { - return; - } - uint32_t ocr; - if (!sd.card()->readOCR(&ocr)) { - sdErrorMsg("\nreadOCR failed"); - return; - } - cout << F("OCR: ") << hex << ocr << dec << endl; - if (!partDmp()) { - return; - } - if (!sd.fsBegin()) { - sdErrorMsg("\nFile System initialization failed.\n"); - return; - } - volDmp(); -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SoftwareSpi/SoftwareSpi.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SoftwareSpi/SoftwareSpi.ino deleted file mode 100644 index cad7763..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/SoftwareSpi/SoftwareSpi.ino +++ /dev/null @@ -1,58 +0,0 @@ -// An example of the SdFatSoftSpi template class. -// This example is for an Adafruit Data Logging Shield on a Mega. -// Software SPI is required on Mega since this shield connects to pins 10-13. -// This example will also run on an Uno and other boards using software SPI. -// -#include -#include "SdFat.h" -#if ENABLE_SOFTWARE_SPI_CLASS // Must be set in SdFat/SdFatConfig.h -// -// Pin numbers in templates must be constants. -const uint8_t SOFT_MISO_PIN = 12; -const uint8_t SOFT_MOSI_PIN = 11; -const uint8_t SOFT_SCK_PIN = 13; -// -// Chip select may be constant or RAM variable. -const uint8_t SD_CHIP_SELECT_PIN = 10; - -// SdFat software SPI template -SdFatSoftSpi sd; - -// Test file. -SdFile file; - -void setup() { - Serial.begin(9600); - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - Serial.println("Type any character to start"); - while (!Serial.available()) { - SysCall::yield(); - } - - if (!sd.begin(SD_CHIP_SELECT_PIN)) { - sd.initErrorHalt(); - } - - if (!file.open("SoftSPI.txt", O_RDWR | O_CREAT)) { - sd.errorHalt(F("open failed")); - } - file.println(F("This line was printed using software SPI.")); - - file.rewind(); - - while (file.available()) { - Serial.write(file.read()); - } - - file.close(); - - Serial.println(F("Done.")); -} -//------------------------------------------------------------------------------ -void loop() {} -#else // ENABLE_SOFTWARE_SPI_CLASS -#error ENABLE_SOFTWARE_SPI_CLASS must be set non-zero in SdFat/SdFatConfig.h -#endif //ENABLE_SOFTWARE_SPI_CLASS \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/StdioBench/StdioBench.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/StdioBench/StdioBench.ino deleted file mode 100644 index 2afe836..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/StdioBench/StdioBench.ino +++ /dev/null @@ -1,214 +0,0 @@ -// Benchmark comparing SdFile and StdioStream. -#include -#include "SdFat.h" - -// Define PRINT_FIELD nonzero to use printField. -#define PRINT_FIELD 0 - -// Number of lines to list on Serial. -#define STDIO_LIST_COUNT 0 -#define VERIFY_CONTENT 0 - -const uint8_t SD_CS_PIN = SS; -SdFat sd; - -SdFile printFile; -StdioStream stdioFile; - -float f[100]; -char buf[20]; -const char* label[] = -{ "uint8_t 0 to 255, 100 times ", "uint16_t 0 to 20000", - "uint32_t 0 to 20000", "uint32_t 1000000000 to 1000010000", - "float nnn.ffff, 10000 times" -}; -//------------------------------------------------------------------------------ -void setup() { - uint32_t printSize; - uint32_t stdioSize = 0; - uint32_t printTime; - uint32_t stdioTime = 0; - - Serial.begin(9600); - while (!Serial) { - SysCall::yield(); - } - - Serial.println(F("Type any character to start")); - while (!Serial.available()) { - SysCall::yield(); - } - Serial.println(F("Starting test")); - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50))) { - sd.errorHalt(); - } - - for (uint8_t i = 0; i < 100; i++) { - f[i] = 123.0 + 0.1234*i; - } - - for (uint8_t dataType = 0; dataType < 5; dataType++) { - for (uint8_t fileType = 0; fileType < 2; fileType++) { - if (!fileType) { - if (!printFile.open("print.txt", O_RDWR | O_CREAT | O_TRUNC)) { - Serial.println(F("open fail")); - return; - } - printTime = millis(); - switch (dataType) { - case 0: - for (uint16_t i =0; i < 100; i++) { - for (uint8_t j = 0; j < 255; j++) { - printFile.println(j); - } - } - break; - case 1: - for (uint16_t i = 0; i < 20000; i++) { - printFile.println(i); - } - break; - - case 2: - for (uint32_t i = 0; i < 20000; i++) { - printFile.println(i); - } - break; - - case 3: - for (uint16_t i = 0; i < 10000; i++) { - printFile.println(i + 1000000000UL); - } - break; - - case 4: - for (int j = 0; j < 100; j++) { - for (uint8_t i = 0; i < 100; i++) { - printFile.println(f[i], 4); - } - } - break; - default: - break; - } - printFile.sync(); - printTime = millis() - printTime; - printFile.rewind(); - printSize = printFile.fileSize(); - - } else { - if (!stdioFile.fopen("stream.txt", "w+")) { - Serial.println(F("fopen fail")); - return; - } - stdioTime = millis(); - - switch (dataType) { - case 0: - for (uint16_t i =0; i < 100; i++) { - for (uint8_t j = 0; j < 255; j++) { -#if PRINT_FIELD - stdioFile.printField(j, '\n'); -#else // PRINT_FIELD - stdioFile.println(j); -#endif // PRINT_FIELD - } - } - break; - case 1: - for (uint16_t i = 0; i < 20000; i++) { -#if PRINT_FIELD - stdioFile.printField(i, '\n'); -#else // PRINT_FIELD - stdioFile.println(i); -#endif // PRINT_FIELD - } - break; - - case 2: - for (uint32_t i = 0; i < 20000; i++) { -#if PRINT_FIELD - stdioFile.printField(i, '\n'); -#else // PRINT_FIELD - stdioFile.println(i); -#endif // PRINT_FIELD - } - break; - - case 3: - for (uint16_t i = 0; i < 10000; i++) { - uint32_t n = i + 1000000000UL; -#if PRINT_FIELD - stdioFile.printField(n, '\n'); -#else // PRINT_FIELD - stdioFile.println(n); -#endif // PRINT_FIELD - } - break; - - case 4: - for (int j = 0; j < 100; j++) { - for (uint8_t i = 0; i < 100; i++) { -#if PRINT_FIELD - stdioFile.printField(f[i], '\n', 4); -#else // PRINT_FIELD - stdioFile.println(f[i], 4); -#endif // PRINT_FIELD - } - } - break; - default: - break; - } - stdioFile.fflush(); - stdioTime = millis() - stdioTime; - stdioSize = stdioFile.ftell(); - if (STDIO_LIST_COUNT) { - size_t len; - stdioFile.rewind(); - for (int i = 0; i < STDIO_LIST_COUNT; i++) { - stdioFile.fgets(buf, sizeof(buf), &len); - Serial.print(len); - Serial.print(','); - Serial.print(buf); - } - } - - } - - } - Serial.println(label[dataType]); - if (VERIFY_CONTENT && printSize == stdioSize) { - printFile.rewind(); - stdioFile.rewind(); - for (uint32_t i = 0; i < stdioSize; i++) { - if (printFile.read() != stdioFile.getc()) { - Serial.print(F("Files differ at pos: ")); - Serial.println(i); - return; - } - } - } - - Serial.print(F("fileSize: ")); - if (printSize != stdioSize) { - Serial.print(printSize); - Serial.print(F(" != ")); - } - Serial.println(stdioSize); - Serial.print(F("print millis: ")); - Serial.println(printTime); - Serial.print(F("stdio millis: ")); - Serial.println(stdioTime); - Serial.print(F("ratio: ")); - Serial.println((float)printTime/(float)stdioTime); - Serial.println(); - printFile.close(); - stdioFile.fclose(); - } - Serial.println(F("Done")); -} -void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/TeensySdioDemo/TeensySdioDemo.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/TeensySdioDemo/TeensySdioDemo.ino deleted file mode 100644 index 988a921..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/TeensySdioDemo/TeensySdioDemo.ino +++ /dev/null @@ -1,169 +0,0 @@ -// Simple performance test for Teensy 3.5/3.6 SDHC. -// Demonstrates yield() efficiency. - -// Warning SdFatSdio and SdFatSdioEX normally should -// not both be used in a program. -// Each has its own cache and member variables. - -#include "SdFat.h" - -// 32 KiB buffer. -const size_t BUF_DIM = 32768; - -// 8 MiB file. -const uint32_t FILE_SIZE = 256UL*BUF_DIM; - -SdFatSdio sd; - -SdFatSdioEX sdEx; - -File file; - -uint8_t buf[BUF_DIM]; - -// buffer as uint32_t -uint32_t* buf32 = (uint32_t*)buf; - -// Total usec in read/write calls. -uint32_t totalMicros = 0; -// Time in yield() function. -uint32_t yieldMicros = 0; -// Number of yield calls. -uint32_t yieldCalls = 0; -// Max busy time for single yield call. -uint32_t yieldMaxUsec = 0; -// Control access to the two versions of SdFat. -bool useEx = false; -//----------------------------------------------------------------------------- -bool sdBusy() { - return useEx ? sdEx.card()->isBusy() : sd.card()->isBusy(); -} -//----------------------------------------------------------------------------- -void errorHalt(const char* msg) { - if (useEx) { - sdEx.errorHalt(msg); - } else { - sd.errorHalt(msg); - } -} -//------------------------------------------------------------------------------ -uint32_t kHzSdClk() { - return useEx ? sdEx.card()->kHzSdClk() : sd.card()->kHzSdClk(); -} -//------------------------------------------------------------------------------ -// Replace "weak" system yield() function. -void yield() { - // Only count cardBusy time. - if (!sdBusy()) { - return; - } - uint32_t m = micros(); - yieldCalls++; - while (sdBusy()) { - // Do something here. - } - m = micros() - m; - if (m > yieldMaxUsec) { - yieldMaxUsec = m; - } - yieldMicros += m; -} -//----------------------------------------------------------------------------- -void runTest() { - // Zero Stats - totalMicros = 0; - yieldMicros = 0; - yieldCalls = 0; - yieldMaxUsec = 0; - if (!file.open("TeensyDemo.bin", O_RDWR | O_CREAT)) { - errorHalt("open failed"); - } - Serial.println("\nsize,write,read"); - Serial.println("bytes,KB/sec,KB/sec"); - for (size_t nb = 512; nb <= BUF_DIM; nb *= 2) { - file.truncate(0); - uint32_t nRdWr = FILE_SIZE/nb; - Serial.print(nb); - Serial.print(','); - uint32_t t = micros(); - for (uint32_t n = 0; n < nRdWr; n++) { - // Set start and end of buffer. - buf32[0] = n; - buf32[nb/4 - 1] = n; - if (nb != file.write(buf, nb)) { - errorHalt("write failed"); - } - } - t = micros() - t; - totalMicros += t; - Serial.print(1000.0*FILE_SIZE/t); - Serial.print(','); - file.rewind(); - t = micros(); - - for (uint32_t n = 0; n < nRdWr; n++) { - if ((int)nb != file.read(buf, nb)) { - errorHalt("read failed"); - } - // crude check of data. - if (buf32[0] != n || buf32[nb/4 - 1] != n) { - errorHalt("data check"); - } - } - t = micros() - t; - totalMicros += t; - Serial.println(1000.0*FILE_SIZE/t); - } - file.close(); - Serial.print("\ntotalMicros "); - Serial.println(totalMicros); - Serial.print("yieldMicros "); - Serial.println(yieldMicros); - Serial.print("yieldCalls "); - Serial.println(yieldCalls); - Serial.print("yieldMaxUsec "); - Serial.println(yieldMaxUsec); - Serial.print("kHzSdClk "); - Serial.println(kHzSdClk()); - Serial.println("Done"); -} -//----------------------------------------------------------------------------- -void setup() { - Serial.begin(9600); - while (!Serial) { - } - Serial.println("SdFatSdioEX uses extended multi-block transfers without DMA."); - Serial.println("SdFatSdio uses a traditional DMA SDIO implementation."); - Serial.println("Note the difference is speed and busy yield time.\n"); -} -//----------------------------------------------------------------------------- -void loop() { - do { - delay(10); - } while (Serial.available() && Serial.read()); - - Serial.println("Type '1' for SdFatSdioEX or '2' for SdFatSdio"); - while (!Serial.available()) { - } - char c = Serial.read(); - if (c != '1' && c != '2') { - Serial.println("Invalid input"); - return; - } - if (c =='1') { - useEx = true; - if (!sdEx.begin()) { - sd.initErrorHalt("SdFatSdioEX begin() failed"); - } - // make sdEx the current volume. - sdEx.chvol(); - } else { - useEx = false; - if (!sd.begin()) { - sd.initErrorHalt("SdFatSdio begin() failed"); - } - // make sd the current volume. - sd.chvol(); - } - runTest(); -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/Timestamp/Timestamp.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/Timestamp/Timestamp.ino deleted file mode 100644 index 74982e1..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/Timestamp/Timestamp.ino +++ /dev/null @@ -1,176 +0,0 @@ -/* - * This program tests the dateTimeCallback() function - * and the timestamp() function. - */ -#include -#include "SdFat.h" -#include "sdios.h" - -SdFat sd; - -SdFile file; - -// Default SD chip select is SS pin -const uint8_t chipSelect = SS; - -// create Serial stream -ArduinoOutStream cout(Serial); -//------------------------------------------------------------------------------ -// store error strings in flash to save RAM -#define error(s) sd.errorHalt(F(s)) -//------------------------------------------------------------------------------ -/* - * date/time values for debug - * normally supplied by a real-time clock or GPS - */ -// date 1-Oct-14 -uint16_t year = 2014; -uint8_t month = 10; -uint8_t day = 1; - -// time 20:30:40 -uint8_t hour = 20; -uint8_t minute = 30; -uint8_t second = 40; -//------------------------------------------------------------------------------ -/* - * User provided date time callback function. - * See SdFile::dateTimeCallback() for usage. - */ -void dateTime(uint16_t* date, uint16_t* time) { - // User gets date and time from GPS or real-time - // clock in real callback function - - // return date using FAT_DATE macro to format fields - *date = FAT_DATE(year, month, day); - - // return time using FAT_TIME macro to format fields - *time = FAT_TIME(hour, minute, second); -} -//------------------------------------------------------------------------------ -/* - * Function to print all timestamps. - */ -void printTimestamps(SdFile& f) { - dir_t d; - if (!f.dirEntry(&d)) { - error("f.dirEntry failed"); - } - - cout << F("Creation: "); - f.printFatDate(d.creationDate); - cout << ' '; - f.printFatTime(d.creationTime); - cout << endl; - - cout << F("Modify: "); - f.printFatDate(d.lastWriteDate); - cout <<' '; - f.printFatTime(d.lastWriteTime); - cout << endl; - - cout << F("Access: "); - f.printFatDate(d.lastAccessDate); - cout << endl; -} -//------------------------------------------------------------------------------ -void setup(void) { - Serial.begin(9600); - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - cout << F("Type any character to start\n"); - while (!Serial.available()) { - SysCall::yield(); - } - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } - - // remove files if they exist - sd.remove("callback.txt"); - sd.remove("default.txt"); - sd.remove("stamp.txt"); - - // create a new file with default timestamps - if (!file.open("default.txt", O_WRONLY | O_CREAT)) { - error("open default.txt failed"); - } - cout << F("\nOpen with default times\n"); - printTimestamps(file); - - // close file - file.close(); - /* - * Test the date time callback function. - * - * dateTimeCallback() sets the function - * that is called when a file is created - * or when a file's directory entry is - * modified by sync(). - * - * The callback can be disabled by the call - * SdFile::dateTimeCallbackCancel() - */ - // set date time callback function - SdFile::dateTimeCallback(dateTime); - - // create a new file with callback timestamps - if (!file.open("callback.txt", O_WRONLY | O_CREAT)) { - error("open callback.txt failed"); - } - cout << ("\nOpen with callback times\n"); - printTimestamps(file); - - // change call back date - day += 1; - - // must add two to see change since FAT second field is 5-bits - second += 2; - - // modify file by writing a byte - file.write('t'); - - // force dir update - file.sync(); - - cout << F("\nTimes after write\n"); - printTimestamps(file); - - // close file - file.close(); - /* - * Test timestamp() function - * - * Cancel callback so sync will not - * change access/modify timestamp - */ - SdFile::dateTimeCallbackCancel(); - - // create a new file with default timestamps - if (!file.open("stamp.txt", O_WRONLY | O_CREAT)) { - error("open stamp.txt failed"); - } - // set creation date time - if (!file.timestamp(T_CREATE, 2014, 11, 10, 1, 2, 3)) { - error("set create time failed"); - } - // set write/modification date time - if (!file.timestamp(T_WRITE, 2014, 11, 11, 4, 5, 6)) { - error("set write time failed"); - } - // set access date - if (!file.timestamp(T_ACCESS, 2014, 11, 12, 7, 8, 9)) { - error("set access time failed"); - } - cout << F("\nTimes after timestamp() calls\n"); - printTimestamps(file); - - file.close(); - cout << F("\nDone\n"); -} - -void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/TwoCards/TwoCards.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/TwoCards/TwoCards.ino deleted file mode 100644 index 98800cc..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/TwoCards/TwoCards.ino +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Warning This example requires extra RAM and may crash on Uno. - * Example use of two SD cards. - */ -#include -#include "SdFat.h" -#include "FreeStack.h" - -SdFat sd1; -const uint8_t SD1_CS = 10; // chip select for sd1 - -SdFat sd2; -const uint8_t SD2_CS = 4; // chip select for sd2 - -const uint8_t BUF_DIM = 100; -uint8_t buf[BUF_DIM]; - -const uint32_t FILE_SIZE = 1000000; -const uint16_t NWRITE = FILE_SIZE/BUF_DIM; -//------------------------------------------------------------------------------ -// print error msg, any SD error codes, and halt. -// store messages in flash -#define errorExit(msg) errorHalt(F(msg)) -#define initError(msg) initErrorHalt(F(msg)) -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - Serial.print(F("FreeStack: ")); - - Serial.println(FreeStack()); - - // fill buffer with known data - for (size_t i = 0; i < sizeof(buf); i++) { - buf[i] = i; - } - - Serial.println(F("type any character to start")); - while (!Serial.available()) { - SysCall::yield(); - } - - // disable sd2 while initializing sd1 - pinMode(SD2_CS, OUTPUT); - digitalWrite(SD2_CS, HIGH); - - // initialize the first card - if (!sd1.begin(SD1_CS)) { - sd1.initError("sd1:"); - } - // create Dir1 on sd1 if it does not exist - if (!sd1.exists("/Dir1")) { - if (!sd1.mkdir("/Dir1")) { - sd1.errorExit("sd1.mkdir"); - } - } - // initialize the second card - if (!sd2.begin(SD2_CS)) { - sd2.initError("sd2:"); - } -// create Dir2 on sd2 if it does not exist - if (!sd2.exists("/Dir2")) { - if (!sd2.mkdir("/Dir2")) { - sd2.errorExit("sd2.mkdir"); - } - } - // list root directory on both cards - Serial.println(F("------sd1 root-------")); - sd1.ls(); - Serial.println(F("------sd2 root-------")); - sd2.ls(); - - // make /Dir1 the default directory for sd1 - if (!sd1.chdir("/Dir1")) { - sd1.errorExit("sd1.chdir"); - } - - // make /Dir2 the default directory for sd2 - if (!sd2.chdir("/Dir2")) { - sd2.errorExit("sd2.chdir"); - } - - // list current directory on both cards - Serial.println(F("------sd1 Dir1-------")); - sd1.ls(); - Serial.println(F("------sd2 Dir2-------")); - sd2.ls(); - Serial.println(F("---------------------")); - - // remove rename.bin from /Dir2 directory of sd2 - if (sd2.exists("rename.bin")) { - if (!sd2.remove("rename.bin")) { - sd2.errorExit("remove rename.bin"); - } - } - // set the current working directory for open() to sd1 - sd1.chvol(); - - // create or open /Dir1/test.bin and truncate it to zero length - SdFile file1; - if (!file1.open("test.bin", O_RDWR | O_CREAT | O_TRUNC)) { - sd1.errorExit("file1"); - } - Serial.println(F("Writing test.bin to sd1")); - - // write data to /Dir1/test.bin on sd1 - for (uint16_t i = 0; i < NWRITE; i++) { - if (file1.write(buf, sizeof(buf)) != sizeof(buf)) { - sd1.errorExit("sd1.write"); - } - } - // set the current working directory for open() to sd2 - sd2.chvol(); - - // create or open /Dir2/copy.bin and truncate it to zero length - SdFile file2; - if (!file2.open("copy.bin", O_WRONLY | O_CREAT | O_TRUNC)) { - sd2.errorExit("file2"); - } - Serial.println(F("Copying test.bin to copy.bin")); - - // copy file1 to file2 - file1.rewind(); - uint32_t t = millis(); - - while (1) { - int n = file1.read(buf, sizeof(buf)); - if (n < 0) { - sd1.errorExit("read1"); - } - if (n == 0) { - break; - } - if ((int)file2.write(buf, n) != n) { - sd2.errorExit("write2"); - } - } - t = millis() - t; - Serial.print(F("File size: ")); - Serial.println(file2.fileSize()); - Serial.print(F("Copy time: ")); - Serial.print(t); - Serial.println(F(" millis")); - // close test.bin - file1.close(); - file2.close(); - // list current directory on both cards - Serial.println(F("------sd1 -------")); - sd1.ls("/", LS_R | LS_DATE | LS_SIZE); - Serial.println(F("------sd2 -------")); - sd2.ls("/", LS_R | LS_DATE | LS_SIZE); - Serial.println(F("---------------------")); - Serial.println(F("Renaming copy.bin")); - // rename the copy - if (!sd2.rename("copy.bin", "rename.bin")) { - sd2.errorExit("sd2.rename"); - } - // list current directory on both cards - Serial.println(F("------sd1 -------")); - sd1.ls("/", LS_R | LS_DATE | LS_SIZE); - Serial.println(F("------sd2 -------")); - sd2.ls("/", LS_R | LS_DATE | LS_SIZE); - Serial.println(F("---------------------")); - Serial.println(F("Done")); -} -//------------------------------------------------------------------------------ -void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/VolumeFreeSpace/VolumeFreeSpace.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/VolumeFreeSpace/VolumeFreeSpace.ino deleted file mode 100644 index fb0fe9f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/VolumeFreeSpace/VolumeFreeSpace.ino +++ /dev/null @@ -1,82 +0,0 @@ -/* - * This program demonstrates the freeClusterCount() call. - */ -#include -#include "SdFat.h" -#include "sdios.h" -/* - * SD chip select pin. Common values are: - * - * Arduino Ethernet shield, pin 4. - * SparkFun SD shield, pin 8. - * Adafruit Datalogging shield, pin 10. - * Default SD chip select is the SPI SS pin. - */ -const uint8_t chipSelect = SS; - -#define TEST_FILE "Cluster.test" -// file system -SdFat sd; - -// test file -SdFile file; - -// Serial output stream -ArduinoOutStream cout(Serial); -//------------------------------------------------------------------------------ -void printFreeSpace() { - cout << F("freeClusterCount() call time: "); - uint32_t m = micros(); - uint32_t volFree = sd.vol()->freeClusterCount(); - cout << micros() - m << F(" micros\n"); - cout << F("freeClusters: ") << volFree << setprecision(3) << endl; - float fs = 0.000512*volFree*sd.vol()->blocksPerCluster(); - cout << F("freeSpace: ") << fs << F(" MB (MB = 1,000,000 bytes)\n\n"); -} -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - if (!MAINTAIN_FREE_CLUSTER_COUNT) { - cout << F("Please edit SdFatConfig.h and set\n"); - cout << F("MAINTAIN_FREE_CLUSTER_COUNT nonzero for\n"); - cout << F("maximum freeClusterCount() performance.\n\n"); - } - // F stores strings in flash to save RAM - cout << F("Type any character to start\n"); - while (!Serial.available()) { - SysCall::yield(); - } - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } - // Insure no TEST_FILE. - sd.remove(TEST_FILE); - - cout << F("\nFirst call to freeClusterCount scans the FAT.\n\n"); - printFreeSpace(); - - cout << F("Create and write to ") << TEST_FILE << endl; - if (!file.open(TEST_FILE, O_WRONLY | O_CREAT)) { - sd.errorHalt(F("Create failed")); - } - file.print(F("Cause a cluster to be allocated")); - file.close(); - - cout << F("\nSecond freeClusterCount call is faster if\n"); - cout << F("MAINTAIN_FREE_CLUSTER_COUNT is nonzero.\n\n"); - - printFreeSpace(); - - cout << F("Remove ") << TEST_FILE << endl << endl; - sd.remove(TEST_FILE); - printFreeSpace(); - cout << F("Done") << endl; -} -//------------------------------------------------------------------------------ -void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/bench/bench.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/bench/bench.ino deleted file mode 100644 index 1a155a8..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/bench/bench.ino +++ /dev/null @@ -1,222 +0,0 @@ -/* - * This program is a simple binary write/read benchmark. - */ -#include -#include "SdFat.h" -#include "sdios.h" -#include "FreeStack.h" - -// Set USE_SDIO to zero for SPI card access. -#define USE_SDIO 0 - -// SD chip select pin -const uint8_t chipSelect = SS; - -// Size of read/write. -const size_t BUF_SIZE = 512; - -// File size in MB where MB = 1,000,000 bytes. -const uint32_t FILE_SIZE_MB = 5; - -// Write pass count. -const uint8_t WRITE_COUNT = 2; - -// Read pass count. -const uint8_t READ_COUNT = 2; -//============================================================================== -// End of configuration constants. -//------------------------------------------------------------------------------ -// File size in bytes. -const uint32_t FILE_SIZE = 1000000UL*FILE_SIZE_MB; - -uint8_t buf[BUF_SIZE]; - -// file system -#if USE_SDIO -// Traditional DMA version. -// SdFatSdio sd; -// Faster version. -SdFatSdioEX sd; -#else // USE_SDIO -SdFat sd; -#endif // USE_SDIO - -// Set ENABLE_EXTENDED_TRANSFER_CLASS to use extended SD I/O. -// Requires dedicated use of the SPI bus. -// SdFatEX sd; - -// Set ENABLE_SOFTWARE_SPI_CLASS to use software SPI. -// Args are misoPin, mosiPin, sckPin. -// SdFatSoftSpi<6, 7, 5> sd; - -// test file -SdFile file; - -// Serial output stream -ArduinoOutStream cout(Serial); -//------------------------------------------------------------------------------ -// Store error strings in flash to save RAM. -#define error(s) sd.errorHalt(F(s)) -//------------------------------------------------------------------------------ -void cidDmp() { - cid_t cid; - if (!sd.card()->readCID(&cid)) { - error("readCID failed"); - } - cout << F("\nManufacturer ID: "); - cout << hex << int(cid.mid) << dec << endl; - cout << F("OEM ID: ") << cid.oid[0] << cid.oid[1] << endl; - cout << F("Product: "); - for (uint8_t i = 0; i < 5; i++) { - cout << cid.pnm[i]; - } - cout << F("\nVersion: "); - cout << int(cid.prv_n) << '.' << int(cid.prv_m) << endl; - cout << F("Serial number: ") << hex << cid.psn << dec << endl; - cout << F("Manufacturing date: "); - cout << int(cid.mdt_month) << '/'; - cout << (2000 + cid.mdt_year_low + 10 * cid.mdt_year_high) << endl; - cout << endl; -} -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - delay(1000); - cout << F("\nUse a freshly formatted SD for best performance.\n"); - - // use uppercase in hex and use 0X base prefix - cout << uppercase << showbase << endl; -} -//------------------------------------------------------------------------------ -void loop() { - float s; - uint32_t t; - uint32_t maxLatency; - uint32_t minLatency; - uint32_t totalLatency; - - // Discard any input. - do { - delay(10); - } while (Serial.available() && Serial.read() >= 0); - - // F( stores strings in flash to save RAM - cout << F("Type any character to start\n"); - while (!Serial.available()) { - SysCall::yield(); - } - cout << F("chipSelect: ") << int(chipSelect) << endl; - cout << F("FreeStack: ") << FreeStack() << endl; - -#if USE_SDIO - if (!sd.begin()) { - sd.initErrorHalt(); - } -#else // USE_SDIO - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } -#endif // USE_SDIO - cout << F("Type is FAT") << int(sd.vol()->fatType()) << endl; - cout << F("Card size: ") << sd.card()->cardSize()*512E-9; - cout << F(" GB (GB = 1E9 bytes)") << endl; - - cidDmp(); - - // open or create file - truncate existing file. - if (!file.open("bench.dat", O_RDWR | O_CREAT | O_TRUNC)) { - error("open failed"); - } - - // fill buf with known data - for (size_t i = 0; i < (BUF_SIZE-2); i++) { - buf[i] = 'A' + (i % 26); - } - buf[BUF_SIZE-2] = '\r'; - buf[BUF_SIZE-1] = '\n'; - - cout << F("File size ") << FILE_SIZE_MB << F(" MB\n"); - cout << F("Buffer size ") << BUF_SIZE << F(" bytes\n"); - cout << F("Starting write test, please wait.") << endl << endl; - - // do write test - uint32_t n = FILE_SIZE/sizeof(buf); - cout < m) { - minLatency = m; - } - totalLatency += m; - } - file.sync(); - t = millis() - t; - s = file.fileSize(); - cout << s/t <<',' << maxLatency << ',' << minLatency; - cout << ',' << totalLatency/n << endl; - } - cout << endl << F("Starting read test, please wait.") << endl; - cout << endl < m) { - minLatency = m; - } - totalLatency += m; - if (buf[BUF_SIZE-1] != '\n') { - error("data check"); - } - } - s = file.fileSize(); - t = millis() - t; - cout << s/t <<',' << maxLatency << ',' << minLatency; - cout << ',' << totalLatency/n << endl; - } - cout << endl << F("Done") << endl; - file.close(); -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/dataLogger/dataLogger.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/dataLogger/dataLogger.ino deleted file mode 100644 index d4a4b4a..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/dataLogger/dataLogger.ino +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Simple data logger. - */ -#include -#include "SdFat.h" - -// SD chip select pin. Be sure to disable any other SPI devices such as Enet. -const uint8_t chipSelect = SS; - -// Interval between data records in milliseconds. -// The interval must be greater than the maximum SD write latency plus the -// time to acquire and write data to the SD to avoid overrun errors. -// Run the bench example to check the quality of your SD card. -const uint32_t SAMPLE_INTERVAL_MS = 1000; - -// Log file base name. Must be six characters or less. -#define FILE_BASE_NAME "Data" -//------------------------------------------------------------------------------ -// File system object. -SdFat sd; - -// Log file. -SdFile file; - -// Time in micros for next data record. -uint32_t logTime; - -//============================================================================== -// User functions. Edit writeHeader() and logData() for your requirements. - -const uint8_t ANALOG_COUNT = 4; -//------------------------------------------------------------------------------ -// Write data header. -void writeHeader() { - file.print(F("micros")); - for (uint8_t i = 0; i < ANALOG_COUNT; i++) { - file.print(F(",adc")); - file.print(i, DEC); - } - file.println(); -} -//------------------------------------------------------------------------------ -// Log a data record. -void logData() { - uint16_t data[ANALOG_COUNT]; - - // Read all channels to avoid SD write latency between readings. - for (uint8_t i = 0; i < ANALOG_COUNT; i++) { - data[i] = analogRead(i); - } - // Write data to file. Start with log time in micros. - file.print(logTime); - - // Write ADC data to CSV record. - for (uint8_t i = 0; i < ANALOG_COUNT; i++) { - file.write(','); - file.print(data[i]); - } - file.println(); -} -//============================================================================== -// Error messages stored in flash. -#define error(msg) sd.errorHalt(F(msg)) -//------------------------------------------------------------------------------ -void setup() { - const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1; - char fileName[13] = FILE_BASE_NAME "00.csv"; - - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - delay(1000); - - Serial.println(F("Type any character to start")); - while (!Serial.available()) { - SysCall::yield(); - } - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } - - // Find an unused file name. - if (BASE_NAME_SIZE > 6) { - error("FILE_BASE_NAME too long"); - } - while (sd.exists(fileName)) { - if (fileName[BASE_NAME_SIZE + 1] != '9') { - fileName[BASE_NAME_SIZE + 1]++; - } else if (fileName[BASE_NAME_SIZE] != '9') { - fileName[BASE_NAME_SIZE + 1] = '0'; - fileName[BASE_NAME_SIZE]++; - } else { - error("Can't create file name"); - } - } - if (!file.open(fileName, O_WRONLY | O_CREAT | O_EXCL)) { - error("file.open"); - } - // Read any Serial data. - do { - delay(10); - } while (Serial.available() && Serial.read() >= 0); - - Serial.print(F("Logging to: ")); - Serial.println(fileName); - Serial.println(F("Type any character to stop")); - - // Write data header. - writeHeader(); - - // Start on a multiple of the sample interval. - logTime = micros()/(1000UL*SAMPLE_INTERVAL_MS) + 1; - logTime *= 1000UL*SAMPLE_INTERVAL_MS; -} -//------------------------------------------------------------------------------ -void loop() { - // Time for next record. - logTime += 1000UL*SAMPLE_INTERVAL_MS; - - // Wait for log time. - int32_t diff; - do { - diff = micros() - logTime; - } while (diff < 0); - - // Check for data rate too high. - if (diff > 10) { - error("Missed data record"); - } - - logData(); - - // Force data to SD and update the directory entry to avoid data loss. - if (!file.sync() || file.getWriteError()) { - error("write error"); - } - - if (Serial.available()) { - // Close file and stop. - file.close(); - Serial.println(F("Done")); - SysCall::halt(); - } -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/fgets/fgets.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/fgets/fgets.ino deleted file mode 100644 index 5996b69..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/fgets/fgets.ino +++ /dev/null @@ -1,88 +0,0 @@ -// Demo of fgets function to read lines from a file. -#include -#include "SdFat.h" -#include "sdios.h" - -// SD chip select pin -const uint8_t chipSelect = SS; - -SdFat sd; -// print stream -ArduinoOutStream cout(Serial); -//------------------------------------------------------------------------------ -// store error strings in flash memory -#define error(s) sd.errorHalt(F(s)) -//------------------------------------------------------------------------------ -void demoFgets() { - char line[25]; - int n; - // open test file - SdFile rdfile("fgets.txt", O_RDONLY); - - // check for open error - if (!rdfile.isOpen()) { - error("demoFgets"); - } - - cout << endl << F( - "Lines with '>' end with a '\\n' character\n" - "Lines with '#' do not end with a '\\n' character\n" - "\n"); - - // read lines from the file - while ((n = rdfile.fgets(line, sizeof(line))) > 0) { - if (line[n - 1] == '\n') { - cout << '>' << line; - } else { - cout << '#' << line << endl; - } - } -} -//------------------------------------------------------------------------------ -void makeTestFile() { - // create or open test file - SdFile wrfile("fgets.txt", O_WRONLY | O_CREAT | O_TRUNC); - - // check for open error - if (!wrfile.isOpen()) { - error("MakeTestFile"); - } - - // write test file - wrfile.print(F( - "Line with CRLF\r\n" - "Line with only LF\n" - "Long line that will require an extra read\n" - "\n" // empty line - "Line at EOF without NL" - )); - wrfile.close(); -} -//------------------------------------------------------------------------------ -void setup(void) { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - - cout << F("Type any character to start\n"); - while (!Serial.available()) { - SysCall::yield(); - } - delay(400); // catch Due reset problem - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } - - makeTestFile(); - - demoFgets(); - - cout << F("\nDone\n"); -} -void loop(void) {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/formatting/formatting.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/formatting/formatting.ino deleted file mode 100644 index 3268965..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/formatting/formatting.ino +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Print a table with various formatting options - * Format dates - */ -#include -#include "SdFat.h" -#include "sdios.h" - -// create Serial stream -ArduinoOutStream cout(Serial); -//------------------------------------------------------------------------------ -// print a table to demonstrate format manipulators -void example(void) { - const int max = 10; - const int width = 4; - - for (int row = 1; row <= max; row++) { - for (int col = 1; col <= max; col++) { - cout << setw(width) << row * col << (col == max ? '\n' : ' '); - } - } - cout << endl; -} -//------------------------------------------------------------------------------ -// print a date as mm/dd/yyyy with zero fill in mm and dd -// shows how to set and restore the fill character -void showDate(int m, int d, int y) { - // convert two digit year - if (y < 100) { - y += 2000; - } - - // set new fill to '0' save old fill character - char old = cout.fill('0'); - - // print date - cout << setw(2) << m << '/' << setw(2) << d << '/' << y << endl; - - // restore old fill character - cout.fill(old); -} -//------------------------------------------------------------------------------ -void setup(void) { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - delay(2000); - - cout << endl << "default formatting" << endl; - example(); - - cout << showpos << "showpos" << endl; - example(); - - cout << hex << left << showbase << "hex left showbase" << endl; - example(); - - cout << internal << setfill('0') << uppercase; - cout << "uppercase hex internal showbase fill('0')" < -#include "SdFat.h" -#include "sdios.h" - -// SD chip select pin -const uint8_t chipSelect = SS; - -// file system object -SdFat sd; - -// create a serial stream -ArduinoOutStream cout(Serial); -//------------------------------------------------------------------------------ -void makeTestFile() { - ofstream sdout("getline.txt"); - // use flash for text to save RAM - sdout << F( - "short line\n" - "\n" - "17 character line\n" - "too long for buffer\n" - "line with no nl"); - - sdout.close(); -} -//------------------------------------------------------------------------------ -void testGetline() { - const int line_buffer_size = 18; - char buffer[line_buffer_size]; - ifstream sdin("getline.txt"); - int line_number = 0; - - while (sdin.getline(buffer, line_buffer_size, '\n') || sdin.gcount()) { - int count = sdin.gcount(); - if (sdin.fail()) { - cout << "Partial long line"; - sdin.clear(sdin.rdstate() & ~ios_base::failbit); - } else if (sdin.eof()) { - cout << "Partial final line"; // sdin.fail() is false - } else { - count--; // Don’t include newline in count - cout << "Line " << ++line_number; - } - cout << " (" << count << " chars): " << buffer << endl; - } -} -//------------------------------------------------------------------------------ -void setup(void) { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - - // F stores strings in flash to save RAM - cout << F("Type any character to start\n"); - while (!Serial.available()) { - SysCall::yield(); - } - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } - - // make the test file - makeTestFile(); - - // run the example - testGetline(); - cout << "\nDone!\n"; -} -//------------------------------------------------------------------------------ -void loop(void) {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/rename/rename.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/rename/rename.ino deleted file mode 100644 index ad4a2d9..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/rename/rename.ino +++ /dev/null @@ -1,107 +0,0 @@ -/* - * This program demonstrates use of SdFile::rename() - * and SdFat::rename(). - */ -#include -#include "SdFat.h" -#include "sdios.h" - -// SD chip select pin -const uint8_t chipSelect = SS; - -// file system -SdFat sd; - -// Serial print stream -ArduinoOutStream cout(Serial); -//------------------------------------------------------------------------------ -// store error strings in flash to save RAM -#define error(s) sd.errorHalt(F(s)) -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - cout << F("Insert an empty SD. Type any character to start.") << endl; - while (!Serial.available()) { - SysCall::yield(); - } - - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } - - // Remove file/dirs from previous run. - if (sd.exists("dir2/DIR3/NAME3.txt")) { - cout << F("Removing /dir2/DIR3/NAME3.txt") << endl; - if (!sd.remove("dir2/DIR3/NAME3.txt") || - !sd.rmdir("dir2/DIR3/") || - !sd.rmdir("dir2/")) { - error("remove/rmdir failed"); - } - } - // create a file and write one line to the file - SdFile file("Name1.txt", O_WRONLY | O_CREAT); - if (!file.isOpen()) { - error("Name1.txt"); - } - file.println("A test line for Name1.txt"); - - // rename the file name2.txt and add a line. - // Use current working directory, root. - if (!file.rename("name2.txt")) { - error("name2.txt"); - } - file.println("A test line for name2.txt"); - - // list files - cout << F("------") << endl; - sd.ls(LS_R); - - // make a new directory - "Dir1" - if (!sd.mkdir("Dir1")) { - error("Dir1"); - } - - // move file into Dir1, rename it NAME3.txt and add a line - if (!file.rename("Dir1/NAME3.txt")) { - error("NAME3.txt"); - } - file.println("A line for Dir1/NAME3.txt"); - - // list files - cout << F("------") << endl; - sd.ls(LS_R); - - // make directory "dir2" - if (!sd.mkdir("dir2")) { - error("dir2"); - } - - // close file before rename(oldPath, newPath) - file.close(); - - // move Dir1 into dir2 and rename it DIR3 - if (!sd.rename("Dir1", "dir2/DIR3")) { - error("dir2/DIR3"); - } - - // open file for append in new location and add a line - if (!file.open("dir2/DIR3/NAME3.txt", O_WRONLY | O_APPEND)) { - error("dir2/DIR3/NAME3.txt"); - } - file.println("A line for dir2/DIR3/NAME3.txt"); - file.close(); - - // list files - cout << F("------") << endl; - sd.ls(LS_R); - - cout << F("Done") << endl; -} -void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/wipe/wipe.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/wipe/wipe.ino deleted file mode 100644 index 6d1bc93..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/examples/wipe/wipe.ino +++ /dev/null @@ -1,42 +0,0 @@ -// Example to wipe all data from an already formatted SD. -#include -#include "SdFat.h" -const int chipSelect = SS; - -SdFat sd; - -void setup() { - int c; - Serial.begin(9600); - // Wait for USB Serial - while (!Serial) { - SysCall::yield(); - } - Serial.println("Type 'Y' to wipe all data."); - while (!Serial.available()) { - SysCall::yield(); - } - c = Serial.read(); - if (c != 'Y') { - sd.errorHalt("Quitting, you did not type 'Y'."); - } - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - sd.initErrorHalt(); - } - // Use wipe() for no dot progress indicator. - if (!sd.wipe(&Serial)) { - sd.errorHalt("Wipe failed."); - } - // Must reinitialize after wipe. - // Initialize at the highest speed supported by the board that is - // not over 50 MHz. Try a lower speed if SPI errors occur. - if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { - sd.errorHalt("Second init failed."); - } - Serial.println("Done"); -} - -void loop() { -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/AdcErrorStudy.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/AdcErrorStudy.txt deleted file mode 100644 index 0f7cbd1..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/AdcErrorStudy.txt +++ /dev/null @@ -1,98 +0,0 @@ -Static Tests of the Arduino Internal ADC. - -Several people have asked about the DC accuracy of the Arduino ADC when used in my data logging applications at slow sample rates. - -Here are my results of some "hobby level" measurements of the Arduino ADC. - -One question is how important is the ADC clock rate. I did measurents for an ADC clock rate of 125 kHz to 2MHz. - -Another question is how much does Noise Reduction Mode help. I did a series of measurements using this mode. - -Noise Reduction Mode only reduced the mean absolute error slightly. - -I do calibration to remove Offset Error and Gain Error. Calibration is very important for good accuracy. - -These tests depend on the Arduino voltage regulator providing a stable voltage during the tests. The Arduino ADC reference voltage is Vcc for these tests. This may not be realistic for practical applications - -Integral Non-linearity (INL) is the main remaining source of error. - -Here are my results for static (DC) tests of the internal ADC for three UNOs. - -The Arduinos are powered by a high quality nine volt power supply. - -These tests measure a DC level so do not include problems due to time jitter, S/H time, and other dynamic errors. -There are several studies of the dynamic behavior of the Arduino ADC that determine ENOB (Effective Number Of Bits). - -I used a shield with a 12-bit MCP4921 DAC to generate voltage levels. This ADC has an output buffer so it provides a very low impedance source. - -I measured the voltage of the DAC with a calibrated 18-bit MCP3422 ADC on the shield. - -I used DAC levels from 20 to 4075 to avoid zero offset errors at low voltages and DAC buffer problems at high voltages. - -Each series of measurements has 4056 data points. - -This is a voltage range of about 0.023 to 4.972 volts. - -I calibrated the Arduino ADC for each series of measurements with a linear fit of the form. - -v = a + b*adcValue - -Errors are the difference between the value measured with the 18-bit ADC and the calibrated value measured with the AVR ADC. - -I also show the results for no calibration, the NoCal column, using the datasheet formula. - -Vin = Vref*adcValue/1024 - - -The rows in the tables tables are. - -Min - minimum error in millivolts - -Max - maximum error in millivolts - -MAE - mean absolute error in millivolts - - -The columns in the tables are: - -Ideal - results for a perfect 10-bit ADC for comparison. - -NoCal - datasheet formula (5/1024)*adcValue with Noise Reduction Mode. - -NR128 - Noise Reduction mode with Prescaler of 128 (ADC clock of 125 kHz). - -PS128 - analogRead with Prescaler of 128 (ADC clock of 125 kHz). - -PS64 - analogRead with Prescaler of 64 (ADC clock of 250 kHz). - -PS32 - analogRead with Prescaler of 32 (ADC clock of 500 kHz). - -PS16 - analogRead with Prescaler of 16 (ADC clock of 1 MHz). - -PS8 - analogRead with Prescaler of 8 (ADC clock of 2 MHz). - - -Results for three UNO Arduinos - - First Arduino - Error Millivolts - - Ideal NoCal NR128 PS128 PS64 PS32 PS16 PS8 -Min -2.44 -2.43 -3.72 -4.01 -3.88 -4.53 -6.57 -27.18 -Max 2.44 11.69 3.74 4.24 4.15 5.17 8.69 23.21 -MAE 1.22 5.02 1.33 1.38 1.37 1.44 1.96 4.11 - - Second Arduino - Error Millivolts - - Ideal NoCal NR128 PS128 PS64 PS32 PS16 PS8 -Min -2.44 -9.24 -4.87 -4.86 -5.05 -5.34 -6.52 -24.04 -Max 2.44 11.62 3.95 4.64 4.69 5.71 8.41 21.29 -MAE 1.22 5.33 1.41 1.43 1.44 1.53 2.02 4.05 - - Third Arduino - Error Millivolts - - Ideal NoCal NR128 PS128 PS64 PS32 PS16 PS8 -Min -2.44 -7.88 -4.12 -4.40 -4.32 -4.41 -6.97 -26.93 -Max 2.44 12.53 3.80 4.04 4.18 5.27 8.84 24.59 -MAE 1.22 4.85 1.29 1.33 1.34 1.42 1.91 4.10 - - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/RateTable.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/RateTable.txt deleted file mode 100644 index 627d143..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/RateTable.txt +++ /dev/null @@ -1,21 +0,0 @@ -Maximum Sample Rate Table - - ADC clock kHz - 125 250 500 1000 -pins -1 7692 14286 25000 40000 -2 3810 6667 11111 16667 -3 2572 4790 8421 13559 -4 1942 3636 6452 10526 -5 1559 2930 5229 8602 -6 1303 2454 4396 7273 -7 1119 2111 3791 6299 -8 980 1852 3333 5556 -9 872 1649 2974 4969 -10 786 1487 2685 4494 -11 715 1354 2446 4103 -12 656 1242 2247 3774 -13 606 1148 2078 3493 -14 563 1067 1932 3252 -15 525 996 1806 3042 -16 493 935 1695 2857 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/bintocsv/AnalogBinLogger.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/bintocsv/AnalogBinLogger.h deleted file mode 100644 index f24afa2..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/bintocsv/AnalogBinLogger.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef AnalogBinLogger_h -#define AnalogBinLogger_h -//------------------------------------------------------------------------------ -// First block of file. -struct metadata_t { - unsigned long adcFrequency; // ADC clock frequency - unsigned long cpuFrequency; // CPU clock frequency - unsigned long sampleInterval; // Sample interval in CPU cycles. - unsigned long recordEightBits; // Size of ADC values, nonzero for 8-bits. - unsigned long pinCount; // Number of analog pins in a sample. - unsigned long pinNumber[123]; // List of pin numbers in a sample. -}; -//------------------------------------------------------------------------------ -// Data block for 8-bit ADC mode. -const size_t DATA_DIM8 = 508; -struct block8_t { - unsigned short count; // count of data bytes - unsigned short overrun; // count of overruns since last block - unsigned char data[DATA_DIM8]; -}; -//------------------------------------------------------------------------------ -// Data block for 10-bit ADC mode. -const size_t DATA_DIM16 = 254; -struct block16_t { - unsigned short count; // count of data bytes - unsigned short overrun; // count of overruns since last block - unsigned short data[DATA_DIM16]; -}; -//------------------------------------------------------------------------------ -// Data block for PC use -struct adcdata_t { - unsigned short count; // count of data bytes - unsigned short overrun; // count of overruns since last block - union { - unsigned char u8[DATA_DIM8]; - unsigned short u16[DATA_DIM16]; - } data; -}; -#endif // AnalogBinLogger_h \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/bintocsv/bintocsv.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/bintocsv/bintocsv.cpp deleted file mode 100644 index 517e061..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/bintocsv/bintocsv.cpp +++ /dev/null @@ -1,82 +0,0 @@ -#include -#include "AnalogBinLogger.h" -FILE *source; -FILE *destination; -int count = 0; - -int main(int argc, char** argv) { - metadata_t meta; - adcdata_t adc; - // Make sure no padding/size problems. - if (sizeof(meta) != 512 || sizeof(adc) != 512) { - printf("block size error\n"); - return 0; - } - if (argc != 3) { - printf("missing arguments:\n"); - printf("%s binFile csvFile\n", argv[0]); - return 0; - } - source = fopen(argv[1], "rb"); - if (!source) { - printf("open failed for %s\n", argv[1]); - return 0; - } - if (fread(&meta, sizeof(meta), 1, source) != 1) { - printf("read meta data failed\n"); - return 0; - } - if ( meta.pinCount == 0 - || meta.pinCount > (sizeof(meta.pinNumber)/sizeof(meta.pinNumber[0])) - || meta.adcFrequency < 50000 || meta.adcFrequency > 4000000) { - printf("Invalid meta data\n"); - return 0; - } - destination = fopen(argv[2], "w"); - if (!destination) { - printf("open failed for %s\n", argv[2]); - return 0; - } - int pinCount = meta.pinCount; - printf("pinCount: %d\n", pinCount); - printf("Sample pins:"); - for (unsigned i = 0; i < meta.pinCount; i++) { - printf(" %d", meta.pinNumber[i]); - } - printf("\n"); - printf("ADC clock rate: %g kHz\n", 0.001*meta.adcFrequency); - float sampleInterval = (float)meta.sampleInterval/(float)meta.cpuFrequency; - printf("Sample rate: %g per sec\n", 1.0/sampleInterval); - printf("Sample interval: %.4f usec\n", 1.0e6*sampleInterval); - - fprintf(destination, "Interval,%.4f,usec\n", 1.0e6*sampleInterval); - // Write header with pin numbers - for (int i = 0; i < ((int)meta.pinCount - 1); i++) { - fprintf(destination, "pin%d,", meta.pinNumber[i]); - } - fprintf(destination, "pin%d\n", meta.pinNumber[meta.pinCount - 1]); - unsigned maxCount = meta.recordEightBits ? DATA_DIM8 : DATA_DIM16; - while (!feof(source)) { - if (fread(&adc, sizeof(adc), 1, source) != 1) break; - if (adc.count > maxCount) { - printf("****Invalid data block****\n"); - return 0; - } - if (adc.overrun) { - fprintf(destination, "Overruns,%d\n", adc.overrun); - } - for (int i = 0; i < adc.count; i++) { - unsigned value = meta.recordEightBits ? adc.data.u8[i] : adc.data.u16[i]; - if ((i + 1)%pinCount) { - fprintf(destination, "%d,", value); - } else { - fprintf(destination, "%d\n", value); - } - } - count += adc.count; - } - printf("%d ADC values read\n", count); - fclose(source); - fclose(destination); - return 0; -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/readme.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/readme.txt deleted file mode 100644 index 2c12fd8..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/AnalogBinLoggerExtras/readme.txt +++ /dev/null @@ -1,95 +0,0 @@ -AnalogBinLogger.ino logs analog data to a binary SD file at high rates. - -Samples are logged at regular intervals by using timer1. Timer/Counter1 -Compare Match B is used to trigger the ADC for the first pin in a sample. -The ADC is triggered for remaining sample pins in the ADC conversion complete -interrupt routine. - -Data is captured in the ADC interrupt routine and saved in 512 byte buffers. - -Buffered data is written to the SD in a function called from loop(). The -entire data set is written to a large contiguous file as a single multi-block -write. This reduces write latency problems. - -Many inexpensive SD cards work well at lower rates. I used a $6.00 -SanDisk 4 GB class 4 card for testing. - -SanDisk class 4 cards work well at fairly high rates. I used the 4 GB SanDisk -card to log a single pin at 40,000 samples per second. - -You may need to increase the time between samples if your card has higher -latency. Using a Mega Arduino can help since it has more buffering. - -The bintocsv folder contains a PC program for converting binary files to -CSV files. Build it from the included source files. bintocvs is a command line program. - -bintocsv binFile csvFile - -AnalogBinLogger requires a recent version of the SdFat library. The SdFat -folder contains a beta version I used for development. - -The latest stable version is here: -http://code.google.com/p/sdfatlib/downloads/list - -You also need to install the included BufferedWriter library. It provides -fast text formatting. - -Example data for a 2 kHz sine wave logged at 40,000 samples per second is -shown in DATA.PNG and FFT.PNG shows a FFT of the data. See ExcelFFT.pdf -in the ADCdocs folder for details on calculating a FFT. - -The accuracy of the ADC samples depends on the ADC clock rate. See the -ADC_ENOB.PNG file for a plot of accuracy vs ADC clock frequency. - -See files in the ADCdocs folder for more information on ADC accuracy. - -To modify this program you will need a good knowledge of the Arduino -ADC, timer1 and C++ programming. This is not for the newbie. - -I have an LED and resistor connected to pin 3 to signal fatal errors and -data overruns. Fatal errors are indicated by a blinking led. Overrun errors -are indicated by a solid lit led. The count of samples dropped is written -to the SD and data logging continues. - -You can disable the error led feature by setting the error pin number negative: - -To use AnalogBinLogger, install these items. - -Place the BufferWriter and SdFat folders in your sketchbook libraries folder. - -Place the AnalogIsrLogger folder in your sketchbook folder. - -You must edit the configuration constants at the beginning of the program -to set the sample pins, sample rate, and other configuration values. - -Initially the program is setup to log the first five analog pins at 5000 -samples per second. Change these values to suit your needs. - -See RateTable.txt for maximum allowed sample rates vs pin count and ADC clock -frequency. - -The program has four commands: - -c - convert file to CSV -d - dump data to Serial -e - overrun error details -r - record ADC data - -All commands can be terminated by entering a character from the serial monitor. - -The c command converts the current binary file to a text file. Entering a -character on the serial monitor terminates the command. - -The d command converts the binary file to text and displays it on the serial -monitor. Entering a character on the serial monitor terminates the command. - -The e command displays details about overruns in the current binary file. -Data overruns happen when data samples are lost due to long write latency -of the SD. - -The r command will record ADC data to a binary file. It will terminate -when a character is entered on the serial monitor or the the maximum file -block count has been reached. - -A number of program options can be set by changing constants at the beginning -of the program. \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/MainPage/SdFatmainpage.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/MainPage/SdFatmainpage.h deleted file mode 100644 index f83e90f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/MainPage/SdFatmainpage.h +++ /dev/null @@ -1,403 +0,0 @@ -/** - * Copyright (c) 20011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -/** -\mainpage Arduino %SdFat Library -
Copyright © 2012-2018 by William Greiman -
- -\section Intro Introduction -The Arduino %SdFat Library is a minimal implementation of FAT16 and FAT32 -file systems on SD flash memory cards. Standard SD and high capacity SDHC -cards are supported. - -Experimental support for FAT12 can be enabled by setting FAT12_SUPPORT -nonzero in SdFatConfig.h. - -The %SdFat library supports Long %File Names or short 8.3 names. -Edit the SdFatConfig.h file to select short or long file names. - -The main classes in %SdFat are SdFat, SdFatEX, SdFatSoftSpi, SdFatSoftSpiEX, -SdBaseFile, SdFile, File, StdioStream, \ref fstream, \ref ifstream, -and \ref ofstream. - -The SdFat, SdFatEX, SdFatSoftSpi and SdFatSoftSpiEX classes maintain a -FAT volume, a current working directory, and simplify initialization -of other classes. The SdFat and SdFatEX classes uses a fast custom hardware SPI -implementation. The SdFatSoftSpi and SdFatSoftSpiEX classes uses software SPI. - -the SdFatEX and SdFatSoftSpiEX use extended multi-block I/O for enhanced -performance. These classes must have exclusive use of the SPI bus. - -The SdBaseFile class provides basic file access functions such as open(), -binary read(), binary write(), close(), remove(), and sync(). SdBaseFile -is the smallest file class. - -The SdFile class has all the SdBaseFile class functions plus the Arduino -Print class functions. - -The File class has all the SdBaseFile functions plus the functions in -the Arduino SD.h File class. This provides compatibility with the -Arduino SD.h library. - -The StdioStream class implements functions similar to Linux/Unix standard -buffered input/output. - -The \ref fstream class implements C++ iostreams for both reading and writing -text files. - -The \ref ifstream class implements C++ iostreams for reading text files. - -The \ref ofstream class implements C++ iostreams for writing text files. - -The classes \ref ifstream, \ref ofstream, \ref istream, and \ref ostream -follow the C++ \ref iostream standard when possible. - -There are many tutorials and much documentation about using C++ iostreams -on the web. - -http://www.cplusplus.com/ is a good C++ site for learning iostreams. - -The classes \ref ibufstream and \ref obufstream format and parse character - strings in memory buffers. - -the classes ArduinoInStream and ArduinoOutStream provide iostream functions -for Serial, LiquidCrystal, and other devices. - -A number of example are provided in the %SdFat/examples folder. These were -developed to test %SdFat and illustrate its use. - -\section Install Installation - -You must manually install SdFat by copying the SdFat folder from the download -package to the Arduino libraries folder in your sketch folder. - -See the Manual installation section of this guide. - -http://arduino.cc/en/Guide/Libraries - -\section SDconfig SdFat Configuration - -Several configuration options may be changed by editing the SdFatConfig.h -file in the %SdFat folder. - -Set USE_LONG_FILE_NAMES nonzero to enable Long %File Names. By default, -Long %File Names are enabled. For the leanest fastest library disable -Long %File Names. Long %File names require extra flash but no extra RAM. -Opening Long %File Names can be slower than opening Short %File Names. -Data read and write performance is not changed by the type of %File Name. - -If the symbol ENABLE_EXTENDED_TRANSFER_CLASS is nonzero, the class SdFatEX -will be defined. If the symbol ENABLE_SOFTWARE_SPI_CLASS is also nonzero, -the class SdFatSoftSpiEX will be defined. -These classes used extended multi-block SD I/O for better performance. -the SPI bus may not be shared with other devices in this mode. - -Set USE_STANDARD_SPI_LIBRARY and ENABLE_SOFTWARE_SPI_CLASS to -enable various SPI options. set USE_STANDARD_SPI_LIBRARY to use the standard -Arduino SPI library. set ENABLE_SOFTWARE_SPI_CLASS to enable the SdFatSoftSpi -class which uses software SPI. - -To enable SD card CRC checking set USE_SD_CRC nonzero. - -Set FAT12_SUPPORT nonzero to enable use of FAT12 volumes. -FAT12 has not been well tested and requires additional flash. - -\section SDPath Paths and Working Directories - -Relative paths in SdFat are resolved in a manner similar to Windows. - -Each instance of SdFat has a current directory. In SdFat this directory -is called the volume working directory, vwd. Initially this directory is -the root directory for the volume. - -The volume working directory is changed by calling SdFat::chdir(path). - -The call sd.chdir("/2014") will change the volume working directory -for sd to "/2014", assuming "/2014" exists. - -Relative paths for SdFat member functions are resolved by starting at -the volume working directory. - -For example, the call sd.mkdir("April") will create the directory -"/2014/April" assuming the volume working directory is "/2014". - -SdFat has a current working directory, cwd, that is used to resolve paths -for file.open() calls. - -For a single SD card the current working directory is always the volume -working directory for that card. - -For multiple SD cards the current working directory is set to the volume -working directory of a card by calling the SdFat::chvol() member function. -The chvol() call is like the Windows \: command. - -The call sd2.chvol() will set the current working directory to the volume -working directory for sd2. - -If the volume working directory for sd2 is "/music" the call - -file.open("BigBand.wav", O_READ); - -will then open "/music/BigBand.wav" on sd2. - -The following functions are used to change or get current directories. -See the html documentation for more information. -@code -bool SdFat::chdir(bool set_cwd = false); -bool SdFat::chdir(const char* path, bool set_cwd = false); -void SdFat::chvol(); -SdBaseFile* SdFat::vwd(); -static SdBaseFile* SdBaseFile::cwd(); -@endcode - -\section SDcard SD\SDHC Cards - -Arduinos access SD cards using the cards SPI protocol. PCs, Macs, and -most consumer devices use the 4-bit parallel SD protocol. A card that -functions well on A PC or Mac may not work well on the Arduino. - -Most cards have good SPI read performance but cards vary widely in SPI -write performance. Write performance is limited by how efficiently the -card manages internal erase/remapping operations. The Arduino cannot -optimize writes to reduce erase operations because of its limit RAM. - -SanDisk cards generally have good write performance. They seem to have -more internal RAM buffering than other cards and therefore can limit -the number of flash erase operations that the Arduino forces due to its -limited RAM. - -\section Hardware Hardware Configuration - -%SdFat was developed using an - Adafruit Industries -Data Logging Shield. - -The hardware interface to the SD card should not use a resistor based level -shifter. %SdFat sets the SPI bus frequency to 8 MHz which results in signal -rise times that are too slow for the edge detectors in many newer SD card -controllers when resistor voltage dividers are used. - -The 5 to 3.3 V level shifter for 5 V Arduinos should be IC based like the -74HC4050N based circuit shown in the file SdLevel.png. The Adafruit Wave Shield -uses a 74AHC125N. Gravitech sells SD and MicroSD Card Adapters based on the -74LCX245. - -If you are using a resistor based level shifter and are having problems try -setting the SPI bus frequency to 4 MHz. This can be done by using -card.init(SPI_HALF_SPEED) to initialize the SD card. - -A feature to use software SPI is available. Software SPI is slower -than hardware SPI but allows any digital pins to be used. See -SdFatConfig.h for software SPI definitions. - -\section comment Bugs and Comments - -If you wish to report bugs or have comments, send email to -fat16lib@sbcglobal.net. If possible, include a simple program that illustrates -the bug or problem. - -\section Trouble Troubleshooting - -The two example programs QuickStart, and SdInfo are useful for troubleshooting. - -A message like this from SdInfo with errorCode 0X1 indicates the SD card -is not seen by SdFat. This is often caused by a wiring error and reformatting -the card will not solve the problem. -
-cardBegin failed
-SD errorCode: 0X1
-SD errorData: 0XFF
-
-Here is a similar message from QuickStart: -
-SD initialization failed.
-Do not reformat the card!
-Is the card correctly inserted?
-Is chipSelect set to the correct value?
-Does another SPI device need to be disabled?
-Is there a wiring/soldering problem?
-
-errorCode: 0x1, errorData: 0xff
-
-Here is a message from QuickStart that indicates a formatting problem: -
-Card successfully initialized.
-Can't find a valid FAT16/FAT32 partition.
-Try reformatting the card.  For best results use
-the SdFormatter program in SdFat/examples or download
-and use SDFormatter from www.sdcard.org/downloads.
-
- -The best source of recent information and help is the Arduino forum. - -http://arduino.cc/forum/ - -Also search the Adafruit forum. - -http://forums.adafruit.com/ - -If you are using a Teensy try. - -http://forum.pjrc.com/forum.php - -\section SdFatClass SdFat Usage - -SdFat supports Long File Names. Long names in SdFat are limited to 7-bit -ASCII characters in the range 0X20 - 0XFE The following are reserved characters: -
    -
  • < (less than) -
  • > (greater than) -
  • : (colon) -
  • " (double quote) -
  • / (forward slash) -
  • \ (backslash) -
  • | (vertical bar or pipe) -
  • ? (question mark) -
  • * (asterisk) -
-%SdFat uses a slightly restricted form of short names. -Short names are limited to 8 characters followed by an optional period (.) -and extension of up to 3 characters. The characters may be any combination -of letters and digits. The following special characters are also allowed: - -$ % ' - _ @ ~ ` ! ( ) { } ^ # & - -Short names are always converted to upper case and their original case -value is lost. Files that have a base-name where all characters have the -same case and an extension where all characters have the same case will -display properly. Examples this type name are UPPER.low, lower.TXT, -UPPER.TXT, and lower.txt. - -An application which writes to a file using print(), println() or -write() must close the file or call sync() at the appropriate time to -force data and directory information to be written to the SD Card. - -Applications must use care calling sync() -since 2048 bytes of I/O is required to update file and -directory information. This includes writing the current data block, reading -the block that contains the directory entry for update, writing the directory -block back and reading back the current data block. - -It is possible to open a file with two or more instances of a file object. -A file may be corrupted if data is written to the file by more than one -instance of a file object. - -\section HowTo How to format SD Cards as FAT Volumes - -The best way to restore an SD card's format on a PC or Mac is to use -SDFormatter which can be downloaded from: - -http://www.sdcard.org/downloads - -A formatter program, SdFormatter.ino, is included in the -%SdFat/examples/SdFormatter directory. This program attempts to -emulate SD Association's SDFormatter. - -SDFormatter aligns flash erase boundaries with file -system structures which reduces write latency and file system overhead. - -The PC/Mac SDFormatter does not have an option for FAT type so it may format -very small cards as FAT12. Use the SdFat formatter to force FAT16 -formatting of small cards. - -Do not format the SD card with an OS utility, OS utilities do not format SD -cards in conformance with the SD standard. - -You should use a freshly formatted SD card for best performance. FAT -file systems become slower if many files have been created and deleted. -This is because the directory entry for a deleted file is marked as deleted, -but is not deleted. When a new file is created, these entries must be scanned -before creating the file. Also files can become -fragmented which causes reads and writes to be slower. - -\section ExampleFilder Examples - -A number of examples are provided in the SdFat/examples folder. -See the html documentation for a list. - -To access these examples from the Arduino development environment -go to: %File -> Examples -> %SdFat -> \ - -Compile, upload to your Arduino and click on Serial Monitor to run -the example. - -Here is a list: - -AnalogBinLogger - Fast AVR ADC logger - see the AnalogBinLoggerExtras folder. - -bench - A read/write benchmark. - -dataLogger - A simple modifiable data logger. - -DirectoryFunctions - Demo of chdir(), ls(), mkdir(), and rmdir(). - -fgets - Demo of the fgets read line/string function. - -formating - Print a table with various formatting options. - -getline - Example of getline from section 27.7.1.3 of the C++ standard. - -LongFileName - Example use of openNext, printName, and open by index. - -LowLatencyLogger - A data logger for higher data rates. ADC version. - -LowLatencyLoggerADXL345 - A data logger for higher data rates. ADXL345 SPI. - -LowLatencyLoggerMPU6050 - A data logger for higher data rates. MPU6050 I2C. - -OpenNext - Open all files in the root dir and print their filename. - -PrintBenchmark - A simple benchmark for printing to a text file. - -QuickStart - A program to quickly test your SD card and SD shield/module. - -RawWrite - A test of raw write functions for contiguous files. - -ReadCsv - Function to read a CSV text file one field at a time. - -ReadCsvStream - Read a comma-separated value file using iostream extractors. - -ReadCsvArray - Read a two dimensional array from a CSV file. - -ReadWrite - Compatibility test of Arduino SD ReadWrite example. - -rename - A demo of SdFat::rename(old, new) and SdFile::rename(dirFile, newPath). - -SdFormatter - This program will format an SD or SDHC card. - -SoftwareSpi - Simple demonstration of the SdFatSoftSpi template class. - -SdInfo - Initialize an SD card and analyze its structure for trouble shooting. - -StdioBench - Demo and test of stdio style stream. - -Timestamp - Sets file create, modify, and access timestamps. - -TwoCards - Example using two SD cards. - -VolumeFreeSpace - Demonstrate the freeClusterCount() call. - -wipe - Example to wipe all data from an already formatted SD. - */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/SdFatTestSuite.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/SdFatTestSuite.cpp deleted file mode 100644 index 8511b0f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/SdFatTestSuite.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright (c) 20011-2017 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#include -static uint16_t failCount; -static uint16_t testCount; -static Print* testOut = &Serial; -//------------------------------------------------------------------------------ -static size_t strlenPGM(PGM_P str) { - PGM_P end = str; - while (pgm_read_byte(end++)) {} - return end - str; -} -//------------------------------------------------------------------------------ -void testBegin() { - Serial.begin(9600); - while (!Serial) {} // wait for leonardo - testOut = &Serial; - Serial.println(F("Type any character to begin.")); - while (Serial.read() <= 0) {} - delay(200); // Catch Due reset problem - - testOut->print(F("FreeStack: ")); - testOut->println(FreeStack()); - testOut->println(); - failCount = 0; - testCount = 0; -} -//------------------------------------------------------------------------------ -void testEnd() { - testOut->println(); - testOut->println(F("Compiled: " __DATE__ " " __TIME__)); - testOut->print(F("FreeStack: ")); - testOut->println(FreeStack()); - testOut->print(F("Test count: ")); - testOut->println(testCount); - testOut->print(F("Fail count: ")); - testOut->println(failCount); -} -//------------------------------------------------------------------------------ -static void testResult(bool b, uint8_t n) { - while (n++ < 60) testOut->write(' '); - if (b) { - testOut->println(F("..ok")); - } else { - testOut->println(F("FAIL")); - failCount++; - } - testCount++; -} -//------------------------------------------------------------------------------ -void testVerify_P(char* result, PGM_P expect) { - testOut->write('"'); - testOut->print(result); - testOut->print("\",\""); - testOut->print((const __FlashStringHelper*)expect); - testOut->write('"'); - uint8_t n = strlen(result) + strlenPGM(expect) + 5; - testResult(!strcmp_P(result, expect), n); -} -//------------------------------------------------------------------------------ -void testVerify_P(bool b, PGM_P msg) { - testOut->print((const __FlashStringHelper*)msg); - uint8_t n = strlenPGM(msg); - testResult(b, n); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/SdFatTestSuite.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/SdFatTestSuite.h deleted file mode 100644 index 4d096d9..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/SdFatTestSuite.h +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 20011-2017 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 SdFatTestSuite_h -#define SdFatTestSuite_h -#include "SdFat.h" -#include "FreeStack.h" - -#if defined(__arm__) && !defined(strcmp_P) -#define strcmp_P(a, b) strcmp((a), (b)) -#endif // strcmp_P - -#if defined(__arm__) && !defined(strncpy_P) -#define strncpy_P(s, t, n) strncpy(s, t, n) -#endif // strncpy_P - -#if defined(__arm__) && !defined(strlen_P) -#define strlen_P(str) strlen(str) -#endif // strlen_P - -#define testVerifyBool(result) testVerify_P(result, PSTR(#result)) -#define testVerifyMsg(result, msg) testVerify_P(result, PSTR(msg)) -#define testVerifyStr(result, expect) testVerify_P(result, PSTR(expect)) - -void testBegin(); -void testEnd(); -void testVerify_P(bool b, PGM_P msg); -void testVerify_P(char* result, PGM_P expect); -#endif // SdFatTestSuite_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_File/ATS_SD_File.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_File/ATS_SD_File.ino deleted file mode 100644 index 2fc6be7..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_File/ATS_SD_File.ino +++ /dev/null @@ -1,105 +0,0 @@ -// modified from ArduinoTestSuite 0022 by William Greiman -// Tests writing to and reading from a file, in particular the -// the Stream implementation (e.g. read() and peek()). - -#include -#include -#include -SdFat SD; -#define ATS_PrintTestStatus(msg, b) testVerify_P(b, PSTR(msg)) -void setup() { - boolean b; - SdFile f; - uint32_t fs; - - testBegin(); - - ATS_PrintTestStatus("SD.begin()", b = SD.begin()); - if (!b) goto done; - - SD.remove("test.txt"); - - f.open("test.txt", FILE_WRITE); - ATS_PrintTestStatus("SD.open()", f.isOpen()); - if (!f.isOpen()) goto done; - - f.print("abc"); - f.print("de"); - f.close(); - - f.open("test.txt", FILE_WRITE); - ATS_PrintTestStatus("SD.open()", f.isOpen()); - if (!f.isOpen()) goto done; - - f.print("fgh"); - f.close(); - - f.open("test.txt", O_READ); - ATS_PrintTestStatus("SD.open()", f.isOpen()); - if (!f.isOpen()) goto done; - fs =f.fileSize(); - ATS_PrintTestStatus("read()", f.read() == 'a'); - ATS_PrintTestStatus("peek()", f.peek() == 'b'); - ATS_PrintTestStatus("read()", f.read() == 'b'); - ATS_PrintTestStatus("read()", f.read() == 'c'); - ATS_PrintTestStatus("peek()", f.peek() == 'd'); - ATS_PrintTestStatus("peek()", f.peek() == 'd'); - ATS_PrintTestStatus("peek()", f.peek() == 'd'); - ATS_PrintTestStatus("peek()", f.peek() == 'd'); - ATS_PrintTestStatus("read()", f.read() == 'd'); - ATS_PrintTestStatus("available()", f.curPosition() != fs); - ATS_PrintTestStatus("read()", f.read() == 'e'); - ATS_PrintTestStatus("available()", f.curPosition() != fs); - ATS_PrintTestStatus("peek()", f.peek() == 'f'); - ATS_PrintTestStatus("read()", f.read() == 'f'); - ATS_PrintTestStatus("peek()", f.peek() == 'g'); - ATS_PrintTestStatus("available()", f.curPosition() != fs); - ATS_PrintTestStatus("peek()", f.peek() == 'g'); - ATS_PrintTestStatus("read()", f.read() == 'g'); - ATS_PrintTestStatus("available()", f.curPosition() != fs); - ATS_PrintTestStatus("available()", f.curPosition() != fs); - ATS_PrintTestStatus("available()", f.curPosition() != fs); - ATS_PrintTestStatus("peek()", f.peek() == 'h'); - ATS_PrintTestStatus("read()", f.read() == 'h'); - ATS_PrintTestStatus("available()", f.curPosition() == fs); - ATS_PrintTestStatus("peek()", f.peek() == -1); - ATS_PrintTestStatus("read()", f.read() == -1); - ATS_PrintTestStatus("peek()", f.peek() == -1); - ATS_PrintTestStatus("read()", f.read() == -1); - - f.close(); - - SD.remove("test2.txt"); - - f.open("test2.txt", FILE_WRITE); - ATS_PrintTestStatus("SD.open()", f.isOpen()); - if (!f.isOpen()) goto done; - - f.print("ABC"); - f.close(); - - f.open("test.txt", O_READ); - ATS_PrintTestStatus("SD.open()", f.isOpen()); - if (!f.isOpen()) goto done; - - ATS_PrintTestStatus("peek()", f.peek() == 'a'); - - f.close(); - - f.open("test2.txt", O_READ); - ATS_PrintTestStatus("SD.open()", f.isOpen()); - if (!f.isOpen()) goto done; - - ATS_PrintTestStatus("peek()", f.peek() == 'A'); - ATS_PrintTestStatus("read()", f.read() == 'A'); - - f.close(); - -done: - testEnd(); - -} - -void loop() {} - - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_Files/ATS_SD_Files.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_Files/ATS_SD_Files.ino deleted file mode 100644 index aa04c84..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_Files/ATS_SD_Files.ino +++ /dev/null @@ -1,75 +0,0 @@ -// modified from ArduinoTestSuite 0022 by William Greiman -#include -#include -#include -SdFat SD; -#define ATS_PrintTestStatus(msg, b) testVerify_P(b, PSTR(msg)) - -void setup() { - boolean b; - SdFile f; - - testBegin(); - - ATS_PrintTestStatus("SD.begin()", b = SD.begin()); - if (!b) goto done; - - ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf.txt")); - ATS_PrintTestStatus("SD.open()", f.open("asdf.txt", FILE_WRITE)); f.close(); - ATS_PrintTestStatus("SD.exists()", SD.exists("asdf.txt")); - ATS_PrintTestStatus("SD.exists()", SD.exists("/asdf.txt")); - ATS_PrintTestStatus("SD.remove()", SD.remove("asdf.txt")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf.txt")); - - ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf")); - ATS_PrintTestStatus("SD.mkdir()", SD.mkdir("asdf")); - ATS_PrintTestStatus("SD.exists()", SD.exists("asdf")); - ATS_PrintTestStatus("SD.exists()", SD.exists("/asdf")); - ATS_PrintTestStatus("SD.exists()", SD.exists("asdf/")); - ATS_PrintTestStatus("SD.rmdir()", SD.rmdir("asdf")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf")); - - ATS_PrintTestStatus("SD.mkdir()", SD.mkdir("x/y/z")); - ATS_PrintTestStatus("SD.exists()", SD.exists("x")); - ATS_PrintTestStatus("SD.exists()", SD.exists("x/")); - ATS_PrintTestStatus("SD.exists()", SD.exists("x/y")); - ATS_PrintTestStatus("SD.exists()", SD.exists("x/y/")); - ATS_PrintTestStatus("SD.exists()", SD.exists("x/y/z")); - ATS_PrintTestStatus("SD.exists()", SD.exists("x/y/z/")); - ATS_PrintTestStatus("SD.exists()", SD.exists("/x/y/z/")); - ATS_PrintTestStatus("SD.rmdir()", SD.rmdir("x/y/z")); - ATS_PrintTestStatus("SD.exists()", SD.exists("x")); - ATS_PrintTestStatus("SD.exists()", SD.exists("x/y")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("x/y/z")); - ATS_PrintTestStatus("SD.rmdir()", SD.rmdir("x/y/")); - ATS_PrintTestStatus("SD.exists()", SD.exists("x")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("x/y")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("x/y/z")); - ATS_PrintTestStatus("SD.rmdir()", SD.rmdir("/x")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("x")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("x/y")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("x/y/z")); - - ATS_PrintTestStatus("!SD.open()", !(f.open("asdf/asdf.txt", FILE_WRITE))); f.close(); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf.txt")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf/asdf.txt")); - ATS_PrintTestStatus("SD.mkdir()", SD.mkdir("asdf")); - ATS_PrintTestStatus("SD.exists()", SD.exists("asdf")); - ATS_PrintTestStatus("SD.open()", f.open("asdf/asdf.txt", FILE_WRITE)); f.close(); - ATS_PrintTestStatus("SD.exists()", SD.exists("asdf/asdf.txt")); - ATS_PrintTestStatus("!SD.rmdir()", !SD.rmdir("asdf")); - ATS_PrintTestStatus("SD.exists()", SD.exists("asdf")); - ATS_PrintTestStatus("SD.exists()", SD.exists("asdf/asdf.txt")); - ATS_PrintTestStatus("SD.remove()", SD.remove("asdf/asdf.txt")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf/asdf.txt")); - ATS_PrintTestStatus("SD.exists()", SD.exists("asdf")); - ATS_PrintTestStatus("SD.rmdir()", SD.rmdir("asdf")); - ATS_PrintTestStatus("!SD.exists()", !SD.exists("asdf")); - -done: - - testEnd(); - -} -void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_Seek/ATS_SD_Seek.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_Seek/ATS_SD_Seek.ino deleted file mode 100644 index 2f20f7d..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/ATS_SD_Seek/ATS_SD_Seek.ino +++ /dev/null @@ -1,108 +0,0 @@ -// modified from ArduinoTestSuite 0022 by William Greiman -// Tests writing to and reading from a file, in particular the -// the Stream implementation (e.g. read() and peek()). -#include -#include -#include -SdFat SD; -#define ATS_PrintTestStatus(msg, b) testVerify_P(b, PSTR(msg)) - -void setup() { - boolean b; - SdFile f; - - testBegin(); - - ATS_PrintTestStatus("SD.begin()", b = SD.begin()); - if (!b) goto done; - - SD.remove("test.txt"); - - f.open("test.txt", FILE_WRITE); - ATS_PrintTestStatus("SD.open()", f.isOpen()); - if (!f.isOpen()) goto done; - - ATS_PrintTestStatus("initial position", f.curPosition() == 0); - ATS_PrintTestStatus("initial size", f.fileSize() == 0); - - f.print("0123456789"); - - ATS_PrintTestStatus("position after writing", f.curPosition() == 10); - ATS_PrintTestStatus("size after writing", f.fileSize() == 10); - - f.seekSet(0); - - ATS_PrintTestStatus("size after seek", f.fileSize() == 10); - ATS_PrintTestStatus("position after seek", f.curPosition() == 0); - - f.seekSet(7); - - ATS_PrintTestStatus("position after seek", f.curPosition() == 7); - ATS_PrintTestStatus("reading after seek", f.read() == '7'); - ATS_PrintTestStatus("position after reading after seeking", f.curPosition() == 8); - ATS_PrintTestStatus("reading after reading after seeking", f.read() == '8'); - - f.seekSet(3); - - ATS_PrintTestStatus("position after seeking", f.curPosition() == 3); - ATS_PrintTestStatus("peeking after seeking", f.peek() == '3'); - ATS_PrintTestStatus("position after peeking after seeking", f.curPosition() == 3); - ATS_PrintTestStatus("peeking after peeking after seeking", f.peek() == '3'); - ATS_PrintTestStatus("position after peeking after seeking", f.curPosition() == 3); - ATS_PrintTestStatus("peeking after peeking after seeking", f.read() == '3'); - ATS_PrintTestStatus("position after peeking after seeking", f.curPosition() == 4); - - f.seekSet(1); - - ATS_PrintTestStatus("position after seeking", f.curPosition() == 1); - ATS_PrintTestStatus("peeking after seeking", f.peek() == '1'); - - f.seekSet(4); - - ATS_PrintTestStatus("position after seeking", f.curPosition() == 4); - ATS_PrintTestStatus("peeking after seeking", f.peek() == '4'); - - f.seekSet(7); - - ATS_PrintTestStatus("position()", f.curPosition() == 7); - ATS_PrintTestStatus("read()", f.read() == '7'); - - f.seekSet(0); - f.peek(); - f.print("AB"); - - ATS_PrintTestStatus("position()", f.curPosition() == 2); - ATS_PrintTestStatus("size()", f.fileSize() == 10); - ATS_PrintTestStatus("read()", f.read() == '2'); - - f.seekSet(0); - - ATS_PrintTestStatus("read()", f.read() == 'A'); - ATS_PrintTestStatus("read()", f.read() == 'B'); - ATS_PrintTestStatus("read()", f.read() == '2'); - - f.close(); - - f.open("test.txt", O_READ); - ATS_PrintTestStatus("SD.open()", f.isOpen()); - if (!f.isOpen()) goto done; - - ATS_PrintTestStatus("position()", f.curPosition() == 0); - ATS_PrintTestStatus("size()", f.fileSize() == 10); - ATS_PrintTestStatus("peek()", f.peek() == 'A'); - ATS_PrintTestStatus("read()", f.read() == 'A'); - - f.seekSet(4); - - ATS_PrintTestStatus("position()", f.curPosition() == 4); - ATS_PrintTestStatus("size()", f.fileSize() == 10); - ATS_PrintTestStatus("peek()", f.peek() == '4'); - ATS_PrintTestStatus("read()", f.read() == '4'); - - f.close(); - -done: - testEnd(); -} - -void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/StressTest/StressTest.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/StressTest/StressTest.ino deleted file mode 100644 index a990925..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/StressTest/StressTest.ino +++ /dev/null @@ -1,76 +0,0 @@ -// This stress test will create and write files until the SD is full. -#include -#include - -// SD chip select pin. -const uint8_t SD_CS_PIN = SS; - -// Set write buffer size. -#ifdef __arm__ -#ifndef CORE_TEENSY -// Due -const size_t BUF_SIZE = 32768; -#else // CORE_TEENSY -// Teensy 3.0 -const size_t BUF_SIZE = 8192; -#endif // CORE_TEENSY -#elif defined(RAMEND) && RAMEND > 5000 -// AVR with more than 4 KB RAM -const size_t BUF_SIZE = 4096; -#else // __arm__ -// other -const size_t BUF_SIZE = 512; -#endif // __arm__ - -const size_t FILE_SIZE_KB = 10240; -const uint16_t BUFS_PER_FILE = (1024L*FILE_SIZE_KB/BUF_SIZE); - -SdFat sd; - -SdFile file; - -uint8_t buf[BUF_SIZE]; -char name[13]; -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - Serial.print("BUF_SIZE "); - Serial.println(BUF_SIZE); - Serial.println("Type any character to start"); - while (Serial.read() < 0) {} - - if (!sd.begin(SD_CS_PIN))sd.errorHalt("sd.begin"); - - // Fill buf with known value. - for (size_t i = 0; i < BUF_SIZE; i++) buf[i] = i; - - // Wait to begin. - do {delay(10);} while (Serial.read() >= 0); - Serial.println("Type any character to stop after next file"); -} -//------------------------------------------------------------------------------ -void loop() { - // Free KB on SD. - uint32_t freeKB = sd.vol()->freeClusterCount()*sd.vol()->blocksPerCluster()/2; - - Serial.print("Free KB: "); - Serial.println(freeKB); - if (freeKB < 2*FILE_SIZE_KB) { - Serial.println(" Done!"); - while(1); - } - sprintf(name, "%lu.DAT", freeKB); - if (!file.open(name, O_WRITE | O_CREAT | O_TRUNC)) { - sd.errorHalt("Open error!"); - } - for (uint16_t i = 0; i < BUFS_PER_FILE; i++) { - if (file.write(buf, BUF_SIZE) != BUF_SIZE) { - sd.errorHalt("Write error!"); - } - } - file.close(); - if (Serial.available()) { - Serial.println("Stopped!"); - while(1); - } -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/TestMkdir/TestMkdir.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/TestMkdir/TestMkdir.ino deleted file mode 100644 index 3fa9434..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/TestMkdir/TestMkdir.ino +++ /dev/null @@ -1,138 +0,0 @@ -/* - * This sketch is a test of subdirectory and file creation. - * It also tests allocation of clusters to directories. - * - * It will create two subdirectories and create enough files - * to force the allocation of a cluster to each directory. - * - * More than 3000 files may be created on a FAT32 volume. - * - * Note: Some cards may 'stutter' others just get slow due - * to the number of flash erases this program causes. - */ -#include -#include -#include - -const uint8_t SD_CHIP_SELECT = SS; - -SdFat sd; - -// store error strings in flash to save RAM -#define error(s) sd.errorHalt(F(s)) - -/* - * create enough files to force a cluster to be allocated to dir. - */ -void dirAllocTest(FatFile* dir) { - char buf[32], name[32]; - SdFile file; - uint16_t n; - uint32_t size = dir->dirSize(); - - // create files and write name to file - for (n = 0; ; n++){ - // make file name - sprintf(name, "%u.TXT", n); - - // open start time - uint32_t t0 = millis(); - if (!file.open(dir, name, O_WRITE | O_CREAT | O_EXCL)) { - error("open for write failed"); - } - - // open end time and write start time - uint32_t t1 = millis(); - // write file name to file - file.print(name); - if (!file.close()) error("close write"); - - // write end time - uint32_t t2 = millis(); - Serial.print(F("WR ")); - Serial.print(n); - Serial.write(' '); - - // print time to create file - Serial.print(t1 - t0); - Serial.write(' '); - - // print time to write file - Serial.println(t2 - t1); - - // directory size will change when a cluster is added - if (dir->curPosition() > size) break; - } - - // read files and check content - for (uint16_t i = 0; i <= n; i++) { - sprintf(name, "%u.TXT", i); - - // open start time - uint32_t t0 = millis(); - if (!file.open(dir, name, O_READ)) { - error("open for read failed"); - } - - // open end time and read start time - uint32_t t1 = millis(); - int16_t nr = file.read(buf, sizeof(buf)); - if (nr < 5) error("file.read failed"); - - // read end time - uint32_t t2 = millis(); - - // check file content - if (strlen(name) != (size_t)nr || strncmp(name, buf, nr)) { - error("content compare failed"); - } - if (!file.close()) error("close read failed"); - - Serial.print(F("RD ")); - Serial.print(i); - Serial.write(' '); - - // print open time - Serial.print(t1 - t0); - Serial.write(' '); - - // print read time - Serial.println(t2 - t1); - } -} - -void setup() { - Serial.begin(9600); - while (!Serial) {} // wait for Leonardo - Serial.println(F("Type any character to start")); - while (Serial.read() <= 0) {} - delay(200); // Catch Due reset problem - - // initialize the SD card at SPI_FULL_SPEED for best performance. - // try SPI_HALF_SPEED if bus errors occur. - if (!sd.begin(SD_CHIP_SELECT, SPI_FULL_SPEED)) sd.initErrorHalt(); - - uint32_t m = millis(); - // write files to root if FAT32 - if (sd.vol()->fatType() == 32) { - Serial.println(F("Writing files to root")); - dirAllocTest(sd.vwd()); - } - - // create sub1 and write files - SdFile sub1; - if (!sub1.mkdir(sd.vwd(), "SUB1")) error("makdeDir SUB1 failed"); - Serial.println(F("Writing files to SUB1")); - dirAllocTest(&sub1); - - // create sub2 and write files - SdFile sub2; - if (!sub2.mkdir(&sub1, "SUB2")) error("mkdir SUB2 failed"); - Serial.println(F("Writing files to SUB2")); - dirAllocTest(&sub2); - m = millis() - m; - Serial.print(F("Done millis: ")); - Serial.println(m); -} - -void loop() { } \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/TestRmdir/TestRmdir.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/TestRmdir/TestRmdir.ino deleted file mode 100644 index 41ce89d..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/TestRmdir/TestRmdir.ino +++ /dev/null @@ -1,98 +0,0 @@ -/* - * This sketch will remove the files and directories - * created by the SdFatMakeDir.pde sketch. - * - * Performance is erratic due to the large number - * of flash erase operations caused by many random - * writes to file structures. - */ -#include -#include -#include - -const uint8_t SD_CHIP_SELECT = SS; - -SdFat sd; - -// store error strings in flash to save RAM -#define error(s) sd.errorHalt(F(s)) - -/* - * remove all files in dir. - */ -void deleteFiles(FatFile* dir) { - char name[32]; - SdFile file; - - // open and delete files - for (uint16_t n = 0; ; n++){ - sprintf(name, "%u.TXT", n); - - // open start time - uint32_t t0 = millis(); - - // assume done if open fails - if (!file.open(dir, name, O_WRITE)) return; - - // open end time and remove start time - uint32_t t1 = millis(); - if (!file.remove()) error("file.remove failed"); - - // remove end time - uint32_t t2 = millis(); - - Serial.print(F("RM ")); - Serial.print(n); - Serial.write(' '); - - // open time - Serial.print(t1 - t0); - Serial.write(' '); - - // remove time - Serial.println(t2 - t1); - } -} - -void setup() { - Serial.begin(9600); - while (!Serial) {} // wait for Leonardo - Serial.println(F("Type any character to start")); - while (Serial.read() <= 0) {} - delay(200); // Catch Due reset problem - - // initialize the SD card at SPI_FULL_SPEED for best performance. - // try SPI_HALF_SPEED if bus errors occur. - if (!sd.begin(SD_CHIP_SELECT, SPI_FULL_SPEED)) sd.initErrorHalt(); - - - // delete files in root if FAT32 - if (sd.vol()->fatType() == 32) { - Serial.println(F("Remove files in root")); - deleteFiles(sd.vwd()); - } - - // open SUB1 and delete files - SdFile sub1; - if (!sub1.open("SUB1", O_READ)) error("open SUB1 failed"); - Serial.println(F("Remove files in SUB1")); - deleteFiles(&sub1); - - // open SUB2 and delete files - SdFile sub2; - if (!sub2.open(&sub1, "SUB2", O_READ)) error("open SUB2 failed"); - Serial.println(F("Remove files in SUB2")); - deleteFiles(&sub2); - - // remove SUB2 - if (!sub2.rmdir()) error("sub2.rmdir failed"); - Serial.println(F("SUB2 removed")); - - // remove SUB1 - if (!sub1.rmdir()) error("sub1.rmdir failed"); - Serial.println(F("SUB1 removed")); - - Serial.println(F("Done")); -} - -void loop() { } diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/fstreamTest/fstreamTest.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/fstreamTest/fstreamTest.ino deleted file mode 100644 index 2bd9bd5..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/fstreamTest/fstreamTest.ino +++ /dev/null @@ -1,94 +0,0 @@ -#include -#include -#include -SdFat sd; -const char *testName = "SDFAT.TST"; -//------------------------------------------------------------------------------ -void fstreamOpen() { - ios::openmode nocreate[] = {ios::in, ios::in | ios::out}; - ios::openmode create[] = - {ios::out, ios::out | ios::app, ios::app, ios::out | ios::trunc, - ios::in | ios::out | ios::trunc, ios::in | ios::out | ios::app, - ios::in | ios::app}; - ios::openmode illegal[] = - {0, ios::trunc, ios::app | ios::trunc, ios::in | ios::app | ios::trunc, - ios::in | ios::trunc, ios::out | ios::app | ios::trunc, - ios::in | ios::out | ios::app | ios::trunc}; - - sd.remove(testName); - fstream file(testName); - testVerifyMsg(!file.is_open()&& !sd.exists(testName), "fstream constructor"); - - for (uint8_t i = 0 ; i < sizeof(nocreate)/sizeof(nocreate[1]); i++) { - file.close(); - sd.remove(testName); - file.open(testName, nocreate[i]); - testVerifyMsg(!sd.exists(testName) && !file.is_open(), "fstream nocreate !exists"); - } - for (uint8_t i = 0 ; i < sizeof(create)/sizeof(create[1]); i++) { - file.close(); - sd.remove(testName); - file.open(testName, create[i]); - testVerifyMsg(sd.exists(testName) && file.is_open(), "fstream create openmode"); - } - for (uint8_t i = 0 ; i < sizeof(illegal)/sizeof(illegal[1]); i++) { - file.close(); - file.open(testName, illegal[i]); - testVerifyMsg(sd.exists(testName) && !file.is_open(), "fstream illegal openmode"); - } - for (uint8_t i = 0 ; i < sizeof(nocreate)/sizeof(nocreate[1]); i++) { - file.close(); - file.open(testName, nocreate[i]); - testVerifyMsg(sd.exists(testName) && file.is_open(), "fstream nocreate exists"); - } -} -//------------------------------------------------------------------------------ -void testPosition() { - sd.remove(testName); - ofstream ofs(testName); - testVerifyBool(ofs.good() && ofs.tellp() == 0); - ofs.seekp(0, ios::end); - testVerifyBool(ofs.good() && ofs.tellp() == 0); - ofs << "abcde"; - testVerifyBool(ofs.good() && ofs.tellp() == 5); - ofs.seekp(4); - testVerifyBool(ofs.good() && ofs.tellp() == 4); - ofs.seekp(-1, ios::cur); - testVerifyBool(ofs.good() && ofs.tellp() == 3); - ofs.close(); - ifstream ifs(testName, ios::ate); - testVerifyBool(ifs.good() && ifs.tellg() == 5); - ifs.seekg(0); - testVerifyBool(ifs.get() == 'a' && ifs.get() == 'b'); - testVerifyBool(ifs.tellg() == 2 && ifs.good()); - ifs.seekg(3, ios::cur); - testVerifyBool(ifs.tellg() == 5 && ifs.good()); - ifs.seekg(4, ios::beg); - testVerifyBool(ifs.good() && ifs.tellg() == 4); - ifs.close(); - ofs.open(testName, ios::app); - testVerifyBool(ofs.good() && ofs.tellp() == 0); - ofs << 'f'; - testVerifyBool(ofs.good() && ofs.tellp() == 6); - ofs.close(); - ofs.open(testName, ios::trunc); - ofs.seekp(0, ios::end); - testVerifyBool(ofs.good() && ofs.tellp() == 0); - ofs << "ABCDEF"; - ofs.close(); - fstream fs(testName); - testVerifyBool(fs.good() && fs.tellp() == 0 && fs.tellg() == 0); - fs.seekg(2); - testVerifyBool(fs.good() && fs.get() == 'C'); -} -//------------------------------------------------------------------------------ -void setup() { - - testBegin(); - if (!sd.begin()) sd.initErrorHalt(); - fstreamOpen(); - testPosition(); - testEnd(); -} -//------------------------------------------------------------------------------ -void loop() {} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/istreamTest/istreamTest.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/istreamTest/istreamTest.ino deleted file mode 100644 index 15d33fb..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/istreamTest/istreamTest.ino +++ /dev/null @@ -1,261 +0,0 @@ -#include -#include -#include - -char buf[100]; -ibufstream ib; -#define ibInit(s) ibInit_P(PSTR(s)) - -//---------------------------------------------------------- -void ibInit_P(PGM_P p) { - if (strlen_P(p) >= sizeof(buf)) { - ib.init(""); - ib.setstate(ios::badbit); - } else { - ib.clear(); - strncpy_P(buf, p, sizeof(buf)); - ib.init(buf); - } -} -//------------------------------------------------------------------------------ -void istreamBool() { - bool b; - ibInit(" 0 1 2"); - testVerifyBool((ib >> b) && !b); - testVerifyBool((ib >> b) && b); - testVerifyBool(!(ib >> b) && !ib.good()); - - ibInit(" true false err"); - testVerifyBool((ib >> boolalpha >> b) && b && ib.good()); - testVerifyBool((ib >> b) && !b && ib.good()); - testVerifyBool(!(ib >> b) && ib.fail()); - - ibInit("1"); - testVerifyBool((ib >> noboolalpha >> b) && b && ib.eof()); -} -//------------------------------------------------------------------------------ -void istreamChar() { - char c; - signed char sc; - unsigned char uc; - - ibInit("c s u g"); - testVerifyBool((ib >> c) && ib.good() && c == 'c'); - testVerifyBool((ib >> sc) && ib.good() && sc == 's'); - testVerifyBool((ib >> uc) && ib.good() && uc == 'u'); - testVerifyBool(ib.get() == ' '); - testVerifyBool(ib.peek() == 'g' && ib.good()); - testVerifyBool(ib.get() == 'g' && ib.good()); - testVerifyBool(ib.get() == -1 && ib.eof()); -} -//------------------------------------------------------------------------------ -void istreamDouble() { - double f; - ibInit("0 .1 1. 2 3.4 .1e5 1e5 -1E6 +2.3e-3 -123.4567"); - testVerifyBool((ib >> f) && f == 0 && ib.good()); - testVerifyBool((ib >> f) && f == 0.1 && ib.good()); - testVerifyBool((ib >> f) && f == 1.0 && ib.good()); - testVerifyBool((ib >> f) && f == 2.0 && ib.good()); - testVerifyBool((ib >> f) && f == 3.4 && ib.good()); - testVerifyBool((ib >> f) && f == 10000.0 && ib.good()); - testVerifyBool((ib >> f) && f == 1e5 && ib.good()); - testVerifyBool((ib >> f) && f == -1E6 && ib.good()); - testVerifyBool((ib >> f) && f == 2.3e-3 && ib.good()); - testVerifyBool((ib >> f) && fabs(f + 123.4567) < 1e-5 && ib.eof()); - if (fabs(f + 123.4567) >= 1e-5) Serial.println(f, 8); -} -//------------------------------------------------------------------------------ -void istreamFloat() { - float f; - ibInit("0 .1 1. 2 3.4 .1e5 1e5 -1E6 +2.3e-3 -123.4567"); - testVerifyBool((ib >> f) && f == 0 && ib.good()); - testVerifyBool((ib >> f) && f == 0.1f && ib.good()); - testVerifyBool((ib >> f) && f == 1.0 && ib.good()); - testVerifyBool((ib >> f) && f == 2.0 && ib.good()); - testVerifyBool((ib >> f) && f == 3.4f && ib.good()); - testVerifyBool((ib >> f) && f == 10000.0 && ib.good()); - testVerifyBool((ib >> f) && f == 1e5 && ib.good()); - testVerifyBool((ib >> f) && f == -1E6 && ib.good()); - testVerifyBool((ib >> f) && f == 2.3e-3f && ib.good()); - testVerifyBool((ib >> f) && fabs(f + 123.4567f) < 1e-5 && ib.eof()); - if (fabs(f + 123.4567) >= 1e-5) Serial.println(f, 8); -} -//------------------------------------------------------------------------------ -void istreamGet() { - char s[4]; - ibInit("ab c"); - testVerifyBool(ib.get() == 'a' && ib.good() && ib.gcount() == 1); - testVerifyBool(ib.get() == 'b' && ib.good() && ib.gcount() == 1); - testVerifyBool(ib.get() == ' ' && ib.good() && ib.gcount() == 1); - testVerifyBool(ib.get() == 'c' && ib.good() && ib.gcount() == 1); - testVerifyBool(ib.get() == -1 && ib.eof() && ib.gcount() == 0); - - ibInit("ab\ncdef"); - ib.get(s, sizeof(s)); - testVerifyBool(ib.good() && ib.gcount() == 2); - testVerifyStr(s, "ab"); - testVerifyBool(ib.get() == '\n' && ib.good() && ib.gcount() == 1); - ib.get(s, sizeof(s)); - testVerifyBool(ib.good() && ib.gcount() == 3); - testVerifyStr(s, "cde"); - ib.get(s, sizeof(s)); - testVerifyBool(ib.eof() && ib.gcount() == 1); - testVerifyStr(s, "f"); - - ibInit( - "short line\n" - "\n" - "17 character line\n" - "too long for buffer\n" - "line with no nl" - ); - char buf[18]; - ib.getline(buf, sizeof(buf)); - testVerifyBool(ib.good() && ib.gcount() == 11); - testVerifyStr(buf, "short line"); - ib.getline(buf, sizeof(buf)); - testVerifyBool(ib.good() && ib.gcount() == 1 && buf[0] == '\0'); - ib.getline(buf, sizeof(buf)); - testVerifyBool(ib.good() && ib.gcount() == 18); - testVerifyStr(buf, "17 character line"); - ib.getline(buf, sizeof(buf)); - testVerifyBool(ib.fail() && !ib.eof() && ib.gcount() == 17); - testVerifyStr(buf, "too long for buff"); - ib.clear(); - ib.getline(buf, sizeof(buf)); - testVerifyBool(ib.good() && !ib.eof() && ib.gcount() == 3); - testVerifyStr(buf, "er"); - ib.getline(buf, sizeof(buf)); - testVerifyBool(!ib.fail() && ib.eof() && ib.gcount() == 15); - testVerifyStr(buf, "line with no nl"); -} -//------------------------------------------------------------------------------ -void istreamNumber() { - short s; - signed short ss; - unsigned short us; - int i; - signed int si; - unsigned int ui; - long l; - signed long sl; - unsigned long ul; - - ibInit("-32769"); - testVerifyBool(!(ib >> s) && ib.fail()); - ibInit("-32768 0 32767 32768"); - testVerifyBool((ib >> s) && s == -32768 && ib.good()); - testVerifyBool((ib >> s) && s == 0 && ib.good()); - testVerifyBool((ib >> s) && s == 32767 && ib.good()); - testVerifyBool(!(ib >> s) && ib.fail()); - - ibInit("-32769"); - testVerifyBool(!(ib >> ss) && ib.fail()); - ibInit("-32768 0 32767 32768"); - testVerifyBool((ib >> ss) && ss == -32768 && ib.good()); - testVerifyBool((ib >> ss) && ss == 0 && ib.good()); - testVerifyBool((ib >> ss) && ss == 32767 && ib.good()); - testVerifyBool(!(ib >> ss) && ib.fail()); - - ibInit("0 65535 65536"); - testVerifyBool((ib >> us) && us == 0 && ib.good()); - testVerifyBool((ib >> us) && us == 65535 && ib.good()); - testVerifyBool(!(ib >> us) && ib.fail()); - -if (sizeof(int) == 2) { - ibInit("-32769"); - testVerifyBool(!(ib >> i) && ib.fail()); - ibInit("-32768 0 32767 32768"); - testVerifyBool((ib >> i) && i == -32768 && ib.good()); - testVerifyBool((ib >> i) && i == 0 && ib.good()); - testVerifyBool((ib >> i) && i == 32767 && ib.good()); - testVerifyBool(!(ib >> i) && ib.fail()); - - ibInit("-32769"); - testVerifyBool(!(ib >> si) && ib.fail()); - ibInit("-32768 0 32767 32768"); - testVerifyBool((ib >> si) && si == -32768 && ib.good()); - testVerifyBool((ib >> si) && si == 0 && ib.good()); - testVerifyBool((ib >> si) && si == 32767 && ib.good()); - testVerifyBool(!(ib >> si) && ib.fail()); - - ibInit("0 65535 65536"); - testVerifyBool((ib >> ui) && ui == 0 && ib.good()); - testVerifyBool((ib >> ui) && ui == 65535 && ib.good()); - testVerifyBool(!(ib >> ui) && ib.fail()); - } else { - ibInit("-2147483649"); - testVerifyBool(!(ib >> i) && ib.fail()); - ibInit("-2147483648 0 2147483647 2147483648"); - testVerifyBool((ib >> i) && i == -2147483648 && ib.good()); - testVerifyBool((ib >> i) && i == 0 && ib.good()); - testVerifyBool((ib >> i) && i == 2147483647 && ib.good()); - testVerifyBool(!(ib >> i) && ib.fail()); - - ibInit("-2147483649"); - testVerifyBool(!(ib >> si) && ib.fail()); - ibInit("-2147483648 0 2147483647 2147483648"); - testVerifyBool((ib >> si) && si == -2147483648 && ib.good()); - testVerifyBool((ib >> si) && si == 0 && ib.good()); - testVerifyBool((ib >> si) && si == 2147483647 && ib.good()); - testVerifyBool(!(ib >> si) && ib.fail()); - - ibInit("0 4294967295 4294967296"); - testVerifyBool((ib >> ui) && ui == 0 && ib.good()); - testVerifyBool((ib >> ui) && ui == 4294967295 && ib.good()); - testVerifyBool(!(ib >> ui) && ib.fail()); - } - ibInit("-2147483649"); - testVerifyBool(!(ib >> l) && ib.fail()); - ibInit("-2147483648 0 2147483647 2147483648"); - testVerifyBool((ib >> l) && l == -2147483648 && ib.good()); - testVerifyBool((ib >> l) && l == 0 && ib.good()); - testVerifyBool((ib >> l) && l == 2147483647 && ib.good()); - testVerifyBool(!(ib >> l) && ib.fail()); - - ibInit("-2147483649"); - testVerifyBool(!(ib >> sl) && ib.fail()); - ibInit("-2147483648 0 2147483647 2147483648"); - testVerifyBool((ib >> sl) && sl == -2147483648 && ib.good()); - testVerifyBool((ib >> sl) && sl == 0 && ib.good()); - testVerifyBool((ib >> sl) && sl == 2147483647 && ib.good()); - testVerifyBool(!(ib >> sl) && ib.fail()); - - ibInit("0 4294967295 4294967296"); - testVerifyBool((ib >> ul) && ul == 0 && ib.good()); - testVerifyBool((ib >> ul) && ul == 4294967295 && ib.good()); - testVerifyBool(!(ib >> ul) && ib.fail()); - - // octal hex - ibInit("123 abc 0xdef 0XABC 567"); - testVerifyBool((ib >> oct >> i) && i == 83); - testVerifyBool((ib >> hex >> i) && i == 0xabc); - testVerifyBool((ib >> i) && i == 0xdef); - testVerifyBool((ib >> i) && i == 0xabc); - testVerifyBool((ib >> dec >> i) && i ==567); -} -//------------------------------------------------------------------------------ -void istreamStr() { - char str[20]; - ibInit("abc def\r\n hij"); - testVerifyBool((ib >> str) && ib.good()); - testVerifyStr(str, "abc"); - testVerifyBool((ib >> str) && ib.good()); - testVerifyStr(str, "def"); - testVerifyBool((ib >> str) && ib.eof()); - testVerifyStr(str, "hij"); -} -//------------------------------------------------------------------------------ -void setup() { - testBegin(); - istreamBool(); - istreamChar(); - istreamDouble(); - istreamFloat(); - istreamGet(); - istreamNumber(); - istreamStr(); - testEnd(); -} -//------------------------------------------------------------------------------ -void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnSize/lfnSize.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnSize/lfnSize.ino deleted file mode 100644 index a0d20b0..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnSize/lfnSize.ino +++ /dev/null @@ -1,36 +0,0 @@ -// Program to compare size of SdFat with the SD.h library. -#include -// Select the test library by commenting out one of the following two lines. -// #include -#include - -// SD chip select pin. -const uint8_t SD_CS_PIN = SS; - -#ifdef __SD_H__ -File file; -#else // __SD_H__ -SdFat SD; -SdFile file; -#endif // __SD_H__ - -void setup() { - Serial.begin(9600); - while (!Serial) {} // wait for Leonardo - - if (!SD.begin(SD_CS_PIN)) { - Serial.println("begin failed"); - return; - } - #ifdef __SD_H__ - file = SD.open("SFN_file.txt", FILE_WRITE); - #else // __SD_H__ - file.open("LFN_file.txt", O_RDWR | O_CREAT); - #endif // __SD_H__ - - file.println("Hello"); - file.close(); - Serial.println("Done"); -} -//------------------------------------------------------------------------------ -void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnTest/lfnTest.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnTest/lfnTest.ino deleted file mode 100644 index f7c0ece..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnTest/lfnTest.ino +++ /dev/null @@ -1,234 +0,0 @@ -#include -#include -#include -const uint8_t SD_CS_PIN = SS; -SdFat sd; -SdFile file; -char name[260]; - -//------------------------------------------------------------------------------ -const char* testName[] = { - "low.low", - "low.Mix", - "low.UP", - "Mix.low", - "Mix.Mix", - "Mix.UP", - "UP.low", - "UP.Mix", - "UP.UP", - ".dot", - ".dot.dot", - "A b c . txt", - " Leading space and no extension", - "Trailing dots and space . . .", - "Long extension.extension", - "Space after dot. txt", - "Dot.dot.test.txt", - "Dot.dot.test.seq.txt", - "LOW.LOW", - "MIX.MIX", - "Invalid character *.test" -}; -//------------------------------------------------------------------------------ -bool checkName(char first, size_t len) { - size_t i; - if (len < 5 || len > sizeof(name)) { - return false; - } - if ( name[0] != first) { - return false; - } - for (i = 1; i < (len - 4); i++) { - if (name[i] != (char)('0' + (i + 1) %10)) { - return false; - } - } - const char* p = ".txt"; - while (*p) { - if (name[i++] != *p++) { - return false; - } - } - return name[i] == 0; -} -//------------------------------------------------------------------------------ -void makeName(char first, size_t len) { - size_t i; - if (len > sizeof(name)) { - len = 255; - } - if (len < 5) { - len = 5; - } - name[0] = first; - for (i = 1; i < (len - 4); i++) { - name[i] = '0' + (i + 1) %10; - } - const char* p = ".txt"; - while (*p) name[i++] = *p++; - name[i] = 0; -} -//------------------------------------------------------------------------------ -// test open, remove, getName, and ls. -void basicTest() { - size_t i; - size_t n = sd.vol()->fatType() == 32 ? 255 : 99; - uint16_t maxIndex = 0; - - makeName('Z', 256); - if (!file.open(name, O_RDWR | O_CREAT)) { - Serial.println(F("255 limit OK")); - } else { - sd.errorHalt(F("255 limit")); - } - for (i = 5; i <= n; i++) { - makeName('A', i); - - if (!file.open(name, O_RDWR | O_CREAT)) { - sd.errorHalt(F("open A")); - } - file.println(name); - Serial.print(i); - Serial.write(' '); - Serial.print(file.dirIndex()); - Serial.write(' '); - Serial.print(file.fileSize()); - Serial.println(F(" open A")); - if (file.fileSize() != (i + 2)) { - sd.errorHalt(F("file size A")); - } - if (file.dirIndex() >= maxIndex) { - maxIndex = file.dirIndex(); - } else { - Serial.print(maxIndex); Serial.print(',');Serial.println(file.dirIndex()); - sd.errorHalt(F("dirIndex")); - } - file.close(); - if (!file.open(sd.vwd(), maxIndex, O_READ)) { - sd.errorHalt(F("open by index")); - } - memset(name, 0, sizeof(name)); - if (!file.getName(name, sizeof(name))) { - sd.errorHalt(F("getName")); - } - if (!checkName('A', i)) { - Serial.println(name); - sd.errorHalt(F("checkName")); - } - file.close(); - } - for (i = n; i >= 5; i -= 2) { - makeName('A', i); - Serial.print(i); - Serial.println(F( " rm A")); - if (!sd.remove(name)) { - sd.errorHalt(F("remove A")); - } - } - for (i = n; i >= 5; i -= 2) { - makeName('B', i); - if (!file.open(name, O_RDWR | O_CREAT)) { - sd.errorHalt(F("open B")); - } - file.println(name); - Serial.print(i); - Serial.write(' '); - Serial.print(file.dirIndex()); - Serial.write(' '); - Serial.print(file.fileSize()); - Serial.println(F(" open B")); - if (file.fileSize() != (i + 2)) { - sd.errorHalt(F("file size B")); - } - if (file.dirIndex() > maxIndex) { - sd.errorHalt(F("maxIndex")); - } - file.close(); - } - Serial.println(F("----- ls ------")); - sd.ls(); - for (i = 5; i <= n; i++) { - char fc = i & 1 ? 'B' : 'A'; - makeName(fc, i); - Serial.print(i); - Serial.print(F(" rm ")); - Serial.println(fc); - if (!sd.remove(name)) { - sd.errorHalt(F("remove A/B")); - } - } - if (file.openNext(sd.vwd())) { - sd.errorHalt(F("remove all")); - } - Serial.println(); - Serial.println(F("basicTest done")); -} -//------------------------------------------------------------------------------ -void nameTest() { - Serial.println(); - uint8_t n = sizeof(testName)/sizeof(char*); - for (uint8_t i = 0; i < n; i++) { - Serial.print(F("Name: ")); - Serial.write('"'); - Serial.print(testName[i]); - Serial.println('"'); - if(!file.open(testName[i], O_CREAT | O_RDWR)) { - Serial.println(F("Open failed")); - } else { - file.println(testName[i]); - if (!file.getName(name, sizeof(name))) { - sd.errorHalt(F("getFilemame")); - } - file.println(name); - Serial.print(F("LFN: ")); - Serial.write('"'); - Serial.print(name); - Serial.println('"'); - Serial.print(F("SFN: ")); - Serial.write('"'); - file.printSFN(&Serial); - Serial.println('"'); - Serial.print(F("Index: ")); - if (file.dirIndex() < 10) { - Serial.write(' '); - } - Serial.println(file.dirIndex()); - file.close(); - } - Serial.println(); - } - Serial.println(F("----- ls ------")); - sd.ls(); - Serial.println(); - Serial.println(F("nameTest done")); -} -//------------------------------------------------------------------------------ -void setup() { - Serial.begin(9600); - while(!Serial); - Serial.print(F("\r\nFreeRam: ")); - Serial.println(FreeRam()); - Serial.println(F("Type any character to start.")); - while (Serial.read() < 0) {} - if (!sd.begin(SD_CS_PIN)) sd.initErrorHalt(); - if (file.openNext(sd.vwd())) { - file.close(); - delay(100); - while (Serial.read() >= 0) {} - Serial.print(F("Type 'W' to wipe the card: ")); - int c; - while ((c = Serial.read()) < 0) {} - if (c != 'W') { - sd.errorHalt(F("Invalid")); - } - Serial.println((char)c); - if (!sd.wipe(&Serial) || !sd.begin(SD_CS_PIN)) { - sd.errorHalt(F("wipe failed")); - } - } - basicTest(); - nameTest(); -} -//------------------------------------------------------------------------------ -void loop() {} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnTestCout/lfnTestCout.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnTestCout/lfnTestCout.ino deleted file mode 100644 index a331bd9..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/extras/SdFatTestSuite/examples/lfnTestCout/lfnTestCout.ino +++ /dev/null @@ -1,218 +0,0 @@ -#include -#include -#include -const uint8_t SD_CS_PIN = SS; -SdFat sd; -SdFile file; -char name[260]; - -// Serial output stream -ArduinoOutStream cout(Serial); - -// Serial in buffer. -char cinBuf[10]; - -// Serial input stream -ArduinoInStream cin(Serial, cinBuf, sizeof(cinBuf)); -//------------------------------------------------------------------------------ -const char* testName[] = { - "low.low", - "low.Mix", - "low.UP", - "Mix.low", - "Mix.Mix", - "Mix.UP", - "UP.low", - "UP.Mix", - "UP.UP", - ".dot", - ".dot.dot", - "A b c . txt", - " Leading space and no extension", - "Trailing dots and space . . .", - "Long extension.extension", - "Space after dot. txt", - "Dot.dot.test.txt", - "Dot.dot.test.seq.txt", - "LOW.LOW", - "MIX.MIX", - "Invalid character *.test" -}; -//------------------------------------------------------------------------------ -bool checkName(char first, size_t len) { - size_t i; - if (len < 5 || len > sizeof(name)) { - return false; - } - if ( name[0] != first) { - return false; - } - for (i = 1; i < (len - 4); i++) { - if (name[i] != (char)('0' + (i + 1) %10)) { - return false; - } - } - const char* p = ".txt"; - while (*p) { - if (name[i++] != *p++) { - return false; - } - } - return name[i] == 0; -} -//------------------------------------------------------------------------------ -void makeName(char first, size_t len) { - size_t i; - if (len > sizeof(name)) { - len = 255; - } - if (len < 5) { - len = 5; - } - name[0] = first; - for (i = 1; i < (len - 4); i++) { - name[i] = '0' + (i + 1) %10; - } - const char* p = ".txt"; - while (*p) name[i++] = *p++; - name[i] = 0; -} -//------------------------------------------------------------------------------ -// test open, remove, getName, and ls. -void basicTest() { - size_t i; - size_t n = sd.vol()->fatType() == 32 ? 255 : 99; - uint16_t maxIndex = 0; - - makeName('Z', 256); - if (!file.open(name, O_RDWR | O_CREAT)) { - cout << F("255 limit OK") << endl; - } else { - sd.errorHalt(F("255 limit")); - } - for (i = 5; i <= n; i++) { - makeName('A', i); - - if (!file.open(name, O_RDWR | O_CREAT)) { - sd.errorHalt(F("open A")); - } - file.println(name); - cout << setw(3) << i << setw(5) << file.dirIndex() << F(" open A") << endl; - - if (file.fileSize() != (i + 2)) { - sd.errorHalt(F("file size A")); - } - if (file.dirIndex() >= maxIndex) { - maxIndex = file.dirIndex(); - } else { - sd.errorHalt(F("dirIndex")); - } - file.close(); - if (!file.open(sd.vwd(), maxIndex, O_READ)) { - sd.errorHalt(F("open by index")); - } - memset(name, 0, sizeof(name)); - if (!file.getName(name, sizeof(name))) { - sd.errorHalt(F("getName")); - } - if (!checkName('A', i)) { - cout << name << endl; - sd.errorHalt(F("checkName")); - } - file.close(); - } - for (i = n; i >= 5; i -= 2) { - makeName('A', i); - cout << setw(3) << i << F( " rm A") << endl; - if (!sd.remove(name)) { - sd.errorHalt(F("remove A")); - } - } - for (i = n; i >= 5; i -= 2) { - makeName('B', i); - if (!file.open(name, O_RDWR | O_CREAT)) { - sd.errorHalt(F("open B")); - } - file.println(name); - - cout << setw(3) << i << setw(5) << file.dirIndex() << F(" open B") << endl; - - if (file.fileSize() != (i + 2)) { - sd.errorHalt(F("file size B")); - } - if (file.dirIndex() > maxIndex) { - sd.errorHalt(F("maxIndex")); - } - file.close(); - } - cout << endl << F("----- ls ------") << endl; - sd.ls(); - for (i = 5; i <= n; i++) { - char fc = i & 1 ? 'B' : 'A'; - makeName(fc, i); - cout << setw(3) << i << F(" rm ") << fc << endl; - if (!sd.remove(name)) { - sd.errorHalt(F("remove A/B")); - } - } - if (file.openNext(sd.vwd())) { - sd.errorHalt(F("remove all")); - } - cout << endl << F("basicTest done") << endl; -} -//------------------------------------------------------------------------------ -void nameTest() { - cout << endl; - uint8_t n = sizeof(testName)/sizeof(char*); - for (uint8_t i = 0; i < n; i++) { - cout << F("Name: \"") << testName[i] << '"' << endl; - if(!file.open(testName[i], O_CREAT | O_RDWR)) { - cout < -#include -#include -//------------------------------------------------------------------------------ -void ostreamBool() { - char buf[40]; - obufstream ob(buf, sizeof(buf)); - bool f = false; - bool t = true; - ob << t << ',' << f << ',' << setw(2) << t << ',' << left << setw(2) << f; - testVerifyStr(buf, "1,0, 1,0 "); - - ob.init(buf, sizeof(buf)); - ob << boolalpha << t << ',' << f << ',' << setw(5) << t; - ob << ',' << right << setw(6) << f; - testVerifyStr(buf, "true,false,true , false"); -} -//------------------------------------------------------------------------------ -void ostreamChar() { - char buf[40]; - obufstream ob(buf, sizeof(buf)); - char c = 'c'; - signed char sc = 's'; - unsigned char uc = 'u'; - ob <<'l' << c << sc << uc; - ob.put('p'); - testVerifyStr(buf, "lcsup"); - - ob.init(buf, sizeof(buf)); - ob << 's' << setw(2) << 'r' << 'n' << left << setw(2) << 'l'; - ob << 'm' << right << setw(2) << 'e'; - testVerifyStr(buf, "s rnl m e"); - - ob.init(buf, sizeof(buf)); - ob << setfill('f') << setw(5) << 'r'; - testVerifyStr(buf, "ffffr"); -} -//------------------------------------------------------------------------------ -void ostreamFloat() { - char buf[50]; - obufstream ob(buf, sizeof(buf)); - float f = 9.87654; - double d = -123.4567; - ob << f <<','; - ob << internal << setw(10) << d << ','; - ob << setfill('0') << setw(10) << d; - testVerifyStr(buf, "9.88,- 123.46,-000123.46"); - - ob.init(buf, sizeof(buf)); - ob << setw(10) << left << d << ',' << showpos << -d << ','; - ob << setprecision(0) << d; - testVerifyStr(buf, "-123.46000,+123.46,-123"); - - ob.init(buf, sizeof(buf)); - ob << showpoint << d << noshowpoint << ',' << d << ','; - ob << setprecision(4) << f << ',' << setprecision(2) << noshowpos << f; - testVerifyStr(buf, "-123.,-123,+9.8765,9.88"); -} -//------------------------------------------------------------------------------ -void ostreamNumber() { - char buf[50]; - obufstream ob(buf, sizeof(buf)); - - short s = 1; - short signed ss = 2; - short unsigned su = 3; - int i = 4; - int signed is = 5; - int unsigned iu = 6; - long l = 7; - long signed ls = 8; - long unsigned lu = 9; - - - ob << s << ss << su << i << is << iu << l < -maintainer=Bill Greiman -sentence=FAT16/FAT32 file system for SD cards. -paragraph=FAT16/FAT32 file system for SD cards. -category=Data Storage -url=https://github.com/greiman/SdFat -repository=https://github.com/greiman/SdFat.git -architectures=* diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/BlockDriver.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/BlockDriver.h deleted file mode 100644 index 2e4f131..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/BlockDriver.h +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ - /** - * \file - * \brief Define block driver. - */ -#ifndef BlockDriver_h -#define BlockDriver_h -#include "FatLib/BaseBlockDriver.h" -#include "SdCard/SdSpiCard.h" -//----------------------------------------------------------------------------- -/** typedef for BlockDriver */ -#if ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS -typedef BaseBlockDriver BlockDriver; -#else // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS -typedef SdSpiCard BlockDriver; -#endif // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS -#endif // BlockDriver_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ArduinoFiles.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ArduinoFiles.h deleted file mode 100644 index 286f509..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ArduinoFiles.h +++ /dev/null @@ -1,249 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -/** - * \file - * \brief PrintFile class - */ -#ifndef ArduinoFiles_h -#define ArduinoFiles_h -#include "FatLibConfig.h" -#if ENABLE_ARDUINO_FEATURES -#include "FatFile.h" -#include -//------------------------------------------------------------------------------ -/** Arduino SD.h style flag for open for read. */ -#define FILE_READ O_RDONLY -/** Arduino SD.h style flag for open at EOF for read/write with create. */ -#define FILE_WRITE (O_RDWR | O_CREAT | O_AT_END) -//============================================================================== -/** - * \class PrintFile - * \brief FatFile with Print. - */ -class PrintFile : public FatFile, public Print { - public: - PrintFile() {} - /** Create a file object and open it in the current working directory. - * - * \param[in] path A path for a file to be opened. - * - * \param[in] oflag Values for \a oflag are constructed by a - * bitwise-inclusive OR of open flags. see - * FatFile::open(FatFile*, const char*, oflag_t). - */ - PrintFile(const char* path, oflag_t oflag) : FatFile(path, oflag) {} -#if DESTRUCTOR_CLOSES_FILE - ~PrintFile() {} -#endif // DESTRUCTOR_CLOSES_FILE - using FatFile::clearWriteError; - using FatFile::getWriteError; - using FatFile::read; - using FatFile::write; - /** \return number of bytes available from the current position to EOF - * or INT_MAX if more than INT_MAX bytes are available. - */ - int available() { - uint32_t n = FatFile::available(); - return n > INT_MAX ? INT_MAX : n; - } - /** Ensure that any bytes written to the file are saved to the SD card. */ - void flush() { - FatFile::sync(); - } - /** Return the next available byte without consuming it. - * - * \return The byte if no error and not at eof else -1; - */ - int peek() { - return FatFile::peek(); - } - /** Read the next byte from a file. - * - * \return For success return the next byte in the file as an int. - * If an error occurs or end of file is reached return -1. - */ -// int read() { -// return FatFile::read(); -// } - /** Write a byte to a file. Required by the Arduino Print class. - * \param[in] b the byte to be written. - * Use getWriteError to check for errors. - * \return 1 for success and 0 for failure. - */ - size_t write(uint8_t b) { - return FatFile::write(b); - } - /** Write data to an open file. Form required by Print. - * - * \note Data is moved to the cache but may not be written to the - * storage device until sync() is called. - * - * \param[in] buf Pointer to the location of the data to be written. - * - * \param[in] size Number of bytes to write. - * - * \return For success write() returns the number of bytes written, always - * \a nbyte. If an error occurs, write() returns -1. Possible errors - * include write() is called before a file has been opened, write is called - * for a read-only file, device is full, a corrupt file system or an - * I/O error. - */ - size_t write(const uint8_t *buf, size_t size) { - return FatFile::write(buf, size); - } -}; -//============================================================================== -/** - * \class File - * \brief Arduino SD.h style File API - */ -class File : public FatFile, public Stream { - public: - File() {} - /** Create a file object and open it in the current working directory. - * - * \param[in] path A path with a valid 8.3 DOS name for a file to be opened. - * - * \param[in] oflag Values for \a oflag are constructed by a - * bitwise-inclusive OR of open flags. see - * FatFile::open(FatFile*, const char*, oflag_t). - */ - File(const char* path, oflag_t oflag) { - open(path, oflag); - } - using FatFile::clearWriteError; - using FatFile::getWriteError; - using FatFile::read; - using FatFile::write; - /** The parenthesis operator. - * - * \return true if a file is open. - */ - operator bool() { - return isOpen(); - } - /** \return number of bytes available from the current position to EOF - * or INT_MAX if more than INT_MAX bytes are available. - */ - int available() { - uint32_t n = FatFile::available(); - return n > INT_MAX ? INT_MAX : n; - } - /** Ensure that any bytes written to the file are saved to the SD card. */ - void flush() { - FatFile::sync(); - } - /** This function reports if the current file is a directory or not. - * \return true if the file is a directory. - */ - bool isDirectory() { - return isDir(); - } - /** No longer implemented due to Long File Names. - * - * Use getName(char* name, size_t size). - * \return a pointer to replacement suggestion. - */ - const char* name() const { - return "use getName()"; - } - /** Return the next available byte without consuming it. - * - * \return The byte if no error and not at eof else -1; - */ - int peek() { - return FatFile::peek(); - } - /** \return the current file position. */ - uint32_t position() { - return curPosition(); - } - /** Opens the next file or folder in a directory. - * - * \param[in] oflag open oflag flags. - * \return a File object. - */ - File openNextFile(oflag_t oflag = O_RDONLY) { - File tmpFile; - tmpFile.openNext(this, oflag); - return tmpFile; - } - /** Read the next byte from a file. - * - * \return For success return the next byte in the file as an int. - * If an error occurs or end of file is reached return -1. - */ - int read() { - return FatFile::read(); - } - /** Rewind a file if it is a directory */ - void rewindDirectory() { - if (isDir()) { - rewind(); - } - } - /** - * Seek to a new position in the file, which must be between - * 0 and the size of the file (inclusive). - * - * \param[in] pos the new file position. - * \return true for success else false. - */ - bool seek(uint32_t pos) { - return seekSet(pos); - } - /** \return the file's size. */ - uint32_t size() { - return fileSize(); - } - /** Write a byte to a file. Required by the Arduino Print class. - * \param[in] b the byte to be written. - * Use getWriteError to check for errors. - * \return 1 for success and 0 for failure. - */ - size_t write(uint8_t b) { - return FatFile::write(b); - } - /** Write data to an open file. Form required by Print. - * - * \note Data is moved to the cache but may not be written to the - * storage device until sync() is called. - * - * \param[in] buf Pointer to the location of the data to be written. - * - * \param[in] size Number of bytes to write. - * - * \return For success write() returns the number of bytes written, always - * \a nbyte. If an error occurs, write() returns -1. Possible errors - * include write() is called before a file has been opened, write is called - * for a read-only file, device is full, a corrupt file system or an - * I/O error. - */ - size_t write(const uint8_t *buf, size_t size) { - return FatFile::write(buf, size); - } -}; -#endif // ENABLE_ARDUINO_FEATURES -#endif // ArduinoFiles_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ArduinoStream.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ArduinoStream.h deleted file mode 100644 index a42f400..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ArduinoStream.h +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 ArduinoStream_h -#define ArduinoStream_h -/** - * \file - * \brief ArduinoInStream and ArduinoOutStream classes - */ -#include "FatLibConfig.h" -#if ENABLE_ARDUINO_FEATURES -#include "bufstream.h" -//============================================================================== -/** - * \class ArduinoInStream - * \brief Input stream for Arduino Stream objects - */ -class ArduinoInStream : public ibufstream { - public: - /** - * Constructor - * \param[in] hws hardware stream - * \param[in] buf buffer for input line - * \param[in] size size of input buffer - */ - ArduinoInStream(Stream &hws, char* buf, size_t size) { - m_hw = &hws; - m_line = buf; - m_size = size; - } - /** read a line. */ - void readline() { - size_t i = 0; - uint32_t t; - m_line[0] = '\0'; - while (!m_hw->available()) { - yield(); - } - - while (1) { - t = millis(); - while (!m_hw->available()) { - if ((millis() - t) > 10) { - goto done; - } - } - if (i >= (m_size - 1)) { - setstate(failbit); - return; - } - m_line[i++] = m_hw->read(); - m_line[i] = '\0'; - } -done: - init(m_line); - } - - protected: - /** Internal - do not use. - * \param[in] off - * \param[in] way - * \return true/false. - */ - bool seekoff(off_type off, seekdir way) { - (void)off; - (void)way; - return false; - } - /** Internal - do not use. - * \param[in] pos - * \return true/false. - */ - bool seekpos(pos_type pos) { - (void)pos; - return false; - } - - private: - char *m_line; - size_t m_size; - Stream* m_hw; -}; -//============================================================================== -/** - * \class ArduinoOutStream - * \brief Output stream for Arduino Print objects - */ -class ArduinoOutStream : public ostream { - public: - /** constructor - * - * \param[in] pr Print object for this ArduinoOutStream. - */ - explicit ArduinoOutStream(Print& pr) : m_pr(&pr) {} - - protected: - /// @cond SHOW_PROTECTED - /** - * Internal do not use - * \param[in] c - */ - void putch(char c) { - if (c == '\n') { - m_pr->write('\r'); - } - m_pr->write(c); - } - void putstr(const char* str) { - m_pr->write(str); - } - bool seekoff(off_type off, seekdir way) { - (void)off; - (void)way; - return false; - } - bool seekpos(pos_type pos) { - (void)pos; - return false; - } - bool sync() { - return true; - } - pos_type tellpos() { - return 0; - } - /// @endcond - private: - ArduinoOutStream() {} - Print* m_pr; -}; -#endif // ENABLE_ARDUINO_FEATURES -#endif // ArduinoStream_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/BaseBlockDriver.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/BaseBlockDriver.h deleted file mode 100644 index c824a18..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/BaseBlockDriver.h +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 BaseBlockDriver_h -#define BaseBlockDriver_h -#include "FatLibConfig.h" -/** - * \class BaseBlockDriver - * \brief Base block driver. - */ -class BaseBlockDriver { - public: - /** - * Read a 512 byte block from an SD card. - * - * \param[in] block Logical block to be read. - * \param[out] dst Pointer to the location that will receive the data. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - virtual bool readBlock(uint32_t block, uint8_t* dst) = 0; - /** End multi-block transfer and go to idle state. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - virtual bool syncBlocks() = 0; - /** - * Writes a 512 byte block to an SD card. - * - * \param[in] block Logical block to be written. - * \param[in] src Pointer to the location of the data to be written. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - virtual bool writeBlock(uint32_t block, const uint8_t* src) = 0; -#if USE_MULTI_BLOCK_IO - /** - * Read multiple 512 byte blocks from an SD card. - * - * \param[in] block Logical block to be read. - * \param[in] nb Number of blocks to be read. - * \param[out] dst Pointer to the location that will receive the data. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - virtual bool readBlocks(uint32_t block, uint8_t* dst, size_t nb) = 0; - /** - * Write multiple 512 byte blocks to an SD card. - * - * \param[in] block Logical block to be written. - * \param[in] nb Number of blocks to be written. - * \param[in] src Pointer to the location of the data to be written. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - virtual bool writeBlocks(uint32_t block, const uint8_t* src, size_t nb) = 0; -#endif // USE_MULTI_BLOCK_IO -}; -#endif // BaseBlockDriver_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatApiConstants.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatApiConstants.h deleted file mode 100644 index 52f4225..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatApiConstants.h +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 FatApiConstants_h -#define FatApiConstants_h -#include "SdFatConfig.h" - -#if USE_FCNTL_H -#include -/* values for GNU Arm Embedded Toolchain. - * O_RDONLY: 0x0 - * O_WRONLY: 0x1 - * O_RDWR: 0x2 - * O_ACCMODE: 0x3 - * O_APPEND: 0x8 - * O_CREAT: 0x200 - * O_TRUNC: 0x400 - * O_EXCL: 0x800 - * O_SYNC: 0x2000 - * O_NONBLOCK: 0x4000 - */ -/** Use O_NONBLOCK for open at EOF */ -#define O_AT_END O_NONBLOCK ///< Open at EOF. -typedef int oflag_t; -#else // USE_FCNTL_H -#define O_RDONLY 0X00 ///< Open for reading only. -#define O_WRONLY 0X01 ///< Open for writing only. -#define O_RDWR 0X02 ///< Open for reading and writing. -#define O_AT_END 0X04 ///< Open at EOF. -#define O_APPEND 0X08 ///< Set append mode. -#define O_CREAT 0x10 ///< Create file if it does not exist. -#define O_TRUNC 0x20 ///< Truncate file to zero length. -#define O_EXCL 0x40 ///< Fail if the file exists. -#define O_SYNC 0x80 ///< Synchronized write I/O operations. - -#define O_ACCMODE (O_RDONLY|O_WRONLY|O_RDWR) ///< Mask for access mode. -typedef uint8_t oflag_t; -#endif // USE_FCNTL_H - -#define O_READ O_RDONLY -#define O_WRITE O_WRONLY - -inline bool isWriteMode(oflag_t oflag) { - oflag &= O_ACCMODE; - return oflag == O_WRONLY || oflag == O_RDWR; -} - -// FatFile class static and const definitions -// flags for ls() -/** ls() flag for list all files including hidden. */ -const uint8_t LS_A = 1; -/** ls() flag to print modify. date */ -const uint8_t LS_DATE = 2; -/** ls() flag to print file size. */ -const uint8_t LS_SIZE = 4; -/** ls() flag for recursive list of subdirectories */ -const uint8_t LS_R = 8; - -// flags for timestamp -/** set the file's last access date */ -const uint8_t T_ACCESS = 1; -/** set the file's creation date and time */ -const uint8_t T_CREATE = 2; -/** Set the file's write date and time */ -const uint8_t T_WRITE = 4; -#endif // FatApiConstants_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFile.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFile.cpp deleted file mode 100644 index 7342e36..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFile.cpp +++ /dev/null @@ -1,1530 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#include "FatFile.h" -#include "FatFileSystem.h" -//------------------------------------------------------------------------------ -// Pointer to cwd directory. -FatFile* FatFile::m_cwd = 0; -// Callback function for date/time. -void (*FatFile::m_dateTime)(uint16_t* date, uint16_t* time) = 0; -//------------------------------------------------------------------------------ -// Add a cluster to a file. -bool FatFile::addCluster() { - m_flags |= F_FILE_DIR_DIRTY; - return m_vol->allocateCluster(m_curCluster, &m_curCluster); -} -//------------------------------------------------------------------------------ -// Add a cluster to a directory file and zero the cluster. -// Return with first block of cluster in the cache. -bool FatFile::addDirCluster() { - uint32_t block; - cache_t* pc; - - if (isRootFixed()) { - DBG_FAIL_MACRO; - goto fail; - } - // max folder size - if (m_curPosition >= 512UL*4095) { - DBG_FAIL_MACRO; - goto fail; - } - if (!addCluster()) { - DBG_FAIL_MACRO; - goto fail; - } - block = m_vol->clusterFirstBlock(m_curCluster); - pc = m_vol->cacheFetchData(block, FatCache::CACHE_RESERVE_FOR_WRITE); - if (!pc) { - DBG_FAIL_MACRO; - goto fail; - } - memset(pc, 0, 512); - // zero rest of clusters - for (uint8_t i = 1; i < m_vol->blocksPerCluster(); i++) { - if (!m_vol->writeBlock(block + i, pc->data)) { - DBG_FAIL_MACRO; - goto fail; - } - } - // Set position to EOF to avoid inconsistent curCluster/curPosition. - m_curPosition += 512UL*m_vol->blocksPerCluster(); - return true; - -fail: - return false; -} -//------------------------------------------------------------------------------ -// cache a file's directory entry -// return pointer to cached entry or null for failure -dir_t* FatFile::cacheDirEntry(uint8_t action) { - cache_t* pc; - pc = m_vol->cacheFetchData(m_dirBlock, action); - if (!pc) { - DBG_FAIL_MACRO; - goto fail; - } - return pc->dir + (m_dirIndex & 0XF); - -fail: - return 0; -} -//------------------------------------------------------------------------------ -bool FatFile::close() { - bool rtn = sync(); - m_attr = FILE_ATTR_CLOSED; - return rtn; -} -//------------------------------------------------------------------------------ -bool FatFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock) { - // error if no blocks - if (m_firstCluster == 0) { - DBG_FAIL_MACRO; - goto fail; - } - for (uint32_t c = m_firstCluster; ; c++) { - uint32_t next; - int8_t fg = m_vol->fatGet(c, &next); - if (fg < 0) { - DBG_FAIL_MACRO; - goto fail; - } - // check for contiguous - if (fg == 0 || next != (c + 1)) { - // error if not end of chain - if (fg) { - DBG_FAIL_MACRO; - goto fail; - } - *bgnBlock = m_vol->clusterFirstBlock(m_firstCluster); - *endBlock = m_vol->clusterFirstBlock(c) - + m_vol->blocksPerCluster() - 1; - return true; - } - } - -fail: - return false; -} -//------------------------------------------------------------------------------ -bool FatFile::createContiguous(FatFile* dirFile, - const char* path, uint32_t size) { - uint32_t count; - - // don't allow zero length file - if (size == 0) { - DBG_FAIL_MACRO; - goto fail; - } - if (!open(dirFile, path, O_RDWR | O_CREAT | O_EXCL)) { - DBG_FAIL_MACRO; - goto fail; - } - // calculate number of clusters needed - count = ((size - 1) >> (m_vol->clusterSizeShift() + 9)) + 1; - - // allocate clusters - if (!m_vol->allocContiguous(count, &m_firstCluster)) { - remove(); - DBG_FAIL_MACRO; - goto fail; - } - m_fileSize = size; - - // insure sync() will update dir entry - m_flags |= F_FILE_DIR_DIRTY; - return sync(); - -fail: - return false; -} -//------------------------------------------------------------------------------ -bool FatFile::dirEntry(dir_t* dst) { - dir_t* dir; - // Make sure fields on device are correct. - if (!sync()) { - DBG_FAIL_MACRO; - goto fail; - } - // read entry - dir = cacheDirEntry(FatCache::CACHE_FOR_READ); - if (!dir) { - DBG_FAIL_MACRO; - goto fail; - } - // copy to caller's struct - memcpy(dst, dir, sizeof(dir_t)); - return true; - -fail: - return false; -} -//------------------------------------------------------------------------------ -uint8_t FatFile::dirName(const dir_t* dir, char* name) { - uint8_t j = 0; - uint8_t lcBit = DIR_NT_LC_BASE; - for (uint8_t i = 0; i < 11; i++) { - if (dir->name[i] == ' ') { - continue; - } - if (i == 8) { - // Position bit for extension. - lcBit = DIR_NT_LC_EXT; - name[j++] = '.'; - } - char c = dir->name[i]; - if ('A' <= c && c <= 'Z' && (lcBit & dir->reservedNT)) { - c += 'a' - 'A'; - } - name[j++] = c; - } - name[j] = 0; - return j; -} - -//------------------------------------------------------------------------------ -uint32_t FatFile::dirSize() { - int8_t fg; - if (!isDir()) { - return 0; - } - if (isRootFixed()) { - return 32*m_vol->rootDirEntryCount(); - } - uint16_t n = 0; - uint32_t c = isRoot32() ? m_vol->rootDirStart() : m_firstCluster; - do { - fg = m_vol->fatGet(c, &c); - if (fg < 0 || n > 4095) { - return 0; - } - n += m_vol->blocksPerCluster(); - } while (fg); - return 512UL*n; -} -//------------------------------------------------------------------------------ -int16_t FatFile::fgets(char* str, int16_t num, char* delim) { - char ch; - int16_t n = 0; - int16_t r = -1; - while ((n + 1) < num && (r = read(&ch, 1)) == 1) { - // delete CR - if (ch == '\r') { - continue; - } - str[n++] = ch; - if (!delim) { - if (ch == '\n') { - break; - } - } else { - if (strchr(delim, ch)) { - break; - } - } - } - if (r < 0) { - // read error - return -1; - } - str[n] = '\0'; - return n; -} -//------------------------------------------------------------------------------ -void FatFile::getpos(FatPos_t* pos) { - pos->position = m_curPosition; - pos->cluster = m_curCluster; -} -//------------------------------------------------------------------------------ -bool FatFile::mkdir(FatFile* parent, const char* path, bool pFlag) { - fname_t fname; - FatFile tmpDir; - - if (isOpen() || !parent->isDir()) { - DBG_FAIL_MACRO; - goto fail; - } - if (isDirSeparator(*path)) { - while (isDirSeparator(*path)) { - path++; - } - if (!tmpDir.openRoot(parent->m_vol)) { - DBG_FAIL_MACRO; - goto fail; - } - parent = &tmpDir; - } - while (1) { - if (!parsePathName(path, &fname, &path)) { - DBG_FAIL_MACRO; - goto fail; - } - if (!*path) { - break; - } - if (!open(parent, &fname, O_RDONLY)) { - if (!pFlag || !mkdir(parent, &fname)) { - DBG_FAIL_MACRO; - goto fail; - } - } - tmpDir = *this; - parent = &tmpDir; - close(); - } - return mkdir(parent, &fname); - -fail: - return false; -} -//------------------------------------------------------------------------------ -bool FatFile::mkdir(FatFile* parent, fname_t* fname) { - uint32_t block; - dir_t dot; - dir_t* dir; - cache_t* pc; - - if (!parent->isDir()) { - DBG_FAIL_MACRO; - goto fail; - } - // create a normal file - if (!open(parent, fname, O_RDWR | O_CREAT | O_EXCL)) { - DBG_FAIL_MACRO; - goto fail; - } - // convert file to directory - m_flags = F_READ; - m_attr = FILE_ATTR_SUBDIR; - - // allocate and zero first cluster - if (!addDirCluster()) { - DBG_FAIL_MACRO; - goto fail; - } - m_firstCluster = m_curCluster; - // Set to start of dir - rewind(); - // force entry to device - if (!sync()) { - DBG_FAIL_MACRO; - goto fail; - } - // cache entry - should already be in cache due to sync() call - dir = cacheDirEntry(FatCache::CACHE_FOR_WRITE); - if (!dir) { - DBG_FAIL_MACRO; - goto fail; - } - // change directory entry attribute - dir->attributes = DIR_ATT_DIRECTORY; - - // make entry for '.' - memcpy(&dot, dir, sizeof(dot)); - dot.name[0] = '.'; - for (uint8_t i = 1; i < 11; i++) { - dot.name[i] = ' '; - } - - // cache block for '.' and '..' - block = m_vol->clusterFirstBlock(m_firstCluster); - pc = m_vol->cacheFetchData(block, FatCache::CACHE_FOR_WRITE); - if (!pc) { - DBG_FAIL_MACRO; - goto fail; - } - // copy '.' to block - memcpy(&pc->dir[0], &dot, sizeof(dot)); - // make entry for '..' - dot.name[1] = '.'; - dot.firstClusterLow = parent->m_firstCluster & 0XFFFF; - dot.firstClusterHigh = parent->m_firstCluster >> 16; - // copy '..' to block - memcpy(&pc->dir[1], &dot, sizeof(dot)); - // write first block - return m_vol->cacheSync(); - -fail: - return false; -} -//------------------------------------------------------------------------------ -bool FatFile::open(FatFileSystem* fs, const char* path, oflag_t oflag) { - return open(fs->vwd(), path, oflag); -} -//------------------------------------------------------------------------------ -bool FatFile::open(FatFile* dirFile, const char* path, oflag_t oflag) { - FatFile tmpDir; - fname_t fname; - - // error if already open - if (isOpen() || !dirFile->isDir()) { - DBG_FAIL_MACRO; - goto fail; - } - if (isDirSeparator(*path)) { - while (isDirSeparator(*path)) { - path++; - } - if (*path == 0) { - return openRoot(dirFile->m_vol); - } - if (!tmpDir.openRoot(dirFile->m_vol)) { - DBG_FAIL_MACRO; - goto fail; - } - dirFile = &tmpDir; - } - while (1) { - if (!parsePathName(path, &fname, &path)) { - DBG_FAIL_MACRO; - goto fail; - } - if (*path == 0) { - break; - } - if (!open(dirFile, &fname, O_RDONLY)) { - DBG_FAIL_MACRO; - goto fail; - } - tmpDir = *this; - dirFile = &tmpDir; - close(); - } - return open(dirFile, &fname, oflag); - -fail: - return false; -} -//------------------------------------------------------------------------------ -bool FatFile::open(FatFile* dirFile, uint16_t index, oflag_t oflag) { - uint8_t chksum = 0; - uint8_t lfnOrd = 0; - dir_t* dir; - ldir_t*ldir; - - // Error if already open. - if (isOpen() || !dirFile->isDir()) { - DBG_FAIL_MACRO; - goto fail; - } - // Don't open existing file if O_EXCL - user call error. - if (oflag & O_EXCL) { - DBG_FAIL_MACRO; - goto fail; - } - if (index) { - // Check for LFN. - if (!dirFile->seekSet(32UL*(index -1))) { - DBG_FAIL_MACRO; - goto fail; - } - ldir = reinterpret_cast(dirFile->readDirCache()); - if (!ldir) { - DBG_FAIL_MACRO; - goto fail; - } - if (ldir->attr == DIR_ATT_LONG_NAME) { - if (1 == (ldir->ord & 0X1F)) { - chksum = ldir->chksum; - // Use largest possible number. - lfnOrd = index > 20 ? 20 : index; - } - } - } else { - dirFile->rewind(); - } - // read entry into cache - dir = dirFile->readDirCache(); - if (!dir) { - DBG_FAIL_MACRO; - goto fail; - } - // error if empty slot or '.' or '..' - if (dir->name[0] == DIR_NAME_DELETED || - dir->name[0] == DIR_NAME_FREE || - dir->name[0] == '.') { - DBG_FAIL_MACRO; - goto fail; - } - if (lfnOrd && chksum != lfnChecksum(dir->name)) { - DBG_FAIL_MACRO; - goto fail; - } - // open cached entry - if (!openCachedEntry(dirFile, index, oflag, lfnOrd)) { - DBG_FAIL_MACRO; - goto fail; - } - return true; - -fail: - return false; -} -//------------------------------------------------------------------------------ -// open a cached directory entry. - -bool FatFile::openCachedEntry(FatFile* dirFile, uint16_t dirIndex, - oflag_t oflag, uint8_t lfnOrd) { - uint32_t firstCluster; - memset(this, 0, sizeof(FatFile)); - // location of entry in cache - m_vol = dirFile->m_vol; - m_dirIndex = dirIndex; - m_dirCluster = dirFile->m_firstCluster; - dir_t* dir = &m_vol->cacheAddress()->dir[0XF & dirIndex]; - - // Must be file or subdirectory. - if (!DIR_IS_FILE_OR_SUBDIR(dir)) { - DBG_FAIL_MACRO; - goto fail; - } - m_attr = dir->attributes & FILE_ATTR_COPY; - if (DIR_IS_FILE(dir)) { - m_attr |= FILE_ATTR_FILE; - } - m_lfnOrd = lfnOrd; - - switch (oflag & O_ACCMODE) { - case O_RDONLY: - if (oflag & O_TRUNC) { - DBG_FAIL_MACRO; - goto fail; - } - m_flags = F_READ; - break; - - case O_RDWR: - m_flags = F_READ | F_WRITE; - break; - - case O_WRONLY: - m_flags = F_WRITE; - break; - - default: - DBG_FAIL_MACRO; - goto fail; - } - - if (m_flags & F_WRITE) { - if (isSubDir() || isReadOnly()) { - DBG_FAIL_MACRO; - goto fail; - } - } - - m_flags |= (oflag & O_APPEND ? F_APPEND : 0) | (oflag & O_SYNC ? F_SYNC : 0); - - m_dirBlock = m_vol->cacheBlockNumber(); - - // copy first cluster number for directory fields - firstCluster = ((uint32_t)dir->firstClusterHigh << 16) - | dir->firstClusterLow; - - if (oflag & O_TRUNC) { - if (firstCluster && !m_vol->freeChain(firstCluster)) { - DBG_FAIL_MACRO; - goto fail; - } - // need to update directory entry - m_flags |= F_FILE_DIR_DIRTY; - } else { - m_firstCluster = firstCluster; - m_fileSize = dir->fileSize; - } - if ((oflag & O_AT_END) && !seekSet(m_fileSize)) { - DBG_FAIL_MACRO; - goto fail; - } - return true; - -fail: - m_attr = FILE_ATTR_CLOSED; - return false; -} -//------------------------------------------------------------------------------ -bool FatFile::openCwd() { - if (!cwd()) { - DBG_FAIL_MACRO; - return false; - } - *this = *cwd(); - rewind(); - return true; -} -//------------------------------------------------------------------------------ -bool FatFile::openNext(FatFile* dirFile, oflag_t oflag) { - uint8_t chksum = 0; - ldir_t* ldir; - uint8_t lfnOrd = 0; - uint16_t index; - - // Check for not open and valid directory.. - if (isOpen() || !dirFile->isDir() || (dirFile->curPosition() & 0X1F)) { - DBG_FAIL_MACRO; - goto fail; - } - while (1) { - // read entry into cache - index = dirFile->curPosition()/32; - dir_t* dir = dirFile->readDirCache(); - if (!dir) { - if (dirFile->getError()) { - DBG_FAIL_MACRO; - } - goto fail; - } - // done if last entry - if (dir->name[0] == DIR_NAME_FREE) { - goto fail; - } - // skip empty slot or '.' or '..' - if (dir->name[0] == '.' || dir->name[0] == DIR_NAME_DELETED) { - lfnOrd = 0; - } else if (DIR_IS_FILE_OR_SUBDIR(dir)) { - if (lfnOrd && chksum != lfnChecksum(dir->name)) { - DBG_FAIL_MACRO; - goto fail; - } - if (!openCachedEntry(dirFile, index, oflag, lfnOrd)) { - DBG_FAIL_MACRO; - goto fail; - } - return true; - } else if (DIR_IS_LONG_NAME(dir)) { - ldir = reinterpret_cast(dir); - if (ldir->ord & LDIR_ORD_LAST_LONG_ENTRY) { - lfnOrd = ldir->ord & 0X1F; - chksum = ldir->chksum; - } - } else { - lfnOrd = 0; - } - } - -fail: - return false; -} -#ifndef DOXYGEN_SHOULD_SKIP_THIS -//------------------------------------------------------------------------------ -/** Open a file's parent directory. - * - * \param[in] file Parent of this directory will be opened. Must not be root. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ -bool FatFile::openParent(FatFile* dirFile) { - FatFile dotdot; - uint32_t lbn; - dir_t* dir; - uint32_t ddc; - cache_t* cb; - - if (isOpen() || !dirFile->isOpen()) { - goto fail; - } - if (dirFile->m_dirCluster == 0) { - return openRoot(dirFile->m_vol); - } - lbn = dirFile->m_vol->clusterFirstBlock(dirFile->m_dirCluster); - cb = dirFile->m_vol->cacheFetchData(lbn, FatCache::CACHE_FOR_READ); - if (!cb) { - DBG_FAIL_MACRO; - goto fail; - } - // Point to dir entery for .. - dir = cb->dir + 1; - ddc = dir->firstClusterLow | ((uint32_t)dir->firstClusterHigh << 16); - if (ddc == 0) { - if (!dotdot.openRoot(dirFile->m_vol)) { - DBG_FAIL_MACRO; - goto fail; - } - } else { - memset(&dotdot, 0, sizeof(FatFile)); - dotdot.m_attr = FILE_ATTR_SUBDIR; - dotdot.m_flags = F_READ; - dotdot.m_vol = dirFile->m_vol; - dotdot.m_firstCluster = ddc; - } - uint32_t di; - do { - di = dotdot.curPosition()/32; - dir = dotdot.readDirCache(); - if (!dir) { - DBG_FAIL_MACRO; - goto fail; - } - ddc = dir->firstClusterLow | ((uint32_t)dir->firstClusterHigh << 16); - } while (ddc != dirFile->m_dirCluster); - return open(&dotdot, di, O_RDONLY); - -fail: - return false; -} -#endif // DOXYGEN_SHOULD_SKIP_THIS -//------------------------------------------------------------------------------ -bool FatFile::openRoot(FatVolume* vol) { - // error if file is already open - if (isOpen()) { - DBG_FAIL_MACRO; - goto fail; - } - memset(this, 0, sizeof(FatFile)); - - m_vol = vol; - switch (vol->fatType()) { -#if FAT12_SUPPORT - case 12: -#endif // FAT12_SUPPORT - case 16: - m_attr = FILE_ATTR_ROOT_FIXED; - break; - - case 32: - m_attr = FILE_ATTR_ROOT32; - break; - - default: - DBG_FAIL_MACRO; - goto fail; - } - // read only - m_flags = F_READ; - return true; - -fail: - return false; -} -//------------------------------------------------------------------------------ -int FatFile::peek() { - FatPos_t pos; - getpos(&pos); - int c = read(); - if (c >= 0) { - setpos(&pos); - } - return c; -} -//------------------------------------------------------------------------------ -int FatFile::read(void* buf, size_t nbyte) { - int8_t fg; - uint8_t blockOfCluster = 0; - uint8_t* dst = reinterpret_cast(buf); - uint16_t offset; - size_t toRead; - uint32_t block; // raw device block number - cache_t* pc; - - // error if not open for read - if (!isOpen() || !(m_flags & F_READ)) { - DBG_FAIL_MACRO; - goto fail; - } - - if (isFile()) { - uint32_t tmp32 = m_fileSize - m_curPosition; - if (nbyte >= tmp32) { - nbyte = tmp32; - } - } else if (isRootFixed()) { - uint16_t tmp16 = 32*m_vol->m_rootDirEntryCount - (uint16_t)m_curPosition; - if (nbyte > tmp16) { - nbyte = tmp16; - } - } - toRead = nbyte; - while (toRead) { - size_t n; - offset = m_curPosition & 0X1FF; // offset in block - if (isRootFixed()) { - block = m_vol->rootDirStart() + (m_curPosition >> 9); - } else { - blockOfCluster = m_vol->blockOfCluster(m_curPosition); - if (offset == 0 && blockOfCluster == 0) { - // start of new cluster - if (m_curPosition == 0) { - // use first cluster in file - m_curCluster = isRoot32() ? m_vol->rootDirStart() : m_firstCluster; - } else { - // get next cluster from FAT - fg = m_vol->fatGet(m_curCluster, &m_curCluster); - if (fg < 0) { - DBG_FAIL_MACRO; - goto fail; - } - if (fg == 0) { - if (isDir()) { - break; - } - DBG_FAIL_MACRO; - goto fail; - } - } - } - block = m_vol->clusterFirstBlock(m_curCluster) + blockOfCluster; - } - if (offset != 0 || toRead < 512 || block == m_vol->cacheBlockNumber()) { - // amount to be read from current block - n = 512 - offset; - if (n > toRead) { - n = toRead; - } - // read block to cache and copy data to caller - pc = m_vol->cacheFetchData(block, FatCache::CACHE_FOR_READ); - if (!pc) { - DBG_FAIL_MACRO; - goto fail; - } - uint8_t* src = pc->data + offset; - memcpy(dst, src, n); -#if USE_MULTI_BLOCK_IO - } else if (toRead >= 1024) { - size_t nb = toRead >> 9; - if (!isRootFixed()) { - uint8_t mb = m_vol->blocksPerCluster() - blockOfCluster; - if (mb < nb) { - nb = mb; - } - } - n = 512*nb; - if (m_vol->cacheBlockNumber() <= block - && block < (m_vol->cacheBlockNumber() + nb)) { - // flush cache if a block is in the cache - if (!m_vol->cacheSyncData()) { - DBG_FAIL_MACRO; - goto fail; - } - } - if (!m_vol->readBlocks(block, dst, nb)) { - DBG_FAIL_MACRO; - goto fail; - } -#endif // USE_MULTI_BLOCK_IO - } else { - // read single block - n = 512; - if (!m_vol->readBlock(block, dst)) { - DBG_FAIL_MACRO; - goto fail; - } - } - dst += n; - m_curPosition += n; - toRead -= n; - } - return nbyte - toRead; - -fail: - m_error |= READ_ERROR; - return -1; -} -//------------------------------------------------------------------------------ -int8_t FatFile::readDir(dir_t* dir) { - int16_t n; - // if not a directory file or miss-positioned return an error - if (!isDir() || (0X1F & m_curPosition)) { - return -1; - } - - while (1) { - n = read(dir, sizeof(dir_t)); - if (n != sizeof(dir_t)) { - return n == 0 ? 0 : -1; - } - // last entry if DIR_NAME_FREE - if (dir->name[0] == DIR_NAME_FREE) { - return 0; - } - // skip empty entries and entry for . and .. - if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') { - continue; - } - // return if normal file or subdirectory - if (DIR_IS_FILE_OR_SUBDIR(dir)) { - return n; - } - } -} -//------------------------------------------------------------------------------ -// Read next directory entry into the cache -// Assumes file is correctly positioned -dir_t* FatFile::readDirCache(bool skipReadOk) { -// uint8_t b; - uint8_t i = (m_curPosition >> 5) & 0XF; - - if (i == 0 || !skipReadOk) { - int8_t n = read(&n, 1); - if (n != 1) { - if (n != 0) { - DBG_FAIL_MACRO; - } - goto fail; - } - m_curPosition += 31; - } else { - m_curPosition += 32; - } - // return pointer to entry - return m_vol->cacheAddress()->dir + i; - -fail: - return 0; -} -//------------------------------------------------------------------------------ -bool FatFile::remove(FatFile* dirFile, const char* path) { - FatFile file; - if (!file.open(dirFile, path, O_WRONLY)) { - DBG_FAIL_MACRO; - goto fail; - } - return file.remove(); - -fail: - return false; -} -//------------------------------------------------------------------------------ -bool FatFile::rename(FatFile* dirFile, const char* newPath) { - dir_t entry; - uint32_t dirCluster = 0; - FatFile file; - FatFile oldFile; - cache_t* pc; - dir_t* dir; - - // Must be an open file or subdirectory. - if (!(isFile() || isSubDir())) { - DBG_FAIL_MACRO; - goto fail; - } - // Can't rename LFN in 8.3 mode. - if (!USE_LONG_FILE_NAMES && isLFN()) { - DBG_FAIL_MACRO; - goto fail; - } - // Can't move file to new volume. - if (m_vol != dirFile->m_vol) { - DBG_FAIL_MACRO; - goto fail; - } - // sync() and cache directory entry - sync(); - oldFile = *this; - dir = cacheDirEntry(FatCache::CACHE_FOR_READ); - if (!dir) { - DBG_FAIL_MACRO; - goto fail; - } - // save directory entry - memcpy(&entry, dir, sizeof(entry)); - // make directory entry for new path - if (isFile()) { - if (!file.open(dirFile, newPath, O_WRONLY | O_CREAT | O_EXCL)) { - DBG_FAIL_MACRO; - goto fail; - } - } else { - // don't create missing path prefix components - if (!file.mkdir(dirFile, newPath, false)) { - DBG_FAIL_MACRO; - goto fail; - } - // save cluster containing new dot dot - dirCluster = file.m_firstCluster; - } - // change to new directory entry - - m_dirBlock = file.m_dirBlock; - m_dirIndex = file.m_dirIndex; - m_lfnOrd = file.m_lfnOrd; - m_dirCluster = file.m_dirCluster; - // mark closed to avoid possible destructor close call - file.m_attr = FILE_ATTR_CLOSED; - - // cache new directory entry - dir = cacheDirEntry(FatCache::CACHE_FOR_WRITE); - if (!dir) { - DBG_FAIL_MACRO; - goto fail; - } - // copy all but name and name flags to new directory entry - memcpy(&dir->creationTimeTenths, &entry.creationTimeTenths, - sizeof(entry) - sizeof(dir->name) - 2); - dir->attributes = entry.attributes; - - // update dot dot if directory - if (dirCluster) { - // get new dot dot - uint32_t block = m_vol->clusterFirstBlock(dirCluster); - pc = m_vol->cacheFetchData(block, FatCache::CACHE_FOR_READ); - if (!pc) { - DBG_FAIL_MACRO; - goto fail; - } - memcpy(&entry, &pc->dir[1], sizeof(entry)); - - // free unused cluster - if (!m_vol->freeChain(dirCluster)) { - DBG_FAIL_MACRO; - goto fail; - } - // store new dot dot - block = m_vol->clusterFirstBlock(m_firstCluster); - pc = m_vol->cacheFetchData(block, FatCache::CACHE_FOR_WRITE); - if (!pc) { - DBG_FAIL_MACRO; - goto fail; - } - memcpy(&pc->dir[1], &entry, sizeof(entry)); - } - // Remove old directory entry; - oldFile.m_firstCluster = 0; - oldFile.m_flags = F_WRITE; - oldFile.m_attr = FILE_ATTR_FILE; - if (!oldFile.remove()) { - DBG_FAIL_MACRO; - goto fail; - } - return m_vol->cacheSync(); - -fail: - return false; -} -//------------------------------------------------------------------------------ -bool FatFile::rmdir() { - // must be open subdirectory - if (!isSubDir() || (!USE_LONG_FILE_NAMES && isLFN())) { - DBG_FAIL_MACRO; - goto fail; - } - rewind(); - - // make sure directory is empty - while (1) { - dir_t* dir = readDirCache(true); - if (!dir) { - // EOF if no error. - if (!getError()) { - break; - } - DBG_FAIL_MACRO; - goto fail; - } - // done if past last used entry - if (dir->name[0] == DIR_NAME_FREE) { - break; - } - // skip empty slot, '.' or '..' - if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') { - continue; - } - // error not empty - if (DIR_IS_FILE_OR_SUBDIR(dir)) { - DBG_FAIL_MACRO; - goto fail; - } - } - // convert empty directory to normal file for remove - m_attr = FILE_ATTR_FILE; - m_flags |= F_WRITE; - return remove(); - -fail: - return false; -} -//------------------------------------------------------------------------------ -bool FatFile::rmRfStar() { - uint16_t index; - FatFile f; - if (!isDir()) { - DBG_FAIL_MACRO; - goto fail; - } - rewind(); - while (1) { - // remember position - index = m_curPosition/32; - - dir_t* dir = readDirCache(); - if (!dir) { - // At EOF if no error. - if (!getError()) { - break; - } - DBG_FAIL_MACRO; - goto fail; - } - // done if past last entry - if (dir->name[0] == DIR_NAME_FREE) { - break; - } - - // skip empty slot or '.' or '..' - if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') { - continue; - } - - // skip if part of long file name or volume label in root - if (!DIR_IS_FILE_OR_SUBDIR(dir)) { - continue; - } - - if (!f.open(this, index, O_RDONLY)) { - DBG_FAIL_MACRO; - goto fail; - } - if (f.isSubDir()) { - // recursively delete - if (!f.rmRfStar()) { - DBG_FAIL_MACRO; - goto fail; - } - } else { - // ignore read-only - f.m_flags |= F_WRITE; - if (!f.remove()) { - DBG_FAIL_MACRO; - goto fail; - } - } - // position to next entry if required - if (m_curPosition != (32UL*(index + 1))) { - if (!seekSet(32UL*(index + 1))) { - DBG_FAIL_MACRO; - goto fail; - } - } - } - // don't try to delete root - if (!isRoot()) { - if (!rmdir()) { - DBG_FAIL_MACRO; - goto fail; - } - } - return true; - -fail: - return false; -} -//------------------------------------------------------------------------------ -bool FatFile::seekSet(uint32_t pos) { - uint32_t nCur; - uint32_t nNew; - uint32_t tmp = m_curCluster; - // error if file not open - if (!isOpen()) { - DBG_FAIL_MACRO; - goto fail; - } - // Optimize O_APPEND writes. - if (pos == m_curPosition) { - return true; - } - if (pos == 0) { - // set position to start of file - m_curCluster = 0; - goto done; - } - if (isFile()) { - if (pos > m_fileSize) { - DBG_FAIL_MACRO; - goto fail; - } - } else if (isRootFixed()) { - if (pos <= 32*m_vol->rootDirEntryCount()) { - goto done; - } - DBG_FAIL_MACRO; - goto fail; - } - // calculate cluster index for cur and new position - nCur = (m_curPosition - 1) >> (m_vol->clusterSizeShift() + 9); - nNew = (pos - 1) >> (m_vol->clusterSizeShift() + 9); - - if (nNew < nCur || m_curPosition == 0) { - // must follow chain from first cluster - m_curCluster = isRoot32() ? m_vol->rootDirStart() : m_firstCluster; - } else { - // advance from curPosition - nNew -= nCur; - } - while (nNew--) { - if (m_vol->fatGet(m_curCluster, &m_curCluster) <= 0) { - DBG_FAIL_MACRO; - goto fail; - } - } - -done: - m_curPosition = pos; - return true; - -fail: - m_curCluster = tmp; - return false; -} -//------------------------------------------------------------------------------ -void FatFile::setpos(FatPos_t* pos) { - m_curPosition = pos->position; - m_curCluster = pos->cluster; -} -//------------------------------------------------------------------------------ -bool FatFile::sync() { - if (!isOpen()) { - return true; - } - if (m_flags & F_FILE_DIR_DIRTY) { - dir_t* dir = cacheDirEntry(FatCache::CACHE_FOR_WRITE); - // check for deleted by another open file object - if (!dir || dir->name[0] == DIR_NAME_DELETED) { - DBG_FAIL_MACRO; - goto fail; - } - // do not set filesize for dir files - if (isFile()) { - dir->fileSize = m_fileSize; - } - - // update first cluster fields - dir->firstClusterLow = m_firstCluster & 0XFFFF; - dir->firstClusterHigh = m_firstCluster >> 16; - - // set modify time if user supplied a callback date/time function - if (m_dateTime) { - m_dateTime(&dir->lastWriteDate, &dir->lastWriteTime); - dir->lastAccessDate = dir->lastWriteDate; - } - // clear directory dirty - m_flags &= ~F_FILE_DIR_DIRTY; - } - if (m_vol->cacheSync()) { - return true; - } - DBG_FAIL_MACRO; - -fail: - m_error |= WRITE_ERROR; - return false; -} -//------------------------------------------------------------------------------ -bool FatFile::timestamp(FatFile* file) { - dir_t* dir; - dir_t srcDir; - - // most be files get timestamps - if (!isFile() || !file->isFile() || !file->dirEntry(&srcDir)) { - DBG_FAIL_MACRO; - goto fail; - } - // update directory fields - if (!sync()) { - DBG_FAIL_MACRO; - goto fail; - } - dir = cacheDirEntry(FatCache::CACHE_FOR_WRITE); - if (!dir) { - DBG_FAIL_MACRO; - goto fail; - } - // copy timestamps - dir->lastAccessDate = srcDir.lastAccessDate; - dir->creationDate = srcDir.creationDate; - dir->creationTime = srcDir.creationTime; - dir->creationTimeTenths = srcDir.creationTimeTenths; - dir->lastWriteDate = srcDir.lastWriteDate; - dir->lastWriteTime = srcDir.lastWriteTime; - - // write back entry - return m_vol->cacheSync(); - -fail: - return false; -} -//------------------------------------------------------------------------------ -bool FatFile::timestamp(uint8_t flags, uint16_t year, uint8_t month, - uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) { - uint16_t dirDate; - uint16_t dirTime; - dir_t* dir; - - if (!isFile() - || year < 1980 - || year > 2107 - || month < 1 - || month > 12 - || day < 1 - || day > 31 - || hour > 23 - || minute > 59 - || second > 59) { - DBG_FAIL_MACRO; - goto fail; - } - // update directory entry - if (!sync()) { - DBG_FAIL_MACRO; - goto fail; - } - dir = cacheDirEntry(FatCache::CACHE_FOR_WRITE); - if (!dir) { - DBG_FAIL_MACRO; - goto fail; - } - dirDate = FAT_DATE(year, month, day); - dirTime = FAT_TIME(hour, minute, second); - if (flags & T_ACCESS) { - dir->lastAccessDate = dirDate; - } - if (flags & T_CREATE) { - dir->creationDate = dirDate; - dir->creationTime = dirTime; - // seems to be units of 1/100 second not 1/10 as Microsoft states - dir->creationTimeTenths = second & 1 ? 100 : 0; - } - if (flags & T_WRITE) { - dir->lastWriteDate = dirDate; - dir->lastWriteTime = dirTime; - } - return m_vol->cacheSync(); - -fail: - return false; -} -//------------------------------------------------------------------------------ -bool FatFile::truncate(uint32_t length) { - uint32_t newPos; - // error if not a normal file or read-only - if (!isFile() || !(m_flags & F_WRITE)) { - DBG_FAIL_MACRO; - goto fail; - } - // error if length is greater than current size - if (length > m_fileSize) { - DBG_FAIL_MACRO; - goto fail; - } - // fileSize and length are zero - nothing to do - if (m_fileSize == 0) { - return true; - } - - // remember position for seek after truncation - newPos = m_curPosition > length ? length : m_curPosition; - - // position to last cluster in truncated file - if (!seekSet(length)) { - DBG_FAIL_MACRO; - goto fail; - } - if (length == 0) { - // free all clusters - if (!m_vol->freeChain(m_firstCluster)) { - DBG_FAIL_MACRO; - goto fail; - } - m_firstCluster = 0; - } else { - uint32_t toFree; - int8_t fg = m_vol->fatGet(m_curCluster, &toFree); - if (fg < 0) { - DBG_FAIL_MACRO; - goto fail; - } - if (fg) { - // free extra clusters - if (!m_vol->freeChain(toFree)) { - DBG_FAIL_MACRO; - goto fail; - } - // current cluster is end of chain - if (!m_vol->fatPutEOC(m_curCluster)) { - DBG_FAIL_MACRO; - goto fail; - } - } - } - m_fileSize = length; - - // need to update directory entry - m_flags |= F_FILE_DIR_DIRTY; - - if (!sync()) { - DBG_FAIL_MACRO; - goto fail; - } - // set file to correct position - return seekSet(newPos); - -fail: - return false; -} -//------------------------------------------------------------------------------ -int FatFile::write(const void* buf, size_t nbyte) { - // convert void* to uint8_t* - must be before goto statements - const uint8_t* src = reinterpret_cast(buf); - cache_t* pc; - uint8_t cacheOption; - // number of bytes left to write - must be before goto statements - size_t nToWrite = nbyte; - size_t n; - // error if not a normal file or is read-only - if (!isFile() || !(m_flags & F_WRITE)) { - DBG_FAIL_MACRO; - goto fail; - } - // seek to end of file if append flag - if ((m_flags & F_APPEND)) { - if (!seekSet(m_fileSize)) { - DBG_FAIL_MACRO; - goto fail; - } - } - // Don't exceed max fileSize. - if (nbyte > (0XFFFFFFFF - m_curPosition)) { - DBG_FAIL_MACRO; - goto fail; - } - while (nToWrite) { - uint8_t blockOfCluster = m_vol->blockOfCluster(m_curPosition); - uint16_t blockOffset = m_curPosition & 0X1FF; - if (blockOfCluster == 0 && blockOffset == 0) { - // start of new cluster - if (m_curCluster != 0) { - int8_t fg = m_vol->fatGet(m_curCluster, &m_curCluster); - if (fg < 0) { - DBG_FAIL_MACRO; - goto fail; - } - if (fg == 0) { - // add cluster if at end of chain - if (!addCluster()) { - DBG_FAIL_MACRO; - goto fail; - } - } - } else { - if (m_firstCluster == 0) { - // allocate first cluster of file - if (!addCluster()) { - DBG_FAIL_MACRO; - goto fail; - } - m_firstCluster = m_curCluster; - } else { - m_curCluster = m_firstCluster; - } - } - } - // block for data write - uint32_t block = m_vol->clusterFirstBlock(m_curCluster) + blockOfCluster; - - if (blockOffset != 0 || nToWrite < 512) { - // partial block - must use cache - // max space in block - n = 512 - blockOffset; - // lesser of space and amount to write - if (n > nToWrite) { - n = nToWrite; - } - - if (blockOffset == 0 && m_curPosition >= m_fileSize) { - // start of new block don't need to read into cache - cacheOption = FatCache::CACHE_RESERVE_FOR_WRITE; - } else { - // rewrite part of block - cacheOption = FatCache::CACHE_FOR_WRITE; - } - pc = m_vol->cacheFetchData(block, cacheOption); - if (!pc) { - DBG_FAIL_MACRO; - goto fail; - } - uint8_t* dst = pc->data + blockOffset; - memcpy(dst, src, n); - if (512 == (n + blockOffset)) { - // Force write if block is full - improves large writes. - if (!m_vol->cacheSyncData()) { - DBG_FAIL_MACRO; - goto fail; - } - } -#if USE_MULTI_BLOCK_IO - } else if (nToWrite >= 1024) { - // use multiple block write command - uint8_t maxBlocks = m_vol->blocksPerCluster() - blockOfCluster; - size_t nb = nToWrite >> 9; - if (nb > maxBlocks) { - nb = maxBlocks; - } - n = 512*nb; - if (m_vol->cacheBlockNumber() <= block - && block < (m_vol->cacheBlockNumber() + nb)) { - // invalidate cache if block is in cache - m_vol->cacheInvalidate(); - } - if (!m_vol->writeBlocks(block, src, nb)) { - DBG_FAIL_MACRO; - goto fail; - } -#endif // USE_MULTI_BLOCK_IO - } else { - // use single block write command - n = 512; - if (m_vol->cacheBlockNumber() == block) { - m_vol->cacheInvalidate(); - } - if (!m_vol->writeBlock(block, src)) { - DBG_FAIL_MACRO; - goto fail; - } - } - m_curPosition += n; - src += n; - nToWrite -= n; - } - if (m_curPosition > m_fileSize) { - // update fileSize and insure sync will update dir entry - m_fileSize = m_curPosition; - m_flags |= F_FILE_DIR_DIRTY; - } else if (m_dateTime) { - // insure sync will update modified date and time - m_flags |= F_FILE_DIR_DIRTY; - } - - if (m_flags & F_SYNC) { - if (!sync()) { - DBG_FAIL_MACRO; - goto fail; - } - } - return nbyte; - -fail: - // return for write error - m_error |= WRITE_ERROR; - return -1; -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFile.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFile.h deleted file mode 100644 index 028fd0f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFile.h +++ /dev/null @@ -1,1029 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 FatFile_h -#define FatFile_h -/** - * \file - * \brief FatFile class - */ -// #include -#include -#include -#include -#include "FatLibConfig.h" -#include "FatApiConstants.h" -#include "FatStructs.h" -#include "FatVolume.h" -class FatFileSystem; -//------------------------------------------------------------------------------ -// Stuff to store strings in AVR flash. -#ifdef __AVR__ -#include -#else // __AVR__ -#ifndef PSTR -/** store literal string in flash for ARM */ -#define PSTR(x) (x) -#endif // PSTR -#ifndef pgm_read_byte -/** read 8-bits from flash for ARM */ -#define pgm_read_byte(addr) (*(const unsigned char*)(addr)) -#endif // pgm_read_byte -#ifndef pgm_read_word -/** read 16-bits from flash for ARM */ -#define pgm_read_word(addr) (*(const uint16_t*)(addr)) -#endif // pgm_read_word -#ifndef PROGMEM -/** store in flash for ARM */ -#define PROGMEM -#endif // PROGMEM -#endif // __AVR__ -//------------------------------------------------------------------------------ -/** - * \struct FatPos_t - * \brief Internal type for file position - do not use in user apps. - */ -struct FatPos_t { - /** stream position */ - uint32_t position; - /** cluster for position */ - uint32_t cluster; - FatPos_t() : position(0), cluster(0) {} -}; -//------------------------------------------------------------------------------ -/** Expression for path name separator. */ -#define isDirSeparator(c) ((c) == '/') -//------------------------------------------------------------------------------ -/** - * \struct fname_t - * \brief Internal type for Short File Name - do not use in user apps. - */ -struct fname_t { - /** Flags for base and extension character case and LFN. */ - uint8_t flags; - /** length of Long File Name */ - size_t len; - /** Long File Name start. */ - const char* lfn; - /** position for sequence number */ - uint8_t seqPos; - /** Short File Name */ - uint8_t sfn[11]; -}; -/** Derived from a LFN with loss or conversion of characters. */ -const uint8_t FNAME_FLAG_LOST_CHARS = 0X01; -/** Base-name or extension has mixed case. */ -const uint8_t FNAME_FLAG_MIXED_CASE = 0X02; -/** LFN entries are required for file name. */ -const uint8_t FNAME_FLAG_NEED_LFN = - FNAME_FLAG_LOST_CHARS | FNAME_FLAG_MIXED_CASE; -/** Filename base-name is all lower case */ -const uint8_t FNAME_FLAG_LC_BASE = DIR_NT_LC_BASE; -/** Filename extension is all lower case. */ -const uint8_t FNAME_FLAG_LC_EXT = DIR_NT_LC_EXT; -//============================================================================== -/** - * \class FatFile - * \brief Basic file class. - */ -class FatFile { - public: - /** Create an instance. */ - FatFile() : m_attr(FILE_ATTR_CLOSED), m_error(0) {} - /** Create a file object and open it in the current working directory. - * - * \param[in] path A path with a valid 8.3 DOS name for a file to be opened. - * - * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive - * OR of open flags. see FatFile::open(FatFile*, const char*, oflag_t). - */ - FatFile(const char* path, oflag_t oflag) { - m_attr = FILE_ATTR_CLOSED; - m_error = 0; - open(path, oflag); - } -#if DESTRUCTOR_CLOSES_FILE - ~FatFile() { - if (isOpen()) { - close(); - } - } -#endif // DESTRUCTOR_CLOSES_FILE - -#if ENABLE_ARDUINO_FEATURES - /** List directory contents. - * - * \param[in] flags The inclusive OR of - * - * LS_DATE - %Print file modification date - * - * LS_SIZE - %Print file size. - * - * LS_R - Recursive list of subdirectories. - * - * \return true for success or false if an error occurred. - */ - bool ls(uint8_t flags = 0) { - return ls(&Serial, flags); - } - /** %Print a directory date field. - * - * Format is yyyy-mm-dd. - * - * \param[in] fatDate The date field from a directory entry. - */ - static void printFatDate(uint16_t fatDate) { - printFatDate(&Serial, fatDate); - } - /** %Print a directory time field. - * - * Format is hh:mm:ss. - * - * \param[in] fatTime The time field from a directory entry. - */ - static void printFatTime(uint16_t fatTime) { - printFatTime(&Serial, fatTime); - } - /** Print a file's name. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - size_t printName() { - return FatFile::printName(&Serial); - } -#endif // ENABLE_ARDUINO_FEATURES - - /** \return value of writeError */ - bool getWriteError() { - return m_error & WRITE_ERROR; - } - /** Set writeError to zero */ - void clearWriteError() { - m_error &= ~WRITE_ERROR; - } - /** Clear all error bits. */ - void clearError() { - m_error = 0; - } - /** \return All error bits. */ - uint8_t getError() { - return m_error; - } - /** get position for streams - * \param[out] pos struct to receive position - */ - void getpos(FatPos_t* pos); - /** set position for streams - * \param[out] pos struct with value for new position - */ - void setpos(FatPos_t* pos); - /** \return The number of bytes available from the current position - * to EOF for normal files. Zero is returned for directory files. - */ - uint32_t available() { - return isFile() ? fileSize() - curPosition() : 0; - } - /** Close a file and force cached data and directory information - * to be written to the storage device. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool close(); - /** Check for contiguous file and return its raw block range. - * - * \param[out] bgnBlock the first block address for the file. - * \param[out] endBlock the last block address for the file. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock); - /** Create and open a new contiguous file of a specified size. - * - * \param[in] dirFile The directory where the file will be created. - * \param[in] path A path with a validfile name. - * \param[in] size The desired file size. - * - * \return The value true is returned for success and - * the value false, is returned for failure. - */ - bool createContiguous(FatFile* dirFile, - const char* path, uint32_t size); - /** Create and open a new contiguous file of a specified size. - * - * \param[in] path A path with a validfile name. - * \param[in] size The desired file size. - * - * \return The value true is returned for success and - * the value false, is returned for failure. - */ - bool createContiguous(const char* path, uint32_t size) { - return createContiguous(m_cwd, path, size); - } - /** \return The current cluster number for a file or directory. */ - uint32_t curCluster() const { - return m_curCluster; - } - /** \return The current position for a file or directory. */ - uint32_t curPosition() const { - return m_curPosition; - } - /** \return Current working directory */ - static FatFile* cwd() { - return m_cwd; - } - /** Set the date/time callback function - * - * \param[in] dateTime The user's call back function. The callback - * function is of the form: - * - * \code - * void dateTime(uint16_t* date, uint16_t* time) { - * uint16_t year; - * uint8_t month, day, hour, minute, second; - * - * // User gets date and time from GPS or real-time clock here - * - * // return date using FAT_DATE macro to format fields - * *date = FAT_DATE(year, month, day); - * - * // return time using FAT_TIME macro to format fields - * *time = FAT_TIME(hour, minute, second); - * } - * \endcode - * - * Sets the function that is called when a file is created or when - * a file's directory entry is modified by sync(). All timestamps, - * access, creation, and modify, are set when a file is created. - * sync() maintains the last access date and last modify date/time. - * - * See the timestamp() function. - */ - static void dateTimeCallback( - void (*dateTime)(uint16_t* date, uint16_t* time)) { - m_dateTime = dateTime; - } - /** Cancel the date/time callback function. */ - static void dateTimeCallbackCancel() { - m_dateTime = 0; - } - /** Return a file's directory entry. - * - * \param[out] dir Location for return of the file's directory entry. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool dirEntry(dir_t* dir); - /** - * \return The index of this file in it's directory. - */ - uint16_t dirIndex() { - return m_dirIndex; - } - /** Format the name field of \a dir into the 13 byte array - * \a name in standard 8.3 short name format. - * - * \param[in] dir The directory structure containing the name. - * \param[out] name A 13 byte char array for the formatted name. - * \return length of the name. - */ - static uint8_t dirName(const dir_t* dir, char* name); - /** \return The number of bytes allocated to a directory or zero - * if an error occurs. - */ - uint32_t dirSize(); - /** Dump file in Hex - * \param[in] pr Print stream for list. - * \param[in] pos Start position in file. - * \param[in] n number of locations to dump. - */ - void dmpFile(print_t* pr, uint32_t pos, size_t n); - /** Test for the existence of a file in a directory - * - * \param[in] path Path of the file to be tested for. - * - * The calling instance must be an open directory file. - * - * dirFile.exists("TOFIND.TXT") searches for "TOFIND.TXT" in the directory - * dirFile. - * - * \return true if the file exists else false. - */ - bool exists(const char* path) { - FatFile file; - return file.open(this, path, O_RDONLY); - } - /** - * Get a string from a file. - * - * fgets() reads bytes from a file into the array pointed to by \a str, until - * \a num - 1 bytes are read, or a delimiter is read and transferred to \a str, - * or end-of-file is encountered. The string is then terminated - * with a null byte. - * - * fgets() deletes CR, '\\r', from the string. This insures only a '\\n' - * terminates the string for Windows text files which use CRLF for newline. - * - * \param[out] str Pointer to the array where the string is stored. - * \param[in] num Maximum number of characters to be read - * (including the final null byte). Usually the length - * of the array \a str is used. - * \param[in] delim Optional set of delimiters. The default is "\n". - * - * \return For success fgets() returns the length of the string in \a str. - * If no data is read, fgets() returns zero for EOF or -1 if an error occurred. - */ - int16_t fgets(char* str, int16_t num, char* delim = 0); - /** \return The total number of bytes in a file. */ - uint32_t fileSize() const { - return m_fileSize; - } - /** \return The first cluster number for a file or directory. */ - uint32_t firstCluster() const { - return m_firstCluster; - } - /** - * Get a file's name followed by a zero byte. - * - * \param[out] name An array of characters for the file's name. - * \param[in] size The size of the array in bytes. The array - * must be at least 13 bytes long. The file's name will be - * truncated if the file's name is too long. - * \return The value true, is returned for success and - * the value false, is returned for failure. - */ - bool getName(char* name, size_t size); - /** - * Get a file's Short File Name followed by a zero byte. - * - * \param[out] name An array of characters for the file's name. - * The array must be at least 13 bytes long. - * \return The value true, is returned for success and - * the value false, is returned for failure. - */ - bool getSFN(char* name); - /** \return True if this is a directory else false. */ - bool isDir() const { - return m_attr & FILE_ATTR_DIR; - } - /** \return True if this is a normal file else false. */ - bool isFile() const { - return m_attr & FILE_ATTR_FILE; - } - /** \return True if this is a hidden file else false. */ - bool isHidden() const { - return m_attr & FILE_ATTR_HIDDEN; - } - /** \return true if this file has a Long File Name. */ - bool isLFN() const { - return m_lfnOrd; - } - /** \return True if this is an open file/directory else false. */ - bool isOpen() const { - return m_attr; - } - /** \return True if this is the root directory. */ - bool isRoot() const { - return m_attr & FILE_ATTR_ROOT; - } - /** \return True if this is the FAT32 root directory. */ - bool isRoot32() const { - return m_attr & FILE_ATTR_ROOT32; - } - /** \return True if this is the FAT12 of FAT16 root directory. */ - bool isRootFixed() const { - return m_attr & FILE_ATTR_ROOT_FIXED; - } - /** \return True if file is read-only */ - bool isReadOnly() const { - return m_attr & FILE_ATTR_READ_ONLY; - } - /** \return True if this is a subdirectory else false. */ - bool isSubDir() const { - return m_attr & FILE_ATTR_SUBDIR; - } - /** \return True if this is a system file else false. */ - bool isSystem() const { - return m_attr & FILE_ATTR_SYSTEM; - } - /** Check for a legal 8.3 character. - * \param[in] c Character to be checked. - * \return true for a legal 8.3 character else false. - */ - static bool legal83Char(uint8_t c) { - if (c == '"' || c == '|') { - return false; - } - // *+,./ - if (0X2A <= c && c <= 0X2F && c != 0X2D) { - return false; - } - // :;<=>? - if (0X3A <= c && c <= 0X3F) { - return false; - } - // [\] - if (0X5B <= c && c <= 0X5D) { - return false; - } - return 0X20 < c && c < 0X7F; - } - /** List directory contents. - * - * \param[in] pr Print stream for list. - * - * \param[in] flags The inclusive OR of - * - * LS_DATE - %Print file modification date - * - * LS_SIZE - %Print file size. - * - * LS_R - Recursive list of subdirectories. - * - * \param[in] indent Amount of space before file name. Used for recursive - * list to indicate subdirectory level. - * - * \return true for success or false if an error occurred. - */ - bool ls(print_t* pr, uint8_t flags = 0, uint8_t indent = 0); - /** Make a new directory. - * - * \param[in] dir An open FatFile instance for the directory that will - * contain the new directory. - * - * \param[in] path A path with a valid 8.3 DOS name for the new directory. - * - * \param[in] pFlag Create missing parent directories if true. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool mkdir(FatFile* dir, const char* path, bool pFlag = true); - /** Open a file in the volume working directory of a FatFileSystem. - * - * \param[in] fs File System where the file is located. - * - * \param[in] path with a valid 8.3 DOS name for a file to be opened. - * - * \param[in] oflag bitwise-inclusive OR of open mode flags. - * See see FatFile::open(FatFile*, const char*, oflag_t). - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool open(FatFileSystem* fs, const char* path, oflag_t oflag); - /** Open a file by index. - * - * \param[in] dirFile An open FatFile instance for the directory. - * - * \param[in] index The \a index of the directory entry for the file to be - * opened. The value for \a index is (directory file position)/32. - * - * \param[in] oflag bitwise-inclusive OR of open mode flags. - * See see FatFile::open(FatFile*, const char*, oflag_t). - * - * See open() by path for definition of flags. - * \return true for success or false for failure. - */ - bool open(FatFile* dirFile, uint16_t index, oflag_t oflag); - /** Open a file or directory by name. - * - * \param[in] dirFile An open FatFile instance for the directory containing - * the file to be opened. - * - * \param[in] path A path with a valid 8.3 DOS name for a file to be opened. - * - * \param[in] oflag Values for \a oflag are constructed by a - * bitwise-inclusive OR of flags from the following list - * - * O_RDONLY - Open for reading. - * - * O_READ - Same as O_RDONLY (GNU). - * - * O_WRONLY - Open for writing. - * - * O_WRITE - Same as O_WRONLY (GNU). - * - * O_RDWR - Open for reading and writing. - * - * O_APPEND - If set, the file offset shall be set to the end of the - * file prior to each write. - * - * O_AT_END - Set the initial position at the end of the file. - * - * O_CREAT - If the file exists, this flag has no effect except as noted - * under O_EXCL below. Otherwise, the file shall be created - * - * O_EXCL - If O_CREAT and O_EXCL are set, open() shall fail if the file exists. - * - * O_SYNC - Call sync() after each write. This flag should not be used with - * write(uint8_t) or any functions do character at a time writes since sync() - * will be called after each byte. - * - * O_TRUNC - If the file exists and is a regular file, and the file is - * successfully opened and is not read only, its length shall be truncated to 0. - * - * WARNING: A given file must not be opened by more than one FatFile object - * or file corruption may occur. - * - * \note Directory files must be opened read only. Write and truncation is - * not allowed for directory files. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool open(FatFile* dirFile, const char* path, oflag_t oflag); - /** Open a file in the current working directory. - * - * \param[in] path A path with a valid 8.3 DOS name for a file to be opened. - * - * \param[in] oflag bitwise-inclusive OR of open mode flags. - * See see FatFile::open(FatFile*, const char*, oflag_t). - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool open(const char* path, oflag_t oflag = O_RDONLY) { - return open(m_cwd, path, oflag); - } - /** Open current working directory. - * - * \return true for success or false for failure. - */ - bool openCwd(); - /** Open the next file or subdirectory in a directory. - * - * \param[in] dirFile An open FatFile instance for the directory - * containing the file to be opened. - * - * \param[in] oflag bitwise-inclusive OR of open mode flags. - * See see FatFile::open(FatFile*, const char*, oflag_t). - * - * \return true for success or false for failure. - */ - bool openNext(FatFile* dirFile, oflag_t oflag = O_RDONLY); - /** Open a volume's root directory. - * - * \param[in] vol The FAT volume containing the root directory to be opened. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool openRoot(FatVolume* vol); - /** Return the next available byte without consuming it. - * - * \return The byte if no error and not at eof else -1; - */ - int peek(); - /** Print a file's creation date and time - * - * \param[in] pr Print stream for output. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool printCreateDateTime(print_t* pr); - /** %Print a directory date field. - * - * Format is yyyy-mm-dd. - * - * \param[in] pr Print stream for output. - * \param[in] fatDate The date field from a directory entry. - */ - static void printFatDate(print_t* pr, uint16_t fatDate); - /** %Print a directory time field. - * - * Format is hh:mm:ss. - * - * \param[in] pr Print stream for output. - * \param[in] fatTime The time field from a directory entry. - */ - static void printFatTime(print_t* pr, uint16_t fatTime); - /** Print a number followed by a field terminator. - * \param[in] value The number to be printed. - * \param[in] term The field terminator. Use '\\n' for CR LF. - * \param[in] prec Number of digits after decimal point. - * \return The number of bytes written or -1 if an error occurs. - */ - int printField(float value, char term, uint8_t prec = 2); - /** Print a number followed by a field terminator. - * \param[in] value The number to be printed. - * \param[in] term The field terminator. Use '\\n' for CR LF. - * \return The number of bytes written or -1 if an error occurs. - */ - int printField(int16_t value, char term); - /** Print a number followed by a field terminator. - * \param[in] value The number to be printed. - * \param[in] term The field terminator. Use '\\n' for CR LF. - * \return The number of bytes written or -1 if an error occurs. - */ - int printField(uint16_t value, char term); - /** Print a number followed by a field terminator. - * \param[in] value The number to be printed. - * \param[in] term The field terminator. Use '\\n' for CR LF. - * \return The number of bytes written or -1 if an error occurs. - */ - int printField(int32_t value, char term); - /** Print a number followed by a field terminator. - * \param[in] value The number to be printed. - * \param[in] term The field terminator. Use '\\n' for CR LF. - * \return The number of bytes written or -1 if an error occurs. - */ - int printField(uint32_t value, char term); - /** Print a file's modify date and time - * - * \param[in] pr Print stream for output. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool printModifyDateTime(print_t* pr); - /** Print a file's name - * - * \param[in] pr Print stream for output. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - size_t printName(print_t* pr); - /** Print a file's size. - * - * \param[in] pr Print stream for output. - * - * \return The number of characters printed is returned - * for success and zero is returned for failure. - */ - size_t printFileSize(print_t* pr); - /** Print a file's Short File Name. - * - * \param[in] pr Print stream for output. - * - * \return The number of characters printed is returned - * for success and zero is returned for failure. - */ - size_t printSFN(print_t* pr); - /** Read the next byte from a file. - * - * \return For success read returns the next byte in the file as an int. - * If an error occurs or end of file is reached -1 is returned. - */ - int read() { - uint8_t b; - return read(&b, 1) == 1 ? b : -1; - } - /** Read data from a file starting at the current position. - * - * \param[out] buf Pointer to the location that will receive the data. - * - * \param[in] nbyte Maximum number of bytes to read. - * - * \return For success read() returns the number of bytes read. - * A value less than \a nbyte, including zero, will be returned - * if end of file is reached. - * If an error occurs, read() returns -1. Possible errors include - * read() called before a file has been opened, corrupt file system - * or an I/O error occurred. - */ - int read(void* buf, size_t nbyte); - /** Read the next directory entry from a directory file. - * - * \param[out] dir The dir_t struct that will receive the data. - * - * \return For success readDir() returns the number of bytes read. - * A value of zero will be returned if end of file is reached. - * If an error occurs, readDir() returns -1. Possible errors include - * readDir() called before a directory has been opened, this is not - * a directory file or an I/O error occurred. - */ - int8_t readDir(dir_t* dir); - /** Remove a file. - * - * The directory entry and all data for the file are deleted. - * - * \note This function should not be used to delete the 8.3 version of a - * file that has a long name. For example if a file has the long name - * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool remove(); - /** Remove a file. - * - * The directory entry and all data for the file are deleted. - * - * \param[in] dirFile The directory that contains the file. - * \param[in] path Path for the file to be removed. - * - * \note This function should not be used to delete the 8.3 version of a - * file that has a long name. For example if a file has the long name - * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - static bool remove(FatFile* dirFile, const char* path); - /** Set the file's current position to zero. */ - void rewind() { - seekSet(0); - } - /** Rename a file or subdirectory. - * - * \note the file will be moved to the current working directory. - * - * \param[in] newPath New path name for the file/directory. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool rename(const char* newPath) { - return rename(cwd(), newPath); - } - /** Rename a file or subdirectory. - * - * \param[in] dirFile Directory for the new path. - * \param[in] newPath New path name for the file/directory. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool rename(FatFile* dirFile, const char* newPath); - /** Remove a directory file. - * - * The directory file will be removed only if it is empty and is not the - * root directory. rmdir() follows DOS and Windows and ignores the - * read-only attribute for the directory. - * - * \note This function should not be used to delete the 8.3 version of a - * directory that has a long name. For example if a directory has the - * long name "New folder" you should not delete the 8.3 name "NEWFOL~1". - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool rmdir(); - /** Recursively delete a directory and all contained files. - * - * This is like the Unix/Linux 'rm -rf *' if called with the root directory - * hence the name. - * - * Warning - This will remove all contents of the directory including - * subdirectories. The directory will then be removed if it is not root. - * The read-only attribute for files will be ignored. - * - * \note This function should not be used to delete the 8.3 version of - * a directory that has a long name. See remove() and rmdir(). - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool rmRfStar(); - /** Set the files position to current position + \a pos. See seekSet(). - * \param[in] offset The new position in bytes from the current position. - * \return true for success or false for failure. - */ - bool seekCur(int32_t offset) { - return seekSet(m_curPosition + offset); - } - /** Set the files position to end-of-file + \a offset. See seekSet(). - * Can't be used for directory files since file size is not defined. - * \param[in] offset The new position in bytes from end-of-file. - * \return true for success or false for failure. - */ - bool seekEnd(int32_t offset = 0) { - return isFile() ? seekSet(m_fileSize + offset) : false; - } - /** Sets a file's position. - * - * \param[in] pos The new position in bytes from the beginning of the file. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool seekSet(uint32_t pos); - /** Set the current working directory. - * - * \param[in] dir New current working directory. - * - * \return true for success else false. - */ - static bool setCwd(FatFile* dir) { - if (!dir->isDir()) { - return false; - } - m_cwd = dir; - return true; - } - /** \return first block of file or zero for empty file. */ - uint32_t firstBlock() { - if (m_firstCluster) { - return m_vol->clusterFirstBlock(m_firstCluster); - } - return 0; - } - /** The sync() call causes all modified data and directory fields - * to be written to the storage device. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool sync(); - /** Copy a file's timestamps - * - * \param[in] file File to copy timestamps from. - * - * \note - * Modify and access timestamps may be overwritten if a date time callback - * function has been set by dateTimeCallback(). - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool timestamp(FatFile* file); - /** Set a file's timestamps in its directory entry. - * - * \param[in] flags Values for \a flags are constructed by a bitwise-inclusive - * OR of flags from the following list - * - * T_ACCESS - Set the file's last access date. - * - * T_CREATE - Set the file's creation date and time. - * - * T_WRITE - Set the file's last write/modification date and time. - * - * \param[in] year Valid range 1980 - 2107 inclusive. - * - * \param[in] month Valid range 1 - 12 inclusive. - * - * \param[in] day Valid range 1 - 31 inclusive. - * - * \param[in] hour Valid range 0 - 23 inclusive. - * - * \param[in] minute Valid range 0 - 59 inclusive. - * - * \param[in] second Valid range 0 - 59 inclusive - * - * \note It is possible to set an invalid date since there is no check for - * the number of days in a month. - * - * \note - * Modify and access timestamps may be overwritten if a date time callback - * function has been set by dateTimeCallback(). - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool timestamp(uint8_t flags, uint16_t year, uint8_t month, uint8_t day, - uint8_t hour, uint8_t minute, uint8_t second); - /** Type of file. You should use isFile() or isDir() instead of fileType() - * if possible. - * - * \return The file or directory type. - */ - uint8_t fileAttr() const { - return m_attr; - } - /** Truncate a file to a specified length. The current file position - * will be maintained if it is less than or equal to \a length otherwise - * it will be set to end of file. - * - * \param[in] length The desired length for the file. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool truncate(uint32_t length); - /** \return FatVolume that contains this file. */ - FatVolume* volume() const { - return m_vol; - } - /** Write a string to a file. Used by the Arduino Print class. - * \param[in] str Pointer to the string. - * Use getWriteError to check for errors. - * \return count of characters written for success or -1 for failure. - */ - int write(const char* str) { - return write(str, strlen(str)); - } - /** Write a single byte. - * \param[in] b The byte to be written. - * \return +1 for success or -1 for failure. - */ - int write(uint8_t b) { - return write(&b, 1); - } - /** Write data to an open file. - * - * \note Data is moved to the cache but may not be written to the - * storage device until sync() is called. - * - * \param[in] buf Pointer to the location of the data to be written. - * - * \param[in] nbyte Number of bytes to write. - * - * \return For success write() returns the number of bytes written, always - * \a nbyte. If an error occurs, write() returns -1. Possible errors - * include write() is called before a file has been opened, write is called - * for a read-only file, device is full, a corrupt file system or an I/O error. - * - */ - int write(const void* buf, size_t nbyte); -//------------------------------------------------------------------------------ - private: - /** This file has not been opened. */ - static const uint8_t FILE_ATTR_CLOSED = 0; - /** File is read-only. */ - static const uint8_t FILE_ATTR_READ_ONLY = DIR_ATT_READ_ONLY; - /** File should be hidden in directory listings. */ - static const uint8_t FILE_ATTR_HIDDEN = DIR_ATT_HIDDEN; - /** Entry is for a system file. */ - static const uint8_t FILE_ATTR_SYSTEM = DIR_ATT_SYSTEM; - /** Entry for normal data file */ - static const uint8_t FILE_ATTR_FILE = 0X08; - /** Entry is for a subdirectory */ - static const uint8_t FILE_ATTR_SUBDIR = DIR_ATT_DIRECTORY; - /** A FAT12 or FAT16 root directory */ - static const uint8_t FILE_ATTR_ROOT_FIXED = 0X20; - /** A FAT32 root directory */ - static const uint8_t FILE_ATTR_ROOT32 = 0X40; - /** Entry is for root. */ - static const uint8_t FILE_ATTR_ROOT = FILE_ATTR_ROOT_FIXED | FILE_ATTR_ROOT32; - /** Directory type bits */ - static const uint8_t FILE_ATTR_DIR = FILE_ATTR_SUBDIR | FILE_ATTR_ROOT; - /** Attributes to copy from directory entry */ - static const uint8_t FILE_ATTR_COPY = DIR_ATT_READ_ONLY | DIR_ATT_HIDDEN | - DIR_ATT_SYSTEM | DIR_ATT_DIRECTORY; - - /** experimental don't use */ - - bool openParent(FatFile* dir); - - // private functions - bool addCluster(); - bool addDirCluster(); - dir_t* cacheDirEntry(uint8_t action); - static uint8_t lfnChecksum(uint8_t* name); - bool lfnUniqueSfn(fname_t* fname); - bool openCluster(FatFile* file); - static bool parsePathName(const char* str, fname_t* fname, const char** ptr); - bool mkdir(FatFile* parent, fname_t* fname); - bool open(FatFile* dirFile, fname_t* fname, oflag_t oflag); - bool openCachedEntry(FatFile* dirFile, uint16_t cacheIndex, oflag_t oflag, - uint8_t lfnOrd); - bool readLBN(uint32_t* lbn); - dir_t* readDirCache(bool skipReadOk = false); - bool setDirSize(); - - // bits defined in m_flags - static const uint8_t F_READ = 0X01; - static const uint8_t F_WRITE = 0X02; - static const uint8_t F_FILE_DIR_DIRTY = 0X04; - static const uint8_t F_APPEND = 0X08; - static const uint8_t F_SYNC = 0X80; - - - // global pointer to cwd dir - static FatFile* m_cwd; - // data time callback function - static void (*m_dateTime)(uint16_t* date, uint16_t* time); - // private data - static const uint8_t WRITE_ERROR = 0X1; - static const uint8_t READ_ERROR = 0X2; - uint8_t m_attr; // File attributes - uint8_t m_error; // Error bits. - uint8_t m_flags; // See above for definition of m_flags bits - uint8_t m_lfnOrd; - uint16_t m_dirIndex; // index of directory entry in dir file - FatVolume* m_vol; // volume where file is located - uint32_t m_dirCluster; - uint32_t m_curCluster; // cluster for current file position - uint32_t m_curPosition; // current file position - uint32_t m_dirBlock; // block for this files directory entry - uint32_t m_fileSize; // file size in bytes - uint32_t m_firstCluster; // first cluster of file -}; -#endif // FatFile_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileLFN.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileLFN.cpp deleted file mode 100644 index f7e4627..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileLFN.cpp +++ /dev/null @@ -1,688 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#include "FatFile.h" -//------------------------------------------------------------------------------ -// -uint8_t FatFile::lfnChecksum(uint8_t* name) { - uint8_t sum = 0; - for (uint8_t i = 0; i < 11; i++) { - sum = (((sum & 1) << 7) | ((sum & 0xfe) >> 1)) + name[i]; - } - return sum; -} -#if USE_LONG_FILE_NAMES -//------------------------------------------------------------------------------ -// Saves about 90 bytes of flash on 328 over tolower(). -inline char lfnToLower(char c) { - return 'A' <= c && c <= 'Z' ? c + 'a' - 'A' : c; -} -//------------------------------------------------------------------------------ -// Daniel Bernstein University of Illinois at Chicago. -// Original had + instead of ^ -static uint16_t Bernstein(uint16_t hash, const char *str, size_t len) { - for (size_t i = 0; i < len; i++) { - // hash = hash * 33 ^ str[i]; - hash = ((hash << 5) + hash) ^ str[i]; - } - return hash; -} -//------------------------------------------------------------------------------ -/** - * Fetch a 16-bit long file name character. - * - * \param[in] ldir Pointer to long file name directory entry. - * \param[in] i Index of character. - * \return The 16-bit character. - */ -static uint16_t lfnGetChar(ldir_t *ldir, uint8_t i) { - if (i < LDIR_NAME1_DIM) { - return ldir->name1[i]; - } else if (i < (LDIR_NAME1_DIM + LDIR_NAME2_DIM)) { - return ldir->name2[i - LDIR_NAME1_DIM]; - } else if (i < (LDIR_NAME1_DIM + LDIR_NAME2_DIM + LDIR_NAME2_DIM)) { - return ldir->name3[i - LDIR_NAME1_DIM - LDIR_NAME2_DIM]; - } - return 0; -} -//------------------------------------------------------------------------------ -static bool lfnGetName(ldir_t *ldir, char* name, size_t n) { - uint8_t i; - size_t k = 13*((ldir->ord & 0X1F) - 1); - for (i = 0; i < 13; i++) { - uint16_t c = lfnGetChar(ldir, i); - if (c == 0 || k >= n) { - break; - } - name[k++] = c >= 0X7F ? '?' : c; - } - // Terminate with zero byte if name fits. - if (k < n && (ldir->ord & LDIR_ORD_LAST_LONG_ENTRY)) { - name[k] = 0; - } - // Truncate if name is too long. - name[n - 1] = 0; - return true; -} -//------------------------------------------------------------------------------ -inline bool lfnLegalChar(char c) { - if (c == '/' || c == '\\' || c == '"' || c == '*' || - c == ':' || c == '<' || c == '>' || c == '?' || c == '|') { - return false; - } - return 0X1F < c && c < 0X7F; -} -//------------------------------------------------------------------------------ -/** - * Store a 16-bit long file name character. - * - * \param[in] ldir Pointer to long file name directory entry. - * \param[in] i Index of character. - * \param[in] c The 16-bit character. - */ -static void lfnPutChar(ldir_t *ldir, uint8_t i, uint16_t c) { - if (i < LDIR_NAME1_DIM) { - ldir->name1[i] = c; - } else if (i < (LDIR_NAME1_DIM + LDIR_NAME2_DIM)) { - ldir->name2[i - LDIR_NAME1_DIM] = c; - } else if (i < (LDIR_NAME1_DIM + LDIR_NAME2_DIM + LDIR_NAME2_DIM)) { - ldir->name3[i - LDIR_NAME1_DIM - LDIR_NAME2_DIM] = c; - } -} -//------------------------------------------------------------------------------ -static void lfnPutName(ldir_t *ldir, const char* name, size_t n) { - size_t k = 13*((ldir->ord & 0X1F) - 1); - for (uint8_t i = 0; i < 13; i++, k++) { - uint16_t c = k < n ? name[k] : k == n ? 0 : 0XFFFF; - lfnPutChar(ldir, i, c); - } -} -//============================================================================== -bool FatFile::getName(char* name, size_t size) { - FatFile dirFile; - ldir_t* ldir; - if (!isOpen() || size < 13) { - DBG_FAIL_MACRO; - goto fail; - } - if (!isLFN()) { - return getSFN(name); - } - if (!dirFile.openCluster(this)) { - DBG_FAIL_MACRO; - goto fail; - } - for (uint8_t ord = 1; ord <= m_lfnOrd; ord++) { - if (!dirFile.seekSet(32UL*(m_dirIndex - ord))) { - DBG_FAIL_MACRO; - goto fail; - } - ldir = reinterpret_cast(dirFile.readDirCache()); - if (!ldir) { - DBG_FAIL_MACRO; - goto fail; - } - if (ldir->attr != DIR_ATT_LONG_NAME) { - DBG_FAIL_MACRO; - goto fail; - } - if (ord != (ldir->ord & 0X1F)) { - DBG_FAIL_MACRO; - goto fail; - } - if (!lfnGetName(ldir, name, size)) { - DBG_FAIL_MACRO; - goto fail; - } - if (ldir->ord & LDIR_ORD_LAST_LONG_ENTRY) { - return true; - } - } - // Fall into fail. - DBG_FAIL_MACRO; - -fail: - name[0] = 0; - return false; -} -//------------------------------------------------------------------------------ -bool FatFile::openCluster(FatFile* file) { - if (file->m_dirCluster == 0) { - return openRoot(file->m_vol); - } - memset(this, 0, sizeof(FatFile)); - m_attr = FILE_ATTR_SUBDIR; - m_flags = F_READ; - m_vol = file->m_vol; - m_firstCluster = file->m_dirCluster; - return true; -} -//------------------------------------------------------------------------------ -bool FatFile::parsePathName(const char* path, - fname_t* fname, const char** ptr) { - char c; - bool is83; - uint8_t bit = DIR_NT_LC_BASE; - uint8_t lc = 0; - uint8_t uc = 0; - uint8_t i = 0; - uint8_t in = 7; - int end; - int len = 0; - int si; - int dot; - - // Skip leading spaces. - while (*path == ' ') { - path++; - } - fname->lfn = path; - - for (len = 0; ; len++) { - c = path[len]; - if (c == 0 || isDirSeparator(c)) { - break; - } - if (!lfnLegalChar(c)) { - return false; - } - } - // Advance to next path component. - for (end = len; path[end] == ' ' || isDirSeparator(path[end]); end++) {} - *ptr = &path[end]; - - // Back over spaces and dots. - while (len) { - c = path[len - 1]; - if (c != '.' && c != ' ') { - break; - } - len--; - } - // Max length of LFN is 255. - if (len > 255) { - return false; - } - fname->len = len; - // Blank file short name. - for (uint8_t k = 0; k < 11; k++) { - fname->sfn[k] = ' '; - } - // skip leading spaces and dots. - for (si = 0; path[si] == '.' || path[si] == ' '; si++) {} - // Not 8.3 if leading dot or space. - is83 = !si; - - // find last dot. - for (dot = len - 1; dot >= 0 && path[dot] != '.'; dot--) {} - for (; si < len; si++) { - c = path[si]; - if (c == ' ' || (c == '.' && dot != si)) { - is83 = false; - continue; - } - if (!legal83Char(c) && si != dot) { - is83 = false; - c = '_'; - } - if (si == dot || i > in) { - if (in == 10) { - // Done - extension longer than three characters. - is83 = false; - break; - } - if (si != dot) { - is83 = false; - } - // Break if no dot and base-name is longer than eight characters. - if (si > dot) { - break; - } - si = dot; - in = 10; // Max index for full 8.3 name. - i = 8; // Place for extension. - bit = DIR_NT_LC_EXT; // bit for extension. - } else { - if ('a' <= c && c <= 'z') { - c += 'A' - 'a'; - lc |= bit; - } else if ('A' <= c && c <= 'Z') { - uc |= bit; - } - fname->sfn[i++] = c; - if (i < 7) { - fname->seqPos = i; - } - } - } - if (fname->sfn[0] == ' ') { - return false; - } - - if (is83) { - fname->flags = lc & uc ? FNAME_FLAG_MIXED_CASE : lc; - } else { - fname->flags = FNAME_FLAG_LOST_CHARS; - fname->sfn[fname->seqPos] = '~'; - fname->sfn[fname->seqPos + 1] = '1'; - } - return true; -} -//------------------------------------------------------------------------------ -bool FatFile::open(FatFile* dirFile, fname_t* fname, oflag_t oflag) { - bool fnameFound = false; - uint8_t lfnOrd = 0; - uint8_t freeNeed; - uint8_t freeFound = 0; - uint8_t ord = 0; - uint8_t chksum = 0; - uint16_t freeIndex = 0; - uint16_t curIndex; - dir_t* dir; - ldir_t* ldir; - size_t len = fname->len; - - if (!dirFile->isDir() || isOpen()) { - DBG_FAIL_MACRO; - goto fail; - } - // Number of directory entries needed. - freeNeed = fname->flags & FNAME_FLAG_NEED_LFN ? 1 + (len + 12)/13 : 1; - - dirFile->rewind(); - while (1) { - curIndex = dirFile->m_curPosition/32; - dir = dirFile->readDirCache(true); - if (!dir) { - if (dirFile->getError()) { - DBG_FAIL_MACRO; - goto fail; - } - // At EOF - goto create; - } - if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == DIR_NAME_FREE) { - if (freeFound == 0) { - freeIndex = curIndex; - } - if (freeFound < freeNeed) { - freeFound++; - } - if (dir->name[0] == DIR_NAME_FREE) { - goto create; - } - } else { - if (freeFound < freeNeed) { - freeFound = 0; - } - } - // skip empty slot or '.' or '..' - if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') { - lfnOrd = 0; - } else if (DIR_IS_LONG_NAME(dir)) { - ldir_t *ldir = reinterpret_cast(dir); - if (!lfnOrd) { - if ((ldir->ord & LDIR_ORD_LAST_LONG_ENTRY) == 0) { - continue; - } - lfnOrd = ord = ldir->ord & 0X1F; - chksum = ldir->chksum; - } else if (ldir->ord != --ord || chksum != ldir->chksum) { - lfnOrd = 0; - continue; - } - size_t k = 13*(ord - 1); - if (k >= len) { - // Not found. - lfnOrd = 0; - continue; - } - for (uint8_t i = 0; i < 13; i++) { - uint16_t u = lfnGetChar(ldir, i); - if (k == len) { - if (u != 0) { - // Not found. - lfnOrd = 0; - } - break; - } - if (u > 255 || lfnToLower(u) != lfnToLower(fname->lfn[k++])) { - // Not found. - lfnOrd = 0; - break; - } - } - } else if (DIR_IS_FILE_OR_SUBDIR(dir)) { - if (lfnOrd) { - if (1 == ord && lfnChecksum(dir->name) == chksum) { - goto found; - } - DBG_FAIL_MACRO; - goto fail; - } - if (!memcmp(dir->name, fname->sfn, sizeof(fname->sfn))) { - if (!(fname->flags & FNAME_FLAG_LOST_CHARS)) { - goto found; - } - fnameFound = true; - } - } else { - lfnOrd = 0; - } - } - -found: - // Don't open if create only. - if (oflag & O_EXCL) { - DBG_FAIL_MACRO; - goto fail; - } - goto open; - -create: - // don't create unless O_CREAT and write mode. - if (!(oflag & O_CREAT) || !isWriteMode(oflag)) { - DBG_FAIL_MACRO; - goto fail; - } - // If at EOF start in next cluster. - if (freeFound == 0) { - freeIndex = curIndex; - } - - while (freeFound < freeNeed) { - dir = dirFile->readDirCache(); - if (!dir) { - if (dirFile->getError()) { - DBG_FAIL_MACRO; - goto fail; - } - // EOF if no error. - break; - } - freeFound++; - } - while (freeFound < freeNeed) { - // Will fail if FAT16 root. - if (!dirFile->addDirCluster()) { - DBG_FAIL_MACRO; - goto fail; - } - // Done if more than one block per cluster. Max freeNeed is 21. - if (dirFile->m_vol->blocksPerCluster() > 1) { - break; - } - freeFound += 16; - } - if (fnameFound) { - if (!dirFile->lfnUniqueSfn(fname)) { - goto fail; - } - } - if (!dirFile->seekSet(32UL*freeIndex)) { - DBG_FAIL_MACRO; - goto fail; - } - lfnOrd = freeNeed - 1; - for (uint8_t ord = lfnOrd ; ord ; ord--) { - ldir = reinterpret_cast(dirFile->readDirCache()); - if (!ldir) { - DBG_FAIL_MACRO; - goto fail; - } - dirFile->m_vol->cacheDirty(); - ldir->ord = ord == lfnOrd ? LDIR_ORD_LAST_LONG_ENTRY | ord : ord; - ldir->attr = DIR_ATT_LONG_NAME; - ldir->type = 0; - ldir->chksum = lfnChecksum(fname->sfn); - ldir->mustBeZero = 0; - lfnPutName(ldir, fname->lfn, len); - } - curIndex = dirFile->m_curPosition/32; - dir = dirFile->readDirCache(); - if (!dir) { - DBG_FAIL_MACRO; - goto fail; - } - // initialize as empty file - memset(dir, 0, sizeof(dir_t)); - memcpy(dir->name, fname->sfn, 11); - - // Set base-name and extension lower case bits. - dir->reservedNT = (DIR_NT_LC_BASE | DIR_NT_LC_EXT) & fname->flags; - - // set timestamps - if (m_dateTime) { - // call user date/time function - m_dateTime(&dir->creationDate, &dir->creationTime); - } else { - // use default date/time - dir->creationDate = FAT_DEFAULT_DATE; - dir->creationTime = FAT_DEFAULT_TIME; - } - dir->lastAccessDate = dir->creationDate; - dir->lastWriteDate = dir->creationDate; - dir->lastWriteTime = dir->creationTime; - - // Force write of entry to device. - dirFile->m_vol->cacheDirty(); - -open: - // open entry in cache. - if (!openCachedEntry(dirFile, curIndex, oflag, lfnOrd)) { - DBG_FAIL_MACRO; - goto fail; - } - return true; - -fail: - return false; -} -//------------------------------------------------------------------------------ -size_t FatFile::printName(print_t* pr) { - FatFile dirFile; - uint16_t u; - size_t n = 0; - ldir_t* ldir; - - if (!isLFN()) { - return printSFN(pr); - } - if (!dirFile.openCluster(this)) { - DBG_FAIL_MACRO; - goto fail; - } - for (uint8_t ord = 1; ord <= m_lfnOrd; ord++) { - if (!dirFile.seekSet(32UL*(m_dirIndex - ord))) { - DBG_FAIL_MACRO; - goto fail; - } - ldir = reinterpret_cast(dirFile.readDirCache()); - if (!ldir) { - DBG_FAIL_MACRO; - goto fail; - } - if (ldir->attr != DIR_ATT_LONG_NAME || - ord != (ldir->ord & 0X1F)) { - DBG_FAIL_MACRO; - goto fail; - } - for (uint8_t i = 0; i < 13; i++) { - u = lfnGetChar(ldir, i); - if (u == 0) { - // End of name. - break; - } - if (u > 0X7E) { - u = '?'; - } - pr->write(static_cast(u)); - n++; - } - if (ldir->ord & LDIR_ORD_LAST_LONG_ENTRY) { - return n; - } - } - // Fall into fail; - DBG_FAIL_MACRO; - -fail: - return 0; -} -//------------------------------------------------------------------------------ -bool FatFile::remove() { - bool last; - uint8_t chksum; - uint8_t ord; - FatFile dirFile; - dir_t* dir; - ldir_t* ldir; - - // Cant' remove not open for write. - if (!isFile() || !(m_flags & F_WRITE)) { - DBG_FAIL_MACRO; - goto fail; - } - // Free any clusters. - if (m_firstCluster && !m_vol->freeChain(m_firstCluster)) { - DBG_FAIL_MACRO; - goto fail; - } - // Cache directory entry. - dir = cacheDirEntry(FatCache::CACHE_FOR_WRITE); - if (!dir) { - DBG_FAIL_MACRO; - goto fail; - } - chksum = lfnChecksum(dir->name); - - // Mark entry deleted. - dir->name[0] = DIR_NAME_DELETED; - - // Set this file closed. - m_attr = FILE_ATTR_CLOSED; - - // Write entry to device. - if (!m_vol->cacheSync()) { - DBG_FAIL_MACRO; - goto fail; - } - if (!isLFN()) { - // Done, no LFN entries. - return true; - } - if (!dirFile.openCluster(this)) { - DBG_FAIL_MACRO; - goto fail; - } - for (ord = 1; ord <= m_lfnOrd; ord++) { - if (!dirFile.seekSet(32UL*(m_dirIndex - ord))) { - DBG_FAIL_MACRO; - goto fail; - } - ldir = reinterpret_cast(dirFile.readDirCache()); - if (!ldir) { - DBG_FAIL_MACRO; - goto fail; - } - if (ldir->attr != DIR_ATT_LONG_NAME || - ord != (ldir->ord & 0X1F) || - chksum != ldir->chksum) { - DBG_FAIL_MACRO; - goto fail; - } - last = ldir->ord & LDIR_ORD_LAST_LONG_ENTRY; - ldir->ord = DIR_NAME_DELETED; - m_vol->cacheDirty(); - if (last) { - if (!m_vol->cacheSync()) { - DBG_FAIL_MACRO; - goto fail; - } - return true; - } - } - // Fall into fail. - DBG_FAIL_MACRO; - -fail: - return false; -} -//------------------------------------------------------------------------------ -bool FatFile::lfnUniqueSfn(fname_t* fname) { - const uint8_t FIRST_HASH_SEQ = 2; // min value is 2 - uint8_t pos = fname->seqPos;; - dir_t *dir; - uint16_t hex; - - DBG_HALT_IF(!(fname->flags & FNAME_FLAG_LOST_CHARS)); - DBG_HALT_IF(fname->sfn[pos] != '~' && fname->sfn[pos + 1] != '1'); - - for (uint8_t seq = 2; seq < 100; seq++) { - if (seq < FIRST_HASH_SEQ) { - fname->sfn[pos + 1] = '0' + seq; - } else { - DBG_PRINT_IF(seq > FIRST_HASH_SEQ); - hex = Bernstein(seq + fname->len, fname->lfn, fname->len); - if (pos > 3) { - // Make space in name for ~HHHH. - pos = 3; - } - for (uint8_t i = pos + 4 ; i > pos; i--) { - uint8_t h = hex & 0XF; - fname->sfn[i] = h < 10 ? h + '0' : h + 'A' - 10; - hex >>= 4; - } - } - fname->sfn[pos] = '~'; - rewind(); - while (1) { - dir = readDirCache(true); - if (!dir) { - if (!getError()) { - // At EOF and name not found if no error. - goto done; - } - DBG_FAIL_MACRO; - goto fail; - } - if (dir->name[0] == DIR_NAME_FREE) { - goto done; - } - if (DIR_IS_FILE_OR_SUBDIR(dir) && !memcmp(fname->sfn, dir->name, 11)) { - // Name found - try another. - break; - } - } - } - // fall inti fail - too many tries. - DBG_FAIL_MACRO; - -fail: - return false; - -done: - return true; -} -#endif // #if USE_LONG_FILE_NAMES diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFilePrint.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFilePrint.cpp deleted file mode 100644 index bc1b00e..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFilePrint.cpp +++ /dev/null @@ -1,267 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#include -#include "FatFile.h" -#include "FmtNumber.h" -//------------------------------------------------------------------------------ -// print uint8_t with width 2 -static void print2u(print_t* pr, uint8_t v) { - char c0 = '?'; - char c1 = '?'; - if (v < 100) { - c1 = v/10; - c0 = v - 10*c1 + '0'; - c1 += '0'; - } - pr->write(c1); - pr->write(c0); -} -//------------------------------------------------------------------------------ -static void printU32(print_t* pr, uint32_t v) { - char buf[11]; - char* ptr = buf + sizeof(buf); - *--ptr = 0; - pr->write(fmtDec(v, ptr)); -} -//------------------------------------------------------------------------------ -static void printHex(print_t* pr, uint8_t w, uint16_t h) { - char buf[5]; - char* ptr = buf + sizeof(buf); - *--ptr = 0; - for (uint8_t i = 0; i < w; i++) { - char c = h & 0XF; - *--ptr = c < 10 ? c + '0' : c + 'A' - 10; - h >>= 4; - } - pr->write(ptr); -} -//------------------------------------------------------------------------------ -void FatFile::dmpFile(print_t* pr, uint32_t pos, size_t n) { - char text[17]; - text[16] = 0; - if (n >= 0XFFF0) { - n = 0XFFF0; - } - if (!seekSet(pos)) { - return; - } - for (size_t i = 0; i <= n; i++) { - if ((i & 15) == 0) { - if (i) { - pr->write(' '); - pr->write(text); - if (i == n) { - break; - } - } - pr->write('\r'); - pr->write('\n'); - if (i >= n) { - break; - } - printHex(pr, 4, i); - pr->write(' '); - } - int16_t h = read(); - if (h < 0) { - break; - } - pr->write(' '); - printHex(pr, 2, h); - text[i&15] = ' ' <= h && h < 0X7F ? h : '.'; - } - pr->write('\r'); - pr->write('\n'); -} -//------------------------------------------------------------------------------ -bool FatFile::ls(print_t* pr, uint8_t flags, uint8_t indent) { - FatFile file; - if (!isDir() || getError()) { - DBG_FAIL_MACRO; - goto fail; - } - rewind(); - while (file.openNext(this, O_RDONLY)) { - if (!file.isHidden() || (flags & LS_A)) { - // indent for dir level - for (uint8_t i = 0; i < indent; i++) { - pr->write(' '); - } - if (flags & LS_DATE) { - file.printModifyDateTime(pr); - pr->write(' '); - } - if (flags & LS_SIZE) { - file.printFileSize(pr); - pr->write(' '); - } - file.printName(pr); - if (file.isDir()) { - pr->write('/'); - } - pr->write('\r'); - pr->write('\n'); - if ((flags & LS_R) && file.isDir()) { - if (!file.ls(pr, flags, indent + 2)) { - DBG_FAIL_MACRO; - goto fail; - } - } - } - file.close(); - } - if (getError()) { - DBG_FAIL_MACRO; - goto fail; - } - return true; - - fail: - return false; -} -//------------------------------------------------------------------------------ -bool FatFile::printCreateDateTime(print_t* pr) { - dir_t dir; - if (!dirEntry(&dir)) { - DBG_FAIL_MACRO; - goto fail; - } - printFatDate(pr, dir.creationDate); - pr->write(' '); - printFatTime(pr, dir.creationTime); - return true; - -fail: - return false; -} -//------------------------------------------------------------------------------ -void FatFile::printFatDate(print_t* pr, uint16_t fatDate) { - printU32(pr, FAT_YEAR(fatDate)); - pr->write('-'); - print2u(pr, FAT_MONTH(fatDate)); - pr->write('-'); - print2u(pr, FAT_DAY(fatDate)); -} -//------------------------------------------------------------------------------ -void FatFile::printFatTime(print_t* pr, uint16_t fatTime) { - print2u(pr, FAT_HOUR(fatTime)); - pr->write(':'); - print2u(pr, FAT_MINUTE(fatTime)); - pr->write(':'); - print2u(pr, FAT_SECOND(fatTime)); -} -//------------------------------------------------------------------------------ -/** Template for FatFile::printField() */ -template -static int printFieldT(FatFile* file, char sign, Type value, char term) { - char buf[3*sizeof(Type) + 3]; - char* str = &buf[sizeof(buf)]; - - if (term) { - *--str = term; - if (term == '\n') { - *--str = '\r'; - } - } -#ifdef OLD_FMT - do { - Type m = value; - value /= 10; - *--str = '0' + m - 10*value; - } while (value); -#else // OLD_FMT - str = fmtDec(value, str); -#endif // OLD_FMT - if (sign) { - *--str = sign; - } - return file->write(str, &buf[sizeof(buf)] - str); -} -//------------------------------------------------------------------------------ - -int FatFile::printField(float value, char term, uint8_t prec) { - char buf[24]; - char* str = &buf[sizeof(buf)]; - if (term) { - *--str = term; - if (term == '\n') { - *--str = '\r'; - } - } - str = fmtFloat(value, str, prec); - return write(str, buf + sizeof(buf) - str); -} -//------------------------------------------------------------------------------ -int FatFile::printField(uint16_t value, char term) { - return printFieldT(this, 0, value, term); -} -//------------------------------------------------------------------------------ -int FatFile::printField(int16_t value, char term) { - char sign = 0; - if (value < 0) { - sign = '-'; - value = -value; - } - return printFieldT(this, sign, (uint16_t)value, term); -} -//------------------------------------------------------------------------------ -int FatFile::printField(uint32_t value, char term) { - return printFieldT(this, 0, value, term); -} -//------------------------------------------------------------------------------ -int FatFile::printField(int32_t value, char term) { - char sign = 0; - if (value < 0) { - sign = '-'; - value = -value; - } - return printFieldT(this, sign, (uint32_t)value, term); -} -//------------------------------------------------------------------------------ -bool FatFile::printModifyDateTime(print_t* pr) { - dir_t dir; - if (!dirEntry(&dir)) { - DBG_FAIL_MACRO; - goto fail; - } - printFatDate(pr, dir.lastWriteDate); - pr->write(' '); - printFatTime(pr, dir.lastWriteTime); - return true; - -fail: - return false; -} -//------------------------------------------------------------------------------ -size_t FatFile::printFileSize(print_t* pr) { - char buf[11]; - char *ptr = buf + sizeof(buf); - *--ptr = 0; - ptr = fmtDec(fileSize(), ptr); - while (ptr > buf) { - *--ptr = ' '; - } - return pr->write(buf); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileSFN.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileSFN.cpp deleted file mode 100644 index c49b4be..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileSFN.cpp +++ /dev/null @@ -1,278 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#include "FatFile.h" -#include "FatFileSystem.h" -//------------------------------------------------------------------------------ -bool FatFile::getSFN(char* name) { - dir_t* dir; - if (!isOpen()) { - DBG_FAIL_MACRO; - goto fail; - } - if (isRoot()) { - name[0] = '/'; - name[1] = '\0'; - return true; - } - // cache entry - dir = cacheDirEntry(FatCache::CACHE_FOR_READ); - if (!dir) { - DBG_FAIL_MACRO; - goto fail; - } - // format name - dirName(dir, name); - return true; - -fail: - return false; -} -//------------------------------------------------------------------------------ -size_t FatFile::printSFN(print_t* pr) { - char name[13]; - if (!getSFN(name)) { - DBG_FAIL_MACRO; - goto fail; - } - return pr->write(name); - -fail: - return 0; -} -#if !USE_LONG_FILE_NAMES -//------------------------------------------------------------------------------ -bool FatFile::getName(char* name, size_t size) { - return size < 13 ? 0 : getSFN(name); -} -//------------------------------------------------------------------------------ -// format directory name field from a 8.3 name string -bool FatFile::parsePathName(const char* path, fname_t* fname, - const char** ptr) { - uint8_t uc = 0; - uint8_t lc = 0; - uint8_t bit = FNAME_FLAG_LC_BASE; - // blank fill name and extension - for (uint8_t i = 0; i < 11; i++) { - fname->sfn[i] = ' '; - } - - for (uint8_t i = 0, n = 7;; path++) { - uint8_t c = *path; - if (c == 0 || isDirSeparator(c)) { - // Done. - break; - } - if (c == '.' && n == 7) { - n = 10; // max index for full 8.3 name - i = 8; // place for extension - - // bit for extension. - bit = FNAME_FLAG_LC_EXT; - } else { - if (!legal83Char(c) || i > n) { - DBG_FAIL_MACRO; - goto fail; - } - if ('a' <= c && c <= 'z') { - c += 'A' - 'a'; - lc |= bit; - } else if ('A' <= c && c <= 'Z') { - uc |= bit; - } - fname->sfn[i++] = c; - } - } - // must have a file name, extension is optional - if (fname->sfn[0] == ' ') { - DBG_FAIL_MACRO; - goto fail; - } - // Set base-name and extension bits. - fname->flags = lc & uc ? 0 : lc; - while (isDirSeparator(*path)) { - path++; - } - *ptr = path; - return true; - -fail: - return false; -} -//------------------------------------------------------------------------------ -// open with filename in fname -#define SFN_OPEN_USES_CHKSUM 0 -bool FatFile::open(FatFile* dirFile, fname_t* fname, oflag_t oflag) { - bool emptyFound = false; -#if SFN_OPEN_USES_CHKSUM - uint8_t chksum; -#endif - uint8_t lfnOrd = 0; - uint16_t emptyIndex; - uint16_t index = 0; - dir_t* dir; - ldir_t* ldir; - - dirFile->rewind(); - while (1) { - if (!emptyFound) { - emptyIndex = index; - } - dir = dirFile->readDirCache(true); - if (!dir) { - if (dirFile->getError()) { - DBG_FAIL_MACRO; - goto fail; - } - // At EOF if no error. - break; - } - if (dir->name[0] == DIR_NAME_FREE) { - emptyFound = true; - break; - } - if (dir->name[0] == DIR_NAME_DELETED) { - lfnOrd = 0; - emptyFound = true; - } else if (DIR_IS_FILE_OR_SUBDIR(dir)) { - if (!memcmp(fname->sfn, dir->name, 11)) { - // don't open existing file if O_EXCL - if (oflag & O_EXCL) { - DBG_FAIL_MACRO; - goto fail; - } -#if SFN_OPEN_USES_CHKSUM - if (lfnOrd && chksum != lfnChecksum(dir->name)) { - DBG_FAIL_MACRO; - goto fail; - } -#endif // SFN_OPEN_USES_CHKSUM - if (!openCachedEntry(dirFile, index, oflag, lfnOrd)) { - DBG_FAIL_MACRO; - goto fail; - } - return true; - } else { - lfnOrd = 0; - } - } else if (DIR_IS_LONG_NAME(dir)) { - ldir = reinterpret_cast(dir); - if (ldir->ord & LDIR_ORD_LAST_LONG_ENTRY) { - lfnOrd = ldir->ord & 0X1F; -#if SFN_OPEN_USES_CHKSUM - chksum = ldir->chksum; -#endif // SFN_OPEN_USES_CHKSUM - } - } else { - lfnOrd = 0; - } - index++; - } - // don't create unless O_CREAT and write mode - if (!(oflag & O_CREAT) || !isWriteMode(oflag)) { - DBG_FAIL_MACRO; - goto fail; - } - if (emptyFound) { - index = emptyIndex; - } else { - if (!dirFile->addDirCluster()) { - DBG_FAIL_MACRO; - goto fail; - } - } - if (!dirFile->seekSet(32UL*index)) { - DBG_FAIL_MACRO; - goto fail; - } - dir = dirFile->readDirCache(); - if (!dir) { - DBG_FAIL_MACRO; - goto fail; - } - // initialize as empty file - memset(dir, 0, sizeof(dir_t)); - memcpy(dir->name, fname->sfn, 11); - - // Set base-name and extension lower case bits. - dir->reservedNT = (DIR_NT_LC_BASE | DIR_NT_LC_EXT) & fname->flags; - - // set timestamps - if (m_dateTime) { - // call user date/time function - m_dateTime(&dir->creationDate, &dir->creationTime); - } else { - // use default date/time - dir->creationDate = FAT_DEFAULT_DATE; - dir->creationTime = FAT_DEFAULT_TIME; - } - dir->lastAccessDate = dir->creationDate; - dir->lastWriteDate = dir->creationDate; - dir->lastWriteTime = dir->creationTime; - - // Force write of entry to device. - dirFile->m_vol->cacheDirty(); - - // open entry in cache. - return openCachedEntry(dirFile, index, oflag, 0); - -fail: - return false; -} -//------------------------------------------------------------------------------ -size_t FatFile::printName(print_t* pr) { - return printSFN(pr); -} -//------------------------------------------------------------------------------ -bool FatFile::remove() { - dir_t* dir; - // Can't remove if LFN or not open for write. - if (!isFile() || isLFN() || !(m_flags & F_WRITE)) { - DBG_FAIL_MACRO; - goto fail; - } - // Free any clusters. - if (m_firstCluster && !m_vol->freeChain(m_firstCluster)) { - DBG_FAIL_MACRO; - goto fail; - } - // Cache directory entry. - dir = cacheDirEntry(FatCache::CACHE_FOR_WRITE); - if (!dir) { - DBG_FAIL_MACRO; - goto fail; - } - // Mark entry deleted. - dir->name[0] = DIR_NAME_DELETED; - - // Set this file closed. - m_attr = FILE_ATTR_CLOSED; - - // Write entry to device. - return m_vol->cacheSync(); - -fail: - return false; -} -#endif // !USE_LONG_FILE_NAMES diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileSystem.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileSystem.h deleted file mode 100644 index 4c78b13..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatFileSystem.h +++ /dev/null @@ -1,332 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 FatFileSystem_h -#define FatFileSystem_h -#include "FatVolume.h" -#include "FatFile.h" -#include "ArduinoFiles.h" -/** - * \file - * \brief FatFileSystem class - */ -//------------------------------------------------------------------------------ -/** - * \class FatFileSystem - * \brief Integration class for the FatLib library. - */ -class FatFileSystem : public FatVolume { - public: - /** - * Initialize an FatFileSystem object. - * \param[in] blockDev Device block driver. - * \param[in] part partition to initialize. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool begin(BlockDriver* blockDev, uint8_t part = 0) { - m_blockDev = blockDev; - vwd()->close(); - return (part ? init(part) : init(1) || init(0)) - && vwd()->openRoot(this) && FatFile::setCwd(vwd()); - } -#if ENABLE_ARDUINO_FEATURES - /** List the directory contents of the volume working directory to Serial. - * - * \param[in] flags The inclusive OR of - * - * LS_DATE - %Print file modification date - * - * LS_SIZE - %Print file size. - * - * LS_R - Recursive list of subdirectories. - * - * \return true for success or false if an error occurred. - */ - bool ls(uint8_t flags = 0) { - return ls(&Serial, flags); - } - /** List the directory contents of a directory to Serial. - * - * \param[in] path directory to list. - * - * \param[in] flags The inclusive OR of - * - * LS_DATE - %Print file modification date - * - * LS_SIZE - %Print file size. - * - * LS_R - Recursive list of subdirectories. - * - * \return true for success or false if an error occurred. - */ - bool ls(const char* path, uint8_t flags = 0) { - return ls(&Serial, path, flags); - } - /** open a file - * - * \param[in] path location of file to be opened. - * \param[in] oflag open flags. - * \return a File object. - */ - File open(const char *path, oflag_t oflag = FILE_READ) { - File tmpFile; - tmpFile.open(vwd(), path, oflag); - return tmpFile; - } - /** open a file - * - * \param[in] path location of file to be opened. - * \param[in] oflag open flags. - * \return a File object. - */ - File open(const String &path, oflag_t oflag = FILE_READ) { - return open(path.c_str(), oflag ); - } -#endif // ENABLE_ARDUINO_FEATURES - /** Change a volume's working directory to root - * - * Changes the volume's working directory to the SD's root directory. - * Optionally set the current working directory to the volume's - * working directory. - * - * \param[in] set_cwd Set the current working directory to this volume's - * working directory if true. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool chdir(bool set_cwd = false) { - vwd()->close(); - return vwd()->openRoot(this) && (set_cwd ? FatFile::setCwd(vwd()) : true); - } - /** Change a volume's working directory - * - * Changes the volume working directory to the \a path subdirectory. - * Optionally set the current working directory to the volume's - * working directory. - * - * Example: If the volume's working directory is "/DIR", chdir("SUB") - * will change the volume's working directory from "/DIR" to "/DIR/SUB". - * - * If path is "/", the volume's working directory will be changed to the - * root directory - * - * \param[in] path The name of the subdirectory. - * - * \param[in] set_cwd Set the current working directory to this volume's - * working directory if true. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - //---------------------------------------------------------------------------- - bool chdir(const char *path, bool set_cwd = false) { - FatFile dir; - if (path[0] == '/' && path[1] == '\0') { - return chdir(set_cwd); - } - if (!dir.open(vwd(), path, O_RDONLY)) { - goto fail; - } - if (!dir.isDir()) { - goto fail; - } - m_vwd = dir; - if (set_cwd) { - FatFile::setCwd(vwd()); - } - return true; - -fail: - return false; - } - //---------------------------------------------------------------------------- - /** Set the current working directory to a volume's working directory. - * - * This is useful with multiple SD cards. - * - * The current working directory is changed to this - * volume's working directory. - * - * This is like the Windows/DOS \: command. - */ - void chvol() { - FatFile::setCwd(vwd()); - } - //---------------------------------------------------------------------------- - /** - * Test for the existence of a file. - * - * \param[in] path Path of the file to be tested for. - * - * \return true if the file exists else false. - */ - bool exists(const char* path) { - return vwd()->exists(path); - } - //---------------------------------------------------------------------------- - /** List the directory contents of the volume working directory. - * - * \param[in] pr Print stream for list. - * - * \param[in] flags The inclusive OR of - * - * LS_DATE - %Print file modification date - * - * LS_SIZE - %Print file size. - * - * LS_R - Recursive list of subdirectories. - * - * \return true for success or false if an error occurred. - */ - bool ls(print_t* pr, uint8_t flags = 0) { - return vwd()->ls(pr, flags); - } - //---------------------------------------------------------------------------- - /** List the directory contents of a directory. - * - * \param[in] pr Print stream for list. - * - * \param[in] path directory to list. - * - * \param[in] flags The inclusive OR of - * - * LS_DATE - %Print file modification date - * - * LS_SIZE - %Print file size. - * - * LS_R - Recursive list of subdirectories. - * - * \return true for success or false if an error occurred. - */ - bool ls(print_t* pr, const char* path, uint8_t flags) { - FatFile dir; - return dir.open(vwd(), path, O_RDONLY) && dir.ls(pr, flags); - } - //---------------------------------------------------------------------------- - /** Make a subdirectory in the volume working directory. - * - * \param[in] path A path with a valid 8.3 DOS name for the subdirectory. - * - * \param[in] pFlag Create missing parent directories if true. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool mkdir(const char* path, bool pFlag = true) { - FatFile sub; - return sub.mkdir(vwd(), path, pFlag); - } - //---------------------------------------------------------------------------- - /** Remove a file from the volume working directory. - * - * \param[in] path A path with a valid 8.3 DOS name for the file. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool remove(const char* path) { - return FatFile::remove(vwd(), path); - } - //---------------------------------------------------------------------------- - /** Rename a file or subdirectory. - * - * \param[in] oldPath Path name to the file or subdirectory to be renamed. - * - * \param[in] newPath New path name of the file or subdirectory. - * - * The \a newPath object must not exist before the rename call. - * - * The file to be renamed must not be open. The directory entry may be - * moved and file system corruption could occur if the file is accessed by - * a file object that was opened before the rename() call. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool rename(const char *oldPath, const char *newPath) { - FatFile file; - if (!file.open(vwd(), oldPath, O_RDONLY)) { - return false; - } - return file.rename(vwd(), newPath); - } - //---------------------------------------------------------------------------- - /** Remove a subdirectory from the volume's working directory. - * - * \param[in] path A path with a valid 8.3 DOS name for the subdirectory. - * - * The subdirectory file will be removed only if it is empty. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool rmdir(const char* path) { - FatFile sub; - if (!sub.open(vwd(), path, O_RDONLY)) { - return false; - } - return sub.rmdir(); - } - //---------------------------------------------------------------------------- - /** Truncate a file to a specified length. The current file position - * will be maintained if it is less than or equal to \a length otherwise - * it will be set to end of file. - * - * \param[in] path A path with a valid 8.3 DOS name for the file. - * \param[in] length The desired length for the file. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool truncate(const char* path, uint32_t length) { - FatFile file; - if (!file.open(vwd(), path, O_WRONLY)) { - return false; - } - return file.truncate(length); - } - /** \return a pointer to the FatVolume object. */ - FatVolume* vol() { - return this; - } - /** \return a pointer to the volume working directory. */ - FatFile* vwd() { - return &m_vwd; - } - /** Wipe all data from the volume. You must reinitialize the volume before - * accessing it again. - * \param[in] pr print stream for status dots. - * \return true for success else false. - */ - bool wipe(print_t* pr = 0) { - vwd()->close(); - return FatVolume::wipe(pr); - } - - private: - FatFile m_vwd; -}; -#endif // FatFileSystem_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatLib.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatLib.h deleted file mode 100644 index 008979d..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatLib.h +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 FatLib_h -#define FatLib_h -#include "ArduinoFiles.h" -#include "FatFileSystem.h" -#include "FatLibConfig.h" -#include "FatVolume.h" -#include "FatFile.h" -#include "StdioStream.h" -//------------------------------------------------------------------------------ -/** FatFileSystem version YYYYMMDD */ -#define FAT_LIB_VERSION 20150131 -#endif // FatLib_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatLibConfig.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatLibConfig.h deleted file mode 100644 index 5036eb2..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatLibConfig.h +++ /dev/null @@ -1,146 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -/** - * \file - * \brief configuration definitions - */ -#ifndef FatLibConfig_h -#define FatLibConfig_h -#include -// Allow this file to override defaults. -#include "SdFatConfig.h" - -#ifdef __AVR__ -#include -#endif // __AVR__ -//------------------------------------------------------------------------------ -/** - * Set USE_LONG_FILE_NAMES nonzero to use long file names (LFN). - * Long File Name are limited to a maximum length of 255 characters. - * - * This implementation allows 7-bit characters in the range - * 0X20 to 0X7E. The following characters are not allowed: - * - * < (less than) - * > (greater than) - * : (colon) - * " (double quote) - * / (forward slash) - * \ (backslash) - * | (vertical bar or pipe) - * ? (question mark) - * * (asterisk) - * - */ -#ifndef USE_LONG_FILE_NAMES -#define USE_LONG_FILE_NAMES 1 -#endif // USE_LONG_FILE_NAMES -//------------------------------------------------------------------------------ -/** - * Set USE_SEPARATE_FAT_CACHE non-zero to use a second 512 byte cache - * for FAT table entries. Improves performance for large writes that - * are not a multiple of 512 bytes. - */ -#ifndef USE_SEPARATE_FAT_CACHE -#ifdef __arm__ -#define USE_SEPARATE_FAT_CACHE 1 -#else // __arm__ -#define USE_SEPARATE_FAT_CACHE 0 -#endif // __arm__ -#endif // USE_SEPARATE_FAT_CACHE -//------------------------------------------------------------------------------ -/** - * Set USE_MULTI_BLOCK_IO non-zero to use multi-block SD read/write. - * - * Don't use mult-block read/write on small AVR boards. - */ -#ifndef USE_MULTI_BLOCK_IO -#if defined(RAMEND) && RAMEND < 3000 -#define USE_MULTI_BLOCK_IO 0 -#else // RAMEND -#define USE_MULTI_BLOCK_IO 1 -#endif // RAMEND -#endif // USE_MULTI_BLOCK_IO -//------------------------------------------------------------------------------ -/** - * Set MAINTAIN_FREE_CLUSTER_COUNT nonzero to keep the count of free clusters - * updated. This will increase the speed of the freeClusterCount() call - * after the first call. Extra flash will be required. - */ -#ifndef MAINTAIN_FREE_CLUSTER_COUNT -#define MAINTAIN_FREE_CLUSTER_COUNT 0 -#endif // MAINTAIN_FREE_CLUSTER_COUNT -//------------------------------------------------------------------------------ -/** - * Set DESTRUCTOR_CLOSES_FILE non-zero to close a file in its destructor. - * - * Causes use of lots of heap in ARM. - */ -#ifndef DESTRUCTOR_CLOSES_FILE -#define DESTRUCTOR_CLOSES_FILE 0 -#endif // DESTRUCTOR_CLOSES_FILE -//------------------------------------------------------------------------------ -/** - * Call flush for endl if ENDL_CALLS_FLUSH is non-zero - * - * The standard for iostreams is to call flush. This is very costly for - * SdFat. Each call to flush causes 2048 bytes of I/O to the SD. - * - * SdFat has a single 512 byte buffer for I/O so it must write the current - * data block to the SD, read the directory block from the SD, update the - * directory entry, write the directory block to the SD and read the data - * block back into the buffer. - * - * The SD flash memory controller is not designed for this many rewrites - * so performance may be reduced by more than a factor of 100. - * - * If ENDL_CALLS_FLUSH is zero, you must call flush and/or close to force - * all data to be written to the SD. - */ -#ifndef ENDL_CALLS_FLUSH -#define ENDL_CALLS_FLUSH 0 -#endif // ENDL_CALLS_FLUSH -//------------------------------------------------------------------------------ -/** - * Allow FAT12 volumes if FAT12_SUPPORT is non-zero. - * FAT12 has not been well tested. - */ -#ifndef FAT12_SUPPORT -#define FAT12_SUPPORT 0 -#endif // FAT12_SUPPORT -//------------------------------------------------------------------------------ -/** - * Enable Extra features for Arduino. - */ -// #define ENABLE_ARDUINO_FEATURES 0 ////////////////////////FIX THIS ///////////////// -#ifndef ENABLE_ARDUINO_FEATURES -#include -#if defined(ARDUINO) || defined(PLATFORM_ID) || defined(DOXYGEN) -#define ENABLE_ARDUINO_FEATURES 1 -#else // #if defined(ARDUINO) || defined(DOXYGEN) -#define ENABLE_ARDUINO_FEATURES 0 -#endif // defined(ARDUINO) || defined(DOXYGEN) -#endif // ENABLE_ARDUINO_FEATURES -#endif // FatLibConfig_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatStructs.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatStructs.h deleted file mode 100644 index cf4ccb8..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatStructs.h +++ /dev/null @@ -1,882 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 FatStructs_h -#define FatStructs_h -/** - * \file - * \brief FAT file structures - */ -/* - * mostly from Microsoft document fatgen103.doc - * http://www.microsoft.com/whdc/system/platform/firmware/fatgen.mspx - */ -//------------------------------------------------------------------------------ -/** Value for byte 510 of boot block or MBR */ -const uint8_t BOOTSIG0 = 0X55; -/** Value for byte 511 of boot block or MBR */ -const uint8_t BOOTSIG1 = 0XAA; -/** Value for bootSignature field int FAT/FAT32 boot sector */ -const uint8_t EXTENDED_BOOT_SIG = 0X29; -//------------------------------------------------------------------------------ -/** - * \struct partitionTable - * \brief MBR partition table entry - * - * A partition table entry for a MBR formatted storage device. - * The MBR partition table has four entries. - */ -struct partitionTable { - /** - * Boot Indicator . Indicates whether the volume is the active - * partition. Legal values include: 0X00. Do not use for booting. - * 0X80 Active partition. - */ - uint8_t boot; - /** - * Head part of Cylinder-head-sector address of the first block in - * the partition. Legal values are 0-255. Only used in old PC BIOS. - */ - uint8_t beginHead; - /** - * Sector part of Cylinder-head-sector address of the first block in - * the partition. Legal values are 1-63. Only used in old PC BIOS. - */ - unsigned beginSector : 6; - /** High bits cylinder for first block in partition. */ - unsigned beginCylinderHigh : 2; - /** - * Combine beginCylinderLow with beginCylinderHigh. Legal values - * are 0-1023. Only used in old PC BIOS. - */ - uint8_t beginCylinderLow; - /** - * Partition type. See defines that begin with PART_TYPE_ for - * some Microsoft partition types. - */ - uint8_t type; - /** - * head part of cylinder-head-sector address of the last sector in the - * partition. Legal values are 0-255. Only used in old PC BIOS. - */ - uint8_t endHead; - /** - * Sector part of cylinder-head-sector address of the last sector in - * the partition. Legal values are 1-63. Only used in old PC BIOS. - */ - unsigned endSector : 6; - /** High bits of end cylinder */ - unsigned endCylinderHigh : 2; - /** - * Combine endCylinderLow with endCylinderHigh. Legal values - * are 0-1023. Only used in old PC BIOS. - */ - uint8_t endCylinderLow; - /** Logical block address of the first block in the partition. */ - uint32_t firstSector; - /** Length of the partition, in blocks. */ - uint32_t totalSectors; -} __attribute__((packed)); -/** Type name for partitionTable */ -typedef struct partitionTable part_t; -//------------------------------------------------------------------------------ -/** - * \struct masterBootRecord - * - * \brief Master Boot Record - * - * The first block of a storage device that is formatted with a MBR. - */ -struct masterBootRecord { - /** Code Area for master boot program. */ - uint8_t codeArea[440]; - /** Optional Windows NT disk signature. May contain boot code. */ - uint32_t diskSignature; - /** Usually zero but may be more boot code. */ - uint16_t usuallyZero; - /** Partition tables. */ - part_t part[4]; - /** First MBR signature byte. Must be 0X55 */ - uint8_t mbrSig0; - /** Second MBR signature byte. Must be 0XAA */ - uint8_t mbrSig1; -} __attribute__((packed)); -/** Type name for masterBootRecord */ -typedef struct masterBootRecord mbr_t; -//------------------------------------------------------------------------------ -/** - * \struct biosParmBlock - * - * \brief BIOS parameter block - * - * The BIOS parameter block describes the physical layout of a FAT volume. - */ -struct biosParmBlock { - /** - * Count of bytes per sector. This value may take on only the - * following values: 512, 1024, 2048 or 4096 - */ - uint16_t bytesPerSector; - /** - * Number of sectors per allocation unit. This value must be a - * power of 2 that is greater than 0. The legal values are - * 1, 2, 4, 8, 16, 32, 64, and 128. - */ - uint8_t sectorsPerCluster; - /** - * Number of sectors before the first FAT. - * This value must not be zero. - */ - uint16_t reservedSectorCount; - /** The count of FAT data structures on the volume. This field should - * always contain the value 2 for any FAT volume of any type. - */ - uint8_t fatCount; - /** - * For FAT12 and FAT16 volumes, this field contains the count of - * 32-byte directory entries in the root directory. For FAT32 volumes, - * this field must be set to 0. For FAT12 and FAT16 volumes, this - * value should always specify a count that when multiplied by 32 - * results in a multiple of bytesPerSector. FAT16 volumes should - * use the value 512. - */ - uint16_t rootDirEntryCount; - /** - * This field is the old 16-bit total count of sectors on the volume. - * This count includes the count of all sectors in all four regions - * of the volume. This field can be 0; if it is 0, then totalSectors32 - * must be nonzero. For FAT32 volumes, this field must be 0. For - * FAT12 and FAT16 volumes, this field contains the sector count, and - * totalSectors32 is 0 if the total sector count fits - * (is less than 0x10000). - */ - uint16_t totalSectors16; - /** - * This dates back to the old MS-DOS 1.x media determination and is - * no longer usually used for anything. 0xF8 is the standard value - * for fixed (nonremovable) media. For removable media, 0xF0 is - * frequently used. Legal values are 0xF0 or 0xF8-0xFF. - */ - uint8_t mediaType; - /** - * Count of sectors occupied by one FAT on FAT12/FAT16 volumes. - * On FAT32 volumes this field must be 0, and sectorsPerFat32 - * contains the FAT size count. - */ - uint16_t sectorsPerFat16; - /** Sectors per track for interrupt 0x13. Not used otherwise. */ - uint16_t sectorsPerTrtack; - /** Number of heads for interrupt 0x13. Not used otherwise. */ - uint16_t headCount; - /** - * Count of hidden sectors preceding the partition that contains this - * FAT volume. This field is generally only relevant for media - * visible on interrupt 0x13. - */ - uint32_t hidddenSectors; - /** - * This field is the new 32-bit total count of sectors on the volume. - * This count includes the count of all sectors in all four regions - * of the volume. This field can be 0; if it is 0, then - * totalSectors16 must be nonzero. - */ - uint32_t totalSectors32; - /** - * Count of sectors occupied by one FAT on FAT32 volumes. - */ - uint32_t sectorsPerFat32; - /** - * This field is only defined for FAT32 media and does not exist on - * FAT12 and FAT16 media. - * Bits 0-3 -- Zero-based number of active FAT. - * Only valid if mirroring is disabled. - * Bits 4-6 -- Reserved. - * Bit 7 -- 0 means the FAT is mirrored at runtime into all FATs. - * -- 1 means only one FAT is active; it is the one referenced in bits 0-3. - * Bits 8-15 -- Reserved. - */ - uint16_t fat32Flags; - /** - * FAT32 version. High byte is major revision number. - * Low byte is minor revision number. Only 0.0 define. - */ - uint16_t fat32Version; - /** - * Cluster number of the first cluster of the root directory for FAT32. - * This usually 2 but not required to be 2. - */ - uint32_t fat32RootCluster; - /** - * Sector number of FSINFO structure in the reserved area of the - * FAT32 volume. Usually 1. - */ - uint16_t fat32FSInfo; - /** - * If nonzero, indicates the sector number in the reserved area - * of the volume of a copy of the boot record. Usually 6. - * No value other than 6 is recommended. - */ - uint16_t fat32BackBootBlock; - /** - * Reserved for future expansion. Code that formats FAT32 volumes - * should always set all of the bytes of this field to 0. - */ - uint8_t fat32Reserved[12]; -} __attribute__((packed)); -/** Type name for biosParmBlock */ -typedef struct biosParmBlock bpb_t; -//------------------------------------------------------------------------------ -/** - * \struct fat_boot - * - * \brief Boot sector for a FAT12/FAT16 volume. - * - */ -struct fat_boot { - /** - * The first three bytes of the boot sector must be valid, - * executable x 86-based CPU instructions. This includes a - * jump instruction that skips the next non-executable bytes. - */ - uint8_t jump[3]; - /** - * This is typically a string of characters that identifies - * the operating system that formatted the volume. - */ - char oemId[8]; - /** - * The size of a hardware sector. Valid decimal values for this - * field are 512, 1024, 2048, and 4096. For most disks used in - * the United States, the value of this field is 512. - */ - uint16_t bytesPerSector; - /** - * Number of sectors per allocation unit. This value must be a - * power of 2 that is greater than 0. The legal values are - * 1, 2, 4, 8, 16, 32, 64, and 128. 128 should be avoided. - */ - uint8_t sectorsPerCluster; - /** - * The number of sectors preceding the start of the first FAT, - * including the boot sector. The value of this field is always 1. - */ - uint16_t reservedSectorCount; - /** - * The number of copies of the FAT on the volume. - * The value of this field is always 2. - */ - uint8_t fatCount; - /** - * For FAT12 and FAT16 volumes, this field contains the count of - * 32-byte directory entries in the root directory. For FAT32 volumes, - * this field must be set to 0. For FAT12 and FAT16 volumes, this - * value should always specify a count that when multiplied by 32 - * results in a multiple of bytesPerSector. FAT16 volumes should - * use the value 512. - */ - uint16_t rootDirEntryCount; - /** - * This field is the old 16-bit total count of sectors on the volume. - * This count includes the count of all sectors in all four regions - * of the volume. This field can be 0; if it is 0, then totalSectors32 - * must be non-zero. For FAT32 volumes, this field must be 0. For - * FAT12 and FAT16 volumes, this field contains the sector count, and - * totalSectors32 is 0 if the total sector count fits - * (is less than 0x10000). - */ - uint16_t totalSectors16; - /** - * This dates back to the old MS-DOS 1.x media determination and is - * no longer usually used for anything. 0xF8 is the standard value - * for fixed (non-removable) media. For removable media, 0xF0 is - * frequently used. Legal values are 0xF0 or 0xF8-0xFF. - */ - uint8_t mediaType; - /** - * Count of sectors occupied by one FAT on FAT12/FAT16 volumes. - * On FAT32 volumes this field must be 0, and sectorsPerFat32 - * contains the FAT size count. - */ - uint16_t sectorsPerFat16; - /** Sectors per track for interrupt 0x13. Not used otherwise. */ - uint16_t sectorsPerTrack; - /** Number of heads for interrupt 0x13. Not used otherwise. */ - uint16_t headCount; - /** - * Count of hidden sectors preceding the partition that contains this - * FAT volume. This field is generally only relevant for media - * visible on interrupt 0x13. - */ - uint32_t hidddenSectors; - /** - * This field is the new 32-bit total count of sectors on the volume. - * This count includes the count of all sectors in all four regions - * of the volume. This field can be 0; if it is 0, then - * totalSectors16 must be non-zero. - */ - uint32_t totalSectors32; - /** - * Related to the BIOS physical drive number. Floppy drives are - * identified as 0x00 and physical hard disks are identified as - * 0x80, regardless of the number of physical disk drives. - * Typically, this value is set prior to issuing an INT 13h BIOS - * call to specify the device to access. The value is only - * relevant if the device is a boot device. - */ - uint8_t driveNumber; - /** used by Windows NT - should be zero for FAT */ - uint8_t reserved1; - /** 0X29 if next three fields are valid */ - uint8_t bootSignature; - /** - * A random serial number created when formatting a disk, - * which helps to distinguish between disks. - * Usually generated by combining date and time. - */ - uint32_t volumeSerialNumber; - /** - * A field once used to store the volume label. The volume label - * is now stored as a special file in the root directory. - */ - char volumeLabel[11]; - /** - * A field with a value of either FAT, FAT12 or FAT16, - * depending on the disk format. - */ - char fileSystemType[8]; - /** X86 boot code */ - uint8_t bootCode[448]; - /** must be 0X55 */ - uint8_t bootSectorSig0; - /** must be 0XAA */ - uint8_t bootSectorSig1; -} __attribute__((packed)); -/** Type name for FAT Boot Sector */ -typedef struct fat_boot fat_boot_t; -//------------------------------------------------------------------------------ -/** - * \struct fat32_boot - * - * \brief Boot sector for a FAT32 volume. - * - */ -struct fat32_boot { - /** - * The first three bytes of the boot sector must be valid, - * executable x 86-based CPU instructions. This includes a - * jump instruction that skips the next non-executable bytes. - */ - uint8_t jump[3]; - /** - * This is typically a string of characters that identifies - * the operating system that formatted the volume. - */ - char oemId[8]; - /** - * The size of a hardware sector. Valid decimal values for this - * field are 512, 1024, 2048, and 4096. For most disks used in - * the United States, the value of this field is 512. - */ - uint16_t bytesPerSector; - /** - * Number of sectors per allocation unit. This value must be a - * power of 2 that is greater than 0. The legal values are - * 1, 2, 4, 8, 16, 32, 64, and 128. 128 should be avoided. - */ - uint8_t sectorsPerCluster; - /** - * The number of sectors preceding the start of the first FAT, - * including the boot sector. Must not be zero - */ - uint16_t reservedSectorCount; - /** - * The number of copies of the FAT on the volume. - * The value of this field is always 2. - */ - uint8_t fatCount; - /** - * FAT12/FAT16 only. For FAT32 volumes, this field must be set to 0. - */ - uint16_t rootDirEntryCount; - /** - * For FAT32 volumes, this field must be 0. - */ - uint16_t totalSectors16; - /** - * This dates back to the old MS-DOS 1.x media determination and is - * no longer usually used for anything. 0xF8 is the standard value - * for fixed (non-removable) media. For removable media, 0xF0 is - * frequently used. Legal values are 0xF0 or 0xF8-0xFF. - */ - uint8_t mediaType; - /** - * On FAT32 volumes this field must be 0, and sectorsPerFat32 - * contains the FAT size count. - */ - uint16_t sectorsPerFat16; - /** Sectors per track for interrupt 0x13. Not used otherwise. */ - uint16_t sectorsPerTrack; - /** Number of heads for interrupt 0x13. Not used otherwise. */ - uint16_t headCount; - /** - * Count of hidden sectors preceding the partition that contains this - * FAT volume. This field is generally only relevant for media - * visible on interrupt 0x13. - */ - uint32_t hidddenSectors; - /** - * Contains the total number of sectors in the FAT32 volume. - */ - uint32_t totalSectors32; - /** - * Count of sectors occupied by one FAT on FAT32 volumes. - */ - uint32_t sectorsPerFat32; - /** - * This field is only defined for FAT32 media and does not exist on - * FAT12 and FAT16 media. - * Bits 0-3 -- Zero-based number of active FAT. - * Only valid if mirroring is disabled. - * Bits 4-6 -- Reserved. - * Bit 7 -- 0 means the FAT is mirrored at runtime into all FATs. - * -- 1 means only one FAT is active; it is the one referenced - * in bits 0-3. - * Bits 8-15 -- Reserved. - */ - uint16_t fat32Flags; - /** - * FAT32 version. High byte is major revision number. - * Low byte is minor revision number. Only 0.0 define. - */ - uint16_t fat32Version; - /** - * Cluster number of the first cluster of the root directory for FAT32. - * This usually 2 but not required to be 2. - */ - uint32_t fat32RootCluster; - /** - * Sector number of FSINFO structure in the reserved area of the - * FAT32 volume. Usually 1. - */ - uint16_t fat32FSInfo; - /** - * If non-zero, indicates the sector number in the reserved area - * of the volume of a copy of the boot record. Usually 6. - * No value other than 6 is recommended. - */ - uint16_t fat32BackBootBlock; - /** - * Reserved for future expansion. Code that formats FAT32 volumes - * should always set all of the bytes of this field to 0. - */ - uint8_t fat32Reserved[12]; - /** - * Related to the BIOS physical drive number. Floppy drives are - * identified as 0x00 and physical hard disks are identified as - * 0x80, regardless of the number of physical disk drives. - * Typically, this value is set prior to issuing an INT 13h BIOS - * call to specify the device to access. The value is only - * relevant if the device is a boot device. - */ - uint8_t driveNumber; - /** used by Windows NT - should be zero for FAT */ - uint8_t reserved1; - /** 0X29 if next three fields are valid */ - uint8_t bootSignature; - /** - * A random serial number created when formatting a disk, - * which helps to distinguish between disks. - * Usually generated by combining date and time. - */ - uint32_t volumeSerialNumber; - /** - * A field once used to store the volume label. The volume label - * is now stored as a special file in the root directory. - */ - char volumeLabel[11]; - /** - * A text field with a value of FAT32. - */ - char fileSystemType[8]; - /** X86 boot code */ - uint8_t bootCode[420]; - /** must be 0X55 */ - uint8_t bootSectorSig0; - /** must be 0XAA */ - uint8_t bootSectorSig1; -} __attribute__((packed)); -/** Type name for FAT32 Boot Sector */ -typedef struct fat32_boot fat32_boot_t; -//------------------------------------------------------------------------------ -/** Lead signature for a FSINFO sector */ -const uint32_t FSINFO_LEAD_SIG = 0x41615252; -/** Struct signature for a FSINFO sector */ -const uint32_t FSINFO_STRUCT_SIG = 0x61417272; -/** - * \struct fat32_fsinfo - * - * \brief FSINFO sector for a FAT32 volume. - * - */ -struct fat32_fsinfo { - /** must be 0X52, 0X52, 0X61, 0X41 */ - uint32_t leadSignature; - /** must be zero */ - uint8_t reserved1[480]; - /** must be 0X72, 0X72, 0X41, 0X61 */ - uint32_t structSignature; - /** - * Contains the last known free cluster count on the volume. - * If the value is 0xFFFFFFFF, then the free count is unknown - * and must be computed. Any other value can be used, but is - * not necessarily correct. It should be range checked at least - * to make sure it is <= volume cluster count. - */ - uint32_t freeCount; - /** - * This is a hint for the FAT driver. It indicates the cluster - * number at which the driver should start looking for free clusters. - * If the value is 0xFFFFFFFF, then there is no hint and the driver - * should start looking at cluster 2. - */ - uint32_t nextFree; - /** must be zero */ - uint8_t reserved2[12]; - /** must be 0X00, 0X00, 0X55, 0XAA */ - uint8_t tailSignature[4]; -} __attribute__((packed)); -/** Type name for FAT32 FSINFO Sector */ -typedef struct fat32_fsinfo fat32_fsinfo_t; -//------------------------------------------------------------------------------ -// End Of Chain values for FAT entries -/** FAT12 end of chain value used by Microsoft. */ -const uint16_t FAT12EOC = 0XFFF; -/** Minimum value for FAT12 EOC. Use to test for EOC. */ -const uint16_t FAT12EOC_MIN = 0XFF8; -/** FAT16 end of chain value used by Microsoft. */ -const uint16_t FAT16EOC = 0XFFFF; -/** Minimum value for FAT16 EOC. Use to test for EOC. */ -const uint16_t FAT16EOC_MIN = 0XFFF8; -/** FAT32 end of chain value used by Microsoft. */ -const uint32_t FAT32EOC = 0X0FFFFFFF; -/** Minimum value for FAT32 EOC. Use to test for EOC. */ -const uint32_t FAT32EOC_MIN = 0X0FFFFFF8; -/** Mask a for FAT32 entry. Entries are 28 bits. */ -const uint32_t FAT32MASK = 0X0FFFFFFF; -//------------------------------------------------------------------------------ -/** - * \struct directoryEntry - * \brief FAT short directory entry - * - * Short means short 8.3 name, not the entry size. - * - * Date Format. A FAT directory entry date stamp is a 16-bit field that is - * basically a date relative to the MS-DOS epoch of 01/01/1980. Here is the - * format (bit 0 is the LSB of the 16-bit word, bit 15 is the MSB of the - * 16-bit word): - * - * Bits 9-15: Count of years from 1980, valid value range 0-127 - * inclusive (1980-2107). - * - * Bits 5-8: Month of year, 1 = January, valid value range 1-12 inclusive. - * - * Bits 0-4: Day of month, valid value range 1-31 inclusive. - * - * Time Format. A FAT directory entry time stamp is a 16-bit field that has - * a granularity of 2 seconds. Here is the format (bit 0 is the LSB of the - * 16-bit word, bit 15 is the MSB of the 16-bit word). - * - * Bits 11-15: Hours, valid value range 0-23 inclusive. - * - * Bits 5-10: Minutes, valid value range 0-59 inclusive. - * - * Bits 0-4: 2-second count, valid value range 0-29 inclusive (0 - 58 seconds). - * - * The valid time range is from Midnight 00:00:00 to 23:59:58. - */ -struct directoryEntry { - /** Short 8.3 name. - * - * The first eight bytes contain the file name with blank fill. - * The last three bytes contain the file extension with blank fill. - */ - uint8_t name[11]; - /** Entry attributes. - * - * The upper two bits of the attribute byte are reserved and should - * always be set to 0 when a file is created and never modified or - * looked at after that. See defines that begin with DIR_ATT_. - */ - uint8_t attributes; - /** - * Reserved for use by Windows NT. Set value to 0 when a file is - * created and never modify or look at it after that. - */ - uint8_t reservedNT; - /** - * The granularity of the seconds part of creationTime is 2 seconds - * so this field is a count of tenths of a second and its valid - * value range is 0-199 inclusive. (WHG note - seems to be hundredths) - */ - uint8_t creationTimeTenths; - /** Time file was created. */ - uint16_t creationTime; - /** Date file was created. */ - uint16_t creationDate; - /** - * Last access date. Note that there is no last access time, only - * a date. This is the date of last read or write. In the case of - * a write, this should be set to the same date as lastWriteDate. - */ - uint16_t lastAccessDate; - /** - * High word of this entry's first cluster number (always 0 for a - * FAT12 or FAT16 volume). - */ - uint16_t firstClusterHigh; - /** Time of last write. File creation is considered a write. */ - uint16_t lastWriteTime; - /** Date of last write. File creation is considered a write. */ - uint16_t lastWriteDate; - /** Low word of this entry's first cluster number. */ - uint16_t firstClusterLow; - /** 32-bit unsigned holding this file's size in bytes. */ - uint32_t fileSize; -} __attribute__((packed)); -/** Type name for directoryEntry */ -typedef struct directoryEntry dir_t; -//------------------------------------------------------------------------------ -// Definitions for directory entries -// -/** escape for name[0] = 0XE5 */ -const uint8_t DIR_NAME_0XE5 = 0X05; -/** name[0] value for entry that is free after being "deleted" */ -const uint8_t DIR_NAME_DELETED = 0XE5; -/** name[0] value for entry that is free and no allocated entries follow */ -const uint8_t DIR_NAME_FREE = 0X00; -/** file is read-only */ -const uint8_t DIR_ATT_READ_ONLY = 0X01; -/** File should e hidden in directory listings */ -const uint8_t DIR_ATT_HIDDEN = 0X02; -/** Entry is for a system file */ -const uint8_t DIR_ATT_SYSTEM = 0X04; -/** Directory entry contains the volume label */ -const uint8_t DIR_ATT_VOLUME_ID = 0X08; -/** Entry is for a directory */ -const uint8_t DIR_ATT_DIRECTORY = 0X10; -/** Old DOS archive bit for backup support */ -const uint8_t DIR_ATT_ARCHIVE = 0X20; -/** Test value for long name entry. Test is - (d->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME. */ -const uint8_t DIR_ATT_LONG_NAME = 0X0F; -/** Test mask for long name entry */ -const uint8_t DIR_ATT_LONG_NAME_MASK = 0X3F; -/** defined attribute bits */ -const uint8_t DIR_ATT_DEFINED_BITS = 0X3F; - -/** Mask for file/subdirectory tests */ -const uint8_t DIR_ATT_FILE_TYPE_MASK = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY); - -/** Filename base-name is all lower case */ -const uint8_t DIR_NT_LC_BASE = 0X08; -/** Filename extension is all lower case.*/ -const uint8_t DIR_NT_LC_EXT = 0X10; - - -/** Directory entry is for a file - * \param[in] dir Pointer to a directory entry. - * - * \return true if the entry is for a normal file else false. - */ -static inline uint8_t DIR_IS_FILE(const dir_t* dir) { - return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == 0; -} -/** Directory entry is for a file or subdirectory - * \param[in] dir Pointer to a directory entry. - * - * \return true if the entry is for a normal file or subdirectory else false. - */ -static inline uint8_t DIR_IS_FILE_OR_SUBDIR(const dir_t* dir) { - return (dir->attributes & DIR_ATT_VOLUME_ID) == 0; -} -/** Directory entry is part of a long name - * \param[in] dir Pointer to a directory entry. - * - * \return true if the entry is for part of a long name else false. - */ -static inline uint8_t DIR_IS_LONG_NAME(const dir_t* dir) { - return dir->attributes == DIR_ATT_LONG_NAME; -} -/** Directory entry is hidden - * \param[in] dir Pointer to a directory entry. - * - * \return true if the entry is hidden else false. - */ -static inline uint8_t DIR_IS_HIDDEN(const dir_t* dir) { - return dir->attributes & DIR_ATT_HIDDEN; -} -/** Directory entry is for a subdirectory - * \param[in] dir Pointer to a directory entry. - * - * \return true if the entry is for a subdirectory else false. - */ -static inline uint8_t DIR_IS_SUBDIR(const dir_t* dir) { - return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == DIR_ATT_DIRECTORY; -} -/** Directory entry is system type - * \param[in] dir Pointer to a directory entry. - * - * \return true if the entry is system else false. - */ -static inline uint8_t DIR_IS_SYSTEM(const dir_t* dir) { - return dir->attributes & DIR_ATT_SYSTEM; -} -/** date field for FAT directory entry - * \param[in] year [1980,2107] - * \param[in] month [1,12] - * \param[in] day [1,31] - * - * \return Packed date for dir_t entry. - */ -static inline uint16_t FAT_DATE(uint16_t year, uint8_t month, uint8_t day) { - return (year - 1980) << 9 | month << 5 | day; -} -/** year part of FAT directory date field - * \param[in] fatDate Date in packed dir format. - * - * \return Extracted year [1980,2107] - */ -static inline uint16_t FAT_YEAR(uint16_t fatDate) { - return 1980 + (fatDate >> 9); -} -/** month part of FAT directory date field - * \param[in] fatDate Date in packed dir format. - * - * \return Extracted month [1,12] - */ -static inline uint8_t FAT_MONTH(uint16_t fatDate) { - return (fatDate >> 5) & 0XF; -} -/** day part of FAT directory date field - * \param[in] fatDate Date in packed dir format. - * - * \return Extracted day [1,31] - */ -static inline uint8_t FAT_DAY(uint16_t fatDate) { - return fatDate & 0X1F; -} -/** time field for FAT directory entry - * \param[in] hour [0,23] - * \param[in] minute [0,59] - * \param[in] second [0,59] - * - * \return Packed time for dir_t entry. - */ -static inline uint16_t FAT_TIME(uint8_t hour, uint8_t minute, uint8_t second) { - return hour << 11 | minute << 5 | second >> 1; -} -/** hour part of FAT directory time field - * \param[in] fatTime Time in packed dir format. - * - * \return Extracted hour [0,23] - */ -static inline uint8_t FAT_HOUR(uint16_t fatTime) { - return fatTime >> 11; -} -/** minute part of FAT directory time field - * \param[in] fatTime Time in packed dir format. - * - * \return Extracted minute [0,59] - */ -static inline uint8_t FAT_MINUTE(uint16_t fatTime) { - return (fatTime >> 5) & 0X3F; -} -/** second part of FAT directory time field - * \note second/2 is stored in packed time. - * - * \param[in] fatTime Time in packed dir format. - * - * \return Extracted second [0,58] - */ -static inline uint8_t FAT_SECOND(uint16_t fatTime) { - return 2*(fatTime & 0X1F); -} -/** Default date for file timestamps is 1 Jan 2000 */ -const uint16_t FAT_DEFAULT_DATE = ((2000 - 1980) << 9) | (1 << 5) | 1; -/** Default time for file timestamp is 1 am */ -const uint16_t FAT_DEFAULT_TIME = (1 << 11); -//------------------------------------------------------------------------------ -/** Dimension of first name field in long directory entry */ -const uint8_t LDIR_NAME1_DIM = 5; -/** Dimension of first name field in long directory entry */ -const uint8_t LDIR_NAME2_DIM = 6; -/** Dimension of first name field in long directory entry */ -const uint8_t LDIR_NAME3_DIM = 2; -/** - * \struct longDirectoryEntry - * \brief FAT long directory entry - */ -struct longDirectoryEntry { - /** - * The order of this entry in the sequence of long dir entries - * associated with the short dir entry at the end of the long dir set. - * - * If masked with 0X40 (LAST_LONG_ENTRY), this indicates the - * entry is the last long dir entry in a set of long dir entries. - * All valid sets of long dir entries must begin with an entry having - * this mask. - */ - uint8_t ord; - /** Characters 1-5 of the long-name sub-component in this entry. */ - uint16_t name1[LDIR_NAME1_DIM]; - /** Attributes - must be ATTR_LONG_NAME */ - uint8_t attr; - /** - * If zero, indicates a directory entry that is a sub-component of a - * long name. NOTE: Other values reserved for future extensions. - * - * Non-zero implies other directory entry types. - */ - uint8_t type; - /** - * Checksum of name in the short dir entry at the end of the - * long dir set. - */ - uint8_t chksum; - /** Characters 6-11 of the long-name sub-component in this entry. */ - uint16_t name2[LDIR_NAME2_DIM]; - /** Must be ZERO. This is an artifact of the FAT "first cluster" */ - uint16_t mustBeZero; - /** Characters 12 and 13 of the long-name sub-component in this entry. */ - uint16_t name3[LDIR_NAME3_DIM]; -} __attribute__((packed)); -/** Type name for longDirectoryEntry */ -typedef struct longDirectoryEntry ldir_t; -/** - * Ord mast that indicates the entry is the last long dir entry in a - * set of long dir entries. All valid sets of long dir entries must - * begin with an entry having this mask. - */ -const uint8_t LDIR_ORD_LAST_LONG_ENTRY = 0X40; -#endif // FatStructs_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatVolume.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatVolume.cpp deleted file mode 100644 index ceb9068..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatVolume.cpp +++ /dev/null @@ -1,614 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#include -#include "FatVolume.h" -//------------------------------------------------------------------------------ -cache_t* FatCache::read(uint32_t lbn, uint8_t option) { - if (m_lbn != lbn) { - if (!sync()) { - DBG_FAIL_MACRO; - goto fail; - } - if (!(option & CACHE_OPTION_NO_READ)) { - if (!m_vol->readBlock(lbn, m_block.data)) { - DBG_FAIL_MACRO; - goto fail; - } - } - m_status = 0; - m_lbn = lbn; - } - m_status |= option & CACHE_STATUS_MASK; - return &m_block; - -fail: - - return 0; -} -//------------------------------------------------------------------------------ -bool FatCache::sync() { - if (m_status & CACHE_STATUS_DIRTY) { - if (!m_vol->writeBlock(m_lbn, m_block.data)) { - DBG_FAIL_MACRO; - goto fail; - } - // mirror second FAT - if (m_status & CACHE_STATUS_MIRROR_FAT) { - uint32_t lbn = m_lbn + m_vol->blocksPerFat(); - if (!m_vol->writeBlock(lbn, m_block.data)) { - DBG_FAIL_MACRO; - goto fail; - } - } - m_status &= ~CACHE_STATUS_DIRTY; - } - return true; - -fail: - return false; -} -//------------------------------------------------------------------------------ -bool FatVolume::allocateCluster(uint32_t current, uint32_t* next) { - uint32_t find; - bool setStart; - if (m_allocSearchStart < current) { - // Try to keep file contiguous. Start just after current cluster. - find = current; - setStart = false; - } else { - find = m_allocSearchStart; - setStart = true; - } - while (1) { - find++; - if (find > m_lastCluster) { - if (setStart) { - // Can't find space, checked all clusters. - DBG_FAIL_MACRO; - goto fail; - } - find = m_allocSearchStart; - setStart = true; - continue; - } - if (find == current) { - // Can't find space, already searched clusters after current. - DBG_FAIL_MACRO; - goto fail; - } - uint32_t f; - int8_t fg = fatGet(find, &f); - if (fg < 0) { - DBG_FAIL_MACRO; - goto fail; - } - if (fg && f == 0) { - break; - } - } - if (setStart) { - m_allocSearchStart = find; - } - // Mark end of chain. - if (!fatPutEOC(find)) { - DBG_FAIL_MACRO; - goto fail; - } - if (current) { - // Link clusters. - if (!fatPut(current, find)) { - DBG_FAIL_MACRO; - goto fail; - } - } - updateFreeClusterCount(-1); - *next = find; - return true; - -fail: - return false; -} -//------------------------------------------------------------------------------ -// find a contiguous group of clusters -bool FatVolume::allocContiguous(uint32_t count, uint32_t* firstCluster) { - // flag to save place to start next search - bool setStart = true; - // start of group - uint32_t bgnCluster; - // end of group - uint32_t endCluster; - // Start at cluster after last allocated cluster. - endCluster = bgnCluster = m_allocSearchStart + 1; - - // search the FAT for free clusters - while (1) { - if (endCluster > m_lastCluster) { - // Can't find space. - DBG_FAIL_MACRO; - goto fail; - } - uint32_t f; - int8_t fg = fatGet(endCluster, &f); - if (fg < 0) { - DBG_FAIL_MACRO; - goto fail; - } - if (f || fg == 0) { - // don't update search start if unallocated clusters before endCluster. - if (bgnCluster != endCluster) { - setStart = false; - } - // cluster in use try next cluster as bgnCluster - bgnCluster = endCluster + 1; - } else if ((endCluster - bgnCluster + 1) == count) { - // done - found space - break; - } - endCluster++; - } - // Remember possible next free cluster. - if (setStart) { - m_allocSearchStart = endCluster; - } - // mark end of chain - if (!fatPutEOC(endCluster)) { - DBG_FAIL_MACRO; - goto fail; - } - // link clusters - while (endCluster > bgnCluster) { - if (!fatPut(endCluster - 1, endCluster)) { - DBG_FAIL_MACRO; - goto fail; - } - endCluster--; - } - // Maintain count of free clusters. - updateFreeClusterCount(-count); - - // return first cluster number to caller - *firstCluster = bgnCluster; - return true; - -fail: - return false; -} -//------------------------------------------------------------------------------ -uint32_t FatVolume::clusterFirstBlock(uint32_t cluster) const { - return m_dataStartBlock + ((cluster - 2) << m_clusterSizeShift); -} -//------------------------------------------------------------------------------ -// Fetch a FAT entry - return -1 error, 0 EOC, else 1. -int8_t FatVolume::fatGet(uint32_t cluster, uint32_t* value) { - uint32_t lba; - uint32_t next; - cache_t* pc; - - // error if reserved cluster of beyond FAT - if (cluster < 2 || cluster > m_lastCluster) { - DBG_FAIL_MACRO; - goto fail; - } - - if (fatType() == 32) { - lba = m_fatStartBlock + (cluster >> 7); - pc = cacheFetchFat(lba, FatCache::CACHE_FOR_READ); - if (!pc) { - DBG_FAIL_MACRO; - goto fail; - } - next = pc->fat32[cluster & 0X7F] & FAT32MASK; - goto done; - } - if (fatType() == 16) { - lba = m_fatStartBlock + ((cluster >> 8) & 0XFF); - pc = cacheFetchFat(lba, FatCache::CACHE_FOR_READ); - if (!pc) { - DBG_FAIL_MACRO; - goto fail; - } - next = pc->fat16[cluster & 0XFF]; - goto done; - } - if (FAT12_SUPPORT && fatType() == 12) { - uint16_t index = cluster; - index += index >> 1; - lba = m_fatStartBlock + (index >> 9); - pc = cacheFetchFat(lba, FatCache::CACHE_FOR_READ); - if (!pc) { - DBG_FAIL_MACRO; - goto fail; - } - index &= 0X1FF; - uint16_t tmp = pc->data[index]; - index++; - if (index == 512) { - pc = cacheFetchFat(lba + 1, FatCache::CACHE_FOR_READ); - if (!pc) { - DBG_FAIL_MACRO; - goto fail; - } - index = 0; - } - tmp |= pc->data[index] << 8; - next = cluster & 1 ? tmp >> 4 : tmp & 0XFFF; - goto done; - } else { - DBG_FAIL_MACRO; - goto fail; - } -done: - if (isEOC(next)) { - return 0; - } - *value = next; - return 1; - -fail: - return -1; -} -//------------------------------------------------------------------------------ -// Store a FAT entry -bool FatVolume::fatPut(uint32_t cluster, uint32_t value) { - uint32_t lba; - cache_t* pc; - - // error if reserved cluster of beyond FAT - if (cluster < 2 || cluster > m_lastCluster) { - DBG_FAIL_MACRO; - goto fail; - } - - if (fatType() == 32) { - lba = m_fatStartBlock + (cluster >> 7); - pc = cacheFetchFat(lba, FatCache::CACHE_FOR_WRITE); - if (!pc) { - DBG_FAIL_MACRO; - goto fail; - } - pc->fat32[cluster & 0X7F] = value; - return true; - } - - if (fatType() == 16) { - lba = m_fatStartBlock + ((cluster >> 8) & 0XFF); - pc = cacheFetchFat(lba, FatCache::CACHE_FOR_WRITE); - if (!pc) { - DBG_FAIL_MACRO; - goto fail; - } - pc->fat16[cluster & 0XFF] = value; - return true; - } - - if (FAT12_SUPPORT && fatType() == 12) { - uint16_t index = cluster; - index += index >> 1; - lba = m_fatStartBlock + (index >> 9); - pc = cacheFetchFat(lba, FatCache::CACHE_FOR_WRITE); - if (!pc) { - DBG_FAIL_MACRO; - goto fail; - } - index &= 0X1FF; - uint8_t tmp = value; - if (cluster & 1) { - tmp = (pc->data[index] & 0XF) | tmp << 4; - } - pc->data[index] = tmp; - - index++; - if (index == 512) { - lba++; - index = 0; - pc = cacheFetchFat(lba, FatCache::CACHE_FOR_WRITE); - if (!pc) { - DBG_FAIL_MACRO; - goto fail; - } - } - tmp = value >> 4; - if (!(cluster & 1)) { - tmp = ((pc->data[index] & 0XF0)) | tmp >> 4; - } - pc->data[index] = tmp; - return true; - } else { - DBG_FAIL_MACRO; - goto fail; - } - -fail: - return false; -} -//------------------------------------------------------------------------------ -// free a cluster chain -bool FatVolume::freeChain(uint32_t cluster) { - uint32_t next; - int8_t fg; - do { - fg = fatGet(cluster, &next); - if (fg < 0) { - DBG_FAIL_MACRO; - goto fail; - } - // free cluster - if (!fatPut(cluster, 0)) { - DBG_FAIL_MACRO; - goto fail; - } - // Add one to count of free clusters. - updateFreeClusterCount(1); - - if (cluster <= m_allocSearchStart) { - m_allocSearchStart = cluster - 1; - } - cluster = next; - } while (fg); - - return true; - -fail: - return false; -} -//------------------------------------------------------------------------------ -int32_t FatVolume::freeClusterCount() { -#if MAINTAIN_FREE_CLUSTER_COUNT - if (m_freeClusterCount >= 0) { - return m_freeClusterCount; - } -#endif // MAINTAIN_FREE_CLUSTER_COUNT - uint32_t free = 0; - uint32_t lba; - uint32_t todo = m_lastCluster + 1; - uint16_t n; - - if (FAT12_SUPPORT && fatType() == 12) { - for (unsigned i = 2; i < todo; i++) { - uint32_t c; - int8_t fg = fatGet(i, &c); - if (fg < 0) { - DBG_FAIL_MACRO; - goto fail; - } - if (fg && c == 0) { - free++; - } - } - } else if (fatType() == 16 || fatType() == 32) { - lba = m_fatStartBlock; - while (todo) { - cache_t* pc = cacheFetchFat(lba++, FatCache::CACHE_FOR_READ); - if (!pc) { - DBG_FAIL_MACRO; - goto fail; - } - n = fatType() == 16 ? 256 : 128; - if (todo < n) { - n = todo; - } - if (fatType() == 16) { - for (uint16_t i = 0; i < n; i++) { - if (pc->fat16[i] == 0) { - free++; - } - } - } else { - for (uint16_t i = 0; i < n; i++) { - if (pc->fat32[i] == 0) { - free++; - } - } - } - todo -= n; - } - } else { - // invalid FAT type - DBG_FAIL_MACRO; - goto fail; - } - setFreeClusterCount(free); - return free; - -fail: - return -1; -} -//------------------------------------------------------------------------------ -bool FatVolume::init(uint8_t part) { - uint32_t clusterCount; - uint32_t totalBlocks; - uint32_t volumeStartBlock = 0; - fat32_boot_t* fbs; - cache_t* pc; - uint8_t tmp; - m_fatType = 0; - m_allocSearchStart = 1; - m_cache.init(this); -#if USE_SEPARATE_FAT_CACHE - m_fatCache.init(this); -#endif // USE_SEPARATE_FAT_CACHE - // if part == 0 assume super floppy with FAT boot sector in block zero - // if part > 0 assume mbr volume with partition table - if (part) { - if (part > 4) { - DBG_FAIL_MACRO; - goto fail; - } - pc = cacheFetchData(0, FatCache::CACHE_FOR_READ); - if (!pc) { - DBG_FAIL_MACRO; - goto fail; - } - part_t* p = &pc->mbr.part[part - 1]; - if ((p->boot & 0X7F) != 0 || p->firstSector == 0) { - // not a valid partition - DBG_FAIL_MACRO; - goto fail; - } - volumeStartBlock = p->firstSector; - } - pc = cacheFetchData(volumeStartBlock, FatCache::CACHE_FOR_READ); - if (!pc) { - DBG_FAIL_MACRO; - goto fail; - } - fbs = &(pc->fbs32); - if (fbs->bytesPerSector != 512 || - fbs->fatCount != 2 || - fbs->reservedSectorCount == 0) { - // not valid FAT volume - DBG_FAIL_MACRO; - goto fail; - } - m_blocksPerCluster = fbs->sectorsPerCluster; - m_clusterBlockMask = m_blocksPerCluster - 1; - // determine shift that is same as multiply by m_blocksPerCluster - m_clusterSizeShift = 0; - for (tmp = 1; m_blocksPerCluster != tmp; tmp <<= 1, m_clusterSizeShift++) { - if (tmp == 0) { - DBG_FAIL_MACRO; - goto fail; - } - } - m_blocksPerFat = fbs->sectorsPerFat16 ? - fbs->sectorsPerFat16 : fbs->sectorsPerFat32; - - m_fatStartBlock = volumeStartBlock + fbs->reservedSectorCount; - - // count for FAT16 zero for FAT32 - m_rootDirEntryCount = fbs->rootDirEntryCount; - - // directory start for FAT16 dataStart for FAT32 - m_rootDirStart = m_fatStartBlock + 2 * m_blocksPerFat; - // data start for FAT16 and FAT32 - m_dataStartBlock = m_rootDirStart + ((32 * fbs->rootDirEntryCount + 511)/512); - - // total blocks for FAT16 or FAT32 - totalBlocks = fbs->totalSectors16 ? - fbs->totalSectors16 : fbs->totalSectors32; - // total data blocks - clusterCount = totalBlocks - (m_dataStartBlock - volumeStartBlock); - - // divide by cluster size to get cluster count - clusterCount >>= m_clusterSizeShift; - m_lastCluster = clusterCount + 1; - - // Indicate unknown number of free clusters. - setFreeClusterCount(-1); - // FAT type is determined by cluster count - if (clusterCount < 4085) { - m_fatType = 12; - if (!FAT12_SUPPORT) { - DBG_FAIL_MACRO; - goto fail; - } - } else if (clusterCount < 65525) { - m_fatType = 16; - } else { - m_rootDirStart = fbs->fat32RootCluster; - m_fatType = 32; - } - return true; - -fail: - return false; -} -//------------------------------------------------------------------------------ -bool FatVolume::wipe(print_t* pr) { - cache_t* cache; - uint16_t count; - uint32_t lbn; - if (!fatType()) { - DBG_FAIL_MACRO; - goto fail; - } - cache = cacheClear(); - if (!cache) { - DBG_FAIL_MACRO; - goto fail; - } - memset(cache->data, 0, 512); - // Zero root. - if (fatType() == 32) { - lbn = clusterFirstBlock(m_rootDirStart); - count = m_blocksPerCluster; - } else { - lbn = m_rootDirStart; - count = m_rootDirEntryCount/16; - } - for (uint32_t n = 0; n < count; n++) { - if (!writeBlock(lbn + n, cache->data)) { - DBG_FAIL_MACRO; - goto fail; - } - } - // Clear FATs. - count = 2*m_blocksPerFat; - lbn = m_fatStartBlock; - for (uint32_t nb = 0; nb < count; nb++) { - if (pr && (nb & 0XFF) == 0) { - pr->write('.'); - } - if (!writeBlock(lbn + nb, cache->data)) { - DBG_FAIL_MACRO; - goto fail; - } - } - // Reserve first two clusters. - if (fatType() == 32) { - cache->fat32[0] = 0x0FFFFFF8; - cache->fat32[1] = 0x0FFFFFFF; - } else if (fatType() == 16) { - cache->fat16[0] = 0XFFF8; - cache->fat16[1] = 0XFFFF; - } else if (FAT12_SUPPORT && fatType() == 12) { - cache->fat32[0] = 0XFFFFF8; - } else { - DBG_FAIL_MACRO; - goto fail; - } - if (!writeBlock(m_fatStartBlock, cache->data) || - !writeBlock(m_fatStartBlock + m_blocksPerFat, cache->data)) { - DBG_FAIL_MACRO; - goto fail; - } - if (fatType() == 32) { - // Reserve root cluster. - if (!fatPutEOC(m_rootDirStart) || !cacheSync()) { - DBG_FAIL_MACRO; - goto fail; - } - } - if (pr) { - pr->write('\r'); - pr->write('\n'); - } - m_fatType = 0; - return true; - -fail: - m_fatType = 0; - return false; -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatVolume.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatVolume.h deleted file mode 100644 index 96f16b0..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FatVolume.h +++ /dev/null @@ -1,375 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 FatVolume_h -#define FatVolume_h -/** - * \file - * \brief FatVolume class - */ -#include -#include "FatLibConfig.h" -#include "FatStructs.h" -#include "BlockDriver.h" -//------------------------------------------------------------------------------ -#ifndef DOXYGEN_SHOULD_SKIP_THIS -/** Macro for debug. */ -#define DEBUG_MODE 0 -#if DEBUG_MODE -#define DBG_FAIL_MACRO Serial.print(F(__FILE__)); Serial.println(__LINE__); -#define DBG_PRINT_IF(b) if (b) {Serial.println(F(#b)); DBG_FAIL_MACRO;} -#define DBG_HALT_IF(b) if (b) {Serial.println(F(#b));\ - DBG_FAIL_MACRO; while (1);} -#else // DEBUG_MODE -#define DBG_FAIL_MACRO -#define DBG_PRINT_IF(b) -#define DBG_HALT_IF(b) -#endif // DEBUG_MODE -#endif // DOXYGEN_SHOULD_SKIP_THIS -//------------------------------------------------------------------------------ -#if ENABLE_ARDUINO_FEATURES -/** Use Print for Arduino */ -typedef Print print_t; -#else // ENABLE_ARDUINO_FEATURES -/** - * \class CharWriter - * \brief Character output - often serial port. - */ -class CharWriter { - public: - virtual size_t write(char c) = 0; - virtual size_t write(const char* s) = 0; -}; -typedef CharWriter print_t; -#endif // ENABLE_ARDUINO_FEATURES -//------------------------------------------------------------------------------ -// Forward declaration of FatVolume. -class FatVolume; -//------------------------------------------------------------------------------ -/** - * \brief Cache for an raw data block. - */ -union cache_t { - /** Used to access cached file data blocks. */ - uint8_t data[512]; - /** Used to access cached FAT16 entries. */ - uint16_t fat16[256]; - /** Used to access cached FAT32 entries. */ - uint32_t fat32[128]; - /** Used to access cached directory entries. */ - dir_t dir[16]; - /** Used to access a cached Master Boot Record. */ - mbr_t mbr; - /** Used to access to a cached FAT boot sector. */ - fat_boot_t fbs; - /** Used to access to a cached FAT32 boot sector. */ - fat32_boot_t fbs32; - /** Used to access to a cached FAT32 FSINFO sector. */ - fat32_fsinfo_t fsinfo; -}; -//============================================================================== -/** - * \class FatCache - * \brief Block cache. - */ -class FatCache { - public: - /** Cached block is dirty */ - static const uint8_t CACHE_STATUS_DIRTY = 1; - /** Cashed block is FAT entry and must be mirrored in second FAT. */ - static const uint8_t CACHE_STATUS_MIRROR_FAT = 2; - /** Cache block status bits */ - static const uint8_t CACHE_STATUS_MASK - = CACHE_STATUS_DIRTY | CACHE_STATUS_MIRROR_FAT; - /** Sync existing block but do not read new block. */ - static const uint8_t CACHE_OPTION_NO_READ = 4; - /** Cache block for read. */ - static const uint8_t CACHE_FOR_READ = 0; - /** Cache block for write. */ - static const uint8_t CACHE_FOR_WRITE = CACHE_STATUS_DIRTY; - /** Reserve cache block for write - do not read from block device. */ - static const uint8_t CACHE_RESERVE_FOR_WRITE - = CACHE_STATUS_DIRTY | CACHE_OPTION_NO_READ; - /** \return Cache block address. */ - cache_t* block() { - return &m_block; - } - /** Set current block dirty. */ - void dirty() { - m_status |= CACHE_STATUS_DIRTY; - } - /** Initialize the cache. - * \param[in] vol FatVolume that owns this FatCache. - */ - void init(FatVolume *vol) { - m_vol = vol; - invalidate(); - } - /** Invalidate current cache block. */ - void invalidate() { - m_status = 0; - m_lbn = 0XFFFFFFFF; - } - /** \return dirty status */ - bool isDirty() { - return m_status & CACHE_STATUS_DIRTY; - } - /** \return Logical block number for cached block. */ - uint32_t lbn() { - return m_lbn; - } - /** Read a block into the cache. - * \param[in] lbn Block to read. - * \param[in] option mode for cached block. - * \return Address of cached block. */ - cache_t* read(uint32_t lbn, uint8_t option); - /** Write current block if dirty. - * \return true for success else false. - */ - bool sync(); - - private: - uint8_t m_status; - FatVolume* m_vol; - uint32_t m_lbn; - cache_t m_block; -}; -//============================================================================== -/** - * \class FatVolume - * \brief Access FAT16 and FAT32 volumes on raw file devices. - */ -class FatVolume { - public: - /** Create an instance of FatVolume - */ - FatVolume() : m_fatType(0) {} - - /** \return The volume's cluster size in blocks. */ - uint8_t blocksPerCluster() const { - return m_blocksPerCluster; - } - /** \return The number of blocks in one FAT. */ - uint32_t blocksPerFat() const { - return m_blocksPerFat; - } - /** Clear the cache and returns a pointer to the cache. Not for normal apps. - * \return A pointer to the cache buffer or zero if an error occurs. - */ - cache_t* cacheClear() { - if (!cacheSync()) { - return 0; - } - m_cache.invalidate(); - return m_cache.block(); - } - /** \return The total number of clusters in the volume. */ - uint32_t clusterCount() const { - return m_lastCluster - 1; - } - /** \return The shift count required to multiply by blocksPerCluster. */ - uint8_t clusterSizeShift() const { - return m_clusterSizeShift; - } - /** \return The logical block number for the start of file data. */ - uint32_t dataStartBlock() const { - return m_dataStartBlock; - } - /** \return The number of File Allocation Tables. */ - uint8_t fatCount() { - return 2; - } - /** \return The logical block number for the start of the first FAT. */ - uint32_t fatStartBlock() const { - return m_fatStartBlock; - } - /** \return The FAT type of the volume. Values are 12, 16 or 32. */ - uint8_t fatType() const { - return m_fatType; - } - /** Volume free space in clusters. - * - * \return Count of free clusters for success or -1 if an error occurs. - */ - int32_t freeClusterCount(); - /** Initialize a FAT volume. Try partition one first then try super - * floppy format. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool init() { - return init(1) || init(0); - } - /** Initialize a FAT volume. - - * \param[in] part The partition to be used. Legal values for \a part are - * 1-4 to use the corresponding partition on a device formatted with - * a MBR, Master Boot Record, or zero if the device is formatted as - * a super floppy with the FAT boot sector in block zero. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool init(uint8_t part); - /** \return The number of entries in the root directory for FAT16 volumes. */ - uint16_t rootDirEntryCount() const { - return m_rootDirEntryCount; - } - /** \return The logical block number for the start of the root directory - on FAT16 volumes or the first cluster number on FAT32 volumes. */ - uint32_t rootDirStart() const { - return m_rootDirStart; - } - /** \return The number of blocks in the volume */ - uint32_t volumeBlockCount() const { - return blocksPerCluster()*clusterCount(); - } - /** Wipe all data from the volume. - * \param[in] pr print stream for status dots. - * \return true for success else false. - */ - bool wipe(print_t* pr = 0); - /** Debug access to FAT table - * - * \param[in] n cluster number. - * \param[out] v value of entry - * \return -1 error, 0 EOC, else 1. - */ - int8_t dbgFat(uint32_t n, uint32_t* v) { - return fatGet(n, v); - } -//------------------------------------------------------------------------------ - private: - // Allow FatFile and FatCache access to FatVolume private functions. - friend class FatCache; ///< Allow access to FatVolume. - friend class FatFile; ///< Allow access to FatVolume. - friend class FatFileSystem; ///< Allow access to FatVolume. -//------------------------------------------------------------------------------ - BlockDriver* m_blockDev; // block device - uint8_t m_blocksPerCluster; // Cluster size in blocks. - uint8_t m_clusterBlockMask; // Mask to extract block of cluster. - uint8_t m_clusterSizeShift; // Cluster count to block count shift. - uint8_t m_fatType; // Volume type (12, 16, OR 32). - uint16_t m_rootDirEntryCount; // Number of entries in FAT16 root dir. - uint32_t m_allocSearchStart; // Start cluster for alloc search. - uint32_t m_blocksPerFat; // FAT size in blocks - uint32_t m_dataStartBlock; // First data block number. - uint32_t m_fatStartBlock; // Start block for first FAT. - uint32_t m_lastCluster; // Last cluster number in FAT. - uint32_t m_rootDirStart; // Start block for FAT16, cluster for FAT32. -//------------------------------------------------------------------------------ - // block I/O functions. - bool readBlock(uint32_t block, uint8_t* dst) { - return m_blockDev->readBlock(block, dst); - } - bool syncBlocks() { - return m_blockDev->syncBlocks(); - } - bool writeBlock(uint32_t block, const uint8_t* src) { - return m_blockDev->writeBlock(block, src); - } -#if USE_MULTI_BLOCK_IO - bool readBlocks(uint32_t block, uint8_t* dst, size_t nb) { - return m_blockDev->readBlocks(block, dst, nb); - } - bool writeBlocks(uint32_t block, const uint8_t* src, size_t nb) { - return m_blockDev->writeBlocks(block, src, nb); - } -#endif // USE_MULTI_BLOCK_IO -#if MAINTAIN_FREE_CLUSTER_COUNT - int32_t m_freeClusterCount; // Count of free clusters in volume. - void setFreeClusterCount(int32_t value) { - m_freeClusterCount = value; - } - void updateFreeClusterCount(int32_t change) { - if (m_freeClusterCount >= 0) { - m_freeClusterCount += change; - } - } -#else // MAINTAIN_FREE_CLUSTER_COUNT - void setFreeClusterCount(int32_t value) { - (void)value; - } - void updateFreeClusterCount(int32_t change) { - (void)change; - } -#endif // MAINTAIN_FREE_CLUSTER_COUNT - -// block caches - FatCache m_cache; -#if USE_SEPARATE_FAT_CACHE - FatCache m_fatCache; - cache_t* cacheFetchFat(uint32_t blockNumber, uint8_t options) { - return m_fatCache.read(blockNumber, - options | FatCache::CACHE_STATUS_MIRROR_FAT); - } - bool cacheSync() { - return m_cache.sync() && m_fatCache.sync() && syncBlocks(); - } -#else // - cache_t* cacheFetchFat(uint32_t blockNumber, uint8_t options) { - return cacheFetchData(blockNumber, - options | FatCache::CACHE_STATUS_MIRROR_FAT); - } - bool cacheSync() { - return m_cache.sync() && syncBlocks(); - } -#endif // USE_SEPARATE_FAT_CACHE - cache_t* cacheFetchData(uint32_t blockNumber, uint8_t options) { - return m_cache.read(blockNumber, options); - } - void cacheInvalidate() { - m_cache.invalidate(); - } - bool cacheSyncData() { - return m_cache.sync(); - } - cache_t *cacheAddress() { - return m_cache.block(); - } - uint32_t cacheBlockNumber() { - return m_cache.lbn(); - } - void cacheDirty() { - m_cache.dirty(); - } -//------------------------------------------------------------------------------ - bool allocateCluster(uint32_t current, uint32_t* next); - bool allocContiguous(uint32_t count, uint32_t* firstCluster); - uint8_t blockOfCluster(uint32_t position) const { - return (position >> 9) & m_clusterBlockMask; - } - uint32_t clusterFirstBlock(uint32_t cluster) const; - int8_t fatGet(uint32_t cluster, uint32_t* value); - bool fatPut(uint32_t cluster, uint32_t value); - bool fatPutEOC(uint32_t cluster) { - return fatPut(cluster, 0x0FFFFFFF); - } - bool freeChain(uint32_t cluster); - bool isEOC(uint32_t cluster) const { - return cluster > m_lastCluster; - } -}; -#endif // FatVolume diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FmtNumber.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FmtNumber.cpp deleted file mode 100644 index a318ab5..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FmtNumber.cpp +++ /dev/null @@ -1,460 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#include "FmtNumber.h" -// Use Stimmer div/mod 10 on avr -#ifdef __AVR__ -#include -#define USE_STIMMER -#endif // __AVR__ -//------------------------------------------------------------------------------ -// Stimmer div/mod 10 for AVR -// this code fragment works out i/10 and i%10 by calculating -// i*(51/256)*(256/255)/2 == i*51/510 == i/10 -// by "j.k" I mean 32.8 fixed point, j is integer part, k is fractional part -// j.k = ((j+1.0)*51.0)/256.0 -// (we add 1 because we will be using the floor of the result later) -// divmod10_asm16 and divmod10_asm32 are public domain code by Stimmer. -// http://forum.arduino.cc/index.php?topic=167414.msg1293679#msg1293679 -#define divmod10_asm16(in32, mod8, tmp8) \ -asm volatile( \ - " ldi %2,51 \n\t" \ - " mul %A0,%2 \n\t" \ - " clr %A0 \n\t" \ - " add r0,%2 \n\t" \ - " adc %A0,r1 \n\t" \ - " mov %1,r0 \n\t" \ - " mul %B0,%2 \n\t" \ - " clr %B0 \n\t" \ - " add %A0,r0 \n\t" \ - " adc %B0,r1 \n\t" \ - " clr r1 \n\t" \ - " add %1,%A0 \n\t" \ - " adc %A0,%B0 \n\t" \ - " adc %B0,r1 \n\t" \ - " add %1,%B0 \n\t" \ - " adc %A0,r1 \n\t" \ - " adc %B0,r1 \n\t" \ - " lsr %B0 \n\t" \ - " ror %A0 \n\t" \ - " ror %1 \n\t" \ - " ldi %2,10 \n\t" \ - " mul %1,%2 \n\t" \ - " mov %1,r1 \n\t" \ - " clr r1 \n\t" \ - :"+r"(in32), "=d"(mod8), "=d"(tmp8) : : "r0") - -#define divmod10_asm32(in32, mod8, tmp8) \ -asm volatile( \ - " ldi %2,51 \n\t" \ - " mul %A0,%2 \n\t" \ - " clr %A0 \n\t" \ - " add r0,%2 \n\t" \ - " adc %A0,r1 \n\t" \ - " mov %1,r0 \n\t" \ - " mul %B0,%2 \n\t" \ - " clr %B0 \n\t" \ - " add %A0,r0 \n\t" \ - " adc %B0,r1 \n\t" \ - " mul %C0,%2 \n\t" \ - " clr %C0 \n\t" \ - " add %B0,r0 \n\t" \ - " adc %C0,r1 \n\t" \ - " mul %D0,%2 \n\t" \ - " clr %D0 \n\t" \ - " add %C0,r0 \n\t" \ - " adc %D0,r1 \n\t" \ - " clr r1 \n\t" \ - " add %1,%A0 \n\t" \ - " adc %A0,%B0 \n\t" \ - " adc %B0,%C0 \n\t" \ - " adc %C0,%D0 \n\t" \ - " adc %D0,r1 \n\t" \ - " add %1,%B0 \n\t" \ - " adc %A0,%C0 \n\t" \ - " adc %B0,%D0 \n\t" \ - " adc %C0,r1 \n\t" \ - " adc %D0,r1 \n\t" \ - " add %1,%D0 \n\t" \ - " adc %A0,r1 \n\t" \ - " adc %B0,r1 \n\t" \ - " adc %C0,r1 \n\t" \ - " adc %D0,r1 \n\t" \ - " lsr %D0 \n\t" \ - " ror %C0 \n\t" \ - " ror %B0 \n\t" \ - " ror %A0 \n\t" \ - " ror %1 \n\t" \ - " ldi %2,10 \n\t" \ - " mul %1,%2 \n\t" \ - " mov %1,r1 \n\t" \ - " clr r1 \n\t" \ - :"+r"(in32), "=d"(mod8), "=d"(tmp8) : : "r0") -//------------------------------------------------------------------------------ -/* -// C++ code is based on this version of divmod10 by robtillaart. -// http://forum.arduino.cc/index.php?topic=167414.msg1246851#msg1246851 -// from robtillaart post: -// The code is based upon the divu10() code from the book Hackers Delight1. -// My insight was that the error formula in divu10() was in fact modulo 10 -// but not always. Sometimes it was 10 more. -void divmod10(uint32_t in, uint32_t &div, uint32_t &mod) -{ - // q = in * 0.8; - uint32_t q = (in >> 1) + (in >> 2); - q = q + (q >> 4); - q = q + (q >> 8); - q = q + (q >> 16); // not needed for 16 bit version - - // q = q / 8; ==> q = in *0.1; - q = q >> 3; - - // determine error - uint32_t r = in - ((q << 3) + (q << 1)); // r = in - q*10; - div = q + (r > 9); - if (r > 9) mod = r - 10; - else mod = r; -} -// Hackers delight function is here: -// http://www.hackersdelight.org/hdcodetxt/divuc.c.txt -// Code below uses 8/10 = 0.1100 1100 1100 1100 1100 1100 1100 1100. -// 15 ops including the multiply, or 17 elementary ops. -unsigned divu10(unsigned n) { - unsigned q, r; - - q = (n >> 1) + (n >> 2); - q = q + (q >> 4); - q = q + (q >> 8); - q = q + (q >> 16); - q = q >> 3; - r = n - q*10; - return q + ((r + 6) >> 4); -// return q + (r > 9); -} -*/ -//------------------------------------------------------------------------------ -#ifndef DOXYGEN_SHOULD_SKIP_THIS -#ifdef __AVR__ -static const float m[] PROGMEM = {1e-1, 1e-2, 1e-4, 1e-8, 1e-16, 1e-32}; -static const float p[] PROGMEM = {1e+1, 1e+2, 1e+4, 1e+8, 1e+16, 1e+32}; -#else // __AVR__ -static const float m[] = {1e-1, 1e-2, 1e-4, 1e-8, 1e-16, 1e-32}; -static const float p[] = {1e+1, 1e+2, 1e+4, 1e+8, 1e+16, 1e+32}; -#endif // __AVR__ -#endif // DOXYGEN_SHOULD_SKIP_THIS -// scale float v by power of ten. return v*10^n -float scale10(float v, int8_t n) { - const float *s; - if (n < 0) { - n = -n; - s = m; - } else { - s = p; - } - n &= 63; - for (uint8_t i = 0; n; n >>= 1, i++) { -#ifdef __AVR__ - if (n & 1) { - v *= pgm_read_float(&s[i]); - } -#else // __AVR__ - if (n & 1) { - v *= s[i]; - } -#endif // __AVR__ - } - return v; -} -//------------------------------------------------------------------------------ -// Format 16-bit unsigned -char* fmtDec(uint16_t n, char* p) { - while (n > 9) { -#ifdef USE_STIMMER - uint8_t tmp8, r; - divmod10_asm16(n, r, tmp8); -#else // USE_STIMMER - uint16_t t = n; - n = (n >> 1) + (n >> 2); - n = n + (n >> 4); - n = n + (n >> 8); - // n = n + (n >> 16); // no code for 16-bit n - n = n >> 3; - uint8_t r = t - (((n << 2) + n) << 1); - if (r > 9) { - n++; - r -= 10; - } -#endif // USE_STIMMER - *--p = r + '0'; - } - *--p = n + '0'; - return p; -} -//------------------------------------------------------------------------------ -// format 32-bit unsigned -char* fmtDec(uint32_t n, char* p) { - while (n >> 16) { -#ifdef USE_STIMMER - uint8_t tmp8, r; - divmod10_asm32(n, r, tmp8); -#else // USE_STIMMER - uint32_t t = n; - n = (n >> 1) + (n >> 2); - n = n + (n >> 4); - n = n + (n >> 8); - n = n + (n >> 16); - n = n >> 3; - uint8_t r = t - (((n << 2) + n) << 1); - if (r > 9) { - n++; - r -= 10; - } -#endif // USE_STIMMER - *--p = r + '0'; - } - return fmtDec((uint16_t)n, p); -} -//------------------------------------------------------------------------------ -char* fmtFloat(float value, char* p, uint8_t prec) { - char sign = value < 0 ? '-' : 0; - if (sign) { - value = -value; - } - - if (isnan(value)) { - *--p = 'n'; - *--p = 'a'; - *--p = 'n'; - return p; - } - if (isinf(value)) { - *--p = 'f'; - *--p = 'n'; - *--p = 'i'; - return p; - } - if (value > 4294967040.0) { - *--p = 'f'; - *--p = 'v'; - *--p = 'o'; - return p; - } - if (prec > 9) { - prec = 9; - } - value += scale10(0.5, -prec); - - uint32_t whole = value; - if (prec) { - char* tmp = p - prec; - uint32_t fraction = scale10(value - whole, prec); - p = fmtDec(fraction, p); - while (p > tmp) { - *--p = '0'; - } - *--p = '.'; - } - p = fmtDec(whole, p); - if (sign) { - *--p = sign; - } - return p; -} -//------------------------------------------------------------------------------ -/** Print a number followed by a field terminator. - * \param[in] value The number to be printed. - * \param[in] ptr Pointer to last char in buffer. - * \param[in] prec Number of digits after decimal point. - * \param[in] expChar Use exp format if non zero. - * \return Pointer to first character of result. - */ -char* fmtFloat(float value, char* ptr, uint8_t prec, char expChar) { - bool neg = value < 0; - if (neg) { - value = -value; - } - - // check for nan inf ovf - if (isnan(value)) { - *--ptr = 'n'; - *--ptr = 'a'; - *--ptr = 'n'; - return ptr; - } - if (isinf(value)) { - *--ptr = 'f'; - *--ptr = 'n'; - *--ptr = 'i'; - return ptr; - } - if (!expChar && value > 4294967040.0) { - *--ptr = 'f'; - *--ptr = 'v'; - *--ptr = 'o'; - return ptr; - } - if (prec > 9) { - prec = 9; - } - float round = scale10(0.5, -prec); - if (expChar) { - int8_t exp = 0; - bool expNeg = false; - if (value) { - while (value > 10.0) { - value *= 0.1; - exp++; - } - while (value < 1.0) { - value *= 10.0; - exp--; - } - value += round; - if (value > 10.0) { - value *= 0.1; - exp++; - } - expNeg = exp < 0; - if (expNeg) { - exp = -exp; - } - } - ptr = fmtDec((uint16_t)exp, ptr); - if (exp < 10) { - *--ptr = '0'; - } - *--ptr = expNeg ? '-' : '+'; - *--ptr = expChar; - } else { - // round value - value += round; - } - uint32_t whole = value; - if (prec) { - char* tmp = ptr - prec; - uint32_t fraction = scale10(value - whole, prec); - ptr = fmtDec(fraction, ptr); - while (ptr > tmp) { - *--ptr = '0'; - } - *--ptr = '.'; - } - ptr = fmtDec(whole, ptr); - if (neg) { - *--ptr = '-'; - } - return ptr; -} -//------------------------------------------------------------------------------ -char* fmtHex(uint32_t n, char* p) { - do { - uint8_t h = n & 0XF; - *--p = h + (h < 10 ? '0' : 'A' - 10); - n >>= 4; - } while (n); - return p; -} -//------------------------------------------------------------------------------ -float scanFloat(const char* str, char** ptr) { - int16_t const EXP_LIMIT = 100; - bool digit = false; - bool dot = false; - uint32_t fract = 0; - int fracExp = 0; - uint8_t nd = 0; - bool neg; - int c; - float v; - const char* successPtr = str; - - if (ptr) { - *ptr = const_cast(str); - } - - while (isSpace((c = *str++))) {} - neg = c == '-'; - if (c == '-' || c == '+') { - c = *str++; - } - // Skip leading zeros - while (c == '0') { - c = *str++; - digit = true; - } - for (;;) { - if (isDigit(c)) { - digit = true; - if (nd < 9) { - fract = 10*fract + c - '0'; - nd++; - if (dot) { - fracExp--; - } - } else { - if (!dot) { - fracExp++; - } - } - } else if (c == '.') { - if (dot) { - goto fail; - } - dot = true; - } else { - if (!digit) { - goto fail; - } - break; - } - successPtr = str; - c = *str++; - } - if (c == 'e' || c == 'E') { - int exp = 0; - c = *str++; - bool expNeg = c == '-'; - if (c == '-' || c == '+') { - c = *str++; - } - while (isDigit(c)) { - if (exp > EXP_LIMIT) { - goto fail; - } - exp = 10*exp + c - '0'; - successPtr = str; - c = *str++; - } - fracExp += expNeg ? -exp : exp; - } - if (ptr) { - *ptr = const_cast(successPtr); - } - v = scale10(static_cast(fract), fracExp); - return neg ? -v : v; - -fail: - return 0; -} - - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FmtNumber.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FmtNumber.h deleted file mode 100644 index daa926e..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/FmtNumber.h +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 FmtNumber_h -#define FmtNumber_h -// #include -inline bool isDigit(char c) { - return '0' <= c && c <= '9'; -} -inline bool isSpace(char c) { - return c == ' ' || (0X9 <= c && c <= 0XD); -} -#include -#include -char* fmtDec(uint16_t n, char* p); -char* fmtDec(uint32_t n, char* p); -char* fmtFloat(float value, char* p, uint8_t prec); -char* fmtFloat(float value, char* ptr, uint8_t prec, char expChar); -char* fmtHex(uint32_t n, char* p); -float scale10(float v, int8_t n); -float scanFloat(const char* str, char** ptr); -#endif // FmtNumber_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/StdioStream.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/StdioStream.cpp deleted file mode 100644 index a6d2e9b..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/StdioStream.cpp +++ /dev/null @@ -1,508 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#include "StdioStream.h" -#include "FmtNumber.h" -//------------------------------------------------------------------------------ -int StdioStream::fclose() { - int rtn = 0; - if (!m_status) { - return EOF; - } - if (m_status & S_SWR) { - if (!flushBuf()) { - rtn = EOF; - } - } - if (!FatFile::close()) { - rtn = EOF; - } - m_r = 0; - m_w = 0; - m_status = 0; - return rtn; -} -//------------------------------------------------------------------------------ -int StdioStream::fflush() { - if ((m_status & (S_SWR | S_SRW)) && !(m_status & S_SRD)) { - if (flushBuf() && FatFile::sync()) { - return 0; - } - } - return EOF; -} -//------------------------------------------------------------------------------ -char* StdioStream::fgets(char* str, size_t num, size_t* len) { - char* s = str; - size_t n; - if (num-- == 0) { - return 0; - } - while (num) { - if ((n = m_r) == 0) { - if (!fillBuf()) { - if (s == str) { - return 0; - } - break; - } - n = m_r; - } - if (n > num) { - n = num; - } - uint8_t* end = reinterpret_cast(memchr(m_p, '\n', n)); - if (end != 0) { - n = ++end - m_p; - memcpy(s, m_p, n); - m_r -= n; - m_p = end; - s += n; - break; - } - memcpy(s, m_p, n); - m_r -= n; - m_p += n; - s += n; - num -= n; - } - *s = 0; - if (len) { - *len = s - str; - } - return str; -} -//------------------------------------------------------------------------------ -bool StdioStream::fopen(const char* path, const char* mode) { - oflag_t oflag; - uint8_t m; - switch (*mode++) { - case 'a': - m = O_WRONLY; - oflag = O_CREAT | O_APPEND; - m_status = S_SWR; - break; - - case 'r': - m = O_RDONLY; - oflag = 0; - m_status = S_SRD; - break; - - case 'w': - m = O_WRONLY; - oflag = O_CREAT | O_TRUNC; - m_status = S_SWR; - break; - - default: - goto fail; - } - while (*mode) { - switch (*mode++) { - case '+': - m_status = S_SRW; - m = O_RDWR; - break; - - case 'b': - break; - - case 'x': - oflag |= O_EXCL; - break; - - default: - goto fail; - } - } - oflag |= m; - - if (!FatFile::open(path, oflag)) { - goto fail; - } - m_r = 0; - m_w = 0; - m_p = m_buf; - return true; - -fail: - m_status = 0; - return false; -} -//------------------------------------------------------------------------------ -int StdioStream::fputs(const char* str) { - size_t len = strlen(str); - return fwrite(str, 1, len) == len ? len : EOF; -} -//------------------------------------------------------------------------------ -size_t StdioStream::fread(void* ptr, size_t size, size_t count) { - uint8_t* dst = reinterpret_cast(ptr); - size_t total = size*count; - if (total == 0) { - return 0; - } - size_t need = total; - while (need > m_r) { - memcpy(dst, m_p, m_r); - dst += m_r; - m_p += m_r; - need -= m_r; - if (!fillBuf()) { - return (total - need)/size; - } - } - memcpy(dst, m_p, need); - m_r -= need; - m_p += need; - return count; -} -//------------------------------------------------------------------------------ -int StdioStream::fseek(int32_t offset, int origin) { - int32_t pos; - if (m_status & S_SWR) { - if (!flushBuf()) { - goto fail; - } - } - switch (origin) { - case SEEK_CUR: - pos = ftell(); - if (pos < 0) { - goto fail; - } - pos += offset; - if (!FatFile::seekCur(pos)) { - goto fail; - } - break; - - case SEEK_SET: - if (!FatFile::seekSet(offset)) { - goto fail; - } - break; - - case SEEK_END: - if (!FatFile::seekEnd(offset)) { - goto fail; - } - break; - - default: - goto fail; - } - m_r = 0; - m_p = m_buf; - return 0; - -fail: - return EOF; -} -//------------------------------------------------------------------------------ -int32_t StdioStream::ftell() { - uint32_t pos = FatFile::curPosition(); - if (m_status & S_SRD) { - if (m_r > pos) { - return -1L; - } - pos -= m_r; - } else if (m_status & S_SWR) { - pos += m_p - m_buf; - } - return pos; -} -//------------------------------------------------------------------------------ -size_t StdioStream::fwrite(const void* ptr, size_t size, size_t count) { - return write(ptr, count*size) < 0 ? EOF : count; -} -//------------------------------------------------------------------------------ -int StdioStream::write(const void* buf, size_t count) { - const uint8_t* src = static_cast(buf); - size_t todo = count; - - while (todo > m_w) { - memcpy(m_p, src, m_w); - m_p += m_w; - src += m_w; - todo -= m_w; - if (!flushBuf()) { - return EOF; - } - } - memcpy(m_p, src, todo); - m_p += todo; - m_w -= todo; - return count; -} -//------------------------------------------------------------------------------ -#if (defined(ARDUINO) && ENABLE_ARDUINO_FEATURES) || defined(DOXYGEN) -size_t StdioStream::print(const __FlashStringHelper *str) { - const char *p = (const char*)str; - uint8_t c; - while ((c = pgm_read_byte(p))) { - if (putc(c) < 0) { - return 0; - } - p++; - } - return p - (const char*)str; -} -#endif // (defined(ARDUINO) && ENABLE_ARDUINO_FEATURES) || defined(DOXYGEN) -//------------------------------------------------------------------------------ -int StdioStream::printDec(float value, uint8_t prec) { - char buf[24]; - char *ptr = fmtFloat(value, buf + sizeof(buf), prec); - return write(ptr, buf + sizeof(buf) - ptr); -} -//------------------------------------------------------------------------------ -int StdioStream::printDec(signed char n) { - if (n < 0) { - if (fputc('-') < 0) { - return -1; - } - n = -n; - } - return printDec((unsigned char)n); -} -//------------------------------------------------------------------------------ -int StdioStream::printDec(int16_t n) { - int s; - uint8_t rtn = 0; - if (n < 0) { - if (fputc('-') < 0) { - return -1; - } - n = -n; - rtn++; - } - if ((s = printDec((uint16_t)n)) < 0) { - return s; - } - return rtn; -} -//------------------------------------------------------------------------------ -int StdioStream::printDec(uint16_t n) { -#define NEW_WAY -#ifdef NEW_WAY - char buf[5]; - char *ptr = fmtDec(n, buf + sizeof(buf)); - uint8_t len = buf + sizeof(buf) - ptr; - return write(ptr, len); -#else - uint8_t len; - if (n < 100) { - len = n < 10 ? 1 : 2; - } else { - len = n < 1000 ? 3 : n < 10000 ? 4 : 5; - } - char* str = fmtSpace(len); - if (!str) { - return -1; - } - fmtDec(n, str); - return len; -#endif -} -//------------------------------------------------------------------------------ -int StdioStream::printDec(int32_t n) { - uint8_t s = 0; - if (n < 0) { - if (fputc('-') < 0) { - return -1; - } - n = -n; - s = 1; - } - int rtn = printDec((uint32_t)n); - return rtn > 0 ? rtn + s : -1; -} -//------------------------------------------------------------------------------ -int StdioStream::printDec(uint32_t n) { -#ifdef NEW_WAY - char buf[10]; - char *ptr = fmtDec(n, buf + sizeof(buf)); - uint8_t len = buf + sizeof(buf) - ptr; - return write(ptr, len); -#else - uint8_t len; - if (n < 0X10000) { - return printDec((uint16_t)n); - } - if (n < 10000000) { - len = n < 100000 ? 5 : n < 1000000 ? 6 : 7; - } else { - len = n < 100000000 ? 8 : n < 1000000000 ? 9 : 10; - } - - char* str = fmtSpace(len); - if (!str) { - return -1; - } - fmtDec(n, str); - return len; -#endif -} -//------------------------------------------------------------------------------ -int StdioStream::printHex(uint32_t n) { -#ifdef NEW_WAY - char buf[8]; - char *ptr = fmtHex(n, buf + sizeof(buf)); - uint8_t len = buf + sizeof(buf) - ptr; - return write(ptr, len); -#else - size_t len; - if (n < 0X10000) { - len = n < 0X10 ? 1 : n < 0X100 ? 2 : n < 0X1000 ? 3 : 4; - } else { - len = n < 0X100000 ? 5 : n < 0X1000000 ? 6 : n < 0X10000000 ? 7 : 8; - } - char* str = fmtSpace(len); - if (!str) { - return -1; - } - - do { - uint8_t h = n & 0XF; - *str-- = h + (h < 10 ? '0' : 'A' - 10); - n >>= 4; - } while (n); - return len; -#endif -} -//------------------------------------------------------------------------------ -bool StdioStream::rewind() { - if (m_status & S_SWR) { - if (!flushBuf()) { - return false; - } - } - FatFile::seekSet(0); - m_r = 0; - return true; -} -//------------------------------------------------------------------------------ -int StdioStream::ungetc(int c) { - // error if EOF. - if (c == EOF) { - return EOF; - } - // error if not reading. - if ((m_status & S_SRD) == 0) { - return EOF; - } - // error if no space. - if (m_p == m_buf) { - return EOF; - } - m_r++; - m_status &= ~S_EOF; - return *--m_p = (uint8_t)c; -} -//============================================================================== -// private -//------------------------------------------------------------------------------ -int StdioStream::fillGet() { - if (!fillBuf()) { - return EOF; - } - m_r--; - return *m_p++; -} -//------------------------------------------------------------------------------ -// private -bool StdioStream::fillBuf() { - if (!(m_status & - S_SRD)) { // check for S_ERR and S_EOF ??///////////////// - if (!(m_status & S_SRW)) { - m_status |= S_ERR; - return false; - } - if (m_status & S_SWR) { - if (!flushBuf()) { - return false; - } - m_status &= ~S_SWR; - m_status |= S_SRD; - m_w = 0; - } - } - m_p = m_buf + UNGETC_BUF_SIZE; - int nr = FatFile::read(m_p, sizeof(m_buf) - UNGETC_BUF_SIZE); - if (nr <= 0) { - m_status |= nr < 0 ? S_ERR : S_EOF; - m_r = 0; - return false; - } - m_r = nr; - return true; -} -//------------------------------------------------------------------------------ -// private -bool StdioStream::flushBuf() { - if (!(m_status & - S_SWR)) { // check for S_ERR ??//////////////////////// - if (!(m_status & S_SRW)) { - m_status |= S_ERR; - return false; - } - m_status &= ~S_SRD; - m_status |= S_SWR; - m_r = 0; - m_w = sizeof(m_buf); - m_p = m_buf; - return true; - } - uint8_t n = m_p - m_buf; - m_p = m_buf; - m_w = sizeof(m_buf); - if (FatFile::write(m_buf, n) == n) { - return true; - } - m_status |= S_ERR; - return false; -} -//------------------------------------------------------------------------------ -int StdioStream::flushPut(uint8_t c) { - if (!flushBuf()) { - return EOF; - } - m_w--; - return *m_p++ = c; -} -//------------------------------------------------------------------------------ -char* StdioStream::fmtSpace(uint8_t len) { - if (m_w < len) { - if (!flushBuf() || m_w < len) { - return 0; - } - } - if (len > m_w) { - return 0; - } - m_p += len; - m_w -= len; - return reinterpret_cast(m_p); -} - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/StdioStream.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/StdioStream.h deleted file mode 100644 index 9fcd064..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/StdioStream.h +++ /dev/null @@ -1,667 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 StdioStream_h -#define StdioStream_h -/** - * \file - * \brief StdioStream class - */ -#include -#include "FatFile.h" -//------------------------------------------------------------------------------ -/** Total size of stream buffer. The entire buffer is used for output. - * During input UNGETC_BUF_SIZE of this space is reserved for ungetc. - */ -const uint8_t STREAM_BUF_SIZE = 64; -/** Amount of buffer allocated for ungetc during input. */ -const uint8_t UNGETC_BUF_SIZE = 2; -//------------------------------------------------------------------------------ -// Get rid of any macros defined in . -#include -#undef clearerr -#undef fclose -#undef feof -#undef ferror -#undef fflush -#undef fgetc -#undef fgetpos -#undef fgets -#undef fopen -#undef fprintf -#undef fputc -#undef fputs -#undef fread -#undef freopen -#undef fscanf -#undef fseek -#undef fsetpos -#undef ftell -#undef fwrite -#undef getc -#undef getchar -#undef gets -#undef perror -//#undef printf // NOLINT -#undef putc -#undef putchar -#undef puts -#undef remove -#undef rename -#undef rewind -#undef scanf -#undef setbuf -#undef setvbuf -//#undef sprintf // NOLINT -#undef sscanf -#undef tmpfile -#undef tmpnam -#undef ungetc -#undef vfprintf -#undef vprintf -#undef vsprintf - -// make sure needed macros are defined -#ifndef EOF -/** End-of-file return value. */ -#define EOF (-1) -#endif // EOF -#ifndef NULL -/** Null pointer */ -#define NULL 0 -#endif // NULL -#ifndef SEEK_CUR -/** Seek relative to current position. */ -#define SEEK_CUR 1 -#endif // SEEK_CUR -#ifndef SEEK_END -/** Seek relative to end-of-file. */ -#define SEEK_END 2 -#endif // SEEK_END -#ifndef SEEK_SET -/** Seek relative to start-of-file. */ -#define SEEK_SET 0 -#endif // SEEK_SET -//------------------------------------------------------------------------------ -/** \class StdioStream - * \brief StdioStream implements a minimal stdio stream. - * - * StdioStream does not support subdirectories or long file names. - */ -class StdioStream : private FatFile { - public: - /** Constructor - * - */ - StdioStream() { - m_w = m_r = 0; - m_p = m_buf; - m_status = 0; - } - //---------------------------------------------------------------------------- - /** Clear the stream's end-of-file and error indicators. */ - void clearerr() { - m_status &= ~(S_ERR | S_EOF); - } - //---------------------------------------------------------------------------- - /** Close a stream. - * - * A successful call to the fclose function causes the stream to be - * flushed and the associated file to be closed. Any unwritten buffered - * data is written to the file; any unread buffered data is discarded. - * Whether or not the call succeeds, the stream is disassociated from - * the file. - * - * \return zero if the stream was successfully closed, or EOF if any any - * errors are detected. - */ - int fclose(); - //---------------------------------------------------------------------------- - /** Test the stream's end-of-file indicator. - * \return non-zero if and only if the end-of-file indicator is set. - */ - int feof() { - return (m_status & S_EOF) != 0; - } - //---------------------------------------------------------------------------- - /** Test the stream's error indicator. - * \return return non-zero if and only if the error indicator is set. - */ - int ferror() { - return (m_status & S_ERR) != 0; - } - //---------------------------------------------------------------------------- - /** Flush the stream. - * - * If stream is an output stream or an update stream in which the most - * recent operation was not input, any unwritten data is written to the - * file; otherwise the call is an error since any buffered input data - * would be lost. - * - * \return sets the error indicator for the stream and returns EOF if an - * error occurs, otherwise it returns zero. - */ - int fflush(); - //---------------------------------------------------------------------------- - /** Get a byte from the stream. - * - * \return If the end-of-file indicator for the stream is set, or if the - * stream is at end-of-file, the end-of-file indicator for the stream is - * set and the fgetc function returns EOF. Otherwise, the fgetc function - * returns the next character from the input stream. - */ - int fgetc() { - return m_r-- == 0 ? fillGet() : *m_p++; - } - //---------------------------------------------------------------------------- - /** Get a string from a stream. - * - * The fgets function reads at most one less than the number of - * characters specified by num from the stream into the array pointed - * to by str. No additional characters are read after a new-line - * character (which is retained) or after end-of-file. A null character - * is written immediately after the last character read into the array. - * - * \param[out] str Pointer to an array of where the string is copied. - * - * \param[in] num Maximum number of characters including the null - * character. - * - * \param[out] len If len is not null and fgets is successful, the - * length of the string is returned. - * - * \return str if successful. If end-of-file is encountered and no - * characters have been read into the array, the contents of the array - * remain unchanged and a null pointer is returned. If a read error - * occurs during the operation, the array contents are indeterminate - * and a null pointer is returned. - */ - char* fgets(char* str, size_t num, size_t* len = 0); - //---------------------------------------------------------------------------- - /** Open a stream. - * - * Open a file and associates the stream with it. - * - * \param[in] path file to be opened. - * - * \param[in] mode a string that indicates the open mode. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
"r" or "rb"Open a file for reading. The file must exist.
"w" or "wb"Truncate an existing to zero length or create an empty file - * for writing.
"wx" or "wbx"Create a file for writing. Fails if the file already exists.
"a" or "ab"Append; open or create file for writing at end-of-file.
"r+" or "rb+" or "r+b"Open a file for update (reading and writing).
"w+" or "w+b" or "wb+"Truncate an existing to zero length or create a file for update.
"w+x" or "w+bx" or "wb+x"Create a file for update. Fails if the file already exists.
"a+" or "a+b" or "ab+"Append; open or create a file for update, writing at end-of-file.
- * The character 'b' shall have no effect, but is allowed for ISO C - * standard conformance. - * - * Opening a file with append mode causes all subsequent writes to the - * file to be forced to the then current end-of-file, regardless of - * intervening calls to the fseek function. - * - * When a file is opened with update mode, both input and output may be - * performed on the associated stream. However, output shall not be - * directly followed by input without an intervening call to the fflush - * function or to a file positioning function (fseek, or rewind), and - * input shall not be directly followed by output without an intervening - * call to a file positioning function, unless the input operation - * encounters end-of-file. - * - * \return true for success or false for failure. - */ - bool fopen(const char* path, const char * mode); - //---------------------------------------------------------------------------- - /** Write a byte to a stream. - * - * \param[in] c the byte to be written (converted to an unsigned char). - * - * \return Upon successful completion, fputc() returns the value it - * has written. Otherwise, it returns EOF and sets the error indicator for - * the stream. - */ - int fputc(int c) { - return m_w-- == 0 ? flushPut(c) : *m_p++ = c; - } - //---------------------------------------------------------------------------- - /** Write a string to a stream. - * - * \param[in] str a pointer to the string to be written. - * - * \return for success, fputs() returns a non-negative - * number. Otherwise, it returns EOF and sets the error indicator for - * the stream. - */ - int fputs(const char* str); - //---------------------------------------------------------------------------- - /** Binary input. - * - * Reads an array of up to count elements, each one with a size of size - * bytes. - * \param[out] ptr pointer to area of at least (size*count) bytes where - * the data will be stored. - * - * \param[in] size the size, in bytes, of each element to be read. - * - * \param[in] count the number of elements to be read. - * - * \return number of elements successfully read, which may be less than - * count if a read error or end-of-file is encountered. If size or count - * is zero, fread returns zero and the contents of the array and the - * state of the stream remain unchanged. - */ - size_t fread(void* ptr, size_t size, size_t count); - //---------------------------------------------------------------------------- - /** Set the file position for the stream. - * - * \param[in] offset number of offset from the origin. - * - * \param[in] origin position used as reference for the offset. It is - * specified by one of the following constants. - * - * SEEK_SET - Beginning of file. - * - * SEEK_CUR - Current position of the file pointer. - * - * SEEK_END - End of file. - * - * \return zero for success. Otherwise, it returns non-zero and sets the - * error indicator for the stream. - */ - int fseek(int32_t offset, int origin); - //---------------------------------------------------------------------------- - /** Get the current position in a stream. - * - * \return If successful, ftell return the current value of the position - * indicator. On failure, ftell returns −1L. - */ - int32_t ftell(); - //---------------------------------------------------------------------------- - /** Binary output. - * - * Writes an array of up to count elements, each one with a size of size - * bytes. - * \param[in] ptr pointer to (size*count) bytes of data to be written. - * - * \param[in] size the size, in bytes, of each element to be written. - * - * \param[in] count the number of elements to be written. - * - * \return number of elements successfully written. if this number is - * less than count, an error has occurred. If size or count is zero, - * fwrite returns zero. - */ - size_t fwrite(const void * ptr, size_t size, size_t count); - //---------------------------------------------------------------------------- - /** Get a byte from the stream. - * - * getc and fgetc are equivalent but getc is in-line so it is faster but - * require more flash memory. - * - * \return If the end-of-file indicator for the stream is set, or if the - * stream is at end-of-file, the end-of-file indicator for the stream is - * set and the fgetc function returns EOF. Otherwise, the fgetc function - * returns the next character from the input stream. - */ - inline __attribute__((always_inline)) - int getc() { - return m_r-- == 0 ? fillGet() : *m_p++; - } - //---------------------------------------------------------------------------- - /** Write a byte to a stream. - * - * putc and fputc are equivalent but putc is in-line so it is faster but - * require more flash memory. - * - * \param[in] c the byte to be written (converted to an unsigned char). - * - * \return Upon successful completion, fputc() returns the value it - * has written. Otherwise, it returns EOF and sets the error indicator for - * the stream. - */ - inline __attribute__((always_inline)) - int putc(int c) { - return m_w-- == 0 ? flushPut(c) : *m_p++ = c; - } - //---------------------------------------------------------------------------- - /** Write a CR/LF. - * - * \return two, the number of bytes written, for success or -1 for failure. - */ - inline __attribute__((always_inline)) - int putCRLF() { - if (m_w < 2) { - if (!flushBuf()) { - return -1; - } - } - *m_p++ = '\r'; - *m_p++ = '\n'; - m_w -= 2; - return 2; - } - //---------------------------------------------------------------------------- - /** Write a character. - * \param[in] c the character to write. - * \return the number of bytes written. - */ - size_t print(char c) { - return putc(c) < 0 ? 0 : 1; - } - //---------------------------------------------------------------------------- - /** Write a string. - * - * \param[in] str the string to be written. - * - * \return the number of bytes written. - */ - size_t print(const char* str) { - int n = fputs(str); - return n < 0 ? 0 : n; - } - //---------------------------------------------------------------------------- -#if (defined(ARDUINO) && ENABLE_ARDUINO_FEATURES) || defined(DOXYGEN) - /** Print a string stored in flash memory. - * - * \param[in] str the string to print. - * - * \return the number of bytes written. - */ - size_t print(const __FlashStringHelper *str); -#endif // (defined(ARDUINO) && ENABLE_ARDUINO_FEATURES) || defined(DOXYGEN) - //---------------------------------------------------------------------------- - /** Print a floating point number. - * - * \param[in] prec Number of digits after decimal point. - * - * \param[in] val the number to be printed. - * - * \return the number of bytes written. - */ - size_t print(double val, uint8_t prec = 2) { - return print(static_cast(val), prec); - } - //---------------------------------------------------------------------------- - /** Print a floating point number. - * - * \param[in] prec Number of digits after decimal point. - * - * \param[in] val the number to be printed. - * - * \return the number of bytes written. - */ - size_t print(float val, uint8_t prec = 2) { - int n = printDec(val, prec); - return n > 0 ? n : 0; - } - //---------------------------------------------------------------------------- - /** Print a number. - * - * \param[in] val the number to be printed. - * - * \return the number of bytes written. - */ - template - size_t print(T val) { - int n = printDec(val); - return n > 0 ? n : 0; - } - //---------------------------------------------------------------------------- - /** Write a CR/LF. - * - * \return two, the number of bytes written, for success or zero for failure. - */ - size_t println() { - return putCRLF() > 0 ? 2 : 0; - } - //---------------------------------------------------------------------------- - /** Print a floating point number followed by CR/LF. - * - * \param[in] val the number to be printed. - * - * \param[in] prec Number of digits after decimal point. - * - * \return the number of bytes written. - */ - size_t println(double val, uint8_t prec = 2) { - return println(static_cast(val), prec); - } - //---------------------------------------------------------------------------- - /** Print a floating point number followed by CR/LF. - * - * \param[in] val the number to be printed. - * - * \param[in] prec Number of digits after decimal point. - * - * \return the number of bytes written. - */ - size_t println(float val, uint8_t prec = 2) { - int n = printDec(val, prec); - return n > 0 && putCRLF() > 0 ? n + 2 : 0; - } - //---------------------------------------------------------------------------- - /** Print an item followed by CR/LF - * - * \param[in] val the item to be printed. - * - * \return the number of bytes written. - */ - template - size_t println(T val) { - int n = print(val); - return putCRLF() > 0 ? n + 2 : 0; - } - //---------------------------------------------------------------------------- - /** Print a char as a number. - * \param[in] n number to be printed. - * \return The number of bytes written or -1 if an error occurs. - */ - int printDec(char n) { - if (CHAR_MIN == 0) { - return printDec((unsigned char)n); - } else { - return printDec((signed char)n); - } - } - //---------------------------------------------------------------------------- - /** print a signed 8-bit integer - * \param[in] n number to be printed. - * \return The number of bytes written or -1 if an error occurs. - */ - int printDec(signed char n); - //---------------------------------------------------------------------------- - /** Print an unsigned 8-bit number. - * \param[in] n number to be print. - * \return The number of bytes written or -1 if an error occurs. - */ - int printDec(unsigned char n) { - return printDec((uint16_t)n); - } - //---------------------------------------------------------------------------- - /** Print a int16_t - * \param[in] n number to be printed. - * \return The number of bytes written or -1 if an error occurs. - */ - int printDec(int16_t n); - //---------------------------------------------------------------------------- - /** print a uint16_t. - * \param[in] n number to be printed. - * \return The number of bytes written or -1 if an error occurs. - */ - int printDec(uint16_t n); - //---------------------------------------------------------------------------- - /** Print a signed 32-bit integer. - * \param[in] n number to be printed. - * \return The number of bytes written or -1 if an error occurs. - */ - int printDec(int32_t n); - //---------------------------------------------------------------------------- - /** Write an unsigned 32-bit number. - * \param[in] n number to be printed. - * \return The number of bytes written or -1 if an error occurs. - */ - int printDec(uint32_t n); - //---------------------------------------------------------------------------- - /** Print a double. - * \param[in] value The number to be printed. - * \param[in] prec Number of digits after decimal point. - * \return The number of bytes written or -1 if an error occurs. - */ - int printDec(double value, uint8_t prec) { - return printDec(static_cast(value), prec); - } - //---------------------------------------------------------------------------- - /** Print a float. - * \param[in] value The number to be printed. - * \param[in] prec Number of digits after decimal point. - * \return The number of bytes written or -1 if an error occurs. - */ - int printDec(float value, uint8_t prec); - //---------------------------------------------------------------------------- - /** Print a number followed by a field terminator. - * \param[in] value The number to be printed. - * \param[in] term The field terminator. - * \param[in] prec Number of digits after decimal point. - * \return The number of bytes written or -1 if an error occurs. - */ - int printField(double value, char term, uint8_t prec = 2) { - return printField(static_cast(value), term, prec) > 0; - } - //---------------------------------------------------------------------------- - /** Print a number followed by a field terminator. - * \param[in] value The number to be printed. - * \param[in] term The field terminator. - * \param[in] prec Number of digits after decimal point. - * \return The number of bytes written or -1 if an error occurs. - */ - int printField(float value, char term, uint8_t prec = 2) { - int rtn = printDec(value, prec); - return rtn < 0 || putc(term) < 0 ? -1 : rtn + 1; - } - //---------------------------------------------------------------------------- - /** Print a number followed by a field terminator. - * \param[in] value The number to be printed. - * \param[in] term The field terminator. - * \return The number of bytes written or -1 if an error occurs. - */ - template - int printField(T value, char term) { - int rtn = printDec(value); - return rtn < 0 || putc(term) < 0 ? -1 : rtn + 1; - } - //---------------------------------------------------------------------------- - /** Print HEX - * \param[in] n number to be printed as HEX. - * - * \return The number of bytes written or -1 if an error occurs. - */ - int printHex(uint32_t n); - //---------------------------------------------------------------------------- - /** Print HEX with CRLF - * \param[in] n number to be printed as HEX. - * - * \return The number of bytes written or -1 if an error occurs. - */ - int printHexln(uint32_t n) { - int rtn = printHex(n); - return rtn < 0 || putCRLF() != 2 ? -1 : rtn + 2; - } - //---------------------------------------------------------------------------- - /** Set position of a stream to the beginning. - * - * The rewind function sets the file position to the beginning of the - * file. It is equivalent to fseek(0L, SEEK_SET) except that the error - * indicator for the stream is also cleared. - * - * \return true for success or false for failure. - */ - bool rewind(); - //---------------------------------------------------------------------------- - /** Push a byte back into an input stream. - * - * \param[in] c the byte (converted to an unsigned char) to be pushed back. - * - * One character of push-back is guaranteed. If the ungetc function is - * called too many times without an intervening read or file positioning - * operation on that stream, the operation may fail. - * - * A successful intervening call to a file positioning function (fseek, - * fsetpos, or rewind) discards any pushed-back characters for the stream. - * - * \return Upon successful completion, ungetc() returns the byte pushed - * back after conversion. Otherwise it returns EOF. - */ - int ungetc(int c); - //============================================================================ - private: - bool fillBuf(); - int fillGet(); - bool flushBuf(); - int flushPut(uint8_t c); - char* fmtSpace(uint8_t len); - int write(const void* buf, size_t count); - //---------------------------------------------------------------------------- - // S_SRD and S_WR are never simultaneously asserted - static const uint8_t S_SRD = 0x01; // OK to read - static const uint8_t S_SWR = 0x02; // OK to write - static const uint8_t S_SRW = 0x04; // open for reading & writing - static const uint8_t S_EOF = 0x10; // found EOF - static const uint8_t S_ERR = 0x20; // found error - //---------------------------------------------------------------------------- - uint8_t m_status; - uint8_t* m_p; - uint8_t m_r; - uint8_t m_w; - uint8_t m_buf[STREAM_BUF_SIZE]; -}; -//------------------------------------------------------------------------------ -#endif // StdioStream_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/bufstream.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/bufstream.h deleted file mode 100644 index 5390aa7..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/bufstream.h +++ /dev/null @@ -1,172 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 bufstream_h -#define bufstream_h -/** - * \file - * \brief \ref ibufstream and \ref obufstream classes - */ -#include -#include "iostream.h" -//============================================================================== -/** - * \class ibufstream - * \brief parse a char string - */ -class ibufstream : public istream { - public: - /** Constructor */ - ibufstream() : m_buf(0), m_len(0) {} - /** Constructor - * \param[in] str pointer to string to be parsed - * Warning: The string will not be copied so must stay in scope. - */ - explicit ibufstream(const char* str) { - init(str); - } - /** Initialize an ibufstream - * \param[in] str pointer to string to be parsed - * Warning: The string will not be copied so must stay in scope. - */ - void init(const char* str) { - m_buf = str; - m_len = strlen(m_buf); - m_pos = 0; - clear(); - } - - protected: - /// @cond SHOW_PROTECTED - int16_t getch() { - if (m_pos < m_len) { - return m_buf[m_pos++]; - } - setstate(eofbit); - return -1; - } - void getpos(FatPos_t *pos) { - pos->position = m_pos; - } - bool seekoff(off_type off, seekdir way) { - (void)off; - (void)way; - return false; - } - bool seekpos(pos_type pos) { - if (pos < m_len) { - m_pos = pos; - return true; - } - return false; - } - void setpos(FatPos_t *pos) { - m_pos = pos->position; - } - pos_type tellpos() { - return m_pos; - } - /// @endcond - private: - const char* m_buf; - size_t m_len; - size_t m_pos; -}; -//============================================================================== -/** - * \class obufstream - * \brief format a char string - */ -class obufstream : public ostream { - public: - /** constructor */ - obufstream() : m_in(0) {} - /** Constructor - * \param[in] buf buffer for formatted string - * \param[in] size buffer size - */ - obufstream(char *buf, size_t size) { - init(buf, size); - } - /** Initialize an obufstream - * \param[in] buf buffer for formatted string - * \param[in] size buffer size - */ - void init(char *buf, size_t size) { - m_buf = buf; - buf[0] = '\0'; - m_size = size; - m_in = 0; - } - /** \return a pointer to the buffer */ - char* buf() { - return m_buf; - } - /** \return the length of the formatted string */ - size_t length() { - return m_in; - } - - protected: - /// @cond SHOW_PROTECTED - void putch(char c) { - if (m_in >= (m_size - 1)) { - setstate(badbit); - return; - } - m_buf[m_in++] = c; - m_buf[m_in] = '\0'; - } - void putstr(const char *str) { - while (*str) { - putch(*str++); - } - } - bool seekoff(off_type off, seekdir way) { - (void)off; - (void)way; - return false; - } - bool seekpos(pos_type pos) { - if (pos > m_in) { - return false; - } - m_in = pos; - m_buf[m_in] = '\0'; - return true; - } - bool sync() { - return true; - } - - pos_type tellpos() { - return m_in; - } - /// @endcond - private: - char *m_buf; - size_t m_size; - size_t m_in; -}; -#endif // bufstream_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/fstream.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/fstream.cpp deleted file mode 100644 index a5a0541..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/fstream.cpp +++ /dev/null @@ -1,172 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#include "fstream.h" -//============================================================================== -/// @cond SHOW_PROTECTED -int16_t FatStreamBase::getch() { - uint8_t c; - int8_t s = read(&c, 1); - if (s != 1) { - if (s < 0) { - setstate(badbit); - } else { - setstate(eofbit); - } - return -1; - } - if (c != '\r' || (getmode() & ios::binary)) { - return c; - } - s = read(&c, 1); - if (s == 1 && c == '\n') { - return c; - } - if (s == 1) { - seekCur(-1); - } - return '\r'; -} -//------------------------------------------------------------------------------ -void FatStreamBase::open(const char* path, ios::openmode mode) { - oflag_t oflag; - switch (mode & (app | in | out | trunc)) { - case app | in: - case app | in | out: - oflag = O_RDWR | O_APPEND | O_CREAT; - break; - - case app: - case app | out: - oflag = O_WRONLY | O_APPEND | O_CREAT; - break; - - case in: - oflag = O_RDONLY; - break; - - case in | out: - oflag = O_RDWR; - break; - - case in | out | trunc: - oflag = O_RDWR | O_TRUNC | O_CREAT; - break; - - case out: - case out | trunc: - oflag = O_WRONLY | O_TRUNC | O_CREAT; - break; - - default: - goto fail; - } - if (mode & ios::ate) { - oflag |= O_AT_END; - } - if (!FatFile::open(path, oflag)) { - goto fail; - } - setmode(mode); - clear(); - return; - -fail: - FatFile::close(); - setstate(failbit); - return; -} -//------------------------------------------------------------------------------ -void FatStreamBase::putch(char c) { - if (c == '\n' && !(getmode() & ios::binary)) { - write('\r'); - } - write(c); - if (getWriteError()) { - setstate(badbit); - } -} -//------------------------------------------------------------------------------ -void FatStreamBase::putstr(const char* str) { - size_t n = 0; - while (1) { - char c = str[n]; - if (c == '\0' || (c == '\n' && !(getmode() & ios::binary))) { - if (n > 0) { - write(str, n); - } - if (c == '\0') { - break; - } - write('\r'); - str += n; - n = 0; - } - n++; - } - if (getWriteError()) { - setstate(badbit); - } -} -//------------------------------------------------------------------------------ -/** Internal do not use - * \param[in] off - * \param[in] way - */ -bool FatStreamBase::seekoff(off_type off, seekdir way) { - pos_type pos; - switch (way) { - case beg: - pos = off; - break; - - case cur: - pos = curPosition() + off; - break; - - case end: - pos = fileSize() + off; - break; - - default: - return false; - } - return seekpos(pos); -} -//------------------------------------------------------------------------------ -/** Internal do not use - * \param[in] pos - */ -bool FatStreamBase::seekpos(pos_type pos) { - return seekSet(pos); -} -//------------------------------------------------------------------------------ -int FatStreamBase::write(const void* buf, size_t n) { - return FatFile::write(buf, n); -} -//------------------------------------------------------------------------------ -void FatStreamBase::write(char c) { - write(&c, 1); -} -/// @endcond diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/fstream.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/fstream.h deleted file mode 100644 index e0228cd..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/fstream.h +++ /dev/null @@ -1,320 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 fstream_h -#define fstream_h -/** - * \file - * \brief \ref fstream, \ref ifstream, and \ref ofstream classes - */ -#include "FatFile.h" -#include "iostream.h" -//============================================================================== -/** - * \class FatStreamBase - * \brief Base class for C++ style streams - */ -class FatStreamBase : protected FatFile, virtual public ios { - protected: - /// @cond SHOW_PROTECTED - int16_t getch(); - void putch(char c); - void putstr(const char *str); - void open(const char* path, ios::openmode mode); - /** Internal do not use - * \return mode - */ - ios::openmode getmode() { - return m_mode; - } - /** Internal do not use - * \param[in] mode - */ - void setmode(ios::openmode mode) { - m_mode = mode; - } - bool seekoff(off_type off, seekdir way); - bool seekpos(pos_type pos); - int write(const void* buf, size_t n); - void write(char c); - /// @endcond - private: - ios::openmode m_mode; -}; -//============================================================================== -/** - * \class fstream - * \brief file input/output stream. - */ -class fstream : public iostream, FatStreamBase { - public: - using iostream::peek; - fstream() {} - /** Constructor with open - * - * \param[in] path path to open - * \param[in] mode open mode - */ - explicit fstream(const char* path, openmode mode = in | out) { - open(path, mode); - } -#if DESTRUCTOR_CLOSES_FILE - ~fstream() {} -#endif // DESTRUCTOR_CLOSES_FILE - /** Clear state and writeError - * \param[in] state new state for stream - */ - void clear(iostate state = goodbit) { - ios::clear(state); - FatFile::clearWriteError(); - } - /** Close a file and force cached data and directory information - * to be written to the storage device. - */ - void close() { - FatFile::close(); - } - /** Open a fstream - * \param[in] path file to open - * \param[in] mode open mode - * - * Valid open modes are (at end, ios::ate, and/or ios::binary may be added): - * - * ios::in - Open file for reading. - * - * ios::out or ios::out | ios::trunc - Truncate to 0 length, if existent, - * or create a file for writing only. - * - * ios::app or ios::out | ios::app - Append; open or create file for - * writing at end-of-file. - * - * ios::in | ios::out - Open file for update (reading and writing). - * - * ios::in | ios::out | ios::trunc - Truncate to zero length, if existent, - * or create file for update. - * - * ios::in | ios::app or ios::in | ios::out | ios::app - Append; open or - * create text file for update, writing at end of file. - */ - void open(const char* path, openmode mode = in | out) { - FatStreamBase::open(path, mode); - } - /** \return True if stream is open else false. */ - bool is_open() { - return FatFile::isOpen(); - } - - protected: - /// @cond SHOW_PROTECTED - /** Internal - do not use - * \return - */ - int16_t getch() { - return FatStreamBase::getch(); - } - /** Internal - do not use - * \param[out] pos - */ - void getpos(FatPos_t* pos) { - FatFile::getpos(pos); - } - /** Internal - do not use - * \param[in] c - */ - void putch(char c) { - FatStreamBase::putch(c); - } - /** Internal - do not use - * \param[in] str - */ - void putstr(const char *str) { - FatStreamBase::putstr(str); - } - /** Internal - do not use - * \param[in] pos - */ - bool seekoff(off_type off, seekdir way) { - return FatStreamBase::seekoff(off, way); - } - bool seekpos(pos_type pos) { - return FatStreamBase::seekpos(pos); - } - void setpos(FatPos_t* pos) { - FatFile::setpos(pos); - } - bool sync() { - return FatStreamBase::sync(); - } - pos_type tellpos() { - return FatStreamBase::curPosition(); - } - /// @endcond -}; -//============================================================================== -/** - * \class ifstream - * \brief file input stream. - */ -class ifstream : public istream, FatStreamBase { - public: - using istream::peek; - ifstream() {} - /** Constructor with open - * \param[in] path file to open - * \param[in] mode open mode - */ - explicit ifstream(const char* path, openmode mode = in) { - open(path, mode); - } -#if DESTRUCTOR_CLOSES_FILE - ~ifstream() {} -#endif // DESTRUCTOR_CLOSES_FILE - /** Close a file and force cached data and directory information - * to be written to the storage device. - */ - void close() { - FatFile::close(); - } - /** \return True if stream is open else false. */ - bool is_open() { - return FatFile::isOpen(); - } - /** Open an ifstream - * \param[in] path file to open - * \param[in] mode open mode - * - * \a mode See fstream::open() for valid modes. - */ - void open(const char* path, openmode mode = in) { - FatStreamBase::open(path, mode | in); - } - - protected: - /// @cond SHOW_PROTECTED - /** Internal - do not use - * \return - */ - int16_t getch() { - return FatStreamBase::getch(); - } - /** Internal - do not use - * \param[out] pos - */ - void getpos(FatPos_t* pos) { - FatFile::getpos(pos); - } - /** Internal - do not use - * \param[in] pos - */ - bool seekoff(off_type off, seekdir way) { - return FatStreamBase::seekoff(off, way); - } - bool seekpos(pos_type pos) { - return FatStreamBase::seekpos(pos); - } - void setpos(FatPos_t* pos) { - FatFile::setpos(pos); - } - pos_type tellpos() { - return FatStreamBase::curPosition(); - } - /// @endcond -}; -//============================================================================== -/** - * \class ofstream - * \brief file output stream. - */ -class ofstream : public ostream, FatStreamBase { - public: - ofstream() {} - /** Constructor with open - * \param[in] path file to open - * \param[in] mode open mode - */ - explicit ofstream(const char* path, ios::openmode mode = out) { - open(path, mode); - } -#if DESTRUCTOR_CLOSES_FILE - ~ofstream() {} -#endif // DESTRUCTOR_CLOSES_FILE - /** Clear state and writeError - * \param[in] state new state for stream - */ - void clear(iostate state = goodbit) { - ios::clear(state); - FatFile::clearWriteError(); - } - /** Close a file and force cached data and directory information - * to be written to the storage device. - */ - void close() { - FatFile::close(); - } - /** Open an ofstream - * \param[in] path file to open - * \param[in] mode open mode - * - * \a mode See fstream::open() for valid modes. - */ - void open(const char* path, openmode mode = out) { - FatStreamBase::open(path, mode | out); - } - /** \return True if stream is open else false. */ - bool is_open() { - return FatFile::isOpen(); - } - - protected: - /// @cond SHOW_PROTECTED - /** - * Internal do not use - * \param[in] c - */ - void putch(char c) { - FatStreamBase::putch(c); - } - void putstr(const char* str) { - FatStreamBase::putstr(str); - } - bool seekoff(off_type off, seekdir way) { - return FatStreamBase::seekoff(off, way); - } - bool seekpos(pos_type pos) { - return FatStreamBase::seekpos(pos); - } - /** - * Internal do not use - * \param[in] b - */ - bool sync() { - return FatStreamBase::sync(); - } - pos_type tellpos() { - return FatStreamBase::curPosition(); - } - /// @endcond -}; -//------------------------------------------------------------------------------ -#endif // fstream_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ios.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ios.h deleted file mode 100644 index 7085f2c..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ios.h +++ /dev/null @@ -1,423 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 ios_h -#define ios_h -#include "FatFile.h" -/** - * \file - * \brief \ref ios_base and \ref ios classes - */ -//============================================================================== -/** - * \class ios_base - * \brief Base class for all streams - */ -class ios_base { - public: - /** typedef for iostate bitmask */ - typedef unsigned char iostate; - // State flags. - /** iostate for no flags */ - static const iostate goodbit = 0x00; - /** iostate bad bit for a nonrecoverable error. */ - static const iostate badbit = 0X01; - /** iostate bit for end of file reached */ - static const iostate eofbit = 0x02; - /** iostate fail bit for nonfatal error */ - static const iostate failbit = 0X04; - /** - * unsigned size that can represent maximum file size. - * (violates spec - should be signed) - */ - typedef uint32_t streamsize; - /** type for absolute seek position */ - typedef uint32_t pos_type; - /** type for relative seek offset */ - typedef int32_t off_type; - - /** enumerated type for the direction of relative seeks */ - enum seekdir { - /** seek relative to the beginning of the stream */ - beg, - /** seek relative to the current stream position */ - cur, - /** seek relative to the end of the stream */ - end - }; - /** type for format flags */ - typedef unsigned int fmtflags; - /** left adjust fields */ - static const fmtflags left = 0x0001; - /** right adjust fields */ - static const fmtflags right = 0x0002; - /** fill between sign/base prefix and number */ - static const fmtflags internal = 0x0004; - /** base 10 flag*/ - static const fmtflags dec = 0x0008; - /** base 16 flag */ - static const fmtflags hex = 0x0010; - /** base 8 flag */ - static const fmtflags oct = 0x0020; - // static const fmtflags fixed = 0x0040; - // static const fmtflags scientific = 0x0080; - /** use strings true/false for bool */ - static const fmtflags boolalpha = 0x0100; - /** use prefix 0X for hex and 0 for oct */ - static const fmtflags showbase = 0x0200; - /** always show '.' for floating numbers */ - static const fmtflags showpoint = 0x0400; - /** show + sign for nonnegative numbers */ - static const fmtflags showpos = 0x0800; - /** skip initial white space */ - static const fmtflags skipws = 0x1000; - // static const fmtflags unitbuf = 0x2000; - /** use uppercase letters in number representations */ - static const fmtflags uppercase = 0x4000; - /** mask for adjustfield */ - static const fmtflags adjustfield = left | right | internal; - /** mask for basefield */ - static const fmtflags basefield = dec | hex | oct; - // static const fmtflags floatfield = scientific | fixed; - //---------------------------------------------------------------------------- - /** typedef for iostream open mode */ - typedef uint8_t openmode; - - // Openmode flags. - /** seek to end before each write */ - static const openmode app = 0X4; - /** open and seek to end immediately after opening */ - static const openmode ate = 0X8; - /** perform input and output in binary mode (as opposed to text mode) */ - static const openmode binary = 0X10; - /** open for input */ - static const openmode in = 0X20; - /** open for output */ - static const openmode out = 0X40; - /** truncate an existing stream when opening */ - static const openmode trunc = 0X80; - //---------------------------------------------------------------------------- - ios_base() : m_fill(' '), m_fmtflags(dec | right | skipws) - , m_precision(2), m_width(0) {} - /** \return fill character */ - char fill() { - return m_fill; - } - /** Set fill character - * \param[in] c new fill character - * \return old fill character - */ - char fill(char c) { - char r = m_fill; - m_fill = c; - return r; - } - /** \return format flags */ - fmtflags flags() const { - return m_fmtflags; - } - /** set format flags - * \param[in] fl new flag - * \return old flags - */ - fmtflags flags(fmtflags fl) { - fmtflags tmp = m_fmtflags; - m_fmtflags = fl; - return tmp; - } - /** \return precision */ - int precision() const { - return m_precision; - } - /** set precision - * \param[in] n new precision - * \return old precision - */ - int precision(unsigned int n) { - int r = m_precision; - m_precision = n; - return r; - } - /** set format flags - * \param[in] fl new flags to be or'ed in - * \return old flags - */ - fmtflags setf(fmtflags fl) { - fmtflags r = m_fmtflags; - m_fmtflags |= fl; - return r; - } - /** modify format flags - * \param[in] mask flags to be removed - * \param[in] fl flags to be set after mask bits have been cleared - * \return old flags - */ - fmtflags setf(fmtflags fl, fmtflags mask) { - fmtflags r = m_fmtflags; - m_fmtflags &= ~mask; - m_fmtflags |= fl; - return r; - } - /** clear format flags - * \param[in] fl flags to be cleared - * \return old flags - */ - void unsetf(fmtflags fl) { - m_fmtflags &= ~fl; - } - /** \return width */ - unsigned width() { - return m_width; - } - /** set width - * \param[in] n new width - * \return old width - */ - unsigned width(unsigned n) { - unsigned r = m_width; - m_width = n; - return r; - } - - protected: - /** \return current number base */ - uint8_t flagsToBase() { - uint8_t f = flags() & basefield; - return f == oct ? 8 : f != hex ? 10 : 16; - } - - private: - char m_fill; - fmtflags m_fmtflags; - unsigned char m_precision; - unsigned int m_width; -}; -//------------------------------------------------------------------------------ -/** function for boolalpha manipulator - * \param[in] str The stream - * \return The stream - */ -inline ios_base& boolalpha(ios_base& str) { - str.setf(ios_base::boolalpha); - return str; -} -/** function for dec manipulator - * \param[in] str The stream - * \return The stream - */ -inline ios_base& dec(ios_base& str) { - str.setf(ios_base::dec, ios_base::basefield); - return str; -} -/** function for hex manipulator - * \param[in] str The stream - * \return The stream - */ -inline ios_base& hex(ios_base& str) { - str.setf(ios_base::hex, ios_base::basefield); - return str; -} -/** function for internal manipulator - * \param[in] str The stream - * \return The stream - */ -inline ios_base& internal(ios_base& str) { - str.setf(ios_base::internal, ios_base::adjustfield); - return str; -} -/** function for left manipulator - * \param[in] str The stream - * \return The stream - */ -inline ios_base& left(ios_base& str) { - str.setf(ios_base::left, ios_base::adjustfield); - return str; -} -/** function for noboolalpha manipulator - * \param[in] str The stream - * \return The stream - */ -inline ios_base& noboolalpha(ios_base& str) { - str.unsetf(ios_base::boolalpha); - return str; -} -/** function for noshowbase manipulator - * \param[in] str The stream - * \return The stream - */ -inline ios_base& noshowbase(ios_base& str) { - str.unsetf(ios_base::showbase); - return str; -} -/** function for noshowpoint manipulator - * \param[in] str The stream - * \return The stream - */ -inline ios_base& noshowpoint(ios_base& str) { - str.unsetf(ios_base::showpoint); - return str; -} -/** function for noshowpos manipulator - * \param[in] str The stream - * \return The stream - */ -inline ios_base& noshowpos(ios_base& str) { - str.unsetf(ios_base::showpos); - return str; -} -/** function for noskipws manipulator - * \param[in] str The stream - * \return The stream - */ -inline ios_base& noskipws(ios_base& str) { - str.unsetf(ios_base::skipws); - return str; -} -/** function for nouppercase manipulator - * \param[in] str The stream - * \return The stream - */ -inline ios_base& nouppercase(ios_base& str) { - str.unsetf(ios_base::uppercase); - return str; -} -/** function for oct manipulator - * \param[in] str The stream - * \return The stream - */ -inline ios_base& oct(ios_base& str) { - str.setf(ios_base::oct, ios_base::basefield); - return str; -} -/** function for right manipulator - * \param[in] str The stream - * \return The stream - */ -inline ios_base& right(ios_base& str) { - str.setf(ios_base::right, ios_base::adjustfield); - return str; -} -/** function for showbase manipulator - * \param[in] str The stream - * \return The stream - */ -inline ios_base& showbase(ios_base& str) { - str.setf(ios_base::showbase); - return str; -} -/** function for showpos manipulator - * \param[in] str The stream - * \return The stream - */ -inline ios_base& showpos(ios_base& str) { - str.setf(ios_base::showpos); - return str; -} -/** function for showpoint manipulator - * \param[in] str The stream - * \return The stream - */ -inline ios_base& showpoint(ios_base& str) { - str.setf(ios_base::showpoint); - return str; -} -/** function for skipws manipulator - * \param[in] str The stream - * \return The stream - */ -inline ios_base& skipws(ios_base& str) { - str.setf(ios_base::skipws); - return str; -} -/** function for uppercase manipulator - * \param[in] str The stream - * \return The stream - */ -inline ios_base& uppercase(ios_base& str) { - str.setf(ios_base::uppercase); - return str; -} -//============================================================================== -/** - * \class ios - * \brief Error and state information for all streams - */ -class ios : public ios_base { - public: - /** Create ios with no error flags set */ - ios() : m_iostate(0) {} - - /** \return null pointer if fail() is true. */ - operator const void*() const { - return !fail() ? reinterpret_cast(this) : 0; - } - /** \return true if fail() else false. */ - bool operator!() const { - return fail(); - } - /** \return The iostate flags for this file. */ - iostate rdstate() const { - return m_iostate; - } - /** \return True if no iostate flags are set else false. */ - bool good() const { - return m_iostate == goodbit; - } - /** \return true if end of file has been reached else false. - * - * Warning: An empty file returns false before the first read. - * - * Moral: eof() is only useful in combination with fail(), to find out - * whether EOF was the cause for failure - */ - bool eof() const { - return m_iostate & eofbit; - } - /** \return true if any iostate bit other than eof are set else false. */ - bool fail() const { - return m_iostate & (failbit | badbit); - } - /** \return true if bad bit is set else false. */ - bool bad() const { - return m_iostate & badbit; - } - /** Clear iostate bits. - * - * \param[in] state The flags you want to set after clearing all flags. - **/ - void clear(iostate state = goodbit) { - m_iostate = state; - } - /** Set iostate bits. - * - * \param[in] state Bitts to set. - **/ - void setstate(iostate state) { - m_iostate |= state; - } - - private: - iostate m_iostate; -}; -#endif // ios_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/iostream.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/iostream.h deleted file mode 100644 index 91801e3..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/iostream.h +++ /dev/null @@ -1,158 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 iostream_h -#define iostream_h -/** - * \file - * \brief \ref iostream class - */ -#include "istream.h" -#include "ostream.h" -/** Skip white space - * \param[in] is the Stream - * \return The stream - */ -inline istream& ws(istream& is) { - is.skipWhite(); - return is; -} -/** insert endline - * \param[in] os The Stream - * \return The stream - */ -inline ostream& endl(ostream& os) { - os.put('\n'); -#if ENDL_CALLS_FLUSH - os.flush(); -#endif // ENDL_CALLS_FLUSH - return os; -} -/** flush manipulator - * \param[in] os The stream - * \return The stream - */ -inline ostream& flush(ostream& os) { - os.flush(); - return os; -} -/** - * \struct setfill - * \brief type for setfill manipulator - */ -struct setfill { - /** fill character */ - char c; - /** constructor - * - * \param[in] arg new fill character - */ - explicit setfill(char arg) : c(arg) {} -}; -/** setfill manipulator - * \param[in] os the stream - * \param[in] arg set setfill object - * \return the stream - */ -inline ostream &operator<< (ostream &os, const setfill &arg) { - os.fill(arg.c); - return os; -} -/** setfill manipulator - * \param[in] obj the stream - * \param[in] arg set setfill object - * \return the stream - */ -inline istream &operator>>(istream &obj, const setfill &arg) { - obj.fill(arg.c); - return obj; -} -//------------------------------------------------------------------------------ -/** \struct setprecision - * \brief type for setprecision manipulator - */ -struct setprecision { - /** precision */ - unsigned int p; - /** constructor - * \param[in] arg new precision - */ - explicit setprecision(unsigned int arg) : p(arg) {} -}; -/** setprecision manipulator - * \param[in] os the stream - * \param[in] arg set setprecision object - * \return the stream - */ -inline ostream &operator<< (ostream &os, const setprecision &arg) { - os.precision(arg.p); - return os; -} -/** setprecision manipulator - * \param[in] is the stream - * \param[in] arg set setprecision object - * \return the stream - */ -inline istream &operator>>(istream &is, const setprecision &arg) { - is.precision(arg.p); - return is; -} -//------------------------------------------------------------------------------ -/** \struct setw - * \brief type for setw manipulator - */ -struct setw { - /** width */ - unsigned w; - /** constructor - * \param[in] arg new width - */ - explicit setw(unsigned arg) : w(arg) {} -}; -/** setw manipulator - * \param[in] os the stream - * \param[in] arg set setw object - * \return the stream - */ -inline ostream &operator<< (ostream &os, const setw &arg) { - os.width(arg.w); - return os; -} -/** setw manipulator - * \param[in] is the stream - * \param[in] arg set setw object - * \return the stream - */ -inline istream &operator>>(istream &is, const setw &arg) { - is.width(arg.w); - return is; -} -//============================================================================== -/** - * \class iostream - * \brief Input/Output stream - */ -class iostream : public istream, public ostream { -}; -#endif // iostream_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/istream.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/istream.cpp deleted file mode 100644 index 86c56f4..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/istream.cpp +++ /dev/null @@ -1,396 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -// #include -#include -#include -#include "istream.h" -//------------------------------------------------------------------------------ -int istream::get() { - int c; - m_gcount = 0; - c = getch(); - if (c < 0) { - setstate(failbit); - } else { - m_gcount = 1; - } - return c; -} -//------------------------------------------------------------------------------ -istream& istream::get(char& c) { - int tmp = get(); - if (tmp >= 0) { - c = tmp; - } - return *this; -} -//------------------------------------------------------------------------------ -istream& istream::get(char *str, streamsize n, char delim) { - int c; - FatPos_t pos; - m_gcount = 0; - while ((m_gcount + 1) < n) { - c = getch(&pos); - if (c < 0) { - break; - } - if (c == delim) { - setpos(&pos); - break; - } - str[m_gcount++] = c; - } - if (n > 0) { - str[m_gcount] = '\0'; - } - if (m_gcount == 0) { - setstate(failbit); - } - return *this; -} -//------------------------------------------------------------------------------ -void istream::getBool(bool *b) { - if ((flags() & boolalpha) == 0) { - getNumber(b); - return; - } -#ifdef __AVR__ - PGM_P truePtr = PSTR("true"); - PGM_P falsePtr = PSTR("false"); -#else // __AVR__ - const char* truePtr = "true"; - const char* falsePtr = "false"; -#endif // __AVR - const uint8_t true_len = 4; - const uint8_t false_len = 5; - bool trueOk = true; - bool falseOk = true; - uint8_t i = 0; - int c = readSkip(); - while (1) { -#ifdef __AVR__ - falseOk = falseOk && c == pgm_read_byte(falsePtr + i); - trueOk = trueOk && c == pgm_read_byte(truePtr + i); -#else // __AVR__ - falseOk = falseOk && c == falsePtr[i]; - trueOk = trueOk && c == truePtr[i]; -#endif // __AVR__ - if (trueOk == false && falseOk == false) { - break; - } - i++; - if (trueOk && i == true_len) { - *b = true; - return; - } - if (falseOk && i == false_len) { - *b = false; - return; - } - c = getch(); - } - setstate(failbit); -} -//------------------------------------------------------------------------------ -void istream::getChar(char* ch) { - int16_t c = readSkip(); - if (c < 0) { - setstate(failbit); - } else { - *ch = c; - } -} -//------------------------------------------------------------------------------ -// -// http://www.exploringbinary.com/category/numbers-in-computers/ -// -int16_t const EXP_LIMIT = 100; -static const uint32_t uint32_max = (uint32_t)-1; -bool istream::getDouble(double* value) { - bool got_digit = false; - bool got_dot = false; - bool neg; - int16_t c; - bool expNeg = false; - int16_t exp = 0; - int16_t fracExp = 0; - uint32_t frac = 0; - FatPos_t endPos; - double pow10; - double v; - - getpos(&endPos); - c = readSkip(); - neg = c == '-'; - if (c == '-' || c == '+') { - c = getch(); - } - while (1) { - if (isdigit(c)) { - got_digit = true; - if (frac < uint32_max/10) { - frac = frac * 10 + (c - '0'); - if (got_dot) { - fracExp--; - } - } else { - if (!got_dot) { - fracExp++; - } - } - } else if (!got_dot && c == '.') { - got_dot = true; - } else { - break; - } - if (fracExp < -EXP_LIMIT || fracExp > EXP_LIMIT) { - goto fail; - } - c = getch(&endPos); - } - if (!got_digit) { - goto fail; - } - if (c == 'e' || c == 'E') { - c = getch(); - expNeg = c == '-'; - if (c == '-' || c == '+') { - c = getch(); - } - while (isdigit(c)) { - if (exp > EXP_LIMIT) { - goto fail; - } - exp = exp * 10 + (c - '0'); - c = getch(&endPos); - } - } - v = static_cast(frac); - exp = expNeg ? fracExp - exp : fracExp + exp; - expNeg = exp < 0; - if (expNeg) { - exp = -exp; - } - pow10 = 10.0; - while (exp) { - if (exp & 1) { - if (expNeg) { - // check for underflow - if (v < FLT_MIN * pow10 && frac != 0) { - goto fail; - } - v /= pow10; - } else { - // check for overflow - if (v > FLT_MAX / pow10) { - goto fail; - } - v *= pow10; - } - } - pow10 *= pow10; - exp >>= 1; - } - setpos(&endPos); - *value = neg ? -v : v; - return true; - -fail: - // error restore position to last good place - setpos(&endPos); - setstate(failbit); - return false; -} -//------------------------------------------------------------------------------ - -istream& istream::getline(char *str, streamsize n, char delim) { - FatPos_t pos; - int c; - m_gcount = 0; - if (n > 0) { - str[0] = '\0'; - } - while (1) { - c = getch(&pos); - if (c < 0) { - break; - } - if (c == delim) { - m_gcount++; - break; - } - if ((m_gcount + 1) >= n) { - setpos(&pos); - setstate(failbit); - break; - } - str[m_gcount++] = c; - str[m_gcount] = '\0'; - } - if (m_gcount == 0) { - setstate(failbit); - } - return *this; -} -//------------------------------------------------------------------------------ -bool istream::getNumber(uint32_t posMax, uint32_t negMax, uint32_t* num) { - int16_t c; - int8_t any = 0; - int8_t have_zero = 0; - uint8_t neg; - uint32_t val = 0; - uint32_t cutoff; - uint8_t cutlim; - FatPos_t endPos; - uint8_t f = flags() & basefield; - uint8_t base = f == oct ? 8 : f != hex ? 10 : 16; - getpos(&endPos); - c = readSkip(); - - neg = c == '-' ? 1 : 0; - if (c == '-' || c == '+') { - c = getch(); - } - - if (base == 16 && c == '0') { // TESTSUITE - c = getch(&endPos); - if (c == 'X' || c == 'x') { - c = getch(); - // remember zero in case no hex digits follow x/X - have_zero = 1; - } else { - any = 1; - } - } - // set values for overflow test - cutoff = neg ? negMax : posMax; - cutlim = cutoff % base; - cutoff /= base; - - while (1) { - if (isdigit(c)) { - c -= '0'; - } else if (isalpha(c)) { - c -= isupper(c) ? 'A' - 10 : 'a' - 10; - } else { - break; - } - if (c >= base) { - break; - } - if (val > cutoff || (val == cutoff && c > cutlim)) { - // indicate overflow error - any = -1; - break; - } - val = val * base + c; - c = getch(&endPos); - any = 1; - } - setpos(&endPos); - if (any > 0 || (have_zero && any >= 0)) { - *num = neg ? -val : val; - return true; - } - setstate(failbit); - return false; -} -//------------------------------------------------------------------------------ -void istream::getStr(char *str) { - FatPos_t pos; - uint16_t i = 0; - uint16_t m = width() ? width() - 1 : 0XFFFE; - if (m != 0) { - getpos(&pos); - int c = readSkip(); - - while (i < m) { - if (c < 0) { - break; - } - if (isspace(c)) { - setpos(&pos); - break; - } - str[i++] = c; - c = getch(&pos); - } - } - str[i] = '\0'; - if (i == 0) { - setstate(failbit); - } - width(0); -} -//------------------------------------------------------------------------------ -istream& istream::ignore(streamsize n, int delim) { - int c; - m_gcount = 0; - while (m_gcount < n) { - c = getch(); - if (c < 0) { - break; - } - m_gcount++; - if (c == delim) { - break; - } - } - return *this; -} -//------------------------------------------------------------------------------ -int istream::peek() { - int16_t c; - FatPos_t pos; - m_gcount = 0; - getpos(&pos); - c = getch(); - if (c < 0) { - if (!bad()) { - setstate(eofbit); - } - } else { - setpos(&pos); - } - return c; -} -//------------------------------------------------------------------------------ -int16_t istream::readSkip() { - int16_t c; - do { - c = getch(); - } while (isspace(c) && (flags() & skipws)); - return c; -} -//------------------------------------------------------------------------------ -/** used to implement ws() */ -void istream::skipWhite() { - int c; - FatPos_t pos; - do { - c = getch(&pos); - } while (isspace(c)); - setpos(&pos); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/istream.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/istream.h deleted file mode 100644 index 40d15f2..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/istream.h +++ /dev/null @@ -1,384 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 istream_h -#define istream_h -/** - * \file - * \brief \ref istream class - */ -#include "ios.h" - -/** - * \class istream - * \brief Input Stream - */ -class istream : public virtual ios { - public: - istream() {} - /** call manipulator - * \param[in] pf function to call - * \return the stream - */ - istream& operator>>(istream& (*pf)(istream& str)) { - return pf(*this); - } - /** call manipulator - * \param[in] pf function to call - * \return the stream - */ - istream& operator>>(ios_base& (*pf)(ios_base& str)) { - pf(*this); - return *this; - } - /** call manipulator - * \param[in] pf function to call - * \return the stream - */ - istream& operator>>(ios& (*pf)(ios& str)) { - pf(*this); - return *this; - } - /** - * Extract a character string - * \param[out] str location to store the string. - * \return Is always *this. Failure is indicated by the state of *this. - */ - istream& operator>>(char *str) { - getStr(str); - return *this; - } - /** - * Extract a character - * \param[out] ch location to store the character. - * \return Is always *this. Failure is indicated by the state of *this. - */ - istream& operator>>(char& ch) { - getChar(&ch); - return *this; - } - /** - * Extract a character string - * \param[out] str location to store the string. - * \return Is always *this. Failure is indicated by the state of *this. - */ - istream& operator>>(signed char *str) { - getStr(reinterpret_cast(str)); - return *this; - } - /** - * Extract a character - * \param[out] ch location to store the character. - * \return Is always *this. Failure is indicated by the state of *this. - */ - istream& operator>>(signed char& ch) { - getChar(reinterpret_cast(&ch)); - return *this; - } - /** - * Extract a character string - * \param[out] str location to store the string. - * \return Is always *this. Failure is indicated by the state of *this. - */ - istream& operator>>(unsigned char *str) { - getStr(reinterpret_cast(str)); - return *this; - } - /** - * Extract a character - * \param[out] ch location to store the character. - * \return Is always *this. Failure is indicated by the state of *this. - */ - istream& operator>>(unsigned char& ch) { - getChar(reinterpret_cast(&ch)); - return *this; - } - /** - * Extract a value of type bool. - * \param[out] arg location to store the value. - * \return Is always *this. Failure is indicated by the state of *this. - */ - istream& operator>>(bool& arg) { - getBool(&arg); - return *this; - } - /** - * Extract a value of type short. - * \param[out] arg location to store the value. - * \return Is always *this. Failure is indicated by the state of *this. - */ - istream &operator>>(short& arg) { // NOLINT - getNumber(&arg); - return *this; - } - /** - * Extract a value of type unsigned short. - * \param[out] arg location to store the value. - * \return Is always *this. Failure is indicated by the state of *this. - */ - istream &operator>>(unsigned short& arg) { // NOLINT - getNumber(&arg); - return *this; - } - /** - * Extract a value of type int. - * \param[out] arg location to store the value. - * \return Is always *this. Failure is indicated by the state of *this. - */ - istream &operator>>(int& arg) { - getNumber(&arg); - return *this; - } - /** - * Extract a value of type unsigned int. - * \param[out] arg location to store the value. - * \return Is always *this. Failure is indicated by the state of *this. - */ - istream &operator>>(unsigned int& arg) { - getNumber(&arg); - return *this; - } - /** - * Extract a value of type long. - * \param[out] arg location to store the value. - * \return Is always *this. Failure is indicated by the state of *this. - */ - istream &operator>>(long& arg) { // NOLINT - getNumber(&arg); - return *this; - } - /** - * Extract a value of type unsigned long. - * \param[out] arg location to store the value. - * \return Is always *this. Failure is indicated by the state of *this. - */ - istream &operator>>(unsigned long& arg) { // NOLINT - getNumber(&arg); - return *this; - } - /** - * Extract a value of type double. - * \param[out] arg location to store the value. - * \return Is always *this. Failure is indicated by the state of *this. - */ - istream &operator>> (double& arg) { - getDouble(&arg); - return *this; - } - /** - * Extract a value of type float. - * \param[out] arg location to store the value. - * \return Is always *this. Failure is indicated by the state of *this. - */ - istream &operator>> (float& arg) { - double v; - getDouble(&v); - arg = v; - return *this; - } - /** - * Extract a value of type void*. - * \param[out] arg location to store the value. - * \return Is always *this. Failure is indicated by the state of *this. - */ - istream& operator>> (void*& arg) { - uint32_t val; - getNumber(&val); - arg = reinterpret_cast(val); - return *this; - } - /** - * \return The number of characters extracted by the last unformatted - * input function. - */ - streamsize gcount() const { - return m_gcount; - } - /** - * Extract a character if one is available. - * - * \return The character or -1 if a failure occurs. A failure is indicated - * by the stream state. - */ - int get(); - /** - * Extract a character if one is available. - * - * \param[out] ch location to receive the extracted character. - * - * \return always returns *this. A failure is indicated by the stream state. - */ - istream& get(char& ch); - /** - * Extract characters. - * - * \param[out] str Location to receive extracted characters. - * \param[in] n Size of str. - * \param[in] delim Delimiter - * - * Characters are extracted until extraction fails, n is less than 1, - * n-1 characters are extracted, or the next character equals - * \a delim (delim is not extracted). If no characters are extracted - * failbit is set. If end-of-file occurs the eofbit is set. - * - * \return always returns *this. A failure is indicated by the stream state. - */ - istream& get(char *str, streamsize n, char delim = '\n'); - /** - * Extract characters - * - * \param[out] str Location to receive extracted characters. - * \param[in] n Size of str. - * \param[in] delim Delimiter - * - * Characters are extracted until extraction fails, - * the next character equals \a delim (delim is extracted), or n-1 - * characters are extracted. - * - * The failbit is set if no characters are extracted or n-1 characters - * are extracted. If end-of-file occurs the eofbit is set. - * - * \return always returns *this. A failure is indicated by the stream state. - */ - istream& getline(char *str, streamsize n, char delim = '\n'); - /** - * Extract characters and discard them. - * - * \param[in] n maximum number of characters to ignore. - * \param[in] delim Delimiter. - * - * Characters are extracted until extraction fails, \a n characters - * are extracted, or the next input character equals \a delim - * (the delimiter is extracted). If end-of-file occurs the eofbit is set. - * - * Failures are indicated by the state of the stream. - * - * \return *this - * - */ - istream& ignore(streamsize n = 1, int delim = -1); - /** - * Return the next available character without consuming it. - * - * \return The character if the stream state is good else -1; - * - */ - int peek(); -// istream& read(char *str, streamsize count); -// streamsize readsome(char *str, streamsize count); - /** - * \return the stream position - */ - pos_type tellg() { - return tellpos(); - } - /** - * Set the stream position - * \param[in] pos The absolute position in which to move the read pointer. - * \return Is always *this. Failure is indicated by the state of *this. - */ - istream& seekg(pos_type pos) { - if (!seekpos(pos)) { - setstate(failbit); - } - return *this; - } - /** - * Set the stream position. - * - * \param[in] off An offset to move the read pointer relative to way. - * \a off is a signed 32-bit int so the offset is limited to +- 2GB. - * \param[in] way One of ios::beg, ios::cur, or ios::end. - * \return Is always *this. Failure is indicated by the state of *this. - */ - istream& seekg(off_type off, seekdir way) { - if (!seekoff(off, way)) { - setstate(failbit); - } - return *this; - } - void skipWhite(); - - protected: - /// @cond SHOW_PROTECTED - /** - * Internal - do not use - * \return - */ - virtual int16_t getch() = 0; - /** - * Internal - do not use - * \param[out] pos - * \return - */ - int16_t getch(FatPos_t* pos) { - getpos(pos); - return getch(); - } - /** - * Internal - do not use - * \param[out] pos - */ - virtual void getpos(FatPos_t* pos) = 0; - /** - * Internal - do not use - * \param[in] pos - */ - virtual bool seekoff(off_type off, seekdir way) = 0; - virtual bool seekpos(pos_type pos) = 0; - virtual void setpos(FatPos_t* pos) = 0; - virtual pos_type tellpos() = 0; - - /// @endcond - private: - void getBool(bool *b); - void getChar(char* ch); - bool getDouble(double* value); - template void getNumber(T* value); - bool getNumber(uint32_t posMax, uint32_t negMax, uint32_t* num); - void getStr(char *str); - int16_t readSkip(); - - size_t m_gcount; -}; -//------------------------------------------------------------------------------ -template -void istream::getNumber(T* value) { - uint32_t tmp; - if ((T)-1 < 0) { - // number is signed, max positive value - uint32_t const m = ((uint32_t)-1) >> (33 - sizeof(T) * 8); - // max absolute value of negative number is m + 1. - if (getNumber(m, m + 1, &tmp)) { - *value = (T)tmp; - } - } else { - // max unsigned value for T - uint32_t const m = (T)-1; - if (getNumber(m, m, &tmp)) { - *value = (T)tmp; - } - } -} -#endif // istream_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ostream.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ostream.cpp deleted file mode 100644 index 61486bb..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ostream.cpp +++ /dev/null @@ -1,196 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#include -#include "ostream.h" -#ifndef PSTR -#define PSTR(x) x -#endif -//------------------------------------------------------------------------------ -void ostream::do_fill(unsigned len) { - for (; len < width(); len++) { - putch(fill()); - } - width(0); -} -//------------------------------------------------------------------------------ -void ostream::fill_not_left(unsigned len) { - if ((flags() & adjustfield) != left) { - do_fill(len); - } -} -//------------------------------------------------------------------------------ -char* ostream::fmtNum(uint32_t n, char *ptr, uint8_t base) { - char a = flags() & uppercase ? 'A' - 10 : 'a' - 10; - do { - uint32_t m = n; - n /= base; - char c = m - base * n; - *--ptr = c < 10 ? c + '0' : c + a; - } while (n); - return ptr; -} -//------------------------------------------------------------------------------ -void ostream::putBool(bool b) { - if (flags() & boolalpha) { - if (b) { - putPgm(PSTR("true")); - } else { - putPgm(PSTR("false")); - } - } else { - putChar(b ? '1' : '0'); - } -} -//------------------------------------------------------------------------------ -void ostream::putChar(char c) { - fill_not_left(1); - putch(c); - do_fill(1); -} -//------------------------------------------------------------------------------ -void ostream::putDouble(double n) { - uint8_t nd = precision(); - double round = 0.5; - char sign; - char buf[13]; // room for sign, 10 digits, '.', and zero byte - char *end = buf + sizeof(buf) - 1; - char *str = end; - // terminate string - *end = '\0'; - - // get sign and make nonnegative - if (n < 0.0) { - sign = '-'; - n = -n; - } else { - sign = flags() & showpos ? '+' : '\0'; - } - // check for larger than uint32_t - if (n > 4.0E9) { - putPgm(PSTR("BIG FLT")); - return; - } - // round up and separate int and fraction parts - for (uint8_t i = 0; i < nd; ++i) { - round *= 0.1; - } - n += round; - uint32_t intPart = n; - double fractionPart = n - intPart; - - // format intPart and decimal point - if (nd || (flags() & showpoint)) { - *--str = '.'; - } - str = fmtNum(intPart, str, 10); - - // calculate length for fill - uint8_t len = sign ? 1 : 0; - len += nd + end - str; - - // extract adjust field - fmtflags adj = flags() & adjustfield; - if (adj == internal) { - if (sign) { - putch(sign); - } - do_fill(len); - } else { - // do fill for internal or right - fill_not_left(len); - if (sign) { - *--str = sign; - } - } - putstr(str); - // output fraction - while (nd-- > 0) { - fractionPart *= 10.0; - int digit = static_cast(fractionPart); - putch(digit + '0'); - fractionPart -= digit; - } - // do fill if not done above - do_fill(len); -} -//------------------------------------------------------------------------------ -void ostream::putNum(int32_t n) { - bool neg = n < 0 && flagsToBase() == 10; - if (neg) { - n = -n; - } - putNum(n, neg); -} -//------------------------------------------------------------------------------ -void ostream::putNum(uint32_t n, bool neg) { - char buf[13]; - char* end = buf + sizeof(buf) - 1; - char* num; - char* str; - uint8_t base = flagsToBase(); - *end = '\0'; - str = num = fmtNum(n, end, base); - if (base == 10) { - if (neg) { - *--str = '-'; - } else if (flags() & showpos) { - *--str = '+'; - } - } else if (flags() & showbase) { - if (flags() & hex) { - *--str = flags() & uppercase ? 'X' : 'x'; - } - *--str = '0'; - } - uint8_t len = end - str; - fmtflags adj = flags() & adjustfield; - if (adj == internal) { - while (str < num) { - putch(*str++); - } - } - if (adj != left) { - do_fill(len); - } - putstr(str); - do_fill(len); -} -//------------------------------------------------------------------------------ -void ostream::putPgm(const char* str) { - int n; - for (n = 0; pgm_read_byte(&str[n]); n++) {} - fill_not_left(n); - for (uint8_t c; (c = pgm_read_byte(str)); str++) { - putch(c); - } - do_fill(n); -} -//------------------------------------------------------------------------------ -void ostream::putStr(const char *str) { - unsigned n = strlen(str); - fill_not_left(n); - putstr(str); - do_fill(n); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ostream.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ostream.h deleted file mode 100644 index 57609e2..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FatLib/ostream.h +++ /dev/null @@ -1,276 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 ostream_h -#define ostream_h -/** - * \file - * \brief \ref ostream class - */ -#include "ios.h" -//============================================================================== -/** - * \class ostream - * \brief Output Stream - */ -class ostream : public virtual ios { - public: - ostream() {} - - /** call manipulator - * \param[in] pf function to call - * \return the stream - */ - ostream& operator<< (ostream& (*pf)(ostream& str)) { - return pf(*this); - } - /** call manipulator - * \param[in] pf function to call - * \return the stream - */ - ostream& operator<< (ios_base& (*pf)(ios_base& str)) { - pf(*this); - return *this; - } - /** Output bool - * \param[in] arg value to output - * \return the stream - */ - ostream &operator<< (bool arg) { - putBool(arg); - return *this; - } - /** Output string - * \param[in] arg string to output - * \return the stream - */ - ostream &operator<< (const char *arg) { - putStr(arg); - return *this; - } - /** Output string - * \param[in] arg string to output - * \return the stream - */ - ostream &operator<< (const signed char *arg) { - putStr((const char*)arg); - return *this; - } - /** Output string - * \param[in] arg string to output - * \return the stream - */ - ostream &operator<< (const unsigned char *arg) { - putStr((const char*)arg); - return *this; - } - /** Output character - * \param[in] arg character to output - * \return the stream - */ - ostream &operator<< (char arg) { - putChar(arg); - return *this; - } - /** Output character - * \param[in] arg character to output - * \return the stream - */ - ostream &operator<< (signed char arg) { - putChar(static_cast(arg)); - return *this; - } - /** Output character - * \param[in] arg character to output - * \return the stream - */ - ostream &operator<< (unsigned char arg) { - putChar(static_cast(arg)); - return *this; - } - /** Output double - * \param[in] arg value to output - * \return the stream - */ - ostream &operator<< (double arg) { - putDouble(arg); - return *this; - } - /** Output float - * \param[in] arg value to output - * \return the stream - */ - ostream &operator<< (float arg) { - putDouble(arg); - return *this; - } - /** Output signed short - * \param[in] arg value to output - * \return the stream - */ - ostream &operator<< (short arg) { // NOLINT - putNum((int32_t)arg); - return *this; - } - /** Output unsigned short - * \param[in] arg value to output - * \return the stream - */ - ostream &operator<< (unsigned short arg) { // NOLINT - putNum((uint32_t)arg); - return *this; - } - /** Output signed int - * \param[in] arg value to output - * \return the stream - */ - ostream &operator<< (int arg) { - putNum((int32_t)arg); - return *this; - } - /** Output unsigned int - * \param[in] arg value to output - * \return the stream - */ - ostream &operator<< (unsigned int arg) { - putNum((uint32_t)arg); - return *this; - } - /** Output signed long - * \param[in] arg value to output - * \return the stream - */ - ostream &operator<< (long arg) { // NOLINT - putNum((int32_t)arg); - return *this; - } - /** Output unsigned long - * \param[in] arg value to output - * \return the stream - */ - ostream &operator<< (unsigned long arg) { // NOLINT - putNum((uint32_t)arg); - return *this; - } - /** Output pointer - * \param[in] arg value to output - * \return the stream - */ - ostream& operator<< (const void* arg) { - putNum(reinterpret_cast(arg)); - return *this; - } -#if (defined(ARDUINO) && ENABLE_ARDUINO_FEATURES) || defined(DOXYGEN) - /** Output a string from flash using the Arduino F() macro. - * \param[in] arg pointing to flash string - * \return the stream - */ - ostream &operator<< (const __FlashStringHelper *arg) { - putPgm(reinterpret_cast(arg)); - return *this; - } -#endif // (defined(ARDUINO) && ENABLE_ARDUINO_FEATURES) || defined(DOXYGEN) - /** - * Puts a character in a stream. - * - * The unformatted output function inserts the element \a ch. - * It returns *this. - * - * \param[in] ch The character - * \return A reference to the ostream object. - */ - ostream& put(char ch) { - putch(ch); - return *this; - } -// ostream& write(char *str, streamsize count); - /** - * Flushes the buffer associated with this stream. The flush function - * calls the sync function of the associated file. - * \return A reference to the ostream object. - */ - ostream& flush() { - if (!sync()) { - setstate(badbit); - } - return *this; - } - /** - * \return the stream position - */ - pos_type tellp() { - return tellpos(); - } - /** - * Set the stream position - * \param[in] pos The absolute position in which to move the write pointer. - * \return Is always *this. Failure is indicated by the state of *this. - */ - ostream& seekp(pos_type pos) { - if (!seekpos(pos)) { - setstate(failbit); - } - return *this; - } - /** - * Set the stream position. - * - * \param[in] off An offset to move the write pointer relative to way. - * \a off is a signed 32-bit int so the offset is limited to +- 2GB. - * \param[in] way One of ios::beg, ios::cur, or ios::end. - * \return Is always *this. Failure is indicated by the state of *this. - */ - ostream& seekp(off_type off, seekdir way) { - if (!seekoff(off, way)) { - setstate(failbit); - } - return *this; - } - - protected: - /// @cond SHOW_PROTECTED - /** Put character with binary/text conversion - * \param[in] ch character to write - */ - virtual void putch(char ch) = 0; - virtual void putstr(const char *str) = 0; - virtual bool seekoff(off_type pos, seekdir way) = 0; - virtual bool seekpos(pos_type pos) = 0; - virtual bool sync() = 0; - - virtual pos_type tellpos() = 0; - /// @endcond - private: - void do_fill(unsigned len); - void fill_not_left(unsigned len); - char* fmtNum(uint32_t n, char *ptr, uint8_t base); - void putBool(bool b); - void putChar(char c); - void putDouble(double n); - void putNum(uint32_t n, bool neg = false); - void putNum(int32_t n); - void putPgm(const char* str); - void putStr(const char* str); -}; -#endif // ostream_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FreeStack.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FreeStack.h deleted file mode 100644 index 709fc46..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/FreeStack.h +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 FreeStack_h -#define FreeStack_h -/** - * \file - * \brief FreeStack() function. - */ -#if defined(__AVR__) || defined(DOXYGEN) -/** boundary between stack and heap. */ -extern char *__brkval; -/** End of bss section.*/ -extern char __bss_end; -/** Amount of free stack space. - * \return The number of free bytes. - */ -static int FreeStack() { - char* sp = reinterpret_cast(SP); - return __brkval ? sp - __brkval : sp - &__bss_end; -// char top; -// return __brkval ? &top - __brkval : &top - &__bss_end; -} -#elif defined(PLATFORM_ID) // Particle board -static int FreeStack() { - return System.freeMemory(); -} -#elif defined(__arm__) -extern "C" char* sbrk(int incr); -static int FreeStack() { - char top = 't'; - return &top - reinterpret_cast(sbrk(0)); -} -#else -#warning FreeStack is not defined for this system. -static int FreeStack() { - return 0; -} -#endif -#endif // FreeStack_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/MinimumSerial.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/MinimumSerial.cpp deleted file mode 100644 index d7161e8..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/MinimumSerial.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#include "SysCall.h" -#if defined(UDR0) || defined(DOXYGEN) -#include "MinimumSerial.h" -const uint16_t MIN_2X_BAUD = F_CPU/(4*(2*0XFFF + 1)) + 1; -//------------------------------------------------------------------------------ -int MinimumSerial::available() { - return UCSR0A & (1 << RXC0) ? 1 : 0; -} -//------------------------------------------------------------------------------ -void MinimumSerial::begin(uint32_t baud) { - uint16_t baud_setting; - // don't worry, the compiler will squeeze out F_CPU != 16000000UL - if ((F_CPU != 16000000UL || baud != 57600) && baud > MIN_2X_BAUD) { - // Double the USART Transmission Speed - UCSR0A = 1 << U2X0; - baud_setting = (F_CPU / 4 / baud - 1) / 2; - } else { - // hardcoded exception for compatibility with the bootloader shipped - // with the Duemilanove and previous boards and the firmware on the 8U2 - // on the Uno and Mega 2560. - UCSR0A = 0; - baud_setting = (F_CPU / 8 / baud - 1) / 2; - } - // assign the baud_setting - UBRR0H = baud_setting >> 8; - UBRR0L = baud_setting; - // enable transmit and receive - UCSR0B |= (1 << TXEN0) | (1 << RXEN0); -} -//------------------------------------------------------------------------------ -void MinimumSerial::flush() { - while (((1 << UDRIE0) & UCSR0B) || !(UCSR0A & (1 << UDRE0))) {} -} -//------------------------------------------------------------------------------ -int MinimumSerial::read() { - if (UCSR0A & (1 << RXC0)) { - return UDR0; - } - return -1; -} -//------------------------------------------------------------------------------ -size_t MinimumSerial::write(uint8_t b) { - while (((1 << UDRIE0) & UCSR0B) || !(UCSR0A & (1 << UDRE0))) {} - UDR0 = b; - return 1; -} -#endif // defined(UDR0) || defined(DOXYGEN) diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/MinimumSerial.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/MinimumSerial.h deleted file mode 100644 index 6fba5b8..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/MinimumSerial.h +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ - /** - * \file - * \brief Minimal AVR Serial driver. - */ -#ifndef MinimumSerial_h -#define MinimumSerial_h -#include "SysCall.h" -//============================================================================== -/** - * \class MinimumSerial - * \brief mini serial class for the %SdFat library. - */ -class MinimumSerial : public Print { - public: - /** \return true for hardware serial */ - operator bool() { return true; } - /** - * \return one if data is available. - */ - int available(); - /** - * Set baud rate for serial port zero and enable in non interrupt mode. - * Do not call this function if you use another serial library. - * \param[in] baud rate - */ - void begin(uint32_t baud); - /** Wait for write done. */ - void flush(); - /** - * Unbuffered read - * \return -1 if no character is available or an available character. - */ - int read(); - /** - * Unbuffered write - * - * \param[in] b byte to write. - * \return 1 - */ - size_t write(uint8_t b); - using Print::write; -}; -#endif // MinimumSerial_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdInfo.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdInfo.h deleted file mode 100644 index f8943b4..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdInfo.h +++ /dev/null @@ -1,485 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 SdInfo_h -#define SdInfo_h -#include -// Based on the document: -// -// SD Specifications -// Part 1 -// Physical Layer -// Simplified Specification -// Version 5.00 -// Aug 10, 2016 -// -// https://www.sdcard.org/downloads/pls/ -//------------------------------------------------------------------------------ -// SD card errors -// See the SD Specification for command info. -typedef enum { - SD_CARD_ERROR_NONE = 0, - - // Basic commands and switch command. - SD_CARD_ERROR_CMD0 = 0X20, - SD_CARD_ERROR_CMD2, - SD_CARD_ERROR_CMD3, - SD_CARD_ERROR_CMD6, - SD_CARD_ERROR_CMD7, - SD_CARD_ERROR_CMD8, - SD_CARD_ERROR_CMD9, - SD_CARD_ERROR_CMD10, - SD_CARD_ERROR_CMD12, - SD_CARD_ERROR_CMD13, - - // Read, write, erase, and extension commands. - SD_CARD_ERROR_CMD17 = 0X30, - SD_CARD_ERROR_CMD18, - SD_CARD_ERROR_CMD24, - SD_CARD_ERROR_CMD25, - SD_CARD_ERROR_CMD32, - SD_CARD_ERROR_CMD33, - SD_CARD_ERROR_CMD38, - SD_CARD_ERROR_CMD58, - SD_CARD_ERROR_CMD59, - - // Application specific commands. - SD_CARD_ERROR_ACMD6 = 0X40, - SD_CARD_ERROR_ACMD13, - SD_CARD_ERROR_ACMD23, - SD_CARD_ERROR_ACMD41, - - // Read/write errors - SD_CARD_ERROR_READ = 0X50, - SD_CARD_ERROR_READ_CRC, - SD_CARD_ERROR_READ_FIFO, - SD_CARD_ERROR_READ_REG, - SD_CARD_ERROR_READ_START, - SD_CARD_ERROR_READ_TIMEOUT, - SD_CARD_ERROR_STOP_TRAN, - SD_CARD_ERROR_WRITE, - SD_CARD_ERROR_WRITE_FIFO, - SD_CARD_ERROR_WRITE_START, - SD_CARD_ERROR_FLASH_PROGRAMMING, - SD_CARD_ERROR_WRITE_TIMEOUT, - - // Misc errors. - SD_CARD_ERROR_DMA = 0X60, - SD_CARD_ERROR_ERASE, - SD_CARD_ERROR_ERASE_SINGLE_BLOCK, - SD_CARD_ERROR_ERASE_TIMEOUT, - SD_CARD_ERROR_INIT_NOT_CALLED, - SD_CARD_ERROR_FUNCTION_NOT_SUPPORTED -} sd_error_code_t; -//------------------------------------------------------------------------------ -// card types -/** Standard capacity V1 SD card */ -const uint8_t SD_CARD_TYPE_SD1 = 1; -/** Standard capacity V2 SD card */ -const uint8_t SD_CARD_TYPE_SD2 = 2; -/** High Capacity SD card */ -const uint8_t SD_CARD_TYPE_SDHC = 3; -//------------------------------------------------------------------------------ -#define SD_SCK_HZ(maxSpeed) SPISettings(maxSpeed, MSBFIRST, SPI_MODE0) -#define SD_SCK_MHZ(maxMhz) SPISettings(1000000UL*maxMhz, MSBFIRST, SPI_MODE0) -// SPI divisor constants -/** Set SCK to max rate of F_CPU/2. */ -#define SPI_FULL_SPEED SD_SCK_MHZ(50) -/** Set SCK rate to F_CPU/3 for Due */ -#define SPI_DIV3_SPEED SD_SCK_HZ(F_CPU/3) -/** Set SCK rate to F_CPU/4. */ -#define SPI_HALF_SPEED SD_SCK_HZ(F_CPU/4) -/** Set SCK rate to F_CPU/6 for Due */ -#define SPI_DIV6_SPEED SD_SCK_HZ(F_CPU/6) -/** Set SCK rate to F_CPU/8. */ -#define SPI_QUARTER_SPEED SD_SCK_HZ(F_CPU/8) -/** Set SCK rate to F_CPU/16. */ -#define SPI_EIGHTH_SPEED SD_SCK_HZ(F_CPU/16) -/** Set SCK rate to F_CPU/32. */ -#define SPI_SIXTEENTH_SPEED SD_SCK_HZ(F_CPU/32) -//------------------------------------------------------------------------------ -// SD operation timeouts -/** CMD0 retry count */ -const uint8_t SD_CMD0_RETRY = 10; -/** command timeout ms */ -const uint16_t SD_CMD_TIMEOUT = 300; -/** init timeout ms */ -const uint16_t SD_INIT_TIMEOUT = 2000; -/** erase timeout ms */ -const uint16_t SD_ERASE_TIMEOUT = 10000; -/** read timeout ms */ -const uint16_t SD_READ_TIMEOUT = 1000; -/** write time out ms */ -const uint16_t SD_WRITE_TIMEOUT = 2000; -//------------------------------------------------------------------------------ -// SD card commands -/** GO_IDLE_STATE - init card in spi mode if CS low */ -const uint8_t CMD0 = 0X00; -/** ALL_SEND_CID - Asks any card to send the CID. */ -const uint8_t CMD2 = 0X02; -/** SEND_RELATIVE_ADDR - Ask the card to publish a new RCA. */ -const uint8_t CMD3 = 0X03; -/** SWITCH_FUNC - Switch Function Command */ -const uint8_t CMD6 = 0X06; -/** SELECT/DESELECT_CARD - toggles between the stand-by and transfer states. */ -const uint8_t CMD7 = 0X07; -/** SEND_IF_COND - verify SD Memory Card interface operating condition.*/ -const uint8_t CMD8 = 0X08; -/** SEND_CSD - read the Card Specific Data (CSD register) */ -const uint8_t CMD9 = 0X09; -/** SEND_CID - read the card identification information (CID register) */ -const uint8_t CMD10 = 0X0A; -/** STOP_TRANSMISSION - end multiple block read sequence */ -const uint8_t CMD12 = 0X0C; -/** SEND_STATUS - read the card status register */ -const uint8_t CMD13 = 0X0D; -/** READ_SINGLE_BLOCK - read a single data block from the card */ -const uint8_t CMD17 = 0X11; -/** READ_MULTIPLE_BLOCK - read a multiple data blocks from the card */ -const uint8_t CMD18 = 0X12; -/** WRITE_BLOCK - write a single data block to the card */ -const uint8_t CMD24 = 0X18; -/** WRITE_MULTIPLE_BLOCK - write blocks of data until a STOP_TRANSMISSION */ -const uint8_t CMD25 = 0X19; -/** ERASE_WR_BLK_START - sets the address of the first block to be erased */ -const uint8_t CMD32 = 0X20; -/** ERASE_WR_BLK_END - sets the address of the last block of the continuous - range to be erased*/ -const uint8_t CMD33 = 0X21; -/** ERASE - erase all previously selected blocks */ -const uint8_t CMD38 = 0X26; -/** APP_CMD - escape for application specific command */ -const uint8_t CMD55 = 0X37; -/** READ_OCR - read the OCR register of a card */ -const uint8_t CMD58 = 0X3A; -/** CRC_ON_OFF - enable or disable CRC checking */ -const uint8_t CMD59 = 0X3B; -/** SET_BUS_WIDTH - Defines the data bus width for data transfer. */ -const uint8_t ACMD6 = 0X06; -/** SD_STATUS - Send the SD Status. */ -const uint8_t ACMD13 = 0X0D; -/** SET_WR_BLK_ERASE_COUNT - Set the number of write blocks to be - pre-erased before writing */ -const uint8_t ACMD23 = 0X17; -/** SD_SEND_OP_COMD - Sends host capacity support information and - activates the card's initialization process */ -const uint8_t ACMD41 = 0X29; -//============================================================================== -// CARD_STATUS -/** The command's argument was out of the allowed range for this card. */ -const uint32_t CARD_STATUS_OUT_OF_RANGE = 1UL << 31; -/** A misaligned address which did not match the block length. */ -const uint32_t CARD_STATUS_ADDRESS_ERROR = 1UL << 30; -/** The transferred block length is not allowed for this card. */ -const uint32_t CARD_STATUS_BLOCK_LEN_ERROR = 1UL << 29; -/** An error in the sequence of erase commands occurred. */ -const uint32_t CARD_STATUS_ERASE_SEQ_ERROR = 1UL <<28; -/** An invalid selection of write-blocks for erase occurred. */ -const uint32_t CARD_STATUS_ERASE_PARAM = 1UL << 27; -/** Set when the host attempts to write to a protected block. */ -const uint32_t CARD_STATUS_WP_VIOLATION = 1UL << 26; -/** When set, signals that the card is locked by the host. */ -const uint32_t CARD_STATUS_CARD_IS_LOCKED = 1UL << 25; -/** Set when a sequence or password error has been detected. */ -const uint32_t CARD_STATUS_LOCK_UNLOCK_FAILED = 1UL << 24; -/** The CRC check of the previous command failed. */ -const uint32_t CARD_STATUS_COM_CRC_ERROR = 1UL << 23; -/** Command not legal for the card state. */ -const uint32_t CARD_STATUS_ILLEGAL_COMMAND = 1UL << 22; -/** Card internal ECC was applied but failed to correct the data. */ -const uint32_t CARD_STATUS_CARD_ECC_FAILED = 1UL << 21; -/** Internal card controller error */ -const uint32_t CARD_STATUS_CC_ERROR = 1UL << 20; -/** A general or an unknown error occurred during the operation. */ -const uint32_t CARD_STATUS_ERROR = 1UL << 19; -// bits 19, 18, and 17 reserved. -/** Permanent WP set or attempt to change read only values of CSD. */ -const uint32_t CARD_STATUS_CSD_OVERWRITE = 1UL <<16; -/** partial address space was erased due to write protect. */ -const uint32_t CARD_STATUS_WP_ERASE_SKIP = 1UL << 15; -/** The command has been executed without using the internal ECC. */ -const uint32_t CARD_STATUS_CARD_ECC_DISABLED = 1UL << 14; -/** out of erase sequence command was received. */ -const uint32_t CARD_STATUS_ERASE_RESET = 1UL << 13; -/** The state of the card when receiving the command. - * 0 = idle - * 1 = ready - * 2 = ident - * 3 = stby - * 4 = tran - * 5 = data - * 6 = rcv - * 7 = prg - * 8 = dis - * 9-14 = reserved - * 15 = reserved for I/O mode - */ -const uint32_t CARD_STATUS_CURRENT_STATE = 0XF << 9; -/** Shift for current state. */ -const uint32_t CARD_STATUS_CURRENT_STATE_SHIFT = 9; -/** Corresponds to buffer empty signaling on the bus. */ -const uint32_t CARD_STATUS_READY_FOR_DATA = 1UL << 8; -// bit 7 reserved. -/** Extension Functions may set this bit to get host to deal with events. */ -const uint32_t CARD_STATUS_FX_EVENT = 1UL << 6; -/** The card will expect ACMD, or the command has been interpreted as ACMD */ -const uint32_t CARD_STATUS_APP_CMD = 1UL << 5; -// bit 4 reserved. -/** Error in the sequence of the authentication process. */ -const uint32_t CARD_STATUS_AKE_SEQ_ERROR = 1UL << 3; -// bits 2,1, and 0 reserved for manufacturer test mode. -//============================================================================== -/** status for card in the ready state */ -const uint8_t R1_READY_STATE = 0X00; -/** status for card in the idle state */ -const uint8_t R1_IDLE_STATE = 0X01; -/** status bit for illegal command */ -const uint8_t R1_ILLEGAL_COMMAND = 0X04; -/** start data token for read or write single block*/ -const uint8_t DATA_START_BLOCK = 0XFE; -/** stop token for write multiple blocks*/ -const uint8_t STOP_TRAN_TOKEN = 0XFD; -/** start data token for write multiple blocks*/ -const uint8_t WRITE_MULTIPLE_TOKEN = 0XFC; -/** mask for data response tokens after a write block operation */ -const uint8_t DATA_RES_MASK = 0X1F; -/** write data accepted token */ -const uint8_t DATA_RES_ACCEPTED = 0X05; -//============================================================================== -/** - * \class CID - * \brief Card IDentification (CID) register. - */ -typedef struct CID { - // byte 0 - /** Manufacturer ID */ - unsigned char mid; - // byte 1-2 - /** OEM/Application ID */ - char oid[2]; - // byte 3-7 - /** Product name */ - char pnm[5]; - // byte 8 - /** Product revision least significant digit */ - unsigned char prv_m : 4; - /** Product revision most significant digit */ - unsigned char prv_n : 4; - // byte 9-12 - /** Product serial number */ - uint32_t psn; - // byte 13 - /** Manufacturing date year low digit */ - unsigned char mdt_year_high : 4; - /** not used */ - unsigned char reserved : 4; - // byte 14 - /** Manufacturing date month */ - unsigned char mdt_month : 4; - /** Manufacturing date year low digit */ - unsigned char mdt_year_low : 4; - // byte 15 - /** not used always 1 */ - unsigned char always1 : 1; - /** CRC7 checksum */ - unsigned char crc : 7; -} __attribute__((packed)) cid_t; - -//============================================================================== -/** - * \class CSDV1 - * \brief CSD register for version 1.00 cards . - */ -typedef struct CSDV1 { - // byte 0 - unsigned char reserved1 : 6; - unsigned char csd_ver : 2; - // byte 1 - unsigned char taac; - // byte 2 - unsigned char nsac; - // byte 3 - unsigned char tran_speed; - // byte 4 - unsigned char ccc_high; - // byte 5 - unsigned char read_bl_len : 4; - unsigned char ccc_low : 4; - // byte 6 - unsigned char c_size_high : 2; - unsigned char reserved2 : 2; - unsigned char dsr_imp : 1; - unsigned char read_blk_misalign : 1; - unsigned char write_blk_misalign : 1; - unsigned char read_bl_partial : 1; - // byte 7 - unsigned char c_size_mid; - // byte 8 - unsigned char vdd_r_curr_max : 3; - unsigned char vdd_r_curr_min : 3; - unsigned char c_size_low : 2; - // byte 9 - unsigned char c_size_mult_high : 2; - unsigned char vdd_w_cur_max : 3; - unsigned char vdd_w_curr_min : 3; - // byte 10 - unsigned char sector_size_high : 6; - unsigned char erase_blk_en : 1; - unsigned char c_size_mult_low : 1; - // byte 11 - unsigned char wp_grp_size : 7; - unsigned char sector_size_low : 1; - // byte 12 - unsigned char write_bl_len_high : 2; - unsigned char r2w_factor : 3; - unsigned char reserved3 : 2; - unsigned char wp_grp_enable : 1; - // byte 13 - unsigned char reserved4 : 5; - unsigned char write_partial : 1; - unsigned char write_bl_len_low : 2; - // byte 14 - unsigned char reserved5: 2; - unsigned char file_format : 2; - unsigned char tmp_write_protect : 1; - unsigned char perm_write_protect : 1; - unsigned char copy : 1; - /** Indicates the file format on the card */ - unsigned char file_format_grp : 1; - // byte 15 - unsigned char always1 : 1; - unsigned char crc : 7; -} __attribute__((packed)) csd1_t; -//============================================================================== -/** - * \class CSDV2 - * \brief CSD register for version 2.00 cards. - */ -typedef struct CSDV2 { - // byte 0 - unsigned char reserved1 : 6; - unsigned char csd_ver : 2; - // byte 1 - /** fixed to 0X0E */ - unsigned char taac; - // byte 2 - /** fixed to 0 */ - unsigned char nsac; - // byte 3 - unsigned char tran_speed; - // byte 4 - unsigned char ccc_high; - // byte 5 - /** This field is fixed to 9h, which indicates READ_BL_LEN=512 Byte */ - unsigned char read_bl_len : 4; - unsigned char ccc_low : 4; - // byte 6 - /** not used */ - unsigned char reserved2 : 4; - unsigned char dsr_imp : 1; - /** fixed to 0 */ - unsigned char read_blk_misalign : 1; - /** fixed to 0 */ - unsigned char write_blk_misalign : 1; - /** fixed to 0 - no partial read */ - unsigned char read_bl_partial : 1; - // byte 7 - /** high part of card size */ - unsigned char c_size_high : 6; - /** not used */ - unsigned char reserved3 : 2; - // byte 8 - /** middle part of card size */ - unsigned char c_size_mid; - // byte 9 - /** low part of card size */ - unsigned char c_size_low; - // byte 10 - /** sector size is fixed at 64 KB */ - unsigned char sector_size_high : 6; - /** fixed to 1 - erase single is supported */ - unsigned char erase_blk_en : 1; - /** not used */ - unsigned char reserved4 : 1; - // byte 11 - unsigned char wp_grp_size : 7; - /** sector size is fixed at 64 KB */ - unsigned char sector_size_low : 1; - // byte 12 - /** write_bl_len fixed for 512 byte blocks */ - unsigned char write_bl_len_high : 2; - /** fixed value of 2 */ - unsigned char r2w_factor : 3; - /** not used */ - unsigned char reserved5 : 2; - /** fixed value of 0 - no write protect groups */ - unsigned char wp_grp_enable : 1; - // byte 13 - unsigned char reserved6 : 5; - /** always zero - no partial block read*/ - unsigned char write_partial : 1; - /** write_bl_len fixed for 512 byte blocks */ - unsigned char write_bl_len_low : 2; - // byte 14 - unsigned char reserved7: 2; - /** Do not use always 0 */ - unsigned char file_format : 2; - unsigned char tmp_write_protect : 1; - unsigned char perm_write_protect : 1; - unsigned char copy : 1; - /** Do not use always 0 */ - unsigned char file_format_grp : 1; - // byte 15 - /** not used always 1 */ - unsigned char always1 : 1; - /** checksum */ - unsigned char crc : 7; -} __attribute__((packed)) csd2_t; -//============================================================================== -/** - * \class csd_t - * \brief Union of old and new style CSD register. - */ -union csd_t { - csd1_t v1; - csd2_t v2; -}; -//----------------------------------------------------------------------------- -inline uint32_t sdCardCapacity(csd_t* csd) { - if (csd->v1.csd_ver == 0) { - uint8_t read_bl_len = csd->v1.read_bl_len; - uint16_t c_size = (csd->v1.c_size_high << 10) - | (csd->v1.c_size_mid << 2) | csd->v1.c_size_low; - uint8_t c_size_mult = (csd->v1.c_size_mult_high << 1) - | csd->v1.c_size_mult_low; - return (uint32_t)(c_size + 1) << (c_size_mult + read_bl_len - 7); - } else if (csd->v2.csd_ver == 1) { - uint32_t c_size = 0X10000L * csd->v2.c_size_high + 0X100L - * (uint32_t)csd->v2.c_size_mid + csd->v2.c_size_low; - return (c_size + 1) << 10; - } else { - return 0; - } -} -#endif // SdInfo_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCard.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCard.cpp deleted file mode 100644 index 4497120..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCard.cpp +++ /dev/null @@ -1,802 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#include "SdSpiCard.h" -//============================================================================== -// debug trace macro -#define SD_TRACE(m, b) -// #define SD_TRACE(m, b) Serial.print(m);Serial.println(b); -#define SD_CS_DBG(m) -// #define SD_CS_DBG(m) Serial.println(F(m)); - -#define DBG_PROFILE_STATS 0 -#if DBG_PROFILE_STATS - -#define DBG_TAG_LIST\ - DBG_TAG(DBG_CMD0_TIME, "CMD0 time")\ - DBG_TAG(DBG_ACMD41_TIME, "ACMD41 time")\ - DBG_TAG(DBG_CMD_BUSY, "cmd busy")\ - DBG_TAG(DBG_ERASE_BUSY, "erase busy")\ - DBG_TAG(DBG_WAIT_READ, "wait read")\ - DBG_TAG(DBG_WRITE_FLASH, "write flash")\ - DBG_TAG(DBG_WRITE_BUSY, "write busy")\ - DBG_TAG(DBG_WRITE_STOP, "write stop")\ - DBG_TAG(DBG_ACMD41_COUNT, "ACMD41 count")\ - DBG_TAG(DBG_CMD0_COUNT, "CMD0 count") - -#define DBG_TIME_DIM DBG_ACMD41_COUNT - -enum DbgTag { - #define DBG_TAG(tag, str) tag, - DBG_TAG_LIST - DBG_COUNT_DIM - #undef DBG_TAG -}; - -static uint32_t dbgCount[DBG_COUNT_DIM]; -static uint32_t dbgBgnTime[DBG_TIME_DIM]; -static uint32_t dbgMaxTime[DBG_TIME_DIM]; -static uint32_t dbgMinTime[DBG_TIME_DIM]; -static uint32_t dbgTotalTime[DBG_TIME_DIM]; -//------------------------------------------------------------------------------ -static void dbgBeginTime(DbgTag tag) { - dbgBgnTime[tag] = micros(); -} -//------------------------------------------------------------------------------ -static void dbgClearStats() { - for (int i = 0; i < DBG_COUNT_DIM; i++) { - dbgCount[i] = 0; - if (i < DBG_TIME_DIM) { - dbgMaxTime[i] = 0; - dbgMinTime[i] = 9999999; - dbgTotalTime[i] = 0; - } - } -} -//------------------------------------------------------------------------------ -static void dbgEndTime(DbgTag tag) { - uint32_t m = micros() - dbgBgnTime[tag]; - dbgTotalTime[tag] += m; - if (m > dbgMaxTime[tag]) { - dbgMaxTime[tag] = m; - } - if (m < dbgMinTime[tag]) { - dbgMinTime[tag] = m; - } - dbgCount[tag]++; -} -//------------------------------------------------------------------------------ -static void dbgEventCount(DbgTag tag) { - dbgCount[tag]++; -} -//------------------------------------------------------------------------------ -static void dbgPrintTagText(uint8_t tag) { - #define DBG_TAG(e, m) case e: Serial.print(F(m)); break; - switch (tag) { - DBG_TAG_LIST - } - #undef DBG_TAG -} -//------------------------------------------------------------------------------ -static void dbgPrintStats() { - Serial.println(); - Serial.println(F("=======================")); - Serial.println(F("item,event,min,max,avg")); - Serial.println(F("tag,count,usec,usec,usec")); - for (int i = 0; i < DBG_COUNT_DIM; i++) { - if (dbgCount[i]) { - dbgPrintTagText(i); - Serial.print(','); - Serial.print(dbgCount[i]); - if (i < DBG_TIME_DIM) { - Serial.print(','); - Serial.print(dbgMinTime[i]); - Serial.print(','); - Serial.print(dbgMaxTime[i]); - Serial.print(','); - Serial.print(dbgTotalTime[i]/dbgCount[i]); - } - Serial.println(); - } - } - Serial.println(F("=======================")); - Serial.println(); -} -#undef DBG_TAG_LIST -#define DBG_BEGIN_TIME(tag) dbgBeginTime(tag) -#define DBG_END_TIME(tag) dbgEndTime(tag) -#define DBG_EVENT_COUNT(tag) dbgEventCount(tag) -#else // DBG_PROFILE_STATS -#define DBG_BEGIN_TIME(tag) -#define DBG_END_TIME(tag) -#define DBG_EVENT_COUNT(tag) -static void dbgClearStats() {} -static void dbgPrintStats() {} -#endif // DBG_PROFILE_STATS -//============================================================================== -#if USE_SD_CRC -// CRC functions -//------------------------------------------------------------------------------ -static uint8_t CRC7(const uint8_t* data, uint8_t n) { - uint8_t crc = 0; - for (uint8_t i = 0; i < n; i++) { - uint8_t d = data[i]; - for (uint8_t j = 0; j < 8; j++) { - crc <<= 1; - if ((d & 0x80) ^ (crc & 0x80)) { - crc ^= 0x09; - } - d <<= 1; - } - } - return (crc << 1) | 1; -} -//------------------------------------------------------------------------------ -#if USE_SD_CRC == 1 -// Shift based CRC-CCITT -// uses the x^16,x^12,x^5,x^1 polynomial. -static uint16_t CRC_CCITT(const uint8_t *data, size_t n) { - uint16_t crc = 0; - for (size_t i = 0; i < n; i++) { - crc = (uint8_t)(crc >> 8) | (crc << 8); - crc ^= data[i]; - crc ^= (uint8_t)(crc & 0xff) >> 4; - crc ^= crc << 12; - crc ^= (crc & 0xff) << 5; - } - return crc; -} -#elif USE_SD_CRC > 1 // CRC_CCITT -//------------------------------------------------------------------------------ -// Table based CRC-CCITT -// uses the x^16,x^12,x^5,x^1 polynomial. -#ifdef __AVR__ -static const uint16_t crctab[] PROGMEM = { -#else // __AVR__ -static const uint16_t crctab[] = { -#endif // __AVR__ - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, - 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, - 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, - 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, - 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, - 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, - 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, - 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, - 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, - 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, - 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, - 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, - 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, - 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, - 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, - 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, - 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, - 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, - 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, - 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, - 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, - 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, - 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, - 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, - 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, - 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, - 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, - 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, - 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0 -}; -static uint16_t CRC_CCITT(const uint8_t* data, size_t n) { - uint16_t crc = 0; - for (size_t i = 0; i < n; i++) { -#ifdef __AVR__ - crc = pgm_read_word(&crctab[(crc >> 8 ^ data[i]) & 0XFF]) ^ (crc << 8); -#else // __AVR__ - crc = crctab[(crc >> 8 ^ data[i]) & 0XFF] ^ (crc << 8); -#endif // __AVR__ - } - return crc; -} -#endif // CRC_CCITT -#endif // USE_SD_CRC -//============================================================================== -// SdSpiCard member functions -//------------------------------------------------------------------------------ -bool SdSpiCard::begin(SdSpiDriver* spi, uint8_t csPin, SPISettings settings) { - m_spiActive = false; - m_errorCode = SD_CARD_ERROR_NONE; - m_type = 0; - m_spiDriver = spi; - uint16_t t0 = curTimeMS(); - uint32_t arg; - - m_spiDriver->begin(csPin); - m_spiDriver->setSpiSettings(SD_SCK_HZ(250000)); - spiStart(); - - // must supply min of 74 clock cycles with CS high. - spiUnselect(); - for (uint8_t i = 0; i < 10; i++) { - spiSend(0XFF); - } - spiSelect(); - - DBG_BEGIN_TIME(DBG_CMD0_TIME); - // command to go idle in SPI mode - for (uint8_t i = 1;; i++) { - DBG_EVENT_COUNT(DBG_CMD0_COUNT); - if (cardCommand(CMD0, 0) == R1_IDLE_STATE) { - break; - } - if (i == SD_CMD0_RETRY) { - error(SD_CARD_ERROR_CMD0); - goto fail; - } - // stop multi-block write - spiSend(STOP_TRAN_TOKEN); - // finish block transfer - for (int i = 0; i < 520; i++) { - spiReceive(); - } - } - DBG_END_TIME(DBG_CMD0_TIME); -#if USE_SD_CRC - if (cardCommand(CMD59, 1) != R1_IDLE_STATE) { - error(SD_CARD_ERROR_CMD59); - goto fail; - } -#endif // USE_SD_CRC - // check SD version - if (cardCommand(CMD8, 0x1AA) == (R1_ILLEGAL_COMMAND | R1_IDLE_STATE)) { - type(SD_CARD_TYPE_SD1); - } else { - for (uint8_t i = 0; i < 4; i++) { - m_status = spiReceive(); - } - if (m_status == 0XAA) { - type(SD_CARD_TYPE_SD2); - } else { - error(SD_CARD_ERROR_CMD8); - goto fail; - } - } - // initialize card and send host supports SDHC if SD2 - arg = type() == SD_CARD_TYPE_SD2 ? 0X40000000 : 0; - DBG_BEGIN_TIME(DBG_ACMD41_TIME); - while (cardAcmd(ACMD41, arg) != R1_READY_STATE) { - DBG_EVENT_COUNT(DBG_ACMD41_COUNT); - // check for timeout - if (isTimedOut(t0, SD_INIT_TIMEOUT)) { - error(SD_CARD_ERROR_ACMD41); - goto fail; - } - } - DBG_END_TIME(DBG_ACMD41_TIME); - // if SD2 read OCR register to check for SDHC card - if (type() == SD_CARD_TYPE_SD2) { - if (cardCommand(CMD58, 0)) { - error(SD_CARD_ERROR_CMD58); - goto fail; - } - if ((spiReceive() & 0XC0) == 0XC0) { - type(SD_CARD_TYPE_SDHC); - } - // Discard rest of ocr - contains allowed voltage range. - for (uint8_t i = 0; i < 3; i++) { - spiReceive(); - } - } - spiStop(); - m_spiDriver->setSpiSettings(settings); - return true; - -fail: - spiStop(); - return false; -} -//------------------------------------------------------------------------------ -// send command and return error code. Return zero for OK -uint8_t SdSpiCard::cardCommand(uint8_t cmd, uint32_t arg) { - // select card - if (!m_spiActive) { - spiStart(); - } - // wait if busy unless CMD0 - if (cmd != CMD0) { - DBG_BEGIN_TIME(DBG_CMD_BUSY); - waitNotBusy(SD_CMD_TIMEOUT); - DBG_END_TIME(DBG_CMD_BUSY); - } - -#if USE_SD_CRC - // form message - uint8_t buf[6]; - buf[0] = (uint8_t)0x40U | cmd; - buf[1] = (uint8_t)(arg >> 24U); - buf[2] = (uint8_t)(arg >> 16U); - buf[3] = (uint8_t)(arg >> 8U); - buf[4] = (uint8_t)arg; - - // add CRC - buf[5] = CRC7(buf, 5); - - // send message - spiSend(buf, 6); -#else // USE_SD_CRC - // send command - spiSend(cmd | 0x40); - - // send argument - uint8_t *pa = reinterpret_cast(&arg); - for (int8_t i = 3; i >= 0; i--) { - spiSend(pa[i]); - } - // send CRC - correct for CMD0 with arg zero or CMD8 with arg 0X1AA - spiSend(cmd == CMD0 ? 0X95 : 0X87); -#endif // USE_SD_CRC - - // discard first fill byte to avoid MISO pull-up problem. - spiReceive(); - - // there are 1-8 fill bytes before response. fill bytes should be 0XFF. - for (uint8_t i = 0; ((m_status = spiReceive()) & 0X80) && i < 10; i++) { - } - return m_status; -} -//------------------------------------------------------------------------------ -uint32_t SdSpiCard::cardSize() { - csd_t csd; - return readCSD(&csd) ? sdCardCapacity(&csd) : 0; -} -//------------------------------------------------------------------------------ -void SdSpiCard::dbgClearStats() {::dbgClearStats();} -//------------------------------------------------------------------------------ -void SdSpiCard::dbgPrintStats() {::dbgPrintStats();} -//------------------------------------------------------------------------------ -bool SdSpiCard::erase(uint32_t firstBlock, uint32_t lastBlock) { - csd_t csd; - if (!readCSD(&csd)) { - goto fail; - } - // check for single block erase - if (!csd.v1.erase_blk_en) { - // erase size mask - uint8_t m = (csd.v1.sector_size_high << 1) | csd.v1.sector_size_low; - if ((firstBlock & m) != 0 || ((lastBlock + 1) & m) != 0) { - // error card can't erase specified area - error(SD_CARD_ERROR_ERASE_SINGLE_BLOCK); - goto fail; - } - } - if (m_type != SD_CARD_TYPE_SDHC) { - firstBlock <<= 9; - lastBlock <<= 9; - } - if (cardCommand(CMD32, firstBlock) - || cardCommand(CMD33, lastBlock) - || cardCommand(CMD38, 0)) { - error(SD_CARD_ERROR_ERASE); - goto fail; - } - DBG_BEGIN_TIME(DBG_ERASE_BUSY); - if (!waitNotBusy(SD_ERASE_TIMEOUT)) { - error(SD_CARD_ERROR_ERASE_TIMEOUT); - goto fail; - } - DBG_END_TIME(DBG_ERASE_BUSY); - spiStop(); - return true; - -fail: - spiStop(); - return false; -} -//------------------------------------------------------------------------------ -bool SdSpiCard::eraseSingleBlockEnable() { - csd_t csd; - return readCSD(&csd) ? csd.v1.erase_blk_en : false; -} -//------------------------------------------------------------------------------ -bool SdSpiCard::isBusy() { - bool rtn = true; - bool spiActive = m_spiActive; - if (!spiActive) { - spiStart(); - } - for (uint8_t i = 0; i < 8; i++) { - if (0XFF == spiReceive()) { - rtn = false; - break; - } - } - if (!spiActive) { - spiStop(); - } - return rtn; -} -//------------------------------------------------------------------------------ -bool SdSpiCard::isTimedOut(uint16_t startMS, uint16_t timeoutMS) { -#if WDT_YIELD_TIME_MICROS - static uint32_t last; - if ((micros() - last) > WDT_YIELD_TIME_MICROS) { - SysCall::yield(); - last = micros(); - } -#endif // WDT_YIELD_TIME_MICROS - return (curTimeMS() - startMS) > timeoutMS; -} -//------------------------------------------------------------------------------ -bool SdSpiCard::readBlock(uint32_t blockNumber, uint8_t* dst) { - SD_TRACE("RB", blockNumber); - // use address if not SDHC card - if (type() != SD_CARD_TYPE_SDHC) { - blockNumber <<= 9; - } - if (cardCommand(CMD17, blockNumber)) { - error(SD_CARD_ERROR_CMD17); - goto fail; - } - if (!readData(dst, 512)) { - goto fail; - } - spiStop(); - return true; - -fail: - spiStop(); - return false; -} -//------------------------------------------------------------------------------ -bool SdSpiCard::readBlocks(uint32_t block, uint8_t* dst, size_t count) { - if (!readStart(block)) { - return false; - } - for (uint16_t b = 0; b < count; b++, dst += 512) { - if (!readData(dst, 512)) { - return false; - } - } - return readStop(); -} -//------------------------------------------------------------------------------ -bool SdSpiCard::readData(uint8_t *dst) { - return readData(dst, 512); -} -//------------------------------------------------------------------------------ -bool SdSpiCard::readData(uint8_t* dst, size_t count) { -#if USE_SD_CRC - uint16_t crc; -#endif // USE_SD_CRC - DBG_BEGIN_TIME(DBG_WAIT_READ); - // wait for start block token - uint16_t t0 = curTimeMS(); - while ((m_status = spiReceive()) == 0XFF) { - if (isTimedOut(t0, SD_READ_TIMEOUT)) { - error(SD_CARD_ERROR_READ_TIMEOUT); - goto fail; - } - } - DBG_END_TIME(DBG_WAIT_READ); - if (m_status != DATA_START_BLOCK) { - error(SD_CARD_ERROR_READ); - goto fail; - } - // transfer data - if ((m_status = spiReceive(dst, count))) { - error(SD_CARD_ERROR_DMA); - goto fail; - } - -#if USE_SD_CRC - // get crc - crc = (spiReceive() << 8) | spiReceive(); - if (crc != CRC_CCITT(dst, count)) { - error(SD_CARD_ERROR_READ_CRC); - goto fail; - } -#else - // discard crc - spiReceive(); - spiReceive(); -#endif // USE_SD_CRC - return true; - -fail: - spiStop(); - return false; -} -//------------------------------------------------------------------------------ -bool SdSpiCard::readOCR(uint32_t* ocr) { - uint8_t *p = reinterpret_cast(ocr); - if (cardCommand(CMD58, 0)) { - error(SD_CARD_ERROR_CMD58); - goto fail; - } - for (uint8_t i = 0; i < 4; i++) { - p[3 - i] = spiReceive(); - } - - spiStop(); - return true; - -fail: - spiStop(); - return false; -} -//------------------------------------------------------------------------------ -/** read CID or CSR register */ -bool SdSpiCard::readRegister(uint8_t cmd, void* buf) { - uint8_t* dst = reinterpret_cast(buf); - if (cardCommand(cmd, 0)) { - error(SD_CARD_ERROR_READ_REG); - goto fail; - } - if (!readData(dst, 16)) { - goto fail; - } - spiStop(); - return true; - -fail: - spiStop(); - return false; -} -//------------------------------------------------------------------------------ -bool SdSpiCard::readStart(uint32_t blockNumber) { - SD_TRACE("RS", blockNumber); - if (type() != SD_CARD_TYPE_SDHC) { - blockNumber <<= 9; - } - if (cardCommand(CMD18, blockNumber)) { - error(SD_CARD_ERROR_CMD18); - goto fail; - } -// spiStop(); - return true; - -fail: - spiStop(); - return false; -} -//----------------------------------------------------------------------------- -bool SdSpiCard::readStatus(uint8_t* status) { - // retrun is R2 so read extra status byte. - if (cardAcmd(ACMD13, 0) || spiReceive()) { - error(SD_CARD_ERROR_ACMD13); - goto fail; - } - if (!readData(status, 64)) { - goto fail; - } - spiStop(); - return true; - -fail: - spiStop(); - return false; -} -//----------------------------------------------------------------------------- -void SdSpiCard::spiStart() { - if (!m_spiActive) { - spiActivate(); - spiSelect(); - m_spiActive = true; - } -} -//----------------------------------------------------------------------------- -void SdSpiCard::spiStop() { - if (m_spiActive) { - spiUnselect(); - spiSend(0XFF); - spiDeactivate(); - m_spiActive = false; - } -} -//------------------------------------------------------------------------------ -bool SdSpiCard::readStop() { - if (cardCommand(CMD12, 0)) { - error(SD_CARD_ERROR_CMD12); - goto fail; - } - spiStop(); - return true; - -fail: - spiStop(); - return false; -} -//------------------------------------------------------------------------------ -// wait for card to go not busy -bool SdSpiCard::waitNotBusy(uint16_t timeoutMS) { - uint16_t t0 = curTimeMS(); -#if WDT_YIELD_TIME_MICROS - // Call isTimedOut first to insure yield is called. - while (!isTimedOut(t0, timeoutMS)) { - if (spiReceive() == 0XFF) { - return true; - } - } - return false; -#else // WDT_YIELD_TIME_MICROS - // Check not busy first since yield is not called in isTimedOut. - while (spiReceive() != 0XFF) { - if (isTimedOut(t0, timeoutMS)) { - return false; - } - } - return true; -#endif // WDT_YIELD_TIME_MICROS -} -//------------------------------------------------------------------------------ -bool SdSpiCard::writeBlock(uint32_t blockNumber, const uint8_t* src) { - SD_TRACE("WB", blockNumber); - // use address if not SDHC card - if (type() != SD_CARD_TYPE_SDHC) { - blockNumber <<= 9; - } - if (cardCommand(CMD24, blockNumber)) { - error(SD_CARD_ERROR_CMD24); - goto fail; - } - if (!writeData(DATA_START_BLOCK, src)) { - goto fail; - } - - -#if CHECK_FLASH_PROGRAMMING - // wait for flash programming to complete - DBG_BEGIN_TIME(DBG_WRITE_FLASH); - if (!waitNotBusy(SD_WRITE_TIMEOUT)) { - error(SD_CARD_ERROR_FLASH_PROGRAMMING); - goto fail; - } - DBG_END_TIME(DBG_WRITE_FLASH); - // response is r2 so get and check two bytes for nonzero - if (cardCommand(CMD13, 0) || spiReceive()) { - error(SD_CARD_ERROR_CMD13); - goto fail; - } -#endif // CHECK_PROGRAMMING - - spiStop(); - return true; - -fail: - spiStop(); - return false; -} -//------------------------------------------------------------------------------ -bool SdSpiCard::writeBlocks(uint32_t block, const uint8_t* src, size_t count) { - if (!writeStart(block)) { - goto fail; - } - for (size_t b = 0; b < count; b++, src += 512) { - if (!writeData(src)) { - goto fail; - } - } - return writeStop(); - - fail: - spiStop(); - return false; -} -//------------------------------------------------------------------------------ -bool SdSpiCard::writeData(const uint8_t* src) { - // wait for previous write to finish - DBG_BEGIN_TIME(DBG_WRITE_BUSY); - if (!waitNotBusy(SD_WRITE_TIMEOUT)) { - error(SD_CARD_ERROR_WRITE_TIMEOUT); - goto fail; - } - DBG_END_TIME(DBG_WRITE_BUSY); - if (!writeData(WRITE_MULTIPLE_TOKEN, src)) { - goto fail; - } - return true; - -fail: - spiStop(); - return false; -} -//------------------------------------------------------------------------------ -// send one block of data for write block or write multiple blocks -bool SdSpiCard::writeData(uint8_t token, const uint8_t* src) { -#if USE_SD_CRC - uint16_t crc = CRC_CCITT(src, 512); -#else // USE_SD_CRC - uint16_t crc = 0XFFFF; -#endif // USE_SD_CRC - spiSend(token); - spiSend(src, 512); - spiSend(crc >> 8); - spiSend(crc & 0XFF); - - m_status = spiReceive(); - if ((m_status & DATA_RES_MASK) != DATA_RES_ACCEPTED) { - error(SD_CARD_ERROR_WRITE); - goto fail; - } - return true; - -fail: - spiStop(); - return false; -} -//------------------------------------------------------------------------------ -bool SdSpiCard::writeStart(uint32_t blockNumber) { - // use address if not SDHC card - if (type() != SD_CARD_TYPE_SDHC) { - blockNumber <<= 9; - } - if (cardCommand(CMD25, blockNumber)) { - error(SD_CARD_ERROR_CMD25); - goto fail; - } - return true; - -fail: - spiStop(); - return false; -} -//------------------------------------------------------------------------------ -bool SdSpiCard::writeStart(uint32_t blockNumber, uint32_t eraseCount) { - SD_TRACE("WS", blockNumber); - // send pre-erase count - if (cardAcmd(ACMD23, eraseCount)) { - error(SD_CARD_ERROR_ACMD23); - goto fail; - } - // use address if not SDHC card - if (type() != SD_CARD_TYPE_SDHC) { - blockNumber <<= 9; - } - if (cardCommand(CMD25, blockNumber)) { - error(SD_CARD_ERROR_CMD25); - goto fail; - } - return true; - -fail: - spiStop(); - return false; -} -//------------------------------------------------------------------------------ -bool SdSpiCard::writeStop() { - DBG_BEGIN_TIME(DBG_WRITE_STOP); - if (!waitNotBusy(SD_WRITE_TIMEOUT)) { - goto fail; - } - DBG_END_TIME(DBG_WRITE_STOP); - spiSend(STOP_TRAN_TOKEN); - spiStop(); - return true; - -fail: - error(SD_CARD_ERROR_STOP_TRAN); - spiStop(); - return false; -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCard.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCard.h deleted file mode 100644 index e89d09f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCard.h +++ /dev/null @@ -1,377 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 SdSpiCard_h -#define SdSpiCard_h -/** - * \file - * \brief SdSpiCard class for V2 SD/SDHC cards - */ -#include -#include "SysCall.h" -#include "SdInfo.h" -#include "../FatLib/BaseBlockDriver.h" -#include "../SpiDriver/SdSpiDriver.h" -//============================================================================== -/** - * \class SdSpiCard - * \brief Raw access to SD and SDHC flash memory cards via SPI protocol. - */ -#if ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS -class SdSpiCard : public BaseBlockDriver { -#else // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS -class SdSpiCard { -#endif // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS - public: - /** Construct an instance of SdSpiCard. */ - SdSpiCard() : m_errorCode(SD_CARD_ERROR_INIT_NOT_CALLED), m_type(0) {} - /** Initialize the SD card. - * \param[in] spi SPI driver for card. - * \param[in] csPin card chip select pin. - * \param[in] spiSettings SPI speed, mode, and bit order. - * \return true for success else false. - */ - bool begin(SdSpiDriver* spi, uint8_t csPin, SPISettings spiSettings); - /** - * Determine the size of an SD flash memory card. - * - * \return The number of 512 byte data blocks in the card - * or zero if an error occurs. - */ - uint32_t cardSize(); - /** Clear debug stats. */ - void dbgClearStats(); - /** Print debug stats. */ - void dbgPrintStats(); - /** Erase a range of blocks. - * - * \param[in] firstBlock The address of the first block in the range. - * \param[in] lastBlock The address of the last block in the range. - * - * \note This function requests the SD card to do a flash erase for a - * range of blocks. The data on the card after an erase operation is - * either 0 or 1, depends on the card vendor. The card must support - * single block erase. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool erase(uint32_t firstBlock, uint32_t lastBlock); - /** Determine if card supports single block erase. - * - * \return true is returned if single block erase is supported. - * false is returned if single block erase is not supported. - */ - bool eraseSingleBlockEnable(); - /** - * Set SD error code. - * \param[in] code value for error code. - */ - void error(uint8_t code) { - m_errorCode = code; - } - /** - * \return code for the last error. See SdInfo.h for a list of error codes. - */ - int errorCode() const { - return m_errorCode; - } - /** \return error data for last error. */ - int errorData() const { - return m_status; - } - /** - * Check for busy. MISO low indicates the card is busy. - * - * \return true if busy else false. - */ - bool isBusy(); - /** - * Read a 512 byte block from an SD card. - * - * \param[in] lba Logical block to be read. - * \param[out] dst Pointer to the location that will receive the data. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool readBlock(uint32_t lba, uint8_t* dst); - /** - * Read multiple 512 byte blocks from an SD card. - * - * \param[in] lba Logical block to be read. - * \param[in] nb Number of blocks to be read. - * \param[out] dst Pointer to the location that will receive the data. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool readBlocks(uint32_t lba, uint8_t* dst, size_t nb); - /** - * Read a card's CID register. The CID contains card identification - * information such as Manufacturer ID, Product name, Product serial - * number and Manufacturing date. - * - * \param[out] cid pointer to area for returned data. - * - * \return true for success or false for failure. - */ - bool readCID(cid_t* cid) { - return readRegister(CMD10, cid); - } - /** - * Read a card's CSD register. The CSD contains Card-Specific Data that - * provides information regarding access to the card's contents. - * - * \param[out] csd pointer to area for returned data. - * - * \return true for success or false for failure. - */ - bool readCSD(csd_t* csd) { - return readRegister(CMD9, csd); - } - /** Read one data block in a multiple block read sequence - * - * \param[out] dst Pointer to the location for the data to be read. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool readData(uint8_t *dst); - /** Read OCR register. - * - * \param[out] ocr Value of OCR register. - * \return true for success else false. - */ - bool readOCR(uint32_t* ocr); - /** Start a read multiple blocks sequence. - * - * \param[in] blockNumber Address of first block in sequence. - * - * \note This function is used with readData() and readStop() for optimized - * multiple block reads. SPI chipSelect must be low for the entire sequence. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool readStart(uint32_t blockNumber); - /** Return the 64 byte card status - * \param[out] status location for 64 status bytes. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool readStatus(uint8_t* status); - /** End a read multiple blocks sequence. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool readStop(); - /** \return success if sync successful. Not for user apps. */ - bool syncBlocks() {return true;} - /** Return the card type: SD V1, SD V2 or SDHC - * \return 0 - SD V1, 1 - SD V2, or 3 - SDHC. - */ - int type() const { - return m_type; - } - /** - * Writes a 512 byte block to an SD card. - * - * \param[in] lba Logical block to be written. - * \param[in] src Pointer to the location of the data to be written. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool writeBlock(uint32_t lba, const uint8_t* src); - /** - * Write multiple 512 byte blocks to an SD card. - * - * \param[in] lba Logical block to be written. - * \param[in] nb Number of blocks to be written. - * \param[in] src Pointer to the location of the data to be written. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool writeBlocks(uint32_t lba, const uint8_t* src, size_t nb); - /** Write one data block in a multiple block write sequence. - * \param[in] src Pointer to the location of the data to be written. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool writeData(const uint8_t* src); - /** Start a write multiple blocks sequence. - * - * \param[in] blockNumber Address of first block in sequence. - * - * \note This function is used with writeData() and writeStop() - * for optimized multiple block writes. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool writeStart(uint32_t blockNumber); - - /** Start a write multiple blocks sequence with pre-erase. - * - * \param[in] blockNumber Address of first block in sequence. - * \param[in] eraseCount The number of blocks to be pre-erased. - * - * \note This function is used with writeData() and writeStop() - * for optimized multiple block writes. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool writeStart(uint32_t blockNumber, uint32_t eraseCount); - /** End a write multiple blocks sequence. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool writeStop(); - /** Set CS low and activate the card. */ - void spiStart(); - /** Set CS high and deactivate the card. */ - void spiStop(); - - private: - // private functions - uint8_t cardAcmd(uint8_t cmd, uint32_t arg) { - cardCommand(CMD55, 0); - return cardCommand(cmd, arg); - } - uint8_t cardCommand(uint8_t cmd, uint32_t arg); - bool isTimedOut(uint16_t startMS, uint16_t timeoutMS); - bool readData(uint8_t* dst, size_t count); - bool readRegister(uint8_t cmd, void* buf); - - void type(uint8_t value) { - m_type = value; - } - - bool waitNotBusy(uint16_t timeoutMS); - bool writeData(uint8_t token, const uint8_t* src); - - //--------------------------------------------------------------------------- - // functions defined in SdSpiDriver.h - void spiActivate() { - m_spiDriver->activate(); - } - void spiDeactivate() { - m_spiDriver->deactivate(); - } - uint8_t spiReceive() { - return m_spiDriver->receive(); - } - uint8_t spiReceive(uint8_t* buf, size_t n) { - return m_spiDriver->receive(buf, n); - } - void spiSend(uint8_t data) { - m_spiDriver->send(data); - } - void spiSend(const uint8_t* buf, size_t n) { - m_spiDriver->send(buf, n); - } - void spiSelect() { - m_spiDriver->select(); - } - void spiUnselect() { - m_spiDriver->unselect(); - } - uint8_t m_errorCode; - SdSpiDriver *m_spiDriver; - bool m_spiActive; - uint8_t m_status; - uint8_t m_type; -}; -//============================================================================== -/** - * \class SdSpiCardEX - * \brief Extended SD I/O block driver. - */ -class SdSpiCardEX : public SdSpiCard { - public: - /** Initialize the SD card - * - * \param[in] spi SPI driver. - * \param[in] csPin Card chip select pin number. - * \param[in] spiSettings SPI speed, mode, and bit order. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool begin(SdSpiDriver* spi, uint8_t csPin, SPISettings spiSettings) { - m_curState = IDLE_STATE; - return SdSpiCard::begin(spi, csPin, spiSettings); - } - /** - * Read a 512 byte block from an SD card. - * - * \param[in] block Logical block to be read. - * \param[out] dst Pointer to the location that will receive the data. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool readBlock(uint32_t block, uint8_t* dst); - /** End multi-block transfer and go to idle state. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool syncBlocks(); - /** - * Writes a 512 byte block to an SD card. - * - * \param[in] block Logical block to be written. - * \param[in] src Pointer to the location of the data to be written. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool writeBlock(uint32_t block, const uint8_t* src); - /** - * Read multiple 512 byte blocks from an SD card. - * - * \param[in] block Logical block to be read. - * \param[in] nb Number of blocks to be read. - * \param[out] dst Pointer to the location that will receive the data. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool readBlocks(uint32_t block, uint8_t* dst, size_t nb); - /** - * Write multiple 512 byte blocks to an SD card. - * - * \param[in] block Logical block to be written. - * \param[in] nb Number of blocks to be written. - * \param[in] src Pointer to the location of the data to be written. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool writeBlocks(uint32_t block, const uint8_t* src, size_t nb); - - private: - static const uint32_t IDLE_STATE = 0; - static const uint32_t READ_STATE = 1; - static const uint32_t WRITE_STATE = 2; - uint32_t m_curBlock; - uint8_t m_curState; -}; -#endif // SdSpiCard_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCardEX.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCardEX.cpp deleted file mode 100644 index e3ab056..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdSpiCardEX.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#include "SdSpiCard.h" -bool SdSpiCardEX::readBlock(uint32_t block, uint8_t* dst) { - if (m_curState != READ_STATE || block != m_curBlock) { - if (!syncBlocks()) { - return false; - } - if (!SdSpiCard::readStart(block)) { - return false; - } - m_curBlock = block; - m_curState = READ_STATE; - } - if (!SdSpiCard::readData(dst)) { - return false; - } - m_curBlock++; - return true; -} -//----------------------------------------------------------------------------- -bool SdSpiCardEX::readBlocks(uint32_t block, uint8_t* dst, size_t nb) { - for (size_t i = 0; i < nb; i++) { - if (!readBlock(block + i, dst + i*512UL)) { - return false; - } - } - return true; -} -//----------------------------------------------------------------------------- -bool SdSpiCardEX::syncBlocks() { - if (m_curState == READ_STATE) { - m_curState = IDLE_STATE; - if (!SdSpiCard::readStop()) { - return false; - } - } else if (m_curState == WRITE_STATE) { - m_curState = IDLE_STATE; - if (!SdSpiCard::writeStop()) { - return false; - } - } - return true; -} -//----------------------------------------------------------------------------- -bool SdSpiCardEX::writeBlock(uint32_t block, const uint8_t* src) { - if (m_curState != WRITE_STATE || m_curBlock != block) { - if (!syncBlocks()) { - return false; - } - if (!SdSpiCard::writeStart(block)) { - return false; - } - m_curBlock = block; - m_curState = WRITE_STATE; - } - if (!SdSpiCard::writeData(src)) { - return false; - } - m_curBlock++; - return true; -} -//----------------------------------------------------------------------------- -bool SdSpiCardEX::writeBlocks(uint32_t block, - const uint8_t* src, size_t nb) { - for (size_t i = 0; i < nb; i++) { - if (!writeBlock(block + i, src + i*512UL)) { - return false; - } - } - return true; -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioCard.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioCard.h deleted file mode 100644 index 06ef571..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioCard.h +++ /dev/null @@ -1,301 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 SdioCard_h -#define SdioCard_h -#include "SysCall.h" -#include "BlockDriver.h" -/** - * \class SdioCard - * \brief Raw SDIO access to SD and SDHC flash memory cards. - */ -class SdioCard : public BaseBlockDriver { - public: - /** Initialize the SD card. - * \return true for success else false. - */ - bool begin(); - /** - * Determine the size of an SD flash memory card. - * - * \return The number of 512 byte data blocks in the card - * or zero if an error occurs. - */ - uint32_t cardSize(); - /** Erase a range of blocks. - * - * \param[in] firstBlock The address of the first block in the range. - * \param[in] lastBlock The address of the last block in the range. - * - * \note This function requests the SD card to do a flash erase for a - * range of blocks. The data on the card after an erase operation is - * either 0 or 1, depends on the card vendor. The card must support - * single block erase. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool erase(uint32_t firstBlock, uint32_t lastBlock); - /** - * \return code for the last error. See SdInfo.h for a list of error codes. - */ - uint8_t errorCode(); - /** \return error data for last error. */ - uint32_t errorData(); - /** \return error line for last error. Tmp function for debug. */ - uint32_t errorLine(); - /** - * Check for busy with CMD13. - * - * \return true if busy else false. - */ - bool isBusy(); - /** \return the SD clock frequency in kHz. */ - uint32_t kHzSdClk(); - /** - * Read a 512 byte block from an SD card. - * - * \param[in] lba Logical block to be read. - * \param[out] dst Pointer to the location that will receive the data. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool readBlock(uint32_t lba, uint8_t* dst); - /** - * Read multiple 512 byte blocks from an SD card. - * - * \param[in] lba Logical block to be read. - * \param[in] nb Number of blocks to be read. - * \param[out] dst Pointer to the location that will receive the data. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool readBlocks(uint32_t lba, uint8_t* dst, size_t nb); - /** - * Read a card's CID register. The CID contains card identification - * information such as Manufacturer ID, Product name, Product serial - * number and Manufacturing date. - * - * \param[out] cid pointer to area for returned data. - * - * \return true for success or false for failure. - */ - bool readCID(void* cid); - /** - * Read a card's CSD register. The CSD contains Card-Specific Data that - * provides information regarding access to the card's contents. - * - * \param[out] csd pointer to area for returned data. - * - * \return true for success or false for failure. - */ - bool readCSD(void* csd); - /** Read one data block in a multiple block read sequence - * - * \param[out] dst Pointer to the location for the data to be read. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool readData(uint8_t *dst); - /** Read OCR register. - * - * \param[out] ocr Value of OCR register. - * \return true for success else false. - */ - bool readOCR(uint32_t* ocr); - /** Start a read multiple blocks sequence. - * - * \param[in] lba Address of first block in sequence. - * - * \note This function is used with readData() and readStop() for optimized - * multiple block reads. SPI chipSelect must be low for the entire sequence. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool readStart(uint32_t lba); - /** Start a read multiple blocks sequence. - * - * \param[in] lba Address of first block in sequence. - * \param[in] count Maximum block count. - * \note This function is used with readData() and readStop() for optimized - * multiple block reads. SPI chipSelect must be low for the entire sequence. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool readStart(uint32_t lba, uint32_t count); - /** End a read multiple blocks sequence. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool readStop(); - /** \return success if sync successful. Not for user apps. */ - bool syncBlocks(); - /** Return the card type: SD V1, SD V2 or SDHC - * \return 0 - SD V1, 1 - SD V2, or 3 - SDHC. - */ - uint8_t type(); - /** - * Writes a 512 byte block to an SD card. - * - * \param[in] lba Logical block to be written. - * \param[in] src Pointer to the location of the data to be written. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool writeBlock(uint32_t lba, const uint8_t* src); - /** - * Write multiple 512 byte blocks to an SD card. - * - * \param[in] lba Logical block to be written. - * \param[in] nb Number of blocks to be written. - * \param[in] src Pointer to the location of the data to be written. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool writeBlocks(uint32_t lba, const uint8_t* src, size_t nb); - /** Write one data block in a multiple block write sequence. - * \param[in] src Pointer to the location of the data to be written. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool writeData(const uint8_t* src); - /** Start a write multiple blocks sequence. - * - * \param[in] lba Address of first block in sequence. - * - * \note This function is used with writeData() and writeStop() - * for optimized multiple block writes. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool writeStart(uint32_t lba); - /** Start a write multiple blocks sequence. - * - * \param[in] lba Address of first block in sequence. - * \param[in] count Maximum block count. - * \note This function is used with writeData() and writeStop() - * for optimized multiple block writes. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool writeStart(uint32_t lba, uint32_t count); - - /** End a write multiple blocks sequence. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool writeStop(); -}; -//============================================================================== -/** - * \class SdioCardEX - * \brief Extended SD I/O block driver. - */ -class SdioCardEX : public SdioCard { - public: - /** Initialize the SD card - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool begin() { - m_curState = IDLE_STATE; - return SdioCard::begin(); - } - /** Erase a range of blocks. - * - * \param[in] firstBlock The address of the first block in the range. - * \param[in] lastBlock The address of the last block in the range. - * - * \note This function requests the SD card to do a flash erase for a - * range of blocks. The data on the card after an erase operation is - * either 0 or 1, depends on the card vendor. The card must support - * single block erase. - * - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool erase(uint32_t firstBlock, uint32_t lastBlock) { - return syncBlocks() && SdioCard::erase(firstBlock, lastBlock); - } - /** - * Read a 512 byte block from an SD card. - * - * \param[in] block Logical block to be read. - * \param[out] dst Pointer to the location that will receive the data. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool readBlock(uint32_t block, uint8_t* dst); - /** End multi-block transfer and go to idle state. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool syncBlocks(); - /** - * Writes a 512 byte block to an SD card. - * - * \param[in] block Logical block to be written. - * \param[in] src Pointer to the location of the data to be written. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool writeBlock(uint32_t block, const uint8_t* src); - /** - * Read multiple 512 byte blocks from an SD card. - * - * \param[in] block Logical block to be read. - * \param[in] nb Number of blocks to be read. - * \param[out] dst Pointer to the location that will receive the data. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool readBlocks(uint32_t block, uint8_t* dst, size_t nb); - /** - * Write multiple 512 byte blocks to an SD card. - * - * \param[in] block Logical block to be written. - * \param[in] nb Number of blocks to be written. - * \param[in] src Pointer to the location of the data to be written. - * \return The value true is returned for success and - * the value false is returned for failure. - */ - bool writeBlocks(uint32_t block, const uint8_t* src, size_t nb); - - private: - static const uint32_t IDLE_STATE = 0; - static const uint32_t READ_STATE = 1; - static const uint32_t WRITE_STATE = 2; - uint32_t m_curLba; - uint32_t m_limitLba; - uint8_t m_curState; -}; -#endif // SdioCard_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioCardEX.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioCardEX.cpp deleted file mode 100644 index 8029c97..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioCardEX.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#include "SdioCard.h" - -// limit of K66 due to errata KINETIS_K_0N65N. -const uint32_t MAX_SDHC_COUNT = 0XFFFF; - -// Max RU is 1024 blocks. -const uint32_t RU_MASK = 0X03FF; - -bool SdioCardEX::readBlock(uint32_t lba, uint8_t* dst) { - if (m_curState != READ_STATE || lba != m_curLba) { - if (!syncBlocks()) { - return false; - } - m_limitLba = (lba + MAX_SDHC_COUNT) & ~RU_MASK; - if (!SdioCard::readStart(lba, m_limitLba - lba)) { - return false; - } - m_curLba = lba; - m_curState = READ_STATE; - } - if (!SdioCard::readData(dst)) { - return false; - } - m_curLba++; - if (m_curLba >= m_limitLba) { - m_curState = IDLE_STATE; - } - return true; -} -//----------------------------------------------------------------------------- -bool SdioCardEX::readBlocks(uint32_t lba, uint8_t* dst, size_t nb) { - for (size_t i = 0; i < nb; i++) { - if (!readBlock(lba + i, dst + i*512UL)) { - return false; - } - } - return true; -} -//----------------------------------------------------------------------------- -bool SdioCardEX::syncBlocks() { - if (m_curState == READ_STATE) { - m_curState = IDLE_STATE; - if (!SdioCard::readStop()) { - return false; - } - } else if (m_curState == WRITE_STATE) { - m_curState = IDLE_STATE; - if (!SdioCard::writeStop()) { - return false; - } - } - return true; -} -//----------------------------------------------------------------------------- -bool SdioCardEX::writeBlock(uint32_t lba, const uint8_t* src) { - if (m_curState != WRITE_STATE || m_curLba != lba) { - if (!syncBlocks()) { - return false; - } - m_limitLba = (lba + MAX_SDHC_COUNT) & ~RU_MASK; - if (!SdioCard::writeStart(lba , m_limitLba - lba)) { - return false; - } - m_curLba = lba; - m_curState = WRITE_STATE; - } - if (!SdioCard::writeData(src)) { - return false; - } - m_curLba++; - if (m_curLba >= m_limitLba) { - m_curState = IDLE_STATE; - } - return true; -} -//----------------------------------------------------------------------------- -bool SdioCardEX::writeBlocks(uint32_t lba, const uint8_t* src, size_t nb) { - for (size_t i = 0; i < nb; i++) { - if (!writeBlock(lba + i, src + i*512UL)) { - return false; - } - } - return true; -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioTeensy.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioTeensy.cpp deleted file mode 100644 index 53c2140..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdCard/SdioTeensy.cpp +++ /dev/null @@ -1,800 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#if defined(__MK64FX512__) || defined(__MK66FX1M0__) -#include "SdioCard.h" -//============================================================================== -#define SDHC_PROCTL_DTW_4BIT 0x01 -const uint32_t FIFO_WML = 16; -const uint32_t CMD8_RETRIES = 10; -const uint32_t BUSY_TIMEOUT_MICROS = 500000; -//============================================================================== -const uint32_t SDHC_IRQSTATEN_MASK = - SDHC_IRQSTATEN_DMAESEN | SDHC_IRQSTATEN_AC12ESEN | - SDHC_IRQSTATEN_DEBESEN | SDHC_IRQSTATEN_DCESEN | - SDHC_IRQSTATEN_DTOESEN | SDHC_IRQSTATEN_CIESEN | - SDHC_IRQSTATEN_CEBESEN | SDHC_IRQSTATEN_CCESEN | - SDHC_IRQSTATEN_CTOESEN | SDHC_IRQSTATEN_DINTSEN | - SDHC_IRQSTATEN_TCSEN | SDHC_IRQSTATEN_CCSEN; - -const uint32_t SDHC_IRQSTAT_CMD_ERROR = - SDHC_IRQSTAT_CIE | SDHC_IRQSTAT_CEBE | - SDHC_IRQSTAT_CCE | SDHC_IRQSTAT_CTOE; - -const uint32_t SDHC_IRQSTAT_DATA_ERROR = - SDHC_IRQSTAT_AC12E | SDHC_IRQSTAT_DEBE | - SDHC_IRQSTAT_DCE | SDHC_IRQSTAT_DTOE; - -const uint32_t SDHC_IRQSTAT_ERROR = - SDHC_IRQSTAT_DMAE | SDHC_IRQSTAT_CMD_ERROR | - SDHC_IRQSTAT_DATA_ERROR; - -const uint32_t SDHC_IRQSIGEN_MASK = - SDHC_IRQSIGEN_DMAEIEN | SDHC_IRQSIGEN_AC12EIEN | - SDHC_IRQSIGEN_DEBEIEN | SDHC_IRQSIGEN_DCEIEN | - SDHC_IRQSIGEN_DTOEIEN | SDHC_IRQSIGEN_CIEIEN | - SDHC_IRQSIGEN_CEBEIEN | SDHC_IRQSIGEN_CCEIEN | - SDHC_IRQSIGEN_CTOEIEN | SDHC_IRQSIGEN_TCIEN; -//============================================================================= -const uint32_t CMD_RESP_NONE = SDHC_XFERTYP_RSPTYP(0); - -const uint32_t CMD_RESP_R1 = SDHC_XFERTYP_CICEN | SDHC_XFERTYP_CCCEN | - SDHC_XFERTYP_RSPTYP(2); - -const uint32_t CMD_RESP_R1b = SDHC_XFERTYP_CICEN | SDHC_XFERTYP_CCCEN | - SDHC_XFERTYP_RSPTYP(3); - -const uint32_t CMD_RESP_R2 = SDHC_XFERTYP_CCCEN | SDHC_XFERTYP_RSPTYP(1); - -const uint32_t CMD_RESP_R3 = SDHC_XFERTYP_RSPTYP(2); - -const uint32_t CMD_RESP_R6 = CMD_RESP_R1; - -const uint32_t CMD_RESP_R7 = CMD_RESP_R1; - -const uint32_t DATA_READ = SDHC_XFERTYP_DTDSEL | SDHC_XFERTYP_DPSEL; - -const uint32_t DATA_READ_DMA = DATA_READ | SDHC_XFERTYP_DMAEN; - -const uint32_t DATA_READ_MULTI_DMA = DATA_READ_DMA | SDHC_XFERTYP_MSBSEL | - SDHC_XFERTYP_AC12EN | SDHC_XFERTYP_BCEN; - -const uint32_t DATA_READ_MULTI_PGM = DATA_READ | SDHC_XFERTYP_MSBSEL | - SDHC_XFERTYP_BCEN | SDHC_XFERTYP_AC12EN; - -const uint32_t DATA_WRITE_DMA = SDHC_XFERTYP_DPSEL | SDHC_XFERTYP_DMAEN; - -const uint32_t DATA_WRITE_MULTI_DMA = DATA_WRITE_DMA | SDHC_XFERTYP_MSBSEL | - SDHC_XFERTYP_AC12EN | SDHC_XFERTYP_BCEN; - -const uint32_t DATA_WRITE_MULTI_PGM = SDHC_XFERTYP_DPSEL | - SDHC_XFERTYP_MSBSEL | - SDHC_XFERTYP_BCEN | SDHC_XFERTYP_AC12EN; - -const uint32_t ACMD6_XFERTYP = SDHC_XFERTYP_CMDINX(ACMD6) | CMD_RESP_R1; - -const uint32_t ACMD41_XFERTYP = SDHC_XFERTYP_CMDINX(ACMD41) | CMD_RESP_R3; - -const uint32_t CMD0_XFERTYP = SDHC_XFERTYP_CMDINX(CMD0) | CMD_RESP_NONE; - -const uint32_t CMD2_XFERTYP = SDHC_XFERTYP_CMDINX(CMD2) | CMD_RESP_R2; - -const uint32_t CMD3_XFERTYP = SDHC_XFERTYP_CMDINX(CMD3) | CMD_RESP_R6; - -const uint32_t CMD6_XFERTYP = SDHC_XFERTYP_CMDINX(CMD6) | CMD_RESP_R1 | - DATA_READ_DMA; - -const uint32_t CMD7_XFERTYP = SDHC_XFERTYP_CMDINX(CMD7) | CMD_RESP_R1b; - -const uint32_t CMD8_XFERTYP = SDHC_XFERTYP_CMDINX(CMD8) | CMD_RESP_R7; - -const uint32_t CMD9_XFERTYP = SDHC_XFERTYP_CMDINX(CMD9) | CMD_RESP_R2; - -const uint32_t CMD10_XFERTYP = SDHC_XFERTYP_CMDINX(CMD10) | CMD_RESP_R2; - -const uint32_t CMD12_XFERTYP = SDHC_XFERTYP_CMDINX(CMD12) | CMD_RESP_R1b | - SDHC_XFERTYP_CMDTYP(3); - -const uint32_t CMD13_XFERTYP = SDHC_XFERTYP_CMDINX(CMD13) | CMD_RESP_R1; - -const uint32_t CMD17_DMA_XFERTYP = SDHC_XFERTYP_CMDINX(CMD17) | CMD_RESP_R1 | - DATA_READ_DMA; - -const uint32_t CMD18_DMA_XFERTYP = SDHC_XFERTYP_CMDINX(CMD18) | CMD_RESP_R1 | - DATA_READ_MULTI_DMA; - -const uint32_t CMD18_PGM_XFERTYP = SDHC_XFERTYP_CMDINX(CMD18) | CMD_RESP_R1 | - DATA_READ_MULTI_PGM; - -const uint32_t CMD24_DMA_XFERTYP = SDHC_XFERTYP_CMDINX(CMD24) | CMD_RESP_R1 | - DATA_WRITE_DMA; - -const uint32_t CMD25_DMA_XFERTYP = SDHC_XFERTYP_CMDINX(CMD25) | CMD_RESP_R1 | - DATA_WRITE_MULTI_DMA; - -const uint32_t CMD25_PGM_XFERTYP = SDHC_XFERTYP_CMDINX(CMD25) | CMD_RESP_R1 | - DATA_WRITE_MULTI_PGM; - -const uint32_t CMD32_XFERTYP = SDHC_XFERTYP_CMDINX(CMD32) | CMD_RESP_R1; - -const uint32_t CMD33_XFERTYP = SDHC_XFERTYP_CMDINX(CMD33) | CMD_RESP_R1; - -const uint32_t CMD38_XFERTYP = SDHC_XFERTYP_CMDINX(CMD38) | CMD_RESP_R1b; - -const uint32_t CMD55_XFERTYP = SDHC_XFERTYP_CMDINX(CMD55) | CMD_RESP_R1; - -//============================================================================= -static bool cardCommand(uint32_t xfertyp, uint32_t arg); -static void enableGPIO(bool enable); -static void enableDmaIrs(); -static void initSDHC(); -static bool isBusyCMD13(); -static bool isBusyCommandComplete(); -static bool isBusyCommandInhibit(); -static bool readReg16(uint32_t xfertyp, void* data); -static void setSdclk(uint32_t kHzMax); -static bool yieldTimeout(bool (*fcn)()); -static bool waitDmaStatus(); -static bool waitTimeout(bool (*fcn)()); -//----------------------------------------------------------------------------- -static bool (*m_busyFcn)() = 0; -static bool m_initDone = false; -static bool m_version2; -static bool m_highCapacity; -static uint8_t m_errorCode = SD_CARD_ERROR_INIT_NOT_CALLED; -static uint32_t m_errorLine = 0; -static uint32_t m_rca; -static volatile bool m_dmaBusy = false; -static volatile uint32_t m_irqstat; -static uint32_t m_sdClkKhz = 0; -static uint32_t m_ocr; -static cid_t m_cid; -static csd_t m_csd; -//============================================================================= -#define USE_DEBUG_MODE 0 -#if USE_DEBUG_MODE -#define DBG_IRQSTAT() if (SDHC_IRQSTAT) {Serial.print(__LINE__);\ - Serial.print(" IRQSTAT "); Serial.println(SDHC_IRQSTAT, HEX);} - -static void printRegs(uint32_t line) { - Serial.print(line); - Serial.print(" PRSSTAT "); - Serial.print(SDHC_PRSSTAT, HEX); - Serial.print(" PROCTL "); - Serial.print(SDHC_PROCTL, HEX); - Serial.print(" IRQSTAT "); - Serial.print(SDHC_IRQSTAT, HEX); - Serial.print(" m_irqstat "); - Serial.println(m_irqstat, HEX); -} -#else // USE_DEBUG_MODE -#define DBG_IRQSTAT() -#endif // USE_DEBUG_MODE -//============================================================================= -// Error function and macro. -#define sdError(code) setSdErrorCode(code, __LINE__) -inline bool setSdErrorCode(uint8_t code, uint32_t line) { - m_errorCode = code; - m_errorLine = line; - return false; // setSdErrorCode -} -//============================================================================= -// ISR -void sdhc_isr() { - SDHC_IRQSIGEN = 0; - m_irqstat = SDHC_IRQSTAT; - SDHC_IRQSTAT = m_irqstat; - m_dmaBusy = false; -} -//============================================================================= -// Static functions. -static bool cardAcmd(uint32_t rca, uint32_t xfertyp, uint32_t arg) { - return cardCommand(CMD55_XFERTYP, rca) && cardCommand (xfertyp, arg); -} -//----------------------------------------------------------------------------- -static bool cardCommand(uint32_t xfertyp, uint32_t arg) { - DBG_IRQSTAT(); - if (waitTimeout(isBusyCommandInhibit)) { - return false; // Caller will set errorCode. - } - SDHC_CMDARG = arg; - SDHC_XFERTYP = xfertyp; - if (waitTimeout(isBusyCommandComplete)) { - return false; // Caller will set errorCode. - } - m_irqstat = SDHC_IRQSTAT; - SDHC_IRQSTAT = m_irqstat; - - return (m_irqstat & SDHC_IRQSTAT_CC) && - !(m_irqstat & SDHC_IRQSTAT_CMD_ERROR); -} -//----------------------------------------------------------------------------- -static bool cardCMD6(uint32_t arg, uint8_t* status) { - // CMD6 returns 64 bytes. - if (waitTimeout(isBusyCMD13)) { - return sdError(SD_CARD_ERROR_CMD13); - } - enableDmaIrs(); - SDHC_DSADDR = (uint32_t)status; - SDHC_CMDARG = arg; - SDHC_BLKATTR = SDHC_BLKATTR_BLKCNT(1) | SDHC_BLKATTR_BLKSIZE(64); - SDHC_IRQSIGEN = SDHC_IRQSIGEN_MASK; - SDHC_XFERTYP = CMD6_XFERTYP; - - if (!waitDmaStatus()) { - return sdError(SD_CARD_ERROR_CMD6); - } - return true; -} -//----------------------------------------------------------------------------- -static void enableGPIO(bool enable) { - const uint32_t PORT_CLK = PORT_PCR_MUX(4) | PORT_PCR_DSE; - const uint32_t PORT_CMD_DATA = PORT_CLK | PORT_PCR_PS | PORT_PCR_PE; - - PORTE_PCR0 = enable ? PORT_CMD_DATA : 0; // SDHC_D1 - PORTE_PCR1 = enable ? PORT_CMD_DATA : 0; // SDHC_D0 - PORTE_PCR2 = enable ? PORT_CLK : 0; // SDHC_CLK - PORTE_PCR3 = enable ? PORT_CMD_DATA : 0; // SDHC_CMD - PORTE_PCR4 = enable ? PORT_CMD_DATA : 0; // SDHC_D3 - PORTE_PCR5 = enable ? PORT_CMD_DATA : 0; // SDHC_D2 -} -//----------------------------------------------------------------------------- -static void enableDmaIrs() { - m_dmaBusy = true; - m_irqstat = 0; -} -//----------------------------------------------------------------------------- -static void initSDHC() { -#ifdef HAS_KINETIS_MPU - // Allow SDHC Bus Master access. - MPU_RGDAAC0 |= 0x0C000000; -#endif - // Enable SDHC clock. - SIM_SCGC3 |= SIM_SCGC3_SDHC; - - // Disable GPIO clock. - enableGPIO(false); - - // Reset SDHC. Use default Water Mark Level of 16. - SDHC_SYSCTL = SDHC_SYSCTL_RSTA; - while (SDHC_SYSCTL & SDHC_SYSCTL_RSTA) { - } - // Set initial SCK rate. - setSdclk(400); - - enableGPIO(true); - - // Enable desired IRQSTAT bits. - SDHC_IRQSTATEN = SDHC_IRQSTATEN_MASK; - - NVIC_SET_PRIORITY(IRQ_SDHC, 6*16); - NVIC_ENABLE_IRQ(IRQ_SDHC); - - // Send 80 clocks to card. - SDHC_SYSCTL |= SDHC_SYSCTL_INITA; - while (SDHC_SYSCTL & SDHC_SYSCTL_INITA) { - } -} -//----------------------------------------------------------------------------- -static bool isBusyCMD13() { - if (!cardCommand(CMD13_XFERTYP, m_rca)) { - // Caller will timeout. - return true; - } - return !(SDHC_CMDRSP0 & CARD_STATUS_READY_FOR_DATA); -} -//----------------------------------------------------------------------------- -static bool isBusyCommandComplete() { - return !(SDHC_IRQSTAT &(SDHC_IRQSTAT_CC | SDHC_IRQSTAT_CMD_ERROR)); -} -//----------------------------------------------------------------------------- -static bool isBusyCommandInhibit() { - return SDHC_PRSSTAT & SDHC_PRSSTAT_CIHB; -} -//----------------------------------------------------------------------------- -static bool isBusyDMA() { - return m_dmaBusy; -} -//----------------------------------------------------------------------------- -static bool isBusyFifoRead() { - return !(SDHC_PRSSTAT & SDHC_PRSSTAT_BREN); -} -//----------------------------------------------------------------------------- -static bool isBusyFifoWrite() { - return !(SDHC_PRSSTAT & SDHC_PRSSTAT_BWEN); -} -//----------------------------------------------------------------------------- -static bool isBusyTransferComplete() { - return !(SDHC_IRQSTAT & (SDHC_IRQSTAT_TC | SDHC_IRQSTAT_ERROR)); -} -//----------------------------------------------------------------------------- -static bool rdWrBlocks(uint32_t xfertyp, - uint32_t lba, uint8_t* buf, size_t n) { - if ((3 & (uint32_t)buf) || n == 0) { - return sdError(SD_CARD_ERROR_DMA); - } - if (yieldTimeout(isBusyCMD13)) { - return sdError(SD_CARD_ERROR_CMD13); - } - enableDmaIrs(); - SDHC_DSADDR = (uint32_t)buf; - SDHC_CMDARG = m_highCapacity ? lba : 512*lba; - SDHC_BLKATTR = SDHC_BLKATTR_BLKCNT(n) | SDHC_BLKATTR_BLKSIZE(512); - SDHC_IRQSIGEN = SDHC_IRQSIGEN_MASK; - SDHC_XFERTYP = xfertyp; - - return waitDmaStatus(); -} -//----------------------------------------------------------------------------- -// Read 16 byte CID or CSD register. -static bool readReg16(uint32_t xfertyp, void* data) { - uint8_t* d = reinterpret_cast(data); - if (!cardCommand(xfertyp, m_rca)) { - return false; // Caller will set errorCode. - } - uint32_t sr[] = {SDHC_CMDRSP0, SDHC_CMDRSP1, SDHC_CMDRSP2, SDHC_CMDRSP3}; - for (int i = 0; i < 15; i++) { - d[14 - i] = sr[i/4] >> 8*(i%4); - } - d[15] = 0; - return true; -} -//----------------------------------------------------------------------------- -static void setSdclk(uint32_t kHzMax) { - const uint32_t DVS_LIMIT = 0X10; - const uint32_t SDCLKFS_LIMIT = 0X100; - uint32_t dvs = 1; - uint32_t sdclkfs = 1; - uint32_t maxSdclk = 1000*kHzMax; - - while ((F_CPU/(sdclkfs*DVS_LIMIT) > maxSdclk) && (sdclkfs < SDCLKFS_LIMIT)) { - sdclkfs <<= 1; - } - while ((F_CPU/(sdclkfs*dvs) > maxSdclk) && (dvs < DVS_LIMIT)) { - dvs++; - } - m_sdClkKhz = F_CPU/(1000*sdclkfs*dvs); - sdclkfs >>= 1; - dvs--; - - // Disable SDHC clock. - SDHC_SYSCTL &= ~SDHC_SYSCTL_SDCLKEN; - - // Change dividers. - uint32_t sysctl = SDHC_SYSCTL & ~(SDHC_SYSCTL_DTOCV_MASK - | SDHC_SYSCTL_DVS_MASK | SDHC_SYSCTL_SDCLKFS_MASK); - - SDHC_SYSCTL = sysctl | SDHC_SYSCTL_DTOCV(0x0E) | SDHC_SYSCTL_DVS(dvs) - | SDHC_SYSCTL_SDCLKFS(sdclkfs); - - // Wait until the SDHC clock is stable. - while (!(SDHC_PRSSTAT & SDHC_PRSSTAT_SDSTB)) { - } - // Enable the SDHC clock. - SDHC_SYSCTL |= SDHC_SYSCTL_SDCLKEN; -} -//----------------------------------------------------------------------------- -static bool transferStop() { - DBG_IRQSTAT(); - - if (!cardCommand(CMD12_XFERTYP, 0)) { - return sdError(SD_CARD_ERROR_CMD12); - } - if (yieldTimeout(isBusyCMD13)) { - return sdError(SD_CARD_ERROR_CMD13); - } - // Save registers before reset DAT lines. - uint32_t irqsststen = SDHC_IRQSTATEN; - uint32_t proctl = SDHC_PROCTL & ~SDHC_PROCTL_SABGREQ; - - // Do reset to clear CDIHB. Should be a better way! - SDHC_SYSCTL |= SDHC_SYSCTL_RSTD; - - // Restore registers. - SDHC_IRQSTATEN = irqsststen; - SDHC_PROCTL = proctl; - - return true; -} -//----------------------------------------------------------------------------- -// Return true if timeout occurs. -static bool yieldTimeout(bool (*fcn)()) { - m_busyFcn = fcn; - uint32_t m = micros(); - while (fcn()) { - if ((micros() - m) > BUSY_TIMEOUT_MICROS) { - m_busyFcn = 0; - return true; - } - yield(); - } - m_busyFcn = 0; - return false; // Caller will set errorCode. -} -//----------------------------------------------------------------------------- -static bool waitDmaStatus() { - if (yieldTimeout(isBusyDMA)) { - return false; // Caller will set errorCode. - } - return (m_irqstat & SDHC_IRQSTAT_TC) && !(m_irqstat & SDHC_IRQSTAT_ERROR); -} -//----------------------------------------------------------------------------- -// Return true if timeout occurs. -static bool waitTimeout(bool (*fcn)()) { - uint32_t m = micros(); - while (fcn()) { - if ((micros() - m) > BUSY_TIMEOUT_MICROS) { - return true; - } - } - return false; // Caller will set errorCode. -} -//============================================================================= -bool SdioCard::begin() { - uint32_t kHzSdClk; - uint32_t arg; - m_initDone = false; - m_errorCode = SD_CARD_ERROR_NONE; - m_highCapacity = false; - m_version2 = false; - - // initialize controller. - initSDHC(); - - if (!cardCommand(CMD0_XFERTYP, 0)) { - return sdError(SD_CARD_ERROR_CMD0); - } - // Try several times for case of reset delay. - for (uint32_t i = 0; i < CMD8_RETRIES; i++) { - if (cardCommand(CMD8_XFERTYP, 0X1AA)) { - if (SDHC_CMDRSP0 != 0X1AA) { - return sdError(SD_CARD_ERROR_CMD8); - } - m_version2 = true; - break; - } - } - arg = m_version2 ? 0X40300000 : 0x00300000; - uint32_t m = micros(); - do { - if (!cardAcmd(0, ACMD41_XFERTYP, arg) || - ((micros() - m) > BUSY_TIMEOUT_MICROS)) { - return sdError(SD_CARD_ERROR_ACMD41); - } - } while ((SDHC_CMDRSP0 & 0x80000000) == 0); - - m_ocr = SDHC_CMDRSP0; - if (SDHC_CMDRSP0 & 0x40000000) { - // Is high capacity. - m_highCapacity = true; - } - if (!cardCommand(CMD2_XFERTYP, 0)) { - return sdError(SD_CARD_ERROR_CMD2); - } - if (!cardCommand(CMD3_XFERTYP, 0)) { - return sdError(SD_CARD_ERROR_CMD3); - } - m_rca = SDHC_CMDRSP0 & 0xFFFF0000; - - if (!readReg16(CMD9_XFERTYP, &m_csd)) { - return sdError(SD_CARD_ERROR_CMD9); - } - if (!readReg16(CMD10_XFERTYP, &m_cid)) { - return sdError(SD_CARD_ERROR_CMD10); - } - if (!cardCommand(CMD7_XFERTYP, m_rca)) { - return sdError(SD_CARD_ERROR_CMD7); - } - // Set card to bus width four. - if (!cardAcmd(m_rca, ACMD6_XFERTYP, 2)) { - return sdError(SD_CARD_ERROR_ACMD6); - } - // Set SDHC to bus width four. - SDHC_PROCTL &= ~SDHC_PROCTL_DTW_MASK; - SDHC_PROCTL |= SDHC_PROCTL_DTW(SDHC_PROCTL_DTW_4BIT); - - SDHC_WML = SDHC_WML_RDWML(FIFO_WML) | SDHC_WML_WRWML(FIFO_WML); - - // Determine if High Speed mode is supported and set frequency. - uint8_t status[64]; - if (cardCMD6(0X00FFFFFF, status) && (2 & status[13]) && - cardCMD6(0X80FFFFF1, status) && (status[16] & 0XF) == 1) { - kHzSdClk = 50000; - } else { - kHzSdClk = 25000; - } - // disable GPIO - enableGPIO(false); - - // Set the SDHC SCK frequency. - setSdclk(kHzSdClk); - - // enable GPIO - enableGPIO(true); - m_initDone = true; - return true; -} -//----------------------------------------------------------------------------- -uint32_t SdioCard::cardSize() { - return sdCardCapacity(&m_csd); -} -//----------------------------------------------------------------------------- -bool SdioCard::erase(uint32_t firstBlock, uint32_t lastBlock) { - // check for single block erase - if (!m_csd.v1.erase_blk_en) { - // erase size mask - uint8_t m = (m_csd.v1.sector_size_high << 1) | m_csd.v1.sector_size_low; - if ((firstBlock & m) != 0 || ((lastBlock + 1) & m) != 0) { - // error card can't erase specified area - return sdError(SD_CARD_ERROR_ERASE_SINGLE_BLOCK); - } - } - if (!m_highCapacity) { - firstBlock <<= 9; - lastBlock <<= 9; - } - if (!cardCommand(CMD32_XFERTYP, firstBlock)) { - return sdError(SD_CARD_ERROR_CMD32); - } - if (!cardCommand(CMD33_XFERTYP, lastBlock)) { - return sdError(SD_CARD_ERROR_CMD33); - } - if (!cardCommand(CMD38_XFERTYP, 0)) { - return sdError(SD_CARD_ERROR_CMD38); - } - if (waitTimeout(isBusyCMD13)) { - return sdError(SD_CARD_ERROR_ERASE_TIMEOUT); - } - return true; -} -//----------------------------------------------------------------------------- -uint8_t SdioCard::errorCode() { - return m_errorCode; -} -//----------------------------------------------------------------------------- -uint32_t SdioCard::errorData() { - return m_irqstat; -} -//----------------------------------------------------------------------------- -uint32_t SdioCard::errorLine() { - return m_errorLine; -} -//----------------------------------------------------------------------------- -bool SdioCard::isBusy() { - return m_busyFcn ? m_busyFcn() : m_initDone && isBusyCMD13(); -} -//----------------------------------------------------------------------------- -uint32_t SdioCard::kHzSdClk() { - return m_sdClkKhz; -} -//----------------------------------------------------------------------------- -bool SdioCard::readBlock(uint32_t lba, uint8_t* buf) { - uint8_t aligned[512]; - - uint8_t* ptr = (uint32_t)buf & 3 ? aligned : buf; - - if (!rdWrBlocks(CMD17_DMA_XFERTYP, lba, ptr, 1)) { - return sdError(SD_CARD_ERROR_CMD18); - } - if (ptr != buf) { - memcpy(buf, aligned, 512); - } - return true; -} -//----------------------------------------------------------------------------- -bool SdioCard::readBlocks(uint32_t lba, uint8_t* buf, size_t n) { - if ((uint32_t)buf & 3) { - for (size_t i = 0; i < n; i++, lba++, buf += 512) { - if (!readBlock(lba, buf)) { - return false; // readBlock will set errorCode. - } - } - return true; - } - if (!rdWrBlocks(CMD18_DMA_XFERTYP, lba, buf, n)) { - return sdError(SD_CARD_ERROR_CMD18); - } - return true; -} -//----------------------------------------------------------------------------- -bool SdioCard::readCID(void* cid) { - memcpy(cid, &m_cid, 16); - return true; -} -//----------------------------------------------------------------------------- -bool SdioCard::readCSD(void* csd) { - memcpy(csd, &m_csd, 16); - return true; -} -//----------------------------------------------------------------------------- -bool SdioCard::readData(uint8_t *dst) { - DBG_IRQSTAT(); - uint32_t *p32 = reinterpret_cast(dst); - - if (!(SDHC_PRSSTAT & SDHC_PRSSTAT_RTA)) { - SDHC_PROCTL &= ~SDHC_PROCTL_SABGREQ; - if ((SDHC_BLKATTR & 0XFFFF0000) == 0X10000) { - // Don't stop at block gap if last block. Allows auto CMD12. - SDHC_PROCTL |= SDHC_PROCTL_CREQ; - } else { - noInterrupts(); - SDHC_PROCTL |= SDHC_PROCTL_CREQ; - SDHC_PROCTL |= SDHC_PROCTL_SABGREQ; - interrupts(); - } - } - if (waitTimeout(isBusyFifoRead)) { - return sdError(SD_CARD_ERROR_READ_FIFO); - } - for (uint32_t iw = 0 ; iw < 512/(4*FIFO_WML); iw++) { - while (0 == (SDHC_PRSSTAT & SDHC_PRSSTAT_BREN)) { - } - for (uint32_t i = 0; i < FIFO_WML; i++) { - p32[i] = SDHC_DATPORT; - } - p32 += FIFO_WML; - } - if (waitTimeout(isBusyTransferComplete)) { - return sdError(SD_CARD_ERROR_READ_TIMEOUT); - } - m_irqstat = SDHC_IRQSTAT; - SDHC_IRQSTAT = m_irqstat; - return (m_irqstat & SDHC_IRQSTAT_TC) && !(m_irqstat & SDHC_IRQSTAT_ERROR); -} -//----------------------------------------------------------------------------- -bool SdioCard::readOCR(uint32_t* ocr) { - *ocr = m_ocr; - return true; -} -//----------------------------------------------------------------------------- -bool SdioCard::readStart(uint32_t lba) { - // K66/K65 Errata - SDHC: Does not support Infinite Block Transfer Mode. - return sdError(SD_CARD_ERROR_FUNCTION_NOT_SUPPORTED); -} -//----------------------------------------------------------------------------- -// SDHC will do Auto CMD12 after count blocks. -bool SdioCard::readStart(uint32_t lba, uint32_t count) { - DBG_IRQSTAT(); - if (count > 0XFFFF) { - return sdError(SD_CARD_ERROR_READ_START); - } - if (yieldTimeout(isBusyCMD13)) { - return sdError(SD_CARD_ERROR_CMD13); - } - if (count > 1) { - SDHC_PROCTL |= SDHC_PROCTL_SABGREQ; - } - SDHC_BLKATTR = SDHC_BLKATTR_BLKCNT(count) | SDHC_BLKATTR_BLKSIZE(512); - if (!cardCommand(CMD18_PGM_XFERTYP, m_highCapacity ? lba : 512*lba)) { - return sdError(SD_CARD_ERROR_CMD18); - } - return true; -} -//----------------------------------------------------------------------------- -bool SdioCard::readStop() { - return transferStop(); -} -//----------------------------------------------------------------------------- -bool SdioCard::syncBlocks() { - return true; -} -//----------------------------------------------------------------------------- -uint8_t SdioCard::type() { - return m_version2 ? m_highCapacity ? - SD_CARD_TYPE_SDHC : SD_CARD_TYPE_SD2 : SD_CARD_TYPE_SD1; -} -//----------------------------------------------------------------------------- -bool SdioCard::writeBlock(uint32_t lba, const uint8_t* buf) { - uint8_t *ptr; - uint8_t aligned[512]; - if (3 & (uint32_t)buf) { - ptr = aligned; - memcpy(aligned, buf, 512); - } else { - ptr = const_cast(buf); - } - if (!rdWrBlocks(CMD24_DMA_XFERTYP, lba, ptr, 1)) { - return sdError(SD_CARD_ERROR_CMD24); - } - return true; -} -//----------------------------------------------------------------------------- -bool SdioCard::writeBlocks(uint32_t lba, const uint8_t* buf, size_t n) { - uint8_t* ptr = const_cast(buf); - if (3 & (uint32_t)ptr) { - for (size_t i = 0; i < n; i++, lba++, ptr += 512) { - if (!writeBlock(lba, ptr)) { - return false; // writeBlock will set errorCode. - } - } - return true; - } - if (!rdWrBlocks(CMD25_DMA_XFERTYP, lba, ptr, n)) { - return sdError(SD_CARD_ERROR_CMD25); - } - return true; -} -//----------------------------------------------------------------------------- -bool SdioCard::writeData(const uint8_t* src) { - DBG_IRQSTAT(); - const uint32_t* p32 = reinterpret_cast(src); - - if (!(SDHC_PRSSTAT & SDHC_PRSSTAT_WTA)) { - SDHC_PROCTL &= ~SDHC_PROCTL_SABGREQ; - // Don't stop at block gap if last block. Allows auto CMD12. - if ((SDHC_BLKATTR & 0XFFFF0000) == 0X10000) { - SDHC_PROCTL |= SDHC_PROCTL_CREQ; - } else { - SDHC_PROCTL |= SDHC_PROCTL_CREQ; - SDHC_PROCTL |= SDHC_PROCTL_SABGREQ; - } - } - if (waitTimeout(isBusyFifoWrite)) { - return sdError(SD_CARD_ERROR_WRITE_FIFO); - } - for (uint32_t iw = 0 ; iw < 512/(4*FIFO_WML); iw++) { - while (0 == (SDHC_PRSSTAT & SDHC_PRSSTAT_BWEN)) { - } - for (uint32_t i = 0; i < FIFO_WML; i++) { - SDHC_DATPORT = p32[i]; - } - p32 += FIFO_WML; - } - if (waitTimeout(isBusyTransferComplete)) { - return sdError(SD_CARD_ERROR_WRITE_TIMEOUT); - } - m_irqstat = SDHC_IRQSTAT; - SDHC_IRQSTAT = m_irqstat; - return (m_irqstat & SDHC_IRQSTAT_TC) && !(m_irqstat & SDHC_IRQSTAT_ERROR); -} -//----------------------------------------------------------------------------- -bool SdioCard::writeStart(uint32_t lba) { - // K66/K65 Errata - SDHC: Does not support Infinite Block Transfer Mode. - return sdError(SD_CARD_ERROR_FUNCTION_NOT_SUPPORTED); -} -//----------------------------------------------------------------------------- -// SDHC will do Auto CMD12 after count blocks. -bool SdioCard::writeStart(uint32_t lba, uint32_t count) { - if (count > 0XFFFF) { - return sdError(SD_CARD_ERROR_WRITE_START); - } - DBG_IRQSTAT(); - if (yieldTimeout(isBusyCMD13)) { - return sdError(SD_CARD_ERROR_CMD13); - } - if (count > 1) { - SDHC_PROCTL |= SDHC_PROCTL_SABGREQ; - } - SDHC_BLKATTR = SDHC_BLKATTR_BLKCNT(count) | SDHC_BLKATTR_BLKSIZE(512); - - if (!cardCommand(CMD25_PGM_XFERTYP, m_highCapacity ? lba : 512*lba)) { - return sdError(SD_CARD_ERROR_CMD25); - } - return true; -} -//----------------------------------------------------------------------------- -bool SdioCard::writeStop() { - return transferStop(); -} -#endif // defined(__MK64FX512__) || defined(__MK66FX1M0__) diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdFat.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdFat.h deleted file mode 100644 index 3cdc970..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdFat.h +++ /dev/null @@ -1,512 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 SdFat_h -#define SdFat_h -/** - * \file - * \brief SdFat class - */ -#include "SysCall.h" -#include "BlockDriver.h" -#include "FatLib/FatLib.h" -#include "SdCard/SdioCard.h" -#if INCLUDE_SDIOS -#include "sdios.h" -#endif // INCLUDE_SDIOS -//------------------------------------------------------------------------------ -/** SdFat version */ -#define SD_FAT_VERSION "1.0.15" -//============================================================================== -/** - * \class SdBaseFile - * \brief Class for backward compatibility. - */ -class SdBaseFile : public FatFile { - public: - SdBaseFile() {} - /** Create a file object and open it in the current working directory. - * - * \param[in] path A path for a file to be opened. - * - * \param[in] oflag Values for \a oflag are constructed by a - * bitwise-inclusive OR of open flags. see - * FatFile::open(FatFile*, const char*, oflag_t). - */ - SdBaseFile(const char* path, oflag_t oflag) : FatFile(path, oflag) {} -}; -//----------------------------------------------------------------------------- -#if ENABLE_ARDUINO_FEATURES -/** - * \class SdFile - * \brief Class for backward compatibility. - */ -class SdFile : public PrintFile { - public: - SdFile() {} - /** Create a file object and open it in the current working directory. - * - * \param[in] path A path for a file to be opened. - * - * \param[in] oflag Values for \a oflag are constructed by a - * bitwise-inclusive OR of open flags. see - * FatFile::open(FatFile*, const char*, oflag_t). - */ - SdFile(const char* path, oflag_t oflag) : PrintFile(path, oflag) {} -}; -#endif // #if ENABLE_ARDUINO_FEATURES -//----------------------------------------------------------------------------- -/** - * \class SdFileSystem - * \brief Virtual base class for %SdFat library. - */ -template -class SdFileSystem : public FatFileSystem { - public: - /** Initialize file system. - * \return true for success else false. - */ - bool begin() { - return FatFileSystem::begin(&m_card); - } - /** \return Pointer to SD card object */ - SdDriverClass *card() { - m_card.syncBlocks(); - return &m_card; - } - /** %Print any SD error code to Serial and halt. */ - void errorHalt() { - errorHalt(&Serial); - } - /** %Print any SD error code and halt. - * - * \param[in] pr Print destination. - */ - void errorHalt(Print* pr) { - errorPrint(pr); - SysCall::halt(); - } - /** %Print msg, any SD error code and halt. - * - * \param[in] msg Message to print. - */ - void errorHalt(char const* msg) { - errorHalt(&Serial, msg); - } - /** %Print msg, any SD error code, and halt. - * - * \param[in] pr Print destination. - * \param[in] msg Message to print. - */ - void errorHalt(Print* pr, char const* msg) { - errorPrint(pr, msg); - SysCall::halt(); - } - /** %Print any SD error code to Serial */ - void errorPrint() { - errorPrint(&Serial); - } - /** %Print any SD error code. - * \param[in] pr Print device. - */ - void errorPrint(Print* pr) { - if (!cardErrorCode()) { - return; - } - pr->print(F("SD errorCode: 0X")); - pr->print(cardErrorCode(), HEX); - pr->print(F(",0X")); - pr->println(cardErrorData(), HEX); - } - /** %Print msg, any SD error code. - * - * \param[in] msg Message to print. - */ - void errorPrint(const char* msg) { - errorPrint(&Serial, msg); - } - /** %Print msg, any SD error code. - * - * \param[in] pr Print destination. - * \param[in] msg Message to print. - */ - void errorPrint(Print* pr, char const* msg) { - pr->print(F("error: ")); - pr->println(msg); - errorPrint(pr); - } - /** %Print any SD error code and halt. */ - void initErrorHalt() { - initErrorHalt(&Serial); - } - /** %Print error details and halt after begin fails. - * - * \param[in] pr Print destination. - */ - void initErrorHalt(Print* pr) { - initErrorPrint(pr); - SysCall::halt(); - } - /**Print message, error details, and halt after begin() fails. - * - * \param[in] msg Message to print. - */ - void initErrorHalt(char const *msg) { - initErrorHalt(&Serial, msg); - } - /**Print message, error details, and halt after begin() fails. - * \param[in] pr Print device. - * \param[in] msg Message to print. - */ - void initErrorHalt(Print* pr, char const *msg) { - pr->println(msg); - initErrorHalt(pr); - } - - /** Print error details after begin() fails. */ - void initErrorPrint() { - initErrorPrint(&Serial); - } - /** Print error details after begin() fails. - * - * \param[in] pr Print destination. - */ - void initErrorPrint(Print* pr) { - if (cardErrorCode()) { - pr->println(F("Can't access SD card. Do not reformat.")); - if (cardErrorCode() == SD_CARD_ERROR_CMD0) { - pr->println(F("No card, wrong chip select pin, or SPI problem?")); - } - errorPrint(pr); - } else if (vol()->fatType() == 0) { - pr->println(F("Invalid format, reformat SD.")); - } else if (!vwd()->isOpen()) { - pr->println(F("Can't open root directory.")); - } else { - pr->println(F("No error found.")); - } - } - /**Print message and error details and halt after begin() fails. - * - * \param[in] msg Message to print. - */ - void initErrorPrint(char const *msg) { - initErrorPrint(&Serial, msg); - } - /**Print message and error details and halt after begin() fails. - * - * \param[in] pr Print destination. - * \param[in] msg Message to print. - */ - void initErrorPrint(Print* pr, char const *msg) { - pr->println(msg); - initErrorPrint(pr); - } -#if defined(ARDUINO) || defined(DOXYGEN) - /** %Print msg, any SD error code, and halt. - * - * \param[in] msg Message to print. - */ - void errorHalt(const __FlashStringHelper* msg) { - errorHalt(&Serial, msg); - } - /** %Print msg, any SD error code, and halt. - * - * \param[in] pr Print destination. - * \param[in] msg Message to print. - */ - void errorHalt(Print* pr, const __FlashStringHelper* msg) { - errorPrint(pr, msg); - SysCall::halt(); - } - - /** %Print msg, any SD error code. - * - * \param[in] msg Message to print. - */ - void errorPrint(const __FlashStringHelper* msg) { - errorPrint(&Serial, msg); - } - /** %Print msg, any SD error code. - * - * \param[in] pr Print destination. - * \param[in] msg Message to print. - */ - void errorPrint(Print* pr, const __FlashStringHelper* msg) { - pr->print(F("error: ")); - pr->println(msg); - errorPrint(pr); - } - /**Print message, error details, and halt after begin() fails. - * - * \param[in] msg Message to print. - */ - void initErrorHalt(const __FlashStringHelper* msg) { - initErrorHalt(&Serial, msg); - } - /**Print message, error details, and halt after begin() fails. - * \param[in] pr Print device for message. - * \param[in] msg Message to print. - */ - void initErrorHalt(Print* pr, const __FlashStringHelper* msg) { - pr->println(msg); - initErrorHalt(pr); - } - /**Print message and error details and halt after begin() fails. - * - * \param[in] msg Message to print. - */ - void initErrorPrint(const __FlashStringHelper* msg) { - initErrorPrint(&Serial, msg); - } - /**Print message and error details and halt after begin() fails. - * - * \param[in] pr Print destination. - * \param[in] msg Message to print. - */ - void initErrorPrint(Print* pr, const __FlashStringHelper* msg) { - pr->println(msg); - initErrorPrint(pr); - } -#endif // defined(ARDUINO) || defined(DOXYGEN) - /** \return The card error code */ - uint8_t cardErrorCode() { - return m_card.errorCode(); - } - /** \return the card error data */ - uint32_t cardErrorData() { - return m_card.errorData(); - } - - protected: - SdDriverClass m_card; -}; -//============================================================================== -/** - * \class SdFat - * \brief Main file system class for %SdFat library. - */ -class SdFat : public SdFileSystem { - public: -#if IMPLEMENT_SPI_PORT_SELECTION || defined(DOXYGEN) - SdFat() { - m_spi.setPort(nullptr); - } - /** Constructor with SPI port selection. - * \param[in] spiPort SPI port number. - */ - explicit SdFat(SPIClass* spiPort) { - m_spi.setPort(spiPort); - } -#endif // IMPLEMENT_SPI_PORT_SELECTION - /** Initialize SD card and file system. - * - * \param[in] csPin SD card chip select pin. - * \param[in] spiSettings SPI speed, mode, and bit order. - * \return true for success else false. - */ - bool begin(uint8_t csPin = SS, SPISettings spiSettings = SPI_FULL_SPEED) { - return m_card.begin(&m_spi, csPin, spiSettings) && - SdFileSystem::begin(); - } - /** Initialize SD card for diagnostic use only. - * - * \param[in] csPin SD card chip select pin. - * \param[in] settings SPI speed, mode, and bit order. - * \return true for success else false. - */ - bool cardBegin(uint8_t csPin = SS, SPISettings settings = SPI_FULL_SPEED) { - return m_card.begin(&m_spi, csPin, settings); - } - /** Initialize file system for diagnostic use only. - * \return true for success else false. - */ - bool fsBegin() { - return FatFileSystem::begin(card()); - } - - private: - SdFatSpiDriver m_spi; -}; -//============================================================================== -#if ENABLE_SDIO_CLASS || defined(DOXYGEN) -/** - * \class SdFatSdio - * \brief SdFat class using SDIO. - */ -class SdFatSdio : public SdFileSystem { - public: - /** Initialize SD card and file system. - * \return true for success else false. - */ - bool begin() { - return m_card.begin() && SdFileSystem::begin(); - } - /** Initialize SD card for diagnostic use only. - * - * \return true for success else false. - */ - bool cardBegin() { - return m_card.begin(); - } - /** Initialize file system for diagnostic use only. - * \return true for success else false. - */ - bool fsBegin() { - return SdFileSystem::begin(); - } -}; -#if ENABLE_SDIOEX_CLASS || defined(DOXYGEN) -//----------------------------------------------------------------------------- -/** - * \class SdFatSdioEX - * \brief SdFat class using SDIO. - */ -class SdFatSdioEX : public SdFileSystem { - public: - /** Initialize SD card and file system. - * \return true for success else false. - */ - bool begin() { - return m_card.begin() && SdFileSystem::begin(); - } - /** \return Pointer to SD card object */ - SdioCardEX* card() { - return &m_card; - } - /** Initialize SD card for diagnostic use only. - * - * \return true for success else false. - */ - bool cardBegin() { - return m_card.begin(); - } - /** Initialize file system for diagnostic use only. - * \return true for success else false. - */ - bool fsBegin() { - return SdFileSystem::begin(); - } -}; -#endif // ENABLE_SDIOEX_CLASS || defined(DOXYGEN) -#endif // ENABLE_SDIO_CLASS || defined(DOXYGEN) -//============================================================================= -#if ENABLE_SOFTWARE_SPI_CLASS || defined(DOXYGEN) -/** - * \class SdFatSoftSpi - * \brief SdFat class using software SPI. - */ -template -class SdFatSoftSpi : public SdFileSystem { - public: - /** Initialize SD card and file system. - * - * \param[in] csPin SD card chip select pin. - * \param[in] spiSettings ignored for software SPI.. - * \return true for success else false. - */ - bool begin(uint8_t csPin = SS, SPISettings spiSettings = SPI_FULL_SPEED) { - return m_card.begin(&m_spi, csPin, spiSettings) && - SdFileSystem::begin(); - } - private: - SdSpiSoftDriver m_spi; -}; -#endif // #if ENABLE_SOFTWARE_SPI_CLASS || defined(DOXYGEN) -//============================================================================== -#if ENABLE_EXTENDED_TRANSFER_CLASS || defined(DOXYGEN) -/** - * \class SdFatEX - * \brief SdFat class with extended SD I/O. - */ -class SdFatEX : public SdFileSystem { - public: -#if IMPLEMENT_SPI_PORT_SELECTION || defined(DOXYGEN) - SdFatEX() { - m_spi.setPort(nullptr); - } - /** Constructor with SPI port selection. - * \param[in] spiPort SPI port number. - */ - explicit SdFatEX(SPIClass* spiPort) { - m_spi.setPort(spiPort); - } -#endif // IMPLEMENT_SPI_PORT_SELECTION - /** Initialize SD card and file system. - * - * \param[in] csPin SD card chip select pin. - * \param[in] spiSettings SPI speed, mode, and bit order. - * \return true for success else false. - */ - bool begin(uint8_t csPin = SS, SPISettings spiSettings = SPI_FULL_SPEED) { - return m_card.begin(&m_spi, csPin, spiSettings) && - SdFileSystem::begin(); - } - - private: - SdFatSpiDriver m_spi; -}; -//============================================================================== -#if ENABLE_SOFTWARE_SPI_CLASS || defined(DOXYGEN) -/** - * \class SdFatSoftSpiEX - * \brief SdFat class using software SPI and extended SD I/O. - */ -template -class SdFatSoftSpiEX : public SdFileSystem { - public: - /** Initialize SD card and file system. - * - * \param[in] csPin SD card chip select pin. - * \param[in] spiSettings ignored for software SPI. - * \return true for success else false. - */ - bool begin(uint8_t csPin = SS, SPISettings spiSettings = SPI_FULL_SPEED) { - return m_card.begin(&m_spi, csPin, spiSettings) && - SdFileSystem::begin(); - } - private: - SdSpiSoftDriver m_spi; -}; -#endif // #if ENABLE_SOFTWARE_SPI_CLASS || defined(DOXYGEN) -#endif // ENABLE_EXTENDED_TRANSFER_CLASS || defined(DOXYGEN) -//============================================================================= -/** - * \class Sd2Card - * \brief Raw access to SD and SDHC card using default SPI library. - */ -class Sd2Card : public SdSpiCard { - public: - /** Initialize the SD card. - * \param[in] csPin SD chip select pin. - * \param[in] settings SPI speed, mode, and bit order. - * \return true for success else false. - */ - bool begin(uint8_t csPin = SS, SPISettings settings = SD_SCK_MHZ(50)) { - return SdSpiCard::begin(&m_spi, csPin, settings); - } - private: - SdFatSpiDriver m_spi; -}; -#endif // SdFat_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdFatConfig.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdFatConfig.h deleted file mode 100644 index c0d1ade..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SdFatConfig.h +++ /dev/null @@ -1,233 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -/** - * \file - * \brief configuration definitions - */ -#ifndef SdFatConfig_h -#define SdFatConfig_h -#include -#include -#ifdef __AVR__ -#include -#endif // __AVR__ -//------------------------------------------------------------------------------ -/** - * Set INCLUDE_SDIOS nonzero to include sdios.h in SdFat.h. - * sdios.h provides C++ style IO Streams. - */ -#define INCLUDE_SDIOS 1 -//------------------------------------------------------------------------------ -/** - * Set USE_LONG_FILE_NAMES nonzero to use long file names (LFN). - * Long File Name are limited to a maximum length of 255 characters. - * - * This implementation allows 7-bit characters in the range - * 0X20 to 0X7E except the following characters are not allowed: - * - * < (less than) - * > (greater than) - * : (colon) - * " (double quote) - * / (forward slash) - * \ (backslash) - * | (vertical bar or pipe) - * ? (question mark) - * * (asterisk) - * - */ -#define USE_LONG_FILE_NAMES 1 -//------------------------------------------------------------------------------ -/** - * If the symbol ENABLE_EXTENDED_TRANSFER_CLASS is nonzero, the class SdFatEX - * will be defined. If the symbol ENABLE_SOFTWARE_SPI_CLASS is also nonzero, - * the class SdFatSoftSpiEX will be defined. - * - * These classes used extended multi-block SD I/O for better performance. - * the SPI bus may not be shared with other devices in this mode. - */ -#define ENABLE_EXTENDED_TRANSFER_CLASS 0 -//------------------------------------------------------------------------------ -/** - * If the symbol USE_STANDARD_SPI_LIBRARY is zero, an optimized custom SPI - * driver is used if it exists. If the symbol USE_STANDARD_SPI_LIBRARY is - * one, the standard Arduino SPI.h library is used with SPI. If the symbol - * USE_STANDARD_SPI_LIBRARY is two, the SPI port can be selected with the - * constructors SdFat(SPIClass* spiPort) and SdFatEX(SPIClass* spiPort). - */ -#define USE_STANDARD_SPI_LIBRARY 0 -//------------------------------------------------------------------------------ -/** - * If the symbol ENABLE_SOFTWARE_SPI_CLASS is nonzero, the class SdFatSoftSpi - * will be defined. If ENABLE_EXTENDED_TRANSFER_CLASS is also nonzero, - * the class SdFatSoftSpiEX will be defined. - */ -#define ENABLE_SOFTWARE_SPI_CLASS 0 -//------------------------------------------------------------------------------ -/** If the symbol USE_FCNTL_H is nonzero, open flags for access modes O_RDONLY, - * O_WRONLY, O_RDWR and the open modifiers O_APPEND, O_CREAT, O_EXCL, O_SYNC - * will be defined by including the system file fcntl.h. - */ -#if defined(__AVR__) -// AVR fcntl.h does not define open flags. -#define USE_FCNTL_H 0 -#elif defined(PLATFORM_ID) -// Particle boards - use fcntl.h. -#define USE_FCNTL_H 1 -#elif defined(__arm__) -// ARM gcc defines open flags. -#define USE_FCNTL_H 1 -#else // defined(__AVR__) -#define USE_FCNTL_H 0 -#endif // defined(__AVR__) -//------------------------------------------------------------------------------ -/** - * If CHECK_FLASH_PROGRAMMING is zero, overlap of single sector flash - * programming and other operations will be allowed for faster write - * performance. - * - * Some cards will not sleep in low power mode unless CHECK_FLASH_PROGRAMMING - * is non-zero. - */ -#define CHECK_FLASH_PROGRAMMING 1 -//------------------------------------------------------------------------------ -/** - * Set MAINTAIN_FREE_CLUSTER_COUNT nonzero to keep the count of free clusters - * updated. This will increase the speed of the freeClusterCount() call - * after the first call. Extra flash will be required. - */ -#define MAINTAIN_FREE_CLUSTER_COUNT 0 -//------------------------------------------------------------------------------ -/** - * To enable SD card CRC checking set USE_SD_CRC nonzero. - * - * Set USE_SD_CRC to 1 to use a smaller CRC-CCITT function. This function - * is slower for AVR but may be fast for ARM and other processors. - * - * Set USE_SD_CRC to 2 to used a larger table driven CRC-CCITT function. This - * function is faster for AVR but may be slower for ARM and other processors. - */ -#define USE_SD_CRC 0 -//------------------------------------------------------------------------------ -/** - * Handle Watchdog Timer for WiFi modules. - * - * Yield will be called before accessing the SPI bus if it has been more - * than WDT_YIELD_TIME_MICROS microseconds since the last yield call by SdFat. - */ -#if defined(PLATFORM_ID) || defined(ESP8266) -// If Particle device or ESP8266 call yield. -#define WDT_YIELD_TIME_MICROS 100000 -#else -#define WDT_YIELD_TIME_MICROS 0 -#endif -//------------------------------------------------------------------------------ -/** - * Set FAT12_SUPPORT nonzero to enable use if FAT12 volumes. - * FAT12 has not been well tested and requires additional flash. - */ -#define FAT12_SUPPORT 0 -//------------------------------------------------------------------------------ -/** - * Set DESTRUCTOR_CLOSES_FILE nonzero to close a file in its destructor. - * - * Causes use of lots of heap in ARM. - */ -#define DESTRUCTOR_CLOSES_FILE 0 -//------------------------------------------------------------------------------ -/** - * Call flush for endl if ENDL_CALLS_FLUSH is nonzero - * - * The standard for iostreams is to call flush. This is very costly for - * SdFat. Each call to flush causes 2048 bytes of I/O to the SD. - * - * SdFat has a single 512 byte buffer for SD I/O so it must write the current - * data block to the SD, read the directory block from the SD, update the - * directory entry, write the directory block to the SD and read the data - * block back into the buffer. - * - * The SD flash memory controller is not designed for this many rewrites - * so performance may be reduced by more than a factor of 100. - * - * If ENDL_CALLS_FLUSH is zero, you must call flush and/or close to force - * all data to be written to the SD. - */ -#define ENDL_CALLS_FLUSH 0 -//------------------------------------------------------------------------------ -/** - * Set USE_SEPARATE_FAT_CACHE nonzero to use a second 512 byte cache - * for FAT table entries. This improves performance for large writes - * that are not a multiple of 512 bytes. - */ -#ifdef __arm__ -#define USE_SEPARATE_FAT_CACHE 1 -#else // __arm__ -#define USE_SEPARATE_FAT_CACHE 0 -#endif // __arm__ -//------------------------------------------------------------------------------ -/** - * Set USE_MULTI_BLOCK_IO nonzero to use multi-block SD read/write. - * - * Don't use mult-block read/write on small AVR boards. - */ -#if defined(RAMEND) && RAMEND < 3000 -#define USE_MULTI_BLOCK_IO 0 -#else // RAMEND -#define USE_MULTI_BLOCK_IO 1 -#endif // RAMEND -//----------------------------------------------------------------------------- -/** Enable SDIO driver if available. */ -#if defined(__MK64FX512__) || defined(__MK66FX1M0__) -#define ENABLE_SDIO_CLASS 1 -#define ENABLE_SDIOEX_CLASS 1 -#else // ENABLE_SDIO_CLASS -#define ENABLE_SDIO_CLASS 0 -#endif // ENABLE_SDIO_CLASS -//------------------------------------------------------------------------------ -/** - * Determine the default SPI configuration. - */ -#if defined(__STM32F1__) || defined(__STM32F4__) || defined(PLATFORM_ID) -// has multiple SPI ports -#define SD_HAS_CUSTOM_SPI 2 -#elif defined(__AVR__)\ - || defined(__SAM3X8E__) || defined(__SAM3X8H__)\ - || (defined(__arm__) && defined(CORE_TEENSY))\ - || defined(ESP8266) -#define SD_HAS_CUSTOM_SPI 1 -#else // SD_HAS_CUSTOM_SPI -// Use standard SPI library. -#define SD_HAS_CUSTOM_SPI 0 -#endif // SD_HAS_CUSTOM_SPI -//------------------------------------------------------------------------------ -/** - * Check if API to select HW SPI port is needed. - */ -#if USE_STANDARD_SPI_LIBRARY > 1 || SD_HAS_CUSTOM_SPI > 1 -#define IMPLEMENT_SPI_PORT_SELECTION 1 -#else // IMPLEMENT_SPI_PORT_SELECTION -#define IMPLEMENT_SPI_PORT_SELECTION 0 -#endif // IMPLEMENT_SPI_PORT_SELECTION -#endif // SdFatConfig_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/DigitalPin.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/DigitalPin.h deleted file mode 100644 index 38859d9..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/DigitalPin.h +++ /dev/null @@ -1,386 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -/** - * @file - * @brief Fast Digital Pin functions - * - * @defgroup digitalPin Fast Pin I/O - * @details Fast Digital I/O functions and template class. - * @{ - */ -#ifndef DigitalPin_h -#define DigitalPin_h -#if defined(__AVR__) || defined(DOXYGEN) -#include -/** GpioPinMap type */ -struct GpioPinMap_t { - volatile uint8_t* pin; /**< address of PIN for this pin */ - volatile uint8_t* ddr; /**< address of DDR for this pin */ - volatile uint8_t* port; /**< address of PORT for this pin */ - uint8_t mask; /**< bit mask for this pin */ -}; - -/** Initializer macro. */ -#define GPIO_PIN(reg, bit) {&PIN##reg, &DDR##reg, &PORT##reg, 1 << bit} - -// Include pin map for current board. -#include "boards/GpioPinMap.h" -//------------------------------------------------------------------------------ -/** generate bad pin number error */ -void badPinNumber(void) - __attribute__((error("Pin number is too large or not a constant"))); -//------------------------------------------------------------------------------ -/** Check for valid pin number - * @param[in] pin Number of pin to be checked. - */ -static inline __attribute__((always_inline)) -void badPinCheck(uint8_t pin) { - if (!__builtin_constant_p(pin) || pin >= NUM_DIGITAL_PINS) { - badPinNumber(); - } -} -//------------------------------------------------------------------------------ -/** DDR register address - * @param[in] pin Arduino pin number - * @return register address - */ -static inline __attribute__((always_inline)) -volatile uint8_t* ddrReg(uint8_t pin) { - badPinCheck(pin); - return GpioPinMap[pin].ddr; -} -//------------------------------------------------------------------------------ -/** Bit mask for pin - * @param[in] pin Arduino pin number - * @return mask - */ -static inline __attribute__((always_inline)) -uint8_t pinMask(uint8_t pin) { - badPinCheck(pin); - return GpioPinMap[pin].mask; -} -//------------------------------------------------------------------------------ -/** PIN register address - * @param[in] pin Arduino pin number - * @return register address - */ -static inline __attribute__((always_inline)) -volatile uint8_t* pinReg(uint8_t pin) { - badPinCheck(pin); - return GpioPinMap[pin].pin; -} -//------------------------------------------------------------------------------ -/** PORT register address - * @param[in] pin Arduino pin number - * @return register address - */ -static inline __attribute__((always_inline)) -volatile uint8_t* portReg(uint8_t pin) { - badPinCheck(pin); - return GpioPinMap[pin].port; -} -//------------------------------------------------------------------------------ -/** Fast write helper. - * @param[in] address I/O register address - * @param[in] mask bit mask for pin - * @param[in] level value for bit - */ -static inline __attribute__((always_inline)) -void fastBitWriteSafe(volatile uint8_t* address, uint8_t mask, bool level) { - uint8_t s; - if (address > reinterpret_cast(0X3F)) { - s = SREG; - cli(); - } - if (level) { - *address |= mask; - } else { - *address &= ~mask; - } - if (address > reinterpret_cast(0X3F)) { - SREG = s; - } -} -//------------------------------------------------------------------------------ -/** Read pin value. - * @param[in] pin Arduino pin number - * @return value read - */ -static inline __attribute__((always_inline)) -bool fastDigitalRead(uint8_t pin) { - return *pinReg(pin) & pinMask(pin); -} -//------------------------------------------------------------------------------ -/** Toggle a pin. - * @param[in] pin Arduino pin number - * - * If the pin is in output mode toggle the pin level. - * If the pin is in input mode toggle the state of the 20K pullup. - */ -static inline __attribute__((always_inline)) -void fastDigitalToggle(uint8_t pin) { - if (pinReg(pin) > reinterpret_cast(0X3F)) { - // must write bit to high address port - *pinReg(pin) = pinMask(pin); - } else { - // will compile to sbi and PIN register will not be read. - *pinReg(pin) |= pinMask(pin); - } -} -//------------------------------------------------------------------------------ -/** Set pin value. - * @param[in] pin Arduino pin number - * @param[in] level value to write - */ -static inline __attribute__((always_inline)) -void fastDigitalWrite(uint8_t pin, bool level) { - fastBitWriteSafe(portReg(pin), pinMask(pin), level); -} -//------------------------------------------------------------------------------ -/** Write the DDR register. - * @param[in] pin Arduino pin number - * @param[in] level value to write - */ -static inline __attribute__((always_inline)) -void fastDdrWrite(uint8_t pin, bool level) { - fastBitWriteSafe(ddrReg(pin), pinMask(pin), level); -} -//------------------------------------------------------------------------------ -/** Set pin mode. - * @param[in] pin Arduino pin number - * @param[in] mode INPUT, OUTPUT, or INPUT_PULLUP. - * - * The internal pullup resistors will be enabled if mode is INPUT_PULLUP - * and disabled if the mode is INPUT. - */ -static inline __attribute__((always_inline)) -void fastPinMode(uint8_t pin, uint8_t mode) { - fastDdrWrite(pin, mode == OUTPUT); - if (mode != OUTPUT) { - fastDigitalWrite(pin, mode == INPUT_PULLUP); - } -} -#else // defined(__AVR__) -#if defined(CORE_TEENSY) -//------------------------------------------------------------------------------ -/** read pin value - * @param[in] pin Arduino pin number - * @return value read - */ -static inline __attribute__((always_inline)) -bool fastDigitalRead(uint8_t pin) { - return *portInputRegister(pin); -} -//------------------------------------------------------------------------------ -/** Set pin value - * @param[in] pin Arduino pin number - * @param[in] level value to write - */ -static inline __attribute__((always_inline)) -void fastDigitalWrite(uint8_t pin, bool value) { - if (value) { - *portSetRegister(pin) = 1; - } else { - *portClearRegister(pin) = 1; - } -} -#elif defined(__SAM3X8E__) || defined(__SAM3X8H__) -//------------------------------------------------------------------------------ -/** read pin value - * @param[in] pin Arduino pin number - * @return value read - */ -static inline __attribute__((always_inline)) -bool fastDigitalRead(uint8_t pin) { - return g_APinDescription[pin].pPort->PIO_PDSR & g_APinDescription[pin].ulPin; -} -//------------------------------------------------------------------------------ -/** Set pin value - * @param[in] pin Arduino pin number - * @param[in] level value to write - */ -static inline __attribute__((always_inline)) -void fastDigitalWrite(uint8_t pin, bool value) { - if (value) { - g_APinDescription[pin].pPort->PIO_SODR = g_APinDescription[pin].ulPin; - } else { - g_APinDescription[pin].pPort->PIO_CODR = g_APinDescription[pin].ulPin; - } -} -#elif defined(ESP8266) -//------------------------------------------------------------------------------ -/** Set pin value - * @param[in] pin Arduino pin number - * @param[in] val value to write - */ -static inline __attribute__((always_inline)) -void fastDigitalWrite(uint8_t pin, uint8_t val) { - if (pin < 16) { - if (val) { - GPOS = (1 << pin); - } else { - GPOC = (1 << pin); - } - } else if (pin == 16) { - if (val) { - GP16O |= 1; - } else { - GP16O &= ~1; - } - } -} -//------------------------------------------------------------------------------ -/** Read pin value - * @param[in] pin Arduino pin number - * @return value read - */ -static inline __attribute__((always_inline)) -bool fastDigitalRead(uint8_t pin) { - if (pin < 16) { - return GPIP(pin); - } else if (pin == 16) { - return GP16I & 0x01; - } - return 0; -} -#else // CORE_TEENSY -//------------------------------------------------------------------------------ -inline void fastDigitalWrite(uint8_t pin, bool value) { - digitalWrite(pin, value); -} -//------------------------------------------------------------------------------ -inline bool fastDigitalRead(uint8_t pin) { - return digitalRead(pin); -} -#endif // CORE_TEENSY -//------------------------------------------------------------------------------ -inline void fastDigitalToggle(uint8_t pin) { - fastDigitalWrite(pin, !fastDigitalRead(pin)); -} -//------------------------------------------------------------------------------ -inline void fastPinMode(uint8_t pin, uint8_t mode) { - pinMode(pin, mode); -} -#endif // __AVR__ -//------------------------------------------------------------------------------ -/** set pin configuration - * @param[in] pin Arduino pin number - * @param[in] mode mode INPUT or OUTPUT. - * @param[in] level If mode is output, set level high/low. - * If mode is input, enable or disable the pin's 20K pullup. - */ -#define fastPinConfig(pin, mode, level)\ - {fastPinMode(pin, mode); fastDigitalWrite(pin, level);} -//============================================================================== -/** - * @class DigitalPin - * @brief Fast digital port I/O - */ -template -class DigitalPin { - public: - //---------------------------------------------------------------------------- - /** Constructor */ - DigitalPin() {} - //---------------------------------------------------------------------------- - /** Asignment operator. - * @param[in] value If true set the pin's level high else set the - * pin's level low. - * - * @return This DigitalPin instance. - */ - inline DigitalPin & operator = (bool value) __attribute__((always_inline)) { - write(value); - return *this; - } - //---------------------------------------------------------------------------- - /** Parenthesis operator. - * @return Pin's level - */ - inline operator bool () const __attribute__((always_inline)) { - return read(); - } - //---------------------------------------------------------------------------- - /** Set pin configuration. - * @param[in] mode: INPUT or OUTPUT. - * @param[in] level If mode is OUTPUT, set level high/low. - * If mode is INPUT, enable or disable the pin's 20K pullup. - */ - inline __attribute__((always_inline)) - void config(uint8_t mode, bool level) { - fastPinConfig(PinNumber, mode, level); - } - //---------------------------------------------------------------------------- - /** - * Set pin level high if output mode or enable 20K pullup if input mode. - */ - inline __attribute__((always_inline)) - void high() {write(true);} - //---------------------------------------------------------------------------- - /** - * Set pin level low if output mode or disable 20K pullup if input mode. - */ - inline __attribute__((always_inline)) - void low() {write(false);} - //---------------------------------------------------------------------------- - /** - * Set pin mode. - * @param[in] mode: INPUT, OUTPUT, or INPUT_PULLUP. - * - * The internal pullup resistors will be enabled if mode is INPUT_PULLUP - * and disabled if the mode is INPUT. - */ - inline __attribute__((always_inline)) - void mode(uint8_t mode) { - fastPinMode(PinNumber, mode); - } - //---------------------------------------------------------------------------- - /** @return Pin's level. */ - inline __attribute__((always_inline)) - bool read() const { - return fastDigitalRead(PinNumber); - } - //---------------------------------------------------------------------------- - /** Toggle a pin. - * - * If the pin is in output mode toggle the pin's level. - * If the pin is in input mode toggle the state of the 20K pullup. - */ - inline __attribute__((always_inline)) - void toggle() { - fastDigitalToggle(PinNumber); - } - //---------------------------------------------------------------------------- - /** Write the pin's level. - * @param[in] value If true set the pin's level high else set the - * pin's level low. - */ - inline __attribute__((always_inline)) - void write(bool value) { - fastDigitalWrite(PinNumber, value); - } -}; -#endif // DigitalPin_h -/** @} */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiBaseDriver.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiBaseDriver.h deleted file mode 100644 index a3374a5..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiBaseDriver.h +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 SdSpiBaseDriver_h -#define SdSpiBaseDriver_h -/** - * \class SdSpiBaseDriver - * \brief SPI base driver. - */ -class SdSpiBaseDriver { - public: - /** Set SPI options for access to SD/SDHC cards. - * - */ - virtual void activate() = 0; - /** Initialize the SPI bus. - * - * \param[in] chipSelectPin SD card chip select pin. - */ - virtual void begin(uint8_t chipSelectPin) = 0; - /** - * End SPI transaction. - */ - virtual void deactivate() = 0; - /** Receive a byte. - * - * \return The byte. - */ - virtual uint8_t receive() = 0; - /** Receive multiple bytes. - * - * \param[out] buf Buffer to receive the data. - * \param[in] n Number of bytes to receive. - * - * \return Zero for no error or nonzero error code. - */ - virtual uint8_t receive(uint8_t* buf, size_t n) = 0; - /** Send a byte. - * - * \param[in] data Byte to send - */ - virtual void send(uint8_t data) = 0; - /** Send multiple bytes. - * - * \param[in] buf Buffer for data to be sent. - * \param[in] n Number of bytes to send. - */ - virtual void send(const uint8_t* buf, size_t n) = 0; - /** Set CS low. */ - virtual void select() = 0; - /** Save SPI settings. - * \param[in] spiSettings SPI speed, mode, and bit order. - */ - virtual void setSpiSettings(SPISettings spiSettings) = 0; - /** Set CS high. */ - virtual void unselect() = 0; -}; -#endif // SdSpiBaseDriver_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiDriver.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiDriver.h deleted file mode 100644 index 47d5538..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiDriver.h +++ /dev/null @@ -1,438 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -/** - * \file - * \brief SpiDriver classes - */ -#ifndef SdSpiDriver_h -#define SdSpiDriver_h -#include -#include "SPI.h" -#include "SdSpiBaseDriver.h" -#include "SdFatConfig.h" -//------------------------------------------------------------------------------ -/** SDCARD_SPI is defined if board has built-in SD card socket */ -#ifndef SDCARD_SPI -#define SDCARD_SPI SPI -#endif // SDCARD_SPI -//------------------------------------------------------------------------------ -/** - * \class SdSpiLibDriver - * \brief SdSpiLibDriver - use standard SPI library. - */ -#if ENABLE_SOFTWARE_SPI_CLASS -class SdSpiLibDriver : public SdSpiBaseDriver { -#else // ENABLE_SOFTWARE_SPI_CLASS -class SdSpiLibDriver { -#endif // ENABLE_SOFTWARE_SPI_CLASS - public: -#if IMPLEMENT_SPI_PORT_SELECTION - /** Activate SPI hardware. */ - void activate() { - m_spi->beginTransaction(m_spiSettings); - } - /** Deactivate SPI hardware. */ - void deactivate() { - m_spi->endTransaction(); - } - /** Initialize the SPI bus. - * - * \param[in] csPin SD card chip select pin. - */ - void begin(uint8_t csPin) { - m_csPin = csPin; - digitalWrite(csPin, HIGH); - pinMode(csPin, OUTPUT); - m_spi->begin(); - } - /** Receive a byte. - * - * \return The byte. - */ - uint8_t receive() { - return m_spi->transfer( 0XFF); - } - /** Receive multiple bytes. - * - * \param[out] buf Buffer to receive the data. - * \param[in] n Number of bytes to receive. - * - * \return Zero for no error or nonzero error code. - */ - uint8_t receive(uint8_t* buf, size_t n) { - for (size_t i = 0; i < n; i++) { - buf[i] = m_spi->transfer(0XFF); - } - return 0; - } - /** Send a byte. - * - * \param[in] data Byte to send - */ - void send(uint8_t data) { - m_spi->transfer(data); - } - /** Send multiple bytes. - * - * \param[in] buf Buffer for data to be sent. - * \param[in] n Number of bytes to send. - */ - void send(const uint8_t* buf, size_t n) { - for (size_t i = 0; i < n; i++) { - m_spi->transfer(buf[i]); - } - } -#else // IMPLEMENT_SPI_PORT_SELECTION - /** Activate SPI hardware. */ - void activate() { - SDCARD_SPI.beginTransaction(m_spiSettings); - } - /** Deactivate SPI hardware. */ - void deactivate() { - SDCARD_SPI.endTransaction(); - } - /** Initialize the SPI bus. - * - * \param[in] csPin SD card chip select pin. - */ - void begin(uint8_t csPin) { - m_csPin = csPin; - digitalWrite(csPin, HIGH); - pinMode(csPin, OUTPUT); - SDCARD_SPI.begin(); - } - /** Receive a byte. - * - * \return The byte. - */ - uint8_t receive() { - return SDCARD_SPI.transfer( 0XFF); - } - /** Receive multiple bytes. - * - * \param[out] buf Buffer to receive the data. - * \param[in] n Number of bytes to receive. - * - * \return Zero for no error or nonzero error code. - */ - uint8_t receive(uint8_t* buf, size_t n) { - for (size_t i = 0; i < n; i++) { - buf[i] = SDCARD_SPI.transfer(0XFF); - } - return 0; - } - /** Send a byte. - * - * \param[in] data Byte to send - */ - void send(uint8_t data) { - SDCARD_SPI.transfer(data); - } - /** Send multiple bytes. - * - * \param[in] buf Buffer for data to be sent. - * \param[in] n Number of bytes to send. - */ - void send(const uint8_t* buf, size_t n) { - for (size_t i = 0; i < n; i++) { - SDCARD_SPI.transfer(buf[i]); - } - } -#endif // IMPLEMENT_SPI_PORT_SELECTION - /** Set CS low. */ - void select() { - digitalWrite(m_csPin, LOW); - } - /** Save SPISettings. - * - * \param[in] spiSettings SPI speed, mode, and byte order. - */ - void setSpiSettings(SPISettings spiSettings) { - m_spiSettings = spiSettings; - } - /** Set CS high. */ - void unselect() { - digitalWrite(m_csPin, HIGH); - } -#if IMPLEMENT_SPI_PORT_SELECTION || defined(DOXYGEN) - /** Set SPI port. - * \param[in] spiPort Hardware SPI port. - */ - void setPort(SPIClass* spiPort) { - m_spi = spiPort ? spiPort : &SDCARD_SPI; - } - private: - SPIClass* m_spi; -#else // IMPLEMENT_SPI_PORT_SELECTION - private: -#endif // IMPLEMENT_SPI_PORT_SELECTION - SPISettings m_spiSettings; - uint8_t m_csPin; -}; -//------------------------------------------------------------------------------ -/** - * \class SdSpiAltDriver - * \brief Optimized SPI class for access to SD and SDHC flash memory cards. - */ -#if ENABLE_SOFTWARE_SPI_CLASS -class SdSpiAltDriver : public SdSpiBaseDriver { -#else // ENABLE_SOFTWARE_SPI_CLASS -class SdSpiAltDriver { -#endif // ENABLE_SOFTWARE_SPI_CLASS - public: - /** Activate SPI hardware. */ - void activate(); - /** Deactivate SPI hardware. */ - void deactivate(); - /** Initialize the SPI bus. - * - * \param[in] csPin SD card chip select pin. - */ - void begin(uint8_t csPin); - /** Receive a byte. - * - * \return The byte. - */ - uint8_t receive(); - /** Receive multiple bytes. - * - * \param[out] buf Buffer to receive the data. - * \param[in] n Number of bytes to receive. - * - * \return Zero for no error or nonzero error code. - */ - uint8_t receive(uint8_t* buf, size_t n); - /** Send a byte. - * - * \param[in] data Byte to send - */ - void send(uint8_t data); - /** Send multiple bytes. - * - * \param[in] buf Buffer for data to be sent. - * \param[in] n Number of bytes to send. - */ - void send(const uint8_t* buf, size_t n); - /** Set CS low. */ - void select() { - digitalWrite(m_csPin, LOW); - } - /** Save SPISettings. - * - * \param[in] spiSettings SPI speed, mode, and byte order. - */ - void setSpiSettings(SPISettings spiSettings) { - m_spiSettings = spiSettings; - } - /** Set CS high. */ - void unselect() { - digitalWrite(m_csPin, HIGH); - } -#if IMPLEMENT_SPI_PORT_SELECTION || defined(DOXYGEN) - /** Set SPI port number. - * \param[in] spiPort Hardware SPI port. - */ - void setPort(SPIClass* spiPort) { - m_spi = spiPort ? spiPort : &SDCARD_SPI; - } - private: - SPIClass* m_spi; -#else // IMPLEMENT_SPI_PORT_SELECTION - private: -#endif // IMPLEMENT_SPI_PORT_SELECTION - SPISettings m_spiSettings; - uint8_t m_csPin; -}; -//------------------------------------------------------------------------------ -#if ENABLE_SOFTWARE_SPI_CLASS || defined(DOXYGEN) -#ifdef ARDUINO -#include "SoftSPI.h" -#elif defined(PLATFORM_ID) // Only defined if a Particle device -#include "SoftSPIParticle.h" -#endif // ARDUINO -/** - * \class SdSpiSoftDriver - * \brief Software SPI class for access to SD and SDHC flash memory cards. - */ -template -class SdSpiSoftDriver : public SdSpiBaseDriver { - public: - /** Dummy activate SPI hardware for software SPI */ - void activate() {} - /** Dummy deactivate SPI hardware for software SPI */ - void deactivate() {} - /** Initialize the SPI bus. - * - * \param[in] csPin SD card chip select pin. - */ - void begin(uint8_t csPin) { - m_csPin = csPin; - pinMode(m_csPin, OUTPUT); - digitalWrite(m_csPin, HIGH); - m_spi.begin(); - } - /** Receive a byte. - * - * \return The byte. - */ - uint8_t receive() { - return m_spi.receive(); - } - /** Receive multiple bytes. - * - * \param[out] buf Buffer to receive the data. - * \param[in] n Number of bytes to receive. - * - * \return Zero for no error or nonzero error code. - */ - uint8_t receive(uint8_t* buf, size_t n) { - for (size_t i = 0; i < n; i++) { - buf[i] = receive(); - } - return 0; - } - /** Send a byte. - * - * \param[in] data Byte to send - */ - void send(uint8_t data) { - m_spi.send(data); - } - /** Send multiple bytes. - * - * \param[in] buf Buffer for data to be sent. - * \param[in] n Number of bytes to send. - */ - void send(const uint8_t* buf , size_t n) { - for (size_t i = 0; i < n; i++) { - send(buf[i]); - } - } - /** Set CS low. */ - void select() { - digitalWrite(m_csPin, LOW); - } - /** Save SPISettings. - * - * \param[in] spiSettings SPI speed, mode, and byte order. - */ - void setSpiSettings(SPISettings spiSettings) { - (void)spiSettings; - } - /** Set CS high. */ - void unselect() { - digitalWrite(m_csPin, HIGH); - } - - private: - uint8_t m_csPin; - SoftSPI m_spi; -}; -#endif // ENABLE_SOFTWARE_SPI_CLASS || defined(DOXYGEN) -//------------------------------------------------------------------------------ -// Choose SPI driver for SdFat and SdFatEX classes. -#if USE_STANDARD_SPI_LIBRARY || !SD_HAS_CUSTOM_SPI -/** SdFat uses Arduino library SPI. */ -typedef SdSpiLibDriver SdFatSpiDriver; -#else // USE_STANDARD_SPI_LIBRARY || !SD_HAS_CUSTOM_SPI -/** SdFat uses custom fast SPI. */ -typedef SdSpiAltDriver SdFatSpiDriver; -#endif // USE_STANDARD_SPI_LIBRARY || !SD_HAS_CUSTOM_SPI - -/** typedef for for SdSpiCard class. */ -#if ENABLE_SOFTWARE_SPI_CLASS -// Need virtual driver. -typedef SdSpiBaseDriver SdSpiDriver; -#else // ENABLE_SOFTWARE_SPI_CLASS -// Don't need virtual driver. -typedef SdFatSpiDriver SdSpiDriver; -#endif // ENABLE_SOFTWARE_SPI_CLASS -//============================================================================== -// Use of in-line for AVR to save flash. -#ifdef __AVR__ -//------------------------------------------------------------------------------ -inline void SdSpiAltDriver::begin(uint8_t csPin) { - m_csPin = csPin; - pinMode(m_csPin, OUTPUT); - digitalWrite(m_csPin, HIGH); - SPI.begin(); -} -//------------------------------------------------------------------------------ -inline void SdSpiAltDriver::activate() { - SPI.beginTransaction(m_spiSettings); -} -//------------------------------------------------------------------------------ -inline void SdSpiAltDriver::deactivate() { - SPI.endTransaction(); -} -//------------------------------------------------------------------------------ -inline uint8_t SdSpiAltDriver::receive() { - SPDR = 0XFF; - while (!(SPSR & (1 << SPIF))) {} - return SPDR; -} -//------------------------------------------------------------------------------ -inline uint8_t SdSpiAltDriver::receive(uint8_t* buf, size_t n) { - if (n-- == 0) { - return 0; - } - SPDR = 0XFF; - for (size_t i = 0; i < n; i++) { - while (!(SPSR & (1 << SPIF))) {} - uint8_t b = SPDR; - SPDR = 0XFF; - buf[i] = b; - } - while (!(SPSR & (1 << SPIF))) {} - buf[n] = SPDR; - return 0; -} -//------------------------------------------------------------------------------ -inline void SdSpiAltDriver::send(uint8_t data) { - SPDR = data; - while (!(SPSR & (1 << SPIF))) {} -} -//------------------------------------------------------------------------------ -inline void SdSpiAltDriver::send(const uint8_t* buf , size_t n) { - if (n == 0) { - return; - } - SPDR = buf[0]; - if (n > 1) { - uint8_t b = buf[1]; - size_t i = 2; - while (1) { - while (!(SPSR & (1 << SPIF))) {} - SPDR = b; - if (i == n) { - break; - } - b = buf[i++]; - } - } - while (!(SPSR & (1 << SPIF))) {} -} -#endif // __AVR__ -#endif // SdSpiDriver_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiESP8266.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiESP8266.cpp deleted file mode 100644 index 9167446..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiESP8266.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#if defined(ESP8266) -#include "SdSpiDriver.h" -//------------------------------------------------------------------------------ -/** Initialize the SPI bus. - * - * \param[in] chipSelectPin SD card chip select pin. - */ -void SdSpiAltDriver::begin(uint8_t csPin) { - m_csPin = csPin; - pinMode(m_csPin, OUTPUT); - digitalWrite(m_csPin, HIGH); - SPI.begin(); -} -//------------------------------------------------------------------------------ -/** Set SPI options for access to SD/SDHC cards. - * - */ -void SdSpiAltDriver::activate() { - SPI.beginTransaction(m_spiSettings); -} -//------------------------------------------------------------------------------ -void SdSpiAltDriver::deactivate() { - // Note: endTransaction is an empty function on ESP8266. - SPI.endTransaction(); -} -//------------------------------------------------------------------------------ -/** Receive a byte. - * - * \return The byte. - */ -uint8_t SdSpiAltDriver::receive() { - return SPI.transfer(0XFF); -} -//------------------------------------------------------------------------------ -/** Receive multiple bytes. - * - * \param[out] buf Buffer to receive the data. - * \param[in] n Number of bytes to receive. - * - * \return Zero for no error or nonzero error code. - */ -uint8_t SdSpiAltDriver::receive(uint8_t* buf, size_t n) { - // Works without 32-bit alignment of buf. - SPI.transferBytes(0, buf, n); - return 0; -} -//------------------------------------------------------------------------------ -/** Send a byte. - * - * \param[in] b Byte to send - */ -void SdSpiAltDriver::send(uint8_t b) { - SPI.transfer(b); -} -//------------------------------------------------------------------------------ -/** Send multiple bytes. - * - * \param[in] buf Buffer for data to be sent. - * \param[in] n Number of bytes to send. - */ -void SdSpiAltDriver::send(const uint8_t* buf , size_t n) { - // Adjust to 32-bit alignment. - while ((reinterpret_cast(buf) & 0X3) && n) { - SPI.transfer(*buf++); - n--; - } - SPI.transferBytes(const_cast(buf), 0, n); -} -#endif // defined(ESP8266) diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiParticle.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiParticle.cpp deleted file mode 100644 index 59e45c2..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiParticle.cpp +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#if defined(PLATFORM_ID) -#include "SdSpiDriver.h" -static volatile bool SPI_DMA_TransferCompleted = false; -//----------------------------------------------------------------------------- -static void SD_SPI_DMA_TransferComplete_Callback(void) { - SPI_DMA_TransferCompleted = true; -} -//------------------------------------------------------------------------------ -/** Set SPI options for access to SD/SDHC cards. - * - * \param[in] divisor SCK clock divider relative to the APB1 or APB2 clock. - */ -void SdSpiAltDriver::activate() { - m_spi->beginTransaction(m_spiSettings); -} -//------------------------------------------------------------------------------ -/** Initialize the SPI bus. - * - * \param[in] chipSelectPin SD card chip select pin. - */ -void SdSpiAltDriver::begin(uint8_t csPin) { - m_csPin = csPin; - m_spi->begin(); - pinMode(m_csPin, OUTPUT); - digitalWrite(m_csPin, HIGH); -} -//------------------------------------------------------------------------------ -/** - * End SPI transaction. - */ -void SdSpiAltDriver::deactivate() { - m_spi->endTransaction(); -} -//------------------------------------------------------------------------------ -/** Receive a byte. - * - * \return The byte. - */ -uint8_t SdSpiAltDriver::receive() { - return m_spi->transfer(0XFF); -} -//------------------------------------------------------------------------------ -/** Receive multiple bytes. - * - * \param[out] buf Buffer to receive the data. - * \param[in] n Number of bytes to receive. - * - * \return Zero for no error or nonzero error code. - */ -uint8_t SdSpiAltDriver::receive(uint8_t* buf, size_t n) { - SPI_DMA_TransferCompleted = false; - m_spi->transfer(nullptr, buf, n, SD_SPI_DMA_TransferComplete_Callback); - while (!SPI_DMA_TransferCompleted) {} - return 0; -} -//------------------------------------------------------------------------------ -/** Send a byte. - * - * \param[in] b Byte to send - */ -void SdSpiAltDriver::send(uint8_t b) { - m_spi->transfer(b); -} -//------------------------------------------------------------------------------ -/** Send multiple bytes. - * - * \param[in] buf Buffer for data to be sent. - * \param[in] n Number of bytes to send. - */ -void SdSpiAltDriver::send(const uint8_t* buf , size_t n) { - SPI_DMA_TransferCompleted = false; - - m_spi->transfer(const_cast(buf), nullptr, n, - SD_SPI_DMA_TransferComplete_Callback); - - while (!SPI_DMA_TransferCompleted) {} -} -#endif // defined(PLATFORM_ID) diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiSAM3X.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiSAM3X.cpp deleted file mode 100644 index 91f8fb5..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiSAM3X.cpp +++ /dev/null @@ -1,218 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#include "SdSpiDriver.h" -#if defined(__SAM3X8E__) || defined(__SAM3X8H__) -/** Use SAM3X DMAC if nonzero */ -#define USE_SAM3X_DMAC 1 -/** Use extra Bus Matrix arbitration fix if nonzero */ -#define USE_SAM3X_BUS_MATRIX_FIX 0 -/** Time in ms for DMA receive timeout */ -#define SAM3X_DMA_TIMEOUT 100 -/** chip select register number */ -#define SPI_CHIP_SEL 3 -/** DMAC receive channel */ -#define SPI_DMAC_RX_CH 1 -/** DMAC transmit channel */ -#define SPI_DMAC_TX_CH 0 -/** DMAC Channel HW Interface Number for SPI TX. */ -#define SPI_TX_IDX 1 -/** DMAC Channel HW Interface Number for SPI RX. */ -#define SPI_RX_IDX 2 -//------------------------------------------------------------------------------ -/** Disable DMA Controller. */ -static void dmac_disable() { - DMAC->DMAC_EN &= (~DMAC_EN_ENABLE); -} -/** Enable DMA Controller. */ -static void dmac_enable() { - DMAC->DMAC_EN = DMAC_EN_ENABLE; -} -/** Disable DMA Channel. */ -static void dmac_channel_disable(uint32_t ul_num) { - DMAC->DMAC_CHDR = DMAC_CHDR_DIS0 << ul_num; -} -/** Enable DMA Channel. */ -static void dmac_channel_enable(uint32_t ul_num) { - DMAC->DMAC_CHER = DMAC_CHER_ENA0 << ul_num; -} -/** Poll for transfer complete. */ -static bool dmac_channel_transfer_done(uint32_t ul_num) { - return (DMAC->DMAC_CHSR & (DMAC_CHSR_ENA0 << ul_num)) ? false : true; -} -//------------------------------------------------------------------------------ -void SdSpiAltDriver::begin(uint8_t csPin) { - m_csPin = csPin; - pinMode(m_csPin, OUTPUT); - digitalWrite(m_csPin, HIGH); -SPI.begin(); -#if USE_SAM3X_DMAC - pmc_enable_periph_clk(ID_DMAC); - dmac_disable(); - DMAC->DMAC_GCFG = DMAC_GCFG_ARB_CFG_FIXED; - dmac_enable(); -#if USE_SAM3X_BUS_MATRIX_FIX - MATRIX->MATRIX_WPMR = 0x4d415400; - MATRIX->MATRIX_MCFG[1] = 1; - MATRIX->MATRIX_MCFG[2] = 1; - MATRIX->MATRIX_SCFG[0] = 0x01000010; - MATRIX->MATRIX_SCFG[1] = 0x01000010; - MATRIX->MATRIX_SCFG[7] = 0x01000010; -#endif // USE_SAM3X_BUS_MATRIX_FIX -#endif // USE_SAM3X_DMAC -} -//------------------------------------------------------------------------------ -// start RX DMA -static void spiDmaRX(uint8_t* dst, uint16_t count) { - dmac_channel_disable(SPI_DMAC_RX_CH); - DMAC->DMAC_CH_NUM[SPI_DMAC_RX_CH].DMAC_SADDR = (uint32_t)&SPI0->SPI_RDR; - DMAC->DMAC_CH_NUM[SPI_DMAC_RX_CH].DMAC_DADDR = (uint32_t)dst; - DMAC->DMAC_CH_NUM[SPI_DMAC_RX_CH].DMAC_DSCR = 0; - DMAC->DMAC_CH_NUM[SPI_DMAC_RX_CH].DMAC_CTRLA = count | - DMAC_CTRLA_SRC_WIDTH_BYTE | DMAC_CTRLA_DST_WIDTH_BYTE; - DMAC->DMAC_CH_NUM[SPI_DMAC_RX_CH].DMAC_CTRLB = DMAC_CTRLB_SRC_DSCR | - DMAC_CTRLB_DST_DSCR | DMAC_CTRLB_FC_PER2MEM_DMA_FC | - DMAC_CTRLB_SRC_INCR_FIXED | DMAC_CTRLB_DST_INCR_INCREMENTING; - DMAC->DMAC_CH_NUM[SPI_DMAC_RX_CH].DMAC_CFG = DMAC_CFG_SRC_PER(SPI_RX_IDX) | - DMAC_CFG_SRC_H2SEL | DMAC_CFG_SOD | DMAC_CFG_FIFOCFG_ASAP_CFG; - dmac_channel_enable(SPI_DMAC_RX_CH); -} -//------------------------------------------------------------------------------ -// start TX DMA -static void spiDmaTX(const uint8_t* src, uint16_t count) { - static uint8_t ff = 0XFF; - uint32_t src_incr = DMAC_CTRLB_SRC_INCR_INCREMENTING; - if (!src) { - src = &ff; - src_incr = DMAC_CTRLB_SRC_INCR_FIXED; - } - dmac_channel_disable(SPI_DMAC_TX_CH); - DMAC->DMAC_CH_NUM[SPI_DMAC_TX_CH].DMAC_SADDR = (uint32_t)src; - DMAC->DMAC_CH_NUM[SPI_DMAC_TX_CH].DMAC_DADDR = (uint32_t)&SPI0->SPI_TDR; - DMAC->DMAC_CH_NUM[SPI_DMAC_TX_CH].DMAC_DSCR = 0; - DMAC->DMAC_CH_NUM[SPI_DMAC_TX_CH].DMAC_CTRLA = count | - DMAC_CTRLA_SRC_WIDTH_BYTE | DMAC_CTRLA_DST_WIDTH_BYTE; - - DMAC->DMAC_CH_NUM[SPI_DMAC_TX_CH].DMAC_CTRLB = DMAC_CTRLB_SRC_DSCR | - DMAC_CTRLB_DST_DSCR | DMAC_CTRLB_FC_MEM2PER_DMA_FC | - src_incr | DMAC_CTRLB_DST_INCR_FIXED; - - DMAC->DMAC_CH_NUM[SPI_DMAC_TX_CH].DMAC_CFG = DMAC_CFG_DST_PER(SPI_TX_IDX) | - DMAC_CFG_DST_H2SEL | DMAC_CFG_SOD | DMAC_CFG_FIFOCFG_ALAP_CFG; - - dmac_channel_enable(SPI_DMAC_TX_CH); -} -//------------------------------------------------------------------------------ -// initialize SPI controller -void SdSpiAltDriver::activate() { - SPI.beginTransaction(m_spiSettings); - - Spi* pSpi = SPI0; - // Save the divisor - uint32_t scbr = pSpi->SPI_CSR[SPI_CHIP_SEL] & 0XFF00; - // Disable SPI - pSpi->SPI_CR = SPI_CR_SPIDIS; - // reset SPI - pSpi->SPI_CR = SPI_CR_SWRST; - // no mode fault detection, set master mode - pSpi->SPI_MR = SPI_PCS(SPI_CHIP_SEL) | SPI_MR_MODFDIS | SPI_MR_MSTR; - // mode 0, 8-bit, - pSpi->SPI_CSR[SPI_CHIP_SEL] = scbr | SPI_CSR_CSAAT | SPI_CSR_NCPHA; - // enable SPI - pSpi->SPI_CR |= SPI_CR_SPIEN; -} -//------------------------------------------------------------------------------ -void SdSpiAltDriver::deactivate() { - SPI.endTransaction(); -} -//------------------------------------------------------------------------------ -static inline uint8_t spiTransfer(uint8_t b) { - Spi* pSpi = SPI0; - - pSpi->SPI_TDR = b; - while ((pSpi->SPI_SR & SPI_SR_RDRF) == 0) {} - b = pSpi->SPI_RDR; - return b; -} -//------------------------------------------------------------------------------ -/** SPI receive a byte */ -uint8_t SdSpiAltDriver::receive() { - return spiTransfer(0XFF); -} -//------------------------------------------------------------------------------ -/** SPI receive multiple bytes */ -uint8_t SdSpiAltDriver::receive(uint8_t* buf, size_t n) { - Spi* pSpi = SPI0; - int rtn = 0; -#if USE_SAM3X_DMAC - // clear overrun error - pSpi->SPI_SR; - - spiDmaRX(buf, n); - spiDmaTX(0, n); - - uint32_t m = millis(); - while (!dmac_channel_transfer_done(SPI_DMAC_RX_CH)) { - if ((millis() - m) > SAM3X_DMA_TIMEOUT) { - dmac_channel_disable(SPI_DMAC_RX_CH); - dmac_channel_disable(SPI_DMAC_TX_CH); - rtn = 2; - break; - } - } - if (pSpi->SPI_SR & SPI_SR_OVRES) { - rtn |= 1; - } -#else // USE_SAM3X_DMAC - for (size_t i = 0; i < n; i++) { - pSpi->SPI_TDR = 0XFF; - while ((pSpi->SPI_SR & SPI_SR_RDRF) == 0) {} - buf[i] = pSpi->SPI_RDR; - } -#endif // USE_SAM3X_DMAC - return rtn; -} -//------------------------------------------------------------------------------ -/** SPI send a byte */ -void SdSpiAltDriver::send(uint8_t b) { - spiTransfer(b); -} -//------------------------------------------------------------------------------ -void SdSpiAltDriver::send(const uint8_t* buf , size_t n) { - Spi* pSpi = SPI0; -#if USE_SAM3X_DMAC - spiDmaTX(buf, n); - while (!dmac_channel_transfer_done(SPI_DMAC_TX_CH)) {} -#else // #if USE_SAM3X_DMAC - while ((pSpi->SPI_SR & SPI_SR_TXEMPTY) == 0) {} - for (size_t i = 0; i < n; i++) { - pSpi->SPI_TDR = buf[i]; - while ((pSpi->SPI_SR & SPI_SR_TDRE) == 0) {} - } -#endif // #if USE_SAM3X_DMAC - while ((pSpi->SPI_SR & SPI_SR_TXEMPTY) == 0) {} - // leave RDR empty - pSpi->SPI_RDR; -} -#endif // defined(__SAM3X8E__) || defined(__SAM3X8H__) diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiSTM32.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiSTM32.cpp deleted file mode 100644 index 114c239..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiSTM32.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#if defined(__STM32F1__) || defined(__STM32F4__) -#include "SdSpiDriver.h" -#if defined(__STM32F1__) -#define USE_STM32_DMA 1 -#elif defined(__STM32F4__) -#define USE_STM32_DMA 1 -#else // defined(__STM32F1__) -#error Unknown STM32 type -#endif // defined(__STM32F1__) -//------------------------------------------------------------------------------ -/** Set SPI options for access to SD/SDHC cards. - * - * \param[in] divisor SCK clock divider relative to the APB1 or APB2 clock. - */ -void SdSpiAltDriver::activate() { - m_spi->beginTransaction(m_spiSettings); -} -//------------------------------------------------------------------------------ -/** Initialize the SPI bus. - * - * \param[in] chipSelectPin SD card chip select pin. - */ -void SdSpiAltDriver::begin(uint8_t csPin) { - m_csPin = csPin; - pinMode(m_csPin, OUTPUT); - digitalWrite(m_csPin, HIGH); - m_spi->begin(); -} -//------------------------------------------------------------------------------ -/** - * End SPI transaction. - */ -void SdSpiAltDriver::deactivate() { - m_spi->endTransaction(); -} -//------------------------------------------------------------------------------ -/** Receive a byte. - * - * \return The byte. - */ -uint8_t SdSpiAltDriver::receive() { - return m_spi->transfer(0XFF); -} -//------------------------------------------------------------------------------ -/** Receive multiple bytes. - * - * \param[out] buf Buffer to receive the data. - * \param[in] n Number of bytes to receive. - * - * \return Zero for no error or nonzero error code. - */ -uint8_t SdSpiAltDriver::receive(uint8_t* buf, size_t n) { -#if USE_STM32_DMA - return m_spi->dmaTransfer(nullptr, buf, n); -#else // USE_STM32_DMA - m_spi->read(buf, n); - return 0; -#endif // USE_STM32_DMA -} -//------------------------------------------------------------------------------ -/** Send a byte. - * - * \param[in] b Byte to send - */ -void SdSpiAltDriver::send(uint8_t b) { - m_spi->transfer(b); -} -//------------------------------------------------------------------------------ -/** Send multiple bytes. - * - * \param[in] buf Buffer for data to be sent. - * \param[in] n Number of bytes to send. - */ -void SdSpiAltDriver::send(const uint8_t* buf , size_t n) { -#if USE_STM32_DMA - m_spi->dmaTransfer(const_cast(buf), nullptr, n); -#else // USE_STM32_DMA - m_spi->write(const_cast(buf), n); -#endif // USE_STM32_DMA -} -#endif // defined(__STM32F1__) || defined(__STM32F4__) diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiTeensy3.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiTeensy3.cpp deleted file mode 100644 index 17bb572..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SdSpiTeensy3.cpp +++ /dev/null @@ -1,233 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -#include "SdSpiDriver.h" -#if defined(__arm__) && defined(CORE_TEENSY) -// SPI definitions -#include "kinetis.h" - -//------------------------------------------------------------------------------ -void SdSpiAltDriver::activate() { - SPI.beginTransaction(m_spiSettings); -} -//------------------------------------------------------------------------------ -void SdSpiAltDriver::begin(uint8_t chipSelectPin) { - m_csPin = chipSelectPin; - pinMode(m_csPin, OUTPUT); - digitalWrite(m_csPin, HIGH); - SPI.begin(); -} -//------------------------------------------------------------------------------ -void SdSpiAltDriver::deactivate() { - SPI.endTransaction(); -} -//============================================================================== -#ifdef KINETISK - -// use 16-bit frame if SPI_USE_8BIT_FRAME is zero -#define SPI_USE_8BIT_FRAME 0 -// Limit initial fifo to three entries to avoid fifo overrun -#define SPI_INITIAL_FIFO_DEPTH 3 -// define some symbols that are not in mk20dx128.h -#ifndef SPI_SR_RXCTR -#define SPI_SR_RXCTR 0XF0 -#endif // SPI_SR_RXCTR -#ifndef SPI_PUSHR_CONT -#define SPI_PUSHR_CONT 0X80000000 -#endif // SPI_PUSHR_CONT -#ifndef SPI_PUSHR_CTAS -#define SPI_PUSHR_CTAS(n) (((n) & 7) << 28) -#endif // SPI_PUSHR_CTAS -//------------------------------------------------------------------------------ -/** SPI receive a byte */ -uint8_t SdSpiAltDriver::receive() { - SPI0_MCR |= SPI_MCR_CLR_RXF; - SPI0_SR = SPI_SR_TCF; - SPI0_PUSHR = 0xFF; - while (!(SPI0_SR & SPI_SR_TCF)) {} - return SPI0_POPR; -} -//------------------------------------------------------------------------------ -/** SPI receive multiple bytes */ -uint8_t SdSpiAltDriver::receive(uint8_t* buf, size_t n) { - // clear any data in RX FIFO - SPI0_MCR = SPI_MCR_MSTR | SPI_MCR_CLR_RXF | SPI_MCR_PCSIS(0x1F); -#if SPI_USE_8BIT_FRAME - // initial number of bytes to push into TX FIFO - int nf = n < SPI_INITIAL_FIFO_DEPTH ? n : SPI_INITIAL_FIFO_DEPTH; - for (int i = 0; i < nf; i++) { - SPI0_PUSHR = 0XFF; - } - // limit for pushing dummy data into TX FIFO - uint8_t* limit = buf + n - nf; - while (buf < limit) { - while (!(SPI0_SR & SPI_SR_RXCTR)) {} - SPI0_PUSHR = 0XFF; - *buf++ = SPI0_POPR; - } - // limit for rest of RX data - limit += nf; - while (buf < limit) { - while (!(SPI0_SR & SPI_SR_RXCTR)) {} - *buf++ = SPI0_POPR; - } -#else // SPI_USE_8BIT_FRAME - // use 16 bit frame to avoid TD delay between frames - // get one byte if n is odd - if (n & 1) { - *buf++ = receive(); - n--; - } - // initial number of words to push into TX FIFO - int nf = n/2 < SPI_INITIAL_FIFO_DEPTH ? n/2 : SPI_INITIAL_FIFO_DEPTH; - for (int i = 0; i < nf; i++) { - SPI0_PUSHR = SPI_PUSHR_CONT | SPI_PUSHR_CTAS(1) | 0XFFFF; - } - uint8_t* limit = buf + n - 2*nf; - while (buf < limit) { - while (!(SPI0_SR & SPI_SR_RXCTR)) {} - SPI0_PUSHR = SPI_PUSHR_CONT | SPI_PUSHR_CTAS(1) | 0XFFFF; - uint16_t w = SPI0_POPR; - *buf++ = w >> 8; - *buf++ = w & 0XFF; - } - // limit for rest of RX data - limit += 2*nf; - while (buf < limit) { - while (!(SPI0_SR & SPI_SR_RXCTR)) {} - uint16_t w = SPI0_POPR; - *buf++ = w >> 8; - *buf++ = w & 0XFF; - } -#endif // SPI_USE_8BIT_FRAME - return 0; -} -//------------------------------------------------------------------------------ -/** SPI send a byte */ -void SdSpiAltDriver::send(uint8_t b) { - SPI0_MCR |= SPI_MCR_CLR_RXF; - SPI0_SR = SPI_SR_TCF; - SPI0_PUSHR = b; - while (!(SPI0_SR & SPI_SR_TCF)) {} -} -//------------------------------------------------------------------------------ -/** SPI send multiple bytes */ -void SdSpiAltDriver::send(const uint8_t* buf , size_t n) { - // clear any data in RX FIFO - SPI0_MCR = SPI_MCR_MSTR | SPI_MCR_CLR_RXF | SPI_MCR_PCSIS(0x1F); -#if SPI_USE_8BIT_FRAME - // initial number of bytes to push into TX FIFO - int nf = n < SPI_INITIAL_FIFO_DEPTH ? n : SPI_INITIAL_FIFO_DEPTH; - // limit for pushing data into TX fifo - const uint8_t* limit = buf + n; - for (int i = 0; i < nf; i++) { - SPI0_PUSHR = *buf++; - } - // write data to TX FIFO - while (buf < limit) { - while (!(SPI0_SR & SPI_SR_RXCTR)) {} - SPI0_PUSHR = *buf++; - SPI0_POPR; - } - // wait for data to be sent - while (nf) { - while (!(SPI0_SR & SPI_SR_RXCTR)) {} - SPI0_POPR; - nf--; - } -#else // SPI_USE_8BIT_FRAME - // use 16 bit frame to avoid TD delay between frames - // send one byte if n is odd - if (n & 1) { - send(*buf++); - n--; - } - // initial number of words to push into TX FIFO - int nf = n/2 < SPI_INITIAL_FIFO_DEPTH ? n/2 : SPI_INITIAL_FIFO_DEPTH; - // limit for pushing data into TX fifo - const uint8_t* limit = buf + n; - for (int i = 0; i < nf; i++) { - uint16_t w = (*buf++) << 8; - w |= *buf++; - SPI0_PUSHR = SPI_PUSHR_CONT | SPI_PUSHR_CTAS(1) | w; - } - // write data to TX FIFO - while (buf < limit) { - uint16_t w = *buf++ << 8; - w |= *buf++; - while (!(SPI0_SR & SPI_SR_RXCTR)) {} - SPI0_PUSHR = SPI_PUSHR_CONT | SPI_PUSHR_CTAS(1) | w; - SPI0_POPR; - } - // wait for data to be sent - while (nf) { - while (!(SPI0_SR & SPI_SR_RXCTR)) {} - SPI0_POPR; - nf--; - } -#endif // SPI_USE_8BIT_FRAME -} -#else // KINETISK -//============================================================================== -// Use standard SPI library if not KINETISK -//------------------------------------------------------------------------------ -/** Receive a byte. - * - * \return The byte. - */ -uint8_t SdSpiAltDriver::receive() { - return SPI.transfer(0XFF); -} -/** Receive multiple bytes. - * - * \param[out] buf Buffer to receive the data. - * \param[in] n Number of bytes to receive. - * - * \return Zero for no error or nonzero error code. - */ -uint8_t SdSpiAltDriver::receive(uint8_t* buf, size_t n) { - for (size_t i = 0; i < n; i++) { - buf[i] = SPI.transfer(0XFF); - } - return 0; -} -/** Send a byte. - * - * \param[in] b Byte to send - */ -void SdSpiAltDriver::send(uint8_t b) { - SPI.transfer(b); -} -/** Send multiple bytes. - * - * \param[in] buf Buffer for data to be sent. - * \param[in] n Number of bytes to send. - */ -void SdSpiAltDriver::send(const uint8_t* buf , size_t n) { - for (size_t i = 0; i < n; i++) { - SPI.transfer(buf[i]); - } -} -#endif // KINETISK -#endif // defined(__arm__) && defined(CORE_TEENSY) diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SoftSPI.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SoftSPI.h deleted file mode 100644 index fd21e1e..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/SoftSPI.h +++ /dev/null @@ -1,167 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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. - */ -/** - * @file - * @brief Software SPI. - * - * @defgroup softSPI Software SPI - * @details Software SPI Template Class. - * @{ - */ - -#ifndef SoftSPI_h -#define SoftSPI_h -#include "DigitalPin.h" -//------------------------------------------------------------------------------ -/** Nop for timing. */ -#define nop asm volatile ("nop\n\t") -//------------------------------------------------------------------------------ -/** Pin Mode for MISO is input.*/ -#define MISO_MODE INPUT -/** Pullups disabled for MISO are disabled. */ -#define MISO_LEVEL false -/** Pin Mode for MOSI is output.*/ -#define MOSI_MODE OUTPUT -/** Pin Mode for SCK is output. */ -#define SCK_MODE OUTPUT -//------------------------------------------------------------------------------ -/** - * @class SoftSPI - * @brief Fast software SPI. - */ -template -class SoftSPI { - public: - //---------------------------------------------------------------------------- - /** Initialize SoftSPI pins. */ - void begin() { - fastPinConfig(MisoPin, MISO_MODE, MISO_LEVEL); - fastPinConfig(MosiPin, MOSI_MODE, !MODE_CPHA(Mode)); - fastPinConfig(SckPin, SCK_MODE, MODE_CPOL(Mode)); - } - //---------------------------------------------------------------------------- - /** Soft SPI receive byte. - * @return Data byte received. - */ - inline __attribute__((always_inline)) - uint8_t receive() { - uint8_t data = 0; - receiveBit(7, &data); - receiveBit(6, &data); - receiveBit(5, &data); - receiveBit(4, &data); - receiveBit(3, &data); - receiveBit(2, &data); - receiveBit(1, &data); - receiveBit(0, &data); - return data; - } - //---------------------------------------------------------------------------- - /** Soft SPI send byte. - * @param[in] data Data byte to send. - */ - inline __attribute__((always_inline)) - void send(uint8_t data) { - sendBit(7, data); - sendBit(6, data); - sendBit(5, data); - sendBit(4, data); - sendBit(3, data); - sendBit(2, data); - sendBit(1, data); - sendBit(0, data); - } - //---------------------------------------------------------------------------- - /** Soft SPI transfer byte. - * @param[in] txData Data byte to send. - * @return Data byte received. - */ - inline __attribute__((always_inline)) - uint8_t transfer(uint8_t txData) { - uint8_t rxData = 0; - transferBit(7, &rxData, txData); - transferBit(6, &rxData, txData); - transferBit(5, &rxData, txData); - transferBit(4, &rxData, txData); - transferBit(3, &rxData, txData); - transferBit(2, &rxData, txData); - transferBit(1, &rxData, txData); - transferBit(0, &rxData, txData); - return rxData; - } - - private: - //---------------------------------------------------------------------------- - inline __attribute__((always_inline)) - bool MODE_CPHA(uint8_t mode) {return (mode & 1) != 0;} - inline __attribute__((always_inline)) - bool MODE_CPOL(uint8_t mode) {return (mode & 2) != 0;} - inline __attribute__((always_inline)) - void receiveBit(uint8_t bit, uint8_t* data) { - if (MODE_CPHA(Mode)) { - fastDigitalWrite(SckPin, !MODE_CPOL(Mode)); - } - nop; - nop; - fastDigitalWrite(SckPin, - MODE_CPHA(Mode) ? MODE_CPOL(Mode) : !MODE_CPOL(Mode)); - if (fastDigitalRead(MisoPin)) *data |= 1 << bit; - if (!MODE_CPHA(Mode)) { - fastDigitalWrite(SckPin, MODE_CPOL(Mode)); - } - } - //---------------------------------------------------------------------------- - inline __attribute__((always_inline)) - void sendBit(uint8_t bit, uint8_t data) { - if (MODE_CPHA(Mode)) { - fastDigitalWrite(SckPin, !MODE_CPOL(Mode)); - } - fastDigitalWrite(MosiPin, data & (1 << bit)); - fastDigitalWrite(SckPin, - MODE_CPHA(Mode) ? MODE_CPOL(Mode) : !MODE_CPOL(Mode)); - nop; - nop; - if (!MODE_CPHA(Mode)) { - fastDigitalWrite(SckPin, MODE_CPOL(Mode)); - } - } - //---------------------------------------------------------------------------- - inline __attribute__((always_inline)) - void transferBit(uint8_t bit, uint8_t* rxData, uint8_t txData) { - if (MODE_CPHA(Mode)) { - fastDigitalWrite(SckPin, !MODE_CPOL(Mode)); - } - fastDigitalWrite(MosiPin, txData & (1 << bit)); - fastDigitalWrite(SckPin, - MODE_CPHA(Mode) ? MODE_CPOL(Mode) : !MODE_CPOL(Mode)); - if (fastDigitalRead(MisoPin)) *rxData |= 1 << bit; - if (!MODE_CPHA(Mode)) { - fastDigitalWrite(SckPin, MODE_CPOL(Mode)); - } - } - //---------------------------------------------------------------------------- -}; -#endif // SoftSPI_h -/** @} */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/AvrDevelopersGpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/AvrDevelopersGpioPinMap.h deleted file mode 100644 index 3393173..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/AvrDevelopersGpioPinMap.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef AvrDevelopersGpioPinMap_h -#define AvrDevelopersGpioPinMap_h -static const GpioPinMap_t GpioPinMap[] = { - GPIO_PIN(B, 0), // D0 - GPIO_PIN(B, 1), // D1 - GPIO_PIN(B, 2), // D2 - GPIO_PIN(B, 3), // D3 - GPIO_PIN(B, 4), // D4 - GPIO_PIN(B, 5), // D5 - GPIO_PIN(B, 6), // D6 - GPIO_PIN(B, 7), // D7 - GPIO_PIN(D, 0), // D8 - GPIO_PIN(D, 1), // D9 - GPIO_PIN(D, 2), // D10 - GPIO_PIN(D, 3), // D11 - GPIO_PIN(D, 4), // D12 - GPIO_PIN(D, 5), // D13 - GPIO_PIN(D, 6), // D14 - GPIO_PIN(D, 7), // D15 - GPIO_PIN(C, 0), // D16 - GPIO_PIN(C, 1), // D17 - GPIO_PIN(C, 2), // D18 - GPIO_PIN(C, 3), // D19 - GPIO_PIN(C, 4), // D20 - GPIO_PIN(C, 5), // D21 - GPIO_PIN(C, 6), // D22 - GPIO_PIN(C, 7), // D23 - GPIO_PIN(A, 7), // D24 - GPIO_PIN(A, 6), // D25 - GPIO_PIN(A, 5), // D26 - GPIO_PIN(A, 4), // D27 - GPIO_PIN(A, 3), // D28 - GPIO_PIN(A, 2), // D29 - GPIO_PIN(A, 1), // D30 - GPIO_PIN(A, 0) // D31 -}; -#endif // AvrDevelopersGpioPinMap_h \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/BobuinoGpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/BobuinoGpioPinMap.h deleted file mode 100644 index 966786e..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/BobuinoGpioPinMap.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef BobuinoGpioPinMap_h -#define BobuinoGpioPinMap_h -static const GpioPinMap_t GpioPinMap[] = { - GPIO_PIN(B, 0), // D0 - GPIO_PIN(B, 1), // D1 - GPIO_PIN(B, 2), // D2 - GPIO_PIN(B, 3), // D3 - GPIO_PIN(B, 4), // D4 - GPIO_PIN(B, 5), // D5 - GPIO_PIN(B, 6), // D6 - GPIO_PIN(B, 7), // D7 - GPIO_PIN(D, 0), // D8 - GPIO_PIN(D, 1), // D9 - GPIO_PIN(D, 2), // D10 - GPIO_PIN(D, 3), // D11 - GPIO_PIN(D, 4), // D12 - GPIO_PIN(D, 5), // D13 - GPIO_PIN(D, 6), // D14 - GPIO_PIN(D, 7), // D15 - GPIO_PIN(C, 0), // D16 - GPIO_PIN(C, 1), // D17 - GPIO_PIN(C, 2), // D18 - GPIO_PIN(C, 3), // D19 - GPIO_PIN(C, 4), // D20 - GPIO_PIN(C, 5), // D21 - GPIO_PIN(C, 6), // D22 - GPIO_PIN(C, 7), // D23 - GPIO_PIN(A, 0), // D24 - GPIO_PIN(A, 1), // D25 - GPIO_PIN(A, 2), // D26 - GPIO_PIN(A, 3), // D27 - GPIO_PIN(A, 4), // D28 - GPIO_PIN(A, 5), // D29 - GPIO_PIN(A, 6), // D30 - GPIO_PIN(A, 7) // D31 -}; -#endif // BobuinoGpioPinMap_h \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/GpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/GpioPinMap.h deleted file mode 100644 index 4abf99c..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/GpioPinMap.h +++ /dev/null @@ -1,45 +0,0 @@ -#ifndef GpioPinMap_h -#define GpioPinMap_h -#if defined(__AVR_ATmega168__)\ -||defined(__AVR_ATmega168P__)\ -||defined(__AVR_ATmega328P__) -// 168 and 328 Arduinos -#include "UnoGpioPinMap.h" -#elif defined(__AVR_ATmega1280__)\ -|| defined(__AVR_ATmega2560__) -// Mega ADK -#include "MegaGpioPinMap.h" -#elif defined(__AVR_ATmega32U4__) -#ifdef CORE_TEENSY -#include "Teensy2GpioPinMap.h" -#else // CORE_TEENSY -// Leonardo or Yun -#include "LeonardoGpioPinMap.h" -#endif // CORE_TEENSY -#elif defined(__AVR_AT90USB646__)\ -|| defined(__AVR_AT90USB1286__) -// Teensy++ 1.0 & 2.0 -#include "Teensy2ppGpioPinMap.h" -#elif defined(__AVR_ATmega1284P__)\ -|| defined(__AVR_ATmega1284__)\ -|| defined(__AVR_ATmega644P__)\ -|| defined(__AVR_ATmega644__)\ -|| defined(__AVR_ATmega64__)\ -|| defined(__AVR_ATmega32__)\ -|| defined(__AVR_ATmega324__)\ -|| defined(__AVR_ATmega16__) -#ifdef ARDUINO_1284P_AVR_DEVELOPERS -#include "AvrDevelopersGpioPinMap.h" -#elif defined(BOBUINO_PINOUT) || defined(ARDUINO_1284P_BOBUINO) -#include "BobuinoGpioPinMap.h" -#elif defined(ARDUINO_1284P_SLEEPINGBEAUTY) -#include "SleepingBeautyGpioPinMap.h" -#elif defined(STANDARD_PINOUT) || defined(ARDUINO_1284P_STANDARD) -#include "Standard1284GpioPinMap.h" -#else // ARDUINO_1284P_AVR_DEVELOPERS -#error Undefined variant 1284, 644, 324 -#endif // ARDUINO_1284P_AVR_DEVELOPERS -#else // 1284P, 1284, 644 -#error Unknown board type. -#endif // end all boards -#endif // GpioPinMap_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/LeonardoGpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/LeonardoGpioPinMap.h deleted file mode 100644 index bd68d66..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/LeonardoGpioPinMap.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef LeonardoGpioPinMap_h -#define LeonardoGpioPinMap_h -static const GpioPinMap_t GpioPinMap[] = { - GPIO_PIN(D, 2), // D0 - GPIO_PIN(D, 3), // D1 - GPIO_PIN(D, 1), // D2 - GPIO_PIN(D, 0), // D3 - GPIO_PIN(D, 4), // D4 - GPIO_PIN(C, 6), // D5 - GPIO_PIN(D, 7), // D6 - GPIO_PIN(E, 6), // D7 - GPIO_PIN(B, 4), // D8 - GPIO_PIN(B, 5), // D9 - GPIO_PIN(B, 6), // D10 - GPIO_PIN(B, 7), // D11 - GPIO_PIN(D, 6), // D12 - GPIO_PIN(C, 7), // D13 - GPIO_PIN(B, 3), // D14 - GPIO_PIN(B, 1), // D15 - GPIO_PIN(B, 2), // D16 - GPIO_PIN(B, 0), // D17 - GPIO_PIN(F, 7), // D18 - GPIO_PIN(F, 6), // D19 - GPIO_PIN(F, 5), // D20 - GPIO_PIN(F, 4), // D21 - GPIO_PIN(F, 1), // D22 - GPIO_PIN(F, 0), // D23 - GPIO_PIN(D, 4), // D24 - GPIO_PIN(D, 7), // D25 - GPIO_PIN(B, 4), // D26 - GPIO_PIN(B, 5), // D27 - GPIO_PIN(B, 6), // D28 - GPIO_PIN(D, 6) // D29 -}; -#endif // LeonardoGpioPinMap_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/MegaGpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/MegaGpioPinMap.h deleted file mode 100644 index 25e7807..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/MegaGpioPinMap.h +++ /dev/null @@ -1,75 +0,0 @@ -#ifndef MegaGpioPinMap_h -#define MegaGpioPinMap_h -static const GpioPinMap_t GpioPinMap[] = { - GPIO_PIN(E, 0), // D0 - GPIO_PIN(E, 1), // D1 - GPIO_PIN(E, 4), // D2 - GPIO_PIN(E, 5), // D3 - GPIO_PIN(G, 5), // D4 - GPIO_PIN(E, 3), // D5 - GPIO_PIN(H, 3), // D6 - GPIO_PIN(H, 4), // D7 - GPIO_PIN(H, 5), // D8 - GPIO_PIN(H, 6), // D9 - GPIO_PIN(B, 4), // D10 - GPIO_PIN(B, 5), // D11 - GPIO_PIN(B, 6), // D12 - GPIO_PIN(B, 7), // D13 - GPIO_PIN(J, 1), // D14 - GPIO_PIN(J, 0), // D15 - GPIO_PIN(H, 1), // D16 - GPIO_PIN(H, 0), // D17 - GPIO_PIN(D, 3), // D18 - GPIO_PIN(D, 2), // D19 - GPIO_PIN(D, 1), // D20 - GPIO_PIN(D, 0), // D21 - GPIO_PIN(A, 0), // D22 - GPIO_PIN(A, 1), // D23 - GPIO_PIN(A, 2), // D24 - GPIO_PIN(A, 3), // D25 - GPIO_PIN(A, 4), // D26 - GPIO_PIN(A, 5), // D27 - GPIO_PIN(A, 6), // D28 - GPIO_PIN(A, 7), // D29 - GPIO_PIN(C, 7), // D30 - GPIO_PIN(C, 6), // D31 - GPIO_PIN(C, 5), // D32 - GPIO_PIN(C, 4), // D33 - GPIO_PIN(C, 3), // D34 - GPIO_PIN(C, 2), // D35 - GPIO_PIN(C, 1), // D36 - GPIO_PIN(C, 0), // D37 - GPIO_PIN(D, 7), // D38 - GPIO_PIN(G, 2), // D39 - GPIO_PIN(G, 1), // D40 - GPIO_PIN(G, 0), // D41 - GPIO_PIN(L, 7), // D42 - GPIO_PIN(L, 6), // D43 - GPIO_PIN(L, 5), // D44 - GPIO_PIN(L, 4), // D45 - GPIO_PIN(L, 3), // D46 - GPIO_PIN(L, 2), // D47 - GPIO_PIN(L, 1), // D48 - GPIO_PIN(L, 0), // D49 - GPIO_PIN(B, 3), // D50 - GPIO_PIN(B, 2), // D51 - GPIO_PIN(B, 1), // D52 - GPIO_PIN(B, 0), // D53 - GPIO_PIN(F, 0), // D54 - GPIO_PIN(F, 1), // D55 - GPIO_PIN(F, 2), // D56 - GPIO_PIN(F, 3), // D57 - GPIO_PIN(F, 4), // D58 - GPIO_PIN(F, 5), // D59 - GPIO_PIN(F, 6), // D60 - GPIO_PIN(F, 7), // D61 - GPIO_PIN(K, 0), // D62 - GPIO_PIN(K, 1), // D63 - GPIO_PIN(K, 2), // D64 - GPIO_PIN(K, 3), // D65 - GPIO_PIN(K, 4), // D66 - GPIO_PIN(K, 5), // D67 - GPIO_PIN(K, 6), // D68 - GPIO_PIN(K, 7) // D69 -}; -#endif // MegaGpioPinMap_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/SleepingBeautyGpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/SleepingBeautyGpioPinMap.h deleted file mode 100644 index 0ac7301..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/SleepingBeautyGpioPinMap.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef SleepingBeautyGpioPinMap_h -#define SleepingBeautyGpioPinMap_h -static const GpioPinMap_t GpioPinMap[] = { - GPIO_PIN(D, 0), // D0 - GPIO_PIN(D, 1), // D1 - GPIO_PIN(D, 2), // D2 - GPIO_PIN(D, 3), // D3 - GPIO_PIN(B, 0), // D4 - GPIO_PIN(B, 1), // D5 - GPIO_PIN(B, 2), // D6 - GPIO_PIN(B, 3), // D7 - GPIO_PIN(D, 6), // D8 - GPIO_PIN(D, 5), // D9 - GPIO_PIN(B, 4), // D10 - GPIO_PIN(B, 5), // D11 - GPIO_PIN(B, 6), // D12 - GPIO_PIN(B, 7), // D13 - GPIO_PIN(C, 7), // D14 - GPIO_PIN(C, 6), // D15 - GPIO_PIN(A, 5), // D16 - GPIO_PIN(A, 4), // D17 - GPIO_PIN(A, 3), // D18 - GPIO_PIN(A, 2), // D19 - GPIO_PIN(A, 1), // D20 - GPIO_PIN(A, 0), // D21 - GPIO_PIN(D, 4), // D22 - GPIO_PIN(D, 7), // D23 - GPIO_PIN(C, 2), // D24 - GPIO_PIN(C, 3), // D25 - GPIO_PIN(C, 4), // D26 - GPIO_PIN(C, 5), // D27 - GPIO_PIN(C, 1), // D28 - GPIO_PIN(C, 0), // D29 - GPIO_PIN(A, 6), // D30 - GPIO_PIN(A, 7) // D31 -}; -#endif // SleepingBeautyGpioPinMap_h \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Standard1284GpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Standard1284GpioPinMap.h deleted file mode 100644 index 8a1dba3..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Standard1284GpioPinMap.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef Standard1284GpioPinMap_h -#define Standard1284GpioPinMap_h -static const GpioPinMap_t GpioPinMap[] = { - GPIO_PIN(B, 0), // D0 - GPIO_PIN(B, 1), // D1 - GPIO_PIN(B, 2), // D2 - GPIO_PIN(B, 3), // D3 - GPIO_PIN(B, 4), // D4 - GPIO_PIN(B, 5), // D5 - GPIO_PIN(B, 6), // D6 - GPIO_PIN(B, 7), // D7 - GPIO_PIN(D, 0), // D8 - GPIO_PIN(D, 1), // D9 - GPIO_PIN(D, 2), // D10 - GPIO_PIN(D, 3), // D11 - GPIO_PIN(D, 4), // D12 - GPIO_PIN(D, 5), // D13 - GPIO_PIN(D, 6), // D14 - GPIO_PIN(D, 7), // D15 - GPIO_PIN(C, 0), // D16 - GPIO_PIN(C, 1), // D17 - GPIO_PIN(C, 2), // D18 - GPIO_PIN(C, 3), // D19 - GPIO_PIN(C, 4), // D20 - GPIO_PIN(C, 5), // D21 - GPIO_PIN(C, 6), // D22 - GPIO_PIN(C, 7), // D23 - GPIO_PIN(A, 0), // D24 - GPIO_PIN(A, 1), // D25 - GPIO_PIN(A, 2), // D26 - GPIO_PIN(A, 3), // D27 - GPIO_PIN(A, 4), // D28 - GPIO_PIN(A, 5), // D29 - GPIO_PIN(A, 6), // D30 - GPIO_PIN(A, 7) // D31 -}; -#endif // Standard1284GpioPinMap_h \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Teensy2GpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Teensy2GpioPinMap.h deleted file mode 100644 index 3e436c7..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Teensy2GpioPinMap.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef Teensy2GpioPinMap_h -#define Teensy2GpioPinMap_h -static const GpioPinMap_t GpioPinMap[] = { - GPIO_PIN(B, 0), // D0 - GPIO_PIN(B, 1), // D1 - GPIO_PIN(B, 2), // D2 - GPIO_PIN(B, 3), // D3 - GPIO_PIN(B, 7), // D4 - GPIO_PIN(D, 0), // D5 - GPIO_PIN(D, 1), // D6 - GPIO_PIN(D, 2), // D7 - GPIO_PIN(D, 3), // D8 - GPIO_PIN(C, 6), // D9 - GPIO_PIN(C, 7), // D10 - GPIO_PIN(D, 6), // D11 - GPIO_PIN(D, 7), // D12 - GPIO_PIN(B, 4), // D13 - GPIO_PIN(B, 5), // D14 - GPIO_PIN(B, 6), // D15 - GPIO_PIN(F, 7), // D16 - GPIO_PIN(F, 6), // D17 - GPIO_PIN(F, 5), // D18 - GPIO_PIN(F, 4), // D19 - GPIO_PIN(F, 1), // D20 - GPIO_PIN(F, 0), // D21 - GPIO_PIN(D, 4), // D22 - GPIO_PIN(D, 5), // D23 - GPIO_PIN(E, 6), // D24 -}; -#endif // Teensy2GpioPinMap_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Teensy2ppGpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Teensy2ppGpioPinMap.h deleted file mode 100644 index f944991..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/Teensy2ppGpioPinMap.h +++ /dev/null @@ -1,51 +0,0 @@ -#ifndef Teensypp2GpioPinMap_h -#define Teensypp2GpioPinMap_h -static const GpioPinMap_t GpioPinMap[] = { - GPIO_PIN(D, 0), // D0 - GPIO_PIN(D, 1), // D1 - GPIO_PIN(D, 2), // D2 - GPIO_PIN(D, 3), // D3 - GPIO_PIN(D, 4), // D4 - GPIO_PIN(D, 5), // D5 - GPIO_PIN(D, 6), // D6 - GPIO_PIN(D, 7), // D7 - GPIO_PIN(E, 0), // D8 - GPIO_PIN(E, 1), // D9 - GPIO_PIN(C, 0), // D10 - GPIO_PIN(C, 1), // D11 - GPIO_PIN(C, 2), // D12 - GPIO_PIN(C, 3), // D13 - GPIO_PIN(C, 4), // D14 - GPIO_PIN(C, 5), // D15 - GPIO_PIN(C, 6), // D16 - GPIO_PIN(C, 7), // D17 - GPIO_PIN(E, 6), // D18 - GPIO_PIN(E, 7), // D19 - GPIO_PIN(B, 0), // D20 - GPIO_PIN(B, 1), // D21 - GPIO_PIN(B, 2), // D22 - GPIO_PIN(B, 3), // D23 - GPIO_PIN(B, 4), // D24 - GPIO_PIN(B, 5), // D25 - GPIO_PIN(B, 6), // D26 - GPIO_PIN(B, 7), // D27 - GPIO_PIN(A, 0), // D28 - GPIO_PIN(A, 1), // D29 - GPIO_PIN(A, 2), // D30 - GPIO_PIN(A, 3), // D31 - GPIO_PIN(A, 4), // D32 - GPIO_PIN(A, 5), // D33 - GPIO_PIN(A, 6), // D34 - GPIO_PIN(A, 7), // D35 - GPIO_PIN(E, 4), // D36 - GPIO_PIN(E, 5), // D37 - GPIO_PIN(F, 0), // D38 - GPIO_PIN(F, 1), // D39 - GPIO_PIN(F, 2), // D40 - GPIO_PIN(F, 3), // D41 - GPIO_PIN(F, 4), // D42 - GPIO_PIN(F, 5), // D43 - GPIO_PIN(F, 6), // D44 - GPIO_PIN(F, 7), // D45 -}; -#endif // Teensypp2GpioPinMap_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/UnoGpioPinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/UnoGpioPinMap.h deleted file mode 100644 index 2ffbb4e..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SpiDriver/boards/UnoGpioPinMap.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef UnoGpioPinMap_h -#define UnoGpioPinMap_h -static const GpioPinMap_t GpioPinMap[] = { - GPIO_PIN(D, 0), // D0 - GPIO_PIN(D, 1), // D1 - GPIO_PIN(D, 2), // D2 - GPIO_PIN(D, 3), // D3 - GPIO_PIN(D, 4), // D4 - GPIO_PIN(D, 5), // D5 - GPIO_PIN(D, 6), // D6 - GPIO_PIN(D, 7), // D7 - GPIO_PIN(B, 0), // D8 - GPIO_PIN(B, 1), // D9 - GPIO_PIN(B, 2), // D10 - GPIO_PIN(B, 3), // D11 - GPIO_PIN(B, 4), // D12 - GPIO_PIN(B, 5), // D13 - GPIO_PIN(C, 0), // D14 - GPIO_PIN(C, 1), // D15 - GPIO_PIN(C, 2), // D16 - GPIO_PIN(C, 3), // D17 - GPIO_PIN(C, 4), // D18 - GPIO_PIN(C, 5) // D19 -}; -#endif // UnoGpioPinMap_h \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SysCall.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SysCall.h deleted file mode 100644 index b8a2e25..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/SysCall.h +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 SysCall_h -#define SysCall_h -/** - * \file - * \brief SysCall class - */ -#if defined(ARDUINO) -#include -#include -#elif defined(PLATFORM_ID) // Only defined if a Particle device -#include "application.h" -#else // defined(ARDUINO) -#error "Unknown system" -#endif // defined(ARDUINO) -//------------------------------------------------------------------------------ -#ifdef ESP8266 -// undefine F macro if ESP8266. -#undef F -#endif // ESP8266 -//------------------------------------------------------------------------------ -#ifndef F -/** Define macro for strings stored in flash. */ -#define F(str) (str) -#endif // F -//------------------------------------------------------------------------------ -/** \return the time in milliseconds. */ -inline uint16_t curTimeMS() { - return millis(); -} -//------------------------------------------------------------------------------ -/** - * \class SysCall - * \brief SysCall - Class to wrap system calls. - */ -class SysCall { - public: - /** Halt execution of this thread. */ - static void halt() { - while (1) { - yield(); - } - } - /** Yield to other threads. */ - static void yield(); -}; - -#if defined(ESP8266) -inline void SysCall::yield() { - // Avoid ESP8266 bug - delay(0); -} -#elif defined(ARDUINO) -inline void SysCall::yield() { - // Use the external Arduino yield() function. - ::yield(); -} -#elif defined(PLATFORM_ID) // Only defined if a Particle device -inline void SysCall::yield() { - Particle.process(); -} -#else // ESP8266 -inline void SysCall::yield() {} -#endif // ESP8266 -#endif // SysCall_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/sdios.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/sdios.h deleted file mode 100644 index 3a8db59..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/lib/SdFat/src/sdios.h +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) 2011-2018 Bill Greiman - * This file is part of the SdFat library for SD memory cards. - * - * 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 sdios_h -#define sdios_h -/** - * \file - * \brief C++ IO Streams features. - */ -#include "FatLib/fstream.h" -#include "FatLib/ArduinoStream.h" -#endif // sdios_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/Adafruit_ASFcore.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/Adafruit_ASFcore.h deleted file mode 100644 index e69de29..0000000 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/README.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/README.md deleted file mode 100644 index 8de73c7..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# ASF (Atmel Software Framework) for Arduino Zero / Adafruit Feather M0 (SAMD21) - -Copy of ASF (Atmel Software Framework) excerpts for the SAMD21 processor used in the Arduino Zero / Adafruit Feather M0 boards. -You typically won't use this library directly, instead other libraries will depend on this library and use the code -within it to simplify their implementation. - -All code is taken directly from Atmel's ASF: http://www.atmel.com/tools/avrsoftwareframework.aspx?tab=overview - -The code is copyright Atmel and released by them under the following license: - - 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. The name of Atmel may not be used to endorse or promote products derived from this software without specific - prior written permission. - - 4. This software may only be redistributed and used in connection with an Atmel microcontroller product. - - THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A - PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN - NO EVENT SHALL ATMEL 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. diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/clock.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/clock.h deleted file mode 100644 index 549e3e9..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/clock.h +++ /dev/null @@ -1,53 +0,0 @@ -/** - * \file - * - * \brief SAM Clock Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef SYSTEM_CLOCK_H_INCLUDED -#define SYSTEM_CLOCK_H_INCLUDED - -#include "compiler.h" -#include "gclk.h" -#include "clock_feature.h" - -#endif /* SYSTEM_CLOCK_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/clock_feature.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/clock_feature.h deleted file mode 100644 index be63c7c..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/clock_feature.h +++ /dev/null @@ -1,1492 +0,0 @@ -/** - * \file - * - * \brief SAM Clock Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef SYSTEM_CLOCK_FEATURE_H_INCLUDED -#define SYSTEM_CLOCK_FEATURE_H_INCLUDED - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \defgroup asfdoc_sam0_system_clock_group SAM System Clock Management Driver (SYSTEM CLOCK) - * - * This driver for Atmel® | SMART ARM®-based microcontrollers provides an interface for the configuration - * and management of the device's clocking related functions. This includes - * the various clock sources, bus clocks, and generic clocks within the device, - * with functions to manage the enabling, disabling, source selection, and - * prescaling of clocks to various internal peripherals. - * - * The following peripherals are used by this module: - * - * - GCLK (Generic Clock Management) - * - PM (Power Management) - * - SYSCTRL (Clock Source Control) - * - * The following devices can use this module: - * - Atmel | SMART SAM D20/D21 - * - Atmel | SMART SAM R21 - * - Atmel | SMART SAM D10/D11 - * - Atmel | SMART SAM DA0/DA1 - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_system_clock_prerequisites - * - \ref asfdoc_sam0_system_clock_module_overview - * - \ref asfdoc_sam0_system_clock_special_considerations - * - \ref asfdoc_sam0_system_clock_extra_info - * - \ref asfdoc_sam0_system_clock_examples - * - \ref asfdoc_sam0_system_clock_api_overview - * - * - * \section asfdoc_sam0_system_clock_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * - * \section asfdoc_sam0_system_clock_module_overview Module Overview - * The SAM devices contain a sophisticated clocking system, which is designed - * to give the maximum flexibility to the user application. This system allows - * a system designer to tune the performance and power consumption of the device - * in a dynamic manner, to achieve the best trade-off between the two for a - * particular application. - * - * This driver provides a set of functions for the configuration and management - * of the various clock related functionality within the device. - * - * \subsection asfdoc_sam0_system_clock_module_features Driver Feature Macro Definition - * - * - * - * - * - * - * - * - * - *
Driver Feature MacroSupported devices
FEATURE_SYSTEM_CLOCK_DPLLSAMD21, SAMR21, SAMD10, SAMD11, SAMDAx
- * \note The specific features are only available in the driver when the - * selected device supports those features. - * - * \subsection asfdoc_sam0_system_clock_module_overview_clock_sources Clock Sources - * The SAM devices have a number of master clock source modules, each of - * which being capable of producing a stabilized output frequency, which can then - * be fed into the various peripherals and modules within the device. - * - * Possible clock source modules include internal R/C oscillators, internal - * DFLL modules, as well as external crystal oscillators and/or clock inputs. - * - * \subsection asfdoc_sam0_system_clock_module_overview_cpu_clock CPU / Bus Clocks - * The CPU and AHB/APBx buses are clocked by the same physical clock source - * (referred in this module as the Main Clock), however the APBx buses may - * have additional prescaler division ratios set to give each peripheral bus a - * different clock speed. - * - * The general main clock tree for the CPU and associated buses is shown in - * \ref asfdoc_sam0_system_clock_module_clock_tree "the figure below". - * - * \anchor asfdoc_sam0_system_clock_module_clock_tree - * \dot - * digraph overview { - * rankdir=LR; - * clk_src [label="Clock Sources", shape=none, height=0]; - * node [label="CPU Bus" shape=ellipse] cpu_bus; - * node [label="AHB Bus" shape=ellipse] ahb_bus; - * node [label="APBA Bus" shape=ellipse] apb_a_bus; - * node [label="APBB Bus" shape=ellipse] apb_b_bus; - * node [label="APBC Bus" shape=ellipse] apb_c_bus; - * node [label="Main Bus\nPrescaler" shape=square] main_prescaler; - * node [label="APBA Bus\nPrescaler" shape=square] apb_a_prescaler; - * node [label="APBB Bus\nPrescaler" shape=square] apb_b_prescaler; - * node [label="APBC Bus\nPrescaler" shape=square] apb_c_prescaler; - * node [label="", shape=polygon, sides=4, distortion=0.6, orientation=90, style=filled, fillcolor=black, height=0.9, width=0.2] main_clock_mux; - * - * clk_src -> main_clock_mux; - * main_clock_mux -> main_prescaler; - * main_prescaler -> cpu_bus; - * main_prescaler -> ahb_bus; - * main_prescaler -> apb_a_prescaler; - * main_prescaler -> apb_b_prescaler; - * main_prescaler -> apb_c_prescaler; - * apb_a_prescaler -> apb_a_bus; - * apb_b_prescaler -> apb_b_bus; - * apb_c_prescaler -> apb_c_bus; - * } - * \enddot - * - * \subsection asfdoc_sam0_system_clock_module_overview_clock_masking Clock Masking - * To save power, the input clock to one or more peripherals on the AHB and APBx - * buses can be masked away - when masked, no clock is passed into the module. - * Disabling of clocks of unused modules will prevent all access to the masked - * module, but will reduce the overall device power consumption. - * - * \subsection asfdoc_sam0_system_clock_module_overview_gclk Generic Clocks - * Within the SAM devices there are a number of Generic Clocks; these are used to - * provide clocks to the various peripheral clock domains in the device in a - * standardized manner. One or more master source clocks can be selected as the - * input clock to a Generic Clock Generator, which can prescale down the input - * frequency to a slower rate for use in a peripheral. - * - * Additionally, a number of individually selectable Generic Clock Channels are - * provided, which multiplex and gate the various generator outputs for one or - * more peripherals within the device. This setup allows for a single common - * generator to feed one or more channels, which can then be enabled or disabled - * individually as required. - * - * \anchor asfdoc_sam0_system_clock_module_chain_overview - * \dot - * digraph overview { - * rankdir=LR; - * node [label="Clock\nSource a" shape=square] system_clock_source; - * node [label="Generator 1" shape=square] clock_gen; - * node [label="Channel x" shape=square] clock_chan0; - * node [label="Channel y" shape=square] clock_chan1; - * node [label="Peripheral x" shape=ellipse style=filled fillcolor=lightgray] peripheral0; - * node [label="Peripheral y" shape=ellipse style=filled fillcolor=lightgray] peripheral1; - * - * system_clock_source -> clock_gen; - * clock_gen -> clock_chan0; - * clock_chan0 -> peripheral0; - * clock_gen -> clock_chan1; - * clock_chan1 -> peripheral1; - * } - * \enddot - * - * \subsubsection asfdoc_sam0_system_clock_module_chain_example Clock Chain Example - * An example setup of a complete clock chain within the device is shown in - * \ref asfdoc_sam0_system_clock_module_chain_example_fig "the figure below". - * - * \anchor asfdoc_sam0_system_clock_module_chain_example_fig - * \dot - * digraph overview { - * rankdir=LR; - * node [label="External\nOscillator" shape=square] system_clock_source0; - * node [label="Generator 0" shape=square] clock_gen0; - * node [label="Channel x" shape=square] clock_chan0; - * node [label="Core CPU" shape=ellipse style=filled fillcolor=lightgray] peripheral0; - * - * system_clock_source0 -> clock_gen0; - * clock_gen0 -> clock_chan0; - * clock_chan0 -> peripheral0; - * node [label="8MHz R/C\nOscillator (OSC8M)" shape=square fillcolor=white] system_clock_source1; - * node [label="Generator 1" shape=square] clock_gen1; - * node [label="Channel y" shape=square] clock_chan1; - * node [label="Channel z" shape=square] clock_chan2; - * node [label="SERCOM\nModule" shape=ellipse style=filled fillcolor=lightgray] peripheral1; - * node [label="Timer\nModule" shape=ellipse style=filled fillcolor=lightgray] peripheral2; - * - * system_clock_source1 -> clock_gen1; - * clock_gen1 -> clock_chan1; - * clock_gen1 -> clock_chan2; - * clock_chan1 -> peripheral1; - * clock_chan2 -> peripheral2; - * } - * \enddot - * - * \subsubsection asfdoc_sam0_system_clock_module_overview_gclk_generators Generic Clock Generators - * Each Generic Clock generator within the device can source its input clock - * from one of the provided Source Clocks, and prescale the output for one or - * more Generic Clock Channels in a one-to-many relationship. The generators - * thus allow for several clocks to be generated of different frequencies, - * power usages, and accuracies, which can be turned on and off individually to - * disable the clocks to multiple peripherals as a group. - * - * \subsubsection asfdoc_sam0_system_clock_module_overview_gclk_channels Generic Clock Channels - * To connect a Generic Clock Generator to a peripheral within the - * device, a Generic Clock Channel is used. Each peripheral or - * peripheral group has an associated Generic Clock Channel, which serves as the - * clock input for the peripheral(s). To supply a clock to the peripheral - * module(s), the associated channel must be connected to a running Generic - * Clock Generator and the channel enabled. - * - * \section asfdoc_sam0_system_clock_special_considerations Special Considerations - * - * There are no special considerations for this module. - * - * - * \section asfdoc_sam0_system_clock_extra_info Extra Information - * - * For extra information, see \ref asfdoc_sam0_system_clock_extra. This includes: - * - \ref asfdoc_sam0_system_clock_extra_acronyms - * - \ref asfdoc_sam0_system_clock_extra_dependencies - * - \ref asfdoc_sam0_system_clock_extra_errata - * - \ref asfdoc_sam0_system_clock_extra_history - * - * - * \section asfdoc_sam0_system_clock_examples Examples - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_system_clock_exqsg. - * - * - * \section asfdoc_sam0_system_clock_api_overview API Overview - * @{ - */ - -#include "compiler.h" -#include "gclk.h" - -/** - * \name Driver Feature Definition - * Define system clock features set according to different device family. - * @{ - */ -#if (SAMD21) || (SAMR21) || (SAMD11) || (SAMD10) || (SAMDA1) || defined(__DOXYGEN__) -/** Digital Phase Locked Loop (DPLL) feature support. */ -# define FEATURE_SYSTEM_CLOCK_DPLL -#endif -/*@}*/ - -/** - * \brief Available start-up times for the XOSC32K. - * - * Available external 32KHz oscillator start-up times, as a number of external - * clock cycles. - */ -enum system_xosc32k_startup { - /** Wait zero clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_0, - /** Wait 32 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_32, - /** Wait 2048 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_2048, - /** Wait 4096 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_4096, - /** Wait 16384 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_16384, - /** Wait 32768 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_32768, - /** Wait 65536 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_65536, - /** Wait 131072 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC32K_STARTUP_131072, -}; - -/** - * \brief Available start-up times for the XOSC. - * - * Available external oscillator start-up times, as a number of external clock - * cycles. - */ -enum system_xosc_startup { - /** Wait one clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_1, - /** Wait two clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_2, - /** Wait four clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_4, - /** Wait eight clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_8, - /** Wait 16 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_16, - /** Wait 32 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_32, - /** Wait 64 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_64, - /** Wait 128 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_128, - /** Wait 256 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_256, - /** Wait 512 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_512, - /** Wait 1024 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_1024, - /** Wait 2048 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_2048, - /** Wait 4096 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_4096, - /** Wait 8192 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_8192, - /** Wait 16384 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_16384, - /** Wait 32768 clock cycles until the clock source is considered stable. */ - SYSTEM_XOSC_STARTUP_32768, -}; - -/** - * \brief Available start-up times for the OSC32K. - * - * Available internal 32KHz oscillator start-up times, as a number of internal - * OSC32K clock cycles. - */ -enum system_osc32k_startup { - /** Wait three clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_3, - /** Wait four clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_4, - /** Wait six clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_6, - /** Wait ten clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_10, - /** Wait 18 clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_18, - /** Wait 34 clock cycles until the clock source is considered stable */ - SYSTEM_OSC32K_STARTUP_34, - /** Wait 66 clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_66, - /** Wait 130 clock cycles until the clock source is considered stable. */ - SYSTEM_OSC32K_STARTUP_130, -}; - -/** - * \brief Division prescalers for the internal 8MHz system clock. - * - * Available prescalers for the internal 8MHz (nominal) system clock. - */ -enum system_osc8m_div { - /** Do not divide the 8MHz RC oscillator output. */ - SYSTEM_OSC8M_DIV_1, - /** Divide the 8MHz RC oscillator output by two. */ - SYSTEM_OSC8M_DIV_2, - /** Divide the 8MHz RC oscillator output by four. */ - SYSTEM_OSC8M_DIV_4, - /** Divide the 8MHz RC oscillator output by eight. */ - SYSTEM_OSC8M_DIV_8, -}; - -/** - * \brief Frequency range for the internal 8MHz RC oscillator. - * - * Internal 8MHz RC oscillator frequency range setting - */ -enum system_osc8m_frequency_range { - /** Frequency range 4MHz to 6MHz. */ - SYSTEM_OSC8M_FREQUENCY_RANGE_4_TO_6, - /** Frequency range 6MHz to 8MHz. */ - SYSTEM_OSC8M_FREQUENCY_RANGE_6_TO_8, - /** Frequency range 8MHz to 11MHz. */ - SYSTEM_OSC8M_FREQUENCY_RANGE_8_TO_11, - /** Frequency range 11MHz to 15MHz. */ - SYSTEM_OSC8M_FREQUENCY_RANGE_11_TO_15, -}; - -/** - * \brief Main CPU and APB/AHB bus clock source prescaler values. - * - * Available division ratios for the CPU and APB/AHB bus clocks. - */ -enum system_main_clock_div { - /** Divide Main clock by one. */ - SYSTEM_MAIN_CLOCK_DIV_1, - /** Divide Main clock by two. */ - SYSTEM_MAIN_CLOCK_DIV_2, - /** Divide Main clock by four. */ - SYSTEM_MAIN_CLOCK_DIV_4, - /** Divide Main clock by eight. */ - SYSTEM_MAIN_CLOCK_DIV_8, - /** Divide Main clock by 16. */ - SYSTEM_MAIN_CLOCK_DIV_16, - /** Divide Main clock by 32. */ - SYSTEM_MAIN_CLOCK_DIV_32, - /** Divide Main clock by 64. */ - SYSTEM_MAIN_CLOCK_DIV_64, - /** Divide Main clock by 128. */ - SYSTEM_MAIN_CLOCK_DIV_128, -}; - -/** - * \brief External clock source types. - * - * Available external clock source types. - */ -enum system_clock_external { - /** The external clock source is a crystal oscillator. */ - SYSTEM_CLOCK_EXTERNAL_CRYSTAL, - /** The connected clock source is an external logic level clock signal. */ - SYSTEM_CLOCK_EXTERNAL_CLOCK, -}; - -/** - * \brief Operating modes of the DFLL clock source. - * - * Available operating modes of the DFLL clock source module. - */ -enum system_clock_dfll_loop_mode { - /** The DFLL is operating in open loop mode with no feedback. */ - SYSTEM_CLOCK_DFLL_LOOP_MODE_OPEN, - /** The DFLL is operating in closed loop mode with frequency feedback from - * a low frequency reference clock. - */ - SYSTEM_CLOCK_DFLL_LOOP_MODE_CLOSED = SYSCTRL_DFLLCTRL_MODE, - -#ifdef SYSCTRL_DFLLCTRL_USBCRM - /** The DFLL is operating in USB recovery mode with frequency feedback - * from USB SOF. - */ - SYSTEM_CLOCK_DFLL_LOOP_MODE_USB_RECOVERY = SYSCTRL_DFLLCTRL_USBCRM, -#endif -}; - -/** - * \brief Locking behavior for the DFLL during device wake-up. - * - * DFLL lock behavior modes on device wake-up from sleep. - */ -enum system_clock_dfll_wakeup_lock { - /** Keep DFLL lock when the device wakes from sleep. */ - SYSTEM_CLOCK_DFLL_WAKEUP_LOCK_KEEP, - /** Lose DFLL lock when the devices wakes from sleep. */ - SYSTEM_CLOCK_DFLL_WAKEUP_LOCK_LOSE = SYSCTRL_DFLLCTRL_LLAW, -}; - -/** - * \brief Fine tracking behavior for the DFLL once a lock has been acquired. - * - * DFLL fine tracking behavior modes after a lock has been acquired. - */ -enum system_clock_dfll_stable_tracking { - /** Keep tracking after the DFLL has gotten a fine lock. */ - SYSTEM_CLOCK_DFLL_STABLE_TRACKING_TRACK_AFTER_LOCK, - /** Stop tracking after the DFLL has gotten a fine lock. */ - SYSTEM_CLOCK_DFLL_STABLE_TRACKING_FIX_AFTER_LOCK = SYSCTRL_DFLLCTRL_STABLE, -}; - -/** - * \brief Chill-cycle behavior of the DFLL module. - * - * DFLL chill-cycle behavior modes of the DFLL module. A chill cycle is a period - * of time when the DFLL output frequency is not measured by the unit, to allow - * the output to stabilize after a change in the input clock source. - */ -enum system_clock_dfll_chill_cycle { - /** Enable a chill cycle, where the DFLL output frequency is not measured. */ - SYSTEM_CLOCK_DFLL_CHILL_CYCLE_ENABLE, - /** Disable a chill cycle, where the DFLL output frequency is not measured. */ - SYSTEM_CLOCK_DFLL_CHILL_CYCLE_DISABLE = SYSCTRL_DFLLCTRL_CCDIS, -}; - -/** - * \brief QuickLock settings for the DFLL module. - * - * DFLL QuickLock settings for the DFLL module, to allow for a faster lock of - * the DFLL output frequency at the expense of accuracy. - */ -enum system_clock_dfll_quick_lock { - /** Enable the QuickLock feature for looser lock requirements on the DFLL. */ - SYSTEM_CLOCK_DFLL_QUICK_LOCK_ENABLE, - /** Disable the QuickLock feature for strict lock requirements on the DFLL. */ - SYSTEM_CLOCK_DFLL_QUICK_LOCK_DISABLE = SYSCTRL_DFLLCTRL_QLDIS, -}; - -/** - * \brief Available clock sources in the system. - * - * Clock sources available to the GCLK generators. - */ -enum system_clock_source { - /** Internal 8MHz RC oscillator. */ - SYSTEM_CLOCK_SOURCE_OSC8M = GCLK_SOURCE_OSC8M, - /** Internal 32KHz RC oscillator. */ - SYSTEM_CLOCK_SOURCE_OSC32K = GCLK_SOURCE_OSC32K, - /** External oscillator. */ - SYSTEM_CLOCK_SOURCE_XOSC = GCLK_SOURCE_XOSC , - /** External 32KHz oscillator. */ - SYSTEM_CLOCK_SOURCE_XOSC32K = GCLK_SOURCE_XOSC32K, - /** Digital Frequency Locked Loop (DFLL). */ - SYSTEM_CLOCK_SOURCE_DFLL = GCLK_SOURCE_DFLL48M, - /** Internal Ultra Low Power 32KHz oscillator. */ - SYSTEM_CLOCK_SOURCE_ULP32K = GCLK_SOURCE_OSCULP32K, - /** Generator input pad. */ - SYSTEM_CLOCK_SOURCE_GCLKIN = GCLK_SOURCE_GCLKIN, - /** Generic clock generator one output. */ - SYSTEM_CLOCK_SOURCE_GCLKGEN1 = GCLK_SOURCE_GCLKGEN1, -#ifdef FEATURE_SYSTEM_CLOCK_DPLL - /** Digital Phase Locked Loop (DPLL). - * Check \c FEATURE_SYSTEM_CLOCK_DPLL for which device support it. - */ - SYSTEM_CLOCK_SOURCE_DPLL = GCLK_SOURCE_FDPLL, -#endif -}; - -/** - * \brief List of APB peripheral buses. - * - * Available bus clock domains on the APB bus. - */ -enum system_clock_apb_bus { - /** Peripheral bus A on the APB bus. */ - SYSTEM_CLOCK_APB_APBA, - /** Peripheral bus B on the APB bus. */ - SYSTEM_CLOCK_APB_APBB, - /** Peripheral bus C on the APB bus. */ - SYSTEM_CLOCK_APB_APBC, -}; - -/** - * \brief Configuration structure for XOSC. - * - * External oscillator clock configuration structure. - */ -struct system_clock_source_xosc_config { - /** External clock type. */ - enum system_clock_external external_clock; - /** Crystal oscillator start-up time. */ - enum system_xosc_startup startup_time; - /** Enable automatic amplitude gain control. */ - bool auto_gain_control; - /** External clock/crystal frequency. */ - uint32_t frequency; - /** Keep the XOSC enabled in standby sleep mode. */ - bool run_in_standby; - /** Run On Demand. If this is set the XOSC won't run - * until requested by a peripheral. */ - bool on_demand; -}; - -/** - * \brief Configuration structure for XOSC32K. - * - * External 32KHz oscillator clock configuration structure. - */ -struct system_clock_source_xosc32k_config { - /** External clock type. */ - enum system_clock_external external_clock; - /** Crystal oscillator start-up time. */ - enum system_xosc32k_startup startup_time; - /** Enable automatic amplitude control. */ - bool auto_gain_control; - /** Enable 1KHz output. */ - bool enable_1khz_output; - /** Enable 32KHz output. */ - bool enable_32khz_output; - /** External clock/crystal frequency. */ - uint32_t frequency; - /** Keep the XOSC32K enabled in standby sleep mode. */ - bool run_in_standby; - /** Run On Demand. If this is set the XOSC32K won't run - * until requested by a peripheral. */ - bool on_demand; - /** Lock configuration after it has been written, - * a device reset will release the lock. */ - bool write_once; -}; - -/** - * \brief Configuration structure for OSC8M. - * - * Internal 8MHz (nominal) oscillator configuration structure. - */ -struct system_clock_source_osc8m_config { - /** Internal 8MHz RC oscillator prescaler. */ - enum system_osc8m_div prescaler; - /** Keep the OSC8M enabled in standby sleep mode. */ - bool run_in_standby; - /** Run On Demand. If this is set the OSC8M won't run - * until requested by a peripheral. */ - bool on_demand; -}; - -/** - * \brief Configuration structure for OSC32K. - * - * Internal 32KHz (nominal) oscillator configuration structure. - */ -struct system_clock_source_osc32k_config { - /** Startup time. */ - enum system_osc32k_startup startup_time; - /** Enable 1KHz output. */ - bool enable_1khz_output; - /** Enable 32KHz output. */ - bool enable_32khz_output; - /** Keep the OSC32K enabled in standby sleep mode. */ - bool run_in_standby; - /** Run On Demand. If this is set the OSC32K won't run - * until requested by a peripheral. */ - bool on_demand; - /** Lock configuration after it has been written, - * a device reset will release the lock. */ - bool write_once; -}; - -/** - * \brief Configuration structure for DFLL. - * - * DFLL oscillator configuration structure. - */ -struct system_clock_source_dfll_config { - /** Loop mode. */ - enum system_clock_dfll_loop_mode loop_mode; - /** Run On Demand. If this is set the DFLL won't run - * until requested by a peripheral. */ - bool on_demand; - /** Enable Quick Lock. */ - enum system_clock_dfll_quick_lock quick_lock; - /** Enable Chill Cycle. */ - enum system_clock_dfll_chill_cycle chill_cycle; - /** DFLL lock state on wakeup. */ - enum system_clock_dfll_wakeup_lock wakeup_lock; - /** DFLL tracking after fine lock. */ - enum system_clock_dfll_stable_tracking stable_tracking; - /** Coarse calibration value (Open loop mode). */ - uint8_t coarse_value; - /** Fine calibration value (Open loop mode). */ - uint16_t fine_value; - /** Coarse adjustment maximum step size (Closed loop mode). */ - uint8_t coarse_max_step; - /** Fine adjustment maximum step size (Closed loop mode). */ - uint16_t fine_max_step; - /** DFLL multiply factor (Closed loop mode. */ - uint16_t multiply_factor; -}; - -/** - * \name External Oscillator Management - * @{ - */ - -/** - * \brief Retrieve the default configuration for XOSC. - * - * Fills a configuration structure with the default configuration for an - * external oscillator module: - * - External Crystal - * - Start-up time of 16384 external clock cycles - * - Automatic crystal gain control mode enabled - * - Frequency of 12MHz - * - Don't run in STANDBY sleep mode - * - Run only when requested by peripheral (on demand) - * - * \param[out] config Configuration structure to fill with default values - */ -static inline void system_clock_source_xosc_get_config_defaults( - struct system_clock_source_xosc_config *const config) -{ - Assert(config); - - config->external_clock = SYSTEM_CLOCK_EXTERNAL_CRYSTAL; - config->startup_time = SYSTEM_XOSC_STARTUP_16384; - config->auto_gain_control = true; - config->frequency = 12000000UL; - config->run_in_standby = false; - config->on_demand = true; -} - -void system_clock_source_xosc_set_config( - struct system_clock_source_xosc_config *const config); - -/** - * @} - */ - - -/** - * \name External 32KHz Oscillator Management - * @{ - */ - -/** - * \brief Retrieve the default configuration for XOSC32K. - * - * Fills a configuration structure with the default configuration for an - * external 32KHz oscillator module: - * - External Crystal - * - Start-up time of 16384 external clock cycles - * - Automatic crystal gain control mode disabled - * - Frequency of 32.768KHz - * - 1KHz clock output disabled - * - 32KHz clock output enabled - * - Don't run in STANDBY sleep mode - * - Run only when requested by peripheral (on demand) - * - Don't lock registers after configuration has been written - * - * \param[out] config Configuration structure to fill with default values - */ -static inline void system_clock_source_xosc32k_get_config_defaults( - struct system_clock_source_xosc32k_config *const config) -{ - Assert(config); - - config->external_clock = SYSTEM_CLOCK_EXTERNAL_CRYSTAL; - config->startup_time = SYSTEM_XOSC32K_STARTUP_16384; - config->auto_gain_control = false; - config->frequency = 32768UL; - config->enable_1khz_output = false; - config->enable_32khz_output = true; - config->run_in_standby = false; - config->on_demand = true; - config->write_once = false; -} - -void system_clock_source_xosc32k_set_config( - struct system_clock_source_xosc32k_config *const config); -/** - * @} - */ - - -/** - * \name Internal 32KHz Oscillator Management - * @{ - */ - -/** - * \brief Retrieve the default configuration for OSC32K. - * - * Fills a configuration structure with the default configuration for an - * internal 32KHz oscillator module: - * - 1KHz clock output enabled - * - 32KHz clock output enabled - * - Don't run in STANDBY sleep mode - * - Run only when requested by peripheral (on demand) - * - Set startup time to 130 cycles - * - Don't lock registers after configuration has been written - * - * \param[out] config Configuration structure to fill with default values - */ -static inline void system_clock_source_osc32k_get_config_defaults( - struct system_clock_source_osc32k_config *const config) -{ - Assert(config); - - config->enable_1khz_output = true; - config->enable_32khz_output = true; - config->run_in_standby = false; - config->on_demand = true; - config->startup_time = SYSTEM_OSC32K_STARTUP_130; - config->write_once = false; -} - -void system_clock_source_osc32k_set_config( - struct system_clock_source_osc32k_config *const config); - -/** - * @} - */ - - -/** - * \name Internal 8MHz Oscillator Management - * @{ - */ - -/** - * \brief Retrieve the default configuration for OSC8M. - * - * Fills a configuration structure with the default configuration for an - * internal 8MHz (nominal) oscillator module: - * - Clock output frequency divided by a factor of eight - * - Don't run in STANDBY sleep mode - * - Run only when requested by peripheral (on demand) - * - * \param[out] config Configuration structure to fill with default values - */ -static inline void system_clock_source_osc8m_get_config_defaults( - struct system_clock_source_osc8m_config *const config) -{ - Assert(config); - - config->prescaler = SYSTEM_OSC8M_DIV_8; - config->run_in_standby = false; - config->on_demand = true; -} - -void system_clock_source_osc8m_set_config( - struct system_clock_source_osc8m_config *const config); - -/** - * @} - */ - - -/** - * \name Internal DFLL Management - * @{ - */ - -/** - * \brief Retrieve the default configuration for DFLL. - * - * Fills a configuration structure with the default configuration for a - * DFLL oscillator module: - * - Open loop mode - * - QuickLock mode enabled - * - Chill cycle enabled - * - Output frequency lock maintained during device wake-up - * - Continuous tracking of the output frequency - * - Default tracking values at the mid-points for both coarse and fine - * tracking parameters - * - Don't run in STANDBY sleep mode - * - Run only when requested by peripheral (on demand) - * - * \param[out] config Configuration structure to fill with default values - */ -static inline void system_clock_source_dfll_get_config_defaults( - struct system_clock_source_dfll_config *const config) -{ - Assert(config); - - config->loop_mode = SYSTEM_CLOCK_DFLL_LOOP_MODE_OPEN; - config->quick_lock = SYSTEM_CLOCK_DFLL_QUICK_LOCK_ENABLE; - config->chill_cycle = SYSTEM_CLOCK_DFLL_CHILL_CYCLE_ENABLE; - config->wakeup_lock = SYSTEM_CLOCK_DFLL_WAKEUP_LOCK_KEEP; - config->stable_tracking = SYSTEM_CLOCK_DFLL_STABLE_TRACKING_TRACK_AFTER_LOCK; - config->on_demand = true; - - /* Open loop mode calibration value */ - config->coarse_value = 0x1f / 4; /* Midpoint */ - config->fine_value = 0xff / 4; /* Midpoint */ - - /* Closed loop mode */ - config->coarse_max_step = 1; - config->fine_max_step = 1; - config->multiply_factor = 6; /* Multiply 8MHz by 6 to get 48MHz */ -} - -void system_clock_source_dfll_set_config( - struct system_clock_source_dfll_config *const config); - -/** - * @} - */ - -/** - * \name Clock Source Management - * @{ - */ -enum status_code system_clock_source_write_calibration( - const enum system_clock_source system_clock_source, - const uint16_t calibration_value, - const uint8_t freq_range); - -enum status_code system_clock_source_enable( - const enum system_clock_source system_clock_source); - -enum status_code system_clock_source_disable( - const enum system_clock_source clk_source); - -bool system_clock_source_is_ready( - const enum system_clock_source clk_source); - -uint32_t system_clock_source_get_hz( - const enum system_clock_source clk_source); - -/** - * @} - */ - -/** - * \name Main Clock Management - * @{ - */ - -/** - * \brief Set main CPU clock divider. - * - * Sets the clock divider used on the main clock to provide the CPU clock. - * - * \param[in] divider CPU clock divider to set - */ -static inline void system_cpu_clock_set_divider( - const enum system_main_clock_div divider) -{ - Assert(((uint32_t)divider & PM_CPUSEL_CPUDIV_Msk) == divider); - PM->CPUSEL.reg = (uint32_t)divider; -} - -/** - * \brief Retrieves the current frequency of the CPU core. - * - * Retrieves the operating frequency of the CPU core, obtained from the main - * generic clock and the set CPU bus divider. - * - * \return Current CPU frequency in Hz. - */ -static inline uint32_t system_cpu_clock_get_hz(void) -{ - return (system_gclk_gen_get_hz(GCLK_GENERATOR_0) >> PM->CPUSEL.reg); -} - -/** - * \brief Set APBx clock divider. - * - * Set the clock divider used on the main clock to provide the clock for the - * given APBx bus. - * - * \param[in] divider APBx bus divider to set - * \param[in] bus APBx bus to set divider - * - * \returns Status of the clock division change operation. - * - * \retval STATUS_ERR_INVALID_ARG Invalid bus ID was given - * \retval STATUS_OK The APBx clock was set successfully - */ -static inline enum status_code system_apb_clock_set_divider( - const enum system_clock_apb_bus bus, - const enum system_main_clock_div divider) -{ - switch (bus) { - case SYSTEM_CLOCK_APB_APBA: - PM->APBASEL.reg = (uint32_t)divider; - break; - case SYSTEM_CLOCK_APB_APBB: - PM->APBBSEL.reg = (uint32_t)divider; - break; - case SYSTEM_CLOCK_APB_APBC: - PM->APBCSEL.reg = (uint32_t)divider; - break; - default: - Assert(false); - return STATUS_ERR_INVALID_ARG; - } - - return STATUS_OK; -} - -/** - * \brief Retrieves the current frequency of a ABPx. - * - * Retrieves the operating frequency of an APBx bus, obtained from the main - * generic clock and the set APBx bus divider. - * - * \return Current APBx bus frequency in Hz. - */ -static inline uint32_t system_apb_clock_get_hz( - const enum system_clock_apb_bus bus) -{ - uint16_t bus_divider = 0; - - switch (bus) { - case SYSTEM_CLOCK_APB_APBA: - bus_divider = PM->APBASEL.reg; - break; - case SYSTEM_CLOCK_APB_APBB: - bus_divider = PM->APBBSEL.reg; - break; - case SYSTEM_CLOCK_APB_APBC: - bus_divider = PM->APBCSEL.reg; - break; - default: - Assert(false); - return 0; - } - - return (system_gclk_gen_get_hz(GCLK_GENERATOR_0) >> bus_divider); -} - - -/** - * @} - */ - -/** - * \name Bus Clock Masking - * @{ - */ - -/** - * \brief Set bits in the clock mask for the AHB bus. - * - * This function will set bits in the clock mask for the AHB bus. - * Any bits set to 1 will enable that clock, 0 bits in the mask - * will be ignored. - * - * \param[in] ahb_mask AHB clock mask to enable - */ -static inline void system_ahb_clock_set_mask( - const uint32_t ahb_mask) -{ - PM->AHBMASK.reg |= ahb_mask; -} - -/** - * \brief Clear bits in the clock mask for the AHB bus. - * - * This function will clear bits in the clock mask for the AHB bus. - * Any bits set to 1 will disable that clock, 0 bits in the mask - * will be ignored. - * - * \param[in] ahb_mask AHB clock mask to disable - */ -static inline void system_ahb_clock_clear_mask( - const uint32_t ahb_mask) -{ - PM->AHBMASK.reg &= ~ahb_mask; -} - -/** - * \brief Set bits in the clock mask for an APBx bus. - * - * This function will set bits in the clock mask for an APBx bus. - * Any bits set to 1 will enable the corresponding module clock, zero bits in - * the mask will be ignored. - * - * \param[in] mask APBx clock mask, a \c SYSTEM_CLOCK_APB_APBx constant from - * the device header files - * \param[in] bus Bus to set clock mask bits for, a mask of \c PM_APBxMASK_* - * constants from the device header files - * - * \returns Status indicating the result of the clock mask change operation. - * - * \retval STATUS_ERR_INVALID_ARG Invalid bus given - * \retval STATUS_OK The clock mask was set successfully - */ -static inline enum status_code system_apb_clock_set_mask( - const enum system_clock_apb_bus bus, - const uint32_t mask) -{ - switch (bus) { - case SYSTEM_CLOCK_APB_APBA: - PM->APBAMASK.reg |= mask; - break; - - case SYSTEM_CLOCK_APB_APBB: - PM->APBBMASK.reg |= mask; - break; - - case SYSTEM_CLOCK_APB_APBC: - PM->APBCMASK.reg |= mask; - break; - - default: - Assert(false); - return STATUS_ERR_INVALID_ARG; - - } - - return STATUS_OK; -} - -/** - * \brief Clear bits in the clock mask for an APBx bus. - * - * This function will clear bits in the clock mask for an APBx bus. - * Any bits set to 1 will disable the corresponding module clock, zero bits in - * the mask will be ignored. - * - * \param[in] mask APBx clock mask, a \c SYSTEM_CLOCK_APB_APBx constant from - * the device header files - * \param[in] bus Bus to clear clock mask bits - * - * \returns Status indicating the result of the clock mask change operation. - * - * \retval STATUS_ERR_INVALID_ARG Invalid bus ID was given - * \retval STATUS_OK The clock mask was changed successfully - */ -static inline enum status_code system_apb_clock_clear_mask( - const enum system_clock_apb_bus bus, - const uint32_t mask) -{ - switch (bus) { - case SYSTEM_CLOCK_APB_APBA: - PM->APBAMASK.reg &= ~mask; - break; - - case SYSTEM_CLOCK_APB_APBB: - PM->APBBMASK.reg &= ~mask; - break; - - case SYSTEM_CLOCK_APB_APBC: - PM->APBCMASK.reg &= ~mask; - break; - - default: - Assert(false); - return STATUS_ERR_INVALID_ARG; - } - - return STATUS_OK; -} - -/** - * @} - */ - -#ifdef FEATURE_SYSTEM_CLOCK_DPLL -/** - * \brief Reference clock source of the DPLL module. - */ -enum system_clock_source_dpll_reference_clock { - /** Select XOSC32K as clock reference. */ - SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_XOSC32K, - /** Select XOSC as clock reference. */ - SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_XOSC, - /** Select GCLK as clock reference. */ - SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_GCLK, -}; - -/** - * \brief Lock time-out value of the DPLL module. - */ -enum system_clock_source_dpll_lock_time { - /** Set no time-out as default. */ - SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_DEFAULT, - /** Set time-out if no lock within 8ms. */ - SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_8MS = 0x04, - /** Set time-out if no lock within 9ms. */ - SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_9MS, - /** Set time-out if no lock within 10ms. */ - SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_10MS, - /** Set time-out if no lock within 11ms. */ - SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_11MS, -}; - -/** - * \brief Filter type of the DPLL module. - */ -enum system_clock_source_dpll_filter { - /** Default filter mode. */ - SYSTEM_CLOCK_SOURCE_DPLL_FILTER_DEFAULT, - /** Low bandwidth filter. */ - SYSTEM_CLOCK_SOURCE_DPLL_FILTER_LOW_BANDWIDTH_FILTER, - /** High bandwidth filter. */ - SYSTEM_CLOCK_SOURCE_DPLL_FILTER_HIGH_BANDWIDTH_FILTER, - /** High damping filter. */ - SYSTEM_CLOCK_SOURCE_DPLL_FILTER_HIGH_DAMPING_FILTER, -}; - -/** - * \brief Configuration structure for DPLL. - * - * DPLL oscillator configuration structure. - */ -struct system_clock_source_dpll_config { - /** Run On Demand. If this is set the DPLL won't run - * until requested by a peripheral. */ - bool on_demand; - /** Keep the DPLL enabled in standby sleep mode. */ - bool run_in_standby; - /** Bypass lock signal. */ - bool lock_bypass; - /** Wake up fast. If this is set DPLL output clock is enabled after - * the startup time. */ - bool wake_up_fast; - /** Enable low power mode. */ - bool low_power_enable; - - /** Output frequency of the clock. */ - uint32_t output_frequency; - /** Reference frequency of the clock. */ - uint32_t reference_frequency; - /** Devider of reference clock. */ - uint16_t reference_divider; - - /** Filter type of the DPLL module. */ - enum system_clock_source_dpll_filter filter; - /** Lock time-out value of the DPLL module. */ - enum system_clock_source_dpll_lock_time lock_time; - /** Reference clock source of the DPLL module. */ - enum system_clock_source_dpll_reference_clock reference_clock; -}; - -/** - * \name Internal DPLL Management - * @{ - */ - -/** - * \brief Retrieve the default configuration for DPLL. - * - * Fills a configuration structure with the default configuration for a - * DPLL oscillator module: - * - Run only when requested by peripheral (on demand) - * - Don't run in STANDBY sleep mode - * - Lock bypass disabled - * - Fast wake up disabled - * - Low power mode disabled - * - Output frequency is 48MHz - * - Reference clock frequency is 32768Hz - * - Not divide reference clock - * - Select REF0 as reference clock - * - Set lock time to default mode - * - Use default filter - * - * \param[out] config Configuration structure to fill with default values - */ -static inline void system_clock_source_dpll_get_config_defaults( - struct system_clock_source_dpll_config *const config) -{ - config->on_demand = true; - config->run_in_standby = false; - config->lock_bypass = false; - config->wake_up_fast = false; - config->low_power_enable = false; - - config->output_frequency = 48000000; - config->reference_frequency = 32768; - config->reference_divider = 1; - config->reference_clock = SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_XOSC32K; - - config->lock_time = SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_DEFAULT; - config->filter = SYSTEM_CLOCK_SOURCE_DPLL_FILTER_DEFAULT; -}; - -void system_clock_source_dpll_set_config( - struct system_clock_source_dpll_config *const config); - -/* @} */ -#endif - -/** - * \name System Clock Initialization - * @{ - */ - -void system_clock_init(void); - -/** - * @} - */ - -/** - * \name System Flash Wait States - * @{ - */ - -/** - * \brief Set flash controller wait states. - * - * Will set the number of wait states that are used by the onboard - * flash memory. The number of wait states depend on both device - * supply voltage and CPU speed. The required number of wait states - * can be found in the electrical characteristics of the device. - * - * \param[in] wait_states Number of wait states to use for internal flash - */ -static inline void system_flash_set_waitstates(uint8_t wait_states) -{ - Assert(NVMCTRL_CTRLB_RWS((uint32_t)wait_states) == - ((uint32_t)wait_states << NVMCTRL_CTRLB_RWS_Pos)); - - NVMCTRL->CTRLB.bit.RWS = wait_states; -} -/** - * @} - */ - -/** - * @} - */ - -/** - * \page asfdoc_sam0_system_clock_extra Extra Information for SYSTEM CLOCK Driver - * - * \section asfdoc_sam0_system_clock_extra_acronyms Acronyms - * Below is a table listing the acronyms used in this module, along with their - * intended meanings. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
AcronymDescription
DFLLDigital Frequency Locked Loop
MUXMultiplexer
OSC32KInternal 32KHz Oscillator
OSC8MInternal 8MHz Oscillator
PLLPhase Locked Loop
OSCOscillator
XOSCExternal Oscillator
XOSC32KExternal 32KHz Oscillator
AHBAdvanced High-performance Bus
APBAdvanced Peripheral Bus
DPLLDigital Phase Locked Loop
- * - * - * \section asfdoc_sam0_system_clock_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - None - * - * - * \section asfdoc_sam0_system_clock_extra_errata Errata - * - * - This driver implements experimental workaround for errata 9905 - * - * "The DFLL clock must be requested before being configured otherwise a - * write access to a DFLL register can freeze the device." - * This driver will enable and configure the DFLL before the ONDEMAND bit is set. - * - * - * \section asfdoc_sam0_system_clock_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Changelog
- * \li Corrected OSC32K startup time definitions - * \li Support locking of OSC32K and XOSC32K config register (default: false) - * \li Added DPLL support, functions added: - * \c system_clock_source_dpll_get_config_defaults() and - * \c system_clock_source_dpll_set_config() - * \li Moved gclk channel locking feature out of the config struct - * functions added: - * \c system_gclk_chan_lock(), - * \c system_gclk_chan_is_locked() - * \c system_gclk_chan_is_enabled() and - * \c system_gclk_gen_is_enabled() - *
Fixed \c system_gclk_chan_disable() deadlocking if a channel is enabled - * and configured to a failed/not running clock generator
- * \li Changed default value for CONF_CLOCK_DFLL_ON_DEMAND from \c true to \c false - * \li Fixed system_flash_set_waitstates() failing with an assertion - * if an odd number of wait states provided - *
- * \li Updated dfll configuration function to implement workaround for - * errata 9905 in the DFLL module - * \li Updated \c system_clock_init() to reset interrupt flags before - * they are used - * \li Fixed \c system_clock_source_get_hz() to return correcy DFLL - * frequency number - *
\li Fixed \c system_clock_source_is_ready not returning the correct - * state for \c SYSTEM_CLOCK_SOURCE_OSC8M - * \li Renamed the various \c system_clock_source_*_get_default_config() - * functions to \c system_clock_source_*_get_config_defaults() to - * match the remainder of ASF - * \li Added OSC8M calibration constant loading from the device signature - * row when the oscillator is initialized - * \li Updated default configuration of the XOSC32 to disable Automatic - * Gain Control due to silicon errata - *
Initial Release
- */ - -/** - * \page asfdoc_sam0_system_clock_exqsg Examples for System Clock Driver - * - * This is a list of the available Quick Start guides (QSGs) and example - * applications for \ref asfdoc_sam0_system_clock_group. QSGs are simple - * examples with step-by-step instructions to configure and use this driver in - * a selection of use cases. Note that QSGs can be compiled as a standalone - * application or be added to the user application. - * - * - \subpage asfdoc_sam0_system_clock_basic_use_case - * - \subpage asfdoc_sam0_system_gclk_basic_use_case - * - * \page asfdoc_sam0_system_clock_document_revision_history Document Revision History - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Doc. Rev. - * Date - * Comments - *
E04/2015Added support for SAMDAx.
D12/2014Added support for SAMR21 and SAMD10/D11.
C01/2014Added support for SAMD21.
B06/2013Corrected documentation typos. Fixed missing steps in the Basic - * Use Case Quick Start Guide.
A06/2013Initial release
- */ - -#ifdef __cplusplus -} -#endif - -#endif /* SYSTEM_CLOCK_FEATURE_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/compiler.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/compiler.h deleted file mode 100644 index 2d95f97..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/compiler.h +++ /dev/null @@ -1,1157 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef UTILS_COMPILER_H_INCLUDED -#define UTILS_COMPILER_H_INCLUDED - -/** - * \defgroup group_sam0_utils Compiler abstraction layer and code utilities - * - * Compiler abstraction layer and code utilities for Cortex-M0+ based Atmel SAM devices. - * This module provides various abstraction layers and utilities to make code compatible between different compilers. - * - * @{ - */ - -#if (defined __ICCARM__) -# include -#endif - -#include -//#include -#include "status_codes.h" -#include "preprocessor/preprocessor.h" -#include - -#ifndef __ASSEMBLY__ - -#include -#include -#include -#include - -/** - * \def UNUSED - * \brief Marking \a v as a unused parameter or value. - */ -#define UNUSED(v) (void)(v) - -/** - * \def barrier - * \brief Memory barrier - */ -#ifdef __GNUC__ -# define barrier() asm volatile("" ::: "memory") -#else -# define barrier() asm ("") -#endif - -/** - * \brief Emit the compiler pragma \a arg. - * - * \param[in] arg The pragma directive as it would appear after \e \#pragma - * (i.e. not stringified). - */ -#define COMPILER_PRAGMA(arg) _Pragma(#arg) - -/** - * \def COMPILER_PACK_SET(alignment) - * \brief Set maximum alignment for subsequent struct and union definitions to \a alignment. - */ -#define COMPILER_PACK_SET(alignment) COMPILER_PRAGMA(pack(alignment)) - -/** - * \def COMPILER_PACK_RESET() - * \brief Set default alignment for subsequent struct and union definitions. - */ -#define COMPILER_PACK_RESET() COMPILER_PRAGMA(pack()) - - -/** - * \brief Set aligned boundary. - */ -#if (defined __GNUC__) || (defined __CC_ARM) -# define COMPILER_ALIGNED(a) __attribute__((__aligned__(a))) -#elif (defined __ICCARM__) -# define COMPILER_ALIGNED(a) COMPILER_PRAGMA(data_alignment = a) -#endif - -/** - * \brief Set word-aligned boundary. - */ -#if (defined __GNUC__) || defined(__CC_ARM) -#define COMPILER_WORD_ALIGNED __attribute__((__aligned__(4))) -#elif (defined __ICCARM__) -#define COMPILER_WORD_ALIGNED COMPILER_PRAGMA(data_alignment = 4) -#endif - -/** - * \def __always_inline - * \brief The function should always be inlined. - * - * This annotation instructs the compiler to ignore its inlining - * heuristics and inline the function no matter how big it thinks it - * becomes. - */ -#if defined(__CC_ARM) -# define __always_inline __forceinline -#elif (defined __GNUC__) -# define __always_inline __attribute__((__always_inline__)) -#elif (defined __ICCARM__) -# define __always_inline _Pragma("inline=forced") -#endif - -/** - * \def __no_inline - * \brief The function should never be inlined - * - * This annotation instructs the compiler to ignore its inlining - * heuristics and not inline the function no matter how small it thinks it - * becomes. - */ -#if defined(__CC_ARM) -# define __no_inline __attribute__((noinline)) -#elif (defined __GNUC__) -# define __no_inline __attribute__((noinline)) -#elif (defined __ICCARM__) -# define __no_inline _Pragma("inline=never") -#endif - - -/** \brief This macro is used to test fatal errors. - * - * The macro tests if the expression is false. If it is, a fatal error is - * detected and the application hangs up. If \c TEST_SUITE_DEFINE_ASSERT_MACRO - * is defined, a unit test version of the macro is used, to allow execution - * of further tests after a false expression. - * - * \param[in] expr Expression to evaluate and supposed to be nonzero. - */ -#if defined(_ASSERT_ENABLE_) -# if defined(TEST_SUITE_DEFINE_ASSERT_MACRO) -# include "unit_test/suite.h" -# else -# undef TEST_SUITE_DEFINE_ASSERT_MACRO -# define Assert(expr) \ - {\ - if (!(expr)) asm("BKPT #0");\ - } -# endif -#else -# define Assert(expr) ((void) 0) -#endif - -/* Define WEAK attribute */ -#if defined ( __CC_ARM ) -# define WEAK __attribute__ ((weak)) -#elif defined ( __ICCARM__ ) -# define WEAK __weak -#elif defined ( __GNUC__ ) -# define WEAK __attribute__ ((weak)) -#endif - -/* Define NO_INIT attribute */ -#if defined ( __CC_ARM ) -# define NO_INIT __attribute__((zero_init)) -#elif defined ( __ICCARM__ ) -# define NO_INIT __no_init -#elif defined ( __GNUC__ ) -# define NO_INIT __attribute__((section(".no_init"))) -#endif - -#include "interrupt.h" - -/** \name Usual Types - * @{ */ -#ifndef __cplusplus -# if !defined(__bool_true_false_are_defined) -typedef unsigned char bool; -# endif -#endif -typedef uint16_t le16_t; -typedef uint16_t be16_t; -typedef uint32_t le32_t; -typedef uint32_t be32_t; -typedef uint32_t iram_size_t; -/** @} */ - -/** \name Aliasing Aggregate Types - * @{ */ - -/** 16-bit union. */ -typedef union -{ - int16_t s16; - uint16_t u16; - int8_t s8[2]; - uint8_t u8[2]; -} Union16; - -/** 32-bit union. */ -typedef union -{ - int32_t s32; - uint32_t u32; - int16_t s16[2]; - uint16_t u16[2]; - int8_t s8[4]; - uint8_t u8[4]; -} Union32; - -/** 64-bit union. */ -typedef union -{ - int64_t s64; - uint64_t u64; - int32_t s32[2]; - uint32_t u32[2]; - int16_t s16[4]; - uint16_t u16[4]; - int8_t s8[8]; - uint8_t u8[8]; -} Union64; - -/** Union of pointers to 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef union -{ - int64_t *s64ptr; - uint64_t *u64ptr; - int32_t *s32ptr; - uint32_t *u32ptr; - int16_t *s16ptr; - uint16_t *u16ptr; - int8_t *s8ptr; - uint8_t *u8ptr; -} UnionPtr; - -/** Union of pointers to volatile 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef union -{ - volatile int64_t *s64ptr; - volatile uint64_t *u64ptr; - volatile int32_t *s32ptr; - volatile uint32_t *u32ptr; - volatile int16_t *s16ptr; - volatile uint16_t *u16ptr; - volatile int8_t *s8ptr; - volatile uint8_t *u8ptr; -} UnionVPtr; - -/** Union of pointers to constant 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef union -{ - const int64_t *s64ptr; - const uint64_t *u64ptr; - const int32_t *s32ptr; - const uint32_t *u32ptr; - const int16_t *s16ptr; - const uint16_t *u16ptr; - const int8_t *s8ptr; - const uint8_t *u8ptr; -} UnionCPtr; - -/** Union of pointers to constant volatile 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef union -{ - const volatile int64_t *s64ptr; - const volatile uint64_t *u64ptr; - const volatile int32_t *s32ptr; - const volatile uint32_t *u32ptr; - const volatile int16_t *s16ptr; - const volatile uint16_t *u16ptr; - const volatile int8_t *s8ptr; - const volatile uint8_t *u8ptr; -} UnionCVPtr; - -/** Structure of pointers to 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef struct -{ - int64_t *s64ptr; - uint64_t *u64ptr; - int32_t *s32ptr; - uint32_t *u32ptr; - int16_t *s16ptr; - uint16_t *u16ptr; - int8_t *s8ptr; - uint8_t *u8ptr; -} StructPtr; - -/** Structure of pointers to volatile 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef struct -{ - volatile int64_t *s64ptr; - volatile uint64_t *u64ptr; - volatile int32_t *s32ptr; - volatile uint32_t *u32ptr; - volatile int16_t *s16ptr; - volatile uint16_t *u16ptr; - volatile int8_t *s8ptr; - volatile uint8_t *u8ptr; -} StructVPtr; - -/** Structure of pointers to constant 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef struct -{ - const int64_t *s64ptr; - const uint64_t *u64ptr; - const int32_t *s32ptr; - const uint32_t *u32ptr; - const int16_t *s16ptr; - const uint16_t *u16ptr; - const int8_t *s8ptr; - const uint8_t *u8ptr; -} StructCPtr; - -/** Structure of pointers to constant volatile 64-, 32-, 16- and 8-bit unsigned integers. */ -typedef struct -{ - const volatile int64_t *s64ptr; - const volatile uint64_t *u64ptr; - const volatile int32_t *s32ptr; - const volatile uint32_t *u32ptr; - const volatile int16_t *s16ptr; - const volatile uint16_t *u16ptr; - const volatile int8_t *s8ptr; - const volatile uint8_t *u8ptr; -} StructCVPtr; - -/** @} */ - -#endif /* #ifndef __ASSEMBLY__ */ - -/** \name Usual Constants - * @{ */ -#define DISABLE 0 -//#define ENABLE 1 - -#ifndef __cplusplus -# if !defined(__bool_true_false_are_defined) -# define false 0 -# define true 1 -# endif -#endif -/** @} */ - -#ifndef __ASSEMBLY__ - -/** \name Optimization Control - * @{ */ - -/** - * \def likely(exp) - * \brief The expression \a exp is likely to be true - */ -#if !defined(likely) || defined(__DOXYGEN__) -# define likely(exp) (exp) -#endif - -/** - * \def unlikely(exp) - * \brief The expression \a exp is unlikely to be true - */ -#if !defined(unlikely) || defined(__DOXYGEN__) -# define unlikely(exp) (exp) -#endif - -/** - * \def is_constant(exp) - * \brief Determine if an expression evaluates to a constant value. - * - * \param[in] exp Any expression - * - * \return true if \a exp is constant, false otherwise. - */ -#if (defined __GNUC__) || (defined __CC_ARM) -# define is_constant(exp) __builtin_constant_p(exp) -#else -# define is_constant(exp) (0) -#endif - -/** @} */ - -/** \name Bit-Field Handling - * @{ */ - -/** \brief Reads the bits of a value specified by a given bit-mask. - * - * \param[in] value Value to read bits from. - * \param[in] mask Bit-mask indicating bits to read. - * - * \return Read bits. - */ -#define Rd_bits( value, mask) ((value) & (mask)) - -/** \brief Writes the bits of a C lvalue specified by a given bit-mask. - * - * \param[in] lvalue C lvalue to write bits to. - * \param[in] mask Bit-mask indicating bits to write. - * \param[in] bits Bits to write. - * - * \return Resulting value with written bits. - */ -#define Wr_bits(lvalue, mask, bits) ((lvalue) = ((lvalue) & ~(mask)) |\ - ((bits ) & (mask))) - -/** \brief Tests the bits of a value specified by a given bit-mask. - * - * \param[in] value Value of which to test bits. - * \param[in] mask Bit-mask indicating bits to test. - * - * \return \c 1 if at least one of the tested bits is set, else \c 0. - */ -#define Tst_bits( value, mask) (Rd_bits(value, mask) != 0) - -/** \brief Clears the bits of a C lvalue specified by a given bit-mask. - * - * \param[in] lvalue C lvalue of which to clear bits. - * \param[in] mask Bit-mask indicating bits to clear. - * - * \return Resulting value with cleared bits. - */ -#define Clr_bits(lvalue, mask) ((lvalue) &= ~(mask)) - -/** \brief Sets the bits of a C lvalue specified by a given bit-mask. - * - * \param[in] lvalue C lvalue of which to set bits. - * \param[in] mask Bit-mask indicating bits to set. - * - * \return Resulting value with set bits. - */ -#define Set_bits(lvalue, mask) ((lvalue) |= (mask)) - -/** \brief Toggles the bits of a C lvalue specified by a given bit-mask. - * - * \param[in] lvalue C lvalue of which to toggle bits. - * \param[in] mask Bit-mask indicating bits to toggle. - * - * \return Resulting value with toggled bits. - */ -#define Tgl_bits(lvalue, mask) ((lvalue) ^= (mask)) - -/** \brief Reads the bit-field of a value specified by a given bit-mask. - * - * \param[in] value Value to read a bit-field from. - * \param[in] mask Bit-mask indicating the bit-field to read. - * - * \return Read bit-field. - */ -#define Rd_bitfield( value, mask) (Rd_bits( value, mask) >> ctz(mask)) - -/** \brief Writes the bit-field of a C lvalue specified by a given bit-mask. - * - * \param[in] lvalue C lvalue to write a bit-field to. - * \param[in] mask Bit-mask indicating the bit-field to write. - * \param[in] bitfield Bit-field to write. - * - * \return Resulting value with written bit-field. - */ -#define Wr_bitfield(lvalue, mask, bitfield) (Wr_bits(lvalue, mask, (uint32_t)(bitfield) << ctz(mask))) - -/** @} */ - - -/** \name Zero-Bit Counting - * - * Under GCC, __builtin_clz and __builtin_ctz behave like macros when - * applied to constant expressions (values known at compile time), so they are - * more optimized than the use of the corresponding assembly instructions and - * they can be used as constant expressions e.g. to initialize objects having - * static storage duration, and like the corresponding assembly instructions - * when applied to non-constant expressions (values unknown at compile time), so - * they are more optimized than an assembly periphrasis. Hence, clz and ctz - * ensure a possible and optimized behavior for both constant and non-constant - * expressions. - * - * @{ */ - -/** \brief Counts the leading zero bits of the given value considered as a 32-bit integer. - * - * \param[in] u Value of which to count the leading zero bits. - * - * \return The count of leading zero bits in \a u. - */ -#if (defined __GNUC__) || (defined __CC_ARM) -# define clz(u) __builtin_clz(u) -#else -# define clz(u) (((u) == 0) ? 32 : \ - ((u) & (1ul << 31)) ? 0 : \ - ((u) & (1ul << 30)) ? 1 : \ - ((u) & (1ul << 29)) ? 2 : \ - ((u) & (1ul << 28)) ? 3 : \ - ((u) & (1ul << 27)) ? 4 : \ - ((u) & (1ul << 26)) ? 5 : \ - ((u) & (1ul << 25)) ? 6 : \ - ((u) & (1ul << 24)) ? 7 : \ - ((u) & (1ul << 23)) ? 8 : \ - ((u) & (1ul << 22)) ? 9 : \ - ((u) & (1ul << 21)) ? 10 : \ - ((u) & (1ul << 20)) ? 11 : \ - ((u) & (1ul << 19)) ? 12 : \ - ((u) & (1ul << 18)) ? 13 : \ - ((u) & (1ul << 17)) ? 14 : \ - ((u) & (1ul << 16)) ? 15 : \ - ((u) & (1ul << 15)) ? 16 : \ - ((u) & (1ul << 14)) ? 17 : \ - ((u) & (1ul << 13)) ? 18 : \ - ((u) & (1ul << 12)) ? 19 : \ - ((u) & (1ul << 11)) ? 20 : \ - ((u) & (1ul << 10)) ? 21 : \ - ((u) & (1ul << 9)) ? 22 : \ - ((u) & (1ul << 8)) ? 23 : \ - ((u) & (1ul << 7)) ? 24 : \ - ((u) & (1ul << 6)) ? 25 : \ - ((u) & (1ul << 5)) ? 26 : \ - ((u) & (1ul << 4)) ? 27 : \ - ((u) & (1ul << 3)) ? 28 : \ - ((u) & (1ul << 2)) ? 29 : \ - ((u) & (1ul << 1)) ? 30 : \ - 31) -#endif - -/** \brief Counts the trailing zero bits of the given value considered as a 32-bit integer. - * - * \param[in] u Value of which to count the trailing zero bits. - * - * \return The count of trailing zero bits in \a u. - */ -#if (defined __GNUC__) || (defined __CC_ARM) -# define ctz(u) __builtin_ctz(u) -#else -# define ctz(u) ((u) & (1ul << 0) ? 0 : \ - (u) & (1ul << 1) ? 1 : \ - (u) & (1ul << 2) ? 2 : \ - (u) & (1ul << 3) ? 3 : \ - (u) & (1ul << 4) ? 4 : \ - (u) & (1ul << 5) ? 5 : \ - (u) & (1ul << 6) ? 6 : \ - (u) & (1ul << 7) ? 7 : \ - (u) & (1ul << 8) ? 8 : \ - (u) & (1ul << 9) ? 9 : \ - (u) & (1ul << 10) ? 10 : \ - (u) & (1ul << 11) ? 11 : \ - (u) & (1ul << 12) ? 12 : \ - (u) & (1ul << 13) ? 13 : \ - (u) & (1ul << 14) ? 14 : \ - (u) & (1ul << 15) ? 15 : \ - (u) & (1ul << 16) ? 16 : \ - (u) & (1ul << 17) ? 17 : \ - (u) & (1ul << 18) ? 18 : \ - (u) & (1ul << 19) ? 19 : \ - (u) & (1ul << 20) ? 20 : \ - (u) & (1ul << 21) ? 21 : \ - (u) & (1ul << 22) ? 22 : \ - (u) & (1ul << 23) ? 23 : \ - (u) & (1ul << 24) ? 24 : \ - (u) & (1ul << 25) ? 25 : \ - (u) & (1ul << 26) ? 26 : \ - (u) & (1ul << 27) ? 27 : \ - (u) & (1ul << 28) ? 28 : \ - (u) & (1ul << 29) ? 29 : \ - (u) & (1ul << 30) ? 30 : \ - (u) & (1ul << 31) ? 31 : \ - 32) -#endif - -/** @} */ - - -/** \name Bit Reversing - * @{ */ - -/** \brief Reverses the bits of \a u8. - * - * \param[in] u8 U8 of which to reverse the bits. - * - * \return Value resulting from \a u8 with reversed bits. - */ -#define bit_reverse8(u8) ((U8)(bit_reverse32((U8)(u8)) >> 24)) - -/** \brief Reverses the bits of \a u16. - * - * \param[in] u16 U16 of which to reverse the bits. - * - * \return Value resulting from \a u16 with reversed bits. - */ -#define bit_reverse16(u16) ((uint16_t)(bit_reverse32((uint16_t)(u16)) >> 16)) - -/** \brief Reverses the bits of \a u32. - * - * \param[in] u32 U32 of which to reverse the bits. - * - * \return Value resulting from \a u32 with reversed bits. - */ -#define bit_reverse32(u32) __RBIT(u32) - -/** \brief Reverses the bits of \a u64. - * - * \param[in] u64 U64 of which to reverse the bits. - * - * \return Value resulting from \a u64 with reversed bits. - */ -#define bit_reverse64(u64) ((uint64_t)(((uint64_t)bit_reverse32((uint64_t)(u64) >> 32)) |\ - ((uint64_t)bit_reverse32((uint64_t)(u64)) << 32))) - -/** @} */ - - -/** \name Alignment - * @{ */ - -/** \brief Tests alignment of the number \a val with the \a n boundary. - * - * \param[in] val Input value. - * \param[in] n Boundary. - * - * \return \c 1 if the number \a val is aligned with the \a n boundary, else \c 0. - */ -#define Test_align(val, n) (!Tst_bits( val, (n) - 1 ) ) - -/** \brief Gets alignment of the number \a val with respect to the \a n boundary. - * - * \param[in] val Input value. - * \param[in] n Boundary. - * - * \return Alignment of the number \a val with respect to the \a n boundary. - */ -#define Get_align(val, n) ( Rd_bits( val, (n) - 1 ) ) - -/** \brief Sets alignment of the lvalue number \a lval to \a alg with respect to the \a n boundary. - * - * \param[in] lval Input/output lvalue. - * \param[in] n Boundary. - * \param[in] alg Alignment. - * - * \return New value of \a lval resulting from its alignment set to \a alg with respect to the \a n boundary. - */ -#define Set_align(lval, n, alg) ( Wr_bits(lval, (n) - 1, alg) ) - -/** \brief Aligns the number \a val with the upper \a n boundary. - * - * \param[in] val Input value. - * \param[in] n Boundary. - * - * \return Value resulting from the number \a val aligned with the upper \a n boundary. - */ -#define Align_up( val, n) (((val) + ((n) - 1)) & ~((n) - 1)) - -/** \brief Aligns the number \a val with the lower \a n boundary. - * - * \param[in] val Input value. - * \param[in] n Boundary. - * - * \return Value resulting from the number \a val aligned with the lower \a n boundary. - */ -#define Align_down(val, n) ( (val) & ~((n) - 1)) - -/** @} */ - - -/** \name Mathematics - * - * The same considerations as for clz and ctz apply here but GCC does not - * provide built-in functions to access the assembly instructions abs, min and - * max and it does not produce them by itself in most cases, so two sets of - * macros are defined here: - * - Abs, Min and Max to apply to constant expressions (values known at - * compile time); - * - abs, min and max to apply to non-constant expressions (values unknown at - * compile time), abs is found in stdlib.h. - * - * @{ */ - -/** \brief Takes the absolute value of \a a. - * - * \param[in] a Input value. - * - * \return Absolute value of \a a. - * - * \note More optimized if only used with values known at compile time. - */ -#define Abs(a) (((a) < 0 ) ? -(a) : (a)) - -/** \brief Takes the minimal value of \a a and \a b. - * - * \param[in] a Input value. - * \param[in] b Input value. - * - * \return Minimal value of \a a and \a b. - * - * \note More optimized if only used with values known at compile time. - */ -#define Min(a, b) (((a) < (b)) ? (a) : (b)) - -/** \brief Takes the maximal value of \a a and \a b. - * - * \param[in] a Input value. - * \param[in] b Input value. - * - * \return Maximal value of \a a and \a b. - * - * \note More optimized if only used with values known at compile time. - */ -#define Max(a, b) (((a) > (b)) ? (a) : (b)) - -/** \brief Takes the minimal value of \a a and \a b. - * - * \param[in] a Input value. - * \param[in] b Input value. - * - * \return Minimal value of \a a and \a b. - * - * \note More optimized if only used with values unknown at compile time. - */ -#define min(a, b) Min(a, b) - -/** \brief Takes the maximal value of \a a and \a b. - * - * \param[in] a Input value. - * \param[in] b Input value. - * - * \return Maximal value of \a a and \a b. - * - * \note More optimized if only used with values unknown at compile time. - */ -#define max(a, b) Max(a, b) - -/** @} */ - - -/** \brief Calls the routine at address \a addr. - * - * It generates a long call opcode. - * - * For example, `Long_call(0x80000000)' generates a software reset on a UC3 if - * it is invoked from the CPU supervisor mode. - * - * \param[in] addr Address of the routine to call. - * - * \note It may be used as a long jump opcode in some special cases. - */ -#define Long_call(addr) ((*(void (*)(void))(addr))()) - - -/** \name MCU Endianism Handling - * ARM is MCU little endian. - * - * @{ */ -#define BE16(x) Swap16(x) -#define LE16(x) (x) - -#define le16_to_cpu(x) (x) -#define cpu_to_le16(x) (x) -#define LE16_TO_CPU(x) (x) -#define CPU_TO_LE16(x) (x) - -#define be16_to_cpu(x) Swap16(x) -#define cpu_to_be16(x) Swap16(x) -#define BE16_TO_CPU(x) Swap16(x) -#define CPU_TO_BE16(x) Swap16(x) - -#define le32_to_cpu(x) (x) -#define cpu_to_le32(x) (x) -#define LE32_TO_CPU(x) (x) -#define CPU_TO_LE32(x) (x) - -#define be32_to_cpu(x) swap32(x) -#define cpu_to_be32(x) swap32(x) -#define BE32_TO_CPU(x) swap32(x) -#define CPU_TO_BE32(x) swap32(x) -/** @} */ - - -/** \name Endianism Conversion - * - * The same considerations as for clz and ctz apply here but GCC's - * __builtin_bswap_32 and __builtin_bswap_64 do not behave like macros when - * applied to constant expressions, so two sets of macros are defined here: - * - Swap16, Swap32 and Swap64 to apply to constant expressions (values known - * at compile time); - * - swap16, swap32 and swap64 to apply to non-constant expressions (values - * unknown at compile time). - * - * @{ */ - -/** \brief Toggles the endianism of \a u16 (by swapping its bytes). - * - * \param[in] u16 U16 of which to toggle the endianism. - * - * \return Value resulting from \a u16 with toggled endianism. - * - * \note More optimized if only used with values known at compile time. - */ -#define Swap16(u16) ((uint16_t)(((uint16_t)(u16) >> 8) |\ - ((uint16_t)(u16) << 8))) - -/** \brief Toggles the endianism of \a u32 (by swapping its bytes). - * - * \param[in] u32 U32 of which to toggle the endianism. - * - * \return Value resulting from \a u32 with toggled endianism. - * - * \note More optimized if only used with values known at compile time. - */ -#define Swap32(u32) ((uint32_t)(((uint32_t)Swap16((uint32_t)(u32) >> 16)) |\ - ((uint32_t)Swap16((uint32_t)(u32)) << 16))) - -/** \brief Toggles the endianism of \a u64 (by swapping its bytes). - * - * \param[in] u64 U64 of which to toggle the endianism. - * - * \return Value resulting from \a u64 with toggled endianism. - * - * \note More optimized if only used with values known at compile time. - */ -#define Swap64(u64) ((uint64_t)(((uint64_t)Swap32((uint64_t)(u64) >> 32)) |\ - ((uint64_t)Swap32((uint64_t)(u64)) << 32))) - -/** \brief Toggles the endianism of \a u16 (by swapping its bytes). - * - * \param[in] u16 U16 of which to toggle the endianism. - * - * \return Value resulting from \a u16 with toggled endianism. - * - * \note More optimized if only used with values unknown at compile time. - */ -#define swap16(u16) Swap16(u16) - -/** \brief Toggles the endianism of \a u32 (by swapping its bytes). - * - * \param[in] u32 U32 of which to toggle the endianism. - * - * \return Value resulting from \a u32 with toggled endianism. - * - * \note More optimized if only used with values unknown at compile time. - */ -#if (defined __GNUC__) -# define swap32(u32) ((uint32_t)__builtin_bswap32((uint32_t)(u32))) -#else -# define swap32(u32) Swap32(u32) -#endif - -/** \brief Toggles the endianism of \a u64 (by swapping its bytes). - * - * \param[in] u64 U64 of which to toggle the endianism. - * - * \return Value resulting from \a u64 with toggled endianism. - * - * \note More optimized if only used with values unknown at compile time. - */ -#if (defined __GNUC__) -# define swap64(u64) ((uint64_t)__builtin_bswap64((uint64_t)(u64))) -#else -# define swap64(u64) ((uint64_t)(((uint64_t)swap32((uint64_t)(u64) >> 32)) |\ - ((uint64_t)swap32((uint64_t)(u64)) << 32))) -#endif - -/** @} */ - - -/** \name Target Abstraction - * - * @{ */ - -#define _GLOBEXT_ extern /**< extern storage-class specifier. */ -#define _CONST_TYPE_ const /**< const type qualifier. */ -#define _MEM_TYPE_SLOW_ /**< Slow memory type. */ -#define _MEM_TYPE_MEDFAST_ /**< Fairly fast memory type. */ -#define _MEM_TYPE_FAST_ /**< Fast memory type. */ - -#define memcmp_ram2ram memcmp /**< Target-specific memcmp of RAM to RAM. */ -#define memcmp_code2ram memcmp /**< Target-specific memcmp of RAM to NVRAM. */ -#define memcpy_ram2ram memcpy /**< Target-specific memcpy from RAM to RAM. */ -#define memcpy_code2ram memcpy /**< Target-specific memcpy from NVRAM to RAM. */ - -/** @} */ - -/** - * \brief Calculate \f$ \left\lceil \frac{a}{b} \right\rceil \f$ using - * integer arithmetic. - * - * \param[in] a An integer - * \param[in] b Another integer - * - * \return (\a a / \a b) rounded up to the nearest integer. - */ -#define div_ceil(a, b) (((a) + (b) - 1) / (b)) - -#endif /* #ifndef __ASSEMBLY__ */ -#ifdef __ICCARM__ -/** \name Compiler Keywords - * - * Port of some keywords from GCC to IAR Embedded Workbench. - * - * @{ */ - -#define __asm__ asm -#define __inline__ inline -#define __volatile__ - -/** @} */ - -#endif - -#define FUNC_PTR void * -/** - * \def unused - * \brief Marking \a v as a unused parameter or value. - */ -#define unused(v) do { (void)(v); } while(0) - -/* Define RAMFUNC attribute */ -#if defined ( __CC_ARM ) /* Keil uVision 4 */ -# define RAMFUNC __attribute__ ((section(".ramfunc"))) -#elif defined ( __ICCARM__ ) /* IAR Ewarm 5.41+ */ -# define RAMFUNC __ramfunc -#elif defined ( __GNUC__ ) /* GCC CS3 2009q3-68 */ -# define RAMFUNC __attribute__ ((section(".ramfunc"))) -#endif - -/* Define OPTIMIZE_HIGH attribute */ -#if defined ( __CC_ARM ) /* Keil uVision 4 */ -# define OPTIMIZE_HIGH _Pragma("O3") -#elif defined ( __ICCARM__ ) /* IAR Ewarm 5.41+ */ -# define OPTIMIZE_HIGH _Pragma("optimize=high") -#elif defined ( __GNUC__ ) /* GCC CS3 2009q3-68 */ -# define OPTIMIZE_HIGH __attribute__((optimize(s))) -#endif -#define PASS 0 -#define FAIL 1 -#define LOW 0 -#define HIGH 1 - -typedef int8_t S8 ; //!< 8-bit signed integer. -typedef uint8_t U8 ; //!< 8-bit unsigned integer. -typedef int16_t S16; //!< 16-bit signed integer. -typedef uint16_t U16; //!< 16-bit unsigned integer. -typedef int32_t S32; //!< 32-bit signed integer. -typedef uint32_t U32; //!< 32-bit unsigned integer. -typedef int64_t S64; //!< 64-bit signed integer. -typedef uint64_t U64; //!< 64-bit unsigned integer. -typedef float F32; //!< 32-bit floating-point number. -typedef double F64; //!< 64-bit floating-point number. - -#define MSB(u16) (((U8 *)&(u16))[1]) //!< Most significant byte of \a u16. -#define LSB(u16) (((U8 *)&(u16))[0]) //!< Least significant byte of \a u16. - -#define MSH(u32) (((U16 *)&(u32))[1]) //!< Most significant half-word of \a u32. -#define LSH(u32) (((U16 *)&(u32))[0]) //!< Least significant half-word of \a u32. -#define MSB0W(u32) (((U8 *)&(u32))[3]) //!< Most significant byte of 1st rank of \a u32. -#define MSB1W(u32) (((U8 *)&(u32))[2]) //!< Most significant byte of 2nd rank of \a u32. -#define MSB2W(u32) (((U8 *)&(u32))[1]) //!< Most significant byte of 3rd rank of \a u32. -#define MSB3W(u32) (((U8 *)&(u32))[0]) //!< Most significant byte of 4th rank of \a u32. -#define LSB3W(u32) MSB0W(u32) //!< Least significant byte of 4th rank of \a u32. -#define LSB2W(u32) MSB1W(u32) //!< Least significant byte of 3rd rank of \a u32. -#define LSB1W(u32) MSB2W(u32) //!< Least significant byte of 2nd rank of \a u32. -#define LSB0W(u32) MSB3W(u32) //!< Least significant byte of 1st rank of \a u32. - -#define MSW(u64) (((U32 *)&(u64))[1]) //!< Most significant word of \a u64. -#define LSW(u64) (((U32 *)&(u64))[0]) //!< Least significant word of \a u64. -#define MSH0(u64) (((U16 *)&(u64))[3]) //!< Most significant half-word of 1st rank of \a u64. -#define MSH1(u64) (((U16 *)&(u64))[2]) //!< Most significant half-word of 2nd rank of \a u64. -#define MSH2(u64) (((U16 *)&(u64))[1]) //!< Most significant half-word of 3rd rank of \a u64. -#define MSH3(u64) (((U16 *)&(u64))[0]) //!< Most significant half-word of 4th rank of \a u64. -#define LSH3(u64) MSH0(u64) //!< Least significant half-word of 4th rank of \a u64. -#define LSH2(u64) MSH1(u64) //!< Least significant half-word of 3rd rank of \a u64. -#define LSH1(u64) MSH2(u64) //!< Least significant half-word of 2nd rank of \a u64. -#define LSH0(u64) MSH3(u64) //!< Least significant half-word of 1st rank of \a u64. -#define MSB0D(u64) (((U8 *)&(u64))[7]) //!< Most significant byte of 1st rank of \a u64. -#define MSB1D(u64) (((U8 *)&(u64))[6]) //!< Most significant byte of 2nd rank of \a u64. -#define MSB2D(u64) (((U8 *)&(u64))[5]) //!< Most significant byte of 3rd rank of \a u64. -#define MSB3D(u64) (((U8 *)&(u64))[4]) //!< Most significant byte of 4th rank of \a u64. -#define MSB4D(u64) (((U8 *)&(u64))[3]) //!< Most significant byte of 5th rank of \a u64. -#define MSB5D(u64) (((U8 *)&(u64))[2]) //!< Most significant byte of 6th rank of \a u64. -#define MSB6D(u64) (((U8 *)&(u64))[1]) //!< Most significant byte of 7th rank of \a u64. -#define MSB7D(u64) (((U8 *)&(u64))[0]) //!< Most significant byte of 8th rank of \a u64. -#define LSB7D(u64) MSB0D(u64) //!< Least significant byte of 8th rank of \a u64. -#define LSB6D(u64) MSB1D(u64) //!< Least significant byte of 7th rank of \a u64. -#define LSB5D(u64) MSB2D(u64) //!< Least significant byte of 6th rank of \a u64. -#define LSB4D(u64) MSB3D(u64) //!< Least significant byte of 5th rank of \a u64. -#define LSB3D(u64) MSB4D(u64) //!< Least significant byte of 4th rank of \a u64. -#define LSB2D(u64) MSB5D(u64) //!< Least significant byte of 3rd rank of \a u64. -#define LSB1D(u64) MSB6D(u64) //!< Least significant byte of 2nd rank of \a u64. -#define LSB0D(u64) MSB7D(u64) //!< Least significant byte of 1st rank of \a u64. - -#define LSB0(u32) LSB0W(u32) //!< Least significant byte of 1st rank of \a u32. -#define LSB1(u32) LSB1W(u32) //!< Least significant byte of 2nd rank of \a u32. -#define LSB2(u32) LSB2W(u32) //!< Least significant byte of 3rd rank of \a u32. -#define LSB3(u32) LSB3W(u32) //!< Least significant byte of 4th rank of \a u32. -#define MSB3(u32) MSB3W(u32) //!< Most significant byte of 4th rank of \a u32. -#define MSB2(u32) MSB2W(u32) //!< Most significant byte of 3rd rank of \a u32. -#define MSB1(u32) MSB1W(u32) //!< Most significant byte of 2nd rank of \a u32. -#define MSB0(u32) MSB0W(u32) //!< Most significant byte of 1st rank of \a u32. - -#if defined(__ICCARM__) -#define SHORTENUM __packed -#elif defined(__GNUC__) -#define SHORTENUM __attribute__((packed)) -#endif - -/* No operation */ -#if defined(__ICCARM__) -#define nop() __no_operation() -#elif defined(__GNUC__) -#define nop() (__NOP()) -#endif - -#define FLASH_DECLARE(x) const x -#define FLASH_EXTERN(x) extern const x -#define PGM_READ_BYTE(x) *(x) -#define PGM_READ_WORD(x) *(x) -#define MEMCPY_ENDIAN memcpy -#define PGM_READ_BLOCK(dst, src, len) memcpy((dst), (src), (len)) - -/*Defines the Flash Storage for the request and response of MAC*/ -#define CMD_ID_OCTET (0) - -/* Converting of values from CPU endian to little endian. */ -#define CPU_ENDIAN_TO_LE16(x) (x) -#define CPU_ENDIAN_TO_LE32(x) (x) -#define CPU_ENDIAN_TO_LE64(x) (x) - -/* Converting of values from little endian to CPU endian. */ -#define LE16_TO_CPU_ENDIAN(x) (x) -#define LE32_TO_CPU_ENDIAN(x) (x) -#define LE64_TO_CPU_ENDIAN(x) (x) - -/* Converting of constants from little endian to CPU endian. */ -#define CLE16_TO_CPU_ENDIAN(x) (x) -#define CLE32_TO_CPU_ENDIAN(x) (x) -#define CLE64_TO_CPU_ENDIAN(x) (x) - -/* Converting of constants from CPU endian to little endian. */ -#define CCPU_ENDIAN_TO_LE16(x) (x) -#define CCPU_ENDIAN_TO_LE32(x) (x) -#define CCPU_ENDIAN_TO_LE64(x) (x) - -#define ADDR_COPY_DST_SRC_16(dst, src) ((dst) = (src)) -#define ADDR_COPY_DST_SRC_64(dst, src) ((dst) = (src)) - -/** - * @brief Converts a 64-Bit value into a 8 Byte array - * - * @param[in] value 64-Bit value - * @param[out] data Pointer to the 8 Byte array to be updated with 64-Bit value - * @ingroup apiPalApi - */ -static inline void convert_64_bit_to_byte_array(uint64_t value, uint8_t *data) -{ - uint8_t index = 0; - - while (index < 8) - { - data[index++] = value & 0xFF; - value = value >> 8; - } -} - -/** - * @brief Converts a 16-Bit value into a 2 Byte array - * - * @param[in] value 16-Bit value - * @param[out] data Pointer to the 2 Byte array to be updated with 16-Bit value - * @ingroup apiPalApi - */ -static inline void convert_16_bit_to_byte_array(uint16_t value, uint8_t *data) -{ - data[0] = value & 0xFF; - data[1] = (value >> 8) & 0xFF; -} - -/* Converts a 16-Bit value into a 2 Byte array */ -static inline void convert_spec_16_bit_to_byte_array(uint16_t value, uint8_t *data) -{ - data[0] = value & 0xFF; - data[1] = (value >> 8) & 0xFF; -} - -/* Converts a 16-Bit value into a 2 Byte array */ -static inline void convert_16_bit_to_byte_address(uint16_t value, uint8_t *data) -{ - data[0] = value & 0xFF; - data[1] = (value >> 8) & 0xFF; -} - -/* - * @brief Converts a 2 Byte array into a 16-Bit value - * - * @param data Specifies the pointer to the 2 Byte array - * - * @return 16-Bit value - * @ingroup apiPalApi - */ -static inline uint16_t convert_byte_array_to_16_bit(uint8_t *data) -{ - return (data[0] | ((uint16_t)data[1] << 8)); -} - -/* Converts a 4 Byte array into a 32-Bit value */ -static inline uint32_t convert_byte_array_to_32_bit(uint8_t *data) -{ - union - { - uint32_t u32; - uint8_t u8[4]; - }long_addr; - uint8_t index; - for (index = 0; index < 4; index++) - { - long_addr.u8[index] = *data++; - } - return long_addr.u32; -} - -/** - * @brief Converts a 8 Byte array into a 64-Bit value - * - * @param data Specifies the pointer to the 8 Byte array - * - * @return 64-Bit value - * @ingroup apiPalApi - */ -static inline uint64_t convert_byte_array_to_64_bit(uint8_t *data) -{ - union - { - uint64_t u64; - uint8_t u8[8]; - } long_addr; - - uint8_t index; - - for (index = 0; index < 8; index++) - { - long_addr.u8[index] = *data++; - } - - return long_addr.u64; -} - -/** @} */ - -#endif /* UTILS_COMPILER_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/gclk.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/gclk.c deleted file mode 100644 index 1199a19..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/gclk.c +++ /dev/null @@ -1,522 +0,0 @@ -/** - * \file - * - * \brief SAM D21/R21/DA0/DA1 Generic Clock Driver - * - * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#include -#include -#include - -/** - * \brief Determines if the hardware module(s) are currently synchronizing to the bus. - * - * Checks to see if the underlying hardware peripheral module(s) are currently - * synchronizing across multiple clock domains to the hardware bus, This - * function can be used to delay further operations on a module until such time - * that it is ready, to prevent blocking delays for synchronization in the - * user application. - * - * \return Synchronization status of the underlying hardware module(s). - * - * \retval false if the module has completed synchronization - * \retval true if the module synchronization is ongoing - */ -static inline bool system_gclk_is_syncing(void) -{ - if (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY){ - return true; - } - - return false; -} - -/** - * \brief Initializes the GCLK driver. - * - * Initializes the Generic Clock module, disabling and resetting all active - * Generic Clock Generators and Channels to their power-on default values. - */ -void system_gclk_init(void) -{ - /* Turn on the digital interface clock */ - system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBA, PM_APBAMASK_GCLK); - - /* Software reset the module to ensure it is re-initialized correctly */ - GCLK->CTRL.reg = GCLK_CTRL_SWRST; - while (GCLK->CTRL.reg & GCLK_CTRL_SWRST) { - /* Wait for reset to complete */ - } -} - -/** - * \brief Writes a Generic Clock Generator configuration to the hardware module. - * - * Writes out a given configuration of a Generic Clock Generator configuration - * to the hardware module. - * - * \note Changing the clock source on the fly (on a running - * generator) can take additional time if the clock source is configured - * to only run on-demand (ONDEMAND bit is set) and it is not currently - * running (no peripheral is requesting the clock source). In this case - * the GCLK will request the new clock while still keeping a request to - * the old clock source until the new clock source is ready. - * - * \note This function will not start a generator that is not already running; - * to start the generator, call \ref system_gclk_gen_enable() - * after configuring a generator. - * - * \param[in] generator Generic Clock Generator index to configure - * \param[in] config Configuration settings for the generator - */ -void system_gclk_gen_set_config( - const uint8_t generator, - struct system_gclk_gen_config *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Cache new register configurations to minimize sync requirements. */ - uint32_t new_genctrl_config = (generator << GCLK_GENCTRL_ID_Pos); - uint32_t new_gendiv_config = (generator << GCLK_GENDIV_ID_Pos); - - /* Select the requested source clock for the generator */ - new_genctrl_config |= config->source_clock << GCLK_GENCTRL_SRC_Pos; - - /* Configure the clock to be either high or low when disabled */ - if (config->high_when_disabled) { - new_genctrl_config |= GCLK_GENCTRL_OOV; - } - - /* Configure if the clock output to I/O pin should be enabled. */ - if (config->output_enable) { - new_genctrl_config |= GCLK_GENCTRL_OE; - } - - /* Set division factor */ - if (config->division_factor > 1) { - /* Check if division is a power of two */ - if (((config->division_factor & (config->division_factor - 1)) == 0)) { - /* Determine the index of the highest bit set to get the - * division factor that must be loaded into the division - * register */ - - uint32_t div2_count = 0; - - uint32_t mask; - for (mask = (1UL << 1); mask < config->division_factor; - mask <<= 1) { - div2_count++; - } - - /* Set binary divider power of 2 division factor */ - new_gendiv_config |= div2_count << GCLK_GENDIV_DIV_Pos; - new_genctrl_config |= GCLK_GENCTRL_DIVSEL; - } else { - /* Set integer division factor */ - - new_gendiv_config |= - (config->division_factor) << GCLK_GENDIV_DIV_Pos; - - /* Enable non-binary division with increased duty cycle accuracy */ - new_genctrl_config |= GCLK_GENCTRL_IDC; - } - - } - - /* Enable or disable the clock in standby mode */ - if (config->run_in_standby) { - new_genctrl_config |= GCLK_GENCTRL_RUNSTDBY; - } - - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - system_interrupt_enter_critical_section(); - - /* Select the correct generator */ - *((uint8_t*)&GCLK->GENDIV.reg) = generator; - - /* Write the new generator configuration */ - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - GCLK->GENDIV.reg = new_gendiv_config; - - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - GCLK->GENCTRL.reg = new_genctrl_config | (GCLK->GENCTRL.reg & GCLK_GENCTRL_GENEN); - - system_interrupt_leave_critical_section(); -} - -/** - * \brief Enables a Generic Clock Generator that was previously configured. - * - * Starts the clock generation of a Generic Clock Generator that was previously - * configured via a call to \ref system_gclk_gen_set_config(). - * - * \param[in] generator Generic Clock Generator index to enable - */ -void system_gclk_gen_enable( - const uint8_t generator) -{ - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - system_interrupt_enter_critical_section(); - - /* Select the requested generator */ - *((uint8_t*)&GCLK->GENCTRL.reg) = generator; - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - /* Enable generator */ - GCLK->GENCTRL.reg |= GCLK_GENCTRL_GENEN; - - system_interrupt_leave_critical_section(); -} - -/** - * \brief Disables a Generic Clock Generator that was previously enabled. - * - * Stops the clock generation of a Generic Clock Generator that was previously - * started via a call to \ref system_gclk_gen_enable(). - * - * \param[in] generator Generic Clock Generator index to disable - */ -void system_gclk_gen_disable( - const uint8_t generator) -{ - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - system_interrupt_enter_critical_section(); - - /* Select the requested generator */ - *((uint8_t*)&GCLK->GENCTRL.reg) = generator; - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - /* Disable generator */ - GCLK->GENCTRL.reg &= ~GCLK_GENCTRL_GENEN; - while (GCLK->GENCTRL.reg & GCLK_GENCTRL_GENEN) { - /* Wait for clock to become disabled */ - } - - system_interrupt_leave_critical_section(); -} - -/** - * \brief Determins if the specified Generic Clock Generator is enabled. - * - * \param[in] generator Generic Clock Generator index to check - * - * \return The enabled status. - * \retval true The Generic Clock Generator is enabled - * \retval false The Generic Clock Generator is disabled - */ -bool system_gclk_gen_is_enabled( - const uint8_t generator) -{ - bool enabled; - - system_interrupt_enter_critical_section(); - - /* Select the requested generator */ - *((uint8_t*)&GCLK->GENCTRL.reg) = generator; - /* Obtain the enabled status */ - enabled = (GCLK->GENCTRL.reg & GCLK_GENCTRL_GENEN); - - system_interrupt_leave_critical_section(); - - return enabled; -} - -/** - * \brief Retrieves the clock frequency of a Generic Clock generator. - * - * Determines the clock frequency (in Hz) of a specified Generic Clock - * generator, used as a source to a Generic Clock Channel module. - * - * \param[in] generator Generic Clock Generator index - * - * \return The frequency of the generic clock generator, in Hz. - */ -uint32_t system_gclk_gen_get_hz( - const uint8_t generator) -{ - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - system_interrupt_enter_critical_section(); - - /* Select the appropriate generator */ - *((uint8_t*)&GCLK->GENCTRL.reg) = generator; - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - /* Get the frequency of the source connected to the GCLK generator */ - uint32_t gen_input_hz = system_clock_source_get_hz( - (enum system_clock_source)GCLK->GENCTRL.bit.SRC); - - *((uint8_t*)&GCLK->GENCTRL.reg) = generator; - - uint8_t divsel = GCLK->GENCTRL.bit.DIVSEL; - - /* Select the appropriate generator division register */ - *((uint8_t*)&GCLK->GENDIV.reg) = generator; - while (system_gclk_is_syncing()) { - /* Wait for synchronization */ - }; - - uint32_t divider = GCLK->GENDIV.bit.DIV; - - system_interrupt_leave_critical_section(); - - /* Check if the generator is using fractional or binary division */ - if (!divsel && divider > 1) { - gen_input_hz /= divider; - } else if (divsel) { - gen_input_hz >>= (divider+1); - } - - return gen_input_hz; -} - -/** - * \brief Writes a Generic Clock configuration to the hardware module. - * - * Writes out a given configuration of a Generic Clock configuration to the - * hardware module. If the clock is currently running, it will be stopped. - * - * \note Once called the clock will not be running; to start the clock, - * call \ref system_gclk_chan_enable() after configuring a clock channel. - * - * \param[in] channel Generic Clock channel to configure - * \param[in] config Configuration settings for the clock - * - */ -void system_gclk_chan_set_config( - const uint8_t channel, - struct system_gclk_chan_config *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Cache the new config to reduce sync requirements */ - uint32_t new_clkctrl_config = (channel << GCLK_CLKCTRL_ID_Pos); - - /* Select the desired generic clock generator */ - new_clkctrl_config |= config->source_generator << GCLK_CLKCTRL_GEN_Pos; - - /* Disable generic clock channel */ - system_gclk_chan_disable(channel); - - /* Write the new configuration */ - GCLK->CLKCTRL.reg = new_clkctrl_config; -} - -/** - * \brief Enables a Generic Clock that was previously configured. - * - * Starts the clock generation of a Generic Clock that was previously - * configured via a call to \ref system_gclk_chan_set_config(). - * - * \param[in] channel Generic Clock channel to enable - */ -void system_gclk_chan_enable( - const uint8_t channel) -{ - system_interrupt_enter_critical_section(); - - /* Select the requested generator channel */ - *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; - - /* Enable the generic clock */ - GCLK->CLKCTRL.reg |= GCLK_CLKCTRL_CLKEN; - - system_interrupt_leave_critical_section(); -} - -/** - * \brief Disables a Generic Clock that was previously enabled. - * - * Stops the clock generation of a Generic Clock that was previously started - * via a call to \ref system_gclk_chan_enable(). - * - * \param[in] channel Generic Clock channel to disable - */ -void system_gclk_chan_disable( - const uint8_t channel) -{ - system_interrupt_enter_critical_section(); - - /* Select the requested generator channel */ - *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; - - /* Sanity check WRTLOCK */ - Assert(!GCLK->CLKCTRL.bit.WRTLOCK); - - /* Switch to known-working source so that the channel can be disabled */ - uint32_t prev_gen_id = GCLK->CLKCTRL.bit.GEN; - GCLK->CLKCTRL.bit.GEN = 0; - - /* Disable the generic clock */ - GCLK->CLKCTRL.reg &= ~GCLK_CLKCTRL_CLKEN; - while (GCLK->CLKCTRL.reg & GCLK_CLKCTRL_CLKEN) { - /* Wait for clock to become disabled */ - } - - /* Restore previous configured clock generator */ - GCLK->CLKCTRL.bit.GEN = prev_gen_id; - - system_interrupt_leave_critical_section(); -} - -/** - * \brief Determins if the specified Generic Clock channel is enabled. - * - * \param[in] channel Generic Clock Channel index - * - * \return The enabled status. - * \retval true The Generic Clock channel is enabled - * \retval false The Generic Clock channel is disabled - */ -bool system_gclk_chan_is_enabled( - const uint8_t channel) -{ - bool enabled; - - system_interrupt_enter_critical_section(); - - /* Select the requested generic clock channel */ - *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; - enabled = GCLK->CLKCTRL.bit.CLKEN; - - system_interrupt_leave_critical_section(); - - return enabled; -} - -/** - * \brief Locks a Generic Clock channel from further configuration writes. - * - * Locks a generic clock channel from further configuration writes. It is only - * possible to unlock the channel configuration through a power on reset. - * - * \param[in] channel Generic Clock channel to enable - */ -void system_gclk_chan_lock( - const uint8_t channel) -{ - system_interrupt_enter_critical_section(); - - /* Select the requested generator channel */ - *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; - - /* Lock the generic clock */ - GCLK->CLKCTRL.reg |= GCLK_CLKCTRL_WRTLOCK; - - system_interrupt_leave_critical_section(); -} - -/** - * \brief Determins if the specified Generic Clock channel is locked. - * - * \param[in] channel Generic Clock Channel index - * - * \return The lock status. - * \retval true The Generic Clock channel is locked - * \retval false The Generic Clock channel is not locked - */ -bool system_gclk_chan_is_locked( - const uint8_t channel) -{ - bool locked; - - system_interrupt_enter_critical_section(); - - /* Select the requested generic clock channel */ - *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; - locked = GCLK->CLKCTRL.bit.WRTLOCK; - - system_interrupt_leave_critical_section(); - - return locked; -} - -/** - * \brief Retrieves the clock frequency of a Generic Clock channel. - * - * Determines the clock frequency (in Hz) of a specified Generic Clock - * channel, used as a source to a device peripheral module. - * - * \param[in] channel Generic Clock Channel index - * - * \return The frequency of the generic clock channel, in Hz. - */ -uint32_t system_gclk_chan_get_hz( - const uint8_t channel) -{ - uint8_t gen_id; - - system_interrupt_enter_critical_section(); - - /* Select the requested generic clock channel */ - *((uint8_t*)&GCLK->CLKCTRL.reg) = channel; - gen_id = GCLK->CLKCTRL.bit.GEN; - - system_interrupt_leave_critical_section(); - - /* Return the clock speed of the associated GCLK generator */ - return system_gclk_gen_get_hz(gen_id); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/gclk.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/gclk.h deleted file mode 100644 index 1e3caf3..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/gclk.h +++ /dev/null @@ -1,307 +0,0 @@ -/** - * \file - * - * \brief SAM Generic Clock Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef SYSTEM_CLOCK_GCLK_H_INCLUDED -#define SYSTEM_CLOCK_GCLK_H_INCLUDED - -/** - * \addtogroup asfdoc_sam0_system_clock_group - * - * @{ - */ - -#include "compiler.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief List of available GCLK generators. - * - * List of Available GCLK generators. This enum is used in the peripheral - * device drivers to select the GCLK generator to be used for its operation. - * - * The number of GCLK generators available is device dependent. - */ -enum gclk_generator { - /** GCLK generator channel 0 */ - GCLK_GENERATOR_0, -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 0) - /** GCLK generator channel 1 */ - GCLK_GENERATOR_1, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 1) - /** GCLK generator channel 2 */ - GCLK_GENERATOR_2, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 2) - /** GCLK generator channel 3 */ - GCLK_GENERATOR_3, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 3) - /** GCLK generator channel 4 */ - GCLK_GENERATOR_4, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 4) - /** GCLK generator channel 5 */ - GCLK_GENERATOR_5, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 5) - /** GCLK generator channel 6 */ - GCLK_GENERATOR_6, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 6) - /** GCLK generator channel 7 */ - GCLK_GENERATOR_7, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 7) - /** GCLK generator channel 8 */ - GCLK_GENERATOR_8, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 8) - /** GCLK generator channel 9 */ - GCLK_GENERATOR_9, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 9) - /** GCLK generator channel 10 */ - GCLK_GENERATOR_10, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 10) - /** GCLK generator channel 11 */ - GCLK_GENERATOR_11, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 11) - /** GCLK generator channel 12 */ - GCLK_GENERATOR_12, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 12) - /** GCLK generator channel 13 */ - GCLK_GENERATOR_13, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 13) - /** GCLK generator channel 14 */ - GCLK_GENERATOR_14, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 14) - /** GCLK generator channel 15 */ - GCLK_GENERATOR_15, -#endif -#if defined(__DOXYGEN__) || (GCLK_GEN_NUM_MSB > 15) - /** GCLK generator channel 16 */ - GCLK_GENERATOR_16, -#endif -}; - -/** - * \brief Generic Clock Generator configuration structure. - * - * Configuration structure for a Generic Clock Generator channel. This - * structure should be initialized by the - * \ref system_gclk_gen_get_config_defaults() function before being modified by - * the user application. - */ -struct system_gclk_gen_config { - /** Source clock input channel index, see the \ref system_clock_source */ - uint8_t source_clock; - /** If \c true, the generator output level is high when disabled */ - bool high_when_disabled; - /** Integer division factor of the clock output compared to the input */ - uint32_t division_factor; - /** If \c true, the clock is kept enabled during device standby mode */ - bool run_in_standby; - /** If \c true, enables GCLK generator clock output to a GPIO pin */ - bool output_enable; -}; - -/** - * \brief Generic Clock configuration structure. - * - * Configuration structure for a Generic Clock channel. This structure - * should be initialized by the \ref system_gclk_chan_get_config_defaults() - * function before being modified by the user application. - */ -struct system_gclk_chan_config { - /** Generic Clock Generator source channel */ - enum gclk_generator source_generator; -}; - -/** \name Generic Clock Management - * @{ - */ -void system_gclk_init(void); - -/** @} */ - - -/** - * \name Generic Clock Management (Generators) - * @{ - */ - -/** - * \brief Initializes a Generic Clock Generator configuration structure to defaults. - * - * Initializes a given Generic Clock Generator configuration structure to - * a set of known default values. This function should be called on all - * new instances of these configuration structures before being modified - * by the user application. - * - * The default configuration is: - * \li Clock is generated undivided from the source frequency - * \li Clock generator output is low when the generator is disabled - * \li The input clock is sourced from input clock channel 0 - * \li Clock will be disabled during sleep - * \li The clock output will not be routed to a physical GPIO pin - * - * \param[out] config Configuration structure to initialize to default values - */ -static inline void system_gclk_gen_get_config_defaults( - struct system_gclk_gen_config *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Default configuration values */ - config->division_factor = 1; - config->high_when_disabled = false; -#if SAML21 || SAML22 - config->source_clock = GCLK_SOURCE_OSC16M; -#elif (SAMC20) || (SAMC21) - config->source_clock = GCLK_SOURCE_OSC48M; -#else - config->source_clock = GCLK_SOURCE_OSC8M; -#endif - config->run_in_standby = false; - config->output_enable = false; -} - -void system_gclk_gen_set_config( - const uint8_t generator, - struct system_gclk_gen_config *const config); - -void system_gclk_gen_enable( - const uint8_t generator); - -void system_gclk_gen_disable( - const uint8_t generator); - -bool system_gclk_gen_is_enabled( - const uint8_t generator); - -/** @} */ - - -/** - * \name Generic Clock Management (Channels) - * @{ - */ - -/** - * \brief Initializes a Generic Clock configuration structure to defaults. - * - * Initializes a given Generic Clock configuration structure to a set of - * known default values. This function should be called on all new - * instances of these configuration structures before being modified by the - * user application. - * - * The default configuration is as follows: - * \li Clock is sourced from the Generic Clock Generator channel 0 - * \li Clock configuration will not be write-locked when set - * - * \param[out] config Configuration structure to initialize to default values - */ -static inline void system_gclk_chan_get_config_defaults( - struct system_gclk_chan_config *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Default configuration values */ - config->source_generator = GCLK_GENERATOR_0; -} - -void system_gclk_chan_set_config( - const uint8_t channel, - struct system_gclk_chan_config *const config); - -void system_gclk_chan_enable( - const uint8_t channel); - -void system_gclk_chan_disable( - const uint8_t channel); - -bool system_gclk_chan_is_enabled( - const uint8_t channel); - -void system_gclk_chan_lock( - const uint8_t channel); - -bool system_gclk_chan_is_locked( - const uint8_t channel); - -/** @} */ - - -/** - * \name Generic Clock Frequency Retrieval - * @{ - */ - -uint32_t system_gclk_gen_get_hz( - const uint8_t generator); - -uint32_t system_gclk_chan_get_hz( - const uint8_t channel); - -/** @} */ - -#ifdef __cplusplus -} -#endif - -/** @} */ - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/i2s.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/i2s.c deleted file mode 100644 index 31fe2d9..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/i2s.c +++ /dev/null @@ -1,750 +0,0 @@ -/** - * \file - * - * \brief SAM I2S - Inter-IC Sound Controller - * - * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#include "i2s.h" - -/** - * \brief Initializes a hardware I2S module instance - * - * Enables the clock and initialize the I2S module. - * - * \param[in,out] module_inst Pointer to the software module instance struct - * \param[in] hw Pointer to the TCC hardware module - * - * \return Status of the initialization procedure. - * - * \retval STATUS_OK The module was initialized successfully - * \retval STATUS_BUSY Hardware module was busy when the - * initialization procedure was attempted - * \retval STATUS_ERR_DENIED Hardware module was already enabled - */ -enum status_code i2s_init( - struct i2s_module *const module_inst, - I2s *hw) -{ - Assert(module_inst); - Assert(hw); - - /* Enable the user interface clock in the PM */ - system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, PM_APBCMASK_I2S); - - /* Status check */ - uint32_t ctrla; - ctrla = module_inst->hw->CTRLA.reg; - if (ctrla & I2S_CTRLA_ENABLE) { - if (ctrla & (I2S_CTRLA_SEREN1 | - I2S_CTRLA_SEREN0 | I2S_CTRLA_CKEN1 | I2S_CTRLA_CKEN0)) { - return STATUS_BUSY; - } else { - return STATUS_ERR_DENIED; - } - } - - /* Initialize module */ - module_inst->hw = hw; - - /* Initialize serializers */ -#if I2S_CALLBACK_MODE == true - int i, j; - for (i = 0; i < 2; i ++) { - for (j = 0; j < I2S_SERIALIZER_CALLBACK_N; j ++) { - module_inst->serializer[i].callback[j] = NULL; - } - module_inst->serializer[i].registered_callback_mask = 0; - module_inst->serializer[i].enabled_callback_mask = 0; - - module_inst->serializer[i].job_buffer = NULL; - module_inst->serializer[i].job_status = STATUS_OK; - module_inst->serializer[i].requested_words = 0; - module_inst->serializer[i].transferred_words = 0; - - module_inst->serializer[i].mode = I2S_SERIALIZER_RECEIVE; - module_inst->serializer[i].data_size = I2S_DATA_SIZE_32BIT; - } - - _i2s_instances[0] = module_inst; - - system_interrupt_enable(SYSTEM_INTERRUPT_MODULE_I2S); -#endif - - return STATUS_OK; -} - - -/** - * \brief Configure specified I2S clock unit - * - * Enables the clock and initialize the clock unit, based on the given - * configurations. - * - * \param[in,out] module_inst Pointer to the software module instance struct - * \param[in] clock_unit I2S clock unit to initialize and configure - * \param[in] config Pointer to the I2S clock unit configuration - * options struct - * - * \return Status of the configuration procedure. - * - * \retval STATUS_OK The module was initialized successfully - * \retval STATUS_BUSY Hardware module was busy when the - * configuration procedure was attempted - * \retval STATUS_ERR_DENIED Hardware module was already enabled - * \retval STATUS_ERR_INVALID_ARG Invalid divider value or - * MCK direction setting conflict - */ -enum status_code i2s_clock_unit_set_config( - struct i2s_module *const module_inst, - const enum i2s_clock_unit clock_unit, - const struct i2s_clock_unit_config *config) -{ - Assert(module_inst); - Assert(module_inst->hw); - Assert(clock_unit < I2S_CLOCK_UNIT_N); - Assert(config); - - /* Status check */ - uint32_t ctrla, syncbusy; - syncbusy = module_inst->hw->SYNCBUSY.reg; - ctrla = module_inst->hw->CTRLA.reg; - - /* Busy ? */ - if (syncbusy & (I2S_SYNCBUSY_CKEN0 << clock_unit)) { - return STATUS_BUSY; - } - /* Already enabled ? */ - if (ctrla & (I2S_CTRLA_CKEN0 << clock_unit)) { - return STATUS_ERR_DENIED; - } - /* Parameter check */ - if (config->clock.mck_src && config->clock.mck_out_enable) { - return STATUS_ERR_INVALID_ARG; - } - - /* Initialize Clock Unit */ - uint32_t clkctrl = - (config->clock.mck_out_invert ? I2S_CLKCTRL_MCKOUTINV : 0) | - (config->clock.sck_out_invert ? I2S_CLKCTRL_SCKOUTINV : 0) | - (config->frame.frame_sync.invert_out ? I2S_CLKCTRL_FSOUTINV : 0) | - (config->clock.mck_out_enable ? I2S_CLKCTRL_MCKEN : 0) | - (config->clock.mck_src ? I2S_CLKCTRL_MCKSEL : 0) | - (config->clock.sck_src ? I2S_CLKCTRL_SCKSEL : 0) | - (config->frame.frame_sync.invert_use ? I2S_CLKCTRL_FSINV : 0) | - (config->frame.frame_sync.source ? I2S_CLKCTRL_FSSEL : 0) | - (config->frame.data_delay ? I2S_CLKCTRL_BITDELAY : 0); - - uint8_t div_val = config->clock.mck_out_div; - if ((div_val > 0x21) || (div_val == 0)) { - return STATUS_ERR_INVALID_ARG; - } else { - div_val --; - } - clkctrl |= I2S_CLKCTRL_MCKOUTDIV(div_val); - - div_val = config->clock.sck_div; - if ((div_val > 0x21) || (div_val == 0)) { - return STATUS_ERR_INVALID_ARG; - } else { - div_val --; - } - clkctrl |= I2S_CLKCTRL_MCKDIV(div_val); - - uint8_t number_slots = config->frame.number_slots; - if (number_slots > 8) { - return STATUS_ERR_INVALID_ARG; - } else if (number_slots > 0) { - number_slots --; - } - clkctrl |= - I2S_CLKCTRL_NBSLOTS(number_slots) | - I2S_CLKCTRL_FSWIDTH(config->frame.frame_sync.width) | - I2S_CLKCTRL_SLOTSIZE(config->frame.slot_size); - - /* Write clock unit configurations */ - module_inst->hw->CLKCTRL[clock_unit].reg = clkctrl; - - /* Select general clock source */ - const uint8_t i2s_gclk_ids[2] = {I2S_GCLK_ID_0, I2S_GCLK_ID_1}; - struct system_gclk_chan_config gclk_chan_config; - system_gclk_chan_get_config_defaults(&gclk_chan_config); - gclk_chan_config.source_generator = config->clock.gclk_src; - system_gclk_chan_set_config(i2s_gclk_ids[clock_unit], &gclk_chan_config); - system_gclk_chan_enable(i2s_gclk_ids[clock_unit]); - - /* Initialize pins */ - struct system_pinmux_config pin_config; - system_pinmux_get_config_defaults(&pin_config); - if (config->mck_pin.enable) { - pin_config.mux_position = config->mck_pin.mux; - system_pinmux_pin_set_config(config->mck_pin.gpio, &pin_config); - } - if (config->sck_pin.enable) { - pin_config.mux_position = config->sck_pin.mux; - system_pinmux_pin_set_config(config->sck_pin.gpio, &pin_config); - } - if (config->fs_pin.enable) { - pin_config.mux_position = config->fs_pin.mux; - system_pinmux_pin_set_config(config->fs_pin.gpio, &pin_config); - } - - return STATUS_OK; -} - - -/** - * \brief Configure specified I2S serializer - * - * Enables the clock and initialize the serializer, based on the given - * configurations. - * - * \param[in,out] module_inst Pointer to the software module instance struct - * \param[in] serializer I2S serializer to initialize and configure - * \param[in] config Pointer to the I2S serializer configuration - * options struct - * - * \return Status of the configuration procedure. - * - * \retval STATUS_OK The module was initialized successfully - * \retval STATUS_BUSY Hardware module was busy when the - * configuration procedure was attempted - * \retval STATUS_ERR_DENIED Hardware module was already enabled - */ -enum status_code i2s_serializer_set_config( - struct i2s_module *const module_inst, - const enum i2s_serializer serializer, - const struct i2s_serializer_config *config) -{ - Assert(module_inst); - Assert(module_inst->hw); - Assert(serializer < I2S_SERIALIZER_N); - Assert(config); - - /* Status check */ - uint32_t ctrla, syncbusy; - syncbusy = module_inst->hw->SYNCBUSY.reg; - ctrla = module_inst->hw->CTRLA.reg; - - /* Busy ? */ - if (syncbusy & ((I2S_SYNCBUSY_SEREN0 | I2S_SYNCBUSY_DATA0) << serializer)) { - return STATUS_BUSY; - } - /* Already enabled ? */ - if (ctrla & (I2S_CTRLA_CKEN0 << serializer)) { - return STATUS_ERR_DENIED; - } - - /* Initialize Serializer */ - uint32_t serctrl = - (config->loop_back ? I2S_SERCTRL_RXLOOP : 0) | - (config->dma_usage ? I2S_SERCTRL_DMA : 0) | - (config->mono_mode ? I2S_SERCTRL_MONO : 0) | - (config->disable_data_slot[7] ? I2S_SERCTRL_SLOTDIS7 : 0) | - (config->disable_data_slot[6] ? I2S_SERCTRL_SLOTDIS6 : 0) | - (config->disable_data_slot[5] ? I2S_SERCTRL_SLOTDIS5 : 0) | - (config->disable_data_slot[4] ? I2S_SERCTRL_SLOTDIS4 : 0) | - (config->disable_data_slot[3] ? I2S_SERCTRL_SLOTDIS3 : 0) | - (config->disable_data_slot[2] ? I2S_SERCTRL_SLOTDIS2 : 0) | - (config->disable_data_slot[1] ? I2S_SERCTRL_SLOTDIS1 : 0) | - (config->disable_data_slot[0] ? I2S_SERCTRL_SLOTDIS0 : 0) | - (config->transfer_lsb_first ? I2S_SERCTRL_BITREV : 0) | - (config->data_adjust_left_in_word ? I2S_SERCTRL_WORDADJ : 0) | - (config->data_adjust_left_in_slot ? I2S_SERCTRL_SLOTADJ : 0) | - (config->data_padding ? I2S_SERCTRL_TXSAME : 0); - - if (config->clock_unit < I2S_CLOCK_UNIT_N) { - serctrl |= (config->clock_unit ? I2S_SERCTRL_CLKSEL : 0); - } else { - return STATUS_ERR_INVALID_ARG; - } - - serctrl |= - I2S_SERCTRL_SERMODE(config->mode) | - I2S_SERCTRL_TXDEFAULT(config->line_default_state) | - I2S_SERCTRL_DATASIZE(config->data_size) | - I2S_SERCTRL_EXTEND(config->bit_padding); - - /* Write Serializer configuration */ - module_inst->hw->SERCTRL[serializer].reg = serctrl; - - /* Initialize pins */ - struct system_pinmux_config pin_config; - system_pinmux_get_config_defaults(&pin_config); - if (config->data_pin.enable) { - pin_config.mux_position = config->data_pin.mux; - system_pinmux_pin_set_config(config->data_pin.gpio, &pin_config); - } - - /* Save configure */ - module_inst->serializer[serializer].mode = config->mode; - module_inst->serializer[serializer].data_size = config->data_size; - - return STATUS_OK; -} - - - -/** - * \brief Retrieves the current module status. - * - * Retrieves the status of the module, giving overall state information. - * - * \param[in] module_inst Pointer to the I2S software instance struct - * - * \return Bitmask of \c I2S_STATUS_* flags - * - * \retval I2S_STATUS_SYNC_BUSY Module is busy synchronization - * \retval I2S_STATUS_TRANSMIT_UNDERRUN(x) Serializer x (0~1) is underrun - * \retval I2S_STATUS_TRANSMIT_READY(x) Serializer x (0~1) is ready to - * transmit new data word - * \retval I2S_STATUS_RECEIVE_OVERRUN(x) Serializer x (0~1) is overrun - * \retval I2S_STATUS_RECEIVE_READY(x) Serializer x (0~1) has data ready to - * read - */ -uint32_t i2s_get_status( - const struct i2s_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - uint32_t intflag = module_inst->hw->INTFLAG.reg; - uint32_t status; - if (module_inst->hw->SYNCBUSY.reg) { - status = I2S_STATUS_SYNC_BUSY; - } else { - status = 0; - } - if (intflag & I2S_INTFLAG_TXUR0) { - status |= I2S_STATUS_TRANSMIT_UNDERRUN(0); - } - if (intflag & I2S_INTFLAG_TXUR1) { - status |= I2S_STATUS_TRANSMIT_UNDERRUN(1); - } - if ((intflag & I2S_INTFLAG_TXRDY0) && - !module_inst->hw->SYNCBUSY.bit.DATA0) { - status |= I2S_STATUS_TRANSMIT_READY(0); - } - if ((intflag & I2S_INTFLAG_TXRDY1) && - !module_inst->hw->SYNCBUSY.bit.DATA1) { - status |= I2S_STATUS_TRANSMIT_READY(1); - } - if (intflag & I2S_INTFLAG_RXOR0) { - status |= I2S_STATUS_RECEIVE_OVERRUN(0); - } - if (intflag & I2S_INTFLAG_RXOR1) { - status |= I2S_STATUS_RECEIVE_OVERRUN(1); - } - if (intflag & I2S_INTFLAG_RXRDY0) { - status |= I2S_STATUS_RECEIVE_READY(0); - } - if (intflag & I2S_INTFLAG_RXRDY1) { - status |= I2S_STATUS_RECEIVE_READY(1); - } - return status; -} - -/** - * \brief Clears a module status flags. - * - * Clears the given status flags of the module. - * - * \param[in] module_inst Pointer to the I2S software instance struct - * \param[in] status Bitmask of \c I2S_STATUS_* flags to clear - */ -void i2s_clear_status( - const struct i2s_module *const module_inst, - uint32_t status) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - uint32_t intflag = 0; - - if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { - intflag = I2S_INTFLAG_TXUR0; - } - if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { - intflag = I2S_INTFLAG_TXUR1; - } - if (status & I2S_STATUS_TRANSMIT_READY(0)) { - intflag = I2S_INTFLAG_TXRDY0; - } - if (status & I2S_STATUS_TRANSMIT_READY(1)) { - intflag = I2S_INTFLAG_TXRDY1; - } - if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { - intflag = I2S_INTFLAG_RXOR0; - } - if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { - intflag = I2S_INTFLAG_RXOR1; - } - if (status & I2S_STATUS_RECEIVE_READY(0)) { - intflag = I2S_INTFLAG_RXRDY0; - } - if (status & I2S_STATUS_RECEIVE_READY(1)) { - intflag = I2S_INTFLAG_RXRDY1; - } - module_inst->hw->INTFLAG.reg = intflag; -} - -/** - * \brief Enable interrupts on status set - * - * Enable the given status interrupt request from the I2S module. - * - * \param[in] module_inst Pointer to the I2S software instance struct - * \param[in] status Status interrupts to enable - * - * \return Status of enable procedure - * - * \retval STATUS_OK Interrupt is enabled successfully - * \retval STATUS_ERR_INVALID_ARG Status with no interrupt is passed - */ -enum status_code i2s_enable_status_interrupt( - struct i2s_module *const module_inst, - uint32_t status) -{ - /* Sanity check arguments */ - Assert(module_inst); - - /* No sync busy interrupt */ - if (status & I2S_STATUS_SYNC_BUSY) { - return STATUS_ERR_INVALID_ARG; - } - Assert(module_inst->hw); - - uint32_t intflag = 0; - if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { - intflag = I2S_INTFLAG_TXUR0; - } - if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { - intflag = I2S_INTFLAG_TXUR1; - } - if (status & I2S_STATUS_TRANSMIT_READY(0)) { - intflag = I2S_INTFLAG_TXRDY0; - } - if (status & I2S_STATUS_TRANSMIT_READY(1)) { - intflag = I2S_INTFLAG_TXRDY1; - } - if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { - intflag = I2S_INTFLAG_RXOR0; - } - if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { - intflag = I2S_INTFLAG_RXOR1; - } - if (status & I2S_STATUS_RECEIVE_READY(0)) { - intflag = I2S_INTFLAG_RXRDY0; - } - if (status & I2S_STATUS_RECEIVE_READY(1)) { - intflag = I2S_INTFLAG_RXRDY1; - } - module_inst->hw->INTENSET.reg = intflag; - return STATUS_OK; -} - -/** - * \brief Disable interrupts on status set - * - * Disable the given status interrupt request from the I2S module. - * - * \param[in] module_inst Pointer to the I2S software instance struct - * \param[in] status Status interrupts to disable - */ -void i2s_disable_status_interrupt( - struct i2s_module *const module_inst, - uint32_t status) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - uint32_t intflag = 0; - if (status & I2S_STATUS_TRANSMIT_UNDERRUN(0)) { - intflag = I2S_INTFLAG_TXUR0; - } - if (status & I2S_STATUS_TRANSMIT_UNDERRUN(1)) { - intflag = I2S_INTFLAG_TXUR1; - } - if (status & I2S_STATUS_TRANSMIT_READY(0)) { - intflag = I2S_INTFLAG_TXRDY0; - } - if (status & I2S_STATUS_TRANSMIT_READY(1)) { - intflag = I2S_INTFLAG_TXRDY1; - } - if (status & I2S_STATUS_RECEIVE_OVERRUN(0)) { - intflag = I2S_INTFLAG_RXOR0; - } - if (status & I2S_STATUS_RECEIVE_OVERRUN(1)) { - intflag = I2S_INTFLAG_RXOR1; - } - if (status & I2S_STATUS_RECEIVE_READY(0)) { - intflag = I2S_INTFLAG_RXRDY0; - } - if (status & I2S_STATUS_RECEIVE_READY(1)) { - intflag = I2S_INTFLAG_RXRDY1; - } - module_inst->hw->INTENCLR.reg = intflag; -} - - -/** - * \brief Write buffer to the specified Serializer of I2S module - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer The serializer to write to - * \param[in] buffer The data buffer to write - * \param[in] size Number of data words to write - * - * \return Status of the initialization procedure. - * - * \retval STATUS_OK The data was sent successfully - * \retval STATUS_ERR_DENIED The module or serializer is disabled - * \retval STATUS_ERR_INVALID_ARG An invalid buffer pointer was supplied - */ -enum status_code i2s_serializer_write_buffer_wait( - const struct i2s_module *const module_inst, - enum i2s_serializer serializer, - void *buffer, uint32_t size) -{ - Assert(module_inst); - Assert(module_inst->hw); - Assert(serializer < I2S_SERIALIZER_N); - Assert(buffer); - - if (size == 0) { - return STATUS_OK; - } - - uint8_t data_size = 1; /* number of bytes */ - struct i2s_serializer_module *data_module = (struct i2s_serializer_module *) - &module_inst->serializer[serializer]; - - /* Check buffer */ - switch(data_module->data_size) { - case I2S_DATA_SIZE_32BIT: - case I2S_DATA_SIZE_24BIT: - case I2S_DATA_SIZE_20BIT: - case I2S_DATA_SIZE_18BIT: - if ((uint32_t)buffer & 0x3) { - return STATUS_ERR_INVALID_ARG; - } - data_size = 4; - break; - case I2S_DATA_SIZE_16BIT: - case I2S_DATA_SIZE_16BIT_COMPACT: - if ((uint32_t)buffer & 0x1) { - return STATUS_ERR_INVALID_ARG; - } - data_size = 2; - break; - default: - break; - } - - /* Check status */ - if (!(module_inst->hw->CTRLA.reg & - (I2S_CTRLA_ENABLE | (I2S_CTRLA_SEREN0 << serializer)))) { - return STATUS_ERR_DENIED; - } - - /* Write */ - uint32_t i; - uint32_t sync_bit = I2S_SYNCBUSY_DATA0 << serializer; - uint32_t ready_bit = I2S_INTFLAG_TXRDY0 << serializer; - if (4 == data_size) { - uint32_t *p32 = (uint32_t*)buffer; - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Tx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - module_inst->hw->DATA[serializer].reg = p32[i]; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } else if (2 == data_size) { - uint16_t *p16 = (uint16_t*)buffer; - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Tx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - module_inst->hw->DATA[serializer].reg = p16[i]; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } else { - uint8_t *p8 = (uint8_t*)buffer; - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Tx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - module_inst->hw->DATA[serializer].reg = p8[i]; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } - - return STATUS_OK; -} - -/** - * \brief Read from the specified Serializer of I2S module to a buffer - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer The serializer to write to - * \param[in] buffer The buffer to fill read data (NULL to discard) - * \param[in] size Number of data words to read - * - * \return Status of the initialization procedure. - * - * \retval STATUS_OK The data was sent successfully - * \retval STATUS_ERR_DENIED The module or serializer is disabled - * \retval STATUS_ERR_INVALID_ARG An invalid buffer pointer was supplied - */ -enum status_code i2s_serializer_read_buffer_wait( - const struct i2s_module *const module_inst, - enum i2s_serializer serializer, - void *buffer, uint32_t size) -{ - Assert(module_inst); - Assert(module_inst->hw); - - if (size == 0) { - return STATUS_OK; - } - - uint8_t data_size = 1; /* number of bytes */ - struct i2s_serializer_module *data_module = (struct i2s_serializer_module *) - &module_inst->serializer[serializer]; - - /* Check buffer */ - switch(data_module->data_size) { - case I2S_DATA_SIZE_32BIT: - case I2S_DATA_SIZE_24BIT: - case I2S_DATA_SIZE_20BIT: - case I2S_DATA_SIZE_18BIT: - if ((uint32_t)buffer & 0x3) { - return STATUS_ERR_INVALID_ARG; - } - data_size = 4; - break; - case I2S_DATA_SIZE_16BIT: - case I2S_DATA_SIZE_16BIT_COMPACT: - if ((uint32_t)buffer & 0x1) { - return STATUS_ERR_INVALID_ARG; - } - data_size = 2; - break; - default: - break; - } - - /* Check status */ - if (!(module_inst->hw->CTRLA.reg & - (I2S_CTRLA_ENABLE | (I2S_CTRLA_SEREN0 << serializer)))) { - return STATUS_ERR_DENIED; - } - - /* Read */ - uint32_t i; - uint32_t sync_bit = I2S_SYNCBUSY_DATA0 << serializer; - uint32_t ready_bit = I2S_INTFLAG_RXRDY0 << serializer; - if (buffer == NULL) { - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Rx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - module_inst->hw->DATA[serializer].reg; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } - else if (4 == data_size) { - uint32_t *p32 = (uint32_t*)buffer; - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Rx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - p32[i] = module_inst->hw->DATA[serializer].reg; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } else if (2 == data_size) { - uint16_t *p16 = (uint16_t*)buffer; - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Rx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - p16[i] = module_inst->hw->DATA[serializer].reg; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } else { - uint8_t *p8 = (uint8_t*)buffer; - for (i = 0; i < size; i ++) { - while(!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait Tx ready */ - } - while(module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait Sync */ - } - p8[i] = module_inst->hw->DATA[serializer].reg; - module_inst->hw->INTFLAG.reg = ready_bit; - } - } - - return STATUS_OK; -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/i2s.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/i2s.h deleted file mode 100644 index 9911e6d..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/i2s.h +++ /dev/null @@ -1,1404 +0,0 @@ -/** - * \file - * - * \brief SAM I2S - Inter-IC Sound Controller - * - * Copyright (c) 2014-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#ifndef I2S_H_INCLUDED -#define I2S_H_INCLUDED - -/** - * \defgroup asfdoc_sam0_i2s_group SAM Inter-IC Sound Controller Driver (I2S) - * - * This driver for Atmel® | SMART SAM devices provides an interface for the configuration - * and management of the device's Inter-IC Sound Controller functionality. - * - * The following driver API modes are covered by this manual: - * - Polled APIs - * \if I2S_CALLBACK_MODE - * - Callback APIs - * \endif - * - * The following peripherals are used by this module: - * - I2S (Inter-IC Sound Controller) - * - * The following devices can use this module: - * - Atmel | SMART SAM D21 - * - Atmel | SMART SAM DA1 - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_i2s_prerequisites - * - \ref asfdoc_sam0_i2s_module_overview - * - \ref asfdoc_sam0_i2s_special_considerations - * - \ref asfdoc_sam0_i2s_extra_info - * - \ref asfdoc_sam0_i2s_examples - * - \ref asfdoc_sam0_i2s_api_overview - * - * \section asfdoc_sam0_i2s_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * \section asfdoc_sam0_i2s_module_overview Module Overview - * - * The I2S provides bidirectional, synchronous, digital audio link with external - * audio devices through these signal pins: - * - Serial Data (SDm) - * - Frame Sync (FSn) - * - Serial Clock (SCKn) - * - Master Clock (MCKn) - * - * The I2S consists of 2 Clock Units and 2 Serializers, which can be separately - * configured and enabled, to provide varies functionalities as follow: - * - Communicate to Audio CODECs as Master or Slave, or provides clock and - * frame sync signals as Controller - * - Communicate to DAC or ADC through dedicated I2S serial interface - * - Communicate to multi-slot or multiple stereo DACs or ADCs, via - * Time Division Multiplexed (TDM) format - * - Reading mono or stereo MEMS microphones, using the Pulse Density - * Modulation (PDM) interface - * - * The I2S supports compact stereo data word, where left channel data bits are - * in lower half and right channel data bits are in upper half. It reduces the - * number of data words for stereo audio data and the DMA bandwidth. - * - * In master mode, the frame is configured by number of slots and slot size, and - * allows range covering 16fs to 1024fs MCK, to provide oversampling clock to an - * external audio CODEC or digital signal processor (DSP). - * - * A block diagram of the I2S can be seen in - * \ref asfdoc_sam0_i2s_module_block_diagram "the figure below". - * - * \anchor asfdoc_sam0_i2s_module_block_diagram - * \image html i2s_blocks.svg "I2S Block Diagram" - * - * This driver for I2S module provides an interface to - * - initialize and control I2S module - * - configure and control the I2S Clock Unit and Serializer - * - transmit/receive data through I2S Serializer - * - * \subsection asfdoc_sam0_i2s_module_overview_clocks Clocks - * - * To use I2S module, the I2S bus interface clock (clk_i2s) must be enabled via - * Power Manager. - * - * For each I2S Clock Unit, a generic clock (gclk_i2s_n) is connnected. When I2S - * works in master mode the generic clock is used. It should be prepared before - * clock unit is used. In master mode the input generic clock will be used as - * MCK for SCKn and FSn generation, in addition, the MCK could be devided and - * output to I2S MCKn pin, as oversampling clock to external audio device. - * - * The I2S Serializer uses clock and control signal from Clock Unit to handle - * transfer. Select different clock unit with different configurations allows - * the I2S to work as master or slave, to work on non-related clocks. - * - * When using the driver with ASF, enabling the register interface is normally - * done by the \c init function. - * The gclk source for the asynchronous domain is normally configured and set - * through the _configuration struct_ / _init_ function. - * If gclk source != 0 is used, this source has to be configured and enabled - * through invoking the system_gclk driver function when needed, or modifying - * conf_clock.h to enable it at the beginning. - * - * \subsection asfdoc_sam0_i2s_module_overview_frame Audio Frame Generation - * - * Audio sample data for all channels are sent in frames, one frame can consist - * 1 - 8 slots where each slot can be configured to a size 8-bit, 16-bit, 24-bit - * or 32-bit. The audio frame synch clock is generated by the I2S Clock unit in - * the master/controller mode. The frame rate (or frame sync frequency) is - * calculated as follow: - * - * FS = SCK / number_of_slots / number_of_bits_in_slot - * - * The serial clock (SCK) source is either an external source (slave mode) or - * generated by the I2S clock unit (controller or master mode) using the MCK as - * source. - * - * SCK = MCK / sck_div - * \note SCK generation division value is MCKDIV in register. - * - * MCK is either an external source or generated using the gclk input from a - * generic clock generator. - * - * \subsection asfdoc_sam0_i2s_module_overview_mode Master, Controller and Slave modes - * - * The i2s module has three modes: master, controller and slave. - * - * \subsubsection asfdoc_sam0_i2s_module_overview_mode_mst Master - * In master mode the module will control the data flow on the i2s bus and can - * be responsible for clock generation. The Serializers are enabled and will - * transmit/receive data. On a bus with only master and slave the SCK and FS - * clock signal will be outputted on the SCK and FS pin on the master module. - * MCK can optionally be outputted on the MCK pin, if there is a controller - * module on the bus the SCK, FS and optionally the MCK clock is sourced from - * the same pins. Serial data will be trancieved on the SD pin in both - * scenarios. - * - * \subsubsection asfdoc_sam0_i2s_module_overview_mode_ctl Controller - * In controller mode the module will generate the clock signals, but the - * Serializers are disabled and no data will be transmitted/received by the - * module in this mode. The clock signals is outputted on the SCK, FS and - * optionally the MCK pin. - * - * \subsubsection asfdoc_sam0_i2s_module_overview_mode_slv Slave - * In slave mode the module will use the SCK and FS clock source from the master - * or the controller which is received on the SCK and FS pin. The MCK can - * optionally be sourced externally on the MCK pin. The Serializers are enabled - * and will tranceive data on the SD pin. All data flow is controlled by the - * master. - * - * \subsubsection asfdoc_sam0_i2s_module_overview_mode_chg Switch modes - * The mode switching between master, controller and slave modes are actually - * done by modifying the source mode of I2S pins. - * The source mode of I2S pins are selected by writing corresponding bits in - * CLKCTRLn. - * Since source mode switching changes the direction of pin, the mode must be - * changed when the I2S Clock Unit is stopped. - * - * \subsection asfdoc_sam0_i2s_module_overview_data Data Stream Reception/Transmission - * - * The I2S module support several data stream formats: - * - I2S format - * - Time Division Multiplexed (TDM) format - * - Pulse Density Modulation (PDM) format (reception only) - * - * Basically the I2S module can send several words within each frame, it's more - * like TDM format. With adjust to the number of data words in a frame, the FS - * width, the FS to data bits delay, etc., the module is able to handle I2S - * compliant data stream. - * - * Also the Serializer can receive PDM format data stream, which allows the I2S - * module receive 1 PDM data on each SCK edge. - * - * \subsubsection asfdoc_sam0_i2s_module_overview_data_i2s I2S Stream Reception/Transmission - * - * For 2-channel I2S compliant data stream format the i2s module uses the FS - * line as word select (WS) signal and will send left channel data word on low - * WS level and right channel data word on high WS level as specified in the I2S - * standard. The supported word sizes are 8-, 16-, 18-, 20-, 24- and 32- bit. - * - * Thus for I2S stream, the following settings should be applied to the module: - * - Data starting delay after FS transition : one SCK period - * - FS width : half of frame - * - Data bits adjust in word : left-adjusted - * - Bit transmitting order : MSB first - * - * Following is an example for I2S application connections and waveforms. See - * \ref asfdoc_sam0_i2s_module_i2s_example_diagram "the figure below". - * - * \anchor asfdoc_sam0_i2s_module_i2s_example_diagram - * \image html i2s_example.svg "I2S Example Diagram" - * - * \subsubsection asfdoc_sam0_i2s_module_overview_data_tdm TDM Stream Reception/Transmission - * In TDM format, the module sends several data words in each frame. For this - * data stream format most of the configurations could be adjusted: - * - Main Frame related settings are as follow: - * - Frame Sync (FS) options: - * - the active edge of the FS (or if FS is inverted before use) - * - the width of the FS - * - the delay between FS to first data bit - * - Data alignment in slot - * - The number of slots and slot size can be adjusted, it has been mentioned - * in \ref asfdoc_sam0_i2s_module_overview_frame - * - The data word size is controlled by Serializer, it can be chosen among - * 8, 16, 18, 20, 24 and 32 bits. - * - * The general TDM waveform generation is as follow: - * - * \anchor asfdoc_sam0_i2s_module_tdm_wave_diagram - * \image html tdm_wave.svg "TDM Waveform generation" - * - * Some other settings could also be found to set up clock, data formatting and - * pin mux. - * refer to \ref i2s_clock_unit_config "Clock Unit Configurations" - * and \ref i2s_serializer_config "Serializer Configurations" for more - * details. - * - * Following is examples for different application use cases. - * - * See \ref asfdoc_sam0_i2s_module_tdm_timeslot_example_diagram "here" for - * the Time Slot Application connection and waveform example. - * - * \anchor asfdoc_sam0_i2s_module_tdm_timeslot_example_diagram - * \image html tdm_timeslot_example.svg "Codec Example Diagram" - * - * See \ref asfdoc_sam0_i2s_module_tdm_codec_example_diagram "here" for the - * Codec Application connection and waveform example. - * - * \anchor asfdoc_sam0_i2s_module_tdm_codec_example_diagram - * \image html tdm_codec_example.svg "Time Slot Example Diagram" - * - * \subsubsection asfdoc_sam0_i2s_module_overview_data_pdm PDM Reception - * The I2S Serializer integrates PDM reception feature, to use this feature, - * simply select PDM2 mode in Serializer configuration. In PDM2 mode, it assumes - * two microphones are input for stereo stream. The left microphone bits will - * be stored in lower half and right microphone bits in upper half of the data - * word, like in compact stereo format. - * - * See \ref asfdoc_sam0_i2s_module_pdm_example_diagram "following figure" for an - * example of PDM Microphones Application with both left and right channel - * microphone connected. - * - * \anchor asfdoc_sam0_i2s_module_pdm_example_diagram - * \image html pdm_example.svg "Time PDM2 Example Diagram" - * - * \subsubsection asfdoc_sam0_i2s_module_overview_data_fmt MONO and Compact Data - * The I2S Serializer can accept some pre-defined data format and generates - * the data stream in specified way. - * - * When transmitting data, the Serializer can work in MONO mode: assum input - * is single channel mono data on left channel and copy it to right channel - * automatically. - * - * Also the I2S Serializer can support compact stereo data word. The data word - * size of the Serializer can be set to \ref I2S_DATA_SIZE_16BIT_COMPACT - * "16-bit compact" or \ref I2S_DATA_SIZE_8BIT_COMPACT "8-bit compact", with - * these option I2S Serializer will compact left channel data and right channel - * data together, the left channel data will take lower bytes and right channel - * data take higher bytes. - * - * \subsection asfdoc_sam0_i2s_module_overview_loop Loop-back Mode - * The I2S can be configured to loop back the Transmitter to Receiver. In this - * mode Serializer's input will be connected to another Serializer's output - * internally. - * - * \subsection asfdoc_sam0_i2s_module_overview_sleep Sleep Modes - * The I2S will continue to operate in any sleep mode, where the selected source - * clocks are running. - * - * \section asfdoc_sam0_i2s_special_considerations Special Considerations - * - * There is no special considerations for I2S module. - * - * \section asfdoc_sam0_i2s_extra_info Extra Information - * - * For extra information see \ref asfdoc_sam0_i2s_extra. This includes: - * - \ref asfdoc_sam0_i2s_extra_acronyms - * - \ref asfdoc_sam0_i2s_extra_dependencies - * - \ref asfdoc_sam0_i2s_extra_errata - * - \ref asfdoc_sam0_i2s_extra_history - * - * \section asfdoc_sam0_i2s_examples Examples - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_i2s_exqsg. - * - * - * \section asfdoc_sam0_i2s_api_overview API Overview - * @{ - */ - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include - -#if I2S_CALLBACK_MODE == true -# include - -#if !defined(__DOXYGEN__) -extern struct i2s_module *_i2s_instances[I2S_INST_NUM]; -#endif - -/** Forward definition of the device instance */ -struct i2s_module; - -/** Type of the callback functions */ -typedef void (*i2s_serializer_callback_t) - (struct i2s_module *const module); - -/** - * \brief I2S Serializer Callback enum - */ -enum i2s_serializer_callback { - /** Callback for buffer read/write finished */ - I2S_SERIALIZER_CALLBACK_BUFFER_DONE, - /** Callback for Serializer overrun/underrun */ - I2S_SERIALIZER_CALLBACK_OVER_UNDER_RUN, -# if !defined(__DOXYGEN__) - I2S_SERIALIZER_CALLBACK_N -# endif -}; - -#endif /* #if I2S_CALLBACK_MODE == true */ - -/** - * \name Module status flags - * - * I2S status flags, returned by \ref i2s_get_status() and cleared by - * \ref i2s_clear_status(). - * - * @{ - */ - -/** Module Serializer x (0~1) Transmit Underrun */ -#define I2S_STATUS_TRANSMIT_UNDERRUN(x) (1u << ((x)+0)) -/** Module Serializer x (0~1) is ready to accept new data to be transmitted */ -#define I2S_STATUS_TRANSMIT_READY(x) (1u << ((x)+2)) -/** Module Serializer x (0~1) Receive Overrun */ -#define I2S_STATUS_RECEIVE_OVERRUN(x) (1u << ((x)+4)) -/** Module Serializer x (0~1) has received a new data */ -#define I2S_STATUS_RECEIVE_READY(x) (1u << ((x)+6)) -/** Module is busy on synchronization */ -#define I2S_STATUS_SYNC_BUSY (1u << 8) - -/** @} */ - -/** - * Master Clock (MCK) source selection - */ -enum i2s_master_clock_source { - /** Master Clock (MCK) is from general clock */ - I2S_MASTER_CLOCK_SOURCE_GCLK, - /** Master Clock (MCK) is from MCK input pin */ - I2S_MASTER_CLOCK_SOURCE_MCKPIN -}; - -/** - * Serial Clock (SCK) source selection - */ -enum i2s_serial_clock_source { - /** Serial Clock (SCK) is divided from Master Clock */ - I2S_SERIAL_CLOCK_SOURCE_MCKDIV, - /** Serial Clock (SCK) is input from SCK input pin */ - I2S_SERIAL_CLOCK_SOURCE_SCKPIN -}; - -/** - * Data delay from Frame Sync (FS) - */ -enum i2s_data_delay { - /** Left Justified (no delay) */ - I2S_DATA_DELAY_0, - /** I2S data delay (1-bit delay) */ - I2S_DATA_DELAY_1, - /** Left Justified (no delay) */ - I2S_DATA_DELAY_LEFT_JUSTIFIED = I2S_DATA_DELAY_0, - /** I2S data delay (1-bit delay) */ - I2S_DATA_DELAY_I2S = I2S_DATA_DELAY_1 -}; - -/** - * Frame Sync (FS) source - */ -enum i2s_frame_sync_source { - /** Frame Sync (FS) is divided from I2S Serial Clock */ - I2S_FRAME_SYNC_SOURCE_SCKDIV, - /** Frame Sync (FS) is input from FS input pin */ - I2S_FRAME_SYNC_SOURCE_FSPIN -}; - -/** - * Frame Sync (FS) output pulse width - */ -enum i2s_frame_sync_width { - /** Frame Sync (FS) Pulse is 1 Slot width */ - I2S_FRAME_SYNC_WIDTH_SLOT, - /** Frame Sync (FS) Pulse is half a Frame width */ - I2S_FRAME_SYNC_WIDTH_HALF_FRAME, - /** Frame Sync (FS) Pulse is 1 Bit width */ - I2S_FRAME_SYNC_WIDTH_BIT, - /** 1-bit wide Frame Sync (FS) per Data sample, only used when Data transfer - * is requested */ - I2S_FRAME_SYNC_WIDTH_BURST -}; - -/** - * Time Slot Size in number of I2S serial clocks (bits) - */ -enum i2s_slot_size { - /** 8-bit slot */ - I2S_SLOT_SIZE_8_BIT, - /** 16-bit slot */ - I2S_SLOT_SIZE_16_BIT, - /** 24-bit slot */ - I2S_SLOT_SIZE_24_BIT, - /** 32-bit slot */ - I2S_SLOT_SIZE_32_BIT -}; - -/** - * DMA channels usage for I2S - */ -enum i2s_dma_usage { - /** Single DMA channel for all I2S channels */ - I2S_DMA_USE_SINGLE_CHANNEL_FOR_ALL, - /** One DMA channel per data channel */ - I2S_DMA_USE_ONE_CHANNEL_PER_DATA_CHANNEL -}; - -/** - * I2S data format, to extend mono data to 2 channels - */ -enum i2s_data_format { - /** Normal mode, keep data to its right channel */ - I2S_DATA_FORMAT_STEREO, - /** Assume input is mono data for left channel, the data is duplicated to - * right channel */ - I2S_DATA_FORMAT_MONO -}; - -/** - * I2S data bit order - */ -enum i2s_bit_order { - /** Transfer Data Most Significant Bit first (Default for I2S protocol) */ - I2S_BIT_ORDER_MSB_FIRST, - /** Transfer Data Least Significant Bit first */ - I2S_BIT_ORDER_LSB_FIRST -}; - -/** - * I2S data bit padding - */ -enum i2s_bit_padding { - /** Padding with 0 */ - I2S_BIT_PADDING_0, - /** Padding with 1 */ - I2S_BIT_PADDING_1, - /** Padding with MSBit */ - I2S_BIT_PADDING_MSB, - /** Padding with LSBit */ - I2S_BIT_PADDING_LSB, -}; - -/** - * I2S data word adjust - */ -enum i2s_data_adjust { - /** Data is right adjusted in word */ - I2S_DATA_ADJUST_RIGHT, - /** Data is left adjusted in word */ - I2S_DATA_ADJUST_LEFT -}; - -/** - * I2S data word size - */ -enum i2s_data_size { - /** 32-bit */ - I2S_DATA_SIZE_32BIT, - /** 24-bit */ - I2S_DATA_SIZE_24BIT, - /** 20-bit */ - I2S_DATA_SIZE_20BIT, - /** 18-bit */ - I2S_DATA_SIZE_18BIT, - /** 16-bit */ - I2S_DATA_SIZE_16BIT, - /** 16-bit compact stereo */ - I2S_DATA_SIZE_16BIT_COMPACT, - /** 8-bit */ - I2S_DATA_SIZE_8BIT, - /** 8-bit compact stereo */ - I2S_DATA_SIZE_8BIT_COMPACT -}; - -/** - * I2S data slot adjust - */ -enum i2s_slot_adjust { - /** Data is right adjusted in slot */ - I2S_SLOT_ADJUST_RIGHT, - /** Data is left adjusted in slot */ - I2S_SLOT_ADJUST_LEFT -}; - -/** - * I2S data padding - */ -enum i2s_data_padding { - /** Padding 0 in case of under-run */ - I2S_DATA_PADDING_0, - /** Padding last data in case of under-run */ - I2S_DATA_PADDING_SAME_AS_LAST, - /** Padding last data in case of under-run - * (abbr. \c I2S_DATA_PADDING_SAME_AS_LAST) */ - I2S_DATA_PADDING_LAST = I2S_DATA_PADDING_SAME_AS_LAST, - /** Padding last data in case of under-run - * (abbr. \c I2S_DATA_PADDING_SAME_AS_LAST) */ - I2S_DATA_PADDING_SAME = I2S_DATA_PADDING_SAME_AS_LAST -}; - -/** - * I2S line default value when slot disabled - */ -enum i2s_line_default_state { - /** Output default value is 0 */ - I2S_LINE_DEFAULT_0, - /** Output default value is 1 */ - I2S_LINE_DEFAULT_1, - /** Output default value is high impedance */ - I2S_LINE_DEFAULT_HIGH_IMPEDANCE = 3, - /** Output default value is high impedance - * (abbr. \c I2S_LINE_DEFAULT_HIGH_IMPEDANCE) */ - I2S_LINE_DEFAULT_HIZ = I2S_LINE_DEFAULT_HIGH_IMPEDANCE -}; - -/** - * I2S Serializer mode - */ -enum i2s_serializer_mode { - /** Serializer is used to receive data */ - I2S_SERIALIZER_RECEIVE, - /** Serializer is used to transmit data */ - I2S_SERIALIZER_TRANSMIT, - /** Serializer is used to receive PDM data on each clock edge */ - I2S_SERIALIZER_PDM2 -}; - -/** - * I2S clock unit selection - */ -enum i2s_clock_unit { - /** Clock Unit channel 0 */ - I2S_CLOCK_UNIT_0, - /** Clock Unit channel 1 */ - I2S_CLOCK_UNIT_1, - /** Number of Clock Unit channels */ - I2S_CLOCK_UNIT_N -}; - -/** - * I2S Serializer selection - */ -enum i2s_serializer { - /** Serializer channel 0 */ - I2S_SERIALIZER_0, - /** Serializer channel 1 */ - I2S_SERIALIZER_1, - /** Number of Serializer channels */ - I2S_SERIALIZER_N -}; - - -/** - * Configure for I2S pin - */ -struct i2s_pin_config { - /** GPIO index to access the pin */ - uint8_t gpio; - /** Pin function MUX */ - uint8_t mux; - /** Enable this pin for I2S module */ - bool enable; -}; - -/** - * Configure for I2S clock (SCK) - */ -struct i2s_clock_config { - /** Divide generic clock to master clock output (1~32, 0,1 means no div) */ - uint8_t mck_out_div; - /** Divide generic clock to serial clock (1~32, 0,1 means no div) */ - uint8_t sck_div; - /** Clock source selection */ - enum gclk_generator gclk_src; - /** Master clock source selection: generated or input from pin */ - enum i2s_master_clock_source mck_src; - /** Serial clock source selection: generated or input from pin */ - enum i2s_serial_clock_source sck_src; - /** Invert master clock output */ - bool mck_out_invert; - /** Invert serial clock output */ - bool sck_out_invert; - /** Generate MCK clock output */ - bool mck_out_enable; -}; - -/** - * Configure fir I2S frame sync (FS) - */ -struct i2s_frame_sync_config { - /** Frame Sync (FS) generated or input from pin */ - enum i2s_frame_sync_source source; - /** Frame Sync (FS) width */ - enum i2s_frame_sync_width width; - /** Invert Frame Sync (FS) signal before use */ - bool invert_use; - /** Invert Frame Sync (FS) signal before output */ - bool invert_out; -}; - -/** - * Configure fir I2S frame - */ -struct i2s_frame_config { - /** Number of slots in a frame (1~8, 0,1 means minimum 1) */ - uint8_t number_slots; - /** Size of each slot in frame */ - enum i2s_slot_size slot_size; - /** Data delay from Frame Sync (FS) to first data bit */ - enum i2s_data_delay data_delay; - /** Frame sync (FS) */ - struct i2s_frame_sync_config frame_sync; -}; - -/** - * Configure for I2S clock unit - */ -struct i2s_clock_unit_config { - /** Configure clock generation */ - struct i2s_clock_config clock; - /** Configure frame generation */ - struct i2s_frame_config frame; - - /** Configure master clock pin */ - struct i2s_pin_config mck_pin; - /** Configure serial clock pin */ - struct i2s_pin_config sck_pin; - /** Configure frame sync pin */ - struct i2s_pin_config fs_pin; -}; - -/** - * Configure for I2S Serializer - */ -struct i2s_serializer_config { - /** Configure Serializer data pin */ - struct i2s_pin_config data_pin; - - /** Set to \c true to loop-back output to input pin for test */ - bool loop_back; - - /** Set to \c true to assumes mono input and duplicate it (left channel) to - * right channel */ - bool mono_mode; - - /** Disable data slot */ - bool disable_data_slot[8]; - - /** Set to \c true to transfer LSB first, \c false to transfer MSB first */ - bool transfer_lsb_first; - /** Data Word Formatting Adjust, - * set to \c true to adjust bits in word to left */ - bool data_adjust_left_in_word; - /** Data Slot Formatting Adjust, - * set to \c true to adjust words in slot to left */ - bool data_adjust_left_in_slot; - - /** Data Word Size */ - enum i2s_data_size data_size; - /** Data Formatting Bit Extension */ - enum i2s_bit_padding bit_padding; - /** Data padding when under-run */ - enum i2s_data_padding data_padding; - - /** DMA usage */ - enum i2s_dma_usage dma_usage; - - /** Clock unit selection */ - enum i2s_clock_unit clock_unit; - - /** Line default state where slot is disabled */ - enum i2s_line_default_state line_default_state; - - /** Serializer Mode */ - enum i2s_serializer_mode mode; -}; - -/** - * \brief I2S Serializer instance struct - */ -struct i2s_serializer_module { - -#if I2S_CALLBACK_MODE == true - /** Callbacks list for Serializer */ - i2s_serializer_callback_t callback[I2S_SERIALIZER_CALLBACK_N]; - - /** Job buffer */ - void *job_buffer; - /** Requested data words to read/write */ - uint32_t requested_words; - /** Transferred data words for read/write */ - uint32_t transferred_words; - - /** Callback mask for registered callbacks */ - uint8_t registered_callback_mask; - /** Callback mask for enabled callbacks */ - uint8_t enabled_callback_mask; - - /** Status of the ongoing or last transfer job */ - enum status_code job_status; -#endif - - /** Serializer mode */ - enum i2s_serializer_mode mode; - /** Serializer data word size */ - enum i2s_data_size data_size; -}; - -/** - * \brief I2S Software Module instance struct - */ -struct i2s_module { - /** Module HW register access base */ - I2s *hw; - - /** Module Serializer used */ - struct i2s_serializer_module serializer[2]; -}; - -/** - * \brief Determines if the hardware module(s) are currently synchronizing to the bus. - * - * Checks to see if the underlying hardware peripheral module(s) are currently - * synchronizing across multiple clock domains to the hardware bus, This - * function can be used to delay further operations on a module until such time - * that it is ready, to prevent blocking delays for synchronization in the - * user application. - * - * \param[in] module_inst Pointer to the software module instance struct - * - * \return Synchronization status of the underlying hardware module(s). - * - * \retval false If the module has completed synchronization - * \retval true If the module synchronization is ongoing - */ -static inline bool i2s_is_syncing( - const struct i2s_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - return (module_inst->hw->SYNCBUSY.reg > 0); -} - -/** - * \name Driver Initialization - * @{ - */ - -enum status_code i2s_init( - struct i2s_module *const module_inst, - I2s *hw); - -/** @} */ - -/** - * \name Enable/Disable/Reset - * @{ - */ - -/** - * \brief Enable the I2S module. - * - * Enables a I2S module that has been previously initialized. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void i2s_enable(const struct i2s_module *const module_inst) -{ - Assert(module_inst); - Assert(module_inst->hw); - - while (module_inst->hw->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE) { - /* Sync wait */ - } - module_inst->hw->CTRLA.reg |= I2S_SYNCBUSY_ENABLE; -} - -/** - * \brief Disables the I2S module. - * - * Disables a I2S module. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void i2s_disable(const struct i2s_module *const module_inst) -{ - Assert(module_inst); - Assert(module_inst->hw); - - while (module_inst->hw->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE) { - /* Sync wait */ - } - module_inst->hw->CTRLA.reg &= ~I2S_SYNCBUSY_ENABLE; -} - -/** - * \brief Resets the I2S module. - * - * Resets the I2S module, restoring all hardware module registers to their - * default values and disabling the module. The I2S module will not be - * accessible while the reset is being performed. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void i2s_reset(const struct i2s_module *const module_inst) -{ - Assert(module_inst); - Assert(module_inst->hw); - - /* Disable the module if it is running */ - if (module_inst->hw->CTRLA.reg & I2S_CTRLA_ENABLE) { - i2s_disable(module_inst); - while (i2s_is_syncing(module_inst)) { - /* Sync wait */ - } - } - /* Reset the HW module */ - module_inst->hw->CTRLA.reg = I2S_CTRLA_SWRST; -} - -/** @} */ - -/** - * \name Clock Unit Initialization and Configuration - * @{ - */ - -/** - * \brief Initializes config with predefined default values for I2S clock unit. - * - * This function will initialize a given I2S Clock Unit configuration structure - * to a set of known default values. This function should be called on any new - * instance of the configuration structures before being modified by the user - * application. - * - * The default configuration is as follow: - * - The clock unit does not generate output clocks (MCK, SCK and FS) - * - The pins (MCK, SCK and FS) and Mux configurations are not set - * - * \param[out] config Pointer to a I2S module clock unit configuration struct - * to set - */ -static inline void i2s_clock_unit_get_config_defaults( - struct i2s_clock_unit_config *const config) -{ - Assert(config); - - config->clock.mck_out_enable = false; - config->clock.gclk_src = GCLK_GENERATOR_0; - - config->clock.mck_src = I2S_MASTER_CLOCK_SOURCE_GCLK; - config->clock.mck_out_div = 1; - config->clock.mck_out_invert = false; - - config->clock.sck_src = I2S_SERIAL_CLOCK_SOURCE_MCKDIV; - config->clock.sck_div = 1; - config->clock.sck_out_invert = false; - - config->frame.number_slots = 1; - config->frame.slot_size = I2S_SLOT_SIZE_32_BIT; - config->frame.data_delay = I2S_DATA_DELAY_I2S; - - config->frame.frame_sync.source = I2S_FRAME_SYNC_SOURCE_SCKDIV; - config->frame.frame_sync.width = I2S_FRAME_SYNC_WIDTH_HALF_FRAME; - config->frame.frame_sync.invert_use = false; - config->frame.frame_sync.invert_out = false; - - config->mck_pin.enable = false; - config->mck_pin.mux = 0; - config->mck_pin.gpio = 0; - - config->sck_pin.enable = false; - config->sck_pin.mux = 0; - config->sck_pin.gpio = 0; - - config->fs_pin.enable = false; - config->fs_pin.mux = 0; - config->fs_pin.gpio = 0; -} - -enum status_code i2s_clock_unit_set_config( - struct i2s_module *const module_inst, - const enum i2s_clock_unit clock_unit, - const struct i2s_clock_unit_config *config); - -/** @} */ - - -/** - * \name Clock Unit Enable/Disable - * @{ - */ - -/** - * \brief Enable the Specified Clock Unit of I2S module. - * - * Enables a Clock Unit in I2S module that has been previously initialized. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] clock_unit I2S Clock Unit to enable - */ -static inline void i2s_clock_unit_enable( - const struct i2s_module *const module_inst, - const enum i2s_clock_unit clock_unit) -{ - uint32_t cken_bit; - - Assert(module_inst); - Assert(module_inst->hw); - - cken_bit = I2S_CTRLA_CKEN0 << clock_unit; - - while (module_inst->hw->SYNCBUSY.reg & cken_bit) { - /* Sync wait */ - } - module_inst->hw->CTRLA.reg |= cken_bit; -} - -/** - * \brief Disable the Specified Clock Unit of I2S module. - * - * Disables a Clock Unit in I2S module that has been previously initialized. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] clock_unit I2S Clock Unit to disable - */ -static inline void i2s_clock_unit_disable( - const struct i2s_module *const module_inst, - const enum i2s_clock_unit clock_unit) -{ - uint32_t cken_bit; - - Assert(module_inst); - Assert(module_inst->hw); - - cken_bit = I2S_CTRLA_CKEN0 << clock_unit; - - while (module_inst->hw->SYNCBUSY.reg & cken_bit) { - /* Sync wait */ - } - module_inst->hw->CTRLA.reg &= ~cken_bit; -} - -/** @} */ - - -/** - * \name Serializer Initialization and Configuration - * @{ - */ - -/** - * \brief Initializes config with predefined default values for I2S Serializer. - * - * This function will initialize a given I2S Clock Unit configuration structure - * to a set of known default values. This function should be called on any new - * instance of the configuration structures before being modified by the user - * application. - * - * The default configuration is as follow: - * - Output data does not internally loopback to input line - * - Does not extend mono data (left channel) to right channel - * - None of the data slot is disabled - * - MSB of I2S data is transferred first - * - In data word data is adjusted right - * - In slot data word is adjusted left - * - The data size is 16-bit width - * - I2S will padd 0 to not defined bits - * - I2S will padd 0 to not defined words - * - I2S will use single DMA channel for all data channels - * - I2S will use clock unit 0 to serve as clock - * - The default data line state is 0, when there is no data - * - I2S will transmit data to output line - * - The data pin and Mux configuration are not set - * - * \param[out] config Pointer to a I2S module Serializer configuration struct - * to set - */ -static inline void i2s_serializer_get_config_defaults( - struct i2s_serializer_config *const config) -{ - config->loop_back = false; - - config->mono_mode = false; - - config->disable_data_slot[0] = false; - config->disable_data_slot[1] = false; - config->disable_data_slot[2] = false; - config->disable_data_slot[3] = false; - config->disable_data_slot[4] = false; - config->disable_data_slot[5] = false; - config->disable_data_slot[6] = false; - config->disable_data_slot[7] = false; - - config->transfer_lsb_first = false; - config->data_adjust_left_in_word = false; - config->data_adjust_left_in_slot = true; - - config->data_size = I2S_DATA_SIZE_16BIT; - - config->bit_padding = I2S_BIT_PADDING_0; - config->data_padding = I2S_DATA_PADDING_0; - - config->dma_usage = I2S_DMA_USE_SINGLE_CHANNEL_FOR_ALL; - - config->clock_unit = I2S_CLOCK_UNIT_0; - - config->line_default_state = I2S_LINE_DEFAULT_0; - - config->mode = I2S_SERIALIZER_TRANSMIT; - - config->data_pin.enable = false; - config->data_pin.gpio = 0; - config->data_pin.mux = 0; -} - -enum status_code i2s_serializer_set_config( - struct i2s_module *const module_inst, - const enum i2s_serializer serializer, - const struct i2s_serializer_config *config); -/** @} */ - -/** - * \name Serializer Enable/Disable - * @{ - */ - -/** - * \brief Enable the Specified Serializer of I2S module. - * - * Enables a Serializer in I2S module that has been previously initialized. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer I2S Serializer to enable - */ -static inline void i2s_serializer_enable( - const struct i2s_module *const module_inst, - const enum i2s_serializer serializer) -{ - uint32_t seren_bit; - - Assert(module_inst); - Assert(module_inst->hw); - - seren_bit = I2S_CTRLA_SEREN0 << serializer; - - while (module_inst->hw->SYNCBUSY.reg & seren_bit) { - /* Sync wait */ - } - module_inst->hw->CTRLA.reg |= seren_bit; -} - -/** - * \brief Disable the Specified Serializer of I2S module. - * - * Disables a Serializer in I2S module that has been previously initialized. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer I2S Serializer to disable - */ -static inline void i2s_serializer_disable( - const struct i2s_module *const module_inst, - const enum i2s_serializer serializer) -{ - uint32_t seren_bit; - - Assert(module_inst); - Assert(module_inst->hw); - - seren_bit = I2S_CTRLA_SEREN0 << serializer; - - while (module_inst->hw->SYNCBUSY.reg & seren_bit) { - /* Sync wait */ - } - module_inst->hw->CTRLA.reg &= ~seren_bit; -} -/** @} */ - -/** - * \name Status Management - * @{ - */ - -uint32_t i2s_get_status( - const struct i2s_module *const module_inst); - -void i2s_clear_status( - const struct i2s_module *const module_inst, - uint32_t status); - - -enum status_code i2s_enable_status_interrupt( - struct i2s_module *const module_inst, - uint32_t status); - -void i2s_disable_status_interrupt( - struct i2s_module *const module_inst, - uint32_t status); - -/** @}*/ - -/** - * \name Data read/write - * @{ - */ - -/** - * \brief Write a data word to the specified Serializer of I2S module - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer The Serializer to write to - * \param[in] data The data to write - * - */ -static inline void i2s_serializer_write_wait( - const struct i2s_module *const module_inst, - enum i2s_serializer serializer, - uint32_t data) -{ - uint32_t sync_bit, ready_bit; - - Assert(module_inst); - Assert(module_inst->hw); - - ready_bit = I2S_INTFLAG_TXRDY0 << serializer; - while (!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait until ready to transmit */ - } - sync_bit = I2S_SYNCBUSY_DATA0 << serializer; - while (module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait sync */ - } - /* Write data */ - module_inst->hw->DATA[serializer].reg = data; - module_inst->hw->INTFLAG.reg = ready_bit; -} - -/** - * \brief Read a data word from the specified Serializer of I2S module - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer The Serializer to read - */ -static inline uint32_t i2s_serializer_read_wait( - const struct i2s_module *const module_inst, - enum i2s_serializer serializer) -{ - uint32_t sync_bit, ready_bit; - uint32_t data; - - Assert(module_inst); - Assert(module_inst->hw); - - ready_bit = I2S_INTFLAG_RXRDY0 << serializer; - while (!(module_inst->hw->INTFLAG.reg & ready_bit)) { - /* Wait until ready to transmit */ - } - sync_bit = I2S_SYNCBUSY_DATA0 << serializer; - while (module_inst->hw->SYNCBUSY.reg & sync_bit) { - /* Wait sync */ - } - /* Read data */ - data = module_inst->hw->DATA[serializer].reg; - module_inst->hw->INTFLAG.reg = ready_bit; - return data; -} - - -/** - * \brief Write buffer to the specified Serializer of I2S module - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer The Serializer to write to - * \param[in] buffer The data buffer to write - * \param[in] size Number of data words to write - * - * \return Status of the initialization procedure. - * - * \retval STATUS_OK The data was sent successfully - * \retval STATUS_INVALID_ARG An invalid buffer pointer was supplied - */ -enum status_code i2s_serializer_write_buffer_wait( - const struct i2s_module *const module_inst, - enum i2s_serializer serializer, - void *buffer, uint32_t size); - -/** - * \brief Read from the specified Serializer of I2S module to a buffer - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] serializer The Serializer to write to - * \param[in] buffer The buffer to fill read data - * \param[in] size Number of data words to read - * - * \return Status of the initialization procedure. - * - * \retval STATUS_OK The data was sent successfully - * \retval STATUS_INVALID_ARG An invalid buffer pointer was supplied - */ -enum status_code i2s_serializer_read_buffer_wait( - const struct i2s_module *const module_inst, - enum i2s_serializer serializer, - void *buffer, uint32_t size); - -/** @} */ - -#ifdef __cplusplus -} -#endif - -/** @} */ - - -/** - * \page asfdoc_sam0_i2s_extra Extra Information for I2S Driver - * - * \section asfdoc_sam0_i2s_extra_acronyms Acronyms - * Below is a table listing the acronyms used in this module, along with their - * intended meanings. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
AcronymDescription
I2S, IISInter-IC Sound Controller
MCKMaster Clock
SCKSerial Clock
FSFrame Sync
SDSerial Data
ADCAnalog-to-Digital Converter
DACDigital-to-Analog Converter
TDMTime Division Multiplexed
PDMPulse Density Modulation
LSBLeast Significant Bit
MSBMost Significant Bit
DSPDigital Signal Processor
- * - * - * \section asfdoc_sam0_i2s_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - \ref asfdoc_sam0_system_pinmux_group "System Pin Multiplexer Driver" - * - * - * \section asfdoc_sam0_i2s_extra_errata Errata - * There are no errata related to this driver. - * - * - * \section asfdoc_sam0_i2s_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * - * - * - *
Changelog
Initial Release
- */ - -/** - * \page asfdoc_sam0_i2s_exqsg Examples for I2S Driver - * - * This is a list of the available Quick Start guides (QSGs) and example - * applications for \ref asfdoc_sam0_i2s_group. QSGs are simple examples with - * step-by-step instructions to configure and use this driver in a selection of - * use cases. Note that QSGs can be compiled as a standalone application or be - * added to the user application. - * - * - \subpage asfdoc_sam0_i2s_basic_use_case - * \if I2S_CALLBACK_MODE - * - \subpage asfdoc_sam0_i2s_callback_use_case - * \endif - * - \subpage asfdoc_sam0_i2s_dma_use_case - * - * \page asfdoc_sam0_i2s_document_revision_history Document Revision History - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Doc. Rev. - * Date - * Comments - *
B04/2015Added support for SAMDA1.
A01/2014Initial release
- */ - -#endif /* #ifndef I2S_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt.h deleted file mode 100644 index fa4878e..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt.h +++ /dev/null @@ -1,117 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ -#ifndef UTILS_INTERRUPT_H -#define UTILS_INTERRUPT_H - -//#include - -#include "interrupt/interrupt_sam_nvic.h" - -/** - * \defgroup interrupt_group Global interrupt management - * - * This is a driver for global enabling and disabling of interrupts. - * - * @{ - */ - -#if defined(__DOXYGEN__) -/** - * \def CONFIG_INTERRUPT_FORCE_INTC - * \brief Force usage of the ASF INTC driver - * - * Predefine this symbol when preprocessing to force the use of the ASF INTC driver. - * This is useful to ensure compatibility across compilers and shall be used only when required - * by the application needs. - */ -# define CONFIG_INTERRUPT_FORCE_INTC -#endif - -//! \name Global interrupt flags -//@{ -/** - * \typedef irqflags_t - * \brief Type used for holding state of interrupt flag - */ - -/** - * \def cpu_irq_enable - * \brief Enable interrupts globally - */ - -/** - * \def cpu_irq_disable - * \brief Disable interrupts globally - */ - -/** - * \fn irqflags_t cpu_irq_save(void) - * \brief Get and clear the global interrupt flags - * - * Use in conjunction with \ref cpu_irq_restore. - * - * \return Current state of interrupt flags. - * - * \note This function leaves interrupts disabled. - */ - -/** - * \fn void cpu_irq_restore(irqflags_t flags) - * \brief Restore global interrupt flags - * - * Use in conjunction with \ref cpu_irq_save. - * - * \param flags State to set interrupt flag to. - */ - -/** - * \fn bool cpu_irq_is_enabled_flags(irqflags_t flags) - * \brief Check if interrupts are globally enabled in supplied flags - * - * \param flags Currents state of interrupt flags. - * - * \return True if interrupts are enabled. - */ - -/** - * \def cpu_irq_is_enabled - * \brief Check if interrupts are globally enabled - * - * \return True if interrupts are enabled. - */ -//@} - -//! @} - -/** - * \ingroup interrupt_group - * \defgroup interrupt_deprecated_group Deprecated interrupt definitions - */ - -#endif /* UTILS_INTERRUPT_H */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c deleted file mode 100644 index d813485..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.c +++ /dev/null @@ -1,69 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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 "interrupt_sam_nvic.h" - -#if !defined(__DOXYGEN__) -/* Deprecated - global flag to determine the global interrupt state. Required by - * QTouch library, however new applications should use cpu_irq_is_enabled() - * which probes the true global interrupt state from the CPU special registers. - */ -volatile bool g_interrupt_enabled = true; -#endif - -void cpu_irq_enter_critical(void) -{ - if (cpu_irq_critical_section_counter == 0) { - if (cpu_irq_is_enabled()) { - cpu_irq_disable(); - cpu_irq_prev_interrupt_state = true; - } else { - /* Make sure the to save the prev state as false */ - cpu_irq_prev_interrupt_state = false; - } - - } - - cpu_irq_critical_section_counter++; -} - -void cpu_irq_leave_critical(void) -{ - /* Check if the user is trying to leave a critical section when not in a critical section */ - Assert(cpu_irq_critical_section_counter > 0); - - cpu_irq_critical_section_counter--; - - /* Only enable global interrupts when the counter reaches 0 and the state of the global interrupt flag - was enabled when entering critical state */ - if ((cpu_irq_critical_section_counter == 0) && (cpu_irq_prev_interrupt_state)) { - cpu_irq_enable(); - } -} - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h deleted file mode 100644 index 9b5645b..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt/interrupt_sam_nvic.h +++ /dev/null @@ -1,172 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef UTILS_INTERRUPT_INTERRUPT_H -#define UTILS_INTERRUPT_INTERRUPT_H - -#include -//#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \weakgroup interrupt_group - * - * @{ - */ - -/** - * \name Interrupt Service Routine definition - * - * @{ - */ - -/** - * \brief Define service routine - * - * \note For NVIC devices the interrupt service routines are predefined to - * add to vector table in binary generation, so there is no service - * register at run time. The routine collections are in exceptions.h. - * - * Usage: - * \code - ISR(foo_irq_handler) - { - // Function definition - ... - } -\endcode - * - * \param func Name for the function. - */ -# define ISR(func) \ - void func (void) - -/** - * \brief Initialize interrupt vectors - * - * For NVIC the interrupt vectors are put in vector table. So nothing - * to do to initialize them, except defined the vector function with - * right name. - * - * This must be called prior to \ref irq_register_handler. - */ -# define irq_initialize_vectors() \ - do { \ - } while(0) - -/** - * \brief Register handler for interrupt - * - * For NVIC the interrupt vectors are put in vector table. So nothing - * to do to register them, except defined the vector function with - * right name. - * - * Usage: - * \code - irq_initialize_vectors(); - irq_register_handler(foo_irq_handler); -\endcode - * - * \note The function \a func must be defined with the \ref ISR macro. - * \note The functions prototypes can be found in the device exception header - * files (exceptions.h). - */ -# define irq_register_handler(int_num, int_prio) \ - NVIC_ClearPendingIRQ( (IRQn_Type)int_num); \ - NVIC_SetPriority( (IRQn_Type)int_num, int_prio); \ - NVIC_EnableIRQ( (IRQn_Type)int_num); \ - -//@} - -# define cpu_irq_enable() \ - do { \ - g_interrupt_enabled = true; \ - __DMB(); \ - __enable_irq(); \ - } while (0) -# define cpu_irq_disable() \ - do { \ - __disable_irq(); \ - __DMB(); \ - g_interrupt_enabled = false; \ - } while (0) - -typedef uint32_t irqflags_t; - -#if !defined(__DOXYGEN__) -extern volatile bool g_interrupt_enabled; -#endif - -#define cpu_irq_is_enabled() (__get_PRIMASK() == 0) - -static volatile uint32_t cpu_irq_critical_section_counter; -static volatile bool cpu_irq_prev_interrupt_state; - -static inline irqflags_t cpu_irq_save(void) -{ - irqflags_t flags = cpu_irq_is_enabled(); - cpu_irq_disable(); - return flags; -} - -static inline bool cpu_irq_is_enabled_flags(irqflags_t flags) -{ - return (flags); -} - -static inline void cpu_irq_restore(irqflags_t flags) -{ - if (cpu_irq_is_enabled_flags(flags)) - cpu_irq_enable(); -} - -void cpu_irq_enter_critical(void); -void cpu_irq_leave_critical(void); - -/** - * \weakgroup interrupt_deprecated_group - * @{ - */ - -#define Enable_global_interrupt() cpu_irq_enable() -#define Disable_global_interrupt() cpu_irq_disable() -#define Is_global_interrupt_enabled() cpu_irq_is_enabled() - -//@} - -//@} - -#ifdef __cplusplus -} -#endif - -#endif /* UTILS_INTERRUPT_INTERRUPT_H */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c deleted file mode 100644 index 26dcc91..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.c +++ /dev/null @@ -1,86 +0,0 @@ -/** - * \file - * - * \brief Global interrupt management for SAM D20, SAM3 and SAM4 (NVIC based) - * - * Copyright (c) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#include "interrupt_sam_nvic.h" - -#if !defined(__DOXYGEN__) -/* Deprecated - global flag to determine the global interrupt state. Required by - * QTouch library, however new applications should use cpu_irq_is_enabled() - * which probes the true global interrupt state from the CPU special registers. - */ -volatile bool g_interrupt_enabled = true; -#endif - -void cpu_irq_enter_critical(void) -{ - if (cpu_irq_critical_section_counter == 0) { - if (cpu_irq_is_enabled()) { - cpu_irq_disable(); - cpu_irq_prev_interrupt_state = true; - } else { - /* Make sure the to save the prev state as false */ - cpu_irq_prev_interrupt_state = false; - } - - } - - cpu_irq_critical_section_counter++; -} - -void cpu_irq_leave_critical(void) -{ - /* Check if the user is trying to leave a critical section when not in a critical section */ - Assert(cpu_irq_critical_section_counter > 0); - - cpu_irq_critical_section_counter--; - - /* Only enable global interrupts when the counter reaches 0 and the state of the global interrupt flag - was enabled when entering critical state */ - if ((cpu_irq_critical_section_counter == 0) && (cpu_irq_prev_interrupt_state)) { - cpu_irq_enable(); - } -} - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h deleted file mode 100644 index f996e92..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/interrupt_sam_nvic.h +++ /dev/null @@ -1,189 +0,0 @@ -/** - * \file - * - * \brief Global interrupt management for SAM D20, SAM3 and SAM4 (NVIC based) - * - * Copyright (c) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#ifndef UTILS_INTERRUPT_INTERRUPT_H -#define UTILS_INTERRUPT_INTERRUPT_H - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \weakgroup interrupt_group - * - * @{ - */ - -/** - * \name Interrupt Service Routine definition - * - * @{ - */ - -/** - * \brief Define service routine - * - * \note For NVIC devices the interrupt service routines are predefined to - * add to vector table in binary generation, so there is no service - * register at run time. The routine collections are in exceptions.h. - * - * Usage: - * \code - ISR(foo_irq_handler) - { - // Function definition - ... - } -\endcode - * - * \param func Name for the function. - */ -# define ISR(func) \ - void func (void) - -/** - * \brief Initialize interrupt vectors - * - * For NVIC the interrupt vectors are put in vector table. So nothing - * to do to initialize them, except defined the vector function with - * right name. - * - * This must be called prior to \ref irq_register_handler. - */ -# define irq_initialize_vectors() \ - do { \ - } while(0) - -/** - * \brief Register handler for interrupt - * - * For NVIC the interrupt vectors are put in vector table. So nothing - * to do to register them, except defined the vector function with - * right name. - * - * Usage: - * \code - irq_initialize_vectors(); - irq_register_handler(foo_irq_handler); -\endcode - * - * \note The function \a func must be defined with the \ref ISR macro. - * \note The functions prototypes can be found in the device exception header - * files (exceptions.h). - */ -# define irq_register_handler(int_num, int_prio) \ - NVIC_ClearPendingIRQ( (IRQn_Type)int_num); \ - NVIC_SetPriority( (IRQn_Type)int_num, int_prio); \ - NVIC_EnableIRQ( (IRQn_Type)int_num); \ - -//@} - -# define cpu_irq_enable() \ - do { \ - g_interrupt_enabled = true; \ - __DMB(); \ - __enable_irq(); \ - } while (0) -# define cpu_irq_disable() \ - do { \ - __disable_irq(); \ - __DMB(); \ - g_interrupt_enabled = false; \ - } while (0) - -typedef uint32_t irqflags_t; - -#if !defined(__DOXYGEN__) -extern volatile bool g_interrupt_enabled; -#endif - -#define cpu_irq_is_enabled() (__get_PRIMASK() == 0) - -static volatile uint32_t cpu_irq_critical_section_counter; -static volatile bool cpu_irq_prev_interrupt_state; - -static inline irqflags_t cpu_irq_save(void) -{ - irqflags_t flags = cpu_irq_is_enabled(); - cpu_irq_disable(); - return flags; -} - -static inline bool cpu_irq_is_enabled_flags(irqflags_t flags) -{ - return (flags); -} - -static inline void cpu_irq_restore(irqflags_t flags) -{ - if (cpu_irq_is_enabled_flags(flags)) - cpu_irq_enable(); -} - -void cpu_irq_enter_critical(void); -void cpu_irq_leave_critical(void); - -/** - * \weakgroup interrupt_deprecated_group - * @{ - */ - -#define Enable_global_interrupt() cpu_irq_enable() -#define Disable_global_interrupt() cpu_irq_disable() -#define Is_global_interrupt_enabled() cpu_irq_is_enabled() - -//@} - -//@} - -#ifdef __cplusplus -} -#endif - -#endif /* UTILS_INTERRUPT_INTERRUPT_H */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/library.properties b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/library.properties deleted file mode 100644 index e2af108..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=Adafruit Arduino Zero ASF Core Library -version=1.0.0 -author=Adafruit -maintainer=Adafruit -sentence=ASF (Atmel Software Framework) files used by Adafruit's Arduino Zero/SAMD21 libraries. -paragraph=ASF (Atmel Software Framework) files used by Adafruit's Arduino Zero/SAMD21 libraries. This is a dependency of other libraries like Adafruit_ZeroTimer. -category=Other -url=https://github.com/adafruit/Adafruit_ASFcore -architectures=* diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/parts.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/parts.h deleted file mode 100644 index 40be022..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/parts.h +++ /dev/null @@ -1,1601 +0,0 @@ -/** - * \file - * - * \brief Atmel part identification macros - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#ifndef ATMEL_PARTS_H -#define ATMEL_PARTS_H - -/** - * \defgroup part_macros_group Atmel part identification macros - * - * This collection of macros identify which series and families that the various - * Atmel parts belong to. These can be used to select part-dependent sections of - * code at compile time. - * - * @{ - */ - -/** - * \name Convenience macros for part checking - * @{ - */ -/* ! Check GCC and IAR part definition for 8-bit AVR */ -#define AVR8_PART_IS_DEFINED(part) \ - (defined(__ ## part ## __) || defined(__AVR_ ## part ## __)) - -/* ! Check GCC and IAR part definition for 32-bit AVR */ -#define AVR32_PART_IS_DEFINED(part) \ - (defined(__AT32 ## part ## __) || defined(__AVR32_ ## part ## __)) - -/* ! Check GCC and IAR part definition for SAM */ -#define SAM_PART_IS_DEFINED(part) (defined(__ ## part ## __)) -/** @} */ - -/** - * \defgroup uc3_part_macros_group AVR UC3 parts - * @{ - */ - -/** - * \name AVR UC3 A series - * @{ - */ -#define UC3A0 ( \ - AVR32_PART_IS_DEFINED(UC3A0128) || \ - AVR32_PART_IS_DEFINED(UC3A0256) || \ - AVR32_PART_IS_DEFINED(UC3A0512) \ - ) - -#define UC3A1 ( \ - AVR32_PART_IS_DEFINED(UC3A1128) || \ - AVR32_PART_IS_DEFINED(UC3A1256) || \ - AVR32_PART_IS_DEFINED(UC3A1512) \ - ) - -#define UC3A3 ( \ - AVR32_PART_IS_DEFINED(UC3A364) || \ - AVR32_PART_IS_DEFINED(UC3A364S) || \ - AVR32_PART_IS_DEFINED(UC3A3128) || \ - AVR32_PART_IS_DEFINED(UC3A3128S) || \ - AVR32_PART_IS_DEFINED(UC3A3256) || \ - AVR32_PART_IS_DEFINED(UC3A3256S) \ - ) - -#define UC3A4 ( \ - AVR32_PART_IS_DEFINED(UC3A464) || \ - AVR32_PART_IS_DEFINED(UC3A464S) || \ - AVR32_PART_IS_DEFINED(UC3A4128) || \ - AVR32_PART_IS_DEFINED(UC3A4128S) || \ - AVR32_PART_IS_DEFINED(UC3A4256) || \ - AVR32_PART_IS_DEFINED(UC3A4256S) \ - ) -/** @} */ - -/** - * \name AVR UC3 B series - * @{ - */ -#define UC3B0 ( \ - AVR32_PART_IS_DEFINED(UC3B064) || \ - AVR32_PART_IS_DEFINED(UC3B0128) || \ - AVR32_PART_IS_DEFINED(UC3B0256) || \ - AVR32_PART_IS_DEFINED(UC3B0512) \ - ) - -#define UC3B1 ( \ - AVR32_PART_IS_DEFINED(UC3B164) || \ - AVR32_PART_IS_DEFINED(UC3B1128) || \ - AVR32_PART_IS_DEFINED(UC3B1256) || \ - AVR32_PART_IS_DEFINED(UC3B1512) \ - ) -/** @} */ - -/** - * \name AVR UC3 C series - * @{ - */ -#define UC3C0 ( \ - AVR32_PART_IS_DEFINED(UC3C064C) || \ - AVR32_PART_IS_DEFINED(UC3C0128C) || \ - AVR32_PART_IS_DEFINED(UC3C0256C) || \ - AVR32_PART_IS_DEFINED(UC3C0512C) \ - ) - -#define UC3C1 ( \ - AVR32_PART_IS_DEFINED(UC3C164C) || \ - AVR32_PART_IS_DEFINED(UC3C1128C) || \ - AVR32_PART_IS_DEFINED(UC3C1256C) || \ - AVR32_PART_IS_DEFINED(UC3C1512C) \ - ) - -#define UC3C2 ( \ - AVR32_PART_IS_DEFINED(UC3C264C) || \ - AVR32_PART_IS_DEFINED(UC3C2128C) || \ - AVR32_PART_IS_DEFINED(UC3C2256C) || \ - AVR32_PART_IS_DEFINED(UC3C2512C) \ - ) -/** @} */ - -/** - * \name AVR UC3 D series - * @{ - */ -#define UC3D3 ( \ - AVR32_PART_IS_DEFINED(UC64D3) || \ - AVR32_PART_IS_DEFINED(UC128D3) \ - ) - -#define UC3D4 ( \ - AVR32_PART_IS_DEFINED(UC64D4) || \ - AVR32_PART_IS_DEFINED(UC128D4) \ - ) -/** @} */ - -/** - * \name AVR UC3 L series - * @{ - */ -#define UC3L0 ( \ - AVR32_PART_IS_DEFINED(UC3L016) || \ - AVR32_PART_IS_DEFINED(UC3L032) || \ - AVR32_PART_IS_DEFINED(UC3L064) \ - ) - -#define UC3L0128 ( \ - AVR32_PART_IS_DEFINED(UC3L0128) \ - ) - -#define UC3L0256 ( \ - AVR32_PART_IS_DEFINED(UC3L0256) \ - ) - -#define UC3L3 ( \ - AVR32_PART_IS_DEFINED(UC64L3U) || \ - AVR32_PART_IS_DEFINED(UC128L3U) || \ - AVR32_PART_IS_DEFINED(UC256L3U) \ - ) - -#define UC3L4 ( \ - AVR32_PART_IS_DEFINED(UC64L4U) || \ - AVR32_PART_IS_DEFINED(UC128L4U) || \ - AVR32_PART_IS_DEFINED(UC256L4U) \ - ) - -#define UC3L3_L4 (UC3L3 || UC3L4) -/** @} */ - -/** - * \name AVR UC3 families - * @{ - */ -/** AVR UC3 A family */ -#define UC3A (UC3A0 || UC3A1 || UC3A3 || UC3A4) - -/** AVR UC3 B family */ -#define UC3B (UC3B0 || UC3B1) - -/** AVR UC3 C family */ -#define UC3C (UC3C0 || UC3C1 || UC3C2) - -/** AVR UC3 D family */ -#define UC3D (UC3D3 || UC3D4) - -/** AVR UC3 L family */ -#define UC3L (UC3L0 || UC3L0128 || UC3L0256 || UC3L3_L4) -/** @} */ - -/** AVR UC3 product line */ -#define UC3 (UC3A || UC3B || UC3C || UC3D || UC3L) - -/** @} */ - -/** - * \defgroup xmega_part_macros_group AVR XMEGA parts - * @{ - */ - -/** - * \name AVR XMEGA A series - * @{ - */ -#define XMEGA_A1 ( \ - AVR8_PART_IS_DEFINED(ATxmega64A1) || \ - AVR8_PART_IS_DEFINED(ATxmega128A1) \ - ) - -#define XMEGA_A3 ( \ - AVR8_PART_IS_DEFINED(ATxmega64A3) || \ - AVR8_PART_IS_DEFINED(ATxmega128A3) || \ - AVR8_PART_IS_DEFINED(ATxmega192A3) || \ - AVR8_PART_IS_DEFINED(ATxmega256A3) \ - ) - -#define XMEGA_A3B ( \ - AVR8_PART_IS_DEFINED(ATxmega256A3B) \ - ) - -#define XMEGA_A4 ( \ - AVR8_PART_IS_DEFINED(ATxmega16A4) || \ - AVR8_PART_IS_DEFINED(ATxmega32A4) \ - ) -/** @} */ - -/** - * \name AVR XMEGA AU series - * @{ - */ -#define XMEGA_A1U ( \ - AVR8_PART_IS_DEFINED(ATxmega64A1U) || \ - AVR8_PART_IS_DEFINED(ATxmega128A1U) \ - ) - -#define XMEGA_A3U ( \ - AVR8_PART_IS_DEFINED(ATxmega64A3U) || \ - AVR8_PART_IS_DEFINED(ATxmega128A3U) || \ - AVR8_PART_IS_DEFINED(ATxmega192A3U) || \ - AVR8_PART_IS_DEFINED(ATxmega256A3U) \ - ) - -#define XMEGA_A3BU ( \ - AVR8_PART_IS_DEFINED(ATxmega256A3BU) \ - ) - -#define XMEGA_A4U ( \ - AVR8_PART_IS_DEFINED(ATxmega16A4U) || \ - AVR8_PART_IS_DEFINED(ATxmega32A4U) || \ - AVR8_PART_IS_DEFINED(ATxmega64A4U) || \ - AVR8_PART_IS_DEFINED(ATxmega128A4U) \ - ) -/** @} */ - -/** - * \name AVR XMEGA B series - * @{ - */ -#define XMEGA_B1 ( \ - AVR8_PART_IS_DEFINED(ATxmega64B1) || \ - AVR8_PART_IS_DEFINED(ATxmega128B1) \ - ) - -#define XMEGA_B3 ( \ - AVR8_PART_IS_DEFINED(ATxmega64B3) || \ - AVR8_PART_IS_DEFINED(ATxmega128B3) \ - ) -/** @} */ - -/** - * \name AVR XMEGA C series - * @{ - */ -#define XMEGA_C3 ( \ - AVR8_PART_IS_DEFINED(ATxmega384C3) || \ - AVR8_PART_IS_DEFINED(ATxmega256C3) || \ - AVR8_PART_IS_DEFINED(ATxmega192C3) || \ - AVR8_PART_IS_DEFINED(ATxmega128C3) || \ - AVR8_PART_IS_DEFINED(ATxmega64C3) || \ - AVR8_PART_IS_DEFINED(ATxmega32C3) \ - ) - -#define XMEGA_C4 ( \ - AVR8_PART_IS_DEFINED(ATxmega32C4) || \ - AVR8_PART_IS_DEFINED(ATxmega16C4) \ - ) -/** @} */ - -/** - * \name AVR XMEGA D series - * @{ - */ -#define XMEGA_D3 ( \ - AVR8_PART_IS_DEFINED(ATxmega32D3) || \ - AVR8_PART_IS_DEFINED(ATxmega64D3) || \ - AVR8_PART_IS_DEFINED(ATxmega128D3) || \ - AVR8_PART_IS_DEFINED(ATxmega192D3) || \ - AVR8_PART_IS_DEFINED(ATxmega256D3) || \ - AVR8_PART_IS_DEFINED(ATxmega384D3) \ - ) - -#define XMEGA_D4 ( \ - AVR8_PART_IS_DEFINED(ATxmega16D4) || \ - AVR8_PART_IS_DEFINED(ATxmega32D4) || \ - AVR8_PART_IS_DEFINED(ATxmega64D4) || \ - AVR8_PART_IS_DEFINED(ATxmega128D4) \ - ) -/** @} */ - -/** - * \name AVR XMEGA E series - * @{ - */ -#define XMEGA_E5 ( \ - AVR8_PART_IS_DEFINED(ATxmega8E5) || \ - AVR8_PART_IS_DEFINED(ATxmega16E5) || \ - AVR8_PART_IS_DEFINED(ATxmega32E5) \ - ) -/** @} */ - - -/** - * \name AVR XMEGA families - * @{ - */ -/** AVR XMEGA A family */ -#define XMEGA_A (XMEGA_A1 || XMEGA_A3 || XMEGA_A3B || XMEGA_A4) - -/** AVR XMEGA AU family */ -#define XMEGA_AU (XMEGA_A1U || XMEGA_A3U || XMEGA_A3BU || XMEGA_A4U) - -/** AVR XMEGA B family */ -#define XMEGA_B (XMEGA_B1 || XMEGA_B3) - -/** AVR XMEGA C family */ -#define XMEGA_C (XMEGA_C3 || XMEGA_C4) - -/** AVR XMEGA D family */ -#define XMEGA_D (XMEGA_D3 || XMEGA_D4) - -/** AVR XMEGA E family */ -#define XMEGA_E (XMEGA_E5) -/** @} */ - - -/** AVR XMEGA product line */ -#define XMEGA (XMEGA_A || XMEGA_AU || XMEGA_B || XMEGA_C || XMEGA_D || XMEGA_E) - -/** @} */ - -/** - * \defgroup mega_part_macros_group megaAVR parts - * - * \note These megaAVR groupings are based on the groups in AVR Libc for the - * part header files. They are not names of official megaAVR device series or - * families. - * - * @{ - */ - -/** - * \name ATmegaxx0/xx1 subgroups - * @{ - */ -#define MEGA_XX0 ( \ - AVR8_PART_IS_DEFINED(ATmega640) || \ - AVR8_PART_IS_DEFINED(ATmega1280) || \ - AVR8_PART_IS_DEFINED(ATmega2560) \ - ) - -#define MEGA_XX1 ( \ - AVR8_PART_IS_DEFINED(ATmega1281) || \ - AVR8_PART_IS_DEFINED(ATmega2561) \ - ) -/** @} */ - -/** - * \name megaAVR groups - * @{ - */ -/** ATmegaxx0/xx1 group */ -#define MEGA_XX0_1 (MEGA_XX0 || MEGA_XX1) - -/** ATmegaxx4 group */ -#define MEGA_XX4 ( \ - AVR8_PART_IS_DEFINED(ATmega164A) || \ - AVR8_PART_IS_DEFINED(ATmega164PA) || \ - AVR8_PART_IS_DEFINED(ATmega324A) || \ - AVR8_PART_IS_DEFINED(ATmega324PA) || \ - AVR8_PART_IS_DEFINED(ATmega644) || \ - AVR8_PART_IS_DEFINED(ATmega644A) || \ - AVR8_PART_IS_DEFINED(ATmega644PA) || \ - AVR8_PART_IS_DEFINED(ATmega1284P) || \ - AVR8_PART_IS_DEFINED(ATmega128RFA1) \ - ) - -/** ATmegaxx4 group */ -#define MEGA_XX4_A ( \ - AVR8_PART_IS_DEFINED(ATmega164A) || \ - AVR8_PART_IS_DEFINED(ATmega164PA) || \ - AVR8_PART_IS_DEFINED(ATmega324A) || \ - AVR8_PART_IS_DEFINED(ATmega324PA) || \ - AVR8_PART_IS_DEFINED(ATmega644A) || \ - AVR8_PART_IS_DEFINED(ATmega644PA) || \ - AVR8_PART_IS_DEFINED(ATmega1284P) \ - ) - -/** ATmegaxx8 group */ -#define MEGA_XX8 ( \ - AVR8_PART_IS_DEFINED(ATmega48) || \ - AVR8_PART_IS_DEFINED(ATmega48A) || \ - AVR8_PART_IS_DEFINED(ATmega48PA) || \ - AVR8_PART_IS_DEFINED(ATmega88) || \ - AVR8_PART_IS_DEFINED(ATmega88A) || \ - AVR8_PART_IS_DEFINED(ATmega88PA) || \ - AVR8_PART_IS_DEFINED(ATmega168) || \ - AVR8_PART_IS_DEFINED(ATmega168A) || \ - AVR8_PART_IS_DEFINED(ATmega168PA) || \ - AVR8_PART_IS_DEFINED(ATmega328) || \ - AVR8_PART_IS_DEFINED(ATmega328P) \ - ) - -/** ATmegaxx8A/P/PA group */ -#define MEGA_XX8_A ( \ - AVR8_PART_IS_DEFINED(ATmega48A) || \ - AVR8_PART_IS_DEFINED(ATmega48PA) || \ - AVR8_PART_IS_DEFINED(ATmega88A) || \ - AVR8_PART_IS_DEFINED(ATmega88PA) || \ - AVR8_PART_IS_DEFINED(ATmega168A) || \ - AVR8_PART_IS_DEFINED(ATmega168PA) || \ - AVR8_PART_IS_DEFINED(ATmega328P) \ - ) - -/** ATmegaxx group */ -#define MEGA_XX ( \ - AVR8_PART_IS_DEFINED(ATmega16) || \ - AVR8_PART_IS_DEFINED(ATmega16A) || \ - AVR8_PART_IS_DEFINED(ATmega32) || \ - AVR8_PART_IS_DEFINED(ATmega32A) || \ - AVR8_PART_IS_DEFINED(ATmega64) || \ - AVR8_PART_IS_DEFINED(ATmega64A) || \ - AVR8_PART_IS_DEFINED(ATmega128) || \ - AVR8_PART_IS_DEFINED(ATmega128A) \ - ) - -/** ATmegaxxA/P/PA group */ -#define MEGA_XX_A ( \ - AVR8_PART_IS_DEFINED(ATmega16A) || \ - AVR8_PART_IS_DEFINED(ATmega32A) || \ - AVR8_PART_IS_DEFINED(ATmega64A) || \ - AVR8_PART_IS_DEFINED(ATmega128A) \ - ) -/** ATmegaxxRFA1 group */ -#define MEGA_RFA1 ( \ - AVR8_PART_IS_DEFINED(ATmega128RFA1) \ - ) - -/** ATmegaxxRFR2 group */ -#define MEGA_RFR2 ( \ - AVR8_PART_IS_DEFINED(ATmega64RFR2) || \ - AVR8_PART_IS_DEFINED(ATmega128RFR2) || \ - AVR8_PART_IS_DEFINED(ATmega256RFR2) || \ - AVR8_PART_IS_DEFINED(ATmega644RFR2) || \ - AVR8_PART_IS_DEFINED(ATmega1284RFR2) || \ - AVR8_PART_IS_DEFINED(ATmega2564RFR2) \ - ) - - -/** ATmegaxxRFxx group */ -#define MEGA_RF (MEGA_RFA1 || MEGA_RFR2) - -/** - * \name ATmegaxx_un0/un1/un2 subgroups - * @{ - */ -#define MEGA_XX_UN0 ( \ - AVR8_PART_IS_DEFINED(ATmega16) || \ - AVR8_PART_IS_DEFINED(ATmega16A) || \ - AVR8_PART_IS_DEFINED(ATmega32) || \ - AVR8_PART_IS_DEFINED(ATmega32A) \ - ) - -/** ATmegaxx group without power reduction and - * And interrupt sense register. - */ -#define MEGA_XX_UN1 ( \ - AVR8_PART_IS_DEFINED(ATmega64) || \ - AVR8_PART_IS_DEFINED(ATmega64A) || \ - AVR8_PART_IS_DEFINED(ATmega128) || \ - AVR8_PART_IS_DEFINED(ATmega128A) \ - ) - -/** ATmegaxx group without power reduction and - * And interrupt sense register. - */ -#define MEGA_XX_UN2 ( \ - AVR8_PART_IS_DEFINED(ATmega169P) || \ - AVR8_PART_IS_DEFINED(ATmega169PA) || \ - AVR8_PART_IS_DEFINED(ATmega329P) || \ - AVR8_PART_IS_DEFINED(ATmega329PA) \ - ) - -/** Devices added to complete megaAVR offering. - * Please do not use this group symbol as it is not intended - * to be permanent: the devices should be regrouped. - */ -#define MEGA_UNCATEGORIZED ( \ - AVR8_PART_IS_DEFINED(AT90CAN128) || \ - AVR8_PART_IS_DEFINED(AT90CAN32) || \ - AVR8_PART_IS_DEFINED(AT90CAN64) || \ - AVR8_PART_IS_DEFINED(AT90PWM1) || \ - AVR8_PART_IS_DEFINED(AT90PWM216) || \ - AVR8_PART_IS_DEFINED(AT90PWM2B) || \ - AVR8_PART_IS_DEFINED(AT90PWM316) || \ - AVR8_PART_IS_DEFINED(AT90PWM3B) || \ - AVR8_PART_IS_DEFINED(AT90PWM81) || \ - AVR8_PART_IS_DEFINED(AT90USB1286) || \ - AVR8_PART_IS_DEFINED(AT90USB1287) || \ - AVR8_PART_IS_DEFINED(AT90USB162) || \ - AVR8_PART_IS_DEFINED(AT90USB646) || \ - AVR8_PART_IS_DEFINED(AT90USB647) || \ - AVR8_PART_IS_DEFINED(AT90USB82) || \ - AVR8_PART_IS_DEFINED(ATmega1284) || \ - AVR8_PART_IS_DEFINED(ATmega162) || \ - AVR8_PART_IS_DEFINED(ATmega164P) || \ - AVR8_PART_IS_DEFINED(ATmega165A) || \ - AVR8_PART_IS_DEFINED(ATmega165P) || \ - AVR8_PART_IS_DEFINED(ATmega165PA) || \ - AVR8_PART_IS_DEFINED(ATmega168P) || \ - AVR8_PART_IS_DEFINED(ATmega169A) || \ - AVR8_PART_IS_DEFINED(ATmega16M1) || \ - AVR8_PART_IS_DEFINED(ATmega16U2) || \ - AVR8_PART_IS_DEFINED(ATmega16U4) || \ - AVR8_PART_IS_DEFINED(ATmega256RFA2) || \ - AVR8_PART_IS_DEFINED(ATmega324P) || \ - AVR8_PART_IS_DEFINED(ATmega325) || \ - AVR8_PART_IS_DEFINED(ATmega3250) || \ - AVR8_PART_IS_DEFINED(ATmega3250A) || \ - AVR8_PART_IS_DEFINED(ATmega3250P) || \ - AVR8_PART_IS_DEFINED(ATmega3250PA) || \ - AVR8_PART_IS_DEFINED(ATmega325A) || \ - AVR8_PART_IS_DEFINED(ATmega325P) || \ - AVR8_PART_IS_DEFINED(ATmega325PA) || \ - AVR8_PART_IS_DEFINED(ATmega329) || \ - AVR8_PART_IS_DEFINED(ATmega3290) || \ - AVR8_PART_IS_DEFINED(ATmega3290A) || \ - AVR8_PART_IS_DEFINED(ATmega3290P) || \ - AVR8_PART_IS_DEFINED(ATmega3290PA) || \ - AVR8_PART_IS_DEFINED(ATmega329A) || \ - AVR8_PART_IS_DEFINED(ATmega32M1) || \ - AVR8_PART_IS_DEFINED(ATmega32U2) || \ - AVR8_PART_IS_DEFINED(ATmega32U4) || \ - AVR8_PART_IS_DEFINED(ATmega48P) || \ - AVR8_PART_IS_DEFINED(ATmega644P) || \ - AVR8_PART_IS_DEFINED(ATmega645) || \ - AVR8_PART_IS_DEFINED(ATmega6450) || \ - AVR8_PART_IS_DEFINED(ATmega6450A) || \ - AVR8_PART_IS_DEFINED(ATmega6450P) || \ - AVR8_PART_IS_DEFINED(ATmega645A) || \ - AVR8_PART_IS_DEFINED(ATmega645P) || \ - AVR8_PART_IS_DEFINED(ATmega649) || \ - AVR8_PART_IS_DEFINED(ATmega6490) || \ - AVR8_PART_IS_DEFINED(ATmega6490A) || \ - AVR8_PART_IS_DEFINED(ATmega6490P) || \ - AVR8_PART_IS_DEFINED(ATmega649A) || \ - AVR8_PART_IS_DEFINED(ATmega649P) || \ - AVR8_PART_IS_DEFINED(ATmega64M1) || \ - AVR8_PART_IS_DEFINED(ATmega64RFA2) || \ - AVR8_PART_IS_DEFINED(ATmega8) || \ - AVR8_PART_IS_DEFINED(ATmega8515) || \ - AVR8_PART_IS_DEFINED(ATmega8535) || \ - AVR8_PART_IS_DEFINED(ATmega88P) || \ - AVR8_PART_IS_DEFINED(ATmega8A) || \ - AVR8_PART_IS_DEFINED(ATmega8U2) \ - ) - -/** Unspecified group */ -#define MEGA_UNSPECIFIED (MEGA_XX_UN0 || MEGA_XX_UN1 || MEGA_XX_UN2 || \ - MEGA_UNCATEGORIZED) - -/** @} */ - -/** megaAVR product line */ -#define MEGA (MEGA_XX0_1 || MEGA_XX4 || MEGA_XX8 || MEGA_XX || MEGA_RF || \ - MEGA_UNSPECIFIED) - -/** @} */ - -/** - * \defgroup tiny_part_macros_group tinyAVR parts - * - * @{ - */ - -/** - * \name tinyAVR groups - * @{ - */ - -/** Devices added to complete tinyAVR offering. - * Please do not use this group symbol as it is not intended - * to be permanent: the devices should be regrouped. - */ -#define TINY_UNCATEGORIZED ( \ - AVR8_PART_IS_DEFINED(ATtiny10) || \ - AVR8_PART_IS_DEFINED(ATtiny13) || \ - AVR8_PART_IS_DEFINED(ATtiny13A) || \ - AVR8_PART_IS_DEFINED(ATtiny1634) || \ - AVR8_PART_IS_DEFINED(ATtiny167) || \ - AVR8_PART_IS_DEFINED(ATtiny20) || \ - AVR8_PART_IS_DEFINED(ATtiny2313) || \ - AVR8_PART_IS_DEFINED(ATtiny2313A) || \ - AVR8_PART_IS_DEFINED(ATtiny24) || \ - AVR8_PART_IS_DEFINED(ATtiny24A) || \ - AVR8_PART_IS_DEFINED(ATtiny25) || \ - AVR8_PART_IS_DEFINED(ATtiny26) || \ - AVR8_PART_IS_DEFINED(ATtiny261) || \ - AVR8_PART_IS_DEFINED(ATtiny261A) || \ - AVR8_PART_IS_DEFINED(ATtiny4) || \ - AVR8_PART_IS_DEFINED(ATtiny40) || \ - AVR8_PART_IS_DEFINED(ATtiny4313) || \ - AVR8_PART_IS_DEFINED(ATtiny43U) || \ - AVR8_PART_IS_DEFINED(ATtiny44) || \ - AVR8_PART_IS_DEFINED(ATtiny44A) || \ - AVR8_PART_IS_DEFINED(ATtiny45) || \ - AVR8_PART_IS_DEFINED(ATtiny461) || \ - AVR8_PART_IS_DEFINED(ATtiny461A) || \ - AVR8_PART_IS_DEFINED(ATtiny48) || \ - AVR8_PART_IS_DEFINED(ATtiny5) || \ - AVR8_PART_IS_DEFINED(ATtiny828) || \ - AVR8_PART_IS_DEFINED(ATtiny84) || \ - AVR8_PART_IS_DEFINED(ATtiny84A) || \ - AVR8_PART_IS_DEFINED(ATtiny85) || \ - AVR8_PART_IS_DEFINED(ATtiny861) || \ - AVR8_PART_IS_DEFINED(ATtiny861A) || \ - AVR8_PART_IS_DEFINED(ATtiny87) || \ - AVR8_PART_IS_DEFINED(ATtiny88) || \ - AVR8_PART_IS_DEFINED(ATtiny9) \ - ) - -/** @} */ - -/** tinyAVR product line */ -#define TINY (TINY_UNCATEGORIZED) - -/** @} */ - -/** - * \defgroup sam_part_macros_group SAM parts - * @{ - */ - -/** - * \name SAM3S series - * @{ - */ -#define SAM3S1 ( \ - SAM_PART_IS_DEFINED(SAM3S1A) || \ - SAM_PART_IS_DEFINED(SAM3S1B) || \ - SAM_PART_IS_DEFINED(SAM3S1C) \ - ) - -#define SAM3S2 ( \ - SAM_PART_IS_DEFINED(SAM3S2A) || \ - SAM_PART_IS_DEFINED(SAM3S2B) || \ - SAM_PART_IS_DEFINED(SAM3S2C) \ - ) - -#define SAM3S4 ( \ - SAM_PART_IS_DEFINED(SAM3S4A) || \ - SAM_PART_IS_DEFINED(SAM3S4B) || \ - SAM_PART_IS_DEFINED(SAM3S4C) \ - ) - -#define SAM3S8 ( \ - SAM_PART_IS_DEFINED(SAM3S8B) || \ - SAM_PART_IS_DEFINED(SAM3S8C) \ - ) - -#define SAM3SD8 ( \ - SAM_PART_IS_DEFINED(SAM3SD8B) || \ - SAM_PART_IS_DEFINED(SAM3SD8C) \ - ) -/** @} */ - -/** - * \name SAM3U series - * @{ - */ -#define SAM3U1 ( \ - SAM_PART_IS_DEFINED(SAM3U1C) || \ - SAM_PART_IS_DEFINED(SAM3U1E) \ - ) - -#define SAM3U2 ( \ - SAM_PART_IS_DEFINED(SAM3U2C) || \ - SAM_PART_IS_DEFINED(SAM3U2E) \ - ) - -#define SAM3U4 ( \ - SAM_PART_IS_DEFINED(SAM3U4C) || \ - SAM_PART_IS_DEFINED(SAM3U4E) \ - ) -/** @} */ - -/** - * \name SAM3N series - * @{ - */ -#define SAM3N00 ( \ - SAM_PART_IS_DEFINED(SAM3N00A) || \ - SAM_PART_IS_DEFINED(SAM3N00B) \ - ) - -#define SAM3N0 ( \ - SAM_PART_IS_DEFINED(SAM3N0A) || \ - SAM_PART_IS_DEFINED(SAM3N0B) || \ - SAM_PART_IS_DEFINED(SAM3N0C) \ - ) - -#define SAM3N1 ( \ - SAM_PART_IS_DEFINED(SAM3N1A) || \ - SAM_PART_IS_DEFINED(SAM3N1B) || \ - SAM_PART_IS_DEFINED(SAM3N1C) \ - ) - -#define SAM3N2 ( \ - SAM_PART_IS_DEFINED(SAM3N2A) || \ - SAM_PART_IS_DEFINED(SAM3N2B) || \ - SAM_PART_IS_DEFINED(SAM3N2C) \ - ) - -#define SAM3N4 ( \ - SAM_PART_IS_DEFINED(SAM3N4A) || \ - SAM_PART_IS_DEFINED(SAM3N4B) || \ - SAM_PART_IS_DEFINED(SAM3N4C) \ - ) -/** @} */ - -/** - * \name SAM3X series - * @{ - */ -#define SAM3X4 ( \ - SAM_PART_IS_DEFINED(SAM3X4C) || \ - SAM_PART_IS_DEFINED(SAM3X4E) \ - ) - -#define SAM3X8 ( \ - SAM_PART_IS_DEFINED(SAM3X8C) || \ - SAM_PART_IS_DEFINED(SAM3X8E) || \ - SAM_PART_IS_DEFINED(SAM3X8H) \ - ) -/** @} */ - -/** - * \name SAM3A series - * @{ - */ -#define SAM3A4 ( \ - SAM_PART_IS_DEFINED(SAM3A4C) \ - ) - -#define SAM3A8 ( \ - SAM_PART_IS_DEFINED(SAM3A8C) \ - ) -/** @} */ - -/** - * \name SAM4S series - * @{ - */ -#define SAM4S2 ( \ - SAM_PART_IS_DEFINED(SAM4S2A) || \ - SAM_PART_IS_DEFINED(SAM4S2B) || \ - SAM_PART_IS_DEFINED(SAM4S2C) \ - ) - -#define SAM4S4 ( \ - SAM_PART_IS_DEFINED(SAM4S4A) || \ - SAM_PART_IS_DEFINED(SAM4S4B) || \ - SAM_PART_IS_DEFINED(SAM4S4C) \ - ) - -#define SAM4S8 ( \ - SAM_PART_IS_DEFINED(SAM4S8B) || \ - SAM_PART_IS_DEFINED(SAM4S8C) \ - ) - -#define SAM4S16 ( \ - SAM_PART_IS_DEFINED(SAM4S16B) || \ - SAM_PART_IS_DEFINED(SAM4S16C) \ - ) - -#define SAM4SA16 ( \ - SAM_PART_IS_DEFINED(SAM4SA16B) || \ - SAM_PART_IS_DEFINED(SAM4SA16C) \ - ) - -#define SAM4SD16 ( \ - SAM_PART_IS_DEFINED(SAM4SD16B) || \ - SAM_PART_IS_DEFINED(SAM4SD16C) \ - ) - -#define SAM4SD32 ( \ - SAM_PART_IS_DEFINED(SAM4SD32B) || \ - SAM_PART_IS_DEFINED(SAM4SD32C) \ - ) -/** @} */ - -/** - * \name SAM4L series - * @{ - */ -#define SAM4LS ( \ - SAM_PART_IS_DEFINED(SAM4LS2A) || \ - SAM_PART_IS_DEFINED(SAM4LS2B) || \ - SAM_PART_IS_DEFINED(SAM4LS2C) || \ - SAM_PART_IS_DEFINED(SAM4LS4A) || \ - SAM_PART_IS_DEFINED(SAM4LS4B) || \ - SAM_PART_IS_DEFINED(SAM4LS4C) || \ - SAM_PART_IS_DEFINED(SAM4LS8A) || \ - SAM_PART_IS_DEFINED(SAM4LS8B) || \ - SAM_PART_IS_DEFINED(SAM4LS8C) \ - ) - -#define SAM4LC ( \ - SAM_PART_IS_DEFINED(SAM4LC2A) || \ - SAM_PART_IS_DEFINED(SAM4LC2B) || \ - SAM_PART_IS_DEFINED(SAM4LC2C) || \ - SAM_PART_IS_DEFINED(SAM4LC4A) || \ - SAM_PART_IS_DEFINED(SAM4LC4B) || \ - SAM_PART_IS_DEFINED(SAM4LC4C) || \ - SAM_PART_IS_DEFINED(SAM4LC8A) || \ - SAM_PART_IS_DEFINED(SAM4LC8B) || \ - SAM_PART_IS_DEFINED(SAM4LC8C) \ - ) -/** @} */ - -/** - * \name SAMD20 series - * @{ - */ -#define SAMD20J ( \ - SAM_PART_IS_DEFINED(SAMD20J14) || \ - SAM_PART_IS_DEFINED(SAMD20J15) || \ - SAM_PART_IS_DEFINED(SAMD20J16) || \ - SAM_PART_IS_DEFINED(SAMD20J17) || \ - SAM_PART_IS_DEFINED(SAMD20J18) \ - ) - -#define SAMD20G ( \ - SAM_PART_IS_DEFINED(SAMD20G14) || \ - SAM_PART_IS_DEFINED(SAMD20G15) || \ - SAM_PART_IS_DEFINED(SAMD20G16) || \ - SAM_PART_IS_DEFINED(SAMD20G17) || \ - SAM_PART_IS_DEFINED(SAMD20G17U) || \ - SAM_PART_IS_DEFINED(SAMD20G18) || \ - SAM_PART_IS_DEFINED(SAMD20G18U) \ - ) - -#define SAMD20E ( \ - SAM_PART_IS_DEFINED(SAMD20E14) || \ - SAM_PART_IS_DEFINED(SAMD20E15) || \ - SAM_PART_IS_DEFINED(SAMD20E16) || \ - SAM_PART_IS_DEFINED(SAMD20E17) || \ - SAM_PART_IS_DEFINED(SAMD20E18) \ - ) -/** @} */ - -/** - * \name SAMD21 series - * @{ - */ -#define SAMD21J ( \ - SAM_PART_IS_DEFINED(SAMD21J15A) || \ - SAM_PART_IS_DEFINED(SAMD21J16A) || \ - SAM_PART_IS_DEFINED(SAMD21J17A) || \ - SAM_PART_IS_DEFINED(SAMD21J18A) || \ - SAM_PART_IS_DEFINED(SAMD21J15B) || \ - SAM_PART_IS_DEFINED(SAMD21J16B) \ - ) - -#define SAMD21G ( \ - SAM_PART_IS_DEFINED(SAMD21G15A) || \ - SAM_PART_IS_DEFINED(SAMD21G16A) || \ - SAM_PART_IS_DEFINED(SAMD21G17A) || \ - SAM_PART_IS_DEFINED(SAMD21G17AU) || \ - SAM_PART_IS_DEFINED(SAMD21G18A) || \ - SAM_PART_IS_DEFINED(SAMD21G18AU) || \ - SAM_PART_IS_DEFINED(SAMD21G15B) || \ - SAM_PART_IS_DEFINED(SAMD21G16B) || \ - SAM_PART_IS_DEFINED(SAMD21G15L) || \ - SAM_PART_IS_DEFINED(SAMD21G16L) \ - ) - -#define SAMD21GXXL ( \ - SAM_PART_IS_DEFINED(SAMD21G15L) || \ - SAM_PART_IS_DEFINED(SAMD21G16L) \ - ) - -#define SAMD21E ( \ - SAM_PART_IS_DEFINED(SAMD21E15A) || \ - SAM_PART_IS_DEFINED(SAMD21E16A) || \ - SAM_PART_IS_DEFINED(SAMD21E17A) || \ - SAM_PART_IS_DEFINED(SAMD21E18A) || \ - SAM_PART_IS_DEFINED(SAMD21E15B) || \ - SAM_PART_IS_DEFINED(SAMD21E15BU) || \ - SAM_PART_IS_DEFINED(SAMD21E16B) || \ - SAM_PART_IS_DEFINED(SAMD21E16BU) || \ - SAM_PART_IS_DEFINED(SAMD21E15L) || \ - SAM_PART_IS_DEFINED(SAMD21E16L) \ - ) - -#define SAMD21EXXL ( \ - SAM_PART_IS_DEFINED(SAMD21E15L) || \ - SAM_PART_IS_DEFINED(SAMD21E16L) \ - ) - -/** @} */ - -/** - * \name SAMR21 series - * @{ - */ -#define SAMR21G ( \ - SAM_PART_IS_DEFINED(SAMR21G16A) || \ - SAM_PART_IS_DEFINED(SAMR21G17A) || \ - SAM_PART_IS_DEFINED(SAMR21G18A) \ - ) - -#define SAMR21E ( \ - SAM_PART_IS_DEFINED(SAMR21E16A) || \ - SAM_PART_IS_DEFINED(SAMR21E17A) || \ - SAM_PART_IS_DEFINED(SAMR21E18A) || \ - SAM_PART_IS_DEFINED(SAMR21E19A) \ - ) -/** @} */ - -/** - * \name SAMD09 series - * @{ - */ -#define SAMD09C ( \ - SAM_PART_IS_DEFINED(SAMD09C13A) \ - ) - -#define SAMD09D ( \ - SAM_PART_IS_DEFINED(SAMD09D14A) \ - ) -/** @} */ - -/** - * \name SAMD10 series - * @{ - */ -#define SAMD10C ( \ - SAM_PART_IS_DEFINED(SAMD10C12A) || \ - SAM_PART_IS_DEFINED(SAMD10C13A) || \ - SAM_PART_IS_DEFINED(SAMD10C14A) \ - ) - -#define SAMD10DS ( \ - SAM_PART_IS_DEFINED(SAMD10D12AS) || \ - SAM_PART_IS_DEFINED(SAMD10D13AS) || \ - SAM_PART_IS_DEFINED(SAMD10D14AS) \ - ) - -#define SAMD10DM ( \ - SAM_PART_IS_DEFINED(SAMD10D12AM) || \ - SAM_PART_IS_DEFINED(SAMD10D13AM) || \ - SAM_PART_IS_DEFINED(SAMD10D14AM) \ - ) -/** @} */ - -/** - * \name SAMD11 series - * @{ - */ -#define SAMD11C ( \ - SAM_PART_IS_DEFINED(SAMD11C14A) \ - ) - -#define SAMD11DS ( \ - SAM_PART_IS_DEFINED(SAMD11D14AS) \ - ) - -#define SAMD11DM ( \ - SAM_PART_IS_DEFINED(SAMD11D14AM) \ - ) -/** @} */ - -/** - * \name SAML21 series - * @{ - */ -#define SAML21E ( \ - SAM_PART_IS_DEFINED(SAML21E18A) || \ - SAM_PART_IS_DEFINED(SAML21E15B) || \ - SAM_PART_IS_DEFINED(SAML21E16B) || \ - SAM_PART_IS_DEFINED(SAML21E17B) || \ - SAM_PART_IS_DEFINED(SAML21E18B) \ - ) - -#define SAML21G ( \ - SAM_PART_IS_DEFINED(SAML21G18A) || \ - SAM_PART_IS_DEFINED(SAML21G16B) || \ - SAM_PART_IS_DEFINED(SAML21G17B) || \ - SAM_PART_IS_DEFINED(SAML21G18B) \ - ) - -#define SAML21J ( \ - SAM_PART_IS_DEFINED(SAML21J18A) || \ - SAM_PART_IS_DEFINED(SAML21J16B) || \ - SAM_PART_IS_DEFINED(SAML21J17B) || \ - SAM_PART_IS_DEFINED(SAML21J18B) \ - ) - -/* Group for SAML21 A variant: SAML21[E/G/J][18]A */ -#define SAML21XXXA ( \ - SAM_PART_IS_DEFINED(SAML21E18A) || \ - SAM_PART_IS_DEFINED(SAML21G18A) || \ - SAM_PART_IS_DEFINED(SAML21J18A) \ - ) - -/* Group for SAML21 B variant: SAML21[E/G/J][15/16/1718]B */ -#define SAML21XXXB ( \ - SAM_PART_IS_DEFINED(SAML21E15B) || \ - SAM_PART_IS_DEFINED(SAML21E16B) || \ - SAM_PART_IS_DEFINED(SAML21E17B) || \ - SAM_PART_IS_DEFINED(SAML21E18B) || \ - SAM_PART_IS_DEFINED(SAML21G16B) || \ - SAM_PART_IS_DEFINED(SAML21G17B) || \ - SAM_PART_IS_DEFINED(SAML21G18B) || \ - SAM_PART_IS_DEFINED(SAML21J16B) || \ - SAM_PART_IS_DEFINED(SAML21J17B) || \ - SAM_PART_IS_DEFINED(SAML21J18B) \ - ) - -/** @} */ - -/** - * \name SAML22 series - * @{ - */ -#define SAML22N ( \ - SAM_PART_IS_DEFINED(SAML22N16A) || \ - SAM_PART_IS_DEFINED(SAML22N17A) || \ - SAM_PART_IS_DEFINED(SAML22N18A) \ - ) - -#define SAML22G ( \ - SAM_PART_IS_DEFINED(SAML22G16A) || \ - SAM_PART_IS_DEFINED(SAML22G17A) || \ - SAM_PART_IS_DEFINED(SAML22G18A) \ - ) - -#define SAML22J ( \ - SAM_PART_IS_DEFINED(SAML22J16A) || \ - SAM_PART_IS_DEFINED(SAML22J17A) || \ - SAM_PART_IS_DEFINED(SAML22J18A) \ - ) -/** @} */ - -/** - * \name SAMDA0 series - * @{ - */ -#define SAMDA0J ( \ - SAM_PART_IS_DEFINED(SAMDA0J14A) || \ - SAM_PART_IS_DEFINED(SAMDA0J15A) || \ - SAM_PART_IS_DEFINED(SAMDA0J16A) \ - ) - -#define SAMDA0G ( \ - SAM_PART_IS_DEFINED(SAMDA0G14A) || \ - SAM_PART_IS_DEFINED(SAMDA0G15A) || \ - SAM_PART_IS_DEFINED(SAMDA0G16A) \ - ) - -#define SAMDA0E ( \ - SAM_PART_IS_DEFINED(SAMDA0E14A) || \ - SAM_PART_IS_DEFINED(SAMDA0E15A) || \ - SAM_PART_IS_DEFINED(SAMDA0E16A) \ - ) -/** @} */ - -/** - * \name SAMDA1 series - * @{ - */ -#define SAMDA1J ( \ - SAM_PART_IS_DEFINED(SAMDA1J14A) || \ - SAM_PART_IS_DEFINED(SAMDA1J15A) || \ - SAM_PART_IS_DEFINED(SAMDA1J16A) \ - ) - -#define SAMDA1G ( \ - SAM_PART_IS_DEFINED(SAMDA1G14A) || \ - SAM_PART_IS_DEFINED(SAMDA1G15A) || \ - SAM_PART_IS_DEFINED(SAMDA1G16A) \ - ) - -#define SAMDA1E ( \ - SAM_PART_IS_DEFINED(SAMDA1E14A) || \ - SAM_PART_IS_DEFINED(SAMDA1E15A) || \ - SAM_PART_IS_DEFINED(SAMDA1E16A) \ - ) -/** @} */ - -/** - * \name SAMC20 series - * @{ - */ -#define SAMC20E ( \ - SAM_PART_IS_DEFINED(SAMC20E15A) || \ - SAM_PART_IS_DEFINED(SAMC20E16A) || \ - SAM_PART_IS_DEFINED(SAMC20E17A) || \ - SAM_PART_IS_DEFINED(SAMC20E18A) \ - ) - -#define SAMC20G ( \ - SAM_PART_IS_DEFINED(SAMC20G15A) || \ - SAM_PART_IS_DEFINED(SAMC20G16A) || \ - SAM_PART_IS_DEFINED(SAMC20G17A) || \ - SAM_PART_IS_DEFINED(SAMC20G18A) \ - ) - -#define SAMC20J ( \ - SAM_PART_IS_DEFINED(SAMC20J15A) || \ - SAM_PART_IS_DEFINED(SAMC20J16A) || \ - SAM_PART_IS_DEFINED(SAMC20J17A) || \ - SAM_PART_IS_DEFINED(SAMC20J18A) \ - ) -/** @} */ - -/** - * \name SAMC21 series - * @{ - */ -#define SAMC21E ( \ - SAM_PART_IS_DEFINED(SAMC21E15A) || \ - SAM_PART_IS_DEFINED(SAMC21E16A) || \ - SAM_PART_IS_DEFINED(SAMC21E17A) || \ - SAM_PART_IS_DEFINED(SAMC21E18A) \ - ) - -#define SAMC21G ( \ - SAM_PART_IS_DEFINED(SAMC21G15A) || \ - SAM_PART_IS_DEFINED(SAMC21G16A) || \ - SAM_PART_IS_DEFINED(SAMC21G17A) || \ - SAM_PART_IS_DEFINED(SAMC21G18A) \ - ) - -#define SAMC21J ( \ - SAM_PART_IS_DEFINED(SAMC21J15A) || \ - SAM_PART_IS_DEFINED(SAMC21J16A) || \ - SAM_PART_IS_DEFINED(SAMC21J17A) || \ - SAM_PART_IS_DEFINED(SAMC21J18A) \ - ) -/** @} */ - -/** - * \name SAM4E series - * @{ - */ -#define SAM4E8 ( \ - SAM_PART_IS_DEFINED(SAM4E8C) || \ - SAM_PART_IS_DEFINED(SAM4E8E) \ - ) - -#define SAM4E16 ( \ - SAM_PART_IS_DEFINED(SAM4E16C) || \ - SAM_PART_IS_DEFINED(SAM4E16E) \ - ) -/** @} */ - -/** - * \name SAM4N series - * @{ - */ -#define SAM4N8 ( \ - SAM_PART_IS_DEFINED(SAM4N8A) || \ - SAM_PART_IS_DEFINED(SAM4N8B) || \ - SAM_PART_IS_DEFINED(SAM4N8C) \ - ) - -#define SAM4N16 ( \ - SAM_PART_IS_DEFINED(SAM4N16B) || \ - SAM_PART_IS_DEFINED(SAM4N16C) \ - ) -/** @} */ - -/** - * \name SAM4C series - * @{ - */ -#define SAM4C4_0 ( \ - SAM_PART_IS_DEFINED(SAM4C4C_0) \ - ) - -#define SAM4C4_1 ( \ - SAM_PART_IS_DEFINED(SAM4C4C_1) \ - ) - -#define SAM4C4 (SAM4C4_0 || SAM4C4_1) - -#define SAM4C8_0 ( \ - SAM_PART_IS_DEFINED(SAM4C8C_0) \ - ) - -#define SAM4C8_1 ( \ - SAM_PART_IS_DEFINED(SAM4C8C_1) \ - ) - -#define SAM4C8 (SAM4C8_0 || SAM4C8_1) - -#define SAM4C16_0 ( \ - SAM_PART_IS_DEFINED(SAM4C16C_0) \ - ) - -#define SAM4C16_1 ( \ - SAM_PART_IS_DEFINED(SAM4C16C_1) \ - ) - -#define SAM4C16 (SAM4C16_0 || SAM4C16_1) - -#define SAM4C32_0 ( \ - SAM_PART_IS_DEFINED(SAM4C32C_0) ||\ - SAM_PART_IS_DEFINED(SAM4C32E_0) \ - ) - -#define SAM4C32_1 ( \ - SAM_PART_IS_DEFINED(SAM4C32C_1) ||\ - SAM_PART_IS_DEFINED(SAM4C32E_1) \ - ) - - -#define SAM4C32 (SAM4C32_0 || SAM4C32_1) - -/** @} */ - -/** - * \name SAM4CM series - * @{ - */ -#define SAM4CMP8_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMP8C_0) \ - ) - -#define SAM4CMP8_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMP8C_1) \ - ) - -#define SAM4CMP8 (SAM4CMP8_0 || SAM4CMP8_1) - -#define SAM4CMP16_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMP16C_0) \ - ) - -#define SAM4CMP16_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMP16C_1) \ - ) - -#define SAM4CMP16 (SAM4CMP16_0 || SAM4CMP16_1) - -#define SAM4CMP32_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMP32C_0) \ - ) - -#define SAM4CMP32_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMP32C_1) \ - ) - -#define SAM4CMP32 (SAM4CMP32_0 || SAM4CMP32_1) - -#define SAM4CMS4_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMS4C_0) \ - ) - -#define SAM4CMS4_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMS4C_1) \ - ) - -#define SAM4CMS4 (SAM4CMS4_0 || SAM4CMS4_1) - -#define SAM4CMS8_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMS8C_0) \ - ) - -#define SAM4CMS8_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMS8C_1) \ - ) - -#define SAM4CMS8 (SAM4CMS8_0 || SAM4CMS8_1) - -#define SAM4CMS16_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMS16C_0) \ - ) - -#define SAM4CMS16_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMS16C_1) \ - ) - -#define SAM4CMS16 (SAM4CMS16_0 || SAM4CMS16_1) - -#define SAM4CMS32_0 ( \ - SAM_PART_IS_DEFINED(SAM4CMS32C_0) \ - ) - -#define SAM4CMS32_1 ( \ - SAM_PART_IS_DEFINED(SAM4CMS32C_1) \ - ) - -#define SAM4CMS32 (SAM4CMS32_0 || SAM4CMS32_1) - -/** @} */ - -/** - * \name SAM4CP series - * @{ - */ -#define SAM4CP16_0 ( \ - SAM_PART_IS_DEFINED(SAM4CP16B_0) \ - ) - -#define SAM4CP16_1 ( \ - SAM_PART_IS_DEFINED(SAM4CP16B_1) \ - ) - -#define SAM4CP16 (SAM4CP16_0 || SAM4CP16_1) -/** @} */ - -/** - * \name SAMG series - * @{ - */ -#define SAMG51 ( \ - SAM_PART_IS_DEFINED(SAMG51G18) \ - ) - -#define SAMG53 ( \ - SAM_PART_IS_DEFINED(SAMG53G19) ||\ - SAM_PART_IS_DEFINED(SAMG53N19) \ - ) - -#define SAMG54 ( \ - SAM_PART_IS_DEFINED(SAMG54G19) ||\ - SAM_PART_IS_DEFINED(SAMG54J19) ||\ - SAM_PART_IS_DEFINED(SAMG54N19) \ - ) - -#define SAMG55 ( \ - SAM_PART_IS_DEFINED(SAMG55G18) ||\ - SAM_PART_IS_DEFINED(SAMG55G19) ||\ - SAM_PART_IS_DEFINED(SAMG55J18) ||\ - SAM_PART_IS_DEFINED(SAMG55J19) ||\ - SAM_PART_IS_DEFINED(SAMG55N19) \ - ) -/** @} */ - -/** - * \name SAMV71 series - * @{ - */ -#define SAMV71J ( \ - SAM_PART_IS_DEFINED(SAMV71J19) || \ - SAM_PART_IS_DEFINED(SAMV71J20) || \ - SAM_PART_IS_DEFINED(SAMV71J21) \ - ) - -#define SAMV71N ( \ - SAM_PART_IS_DEFINED(SAMV71N19) || \ - SAM_PART_IS_DEFINED(SAMV71N20) || \ - SAM_PART_IS_DEFINED(SAMV71N21) \ - ) - -#define SAMV71Q ( \ - SAM_PART_IS_DEFINED(SAMV71Q19) || \ - SAM_PART_IS_DEFINED(SAMV71Q20) || \ - SAM_PART_IS_DEFINED(SAMV71Q21) \ - ) -/** @} */ - -/** - * \name SAMV70 series - * @{ - */ -#define SAMV70J ( \ - SAM_PART_IS_DEFINED(SAMV70J19) || \ - SAM_PART_IS_DEFINED(SAMV70J20) \ - ) - -#define SAMV70N ( \ - SAM_PART_IS_DEFINED(SAMV70N19) || \ - SAM_PART_IS_DEFINED(SAMV70N20) \ - ) - -#define SAMV70Q ( \ - SAM_PART_IS_DEFINED(SAMV70Q19) || \ - SAM_PART_IS_DEFINED(SAMV70Q20) \ - ) -/** @} */ - -/** - * \name SAMS70 series - * @{ - */ -#define SAMS70J ( \ - SAM_PART_IS_DEFINED(SAMS70J19) || \ - SAM_PART_IS_DEFINED(SAMS70J20) || \ - SAM_PART_IS_DEFINED(SAMS70J21) \ - ) - -#define SAMS70N ( \ - SAM_PART_IS_DEFINED(SAMS70N19) || \ - SAM_PART_IS_DEFINED(SAMS70N20) || \ - SAM_PART_IS_DEFINED(SAMS70N21) \ - ) - -#define SAMS70Q ( \ - SAM_PART_IS_DEFINED(SAMS70Q19) || \ - SAM_PART_IS_DEFINED(SAMS70Q20) || \ - SAM_PART_IS_DEFINED(SAMS70Q21) \ - ) -/** @} */ - -/** - * \name SAME70 series - * @{ - */ -#define SAME70J ( \ - SAM_PART_IS_DEFINED(SAME70J19) || \ - SAM_PART_IS_DEFINED(SAME70J20) || \ - SAM_PART_IS_DEFINED(SAME70J21) \ - ) - -#define SAME70N ( \ - SAM_PART_IS_DEFINED(SAME70N19) || \ - SAM_PART_IS_DEFINED(SAME70N20) || \ - SAM_PART_IS_DEFINED(SAME70N21) \ - ) - -#define SAME70Q ( \ - SAM_PART_IS_DEFINED(SAME70Q19) || \ - SAM_PART_IS_DEFINED(SAME70Q20) || \ - SAM_PART_IS_DEFINED(SAME70Q21) \ - ) -/** @} */ - -/** - * \name SAM families - * @{ - */ -/** SAM3S Family */ -#define SAM3S (SAM3S1 || SAM3S2 || SAM3S4 || SAM3S8 || SAM3SD8) - -/** SAM3U Family */ -#define SAM3U (SAM3U1 || SAM3U2 || SAM3U4) - -/** SAM3N Family */ -#define SAM3N (SAM3N00 || SAM3N0 || SAM3N1 || SAM3N2 || SAM3N4) - -/** SAM3XA Family */ -#define SAM3XA (SAM3X4 || SAM3X8 || SAM3A4 || SAM3A8) - -/** SAM4S Family */ -#define SAM4S (SAM4S2 || SAM4S4 || SAM4S8 || SAM4S16 || SAM4SA16 || SAM4SD16 || SAM4SD32) - -/** SAM4L Family */ -#define SAM4L (SAM4LS || SAM4LC) - -/** SAMD20 Family */ -#define SAMD20 (SAMD20J || SAMD20G || SAMD20E) - -/** SAMD21 Family */ -#define SAMD21 (SAMD21J || SAMD21G || SAMD21E) - -/** SAMD09 Family */ -#define SAMD09 (SAMD09C || SAMD09D) - -/** SAMD10 Family */ -#define SAMD10 (SAMD10C || SAMD10DS || SAMD10DM) - -/** SAMD11 Family */ -#define SAMD11 (SAMD11C || SAMD11DS || SAMD11DM) - -/** SAMDA1 Family */ -#define SAMDA1 (SAMDA1J || SAMDA1G || SAMDA1E) - -/** SAMD Family */ -#define SAMD (SAMD20 || SAMD21 || SAMD09 || SAMD10 || SAMD11 || SAMDA1) - -/** SAMR21 Family */ -#define SAMR21 (SAMR21G || SAMR21E) - -/** SAML21 Family */ -#define SAML21 (SAML21J || SAML21G || SAML21E) - -/** SAML22 Family */ -#define SAML22 (SAML22J || SAML22G || SAML22N) -/** SAMC20 Family */ -#define SAMC20 (SAMC20J || SAMC20G || SAMC20E) - -/** SAMC21 Family */ -#define SAMC21 (SAMC21J || SAMC21G || SAMC21E) - -/** SAM4E Family */ -#define SAM4E (SAM4E8 || SAM4E16) - -/** SAM4N Family */ -#define SAM4N (SAM4N8 || SAM4N16) - -/** SAM4C Family */ -#define SAM4C_0 (SAM4C4_0 || SAM4C8_0 || SAM4C16_0 || SAM4C32_0) -#define SAM4C_1 (SAM4C4_1 || SAM4C8_1 || SAM4C16_1 || SAM4C32_1) -#define SAM4C (SAM4C4 || SAM4C8 || SAM4C16 || SAM4C32) - -/** SAM4CM Family */ -#define SAM4CM_0 (SAM4CMP8_0 || SAM4CMP16_0 || SAM4CMP32_0 || \ - SAM4CMS4_0 || SAM4CMS8_0 || SAM4CMS16_0 || SAM4CMS32_0) -#define SAM4CM_1 (SAM4CMP8_1 || SAM4CMP16_1 || SAM4CMP32_1 || \ - SAM4CMS4_1 || SAM4CMS8_1 || SAM4CMS16_1 || SAM4CMS32_1) -#define SAM4CM (SAM4CMP8 || SAM4CMP16 || SAM4CMP32 || \ - SAM4CMS4 || SAM4CMS8 || SAM4CMS16 || SAM4CMS32) - -/** SAM4CP Family */ -#define SAM4CP_0 (SAM4CP16_0) -#define SAM4CP_1 (SAM4CP16_1) -#define SAM4CP (SAM4CP16) - -/** SAMG Family */ -#define SAMG (SAMG51 || SAMG53 || SAMG54 || SAMG55) - -/** SAMV71 Family */ -#define SAMV71 (SAMV71J || SAMV71N || SAMV71Q) - -/** SAMV70 Family */ -#define SAMV70 (SAMV70J || SAMV70N || SAMV70Q) - -/** SAME70 Family */ -#define SAME70 (SAME70J || SAME70N || SAME70Q) - -/** SAMS70 Family */ -#define SAMS70 (SAMS70J || SAMS70N || SAMS70Q) - -/** SAM0 product line (cortex-m0+) */ -#define SAM0 (SAMD20 || SAMD21 || SAMR21 || SAMD10 || SAMD11 || SAML21 ||\ - SAMDA1 || SAMC20 || SAMC21 || SAML22 || SAMD09) - -/** @} */ - -/** SAM product line */ -#define SAM (SAM3S || SAM3U || SAM3N || SAM3XA || SAM4S || SAM4L || SAM4E || \ - SAM0 || SAM4N || SAM4C || SAM4CM || SAM4CP || SAMG || SAMV71 || SAMV70 || SAME70 || SAMS70) - -/** @} */ - -/** @} */ - -/** @} */ - -#endif /* ATMEL_PARTS_H */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/pinmux.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/pinmux.c deleted file mode 100644 index a2c9c7c..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/pinmux.c +++ /dev/null @@ -1,311 +0,0 @@ -/** - * \file - * - * \brief SAM Pin Multiplexer Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#include - -/** - * \internal - * Writes out a given configuration of a Port pin configuration to the - * hardware module. - * - * \note If the pin direction is set as an output, the pull-up/pull-down input - * configuration setting is ignored. - * - * \param[in] port Base of the PORT module to configure - * \param[in] pin_mask Mask of the port pin to configure - * \param[in] config Configuration settings for the pin - */ -static void _system_pinmux_config( - PortGroup *const port, - const uint32_t pin_mask, - const struct system_pinmux_config *const config) -{ - Assert(port); - Assert(config); - - /* Track the configuration bits into a temporary variable before writing */ - uint32_t pin_cfg = 0; - - /* Enabled powersave mode, don't create configuration */ - if (!config->powersave) { - /* Enable the pin peripheral MUX flag if non-GPIO selected (pinmux will - * be written later) and store the new MUX mask */ - if (config->mux_position != SYSTEM_PINMUX_GPIO) { - pin_cfg |= PORT_WRCONFIG_PMUXEN; - pin_cfg |= (config->mux_position << PORT_WRCONFIG_PMUX_Pos); - } - - /* Check if the user has requested that the input buffer be enabled */ - if ((config->direction == SYSTEM_PINMUX_PIN_DIR_INPUT) || - (config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK)) { - /* Enable input buffer flag */ - pin_cfg |= PORT_WRCONFIG_INEN; - - /* Enable pull-up/pull-down control flag if requested */ - if (config->input_pull != SYSTEM_PINMUX_PIN_PULL_NONE) { - pin_cfg |= PORT_WRCONFIG_PULLEN; - } - - /* Clear the port DIR bits to disable the output buffer */ - port->DIRCLR.reg = pin_mask; - } - - /* Check if the user has requested that the output buffer be enabled */ - if ((config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT) || - (config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK)) { - /* Cannot use a pull-up if the output driver is enabled, - * if requested the input buffer can only sample the current - * output state */ - pin_cfg &= ~PORT_WRCONFIG_PULLEN; - } - } else { - port->DIRCLR.reg = pin_mask; - } - - /* The Write Configuration register (WRCONFIG) requires the - * pins to to grouped into two 16-bit half-words - split them out here */ - uint32_t lower_pin_mask = (pin_mask & 0xFFFF); - uint32_t upper_pin_mask = (pin_mask >> 16); - - /* Configure the lower 16-bits of the port to the desired configuration, - * including the pin peripheral multiplexer just in case it is enabled */ - port->WRCONFIG.reg - = (lower_pin_mask << PORT_WRCONFIG_PINMASK_Pos) | - pin_cfg | PORT_WRCONFIG_WRPMUX | PORT_WRCONFIG_WRPINCFG; - - /* Configure the upper 16-bits of the port to the desired configuration, - * including the pin peripheral multiplexer just in case it is enabled */ - port->WRCONFIG.reg - = (upper_pin_mask << PORT_WRCONFIG_PINMASK_Pos) | - pin_cfg | PORT_WRCONFIG_WRPMUX | PORT_WRCONFIG_WRPINCFG | - PORT_WRCONFIG_HWSEL; - - if(!config->powersave) { - /* Set the pull-up state once the port pins are configured if one was - * requested and it does not violate the valid set of port - * configurations */ - if (pin_cfg & PORT_WRCONFIG_PULLEN) { - /* Set the OUT register bits to enable the pull-up if requested, - * clear to enable pull-down */ - if (config->input_pull == SYSTEM_PINMUX_PIN_PULL_UP) { - port->OUTSET.reg = pin_mask; - } else { - port->OUTCLR.reg = pin_mask; - } - } - - /* Check if the user has requested that the output buffer be enabled */ - if ((config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT) || - (config->direction == SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK)) { - /* Set the port DIR bits to enable the output buffer */ - port->DIRSET.reg = pin_mask; - } - } -} - -/** - * \brief Writes a Port pin configuration to the hardware module. - * - * Writes out a given configuration of a Port pin configuration to the hardware - * module. - * - * \note If the pin direction is set as an output, the pull-up/pull-down input - * configuration setting is ignored. - * - * \param[in] gpio_pin Index of the GPIO pin to configure - * \param[in] config Configuration settings for the pin - */ -void system_pinmux_pin_set_config( - const uint8_t gpio_pin, - const struct system_pinmux_config *const config) -{ - PortGroup *const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); - uint32_t pin_mask = (1UL << (gpio_pin % 32)); - - _system_pinmux_config(port, pin_mask, config); -} - -/** - * \brief Writes a Port pin group configuration to the hardware module. - * - * Writes out a given configuration of a Port pin group configuration to the - * hardware module. - * - * \note If the pin direction is set as an output, the pull-up/pull-down input - * configuration setting is ignored. - * - * \param[in] port Base of the PORT module to configure - * \param[in] mask Mask of the port pin(s) to configure - * \param[in] config Configuration settings for the pin - */ -void system_pinmux_group_set_config( - PortGroup *const port, - const uint32_t mask, - const struct system_pinmux_config *const config) -{ - Assert(port); - - for (int i = 0; i < 32; i++) { - if (mask & (1UL << i)) { - _system_pinmux_config(port, (1UL << i), config); - } - } -} - -/** - * \brief Configures the input sampling mode for a group of pins. - * - * Configures the input sampling mode for a group of pins, to - * control when the physical I/O pin value is sampled and - * stored inside the microcontroller. - * - * \param[in] port Base of the PORT module to configure - * \param[in] mask Mask of the port pin(s) to configure - * \param[in] mode New pin sampling mode to configure - */ -void system_pinmux_group_set_input_sample_mode( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_sample mode) -{ - Assert(port); - - if (mode == SYSTEM_PINMUX_PIN_SAMPLE_ONDEMAND) { - port->CTRL.reg |= mask; - } else { - port->CTRL.reg &= ~mask; - } -} - -#ifdef FEATURE_SYSTEM_PINMUX_SLEWRATE_LIMITER -/** - * \brief Configures the output slew rate mode for a group of pins. - * - * Configures the output slew rate mode for a group of pins, to - * control the speed at which the physical output pin can react to - * logical changes of the I/O pin value. - * - * \param[in] port Base of the PORT module to configure - * \param[in] mask Mask of the port pin(s) to configure - * \param[in] mode New pin slew rate mode to configure - */ -void system_pinmux_group_set_output_slew_rate( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_slew_rate mode) -{ - Assert(port); - - for (int i = 0; i < 32; i++) { - if (mask & (1UL << i)) { - if (mode == SYSTEM_PINMUX_PIN_SLEW_RATE_LIMITED) { - port->PINCFG[i].reg |= PORT_PINCFG_SLEWLIM; - } else { - port->PINCFG[i].reg &= ~PORT_PINCFG_SLEWLIM; - } - } - } -} -#endif - -#ifdef FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTH -/** - * \brief Configures the output driver strength mode for a group of pins. - * - * Configures the output drive strength for a group of pins, to - * control the amount of current the pad is able to sink/source. - * - * \param[in] port Base of the PORT module to configure - * \param[in] mask Mask of the port pin(s) to configure - * \param[in] mode New output driver strength mode to configure - */ -void system_pinmux_group_set_output_strength( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_strength mode) -{ - Assert(port); - - for (int i = 0; i < 32; i++) { - if (mask & (1UL << i)) { - if (mode == SYSTEM_PINMUX_PIN_STRENGTH_HIGH) { - port->PINCFG[i].reg |= PORT_PINCFG_DRVSTR; - } else { - port->PINCFG[i].reg &= ~PORT_PINCFG_DRVSTR; - } - } - } -} -#endif - -#ifdef FEATURE_SYSTEM_PINMUX_OPEN_DRAIN -/** - * \brief Configures the output driver mode for a group of pins. - * - * Configures the output driver mode for a group of pins, to - * control the pad behavior. - * - * \param[in] port Base of the PORT module to configure - * \param[in] mask Mask of the port pin(s) to configure - * \param[in] mode New pad output driver mode to configure - */ -void system_pinmux_group_set_output_drive( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_drive mode) -{ - Assert(port); - - for (int i = 0; i < 32; i++) { - if (mask & (1UL << i)) { - if (mode == SYSTEM_PINMUX_PIN_DRIVE_OPEN_DRAIN) { - port->PINCFG[i].reg |= PORT_PINCFG_ODRAIN; - } else { - port->PINCFG[i].reg &= ~PORT_PINCFG_ODRAIN; - } - } - } -} -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/pinmux.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/pinmux.h deleted file mode 100644 index 7a441cc..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/pinmux.h +++ /dev/null @@ -1,678 +0,0 @@ -/** - * \file - * - * \brief SAM Pin Multiplexer Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef PINMUX_H_INCLUDED -#define PINMUX_H_INCLUDED - -/** - * \defgroup asfdoc_sam0_system_pinmux_group SAM System Pin Multiplexer (SYSTEM PINMUX) Driver - * - * This driver for Atmel® | SMART ARM®-based microcontrollers provides - * an interface for the configuration and management of the device's physical - * I/O Pins, to alter the direction and input/drive characteristics as well as - * to configure the pin peripheral multiplexer selection. - * - * The following peripheral is used by this module: - * - PORT (Port I/O Management) - * - * The following devices can use this module: - * - Atmel | SMART SAM D20/D21 - * - Atmel | SMART SAM R21 - * - Atmel | SMART SAM D09/D10/D11 - * - Atmel | SMART SAM L21/L22 - * - Atmel | SMART SAM DA1 - * - Atmel | SMART SAM C20/C21 - * - * Physically, the modules are interconnected within the device as shown in the - * following diagram: - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_system_pinmux_prerequisites - * - \ref asfdoc_sam0_system_pinmux_module_overview - * - \ref asfdoc_sam0_system_pinmux_special_considerations - * - \ref asfdoc_sam0_system_pinmux_extra_info - * - \ref asfdoc_sam0_system_pinmux_examples - * - \ref asfdoc_sam0_system_pinmux_api_overview - * - * - * \section asfdoc_sam0_system_pinmux_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * - * \section asfdoc_sam0_system_pinmux_module_overview Module Overview - * - * The SAM devices contain a number of General Purpose I/O pins, used to - * interface the user application logic and internal hardware peripherals to - * an external system. The Pin Multiplexer (PINMUX) driver provides a method - * of configuring the individual pin peripheral multiplexers to select - * alternate pin functions. - * - * \subsection asfdoc_sam0_system_pinmux_features Driver Feature Macro Definition - * - * - * - * - * - * - * - * - * - *
Driver Feature MacroSupported devices
FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTHSAM L21, SAM C20/C21
- * \note The specific features are only available in the driver when the - * selected device supports those features. - * - * \subsection asfdoc_sam0_system_pinmux_physical_logical_pins Physical and Logical GPIO Pins - * SAM devices use two naming conventions for the I/O pins in the device; one - * physical and one logical. Each physical pin on a device package is assigned - * both a physical port and pin identifier (e.g. "PORTA.0") as well as a - * monotonically incrementing logical GPIO number (e.g. "GPIO0"). While the - * former is used to map physical pins to their physical internal device module - * counterparts, for simplicity the design of this driver uses the logical GPIO - * numbers instead. - * - * \subsection asfdoc_sam0_system_pinmux_peripheral_muxing Peripheral Multiplexing - * SAM devices contain a peripheral MUX, which is individually controllable - * for each I/O pin of the device. The peripheral MUX allows you to select the - * function of a physical package pin - whether it will be controlled as a user - * controllable GPIO pin, or whether it will be connected internally to one of - * several peripheral modules (such as an I2C module). When a pin is - * configured in GPIO mode, other peripherals connected to the same pin will be - * disabled. - * - * \subsection asfdoc_sam0_system_pinmux_pad_characteristics Special Pad Characteristics - * There are several special modes that can be selected on one or more I/O pins - * of the device, which alter the input and output characteristics of the pad. - * - * \subsubsection asfdoc_sam0_system_pinmux_drive_strength Drive Strength - * The Drive Strength configures the strength of the output driver on the - * pad. Normally, there is a fixed current limit that each I/O pin can safely - * drive, however some I/O pads offer a higher drive mode which increases this - * limit for that I/O pin at the expense of an increased power consumption. - * - * \subsubsection asfdoc_sam0_system_pinmux_slew_rate Slew Rate - * The Slew Rate configures the slew rate of the output driver, limiting the - * rate at which the pad output voltage can change with time. - * - * \subsubsection asfdoc_sam0_system_pinmux_input_sample_mode Input Sample Mode - * The Input Sample Mode configures the input sampler buffer of the pad. By - * default, the input buffer is only sampled "on-demand", i.e. when the user - * application attempts to read from the input buffer. This mode is the most - * power efficient, but increases the latency of the input sample by two clock - * cycles of the port clock. To reduce latency, the input sampler can instead - * be configured to always sample the input buffer on each port clock cycle, at - * the expense of an increased power consumption. - * - * \subsection asfdoc_sam0_system_pinmux_module_overview_physical Physical Connection - * - * \ref asfdoc_sam0_system_pinmux_intconnections "The diagram below" shows - * how this module is interconnected within the device: - * - * \anchor asfdoc_sam0_system_pinmux_intconnections - * \dot - * digraph overview { - * node [label="Port Pad" shape=square] pad; - * - * subgraph driver { - * node [label="Peripheral MUX" shape=trapezium] pinmux; - * node [label="GPIO Module" shape=ellipse shape=ellipse style=filled fillcolor=lightgray] gpio; - * node [label="Other Peripheral Modules" shape=ellipse style=filled fillcolor=lightgray] peripherals; - * } - * - * pinmux -> gpio; - * pad -> pinmux; - * pinmux -> peripherals; - * } - * \enddot - * - * \section asfdoc_sam0_system_pinmux_special_considerations Special Considerations - * - * The SAM port pin input sampling mode is set in groups of four physical - * pins; setting the sampling mode of any pin in a sub-group of eight I/O pins - * will configure the sampling mode of the entire sub-group. - * - * High Drive Strength output driver mode is not available on all device pins - - * refer to your device specific datasheet. - * - * - * \section asfdoc_sam0_system_pinmux_extra_info Extra Information - * - * For extra information, see \ref asfdoc_sam0_system_pinmux_extra. This includes: - * - \ref asfdoc_sam0_system_pinmux_extra_acronyms - * - \ref asfdoc_sam0_system_pinmux_extra_dependencies - * - \ref asfdoc_sam0_system_pinmux_extra_errata - * - \ref asfdoc_sam0_system_pinmux_extra_history - * - * - * \section asfdoc_sam0_system_pinmux_examples Examples - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_system_pinmux_exqsg. - * - * - * \section asfdoc_sam0_system_pinmux_api_overview API Overview - * @{ - */ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/*@{*/ -#if (SAML21) || (SAMC20) || (SAMC21) || defined(__DOXYGEN__) -/** Output Driver Strength Selection feature support */ -# define FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTH -#endif -/*@}*/ - -/** Peripheral multiplexer index to select GPIO mode for a pin */ -#define SYSTEM_PINMUX_GPIO (1 << 7) - -/** - * \brief Port pin direction configuration enum. - * - * Enum for the possible pin direction settings of the port pin configuration - * structure, to indicate the direction the pin should use. - */ -enum system_pinmux_pin_dir { - /** The pin's input buffer should be enabled, so that the pin state can - * be read */ - SYSTEM_PINMUX_PIN_DIR_INPUT, - /** The pin's output buffer should be enabled, so that the pin state can - * be set (but not read back) */ - SYSTEM_PINMUX_PIN_DIR_OUTPUT, - /** The pin's output and input buffers should both be enabled, so that the - * pin state can be set and read back */ - SYSTEM_PINMUX_PIN_DIR_OUTPUT_WITH_READBACK, -}; - -/** - * \brief Port pin input pull configuration enum. - * - * Enum for the possible pin pull settings of the port pin configuration - * structure, to indicate the type of logic level pull the pin should use. - */ -enum system_pinmux_pin_pull { - /** No logical pull should be applied to the pin */ - SYSTEM_PINMUX_PIN_PULL_NONE, - /** Pin should be pulled up when idle */ - SYSTEM_PINMUX_PIN_PULL_UP, - /** Pin should be pulled down when idle */ - SYSTEM_PINMUX_PIN_PULL_DOWN, -}; - -/** - * \brief Port pin digital input sampling mode enum. - * - * Enum for the possible input sampling modes for the port pin configuration - * structure, to indicate the type of sampling a port pin should use. - */ -enum system_pinmux_pin_sample { - /** Pin input buffer should continuously sample the pin state */ - SYSTEM_PINMUX_PIN_SAMPLE_CONTINUOUS, - /** Pin input buffer should be enabled when the IN register is read */ - SYSTEM_PINMUX_PIN_SAMPLE_ONDEMAND, -}; - -/** - * \brief Port pin configuration structure. - * - * Configuration structure for a port pin instance. This structure should - * be initialized by the \ref system_pinmux_get_config_defaults() function - * before being modified by the user application. - */ -struct system_pinmux_config { - /** MUX index of the peripheral that should control the pin, if peripheral - * control is desired. For GPIO use, this should be set to - * \ref SYSTEM_PINMUX_GPIO. */ - uint8_t mux_position; - - /** Port buffer input/output direction */ - enum system_pinmux_pin_dir direction; - - /** Logic level pull of the input buffer */ - enum system_pinmux_pin_pull input_pull; - - /** Enable lowest possible powerstate on the pin. - * - * \note All other configurations will be ignored, the pin will be disabled. - */ - bool powersave; -}; - -/** \name Configuration and Initialization - * @{ - */ - -/** - * \brief Initializes a Port pin configuration structure to defaults. - * - * Initializes a given Port pin configuration structure to a set of - * known default values. This function should be called on all new - * instances of these configuration structures before being modified by the - * user application. - * - * The default configuration is as follows: - * \li Non peripheral (i.e. GPIO) controlled - * \li Input mode with internal pull-up enabled - * - * \param[out] config Configuration structure to initialize to default values - */ -static inline void system_pinmux_get_config_defaults( - struct system_pinmux_config *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Default configuration values */ - config->mux_position = SYSTEM_PINMUX_GPIO; - config->direction = SYSTEM_PINMUX_PIN_DIR_INPUT; - config->input_pull = SYSTEM_PINMUX_PIN_PULL_UP; - config->powersave = false; -} - -void system_pinmux_pin_set_config( - const uint8_t gpio_pin, - const struct system_pinmux_config *const config); - -void system_pinmux_group_set_config( - PortGroup *const port, - const uint32_t mask, - const struct system_pinmux_config *const config); - -/** @} */ - -/** \name Special Mode Configuration (Physical Group Orientated) - * @{ - */ - -/** - * \brief Retrieves the PORT module group instance from a given GPIO pin number. - * - * Retrieves the PORT module group instance associated with a given logical - * GPIO pin number. - * - * \param[in] gpio_pin Index of the GPIO pin to convert - * - * \return Base address of the associated PORT module. - */ -static inline PortGroup* system_pinmux_get_group_from_gpio_pin( - const uint8_t gpio_pin) -{ - uint8_t port_index = (gpio_pin / 128); - uint8_t group_index = (gpio_pin / 32); - - /* Array of available ports */ - Port *const ports[PORT_INST_NUM] = PORT_INSTS; - - if (port_index < PORT_INST_NUM) { - return &(ports[port_index]->Group[group_index]); - } else { - Assert(false); - return NULL; - } -} - -void system_pinmux_group_set_input_sample_mode( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_sample mode); - -/** @} */ - -/** \name Special Mode Configuration (Logical Pin Orientated) - * @{ - */ - -/** - * \brief Retrieves the currently selected MUX position of a logical pin. - * - * Retrieves the selected MUX peripheral on a given logical GPIO pin. - * - * \param[in] gpio_pin Index of the GPIO pin to configure - * - * \return Currently selected peripheral index on the specified pin. - */ -static inline uint8_t system_pinmux_pin_get_mux_position( - const uint8_t gpio_pin) -{ - PortGroup *const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); - uint32_t pin_index = (gpio_pin % 32); - - if (!(port->PINCFG[pin_index].reg & PORT_PINCFG_PMUXEN)) { - return SYSTEM_PINMUX_GPIO; - } - - uint32_t pmux_reg = port->PMUX[pin_index / 2].reg; - - if (pin_index & 1) { - return (pmux_reg & PORT_PMUX_PMUXO_Msk) >> PORT_PMUX_PMUXO_Pos; - } - else { - return (pmux_reg & PORT_PMUX_PMUXE_Msk) >> PORT_PMUX_PMUXE_Pos; - } -} - -/** - * \brief Configures the input sampling mode for a GPIO pin. - * - * Configures the input sampling mode for a GPIO input, to - * control when the physical I/O pin value is sampled and - * stored inside the microcontroller. - * - * \param[in] gpio_pin Index of the GPIO pin to configure - * \param[in] mode New pin sampling mode to configure - */ -static inline void system_pinmux_pin_set_input_sample_mode( - const uint8_t gpio_pin, - const enum system_pinmux_pin_sample mode) -{ - PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); - uint32_t pin_index = (gpio_pin % 32); - - if (mode == SYSTEM_PINMUX_PIN_SAMPLE_ONDEMAND) { - port->CTRL.reg |= (1 << pin_index); - } else { - port->CTRL.reg &= ~(1 << pin_index); - } -} - -/** @} */ - -#ifdef FEATURE_SYSTEM_PINMUX_DRIVE_STRENGTH -/** - * \brief Port pin drive output strength enum. - * - * Enum for the possible output drive strengths for the port pin - * configuration structure, to indicate the driver strength the pin should - * use. - */ -enum system_pinmux_pin_strength { - /** Normal output driver strength */ - SYSTEM_PINMUX_PIN_STRENGTH_NORMAL, - /** High current output driver strength */ - SYSTEM_PINMUX_PIN_STRENGTH_HIGH, -}; - -/** - * \brief Configures the output driver strength mode for a GPIO pin. - * - * Configures the output drive strength for a GPIO output, to - * control the amount of current the pad is able to sink/source. - * - * \param[in] gpio_pin Index of the GPIO pin to configure - * \param[in] mode New output driver strength mode to configure - */ -static inline void system_pinmux_pin_set_output_strength( - const uint8_t gpio_pin, - const enum system_pinmux_pin_strength mode) -{ - PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); - uint32_t pin_index = (gpio_pin % 32); - - if (mode == SYSTEM_PINMUX_PIN_STRENGTH_HIGH) { - port->PINCFG[pin_index].reg |= PORT_PINCFG_DRVSTR; - } - else { - port->PINCFG[pin_index].reg &= ~PORT_PINCFG_DRVSTR; - } -} - -void system_pinmux_group_set_output_strength( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_strength mode); -#endif - -#ifdef FEATURE_SYSTEM_PINMUX_SLEWRATE_LIMITER -/** - * \brief Port pin output slew rate enum. - * - * Enum for the possible output drive slew rates for the port pin - * configuration structure, to indicate the driver slew rate the pin should - * use. - */ -enum system_pinmux_pin_slew_rate { - /** Normal pin output slew rate */ - SYSTEM_PINMUX_PIN_SLEW_RATE_NORMAL, - /** Enable slew rate limiter on the pin */ - SYSTEM_PINMUX_PIN_SLEW_RATE_LIMITED, -}; - -/** - * \brief Configures the output slew rate mode for a GPIO pin. - * - * Configures the output slew rate mode for a GPIO output, to - * control the speed at which the physical output pin can react to - * logical changes of the I/O pin value. - * - * \param[in] gpio_pin Index of the GPIO pin to configure - * \param[in] mode New pin slew rate mode to configure - */ -static inline void system_pinmux_pin_set_output_slew_rate( - const uint8_t gpio_pin, - const enum system_pinmux_pin_slew_rate mode) -{ - PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); - uint32_t pin_index = (gpio_pin % 32); - - if (mode == SYSTEM_PINMUX_PIN_SLEW_RATE_LIMITED) { - port->PINCFG[pin_index].reg |= PORT_PINCFG_SLEWLIM; - } - else { - port->PINCFG[pin_index].reg &= ~PORT_PINCFG_SLEWLIM; - } -} - -void system_pinmux_group_set_output_slew_rate( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_slew_rate mode); -#endif - -#ifdef FEATURE_SYSTEM_PINMUX_OPEN_DRAIN -/** - * \brief Port pin output drive mode enum. - * - * Enum for the possible output drive modes for the port pin configuration - * structure, to indicate the output mode the pin should use. - */ -enum system_pinmux_pin_drive { - /** Use totem pole output drive mode */ - SYSTEM_PINMUX_PIN_DRIVE_TOTEM, - /** Use open drain output drive mode */ - SYSTEM_PINMUX_PIN_DRIVE_OPEN_DRAIN, -}; - -/** - * \brief Configures the output driver mode for a GPIO pin. - * - * Configures the output driver mode for a GPIO output, to - * control the pad behavior. - * - * \param[in] gpio_pin Index of the GPIO pin to configure - * \param[in] mode New pad output driver mode to configure - */ -static inline void system_pinmux_pin_set_output_drive( - const uint8_t gpio_pin, - const enum system_pinmux_pin_drive mode) -{ - PortGroup* const port = system_pinmux_get_group_from_gpio_pin(gpio_pin); - uint32_t pin_index = (gpio_pin % 32); - - if (mode == SYSTEM_PINMUX_PIN_DRIVE_OPEN_DRAIN) { - port->PINCFG[pin_index].reg |= PORT_PINCFG_ODRAIN; - } - else { - port->PINCFG[pin_index].reg &= ~PORT_PINCFG_ODRAIN; - } -} - -void system_pinmux_group_set_output_drive( - PortGroup *const port, - const uint32_t mask, - const enum system_pinmux_pin_drive mode); -#endif - -#ifdef __cplusplus -} -#endif - -/** @} */ - -/** - * \page asfdoc_sam0_system_pinmux_extra Extra Information for SYSTEM PINMUX Driver - * - * \section asfdoc_sam0_system_pinmux_extra_acronyms Acronyms - * The table below presents the acronyms used in this module: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
AcronymDescription
GPIOGeneral Purpose Input/Output
MUXMultiplexer
- * - * - * \section asfdoc_sam0_system_pinmux_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - None - * - * - * \section asfdoc_sam0_system_pinmux_extra_errata Errata - * There are no errata related to this driver. - * - * - * \section asfdoc_sam0_system_pinmux_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Changelog
Removed code of open drain, slew limit and drive strength - * features
Fixed broken sampling mode function implementations, which wrote - * corrupt configuration values to the device registers
Added missing NULL pointer asserts to the PORT driver functions
Initial Release
- */ - -/** - * \page asfdoc_sam0_system_pinmux_exqsg Examples for SYSTEM PINMUX Driver - * - * This is a list of the available Quick Start guides (QSGs) and example - * applications for \ref asfdoc_sam0_system_pinmux_group. QSGs are simple - * examples with step-by-step instructions to configure and use this driver in a - * selection of use cases. Note that a QSG can be compiled as a standalone - * application or be added to the user application. - * - * - \subpage asfdoc_sam0_system_pinmux_basic_use_case - * - * \page asfdoc_sam0_system_pinmux_document_revision_history Document Revision History - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Doc. Rev. - * Date - * Comments - *
42121F08/2015Added support for SAM L21/L22, SAM DA1, and SAM C20/C21
42121E12/2014Added support for SAM R21 and SAM D10/D11
42121D01/2014Added support for SAM D21
42121C09/2013Fixed incorrect documentation for the device pin sampling mode
42121B06/2013Corrected documentation typos
42121A06/2013Initial release
- */ - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/power.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/power.h deleted file mode 100644 index 5e90585..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/power.h +++ /dev/null @@ -1,224 +0,0 @@ -/** - * \file - * - * \brief SAM Power related functionality - * - * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef POWER_H_INCLUDED -#define POWER_H_INCLUDED - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \addtogroup asfdoc_sam0_system_group - * @{ - */ - -/** - * \brief Voltage references within the device. - * - * List of available voltage references (VREF) that may be used within the - * device. - */ -enum system_voltage_reference { - /** Temperature sensor voltage reference. */ - SYSTEM_VOLTAGE_REFERENCE_TEMPSENSE, - /** Bandgap voltage reference. */ - SYSTEM_VOLTAGE_REFERENCE_BANDGAP, -}; - -/** - * \brief Device sleep modes. - * - * List of available sleep modes in the device. A table of clocks available in - * different sleep modes can be found in \ref asfdoc_sam0_system_module_overview_sleep_mode. - */ -enum system_sleepmode { - /** IDLE 0 sleep mode. */ - SYSTEM_SLEEPMODE_IDLE_0, - /** IDLE 1 sleep mode. */ - SYSTEM_SLEEPMODE_IDLE_1, - /** IDLE 2 sleep mode. */ - SYSTEM_SLEEPMODE_IDLE_2, - /** Standby sleep mode. */ - SYSTEM_SLEEPMODE_STANDBY, -}; - - - -/** - * \name Voltage References - * @{ - */ - -/** - * \brief Enable the selected voltage reference - * - * Enables the selected voltage reference source, making the voltage reference - * available on a pin as well as an input source to the analog peripherals. - * - * \param[in] vref Voltage reference to enable - */ -static inline void system_voltage_reference_enable( - const enum system_voltage_reference vref) -{ - switch (vref) { - case SYSTEM_VOLTAGE_REFERENCE_TEMPSENSE: - SYSCTRL->VREF.reg |= SYSCTRL_VREF_TSEN; - break; - - case SYSTEM_VOLTAGE_REFERENCE_BANDGAP: - SYSCTRL->VREF.reg |= SYSCTRL_VREF_BGOUTEN; - break; - - default: - Assert(false); - return; - } -} - -/** - * \brief Disable the selected voltage reference - * - * Disables the selected voltage reference source. - * - * \param[in] vref Voltage reference to disable - */ -static inline void system_voltage_reference_disable( - const enum system_voltage_reference vref) -{ - switch (vref) { - case SYSTEM_VOLTAGE_REFERENCE_TEMPSENSE: - SYSCTRL->VREF.reg &= ~SYSCTRL_VREF_TSEN; - break; - - case SYSTEM_VOLTAGE_REFERENCE_BANDGAP: - SYSCTRL->VREF.reg &= ~SYSCTRL_VREF_BGOUTEN; - break; - - default: - Assert(false); - return; - } -} - -/** - * @} - */ - - -/** - * \name Device Sleep Control - * @{ - */ - -/** - * \brief Set the sleep mode of the device - * - * Sets the sleep mode of the device; the configured sleep mode will be entered - * upon the next call of the \ref system_sleep() function. - * - * For an overview of which systems are disabled in sleep for the different - * sleep modes, see \ref asfdoc_sam0_system_module_overview_sleep_mode. - * - * \param[in] sleep_mode Sleep mode to configure for the next sleep operation - * - * \retval STATUS_OK Operation completed successfully - * \retval STATUS_ERR_INVALID_ARG The requested sleep mode was invalid or not - * available - */ -static inline enum status_code system_set_sleepmode( - const enum system_sleepmode sleep_mode) -{ -#if (SAMD20 || SAMD21) - /* Errata: Make sure that the Flash does not power all the way down - * when in sleep mode. */ - NVMCTRL->CTRLB.bit.SLEEPPRM = NVMCTRL_CTRLB_SLEEPPRM_DISABLED_Val; -#endif - - switch (sleep_mode) { - case SYSTEM_SLEEPMODE_IDLE_0: - case SYSTEM_SLEEPMODE_IDLE_1: - case SYSTEM_SLEEPMODE_IDLE_2: - SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk; - PM->SLEEP.reg = sleep_mode; - break; - - case SYSTEM_SLEEPMODE_STANDBY: - SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; - break; - - default: - return STATUS_ERR_INVALID_ARG; - } - - return STATUS_OK; -} - -/** - * \brief Put the system to sleep waiting for interrupt - * - * Executes a device DSB (Data Synchronization Barrier) instruction to ensure - * all ongoing memory accesses have completed, then a WFI (Wait For Interrupt) - * instruction to place the device into the sleep mode specified by - * \ref system_set_sleepmode until woken by an interrupt. - */ -static inline void system_sleep(void) -{ - __DSB(); - __WFI(); -} - -/** - * @} - */ - -/** @} */ -#ifdef __cplusplus -} -#endif - -#endif /* POWER_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h deleted file mode 100644 index 4447927..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/mrecursion.h +++ /dev/null @@ -1,581 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef _MRECURSION_H_ -#define _MRECURSION_H_ - -/** - * \defgroup group_sam0_utils_mrecursion Preprocessor - Macro Recursion - * - * \ingroup group_sam0_utils - * - * @{ - */ - -#include "preprocessor.h" - -#define DEC_256 255 -#define DEC_255 254 -#define DEC_254 253 -#define DEC_253 252 -#define DEC_252 251 -#define DEC_251 250 -#define DEC_250 249 -#define DEC_249 248 -#define DEC_248 247 -#define DEC_247 246 -#define DEC_246 245 -#define DEC_245 244 -#define DEC_244 243 -#define DEC_243 242 -#define DEC_242 241 -#define DEC_241 240 -#define DEC_240 239 -#define DEC_239 238 -#define DEC_238 237 -#define DEC_237 236 -#define DEC_236 235 -#define DEC_235 234 -#define DEC_234 233 -#define DEC_233 232 -#define DEC_232 231 -#define DEC_231 230 -#define DEC_230 229 -#define DEC_229 228 -#define DEC_228 227 -#define DEC_227 226 -#define DEC_226 225 -#define DEC_225 224 -#define DEC_224 223 -#define DEC_223 222 -#define DEC_222 221 -#define DEC_221 220 -#define DEC_220 219 -#define DEC_219 218 -#define DEC_218 217 -#define DEC_217 216 -#define DEC_216 215 -#define DEC_215 214 -#define DEC_214 213 -#define DEC_213 212 -#define DEC_212 211 -#define DEC_211 210 -#define DEC_210 209 -#define DEC_209 208 -#define DEC_208 207 -#define DEC_207 206 -#define DEC_206 205 -#define DEC_205 204 -#define DEC_204 203 -#define DEC_203 202 -#define DEC_202 201 -#define DEC_201 200 -#define DEC_200 199 -#define DEC_199 198 -#define DEC_198 197 -#define DEC_197 196 -#define DEC_196 195 -#define DEC_195 194 -#define DEC_194 193 -#define DEC_193 192 -#define DEC_192 191 -#define DEC_191 190 -#define DEC_190 189 -#define DEC_189 188 -#define DEC_188 187 -#define DEC_187 186 -#define DEC_186 185 -#define DEC_185 184 -#define DEC_184 183 -#define DEC_183 182 -#define DEC_182 181 -#define DEC_181 180 -#define DEC_180 179 -#define DEC_179 178 -#define DEC_178 177 -#define DEC_177 176 -#define DEC_176 175 -#define DEC_175 174 -#define DEC_174 173 -#define DEC_173 172 -#define DEC_172 171 -#define DEC_171 170 -#define DEC_170 169 -#define DEC_169 168 -#define DEC_168 167 -#define DEC_167 166 -#define DEC_166 165 -#define DEC_165 164 -#define DEC_164 163 -#define DEC_163 162 -#define DEC_162 161 -#define DEC_161 160 -#define DEC_160 159 -#define DEC_159 158 -#define DEC_158 157 -#define DEC_157 156 -#define DEC_156 155 -#define DEC_155 154 -#define DEC_154 153 -#define DEC_153 152 -#define DEC_152 151 -#define DEC_151 150 -#define DEC_150 149 -#define DEC_149 148 -#define DEC_148 147 -#define DEC_147 146 -#define DEC_146 145 -#define DEC_145 144 -#define DEC_144 143 -#define DEC_143 142 -#define DEC_142 141 -#define DEC_141 140 -#define DEC_140 139 -#define DEC_139 138 -#define DEC_138 137 -#define DEC_137 136 -#define DEC_136 135 -#define DEC_135 134 -#define DEC_134 133 -#define DEC_133 132 -#define DEC_132 131 -#define DEC_131 130 -#define DEC_130 129 -#define DEC_129 128 -#define DEC_128 127 -#define DEC_127 126 -#define DEC_126 125 -#define DEC_125 124 -#define DEC_124 123 -#define DEC_123 122 -#define DEC_122 121 -#define DEC_121 120 -#define DEC_120 119 -#define DEC_119 118 -#define DEC_118 117 -#define DEC_117 116 -#define DEC_116 115 -#define DEC_115 114 -#define DEC_114 113 -#define DEC_113 112 -#define DEC_112 111 -#define DEC_111 110 -#define DEC_110 109 -#define DEC_109 108 -#define DEC_108 107 -#define DEC_107 106 -#define DEC_106 105 -#define DEC_105 104 -#define DEC_104 103 -#define DEC_103 102 -#define DEC_102 101 -#define DEC_101 100 -#define DEC_100 99 -#define DEC_99 98 -#define DEC_98 97 -#define DEC_97 96 -#define DEC_96 95 -#define DEC_95 94 -#define DEC_94 93 -#define DEC_93 92 -#define DEC_92 91 -#define DEC_91 90 -#define DEC_90 89 -#define DEC_89 88 -#define DEC_88 87 -#define DEC_87 86 -#define DEC_86 85 -#define DEC_85 84 -#define DEC_84 83 -#define DEC_83 82 -#define DEC_82 81 -#define DEC_81 80 -#define DEC_80 79 -#define DEC_79 78 -#define DEC_78 77 -#define DEC_77 76 -#define DEC_76 75 -#define DEC_75 74 -#define DEC_74 73 -#define DEC_73 72 -#define DEC_72 71 -#define DEC_71 70 -#define DEC_70 69 -#define DEC_69 68 -#define DEC_68 67 -#define DEC_67 66 -#define DEC_66 65 -#define DEC_65 64 -#define DEC_64 63 -#define DEC_63 62 -#define DEC_62 61 -#define DEC_61 60 -#define DEC_60 59 -#define DEC_59 58 -#define DEC_58 57 -#define DEC_57 56 -#define DEC_56 55 -#define DEC_55 54 -#define DEC_54 53 -#define DEC_53 52 -#define DEC_52 51 -#define DEC_51 50 -#define DEC_50 49 -#define DEC_49 48 -#define DEC_48 47 -#define DEC_47 46 -#define DEC_46 45 -#define DEC_45 44 -#define DEC_44 43 -#define DEC_43 42 -#define DEC_42 41 -#define DEC_41 40 -#define DEC_40 39 -#define DEC_39 38 -#define DEC_38 37 -#define DEC_37 36 -#define DEC_36 35 -#define DEC_35 34 -#define DEC_34 33 -#define DEC_33 32 -#define DEC_32 31 -#define DEC_31 30 -#define DEC_30 29 -#define DEC_29 28 -#define DEC_28 27 -#define DEC_27 26 -#define DEC_26 25 -#define DEC_25 24 -#define DEC_24 23 -#define DEC_23 22 -#define DEC_22 21 -#define DEC_21 20 -#define DEC_20 19 -#define DEC_19 18 -#define DEC_18 17 -#define DEC_17 16 -#define DEC_16 15 -#define DEC_15 14 -#define DEC_14 13 -#define DEC_13 12 -#define DEC_12 11 -#define DEC_11 10 -#define DEC_10 9 -#define DEC_9 8 -#define DEC_8 7 -#define DEC_7 6 -#define DEC_6 5 -#define DEC_5 4 -#define DEC_4 3 -#define DEC_3 2 -#define DEC_2 1 -#define DEC_1 0 -#define DEC_(n) DEC_##n - - -/** Maximal number of repetitions supported by MRECURSION. */ -#define MRECURSION_LIMIT 256 - -/** \brief Macro recursion. - * - * This macro represents a horizontal repetition construct. - * - * \param[in] count The number of repetitious calls to macro. Valid values - * range from 0 to MRECURSION_LIMIT. - * \param[in] macro A binary operation of the form macro(data, n). This macro - * is expanded by MRECURSION with the current repetition number - * and the auxiliary data argument. - * \param[in] data A recursive threshold, building on this to decline by times - * defined with param count. - * - * \return macro(data-count+1,0) macro(data-count+2,1)...macro(data,count-1) - */ -#define MRECURSION(count, macro, data) TPASTE2(MRECURSION, count) (macro, data) - -#define MRECURSION0( macro, data) -#define MRECURSION1( macro, data) MRECURSION0( macro, DEC_(data)) macro(data, 0) -#define MRECURSION2( macro, data) MRECURSION1( macro, DEC_(data)) macro(data, 1) -#define MRECURSION3( macro, data) MRECURSION2( macro, DEC_(data)) macro(data, 2) -#define MRECURSION4( macro, data) MRECURSION3( macro, DEC_(data)) macro(data, 3) -#define MRECURSION5( macro, data) MRECURSION4( macro, DEC_(data)) macro(data, 4) -#define MRECURSION6( macro, data) MRECURSION5( macro, DEC_(data)) macro(data, 5) -#define MRECURSION7( macro, data) MRECURSION6( macro, DEC_(data)) macro(data, 6) -#define MRECURSION8( macro, data) MRECURSION7( macro, DEC_(data)) macro(data, 7) -#define MRECURSION9( macro, data) MRECURSION8( macro, DEC_(data)) macro(data, 8) -#define MRECURSION10( macro, data) MRECURSION9( macro, DEC_(data)) macro(data, 9) -#define MRECURSION11( macro, data) MRECURSION10( macro, DEC_(data)) macro(data, 10) -#define MRECURSION12( macro, data) MRECURSION11( macro, DEC_(data)) macro(data, 11) -#define MRECURSION13( macro, data) MRECURSION12( macro, DEC_(data)) macro(data, 12) -#define MRECURSION14( macro, data) MRECURSION13( macro, DEC_(data)) macro(data, 13) -#define MRECURSION15( macro, data) MRECURSION14( macro, DEC_(data)) macro(data, 14) -#define MRECURSION16( macro, data) MRECURSION15( macro, DEC_(data)) macro(data, 15) -#define MRECURSION17( macro, data) MRECURSION16( macro, DEC_(data)) macro(data, 16) -#define MRECURSION18( macro, data) MRECURSION17( macro, DEC_(data)) macro(data, 17) -#define MRECURSION19( macro, data) MRECURSION18( macro, DEC_(data)) macro(data, 18) -#define MRECURSION20( macro, data) MRECURSION19( macro, DEC_(data)) macro(data, 19) -#define MRECURSION21( macro, data) MRECURSION20( macro, DEC_(data)) macro(data, 20) -#define MRECURSION22( macro, data) MRECURSION21( macro, DEC_(data)) macro(data, 21) -#define MRECURSION23( macro, data) MRECURSION22( macro, DEC_(data)) macro(data, 22) -#define MRECURSION24( macro, data) MRECURSION23( macro, DEC_(data)) macro(data, 23) -#define MRECURSION25( macro, data) MRECURSION24( macro, DEC_(data)) macro(data, 24) -#define MRECURSION26( macro, data) MRECURSION25( macro, DEC_(data)) macro(data, 25) -#define MRECURSION27( macro, data) MRECURSION26( macro, DEC_(data)) macro(data, 26) -#define MRECURSION28( macro, data) MRECURSION27( macro, DEC_(data)) macro(data, 27) -#define MRECURSION29( macro, data) MRECURSION28( macro, DEC_(data)) macro(data, 28) -#define MRECURSION30( macro, data) MRECURSION29( macro, DEC_(data)) macro(data, 29) -#define MRECURSION31( macro, data) MRECURSION30( macro, DEC_(data)) macro(data, 30) -#define MRECURSION32( macro, data) MRECURSION31( macro, DEC_(data)) macro(data, 31) -#define MRECURSION33( macro, data) MRECURSION32( macro, DEC_(data)) macro(data, 32) -#define MRECURSION34( macro, data) MRECURSION33( macro, DEC_(data)) macro(data, 33) -#define MRECURSION35( macro, data) MRECURSION34( macro, DEC_(data)) macro(data, 34) -#define MRECURSION36( macro, data) MRECURSION35( macro, DEC_(data)) macro(data, 35) -#define MRECURSION37( macro, data) MRECURSION36( macro, DEC_(data)) macro(data, 36) -#define MRECURSION38( macro, data) MRECURSION37( macro, DEC_(data)) macro(data, 37) -#define MRECURSION39( macro, data) MRECURSION38( macro, DEC_(data)) macro(data, 38) -#define MRECURSION40( macro, data) MRECURSION39( macro, DEC_(data)) macro(data, 39) -#define MRECURSION41( macro, data) MRECURSION40( macro, DEC_(data)) macro(data, 40) -#define MRECURSION42( macro, data) MRECURSION41( macro, DEC_(data)) macro(data, 41) -#define MRECURSION43( macro, data) MRECURSION42( macro, DEC_(data)) macro(data, 42) -#define MRECURSION44( macro, data) MRECURSION43( macro, DEC_(data)) macro(data, 43) -#define MRECURSION45( macro, data) MRECURSION44( macro, DEC_(data)) macro(data, 44) -#define MRECURSION46( macro, data) MRECURSION45( macro, DEC_(data)) macro(data, 45) -#define MRECURSION47( macro, data) MRECURSION46( macro, DEC_(data)) macro(data, 46) -#define MRECURSION48( macro, data) MRECURSION47( macro, DEC_(data)) macro(data, 47) -#define MRECURSION49( macro, data) MRECURSION48( macro, DEC_(data)) macro(data, 48) -#define MRECURSION50( macro, data) MRECURSION49( macro, DEC_(data)) macro(data, 49) -#define MRECURSION51( macro, data) MRECURSION50( macro, DEC_(data)) macro(data, 50) -#define MRECURSION52( macro, data) MRECURSION51( macro, DEC_(data)) macro(data, 51) -#define MRECURSION53( macro, data) MRECURSION52( macro, DEC_(data)) macro(data, 52) -#define MRECURSION54( macro, data) MRECURSION53( macro, DEC_(data)) macro(data, 53) -#define MRECURSION55( macro, data) MRECURSION54( macro, DEC_(data)) macro(data, 54) -#define MRECURSION56( macro, data) MRECURSION55( macro, DEC_(data)) macro(data, 55) -#define MRECURSION57( macro, data) MRECURSION56( macro, DEC_(data)) macro(data, 56) -#define MRECURSION58( macro, data) MRECURSION57( macro, DEC_(data)) macro(data, 57) -#define MRECURSION59( macro, data) MRECURSION58( macro, DEC_(data)) macro(data, 58) -#define MRECURSION60( macro, data) MRECURSION59( macro, DEC_(data)) macro(data, 59) -#define MRECURSION61( macro, data) MRECURSION60( macro, DEC_(data)) macro(data, 60) -#define MRECURSION62( macro, data) MRECURSION61( macro, DEC_(data)) macro(data, 61) -#define MRECURSION63( macro, data) MRECURSION62( macro, DEC_(data)) macro(data, 62) -#define MRECURSION64( macro, data) MRECURSION63( macro, DEC_(data)) macro(data, 63) -#define MRECURSION65( macro, data) MRECURSION64( macro, DEC_(data)) macro(data, 64) -#define MRECURSION66( macro, data) MRECURSION65( macro, DEC_(data)) macro(data, 65) -#define MRECURSION67( macro, data) MRECURSION66( macro, DEC_(data)) macro(data, 66) -#define MRECURSION68( macro, data) MRECURSION67( macro, DEC_(data)) macro(data, 67) -#define MRECURSION69( macro, data) MRECURSION68( macro, DEC_(data)) macro(data, 68) -#define MRECURSION70( macro, data) MRECURSION69( macro, DEC_(data)) macro(data, 69) -#define MRECURSION71( macro, data) MRECURSION70( macro, DEC_(data)) macro(data, 70) -#define MRECURSION72( macro, data) MRECURSION71( macro, DEC_(data)) macro(data, 71) -#define MRECURSION73( macro, data) MRECURSION72( macro, DEC_(data)) macro(data, 72) -#define MRECURSION74( macro, data) MRECURSION73( macro, DEC_(data)) macro(data, 73) -#define MRECURSION75( macro, data) MRECURSION74( macro, DEC_(data)) macro(data, 74) -#define MRECURSION76( macro, data) MRECURSION75( macro, DEC_(data)) macro(data, 75) -#define MRECURSION77( macro, data) MRECURSION76( macro, DEC_(data)) macro(data, 76) -#define MRECURSION78( macro, data) MRECURSION77( macro, DEC_(data)) macro(data, 77) -#define MRECURSION79( macro, data) MRECURSION78( macro, DEC_(data)) macro(data, 78) -#define MRECURSION80( macro, data) MRECURSION79( macro, DEC_(data)) macro(data, 79) -#define MRECURSION81( macro, data) MRECURSION80( macro, DEC_(data)) macro(data, 80) -#define MRECURSION82( macro, data) MRECURSION81( macro, DEC_(data)) macro(data, 81) -#define MRECURSION83( macro, data) MRECURSION82( macro, DEC_(data)) macro(data, 82) -#define MRECURSION84( macro, data) MRECURSION83( macro, DEC_(data)) macro(data, 83) -#define MRECURSION85( macro, data) MRECURSION84( macro, DEC_(data)) macro(data, 84) -#define MRECURSION86( macro, data) MRECURSION85( macro, DEC_(data)) macro(data, 85) -#define MRECURSION87( macro, data) MRECURSION86( macro, DEC_(data)) macro(data, 86) -#define MRECURSION88( macro, data) MRECURSION87( macro, DEC_(data)) macro(data, 87) -#define MRECURSION89( macro, data) MRECURSION88( macro, DEC_(data)) macro(data, 88) -#define MRECURSION90( macro, data) MRECURSION89( macro, DEC_(data)) macro(data, 89) -#define MRECURSION91( macro, data) MRECURSION90( macro, DEC_(data)) macro(data, 90) -#define MRECURSION92( macro, data) MRECURSION91( macro, DEC_(data)) macro(data, 91) -#define MRECURSION93( macro, data) MRECURSION92( macro, DEC_(data)) macro(data, 92) -#define MRECURSION94( macro, data) MRECURSION93( macro, DEC_(data)) macro(data, 93) -#define MRECURSION95( macro, data) MRECURSION94( macro, DEC_(data)) macro(data, 94) -#define MRECURSION96( macro, data) MRECURSION95( macro, DEC_(data)) macro(data, 95) -#define MRECURSION97( macro, data) MRECURSION96( macro, DEC_(data)) macro(data, 96) -#define MRECURSION98( macro, data) MRECURSION97( macro, DEC_(data)) macro(data, 97) -#define MRECURSION99( macro, data) MRECURSION98( macro, DEC_(data)) macro(data, 98) -#define MRECURSION100(macro, data) MRECURSION99( macro, DEC_(data)) macro(data, 99) -#define MRECURSION101(macro, data) MRECURSION100( macro, DEC_(data)) macro(data, 100) -#define MRECURSION102(macro, data) MRECURSION101( macro, DEC_(data)) macro(data, 101) -#define MRECURSION103(macro, data) MRECURSION102( macro, DEC_(data)) macro(data, 102) -#define MRECURSION104(macro, data) MRECURSION103( macro, DEC_(data)) macro(data, 103) -#define MRECURSION105(macro, data) MRECURSION104( macro, DEC_(data)) macro(data, 104) -#define MRECURSION106(macro, data) MRECURSION105( macro, DEC_(data)) macro(data, 105) -#define MRECURSION107(macro, data) MRECURSION106( macro, DEC_(data)) macro(data, 106) -#define MRECURSION108(macro, data) MRECURSION107( macro, DEC_(data)) macro(data, 107) -#define MRECURSION109(macro, data) MRECURSION108( macro, DEC_(data)) macro(data, 108) -#define MRECURSION110(macro, data) MRECURSION109( macro, DEC_(data)) macro(data, 109) -#define MRECURSION111(macro, data) MRECURSION110( macro, DEC_(data)) macro(data, 110) -#define MRECURSION112(macro, data) MRECURSION111( macro, DEC_(data)) macro(data, 111) -#define MRECURSION113(macro, data) MRECURSION112( macro, DEC_(data)) macro(data, 112) -#define MRECURSION114(macro, data) MRECURSION113( macro, DEC_(data)) macro(data, 113) -#define MRECURSION115(macro, data) MRECURSION114( macro, DEC_(data)) macro(data, 114) -#define MRECURSION116(macro, data) MRECURSION115( macro, DEC_(data)) macro(data, 115) -#define MRECURSION117(macro, data) MRECURSION116( macro, DEC_(data)) macro(data, 116) -#define MRECURSION118(macro, data) MRECURSION117( macro, DEC_(data)) macro(data, 117) -#define MRECURSION119(macro, data) MRECURSION118( macro, DEC_(data)) macro(data, 118) -#define MRECURSION120(macro, data) MRECURSION119( macro, DEC_(data)) macro(data, 119) -#define MRECURSION121(macro, data) MRECURSION120( macro, DEC_(data)) macro(data, 120) -#define MRECURSION122(macro, data) MRECURSION121( macro, DEC_(data)) macro(data, 121) -#define MRECURSION123(macro, data) MRECURSION122( macro, DEC_(data)) macro(data, 122) -#define MRECURSION124(macro, data) MRECURSION123( macro, DEC_(data)) macro(data, 123) -#define MRECURSION125(macro, data) MRECURSION124( macro, DEC_(data)) macro(data, 124) -#define MRECURSION126(macro, data) MRECURSION125( macro, DEC_(data)) macro(data, 125) -#define MRECURSION127(macro, data) MRECURSION126( macro, DEC_(data)) macro(data, 126) -#define MRECURSION128(macro, data) MRECURSION127( macro, DEC_(data)) macro(data, 127) -#define MRECURSION129(macro, data) MRECURSION128( macro, DEC_(data)) macro(data, 128) -#define MRECURSION130(macro, data) MRECURSION129( macro, DEC_(data)) macro(data, 129) -#define MRECURSION131(macro, data) MRECURSION130( macro, DEC_(data)) macro(data, 130) -#define MRECURSION132(macro, data) MRECURSION131( macro, DEC_(data)) macro(data, 131) -#define MRECURSION133(macro, data) MRECURSION132( macro, DEC_(data)) macro(data, 132) -#define MRECURSION134(macro, data) MRECURSION133( macro, DEC_(data)) macro(data, 133) -#define MRECURSION135(macro, data) MRECURSION134( macro, DEC_(data)) macro(data, 134) -#define MRECURSION136(macro, data) MRECURSION135( macro, DEC_(data)) macro(data, 135) -#define MRECURSION137(macro, data) MRECURSION136( macro, DEC_(data)) macro(data, 136) -#define MRECURSION138(macro, data) MRECURSION137( macro, DEC_(data)) macro(data, 137) -#define MRECURSION139(macro, data) MRECURSION138( macro, DEC_(data)) macro(data, 138) -#define MRECURSION140(macro, data) MRECURSION139( macro, DEC_(data)) macro(data, 139) -#define MRECURSION141(macro, data) MRECURSION140( macro, DEC_(data)) macro(data, 140) -#define MRECURSION142(macro, data) MRECURSION141( macro, DEC_(data)) macro(data, 141) -#define MRECURSION143(macro, data) MRECURSION142( macro, DEC_(data)) macro(data, 142) -#define MRECURSION144(macro, data) MRECURSION143( macro, DEC_(data)) macro(data, 143) -#define MRECURSION145(macro, data) MRECURSION144( macro, DEC_(data)) macro(data, 144) -#define MRECURSION146(macro, data) MRECURSION145( macro, DEC_(data)) macro(data, 145) -#define MRECURSION147(macro, data) MRECURSION146( macro, DEC_(data)) macro(data, 146) -#define MRECURSION148(macro, data) MRECURSION147( macro, DEC_(data)) macro(data, 147) -#define MRECURSION149(macro, data) MRECURSION148( macro, DEC_(data)) macro(data, 148) -#define MRECURSION150(macro, data) MRECURSION149( macro, DEC_(data)) macro(data, 149) -#define MRECURSION151(macro, data) MRECURSION150( macro, DEC_(data)) macro(data, 150) -#define MRECURSION152(macro, data) MRECURSION151( macro, DEC_(data)) macro(data, 151) -#define MRECURSION153(macro, data) MRECURSION152( macro, DEC_(data)) macro(data, 152) -#define MRECURSION154(macro, data) MRECURSION153( macro, DEC_(data)) macro(data, 153) -#define MRECURSION155(macro, data) MRECURSION154( macro, DEC_(data)) macro(data, 154) -#define MRECURSION156(macro, data) MRECURSION155( macro, DEC_(data)) macro(data, 155) -#define MRECURSION157(macro, data) MRECURSION156( macro, DEC_(data)) macro(data, 156) -#define MRECURSION158(macro, data) MRECURSION157( macro, DEC_(data)) macro(data, 157) -#define MRECURSION159(macro, data) MRECURSION158( macro, DEC_(data)) macro(data, 158) -#define MRECURSION160(macro, data) MRECURSION159( macro, DEC_(data)) macro(data, 159) -#define MRECURSION161(macro, data) MRECURSION160( macro, DEC_(data)) macro(data, 160) -#define MRECURSION162(macro, data) MRECURSION161( macro, DEC_(data)) macro(data, 161) -#define MRECURSION163(macro, data) MRECURSION162( macro, DEC_(data)) macro(data, 162) -#define MRECURSION164(macro, data) MRECURSION163( macro, DEC_(data)) macro(data, 163) -#define MRECURSION165(macro, data) MRECURSION164( macro, DEC_(data)) macro(data, 164) -#define MRECURSION166(macro, data) MRECURSION165( macro, DEC_(data)) macro(data, 165) -#define MRECURSION167(macro, data) MRECURSION166( macro, DEC_(data)) macro(data, 166) -#define MRECURSION168(macro, data) MRECURSION167( macro, DEC_(data)) macro(data, 167) -#define MRECURSION169(macro, data) MRECURSION168( macro, DEC_(data)) macro(data, 168) -#define MRECURSION170(macro, data) MRECURSION169( macro, DEC_(data)) macro(data, 169) -#define MRECURSION171(macro, data) MRECURSION170( macro, DEC_(data)) macro(data, 170) -#define MRECURSION172(macro, data) MRECURSION171( macro, DEC_(data)) macro(data, 171) -#define MRECURSION173(macro, data) MRECURSION172( macro, DEC_(data)) macro(data, 172) -#define MRECURSION174(macro, data) MRECURSION173( macro, DEC_(data)) macro(data, 173) -#define MRECURSION175(macro, data) MRECURSION174( macro, DEC_(data)) macro(data, 174) -#define MRECURSION176(macro, data) MRECURSION175( macro, DEC_(data)) macro(data, 175) -#define MRECURSION177(macro, data) MRECURSION176( macro, DEC_(data)) macro(data, 176) -#define MRECURSION178(macro, data) MRECURSION177( macro, DEC_(data)) macro(data, 177) -#define MRECURSION179(macro, data) MRECURSION178( macro, DEC_(data)) macro(data, 178) -#define MRECURSION180(macro, data) MRECURSION179( macro, DEC_(data)) macro(data, 179) -#define MRECURSION181(macro, data) MRECURSION180( macro, DEC_(data)) macro(data, 180) -#define MRECURSION182(macro, data) MRECURSION181( macro, DEC_(data)) macro(data, 181) -#define MRECURSION183(macro, data) MRECURSION182( macro, DEC_(data)) macro(data, 182) -#define MRECURSION184(macro, data) MRECURSION183( macro, DEC_(data)) macro(data, 183) -#define MRECURSION185(macro, data) MRECURSION184( macro, DEC_(data)) macro(data, 184) -#define MRECURSION186(macro, data) MRECURSION185( macro, DEC_(data)) macro(data, 185) -#define MRECURSION187(macro, data) MRECURSION186( macro, DEC_(data)) macro(data, 186) -#define MRECURSION188(macro, data) MRECURSION187( macro, DEC_(data)) macro(data, 187) -#define MRECURSION189(macro, data) MRECURSION188( macro, DEC_(data)) macro(data, 188) -#define MRECURSION190(macro, data) MRECURSION189( macro, DEC_(data)) macro(data, 189) -#define MRECURSION191(macro, data) MRECURSION190( macro, DEC_(data)) macro(data, 190) -#define MRECURSION192(macro, data) MRECURSION191( macro, DEC_(data)) macro(data, 191) -#define MRECURSION193(macro, data) MRECURSION192( macro, DEC_(data)) macro(data, 192) -#define MRECURSION194(macro, data) MRECURSION193( macro, DEC_(data)) macro(data, 193) -#define MRECURSION195(macro, data) MRECURSION194( macro, DEC_(data)) macro(data, 194) -#define MRECURSION196(macro, data) MRECURSION195( macro, DEC_(data)) macro(data, 195) -#define MRECURSION197(macro, data) MRECURSION196( macro, DEC_(data)) macro(data, 196) -#define MRECURSION198(macro, data) MRECURSION197( macro, DEC_(data)) macro(data, 197) -#define MRECURSION199(macro, data) MRECURSION198( macro, DEC_(data)) macro(data, 198) -#define MRECURSION200(macro, data) MRECURSION199( macro, DEC_(data)) macro(data, 199) -#define MRECURSION201(macro, data) MRECURSION200( macro, DEC_(data)) macro(data, 200) -#define MRECURSION202(macro, data) MRECURSION201( macro, DEC_(data)) macro(data, 201) -#define MRECURSION203(macro, data) MRECURSION202( macro, DEC_(data)) macro(data, 202) -#define MRECURSION204(macro, data) MRECURSION203( macro, DEC_(data)) macro(data, 203) -#define MRECURSION205(macro, data) MRECURSION204( macro, DEC_(data)) macro(data, 204) -#define MRECURSION206(macro, data) MRECURSION205( macro, DEC_(data)) macro(data, 205) -#define MRECURSION207(macro, data) MRECURSION206( macro, DEC_(data)) macro(data, 206) -#define MRECURSION208(macro, data) MRECURSION207( macro, DEC_(data)) macro(data, 207) -#define MRECURSION209(macro, data) MRECURSION208( macro, DEC_(data)) macro(data, 208) -#define MRECURSION210(macro, data) MRECURSION209( macro, DEC_(data)) macro(data, 209) -#define MRECURSION211(macro, data) MRECURSION210( macro, DEC_(data)) macro(data, 210) -#define MRECURSION212(macro, data) MRECURSION211( macro, DEC_(data)) macro(data, 211) -#define MRECURSION213(macro, data) MRECURSION212( macro, DEC_(data)) macro(data, 212) -#define MRECURSION214(macro, data) MRECURSION213( macro, DEC_(data)) macro(data, 213) -#define MRECURSION215(macro, data) MRECURSION214( macro, DEC_(data)) macro(data, 214) -#define MRECURSION216(macro, data) MRECURSION215( macro, DEC_(data)) macro(data, 215) -#define MRECURSION217(macro, data) MRECURSION216( macro, DEC_(data)) macro(data, 216) -#define MRECURSION218(macro, data) MRECURSION217( macro, DEC_(data)) macro(data, 217) -#define MRECURSION219(macro, data) MRECURSION218( macro, DEC_(data)) macro(data, 218) -#define MRECURSION220(macro, data) MRECURSION219( macro, DEC_(data)) macro(data, 219) -#define MRECURSION221(macro, data) MRECURSION220( macro, DEC_(data)) macro(data, 220) -#define MRECURSION222(macro, data) MRECURSION221( macro, DEC_(data)) macro(data, 221) -#define MRECURSION223(macro, data) MRECURSION222( macro, DEC_(data)) macro(data, 222) -#define MRECURSION224(macro, data) MRECURSION223( macro, DEC_(data)) macro(data, 223) -#define MRECURSION225(macro, data) MRECURSION224( macro, DEC_(data)) macro(data, 224) -#define MRECURSION226(macro, data) MRECURSION225( macro, DEC_(data)) macro(data, 225) -#define MRECURSION227(macro, data) MRECURSION226( macro, DEC_(data)) macro(data, 226) -#define MRECURSION228(macro, data) MRECURSION227( macro, DEC_(data)) macro(data, 227) -#define MRECURSION229(macro, data) MRECURSION228( macro, DEC_(data)) macro(data, 228) -#define MRECURSION230(macro, data) MRECURSION229( macro, DEC_(data)) macro(data, 229) -#define MRECURSION231(macro, data) MRECURSION230( macro, DEC_(data)) macro(data, 230) -#define MRECURSION232(macro, data) MRECURSION231( macro, DEC_(data)) macro(data, 231) -#define MRECURSION233(macro, data) MRECURSION232( macro, DEC_(data)) macro(data, 232) -#define MRECURSION234(macro, data) MRECURSION233( macro, DEC_(data)) macro(data, 233) -#define MRECURSION235(macro, data) MRECURSION234( macro, DEC_(data)) macro(data, 234) -#define MRECURSION236(macro, data) MRECURSION235( macro, DEC_(data)) macro(data, 235) -#define MRECURSION237(macro, data) MRECURSION236( macro, DEC_(data)) macro(data, 236) -#define MRECURSION238(macro, data) MRECURSION237( macro, DEC_(data)) macro(data, 237) -#define MRECURSION239(macro, data) MRECURSION238( macro, DEC_(data)) macro(data, 238) -#define MRECURSION240(macro, data) MRECURSION239( macro, DEC_(data)) macro(data, 239) -#define MRECURSION241(macro, data) MRECURSION240( macro, DEC_(data)) macro(data, 240) -#define MRECURSION242(macro, data) MRECURSION241( macro, DEC_(data)) macro(data, 241) -#define MRECURSION243(macro, data) MRECURSION242( macro, DEC_(data)) macro(data, 242) -#define MRECURSION244(macro, data) MRECURSION243( macro, DEC_(data)) macro(data, 243) -#define MRECURSION245(macro, data) MRECURSION244( macro, DEC_(data)) macro(data, 244) -#define MRECURSION246(macro, data) MRECURSION245( macro, DEC_(data)) macro(data, 245) -#define MRECURSION247(macro, data) MRECURSION246( macro, DEC_(data)) macro(data, 246) -#define MRECURSION248(macro, data) MRECURSION247( macro, DEC_(data)) macro(data, 247) -#define MRECURSION249(macro, data) MRECURSION248( macro, DEC_(data)) macro(data, 248) -#define MRECURSION250(macro, data) MRECURSION249( macro, DEC_(data)) macro(data, 249) -#define MRECURSION251(macro, data) MRECURSION250( macro, DEC_(data)) macro(data, 250) -#define MRECURSION252(macro, data) MRECURSION251( macro, DEC_(data)) macro(data, 251) -#define MRECURSION253(macro, data) MRECURSION252( macro, DEC_(data)) macro(data, 252) -#define MRECURSION254(macro, data) MRECURSION253( macro, DEC_(data)) macro(data, 253) -#define MRECURSION255(macro, data) MRECURSION254( macro, DEC_(data)) macro(data, 254) -#define MRECURSION256(macro, data) MRECURSION255( macro, DEC_(data)) macro(data, 255) - -/** @} */ - -#endif /* _MRECURSION_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h deleted file mode 100644 index fb820d5..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/mrepeat.h +++ /dev/null @@ -1,321 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef _MREPEAT_H_ -#define _MREPEAT_H_ - -/** - * \defgroup group_sam0_utils_mrepeat Preprocessor - Macro Repeat - * - * \ingroup group_sam0_utils - * - * @{ - */ - -#include "preprocessor.h" - -/** Maximal number of repetitions supported by MREPEAT. */ -#define MREPEAT_LIMIT 256 - -/** \brief Macro repeat. - * - * This macro represents a horizontal repetition construct. - * - * \param[in] count The number of repetitious calls to macro. Valid values - * range from 0 to MREPEAT_LIMIT. - * \param[in] macro A binary operation of the form macro(n, data). This macro - * is expanded by MREPEAT with the current repetition number - * and the auxiliary data argument. - * \param[in] data Auxiliary data passed to macro. - * - * \return macro(0, data) macro(1, data) ... macro(count - 1, data) - */ -#define MREPEAT(count, macro, data) TPASTE2(MREPEAT, count) (macro, data) - -#define MREPEAT0( macro, data) -#define MREPEAT1( macro, data) MREPEAT0( macro, data) macro( 0, data) -#define MREPEAT2( macro, data) MREPEAT1( macro, data) macro( 1, data) -#define MREPEAT3( macro, data) MREPEAT2( macro, data) macro( 2, data) -#define MREPEAT4( macro, data) MREPEAT3( macro, data) macro( 3, data) -#define MREPEAT5( macro, data) MREPEAT4( macro, data) macro( 4, data) -#define MREPEAT6( macro, data) MREPEAT5( macro, data) macro( 5, data) -#define MREPEAT7( macro, data) MREPEAT6( macro, data) macro( 6, data) -#define MREPEAT8( macro, data) MREPEAT7( macro, data) macro( 7, data) -#define MREPEAT9( macro, data) MREPEAT8( macro, data) macro( 8, data) -#define MREPEAT10( macro, data) MREPEAT9( macro, data) macro( 9, data) -#define MREPEAT11( macro, data) MREPEAT10( macro, data) macro( 10, data) -#define MREPEAT12( macro, data) MREPEAT11( macro, data) macro( 11, data) -#define MREPEAT13( macro, data) MREPEAT12( macro, data) macro( 12, data) -#define MREPEAT14( macro, data) MREPEAT13( macro, data) macro( 13, data) -#define MREPEAT15( macro, data) MREPEAT14( macro, data) macro( 14, data) -#define MREPEAT16( macro, data) MREPEAT15( macro, data) macro( 15, data) -#define MREPEAT17( macro, data) MREPEAT16( macro, data) macro( 16, data) -#define MREPEAT18( macro, data) MREPEAT17( macro, data) macro( 17, data) -#define MREPEAT19( macro, data) MREPEAT18( macro, data) macro( 18, data) -#define MREPEAT20( macro, data) MREPEAT19( macro, data) macro( 19, data) -#define MREPEAT21( macro, data) MREPEAT20( macro, data) macro( 20, data) -#define MREPEAT22( macro, data) MREPEAT21( macro, data) macro( 21, data) -#define MREPEAT23( macro, data) MREPEAT22( macro, data) macro( 22, data) -#define MREPEAT24( macro, data) MREPEAT23( macro, data) macro( 23, data) -#define MREPEAT25( macro, data) MREPEAT24( macro, data) macro( 24, data) -#define MREPEAT26( macro, data) MREPEAT25( macro, data) macro( 25, data) -#define MREPEAT27( macro, data) MREPEAT26( macro, data) macro( 26, data) -#define MREPEAT28( macro, data) MREPEAT27( macro, data) macro( 27, data) -#define MREPEAT29( macro, data) MREPEAT28( macro, data) macro( 28, data) -#define MREPEAT30( macro, data) MREPEAT29( macro, data) macro( 29, data) -#define MREPEAT31( macro, data) MREPEAT30( macro, data) macro( 30, data) -#define MREPEAT32( macro, data) MREPEAT31( macro, data) macro( 31, data) -#define MREPEAT33( macro, data) MREPEAT32( macro, data) macro( 32, data) -#define MREPEAT34( macro, data) MREPEAT33( macro, data) macro( 33, data) -#define MREPEAT35( macro, data) MREPEAT34( macro, data) macro( 34, data) -#define MREPEAT36( macro, data) MREPEAT35( macro, data) macro( 35, data) -#define MREPEAT37( macro, data) MREPEAT36( macro, data) macro( 36, data) -#define MREPEAT38( macro, data) MREPEAT37( macro, data) macro( 37, data) -#define MREPEAT39( macro, data) MREPEAT38( macro, data) macro( 38, data) -#define MREPEAT40( macro, data) MREPEAT39( macro, data) macro( 39, data) -#define MREPEAT41( macro, data) MREPEAT40( macro, data) macro( 40, data) -#define MREPEAT42( macro, data) MREPEAT41( macro, data) macro( 41, data) -#define MREPEAT43( macro, data) MREPEAT42( macro, data) macro( 42, data) -#define MREPEAT44( macro, data) MREPEAT43( macro, data) macro( 43, data) -#define MREPEAT45( macro, data) MREPEAT44( macro, data) macro( 44, data) -#define MREPEAT46( macro, data) MREPEAT45( macro, data) macro( 45, data) -#define MREPEAT47( macro, data) MREPEAT46( macro, data) macro( 46, data) -#define MREPEAT48( macro, data) MREPEAT47( macro, data) macro( 47, data) -#define MREPEAT49( macro, data) MREPEAT48( macro, data) macro( 48, data) -#define MREPEAT50( macro, data) MREPEAT49( macro, data) macro( 49, data) -#define MREPEAT51( macro, data) MREPEAT50( macro, data) macro( 50, data) -#define MREPEAT52( macro, data) MREPEAT51( macro, data) macro( 51, data) -#define MREPEAT53( macro, data) MREPEAT52( macro, data) macro( 52, data) -#define MREPEAT54( macro, data) MREPEAT53( macro, data) macro( 53, data) -#define MREPEAT55( macro, data) MREPEAT54( macro, data) macro( 54, data) -#define MREPEAT56( macro, data) MREPEAT55( macro, data) macro( 55, data) -#define MREPEAT57( macro, data) MREPEAT56( macro, data) macro( 56, data) -#define MREPEAT58( macro, data) MREPEAT57( macro, data) macro( 57, data) -#define MREPEAT59( macro, data) MREPEAT58( macro, data) macro( 58, data) -#define MREPEAT60( macro, data) MREPEAT59( macro, data) macro( 59, data) -#define MREPEAT61( macro, data) MREPEAT60( macro, data) macro( 60, data) -#define MREPEAT62( macro, data) MREPEAT61( macro, data) macro( 61, data) -#define MREPEAT63( macro, data) MREPEAT62( macro, data) macro( 62, data) -#define MREPEAT64( macro, data) MREPEAT63( macro, data) macro( 63, data) -#define MREPEAT65( macro, data) MREPEAT64( macro, data) macro( 64, data) -#define MREPEAT66( macro, data) MREPEAT65( macro, data) macro( 65, data) -#define MREPEAT67( macro, data) MREPEAT66( macro, data) macro( 66, data) -#define MREPEAT68( macro, data) MREPEAT67( macro, data) macro( 67, data) -#define MREPEAT69( macro, data) MREPEAT68( macro, data) macro( 68, data) -#define MREPEAT70( macro, data) MREPEAT69( macro, data) macro( 69, data) -#define MREPEAT71( macro, data) MREPEAT70( macro, data) macro( 70, data) -#define MREPEAT72( macro, data) MREPEAT71( macro, data) macro( 71, data) -#define MREPEAT73( macro, data) MREPEAT72( macro, data) macro( 72, data) -#define MREPEAT74( macro, data) MREPEAT73( macro, data) macro( 73, data) -#define MREPEAT75( macro, data) MREPEAT74( macro, data) macro( 74, data) -#define MREPEAT76( macro, data) MREPEAT75( macro, data) macro( 75, data) -#define MREPEAT77( macro, data) MREPEAT76( macro, data) macro( 76, data) -#define MREPEAT78( macro, data) MREPEAT77( macro, data) macro( 77, data) -#define MREPEAT79( macro, data) MREPEAT78( macro, data) macro( 78, data) -#define MREPEAT80( macro, data) MREPEAT79( macro, data) macro( 79, data) -#define MREPEAT81( macro, data) MREPEAT80( macro, data) macro( 80, data) -#define MREPEAT82( macro, data) MREPEAT81( macro, data) macro( 81, data) -#define MREPEAT83( macro, data) MREPEAT82( macro, data) macro( 82, data) -#define MREPEAT84( macro, data) MREPEAT83( macro, data) macro( 83, data) -#define MREPEAT85( macro, data) MREPEAT84( macro, data) macro( 84, data) -#define MREPEAT86( macro, data) MREPEAT85( macro, data) macro( 85, data) -#define MREPEAT87( macro, data) MREPEAT86( macro, data) macro( 86, data) -#define MREPEAT88( macro, data) MREPEAT87( macro, data) macro( 87, data) -#define MREPEAT89( macro, data) MREPEAT88( macro, data) macro( 88, data) -#define MREPEAT90( macro, data) MREPEAT89( macro, data) macro( 89, data) -#define MREPEAT91( macro, data) MREPEAT90( macro, data) macro( 90, data) -#define MREPEAT92( macro, data) MREPEAT91( macro, data) macro( 91, data) -#define MREPEAT93( macro, data) MREPEAT92( macro, data) macro( 92, data) -#define MREPEAT94( macro, data) MREPEAT93( macro, data) macro( 93, data) -#define MREPEAT95( macro, data) MREPEAT94( macro, data) macro( 94, data) -#define MREPEAT96( macro, data) MREPEAT95( macro, data) macro( 95, data) -#define MREPEAT97( macro, data) MREPEAT96( macro, data) macro( 96, data) -#define MREPEAT98( macro, data) MREPEAT97( macro, data) macro( 97, data) -#define MREPEAT99( macro, data) MREPEAT98( macro, data) macro( 98, data) -#define MREPEAT100(macro, data) MREPEAT99( macro, data) macro( 99, data) -#define MREPEAT101(macro, data) MREPEAT100(macro, data) macro(100, data) -#define MREPEAT102(macro, data) MREPEAT101(macro, data) macro(101, data) -#define MREPEAT103(macro, data) MREPEAT102(macro, data) macro(102, data) -#define MREPEAT104(macro, data) MREPEAT103(macro, data) macro(103, data) -#define MREPEAT105(macro, data) MREPEAT104(macro, data) macro(104, data) -#define MREPEAT106(macro, data) MREPEAT105(macro, data) macro(105, data) -#define MREPEAT107(macro, data) MREPEAT106(macro, data) macro(106, data) -#define MREPEAT108(macro, data) MREPEAT107(macro, data) macro(107, data) -#define MREPEAT109(macro, data) MREPEAT108(macro, data) macro(108, data) -#define MREPEAT110(macro, data) MREPEAT109(macro, data) macro(109, data) -#define MREPEAT111(macro, data) MREPEAT110(macro, data) macro(110, data) -#define MREPEAT112(macro, data) MREPEAT111(macro, data) macro(111, data) -#define MREPEAT113(macro, data) MREPEAT112(macro, data) macro(112, data) -#define MREPEAT114(macro, data) MREPEAT113(macro, data) macro(113, data) -#define MREPEAT115(macro, data) MREPEAT114(macro, data) macro(114, data) -#define MREPEAT116(macro, data) MREPEAT115(macro, data) macro(115, data) -#define MREPEAT117(macro, data) MREPEAT116(macro, data) macro(116, data) -#define MREPEAT118(macro, data) MREPEAT117(macro, data) macro(117, data) -#define MREPEAT119(macro, data) MREPEAT118(macro, data) macro(118, data) -#define MREPEAT120(macro, data) MREPEAT119(macro, data) macro(119, data) -#define MREPEAT121(macro, data) MREPEAT120(macro, data) macro(120, data) -#define MREPEAT122(macro, data) MREPEAT121(macro, data) macro(121, data) -#define MREPEAT123(macro, data) MREPEAT122(macro, data) macro(122, data) -#define MREPEAT124(macro, data) MREPEAT123(macro, data) macro(123, data) -#define MREPEAT125(macro, data) MREPEAT124(macro, data) macro(124, data) -#define MREPEAT126(macro, data) MREPEAT125(macro, data) macro(125, data) -#define MREPEAT127(macro, data) MREPEAT126(macro, data) macro(126, data) -#define MREPEAT128(macro, data) MREPEAT127(macro, data) macro(127, data) -#define MREPEAT129(macro, data) MREPEAT128(macro, data) macro(128, data) -#define MREPEAT130(macro, data) MREPEAT129(macro, data) macro(129, data) -#define MREPEAT131(macro, data) MREPEAT130(macro, data) macro(130, data) -#define MREPEAT132(macro, data) MREPEAT131(macro, data) macro(131, data) -#define MREPEAT133(macro, data) MREPEAT132(macro, data) macro(132, data) -#define MREPEAT134(macro, data) MREPEAT133(macro, data) macro(133, data) -#define MREPEAT135(macro, data) MREPEAT134(macro, data) macro(134, data) -#define MREPEAT136(macro, data) MREPEAT135(macro, data) macro(135, data) -#define MREPEAT137(macro, data) MREPEAT136(macro, data) macro(136, data) -#define MREPEAT138(macro, data) MREPEAT137(macro, data) macro(137, data) -#define MREPEAT139(macro, data) MREPEAT138(macro, data) macro(138, data) -#define MREPEAT140(macro, data) MREPEAT139(macro, data) macro(139, data) -#define MREPEAT141(macro, data) MREPEAT140(macro, data) macro(140, data) -#define MREPEAT142(macro, data) MREPEAT141(macro, data) macro(141, data) -#define MREPEAT143(macro, data) MREPEAT142(macro, data) macro(142, data) -#define MREPEAT144(macro, data) MREPEAT143(macro, data) macro(143, data) -#define MREPEAT145(macro, data) MREPEAT144(macro, data) macro(144, data) -#define MREPEAT146(macro, data) MREPEAT145(macro, data) macro(145, data) -#define MREPEAT147(macro, data) MREPEAT146(macro, data) macro(146, data) -#define MREPEAT148(macro, data) MREPEAT147(macro, data) macro(147, data) -#define MREPEAT149(macro, data) MREPEAT148(macro, data) macro(148, data) -#define MREPEAT150(macro, data) MREPEAT149(macro, data) macro(149, data) -#define MREPEAT151(macro, data) MREPEAT150(macro, data) macro(150, data) -#define MREPEAT152(macro, data) MREPEAT151(macro, data) macro(151, data) -#define MREPEAT153(macro, data) MREPEAT152(macro, data) macro(152, data) -#define MREPEAT154(macro, data) MREPEAT153(macro, data) macro(153, data) -#define MREPEAT155(macro, data) MREPEAT154(macro, data) macro(154, data) -#define MREPEAT156(macro, data) MREPEAT155(macro, data) macro(155, data) -#define MREPEAT157(macro, data) MREPEAT156(macro, data) macro(156, data) -#define MREPEAT158(macro, data) MREPEAT157(macro, data) macro(157, data) -#define MREPEAT159(macro, data) MREPEAT158(macro, data) macro(158, data) -#define MREPEAT160(macro, data) MREPEAT159(macro, data) macro(159, data) -#define MREPEAT161(macro, data) MREPEAT160(macro, data) macro(160, data) -#define MREPEAT162(macro, data) MREPEAT161(macro, data) macro(161, data) -#define MREPEAT163(macro, data) MREPEAT162(macro, data) macro(162, data) -#define MREPEAT164(macro, data) MREPEAT163(macro, data) macro(163, data) -#define MREPEAT165(macro, data) MREPEAT164(macro, data) macro(164, data) -#define MREPEAT166(macro, data) MREPEAT165(macro, data) macro(165, data) -#define MREPEAT167(macro, data) MREPEAT166(macro, data) macro(166, data) -#define MREPEAT168(macro, data) MREPEAT167(macro, data) macro(167, data) -#define MREPEAT169(macro, data) MREPEAT168(macro, data) macro(168, data) -#define MREPEAT170(macro, data) MREPEAT169(macro, data) macro(169, data) -#define MREPEAT171(macro, data) MREPEAT170(macro, data) macro(170, data) -#define MREPEAT172(macro, data) MREPEAT171(macro, data) macro(171, data) -#define MREPEAT173(macro, data) MREPEAT172(macro, data) macro(172, data) -#define MREPEAT174(macro, data) MREPEAT173(macro, data) macro(173, data) -#define MREPEAT175(macro, data) MREPEAT174(macro, data) macro(174, data) -#define MREPEAT176(macro, data) MREPEAT175(macro, data) macro(175, data) -#define MREPEAT177(macro, data) MREPEAT176(macro, data) macro(176, data) -#define MREPEAT178(macro, data) MREPEAT177(macro, data) macro(177, data) -#define MREPEAT179(macro, data) MREPEAT178(macro, data) macro(178, data) -#define MREPEAT180(macro, data) MREPEAT179(macro, data) macro(179, data) -#define MREPEAT181(macro, data) MREPEAT180(macro, data) macro(180, data) -#define MREPEAT182(macro, data) MREPEAT181(macro, data) macro(181, data) -#define MREPEAT183(macro, data) MREPEAT182(macro, data) macro(182, data) -#define MREPEAT184(macro, data) MREPEAT183(macro, data) macro(183, data) -#define MREPEAT185(macro, data) MREPEAT184(macro, data) macro(184, data) -#define MREPEAT186(macro, data) MREPEAT185(macro, data) macro(185, data) -#define MREPEAT187(macro, data) MREPEAT186(macro, data) macro(186, data) -#define MREPEAT188(macro, data) MREPEAT187(macro, data) macro(187, data) -#define MREPEAT189(macro, data) MREPEAT188(macro, data) macro(188, data) -#define MREPEAT190(macro, data) MREPEAT189(macro, data) macro(189, data) -#define MREPEAT191(macro, data) MREPEAT190(macro, data) macro(190, data) -#define MREPEAT192(macro, data) MREPEAT191(macro, data) macro(191, data) -#define MREPEAT193(macro, data) MREPEAT192(macro, data) macro(192, data) -#define MREPEAT194(macro, data) MREPEAT193(macro, data) macro(193, data) -#define MREPEAT195(macro, data) MREPEAT194(macro, data) macro(194, data) -#define MREPEAT196(macro, data) MREPEAT195(macro, data) macro(195, data) -#define MREPEAT197(macro, data) MREPEAT196(macro, data) macro(196, data) -#define MREPEAT198(macro, data) MREPEAT197(macro, data) macro(197, data) -#define MREPEAT199(macro, data) MREPEAT198(macro, data) macro(198, data) -#define MREPEAT200(macro, data) MREPEAT199(macro, data) macro(199, data) -#define MREPEAT201(macro, data) MREPEAT200(macro, data) macro(200, data) -#define MREPEAT202(macro, data) MREPEAT201(macro, data) macro(201, data) -#define MREPEAT203(macro, data) MREPEAT202(macro, data) macro(202, data) -#define MREPEAT204(macro, data) MREPEAT203(macro, data) macro(203, data) -#define MREPEAT205(macro, data) MREPEAT204(macro, data) macro(204, data) -#define MREPEAT206(macro, data) MREPEAT205(macro, data) macro(205, data) -#define MREPEAT207(macro, data) MREPEAT206(macro, data) macro(206, data) -#define MREPEAT208(macro, data) MREPEAT207(macro, data) macro(207, data) -#define MREPEAT209(macro, data) MREPEAT208(macro, data) macro(208, data) -#define MREPEAT210(macro, data) MREPEAT209(macro, data) macro(209, data) -#define MREPEAT211(macro, data) MREPEAT210(macro, data) macro(210, data) -#define MREPEAT212(macro, data) MREPEAT211(macro, data) macro(211, data) -#define MREPEAT213(macro, data) MREPEAT212(macro, data) macro(212, data) -#define MREPEAT214(macro, data) MREPEAT213(macro, data) macro(213, data) -#define MREPEAT215(macro, data) MREPEAT214(macro, data) macro(214, data) -#define MREPEAT216(macro, data) MREPEAT215(macro, data) macro(215, data) -#define MREPEAT217(macro, data) MREPEAT216(macro, data) macro(216, data) -#define MREPEAT218(macro, data) MREPEAT217(macro, data) macro(217, data) -#define MREPEAT219(macro, data) MREPEAT218(macro, data) macro(218, data) -#define MREPEAT220(macro, data) MREPEAT219(macro, data) macro(219, data) -#define MREPEAT221(macro, data) MREPEAT220(macro, data) macro(220, data) -#define MREPEAT222(macro, data) MREPEAT221(macro, data) macro(221, data) -#define MREPEAT223(macro, data) MREPEAT222(macro, data) macro(222, data) -#define MREPEAT224(macro, data) MREPEAT223(macro, data) macro(223, data) -#define MREPEAT225(macro, data) MREPEAT224(macro, data) macro(224, data) -#define MREPEAT226(macro, data) MREPEAT225(macro, data) macro(225, data) -#define MREPEAT227(macro, data) MREPEAT226(macro, data) macro(226, data) -#define MREPEAT228(macro, data) MREPEAT227(macro, data) macro(227, data) -#define MREPEAT229(macro, data) MREPEAT228(macro, data) macro(228, data) -#define MREPEAT230(macro, data) MREPEAT229(macro, data) macro(229, data) -#define MREPEAT231(macro, data) MREPEAT230(macro, data) macro(230, data) -#define MREPEAT232(macro, data) MREPEAT231(macro, data) macro(231, data) -#define MREPEAT233(macro, data) MREPEAT232(macro, data) macro(232, data) -#define MREPEAT234(macro, data) MREPEAT233(macro, data) macro(233, data) -#define MREPEAT235(macro, data) MREPEAT234(macro, data) macro(234, data) -#define MREPEAT236(macro, data) MREPEAT235(macro, data) macro(235, data) -#define MREPEAT237(macro, data) MREPEAT236(macro, data) macro(236, data) -#define MREPEAT238(macro, data) MREPEAT237(macro, data) macro(237, data) -#define MREPEAT239(macro, data) MREPEAT238(macro, data) macro(238, data) -#define MREPEAT240(macro, data) MREPEAT239(macro, data) macro(239, data) -#define MREPEAT241(macro, data) MREPEAT240(macro, data) macro(240, data) -#define MREPEAT242(macro, data) MREPEAT241(macro, data) macro(241, data) -#define MREPEAT243(macro, data) MREPEAT242(macro, data) macro(242, data) -#define MREPEAT244(macro, data) MREPEAT243(macro, data) macro(243, data) -#define MREPEAT245(macro, data) MREPEAT244(macro, data) macro(244, data) -#define MREPEAT246(macro, data) MREPEAT245(macro, data) macro(245, data) -#define MREPEAT247(macro, data) MREPEAT246(macro, data) macro(246, data) -#define MREPEAT248(macro, data) MREPEAT247(macro, data) macro(247, data) -#define MREPEAT249(macro, data) MREPEAT248(macro, data) macro(248, data) -#define MREPEAT250(macro, data) MREPEAT249(macro, data) macro(249, data) -#define MREPEAT251(macro, data) MREPEAT250(macro, data) macro(250, data) -#define MREPEAT252(macro, data) MREPEAT251(macro, data) macro(251, data) -#define MREPEAT253(macro, data) MREPEAT252(macro, data) macro(252, data) -#define MREPEAT254(macro, data) MREPEAT253(macro, data) macro(253, data) -#define MREPEAT255(macro, data) MREPEAT254(macro, data) macro(254, data) -#define MREPEAT256(macro, data) MREPEAT255(macro, data) macro(255, data) - -/** @} */ - -#endif /* _MREPEAT_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h deleted file mode 100644 index 7f67d8a..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/preprocessor.h +++ /dev/null @@ -1,38 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef _PREPROCESSOR_H_ -#define _PREPROCESSOR_H_ - -#include "tpaste.h" -#include "stringz.h" -#include "mrepeat.h" -#include "mrecursion.h" - -#endif // _PREPROCESSOR_H_ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/stringz.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/stringz.h deleted file mode 100644 index 70937c4..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/stringz.h +++ /dev/null @@ -1,67 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef _STRINGZ_H_ -#define _STRINGZ_H_ - -/** - * \defgroup group_sam0_utils_stringz Preprocessor - Stringize - * - * \ingroup group_sam0_utils - * - * @{ - */ - -/** \brief Stringize. - * - * Stringize a preprocessing token, this token being allowed to be \#defined. - * - * May be used only within macros with the token passed as an argument if the - * token is \#defined. - * - * For example, writing STRINGZ(PIN) within a macro \#defined by PIN_NAME(PIN) - * and invoked as PIN_NAME(PIN0) with PIN0 \#defined as A0 is equivalent to - * writing "A0". - */ -#define STRINGZ(x) #x - -/** \brief Absolute stringize. - * - * Stringize a preprocessing token, this token being allowed to be \#defined. - * - * No restriction of use if the token is \#defined. - * - * For example, writing ASTRINGZ(PIN0) anywhere with PIN0 \#defined as A0 is - * equivalent to writing "A0". - */ -#define ASTRINGZ(x) STRINGZ(x) - -/** @} */ - -#endif // _STRINGZ_H_ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/tpaste.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/tpaste.h deleted file mode 100644 index 9108183..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/preprocessor/tpaste.h +++ /dev/null @@ -1,85 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ -#ifndef _TPASTE_H_ -#define _TPASTE_H_ - -/** - * \defgroup group_sam0_utils_tpaste Preprocessor - Token Paste - * - * \ingroup group_sam0_utils - * - * @{ - */ - -/** \name Token Paste - * - * Paste N preprocessing tokens together, these tokens being allowed to be \#defined. - * - * May be used only within macros with the tokens passed as arguments if the tokens are \#defined. - * - * For example, writing TPASTE2(U, WIDTH) within a macro \#defined by - * UTYPE(WIDTH) and invoked as UTYPE(UL_WIDTH) with UL_WIDTH \#defined as 32 is - * equivalent to writing U32. - * - * @{ */ -#define TPASTE2( a, b) a##b -#define TPASTE3( a, b, c) a##b##c -#define TPASTE4( a, b, c, d) a##b##c##d -#define TPASTE5( a, b, c, d, e) a##b##c##d##e -#define TPASTE6( a, b, c, d, e, f) a##b##c##d##e##f -#define TPASTE7( a, b, c, d, e, f, g) a##b##c##d##e##f##g -#define TPASTE8( a, b, c, d, e, f, g, h) a##b##c##d##e##f##g##h -#define TPASTE9( a, b, c, d, e, f, g, h, i) a##b##c##d##e##f##g##h##i -#define TPASTE10(a, b, c, d, e, f, g, h, i, j) a##b##c##d##e##f##g##h##i##j -/** @} */ - -/** \name Absolute Token Paste - * - * Paste N preprocessing tokens together, these tokens being allowed to be \#defined. - * - * No restriction of use if the tokens are \#defined. - * - * For example, writing ATPASTE2(U, UL_WIDTH) anywhere with UL_WIDTH \#defined - * as 32 is equivalent to writing U32. - * - * @{ */ -#define ATPASTE2( a, b) TPASTE2( a, b) -#define ATPASTE3( a, b, c) TPASTE3( a, b, c) -#define ATPASTE4( a, b, c, d) TPASTE4( a, b, c, d) -#define ATPASTE5( a, b, c, d, e) TPASTE5( a, b, c, d, e) -#define ATPASTE6( a, b, c, d, e, f) TPASTE6( a, b, c, d, e, f) -#define ATPASTE7( a, b, c, d, e, f, g) TPASTE7( a, b, c, d, e, f, g) -#define ATPASTE8( a, b, c, d, e, f, g, h) TPASTE8( a, b, c, d, e, f, g, h) -#define ATPASTE9( a, b, c, d, e, f, g, h, i) TPASTE9( a, b, c, d, e, f, g, h, i) -#define ATPASTE10(a, b, c, d, e, f, g, h, i, j) TPASTE10(a, b, c, d, e, f, g, h, i, j) -/** @} */ - -/** @} */ - -#endif // _TPASTE_H_ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/reset.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/reset.h deleted file mode 100644 index ae1eb5a..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/reset.h +++ /dev/null @@ -1,119 +0,0 @@ -/** - * \file - * - * \brief SAM Reset related functionality - * - * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef RESET_H_INCLUDED -#define RESET_H_INCLUDED - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \addtogroup asfdoc_sam0_system_group - * @{ - */ - -/** - * \brief Reset causes of the system. - * - * List of possible reset causes of the system. - */ -enum system_reset_cause { - /** The system was last reset by a software reset. */ - SYSTEM_RESET_CAUSE_SOFTWARE = PM_RCAUSE_SYST, - /** The system was last reset by the watchdog timer. */ - SYSTEM_RESET_CAUSE_WDT = PM_RCAUSE_WDT, - /** The system was last reset because the external reset line was pulled low. */ - SYSTEM_RESET_CAUSE_EXTERNAL_RESET = PM_RCAUSE_EXT, - /** The system was last reset by the BOD33. */ - SYSTEM_RESET_CAUSE_BOD33 = PM_RCAUSE_BOD33, - /** The system was last reset by the BOD12. */ - SYSTEM_RESET_CAUSE_BOD12 = PM_RCAUSE_BOD12, - /** The system was last reset by the POR (Power on reset). */ - SYSTEM_RESET_CAUSE_POR = PM_RCAUSE_POR, -}; - - -/** - * \name Reset Control - * @{ - */ - -/** - * \brief Reset the MCU. - * - * Resets the MCU and all associated peripherals and registers, except RTC, all 32KHz sources, - * WDT (if ALWAYSON is set) and GCLK (if WRTLOCK is set). - * - */ -static inline void system_reset(void) -{ - NVIC_SystemReset(); -} - -/** - * \brief Return the reset cause. - * - * Retrieves the cause of the last system reset. - * - * \return An enum value indicating the cause of the last system reset. - */ -static inline enum system_reset_cause system_get_reset_cause(void) -{ - return (enum system_reset_cause)PM->RCAUSE.reg; -} - -/** - * @} - */ - -/** @} */ -#ifdef __cplusplus -} -#endif - -#endif /* RESET_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/status_codes.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/status_codes.h deleted file mode 100644 index 29bbf41..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/status_codes.h +++ /dev/null @@ -1,138 +0,0 @@ -/* ---------------------------------------------------------------------------- - * SAM Software Package License - * ---------------------------------------------------------------------------- - * Copyright (c) 2011-2012, Atmel Corporation - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following condition is met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the disclaimer below. - * - * Atmel's name may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * ---------------------------------------------------------------------------- - */ - -#ifndef STATUS_CODES_H_INCLUDED -#define STATUS_CODES_H_INCLUDED - -#include - -/** - * \defgroup group_sam0_utils_status_codes Status Codes - * - * \ingroup group_sam0_utils - * - * @{ - */ - -/** Mask to retrieve the error category of a status code. */ -#define STATUS_CATEGORY_MASK 0xF0 - -/** Mask to retrieve the error code within the category of a status code. */ -#define STATUS_ERROR_MASK 0x0F - -/** Status code error categories. */ -enum status_categories { - STATUS_CATEGORY_OK = 0x00, - STATUS_CATEGORY_COMMON = 0x10, - STATUS_CATEGORY_ANALOG = 0x30, - STATUS_CATEGORY_COM = 0x40, - STATUS_CATEGORY_IO = 0x50, -}; - -/** - * Status code that may be returned by shell commands and protocol - * implementations. - * - * \note Any change to these status codes and the corresponding - * message strings is strictly forbidden. New codes can be added, - * however, but make sure that any message string tables are updated - * at the same time. - */ -enum status_code { - STATUS_OK = STATUS_CATEGORY_OK | 0x00, - STATUS_VALID_DATA = STATUS_CATEGORY_OK | 0x01, - STATUS_NO_CHANGE = STATUS_CATEGORY_OK | 0x02, - STATUS_ABORTED = STATUS_CATEGORY_OK | 0x04, - STATUS_BUSY = STATUS_CATEGORY_OK | 0x05, - STATUS_SUSPEND = STATUS_CATEGORY_OK | 0x06, - - STATUS_ERR_IO = STATUS_CATEGORY_COMMON | 0x00, - STATUS_ERR_REQ_FLUSHED = STATUS_CATEGORY_COMMON | 0x01, - STATUS_ERR_TIMEOUT = STATUS_CATEGORY_COMMON | 0x02, - STATUS_ERR_BAD_DATA = STATUS_CATEGORY_COMMON | 0x03, - STATUS_ERR_NOT_FOUND = STATUS_CATEGORY_COMMON | 0x04, - STATUS_ERR_UNSUPPORTED_DEV = STATUS_CATEGORY_COMMON | 0x05, - STATUS_ERR_NO_MEMORY = STATUS_CATEGORY_COMMON | 0x06, - STATUS_ERR_INVALID_ARG = STATUS_CATEGORY_COMMON | 0x07, - STATUS_ERR_BAD_ADDRESS = STATUS_CATEGORY_COMMON | 0x08, - STATUS_ERR_BAD_FORMAT = STATUS_CATEGORY_COMMON | 0x0A, - STATUS_ERR_BAD_FRQ = STATUS_CATEGORY_COMMON | 0x0B, - STATUS_ERR_DENIED = STATUS_CATEGORY_COMMON | 0x0c, - STATUS_ERR_ALREADY_INITIALIZED = STATUS_CATEGORY_COMMON | 0x0d, - STATUS_ERR_OVERFLOW = STATUS_CATEGORY_COMMON | 0x0e, - STATUS_ERR_NOT_INITIALIZED = STATUS_CATEGORY_COMMON | 0x0f, - - STATUS_ERR_SAMPLERATE_UNAVAILABLE = STATUS_CATEGORY_ANALOG | 0x00, - STATUS_ERR_RESOLUTION_UNAVAILABLE = STATUS_CATEGORY_ANALOG | 0x01, - - STATUS_ERR_BAUDRATE_UNAVAILABLE = STATUS_CATEGORY_COM | 0x00, - STATUS_ERR_PACKET_COLLISION = STATUS_CATEGORY_COM | 0x01, - STATUS_ERR_PROTOCOL = STATUS_CATEGORY_COM | 0x02, - - STATUS_ERR_PIN_MUX_INVALID = STATUS_CATEGORY_IO | 0x00, -}; -typedef enum status_code status_code_genare_t; - -/** - Status codes used by MAC stack. - */ -enum status_code_wireless { - //STATUS_OK = 0, //!< Success - ERR_IO_ERROR = -1, //!< I/O error - ERR_FLUSHED = -2, //!< Request flushed from queue - ERR_TIMEOUT = -3, //!< Operation timed out - ERR_BAD_DATA = -4, //!< Data integrity check failed - ERR_PROTOCOL = -5, //!< Protocol error - ERR_UNSUPPORTED_DEV = -6, //!< Unsupported device - ERR_NO_MEMORY = -7, //!< Insufficient memory - ERR_INVALID_ARG = -8, //!< Invalid argument - ERR_BAD_ADDRESS = -9, //!< Bad address - ERR_BUSY = -10, //!< Resource is busy - ERR_BAD_FORMAT = -11, //!< Data format not recognized - ERR_NO_TIMER = -12, //!< No timer available - ERR_TIMER_ALREADY_RUNNING = -13, //!< Timer already running - ERR_TIMER_NOT_RUNNING = -14, //!< Timer not running - - /** - * \brief Operation in progress - * - * This status code is for driver-internal use when an operation - * is currently being performed. - * - * \note Drivers should never return this status code to any - * callers. It is strictly for internal use. - */ - OPERATION_IN_PROGRESS = -128, -}; - -typedef enum status_code_wireless status_code_t; - -/** @} */ - -#endif /* STATUS_CODES_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system.c deleted file mode 100644 index 0121588..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system.c +++ /dev/null @@ -1,111 +0,0 @@ -/** - * \file - * - * \brief SAM System related functionality - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#include - -/** - * \internal - * Dummy initialization function, used as a weak alias target for the various - * init functions called by \ref system_init(). - */ -void _system_dummy_init(void); -void _system_dummy_init(void) -{ - return; -} - -#if !defined(__DOXYGEN__) -# if defined(__GNUC__) -void system_clock_init(void) WEAK __attribute__((alias("_system_dummy_init"))); -void system_board_init(void) WEAK __attribute__((alias("_system_dummy_init"))); -void _system_events_init(void) WEAK __attribute__((alias("_system_dummy_init"))); -void _system_extint_init(void) WEAK __attribute__((alias("_system_dummy_init"))); -void _system_divas_init(void) WEAK __attribute__((alias("_system_dummy_init"))); -# elif defined(__ICCARM__) -void system_clock_init(void); -void system_board_init(void); -void _system_events_init(void); -void _system_extint_init(void); -void _system_divas_init(void); -# pragma weak system_clock_init=_system_dummy_init -# pragma weak system_board_init=_system_dummy_init -# pragma weak _system_events_init=_system_dummy_init -# pragma weak _system_extint_init=_system_dummy_init -# pragma weak _system_divas_init=_system_dummy_init -# endif -#endif - -/** - * \brief Initialize system - * - * This function will call the various initialization functions within the - * system namespace. If a given optional system module is not available, the - * associated call will effectively be a NOP (No Operation). - * - * Currently the following initialization functions are supported: - * - System clock initialization (via the SYSTEM CLOCK sub-module) - * - Board hardware initialization (via the Board module) - * - Event system driver initialization (via the EVSYS module) - * - External Interrupt driver initialization (via the EXTINT module) - */ -void system_init(void) -{ - /* Configure GCLK and clock sources according to conf_clocks.h */ - system_clock_init(); - - /* Initialize board hardware */ - system_board_init(); - - /* Initialize EVSYS hardware */ - _system_events_init(); - - /* Initialize External hardware */ - _system_extint_init(); - - /* Initialize DIVAS hardware */ - _system_divas_init(); -} - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system.h deleted file mode 100644 index 7b7bc00..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system.h +++ /dev/null @@ -1,726 +0,0 @@ -/** - * \file - * - * \brief SAM System related functionality - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef SYSTEM_H_INCLUDED -#define SYSTEM_H_INCLUDED - -#include -#include -#include -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \defgroup asfdoc_sam0_system_group SAM System (SYSTEM) Driver - * - * This driver for Atmel® | SMART ARM®-based microcontrollers provides an interface for the configuration - * and management of the device's system relation functionality, necessary for - * the basic device operation. This is not limited to a single peripheral, but - * extends across multiple hardware peripherals. - * - * The following peripherals are used by this module: - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - PM (Power Manager) - * - RSTC(Reset Controller) - * - SUPC(Supply Controller) - * \endif - * \if DEVICE_SAMC21_SYSTEM_SUPPORT - * - PM (Power Manager) - * - RSTC(Reset Controller) - * - SUPC(Supply Controller) - * \endif - * \if DEVICE_SAMD21_SYSTEM_SUPPORT - * - SYSCTRL (System Control) - * - PM (Power Manager) - * \endif - * - * The following devices can use this module: - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - Atmel | SMART SAM L21 - * \endif - * \if DEVICE_SAMC21_SYSTEM_SUPPORT - * - Atmel | SMART SAM C20/C21 - * \endif - * \if DEVICE_SAMD21_SYSTEM_SUPPORT - * - Atmel | SMART SAM D20/D21 - * - Atmel | SMART SAM R21 - * - Atmel | SMART SAM D09/D10/D11 - * - Atmel | SMART SAM DAx - * \endif - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_system_prerequisites - * - \ref asfdoc_sam0_system_module_overview - * - \ref asfdoc_sam0_system_special_considerations - * - \ref asfdoc_sam0_system_extra_info - * - \ref asfdoc_sam0_system_examples - * - \ref asfdoc_sam0_system_api_overview - * - * - * \section asfdoc_sam0_system_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * - * \section asfdoc_sam0_system_module_overview Module Overview - * - * The System driver provides a collection of interfaces between the user - * application logic, and the core device functionality (such as clocks, reset - * cause determination, etc.) that is required for all applications. It contains - * a number of sub-modules that control one specific aspect of the device: - * - * - System Core (this module) - * - \ref asfdoc_sam0_system_clock_group "System Clock Control" (sub-module) - * - \ref asfdoc_sam0_system_interrupt_group "System Interrupt Control" (sub-module) - * - \ref asfdoc_sam0_system_pinmux_group "System Pin Multiplexer Control" (sub-module) - * - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * \subsection asfdoc_sam0_system_module_overview_vreg_l21 Voltage Regulator - * The SAM device controls the voltage regulators for the core (VDDCORE) and - * backup (VDDBU) domains. It sets the voltage regulators according to the sleep - * modes, the performance level, or the user configuration. - * - * In active mode, the voltage regulator can be chosen on the fly between a LDO - * or a Buck converter. In standby mode, the low power voltage regulator is used - * to supply VDDCORE. - * - * \subsection asfdoc_sam0_system_module_overview_bbps Battery Backup Power Switch - * The SAM device supports connection of a battery backup to the VBAT power pin. - * It includes functionality that enables automatic power switching between main - * power and battery backup power. This will ensure power to the backup domain, - * when the main battery or power source is unavailable. - * \endif - * - * \if DEVICE_SAMC21_SYSTEM_SUPPORT - * \subsection asfdoc_sam0_system_module_overview_vreg_c21 Voltage Regulator - * The SAM device controls the voltage regulators for the core (VDDCORE). It sets - * the voltage regulators according to the sleep modes. - * - * There are a selectable reference voltage and voltage dependent on the temperature - * which can be used by analog modules like the ADC. - * \endif - * - * \subsection asfdoc_sam0_system_module_overview_vref Voltage References - * The various analog modules within the SAM devices (such as AC, ADC, and - * DAC) require a voltage reference to be configured to act as a reference point - * for comparisons and conversions. - * - * The SAM devices contain multiple references, including an internal - * temperature sensor and a fixed band-gap voltage source. When enabled, the - * associated voltage reference can be selected within the desired peripheral - * where applicable. - * - * \subsection asfdoc_sam0_system_module_overview_reset_cause System Reset Cause - * In some applications there may be a need to execute a different program - * flow based on how the device was reset. For example, if the cause of reset - * was the Watchdog timer (WDT), this might indicate an error in the application, - * and a form of error handling or error logging might be needed. - * - * For this reason, an API is provided to retrieve the cause of the last system - * reset, so that appropriate action can be taken. - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * There are three groups of reset sources: - * - Power supply reset: Resets caused by an electrical issue. It covers POR and BOD reset. - * - User reset: Resets caused by the application. It covers external reset, - * system reset, and watchdog reset. - * - Backup reset: Resets caused by a backup mode exit condition. - * - * \subsection asfdoc_sam0_system_module_overview_performance_level Performance Level - * Performance level allows the user to adjust the regulator output voltage to reduce - * power consumption. The user can on the fly select the most suitable performance - * level, depending on the application demands. - * - * The SAM device can operate at two different performance levels (PL0 and PL2). - * When operating at PL0, the voltage applied on the full logic area is reduced - * by voltage scaling. This voltage scaling technique allows to reduce the active - * power consumption while decreasing the maximum frequency of the device. When - * operating at PL2, the voltage regulator supplies the highest voltage, allowing - * the device to run at higher clock speeds. - * - * Performance level transition is possible only when the device is in active - * mode. After a reset, the device starts at the lowest performance level - * (lowest power consumption and lowest max. frequency). The application can then - * switch to another performance level at any time without any stop in the code - * execution. As shown in \ref asfdoc_sam0_system_performance_level_transition_figure. - * - * \note When scaling down the performance level, the bus frequency should first be - * scaled down in order to not exceed the maximum frequency allowed for the - * low performance level. - * When scaling up the performance level (e.g. from PL0 to PL2), check the performance - * level status before increasing the bus frequency. It can be increased only - * when the performance level transition is completed. - * - * \anchor asfdoc_sam0_system_performance_level_transition_figure - * \image html performance_level_transition.svg "Performance Level Transition" - * - * \subsection asfdoc_sam0_system_module_overview_power_domain Power Domain Gating - * Power domain gating allows power saving by reducing the voltage in logic - * areas in the device to a low-power supply. The feature is available in - * Standby sleep mode and will reduce the voltage in domains where all peripherals - * are idle. Internal logic will maintain its content, meaning the corresponding - * peripherals will not need to be reconfigured when normal operating voltage - * is returned. Most power domains can be in the following three states: - * - * - Active state: The power domain is powered on. - * - Retention state: The main voltage supply for the power domain is switched off, - * while maintaining a secondary low-power supply for the sequential cells. The - * logic context is restored when waking up. - * - Off state: The power domain is entirely powered off. The logic context is lost. - * - * The SAM L21 device contains three power domains which can be controlled using - * power domain gating, namely PD0, PD1, and PD2. These power domains can be - * configured to the following cases: - * - Default with no sleepwalking peripherals: A power domain is automatically set - * to retention state in standby sleep mode if no activity require it. The application - * can force all power domains to remain in active state during standby sleep mode - * in order to accelerate wakeup time. - * - Default with sleepwalking peripherals: If one or more peripherals are enabled - * to perform sleepwalking tasks in standby sleep mode, the corresponding power - * domain (PDn) remains in active state as well as all inferior power domains (PDn) in order - * to perform a sleepwalking task. The superior power domain is then automatically - * set to active state. At the end of the sleepwalking task, the device can either - * be woken up or the superior power domain can return to retention state. - * - * Power domains can be linked to each other, it allows a power domain (PDn) to be kept - * in active state if the inferior power domain (PDn-1) is in active state too. - * - * \ref asfdoc_sam0_system_power_domain_overview_table illustrates the - * four cases to consider in standby mode. - * - * \anchor asfdoc_sam0_system_power_domain_overview_table - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Sleep Mode versus Power Domain State Overview
Sleep modePD0PD1PD2PDTOPPDBACKUP
Idleactiveactiveactiveactiveactive
Standby - Case 1activeactiveactiveactiveactive
Standby - Case 2activeactiveretentionactiveactive
Standby - Case 3activeretentionretentionactiveactive
Standby - Case 4retentionretentionretentionactiveactive
Backupoffoffoffoffactive
Offoffoffoffoffoff
- * - * \subsection asfdoc_sam0_system_module_overview_ram_state RAMs Low Power Mode - * By default, in standby sleep mode, RAM is in low power mode (back biased) - * if its power domain is in retention state. - * \ref asfdoc_sam0_system_power_ram_state_table lists RAMs low power mode. - * - * \anchor asfdoc_sam0_system_power_ram_state_table - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
RAM Back-biasing Mode
RAM modeDescription
Retention Back-biasing modeRAM is back-biased if its power domain is in retention mode
Standby Back-biasing modeRAM is back-biased if the device is in standby mode
Standby OFF modeRAM is OFF if the device is in standby mode
Always OFF modeRAM is OFF if the device is in RET mode
- * - * \endif - * - * \subsection asfdoc_sam0_system_module_overview_sleep_mode Sleep Modes - * The SAM devices have several sleep modes. The sleep mode controls - * which clock systems on the device will remain enabled or disabled when the - * device enters a low power sleep mode. - * \ref asfdoc_sam0_system_module_sleep_mode_table "The table below" lists the - * clock settings of the different sleep modes. - * - * \anchor asfdoc_sam0_system_module_sleep_mode_table - * - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * \else - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * \endif - *
SAM Device Sleep Modes
Sleep modeSystem clockCPU clockAHB/AHB clockGCLK clocksOscillators (ONDEMAND = 0)Oscillators (ONDEMAND = 1)Regulator modeRAM mode
IdleRunStopRun if requestedRunRunRun if requestedNormalNormal
StandbyStopStopRun if requestedRun if requestedRun if requested or RUNSTDBY = 1Run if requestedLow pwerLow pwer
BackupStopStopStopStopStopStopBackupOff
OffOffOffOffOffOffOffOffOff
Sleep modeCPU clockAHB clockAPB clocksClock sourcesSystem clock32KHzReg modeRAM mode
Idle 0StopRunRunRunRunRunNormalNormal
Idle 1StopStopRunRunRunRunNormalNormal
Idle 2StopStopStopRunRunRunNormalNormal
StandbyStopStopStopStopStopStopLow PowerSource/Drain biasing
- * - * Before entering device sleep, one of the available sleep modes must be set. - * The device will automatically wake up in response to an interrupt being - * generated or upon any other sleep mode exit condition. - * - * Some peripheral clocks will remain enabled during sleep, depending on their - * configuration. If desired, the modules can remain clocked during sleep to allow - * them continue to operate while other parts of the system are powered down - * to save power. - * - * - * \section asfdoc_sam0_system_special_considerations Special Considerations - * - * Most of the functions in this driver have device specific restrictions and - * caveats; refer to your device datasheet. - * - * - * \section asfdoc_sam0_system_extra_info Extra Information - * - * For extra information, see \ref asfdoc_sam0_system_extra. This includes: - * - \ref asfdoc_sam0_system_extra_acronyms - * - \ref asfdoc_sam0_system_extra_dependencies - * - \ref asfdoc_sam0_system_extra_errata - * - \ref asfdoc_sam0_system_extra_history - * - * - * \section asfdoc_sam0_system_examples Examples - * - * For SYSTEM module related examples, refer to the sub-modules listed in - * the \ref asfdoc_sam0_system_module_overview "system module overview". - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_drivers_power_exqsg. - * - * - * \section asfdoc_sam0_system_api_overview API Overview - * @{ - */ - -/** - * \name System Debugger - * @{ - */ - -/** - * \brief Check if debugger is present. - * - * Check if debugger is connected to the onboard debug system (DAP). - * - * \return A bool identifying if a debugger is present. - * - * \retval true Debugger is connected to the system - * \retval false Debugger is not connected to the system - * - */ -static inline bool system_is_debugger_present(void) -{ - return DSU->STATUSB.reg & DSU_STATUSB_DBGPRES; -} - -/** - * @} - */ - -/** - * \name System Identification - * @{ - */ - -/** - * \brief Retrieve the device identification signature. - * - * Retrieves the signature of the current device. - * - * \return Device ID signature as a 32-bit integer. - */ -static inline uint32_t system_get_device_id(void) -{ - return DSU->DID.reg; -} - -/** - * @} - */ - -/** - * \name System Initialization - * @{ - */ - -void system_init(void); - -/** - * @} - */ - - -/** - * @} - */ - -/** - -* \page asfdoc_sam0_drivers_power_exqsg Examples for Power Driver - * - * This is a list of the available Quick Start Guides (QSGs) and example - * applications. QSGs are simple examples with step-by-step instructions to - * configure and use this driver in a selection of - * use cases. Note that a QSG can be compiled as a standalone application or be - * added to the user application. - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - \subpage asfdoc_sam0_power_basic_use_case - * \endif - * - * \page asfdoc_sam0_system_extra Extra Information for SYSTEM Driver - * - * \section asfdoc_sam0_system_extra_acronyms Acronyms - * Below is a table listing the acronyms used in this module, along with their - * intended meanings. - * - * - * - * - * - * - * - * - * - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - * - * - * - * - * - * - * - * \endif - * \if DEVICE_SAMC21_SYSTEM_SUPPORT - * - * - * - * - * - * - * - * - * \endif - * \if DEVICE_SAMD21_SYSTEM_SUPPORT - * - * - * - * - * \endif - *
AcronymDefinition
PMPower Manager
SUPCSupply Controller
RSTCReset Controller
SUPCSupply Controller
RSTCReset Controller
SYSCTRLSystem control interface
- * - * - * \section asfdoc_sam0_system_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - None - * - * - * \section asfdoc_sam0_system_extra_errata Errata - * There are no errata related to this driver. - * - * - * \section asfdoc_sam0_system_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - * - * - * \endif - * \if DEVICE_SAMC21_SYSTEM_SUPPORT - * - * - * - * \endif - * \if DEVICE_SAMD21_SYSTEM_SUPPORT - * - * - * - * - * - * - * - * - * - * \endif - *
Changelog
Initial Release
Initial Release
Added new \c system_reset() to reset the complete MCU with some exceptions
Added new \c system_get_device_id() function to retrieved the device - * ID.
Initial Release
- * - * \page asfdoc_sam0_system_document_revision_history Document Revision History - * - * - * - * - * \if DEVICE_SAML21_SYSTEM_SUPPORT - * - * - * - * - * - * \endif - * \if DEVICE_SAMC21_SYSTEM_SUPPORT - * - * - * - * - * - * \endif - * \if DEVICE_SAMD21_SYSTEM_SUPPORT - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * \endif - *
Doc. Rev. - * Date - * Comments - *
42449A07/2015Initial document release
42484A08/2015Initial document release.
42120E04/2015Added support for SAMDAx
42120D12/2014Added support for SAMR21 and SAMD10/D11
42120C01/2014Added support for SAMD21
42120B06/2013Corrected documentation typos
42120A06/2013Initial document release
- */ - -#ifdef __cplusplus -} -#endif - -#endif /* SYSTEM_H_INCLUDED */ - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system_interrupt.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system_interrupt.h deleted file mode 100644 index 93a542d..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system_interrupt.h +++ /dev/null @@ -1,429 +0,0 @@ -/** - * \file - * - * \brief SAM System Interrupt Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef SYSTEM_INTERRUPT_H_INCLUDED -#define SYSTEM_INTERRUPT_H_INCLUDED - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \defgroup asfdoc_sam0_system_interrupt_group SAM System Interrupt (SYSTEM INTERRUPT) Driver - * - * This driver for Atmel® | SMART ARM®-based microcontrollers provides - * an interface for the configuration and management of internal software and - * hardware interrupts/exceptions. - * - * The following peripheral is used by this module: - * - NVIC (Nested Vector Interrupt Controller) - * - * The following devices can use this module: - * - Atmel | SMART SAM D20/D21 - * - Atmel | SMART SAM R21 - * - Atmel | SMART SAM D09/D10/D11 - * - Atmel | SMART SAM L21/L22 - * - Atmel | SMART SAM DA1 - * - Atmel | SMART SAM C20/C21 - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_system_interrupt_prerequisites - * - \ref asfdoc_sam0_system_interrupt_module_overview - * - \ref asfdoc_sam0_system_interrupt_special_considerations - * - \ref asfdoc_sam0_system_interrupt_extra_info - * - \ref asfdoc_sam0_system_interrupt_examples - * - \ref asfdoc_sam0_system_interrupt_api_overview - * - * - * \section asfdoc_sam0_system_interrupt_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * - * \section asfdoc_sam0_system_interrupt_module_overview Module Overview - * - * The ARM® Cortex® M0+ core contains an interrupt and exception vector table, which - * can be used to configure the device's interrupt handlers; individual - * interrupts and exceptions can be enabled and disabled, as well as configured - * with a variable priority. - * - * This driver provides a set of wrappers around the core interrupt functions, - * to expose a simple API for the management of global and individual interrupts - * within the device. - * - * \subsection asfdoc_sam0_system_interrupt_module_overview_criticalsec Critical Sections - * In some applications it is important to ensure that no interrupts may be - * executed by the system whilst a critical portion of code is being run; for - * example, a buffer may be copied from one context to another - during which - * interrupts must be disabled to avoid corruption of the source buffer contents - * until the copy has completed. This driver provides a basic API to enter and - * exit nested critical sections, so that global interrupts can be kept disabled - * for as long as necessary to complete a critical application code section. - * - * \subsection asfdoc_sam0_system_interrupt_module_overview_softints Software Interrupts - * For some applications, it may be desirable to raise a module or core - * interrupt via software. For this reason, a set of APIs to set an interrupt or - * exception as pending are provided to the user application. - * - * \section asfdoc_sam0_system_interrupt_special_considerations Special Considerations - * - * Interrupts from peripherals in the SAM devices are on a per-module basis; - * an interrupt raised from any source within a module will cause a single, - * module-common handler to execute. It is the user application or driver's - * responsibility to de-multiplex the module-common interrupt to determine the - * exact interrupt cause. - * - * \section asfdoc_sam0_system_interrupt_extra_info Extra Information - * - * For extra information, see \ref asfdoc_sam0_system_interrupt_extra. This includes: - * - \ref asfdoc_sam0_system_interrupt_extra_acronyms - * - \ref asfdoc_sam0_system_interrupt_extra_dependencies - * - \ref asfdoc_sam0_system_interrupt_extra_errata - * - \ref asfdoc_sam0_system_interrupt_extra_history - * - * - * \section asfdoc_sam0_system_interrupt_examples Examples - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_system_interrupt_exqsg. - * - * \section asfdoc_sam0_system_interrupt_api_overview API Overview - * @{ - */ - -#include "compiler.h" -#include -#include "system_interrupt_features.h" - -/** - * \brief Table of possible system interrupt/exception vector priorities. - * - * Table of all possible interrupt and exception vector priorities within the - * device. - */ -enum system_interrupt_priority_level { - /** Priority level 0, the highest possible interrupt priority */ - SYSTEM_INTERRUPT_PRIORITY_LEVEL_0 = 0, - /** Priority level 1 */ - SYSTEM_INTERRUPT_PRIORITY_LEVEL_1 = 1, - /** Priority level 2 */ - SYSTEM_INTERRUPT_PRIORITY_LEVEL_2 = 2, - /** Priority level 3, the lowest possible interrupt priority */ - SYSTEM_INTERRUPT_PRIORITY_LEVEL_3 = 3, -}; - -/** - * \name Critical Section Management - * @{ - */ - -/** - * \brief Enters a critical section. - * - * Disables global interrupts. To support nested critical sections, an internal - * count of the critical section nesting will be kept, so that global interrupts - * are only re-enabled upon leaving the outermost nested critical section. - * - */ -static inline void system_interrupt_enter_critical_section(void) -{ - cpu_irq_enter_critical(); -} - -/** - * \brief Leaves a critical section. - * - * Enables global interrupts. To support nested critical sections, an internal - * count of the critical section nesting will be kept, so that global interrupts - * are only re-enabled upon leaving the outermost nested critical section. - * - */ -static inline void system_interrupt_leave_critical_section(void) -{ - cpu_irq_leave_critical(); -} - -/** @} */ - -/** - * \name Interrupt Enabling/Disabling - * @{ - */ - -/** - * \brief Check if global interrupts are enabled. - * - * Checks if global interrupts are currently enabled. - * - * \returns A boolean that identifies if the global interrupts are enabled or not. - * - * \retval true Global interrupts are currently enabled - * \retval false Global interrupts are currently disabled - * - */ -static inline bool system_interrupt_is_global_enabled(void) -{ - return cpu_irq_is_enabled(); -} - -/** - * \brief Enables global interrupts. - * - * Enables global interrupts in the device to fire any enabled interrupt handlers. - */ -static inline void system_interrupt_enable_global(void) -{ - cpu_irq_enable(); -} - -/** - * \brief Disables global interrupts. - * - * Disabled global interrupts in the device, preventing any enabled interrupt - * handlers from executing. - */ -static inline void system_interrupt_disable_global(void) -{ - cpu_irq_disable(); -} - -/** - * \brief Checks if an interrupt vector is enabled or not. - * - * Checks if a specific interrupt vector is currently enabled. - * - * \param[in] vector Interrupt vector number to check - * - * \returns A variable identifying if the requested interrupt vector is enabled. - * - * \retval true Specified interrupt vector is currently enabled - * \retval false Specified interrupt vector is currently disabled - * - */ -static inline bool system_interrupt_is_enabled( - const enum system_interrupt_vector vector) -{ - return (bool)((NVIC->ISER[0] >> (uint32_t)vector) & 0x00000001); -} - -/** - * \brief Enable interrupt vector. - * - * Enables execution of the software handler for the requested interrupt vector. - * - * \param[in] vector Interrupt vector to enable - */ -static inline void system_interrupt_enable( - const enum system_interrupt_vector vector) -{ - NVIC->ISER[0] = (uint32_t)(1 << ((uint32_t)vector & 0x0000001f)); -} - -/** - * \brief Disable interrupt vector. - * - * Disables execution of the software handler for the requested interrupt vector. - * - * \param[in] vector Interrupt vector to disable - */ -static inline void system_interrupt_disable( - const enum system_interrupt_vector vector) -{ - NVIC->ICER[0] = (uint32_t)(1 << ((uint32_t)vector & 0x0000001f)); -} - -/** @} */ - -/** - * \name Interrupt State Management - * @{ - */ - -/** - * \brief Get active interrupt (if any). - * - * Return the vector number for the current executing software handler, if any. - * - * \return Interrupt number that is currently executing. - */ -static inline enum system_interrupt_vector system_interrupt_get_active(void) -{ - uint32_t IPSR = __get_IPSR(); - /* The IPSR returns the Exception number, which with an offset 16 to IRQ number. */ - return (enum system_interrupt_vector)((IPSR & _SYSTEM_INTERRUPT_IPSR_MASK) - 16); -} - -bool system_interrupt_is_pending( - const enum system_interrupt_vector vector); - -enum status_code system_interrupt_set_pending( - const enum system_interrupt_vector vector); - -enum status_code system_interrupt_clear_pending( - const enum system_interrupt_vector vector); - -/** @} */ - -/** - * \name Interrupt Priority Management - * @{ - */ - -enum status_code system_interrupt_set_priority( - const enum system_interrupt_vector vector, - const enum system_interrupt_priority_level priority_level); - -enum system_interrupt_priority_level system_interrupt_get_priority( - const enum system_interrupt_vector vector); - -/** @} */ - -/** @} */ - -/** - * \page asfdoc_sam0_system_interrupt_extra Extra Information for SYSTEM INTERRUPT Driver - * - * \section asfdoc_sam0_system_interrupt_extra_acronyms Acronyms - * The table below presents the acronyms used in this module: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
AcronymDescription
ISRInterrupt Service Routine
NMINon-maskable Interrupt
SERCOMSerial Communication Interface
- * - * - * \section asfdoc_sam0_system_interrupt_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - None - * - * - * \section asfdoc_sam0_system_interrupt_extra_errata Errata - * There are no errata related to this driver. - * - * - * \section asfdoc_sam0_system_interrupt_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * - * - * - *
Changelog
Initial Release
- */ - -/** - * \page asfdoc_sam0_system_interrupt_exqsg Examples for SYSTEM INTERRUPT Driver - * - * This is a list of the available Quick Start guides (QSGs) and example - * applications for \ref asfdoc_sam0_system_interrupt_group. QSGs are simple examples with - * step-by-step instructions to configure and use this driver in a selection of - * use cases. Note that a QSG can be compiled as a standalone application or be - * added to the user application. - * - * - \subpage asfdoc_sam0_system_interrupt_critsec_use_case - * - \subpage asfdoc_sam0_system_interrupt_enablemodint_use_case - * - * \page asfdoc_sam0_system_interrupt_document_revision_history Document Revision History - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Doc. Rev. - * Date - * Comments - *
42122E08/2015Added support for SAM L21/L22, SAM DA1, and SAM C20/C21
42122D12/2014Added support for SAM R21 and SAM D10/D11
42122C01/2014Added support for SAM D21
42122B06/2013Corrected documentation typos
42122A06/2013Initial release
- */ - -#ifdef __cplusplus -} -#endif - -#endif // #ifndef SYSTEM_INTERRUPT_H_INCLUDED diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system_interrupt_features.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system_interrupt_features.h deleted file mode 100644 index 25dfa83..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/system_interrupt_features.h +++ /dev/null @@ -1,195 +0,0 @@ -/** - * \file - * - * \brief SAM D21 System Interrupt Driver - * - * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#ifndef SYSTEM_INTERRUPT_FEATURES_H_INCLUDED -#define SYSTEM_INTERRUPT_FEATURES_H_INCLUDED - -#if !defined(__DOXYGEN__) - -/* Generates a interrupt vector table enum list entry for a given module type - and index (e.g. "SYSTEM_INTERRUPT_MODULE_TC0 = TC0_IRQn,"). */ -# define _MODULE_IRQn(n, module) \ - SYSTEM_INTERRUPT_MODULE_##module##n = module##n##_IRQn, - -/* Generates interrupt vector table enum list entries for all instances of a - given module type on the selected device. */ -# define _SYSTEM_INTERRUPT_MODULES(name) \ - MREPEAT(name##_INST_NUM, _MODULE_IRQn, name) - -# define _SYSTEM_INTERRUPT_IPSR_MASK 0x0000003f -# define _SYSTEM_INTERRUPT_PRIORITY_MASK 0x00000003 - -# define _SYSTEM_INTERRUPT_EXTERNAL_VECTOR_START 0 - -# define _SYSTEM_INTERRUPT_SYSTICK_PRI_POS 30 -#endif - -/** - * \addtogroup asfdoc_sam0_system_interrupt_group - * @{ - */ - -/** - * \brief Table of possible system interrupt/exception vector numbers. - * - * Table of all possible interrupt and exception vector indexes within the - * SAM D21 device. Check peripherals configuration in SAM D21 datasheet for - * available vector index for specific device. - * - */ -#if defined(__DOXYGEN__) -/** \note The actual enumeration name is "system_interrupt_vector". */ -enum system_interrupt_vector_samd21 { -#else -enum system_interrupt_vector { -#endif - /** Interrupt vector index for a NMI interrupt */ - SYSTEM_INTERRUPT_NON_MASKABLE = NonMaskableInt_IRQn, - /** Interrupt vector index for a Hard Fault memory access exception */ - SYSTEM_INTERRUPT_HARD_FAULT = HardFault_IRQn, - /** Interrupt vector index for a Supervisor Call exception */ - SYSTEM_INTERRUPT_SV_CALL = SVCall_IRQn, - /** Interrupt vector index for a Pending Supervisor interrupt */ - SYSTEM_INTERRUPT_PENDING_SV = PendSV_IRQn, - /** Interrupt vector index for a System Tick interrupt */ - SYSTEM_INTERRUPT_SYSTICK = SysTick_IRQn, - - /** Interrupt vector index for a Power Manager peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_PM = PM_IRQn, - /** Interrupt vector index for a System Control peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_SYSCTRL = SYSCTRL_IRQn, - /** Interrupt vector index for a Watch Dog peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_WDT = WDT_IRQn, - /** Interrupt vector index for a Real Time Clock peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_RTC = RTC_IRQn, - /** Interrupt vector index for an External Interrupt peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_EIC = EIC_IRQn, - /** Interrupt vector index for a Non Volatile Memory Controller interrupt */ - SYSTEM_INTERRUPT_MODULE_NVMCTRL = NVMCTRL_IRQn, - /** Interrupt vector index for a Direct Memory Access interrupt */ - SYSTEM_INTERRUPT_MODULE_DMA = DMAC_IRQn, -#if defined(__DOXYGEN__) || defined(ID_USB) - /** Interrupt vector index for a Universal Serial Bus interrupt */ - SYSTEM_INTERRUPT_MODULE_USB = USB_IRQn, -#endif - /** Interrupt vector index for an Event System interrupt */ - SYSTEM_INTERRUPT_MODULE_EVSYS = EVSYS_IRQn, -#if defined(__DOXYGEN__) - /** Interrupt vector index for a SERCOM peripheral interrupt. - * - * Each specific device may contain several SERCOM peripherals; each module - * instance will have its own entry in the table, with the instance number - * substituted for "n" in the entry name (e.g. - * \c SYSTEM_INTERRUPT_MODULE_SERCOM0). - */ - SYSTEM_INTERRUPT_MODULE_SERCOMn = SERCOMn_IRQn, - - /** Interrupt vector index for a Timer/Counter Control peripheral interrupt. - * - * Each specific device may contain several TCC peripherals; each module - * instance will have its own entry in the table, with the instance number - * substituted for "n" in the entry name (e.g. - * \c SYSTEM_INTERRUPT_MODULE_TCC0). - */ - SYSTEM_INTERRUPT_MODULE_TCCn = TCCn_IRQn, - - /** Interrupt vector index for a Timer/Counter peripheral interrupt. - * - * Each specific device may contain several TC peripherals; each module - * instance will have its own entry in the table, with the instance number - * substituted for "n" in the entry name (e.g. - * \c SYSTEM_INTERRUPT_MODULE_TC3). - */ - SYSTEM_INTERRUPT_MODULE_TCn = TCn_IRQn, -#else - _SYSTEM_INTERRUPT_MODULES(SERCOM) - - _SYSTEM_INTERRUPT_MODULES(TCC) - - SYSTEM_INTERRUPT_MODULE_TC3 = TC3_IRQn, - SYSTEM_INTERRUPT_MODULE_TC4 = TC4_IRQn, - SYSTEM_INTERRUPT_MODULE_TC5 = TC5_IRQn, -# if defined(ID_TC6) - SYSTEM_INTERRUPT_MODULE_TC6 = TC6_IRQn, -# endif -# if defined(ID_TC7) - SYSTEM_INTERRUPT_MODULE_TC7 = TC7_IRQn, -# endif -#endif - -#if defined(__DOXYGEN__) || defined(ID_ADC) - /** Interrupt vector index for an Analog-to-Digital peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_ADC = ADC_IRQn, -#endif - -#if defined(__DOXYGEN__) || defined(ID_AC) - /** Interrupt vector index for an Analog Comparator peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_AC = AC_IRQn, -#endif - -#if defined(__DOXYGEN__) || defined(ID_DAC) - /** Interrupt vector index for a Digital-to-Analog peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_DAC = DAC_IRQn, -#endif -#if defined(__DOXYGEN__) || defined(ID_PTC) - /** Interrupt vector index for a Peripheral Touch Controller peripheral - * interrupt */ - SYSTEM_INTERRUPT_MODULE_PTC = PTC_IRQn, -#endif -#if defined(__DOXYGEN__) || defined(ID_I2S) - /** Interrupt vector index for a Inter-IC Sound Interface peripheral - * interrupt */ - SYSTEM_INTERRUPT_MODULE_I2S = I2S_IRQn, -#endif -#if defined(__DOXYGEN__) || defined(ID_AC1) - /** Interrupt vector index for an Analog Comparator 1 peripheral interrupt */ - SYSTEM_INTERRUPT_MODULE_AC1 = AC1_IRQn, -#endif -}; - -/** @} */ - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc.c deleted file mode 100644 index 23e2703..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc.c +++ /dev/null @@ -1,685 +0,0 @@ -/** - * \file - * - * \brief SAM TC - Timer Counter Driver - * - * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#include "tc.h" - -#if TC_ASYNC == true -# include "tc_interrupt.h" -# include - -/** \internal - * Converts a given TC index to its interrupt vector index. - */ -# define _TC_INTERRUPT_VECT_NUM(n, unused) \ - SYSTEM_INTERRUPT_MODULE_TC##n, -#endif - -#if !defined(__DOXYGEN__) -# define _TC_GCLK_ID(n,unused) TPASTE3(TC,n,_GCLK_ID) , -# define _TC_PM_APBCMASK(n,unused) TPASTE2(PM_APBCMASK_TC,n) , - -# define TC_INST_GCLK_ID { MRECURSION(TC_INST_NUM, _TC_GCLK_ID, TC_INST_MAX_ID) } -# define TC_INST_PM_APBCMASK { MRECURSION(TC_INST_NUM, _TC_PM_APBCMASK, TC_INST_MAX_ID) } - -#endif - -/** - * \internal Find the index of given TC module instance. - * - * \param[in] TC module instance pointer. - * - * \return Index of the given TC module instance. - */ -uint8_t _tc_get_inst_index( - Tc *const hw) -{ - /* List of available TC modules. */ - Tc *const tc_modules[TC_INST_NUM] = TC_INSTS; - - /* Find index for TC instance. */ - for (uint32_t i = 0; i < TC_INST_NUM; i++) { - if (hw == tc_modules[i]) { - return i; - } - } - - /* Invalid data given. */ - Assert(false); - return 0; -} - - -/** - * \brief Initializes a hardware TC module instance. - * - * Enables the clock and initializes the TC module, based on the given - * configuration values. - * - * \param[in,out] module_inst Pointer to the software module instance struct - * \param[in] hw Pointer to the TC hardware module - * \param[in] config Pointer to the TC configuration options struct - * - * \return Status of the initialization procedure. - * - * \retval STATUS_OK The module was initialized successfully - * \retval STATUS_BUSY Hardware module was busy when the - * initialization procedure was attempted - * \retval STATUS_INVALID_ARG An invalid configuration option or argument - * was supplied - * \retval STATUS_ERR_DENIED Hardware module was already enabled, or the - * hardware module is configured in 32-bit - * slave mode - */ -enum status_code tc_init( - struct tc_module *const module_inst, - Tc *const hw, - const struct tc_config *const config) -{ - /* Sanity check arguments */ - Assert(hw); - Assert(module_inst); - Assert(config); - - /* Temporary variable to hold all updates to the CTRLA - * register before they are written to it */ - uint16_t ctrla_tmp = 0; - /* Temporary variable to hold all updates to the CTRLBSET - * register before they are written to it */ - uint8_t ctrlbset_tmp = 0; - /* Temporary variable to hold all updates to the CTRLC - * register before they are written to it */ - uint8_t ctrlc_tmp = 0; - /* Temporary variable to hold TC instance number */ - uint8_t instance = _tc_get_inst_index(hw); - - /* Array of GLCK ID for different TC instances */ - uint8_t inst_gclk_id[] = TC_INST_GCLK_ID; - /* Array of PM APBC mask bit position for different TC instances */ - uint16_t inst_pm_apbmask[] = TC_INST_PM_APBCMASK; - - struct system_pinmux_config pin_config; - struct system_gclk_chan_config gclk_chan_config; - -#if TC_ASYNC == true - /* Initialize parameters */ - for (uint8_t i = 0; i < TC_CALLBACK_N; i++) { - module_inst->callback[i] = NULL; - } - module_inst->register_callback_mask = 0x00; - module_inst->enable_callback_mask = 0x00; - - /* Register this instance for callbacks*/ - _tc_instances[instance] = module_inst; -#endif - - /* Associate the given device instance with the hardware module */ - module_inst->hw = hw; - -#if SAMD09 || SAMD10 || SAMD11 - /* Check if even numbered TC modules are being configured in 32-bit - * counter size. Only odd numbered counters are allowed to be - * configured in 32-bit counter size. - */ - if ((config->counter_size == TC_COUNTER_SIZE_32BIT) && - !((instance + TC_INSTANCE_OFFSET) & 0x01)) { - Assert(false); - return STATUS_ERR_INVALID_ARG; - } -#else - /* Check if odd numbered TC modules are being configured in 32-bit - * counter size. Only even numbered counters are allowed to be - * configured in 32-bit counter size. - */ - if ((config->counter_size == TC_COUNTER_SIZE_32BIT) && - ((instance + TC_INSTANCE_OFFSET) & 0x01)) { - Assert(false); - return STATUS_ERR_INVALID_ARG; - } -#endif - - /* Make the counter size variable in the module_inst struct reflect - * the counter size in the module - */ - module_inst->counter_size = config->counter_size; - - if (hw->COUNT8.CTRLA.reg & TC_CTRLA_SWRST) { - /* We are in the middle of a reset. Abort. */ - return STATUS_BUSY; - } - - if (hw->COUNT8.STATUS.reg & TC_STATUS_SLAVE) { - /* Module is used as a slave */ - return STATUS_ERR_DENIED; - } - - if (hw->COUNT8.CTRLA.reg & TC_CTRLA_ENABLE) { - /* Module must be disabled before initialization. Abort. */ - return STATUS_ERR_DENIED; - } - - /* Set up the TC PWM out pin for channel 0 */ - if (config->pwm_channel[0].enabled) { - system_pinmux_get_config_defaults(&pin_config); - pin_config.mux_position = config->pwm_channel[0].pin_mux; - pin_config.direction = SYSTEM_PINMUX_PIN_DIR_OUTPUT; - system_pinmux_pin_set_config( - config->pwm_channel[0].pin_out, &pin_config); - } - - /* Set up the TC PWM out pin for channel 1 */ - if (config->pwm_channel[1].enabled) { - system_pinmux_get_config_defaults(&pin_config); - pin_config.mux_position = config->pwm_channel[1].pin_mux; - pin_config.direction = SYSTEM_PINMUX_PIN_DIR_OUTPUT; - system_pinmux_pin_set_config( - config->pwm_channel[1].pin_out, &pin_config); - } - - /* Enable the user interface clock in the PM */ - system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, - inst_pm_apbmask[instance]); - - /* Enable the slave counter if counter_size is 32-bit */ - if ((config->counter_size == TC_COUNTER_SIZE_32BIT)) - { - /* Enable the user interface clock in the PM */ - system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBC, - inst_pm_apbmask[instance + 1]); - } - - /* Setup clock for module */ - system_gclk_chan_get_config_defaults(&gclk_chan_config); - gclk_chan_config.source_generator = config->clock_source; - system_gclk_chan_set_config(inst_gclk_id[instance], &gclk_chan_config); - system_gclk_chan_enable(inst_gclk_id[instance]); - - /* Set ctrla register */ - ctrla_tmp = - (uint32_t)config->counter_size | - (uint32_t)config->wave_generation | - (uint32_t)config->reload_action | - (uint32_t)config->clock_prescaler; - - if (config->run_in_standby) { - ctrla_tmp |= TC_CTRLA_RUNSTDBY; - } - - /* Write configuration to register */ - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - hw->COUNT8.CTRLA.reg = ctrla_tmp; - - /* Set ctrlb register */ - if (config->oneshot) { - ctrlbset_tmp = TC_CTRLBSET_ONESHOT; - } - - if (config->count_direction) { - ctrlbset_tmp |= TC_CTRLBSET_DIR; - } - - /* Clear old ctrlb configuration */ - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - hw->COUNT8.CTRLBCLR.reg = 0xFF; - - /* Check if we actually need to go into a wait state. */ - if (ctrlbset_tmp) { - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - /* Write configuration to register */ - hw->COUNT8.CTRLBSET.reg = ctrlbset_tmp; - } - - /* Set ctrlc register*/ - ctrlc_tmp = config->waveform_invert_output; - for (uint8_t i = 0; i < NUMBER_OF_COMPARE_CAPTURE_CHANNELS; i++) { - if (config->enable_capture_on_channel[i] == true) { - ctrlc_tmp |= (TC_CTRLC_CPTEN(1) << i); - } - } - - /* Write configuration to register */ - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - hw->COUNT8.CTRLC.reg = ctrlc_tmp; - - /* Write configuration to register */ - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Switch for TC counter size */ - switch (module_inst->counter_size) { - case TC_COUNTER_SIZE_8BIT: - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT8.COUNT.reg = - config->counter_8_bit.value; - - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT8.PER.reg = - config->counter_8_bit.period; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT8.CC[0].reg = - config->counter_8_bit.compare_capture_channel[0]; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT8.CC[1].reg = - config->counter_8_bit.compare_capture_channel[1]; - - return STATUS_OK; - - case TC_COUNTER_SIZE_16BIT: - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT16.COUNT.reg - = config->counter_16_bit.value; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT16.CC[0].reg = - config->counter_16_bit.compare_capture_channel[0]; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT16.CC[1].reg = - config->counter_16_bit.compare_capture_channel[1]; - - return STATUS_OK; - - case TC_COUNTER_SIZE_32BIT: - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT32.COUNT.reg - = config->counter_32_bit.value; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT32.CC[0].reg = - config->counter_32_bit.compare_capture_channel[0]; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - hw->COUNT32.CC[1].reg = - config->counter_32_bit.compare_capture_channel[1]; - - return STATUS_OK; - } - - Assert(false); - return STATUS_ERR_INVALID_ARG; -} - -/** - * \brief Sets TC module count value. - * - * Sets the current timer count value of a initialized TC module. The - * specified TC module may be started or stopped. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] count New timer count value to set - * - * \return Status of the count update procedure. - * - * \retval STATUS_OK The timer count was updated successfully - * \retval STATUS_ERR_INVALID_ARG An invalid timer counter size was specified - */ -enum status_code tc_set_count_value( - const struct tc_module *const module_inst, - const uint32_t count) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance*/ - Tc *const tc_module = module_inst->hw; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Write to based on the TC counter_size */ - switch (module_inst->counter_size) { - case TC_COUNTER_SIZE_8BIT: - tc_module->COUNT8.COUNT.reg = (uint8_t)count; - return STATUS_OK; - - case TC_COUNTER_SIZE_16BIT: - tc_module->COUNT16.COUNT.reg = (uint16_t)count; - return STATUS_OK; - - case TC_COUNTER_SIZE_32BIT: - tc_module->COUNT32.COUNT.reg = (uint32_t)count; - return STATUS_OK; - - default: - return STATUS_ERR_INVALID_ARG; - } -} - -/** - * \brief Get TC module count value. - * - * Retrieves the current count value of a TC module. The specified TC module - * may be started or stopped. - * - * \param[in] module_inst Pointer to the software module instance struct - * - * \return Count value of the specified TC module. - */ -uint32_t tc_get_count_value( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - Tc *const tc_module = module_inst->hw; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Read from based on the TC counter size */ - switch (module_inst->counter_size) { - case TC_COUNTER_SIZE_8BIT: - return (uint32_t)tc_module->COUNT8.COUNT.reg; - - case TC_COUNTER_SIZE_16BIT: - return (uint32_t)tc_module->COUNT16.COUNT.reg; - - case TC_COUNTER_SIZE_32BIT: - return tc_module->COUNT32.COUNT.reg; - } - - Assert(false); - return 0; -} - -/** - * \brief Gets the TC module capture value. - * - * Retrieves the capture value in the indicated TC module capture channel. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] channel_index Index of the Compare Capture channel to read - * - * \return Capture value stored in the specified timer channel. - */ -uint32_t tc_get_capture_value( - const struct tc_module *const module_inst, - const enum tc_compare_capture_channel channel_index) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - Tc *const tc_module = module_inst->hw; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Read out based on the TC counter size */ - switch (module_inst->counter_size) { - case TC_COUNTER_SIZE_8BIT: - if (channel_index < - NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { - return tc_module->COUNT8.CC[channel_index].reg; - } - - case TC_COUNTER_SIZE_16BIT: - if (channel_index < - NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { - return tc_module->COUNT16.CC[channel_index].reg; - } - - case TC_COUNTER_SIZE_32BIT: - if (channel_index < - NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { - return tc_module->COUNT32.CC[channel_index].reg; - } - } - - Assert(false); - return 0; -} - -/** - * \brief Sets a TC module compare value. - * - * Writes a compare value to the given TC module compare/capture channel. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] channel_index Index of the compare channel to write to - * \param[in] compare New compare value to set - * - * \return Status of the compare update procedure. - * - * \retval STATUS_OK The compare value was updated successfully - * \retval STATUS_ERR_INVALID_ARG An invalid channel index was supplied - */ -enum status_code tc_set_compare_value( - const struct tc_module *const module_inst, - const enum tc_compare_capture_channel channel_index, - const uint32_t compare) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - Tc *const tc_module = module_inst->hw; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Read out based on the TC counter size */ - switch (module_inst->counter_size) { - case TC_COUNTER_SIZE_8BIT: - if (channel_index < - NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { - tc_module->COUNT8.CC[channel_index].reg = - (uint8_t)compare; - return STATUS_OK; - } - - case TC_COUNTER_SIZE_16BIT: - if (channel_index < - NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { - tc_module->COUNT16.CC[channel_index].reg = - (uint16_t)compare; - return STATUS_OK; - } - - case TC_COUNTER_SIZE_32BIT: - if (channel_index < - NUMBER_OF_COMPARE_CAPTURE_CHANNELS) { - tc_module->COUNT32.CC[channel_index].reg = - (uint32_t)compare; - return STATUS_OK; - } - } - - return STATUS_ERR_INVALID_ARG; -} - -/** - * \brief Resets the TC module. - * - * Resets the TC module, restoring all hardware module registers to their - * default values and disabling the module. The TC module will not be - * accessible while the reset is being performed. - * - * \note When resetting a 32-bit counter only the master TC module's instance - * structure should be passed to the function. - * - * \param[in] module_inst Pointer to the software module instance struct - * - * \return Status of the procedure. - * \retval STATUS_OK The module was reset successfully - * \retval STATUS_ERR_UNSUPPORTED_DEV A 32-bit slave TC module was passed to - * the function. Only use reset on master - * TC - */ -enum status_code tc_reset( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - if (tc_module->STATUS.reg & TC_STATUS_SLAVE) { - return STATUS_ERR_UNSUPPORTED_DEV; - } - - /* Disable this module if it is running */ - if (tc_module->CTRLA.reg & TC_CTRLA_ENABLE) { - tc_disable(module_inst); - while (tc_is_syncing(module_inst)) { - /* wait while module is disabling */ - } - } - - /* Reset this TC module */ - tc_module->CTRLA.reg |= TC_CTRLA_SWRST; - - return STATUS_OK; -} - -/** - * \brief Set the timer TOP/period value. - * - * For 8-bit counter size this function writes the top value to the period - * register. - * - * For 16- and 32-bit counter size this function writes the top value to - * Capture Compare register 0. The value in this register can not be used for - * any other purpose. - * - * \note This function is designed to be used in PWM or frequency - * match modes only. When the counter is set to 16- or 32-bit counter - * size. In 8-bit counter size it will always be possible to change the - * top value even in normal mode. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] top_value New timer TOP value to set - * - * \return Status of the TOP set procedure. - * - * \retval STATUS_OK The timer TOP value was updated successfully - * \retval STATUS_ERR_INVALID_ARG The configured TC module counter size in the - * module instance is invalid - */ -enum status_code tc_set_top_value ( - const struct tc_module *const module_inst, - const uint32_t top_value) -{ - Assert(module_inst); - Assert(module_inst->hw); - Assert(top_value); - - Tc *const tc_module = module_inst->hw; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - switch (module_inst->counter_size) { - case TC_COUNTER_SIZE_8BIT: - tc_module->COUNT8.PER.reg = (uint8_t)top_value; - return STATUS_OK; - - case TC_COUNTER_SIZE_16BIT: - tc_module->COUNT16.CC[0].reg = (uint16_t)top_value; - return STATUS_OK; - - case TC_COUNTER_SIZE_32BIT: - tc_module->COUNT32.CC[0].reg = (uint32_t)top_value; - return STATUS_OK; - - default: - Assert(false); - return STATUS_ERR_INVALID_ARG; - } -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc.h deleted file mode 100644 index 0ee7006..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc.h +++ /dev/null @@ -1,1783 +0,0 @@ -/** - * \file - * - * \brief SAM TC - Timer Counter Driver - * - * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ - -#ifndef TC_H_INCLUDED -#define TC_H_INCLUDED - -/** - * \defgroup asfdoc_sam0_tc_group SAM Timer/Counter Driver (TC) - * - * This driver for Atmel® | SMART ARM®-based microcontrollers provides an interface for the configuration - * and management of the timer modules within the device, for waveform - * generation and timing operations. The following driver API modes are covered - * by this manual: - * - * - Polled APIs - * \if TC_CALLBACK_MODE - * - Callback APIs - * \endif - * - * - * The following peripherals are used by this module: - * - TC (Timer/Counter) - * - * The following devices can use this module: - * - Atmel | SMART SAM D20/D21 - * - Atmel | SMART SAM R21 - * - Atmel | SMART SAM D09/D10/D11 - * - Atmel | SMART SAM L21/L22 - * - Atmel | SMART SAM DA1 - * - Atmel | SMART SAM C20/C21 - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_tc_prerequisites - * - \ref asfdoc_sam0_tc_module_overview - * - \ref asfdoc_sam0_tc_special_considerations - * - \ref asfdoc_sam0_tc_extra_info - * - \ref asfdoc_sam0_tc_examples - * - \ref asfdoc_sam0_tc_api_overview - * - * - * \section asfdoc_sam0_tc_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * - * \section asfdoc_sam0_tc_module_overview Module Overview - * - * The Timer/Counter (TC) module provides a set of timing and counting related - * functionality, such as the generation of periodic waveforms, the capturing - * of a periodic waveform's frequency/duty cycle, and software timekeeping for - * periodic operations. TC modules can be configured to use an 8-, 16-, or - * 32-bit counter size. - * - * This TC module for the SAM is capable of the following functions: - * - * - Generation of PWM signals - * - Generation of timestamps for events - * - General time counting - * - Waveform period capture - * - Waveform frequency capture - * - * \ref asfdoc_sam0_tc_block_diagram "The diagram below" shows the overview - * of the TC module design. - * - * \anchor asfdoc_sam0_tc_block_diagram - * \image html overview.svg "Basic Overview of the TC Module" - * - * - * \subsection asfdoc_sam0_tc_features Driver Feature Macro Definition - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Driver Feature MacroSupported devices
FEATURE_TC_DOUBLE_BUFFEREDSAM L21/L22/C20/C21
FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2SAM L21/L22/C20/C21
FEATURE_TC_STAMP_PW_CAPTURESAM L21/L22/C20/C21
FEATURE_TC_READ_SYNCSAM L21/L22/C20/C21
FEATURE_TC_IO_CAPTURESAM L21/L22/C20/C21
FEATURE_TC_GENERATE_DMA_TRIGGERSAM L21/L22
- * \note The specific features are only available in the driver when the - * selected device supports those features. - * - * \subsection asfdoc_sam0_tc_module_overview_func_desc Functional Description - * Independent of the configured counter size, each TC module can be set up - * in one of two different modes; capture and compare. - * - * In capture mode, the counter value is stored when a configurable event - * occurs. This mode can be used to generate timestamps used in event capture, - * or it can be used for the measurement of a periodic input signal's - * frequency/duty cycle. - * - * In compare mode, the counter value is compared against one or more of the - * configured channel compare values. When the counter value coincides with a - * compare value an action can be taken automatically by the module, such as - * generating an output event or toggling a pin when used for frequency or PWM - * signal generation. - * - * \note The connection of events between modules requires the use of the - * \ref asfdoc_sam0_events_group "SAM Event System Driver (EVENTS)" - * to route output event of one module to the input event of another. - * For more information on event routing, refer to the event driver - * documentation. - * - * \subsection asfdoc_sam0_tc_module_overview_tc_size Timer/Counter Size - * Each timer module can be configured in one of three different counter - * sizes; 8-, 16-, and 32-bit. The size of the counter determines the maximum - * value it can count to before an overflow occurs and the count is reset back - * to zero. \ref asfdoc_sam0_tc_count_size_vs_top "The table below" shows the - * maximum values for each of the possible counter sizes. - * - * \anchor asfdoc_sam0_tc_count_size_vs_top - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Timer Counter Sizes and Their Maximum Count Values
Counter sizeMax. (hexadecimal)Max. (decimal)
8-bit0xFF255
16-bit0xFFFF65,535
32-bit0xFFFFFFFF4,294,967,295
- * - * When using the counter in 16- or 32-bit count mode, Compare Capture - * register 0 (CC0) is used to store the period value when running in PWM - * generation match mode. - * - * When using 32-bit counter size, two 16-bit counters are chained together - * in a cascade formation. Except in SAM D09/D10/D11, Even numbered TC modules - * (e.g. TC0, TC2) can be configured as 32-bit counters. The odd numbered - * counters will act as slaves to the even numbered masters, and will not - * be reconfigurable until the master timer is disabled. The pairing of timer - * modules for 32-bit mode is shown in \ref asfdoc_sam0_tc_module_ms_pairs - * "the table below". - * - * \anchor asfdoc_sam0_tc_module_ms_pairs - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
TC Master and Slave Module Pairings
Master TC ModuleSlave TC Module
TC0TC1
TC2TC3
......
TCn-1TCn
- * - * In SAM D09/D10/D11, odd numbered TC modules (e.g. TC1) can be configured as 32-bit - * counters. The even numbered(e.g. TC2) counters will act as slaves to the odd - * numbered masters. - * - * \subsection asfdoc_sam0_tc_module_overview_clock Clock Settings - * - * \subsubsection asfdoc_sam0_tc_module_overview_clock_selection Clock Selection - * Each TC peripheral is clocked asynchronously to the system clock by a GCLK - * (Generic Clock) channel. The GCLK channel connects to any of the GCLK - * generators. The GCLK generators are configured to use one of the available - * clock sources on the system such as internal oscillator, external crystals, - * etc. see the \ref asfdoc_sam0_system_clock_group "Generic Clock driver" - *for - * more information. - * - * \subsubsection asfdoc_sam0_tc_module_overview_clock_prescaler Prescaler - * Each TC module in the SAM has its own individual clock prescaler, which - * can be used to divide the input clock frequency used in the counter. This - * prescaler only scales the clock used to provide clock pulses for the counter - * to count, and does not affect the digital register interface portion of - * the module, thus the timer registers will synchronize to the raw GCLK - * frequency input to the module. - * - * As a result of this, when selecting a GCLK frequency and timer prescaler - * value the user application should consider both the timer resolution - * required and the synchronization frequency, to avoid lengthy - * synchronization times of the module if a very slow GCLK frequency is fed - * into the TC module. It is preferable to use a higher module GCLK frequency - * as the input to the timer, and prescale this down as much as possible to - * obtain a suitable counter frequency in latency-sensitive applications. - * - * \subsubsection asfdoc_sam0_tc_module_overview_clock_reloading Reloading - * Timer modules also contain a configurable reload action, used when a - * re-trigger event occurs. Examples of a re-trigger event are the counter - * reaching the maximum value when counting up, or when an event from the event - * system tells the counter to re-trigger. The reload action determines if the - * prescaler should be reset, and when this should happen. The counter will - * always be reloaded with the value it is set to start counting from. The user - * can choose between three different reload actions, described in - * \ref asfdoc_sam0_tc_module_reload_act "the table below". - * - * \anchor asfdoc_sam0_tc_module_reload_act - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
TC Module Reload Actions
Reload actionDescription
\ref TC_RELOAD_ACTION_GCLK Reload TC counter value on next GCLK cycle. Leave prescaler - * as-is.
\ref TC_RELOAD_ACTION_PRESC Reloads TC counter value on next prescaler clock. Leave prescaler - * as-is.
\ref TC_RELOAD_ACTION_RESYNC Reload TC counter value on next GCLK cycle. Clear prescaler to - * zero.
- * - * The reload action to use will depend on the specific application being - * implemented. One example is when an external trigger for a reload occurs; if - * the TC uses the prescaler, the counter in the prescaler should not have a - * value between zero and the division factor. The TC counter and the counter - * in the prescaler should both start at zero. When the counter is set to - * re-trigger when it reaches the maximum value on the other hand, this is not the - * right option to use. In such a case it would be better if the prescaler is - * left unaltered when the re-trigger happens, letting the counter reset on the - * next GCLK cycle. - * - * \subsection asfdoc_sam0_tc_module_overview_compare_match Compare Match Operations - * In compare match operation, Compare/Capture registers are used in comparison - * with the counter value. When the timer's count value matches the value of a - * compare channel, a user defined action can be taken. - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_timer Basic Timer - * - * A Basic Timer is a simple application where compare match operations is used - * to determine when a specific period has elapsed. In Basic Timer operations, - * one or more values in the module's Compare/Capture registers are used to - * specify the time (as a number of prescaled GCLK cycles) when an action should - * be taken by the microcontroller. This can be an Interrupt Service Routine - * (ISR), event generator via the event system, or a software flag that is - * polled via the user application. - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_wg Waveform Generation - * - * Waveform generation enables the TC module to generate square waves, or if - * combined with an external passive low-pass filter; analog waveforms. - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_wg_pwm Waveform Generation - PWM - * - * Pulse width modulation is a form of waveform generation and a signalling - * technique that can be useful in many situations. When PWM mode is used, - * a digital pulse train with a configurable frequency and duty cycle can be - * generated by the TC module and output to a GPIO pin of the device. - * - * Often PWM is used to communicate a control or information parameter to an - * external circuit or component. Differing impedances of the source generator - * and sink receiver circuits is less of an issue when using PWM compared to - * using an analog voltage value, as noise will not generally affect the - * signal's integrity to a meaningful extent. - * - * \ref asfdoc_sam0_tc_module_pwm_normal_diag "The figure below" illustrates - * operations and different states of the counter and its output when running - * the counter in PWM normal mode. As can be seen, the TOP value is unchanged - * and is set to MAX. The compare match value is changed at several points to - * illustrate the resulting waveform output changes. The PWM output is set to - * normal (i.e. non-inverted) output mode. - * - * \anchor asfdoc_sam0_tc_module_pwm_normal_diag - * \image html pwm_normal_ex.svg "Example of PWM in Normal Mode, and Different Counter Operations" - * - * - * In \ref asfdoc_sam0_tc_module_pwm_match_diag "the figure below", the - * counter is set to generate PWM in Match mode. The PWM output is inverted via - * the appropriate configuration option in the TC driver configuration - * structure. In this example, the counter value is changed once, but the - * compare match value is kept unchanged. As can be seen, it is possible to - * change the TOP value when running in PWM match mode. - * - * \anchor asfdoc_sam0_tc_module_pwm_match_diag - * \image html pwm_match_ex.svg "Example of PWM in Match Mode, and Different Counter Operations" - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_wg_freq Waveform Generation - Frequency - * - * Frequency Generation mode is in many ways identical to PWM - * generation. However, in Frequency Generation a toggle only occurs - * on the output when a match on a capture channels occurs. When the - * match is made, the timer value is reset, resulting in a variable - * frequency square wave with a fixed 50% duty cycle. - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_capt Capture Operations - * - * In capture operations, any event from the event system or a pin change can - * trigger a capture of the counter value. This captured counter value can be - * used as a timestamp for the event, or it can be used in frequency and pulse - * width capture. - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_capt_event_capture Capture Operations - Event - * - * Event capture is a simple use of the capture functionality, - * designed to create timestamps for specific events. When the TC - * module's input capture pin is externally toggled, the current timer - * count value is copied into a buffered register which can then be - * read out by the user application. - * - * Note that when performing any capture operation, there is a risk that the - * counter reaches its top value (MAX) when counting up, or the bottom value - * (zero) when counting down, before the capture event occurs. This can distort - * the result, making event timestamps to appear shorter than reality; the - * user application should check for timer overflow when reading a capture - * result in order to detect this situation and perform an appropriate - * adjustment. - * - * Before checking for a new capture, \ref TC_STATUS_COUNT_OVERFLOW - * should be checked. The response to an overflow error is left to the user - * application, however it may be necessary to clear both the capture overflow - * flag and the capture flag upon each capture reading. - * - * \subsubsection asfdoc_sam0_tc_module_overview_compare_match_capt_pwc Capture Operations - Pulse Width - * - * Pulse Width Capture mode makes it possible to measure the pulse width and - * period of PWM signals. This mode uses two capture channels of the counter. - * This means that the counter module used for Pulse Width Capture can not be - * used for any other purpose. There are two modes for pulse width capture; - * Pulse Width Period (PWP) and Period Pulse Width (PPW). In PWP mode, capture - * channel 0 is used for storing the pulse width and capture channel 1 stores - * the observed period. While in PPW mode, the roles of the two capture channels - * is reversed. - * - * As in the above example it is necessary to poll on interrupt flags to see - * if a new capture has happened and check that a capture overflow error has - * not occurred. - * - * \subsection asfdoc_sam0_tc_module_overview_oneshot One-shot Mode - * - * TC modules can be configured into a one-shot mode. When configured in this - * manner, starting the timer will cause it to count until the next overflow - * or underflow condition before automatically halting, waiting to be manually - * triggered by the user application software or an event signal from the event - * system. - * - * \subsubsection asfdoc_sam0_tc_module_overview_inversion Wave Generation Output Inversion - * - * The output of the wave generation can be inverted by hardware if desired, - * resulting in the logically inverted value being output to the configured - * device GPIO pin. - * - * - * \section asfdoc_sam0_tc_special_considerations Special Considerations - * - * The number of capture compare registers in each TC module is dependent on - * the specific SAM device being used, and in some cases the counter size. - * - * The maximum amount of capture compare registers available in any SAM - * device is two when running in 32-bit mode and four in 8- and 16-bit modes. - * - * - * \section asfdoc_sam0_tc_extra_info Extra Information - * - * For extra information, see \ref asfdoc_sam0_tc_extra. This includes: - * - \ref asfdoc_sam0_tc_extra_acronyms - * - \ref asfdoc_sam0_tc_extra_dependencies - * - \ref asfdoc_sam0_tc_extra_errata - * - \ref asfdoc_sam0_tc_extra_history - * - * - * \section asfdoc_sam0_tc_examples Examples - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_tc_exqsg. - * - * \section asfdoc_sam0_tc_api_overview API Overview - * @{ - */ - -#include "compiler.h" -#include "clock.h" -#include "gclk.h" -#include "pinmux.h" - -// fix for Arduino zero -#if defined(__SAMD21G18A__) - #define SAMD21 1 - #define SAMD21G 1 - #define TC_ASYNC 1 -#endif - -// fix for Trinket/Gemma M0 -#if defined(__SAMD21E18A__) - #define SAMD21 1 - #define SAMD21E 1 - #define TC_ASYNC 1 -#endif - -/** - * Define port features set according to different device family - * @{ -*/ -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) || defined(__DOXYGEN__) -/** TC double buffered. */ -# define FEATURE_TC_DOUBLE_BUFFERED -/** SYNCBUSY scheme version 2. */ -# define FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2 -/** TC time stamp capture and pulse width capture. */ -# define FEATURE_TC_STAMP_PW_CAPTURE -/** Read synchronization of COUNT. */ -# define FEATURE_TC_READ_SYNC -/** IO pin edge capture. */ -# define FEATURE_TC_IO_CAPTURE -#endif - -#if (SAML21XXXB) || defined(__DOXYGEN__) -/** Generate DMA triggers*/ -# define FEATURE_TC_GENERATE_DMA_TRIGGER -#endif -/*@}*/ - -#if !defined(__DOXYGEN__) -#if SAMD20 || SAML21 || SAML22 || SAMC20 || SAMC21 -# define TC_INSTANCE_OFFSET 0 -#endif -#if SAMD21 || SAMR21 || SAMDA1 -# define TC_INSTANCE_OFFSET 3 -#endif -#if SAMD09 || SAMD10 || SAMD11 -# define TC_INSTANCE_OFFSET 1 -#endif - -#if SAMD20 -# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC0_CC8_NUM -#elif SAML21 || SAML22 || SAMC20 || SAMC21 -# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC0_CC_NUM -#elif SAMD09 || SAMD10 || SAMD11 -# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC1_CC8_NUM -#else -# define NUMBER_OF_COMPARE_CAPTURE_CHANNELS TC3_CC8_NUM - /* Same number for 8-, 16- and 32-bit TC and all TC instances */ -#endif - -/** TC Instance MAX ID Number. */ -#if SAMD20E || SAMD21G || SAMD21E || SAMR21 -# if SAMD21GXXL -# define TC_INST_MAX_ID 7 -# else -# define TC_INST_MAX_ID 5 -# endif -#elif SAML21 || SAMC20 || SAMC21 -# define TC_INST_MAX_ID 4 -#elif SAML22 -# define TC_INST_MAX_ID 3 -#elif SAMD09 || SAMD10 || SAMD11 -# define TC_INST_MAX_ID 2 -#else -# define TC_INST_MAX_ID 7 -#endif - -#endif - -#if TC_ASYNC == true -# include "system_interrupt.h" -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#if TC_ASYNC == true -/** Enum for the possible callback types for the TC module. */ -enum tc_callback { - /** Callback for TC overflow. */ - TC_CALLBACK_OVERFLOW, - /** Callback for capture overflow error. */ - TC_CALLBACK_ERROR, - /** Callback for capture compare channel 0. */ - TC_CALLBACK_CC_CHANNEL0, - /** Callback for capture compare channel 1. */ - TC_CALLBACK_CC_CHANNEL1, -# if !defined(__DOXYGEN__) - /** Number of available callbacks. */ - TC_CALLBACK_N, -# endif -}; -#endif - -/** - * \name Module Status Flags - * - * TC status flags, returned by \ref tc_get_status() and cleared by - * \ref tc_clear_status(). - * - * @{ - */ - -/** Timer channel 0 has matched against its compare value, or has captured a - * new value. - */ -#define TC_STATUS_CHANNEL_0_MATCH (1UL << 0) - -/** Timer channel 1 has matched against its compare value, or has captured a - * new value. - */ -#define TC_STATUS_CHANNEL_1_MATCH (1UL << 1) - -/** Timer register synchronization has completed, and the synchronized count - * value may be read. - */ -#define TC_STATUS_SYNC_READY (1UL << 2) - -/** A new value was captured before the previous value was read, resulting in - * lost data. - */ -#define TC_STATUS_CAPTURE_OVERFLOW (1UL << 3) - -/** The timer count value has overflowed from its maximum value to its minimum - * when counting upward, or from its minimum value to its maximum when - * counting downward. - */ -#define TC_STATUS_COUNT_OVERFLOW (1UL << 4) - -#ifdef FEATURE_TC_DOUBLE_BUFFERED -/** Channel 0 compare or capture buffer valid. */ -#define TC_STATUS_CHN0_BUFFER_VALID (1UL << 5) -/** Channel 1 compare or capture buffer valid. */ -#define TC_STATUS_CHN1_BUFFER_VALID (1UL << 6) -/** Period buffer valid. */ -#define TC_STATUS_PERIOD_BUFFER_VALID (1UL << 7) -#endif -/** @} */ - -/** - * \brief Index of the compare capture channels. - * - * This enum is used to specify which capture/compare channel to do - * operations on. - */ -enum tc_compare_capture_channel { - /** Index of compare capture channel 0. */ - TC_COMPARE_CAPTURE_CHANNEL_0, - /** Index of compare capture channel 1. */ - TC_COMPARE_CAPTURE_CHANNEL_1, -}; - -/** TC wave generation mode. */ -#if SAML21 || SAML22 || SAMC20 || SAMC21 -#define TC_WAVE_GENERATION_NORMAL_FREQ_MODE TC_WAVE_WAVEGEN_NFRQ -#define TC_WAVE_GENERATION_MATCH_FREQ_MODE TC_WAVE_WAVEGEN_MFRQ -#define TC_WAVE_GENERATION_NORMAL_PWM_MODE TC_WAVE_WAVEGEN_NPWM -#define TC_WAVE_GENERATION_MATCH_PWM_MODE TC_WAVE_WAVEGEN_MPWM -#else -#define TC_WAVE_GENERATION_NORMAL_FREQ_MODE TC_CTRLA_WAVEGEN_NFRQ -#define TC_WAVE_GENERATION_MATCH_FREQ_MODE TC_CTRLA_WAVEGEN_MFRQ -#define TC_WAVE_GENERATION_NORMAL_PWM_MODE TC_CTRLA_WAVEGEN_NPWM -#define TC_WAVE_GENERATION_MATCH_PWM_MODE TC_CTRLA_WAVEGEN_MPWM -#endif - -/** - * \brief TC wave generation mode enum. - * - * This enum is used to select which mode to run the wave - * generation in. - * - */ -enum tc_wave_generation { - /** Top is maximum, except in 8-bit counter size where it is the PER - * register. - */ - TC_WAVE_GENERATION_NORMAL_FREQ = TC_WAVE_GENERATION_NORMAL_FREQ_MODE, - - /** Top is CC0, except in 8-bit counter size where it is the PER - * register. - */ - TC_WAVE_GENERATION_MATCH_FREQ = TC_WAVE_GENERATION_MATCH_FREQ_MODE, - - /** Top is maximum, except in 8-bit counter size where it is the PER - * register. - */ - TC_WAVE_GENERATION_NORMAL_PWM = TC_WAVE_GENERATION_NORMAL_PWM_MODE, - - /** Top is CC0, except in 8-bit counter size where it is the PER - * register. - */ - TC_WAVE_GENERATION_MATCH_PWM = TC_WAVE_GENERATION_MATCH_PWM_MODE, -}; - -/** - * \brief Specifies if the counter is 8-, 16-, or 32-bit. - * - * This enum specifies the maximum value it is possible to count to. - */ -enum tc_counter_size { - /** The counter's maximum value is 0xFF, the period register is - * available to be used as top value. - */ - TC_COUNTER_SIZE_8BIT = TC_CTRLA_MODE_COUNT8, - - /** The counter's maximum value is 0xFFFF. There is no separate - * period register, to modify top one of the capture compare - * registers has to be used. This limits the amount of - * available channels. - */ - TC_COUNTER_SIZE_16BIT = TC_CTRLA_MODE_COUNT16, - - /** The counter's maximum value is 0xFFFFFFFF. There is no separate - * period register, to modify top one of the capture compare - * registers has to be used. This limits the amount of - * available channels. - */ - TC_COUNTER_SIZE_32BIT = TC_CTRLA_MODE_COUNT32, -}; - -/** - * \brief TC Counter reload action enum. - * - * This enum specify how the counter and prescaler should reload. - */ -enum tc_reload_action { - /** The counter is reloaded/reset on the next GCLK and starts - * counting on the prescaler clock. - */ - TC_RELOAD_ACTION_GCLK = TC_CTRLA_PRESCSYNC_GCLK, - - /** The counter is reloaded/reset on the next prescaler clock. - */ - TC_RELOAD_ACTION_PRESC = TC_CTRLA_PRESCSYNC_PRESC, - - /** The counter is reloaded/reset on the next GCLK, and the - * prescaler is restarted as well. - */ - TC_RELOAD_ACTION_RESYNC = TC_CTRLA_PRESCSYNC_RESYNC, -}; - -/** - * \brief TC clock prescaler values. - * - * This enum is used to choose the clock prescaler - * configuration. The prescaler divides the clock frequency of the TC - * module to make the counter count slower. - */ -enum tc_clock_prescaler { - /** Divide clock by 1. */ - TC_CLOCK_PRESCALER_DIV1 = TC_CTRLA_PRESCALER(0), - /** Divide clock by 2. */ - TC_CLOCK_PRESCALER_DIV2 = TC_CTRLA_PRESCALER(1), - /** Divide clock by 4. */ - TC_CLOCK_PRESCALER_DIV4 = TC_CTRLA_PRESCALER(2), - /** Divide clock by 8. */ - TC_CLOCK_PRESCALER_DIV8 = TC_CTRLA_PRESCALER(3), - /** Divide clock by 16. */ - TC_CLOCK_PRESCALER_DIV16 = TC_CTRLA_PRESCALER(4), - /** Divide clock by 64. */ - TC_CLOCK_PRESCALER_DIV64 = TC_CTRLA_PRESCALER(5), - /** Divide clock by 256. */ - TC_CLOCK_PRESCALER_DIV256 = TC_CTRLA_PRESCALER(6), - /** Divide clock by 1024. */ - TC_CLOCK_PRESCALER_DIV1024 = TC_CTRLA_PRESCALER(7), -}; - -/** - * \brief TC module count direction. - * - * Timer/Counter count direction. - */ -enum tc_count_direction { - /** Timer should count upward from zero to MAX. */ - TC_COUNT_DIRECTION_UP, - - /** Timer should count downward to zero from MAX. */ - TC_COUNT_DIRECTION_DOWN, -}; - -/** Waveform inversion mode. */ -#if SAML21 || SAML22 || SAMC20 || SAMC21 -#define TC_WAVEFORM_INVERT_CC0_MODE TC_DRVCTRL_INVEN(1) -#define TC_WAVEFORM_INVERT_CC1_MODE TC_DRVCTRL_INVEN(2) -#else -#define TC_WAVEFORM_INVERT_CC0_MODE TC_CTRLC_INVEN(1) -#define TC_WAVEFORM_INVERT_CC1_MODE TC_CTRLC_INVEN(2) -#endif - -/** - * \brief Waveform inversion mode. - * - * Output waveform inversion mode. - */ -enum tc_waveform_invert_output { - /** No inversion of the waveform output. */ - TC_WAVEFORM_INVERT_OUTPUT_NONE = 0, - /** Invert output from compare channel 0. */ - TC_WAVEFORM_INVERT_OUTPUT_CHANNEL_0 = TC_WAVEFORM_INVERT_CC0_MODE, - /** Invert output from compare channel 1. */ - TC_WAVEFORM_INVERT_OUTPUT_CHANNEL_1 = TC_WAVEFORM_INVERT_CC1_MODE, -}; - -/** - * \brief Action to perform when the TC module is triggered by an event. - * - * Event action to perform when the module is triggered by an event. - */ -enum tc_event_action { - /** No event action. */ - TC_EVENT_ACTION_OFF = TC_EVCTRL_EVACT_OFF, - /** Re-trigger on event. */ - TC_EVENT_ACTION_RETRIGGER = TC_EVCTRL_EVACT_RETRIGGER, - /** Increment counter on event. */ - TC_EVENT_ACTION_INCREMENT_COUNTER = TC_EVCTRL_EVACT_COUNT, - /** Start counter on event. */ - TC_EVENT_ACTION_START = TC_EVCTRL_EVACT_START, - - /** Store period in capture register 0, pulse width in capture - * register 1. - */ - TC_EVENT_ACTION_PPW = TC_EVCTRL_EVACT_PPW, - - /** Store pulse width in capture register 0, period in capture - * register 1. - */ - TC_EVENT_ACTION_PWP = TC_EVCTRL_EVACT_PWP, -#ifdef FEATURE_TC_STAMP_PW_CAPTURE - /** Time stamp capture. */ - TC_EVENT_ACTION_STAMP = TC_EVCTRL_EVACT_STAMP, - /** Pulse width capture. */ - TC_EVENT_ACTION_PW = TC_EVCTRL_EVACT_PW, -#endif -}; - -/** - * \brief TC event enable/disable structure. - * - * Event flags for the \ref tc_enable_events() and \ref tc_disable_events(). - */ -struct tc_events { - /** Generate an output event on a compare channel match. */ - bool generate_event_on_compare_channel - [NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; - /** Generate an output event on counter overflow. */ - bool generate_event_on_overflow; - /** Perform the configured event action when an incoming event is signalled. */ - bool on_event_perform_action; - /** Specifies if the input event source is inverted, when used in PWP or - * PPW event action modes. - */ - bool invert_event_input; - /** Specifies which event to trigger if an event is triggered. */ - enum tc_event_action event_action; -}; - -/** - * \brief Configuration struct for TC module in 8-bit size counter mode. - */ -struct tc_8bit_config { - /** Initial timer count value. */ - uint8_t value; - /** Where to count to or from depending on the direction on the counter. */ - uint8_t period; - /** Value to be used for compare match on each channel. */ - uint8_t compare_capture_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; -}; - -/** - * \brief Configuration struct for TC module in 16-bit size counter mode. - */ -struct tc_16bit_config { - /** Initial timer count value. */ - uint16_t value; - /** Value to be used for compare match on each channel. */ - uint16_t compare_capture_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; -}; - -/** - * \brief Configuration struct for TC module in 32-bit size counter mode. - */ -struct tc_32bit_config { - /** Initial timer count value. */ - uint32_t value; - /** Value to be used for compare match on each channel. */ - uint32_t compare_capture_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; -}; - -/** - * \brief Configuration struct for TC module in 32-bit size counter mode. - */ -struct tc_pwm_channel { - /** When \c true, PWM output for the given channel is enabled. */ - bool enabled; - /** Specifies pin output for each channel. */ - uint32_t pin_out; - /** Specifies MUX setting for each output channel pin. */ - uint32_t pin_mux; -}; - -/** - * \brief TC configuration structure. - * - * Configuration struct for a TC instance. This structure should be - * initialized by the \ref tc_get_config_defaults function before being - * modified by the user application. - */ -struct tc_config { - /** GCLK generator used to clock the peripheral. */ - enum gclk_generator clock_source; - - /** When \c true the module is enabled during standby. */ - bool run_in_standby; -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) - /** Run on demand. */ - bool on_demand; -#endif - /** Specifies either 8-, 16-, or 32-bit counter size. */ - enum tc_counter_size counter_size; - /** Specifies the prescaler value for GCLK_TC. */ - enum tc_clock_prescaler clock_prescaler; - /** Specifies which waveform generation mode to use. */ - enum tc_wave_generation wave_generation; - - /** Specifies the reload or reset time of the counter and prescaler - * resynchronization on a re-trigger event for the TC. - */ - enum tc_reload_action reload_action; - - /** Specifies which channel(s) to invert the waveform on. - For SAM L21/L22/C20/C21, it's also used to invert IO input pin. */ - uint8_t waveform_invert_output; - - /** Specifies which channel(s) to enable channel capture - * operation on. - */ - bool enable_capture_on_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; -#ifdef FEATURE_TC_IO_CAPTURE - /** Specifies which channel(s) to enable I/O capture - * operation on. - */ - bool enable_capture_on_IO[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; -#endif - - /** When \c true, one-shot will stop the TC on next hardware or software - * re-trigger event or overflow/underflow. - */ - bool oneshot; - - /** Specifies the direction for the TC to count. */ - enum tc_count_direction count_direction; - - /** Specifies the PWM channel for TC. */ - struct tc_pwm_channel pwm_channel[NUMBER_OF_COMPARE_CAPTURE_CHANNELS]; - - /** Access the different counter size settings though this configuration member. */ - union { - /** Struct for 8-bit specific timer configuration. */ - struct tc_8bit_config counter_8_bit; - /** Struct for 16-bit specific timer configuration. */ - struct tc_16bit_config counter_16_bit; - /** Struct for 32-bit specific timer configuration. */ - struct tc_32bit_config counter_32_bit; - }; - -#ifdef FEATURE_TC_DOUBLE_BUFFERED - /** Set to \c true to enable double buffering write. When enabled any write - * through \ref tc_set_top_value(), \ref tc_set_compare_value() and - * will direct to the buffer register as buffered - * value, and the buffered value will be committed to effective register - * on UPDATE condition, if update is not locked. - */ - bool double_buffering_enabled; -#endif -}; - -#if TC_ASYNC == true -/* Forward Declaration for the device instance. */ -struct tc_module; - -/* Type of the callback functions. */ -typedef void (*tc_callback_t)(struct tc_module *const module); -#endif - -/** - * \brief TC software device instance structure. - * - * TC software instance structure, used to retain software state information - * of an associated hardware module instance. - * - * \note The fields of this structure should not be altered by the user - * application; they are reserved for module-internal use only. - */ -struct tc_module { -#if !defined(__DOXYGEN__) - /** Hardware module pointer of the associated Timer/Counter peripheral. */ - Tc *hw; - - /** Size of the initialized Timer/Counter module configuration. */ - enum tc_counter_size counter_size; -# if TC_ASYNC == true - /** Array of callbacks. */ - tc_callback_t callback[TC_CALLBACK_N]; - /** Bit mask for callbacks registered. */ - uint8_t register_callback_mask; - /** Bit mask for callbacks enabled. */ - uint8_t enable_callback_mask; -# endif -#ifdef FEATURE_TC_DOUBLE_BUFFERED - /** Set to \c true to enable double buffering write. */ - bool double_buffering_enabled; -#endif -#endif -}; - -#if !defined(__DOXYGEN__) -uint8_t _tc_get_inst_index( - Tc *const hw); -#endif - -/** - * \name Driver Initialization and Configuration - * @{ - */ - -/** - * \brief Determines if the hardware module(s) are currently synchronizing to - *the bus. - * - * Checks to see if the underlying hardware peripheral module(s) are currently - * synchronizing across multiple clock domains to the hardware bus. This - * function can be used to delay further operations on a module until such time - * that it is ready, to prevent blocking delays for synchronization in the - * user application. - * - * \param[in] module_inst Pointer to the software module instance struct - * - * \return Synchronization status of the underlying hardware module(s). - * - * \retval false If the module has completed synchronization - * \retval true If the module synchronization is ongoing - */ -static inline bool tc_is_syncing( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) - return (tc_module->SYNCBUSY.reg); -#else - return (tc_module->STATUS.reg & TC_STATUS_SYNCBUSY); -#endif -} - -/** - * \brief Initializes config with predefined default values. - * - * This function will initialize a given TC configuration structure to - * a set of known default values. This function should be called on - * any new instance of the configuration structures before being - * modified by the user application. - * - * The default configuration is as follows: - * \li GCLK generator 0 (GCLK main) clock source - * \li 16-bit counter size on the counter - * \li No prescaler - * \li Normal frequency wave generation - * \li GCLK reload action - * \li Don't run in standby - * \li Don't run on demand for SAM L21/L22/C20/C21 - * \li No inversion of waveform output - * \li No capture enabled - * \li No I/O capture enabled for SAM L21/L22/C20/C21 - * \li No event input enabled - * \li Count upward - * \li Don't perform one-shot operations - * \li No event action - * \li No channel 0 PWM output - * \li No channel 1 PWM output - * \li Counter starts on 0 - * \li Capture compare channel 0 set to 0 - * \li Capture compare channel 1 set to 0 - * \li No PWM pin output enabled - * \li Pin and MUX configuration not set - * \li Double buffer disabled (if have this feature) - * - * \param[out] config Pointer to a TC module configuration structure to set - */ -static inline void tc_get_config_defaults( - struct tc_config *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Write default config to config struct */ - config->clock_source = GCLK_GENERATOR_0; - config->counter_size = TC_COUNTER_SIZE_16BIT; - config->clock_prescaler = TC_CLOCK_PRESCALER_DIV1; - config->wave_generation = TC_WAVE_GENERATION_NORMAL_FREQ; - config->reload_action = TC_RELOAD_ACTION_GCLK; - config->run_in_standby = false; -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) - config->on_demand = false; -#endif - config->waveform_invert_output = TC_WAVEFORM_INVERT_OUTPUT_NONE; - config->enable_capture_on_channel[TC_COMPARE_CAPTURE_CHANNEL_0] = false; - config->enable_capture_on_channel[TC_COMPARE_CAPTURE_CHANNEL_1] = false; -#ifdef FEATURE_TC_IO_CAPTURE - config->enable_capture_on_IO[TC_COMPARE_CAPTURE_CHANNEL_0] = false; - config->enable_capture_on_IO[TC_COMPARE_CAPTURE_CHANNEL_1] = false; -#endif - - config->count_direction = TC_COUNT_DIRECTION_UP; - config->oneshot = false; - - config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_0].enabled = false; - config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_0].pin_out = 0; - config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_0].pin_mux = 0; - - config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_1].enabled = false; - config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_1].pin_out = 0; - config->pwm_channel[TC_COMPARE_CAPTURE_CHANNEL_1].pin_mux = 0; - - config->counter_16_bit.value = 0x0000; - config->counter_16_bit.compare_capture_channel\ - [TC_COMPARE_CAPTURE_CHANNEL_0] = 0x0000; - config->counter_16_bit.compare_capture_channel\ - [TC_COMPARE_CAPTURE_CHANNEL_1] = 0x0000; -#ifdef FEATURE_TC_DOUBLE_BUFFERED - config->double_buffering_enabled = false; -#endif - -} - -enum status_code tc_init( - struct tc_module *const module_inst, - Tc *const hw, - const struct tc_config *const config); - -/** @} */ - -/** - * \name Event Management - * @{ - */ - -/** - * \brief Enables a TC module event input or output. - * - * Enables one or more input or output events to or from the TC module. - * See \ref tc_events for a list of events this module supports. - * - * \note Events cannot be altered while the module is enabled. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] events Struct containing flags of events to enable - */ -static inline void tc_enable_events( - struct tc_module *const module_inst, - struct tc_events *const events) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - Assert(events); - - Tc *const tc_module = module_inst->hw; - - uint32_t event_mask = 0; - - if (events->invert_event_input == true) { - event_mask |= TC_EVCTRL_TCINV; - } - - if (events->on_event_perform_action == true) { - event_mask |= TC_EVCTRL_TCEI; - } - - if (events->generate_event_on_overflow == true) { - event_mask |= TC_EVCTRL_OVFEO; - } - - for (uint8_t i = 0; i < NUMBER_OF_COMPARE_CAPTURE_CHANNELS; i++) { - if (events->generate_event_on_compare_channel[i] == true) { - event_mask |= (TC_EVCTRL_MCEO(1) << i); - } - } - - tc_module->COUNT8.EVCTRL.reg |= event_mask | events->event_action; -} - -/** - * \brief Disables a TC module event input or output. - * - * Disables one or more input or output events to or from the TC module. - * See \ref tc_events for a list of events this module supports. - * - * \note Events cannot be altered while the module is enabled. - * - * \param[in] module_inst Pointer to the software module instance struct - * \param[in] events Struct containing flags of events to disable - */ -static inline void tc_disable_events( - struct tc_module *const module_inst, - struct tc_events *const events) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - Assert(events); - - Tc *const tc_module = module_inst->hw; - - uint32_t event_mask = 0; - - if (events->invert_event_input == true) { - event_mask |= TC_EVCTRL_TCINV; - } - - if (events->on_event_perform_action == true) { - event_mask |= TC_EVCTRL_TCEI; - } - - if (events->generate_event_on_overflow == true) { - event_mask |= TC_EVCTRL_OVFEO; - } - - for (uint8_t i = 0; i < NUMBER_OF_COMPARE_CAPTURE_CHANNELS; i++) { - if (events->generate_event_on_compare_channel[i] == true) { - event_mask |= (TC_EVCTRL_MCEO(1) << i); - } - } - - tc_module->COUNT8.EVCTRL.reg &= ~event_mask; -} - -/** @} */ - -/** - * \name Enable/Disable/Reset - * @{ - */ - -enum status_code tc_reset( - const struct tc_module *const module_inst); - -/** - * \brief Enable the TC module. - * - * Enables a TC module that has been previously initialized. The counter will - * start when the counter is enabled. - * - * \note When the counter is configured to re-trigger on an event, the counter - * will not start until the start function is used. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_enable( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Enable TC module */ - tc_module->CTRLA.reg |= TC_CTRLA_ENABLE; -} - -/** - * \brief Disables the TC module. - * - * Disables a TC module and stops the counter. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_disable( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Disable TC module */ - tc_module->CTRLA.reg &= ~TC_CTRLA_ENABLE; -} - -/** @} */ - -/** - * \name Get/Set Count Value - * @{ - */ - -uint32_t tc_get_count_value( - const struct tc_module *const module_inst); - -enum status_code tc_set_count_value( - const struct tc_module *const module_inst, - const uint32_t count); - -/** @} */ - -/** - * \name Start/Stop Counter - * @{ - */ - -/** - * \brief Stops the counter. - * - * This function will stop the counter. When the counter is stopped - * the value in the count value is set to 0 if the counter was - * counting up, or maximum if the counter was counting - * down when stopped. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_stop_counter( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Write command to execute */ - tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_STOP_Val); -} - -/** - * \brief Starts the counter. - * - * Starts or restarts an initialized TC module's counter. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_start_counter( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Make certain that there are no conflicting commands in the register */ - tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Write command to execute */ - tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_RETRIGGER_Val); -} - -/** @} */ - -#ifdef FEATURE_TC_DOUBLE_BUFFERED -/** - * \name Double Buffering - * @{ - */ - -/** - * \brief Update double buffer. - * - * Update double buffer. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_update_double_buffer( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Make certain that there are no conflicting commands in the register */ - tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Write command to execute */ - tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_UPDATE_Val); -} -/** @} */ -#endif - -#ifdef FEATURE_TC_READ_SYNC -/** - * \name Count Read Synchronization - * @{ - */ - -/** - * \brief Read synchronization of COUNT. - * - * Read synchronization of COUNT. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_sync_read_count( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Make certain that there are no conflicting commands in the register */ - tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Write command to execute */ - tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_READSYNC_Val); -} -/** @} */ -#endif - -#ifdef FEATURE_TC_GENERATE_DMA_TRIGGER -/** - * \name Generate TC DMA Triggers command - * @{ - */ - -/** - * \brief TC DMA Trigger. - * - * TC DMA trigger command. - * - * \param[in] module_inst Pointer to the software module instance struct - */ -static inline void tc_dma_trigger_command( - const struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - - /* Make certain that there are no conflicting commands in the register */ - tc_module->CTRLBCLR.reg = TC_CTRLBCLR_CMD_NONE; - - while (tc_is_syncing(module_inst)) { - /* Wait for sync */ - } - -#if (SAMC20) || (SAMC21) || (SAML22) || (SAML21XXXB) - /* Write command to execute */ - tc_module->CTRLBSET.reg = TC_CTRLBSET_CMD(TC_CTRLBSET_CMD_DMAOS_Val); -#endif -} -/** @} */ -#endif - -/** - * \name Get Capture Set Compare - * @{ - */ - -uint32_t tc_get_capture_value( - const struct tc_module *const module_inst, - const enum tc_compare_capture_channel channel_index); - -enum status_code tc_set_compare_value( - const struct tc_module *const module_inst, - const enum tc_compare_capture_channel channel_index, - const uint32_t compare_value); - -/** @} */ - -/** - * \name Set Top Value - * @{ - */ - -enum status_code tc_set_top_value( - const struct tc_module *const module_inst, - const uint32_t top_value); - -/** @} */ - -/** - * \name Status Management - * @{ - */ - -/** - * \brief Retrieves the current module status. - * - * Retrieves the status of the module, giving overall state information. - * - * \param[in] module_inst Pointer to the TC software instance struct - * - * \return Bitmask of \c TC_STATUS_* flags. - * - * \retval TC_STATUS_CHANNEL_0_MATCH Timer channel 0 compare/capture match - * \retval TC_STATUS_CHANNEL_1_MATCH Timer channel 1 compare/capture match - * \retval TC_STATUS_SYNC_READY Timer read synchronization has completed - * \retval TC_STATUS_CAPTURE_OVERFLOW Timer capture data has overflowed - * \retval TC_STATUS_COUNT_OVERFLOW Timer count value has overflowed - * \retval TC_STATUS_CHN0_BUFFER_VALID Timer count channel 0 compare/capture buffer valid - * \retval TC_STATUS_CHN1_BUFFER_VALID Timer count channel 1 compare/capture buffer valid - * \retval TC_STATUS_PERIOD_BUFFER_VALID Timer count period buffer valid - */ -static inline uint32_t tc_get_status( - struct tc_module *const module_inst) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - uint32_t int_flags = tc_module->INTFLAG.reg; - - uint32_t status_flags = 0; - - /* Check for TC channel 0 match */ - if (int_flags & TC_INTFLAG_MC(1)) { - status_flags |= TC_STATUS_CHANNEL_0_MATCH; - } - - /* Check for TC channel 1 match */ - if (int_flags & TC_INTFLAG_MC(2)) { - status_flags |= TC_STATUS_CHANNEL_1_MATCH; - } - -#if !defined(FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2) - /* Check for TC read synchronization ready */ - if (int_flags & TC_INTFLAG_SYNCRDY) { - status_flags |= TC_STATUS_SYNC_READY; - } -#endif - - /* Check for TC capture overflow */ - if (int_flags & TC_INTFLAG_ERR) { - status_flags |= TC_STATUS_CAPTURE_OVERFLOW; - } - - /* Check for TC count overflow */ - if (int_flags & TC_INTFLAG_OVF) { - status_flags |= TC_STATUS_COUNT_OVERFLOW; - } -#ifdef FEATURE_TC_DOUBLE_BUFFERED - uint8_t double_buffer_valid_status = tc_module->STATUS.reg; - - /* Check channel 0 compare or capture buffer valid */ - if (double_buffer_valid_status & TC_STATUS_CCBUFV0) { - status_flags |= TC_STATUS_CHN0_BUFFER_VALID; - } - /* Check channel 0 compare or capture buffer valid */ - if (double_buffer_valid_status & TC_STATUS_CCBUFV1) { - status_flags |= TC_STATUS_CHN1_BUFFER_VALID; - } - /* Check period buffer valid */ - if (double_buffer_valid_status & TC_STATUS_PERBUFV) { - status_flags |= TC_STATUS_PERIOD_BUFFER_VALID; - } -#endif - - return status_flags; -} - -/** - * \brief Clears a module status flag. - * - * Clears the given status flag of the module. - * - * \param[in] module_inst Pointer to the TC software instance struct - * \param[in] status_flags Bitmask of \c TC_STATUS_* flags to clear - */ -static inline void tc_clear_status( - struct tc_module *const module_inst, - const uint32_t status_flags) -{ - /* Sanity check arguments */ - Assert(module_inst); - Assert(module_inst->hw); - - /* Get a pointer to the module's hardware instance */ - TcCount8 *const tc_module = &(module_inst->hw->COUNT8); - - uint32_t int_flags = 0; - - /* Check for TC channel 0 match */ - if (status_flags & TC_STATUS_CHANNEL_0_MATCH) { - int_flags |= TC_INTFLAG_MC(1); - } - - /* Check for TC channel 1 match */ - if (status_flags & TC_STATUS_CHANNEL_1_MATCH) { - int_flags |= TC_INTFLAG_MC(2); - } - -#if !defined(FEATURE_TC_SYNCBUSY_SCHEME_VERSION_2) - /* Check for TC read synchronization ready */ - if (status_flags & TC_STATUS_SYNC_READY) { - int_flags |= TC_INTFLAG_SYNCRDY; - } -#endif - - /* Check for TC capture overflow */ - if (status_flags & TC_STATUS_CAPTURE_OVERFLOW) { - int_flags |= TC_INTFLAG_ERR; - } - - /* Check for TC count overflow */ - if (status_flags & TC_STATUS_COUNT_OVERFLOW) { - int_flags |= TC_INTFLAG_OVF; - } - - /* Clear interrupt flag */ - tc_module->INTFLAG.reg = int_flags; -} - -/** @} */ - -/** @} */ - -#ifdef __cplusplus -} -#endif - -/** - * \page asfdoc_sam0_tc_extra Extra Information for TC Driver - * - * \section asfdoc_sam0_tc_extra_acronyms Acronyms - * The table below presents the acronyms used in this module: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
AcronymDescription
DMADirect Memory Access
TCTimer Counter
PWMPulse Width Modulation
PWPPulse Width Period
PPWPeriod Pulse Width
- * - * - * \section asfdoc_sam0_tc_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - \ref asfdoc_sam0_system_pinmux_group "System Pin Multiplexer Driver" - * - * - * \section asfdoc_sam0_tc_extra_errata Errata - * There are no errata related to this driver. - * - * - * \section asfdoc_sam0_tc_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Changelog
Added support for SAMD21 and do some modifications as below: - * \li Clean up in the configuration structure, the counter size - * setting specific registers is accessed through the counter_8_bit, - * counter_16_bit and counter_32_bit structures - * \li All event related settings moved into the tc_event structure
Added automatic digital clock interface enable for the slave TC - * module when a timer is initialized in 32-bit mode
Initial Release
- */ - -/** - * \page asfdoc_sam0_tc_exqsg Examples for TC Driver - * - * This is a list of the available Quick Start guides (QSGs) and example - * applications for \ref asfdoc_sam0_tc_group. QSGs are simple examples with - * step-by-step instructions to configure and use this driver in a selection of - * use cases. Note that QSGs can be compiled as a standalone application or be - * added to the user application. - * - * - \subpage asfdoc_sam0_tc_basic_use_case - * - \subpage asfdoc_sam0_tc_macth_freq_use_case - * \if TC_CALLBACK_MODE - * - \subpage asfdoc_sam0_tc_timer_use_case - * - \subpage asfdoc_sam0_tc_callback_use_case - * \endif - * - \subpage asfdoc_sam0_tc_dma_use_case - * - * \page asfdoc_sam0_tc_document_revision_history Document Revision History - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Doc. Rev. - * Date - * Comments - *
F08/2015Added support for SAM C21 and SAM L22
E04/2015Added support for SAM L21 and SAM DA1
D12/2014Added timer use case. - * Added support for SAM R21 and SAM D10/D11
C01/2014Added support for SAM D21
B06/2013Corrected documentation typos
A06/2013Initial release
- */ - -#endif /* TC_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc_interrupt.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc_interrupt.c deleted file mode 100644 index 032be2f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc_interrupt.c +++ /dev/null @@ -1,199 +0,0 @@ -/** - * \file - * - * \brief SAM TC - Timer Counter Callback Driver - * - * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/* - * Support and FAQ: visit Atmel Support - */ - -#include "tc_interrupt.h" - -void *_tc_instances[TC_INST_NUM]; - -void _tc_interrupt_handler(uint8_t instance); - -/** - * \brief Registers a callback. - * - * Registers a callback function which is implemented by the user. - * - * \note The callback must be enabled by \ref tc_enable_callback, - * in order for the interrupt handler to call it when the conditions for the - * callback type is met. - * - * \param[in] module Pointer to TC software instance struct - * \param[in] callback_func Pointer to callback function - * \param[in] callback_type Callback type given by an enum - */ -enum status_code tc_register_callback( - struct tc_module *const module, - tc_callback_t callback_func, - const enum tc_callback callback_type) -{ - /* Sanity check arguments */ - Assert(module); - Assert(callback_func); - - /* Register callback function */ - module->callback[callback_type] = callback_func; - - /* Set the bit corresponding to the callback_type */ - if (callback_type == TC_CALLBACK_CC_CHANNEL0) { - module->register_callback_mask |= TC_INTFLAG_MC(1); - } - else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { - module->register_callback_mask |= TC_INTFLAG_MC(2); - } - else { - module->register_callback_mask |= (1 << callback_type); - } - return STATUS_OK; -} - -/** - * \brief Unregisters a callback. - * - * Unregisters a callback function implemented by the user. The callback should be - * disabled before it is unregistered. - * - * \param[in] module Pointer to TC software instance struct - * \param[in] callback_type Callback type given by an enum - */ -enum status_code tc_unregister_callback( - struct tc_module *const module, - const enum tc_callback callback_type) -{ - /* Sanity check arguments */ - Assert(module); - - /* Unregister callback function */ - module->callback[callback_type] = NULL; - - /* Clear the bit corresponding to the callback_type */ - if (callback_type == TC_CALLBACK_CC_CHANNEL0) { - module->register_callback_mask &= ~TC_INTFLAG_MC(1); - } - else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { - module->register_callback_mask &= ~TC_INTFLAG_MC(2); - } - else { - module->register_callback_mask &= ~(1 << callback_type); - } - return STATUS_OK; -} - -/** - * \internal ISR handler for TC - * - * Auto-generate a set of interrupt handlers for each TC in the device. - */ -#define _TC_INTERRUPT_HANDLER(n, m) \ - void TC##n##_Handler(void) \ - { \ - _tc_interrupt_handler(m); \ - } - -#if (SAML21E) || (SAML21G) - _TC_INTERRUPT_HANDLER(0,0) - _TC_INTERRUPT_HANDLER(1,1) - _TC_INTERRUPT_HANDLER(4,2) -#else - MRECURSION(TC_INST_NUM, _TC_INTERRUPT_HANDLER, TC_INST_MAX_ID) -#endif - - -/** - * \internal Interrupt Handler for TC module - * - * Handles interrupts as they occur, it will run the callback functions - * that are registered and enabled. - * - * \param[in] instance ID of the TC instance calling the interrupt - * handler. - */ -void _tc_interrupt_handler( - uint8_t instance) -{ - /* Temporary variable */ - uint8_t interrupt_and_callback_status_mask; - - /* Get device instance from the look-up table */ - struct tc_module *module - = (struct tc_module *)_tc_instances[instance]; - - /* Read and mask interrupt flag register */ - interrupt_and_callback_status_mask = module->hw->COUNT8.INTFLAG.reg & - module->register_callback_mask & - module->enable_callback_mask; - - /* Check if an Overflow interrupt has occurred */ - if (interrupt_and_callback_status_mask & TC_INTFLAG_OVF) { - /* Invoke registered and enabled callback function */ - (module->callback[TC_CALLBACK_OVERFLOW])(module); - /* Clear interrupt flag */ - module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_OVF; - } - - /* Check if an Error interrupt has occurred */ - if (interrupt_and_callback_status_mask & TC_INTFLAG_ERR) { - /* Invoke registered and enabled callback function */ - (module->callback[TC_CALLBACK_ERROR])(module); - /* Clear interrupt flag */ - module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_ERR; - } - - /* Check if an Match/Capture Channel 0 interrupt has occurred */ - if (interrupt_and_callback_status_mask & TC_INTFLAG_MC(1)) { - /* Invoke registered and enabled callback function */ - (module->callback[TC_CALLBACK_CC_CHANNEL0])(module); - /* Clear interrupt flag */ - module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_MC(1); - } - - /* Check if an Match/Capture Channel 1 interrupt has occurred */ - if (interrupt_and_callback_status_mask & TC_INTFLAG_MC(2)) { - /* Invoke registered and enabled callback function */ - (module->callback[TC_CALLBACK_CC_CHANNEL1])(module); - /* Clear interrupt flag */ - module->hw->COUNT8.INTFLAG.reg = TC_INTFLAG_MC(2); - } -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc_interrupt.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc_interrupt.h deleted file mode 100644 index 4e1fd8e..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/tc_interrupt.h +++ /dev/null @@ -1,179 +0,0 @@ -/** - * \file - * - * \brief SAM TC - Timer Counter Callback Driver - * - * Copyright (C) 2013-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/* - * Support and FAQ: visit Atmel Support - */ - -#ifndef TC_INTERRUPT_H_INCLUDED -#define TC_INTERRUPT_H_INCLUDED - -#include "tc.h" -#include "system_interrupt.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#if !defined(__DOXYGEN__) -extern void *_tc_instances[TC_INST_NUM]; - -# define _TC_INTERRUPT_VECT_NUM(n, unused) \ - SYSTEM_INTERRUPT_MODULE_TC##n, -/** - * \internal Get the interrupt vector for the given device instance - * - * \param[in] TC module instance number. - * - * \return Interrupt vector for of the given TC module instance. - */ -static enum system_interrupt_vector _tc_interrupt_get_interrupt_vector( - uint32_t inst_num) -{ - static uint8_t tc_interrupt_vectors[TC_INST_NUM] = - { -#if (SAML21E) || (SAML21G) - SYSTEM_INTERRUPT_MODULE_TC0, - SYSTEM_INTERRUPT_MODULE_TC1, - SYSTEM_INTERRUPT_MODULE_TC4 -#else - MRECURSION(TC_INST_NUM, _TC_INTERRUPT_VECT_NUM, TC_INST_MAX_ID) -#endif - }; - - return (enum system_interrupt_vector)tc_interrupt_vectors[inst_num]; -} -#endif /* !defined(__DOXYGEN__) */ - -/** - * \name Callback Management - * {@ - */ - -enum status_code tc_register_callback( - struct tc_module *const module, - tc_callback_t callback_func, - const enum tc_callback callback_type); - -enum status_code tc_unregister_callback( - struct tc_module *const module, - const enum tc_callback callback_type); - -/** - * \brief Enables callback. - * - * Enables the callback function registered by the \ref - * tc_register_callback. The callback function will be called from the - * interrupt handler when the conditions for the callback type are - * met. This function will also enable the appropriate interrupts. - * - * \param[in] module Pointer to TC software instance struct - * \param[in] callback_type Callback type given by an enum - */ -static inline void tc_enable_callback( - struct tc_module *const module, - const enum tc_callback callback_type) -{ - /* Sanity check arguments */ - Assert(module); - - - /* Enable interrupts for this TC module */ - system_interrupt_enable(_tc_interrupt_get_interrupt_vector(_tc_get_inst_index(module->hw))); - - /* Enable callback */ - if (callback_type == TC_CALLBACK_CC_CHANNEL0) { - module->enable_callback_mask |= TC_INTFLAG_MC(1); - module->hw->COUNT8.INTENSET.reg = TC_INTFLAG_MC(1); - } - else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { - module->enable_callback_mask |= TC_INTFLAG_MC(2); - module->hw->COUNT8.INTENSET.reg = TC_INTFLAG_MC(2); - } - else { - module->enable_callback_mask |= (1 << callback_type); - module->hw->COUNT8.INTENSET.reg = (1 << callback_type); - } -} - -/** - * \brief Disables callback. - * - * Disables the callback function registered by the \ref - * tc_register_callback, and the callback will not be called from the - * interrupt routine. The function will also disable the appropriate - * interrupts. - * - * \param[in] module Pointer to TC software instance struct - * \param[in] callback_type Callback type given by an enum - */ -static inline void tc_disable_callback( - struct tc_module *const module, - const enum tc_callback callback_type){ - /* Sanity check arguments */ - Assert(module); - - /* Disable callback */ - if (callback_type == TC_CALLBACK_CC_CHANNEL0) { - module->hw->COUNT8.INTENCLR.reg = TC_INTFLAG_MC(1); - module->enable_callback_mask &= ~TC_INTFLAG_MC(1); - } - else if (callback_type == TC_CALLBACK_CC_CHANNEL1) { - module->hw->COUNT8.INTENCLR.reg = TC_INTFLAG_MC(2); - module->enable_callback_mask &= ~TC_INTFLAG_MC(2); - } - else { - module->hw->COUNT8.INTENCLR.reg = (1 << callback_type); - module->enable_callback_mask &= ~(1 << callback_type); - } -} - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* TC_INTERRUPT_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/wdt.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/wdt.c deleted file mode 100644 index c5b0895..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/wdt.c +++ /dev/null @@ -1,264 +0,0 @@ -/** - * \file - * - * \brief SAM Watchdog Driver - * - * Copyright (C) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#include "wdt.h" -#include - -/** - * \brief Sets up the WDT hardware module based on the configuration. - * - * Writes a given configuration of a WDT configuration to the - * hardware module, and initializes the internal device struct. - * - * \param[in] config Pointer to the configuration struct - * - * \return Status of the configuration procedure. - * - * \retval STATUS_OK If the module was configured correctly - * \retval STATUS_ERR_INVALID_ARG If invalid argument(s) were supplied - * \retval STATUS_ERR_IO If the Watchdog module is locked to be always on - */ -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) -enum status_code wdt_set_config( - const struct wdt_conf *const config) -{ - /* Sanity check arguments */ - Assert(config); - - Wdt *const WDT_module = WDT; - - /* Turn on the digital interface clock */ - system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBA, MCLK_APBAMASK_WDT); - - /* Check of the Watchdog has been locked to be always on, if so, abort */ - if (wdt_is_locked()) { - return STATUS_ERR_IO; - } - - /* Check for an invalid timeout period, abort if found */ - if (config->timeout_period == WDT_PERIOD_NONE) { - return STATUS_ERR_INVALID_ARG; - } - - /* Make sure the Window and Early Warning periods are not more than the - * reset period, abort if either is invalid */ - if ((config->timeout_period < config->window_period) || - (config->timeout_period < config->early_warning_period)) { - return STATUS_ERR_INVALID_ARG; - } - - /* Disable the Watchdog module */ - WDT_module->CTRLA.reg &= ~WDT_CTRLA_ENABLE; - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - if(config->enable == false) { - return STATUS_OK; - } - - uint32_t new_config = 0; - - /* Update the timeout period value with the requested period */ - new_config |= (config->timeout_period - 1) << WDT_CONFIG_PER_Pos; - - /* Check if the user has requested a reset window period */ - if (config->window_period != WDT_PERIOD_NONE) { - WDT_module->CTRLA.reg |= WDT_CTRLA_WEN; - - /* Update and enable the timeout period value */ - new_config |= (config->window_period - 1) << WDT_CONFIG_WINDOW_Pos; - } else { - /* Ensure the window enable control flag is cleared */ - WDT_module->CTRLA.reg &= ~WDT_CTRLA_WEN; - } - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - /* Write the new Watchdog configuration */ - WDT_module->CONFIG.reg = new_config; - - /* Check if the user has requested an early warning period */ - if (config->early_warning_period != WDT_PERIOD_NONE) { - /* Set the Early Warning period */ - WDT_module->EWCTRL.reg - = (config->early_warning_period - 1) << WDT_EWCTRL_EWOFFSET_Pos; - } - - /* Either enable or lock-enable the Watchdog timer depending on the user - * settings */ - if (config->always_on) { - WDT_module->CTRLA.reg |= WDT_CTRLA_ALWAYSON; - } else { - WDT_module->CTRLA.reg |= WDT_CTRLA_ENABLE; - } - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - return STATUS_OK; -} -#else -enum status_code wdt_set_config( - const struct wdt_conf *const config) -{ - /* Sanity check arguments */ - Assert(config); - - Wdt *const WDT_module = WDT; - - /* Turn on the digital interface clock */ - system_apb_clock_set_mask(SYSTEM_CLOCK_APB_APBA, PM_APBAMASK_WDT); - - /* Check of the Watchdog has been locked to be always on, if so, abort */ - if (wdt_is_locked()) { - return STATUS_ERR_IO; - } - - /* Check for an invalid timeout period, abort if found */ - if (config->timeout_period == WDT_PERIOD_NONE) { - return STATUS_ERR_INVALID_ARG; - } - - /* Make sure the Window and Early Warning periods are not more than the - * reset period, abort if either is invalid */ - if ((config->timeout_period < config->window_period) || - (config->timeout_period < config->early_warning_period)) { - return STATUS_ERR_INVALID_ARG; - } - - /* Disable the Watchdog module */ - WDT_module->CTRL.reg &= ~WDT_CTRL_ENABLE; - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - if(config->enable == false) { - return STATUS_OK; - } - - /* Configure GCLK channel and enable clock */ - struct system_gclk_chan_config gclk_chan_conf; - gclk_chan_conf.source_generator = config->clock_source; - system_gclk_chan_set_config(WDT_GCLK_ID, &gclk_chan_conf); - system_gclk_chan_enable(WDT_GCLK_ID); - if (config->always_on) { - system_gclk_chan_lock(WDT_GCLK_ID); - } - - uint32_t new_config = 0; - - /* Update the timeout period value with the requested period */ - new_config |= (config->timeout_period - 1) << WDT_CONFIG_PER_Pos; - - /* Check if the user has requested a reset window period */ - if (config->window_period != WDT_PERIOD_NONE) { - WDT_module->CTRL.reg |= WDT_CTRL_WEN; - - /* Update and enable the timeout period value */ - new_config |= (config->window_period - 1) << WDT_CONFIG_WINDOW_Pos; - } else { - /* Ensure the window enable control flag is cleared */ - WDT_module->CTRL.reg &= ~WDT_CTRL_WEN; - } - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - /* Write the new Watchdog configuration */ - WDT_module->CONFIG.reg = new_config; - - /* Check if the user has requested an early warning period */ - if (config->early_warning_period != WDT_PERIOD_NONE) { - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - /* Set the Early Warning period */ - WDT_module->EWCTRL.reg - = (config->early_warning_period - 1) << WDT_EWCTRL_EWOFFSET_Pos; - } - - /* Either enable or lock-enable the Watchdog timer depending on the user - * settings */ - if (config->always_on) { - WDT_module->CTRL.reg |= WDT_CTRL_ALWAYSON; - } else { - WDT_module->CTRL.reg |= WDT_CTRL_ENABLE; - } - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } - - return STATUS_OK; -} -#endif - -/** - * \brief Resets the count of the running Watchdog Timer that was previously enabled. - * - * Resets the current count of the Watchdog Timer, restarting the timeout - * period count elapsed. This function should be called after the window - * period (if one was set in the module configuration) but before the timeout - * period to prevent a reset of the system. - */ -void wdt_reset_count(void) -{ - Wdt *const WDT_module = WDT; - - /* Disable the Watchdog module */ - WDT_module->CLEAR.reg = WDT_CLEAR_CLEAR_KEY; - - while (wdt_is_syncing()) { - /* Wait for all hardware modules to complete synchronization */ - } -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/wdt.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/wdt.h deleted file mode 100644 index c4c37cf..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_ASFcore/wdt.h +++ /dev/null @@ -1,501 +0,0 @@ -/** - * \file - * - * \brief SAM Watchdog Driver - * - * Copyright (c) 2012-2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/* - * Support and FAQ: visit Atmel Support - */ -#ifndef WDT_H_INCLUDED -#define WDT_H_INCLUDED - -/** - * \defgroup asfdoc_sam0_wdt_group SAM Watchdog Driver (WDT) - * - * This driver for Atmel® | SMART SAM devices provides an interface for the configuration - * and management of the device's Watchdog Timer module, including the enabling, - * disabling, and kicking within the device. The following driver API modes are - * covered by this manual: - * - * - Polled APIs - * \if WDT_CALLBACK_MODE - * - Callback APIs - * \endif - * - * The following peripherals are used by this module: - * - WDT (Watchdog Timer) - * - * The following devices can use this module: - * - Atmel | SMART SAM D20/D21 - * - Atmel | SMART SAM R21 - * - Atmel | SMART SAM D09/D10/D11 - * - Atmel | SMART SAM L21/L22 - * - Atmel | SMART SAM DA1 - * - Atmel | SMART SAM C20/C21 - * - * The outline of this documentation is as follows: - * - \ref asfdoc_sam0_wdt_prerequisites - * - \ref asfdoc_sam0_wdt_module_overview - * - \ref asfdoc_sam0_wdt_special_considerations - * - \ref asfdoc_sam0_wdt_extra_info - * - \ref asfdoc_sam0_wdt_examples - * - \ref asfdoc_sam0_wdt_api_overview - * - * - * \section asfdoc_sam0_wdt_prerequisites Prerequisites - * - * There are no prerequisites for this module. - * - * - * \section asfdoc_sam0_wdt_module_overview Module Overview - * - * The Watchdog module (WDT) is designed to give an added level of safety in - * critical systems, to ensure a system reset is triggered in the case of a - * deadlock or other software malfunction that prevents normal device operation. - * - * At a basic level, the Watchdog is a system timer with a fixed period; once - * enabled, it will continue to count ticks of its asynchronous clock until - * it is periodically reset, or the timeout period is reached. In the event of a - * Watchdog timeout, the module will trigger a system reset identical to a pulse - * of the device's reset pin, resetting all peripherals to their power-on - * default states and restarting the application software from the reset vector. - * - * In many systems, there is an obvious upper bound to the amount of time each - * iteration of the main application loop can be expected to run, before a - * malfunction can be assumed (either due to a deadlock waiting on hardware or - * software, or due to other means). When the Watchdog is configured with a - * timeout period equal to this upper bound, a malfunction in the system will - * force a full system reset to allow for a graceful recovery. - * - * \subsection asfdoc_sam0_wdt_module_locked_mode Locked Mode - * The Watchdog configuration can be set in the device fuses and locked in - * hardware, so that no software changes can be made to the Watchdog - * configuration. Additionally, the Watchdog can be locked on in software if it - * is not already locked, so that the module configuration cannot be modified - * until a power on reset of the device. - * - * The locked configuration can be used to ensure that faulty software does not - * cause the Watchdog configuration to be changed, preserving the level of - * safety given by the module. - * - * \subsection asfdoc_sam0_wdt_module_window_mode Window Mode - * Just as there is a reasonable upper bound to the time the main program loop - * should take for each iteration, there is also in many applications a lower - * bound, i.e. a \a minimum time for which each loop iteration should run for - * under normal circumstances. To guard against a system failure resetting the - * Watchdog in a tight loop (or a failure in the system application causing the - * main loop to run faster than expected) a "Window" mode can be enabled to - * disallow resetting of the Watchdog counter before a certain period of time. - * If the Watchdog is not reset \a after the window opens but not \a before the - * Watchdog expires, the system will reset. - * - * \subsection asfdoc_sam0_wdt_module_early_warning Early Warning - * In some cases it is desirable to receive an early warning that the Watchdog is - * about to expire, so that some system action (such as saving any system - * configuration data for failure analysis purposes) can be performed before the - * system reset occurs. The Early Warning feature of the Watchdog module allows - * such a notification to be requested; after the configured early warning time - * (but before the expiry of the Watchdog counter) the Early Warning flag will - * become set, so that the user application can take an appropriate action. - * - * \note It is important to note that the purpose of the Early Warning feature - * is \a not to allow the user application to reset the Watchdog; doing - * so will defeat the safety the module gives to the user application. - * Instead, this feature should be used purely to perform any tasks that - * need to be undertaken before the system reset occurs. - * - * \subsection asfdoc_sam0_wdt_module_overview_physical Physical Connection - * - * \ref asfdoc_sam0_wdt_module_int_connections "The figure below" shows how - * this module is interconnected within the device. - * - * \anchor asfdoc_sam0_wdt_module_int_connections - * \dot - * digraph overview { - * rankdir=LR; - * node [label="GCLK*\nGeneric Clock" shape=square] wdt_clock; - * - * subgraph driver { - * node [label=" WDT | Watchdog Counter" shape=record] wdt_module; - * node [label="System Reset Logic" shape=ellipse style=filled fillcolor=lightgray] sys_reset; - * } - * - * wdt_clock -> wdt_module:f1; - * wdt_module:f1 -> sys_reset; - * } - * \enddot - * - * \note Watchdog Counter of SAM L21/L22 is \a not provided by GCLK, but it uses an - * internal 1KHz OSCULP32K output clock. - * - * \section asfdoc_sam0_wdt_special_considerations Special Considerations - * - * On some devices the Watchdog configuration can be fused to be always on in - * a particular configuration; if this mode is enabled the Watchdog is not - * software configurable and can have its count reset and early warning state - * checked/cleared only. - * - * \section asfdoc_sam0_wdt_extra_info Extra Information - * - * For extra information, see \ref asfdoc_sam0_wdt_extra. This includes: - * - \ref asfdoc_sam0_wdt_extra_acronyms - * - \ref asfdoc_sam0_wdt_extra_dependencies - * - \ref asfdoc_sam0_wdt_extra_errata - * - \ref asfdoc_sam0_wdt_extra_history - * - * - * \section asfdoc_sam0_wdt_examples Examples - * - * For a list of examples related to this driver, see - * \ref asfdoc_sam0_wdt_exqsg. - * - * \section asfdoc_sam0_wdt_api_overview API Overview - * @{ - */ - -#include -#include -#include - -#if WDT_CALLBACK_MODE == true -# include "wdt_callback.h" -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief Watchdog Timer period configuration enum. - * - * Enum for the possible period settings of the Watchdog timer module, for - * values requiring a period as a number of Watchdog timer clock ticks. - */ -enum wdt_period { - /** No Watchdog period. This value can only be used when setting the - * Window and Early Warning periods; its use as the Watchdog Reset - * Period is invalid. */ - WDT_PERIOD_NONE = 0, - /** Watchdog period of 8 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_8CLK = 1, - /** Watchdog period of 16 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_16CLK = 2, - /** Watchdog period of 32 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_32CLK = 3, - /** Watchdog period of 64 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_64CLK = 4, - /** Watchdog period of 128 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_128CLK = 5, - /** Watchdog period of 256 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_256CLK = 6, - /** Watchdog period of 512 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_512CLK = 7, - /** Watchdog period of 1024 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_1024CLK = 8, - /** Watchdog period of 2048 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_2048CLK = 9, - /** Watchdog period of 4096 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_4096CLK = 10, - /** Watchdog period of 8192 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_8192CLK = 11, - /** Watchdog period of 16384 clocks of the Watchdog Timer Generic Clock. */ - WDT_PERIOD_16384CLK = 12, -}; - -/** - * \brief Watchdog Timer configuration structure. - * - * Configuration structure for a Watchdog Timer instance. This - * structure should be initialized by the \ref wdt_get_config_defaults() - * function before being modified by the user application. - */ -struct wdt_conf { - /** If \c true, the Watchdog will be locked to the current configuration - * settings when the Watchdog is enabled. */ - bool always_on; - /** Enable/Disable the Watchdog Timer. */ - bool enable; -#if !(SAML21) && !(SAML22) && !(SAMC20) && !(SAMC21) - /** GCLK generator used to clock the peripheral except SAM L21/L22/C21/C20.*/ - enum gclk_generator clock_source; -#endif - /** Number of Watchdog timer clock ticks until the Watchdog expires. */ - enum wdt_period timeout_period; - /** Number of Watchdog timer clock ticks until the reset window opens. */ - enum wdt_period window_period; - /** Number of Watchdog timer clock ticks until the early warning flag is - * set. */ - enum wdt_period early_warning_period; -}; - -/** \name Configuration and Initialization - * @{ - */ - -/** - * \brief Determines if the hardware module(s) are currently synchronizing to the bus. - * - * Checks to see if the underlying hardware peripheral module(s) are currently - * synchronizing across multiple clock domains to the hardware bus. This - * function can be used to delay further operations on a module until such time - * that it is ready, to prevent blocking delays for synchronization in the - * user application. - * - * \return Synchronization status of the underlying hardware module(s). - * - * \retval false If the module has completed synchronization - * \retval true If the module synchronization is ongoing - */ -static inline bool wdt_is_syncing(void) -{ - Wdt *const WDT_module = WDT; - -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) - if (WDT_module->SYNCBUSY.reg) { -#else - if (WDT_module->STATUS.reg & WDT_STATUS_SYNCBUSY) { -#endif - return true; - } - - return false; -} - -/** - * \brief Initializes a Watchdog Timer configuration structure to defaults. - * - * Initializes a given Watchdog Timer configuration structure to a set of - * known default values. This function should be called on all new - * instances of these configuration structures before being modified by the - * user application. - * - * The default configuration is as follows: - * \li Not locked, to allow for further (re-)configuration - * \li Enable WDT - * \li Watchdog timer sourced from Generic Clock Channel 4 - * \li A timeout period of 16384 clocks of the Watchdog module clock - * \li No window period, so that the Watchdog count can be reset at any time - * \li No early warning period to indicate the Watchdog will soon expire - * - * \param[out] config Configuration structure to initialize to default values - */ -static inline void wdt_get_config_defaults( - struct wdt_conf *const config) -{ - /* Sanity check arguments */ - Assert(config); - - /* Default configuration values */ - config->always_on = false; - config->enable = true; -#if !(SAML21) && !(SAML22) && !(SAMC20) && !(SAMC21) - config->clock_source = GCLK_GENERATOR_4; -#endif - config->timeout_period = WDT_PERIOD_16384CLK; - config->window_period = WDT_PERIOD_NONE; - config->early_warning_period = WDT_PERIOD_NONE; -} - -enum status_code wdt_set_config( - const struct wdt_conf *const config); - -/** \brief Determines if the Watchdog timer is currently locked in an enabled state. - * - * Determines if the Watchdog timer is currently enabled and locked, so that - * it cannot be disabled or otherwise reconfigured. - * - * \return Current Watchdog lock state. - */ -static inline bool wdt_is_locked(void) -{ - Wdt *const WDT_module = WDT; - -#if (SAML21) || (SAML22) || (SAMC20) || (SAMC21) - return (WDT_module->CTRLA.reg & WDT_CTRLA_ALWAYSON); -#else - return (WDT_module->CTRL.reg & WDT_CTRL_ALWAYSON); -#endif -} - -/** @} */ - -/** \name Timeout and Early Warning Management - * @{ - */ - -/** \brief Clears the Watchdog timer early warning period elapsed flag. - * - * Clears the Watchdog timer early warning period elapsed flag, so that a new - * early warning period can be detected. - */ -static inline void wdt_clear_early_warning(void) -{ - Wdt *const WDT_module = WDT; - - WDT_module->INTFLAG.reg = WDT_INTFLAG_EW; -} - -/** \brief Determines if the Watchdog timer early warning period has elapsed. - * - * Determines if the Watchdog timer early warning period has elapsed. - * - * \note If no early warning period was configured, the value returned by this - * function is invalid. - * - * \return Current Watchdog Early Warning state. - */ -static inline bool wdt_is_early_warning(void) -{ - Wdt *const WDT_module = WDT; - - return (WDT_module->INTFLAG.reg & WDT_INTFLAG_EW); -} - -void wdt_reset_count(void); - -/** @} */ - -#ifdef __cplusplus -} -#endif - -/** @} */ - -/** - * \page asfdoc_sam0_wdt_extra Extra Information for WDT Driver - * - * \section asfdoc_sam0_wdt_extra_acronyms Acronyms - * The table below presents the acronyms used in this module: - * - * - * - * - * - * - * - * - * - * - *
AcronymDescription
WDTWatchdog Timer
- * - * - * \section asfdoc_sam0_wdt_extra_dependencies Dependencies - * This driver has the following dependencies: - * - * - \ref asfdoc_sam0_system_clock_group "System Clock Driver" - * - * - * \section asfdoc_sam0_wdt_extra_errata Errata - * There are no errata related to this driver. - * - * - * \section asfdoc_sam0_wdt_extra_history Module History - * An overview of the module history is presented in the table below, with - * details on the enhancements and fixes made to the module since its first - * release. The current version of this corresponds to the newest version in - * the table. - * - * - * - * - * - * - * - * - * - * - * - *
Changelog
Driver updated to follow driver type convention: - * \li wdt_init, wdt_enable, wdt_disable functions removed - * \li wdt_set_config function added - * \li WDT module enable state moved inside the configuration struct
Initial Release
- */ - -/** - * \page asfdoc_sam0_wdt_exqsg Examples for WDT Driver - * - * This is a list of the available Quick Start guides (QSGs) and example - * applications for \ref asfdoc_sam0_wdt_group. QSGs are simple examples with - * step-by-step instructions to configure and use this driver in a selection of - * use cases. Note that QSGs can be compiled as a standalone application or be - * added to the user application. - * - * - \subpage asfdoc_sam0_wdt_basic_use_case - * \if WDT_CALLBACK_MODE - * - \subpage asfdoc_sam0_wdt_callback_use_case - * \endif - * - * \page asfdoc_sam0_wdt_document_revision_history Document Revision History - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Doc. Rev. - * Date - * Comments - *
E08/2015Added support for SAM L21/L22, SAM DA1, and SAM C20/C2
D12/2014Added SAMR21 and SAMD10/D11 support
C01/2014Add SAMD21 support
B06/2013Corrected documentation typos
A06/2013Initial release
- */ - -#endif /* WDT_H_INCLUDED */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp deleted file mode 100644 index fe721be..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/Adafruit_FONA.cpp +++ /dev/null @@ -1,2079 +0,0 @@ -/*************************************************** - This is a library for our Adafruit FONA Cellular Module - - Designed specifically to work with the Adafruit FONA - ----> http://www.adafruit.com/products/1946 - ----> http://www.adafruit.com/products/1963 - - These displays use TTL Serial to communicate, 2 pins are required to - interface - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - BSD license, all text above must be included in any redistribution - ****************************************************/ - // next line per http://postwarrior.com/arduino-ethershield-error-prog_char-does-not-name-a-type/ - -#include "Adafruit_FONA.h" - - - - -Adafruit_FONA::Adafruit_FONA(int8_t rst) -{ - _rstpin = rst; - - apn = F("FONAnet"); - apnusername = 0; - apnpassword = 0; - mySerial = 0; - httpsredirect = false; - useragent = F("FONA"); - ok_reply = F("OK"); -} - -uint8_t Adafruit_FONA::type(void) { - return _type; -} - -boolean Adafruit_FONA::begin(Stream &port) { - mySerial = &port; - - pinMode(_rstpin, OUTPUT); - digitalWrite(_rstpin, HIGH); - delay(10); - digitalWrite(_rstpin, LOW); - delay(100); - digitalWrite(_rstpin, HIGH); - - DEBUG_PRINTLN(F("Attempting to open comm with ATs")); - // give 7 seconds to reboot - int16_t timeout = 7000; - - while (timeout > 0) { - while (mySerial->available()) mySerial->read(); - if (sendCheckReply(F("AT"), ok_reply)) - break; - while (mySerial->available()) mySerial->read(); - if (sendCheckReply(F("AT"), F("AT"))) - break; - delay(500); - timeout-=500; - } - -#ifdef ADAFRUIT_FONA_DEBUG - if (timeout <= 0) - DEBUG_PRINTLN(F("Timeout: No response to AT... last ditch attempt.")); -#endif - - sendCheckReply(F("AT"), ok_reply); - delay(100); - sendCheckReply(F("AT"), ok_reply); - delay(100); - sendCheckReply(F("AT"), ok_reply); - delay(100); - - // turn off Echo! - sendCheckReply(F("ATE0"), ok_reply); - delay(100); - - if (! sendCheckReply(F("ATE0"), ok_reply)) { - return false; - } - - // turn on hangupitude - sendCheckReply(F("AT+CVHU=0"), ok_reply); - - delay(100); - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN("ATI"); - - mySerial->println("ATI"); - readline(500, true); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - - - if (prog_char_strstr(replybuffer, (prog_char *)F("SIM808 R14")) != 0) { - _type = FONA808_V2; - } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIM808 R13")) != 0) { - _type = FONA808_V1; - } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIM800 R14")) != 0) { - _type = FONA800L; - } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIMCOM_SIM5320A")) != 0) { - _type = FONA3G_A; - } else if (prog_char_strstr(replybuffer, (prog_char *)F("SIMCOM_SIM5320E")) != 0) { - _type = FONA3G_E; - } - - if (_type == FONA800L) { - // determine if L or H - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN("AT+GMM"); - - mySerial->println("AT+GMM"); - readline(500, true); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - - if (prog_char_strstr(replybuffer, (prog_char *)F("SIM800H")) != 0) { - _type = FONA800H; - } - } - -#if defined(FONA_PREF_SMS_STORAGE) - sendCheckReply(F("AT+CPMS=\"" FONA_PREF_SMS_STORAGE "\""), ok_reply); -#endif - - return true; -} - - -/********* Serial port ********************************************/ -boolean Adafruit_FONA::setBaudrate(uint16_t baud) { - return sendCheckReply(F("AT+IPREX="), baud, ok_reply); -} - -/********* Real Time Clock ********************************************/ - -boolean Adafruit_FONA::readRTC(uint8_t *year, uint8_t *month, uint8_t *date, uint8_t *hr, uint8_t *min, uint8_t *sec) { - uint16_t v; - sendParseReply(F("AT+CCLK?"), F("+CCLK: "), &v, '/', 0); - *year = v; - - DEBUG_PRINTLN(*year); -} - -boolean Adafruit_FONA::enableRTC(uint8_t i) { - if (! sendCheckReply(F("AT+CLTS="), i, ok_reply)) - return false; - return sendCheckReply(F("AT&W"), ok_reply); -} - - -/********* BATTERY & ADC ********************************************/ - -/* returns value in mV (uint16_t) */ -boolean Adafruit_FONA::getBattVoltage(uint16_t *v) { - return sendParseReply(F("AT+CBC"), F("+CBC: "), v, ',', 2); -} - -/* returns value in mV (uint16_t) */ -boolean Adafruit_FONA_3G::getBattVoltage(uint16_t *v) { - float f; - boolean b = sendParseReply(F("AT+CBC"), F("+CBC: "), &f, ',', 2); - *v = f*1000; - return b; -} - - -/* returns the percentage charge of battery as reported by sim800 */ -boolean Adafruit_FONA::getBattPercent(uint16_t *p) { - return sendParseReply(F("AT+CBC"), F("+CBC: "), p, ',', 1); -} - -boolean Adafruit_FONA::getADCVoltage(uint16_t *v) { - return sendParseReply(F("AT+CADC?"), F("+CADC: 1,"), v); -} - -/********* SIM ***********************************************************/ - -uint8_t Adafruit_FONA::unlockSIM(char *pin) -{ - char sendbuff[14] = "AT+CPIN="; - sendbuff[8] = pin[0]; - sendbuff[9] = pin[1]; - sendbuff[10] = pin[2]; - sendbuff[11] = pin[3]; - sendbuff[12] = '\0'; - - return sendCheckReply(sendbuff, ok_reply); -} - -uint8_t Adafruit_FONA::getSIMCCID(char *ccid) { - getReply(F("AT+CCID")); - // up to 28 chars for reply, 20 char total ccid - if (replybuffer[0] == '+') { - // fona 3g? - strncpy(ccid, replybuffer+8, 20); - } else { - // fona 800 or 800 - strncpy(ccid, replybuffer, 20); - } - ccid[20] = 0; - - readline(); // eat 'OK' - - return strlen(ccid); -} - -/********* IMEI **********************************************************/ - -uint8_t Adafruit_FONA::getIMEI(char *imei) { - getReply(F("AT+GSN")); - - // up to 15 chars - strncpy(imei, replybuffer, 15); - imei[15] = 0; - - readline(); // eat 'OK' - - return strlen(imei); -} - -/********* NETWORK *******************************************************/ - -uint8_t Adafruit_FONA::getNetworkStatus(void) { - uint16_t status; - - if (! sendParseReply(F("AT+CREG?"), F("+CREG: "), &status, ',', 1)) return 0; - - return status; -} - - -uint8_t Adafruit_FONA::getRSSI(void) { - uint16_t reply; - - if (! sendParseReply(F("AT+CSQ"), F("+CSQ: "), &reply) ) return 0; - - return reply; -} - -/********* AUDIO *******************************************************/ - -boolean Adafruit_FONA::setAudio(uint8_t a) { - // 0 is headset, 1 is external audio - if (a > 1) return false; - - return sendCheckReply(F("AT+CHFA="), a, ok_reply); -} - -uint8_t Adafruit_FONA::getVolume(void) { - uint16_t reply; - - if (! sendParseReply(F("AT+CLVL?"), F("+CLVL: "), &reply) ) return 0; - - return reply; -} - -boolean Adafruit_FONA::setVolume(uint8_t i) { - return sendCheckReply(F("AT+CLVL="), i, ok_reply); -} - - -boolean Adafruit_FONA::playDTMF(char dtmf) { - char str[4]; - str[0] = '\"'; - str[1] = dtmf; - str[2] = '\"'; - str[3] = 0; - return sendCheckReply(F("AT+CLDTMF=3,"), str, ok_reply); -} - -boolean Adafruit_FONA::playToolkitTone(uint8_t t, uint16_t len) { - return sendCheckReply(F("AT+STTONE=1,"), t, len, ok_reply); -} - -boolean Adafruit_FONA_3G::playToolkitTone(uint8_t t, uint16_t len) { - if (! sendCheckReply(F("AT+CPTONE="), t, ok_reply)) - return false; - delay(len); - return sendCheckReply(F("AT+CPTONE=0"), ok_reply); -} - -boolean Adafruit_FONA::setMicVolume(uint8_t a, uint8_t level) { - // 0 is headset, 1 is external audio - if (a > 1) return false; - - return sendCheckReply(F("AT+CMIC="), a, level, ok_reply); -} - -/********* FM RADIO *******************************************************/ - - -boolean Adafruit_FONA::FMradio(boolean onoff, uint8_t a) { - if (! onoff) { - return sendCheckReply(F("AT+FMCLOSE"), ok_reply); - } - - // 0 is headset, 1 is external audio - if (a > 1) return false; - - return sendCheckReply(F("AT+FMOPEN="), a, ok_reply); -} - -boolean Adafruit_FONA::tuneFMradio(uint16_t station) { - // Fail if FM station is outside allowed range. - if ((station < 870) || (station > 1090)) - return false; - - return sendCheckReply(F("AT+FMFREQ="), station, ok_reply); -} - -boolean Adafruit_FONA::setFMVolume(uint8_t i) { - // Fail if volume is outside allowed range (0-6). - if (i > 6) { - return false; - } - // Send FM volume command and verify response. - return sendCheckReply(F("AT+FMVOLUME="), i, ok_reply); -} - -int8_t Adafruit_FONA::getFMVolume() { - uint16_t level; - - if (! sendParseReply(F("AT+FMVOLUME?"), F("+FMVOLUME: "), &level) ) return 0; - - return level; -} - -int8_t Adafruit_FONA::getFMSignalLevel(uint16_t station) { - // Fail if FM station is outside allowed range. - if ((station < 875) || (station > 1080)) { - return -1; - } - - // Send FM signal level query command. - // Note, need to explicitly send timeout so right overload is chosen. - getReply(F("AT+FMSIGNAL="), station, FONA_DEFAULT_TIMEOUT_MS); - // Check response starts with expected value. - char *p = prog_char_strstr(replybuffer, PSTR("+FMSIGNAL: ")); - if (p == 0) return -1; - p+=11; - // Find second colon to get start of signal quality. - p = strchr(p, ':'); - if (p == 0) return -1; - p+=1; - // Parse signal quality. - int8_t level = atoi(p); - readline(); // eat the "OK" - return level; -} - -/********* PWM/BUZZER **************************************************/ - -boolean Adafruit_FONA::setPWM(uint16_t period, uint8_t duty) { - if (period > 2000) return false; - if (duty > 100) return false; - - return sendCheckReply(F("AT+SPWM=0,"), period, duty, ok_reply); -} - -/********* CALL PHONES **************************************************/ -boolean Adafruit_FONA::callPhone(char *number) { - char sendbuff[35] = "ATD"; - strncpy(sendbuff+3, number, min(30, strlen(number))); - uint8_t x = strlen(sendbuff); - sendbuff[x] = ';'; - sendbuff[x+1] = 0; - //DEBUG_PRINTLN(sendbuff); - - return sendCheckReply(sendbuff, ok_reply); -} - - -uint8_t Adafruit_FONA::getCallStatus(void) { - uint16_t phoneStatus; - - if (! sendParseReply(F("AT+CPAS"), F("+CPAS: "), &phoneStatus)) - return FONA_CALL_FAILED; // 1, since 0 is actually a known, good reply - - return phoneStatus; // 0 ready, 2 unkown, 3 ringing, 4 call in progress -} - -boolean Adafruit_FONA::hangUp(void) { - return sendCheckReply(F("ATH0"), ok_reply); -} - -boolean Adafruit_FONA_3G::hangUp(void) { - getReply(F("ATH")); - - return (prog_char_strstr(replybuffer, (prog_char *)F("VOICE CALL: END")) != 0); -} - -boolean Adafruit_FONA::pickUp(void) { - return sendCheckReply(F("ATA"), ok_reply); -} - -boolean Adafruit_FONA_3G::pickUp(void) { - return sendCheckReply(F("ATA"), F("VOICE CALL: BEGIN")); -} - - -void Adafruit_FONA::onIncomingCall() { - - DEBUG_PRINT(F("> ")); DEBUG_PRINTLN(F("Incoming call...")); - - Adafruit_FONA::_incomingCall = true; -} - -boolean Adafruit_FONA::_incomingCall = false; - -boolean Adafruit_FONA::callerIdNotification(boolean enable, uint8_t interrupt) { - if(enable){ - attachInterrupt(interrupt, onIncomingCall, FALLING); - return sendCheckReply(F("AT+CLIP=1"), ok_reply); - } - - detachInterrupt(interrupt); - return sendCheckReply(F("AT+CLIP=0"), ok_reply); -} - -boolean Adafruit_FONA::incomingCallNumber(char* phonenum) { - //+CLIP: "",145,"",0,"",0 - if(!Adafruit_FONA::_incomingCall) - return false; - - readline(); - while(!prog_char_strcmp(replybuffer, (prog_char*)F("RING")) == 0) { - flushInput(); - readline(); - } - - readline(); //reads incoming phone number line - - parseReply(F("+CLIP: \""), phonenum, '"'); - - - DEBUG_PRINT(F("Phone Number: ")); - DEBUG_PRINTLN(replybuffer); - - - Adafruit_FONA::_incomingCall = false; - return true; -} - -/********* SMS **********************************************************/ - -uint8_t Adafruit_FONA::getSMSInterrupt(void) { - uint16_t reply; - - if (! sendParseReply(F("AT+CFGRI?"), F("+CFGRI: "), &reply) ) return 0; - - return reply; -} - -boolean Adafruit_FONA::setSMSInterrupt(uint8_t i) { - return sendCheckReply(F("AT+CFGRI="), i, ok_reply); -} - -int8_t Adafruit_FONA::getNumSMS(void) { - uint16_t numsms; - - // get into text mode - if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return -1; - - // ask how many sms are stored - if (sendParseReply(F("AT+CPMS?"), F("\"SM\","), &numsms)) - return numsms; - if (sendParseReply(F("AT+CPMS?"), F("\"SM_P\","), &numsms)) - return numsms; - return -1; -} - -// Reading SMS's is a bit involved so we don't use helpers that may cause delays or debug -// printouts! -boolean Adafruit_FONA::readSMS(uint8_t i, char *smsbuff, - uint16_t maxlen, uint16_t *readlen) { - // text mode - if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return false; - - // show all text mode parameters - if (! sendCheckReply(F("AT+CSDH=1"), ok_reply)) return false; - - // parse out the SMS len - uint16_t thesmslen = 0; - - - DEBUG_PRINT(F("AT+CMGR=")); - DEBUG_PRINTLN(i); - - - //getReply(F("AT+CMGR="), i, 1000); // do not print debug! - mySerial->print(F("AT+CMGR=")); - mySerial->println(i); - readline(1000); // timeout - - //DEBUG_PRINT(F("Reply: ")); DEBUG_PRINTLN(replybuffer); - // parse it out... - - - DEBUG_PRINTLN(replybuffer); - - - if (! parseReply(F("+CMGR:"), &thesmslen, ',', 11)) { - *readlen = 0; - return false; - } - - readRaw(thesmslen); - - flushInput(); - - uint16_t thelen = min(maxlen, strlen(replybuffer)); - strncpy(smsbuff, replybuffer, thelen); - smsbuff[thelen] = 0; // end the string - - - DEBUG_PRINTLN(replybuffer); - - *readlen = thelen; - return true; -} - -// Retrieve the sender of the specified SMS message and copy it as a string to -// the sender buffer. Up to senderlen characters of the sender will be copied -// and a null terminator will be added if less than senderlen charactesr are -// copied to the result. Returns true if a result was successfully retrieved, -// otherwise false. -boolean Adafruit_FONA::getSMSSender(uint8_t i, char *sender, int senderlen) { - // Ensure text mode and all text mode parameters are sent. - if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return false; - if (! sendCheckReply(F("AT+CSDH=1"), ok_reply)) return false; - - - DEBUG_PRINT(F("AT+CMGR=")); - DEBUG_PRINTLN(i); - - - // Send command to retrieve SMS message and parse a line of response. - mySerial->print(F("AT+CMGR=")); - mySerial->println(i); - readline(1000); - - - DEBUG_PRINTLN(replybuffer); - - - // Parse the second field in the response. - boolean result = parseReplyQuoted(F("+CMGR:"), sender, senderlen, ',', 1); - // Drop any remaining data from the response. - flushInput(); - return result; -} - -boolean Adafruit_FONA::sendSMS(char *smsaddr, char *smsmsg) { - if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return -1; - - char sendcmd[30] = "AT+CMGS=\""; - strncpy(sendcmd+9, smsaddr, 30-9-2); // 9 bytes beginning, 2 bytes for close quote + null - sendcmd[strlen(sendcmd)] = '\"'; - - if (! sendCheckReply(sendcmd, F("> "))) return false; - - DEBUG_PRINT(F("> ")); DEBUG_PRINTLN(smsmsg); - - mySerial->println(smsmsg); - mySerial->println(); - mySerial->write(0x1A); - - DEBUG_PRINTLN("^Z"); - - if ( (_type == FONA3G_A) || (_type == FONA3G_E) ) { - // Eat two sets of CRLF - readline(200); - //DEBUG_PRINT("Line 1: "); DEBUG_PRINTLN(strlen(replybuffer)); - readline(200); - //DEBUG_PRINT("Line 2: "); DEBUG_PRINTLN(strlen(replybuffer)); - } - readline(10000); // read the +CMGS reply, wait up to 10 seconds!!! - //DEBUG_PRINT("Line 3: "); DEBUG_PRINTLN(strlen(replybuffer)); - if (strstr(replybuffer, "+CMGS") == 0) { - return false; - } - readline(1000); // read OK - //DEBUG_PRINT("* "); DEBUG_PRINTLN(replybuffer); - - if (strcmp(replybuffer, "OK") != 0) { - return false; - } - - return true; -} - - -boolean Adafruit_FONA::deleteSMS(uint8_t i) { - if (! sendCheckReply(F("AT+CMGF=1"), ok_reply)) return -1; - // read an sms - char sendbuff[12] = "AT+CMGD=000"; - sendbuff[8] = (i / 100) + '0'; - i %= 100; - sendbuff[9] = (i / 10) + '0'; - i %= 10; - sendbuff[10] = i + '0'; - - return sendCheckReply(sendbuff, ok_reply, 2000); -} - -/********* USSD *********************************************************/ - -boolean Adafruit_FONA::sendUSSD(char *ussdmsg, char *ussdbuff, uint16_t maxlen, uint16_t *readlen) { - if (! sendCheckReply(F("AT+CUSD=1"), ok_reply)) return -1; - - char sendcmd[30] = "AT+CUSD=1,\""; - strncpy(sendcmd+11, ussdmsg, 30-11-2); // 11 bytes beginning, 2 bytes for close quote + null - sendcmd[strlen(sendcmd)] = '\"'; - - if (! sendCheckReply(sendcmd, ok_reply)) { - *readlen = 0; - return false; - } else { - readline(10000); // read the +CUSD reply, wait up to 10 seconds!!! - //DEBUG_PRINT("* "); DEBUG_PRINTLN(replybuffer); - char *p = prog_char_strstr(replybuffer, PSTR("+CUSD: ")); - if (p == 0) { - *readlen = 0; - return false; - } - p+=7; //+CUSD - // Find " to get start of ussd message. - p = strchr(p, '\"'); - if (p == 0) { - *readlen = 0; - return false; - } - p+=1; //" - // Find " to get end of ussd message. - char *strend = strchr(p, '\"'); - - uint16_t lentocopy = min(maxlen-1, strend - p); - strncpy(ussdbuff, p, lentocopy+1); - ussdbuff[lentocopy] = 0; - *readlen = lentocopy; - } - return true; -} - - -/********* TIME **********************************************************/ - -boolean Adafruit_FONA::enableNetworkTimeSync(boolean onoff) { - if (onoff) { - if (! sendCheckReply(F("AT+CLTS=1"), ok_reply)) - return false; - } else { - if (! sendCheckReply(F("AT+CLTS=0"), ok_reply)) - return false; - } - - flushInput(); // eat any 'Unsolicted Result Code' - - return true; -} - -boolean Adafruit_FONA::enableNTPTimeSync(boolean onoff, FONAFlashStringPtr ntpserver) { - if (onoff) { - if (! sendCheckReply(F("AT+CNTPCID=1"), ok_reply)) - return false; - - mySerial->print(F("AT+CNTP=\"")); - if (ntpserver != 0) { - mySerial->print(ntpserver); - } else { - mySerial->print(F("pool.ntp.org")); - } - mySerial->println(F("\",0")); - readline(FONA_DEFAULT_TIMEOUT_MS); - if (strcmp(replybuffer, "OK") != 0) - return false; - - if (! sendCheckReply(F("AT+CNTP"), ok_reply, 10000)) - return false; - - uint16_t status; - readline(10000); - if (! parseReply(F("+CNTP:"), &status)) - return false; - } else { - if (! sendCheckReply(F("AT+CNTPCID=0"), ok_reply)) - return false; - } - - return true; -} - -boolean Adafruit_FONA::getTime(char *buff, uint16_t maxlen) { - getReply(F("AT+CCLK?"), (uint16_t) 10000); - if (strncmp(replybuffer, "+CCLK: ", 7) != 0) - return false; - - char *p = replybuffer+7; - uint16_t lentocopy = min(maxlen-1, strlen(p)); - strncpy(buff, p, lentocopy+1); - buff[lentocopy] = 0; - - readline(); // eat OK - - return true; -} - -/********* GPS **********************************************************/ - - -boolean Adafruit_FONA::enableGPS(boolean onoff) { - uint16_t state; - - // first check if its already on or off - - if (_type == FONA808_V2) { - if (! sendParseReply(F("AT+CGNSPWR?"), F("+CGNSPWR: "), &state) ) - return false; - } else { - if (! sendParseReply(F("AT+CGPSPWR?"), F("+CGPSPWR: "), &state)) - return false; - } - - if (onoff && !state) { - if (_type == FONA808_V2) { - if (! sendCheckReply(F("AT+CGNSPWR=1"), ok_reply)) // try GNS command - return false; - } else { - if (! sendCheckReply(F("AT+CGPSPWR=1"), ok_reply)) - return false; - } - } else if (!onoff && state) { - if (_type == FONA808_V2) { - if (! sendCheckReply(F("AT+CGNSPWR=0"), ok_reply)) // try GNS command - return false; - } else { - if (! sendCheckReply(F("AT+CGPSPWR=0"), ok_reply)) - return false; - } - } - return true; -} - - - -boolean Adafruit_FONA_3G::enableGPS(boolean onoff) { - uint16_t state; - - // first check if its already on or off - if (! Adafruit_FONA::sendParseReply(F("AT+CGPS?"), F("+CGPS: "), &state) ) - return false; - - if (onoff && !state) { - if (! sendCheckReply(F("AT+CGPS=1"), ok_reply)) - return false; - } else if (!onoff && state) { - if (! sendCheckReply(F("AT+CGPS=0"), ok_reply)) - return false; - // this takes a little time - readline(2000); // eat '+CGPS: 0' - } - return true; -} - -int8_t Adafruit_FONA::GPSstatus(void) { - if (_type == FONA808_V2) { - // 808 V2 uses GNS commands and doesn't have an explicit 2D/3D fix status. - // Instead just look for a fix and if found assume it's a 3D fix. - getReply(F("AT+CGNSINF")); - char *p = prog_char_strstr(replybuffer, (prog_char*)F("+CGNSINF: ")); - if (p == 0) return -1; - p+=12; // Skip to second value, fix status. - readline(); // eat 'OK' - //DEBUG_PRINTLN(p); - // Assume if the fix status is '1' then we have a 3D fix, otherwise no fix. - if (p[0] == '1') return 3; - else return 0; - } - if (_type == FONA3G_A || _type == FONA3G_E) { - // FONA 3G doesn't have an explicit 2D/3D fix status. - // Instead just look for a fix and if found assume it's a 3D fix. - getReply(F("AT+CGPSINFO")); - char *p = prog_char_strstr(replybuffer, (prog_char*)F("+CGPSINFO:")); - if (p == 0) return -1; - if (p[10] != ',') return 3; // if you get anything, its 3D fix - return 0; - } - else { - // 808 V1 looks for specific 2D or 3D fix state. - getReply(F("AT+CGPSSTATUS?")); - char *p = prog_char_strstr(replybuffer, (prog_char*)F("SSTATUS: Location ")); - if (p == 0) return -1; - p+=18; - readline(); // eat 'OK' - //DEBUG_PRINTLN(p); - if (p[0] == 'U') return 0; - if (p[0] == 'N') return 1; - if (p[0] == '2') return 2; - if (p[0] == '3') return 3; - } - // else - return 0; -} - -uint8_t Adafruit_FONA::getGPS(uint8_t arg, char *buffer, uint8_t maxbuff) { - int32_t x = arg; - - if ( (_type == FONA3G_A) || (_type == FONA3G_E) ) { - getReply(F("AT+CGPSINFO")); - } else if (_type == FONA808_V1) { - getReply(F("AT+CGPSINF="), x); - } else { - getReply(F("AT+CGNSINF")); - } - - char *p = prog_char_strstr(replybuffer, (prog_char*)F("SINF")); - if (p == 0) { - buffer[0] = 0; - return 0; - } - - p+=6; - - uint8_t len = max(maxbuff-1, strlen(p)); - strncpy(buffer, p, len); - buffer[len] = 0; - - readline(); // eat 'OK' - return len; -} - -boolean Adafruit_FONA::getGPS(float *lat, float *lon, float *speed_kph, float *heading, float *altitude) { - - char gpsbuffer[120]; - - // we need at least a 2D fix - if (GPSstatus() < 2) - return false; - - // grab the mode 2^5 gps csv from the sim808 - uint8_t res_len = getGPS(32, gpsbuffer, 120); - - // make sure we have a response - if (res_len == 0) - return false; - - if (_type == FONA3G_A || _type == FONA3G_E) { - // Parse 3G respose - // +CGPSINFO:4043.000000,N,07400.000000,W,151015,203802.1,-12.0,0.0,0 - // skip beginning - char *tok; - - // grab the latitude - char *latp = strtok(gpsbuffer, ","); - if (! latp) return false; - - // grab latitude direction - char *latdir = strtok(NULL, ","); - if (! latdir) return false; - - // grab longitude - char *longp = strtok(NULL, ","); - if (! longp) return false; - - // grab longitude direction - char *longdir = strtok(NULL, ","); - if (! longdir) return false; - - // skip date & time - tok = strtok(NULL, ","); - tok = strtok(NULL, ","); - - // only grab altitude if needed - if (altitude != NULL) { - // grab altitude - char *altp = strtok(NULL, ","); - if (! altp) return false; - *altitude = atof(altp); - } - - // only grab speed if needed - if (speed_kph != NULL) { - // grab the speed in km/h - char *speedp = strtok(NULL, ","); - if (! speedp) return false; - - *speed_kph = atof(speedp); - } - - // only grab heading if needed - if (heading != NULL) { - - // grab the speed in knots - char *coursep = strtok(NULL, ","); - if (! coursep) return false; - - *heading = atof(coursep); - } - - double latitude = atof(latp); - double longitude = atof(longp); - - // convert latitude from minutes to decimal - float degrees = floor(latitude / 100); - double minutes = latitude - (100 * degrees); - minutes /= 60; - degrees += minutes; - - // turn direction into + or - - if (latdir[0] == 'S') degrees *= -1; - - *lat = degrees; - - // convert longitude from minutes to decimal - degrees = floor(longitude / 100); - minutes = longitude - (100 * degrees); - minutes /= 60; - degrees += minutes; - - // turn direction into + or - - if (longdir[0] == 'W') degrees *= -1; - - *lon = degrees; - - } else if (_type == FONA808_V2) { - // Parse 808 V2 response. See table 2-3 from here for format: - // http://www.adafruit.com/datasheets/SIM800%20Series_GNSS_Application%20Note%20V1.00.pdf - - // skip GPS run status - char *tok = strtok(gpsbuffer, ","); - if (! tok) return false; - - // skip fix status - tok = strtok(NULL, ","); - if (! tok) return false; - - // skip date - tok = strtok(NULL, ","); - if (! tok) return false; - - // grab the latitude - char *latp = strtok(NULL, ","); - if (! latp) return false; - - // grab longitude - char *longp = strtok(NULL, ","); - if (! longp) return false; - - *lat = atof(latp); - *lon = atof(longp); - - // only grab altitude if needed - if (altitude != NULL) { - // grab altitude - char *altp = strtok(NULL, ","); - if (! altp) return false; - - *altitude = atof(altp); - } - - // only grab speed if needed - if (speed_kph != NULL) { - // grab the speed in km/h - char *speedp = strtok(NULL, ","); - if (! speedp) return false; - - *speed_kph = atof(speedp); - } - - // only grab heading if needed - if (heading != NULL) { - - // grab the speed in knots - char *coursep = strtok(NULL, ","); - if (! coursep) return false; - - *heading = atof(coursep); - } - } - else { - // Parse 808 V1 response. - - // skip mode - char *tok = strtok(gpsbuffer, ","); - if (! tok) return false; - - // skip date - tok = strtok(NULL, ","); - if (! tok) return false; - - // skip fix - tok = strtok(NULL, ","); - if (! tok) return false; - - // grab the latitude - char *latp = strtok(NULL, ","); - if (! latp) return false; - - // grab latitude direction - char *latdir = strtok(NULL, ","); - if (! latdir) return false; - - // grab longitude - char *longp = strtok(NULL, ","); - if (! longp) return false; - - // grab longitude direction - char *longdir = strtok(NULL, ","); - if (! longdir) return false; - - double latitude = atof(latp); - double longitude = atof(longp); - - // convert latitude from minutes to decimal - float degrees = floor(latitude / 100); - double minutes = latitude - (100 * degrees); - minutes /= 60; - degrees += minutes; - - // turn direction into + or - - if (latdir[0] == 'S') degrees *= -1; - - *lat = degrees; - - // convert longitude from minutes to decimal - degrees = floor(longitude / 100); - minutes = longitude - (100 * degrees); - minutes /= 60; - degrees += minutes; - - // turn direction into + or - - if (longdir[0] == 'W') degrees *= -1; - - *lon = degrees; - - // only grab speed if needed - if (speed_kph != NULL) { - - // grab the speed in knots - char *speedp = strtok(NULL, ","); - if (! speedp) return false; - - // convert to kph - *speed_kph = atof(speedp) * 1.852; - - } - - // only grab heading if needed - if (heading != NULL) { - - // grab the speed in knots - char *coursep = strtok(NULL, ","); - if (! coursep) return false; - - *heading = atof(coursep); - - } - - // no need to continue - if (altitude == NULL) - return true; - - // we need at least a 3D fix for altitude - if (GPSstatus() < 3) - return false; - - // grab the mode 0 gps csv from the sim808 - res_len = getGPS(0, gpsbuffer, 120); - - // make sure we have a response - if (res_len == 0) - return false; - - // skip mode - tok = strtok(gpsbuffer, ","); - if (! tok) return false; - - // skip lat - tok = strtok(NULL, ","); - if (! tok) return false; - - // skip long - tok = strtok(NULL, ","); - if (! tok) return false; - - // grab altitude - char *altp = strtok(NULL, ","); - if (! altp) return false; - - *altitude = atof(altp); - } - - return true; - -} - -boolean Adafruit_FONA::enableGPSNMEA(uint8_t i) { - - char sendbuff[15] = "AT+CGPSOUT=000"; - sendbuff[11] = (i / 100) + '0'; - i %= 100; - sendbuff[12] = (i / 10) + '0'; - i %= 10; - sendbuff[13] = i + '0'; - - if (_type == FONA808_V2) { - if (i) - return sendCheckReply(F("AT+CGNSTST=1"), ok_reply); - else - return sendCheckReply(F("AT+CGNSTST=0"), ok_reply); - } else { - return sendCheckReply(sendbuff, ok_reply, 2000); - } -} - - -/********* GPRS **********************************************************/ - - -boolean Adafruit_FONA::enableGPRS(boolean onoff) { - - if (onoff) { - // disconnect all sockets - sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 20000); - - if (! sendCheckReply(F("AT+CGATT=1"), ok_reply, 10000)) - return false; - - // set bearer profile! connection type GPRS - if (! sendCheckReply(F("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\""), - ok_reply, 10000)) - return false; - - // set bearer profile access point name - if (apn) { - // Send command AT+SAPBR=3,1,"APN","" where is the configured APN value. - if (! sendCheckReplyQuoted(F("AT+SAPBR=3,1,\"APN\","), apn, ok_reply, 10000)) - return false; - - // send AT+CSTT,"apn","user","pass" - flushInput(); - - mySerial->print(F("AT+CSTT=\"")); - mySerial->print(apn); - if (apnusername) { - mySerial->print("\",\""); - mySerial->print(apnusername); - } - if (apnpassword) { - mySerial->print("\",\""); - mySerial->print(apnpassword); - } - mySerial->println("\""); - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(F("AT+CSTT=\"")); - DEBUG_PRINT(apn); - - if (apnusername) { - DEBUG_PRINT("\",\""); - DEBUG_PRINT(apnusername); - } - if (apnpassword) { - DEBUG_PRINT("\",\""); - DEBUG_PRINT(apnpassword); - } - DEBUG_PRINTLN("\""); - - if (! expectReply(ok_reply)) return false; - - // set username/password - if (apnusername) { - // Send command AT+SAPBR=3,1,"USER","" where is the configured APN username. - if (! sendCheckReplyQuoted(F("AT+SAPBR=3,1,\"USER\","), apnusername, ok_reply, 10000)) - return false; - } - if (apnpassword) { - // Send command AT+SAPBR=3,1,"PWD","" where is the configured APN password. - if (! sendCheckReplyQuoted(F("AT+SAPBR=3,1,\"PWD\","), apnpassword, ok_reply, 10000)) - return false; - } - } - - // open GPRS context - if (! sendCheckReply(F("AT+SAPBR=1,1"), ok_reply, 30000)) - return false; - - // bring up wireless connection - if (! sendCheckReply(F("AT+CIICR"), ok_reply, 10000)) - return false; - - } else { - // disconnect all sockets - if (! sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 20000)) - return false; - - // close GPRS context - if (! sendCheckReply(F("AT+SAPBR=0,1"), ok_reply, 10000)) - return false; - - if (! sendCheckReply(F("AT+CGATT=0"), ok_reply, 10000)) - return false; - - } - return true; -} - -boolean Adafruit_FONA_3G::enableGPRS(boolean onoff) { - - if (onoff) { - // disconnect all sockets - //sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 5000); - - if (! sendCheckReply(F("AT+CGATT=1"), ok_reply, 10000)) - return false; - - - // set bearer profile access point name - if (apn) { - // Send command AT+CGSOCKCONT=1,"IP","" where is the configured APN name. - if (! sendCheckReplyQuoted(F("AT+CGSOCKCONT=1,\"IP\","), apn, ok_reply, 10000)) - return false; - - // set username/password - if (apnusername) { - char authstring[100] = "AT+CGAUTH=1,1,\""; - char *strp = authstring + strlen(authstring); - prog_char_strcpy(strp, (prog_char *)apnusername); - strp+=prog_char_strlen((prog_char *)apnusername); - strp[0] = '\"'; - strp++; - strp[0] = 0; - - if (apnpassword) { - strp[0] = ','; strp++; - strp[0] = '\"'; strp++; - prog_char_strcpy(strp, (prog_char *)apnpassword); - strp+=prog_char_strlen((prog_char *)apnpassword); - strp[0] = '\"'; - strp++; - strp[0] = 0; - } - - if (! sendCheckReply(authstring, ok_reply, 10000)) - return false; - } - } - - // connect in transparent - if (! sendCheckReply(F("AT+CIPMODE=1"), ok_reply, 10000)) - return false; - // open network (?) - if (! sendCheckReply(F("AT+NETOPEN=,,1"), F("Network opened"), 10000)) - return false; - - readline(); // eat 'OK' - } else { - // close GPRS context - if (! sendCheckReply(F("AT+NETCLOSE"), F("Network closed"), 10000)) - return false; - - readline(); // eat 'OK' - } - - return true; -} - -uint8_t Adafruit_FONA::GPRSstate(void) { - uint16_t state; - - if (! sendParseReply(F("AT+CGATT?"), F("+CGATT: "), &state) ) - return -1; - - return state; -} - -void Adafruit_FONA::setGPRSNetworkSettings(FONAFlashStringPtr apn, - FONAFlashStringPtr username, FONAFlashStringPtr password) { - this->apn = apn; - this->apnusername = username; - this->apnpassword = password; -} - -boolean Adafruit_FONA::getGSMLoc(uint16_t *errorcode, char *buff, uint16_t maxlen) { - - getReply(F("AT+CIPGSMLOC=1,1"), (uint16_t)10000); - - if (! parseReply(F("+CIPGSMLOC: "), errorcode)) - return false; - - char *p = replybuffer+14; - uint16_t lentocopy = min(maxlen-1, strlen(p)); - strncpy(buff, p, lentocopy+1); - - readline(); // eat OK - - return true; -} - -boolean Adafruit_FONA::getGSMLoc(float *lat, float *lon) { - - uint16_t returncode; - char gpsbuffer[120]; - - // make sure we could get a response - if (! getGSMLoc(&returncode, gpsbuffer, 120)) - return false; - - // make sure we have a valid return code - if (returncode != 0) - return false; - - // +CIPGSMLOC: 0,-74.007729,40.730160,2015/10/15,19:24:55 - // tokenize the gps buffer to locate the lat & long - char *longp = strtok(gpsbuffer, ","); - if (! longp) return false; - - char *latp = strtok(NULL, ","); - if (! latp) return false; - - *lat = atof(latp); - *lon = atof(longp); - - return true; - -} -/********* TCP FUNCTIONS ************************************/ - - -boolean Adafruit_FONA::TCPconnect(char *server, uint16_t port) { - flushInput(); - - // close all old connections - if (! sendCheckReply(F("AT+CIPSHUT"), F("SHUT OK"), 20000) ) return false; - - // single connection at a time - if (! sendCheckReply(F("AT+CIPMUX=0"), ok_reply) ) return false; - - // manually read data - if (! sendCheckReply(F("AT+CIPRXGET=1"), ok_reply) ) return false; - - - DEBUG_PRINT(F("AT+CIPSTART=\"TCP\",\"")); - DEBUG_PRINT(server); - DEBUG_PRINT(F("\",\"")); - DEBUG_PRINT(port); - DEBUG_PRINTLN(F("\"")); - - - mySerial->print(F("AT+CIPSTART=\"TCP\",\"")); - mySerial->print(server); - mySerial->print(F("\",\"")); - mySerial->print(port); - mySerial->println(F("\"")); - - if (! expectReply(ok_reply)) return false; - if (! expectReply(F("CONNECT OK"))) return false; - - // looks like it was a success (?) - return true; -} - -boolean Adafruit_FONA::TCPclose(void) { - return sendCheckReply(F("AT+CIPCLOSE"), ok_reply); -} - -boolean Adafruit_FONA::TCPconnected(void) { - if (! sendCheckReply(F("AT+CIPSTATUS"), ok_reply, 100) ) return false; - readline(100); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return (strcmp(replybuffer, "STATE: CONNECT OK") == 0); -} - -boolean Adafruit_FONA::TCPsend(char *packet, uint8_t len) { - - DEBUG_PRINT(F("AT+CIPSEND=")); - DEBUG_PRINTLN(len); -#ifdef ADAFRUIT_FONA_DEBUG - for (uint16_t i=0; iprint(F("AT+CIPSEND=")); - mySerial->println(len); - readline(); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - if (replybuffer[0] != '>') return false; - - mySerial->write(packet, len); - readline(3000); // wait up to 3 seconds to send the data - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - - return (strcmp(replybuffer, "SEND OK") == 0); -} - -uint16_t Adafruit_FONA::TCPavailable(void) { - uint16_t avail; - - if (! sendParseReply(F("AT+CIPRXGET=4"), F("+CIPRXGET: 4,"), &avail, ',', 0) ) return false; - - - DEBUG_PRINT (avail); DEBUG_PRINTLN(F(" bytes available")); - - - return avail; -} - - -uint16_t Adafruit_FONA::TCPread(uint8_t *buff, uint8_t len) { - uint16_t avail; - - mySerial->print(F("AT+CIPRXGET=2,")); - mySerial->println(len); - readline(); - if (! parseReply(F("+CIPRXGET: 2,"), &avail, ',', 0)) return false; - - readRaw(avail); - -#ifdef ADAFRUIT_FONA_DEBUG - DEBUG_PRINT (avail); DEBUG_PRINTLN(F(" bytes read")); - for (uint8_t i=0;i ")); - DEBUG_PRINT(F("AT+HTTPPARA=\"")); - DEBUG_PRINT(parameter); - DEBUG_PRINTLN('"'); - - - mySerial->print(F("AT+HTTPPARA=\"")); - mySerial->print(parameter); - if (quoted) - mySerial->print(F("\",\"")); - else - mySerial->print(F("\",")); -} - -boolean Adafruit_FONA::HTTP_para_end(boolean quoted) { - if (quoted) - mySerial->println('"'); - else - mySerial->println(); - - return expectReply(ok_reply); -} - -boolean Adafruit_FONA::HTTP_para(FONAFlashStringPtr parameter, - const char *value) { - HTTP_para_start(parameter, true); - mySerial->print(value); - return HTTP_para_end(true); -} - -boolean Adafruit_FONA::HTTP_para(FONAFlashStringPtr parameter, - FONAFlashStringPtr value) { - HTTP_para_start(parameter, true); - mySerial->print(value); - return HTTP_para_end(true); -} - -boolean Adafruit_FONA::HTTP_para(FONAFlashStringPtr parameter, - int32_t value) { - HTTP_para_start(parameter, false); - mySerial->print(value); - return HTTP_para_end(false); -} - -boolean Adafruit_FONA::HTTP_data(uint32_t size, uint32_t maxTime) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); - DEBUG_PRINT(F("AT+HTTPDATA=")); - DEBUG_PRINT(size); - DEBUG_PRINT(','); - DEBUG_PRINTLN(maxTime); - - - mySerial->print(F("AT+HTTPDATA=")); - mySerial->print(size); - mySerial->print(","); - mySerial->println(maxTime); - - return expectReply(F("DOWNLOAD")); -} - -boolean Adafruit_FONA::HTTP_action(uint8_t method, uint16_t *status, - uint16_t *datalen, int32_t timeout) { - // Send request. - if (! sendCheckReply(F("AT+HTTPACTION="), method, ok_reply)) - return false; - - // Parse response status and size. - readline(timeout); - if (! parseReply(F("+HTTPACTION:"), status, ',', 1)) - return false; - if (! parseReply(F("+HTTPACTION:"), datalen, ',', 2)) - return false; - - return true; -} - -boolean Adafruit_FONA::HTTP_readall(uint16_t *datalen) { - getReply(F("AT+HTTPREAD")); - if (! parseReply(F("+HTTPREAD:"), datalen, ',', 0)) - return false; - - return true; -} - -boolean Adafruit_FONA::HTTP_ssl(boolean onoff) { - return sendCheckReply(F("AT+HTTPSSL="), onoff ? 1 : 0, ok_reply); -} - -/********* HTTP HIGH LEVEL FUNCTIONS ***************************/ - -boolean Adafruit_FONA::HTTP_GET_start(char *url, - uint16_t *status, uint16_t *datalen){ - if (! HTTP_setup(url)) - return false; - - // HTTP GET - if (! HTTP_action(FONA_HTTP_GET, status, datalen, 30000)) - return false; - - DEBUG_PRINT(F("Status: ")); DEBUG_PRINTLN(*status); - DEBUG_PRINT(F("Len: ")); DEBUG_PRINTLN(*datalen); - - // HTTP response data - if (! HTTP_readall(datalen)) - return false; - - return true; -} - -/* -boolean Adafruit_FONA_3G::HTTP_GET_start(char *ipaddr, char *path, uint16_t port - uint16_t *status, uint16_t *datalen){ - char send[100] = "AT+CHTTPACT=\""; - char *sendp = send + strlen(send); - memset(sendp, 0, 100 - strlen(send)); - - strcpy(sendp, ipaddr); - sendp+=strlen(ipaddr); - sendp[0] = '\"'; - sendp++; - sendp[0] = ','; - itoa(sendp, port); - getReply(send, 500); - - return; - - if (! HTTP_setup(url)) - - return false; - - // HTTP GET - if (! HTTP_action(FONA_HTTP_GET, status, datalen)) - return false; - - DEBUG_PRINT("Status: "); DEBUG_PRINTLN(*status); - DEBUG_PRINT("Len: "); DEBUG_PRINTLN(*datalen); - - // HTTP response data - if (! HTTP_readall(datalen)) - return false; - - return true; -} -*/ - -void Adafruit_FONA::HTTP_GET_end(void) { - HTTP_term(); -} - -boolean Adafruit_FONA::HTTP_POST_start(char *url, - FONAFlashStringPtr contenttype, - const uint8_t *postdata, uint16_t postdatalen, - uint16_t *status, uint16_t *datalen){ - if (! HTTP_setup(url)) - return false; - - if (! HTTP_para(F("CONTENT"), contenttype)) { - return false; - } - - // HTTP POST data - if (! HTTP_data(postdatalen, 10000)) - return false; - mySerial->write(postdata, postdatalen); - if (! expectReply(ok_reply)) - return false; - - // HTTP POST - if (! HTTP_action(FONA_HTTP_POST, status, datalen)) - return false; - - DEBUG_PRINT(F("Status: ")); DEBUG_PRINTLN(*status); - DEBUG_PRINT(F("Len: ")); DEBUG_PRINTLN(*datalen); - - // HTTP response data - if (! HTTP_readall(datalen)) - return false; - - return true; -} - -void Adafruit_FONA::HTTP_POST_end(void) { - HTTP_term(); -} - -void Adafruit_FONA::setUserAgent(FONAFlashStringPtr useragent) { - this->useragent = useragent; -} - -void Adafruit_FONA::setHTTPSRedirect(boolean onoff) { - httpsredirect = onoff; -} - -/********* HTTP HELPERS ****************************************/ - -boolean Adafruit_FONA::HTTP_setup(char *url) { - // Handle any pending - HTTP_term(); - - // Initialize and set parameters - if (! HTTP_init()) - return false; - if (! HTTP_para(F("CID"), 1)) - return false; - if (! HTTP_para(F("UA"), useragent)) - return false; - if (! HTTP_para(F("URL"), url)) - return false; - - // HTTPS redirect - if (httpsredirect) { - if (! HTTP_para(F("REDIR"),1)) - return false; - - if (! HTTP_ssl(true)) - return false; - } - - return true; -} - -/********* HELPERS *********************************************/ - -boolean Adafruit_FONA::expectReply(FONAFlashStringPtr reply, - uint16_t timeout) { - readline(timeout); - - DEBUG_PRINT(F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return (prog_char_strcmp(replybuffer, (prog_char*)reply) == 0); -} - -/********* LOW LEVEL *******************************************/ - -inline int Adafruit_FONA::available(void) { - return mySerial->available(); -} - -inline size_t Adafruit_FONA::write(uint8_t x) { - return mySerial->write(x); -} - -inline int Adafruit_FONA::read(void) { - return mySerial->read(); -} - -inline int Adafruit_FONA::peek(void) { - return mySerial->peek(); -} - -inline void Adafruit_FONA::flush() { - mySerial->flush(); -} - -void Adafruit_FONA::flushInput() { - // Read all available serial input to flush pending data. - uint16_t timeoutloop = 0; - while (timeoutloop++ < 40) { - while(available()) { - read(); - timeoutloop = 0; // If char was received reset the timer - } - delay(1); - } -} - -uint16_t Adafruit_FONA::readRaw(uint16_t b) { - uint16_t idx = 0; - - while (b && (idx < sizeof(replybuffer)-1)) { - if (mySerial->available()) { - replybuffer[idx] = mySerial->read(); - idx++; - b--; - } - } - replybuffer[idx] = 0; - - return idx; -} - -uint8_t Adafruit_FONA::readline(uint16_t timeout, boolean multiline) { - uint16_t replyidx = 0; - - while (timeout--) { - if (replyidx >= 254) { - //DEBUG_PRINTLN(F("SPACE")); - break; - } - - while(mySerial->available()) { - char c = mySerial->read(); - if (c == '\r') continue; - if (c == 0xA) { - if (replyidx == 0) // the first 0x0A is ignored - continue; - - if (!multiline) { - timeout = 0; // the second 0x0A is the end of the line - break; - } - } - replybuffer[replyidx] = c; - //DEBUG_PRINT(c, HEX); DEBUG_PRINT("#"); DEBUG_PRINTLN(c); - replyidx++; - } - - if (timeout == 0) { - //DEBUG_PRINTLN(F("TIMEOUT")); - break; - } - delay(1); - } - replybuffer[replyidx] = 0; // null term - return replyidx; -} - -uint8_t Adafruit_FONA::getReply(char *send, uint16_t timeout) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN(send); - - - mySerial->println(send); - - uint8_t l = readline(timeout); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return l; -} - -uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr send, uint16_t timeout) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINTLN(send); - - - mySerial->println(send); - - uint8_t l = readline(timeout); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return l; -} - -// Send prefix, suffix, and newline. Return response (and also set replybuffer with response). -uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr prefix, char *suffix, uint16_t timeout) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); DEBUG_PRINTLN(suffix); - - - mySerial->print(prefix); - mySerial->println(suffix); - - uint8_t l = readline(timeout); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return l; -} - -// Send prefix, suffix, and newline. Return response (and also set replybuffer with response). -uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr prefix, int32_t suffix, uint16_t timeout) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); DEBUG_PRINTLN(suffix, DEC); - - - mySerial->print(prefix); - mySerial->println(suffix, DEC); - - uint8_t l = readline(timeout); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return l; -} - -// Send prefix, suffix, suffix2, and newline. Return response (and also set replybuffer with response). -uint8_t Adafruit_FONA::getReply(FONAFlashStringPtr prefix, int32_t suffix1, int32_t suffix2, uint16_t timeout) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); - DEBUG_PRINT(suffix1, DEC); DEBUG_PRINT(','); DEBUG_PRINTLN(suffix2, DEC); - - - mySerial->print(prefix); - mySerial->print(suffix1); - mySerial->print(','); - mySerial->println(suffix2, DEC); - - uint8_t l = readline(timeout); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return l; -} - -// Send prefix, ", suffix, ", and newline. Return response (and also set replybuffer with response). -uint8_t Adafruit_FONA::getReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, uint16_t timeout) { - flushInput(); - - - DEBUG_PRINT(F("\t---> ")); DEBUG_PRINT(prefix); - DEBUG_PRINT('"'); DEBUG_PRINT(suffix); DEBUG_PRINTLN('"'); - - - mySerial->print(prefix); - mySerial->print('"'); - mySerial->print(suffix); - mySerial->println('"'); - - uint8_t l = readline(timeout); - - DEBUG_PRINT (F("\t<--- ")); DEBUG_PRINTLN(replybuffer); - - return l; -} - -boolean Adafruit_FONA::sendCheckReply(char *send, char *reply, uint16_t timeout) { - if (! getReply(send, timeout) ) - return false; -/* - for (uint8_t i=0; i http://www.adafruit.com/products/1946 - ----> http://www.adafruit.com/products/1963 - - These displays use TTL Serial to communicate, 2 pins are required to - interface - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - BSD license, all text above must be included in any redistribution - ****************************************************/ -#ifndef ADAFRUIT_FONA_H -#define ADAFRUIT_FONA_H - -#include "includes/FONAConfig.h" -#include "includes/FONAExtIncludes.h" -#include "includes/platform/FONAPlatform.h" - - - -#define FONA800L 1 -#define FONA800H 6 - -#define FONA808_V1 2 -#define FONA808_V2 3 - -#define FONA3G_A 4 -#define FONA3G_E 5 - -// Uncomment to changed the preferred SMS storage -//#define FONA_PREF_SMS_STORAGE "SM" - -#define FONA_HEADSETAUDIO 0 -#define FONA_EXTAUDIO 1 - -#define FONA_STTONE_DIALTONE 1 -#define FONA_STTONE_BUSY 2 -#define FONA_STTONE_CONGESTION 3 -#define FONA_STTONE_PATHACK 4 -#define FONA_STTONE_DROPPED 5 -#define FONA_STTONE_ERROR 6 -#define FONA_STTONE_CALLWAIT 7 -#define FONA_STTONE_RINGING 8 -#define FONA_STTONE_BEEP 16 -#define FONA_STTONE_POSTONE 17 -#define FONA_STTONE_ERRTONE 18 -#define FONA_STTONE_INDIANDIALTONE 19 -#define FONA_STTONE_USADIALTONE 20 - -#define FONA_DEFAULT_TIMEOUT_MS 500 - -#define FONA_HTTP_GET 0 -#define FONA_HTTP_POST 1 -#define FONA_HTTP_HEAD 2 - -#define FONA_CALL_READY 0 -#define FONA_CALL_FAILED 1 -#define FONA_CALL_UNKNOWN 2 -#define FONA_CALL_RINGING 3 -#define FONA_CALL_INPROGRESS 4 - -class Adafruit_FONA : public FONAStreamType { - public: - Adafruit_FONA(int8_t r); - boolean begin(FONAStreamType &port); - uint8_t type(); - - // Stream - int available(void); - size_t write(uint8_t x); - int read(void); - int peek(void); - void flush(); - - // FONA 3G requirements - boolean setBaudrate(uint16_t baud); - - // RTC - boolean enableRTC(uint8_t i); - boolean readRTC(uint8_t *year, uint8_t *month, uint8_t *date, uint8_t *hr, uint8_t *min, uint8_t *sec); - - // Battery and ADC - boolean getADCVoltage(uint16_t *v); - boolean getBattPercent(uint16_t *p); - boolean getBattVoltage(uint16_t *v); - - // SIM query - uint8_t unlockSIM(char *pin); - uint8_t getSIMCCID(char *ccid); - uint8_t getNetworkStatus(void); - uint8_t getRSSI(void); - - // IMEI - uint8_t getIMEI(char *imei); - - // set Audio output - boolean setAudio(uint8_t a); - boolean setVolume(uint8_t i); - uint8_t getVolume(void); - boolean playToolkitTone(uint8_t t, uint16_t len); - boolean setMicVolume(uint8_t a, uint8_t level); - boolean playDTMF(char tone); - - // FM radio functions. - boolean tuneFMradio(uint16_t station); - boolean FMradio(boolean onoff, uint8_t a = FONA_HEADSETAUDIO); - boolean setFMVolume(uint8_t i); - int8_t getFMVolume(); - int8_t getFMSignalLevel(uint16_t station); - - // SMS handling - boolean setSMSInterrupt(uint8_t i); - uint8_t getSMSInterrupt(void); - int8_t getNumSMS(void); - boolean readSMS(uint8_t i, char *smsbuff, uint16_t max, uint16_t *readsize); - boolean sendSMS(char *smsaddr, char *smsmsg); - boolean deleteSMS(uint8_t i); - boolean getSMSSender(uint8_t i, char *sender, int senderlen); - boolean sendUSSD(char *ussdmsg, char *ussdbuff, uint16_t maxlen, uint16_t *readlen); - - // Time - boolean enableNetworkTimeSync(boolean onoff); - boolean enableNTPTimeSync(boolean onoff, FONAFlashStringPtr ntpserver=0); - boolean getTime(char *buff, uint16_t maxlen); - - // GPRS handling - boolean enableGPRS(boolean onoff); - uint8_t GPRSstate(void); - boolean getGSMLoc(uint16_t *replycode, char *buff, uint16_t maxlen); - boolean getGSMLoc(float *lat, float *lon); - void setGPRSNetworkSettings(FONAFlashStringPtr apn, FONAFlashStringPtr username=0, FONAFlashStringPtr password=0); - - // GPS handling - boolean enableGPS(boolean onoff); - int8_t GPSstatus(void); - uint8_t getGPS(uint8_t arg, char *buffer, uint8_t maxbuff); - boolean getGPS(float *lat, float *lon, float *speed_kph=0, float *heading=0, float *altitude=0); - boolean enableGPSNMEA(uint8_t nmea); - - // TCP raw connections - boolean TCPconnect(char *server, uint16_t port); - boolean TCPclose(void); - boolean TCPconnected(void); - boolean TCPsend(char *packet, uint8_t len); - uint16_t TCPavailable(void); - uint16_t TCPread(uint8_t *buff, uint8_t len); - - // HTTP low level interface (maps directly to SIM800 commands). - boolean HTTP_init(); - boolean HTTP_term(); - void HTTP_para_start(FONAFlashStringPtr parameter, boolean quoted = true); - boolean HTTP_para_end(boolean quoted = true); - boolean HTTP_para(FONAFlashStringPtr parameter, const char *value); - boolean HTTP_para(FONAFlashStringPtr parameter, FONAFlashStringPtr value); - boolean HTTP_para(FONAFlashStringPtr parameter, int32_t value); - boolean HTTP_data(uint32_t size, uint32_t maxTime=10000); - boolean HTTP_action(uint8_t method, uint16_t *status, uint16_t *datalen, int32_t timeout = 10000); - boolean HTTP_readall(uint16_t *datalen); - boolean HTTP_ssl(boolean onoff); - - // HTTP high level interface (easier to use, less flexible). - boolean HTTP_GET_start(char *url, uint16_t *status, uint16_t *datalen); - void HTTP_GET_end(void); - boolean HTTP_POST_start(char *url, FONAFlashStringPtr contenttype, const uint8_t *postdata, uint16_t postdatalen, uint16_t *status, uint16_t *datalen); - void HTTP_POST_end(void); - void setUserAgent(FONAFlashStringPtr useragent); - - // HTTPS - void setHTTPSRedirect(boolean onoff); - - // PWM (buzzer) - boolean setPWM(uint16_t period, uint8_t duty = 50); - - // Phone calls - boolean callPhone(char *phonenum); - uint8_t getCallStatus(void); - boolean hangUp(void); - boolean pickUp(void); - boolean callerIdNotification(boolean enable, uint8_t interrupt = 0); - boolean incomingCallNumber(char* phonenum); - - // Helper functions to verify responses. - boolean expectReply(FONAFlashStringPtr reply, uint16_t timeout = 10000); - boolean sendCheckReply(char *send, char *reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - boolean sendCheckReply(FONAFlashStringPtr send, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - boolean sendCheckReply(char* send, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - - - protected: - int8_t _rstpin; - uint8_t _type; - - char replybuffer[255]; - FONAFlashStringPtr apn; - FONAFlashStringPtr apnusername; - FONAFlashStringPtr apnpassword; - boolean httpsredirect; - FONAFlashStringPtr useragent; - FONAFlashStringPtr ok_reply; - - // HTTP helpers - boolean HTTP_setup(char *url); - - void flushInput(); - uint16_t readRaw(uint16_t b); - uint8_t readline(uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS, boolean multiline = false); - uint8_t getReply(char *send, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - uint8_t getReply(FONAFlashStringPtr send, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - uint8_t getReply(FONAFlashStringPtr prefix, char *suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - uint8_t getReply(FONAFlashStringPtr prefix, int32_t suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - uint8_t getReply(FONAFlashStringPtr prefix, int32_t suffix1, int32_t suffix2, uint16_t timeout); // Don't set default value or else function call is ambiguous. - uint8_t getReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - - boolean sendCheckReply(FONAFlashStringPtr prefix, char *suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - boolean sendCheckReply(FONAFlashStringPtr prefix, int32_t suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - boolean sendCheckReply(FONAFlashStringPtr prefix, int32_t suffix, int32_t suffix2, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - boolean sendCheckReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS); - - - boolean parseReply(FONAFlashStringPtr toreply, - uint16_t *v, char divider = ',', uint8_t index=0); - boolean parseReply(FONAFlashStringPtr toreply, - char *v, char divider = ',', uint8_t index=0); - boolean parseReplyQuoted(FONAFlashStringPtr toreply, - char *v, int maxlen, char divider, uint8_t index); - - boolean sendParseReply(FONAFlashStringPtr tosend, - FONAFlashStringPtr toreply, - uint16_t *v, char divider = ',', uint8_t index=0); - - static boolean _incomingCall; - static void onIncomingCall(); - - FONAStreamType *mySerial; -}; - -class Adafruit_FONA_3G : public Adafruit_FONA { - - public: - Adafruit_FONA_3G (int8_t r) : Adafruit_FONA(r) { _type = FONA3G_A; } - - boolean getBattVoltage(uint16_t *v); - boolean playToolkitTone(uint8_t t, uint16_t len); - boolean hangUp(void); - boolean pickUp(void); - boolean enableGPRS(boolean onoff); - boolean enableGPS(boolean onoff); - - protected: - boolean parseReply(FONAFlashStringPtr toreply, - float *f, char divider, uint8_t index); - - boolean sendParseReply(FONAFlashStringPtr tosend, - FONAFlashStringPtr toreply, - float *f, char divider = ',', uint8_t index=0); -}; - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/README.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/README.md deleted file mode 100644 index 73452ca..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Adafruit FONA Library [![Build Status](https://secure.travis-ci.org/adafruit/Adafruit_FONA_Library.svg?branch=master)](https://travis-ci.org/adafruit/Adafruit_FONA_Library) - -**This library requires Arduino v1.0.6 or higher** - -This is a library for the Adafruit FONA Cellular GSM Breakouts etc - -Designed specifically to work with the Adafruit FONA Breakout - * https://www.adafruit.com/products/1946 - * https://www.adafruit.com/products/1963 - * http://www.adafruit.com/products/2468 - * http://www.adafruit.com/products/2542 - -These modules use TTL Serial to communicate, 2 pins are required to interface - -Adafruit invests time and resources providing this open source code, -please support Adafruit and open-source hardware by purchasing -products from Adafruit! - -Check out the links above for our tutorials and wiring diagrams - -Written by Limor Fried/Ladyada for Adafruit Industries. -BSD license, all text above must be included in any redistribution -With updates from Samy Kamkar - -To download. click the DOWNLOADS button in the top right corner, rename the uncompressed folder Adafruit_FONA -Check that the Adafruit_FONA folder contains Adafruit_FONA.cpp and Adafruit_FONA.h - -Place the Adafruit_FONA library folder your *arduinosketchfolder*/libraries/ folder. -You may need to create the libraries subfolder if its your first library. Restart the IDE. diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/.esp8266.test.skip b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/.esp8266.test.skip deleted file mode 100644 index e69de29..0000000 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino deleted file mode 100644 index b0be4c5..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA3G_setbaud/FONA3G_setbaud.ino +++ /dev/null @@ -1,77 +0,0 @@ -/*************************************************** - This is an example for our Adafruit FONA Cellular Module - since the FONA 3G does not do auto-baud very well, this demo - fixes the baud rate to 4800 from the default 115200 - - Designed specifically to work with the Adafruit FONA 3G - ----> http://www.adafruit.com/products/2691 - ----> http://www.adafruit.com/products/2687 - - These cellular modules use TTL Serial to communicate, 2 pins are - required to interface - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - BSD license, all text above must be included in any redistribution - ****************************************************/ - -#include "Adafruit_FONA.h" - -#define FONA_RX 2 -#define FONA_TX 3 -#define FONA_RST 4 - -// this is a large buffer for replies -char replybuffer[255]; - -// We default to using software serial. If you want to use hardware serial -// (because softserial isnt supported) comment out the following three lines -// and uncomment the HardwareSerial line -#include -SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); -SoftwareSerial *fonaSerial = &fonaSS; - -// Hardware serial is also possible! -// HardwareSerial *fonaSerial = &Serial1; - -Adafruit_FONA fona = Adafruit_FONA(FONA_RST); - -uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); - -void setup() { - while (!Serial); - - Serial.begin(115200); - Serial.println(F("FONA set baudrate")); - - Serial.println(F("First trying 115200 baud")); - // start at 115200 baud - fonaSerial->begin(115200); - fona.begin(*fonaSerial); - - // send the command to reset the baud rate to 4800 - fona.setBaudrate(4800); - - // restart with 4800 baud - fonaSerial->begin(4800); - Serial.println(F("Initializing @ 4800 baud...")); - - if (! fona.begin(*fonaSerial)) { - Serial.println(F("Couldn't find FONA")); - while(1); - } - Serial.println(F("FONA is OK")); - - // Print module IMEI number. - char imei[15] = {0}; // MUST use a 16 character buffer for IMEI! - uint8_t imeiLen = fona.getIMEI(imei); - if (imeiLen > 0) { - Serial.print("Module IMEI: "); Serial.println(imei); - } - -} - -void loop() { -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/.esp8266.test.skip b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/.esp8266.test.skip deleted file mode 100644 index e69de29..0000000 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino deleted file mode 100644 index 7201641..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONA_SMS_Response/FONA_SMS_Response.ino +++ /dev/null @@ -1,131 +0,0 @@ -/*************************************************** - This is an example for our Adafruit FONA Cellular Module - - Designed specifically to work with the Adafruit FONA - ----> http://www.adafruit.com/products/1946 - ----> http://www.adafruit.com/products/1963 - ----> http://www.adafruit.com/products/2468 - ----> http://www.adafruit.com/products/2542 - - These cellular modules use TTL Serial to communicate, 2 pins are - required to interface - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - BSD license, all text above must be included in any redistribution - ****************************************************/ - -/* -THIS CODE IS STILL IN PROGRESS! - -Open up the serial console on the Arduino at 115200 baud to interact with FONA - - -This code will receive an SMS, identify the sender's phone number, and automatically send a response - -For use with FONA 800 & 808, not 3G -*/ - -#include "Adafruit_FONA.h" - -#define FONA_RX 2 -#define FONA_TX 3 -#define FONA_RST 4 - -// this is a large buffer for replies -char replybuffer[255]; - -// We default to using software serial. If you want to use hardware serial -// (because softserial isnt supported) comment out the following three lines -// and uncomment the HardwareSerial line -#include -SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); -SoftwareSerial *fonaSerial = &fonaSS; - -// Hardware serial is also possible! -// HardwareSerial *fonaSerial = &Serial1; - -Adafruit_FONA fona = Adafruit_FONA(FONA_RST); - -uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); - -void setup() { - while (!Serial); - - Serial.begin(115200); - Serial.println(F("FONA SMS caller ID test")); - Serial.println(F("Initializing....(May take 3 seconds)")); - - // make it slow so its easy to read! - fonaSerial->begin(4800); - if (! fona.begin(*fonaSerial)) { - Serial.println(F("Couldn't find FONA")); - while(1); - } - Serial.println(F("FONA is OK")); - - // Print SIM card IMEI number. - char imei[15] = {0}; // MUST use a 16 character buffer for IMEI! - uint8_t imeiLen = fona.getIMEI(imei); - if (imeiLen > 0) { - Serial.print("SIM card IMEI: "); Serial.println(imei); - } - - Serial.println("FONA Ready"); -} - - -char fonaInBuffer[64]; //for notifications from the FONA - -void loop() { - - char* bufPtr = fonaInBuffer; //handy buffer pointer - - if (fona.available()) //any data available from the FONA? - { - int slot = 0; //this will be the slot number of the SMS - int charCount = 0; - //Read the notification into fonaInBuffer - do { - *bufPtr = fona.read(); - Serial.write(*bufPtr); - delay(1); - } while ((*bufPtr++ != '\n') && (fona.available()) && (++charCount < (sizeof(fonaInBuffer)-1))); - - //Add a terminal NULL to the notification string - *bufPtr = 0; - - //Scan the notification string for an SMS received notification. - // If it's an SMS message, we'll get the slot number in 'slot' - if (1 == sscanf(fonaInBuffer, "+CMTI: \"SM\",%d", &slot)) { - Serial.print("slot: "); Serial.println(slot); - - char callerIDbuffer[32]; //we'll store the SMS sender number in here - - // Retrieve SMS sender address/phone number. - if (! fona.getSMSSender(slot, callerIDbuffer, 31)) { - Serial.println("Didn't find SMS message in slot!"); - } - Serial.print(F("FROM: ")); Serial.println(callerIDbuffer); - - //Send back an automatic response - Serial.println("Sending reponse..."); - if (!fona.sendSMS(callerIDbuffer, "Hey, I got your text!")) { - Serial.println(F("Failed")); - } else { - Serial.println(F("Sent!")); - } - - // delete the original msg after it is processed - // otherwise, we will fill up all the slots - // and then we won't be able to receive SMS anymore - if (fona.deleteSMS(slot)) { - Serial.println(F("OK!")); - } else { - Serial.println(F("Couldn't delete")); - } - } - } -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/.esp8266.test.skip b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/.esp8266.test.skip deleted file mode 100644 index e69de29..0000000 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino deleted file mode 100644 index 1b27732..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/FONAtest/FONAtest.ino +++ /dev/null @@ -1,886 +0,0 @@ -/*************************************************** - This is an example for our Adafruit FONA Cellular Module - - Designed specifically to work with the Adafruit FONA - ----> http://www.adafruit.com/products/1946 - ----> http://www.adafruit.com/products/1963 - ----> http://www.adafruit.com/products/2468 - ----> http://www.adafruit.com/products/2542 - - These cellular modules use TTL Serial to communicate, 2 pins are - required to interface - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - BSD license, all text above must be included in any redistribution - ****************************************************/ - -/* -THIS CODE IS STILL IN PROGRESS! - -Open up the serial console on the Arduino at 115200 baud to interact with FONA - -Note that if you need to set a GPRS APN, username, and password scroll down to -the commented section below at the end of the setup() function. -*/ -#include "Adafruit_FONA.h" - -#define FONA_RX 2 -#define FONA_TX 3 -#define FONA_RST 4 - -// this is a large buffer for replies -char replybuffer[255]; - -// We default to using software serial. If you want to use hardware serial -// (because softserial isnt supported) comment out the following three lines -// and uncomment the HardwareSerial line -#include -SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); -SoftwareSerial *fonaSerial = &fonaSS; - -// Hardware serial is also possible! -// HardwareSerial *fonaSerial = &Serial1; - -// Use this for FONA 800 and 808s -Adafruit_FONA fona = Adafruit_FONA(FONA_RST); -// Use this one for FONA 3G -//Adafruit_FONA_3G fona = Adafruit_FONA_3G(FONA_RST); - -uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); - -uint8_t type; - -void setup() { - while (!Serial); - - Serial.begin(115200); - Serial.println(F("FONA basic test")); - Serial.println(F("Initializing....(May take 3 seconds)")); - - fonaSerial->begin(4800); - if (! fona.begin(*fonaSerial)) { - Serial.println(F("Couldn't find FONA")); - while (1); - } - type = fona.type(); - Serial.println(F("FONA is OK")); - Serial.print(F("Found ")); - switch (type) { - case FONA800L: - Serial.println(F("FONA 800L")); break; - case FONA800H: - Serial.println(F("FONA 800H")); break; - case FONA808_V1: - Serial.println(F("FONA 808 (v1)")); break; - case FONA808_V2: - Serial.println(F("FONA 808 (v2)")); break; - case FONA3G_A: - Serial.println(F("FONA 3G (American)")); break; - case FONA3G_E: - Serial.println(F("FONA 3G (European)")); break; - default: - Serial.println(F("???")); break; - } - - // Print module IMEI number. - char imei[15] = {0}; // MUST use a 16 character buffer for IMEI! - uint8_t imeiLen = fona.getIMEI(imei); - if (imeiLen > 0) { - Serial.print("Module IMEI: "); Serial.println(imei); - } - - // Optionally configure a GPRS APN, username, and password. - // You might need to do this to access your network's GPRS/data - // network. Contact your provider for the exact APN, username, - // and password values. Username and password are optional and - // can be removed, but APN is required. - //fona.setGPRSNetworkSettings(F("your APN"), F("your username"), F("your password")); - - // Optionally configure HTTP gets to follow redirects over SSL. - // Default is not to follow SSL redirects, however if you uncomment - // the following line then redirects over SSL will be followed. - //fona.setHTTPSRedirect(true); - - printMenu(); -} - -void printMenu(void) { - Serial.println(F("-------------------------------------")); - Serial.println(F("[?] Print this menu")); - Serial.println(F("[a] read the ADC 2.8V max (FONA800 & 808)")); - Serial.println(F("[b] read the Battery V and % charged")); - Serial.println(F("[C] read the SIM CCID")); - Serial.println(F("[U] Unlock SIM with PIN code")); - Serial.println(F("[i] read RSSI")); - Serial.println(F("[n] get Network status")); - Serial.println(F("[v] set audio Volume")); - Serial.println(F("[V] get Volume")); - Serial.println(F("[H] set Headphone audio (FONA800 & 808)")); - Serial.println(F("[e] set External audio (FONA800 & 808)")); - Serial.println(F("[T] play audio Tone")); - Serial.println(F("[P] PWM/Buzzer out (FONA800 & 808)")); - - // FM (SIM800 only!) - Serial.println(F("[f] tune FM radio (FONA800)")); - Serial.println(F("[F] turn off FM (FONA800)")); - Serial.println(F("[m] set FM volume (FONA800)")); - Serial.println(F("[M] get FM volume (FONA800)")); - Serial.println(F("[q] get FM station signal level (FONA800)")); - - // Phone - Serial.println(F("[c] make phone Call")); - Serial.println(F("[A] get call status")); - Serial.println(F("[h] Hang up phone")); - Serial.println(F("[p] Pick up phone")); - - // SMS - Serial.println(F("[N] Number of SMSs")); - Serial.println(F("[r] Read SMS #")); - Serial.println(F("[R] Read All SMS")); - Serial.println(F("[d] Delete SMS #")); - Serial.println(F("[s] Send SMS")); - Serial.println(F("[u] Send USSD")); - - // Time - Serial.println(F("[y] Enable network time sync (FONA 800 & 808)")); - Serial.println(F("[Y] Enable NTP time sync (GPRS FONA 800 & 808)")); - Serial.println(F("[t] Get network time")); - - // GPRS - Serial.println(F("[G] Enable GPRS")); - Serial.println(F("[g] Disable GPRS")); - Serial.println(F("[l] Query GSMLOC (GPRS)")); - Serial.println(F("[w] Read webpage (GPRS)")); - Serial.println(F("[W] Post to website (GPRS)")); - - // GPS - if ((type == FONA3G_A) || (type == FONA3G_E) || (type == FONA808_V1) || (type == FONA808_V2)) { - Serial.println(F("[O] Turn GPS on (FONA 808 & 3G)")); - Serial.println(F("[o] Turn GPS off (FONA 808 & 3G)")); - Serial.println(F("[L] Query GPS location (FONA 808 & 3G)")); - if (type == FONA808_V1) { - Serial.println(F("[x] GPS fix status (FONA808 v1 only)")); - } - Serial.println(F("[E] Raw NMEA out (FONA808)")); - } - - Serial.println(F("[S] create Serial passthru tunnel")); - Serial.println(F("-------------------------------------")); - Serial.println(F("")); - -} -void loop() { - Serial.print(F("FONA> ")); - while (! Serial.available() ) { - if (fona.available()) { - Serial.write(fona.read()); - } - } - - char command = Serial.read(); - Serial.println(command); - - - switch (command) { - case '?': { - printMenu(); - break; - } - - case 'a': { - // read the ADC - uint16_t adc; - if (! fona.getADCVoltage(&adc)) { - Serial.println(F("Failed to read ADC")); - } else { - Serial.print(F("ADC = ")); Serial.print(adc); Serial.println(F(" mV")); - } - break; - } - - case 'b': { - // read the battery voltage and percentage - uint16_t vbat; - if (! fona.getBattVoltage(&vbat)) { - Serial.println(F("Failed to read Batt")); - } else { - Serial.print(F("VBat = ")); Serial.print(vbat); Serial.println(F(" mV")); - } - - - if (! fona.getBattPercent(&vbat)) { - Serial.println(F("Failed to read Batt")); - } else { - Serial.print(F("VPct = ")); Serial.print(vbat); Serial.println(F("%")); - } - - break; - } - - case 'U': { - // Unlock the SIM with a PIN code - char PIN[5]; - flushSerial(); - Serial.println(F("Enter 4-digit PIN")); - readline(PIN, 3); - Serial.println(PIN); - Serial.print(F("Unlocking SIM card: ")); - if (! fona.unlockSIM(PIN)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - - case 'C': { - // read the CCID - fona.getSIMCCID(replybuffer); // make sure replybuffer is at least 21 bytes! - Serial.print(F("SIM CCID = ")); Serial.println(replybuffer); - break; - } - - case 'i': { - // read the RSSI - uint8_t n = fona.getRSSI(); - int8_t r; - - Serial.print(F("RSSI = ")); Serial.print(n); Serial.print(": "); - if (n == 0) r = -115; - if (n == 1) r = -111; - if (n == 31) r = -52; - if ((n >= 2) && (n <= 30)) { - r = map(n, 2, 30, -110, -54); - } - Serial.print(r); Serial.println(F(" dBm")); - - break; - } - - case 'n': { - // read the network/cellular status - uint8_t n = fona.getNetworkStatus(); - Serial.print(F("Network status ")); - Serial.print(n); - Serial.print(F(": ")); - if (n == 0) Serial.println(F("Not registered")); - if (n == 1) Serial.println(F("Registered (home)")); - if (n == 2) Serial.println(F("Not registered (searching)")); - if (n == 3) Serial.println(F("Denied")); - if (n == 4) Serial.println(F("Unknown")); - if (n == 5) Serial.println(F("Registered roaming")); - break; - } - - /*** Audio ***/ - case 'v': { - // set volume - flushSerial(); - if ( (type == FONA3G_A) || (type == FONA3G_E) ) { - Serial.print(F("Set Vol [0-8] ")); - } else { - Serial.print(F("Set Vol % [0-100] ")); - } - uint8_t vol = readnumber(); - Serial.println(); - if (! fona.setVolume(vol)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - - case 'V': { - uint8_t v = fona.getVolume(); - Serial.print(v); - if ( (type == FONA3G_A) || (type == FONA3G_E) ) { - Serial.println(" / 8"); - } else { - Serial.println("%"); - } - break; - } - - case 'H': { - // Set Headphone output - if (! fona.setAudio(FONA_HEADSETAUDIO)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - fona.setMicVolume(FONA_HEADSETAUDIO, 15); - break; - } - case 'e': { - // Set External output - if (! fona.setAudio(FONA_EXTAUDIO)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - - fona.setMicVolume(FONA_EXTAUDIO, 10); - break; - } - - case 'T': { - // play tone - flushSerial(); - Serial.print(F("Play tone #")); - uint8_t kittone = readnumber(); - Serial.println(); - // play for 1 second (1000 ms) - if (! fona.playToolkitTone(kittone, 1000)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - - /*** FM Radio ***/ - - case 'f': { - // get freq - flushSerial(); - Serial.print(F("FM Freq (eg 1011 == 101.1 MHz): ")); - uint16_t station = readnumber(); - Serial.println(); - // FM radio ON using headset - if (fona.FMradio(true, FONA_HEADSETAUDIO)) { - Serial.println(F("Opened")); - } - if (! fona.tuneFMradio(station)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("Tuned")); - } - break; - } - case 'F': { - // FM radio off - if (! fona.FMradio(false)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - case 'm': { - // Set FM volume. - flushSerial(); - Serial.print(F("Set FM Vol [0-6]:")); - uint8_t vol = readnumber(); - Serial.println(); - if (!fona.setFMVolume(vol)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - case 'M': { - // Get FM volume. - uint8_t fmvol = fona.getFMVolume(); - if (fmvol < 0) { - Serial.println(F("Failed")); - } else { - Serial.print(F("FM volume: ")); - Serial.println(fmvol, DEC); - } - break; - } - case 'q': { - // Get FM station signal level (in decibels). - flushSerial(); - Serial.print(F("FM Freq (eg 1011 == 101.1 MHz): ")); - uint16_t station = readnumber(); - Serial.println(); - int8_t level = fona.getFMSignalLevel(station); - if (level < 0) { - Serial.println(F("Failed! Make sure FM radio is on (tuned to station).")); - } else { - Serial.print(F("Signal level (dB): ")); - Serial.println(level, DEC); - } - break; - } - - /*** PWM ***/ - - case 'P': { - // PWM Buzzer output @ 2KHz max - flushSerial(); - Serial.print(F("PWM Freq, 0 = Off, (1-2000): ")); - uint16_t freq = readnumber(); - Serial.println(); - if (! fona.setPWM(freq)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - - /*** Call ***/ - case 'c': { - // call a phone! - char number[30]; - flushSerial(); - Serial.print(F("Call #")); - readline(number, 30); - Serial.println(); - Serial.print(F("Calling ")); Serial.println(number); - if (!fona.callPhone(number)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("Sent!")); - } - - break; - } - case 'A': { - // get call status - int8_t callstat = fona.getCallStatus(); - switch (callstat) { - case 0: Serial.println(F("Ready")); break; - case 1: Serial.println(F("Could not get status")); break; - case 3: Serial.println(F("Ringing (incoming)")); break; - case 4: Serial.println(F("Ringing/in progress (outgoing)")); break; - default: Serial.println(F("Unknown")); break; - } - break; - } - - case 'h': { - // hang up! - if (! fona.hangUp()) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - - case 'p': { - // pick up! - if (! fona.pickUp()) { - Serial.println(F("Failed")); - } else { - Serial.println(F("OK!")); - } - break; - } - - /*** SMS ***/ - - case 'N': { - // read the number of SMS's! - int8_t smsnum = fona.getNumSMS(); - if (smsnum < 0) { - Serial.println(F("Could not read # SMS")); - } else { - Serial.print(smsnum); - Serial.println(F(" SMS's on SIM card!")); - } - break; - } - case 'r': { - // read an SMS - flushSerial(); - Serial.print(F("Read #")); - uint8_t smsn = readnumber(); - Serial.print(F("\n\rReading SMS #")); Serial.println(smsn); - - // Retrieve SMS sender address/phone number. - if (! fona.getSMSSender(smsn, replybuffer, 250)) { - Serial.println("Failed!"); - break; - } - Serial.print(F("FROM: ")); Serial.println(replybuffer); - - // Retrieve SMS value. - uint16_t smslen; - if (! fona.readSMS(smsn, replybuffer, 250, &smslen)) { // pass in buffer and max len! - Serial.println("Failed!"); - break; - } - Serial.print(F("***** SMS #")); Serial.print(smsn); - Serial.print(" ("); Serial.print(smslen); Serial.println(F(") bytes *****")); - Serial.println(replybuffer); - Serial.println(F("*****")); - - break; - } - case 'R': { - // read all SMS - int8_t smsnum = fona.getNumSMS(); - uint16_t smslen; - int8_t smsn; - - if ( (type == FONA3G_A) || (type == FONA3G_E) ) { - smsn = 0; // zero indexed - smsnum--; - } else { - smsn = 1; // 1 indexed - } - - for ( ; smsn <= smsnum; smsn++) { - Serial.print(F("\n\rReading SMS #")); Serial.println(smsn); - if (!fona.readSMS(smsn, replybuffer, 250, &smslen)) { // pass in buffer and max len! - Serial.println(F("Failed!")); - break; - } - // if the length is zero, its a special case where the index number is higher - // so increase the max we'll look at! - if (smslen == 0) { - Serial.println(F("[empty slot]")); - smsnum++; - continue; - } - - Serial.print(F("***** SMS #")); Serial.print(smsn); - Serial.print(" ("); Serial.print(smslen); Serial.println(F(") bytes *****")); - Serial.println(replybuffer); - Serial.println(F("*****")); - } - break; - } - - case 'd': { - // delete an SMS - flushSerial(); - Serial.print(F("Delete #")); - uint8_t smsn = readnumber(); - - Serial.print(F("\n\rDeleting SMS #")); Serial.println(smsn); - if (fona.deleteSMS(smsn)) { - Serial.println(F("OK!")); - } else { - Serial.println(F("Couldn't delete")); - } - break; - } - - case 's': { - // send an SMS! - char sendto[21], message[141]; - flushSerial(); - Serial.print(F("Send to #")); - readline(sendto, 20); - Serial.println(sendto); - Serial.print(F("Type out one-line message (140 char): ")); - readline(message, 140); - Serial.println(message); - if (!fona.sendSMS(sendto, message)) { - Serial.println(F("Failed")); - } else { - Serial.println(F("Sent!")); - } - - break; - } - - case 'u': { - // send a USSD! - char message[141]; - flushSerial(); - Serial.print(F("Type out one-line message (140 char): ")); - readline(message, 140); - Serial.println(message); - - uint16_t ussdlen; - if (!fona.sendUSSD(message, replybuffer, 250, &ussdlen)) { // pass in buffer and max len! - Serial.println(F("Failed")); - } else { - Serial.println(F("Sent!")); - Serial.print(F("***** USSD Reply")); - Serial.print(" ("); Serial.print(ussdlen); Serial.println(F(") bytes *****")); - Serial.println(replybuffer); - Serial.println(F("*****")); - } - } - - /*** Time ***/ - - case 'y': { - // enable network time sync - if (!fona.enableNetworkTimeSync(true)) - Serial.println(F("Failed to enable")); - break; - } - - case 'Y': { - // enable NTP time sync - if (!fona.enableNTPTimeSync(true, F("pool.ntp.org"))) - Serial.println(F("Failed to enable")); - break; - } - - case 't': { - // read the time - char buffer[23]; - - fona.getTime(buffer, 23); // make sure replybuffer is at least 23 bytes! - Serial.print(F("Time = ")); Serial.println(buffer); - break; - } - - - /*********************************** GPS (SIM808 only) */ - - case 'o': { - // turn GPS off - if (!fona.enableGPS(false)) - Serial.println(F("Failed to turn off")); - break; - } - case 'O': { - // turn GPS on - if (!fona.enableGPS(true)) - Serial.println(F("Failed to turn on")); - break; - } - case 'x': { - int8_t stat; - // check GPS fix - stat = fona.GPSstatus(); - if (stat < 0) - Serial.println(F("Failed to query")); - if (stat == 0) Serial.println(F("GPS off")); - if (stat == 1) Serial.println(F("No fix")); - if (stat == 2) Serial.println(F("2D fix")); - if (stat == 3) Serial.println(F("3D fix")); - break; - } - - case 'L': { - // check for GPS location - char gpsdata[120]; - fona.getGPS(0, gpsdata, 120); - if (type == FONA808_V1) - Serial.println(F("Reply in format: mode,longitude,latitude,altitude,utctime(yyyymmddHHMMSS),ttff,satellites,speed,course")); - else - Serial.println(F("Reply in format: mode,fixstatus,utctime(yyyymmddHHMMSS),latitude,longitude,altitude,speed,course,fixmode,reserved1,HDOP,PDOP,VDOP,reserved2,view_satellites,used_satellites,reserved3,C/N0max,HPA,VPA")); - Serial.println(gpsdata); - - break; - } - - case 'E': { - flushSerial(); - if (type == FONA808_V1) { - Serial.print(F("GPS NMEA output sentences (0 = off, 34 = RMC+GGA, 255 = all)")); - } else { - Serial.print(F("On (1) or Off (0)? ")); - } - uint8_t nmeaout = readnumber(); - - // turn on NMEA output - fona.enableGPSNMEA(nmeaout); - - break; - } - - /*********************************** GPRS */ - - case 'g': { - // turn GPRS off - if (!fona.enableGPRS(false)) - Serial.println(F("Failed to turn off")); - break; - } - case 'G': { - // turn GPRS on - if (!fona.enableGPRS(true)) - Serial.println(F("Failed to turn on")); - break; - } - case 'l': { - // check for GSMLOC (requires GPRS) - uint16_t returncode; - - if (!fona.getGSMLoc(&returncode, replybuffer, 250)) - Serial.println(F("Failed!")); - if (returncode == 0) { - Serial.println(replybuffer); - } else { - Serial.print(F("Fail code #")); Serial.println(returncode); - } - - break; - } - case 'w': { - // read website URL - uint16_t statuscode; - int16_t length; - char url[80]; - - flushSerial(); - Serial.println(F("NOTE: in beta! Use small webpages to read!")); - Serial.println(F("URL to read (e.g. www.adafruit.com/testwifi/index.html):")); - Serial.print(F("http://")); readline(url, 79); - Serial.println(url); - - Serial.println(F("****")); - if (!fona.HTTP_GET_start(url, &statuscode, (uint16_t *)&length)) { - Serial.println("Failed!"); - break; - } - while (length > 0) { - while (fona.available()) { - char c = fona.read(); - - // Serial.write is too slow, we'll write directly to Serial register! -#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) - loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data register empty. */ - UDR0 = c; -#else - Serial.write(c); -#endif - length--; - if (! length) break; - } - } - Serial.println(F("\n****")); - fona.HTTP_GET_end(); - break; - } - - case 'W': { - // Post data to website - uint16_t statuscode; - int16_t length; - char url[80]; - char data[80]; - - flushSerial(); - Serial.println(F("NOTE: in beta! Use simple websites to post!")); - Serial.println(F("URL to post (e.g. httpbin.org/post):")); - Serial.print(F("http://")); readline(url, 79); - Serial.println(url); - Serial.println(F("Data to post (e.g. \"foo\" or \"{\"simple\":\"json\"}\"):")); - readline(data, 79); - Serial.println(data); - - Serial.println(F("****")); - if (!fona.HTTP_POST_start(url, F("text/plain"), (uint8_t *) data, strlen(data), &statuscode, (uint16_t *)&length)) { - Serial.println("Failed!"); - break; - } - while (length > 0) { - while (fona.available()) { - char c = fona.read(); - -#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) - loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data register empty. */ - UDR0 = c; -#else - Serial.write(c); -#endif - - length--; - if (! length) break; - } - } - Serial.println(F("\n****")); - fona.HTTP_POST_end(); - break; - } - /*****************************************/ - - case 'S': { - Serial.println(F("Creating SERIAL TUBE")); - while (1) { - while (Serial.available()) { - delay(1); - fona.write(Serial.read()); - } - if (fona.available()) { - Serial.write(fona.read()); - } - } - break; - } - - default: { - Serial.println(F("Unknown command")); - printMenu(); - break; - } - } - // flush input - flushSerial(); - while (fona.available()) { - Serial.write(fona.read()); - } - -} - -void flushSerial() { - while (Serial.available()) - Serial.read(); -} - -char readBlocking() { - while (!Serial.available()); - return Serial.read(); -} -uint16_t readnumber() { - uint16_t x = 0; - char c; - while (! isdigit(c = readBlocking())) { - //Serial.print(c); - } - Serial.print(c); - x = c - '0'; - while (isdigit(c = readBlocking())) { - Serial.print(c); - x *= 10; - x += c - '0'; - } - return x; -} - -uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout) { - uint16_t buffidx = 0; - boolean timeoutvalid = true; - if (timeout == 0) timeoutvalid = false; - - while (true) { - if (buffidx > maxbuff) { - //Serial.println(F("SPACE")); - break; - } - - while (Serial.available()) { - char c = Serial.read(); - - //Serial.print(c, HEX); Serial.print("#"); Serial.println(c); - - if (c == '\r') continue; - if (c == 0xA) { - if (buffidx == 0) // the first 0x0A is ignored - continue; - - timeout = 0; // the second 0x0A is the end of the line - timeoutvalid = true; - break; - } - buff[buffidx] = c; - buffidx++; - } - - if (timeoutvalid && timeout == 0) { - //Serial.println(F("TIMEOUT")); - break; - } - delay(1); - } - buff[buffidx] = 0; // null term - return buffidx; -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/GPS/.esp8266.test.skip b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/GPS/.esp8266.test.skip deleted file mode 100644 index e69de29..0000000 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino deleted file mode 100644 index cce63d5..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/GPS/GPS.ino +++ /dev/null @@ -1,112 +0,0 @@ -/** - * ___ ___ _ _ _ ___ __ ___ ___ ___ ___ - * | __/ _ \| \| | /_\ ( _ )/ \( _ ) / __| _ \/ __| - * | _| (_) | .` |/ _ \ / _ \ () / _ \ | (_ | _/\__ \ - * |_| \___/|_|\_/_/ \_\ \___/\__/\___/ \___|_| |___/ - * - * This example is meant to work with the Adafruit - * FONA 808 or 3G Shield or Breakout - * - * Copyright: 2015 Adafruit - * Author: Todd Treece - * Licence: MIT - * - */ -#include "Adafruit_FONA.h" - -// standard pins for the shield, adjust as necessary -#define FONA_RX 2 -#define FONA_TX 3 -#define FONA_RST 4 - -// We default to using software serial. If you want to use hardware serial -// (because softserial isnt supported) comment out the following three lines -// and uncomment the HardwareSerial line -#include -SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); -SoftwareSerial *fonaSerial = &fonaSS; - -// Hardware serial is also possible! -// HardwareSerial *fonaSerial = &Serial1; - -Adafruit_FONA fona = Adafruit_FONA(FONA_RST); - -// Have a FONA 3G? use this object type instead -//Adafruit_FONA_3G fona = Adafruit_FONA_3G(FONA_RST); - - -void setup() { - - while (! Serial); - - Serial.begin(115200); - Serial.println(F("Adafruit FONA 808 & 3G GPS demo")); - Serial.println(F("Initializing FONA... (May take a few seconds)")); - - fonaSerial->begin(4800); - if (! fona.begin(*fonaSerial)) { - Serial.println(F("Couldn't find FONA")); - while(1); - } - Serial.println(F("FONA is OK")); - // Try to enable GPRS - - - Serial.println(F("Enabling GPS...")); - fona.enableGPS(true); -} - -void loop() { - delay(2000); - - float latitude, longitude, speed_kph, heading, speed_mph, altitude; - - // if you ask for an altitude reading, getGPS will return false if there isn't a 3D fix - boolean gps_success = fona.getGPS(&latitude, &longitude, &speed_kph, &heading, &altitude); - - if (gps_success) { - - Serial.print("GPS lat:"); - Serial.println(latitude, 6); - Serial.print("GPS long:"); - Serial.println(longitude, 6); - Serial.print("GPS speed KPH:"); - Serial.println(speed_kph); - Serial.print("GPS speed MPH:"); - speed_mph = speed_kph * 0.621371192; - Serial.println(speed_mph); - Serial.print("GPS heading:"); - Serial.println(heading); - Serial.print("GPS altitude:"); - Serial.println(altitude); - - } else { - Serial.println("Waiting for FONA GPS 3D fix..."); - } - - // Fona 3G doesnt have GPRSlocation :/ - if ((fona.type() == FONA3G_A) || (fona.type() == FONA3G_E)) - return; - // Check for network, then GPRS - Serial.println(F("Checking for Cell network...")); - if (fona.getNetworkStatus() == 1) { - // network & GPRS? Great! Print out the GSM location to compare - boolean gsmloc_success = fona.getGSMLoc(&latitude, &longitude); - - if (gsmloc_success) { - Serial.print("GSMLoc lat:"); - Serial.println(latitude, 6); - Serial.print("GSMLoc long:"); - Serial.println(longitude, 6); - } else { - Serial.println("GSM location failed..."); - Serial.println(F("Disabling GPRS")); - fona.enableGPRS(false); - Serial.println(F("Enabling GPRS")); - if (!fona.enableGPRS(true)) { - Serial.println(F("Failed to turn GPRS on")); - } - } - } -} - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/.esp8266.test.skip b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/.esp8266.test.skip deleted file mode 100644 index e69de29..0000000 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino deleted file mode 100644 index 8dba308..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/examples/IncomingCall/IncomingCall.ino +++ /dev/null @@ -1,62 +0,0 @@ -// FONA Incoming Call Number Example -// Listens for a call and displays the phone number of the caller (if available). -// Use this example to add phone call detection to your own FONA sketch. -#include "Adafruit_FONA.h" - -// Pins which are connected to the FONA. -// Note that this is different from FONAtest! -#define FONA_RX 3 -#define FONA_TX 4 -#define FONA_RST 5 - -// Note you need to map interrupt number to pin number -// for your board. On an Uno & Mega interrupt 0 is -// digital pin 2, and on a Leonardo interrupt 0 is -// digital pin 3. See this page for a complete table: -// http://arduino.cc/en/Reference/attachInterrupt -// Make sure this interrupt pin is connected to FONA RI! -#define FONA_RI_INTERRUPT 0 - -// We default to using software serial. If you want to use hardware serial -// (because softserial isnt supported) comment out the following three lines -// and uncomment the HardwareSerial line -#include -SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); -SoftwareSerial *fonaSerial = &fonaSS; - -// Hardware serial is also possible! -// HardwareSerial *fonaSerial = &Serial1; - -Adafruit_FONA fona = Adafruit_FONA(FONA_RST); - -void setup() { - Serial.begin(115200); - Serial.println(F("FONA incoming call example")); - Serial.println(F("Initializing....(May take 3 seconds)")); - - fonaSerial->begin(4800); - if (! fona.begin(*fonaSerial)) { - Serial.println(F("Couldn't find FONA")); - while(1); - } - Serial.println(F("FONA is OK")); - - // Enable incoming call notification. - if(fona.callerIdNotification(true, FONA_RI_INTERRUPT)) { - Serial.println(F("Caller id notification enabled.")); - } - else { - Serial.println(F("Caller id notification disabled")); - } -} - -void loop(){ - // Create a small string buffer to hold incoming call number. - char phone[32] = {0}; - // Check for an incoming call. Will return true if a call is incoming. - if(fona.incomingCallNumber(phone)){ - Serial.println(F("RING!")); - Serial.print(F("Phone Number: ")); - Serial.println(phone); - } -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/FONAConfig.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/FONAConfig.h deleted file mode 100644 index 5fa3e13..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/FONAConfig.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * FONAConfig.h -- compile-time configuration - * This is part of the library for the Adafruit FONA Cellular Module - * - * Designed specifically to work with the Adafruit FONA - * ----> https://www.adafruit.com/products/1946 - * ----> https://www.adafruit.com/products/1963 - * ----> http://www.adafruit.com/products/2468 - * ----> http://www.adafruit.com/products/2542 - * - * Adafruit invests time and resources providing this open source code, - * please support Adafruit and open-source hardware by purchasing - * products from Adafruit! - * - * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in - * the Adafruit_FONA_Library and released under the - * BSD license, all text above must be included in any redistribution. - * - * Created on: Jan 16, 2016 - * Author: Pat Deegan - */ - -#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONACONFIG_H_ -#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONACONFIG_H_ - -/* ADAFRUIT_FONA_DEBUG - * When defined, will cause extensive debug output on the - * DebugStream set in the appropriate platform/ header. - */ - -#define ADAFRUIT_FONA_DEBUG - - -#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONACONFIG_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h deleted file mode 100644 index f8fe878..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/FONAExtIncludes.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * FONAExtIncludes.h -- system-wide includes - * This is part of the library for the Adafruit FONA Cellular Module - * - * Designed specifically to work with the Adafruit FONA - * ----> https://www.adafruit.com/products/1946 - * ----> https://www.adafruit.com/products/1963 - * ----> http://www.adafruit.com/products/2468 - * ----> http://www.adafruit.com/products/2542 - * - * Adafruit invests time and resources providing this open source code, - * please support Adafruit and open-source hardware by purchasing - * products from Adafruit! - * - * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in - * the Adafruit_FONA_Library and released under the - * BSD license, all text above must be included in any redistribution. - * - * Created on: Jan 16, 2016 - * Author: Pat Deegan - */ - - -#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONAEXTINCLUDES_H_ -#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONAEXTINCLUDES_H_ - - -#include "FONAConfig.h" -// include any system-wide includes required here - - - -#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_FONAEXTINCLUDES_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h deleted file mode 100644 index 85bc8fe..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatStd.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * FONAPlatStd.h -- standard AVR/Arduino platform. - * - * This is part of the library for the Adafruit FONA Cellular Module - * - * Designed specifically to work with the Adafruit FONA - * ----> https://www.adafruit.com/products/1946 - * ----> https://www.adafruit.com/products/1963 - * ----> http://www.adafruit.com/products/2468 - * ----> http://www.adafruit.com/products/2542 - * - * Adafruit invests time and resources providing this open source code, - * please support Adafruit and open-source hardware by purchasing - * products from Adafruit! - * - * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in - * the Adafruit_FONA_Library and released under the - * BSD license, all text above must be included in any redistribution. - * - * Created on: Jan 16, 2016 - * Author: Pat Deegan - */ - - -#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATSTD_H_ -#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATSTD_H_ - -#include "../FONAConfig.h" - - -#if (ARDUINO >= 100) - #include "Arduino.h" - #if !defined(__SAM3X8E__) && !defined(ARDUINO_ARCH_SAMD) // Arduino Due doesn't support #include - #endif -#else - #include "WProgram.h" - #include -#endif - -#include - - -// DebugStream sets the Stream output to use -// for debug (only applies when ADAFRUIT_FONA_DEBUG -// is defined in config) -#define DebugStream Serial - -#ifdef ADAFRUIT_FONA_DEBUG -// need to do some debugging... -#define DEBUG_PRINT(...) DebugStream.print(__VA_ARGS__) -#define DEBUG_PRINTLN(...) DebugStream.println(__VA_ARGS__) -#endif - -// a few typedefs to keep things portable -typedef Stream FONAStreamType; -typedef const __FlashStringHelper * FONAFlashStringPtr; - -#define prog_char char PROGMEM - -#define prog_char_strcmp(a, b) strcmp_P((a), (b)) -// define prog_char_strncmp(a, b, c) strncmp_P((a), (b), (c)) -#define prog_char_strstr(a, b) strstr_P((a), (b)) -#define prog_char_strlen(a) strlen_P((a)) -#define prog_char_strcpy(to, fromprogmem) strcpy_P((to), (fromprogmem)) -//define prog_char_strncpy(to, from, len) strncpy_P((to), (fromprogmem), (len)) - -#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATSTD_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h deleted file mode 100644 index 0bf98d0..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/includes/platform/FONAPlatform.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * FONAPlatform.h -- platform definitions includes. - * - * This is part of the library for the Adafruit FONA Cellular Module - * - * Designed specifically to work with the Adafruit FONA - * ----> https://www.adafruit.com/products/1946 - * ----> https://www.adafruit.com/products/1963 - * ----> http://www.adafruit.com/products/2468 - * ----> http://www.adafruit.com/products/2542 - * - * Adafruit invests time and resources providing this open source code, - * please support Adafruit and open-source hardware by purchasing - * products from Adafruit! - * - * Written by Pat Deegan, http://flyingcarsandstuff.com, for inclusion in - * the Adafruit_FONA_Library and released under the - * BSD license, all text above must be included in any redistribution. - * - * Created on: Jan 16, 2016 - * Author: Pat Deegan - */ - - -#ifndef ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATFORM_H_ -#define ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATFORM_H_ - -#include "../FONAConfig.h" - -// only "standard" config supported in this release -- namely AVR-based arduino type affairs -#include "FONAPlatStd.h" - - - -#ifndef DEBUG_PRINT -// debug is disabled - -#define DEBUG_PRINT(...) -#define DEBUG_PRINTLN(...) - -#endif - - -#ifndef prog_char_strcmp -#define prog_char_strcmp(a, b) strcmp((a), (b)) -#endif - -#ifndef prog_char_strstr -#define prog_char_strstr(a, b) strstr((a), (b)) -#endif - -#ifndef prog_char_strlen -#define prog_char_strlen(a) strlen((a)) -#endif - - -#ifndef prog_char_strcpy -#define prog_char_strcpy(to, fromprogmem) strcpy((to), (fromprogmem)) -#endif - - -#endif /* ADAFRUIT_FONA_LIBRARY_SRC_INCLUDES_PLATFORM_FONAPLATFORM_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/library.properties b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/library.properties deleted file mode 100644 index bb7099c..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_FONA_Library/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=Adafruit FONA Library -version=1.3.2 -author=Adafruit -maintainer=Adafruit -sentence=Arduino library for the Adafruit FONA -paragraph=Arduino library for the Adafruit FONA -category=Communication -url=https://github.com/adafruit/Adafruit_FONA_Library -architectures=* diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp deleted file mode 100644 index 9448278..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.cpp +++ /dev/null @@ -1,4 +0,0 @@ -#include "Adafruit_SleepyDog.h" - -// Global instance of the main class for sketches to use. -WatchdogType Watchdog; diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h deleted file mode 100644 index 4cdf4b4..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/Adafruit_SleepyDog.h +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef ADAFRUIT_SLEEPYDOG_H -#define ADAFRUIT_SLEEPYDOG_H - -// Platform-specific code goes below. Each #ifdef should check for the presence -// of their platform and pull in the appropriate watchdog implementation type, -// then typedef it to WatchdogType so the .cpp file can create a global instance. -#if defined(ARDUINO_ARCH_AVR) || defined(__AVR__) - #include "utility/WatchdogAVR.h" - typedef WatchdogAVR WatchdogType; -#elif defined(ARDUINO_ARCH_SAMD) - // Arduino Zero / ATSAMD series CPU watchdog support. - #include "utility/WatchdogSAMD.h" - typedef WatchdogSAMD WatchdogType; -#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) - // Teensy 3.x watchdog support. - #include "utility/WatchdogKinetisK.h" - typedef WatchdogKinetisKseries WatchdogType; -#elif defined(__MKL26Z64__) - // Teensy LC watchdog support. - #include "utility/WatchdogKinetisL.h" - typedef WatchdogKinetisLseries WatchdogType; -#else - #error Unsupported platform for the Adafruit Watchdog library! -#endif - -extern WatchdogType Watchdog; - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/LICENSE b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/LICENSE deleted file mode 100644 index 04ebb92..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Adafruit Industries - -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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/README.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/README.md deleted file mode 100644 index 3aa268a..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# Adafruit SleepyDog Arduino Library - -Arduino library to use the watchdog timer for system reset and low power sleep. - -Currently supports the following hardware: -* Arduino Uno or compatible (ATmega328P). diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino deleted file mode 100644 index 8d47041..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/examples/BasicUsage/BasicUsage.ino +++ /dev/null @@ -1,62 +0,0 @@ -// Adafruit Watchdog Library Basic Usage Example -// -// Simple example of how to use the watchdog library. -// -// Author: Tony DiCola - -#include - -void setup() { - Serial.begin(115200); - while (!Serial) ; // wait for Arduino Serial Monitor (native USB boards) - Serial.println("Adafruit Watchdog Library Demo!"); - Serial.println(); - - // First a normal example of using the watchdog timer. - // Enable the watchdog by calling Watchdog.enable() as below. This will turn - // on the watchdog timer with a ~4 second timeout before reseting the Arduino. - // The estimated actual milliseconds before reset (in milliseconds) is returned. - // Make sure to reset the watchdog before the countdown expires or the Arduino - // will reset! - int countdownMS = Watchdog.enable(4000); - Serial.print("Enabled the watchdog with max countdown of "); - Serial.print(countdownMS, DEC); - Serial.println(" milliseconds!"); - Serial.println(); - - // Now loop a few times and periodically reset the watchdog. - Serial.println("Looping ten times while resetting the watchdog..."); - for (int i = 1; i <= 10; ++i) { - Serial.print("Loop #"); Serial.println(i, DEC); - delay(1000); - // Reset the watchdog with every loop to make sure the sketch keeps running. - // If you comment out this call watch what happens after about 4 iterations! - Watchdog.reset(); - } - Serial.println(); - - // Disable the watchdog entirely by calling Watchdog.disable(); - Watchdog.disable(); - - // Finally demonstrate the watchdog resetting by enabling it for a shorter - // period of time and waiting a long time without a reset. Notice you can pass - // a _maximum_ countdown time (in milliseconds) to the enable call. The library - // will try to use that value as the countdown, but it might pick a smaller - // value if the hardware doesn't support it. The actual countdown value will - // be returned so you can see what it is. - countdownMS = Watchdog.enable(4000); - Serial.print("Get ready, the watchdog will reset in "); - Serial.print(countdownMS, DEC); - Serial.println(" milliseconds!"); - Serial.println(); - delay(countdownMS+1000); - - // Execution will never get here because the watchdog resets the Arduino! -} - -void loop() { - // We'll never actually get to the loop because the watchdog will reset in - // the setup function. - Serial.println("You shouldn't see this message."); - delay(1000); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino deleted file mode 100644 index d8eab80..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/examples/Sleep/Sleep.ino +++ /dev/null @@ -1,37 +0,0 @@ -// Adafruit Watchdog Library Sleep Example -// -// Simple example of how to do low power sleep with the watchdog timer. -// -// Author: Tony DiCola - -#include - -void setup() { - Serial.begin(115200); - while (!Serial) ; // wait for Arduino Serial Monitor (native USB boards) - Serial.println("Adafruit Watchdog Library Sleep Demo!"); - Serial.println(); -} - -void loop() { - Serial.println("Going to sleep in one second..."); - delay(1000); - - // To enter low power sleep mode call Watchdog.sleep() like below - // and the watchdog will allow low power sleep for as long as possible. - // The actual amount of time spent in sleep will be returned (in - // milliseconds). - int sleepMS = Watchdog.sleep(); - - // Alternatively you can provide a millisecond value to specify - // how long you'd like the chip to sleep, but the hardware only - // supports a limited range of values so the actual sleep time might - // be smaller. The time spent in sleep will be returned (in - // milliseconds). - // int sleepMS = Watchdog.sleep(1000); // Sleep for up to 1 second. - - Serial.print("I'm awake now! I slept for "); - Serial.print(sleepMS, DEC); - Serial.println(" milliseconds."); - Serial.println(); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/library.properties b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/library.properties deleted file mode 100644 index c41d74b..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=Adafruit SleepyDog Library -version=1.1.1 -author=Adafruit -maintainer=Adafruit -sentence=Arduino library to use the watchdog timer for system reset and low power sleep. -paragraph=Arduino library to use the watchdog timer for system reset and low power sleep. -category=Other -url=https://github.com/adafruit/Adafruit_SleepyDog -architectures=* diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp deleted file mode 100644 index 3355c13..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.cpp +++ /dev/null @@ -1,137 +0,0 @@ -// Be careful to use a platform-specific conditional include to only make the -// code visible for the appropriate platform. Arduino will try to compile and -// link all .cpp files regardless of platform. -#if defined(ARDUINO_ARCH_AVR) || defined(__AVR__) - -#include -#include -#include -#include - -#include "WatchdogAVR.h" - -// Define watchdog timer interrupt. -ISR(WDT_vect) -{ - // Nothing needs to be done, however interrupt handler must be defined to - // prevent a reset. -} - -int WatchdogAVR::enable(int maxPeriodMS) { - // Pick the closest appropriate watchdog timer value. - int actualMS; - _setPeriod(maxPeriodMS, _wdto, actualMS); - // Enable the watchdog and return the actual countdown value. - wdt_enable(_wdto); - return actualMS; -} - -void WatchdogAVR::reset() { - // Reset the watchdog. - wdt_reset(); -} - -void WatchdogAVR::disable() { - // Disable the watchdog and clear any saved watchdog timer value. - wdt_disable(); - _wdto = -1; -} - -int WatchdogAVR::sleep(int maxPeriodMS) { - // Pick the closest appropriate watchdog timer value. - int sleepWDTO, actualMS; - _setPeriod(maxPeriodMS, sleepWDTO, actualMS); - - // Build watchdog prescaler register value before timing critical code. - uint8_t wdps = ((sleepWDTO & 0x08 ? 1 : 0) << WDP3) | - ((sleepWDTO & 0x04 ? 1 : 0) << WDP2) | - ((sleepWDTO & 0x02 ? 1 : 0) << WDP1) | - ((sleepWDTO & 0x01 ? 1 : 0) << WDP0); - - // The next section is timing critical so interrupts are disabled. - cli(); - // First clear any previous watchdog reset. - MCUSR &= ~(1<= 8000) || (maxMS == 0)) { - wdto = WDTO_8S; - actualMS = 8000; - } - else if (maxMS >= 4000) { - wdto = WDTO_4S; - actualMS = 4000; - } - else if (maxMS >= 2000) { - wdto = WDTO_2S; - actualMS = 2000; - } - else if (maxMS >= 1000) { - wdto = WDTO_1S; - actualMS = 1000; - } - else if (maxMS >= 500) { - wdto = WDTO_500MS; - actualMS = 500; - } - else if (maxMS >= 250) { - wdto = WDTO_250MS; - actualMS = 250; - } - else if (maxMS >= 120) { - wdto = WDTO_120MS; - actualMS = 120; - } - else if (maxMS >= 60) { - wdto = WDTO_60MS; - actualMS = 60; - } - else if (maxMS >= 30) { - wdto = WDTO_30MS; - actualMS = 30; - } - else { - wdto = WDTO_15MS; - actualMS = 15; - } -} - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h deleted file mode 100644 index 9753b08..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogAVR.h +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef WATCHDOGAVR_H -#define WATCHDOGAVR_H - -class WatchdogAVR { -public: - WatchdogAVR(): - _wdto(-1) - {} - - // Enable the watchdog timer to reset the machine after a period of time - // without any calls to reset(). The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware does - // not support the exact desired value. - // - // The actual period (in milliseconds) before a watchdog timer reset is - // returned. - int enable(int maxPeriodMS = 0); - - // Reset or 'kick' the watchdog timer to prevent a reset of the device. - void reset(); - - // Completely disable the watchdog timer. - void disable(); - - // Enter the lowest power sleep mode (using the watchdog timer) for the - // desired period of time. The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware does - // not support the exact desired value - // - // The actual period (in milliseconds) that the hardware was asleep will be - // returned. - int sleep(int maxPeriodMS = 0); - -private: - // Pick the closest (but not higher) watchdog timer value from the provided - // maximum period. Sets wdto to the chosen period value suitable for - // passing to wdt_enable(), and actualMS to the chosen period value in - // milliseconds. A max value of 0 will pick the longest value possible. - void _setPeriod(int maxMS, int &wdto, int &actualMS); - - // Keep the last selected watchdog timer period so that the watchdog can be - // re-enabled at that rate after sleep. A value of -1 means no watchdog - // timer was enabled. - int _wdto; -}; - -#endif \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp deleted file mode 100644 index 9705859..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.cpp +++ /dev/null @@ -1,104 +0,0 @@ -// Be careful to use a platform-specific conditional include to only make the -// code visible for the appropriate platform. Arduino will try to compile and -// link all .cpp files regardless of platform. -#if defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) - -#include -#include "WatchdogKinetisK.h" - -static void one_bus_cycle(void) __attribute__((always_inline)); -static void watchdog_config(int cfg, int val); - -// Enable the watchdog timer to reset the machine after a period of time -// without any calls to reset(). The passed in period (in milliseconds) is -// just a suggestion and a lower value might be picked if the hardware does -// not support the exact desired value. -// -// The actual period (in milliseconds) before a watchdog timer reset is -// returned. -int WatchdogKinetisKseries::enable(int maxPeriodMS) -{ - if (maxPeriodMS < 4) { - maxPeriodMS = 8000; // default is 8 seconds - } - if (setting != maxPeriodMS) { - watchdog_config(WDOG_STCTRLH_WDOGEN, maxPeriodMS); - setting = maxPeriodMS; - } - return maxPeriodMS; -} - -// Reset or 'kick' the watchdog timer to prevent a reset of the device. -void WatchdogKinetisKseries::reset() -{ - __disable_irq(); - WDOG_REFRESH = 0xA602; - WDOG_REFRESH = 0xB480; - __enable_irq(); -} - -// Completely disable the watchdog timer. -void WatchdogKinetisKseries::disable() -{ - if (setting > 0) { - watchdog_config(0, 4); - setting = 0; - } -} - -// Enter the lowest power sleep mode for the desired period of time. The -// passed in period (in milliseconds) is just a suggestion and a lower value -// might be picked if the hardware does not support the exact desired value -// -// The actual period (in milliseconds) that the hardware was asleep will be -// returned. -int WatchdogKinetisKseries::sleep(int maxPeriodMS) -{ - if (maxPeriodMS <= 0) return 0; - // TODO.... - return 0; -} - -static void watchdog_config(int cfg, int val) -{ - __disable_irq(); - WDOG_UNLOCK = WDOG_UNLOCK_SEQ1; - WDOG_UNLOCK = WDOG_UNLOCK_SEQ2; - one_bus_cycle(); - WDOG_STCTRLH = cfg | WDOG_STCTRLH_ALLOWUPDATE; - WDOG_TOVALH = val >> 16; - WDOG_TOVALL = val; - WDOG_PRESC = 0; - __enable_irq(); - for (int i=0; i < 256; i++) { - one_bus_cycle(); - } -} - -static void one_bus_cycle(void) -{ - __asm__ volatile ("nop"); - #if (F_CPU / F_BUS) > 1 - __asm__ volatile ("nop"); - #endif - #if (F_CPU / F_BUS) > 2 - __asm__ volatile ("nop"); - #endif - #if (F_CPU / F_BUS) > 3 - __asm__ volatile ("nop"); - #endif - #if (F_CPU / F_BUS) > 4 - __asm__ volatile ("nop"); - #endif - #if (F_CPU / F_BUS) > 5 - __asm__ volatile ("nop"); - #endif - #if (F_CPU / F_BUS) > 6 - __asm__ volatile ("nop"); - #endif - #if (F_CPU / F_BUS) > 7 - __asm__ volatile ("nop"); - #endif -} - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h deleted file mode 100644 index e09a0c2..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisK.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef WATCHDOGKINETISK_H -#define WATCHDOGKINETISK_H - -class WatchdogKinetisKseries { -public: - WatchdogKinetisKseries(): setting(0) {} - - // Enable the watchdog timer to reset the machine after a period of time - // without any calls to reset(). The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware does - // not support the exact desired value. - // - // The actual period (in milliseconds) before a watchdog timer reset is - // returned. - int enable(int maxPeriodMS = 0); - - // Reset or 'kick' the watchdog timer to prevent a reset of the device. - void reset(); - - // Completely disable the watchdog timer. - void disable(); - - // Enter the lowest power sleep mode (using the watchdog timer) for the - // desired period of time. The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware does - // not support the exact desired value - // - // The actual period (in milliseconds) that the hardware was asleep will be - // returned. - // - // NOTE: This is currently not implemented on the SAMD21! - int sleep(int maxPeriodMS = 0); - -private: - int setting; -}; - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp deleted file mode 100644 index 501e9c0..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.cpp +++ /dev/null @@ -1,74 +0,0 @@ -// Be careful to use a platform-specific conditional include to only make the -// code visible for the appropriate platform. Arduino will try to compile and -// link all .cpp files regardless of platform. -#if defined(__MKL26Z64__) - -#include -#include "WatchdogKinetisL.h" - -// Normally the watchdog is disabled at startup. This removes the startup -// code. The watchdog will be active with 1024 ms timeout. Hopefully the -// user will configure the watchdog and begin resetting it before it causes -// a reboot. There is no way to start up without the watchdog and then -// enable it later... -extern "C" void startup_early_hook(void) {} - - -// Enable the watchdog timer to reset the machine after a period of time -// without any calls to reset(). The passed in period (in milliseconds) is -// just a suggestion and a lower value might be picked if the hardware does -// not support the exact desired value. -// -// The actual period (in milliseconds) before a watchdog timer reset is -// returned. -int WatchdogKinetisLseries::enable(int maxPeriodMS) -{ - // The watchdog can only be programmed once. Then it's forever - // locked to this setting (until the chip reboots). - if (maxPeriodMS <= 0 || maxPeriodMS > 256) { - SIM_COPC = 12; - } else if (maxPeriodMS > 32) { - SIM_COPC = 8; - } else { - SIM_COPC = 4; - } - // Read the actual setting. - int val = SIM_COPC & 12; - if (val == 12) return 1024; - if (val == 8) return 256; - return 32; -} - -// Reset or 'kick' the watchdog timer to prevent a reset of the device. -void WatchdogKinetisLseries::reset() -{ - __disable_irq(); - SIM_SRVCOP = 0x55; - SIM_SRVCOP = 0xAA; - __enable_irq(); -} - -// Completely disable the watchdog timer. -void WatchdogKinetisLseries::disable() -{ - // no can do.... - // The watchdog timer in this chip is write-once. - // The chip boots up with the watchdog at 1024 ms. - // You only get to configure it once. Then it - // remains locked to that setting, until a reboot. -} - -// Enter the lowest power sleep mode for the desired period of time. The -// passed in period (in milliseconds) is just a suggestion and a lower value -// might be picked if the hardware does not support the exact desired value -// -// The actual period (in milliseconds) that the hardware was asleep will be -// returned. -int WatchdogKinetisLseries::sleep(int maxPeriodMS) -{ - if (maxPeriodMS <= 0) return 0; - // TODO.... - return 0; -} - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h deleted file mode 100644 index 3c68d5e..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogKinetisL.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef WATCHDOGKINETISL_H -#define WATCHDOGKINETISL_H - -class WatchdogKinetisLseries { -public: - WatchdogKinetisLseries() {} - - // Enable the watchdog timer to reset the machine after a period of time - // without any calls to reset(). The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware does - // not support the exact desired value. - // - // The actual period (in milliseconds) before a watchdog timer reset is - // returned. - int enable(int maxPeriodMS = 0); - - // Reset or 'kick' the watchdog timer to prevent a reset of the device. - void reset(); - - // Completely disable the watchdog timer. - void disable(); - - // Enter the lowest power sleep mode (using the watchdog timer) for the - // desired period of time. The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware does - // not support the exact desired value - // - // The actual period (in milliseconds) that the hardware was asleep will be - // returned. - // - // NOTE: This is currently not implemented on the SAMD21! - int sleep(int maxPeriodMS = 0); -}; - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp deleted file mode 100644 index d21d9a9..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.cpp +++ /dev/null @@ -1,175 +0,0 @@ -// Requires Adafruit_ASFcore library! - -// Be careful to use a platform-specific conditional include to only make the -// code visible for the appropriate platform. Arduino will try to compile and -// link all .cpp files regardless of platform. -#if defined(ARDUINO_ARCH_SAMD) - -#include -#include -#include -#include "WatchdogSAMD.h" - -int WatchdogSAMD::enable(int maxPeriodMS, bool isForSleep) { - // Enable the watchdog with a period up to the specified max period in - // milliseconds. - - // Review the watchdog section from the SAMD21 datasheet section 17: - // http://www.atmel.com/images/atmel-42181-sam-d21_datasheet.pdf - - int cycles, actualMS; - uint8_t bits; - - if(!_initialized) _initialize_wdt(); - - WDT->CTRL.reg = 0; // Disable watchdog for config - while(WDT->STATUS.bit.SYNCBUSY); - - // You'll see some occasional conversion here compensating between - // milliseconds (1000 Hz) and WDT clock cycles (~1024 Hz). The low- - // power oscillator used by the WDT ostensibly runs at 32,768 Hz with - // a 1:32 prescale, thus 1024 Hz, though probably not super precise. - - if((maxPeriodMS >= 16000) || !maxPeriodMS) { - cycles = 16384; - bits = 0xB; - } else { - cycles = (maxPeriodMS * 1024L + 500) / 1000; // ms -> WDT cycles - if(cycles >= 8192) { - cycles = 8192; - bits = 0xA; - } else if(cycles >= 4096) { - cycles = 4096; - bits = 0x9; - } else if(cycles >= 2048) { - cycles = 2048; - bits = 0x8; - } else if(cycles >= 1024) { - cycles = 1024; - bits = 0x7; - } else if(cycles >= 512) { - cycles = 512; - bits = 0x6; - } else if(cycles >= 256) { - cycles = 256; - bits = 0x5; - } else if(cycles >= 128) { - cycles = 128; - bits = 0x4; - } else if(cycles >= 64) { - cycles = 64; - bits = 0x3; - } else if(cycles >= 32) { - cycles = 32; - bits = 0x2; - } else if(cycles >= 16) { - cycles = 16; - bits = 0x1; - } else { - cycles = 8; - bits = 0x0; - } - } - - // Watchdog timer on SAMD is a slightly different animal than on AVR. - // On AVR, the WTD timeout is configured in one register and then an - // interrupt can optionally be enabled to handle the timeout in code - // (as in waking from sleep) vs resetting the chip. Easy. - // On SAMD, when the WDT fires, that's it, the chip's getting reset. - // Instead, it has an "early warning interrupt" with a different set - // interval prior to the reset. For equivalent behavior to the AVR - // library, this requires a slightly different configuration depending - // whether we're coming from the sleep() function (which needs the - // interrupt), or just enable() (no interrupt, we want the chip reset - // unless the WDT is cleared first). In the sleep case, 'windowed' - // mode is used in order to allow access to the longest available - // sleep interval (about 16 sec); the WDT 'period' (when a reset - // occurs) follows this and is always just set to the max, since the - // interrupt will trigger first. In the enable case, windowed mode - // is not used, the WDT period is set and that's that. - // The 'isForSleep' argument determines which behavior is used; - // this isn't present in the AVR code, just here. It defaults to - // 'false' so existing Arduino code works as normal, while the sleep() - // function (later in this file) explicitly passes 'true' to get the - // alternate behavior. - - if(isForSleep) { - WDT->INTENSET.bit.EW = 1; // Enable early warning interrupt - WDT->CONFIG.bit.PER = 0xB; // Period = max - WDT->CONFIG.bit.WINDOW = bits; // Set time of interrupt - WDT->CTRL.bit.WEN = 1; // Enable window mode - while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write - } else { - WDT->INTENCLR.bit.EW = 1; // Disable early warning interrupt - WDT->CONFIG.bit.PER = bits; // Set period for chip reset - WDT->CTRL.bit.WEN = 0; // Disable window mode - while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write - } - - actualMS = (cycles * 1000L + 512) / 1024; // WDT cycles -> ms - - reset(); // Clear watchdog interval - WDT->CTRL.bit.ENABLE = 1; // Start watchdog now! - while(WDT->STATUS.bit.SYNCBUSY); - - return actualMS; -} - -void WatchdogSAMD::reset() { - // Write the watchdog clear key value (0xA5) to the watchdog - // clear register to clear the watchdog timer and reset it. - WDT->CLEAR.reg = WDT_CLEAR_CLEAR_KEY; - while(WDT->STATUS.bit.SYNCBUSY); -} - -void WatchdogSAMD::disable() { - WDT->CTRL.bit.ENABLE = 0; - while(WDT->STATUS.bit.SYNCBUSY); -} - -void WDT_Handler(void) { - // ISR for watchdog early warning, DO NOT RENAME! - WDT->CTRL.bit.ENABLE = 0; // Disable watchdog - while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write - WDT->INTFLAG.bit.EW = 1; // Clear interrupt flag -} - -int WatchdogSAMD::sleep(int maxPeriodMS) { - - int actualPeriodMS = enable(maxPeriodMS, true); // true = for sleep - - system_set_sleepmode(SYSTEM_SLEEPMODE_STANDBY); // Deepest sleep - system_sleep(); - // Code resumes here on wake (WDT early warning interrupt) - - return actualPeriodMS; -} - -void WatchdogSAMD::_initialize_wdt() { - // One-time initialization of watchdog timer. - // Insights from rickrlh and rbrucemtl in Arduino forum! - - // Generic clock generator 2, divisor = 32 (2^(DIV+1)) - GCLK->GENDIV.reg = GCLK_GENDIV_ID(2) | GCLK_GENDIV_DIV(4); - // Enable clock generator 2 using low-power 32KHz oscillator. - // With /32 divisor above, this yields 1024Hz(ish) clock. - GCLK->GENCTRL.reg = GCLK_GENCTRL_ID(2) | - GCLK_GENCTRL_GENEN | - GCLK_GENCTRL_SRC_OSCULP32K | - GCLK_GENCTRL_DIVSEL; - while(GCLK->STATUS.bit.SYNCBUSY); - // WDT clock = clock gen 2 - GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID_WDT | - GCLK_CLKCTRL_CLKEN | - GCLK_CLKCTRL_GEN_GCLK2; - - // Enable WDT early-warning interrupt - NVIC_DisableIRQ(WDT_IRQn); - NVIC_ClearPendingIRQ(WDT_IRQn); - NVIC_SetPriority(WDT_IRQn, 0); // Top priority - NVIC_EnableIRQ(WDT_IRQn); - - _initialized = true; -} - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h deleted file mode 100644 index 8b03c27..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/Adafruit_SleepyDog_Library/utility/WatchdogSAMD.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef WATCHDOGSAMD_H -#define WATCHDOGSAMD_H - -class WatchdogSAMD { -public: - WatchdogSAMD(): - _initialized(false) - {} - - // Enable the watchdog timer to reset the machine after a period of time - // without any calls to reset(). The passed in period (in milliseconds) - // is just a suggestion and a lower value might be picked if the hardware - // does not support the exact desired value. - // User code should NOT set the 'isForSleep' argument either way -- - // it's used internally by the library, but your sketch should leave this - // out when calling enable(), just let the default have its way. - // - // The actual period (in milliseconds) before a watchdog timer reset is - // returned. - int enable(int maxPeriodMS = 0, bool isForSleep = false); - - // Reset or 'kick' the watchdog timer to prevent a reset of the device. - void reset(); - - // Completely disable the watchdog timer. - void disable(); - - // Enter the lowest power sleep mode (using the watchdog timer) for the - // desired period of time. The passed in period (in milliseconds) is - // just a suggestion and a lower value might be picked if the hardware - // does not support the exact desired value - // - // The actual period (in milliseconds) that the hardware was asleep will be - // returned. - int sleep(int maxPeriodMS = 0); - -private: - void _initialize_wdt(); - - bool _initialized; -}; - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/.gitignore b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/.gitignore deleted file mode 100644 index 89d225a..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.development -examples/node_test_server/node_modules/ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/CHANGELOG.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/CHANGELOG.md deleted file mode 100644 index 5645508..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/CHANGELOG.md +++ /dev/null @@ -1,25 +0,0 @@ -## ArduinoHttpClient 0.3.1 - 2017.09.25 - -* Changed examples to support Arduino Create secret tabs -* Increase WebSocket secrect-key length to 24 characters - -## ArduinoHttpClient 0.3.0 - 2017.04.20 - -* Added support for PATCH operations -* Added support for chunked response bodies -* Added new beginBody API - -## ArduinoHttpClient 0.2.0 - 2017.01.12 - -* Added PATCH method -* Added basic auth example -* Added custom header example - -## ArduinoHttpClient 0.1.1 - 2016.12.16 - -* More robust response parser - -## ArduinoHttpClient 0.1.0 - 2016.07.05 - -* Initial release - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/README.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/README.md deleted file mode 100644 index 655b618..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# ArduinoHttpClient - -ArduinoHttpClient is a library to make it easier to interact with web servers from Arduino. - -Derived from [Adrian McEwen's HttpClient library](https://github.com/amcewen/HttpClient) - -## Dependencies - -- Requires a networking hardware and a library that provides transport specific `Client` instance, such as: - - [WiFi101](https://github.com/arduino-libraries/WiFi101) - - [Ethernet](https://github.com/arduino-libraries/Ethernet) - - [WiFi](https://github.com/arduino-libraries/WiFi) - - [GSM](https://github.com/arduino-libraries/GSM) - -## Usage - -In normal usage, handles the outgoing request and Host header. The returned status code is parsed for you, as is the Content-Length header (if present). - -Because it expects an object of type Client, you can use it with any of the networking classes that derive from that. Which means it will work with WiFiClient, EthernetClient and GSMClient. - -See the examples for more detail on how the library is used. - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino deleted file mode 100644 index e793d47..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/BasicAuthGet.ino +++ /dev/null @@ -1,69 +0,0 @@ -/* - GET client with HTTP basic authentication for ArduinoHttpClient library - Connects to server once every five seconds, sends a GET request - - - - created 14 Feb 2016 - by Tom Igoe - modified 3 Jan 2017 to add HTTP basic authentication - by Sandeep Mistry - - this example is in the public domain - */ -#include -#include -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("making GET request with HTTP basic authentication"); - client.beginRequest(); - client.get("/secure"); - client.sendBasicAuth("username", "password"); // send the username and password for authentication - client.endRequest(); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - Serial.println("Wait five seconds"); - delay(5000); -} - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/BasicAuthGet/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino deleted file mode 100644 index fa44aca..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/CustomHeader/CustomHeader.ino +++ /dev/null @@ -1,96 +0,0 @@ -/* - Custom request header example for the ArduinoHttpClient - library. This example sends a GET and a POST request with a custom header every 5 seconds. - - note: WiFi SSID and password are stored in config.h file. - If it is not present, add a new tab, call it "config.h" - and add the following variables: - char ssid[] = "ssid"; // your network SSID (name) - char pass[] = "password"; // your network password - - based on SimpleGet example by Tom Igoe - header modifications by Todd Treece - - this example is in the public domain - */ - -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - - Serial.println("making GET request"); - client.beginRequest(); - client.get("/"); - client.sendHeader("X-CUSTOM-HEADER", "custom_value"); - client.endRequest(); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("GET Status code: "); - Serial.println(statusCode); - Serial.print("GET Response: "); - Serial.println(response); - - Serial.println("Wait five seconds"); - delay(5000); - - Serial.println("making POST request"); - String postData = "name=Alice&age=12"; - client.beginRequest(); - client.post("/"); - client.sendHeader(HTTP_HEADER_CONTENT_TYPE, "application/x-www-form-urlencoded"); - client.sendHeader(HTTP_HEADER_CONTENT_LENGTH, postData.length()); - client.sendHeader("X-CUSTOM-HEADER", "custom_value"); - client.endRequest(); - client.write((const byte*)postData.c_str(), postData.length()); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("POST Status code: "); - Serial.println(statusCode); - Serial.print("POST Response: "); - Serial.println(response); - - Serial.println("Wait five seconds"); - delay(5000); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/CustomHeader/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino deleted file mode 100644 index 51abd3f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetGet/DweetGet.ino +++ /dev/null @@ -1,107 +0,0 @@ -/* - Dweet.io GET client for ArduinoHttpClient library - Connects to dweet.io once every ten seconds, - sends a GET request and a request body. Uses SSL - - Shows how to use Strings to assemble path and parse content - from response. dweet.io expects: - https://dweet.io/get/latest/dweet/for/thingName - - For more on dweet.io, see https://dweet.io/play/ - - - - created 15 Feb 2016 - updated 16 Feb 2016 - by Tom Igoe - - this example is in the public domain -*/ -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - -const char serverAddress[] = "dweet.io"; // server address -int port = 80; -String dweetName = "scandalous-cheese-hoarder"; // use your own thing name here - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -int statusCode = 0; -String response; - -void setup() { - Serial.begin(9600); - while (!Serial); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - // assemble the path for the GET message: - String path = "/get/latest/dweet/for/" + dweetName; - - // send the GET request - Serial.println("making GET request"); - client.get(path); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - /* - Typical response is: - {"this":"succeeded", - "by":"getting", - "the":"dweets", - "with":[{"thing":"my-thing-name", - "created":"2016-02-16T05:10:36.589Z", - "content":{"sensorValue":456}}]} - - You want "content": numberValue - */ - // now parse the response looking for "content": - int labelStart = response.indexOf("content\":"); - // find the first { after "content": - int contentStart = response.indexOf("{", labelStart); - // find the following } and get what's between the braces: - int contentEnd = response.indexOf("}", labelStart); - String content = response.substring(contentStart + 1, contentEnd); - Serial.println(content); - - // now get the value after the colon, and convert to an int: - int valueStart = content.indexOf(":"); - String valueString = content.substring(valueStart + 1); - int number = valueString.toInt(); - Serial.print("Value string: "); - Serial.println(valueString); - Serial.print("Actual value: "); - Serial.println(number); - - Serial.println("Wait ten seconds\n"); - delay(10000); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetGet/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino deleted file mode 100644 index 41c6f2f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetPost/DweetPost.ino +++ /dev/null @@ -1,87 +0,0 @@ -/* - Dweet.io POST client for ArduinoHttpClient library - Connects to dweet.io once every ten seconds, - sends a POST request and a request body. - - Shows how to use Strings to assemble path and body - - note: WiFi SSID and password are stored in config.h file. - If it is not present, add a new tab, call it "config.h" - and add the following variables: - char ssid[] = "ssid"; // your network SSID (name) - char pass[] = "password"; // your network password - - created 15 Feb 2016 - by Tom Igoe - - this example is in the public domain -*/ -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - -const char serverAddress[] = "dweet.io"; // server address -int port = 80; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -int statusCode = 0; -String response; - -void setup() { - Serial.begin(9600); - while(!Serial); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - // assemble the path for the POST message: - String dweetName = "scandalous-cheese-hoarder"; - String path = "/dweet/for/" + dweetName; - - String contentType = "application/json"; - - // assemble the body of the POST message: - int sensorValue = analogRead(A0); - String postData = "{\"sensorValue\":\""; - postData += sensorValue; - postData += "\"}"; - - Serial.println("making POST request"); - - // send the POST request - client.post(path, contentType, postData); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - Serial.println("Wait ten seconds\n"); - delay(10000); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/DweetPost/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino deleted file mode 100644 index c18ae47..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/HueBlink/HueBlink.ino +++ /dev/null @@ -1,102 +0,0 @@ -/* HueBlink example for ArduinoHttpClient library - - Uses ArduinoHttpClient library to control Philips Hue - For more on Hue developer API see http://developer.meethue.com - - To control a light, the Hue expects a HTTP PUT request to: - - http://hue.hub.address/api/hueUserName/lights/lightNumber/state - - The body of the PUT request looks like this: - {"on": true} or {"on":false} - - This example shows how to concatenate Strings to assemble the - PUT request and the body of the request. - - - - modified 15 Feb 2016 - by Tom Igoe (tigoe) to match new API -*/ - -#include -#include -#include -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - -int status = WL_IDLE_STATUS; // the Wifi radio's status - -char hueHubIP[] = "192.168.0.3"; // IP address of the HUE bridge -String hueUserName = "huebridgeusername"; // hue bridge username - -// make a wifi instance and a HttpClient instance: -WiFiClient wifi; -HttpClient httpClient = HttpClient(wifi, hueHubIP); - - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial); // wait for serial port to connect. - - // attempt to connect to Wifi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to WPA SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // you're connected now, so print out the data: - Serial.print("You're connected to the network IP = "); - IPAddress ip = WiFi.localIP(); - Serial.println(ip); -} - -void loop() { - sendRequest(3, "on", "true"); // turn light on - delay(2000); // wait 2 seconds - sendRequest(3, "on", "false"); // turn light off - delay(2000); // wait 2 seconds -} - -void sendRequest(int light, String cmd, String value) { - // make a String for the HTTP request path: - String request = "/api/" + hueUserName; - request += "/lights/"; - request += light; - request += "/state/"; - - String contentType = "application/json"; - - // make a string for the JSON command: - String hueCmd = "{\"" + cmd; - hueCmd += "\":"; - hueCmd += value; - hueCmd += "}"; - // see what you assembled to send: - Serial.print("PUT request to server: "); - Serial.println(request); - Serial.print("JSON command to server: "); - - // make the PUT request to the hub: - httpClient.put(request, contentType, hueCmd); - - // read the status code and body of the response - int statusCode = httpClient.responseStatusCode(); - String response = httpClient.responseBody(); - - Serial.println(hueCmd); - Serial.print("Status code from server: "); - Serial.println(statusCode); - Serial.print("Server response: "); - Serial.println(response); - Serial.println(); -} - - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/HueBlink/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino deleted file mode 100644 index 835a26f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/PostWithHeaders.ino +++ /dev/null @@ -1,79 +0,0 @@ -/* - POST with headers client for ArduinoHttpClient library - Connects to server once every five seconds, sends a POST request - with custome headers and a request body - - - - created 14 Feb 2016 - by Tom Igoe - modified 18 Mar 2017 - by Sandeep Mistry - - this example is in the public domain - */ -#include -#include - -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("making POST request"); - String postData = "name=Alice&age=12"; - - client.beginRequest(); - client.post("/"); - client.sendHeader("Content-Type", "application/x-www-form-urlencoded"); - client.sendHeader("Content-Length", postData.length()); - client.sendHeader("X-Custom-Header", "custom-header-value"); - client.beginBody(); - client.print(postData); - client.endRequest(); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - Serial.println("Wait five seconds"); - delay(5000); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/PostWithHeaders/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino deleted file mode 100644 index 374a145..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/SimpleDelete.ino +++ /dev/null @@ -1,71 +0,0 @@ -/* - Simple DELETE client for ArduinoHttpClient library - Connects to server once every five seconds, sends a DELETE request - and a request body - - - - created 14 Feb 2016 - by Tom Igoe - - this example is in the public domain - */ -#include -#include - -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("making DELETE request"); - String contentType = "application/x-www-form-urlencoded"; - String delData = "name=light&age=46"; - - client.del("/", contentType, delData); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - Serial.println("Wait five seconds"); - delay(5000); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleDelete/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino deleted file mode 100644 index 75db9a7..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleGet/SimpleGet.ino +++ /dev/null @@ -1,66 +0,0 @@ -/* - Simple GET client for ArduinoHttpClient library - Connects to server once every five seconds, sends a GET request - - - - created 14 Feb 2016 - by Tom Igoe - - this example is in the public domain - */ -#include -#include - -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("making GET request"); - client.get("/"); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - Serial.println("Wait five seconds"); - delay(5000); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleGet/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino deleted file mode 100644 index f64b9ba..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/SimpleHttpExample.ino +++ /dev/null @@ -1,133 +0,0 @@ -// (c) Copyright 2010-2012 MCQN Ltd. -// Released under Apache License, version 2.0 -// -// Simple example to show how to use the HttpClient library -// Get's the web page given at http:// and -// outputs the content to the serial port - -#include -#include -#include - -// This example downloads the URL "http://arduino.cc/" - -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - - - -// Name of the server we want to connect to -const char kHostname[] = "arduino.cc"; -// Path to download (this is the bit after the hostname in the URL -// that you want to download -const char kPath[] = "/"; - -// Number of milliseconds to wait without receiving any data before we give up -const int kNetworkTimeout = 30*1000; -// Number of milliseconds to wait if no data is available before trying again -const int kNetworkDelay = 1000; - -WiFiClient c; -HttpClient http(c, kHostname); - -void setup() -{ - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // attempt to connect to Wifi network: - Serial.print("Attempting to connect to WPA SSID: "); - Serial.println(ssid); - while (WiFi.begin(ssid, pass) != WL_CONNECTED) { - // unsuccessful, retry in 4 seconds - Serial.print("failed ... "); - delay(4000); - Serial.print("retrying ... "); - } - - Serial.println("connected"); -} - -void loop() -{ - int err =0; - - err = http.get(kPath); - if (err == 0) - { - Serial.println("startedRequest ok"); - - err = http.responseStatusCode(); - if (err >= 0) - { - Serial.print("Got status code: "); - Serial.println(err); - - // Usually you'd check that the response code is 200 or a - // similar "success" code (200-299) before carrying on, - // but we'll print out whatever response we get - - // If you are interesting in the response headers, you - // can read them here: - //while(http.headerAvailable()) - //{ - // String headerName = http.readHeaderName(); - // String headerValue = http.readHeaderValue(); - //} - - int bodyLen = http.contentLength(); - Serial.print("Content length is: "); - Serial.println(bodyLen); - Serial.println(); - Serial.println("Body returned follows:"); - - // Now we've got to the body, so we can print it out - unsigned long timeoutStart = millis(); - char c; - // Whilst we haven't timed out & haven't reached the end of the body - while ( (http.connected() || http.available()) && - (!http.endOfBodyReached()) && - ((millis() - timeoutStart) < kNetworkTimeout) ) - { - if (http.available()) - { - c = http.read(); - // Print out this character - Serial.print(c); - - // We read something, reset the timeout counter - timeoutStart = millis(); - } - else - { - // We haven't got any data, so let's pause to allow some to - // arrive - delay(kNetworkDelay); - } - } - } - else - { - Serial.print("Getting response failed: "); - Serial.println(err); - } - } - else - { - Serial.print("Connect failed: "); - Serial.println(err); - } - http.stop(); - - // And just stop, now that we've tried a download - while(1); -} - - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleHttpExample/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino deleted file mode 100644 index 6cc3517..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePost/SimplePost.ino +++ /dev/null @@ -1,70 +0,0 @@ -/* - Simple POST client for ArduinoHttpClient library - Connects to server once every five seconds, sends a POST request - and a request body - - - - created 14 Feb 2016 - by Tom Igoe - - this example is in the public domain - */ -#include -#include -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("making POST request"); - String contentType = "application/x-www-form-urlencoded"; - String postData = "name=Alice&age=12"; - - client.post("/", contentType, postData); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - Serial.println("Wait five seconds"); - delay(5000); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePost/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino deleted file mode 100644 index 1b06105..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePut/SimplePut.ino +++ /dev/null @@ -1,70 +0,0 @@ -/* - Simple PUT client for ArduinoHttpClient library - Connects to server once every five seconds, sends a PUT request - and a request body - - - - created 14 Feb 2016 - by Tom Igoe - - this example is in the public domain - */ -#include -#include -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - - -char serverAddress[] = "192.168.0.3"; // server address -int port = 8080; - -WiFiClient wifi; -HttpClient client = HttpClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -String response; -int statusCode = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("making PUT request"); - String contentType = "application/x-www-form-urlencoded"; - String putData = "name=light&age=46"; - - client.put("/", contentType, putData); - - // read the status code and body of the response - statusCode = client.responseStatusCode(); - response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - Serial.println("Wait five seconds"); - delay(5000); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimplePut/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino deleted file mode 100644 index baac12f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/SimpleWebSocket.ino +++ /dev/null @@ -1,80 +0,0 @@ -/* - Simple WebSocket client for ArduinoHttpClient library - Connects to the WebSocket server, and sends a hello - message every 5 seconds - - - created 28 Jun 2016 - by Sandeep Mistry - - this example is in the public domain -*/ -#include -#include -#include "arduino_secrets.h" - -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -/////// Wifi Settings /////// -char ssid[] = SECRET_SSID; -char pass[] = SECRET_PASS; - -char serverAddress[] = "echo.websocket.org"; // server address -int port = 80; - -WiFiClient wifi; -WebSocketClient client = WebSocketClient(wifi, serverAddress, port); -int status = WL_IDLE_STATUS; -int count = 0; - -void setup() { - Serial.begin(9600); - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - } - - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); -} - -void loop() { - Serial.println("starting WebSocket client"); - client.begin(); - - while (client.connected()) { - Serial.print("Sending hello "); - Serial.println(count); - - // send a hello # - client.beginMessage(TYPE_TEXT); - client.print("hello "); - client.print(count); - client.endMessage(); - - // increment count for next message - count++; - - // check if a message is available to be received - int messageSize = client.parseMessage(); - - if (messageSize > 0) { - Serial.println("Received a message:"); - Serial.println(client.readString()); - } - - // wait 5 seconds - delay(5000); - } - - Serial.println("disconnected"); -} - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/SimpleWebSocket/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js deleted file mode 100644 index f3dd4d8..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/node_test_server/getPostPutDelete.js +++ /dev/null @@ -1,102 +0,0 @@ -/* - Express.js GET/POST example - Shows how handle GET, POST, PUT, DELETE - in Express.js 4.0 - - created 14 Feb 2016 - by Tom Igoe -*/ - -var express = require('express'); // include express.js -var app = express(); // a local instance of it -var bodyParser = require('body-parser'); // include body-parser -var WebSocketServer = require('ws').Server // include Web Socket server - -// you need a body parser: -app.use(bodyParser.urlencoded({extended: false})); // for application/x-www-form-urlencoded - -// this runs after the server successfully starts: -function serverStart() { - var port = server.address().port; - console.log('Server listening on port '+ port); -} - -app.get('/chunked', function(request, response) { - response.write('\n'); - response.write(' `:;;;,` .:;;:. \n'); - response.write(' .;;;;;;;;;;;` :;;;;;;;;;;: TM \n'); - response.write(' `;;;;;;;;;;;;;;;` :;;;;;;;;;;;;;;; \n'); - response.write(' :;;;;;;;;;;;;;;;;;; `;;;;;;;;;;;;;;;;;; \n'); - response.write(' ;;;;;;;;;;;;;;;;;;;;; .;;;;;;;;;;;;;;;;;;;; \n'); - response.write(' ;;;;;;;;:` `;;;;;;;;; ,;;;;;;;;.` .;;;;;;;; \n'); - response.write(' .;;;;;;, :;;;;;;; .;;;;;;; ;;;;;;; \n'); - response.write(' ;;;;;; ;;;;;;; ;;;;;;, ;;;;;;. \n'); - response.write(' ,;;;;; ;;;;;;.;;;;;;` ;;;;;; \n'); - response.write(' ;;;;;. ;;;;;;;;;;;` ``` ;;;;;`\n'); - response.write(' ;;;;; ;;;;;;;;;, ;;; .;;;;;\n'); - response.write('`;;;;: `;;;;;;;; ;;; ;;;;;\n'); - response.write(',;;;;` `,,,,,,,, ;;;;;;; .,,;;;,,, ;;;;;\n'); - response.write(':;;;;` .;;;;;;;; ;;;;;, :;;;;;;;; ;;;;;\n'); - response.write(':;;;;` .;;;;;;;; `;;;;;; :;;;;;;;; ;;;;;\n'); - response.write('.;;;;. ;;;;;;;. ;;; ;;;;;\n'); - response.write(' ;;;;; ;;;;;;;;; ;;; ;;;;;\n'); - response.write(' ;;;;; .;;;;;;;;;; ;;; ;;;;;,\n'); - response.write(' ;;;;;; `;;;;;;;;;;;; ;;;;; \n'); - response.write(' `;;;;;, .;;;;;; ;;;;;;; ;;;;;; \n'); - response.write(' ;;;;;;: :;;;;;;. ;;;;;;; ;;;;;; \n'); - response.write(' ;;;;;;;` .;;;;;;;, ;;;;;;;; ;;;;;;;: \n'); - response.write(' ;;;;;;;;;:,:;;;;;;;;;: ;;;;;;;;;;:,;;;;;;;;;; \n'); - response.write(' `;;;;;;;;;;;;;;;;;;;. ;;;;;;;;;;;;;;;;;;;; \n'); - response.write(' ;;;;;;;;;;;;;;;;; :;;;;;;;;;;;;;;;;: \n'); - response.write(' ,;;;;;;;;;;;;;, ;;;;;;;;;;;;;; \n'); - response.write(' .;;;;;;;;;` ,;;;;;;;;: \n'); - response.write(' \n'); - response.write(' \n'); - response.write(' \n'); - response.write(' \n'); - response.write(' ;;; ;;;;;` ;;;;: .;; ;; ,;;;;;, ;;. `;, ;;;; \n'); - response.write(' ;;; ;;:;;; ;;;;;; .;; ;; ,;;;;;: ;;; `;, ;;;:;; \n'); - response.write(' ,;:; ;; ;; ;; ;; .;; ;; ,;, ;;;,`;, ;; ;; \n'); - response.write(' ;; ;: ;; ;; ;; ;; .;; ;; ,;, ;;;;`;, ;; ;;. \n'); - response.write(' ;: ;; ;;;;;: ;; ;; .;; ;; ,;, ;;`;;;, ;; ;;` \n'); - response.write(' ,;;;;; ;;`;; ;; ;; .;; ;; ,;, ;; ;;;, ;; ;; \n'); - response.write(' ;; ,;, ;; .;; ;;;;;: ;;;;;: ,;;;;;: ;; ;;, ;;;;;; \n'); - response.write(' ;; ;; ;; ;;` ;;;;. `;;;: ,;;;;;, ;; ;;, ;;;; \n'); - response.write('\n'); - response.end(); -}); - -// this is the POST handler: -app.all('/*', function (request, response) { - console.log('Got a ' + request.method + ' request'); - // the parameters of a GET request are passed in - // request.body. Pass that to formatResponse() - // for formatting: - console.log(request.headers); - if (request.method == 'GET') { - console.log(request.query); - } else { - console.log(request.body); - } - - // send the response: - response.send('OK'); - response.end(); -}); - -// start the server: -var server = app.listen(8080, serverStart); - -// create a WebSocket server and attach it to the server -var wss = new WebSocketServer({server: server}); - -wss.on('connection', function connection(ws) { - // new connection, add message listener - ws.on('message', function incoming(message) { - // received a message - console.log('received: %s', message); - - // echo it back - ws.send(message); - }); -}); diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/node_test_server/package.json b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/node_test_server/package.json deleted file mode 100644 index 09f2d8b..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/examples/node_test_server/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "node_test_server", - "version": "0.0.1", - "author": { - "name": "Tom Igoe" - }, - "dependencies": { - "body-parser": ">=1.11.0", - "express": ">=4.0.0", - "multer": "*", - "ws": "^1.1.1" - } -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/keywords.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/keywords.txt deleted file mode 100644 index 27cd516..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/keywords.txt +++ /dev/null @@ -1,64 +0,0 @@ -####################################### -# Syntax Coloring Map For HttpClient -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -ArduinoHttpClient KEYWORD1 -HttpClient KEYWORD1 -WebSocketClient KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -get KEYWORD2 -post KEYWORD2 -put KEYWORD2 -patch KEYWORD2 -startRequest KEYWORD2 -beginRequest KEYWORD2 -beginBody KEYWORD2 -sendHeader KEYWORD2 -sendBasicAuth KEYWORD2 -endRequest KEYWORD2 -responseStatusCode KEYWORD2 -readHeader KEYWORD2 -skipResponseHeaders KEYWORD2 -endOfHeadersReached KEYWORD2 -endOfBodyReached KEYWORD2 -completed KEYWORD2 -contentLength KEYWORD2 -isResponseChunked KEYWORD2 -connectionKeepAlive KEYWORD2 -noDefaultRequestHeaders KEYWORD2 -headerAvailable KEYWORD2 -readHeaderName KEYWORD2 -readHeaderValue KEYWORD2 -responseBody KEYWORD2 - -beginMessage KEYWORD2 -endMessage KEYWORD2 -parseMessage KEYWORD2 -messageType KEYWORD2 -isFinal KEYWORD2 -readString KEYWORD2 -ping KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### -HTTP_SUCCESS LITERAL1 -HTTP_ERROR_CONNECTION_FAILED LITERAL1 -HTTP_ERROR_API LITERAL1 -HTTP_ERROR_TIMED_OUT LITERAL1 -HTTP_ERROR_INVALID_RESPONSE LITERAL1 - -TYPE_CONTINUATION LITERAL1 -TYPE_TEXT LITERAL1 -TYPE_BINARY LITERAL1 -TYPE_CONNECTION_CLOSE LITERAL1 -TYPE_PING LITERAL1 -TYPE_PONG LITERAL1 diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/library.json b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/library.json deleted file mode 100644 index 6bbda24..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/library.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "ArduinoHttpClient", - "keywords": "http, web, client, ethernet, wifi, GSM", - "description": "Easily interact with web servers from Arduino, using HTTP and WebSocket's.", - "repository": - { - "type": "git", - "url": "https://github.com/arduino-libraries/ArduinoHttpClient.git" - }, - "frameworks": "arduino", - "platforms": "*" -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/library.properties b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/library.properties deleted file mode 100644 index 2ac5bb5..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/library.properties +++ /dev/null @@ -1,10 +0,0 @@ -name=ArduinoHttpClient -version=0.3.1 -author=Arduino -maintainer=Arduino -sentence=[EXPERIMENTAL] Easily interact with web servers from Arduino, using HTTP and WebSocket's. -paragraph=This library can be used for HTTP (GET, POST, PUT, DELETE) requests to a web server. It also supports exchanging messages with WebSocket servers. Based on Adrian McEwen's HttpClient library. -category=Communication -url=https://github.com/arduino-libraries/ArduinoHttpClient -architectures=* -includes=ArduinoHttpClient.h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h deleted file mode 100644 index 578733f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/ArduinoHttpClient.h +++ /dev/null @@ -1,11 +0,0 @@ -// Library to simplify HTTP fetching on Arduino -// (c) Copyright Arduino. 2016 -// Released under Apache License, version 2.0 - -#ifndef ArduinoHttpClient_h -#define ArduinoHttpClient_h - -#include "HttpClient.h" -#include "WebSocketClient.h" - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/HttpClient.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/HttpClient.cpp deleted file mode 100644 index 7517eea..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/HttpClient.cpp +++ /dev/null @@ -1,862 +0,0 @@ -// Class to simplify HTTP fetching on Arduino -// (c) Copyright 2010-2011 MCQN Ltd -// Released under Apache License, version 2.0 - -#include "HttpClient.h" -#include "b64.h" - -// Initialize constants -const char* HttpClient::kUserAgent = "Arduino/2.2.0"; -const char* HttpClient::kContentLengthPrefix = HTTP_HEADER_CONTENT_LENGTH ": "; -const char* HttpClient::kTransferEncodingChunked = HTTP_HEADER_TRANSFER_ENCODING ": " HTTP_HEADER_VALUE_CHUNKED; - -HttpClient::HttpClient(Client& aClient, const char* aServerName, uint16_t aServerPort) - : iClient(&aClient), iServerName(aServerName), iServerAddress(), iServerPort(aServerPort), - iConnectionClose(true), iSendDefaultRequestHeaders(true) -{ - resetState(); -} - -HttpClient::HttpClient(Client& aClient, const String& aServerName, uint16_t aServerPort) - : HttpClient(aClient, aServerName.c_str(), aServerPort) -{ -} - -HttpClient::HttpClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort) - : iClient(&aClient), iServerName(NULL), iServerAddress(aServerAddress), iServerPort(aServerPort), - iConnectionClose(true), iSendDefaultRequestHeaders(true) -{ - resetState(); -} - -void HttpClient::resetState() -{ - iState = eIdle; - iStatusCode = 0; - iContentLength = kNoContentLengthHeader; - iBodyLengthConsumed = 0; - iContentLengthPtr = kContentLengthPrefix; - iTransferEncodingChunkedPtr = kTransferEncodingChunked; - iIsChunked = false; - iChunkLength = 0; - iHttpResponseTimeout = kHttpResponseTimeout; -} - -void HttpClient::stop() -{ - iClient->stop(); - resetState(); -} - -void HttpClient::connectionKeepAlive() -{ - iConnectionClose = false; -} - -void HttpClient::noDefaultRequestHeaders() -{ - iSendDefaultRequestHeaders = false; -} - -void HttpClient::beginRequest() -{ - iState = eRequestStarted; -} - -int HttpClient::startRequest(const char* aURLPath, const char* aHttpMethod, - const char* aContentType, int aContentLength, const byte aBody[]) -{ - if (iState == eReadingBody || iState == eReadingChunkLength || iState == eReadingBodyChunk) - { - flushClientRx(); - - resetState(); - } - - tHttpState initialState = iState; - - if ((eIdle != iState) && (eRequestStarted != iState)) - { - return HTTP_ERROR_API; - } - - if (iConnectionClose || !iClient->connected()) - { - if (iServerName) - { - if (!iClient->connect(iServerName, iServerPort) > 0) - { -#ifdef LOGGING - Serial.println("Connection failed"); -#endif - return HTTP_ERROR_CONNECTION_FAILED; - } - } - else - { - if (!iClient->connect(iServerAddress, iServerPort) > 0) - { -#ifdef LOGGING - Serial.println("Connection failed"); -#endif - return HTTP_ERROR_CONNECTION_FAILED; - } - } - } - else - { -#ifdef LOGGING - Serial.println("Connection already open"); -#endif - } - - // Now we're connected, send the first part of the request - int ret = sendInitialHeaders(aURLPath, aHttpMethod); - - if (HTTP_SUCCESS == ret) - { - if (aContentType) - { - sendHeader(HTTP_HEADER_CONTENT_TYPE, aContentType); - } - - if (aContentLength > 0) - { - sendHeader(HTTP_HEADER_CONTENT_LENGTH, aContentLength); - } - - bool hasBody = (aBody && aContentLength > 0); - - if (initialState == eIdle || hasBody) - { - // This was a simple version of the API, so terminate the headers now - finishHeaders(); - } - // else we'll call it in endRequest or in the first call to print, etc. - - if (hasBody) - { - write(aBody, aContentLength); - } - } - - return ret; -} - -int HttpClient::sendInitialHeaders(const char* aURLPath, const char* aHttpMethod) -{ -#ifdef LOGGING - Serial.println("Connected"); -#endif - // Send the HTTP command, i.e. "GET /somepath/ HTTP/1.0" - iClient->print(aHttpMethod); - iClient->print(" "); - - iClient->print(aURLPath); - iClient->println(" HTTP/1.1"); - if (iSendDefaultRequestHeaders) - { - // The host header, if required - if (iServerName) - { - iClient->print("Host: "); - iClient->print(iServerName); - if (iServerPort != kHttpPort) - { - iClient->print(":"); - iClient->print(iServerPort); - } - iClient->println(); - } - // And user-agent string - sendHeader(HTTP_HEADER_USER_AGENT, kUserAgent); - } - - if (iConnectionClose) - { - // Tell the server to - // close this connection after we're done - sendHeader(HTTP_HEADER_CONNECTION, "close"); - } - - // Everything has gone well - iState = eRequestStarted; - return HTTP_SUCCESS; -} - -void HttpClient::sendHeader(const char* aHeader) -{ - iClient->println(aHeader); -} - -void HttpClient::sendHeader(const char* aHeaderName, const char* aHeaderValue) -{ - iClient->print(aHeaderName); - iClient->print(": "); - iClient->println(aHeaderValue); -} - -void HttpClient::sendHeader(const char* aHeaderName, const int aHeaderValue) -{ - iClient->print(aHeaderName); - iClient->print(": "); - iClient->println(aHeaderValue); -} - -void HttpClient::sendBasicAuth(const char* aUser, const char* aPassword) -{ - // Send the initial part of this header line - iClient->print("Authorization: Basic "); - // Now Base64 encode "aUser:aPassword" and send that - // This seems trickier than it should be but it's mostly to avoid either - // (a) some arbitrarily sized buffer which hopes to be big enough, or - // (b) allocating and freeing memory - // ...so we'll loop through 3 bytes at a time, outputting the results as we - // go. - // In Base64, each 3 bytes of unencoded data become 4 bytes of encoded data - unsigned char input[3]; - unsigned char output[5]; // Leave space for a '\0' terminator so we can easily print - int userLen = strlen(aUser); - int passwordLen = strlen(aPassword); - int inputOffset = 0; - for (int i = 0; i < (userLen+1+passwordLen); i++) - { - // Copy the relevant input byte into the input - if (i < userLen) - { - input[inputOffset++] = aUser[i]; - } - else if (i == userLen) - { - input[inputOffset++] = ':'; - } - else - { - input[inputOffset++] = aPassword[i-(userLen+1)]; - } - // See if we've got a chunk to encode - if ( (inputOffset == 3) || (i == userLen+passwordLen) ) - { - // We've either got to a 3-byte boundary, or we've reached then end - b64_encode(input, inputOffset, output, 4); - // NUL-terminate the output string - output[4] = '\0'; - // And write it out - iClient->print((char*)output); -// FIXME We might want to fill output with '=' characters if b64_encode doesn't -// FIXME do it for us when we're encoding the final chunk - inputOffset = 0; - } - } - // And end the header we've sent - iClient->println(); -} - -void HttpClient::finishHeaders() -{ - iClient->println(); - iState = eRequestSent; -} - -void HttpClient::flushClientRx() -{ - while (iClient->available()) - { - iClient->read(); - } -} - -void HttpClient::endRequest() -{ - beginBody(); -} - -void HttpClient::beginBody() -{ - if (iState < eRequestSent) - { - // We still need to finish off the headers - finishHeaders(); - } - // else the end of headers has already been sent, so nothing to do here -} - -int HttpClient::get(const char* aURLPath) -{ - return startRequest(aURLPath, HTTP_METHOD_GET); -} - -int HttpClient::get(const String& aURLPath) -{ - return get(aURLPath.c_str()); -} - -int HttpClient::post(const char* aURLPath) -{ - return startRequest(aURLPath, HTTP_METHOD_POST); -} - -int HttpClient::post(const String& aURLPath) -{ - return post(aURLPath.c_str()); -} - -int HttpClient::post(const char* aURLPath, const char* aContentType, const char* aBody) -{ - return post(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); -} - -int HttpClient::post(const String& aURLPath, const String& aContentType, const String& aBody) -{ - return post(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); -} - -int HttpClient::post(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) -{ - return startRequest(aURLPath, HTTP_METHOD_POST, aContentType, aContentLength, aBody); -} - -int HttpClient::put(const char* aURLPath) -{ - return startRequest(aURLPath, HTTP_METHOD_PUT); -} - -int HttpClient::put(const String& aURLPath) -{ - return put(aURLPath.c_str()); -} - -int HttpClient::put(const char* aURLPath, const char* aContentType, const char* aBody) -{ - return put(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); -} - -int HttpClient::put(const String& aURLPath, const String& aContentType, const String& aBody) -{ - return put(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); -} - -int HttpClient::put(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) -{ - return startRequest(aURLPath, HTTP_METHOD_PUT, aContentType, aContentLength, aBody); -} - -int HttpClient::patch(const char* aURLPath) -{ - return startRequest(aURLPath, HTTP_METHOD_PATCH); -} - -int HttpClient::patch(const String& aURLPath) -{ - return patch(aURLPath.c_str()); -} - -int HttpClient::patch(const char* aURLPath, const char* aContentType, const char* aBody) -{ - return patch(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); -} - -int HttpClient::patch(const String& aURLPath, const String& aContentType, const String& aBody) -{ - return patch(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); -} - -int HttpClient::patch(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) -{ - return startRequest(aURLPath, HTTP_METHOD_PATCH, aContentType, aContentLength, aBody); -} - -int HttpClient::del(const char* aURLPath) -{ - return startRequest(aURLPath, HTTP_METHOD_DELETE); -} - -int HttpClient::del(const String& aURLPath) -{ - return del(aURLPath.c_str()); -} - -int HttpClient::del(const char* aURLPath, const char* aContentType, const char* aBody) -{ - return del(aURLPath, aContentType, strlen(aBody), (const byte*)aBody); -} - -int HttpClient::del(const String& aURLPath, const String& aContentType, const String& aBody) -{ - return del(aURLPath.c_str(), aContentType.c_str(), aBody.length(), (const byte*)aBody.c_str()); -} - -int HttpClient::del(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]) -{ - return startRequest(aURLPath, HTTP_METHOD_DELETE, aContentType, aContentLength, aBody); -} - -int HttpClient::responseStatusCode() -{ - if (iState < eRequestSent) - { - return HTTP_ERROR_API; - } - // The first line will be of the form Status-Line: - // HTTP-Version SP Status-Code SP Reason-Phrase CRLF - // Where HTTP-Version is of the form: - // HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT - - int c = '\0'; - do - { - // Make sure the status code is reset, and likewise the state. This - // lets us easily cope with 1xx informational responses by just - // ignoring them really, and reading the next line for a proper response - iStatusCode = 0; - iState = eRequestSent; - - unsigned long timeoutStart = millis(); - // Psuedo-regexp we're expecting before the status-code - const char* statusPrefix = "HTTP/*.* "; - const char* statusPtr = statusPrefix; - // Whilst we haven't timed out & haven't reached the end of the headers - while ((c != '\n') && - ( (millis() - timeoutStart) < iHttpResponseTimeout )) - { - if (available()) - { - c = read(); - if (c != -1) - { - switch(iState) - { - case eRequestSent: - // We haven't reached the status code yet - if ( (*statusPtr == '*') || (*statusPtr == c) ) - { - // This character matches, just move along - statusPtr++; - if (*statusPtr == '\0') - { - // We've reached the end of the prefix - iState = eReadingStatusCode; - } - } - else - { - return HTTP_ERROR_INVALID_RESPONSE; - } - break; - case eReadingStatusCode: - if (isdigit(c)) - { - // This assumes we won't get more than the 3 digits we - // want - iStatusCode = iStatusCode*10 + (c - '0'); - } - else - { - // We've reached the end of the status code - // We could sanity check it here or double-check for ' ' - // rather than anything else, but let's be lenient - iState = eStatusCodeRead; - } - break; - case eStatusCodeRead: - // We're just waiting for the end of the line now - break; - - default: - break; - }; - // We read something, reset the timeout counter - timeoutStart = millis(); - } - } - else - { - // We haven't got any data, so let's pause to allow some to - // arrive - delay(kHttpWaitForDataDelay); - } - } - if ( (c == '\n') && (iStatusCode < 200 && iStatusCode != 101) ) - { - // We've reached the end of an informational status line - c = '\0'; // Clear c so we'll go back into the data reading loop - } - } - // If we've read a status code successfully but it's informational (1xx) - // loop back to the start - while ( (iState == eStatusCodeRead) && (iStatusCode < 200 && iStatusCode != 101) ); - - if ( (c == '\n') && (iState == eStatusCodeRead) ) - { - // We've read the status-line successfully - return iStatusCode; - } - else if (c != '\n') - { - // We must've timed out before we reached the end of the line - return HTTP_ERROR_TIMED_OUT; - } - else - { - // This wasn't a properly formed status line, or at least not one we - // could understand - return HTTP_ERROR_INVALID_RESPONSE; - } -} - -int HttpClient::skipResponseHeaders() -{ - // Just keep reading until we finish reading the headers or time out - unsigned long timeoutStart = millis(); - // Whilst we haven't timed out & haven't reached the end of the headers - while ((!endOfHeadersReached()) && - ( (millis() - timeoutStart) < iHttpResponseTimeout )) - { - if (available()) - { - (void)readHeader(); - // We read something, reset the timeout counter - timeoutStart = millis(); - } - else - { - // We haven't got any data, so let's pause to allow some to - // arrive - delay(kHttpWaitForDataDelay); - } - } - if (endOfHeadersReached()) - { - // Success - return HTTP_SUCCESS; - } - else - { - // We must've timed out - return HTTP_ERROR_TIMED_OUT; - } -} - -bool HttpClient::endOfHeadersReached() -{ - return (iState == eReadingBody || iState == eReadingChunkLength || iState == eReadingBodyChunk); -}; - -int HttpClient::contentLength() -{ - // skip the response headers, if they haven't been read already - if (!endOfHeadersReached()) - { - skipResponseHeaders(); - } - - return iContentLength; -} - -String HttpClient::responseBody() -{ - int bodyLength = contentLength(); - String response; - - if (bodyLength > 0) - { - // try to reserve bodyLength bytes - if (response.reserve(bodyLength) == 0) { - // String reserve failed - return String((const char*)NULL); - } - } - - // keep on timedRead'ing, until: - // - we have a content length: body length equals consumed or no bytes - // available - // - no content length: no bytes are available - while (iBodyLengthConsumed != bodyLength) - { - int c = timedRead(); - - if (c == -1) { - // read timed out, done - break; - } - - if (!response.concat((char)c)) { - // adding char failed - return String((const char*)NULL); - } - } - - if (bodyLength > 0 && (unsigned int)bodyLength != response.length()) { - // failure, we did not read in reponse content length bytes - return String((const char*)NULL); - } - - return response; -} - -bool HttpClient::endOfBodyReached() -{ - if (endOfHeadersReached() && (contentLength() != kNoContentLengthHeader)) - { - // We've got to the body and we know how long it will be - return (iBodyLengthConsumed >= contentLength()); - } - return false; -} - -int HttpClient::available() -{ - if (iState == eReadingChunkLength) - { - while (iClient->available()) - { - char c = iClient->read(); - - if (c == '\n') - { - iState = eReadingBodyChunk; - break; - } - else if (c == '\r') - { - // no-op - } - else if (isHexadecimalDigit(c)) - { - char digit[2] = {c, '\0'}; - - iChunkLength = (iChunkLength * 16) + strtol(digit, NULL, 16); - } - } - } - - if (iState == eReadingBodyChunk && iChunkLength == 0) - { - iState = eReadingChunkLength; - } - - if (iState == eReadingChunkLength) - { - return 0; - } - - int clientAvailable = iClient->available(); - - if (iState == eReadingBodyChunk) - { - return min(clientAvailable, iChunkLength); - } - else - { - return clientAvailable; - } -} - - -int HttpClient::read() -{ - if (iIsChunked && !available()) - { - return -1; - } - - int ret = iClient->read(); - if (ret >= 0) - { - if (endOfHeadersReached() && iContentLength > 0) - { - // We're outputting the body now and we've seen a Content-Length header - // So keep track of how many bytes are left - iBodyLengthConsumed++; - } - - if (iState == eReadingBodyChunk) - { - iChunkLength--; - - if (iChunkLength == 0) - { - iState = eReadingChunkLength; - } - } - } - return ret; -} - -bool HttpClient::headerAvailable() -{ - // clear the currently store header line - iHeaderLine = ""; - - while (!endOfHeadersReached()) - { - // read a byte from the header - int c = readHeader(); - - if (c == '\r' || c == '\n') - { - if (iHeaderLine.length()) - { - // end of the line, all done - break; - } - else - { - // ignore any CR or LF characters - continue; - } - } - - // append byte to header line - iHeaderLine += (char)c; - } - - return (iHeaderLine.length() > 0); -} - -String HttpClient::readHeaderName() -{ - int colonIndex = iHeaderLine.indexOf(':'); - - if (colonIndex == -1) - { - return ""; - } - - return iHeaderLine.substring(0, colonIndex); -} - -String HttpClient::readHeaderValue() -{ - int colonIndex = iHeaderLine.indexOf(':'); - int startIndex = colonIndex + 1; - - if (colonIndex == -1) - { - return ""; - } - - // trim any leading whitespace - while (startIndex < (int)iHeaderLine.length() && isSpace(iHeaderLine[startIndex])) - { - startIndex++; - } - - return iHeaderLine.substring(startIndex); -} - -int HttpClient::read(uint8_t *buf, size_t size) -{ - int ret =iClient->read(buf, size); - if (endOfHeadersReached() && iContentLength > 0) - { - // We're outputting the body now and we've seen a Content-Length header - // So keep track of how many bytes are left - if (ret >= 0) - { - iBodyLengthConsumed += ret; - } - } - return ret; -} - -int HttpClient::readHeader() -{ - char c = read(); - - if (endOfHeadersReached()) - { - // We've passed the headers, but rather than return an error, we'll just - // act as a slightly less efficient version of read() - return c; - } - - // Whilst reading out the headers to whoever wants them, we'll keep an - // eye out for the "Content-Length" header - switch(iState) - { - case eStatusCodeRead: - // We're at the start of a line, or somewhere in the middle of reading - // the Content-Length prefix - if (*iContentLengthPtr == c) - { - // This character matches, just move along - iContentLengthPtr++; - if (*iContentLengthPtr == '\0') - { - // We've reached the end of the prefix - iState = eReadingContentLength; - // Just in case we get multiple Content-Length headers, this - // will ensure we just get the value of the last one - iContentLength = 0; - iBodyLengthConsumed = 0; - } - } - else if (*iTransferEncodingChunkedPtr == c) - { - // This character matches, just move along - iTransferEncodingChunkedPtr++; - if (*iTransferEncodingChunkedPtr == '\0') - { - // We've reached the end of the Transfer Encoding: chunked header - iIsChunked = true; - iState = eSkipToEndOfHeader; - } - } - else if (((iContentLengthPtr == kContentLengthPrefix) && (iTransferEncodingChunkedPtr == kTransferEncodingChunked)) && (c == '\r')) - { - // We've found a '\r' at the start of a line, so this is probably - // the end of the headers - iState = eLineStartingCRFound; - } - else - { - // This isn't the Content-Length or Transfer Encoding chunked header, skip to the end of the line - iState = eSkipToEndOfHeader; - } - break; - case eReadingContentLength: - if (isdigit(c)) - { - iContentLength = iContentLength*10 + (c - '0'); - } - else - { - // We've reached the end of the content length - // We could sanity check it here or double-check for "\r\n" - // rather than anything else, but let's be lenient - iState = eSkipToEndOfHeader; - } - break; - case eLineStartingCRFound: - if (c == '\n') - { - if (iIsChunked) - { - iState = eReadingChunkLength; - iChunkLength = 0; - } - else - { - iState = eReadingBody; - } - } - break; - default: - // We're just waiting for the end of the line now - break; - }; - - if ( (c == '\n') && !endOfHeadersReached() ) - { - // We've got to the end of this line, start processing again - iState = eStatusCodeRead; - iContentLengthPtr = kContentLengthPrefix; - iTransferEncodingChunkedPtr = kTransferEncodingChunked; - } - // And return the character read to whoever wants it - return c; -} - - - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/HttpClient.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/HttpClient.h deleted file mode 100644 index c954872..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/HttpClient.h +++ /dev/null @@ -1,392 +0,0 @@ -// Class to simplify HTTP fetching on Arduino -// (c) Copyright MCQN Ltd. 2010-2012 -// Released under Apache License, version 2.0 - -#ifndef HttpClient_h -#define HttpClient_h - -#include -#include -#include "Client.h" - -static const int HTTP_SUCCESS =0; -// The end of the headers has been reached. This consumes the '\n' -// Could not connect to the server -static const int HTTP_ERROR_CONNECTION_FAILED =-1; -// This call was made when the HttpClient class wasn't expecting it -// to be called. Usually indicates your code is using the class -// incorrectly -static const int HTTP_ERROR_API =-2; -// Spent too long waiting for a reply -static const int HTTP_ERROR_TIMED_OUT =-3; -// The response from the server is invalid, is it definitely an HTTP -// server? -static const int HTTP_ERROR_INVALID_RESPONSE =-4; - -// Define some of the common methods and headers here -// That lets other code reuse them without having to declare another copy -// of them, so saves code space and RAM -#define HTTP_METHOD_GET "GET" -#define HTTP_METHOD_POST "POST" -#define HTTP_METHOD_PUT "PUT" -#define HTTP_METHOD_PATCH "PATCH" -#define HTTP_METHOD_DELETE "DELETE" -#define HTTP_HEADER_CONTENT_LENGTH "Content-Length" -#define HTTP_HEADER_CONTENT_TYPE "Content-Type" -#define HTTP_HEADER_CONNECTION "Connection" -#define HTTP_HEADER_TRANSFER_ENCODING "Transfer-Encoding" -#define HTTP_HEADER_USER_AGENT "User-Agent" -#define HTTP_HEADER_VALUE_CHUNKED "chunked" - -class HttpClient : public Client -{ -public: - static const int kNoContentLengthHeader =-1; - static const int kHttpPort =80; - static const char* kUserAgent; - -// FIXME Write longer API request, using port and user-agent, example -// FIXME Update tempToPachube example to calculate Content-Length correctly - - HttpClient(Client& aClient, const char* aServerName, uint16_t aServerPort = kHttpPort); - HttpClient(Client& aClient, const String& aServerName, uint16_t aServerPort = kHttpPort); - HttpClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort = kHttpPort); - - /** Start a more complex request. - Use this when you need to send additional headers in the request, - but you will also need to call endRequest() when you are finished. - */ - void beginRequest(); - - /** End a more complex request. - Use this when you need to have sent additional headers in the request, - but you will also need to call beginRequest() at the start. - */ - void endRequest(); - - /** Start the body of a more complex request. - Use this when you need to send the body after additional headers - in the request, but can optionally call endRequest() when - you are finished. - */ - void beginBody(); - - /** Connect to the server and start to send a GET request. - @param aURLPath Url to request - @return 0 if successful, else error - */ - int get(const char* aURLPath); - int get(const String& aURLPath); - - /** Connect to the server and start to send a POST request. - @param aURLPath Url to request - @return 0 if successful, else error - */ - int post(const char* aURLPath); - int post(const String& aURLPath); - - /** Connect to the server and send a POST request - with body and content type - @param aURLPath Url to request - @param aContentType Content type of request body - @param aBody Body of the request - @return 0 if successful, else error - */ - int post(const char* aURLPath, const char* aContentType, const char* aBody); - int post(const String& aURLPath, const String& aContentType, const String& aBody); - int post(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); - - /** Connect to the server and start to send a PUT request. - @param aURLPath Url to request - @return 0 if successful, else error - */ - int put(const char* aURLPath); - int put(const String& aURLPath); - - /** Connect to the server and send a PUT request - with body and content type - @param aURLPath Url to request - @param aContentType Content type of request body - @param aBody Body of the request - @return 0 if successful, else error - */ - int put(const char* aURLPath, const char* aContentType, const char* aBody); - int put(const String& aURLPath, const String& aContentType, const String& aBody); - int put(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); - - /** Connect to the server and start to send a PATCH request. - @param aURLPath Url to request - @return 0 if successful, else error - */ - int patch(const char* aURLPath); - int patch(const String& aURLPath); - - /** Connect to the server and send a PATCH request - with body and content type - @param aURLPath Url to request - @param aContentType Content type of request body - @param aBody Body of the request - @return 0 if successful, else error - */ - int patch(const char* aURLPath, const char* aContentType, const char* aBody); - int patch(const String& aURLPath, const String& aContentType, const String& aBody); - int patch(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); - - /** Connect to the server and start to send a DELETE request. - @param aURLPath Url to request - @return 0 if successful, else error - */ - int del(const char* aURLPath); - int del(const String& aURLPath); - - /** Connect to the server and send a DELETE request - with body and content type - @param aURLPath Url to request - @param aContentType Content type of request body - @param aBody Body of the request - @return 0 if successful, else error - */ - int del(const char* aURLPath, const char* aContentType, const char* aBody); - int del(const String& aURLPath, const String& aContentType, const String& aBody); - int del(const char* aURLPath, const char* aContentType, int aContentLength, const byte aBody[]); - - /** Connect to the server and start to send the request. - If a body is provided, the entire request (including headers and body) will be sent - @param aURLPath Url to request - @param aHttpMethod Type of HTTP request to make, e.g. "GET", "POST", etc. - @param aContentType Content type of request body (optional) - @param aContentLength Length of request body (optional) - @param aBody Body of request (optional) - @return 0 if successful, else error - */ - int startRequest(const char* aURLPath, - const char* aHttpMethod, - const char* aContentType = NULL, - int aContentLength = -1, - const byte aBody[] = NULL); - - /** Send an additional header line. This can only be called in between the - calls to startRequest and finishRequest. - @param aHeader Header line to send, in its entirety (but without the - trailing CRLF. E.g. "Authorization: Basic YQDDCAIGES" - */ - void sendHeader(const char* aHeader); - - void sendHeader(const String& aHeader) - { sendHeader(aHeader.c_str()); } - - /** Send an additional header line. This is an alternate form of - sendHeader() which takes the header name and content as separate strings. - The call will add the ": " to separate the header, so for example, to - send a XXXXXX header call sendHeader("XXXXX", "Something") - @param aHeaderName Type of header being sent - @param aHeaderValue Value for that header - */ - void sendHeader(const char* aHeaderName, const char* aHeaderValue); - - void sendHeader(const String& aHeaderName, const String& aHeaderValue) - { sendHeader(aHeaderName.c_str(), aHeaderValue.c_str()); } - - /** Send an additional header line. This is an alternate form of - sendHeader() which takes the header name and content separately but where - the value is provided as an integer. - The call will add the ": " to separate the header, so for example, to - send a XXXXXX header call sendHeader("XXXXX", 123) - @param aHeaderName Type of header being sent - @param aHeaderValue Value for that header - */ - void sendHeader(const char* aHeaderName, const int aHeaderValue); - - void sendHeader(const String& aHeaderName, const int aHeaderValue) - { sendHeader(aHeaderName.c_str(), aHeaderValue); } - - /** Send a basic authentication header. This will encode the given username - and password, and send them in suitable header line for doing Basic - Authentication. - @param aUser Username for the authorization - @param aPassword Password for the user aUser - */ - void sendBasicAuth(const char* aUser, const char* aPassword); - - void sendBasicAuth(const String& aUser, const String& aPassword) - { sendBasicAuth(aUser.c_str(), aPassword.c_str()); } - - /** Get the HTTP status code contained in the response. - For example, 200 for successful request, 404 for file not found, etc. - */ - int responseStatusCode(); - - /** Check if a header is available to be read. - Use readHeaderName() to read header name, and readHeaderValue() to - read the header value - MUST be called after responseStatusCode() and before contentLength() - */ - bool headerAvailable(); - - /** Read the name of the current response header. - Returns empty string if a header is not available. - */ - String readHeaderName(); - - /** Read the vallue of the current response header. - Returns empty string if a header is not available. - */ - String readHeaderValue(); - - /** Read the next character of the response headers. - This functions in the same way as read() but to be used when reading - through the headers. Check whether or not the end of the headers has - been reached by calling endOfHeadersReached(), although after that point - this will still return data as read() would, but slightly less efficiently - MUST be called after responseStatusCode() and before contentLength() - @return The next character of the response headers - */ - int readHeader(); - - /** Skip any response headers to get to the body. - Use this if you don't want to do any special processing of the headers - returned in the response. You can also use it after you've found all of - the headers you're interested in, and just want to get on with processing - the body. - MUST be called after responseStatusCode() - @return HTTP_SUCCESS if successful, else an error code - */ - int skipResponseHeaders(); - - /** Test whether all of the response headers have been consumed. - @return true if we are now processing the response body, else false - */ - bool endOfHeadersReached(); - - /** Test whether the end of the body has been reached. - Only works if the Content-Length header was returned by the server - @return true if we are now at the end of the body, else false - */ - bool endOfBodyReached(); - virtual bool endOfStream() { return endOfBodyReached(); }; - virtual bool completed() { return endOfBodyReached(); }; - - /** Return the length of the body. - Also skips response headers if they have not been read already - MUST be called after responseStatusCode() - @return Length of the body, in bytes, or kNoContentLengthHeader if no - Content-Length header was returned by the server - */ - int contentLength(); - - /** Returns if the response body is chunked - @return true if response body is chunked, false otherwise - */ - int isResponseChunked() { return iIsChunked; } - - /** Return the response body as a String - Also skips response headers if they have not been read already - MUST be called after responseStatusCode() - @return response body of request as a String - */ - String responseBody(); - - /** Enables connection keep-alive mode - */ - void connectionKeepAlive(); - - /** Disables sending the default request headers (Host and User Agent) - */ - void noDefaultRequestHeaders(); - - // Inherited from Print - // Note: 1st call to these indicates the user is sending the body, so if need - // Note: be we should finish the header first - virtual size_t write(uint8_t aByte) { if (iState < eRequestSent) { finishHeaders(); }; return iClient-> write(aByte); }; - virtual size_t write(const uint8_t *aBuffer, size_t aSize) { if (iState < eRequestSent) { finishHeaders(); }; return iClient->write(aBuffer, aSize); }; - // Inherited from Stream - virtual int available(); - /** Read the next byte from the server. - @return Byte read or -1 if there are no bytes available. - */ - virtual int read(); - virtual int read(uint8_t *buf, size_t size); - virtual int peek() { return iClient->peek(); }; - virtual void flush() { return iClient->flush(); }; - - // Inherited from Client - virtual int connect(IPAddress ip, uint16_t port) { return iClient->connect(ip, port); }; - virtual int connect(const char *host, uint16_t port) { return iClient->connect(host, port); }; - virtual void stop(); - virtual uint8_t connected() { return iClient->connected(); }; - virtual operator bool() { return bool(iClient); }; - virtual uint32_t httpResponseTimeout() { return iHttpResponseTimeout; }; - virtual void setHttpResponseTimeout(uint32_t timeout) { iHttpResponseTimeout = timeout; }; -protected: - /** Reset internal state data back to the "just initialised" state - */ - void resetState(); - - /** Send the first part of the request and the initial headers. - @param aURLPath Url to request - @param aHttpMethod Type of HTTP request to make, e.g. "GET", "POST", etc. - @return 0 if successful, else error - */ - int sendInitialHeaders(const char* aURLPath, - const char* aHttpMethod); - - /* Let the server know that we've reached the end of the headers - */ - void finishHeaders(); - - /** Reading any pending data from the client (used in connection keep alive mode) - */ - void flushClientRx(); - - // Number of milliseconds that we wait each time there isn't any data - // available to be read (during status code and header processing) - static const int kHttpWaitForDataDelay = 1000; - // Number of milliseconds that we'll wait in total without receiveing any - // data before returning HTTP_ERROR_TIMED_OUT (during status code and header - // processing) - static const int kHttpResponseTimeout = 30*1000; - static const char* kContentLengthPrefix; - static const char* kTransferEncodingChunked; - typedef enum { - eIdle, - eRequestStarted, - eRequestSent, - eReadingStatusCode, - eStatusCodeRead, - eReadingContentLength, - eSkipToEndOfHeader, - eLineStartingCRFound, - eReadingBody, - eReadingChunkLength, - eReadingBodyChunk - } tHttpState; - // Client we're using - Client* iClient; - // Server we are connecting to - const char* iServerName; - IPAddress iServerAddress; - // Port of server we are connecting to - uint16_t iServerPort; - // Current state of the finite-state-machine - tHttpState iState; - // Stores the status code for the response, once known - int iStatusCode; - // Stores the value of the Content-Length header, if present - int iContentLength; - // How many bytes of the response body have been read by the user - int iBodyLengthConsumed; - // How far through a Content-Length header prefix we are - const char* iContentLengthPtr; - // How far through a Transfer-Encoding chunked header we are - const char* iTransferEncodingChunkedPtr; - // Stores if the response body is chunked - bool iIsChunked; - // Stores the value of the current chunk length, if present - int iChunkLength; - uint32_t iHttpResponseTimeout; - bool iConnectionClose; - bool iSendDefaultRequestHeaders; - String iHeaderLine; -}; - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/WebSocketClient.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/WebSocketClient.cpp deleted file mode 100644 index ab41b0a..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/WebSocketClient.cpp +++ /dev/null @@ -1,372 +0,0 @@ -// (c) Copyright Arduino. 2016 -// Released under Apache License, version 2.0 - -#include "b64.h" - -#include "WebSocketClient.h" - -WebSocketClient::WebSocketClient(Client& aClient, const char* aServerName, uint16_t aServerPort) - : HttpClient(aClient, aServerName, aServerPort), - iTxStarted(false), - iRxSize(0) -{ -} - -WebSocketClient::WebSocketClient(Client& aClient, const String& aServerName, uint16_t aServerPort) - : HttpClient(aClient, aServerName, aServerPort), - iTxStarted(false), - iRxSize(0) -{ -} - -WebSocketClient::WebSocketClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort) - : HttpClient(aClient, aServerAddress, aServerPort), - iTxStarted(false), - iRxSize(0) -{ -} - -int WebSocketClient::begin(const char* aPath) -{ - // start the GET request - beginRequest(); - connectionKeepAlive(); - int status = get(aPath); - - if (status == 0) - { - uint8_t randomKey[16]; - char base64RandomKey[25]; - - // create a random key for the connection upgrade - for (int i = 0; i < (int)sizeof(randomKey); i++) - { - randomKey[i] = random(0x01, 0xff); - } - memset(base64RandomKey, 0x00, sizeof(base64RandomKey)); - b64_encode(randomKey, sizeof(randomKey), (unsigned char*)base64RandomKey, sizeof(base64RandomKey)); - - // start the connection upgrade sequence - sendHeader("Upgrade", "websocket"); - sendHeader("Connection", "Upgrade"); - sendHeader("Sec-WebSocket-Key", base64RandomKey); - sendHeader("Sec-WebSocket-Version", "13"); - endRequest(); - - status = responseStatusCode(); - - if (status > 0) - { - skipResponseHeaders(); - } - } - - iRxSize = 0; - - // status code of 101 means success - return (status == 101) ? 0 : status; -} - -int WebSocketClient::begin(const String& aPath) -{ - return begin(aPath.c_str()); -} - -int WebSocketClient::beginMessage(int aType) -{ - if (iTxStarted) - { - // fail TX already started - return 1; - } - - iTxStarted = true; - iTxMessageType = (aType & 0xf); - iTxSize = 0; - - return 0; -} - -int WebSocketClient::endMessage() -{ - if (!iTxStarted) - { - // fail TX not started - return 1; - } - - // send FIN + the message type (opcode) - HttpClient::write(0x80 | iTxMessageType); - - // the message is masked (0x80) - // send the length - if (iTxSize < 126) - { - HttpClient::write(0x80 | (uint8_t)iTxSize); - } - else if (iTxSize < 0xffff) - { - HttpClient::write(0x80 | 126); - HttpClient::write((iTxSize >> 8) & 0xff); - HttpClient::write((iTxSize >> 0) & 0xff); - } - else - { - HttpClient::write(0x80 | 127); - HttpClient::write((iTxSize >> 56) & 0xff); - HttpClient::write((iTxSize >> 48) & 0xff); - HttpClient::write((iTxSize >> 40) & 0xff); - HttpClient::write((iTxSize >> 32) & 0xff); - HttpClient::write((iTxSize >> 24) & 0xff); - HttpClient::write((iTxSize >> 16) & 0xff); - HttpClient::write((iTxSize >> 8) & 0xff); - HttpClient::write((iTxSize >> 0) & 0xff); - } - - uint8_t maskKey[4]; - - // create a random mask for the data and send - for (int i = 0; i < (int)sizeof(maskKey); i++) - { - maskKey[i] = random(0xff); - } - HttpClient::write(maskKey, sizeof(maskKey)); - - // mask the data and send - for (int i = 0; i < (int)iTxSize; i++) { - iTxBuffer[i] ^= maskKey[i % sizeof(maskKey)]; - } - - size_t txSize = iTxSize; - - iTxStarted = false; - iTxSize = 0; - - return (HttpClient::write(iTxBuffer, txSize) == txSize) ? 0 : 1; -} - -size_t WebSocketClient::write(uint8_t aByte) -{ - return write(&aByte, sizeof(aByte)); -} - -size_t WebSocketClient::write(const uint8_t *aBuffer, size_t aSize) -{ - if (iState < eReadingBody) - { - // have not upgraded the connection yet - return HttpClient::write(aBuffer, aSize); - } - - if (!iTxStarted) - { - // fail TX not started - return 0; - } - - // check if the write size, fits in the buffer - if ((iTxSize + aSize) > sizeof(iTxBuffer)) - { - aSize = sizeof(iTxSize) - iTxSize; - } - - // copy data into the buffer - memcpy(iTxBuffer + iTxSize, aBuffer, aSize); - - iTxSize += aSize; - - return aSize; -} - -int WebSocketClient::parseMessage() -{ - flushRx(); - - // make sure 2 bytes (opcode + length) - // are available - if (HttpClient::available() < 2) - { - return 0; - } - - // read open code and length - uint8_t opcode = HttpClient::read(); - int length = HttpClient::read(); - - if ((opcode & 0x0f) == 0) - { - // continuation, use previous opcode and update flags - iRxOpCode |= opcode; - } - else - { - iRxOpCode = opcode; - } - - iRxMasked = (length & 0x80); - length &= 0x7f; - - // read the RX size - if (length < 126) - { - iRxSize = length; - } - else if (length == 126) - { - iRxSize = (HttpClient::read() << 8) | HttpClient::read(); - } - else - { - iRxSize = ((uint64_t)HttpClient::read() << 56) | - ((uint64_t)HttpClient::read() << 48) | - ((uint64_t)HttpClient::read() << 40) | - ((uint64_t)HttpClient::read() << 32) | - ((uint64_t)HttpClient::read() << 24) | - ((uint64_t)HttpClient::read() << 16) | - ((uint64_t)HttpClient::read() << 8) | - (uint64_t)HttpClient::read(); - } - - // read in the mask, if present - if (iRxMasked) - { - for (int i = 0; i < (int)sizeof(iRxMaskKey); i++) - { - iRxMaskKey[i] = HttpClient::read(); - } - } - - iRxMaskIndex = 0; - - if (TYPE_CONNECTION_CLOSE == messageType()) - { - flushRx(); - stop(); - iRxSize = 0; - } - else if (TYPE_PING == messageType()) - { - beginMessage(TYPE_PONG); - while(available()) - { - write(read()); - } - endMessage(); - - iRxSize = 0; - } - else if (TYPE_PONG == messageType()) - { - flushRx(); - iRxSize = 0; - } - - return iRxSize; -} - -int WebSocketClient::messageType() -{ - return (iRxOpCode & 0x0f); -} - -bool WebSocketClient::isFinal() -{ - return ((iRxOpCode & 0x80) != 0); -} - -String WebSocketClient::readString() -{ - int avail = available(); - String s; - - if (avail > 0) - { - s.reserve(avail); - - for (int i = 0; i < avail; i++) - { - s += (char)read(); - } - } - - return s; -} - -int WebSocketClient::ping() -{ - uint8_t pingData[16]; - - // create random data for the ping - for (int i = 0; i < (int)sizeof(pingData); i++) - { - pingData[i] = random(0xff); - } - - beginMessage(TYPE_PING); - write(pingData, sizeof(pingData)); - return endMessage(); -} - -int WebSocketClient::available() -{ - if (iState < eReadingBody) - { - return HttpClient::available(); - } - - return iRxSize; -} - -int WebSocketClient::read() -{ - byte b; - - if (read(&b, sizeof(b))) - { - return b; - } - - return -1; -} - -int WebSocketClient::read(uint8_t *aBuffer, size_t aSize) -{ - int readCount = HttpClient::read(aBuffer, aSize); - - if (readCount > 0) - { - iRxSize -= readCount; - - // unmask the RX data if needed - if (iRxMasked) - { - for (int i = 0; i < (int)aSize; i++, iRxMaskIndex++) - { - aBuffer[i] ^= iRxMaskKey[iRxMaskIndex % sizeof(iRxMaskKey)]; - } - } - } - - return readCount; -} - -int WebSocketClient::peek() -{ - int p = HttpClient::peek(); - - if (p != -1 && iRxMasked) - { - // unmask the RX data if needed - p = (uint8_t)p ^ iRxMaskKey[iRxMaskIndex % sizeof(iRxMaskKey)]; - } - - return p; -} - -void WebSocketClient::flushRx() -{ - while(available()) - { - read(); - } -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/WebSocketClient.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/WebSocketClient.h deleted file mode 100644 index 4b009e6..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/WebSocketClient.h +++ /dev/null @@ -1,99 +0,0 @@ -// (c) Copyright Arduino. 2016 -// Released under Apache License, version 2.0 - -#ifndef WebSocketClient_h -#define WebSocketClient_h - -#include - -#include "HttpClient.h" - -static const int TYPE_CONTINUATION = 0x0; -static const int TYPE_TEXT = 0x1; -static const int TYPE_BINARY = 0x2; -static const int TYPE_CONNECTION_CLOSE = 0x8; -static const int TYPE_PING = 0x9; -static const int TYPE_PONG = 0xa; - -class WebSocketClient : public HttpClient -{ -public: - WebSocketClient(Client& aClient, const char* aServerName, uint16_t aServerPort = HttpClient::kHttpPort); - WebSocketClient(Client& aClient, const String& aServerName, uint16_t aServerPort = HttpClient::kHttpPort); - WebSocketClient(Client& aClient, const IPAddress& aServerAddress, uint16_t aServerPort = HttpClient::kHttpPort); - - /** Start the Web Socket connection to the specified path - @param aURLPath Path to use in request (optional, "/" is used by default) - @return 0 if successful, else error - */ - int begin(const char* aPath = "/"); - int begin(const String& aPath); - - /** Begin to send a message of type (TYPE_TEXT or TYPE_BINARY) - Use the write or Stream API's to set message content, followed by endMessage - to complete the message. - @param aURLPath Path to use in request - @return 0 if successful, else error - */ - int beginMessage(int aType); - - /** Completes sending of a message started by beginMessage - @return 0 if successful, else error - */ - int endMessage(); - - /** Try to parse an incoming messages - @return 0 if no message available, else size of parsed message - */ - int parseMessage(); - - /** Returns type of current parsed message - @return type of current parsedMessage (TYPE_TEXT or TYPE_BINARY) - */ - int messageType(); - - /** Returns if the current message is the final chunk of a split - message - @return true for final message, false otherwise - */ - bool isFinal(); - - /** Read the current messages as a string - @return current message as a string - */ - String readString(); - - /** Send a ping - @return 0 if successful, else error - */ - int ping(); - - // Inherited from Print - virtual size_t write(uint8_t aByte); - virtual size_t write(const uint8_t *aBuffer, size_t aSize); - // Inherited from Stream - virtual int available(); - /** Read the next byte from the server. - @return Byte read or -1 if there are no bytes available. - */ - virtual int read(); - virtual int read(uint8_t *buf, size_t size); - virtual int peek(); - -private: - void flushRx(); - -private: - bool iTxStarted; - uint8_t iTxMessageType; - uint8_t iTxBuffer[128]; - uint64_t iTxSize; - - uint8_t iRxOpCode; - uint64_t iRxSize; - bool iRxMasked; - int iRxMaskIndex; - uint8_t iRxMaskKey[4]; -}; - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/b64.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/b64.cpp deleted file mode 100644 index 683d60a..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/b64.cpp +++ /dev/null @@ -1,72 +0,0 @@ -// Simple Base64 code -// (c) Copyright 2010 MCQN Ltd. -// Released under Apache License, version 2.0 - -#include "b64.h" - -/* Simple test program -#include -void main() -{ - char* in = "amcewen"; - char out[22]; - - b64_encode(in, 15, out, 22); - out[21] = '\0'; - - printf(out); -} -*/ - -int b64_encode(const unsigned char* aInput, int aInputLen, unsigned char* aOutput, int aOutputLen) -{ - // Work out if we've got enough space to encode the input - // Every 6 bits of input becomes a byte of output - if (aOutputLen < (aInputLen*8)/6) - { - // FIXME Should we return an error here, or just the length - return (aInputLen*8)/6; - } - - // If we get here we've got enough space to do the encoding - - const char* b64_dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - if (aInputLen == 3) - { - aOutput[0] = b64_dictionary[aInput[0] >> 2]; - aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4|(aInput[1]>>4)]; - aOutput[2] = b64_dictionary[(aInput[1]&0x0F)<<2|(aInput[2]>>6)]; - aOutput[3] = b64_dictionary[aInput[2]&0x3F]; - } - else if (aInputLen == 2) - { - aOutput[0] = b64_dictionary[aInput[0] >> 2]; - aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4|(aInput[1]>>4)]; - aOutput[2] = b64_dictionary[(aInput[1]&0x0F)<<2]; - aOutput[3] = '='; - } - else if (aInputLen == 1) - { - aOutput[0] = b64_dictionary[aInput[0] >> 2]; - aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4]; - aOutput[2] = '='; - aOutput[3] = '='; - } - else - { - // Break the input into 3-byte chunks and process each of them - int i; - for (i = 0; i < aInputLen/3; i++) - { - b64_encode(&aInput[i*3], 3, &aOutput[i*4], 4); - } - if (aInputLen % 3 > 0) - { - // It doesn't fit neatly into a 3-byte chunk, so process what's left - b64_encode(&aInput[i*3], aInputLen % 3, &aOutput[i*4], aOutputLen - (i*4)); - } - } - - return ((aInputLen+2)/3)*4; -} - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/b64.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/b64.h deleted file mode 100644 index cdb1226..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/ArduinoHttpClient/src/b64.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef b64_h -#define b64_h - -int b64_encode(const unsigned char* aInput, int aInputLen, unsigned char* aOutput, int aOutputLen); - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/.github/ISSUE_TEMPLATE.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index f0e2614..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/.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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 7b641eb..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/.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/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/README.md b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/README.md deleted file mode 100644 index 661e18d..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/README.md +++ /dev/null @@ -1,42 +0,0 @@ -This is a fork of JeeLab's fantastic real time clock library for Arduino. - -For details on using this library with an RTC module like the DS1307, PCF8523, or DS3231, see the guide at: https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/overview - -To download. click the DOWNLOADS button to the right, and rename the uncompressed folder RTClib. - -Place the RTClib folder in your *arduinosketchfolder*/libraries/ folder. -You may need to create the libraries subfolder if its your first library. Restart the IDE. - -Please note that dayOfTheWeek() ranges from 0 to 6 inclusive with 0 being 'Sunday' - - - -## Compatibility - -MCU | Tested Works | Doesn't Work | Not Tested | Notes ------------------- | :----------: | :----------: | :---------: | ----- -Atmega328 @ 16MHz | X | | | -Atmega328 @ 12MHz | X | | | -Atmega32u4 @ 16MHz | X | | | Use SDA/SCL on pins D3 & D2 -Atmega32u4 @ 8MHz | X | | | Use SDA/SCL on pins D3 & D2 -ESP8266 | X | | | SDA/SCL default to pins 4 & 5 but any two pins can be assigned as SDA/SCL using Wire.begin(SDA,SCL) -Atmega2560 @ 16MHz | X | | | Use SDA/SCL on Pins 20 & 21 -ATSAM3X8E | X | | | Use SDA1 and SCL1 -ATSAM21D | X | | | -ATtiny85 @ 16MHz | X | | | -ATtiny85 @ 8MHz | X | | | -Intel Curie @ 32MHz | | | X | -STM32F2 | | | X | - - * ATmega328 @ 16MHz : Arduino UNO, Adafruit Pro Trinket 5V, Adafruit Metro 328, Adafruit Metro Mini - * ATmega328 @ 12MHz : Adafruit Pro Trinket 3V - * ATmega32u4 @ 16MHz : Arduino Leonardo, Arduino Micro, Arduino Yun, Teensy 2.0 - * ATmega32u4 @ 8MHz : Adafruit Flora, Bluefruit Micro - * ESP8266 : Adafruit Huzzah - * ATmega2560 @ 16MHz : Arduino Mega - * ATSAM3X8E : Arduino Due - * ATSAM21D : Arduino Zero, M0 Pro - * ATtiny85 @ 16MHz : Adafruit Trinket 5V - * ATtiny85 @ 8MHz : Adafruit Gemma, Arduino Gemma, Adafruit Trinket 3V - - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/RTClib.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/RTClib.cpp deleted file mode 100644 index a08dfe9..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/RTClib.cpp +++ /dev/null @@ -1,506 +0,0 @@ -// Code by JeeLabs http://news.jeelabs.org/code/ -// Released to the public domain! Enjoy! - -#include -#include "RTClib.h" -#ifdef __AVR__ - #include -#elif defined(ESP8266) - #include -#elif defined(ARDUINO_ARCH_SAMD) -// nothing special needed -#elif defined(ARDUINO_SAM_DUE) - #define PROGMEM - #define pgm_read_byte(addr) (*(const unsigned char *)(addr)) - #define Wire Wire1 -#endif - - - -#if (ARDUINO >= 100) - #include // capital A so it is error prone on case-sensitive filesystems - // Macro to deal with the difference in I2C write functions from old and new Arduino versions. - #define _I2C_WRITE write - #define _I2C_READ read -#else - #include - #define _I2C_WRITE send - #define _I2C_READ receive -#endif - - -static uint8_t read_i2c_register(uint8_t addr, uint8_t reg) { - Wire.beginTransmission(addr); - Wire._I2C_WRITE((byte)reg); - Wire.endTransmission(); - - Wire.requestFrom(addr, (byte)1); - return Wire._I2C_READ(); -} - -static void write_i2c_register(uint8_t addr, uint8_t reg, uint8_t val) { - Wire.beginTransmission(addr); - Wire._I2C_WRITE((byte)reg); - Wire._I2C_WRITE((byte)val); - Wire.endTransmission(); -} - - -//////////////////////////////////////////////////////////////////////////////// -// utility code, some of this could be exposed in the DateTime API if needed - -const uint8_t daysInMonth [] PROGMEM = { 31,28,31,30,31,30,31,31,30,31,30,31 }; - -// number of days since 2000/01/01, valid for 2001..2099 -static uint16_t date2days(uint16_t y, uint8_t m, uint8_t d) { - if (y >= 2000) - y -= 2000; - uint16_t days = d; - for (uint8_t i = 1; i < m; ++i) - days += pgm_read_byte(daysInMonth + i - 1); - if (m > 2 && y % 4 == 0) - ++days; - return days + 365 * y + (y + 3) / 4 - 1; -} - -static long time2long(uint16_t days, uint8_t h, uint8_t m, uint8_t s) { - return ((days * 24L + h) * 60 + m) * 60 + s; -} - -//////////////////////////////////////////////////////////////////////////////// -// DateTime implementation - ignores time zones and DST changes -// NOTE: also ignores leap seconds, see http://en.wikipedia.org/wiki/Leap_second - -DateTime::DateTime (uint32_t t) { - t -= SECONDS_FROM_1970_TO_2000; // bring to 2000 timestamp from 1970 - - ss = t % 60; - t /= 60; - mm = t % 60; - t /= 60; - hh = t % 24; - uint16_t days = t / 24; - uint8_t leap; - for (yOff = 0; ; ++yOff) { - leap = yOff % 4 == 0; - if (days < 365 + leap) - break; - days -= 365 + leap; - } - for (m = 1; ; ++m) { - uint8_t daysPerMonth = pgm_read_byte(daysInMonth + m - 1); - if (leap && m == 2) - ++daysPerMonth; - if (days < daysPerMonth) - break; - days -= daysPerMonth; - } - d = days + 1; -} - -DateTime::DateTime (uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t min, uint8_t sec) { - if (year >= 2000) - year -= 2000; - yOff = year; - m = month; - d = day; - hh = hour; - mm = min; - ss = sec; -} - -DateTime::DateTime (const DateTime& copy): - yOff(copy.yOff), - m(copy.m), - d(copy.d), - hh(copy.hh), - mm(copy.mm), - ss(copy.ss) -{} - -static uint8_t conv2d(const char* p) { - uint8_t v = 0; - if ('0' <= *p && *p <= '9') - v = *p - '0'; - return 10 * v + *++p - '0'; -} - -// A convenient constructor for using "the compiler's time": -// DateTime now (__DATE__, __TIME__); -// NOTE: using F() would further reduce the RAM footprint, see below. -DateTime::DateTime (const char* date, const char* time) { - // sample input: date = "Dec 26 2009", time = "12:34:56" - yOff = conv2d(date + 9); - // Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec - switch (date[0]) { - case 'J': m = (date[1] == 'a') ? 1 : ((date[2] == 'n') ? 6 : 7); break; - case 'F': m = 2; break; - case 'A': m = date[2] == 'r' ? 4 : 8; break; - case 'M': m = date[2] == 'r' ? 3 : 5; break; - case 'S': m = 9; break; - case 'O': m = 10; break; - case 'N': m = 11; break; - case 'D': m = 12; break; - } - d = conv2d(date + 4); - hh = conv2d(time); - mm = conv2d(time + 3); - ss = conv2d(time + 6); -} - -// A convenient constructor for using "the compiler's time": -// This version will save RAM by using PROGMEM to store it by using the F macro. -// DateTime now (F(__DATE__), F(__TIME__)); -DateTime::DateTime (const __FlashStringHelper* date, const __FlashStringHelper* time) { - // sample input: date = "Dec 26 2009", time = "12:34:56" - char buff[11]; - memcpy_P(buff, date, 11); - yOff = conv2d(buff + 9); - // Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec - switch (buff[0]) { - case 'J': m = (buff[1] == 'a') ? 1 : ((buff[2] == 'n') ? 6 : 7); break; - case 'F': m = 2; break; - case 'A': m = buff[2] == 'r' ? 4 : 8; break; - case 'M': m = buff[2] == 'r' ? 3 : 5; break; - case 'S': m = 9; break; - case 'O': m = 10; break; - case 'N': m = 11; break; - case 'D': m = 12; break; - } - d = conv2d(buff + 4); - memcpy_P(buff, time, 8); - hh = conv2d(buff); - mm = conv2d(buff + 3); - ss = conv2d(buff + 6); -} - -uint8_t DateTime::dayOfTheWeek() const { - uint16_t day = date2days(yOff, m, d); - return (day + 6) % 7; // Jan 1, 2000 is a Saturday, i.e. returns 6 -} - -uint32_t DateTime::unixtime(void) const { - uint32_t t; - uint16_t days = date2days(yOff, m, d); - t = time2long(days, hh, mm, ss); - t += SECONDS_FROM_1970_TO_2000; // seconds from 1970 to 2000 - - return t; -} - -long DateTime::secondstime(void) const { - long t; - uint16_t days = date2days(yOff, m, d); - t = time2long(days, hh, mm, ss); - return t; -} - -DateTime DateTime::operator+(const TimeSpan& span) { - return DateTime(unixtime()+span.totalseconds()); -} - -DateTime DateTime::operator-(const TimeSpan& span) { - return DateTime(unixtime()-span.totalseconds()); -} - -TimeSpan DateTime::operator-(const DateTime& right) { - return TimeSpan(unixtime()-right.unixtime()); -} - -//////////////////////////////////////////////////////////////////////////////// -// TimeSpan implementation - -TimeSpan::TimeSpan (int32_t seconds): - _seconds(seconds) -{} - -TimeSpan::TimeSpan (int16_t days, int8_t hours, int8_t minutes, int8_t seconds): - _seconds((int32_t)days*86400L + (int32_t)hours*3600 + (int32_t)minutes*60 + seconds) -{} - -TimeSpan::TimeSpan (const TimeSpan& copy): - _seconds(copy._seconds) -{} - -TimeSpan TimeSpan::operator+(const TimeSpan& right) { - return TimeSpan(_seconds+right._seconds); -} - -TimeSpan TimeSpan::operator-(const TimeSpan& right) { - return TimeSpan(_seconds-right._seconds); -} - -//////////////////////////////////////////////////////////////////////////////// -// RTC_DS1307 implementation - -static uint8_t bcd2bin (uint8_t val) { return val - 6 * (val >> 4); } -static uint8_t bin2bcd (uint8_t val) { return val + 6 * (val / 10); } - -boolean RTC_DS1307::begin(void) { - Wire.begin(); - return true; -} - -uint8_t RTC_DS1307::isrunning(void) { - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE((byte)0); - Wire.endTransmission(); - - Wire.requestFrom(DS1307_ADDRESS, 1); - uint8_t ss = Wire._I2C_READ(); - return !(ss>>7); -} - -void RTC_DS1307::adjust(const DateTime& dt) { - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE((byte)0); // start at location 0 - Wire._I2C_WRITE(bin2bcd(dt.second())); - Wire._I2C_WRITE(bin2bcd(dt.minute())); - Wire._I2C_WRITE(bin2bcd(dt.hour())); - Wire._I2C_WRITE(bin2bcd(0)); - Wire._I2C_WRITE(bin2bcd(dt.day())); - Wire._I2C_WRITE(bin2bcd(dt.month())); - Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); - Wire.endTransmission(); -} - -DateTime RTC_DS1307::now() { - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE((byte)0); - Wire.endTransmission(); - - Wire.requestFrom(DS1307_ADDRESS, 7); - uint8_t ss = bcd2bin(Wire._I2C_READ() & 0x7F); - uint8_t mm = bcd2bin(Wire._I2C_READ()); - uint8_t hh = bcd2bin(Wire._I2C_READ()); - Wire._I2C_READ(); - uint8_t d = bcd2bin(Wire._I2C_READ()); - uint8_t m = bcd2bin(Wire._I2C_READ()); - uint16_t y = bcd2bin(Wire._I2C_READ()) + 2000; - - return DateTime (y, m, d, hh, mm, ss); -} - -Ds1307SqwPinMode RTC_DS1307::readSqwPinMode() { - int mode; - - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE(DS1307_CONTROL); - Wire.endTransmission(); - - Wire.requestFrom((uint8_t)DS1307_ADDRESS, (uint8_t)1); - mode = Wire._I2C_READ(); - - mode &= 0x93; - return static_cast(mode); -} - -void RTC_DS1307::writeSqwPinMode(Ds1307SqwPinMode mode) { - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE(DS1307_CONTROL); - Wire._I2C_WRITE(mode); - Wire.endTransmission(); -} - -void RTC_DS1307::readnvram(uint8_t* buf, uint8_t size, uint8_t address) { - int addrByte = DS1307_NVRAM + address; - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE(addrByte); - Wire.endTransmission(); - - Wire.requestFrom((uint8_t) DS1307_ADDRESS, size); - for (uint8_t pos = 0; pos < size; ++pos) { - buf[pos] = Wire._I2C_READ(); - } -} - -void RTC_DS1307::writenvram(uint8_t address, uint8_t* buf, uint8_t size) { - int addrByte = DS1307_NVRAM + address; - Wire.beginTransmission(DS1307_ADDRESS); - Wire._I2C_WRITE(addrByte); - for (uint8_t pos = 0; pos < size; ++pos) { - Wire._I2C_WRITE(buf[pos]); - } - Wire.endTransmission(); -} - -uint8_t RTC_DS1307::readnvram(uint8_t address) { - uint8_t data; - readnvram(&data, 1, address); - return data; -} - -void RTC_DS1307::writenvram(uint8_t address, uint8_t data) { - writenvram(address, &data, 1); -} - -//////////////////////////////////////////////////////////////////////////////// -// RTC_Millis implementation - -long RTC_Millis::offset = 0; - -void RTC_Millis::adjust(const DateTime& dt) { - offset = dt.unixtime() - millis() / 1000; -} - -DateTime RTC_Millis::now() { - return (uint32_t)(offset + millis() / 1000); -} - -//////////////////////////////////////////////////////////////////////////////// - -//////////////////////////////////////////////////////////////////////////////// -// RTC_PCF8563 implementation - -boolean RTC_PCF8523::begin(void) { - Wire.begin(); - return true; -} - -boolean RTC_PCF8523::initialized(void) { - Wire.beginTransmission(PCF8523_ADDRESS); - Wire._I2C_WRITE((byte)PCF8523_CONTROL_3); - Wire.endTransmission(); - - Wire.requestFrom(PCF8523_ADDRESS, 1); - uint8_t ss = Wire._I2C_READ(); - return ((ss & 0xE0) != 0xE0); -} - -void RTC_PCF8523::adjust(const DateTime& dt) { - Wire.beginTransmission(PCF8523_ADDRESS); - Wire._I2C_WRITE((byte)3); // start at location 3 - Wire._I2C_WRITE(bin2bcd(dt.second())); - Wire._I2C_WRITE(bin2bcd(dt.minute())); - Wire._I2C_WRITE(bin2bcd(dt.hour())); - Wire._I2C_WRITE(bin2bcd(dt.day())); - Wire._I2C_WRITE(bin2bcd(0)); // skip weekdays - Wire._I2C_WRITE(bin2bcd(dt.month())); - Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); - Wire.endTransmission(); - - // set to battery switchover mode - Wire.beginTransmission(PCF8523_ADDRESS); - Wire._I2C_WRITE((byte)PCF8523_CONTROL_3); - Wire._I2C_WRITE((byte)0x00); - Wire.endTransmission(); -} - -DateTime RTC_PCF8523::now() { - Wire.beginTransmission(PCF8523_ADDRESS); - Wire._I2C_WRITE((byte)3); - Wire.endTransmission(); - - Wire.requestFrom(PCF8523_ADDRESS, 7); - uint8_t ss = bcd2bin(Wire._I2C_READ() & 0x7F); - uint8_t mm = bcd2bin(Wire._I2C_READ()); - uint8_t hh = bcd2bin(Wire._I2C_READ()); - uint8_t d = bcd2bin(Wire._I2C_READ()); - Wire._I2C_READ(); // skip 'weekdays' - uint8_t m = bcd2bin(Wire._I2C_READ()); - uint16_t y = bcd2bin(Wire._I2C_READ()) + 2000; - - return DateTime (y, m, d, hh, mm, ss); -} - -Pcf8523SqwPinMode RTC_PCF8523::readSqwPinMode() { - int mode; - - Wire.beginTransmission(PCF8523_ADDRESS); - Wire._I2C_WRITE(PCF8523_CLKOUTCONTROL); - Wire.endTransmission(); - - Wire.requestFrom((uint8_t)PCF8523_ADDRESS, (uint8_t)1); - mode = Wire._I2C_READ(); - - mode >>= 3; - mode &= 0x7; - return static_cast(mode); -} - -void RTC_PCF8523::writeSqwPinMode(Pcf8523SqwPinMode mode) { - Wire.beginTransmission(PCF8523_ADDRESS); - Wire._I2C_WRITE(PCF8523_CLKOUTCONTROL); - Wire._I2C_WRITE(mode << 3); - Wire.endTransmission(); -} - - - - -//////////////////////////////////////////////////////////////////////////////// -// RTC_DS3231 implementation - -boolean RTC_DS3231::begin(void) { - Wire.begin(); - return true; -} - -bool RTC_DS3231::lostPower(void) { - return (read_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG) >> 7); -} - -void RTC_DS3231::adjust(const DateTime& dt) { - Wire.beginTransmission(DS3231_ADDRESS); - Wire._I2C_WRITE((byte)0); // start at location 0 - Wire._I2C_WRITE(bin2bcd(dt.second())); - Wire._I2C_WRITE(bin2bcd(dt.minute())); - Wire._I2C_WRITE(bin2bcd(dt.hour())); - Wire._I2C_WRITE(bin2bcd(0)); - Wire._I2C_WRITE(bin2bcd(dt.day())); - Wire._I2C_WRITE(bin2bcd(dt.month())); - Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); - Wire.endTransmission(); - - uint8_t statreg = read_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG); - statreg &= ~0x80; // flip OSF bit - write_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG, statreg); -} - -DateTime RTC_DS3231::now() { - Wire.beginTransmission(DS3231_ADDRESS); - Wire._I2C_WRITE((byte)0); - Wire.endTransmission(); - - Wire.requestFrom(DS3231_ADDRESS, 7); - uint8_t ss = bcd2bin(Wire._I2C_READ() & 0x7F); - uint8_t mm = bcd2bin(Wire._I2C_READ()); - uint8_t hh = bcd2bin(Wire._I2C_READ()); - Wire._I2C_READ(); - uint8_t d = bcd2bin(Wire._I2C_READ()); - uint8_t m = bcd2bin(Wire._I2C_READ()); - uint16_t y = bcd2bin(Wire._I2C_READ()) + 2000; - - return DateTime (y, m, d, hh, mm, ss); -} - -Ds3231SqwPinMode RTC_DS3231::readSqwPinMode() { - int mode; - - Wire.beginTransmission(DS3231_ADDRESS); - Wire._I2C_WRITE(DS3231_CONTROL); - Wire.endTransmission(); - - Wire.requestFrom((uint8_t)DS3231_ADDRESS, (uint8_t)1); - mode = Wire._I2C_READ(); - - mode &= 0x93; - return static_cast(mode); -} - -void RTC_DS3231::writeSqwPinMode(Ds3231SqwPinMode mode) { - uint8_t ctrl; - ctrl = read_i2c_register(DS3231_ADDRESS, DS3231_CONTROL); - - ctrl &= ~0x04; // turn off INTCON - ctrl &= ~0x18; // set freq bits to 0 - - if (mode == DS3231_OFF) { - ctrl |= 0x04; // turn on INTCN - } else { - ctrl |= mode; - } - write_i2c_register(DS3231_ADDRESS, DS3231_CONTROL, ctrl); - - //Serial.println( read_i2c_register(DS3231_ADDRESS, DS3231_CONTROL), HEX); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/RTClib.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/RTClib.h deleted file mode 100644 index abf5d9b..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/RTClib.h +++ /dev/null @@ -1,135 +0,0 @@ -// Code by JeeLabs http://news.jeelabs.org/code/ -// Released to the public domain! Enjoy! - -#ifndef _RTCLIB_H_ -#define _RTCLIB_H_ - -#include -class TimeSpan; - - -#define PCF8523_ADDRESS 0x68 -#define PCF8523_CLKOUTCONTROL 0x0F -#define PCF8523_CONTROL_3 0x02 - -#define DS1307_ADDRESS 0x68 -#define DS1307_CONTROL 0x07 -#define DS1307_NVRAM 0x08 - -#define DS3231_ADDRESS 0x68 -#define DS3231_CONTROL 0x0E -#define DS3231_STATUSREG 0x0F - -#define SECONDS_PER_DAY 86400L - -#define SECONDS_FROM_1970_TO_2000 946684800 - - - -// Simple general-purpose date/time class (no TZ / DST / leap second handling!) -class DateTime { -public: - DateTime (uint32_t t =0); - DateTime (uint16_t year, uint8_t month, uint8_t day, - uint8_t hour =0, uint8_t min =0, uint8_t sec =0); - DateTime (const DateTime& copy); - DateTime (const char* date, const char* time); - DateTime (const __FlashStringHelper* date, const __FlashStringHelper* time); - uint16_t year() const { return 2000 + yOff; } - uint8_t month() const { return m; } - uint8_t day() const { return d; } - uint8_t hour() const { return hh; } - uint8_t minute() const { return mm; } - uint8_t second() const { return ss; } - uint8_t dayOfTheWeek() const; - - // 32-bit times as seconds since 1/1/2000 - long secondstime() const; - // 32-bit times as seconds since 1/1/1970 - uint32_t unixtime(void) const; - - DateTime operator+(const TimeSpan& span); - DateTime operator-(const TimeSpan& span); - TimeSpan operator-(const DateTime& right); - -protected: - uint8_t yOff, m, d, hh, mm, ss; -}; - -// Timespan which can represent changes in time with seconds accuracy. -class TimeSpan { -public: - TimeSpan (int32_t seconds = 0); - TimeSpan (int16_t days, int8_t hours, int8_t minutes, int8_t seconds); - TimeSpan (const TimeSpan& copy); - int16_t days() const { return _seconds / 86400L; } - int8_t hours() const { return _seconds / 3600 % 24; } - int8_t minutes() const { return _seconds / 60 % 60; } - int8_t seconds() const { return _seconds % 60; } - int32_t totalseconds() const { return _seconds; } - - TimeSpan operator+(const TimeSpan& right); - TimeSpan operator-(const TimeSpan& right); - -protected: - int32_t _seconds; -}; - -// RTC based on the DS1307 chip connected via I2C and the Wire library -enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 }; - -class RTC_DS1307 { -public: - boolean begin(void); - static void adjust(const DateTime& dt); - uint8_t isrunning(void); - static DateTime now(); - static Ds1307SqwPinMode readSqwPinMode(); - static void writeSqwPinMode(Ds1307SqwPinMode mode); - uint8_t readnvram(uint8_t address); - void readnvram(uint8_t* buf, uint8_t size, uint8_t address); - void writenvram(uint8_t address, uint8_t data); - void writenvram(uint8_t address, uint8_t* buf, uint8_t size); -}; - -// RTC based on the DS3231 chip connected via I2C and the Wire library -enum Ds3231SqwPinMode { DS3231_OFF = 0x01, DS3231_SquareWave1Hz = 0x00, DS3231_SquareWave1kHz = 0x08, DS3231_SquareWave4kHz = 0x10, DS3231_SquareWave8kHz = 0x18 }; - -class RTC_DS3231 { -public: - boolean begin(void); - static void adjust(const DateTime& dt); - bool lostPower(void); - static DateTime now(); - static Ds3231SqwPinMode readSqwPinMode(); - static void writeSqwPinMode(Ds3231SqwPinMode mode); -}; - - -// RTC based on the PCF8523 chip connected via I2C and the Wire library -enum Pcf8523SqwPinMode { PCF8523_OFF = 7, PCF8523_SquareWave1HZ = 6, PCF8523_SquareWave32HZ = 5, PCF8523_SquareWave1kHz = 4, PCF8523_SquareWave4kHz = 3, PCF8523_SquareWave8kHz = 2, PCF8523_SquareWave16kHz = 1, PCF8523_SquareWave32kHz = 0 }; - -class RTC_PCF8523 { -public: - boolean begin(void); - void adjust(const DateTime& dt); - boolean initialized(void); - static DateTime now(); - - Pcf8523SqwPinMode readSqwPinMode(); - void writeSqwPinMode(Pcf8523SqwPinMode mode); -}; - -// RTC using the internal millis() clock, has to be initialized before use -// NOTE: this clock won't be correct once the millis() timer rolls over (>49d?) -class RTC_Millis { -public: - static void begin(const DateTime& dt) { adjust(dt); } - static void adjust(const DateTime& dt); - static DateTime now(); - -protected: - static long offset; -}; - -#endif // _RTCLIB_H_ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/datecalc/datecalc.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/datecalc/datecalc.ino deleted file mode 100644 index 771dacd..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/datecalc/datecalc.ino +++ /dev/null @@ -1,111 +0,0 @@ -// Simple date conversions and calculations - -#include -#include "RTClib.h" - -#if defined(ARDUINO_ARCH_SAMD) -// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! - #define Serial SerialUSB -#endif - -void showDate(const char* txt, const DateTime& dt) { - Serial.print(txt); - Serial.print(' '); - Serial.print(dt.year(), DEC); - Serial.print('/'); - Serial.print(dt.month(), DEC); - Serial.print('/'); - Serial.print(dt.day(), DEC); - Serial.print(' '); - Serial.print(dt.hour(), DEC); - Serial.print(':'); - Serial.print(dt.minute(), DEC); - Serial.print(':'); - Serial.print(dt.second(), DEC); - - Serial.print(" = "); - Serial.print(dt.unixtime()); - Serial.print("s / "); - Serial.print(dt.unixtime() / 86400L); - Serial.print("d since 1970"); - - Serial.println(); -} - -void showTimeSpan(const char* txt, const TimeSpan& ts) { - Serial.print(txt); - Serial.print(" "); - Serial.print(ts.days(), DEC); - Serial.print(" days "); - Serial.print(ts.hours(), DEC); - Serial.print(" hours "); - Serial.print(ts.minutes(), DEC); - Serial.print(" minutes "); - Serial.print(ts.seconds(), DEC); - Serial.print(" seconds ("); - Serial.print(ts.totalseconds(), DEC); - Serial.print(" total seconds)"); - Serial.println(); -} - -void setup () { - -#ifndef ESP8266 - while (!Serial); // for Leonardo/Micro/Zero -#endif - Serial.begin(57600); - - DateTime dt0 (0, 1, 1, 0, 0, 0); - showDate("dt0", dt0); - - DateTime dt1 (1, 1, 1, 0, 0, 0); - showDate("dt1", dt1); - - DateTime dt2 (2009, 1, 1, 0, 0, 0); - showDate("dt2", dt2); - - DateTime dt3 (2009, 1, 2, 0, 0, 0); - showDate("dt3", dt3); - - DateTime dt4 (2009, 1, 27, 0, 0, 0); - showDate("dt4", dt4); - - DateTime dt5 (2009, 2, 27, 0, 0, 0); - showDate("dt5", dt5); - - DateTime dt6 (2009, 12, 27, 0, 0, 0); - showDate("dt6", dt6); - - DateTime dt7 (dt6.unixtime() + 3600); // One hour later. - showDate("dt7", dt7); - - DateTime dt75 = dt6 + TimeSpan(0, 1, 0, 0); // One hour later with TimeSpan addition. - showDate("dt7.5", dt75); - - DateTime dt8 (dt6.unixtime() + 86400L); // One day later. - showDate("dt8", dt8); - - DateTime dt85 = dt6 + TimeSpan(1, 0, 0, 0); // One day later with TimeSpan addition. - showDate("dt8.5", dt85); - - DateTime dt9 (dt6.unixtime() + 7 * 86400L); // One week later. - showDate("dt9", dt9); - - DateTime dt95 = dt6 + TimeSpan(7, 0, 0, 0); // One week later with TimeSpan addition. - showDate("dt9.5", dt95); - - DateTime dt10 = dt6 + TimeSpan(0, 0, 42, 42); // Fourty two minutes and fourty two seconds later. - showDate("dt10", dt10); - - DateTime dt11 = dt6 - TimeSpan(7, 0, 0, 0); // One week ago. - showDate("dt11", dt11); - - TimeSpan ts1 = dt6 - dt5; - showTimeSpan("dt6-dt5", ts1); - - TimeSpan ts2 = dt10 - dt6; - showTimeSpan("dt10-dt6", ts2); -} - -void loop () { -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307/ds1307.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307/ds1307.ino deleted file mode 100644 index 7d9162f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307/ds1307.ino +++ /dev/null @@ -1,71 +0,0 @@ -// Date and time functions using a DS1307 RTC connected via I2C and Wire lib -#include -#include "RTClib.h" - -RTC_DS1307 rtc; - -char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; - -void setup () { - while (!Serial); // for Leonardo/Micro/Zero - - Serial.begin(57600); - if (! rtc.begin()) { - Serial.println("Couldn't find RTC"); - while (1); - } - - if (! rtc.isrunning()) { - Serial.println("RTC is NOT running!"); - // following line sets the RTC to the date & time this sketch was compiled - // rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); - // This line sets the RTC with an explicit date & time, for example to set - // January 21, 2014 at 3am you would call: - // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); - } -} - -void loop () { - DateTime now = rtc.now(); - - Serial.print(now.year(), DEC); - Serial.print('/'); - Serial.print(now.month(), DEC); - Serial.print('/'); - Serial.print(now.day(), DEC); - Serial.print(" ("); - Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); - Serial.print(") "); - Serial.print(now.hour(), DEC); - Serial.print(':'); - Serial.print(now.minute(), DEC); - Serial.print(':'); - Serial.print(now.second(), DEC); - Serial.println(); - - Serial.print(" since midnight 1/1/1970 = "); - Serial.print(now.unixtime()); - Serial.print("s = "); - Serial.print(now.unixtime() / 86400L); - Serial.println("d"); - - // calculate a date which is 7 days and 30 seconds into the future - DateTime future (now + TimeSpan(7,12,30,6)); - - Serial.print(" now + 7d + 30s: "); - Serial.print(future.year(), DEC); - Serial.print('/'); - Serial.print(future.month(), DEC); - Serial.print('/'); - Serial.print(future.day(), DEC); - Serial.print(' '); - Serial.print(future.hour(), DEC); - Serial.print(':'); - Serial.print(future.minute(), DEC); - Serial.print(':'); - Serial.print(future.second(), DEC); - Serial.println(); - - Serial.println(); - delay(3000); -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino deleted file mode 100644 index c12c26c..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307SqwPin/ds1307SqwPin.ino +++ /dev/null @@ -1,68 +0,0 @@ -// SQW/OUT pin mode using a DS1307 RTC connected via I2C. -// -// According to the data sheet (http://datasheets.maxim-ic.com/en/ds/DS1307.pdf), the -// DS1307's SQW/OUT pin can be set to low, high, 1Hz, 4.096kHz, 8.192kHz, or 32.768kHz. -// -// This sketch reads the state of the pin, then iterates through the possible values at -// 5 second intervals. -// - -// NOTE: -// You must connect a pull up resistor (~10kohm) from the SQW pin up to VCC. Without -// this pull up the wave output will not work! - -#include -#include "RTClib.h" - -#if defined(ARDUINO_ARCH_SAMD) -// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! - #define Serial SerialUSB -#endif - -RTC_DS1307 rtc; - -int mode_index = 0; - -Ds1307SqwPinMode modes[] = {OFF, ON, SquareWave1HZ, SquareWave4kHz, SquareWave8kHz, SquareWave32kHz}; - - -void print_mode() { - Ds1307SqwPinMode mode = rtc.readSqwPinMode(); - - Serial.print("Sqw Pin Mode: "); - switch(mode) { - case OFF: Serial.println("OFF"); break; - case ON: Serial.println("ON"); break; - case SquareWave1HZ: Serial.println("1Hz"); break; - case SquareWave4kHz: Serial.println("4.096kHz"); break; - case SquareWave8kHz: Serial.println("8.192kHz"); break; - case SquareWave32kHz: Serial.println("32.768kHz"); break; - default: Serial.println("UNKNOWN"); break; - } -} - -void setup () { - -#ifndef ESP8266 - while (!Serial); // for Leonardo/Micro/Zero -#endif - - Serial.begin(57600); - if (! rtc.begin()) { - Serial.println("Couldn't find RTC"); - while (1); - } - - print_mode(); -} - -void loop () { - rtc.writeSqwPinMode(modes[mode_index++]); - print_mode(); - - if (mode_index > 5) { - mode_index = 0; - } - - delay(5000); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino deleted file mode 100644 index 0acd0cf..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds1307nvram/ds1307nvram.ino +++ /dev/null @@ -1,63 +0,0 @@ -// Example of using the non-volatile RAM storage on the DS1307. -// You can write up to 56 bytes from address 0 to 55. -// Data will be persisted as long as the DS1307 has battery power. - -#include -#include "RTClib.h" - -#if defined(ARDUINO_ARCH_SAMD) -// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! - #define Serial SerialUSB -#endif - -RTC_DS1307 rtc; - -void printnvram(uint8_t address) { - Serial.print("Address 0x"); - Serial.print(address, HEX); - Serial.print(" = 0x"); - Serial.println(rtc.readnvram(address), HEX); -} - -void setup () { - -#ifndef ESP8266 - while (!Serial); // for Leonardo/Micro/Zero -#endif - Serial.begin(57600); - rtc.begin(); - - // Print old RAM contents on startup. - Serial.println("Current NVRAM values:"); - for (int i = 0; i < 6; ++i) { - printnvram(i); - } - - // Write some bytes to non-volatile RAM storage. - // NOTE: You can only read and write from addresses 0 to 55 (i.e. 56 byte values). - Serial.println("Writing NVRAM values."); - // Example writing one byte at a time: - rtc.writenvram(0, 0xFE); - rtc.writenvram(1, 0xED); - // Example writing multiple bytes: - uint8_t writeData[4] = { 0xBE, 0xEF, 0x01, 0x02 }; - rtc.writenvram(2, writeData, 4); - - // Read bytes from non-volatile RAM storage. - Serial.println("Reading NVRAM values:"); - // Example reading one byte at a time. - Serial.println(rtc.readnvram(0), HEX); - Serial.println(rtc.readnvram(1), HEX); - // Example reading multiple bytes: - uint8_t readData[4] = {0}; - rtc.readnvram(readData, 4, 2); - Serial.println(readData[0], HEX); - Serial.println(readData[1], HEX); - Serial.println(readData[2], HEX); - Serial.println(readData[3], HEX); - -} - -void loop () { - // Do nothing in the loop. -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds3231/ds3231.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds3231/ds3231.ino deleted file mode 100644 index b62d510..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/ds3231/ds3231.ino +++ /dev/null @@ -1,77 +0,0 @@ -// Date and time functions using a DS3231 RTC connected via I2C and Wire lib -#include -#include "RTClib.h" - -RTC_DS3231 rtc; - -char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; - -void setup () { - -#ifndef ESP8266 - while (!Serial); // for Leonardo/Micro/Zero -#endif - - Serial.begin(9600); - - delay(3000); // wait for console opening - - if (! rtc.begin()) { - Serial.println("Couldn't find RTC"); - while (1); - } - - if (rtc.lostPower()) { - Serial.println("RTC lost power, lets set the time!"); - // following line sets the RTC to the date & time this sketch was compiled - rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); - // This line sets the RTC with an explicit date & time, for example to set - // January 21, 2014 at 3am you would call: - // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); - } -} - -void loop () { - DateTime now = rtc.now(); - - Serial.print(now.year(), DEC); - Serial.print('/'); - Serial.print(now.month(), DEC); - Serial.print('/'); - Serial.print(now.day(), DEC); - Serial.print(" ("); - Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); - Serial.print(") "); - Serial.print(now.hour(), DEC); - Serial.print(':'); - Serial.print(now.minute(), DEC); - Serial.print(':'); - Serial.print(now.second(), DEC); - Serial.println(); - - Serial.print(" since midnight 1/1/1970 = "); - Serial.print(now.unixtime()); - Serial.print("s = "); - Serial.print(now.unixtime() / 86400L); - Serial.println("d"); - - // calculate a date which is 7 days and 30 seconds into the future - DateTime future (now + TimeSpan(7,12,30,6)); - - Serial.print(" now + 7d + 30s: "); - Serial.print(future.year(), DEC); - Serial.print('/'); - Serial.print(future.month(), DEC); - Serial.print('/'); - Serial.print(future.day(), DEC); - Serial.print(' '); - Serial.print(future.hour(), DEC); - Serial.print(':'); - Serial.print(future.minute(), DEC); - Serial.print(':'); - Serial.print(future.second(), DEC); - Serial.println(); - - Serial.println(); - delay(3000); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/pcf8523/pcf8523.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/pcf8523/pcf8523.ino deleted file mode 100644 index fc7dfe8..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/pcf8523/pcf8523.ino +++ /dev/null @@ -1,74 +0,0 @@ -// Date and time functions using a DS1307 RTC connected via I2C and Wire lib -#include -#include "RTClib.h" - -RTC_PCF8523 rtc; - -char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; - -void setup () { - - while (!Serial) { - delay(1); // for Leonardo/Micro/Zero - } - - Serial.begin(57600); - if (! rtc.begin()) { - Serial.println("Couldn't find RTC"); - while (1); - } - - if (! rtc.initialized()) { - Serial.println("RTC is NOT running!"); - // following line sets the RTC to the date & time this sketch was compiled - // rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); - // This line sets the RTC with an explicit date & time, for example to set - // January 21, 2014 at 3am you would call: - // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); - } -} - -void loop () { - DateTime now = rtc.now(); - - Serial.print(now.year(), DEC); - Serial.print('/'); - Serial.print(now.month(), DEC); - Serial.print('/'); - Serial.print(now.day(), DEC); - Serial.print(" ("); - Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); - Serial.print(") "); - Serial.print(now.hour(), DEC); - Serial.print(':'); - Serial.print(now.minute(), DEC); - Serial.print(':'); - Serial.print(now.second(), DEC); - Serial.println(); - - Serial.print(" since midnight 1/1/1970 = "); - Serial.print(now.unixtime()); - Serial.print("s = "); - Serial.print(now.unixtime() / 86400L); - Serial.println("d"); - - // calculate a date which is 7 days and 30 seconds into the future - DateTime future (now + TimeSpan(7,12,30,6)); - - Serial.print(" now + 7d + 30s: "); - Serial.print(future.year(), DEC); - Serial.print('/'); - Serial.print(future.month(), DEC); - Serial.print('/'); - Serial.print(future.day(), DEC); - Serial.print(' '); - Serial.print(future.hour(), DEC); - Serial.print(':'); - Serial.print(future.minute(), DEC); - Serial.print(':'); - Serial.print(future.second(), DEC); - Serial.println(); - - Serial.println(); - delay(3000); -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/softrtc/softrtc.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/softrtc/softrtc.ino deleted file mode 100644 index 80f1886..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/examples/softrtc/softrtc.ino +++ /dev/null @@ -1,61 +0,0 @@ -// Date and time functions using just software, based on millis() & timer - -#include -#include // this #include still required because the RTClib depends on it -#include "RTClib.h" - -#if defined(ARDUINO_ARCH_SAMD) -// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero! - #define Serial SerialUSB -#endif - -RTC_Millis rtc; - -void setup () { - Serial.begin(57600); - // following line sets the RTC to the date & time this sketch was compiled - rtc.begin(DateTime(F(__DATE__), F(__TIME__))); - // This line sets the RTC with an explicit date & time, for example to set - // January 21, 2014 at 3am you would call: - // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); -} - -void loop () { - DateTime now = rtc.now(); - - Serial.print(now.year(), DEC); - Serial.print('/'); - Serial.print(now.month(), DEC); - Serial.print('/'); - Serial.print(now.day(), DEC); - Serial.print(' '); - Serial.print(now.hour(), DEC); - Serial.print(':'); - Serial.print(now.minute(), DEC); - Serial.print(':'); - Serial.print(now.second(), DEC); - Serial.println(); - - Serial.print(" seconds since 1970: "); - Serial.println(now.unixtime()); - - // calculate a date which is 7 days and 30 seconds into the future - DateTime future (now.unixtime() + 7 * 86400L + 30); - - Serial.print(" now + 7d + 30s: "); - Serial.print(future.year(), DEC); - Serial.print('/'); - Serial.print(future.month(), DEC); - Serial.print('/'); - Serial.print(future.day(), DEC); - Serial.print(' '); - Serial.print(future.hour(), DEC); - Serial.print(':'); - Serial.print(future.minute(), DEC); - Serial.print(':'); - Serial.print(future.second(), DEC); - Serial.println(); - - Serial.println(); - delay(3000); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/keywords.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/keywords.txt deleted file mode 100644 index 26cdc1e..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/keywords.txt +++ /dev/null @@ -1,37 +0,0 @@ -####################################### -# Syntax Coloring Map For RTC -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -DateTime KEYWORD1 -RTC_DS1307 KEYWORD1 -RTC_Millis KEYWORD1 -Ds1307SqwPinMode KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -year KEYWORD2 -month KEYWORD2 -day KEYWORD2 -hour KEYWORD2 -minute KEYWORD2 -second KEYWORD2 -dayOfWeek KEYWORD2 -secondstime KEYWORD2 -unixtime KEYWORD2 -begin KEYWORD2 -adjust KEYWORD2 -isrunning KEYWORD2 -now KEYWORD2 -readSqwPinMode KEYWORD2 -writeSqwPinMode KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/library.properties b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/library.properties deleted file mode 100644 index 13d6177..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/RTClib/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=RTClib -version=1.2.1 -author=Adafruit -maintainer=Adafruit -sentence=A fork of Jeelab's fantastic RTC library -paragraph=A fork of Jeelab's fantastic RTC library -category=Timing -url=https://github.com/adafruit/RTClib -architectures=* diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/File.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/File.cpp deleted file mode 100755 index 5e37166..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/File.cpp +++ /dev/null @@ -1,168 +0,0 @@ -/* - - SD - a slightly more friendly wrapper for sdfatlib - - This library aims to expose a subset of SD card functionality - in the form of a higher level "wrapper" object. - - License: GNU General Public License V3 - (Because sdfatlib is licensed with this.) - - (C) Copyright 2010 SparkFun Electronics - -*/ - -#include - -/* for debugging file open/close leaks - uint8_t nfilecount=0; -*/ - -File::File(SdFile f, const char *n) { - // oh man you are kidding me, new() doesn't exist? Ok we do it by hand! - _file = (SdFile *)malloc(sizeof(SdFile)); - if (_file) { - memcpy(_file, &f, sizeof(SdFile)); - - strncpy(_name, n, 12); - _name[12] = 0; - - /* for debugging file open/close leaks - nfilecount++; - Serial.print("Created \""); - Serial.print(n); - Serial.print("\": "); - Serial.println(nfilecount, DEC); - */ - } -} - -File::File(void) { - _file = 0; - _name[0] = 0; - //Serial.print("Created empty file object"); -} - -// returns a pointer to the file name -char *File::name(void) { - return _name; -} - -// a directory is a special type of file -boolean File::isDirectory(void) { - return (_file && _file->isDir()); -} - - -size_t File::write(uint8_t val) { - return write(&val, 1); -} - -size_t File::write(const uint8_t *buf, size_t size) { - size_t t; - if (!_file) { - setWriteError(); - return 0; - } - _file->clearWriteError(); - t = _file->write(buf, size); - if (_file->getWriteError()) { - setWriteError(); - return 0; - } - return t; -} - -int File::availableForWrite() { - if (_file) { - return _file->availableForWrite(); - } - return 0; -} - -int File::peek() { - if (! _file) { - return 0; - } - - int c = _file->read(); - if (c != -1) { - _file->seekCur(-1); - } - return c; -} - -int File::read() { - if (_file) { - return _file->read(); - } - return -1; -} - -// buffered read for more efficient, high speed reading -int File::read(void *buf, uint16_t nbyte) { - if (_file) { - return _file->read(buf, nbyte); - } - return 0; -} - -int File::available() { - if (! _file) { - return 0; - } - - uint32_t n = size() - position(); - - return n > 0X7FFF ? 0X7FFF : n; -} - -void File::flush() { - if (_file) { - _file->sync(); - } -} - -boolean File::seek(uint32_t pos) { - if (! _file) { - return false; - } - - return _file->seekSet(pos); -} - -uint32_t File::position() { - if (! _file) { - return -1; - } - return _file->curPosition(); -} - -uint32_t File::size() { - if (! _file) { - return 0; - } - return _file->fileSize(); -} - -void File::close() { - if (_file) { - _file->close(); - free(_file); - _file = 0; - - /* for debugging file open/close leaks - nfilecount--; - Serial.print("Deleted "); - Serial.println(nfilecount, DEC); - */ - } -} - -File::operator bool() { - if (_file) { - return _file->isOpen(); - } - return false; -} - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/README.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/README.txt deleted file mode 100755 index 495ea4c..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/README.txt +++ /dev/null @@ -1,13 +0,0 @@ - -** SD - a slightly more friendly wrapper for sdfatlib ** - -This library aims to expose a subset of SD card functionality in the -form of a higher level "wrapper" object. - -License: GNU General Public License V3 - (Because sdfatlib is licensed with this.) - -(C) Copyright 2010 SparkFun Electronics - -Now better than ever with optimization, multiple file support, directory handling, etc - ladyada! - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/SD.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/SD.cpp deleted file mode 100755 index 8c9a29e..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/SD.cpp +++ /dev/null @@ -1,637 +0,0 @@ -/* - - SD - a slightly more friendly wrapper for sdfatlib - - This library aims to expose a subset of SD card functionality - in the form of a higher level "wrapper" object. - - License: GNU General Public License V3 - (Because sdfatlib is licensed with this.) - - (C) Copyright 2010 SparkFun Electronics - - - This library provides four key benefits: - - Including `SD.h` automatically creates a global - `SD` object which can be interacted with in a similar - manner to other standard global objects like `Serial` and `Ethernet`. - - Boilerplate initialisation code is contained in one method named - `begin` and no further objects need to be created in order to access - the SD card. - - Calls to `open` can supply a full path name including parent - directories which simplifies interacting with files in subdirectories. - - Utility methods are provided to determine whether a file exists - and to create a directory hierarchy. - - - Note however that not all functionality provided by the underlying - sdfatlib library is exposed. - -*/ - -/* - - Implementation Notes - - In order to handle multi-directory path traversal, functionality that - requires this ability is implemented as callback functions. - - Individual methods call the `walkPath` function which performs the actual - directory traversal (swapping between two different directory/file handles - along the way) and at each level calls the supplied callback function. - - Some types of functionality will take an action at each level (e.g. exists - or make directory) which others will only take an action at the bottom - level (e.g. open). - -*/ - -#include "SD.h" - -namespace SDLib { - - // Used by `getNextPathComponent` -#define MAX_COMPONENT_LEN 12 // What is max length? -#define PATH_COMPONENT_BUFFER_LEN MAX_COMPONENT_LEN+1 - - bool getNextPathComponent(const char *path, unsigned int *p_offset, - char *buffer) { - /* - - Parse individual path components from a path. - - e.g. after repeated calls '/foo/bar/baz' will be split - into 'foo', 'bar', 'baz'. - - This is similar to `strtok()` but copies the component into the - supplied buffer rather than modifying the original string. - - - `buffer` needs to be PATH_COMPONENT_BUFFER_LEN in size. - - `p_offset` needs to point to an integer of the offset at - which the previous path component finished. - - Returns `true` if more components remain. - - Returns `false` if this is the last component. - (This means path ended with 'foo' or 'foo/'.) - - */ - - // TODO: Have buffer local to this function, so we know it's the - // correct length? - - int bufferOffset = 0; - - int offset = *p_offset; - - // Skip root or other separator - if (path[offset] == '/') { - offset++; - } - - // Copy the next next path segment - while (bufferOffset < MAX_COMPONENT_LEN - && (path[offset] != '/') - && (path[offset] != '\0')) { - buffer[bufferOffset++] = path[offset++]; - } - - buffer[bufferOffset] = '\0'; - - // Skip trailing separator so we can determine if this - // is the last component in the path or not. - if (path[offset] == '/') { - offset++; - } - - *p_offset = offset; - - return (path[offset] != '\0'); - } - - - - boolean walkPath(const char *filepath, SdFile& parentDir, - boolean(*callback)(SdFile& parentDir, - const char *filePathComponent, - boolean isLastComponent, - void *object), - void *object = NULL) { - /* - - When given a file path (and parent directory--normally root), - this function traverses the directories in the path and at each - level calls the supplied callback function while also providing - the supplied object for context if required. - - e.g. given the path '/foo/bar/baz' - the callback would be called at the equivalent of - '/foo', '/foo/bar' and '/foo/bar/baz'. - - The implementation swaps between two different directory/file - handles as it traverses the directories and does not use recursion - in an attempt to use memory efficiently. - - If a callback wishes to stop the directory traversal it should - return false--in this case the function will stop the traversal, - tidy up and return false. - - If a directory path doesn't exist at some point this function will - also return false and not subsequently call the callback. - - If a directory path specified is complete, valid and the callback - did not indicate the traversal should be interrupted then this - function will return true. - - */ - - - SdFile subfile1; - SdFile subfile2; - - char buffer[PATH_COMPONENT_BUFFER_LEN]; - - unsigned int offset = 0; - - SdFile *p_parent; - SdFile *p_child; - - SdFile *p_tmp_sdfile; - - p_child = &subfile1; - - p_parent = &parentDir; - - while (true) { - - boolean moreComponents = getNextPathComponent(filepath, &offset, buffer); - - boolean shouldContinue = callback((*p_parent), buffer, !moreComponents, object); - - if (!shouldContinue) { - // TODO: Don't repeat this code? - // If it's one we've created then we - // don't need the parent handle anymore. - if (p_parent != &parentDir) { - (*p_parent).close(); - } - return false; - } - - if (!moreComponents) { - break; - } - - boolean exists = (*p_child).open(*p_parent, buffer, O_RDONLY); - - // If it's one we've created then we - // don't need the parent handle anymore. - if (p_parent != &parentDir) { - (*p_parent).close(); - } - - // Handle case when it doesn't exist and we can't continue... - if (exists) { - // We alternate between two file handles as we go down - // the path. - if (p_parent == &parentDir) { - p_parent = &subfile2; - } - - p_tmp_sdfile = p_parent; - p_parent = p_child; - p_child = p_tmp_sdfile; - } else { - return false; - } - } - - if (p_parent != &parentDir) { - (*p_parent).close(); // TODO: Return/ handle different? - } - - return true; - } - - - - /* - - The callbacks used to implement various functionality follow. - - Each callback is supplied with a parent directory handle, - character string with the name of the current file path component, - a flag indicating if this component is the last in the path and - a pointer to an arbitrary object used for context. - - */ - - boolean callback_pathExists(SdFile& parentDir, const char *filePathComponent, - boolean /* isLastComponent */, void * /* object */) { - /* - - Callback used to determine if a file/directory exists in parent - directory. - - Returns true if file path exists. - - */ - SdFile child; - - boolean exists = child.open(parentDir, filePathComponent, O_RDONLY); - - if (exists) { - child.close(); - } - - return exists; - } - - - - boolean callback_makeDirPath(SdFile& parentDir, const char *filePathComponent, - boolean isLastComponent, void *object) { - /* - - Callback used to create a directory in the parent directory if - it does not already exist. - - Returns true if a directory was created or it already existed. - - */ - boolean result = false; - SdFile child; - - result = callback_pathExists(parentDir, filePathComponent, isLastComponent, object); - if (!result) { - result = child.makeDir(parentDir, filePathComponent); - } - - return result; - } - - - /* - - boolean callback_openPath(SdFile& parentDir, char *filePathComponent, - boolean isLastComponent, void *object) { - - Callback used to open a file specified by a filepath that may - specify one or more directories above it. - - Expects the context object to be an instance of `SDClass` and - will use the `file` property of the instance to open the requested - file/directory with the associated file open mode property. - - Always returns true if the directory traversal hasn't reached the - bottom of the directory hierarchy. - - Returns false once the file has been opened--to prevent the traversal - from descending further. (This may be unnecessary.) - - if (isLastComponent) { - SDClass *p_SD = static_cast(object); - p_SD->file.open(parentDir, filePathComponent, p_SD->fileOpenMode); - if (p_SD->fileOpenMode == FILE_WRITE) { - p_SD->file.seekSet(p_SD->file.fileSize()); - } - // TODO: Return file open result? - return false; - } - return true; - } - */ - - - - boolean callback_remove(SdFile& parentDir, const char *filePathComponent, - boolean isLastComponent, void * /* object */) { - if (isLastComponent) { - return SdFile::remove(parentDir, filePathComponent); - } - return true; - } - - boolean callback_rmdir(SdFile& parentDir, const char *filePathComponent, - boolean isLastComponent, void * /* object */) { - if (isLastComponent) { - SdFile f; - if (!f.open(parentDir, filePathComponent, O_READ)) { - return false; - } - return f.rmDir(); - } - return true; - } - - - - /* Implementation of class used to create `SDCard` object. */ - - - - boolean SDClass::begin(uint8_t csPin) { - if (root.isOpen()) { - root.close(); - } - - /* - - Performs the initialisation required by the sdfatlib library. - - Return true if initialization succeeds, false otherwise. - - */ - return card.init(SPI_HALF_SPEED, csPin) && - volume.init(card) && - root.openRoot(volume); - } - - boolean SDClass::begin(uint32_t clock, uint8_t csPin) { - if (root.isOpen()) { - root.close(); - } - - return card.init(SPI_HALF_SPEED, csPin) && - card.setSpiClock(clock) && - volume.init(card) && - root.openRoot(volume); - } - - //call this when a card is removed. It will allow you to insert and initialise a new card. - void SDClass::end() { - root.close(); - } - - // this little helper is used to traverse paths - SdFile SDClass::getParentDir(const char *filepath, int *index) { - // get parent directory - SdFile d1; - SdFile d2; - - d1.openRoot(volume); // start with the mostparent, root! - - // we'll use the pointers to swap between the two objects - SdFile *parent = &d1; - SdFile *subdir = &d2; - - const char *origpath = filepath; - - while (strchr(filepath, '/')) { - - // get rid of leading /'s - if (filepath[0] == '/') { - filepath++; - continue; - } - - if (! strchr(filepath, '/')) { - // it was in the root directory, so leave now - break; - } - - // extract just the name of the next subdirectory - uint8_t idx = strchr(filepath, '/') - filepath; - if (idx > 12) { - idx = 12; // don't let them specify long names - } - char subdirname[13]; - strncpy(subdirname, filepath, idx); - subdirname[idx] = 0; - - // close the subdir (we reuse them) if open - subdir->close(); - if (! subdir->open(parent, subdirname, O_READ)) { - // failed to open one of the subdirectories - return SdFile(); - } - // move forward to the next subdirectory - filepath += idx; - - // we reuse the objects, close it. - parent->close(); - - // swap the pointers - SdFile *t = parent; - parent = subdir; - subdir = t; - } - - *index = (int)(filepath - origpath); - // parent is now the parent directory of the file! - return *parent; - } - - - File SDClass::open(const char *filepath, uint8_t mode) { - /* - - Open the supplied file path for reading or writing. - - The file content can be accessed via the `file` property of - the `SDClass` object--this property is currently - a standard `SdFile` object from `sdfatlib`. - - Defaults to read only. - - If `write` is true, default action (when `append` is true) is to - append data to the end of the file. - - If `append` is false then the file will be truncated first. - - If the file does not exist and it is opened for writing the file - will be created. - - An attempt to open a file for reading that does not exist is an - error. - - */ - - int pathidx; - - // do the interactive search - SdFile parentdir = getParentDir(filepath, &pathidx); - // no more subdirs! - - filepath += pathidx; - - if (! filepath[0]) { - // it was the directory itself! - return File(parentdir, "/"); - } - - // Open the file itself - SdFile file; - - // failed to open a subdir! - if (!parentdir.isOpen()) { - return File(); - } - - if (! file.open(parentdir, filepath, mode)) { - return File(); - } - // close the parent - parentdir.close(); - - if ((mode & (O_APPEND | O_WRITE)) == (O_APPEND | O_WRITE)) { - file.seekSet(file.fileSize()); - } - return File(file, filepath); - } - - - /* - File SDClass::open(char *filepath, uint8_t mode) { - // - - Open the supplied file path for reading or writing. - - The file content can be accessed via the `file` property of - the `SDClass` object--this property is currently - a standard `SdFile` object from `sdfatlib`. - - Defaults to read only. - - If `write` is true, default action (when `append` is true) is to - append data to the end of the file. - - If `append` is false then the file will be truncated first. - - If the file does not exist and it is opened for writing the file - will be created. - - An attempt to open a file for reading that does not exist is an - error. - - // - - // TODO: Allow for read&write? (Possibly not, as it requires seek.) - - fileOpenMode = mode; - walkPath(filepath, root, callback_openPath, this); - - return File(); - - } - */ - - - //boolean SDClass::close() { - // /* - // - // Closes the file opened by the `open` method. - // - // */ - // file.close(); - //} - - - boolean SDClass::exists(const char *filepath) { - /* - - Returns true if the supplied file path exists. - - */ - return walkPath(filepath, root, callback_pathExists); - } - - - //boolean SDClass::exists(char *filepath, SdFile& parentDir) { - // /* - // - // Returns true if the supplied file path rooted at `parentDir` - // exists. - // - // */ - // return walkPath(filepath, parentDir, callback_pathExists); - //} - - - boolean SDClass::mkdir(const char *filepath) { - /* - - Makes a single directory or a hierarchy of directories. - - A rough equivalent to `mkdir -p`. - - */ - return walkPath(filepath, root, callback_makeDirPath); - } - - boolean SDClass::rmdir(const char *filepath) { - /* - - Remove a single directory or a hierarchy of directories. - - A rough equivalent to `rm -rf`. - - */ - return walkPath(filepath, root, callback_rmdir); - } - - boolean SDClass::remove(const char *filepath) { - return walkPath(filepath, root, callback_remove); - } - - - // allows you to recurse into a directory - File File::openNextFile(uint8_t mode) { - dir_t p; - - //Serial.print("\t\treading dir..."); - while (_file->readDir(&p) > 0) { - - // done if past last used entry - if (p.name[0] == DIR_NAME_FREE) { - //Serial.println("end"); - return File(); - } - - // skip deleted entry and entries for . and .. - if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') { - //Serial.println("dots"); - continue; - } - - // only list subdirectories and files - if (!DIR_IS_FILE_OR_SUBDIR(&p)) { - //Serial.println("notafile"); - continue; - } - - // print file name with possible blank fill - SdFile f; - char name[13]; - _file->dirName(p, name); - //Serial.print("try to open file "); - //Serial.println(name); - - if (f.open(_file, name, mode)) { - //Serial.println("OK!"); - return File(f, name); - } else { - //Serial.println("ugh"); - return File(); - } - } - - //Serial.println("nothing"); - return File(); - } - - void File::rewindDirectory(void) { - if (isDirectory()) { - _file->rewind(); - } - } - - SDClass SD; - -}; diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/SD.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/SD.h deleted file mode 100755 index fa34ccd..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/SD.h +++ /dev/null @@ -1,138 +0,0 @@ -/* - - SD - a slightly more friendly wrapper for sdfatlib - - This library aims to expose a subset of SD card functionality - in the form of a higher level "wrapper" object. - - License: GNU General Public License V3 - (Because sdfatlib is licensed with this.) - - (C) Copyright 2010 SparkFun Electronics - -*/ - -#ifndef __SD_H__ -#define __SD_H__ - -#include - -#include "utility/SdFat.h" -#include "utility/SdFatUtil.h" - -#define FILE_READ O_READ -#define FILE_WRITE (O_READ | O_WRITE | O_CREAT | O_APPEND) - -namespace SDLib { - - class File : public Stream { - private: - char _name[13]; // our name - SdFile *_file; // underlying file pointer - - public: - File(SdFile f, const char *name); // wraps an underlying SdFile - File(void); // 'empty' constructor - virtual size_t write(uint8_t); - virtual size_t write(const uint8_t *buf, size_t size); - virtual int availableForWrite(); - virtual int read(); - virtual int peek(); - virtual int available(); - virtual void flush(); - int read(void *buf, uint16_t nbyte); - boolean seek(uint32_t pos); - uint32_t position(); - uint32_t size(); - void close(); - operator bool(); - char * name(); - - boolean isDirectory(void); - File openNextFile(uint8_t mode = O_RDONLY); - void rewindDirectory(void); - - using Print::write; - }; - - class SDClass { - - private: - // These are required for initialisation and use of sdfatlib - Sd2Card card; - SdVolume volume; - SdFile root; - - // my quick&dirty iterator, should be replaced - SdFile getParentDir(const char *filepath, int *indx); - public: - // This needs to be called to set up the connection to the SD card - // before other methods are used. - boolean begin(uint8_t csPin = SD_CHIP_SELECT_PIN); - boolean begin(uint32_t clock, uint8_t csPin); - - //call this when a card is removed. It will allow you to insert and initialise a new card. - void end(); - - // Open the specified file/directory with the supplied mode (e.g. read or - // write, etc). Returns a File object for interacting with the file. - // Note that currently only one file can be open at a time. - File open(const char *filename, uint8_t mode = FILE_READ); - File open(const String &filename, uint8_t mode = FILE_READ) { - return open(filename.c_str(), mode); - } - - // Methods to determine if the requested file path exists. - boolean exists(const char *filepath); - boolean exists(const String &filepath) { - return exists(filepath.c_str()); - } - - // Create the requested directory heirarchy--if intermediate directories - // do not exist they will be created. - boolean mkdir(const char *filepath); - boolean mkdir(const String &filepath) { - return mkdir(filepath.c_str()); - } - - // Delete the file. - boolean remove(const char *filepath); - boolean remove(const String &filepath) { - return remove(filepath.c_str()); - } - - boolean rmdir(const char *filepath); - boolean rmdir(const String &filepath) { - return rmdir(filepath.c_str()); - } - - private: - - // This is used to determine the mode used to open a file - // it's here because it's the easiest place to pass the - // information through the directory walking function. But - // it's probably not the best place for it. - // It shouldn't be set directly--it is set via the parameters to `open`. - int fileOpenMode; - - friend class File; - friend boolean callback_openPath(SdFile&, const char *, boolean, void *); - }; - - extern SDClass SD; - -}; - -// We enclose File and SD classes in namespace SDLib to avoid conflicts -// with others legacy libraries that redefines File class. - -// This ensure compatibility with sketches that uses only SD library -using namespace SDLib; - -// This allows sketches to use SDLib::File with other libraries (in the -// sketch you must use SDFile instead of File to disambiguate) -typedef SDLib::File SDFile; -typedef SDLib::SDClass SDFileSystemClass; -#define SDFileSystem SDLib::SD - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/FatStructs.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/FatStructs.h deleted file mode 100755 index 84c1cc7..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/FatStructs.h +++ /dev/null @@ -1,418 +0,0 @@ -/* Arduino SdFat Library - Copyright (C) 2009 by William Greiman - - This file is part of the Arduino SdFat Library - - This Library 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 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with the Arduino SdFat Library. If not, see - . -*/ -#ifndef FatStructs_h -#define FatStructs_h -/** - \file - FAT file structures -*/ -/* - mostly from Microsoft document fatgen103.doc - http://www.microsoft.com/whdc/system/platform/firmware/fatgen.mspx -*/ -//------------------------------------------------------------------------------ -/** Value for byte 510 of boot block or MBR */ -uint8_t const BOOTSIG0 = 0X55; -/** Value for byte 511 of boot block or MBR */ -uint8_t const BOOTSIG1 = 0XAA; -//------------------------------------------------------------------------------ -/** - \struct partitionTable - \brief MBR partition table entry - - A partition table entry for a MBR formatted storage device. - The MBR partition table has four entries. -*/ -struct partitionTable { - /** - Boot Indicator . Indicates whether the volume is the active - partition. Legal values include: 0X00. Do not use for booting. - 0X80 Active partition. - */ - uint8_t boot; - /** - Head part of Cylinder-head-sector address of the first block in - the partition. Legal values are 0-255. Only used in old PC BIOS. - */ - uint8_t beginHead; - /** - Sector part of Cylinder-head-sector address of the first block in - the partition. Legal values are 1-63. Only used in old PC BIOS. - */ - unsigned beginSector : 6; - /** High bits cylinder for first block in partition. */ - unsigned beginCylinderHigh : 2; - /** - Combine beginCylinderLow with beginCylinderHigh. Legal values - are 0-1023. Only used in old PC BIOS. - */ - uint8_t beginCylinderLow; - /** - Partition type. See defines that begin with PART_TYPE_ for - some Microsoft partition types. - */ - uint8_t type; - /** - head part of cylinder-head-sector address of the last sector in the - partition. Legal values are 0-255. Only used in old PC BIOS. - */ - uint8_t endHead; - /** - Sector part of cylinder-head-sector address of the last sector in - the partition. Legal values are 1-63. Only used in old PC BIOS. - */ - unsigned endSector : 6; - /** High bits of end cylinder */ - unsigned endCylinderHigh : 2; - /** - Combine endCylinderLow with endCylinderHigh. Legal values - are 0-1023. Only used in old PC BIOS. - */ - uint8_t endCylinderLow; - /** Logical block address of the first block in the partition. */ - uint32_t firstSector; - /** Length of the partition, in blocks. */ - uint32_t totalSectors; -} __attribute__((packed)); -/** Type name for partitionTable */ -typedef struct partitionTable part_t; -//------------------------------------------------------------------------------ -/** - \struct masterBootRecord - - \brief Master Boot Record - - The first block of a storage device that is formatted with a MBR. -*/ -struct masterBootRecord { - /** Code Area for master boot program. */ - uint8_t codeArea[440]; - /** Optional WindowsNT disk signature. May contain more boot code. */ - uint32_t diskSignature; - /** Usually zero but may be more boot code. */ - uint16_t usuallyZero; - /** Partition tables. */ - part_t part[4]; - /** First MBR signature byte. Must be 0X55 */ - uint8_t mbrSig0; - /** Second MBR signature byte. Must be 0XAA */ - uint8_t mbrSig1; -} __attribute__((packed)); -/** Type name for masterBootRecord */ -typedef struct masterBootRecord mbr_t; -//------------------------------------------------------------------------------ -/** - \struct biosParmBlock - - \brief BIOS parameter block - - The BIOS parameter block describes the physical layout of a FAT volume. -*/ -struct biosParmBlock { - /** - Count of bytes per sector. This value may take on only the - following values: 512, 1024, 2048 or 4096 - */ - uint16_t bytesPerSector; - /** - Number of sectors per allocation unit. This value must be a - power of 2 that is greater than 0. The legal values are - 1, 2, 4, 8, 16, 32, 64, and 128. - */ - uint8_t sectorsPerCluster; - /** - Number of sectors before the first FAT. - This value must not be zero. - */ - uint16_t reservedSectorCount; - /** The count of FAT data structures on the volume. This field should - always contain the value 2 for any FAT volume of any type. - */ - uint8_t fatCount; - /** - For FAT12 and FAT16 volumes, this field contains the count of - 32-byte directory entries in the root directory. For FAT32 volumes, - this field must be set to 0. For FAT12 and FAT16 volumes, this - value should always specify a count that when multiplied by 32 - results in a multiple of bytesPerSector. FAT16 volumes should - use the value 512. - */ - uint16_t rootDirEntryCount; - /** - This field is the old 16-bit total count of sectors on the volume. - This count includes the count of all sectors in all four regions - of the volume. This field can be 0; if it is 0, then totalSectors32 - must be non-zero. For FAT32 volumes, this field must be 0. For - FAT12 and FAT16 volumes, this field contains the sector count, and - totalSectors32 is 0 if the total sector count fits - (is less than 0x10000). - */ - uint16_t totalSectors16; - /** - This dates back to the old MS-DOS 1.x media determination and is - no longer usually used for anything. 0xF8 is the standard value - for fixed (non-removable) media. For removable media, 0xF0 is - frequently used. Legal values are 0xF0 or 0xF8-0xFF. - */ - uint8_t mediaType; - /** - Count of sectors occupied by one FAT on FAT12/FAT16 volumes. - On FAT32 volumes this field must be 0, and sectorsPerFat32 - contains the FAT size count. - */ - uint16_t sectorsPerFat16; - /** Sectors per track for interrupt 0x13. Not used otherwise. */ - uint16_t sectorsPerTrtack; - /** Number of heads for interrupt 0x13. Not used otherwise. */ - uint16_t headCount; - /** - Count of hidden sectors preceding the partition that contains this - FAT volume. This field is generally only relevant for media - visible on interrupt 0x13. - */ - uint32_t hidddenSectors; - /** - This field is the new 32-bit total count of sectors on the volume. - This count includes the count of all sectors in all four regions - of the volume. This field can be 0; if it is 0, then - totalSectors16 must be non-zero. - */ - uint32_t totalSectors32; - /** - Count of sectors occupied by one FAT on FAT32 volumes. - */ - uint32_t sectorsPerFat32; - /** - This field is only defined for FAT32 media and does not exist on - FAT12 and FAT16 media. - Bits 0-3 -- Zero-based number of active FAT. - Only valid if mirroring is disabled. - Bits 4-6 -- Reserved. - Bit 7 -- 0 means the FAT is mirrored at runtime into all FATs. - -- 1 means only one FAT is active; it is the one referenced in bits 0-3. - Bits 8-15 -- Reserved. - */ - uint16_t fat32Flags; - /** - FAT32 version. High byte is major revision number. - Low byte is minor revision number. Only 0.0 define. - */ - uint16_t fat32Version; - /** - Cluster number of the first cluster of the root directory for FAT32. - This usually 2 but not required to be 2. - */ - uint32_t fat32RootCluster; - /** - Sector number of FSINFO structure in the reserved area of the - FAT32 volume. Usually 1. - */ - uint16_t fat32FSInfo; - /** - If non-zero, indicates the sector number in the reserved area - of the volume of a copy of the boot record. Usually 6. - No value other than 6 is recommended. - */ - uint16_t fat32BackBootBlock; - /** - Reserved for future expansion. Code that formats FAT32 volumes - should always set all of the bytes of this field to 0. - */ - uint8_t fat32Reserved[12]; -} __attribute__((packed)); -/** Type name for biosParmBlock */ -typedef struct biosParmBlock bpb_t; -//------------------------------------------------------------------------------ -/** - \struct fat32BootSector - - \brief Boot sector for a FAT16 or FAT32 volume. - -*/ -struct fat32BootSector { - /** X86 jmp to boot program */ - uint8_t jmpToBootCode[3]; - /** informational only - don't depend on it */ - char oemName[8]; - /** BIOS Parameter Block */ - bpb_t bpb; - /** for int0x13 use value 0X80 for hard drive */ - uint8_t driveNumber; - /** used by Windows NT - should be zero for FAT */ - uint8_t reserved1; - /** 0X29 if next three fields are valid */ - uint8_t bootSignature; - /** usually generated by combining date and time */ - uint32_t volumeSerialNumber; - /** should match volume label in root dir */ - char volumeLabel[11]; - /** informational only - don't depend on it */ - char fileSystemType[8]; - /** X86 boot code */ - uint8_t bootCode[420]; - /** must be 0X55 */ - uint8_t bootSectorSig0; - /** must be 0XAA */ - uint8_t bootSectorSig1; -} __attribute__((packed)); -//------------------------------------------------------------------------------ -// End Of Chain values for FAT entries -/** FAT16 end of chain value used by Microsoft. */ -uint16_t const FAT16EOC = 0XFFFF; -/** Minimum value for FAT16 EOC. Use to test for EOC. */ -uint16_t const FAT16EOC_MIN = 0XFFF8; -/** FAT32 end of chain value used by Microsoft. */ -uint32_t const FAT32EOC = 0X0FFFFFFF; -/** Minimum value for FAT32 EOC. Use to test for EOC. */ -uint32_t const FAT32EOC_MIN = 0X0FFFFFF8; -/** Mask a for FAT32 entry. Entries are 28 bits. */ -uint32_t const FAT32MASK = 0X0FFFFFFF; - -/** Type name for fat32BootSector */ -typedef struct fat32BootSector fbs_t; -//------------------------------------------------------------------------------ -/** - \struct directoryEntry - \brief FAT short directory entry - - Short means short 8.3 name, not the entry size. - - Date Format. A FAT directory entry date stamp is a 16-bit field that is - basically a date relative to the MS-DOS epoch of 01/01/1980. Here is the - format (bit 0 is the LSB of the 16-bit word, bit 15 is the MSB of the - 16-bit word): - - Bits 9-15: Count of years from 1980, valid value range 0-127 - inclusive (1980-2107). - - Bits 5-8: Month of year, 1 = January, valid value range 1-12 inclusive. - - Bits 0-4: Day of month, valid value range 1-31 inclusive. - - Time Format. A FAT directory entry time stamp is a 16-bit field that has - a granularity of 2 seconds. Here is the format (bit 0 is the LSB of the - 16-bit word, bit 15 is the MSB of the 16-bit word). - - Bits 11-15: Hours, valid value range 0-23 inclusive. - - Bits 5-10: Minutes, valid value range 0-59 inclusive. - - Bits 0-4: 2-second count, valid value range 0-29 inclusive (0 - 58 seconds). - - The valid time range is from Midnight 00:00:00 to 23:59:58. -*/ -struct directoryEntry { - /** - Short 8.3 name. - The first eight bytes contain the file name with blank fill. - The last three bytes contain the file extension with blank fill. - */ - uint8_t name[11]; - /** Entry attributes. - - The upper two bits of the attribute byte are reserved and should - always be set to 0 when a file is created and never modified or - looked at after that. See defines that begin with DIR_ATT_. - */ - uint8_t attributes; - /** - Reserved for use by Windows NT. Set value to 0 when a file is - created and never modify or look at it after that. - */ - uint8_t reservedNT; - /** - The granularity of the seconds part of creationTime is 2 seconds - so this field is a count of tenths of a second and its valid - value range is 0-199 inclusive. (WHG note - seems to be hundredths) - */ - uint8_t creationTimeTenths; - /** Time file was created. */ - uint16_t creationTime; - /** Date file was created. */ - uint16_t creationDate; - /** - Last access date. Note that there is no last access time, only - a date. This is the date of last read or write. In the case of - a write, this should be set to the same date as lastWriteDate. - */ - uint16_t lastAccessDate; - /** - High word of this entry's first cluster number (always 0 for a - FAT12 or FAT16 volume). - */ - uint16_t firstClusterHigh; - /** Time of last write. File creation is considered a write. */ - uint16_t lastWriteTime; - /** Date of last write. File creation is considered a write. */ - uint16_t lastWriteDate; - /** Low word of this entry's first cluster number. */ - uint16_t firstClusterLow; - /** 32-bit unsigned holding this file's size in bytes. */ - uint32_t fileSize; -} __attribute__((packed)); -//------------------------------------------------------------------------------ -// Definitions for directory entries -// -/** Type name for directoryEntry */ -typedef struct directoryEntry dir_t; -/** escape for name[0] = 0XE5 */ -uint8_t const DIR_NAME_0XE5 = 0X05; -/** name[0] value for entry that is free after being "deleted" */ -uint8_t const DIR_NAME_DELETED = 0XE5; -/** name[0] value for entry that is free and no allocated entries follow */ -uint8_t const DIR_NAME_FREE = 0X00; -/** file is read-only */ -uint8_t const DIR_ATT_READ_ONLY = 0X01; -/** File should hidden in directory listings */ -uint8_t const DIR_ATT_HIDDEN = 0X02; -/** Entry is for a system file */ -uint8_t const DIR_ATT_SYSTEM = 0X04; -/** Directory entry contains the volume label */ -uint8_t const DIR_ATT_VOLUME_ID = 0X08; -/** Entry is for a directory */ -uint8_t const DIR_ATT_DIRECTORY = 0X10; -/** Old DOS archive bit for backup support */ -uint8_t const DIR_ATT_ARCHIVE = 0X20; -/** Test value for long name entry. Test is - (d->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME. */ -uint8_t const DIR_ATT_LONG_NAME = 0X0F; -/** Test mask for long name entry */ -uint8_t const DIR_ATT_LONG_NAME_MASK = 0X3F; -/** defined attribute bits */ -uint8_t const DIR_ATT_DEFINED_BITS = 0X3F; -/** Directory entry is part of a long name */ -static inline uint8_t DIR_IS_LONG_NAME(const dir_t* dir) { - return (dir->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME; -} -/** Mask for file/subdirectory tests */ -uint8_t const DIR_ATT_FILE_TYPE_MASK = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY); -/** Directory entry is for a file */ -static inline uint8_t DIR_IS_FILE(const dir_t* dir) { - return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == 0; -} -/** Directory entry is for a subdirectory */ -static inline uint8_t DIR_IS_SUBDIR(const dir_t* dir) { - return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == DIR_ATT_DIRECTORY; -} -/** Directory entry is for a file or subdirectory */ -static inline uint8_t DIR_IS_FILE_OR_SUBDIR(const dir_t* dir) { - return (dir->attributes & DIR_ATT_VOLUME_ID) == 0; -} -#endif // FatStructs_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2Card.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2Card.cpp deleted file mode 100755 index 7cfbe73..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2Card.cpp +++ /dev/null @@ -1,777 +0,0 @@ -/* Arduino Sd2Card Library - Copyright (C) 2009 by William Greiman - - This file is part of the Arduino Sd2Card Library - - This Library 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 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with the Arduino Sd2Card Library. If not, see - . -*/ -#define USE_SPI_LIB -#include -#include "Sd2Card.h" -//------------------------------------------------------------------------------ -#ifndef SOFTWARE_SPI -#ifdef USE_SPI_LIB - - #ifndef SDCARD_SPI - #define SDCARD_SPI SPI - #endif - - #include - static SPISettings settings; -#endif -// functions for hardware SPI -/** Send a byte to the card */ -static void spiSend(uint8_t b) { - #ifndef USE_SPI_LIB - SPDR = b; - while (!(SPSR & (1 << SPIF))) - ; - #else - SDCARD_SPI.transfer(b); - #endif -} -/** Receive a byte from the card */ -static uint8_t spiRec(void) { - #ifndef USE_SPI_LIB - spiSend(0XFF); - return SPDR; - #else - return SDCARD_SPI.transfer(0xFF); - #endif -} -#else // SOFTWARE_SPI -//------------------------------------------------------------------------------ -/** nop to tune soft SPI timing */ -#define nop asm volatile ("nop\n\t") -//------------------------------------------------------------------------------ -/** Soft SPI receive */ -uint8_t spiRec(void) { - uint8_t data = 0; - // no interrupts during byte receive - about 8 us - cli(); - // output pin high - like sending 0XFF - fastDigitalWrite(SPI_MOSI_PIN, HIGH); - - for (uint8_t i = 0; i < 8; i++) { - fastDigitalWrite(SPI_SCK_PIN, HIGH); - - // adjust so SCK is nice - nop; - nop; - - data <<= 1; - - if (fastDigitalRead(SPI_MISO_PIN)) { - data |= 1; - } - - fastDigitalWrite(SPI_SCK_PIN, LOW); - } - // enable interrupts - sei(); - return data; -} -//------------------------------------------------------------------------------ -/** Soft SPI send */ -void spiSend(uint8_t data) { - // no interrupts during byte send - about 8 us - cli(); - for (uint8_t i = 0; i < 8; i++) { - fastDigitalWrite(SPI_SCK_PIN, LOW); - - fastDigitalWrite(SPI_MOSI_PIN, data & 0X80); - - data <<= 1; - - fastDigitalWrite(SPI_SCK_PIN, HIGH); - } - // hold SCK high for a few ns - nop; - nop; - nop; - nop; - - fastDigitalWrite(SPI_SCK_PIN, LOW); - // enable interrupts - sei(); -} -#endif // SOFTWARE_SPI -//------------------------------------------------------------------------------ -// send command and return error code. Return zero for OK -uint8_t Sd2Card::cardCommand(uint8_t cmd, uint32_t arg) { - // end read if in partialBlockRead mode - readEnd(); - - // select card - chipSelectLow(); - - // wait up to 300 ms if busy - waitNotBusy(300); - - // send command - spiSend(cmd | 0x40); - - // send argument - for (int8_t s = 24; s >= 0; s -= 8) { - spiSend(arg >> s); - } - - // send CRC - uint8_t crc = 0XFF; - if (cmd == CMD0) { - crc = 0X95; // correct crc for CMD0 with arg 0 - } - if (cmd == CMD8) { - crc = 0X87; // correct crc for CMD8 with arg 0X1AA - } - spiSend(crc); - - // wait for response - for (uint8_t i = 0; ((status_ = spiRec()) & 0X80) && i != 0XFF; i++) - ; - return status_; -} -//------------------------------------------------------------------------------ -/** - Determine the size of an SD flash memory card. - - \return The number of 512 byte data blocks in the card - or zero if an error occurs. -*/ -uint32_t Sd2Card::cardSize(void) { - csd_t csd; - if (!readCSD(&csd)) { - return 0; - } - if (csd.v1.csd_ver == 0) { - uint8_t read_bl_len = csd.v1.read_bl_len; - uint16_t c_size = (csd.v1.c_size_high << 10) - | (csd.v1.c_size_mid << 2) | csd.v1.c_size_low; - uint8_t c_size_mult = (csd.v1.c_size_mult_high << 1) - | csd.v1.c_size_mult_low; - return (uint32_t)(c_size + 1) << (c_size_mult + read_bl_len - 7); - } else if (csd.v2.csd_ver == 1) { - uint32_t c_size = ((uint32_t)csd.v2.c_size_high << 16) - | (csd.v2.c_size_mid << 8) | csd.v2.c_size_low; - return (c_size + 1) << 10; - } else { - error(SD_CARD_ERROR_BAD_CSD); - return 0; - } -} -//------------------------------------------------------------------------------ -static uint8_t chip_select_asserted = 0; - -void Sd2Card::chipSelectHigh(void) { - digitalWrite(chipSelectPin_, HIGH); - #ifdef USE_SPI_LIB - if (chip_select_asserted) { - chip_select_asserted = 0; - SDCARD_SPI.endTransaction(); - } - #endif -} -//------------------------------------------------------------------------------ -void Sd2Card::chipSelectLow(void) { - #ifdef USE_SPI_LIB - if (!chip_select_asserted) { - chip_select_asserted = 1; - SDCARD_SPI.beginTransaction(settings); - } - #endif - digitalWrite(chipSelectPin_, LOW); -} -//------------------------------------------------------------------------------ -/** Erase a range of blocks. - - \param[in] firstBlock The address of the first block in the range. - \param[in] lastBlock The address of the last block in the range. - - \note This function requests the SD card to do a flash erase for a - range of blocks. The data on the card after an erase operation is - either 0 or 1, depends on the card vendor. The card must support - single block erase. - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. -*/ -uint8_t Sd2Card::erase(uint32_t firstBlock, uint32_t lastBlock) { - if (!eraseSingleBlockEnable()) { - error(SD_CARD_ERROR_ERASE_SINGLE_BLOCK); - goto fail; - } - if (type_ != SD_CARD_TYPE_SDHC) { - firstBlock <<= 9; - lastBlock <<= 9; - } - if (cardCommand(CMD32, firstBlock) - || cardCommand(CMD33, lastBlock) - || cardCommand(CMD38, 0)) { - error(SD_CARD_ERROR_ERASE); - goto fail; - } - if (!waitNotBusy(SD_ERASE_TIMEOUT)) { - error(SD_CARD_ERROR_ERASE_TIMEOUT); - goto fail; - } - chipSelectHigh(); - return true; - -fail: - chipSelectHigh(); - return false; -} -//------------------------------------------------------------------------------ -/** Determine if card supports single block erase. - - \return The value one, true, is returned if single block erase is supported. - The value zero, false, is returned if single block erase is not supported. -*/ -uint8_t Sd2Card::eraseSingleBlockEnable(void) { - csd_t csd; - return readCSD(&csd) ? csd.v1.erase_blk_en : 0; -} -//------------------------------------------------------------------------------ -/** - Initialize an SD flash memory card. - - \param[in] sckRateID SPI clock rate selector. See setSckRate(). - \param[in] chipSelectPin SD chip select pin number. - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. The reason for failure - can be determined by calling errorCode() and errorData(). -*/ -uint8_t Sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin) { - errorCode_ = inBlock_ = partialBlockRead_ = type_ = 0; - chipSelectPin_ = chipSelectPin; - // 16-bit init start time allows over a minute - unsigned int t0 = millis(); - uint32_t arg; - - // set pin modes - pinMode(chipSelectPin_, OUTPUT); - digitalWrite(chipSelectPin_, HIGH); - #ifndef USE_SPI_LIB - pinMode(SPI_MISO_PIN, INPUT); - pinMode(SPI_MOSI_PIN, OUTPUT); - pinMode(SPI_SCK_PIN, OUTPUT); - #endif - - #ifndef SOFTWARE_SPI - #ifndef USE_SPI_LIB - // SS must be in output mode even it is not chip select - pinMode(SS_PIN, OUTPUT); - digitalWrite(SS_PIN, HIGH); // disable any SPI device using hardware SS pin - // Enable SPI, Master, clock rate f_osc/128 - SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR1) | (1 << SPR0); - // clear double speed - SPSR &= ~(1 << SPI2X); - #else // USE_SPI_LIB - SDCARD_SPI.begin(); - settings = SPISettings(250000, MSBFIRST, SPI_MODE0); - #endif // USE_SPI_LIB - #endif // SOFTWARE_SPI - - // must supply min of 74 clock cycles with CS high. - #ifdef USE_SPI_LIB - SDCARD_SPI.beginTransaction(settings); - #endif - for (uint8_t i = 0; i < 10; i++) { - spiSend(0XFF); - } - #ifdef USE_SPI_LIB - SDCARD_SPI.endTransaction(); - #endif - - chipSelectLow(); - - // command to go idle in SPI mode - while ((status_ = cardCommand(CMD0, 0)) != R1_IDLE_STATE) { - unsigned int d = millis() - t0; - if (d > SD_INIT_TIMEOUT) { - error(SD_CARD_ERROR_CMD0); - goto fail; - } - } - // check SD version - if ((cardCommand(CMD8, 0x1AA) & R1_ILLEGAL_COMMAND)) { - type(SD_CARD_TYPE_SD1); - } else { - // only need last byte of r7 response - for (uint8_t i = 0; i < 4; i++) { - status_ = spiRec(); - } - if (status_ != 0XAA) { - error(SD_CARD_ERROR_CMD8); - goto fail; - } - type(SD_CARD_TYPE_SD2); - } - // initialize card and send host supports SDHC if SD2 - arg = type() == SD_CARD_TYPE_SD2 ? 0X40000000 : 0; - - while ((status_ = cardAcmd(ACMD41, arg)) != R1_READY_STATE) { - // check for timeout - unsigned int d = millis() - t0; - if (d > SD_INIT_TIMEOUT) { - error(SD_CARD_ERROR_ACMD41); - goto fail; - } - } - // if SD2 read OCR register to check for SDHC card - if (type() == SD_CARD_TYPE_SD2) { - if (cardCommand(CMD58, 0)) { - error(SD_CARD_ERROR_CMD58); - goto fail; - } - if ((spiRec() & 0XC0) == 0XC0) { - type(SD_CARD_TYPE_SDHC); - } - // discard rest of ocr - contains allowed voltage range - for (uint8_t i = 0; i < 3; i++) { - spiRec(); - } - } - chipSelectHigh(); - - #ifndef SOFTWARE_SPI - return setSckRate(sckRateID); - #else // SOFTWARE_SPI - return true; - #endif // SOFTWARE_SPI - -fail: - chipSelectHigh(); - return false; -} -//------------------------------------------------------------------------------ -/** - Enable or disable partial block reads. - - Enabling partial block reads improves performance by allowing a block - to be read over the SPI bus as several sub-blocks. Errors may occur - if the time between reads is too long since the SD card may timeout. - The SPI SS line will be held low until the entire block is read or - readEnd() is called. - - Use this for applications like the Adafruit Wave Shield. - - \param[in] value The value TRUE (non-zero) or FALSE (zero).) -*/ -void Sd2Card::partialBlockRead(uint8_t value) { - readEnd(); - partialBlockRead_ = value; -} -//------------------------------------------------------------------------------ -/** - Read a 512 byte block from an SD card device. - - \param[in] block Logical block to be read. - \param[out] dst Pointer to the location that will receive the data. - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. -*/ -uint8_t Sd2Card::readBlock(uint32_t block, uint8_t* dst) { - return readData(block, 0, 512, dst); -} -//------------------------------------------------------------------------------ -/** - Read part of a 512 byte block from an SD card. - - \param[in] block Logical block to be read. - \param[in] offset Number of bytes to skip at start of block - \param[out] dst Pointer to the location that will receive the data. - \param[in] count Number of bytes to read - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. -*/ -uint8_t Sd2Card::readData(uint32_t block, - uint16_t offset, uint16_t count, uint8_t* dst) { - if (count == 0) { - return true; - } - if ((count + offset) > 512) { - goto fail; - } - if (!inBlock_ || block != block_ || offset < offset_) { - block_ = block; - // use address if not SDHC card - if (type() != SD_CARD_TYPE_SDHC) { - block <<= 9; - } - if (cardCommand(CMD17, block)) { - error(SD_CARD_ERROR_CMD17); - goto fail; - } - if (!waitStartBlock()) { - goto fail; - } - offset_ = 0; - inBlock_ = 1; - } - - #ifdef OPTIMIZE_HARDWARE_SPI - // start first spi transfer - SPDR = 0XFF; - - // skip data before offset - for (; offset_ < offset; offset_++) { - while (!(SPSR & (1 << SPIF))) - ; - SPDR = 0XFF; - } - // transfer data - n = count - 1; - for (uint16_t i = 0; i < n; i++) { - while (!(SPSR & (1 << SPIF))) - ; - dst[i] = SPDR; - SPDR = 0XFF; - } - // wait for last byte - while (!(SPSR & (1 << SPIF))) - ; - dst[n] = SPDR; - - #else // OPTIMIZE_HARDWARE_SPI - - // skip data before offset - for (; offset_ < offset; offset_++) { - spiRec(); - } - // transfer data - for (uint16_t i = 0; i < count; i++) { - dst[i] = spiRec(); - } - #endif // OPTIMIZE_HARDWARE_SPI - - offset_ += count; - if (!partialBlockRead_ || offset_ >= 512) { - // read rest of data, checksum and set chip select high - readEnd(); - } - return true; - -fail: - chipSelectHigh(); - return false; -} -//------------------------------------------------------------------------------ -/** Skip remaining data in a block when in partial block read mode. */ -void Sd2Card::readEnd(void) { - if (inBlock_) { - // skip data and crc - #ifdef OPTIMIZE_HARDWARE_SPI - // optimize skip for hardware - SPDR = 0XFF; - while (offset_++ < 513) { - while (!(SPSR & (1 << SPIF))) - ; - SPDR = 0XFF; - } - // wait for last crc byte - while (!(SPSR & (1 << SPIF))) - ; - #else // OPTIMIZE_HARDWARE_SPI - while (offset_++ < 514) { - spiRec(); - } - #endif // OPTIMIZE_HARDWARE_SPI - chipSelectHigh(); - inBlock_ = 0; - } -} -//------------------------------------------------------------------------------ -/** read CID or CSR register */ -uint8_t Sd2Card::readRegister(uint8_t cmd, void* buf) { - uint8_t* dst = reinterpret_cast(buf); - if (cardCommand(cmd, 0)) { - error(SD_CARD_ERROR_READ_REG); - goto fail; - } - if (!waitStartBlock()) { - goto fail; - } - // transfer data - for (uint16_t i = 0; i < 16; i++) { - dst[i] = spiRec(); - } - spiRec(); // get first crc byte - spiRec(); // get second crc byte - chipSelectHigh(); - return true; - -fail: - chipSelectHigh(); - return false; -} -//------------------------------------------------------------------------------ -/** - Set the SPI clock rate. - - \param[in] sckRateID A value in the range [0, 6]. - - The SPI clock will be set to F_CPU/pow(2, 1 + sckRateID). The maximum - SPI rate is F_CPU/2 for \a sckRateID = 0 and the minimum rate is F_CPU/128 - for \a scsRateID = 6. - - \return The value one, true, is returned for success and the value zero, - false, is returned for an invalid value of \a sckRateID. -*/ -uint8_t Sd2Card::setSckRate(uint8_t sckRateID) { - if (sckRateID > 6) { - error(SD_CARD_ERROR_SCK_RATE); - return false; - } - #ifndef USE_SPI_LIB - // see avr processor datasheet for SPI register bit definitions - if ((sckRateID & 1) || sckRateID == 6) { - SPSR &= ~(1 << SPI2X); - } else { - SPSR |= (1 << SPI2X); - } - SPCR &= ~((1 << SPR1) | (1 << SPR0)); - SPCR |= (sckRateID & 4 ? (1 << SPR1) : 0) - | (sckRateID & 2 ? (1 << SPR0) : 0); - #else // USE_SPI_LIB - switch (sckRateID) { - case 0: settings = SPISettings(25000000, MSBFIRST, SPI_MODE0); break; - case 1: settings = SPISettings(4000000, MSBFIRST, SPI_MODE0); break; - case 2: settings = SPISettings(2000000, MSBFIRST, SPI_MODE0); break; - case 3: settings = SPISettings(1000000, MSBFIRST, SPI_MODE0); break; - case 4: settings = SPISettings(500000, MSBFIRST, SPI_MODE0); break; - case 5: settings = SPISettings(250000, MSBFIRST, SPI_MODE0); break; - default: settings = SPISettings(125000, MSBFIRST, SPI_MODE0); - } - #endif // USE_SPI_LIB - return true; -} -#ifdef USE_SPI_LIB -//------------------------------------------------------------------------------ -// set the SPI clock frequency -uint8_t Sd2Card::setSpiClock(uint32_t clock) { - settings = SPISettings(clock, MSBFIRST, SPI_MODE0); - return true; -} -#endif -//------------------------------------------------------------------------------ -// wait for card to go not busy -uint8_t Sd2Card::waitNotBusy(unsigned int timeoutMillis) { - unsigned int t0 = millis(); - unsigned int d; - do { - if (spiRec() == 0XFF) { - return true; - } - d = millis() - t0; - } while (d < timeoutMillis); - return false; -} -//------------------------------------------------------------------------------ -/** Wait for start block token */ -uint8_t Sd2Card::waitStartBlock(void) { - unsigned int t0 = millis(); - while ((status_ = spiRec()) == 0XFF) { - unsigned int d = millis() - t0; - if (d > SD_READ_TIMEOUT) { - error(SD_CARD_ERROR_READ_TIMEOUT); - goto fail; - } - } - if (status_ != DATA_START_BLOCK) { - error(SD_CARD_ERROR_READ); - goto fail; - } - return true; - -fail: - chipSelectHigh(); - return false; -} -//------------------------------------------------------------------------------ -/** - Writes a 512 byte block to an SD card. - - \param[in] blockNumber Logical block to be written. - \param[in] src Pointer to the location of the data to be written. - \param[in] blocking If the write should be blocking. - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. -*/ -uint8_t Sd2Card::writeBlock(uint32_t blockNumber, const uint8_t* src, uint8_t blocking) { - #if SD_PROTECT_BLOCK_ZERO - // don't allow write to first block - if (blockNumber == 0) { - error(SD_CARD_ERROR_WRITE_BLOCK_ZERO); - goto fail; - } - #endif // SD_PROTECT_BLOCK_ZERO - - // use address if not SDHC card - if (type() != SD_CARD_TYPE_SDHC) { - blockNumber <<= 9; - } - if (cardCommand(CMD24, blockNumber)) { - error(SD_CARD_ERROR_CMD24); - goto fail; - } - if (!writeData(DATA_START_BLOCK, src)) { - goto fail; - } - if (blocking) { - // wait for flash programming to complete - if (!waitNotBusy(SD_WRITE_TIMEOUT)) { - error(SD_CARD_ERROR_WRITE_TIMEOUT); - goto fail; - } - // response is r2 so get and check two bytes for nonzero - if (cardCommand(CMD13, 0) || spiRec()) { - error(SD_CARD_ERROR_WRITE_PROGRAMMING); - goto fail; - } - } - chipSelectHigh(); - return true; - -fail: - chipSelectHigh(); - return false; -} -//------------------------------------------------------------------------------ -/** Write one data block in a multiple block write sequence */ -uint8_t Sd2Card::writeData(const uint8_t* src) { - // wait for previous write to finish - if (!waitNotBusy(SD_WRITE_TIMEOUT)) { - error(SD_CARD_ERROR_WRITE_MULTIPLE); - chipSelectHigh(); - return false; - } - return writeData(WRITE_MULTIPLE_TOKEN, src); -} -//------------------------------------------------------------------------------ -// send one block of data for write block or write multiple blocks -uint8_t Sd2Card::writeData(uint8_t token, const uint8_t* src) { - #ifdef OPTIMIZE_HARDWARE_SPI - - // send data - optimized loop - SPDR = token; - - // send two byte per iteration - for (uint16_t i = 0; i < 512; i += 2) { - while (!(SPSR & (1 << SPIF))) - ; - SPDR = src[i]; - while (!(SPSR & (1 << SPIF))) - ; - SPDR = src[i + 1]; - } - - // wait for last data byte - while (!(SPSR & (1 << SPIF))) - ; - - #else // OPTIMIZE_HARDWARE_SPI - spiSend(token); - for (uint16_t i = 0; i < 512; i++) { - spiSend(src[i]); - } - #endif // OPTIMIZE_HARDWARE_SPI - spiSend(0xff); // dummy crc - spiSend(0xff); // dummy crc - - status_ = spiRec(); - if ((status_ & DATA_RES_MASK) != DATA_RES_ACCEPTED) { - error(SD_CARD_ERROR_WRITE); - chipSelectHigh(); - return false; - } - return true; -} -//------------------------------------------------------------------------------ -/** Start a write multiple blocks sequence. - - \param[in] blockNumber Address of first block in sequence. - \param[in] eraseCount The number of blocks to be pre-erased. - - \note This function is used with writeData() and writeStop() - for optimized multiple block writes. - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. -*/ -uint8_t Sd2Card::writeStart(uint32_t blockNumber, uint32_t eraseCount) { - #if SD_PROTECT_BLOCK_ZERO - // don't allow write to first block - if (blockNumber == 0) { - error(SD_CARD_ERROR_WRITE_BLOCK_ZERO); - goto fail; - } - #endif // SD_PROTECT_BLOCK_ZERO - // send pre-erase count - if (cardAcmd(ACMD23, eraseCount)) { - error(SD_CARD_ERROR_ACMD23); - goto fail; - } - // use address if not SDHC card - if (type() != SD_CARD_TYPE_SDHC) { - blockNumber <<= 9; - } - if (cardCommand(CMD25, blockNumber)) { - error(SD_CARD_ERROR_CMD25); - goto fail; - } - return true; - -fail: - chipSelectHigh(); - return false; -} -//------------------------------------------------------------------------------ -/** End a write multiple blocks sequence. - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. -*/ -uint8_t Sd2Card::writeStop(void) { - if (!waitNotBusy(SD_WRITE_TIMEOUT)) { - goto fail; - } - spiSend(STOP_TRAN_TOKEN); - if (!waitNotBusy(SD_WRITE_TIMEOUT)) { - goto fail; - } - chipSelectHigh(); - return true; - -fail: - error(SD_CARD_ERROR_STOP_TRAN); - chipSelectHigh(); - return false; -} -//------------------------------------------------------------------------------ -/** Check if the SD card is busy - - \return The value one, true, is returned when is busy and - the value zero, false, is returned for when is NOT busy. -*/ -uint8_t Sd2Card::isBusy(void) { - chipSelectLow(); - byte b = spiRec(); - chipSelectHigh(); - - return (b != 0XFF); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2Card.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2Card.h deleted file mode 100755 index 5d91ebf..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2Card.h +++ /dev/null @@ -1,273 +0,0 @@ -/* Arduino Sd2Card Library - Copyright (C) 2009 by William Greiman - - This file is part of the Arduino Sd2Card Library - - This Library 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 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with the Arduino Sd2Card Library. If not, see - . -*/ -#ifndef Sd2Card_h -#define Sd2Card_h -/** - \file - Sd2Card class -*/ -#include "Sd2PinMap.h" -#include "SdInfo.h" -/** Set SCK to max rate of F_CPU/2. See Sd2Card::setSckRate(). */ -uint8_t const SPI_FULL_SPEED = 0; -/** Set SCK rate to F_CPU/4. See Sd2Card::setSckRate(). */ -uint8_t const SPI_HALF_SPEED = 1; -/** Set SCK rate to F_CPU/8. Sd2Card::setSckRate(). */ -uint8_t const SPI_QUARTER_SPEED = 2; -/** - USE_SPI_LIB: if set, use the SPI library bundled with Arduino IDE, otherwise - run with a standalone driver for AVR. -*/ -#define USE_SPI_LIB -/** - Define MEGA_SOFT_SPI non-zero to use software SPI on Mega Arduinos. - Pins used are SS 10, MOSI 11, MISO 12, and SCK 13. - - MEGA_SOFT_SPI allows an unmodified Adafruit GPS Shield to be used - on Mega Arduinos. Software SPI works well with GPS Shield V1.1 - but many SD cards will fail with GPS Shield V1.0. -*/ -#define MEGA_SOFT_SPI 0 -//------------------------------------------------------------------------------ -#if MEGA_SOFT_SPI && (defined(__AVR_ATmega1280__)||defined(__AVR_ATmega2560__)) - #define SOFTWARE_SPI -#endif // MEGA_SOFT_SPI -//------------------------------------------------------------------------------ -// SPI pin definitions -// -#ifndef SOFTWARE_SPI - // hardware pin defs - - // include pins_arduino.h or variant.h depending on architecture, via Arduino.h - #include - - /** - SD Chip Select pin - - Warning if this pin is redefined the hardware SS will pin will be enabled - as an output by init(). An avr processor will not function as an SPI - master unless SS is set to output mode. - */ - #ifndef SDCARD_SS_PIN - /** The default chip select pin for the SD card is SS. */ - uint8_t const SD_CHIP_SELECT_PIN = SS; - #else - uint8_t const SD_CHIP_SELECT_PIN = SDCARD_SS_PIN; - #endif - - // The following three pins must not be redefined for hardware SPI, - // so ensure that they are taken from pins_arduino.h or variant.h, depending on architecture. - #ifndef SDCARD_MOSI_PIN - /** SPI Master Out Slave In pin */ - uint8_t const SPI_MOSI_PIN = MOSI; - /** SPI Master In Slave Out pin */ - uint8_t const SPI_MISO_PIN = MISO; - /** SPI Clock pin */ - uint8_t const SPI_SCK_PIN = SCK; - #else - uint8_t const SPI_MOSI_PIN = SDCARD_MOSI_PIN; - uint8_t const SPI_MISO_PIN = SDCARD_MISO_PIN; - uint8_t const SPI_SCK_PIN = SDCARD_SCK_PIN; - #endif - - /** optimize loops for hardware SPI */ - #ifndef USE_SPI_LIB - #define OPTIMIZE_HARDWARE_SPI - #endif - -#else // SOFTWARE_SPI - // define software SPI pins so Mega can use unmodified GPS Shield - /** SPI chip select pin */ - uint8_t const SD_CHIP_SELECT_PIN = 10; - /** SPI Master Out Slave In pin */ - uint8_t const SPI_MOSI_PIN = 11; - /** SPI Master In Slave Out pin */ - uint8_t const SPI_MISO_PIN = 12; - /** SPI Clock pin */ - uint8_t const SPI_SCK_PIN = 13; -#endif // SOFTWARE_SPI -//------------------------------------------------------------------------------ -/** Protect block zero from write if nonzero */ -#define SD_PROTECT_BLOCK_ZERO 1 -/** init timeout ms */ -unsigned int const SD_INIT_TIMEOUT = 2000; -/** erase timeout ms */ -unsigned int const SD_ERASE_TIMEOUT = 10000; -/** read timeout ms */ -unsigned int const SD_READ_TIMEOUT = 300; -/** write time out ms */ -unsigned int const SD_WRITE_TIMEOUT = 600; -//------------------------------------------------------------------------------ -// SD card errors -/** timeout error for command CMD0 */ -uint8_t const SD_CARD_ERROR_CMD0 = 0X1; -/** CMD8 was not accepted - not a valid SD card*/ -uint8_t const SD_CARD_ERROR_CMD8 = 0X2; -/** card returned an error response for CMD17 (read block) */ -uint8_t const SD_CARD_ERROR_CMD17 = 0X3; -/** card returned an error response for CMD24 (write block) */ -uint8_t const SD_CARD_ERROR_CMD24 = 0X4; -/** WRITE_MULTIPLE_BLOCKS command failed */ -uint8_t const SD_CARD_ERROR_CMD25 = 0X05; -/** card returned an error response for CMD58 (read OCR) */ -uint8_t const SD_CARD_ERROR_CMD58 = 0X06; -/** SET_WR_BLK_ERASE_COUNT failed */ -uint8_t const SD_CARD_ERROR_ACMD23 = 0X07; -/** card's ACMD41 initialization process timeout */ -uint8_t const SD_CARD_ERROR_ACMD41 = 0X08; -/** card returned a bad CSR version field */ -uint8_t const SD_CARD_ERROR_BAD_CSD = 0X09; -/** erase block group command failed */ -uint8_t const SD_CARD_ERROR_ERASE = 0X0A; -/** card not capable of single block erase */ -uint8_t const SD_CARD_ERROR_ERASE_SINGLE_BLOCK = 0X0B; -/** Erase sequence timed out */ -uint8_t const SD_CARD_ERROR_ERASE_TIMEOUT = 0X0C; -/** card returned an error token instead of read data */ -uint8_t const SD_CARD_ERROR_READ = 0X0D; -/** read CID or CSD failed */ -uint8_t const SD_CARD_ERROR_READ_REG = 0X0E; -/** timeout while waiting for start of read data */ -uint8_t const SD_CARD_ERROR_READ_TIMEOUT = 0X0F; -/** card did not accept STOP_TRAN_TOKEN */ -uint8_t const SD_CARD_ERROR_STOP_TRAN = 0X10; -/** card returned an error token as a response to a write operation */ -uint8_t const SD_CARD_ERROR_WRITE = 0X11; -/** attempt to write protected block zero */ -uint8_t const SD_CARD_ERROR_WRITE_BLOCK_ZERO = 0X12; -/** card did not go ready for a multiple block write */ -uint8_t const SD_CARD_ERROR_WRITE_MULTIPLE = 0X13; -/** card returned an error to a CMD13 status check after a write */ -uint8_t const SD_CARD_ERROR_WRITE_PROGRAMMING = 0X14; -/** timeout occurred during write programming */ -uint8_t const SD_CARD_ERROR_WRITE_TIMEOUT = 0X15; -/** incorrect rate selected */ -uint8_t const SD_CARD_ERROR_SCK_RATE = 0X16; -//------------------------------------------------------------------------------ -// card types -/** Standard capacity V1 SD card */ -uint8_t const SD_CARD_TYPE_SD1 = 1; -/** Standard capacity V2 SD card */ -uint8_t const SD_CARD_TYPE_SD2 = 2; -/** High Capacity SD card */ -uint8_t const SD_CARD_TYPE_SDHC = 3; -//------------------------------------------------------------------------------ -/** - \class Sd2Card - \brief Raw access to SD and SDHC flash memory cards. -*/ -class Sd2Card { - public: - /** Construct an instance of Sd2Card. */ - Sd2Card(void) : errorCode_(0), inBlock_(0), partialBlockRead_(0), type_(0) {} - uint32_t cardSize(void); - uint8_t erase(uint32_t firstBlock, uint32_t lastBlock); - uint8_t eraseSingleBlockEnable(void); - /** - \return error code for last error. See Sd2Card.h for a list of error codes. - */ - uint8_t errorCode(void) const { - return errorCode_; - } - /** \return error data for last error. */ - uint8_t errorData(void) const { - return status_; - } - /** - Initialize an SD flash memory card with default clock rate and chip - select pin. See sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin). - */ - uint8_t init(void) { - return init(SPI_FULL_SPEED, SD_CHIP_SELECT_PIN); - } - /** - Initialize an SD flash memory card with the selected SPI clock rate - and the default SD chip select pin. - See sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin). - */ - uint8_t init(uint8_t sckRateID) { - return init(sckRateID, SD_CHIP_SELECT_PIN); - } - uint8_t init(uint8_t sckRateID, uint8_t chipSelectPin); - void partialBlockRead(uint8_t value); - /** Returns the current value, true or false, for partial block read. */ - uint8_t partialBlockRead(void) const { - return partialBlockRead_; - } - uint8_t readBlock(uint32_t block, uint8_t* dst); - uint8_t readData(uint32_t block, - uint16_t offset, uint16_t count, uint8_t* dst); - /** - Read a cards CID register. The CID contains card identification - information such as Manufacturer ID, Product name, Product serial - number and Manufacturing date. */ - uint8_t readCID(cid_t* cid) { - return readRegister(CMD10, cid); - } - /** - Read a cards CSD register. The CSD contains Card-Specific Data that - provides information regarding access to the card's contents. */ - uint8_t readCSD(csd_t* csd) { - return readRegister(CMD9, csd); - } - void readEnd(void); - uint8_t setSckRate(uint8_t sckRateID); - #ifdef USE_SPI_LIB - uint8_t setSpiClock(uint32_t clock); - #endif - /** Return the card type: SD V1, SD V2 or SDHC */ - uint8_t type(void) const { - return type_; - } - uint8_t writeBlock(uint32_t blockNumber, const uint8_t* src, uint8_t blocking = 1); - uint8_t writeData(const uint8_t* src); - uint8_t writeStart(uint32_t blockNumber, uint32_t eraseCount); - uint8_t writeStop(void); - uint8_t isBusy(void); - private: - uint32_t block_; - uint8_t chipSelectPin_; - uint8_t errorCode_; - uint8_t inBlock_; - uint16_t offset_; - uint8_t partialBlockRead_; - uint8_t status_; - uint8_t type_; - // private functions - uint8_t cardAcmd(uint8_t cmd, uint32_t arg) { - cardCommand(CMD55, 0); - return cardCommand(cmd, arg); - } - uint8_t cardCommand(uint8_t cmd, uint32_t arg); - void error(uint8_t code) { - errorCode_ = code; - } - uint8_t readRegister(uint8_t cmd, void* buf); - uint8_t sendWriteCommand(uint32_t blockNumber, uint32_t eraseCount); - void chipSelectHigh(void); - void chipSelectLow(void); - void type(uint8_t value) { - type_ = value; - } - uint8_t waitNotBusy(unsigned int timeoutMillis); - uint8_t writeData(uint8_t token, const uint8_t* src); - uint8_t waitStartBlock(void); -}; -#endif // Sd2Card_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2PinMap.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2PinMap.h deleted file mode 100755 index 0609ffe..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/Sd2PinMap.h +++ /dev/null @@ -1,525 +0,0 @@ -/* Arduino SdFat Library - Copyright (C) 2010 by William Greiman - - This file is part of the Arduino SdFat Library - - This Library 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 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with the Arduino SdFat Library. If not, see - . -*/ -#if defined(__arm__) // Arduino Due Board follows - -#ifndef Sd2PinMap_h - #define Sd2PinMap_h - - #include - - uint8_t const SS_PIN = SS; - uint8_t const MOSI_PIN = MOSI; - uint8_t const MISO_PIN = MISO; - uint8_t const SCK_PIN = SCK; - -#endif // Sd2PinMap_h - -#elif defined(__AVR_ATmega4809__) // Arduino UNO WiFI Rev2 follows - -#ifndef Sd2PinMap_h - #define Sd2PinMap_h - - #include - - uint8_t const SS_PIN = SS; - uint8_t const MOSI_PIN = MOSI; - uint8_t const MISO_PIN = MISO; - uint8_t const SCK_PIN = SCK; - -#endif // Sd2PinMap_h - -#elif defined(__AVR__) // Other AVR based Boards follows - -// Warning this file was generated by a program. -#ifndef Sd2PinMap_h -#define Sd2PinMap_h -#include - -//------------------------------------------------------------------------------ -/** struct for mapping digital pins */ -struct pin_map_t { - volatile uint8_t* ddr; - volatile uint8_t* pin; - volatile uint8_t* port; - uint8_t bit; -}; -//------------------------------------------------------------------------------ -#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) -// Mega - -// Two Wire (aka I2C) ports -uint8_t const SDA_PIN = 20; -uint8_t const SCL_PIN = 21; - -// SPI port -uint8_t const SS_PIN = 53; -uint8_t const MOSI_PIN = 51; -uint8_t const MISO_PIN = 50; -uint8_t const SCK_PIN = 52; - -static const pin_map_t digitalPinMap[] = { - {&DDRE, &PINE, &PORTE, 0}, // E0 0 - {&DDRE, &PINE, &PORTE, 1}, // E1 1 - {&DDRE, &PINE, &PORTE, 4}, // E4 2 - {&DDRE, &PINE, &PORTE, 5}, // E5 3 - {&DDRG, &PING, &PORTG, 5}, // G5 4 - {&DDRE, &PINE, &PORTE, 3}, // E3 5 - {&DDRH, &PINH, &PORTH, 3}, // H3 6 - {&DDRH, &PINH, &PORTH, 4}, // H4 7 - {&DDRH, &PINH, &PORTH, 5}, // H5 8 - {&DDRH, &PINH, &PORTH, 6}, // H6 9 - {&DDRB, &PINB, &PORTB, 4}, // B4 10 - {&DDRB, &PINB, &PORTB, 5}, // B5 11 - {&DDRB, &PINB, &PORTB, 6}, // B6 12 - {&DDRB, &PINB, &PORTB, 7}, // B7 13 - {&DDRJ, &PINJ, &PORTJ, 1}, // J1 14 - {&DDRJ, &PINJ, &PORTJ, 0}, // J0 15 - {&DDRH, &PINH, &PORTH, 1}, // H1 16 - {&DDRH, &PINH, &PORTH, 0}, // H0 17 - {&DDRD, &PIND, &PORTD, 3}, // D3 18 - {&DDRD, &PIND, &PORTD, 2}, // D2 19 - {&DDRD, &PIND, &PORTD, 1}, // D1 20 - {&DDRD, &PIND, &PORTD, 0}, // D0 21 - {&DDRA, &PINA, &PORTA, 0}, // A0 22 - {&DDRA, &PINA, &PORTA, 1}, // A1 23 - {&DDRA, &PINA, &PORTA, 2}, // A2 24 - {&DDRA, &PINA, &PORTA, 3}, // A3 25 - {&DDRA, &PINA, &PORTA, 4}, // A4 26 - {&DDRA, &PINA, &PORTA, 5}, // A5 27 - {&DDRA, &PINA, &PORTA, 6}, // A6 28 - {&DDRA, &PINA, &PORTA, 7}, // A7 29 - {&DDRC, &PINC, &PORTC, 7}, // C7 30 - {&DDRC, &PINC, &PORTC, 6}, // C6 31 - {&DDRC, &PINC, &PORTC, 5}, // C5 32 - {&DDRC, &PINC, &PORTC, 4}, // C4 33 - {&DDRC, &PINC, &PORTC, 3}, // C3 34 - {&DDRC, &PINC, &PORTC, 2}, // C2 35 - {&DDRC, &PINC, &PORTC, 1}, // C1 36 - {&DDRC, &PINC, &PORTC, 0}, // C0 37 - {&DDRD, &PIND, &PORTD, 7}, // D7 38 - {&DDRG, &PING, &PORTG, 2}, // G2 39 - {&DDRG, &PING, &PORTG, 1}, // G1 40 - {&DDRG, &PING, &PORTG, 0}, // G0 41 - {&DDRL, &PINL, &PORTL, 7}, // L7 42 - {&DDRL, &PINL, &PORTL, 6}, // L6 43 - {&DDRL, &PINL, &PORTL, 5}, // L5 44 - {&DDRL, &PINL, &PORTL, 4}, // L4 45 - {&DDRL, &PINL, &PORTL, 3}, // L3 46 - {&DDRL, &PINL, &PORTL, 2}, // L2 47 - {&DDRL, &PINL, &PORTL, 1}, // L1 48 - {&DDRL, &PINL, &PORTL, 0}, // L0 49 - {&DDRB, &PINB, &PORTB, 3}, // B3 50 - {&DDRB, &PINB, &PORTB, 2}, // B2 51 - {&DDRB, &PINB, &PORTB, 1}, // B1 52 - {&DDRB, &PINB, &PORTB, 0}, // B0 53 - {&DDRF, &PINF, &PORTF, 0}, // F0 54 - {&DDRF, &PINF, &PORTF, 1}, // F1 55 - {&DDRF, &PINF, &PORTF, 2}, // F2 56 - {&DDRF, &PINF, &PORTF, 3}, // F3 57 - {&DDRF, &PINF, &PORTF, 4}, // F4 58 - {&DDRF, &PINF, &PORTF, 5}, // F5 59 - {&DDRF, &PINF, &PORTF, 6}, // F6 60 - {&DDRF, &PINF, &PORTF, 7}, // F7 61 - {&DDRK, &PINK, &PORTK, 0}, // K0 62 - {&DDRK, &PINK, &PORTK, 1}, // K1 63 - {&DDRK, &PINK, &PORTK, 2}, // K2 64 - {&DDRK, &PINK, &PORTK, 3}, // K3 65 - {&DDRK, &PINK, &PORTK, 4}, // K4 66 - {&DDRK, &PINK, &PORTK, 5}, // K5 67 - {&DDRK, &PINK, &PORTK, 6}, // K6 68 - {&DDRK, &PINK, &PORTK, 7} // K7 69 -}; -//------------------------------------------------------------------------------ -#elif (defined(__AVR_ATmega644P__) || defined(__AVR_ATmega1284P__)) && defined(CORE_MICRODUINO) -// Microduino Core+ - -// Two Wire (aka I2C) ports -uint8_t const SDA_PIN = 20; -uint8_t const SCL_PIN = 21; - -// SPI port -uint8_t const SS_PIN = 10; -uint8_t const MOSI_PIN = 11; -uint8_t const MISO_PIN = 12; -uint8_t const SCK_PIN = 13; - -static const pin_map_t digitalPinMap[] = { - {&DDRD, &PIND, &PORTD, 0}, // D0 PD0 - {&DDRD, &PIND, &PORTD, 1}, // D1 PD1 - {&DDRD, &PIND, &PORTD, 2}, // D2 PD2 - {&DDRD, &PIND, &PORTD, 3}, // D3 PD3 - {&DDRB, &PINB, &PORTB, 0}, // D4 PB0 - {&DDRB, &PINB, &PORTB, 1}, // D5 PB1 - {&DDRB, &PINB, &PORTB, 2}, // D6 PB2 - {&DDRB, &PINB, &PORTB, 3}, // D7 PB3 - {&DDRD, &PIND, &PORTD, 6}, // D8 PD6 - {&DDRD, &PIND, &PORTD, 5}, // D9 PD5 - {&DDRB, &PINB, &PORTB, 4}, // D10 PB4 - {&DDRB, &PINB, &PORTB, 5}, // D11 PB5 - {&DDRB, &PINB, &PORTB, 6}, // D12 PB6 - {&DDRB, &PINB, &PORTB, 7}, // D13 PB7 - {&DDRC, &PINC, &PORTC, 7}, // D14 PC7 - {&DDRC, &PINC, &PORTC, 6}, // D15 PC6 - {&DDRC, &PINC, &PORTC, 5}, // D16 PC5 - {&DDRC, &PINC, &PORTC, 4}, // D17 PC4 - {&DDRC, &PINC, &PORTC, 3}, // D18 PC3 - {&DDRC, &PINC, &PORTC, 2}, // D19 PC2 - {&DDRC, &PINC, &PORTC, 1}, // D20 PC1 - {&DDRC, &PINC, &PORTC, 0}, // D21 PC0 - {&DDRD, &PIND, &PORTD, 4}, // D22 PD4 - {&DDRD, &PIND, &PORTD, 7}, // D23 PD7 - {&DDRA, &PINA, &PORTA, 7}, // D24 PA7 - {&DDRA, &PINA, &PORTA, 6}, // D25 PA6 - {&DDRA, &PINA, &PORTA, 5}, // D26 PA5 - {&DDRA, &PINA, &PORTA, 4}, // D27 PA4 - {&DDRA, &PINA, &PORTA, 3}, // D28 PA3 - {&DDRA, &PINA, &PORTA, 2}, // D29 PA2 - {&DDRA, &PINA, &PORTA, 1}, // D30 PA1 - {&DDRA, &PINA, &PORTA, 0} // D31 PA0 -}; -//------------------------------------------------------------------------------ -#elif defined(__AVR_ATmega128RFA1__) && defined(CORE_MICRODUINO) -// Microduino Core RF - -// Two Wire (aka I2C) ports -uint8_t const SDA_PIN = 18; -uint8_t const SCL_PIN = 19; - -// SPI port -uint8_t const SS_PIN = 10; -uint8_t const MOSI_PIN = 11; -uint8_t const MISO_PIN = 12; -uint8_t const SCK_PIN = 13; - -static const pin_map_t digitalPinMap[] = { - {&DDRD, &PINE, &PORTE, 0}, // D0 PE0 - {&DDRD, &PINE, &PORTE, 1}, // D1 PE1 - {&DDRD, &PIND, &PORTD, 2}, // D2 PD2 - {&DDRD, &PIND, &PORTD, 3}, // D3 PD3 - {&DDRB, &PINE, &PORTE, 3}, // D4 PE3 - {&DDRB, &PINE, &PORTE, 4}, // D5 PE4 - {&DDRB, &PINE, &PORTE, 5}, // D6 PE5 - {&DDRB, &PINB, &PORTB, 7}, // D7 PB7 - {&DDRD, &PINB, &PORTB, 6}, // D8 PB6 - {&DDRD, &PINB, &PORTB, 5}, // D9 PB5 - {&DDRB, &PINB, &PORTB, 4}, // D10 PB4 - {&DDRB, &PINB, &PORTB, 2}, // D11 PB2 - {&DDRB, &PINB, &PORTB, 3}, // D12 PB3 - {&DDRB, &PINB, &PORTB, 1}, // D13 PB1 - {&DDRF, &PINF, &PORTF, 7}, // D14 PF7 - {&DDRF, &PINF, &PORTF, 6}, // D15 PF6 - {&DDRF, &PINF, &PORTF, 5}, // D16 PF5 - {&DDRF, &PINF, &PORTF, 4}, // D17 PF4 - {&DDRD, &PIND, &PORTD, 1}, // D18 PD1 - {&DDRD, &PIND, &PORTD, 0}, // D19 PD0 - {&DDRF, &PINF, &PORTF, 3}, // D20 PF3 - {&DDRF, &PINF, &PORTF, 2}, // D21 PF2 -}; -//------------------------------------------------------------------------------ -#elif defined(__AVR_ATmega32U4__) && defined(CORE_MICRODUINO) -// Microduino Core USB - -// Two Wire (aka I2C) ports -uint8_t const SDA_PIN = 18; -uint8_t const SCL_PIN = 19; - -// SPI port -uint8_t const SS_PIN = 10; -uint8_t const MOSI_PIN = 11; -uint8_t const MISO_PIN = 12; -uint8_t const SCK_PIN = 13; - -static const pin_map_t digitalPinMap[] = { - {&DDRD, &PIND, &PORTD, 2}, // D0 - PD2 - {&DDRD, &PIND, &PORTD, 3}, // D1 - PD3 - {&DDRE, &PINE, &PORTE, 6}, // D2 - PE6 - {&DDRD, &PIND, &PORTD, 6}, // D3 - PD6 - {&DDRD, &PIND, &PORTD, 7}, // D4 - PD7 - {&DDRC, &PINC, &PORTC, 6}, // D5 - PC6 - {&DDRC, &PINC, &PORTC, 7}, // D6 - PC7 - {&DDRE, &PINE, &PORTE, 7}, // D7 - PE7 - {&DDRB, &PINB, &PORTB, 6}, // D8 - PB6 - {&DDRB, &PINB, &PORTB, 5}, // D9 - PB5 - {&DDRB, &PINB, &PORTB, 0}, // D10 - PB0 - {&DDRB, &PINB, &PORTB, 2}, // D11 - MOSI - PB2 - {&DDRB, &PINB, &PORTB, 3}, // D12 -MISO - PB3 - {&DDRB, &PINB, &PORTB, 1}, // D13 -SCK - PB1 - {&DDRF, &PINF, &PORTF, 7}, // D14 - A0 - PF7 - {&DDRF, &PINF, &PORTF, 6}, // D15 - A1 - PF6 - {&DDRF, &PINF, &PORTF, 5}, // D16 - A2 - PF5 - {&DDRF, &PINF, &PORTF, 4}, // D17 - A3 - PF4 - {&DDRD, &PIND, &PORTD, 1}, // D18 - PD1 - {&DDRD, &PIND, &PORTD, 0}, // D19 - PD0 - {&DDRF, &PINF, &PORTF, 1}, // D20 - A6 - PF1 - {&DDRF, &PINF, &PORTF, 0}, // D21 - A7 - PF0 -}; -//------------------------------------------------------------------------------ -#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) -// Sanguino - -// Two Wire (aka I2C) ports -uint8_t const SDA_PIN = 17; -uint8_t const SCL_PIN = 18; - -// SPI port -uint8_t const SS_PIN = 4; -uint8_t const MOSI_PIN = 5; -uint8_t const MISO_PIN = 6; -uint8_t const SCK_PIN = 7; - -static const pin_map_t digitalPinMap[] = { - {&DDRB, &PINB, &PORTB, 0}, // B0 0 - {&DDRB, &PINB, &PORTB, 1}, // B1 1 - {&DDRB, &PINB, &PORTB, 2}, // B2 2 - {&DDRB, &PINB, &PORTB, 3}, // B3 3 - {&DDRB, &PINB, &PORTB, 4}, // B4 4 - {&DDRB, &PINB, &PORTB, 5}, // B5 5 - {&DDRB, &PINB, &PORTB, 6}, // B6 6 - {&DDRB, &PINB, &PORTB, 7}, // B7 7 - {&DDRD, &PIND, &PORTD, 0}, // D0 8 - {&DDRD, &PIND, &PORTD, 1}, // D1 9 - {&DDRD, &PIND, &PORTD, 2}, // D2 10 - {&DDRD, &PIND, &PORTD, 3}, // D3 11 - {&DDRD, &PIND, &PORTD, 4}, // D4 12 - {&DDRD, &PIND, &PORTD, 5}, // D5 13 - {&DDRD, &PIND, &PORTD, 6}, // D6 14 - {&DDRD, &PIND, &PORTD, 7}, // D7 15 - {&DDRC, &PINC, &PORTC, 0}, // C0 16 - {&DDRC, &PINC, &PORTC, 1}, // C1 17 - {&DDRC, &PINC, &PORTC, 2}, // C2 18 - {&DDRC, &PINC, &PORTC, 3}, // C3 19 - {&DDRC, &PINC, &PORTC, 4}, // C4 20 - {&DDRC, &PINC, &PORTC, 5}, // C5 21 - {&DDRC, &PINC, &PORTC, 6}, // C6 22 - {&DDRC, &PINC, &PORTC, 7}, // C7 23 - {&DDRA, &PINA, &PORTA, 7}, // A7 24 - {&DDRA, &PINA, &PORTA, 6}, // A6 25 - {&DDRA, &PINA, &PORTA, 5}, // A5 26 - {&DDRA, &PINA, &PORTA, 4}, // A4 27 - {&DDRA, &PINA, &PORTA, 3}, // A3 28 - {&DDRA, &PINA, &PORTA, 2}, // A2 29 - {&DDRA, &PINA, &PORTA, 1}, // A1 30 - {&DDRA, &PINA, &PORTA, 0} // A0 31 -}; -//------------------------------------------------------------------------------ -#elif defined(__AVR_ATmega32U4__) -// Leonardo - -// Two Wire (aka I2C) ports -uint8_t const SDA_PIN = 2; -uint8_t const SCL_PIN = 3; - -// SPI port -uint8_t const SS_PIN = 17; -uint8_t const MOSI_PIN = 16; -uint8_t const MISO_PIN = 14; -uint8_t const SCK_PIN = 15; - -static const pin_map_t digitalPinMap[] = { - {&DDRD, &PIND, &PORTD, 2}, // D2 0 - {&DDRD, &PIND, &PORTD, 3}, // D3 1 - {&DDRD, &PIND, &PORTD, 1}, // D1 2 - {&DDRD, &PIND, &PORTD, 0}, // D0 3 - {&DDRD, &PIND, &PORTD, 4}, // D4 4 - {&DDRC, &PINC, &PORTC, 6}, // C6 5 - {&DDRD, &PIND, &PORTD, 7}, // D7 6 - {&DDRE, &PINE, &PORTE, 6}, // E6 7 - {&DDRB, &PINB, &PORTB, 4}, // B4 8 - {&DDRB, &PINB, &PORTB, 5}, // B5 9 - {&DDRB, &PINB, &PORTB, 6}, // B6 10 - {&DDRB, &PINB, &PORTB, 7}, // B7 11 - {&DDRD, &PIND, &PORTD, 6}, // D6 12 - {&DDRC, &PINC, &PORTC, 7}, // C7 13 - {&DDRB, &PINB, &PORTB, 3}, // B3 14 - {&DDRB, &PINB, &PORTB, 1}, // B1 15 - {&DDRB, &PINB, &PORTB, 2}, // B2 16 - {&DDRB, &PINB, &PORTB, 0}, // B0 17 - {&DDRF, &PINF, &PORTF, 7}, // F7 18 - {&DDRF, &PINF, &PORTF, 6}, // F6 19 - {&DDRF, &PINF, &PORTF, 5}, // F5 20 - {&DDRF, &PINF, &PORTF, 4}, // F4 21 - {&DDRF, &PINF, &PORTF, 1}, // F1 22 - {&DDRF, &PINF, &PORTF, 0}, // F0 23 -}; -//------------------------------------------------------------------------------ -#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) -// Teensy++ 1.0 & 2.0 - -// Two Wire (aka I2C) ports -uint8_t const SDA_PIN = 1; -uint8_t const SCL_PIN = 0; - -// SPI port -uint8_t const SS_PIN = 20; -uint8_t const MOSI_PIN = 22; -uint8_t const MISO_PIN = 23; -uint8_t const SCK_PIN = 21; - -static const pin_map_t digitalPinMap[] = { - {&DDRD, &PIND, &PORTD, 0}, // D0 0 - {&DDRD, &PIND, &PORTD, 1}, // D1 1 - {&DDRD, &PIND, &PORTD, 2}, // D2 2 - {&DDRD, &PIND, &PORTD, 3}, // D3 3 - {&DDRD, &PIND, &PORTD, 4}, // D4 4 - {&DDRD, &PIND, &PORTD, 5}, // D5 5 - {&DDRD, &PIND, &PORTD, 6}, // D6 6 - {&DDRD, &PIND, &PORTD, 7}, // D7 7 - {&DDRE, &PINE, &PORTE, 0}, // E0 8 - {&DDRE, &PINE, &PORTE, 1}, // E1 9 - {&DDRC, &PINC, &PORTC, 0}, // C0 10 - {&DDRC, &PINC, &PORTC, 1}, // C1 11 - {&DDRC, &PINC, &PORTC, 2}, // C2 12 - {&DDRC, &PINC, &PORTC, 3}, // C3 13 - {&DDRC, &PINC, &PORTC, 4}, // C4 14 - {&DDRC, &PINC, &PORTC, 5}, // C5 15 - {&DDRC, &PINC, &PORTC, 6}, // C6 16 - {&DDRC, &PINC, &PORTC, 7}, // C7 17 - {&DDRE, &PINE, &PORTE, 6}, // E6 18 - {&DDRE, &PINE, &PORTE, 7}, // E7 19 - {&DDRB, &PINB, &PORTB, 0}, // B0 20 - {&DDRB, &PINB, &PORTB, 1}, // B1 21 - {&DDRB, &PINB, &PORTB, 2}, // B2 22 - {&DDRB, &PINB, &PORTB, 3}, // B3 23 - {&DDRB, &PINB, &PORTB, 4}, // B4 24 - {&DDRB, &PINB, &PORTB, 5}, // B5 25 - {&DDRB, &PINB, &PORTB, 6}, // B6 26 - {&DDRB, &PINB, &PORTB, 7}, // B7 27 - {&DDRA, &PINA, &PORTA, 0}, // A0 28 - {&DDRA, &PINA, &PORTA, 1}, // A1 29 - {&DDRA, &PINA, &PORTA, 2}, // A2 30 - {&DDRA, &PINA, &PORTA, 3}, // A3 31 - {&DDRA, &PINA, &PORTA, 4}, // A4 32 - {&DDRA, &PINA, &PORTA, 5}, // A5 33 - {&DDRA, &PINA, &PORTA, 6}, // A6 34 - {&DDRA, &PINA, &PORTA, 7}, // A7 35 - {&DDRE, &PINE, &PORTE, 4}, // E4 36 - {&DDRE, &PINE, &PORTE, 5}, // E5 37 - {&DDRF, &PINF, &PORTF, 0}, // F0 38 - {&DDRF, &PINF, &PORTF, 1}, // F1 39 - {&DDRF, &PINF, &PORTF, 2}, // F2 40 - {&DDRF, &PINF, &PORTF, 3}, // F3 41 - {&DDRF, &PINF, &PORTF, 4}, // F4 42 - {&DDRF, &PINF, &PORTF, 5}, // F5 43 - {&DDRF, &PINF, &PORTF, 6}, // F6 44 - {&DDRF, &PINF, &PORTF, 7} // F7 45 -}; -//------------------------------------------------------------------------------ -#else // defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) -// 168 and 328 Arduinos - -// Two Wire (aka I2C) ports -uint8_t const SDA_PIN = 18; -uint8_t const SCL_PIN = 19; - -// SPI port -uint8_t const SS_PIN = 10; -uint8_t const MOSI_PIN = 11; -uint8_t const MISO_PIN = 12; -uint8_t const SCK_PIN = 13; - -static const pin_map_t digitalPinMap[] = { - {&DDRD, &PIND, &PORTD, 0}, // D0 0 - {&DDRD, &PIND, &PORTD, 1}, // D1 1 - {&DDRD, &PIND, &PORTD, 2}, // D2 2 - {&DDRD, &PIND, &PORTD, 3}, // D3 3 - {&DDRD, &PIND, &PORTD, 4}, // D4 4 - {&DDRD, &PIND, &PORTD, 5}, // D5 5 - {&DDRD, &PIND, &PORTD, 6}, // D6 6 - {&DDRD, &PIND, &PORTD, 7}, // D7 7 - {&DDRB, &PINB, &PORTB, 0}, // B0 8 - {&DDRB, &PINB, &PORTB, 1}, // B1 9 - {&DDRB, &PINB, &PORTB, 2}, // B2 10 - {&DDRB, &PINB, &PORTB, 3}, // B3 11 - {&DDRB, &PINB, &PORTB, 4}, // B4 12 - {&DDRB, &PINB, &PORTB, 5}, // B5 13 - {&DDRC, &PINC, &PORTC, 0}, // C0 14 - {&DDRC, &PINC, &PORTC, 1}, // C1 15 - {&DDRC, &PINC, &PORTC, 2}, // C2 16 - {&DDRC, &PINC, &PORTC, 3}, // C3 17 - {&DDRC, &PINC, &PORTC, 4}, // C4 18 - {&DDRC, &PINC, &PORTC, 5} // C5 19 -}; -#endif // defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) -//------------------------------------------------------------------------------ -static const uint8_t digitalPinCount = sizeof(digitalPinMap) / sizeof(pin_map_t); - -uint8_t badPinNumber(void) -__attribute__((error("Pin number is too large or not a constant"))); - -static inline __attribute__((always_inline)) -uint8_t getPinMode(uint8_t pin) { - if (__builtin_constant_p(pin) && pin < digitalPinCount) { - return (*digitalPinMap[pin].ddr >> digitalPinMap[pin].bit) & 1; - } else { - return badPinNumber(); - } -} -static inline __attribute__((always_inline)) -void setPinMode(uint8_t pin, uint8_t mode) { - if (__builtin_constant_p(pin) && pin < digitalPinCount) { - if (mode) { - *digitalPinMap[pin].ddr |= 1 << digitalPinMap[pin].bit; - } else { - *digitalPinMap[pin].ddr &= ~(1 << digitalPinMap[pin].bit); - } - } else { - badPinNumber(); - } -} -static inline __attribute__((always_inline)) -uint8_t fastDigitalRead(uint8_t pin) { - if (__builtin_constant_p(pin) && pin < digitalPinCount) { - return (*digitalPinMap[pin].pin >> digitalPinMap[pin].bit) & 1; - } else { - return badPinNumber(); - } -} -static inline __attribute__((always_inline)) -void fastDigitalWrite(uint8_t pin, uint8_t value) { - if (__builtin_constant_p(pin) && pin < digitalPinCount) { - if (value) { - *digitalPinMap[pin].port |= 1 << digitalPinMap[pin].bit; - } else { - *digitalPinMap[pin].port &= ~(1 << digitalPinMap[pin].bit); - } - } else { - badPinNumber(); - } -} -#endif // Sd2PinMap_h - -#elif defined (__CPU_ARC__) - -#if defined (__ARDUINO_ARC__) - // Two Wire (aka I2C) ports - uint8_t const SDA_PIN = 18; - uint8_t const SCL_PIN = 19; - - // SPI port - uint8_t const SS_PIN = 10; - uint8_t const MOSI_PIN = 11; - uint8_t const MISO_PIN = 12; - uint8_t const SCK_PIN = 13; - -#endif // Arduino ARC - -#else -#error Architecture or board not supported. -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFat.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFat.h deleted file mode 100755 index e57974d..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFat.h +++ /dev/null @@ -1,641 +0,0 @@ -/* Arduino SdFat Library - Copyright (C) 2009 by William Greiman - - This file is part of the Arduino SdFat Library - - This Library 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 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with the Arduino SdFat Library. If not, see - . -*/ -#ifndef SdFat_h -#define SdFat_h -/** - \file - SdFile and SdVolume classes -*/ -#if defined (__AVR__) || defined (__CPU_ARC__) - #include -#endif -#include "Sd2Card.h" -#include "FatStructs.h" -#include -//------------------------------------------------------------------------------ -/** - Allow use of deprecated functions if non-zero -*/ -#define ALLOW_DEPRECATED_FUNCTIONS 1 -//------------------------------------------------------------------------------ -// forward declaration since SdVolume is used in SdFile -class SdVolume; -//============================================================================== -// SdFile class - -#ifdef O_RDONLY //ARDUINO_ARCH_MBED -#undef O_READ -#undef O_RDONLY -#undef O_WRITE -#undef O_WRONLY -#undef O_RDWR -#undef O_ACCMODE -#undef O_APPEND -#undef O_SYNC -#undef O_CREAT -#undef O_EXCL -#undef O_TRUNC -#endif - -// flags for ls() -/** ls() flag to print modify date */ -uint8_t const LS_DATE = 1; -/** ls() flag to print file size */ -uint8_t const LS_SIZE = 2; -/** ls() flag for recursive list of subdirectories */ -uint8_t const LS_R = 4; - -// use the gnu style oflag in open() -/** open() oflag for reading */ -uint8_t const O_READ = 0X01; -/** open() oflag - same as O_READ */ -uint8_t const O_RDONLY = O_READ; -/** open() oflag for write */ -uint8_t const O_WRITE = 0X02; -/** open() oflag - same as O_WRITE */ -uint8_t const O_WRONLY = O_WRITE; -/** open() oflag for reading and writing */ -uint8_t const O_RDWR = (O_READ | O_WRITE); -/** open() oflag mask for access modes */ -uint8_t const O_ACCMODE = (O_READ | O_WRITE); -/** The file offset shall be set to the end of the file prior to each write. */ -uint8_t const O_APPEND = 0X04; -/** synchronous writes - call sync() after each write */ -uint8_t const O_SYNC = 0X08; -/** create the file if nonexistent */ -uint8_t const O_CREAT = 0X10; -/** If O_CREAT and O_EXCL are set, open() shall fail if the file exists */ -uint8_t const O_EXCL = 0X20; -/** truncate the file to zero length */ -uint8_t const O_TRUNC = 0X40; - -// flags for timestamp -/** set the file's last access date */ -uint8_t const T_ACCESS = 1; -/** set the file's creation date and time */ -uint8_t const T_CREATE = 2; -/** Set the file's write date and time */ -uint8_t const T_WRITE = 4; -// values for type_ -/** This SdFile has not been opened. */ -uint8_t const FAT_FILE_TYPE_CLOSED = 0; -/** SdFile for a file */ -uint8_t const FAT_FILE_TYPE_NORMAL = 1; -/** SdFile for a FAT16 root directory */ -uint8_t const FAT_FILE_TYPE_ROOT16 = 2; -/** SdFile for a FAT32 root directory */ -uint8_t const FAT_FILE_TYPE_ROOT32 = 3; -/** SdFile for a subdirectory */ -uint8_t const FAT_FILE_TYPE_SUBDIR = 4; -/** Test value for directory type */ -uint8_t const FAT_FILE_TYPE_MIN_DIR = FAT_FILE_TYPE_ROOT16; - -/** date field for FAT directory entry */ -static inline uint16_t FAT_DATE(uint16_t year, uint8_t month, uint8_t day) { - return (year - 1980) << 9 | month << 5 | day; -} -/** year part of FAT directory date field */ -static inline uint16_t FAT_YEAR(uint16_t fatDate) { - return 1980 + (fatDate >> 9); -} -/** month part of FAT directory date field */ -static inline uint8_t FAT_MONTH(uint16_t fatDate) { - return (fatDate >> 5) & 0XF; -} -/** day part of FAT directory date field */ -static inline uint8_t FAT_DAY(uint16_t fatDate) { - return fatDate & 0X1F; -} -/** time field for FAT directory entry */ -static inline uint16_t FAT_TIME(uint8_t hour, uint8_t minute, uint8_t second) { - return hour << 11 | minute << 5 | second >> 1; -} -/** hour part of FAT directory time field */ -static inline uint8_t FAT_HOUR(uint16_t fatTime) { - return fatTime >> 11; -} -/** minute part of FAT directory time field */ -static inline uint8_t FAT_MINUTE(uint16_t fatTime) { - return (fatTime >> 5) & 0X3F; -} -/** second part of FAT directory time field */ -static inline uint8_t FAT_SECOND(uint16_t fatTime) { - return 2 * (fatTime & 0X1F); -} -/** Default date for file timestamps is 1 Jan 2000 */ -uint16_t const FAT_DEFAULT_DATE = ((2000 - 1980) << 9) | (1 << 5) | 1; -/** Default time for file timestamp is 1 am */ -uint16_t const FAT_DEFAULT_TIME = (1 << 11); -//------------------------------------------------------------------------------ -/** - \class SdFile - \brief Access FAT16 and FAT32 files on SD and SDHC cards. -*/ -class SdFile : public Print { - public: - /** Create an instance of SdFile. */ - SdFile(void) : type_(FAT_FILE_TYPE_CLOSED) {} - /** - writeError is set to true if an error occurs during a write(). - Set writeError to false before calling print() and/or write() and check - for true after calls to print() and/or write(). - */ - //bool writeError; - /** - Cancel unbuffered reads for this file. - See setUnbufferedRead() - */ - void clearUnbufferedRead(void) { - flags_ &= ~F_FILE_UNBUFFERED_READ; - } - uint8_t close(void); - uint8_t contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock); - uint8_t createContiguous(SdFile* dirFile, - const char* fileName, uint32_t size); - /** \return The current cluster number for a file or directory. */ - uint32_t curCluster(void) const { - return curCluster_; - } - /** \return The current position for a file or directory. */ - uint32_t curPosition(void) const { - return curPosition_; - } - /** - Set the date/time callback function - - \param[in] dateTime The user's call back function. The callback - function is of the form: - - \code - void dateTime(uint16_t* date, uint16_t* time) { - uint16_t year; - uint8_t month, day, hour, minute, second; - - // User gets date and time from GPS or real-time clock here - - // return date using FAT_DATE macro to format fields - * *date = FAT_DATE(year, month, day); - - // return time using FAT_TIME macro to format fields - * *time = FAT_TIME(hour, minute, second); - } - \endcode - - Sets the function that is called when a file is created or when - a file's directory entry is modified by sync(). All timestamps, - access, creation, and modify, are set when a file is created. - sync() maintains the last access date and last modify date/time. - - See the timestamp() function. - */ - static void dateTimeCallback( - void (*dateTime)(uint16_t* date, uint16_t* time)) { - dateTime_ = dateTime; - } - /** - Cancel the date/time callback function. - */ - static void dateTimeCallbackCancel(void) { - // use explicit zero since NULL is not defined for Sanguino - dateTime_ = 0; - } - /** \return Address of the block that contains this file's directory. */ - uint32_t dirBlock(void) const { - return dirBlock_; - } - uint8_t dirEntry(dir_t* dir); - /** \return Index of this file's directory in the block dirBlock. */ - uint8_t dirIndex(void) const { - return dirIndex_; - } - static void dirName(const dir_t& dir, char* name); - /** \return The total number of bytes in a file or directory. */ - uint32_t fileSize(void) const { - return fileSize_; - } - /** \return The first cluster number for a file or directory. */ - uint32_t firstCluster(void) const { - return firstCluster_; - } - /** \return True if this is a SdFile for a directory else false. */ - uint8_t isDir(void) const { - return type_ >= FAT_FILE_TYPE_MIN_DIR; - } - /** \return True if this is a SdFile for a file else false. */ - uint8_t isFile(void) const { - return type_ == FAT_FILE_TYPE_NORMAL; - } - /** \return True if this is a SdFile for an open file/directory else false. */ - uint8_t isOpen(void) const { - return type_ != FAT_FILE_TYPE_CLOSED; - } - /** \return True if this is a SdFile for a subdirectory else false. */ - uint8_t isSubDir(void) const { - return type_ == FAT_FILE_TYPE_SUBDIR; - } - /** \return True if this is a SdFile for the root directory. */ - uint8_t isRoot(void) const { - return type_ == FAT_FILE_TYPE_ROOT16 || type_ == FAT_FILE_TYPE_ROOT32; - } - void ls(uint8_t flags = 0, uint8_t indent = 0); - uint8_t makeDir(SdFile* dir, const char* dirName); - uint8_t open(SdFile* dirFile, uint16_t index, uint8_t oflag); - uint8_t open(SdFile* dirFile, const char* fileName, uint8_t oflag); - - uint8_t openRoot(SdVolume* vol); - static void printDirName(const dir_t& dir, uint8_t width); - static void printFatDate(uint16_t fatDate); - static void printFatTime(uint16_t fatTime); - static void printTwoDigits(uint8_t v); - /** - Read the next byte from a file. - - \return For success read returns the next byte in the file as an int. - If an error occurs or end of file is reached -1 is returned. - */ - int16_t read(void) { - uint8_t b; - return read(&b, 1) == 1 ? b : -1; - } - int16_t read(void* buf, uint16_t nbyte); - int8_t readDir(dir_t* dir); - static uint8_t remove(SdFile* dirFile, const char* fileName); - uint8_t remove(void); - /** Set the file's current position to zero. */ - void rewind(void) { - curPosition_ = curCluster_ = 0; - } - uint8_t rmDir(void); - uint8_t rmRfStar(void); - /** Set the files position to current position + \a pos. See seekSet(). */ - uint8_t seekCur(uint32_t pos) { - return seekSet(curPosition_ + pos); - } - /** - Set the files current position to end of file. Useful to position - a file for append. See seekSet(). - */ - uint8_t seekEnd(void) { - return seekSet(fileSize_); - } - uint8_t seekSet(uint32_t pos); - /** - Use unbuffered reads to access this file. Used with Wave - Shield ISR. Used with Sd2Card::partialBlockRead() in WaveRP. - - Not recommended for normal applications. - */ - void setUnbufferedRead(void) { - if (isFile()) { - flags_ |= F_FILE_UNBUFFERED_READ; - } - } - uint8_t timestamp(uint8_t flag, uint16_t year, uint8_t month, uint8_t day, - uint8_t hour, uint8_t minute, uint8_t second); - uint8_t sync(uint8_t blocking = 1); - /** Type of this SdFile. You should use isFile() or isDir() instead of type() - if possible. - - \return The file or directory type. - */ - uint8_t type(void) const { - return type_; - } - uint8_t truncate(uint32_t size); - /** \return Unbuffered read flag. */ - uint8_t unbufferedRead(void) const { - return flags_ & F_FILE_UNBUFFERED_READ; - } - /** \return SdVolume that contains this file. */ - SdVolume* volume(void) const { - return vol_; - } - size_t write(uint8_t b); - size_t write(const void* buf, uint16_t nbyte); - size_t write(const char* str); - #ifdef __AVR__ - void write_P(PGM_P str); - void writeln_P(PGM_P str); - #endif - int availableForWrite(void); - //------------------------------------------------------------------------------ - #if ALLOW_DEPRECATED_FUNCTIONS - // Deprecated functions - suppress cpplint warnings with NOLINT comment - /** \deprecated Use: - uint8_t SdFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock); - */ - uint8_t contiguousRange(uint32_t& bgnBlock, uint32_t& endBlock) { // NOLINT - return contiguousRange(&bgnBlock, &endBlock); - } - /** \deprecated Use: - uint8_t SdFile::createContiguous(SdFile* dirFile, - const char* fileName, uint32_t size) - */ - uint8_t createContiguous(SdFile& dirFile, // NOLINT - const char* fileName, uint32_t size) { - return createContiguous(&dirFile, fileName, size); - } - - /** - \deprecated Use: - static void SdFile::dateTimeCallback( - void (*dateTime)(uint16_t* date, uint16_t* time)); - */ - static void dateTimeCallback( - void (*dateTime)(uint16_t& date, uint16_t& time)) { // NOLINT - oldDateTime_ = dateTime; - dateTime_ = dateTime ? oldToNew : 0; - } - /** \deprecated Use: uint8_t SdFile::dirEntry(dir_t* dir); */ - uint8_t dirEntry(dir_t& dir) { - return dirEntry(&dir); // NOLINT - } - /** \deprecated Use: - uint8_t SdFile::makeDir(SdFile* dir, const char* dirName); - */ - uint8_t makeDir(SdFile& dir, const char* dirName) { // NOLINT - return makeDir(&dir, dirName); - } - /** \deprecated Use: - uint8_t SdFile::open(SdFile* dirFile, const char* fileName, uint8_t oflag); - */ - uint8_t open(SdFile& dirFile, // NOLINT - const char* fileName, uint8_t oflag) { - return open(&dirFile, fileName, oflag); - } - /** \deprecated Do not use in new apps */ - uint8_t open(SdFile& dirFile, const char* fileName) { // NOLINT - return open(dirFile, fileName, O_RDWR); - } - /** \deprecated Use: - uint8_t SdFile::open(SdFile* dirFile, uint16_t index, uint8_t oflag); - */ - uint8_t open(SdFile& dirFile, uint16_t index, uint8_t oflag) { // NOLINT - return open(&dirFile, index, oflag); - } - /** \deprecated Use: uint8_t SdFile::openRoot(SdVolume* vol); */ - uint8_t openRoot(SdVolume& vol) { - return openRoot(&vol); // NOLINT - } - - /** \deprecated Use: int8_t SdFile::readDir(dir_t* dir); */ - int8_t readDir(dir_t& dir) { - return readDir(&dir); // NOLINT - } - /** \deprecated Use: - static uint8_t SdFile::remove(SdFile* dirFile, const char* fileName); - */ - static uint8_t remove(SdFile& dirFile, const char* fileName) { // NOLINT - return remove(&dirFile, fileName); - } - //------------------------------------------------------------------------------ - // rest are private - private: - static void (*oldDateTime_)(uint16_t& date, uint16_t& time); // NOLINT - static void oldToNew(uint16_t* date, uint16_t* time) { - uint16_t d; - uint16_t t; - oldDateTime_(d, t); - *date = d; - *time = t; - } - #endif // ALLOW_DEPRECATED_FUNCTIONS - private: - // bits defined in flags_ - // should be 0XF - static uint8_t const F_OFLAG = (O_ACCMODE | O_APPEND | O_SYNC); - // available bits - static uint8_t const F_FILE_NON_BLOCKING_WRITE = 0X10; - // a new cluster was added to the file - static uint8_t const F_FILE_CLUSTER_ADDED = 0X20; - // use unbuffered SD read - static uint8_t const F_FILE_UNBUFFERED_READ = 0X40; - // sync of directory entry required - static uint8_t const F_FILE_DIR_DIRTY = 0X80; - - // make sure F_OFLAG is ok - #if ((F_FILE_NON_BLOCKING_WRITE | F_FILE_CLUSTER_ADDED | F_FILE_UNBUFFERED_READ | F_FILE_DIR_DIRTY) & F_OFLAG) -#error flags_ bits conflict - #endif // flags_ bits - - // private data - uint8_t flags_; // See above for definition of flags_ bits - uint8_t type_; // type of file see above for values - uint32_t curCluster_; // cluster for current file position - uint32_t curPosition_; // current file position in bytes from beginning - uint32_t dirBlock_; // SD block that contains directory entry for file - uint8_t dirIndex_; // index of entry in dirBlock 0 <= dirIndex_ <= 0XF - uint32_t fileSize_; // file size in bytes - uint32_t firstCluster_; // first cluster of file - SdVolume* vol_; // volume where file is located - - // private functions - uint8_t addCluster(void); - uint8_t addDirCluster(void); - dir_t* cacheDirEntry(uint8_t action); - static void (*dateTime_)(uint16_t* date, uint16_t* time); - static uint8_t make83Name(const char* str, uint8_t* name); - uint8_t openCachedEntry(uint8_t cacheIndex, uint8_t oflags); - dir_t* readDirCache(void); -}; -//============================================================================== -// SdVolume class -/** - \brief Cache for an SD data block -*/ -union cache_t { - /** Used to access cached file data blocks. */ - uint8_t data[512]; - /** Used to access cached FAT16 entries. */ - uint16_t fat16[256]; - /** Used to access cached FAT32 entries. */ - uint32_t fat32[128]; - /** Used to access cached directory entries. */ - dir_t dir[16]; - /** Used to access a cached MasterBoot Record. */ - mbr_t mbr; - /** Used to access to a cached FAT boot sector. */ - fbs_t fbs; -}; -//------------------------------------------------------------------------------ -/** - \class SdVolume - \brief Access FAT16 and FAT32 volumes on SD and SDHC cards. -*/ -class SdVolume { - public: - /** Create an instance of SdVolume */ - SdVolume(void) : allocSearchStart_(2), fatType_(0) {} - /** Clear the cache and returns a pointer to the cache. Used by the WaveRP - recorder to do raw write to the SD card. Not for normal apps. - */ - static uint8_t* cacheClear(void) { - cacheFlush(); - cacheBlockNumber_ = 0XFFFFFFFF; - return cacheBuffer_.data; - } - /** - Initialize a FAT volume. Try partition one first then try super - floppy format. - - \param[in] dev The Sd2Card where the volume is located. - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. Reasons for - failure include not finding a valid partition, not finding a valid - FAT file system or an I/O error. - */ - uint8_t init(Sd2Card* dev) { - return init(dev, 1) ? true : init(dev, 0); - } - uint8_t init(Sd2Card* dev, uint8_t part); - - // inline functions that return volume info - /** \return The volume's cluster size in blocks. */ - uint8_t blocksPerCluster(void) const { - return blocksPerCluster_; - } - /** \return The number of blocks in one FAT. */ - uint32_t blocksPerFat(void) const { - return blocksPerFat_; - } - /** \return The total number of clusters in the volume. */ - uint32_t clusterCount(void) const { - return clusterCount_; - } - /** \return The shift count required to multiply by blocksPerCluster. */ - uint8_t clusterSizeShift(void) const { - return clusterSizeShift_; - } - /** \return The logical block number for the start of file data. */ - uint32_t dataStartBlock(void) const { - return dataStartBlock_; - } - /** \return The number of FAT structures on the volume. */ - uint8_t fatCount(void) const { - return fatCount_; - } - /** \return The logical block number for the start of the first FAT. */ - uint32_t fatStartBlock(void) const { - return fatStartBlock_; - } - /** \return The FAT type of the volume. Values are 12, 16 or 32. */ - uint8_t fatType(void) const { - return fatType_; - } - /** \return The number of entries in the root directory for FAT16 volumes. */ - uint32_t rootDirEntryCount(void) const { - return rootDirEntryCount_; - } - /** \return The logical block number for the start of the root directory - on FAT16 volumes or the first cluster number on FAT32 volumes. */ - uint32_t rootDirStart(void) const { - return rootDirStart_; - } - /** return a pointer to the Sd2Card object for this volume */ - static Sd2Card* sdCard(void) { - return sdCard_; - } - //------------------------------------------------------------------------------ - #if ALLOW_DEPRECATED_FUNCTIONS - // Deprecated functions - suppress cpplint warnings with NOLINT comment - /** \deprecated Use: uint8_t SdVolume::init(Sd2Card* dev); */ - uint8_t init(Sd2Card& dev) { - return init(&dev); // NOLINT - } - - /** \deprecated Use: uint8_t SdVolume::init(Sd2Card* dev, uint8_t vol); */ - uint8_t init(Sd2Card& dev, uint8_t part) { // NOLINT - return init(&dev, part); - } - #endif // ALLOW_DEPRECATED_FUNCTIONS - //------------------------------------------------------------------------------ - private: - // Allow SdFile access to SdVolume private data. - friend class SdFile; - - // value for action argument in cacheRawBlock to indicate read from cache - static uint8_t const CACHE_FOR_READ = 0; - // value for action argument in cacheRawBlock to indicate cache dirty - static uint8_t const CACHE_FOR_WRITE = 1; - - static cache_t cacheBuffer_; // 512 byte cache for device blocks - static uint32_t cacheBlockNumber_; // Logical number of block in the cache - static Sd2Card* sdCard_; // Sd2Card object for cache - static uint8_t cacheDirty_; // cacheFlush() will write block if true - static uint32_t cacheMirrorBlock_; // block number for mirror FAT - // - uint32_t allocSearchStart_; // start cluster for alloc search - uint8_t blocksPerCluster_; // cluster size in blocks - uint32_t blocksPerFat_; // FAT size in blocks - uint32_t clusterCount_; // clusters in one FAT - uint8_t clusterSizeShift_; // shift to convert cluster count to block count - uint32_t dataStartBlock_; // first data block number - uint8_t fatCount_; // number of FATs on volume - uint32_t fatStartBlock_; // start block for first FAT - uint8_t fatType_; // volume type (12, 16, OR 32) - uint16_t rootDirEntryCount_; // number of entries in FAT16 root dir - uint32_t rootDirStart_; // root start block for FAT16, cluster for FAT32 - //---------------------------------------------------------------------------- - uint8_t allocContiguous(uint32_t count, uint32_t* curCluster); - uint8_t blockOfCluster(uint32_t position) const { - return (position >> 9) & (blocksPerCluster_ - 1); - } - uint32_t clusterStartBlock(uint32_t cluster) const { - return dataStartBlock_ + ((cluster - 2) << clusterSizeShift_); - } - uint32_t blockNumber(uint32_t cluster, uint32_t position) const { - return clusterStartBlock(cluster) + blockOfCluster(position); - } - static uint8_t cacheFlush(uint8_t blocking = 1); - static uint8_t cacheMirrorBlockFlush(uint8_t blocking); - static uint8_t cacheRawBlock(uint32_t blockNumber, uint8_t action); - static void cacheSetDirty(void) { - cacheDirty_ |= CACHE_FOR_WRITE; - } - static uint8_t cacheZeroBlock(uint32_t blockNumber); - uint8_t chainSize(uint32_t beginCluster, uint32_t* size) const; - uint8_t fatGet(uint32_t cluster, uint32_t* value) const; - uint8_t fatPut(uint32_t cluster, uint32_t value); - uint8_t fatPutEOC(uint32_t cluster) { - return fatPut(cluster, 0x0FFFFFFF); - } - uint8_t freeChain(uint32_t cluster); - uint8_t isEOC(uint32_t cluster) const { - return cluster >= (fatType_ == 16 ? FAT16EOC_MIN : FAT32EOC_MIN); - } - uint8_t readBlock(uint32_t block, uint8_t* dst) { - return sdCard_->readBlock(block, dst); - } - uint8_t readData(uint32_t block, uint16_t offset, - uint16_t count, uint8_t* dst) { - return sdCard_->readData(block, offset, count, dst); - } - uint8_t writeBlock(uint32_t block, const uint8_t* dst, uint8_t blocking = 1) { - return sdCard_->writeBlock(block, dst, blocking); - } - uint8_t isBusy(void) { - return sdCard_->isBusy(); - } - uint8_t isCacheMirrorBlockDirty(void) { - return (cacheMirrorBlock_ != 0); - } -}; -#endif // SdFat_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFatUtil.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFatUtil.h deleted file mode 100755 index 4b93de8..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFatUtil.h +++ /dev/null @@ -1,77 +0,0 @@ -/* Arduino SdFat Library - Copyright (C) 2008 by William Greiman - - This file is part of the Arduino SdFat Library - - This Library 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 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with the Arduino SdFat Library. If not, see - . -*/ -#ifndef SdFatUtil_h -#define SdFatUtil_h -/** - \file - Useful utility functions. -*/ -#include -#ifdef __AVR__ - #include - /** Store and print a string in flash memory.*/ - #define PgmPrint(x) SerialPrint_P(PSTR(x)) - /** Store and print a string in flash memory followed by a CR/LF.*/ - #define PgmPrintln(x) SerialPrintln_P(PSTR(x)) - /** Defined so doxygen works for function definitions. */ -#endif -#define NOINLINE __attribute__((noinline,unused)) -#define UNUSEDOK __attribute__((unused)) -//------------------------------------------------------------------------------ -/** Return the number of bytes currently free in RAM. */ -static UNUSEDOK int FreeRam(void) { - extern int __bss_end; - extern int* __brkval; - int free_memory; - if (reinterpret_cast(__brkval) == 0) { - // if no heap use from end of bss section - free_memory = reinterpret_cast(&free_memory) - - reinterpret_cast(&__bss_end); - } else { - // use from top of stack to heap - free_memory = reinterpret_cast(&free_memory) - - reinterpret_cast(__brkval); - } - return free_memory; -} -#ifdef __AVR__ -//------------------------------------------------------------------------------ -/** - %Print a string in flash memory to the serial port. - - \param[in] str Pointer to string stored in flash memory. -*/ -static NOINLINE void SerialPrint_P(PGM_P str) { - for (uint8_t c; (c = pgm_read_byte(str)); str++) { - Serial.write(c); - } -} -//------------------------------------------------------------------------------ -/** - %Print a string in flash memory followed by a CR/LF. - - \param[in] str Pointer to string stored in flash memory. -*/ -static NOINLINE void SerialPrintln_P(PGM_P str) { - SerialPrint_P(str); - Serial.println(); -} -#endif // __AVR__ -#endif // #define SdFatUtil_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFatmainpage.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFatmainpage.h deleted file mode 100755 index 1e6d96f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFatmainpage.h +++ /dev/null @@ -1,202 +0,0 @@ -/* Arduino SdFat Library - Copyright (C) 2009 by William Greiman - - This file is part of the Arduino SdFat Library - - This Library 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 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with the Arduino SdFat Library. If not, see - . -*/ - -/** - \mainpage Arduino SdFat Library -
Copyright © 2009 by William Greiman -
- - \section Intro Introduction - The Arduino SdFat Library is a minimal implementation of FAT16 and FAT32 - file systems on SD flash memory cards. Standard SD and high capacity - SDHC cards are supported. - - The SdFat only supports short 8.3 names. - - The main classes in SdFat are Sd2Card, SdVolume, and SdFile. - - The Sd2Card class supports access to standard SD cards and SDHC cards. Most - applications will only need to call the Sd2Card::init() member function. - - The SdVolume class supports FAT16 and FAT32 partitions. Most applications - will only need to call the SdVolume::init() member function. - - The SdFile class provides file access functions such as open(), read(), - remove(), write(), close() and sync(). This class supports access to the root - directory and subdirectories. - - A number of example are provided in the SdFat/examples folder. These were - developed to test SdFat and illustrate its use. - - SdFat was developed for high speed data recording. SdFat was used to implement - an audio record/play class, WaveRP, for the Adafruit Wave Shield. This - application uses special Sd2Card calls to write to contiguous files in raw mode. - These functions reduce write latency so that audio can be recorded with the - small amount of RAM in the Arduino. - - \section SDcard SD\SDHC Cards - - Arduinos access SD cards using the cards SPI protocol. PCs, Macs, and - most consumer devices use the 4-bit parallel SD protocol. A card that - functions well on A PC or Mac may not work well on the Arduino. - - Most cards have good SPI read performance but cards vary widely in SPI - write performance. Write performance is limited by how efficiently the - card manages internal erase/remapping operations. The Arduino cannot - optimize writes to reduce erase operations because of its limit RAM. - - SanDisk cards generally have good write performance. They seem to have - more internal RAM buffering than other cards and therefore can limit - the number of flash erase operations that the Arduino forces due to its - limited RAM. - - \section Hardware Hardware Configuration - - SdFat was developed using an - Adafruit Industries - Wave Shield. - - The hardware interface to the SD card should not use a resistor based level - shifter. SdFat sets the SPI bus frequency to 8 MHz which results in signal - rise times that are too slow for the edge detectors in many newer SD card - controllers when resistor voltage dividers are used. - - The 5 to 3.3 V level shifter for 5 V Arduinos should be IC based like the - 74HC4050N based circuit shown in the file SdLevel.png. The Adafruit Wave Shield - uses a 74AHC125N. Gravitech sells SD and MicroSD Card Adapters based on the - 74LCX245. - - If you are using a resistor based level shifter and are having problems try - setting the SPI bus frequency to 4 MHz. This can be done by using - card.init(SPI_HALF_SPEED) to initialize the SD card. - - \section comment Bugs and Comments - - If you wish to report bugs or have comments, send email to fat16lib@sbcglobal.net. - - \section SdFatClass SdFat Usage - - SdFat uses a slightly restricted form of short names. - Only printable ASCII characters are supported. No characters with code point - values greater than 127 are allowed. Space is not allowed even though space - was allowed in the API of early versions of DOS. - - Short names are limited to 8 characters followed by an optional period (.) - and extension of up to 3 characters. The characters may be any combination - of letters and digits. The following special characters are also allowed: - - $ % ' - _ @ ~ ` ! ( ) { } ^ # & - - Short names are always converted to upper case and their original case - value is lost. - - \note - The Arduino Print class uses character - at a time writes so it was necessary to use a \link SdFile::sync() sync() \endlink - function to control when data is written to the SD card. - - \par - An application which writes to a file using \link Print::print() print()\endlink, - \link Print::println() println() \endlink - or \link SdFile::write write() \endlink must call \link SdFile::sync() sync() \endlink - at the appropriate time to force data and directory information to be written - to the SD Card. Data and directory information are also written to the SD card - when \link SdFile::close() close() \endlink is called. - - \par - Applications must use care calling \link SdFile::sync() sync() \endlink - since 2048 bytes of I/O is required to update file and - directory information. This includes writing the current data block, reading - the block that contains the directory entry for update, writing the directory - block back and reading back the current data block. - - It is possible to open a file with two or more instances of SdFile. A file may - be corrupted if data is written to the file by more than one instance of SdFile. - - \section HowTo How to format SD Cards as FAT Volumes - - You should use a freshly formatted SD card for best performance. FAT - file systems become slower if many files have been created and deleted. - This is because the directory entry for a deleted file is marked as deleted, - but is not deleted. When a new file is created, these entries must be scanned - before creating the file, a flaw in the FAT design. Also files can become - fragmented which causes reads and writes to be slower. - - Microsoft operating systems support removable media formatted with a - Master Boot Record, MBR, or formatted as a super floppy with a FAT Boot Sector - in block zero. - - Microsoft operating systems expect MBR formatted removable media - to have only one partition. The first partition should be used. - - Microsoft operating systems do not support partitioning SD flash cards. - If you erase an SD card with a program like KillDisk, Most versions of - Windows will format the card as a super floppy. - - The best way to restore an SD card's format is to use SDFormatter - which can be downloaded from: - - http://www.sdcard.org/consumers/formatter/ - - SDFormatter aligns flash erase boundaries with file - system structures which reduces write latency and file system overhead. - - SDFormatter does not have an option for FAT type so it may format - small cards as FAT12. - - After the MBR is restored by SDFormatter you may need to reformat small - cards that have been formatted FAT12 to force the volume type to be FAT16. - - If you reformat the SD card with an OS utility, choose a cluster size that - will result in: - - 4084 < CountOfClusters && CountOfClusters < 65525 - - The volume will then be FAT16. - - If you are formatting an SD card on OS X or Linux, be sure to use the first - partition. Format this partition with a cluster count in above range. - - \section References References - - Adafruit Industries: - - http://www.adafruit.com/ - - http://www.ladyada.net/make/waveshield/ - - The Arduino site: - - http://www.arduino.cc/ - - For more information about FAT file systems see: - - http://www.microsoft.com/whdc/system/platform/firmware/fatgen.mspx - - For information about using SD cards as SPI devices see: - - http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf - - The ATmega328 datasheet: - - http://www.atmel.com/dyn/resources/prod_documents/doc8161.pdf - - -*/ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFile.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFile.cpp deleted file mode 100755 index 18a1db6..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdFile.cpp +++ /dev/null @@ -1,1527 +0,0 @@ -/* Arduino SdFat Library - Copyright (C) 2009 by William Greiman - - This file is part of the Arduino SdFat Library - - This Library 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 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with the Arduino SdFat Library. If not, see - . -*/ -#include "SdFat.h" -#ifdef __AVR__ - #include -#endif -#include -//------------------------------------------------------------------------------ -// callback function for date/time -void (*SdFile::dateTime_)(uint16_t* date, uint16_t* time) = NULL; - -#if ALLOW_DEPRECATED_FUNCTIONS - // suppress cpplint warnings with NOLINT comment - void (*SdFile::oldDateTime_)(uint16_t& date, uint16_t& time) = NULL; // NOLINT -#endif // ALLOW_DEPRECATED_FUNCTIONS -//------------------------------------------------------------------------------ -// add a cluster to a file -uint8_t SdFile::addCluster() { - if (!vol_->allocContiguous(1, &curCluster_)) { - return false; - } - - // if first cluster of file link to directory entry - if (firstCluster_ == 0) { - firstCluster_ = curCluster_; - flags_ |= F_FILE_DIR_DIRTY; - } - flags_ |= F_FILE_CLUSTER_ADDED; - return true; -} -//------------------------------------------------------------------------------ -// Add a cluster to a directory file and zero the cluster. -// return with first block of cluster in the cache -uint8_t SdFile::addDirCluster(void) { - if (!addCluster()) { - return false; - } - - // zero data in cluster insure first cluster is in cache - uint32_t block = vol_->clusterStartBlock(curCluster_); - for (uint8_t i = vol_->blocksPerCluster_; i != 0; i--) { - if (!SdVolume::cacheZeroBlock(block + i - 1)) { - return false; - } - } - // Increase directory file size by cluster size - fileSize_ += 512UL << vol_->clusterSizeShift_; - return true; -} -//------------------------------------------------------------------------------ -// cache a file's directory entry -// return pointer to cached entry or null for failure -dir_t* SdFile::cacheDirEntry(uint8_t action) { - if (!SdVolume::cacheRawBlock(dirBlock_, action)) { - return NULL; - } - return SdVolume::cacheBuffer_.dir + dirIndex_; -} -//------------------------------------------------------------------------------ -/** - Close a file and force cached data and directory information - to be written to the storage device. - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. - Reasons for failure include no file is open or an I/O error. -*/ -uint8_t SdFile::close(void) { - if (!sync()) { - return false; - } - type_ = FAT_FILE_TYPE_CLOSED; - return true; -} -//------------------------------------------------------------------------------ -/** - Check for contiguous file and return its raw block range. - - \param[out] bgnBlock the first block address for the file. - \param[out] endBlock the last block address for the file. - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. - Reasons for failure include file is not contiguous, file has zero length - or an I/O error occurred. -*/ -uint8_t SdFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock) { - // error if no blocks - if (firstCluster_ == 0) { - return false; - } - - for (uint32_t c = firstCluster_; ; c++) { - uint32_t next; - if (!vol_->fatGet(c, &next)) { - return false; - } - - // check for contiguous - if (next != (c + 1)) { - // error if not end of chain - if (!vol_->isEOC(next)) { - return false; - } - *bgnBlock = vol_->clusterStartBlock(firstCluster_); - *endBlock = vol_->clusterStartBlock(c) - + vol_->blocksPerCluster_ - 1; - return true; - } - } -} -//------------------------------------------------------------------------------ -/** - Create and open a new contiguous file of a specified size. - - \note This function only supports short DOS 8.3 names. - See open() for more information. - - \param[in] dirFile The directory where the file will be created. - \param[in] fileName A valid DOS 8.3 file name. - \param[in] size The desired file size. - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. - Reasons for failure include \a fileName contains - an invalid DOS 8.3 file name, the FAT volume has not been initialized, - a file is already open, the file already exists, the root - directory is full or an I/O error. - -*/ -uint8_t SdFile::createContiguous(SdFile* dirFile, - const char* fileName, uint32_t size) { - // don't allow zero length file - if (size == 0) { - return false; - } - if (!open(dirFile, fileName, O_CREAT | O_EXCL | O_RDWR)) { - return false; - } - - // calculate number of clusters needed - uint32_t count = ((size - 1) >> (vol_->clusterSizeShift_ + 9)) + 1; - - // allocate clusters - if (!vol_->allocContiguous(count, &firstCluster_)) { - remove(); - return false; - } - fileSize_ = size; - - // insure sync() will update dir entry - flags_ |= F_FILE_DIR_DIRTY; - return sync(); -} -//------------------------------------------------------------------------------ -/** - Return a files directory entry - - \param[out] dir Location for return of the files directory entry. - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. -*/ -uint8_t SdFile::dirEntry(dir_t* dir) { - // make sure fields on SD are correct - if (!sync()) { - return false; - } - - // read entry - dir_t* p = cacheDirEntry(SdVolume::CACHE_FOR_READ); - if (!p) { - return false; - } - - // copy to caller's struct - memcpy(dir, p, sizeof(dir_t)); - return true; -} -//------------------------------------------------------------------------------ -/** - Format the name field of \a dir into the 13 byte array - \a name in standard 8.3 short name format. - - \param[in] dir The directory structure containing the name. - \param[out] name A 13 byte char array for the formatted name. -*/ -void SdFile::dirName(const dir_t& dir, char* name) { - uint8_t j = 0; - for (uint8_t i = 0; i < 11; i++) { - if (dir.name[i] == ' ') { - continue; - } - if (i == 8) { - name[j++] = '.'; - } - name[j++] = dir.name[i]; - } - name[j] = 0; -} -//------------------------------------------------------------------------------ -/** List directory contents to Serial. - - \param[in] flags The inclusive OR of - - LS_DATE - %Print file modification date - - LS_SIZE - %Print file size. - - LS_R - Recursive list of subdirectories. - - \param[in] indent Amount of space before file name. Used for recursive - list to indicate subdirectory level. -*/ -void SdFile::ls(uint8_t flags, uint8_t indent) { - dir_t* p; - - rewind(); - while ((p = readDirCache())) { - // done if past last used entry - if (p->name[0] == DIR_NAME_FREE) { - break; - } - - // skip deleted entry and entries for . and .. - if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') { - continue; - } - - // only list subdirectories and files - if (!DIR_IS_FILE_OR_SUBDIR(p)) { - continue; - } - - // print any indent spaces - for (int8_t i = 0; i < indent; i++) { - Serial.print(' '); - } - - // print file name with possible blank fill - printDirName(*p, flags & (LS_DATE | LS_SIZE) ? 14 : 0); - - // print modify date/time if requested - if (flags & LS_DATE) { - printFatDate(p->lastWriteDate); - Serial.print(' '); - printFatTime(p->lastWriteTime); - } - // print size if requested - if (!DIR_IS_SUBDIR(p) && (flags & LS_SIZE)) { - Serial.print(' '); - Serial.print(p->fileSize); - } - Serial.println(); - - // list subdirectory content if requested - if ((flags & LS_R) && DIR_IS_SUBDIR(p)) { - uint16_t index = curPosition() / 32 - 1; - SdFile s; - if (s.open(this, index, O_READ)) { - s.ls(flags, indent + 2); - } - seekSet(32 * (index + 1)); - } - } -} -//------------------------------------------------------------------------------ -// format directory name field from a 8.3 name string -uint8_t SdFile::make83Name(const char* str, uint8_t* name) { - uint8_t c; - uint8_t n = 7; // max index for part before dot - uint8_t i = 0; - // blank fill name and extension - while (i < 11) { - name[i++] = ' '; - } - i = 0; - while ((c = *str++) != '\0') { - if (c == '.') { - if (n == 10) { - return false; // only one dot allowed - } - n = 10; // max index for full 8.3 name - i = 8; // place for extension - } else { - // illegal FAT characters - uint8_t b; - #if defined(__AVR__) - PGM_P p = PSTR("|<>^+=?/[];,*\"\\"); - while ((b = pgm_read_byte(p++))) if (b == c) { - return false; - } - #elif defined(__arm__) - const uint8_t valid[] = "|<>^+=?/[];,*\"\\"; - const uint8_t *p = valid; - while ((b = *p++)) if (b == c) { - return false; - } - #endif - // check size and only allow ASCII printable characters - if (i > n || c < 0X21 || c > 0X7E) { - return false; - } - // only upper case allowed in 8.3 names - convert lower to upper - name[i++] = c < 'a' || c > 'z' ? c : c + ('A' - 'a'); - } - } - // must have a file name, extension is optional - return name[0] != ' '; -} -//------------------------------------------------------------------------------ -/** Make a new directory. - - \param[in] dir An open SdFat instance for the directory that will containing - the new directory. - - \param[in] dirName A valid 8.3 DOS name for the new directory. - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. - Reasons for failure include this SdFile is already open, \a dir is not a - directory, \a dirName is invalid or already exists in \a dir. -*/ -uint8_t SdFile::makeDir(SdFile* dir, const char* dirName) { - dir_t d; - - // create a normal file - if (!open(dir, dirName, O_CREAT | O_EXCL | O_RDWR)) { - return false; - } - - // convert SdFile to directory - flags_ = O_READ; - type_ = FAT_FILE_TYPE_SUBDIR; - - // allocate and zero first cluster - if (!addDirCluster()) { - return false; - } - - // force entry to SD - if (!sync()) { - return false; - } - - // cache entry - should already be in cache due to sync() call - dir_t* p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); - if (!p) { - return false; - } - - // change directory entry attribute - p->attributes = DIR_ATT_DIRECTORY; - - // make entry for '.' - memcpy(&d, p, sizeof(d)); - for (uint8_t i = 1; i < 11; i++) { - d.name[i] = ' '; - } - d.name[0] = '.'; - - // cache block for '.' and '..' - uint32_t block = vol_->clusterStartBlock(firstCluster_); - if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) { - return false; - } - - // copy '.' to block - memcpy(&SdVolume::cacheBuffer_.dir[0], &d, sizeof(d)); - - // make entry for '..' - d.name[1] = '.'; - if (dir->isRoot()) { - d.firstClusterLow = 0; - d.firstClusterHigh = 0; - } else { - d.firstClusterLow = dir->firstCluster_ & 0XFFFF; - d.firstClusterHigh = dir->firstCluster_ >> 16; - } - // copy '..' to block - memcpy(&SdVolume::cacheBuffer_.dir[1], &d, sizeof(d)); - - // set position after '..' - curPosition_ = 2 * sizeof(d); - - // write first block - return SdVolume::cacheFlush(); -} -//------------------------------------------------------------------------------ -/** - Open a file or directory by name. - - \param[in] dirFile An open SdFat instance for the directory containing the - file to be opened. - - \param[in] fileName A valid 8.3 DOS name for a file to be opened. - - \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive - OR of flags from the following list - - O_READ - Open for reading. - - O_RDONLY - Same as O_READ. - - O_WRITE - Open for writing. - - O_WRONLY - Same as O_WRITE. - - O_RDWR - Open for reading and writing. - - O_APPEND - If set, the file offset shall be set to the end of the - file prior to each write. - - O_CREAT - If the file exists, this flag has no effect except as noted - under O_EXCL below. Otherwise, the file shall be created - - O_EXCL - If O_CREAT and O_EXCL are set, open() shall fail if the file exists. - - O_SYNC - Call sync() after each write. This flag should not be used with - write(uint8_t), write_P(PGM_P), writeln_P(PGM_P), or the Arduino Print class. - These functions do character at a time writes so sync() will be called - after each byte. - - O_TRUNC - If the file exists and is a regular file, and the file is - successfully opened and is not read only, its length shall be truncated to 0. - - \note Directory files must be opened read only. Write and truncation is - not allowed for directory files. - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. - Reasons for failure include this SdFile is already open, \a difFile is not - a directory, \a fileName is invalid, the file does not exist - or can't be opened in the access mode specified by oflag. -*/ -uint8_t SdFile::open(SdFile* dirFile, const char* fileName, uint8_t oflag) { - uint8_t dname[11]; - dir_t* p; - - // error if already open - if (isOpen()) { - return false; - } - - if (!make83Name(fileName, dname)) { - return false; - } - vol_ = dirFile->vol_; - dirFile->rewind(); - - // bool for empty entry found - uint8_t emptyFound = false; - - // search for file - while (dirFile->curPosition_ < dirFile->fileSize_) { - uint8_t index = 0XF & (dirFile->curPosition_ >> 5); - p = dirFile->readDirCache(); - if (p == NULL) { - return false; - } - - if (p->name[0] == DIR_NAME_FREE || p->name[0] == DIR_NAME_DELETED) { - // remember first empty slot - if (!emptyFound) { - emptyFound = true; - dirIndex_ = index; - dirBlock_ = SdVolume::cacheBlockNumber_; - } - // done if no entries follow - if (p->name[0] == DIR_NAME_FREE) { - break; - } - } else if (!memcmp(dname, p->name, 11)) { - // don't open existing file if O_CREAT and O_EXCL - if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) { - return false; - } - - // open found file - return openCachedEntry(0XF & index, oflag); - } - } - // only create file if O_CREAT and O_WRITE - if ((oflag & (O_CREAT | O_WRITE)) != (O_CREAT | O_WRITE)) { - return false; - } - - // cache found slot or add cluster if end of file - if (emptyFound) { - p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); - if (!p) { - return false; - } - } else { - if (dirFile->type_ == FAT_FILE_TYPE_ROOT16) { - return false; - } - - // add and zero cluster for dirFile - first cluster is in cache for write - if (!dirFile->addDirCluster()) { - return false; - } - - // use first entry in cluster - dirIndex_ = 0; - p = SdVolume::cacheBuffer_.dir; - } - // initialize as empty file - memset(p, 0, sizeof(dir_t)); - memcpy(p->name, dname, 11); - - // set timestamps - if (dateTime_) { - // call user function - dateTime_(&p->creationDate, &p->creationTime); - } else { - // use default date/time - p->creationDate = FAT_DEFAULT_DATE; - p->creationTime = FAT_DEFAULT_TIME; - } - p->lastAccessDate = p->creationDate; - p->lastWriteDate = p->creationDate; - p->lastWriteTime = p->creationTime; - - // force write of entry to SD - if (!SdVolume::cacheFlush()) { - return false; - } - - // open entry in cache - return openCachedEntry(dirIndex_, oflag); -} -//------------------------------------------------------------------------------ -/** - Open a file by index. - - \param[in] dirFile An open SdFat instance for the directory. - - \param[in] index The \a index of the directory entry for the file to be - opened. The value for \a index is (directory file position)/32. - - \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive - OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC. - - See open() by fileName for definition of flags and return values. - -*/ -uint8_t SdFile::open(SdFile* dirFile, uint16_t index, uint8_t oflag) { - // error if already open - if (isOpen()) { - return false; - } - - // don't open existing file if O_CREAT and O_EXCL - user call error - if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) { - return false; - } - - vol_ = dirFile->vol_; - - // seek to location of entry - if (!dirFile->seekSet(32 * index)) { - return false; - } - - // read entry into cache - dir_t* p = dirFile->readDirCache(); - if (p == NULL) { - return false; - } - - // error if empty slot or '.' or '..' - if (p->name[0] == DIR_NAME_FREE || - p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') { - return false; - } - // open cached entry - return openCachedEntry(index & 0XF, oflag); -} -//------------------------------------------------------------------------------ -// open a cached directory entry. Assumes vol_ is initializes -uint8_t SdFile::openCachedEntry(uint8_t dirIndex, uint8_t oflag) { - // location of entry in cache - dir_t* p = SdVolume::cacheBuffer_.dir + dirIndex; - - // write or truncate is an error for a directory or read-only file - if (p->attributes & (DIR_ATT_READ_ONLY | DIR_ATT_DIRECTORY)) { - if (oflag & (O_WRITE | O_TRUNC)) { - return false; - } - } - // remember location of directory entry on SD - dirIndex_ = dirIndex; - dirBlock_ = SdVolume::cacheBlockNumber_; - - // copy first cluster number for directory fields - firstCluster_ = (uint32_t)p->firstClusterHigh << 16; - firstCluster_ |= p->firstClusterLow; - - // make sure it is a normal file or subdirectory - if (DIR_IS_FILE(p)) { - fileSize_ = p->fileSize; - type_ = FAT_FILE_TYPE_NORMAL; - } else if (DIR_IS_SUBDIR(p)) { - if (!vol_->chainSize(firstCluster_, &fileSize_)) { - return false; - } - type_ = FAT_FILE_TYPE_SUBDIR; - } else { - return false; - } - // save open flags for read/write - flags_ = oflag & (O_ACCMODE | O_SYNC | O_APPEND); - - // set to start of file - curCluster_ = 0; - curPosition_ = 0; - - // truncate file to zero length if requested - if (oflag & O_TRUNC) { - return truncate(0); - } - return true; -} -//------------------------------------------------------------------------------ -/** - Open a volume's root directory. - - \param[in] vol The FAT volume containing the root directory to be opened. - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. - Reasons for failure include the FAT volume has not been initialized - or it a FAT12 volume. -*/ -uint8_t SdFile::openRoot(SdVolume* vol) { - // error if file is already open - if (isOpen()) { - return false; - } - - if (vol->fatType() == 16) { - type_ = FAT_FILE_TYPE_ROOT16; - firstCluster_ = 0; - fileSize_ = 32 * vol->rootDirEntryCount(); - } else if (vol->fatType() == 32) { - type_ = FAT_FILE_TYPE_ROOT32; - firstCluster_ = vol->rootDirStart(); - if (!vol->chainSize(firstCluster_, &fileSize_)) { - return false; - } - } else { - // volume is not initialized or FAT12 - return false; - } - vol_ = vol; - // read only - flags_ = O_READ; - - // set to start of file - curCluster_ = 0; - curPosition_ = 0; - - // root has no directory entry - dirBlock_ = 0; - dirIndex_ = 0; - return true; -} -//------------------------------------------------------------------------------ -/** %Print the name field of a directory entry in 8.3 format to Serial. - - \param[in] dir The directory structure containing the name. - \param[in] width Blank fill name if length is less than \a width. -*/ -void SdFile::printDirName(const dir_t& dir, uint8_t width) { - uint8_t w = 0; - for (uint8_t i = 0; i < 11; i++) { - if (dir.name[i] == ' ') { - continue; - } - if (i == 8) { - Serial.print('.'); - w++; - } - Serial.write(dir.name[i]); - w++; - } - if (DIR_IS_SUBDIR(&dir)) { - Serial.print('/'); - w++; - } - while (w < width) { - Serial.print(' '); - w++; - } -} -//------------------------------------------------------------------------------ -/** %Print a directory date field to Serial. - - Format is yyyy-mm-dd. - - \param[in] fatDate The date field from a directory entry. -*/ -void SdFile::printFatDate(uint16_t fatDate) { - Serial.print(FAT_YEAR(fatDate)); - Serial.print('-'); - printTwoDigits(FAT_MONTH(fatDate)); - Serial.print('-'); - printTwoDigits(FAT_DAY(fatDate)); -} -//------------------------------------------------------------------------------ -/** %Print a directory time field to Serial. - - Format is hh:mm:ss. - - \param[in] fatTime The time field from a directory entry. -*/ -void SdFile::printFatTime(uint16_t fatTime) { - printTwoDigits(FAT_HOUR(fatTime)); - Serial.print(':'); - printTwoDigits(FAT_MINUTE(fatTime)); - Serial.print(':'); - printTwoDigits(FAT_SECOND(fatTime)); -} -//------------------------------------------------------------------------------ -/** %Print a value as two digits to Serial. - - \param[in] v Value to be printed, 0 <= \a v <= 99 -*/ -void SdFile::printTwoDigits(uint8_t v) { - char str[3]; - str[0] = '0' + v / 10; - str[1] = '0' + v % 10; - str[2] = 0; - Serial.print(str); -} -//------------------------------------------------------------------------------ -/** - Read data from a file starting at the current position. - - \param[out] buf Pointer to the location that will receive the data. - - \param[in] nbyte Maximum number of bytes to read. - - \return For success read() returns the number of bytes read. - A value less than \a nbyte, including zero, will be returned - if end of file is reached. - If an error occurs, read() returns -1. Possible errors include - read() called before a file has been opened, corrupt file system - or an I/O error occurred. -*/ -int16_t SdFile::read(void* buf, uint16_t nbyte) { - uint8_t* dst = reinterpret_cast(buf); - - // error if not open or write only - if (!isOpen() || !(flags_ & O_READ)) { - return -1; - } - - // max bytes left in file - if (nbyte > (fileSize_ - curPosition_)) { - nbyte = fileSize_ - curPosition_; - } - - // amount left to read - uint16_t toRead = nbyte; - while (toRead > 0) { - uint32_t block; // raw device block number - uint16_t offset = curPosition_ & 0X1FF; // offset in block - if (type_ == FAT_FILE_TYPE_ROOT16) { - block = vol_->rootDirStart() + (curPosition_ >> 9); - } else { - uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_); - if (offset == 0 && blockOfCluster == 0) { - // start of new cluster - if (curPosition_ == 0) { - // use first cluster in file - curCluster_ = firstCluster_; - } else { - // get next cluster from FAT - if (!vol_->fatGet(curCluster_, &curCluster_)) { - return -1; - } - } - } - block = vol_->clusterStartBlock(curCluster_) + blockOfCluster; - } - uint16_t n = toRead; - - // amount to be read from current block - if (n > (512 - offset)) { - n = 512 - offset; - } - - // no buffering needed if n == 512 or user requests no buffering - if ((unbufferedRead() || n == 512) && - block != SdVolume::cacheBlockNumber_) { - if (!vol_->readData(block, offset, n, dst)) { - return -1; - } - dst += n; - } else { - // read block to cache and copy data to caller - if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_READ)) { - return -1; - } - uint8_t* src = SdVolume::cacheBuffer_.data + offset; - uint8_t* end = src + n; - while (src != end) { - *dst++ = *src++; - } - } - curPosition_ += n; - toRead -= n; - } - return nbyte; -} -//------------------------------------------------------------------------------ -/** - Read the next directory entry from a directory file. - - \param[out] dir The dir_t struct that will receive the data. - - \return For success readDir() returns the number of bytes read. - A value of zero will be returned if end of file is reached. - If an error occurs, readDir() returns -1. Possible errors include - readDir() called before a directory has been opened, this is not - a directory file or an I/O error occurred. -*/ -int8_t SdFile::readDir(dir_t* dir) { - int8_t n; - // if not a directory file or miss-positioned return an error - if (!isDir() || (0X1F & curPosition_)) { - return -1; - } - - while ((n = read(dir, sizeof(dir_t))) == sizeof(dir_t)) { - // last entry if DIR_NAME_FREE - if (dir->name[0] == DIR_NAME_FREE) { - break; - } - // skip empty entries and entry for . and .. - if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') { - continue; - } - // return if normal file or subdirectory - if (DIR_IS_FILE_OR_SUBDIR(dir)) { - return n; - } - } - // error, end of file, or past last entry - return n < 0 ? -1 : 0; -} -//------------------------------------------------------------------------------ -// Read next directory entry into the cache -// Assumes file is correctly positioned -dir_t* SdFile::readDirCache(void) { - // error if not directory - if (!isDir()) { - return NULL; - } - - // index of entry in cache - uint8_t i = (curPosition_ >> 5) & 0XF; - - // use read to locate and cache block - if (read() < 0) { - return NULL; - } - - // advance to next entry - curPosition_ += 31; - - // return pointer to entry - return (SdVolume::cacheBuffer_.dir + i); -} -//------------------------------------------------------------------------------ -/** - Remove a file. - - The directory entry and all data for the file are deleted. - - \note This function should not be used to delete the 8.3 version of a - file that has a long name. For example if a file has the long name - "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. - Reasons for failure include the file read-only, is a directory, - or an I/O error occurred. -*/ -uint8_t SdFile::remove(void) { - // free any clusters - will fail if read-only or directory - if (!truncate(0)) { - return false; - } - - // cache directory entry - dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); - if (!d) { - return false; - } - - // mark entry deleted - d->name[0] = DIR_NAME_DELETED; - - // set this SdFile closed - type_ = FAT_FILE_TYPE_CLOSED; - - // write entry to SD - return SdVolume::cacheFlush(); -} -//------------------------------------------------------------------------------ -/** - Remove a file. - - The directory entry and all data for the file are deleted. - - \param[in] dirFile The directory that contains the file. - \param[in] fileName The name of the file to be removed. - - \note This function should not be used to delete the 8.3 version of a - file that has a long name. For example if a file has the long name - "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. - Reasons for failure include the file is a directory, is read only, - \a dirFile is not a directory, \a fileName is not found - or an I/O error occurred. -*/ -uint8_t SdFile::remove(SdFile* dirFile, const char* fileName) { - SdFile file; - if (!file.open(dirFile, fileName, O_WRITE)) { - return false; - } - return file.remove(); -} -//------------------------------------------------------------------------------ -/** Remove a directory file. - - The directory file will be removed only if it is empty and is not the - root directory. rmDir() follows DOS and Windows and ignores the - read-only attribute for the directory. - - \note This function should not be used to delete the 8.3 version of a - directory that has a long name. For example if a directory has the - long name "New folder" you should not delete the 8.3 name "NEWFOL~1". - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. - Reasons for failure include the file is not a directory, is the root - directory, is not empty, or an I/O error occurred. -*/ -uint8_t SdFile::rmDir(void) { - // must be open subdirectory - if (!isSubDir()) { - return false; - } - - rewind(); - - // make sure directory is empty - while (curPosition_ < fileSize_) { - dir_t* p = readDirCache(); - if (p == NULL) { - return false; - } - // done if past last used entry - if (p->name[0] == DIR_NAME_FREE) { - break; - } - // skip empty slot or '.' or '..' - if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') { - continue; - } - // error not empty - if (DIR_IS_FILE_OR_SUBDIR(p)) { - return false; - } - } - // convert empty directory to normal file for remove - type_ = FAT_FILE_TYPE_NORMAL; - flags_ |= O_WRITE; - return remove(); -} -//------------------------------------------------------------------------------ -/** Recursively delete a directory and all contained files. - - This is like the Unix/Linux 'rm -rf *' if called with the root directory - hence the name. - - Warning - This will remove all contents of the directory including - subdirectories. The directory will then be removed if it is not root. - The read-only attribute for files will be ignored. - - \note This function should not be used to delete the 8.3 version of - a directory that has a long name. See remove() and rmDir(). - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. -*/ -uint8_t SdFile::rmRfStar(void) { - rewind(); - while (curPosition_ < fileSize_) { - SdFile f; - - // remember position - uint16_t index = curPosition_ / 32; - - dir_t* p = readDirCache(); - if (!p) { - return false; - } - - // done if past last entry - if (p->name[0] == DIR_NAME_FREE) { - break; - } - - // skip empty slot or '.' or '..' - if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') { - continue; - } - - // skip if part of long file name or volume label in root - if (!DIR_IS_FILE_OR_SUBDIR(p)) { - continue; - } - - if (!f.open(this, index, O_READ)) { - return false; - } - if (f.isSubDir()) { - // recursively delete - if (!f.rmRfStar()) { - return false; - } - } else { - // ignore read-only - f.flags_ |= O_WRITE; - if (!f.remove()) { - return false; - } - } - // position to next entry if required - if (curPosition_ != (32u * (index + 1))) { - if (!seekSet(32u * (index + 1))) { - return false; - } - } - } - // don't try to delete root - if (isRoot()) { - return true; - } - return rmDir(); -} -//------------------------------------------------------------------------------ -/** - Sets a file's position. - - \param[in] pos The new position in bytes from the beginning of the file. - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. -*/ -uint8_t SdFile::seekSet(uint32_t pos) { - // error if file not open or seek past end of file - if (!isOpen() || pos > fileSize_) { - return false; - } - - if (type_ == FAT_FILE_TYPE_ROOT16) { - curPosition_ = pos; - return true; - } - if (pos == 0) { - // set position to start of file - curCluster_ = 0; - curPosition_ = 0; - return true; - } - // calculate cluster index for cur and new position - uint32_t nCur = (curPosition_ - 1) >> (vol_->clusterSizeShift_ + 9); - uint32_t nNew = (pos - 1) >> (vol_->clusterSizeShift_ + 9); - - if (nNew < nCur || curPosition_ == 0) { - // must follow chain from first cluster - curCluster_ = firstCluster_; - } else { - // advance from curPosition - nNew -= nCur; - } - while (nNew--) { - if (!vol_->fatGet(curCluster_, &curCluster_)) { - return false; - } - } - curPosition_ = pos; - return true; -} -//------------------------------------------------------------------------------ -/** - The sync() call causes all modified data and directory fields - to be written to the storage device. - - \param[in] blocking If the sync should block until fully complete. - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. - Reasons for failure include a call to sync() before a file has been - opened or an I/O error. -*/ -uint8_t SdFile::sync(uint8_t blocking) { - // only allow open files and directories - if (!isOpen()) { - return false; - } - - if (flags_ & F_FILE_DIR_DIRTY) { - dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); - if (!d) { - return false; - } - - // do not set filesize for dir files - if (!isDir()) { - d->fileSize = fileSize_; - } - - // update first cluster fields - d->firstClusterLow = firstCluster_ & 0XFFFF; - d->firstClusterHigh = firstCluster_ >> 16; - - // set modify time if user supplied a callback date/time function - if (dateTime_) { - dateTime_(&d->lastWriteDate, &d->lastWriteTime); - d->lastAccessDate = d->lastWriteDate; - } - // clear directory dirty - flags_ &= ~F_FILE_DIR_DIRTY; - } - - if (!blocking) { - flags_ &= ~F_FILE_NON_BLOCKING_WRITE; - } - - return SdVolume::cacheFlush(blocking); -} -//------------------------------------------------------------------------------ -/** - Set a file's timestamps in its directory entry. - - \param[in] flags Values for \a flags are constructed by a bitwise-inclusive - OR of flags from the following list - - T_ACCESS - Set the file's last access date. - - T_CREATE - Set the file's creation date and time. - - T_WRITE - Set the file's last write/modification date and time. - - \param[in] year Valid range 1980 - 2107 inclusive. - - \param[in] month Valid range 1 - 12 inclusive. - - \param[in] day Valid range 1 - 31 inclusive. - - \param[in] hour Valid range 0 - 23 inclusive. - - \param[in] minute Valid range 0 - 59 inclusive. - - \param[in] second Valid range 0 - 59 inclusive - - \note It is possible to set an invalid date since there is no check for - the number of days in a month. - - \note - Modify and access timestamps may be overwritten if a date time callback - function has been set by dateTimeCallback(). - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. -*/ -uint8_t SdFile::timestamp(uint8_t flags, uint16_t year, uint8_t month, - uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) { - if (!isOpen() - || year < 1980 - || year > 2107 - || month < 1 - || month > 12 - || day < 1 - || day > 31 - || hour > 23 - || minute > 59 - || second > 59) { - return false; - } - dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); - if (!d) { - return false; - } - - uint16_t dirDate = FAT_DATE(year, month, day); - uint16_t dirTime = FAT_TIME(hour, minute, second); - if (flags & T_ACCESS) { - d->lastAccessDate = dirDate; - } - if (flags & T_CREATE) { - d->creationDate = dirDate; - d->creationTime = dirTime; - // seems to be units of 1/100 second not 1/10 as Microsoft states - d->creationTimeTenths = second & 1 ? 100 : 0; - } - if (flags & T_WRITE) { - d->lastWriteDate = dirDate; - d->lastWriteTime = dirTime; - } - SdVolume::cacheSetDirty(); - return sync(); -} -//------------------------------------------------------------------------------ -/** - Truncate a file to a specified length. The current file position - will be maintained if it is less than or equal to \a length otherwise - it will be set to end of file. - - \param[in] length The desired length for the file. - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. - Reasons for failure include file is read only, file is a directory, - \a length is greater than the current file size or an I/O error occurs. -*/ -uint8_t SdFile::truncate(uint32_t length) { - // error if not a normal file or read-only - if (!isFile() || !(flags_ & O_WRITE)) { - return false; - } - - // error if length is greater than current size - if (length > fileSize_) { - return false; - } - - // fileSize and length are zero - nothing to do - if (fileSize_ == 0) { - return true; - } - - // remember position for seek after truncation - uint32_t newPos = curPosition_ > length ? length : curPosition_; - - // position to last cluster in truncated file - if (!seekSet(length)) { - return false; - } - - if (length == 0) { - // free all clusters - if (!vol_->freeChain(firstCluster_)) { - return false; - } - firstCluster_ = 0; - } else { - uint32_t toFree; - if (!vol_->fatGet(curCluster_, &toFree)) { - return false; - } - - if (!vol_->isEOC(toFree)) { - // free extra clusters - if (!vol_->freeChain(toFree)) { - return false; - } - - // current cluster is end of chain - if (!vol_->fatPutEOC(curCluster_)) { - return false; - } - } - } - fileSize_ = length; - - // need to update directory entry - flags_ |= F_FILE_DIR_DIRTY; - - if (!sync()) { - return false; - } - - // set file to correct position - return seekSet(newPos); -} -//------------------------------------------------------------------------------ -/** - Write data to an open file. - - \note Data is moved to the cache but may not be written to the - storage device until sync() is called. - - \param[in] buf Pointer to the location of the data to be written. - - \param[in] nbyte Number of bytes to write. - - \return For success write() returns the number of bytes written, always - \a nbyte. If an error occurs, write() returns 0. Possible errors - include write() is called before a file has been opened, write is called - for a read-only file, device is full, a corrupt file system or an I/O error. - -*/ -size_t SdFile::write(const void* buf, uint16_t nbyte) { - // convert void* to uint8_t* - must be before goto statements - const uint8_t* src = reinterpret_cast(buf); - - // number of bytes left to write - must be before goto statements - uint16_t nToWrite = nbyte; - // if blocking writes should be used - uint8_t blocking = (flags_ & F_FILE_NON_BLOCKING_WRITE) == 0x00; - - // error if not a normal file or is read-only - if (!isFile() || !(flags_ & O_WRITE)) { - goto writeErrorReturn; - } - - // seek to end of file if append flag - if ((flags_ & O_APPEND) && curPosition_ != fileSize_) { - if (!seekEnd()) { - goto writeErrorReturn; - } - } - - while (nToWrite > 0) { - uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_); - uint16_t blockOffset = curPosition_ & 0X1FF; - if (blockOfCluster == 0 && blockOffset == 0) { - // start of new cluster - if (curCluster_ == 0) { - if (firstCluster_ == 0) { - // allocate first cluster of file - if (!addCluster()) { - goto writeErrorReturn; - } - } else { - curCluster_ = firstCluster_; - } - } else { - uint32_t next; - if (!vol_->fatGet(curCluster_, &next)) { - return false; - } - if (vol_->isEOC(next)) { - // add cluster if at end of chain - if (!addCluster()) { - goto writeErrorReturn; - } - } else { - curCluster_ = next; - } - } - } - // max space in block - uint16_t n = 512 - blockOffset; - - // lesser of space and amount to write - if (n > nToWrite) { - n = nToWrite; - } - - // block for data write - uint32_t block = vol_->clusterStartBlock(curCluster_) + blockOfCluster; - if (n == 512) { - // full block - don't need to use cache - // invalidate cache if block is in cache - if (SdVolume::cacheBlockNumber_ == block) { - SdVolume::cacheBlockNumber_ = 0XFFFFFFFF; - } - if (!vol_->writeBlock(block, src, blocking)) { - goto writeErrorReturn; - } - src += 512; - } else { - if (blockOffset == 0 && curPosition_ >= fileSize_) { - // start of new block don't need to read into cache - if (!SdVolume::cacheFlush()) { - goto writeErrorReturn; - } - SdVolume::cacheBlockNumber_ = block; - SdVolume::cacheSetDirty(); - } else { - // rewrite part of block - if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) { - goto writeErrorReturn; - } - } - uint8_t* dst = SdVolume::cacheBuffer_.data + blockOffset; - uint8_t* end = dst + n; - while (dst != end) { - *dst++ = *src++; - } - } - nToWrite -= n; - curPosition_ += n; - } - if (curPosition_ > fileSize_) { - // update fileSize and insure sync will update dir entry - fileSize_ = curPosition_; - flags_ |= F_FILE_DIR_DIRTY; - } else if (dateTime_ && nbyte) { - // insure sync will update modified date and time - flags_ |= F_FILE_DIR_DIRTY; - } - - if (flags_ & O_SYNC) { - if (!sync()) { - goto writeErrorReturn; - } - } - return nbyte; - -writeErrorReturn: - // return for write error - //writeError = true; - setWriteError(); - return 0; -} -//------------------------------------------------------------------------------ -/** - Write a byte to a file. Required by the Arduino Print class. - - Use SdFile::writeError to check for errors. -*/ -size_t SdFile::write(uint8_t b) { - return write(&b, 1); -} -//------------------------------------------------------------------------------ -/** - Write a string to a file. Used by the Arduino Print class. - - Use SdFile::writeError to check for errors. -*/ -size_t SdFile::write(const char* str) { - return write(str, strlen(str)); -} -#ifdef __AVR__ -//------------------------------------------------------------------------------ -/** - Write a PROGMEM string to a file. - - Use SdFile::writeError to check for errors. -*/ -void SdFile::write_P(PGM_P str) { - for (uint8_t c; (c = pgm_read_byte(str)); str++) { - write(c); - } -} -//------------------------------------------------------------------------------ -/** - Write a PROGMEM string followed by CR/LF to a file. - - Use SdFile::writeError to check for errors. -*/ -void SdFile::writeln_P(PGM_P str) { - write_P(str); - println(); -} -#endif -//------------------------------------------------------------------------------ -/** - Check how many bytes can be written without blocking. - - \return The number of bytes that can be written without blocking. -*/ -int SdFile::availableForWrite() { - if (!isFile() || !(flags_ & O_WRITE)) { - return 0; - } - - // seek to end of file if append flag - if ((flags_ & O_APPEND) && curPosition_ != fileSize_) { - if (!seekEnd()) { - return 0; - } - } - - if (vol_->isBusy()) { - return 0; - } - - if (flags_ & F_FILE_CLUSTER_ADDED) { - // new cluster added, trigger a non-blocking sync - sync(0); - flags_ &= ~F_FILE_CLUSTER_ADDED; - return 0; - } - - if (vol_->isCacheMirrorBlockDirty()) { - // cache mirror block is dirty, trigger a non-blocking sync - vol_->cacheMirrorBlockFlush(0); - return 0; - } - - flags_ |= F_FILE_NON_BLOCKING_WRITE; - - uint16_t blockOffset = curPosition_ & 0X1FF; - uint16_t n = 512 - blockOffset; - - return n; -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdInfo.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdInfo.h deleted file mode 100755 index 6a0e087..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdInfo.h +++ /dev/null @@ -1,232 +0,0 @@ -/* Arduino Sd2Card Library - Copyright (C) 2009 by William Greiman - - This file is part of the Arduino Sd2Card Library - - This Library 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 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with the Arduino Sd2Card Library. If not, see - . -*/ -#ifndef SdInfo_h -#define SdInfo_h -#include -// Based on the document: -// -// SD Specifications -// Part 1 -// Physical Layer -// Simplified Specification -// Version 2.00 -// September 25, 2006 -// -// www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf -//------------------------------------------------------------------------------ -// SD card commands -/** GO_IDLE_STATE - init card in spi mode if CS low */ -uint8_t const CMD0 = 0X00; -/** SEND_IF_COND - verify SD Memory Card interface operating condition.*/ -uint8_t const CMD8 = 0X08; -/** SEND_CSD - read the Card Specific Data (CSD register) */ -uint8_t const CMD9 = 0X09; -/** SEND_CID - read the card identification information (CID register) */ -uint8_t const CMD10 = 0X0A; -/** SEND_STATUS - read the card status register */ -uint8_t const CMD13 = 0X0D; -/** READ_BLOCK - read a single data block from the card */ -uint8_t const CMD17 = 0X11; -/** WRITE_BLOCK - write a single data block to the card */ -uint8_t const CMD24 = 0X18; -/** WRITE_MULTIPLE_BLOCK - write blocks of data until a STOP_TRANSMISSION */ -uint8_t const CMD25 = 0X19; -/** ERASE_WR_BLK_START - sets the address of the first block to be erased */ -uint8_t const CMD32 = 0X20; -/** ERASE_WR_BLK_END - sets the address of the last block of the continuous - range to be erased*/ -uint8_t const CMD33 = 0X21; -/** ERASE - erase all previously selected blocks */ -uint8_t const CMD38 = 0X26; -/** APP_CMD - escape for application specific command */ -uint8_t const CMD55 = 0X37; -/** READ_OCR - read the OCR register of a card */ -uint8_t const CMD58 = 0X3A; -/** SET_WR_BLK_ERASE_COUNT - Set the number of write blocks to be - pre-erased before writing */ -uint8_t const ACMD23 = 0X17; -/** SD_SEND_OP_COMD - Sends host capacity support information and - activates the card's initialization process */ -uint8_t const ACMD41 = 0X29; -//------------------------------------------------------------------------------ -/** status for card in the ready state */ -uint8_t const R1_READY_STATE = 0X00; -/** status for card in the idle state */ -uint8_t const R1_IDLE_STATE = 0X01; -/** status bit for illegal command */ -uint8_t const R1_ILLEGAL_COMMAND = 0X04; -/** start data token for read or write single block*/ -uint8_t const DATA_START_BLOCK = 0XFE; -/** stop token for write multiple blocks*/ -uint8_t const STOP_TRAN_TOKEN = 0XFD; -/** start data token for write multiple blocks*/ -uint8_t const WRITE_MULTIPLE_TOKEN = 0XFC; -/** mask for data response tokens after a write block operation */ -uint8_t const DATA_RES_MASK = 0X1F; -/** write data accepted token */ -uint8_t const DATA_RES_ACCEPTED = 0X05; -//------------------------------------------------------------------------------ -typedef struct CID { - // byte 0 - uint8_t mid; // Manufacturer ID - // byte 1-2 - char oid[2]; // OEM/Application ID - // byte 3-7 - char pnm[5]; // Product name - // byte 8 - unsigned prv_m : 4; // Product revision n.m - unsigned prv_n : 4; - // byte 9-12 - uint32_t psn; // Product serial number - // byte 13 - unsigned mdt_year_high : 4; // Manufacturing date - unsigned reserved : 4; - // byte 14 - unsigned mdt_month : 4; - unsigned mdt_year_low : 4; - // byte 15 - unsigned always1 : 1; - unsigned crc : 7; -} cid_t; -//------------------------------------------------------------------------------ -// CSD for version 1.00 cards -typedef struct CSDV1 { - // byte 0 - unsigned reserved1 : 6; - unsigned csd_ver : 2; - // byte 1 - uint8_t taac; - // byte 2 - uint8_t nsac; - // byte 3 - uint8_t tran_speed; - // byte 4 - uint8_t ccc_high; - // byte 5 - unsigned read_bl_len : 4; - unsigned ccc_low : 4; - // byte 6 - unsigned c_size_high : 2; - unsigned reserved2 : 2; - unsigned dsr_imp : 1; - unsigned read_blk_misalign : 1; - unsigned write_blk_misalign : 1; - unsigned read_bl_partial : 1; - // byte 7 - uint8_t c_size_mid; - // byte 8 - unsigned vdd_r_curr_max : 3; - unsigned vdd_r_curr_min : 3; - unsigned c_size_low : 2; - // byte 9 - unsigned c_size_mult_high : 2; - unsigned vdd_w_cur_max : 3; - unsigned vdd_w_curr_min : 3; - // byte 10 - unsigned sector_size_high : 6; - unsigned erase_blk_en : 1; - unsigned c_size_mult_low : 1; - // byte 11 - unsigned wp_grp_size : 7; - unsigned sector_size_low : 1; - // byte 12 - unsigned write_bl_len_high : 2; - unsigned r2w_factor : 3; - unsigned reserved3 : 2; - unsigned wp_grp_enable : 1; - // byte 13 - unsigned reserved4 : 5; - unsigned write_partial : 1; - unsigned write_bl_len_low : 2; - // byte 14 - unsigned reserved5: 2; - unsigned file_format : 2; - unsigned tmp_write_protect : 1; - unsigned perm_write_protect : 1; - unsigned copy : 1; - unsigned file_format_grp : 1; - // byte 15 - unsigned always1 : 1; - unsigned crc : 7; -} csd1_t; -//------------------------------------------------------------------------------ -// CSD for version 2.00 cards -typedef struct CSDV2 { - // byte 0 - unsigned reserved1 : 6; - unsigned csd_ver : 2; - // byte 1 - uint8_t taac; - // byte 2 - uint8_t nsac; - // byte 3 - uint8_t tran_speed; - // byte 4 - uint8_t ccc_high; - // byte 5 - unsigned read_bl_len : 4; - unsigned ccc_low : 4; - // byte 6 - unsigned reserved2 : 4; - unsigned dsr_imp : 1; - unsigned read_blk_misalign : 1; - unsigned write_blk_misalign : 1; - unsigned read_bl_partial : 1; - // byte 7 - unsigned reserved3 : 2; - unsigned c_size_high : 6; - // byte 8 - uint8_t c_size_mid; - // byte 9 - uint8_t c_size_low; - // byte 10 - unsigned sector_size_high : 6; - unsigned erase_blk_en : 1; - unsigned reserved4 : 1; - // byte 11 - unsigned wp_grp_size : 7; - unsigned sector_size_low : 1; - // byte 12 - unsigned write_bl_len_high : 2; - unsigned r2w_factor : 3; - unsigned reserved5 : 2; - unsigned wp_grp_enable : 1; - // byte 13 - unsigned reserved6 : 5; - unsigned write_partial : 1; - unsigned write_bl_len_low : 2; - // byte 14 - unsigned reserved7: 2; - unsigned file_format : 2; - unsigned tmp_write_protect : 1; - unsigned perm_write_protect : 1; - unsigned copy : 1; - unsigned file_format_grp : 1; - // byte 15 - unsigned always1 : 1; - unsigned crc : 7; -} csd2_t; -//------------------------------------------------------------------------------ -// union of old and new style CSD register -union csd_t { - csd1_t v1; - csd2_t v2; -}; -#endif // SdInfo_h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdVolume.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdVolume.cpp deleted file mode 100755 index 60375c4..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/SD/utility/SdVolume.cpp +++ /dev/null @@ -1,351 +0,0 @@ -/* Arduino SdFat Library - Copyright (C) 2009 by William Greiman - - This file is part of the Arduino SdFat Library - - This Library 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 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with the Arduino SdFat Library. If not, see - . -*/ -#include "SdFat.h" -//------------------------------------------------------------------------------ -// raw block cache -// init cacheBlockNumber_to invalid SD block number -uint32_t SdVolume::cacheBlockNumber_ = 0XFFFFFFFF; -cache_t SdVolume::cacheBuffer_; // 512 byte cache for Sd2Card -Sd2Card* SdVolume::sdCard_; // pointer to SD card object -uint8_t SdVolume::cacheDirty_ = 0; // cacheFlush() will write block if true -uint32_t SdVolume::cacheMirrorBlock_ = 0; // mirror block for second FAT -//------------------------------------------------------------------------------ -// find a contiguous group of clusters -uint8_t SdVolume::allocContiguous(uint32_t count, uint32_t* curCluster) { - // start of group - uint32_t bgnCluster; - - // flag to save place to start next search - uint8_t setStart; - - // set search start cluster - if (*curCluster) { - // try to make file contiguous - bgnCluster = *curCluster + 1; - - // don't save new start location - setStart = false; - } else { - // start at likely place for free cluster - bgnCluster = allocSearchStart_; - - // save next search start if one cluster - setStart = 1 == count; - } - // end of group - uint32_t endCluster = bgnCluster; - - // last cluster of FAT - uint32_t fatEnd = clusterCount_ + 1; - - // search the FAT for free clusters - for (uint32_t n = 0;; n++, endCluster++) { - // can't find space checked all clusters - if (n >= clusterCount_) { - return false; - } - - // past end - start from beginning of FAT - if (endCluster > fatEnd) { - bgnCluster = endCluster = 2; - } - uint32_t f; - if (!fatGet(endCluster, &f)) { - return false; - } - - if (f != 0) { - // cluster in use try next cluster as bgnCluster - bgnCluster = endCluster + 1; - } else if ((endCluster - bgnCluster + 1) == count) { - // done - found space - break; - } - } - // mark end of chain - if (!fatPutEOC(endCluster)) { - return false; - } - - // link clusters - while (endCluster > bgnCluster) { - if (!fatPut(endCluster - 1, endCluster)) { - return false; - } - endCluster--; - } - if (*curCluster != 0) { - // connect chains - if (!fatPut(*curCluster, bgnCluster)) { - return false; - } - } - // return first cluster number to caller - *curCluster = bgnCluster; - - // remember possible next free cluster - if (setStart) { - allocSearchStart_ = bgnCluster + 1; - } - - return true; -} -//------------------------------------------------------------------------------ -uint8_t SdVolume::cacheFlush(uint8_t blocking) { - if (cacheDirty_) { - if (!sdCard_->writeBlock(cacheBlockNumber_, cacheBuffer_.data, blocking)) { - return false; - } - - if (!blocking) { - return true; - } - - // mirror FAT tables - if (!cacheMirrorBlockFlush(blocking)) { - return false; - } - cacheDirty_ = 0; - } - return true; -} -//------------------------------------------------------------------------------ -uint8_t SdVolume::cacheMirrorBlockFlush(uint8_t blocking) { - if (cacheMirrorBlock_) { - if (!sdCard_->writeBlock(cacheMirrorBlock_, cacheBuffer_.data, blocking)) { - return false; - } - cacheMirrorBlock_ = 0; - } - return true; -} -//------------------------------------------------------------------------------ -uint8_t SdVolume::cacheRawBlock(uint32_t blockNumber, uint8_t action) { - if (cacheBlockNumber_ != blockNumber) { - if (!cacheFlush()) { - return false; - } - if (!sdCard_->readBlock(blockNumber, cacheBuffer_.data)) { - return false; - } - cacheBlockNumber_ = blockNumber; - } - cacheDirty_ |= action; - return true; -} -//------------------------------------------------------------------------------ -// cache a zero block for blockNumber -uint8_t SdVolume::cacheZeroBlock(uint32_t blockNumber) { - if (!cacheFlush()) { - return false; - } - - // loop take less flash than memset(cacheBuffer_.data, 0, 512); - for (uint16_t i = 0; i < 512; i++) { - cacheBuffer_.data[i] = 0; - } - cacheBlockNumber_ = blockNumber; - cacheSetDirty(); - return true; -} -//------------------------------------------------------------------------------ -// return the size in bytes of a cluster chain -uint8_t SdVolume::chainSize(uint32_t cluster, uint32_t* size) const { - uint32_t s = 0; - do { - if (!fatGet(cluster, &cluster)) { - return false; - } - s += 512UL << clusterSizeShift_; - } while (!isEOC(cluster)); - *size = s; - return true; -} -//------------------------------------------------------------------------------ -// Fetch a FAT entry -uint8_t SdVolume::fatGet(uint32_t cluster, uint32_t* value) const { - if (cluster > (clusterCount_ + 1)) { - return false; - } - uint32_t lba = fatStartBlock_; - lba += fatType_ == 16 ? cluster >> 8 : cluster >> 7; - if (lba != cacheBlockNumber_) { - if (!cacheRawBlock(lba, CACHE_FOR_READ)) { - return false; - } - } - if (fatType_ == 16) { - *value = cacheBuffer_.fat16[cluster & 0XFF]; - } else { - *value = cacheBuffer_.fat32[cluster & 0X7F] & FAT32MASK; - } - return true; -} -//------------------------------------------------------------------------------ -// Store a FAT entry -uint8_t SdVolume::fatPut(uint32_t cluster, uint32_t value) { - // error if reserved cluster - if (cluster < 2) { - return false; - } - - // error if not in FAT - if (cluster > (clusterCount_ + 1)) { - return false; - } - - // calculate block address for entry - uint32_t lba = fatStartBlock_; - lba += fatType_ == 16 ? cluster >> 8 : cluster >> 7; - - if (lba != cacheBlockNumber_) { - if (!cacheRawBlock(lba, CACHE_FOR_READ)) { - return false; - } - } - // store entry - if (fatType_ == 16) { - cacheBuffer_.fat16[cluster & 0XFF] = value; - } else { - cacheBuffer_.fat32[cluster & 0X7F] = value; - } - cacheSetDirty(); - - // mirror second FAT - if (fatCount_ > 1) { - cacheMirrorBlock_ = lba + blocksPerFat_; - } - return true; -} -//------------------------------------------------------------------------------ -// free a cluster chain -uint8_t SdVolume::freeChain(uint32_t cluster) { - // clear free cluster location - allocSearchStart_ = 2; - - do { - uint32_t next; - if (!fatGet(cluster, &next)) { - return false; - } - - // free cluster - if (!fatPut(cluster, 0)) { - return false; - } - - cluster = next; - } while (!isEOC(cluster)); - - return true; -} -//------------------------------------------------------------------------------ -/** - Initialize a FAT volume. - - \param[in] dev The SD card where the volume is located. - - \param[in] part The partition to be used. Legal values for \a part are - 1-4 to use the corresponding partition on a device formatted with - a MBR, Master Boot Record, or zero if the device is formatted as - a super floppy with the FAT boot sector in block zero. - - \return The value one, true, is returned for success and - the value zero, false, is returned for failure. Reasons for - failure include not finding a valid partition, not finding a valid - FAT file system in the specified partition or an I/O error. -*/ -uint8_t SdVolume::init(Sd2Card* dev, uint8_t part) { - uint32_t volumeStartBlock = 0; - sdCard_ = dev; - // if part == 0 assume super floppy with FAT boot sector in block zero - // if part > 0 assume mbr volume with partition table - if (part) { - if (part > 4) { - return false; - } - if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) { - return false; - } - part_t* p = &cacheBuffer_.mbr.part[part - 1]; - if ((p->boot & 0X7F) != 0 || - p->totalSectors < 100 || - p->firstSector == 0) { - // not a valid partition - return false; - } - volumeStartBlock = p->firstSector; - } - if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) { - return false; - } - bpb_t* bpb = &cacheBuffer_.fbs.bpb; - if (bpb->bytesPerSector != 512 || - bpb->fatCount == 0 || - bpb->reservedSectorCount == 0 || - bpb->sectorsPerCluster == 0) { - // not valid FAT volume - return false; - } - fatCount_ = bpb->fatCount; - blocksPerCluster_ = bpb->sectorsPerCluster; - - // determine shift that is same as multiply by blocksPerCluster_ - clusterSizeShift_ = 0; - while (blocksPerCluster_ != (1 << clusterSizeShift_)) { - // error if not power of 2 - if (clusterSizeShift_++ > 7) { - return false; - } - } - blocksPerFat_ = bpb->sectorsPerFat16 ? - bpb->sectorsPerFat16 : bpb->sectorsPerFat32; - - fatStartBlock_ = volumeStartBlock + bpb->reservedSectorCount; - - // count for FAT16 zero for FAT32 - rootDirEntryCount_ = bpb->rootDirEntryCount; - - // directory start for FAT16 dataStart for FAT32 - rootDirStart_ = fatStartBlock_ + bpb->fatCount * blocksPerFat_; - - // data start for FAT16 and FAT32 - dataStartBlock_ = rootDirStart_ + ((32 * bpb->rootDirEntryCount + 511) / 512); - - // total blocks for FAT16 or FAT32 - uint32_t totalBlocks = bpb->totalSectors16 ? - bpb->totalSectors16 : bpb->totalSectors32; - // total data blocks - clusterCount_ = totalBlocks - (dataStartBlock_ - volumeStartBlock); - - // divide by cluster size to get cluster count - clusterCount_ >>= clusterSizeShift_; - - // FAT type is determined by cluster count - if (clusterCount_ < 4085) { - fatType_ = 12; - } else if (clusterCount_ < 65525) { - fatType_ = 16; - } else { - rootDirStart_ = bpb->fat32RootCluster; - fatType_ = 32; - } - return true; -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/.travis.yml b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/.travis.yml deleted file mode 100644 index 465c761..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/.travis.yml +++ /dev/null @@ -1,48 +0,0 @@ -language: generic -env: - global: - - IDE_VERSION=1.8.2 - matrix: - - BOARD="arduino:avr:uno" - - BOARD="arduino:avr:mega:cpu=atmega2560" - - BOARD="arduino:sam:arduino_due_x_dbg" - - BOARD="arduino:samd:arduino_zero_edbg" - - BOARD="arduino:samd:mkr1000" - - BOARD="Intel:arc32:arduino_101" -before_install: - - wget http://downloads.arduino.cc/arduino-$IDE_VERSION-linux64.tar.xz - - tar xf arduino-$IDE_VERSION-linux64.tar.xz - - mv arduino-$IDE_VERSION $HOME/arduino-ide - - export PATH=$PATH:$HOME/arduino-ide - - if [[ "$BOARD" =~ "arduino:sam:" ]]; then - arduino --install-boards arduino:sam; - fi - - if [[ "$BOARD" =~ "arduino:samd:" ]]; then - arduino --install-boards arduino:samd; - fi - - if [[ "$BOARD" =~ "Intel:arc32" ]]; then - arduino --install-boards Intel:arc32; - fi - - buildExampleSketch() { arduino --verbose-build --verify --board $BOARD $PWD/examples/$1/$1.ino; } -install: - - mkdir -p $HOME/Arduino/libraries - - ln -s $PWD $HOME/Arduino/libraries/. -script: - - buildExampleSketch AP_SimpleWebServer - - buildExampleSketch CheckWifi101FirmwareVersion - - buildExampleSketch ConnectNoEncryption - - buildExampleSketch ConnectWithWEP - - buildExampleSketch ConnectWithWPA - - buildExampleSketch FirmwareUpdater - - buildExampleSketch MDNS_WiFiWebServer - - buildExampleSketch ScanNetworks - - buildExampleSketch SimpleWebServerWiFi - - buildExampleSketch WiFiChatServer - - buildExampleSketch WiFiPing - - buildExampleSketch WiFiSSLClient - - buildExampleSketch WiFiUdpNtpClient - - buildExampleSketch WiFiUdpSendReceiveString - - buildExampleSketch WiFiWebClient - - buildExampleSketch WiFiWebClientRepeating - - buildExampleSketch WiFiWebServer - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/CHANGELOG b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/CHANGELOG deleted file mode 100644 index fbe1643..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/CHANGELOG +++ /dev/null @@ -1,122 +0,0 @@ -WiFi101 ?.?.? - ????.??.?? - -WiFi101 0.14.3 - 2017.06.01 - -* Fixed issues with WiFiMDNSResponder and large request packets -* Fixed issues with WiFiClient and sending data after the socket is closed - -WiFi101 0.14.2 - 2017.05.08 - -* Fixed issues with WiFiServer::write not working - -WiFi101 0.14.1 - 2017.04.20 - -* Fixed issues with WiFiMDNSResponder and Windows using Bonjour -* Correct cast of buffer size when processing received data - -WiFi101 0.14.0 - 2017.03.22 - -* Added support for firmware 19.5.2 -* Add ability to create Access Point with WPA security (f/w 19.5.2 or higher) -* Add WiFi.hostname(name) method to set custom host name for DHCP (f/w 19.5.2 or higher) -* Enables support for AES-256 Ciphers (f/w 19.5.2 or higher) -* Make provisioning mode backwards compatible with f/w 19.4.4 and older - -WiFi101 0.13.0 - 2017.03.01 - -* Added WiFi.channel() and WiFi.BSSID() - -WiFi101 0.12.1 - 2017.01.19 - -* Fixed tomorrow day issue in WiFi.getTime() - -WiFi101 0.12.0 - 2017.01.05 - -* Made provisioning mode easier and added example sketch -* Fixed WiFi.getTime() not returning 0, if time has not been synced via NTP -* Fixed crashing when connecting after scanning -* Fixed WiFiServer::available() returning valid client on outbound client connection -* Added WiFiUdp::beginMulticast(port) function for compatiblity with EthernetUdp, as beginMulti was inconsistent - -WiFi101 0.11.2 - 2016.12.15 - -* Fixed value of WiFi.getTime() being off by one day -* Fixed calling WiFi.RSSI() causing lockups - -WiFi101 0.11.1 - 2016.11.29 - -* Fixed regression for non-AVR boards that resulted in corrupt with data over than 1400 bytes was received - -WiFi101 0.11.0 - 2016.11.14 - -* Changed WiFi.ping(...) to return round trip time on success, negative value on error. Thanks @PKGeorgiev -* WiFi.end() now powers down the WiFi module -* WiFi.config(ip) can now be used to set a static IP for WiFi.begin(...) -* Fixed WiFi.BSSID(bssid) returning reversed MAC address -* Added WiFi.APClientMacAddress() API to get MAC address of AP client in AP mode -* Added WiFi.getTime() API to get epoch from NTP - -WiFi101 0.10.0 - 2016.09.08 - -* Added WiFi.end() to disconnect from the AP or end AP mode -* Added new WiFi.ping(...) functionality. Thanks @PKGeorgiev -* Added WiFi.setPins(...) to customize the CS, INTN, RESET and CHIPEN pins -* Add new WL_AP_LISTENING, WL_AP_CONNECTED, and WL_AP_FAILED status types for AP mode -* Fixed return value of WiFiUDP::beginPacket(host, port) when host is successfully resolved -* Added power management methods: WiFi.lowPowerMode(), WiFi.maxLowPowerMode(), WiFi.noLowPowerMode() -* Close TCP sockets when physical link is disconnected -* Fixed WiFi.RSSI() returning 0 when there was pending socket data - -WiFi101 0.9.1 - 2016.04.19 - -* Increased compatibility with 3rd party boards and architectures. -* Rename WiFiMdnsResponder.h/cpp to WiFiMDNSResponder.h/cpp -* Fixed buffering of UDP packet - -WiFi101 0.9.0 - 2016.03.21 - -* Fixed WiFi.status() hanging when shield is not present -* Fixed MAC address returning 00:00:00:00:00:00 with firmware version 19.3.0 -* Fixed SSL write functionality with firmware version 19.3.0 -* Fixed previous version of the library not working on the Uno and other boards that used PCINT's -* Added beginAP(...) API's to create access point with WEP passwords -* Fixed beginAP(...) channel off by one error -* Fixed WiFi.status() always returning WL_CONNECTED once connected, even if access point is disconnected later -* Added beginMulti API for Multicast UDP support -* Added WiFiMDNSResponder class and MDNS Web server example - -WiFi101 0.8.0 - 2016.02.15 - -* Added example for Access Point web server (thanks @ladyada) -* Fixed MAC Address printed in reverse order -* Allow another library to override PCINT ISR (fix issues when using the WiFi101 - library with other libraries like SoftwareSerial) - -WiFi101 0.7.0 - 2015.01.11 - -* Added support for WiFi Firmware 19.4.4 -* WiFi.hostByName(...) will not try resolve the domain name if it's already a numeric IP -* Fixed manual IP configuration (no DHCP) -* Fixed WiFiServer.available(), now follows API specification -* Fixed WEP key connection -* Fixed WiFiClient copy constructor and assignment operator. This improves stability when - Client objects are assigned or returned from functions. -* Control pins are now configurable through defines from variant. - -WiFi101 0.6.0 - 2015.11.27 - -* Fixed bug with AVR boards when Web Server is used -* Fixed UDP read bug on AVR Boards -* Added missing inlcude for SSL Client -* Fixed peek() function -* Fixed some examples - -WiFi101 0.5.1 - 2015.10.06 - -* Improved support for AVR Boards (Uno, Mega, Leonardo, etc.) and - ARM based boards (Due and Zero). - -WiFi101 0.5.0 - 2015.10.01 - -* Initial release - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/README.adoc b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/README.adoc deleted file mode 100644 index 8eb6924..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/README.adoc +++ /dev/null @@ -1,27 +0,0 @@ -= WiFi library for the Arduino WiFi Shield 101 and MKR1000 board = - -image:https://travis-ci.org/arduino-libraries/WiFi101.svg?branch=master["Build Status", link="https://travis-ci.org/arduino-libraries/WiFi101"] - -This library implements a network driver for devices based -on the ATMEL WINC1500 WiFi module. - -For more information about this library please visit us at -https://www.arduino.cc/en/Reference/WiFi101 - -== License == - -Copyright (c) Arduino LLC. All right reserved. - -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 2.1 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 Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino deleted file mode 100644 index b5caf7a..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino +++ /dev/null @@ -1,176 +0,0 @@ -/* - WiFi Web Server LED Blink - - A simple web server that lets you blink an LED via the web. - This sketch will create a new access point (with no password). - It will then launch a new server and print out the IP address - to the Serial monitor. From there, you can open that address in a web browser - to turn on and off the LED on pin 13. - - If the IP address of your shield is yourAddress: - http://yourAddress/H turns the LED on - http://yourAddress/L turns it off - - created 25 Nov 2012 - by Tom Igoe - adapted to WiFi AP by Adafruit - */ - -#include -#include -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int led = LED_BUILTIN; -int status = WL_IDLE_STATUS; -WiFiServer server(80); - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - Serial.println("Access Point Web Server"); - - pinMode(led, OUTPUT); // set the LED pin mode - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue - while (true); - } - - // by default the local IP address of will be 192.168.1.1 - // you can override it with the following: - // WiFi.config(IPAddress(10, 0, 0, 1)); - - // print the network name (SSID); - Serial.print("Creating access point named: "); - Serial.println(ssid); - - // Create open network. Change this line if you want to create an WEP network: - status = WiFi.beginAP(ssid); - if (status != WL_AP_LISTENING) { - Serial.println("Creating access point failed"); - // don't continue - while (true); - } - - // wait 10 seconds for connection: - delay(10000); - - // start the web server on port 80 - server.begin(); - - // you're connected now, so print out the status - printWiFiStatus(); -} - - -void loop() { - // compare the previous status to the current status - if (status != WiFi.status()) { - // it has changed update the variable - status = WiFi.status(); - - if (status == WL_AP_CONNECTED) { - byte remoteMac[6]; - - // a device has connected to the AP - Serial.print("Device connected to AP, MAC address: "); - WiFi.APClientMacAddress(remoteMac); - Serial.print(remoteMac[5], HEX); - Serial.print(":"); - Serial.print(remoteMac[4], HEX); - Serial.print(":"); - Serial.print(remoteMac[3], HEX); - Serial.print(":"); - Serial.print(remoteMac[2], HEX); - Serial.print(":"); - Serial.print(remoteMac[1], HEX); - Serial.print(":"); - Serial.println(remoteMac[0], HEX); - } else { - // a device has disconnected from the AP, and we are back in listening mode - Serial.println("Device disconnected from AP"); - } - } - - WiFiClient client = server.available(); // listen for incoming clients - - if (client) { // if you get a client, - Serial.println("new client"); // print a message out the serial port - String currentLine = ""; // make a String to hold incoming data from the client - while (client.connected()) { // loop while the client's connected - if (client.available()) { // if there's bytes to read from the client, - char c = client.read(); // read a byte, then - Serial.write(c); // print it out the serial monitor - if (c == '\n') { // if the byte is a newline character - - // if the current line is blank, you got two newline characters in a row. - // that's the end of the client HTTP request, so send a response: - if (currentLine.length() == 0) { - // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) - // and a content-type so the client knows what's coming, then a blank line: - client.println("HTTP/1.1 200 OK"); - client.println("Content-type:text/html"); - client.println(); - - // the content of the HTTP response follows the header: - client.print("Click here turn the LED on
"); - client.print("Click here turn the LED off
"); - - // The HTTP response ends with another blank line: - client.println(); - // break out of the while loop: - break; - } - else { // if you got a newline, then clear currentLine: - currentLine = ""; - } - } - else if (c != '\r') { // if you got anything else but a carriage return character, - currentLine += c; // add it to the end of the currentLine - } - - // Check to see if the client request was "GET /H" or "GET /L": - if (currentLine.endsWith("GET /H")) { - digitalWrite(led, HIGH); // GET /H turns the LED on - } - if (currentLine.endsWith("GET /L")) { - digitalWrite(led, LOW); // GET /L turns the LED off - } - } - } - // close the connection: - client.stop(); - Serial.println("client disconnected"); - } -} - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); - // print where to go in a browser: - Serial.print("To see this page in action, open a browser to http://"); - Serial.println(ip); - -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/AP_SimpleWebServer/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino deleted file mode 100644 index 8cd312e..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/CheckWifi101FirmwareVersion/CheckWifi101FirmwareVersion.ino +++ /dev/null @@ -1,67 +0,0 @@ -/* - * This example check if the firmware loaded on the WiFi101 - * shield is updated. - * - * Circuit: - * - WiFi101 Shield attached - * - * Created 29 July 2015 by Cristian Maglie - * This code is in the public domain. - */ -#include -#include -#include - -void setup() { - // Initialize serial - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // Print a welcome message - Serial.println("WiFi101 firmware check."); - Serial.println(); - - // Check for the presence of the shield - Serial.print("WiFi101 shield: "); - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("NOT PRESENT"); - return; // don't continue - } - Serial.println("DETECTED"); - - // Print firmware version on the shield - String fv = WiFi.firmwareVersion(); - String latestFv; - Serial.print("Firmware version installed: "); - Serial.println(fv); - - if (REV(GET_CHIPID()) >= REV_3A0) { - // model B - latestFv = WIFI_FIRMWARE_LATEST_MODEL_B; - } else { - // model A - latestFv = WIFI_FIRMWARE_LATEST_MODEL_A; - } - - // Print required firmware version - Serial.print("Latest firmware version available : "); - Serial.println(latestFv); - - // Check if the latest version is installed - Serial.println(); - if (fv == latestFv) { - Serial.println("Check result: PASSED"); - } else { - Serial.println("Check result: NOT PASSED"); - Serial.println(" - The firmware version on the shield do not match the"); - Serial.println(" version required by the library, you may experience"); - Serial.println(" issues or failures."); - } -} - -void loop() { - // do nothing -} - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino deleted file mode 100644 index f43a232..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectNoEncryption/ConnectNoEncryption.ino +++ /dev/null @@ -1,123 +0,0 @@ -/* - - This example connects to an unencrypted WiFi network. - Then it prints the MAC address of the WiFi shield, - the IP address obtained, and other network details. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - */ -#include -#include -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -int status = WL_IDLE_STATUS; // the WiFi radio's status - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to open SSID: "); - Serial.println(ssid); - status = WiFi.begin(ssid); - - // wait 10 seconds for connection: - delay(10000); - } - - // you're connected now, so print out the data: - Serial.print("You're connected to the network"); - printCurrentNet(); - printWiFiData(); -} - -void loop() { - // check the network connection once every 10 seconds: - delay(10000); - printCurrentNet(); -} - -void printWiFiData() { - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - Serial.println(ip); - - // print your MAC address: - byte mac[6]; - WiFi.macAddress(mac); - Serial.print("MAC address: "); - Serial.print(mac[5], HEX); - Serial.print(":"); - Serial.print(mac[4], HEX); - Serial.print(":"); - Serial.print(mac[3], HEX); - Serial.print(":"); - Serial.print(mac[2], HEX); - Serial.print(":"); - Serial.print(mac[1], HEX); - Serial.print(":"); - Serial.println(mac[0], HEX); - - // print your subnet mask: - IPAddress subnet = WiFi.subnetMask(); - Serial.print("NetMask: "); - Serial.println(subnet); - - // print your gateway address: - IPAddress gateway = WiFi.gatewayIP(); - Serial.print("Gateway: "); - Serial.println(gateway); -} - -void printCurrentNet() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print the MAC address of the router you're attached to: - byte bssid[6]; - WiFi.BSSID(bssid); - Serial.print("BSSID: "); - Serial.print(bssid[5], HEX); - Serial.print(":"); - Serial.print(bssid[4], HEX); - Serial.print(":"); - Serial.print(bssid[3], HEX); - Serial.print(":"); - Serial.print(bssid[2], HEX); - Serial.print(":"); - Serial.print(bssid[1], HEX); - Serial.print(":"); - Serial.println(bssid[0], HEX); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.println(rssi); - - // print the encryption type: - byte encryption = WiFi.encryptionType(); - Serial.print("Encryption Type:"); - Serial.println(encryption, HEX); -} - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h deleted file mode 100644 index 07c1148..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectNoEncryption/arduino_secrets.h +++ /dev/null @@ -1 +0,0 @@ -#define SECRET_SSID "" diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino deleted file mode 100644 index c226fa7..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWEP/ConnectWithWEP.ino +++ /dev/null @@ -1,129 +0,0 @@ -/* - - This example connects to a WEP-encrypted WiFi network. - Then it prints the MAC address of the WiFi shield, - the IP address obtained, and other network details. - - If you use 40-bit WEP, you need a key that is 10 characters long, - and the characters must be hexadecimal (0-9 or A-F). - e.g. for 40-bit, ABBADEAF01 will work, but ABBADEAF won't work - (too short) and ABBAISDEAF won't work (I and S are not - hexadecimal characters). - - For 128-bit, you need a string that is 26 characters long. - D0D0DEADF00DABBADEAFBEADED will work because it's 26 characters, - all in the 0-9, A-F range. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - */ -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char key[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number -int status = WL_IDLE_STATUS; // the WiFi radio's status - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to WEP network, SSID: "); - Serial.println(ssid); - status = WiFi.begin(ssid, keyIndex, key); - - // wait 10 seconds for connection: - delay(10000); - } - - // once you are connected : - Serial.print("You're connected to the network"); - printCurrentNet(); - printWiFiData(); -} - -void loop() { - // check the network connection once every 10 seconds: - delay(10000); - printCurrentNet(); -} - -void printWiFiData() { - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - Serial.println(ip); - - // print your MAC address: - byte mac[6]; - WiFi.macAddress(mac); - Serial.print("MAC address: "); - Serial.print(mac[5], HEX); - Serial.print(":"); - Serial.print(mac[4], HEX); - Serial.print(":"); - Serial.print(mac[3], HEX); - Serial.print(":"); - Serial.print(mac[2], HEX); - Serial.print(":"); - Serial.print(mac[1], HEX); - Serial.print(":"); - Serial.println(mac[0], HEX); -} - -void printCurrentNet() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print the MAC address of the router you're attached to: - byte bssid[6]; - WiFi.BSSID(bssid); - Serial.print("BSSID: "); - Serial.print(bssid[5], HEX); - Serial.print(":"); - Serial.print(bssid[4], HEX); - Serial.print(":"); - Serial.print(bssid[3], HEX); - Serial.print(":"); - Serial.print(bssid[2], HEX); - Serial.print(":"); - Serial.print(bssid[1], HEX); - Serial.print(":"); - Serial.println(bssid[0], HEX); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.println(rssi); - - // print the encryption type: - byte encryption = WiFi.encryptionType(); - Serial.print("Encryption Type:"); - Serial.println(encryption, HEX); - Serial.println(); -} - - - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWEP/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino deleted file mode 100644 index b98af65..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWPA/ConnectWithWPA.ino +++ /dev/null @@ -1,119 +0,0 @@ -/* - - This example connects to an unencrypted WiFi network. - Then it prints the MAC address of the WiFi shield, - the IP address obtained, and other network details. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - */ -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int status = WL_IDLE_STATUS; // the WiFi radio's status - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to WPA SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - - // you're connected now, so print out the data: - Serial.print("You're connected to the network"); - printCurrentNet(); - printWiFiData(); - -} - -void loop() { - // check the network connection once every 10 seconds: - delay(10000); - printCurrentNet(); -} - -void printWiFiData() { - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - Serial.println(ip); - - // print your MAC address: - byte mac[6]; - WiFi.macAddress(mac); - Serial.print("MAC address: "); - Serial.print(mac[5], HEX); - Serial.print(":"); - Serial.print(mac[4], HEX); - Serial.print(":"); - Serial.print(mac[3], HEX); - Serial.print(":"); - Serial.print(mac[2], HEX); - Serial.print(":"); - Serial.print(mac[1], HEX); - Serial.print(":"); - Serial.println(mac[0], HEX); - -} - -void printCurrentNet() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print the MAC address of the router you're attached to: - byte bssid[6]; - WiFi.BSSID(bssid); - Serial.print("BSSID: "); - Serial.print(bssid[5], HEX); - Serial.print(":"); - Serial.print(bssid[4], HEX); - Serial.print(":"); - Serial.print(bssid[3], HEX); - Serial.print(":"); - Serial.print(bssid[2], HEX); - Serial.print(":"); - Serial.print(bssid[1], HEX); - Serial.print(":"); - Serial.println(bssid[0], HEX); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.println(rssi); - - // print the encryption type: - byte encryption = WiFi.encryptionType(); - Serial.print("Encryption Type:"); - Serial.println(encryption, HEX); - Serial.println(); -} - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ConnectWithWPA/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino deleted file mode 100644 index 897c770..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/FirmwareUpdater/Endianess.ino +++ /dev/null @@ -1,62 +0,0 @@ -/* - Endianess.ino - Network byte order conversion functions. - Copyright (c) 2015 Arduino LLC. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - - -bool isBigEndian() { - uint32_t test = 0x11223344; - uint8_t *pTest = reinterpret_cast(&test); - return pTest[0] == 0x11; -} - -uint32_t fromNetwork32(uint32_t from) { - static const bool be = isBigEndian(); - if (be) { - return from; - } else { - uint8_t *pFrom = reinterpret_cast(&from); - uint32_t to; - to = pFrom[0]; to <<= 8; - to |= pFrom[1]; to <<= 8; - to |= pFrom[2]; to <<= 8; - to |= pFrom[3]; - return to; - } -} - -uint16_t fromNetwork16(uint16_t from) { - static bool be = isBigEndian(); - if (be) { - return from; - } else { - uint8_t *pFrom = reinterpret_cast(&from); - uint16_t to; - to = pFrom[0]; to <<= 8; - to |= pFrom[1]; - return to; - } -} - -uint32_t toNetwork32(uint32_t to) { - return fromNetwork32(to); -} - -uint16_t toNetwork16(uint16_t to) { - return fromNetwork16(to); -} - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino deleted file mode 100644 index 1bbd6b9..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/FirmwareUpdater/FirmwareUpdater.ino +++ /dev/null @@ -1,129 +0,0 @@ -/* - FirmwareUpdate.h - Firmware Updater for WiFi101 / WINC1500. - Copyright (c) 2015 Arduino LLC. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include -#include - -typedef struct __attribute__((__packed__)) { - uint8_t command; - uint32_t address; - uint32_t arg1; - uint16_t payloadLength; - - // payloadLenght bytes of data follows... -} UartPacket; - -static const int MAX_PAYLOAD_SIZE = 1024; - -#define CMD_READ_FLASH 0x01 -#define CMD_WRITE_FLASH 0x02 -#define CMD_ERASE_FLASH 0x03 -#define CMD_MAX_PAYLOAD_SIZE 0x50 -#define CMD_HELLO 0x99 - -void setup() { - Serial.begin(115200); - - nm_bsp_init(); - if (m2m_wifi_download_mode() != M2M_SUCCESS) { - Serial.println(F("Failed to put the WiFi module in download mode")); - while (true) - ; - } -} - -void receivePacket(UartPacket *pkt, uint8_t *payload) { - // Read command - uint8_t *p = reinterpret_cast(pkt); - uint16_t l = sizeof(UartPacket); - while (l > 0) { - int c = Serial.read(); - if (c == -1) - continue; - *p++ = c; - l--; - } - - // Convert parameters from network byte order to cpu byte order - pkt->address = fromNetwork32(pkt->address); - pkt->arg1 = fromNetwork32(pkt->arg1); - pkt->payloadLength = fromNetwork16(pkt->payloadLength); - - // Read payload - l = pkt->payloadLength; - while (l > 0) { - int c = Serial.read(); - if (c == -1) - continue; - *payload++ = c; - l--; - } -} - -// Allocated statically so the compiler can tell us -// about the amount of used RAM -static UartPacket pkt; -static uint8_t payload[MAX_PAYLOAD_SIZE]; - -void loop() { - receivePacket(&pkt, payload); - - if (pkt.command == CMD_HELLO) { - if (pkt.address == 0x11223344 && pkt.arg1 == 0x55667788) - Serial.print("v10000"); - } - - if (pkt.command == CMD_MAX_PAYLOAD_SIZE) { - uint16_t res = toNetwork16(MAX_PAYLOAD_SIZE); - Serial.write(reinterpret_cast(&res), sizeof(res)); - } - - if (pkt.command == CMD_READ_FLASH) { - uint32_t address = pkt.address; - uint32_t len = pkt.arg1; - if (spi_flash_read(payload, address, len) != M2M_SUCCESS) { - Serial.println("ER"); - } else { - Serial.write(payload, len); - Serial.print("OK"); - } - } - - if (pkt.command == CMD_WRITE_FLASH) { - uint32_t address = pkt.address; - uint32_t len = pkt.payloadLength; - if (spi_flash_write(payload, address, len) != M2M_SUCCESS) { - Serial.print("ER"); - } else { - Serial.print("OK"); - } - } - - if (pkt.command == CMD_ERASE_FLASH) { - uint32_t address = pkt.address; - uint32_t len = pkt.arg1; - if (spi_flash_erase(address, len) != M2M_SUCCESS) { - Serial.print("ER"); - } else { - Serial.print("OK"); - } - } -} - - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino deleted file mode 100644 index f62ac62..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/MDNS_WiFiWebServer.ino +++ /dev/null @@ -1,170 +0,0 @@ -/* - MDNS WiFi Web Server - - A simple web server that shows the value of the analog input pins, - and exposes itself on the MDNS name 'wifi101.local'. - - On Linux (like Ubuntu 15.04) or OSX you can access the web page - on the device in a browser at 'http://wifi101.local/'. - - On Windows you'll first need to install the Bonjour Printer Services - from: - https://support.apple.com/kb/dl999?locale=en_US - Then you can access the device in a browser at 'http://wifi101.local/'. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the WiFi.begin() call accordingly. - - Circuit: - * WiFi shield attached - * Analog inputs attached to pins A0 through A5 (optional) - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - modified 27 January 2016 - by Tony DiCola - -*/ - -#include -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -char mdnsName[] = "wifi101"; // the MDNS name that the board will respond to -// Note that the actual MDNS name will have '.local' after -// the name above, so "wifi101" will be accessible on -// the MDNS name "wifi101.local". - -int status = WL_IDLE_STATUS; - -// Create a MDNS responder to listen and respond to MDNS name requests. -WiFiMDNSResponder mdnsResponder; - -WiFiServer server(80); - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - // you're connected now, so print out the status: - printWiFiStatus(); - - server.begin(); - - // Setup the MDNS responder to listen to the configured name. - // NOTE: You _must_ call this _after_ connecting to the WiFi network and - // being assigned an IP address. - if (!mdnsResponder.begin(mdnsName)) { - Serial.println("Failed to start MDNS responder!"); - while(1); - } - - Serial.print("Server listening at http://"); - Serial.print(mdnsName); - Serial.println(".local/"); -} - - -void loop() { - // Call the update() function on the MDNS responder every loop iteration to - // make sure it can detect and respond to name requests. - mdnsResponder.poll(); - - // listen for incoming clients - WiFiClient client = server.available(); - if (client) { - Serial.println("new client"); - // an http request ends with a blank line - boolean currentLineIsBlank = true; - while (client.connected()) { - if (client.available()) { - char c = client.read(); - Serial.write(c); - // if you've gotten to the end of the line (received a newline - // character) and the line is blank, the http request has ended, - // so you can send a reply - if (c == '\n' && currentLineIsBlank) { - // send a standard http response header - client.println("HTTP/1.1 200 OK"); - client.println("Content-Type: text/html"); - client.println("Connection: close"); // the connection will be closed after completion of the response - client.println("Refresh: 5"); // refresh the page automatically every 5 sec - client.println(); - client.println(""); - client.println(""); - // output the value of each analog input pin - for (int analogChannel = 0; analogChannel < 6; analogChannel++) { - int sensorReading = analogRead(analogChannel); - client.print("analog input "); - client.print(analogChannel); - client.print(" is "); - client.print(sensorReading); - client.println("
"); - } - client.println(""); - break; - } - if (c == '\n') { - // you're starting a new line - currentLineIsBlank = true; - } - else if (c != '\r') { - // you've gotten a character on the current line - currentLineIsBlank = false; - } - } - } - // give the web browser time to receive the data - delay(1); - - // close the connection: - client.stop(); - Serial.println("client disconnected"); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/MDNS_WiFiWebServer/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino deleted file mode 100644 index 0297707..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/Provisioning_WiFiWebServer/Provisioning_WiFiWebServer.ino +++ /dev/null @@ -1,167 +0,0 @@ -/* - WiFi Web Server - - A simple web server that shows the value of the analog input pins. - using a WiFi shield. - - This example is written to configure the WiFi settings using provisioning mode. - It also sets up an mDNS server so the IP address of the board doesn't have to - be obtained via the serial monitor. - - Circuit: - WiFi shield attached - Analog inputs attached to pins A0 through A5 (optional) - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - -*/ - -#include -#include -#include - -const int ledPin = 6; // LED pin for connectivity status indicator - -char mdnsName[] = "wifi101"; // the MDNS name that the board will respond to - // after WiFi settings have been provisioned -// Note that the actual MDNS name will have '.local' after -// the name above, so "wifi101" will be accessible on -// the MDNS name "wifi101.local". - -WiFiServer server(80); - -// Create a MDNS responder to listen and respond to MDNS name requests. -WiFiMDNSResponder mdnsResponder; - -void setup() { - //Initialize serial: - Serial.begin(9600); - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // configure the LED pin for output mode - pinMode(ledPin, OUTPUT); - - // Start in provisioning mode: - // 1) This will try to connect to a previously associated access point. - // 2) If this fails, an access point named "wifi101-XXXX" will be created, where XXXX - // is the last 4 digits of the boards MAC address. Once you are connected to the access point, - // you can configure an SSID and password by visiting http://wifi101/ - WiFi.beginProvision(); - - while (WiFi.status() != WL_CONNECTED) { - // wait while not connected - - // blink the led to show an unconnected status - digitalWrite(ledPin, HIGH); - delay(500); - digitalWrite(ledPin, LOW); - delay(500); - } - - // connected, make the LED stay on - digitalWrite(ledPin, HIGH); - - server.begin(); - - // Setup the MDNS responder to listen to the configured name. - // NOTE: You _must_ call this _after_ connecting to the WiFi network and - // being assigned an IP address. - if (!mdnsResponder.begin(mdnsName)) { - Serial.println("Failed to start MDNS responder!"); - while(1); - } - - Serial.print("Server listening at http://"); - Serial.print(mdnsName); - Serial.println(".local/"); - - // you're connected now, so print out the status: - printWiFiStatus(); -} - - -void loop() { - // Call the update() function on the MDNS responder every loop iteration to - // make sure it can detect and respond to name requests. - mdnsResponder.poll(); - - // listen for incoming clients - WiFiClient client = server.available(); - if (client) { - Serial.println("new client"); - // an http request ends with a blank line - boolean currentLineIsBlank = true; - while (client.connected()) { - if (client.available()) { - char c = client.read(); - Serial.write(c); - // if you've gotten to the end of the line (received a newline - // character) and the line is blank, the http request has ended, - // so you can send a reply - if (c == '\n' && currentLineIsBlank) { - // send a standard http response header - client.println("HTTP/1.1 200 OK"); - client.println("Content-Type: text/html"); - client.println("Connection: close"); // the connection will be closed after completion of the response - client.println("Refresh: 5"); // refresh the page automatically every 5 sec - client.println(); - client.println(""); - client.println(""); - // output the value of each analog input pin - for (int analogChannel = 0; analogChannel < 6; analogChannel++) { - int sensorReading = analogRead(analogChannel); - client.print("analog input "); - client.print(analogChannel); - client.print(" is "); - client.print(sensorReading); - client.println("
"); - } - client.println(""); - break; - } - if (c == '\n') { - // you're starting a new line - currentLineIsBlank = true; - } - else if (c != '\r') { - // you've gotten a character on the current line - currentLineIsBlank = false; - } - } - } - // give the web browser time to receive the data - delay(1); - - // close the connection: - client.stop(); - Serial.println("client disonnected"); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino deleted file mode 100644 index 45b908e..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino +++ /dev/null @@ -1,120 +0,0 @@ -/* - - This example prints the WiFi shield's MAC address, and - scans for available WiFi networks using the WiFi shield. - Every ten seconds, it scans again. It doesn't actually - connect to any network, so no encryption scheme is specified. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 21 Junn 2012 - by Tom Igoe and Jaymes Dec - */ - - -#include -#include - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // Print WiFi MAC address: - printMacAddress(); - - // scan for existing networks: - Serial.println("Scanning available networks..."); - listNetworks(); -} - -void loop() { - delay(10000); - // scan for existing networks: - Serial.println("Scanning available networks..."); - listNetworks(); -} - -void printMacAddress() { - // the MAC address of your WiFi shield - byte mac[6]; - - // print your MAC address: - WiFi.macAddress(mac); - Serial.print("MAC: "); - Serial.print(mac[5], HEX); - Serial.print(":"); - Serial.print(mac[4], HEX); - Serial.print(":"); - Serial.print(mac[3], HEX); - Serial.print(":"); - Serial.print(mac[2], HEX); - Serial.print(":"); - Serial.print(mac[1], HEX); - Serial.print(":"); - Serial.println(mac[0], HEX); -} - -void listNetworks() { - // scan for nearby networks: - Serial.println("** Scan Networks **"); - int numSsid = WiFi.scanNetworks(); - if (numSsid == -1) - { - Serial.println("Couldn't get a wifi connection"); - while (true); - } - - // print the list of networks seen: - Serial.print("number of available networks:"); - Serial.println(numSsid); - - // print the network number and name for each network found: - for (int thisNet = 0; thisNet < numSsid; thisNet++) { - Serial.print(thisNet); - Serial.print(") "); - Serial.print(WiFi.SSID(thisNet)); - Serial.print("\tSignal: "); - Serial.print(WiFi.RSSI(thisNet)); - Serial.print(" dBm"); - Serial.print("\tEncryption: "); - printEncryptionType(WiFi.encryptionType(thisNet)); - Serial.flush(); - } -} - -void printEncryptionType(int thisType) { - // read the encryption type and print out the name: - switch (thisType) { - case ENC_TYPE_WEP: - Serial.println("WEP"); - break; - case ENC_TYPE_TKIP: - Serial.println("WPA"); - break; - case ENC_TYPE_CCMP: - Serial.println("WPA2"); - break; - case ENC_TYPE_NONE: - Serial.println("None"); - break; - case ENC_TYPE_AUTO: - Serial.println("Auto"); - break; - } -} - - - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino deleted file mode 100644 index 2afb544..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/ScanNetworksAdvanced/ScanNetworksAdvanced.ino +++ /dev/null @@ -1,149 +0,0 @@ -/* - - This example prints the WiFi 101 shield or MKR1000 MAC address, and - scans for available WiFi networks using the WiFi 101 shield or MKR1000 board. - Every ten seconds, it scans again. It doesn't actually - connect to any network, so no encryption scheme is specified. - BSSID and WiFi channel are printed - - Circuit: - WiFi 101 shield attached or MKR1000 board - - This example is based on ScanNetworks - - created 1 Mar 2017 - by Arturo Guadalupi -*/ - - -#include -#include - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // Print WiFi MAC address: - printMacAddress(); - - // scan for existing networks: - Serial.println(); - Serial.println("Scanning available networks..."); - listNetworks(); -} - -void loop() { - delay(10000); - // scan for existing networks: - Serial.println("Scanning available networks..."); - listNetworks(); -} - -void printMacAddress() { - // the MAC address of your WiFi shield - byte mac[6]; - - // print your MAC address: - WiFi.macAddress(mac); - Serial.print("MAC: "); - print2Digits(mac[5]); - Serial.print(":"); - print2Digits(mac[4]); - Serial.print(":"); - print2Digits(mac[3]); - Serial.print(":"); - print2Digits(mac[2]); - Serial.print(":"); - print2Digits(mac[1]); - Serial.print(":"); - print2Digits(mac[0]); -} - -void listNetworks() { - // scan for nearby networks: - Serial.println("** Scan Networks **"); - int numSsid = WiFi.scanNetworks(); - if (numSsid == -1) - { - Serial.println("Couldn't get a WiFi connection"); - while (true); - } - - // print the list of networks seen: - Serial.print("number of available networks: "); - Serial.println(numSsid); - - // print the network number and name for each network found: - for (int thisNet = 0; thisNet < numSsid; thisNet++) { - Serial.print(thisNet + 1); - Serial.print(") "); - Serial.print("Signal: "); - Serial.print(WiFi.RSSI(thisNet)); - Serial.print(" dBm"); - Serial.print("\tChannel: "); - Serial.print(WiFi.channel(thisNet)); - byte bssid[6]; - Serial.print("\t\tBSSID: "); - printBSSID(WiFi.BSSID(thisNet, bssid)); - Serial.print("\tEncryption: "); - printEncryptionType(WiFi.encryptionType(thisNet)); - Serial.print("\t\tSSID: "); - Serial.println(WiFi.SSID(thisNet)); - Serial.flush(); - } - Serial.println(); -} - -void printBSSID(byte bssid[]) { - print2Digits(bssid[5]); - Serial.print(":"); - print2Digits(bssid[4]); - Serial.print(":"); - print2Digits(bssid[3]); - Serial.print(":"); - print2Digits(bssid[2]); - Serial.print(":"); - print2Digits(bssid[1]); - Serial.print(":"); - print2Digits(bssid[0]); -} - -void printEncryptionType(int thisType) { - // read the encryption type and print out the name: - switch (thisType) { - case ENC_TYPE_WEP: - Serial.print("WEP"); - break; - case ENC_TYPE_TKIP: - Serial.print("WPA"); - break; - case ENC_TYPE_CCMP: - Serial.print("WPA2"); - break; - case ENC_TYPE_NONE: - Serial.print("None"); - break; - case ENC_TYPE_AUTO: - Serial.print("Auto"); - break; - } -} - -void print2Digits(byte thisByte) { - if (thisByte < 0xF) { - Serial.print("0"); - } - Serial.print(thisByte, HEX); -} - - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino deleted file mode 100644 index aeaf0c6..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/SimpleWebServerWiFi.ino +++ /dev/null @@ -1,131 +0,0 @@ -/* - WiFi Web Server LED Blink - - A simple web server that lets you blink an LED via the web. - This sketch will print the IP address of your WiFi Shield (once connected) - to the Serial monitor. From there, you can open that address in a web browser - to turn on and off the LED on pin 9. - - If the IP address of your shield is yourAddress: - http://yourAddress/H turns the LED on - http://yourAddress/L turns it off - - This example is written for a network using WPA encryption. For - WEP or WPA, change the WiFi.begin() call accordingly. - - Circuit: - * WiFi shield attached - * LED attached to pin 9 - - created 25 Nov 2012 - by Tom Igoe - */ -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; -WiFiServer server(80); - -void setup() { - Serial.begin(9600); // initialize serial communication - pinMode(9, OUTPUT); // set the LED pin mode - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - while (true); // don't continue - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to Network named: "); - Serial.println(ssid); // print the network name (SSID); - - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - // wait 10 seconds for connection: - delay(10000); - } - server.begin(); // start the web server on port 80 - printWiFiStatus(); // you're connected now, so print out the status -} - - -void loop() { - WiFiClient client = server.available(); // listen for incoming clients - - if (client) { // if you get a client, - Serial.println("new client"); // print a message out the serial port - String currentLine = ""; // make a String to hold incoming data from the client - while (client.connected()) { // loop while the client's connected - if (client.available()) { // if there's bytes to read from the client, - char c = client.read(); // read a byte, then - Serial.write(c); // print it out the serial monitor - if (c == '\n') { // if the byte is a newline character - - // if the current line is blank, you got two newline characters in a row. - // that's the end of the client HTTP request, so send a response: - if (currentLine.length() == 0) { - // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) - // and a content-type so the client knows what's coming, then a blank line: - client.println("HTTP/1.1 200 OK"); - client.println("Content-type:text/html"); - client.println(); - - // the content of the HTTP response follows the header: - client.print("Click here turn the LED on pin 9 on
"); - client.print("Click here turn the LED on pin 9 off
"); - - // The HTTP response ends with another blank line: - client.println(); - // break out of the while loop: - break; - } - else { // if you got a newline, then clear currentLine: - currentLine = ""; - } - } - else if (c != '\r') { // if you got anything else but a carriage return character, - currentLine += c; // add it to the end of the currentLine - } - - // Check to see if the client request was "GET /H" or "GET /L": - if (currentLine.endsWith("GET /H")) { - digitalWrite(9, HIGH); // GET /H turns the LED on - } - if (currentLine.endsWith("GET /L")) { - digitalWrite(9, LOW); // GET /L turns the LED off - } - } - } - // close the connection: - client.stop(); - Serial.println("client disonnected"); - } -} - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); - // print where to go in a browser: - Serial.print("To see this page in action, open a browser to http://"); - Serial.println(ip); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/SimpleWebServerWiFi/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino deleted file mode 100644 index ac7bd76..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiChatServer/WiFiChatServer.ino +++ /dev/null @@ -1,114 +0,0 @@ -/* - Chat Server - - A simple server that distributes any incoming messages to all - connected clients. To use telnet to your device's IP address and type. - You can see the client's input in the serial monitor as well. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the WiFi.begin() call accordingly. - - - Circuit: - * WiFi shield attached - - created 18 Dec 2009 - by David A. Mellis - modified 31 May 2012 - by Tom Igoe - - */ - -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) - -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; - -WiFiServer server(23); - -boolean alreadyConnected = false; // whether or not the client was connected previously - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - - // start the server: - server.begin(); - // you're connected now, so print out the status: - printWiFiStatus(); -} - - -void loop() { - // wait for a new client: - WiFiClient client = server.available(); - - - // when the client sends the first byte, say hello: - if (client) { - if (!alreadyConnected) { - // clead out the input buffer: - client.flush(); - Serial.println("We have a new client"); - client.println("Hello, client!"); - alreadyConnected = true; - } - - if (client.available() > 0) { - // read the bytes incoming from the client: - char thisChar = client.read(); - // echo the bytes back to the client: - server.write(thisChar); - // echo the bytes to the server as well: - Serial.write(thisChar); - } - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiChatServer/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino deleted file mode 100644 index 9a51c19..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiPing/WiFiPing.ino +++ /dev/null @@ -1,140 +0,0 @@ -/* - - This example connects to a encrypted WiFi network (WPA/WPA2). - Then it prints the MAC address of the WiFi shield, - the IP address obtained, and other network details. - Then it continuously pings given host specified by IP Address or name. - - Circuit: - WiFi shield attached / MKR1000 - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 09 June 2016 - by Petar Georgiev -*/ -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int status = WL_IDLE_STATUS; // the WiFi radio's status - -// Specify IP address or hostname -String hostName = "www.google.com"; -int pingResult; - -void setup() { - // Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to WPA SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network: - status = WiFi.begin(ssid, pass); - - // wait 5 seconds for connection: - delay(5000); - } - - // you're connected now, so print out the data: - Serial.println("You're connected to the network"); - printCurrentNet(); - printWiFiData(); -} - -void loop() { - Serial.print("Pinging "); - Serial.print(hostName); - Serial.print(": "); - - pingResult = WiFi.ping(hostName); - - if (pingResult >= 0) { - Serial.print("SUCCESS! RTT = "); - Serial.print(pingResult); - Serial.println(" ms"); - } else { - Serial.print("FAILED! Error code: "); - Serial.println(pingResult); - } - - delay(5000); -} - -void printWiFiData() { - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP address : "); - Serial.println(ip); - - Serial.print("Subnet mask: "); - Serial.println((IPAddress)WiFi.subnetMask()); - - Serial.print("Gateway IP : "); - Serial.println((IPAddress)WiFi.gatewayIP()); - - // print your MAC address: - byte mac[6]; - WiFi.macAddress(mac); - Serial.print("MAC address: "); - Serial.print(mac[5], HEX); - Serial.print(":"); - Serial.print(mac[4], HEX); - Serial.print(":"); - Serial.print(mac[3], HEX); - Serial.print(":"); - Serial.print(mac[2], HEX); - Serial.print(":"); - Serial.print(mac[1], HEX); - Serial.print(":"); - Serial.println(mac[0], HEX); - Serial.println(); -} - -void printCurrentNet() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print the MAC address of the router you're attached to: - byte bssid[6]; - WiFi.BSSID(bssid); - Serial.print("BSSID: "); - Serial.print(bssid[5], HEX); - Serial.print(":"); - Serial.print(bssid[4], HEX); - Serial.print(":"); - Serial.print(bssid[3], HEX); - Serial.print(":"); - Serial.print(bssid[2], HEX); - Serial.print(":"); - Serial.print(bssid[1], HEX); - Serial.print(":"); - Serial.println(bssid[0], HEX); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI): "); - Serial.println(rssi); - - // print the encryption type: - byte encryption = WiFi.encryptionType(); - Serial.print("Encryption Type: "); - Serial.println(encryption, HEX); - Serial.println(); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiPing/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino deleted file mode 100644 index a436902..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiSSLClient/WiFiSSLClient.ino +++ /dev/null @@ -1,107 +0,0 @@ -/* -This example creates a client object that connects and transfers -data using always SSL. - -It is compatible with the methods normally related to plain -connections, like client.connect(host, port). - -Written by Arturo Guadalupi -last revision November 2015 - -*/ - -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; -// if you don't want to use DNS (and reduce your sketch size) -// use the numeric IP instead of the name for the server: -//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) -char server[] = "www.google.com"; // name address for Google (using DNS) - -// Initialize the Ethernet client library -// with the IP address and port of the server -// that you want to connect to (port 80 is default for HTTP): -WiFiSSLClient client; - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while (status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - Serial.println("Connected to wifi"); - printWiFiStatus(); - - Serial.println("\nStarting connection to server..."); - // if you get a connection, report back via serial: - if (client.connect(server, 443)) { - Serial.println("connected to server"); - // Make a HTTP request: - client.println("GET /search?q=arduino HTTP/1.1"); - client.println("Host: www.google.com"); - client.println("Connection: close"); - client.println(); - } -} - -void loop() { - // if there are incoming bytes available - // from the server, read them and print them: - while (client.available()) { - char c = client.read(); - Serial.write(c); - } - - // if the server's disconnected, stop the client: - if (!client.connected()) { - Serial.println(); - Serial.println("disconnecting from server."); - client.stop(); - - // do nothing forevermore: - while (true); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiSSLClient/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino deleted file mode 100644 index e82fbaa..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/WiFiUdpNtpClient.ino +++ /dev/null @@ -1,182 +0,0 @@ -/* - - Udp NTP Client - - Get the time from a Network Time Protocol (NTP) time server - Demonstrates use of UDP sendPacket and ReceivePacket - For more on NTP time servers and the messages needed to communicate with them, - see http://en.wikipedia.org/wiki/Network_Time_Protocol - - created 4 Sep 2010 - by Michael Margolis - modified 9 Apr 2012 - by Tom Igoe - - This code is in the public domain. - - */ - -#include -#include -#include - -int status = WL_IDLE_STATUS; -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -unsigned int localPort = 2390; // local port to listen for UDP packets - -IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server - -const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message - -byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets - -// A UDP instance to let us send and receive packets over UDP -WiFiUDP Udp; - -void setup() -{ - // Open serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - - Serial.println("Connected to wifi"); - printWiFiStatus(); - - Serial.println("\nStarting connection to server..."); - Udp.begin(localPort); -} - -void loop() -{ - sendNTPpacket(timeServer); // send an NTP packet to a time server - // wait to see if a reply is available - delay(1000); - if ( Udp.parsePacket() ) { - Serial.println("packet received"); - // We've received a packet, read the data from it - Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer - - //the timestamp starts at byte 40 of the received packet and is four bytes, - // or two words, long. First, esxtract the two words: - - unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); - unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); - // combine the four bytes (two words) into a long integer - // this is NTP time (seconds since Jan 1 1900): - unsigned long secsSince1900 = highWord << 16 | lowWord; - Serial.print("Seconds since Jan 1 1900 = " ); - Serial.println(secsSince1900); - - // now convert NTP time into everyday time: - Serial.print("Unix time = "); - // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: - const unsigned long seventyYears = 2208988800UL; - // subtract seventy years: - unsigned long epoch = secsSince1900 - seventyYears; - // print Unix time: - Serial.println(epoch); - - - // print the hour, minute and second: - Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) - Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) - Serial.print(':'); - if ( ((epoch % 3600) / 60) < 10 ) { - // In the first 10 minutes of each hour, we'll want a leading '0' - Serial.print('0'); - } - Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) - Serial.print(':'); - if ( (epoch % 60) < 10 ) { - // In the first 10 seconds of each minute, we'll want a leading '0' - Serial.print('0'); - } - Serial.println(epoch % 60); // print the second - } - // wait ten seconds before asking for the time again - delay(10000); -} - -// send an NTP request to the time server at the given address -unsigned long sendNTPpacket(IPAddress& address) -{ - //Serial.println("1"); - // set all bytes in the buffer to 0 - memset(packetBuffer, 0, NTP_PACKET_SIZE); - // Initialize values needed to form NTP request - // (see URL above for details on the packets) - //Serial.println("2"); - packetBuffer[0] = 0b11100011; // LI, Version, Mode - packetBuffer[1] = 0; // Stratum, or type of clock - packetBuffer[2] = 6; // Polling Interval - packetBuffer[3] = 0xEC; // Peer Clock Precision - // 8 bytes of zero for Root Delay & Root Dispersion - packetBuffer[12] = 49; - packetBuffer[13] = 0x4E; - packetBuffer[14] = 49; - packetBuffer[15] = 52; - - //Serial.println("3"); - - // all NTP fields have been given values, now - // you can send a packet requesting a timestamp: - Udp.beginPacket(address, 123); //NTP requests are to port 123 - //Serial.println("4"); - Udp.write(packetBuffer, NTP_PACKET_SIZE); - //Serial.println("5"); - Udp.endPacket(); - //Serial.println("6"); -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - - - - - - - - - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpNtpClient/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino deleted file mode 100644 index cbc9f7f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/WiFiUdpSendReceiveString.ino +++ /dev/null @@ -1,113 +0,0 @@ -/* - WiFi UDP Send and Receive String - - This sketch wait an UDP packet on localPort using a WiFi shield. - When a packet is received an Acknowledge packet is sent to the client on port remotePort - - Circuit: - * WiFi shield attached - - created 30 December 2012 - by dlf (Metodo2 srl) - - */ - - -#include -#include -#include - -int status = WL_IDLE_STATUS; -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -unsigned int localPort = 2390; // local port to listen on - -char packetBuffer[255]; //buffer to hold incoming packet -char ReplyBuffer[] = "acknowledged"; // a string to send back - -WiFiUDP Udp; - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - Serial.println("Connected to wifi"); - printWiFiStatus(); - - Serial.println("\nStarting connection to server..."); - // if you get a connection, report back via serial: - Udp.begin(localPort); -} - -void loop() { - - // if there's data available, read a packet - int packetSize = Udp.parsePacket(); - if (packetSize) - { - Serial.print("Received packet of size "); - Serial.println(packetSize); - Serial.print("From "); - IPAddress remoteIp = Udp.remoteIP(); - Serial.print(remoteIp); - Serial.print(", port "); - Serial.println(Udp.remotePort()); - - // read the packet into packetBufffer - int len = Udp.read(packetBuffer, 255); - if (len > 0) packetBuffer[len] = 0; - Serial.println("Contents:"); - Serial.println(packetBuffer); - - // send a reply, to the IP address and port that sent us the packet we received - Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); - Udp.write(ReplyBuffer); - Udp.endPacket(); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - - - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiUdpSendReceiveString/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino deleted file mode 100644 index 5faa779..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClient/WiFiWebClient.ino +++ /dev/null @@ -1,121 +0,0 @@ -/* - Web client - - This sketch connects to a website (http://www.google.com) - using a WiFi shield. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the WiFi.begin() call accordingly. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the WiFi.begin() call accordingly. - - Circuit: - * WiFi shield attached - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - */ - - -#include -#include -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; -// if you don't want to use DNS (and reduce your sketch size) -// use the numeric IP instead of the name for the server: -//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) -char server[] = "www.google.com"; // name address for Google (using DNS) - -// Initialize the Ethernet client library -// with the IP address and port of the server -// that you want to connect to (port 80 is default for HTTP): -WiFiClient client; - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while (status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - Serial.println("Connected to wifi"); - printWiFiStatus(); - - Serial.println("\nStarting connection to server..."); - // if you get a connection, report back via serial: - if (client.connect(server, 80)) { - Serial.println("connected to server"); - // Make a HTTP request: - client.println("GET /search?q=arduino HTTP/1.1"); - client.println("Host: www.google.com"); - client.println("Connection: close"); - client.println(); - } -} - -void loop() { - // if there are incoming bytes available - // from the server, read them and print them: - while (client.available()) { - char c = client.read(); - Serial.write(c); - } - - // if the server's disconnected, stop the client: - if (!client.connected()) { - Serial.println(); - Serial.println("disconnecting from server."); - client.stop(); - - // do nothing forevermore: - while (true); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} - - - - - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClient/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino deleted file mode 100644 index ac8b4e5..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/WiFiWebClientRepeating.ino +++ /dev/null @@ -1,127 +0,0 @@ -/* - Repeating WiFi Web Client - - This sketch connects to a a web server and makes a request - using an Arduino WiFi shield. - - Circuit: - * WiFi shield attached to pins SPI pins and pin 7 - - created 23 April 2012 - modified 31 May 2012 - by Tom Igoe - modified 13 Jan 2014 - by Federico Vanzati - - http://arduino.cc/en/Tutorial/WiFiWebClientRepeating - This code is in the public domain. - */ - -#include -#include - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; - -// Initialize the WiFi client library -WiFiClient client; - -// server address: -char server[] = "www.arduino.cc"; -//IPAddress server(64,131,82,241); - -unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds -const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while ( status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - // you're connected now, so print out the status: - printWiFiStatus(); -} - -void loop() { - // if there's incoming data from the net connection. - // send it out the serial port. This is for debugging - // purposes only: - while (client.available()) { - char c = client.read(); - Serial.write(c); - } - - // if ten seconds have passed since your last connection, - // then connect again and send data: - if (millis() - lastConnectionTime > postingInterval) { - httpRequest(); - } - -} - -// this method makes a HTTP connection to the server: -void httpRequest() { - // close any connection before send a new request. - // This will free the socket on the WiFi shield - client.stop(); - - // if there's a successful connection: - if (client.connect(server, 80)) { - Serial.println("connecting..."); - // send the HTTP PUT request: - client.println("GET /latest.txt HTTP/1.1"); - client.println("Host: www.arduino.cc"); - client.println("User-Agent: ArduinoWiFi/1.1"); - client.println("Connection: close"); - client.println(); - - // note the time that the connection was made: - lastConnectionTime = millis(); - } - else { - // if you couldn't make a connection: - Serial.println("connection failed"); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebClientRepeating/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino deleted file mode 100644 index 24d0083..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebServer/WiFiWebServer.ino +++ /dev/null @@ -1,135 +0,0 @@ -/* - WiFi Web Server - - A simple web server that shows the value of the analog input pins. - using a WiFi shield. - - This example is written for a network using WPA encryption. For - WEP or WPA, change the WiFi.begin() call accordingly. - - Circuit: - * WiFi shield attached - * Analog inputs attached to pins A0 through A5 (optional) - - created 13 July 2010 - by dlf (Metodo2 srl) - modified 31 May 2012 - by Tom Igoe - - */ - -#include -#include - - -#include "arduino_secrets.h" -///////please enter your sensitive data in the Secret tab/arduino_secrets.h -char ssid[] = SECRET_SSID; // your network SSID (name) -char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) -int keyIndex = 0; // your network key Index number (needed only for WEP) - -int status = WL_IDLE_STATUS; - -WiFiServer server(80); - -void setup() { - //Initialize serial and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only - } - - // check for the presence of the shield: - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to WiFi network: - while (status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - // wait 10 seconds for connection: - delay(10000); - } - server.begin(); - // you're connected now, so print out the status: - printWiFiStatus(); -} - - -void loop() { - // listen for incoming clients - WiFiClient client = server.available(); - if (client) { - Serial.println("new client"); - // an http request ends with a blank line - boolean currentLineIsBlank = true; - while (client.connected()) { - if (client.available()) { - char c = client.read(); - Serial.write(c); - // if you've gotten to the end of the line (received a newline - // character) and the line is blank, the http request has ended, - // so you can send a reply - if (c == '\n' && currentLineIsBlank) { - // send a standard http response header - client.println("HTTP/1.1 200 OK"); - client.println("Content-Type: text/html"); - client.println("Connection: close"); // the connection will be closed after completion of the response - client.println("Refresh: 5"); // refresh the page automatically every 5 sec - client.println(); - client.println(""); - client.println(""); - // output the value of each analog input pin - for (int analogChannel = 0; analogChannel < 6; analogChannel++) { - int sensorReading = analogRead(analogChannel); - client.print("analog input "); - client.print(analogChannel); - client.print(" is "); - client.print(sensorReading); - client.println("
"); - } - client.println(""); - break; - } - if (c == '\n') { - // you're starting a new line - currentLineIsBlank = true; - } - else if (c != '\r') { - // you've gotten a character on the current line - currentLineIsBlank = false; - } - } - } - // give the web browser time to receive the data - delay(1); - - // close the connection: - client.stop(); - Serial.println("client disconnected"); - } -} - - -void printWiFiStatus() { - // print the SSID of the network you're attached to: - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print your WiFi shield's IP address: - IPAddress ip = WiFi.localIP(); - Serial.print("IP Address: "); - Serial.println(ip); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h deleted file mode 100644 index a8ff904..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/examples/WiFiWebServer/arduino_secrets.h +++ /dev/null @@ -1,3 +0,0 @@ -#define SECRET_SSID "" -#define SECRET_PASS "" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/keywords.txt b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/keywords.txt deleted file mode 100644 index 498954d..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/keywords.txt +++ /dev/null @@ -1,61 +0,0 @@ -####################################### -# Syntax Coloring Map For WiFi -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -WiFi KEYWORD1 -WiFi101 KEYWORD1 -Client KEYWORD1 -Server KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -setPins KEYWORD2 -status KEYWORD2 -connect KEYWORD2 -connectSSL KEYWORD2 -write KEYWORD2 -available KEYWORD2 -read KEYWORD2 -flush KEYWORD2 -stop KEYWORD2 -connected KEYWORD2 -begin KEYWORD2 -beginProvision KEYWORD2 -beginOrProvision KEYWORD2 -beginMulticast KEYWORD2 -disconnect KEYWORD2 -macAddress KEYWORD2 -localIP KEYWORD2 -subnetMask KEYWORD2 -gatewayIP KEYWORD2 -SSID KEYWORD2 -BSSID KEYWORD2 -APClientMacAddress KEYWORD2 -RSSI KEYWORD2 -encryptionType KEYWORD2 -channel KEYWORD2 -provisioned KEYWORD2 -getResult KEYWORD2 -getSocket KEYWORD2 -poll KEYWORD2 -getTime KEYWORD2 -hostname KEYWORD2 -WiFiClient KEYWORD2 -WiFiServer KEYWORD2 -WiFiSSLClient KEYWORD2 -WiFiMDNSResponder KEYWORD2 - -lowPowerMode KEYWORD2 -maxLowPowerMode KEYWORD2 -noLowPowerMode KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/library.properties b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/library.properties deleted file mode 100644 index f6d0b6d..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/library.properties +++ /dev/null @@ -1,10 +0,0 @@ -name=WiFi101 -version=0.14.4 -author=Arduino -maintainer=Arduino -sentence=Network driver for ATMEL WINC1500 module (used on Arduino/Genuino Wifi Shield 101 and MKR1000 boards) -paragraph=This library implements a network driver for devices based on the ATMEL WINC1500 wifi module -category=Communication -url=http://www.arduino.cc/en/Reference/WiFi101 -architectures=* -includes=WiFi101.h diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFi.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFi.cpp deleted file mode 100644 index 0c71ffc..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFi.cpp +++ /dev/null @@ -1,1106 +0,0 @@ -/* - WiFi.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifdef ARDUINO_ARCH_AVR -#include -#if (__AVR_LIBC_MAJOR__ < 2) -#define WIFI_101_NO_TIME_H -#endif -#endif - -#ifndef WIFI_101_NO_TIME_H -#include -#endif - -#if !defined(_TIME_H_) && !defined(TIME_H) -// another library overrided the time.h header -#define WIFI_101_NO_TIME_H -#endif - -#include "WiFi101.h" - -extern "C" { - #include "bsp/include/nm_bsp.h" - #include "bsp/include/nm_bsp_arduino.h" - #include "socket/include/socket_buffer.h" - #include "socket/include/m2m_socket_host_if.h" - #include "driver/source/nmasic.h" - #include "driver/include/m2m_periph.h" - #include "driver/include/m2m_ssl.h" -} - -static void wifi_cb(uint8_t u8MsgType, void *pvMsg) -{ - switch (u8MsgType) { - case M2M_WIFI_RESP_DEFAULT_CONNECT: - { - tstrM2MDefaultConnResp *pstrDefaultConnResp = (tstrM2MDefaultConnResp *)pvMsg; - if (pstrDefaultConnResp->s8ErrorCode) { - WiFi._status = WL_DISCONNECTED; - } - } - break; - - case M2M_WIFI_RESP_CON_STATE_CHANGED: - { - tstrM2mWifiStateChanged *pstrWifiState = (tstrM2mWifiStateChanged *)pvMsg; - if (pstrWifiState->u8CurrState == M2M_WIFI_CONNECTED) { - //SERIAL_PORT_MONITOR.println("wifi_cb: M2M_WIFI_RESP_CON_STATE_CHANGED: CONNECTED"); - if (WiFi._mode == WL_STA_MODE && !WiFi._dhcp) { - WiFi._status = WL_CONNECTED; - - // WiFi led ON. - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); - } else if (WiFi._mode == WL_AP_MODE) { - WiFi._status = WL_AP_CONNECTED; - } - } else if (pstrWifiState->u8CurrState == M2M_WIFI_DISCONNECTED) { - //SERIAL_PORT_MONITOR.println("wifi_cb: M2M_WIFI_RESP_CON_STATE_CHANGED: DISCONNECTED"); - if (WiFi._mode == WL_STA_MODE) { - WiFi._status = WL_DISCONNECTED; - if (WiFi._dhcp) { - WiFi._localip = 0; - WiFi._submask = 0; - WiFi._gateway = 0; - } - // Close sockets to clean state - // Clients will need to reconnect once the physical link will be re-established - for (int i=0; i < TCP_SOCK_MAX; i++) { - if (WiFi._client[i]) - WiFi._client[i]->stop(); - } - } else if (WiFi._mode == WL_AP_MODE) { - WiFi._status = WL_AP_LISTENING; - } - // WiFi led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); - } - } - break; - - case M2M_WIFI_REQ_DHCP_CONF: - { - if (WiFi._mode == WL_STA_MODE) { - tstrM2MIPConfig *pstrIPCfg = (tstrM2MIPConfig *)pvMsg; - WiFi._localip = pstrIPCfg->u32StaticIP; - WiFi._submask = pstrIPCfg->u32SubnetMask; - WiFi._gateway = pstrIPCfg->u32Gateway; - - WiFi._status = WL_CONNECTED; - - // WiFi led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0); - } - /*uint8_t *pu8IPAddress = (uint8_t *)pvMsg; - SERIAL_PORT_MONITOR.print("wifi_cb: M2M_WIFI_REQ_DHCP_CONF: IP is "); - SERIAL_PORT_MONITOR.print(pu8IPAddress[0], 10); - SERIAL_PORT_MONITOR.print("."); - SERIAL_PORT_MONITOR.print(pu8IPAddress[1], 10); - SERIAL_PORT_MONITOR.print("."); - SERIAL_PORT_MONITOR.print(pu8IPAddress[2], 10); - SERIAL_PORT_MONITOR.print("."); - SERIAL_PORT_MONITOR.print(pu8IPAddress[3], 10); - SERIAL_PORT_MONITOR.println("");*/ - } - break; - - case M2M_WIFI_RESP_CURRENT_RSSI: - { - WiFi._resolve = *((int8_t *)pvMsg); - } - break; - - case M2M_WIFI_RESP_PROVISION_INFO: - { - tstrM2MProvisionInfo *pstrProvInfo = (tstrM2MProvisionInfo *)pvMsg; - //SERIAL_PORT_MONITOR.println("wifi_cb: M2M_WIFI_RESP_PROVISION_INFO"); - - if (pstrProvInfo->u8Status == M2M_SUCCESS) { - memset(WiFi._ssid, 0, M2M_MAX_SSID_LEN); - memcpy(WiFi._ssid, (char *)pstrProvInfo->au8SSID, strlen((char *)pstrProvInfo->au8SSID)); - WiFi._mode = WL_STA_MODE; - WiFi._localip = 0; - WiFi._submask = 0; - WiFi._gateway = 0; - m2m_wifi_connect((char *)pstrProvInfo->au8SSID, strlen((char *)pstrProvInfo->au8SSID), - pstrProvInfo->u8SecType, pstrProvInfo->au8Password, M2M_WIFI_CH_ALL); - } else { - WiFi._status = WL_PROVISIONING_FAILED; - //SERIAL_PORT_MONITOR.println("wifi_cb: Provision failed.\r\n"); - WiFi.beginProvision(); - } - } - break; - - case M2M_WIFI_RESP_SCAN_DONE: - { - tstrM2mScanDone *pstrInfo = (tstrM2mScanDone *)pvMsg; - if (pstrInfo->u8NumofCh >= 1) { - WiFi._status = WL_SCAN_COMPLETED; - } - } - break; - - case M2M_WIFI_RESP_SCAN_RESULT: - { - tstrM2mWifiscanResult *pstrScanResult = (tstrM2mWifiscanResult *)pvMsg; - uint16_t scan_ssid_len = strlen((const char *)pstrScanResult->au8SSID); - memset(WiFi._scan_ssid, 0, M2M_MAX_SSID_LEN); - if (scan_ssid_len) { - memcpy(WiFi._scan_ssid, (const char *)pstrScanResult->au8SSID, scan_ssid_len); - } - if (WiFi._remoteMacAddress) { - // reverse copy the remote MAC - for(int i = 0; i < 6; i++) { - WiFi._remoteMacAddress[i] = pstrScanResult->au8BSSID[5-i]; - } - } - WiFi._resolve = pstrScanResult->s8rssi; - WiFi._scan_auth = pstrScanResult->u8AuthType; - WiFi._scan_channel = pstrScanResult->u8ch; - WiFi._status = WL_SCAN_COMPLETED; - } - break; - - case M2M_WIFI_RESP_CONN_INFO: - { - tstrM2MConnInfo *pstrConnInfo = (tstrM2MConnInfo*)pvMsg; - - if (WiFi._remoteMacAddress) { - // reverse copy the remote MAC - for(int i = 0; i < 6; i++) { - WiFi._remoteMacAddress[i] = pstrConnInfo->au8MACAddress[5-i]; - } - WiFi._remoteMacAddress = 0; - } - - strcpy((char *)WiFi._ssid, pstrConnInfo->acSSID); - } - break; - - case M2M_WIFI_RESP_GET_SYS_TIME: - { - if (WiFi._resolve != 0) { - memcpy((tstrSystemTime *)WiFi._resolve, pvMsg, sizeof(tstrSystemTime)); - - WiFi._resolve = 0; - } - } - break; - - default: - break; - } -} - -static void resolve_cb(uint8_t * /* hostName */, uint32_t hostIp) -{ - WiFi._resolve = hostIp; -} - -static void ping_cb(uint32 u32IPAddr, uint32 u32RTT, uint8 u8ErrorCode) -{ - if (PING_ERR_SUCCESS == u8ErrorCode) { - // Ensure this ICMP reply comes from requested IP address - if (WiFi._resolve == u32IPAddr) { - WiFi._resolve = (uint32_t)u32RTT; - } else { - // Another network device replied to the our ICMP request - WiFi._resolve = (uint32_t)WL_PING_DEST_UNREACHABLE; - } - } else if (PING_ERR_DEST_UNREACH == u8ErrorCode) { - WiFi._resolve = (uint32_t)WL_PING_DEST_UNREACHABLE; - } else if (PING_ERR_TIMEOUT == u8ErrorCode) { - WiFi._resolve = (uint32_t)WL_PING_TIMEOUT; - } else { - WiFi._resolve = (uint32_t)WL_PING_ERROR; - } -} - -WiFiClass::WiFiClass() -{ - _mode = WL_RESET_MODE; - _status = WL_NO_SHIELD; - _init = 0; -} - -void WiFiClass::setPins(int8_t cs, int8_t irq, int8_t rst, int8_t en) -{ - gi8Winc1501CsPin = cs; - gi8Winc1501IntnPin = irq; - gi8Winc1501ResetPin = rst; - gi8Winc1501ChipEnPin = en; -} - -int WiFiClass::init() -{ - tstrWifiInitParam param; - int8_t ret; - - // Initialize the WiFi BSP: - nm_bsp_init(); - - // Initialize WiFi module and register status callback: - param.pfAppWifiCb = wifi_cb; - ret = m2m_wifi_init(¶m); - if (M2M_SUCCESS != ret && M2M_ERR_FW_VER_MISMATCH != ret) { - // Error led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO18, 0); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO6, 1); - return ret; - } - - // Initialize socket API and register socket callback: - socketInit(); - socketBufferInit(); - registerSocketCallback(socketBufferCb, resolve_cb); - _init = 1; - _status = WL_IDLE_STATUS; - _localip = 0; - _submask = 0; - _gateway = 0; - _dhcp = 1; - _resolve = 0; - _remoteMacAddress = 0; - memset(_client, 0, sizeof(WiFiClient *) * TCP_SOCK_MAX); - - extern uint32 nmdrv_firm_ver; - - if (nmdrv_firm_ver >= M2M_MAKE_VERSION(19, 5, 0)) { - // enable AES-128 and AES-256 Ciphers, if firmware is 19.5.0 or higher - m2m_ssl_set_active_ciphersuites(SSL_NON_ECC_CIPHERS_AES_128 | SSL_NON_ECC_CIPHERS_AES_256); - } - - // Initialize IO expander LED control (rev A then rev B).. - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO18, 1); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO15, 1); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO18, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO6, 1); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO4, 1); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO5, 1); - m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO6, 1); - - return ret; -} - -extern "C" { - sint8 nm_get_firmware_info(tstrM2mRev* M2mRev); -} - -char* WiFiClass::firmwareVersion() -{ - tstrM2mRev rev; - - if (!_init) { - init(); - } - nm_get_firmware_info(&rev); - memset(_version, 0, 9); - if (rev.u8FirmwareMajor != rev.u8DriverMajor && rev.u8FirmwareMinor != rev.u8DriverMinor) { - sprintf(_version, "-Err-"); - } - else { - sprintf(_version, "%d.%d.%d", rev.u8FirmwareMajor, rev.u8FirmwareMinor, rev.u8FirmwarePatch); - } - return _version; -} - -uint8_t WiFiClass::begin() -{ - if (!_init) { - init(); - } - - // Connect to router: - if (_dhcp) { - _localip = 0; - _submask = 0; - _gateway = 0; - } - if (m2m_wifi_default_connect() < 0) { - _status = WL_CONNECT_FAILED; - return _status; - } - _status = WL_IDLE_STATUS; - _mode = WL_STA_MODE; - - // Wait for connection or timeout: - unsigned long start = millis(); - while (!(_status & WL_CONNECTED) && - !(_status & WL_DISCONNECTED) && - millis() - start < 60000) { - m2m_wifi_handle_events(NULL); - } - - memset(_ssid, 0, M2M_MAX_SSID_LEN); - - if (!(_status & WL_CONNECTED)) { - _mode = WL_RESET_MODE; - } else { - m2m_wifi_get_connection_info(); - - m2m_wifi_handle_events(NULL); - } - - return _status; -} - -uint8_t WiFiClass::begin(const char *ssid) -{ - return startConnect(ssid, M2M_WIFI_SEC_OPEN, (void *)0); -} - -uint8_t WiFiClass::begin(const char *ssid, uint8_t key_idx, const char* key) -{ - tstrM2mWifiWepParams wep_params; - - memset(&wep_params, 0, sizeof(tstrM2mWifiWepParams)); - wep_params.u8KeyIndx = key_idx; - wep_params.u8KeySz = strlen(key); - strcpy((char *)&wep_params.au8WepKey[0], key); - return startConnect(ssid, M2M_WIFI_SEC_WEP, &wep_params); -} - -uint8_t WiFiClass::begin(const char *ssid, const char *key) -{ - return startConnect(ssid, M2M_WIFI_SEC_WPA_PSK, key); -} - -uint8_t WiFiClass::startConnect(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo) -{ - if (!_init) { - init(); - } - - // Connect to router: - if (_dhcp) { - _localip = 0; - _submask = 0; - _gateway = 0; - } - if (m2m_wifi_connect((char*)ssid, strlen(ssid), u8SecType, (void*)pvAuthInfo, M2M_WIFI_CH_ALL) < 0) { - _status = WL_CONNECT_FAILED; - return _status; - } - _status = WL_IDLE_STATUS; - _mode = WL_STA_MODE; - - // Wait for connection or timeout: - unsigned long start = millis(); - while (!(_status & WL_CONNECTED) && - !(_status & WL_DISCONNECTED) && - millis() - start < 60000) { - m2m_wifi_handle_events(NULL); - } - if (!(_status & WL_CONNECTED)) { - _mode = WL_RESET_MODE; - } - - memset(_ssid, 0, M2M_MAX_SSID_LEN); - memcpy(_ssid, ssid, strlen(ssid)); - return _status; -} - -uint8_t WiFiClass::beginAP(const char *ssid) -{ - return beginAP(ssid, 1); -} - -uint8_t WiFiClass::beginAP(const char *ssid, uint8_t channel) -{ - return startAP(ssid, M2M_WIFI_SEC_OPEN, NULL, channel); -} - -uint8_t WiFiClass::beginAP(const char *ssid, uint8_t key_idx, const char* key) -{ - return beginAP(ssid, key_idx, key, 1); -} - -uint8_t WiFiClass::beginAP(const char *ssid, uint8_t key_idx, const char* key, uint8_t channel) -{ - tstrM2mWifiWepParams wep_params; - - if (key_idx == 0) { - key_idx = 1; // 1 is the minimum key index - } - - memset(&wep_params, 0, sizeof(tstrM2mWifiWepParams)); - wep_params.u8KeyIndx = key_idx; - wep_params.u8KeySz = strlen(key); - strcpy((char *)&wep_params.au8WepKey[0], key); - - return startAP(ssid, M2M_WIFI_SEC_WEP, &wep_params, channel); -} - -uint8_t WiFiClass::beginAP(const char *ssid, const char* key) -{ - return beginAP(ssid, key, 1); -} - -uint8_t WiFiClass::beginAP(const char *ssid, const char* key, uint8_t channel) -{ - return startAP(ssid, M2M_WIFI_SEC_WPA_PSK, key, channel); -} - -uint8_t WiFiClass::startAP(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo, uint8_t channel) -{ - tstrM2MAPConfig strM2MAPConfig; - - if (!_init) { - init(); - } - - if (channel == 0) { - channel = 1; // channel 1 is the minium channel - } - - // Enter Access Point mode: - memset(&strM2MAPConfig, 0x00, sizeof(tstrM2MAPConfig)); - strcpy((char *)&strM2MAPConfig.au8SSID, ssid); - strM2MAPConfig.u8ListenChannel = channel; - strM2MAPConfig.u8SecType = u8SecType; - if (_localip == 0) { - strM2MAPConfig.au8DHCPServerIP[0] = 192; - strM2MAPConfig.au8DHCPServerIP[1] = 168; - strM2MAPConfig.au8DHCPServerIP[2] = 1; - strM2MAPConfig.au8DHCPServerIP[3] = 1; - } else { - memcpy(strM2MAPConfig.au8DHCPServerIP, &_localip, sizeof(_localip)); - if (strM2MAPConfig.au8DHCPServerIP[3] == 100) { - // limitation of WINC1500 firmware, IP address of client is always x.x.x.100 - _status = WL_AP_FAILED; - return _status; - } - } - - if (u8SecType == M2M_WIFI_SEC_WEP) { - tstrM2mWifiWepParams* wep_params = (tstrM2mWifiWepParams*)pvAuthInfo; - - strM2MAPConfig.u8KeyIndx = wep_params->u8KeyIndx; - strM2MAPConfig.u8KeySz = wep_params->u8KeySz; - strcpy((char*)strM2MAPConfig.au8WepKey, (char *)wep_params->au8WepKey); - } - - if (u8SecType == M2M_WIFI_SEC_WPA_PSK) { - strM2MAPConfig.u8KeySz = strlen((char*)pvAuthInfo); - strcpy((char*)strM2MAPConfig.au8Key, (char *)pvAuthInfo); - } - - if (m2m_wifi_enable_ap(&strM2MAPConfig) < 0) { - _status = WL_AP_FAILED; - return _status; - } - _status = WL_AP_LISTENING; - _mode = WL_AP_MODE; - - memset(_ssid, 0, M2M_MAX_SSID_LEN); - memcpy(_ssid, ssid, strlen(ssid)); - m2m_memcpy((uint8 *)&_localip, (uint8 *)&strM2MAPConfig.au8DHCPServerIP[0], 4); - _submask = 0x00FFFFFF; - _gateway = _localip; - - // WiFi led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0); - - return _status; -} - -uint8_t WiFiClass::beginProvision() -{ - return beginProvision(1); -} - -uint8_t WiFiClass::beginProvision(uint8_t channel) -{ - // try to connect using begin - if (begin() != WL_CONNECTED) { - // failed, enter provisioning mode - - uint8_t mac[6]; - char provSsid[13]; - - // get MAC address for provisioning SSID - macAddress(mac); - sprintf(provSsid, "wifi101-%.2X%2X", mac[1], mac[0]); - - // start provisioning mode - startProvision(provSsid, "wifi101", channel); - } - - return status(); -} - -uint8_t WiFiClass::startProvision(const char *ssid, const char *url, uint8_t channel) -{ - tstrM2MAPConfig strM2MAPConfig; - - if (!_init) { - init(); - } - - // Enter Provision mode: - memset(&strM2MAPConfig, 0x00, sizeof(tstrM2MAPConfig)); - strcpy((char *)&strM2MAPConfig.au8SSID, ssid); - strM2MAPConfig.u8ListenChannel = channel; - strM2MAPConfig.u8SecType = M2M_WIFI_SEC_OPEN; - strM2MAPConfig.u8SsidHide = SSID_MODE_VISIBLE; - strM2MAPConfig.au8DHCPServerIP[0] = 192; - strM2MAPConfig.au8DHCPServerIP[1] = 168; - strM2MAPConfig.au8DHCPServerIP[2] = 1; - strM2MAPConfig.au8DHCPServerIP[3] = 1; - - if (m2m_wifi_start_provision_mode((tstrM2MAPConfig *)&strM2MAPConfig, (char*)url, 1) < 0) { - _status = WL_PROVISIONING_FAILED; - return _status; - } - _status = WL_PROVISIONING; - _mode = WL_PROV_MODE; - - memset(_ssid, 0, M2M_MAX_SSID_LEN); - memcpy(_ssid, ssid, strlen(ssid)); - m2m_memcpy((uint8 *)&_localip, (uint8 *)&strM2MAPConfig.au8DHCPServerIP[0], 4); - _submask = 0x00FFFFFF; - _gateway = _localip; - - // WiFi led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0); - - return _status; -} - -uint32_t WiFiClass::provisioned() -{ - m2m_wifi_handle_events(NULL); - - if (_mode == WL_STA_MODE) { - return 1; - } - else { - return 0; - } -} - -void WiFiClass::config(IPAddress local_ip) -{ - config(local_ip, (uint32_t)0); -} - -void WiFiClass::config(IPAddress local_ip, IPAddress dns_server) -{ - config(local_ip, dns_server, (uint32_t)0); -} - -void WiFiClass::config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway) -{ - config(local_ip, dns_server, gateway, (uint32_t)0); -} - -void WiFiClass::config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet) -{ - tstrM2MIPConfig conf; - - if (!_init) { - init(); - } - - conf.u32DNS = (uint32_t)dns_server; - conf.u32Gateway = (uint32_t)gateway; - conf.u32StaticIP = (uint32_t)local_ip; - conf.u32SubnetMask = (uint32_t)subnet; - _dhcp = 0; - m2m_wifi_enable_dhcp(0); // disable DHCP - m2m_wifi_set_static_ip(&conf); - _localip = conf.u32StaticIP; - _submask = conf.u32SubnetMask; - _gateway = conf.u32Gateway; -} - -void WiFiClass::hostname(const char* name) -{ - if (!_init) { - init(); - } - - m2m_wifi_set_device_name((uint8 *)name, strlen(name)); -} - -void WiFiClass::disconnect() -{ - m2m_wifi_disconnect(); - - // WiFi led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); -} - -void WiFiClass::end() -{ - if (_mode == WL_AP_MODE) { - m2m_wifi_disable_ap(); - } else { - if (_mode == WL_PROV_MODE) { - m2m_wifi_stop_provision_mode(); - } - - m2m_wifi_disconnect(); - } - - // WiFi led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); - - socketDeinit(); - - m2m_wifi_deinit(NULL); - - nm_bsp_deinit(); - - _mode = WL_RESET_MODE; - _status = WL_NO_SHIELD; - _init = 0; -} - -uint8_t *WiFiClass::macAddress(uint8_t *mac) -{ - m2m_wifi_get_mac_address(mac); - byte tmpMac[6], i; - - m2m_wifi_get_mac_address(tmpMac); - - for(i = 0; i < 6; i++) - mac[i] = tmpMac[5-i]; - - return mac; -} - -uint32_t WiFiClass::localIP() -{ - return _localip; -} - -uint32_t WiFiClass::subnetMask() -{ - return _submask; -} - -uint32_t WiFiClass::gatewayIP() -{ - return _gateway; -} - -char* WiFiClass::SSID() -{ - if (_status == WL_CONNECTED || _status == WL_AP_LISTENING || _status == WL_AP_CONNECTED) { - return _ssid; - } - else { - return 0; - } -} - -uint8_t* WiFiClass::BSSID(uint8_t* bssid) -{ - if (_mode == WL_AP_MODE) { - return macAddress(bssid); - } else { - return remoteMacAddress(bssid); - } -} - -uint8_t* WiFiClass::APClientMacAddress(uint8_t* mac) -{ - if (_mode == WL_AP_MODE) { - return remoteMacAddress(mac); - } else { - memset(mac, 0, 6); - return mac; - } -} - -uint8_t* WiFiClass::remoteMacAddress(uint8_t* remoteMacAddress) -{ - _remoteMacAddress = remoteMacAddress; - memset(remoteMacAddress, 0, 6); - - m2m_wifi_get_connection_info(); - - // Wait for connection or timeout: - unsigned long start = millis(); - while (_remoteMacAddress != 0 && millis() - start < 1000) { - m2m_wifi_handle_events(NULL); - } - - _remoteMacAddress = 0; - return remoteMacAddress; -} - -int32_t WiFiClass::RSSI() -{ - // Clear pending events: - m2m_wifi_handle_events(NULL); - - // Send RSSI request: - _resolve = 0; - if (m2m_wifi_req_curr_rssi() < 0) { - return 0; - } - - // Wait for connection or timeout: - unsigned long start = millis(); - while (_resolve == 0 && millis() - start < 1000) { - m2m_wifi_handle_events(NULL); - } - - int32_t rssi = _resolve; - - _resolve = 0; - - return rssi; -} - -int8_t WiFiClass::scanNetworks() -{ - wl_status_t tmp = _status; - - if (!_init) { - init(); - } - - // Start scan: - if (m2m_wifi_request_scan(M2M_WIFI_CH_ALL) < 0) { - return 0; - } - - // Wait for scan result or timeout: - _status = WL_IDLE_STATUS; - unsigned long start = millis(); - while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 5000) { - m2m_wifi_handle_events(NULL); - } - _status = tmp; - return m2m_wifi_get_num_ap_found(); -} - -char* WiFiClass::SSID(uint8_t pos) -{ - wl_status_t tmp = _status; - - // Get scan SSID result: - memset(_scan_ssid, 0, M2M_MAX_SSID_LEN); - if (m2m_wifi_req_scan_result(pos) < 0) { - return 0; - } - - // Wait for connection or timeout: - _status = WL_IDLE_STATUS; - unsigned long start = millis(); - while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - - _status = tmp; - _resolve = 0; - - return _scan_ssid; -} - -int32_t WiFiClass::RSSI(uint8_t pos) -{ - wl_status_t tmp = _status; - - // Get scan RSSI result: - if (m2m_wifi_req_scan_result(pos) < 0) { - return 0; - } - - // Wait for connection or timeout: - _status = WL_IDLE_STATUS; - unsigned long start = millis(); - while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - - _status = tmp; - - int32_t rssi = _resolve; - - _resolve = 0; - - return rssi; -} - -uint8_t WiFiClass::encryptionType() -{ - int8_t net = scanNetworks(); - - for (uint8_t i = 0; i < net; ++i) { - SSID(i); - if (strcmp(_scan_ssid, _ssid) == 0) { - break; - } - } - - return _scan_auth; -} - -uint8_t WiFiClass::encryptionType(uint8_t pos) -{ - wl_status_t tmp = _status; - - // Get scan auth result: - if (m2m_wifi_req_scan_result(pos) < 0) { - return 0; - } - - // Wait for connection or timeout: - _status = WL_IDLE_STATUS; - unsigned long start = millis(); - while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - - _status = tmp; - _resolve = 0; - - return _scan_auth; -} - -uint8_t* WiFiClass::BSSID(uint8_t pos, uint8_t* bssid) -{ - wl_status_t tmp = _status; - - _remoteMacAddress = bssid; - - // Get scan auth result: - if (m2m_wifi_req_scan_result(pos) < 0) { - return 0; - } - - // Wait for connection or timeout: - _status = WL_IDLE_STATUS; - unsigned long start = millis(); - while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - - _status = tmp; - _resolve = 0; - _remoteMacAddress = 0; - - return bssid; -} - -uint8_t WiFiClass::channel(uint8_t pos) -{ - wl_status_t tmp = _status; - - // Get scan auth result: - if (m2m_wifi_req_scan_result(pos) < 0) { - return 0; - } - - // Wait for connection or timeout: - _status = WL_IDLE_STATUS; - unsigned long start = millis(); - while (!(_status & WL_SCAN_COMPLETED) && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - - _status = tmp; - _resolve = 0; - - return _scan_channel; -} - -uint8_t WiFiClass::status() -{ - if (!_init) { - init(); - } - - m2m_wifi_handle_events(NULL); - - return _status; -} - -int WiFiClass::hostByName(const char* aHostname, IPAddress& aResult) -{ - - // check if aHostname is already an ipaddress - if (aResult.fromString(aHostname)) { - // if fromString returns true we have an IP address ready - return 1; - - } else { - // Network led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); - - // Send DNS request: - _resolve = 0; - if (gethostbyname((uint8 *)aHostname) < 0) { - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - return 0; - } - - // Wait for connection or timeout: - unsigned long start = millis(); - while (_resolve == 0 && millis() - start < 20000) { - m2m_wifi_handle_events(NULL); - } - - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - - if (_resolve == 0) { - return 0; - } - - aResult = _resolve; - _resolve = 0; - return 1; - } -} - -void WiFiClass::refresh(void) -{ - // Update state machine: - m2m_wifi_handle_events(NULL); -} - -void WiFiClass::lowPowerMode(void) -{ - m2m_wifi_set_sleep_mode(M2M_PS_H_AUTOMATIC, true); -} - -void WiFiClass::maxLowPowerMode(void) -{ - m2m_wifi_set_sleep_mode(M2M_PS_DEEP_AUTOMATIC, true); -} - -void WiFiClass::noLowPowerMode(void) -{ - m2m_wifi_set_sleep_mode(M2M_NO_PS, false); -} - -int WiFiClass::ping(const char* hostname, uint8_t ttl) -{ - IPAddress ip; - - if (hostByName(hostname, ip) > 0) { - return ping(ip, ttl); - } else { - return WL_PING_UNKNOWN_HOST; - } -} - -int WiFiClass::ping(const String &hostname, uint8_t ttl) -{ - return ping(hostname.c_str(), ttl); -} - -int WiFiClass::ping(IPAddress host, uint8_t ttl) -{ - // Network led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); - - uint32_t dstHost = (uint32_t)host; - _resolve = dstHost; - - if (m2m_ping_req((uint32_t)host, ttl, &ping_cb) < 0) { - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - // Error sending ping request - return WL_PING_ERROR; - } - - // Wait for success or timeout: - unsigned long start = millis(); - while (_resolve == dstHost && millis() - start < 5000) { - m2m_wifi_handle_events(NULL); - } - - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - - if (_resolve == dstHost) { - _resolve = 0; - return WL_PING_TIMEOUT; - } else { - int rtt = (int)_resolve; - _resolve = 0; - return rtt; - } -} - -uint32_t WiFiClass::getTime() -{ -#ifdef WIFI_101_NO_TIME_H - #warning "No system header included, WiFi.getTime() will always return 0" - return 0; -#else - tstrSystemTime systemTime; - - _resolve = (uint32_t)&systemTime; - - m2m_wifi_get_sytem_time(); - - unsigned long start = millis(); - while (_resolve != 0 && millis() - start < 5000) { - m2m_wifi_handle_events(NULL); - } - - time_t t = 0; - - if (_resolve == 0 && systemTime.u16Year > 0) { - struct tm tm; - - tm.tm_year = systemTime.u16Year - 1900; - tm.tm_mon = systemTime.u8Month - 1; - tm.tm_mday = systemTime.u8Day; - tm.tm_hour = systemTime.u8Hour; - tm.tm_min = systemTime.u8Minute; - tm.tm_sec = systemTime.u8Second; - tm.tm_isdst = -1; - - t = mktime(&tm); - } - - _resolve = 0; - - return t; -#endif -} - -WiFiClass WiFi; diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFi101.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFi101.h deleted file mode 100644 index 6e46fab..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFi101.h +++ /dev/null @@ -1,193 +0,0 @@ -/* - WiFi.h - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef WIFI_H -#define WIFI_H - -#define WIFI_FIRMWARE_LATEST_MODEL_A "19.4.4" -#define WIFI_FIRMWARE_LATEST_MODEL_B "19.5.2" - -// for backwards compatibility -#define WIFI_FIRMWARE_REQUIRED WIFI_FIRMWARE_LATEST_MODEL_B - -#include - -extern "C" { - #include "driver/include/m2m_wifi.h" - #include "socket/include/socket.h" -} - -#include "WiFiClient.h" -#include "WiFiSSLClient.h" -#include "WiFiServer.h" - -typedef enum { - WL_NO_SHIELD = 255, - WL_IDLE_STATUS = 0, - WL_NO_SSID_AVAIL, - WL_SCAN_COMPLETED, - WL_CONNECTED, - WL_CONNECT_FAILED, - WL_CONNECTION_LOST, - WL_DISCONNECTED, - WL_AP_LISTENING, - WL_AP_CONNECTED, - WL_AP_FAILED, - WL_PROVISIONING, - WL_PROVISIONING_FAILED -} wl_status_t; - -/* Encryption modes */ -enum wl_enc_type { /* Values map to 802.11 encryption suites... */ - ENC_TYPE_WEP = M2M_WIFI_SEC_WEP, - ENC_TYPE_TKIP = M2M_WIFI_SEC_WPA_PSK, - ENC_TYPE_CCMP = M2M_WIFI_SEC_802_1X, - /* ... except these two, 7 and 8 are reserved in 802.11-2007 */ - ENC_TYPE_NONE = M2M_WIFI_SEC_OPEN, - ENC_TYPE_AUTO = M2M_WIFI_SEC_INVALID -}; - -typedef enum { - WL_RESET_MODE = 0, - WL_STA_MODE, - WL_PROV_MODE, - WL_AP_MODE -} wl_mode_t; - -typedef enum { - WL_PING_DEST_UNREACHABLE = -1, - WL_PING_TIMEOUT = -2, - WL_PING_UNKNOWN_HOST = -3, - WL_PING_ERROR = -4 -} wl_ping_result_t; - -class WiFiClass -{ -public: - uint32_t _localip; - uint32_t _submask; - uint32_t _gateway; - int _dhcp; - uint32_t _resolve; - byte *_remoteMacAddress; - wl_mode_t _mode; - wl_status_t _status; - char _scan_ssid[M2M_MAX_SSID_LEN]; - uint8_t _scan_auth; - uint8_t _scan_channel; - char _ssid[M2M_MAX_SSID_LEN]; - WiFiClient *_client[TCP_SOCK_MAX]; - - WiFiClass(); - - void setPins(int8_t cs, int8_t irq, int8_t rst, int8_t en = -1); - - int init(); - - char* firmwareVersion(); - - /* Start Wifi connection with WPA/WPA2 encryption. - * - * param ssid: Pointer to the SSID string. - * param key: Key input buffer. - */ - uint8_t begin(); - uint8_t begin(const char *ssid); - uint8_t begin(const char *ssid, uint8_t key_idx, const char* key); - uint8_t begin(const char *ssid, const char *key); - uint8_t begin(const String &ssid) { return begin(ssid.c_str()); } - uint8_t begin(const String &ssid, uint8_t key_idx, const String &key) { return begin(ssid.c_str(), key_idx, key.c_str()); } - uint8_t begin(const String &ssid, const String &key) { return begin(ssid.c_str(), key.c_str()); } - - /* Start Wifi in Access Point, with open security. - * Only one client can connect to the AP at a time. - * - * param ssid: Pointer to the SSID string. - * param channel: Wifi channel to use. Valid values are 1-12. - */ - uint8_t beginAP(const char *ssid); - uint8_t beginAP(const char *ssid, uint8_t channel); - uint8_t beginAP(const char *ssid, uint8_t key_idx, const char* key); - uint8_t beginAP(const char *ssid, uint8_t key_idx, const char* key, uint8_t channel); - uint8_t beginAP(const char *ssid, const char* key); - uint8_t beginAP(const char *ssid, const char* key, uint8_t channel); - - uint8_t beginProvision(); - uint8_t beginProvision(uint8_t channel); - - uint32_t provisioned(); - - void config(IPAddress local_ip); - void config(IPAddress local_ip, IPAddress dns_server); - void config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway); - void config(IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet); - - void hostname(const char* name); - - void disconnect(); - void end(); - - uint8_t *macAddress(uint8_t *mac); - - uint32_t localIP(); - uint32_t subnetMask(); - uint32_t gatewayIP(); - char* SSID(); - int32_t RSSI(); - uint8_t encryptionType(); - uint8_t* BSSID(uint8_t* bssid); - uint8_t* APClientMacAddress(uint8_t* mac); - int8_t scanNetworks(); - char* SSID(uint8_t pos); - int32_t RSSI(uint8_t pos); - uint8_t encryptionType(uint8_t pos); - uint8_t* BSSID(uint8_t pos, uint8_t* bssid); - uint8_t channel(uint8_t pos); - - uint8_t status(); - - int hostByName(const char* hostname, IPAddress& result); - int hostByName(const String &hostname, IPAddress& result) { return hostByName(hostname.c_str(), result); } - - int ping(const char* hostname, uint8_t ttl = 128); - int ping(const String &hostname, uint8_t ttl = 128); - int ping(IPAddress host, uint8_t ttl = 128); - - unsigned long getTime(); - - void refresh(void); - - void lowPowerMode(void); - void maxLowPowerMode(void); - void noLowPowerMode(void); - -private: - int _init; - char _version[9]; - - uint8_t startConnect(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo); - uint8_t startAP(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo, uint8_t channel); - uint8_t* remoteMacAddress(uint8_t* remoteMacAddress); - - uint8_t startProvision(const char *ssid, const char *url, uint8_t channel); -}; - -extern WiFiClass WiFi; - -#endif /* WIFI_H */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiClient.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiClient.cpp deleted file mode 100644 index 8298618..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiClient.cpp +++ /dev/null @@ -1,308 +0,0 @@ -/* - WiFiClient.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -extern "C" { - #include "socket/include/socket.h" - #include "driver/include/m2m_periph.h" -} - -#include "WiFi101.h" -#include "WiFiClient.h" - -#define IS_CONNECTED (_flag & SOCKET_BUFFER_FLAG_CONNECTED) - -WiFiClient::WiFiClient() -{ - _socket = -1; - _flag = 0; - _head = 0; - _tail = 0; -} - -WiFiClient::WiFiClient(uint8_t sock, uint8_t parentsock) -{ - // Spawn connected TCP client from TCP server socket: - _socket = sock; - _flag = SOCKET_BUFFER_FLAG_CONNECTED; - if (parentsock) { - _flag |= ((uint32_t)parentsock) << SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS; - } - _head = 0; - _tail = 0; - for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { - if (WiFi._client[sock] == this) - WiFi._client[sock] = 0; - } - WiFi._client[_socket] = this; - - // Add socket buffer handler: - socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_buffer); - - // Enable receive buffer: - recv(_socket, _buffer, SOCKET_BUFFER_MTU, 0); - - m2m_wifi_handle_events(NULL); -} - -WiFiClient::WiFiClient(const WiFiClient& other) -{ - copyFrom(other); -} - -void WiFiClient::copyFrom(const WiFiClient& other) -{ - _socket = other._socket; - _flag = other._flag; - _head = other._head; - _tail = other._tail; - if (_head > _tail) { - memcpy(_buffer + _tail, other._buffer + _tail, (_head - _tail)); - } - - for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { - if (WiFi._client[sock] == this) - WiFi._client[sock] = 0; - } - - if (_socket > -1) { - WiFi._client[_socket] = this; - - // Add socket buffer handler: - socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_buffer); - - // Enable receive buffer: - recv(_socket, _buffer, SOCKET_BUFFER_MTU, 0); - } - - m2m_wifi_handle_events(NULL); -} - -int WiFiClient::connectSSL(const char* host, uint16_t port) -{ - return connect(host, port, SOCKET_FLAGS_SSL); -} - -int WiFiClient::connectSSL(IPAddress ip, uint16_t port) -{ - return connect(ip, port, SOCKET_FLAGS_SSL, 0); -} - -int WiFiClient::connect(const char* host, uint16_t port) -{ - return connect(host, port, 0); -} - -int WiFiClient::connect(IPAddress ip, uint16_t port) -{ - return connect(ip, port, 0, 0); -} - -int WiFiClient::connect(const char* host, uint16_t port, uint8_t opt) -{ - IPAddress remote_addr; - if (WiFi.hostByName(host, remote_addr)) { - return connect(remote_addr, port, opt, (const uint8_t *)host); - } - return 0; -} - -int WiFiClient::connect(IPAddress ip, uint16_t port, uint8_t opt, const uint8_t *hostname) -{ - struct sockaddr_in addr; - - // Initialize socket address structure: - addr.sin_family = AF_INET; - addr.sin_port = _htons(port); - addr.sin_addr.s_addr = ip; - - // Create TCP socket: - _flag = 0; - _head = 0; - _tail = 0; - if ((_socket = socket(AF_INET, SOCK_STREAM, opt)) < 0) { - return 0; - } - - if (opt & SOCKET_FLAGS_SSL && hostname) { - setsockopt(_socket, SOL_SSL_SOCKET, SO_SSL_SNI, hostname, m2m_strlen((uint8_t *)hostname)); - } - - // Add socket buffer handler: - socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_buffer); - - // Connect to remote host: - if (connectSocket(_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { - close(_socket); - _socket = -1; - return 0; - } - - // Wait for connection or timeout: - unsigned long start = millis(); - while (!IS_CONNECTED && millis() - start < 20000) { - m2m_wifi_handle_events(NULL); - } - if (!IS_CONNECTED) { - close(_socket); - _socket = -1; - return 0; - } - - WiFi._client[_socket] = this; - - return 1; -} - -size_t WiFiClient::write(uint8_t b) -{ - return write(&b, 1); -} - -size_t WiFiClient::write(const uint8_t *buf, size_t size) -{ - sint16 err; - - if (_socket < 0 || size == 0 || !IS_CONNECTED) { - setWriteError(); - return 0; - } - - // Network led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); - - m2m_wifi_handle_events(NULL); - - while ((err = send(_socket, (void *)buf, size, 0)) < 0) { - // Exit on fatal error, retry if buffer not ready. - if (err != SOCK_ERR_BUFFER_FULL) { - setWriteError(); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - return 0; - } - m2m_wifi_handle_events(NULL); - } - - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - - return size; -} - -int WiFiClient::available() -{ - m2m_wifi_handle_events(NULL); - - if (_socket != -1) { - return _head - _tail; - } - return 0; -} - -int WiFiClient::read() -{ - uint8_t b; - - if (read(&b, sizeof(b)) == -1) { - return -1; - } - - return b; -} - -int WiFiClient::read(uint8_t* buf, size_t size) -{ - // sizeof(size_t) is architecture dependent - // but we need a 16 bit data type here - uint16_t size_tmp = available(); - - if (size_tmp == 0) { - return -1; - } - - if (size < size_tmp) { - size_tmp = size; - } - - for (uint32_t i = 0; i < size_tmp; ++i) { - buf[i] = _buffer[_tail++]; - } - - if (_tail == _head) { - _tail = _head = 0; - _flag &= ~SOCKET_BUFFER_FLAG_FULL; - recv(_socket, _buffer, SOCKET_BUFFER_MTU, 0); - m2m_wifi_handle_events(NULL); - } - - return size_tmp; -} - -int WiFiClient::peek() -{ - if (!available()) - return -1; - - return _buffer[_tail]; -} - -void WiFiClient::flush() -{ - while (available()) - read(); -} - -void WiFiClient::stop() -{ - if (_socket < 0) - return; - - socketBufferUnregister(_socket); - close(_socket); - _socket = -1; - _flag = 0; -} - -uint8_t WiFiClient::connected() -{ - m2m_wifi_handle_events(NULL); - if (available()) - return 1; - return IS_CONNECTED; -} - -uint8_t WiFiClient::status() -{ - // Deprecated. - return 0; -} - -WiFiClient::operator bool() -{ - return _socket != -1; -} - -WiFiClient& WiFiClient::operator =(const WiFiClient& other) -{ - copyFrom(other); - - return *this; -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiClient.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiClient.h deleted file mode 100644 index bef171d..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiClient.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - WiFiClient.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef WIFICLIENT_H -#define WIFICLIENT_H - -#include -#include -#include -#include "socket/include/socket_buffer.h" - -class WiFiClient : public Client { - -public: - WiFiClient(); - WiFiClient(uint8_t sock, uint8_t parentsock = 0); - WiFiClient(const WiFiClient& other); - - uint8_t status(); - - int connectSSL(IPAddress ip, uint16_t port); - int connectSSL(const char* host, uint16_t port); - virtual int connect(IPAddress ip, uint16_t port); - virtual int connect(const char* host, uint16_t port); - virtual size_t write(uint8_t); - virtual size_t write(const uint8_t *buf, size_t size); - virtual int available(); - virtual int read(); - virtual int read(uint8_t *buf, size_t size); - virtual int peek(); - virtual void flush(); - virtual void stop(); - virtual uint8_t connected(); - virtual operator bool(); - virtual WiFiClient& operator =(const WiFiClient& other); - - using Print::write; - - uint32_t _flag; - -private: - SOCKET _socket; - uint32_t _head; - uint32_t _tail; - uint8_t _buffer[SOCKET_BUFFER_TCP_SIZE]; - int connect(const char* host, uint16_t port, uint8_t opt); - int connect(IPAddress ip, uint16_t port, uint8_t opt, const uint8_t *hostname); - void copyFrom(const WiFiClient& other); - -}; - -#endif /* WIFICLIENT_H */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiMDNSResponder.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiMDNSResponder.cpp deleted file mode 100644 index a192113..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiMDNSResponder.cpp +++ /dev/null @@ -1,220 +0,0 @@ -// Port of CC3000 MDNS Responder to WINC1500. -// Author: Tony DiCola -// -// This MDNSResponder class implements just enough MDNS functionality to respond -// to name requests, for example 'foo.local'. This does not implement any other -// MDNS or Bonjour functionality like services, etc. -// -// Copyright (c) 2016 Adafruit Industries. All right reserved. -// -// 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 2.1 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 Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -#include -#ifndef ARDUINO_ARCH_AVR -#include -#endif - -#include "Arduino.h" -#include "WiFiMDNSResponder.h" - -// Important RFC's for reference: -// - DNS request and response: http://www.ietf.org/rfc/rfc1035.txt -// - Multicast DNS: http://www.ietf.org/rfc/rfc6762.txt - -#define HEADER_SIZE 12 -#define TTL_OFFSET 4 -#define IP_OFFSET 10 - -const uint8_t expectedRequestHeader[HEADER_SIZE] PROGMEM = { - 0x00, 0x00, - 0x00, 0x00, - 0x00, 0x01, // questions (these 2 bytes are ignored) - 0x00, 0x00, - 0x00, 0x00, - 0x00, 0x00 -}; - -const uint8_t responseHeader[] PROGMEM = { - 0x00, 0x00, // ID = 0 - 0x84, 0x00, // Flags = response + authoritative answer - 0x00, 0x00, // Question count = 0 - 0x00, 0x01, // Answer count = 1 - 0x00, 0x00, // Name server records = 0 - 0x00, 0x01 // Additional records = 1 -}; - -// Generate positive response for IPV4 address -const uint8_t aRecord[] PROGMEM = { - 0x00, 0x01, // Type = 1, A record/IPV4 address - 0x80, 0x01, // Class = Internet, with cache flush bit - 0x00, 0x00, 0x00, 0x00, // TTL in seconds, to be filled in later - 0x00, 0x04, // Length of record - 0x00, 0x00, 0x00, 0x00 // IP address, to be filled in later -}; - -// Generate negative response for IPV6 address (CC3000 doesn't support IPV6) -const uint8_t nsecRecord[] PROGMEM = { - 0xC0, 0x0C, // Name offset - 0x00, 0x2F, // Type = 47, NSEC (overloaded by MDNS) - 0x80, 0x01, // Class = Internet, with cache flush bit - 0x00, 0x00, 0x00, 0x00, // TTL in seconds, to be filled in later - 0x00, 0x08, // Length of record - 0xC0, 0x0C, // Next domain = offset to FQDN - 0x00, // Block number = 0 - 0x04, // Length of bitmap = 4 bytes - 0x40, 0x00, 0x00, 0x00 // Bitmap value = Only first bit (A record/IPV4) is set -}; - -const uint8_t domain[] PROGMEM = { 'l', 'o', 'c', 'a', 'l' }; - -WiFiMDNSResponder::WiFiMDNSResponder() : - minimumExpectedRequestLength(0) -{ -} - -WiFiMDNSResponder::~WiFiMDNSResponder() -{ -} - -bool WiFiMDNSResponder::begin(const char* _name, uint32_t _ttlSeconds) -{ - int nameLength = strlen(_name); - - if (nameLength > 255) { - // Can only handle domains that are upto 255 chars in length. - minimumExpectedRequestLength = 0; - return false; - } - - name = _name; - ttlSeconds = _ttlSeconds; - - name.toLowerCase(); - minimumExpectedRequestLength = HEADER_SIZE + 1 + nameLength + 1 + sizeof(domain) + 5; - - // Open the MDNS UDP listening socket on port 5353 with multicast address - // 224.0.0.251 (0xE00000FB) - if (!udpSocket.beginMulticast(IPAddress(224, 0, 0, 251), 5353)) { - return false; - } - - return true; -} - -void WiFiMDNSResponder::poll() -{ - if (parseRequest()) { - replyToRequest(); - } -} - -bool WiFiMDNSResponder::parseRequest() -{ - int packetLength = udpSocket.parsePacket(); - - if (packetLength) { - // check if parsed packet matches expected request length - if (packetLength < minimumExpectedRequestLength) { - // it does not, read the full packet in and drop data - while(udpSocket.available()) { - udpSocket.read(); - } - - return false; - } - - // read up to the min expect request length - uint8_t request[minimumExpectedRequestLength]; - udpSocket.read(request, minimumExpectedRequestLength); - - // discard the rest - while(udpSocket.available()) { - udpSocket.read(); - } - - // parse request - uint8_t requestNameLength = request[HEADER_SIZE]; - uint8_t* requestName = &request[HEADER_SIZE + 1]; - uint8_t requestDomainLength = request[HEADER_SIZE + 1 + requestNameLength]; - uint8_t* requestDomain = &request[HEADER_SIZE + 1 + requestNameLength + 1]; - uint16_t requestQtype; - uint16_t requestQclass; - - memcpy(&requestQtype, &request[minimumExpectedRequestLength - 4], sizeof(requestQtype)); - memcpy(&requestQclass, &request[minimumExpectedRequestLength - 2], sizeof(requestQclass)); - - requestQtype = _ntohs(requestQtype); - requestQclass = _ntohs(requestQclass); - - // compare request - if (memcmp_P(request, expectedRequestHeader, 4) == 0 && // request header start match - memcmp_P(&request[6], &expectedRequestHeader[6], 6) == 0 && // request header end match - requestNameLength == name.length() && // name length match - strncasecmp(name.c_str(), (char*)requestName, requestNameLength) == 0 && // name match - requestDomainLength == sizeof(domain) && // domain length match - memcmp_P(requestDomain, domain, requestDomainLength) == 0 && // suffix match - requestQtype == 0x0001 && // request QType match - requestQclass == 0x0001) { // request QClass match - - return true; - } - } - - return false; -} - -void WiFiMDNSResponder::replyToRequest() -{ - int nameLength = name.length(); - int domainLength = sizeof(domain); - uint32_t ipAddress = WiFi.localIP(); - uint32_t ttl = _htonl(ttlSeconds); - - int responseSize = sizeof(responseHeader) + 1 + nameLength + 1 + domainLength + 1 + sizeof(aRecord) + sizeof(nsecRecord); - uint8_t response[responseSize]; - uint8_t* r = response; - - // copy header - memcpy_P(r, responseHeader, sizeof(responseHeader)); - r += sizeof(responseHeader); - - // copy name - *r = nameLength; - memcpy(r + 1, name.c_str(), nameLength); - r += (1 + nameLength); - - // copy domain - *r = domainLength; - memcpy_P(r + 1, domain, domainLength); - r += (1 + domainLength); - - // terminator - *r = 0x00; - r++; - - // copy A record - memcpy_P(r, aRecord, sizeof(aRecord)); - memcpy(r + TTL_OFFSET, &ttl, sizeof(ttl)); // replace TTL value - memcpy(r + IP_OFFSET, &ipAddress, sizeof(ipAddress)); // replace IP address value - r += sizeof(aRecord); - - // copy NSEC record - memcpy_P(r, nsecRecord, sizeof(nsecRecord)); - r += sizeof(nsecRecord); - - udpSocket.beginPacket(IPAddress(224, 0, 0, 251), 5353); - udpSocket.write(response, responseSize); - udpSocket.endPacket(); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiMDNSResponder.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiMDNSResponder.h deleted file mode 100644 index d7e3d43..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiMDNSResponder.h +++ /dev/null @@ -1,51 +0,0 @@ -// Port of CC3000 MDNS Responder to WINC1500. -// Author: Tony DiCola -// -// This MDNSResponder class implements just enough MDNS functionality to respond -// to name requests, for example 'foo.local'. This does not implement any other -// MDNS or Bonjour functionality like services, etc. -// -// Copyright (c) 2016 Adafruit Industries. All right reserved. -// -// 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 2.1 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 Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -#ifndef WIFIMDNSRESPONDER_H -#define WIFIMDNSRESPONDER_H - -#include "WiFi101.h" -#include "WiFiUdp.h" - -class WiFiMDNSResponder { -public: - WiFiMDNSResponder(); - ~WiFiMDNSResponder(); - bool begin(const char* _name, uint32_t _ttlSeconds = 3600); - void poll(); - -private: - bool parseRequest(); - void replyToRequest(); - -private: - String name; - uint32_t ttlSeconds; - - int minimumExpectedRequestLength; - - // UDP socket for receiving/sending MDNS data. - WiFiUDP udpSocket; -}; - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiSSLClient.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiSSLClient.cpp deleted file mode 100644 index e7be43c..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiSSLClient.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/* - WiFiSSLClient.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "WiFiSSLClient.h" - -WiFiSSLClient::WiFiSSLClient() : - WiFiClient() -{ -} - -WiFiSSLClient::WiFiSSLClient(uint8_t sock, uint8_t parentsock) : - WiFiClient(sock, parentsock) -{ -} - -WiFiSSLClient::WiFiSSLClient(const WiFiSSLClient& other) : - WiFiClient(other) -{ -} - -int WiFiSSLClient::connect(IPAddress ip, uint16_t port) -{ - return WiFiClient::connectSSL(ip, port); -} - -int WiFiSSLClient::connect(const char* host, uint16_t port) -{ - return WiFiClient::connectSSL(host, port); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiSSLClient.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiSSLClient.h deleted file mode 100644 index c5851e5..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiSSLClient.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - WiFiSSLClient.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef WIFISSLCLIENT_H -#define WIFISSLCLIENT_H - -#include "WiFiClient.h" - -class WiFiSSLClient : public WiFiClient { - -public: - WiFiSSLClient(); - WiFiSSLClient(uint8_t sock, uint8_t parentsock = 0); - WiFiSSLClient(const WiFiSSLClient& other); - - virtual int connect(IPAddress ip, uint16_t port); - virtual int connect(const char* host, uint16_t port); -}; - -#endif /* WIFISSLCLIENT_H */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiServer.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiServer.cpp deleted file mode 100644 index 5f330ba..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiServer.cpp +++ /dev/null @@ -1,140 +0,0 @@ -/* - WiFiClient.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -extern "C" { - #include "socket/include/socket.h" -} - -#include "WiFi101.h" -#include "WiFiClient.h" -#include "WiFiServer.h" - -#define READY (_flag & SOCKET_BUFFER_FLAG_BIND) - -WiFiServer::WiFiServer(uint16_t port) -{ - _port = port; - _flag = 0; -} - -void WiFiServer::begin() -{ - begin(0); -} - -uint8_t WiFiServer::beginSSL() -{ - return begin(SOCKET_FLAGS_SSL); -} - -uint8_t WiFiServer::begin(uint8_t opt) -{ - struct sockaddr_in addr; - - _flag = 0; - - // Initialize socket address structure. - addr.sin_family = AF_INET; - addr.sin_port = _htons(_port); - addr.sin_addr.s_addr = 0; - - // Open TCP server socket. - if ((_socket = socket(AF_INET, SOCK_STREAM, opt)) < 0) { - return 0; - } - - // Add socket buffer handler: - socketBufferRegister(_socket, &_flag, 0, 0, 0); - - // Bind socket: - if (bind(_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { - close(_socket); - _socket = -1; - return 0; - } - - // Wait for connection or timeout: - unsigned long start = millis(); - while (!READY && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - if (!READY) { - close(_socket); - _socket = -1; - return 0; - } - _flag &= ~SOCKET_BUFFER_FLAG_BIND; - - return 1; -} - -WiFiClient WiFiServer::available(uint8_t* status) -{ - uint32_t flag; - - m2m_wifi_handle_events(NULL); - if (_flag & SOCKET_BUFFER_FLAG_SPAWN) { - flag = _flag; - _flag &= ~SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK; - _flag &= ~SOCKET_BUFFER_FLAG_SPAWN; - if (status != NULL) { - *status = 0; - } - return WiFiClient(((flag & SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK) >> SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS), _socket + 1); - } else { - WiFiClient *client; - - for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { - client = WiFi._client[sock]; - if (client && client->_flag & SOCKET_BUFFER_FLAG_CONNECTED) { - if (((client->_flag >> SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS) & 0xff) == (uint8)(_socket + 1)) { - return *client; - } - } - } - } - - return WiFiClient(); -} - -uint8_t WiFiServer::status() { - // Deprecated. - return 0; -} - -size_t WiFiServer::write(uint8_t b) -{ - return write(&b, 1); -} - -size_t WiFiServer::write(const uint8_t *buffer, size_t size) -{ - size_t n = 0; - WiFiClient *client; - - for (int sock = 0; sock < TCP_SOCK_MAX; sock++) { - client = WiFi._client[sock]; - if (client && client->_flag & SOCKET_BUFFER_FLAG_CONNECTED) { - if (((client->_flag >> SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS) & 0xff) == (uint8)(_socket + 1)) { - n += client->write(buffer, size); - } - } - } - return n; -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiServer.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiServer.h deleted file mode 100644 index d658b2f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiServer.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - WiFiClient.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef WIFISERVER_H -#define WIFISERVER_H - -#include -#include - -class WiFiClient; - -class WiFiServer : public Server { - -private: - SOCKET _socket; - uint32_t _flag; - uint16_t _port; - uint8_t begin(uint8_t opt); - -public: - WiFiServer(uint16_t); - WiFiClient available(uint8_t* status = NULL); - void begin(); - uint8_t beginSSL(); - virtual size_t write(uint8_t); - virtual size_t write(const uint8_t *buf, size_t size); - uint8_t status(); - - using Print::write; - -}; - -#endif /* WIFISERVER_H */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiUdp.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiUdp.cpp deleted file mode 100644 index e55c965..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiUdp.cpp +++ /dev/null @@ -1,289 +0,0 @@ -/* - WiFiUdp.cpp - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -extern "C" { - #include "socket/include/socket.h" - #include "driver/include/m2m_periph.h" - extern uint8 hif_small_xfer; -} - -#include -#include "WiFi101.h" -#include "WiFiUdp.h" -#include "WiFiClient.h" -#include "WiFiServer.h" - -#define READY (_flag & SOCKET_BUFFER_FLAG_BIND) - -/* Constructor. */ -WiFiUDP::WiFiUDP() -{ - _socket = -1; - _flag = 0; - _head = 0; - _tail = 0; - _rcvSize = 0; - _rcvPort = 0; - _rcvIP = 0; - _sndSize = 0; -} - -/* Start WiFiUDP socket, listening at local port PORT */ -uint8_t WiFiUDP::begin(uint16_t port) -{ - struct sockaddr_in addr; - uint32 u32EnableCallbacks = 0; - - _flag = 0; - _head = 0; - _tail = 0; - _rcvSize = 0; - _rcvPort = 0; - _rcvIP = 0; - _sndSize = 0; - - // Initialize socket address structure. - addr.sin_family = AF_INET; - addr.sin_port = _htons(port); - addr.sin_addr.s_addr = 0; - - // Open TCP server socket. - if ((_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { - return 0; - } - - // Add socket buffer handler: - socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_recvBuffer); - setsockopt(_socket, SOL_SOCKET, SO_SET_UDP_SEND_CALLBACK, &u32EnableCallbacks, 0); - - // Bind socket: - if (bind(_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { - close(_socket); - _socket = -1; - return 0; - } - - // Wait for connection or timeout: - unsigned long start = millis(); - while (!READY && millis() - start < 2000) { - m2m_wifi_handle_events(NULL); - } - if (!READY) { - close(_socket); - _socket = -1; - return 0; - } - _flag &= ~SOCKET_BUFFER_FLAG_BIND; - - return 1; -} - -uint8_t WiFiUDP::beginMulticast(IPAddress ip, uint16_t port) -{ - uint32_t multiIp = ip; - - if (!begin(port)) { - return 0; - } - - setsockopt(_socket, SOL_SOCKET, IP_ADD_MEMBERSHIP, &multiIp, sizeof(multiIp)); - - return 1; -} - -/* return number of bytes available in the current packet, - will return zero if parsePacket hasn't been called yet */ -int WiFiUDP::available() -{ - m2m_wifi_handle_events(NULL); - - if (_socket != -1) { - return _rcvSize; - } - return 0; - } - -/* Release any resources being used by this WiFiUDP instance */ -void WiFiUDP::stop() -{ - if (_socket < 0) - return; - - socketBufferUnregister(_socket); - close(_socket); - _socket = -1; -} - -int WiFiUDP::beginPacket(const char *host, uint16_t port) -{ - IPAddress ip; - if (WiFi.hostByName(host, ip)) { - return beginPacket(ip, port); - } - - return 0; -} - -int WiFiUDP::beginPacket(IPAddress ip, uint16_t port) -{ - _sndIP = ip; - _sndPort = port; - _sndSize = 0; - - return 1; -} - -int WiFiUDP::endPacket() -{ - struct sockaddr_in addr; - - // Network led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); - - addr.sin_family = AF_INET; - addr.sin_port = _htons(_sndPort); - addr.sin_addr.s_addr = _sndIP; - - if (sendto(_socket, (void *)_sndBuffer, _sndSize, 0, - (struct sockaddr *)&addr, sizeof(addr)) < 0) { - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - return 0; - } - - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - - return 1; -} - -size_t WiFiUDP::write(uint8_t byte) -{ - return write(&byte, 1); -} - -size_t WiFiUDP::write(const uint8_t *buffer, size_t size) -{ - if ((size + _sndSize) > sizeof(_sndBuffer)) { - size = sizeof(_sndBuffer) - _sndSize; - } - - memcpy(_sndBuffer + _sndSize, buffer, size); - - _sndSize += size; - - return size; -} - -int WiFiUDP::parsePacket() -{ - m2m_wifi_handle_events(NULL); - - if (_socket != -1) { - if (_rcvSize != 0) { - return _rcvSize; - } - if (_head != _tail) { - _rcvSize = ((uint16_t)_recvBuffer[_tail] << 8) + (uint16_t)_recvBuffer[_tail + 1]; - _rcvPort = ((uint16_t)_recvBuffer[_tail + 2] << 8) + (uint16_t)_recvBuffer[_tail + 3]; - _rcvIP = ((uint32_t)_recvBuffer[_tail + 4] << 24) + ((uint32_t)_recvBuffer[_tail + 5] << 16) + - ((uint32_t)_recvBuffer[_tail + 6] << 8) + (uint32_t)_recvBuffer[_tail + 7]; - _tail += SOCKET_BUFFER_UDP_HEADER_SIZE; - return _rcvSize; - } - } - return 0; -} - -int WiFiUDP::read() -{ - uint8_t b; - - if (read(&b, sizeof(b)) == -1) { - return -1; - } - - return b; -} - -int WiFiUDP::read(unsigned char* buf, size_t size) -{ - // sizeof(size_t) is architecture dependent - // but we need a 16 bit data type here - uint16_t size_tmp = available(); - - if (size_tmp == 0) { - return -1; - } - - if (size < size_tmp) { - size_tmp = size; - } - - for (uint32_t i = 0; i < size_tmp; ++i) { - buf[i] = _recvBuffer[_tail++]; - _rcvSize--; - - if (_tail == _head) { - // the full buffered data has been read, reset head and tail for next transfer - _tail = _head = 0; - - // clear the buffer full flag - _flag &= ~SOCKET_BUFFER_FLAG_FULL; - - // setup buffer and buffer size to transfer the remainder of the current packet - // or next received packet - if (hif_small_xfer) { - recvfrom(_socket, _recvBuffer, SOCKET_BUFFER_MTU, 0); - } else { - recvfrom(_socket, _recvBuffer + SOCKET_BUFFER_UDP_HEADER_SIZE, SOCKET_BUFFER_MTU, 0); - } - m2m_wifi_handle_events(NULL); - } - } - - return size_tmp; -} - -int WiFiUDP::peek() -{ - if (!available()) - return -1; - - return _recvBuffer[_tail]; -} - -void WiFiUDP::flush() -{ - while (available()) - read(); -} - -IPAddress WiFiUDP::remoteIP() -{ - return _rcvIP; -} - -uint16_t WiFiUDP::remotePort() -{ - return _rcvPort; -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiUdp.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiUdp.h deleted file mode 100644 index d961682..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/WiFiUdp.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - WiFiUdp.h - Library for Arduino Wifi shield. - Copyright (c) 2011-2014 Arduino. All right reserved. - - 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 2.1 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef WIFIUDP_H -#define WIFIUDP_H - -#include - -class WiFiUDP : public UDP { -private: - SOCKET _socket; - uint32_t _flag; - uint32_t _head; - uint32_t _tail; - uint8_t _recvBuffer[SOCKET_BUFFER_UDP_SIZE]; - uint16_t _rcvSize; - uint16_t _rcvPort; - uint32_t _rcvIP; - uint8_t _sndBuffer[SOCKET_BUFFER_UDP_SIZE]; - uint16_t _sndSize; - uint16_t _sndPort; - uint32_t _sndIP; - -public: - WiFiUDP(); // Constructor - virtual uint8_t begin(uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use - virtual uint8_t beginMulticast(IPAddress, uint16_t); // initialize, start listening on specified multicast IP address and port. Returns 1 if successful, 0 if there are no sockets available to use - virtual uint8_t beginMulti(IPAddress ip, uint16_t port) { return beginMulticast(ip, port); } - virtual void stop(); // Finish with the UDP socket - - // Sending UDP packets - - // Start building up a packet to send to the remote host specific in ip and port - // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port - virtual int beginPacket(IPAddress ip, uint16_t port); - // Start building up a packet to send to the remote host specific in host and port - // Returns 1 if successful, 0 if there was a problem resolving the hostname or port - virtual int beginPacket(const char *host, uint16_t port); - // Finish off this packet and send it - // Returns 1 if the packet was sent successfully, 0 if there was an error - virtual int endPacket(); - // Write a single byte into the packet - virtual size_t write(uint8_t); - // Write size bytes from buffer into the packet - virtual size_t write(const uint8_t *buffer, size_t size); - - using Print::write; - - // Start processing the next available incoming packet - // Returns the size of the packet in bytes, or 0 if no packets are available - virtual int parsePacket(); - // Number of bytes remaining in the current packet - virtual int available(); - // Read a single byte from the current packet - virtual int read(); - // Read up to len bytes from the current packet and place them into buffer - // Returns the number of bytes read, or 0 if none are available - virtual int read(unsigned char* buffer, size_t len); - // Read up to len characters from the current packet and place them into buffer - // Returns the number of characters read, or 0 if none are available - virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; - // Return the next byte from the current packet without moving on to the next byte - virtual int peek(); - virtual void flush(); // Finish reading the current packet - - // Return the IP address of the host who sent the current incoming packet - virtual IPAddress remoteIP(); - // Return the port of the host who sent the current incoming packet - virtual uint16_t remotePort(); - -}; - -#endif /* WIFIUDP_H */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp.h deleted file mode 100644 index 5527bab..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp.h +++ /dev/null @@ -1,283 +0,0 @@ -/** - * - * \file - * - * \brief WINC BSP API Declarations. - * - * Copyright (c) 2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/** \defgroup nm_bsp BSP - */ -/**@defgroup BSPDefine Defines - * @ingroup nm_bsp - * @{ - */ -#ifndef _NM_BSP_H_ -#define _NM_BSP_H_ - -#define NMI_API -/*!< -* Attribute used to define memory section to map Functions in host memory. -*/ -#define CONST const - -/*!< -* Used for code portability. -*/ - -/*! - * @typedef void (*tpfNmBspIsr) (void); - * @brief Pointer to function.\n - * Used as a data type of ISR function registered by \ref nm_bsp_register_isr - * @return None - */ -typedef void (*tpfNmBspIsr)(void); - - - -#ifndef NULL -#define NULL ((void*)0) -#endif -/*!< -* Void Pointer to '0' in case of NULL is not defined. -*/ - - -#define BSP_MIN(x,y) ((x)>(y)?(y):(x)) -/*!< -* Computes the minimum of \b x and \b y. -*/ - - //@} - -/**@defgroup DataT DataTypes - * @ingroup nm_bsp - * @{ - */ - - /*! - * @ingroup DataTypes - * @typedef unsigned char uint8; - * @brief Range of values between 0 to 255 - */ -typedef unsigned char uint8; - - /*! - * @ingroup DataTypes - * @typedef unsigned short uint16; - * @brief Range of values between 0 to 65535 - */ -typedef unsigned short uint16; - - /*! - * @ingroup Data Types - * @typedef unsigned long uint32; - * @brief Range of values between 0 to 4294967295 - */ -typedef unsigned long uint32; - - - /*! - * @ingroup Data Types - * @typedef signed char sint8; - * @brief Range of values between -128 to 127 - */ -typedef signed char sint8; - - /*! - * @ingroup DataTypes - * @typedef signed short sint16; - * @brief Range of values between -32768 to 32767 - */ -typedef signed short sint16; - - /*! - * @ingroup DataTypes - * @typedef signed long sint32; - * @brief Range of values between -2147483648 to 2147483647 - */ - -typedef signed long sint32; - //@} - -#ifndef CORTUS_APP - - -#ifdef __cplusplus -extern "C"{ -#endif - -/** \defgroup BSPAPI Function - * @ingroup nm_bsp - */ - - -/** @defgroup NmBspInitFn nm_bsp_init - * @ingroup BSPAPI - * Initialization for BSP such as Reset and Chip Enable Pins for WINC, delays, register ISR, enable/disable IRQ for WINC, ...etc. You must use this function in the head of your application to - * enable WINC and Host Driver communicate each other. - */ - /**@{*/ -/*! - * @fn sint8 nm_bsp_init(void); - * @note Implementation of this function is host dependent. - * @warning Missing use will lead to unavailability of host communication.\n - * - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - - */ -sint8 nm_bsp_init(void); - /**@}*/ - - - /** @defgroup NmBspDeinitFn nm_bsp_deinit - * @ingroup BSPAPI - * De-initialization for BSP (\e Board \e Support \e Package) - */ - /**@{*/ -/*! - * @fn sint8 nm_bsp_deinit(void); - * @pre Initialize \ref nm_bsp_init first - * @note Implementation of this function is host dependent. - * @warning Missing use may lead to unknown behavior in case of soft reset.\n - * @see nm_bsp_init - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - - */ -sint8 nm_bsp_deinit(void); - /**@}*/ - - -/** @defgroup NmBspResetFn nm_bsp_reset -* @ingroup BSPAPI -* Resetting NMC1500 SoC by setting CHIP_EN and RESET_N signals low, then after specific delay the function will put CHIP_EN high then RESET_N high, -* for the timing between signals please review the WINC data-sheet -*/ -/**@{*/ - /*! - * @fn void nm_bsp_reset(void); - * @param [in] None - * @pre Initialize \ref nm_bsp_init first - * @note Implementation of this function is host dependent and called by HIF layer. - * @see nm_bsp_init - * @return None - - */ -void nm_bsp_reset(void); - /**@}*/ - - -/** @defgroup NmBspSleepFn nm_bsp_sleep -* @ingroup BSPAPI -* Sleep in units of milliseconds.\n -* This function used by HIF Layer according to different situations. -*/ -/**@{*/ -/*! - * @fn void nm_bsp_sleep(uint32); - * @brief - * @param [in] u32TimeMsec - * Time unit in milliseconds - * @pre Initialize \ref nm_bsp_init first - * @warning Maximum value must nor exceed 4294967295 milliseconds which is equal to 4294967.295 seconds.\n - * @note Implementation of this function is host dependent. - * @see nm_bsp_init - * @return None - */ -void nm_bsp_sleep(uint32 u32TimeMsec); -/**@}*/ - - -/** @defgroup NmBspRegisterFn nm_bsp_register_isr -* @ingroup BSPAPI -* Register ISR (Interrupt Service Routine) in the initialization of HIF (Host Interface) Layer. -* When the interrupt trigger the BSP layer should call the pfisr function once inside the interrupt. -*/ -/**@{*/ -/*! - * @fn void nm_bsp_register_isr(tpfNmBspIsr); - * @param [in] tpfNmBspIsr pfIsr - * Pointer to ISR handler in HIF - * @warning Make sure that ISR for IRQ pin for WINC is disabled by default in your implementation. - * @note Implementation of this function is host dependent and called by HIF layer. - * @see tpfNmBspIsr - * @return None - - */ -void nm_bsp_register_isr(tpfNmBspIsr pfIsr); -/**@}*/ - - -/** @defgroup NmBspInterruptCtrl nm_bsp_interrupt_ctrl -* @ingroup BSPAPI -* Synchronous enable/disable interrupts function -*/ -/**@{*/ -/*! - * @fn void nm_bsp_interrupt_ctrl(uint8); - * @brief Enable/Disable interrupts - * @param [in] u8Enable - * '0' disable interrupts. '1' enable interrupts - * @see tpfNmBspIsr - * @note Implementation of this function is host dependent and called by HIF layer. - * @return None - - */ -void nm_bsp_interrupt_ctrl(uint8 u8Enable); - /**@}*/ - -#ifdef __cplusplus -} -#endif - -#endif - -#ifdef _NM_BSP_BIG_END -#define NM_BSP_B_L_32(x) \ -((((x) & 0x000000FF) << 24) + \ -(((x) & 0x0000FF00) << 8) + \ -(((x) & 0x00FF0000) >> 8) + \ -(((x) & 0xFF000000) >> 24)) -#define NM_BSP_B_L_16(x) \ -((((x) & 0x00FF) << 8) + \ -(((x) & 0xFF00) >> 8)) -#else -#define NM_BSP_B_L_32(x) (x) -#define NM_BSP_B_L_16(x) (x) -#endif - - -#endif /*_NM_BSP_H_*/ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h deleted file mode 100644 index 77417e8..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_arduino.h +++ /dev/null @@ -1,74 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 BSP APIs definitions. - * - * Copyright (c) 2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NM_BSP_ARDUINO_H_ -#define _NM_BSP_ARDUINO_H_ - -#include - -#include - -/* - * Arduino variants may redefine those pins. - * If no pins are specified the following defaults are used: - * WINC1501_RESET_PIN - pin 5 - * WINC1501_INTN_PIN - pin 7 - * WINC1501_CHIP_EN_PIN - not connected (tied to VCC) - */ -#if !defined(WINC1501_RESET_PIN) - #define WINC1501_RESET_PIN 5 -#endif -#if !defined(WINC1501_INTN_PIN) - #define WINC1501_INTN_PIN 7 -#endif -#if !defined(WINC1501_SPI_CS_PIN) - #define WINC1501_SPI_CS_PIN 10 -#endif -#if !defined(WINC1501_CHIP_EN_PIN) - #define WINC1501_CHIP_EN_PIN -1 -#endif - -extern int8_t gi8Winc1501CsPin; -extern int8_t gi8Winc1501ResetPin; -extern int8_t gi8Winc1501IntnPin; -extern int8_t gi8Winc1501ChipEnPin; - -#endif /* _NM_BSP_ARDUINO_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h deleted file mode 100644 index c5991f2..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_avr.h +++ /dev/null @@ -1,54 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 BSP APIs definitions. - * - * Copyright (c) 2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NM_BSP_AVR_H_ -#define _NM_BSP_AVR_H_ - -#pragma once - -#define NM_DEBUG 0 -#define NM_BSP_PRINTF - -#define CONF_WINC_USE_SPI 1 - -#define NM_EDGE_INTERRUPT 1 - -#endif /* _NM_BSP_AVR_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h deleted file mode 100644 index 45d3ff2..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_internal.h +++ /dev/null @@ -1,59 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 BSP APIs declarations. - * - * Copyright (c) 2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -/**@defgroup BSPDefine Defines - * @ingroup nm_bsp - * @{ - */ -#ifndef _NM_BSP_INTERNAL_H_ -#define _NM_BSP_INTERNAL_H_ - -#ifdef ARDUINO_ARCH_AVR -#define LIMITED_RAM_DEVICE -#include "bsp/include/nm_bsp_avr.h" -#else -#include "bsp/include/nm_bsp_samd21.h" -#endif - -#ifdef ARDUINO -#define CONF_PERIPH -#endif - -#endif //_NM_BSP_INTERNAL_H_ \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h deleted file mode 100644 index 296cd20..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/include/nm_bsp_samd21.h +++ /dev/null @@ -1,52 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 BSP APIs definitions. - * - * Copyright (c) 2015 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NM_BSP_SAMD21_H_ -#define _NM_BSP_SAMD21_H_ - -#define NM_DEBUG 0 -#define NM_BSP_PRINTF - -#define CONF_WINC_USE_SPI 1 - -#define NM_EDGE_INTERRUPT 1 - -#endif /* _NM_BSP_SAMD21_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c deleted file mode 100644 index e27be14..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino.c +++ /dev/null @@ -1,205 +0,0 @@ -/** - * - * \file - * - * \brief This module contains SAMD21 BSP APIs implementation. - * - * Copyright (c) 2014 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "bsp/include/nm_bsp.h" -#include "bsp/include/nm_bsp_arduino.h" -#include "common/include/nm_common.h" - -int8_t gi8Winc1501CsPin = WINC1501_SPI_CS_PIN; -int8_t gi8Winc1501ResetPin = WINC1501_RESET_PIN; -int8_t gi8Winc1501IntnPin = WINC1501_INTN_PIN; -int8_t gi8Winc1501ChipEnPin = WINC1501_CHIP_EN_PIN; - -static tpfNmBspIsr gpfIsr; - -void __attribute__((weak)) attachInterruptMultiArch(uint32_t pin, void *chip_isr, uint32_t mode) -{ - attachInterrupt(pin, chip_isr, mode); -} - -void __attribute__((weak)) detachInterruptMultiArch(uint32_t pin) -{ - detachInterrupt(pin); -} - -static void chip_isr(void) -{ - if (gpfIsr) { - gpfIsr(); - } -} - -/* - * @fn init_chip_pins - * @brief Initialize reset, chip enable and wake pin - * @author M.S.M - * @date 11 July 2012 - * @version 1.0 - */ -static void init_chip_pins(void) -{ - /* Configure RESETN pin as output. */ - pinMode(gi8Winc1501ResetPin, OUTPUT); - digitalWrite(gi8Winc1501ResetPin, HIGH); - - /* Configure INTN pins as input. */ - pinMode(gi8Winc1501IntnPin, INPUT); - - if (gi8Winc1501ChipEnPin > -1) - { - /* Configure CHIP_EN as pull-up */ - pinMode(gi8Winc1501ChipEnPin, INPUT_PULLUP); - } -} - -static void deinit_chip_pins(void) -{ - digitalWrite(gi8Winc1501ResetPin, LOW); - pinMode(gi8Winc1501ResetPin, INPUT); - - if (gi8Winc1501ChipEnPin > -1) - { - pinMode(gi8Winc1501ChipEnPin, INPUT); - } -} - -/* - * @fn nm_bsp_init - * @brief Initialize BSP - * @return 0 in case of success and -1 in case of failure - * @author M.S.M - * @date 11 July 2012 - * @version 1.0 - */ -sint8 nm_bsp_init(void) -{ - gpfIsr = NULL; - - init_chip_pins(); - - nm_bsp_reset(); - - return M2M_SUCCESS; -} - -/** - * @fn nm_bsp_deinit - * @brief De-iInitialize BSP - * @return 0 in case of success and -1 in case of failure - * @author M. Abdelmawla - * @date 11 July 2012 - * @version 1.0 - */ -sint8 nm_bsp_deinit(void) -{ - deinit_chip_pins(); - - return M2M_SUCCESS; -} - -/** - * @fn nm_bsp_reset - * @brief Reset NMC1500 SoC by setting CHIP_EN and RESET_N signals low, - * CHIP_EN high then RESET_N high - * @author M. Abdelmawla - * @date 11 July 2012 - * @version 1.0 - */ -void nm_bsp_reset(void) -{ - digitalWrite(gi8Winc1501ResetPin, LOW); - nm_bsp_sleep(100); - digitalWrite(gi8Winc1501ResetPin, HIGH); - nm_bsp_sleep(100); -} - -/* - * @fn nm_bsp_sleep - * @brief Sleep in units of mSec - * @param[IN] u32TimeMsec - * Time in milliseconds - * @author M.S.M - * @date 28 OCT 2013 - * @version 1.0 - */ -void nm_bsp_sleep(uint32 u32TimeMsec) -{ - while (u32TimeMsec--) { - delay(1); - } -} - -/* - * @fn nm_bsp_register_isr - * @brief Register interrupt service routine - * @param[IN] pfIsr - * Pointer to ISR handler - * @author M.S.M - * @date 28 OCT 2013 - * @sa tpfNmBspIsr - * @version 1.0 - */ -void nm_bsp_register_isr(tpfNmBspIsr pfIsr) -{ - gpfIsr = pfIsr; - attachInterruptMultiArch(gi8Winc1501IntnPin, chip_isr, FALLING); -} - -/* - * @fn nm_bsp_interrupt_ctrl - * @brief Enable/Disable interrupts - * @param[IN] u8Enable - * '0' disable interrupts. '1' enable interrupts - * @author M.S.M - * @date 28 OCT 2013 - * @version 1.0 - */ -void nm_bsp_interrupt_ctrl(uint8 u8Enable) -{ - if (u8Enable) { - attachInterruptMultiArch(gi8Winc1501IntnPin, chip_isr, FALLING); - } else { - detachInterruptMultiArch(gi8Winc1501IntnPin); - } -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c deleted file mode 100644 index 050d5d5..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bsp/source/nm_bsp_arduino_avr.c +++ /dev/null @@ -1,164 +0,0 @@ -/** - * - * \file - * - * \brief This module contains SAMD21 BSP APIs implementation. - * - * Copyright (c) 2014 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifdef ARDUINO_ARCH_AVR - -#include "bsp/include/nm_bsp.h" -#include "bsp/include/nm_bsp_arduino.h" -#include "common/include/nm_common.h" - -#define IS_MEGA (defined(ARDUINO_AVR_MEGA) || defined(ARDUINO_AVR_MEGA2560)) - -static tpfNmBspIsr gpfIsr; - -volatile uint8_t *_receivePortRegister; -volatile uint8_t *_pcint_maskreg; -uint8_t _receiveBitMask; -volatile uint8_t prev_pin_read = 1; - -uint8_t rx_pin_read() -{ - return *_receivePortRegister & _receiveBitMask; -} - -#if !IS_MEGA - -#if defined(PCINT0_vect) -ISR(PCINT0_vect) -{ - if (!rx_pin_read() && gpfIsr) - { - gpfIsr(); - } -} -#endif - -#if defined(PCINT1_vect) -ISR(PCINT1_vect, ISR_ALIASOF(PCINT0_vect)); -#endif - -#if defined(PCINT2_vect) -ISR(PCINT2_vect, ISR_ALIASOF(PCINT0_vect)); -#endif - -#if defined(PCINT3_vect) -ISR(PCINT3_vect, ISR_ALIASOF(PCINT0_vect)); -#endif - -#endif // !IS_MEGA - -#if defined(TIMER4_OVF_vect) -ISR(TIMER4_OVF_vect) { - uint8_t curr_pin_read = rx_pin_read(); - if ((curr_pin_read != prev_pin_read) && !curr_pin_read && gpfIsr) - { - gpfIsr(); - } - prev_pin_read = curr_pin_read; -} - -// stategy 3 - start a timer and perform a sort of polling -void attachFakeInterruptToTimer(void) { - TCCR4B = (1< I2C/UART. Parameter:tstrNmI2cDefault/tstrNmUartDefault */ -#define NM_BUS_IOCTL_W ((uint8)1) /*!< Write only ==> I2C/UART. Parameter type tstrNmI2cDefault/tstrNmUartDefault*/ -#define NM_BUS_IOCTL_W_SPECIAL ((uint8)2) /*!< Write two buffers within the same transaction - (same start/stop conditions) ==> I2C only. Parameter:tstrNmI2cSpecial */ -#define NM_BUS_IOCTL_RW ((uint8)3) /*!< Read/Write at the same time ==> SPI only. Parameter:tstrNmSpiRw */ - -#define NM_BUS_IOCTL_WR_RESTART ((uint8)4) /*!< Write buffer then made restart condition then read ==> I2C only. parameter:tstrNmI2cSpecial */ -/** -* @struct tstrNmBusCapabilities -* @brief Structure holding bus capabilities information -* @sa NM_BUS_TYPE_I2C, NM_BUS_TYPE_SPI -*/ -typedef struct -{ - uint16 u16MaxTrxSz; /*!< Maximum transfer size. Must be >= 16 bytes*/ -} tstrNmBusCapabilities; - -/** -* @struct tstrNmI2cDefault -* @brief Structure holding I2C default operation parameters -* @sa NM_BUS_IOCTL_R, NM_BUS_IOCTL_W -*/ -typedef struct -{ - uint8 u8SlaveAdr; - uint8 *pu8Buf; /*!< Operation buffer */ - uint16 u16Sz; /*!< Operation size */ -} tstrNmI2cDefault; - -/** -* @struct tstrNmI2cSpecial -* @brief Structure holding I2C special operation parameters -* @sa NM_BUS_IOCTL_W_SPECIAL -*/ -typedef struct -{ - uint8 u8SlaveAdr; - uint8 *pu8Buf1; /*!< pointer to the 1st buffer */ - uint8 *pu8Buf2; /*!< pointer to the 2nd buffer */ - uint16 u16Sz1; /*!< 1st buffer size */ - uint16 u16Sz2; /*!< 2nd buffer size */ -} tstrNmI2cSpecial; - -/** -* @struct tstrNmSpiRw -* @brief Structure holding SPI R/W parameters -* @sa NM_BUS_IOCTL_RW -*/ -typedef struct -{ - uint8 *pu8InBuf; /*!< pointer to input buffer. - Can be set to null and in this case zeros should be sent at MOSI */ - uint8 *pu8OutBuf; /*!< pointer to output buffer. - Can be set to null and in this case data from MISO can be ignored */ - uint16 u16Sz; /*!< Transfere size */ -} tstrNmSpiRw; - - -/** -* @struct tstrNmUartDefault -* @brief Structure holding UART default operation parameters -* @sa NM_BUS_IOCTL_R, NM_BUS_IOCTL_W -*/ -typedef struct -{ - uint8 *pu8Buf; /*!< Operation buffer */ - uint16 u16Sz; /*!< Operation size */ -} tstrNmUartDefault; -/*!< Bus capabilities. This structure must be declared at platform specific bus wrapper */ -extern tstrNmBusCapabilities egstrNmBusCapabilities; - - -#ifdef __cplusplus - extern "C" { - #endif -/** -* @fn nm_bus_init -* @brief Initialize the bus wrapper -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_bus_init(void *); - -/** -* @fn nm_bus_ioctl -* @brief send/receive from the bus -* @param [in] u8Cmd -* IOCTL command for the operation -* @param [in] pvParameter -* Arbitrary parameter depending on IOCTL -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -* @note For SPI only, it's important to be able to send/receive at the same time -*/ -sint8 nm_bus_ioctl(uint8 u8Cmd, void* pvParameter); - -/** -* @fn nm_bus_deinit -* @brief De-initialize the bus wrapper -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_bus_deinit(void); - -/* -* @fn nm_bus_reinit -* @brief re-initialize the bus wrapper -* @param [in] void *config -* re-init configuration data -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_bus_reinit(void *); -/* -* @fn nm_bus_get_chip_type -* @brief get chip type -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -#ifdef CONF_WINC_USE_UART -uint8 nm_bus_get_chip_type(void); -#endif -#ifdef __cplusplus - } - #endif - -#endif /*_NM_BUS_WRAPPER_H_*/ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp deleted file mode 100644 index 22a7473..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/bus_wrapper/source/nm_bus_wrapper_samd21.cpp +++ /dev/null @@ -1,200 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 bus wrapper APIs implementation. - * - * Copyright (c) 2014 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * 4. This software may only be redistributed and used in connection with an - * Atmel microcontroller product. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include -#include - -/* - * Variants may define an alternative SPI instace to use for WiFi101. - * If not defined the following defaults are used: - * WINC1501_SPI - SPI - */ -#if !defined(WINC1501_SPI) - #define WINC1501_SPI SPI -#endif - -extern "C" { - -#include "bsp/include/nm_bsp.h" -#include "bsp/include/nm_bsp_arduino.h" -#include "common/include/nm_common.h" -#include "bus_wrapper/include/nm_bus_wrapper.h" - -} - -#define NM_BUS_MAX_TRX_SZ 256 - -tstrNmBusCapabilities egstrNmBusCapabilities = -{ - NM_BUS_MAX_TRX_SZ -}; - -static const SPISettings wifi_SPISettings(12000000L, MSBFIRST, SPI_MODE0); - -static sint8 spi_rw(uint8* pu8Mosi, uint8* pu8Miso, uint16 u16Sz) -{ - uint8 u8Dummy = 0; - uint8 u8SkipMosi = 0, u8SkipMiso = 0; - - if (!pu8Mosi) { - pu8Mosi = &u8Dummy; - u8SkipMosi = 1; - } - else if(!pu8Miso) { - pu8Miso = &u8Dummy; - u8SkipMiso = 1; - } - else { - return M2M_ERR_BUS_FAIL; - } - - WINC1501_SPI.beginTransaction(wifi_SPISettings); - digitalWrite(gi8Winc1501CsPin, LOW); - - while (u16Sz) { - *pu8Miso = WINC1501_SPI.transfer(*pu8Mosi); - - u16Sz--; - if (!u8SkipMiso) - pu8Miso++; - if (!u8SkipMosi) - pu8Mosi++; - } - - digitalWrite(gi8Winc1501CsPin, HIGH); - WINC1501_SPI.endTransaction(); - - return M2M_SUCCESS; -} - -extern "C" { - -/* -* @fn nm_bus_init -* @brief Initialize the bus wrapper -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M.S.M -* @date 28 oct 2013 -* @version 1.0 -*/ -sint8 nm_bus_init(void * /* pvInitValue */) -{ - sint8 result = M2M_SUCCESS; - - /* Configure SPI peripheral. */ - WINC1501_SPI.begin(); - - /* Configure CS PIN. */ - pinMode(gi8Winc1501CsPin, OUTPUT); - digitalWrite(gi8Winc1501CsPin, HIGH); - - /* Reset WINC1500. */ - nm_bsp_reset(); - nm_bsp_sleep(1); - - return result; -} - -/* -* @fn nm_bus_ioctl -* @brief send/receive from the bus -* @param[IN] u8Cmd -* IOCTL command for the operation -* @param[IN] pvParameter -* Arbitrary parameter depenging on IOCTL -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M.S.M -* @date 28 oct 2013 -* @note For SPI only, it's important to be able to send/receive at the same time -* @version 1.0 -*/ -sint8 nm_bus_ioctl(uint8 u8Cmd, void* pvParameter) -{ - sint8 s8Ret = 0; - switch(u8Cmd) - { - case NM_BUS_IOCTL_RW: { - tstrNmSpiRw *pstrParam = (tstrNmSpiRw *)pvParameter; - s8Ret = spi_rw(pstrParam->pu8InBuf, pstrParam->pu8OutBuf, pstrParam->u16Sz); - } - break; - default: - s8Ret = -1; - M2M_ERR("invalide ioclt cmd\n"); - break; - } - - return s8Ret; -} - -/* -* @fn nm_bus_deinit -* @brief De-initialize the bus wrapper -* @author M.S.M -* @date 28 oct 2013 -* @version 1.0 -*/ -sint8 nm_bus_deinit(void) -{ - WINC1501_SPI.end(); - return 0; -} - -/* -* @fn nm_bus_reinit -* @brief re-initialize the bus wrapper -* @param [in] void *config -* re-init configuration data -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Dina El Sissy -* @date 19 Sept 2012 -* @version 1.0 -*/ -sint8 nm_bus_reinit(void* /* config */) -{ - return M2M_SUCCESS; -} - -} // extern "C" - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/include/nm_common.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/include/nm_common.h deleted file mode 100644 index d66fbdb..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/include/nm_common.h +++ /dev/null @@ -1,153 +0,0 @@ -/** - * - * \file - * - * \brief WINC Driver Common API Declarations. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NM_COMMON_H_ -#define _NM_COMMON_H_ - -#include "bsp/include/nm_bsp.h" -#include "common/include/nm_debug.h" - -/**@defgroup CommonDefines CommonDefines - * @ingroup WlanDefines - */ -/**@{*/ -#define M2M_TIME_OUT_DELAY 10000 - -/*states*/ -#define M2M_SUCCESS ((sint8)0) -#define M2M_ERR_SEND ((sint8)-1) -#define M2M_ERR_RCV ((sint8)-2) -#define M2M_ERR_MEM_ALLOC ((sint8)-3) -#define M2M_ERR_TIME_OUT ((sint8)-4) -#define M2M_ERR_INIT ((sint8)-5) -#define M2M_ERR_BUS_FAIL ((sint8)-6) -#define M2M_NOT_YET ((sint8)-7) -#define M2M_ERR_FIRMWARE ((sint8)-8) -#define M2M_SPI_FAIL ((sint8)-9) -#define M2M_ERR_FIRMWARE_bURN ((sint8)-10) -#define M2M_ACK ((sint8)-11) -#define M2M_ERR_FAIL ((sint8)-12) -#define M2M_ERR_FW_VER_MISMATCH ((sint8)-13) -#define M2M_ERR_SCAN_IN_PROGRESS ((sint8)-14) -#define M2M_ERR_INVALID_ARG ((sint8)-15) -#define M2M_ERR_INVALID ((sint8)-16) - -/*i2c MAASTER ERR*/ -#define I2C_ERR_LARGE_ADDRESS 0xE1UL /*the address exceed the max addressing mode in i2c flash*/ -#define I2C_ERR_TX_ABRT 0xE2UL /*NO ACK from slave*/ -#define I2C_ERR_OVER_SIZE 0xE3UL /**/ -#define ERR_PREFIX_NMIS 0xE4UL /*wrong first four byte in flash NMIS*/ -#define ERR_FIRMEWARE_EXCEED_SIZE 0xE5UL /*Total size of firmware exceed the max size 256k*/ -/**/ -#define PROGRAM_START 0x26961735UL -#define BOOT_SUCCESS 0x10add09eUL -#define BOOT_START 0x12345678UL - - -#define NBIT31 (0x80000000) -#define NBIT30 (0x40000000) -#define NBIT29 (0x20000000) -#define NBIT28 (0x10000000) -#define NBIT27 (0x08000000) -#define NBIT26 (0x04000000) -#define NBIT25 (0x02000000) -#define NBIT24 (0x01000000) -#define NBIT23 (0x00800000) -#define NBIT22 (0x00400000) -#define NBIT21 (0x00200000) -#define NBIT20 (0x00100000) -#define NBIT19 (0x00080000) -#define NBIT18 (0x00040000) -#define NBIT17 (0x00020000) -#define NBIT16 (0x00010000) -#define NBIT15 (0x00008000) -#define NBIT14 (0x00004000) -#define NBIT13 (0x00002000) -#define NBIT12 (0x00001000) -#define NBIT11 (0x00000800) -#define NBIT10 (0x00000400) -#define NBIT9 (0x00000200) -#define NBIT8 (0x00000100) -#define NBIT7 (0x00000080) -#define NBIT6 (0x00000040) -#define NBIT5 (0x00000020) -#define NBIT4 (0x00000010) -#define NBIT3 (0x00000008) -#define NBIT2 (0x00000004) -#define NBIT1 (0x00000002) -#define NBIT0 (0x00000001) - -#define M2M_MAX(A,B) ((A) > (B) ? (A) : (B)) -#define M2M_SEL(x,m1,m2,m3) ((x>1)?((x>2)?(m3):(m2)):(m1)) -#define WORD_ALIGN(val) (((val) & 0x03) ? ((val) + 4 - ((val) & 0x03)) : (val)) - - - -#define DATA_PKT_OFFSET 4 - -#ifndef BIG_ENDIAN -#define BYTE_0(word) ((uint8)(((word) >> 0 ) & 0x000000FFUL)) -#define BYTE_1(word) ((uint8)(((word) >> 8 ) & 0x000000FFUL)) -#define BYTE_2(word) ((uint8)(((word) >> 16) & 0x000000FFUL)) -#define BYTE_3(word) ((uint8)(((word) >> 24) & 0x000000FFUL)) -#else -#define BYTE_0(word) ((uint8)(((word) >> 24) & 0x000000FFUL)) -#define BYTE_1(word) ((uint8)(((word) >> 16) & 0x000000FFUL)) -#define BYTE_2(word) ((uint8)(((word) >> 8 ) & 0x000000FFUL)) -#define BYTE_3(word) ((uint8)(((word) >> 0 ) & 0x000000FFUL)) -#endif - -/**@}*/ -#ifdef __cplusplus - extern "C" { - #endif -NMI_API void m2m_memcpy(uint8* pDst,uint8* pSrc,uint32 sz); -NMI_API void m2m_memset(uint8* pBuf,uint8 val,uint32 sz); -NMI_API uint16 m2m_strlen(uint8 * pcStr); -NMI_API sint8 m2m_memcmp(uint8 *pu8Buff1,uint8 *pu8Buff2 ,uint32 u32Size); -NMI_API uint8 m2m_strncmp(uint8 *pcS1, uint8 *pcS2, uint16 u16Len); -NMI_API uint8 * m2m_strstr(uint8 *pcIn, uint8 *pcStr); -NMI_API uint8 m2m_checksum(uint8* buf, int sz); - -#ifdef __cplusplus -} - #endif -#endif /*_NM_COMMON_H_*/ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/include/nm_debug.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/include/nm_debug.h deleted file mode 100644 index a710f6c..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/include/nm_debug.h +++ /dev/null @@ -1,95 +0,0 @@ -/** - * - * \file - * - * \brief This module contains debug APIs declarations. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NM_DEBUG_H_ -#define _NM_DEBUG_H_ - -#include "bsp/include/nm_bsp.h" -#include "bsp/include/nm_bsp_internal.h" - -/**@defgroup DebugDefines DebugDefines - * @ingroup WlanDefines - */ -/**@{*/ - - -#define M2M_LOG_NONE 0 -#define M2M_LOG_ERROR 1 -#define M2M_LOG_INFO 2 -#define M2M_LOG_REQ 3 -#define M2M_LOG_DBG 4 - -#if (defined __APS3_CORTUS__) -#define M2M_LOG_LEVEL M2M_LOG_INFO -#else -#define M2M_LOG_LEVEL M2M_LOG_REQ -#endif - - -#define M2M_ERR(...) -#define M2M_INFO(...) -#define M2M_REQ(...) -#define M2M_DBG(...) -#define M2M_PRINT(...) - -#if (CONF_WINC_DEBUG == 1) -#undef M2M_PRINT -#define M2M_PRINT(...) do{CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) -#if (M2M_LOG_LEVEL >= M2M_LOG_ERROR) -#undef M2M_ERR -#define M2M_ERR(...) do{CONF_WINC_PRINTF("(APP)(ERR)[%s][%d]",__FUNCTION__,__LINE__); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) -#if (M2M_LOG_LEVEL >= M2M_LOG_INFO) -#undef M2M_INFO -#define M2M_INFO(...) do{CONF_WINC_PRINTF("(APP)(INFO)"); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) -#if (M2M_LOG_LEVEL >= M2M_LOG_REQ) -#undef M2M_REQ -#define M2M_REQ(...) do{CONF_WINC_PRINTF("(APP)(R)"); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) -#if (M2M_LOG_LEVEL >= M2M_LOG_DBG) -#undef M2M_DBG -#define M2M_DBG(...) do{CONF_WINC_PRINTF("(APP)(DBG)[%s][%d]",__FUNCTION__,__LINE__); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0) -#endif /*M2M_LOG_DBG*/ -#endif /*M2M_LOG_REQ*/ -#endif /*M2M_LOG_INFO*/ -#endif /*M2M_LOG_ERROR*/ -#endif /*CONF_WINC_DEBUG */ - -/**@}*/ -#endif /* _NM_DEBUG_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/source/nm_common.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/source/nm_common.c deleted file mode 100644 index 8b3c941..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/common/source/nm_common.c +++ /dev/null @@ -1,136 +0,0 @@ -/** - * - * \file - * - * \brief This module contains common APIs declarations. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -#include "common/include/nm_common.h" - -void m2m_memcpy(uint8* pDst,uint8* pSrc,uint32 sz) -{ - if(sz == 0) return; - do - { - *pDst = *pSrc; - pDst++; - pSrc++; - }while(--sz); -} -uint8 m2m_checksum(uint8* buf, int sz) -{ - uint8 cs = 0; - while(--sz) - { - cs ^= *buf; - buf++; - } - - return cs; -} - -void m2m_memset(uint8* pBuf,uint8 val,uint32 sz) -{ - if(sz == 0) return; - do - { - *pBuf = val; - pBuf++; - }while(--sz); -} - -uint16 m2m_strlen(uint8 * pcStr) -{ - uint16 u16StrLen = 0; - while(*pcStr) - { - u16StrLen ++; - pcStr++; - } - return u16StrLen; -} - -uint8 m2m_strncmp(uint8 *pcS1, uint8 *pcS2, uint16 u16Len) -{ - for ( ; u16Len > 0; pcS1++, pcS2++, --u16Len) - if (*pcS1 != *pcS2) - return ((*(uint8 *)pcS1 < *(uint8 *)pcS2) ? -1 : +1); - else if (*pcS1 == '\0') - return 0; - return 0; -} - -/* Finds the occurance of pcStr in pcIn. -If pcStr is part of pcIn it returns a valid pointer to the start of pcStr within pcIn. -Otherwise a NULL Pointer is returned. -*/ -uint8 * m2m_strstr(uint8 *pcIn, uint8 *pcStr) -{ - uint8 u8c; - uint16 u16StrLen; - - u8c = *pcStr++; - if (!u8c) - return (uint8 *) pcIn; // Trivial empty string case - - u16StrLen = m2m_strlen(pcStr); - do { - uint8 u8Sc; - - do { - u8Sc = *pcIn++; - if (!u8Sc) - return (uint8 *) 0; - } while (u8Sc != u8c); - } while (m2m_strncmp(pcIn, pcStr, u16StrLen) != 0); - - return (uint8 *) (pcIn - 1); -} - -sint8 m2m_memcmp(uint8 *pu8Buff1,uint8 *pu8Buff2 ,uint32 u32Size) -{ - uint32 i; - sint8 s8Result = 0; - for(i = 0 ; i < u32Size ; i++) - { - if(pu8Buff1[i] != pu8Buff2[i]) - { - s8Result = 1; - break; - } - } - return s8Result; -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/ecc_types.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/ecc_types.h deleted file mode 100644 index 764c3b9..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/ecc_types.h +++ /dev/null @@ -1,245 +0,0 @@ -/** - * - * \file - * - * \brief WINC Application Interface Internal Types. - * - * Copyright (c) 2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef __ECC_TYPES_H__ -#define __ECC_TYPES_H__ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "m2m_types.h" - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - - -#define ECC_LARGEST_CURVE_SIZE (32) -/*!< - The size of the the largest supported EC. For now, assuming - the 256-bit EC is the largest supported curve type. -*/ - - -#define ECC_POINT_MAX_SIZE ECC_LARGEST_CURVE_SIZE -/*!< - Maximum size of one coordinate of an EC point. -*/ - - -#define ECC_POINT_MAX_SIZE_WORDS (ECC_POINT_MAX_SIZE / 4) -/*!< - SIZE in 32-bit words. -*/ - -#if 0 -#define ECC_NUM_SUPP_CURVES ((sizeof(gastrECCSuppList)) / (sizeof(tstrEllipticCurve))) -#endif -/*!< -*/ - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -/*! -@enum \ - tenuEcNamedCurve - -@brief EC Named Curves - - Defines a list of supported ECC named curves. -*/ -typedef enum EcNamedCurve{ - EC_SECP192R1 = 19, - /*!< - It is defined by NIST as P192 and by the SEC Group as secp192r1. - */ - EC_SECP256R1 = 23, - /*!< - It is defined by NIST as P256 and by the SEC Group as secp256r1. - */ - EC_SECP384R1 = 24, - /*!< - It is defined by NIST as P384 and by the SEC Group as secp384r1. - */ - EC_SECP521R1 = 25, - /*!< - It is defined by NIST as P521 and by the SEC Group as secp521r1. - */ - EC_UNKNOWN = 255 -}tenuEcNamedCurve; - - -/*! -@struct \ - tstrECPoint - -@brief Elliptic Curve point representation -*/ -typedef struct EcPoint{ - uint8 X[ECC_POINT_MAX_SIZE]; - /*!< - The X-coordinate of the ec point. - */ - uint8 Y[ECC_POINT_MAX_SIZE]; - /*!< - The Y-coordinate of the ec point. - */ - uint16 u16Size; - /*!< - Point size in bytes (for each of the coordinates). - */ - uint16 u16PrivKeyID; - /*!< - ID for the corresponding private key. - */ -}tstrECPoint; - - -/*! -@struct \ - tstrECDomainParam - -@brief ECC Curve Domain Parameters - - The structure defines the ECC domain parameters for curves defined over prime finite fields. -*/ -typedef struct EcDomainParam{ - uint32 p[ECC_POINT_MAX_SIZE_WORDS]; - uint32 a[ECC_POINT_MAX_SIZE_WORDS]; - uint32 b[ECC_POINT_MAX_SIZE_WORDS]; - tstrECPoint G; -}tstrECDomainParam; - - -/*! -@struct \ - tstrEllipticCurve - -@brief - Definition of an elliptic curve -*/ -typedef struct{ - tenuEcNamedCurve enuType; - tstrECDomainParam strParam; -}tstrEllipticCurve; - - -typedef enum{ - ECC_REQ_NONE, - ECC_REQ_CLIENT_ECDH, - ECC_REQ_SERVER_ECDH, - ECC_REQ_GEN_KEY, - ECC_REQ_SIGN_GEN, - ECC_REQ_SIGN_VERIFY -}tenuEccREQ; - - -typedef struct{ - tstrECPoint strPubKey; - uint8 au8Key[ECC_POINT_MAX_SIZE]; -}tstrEcdhReqInfo; - - -typedef struct{ - uint32 u32nSig; -}tstrEcdsaVerifyReqInfo; - - -typedef struct{ - uint16 u16CurveType; - uint16 u16HashSz; -}tstrEcdsaSignReqInfo; - - -typedef struct{ - uint16 u16REQ; - uint16 u16Status; - uint32 u32UserData; - uint32 u32SeqNo; - union{ - tstrEcdhReqInfo strEcdhREQ; - tstrEcdsaSignReqInfo strEcdsaSignREQ; - tstrEcdsaVerifyReqInfo strEcdsaVerifyREQ; - }; -}tstrEccReqInfo; - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -GLOBALS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#if 0 -static tstrEllipticCurve gastrECCSuppList[] = { - { - EC_SECP256R1, - { - {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF}, - {0xFFFFFFFC, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF}, - {0x27D2604B, 0x3BCE3C3E, 0xCC53B0F6, 0x651D06B0, 0x769886BC, 0xB3EBBD55, 0xAA3A93E7, 0x5AC635D8}, - { - { - 0x6B, 0x17, 0xD1, 0xF2, 0xE1, 0x2C, 0x42, 0x47, 0xF8, 0xBC, 0xE6, 0xE5, 0x63, 0xA4, 0x40, 0xF2, - 0x77, 0x03, 0x7D, 0x81, 0x2D, 0xEB, 0x33, 0xA0, 0xF4, 0xA1, 0x39, 0x45, 0xD8, 0x98, 0xC2, 0x96 - }, - { - 0x4F, 0xE3, 0x42, 0xE2, 0xFE, 0x1A, 0x7F, 0x9B, 0x8E, 0xE7, 0xEB, 0x4A, 0x7C, 0x0F, 0x9E, 0x16, - 0x2B, 0xCE, 0x33, 0x57, 0x6B, 0x31, 0x5E, 0xCE, 0xCB, 0xB6, 0x40, 0x68, 0x37, 0xBF, 0x51, 0xF5 - }, - 32 - } - } - } -}; -#endif - -/*!< - List of supported Elliptic Curves ordered by security level (most secure curve is at index ZERO). -*/ - - - -#endif /* __ECC_TYPES_H__ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_ate_mode.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_ate_mode.h deleted file mode 100644 index a17d298..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_ate_mode.h +++ /dev/null @@ -1,732 +0,0 @@ -/** - * - * \file - * - * \brief WINC ATE Test Driver Interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifdef _M2M_ATE_FW_ - -#ifndef _M2M_ATE_MODE_H_ -#define _M2M_ATE_MODE_H_ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#include "common/include/nm_common.h" -#include "driver/include/m2m_types.h" - -/** \defgroup m2m_ate ATE -*/ -/**@defgroup ATEDefine Defines - * @ingroup m2m_ate - * @{ - */ -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#define M2M_ATE_MAX_NUM_OF_RATES (20) -/*!< -Maximum number of all rates (b,g and n) - */ -#define M2M_ATE_MAX_FRAME_LENGTH (1024) -/*!< Maximum number of length for each frame - */ -#define M2M_ATE_MIN_FRAME_LENGTH (1) -/*!< Minimum number of length for each frame - */ -#define M2M_ATE_SUCCESS (M2M_SUCCESS) -/*!< No Error and operation has been completed successfully. -*/ -#define M2M_ATE_ERR_VALIDATE (M2M_ERR_FAIL) -/*!< Error in parameters passed to functions. - */ -#define M2M_ATE_ERR_TX_ALREADY_RUNNING (-1) -/*!< Error in starting a transmission test. Another test is already running and its not allowed to start another ATE test. - */ -#define M2M_ATE_ERR_RX_ALREADY_RUNNING (-2) -/*!< Error in starting a reception test. Another test is already running and its not allowed to start another ATE test. - */ -#define M2M_ATE_ERR_UNHANDLED_CASE (-3) -/*!< Invalid case. - */ -#define M2M_ATE_RX_DISABLE_DA 0x0 -/*!< Filter selection for received frames: Disable filtering received frames by the destination address. - */ -#define M2M_ATE_RX_ENABLE_DA 0x1 -/*!< Filter selection for received frames: Enable filtering received frames by the destination address. - */ -#define M2M_ATE_RX_DISABLE_SA 0x0 -/*!< Filter selection for received frames: Disable filtering received frames by the source address. - */ -#define M2M_ATE_RX_ENABLE_SA 0x1 -/*!< Filter selection for received frames: Enable filtering received frames by the source address. - */ -#define M2M_ATE_DISABLE_SELF_MACADDR 0x0 -/*!\n",ret); - while(1); - } - //Initialize the OTA module - m2m_ota_init(OtaUpdateCb,NULL); - //connect to AP that provide connection to the OTA server - m2m_wifi_default_connect(); - - while(1) - { - - //Handle the app state machine plus the WINC event handler - while(m2m_wifi_handle_events(NULL) != M2M_SUCCESS) { - - } - - } -} -@endcode - -*/ -NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl); - /**@}*/ -/** @defgroup OtaStartUpdatefn m2m_ota_start_update_crt -* @ingroup WLANAPI -* Request OTA start for cortus application image using the downloaded URL, the OTA module will download the OTA image and ensure integrity of the image, -* and update the validity of the image in control structure. Switching to that image requires calling @ref m2m_ota_switch_crt API. -* As a prerequisite @ref m2m_ota_init should be called before using @ref m2m_ota_start_update_crt(). -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl); - -@param [in] u8DownloadUrl - The cortus application image url. -@warning - Calling this API does not guarantee cortus application image update, It depends on the connection with the download server and the validity of the image. - If the API response is failure this may invalidate the roll-back image if it was previously valid, since the WINC does not have any internal memory - except the flash roll-back image location to validate the downloaded image from - -@see - m2m_ota_init - tpfOtaUpdateCb - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl); - /**@}*/ -/** @defgroup OtaRollbackfn m2m_ota_rollback -* @ingroup WLANAPI - Request OTA Roll-back to the old (other) WINC image, the WINC firmware will check the validation of the Roll-back image - and switch to it if it is valid. - If the API response is success, system restart is required (re-initialize the driver with hardware rest) update the host driver version may - be required if it is did not match the minimum version supported by the WINC firmware. - -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ota_rollback(void); - -@sa - m2m_ota_init - m2m_ota_start_update - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_rollback(void); - /**@}*/ -/** @defgroup OtaRollbackfn m2m_ota_rollback_crt -* @ingroup WLANAPI - Request Cortus application OTA Roll-back to the old (other) cortus application image, the WINC firmware will check the validation of the Roll-back image - and switch to it if it is valid. - If the API response is success, system restart is required (re-initialize the driver with hardware rest) update the host driver version may - be required. - -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ota_rollback_crt(void); - -@sa - m2m_ota_init - m2m_ota_start_update_crt - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_rollback_crt(void); - /**@}*/ -/** @defgroup OtaAbortfn m2m_ota_abort -* @ingroup WLANAPI - Request abort of current OTA download. - The WINC firmware will terminate the OTA download if one is in progress. - If no download is in progress, the API will respond with failure. -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ota_abort(void); - -@return - The function returns @ref M2M_SUCCESS for successful operation and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_abort(void); - /**@}*/ - /**@}*/ -/** @defgroup OtaSwitchFirmware m2m_ota_switch_firmware -* @ingroup WLANAPI -* Switch to the upgraded Firmware, that API will update the control structure working image to the upgraded image - take effect will be on the next system restart -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ota_switch_firmware(void); - -@warning - It is important to note that if the API succeeds, system restart is required (re-initializing the driver with hardware reset) updating the host driver version may be required - if it does not match the minimum driver version supported by the WINC's firmware. -@sa - m2m_ota_init - m2m_ota_start_update - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_switch_firmware(void); - /**@}*/ - /**@}*/ -/** @defgroup OtaSwitchFirmware m2m_ota_switch_crt -* @ingroup WLANAPI -* Switch to the upgraded cortus application, that API will update the control structure working image to the upgraded image - take effect will be on the next system restart -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ota_switch_firmware(void); - -@warning - It is important to note that if the API succeeds, system restart is required (re-initializing the driver with hardware reset) updating the host driver version may be required - if it does not match the minimum driver version supported by the WINC's firmware. -@sa - m2m_ota_init - m2m_ota_start_update_crt - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_switch_crt(void); -/*! -@fn \ - NMI_API sint8 m2m_ota_get_firmware_version(void); - -@brief - Get the OTA Firmware version. - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_get_firmware_version(tstrM2mRev *pstrRev); - /**@}*/ -NMI_API sint8 m2m_ota_test(void); - -#ifdef __cplusplus -} -#endif -#endif /* __M2M_OTA_H__ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_periph.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_periph.h deleted file mode 100644 index 1012882..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_periph.h +++ /dev/null @@ -1,411 +0,0 @@ -/** - * - * \file - * - * \brief WINC Peripherals Application Interface. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _M2M_PERIPH_H_ -#define _M2M_PERIPH_H_ - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -#include "common/include/nm_common.h" -#include "driver/include/m2m_types.h" - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*! -@struct \ - tstrPerphInitParam - -@brief - Peripheral module initialization parameters. -*/ -typedef struct { - void * arg; -} tstrPerphInitParam; - - -/*! -@enum \ - tenuGpioNum - -@brief - A list of GPIO numbers configurable through the m2m_periph module. -*/ -typedef enum { - M2M_PERIPH_GPIO3, /*!< GPIO15 pad */ - M2M_PERIPH_GPIO4, /*!< GPIO16 pad */ - M2M_PERIPH_GPIO5, /*!< GPIO18 pad */ - M2M_PERIPH_GPIO6, /*!< GPIO18 pad */ - M2M_PERIPH_GPIO15, /*!< GPIO15 pad */ - M2M_PERIPH_GPIO16, /*!< GPIO16 pad */ - M2M_PERIPH_GPIO18, /*!< GPIO18 pad */ - M2M_PERIPH_GPIO_MAX -} tenuGpioNum; - - -/*! -@enum \ - tenuI2cMasterSclMuxOpt - -@brief - Allowed pin multiplexing options for I2C master SCL signal. -*/ -typedef enum { - M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_HOST_WAKEUP, /*!< I2C master SCL is avaiable on HOST_WAKEUP. */ - M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_SD_DAT3, /*!< I2C master SCL is avaiable on SD_DAT3 (GPIO 7). */ - M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_GPIO13, /*!< I2C master SCL is avaiable on GPIO 13. */ - M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_GPIO4, /*!< I2C master SCL is avaiable on GPIO 4.*/ - M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_I2C_SCL, /*!< I2C master SCL is avaiable on I2C slave SCL. */ - M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_NUM -} tenuI2cMasterSclMuxOpt; - -/*! -@enum \ - tenuI2cMasterSdaMuxOpt - -@brief - Allowed pin multiplexing options for I2C master SDA signal. -*/ -typedef enum { - M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_RTC_CLK , /*!< I2C master SDA is avaiable on RTC_CLK. */ - M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_SD_CLK, /*!< I2C master SDA is avaiable on SD_CLK (GPIO 8). */ - M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_GPIO14, /*!< I2C master SDA is avaiable on GPIO 14. */ - M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_GPIO6, /*!< I2C master SDA is avaiable on GPIO 6.*/ - M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_I2C_SDA, /*!< I2C master SDA is avaiable on I2C slave SDA. */ - M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_NUM -} tenuI2cMasterSdaMuxOpt; - - -/*! -@struct \ - tstrI2cMasterInitParam - -@brief - I2C master configuration parameters. -@sa - tenuI2cMasterSclMuxOpt - tenuI2cMasterSdaMuxOpt -*/ -typedef struct { - uint8 enuSclMuxOpt; /*!< SCL multiplexing option. Allowed value are defined in tenuI2cMasterSclMuxOpt */ - uint8 enuSdaMuxOpt; /*!< SDA multiplexing option. Allowed value are defined in tenuI2cMasterSdaMuxOpt */ - uint8 u8ClkSpeedKHz; /*!< I2C master clock speed in KHz. */ -} tstrI2cMasterInitParam; - -/*! -@enum \ - tenuI2cMasterFlags - -@brief - Bitwise-ORed flags for use in m2m_periph_i2c_master_write and m2m_periph_i2c_master_read -@sa - m2m_periph_i2c_master_write - m2m_periph_i2c_master_read -*/ -typedef enum { - I2C_MASTER_NO_FLAGS = 0x00, - /*!< No flags. */ - I2C_MASTER_NO_STOP = 0x01, - /*!< No stop bit after this transaction. Useful for scattered buffer read/write operations. */ - I2C_MASTER_NO_START = 0x02, - /*!< No start bit at the beginning of this transaction. Useful for scattered buffer read/write operations.*/ -} tenuI2cMasterFlags; - -/*! -@enum \ - tenuPullupMask - -@brief - Bitwise-ORed flags for use in m2m_perph_pullup_ctrl. -@sa - m2m_periph_pullup_ctrl - -*/ -typedef enum { - M2M_PERIPH_PULLUP_DIS_HOST_WAKEUP = (1ul << 0), - M2M_PERIPH_PULLUP_DIS_RTC_CLK = (1ul << 1), - M2M_PERIPH_PULLUP_DIS_IRQN = (1ul << 2), - M2M_PERIPH_PULLUP_DIS_GPIO_3 = (1ul << 3), - M2M_PERIPH_PULLUP_DIS_GPIO_4 = (1ul << 4), - M2M_PERIPH_PULLUP_DIS_GPIO_5 = (1ul << 5), - M2M_PERIPH_PULLUP_DIS_SD_DAT3 = (1ul << 6), - M2M_PERIPH_PULLUP_DIS_SD_DAT2_SPI_RXD = (1ul << 7), - M2M_PERIPH_PULLUP_DIS_SD_DAT1_SPI_SSN = (1ul << 9), - M2M_PERIPH_PULLUP_DIS_SD_CMD_SPI_SCK = (1ul << 10), - M2M_PERIPH_PULLUP_DIS_SD_DAT0_SPI_TXD = (1ul << 11), - M2M_PERIPH_PULLUP_DIS_GPIO_6 = (1ul << 12), - M2M_PERIPH_PULLUP_DIS_SD_CLK = (1ul << 13), - M2M_PERIPH_PULLUP_DIS_I2C_SCL = (1ul << 14), - M2M_PERIPH_PULLUP_DIS_I2C_SDA = (1ul << 15), - M2M_PERIPH_PULLUP_DIS_GPIO_11 = (1ul << 16), - M2M_PERIPH_PULLUP_DIS_GPIO_12 = (1ul << 17), - M2M_PERIPH_PULLUP_DIS_GPIO_13 = (1ul << 18), - M2M_PERIPH_PULLUP_DIS_GPIO_14 = (1ul << 19), - M2M_PERIPH_PULLUP_DIS_GPIO_15 = (1ul << 20), - M2M_PERIPH_PULLUP_DIS_GPIO_16 = (1ul << 21), - M2M_PERIPH_PULLUP_DIS_GPIO_17 = (1ul << 22), - M2M_PERIPH_PULLUP_DIS_GPIO_18 = (1ul << 23), - M2M_PERIPH_PULLUP_DIS_GPIO_19 = (1ul << 24), - M2M_PERIPH_PULLUP_DIS_GPIO_20 = (1ul << 25), - M2M_PERIPH_PULLUP_DIS_GPIO_21 = (1ul << 26), - M2M_PERIPH_PULLUP_DIS_GPIO_22 = (1ul << 27), - M2M_PERIPH_PULLUP_DIS_GPIO_23 = (1ul << 28), - M2M_PERIPH_PULLUP_DIS_GPIO_24 = (1ul << 29), -} tenuPullupMask; - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -#ifdef __cplusplus - extern "C" { -#endif - -/*! -@fn \ - NMI_API sint8 m2m_periph_init(tstrPerphInitParam * param); - -@brief - Initialize the NMC1500 peripheral driver module. - -@param [in] param - Peripheral module initialization structure. See members of tstrPerphInitParam. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tstrPerphInitParam -*/ -NMI_API sint8 m2m_periph_init(tstrPerphInitParam * param); - -/*! -@fn \ - NMI_API sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir); - -@brief - Configure a specific NMC1500 pad as a GPIO and sets its direction (input or output). - -@param [in] u8GpioNum - GPIO number. Allowed values are defined in tenuGpioNum. - -@param [in] u8GpioDir - GPIO direction: Zero = input. Non-zero = output. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuGpioNum -*/ -NMI_API sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir); - -/*! -@fn \ - NMI_API sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal); - -@brief - Set an NMC1500 GPIO output level high or low. - -@param [in] u8GpioNum - GPIO number. Allowed values are defined in tenuGpioNum. - -@param [in] u8GpioVal - GPIO output value. Zero = low, non-zero = high. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuGpioNum -*/ -NMI_API sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal); - -/*! -@fn \ - NMI_API sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal); - -@brief - Read an NMC1500 GPIO input level. - -@param [in] u8GpioNum - GPIO number. Allowed values are defined in tenuGpioNum. - -@param [out] pu8GpioVal - GPIO input value. Zero = low, non-zero = high. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuGpioNum -*/ -NMI_API sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal); - -/*! -@fn \ - NMI_API sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn); - -@brief - Set an NMC1500 GPIO pullup resisitor enable or disable. - -@param [in] u8GpioNum - GPIO number. Allowed values are defined in tenuGpioNum. - -@param [in] u8PullupEn - Zero: pullup disabled. Non-zero: pullup enabled. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuGpioNum -*/ -NMI_API sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn); - -/*! -@fn \ - NMI_API sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param); - -@brief - Initialize and configure the NMC1500 I2C master peripheral. - -@param [in] param - I2C master initialization structure. See members of tstrI2cMasterInitParam. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tstrI2cMasterInitParam -*/ -NMI_API sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param); - -/*! -@fn \ - NMI_API sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags); - -@brief - Write a stream of bytes to the I2C slave device. - -@param [in] u8SlaveAddr - 7-bit I2C slave address. -@param [in] pu8Buf - A pointer to an input buffer which contains a stream of bytes. -@param [in] u16BufLen - Input buffer length in bytes. -@param [in] flags - Write operation bitwise-ORed flags. See tenuI2cMasterFlags. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuI2cMasterFlags -*/ -NMI_API sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags); - - -/*! -@fn \ - NMI_API sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags); - -@brief - Write a stream of bytes to the I2C slave device. - -@param [in] u8SlaveAddr - 7-bit I2C slave address. -@param [out] pu8Buf - A pointer to an output buffer in which a stream of bytes are received. -@param [in] u16BufLen - Max output buffer length in bytes. -@param [out] pu16ReadLen - Actual number of bytes received. -@param [in] flags - Write operation bitwise-ORed flags. See tenuI2cMasterFlags. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuI2cMasterFlags -*/ -NMI_API sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags); - - -/*! -@fn \ - NMI_API sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable); - -@brief - Control the programmable pull-up resistor on the chip pads . - - -@param [in] pinmask - Write operation bitwise-ORed mask for which pads to control. Allowed values are defined in tenuPullupMask. - -@param [in] enable - Set to 0 to disable pull-up resistor. Non-zero will enable the pull-up. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -@sa - tenuPullupMask -*/ -NMI_API sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable); - -#ifdef __cplusplus -} -#endif - - -#endif /* _M2M_PERIPH_H_ */ \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_ssl.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_ssl.h deleted file mode 100644 index f5271f0..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_ssl.h +++ /dev/null @@ -1,182 +0,0 @@ -/** - * - * \file - * - * \brief WINC Application Interface Internal Types. - * - * Copyright (c) 2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/**@defgroup SSLAPI SSL -*/ - -#ifndef __M2M_SSL_H__ -#define __M2M_SSL_H__ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "common/include/nm_common.h" -#include "driver/include/m2m_types.h" -#include "driver/source/nmdrv.h" -#include "ecc_types.h" -#include "socket/include/socket.h" - -/**@defgroup SSLEnums Enumeration/Typedefs - * @ingroup SSLAPI - * @{*/ - -/*! -@typedef \ - void (*tpfAppSslCb) (uint8 u8MsgType, void * pvMsg); - -@brief A callback to get SSL notifications. - -@param[in] u8MsgType -@param[in] pvMsg A structure to provide notification payload. -*/ -typedef void (*tpfAppSSLCb) (uint8 u8MsgType, void * pvMsg); - -/**@} -*/ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/** \defgroup SSLFUNCTIONS Functions -* @ingroup SSLAPI -*/ - -/**@{*/ -/*! - @fn \ m2m_ssl_init(tpfAppSslCb pfAppSslCb); - @brief Initializes the SSL layer. - @param [in] pfAppSslCb - Application SSL callback function. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_init(tpfAppSSLCb pfAppSSLCb); - -/*! - @fn \ NMI_API sint8 m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz) - @brief Sends ECC responses to the WINC - @param [in] strECCResp - ECC Response struct. - @param [in] pu8RspDataBuffe - Pointer of the response data to be sent. - @param [in] u16RspDataSz - Response data size. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz); - -/*! - @fn \ NMI_API sint8 m2m_ssl_send_certs_to_winc(uint8* pu8Buffer, uint32 u32BufferSz) - @brief Sends certificates to the WINC - @param [in] pu8Buffer - Pointer to the certificates. - @param [in] u32BufferSz - Size of the certificates. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_send_certs_to_winc(uint8* pu8Buffer, uint32 u32BufferSz); - -/*! - @fn \ NMI_API sint8 m2m_ssl_retrieve_cert(uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key) - @brief Retrieve the certificate to be verified from the WINC - @param [in] pu16CurveType - Pointer to the certificate curve type. - @param [in] pu8Hash - Pointer to the certificate hash. - @param [in] pu8Sig - Pointer to the certificate signature. - @param [in] pu8Key - Pointer to the certificate Key. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_retrieve_cert(uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key); - -/*! - @fn \ NMI_API sint8 m2m_ssl_retrieve_hash(uint8* pu8Hash, uint16 u16HashSz) - @brief Retrieve the certificate hash - @param [in] pu8Hash - Pointer to the certificate hash. - @param [in] u16HashSz - Hash size. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_retrieve_hash(uint8* pu8Hash, uint16 u16HashSz); - -/*! - @fn \ NMI_API void m2m_ssl_stop_processing_certs(void) - @brief Allow ssl driver to tidy up in case application does not read all available certificates. - @warning This API must only be called if some certificates are left unread. - @return None. -*/ -NMI_API void m2m_ssl_stop_processing_certs(void); - -/*! - @fn \ NMI_API void m2m_ssl_ecc_process_done(void) - @brief Allow ssl driver to tidy up after application has finished processing ecc message. - @warning This API must be called after receiving a SSL callback with type @ref M2M_SSL_REQ_ECC - @return None. -*/ -NMI_API void m2m_ssl_ecc_process_done(void); - -/*! -@fn \ - NMI_API sint8 m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP); - Override the default Active SSL ciphers in the SSL module with a certain combination selected by the caller in the form of - a bitmap containing the required ciphers to be on. - There is no need to call this function if the application will not change the default ciphersuites. - -@param [in] u32SslCsBMP - Bitmap containing the desired ciphers to be enabled for the SSL module. The ciphersuites are defined in - @ref SSLCipherSuiteID. - The default ciphersuites are all ciphersuites supported by the firmware with the exception of ECC ciphersuites. - The caller can override the default with any desired combination, except for combinations involving both RSA - and ECC; if any RSA ciphersuite is enabled, then firmware will disable all ECC ciphersuites. - If u32SslCsBMP does not contain any ciphersuites supported by firmware, then the current active list will not - be changed. - -@return - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) -*/ -sint8 m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP); - - /**@}*/ -#endif /* __M2M_SSL_H__ */ \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_types.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_types.h deleted file mode 100644 index a847f3f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_types.h +++ /dev/null @@ -1,2383 +0,0 @@ -/** - * - * \file - * - * \brief WINC Application Interface Internal Types. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef __M2M_WIFI_TYPES_H__ -#define __M2M_WIFI_TYPES_H__ - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#ifndef _BOOT_ -#ifndef _FIRMWARE_ -#include "common/include/nm_common.h" -#else -#include "m2m_common.h" -#endif -#endif - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/**@defgroup WlanDefines Defines - * @ingroup m2m_wifi - */ -/**@{*/ -#define M2M_MAJOR_SHIFT (8) -#define M2M_MINOR_SHIFT (4) -#define M2M_PATCH_SHIFT (0) - -#define M2M_DRV_VERSION_SHIFT (16) -#define M2M_FW_VERSION_SHIFT (0) - -#define M2M_GET_MAJOR(ver_info_hword) ((uint8)((ver_info_hword) >> M2M_MAJOR_SHIFT) & 0xff) -#define M2M_GET_MINOR(ver_info_hword) ((uint8)((ver_info_hword) >> M2M_MINOR_SHIFT) & 0x0f) -#define M2M_GET_PATCH(ver_info_hword) ((uint8)((ver_info_hword) >> M2M_PATCH_SHIFT) & 0x0f) - -#define M2M_GET_FW_VER(ver_info_word) ((uint16) ((ver_info_word) >> M2M_FW_VERSION_SHIFT)) -#define M2M_GET_DRV_VER(ver_info_word) ((uint16) ((ver_info_word) >> M2M_DRV_VERSION_SHIFT)) - -#define M2M_GET_DRV_MAJOR(ver_info_word) M2M_GET_MAJOR(M2M_GET_DRV_VER(ver_info_word)) -#define M2M_GET_DRV_MINOR(ver_info_word) M2M_GET_MINOR(M2M_GET_DRV_VER(ver_info_word)) -#define M2M_GET_DRV_PATCH(ver_info_word) M2M_GET_PATCH(M2M_GET_DRV_VER(ver_info_word)) - -#define M2M_GET_FW_MAJOR(ver_info_word) M2M_GET_MAJOR(M2M_GET_FW_VER(ver_info_word)) -#define M2M_GET_FW_MINOR(ver_info_word) M2M_GET_MINOR(M2M_GET_FW_VER(ver_info_word)) -#define M2M_GET_FW_PATCH(ver_info_word) M2M_GET_PATCH(M2M_GET_FW_VER(ver_info_word)) - -#define M2M_MAKE_VERSION(major, minor, patch) ( \ - ((uint16)((major) & 0xff) << M2M_MAJOR_SHIFT) | \ - ((uint16)((minor) & 0x0f) << M2M_MINOR_SHIFT) | \ - ((uint16)((patch) & 0x0f) << M2M_PATCH_SHIFT)) - -#define M2M_MAKE_VERSION_INFO(fw_major, fw_minor, fw_patch, drv_major, drv_minor, drv_patch) \ - ( \ - ( ((uint32)M2M_MAKE_VERSION((fw_major), (fw_minor), (fw_patch))) << M2M_FW_VERSION_SHIFT) | \ - ( ((uint32)M2M_MAKE_VERSION((drv_major), (drv_minor), (drv_patch))) << M2M_DRV_VERSION_SHIFT)) - -#define REL_19_5_2_VER M2M_MAKE_VERSION_INFO(19,5,2,19,3,0) -#define REL_19_5_1_VER M2M_MAKE_VERSION_INFO(19,5,1,19,3,0) -#define REL_19_5_0_VER M2M_MAKE_VERSION_INFO(19,5,0,19,3,0) -#define REL_19_4_6_VER M2M_MAKE_VERSION_INFO(19,4,6,19,3,0) -#define REL_19_4_5_VER M2M_MAKE_VERSION_INFO(19,4,5,19,3,0) -#define REL_19_4_4_VER M2M_MAKE_VERSION_INFO(19,4,4,19,3,0) -#define REL_19_4_3_VER M2M_MAKE_VERSION_INFO(19,4,3,19,3,0) -#define REL_19_4_2_VER M2M_MAKE_VERSION_INFO(19,4,2,19,3,0) -#define REL_19_4_1_VER M2M_MAKE_VERSION_INFO(19,4,1,19,3,0) -#define REL_19_4_0_VER M2M_MAKE_VERSION_INFO(19,4,0,19,3,0) -#define REL_19_3_1_VER M2M_MAKE_VERSION_INFO(19,3,1,19,3,0) -#define REL_19_3_0_VER M2M_MAKE_VERSION_INFO(19,3,0,19,3,0) -#define REL_19_2_2_VER M2M_MAKE_VERSION_INFO(19,2,2,19,2,0) -#define REL_19_2_1_VER M2M_MAKE_VERSION_INFO(19,2,1,19,2,0) -#define REL_19_2_0_VER M2M_MAKE_VERSION_INFO(19,2,0,19,2,0) -#define REL_19_1_0_VER M2M_MAKE_VERSION_INFO(19,1,0,18,2,0) -#define REL_19_0_0_VER M2M_MAKE_VERSION_INFO(19,0,0,18,1,1) - -/*======*======*======*======* - FIRMWARE VERSION NO INFO - *======*======*======*======*/ - -#define M2M_RELEASE_VERSION_MAJOR_NO (19) -/*!< Firmware Major release version number. -*/ - - -#define M2M_RELEASE_VERSION_MINOR_NO (5) -/*!< Firmware Minor release version number. -*/ - -#define M2M_RELEASE_VERSION_PATCH_NO (2) -/*!< Firmware patch release version number. -*/ - -/*======*======*======*======* - SUPPORTED DRIVER VERSION NO INFO - *======*======*======*======*/ - -#define M2M_MIN_REQ_DRV_VERSION_MAJOR_NO (19) -/*!< Driver Major release version number. -*/ - - -#define M2M_MIN_REQ_DRV_VERSION_MINOR_NO (3) -/*!< Driver Minor release version number. -*/ - -#define M2M_MIN_REQ_DRV_VERSION_PATCH_NO (0) -/*!< Driver patch release version number. -*/ - -#define M2M_MIN_REQ_DRV_SVN_VERSION (0) -/*!< Driver svn version. -*/ - - - -#if !defined(M2M_RELEASE_VERSION_MAJOR_NO) || !defined(M2M_RELEASE_VERSION_MINOR_NO) -#error Undefined version number -#endif - -#define M2M_BUFFER_MAX_SIZE (1600UL - 4) -/*!< Maximum size for the shared packet buffer. - */ - - -#define M2M_MAC_ADDRES_LEN 6 -/*!< The size fo 802 MAC address. - */ - -#define M2M_ETHERNET_HDR_OFFSET 34 -/*!< The offset of the Ethernet header within the WLAN Tx Buffer. - */ - - -#define M2M_ETHERNET_HDR_LEN 14 -/*!< Length of the Etherenet header in bytes. -*/ - - -#define M2M_MAX_SSID_LEN 33 -/*!< Maximum size for the Wi-Fi SSID including the NULL termination. - */ - - -#define M2M_MAX_PSK_LEN 65 -/*!< Maximum size for the WPA PSK including the NULL termination. - */ - -#define M2M_MIN_PSK_LEN 9 -/*!< Maximum size for the WPA PSK including the NULL termination. - */ - -#define M2M_DEVICE_NAME_MAX 48 -/*!< Maximum Size for the device name including the NULL termination. - */ - - -#define M2M_LISTEN_INTERVAL 1 -/*!< The STA uses the Listen Interval parameter to indicate to the AP how - many beacon intervals it shall sleep before it retrieves the queued frames - from the AP. -*/ - -#define MAX_HIDDEN_SITES 4 -/*!< - max number of hidden SSID suuported by scan request -*/ - - -#define M2M_1X_USR_NAME_MAX 21 -/*!< The maximum size of the user name including the NULL termination. - It is used for RADIUS authentication in case of connecting the device to - an AP secured with WPA-Enterprise. -*/ - - -#define M2M_1X_PWD_MAX 41 -/*!< The maximum size of the password including the NULL termination. - It is used for RADIUS authentication in case of connecting the device to - an AP secured with WPA-Enterprise. -*/ - -#define M2M_CUST_IE_LEN_MAX 252 -/*!< The maximum size of IE (Information Element). -*/ - -#define PWR_DEFAULT PWR_HIGH -/********************* - * - * WIFI GROUP requests - */ - -#define M2M_CONFIG_CMD_BASE 1 -/*!< The base value of all the host configuration commands opcodes. -*/ -#define M2M_STA_CMD_BASE 40 -/*!< The base value of all the station mode host commands opcodes. -*/ -#define M2M_AP_CMD_BASE 70 -/*!< The base value of all the Access Point mode host commands opcodes. -*/ -#define M2M_P2P_CMD_BASE 90 -/*!< The base value of all the P2P mode host commands opcodes. -*/ -#define M2M_SERVER_CMD_BASE 100 -/*!< The base value of all the power save mode host commands codes. -*/ -/********************** - * OTA GROUP requests - */ -#define M2M_OTA_CMD_BASE 100 -/*!< The base value of all the OTA mode host commands opcodes. - * The OTA Have special group so can extended from 1-M2M_MAX_GRP_NUM_REQ -*/ -/*********************** - * - * CRYPTO group requests - */ -#define M2M_CRYPTO_CMD_BASE 1 -/*!< The base value of all the crypto mode host commands opcodes. - * The crypto Have special group so can extended from 1-M2M_MAX_GRP_NUM_REQ -*/ - -#define M2M_MAX_GRP_NUM_REQ (127) -/*!< max number of request in one group equal to 127 as the last bit reserved for config or data pkt -*/ - -#define WEP_40_KEY_STRING_SIZE ((uint8)10) -/*!< Indicate the wep key size in bytes for 40 bit string passphrase. -*/ - -#define WEP_104_KEY_STRING_SIZE ((uint8)26) -/*!< Indicate the wep key size in bytes for 104 bit string passphrase. -*/ -#define WEP_KEY_MAX_INDEX ((uint8)4) -/*!< Indicate the max key index value for WEP authentication -*/ -#define M2M_SHA256_CONTEXT_BUFF_LEN (128) -/*!< sha256 context size -*/ -#define M2M_SCAN_DEFAULT_NUM_SLOTS (2) -/*!< The default. number of scan slots performed by the WINC board. -*/ -#define M2M_SCAN_DEFAULT_SLOT_TIME (30) -/*!< The default. duration in miliseconds of a scan slots performed by the WINC board. -*/ -#define M2M_SCAN_DEFAULT_NUM_PROBE (2) -/*!< The default. number of scan slots performed by the WINC board. -*/ - - -/*======*======*======*======* - CONNECTION ERROR DEFINITIONS - *======*======*======*======*/ -typedef enum { - M2M_DEFAULT_CONN_INPROGRESS = ((sint8)-23), - /*!< - A failure that indicates that a default connection or forced connection is in progress - */ - M2M_DEFAULT_CONN_FAIL, - /*!< - A failure response that indicates that the winc failed to connect to the cached network - */ - M2M_DEFAULT_CONN_SCAN_MISMATCH, - /*!< - A failure response that indicates that no one of the cached networks - was found in the scan results, as a result to the function call m2m_default_connect. - */ - M2M_DEFAULT_CONN_EMPTY_LIST - /*!< - A failure response that indicates an empty network list as - a result to the function call m2m_default_connect. - */ - -}tenuM2mDefaultConnErrcode; - - - -/*======*======*======*======* - TLS DEFINITIONS - *======*======*======*======*/ -#define TLS_FILE_NAME_MAX 48 -/*!< Maximum length for each TLS certificate file name including null terminator. -*/ -#define TLS_SRV_SEC_MAX_FILES 8 -/*!< Maximum number of certificates allowed in TLS_SRV section. -*/ -#define TLS_SRV_SEC_START_PATTERN_LEN 8 -/*!< Length of certificate struct start pattern. -*/ -/*======*======*======*======* - OTA DEFINITIONS - *======*======*======*======*/ - -#define OTA_STATUS_VALID (0x12526285) -/*!< - Magic value updated in the Control structure in case of ROLLACK image Valid -*/ -#define OTA_STATUS_INVALID (0x23987718) -/*!< - Magic value updated in the Control structure in case of ROLLACK image InValid -*/ -#define OTA_MAGIC_VALUE (0x1ABCDEF9) -/*!< - Magic value set at the beginning of the OTA image header -*/ -#define M2M_MAGIC_APP (0xef522f61UL) -/*!< - Magic value set at the beginning of the Cortus OTA image header -*/ - -#define OTA_FORMAT_VER_0 (0) /*Till 19.2.2 format*/ -#define OTA_FORMAT_VER_1 (1) /*starting from 19.3.0 CRC is used and sequence number is used*/ -/*!< - Control structure format version -*/ -#define OTA_SHA256_DIGEST_SIZE (32) -/*!< - Sha256 digest size in the OTA image, - the sha256 digest is set at the beginning of image before the OTA header - */ - -/*======*======*======*======* - SSL DEFINITIONS - *======*======*======*======*/ - -#define TLS_CRL_DATA_MAX_LEN 64 -/* Every bit have 3dB gain control each. - for example: - 1 ->3db - 3 ->6db - 7 ->9db - */ - uint16 u8PPAGFor11GN; - /*!< PPA gain for 11GN (as the RF document represented) - PPA_AGC<0:2> Every bit have 3dB gain control each. - for example: - 1 ->3db - 3 ->6db - 7 ->9db - */ -}tstrM2mWifiGainsParams; - -/*! -@struct \ - tstrM2mWifiWepParams - -@brief - WEP security key parameters. -*/ -typedef struct{ - uint8 u8KeyIndx; - /*!< Wep key Index. - */ - uint8 u8KeySz; - /*!< Wep key Size. - */ - uint8 au8WepKey[WEP_104_KEY_STRING_SIZE + 1]; - /*!< WEP Key represented as a NULL terminated ASCII string. - */ - uint8 __PAD24__[3]; - /*!< Padding bytes to keep the structure word alligned. - */ -}tstrM2mWifiWepParams; - - -/*! -@struct \ - tstr1xAuthCredentials - -@brief - Credentials for the user to authenticate with the AAA server (WPA-Enterprise Mode IEEE802.1x). -*/ -typedef struct{ - uint8 au8UserName[M2M_1X_USR_NAME_MAX]; - /*!< User Name. It must be Null terminated string. - */ - uint8 au8Passwd[M2M_1X_PWD_MAX]; - /*!< Password corresponding to the user name. It must be Null terminated string. - */ -}tstr1xAuthCredentials; - - -/*! -@union \ - tuniM2MWifiAuth - -@brief - Wi-Fi Security Parameters for all supported security modes. -*/ -typedef union{ - uint8 au8PSK[M2M_MAX_PSK_LEN]; - /*!< Pre-Shared Key in case of WPA-Personal security. - */ - tstr1xAuthCredentials strCred1x; - /*!< Credentials for RADIUS server authentication in case of WPA-Enterprise security. - */ - tstrM2mWifiWepParams strWepInfo; - /*!< WEP key parameters in case of WEP security. - */ -}tuniM2MWifiAuth; - - -/*! -@struct \ - tstrM2MWifiSecInfo - -@brief - Authentication credentials to connect to a Wi-Fi network. -*/ -typedef struct{ - tuniM2MWifiAuth uniAuth; - /*!< Union holding all possible authentication parameters corresponding the current security types. - */ - uint8 u8SecType; - /*!< Wi-Fi network security type. See tenuM2mSecType for supported security types. - */ -#define __PADDING__ (4 - ((sizeof(tuniM2MWifiAuth) + 1) % 4)) - uint8 __PAD__[__PADDING__]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2MWifiSecInfo; - - -/*! -@struct \ - tstrM2mWifiConnect - -@brief - Wi-Fi Connect Request -*/ -typedef struct{ - tstrM2MWifiSecInfo strSec; - /*!< Security parameters for authenticating with the AP. - */ - uint16 u16Ch; - /*!< RF Channel for the target SSID. - */ - uint8 au8SSID[M2M_MAX_SSID_LEN]; - /*!< SSID of the desired AP. It must be NULL terminated string. - */ - uint8 u8NoSaveCred; -#define __CONN_PAD_SIZE__ (4 - ((sizeof(tstrM2MWifiSecInfo) + M2M_MAX_SSID_LEN + 3) % 4)) - uint8 __PAD__[__CONN_PAD_SIZE__]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mWifiConnect; - - -/*! -@struct \ - tstrM2MWPSConnect - -@brief - WPS Configuration parameters - -@sa - tenuWPSTrigger -*/ -typedef struct { - uint8 u8TriggerType; - /*!< WPS triggering method (Push button or PIN) - */ - char acPinNumber[8]; - /*!< WPS PIN No (for PIN method) - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2MWPSConnect; - - -/*! -@struct \ - tstrM2MWPSInfo - -@brief WPS Result - - This structure is passed to the application in response to a WPS request. If the WPS session is completed successfully, the - structure will have Non-ZERO authentication type. If the WPS Session fails (due to error or timeout) the authentication type - is set to ZERO. - -@sa - tenuM2mSecType -*/ -typedef struct{ - uint8 u8AuthType; - /*!< Network authentication type. - */ - uint8 u8Ch; - /*!< RF Channel for the AP. - */ - uint8 au8SSID[M2M_MAX_SSID_LEN]; - /*!< SSID obtained from WPS. - */ - uint8 au8PSK[M2M_MAX_PSK_LEN]; - /*!< PSK for the network obtained from WPS. - */ -}tstrM2MWPSInfo; - - -/*! -@struct \ - tstrM2MDefaultConnResp - -@brief - Response error of the m2m_default_connect - -@sa - M2M_DEFAULT_CONN_SCAN_MISMATCH - M2M_DEFAULT_CONN_EMPTY_LIST -*/ -typedef struct{ - sint8 s8ErrorCode; - /*!< - Default connect error code. possible values are: - - M2M_DEFAULT_CONN_EMPTY_LIST - - M2M_DEFAULT_CONN_SCAN_MISMATCH - */ - uint8 __PAD24__[3]; -}tstrM2MDefaultConnResp; - -/*! -@struct \ - tstrM2MScanOption - -@brief - Scan options and configurations. - -@sa - tenuM2mScanCh - tstrM2MScan -*/ -typedef struct { - uint8 u8NumOfSlot; - /*|< The min number of slots is 2 for every channel, - every slot the soc will send Probe Request on air, and wait/listen for PROBE RESP/BEACONS for the u16slotTime - */ - uint8 u8SlotTime; - /*|< the time that the Soc will wait on every channel listening to the frames on air - when that time increaseed number of AP will increased in the scan results - min time is 10 ms and the max is 250 ms - */ - uint8 u8ProbesPerSlot; - /*!< Number of probe requests to be sent per channel scan slot. - */ - sint8 s8RssiThresh; - /*! < The RSSI threshold of the AP which will be connected to directly. - */ - -}tstrM2MScanOption; - -/*! -@struct \ - tstrM2MScanRegion - -@brief - Wi-Fi channel regulation region information. - -@sa - tenuM2mScanRegion -*/ -typedef struct { - uint16 u16ScanRegion; - /*|< Specifies the number of channels allowed in the region (e.g. North America = 11 ... etc.). - */ - uint8 __PAD16__[2]; - -}tstrM2MScanRegion; - -/*! -@struct \ - tstrM2MScan - -@brief - Wi-Fi Scan Request - -@sa - tenuM2mScanCh - tstrM2MScanOption -*/ -typedef struct { - uint8 u8ChNum; - /*!< The Wi-Fi RF Channel number - */ - uint8 __RSVD8__[1]; - /*!< Reserved for future use. - */ - uint16 u16PassiveScanTime; - /*!< Passive Scan Timeout in ms. The field is ignored for active scan. - */ -}tstrM2MScan; - -/*! -@struct \ - tstrCyptoResp - -@brief - crypto response -*/ -typedef struct { - sint8 s8Resp; - /***/ - uint8 __PAD24__[3]; - /* - */ -}tstrCyptoResp; - - -/*! -@struct \ - tstrM2mScanDone - -@brief - Wi-Fi Scan Result -*/ -typedef struct{ - uint8 u8NumofCh; - /*!< Number of found APs - */ - sint8 s8ScanState; - /*!< Scan status - */ - uint8 __PAD16__[2]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mScanDone; - - -/*! -@struct \ - tstrM2mReqScanResult - -@brief Scan Result Request - - The Wi-Fi Scan results list is stored in Firmware. The application can request a certain scan result by its index. -*/ -typedef struct { - uint8 u8Index; - /*!< Index of the desired scan result - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mReqScanResult; - - -/*! -@struct \ - tstrM2mWifiscanResult - -@brief Wi-Fi Scan Result - - Information corresponding to an AP in the Scan Result list identified by its order (index) in the list. -*/ -typedef struct { - uint8 u8index; - /*!< AP index in the scan result list. - */ - sint8 s8rssi; - /*!< AP signal strength. - */ - uint8 u8AuthType; - /*!< AP authentication type. - */ - uint8 u8ch; - /*!< AP RF channel. - */ - uint8 au8BSSID[6]; - /*!< BSSID of the AP. - */ - uint8 au8SSID[M2M_MAX_SSID_LEN]; - /*!< AP ssid. - */ - uint8 _PAD8_; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mWifiscanResult; - - -/*! -@struct \ - tstrM2mWifiStateChanged - -@brief - Wi-Fi Connection State - -@sa - M2M_WIFI_DISCONNECTED, M2M_WIFI_CONNECTED, M2M_WIFI_REQ_CON_STATE_CHANGED,tenuM2mConnChangedErrcode -*/ -typedef struct { - uint8 u8CurrState; - /*!< Current Wi-Fi connection state - */ - uint8 u8ErrCode; - /*!< Error type review tenuM2mConnChangedErrcode - */ - uint8 __PAD16__[2]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mWifiStateChanged; - - -/*! -@struct \ - tstrM2mPsType - -@brief - Power Save Configuration - -@sa - tenuPowerSaveModes -*/ -typedef struct{ - uint8 u8PsType; - /*!< Power save operating mode - */ - uint8 u8BcastEn; - /*!< - */ - uint8 __PAD16__[2]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mPsType; - -/*! -@struct \ - tstrM2mSlpReqTime - -@brief - Manual power save request sleep time - -*/ -typedef struct { - /*!< Sleep time in ms - */ - uint32 u32SleepTime; - -} tstrM2mSlpReqTime; - -/*! -@struct \ - tstrM2mLsnInt - -@brief Listen interval - - It is the value of the Wi-Fi STA listen interval for power saving. It is given in units of Beacon period. - Periodically after the listen interval fires, the WINC is wakeup and listen to the beacon and check for any buffered frames for it from the AP. -*/ -typedef struct { - uint16 u16LsnInt; - /*!< Listen interval in Beacon period count. - */ - uint8 __PAD16__[2]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mLsnInt; - - -/*! -@struct \ - tstrM2MWifiMonitorModeCtrl - -@brief Wi-Fi Monitor Mode Filter - - This structure sets the filtering criteria for WLAN packets when monitoring mode is enable. - The received packets matching the filtering parameters, are passed directly to the application. -*/ -typedef struct{ - uint8 u8ChannelID; - /* !< RF Channel ID. It must use values from tenuM2mScanCh - */ - uint8 u8FrameType; - /*!< It must use values from tenuWifiFrameType. - */ - uint8 u8FrameSubtype; - /*!< It must use values from tenuSubTypes. - */ - uint8 au8SrcMacAddress[6]; - /* ZERO means DO NOT FILTER Source address. - */ - uint8 au8DstMacAddress[6]; - /* ZERO means DO NOT FILTER Destination address. - */ - uint8 au8BSSID[6]; - /* ZERO means DO NOT FILTER BSSID. - */ - uint8 u8EnRecvHdr; - /* - Enable recv the full hder before the payload - */ - uint8 __PAD16__[2]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2MWifiMonitorModeCtrl; - - -/*! -@struct \ - tstrM2MWifiRxPacketInfo - -@brief Wi-Fi RX Frame Header - - The M2M application has the ability to allow Wi-Fi monitoring mode for receiving all Wi-Fi Raw frames matching a well defined filtering criteria. - When a target Wi-Fi packet is received, the header information are extracted and assigned in this structure. -*/ -typedef struct{ - uint8 u8FrameType; - /*!< It must use values from tenuWifiFrameType. - */ - uint8 u8FrameSubtype; - /*!< It must use values from tenuSubTypes. - */ - uint8 u8ServiceClass; - /*!< Service class from Wi-Fi header. - */ - uint8 u8Priority; - /*!< Priority from Wi-Fi header. - */ - uint8 u8HeaderLength; - /*!< Frame Header length. - */ - uint8 u8CipherType; - /*!< Encryption type for the rx packet. - */ - uint8 au8SrcMacAddress[6]; - /* ZERO means DO NOT FILTER Source address. - */ - uint8 au8DstMacAddress[6]; - /* ZERO means DO NOT FILTER Destination address. - */ - uint8 au8BSSID[6]; - /* ZERO means DO NOT FILTER BSSID. - */ - uint16 u16DataLength; - /*!< Data payload length (Header excluded). - */ - uint16 u16FrameLength; - /*!< Total frame length (Header + Data). - */ - uint32 u32DataRateKbps; - /*!< Data Rate in Kbps. - */ - sint8 s8RSSI; - /*!< RSSI. - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2MWifiRxPacketInfo; - - -/*! -@struct \ - tstrM2MWifiTxPacketInfo - -@brief Wi-Fi TX Packet Info - - The M2M Application has the ability to compose a RAW Wi-Fi frames (under the application responsibility). - When transmitting a Wi-Fi packet, the application must supply the firmware with this structure for sending the target frame. -*/ -typedef struct{ - uint16 u16PacketSize; - /*!< Wlan frame length. - */ - uint16 u16HeaderLength; - /*!< Wlan frame header length. - */ -}tstrM2MWifiTxPacketInfo; - - -/*! - @struct \ - tstrM2MP2PConnect - - @brief - Set the device to operate in the Wi-Fi Direct (P2P) mode. -*/ -typedef struct { - uint8 u8ListenChannel; - /*!< P2P Listen Channel (1, 6 or 11) - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2MP2PConnect; - -/*! -@struct \ - tstrM2MAPConfig - -@brief AP Configuration - - This structure holds the configuration parameters for the M2M AP mode. It should be set by the application when - it requests to enable the M2M AP operation mode. The M2M AP mode currently supports only WEP security (with - the NO Security option available of course). -*/ -typedef struct { - /*!< - Configuration parameters for the WiFi AP. - */ - uint8 au8SSID[M2M_MAX_SSID_LEN]; - /*!< AP SSID - */ - uint8 u8ListenChannel; - /*!< Wi-Fi RF Channel which the AP will operate on - */ - uint8 u8KeyIndx; - /*!< Wep key Index - */ - uint8 u8KeySz; - /*!< Wep/WPA key Size - */ - uint8 au8WepKey[WEP_104_KEY_STRING_SIZE + 1]; - /*!< Wep key - */ - uint8 u8SecType; - /*!< Security type: Open or WEP or WPA in the current implementation - */ - uint8 u8SsidHide; - /*!< SSID Status "Hidden(1)/Visible(0)" - */ - uint8 au8DHCPServerIP[4]; - /*!< Ap IP server address - */ - uint8 au8Key[M2M_MAX_PSK_LEN]; - /*!< WPA key - */ - uint8 __PAD24__[2]; - /*!< Padding bytes for forcing alignment - */ -}tstrM2MAPConfig; - - -/*! -@struct \ - tstrM2mServerInit - -@brief - PS Server initialization. -*/ -typedef struct { - uint8 u8Channel; - /*!< Server Listen channel - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mServerInit; - - -/*! -@struct \ - tstrM2mClientState - -@brief - PS Client State. -*/ -typedef struct { - uint8 u8State; - /*!< PS Client State - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mClientState; - - -/*! -@struct \ - tstrM2Mservercmd - -@brief - PS Server CMD -*/ -typedef struct { - uint8 u8cmd; - /*!< PS Server Cmd - */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2Mservercmd; - - -/*! -@struct \ - tstrM2mSetMacAddress - -@brief - Sets the MAC address from application. The WINC load the mac address from the effuse by default to the WINC configuration memory, - but that function is used to let the application overwrite the configuration memory with the mac address from the host. - -@note - It's recommended to call this only once before calling connect request and after the m2m_wifi_init -*/ -typedef struct { - uint8 au8Mac[6]; - /*!< MAC address array - */ - uint8 __PAD16__[2]; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2mSetMacAddress; - - -/*! -@struct \ - tstrM2MDeviceNameConfig - -@brief Device name - - It is assigned by the application. It is used mainly for Wi-Fi Direct device - discovery and WPS device information. -*/ -typedef struct { - uint8 au8DeviceName[M2M_DEVICE_NAME_MAX]; - /*!< NULL terminated device name - */ -}tstrM2MDeviceNameConfig; - - -/*! -@struct \ - tstrM2MIPConfig - -@brief - Static IP configuration. - -@note - All member IP addresses are expressed in Network Byte Order (eg. "192.168.10.1" will be expressed as 0x010AA8C0). - */ -typedef struct { - uint32 u32StaticIP; - /*!< The static IP assigned to the device. - */ - uint32 u32Gateway; - /*!< IP of the Default internet gateway. - */ - uint32 u32DNS; - /*!< IP for the DNS server. - */ - uint32 u32SubnetMask; - /*!< Subnet mask for the local area network. - */ - uint32 u32DhcpLeaseTime; - /*!< Dhcp Lease Time in sec - */ -} tstrM2MIPConfig; - -/*! -@struct \ - tstrM2mIpRsvdPkt - -@brief - Received Packet Size and Data Offset - - */ -typedef struct{ - uint16 u16PktSz; - uint16 u16PktOffset; -} tstrM2mIpRsvdPkt; - - -/*! -@struct \ - tstrM2MProvisionModeConfig - -@brief - M2M Provisioning Mode Configuration - */ - -typedef struct { - tstrM2MAPConfig strApConfig; - /*!< - Configuration parameters for the WiFi AP. - */ - char acHttpServerDomainName[64]; - /*!< - The device domain name for HTTP provisioning. - */ - uint8 u8EnableRedirect; - /*!< - A flag to enable/disable HTTP redirect feature for the HTTP Provisioning server. If the Redirect is enabled, - all HTTP traffic (http://URL) from the device associated with WINC AP will be redirected to the HTTP Provisioning Web page. - - 0 : Disable HTTP Redirect. - - 1 : Enable HTTP Redirect. - */ - uint8 __PAD24__[3]; -}tstrM2MProvisionModeConfig; - - -/*! -@struct \ - tstrM2MProvisionInfo - -@brief - M2M Provisioning Information obtained from the HTTP Provisioning server. - */ -typedef struct{ - uint8 au8SSID[M2M_MAX_SSID_LEN]; - /*!< - Provisioned SSID. - */ - uint8 au8Password[M2M_MAX_PSK_LEN]; - /*!< - Provisioned Password. - */ - uint8 u8SecType; - /*!< - Wifi Security type. - */ - uint8 u8Status; - /*!< - Provisioning status. It must be checked before reading the provisioning information. It may be - - M2M_SUCCESS : Provision successful. - - M2M_FAIL : Provision Failed. - */ -}tstrM2MProvisionInfo; - - -/*! -@struct \ - tstrM2MConnInfo - -@brief - M2M Provisioning Information obtained from the HTTP Provisioning server. - */ -typedef struct{ - char acSSID[M2M_MAX_SSID_LEN]; - /*!< AP connection SSID name */ - uint8 u8SecType; - /*!< Security type */ - uint8 au8IPAddr[4]; - /*!< Connection IP address */ - uint8 au8MACAddress[6]; - /*!< MAC address of the peer Wi-Fi station */ - sint8 s8RSSI; - /*!< Connection RSSI signal */ - uint8 __PAD24__[3]; - /*!< Padding bytes for forcing 4-byte alignment */ -}tstrM2MConnInfo; - -/*! -@struct \ - tstrOtaInitHdr - -@brief - OTA Image Header - */ - -typedef struct{ - uint32 u32OtaMagicValue; - /*!< Magic value kept in the OTA image after the - sha256 Digest buffer to define the Start of OTA Header */ - uint32 u32OtaPayloadSzie; - /*!< - The Total OTA image payload size, include the sha256 key size - */ - -}tstrOtaInitHdr; - - -/*! -@struct \ - tstrOtaControlSec - -@brief - Control section structure is used to define the working image and - the validity of the roll-back image and its offset, also both firmware versions is kept in that structure. - */ - -typedef struct { - uint32 u32OtaMagicValue; -/*!< - Magic value used to ensure the structure is valid or not -*/ - uint32 u32OtaFormatVersion; -/*!< - NA NA NA Flash version cs struct version - 00 00 00 00 00 - Control structure format version, the value will be incremented in case of structure changed or updated -*/ - uint32 u32OtaSequenceNumber; -/*!< - Sequence number is used while update the control structure to keep track of how many times that section updated -*/ - uint32 u32OtaLastCheckTime; -/*!< - Last time OTA check for update -*/ - uint32 u32OtaCurrentworkingImagOffset; -/*!< - Current working offset in flash -*/ - uint32 u32OtaCurrentworkingImagFirmwareVer; -/*!< - current working image version ex 18.0.1 -*/ - uint32 u32OtaRollbackImageOffset; -/*!< - Roll-back image offset in flash -*/ - uint32 u32OtaRollbackImageValidStatus; -/*!< - roll-back image valid status -*/ - uint32 u32OtaRollbackImagFirmwareVer; -/*!< - Roll-back image version (ex 18.0.3) -*/ - uint32 u32OtaCortusAppWorkingOffset; -/*!< - cortus app working offset in flash -*/ - uint32 u32OtaCortusAppWorkingValidSts; -/*!< - Working Cortus app valid status -*/ - uint32 u32OtaCortusAppWorkingVer; -/*!< - Working cortus app version (ex 18.0.3) -*/ - uint32 u32OtaCortusAppRollbackOffset; -/*!< - cortus app rollback offset in flash -*/ - uint32 u32OtaCortusAppRollbackValidSts; -/*!< - roll-back cortus app valid status -*/ - uint32 u32OtaCortusAppRollbackVer; -/*!< - Roll-back cortus app version (ex 18.0.3) -*/ - uint32 u32OtaControlSecCrc; -/*!< - CRC for the control structure to ensure validity -*/ -} tstrOtaControlSec; - -/*! -@enum \ - tenuOtaUpdateStatus - -@brief - OTA return status -*/ -typedef enum { - OTA_STATUS_SUCSESS = 0, - /*!< OTA Success with not errors. */ - OTA_STATUS_FAIL = 1, - /*!< OTA generic fail. */ - OTA_STATUS_INVAILD_ARG = 2, - /*!< Invalid or malformed download URL. */ - OTA_STATUS_INVAILD_RB_IMAGE = 3, - /*!< Invalid rollback image. */ - OTA_STATUS_INVAILD_FLASH_SIZE = 4, - /*!< Flash size on device is not enough for OTA. */ - OTA_STATUS_AlREADY_ENABLED = 5, - /*!< An OTA operation is already enabled. */ - OTA_STATUS_UPDATE_INPROGRESS = 6, - /*!< An OTA operation update is in progress */ - OTA_STATUS_IMAGE_VERIF_FAILED = 7, - /*!< OTA Verfication failed */ - OTA_STATUS_CONNECTION_ERROR = 8, - /*!< OTA connection error */ - OTA_STATUS_SERVER_ERROR = 9, - /*!< OTA server Error (file not found or else ...) */ - OTA_STATUS_ABORTED = 10 - /*!< OTA download has been aborted by the application. */ -} tenuOtaUpdateStatus; -/*! -@enum \ - tenuOtaUpdateStatusType - -@brief - OTA update Status type -*/ -typedef enum { - - DL_STATUS = 1, - /*!< Download OTA file status - */ - SW_STATUS = 2, - /*!< Switching to the upgrade firmware status - */ - RB_STATUS = 3, - /*!< Roll-back status - */ - AB_STATUS = 4 - /*!< Abort status - */ -}tenuOtaUpdateStatusType; - - -/*! -@struct \ - tstrOtaUpdateStatusResp - -@brief - OTA Update Information - -@sa - tenuWPSTrigger -*/ -typedef struct { - uint8 u8OtaUpdateStatusType; - /*!< - Status type tenuOtaUpdateStatusType - */ - uint8 u8OtaUpdateStatus; - /*!< - OTA_SUCCESS - OTA_ERR_WORKING_IMAGE_LOAD_FAIL - OTA_ERR_INVAILD_CONTROL_SEC - M2M_ERR_OTA_SWITCH_FAIL - M2M_ERR_OTA_START_UPDATE_FAIL - M2M_ERR_OTA_ROLLBACK_FAIL - M2M_ERR_OTA_INVAILD_FLASH_SIZE - M2M_ERR_OTA_INVAILD_ARG - */ - uint8 _PAD16_[2]; -}tstrOtaUpdateStatusResp; - -/*! -@struct \ - tstrOtaUpdateInfo - -@brief - OTA Update Information - -@sa - tenuWPSTrigger -*/ -typedef struct { - uint32 u8NcfUpgradeVersion; - /*!< NCF OTA Upgrade Version - */ - uint32 u8NcfCurrentVersion; - /*!< NCF OTA Current firmware version - */ - uint32 u8NcdUpgradeVersion; - /*!< NCD (host) upgraded version (if the u8NcdRequiredUpgrade == true) - */ - uint8 u8NcdRequiredUpgrade; - /*!< NCD Required upgrade to the above version - */ - uint8 u8DownloadUrlOffset; - /*!< Download URL offset in the received packet - */ - uint8 u8DownloadUrlSize; - /*!< Download URL size in the received packet - */ - uint8 __PAD8__; - /*!< Padding bytes for forcing 4-byte alignment - */ -} tstrOtaUpdateInfo; - -/*! -@struct \ - tstrSystemTime - -@brief - Used for time storage. -*/ -typedef struct{ - uint16 u16Year; - uint8 u8Month; - uint8 u8Day; - uint8 u8Hour; - uint8 u8Minute; - uint8 u8Second; - uint8 __PAD8__; -}tstrSystemTime; - -/*! -@struct \ - tstrM2MMulticastMac - -@brief - M2M add/remove multi-cast mac address - */ - typedef struct { - uint8 au8macaddress[M2M_MAC_ADDRES_LEN]; - /*!< - Mac address needed to be added or removed from filter. - */ - uint8 u8AddRemove; - /*!< - set by 1 to add or 0 to remove from filter. - */ - uint8 __PAD8__; - /*!< Padding bytes for forcing 4-byte alignment - */ -}tstrM2MMulticastMac; - -/*! -@struct \ - tstrPrng - -@brief - M2M Request PRNG - */ - typedef struct { - /*!< - return buffer address - */ - uint8 *pu8RngBuff; - /*!< - PRNG size requested - */ - uint16 u16PrngSize; - /*!< - PRNG pads - */ - uint8 __PAD16__[2]; -}tstrPrng; - -/* - * TLS certificate revocation list - * Typedefs common between fw and host - */ - -/*! -@struct \ - tstrTlsCrlEntry - -@brief - Certificate data for inclusion in a revocation list (CRL) -*/ -typedef struct { - uint8 u8DataLen; - /*!< - Length of certificate data (maximum possible is @ref TLS_CRL_DATA_MAX_LEN) - */ - uint8 au8Data[TLS_CRL_DATA_MAX_LEN]; - /*!< - Certificate data - */ - uint8 __PAD24__[3]; - /*!< - Padding bytes for forcing 4-byte alignment - */ -}tstrTlsCrlEntry; - -/*! -@struct \ - tstrTlsCrlInfo - -@brief - Certificate revocation list details -*/ -typedef struct { - uint8 u8CrlType; - /*!< - Type of certificate data contained in list - */ - uint8 u8Rsv1; - /*!< - Reserved for future use - */ - uint8 u8Rsv2; - /*!< - Reserved for future use - */ - uint8 u8Rsv3; - /*!< - Reserved for future use - */ - tstrTlsCrlEntry astrTlsCrl[TLS_CRL_MAX_ENTRIES]; - /*!< - List entries - */ -}tstrTlsCrlInfo; - - /*! -@enum\ - tenuSslCertExpSettings - -@brief SSL Certificate Expiry Validation Options -*/ -typedef enum{ - SSL_CERT_EXP_CHECK_DISABLE, - /*!< - ALWAYS OFF. - Ignore certificate expiration date validation. If a certificate is - expired or there is no configured system time, the SSL connection SUCCEEDs. - */ - SSL_CERT_EXP_CHECK_ENABLE, - /*!< - ALWAYS ON. - Validate certificate expiration date. If a certificate is expired or - there is no configured system time, the SSL connection FAILs. - */ - SSL_CERT_EXP_CHECK_EN_IF_SYS_TIME - /*!< - CONDITIONAL VALIDATION (Default setting at startup). - Validate the certificate expiration date only if there is a configured system time. - If there is no configured system time, the certificate expiration is bypassed and the - SSL connection SUCCEEDs. - */ -}tenuSslCertExpSettings; - - -/*! -@struct \ - tstrTlsSrvSecFileEntry - -@brief - This struct contains a TLS certificate. - */ -typedef struct{ - char acFileName[TLS_FILE_NAME_MAX]; - /*!< Name of the certificate. */ - uint32 u32FileSize; - /*!< Size of the certificate. */ - uint32 u32FileAddr; - /*!< Error Code. */ -}tstrTlsSrvSecFileEntry; - -/*! -@struct \ - tstrTlsSrvSecHdr - -@brief - This struct contains a set of TLS certificates. - */ -typedef struct{ - uint8 au8SecStartPattern[TLS_SRV_SEC_START_PATTERN_LEN]; - /*!< Start pattern. */ - uint32 u32nEntries; - /*!< Number of certificates stored in the struct. */ - uint32 u32NextWriteAddr; - /*!< TLS Certificates. */ - tstrTlsSrvSecFileEntry astrEntries[TLS_SRV_SEC_MAX_FILES]; -}tstrTlsSrvSecHdr; - -typedef struct{ - uint32 u32CsBMP; -}tstrSslSetActiveCsList; - - - /**@}*/ - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_wifi.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_wifi.h deleted file mode 100644 index 3477196..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/include/m2m_wifi.h +++ /dev/null @@ -1,2882 +0,0 @@ -/** - * - * \file - * - * \brief WINC WLAN Application Interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef __M2M_WIFI_H__ -#define __M2M_WIFI_H__ - -/** \defgroup m2m_wifi WLAN - * - */ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "common/include/nm_common.h" -#include "driver/include/m2m_types.h" -#include "driver/source/nmdrv.h" - -#ifdef CONF_MGMT - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/**@defgroup WlanEnums DataTypes - * @ingroup m2m_wifi - * @{*/ -/*! -@enum \ - tenuWifiFrameType - -@brief - Enumeration for Wi-Fi MAC frame type codes (2-bit) - The following types are used to identify the type of frame sent or received. - Each frame type constitutes a number of frame subtypes as defined in @ref tenuSubTypes to specify the exact type of frame. - Values are defined as per the IEEE 802.11 standard. - -@remarks - The following frame types are useful for advanced user usage when monitoring mode is used (defining @ref CONF_MGMT) - and the user application requires to monitor the frame transmission and reception. -@see - tenuSubTypes -*/ -typedef enum { - MANAGEMENT = 0x00, - /*!< Wi-Fi Management frame (Probe Req/Resp, Beacon, Association Req/Resp ...etc). - */ - CONTROL = 0x04, - /*!< Wi-Fi Control frame (eg. ACK frame). - */ - DATA_BASICTYPE = 0x08, - /*!< Wi-Fi Data frame. - */ - RESERVED = 0x0C, - - M2M_WIFI_FRAME_TYPE_ANY = 0xFF -/*!< Set monitor mode to receive any of the frames types -*/ -}tenuWifiFrameType; - - -/*! -@enum \ - tenuSubTypes - -@brief - Enumeration for Wi-Fi MAC Frame subtype code (6-bit). - The frame subtypes fall into one of the three frame type groups as defined in @ref tenuWifiFrameType - (MANAGEMENT, CONTROL & DATA). - Values are defined as per the IEEE 802.11 standard. -@remarks - The following sub-frame types are useful for advanced user usage when @ref CONF_MGMT is defined - and the application developer requires to monitor the frame transmission and reception. -@see - tenuWifiFrameType - tstrM2MWifiMonitorModeCtrl -*/ -typedef enum { - /*!< Sub-Types related to Management Sub-Types */ - ASSOC_REQ = 0x00, - ASSOC_RSP = 0x10, - REASSOC_REQ = 0x20, - REASSOC_RSP = 0x30, - PROBE_REQ = 0x40, - PROBE_RSP = 0x50, - BEACON = 0x80, - ATIM = 0x90, - DISASOC = 0xA0, - AUTH = 0xB0, - DEAUTH = 0xC0, - ACTION = 0xD0, -/**@{*/ - /* Sub-Types related to Control */ - PS_POLL = 0xA4, - RTS = 0xB4, - CTS = 0xC4, - ACK = 0xD4, - CFEND = 0xE4, - CFEND_ACK = 0xF4, - BLOCKACK_REQ = 0x84, - BLOCKACK = 0x94, -/**@{*/ - /* Sub-Types related to Data */ - DATA = 0x08, - DATA_ACK = 0x18, - DATA_POLL = 0x28, - DATA_POLL_ACK = 0x38, - NULL_FRAME = 0x48, - CFACK = 0x58, - CFPOLL = 0x68, - CFPOLL_ACK = 0x78, - QOS_DATA = 0x88, - QOS_DATA_ACK = 0x98, - QOS_DATA_POLL = 0xA8, - QOS_DATA_POLL_ACK = 0xB8, - QOS_NULL_FRAME = 0xC8, - QOS_CFPOLL = 0xE8, - QOS_CFPOLL_ACK = 0xF8, - M2M_WIFI_FRAME_SUB_TYPE_ANY = 0xFF - /*!< Set monitor mode to receive any of the frames types - */ -}tenuSubTypes; - - -/*! -@enum \ - tenuInfoElementId - -@brief - Enumeration for the Wi-Fi Information Element(IE) IDs, which indicates the specific type of IEs. - IEs are management frame information included in management frames. - Values are defined as per the IEEE 802.11 standard. - -*/ -typedef enum { - ISSID = 0, - /*!< Service Set Identifier (SSID) - */ - ISUPRATES = 1, - /*!< Supported Rates - */ - IFHPARMS = 2, - /*!< FH parameter set - */ - IDSPARMS = 3, - /*!< DS parameter set - */ - ICFPARMS = 4, - /*!< CF parameter set - */ - ITIM = 5, - /*!< Traffic Information Map - */ - IIBPARMS = 6, - /*!< IBSS parameter set - */ - ICOUNTRY = 7, - /*!< Country element. - */ - IEDCAPARAMS = 12, - /*!< EDCA parameter set - */ - ITSPEC = 13, - /*!< Traffic Specification - */ - ITCLAS = 14, - /*!< Traffic Classification - */ - ISCHED = 15, - /*!< Schedule. - */ - ICTEXT = 16, - /*!< Challenge Text - */ - IPOWERCONSTRAINT = 32, - /*!< Power Constraint. - */ - IPOWERCAPABILITY = 33, - /*!< Power Capability - */ - ITPCREQUEST = 34, - /*!< TPC Request - */ - ITPCREPORT = 35, - /*!< TPC Report - */ - ISUPCHANNEL = 36, - /* Supported channel list - */ - ICHSWANNOUNC = 37, - /*!< Channel Switch Announcement - */ - IMEASUREMENTREQUEST = 38, - /*!< Measurement request - */ - IMEASUREMENTREPORT = 39, - /*!< Measurement report - */ - IQUIET = 40, - /*!< Quiet element Info - */ - IIBSSDFS = 41, - /*!< IBSS DFS - */ - IERPINFO = 42, - /*!< ERP Information - */ - ITSDELAY = 43, - /*!< TS Delay - */ - ITCLASPROCESS = 44, - /*!< TCLAS Processing - */ - IHTCAP = 45, - /*!< HT Capabilities - */ - IQOSCAP = 46, - /*!< QoS Capability - */ - IRSNELEMENT = 48, - /*!< RSN Information Element - */ - IEXSUPRATES = 50, - /*!< Extended Supported Rates - */ - IEXCHSWANNOUNC = 60, - /*!< Extended Ch Switch Announcement - */ - IHTOPERATION = 61, - /*!< HT Information - */ - ISECCHOFF = 62, - /*!< Secondary Channel Offset - */ - I2040COEX = 72, - /*!< 20/40 Coexistence IE - */ - I2040INTOLCHREPORT = 73, - /*!< 20/40 Intolerant channel report - */ - IOBSSSCAN = 74, - /*!< OBSS Scan parameters - */ - IEXTCAP = 127, - /*!< Extended capability - */ - IWMM = 221, - /*!< WMM parameters - */ - IWPAELEMENT = 221 - /*!< WPA Information Element - */ -}tenuInfoElementId; - - -/*! -@struct \ - tenuWifiCapability - -@brief - Enumeration for capability Information field bit. - The value of the capability information field from the 802.11 management frames received by the wireless LAN interface. - Defining the capabilities of the Wi-Fi system. Values are defined as per the IEEE 802.11 standard. - -@details - Capabilities:- - ESS/IBSS : Defines whether a frame is coming from an AP or not. - POLLABLE : CF Poll-able - POLLREQ : Request to be polled - PRIVACY : WEP encryption supported - SHORTPREAMBLE : Short Preamble is supported - SHORTSLOT : Short Slot is supported - PBCC :PBCC - CHANNELAGILITY :Channel Agility - SPECTRUM_MGMT :Spectrum Management - DSSS_OFDM : DSSS-OFDM -*/ -typedef enum{ - ESS = 0x01, - /*!< ESS capability - */ - IBSS = 0x02, - /*!< IBSS mode - */ - POLLABLE = 0x04, - /*!< CF Pollable - */ - POLLREQ = 0x08, - /*!< Request to be polled - */ - PRIVACY = 0x10, - /*!< WEP encryption supported - */ - SHORTPREAMBLE = 0x20, - /*!< Short Preamble is supported - */ - SHORTSLOT = 0x400, - /*!< Short Slot is supported - */ - PBCC = 0x40, - /*!< PBCC - */ - CHANNELAGILITY = 0x80, - /*!< Channel Agility - */ - SPECTRUM_MGMT = 0x100, - /*!< Spectrum Management - */ - DSSS_OFDM = 0x2000 - /*!< DSSS-OFDM - */ -}tenuWifiCapability; - - -#endif - -/*! -@typedef \ - tpfAppWifiCb - -@brief - Wi-Fi's main callback function handler, for handling the M2M_WIFI events received on the Wi-Fi interface. - Such notifications are received in response to Wi-Fi/P2P operations such as @ref m2m_wifi_request_scan, - @ref m2m_wifi_connect. - Wi-Fi/P2P operations are implemented in an asynchronous mode, and all incoming information/status - are to be handled through this callback function when the corresponding notification is received. - Applications are expected to assign this wi-fi callback function by calling @ref m2m_wifi_init -@param [in] u8MsgType - Type of notifications. Possible types are: - /ref M2M_WIFI_RESP_CON_STATE_CHANGED - /ref M2M_WIFI_RESP_CONN_INFO - /ref M2M_WIFI_REQ_DHCP_CONF - /ref M2M_WIFI_REQ_WPS - /ref M2M_WIFI_RESP_IP_CONFLICT - /ref M2M_WIFI_RESP_SCAN_DONE - /ref M2M_WIFI_RESP_SCAN_RESULT - /ref M2M_WIFI_RESP_CURRENT_RSSI - /ref M2M_WIFI_RESP_CLIENT_INFO - /ref M2M_WIFI_RESP_PROVISION_INFO - /ref M2M_WIFI_RESP_DEFAULT_CONNECT - - In case Ethernet/Bypass mode is defined : - @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET - - In case monitoring mode is used: - @ref M2M_WIFI_RESP_WIFI_RX_PACKET - -@param [in] pvMsg - A pointer to a buffer containing the notification parameters (if any). It should be - casted to the correct data type corresponding to the notification type. - -@see - tstrM2mWifiStateChanged - tstrM2MWPSInfo - tstrM2mScanDone - tstrM2mWifiscanResult -*/ -typedef void (*tpfAppWifiCb) (uint8 u8MsgType, void * pvMsg); - -/*! -@typedef \ - tpfAppEthCb - -@brief - ETHERNET (bypass mode) notification callback function receiving Bypass mode events as defined in - the Wi-Fi responses enumeration @ref tenuM2mStaCmd. - -@param [in] u8MsgType - Type of notification. Possible types are: - - [M2M_WIFI_RESP_ETHERNET_RX_PACKET](@ref M2M_WIFI_RESP_ETHERNET_RX_PACKET) - -@param [in] pvMsg - A pointer to a buffer containing the notification parameters (if any). It should be - casted to the correct data type corresponding to the notification type. - For example, it could be a pointer to the buffer holding the received frame in case of @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET - event. - -@param [in] pvControlBuf - A pointer to control buffer describing the accompanied message. - To be casted to @ref tstrM2mIpCtrlBuf in case of @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET event. - -@warning - Make sure that the application defines @ref ETH_MODE. - -@see - m2m_wifi_init - -*/ -typedef void (*tpfAppEthCb) (uint8 u8MsgType, void * pvMsg,void * pvCtrlBuf); - -/*! -@typedef \ - tpfAppMonCb - -@brief - Wi-Fi monitoring mode callback function. This function delivers all received wi-Fi packets through the Wi-Fi interface. - Applications requiring to operate in the monitoring should call the asynchronous function m2m_wifi_enable_monitoring_mode - and expect to receive the Wi-Fi packets through this callback function, when the event is received. - To disable the monitoring mode a call to @ref m2m_wifi_disable_monitoring_mode should be made. -@param [in] pstrWifiRxPacket - Pointer to a structure holding the Wi-Fi packet header parameters. - -@param [in] pu8Payload - Pointer to the buffer holding the Wi-Fi packet payload information required by the application starting from the - defined OFFSET by the application (when calling m2m_wifi_enable_monitoring_mode). - Could hold a value of NULL, if the application does not need any data from the payload. - -@param [in] u16PayloadSize - The size of the payload in bytes. - -@see - m2m_wifi_enable_monitoring_mode,m2m_wifi_init - -@warning - u16PayloadSize should not exceed the buffer size given through m2m_wifi_enable_monitoring_mode. - -*/ -typedef void (*tpfAppMonCb) (tstrM2MWifiRxPacketInfo *pstrWifiRxPacket, uint8 * pu8Payload, uint16 u16PayloadSize); - -/** -@struct \ - tstrEthInitParam - -@brief - Structure to hold Ethernet interface parameters. - Structure is to be defined and have its attributes set,based on the application's functionality before - a call is made to initialize the Wi-Fi operations by calling the @ref m2m_wifi_init function. - This structure is part of the Wi-Fi configuration structure @ref tstrWifiInitParam. - Applications shouldn't need to define this structure, if the bypass mode is not defined. - -@see - tpfAppEthCb - tpfAppWifiCb - m2m_wifi_init - -@warning - Make sure that application defines @ref ETH_MODE before using @ref tstrEthInitParam. - -*/ -typedef struct { - tpfAppWifiCb pfAppWifiCb; - /*!< - Callback for wifi notifications. - */ - tpfAppEthCb pfAppEthCb; - /*!< - Callback for Ethernet interface. - */ - uint8 * au8ethRcvBuf; - /*!< - Pointer to Receive Buffer of Ethernet Packet - */ - uint16 u16ethRcvBufSize; - /*!< - Size of Receive Buffer for Ethernet Packet - */ - uint8 u8EthernetEnable; - /*!< - Enable Ethernet mode flag - */ - uint8 __PAD8__; - /*!< - Padding - */ -} tstrEthInitParam; -/*! -@struct \ - tstrM2mIpCtrlBuf - -@brief - Structure holding the incoming buffer's data size information, indicating the data size of the buffer and the remaining buffer's data size . - The data of the buffer which holds the packet sent to the host when in the bypass mode, is placed in the @ref tstrEthInitParam structure in the - @ref au8ethRcvBuf attribute. This following information is retrieved in the host when an event @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET is received in - the Wi-Fi callback function @ref tpfAppWifiCb. - - The application is expected to use this structure's information to determine if there is still incoming data to be received from the firmware. - - @see - tpfAppEthCb - tstrEthInitParam - - @warning - Make sure that ETHERNET/bypass mode is defined before using @ref tstrM2mIpCtrlBuf - - */ -typedef struct{ - uint16 u16DataSize; - /*!< - Size of the received data in bytes. - */ - uint16 u16RemainigDataSize; - /*!< - Size of the remaining data bytes to be delivered to host. - */ -} tstrM2mIpCtrlBuf; - - -/** -@struct \ - tstrWifiInitParam - -@brief - Structure, holding the Wi-fi configuration attributes such as the wi-fi callback , monitoring mode callback and Ethernet parameter initialization structure. - Such configuration parameters are required to be set before calling the wi-fi initialization function @ref m2m_wifi_init. - @ref pfAppWifiCb attribute must be set to handle the wi-fi callback operations. - @ref pfAppMonCb attribute, is optional based on whether the application requires the monitoring mode configuration, and can there not - be set before the initialization. - @ref strEthInitParam structure, is another optional configuration based on whether the bypass mode is set. - - @see - tpfAppEthCb - tpfAppMonCb - tstrEthInitParam - -*/ -typedef struct { - tpfAppWifiCb pfAppWifiCb; - /*!< - Callback for Wi-Fi notifications. - */ - tpfAppMonCb pfAppMonCb; - /*!< - Callback for monitoring interface. - */ - tstrEthInitParam strEthInitParam ; - /*!< - Structure to hold Ethernet interface parameters. - */ - -} tstrWifiInitParam; - //@} -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/** \defgroup WLANAPI Function - * @ingroup m2m_wifi - */ -#ifdef __cplusplus - extern "C" { -#endif - /** @defgroup WiFiDownloadFn m2m_wifi_download_mode - * @ingroup WLANAPI - * Synchronous download mode entry function that prepares the WINC board to enter the download mode, ready for the firmware or certificate download. -* The WINC board is prepared for download, through initializations for the WINC driver including bus initializations and interrupt enabling, it also halts the chip, to allow for the firmware downloads. -* Firmware can be downloaded through a number of interfaces, UART, I2C and SPI. - */ - /**@{*/ -/*! -@fn \ - NMI_API void m2m_wifi_download_mode(void); -@brief Prepares the WINC broard before downloading any data (Firmware, Certificates .. etc) - - This function should called before starting to download any data to the WINC board. The WINC board is prepared for download, through initializations for the WINC driver including bus initializations - and interrupt enabling, it also halts the chip, to allow for the firmware downloads Firmware can be downloaded through a number of interfaces, UART, I2C and SPI. - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_download_mode(void); - - /**@}*/ - /** @defgroup WifiInitFn m2m_wifi_init - * @ingroup WLANAPI - * Synchronous initialization function for the WINC driver. This function initializes the driver by, registering the call back function for M2M_WIFI layer(also the call back function for bypass mode/monitoring mode if defined), - * initializing the host interface layer and the bus interfaces. - * Wi-Fi callback registering is essential to allow the handling of the events received, in response to the asynchronous Wi-Fi operations. - -Following are the possible Wi-Fi events that are expected to be received through the call back function(provided by the application) to the M2M_WIFI layer are : - - @ref M2M_WIFI_RESP_CON_STATE_CHANGED \n - @ref M2M_WIFI_RESP_CONN_INFO \n - @ref M2M_WIFI_REQ_DHCP_CONF \n - @ref M2M_WIFI_REQ_WPS \n - @ref M2M_WIFI_RESP_IP_CONFLICT \n - @ref M2M_WIFI_RESP_SCAN_DONE \n - @ref M2M_WIFI_RESP_SCAN_RESULT \n - @ref M2M_WIFI_RESP_CURRENT_RSSI \n - @ref M2M_WIFI_RESP_CLIENT_INFO \n - @ref M2M_WIFI_RESP_PROVISION_INFO \n - @ref M2M_WIFI_RESP_DEFAULT_CONNECT \n - Example: \n - In case Bypass mode is defined : \n - @ref M2M_WIFI_RESP_ETHERNET_RX_PACKET - - In case Monitoring mode is used: \n - @ref M2M_WIFI_RESP_WIFI_RX_PACKET - - Any application using the WINC driver must call this function at the start of its main function. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_init(tstrWifiInitParam * pWifiInitParam); - -@param [in] pWifiInitParam - This is a pointer to the @ref tstrWifiInitParam structure which holds the pointer to the application WIFI layer call back function, - monitoring mode call back and @ref tstrEthInitParam structure containing bypass mode parameters. - -@brief Initialize the WINC host driver. - This function initializes the driver by, registering the call back function for M2M_WIFI layer(also the call back function for bypass mode/monitoring mode if defined), - initializing the host interface layer and the bus interfaces. - -@pre - Prior to this function call, The application should initialize the BSP using "nm_bsp_init". - Also,application users must provide a call back function responsible for receiving all the WI-FI events that are received on the M2M_WIFI layer. - -@warning - Failure to successfully complete function indicates that the driver couldn't be initialized and a fatal error will prevent the application from proceeding. - -@see - nm_bsp_init - m2m_wifi_deinit - tenuM2mStaCmd - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_init(tstrWifiInitParam * pWifiInitParam); - /**@}*/ - /** @defgroup WifiDeinitFn m2m_wifi_deinit - * @ingroup WLANAPI - * Synchronous de-initialization function to the WINC1500 driver. De-initializes the host interface and frees any resources used by the M2M_WIFI layer. - * This function must be called in the application closing phase to ensure that all resources have been correctly released. No arguments are expected to be passed in. - */ -/**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_deinit(void * arg); - -@param [in] arg - Generic argument. Not used in the current implementation. -@brief Deinitilize the WINC driver and host enterface. - This function must be called at the De-initilization stage of the application. Generally This function should be the last function before switching off the chip - and it should be followed only by "nm_bsp_deinit" function call. Every function call of "nm_wifi_init" should be matched with a call to nm_wifi_deinit. -@see - nm_bsp_deinit - nm_wifi_init - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_deinit(void * arg); - - /**@}*/ -/** @defgroup WifiHandleEventsFn m2m_wifi_handle_events -* @ingroup WLANAPI -* Synchronous M2M event handler function, responsible for handling interrupts received from the WINC firmware. -* Application developers should call this function periodically in-order to receive the events that are to be handled by the -* callback functions implemented by the application. - - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_handle_events(void * arg); - -@pre - Prior to receiving events, the WINC driver should have been successfully initialized by calling the @ref m2m_wifi_init function. - -@brief Handle the varios events received from the WINC board. - Whenever an event happen in the WINC board (e.g. Connection, Disconnection , DHCP .. etc), WINC will interrupt the host to let it know that a new - event has occured. The host driver will attempt to handle these events whenever the host driver decides to do that by calling the "m2m_wifi_handle_events" function. - It's mandatory to call this function periodically and independantly of any other condition. It's ideal to include this function in the main and the most frequent loop of the - host application. -@warning - Failure to successfully complete this function indicates bus errors and hence a fatal error that will prevent the application from proceeding. - -@return - The function returns @ref M2M_SUCCESS for successful interrupt handling and a negative value otherwise. -*/ - -NMI_API sint8 m2m_wifi_handle_events(void * arg); - - /**@}*/ -/** @defgroup WifiSendCRLFn m2m_wifi_send_crl -* @ingroup WLANAPI -* Asynchronous API that notifies the WINC with the Certificate Revocation List to be used for TLS. - - */ - /**@{*/ -/*! -@fn \ - sint8 m2m_wifi_send_crl(tstrTlsCrlInfo* pCRL); - -@brief - Asynchronous API that notifies the WINC with the Certificate Revocation List. - -@param [in] pCRL - Pointer to the structure containing certificate revocation list details. - -@return - The function returns @ref M2M_SUCCESS if the command has been successfully queued to the WINC, - and a negative value otherwise. -*/ - -sint8 m2m_wifi_send_crl(tstrTlsCrlInfo* pCRL); - - /**@}*/ -/** @defgroup WifiDefaultConnectFn m2m_wifi_default_connect - * @ingroup WLANAPI - * Asynchronous Wi-Fi connection function. An application calling this function will cause the firmware to correspondingly connect to the last successfully connected AP from the cached connections. - * A failure to connect will result in a response of @ref M2M_WIFI_RESP_DEFAULT_CONNECT indicating the connection error as defined in the structure @ref tstrM2MDefaultConnResp. - * Possible errors are: - * The connection list is empty @ref M2M_DEFAULT_CONN_EMPTY_LIST or a mismatch for the saved AP name @ref M2M_DEFAULT_CONN_SCAN_MISMATCH. - * only difference between this function and @ref m2m_wifi_connect, is the connection parameters. - * Connection using this function is expected to connect using cached connection parameters. - - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_default_connect(void); - -@pre - Prior to connecting, the WINC driver should have been successfully initialized by calling the @ref m2m_wifi_init function. - -@brief Connect to the last successfully connected AP from the cached connections. - -@warning - This function must be called in station mode only. - It's important to note that successful completion of a call to m2m_wifi_default_connect() does not guarantee success of the WIFI connection, - and a negative return value indicates only locally-detected errors. - -@see - m2m_wifi_connect - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_default_connect(void); - /**@}*/ -/** @defgroup WifiConnectFn m2m_wifi_connect - * @ingroup WLANAPI - * Asynchronous wi-fi connection function to a specific AP. Prior to a successful connection, the application must define the SSID of the AP, the security type, - * the authentication information parameters and the channel number to which the connection will be established. - * The connection status is known when a response of @ref M2M_WIFI_RESP_CON_STATE_CHANGED is received based on the states defined in @ref tenuM2mConnState, - * successful connection is defined by @ref M2M_WIFI_CONNECTED -* - * The only difference between this function and @ref m2m_wifi_default_connect, is the connection parameters. - * Connection using this function is expected to be made to a specific AP and to a specified channel. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_connect(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch); - -@param [in] pcSsid - A buffer holding the SSID corresponding to the requested AP. - -@param [in] u8SsidLen - Length of the given SSID (not including the NULL termination). - A length less than ZERO or greater than the maximum defined SSID @ref M2M_MAX_SSID_LEN will result in a negative error - @ref M2M_ERR_FAIL. - -@param [in] u8SecType - Wi-Fi security type security for the network. It can be one of the following types: - -@ref M2M_WIFI_SEC_OPEN - -@ref M2M_WIFI_SEC_WEP - -@ref M2M_WIFI_SEC_WPA_PSK - -@ref M2M_WIFI_SEC_802_1X - A value outside these possible values will result in a negative return error @ref M2M_ERR_FAIL. - -@param [in] pvAuthInfo - Authentication parameters required for completing the connection. It is type is based on the Security type. - If the authentication parameters are NULL or are greater than the maximum length of the authentication parameters length as defined by - @ref M2M_MAX_PSK_LEN a negative error will return @ref M2M_ERR_FAIL(-12) indicating connection failure. - -@param [in] u16Ch - Wi-Fi channel number as defined in @ref tenuM2mScanCh enumeration. - Channel number greater than @ref M2M_WIFI_CH_14 returns a negative error @ref M2M_ERR_FAIL(-12). - Except if the value is M2M_WIFI_CH_ALL(255), since this indicates that the firmware should scan all channels to find the SSID requested to connect to. - Failure to find the connection match will return a negative error @ref M2M_DEFAULT_CONN_SCAN_MISMATCH. -@pre - Prior to a successful connection request, the Wi-Fi driver must have been successfully initialized through the call of the @ref @m2m_wifi_init function -@see - tuniM2MWifiAuth - tstr1xAuthCredentials - tstrM2mWifiWepParams - -@warning - -This function must be called in station mode only. - -Successful completion of this function does not guarantee success of the WIFI connection, and - a negative return value indicates only locally-detected errors. - -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_connect(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch); - /**@}*/ -/** @defgroup WifiConnectFn m2m_wifi_connect_sc - * @ingroup WLANAPI - * Asynchronous wi-fi connection function to a specific AP. Prior to a successful connection, the application developers must know the SSID of the AP, the security type, - * the authentication information parameters and the channel number to which the connection will be established.this API allows the user to choose - * whether to - * The connection status is known when a response of @ref M2M_WIFI_RESP_CON_STATE_CHANGED is received based on the states defined in @ref tenuM2mConnState, - * successful connection is defined by @ref M2M_WIFI_CONNECTED - * The only difference between this function and @ref m2m_wifi_connect, is the option to save the acess point info ( SSID, password...etc) or not. - * Connection using this function is expected to be made to a specific AP and to a specified channel. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_connect_sc(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch,uint8 u8SaveCred); - -@param [in] pcSsid - A buffer holding the SSID corresponding to the requested AP. - -@param [in] u8SsidLen - Length of the given SSID (not including the NULL termination). - A length less than ZERO or greater than the maximum defined SSID @ref M2M_MAX_SSID_LEN will result in a negative error - @ref M2M_ERR_FAIL. - -@param [in] u8SecType - Wi-Fi security type security for the network. It can be one of the following types: - -@ref M2M_WIFI_SEC_OPEN - -@ref M2M_WIFI_SEC_WEP - -@ref M2M_WIFI_SEC_WPA_PSK - -@ref M2M_WIFI_SEC_802_1X - A value outside these possible values will result in a negative return error @ref M2M_ERR_FAIL. - -@param [in] pvAuthInfo - Authentication parameters required for completing the connection. It is type is based on the Security type. - If the authentication parameters are NULL or are greater than the maximum length of the authentication parameters length as defined by - @ref M2M_MAX_PSK_LEN a negative error will return @ref M2M_ERR_FAIL(-12) indicating connection failure. - -@param [in] u16Ch - Wi-Fi channel number as defined in @ref tenuM2mScanCh enumeration. - Channel number greater than @ref M2M_WIFI_CH_14 returns a negative error @ref M2M_ERR_FAIL(-12). - Except if the value is M2M_WIFI_CH_ALL(255), since this indicates that the firmware should scan all channels to find the SSID requested to connect to. - Failure to find the connection match will return a negative error @ref M2M_DEFAULT_CONN_SCAN_MISMATCH. - -@param [in] u8NoSaveCred - Option to store the acess point SSID and password into the WINC flash memory or not. - -@pre - Prior to a successful connection request, the wi-fi driver must have been successfully initialized through the call of the @ref @m2m_wifi_init function -@see - tuniM2MWifiAuth - tstr1xAuthCredentials - tstrM2mWifiWepParams - -@warning - -This function must be called in station mode only. - -Successful completion of this function does not guarantee success of the WIFI connection, and - a negative return value indicates only locally-detected errors. - -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ - NMI_API sint8 m2m_wifi_connect_sc(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch, uint8 u8SaveCred); - /**@}*/ -/** @defgroup WifiDisconnectFn m2m_wifi_disconnect - * @ingroup WLANAPI - * Synchronous wi-fi disconnection function, requesting a Wi-Fi disconnection from the currently connected AP. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_disconnect(void); - -@pre - Disconnection request must be made to a successfully connected AP. If the WINC is not in the connected state, a call to this function will hold insignificant. - -@brief Request a Wi-Fi disconnect from the currently connected AP. - After the Disconnect is complete the driver should recieve a response of @ref M2M_WIFI_RESP_CON_STATE_CHANGED based on the states defined - in @ref tenuM2mConnState, successful disconnection is defined by @ref M2M_WIFI_DISCONNECTED . -@warning - This function must be called in station mode only. - -@see - m2m_wifi_connect - m2m_wifi_default_connect - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_disconnect(void); - - /**@}*/ -/** @defgroup StartProvisionModeFn m2m_wifi_start_provision_mode - * @ingroup WLANAPI - * Asynchronous Wi-Fi provisioning function, which starts the WINC HTTP PROVISIONING mode. - The function triggers the WINC to activate the Wi-Fi AP (HOTSPOT) mode with the passed configuration parameters and then starts the - HTTP Provision WEB Server. - The provisioning status is returned in an event @ref M2M_WIFI_RESP_PROVISION_INFO - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_start_provision_mode(tstrM2MAPConfig *pstrAPConfig, char *pcHttpServerDomainName, uint8 bEnableHttpRedirect); - -@param [in] pstrAPConfig - AP configuration parameters as defined in @ref tstrM2MAPConfig configuration structure. - A NULL value passed in, will result in a negative error @ref M2M_ERR_FAIL. - -@param [in] pcHttpServerDomainName - Domain name of the HTTP Provision WEB server which others will use to load the provisioning Home page. - The domain name can have one of the following 3 forms: - 1- "wincprov.com" - 2- "http://wincprov.com" - 3- "https://wincprov.com" - The forms 1 and 2 are equivalent, they both will start a plain http server, while form 3 - will start a secure HTTP provisioning Session (HTTP over SSL connection). - -@param [in] bEnableHttpRedirect - A flag to enable/disable the HTTP redirect feature. If Secure provisioning is enabled (i.e. the server - domain name uses "https" prefix) this flag is ignored (no meaning for redirect in HTTPS). - Possible values are: - - ZERO DO NOT Use HTTP Redirect. In this case the associated device could open the provisioning page ONLY when - the HTTP Provision URL of the WINC HTTP Server is correctly written on the browser. - - Non-Zero value Use HTTP Redirect. In this case, all http traffic (http://URL) from the associated - device (Phone, PC, ...etc) will be redirected to the WINC HTTP Provisioning Home page. - -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback - is done through passing it to the initialization @ref m2m_wifi_init function. - - The event @ref M2M_WIFI_RESP_CONN_INFO must be handled in the callback to receive the requested connection info. - -@see - tpfAppWifiCb - m2m_wifi_init - M2M_WIFI_RESP_PROVISION_INFO - m2m_wifi_stop_provision_mode - tstrM2MAPConfig - -@warning - DO Not use ".local" in the pcHttpServerDomainName. - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -\section Example - The example demonstrates a code snippet for how provisioning is triggered and the response event received accordingly. -@code - #include "m2m_wifi.h" - #include "m2m_types.h" - - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_PROVISION_INFO: - { - tstrM2MProvisionInfo *pstrProvInfo = (tstrM2MProvisionInfo*)pvMsg; - if(pstrProvInfo->u8Status == M2M_SUCCESS) - { - m2m_wifi_connect((char*)pstrProvInfo->au8SSID, (uint8)strlen(pstrProvInfo->au8SSID), pstrProvInfo->u8SecType, - pstrProvInfo->au8Password, M2M_WIFI_CH_ALL); - - printf("PROV SSID : %s\n",pstrProvInfo->au8SSID); - printf("PROV PSK : %s\n",pstrProvInfo->au8Password); - } - else - { - printf("(ERR) Provisioning Failed\n"); - } - } - break; - - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - tstrM2MAPConfig apConfig; - uint8 bEnableRedirect = 1; - - strcpy(apConfig.au8SSID, "WINC_SSID"); - apConfig.u8ListenChannel = 1; - apConfig.u8SecType = M2M_WIFI_SEC_OPEN; - apConfig.u8SsidHide = 0; - - // IP Address - apConfig.au8DHCPServerIP[0] = 192; - apConfig.au8DHCPServerIP[1] = 168; - apConfig.au8DHCPServerIP[2] = 1; - apConfig.au8DHCPServerIP[0] = 1; - - m2m_wifi_start_provision_mode(&apConfig, "atmelwincconf.com", bEnableRedirect); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API sint8 m2m_wifi_start_provision_mode(tstrM2MAPConfig *pstrAPConfig, char *pcHttpServerDomainName, uint8 bEnableHttpRedirect); - /**@}*/ -/** @defgroup StopProvisioningModeFn m2m_wifi_stop_provision_mode - * @ingroup WLANAPI - * Synchronous provision termination function which stops the provision mode if it is active. - */ - /**@{*/ -/*! -@fn \ - sint8 m2m_wifi_stop_provision_mode(void); - -@pre - An active provisioning session must be active before it is terminated through this function. -@see - m2m_wifi_start_provision_mode - -@return - The function returns ZERO for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_stop_provision_mode(void); - /**@}*/ -/** @defgroup GetConnectionInfoFn m2m_wifi_get_connection_info - * @ingroup WLANAPI - * Asynchronous connection status retrieval function, retrieves the status information of the currently connected AP. The result is passed to the Wi-Fi notification callback -* through the event @ref M2M_WIFI_RESP_CONN_INFO. Connection information is retrieved from the structure @ref tstrM2MConnInfo. - */ - /**@{*/ -/*! -@fn \ - sint8 m2m_wifi_get_connection_info(void); - -@brief - Retrieve the current Connection information. The result is passed to the Wi-Fi notification callback - with [M2M_WIFI_RESP_CONN_INFO](@ref M2M_WIFI_RESP_CONN_INFO). -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback - is done through passing it to the initialization @ref m2m_wifi_init function. - - The event @ref M2M_WIFI_RESP_CONN_INFO must be handled in the callback to receive the requested connection info. - - Connection Information retrieved: - - - -Connection Security - -Connection RSSI - -Remote MAC address - -Remote IP address - - and in case of WINC station mode the SSID of the AP is also retrieved. -@warning - -In case of WINC AP mode or P2P mode, ignore the SSID field (NULL string). -@sa - M2M_WIFI_RESP_CONN_INFO, - tstrM2MConnInfo -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet shows an example of how wi-fi connection information is retrieved . -@code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_CONN_INFO: - { - tstrM2MConnInfo *pstrConnInfo = (tstrM2MConnInfo*)pvMsg; - - printf("CONNECTED AP INFO\n"); - printf("SSID : %s\n",pstrConnInfo->acSSID); - printf("SEC TYPE : %d\n",pstrConnInfo->u8SecType); - printf("Signal Strength : %d\n", pstrConnInfo->s8RSSI); - printf("Local IP Address : %d.%d.%d.%d\n", - pstrConnInfo->au8IPAddr[0] , pstrConnInfo->au8IPAddr[1], pstrConnInfo->au8IPAddr[2], pstrConnInfo->au8IPAddr[3]); - } - break; - - case M2M_WIFI_REQ_DHCP_CONF: - { - // Get the current AP information. - m2m_wifi_get_connection_info(); - } - break; - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // connect to the default AP - m2m_wifi_default_connect(); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API sint8 m2m_wifi_get_connection_info(void); - /**@}*/ -/** @defgroup WifiSetMacAddFn m2m_wifi_set_mac_address - * @ingroup WLANAPI - * Synchronous MAC address assigning to the NMC1500. It is used for non-production SW. Assign MAC address to the WINC device. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_set_mac_address(uint8 au8MacAddress[6]); - -@brief Assign a MAC address to the WINC board. - This function override the already assigned MAC address of the WINC board with a user provided one. This is for experimental - use only and should never be used in the production SW. - -@param [in] au8MacAddress - MAC Address to be set to the WINC. - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_set_mac_address(uint8 au8MacAddress[6]); - - /**@}*/ -/** @defgroup WifiWpsFn m2m_wifi_wps - * @ingroup WLANAPI - * Asynchronous WPS triggering function. - * This function is called for the WINC to enter the WPS (Wi-Fi Protected Setup) mode. The result is passed to the Wi-Fi notification callback -* with the event @ref M2M_WIFI_REQ_WPS. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_wps(uint8 u8TriggerType,const char * pcPinNumber); - -@param [in] u8TriggerType - WPS Trigger method. Could be: - - [WPS_PIN_TRIGGER](@ref WPS_PIN_TRIGGER) Push button method - - [WPS_PBC_TRIGGER](@ref WPS_PBC_TRIGGER) Pin method - -@param [in] pcPinNumber - PIN number for WPS PIN method. It is not used if the trigger type is WPS_PBC_TRIGGER. It must follow the rules - stated by the WPS standard. - -@warning - This function is not allowed in AP or P2P modes. - -@pre - - A Wi-Fi notification callback of type (@ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback - is done through passing it to the [m2m_wifi_init](@ref m2m_wifi_init). - - The event [M2M_WIFI_REQ_WPS](@ref M2M_WIFI_REQ_WPS) must be handled in the callback to receive the WPS status. - - The WINC device MUST be in IDLE or STA mode. If AP or P2P mode is active, the WPS will not be performed. - - The [m2m_wifi_handle_events](@ref m2m_wifi_handle_events) MUST be called periodically to receive the responses in the callback. -@see - tpfAppWifiCb - m2m_wifi_init - M2M_WIFI_REQ_WPS - tenuWPSTrigger - tstrM2MWPSInfo - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet shows an example of how Wi-Fi WPS is triggered . -@code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - switch(u8WiFiEvent) - { - case M2M_WIFI_REQ_WPS: - { - tstrM2MWPSInfo *pstrWPS = (tstrM2MWPSInfo*)pvMsg; - if(pstrWPS->u8AuthType != 0) - { - printf("WPS SSID : %s\n",pstrWPS->au8SSID); - printf("WPS PSK : %s\n",pstrWPS->au8PSK); - printf("WPS SSID Auth Type : %s\n",pstrWPS->u8AuthType == M2M_WIFI_SEC_OPEN ? "OPEN" : "WPA/WPA2"); - printf("WPS Channel : %d\n",pstrWPS->u8Ch + 1); - - // establish Wi-Fi connection - m2m_wifi_connect((char*)pstrWPS->au8SSID, (uint8)m2m_strlen(pstrWPS->au8SSID), - pstrWPS->u8AuthType, pstrWPS->au8PSK, pstrWPS->u8Ch); - } - else - { - printf("(ERR) WPS Is not enabled OR Timed out\n"); - } - } - break; - - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // Trigger WPS in Push button mode. - m2m_wifi_wps(WPS_PBC_TRIGGER, NULL); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API sint8 m2m_wifi_wps(uint8 u8TriggerType,const char *pcPinNumber); - /**@}*/ -/** @defgroup WifiWpsDisableFn m2m_wifi_wps_disable - * @ingroup WLANAPI - * Disable the WINC1500 WPS operation. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_wps_disable(void); - -@pre WINC should be already in WPS mode using @ref m2m_wifi_wps - -@brief Stops the WPS ongoing session. - -@see - m2m_wifi_wps - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_wps_disable(void); - - /**@}*/ -/** @defgroup WifiP2PFn m2m_wifi_p2p - * @ingroup WLANAPI - * Asynchronous Wi-Fi direct (P2P) enabling mode function. - The WINC supports P2P in device listening mode ONLY (intent is ZERO). - The WINC P2P implementation does not support P2P GO (Group Owner) mode. - Active P2P devices (e.g. phones) could find the WINC in the search list. When a device is connected to WINC, a Wi-Fi notification event - @ref M2M_WIFI_RESP_CON_STATE_CHANGED is triggered. After a short while, the DHCP IP Address is obtained - and an event @ref M2M_WIFI_REQ_DHCP_CONF is triggered. Refer to the code examples for a more illustrative example. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_p2p(uint8 u8Channel); - -@param [in] u8Channel - P2P Listen RF channel. According to the P2P standard It must hold only one of the following values 1, 6 or 11. - -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback - is done through passing it to the @ref m2m_wifi_init. - - The events @ref M2M_WIFI_RESP_CON_STATE_CHANGED and @ref M2M_WIFI_REQ_DHCP_CONF - must be handled in the callback. - - The @ref m2m_wifi_handle_events MUST be called to receive the responses in the callback. - -@warning - This function is not allowed in AP or STA modes. - -@see - tpfAppWifiCb - m2m_wifi_init - M2M_WIFI_RESP_CON_STATE_CHANGED - M2M_WIFI_REQ_DHCP_CONF - tstrM2mWifiStateChanged - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet shown an example of how the p2p mode operates. -@code - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_CON_STATE_CHANGED: - { - tstrM2mWifiStateChanged *pstrWifiState = (tstrM2mWifiStateChanged*)pvMsg; - M2M_INFO("Wifi State :: %s :: ErrCode %d\n", pstrWifiState->u8CurrState? "CONNECTED":"DISCONNECTED",pstrWifiState->u8ErrCode); - - // Do something - } - break; - - case M2M_WIFI_REQ_DHCP_CONF: - { - uint8 *pu8IPAddress = (uint8*)pvMsg; - - printf("P2P IP Address \"%u.%u.%u.%u\"\n",pu8IPAddress[0],pu8IPAddress[1],pu8IPAddress[2],pu8IPAddress[3]); - } - break; - - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // Trigger P2P - m2m_wifi_p2p(M2M_WIFI_CH_1); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode - -*/ -NMI_API sint8 m2m_wifi_p2p(uint8 u8Channel); - /**@}*/ -/** @defgroup WifiP2PDisconnectFn m2m_wifi_p2p_disconnect - * @ingroup WLANAPI - * Disable the WINC1500 device Wi-Fi direct mode (P2P). - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_p2p_disconnect(void); -@pre - The p2p mode must have be enabled and active before a disconnect can be called. - -@see - m2m_wifi_p2p -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_p2p_disconnect(void); - /**@}*/ -/** @defgroup WifiEnableApFn m2m_wifi_enable_ap - * @ingroup WLANAPI - * Asynchronous Wi-FI hot-spot enabling function. - * The WINC supports AP mode operation with the following limitations: - - Only 1 STA could be associated at a time. - - Open and WEP are the only supported security types - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_enable_ap(CONST tstrM2MAPConfig* pstrM2MAPConfig); - -@param [in] pstrM2MAPConfig - A structure holding the AP configurations. - -@warning - This function is not allowed in P2P or STA modes. - -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback - is done through passing it to the [m2m_wifi_init](@ref m2m_wifi_init). - - The event @ref M2M_WIFI_REQ_DHCP_CONF must be handled in the callback. - - The @ref m2m_wifi_handle_events MUST be called to receive the responses in the callback. - -@see - tpfAppWifiCb - tenuM2mSecType - m2m_wifi_init - M2M_WIFI_REQ_DHCP_CONF - tstrM2mWifiStateChanged - tstrM2MAPConfig - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet demonstrates how the AP mode is enabled after the driver is initialized in the application's main function and the handling - of the event @ref M2M_WIFI_REQ_DHCP_CONF, to indicate successful connection. -@code - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - switch(u8WiFiEvent) - { - case M2M_WIFI_REQ_DHCP_CONF: - { - uint8 *pu8IPAddress = (uint8*)pvMsg; - - printf("Associated STA has IP Address \"%u.%u.%u.%u\"\n",pu8IPAddress[0],pu8IPAddress[1],pu8IPAddress[2],pu8IPAddress[3]); - } - break; - - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - tstrM2MAPConfig apConfig; - - strcpy(apConfig.au8SSID, "WINC_SSID"); - apConfig.u8ListenChannel = 1; - apConfig.u8SecType = M2M_WIFI_SEC_OPEN; - apConfig.u8SsidHide = 0; - - // IP Address - apConfig.au8DHCPServerIP[0] = 192; - apConfig.au8DHCPServerIP[1] = 168; - apConfig.au8DHCPServerIP[2] = 1; - apConfig.au8DHCPServerIP[0] = 1; - - // Trigger AP - m2m_wifi_enable_ap(&apConfig); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode - -*/ -NMI_API sint8 m2m_wifi_enable_ap(CONST tstrM2MAPConfig* pstrM2MAPConfig); - /**@}*/ -/** @defgroup WifiDisableApFn m2m_wifi_disable_ap - * @ingroup WLANAPI - * Synchronous Wi-Fi hot-spot disabling function. Must be called only when the AP is enabled through the @ref m2m_wifi_enable_ap - * function. Otherwise the call to this function will not be useful. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_disable_ap(void); -@see - m2m_wifi_enable_ap -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_disable_ap(void); - /**@}*/ -/** @defgroup SetStaticIPFn m2m_wifi_set_static_ip - * @ingroup WLANAPI - * Synchronous static IP Address configuration function. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_set_static_ip(tstrM2MIPConfig * pstrStaticIPConf); - -@param [in] pstrStaticIPConf - Pointer to a structure holding the static IP Configurations (IP, - Gateway, subnet mask and DNS address). - -@pre The application must disable auto DHCP using @ref m2m_wifi_enable_dhcp before assigning a static IP address. - -@brief Assign a static IP address to the WINC board. - This function assigns a static IP address in case the AP doesn't have a DHCP server or in case the application wants to assign - a predefined known IP address. The user must take in mind that assigning a static IP address might result in an IP address - conflict. In case of an IP address conflict observed by the WINC board the user will get a response of @ref M2M_WIFI_RESP_IP_CONFLICT - in the wifi callback. The application is then responsible to either solve the conflict or assign another IP address. -@warning - Normally this function normally should not be used. DHCP configuration is requested automatically after successful Wi-Fi connection is established. - -@see - tstrM2MIPConfig - - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_set_static_ip(tstrM2MIPConfig * pstrStaticIPConf); - - /**@}*/ -/** @defgroup RequestDHCPClientFn m2m_wifi_request_dhcp_client - * @ingroup WLANAPI - * Starts the DHCP client operation(DHCP requested by the firmware automatically in STA/AP/P2P mode). - * - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_request_dhcp_client(void); - -@warning - This function is legacy and exists only for compatability with older applications. DHCP configuration is requested automatically after successful Wi-Fi connection is established. - -@return - The function returns @ref M2M_SUCCESS always. -*/ -NMI_API sint8 m2m_wifi_request_dhcp_client(void); - /**@}*/ -/** @defgroup RequestDHCPServerFn m2m_wifi_request_dhcp_server - * @ingroup WLANAPI - * Dhcp requested by the firmware automatically in STA/AP/P2P mode). - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_request_dhcp_server(uint8* addr); - -@warning - This function is legacy and exists only for compatability with older applications. DHCP server is started automatically when enabling the AP mode. - - -@return - The function returns @ref M2M_SUCCESS always. -*/ -NMI_API sint8 m2m_wifi_request_dhcp_server(uint8* addr); - /**@}*/ -/** @defgroup WifiDHCPEnableFn m2m_wifi_enable_dhcp - * @ingroup WLANAPI - * Synchronous Wi-Fi DHCP enable function. This function Enable/Disable DHCP protocol. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_enable_dhcp(uint8 u8DhcpEn ); - -@brief - Enable/Disable the DHCP client after connection. - -@param [in] u8DhcpEn - Possible values: - 1: Enable DHCP client after connection. - 0: Disable DHCP client after connection. -@warnings - -DHCP client is enabled by default - -This Function should be called before using m2m_wifi_set_static_ip() - - -@sa - m2m_wifi_set_static_ip() - -@return - The function SHALL return @ref M2M_SUCCESS for successful operation and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_enable_dhcp(uint8 u8DhcpEn ); - /**@}*/ -/** @defgroup WifiSetScanOptionFn m2m_wifi_set_scan_options - * @ingroup WLANAPI - * Synchronous Wi-Fi scan settings function. This function sets the time configuration parameters for the scan operation. - */ - -/*! -@fn \ - sint8 m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption) - -@param [in] ptstrM2MScanOption; - Pointer to the structure holding the Scan Parameters. - -@see - tenuM2mScanCh - m2m_wifi_request_scan - tstrM2MScanOption - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption); - /**@}*/ -/** @defgroup WifiSetScanRegionFn m2m_wifi_set_scan_region - * @ingroup WLANAPI - * Synchronous wi-fi scan region setting function. - * This function sets the scan region, which will affect the range of possible scan channels. - * For 2.5GHz supported in the current release, the requested scan region can't exceed the maximum number of channels (14). - *@{*/ -/*! -@fn \ - sint8 m2m_wifi_set_scan_region(uint16 ScanRegion) - -@param [in] ScanRegion; - ASIA - NORTH_AMERICA -@see - tenuM2mScanCh - m2m_wifi_request_scan - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_set_scan_region(uint16 ScanRegion); - /**@}*/ -/** @defgroup WifiRequestScanFn m2m_wifi_request_scan -* @ingroup WLANAPI -* Asynchronous Wi-FI scan request on the given channel. The scan status is delivered in the wifi event callback and then the application -* is supposed to read the scan results sequentially. -* The number of APs found (N) is returned in event @ref M2M_WIFI_RESP_SCAN_DONE with the number of found -* APs. -* The application reads the list of APs by calling the function @ref m2m_wifi_req_scan_result N times. -* -*@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_request_scan(uint8 ch); - -@param [in] ch - RF Channel ID for SCAN operation. It should be set according to tenuM2mScanCh. - With a value of M2M_WIFI_CH_ALL(255)), means to scan all channels. - -@warning - This function is not allowed in P2P or AP modes. It works only for STA mode (both connected or disconnected states). - -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback - is done through passing it to the @ref m2m_wifi_init. - - The events @ref M2M_WIFI_RESP_SCAN_DONE and @ref M2M_WIFI_RESP_SCAN_RESULT. - must be handled in the callback. - - The @ref m2m_wifi_handle_events function MUST be called to receive the responses in the callback. - -@see - M2M_WIFI_RESP_SCAN_DONE - M2M_WIFI_RESP_SCAN_RESULT - tpfAppWifiCb - tstrM2mWifiscanResult - tenuM2mScanCh - m2m_wifi_init - m2m_wifi_handle_events - m2m_wifi_req_scan_result - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of - the events received in response. -@code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - static uint8 u8ScanResultIdx = 0; - - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_SCAN_DONE: - { - tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; - - printf("Num of AP found %d\n",pstrInfo->u8NumofCh); - if(pstrInfo->s8ScanState == M2M_SUCCESS) - { - u8ScanResultIdx = 0; - if(pstrInfo->u8NumofCh >= 1) - { - m2m_wifi_req_scan_result(u8ScanResultIdx); - u8ScanResultIdx ++; - } - else - { - printf("No AP Found Rescan\n"); - m2m_wifi_request_scan(M2M_WIFI_CH_ALL); - } - } - else - { - printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); - } - } - break; - - case M2M_WIFI_RESP_SCAN_RESULT: - { - tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; - uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); - - printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", - pstrScanResult->u8index,pstrScanResult->s8rssi, - pstrScanResult->u8AuthType, - pstrScanResult->u8ch, - pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], - pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], - pstrScanResult->au8SSID); - - if(u8ScanResultIdx < u8NumFoundAPs) - { - // Read the next scan result - m2m_wifi_req_scan_result(index); - u8ScanResultIdx ++; - } - } - break; - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // Scan all channels - m2m_wifi_request_scan(M2M_WIFI_CH_ALL); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API sint8 m2m_wifi_request_scan(uint8 ch); - - /**@}*/ -/** @defgroup WifiRequestScanFn m2m_wifi_request_scan_passive -* @ingroup WLANAPI -* Same as m2m_wifi_request_scan but perform passive scanning while the other one perform active scanning. - -* -*@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_request_scan_passive(uint8 ch, uint16 scan_time); - -@param [in] ch - RF Channel ID for SCAN operation. It should be set according to tenuM2mScanCh. - With a value of M2M_WIFI_CH_ALL(255)), means to scan all channels. - -@param [in] scan_time - The time in ms that passive scan is listening to beacons on each channel per one slot, enter 0 for deafult setting. - -@warning - This function is not allowed in P2P or AP modes. It works only for STA mode (both connected or disconnected states). - -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback - is done through passing it to the @ref m2m_wifi_init. - - The events @ref M2M_WIFI_RESP_SCAN_DONE and @ref M2M_WIFI_RESP_SCAN_RESULT. - must be handled in the callback. - - The @ref m2m_wifi_handle_events function MUST be called to receive the responses in the callback. - -@see - m2m_wifi_request_scan - M2M_WIFI_RESP_SCAN_DONE - M2M_WIFI_RESP_SCAN_RESULT - tpfAppWifiCb - tstrM2mWifiscanResult - tenuM2mScanCh - m2m_wifi_init - m2m_wifi_handle_events - m2m_wifi_req_scan_result - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_request_scan_passive(uint8 ch, uint16 scan_time); - - - /**@}*/ -/** @defgroup WifiRequestScanFn m2m_wifi_request_scan_ssid_list -* @ingroup WLANAPI -* Asynchronous wi-fi scan request on the given channel and the hidden scan list. The scan status is delivered in the wi-fi event callback and then the application -* is to read the scan results sequentially. -* The number of APs found (N) is returned in event @ref M2M_WIFI_RESP_SCAN_DONE with the number of found -* APs. -* The application could read the list of APs by calling the function @ref m2m_wifi_req_scan_result N times. -* -*@{*/ -/*! -@fn \ - NMI_API sint8 m2m_wifi_request_scan_ssid_list(uint8 ch,uint8 * u8SsidList); - -@param [in] ch - RF Channel ID for SCAN operation. It should be set according to tenuM2mScanCh. - With a value of M2M_WIFI_CH_ALL(255)), means to scan all channels. -@param [in] u8SsidList - u8SsidList is a buffer containing a list of hidden SSIDs to - include during the scan. The first byte in the buffer, u8SsidList[0], - is the number of SSIDs encoded in the string. The number of hidden SSIDs - cannot exceed MAX_HIDDEN_SITES. All SSIDs are concatenated in the following - bytes and each SSID is prefixed with a one-byte header containing its length. - The total number of bytes in u8SsidList buffer, including length byte, cannot - exceed 133 bytes (MAX_HIDDEN_SITES SSIDs x 32 bytes each, which is max SSID length). - For instance, encoding the two hidden SSIDs "DEMO_AP" and "TEST" - results in the following buffer content: -@code - uint8 u8SsidList[14]; - u8SsidList[0] = 2; // Number of SSIDs is 2 - u8SsidList[1] = 7; // Length of the string "DEMO_AP" without NULL termination - memcpy(&u8SsidList[2], "DEMO_AP", 7); // Bytes index 2-9 containing the string DEMO_AP - u8SsidList[9] = 4; // Length of the string "TEST" without NULL termination - memcpy(&u8SsidList[10], "TEST", 4); // Bytes index 10-13 containing the string TEST -@endcode - -@warning - This function is not allowed in P2P. It works only for STA/AP mode (connected or disconnected). - -@pre - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback - is done through passing it to the @ref m2m_wifi_init. - - The events @ref M2M_WIFI_RESP_SCAN_DONE and @ref M2M_WIFI_RESP_SCAN_RESULT. - must be handled in the callback. - - The @ref m2m_wifi_handle_events function MUST be called to receive the responses in the callback. - -@see - M2M_WIFI_RESP_SCAN_DONE - M2M_WIFI_RESP_SCAN_RESULT - tpfAppWifiCb - tstrM2mWifiscanResult - tenuM2mScanCh - m2m_wifi_init - m2m_wifi_handle_events - m2m_wifi_req_scan_result - -@return - The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of - the events received in response. -@code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - static void request_scan_hidden_demo_ap(void); - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - static uint8 u8ScanResultIdx = 0; - - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_SCAN_DONE: - { - tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; - - printf("Num of AP found %d\n",pstrInfo->u8NumofCh); - if(pstrInfo->s8ScanState == M2M_SUCCESS) - { - u8ScanResultIdx = 0; - if(pstrInfo->u8NumofCh >= 1) - { - m2m_wifi_req_scan_result(u8ScanResultIdx); - u8ScanResultIdx ++; - } - else - { - printf("No AP Found Rescan\n"); - request_scan_hidden_demo_ap(); - } - } - else - { - printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); - } - } - break; - - case M2M_WIFI_RESP_SCAN_RESULT: - { - tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; - uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); - - printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", - pstrScanResult->u8index,pstrScanResult->s8rssi, - pstrScanResult->u8AuthType, - pstrScanResult->u8ch, - pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], - pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], - pstrScanResult->au8SSID); - - if(u8ScanResultIdx < u8NumFoundAPs) - { - // Read the next scan result - m2m_wifi_req_scan_result(index); - u8ScanResultIdx ++; - } - } - break; - default: - break; - } - } - - static void request_scan_hidden_demo_ap(void) - { - uint8 list[9]; - char ssid[] = "DEMO_AP"; - uint8 len = (uint8)(sizeof(ssid)-1); - - list[0] = 1; - list[1] = len; - memcpy(&list[2], ssid, len); // copy 7 bytes - // Scan all channels - m2m_wifi_request_scan_ssid_list(M2M_WIFI_CH_ALL, list); - } - - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - request_scan_hidden_demo_ap(); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API sint8 m2m_wifi_request_scan_ssid_list(uint8 ch,uint8 * u8Ssidlist); - -/**@}*/ -/** @defgroup WifiGetNumAPFoundFn m2m_wifi_get_num_ap_found - * @ingroup WLANAPI -* Synchronous function to retrieve the number of AP's found in the last scan request, The function reads the number of APs from global variable which was updated in the Wi-Fi callback function through the M2M_WIFI_RESP_SCAN_DONE event. -* Function used only in STA mode only. - */ - /**@{*/ -/*! -@fn NMI_API uint8 m2m_wifi_get_num_ap_found(void); - -@see m2m_wifi_request_scan - M2M_WIFI_RESP_SCAN_DONE - M2M_WIFI_RESP_SCAN_RESULT -@pre m2m_wifi_request_scan need to be called first - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at initialization. Registering the callback - is done through passing it to the @ref m2m_wifi_init. - - The event @ref M2M_WIFI_RESP_SCAN_DONE must be handled in the callback to receive the requested scan information. -@warning This function must be called only in the wi-fi callback function when the events @ref M2M_WIFI_RESP_SCAN_DONE or @ref M2M_WIFI_RESP_SCAN_RESULT - are received. - Calling this function in any other place will result in undefined/outdated numbers. -@return Return the number of AP's found in the last Scan Request. - -\section Example - The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of - the events received in response. -@code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - static uint8 u8ScanResultIdx = 0; - - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_SCAN_DONE: - { - tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; - - printf("Num of AP found %d\n",pstrInfo->u8NumofCh); - if(pstrInfo->s8ScanState == M2M_SUCCESS) - { - u8ScanResultIdx = 0; - if(pstrInfo->u8NumofCh >= 1) - { - m2m_wifi_req_scan_result(u8ScanResultIdx); - u8ScanResultIdx ++; - } - else - { - printf("No AP Found Rescan\n"); - m2m_wifi_request_scan(M2M_WIFI_CH_ALL); - } - } - else - { - printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); - } - } - break; - - case M2M_WIFI_RESP_SCAN_RESULT: - { - tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; - uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); - - printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", - pstrScanResult->u8index,pstrScanResult->s8rssi, - pstrScanResult->u8AuthType, - pstrScanResult->u8ch, - pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], - pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], - pstrScanResult->au8SSID); - - if(u8ScanResultIdx < u8NumFoundAPs) - { - // Read the next scan result - m2m_wifi_req_scan_result(index); - u8ScanResultIdx ++; - } - } - break; - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // Scan all channels - m2m_wifi_request_scan(M2M_WIFI_CH_ALL); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API uint8 m2m_wifi_get_num_ap_found(void); -/**@}*/ -/** @defgroup WifiReqScanResult m2m_wifi_req_scan_result -* @ingroup WLANAPI -* Synchronous call to read the AP information from the SCAN Result list with the given index. -* This function is expected to be called when the response events M2M_WIFI_RESP_SCAN_RESULT or -* M2M_WIFI_RESP_SCAN_DONE are received in the wi-fi callback function. -* The response information received can be obtained through the casting to the @ref tstrM2mWifiscanResult structure - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_req_scan_result(uint8 index); -@param [in] index - Index for the requested result, the index range start from 0 till number of AP's found - -@see tstrM2mWifiscanResult - m2m_wifi_get_num_ap_found - m2m_wifi_request_scan - -@pre @ref m2m_wifi_request_scan needs to be called first, then m2m_wifi_get_num_ap_found - to get the number of AP's found - - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered at startup. Registering the callback - is done through passing it to the @ref m2m_wifi_init function. - - The event @ref M2M_WIFI_RESP_SCAN_RESULT must be handled in the callback to receive the requested scan information. -@warning Function used in STA mode only. the scan results are updated only if the scan request is called. - Calling this function only without a scan request will lead to firmware errors. - Refrain from introducing a large delay between the scan request and the scan result request, to prevent - errors occurring. - -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet demonstrates an example of how the scan request is called from the application's main function and the handling of - the events received in response. -@code - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - static uint8 u8ScanResultIdx = 0; - - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_SCAN_DONE: - { - tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*)pvMsg; - - printf("Num of AP found %d\n",pstrInfo->u8NumofCh); - if(pstrInfo->s8ScanState == M2M_SUCCESS) - { - u8ScanResultIdx = 0; - if(pstrInfo->u8NumofCh >= 1) - { - m2m_wifi_req_scan_result(u8ScanResultIdx); - u8ScanResultIdx ++; - } - else - { - printf("No AP Found Rescan\n"); - m2m_wifi_request_scan(M2M_WIFI_CH_ALL); - } - } - else - { - printf("(ERR) Scan fail with error <%d>\n",pstrInfo->s8ScanState); - } - } - break; - - case M2M_WIFI_RESP_SCAN_RESULT: - { - tstrM2mWifiscanResult *pstrScanResult =(tstrM2mWifiscanResult*)pvMsg; - uint8 u8NumFoundAPs = m2m_wifi_get_num_ap_found(); - - printf(">>%02d RI %d SEC %s CH %02d BSSID %02X:%02X:%02X:%02X:%02X:%02X SSID %s\n", - pstrScanResult->u8index,pstrScanResult->s8rssi, - pstrScanResult->u8AuthType, - pstrScanResult->u8ch, - pstrScanResult->au8BSSID[0], pstrScanResult->au8BSSID[1], pstrScanResult->au8BSSID[2], - pstrScanResult->au8BSSID[3], pstrScanResult->au8BSSID[4], pstrScanResult->au8BSSID[5], - pstrScanResult->au8SSID); - - if(u8ScanResultIdx < u8NumFoundAPs) - { - // Read the next scan result - m2m_wifi_req_scan_result(index); - u8ScanResultIdx ++; - } - } - break; - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // Scan all channels - m2m_wifi_request_scan(M2M_WIFI_CH_ALL); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode -*/ -NMI_API sint8 m2m_wifi_req_scan_result(uint8 index); -/**@}*/ -/** @defgroup WifiReqCurrentRssiFn m2m_wifi_req_curr_rssi - * @ingroup WLANAPI - * Asynchronous request for the current RSSI of the connected AP. - * The response received in through the @ref M2M_WIFI_RESP_CURRENT_RSSI event. - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_req_curr_rssi(void); -@pre - A Wi-Fi notification callback of type @ref tpfAppWifiCb MUST be implemented and registered before initialization. Registering the callback - is done through passing it to the [m2m_wifi_init](@ref m2m_wifi_init) through the @ref tstrWifiInitParam initialization structure. - - The event @ref M2M_WIFI_RESP_CURRENT_RSSI must be handled in the callback to receive the requested Rssi information. -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -\section Example - The code snippet demonstrates how the RSSI request is called in the application's main function and the handling of the event received in the callback. -@code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg) - { - static uint8 u8ScanResultIdx = 0; - - switch(u8WiFiEvent) - { - case M2M_WIFI_RESP_CURRENT_RSSI: - { - sint8 *rssi = (sint8*)pvMsg; - M2M_INFO("ch rssi %d\n",*rssi); - } - break; - default: - break; - } - } - - int main() - { - tstrWifiInitParam param; - - param.pfAppWifiCb = wifi_event_cb; - if(!m2m_wifi_init(¶m)) - { - // Scan all channels - m2m_wifi_req_curr_rssi(); - - while(1) - { - m2m_wifi_handle_events(NULL); - } - } - } - -@endcode - -*/ -NMI_API sint8 m2m_wifi_req_curr_rssi(void); -/**@}*/ -/** @defgroup WifiGetOtpMacAddFn m2m_wifi_get_otp_mac_address -* @ingroup WLANAPI -* Request the MAC address stored on the One Time Programmable(OTP) memory of the device. -* The function is blocking until the response is received. -*/ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); - -@param [out] pu8MacAddr - Output MAC address buffer of 6 bytes size. Valid only if *pu8Valid=1. -@param [out] pu8IsValid - Output boolean value to indicate the validity of pu8MacAddr in OTP. - Output zero if the OTP memory is not programmed, non-zero otherwise. -@pre m2m_wifi_init required to be called before any WIFI/socket function -@see m2m_wifi_get_mac_address - -@return The function returns @ref M2M_SUCCESS for success and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); -/**@}*/ -/** @defgroup WifiGetMacAddFn m2m_wifi_get_mac_address -* @ingroup WLANAPI -* Function to retrieve the current MAC address. The function is blocking until the response is received. -*/ -/**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr) -@param [out] pu8MacAddr - Output MAC address buffer of 6 bytes size. -@pre m2m_wifi_init required to be called before any WIFI/socket function -@see m2m_wifi_get_otp_mac_address -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr); -/**@}*/ -/** @defgroup SetSleepModeFn m2m_wifi_set_sleep_mode - * @ingroup WLANAPI - * This is one of the two synchronous power-save setting functions that - * allow the host MCU application to tweak the system power consumption. Such tweaking can be done through one of two ways: -* 1) Changing the power save mode, to one of the allowed power save modes @ref tenuPowerSaveModes. This is done by setting the first parameter -* 2) Configuring DTIM monitoring: Configuring beacon monitoring parameters by enabling or disabling the reception of broadcast/multicast data. -* this is done by setting the second parameter. - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn); -@param [in] PsTyp - Desired power saving mode. Supported types are enumerated in @ref tenuPowerSaveModes. -@param [in] BcastEn - Broadcast reception enable flag. - If it is 1, the WINC1500 will be awake each DTIM beacon for receiving broadcast traffic. - If it is 0, the WINC1500: disable broadcast traffic. Through this flag the WINC1500 will not wakeup at the DTIM beacon, but it will wakeup depends only - on the the configured Listen Interval. - -@warning The function called once after initialization. - -@see tenuPowerSaveModes - m2m_wifi_get_sleep_mode - m2m_wifi_set_lsn_int - -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn); -/**@}*/ -/** @defgroup WifiRequestSleepFn m2m_wifi_request_sleep - * @ingroup WLANAPI - * Synchronous power-save sleep request function, which requests from the WINC1500 device to sleep in the currenlty configured power save mode as defined - * by the @ref m2m_wifi_set_sleep_mode, for a specific time as defined by the passed in parameter. - * This function should be used in the @ref M2M_PS_MANUAL power save mode only. - * A wake up request is automatically performed by the WINC1500 device when any host driver API function, e.g. Wi-Fi or socket operation is called. - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_request_sleep(uint32 u32SlpReqTime); -@param [in] u32SlpReqTime - Request sleep time in ms - The best recommended sleep duration is left to be determined by the application. Taking into account that if the application sends notifications very rarely, - sleeping for a long time can be a power-efficient decision. In contrast applications that are senstive for long periods of absence can experience - performance degradation in the connection if long sleeping times are used. -@warning The function should be called in @ref M2M_PS_MANUAL power save mode only. As enumerated in @ref tenuPowerSaveModes - It's also important to note that during the sleeping time while in the M2M_PS_MANUAL mode, AP beacon monitoring is bypassed and the wifi-connection may drop if - the sleep period is enlongated. -@see tenuPowerSaveModes - m2m_wifi_set_sleep_mode - -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_request_sleep(uint32 u32SlpReqTime); -/**@}*/ -/** @defgroup GetSleepModeFn m2m_wifi_get_sleep_mode - * @ingroup WLANAPI - * Synchronous power save mode retrieval function. - */ - /**@{*/ -/*! -@fn NMI_API uint8 m2m_wifi_get_sleep_mode(void); -@see tenuPowerSaveModes - m2m_wifi_set_sleep_mode -@return The current operating power saving mode based on the enumerated sleep modes @ref tenuPowerSaveModes. -*/ -NMI_API uint8 m2m_wifi_get_sleep_mode(void); -/**@}*/ -/** @defgroup WifiReqClientCtrlFn m2m_wifi_req_client_ctrl - * @ingroup WLANAPI - * Asynchronous command sending function to the PS Client (An WINC1500 board running the ps_firmware) -* if the PS client send any command it will be received through the @ref M2M_WIFI_RESP_CLIENT_INFO event - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_req_client_ctrl(uint8 cmd); -@brief -@param [in] cmd - Control command sent from PS Server to PS Client (command values defined by the application) -@pre @ref m2m_wifi_req_server_init should be called first -@warning This mode is not supported in the current release. -@see m2m_wifi_req_server_init - M2M_WIFI_RESP_CLIENT_INFO -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_req_client_ctrl(uint8 cmd); -/**@}*/ -/** @defgroup WifiReqServerInit m2m_wifi_req_server_init - * @ingroup WLANAPI - * Synchronous function to initialize the PS Server. - * The WINC1500 supports non secure communication with another WINC1500, -* (SERVER/CLIENT) through one byte command (probe request and probe response) without any connection setup. -* The server mode can't be used with any other modes (STA/P2P/AP) -*/ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_req_server_init(uint8 ch); -@param [in] ch - Server listening channel -@see m2m_wifi_req_client_ctrl -@warning This mode is not supported in the current release. -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_req_server_init(uint8 ch); -/**@}*/ -/** @defgroup WifiSetDeviceNameFn m2m_wifi_set_device_name - * @ingroup WLANAPI - * Sets the WINC device name. The name string is used as a device name in both (P2P) WiFi-Direct mode as well as DHCP hostname (option 12). - * For P2P devices to communicate a device name must be present. If it is not set through this function a default name is assigned. - * The default name is WINC-XX-YY, where XX and YY are the last 2 octets of the OTP MAC address. If OTP (eFuse) is programmed, - * then the default name is WINC-00-00. - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength); -@param [in] pu8DeviceName - A Buffer holding the device name. Device name is a null terminated C string. -@param [in] u8DeviceNameLength - The length of the device name. Should not exceed the maximum device name's length @ref M2M_DEVICE_NAME_MAX (including null character). -@warning The function called once after initialization. - Used for the Wi-Fi Direct (P2P) as well as DHCP client hostname option (12). -@warning Device name shall contain only characters allowed in valid internet host name as defined in RFC 952 and 1123. -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength); -/**@}*/ -/** @defgroup WifiSetLsnIntFn m2m_wifi_set_lsn_int - * @ingroup WLANAPI -* This is one of the two synchronous power-save setting functions that -* allow the host MCU application to tweak the system power consumption. Such tweaking can be done by modifying the -* the Wi-Fi listen interval. The listen interval is how many beacon periods the station can sleep before it wakes up to receive data buffer in AP. -* It is represented in units of AP beacon periods(100ms). -*/ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt * pstrM2mLsnInt); - -@param [in] pstrM2mLsnInt - Structure holding the listen interval configurations. -@pre Function @m2m_wifi_set_sleep_mode shall be called first, to set the power saving mode required. -@warning The function should be called once after initialization. -@see tstrM2mLsnInt - m2m_wifi_set_sleep_mode -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*/ -NMI_API sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt *pstrM2mLsnInt); -/**@}*/ -/** @defgroup WifiEnableMonitorModeFn m2m_wifi_enable_monitoring_mode - * @ingroup WLANAPI - * Asynchronous Wi-Fi monitoring mode (Promiscuous mode) enabling function. This function enables the monitoring mode, thus allowing two operations to be performed: - * 1) Transmission of manually configured frames, through using the @ref m2m_wifi_send_wlan_pkt function. - * 2) Reception of frames based on a defined filtering criteria - * When the monitoring mode is enabled, reception of all frames that satisfy the filter criteria passed in as a parameter is allowed, on the current wireless channel \n. - * All packets that meet the filtering criteria are passed to the application layer, to be handled by the assigned monitoring callback function \n. - * The monitoring callback function must be implemented before starting the monitoring mode, in-order to handle the packets received \n. - * Registering of the implemented callback function is through the callback pointer @ref tpfAppMonCb in the @ref tstrWifiInitParam structure\n. - * passed to @ref m2m_wifi_init function at initialization. - * - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_enable_monitoring_mode(tstrM2MWifiMonitorModeCtrl *, uint8 *, uint16 , uint16); - * @param [in] pstrMtrCtrl - * Pointer to @ref tstrM2MWifiMonitorModeCtrl structure holding the filtering parameters. - * @param [in] pu8PayloadBuffer - * Pointer to a buffer allocated by the application. The buffer SHALL hold the Data field of - * the WIFI RX Packet (Or a part from it). If it is set to NULL, the WIFI data payload will - * be discarded by the monitoring driver. - * @param [in] u16BufferSize - * The total size of the pu8PayloadBuffer in bytes. - * @param [in] u16DataOffset - * Starting offset in the DATA FIELD of the received WIFI packet. The application may be interested - * in reading specific information from the received packet. It must assign the offset to the starting - * position of it relative to the DATA payload start.\n - * \e Example, \e if \e the \e SSID \e is \e needed \e to \e be \e read \e from \e a \e PROBE \e REQ \e packet, \e the \e u16Offset \e MUST \e be \e set \e to \e 0. - * @warning When This mode is enabled, you can not be connected in any mode (Station, Access Point, or P2P).\n - * @see tstrM2MWifiMonitorModeCtrl - tstrM2MWifiRxPacketInfo - tstrWifiInitParam - tenuM2mScanCh - m2m_wifi_disable_monitoring_mode - m2m_wifi_send_wlan_pkt - m2m_wifi_send_ethernet_pkt - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - -*\section Example -* The example demonstrates the main function where-by the monitoring enable function is called after the initialization of the driver and the packets are -* handled in the callback function. -* @code - - #include "m2m_wifi.h" - #include "m2m_types.h" - - //Declare receive buffer - uint8 gmgmt[1600]; - - //Callback functions - void wifi_cb(uint8 u8WiFiEvent, void * pvMsg) - { - ; - } - void wifi_monitoring_cb(tstrM2MWifiRxPacketInfo *pstrWifiRxPacket, uint8 *pu8Payload, uint16 u16PayloadSize) - { - if((NULL != pstrWifiRxPacket) && (0 != u16PayloadSize)) { - if(MANAGEMENT == pstrWifiRxPacket->u8FrameType) { - M2M_INFO("***# MGMT PACKET #***\n"); - } else if(DATA_BASICTYPE == pstrWifiRxPacket->u8FrameType) { - M2M_INFO("***# DATA PACKET #***\n"); - } else if(CONTROL == pstrWifiRxPacket->u8FrameType) { - M2M_INFO("***# CONTROL PACKET #***\n"); - } - } - } - - int main() - { - //Register wifi_monitoring_cb - tstrWifiInitParam param; - param.pfAppWifiCb = wifi_cb; - param.pfAppMonCb = wifi_monitoring_cb; - - nm_bsp_init(); - - if(!m2m_wifi_init(¶m)) { - //Enable Monitor Mode with filter to receive all data frames on channel 1 - tstrM2MWifiMonitorModeCtrl strMonitorCtrl = {0}; - strMonitorCtrl.u8ChannelID = M2M_WIFI_CH_1; - strMonitorCtrl.u8FrameType = DATA_BASICTYPE; - strMonitorCtrl.u8FrameSubtype = M2M_WIFI_FRAME_SUB_TYPE_ANY; //Receive any subtype of data frame - m2m_wifi_enable_monitoring_mode(&strMonitorCtrl, gmgmt, sizeof(gmgmt), 0); - - while(1) { - m2m_wifi_handle_events(NULL); - } - } - return 0; - } - * @endcode - */ -NMI_API sint8 m2m_wifi_enable_monitoring_mode(tstrM2MWifiMonitorModeCtrl *pstrMtrCtrl, uint8 *pu8PayloadBuffer, - uint16 u16BufferSize, uint16 u16DataOffset); -/**@}*/ -/** @defgroup WifiDisableMonitorModeFn m2m_wifi_disable_monitoring_mode - * @ingroup WLANAPI - * Synchronous function to disable Wi-Fi monitoring mode (Promiscuous mode). Expected to be called, if the enable monitoring mode is set, but if it was called without enabling - * no negative impact will reside. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_disable_monitoring_mode(void); - * @see m2m_wifi_enable_monitoring_mode - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_disable_monitoring_mode(void); - /**@}*/ - /** @defgroup SendWlanPktFn m2m_wifi_send_wlan_pkt - * @ingroup WLANAPI - * Synchronous function to transmit a WIFI RAW packet while the implementation of this packet is left to the application developer. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_send_wlan_pkt(uint8 *, uint16, uint16); - - * @param [in] pu8WlanPacket - * Pointer to a buffer holding the whole WIFI frame. - * @param [in] u16WlanHeaderLength - * The size of the WIFI packet header ONLY. - * @param [in] u16WlanPktSize - * The size of the whole bytes in packet. - * @see m2m_wifi_enable_monitoring_mode - m2m_wifi_disable_monitoring_mode - * @pre Enable Monitoring mode first using @ref m2m_wifi_enable_monitoring_mode - * @warning This function available in monitoring mode ONLY.\n - * @note Packets are user's responsibility. - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_send_wlan_pkt(uint8 *pu8WlanPacket, uint16 u16WlanHeaderLength, uint16 u16WlanPktSize); -/**@}*/ -/** @defgroup WifiSendEthernetPktFn m2m_wifi_send_ethernet_pkt - * @ingroup WLANAPI - * Synchronous function to transmit an Ethernet packet. Transmit a packet directly in ETHERNET/bypass mode where the TCP/IP stack is disabled and the implementation of this packet is left to the application developer. - * The Ethernet packet composition is left to the application developer. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_send_ethernet_pkt(uint8* pu8Packet,uint16 u16PacketSize) - * @param [in] pu8Packet - * Pointer to a buffer holding the whole Ethernet frame. - * @param [in] u16PacketSize - * The size of the whole bytes in packet. - * @warning This function available in ETHERNET/Bypass mode ONLY. Make sure that application defines @ref ETH_MODE.\n - * @note Packets are the user's responsibility. - * @sa m2m_wifi_enable_mac_mcast,m2m_wifi_set_receive_buffer - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - - */ -NMI_API sint8 m2m_wifi_send_ethernet_pkt(uint8* pu8Packet,uint16 u16PacketSize); -/**@}*/ -/** @defgroup WifiEnableSntpFn m2m_wifi_enable_sntp - * @ingroup WLANAPI - * Synchronous function to enable/disable the native Simple Network Time Protocol(SNTP) client in the WINC1500 firmware.\n - * The SNTP is enabled by default at start-up.The SNTP client at firmware is used to synchronize the system clock to the UTC time from the well known time - * servers (e.g. "time-c.nist.gov"). The SNTP client uses a default update cycle of 1 day. - * The UTC is important for checking the expiration date of X509 certificates used while establishing - * TLS (Transport Layer Security) connections. - * It is highly recommended to use it if there is no other means to get the UTC time. If there is a RTC - * on the host MCU, the SNTP could be disabled and the host should set the system time to the firmware - * using the @ref m2m_wifi_set_system_time function. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_enable_sntp(uint8); - * @param [in] bEnable -* Enabling/Disabling flag - * '0' :disable SNTP - * '1' :enable SNTP - * @see m2m_wifi_set_sytem_time - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_enable_sntp(uint8 bEnable); -/**@}*/ -/** @defgroup WifiSetSystemTime m2m_wifi_set_sytem_time - * @ingroup WLANAPI - * Synchronous function for setting the system time in time/date format (@ref uint32).\n - * The @ref tstrSystemTime structure can be used as a reference to the time values that should be set and pass its value as @ref uint32 - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_set_sytem_time(uint32); - * @param [in] u32UTCSeconds - * Seconds elapsed since January 1, 1900 (NTP Timestamp). - * @see m2m_wifi_enable_sntp - * tstrSystemTime - * @note If there is an RTC on the host MCU, the SNTP could be disabled and the host should set the system time to the firmware - * using the API @ref m2m_wifi_set_sytem_time. - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_set_sytem_time(uint32 u32UTCSeconds); -/**@}*/ -/** @defgroup WifiGetSystemTime m2m_wifi_get_sytem_time - * @ingroup WLANAPI - * Asynchronous function used to retrieve the system time through the use of the response @ref M2M_WIFI_RESP_GET_SYS_TIME. - * Response time retrieved is parsed into the members defined in the structure @ref tstrSystemTime. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_get_sytem_time(void); - * @see m2m_wifi_enable_sntp - tstrSystemTime - * @note Get the system time from the SNTP client - * using the API @ref m2m_wifi_get_sytem_time. - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_get_sytem_time(void); -/**@}*/ -/** @defgroup WifiSetCustInfoElementFn m2m_wifi_set_cust_InfoElement - * @ingroup WLANAPI - * Synchronous function to Add/Remove user-defined Information Element to the WIFIBeacon and Probe Response frames while chip mode is Access Point Mode.\n - * According to the information element layout shown bellow, if it is required to set new data for the information elements, pass in the buffer with the - * information according to the sizes and ordering defined bellow. However, if it's required to delete these IEs, fill the buffer with zeros. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_set_cust_InfoElement(uint8*); - * @param [in] pau8M2mCustInfoElement - * Pointer to Buffer containing the IE to be sent. It is the application developer's responsibility to ensure on the correctness of the information element's ordering passed in. - * @warning - Size of All elements combined must not exceed 255 byte.\n - * - Used in Access Point Mode \n - * @note IEs Format will be follow the following layout:\n - * @verbatim - --------------- ---------- ---------- ------------------- -------- -------- ----------- ---------------------- - | Byte[0] | Byte[1] | Byte[2] | Byte[3:length1+2] | ..... | Byte[n] | Byte[n+1] | Byte[n+2:lengthx+2] | - |---------------|----------|----------|-------------------|-------- --------|-----------|------------------| - | #of all Bytes | IE1 ID | Length1 | Data1(Hex Coded) | ..... | IEx ID | Lengthx | Datax(Hex Coded) | - --------------- ---------- ---------- ------------------- -------- -------- ----------- ---------------------- - * @endverbatim - * @see m2m_wifi_enable_sntp - * tstrSystemTime - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - \section Example - The example demonstrates how the information elements are set using this function. - *@code - * - char elementData[21]; - static char state = 0; // To Add, Append, and Delete - if(0 == state) { //Add 3 IEs - state = 1; - //Total Number of Bytes - elementData[0]=12; - //First IE - elementData[1]=200; elementData[2]=1; elementData[3]='A'; - //Second IE - elementData[4]=201; elementData[5]=2; elementData[6]='B'; elementData[7]='C'; - //Third IE - elementData[8]=202; elementData[9]=3; elementData[10]='D'; elementData[11]=0; elementData[12]='F'; - } else if(1 == state) { - //Append 2 IEs to others, Notice that we keep old data in array starting with\n - //element 13 and total number of bytes increased to 20 - state = 2; - //Total Number of Bytes - elementData[0]=20; - //Fourth IE - elementData[13]=203; elementData[14]=1; elementData[15]='G'; - //Fifth IE - elementData[16]=204; elementData[17]=3; elementData[18]='X'; elementData[19]=5; elementData[20]='Z'; - } else if(2 == state) { //Delete All IEs - state = 0; - //Total Number of Bytes - elementData[0]=0; - } - m2m_wifi_set_cust_InfoElement(elementData); - * @endcode - */ -NMI_API sint8 m2m_wifi_set_cust_InfoElement(uint8* pau8M2mCustInfoElement); - /**@}*/ -/** @defgroup WifiSetPowerProfile m2m_wifi_set_power_profile - * @ingroup WLANAPI - * Change the power profile mode - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode); -@brief -@param [in] u8PwrMode - Change the WINC1500 power profile to different mode based on the enumeration - @ref tenuM2mPwrMode -@pre Must be called after the initializations and before any connection request and can't be changed in run time. -@sa tenuM2mPwrMode - m2m_wifi_init -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode); - /**@}*/ - /** @defgroup WifiSetTxPower m2m_wifi_set_tx_power - * @ingroup WLANAPI - * Set the TX power tenuM2mTxPwrLevel - */ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel); -@param [in] u8TxPwrLevel - change the TX power based on the enumeration tenuM2mTxPwrLevel -@pre Must be called after the initialization and before any connection request and can't be changed in runtime. -@sa tenuM2mTxPwrLevel - m2m_wifi_init -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel); - /**@}*/ -/** @defgroup WifiEnableFirmware m2m_wifi_enable_firmware_logs -* @ingroup WLANAPI -* Enable or Disable logs in run time (Disabling Firmware logs will -* enhance the firmware start-up time and performance) -*/ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable); -@param [in] u8Enable - Set 1 to enable the logs, 0 for disable -@pre Must be called after intialization through the following function @ref m2m_wifi_init -@sa __DISABLE_FIRMWARE_LOGS__ (build option to disable logs from initializations) - m2m_wifi_init -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable); - /**@}*/ - /** @defgroup WifiSetBatteryVoltage m2m_wifi_set_battery_voltage -* @ingroup WLANAPI -* Set the battery voltage to update the firmware calculations -*/ - /**@{*/ -/*! -@fn NMI_API sint8 m2m_wifi_set_battery_voltage(uint8 u8BattVolt) -@brief Set the battery voltage to update the firmware calculations -@param [in] dbBattVolt - Battery Volt in double -@pre Must be called after intialization through the following function @ref m2m_wifi_init -@sa m2m_wifi_init -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -sint8 m2m_wifi_set_battery_voltage(uint16 u16BattVoltx100); - /**@}*/ - /** @defgroup WifiSetGains m2m_wifi_set_gains -* @ingroup WLANAPI -* Set the chip gains mainly (PPA for 11b/11gn) -*/ - /**@{*/ -/*! -@fn sint8 m2m_wifi_set_gains(tstrM2mWifiGainsParams* pstrM2mGain); -@brief Set the chip PPA gain for 11b/11gn -@param [in] pstrM2mGain - tstrM2mWifiGainsParams contain gain parmaters as implemnted in rf document -@pre Must be called after intialization through the following function @ref m2m_wifi_init -@sa m2m_wifi_init -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -sint8 m2m_wifi_set_gains(tstrM2mWifiGainsParams* pstrM2mGain); - /**@}*/ -/** @defgroup WifiGetFirmwareVersion m2m_wifi_get_firmware_version -* @ingroup WLANAPI -* Get Firmware version info as defined in the structure @ref tstrM2mRev. -*/ - /**@{*/ -/*! -@fn m2m_wifi_get_firmware_version(tstrM2mRev* pstrRev) -@param [out] M2mRev - Pointer to the structure @ref tstrM2mRev that contains the firmware version parameters -@pre Must be called after intialization through the following function @ref m2m_wifi_init -@sa m2m_wifi_init -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -sint8 m2m_wifi_get_firmware_version(tstrM2mRev *pstrRev); -/**@}*/ -#ifdef ETH_MODE -/** @defgroup WifiEnableMacMcastFn m2m_wifi_enable_mac_mcast - * @ingroup WLANAPI - * Synchronous function for filtering received MAC addresses from certain MAC address groups. - * This function allows the addtion/removal of certain MAC addresses, used in the multicast filter. - */ - /**@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8 *, uint8); - * @brief - * @param [in] pu8MulticastMacAddress - * Pointer to MAC address - * @param [in] u8AddRemove - * A flag to add or remove the MAC ADDRESS, based on the following values: - * - 0 : remove MAC address - * - 1 : add MAC address - * @warning This function is available in ETHERNET/bypass mode ONLY. Make sure that the application defines @ref ETH_MODE.\n - * @note Maximum number of MAC addresses that could be added is 8. - * @sa m2m_wifi_set_receive_buffer, m2m_wifi_send_ethernet_pkt - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8* pu8MulticastMacAddress, uint8 u8AddRemove); -/**@}*/ -/** @defgroup SetReceiveBufferFn m2m_wifi_set_receive_buffer - * @ingroup WLANAPI - * Synchronous function for setting or modifying the receiver buffer's length. - * In the ETHERNET/bypass mode the application should define a callback of type @ref tpfAppEthCb, through which the application handles the received - * ethernet frames. It is through this callback function that the user can dynamically modify the length of the currently used receiver buffer. - *@{*/ -/*! - * @fn NMI_API sint8 m2m_wifi_set_receive_buffer(void *, uint16); - - * @param [in] pvBuffer - * Pointer to Buffer to receive data. - * NULL pointer causes a negative error @ref M2M_ERR_FAIL. - * - * @param [in] u16BufferLen - * Length of data to be received. Maximum length of data should not exceed the size defined by TCP/IP - * defined as @ref SOCKET_BUFFER_MAX_LENGTH - * - * @warning This function is available in the Ethernet/bypass mode ONLY. Make sure that the application defines @ref ETH_MODE.\n - * @sa m2m_wifi_enable_mac_mcast,m2m_wifi_send_ethernet_pkt - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -NMI_API sint8 m2m_wifi_set_receive_buffer(void* pvBuffer,uint16 u16BufferLen); -/**@}*/ -#endif /* ETH_MODE */ -/** @defgroup GetPrngBytes m2m_wifi_prng_get_random_bytes - * @ingroup WLANAPI - * Asynchronous function for retrieving from the firmware a pseudo-random set of bytes as specifed in the size passed in as a parameter. - * The registered wifi-cb function retrieves the random bytes through the response @ref M2M_WIFI_RESP_GET_PRNG - *@{*/ -/*! - * @fn sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PRNGBuff,uint16 u16PRNGSize) - * @param [out] pu8PrngBuff - * Pointer to a buffer to receive data. - * @param [in] u16PrngSize - * Request size in bytes - *@warning Size greater than the maximum specified (@ref M2M_BUFFER_MAX_SIZE - sizeof(tstrPrng)) - * causes a negative error @ref M2M_ERR_FAIL. - *@see tstrPrng - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PrngBuff,uint16 u16PrngSize); -/**@}*/ -#ifdef __cplusplus -} -#endif -#endif /* __M2M_WIFI_H__ */ - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ate_mode.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ate_mode.c deleted file mode 100644 index beb1af8..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ate_mode.c +++ /dev/null @@ -1,826 +0,0 @@ -/** - * - * \file - * - * \brief NMC1500 Peripherials Application Interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifdef _M2M_ATE_FW_ -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#include "driver/include/m2m_ate_mode.h" -#include "driver/source/nmasic.h" -#include "driver/source/nmdrv.h" -#include "m2m_hif.h" -#include "driver/source/nmbus.h" -#include "bsp/include/nm_bsp.h" - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#define rInterrupt_CORTUS_0 (0x10a8) -#define rInterrupt_CORTUS_1 (0x10ac) -#define rInterrupt_CORTUS_2 (0x10b0) - -#define rBurstTx_NMI_TX_RATE (0x161d00) -#define rBurstTx_NMI_NUM_TX_FRAMES (0x161d04) -#define rBurstTx_NMI_TX_FRAME_LEN (0x161d08) -#define rBurstTx_NMI_TX_CW_PARAM (0x161d0c) -#define rBurstTx_NMI_TX_GAIN (0x161d10) -#define rBurstTx_NMI_TX_DPD_CTRL (0x161d14) -#define rBurstTx_NMI_USE_PMU (0x161d18) -#define rBurstTx_NMI_TEST_CH (0x161d1c) -#define rBurstTx_NMI_TX_PHY_CONT (0x161d20) -#define rBurstTx_NMI_TX_CW_MODE (0x161d24) -#define rBurstTx_NMI_TEST_XO_OFF (0x161d28) -#define rBurstTx_NMI_USE_EFUSE_XO_OFF (0x161d2c) - -#define rBurstTx_NMI_MAC_FILTER_ENABLE_DA (0x161d30) -#define rBurstTx_NMI_MAC_ADDR_LO_PEER (0x161d34) -#define rBurstTx_NMI_MAC_ADDR_LO_SELF (0x161d38) -#define rBurstTx_NMI_MAC_ADDR_HI_PEER (0x161d3c) -#define rBurstTx_NMI_MAC_ADDR_HI_SELF (0x161d40) -#define rBurstTx_NMI_RX_PKT_CNT_SUCCESS (0x161d44) -#define rBurstTx_NMI_RX_PKT_CNT_FAIL (0x161d48) -#define rBurstTx_NMI_SET_SELF_MAC_ADDR (0x161d4c) -#define rBurstTx_NMI_MAC_ADDR_LO_SA (0x161d50) -#define rBurstTx_NMI_MAC_ADDR_HI_SA (0x161d54) -#define rBurstTx_NMI_MAC_FILTER_ENABLE_SA (0x161d58) - -#define rBurstRx_NMI_RX_ALL_PKTS_CONT (0x9898) -#define rBurstRx_NMI_RX_ERR_PKTS_CONT (0x988c) - -#define TX_DGAIN_MAX_NUM_REGS (4) -#define TX_DGAIN_REG_BASE_ADDRESS (0x1240) -#define TX_GAIN_CODE_MAX_NUM_REGS (3) -#define TX_GAIN_CODE_BASE_ADDRESS (0x1250) -#define TX_PA_MAX_NUM_REGS (3) -#define TX_PA_BASE_ADDRESS (0x1e58) -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -VARIABLES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -volatile static uint8 gu8AteIsRunning = 0; /*!< ATE firmware status, 1 means ATE is running otherwise stopped */ -volatile static uint8 gu8RxState = 0; /*!< RX status, 1 means Rx is running otherwise stopped */ -volatile static uint8 gu8TxState = 0; /*!< TX status, 1 means Tx is running otherwise stopped */ -volatile static uint32 gaAteFwTxRates[M2M_ATE_MAX_NUM_OF_RATES] = -{ - 0x01, 0x02, 0x05, 0x0B, /*B-Rats*/ - 0x06, 0x09, 0x0C, 0x12, 0x18, 0x24, 0x30, 0x36, /*G-Rats*/ - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87 /*N-Rats*/ -}; - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -STATIC FUNCTIONS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -static void m2m_ate_set_rx_status(uint8 u8Value) -{ - gu8RxState = u8Value; -} - -static void m2m_ate_set_tx_status(uint8 u8Value) -{ - gu8TxState = u8Value; -} - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION IMPLEMENTATION -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/*! -@fn \ - sint8 m2m_ate_init(void); - -@brief - This function used to download ATE firmware from flash and start it - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_init(void) -{ - sint8 s8Ret = M2M_SUCCESS; - uint8 u8WifiMode = M2M_WIFI_MODE_ATE_HIGH; - - s8Ret = nm_drv_init(&u8WifiMode); - - return s8Ret; -} - -/*! -@fn \ - sint8 m2m_ate_init(tstrM2mAteInit *pstrInit); - -@brief - This function used to download ATE firmware from flash and start it - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_init_param(tstrM2mAteInit *pstrInit) -{ - sint8 s8Ret = M2M_SUCCESS; - - s8Ret = nm_drv_init((void*)&pstrInit->u8RxPwrMode); - - return s8Ret; -} - -/*! -@fn \ - sint8 m2m_ate_deinit(void); - -@brief - De-Initialization of ATE firmware mode - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_deinit(void) -{ - return nm_drv_deinit(NULL); -} - -/*! -@fn \ - sint8 m2m_ate_set_fw_state(uint8); - -@brief - This function used to change ATE firmware status from running to stopped or vice versa. - -@param [in] u8State - Required state of ATE firmware, one of \ref tenuM2mAteFwState enumeration values. -@return - The function SHALL return 0 for success and a negative value otherwise. -\sa - m2m_ate_init -*/ -sint8 m2m_ate_set_fw_state(uint8 u8State) -{ - sint8 s8Ret = M2M_SUCCESS; - uint32_t u32Val = 0; - - if((M2M_ATE_FW_STATE_STOP == u8State) && (M2M_ATE_FW_STATE_STOP != gu8AteIsRunning)) - { - u32Val = nm_read_reg(rNMI_GLB_RESET); - u32Val &= ~(1 << 10); - s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val); - gu8AteIsRunning = M2M_ATE_FW_STATE_STOP; - } - else if((M2M_ATE_FW_STATE_RUN == u8State) && (M2M_ATE_FW_STATE_RUN != gu8AteIsRunning)) - { - /* 0x1118[0]=0 at power-on-reset: pad-based control. */ - /* Switch cortus reset register to register control. 0x1118[0]=1. */ - u32Val = nm_read_reg(rNMI_BOOT_RESET_MUX); - u32Val |= (1 << 0); - s8Ret = nm_write_reg(rNMI_BOOT_RESET_MUX, u32Val); - if(M2M_SUCCESS != s8Ret) - { - goto __EXIT; - } - /** - Write the firmware download complete magic value 0x10ADD09E at - location 0xFFFF000C (Cortus map) or C000C (AHB map). - This will let the boot-rom code execute from RAM. - **/ - s8Ret = nm_write_reg(0xc0000, 0x71); - if(M2M_SUCCESS != s8Ret) - { - goto __EXIT; - } - - u32Val = nm_read_reg(rNMI_GLB_RESET); - if((u32Val & (1ul << 10)) == (1ul << 10)) - { - u32Val &= ~(1ul << 10); - s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val); - if(M2M_SUCCESS != s8Ret) - { - goto __EXIT; - } - } - - u32Val |= (1ul << 10); - s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val); - if(M2M_SUCCESS != s8Ret) - { - goto __EXIT; - } - gu8AteIsRunning = M2M_ATE_FW_STATE_RUN; - } - else - { - s8Ret = M2M_ATE_ERR_UNHANDLED_CASE; - } - -__EXIT: - if((M2M_SUCCESS == s8Ret) && (M2M_ATE_FW_STATE_RUN == gu8AteIsRunning)) - { - nm_bsp_sleep(500); /*wait for ATE firmware start up*/ - } - return s8Ret; -} - -/*! -@fn \ - sint8 m2m_ate_get_fw_state(uint8); - -@brief - This function used to return status of ATE firmware. - -@return - The function SHALL return status of ATE firmware, one of \ref tenuM2mAteFwState enumeration values. -\sa - m2m_ate_init, m2m_ate_set_fw_state -*/ -sint8 m2m_ate_get_fw_state(void) -{ - return gu8AteIsRunning; -} - -/*! -@fn \ - uint32 m2m_ate_get_tx_rate(uint8); - -@brief - This function used to return value of TX rate required by application developer. - -@param [in] u8Index - Index of required rate , one of \ref tenuM2mAteTxIndexOfRates enumeration values. -@return - The function SHALL return 0 for in case of failure otherwise selected rate value. -\sa - tenuM2mAteTxIndexOfRates -*/ -uint32 m2m_ate_get_tx_rate(uint8 u8Index) -{ - if(M2M_ATE_MAX_NUM_OF_RATES <= u8Index) - { - return 0; - } - return gaAteFwTxRates[u8Index]; -} - -/*! -@fn \ - sint8 m2m_ate_get_tx_status(void); - -@brief - This function used to return status of TX test case either running or stopped. - -@return - The function SHALL return status of ATE firmware, 1 if TX is running otherwise 0. -\sa - m2m_ate_start_tx, m2m_ate_stop_tx -*/ -sint8 m2m_ate_get_tx_status(void) -{ - return gu8TxState; -} - -/*! -@fn \ - sint8 m2m_ate_start_tx(tstrM2mAteTx *) - -@brief - This function used to start TX test case. - -@param [in] strM2mAteTx - Type of \ref tstrM2mAteTx, with the values required to enable TX test case. You must use \ref m2m_ate_init first. -@return - The function SHALL return 0 for success and a negative value otherwise. -\sa - m2m_ate_init, m2m_ate_stop_tx, m2m_ate_get_tx_status -*/ -sint8 m2m_ate_start_tx(tstrM2mAteTx * strM2mAteTx) -{ - sint8 s8Ret = M2M_SUCCESS; - uint8 u8LoopCntr = 0; - uint32_t val32; - - - if(NULL == strM2mAteTx) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - if(0 != m2m_ate_get_tx_status()) - { - s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING; - goto __EXIT; - } - - if(0 != m2m_ate_get_rx_status()) - { - s8Ret = M2M_ATE_ERR_RX_ALREADY_RUNNING; - goto __EXIT; - } - - if( (strM2mAteTx->channel_num < M2M_ATE_CHANNEL_1) || - (strM2mAteTx->channel_num > M2M_ATE_CHANNEL_14) || - (strM2mAteTx->tx_gain_sel < M2M_ATE_TX_GAIN_DYNAMIC) || - (strM2mAteTx->tx_gain_sel > M2M_ATE_TX_GAIN_TELEC) || - (strM2mAteTx->frame_len > M2M_ATE_MAX_FRAME_LENGTH) || - (strM2mAteTx->frame_len < M2M_ATE_MIN_FRAME_LENGTH) - ) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - if( (strM2mAteTx->duty_cycle < M2M_ATE_TX_DUTY_MAX_VALUE /*1*/) || - (strM2mAteTx->duty_cycle > M2M_ATE_TX_DUTY_MIN_VALUE /*10*/ ) || - (strM2mAteTx->dpd_ctrl < M2M_ATE_TX_DPD_DYNAMIC) || - (strM2mAteTx->dpd_ctrl > M2M_ATE_TX_DPD_ENABLED) || - (strM2mAteTx->use_pmu > M2M_ATE_PMU_ENABLE) || - (strM2mAteTx->phy_burst_tx < M2M_ATE_TX_SRC_MAC) || - (strM2mAteTx->phy_burst_tx > M2M_ATE_TX_SRC_PHY) || - (strM2mAteTx->cw_tx < M2M_ATE_TX_MODE_NORM) || - (strM2mAteTx->cw_tx > M2M_ATE_TX_MODE_CW) - ) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - for(u8LoopCntr=0; u8LoopCntrdata_rate) - { - break; - } - } - - if(M2M_ATE_MAX_NUM_OF_RATES == u8LoopCntr) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - - - s8Ret += nm_write_reg(rBurstTx_NMI_USE_PMU, strM2mAteTx->use_pmu); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_PHY_CONT, strM2mAteTx->phy_burst_tx); - s8Ret += nm_write_reg(rBurstTx_NMI_NUM_TX_FRAMES, strM2mAteTx->num_frames); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_GAIN, strM2mAteTx->tx_gain_sel); - s8Ret += nm_write_reg(rBurstTx_NMI_TEST_CH, strM2mAteTx->channel_num); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_FRAME_LEN, strM2mAteTx->frame_len); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_CW_PARAM, strM2mAteTx->duty_cycle); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_DPD_CTRL, strM2mAteTx->dpd_ctrl); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_RATE, strM2mAteTx->data_rate); - s8Ret += nm_write_reg(rBurstTx_NMI_TX_CW_MODE, strM2mAteTx->cw_tx); - s8Ret += nm_write_reg(rBurstTx_NMI_TEST_XO_OFF, strM2mAteTx->xo_offset_x1000); - s8Ret += nm_write_reg(rBurstTx_NMI_USE_EFUSE_XO_OFF, strM2mAteTx->use_efuse_xo_offset); - - val32 = strM2mAteTx->peer_mac_addr[5] << 0; - val32 |= strM2mAteTx->peer_mac_addr[4] << 8; - val32 |= strM2mAteTx->peer_mac_addr[3] << 16; - nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_PEER, val32 ); - - val32 = strM2mAteTx->peer_mac_addr[2] << 0; - val32 |= strM2mAteTx->peer_mac_addr[1] << 8; - val32 |= strM2mAteTx->peer_mac_addr[0] << 16; - nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_PEER, val32 ); - - if(M2M_SUCCESS == s8Ret) - { - s8Ret += nm_write_reg(rInterrupt_CORTUS_0, 1); /*Interrupt Cortus*/ - m2m_ate_set_tx_status(1); - nm_bsp_sleep(200); /*Recommended*/ - } - -__EXIT: - return s8Ret; -} - -/*! -@fn \ - sint8 m2m_ate_stop_tx(void) - -@brief - This function used to stop TX test case. - -@return - The function SHALL return 0 for success and a negative value otherwise. -\sa - m2m_ate_init, m2m_ate_start_tx, m2m_ate_get_tx_status -*/ -sint8 m2m_ate_stop_tx(void) -{ - sint8 s8Ret = M2M_SUCCESS; - - s8Ret = nm_write_reg(rInterrupt_CORTUS_1, 1); - if(M2M_SUCCESS == s8Ret) - { - m2m_ate_set_tx_status(0); - } - - return s8Ret; -} - -/*! -@fn \ - sint8 m2m_ate_get_rx_status(uint8); - -@brief - This function used to return status of RX test case either running or stopped. - -@return - The function SHALL return status of ATE firmware, 1 if RX is running otherwise 0. -\sa - m2m_ate_start_rx, m2m_ate_stop_rx -*/ -sint8 m2m_ate_get_rx_status(void) -{ - return gu8RxState; -} - -/*! -@fn \ - sint8 m2m_ate_start_rx(tstrM2mAteRx *) - -@brief - This function used to start RX test case. - -@param [in] strM2mAteRx - Type of \ref tstrM2mAteRx, with the values required to enable RX test case. You must use \ref m2m_ate_init first. -@return - The function SHALL return 0 for success and a negative value otherwise. -\sa - m2m_ate_init, m2m_ate_stop_rx, m2m_ate_get_rx_status -*/ -sint8 m2m_ate_start_rx(tstrM2mAteRx * strM2mAteRxStr) -{ - sint8 s8Ret = M2M_SUCCESS; - uint32 val32; - if(NULL == strM2mAteRxStr) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - if(0 != m2m_ate_get_tx_status()) - { - s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING; - goto __EXIT; - } - - if(0 != m2m_ate_get_rx_status()) - { - s8Ret = M2M_ATE_ERR_RX_ALREADY_RUNNING; - goto __EXIT; - } - - if( (strM2mAteRxStr->channel_num < M2M_ATE_CHANNEL_1) || - (strM2mAteRxStr->channel_num > M2M_ATE_CHANNEL_14)|| - (strM2mAteRxStr->use_pmu > M2M_ATE_PMU_ENABLE) - ) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - s8Ret += nm_write_reg(rBurstTx_NMI_TEST_CH, strM2mAteRxStr->channel_num); - s8Ret += nm_write_reg(rBurstTx_NMI_USE_PMU, strM2mAteRxStr->use_pmu); - s8Ret += nm_write_reg(rBurstTx_NMI_TEST_XO_OFF, strM2mAteRxStr->xo_offset_x1000); - s8Ret += nm_write_reg(rBurstTx_NMI_USE_EFUSE_XO_OFF, strM2mAteRxStr->use_efuse_xo_offset); - - if(strM2mAteRxStr->override_self_mac_addr) - { - val32 = strM2mAteRxStr->self_mac_addr[5] << 0; - val32 |= strM2mAteRxStr->self_mac_addr[4] << 8; - val32 |= strM2mAteRxStr->self_mac_addr[3] << 16; - nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_SELF, val32 ); - - val32 = strM2mAteRxStr->self_mac_addr[2] << 0; - val32 |= strM2mAteRxStr->self_mac_addr[1] << 8; - val32 |= strM2mAteRxStr->self_mac_addr[0] << 16; - nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_SELF, val32 ); - } - - if(strM2mAteRxStr->mac_filter_en_sa) - { - val32 = strM2mAteRxStr->peer_mac_addr[5] << 0; - val32 |= strM2mAteRxStr->peer_mac_addr[4] << 8; - val32 |= strM2mAteRxStr->peer_mac_addr[3] << 16; - nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_SA, val32 ); - - val32 = strM2mAteRxStr->peer_mac_addr[2] << 0; - val32 |= strM2mAteRxStr->peer_mac_addr[1] << 8; - val32 |= strM2mAteRxStr->peer_mac_addr[0] << 16; - nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_SA, val32 ); - } - - nm_write_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_DA, strM2mAteRxStr->mac_filter_en_da); - nm_write_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_SA, strM2mAteRxStr->mac_filter_en_sa); - nm_write_reg(rBurstTx_NMI_SET_SELF_MAC_ADDR, strM2mAteRxStr->override_self_mac_addr); - - if(M2M_SUCCESS == s8Ret) - { - s8Ret += nm_write_reg(rInterrupt_CORTUS_2, 1); /*Interrupt Cortus*/ - m2m_ate_set_rx_status(1); - nm_bsp_sleep(10); /*Recommended*/ - } - -__EXIT: - return s8Ret; -} - -/*! -@fn \ - sint8 m2m_ate_stop_rx(void) - -@brief - This function used to stop RX test case. - -@return - The function SHALL return 0 for success and a negative value otherwise. -\sa - m2m_ate_init, m2m_ate_start_rx, m2m_ate_get_rx_status -*/ -sint8 m2m_ate_stop_rx(void) -{ - m2m_ate_set_rx_status(0); - nm_bsp_sleep(200); /*Recommended*/ - return M2M_SUCCESS; -} - -/*! -@fn \ - sint8 m2m_ate_read_rx_status(tstrM2mAteRxStatus *) - -@brief - This function used to read RX statistics from ATE firmware. - -@param [out] strM2mAteRxStatus - Type of \ref tstrM2mAteRxStatus used to save statistics of RX test case. You must use \ref m2m_ate_start_rx first. -@return - The function SHALL return 0 for success and a negative value otherwise. -\sa - m2m_ate_init, m2m_ate_start_rx -*/ -sint8 m2m_ate_read_rx_status(tstrM2mAteRxStatus *strM2mAteRxStatus) -{ - sint8 s8Ret = M2M_SUCCESS; - - if(NULL == strM2mAteRxStatus) - { - s8Ret = M2M_ATE_ERR_VALIDATE; - goto __EXIT; - } - - if(0 != m2m_ate_get_tx_status()) - { - s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING; - goto __EXIT; - } - - if (nm_read_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_DA) || nm_read_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_SA)) - { - strM2mAteRxStatus->num_rx_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_SUCCESS) + nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_FAIL); - strM2mAteRxStatus->num_good_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_SUCCESS); - strM2mAteRxStatus->num_err_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_FAIL); - } - else - { - strM2mAteRxStatus->num_rx_pkts = nm_read_reg(rBurstRx_NMI_RX_ALL_PKTS_CONT) + nm_read_reg(0x989c); - strM2mAteRxStatus->num_err_pkts = nm_read_reg(rBurstRx_NMI_RX_ERR_PKTS_CONT); - strM2mAteRxStatus->num_good_pkts = strM2mAteRxStatus->num_rx_pkts - strM2mAteRxStatus->num_err_pkts; - } - -__EXIT: - return s8Ret; -} -/*! -@fn \ - sint8 m2m_ate_set_dig_gain(double dGaindB) - -@brief - This function is used to set the digital gain - -@param [in] double dGaindB - The digital gain value required to be set. -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_set_dig_gain(double dGaindB) -{ - uint32_t dGain, val32; - dGain = (uint32_t)(pow(10, dGaindB/20.0) * 1024.0); - - val32 = nm_read_reg(0x160cd0); - val32 &= ~(0x1ffful << 0); - val32 |= (((uint32_t)dGain) << 0); - nm_write_reg(0x160cd0, val32); - return M2M_SUCCESS; -} -/*! -@fn \ - sint8 m2m_ate_get_dig_gain(double * dGaindB) - -@brief - This function is used to get the digital gain - -@param [out] double * dGaindB - The retrieved digital gain value obtained from HW registers in dB. -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_get_dig_gain(double * dGaindB) -{ - uint32 dGain, val32; - - if(!dGaindB) return M2M_ERR_INVALID_ARG; - - val32 = nm_read_reg(0x160cd0); - - dGain = (val32 >> 0) & 0x1ffful; - *dGaindB = 20.0*log10((double)dGain / 1024.0); - - return M2M_SUCCESS; -} -/*! -@fn \ - void m2m_ate_set_pa_gain(uint8 gain_db) - -@brief - This function is used to set the PA gain (18/15/12/9/6/3/0 only) - -@param [in] uint8 gain_db - PA gain level allowed (18/15/12/9/6/3/0 only) - -*/ -void m2m_ate_set_pa_gain(uint8 gain_db) -{ - uint32 PA_1e9c; - uint8 aGain[] = { - /* "0 dB" */ 0x00, - /* "3 dB" */ 0x01, - /* "6 dB" */ 0x03, - /* "9 dB" */ 0x07, - /* "12 dB" */ 0x0f, - /* "15 dB" */ 0x1f, - /* "18 dB" */ 0x3f }; - /* The variable PA gain is valid only for High power mode */ - PA_1e9c = nm_read_reg(0x1e9c); - /* TX bank 0. */ - PA_1e9c &= ~(0x3ful << 8); - PA_1e9c |= (((uint32)aGain[gain_db/3] & 0x3f) << 8); - nm_write_reg(0x1e9c, PA_1e9c); -} -/*! -@fn \ - sint8 m2m_ate_get_pa_gain(double *paGaindB) - -@brief - This function is used to get the PA gain - -@param [out] double *paGaindB - The retrieved PA gain value obtained from HW registers in dB. -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_get_pa_gain(double *paGaindB) -{ - uint32 val32, paGain; - uint32 m_cmbPAGainStep; - - if(!paGaindB) - return M2M_ERR_INVALID_ARG; - - val32 = nm_read_reg(0x1e9c); - - paGain = (val32 >> 8) & 0x3f; - - switch(paGain){ - case 0x1: - m_cmbPAGainStep = 5; - break; - case 0x3: - m_cmbPAGainStep = 4; - break; - case 0x7: - m_cmbPAGainStep = 3; - break; - case 0xf: - m_cmbPAGainStep = 2; - break; - case 0x1f: - m_cmbPAGainStep = 1; - break; - case 0x3f: - m_cmbPAGainStep = 0; - break; - default: - m_cmbPAGainStep = 0; - break; - } - - *paGaindB = 18 - m_cmbPAGainStep*3; - - return M2M_SUCCESS; -} -/*! -@fn \ - sint8 m2m_ate_get_ppa_gain(double * ppaGaindB) - -@brief - This function is used to get the PPA gain - -@param [out] uint32 * ppaGaindB - The retrieved PPA gain value obtained from HW registers in dB. -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_get_ppa_gain(double * ppaGaindB) -{ - uint32 val32, ppaGain, m_cmbPPAGainStep; - - if(!ppaGaindB) return M2M_ERR_INVALID_ARG; - - val32 = nm_read_reg(0x1ea0); - - ppaGain = (val32 >> 5) & 0x7; - - switch(ppaGain){ - case 0x1: - m_cmbPPAGainStep = 2; - break; - case 0x3: - m_cmbPPAGainStep = 1; - break; - case 0x7: - m_cmbPPAGainStep = 0; - break; - default: - m_cmbPPAGainStep = 3; - break; - } - - *ppaGaindB = 9 - m_cmbPPAGainStep*3; - - - return M2M_SUCCESS; -} -/*! -@fn \ - sint8 m2m_ate_get_tot_gain(double * totGaindB) - -@brief - This function is used to calculate the total gain - -@param [out] double * totGaindB - The retrieved total gain value obtained from calculations made based on the digital gain, PA and PPA gain values. -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -sint8 m2m_ate_get_tot_gain(double * totGaindB) -{ - double dGaindB, paGaindB, ppaGaindB; - - if(!totGaindB) return M2M_ERR_INVALID_ARG; - - m2m_ate_get_pa_gain(&paGaindB); - m2m_ate_get_ppa_gain(&ppaGaindB); - m2m_ate_get_dig_gain(&dGaindB); - - *totGaindB = dGaindB + paGaindB + ppaGaindB; - - return M2M_SUCCESS; -} - -#endif //_M2M_ATE_FW_ \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_crypto.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_crypto.c deleted file mode 100644 index 9ac7711..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_crypto.c +++ /dev/null @@ -1,1010 +0,0 @@ -/** - * - * \file - * - * \brief WINC Crypto module. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "driver/include/m2m_crypto.h" -#include "driver/source/nmbus.h" -#include "driver/source/nmasic.h" - -#ifdef CONF_CRYPTO_HW - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*======*======*======*======*======*=======* -* WINC SHA256 HW Engine Register Definition * -*======*======*======*======*======*========*/ - -#define SHA_BLOCK_SIZE (64) - -#define SHARED_MEM_BASE (0xd0000) - - -#define SHA256_MEM_BASE (0x180000UL) -#define SHA256_ENGINE_ADDR (0x180000ul) - -/* SHA256 Registers */ -#define SHA256_CTRL (SHA256_MEM_BASE+0x00) -#define SHA256_CTRL_START_CALC_MASK (NBIT0) -#define SHA256_CTRL_START_CALC_SHIFT (0) -#define SHA256_CTRL_PREPROCESS_MASK (NBIT1) -#define SHA256_CTRL_PREPROCESS_SHIFT (1) -#define SHA256_CTRL_HASH_HASH_MASK (NBIT2) -#define SHA256_CTRL_HASH_HASH_SHIFT (2) -#define SHA256_CTRL_INIT_SHA256_STATE_MASK (NBIT3) -#define SHA256_CTRL_INIT_SHA256_STATE_SHIFT (3) -#define SHA256_CTRL_WR_BACK_HASH_VALUE_MASK (NBIT4) -#define SHA256_CTRL_WR_BACK_HASH_VALUE_SHIFT (4) -#define SHA256_CTRL_FORCE_SHA256_QUIT_MASK (NBIT5) -#define SHA256_CTRL_FORCE_SHA256_QUIT_SHIFT (5) - -#define SHA256_REGS_SHA256_CTRL_AHB_BYTE_REV_EN (NBIT6) -#define SHA256_REGS_SHA256_CTRL_RESERVED (NBIT7) -#define SHA256_REGS_SHA256_CTRL_CORE_TO_AHB_CLK_RATIO (NBIT8+ NBIT9+ NBIT10) -#define SHA256_REGS_SHA256_CTRL_CORE_TO_AHB_CLK_RATIO_MASK (NBIT2+ NBIT1+ NBIT0) -#define SHA256_REGS_SHA256_CTRL_CORE_TO_AHB_CLK_RATIO_SHIFT (8) -#define SHA256_REGS_SHA256_CTRL_RESERVED_11 (NBIT11) -#define SHA256_REGS_SHA256_CTRL_SHA1_CALC (NBIT12) -#define SHA256_REGS_SHA256_CTRL_PBKDF2_SHA1_CALC (NBIT13) - - -#define SHA256_START_RD_ADDR (SHA256_MEM_BASE+0x04UL) -#define SHA256_DATA_LENGTH (SHA256_MEM_BASE+0x08UL) -#define SHA256_START_WR_ADDR (SHA256_MEM_BASE+0x0cUL) -#define SHA256_COND_CHK_CTRL (SHA256_MEM_BASE+0x10) -#define SHA256_COND_CHK_CTRL_HASH_VAL_COND_CHK_MASK (NBIT1 | NBIT0) -#define SHA256_COND_CHK_CTRL_HASH_VAL_COND_CHK_SHIFT (0) -#define SHA256_COND_CHK_CTRL_STEP_VAL_MASK (NBIT6 | NBIT5 | NBIT4 | NBIT3 | NBIT2) -#define SHA256_COND_CHK_CTRL_STEP_VAL_SHIFT (2) -#define SHA256_COND_CHK_CTRL_COND_CHK_RESULT_MASK (NBIT7) -#define SHA256_COND_CHK_CTRL_COND_CHK_RESULT_SHIFT (7) - -#define SHA256_MOD_DATA_RANGE (SHA256_MEM_BASE+0x14) -#define SHA256_MOD_DATA_RANGE_ST_BYTE_2_ADD_STP_MASK (NBIT24-1) -#define SHA256_MOD_DATA_RANGE_ST_BYTE_2_ADD_STP_SHIFT (0) -#define SHA256_MOD_DATA_RANGE_MOD_DATA_LEN_MASK (NBIT24 | NBIT25| NBIT26) -#define SHA256_MOD_DATA_RANGE_MOD_DATA_LEN_SHIFT (24) - - -#define SHA256_COND_CHK_STS_1 (SHA256_MEM_BASE+0x18) -#define SHA256_COND_CHK_STS_2 (SHA256_MEM_BASE+0x1c) -#define SHA256_DONE_INTR_ENABLE (SHA256_MEM_BASE+0x20) -#define SHA256_DONE_INTR_STS (SHA256_MEM_BASE+0x24) -#define SHA256_TARGET_HASH_H1 (SHA256_MEM_BASE+0x28) -#define SHA256_TARGET_HASH_H2 (SHA256_MEM_BASE+0x2c) -#define SHA256_TARGET_HASH_H3 (SHA256_MEM_BASE+0x30) -#define SHA256_TARGET_HASH_H4 (SHA256_MEM_BASE+0x34) -#define SHA256_TARGET_HASH_H5 (SHA256_MEM_BASE+0x38) -#define SHA256_TARGET_HASH_H6 (SHA256_MEM_BASE+0x3c) -#define SHA256_TARGET_HASH_H7 (SHA256_MEM_BASE+0x40) -#define SHA256_TARGET_HASH_H8 (SHA256_MEM_BASE+0x44) - -/*======*======*======*======*======*=======* -* WINC BIGINT HW Engine Register Definition * -*======*======*======*======*======*========*/ - - -#define BIGINT_ENGINE_ADDR (0x180080ul) -#define BIGINT_VERSION (BIGINT_ENGINE_ADDR + 0x00) - -#define BIGINT_MISC_CTRL (BIGINT_ENGINE_ADDR + 0x04) -#define BIGINT_MISC_CTRL_CTL_START (NBIT0) -#define BIGINT_MISC_CTRL_CTL_RESET (NBIT1) -#define BIGINT_MISC_CTRL_CTL_MSW_FIRST (NBIT2) -#define BIGINT_MISC_CTRL_CTL_SWAP_BYTE_ORDER (NBIT3) -#define BIGINT_MISC_CTRL_CTL_FORCE_BARRETT (NBIT4) -#define BIGINT_MISC_CTRL_CTL_M_PRIME_VALID (NBIT5) - -#define BIGINT_M_PRIME (BIGINT_ENGINE_ADDR + 0x08) - -#define BIGINT_STATUS (BIGINT_ENGINE_ADDR + 0x0C) -#define BIGINT_STATUS_STS_DONE (NBIT0) - -#define BIGINT_CLK_COUNT (BIGINT_ENGINE_ADDR + 0x10) -#define BIGINT_ADDR_X (BIGINT_ENGINE_ADDR + 0x14) -#define BIGINT_ADDR_E (BIGINT_ENGINE_ADDR + 0x18) -#define BIGINT_ADDR_M (BIGINT_ENGINE_ADDR + 0x1C) -#define BIGINT_ADDR_R (BIGINT_ENGINE_ADDR + 0x20) -#define BIGINT_LENGTH (BIGINT_ENGINE_ADDR + 0x24) - -#define BIGINT_IRQ_STS (BIGINT_ENGINE_ADDR + 0x28) -#define BIGINT_IRQ_STS_DONE (NBIT0) -#define BIGINT_IRQ_STS_CHOOSE_MONT (NBIT1) -#define BIGINT_IRQ_STS_M_READ (NBIT2) -#define BIGINT_IRQ_STS_X_READ (NBIT3) -#define BIGINT_IRQ_STS_START (NBIT4) -#define BIGINT_IRQ_STS_PRECOMP_FINISH (NBIT5) - -#define BIGINT_IRQ_MASK (BIGINT_ENGINE_ADDR + 0x2C) -#define BIGINT_IRQ_MASK_CTL_IRQ_MASK_START (NBIT4) - -#define ENABLE_FLIPPING 1 - - - - -#define GET_UINT32(BUF,OFFSET) (((uint32)((BUF)[OFFSET])) | ((uint32)(((BUF)[OFFSET + 1]) << 8)) | \ -((uint32)(((BUF)[OFFSET + 2]) << 16)) | ((uint32)(((BUF)[OFFSET + 3]) << 24))) - -#define PUTU32(VAL32,BUF,OFFSET) \ -do \ -{ \ - (BUF)[OFFSET ] = BYTE_3((VAL32)); \ - (BUF)[OFFSET +1 ] = BYTE_2((VAL32)); \ - (BUF)[OFFSET +2 ] = BYTE_1((VAL32)); \ - (BUF)[OFFSET +3 ] = BYTE_0((VAL32)); \ -}while(0) - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*! -@struct \ - tstrHashContext - -@brief -*/ -typedef struct{ - uint32 au32HashState[M2M_SHA256_DIGEST_LEN/4]; - uint8 au8CurrentBlock[64]; - uint32 u32TotalLength; - uint8 u8InitHashFlag; -}tstrSHA256HashCtxt; - - - -/*======*======*======*======*======*=======* -* SHA256 IMPLEMENTATION * -*======*======*======*======*======*========*/ - -sint8 m2m_crypto_sha256_hash_init(tstrM2mSha256Ctxt *pstrSha256Ctxt) -{ - tstrSHA256HashCtxt *pstrSHA256 = (tstrSHA256HashCtxt*)pstrSha256Ctxt; - if(pstrSHA256 != NULL) - { - m2m_memset((uint8*)pstrSha256Ctxt, 0, sizeof(tstrM2mSha256Ctxt)); - pstrSHA256->u8InitHashFlag = 1; - } - return 0; -} - -sint8 m2m_crypto_sha256_hash_update(tstrM2mSha256Ctxt *pstrSha256Ctxt, uint8 *pu8Data, uint16 u16DataLength) -{ - sint8 s8Ret = M2M_ERR_FAIL; - tstrSHA256HashCtxt *pstrSHA256 = (tstrSHA256HashCtxt*)pstrSha256Ctxt; - if(pstrSHA256 != NULL) - { - uint32 u32ReadAddr; - uint32 u32WriteAddr = SHARED_MEM_BASE; - uint32 u32Addr = u32WriteAddr; - uint32 u32ResidualBytes; - uint32 u32NBlocks; - uint32 u32Offset; - uint32 u32CurrentBlock = 0; - uint8 u8IsDone = 0; - - /* Get the remaining bytes from the previous update (if the length is not block aligned). */ - u32ResidualBytes = pstrSHA256->u32TotalLength % SHA_BLOCK_SIZE; - - /* Update the total data length. */ - pstrSHA256->u32TotalLength += u16DataLength; - - if(u32ResidualBytes != 0) - { - if((u32ResidualBytes + u16DataLength) >= SHA_BLOCK_SIZE) - { - u32Offset = SHA_BLOCK_SIZE - u32ResidualBytes; - m2m_memcpy(&pstrSHA256->au8CurrentBlock[u32ResidualBytes], pu8Data, u32Offset); - pu8Data += u32Offset; - u16DataLength -= u32Offset; - - nm_write_block(u32Addr, pstrSHA256->au8CurrentBlock, SHA_BLOCK_SIZE); - u32Addr += SHA_BLOCK_SIZE; - u32CurrentBlock = 1; - } - else - { - m2m_memcpy(&pstrSHA256->au8CurrentBlock[u32ResidualBytes], pu8Data, u16DataLength); - u16DataLength = 0; - } - } - - /* Get the number of HASH BLOCKs and the residual bytes. */ - u32NBlocks = u16DataLength / SHA_BLOCK_SIZE; - u32ResidualBytes = u16DataLength % SHA_BLOCK_SIZE; - - if(u32NBlocks != 0) - { - nm_write_block(u32Addr, pu8Data, (uint16)(u32NBlocks * SHA_BLOCK_SIZE)); - pu8Data += (u32NBlocks * SHA_BLOCK_SIZE); - } - - u32NBlocks += u32CurrentBlock; - if(u32NBlocks != 0) - { - uint32 u32RegVal = 0; - - nm_write_reg(SHA256_CTRL, u32RegVal); - u32RegVal |= SHA256_CTRL_FORCE_SHA256_QUIT_MASK; - nm_write_reg(SHA256_CTRL, u32RegVal); - - if(pstrSHA256->u8InitHashFlag) - { - pstrSHA256->u8InitHashFlag = 0; - u32RegVal |= SHA256_CTRL_INIT_SHA256_STATE_MASK; - } - - u32ReadAddr = u32WriteAddr + (u32NBlocks * SHA_BLOCK_SIZE); - nm_write_reg(SHA256_DATA_LENGTH, (u32NBlocks * SHA_BLOCK_SIZE)); - nm_write_reg(SHA256_START_RD_ADDR, u32WriteAddr); - nm_write_reg(SHA256_START_WR_ADDR, u32ReadAddr); - - u32RegVal |= SHA256_CTRL_START_CALC_MASK; - - u32RegVal &= ~(0x7 << 8); - u32RegVal |= (2 << 8); - - nm_write_reg(SHA256_CTRL, u32RegVal); - - /* 5. Wait for done_intr */ - while(!u8IsDone) - { - u32RegVal = nm_read_reg(SHA256_DONE_INTR_STS); - u8IsDone = u32RegVal & NBIT0; - } - } - if(u32ResidualBytes != 0) - { - m2m_memcpy(pstrSHA256->au8CurrentBlock, pu8Data, u32ResidualBytes); - } - s8Ret = M2M_SUCCESS; - } - return s8Ret; -} - - -sint8 m2m_crypto_sha256_hash_finish(tstrM2mSha256Ctxt *pstrSha256Ctxt, uint8 *pu8Sha256Digest) -{ - sint8 s8Ret = M2M_ERR_FAIL; - tstrSHA256HashCtxt *pstrSHA256 = (tstrSHA256HashCtxt*)pstrSha256Ctxt; - if(pstrSHA256 != NULL) - { - uint32 u32ReadAddr; - uint32 u32WriteAddr = SHARED_MEM_BASE; - uint32 u32Addr = u32WriteAddr; - uint16 u16Offset; - uint16 u16PaddingLength; - uint16 u16NBlocks = 1; - uint32 u32RegVal = 0; - uint32 u32Idx,u32ByteIdx; - uint32 au32Digest[M2M_SHA256_DIGEST_LEN / 4]; - uint8 u8IsDone = 0; - - nm_write_reg(SHA256_CTRL,u32RegVal); - u32RegVal |= SHA256_CTRL_FORCE_SHA256_QUIT_MASK; - nm_write_reg(SHA256_CTRL,u32RegVal); - - if(pstrSHA256->u8InitHashFlag) - { - pstrSHA256->u8InitHashFlag = 0; - u32RegVal |= SHA256_CTRL_INIT_SHA256_STATE_MASK; - } - - /* Calculate the offset of the last data byte in the current block. */ - u16Offset = (uint16)(pstrSHA256->u32TotalLength % SHA_BLOCK_SIZE); - - /* Add the padding byte 0x80. */ - pstrSHA256->au8CurrentBlock[u16Offset ++] = 0x80; - - /* Calculate the required padding to complete - one Hash Block Size. - */ - u16PaddingLength = SHA_BLOCK_SIZE - u16Offset; - m2m_memset(&pstrSHA256->au8CurrentBlock[u16Offset], 0, u16PaddingLength); - - /* If the padding count is not enough to hold 64-bit representation of - the total input message length, one padding block is required. - */ - if(u16PaddingLength < 8) - { - nm_write_block(u32Addr, pstrSHA256->au8CurrentBlock, SHA_BLOCK_SIZE); - u32Addr += SHA_BLOCK_SIZE; - m2m_memset(pstrSHA256->au8CurrentBlock, 0, SHA_BLOCK_SIZE); - u16NBlocks ++; - } - - /* pack the length at the end of the padding block */ - PUTU32(pstrSHA256->u32TotalLength << 3, pstrSHA256->au8CurrentBlock, (SHA_BLOCK_SIZE - 4)); - - u32ReadAddr = u32WriteAddr + (u16NBlocks * SHA_BLOCK_SIZE); - nm_write_block(u32Addr, pstrSHA256->au8CurrentBlock, SHA_BLOCK_SIZE); - nm_write_reg(SHA256_DATA_LENGTH, (u16NBlocks * SHA_BLOCK_SIZE)); - nm_write_reg(SHA256_START_RD_ADDR, u32WriteAddr); - nm_write_reg(SHA256_START_WR_ADDR, u32ReadAddr); - - u32RegVal |= SHA256_CTRL_START_CALC_MASK; - u32RegVal |= SHA256_CTRL_WR_BACK_HASH_VALUE_MASK; - u32RegVal &= ~(0x7UL << 8); - u32RegVal |= (0x2UL << 8); - - nm_write_reg(SHA256_CTRL,u32RegVal); - - - /* 5. Wait for done_intr */ - while(!u8IsDone) - { - u32RegVal = nm_read_reg(SHA256_DONE_INTR_STS); - u8IsDone = u32RegVal & NBIT0; - } - nm_read_block(u32ReadAddr, (uint8*)au32Digest, 32); - - /* Convert the output words to an array of bytes. - */ - u32ByteIdx = 0; - for(u32Idx = 0; u32Idx < (M2M_SHA256_DIGEST_LEN / 4); u32Idx ++) - { - pu8Sha256Digest[u32ByteIdx ++] = BYTE_3(au32Digest[u32Idx]); - pu8Sha256Digest[u32ByteIdx ++] = BYTE_2(au32Digest[u32Idx]); - pu8Sha256Digest[u32ByteIdx ++] = BYTE_1(au32Digest[u32Idx]); - pu8Sha256Digest[u32ByteIdx ++] = BYTE_0(au32Digest[u32Idx]); - } - s8Ret = M2M_SUCCESS; - } - return s8Ret; -} - - -/*======*======*======*======*======*=======* -* RSA IMPLEMENTATION * -*======*======*======*======*======*========*/ - -static void FlipBuffer(uint8 *pu8InBuffer, uint8 *pu8OutBuffer, uint16 u16BufferSize) -{ - uint16 u16Idx; - for(u16Idx = 0; u16Idx < u16BufferSize; u16Idx ++) - { -#if ENABLE_FLIPPING == 1 - pu8OutBuffer[u16Idx] = pu8InBuffer[u16BufferSize - u16Idx - 1]; -#else - pu8OutBuffer[u16Idx] = pu8InBuffer[u16Idx]; -#endif - } -} - -void BigInt_ModExp -( - uint8 *pu8X, uint16 u16XSize, - uint8 *pu8E, uint16 u16ESize, - uint8 *pu8M, uint16 u16MSize, - uint8 *pu8R, uint16 u16RSize - ) -{ - uint32 u32Reg; - uint8 au8Tmp[780] = {0}; - uint32 u32XAddr = SHARED_MEM_BASE; - uint32 u32MAddr; - uint32 u32EAddr; - uint32 u32RAddr; - uint8 u8EMswBits = 32; - uint32 u32Mprime = 0x7F; - uint16 u16XSizeWords,u16ESizeWords; - uint32 u32Exponent; - - u16XSizeWords = (u16XSize + 3) / 4; - u16ESizeWords = (u16ESize + 3) / 4; - - u32MAddr = u32XAddr + (u16XSizeWords * 4); - u32EAddr = u32MAddr + (u16XSizeWords * 4); - u32RAddr = u32EAddr + (u16ESizeWords * 4); - - /* Reset the core. - */ - u32Reg = 0; - u32Reg |= BIGINT_MISC_CTRL_CTL_RESET; - u32Reg = nm_read_reg(BIGINT_MISC_CTRL); - u32Reg &= ~BIGINT_MISC_CTRL_CTL_RESET; - u32Reg = nm_read_reg(BIGINT_MISC_CTRL); - - nm_write_block(u32RAddr,au8Tmp, u16RSize); - - /* Write Input Operands to Chip Memory. - */ - /*------- X -------*/ - FlipBuffer(pu8X,au8Tmp,u16XSize); - nm_write_block(u32XAddr,au8Tmp,u16XSizeWords * 4); - - /*------- E -------*/ - m2m_memset(au8Tmp, 0, sizeof(au8Tmp)); - FlipBuffer(pu8E, au8Tmp, u16ESize); - nm_write_block(u32EAddr, au8Tmp, u16ESizeWords * 4); - u32Exponent = GET_UINT32(au8Tmp, (u16ESizeWords * 4) - 4); - while((u32Exponent & NBIT31)== 0) - { - u32Exponent <<= 1; - u8EMswBits --; - } - - /*------- M -------*/ - m2m_memset(au8Tmp, 0, sizeof(au8Tmp)); - FlipBuffer(pu8M, au8Tmp, u16XSize); - nm_write_block(u32MAddr, au8Tmp, u16XSizeWords * 4); - - /* Program the addresses of the input operands. - */ - nm_write_reg(BIGINT_ADDR_X, u32XAddr); - nm_write_reg(BIGINT_ADDR_E, u32EAddr); - nm_write_reg(BIGINT_ADDR_M, u32MAddr); - nm_write_reg(BIGINT_ADDR_R, u32RAddr); - - /* Mprime. - */ - nm_write_reg(BIGINT_M_PRIME,u32Mprime); - - /* Length. - */ - u32Reg = (u16XSizeWords & 0xFF); - u32Reg += ((u16ESizeWords & 0xFF) << 8); - u32Reg += (u8EMswBits << 16); - nm_write_reg(BIGINT_LENGTH,u32Reg); - - /* CTRL Register. - */ - u32Reg = nm_read_reg(BIGINT_MISC_CTRL); - u32Reg ^= BIGINT_MISC_CTRL_CTL_START; - u32Reg |= BIGINT_MISC_CTRL_CTL_FORCE_BARRETT; - //u32Reg |= BIGINT_MISC_CTRL_CTL_M_PRIME_VALID; -#if ENABLE_FLIPPING == 0 - u32Reg |= BIGINT_MISC_CTRL_CTL_MSW_FIRST; -#endif - nm_write_reg(BIGINT_MISC_CTRL,u32Reg); - - /* Wait for computation to complete. */ - while(1) - { - u32Reg = nm_read_reg(BIGINT_IRQ_STS); - if(u32Reg & BIGINT_IRQ_STS_DONE) - { - break; - } - } - nm_write_reg(BIGINT_IRQ_STS,0); - m2m_memset(au8Tmp, 0, sizeof(au8Tmp)); - nm_read_block(u32RAddr, au8Tmp, u16RSize); - FlipBuffer(au8Tmp, pu8R, u16RSize); -} - - - -#define MD5_DIGEST_SIZE (16) -#define SHA1_DIGEST_SIZE (20) - -static const uint8 au8TEncodingMD5[] = -{ - 0x30, 0x20, 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86, - 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05, 0x05, 0x00, - 0x04 -}; -/*!< Fixed part of the Encoding T for the MD5 hash algorithm. -*/ - - -static const uint8 au8TEncodingSHA1[] = -{ - 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, - 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04 -}; -/*!< Fixed part of the Encoding T for the SHA-1 hash algorithm. -*/ - - -static const uint8 au8TEncodingSHA2[] = -{ - 0x30, 0x31, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, - 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, - 0x00, 0x04 -}; -/*!< Fixed part of the Encoding T for the SHA-2 hash algorithm. -*/ - - -sint8 m2m_crypto_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash, - uint16 u16HashLength, uint8 *pu8RsaSignature) -{ - sint8 s8Ret = M2M_RSA_SIGN_FAIL; - - if((pu8N != NULL) && (pu8E != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL)) - { - uint16 u16TLength, u16TEncodingLength; - uint8 *pu8T; - uint8 au8EM[512]; - - /* Selection of correct T Encoding based on the hash size. - */ - if(u16HashLength == MD5_DIGEST_SIZE) - { - pu8T = (uint8*)au8TEncodingMD5; - u16TEncodingLength = sizeof(au8TEncodingMD5); - } - else if(u16HashLength == SHA1_DIGEST_SIZE) - { - pu8T = (uint8*)au8TEncodingSHA1; - u16TEncodingLength = sizeof(au8TEncodingSHA1); - } - else - { - pu8T = (uint8*)au8TEncodingSHA2; - u16TEncodingLength = sizeof(au8TEncodingSHA2); - } - u16TLength = u16TEncodingLength + 1 + u16HashLength; - - /* If emLen < tLen + 11. - */ - if(u16NSize >= (u16TLength + 11)) - { - uint32 u32PSLength,u32Idx = 0; - - /* - RSA verification - */ - BigInt_ModExp(pu8RsaSignature, u16NSize, pu8E, u16ESize, pu8N, u16NSize, au8EM, u16NSize); - - u32PSLength = u16NSize - u16TLength - 3; - - /* - The calculated EM must match the following pattern. - *======*======*======*======*======* - * 0x00 || 0x01 || PS || 0x00 || T * - *======*======*======*======*======* - Where PS is all 0xFF - T is defined based on the hash algorithm. - */ - if((au8EM[0] == 0x00) && (au8EM[1] == 0x01)) - { - for(u32Idx = 2; au8EM[u32Idx] == 0xFF; u32Idx ++); - if(u32Idx == (u32PSLength + 2)) - { - if(au8EM[u32Idx ++] == 0x00) - { - if(!m2m_memcmp(&au8EM[u32Idx], pu8T, u16TEncodingLength)) - { - u32Idx += u16TEncodingLength; - if(au8EM[u32Idx ++] == u16HashLength) - s8Ret = m2m_memcmp(&au8EM[u32Idx], pu8SignedMsgHash, u16HashLength); - } - } - } - } - } - } - return s8Ret; -} - - -sint8 m2m_crypto_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash, - uint16 u16HashLength, uint8 *pu8RsaSignature) -{ - sint8 s8Ret = M2M_RSA_SIGN_FAIL; - - if((pu8N != NULL) && (pu8d != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL)) - { - uint16 u16TLength, u16TEncodingLength; - uint8 *pu8T; - uint8 au8EM[512]; - - /* Selection of correct T Encoding based on the hash size. - */ - if(u16HashLength == MD5_DIGEST_SIZE) - { - pu8T = (uint8*)au8TEncodingMD5; - u16TEncodingLength = sizeof(au8TEncodingMD5); - } - else if(u16HashLength == SHA1_DIGEST_SIZE) - { - pu8T = (uint8*)au8TEncodingSHA1; - u16TEncodingLength = sizeof(au8TEncodingSHA1); - } - else - { - pu8T = (uint8*)au8TEncodingSHA2; - u16TEncodingLength = sizeof(au8TEncodingSHA2); - } - u16TLength = u16TEncodingLength + 1 + u16HashLength; - - /* If emLen < tLen + 11. - */ - if(u16NSize >= (u16TLength + 11)) - { - uint16 u16PSLength = 0; - uint16 u16Offset = 0; - - /* - The calculated EM must match the following pattern. - *======*======*======*======*======* - * 0x00 || 0x01 || PS || 0x00 || T * - *======*======*======*======*======* - Where PS is all 0xFF - T is defined based on the hash algorithm. - */ - au8EM[u16Offset ++] = 0; - au8EM[u16Offset ++] = 1; - u16PSLength = u16NSize - u16TLength - 3; - m2m_memset(&au8EM[u16Offset], 0xFF, u16PSLength); - u16Offset += u16PSLength; - au8EM[u16Offset ++] = 0; - m2m_memcpy(&au8EM[u16Offset], pu8T, u16TEncodingLength); - u16Offset += u16TEncodingLength; - au8EM[u16Offset ++] = u16HashLength; - m2m_memcpy(&au8EM[u16Offset], pu8SignedMsgHash, u16HashLength); - - /* - RSA Signature Generation - */ - BigInt_ModExp(au8EM, u16NSize, pu8d, u16dSize, pu8N, u16NSize, pu8RsaSignature, u16NSize); - s8Ret = M2M_RSA_SIGN_OK; - } - } - return s8Ret; -} - -#endif /* CONF_CRYPTO */ - -#ifdef CONF_CRYPTO_SOFT - -typedef struct { - tpfAppCryproCb pfAppCryptoCb; - uint8 * pu8Digest; - uint8 * pu8Rsa; - uint8 u8CryptoBusy; -}tstrCryptoCtxt; - -typedef struct { - uint8 au8N[M2M_MAX_RSA_LEN]; - uint8 au8E[M2M_MAX_RSA_LEN]; - uint8 au8Hash[M2M_SHA256_DIGEST_LEN]; - uint16 u16Nsz; - uint16 u16Esz; - uint16 u16Hsz; - uint8 _pad16_[2]; -}tstrRsaPayload; - -static tstrCryptoCtxt gstrCryptoCtxt; - - -/** -* @fn m2m_crypto_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -* @brief WiFi call back function -* @param [in] u8OpCode -* HIF Opcode type. -* @param [in] u16DataSize -* HIF data length. -* @param [in] u32Addr -* HIF address. -* @author -* @date -* @version 1.0 -*/ -static void m2m_crypto_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -{ - sint8 ret = M2M_SUCCESS; - gstrCryptoCtxt.u8CryptoBusy = 0; - if(u8OpCode == M2M_CRYPTO_RESP_SHA256_INIT) - { - tstrM2mSha256Ctxt strCtxt; - if (hif_receive(u32Addr, (uint8*) &strCtxt,sizeof(tstrM2mSha256Ctxt), 0) == M2M_SUCCESS) - { - tstrCyptoResp strResp; - if(hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt), (uint8*) &strResp,sizeof(tstrCyptoResp), 1) == M2M_SUCCESS) - { - if (gstrCryptoCtxt.pfAppCryptoCb) - gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,&strCtxt); - } - } - } - else if(u8OpCode == M2M_CRYPTO_RESP_SHA256_UPDATE) - { - tstrM2mSha256Ctxt strCtxt; - if (hif_receive(u32Addr, (uint8*) &strCtxt,sizeof(tstrM2mSha256Ctxt), 0) == M2M_SUCCESS) - { - tstrCyptoResp strResp; - if (hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt), (uint8*) &strResp,sizeof(tstrCyptoResp), 1) == M2M_SUCCESS) - { - if (gstrCryptoCtxt.pfAppCryptoCb) - gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,&strCtxt); - } - } - - } - else if(u8OpCode == M2M_CRYPTO_RESP_SHA256_FINSIH) - { - tstrCyptoResp strResp; - if (hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt), (uint8*) &strResp,sizeof(tstrCyptoResp), 0) == M2M_SUCCESS) - { - if (hif_receive(u32Addr + sizeof(tstrM2mSha256Ctxt) + sizeof(tstrCyptoResp), (uint8*)gstrCryptoCtxt.pu8Digest,M2M_SHA256_DIGEST_LEN, 1) == M2M_SUCCESS) - { - if (gstrCryptoCtxt.pfAppCryptoCb) - gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,gstrCryptoCtxt.pu8Digest); - - } - } - } - else if(u8OpCode == M2M_CRYPTO_RESP_RSA_SIGN_GEN) - { - tstrCyptoResp strResp; - if (hif_receive(u32Addr + sizeof(tstrRsaPayload), (uint8*)&strResp,sizeof(tstrCyptoResp), 0) == M2M_SUCCESS) - { - if (hif_receive(u32Addr + sizeof(tstrRsaPayload) + sizeof(tstrCyptoResp), (uint8*)gstrCryptoCtxt.pu8Rsa,M2M_MAX_RSA_LEN, 0) == M2M_SUCCESS) - { - if (gstrCryptoCtxt.pfAppCryptoCb) - gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,gstrCryptoCtxt.pu8Rsa); - } - } - } - else if(u8OpCode == M2M_CRYPTO_RESP_RSA_SIGN_VERIFY) - { - tstrCyptoResp strResp; - if (hif_receive(u32Addr + sizeof(tstrRsaPayload), (uint8*)&strResp,sizeof(tstrCyptoResp), 1) == M2M_SUCCESS) - { - if (gstrCryptoCtxt.pfAppCryptoCb) - gstrCryptoCtxt.pfAppCryptoCb(u8OpCode,&strResp,NULL); - } - } - else - { - M2M_ERR("u8Code %d ??\n",u8OpCode); - } - -} -/*! -@fn \ - sint8 m2m_crypto_init(); - -@brief crypto initialization - -@param[in] pfAppCryproCb - -*/ -sint8 m2m_crypto_init(tpfAppCryproCb pfAppCryproCb) -{ - sint8 ret = M2M_ERR_FAIL; - m2m_memset((uint8*)&gstrCryptoCtxt,0,sizeof(tstrCryptoCtxt)); - if(pfAppCryproCb != NULL) - { - gstrCryptoCtxt.pfAppCryptoCb = pfAppCryproCb; - ret = hif_register_cb(M2M_REQ_GROUP_CRYPTO,m2m_crypto_cb); - } - return ret; -} -/*! -@fn \ - sint8 m2m_sha256_hash_init(tstrM2mSha256Ctxt *psha256Ctxt); - -@brief SHA256 hash initialization - -@param[in] psha256Ctxt - Pointer to a sha256 context allocated by the caller. -*/ -sint8 m2m_crypto_sha256_hash_init(tstrM2mSha256Ctxt *psha256Ctxt) -{ - sint8 ret = M2M_ERR_FAIL; - if((psha256Ctxt != NULL)&&(!gstrCryptoCtxt.u8CryptoBusy)) - { - ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_SHA256_INIT|M2M_REQ_DATA_PKT,(uint8*)psha256Ctxt,sizeof(tstrM2mSha256Ctxt),NULL,0,0); - } - return ret; -} - - -/*! -@fn \ - sint8 m2m_sha256_hash_update(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Data, uint16 u16DataLength); - -@brief SHA256 hash update - -@param [in] psha256Ctxt - Pointer to the sha256 context. - -@param [in] pu8Data - Buffer holding the data submitted to the hash. - -@param [in] u16DataLength - Size of the data bufefr in bytes. -*/ -sint8 m2m_crypto_sha256_hash_update(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Data, uint16 u16DataLength) -{ - sint8 ret = M2M_ERR_FAIL; - if((!gstrCryptoCtxt.u8CryptoBusy) && (psha256Ctxt != NULL) && (pu8Data != NULL) && (u16DataLength < M2M_SHA256_MAX_DATA)) - { - ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_SHA256_UPDATE|M2M_REQ_DATA_PKT,(uint8*)psha256Ctxt,sizeof(tstrM2mSha256Ctxt),pu8Data,u16DataLength,sizeof(tstrM2mSha256Ctxt) + sizeof(tstrCyptoResp)); - } - return ret; - -} - - -/*! -@fn \ - sint8 m2m_sha256_hash_finish(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Sha256Digest); - -@brief SHA256 hash finalization - -@param[in] psha256Ctxt - Pointer to a sha256 context allocated by the caller. - -@param [in] pu8Sha256Digest - Buffer allocated by the caller which will hold the resultant SHA256 Digest. It must be allocated no less than M2M_SHA256_DIGEST_LEN. -*/ -sint8 m2m_crypto_sha256_hash_finish(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Sha256Digest) -{ - sint8 ret = M2M_ERR_FAIL; - if((!gstrCryptoCtxt.u8CryptoBusy) && (psha256Ctxt != NULL) && (pu8Sha256Digest != NULL)) - { - gstrCryptoCtxt.pu8Digest = pu8Sha256Digest; - ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_SHA256_FINSIH|M2M_REQ_DATA_PKT,(uint8*)psha256Ctxt,sizeof(tstrM2mSha256Ctxt),NULL,0,0); - } - return ret; -} - - - - -/*! -@fn \ - sint8 m2m_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash, \ - uint16 u16HashLength, uint8 *pu8RsaSignature); - -@brief RSA Signature Verification - - The function shall request the RSA Signature verification from the WINC Firmware for the given message. The signed message shall be - compressed to the corresponding hash algorithm before calling this function. - The hash type is identified by the given hash length. For example, if the hash length is 32 bytes, then it is SHA256. - -@param[in] pu8N - RSA Key modulus n. - -@param[in] u16NSize - Size of the RSA modulus n in bytes. - -@param[in] pu8E - RSA public exponent. - -@param[in] u16ESize - Size of the RSA public exponent in bytes. - -@param[in] pu8SignedMsgHash - The hash digest of the signed message. - -@param[in] u16HashLength - The length of the hash digest. - -@param[out] pu8RsaSignature - Signature value to be verified. -*/ - - -sint8 m2m_crypto_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash, - uint16 u16HashLength, uint8 *pu8RsaSignature) -{ - sint8 ret = M2M_ERR_FAIL; - if((!gstrCryptoCtxt.u8CryptoBusy) && (pu8N != NULL) && (pu8E != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL) - && (u16NSize != 0) && (u16ESize != 0) && (u16HashLength != 0) && (pu8RsaSignature != NULL) ) - - { - tstrRsaPayload strRsa = {0}; - - m2m_memcpy(strRsa.au8N,pu8N,u16NSize); - m2m_memcpy(strRsa.au8E,pu8E,u16ESize); - m2m_memcpy(strRsa.au8Hash,pu8SignedMsgHash,u16HashLength); - - strRsa.u16Esz = u16ESize; - strRsa.u16Hsz = u16HashLength; - strRsa.u16Nsz = u16NSize; - - ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_RSA_SIGN_VERIFY|M2M_REQ_DATA_PKT,(uint8*)&strRsa,sizeof(tstrRsaPayload),NULL,0,0); - - } - return ret; -} - - -/*! -@fn \ - sint8 m2m_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash, \ - uint16 u16HashLength, uint8 *pu8RsaSignature); - -@brief RSA Signature Generation - - The function shall request the RSA Signature generation from the WINC Firmware for the given message. The signed message shall be - compressed to the corresponding hash algorithm before calling this function. - The hash type is identified by the given hash length. For example, if the hash length is 32 bytes, then it is SHA256. - -@param[in] pu8N - RSA Key modulus n. - -@param[in] u16NSize - Size of the RSA modulus n in bytes. - -@param[in] pu8d - RSA private exponent. - -@param[in] u16dSize - Size of the RSA private exponent in bytes. - -@param[in] pu8SignedMsgHash - The hash digest of the signed message. - -@param[in] u16HashLength - The length of the hash digest. - -@param[out] pu8RsaSignature - Pointer to a user buffer allocated by teh caller shall hold the generated signature. -*/ -sint8 m2m_crypto_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash, - uint16 u16HashLength, uint8 *pu8RsaSignature) -{ - sint8 ret = M2M_ERR_FAIL; - if((!gstrCryptoCtxt.u8CryptoBusy) && (pu8N != NULL) && (pu8d != NULL) && (pu8RsaSignature != NULL) && (pu8SignedMsgHash != NULL) - && (u16NSize != 0) && (u16dSize != 0) && (u16HashLength != 0) && (pu8RsaSignature != NULL)) - - { - tstrRsaPayload strRsa = {0}; - - m2m_memcpy(strRsa.au8N,pu8N,u16NSize); - m2m_memcpy(strRsa.au8E,pu8d,u16dSize); - m2m_memcpy(strRsa.au8Hash,pu8SignedMsgHash,u16HashLength); - - strRsa.u16Esz = u16dSize; - strRsa.u16Hsz = u16HashLength; - strRsa.u16Nsz = u16NSize; - - gstrCryptoCtxt.pu8Rsa = pu8RsaSignature; - ret = hif_send(M2M_REQ_GROUP_CRYPTO,M2M_CRYPTO_REQ_RSA_SIGN_GEN|M2M_REQ_DATA_PKT,(uint8*)&strRsa,sizeof(tstrRsaPayload),NULL,0,0); - - } - return ret; -} - -#endif \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_hif.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_hif.c deleted file mode 100644 index f0ed93a..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_hif.c +++ /dev/null @@ -1,767 +0,0 @@ -/** - * - * \file - * - * \brief This module contains M2M host interface APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "common/include/nm_common.h" -#include "driver/source/nmbus.h" -#include "bsp/include/nm_bsp.h" -#include "m2m_hif.h" -#include "driver/include/m2m_types.h" -#include "driver/source/nmasic.h" -#include "driver/include/m2m_periph.h" - -#if (defined NM_EDGE_INTERRUPT)&&(defined NM_LEVEL_INTERRUPT) -#error "only one type of interrupt NM_EDGE_INTERRUPT,NM_LEVEL_INTERRUPT" -#endif - -#if !((defined NM_EDGE_INTERRUPT)||(defined NM_LEVEL_INTERRUPT)) -#error "define interrupt type NM_EDGE_INTERRUPT,NM_LEVEL_INTERRUPT" -#endif - -#ifndef CORTUS_APP -#define NMI_AHB_DATA_MEM_BASE 0x30000 -#define NMI_AHB_SHARE_MEM_BASE 0xd0000 - -#define WIFI_HOST_RCV_CTRL_0 (0x1070) -#define WIFI_HOST_RCV_CTRL_1 (0x1084) -#define WIFI_HOST_RCV_CTRL_2 (0x1078) -#define WIFI_HOST_RCV_CTRL_3 (0x106c) -#define WIFI_HOST_RCV_CTRL_4 (0x150400) -#define WIFI_HOST_RCV_CTRL_5 (0x1088) - -typedef struct { - uint8 u8ChipMode; - uint8 u8ChipSleep; - uint8 u8HifRXDone; - uint8 u8Interrupt; - uint32 u32RxAddr; - uint32 u32RxSize; - tpfHifCallBack pfWifiCb; - tpfHifCallBack pfIpCb; - tpfHifCallBack pfOtaCb; - tpfHifCallBack pfSigmaCb; - tpfHifCallBack pfHifCb; - tpfHifCallBack pfCryptoCb; - tpfHifCallBack pfSslCb; -}tstrHifContext; - -volatile tstrHifContext gstrHifCxt; - -static void isr(void) -{ - gstrHifCxt.u8Interrupt++; -#ifdef NM_LEVEL_INTERRUPT - nm_bsp_interrupt_ctrl(0); -#endif -} -static sint8 hif_set_rx_done(void) -{ - uint32 reg; - sint8 ret = M2M_SUCCESS; - - gstrHifCxt.u8HifRXDone = 0; -#ifdef NM_EDGE_INTERRUPT - nm_bsp_interrupt_ctrl(1); -#endif - ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0,®); - if(ret != M2M_SUCCESS)goto ERR1; - /* Set RX Done */ - reg |= NBIT1; - ret = nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg); - if(ret != M2M_SUCCESS)goto ERR1; -#ifdef NM_LEVEL_INTERRUPT - nm_bsp_interrupt_ctrl(1); -#endif -ERR1: - return ret; - -} -/** -* @fn static void m2m_hif_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -* @brief WiFi call back function -* @param [in] u8OpCode -* HIF Opcode type. -* @param [in] u16DataSize -* HIF data length. -* @param [in] u32Addr -* HIF address. -* @param [in] grp -* HIF group type. -* @author -* @date -* @version 1.0 -*/ -static void m2m_hif_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)u8OpCode; - (void)u16DataSize; - (void)u32Addr; -#endif -} -/** -* @fn NMI_API sint8 hif_chip_wake(void); -* @brief To Wakeup the chip. -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -sint8 hif_chip_wake(void) -{ - sint8 ret = M2M_SUCCESS; - if(gstrHifCxt.u8HifRXDone) - { - /*chip already wake for the rx not done no need to send wake request*/ - return ret; - } - if(gstrHifCxt.u8ChipSleep == 0) - { - if(gstrHifCxt.u8ChipMode != M2M_NO_PS) - { - ret = chip_wake(); - if(ret != M2M_SUCCESS)goto ERR1; - } - else - { - } - } - gstrHifCxt.u8ChipSleep++; -ERR1: - return ret; -} -/*! -@fn \ - NMI_API void hif_set_sleep_mode(uint8 u8Pstype); - -@brief - Set the sleep mode of the HIF layer. - -@param [in] u8Pstype - Sleep mode. - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ - -void hif_set_sleep_mode(uint8 u8Pstype) -{ - gstrHifCxt.u8ChipMode = u8Pstype; -} -/*! -@fn \ - NMI_API uint8 hif_get_sleep_mode(void); - -@brief - Get the sleep mode of the HIF layer. - -@return - The function SHALL return the sleep mode of the HIF layer. -*/ - -uint8 hif_get_sleep_mode(void) -{ - return gstrHifCxt.u8ChipMode; -} - -/** -* @fn NMI_API sint8 hif_chip_sleep_sc(void); -* @brief To clear the chip sleep but keep the chip sleep -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -sint8 hif_chip_sleep_sc(void) -{ - if(gstrHifCxt.u8ChipSleep >= 1) - { - gstrHifCxt.u8ChipSleep--; - } - return M2M_SUCCESS; -} -/** -* @fn NMI_API sint8 hif_chip_sleep(void); -* @brief To make the chip sleep. -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -sint8 hif_chip_sleep(void) -{ - sint8 ret = M2M_SUCCESS; - - if(gstrHifCxt.u8ChipSleep >= 1) - { - gstrHifCxt.u8ChipSleep--; - } - - if(gstrHifCxt.u8ChipSleep == 0) - { - if(gstrHifCxt.u8ChipMode != M2M_NO_PS) - { - ret = chip_sleep(); - if(ret != M2M_SUCCESS)goto ERR1; - - } - else - { - } - } -ERR1: - return ret; -} -/** -* @fn NMI_API sint8 hif_init(void * arg); -* @brief To initialize HIF layer. -* @param [in] arg -* Pointer to the arguments. -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -sint8 hif_init(void * arg) -{ -#ifdef ARDUINO - (void)arg; // Silence "unused" warning -#endif - m2m_memset((uint8*)&gstrHifCxt,0,sizeof(tstrHifContext)); - nm_bsp_register_isr(isr); - hif_register_cb(M2M_REQ_GROUP_HIF,m2m_hif_cb); - return M2M_SUCCESS; -} -/** -* @fn NMI_API sint8 hif_deinit(void * arg); -* @brief To De-initialize HIF layer. -* @param [in] arg -* Pointer to the arguments. -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ -sint8 hif_deinit(void * arg) -{ -#ifdef ARDUINO - (void)arg; // Silence "unused" warning -#endif - sint8 ret = M2M_SUCCESS; - ret = hif_chip_wake(); - m2m_memset((uint8*)&gstrHifCxt,0,sizeof(tstrHifContext)); - return ret; -} -/** -* @fn NMI_API sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, - uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) -* @brief Send packet using host interface. - -* @param [in] u8Gid -* Group ID. -* @param [in] u8Opcode -* Operation ID. -* @param [in] pu8CtrlBuf -* Pointer to the Control buffer. -* @param [in] u16CtrlBufSize - Control buffer size. -* @param [in] u16DataOffset - Packet Data offset. -* @param [in] pu8DataBuf -* Packet buffer Allocated by the caller. -* @param [in] u16DataSize - Packet buffer size (including the HIF header). -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, - uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) -{ - sint8 ret = M2M_ERR_SEND; - volatile tstrHifHdr strHif; - - strHif.u8Opcode = u8Opcode&(~NBIT7); - strHif.u8Gid = u8Gid; - strHif.u16Length = M2M_HIF_HDR_OFFSET; - if(pu8DataBuf != NULL) - { - strHif.u16Length += u16DataOffset + u16DataSize; - } - else - { - strHif.u16Length += u16CtrlBufSize; - } - ret = hif_chip_wake(); - if(ret == M2M_SUCCESS) - { - volatile uint32 reg, dma_addr = 0; - volatile uint16 cnt = 0; -//#define OPTIMIZE_BUS -/*please define in firmware also*/ -#ifndef OPTIMIZE_BUS - reg = 0UL; - reg |= (uint32)u8Gid; - reg |= ((uint32)u8Opcode<<8); - reg |= ((uint32)strHif.u16Length<<16); - ret = nm_write_reg(NMI_STATE_REG,reg); - if(M2M_SUCCESS != ret) goto ERR1; - - reg = 0UL; - reg |= NBIT1; - ret = nm_write_reg(WIFI_HOST_RCV_CTRL_2, reg); - if(M2M_SUCCESS != ret) goto ERR1; -#else - reg = 0UL; - reg |= NBIT1; - reg |= ((u8Opcode & NBIT7) ? (NBIT2):(0)); /*Data = 1 or config*/ - reg |= (u8Gid == M2M_REQ_GROUP_IP) ? (NBIT3):(0); /*IP = 1 or non IP*/ - reg |= ((uint32)strHif.u16Length << 4); /*length of pkt max = 4096*/ - ret = nm_write_reg(WIFI_HOST_RCV_CTRL_2, reg); - if(M2M_SUCCESS != ret) goto ERR1; -#endif - dma_addr = 0; - - for(cnt = 0; cnt < 1000; cnt ++) - { - ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_2,(uint32 *)®); - if(ret != M2M_SUCCESS) break; - /* - * If it takes too long to get a response, the slow down to - * avoid back-to-back register read operations. - */ - if(cnt >= 500) { - if(cnt < 501) { - M2M_INFO("Slowing down...\n"); - } - nm_bsp_sleep(1); - } - if (!(reg & NBIT1)) - { - ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_4,(uint32 *)&dma_addr); - if(ret != M2M_SUCCESS) { - /*in case of read error clear the DMA address and return error*/ - dma_addr = 0; - goto ERR1; - } - /*in case of success break */ - break; - } - } - - if (dma_addr != 0) - { - volatile uint32 u32CurrAddr; - u32CurrAddr = dma_addr; - strHif.u16Length=NM_BSP_B_L_16(strHif.u16Length); - ret = nm_write_block(u32CurrAddr, (uint8*)&strHif, M2M_HIF_HDR_OFFSET); - if(M2M_SUCCESS != ret) goto ERR1; - u32CurrAddr += M2M_HIF_HDR_OFFSET; - if(pu8CtrlBuf != NULL) - { - ret = nm_write_block(u32CurrAddr, pu8CtrlBuf, u16CtrlBufSize); - if(M2M_SUCCESS != ret) goto ERR1; - u32CurrAddr += u16CtrlBufSize; - } - if(pu8DataBuf != NULL) - { - u32CurrAddr += (u16DataOffset - u16CtrlBufSize); - ret = nm_write_block(u32CurrAddr, pu8DataBuf, u16DataSize); - if(M2M_SUCCESS != ret) goto ERR1; - u32CurrAddr += u16DataSize; - } - - reg = dma_addr << 2; - reg |= NBIT1; - ret = nm_write_reg(WIFI_HOST_RCV_CTRL_3, reg); - if(M2M_SUCCESS != ret) goto ERR1; - } - else - { - ret = hif_chip_sleep(); - M2M_DBG("Failed to alloc rx size %d\r",ret); - ret = M2M_ERR_MEM_ALLOC; - goto ERR2; - } - - } - else - { - M2M_ERR("(HIF)Fail to wakup the chip\n"); - goto ERR2; - } - /*actual sleep ret = M2M_SUCCESS*/ - ret = hif_chip_sleep(); - return ret; -ERR1: - /*reset the count but no actual sleep as it already bus error*/ - hif_chip_sleep_sc(); -ERR2: - /*logical error*/ - return ret; -} - -#ifdef ARDUINO -volatile uint8 hif_small_xfer = 0; -#endif - -/** -* @fn hif_isr -* @brief Host interface interrupt service routine -* @author M. Abdelmawla -* @date 15 July 2012 -* @return 1 in case of interrupt received else 0 will be returned -* @version 1.0 -*/ -static sint8 hif_isr(void) -{ - sint8 ret = M2M_SUCCESS; - volatile uint32 reg; - volatile tstrHifHdr strHif; - -#ifdef ARDUINO - ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, (uint32*)®); -#else - ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, ®); -#endif - if(M2M_SUCCESS == ret) - { - if(reg & 0x1) /* New interrupt has been received */ - { - uint16 size; - - nm_bsp_interrupt_ctrl(0); - /*Clearing RX interrupt*/ - reg &= ~NBIT0; - ret = nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg); - if(ret != M2M_SUCCESS)goto ERR1; - gstrHifCxt.u8HifRXDone = 1; - size = (uint16)((reg >> 2) & 0xfff); - if (size > 0) { - uint32 address = 0; - /** - start bus transfer - **/ - ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_1, &address); - if(M2M_SUCCESS != ret) - { - M2M_ERR("(hif) WIFI_HOST_RCV_CTRL_1 bus fail\n"); - nm_bsp_interrupt_ctrl(1); - goto ERR1; - } - gstrHifCxt.u32RxAddr = address; - gstrHifCxt.u32RxSize = size; - ret = nm_read_block(address, (uint8*)&strHif, sizeof(tstrHifHdr)); - strHif.u16Length = NM_BSP_B_L_16(strHif.u16Length); - if(M2M_SUCCESS != ret) - { - M2M_ERR("(hif) address bus fail\n"); - nm_bsp_interrupt_ctrl(1); - goto ERR1; - } - if(strHif.u16Length != size) - { - if((size - strHif.u16Length) > 4) - { - M2M_ERR("(hif) Corrupted packet Size = %u \n", - size, strHif.u16Length, strHif.u8Gid, strHif.u8Opcode); - nm_bsp_interrupt_ctrl(1); - ret = M2M_ERR_BUS_FAIL; - goto ERR1; - } - } - - if(M2M_REQ_GROUP_WIFI == strHif.u8Gid) - { - if(gstrHifCxt.pfWifiCb) - gstrHifCxt.pfWifiCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); - else -#ifdef ARDUINO - { -#endif - M2M_ERR("WIFI callback is not registered\n"); -#ifdef ARDUINO - } -#endif - } - else if(M2M_REQ_GROUP_IP == strHif.u8Gid) - { - if(gstrHifCxt.pfIpCb) - gstrHifCxt.pfIpCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); - else -#ifdef ARDUINO - { -#endif - M2M_ERR("Scoket callback is not registered\n"); -#ifdef ARDUINO - } -#endif - } - else if(M2M_REQ_GROUP_OTA == strHif.u8Gid) - { - if(gstrHifCxt.pfOtaCb) - gstrHifCxt.pfOtaCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); - else -#ifdef ARDUINO - { -#endif - M2M_ERR("Ota callback is not registered\n"); -#ifdef ARDUINO - } -#endif - } - else if(M2M_REQ_GROUP_CRYPTO == strHif.u8Gid) - { - if(gstrHifCxt.pfCryptoCb) - gstrHifCxt.pfCryptoCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); - - else -#ifdef ARDUINO - { -#endif - M2M_ERR("Crypto callback is not registered\n"); -#ifdef ARDUINO - } -#endif - } - else if(M2M_REQ_GROUP_SIGMA == strHif.u8Gid) - { - if(gstrHifCxt.pfSigmaCb) - gstrHifCxt.pfSigmaCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); - else -#ifdef ARDUINO - { -#endif - M2M_ERR("Sigma callback is not registered\n"); -#ifdef ARDUINO - } -#endif - } - else if(M2M_REQ_GROUP_SSL == strHif.u8Gid) - { - if(gstrHifCxt.pfSslCb) - gstrHifCxt.pfSslCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET); - } - else - { - M2M_ERR("(hif) invalid group ID\n"); - ret = M2M_ERR_BUS_FAIL; - goto ERR1; - } -#ifdef ARDUINO - if(hif_small_xfer) - { - /*Pause SPI transfer*/ - return ret; - } -#endif - if(gstrHifCxt.u8HifRXDone) - { - M2M_ERR("(hif) host app didn't set RX Done <%u><%X>\n", strHif.u8Gid, strHif.u8Opcode); - ret = hif_set_rx_done(); - if(ret != M2M_SUCCESS) goto ERR1; - } - } - else - { - M2M_ERR("(hif) Wrong Size\n"); - ret = M2M_ERR_RCV; - goto ERR1; - } - } - else - { -#ifndef WIN32 - M2M_ERR("(hif) False interrupt %lx",reg); - ret = M2M_ERR_FAIL; - goto ERR1; -#else -#endif - } - } - else - { - M2M_ERR("(hif) Fail to Read interrupt reg\n"); - goto ERR1; - } - -ERR1: - return ret; -} - -#ifdef ARDUINO -void Socket_ReadSocketData_Small(void); -#endif - -/** -* @fn hif_handle_isr(void) -* @brief Handle interrupt received from NMC1500 firmware. -* @return The function SHALL return 0 for success and a negative value otherwise. -*/ - -sint8 hif_handle_isr(void) -{ - sint8 ret = M2M_SUCCESS; - -#ifdef ARDUINO - if(hif_small_xfer) { - /*SPI protocol paused to allow small transfer*/ - Socket_ReadSocketData_Small(); - return ret; - } -#endif - - while (gstrHifCxt.u8Interrupt) { - /*must be at that place because of the race of interrupt increment and that decrement*/ - /*when the interrupt enabled*/ - gstrHifCxt.u8Interrupt--; - while(1) - { - ret = hif_isr(); -#ifdef ARDUINO - if(hif_small_xfer) { - return ret; - } -#endif - if(ret == M2M_SUCCESS) { - /*we will try forever untill we get that interrupt*/ - /*Fail return errors here due to bus errors (reading expected values)*/ - break; - } else { - M2M_ERR("(HIF) Fail to handle interrupt %d try Again..\n",ret); - } - } - } - - return ret; -} -/* -* @fn hif_receive -* @brief Host interface interrupt serviece routine -* @param [in] u32Addr -* Receive start address -* @param [out] pu8Buf -* Pointer to receive buffer. Allocated by the caller -* @param [in] u16Sz -* Receive buffer size -* @param [in] isDone -* If you don't need any more packets send True otherwise send false -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ -sint8 hif_receive(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz, uint8 isDone) -{ - sint8 ret = M2M_SUCCESS; - if((u32Addr == 0)||(pu8Buf == NULL) || (u16Sz == 0)) - { - if(isDone) - { - /* set RX done */ - ret = hif_set_rx_done(); - } - else - { - ret = M2M_ERR_FAIL; - M2M_ERR(" hif_receive: Invalid argument\n"); - } - goto ERR1; - } - - if(u16Sz > gstrHifCxt.u32RxSize) - { - ret = M2M_ERR_FAIL; - M2M_ERR("APP Requested Size is larger than the recived buffer size <%u><%lu>\n",u16Sz, gstrHifCxt.u32RxSize); - goto ERR1; - } - if((u32Addr < gstrHifCxt.u32RxAddr)||((u32Addr + u16Sz)>(gstrHifCxt.u32RxAddr + gstrHifCxt.u32RxSize))) - { - ret = M2M_ERR_FAIL; - M2M_ERR("APP Requested Address beyond the recived buffer address and length\n"); - goto ERR1; - } - - /* Receive the payload */ - ret = nm_read_block(u32Addr, pu8Buf, u16Sz); - if(ret != M2M_SUCCESS)goto ERR1; - - /* check if this is the last packet */ - if((((gstrHifCxt.u32RxAddr + gstrHifCxt.u32RxSize) - (u32Addr + u16Sz)) <= 0) || isDone) - { - /* set RX done */ - ret = hif_set_rx_done(); - } - -ERR1: - return ret; -} - -/** -* @fn hif_register_cb -* @brief To set Callback function for every compantent Component -* @param [in] u8Grp -* Group to which the Callback function should be set. -* @param [in] fn -* function to be set -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -sint8 hif_register_cb(uint8 u8Grp,tpfHifCallBack fn) -{ - sint8 ret = M2M_SUCCESS; - switch(u8Grp) - { - case M2M_REQ_GROUP_IP: - gstrHifCxt.pfIpCb = fn; - break; - case M2M_REQ_GROUP_WIFI: - gstrHifCxt.pfWifiCb = fn; - break; - case M2M_REQ_GROUP_OTA: - gstrHifCxt.pfOtaCb = fn; - break; - case M2M_REQ_GROUP_HIF: - gstrHifCxt.pfHifCb = fn; - break; - case M2M_REQ_GROUP_CRYPTO: - gstrHifCxt.pfCryptoCb = fn; - break; - case M2M_REQ_GROUP_SIGMA: - gstrHifCxt.pfSigmaCb = fn; - break; - case M2M_REQ_GROUP_SSL: - gstrHifCxt.pfSslCb = fn; - break; - default: - M2M_ERR("GRp ? %d\n",u8Grp); - ret = M2M_ERR_FAIL; - break; - } - return ret; -} - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_hif.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_hif.h deleted file mode 100644 index 1187183..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_hif.h +++ /dev/null @@ -1,249 +0,0 @@ -/** - * - * \file - * - * \brief This module contains M2M host interface APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _M2M_HIF_ -#define _M2M_HIF_ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "common/include/nm_common.h" -/*!< Include depends on UNO Board is used or not*/ -#ifdef ENABLE_UNO_BOARD -#include "m2m_uno_hif.h" -#endif - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#define M2M_HIF_MAX_PACKET_SIZE (1600 - 4) -/*!< Maximum size of the buffer could be transferred between Host and Firmware. -*/ - -#define M2M_HIF_HDR_OFFSET (sizeof(tstrHifHdr) + 4) - -/** -* @struct tstrHifHdr -* @brief Structure to hold HIF header -*/ -typedef struct -{ - uint8 u8Gid; /*!< Group ID */ - uint8 u8Opcode; /*!< OP code */ - uint16 u16Length; /*!< Payload length */ -}tstrHifHdr; - -#ifdef __cplusplus - extern "C" { -#endif - -/*! -@typedef typedef void (*tpfHifCallBack)(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr); -@brief used to point to Wi-Fi call back function depend on Arduino project or other projects. -@param [in] u8OpCode - HIF Opcode type. -@param [in] u16DataSize - HIF data length. -@param [in] u32Addr - HIF address. -@param [in] grp - HIF group type. -*/ -typedef void (*tpfHifCallBack)(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr); -/** -* @fn NMI_API sint8 hif_init(void * arg); -* @brief - To initialize HIF layer. -* @param [in] arg -* Pointer to the arguments. -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 hif_init(void * arg); -/** -* @fn NMI_API sint8 hif_deinit(void * arg); -* @brief - To Deinitialize HIF layer. -* @param [in] arg -* Pointer to the arguments. -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 hif_deinit(void * arg); -/** -* @fn NMI_API sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, - uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset) -* @brief Send packet using host interface. - -* @param [in] u8Gid -* Group ID. -* @param [in] u8Opcode -* Operation ID. -* @param [in] pu8CtrlBuf -* Pointer to the Control buffer. -* @param [in] u16CtrlBufSize - Control buffer size. -* @param [in] u16DataOffset - Packet Data offset. -* @param [in] pu8DataBuf -* Packet buffer Allocated by the caller. -* @param [in] u16DataSize - Packet buffer size (including the HIF header). -* @return The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize, - uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset); -/* -* @fn hif_receive -* @brief Host interface interrupt serviece routine -* @param [in] u32Addr -* Receive start address -* @param [out] pu8Buf -* Pointer to receive buffer. Allocated by the caller -* @param [in] u16Sz -* Receive buffer size -* @param [in] isDone -* If you don't need any more packets send True otherwise send false -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -NMI_API sint8 hif_receive(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz, uint8 isDone); -/** -* @fn hif_register_cb -* @brief - To set Callback function for every Component. - -* @param [in] u8Grp -* Group to which the Callback function should be set. - -* @param [in] fn -* function to be set to the specified group. -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 hif_register_cb(uint8 u8Grp,tpfHifCallBack fn); -/** -* @fn NMI_API sint8 hif_chip_sleep(void); -* @brief - To make the chip sleep. -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 hif_chip_sleep(void); -/** -* @fn NMI_API sint8 hif_chip_sleep_sc(void); -* @brief - To clear the chip count only but keep the chip awake -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 hif_chip_sleep_sc(void); -/** -* @fn NMI_API sint8 hif_chip_wake(void); -* @brief - To Wakeup the chip. -* @return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ - -NMI_API sint8 hif_chip_wake(void); -/*! -@fn \ - NMI_API void hif_set_sleep_mode(uint8 u8Pstype); - -@brief - Set the sleep mode of the HIF layer. - -@param [in] u8Pstype - Sleep mode. - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ - -NMI_API void hif_set_sleep_mode(uint8 u8Pstype); -/*! -@fn \ - NMI_API uint8 hif_get_sleep_mode(void); - -@brief - Get the sleep mode of the HIF layer. - -@return - The function SHALL return the sleep mode of the HIF layer. -*/ - -NMI_API uint8 hif_get_sleep_mode(void); - -#ifdef CORTUS_APP -/** -* @fn hif_Resp_handler(uint8 *pu8Buffer, uint16 u16BufferSize) -* @brief - Response handler for HIF layer. - -* @param [in] pu8Buffer - Pointer to the buffer. - -* @param [in] u16BufferSize - Buffer size. - -* @return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 hif_Resp_handler(uint8 *pu8Buffer, uint16 u16BufferSize); -#endif - -/** -* @fn hif_handle_isr(void) -* @brief - Handle interrupt received from NMC1500 firmware. -* @return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 hif_handle_isr(void); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ota.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ota.c deleted file mode 100644 index cf4a30f..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ota.c +++ /dev/null @@ -1,417 +0,0 @@ -/** - * - * \file - * - * \brief NMC1500 IoT OTA Interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#include "common/include/nm_common.h" -#include "driver/include/m2m_types.h" -#include "driver/include/m2m_ota.h" -#include "driver/source/m2m_hif.h" -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -static tpfOtaUpdateCb gpfOtaUpdateCb = NULL; -static tpfOtaNotifCb gpfOtaNotifCb = NULL; - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/** -* @fn m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr, uint8 grp) -* @brief WiFi call back function -* @param [in] u8OpCode -* HIF Opcode type. -* @param [in] u16DataSize -* HIF data length. -* @param [in] u32Addr -* HIF address. -* @param [in] grp -* HIF group type. -* @author -* @date -* @version 1.0 -*/ -static void m2m_ota_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -{ -#ifdef ARDUINO - (void)u16DataSize; // Silence "unused" warning -#endif - sint8 ret = M2M_SUCCESS; - if(u8OpCode == M2M_OTA_RESP_NOTIF_UPDATE_INFO) - { - tstrOtaUpdateInfo strOtaUpdateInfo; - m2m_memset((uint8*)&strOtaUpdateInfo,0,sizeof(tstrOtaUpdateInfo)); - ret = hif_receive(u32Addr,(uint8*)&strOtaUpdateInfo,sizeof(tstrOtaUpdateInfo),0); - if(ret == M2M_SUCCESS) - { - if(gpfOtaNotifCb) - gpfOtaNotifCb(&strOtaUpdateInfo); - } - } - else if (u8OpCode == M2M_OTA_RESP_UPDATE_STATUS) - { - tstrOtaUpdateStatusResp strOtaUpdateStatusResp; - m2m_memset((uint8*)&strOtaUpdateStatusResp,0,sizeof(tstrOtaUpdateStatusResp)); - ret = hif_receive(u32Addr, (uint8*) &strOtaUpdateStatusResp,sizeof(tstrOtaUpdateStatusResp), 0); - if(ret == M2M_SUCCESS) - { - if(gpfOtaUpdateCb) - gpfOtaUpdateCb(strOtaUpdateStatusResp.u8OtaUpdateStatusType,strOtaUpdateStatusResp.u8OtaUpdateStatus); - } - } - else - { - M2M_ERR("Invaild OTA resp %d ?\n",u8OpCode); - } - -} -/*! -@fn \ - NMI_API sint8 m2m_ota_init(tpfOtaUpdateCb pfOtaUpdateCb, tpfOtaNotifCb pfOtaNotifCb); - -@brief - Initialize the OTA layer. - -@param [in] pfOtaUpdateCb - OTA Update callback function - -@param [in] pfOtaNotifCb - OTA notify callback function - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_init(tpfOtaUpdateCb pfOtaUpdateCb, tpfOtaNotifCb pfOtaNotifCb) -{ - sint8 ret = M2M_SUCCESS; - - if(pfOtaUpdateCb){ - gpfOtaUpdateCb = pfOtaUpdateCb; - }else{ - M2M_ERR("Invaild Ota update cb\n"); - } - if(pfOtaNotifCb){ - gpfOtaNotifCb = pfOtaNotifCb; - }else{ - M2M_ERR("Invaild Ota notify cb\n"); - } - - hif_register_cb(M2M_REQ_GROUP_OTA,m2m_ota_cb); - - return ret; -} -/*! -@fn \ - NMI_API sint8 m2m_ota_notif_set_url(uint8 * u8Url); - -@brief - Set the OTA url - -@param [in] u8Url - The url server address - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_notif_set_url(uint8 * u8Url) -{ - sint8 ret = M2M_SUCCESS; - uint16 u16UrlSize = m2m_strlen(u8Url) + 1; - /*Todo: we may change it to data pkt but we need to give it higer priority - but the priorty is not implemnted yet in data pkt - */ - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_NOTIF_SET_URL,u8Url,u16UrlSize,NULL,0,0); - return ret; - -} - -/*! -@fn \ - NMI_API sint8 m2m_ota_notif_check_for_update(void); - -@brief - check for ota update - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_notif_check_for_update(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_NOTIF_CHECK_FOR_UPDATE,NULL,0,NULL,0,0); - return ret; -} - -/*! -@fn \ - NMI_API sint8 m2m_ota_notif_sched(uint32 u32Period); - -@brief - Schedule OTA update - -@param [in] u32Period - Period in days - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_notif_sched(uint32 u32Period) -{ -#ifdef ARDUINO - (void)u32Period; // Silence "unused" warning -#endif - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_NOTIF_CHECK_FOR_UPDATE,NULL,0,NULL,0,0); - return ret; -} - -/*! -@fn \ - NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl); - -@brief - Request OTA start update using the downloaded url - -@param [in] u8DownloadUrl - The download firmware url, you get it from device info - -@return - The function SHALL return 0 for success and a negative value otherwise. - -*/ -NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl) -{ - sint8 ret = M2M_SUCCESS; - uint16 u16DurlSize = m2m_strlen(u8DownloadUrl) + 1; - /*Todo: we may change it to data pkt but we need to give it higer priority - but the priorty is not implemnted yet in data pkt - */ - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_START_FW_UPDATE,u8DownloadUrl,u16DurlSize,NULL,0,0); - return ret; -} -/*! -@fn \ - NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl); - -@brief - Request OTA start for the Cortus app image. - -@param [in] u8DownloadUrl - The cortus application image url. - -@return - The function SHALL return 0 for success and a negative value otherwise. - -*/ -NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl) -{ - sint8 ret = M2M_SUCCESS; - uint16 u16DurlSize = m2m_strlen(u8DownloadUrl) + 1; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_START_CRT_UPDATE,u8DownloadUrl,u16DurlSize,NULL,0,0); - return ret; -} - - -/*! -@fn \ - NMI_API sint8 m2m_ota_rollback(void); - -@brief - Request OTA Rollback image - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_rollback(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_ROLLBACK_FW,NULL,0,NULL,0,0); - return ret; -} -/*! -@fn \ - NMI_API sint8 m2m_ota_rollback_crt(void); - -@brief - Request Cortus application OTA Rollback image - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_rollback_crt(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_ROLLBACK_CRT,NULL,0,NULL,0,0); - return ret; -} - -/*! -@fn \ - NMI_API sint8 m2m_ota_abort(void); - -@brief - Request OTA Abort - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_abort(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_ABORT,NULL,0,NULL,0,0); - return ret; -} - - -/*! -@fn \ - NMI_API sint8 m2m_ota_switch_firmware(void); - -@brief - Switch to the upgraded Firmware - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_switch_firmware(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_SWITCH_FIRMWARE,NULL,0,NULL,0,0); - return ret; -} -/*! -@fn \ - NMI_API sint8 m2m_ota_switch_crt(void); - -@brief - Switch to the upgraded cortus application. - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_switch_crt(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_SWITCH_CRT_IMG,NULL,0,NULL,0,0); - return ret; -} - -/*! -@fn \ - NMI_API sint8 m2m_ota_get_firmware_version(tstrM2mRev * pstrRev); - -@brief - Get the OTA Firmware version. - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ota_get_firmware_version(tstrM2mRev * pstrRev) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_chip_wake(); - if(ret == M2M_SUCCESS) - { - ret = nm_get_ota_firmware_info(pstrRev); - hif_chip_sleep(); - } - return ret; -} -#if 0 -#define M2M_OTA_FILE "../../../m2m_ota.dat" -NMI_API sint8 m2m_ota_test(void) -{ - uint32 page = 0; - uint8 buffer[1500]; - uint32 u32Sz = 0; - sint8 ret = M2M_SUCCESS; - FILE *fp =NULL; - fp = fopen(M2M_OTA_FILE,"rb"); - if(fp) - { - fseek(fp, 0L, SEEK_END); - u32Sz = ftell(fp); - fseek(fp, 0L, SEEK_SET); - - while(u32Sz > 0) - { - { - page = (rand()%1400); - - if((page<100)||(page>1400)) page = 1400; - } - - if(u32Sz>page) - { - u32Sz-=page; - } - else - { - page = u32Sz; - u32Sz = 0; - } - printf("page %d\n", (int)page); - fread(buffer,page,1,fp); - ret = hif_send(M2M_REQ_GROUP_OTA,M2M_OTA_REQ_TEST|M2M_REQ_DATA_PKT,NULL,0,(uint8*)&buffer,page,0); - if(ret != M2M_SUCCESS) - { - M2M_ERR("\n"); - } - nm_bsp_sleep(1); - } - - } - else - { - M2M_ERR("nO err\n"); - } - return ret; -} -#endif - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_periph.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_periph.c deleted file mode 100644 index 0f8890b..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_periph.c +++ /dev/null @@ -1,187 +0,0 @@ -/** - * - * \file - * - * \brief NMC1500 Peripherials Application Interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "driver/include/m2m_periph.h" -#include "driver/source/nmasic.h" -#include "m2m_hif.h" - -#ifdef CONF_PERIPH - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#define GPIO_OP_DIR 0 -#define GPIO_OP_SET 1 -#define GPIO_OP_GET 2 -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -STATIC FUNCTIONS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -static sint8 get_gpio_idx(uint8 u8GpioNum) -{ - if(u8GpioNum >= M2M_PERIPH_GPIO_MAX) return -1; - if(u8GpioNum == M2M_PERIPH_GPIO15) { return 15; - } else if(u8GpioNum == M2M_PERIPH_GPIO16) { return 16; - } else if(u8GpioNum == M2M_PERIPH_GPIO18) { return 18; - } else if(u8GpioNum == M2M_PERIPH_GPIO3) { return 3; - } else if(u8GpioNum == M2M_PERIPH_GPIO4) { return 4; - } else if(u8GpioNum == M2M_PERIPH_GPIO5) { return 5; - } else if(u8GpioNum == M2M_PERIPH_GPIO6) { return 6; - } else { - return -2; - } -} -/* - * GPIO read/write skeleton with wakeup/sleep capability. - */ -static sint8 gpio_ioctl(uint8 op, uint8 u8GpioNum, uint8 u8InVal, uint8 * pu8OutVal) -{ - sint8 ret, gpio; - - ret = hif_chip_wake(); - if(ret != M2M_SUCCESS) goto _EXIT; - - gpio = get_gpio_idx(u8GpioNum); - if(gpio < 0) goto _EXIT1; - - if(op == GPIO_OP_DIR) { - ret = set_gpio_dir((uint8)gpio, u8InVal); - } else if(op == GPIO_OP_SET) { - ret = set_gpio_val((uint8)gpio, u8InVal); - } else if(op == GPIO_OP_GET) { - ret = get_gpio_val((uint8)gpio, pu8OutVal); - } - if(ret != M2M_SUCCESS) goto _EXIT1; - -_EXIT1: - ret = hif_chip_sleep(); -_EXIT: - return ret; -} -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION IMPLEMENTATION -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -sint8 m2m_periph_init(tstrPerphInitParam * param) -{ -#ifdef ARDUINO - (void)param; // Silence "unused" warning -#endif - return M2M_SUCCESS; -} - -sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir) -{ - return gpio_ioctl(GPIO_OP_DIR, u8GpioNum, u8GpioDir, NULL); -} - -sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal) -{ - return gpio_ioctl(GPIO_OP_SET, u8GpioNum, u8GpioVal, NULL); -} - -sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal) -{ - return gpio_ioctl(GPIO_OP_GET, u8GpioNum, 0, pu8GpioVal); -} - -sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn) -{ -#ifdef ARDUINO - (void)u8GpioNum; // Silence "unused" warning - (void)u8PullupEn; -#endif - /* TBD */ - return M2M_SUCCESS; -} - -sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)param; -#endif - /* TBD */ - return M2M_SUCCESS; -} - -sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)u8SlaveAddr; - (void)pu8Buf; - (void)u16BufLen; - (void)flags; -#endif - /* TBD */ - return M2M_SUCCESS; -} - -sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)u8SlaveAddr; - (void)pu8Buf; - (void)u16BufLen; - (void)pu16ReadLen; - (void)flags; -#endif - /* TBD */ - return M2M_SUCCESS; -} - - -sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable) -{ - return pullup_ctrl(pinmask, enable); -} -#endif /* CONF_PERIPH */ \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ssl.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ssl.c deleted file mode 100644 index 07513f7..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_ssl.c +++ /dev/null @@ -1,309 +0,0 @@ -/** - * - * \file - * - * \brief This module contains M2M Wi-Fi APIs implementation. - * - * Copyright (c) 2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "driver/include/m2m_ssl.h" -#include "driver/source/m2m_hif.h" -#include "driver/source/nmasic.h" - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -static tpfAppSSLCb gpfAppSSLCb = NULL; -static uint32 gu32HIFAddr = 0; - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/*! - @fn \ m2m_ssl_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) - @brief SSL callback function - @param [in] u8OpCode - HIF Opcode type. - @param [in] u16DataSize - HIF data length. - @param [in] u32Addr - HIF address. -*/ -static void m2m_ssl_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -{ -#ifdef ARDUINO - (void)u16DataSize; // Silence "unused" warning -#endif - sint8 s8tmp = M2M_SUCCESS; - switch(u8OpCode) - { - case M2M_SSL_REQ_ECC: - { - tstrEccReqInfo strEccREQ; - s8tmp = hif_receive(u32Addr, (uint8*)&strEccREQ, sizeof(tstrEccReqInfo), 0); - if(s8tmp == M2M_SUCCESS) - { - if (gpfAppSSLCb) - { - gu32HIFAddr = u32Addr + sizeof(tstrEccReqInfo); - gpfAppSSLCb(M2M_SSL_REQ_ECC, &strEccREQ); - } - } - } - break; - case M2M_SSL_RESP_SET_CS_LIST: - { - tstrSslSetActiveCsList strCsList; - s8tmp = hif_receive(u32Addr, (uint8*)&strCsList, sizeof(tstrSslSetActiveCsList), 0); - if(s8tmp == M2M_SUCCESS) - { - if (gpfAppSSLCb) - gpfAppSSLCb(M2M_SSL_RESP_SET_CS_LIST, &strCsList); - } - } - break; - } - if(s8tmp != M2M_SUCCESS) - { - M2M_ERR("Error receiving SSL from the HIF\n"); - } -} - - -/*! - @fn \ m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz) - @brief Sends ECC responses to the WINC - @param [in] strECCResp - ECC Response struct. - @param [in] pu8RspDataBuffe - Pointer of the response data to be sent. - @param [in] u16RspDataSz - Response data size. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_handshake_rsp(tstrEccReqInfo* strECCResp, uint8* pu8RspDataBuff, uint16 u16RspDataSz) -{ - sint8 s8Ret = M2M_SUCCESS; - - s8Ret = hif_send(M2M_REQ_GROUP_SSL, (M2M_SSL_RESP_ECC | M2M_REQ_DATA_PKT), (uint8*)strECCResp, sizeof(tstrEccReqInfo), pu8RspDataBuff, u16RspDataSz, sizeof(tstrEccReqInfo)); - - return s8Ret; -} - -/*! - @fn \ m2m_ssl_send_certs_to_winc(uint8* sector_buffer, uint32 sector_size) - @brief Sends certificates to the WINC - @param [in] pu8Buffer - Pointer to the certificates. - @param [in] u32BufferSz - Size of the certificates. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_send_certs_to_winc(uint8* pu8Buffer, uint32 u32BufferSz) -{ - sint8 s8Ret = M2M_SUCCESS; - - s8Ret = hif_send(M2M_REQ_GROUP_SSL, (M2M_SSL_IND_CERTS_ECC | M2M_REQ_DATA_PKT), NULL, 0, pu8Buffer, u32BufferSz, 0); - - return s8Ret; -} - -/*! - @fn \ m2m_ssl_retrieve_cert(uint32 u32ReadAddr, uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key) - @brief Retrieve the certificate to be verified from the WINC - @param [in] pu16CurveType - Pointer to the certificate curve type. - @param [in] pu8Hash - Pointer to the certificate hash. - @param [in] pu8Sig - Pointer to the certificate signature. - @param [in] pu8Key - Pointer to the certificate Key. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_retrieve_cert(uint16* pu16CurveType, uint8* pu8Hash, uint8* pu8Sig, tstrECPoint* pu8Key) -{ - uint8 bSetRxDone = 1; - uint16 u16HashSz, u16SigSz, u16KeySz; - sint8 s8Ret = M2M_SUCCESS; - - if(gu32HIFAddr == 0) return M2M_ERR_FAIL; - - if(hif_receive(gu32HIFAddr, (uint8*)pu16CurveType, 2, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += 2; - - if(hif_receive(gu32HIFAddr, (uint8*)&u16KeySz, 2, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += 2; - - if(hif_receive(gu32HIFAddr, (uint8*)&u16HashSz, 2, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += 2; - - if(hif_receive(gu32HIFAddr, (uint8*)&u16SigSz, 2, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += 2; - - (*pu16CurveType)= _htons((*pu16CurveType)); - pu8Key->u16Size = _htons(u16KeySz); - u16HashSz = _htons(u16HashSz); - u16SigSz = _htons(u16SigSz); - - if(hif_receive(gu32HIFAddr, pu8Key->X, pu8Key->u16Size * 2, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += (pu8Key->u16Size * 2); - - if(hif_receive(gu32HIFAddr, pu8Hash, u16HashSz, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += u16HashSz; - - if(hif_receive(gu32HIFAddr, pu8Sig, u16SigSz, 0) != M2M_SUCCESS) goto __ERR; - gu32HIFAddr += u16SigSz; - - bSetRxDone = 0; - -__ERR: - if(bSetRxDone) - { - s8Ret = M2M_ERR_FAIL; - hif_receive(0, NULL, 0, 1); - } - return s8Ret; -} - -/*! - @fn \ m2m_ssl_retrieve_hash(uint32 u32ReadAddr, uint8* pu8Hash, uint16 u16HashSz) - @brief Retrieve the certificate hash - @param [in] pu8Hash - Pointer to the certificate hash. - @param [in] u16HashSz - Hash size. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_retrieve_hash(uint8* pu8Hash, uint16 u16HashSz) -{ - uint8 bSetRxDone = 1; - sint8 s8Ret = M2M_SUCCESS; - - if(gu32HIFAddr == 0) return M2M_ERR_FAIL; - - if(hif_receive(gu32HIFAddr, pu8Hash, u16HashSz, 0) != M2M_SUCCESS) goto __ERR; - - bSetRxDone = 0; - -__ERR: - if(bSetRxDone) - { - s8Ret = M2M_ERR_FAIL; - hif_receive(0, NULL, 0, 1); - } - return s8Ret; -} - -/*! - @fn \ m2m_ssl_stop_processing_certs(void) - @brief Stops receiving from the HIF -*/ -NMI_API void m2m_ssl_stop_processing_certs(void) -{ - hif_receive(0, NULL, 0, 1); -} - -/*! - @fn \ m2m_ssl_ecc_process_done(void) - @brief Stops receiving from the HIF -*/ -NMI_API void m2m_ssl_ecc_process_done(void) -{ - gu32HIFAddr = 0; -} - -/*! -@fn \ - m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP); - Override the default Active SSL ciphers in the SSL module with a certain combination selected by the caller in the form of - a bitmap containing the required ciphers to be on. - There is no need to call this function if the application will not change the default ciphersuites. - -@param [in] u32SslCsBMP - Bitmap containing the desired ciphers to be enabled for the SSL module. The ciphersuites are defined in - @ref SSLCipherSuiteID. - The default ciphersuites are all ciphersuites supported by the firmware with the exception of ECC ciphersuites. - The caller can override the default with any desired combination, except for combinations involving both RSA - and ECC; if any RSA ciphersuite is enabled, then firmware will disable all ECC ciphersuites. - If u32SslCsBMP does not contain any ciphersuites supported by firmware, then the current active list will not - be changed. - -@return - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) -*/ -sint8 m2m_ssl_set_active_ciphersuites(uint32 u32SslCsBMP) -{ - sint8 s8Ret = M2M_SUCCESS; - tstrSslSetActiveCsList strCsList; - - strCsList.u32CsBMP = u32SslCsBMP; - s8Ret = hif_send(M2M_REQ_GROUP_SSL, M2M_SSL_REQ_SET_CS_LIST, (uint8*)&strCsList, sizeof(tstrSslSetActiveCsList), NULL, 0, 0); - - return s8Ret; -} - -/*! - @fn \ m2m_ssl_init(tpfAppSslCb pfAppSslCb); - @brief Initializes the SSL layer. - @param [in] pfAppSslCb - Application SSL callback function. - @return The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_ssl_init(tpfAppSSLCb pfAppSSLCb) -{ - sint8 s8Ret = M2M_SUCCESS; - - gpfAppSSLCb = pfAppSSLCb; - gu32HIFAddr = 0; - - s8Ret = hif_register_cb(M2M_REQ_GROUP_SSL,m2m_ssl_cb); - if (s8Ret != M2M_SUCCESS) - { - M2M_ERR("hif_register_cb() failed with ret=%d", s8Ret); - } - return s8Ret; -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_wifi.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_wifi.c deleted file mode 100644 index 7998623..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/m2m_wifi.c +++ /dev/null @@ -1,1522 +0,0 @@ -/** - * - * \file - * - * \brief This module contains M2M Wi-Fi APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "driver/include/m2m_wifi.h" -#include "driver/source/m2m_hif.h" -#include "driver/source/nmasic.h" - -static volatile uint8 gu8ChNum; -static volatile uint8 gu8scanInProgress = 0; -static tpfAppWifiCb gpfAppWifiCb = NULL; - - -#ifdef ETH_MODE -static tpfAppEthCb gpfAppEthCb = NULL; -static uint8* gau8ethRcvBuf=NULL; -static uint16 gu16ethRcvBufSize ; -#endif - - -//#define CONF_MGMT -#ifdef CONF_MGMT -static tpfAppMonCb gpfAppMonCb = NULL; -static struct _tstrMgmtCtrl -{ - uint8* pu8Buf; - uint16 u16Offset; - uint16 u16Sz; -} -gstrMgmtCtrl = {NULL, 0 , 0}; -#endif -/** -* @fn m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr, uint8 grp) -* @brief WiFi call back function -* @param [in] u8OpCode -* HIF Opcode type. -* @param [in] u16DataSize -* HIF data length. -* @param [in] u32Addr -* HIF address. -* @param [in] grp -* HIF group type. -* @author -* @date -* @version 1.0 -*/ -static void m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr) -{ -#ifdef ARDUINO - (void)u16DataSize; // Silence "unused" warning -#endif - uint8 rx_buf[8]; - if (u8OpCode == M2M_WIFI_RESP_CON_STATE_CHANGED) - { - tstrM2mWifiStateChanged strState; - if (hif_receive(u32Addr, (uint8*) &strState,sizeof(tstrM2mWifiStateChanged), 0) == M2M_SUCCESS) - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_CON_STATE_CHANGED, &strState); - } - } - else if (u8OpCode == M2M_WIFI_RESP_GET_SYS_TIME) - { - tstrSystemTime strSysTime; - if (hif_receive(u32Addr, (uint8*) &strSysTime,sizeof(tstrSystemTime), 0) == M2M_SUCCESS) - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_GET_SYS_TIME, &strSysTime); - } - } - else if(u8OpCode == M2M_WIFI_RESP_CONN_INFO) - { - tstrM2MConnInfo strConnInfo; - if(hif_receive(u32Addr, (uint8*)&strConnInfo, sizeof(tstrM2MConnInfo), 1) == M2M_SUCCESS) - { - if(gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_CONN_INFO, &strConnInfo); - } - } - else if (u8OpCode == M2M_WIFI_RESP_MEMORY_RECOVER) - { -#if 0 - if (hif_receive(u32Addr, rx_buf, 4, 1) == M2M_SUCCESS) - { - tstrM2mWifiStateChanged strState; - m2m_memcpy((uint8*) &strState, rx_buf,sizeof(tstrM2mWifiStateChanged)); - if (app_wifi_recover_cb) - app_wifi_recover_cb(strState.u8CurrState); - } -#endif - } - else if (u8OpCode == M2M_WIFI_REQ_DHCP_CONF) - { - tstrM2MIPConfig strIpConfig; -#ifdef ARDUINO - extern uint32 nmdrv_firm_ver; - uint16 rxSize = sizeof(tstrM2MIPConfig); - - if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 5, 0)) { - // for backwards compatibility with firmware 19.4.4 and older, - // the old tstrM2MIPConfig does not contain the u32DhcpLeaseTime field - rxSize -= sizeof(strIpConfig.u32DhcpLeaseTime); - } - - if (hif_receive(u32Addr, (uint8 *)&strIpConfig, rxSize, 0) == M2M_SUCCESS) -#else - if (hif_receive(u32Addr, (uint8 *)&strIpConfig, sizeof(tstrM2MIPConfig), 0) == M2M_SUCCESS) -#endif - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_REQ_DHCP_CONF, (uint8 *)&strIpConfig); - } - } - else if (u8OpCode == M2M_WIFI_REQ_WPS) - { - tstrM2MWPSInfo strWps; - m2m_memset((uint8*)&strWps,0,sizeof(tstrM2MWPSInfo)); - if(hif_receive(u32Addr, (uint8*)&strWps, sizeof(tstrM2MWPSInfo), 0) == M2M_SUCCESS) - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_REQ_WPS, &strWps); - } - } - else if (u8OpCode == M2M_WIFI_RESP_IP_CONFLICT) - { - uint32 u32ConflictedIP; - if(hif_receive(u32Addr, (uint8 *)&u32ConflictedIP, sizeof(u32ConflictedIP), 0) == M2M_SUCCESS) - { - M2M_INFO("Conflicted IP \" %u.%u.%u.%u \" \n", - BYTE_0(u32ConflictedIP),BYTE_1(u32ConflictedIP),BYTE_2(u32ConflictedIP),BYTE_3(u32ConflictedIP)); - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_IP_CONFLICT, NULL); - - } - } - else if (u8OpCode == M2M_WIFI_RESP_SCAN_DONE) - { - tstrM2mScanDone strState; - gu8scanInProgress = 0; - if(hif_receive(u32Addr, (uint8*)&strState, sizeof(tstrM2mScanDone), 0) == M2M_SUCCESS) - { - gu8ChNum = strState.u8NumofCh; - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_SCAN_DONE, &strState); - } - } - else if (u8OpCode == M2M_WIFI_RESP_SCAN_RESULT) - { - tstrM2mWifiscanResult strScanResult; - if(hif_receive(u32Addr, (uint8*)&strScanResult, sizeof(tstrM2mWifiscanResult), 0) == M2M_SUCCESS) - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_SCAN_RESULT, &strScanResult); - } - } - else if (u8OpCode == M2M_WIFI_RESP_CURRENT_RSSI) - { - if (hif_receive(u32Addr, rx_buf, 4, 0) == M2M_SUCCESS) - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_CURRENT_RSSI, rx_buf); - } - } - else if (u8OpCode == M2M_WIFI_RESP_CLIENT_INFO) - { - if (hif_receive(u32Addr, rx_buf, 4, 0) == M2M_SUCCESS) - { - if (gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_CLIENT_INFO, rx_buf); - } - } - else if(u8OpCode == M2M_WIFI_RESP_PROVISION_INFO) - { - tstrM2MProvisionInfo strProvInfo; - if(hif_receive(u32Addr, (uint8*)&strProvInfo, sizeof(tstrM2MProvisionInfo), 1) == M2M_SUCCESS) - { - if(gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_PROVISION_INFO, &strProvInfo); - } - } - else if(u8OpCode == M2M_WIFI_RESP_DEFAULT_CONNECT) - { - tstrM2MDefaultConnResp strResp; - if(hif_receive(u32Addr, (uint8*)&strResp, sizeof(tstrM2MDefaultConnResp), 1) == M2M_SUCCESS) - { - if(gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_DEFAULT_CONNECT, &strResp); - } - } - - else if(u8OpCode == M2M_WIFI_RESP_GET_PRNG) - { - tstrPrng strPrng; - if(hif_receive(u32Addr, (uint8*)&strPrng,sizeof(tstrPrng), 0) == M2M_SUCCESS) - { - if(hif_receive(u32Addr + sizeof(tstrPrng),strPrng.pu8RngBuff,strPrng.u16PrngSize, 1) == M2M_SUCCESS) - { - if(gpfAppWifiCb) - gpfAppWifiCb(M2M_WIFI_RESP_GET_PRNG,&strPrng); - } - } - } -#ifdef ETH_MODE - else if(u8OpCode == M2M_WIFI_RESP_ETHERNET_RX_PACKET) - { - uint8 u8SetRxDone; - tstrM2mIpRsvdPkt strM2mRsvd; - if(hif_receive(u32Addr, &strM2mRsvd ,sizeof(tstrM2mIpRsvdPkt), 0) == M2M_SUCCESS) - { - tstrM2mIpCtrlBuf strM2mIpCtrlBuf; - uint16 u16Offset = strM2mRsvd.u16PktOffset; - strM2mIpCtrlBuf.u16RemainigDataSize = strM2mRsvd.u16PktSz; - if((gpfAppEthCb) && (gau8ethRcvBuf) && (gu16ethRcvBufSize > 0)) - { - do - { - u8SetRxDone = 1; - if(strM2mIpCtrlBuf.u16RemainigDataSize > gu16ethRcvBufSize) - { - u8SetRxDone = 0; - strM2mIpCtrlBuf.u16DataSize = gu16ethRcvBufSize; - } - else - { - strM2mIpCtrlBuf.u16DataSize = strM2mIpCtrlBuf.u16RemainigDataSize; - } - - if(hif_receive(u32Addr + u16Offset, gau8ethRcvBuf, strM2mIpCtrlBuf.u16DataSize, u8SetRxDone) == M2M_SUCCESS) - { - strM2mIpCtrlBuf.u16RemainigDataSize -= strM2mIpCtrlBuf.u16DataSize; - u16Offset += strM2mIpCtrlBuf.u16DataSize; - gpfAppEthCb(M2M_WIFI_RESP_ETHERNET_RX_PACKET, gau8ethRcvBuf, &(strM2mIpCtrlBuf)); - } - else - { - break; - } - }while (strM2mIpCtrlBuf.u16RemainigDataSize > 0); - } - } - } -#endif /* ETH_MODE */ -#ifdef CONF_MGMT - else if(u8OpCode == M2M_WIFI_RESP_WIFI_RX_PACKET) - { - - tstrM2MWifiRxPacketInfo strRxPacketInfo; - if(u16DataSize >= sizeof(tstrM2MWifiRxPacketInfo)) { - if(hif_receive(u32Addr, (uint8*)&strRxPacketInfo, sizeof(tstrM2MWifiRxPacketInfo), 0) == M2M_SUCCESS) - { - u16DataSize -= sizeof(tstrM2MWifiRxPacketInfo); - if(u16DataSize > 0 && gstrMgmtCtrl.pu8Buf != NULL) - { - if(u16DataSize > (gstrMgmtCtrl.u16Sz + gstrMgmtCtrl.u16Offset)) - { - u16DataSize = gstrMgmtCtrl.u16Sz; - } - u32Addr += sizeof(tstrM2MWifiRxPacketInfo) + gstrMgmtCtrl.u16Offset; - if(hif_receive(u32Addr , gstrMgmtCtrl.pu8Buf, u16DataSize, 1) != M2M_SUCCESS) return; - } - if(gpfAppMonCb) - gpfAppMonCb(&strRxPacketInfo, gstrMgmtCtrl.pu8Buf,u16DataSize); - } - } else { - M2M_ERR("Incorrect mon data size %u\n", u16DataSize); - } - } -#endif - else - { - M2M_ERR("REQ Not defined %d\n",u8OpCode); - } -} - -sint8 m2m_wifi_download_mode() -{ - sint8 ret = M2M_SUCCESS; - /* Apply device specific initialization. */ - ret = nm_drv_init_download_mode(); - if(ret != M2M_SUCCESS) goto _EXIT0; - - - - enable_interrupts(); - -_EXIT0: - return ret; -} - -static sint8 m2m_validate_ap_parameters(CONST tstrM2MAPConfig* pstrM2MAPConfig) -{ - sint8 s8Ret = M2M_SUCCESS; - /* Check for incoming pointer */ - if(pstrM2MAPConfig == NULL) - { - M2M_ERR("INVALID POINTER\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - /* Check for SSID */ - if((m2m_strlen((uint8 *)pstrM2MAPConfig->au8SSID) <= 0) || (m2m_strlen((uint8 *)pstrM2MAPConfig->au8SSID) >= M2M_MAX_SSID_LEN)) - { - M2M_ERR("INVALID SSID\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - /* Check for Channel */ - if(pstrM2MAPConfig->u8ListenChannel > M2M_WIFI_CH_14 || pstrM2MAPConfig->u8ListenChannel < M2M_WIFI_CH_1) - { - M2M_ERR("INVALID CH\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - /* Check for DHCP Server IP address */ - if(!(pstrM2MAPConfig->au8DHCPServerIP[0] || pstrM2MAPConfig->au8DHCPServerIP[1])) - { - if(!(pstrM2MAPConfig->au8DHCPServerIP[2])) - { - M2M_ERR("INVALID DHCP SERVER IP\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - } - /* Check for Security */ - if(pstrM2MAPConfig->u8SecType == M2M_WIFI_SEC_OPEN) - { - goto ERR1; - } - else if(pstrM2MAPConfig->u8SecType == M2M_WIFI_SEC_WEP) - { - /* Check for WEP Key index */ - if((pstrM2MAPConfig->u8KeyIndx <= 0) || (pstrM2MAPConfig->u8KeyIndx > WEP_KEY_MAX_INDEX)) - { - M2M_ERR("INVALID KEY INDEX\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - /* Check for WEP Key size */ - if( (pstrM2MAPConfig->u8KeySz != WEP_40_KEY_STRING_SIZE) && - (pstrM2MAPConfig->u8KeySz != WEP_104_KEY_STRING_SIZE) - ) - { - M2M_ERR("INVALID KEY STRING SIZE\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - - if((m2m_strlen((uint8 *)pstrM2MAPConfig->au8WepKey) <= 0) || (m2m_strlen((uint8 *)pstrM2MAPConfig->au8WepKey) > WEP_104_KEY_STRING_SIZE)) - { - M2M_ERR("INVALID KEY SIZE\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - } - else if(pstrM2MAPConfig->u8SecType == M2M_WIFI_SEC_WPA_PSK) - { - /* Check for WPA Key size */ - if( ((pstrM2MAPConfig->u8KeySz + 1) < M2M_MIN_PSK_LEN) || ((pstrM2MAPConfig->u8KeySz + 1) > M2M_MAX_PSK_LEN)) - { - M2M_ERR("INVALID WPA KEY SIZE\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - } - else - { - M2M_ERR("INVALID AUTHENTICATION MODE\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR1; - } - -ERR1: - return s8Ret; -} -static sint8 m2m_validate_scan_options(tstrM2MScanOption* ptstrM2MScanOption) -{ - sint8 s8Ret = M2M_SUCCESS; - /* Check for incoming pointer */ - if(ptstrM2MScanOption == NULL) - { - M2M_ERR("INVALID POINTER\n"); - s8Ret = M2M_ERR_FAIL; - goto ERR; - } - /* Check for valid No of slots */ - if(ptstrM2MScanOption->u8NumOfSlot == 0) - { - M2M_ERR("INVALID No of scan slots! %d\n",ptstrM2MScanOption->u8NumOfSlot); - s8Ret = M2M_ERR_FAIL; - goto ERR; - } - /* Check for valid time of slots */ - if(ptstrM2MScanOption->u8SlotTime < 10 || ptstrM2MScanOption->u8SlotTime > 250) - { - M2M_ERR("INVALID scan slot time! %d\n",ptstrM2MScanOption->u8SlotTime); - s8Ret = M2M_ERR_FAIL; - goto ERR; - } - /* Check for valid No of probe requests per slot */ - if((ptstrM2MScanOption->u8ProbesPerSlot == 0)||(ptstrM2MScanOption->u8ProbesPerSlot > M2M_SCAN_DEFAULT_NUM_PROBE)) - { - M2M_ERR("INVALID No of probe requests per scan slot %d\n",ptstrM2MScanOption->u8ProbesPerSlot); - s8Ret = M2M_ERR_FAIL; - goto ERR; - } - /* Check for valid RSSI threshold */ - if((ptstrM2MScanOption->s8RssiThresh < -99) || (ptstrM2MScanOption->s8RssiThresh >= 0)) - { - M2M_ERR("INVALID RSSI threshold %d \n",ptstrM2MScanOption->s8RssiThresh); - s8Ret = M2M_ERR_FAIL; - } - -ERR: - return s8Ret; -} - -sint8 m2m_wifi_send_crl(tstrTlsCrlInfo* pCRL) -{ - sint8 s8Ret = M2M_ERR_FAIL; - s8Ret = hif_send(M2M_REQ_GROUP_SSL, M2M_SSL_IND_CRL|M2M_REQ_DATA_PKT, NULL, 0, (uint8*)pCRL, sizeof(tstrTlsCrlInfo), 0); - return s8Ret; -} - -sint8 m2m_wifi_init(tstrWifiInitParam * param) -{ - tstrM2mRev strtmp; - sint8 ret = M2M_SUCCESS; - uint8 u8WifiMode = M2M_WIFI_MODE_NORMAL; - - if(param == NULL) { - ret = M2M_ERR_FAIL; - goto _EXIT0; - } - - gpfAppWifiCb = param->pfAppWifiCb; - -#ifdef ETH_MODE - gpfAppEthCb = param->strEthInitParam.pfAppEthCb; - gau8ethRcvBuf = param->strEthInitParam.au8ethRcvBuf; - gu16ethRcvBufSize = param->strEthInitParam.u16ethRcvBufSize; - u8WifiMode = param->strEthInitParam.u8EthernetEnable; -#endif /* ETH_MODE */ - -#ifdef CONF_MGMT - gpfAppMonCb = param->pfAppMonCb; -#endif - gu8scanInProgress = 0; - /* Apply device specific initialization. */ - ret = nm_drv_init(&u8WifiMode); - if(ret != M2M_SUCCESS) goto _EXIT0; - /* Initialize host interface module */ - ret = hif_init(NULL); - if(ret != M2M_SUCCESS) goto _EXIT1; - - hif_register_cb(M2M_REQ_GROUP_WIFI,m2m_wifi_cb); - - ret = nm_get_firmware_full_info(&strtmp); - -#ifdef ARDUINO - if (M2M_ERR_FAIL == ret) - { - // for compatibility with firmware version 19.3.0 - ret = nm_get_firmware_info(&strtmp); - } -#endif - M2M_INFO("Firmware ver : %u.%u.%u Svnrev %u\n", strtmp.u8FirmwareMajor, strtmp.u8FirmwareMinor, strtmp.u8FirmwarePatch,strtmp.u16FirmwareSvnNum); - M2M_INFO("Firmware Build %s Time %s\n",strtmp.BuildDate,strtmp.BuildTime); - M2M_INFO("Firmware Min driver ver : %u.%u.%u\n", strtmp.u8DriverMajor, strtmp.u8DriverMinor, strtmp.u8DriverPatch); - M2M_INFO("Driver ver: %u.%u.%u\n", M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); - M2M_INFO("Driver built at %s\t%s\n",__DATE__,__TIME__); - if(M2M_ERR_FW_VER_MISMATCH == ret) - { - M2M_ERR("Mismatch Firmawre Version\n"); - } - - goto _EXIT0; - -_EXIT1: - nm_drv_deinit(NULL); -_EXIT0: - return ret; -} - -sint8 m2m_wifi_deinit(void * arg) -{ -#ifdef ARDUINO - (void)arg; // Silence "unused" warning -#endif - hif_deinit(NULL); - - nm_drv_deinit(NULL); - - return M2M_SUCCESS; -} - - -#ifdef ARDUINO -#include "socket/include/socket_buffer.h" -extern tstrSocketBuffer gastrSocketBuffer[]; -#endif - -sint8 m2m_wifi_handle_events(void * arg) -{ -#ifdef ARDUINO - (void)arg; // Silence "unused" warning - - uint8 i; - - /* Arduino API LIMITATION: */ - /* To be compliant with the standard Arduino WiFi API socket must be buffered. */ - /* WiFi101 shield does not have this ability and automatically pushes incoming */ - /* data to the Arduino MCU. Function m2m_wifi_handle_events() is taking care of */ - /* this transfer. Hence by ensuring that all the MCU socket buffers are available */ - /* we can perform the transfer. */ - /* However, if one socket buffer is full, we have to delay this transfer by */ - /* returning an error value, as we have no way of knowing which socket is about */ - /* to be used. */ - /* Consequently, the Arduino sketch must NOT block on reading only one socket if */ - /* several sockets are to be used. Instead, application must carefully read for */ - /* all sockets, anytime. */ - for (i = 0; i < MAX_SOCKET; ++i) { - if (gastrSocketBuffer[i].flag && (*(gastrSocketBuffer[i].flag) & SOCKET_BUFFER_FLAG_FULL)) { - return M2M_ERR_FAIL; - } - } -#endif - return hif_handle_isr(); -} - -sint8 m2m_wifi_default_connect(void) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DEFAULT_CONNECT, NULL, 0,NULL, 0,0); -} - -sint8 m2m_wifi_connect(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch) -{ - return m2m_wifi_connect_sc(pcSsid, u8SsidLen, u8SecType, pvAuthInfo, u16Ch,0); -} -sint8 m2m_wifi_connect_sc(char *pcSsid, uint8 u8SsidLen, uint8 u8SecType, void *pvAuthInfo, uint16 u16Ch, uint8 u8NoSaveCred) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mWifiConnect strConnect; - tstrM2MWifiSecInfo *pstrAuthInfo; - - if(u8SecType != M2M_WIFI_SEC_OPEN) - { - if(pvAuthInfo == NULL) - { - M2M_ERR("Key is not valid\n"); - ret = M2M_ERR_FAIL; - goto ERR1; - } - if((u8SecType == M2M_WIFI_SEC_WPA_PSK) && (m2m_strlen(pvAuthInfo) == (M2M_MAX_PSK_LEN-1))) - { - uint8 i = 0; - uint8* pu8Psk = (uint8*)pvAuthInfo; - while(i < (M2M_MAX_PSK_LEN-1)) - { - if(pu8Psk[i]<'0' || (pu8Psk[i]>'9' && pu8Psk[i] < 'A')|| (pu8Psk[i]>'F' && pu8Psk[i] < 'a') || pu8Psk[i] > 'f') - { - M2M_ERR("Invalid Key\n"); - ret = M2M_ERR_FAIL; - goto ERR1; - } - i++; - } - } - } - if((u8SsidLen<=0)||(u8SsidLen>=M2M_MAX_SSID_LEN)) - { - M2M_ERR("SSID LEN INVALID\n"); - ret = M2M_ERR_FAIL; - goto ERR1; - } - - if(u16Ch < M2M_WIFI_CH_1|| u16Ch > M2M_WIFI_CH_14) - { - if(u16Ch!=M2M_WIFI_CH_ALL) - { - M2M_ERR("CH INVALID\n"); - ret = M2M_ERR_FAIL; - goto ERR1; - } - } - - - m2m_memcpy(strConnect.au8SSID, (uint8*)pcSsid, u8SsidLen); - strConnect.au8SSID[u8SsidLen] = 0; - strConnect.u16Ch = NM_BSP_B_L_16(u16Ch); - /* Credentials will be Not be saved if u8NoSaveCred is set */ - strConnect.u8NoSaveCred = u8NoSaveCred ? 1:0; - pstrAuthInfo = &strConnect.strSec; - pstrAuthInfo->u8SecType = u8SecType; - - if(u8SecType == M2M_WIFI_SEC_WEP) - { - tstrM2mWifiWepParams * pstrWepParams = (tstrM2mWifiWepParams*)pvAuthInfo; - tstrM2mWifiWepParams *pstrWep = &pstrAuthInfo->uniAuth.strWepInfo; -#ifdef ARDUINO - pstrWep->u8KeyIndx =pstrWepParams->u8KeyIndx; -#else - pstrWep->u8KeyIndx =pstrWepParams->u8KeyIndx-1; -#endif - - if(pstrWep->u8KeyIndx >= WEP_KEY_MAX_INDEX) - { - M2M_ERR("Invalid Wep key index %d\n", pstrWep->u8KeyIndx); - ret = M2M_ERR_FAIL; - goto ERR1; - } -#ifdef ARDUINO - pstrWep->u8KeySz = pstrWepParams->u8KeySz; -#else - pstrWep->u8KeySz = pstrWepParams->u8KeySz-1; -#endif - if ((pstrWep->u8KeySz != WEP_40_KEY_STRING_SIZE)&& (pstrWep->u8KeySz != WEP_104_KEY_STRING_SIZE)) - { - M2M_ERR("Invalid Wep key length %d\n", pstrWep->u8KeySz); - ret = M2M_ERR_FAIL; - goto ERR1; - } - m2m_memcpy((uint8*)pstrWep->au8WepKey,(uint8*)pstrWepParams->au8WepKey, pstrWepParams->u8KeySz); - pstrWep->au8WepKey[pstrWepParams->u8KeySz] = 0; - - } - - - else if(u8SecType == M2M_WIFI_SEC_WPA_PSK) - { - uint16 u16KeyLen = m2m_strlen((uint8*)pvAuthInfo); - if((u16KeyLen <= 0)||(u16KeyLen >= M2M_MAX_PSK_LEN)) - { - M2M_ERR("Incorrect PSK key length\n"); - ret = M2M_ERR_FAIL; - goto ERR1; - } - m2m_memcpy(pstrAuthInfo->uniAuth.au8PSK, (uint8*)pvAuthInfo, u16KeyLen + 1); - } - else if(u8SecType == M2M_WIFI_SEC_802_1X) - { - m2m_memcpy((uint8*)&pstrAuthInfo->uniAuth.strCred1x, (uint8*)pvAuthInfo, sizeof(tstr1xAuthCredentials)); - } - else if(u8SecType == M2M_WIFI_SEC_OPEN) - { - - } - else - { - M2M_ERR("undefined sec type\n"); - ret = M2M_ERR_FAIL; - goto ERR1; - } - - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CONNECT, (uint8*)&strConnect, sizeof(tstrM2mWifiConnect),NULL, 0,0); - -ERR1: - return ret; -} - -sint8 m2m_wifi_disconnect(void) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISCONNECT, NULL, 0, NULL, 0,0); -} -sint8 m2m_wifi_set_mac_address(uint8 au8MacAddress[6]) -{ - tstrM2mSetMacAddress strTmp; - m2m_memcpy((uint8*) strTmp.au8Mac, (uint8*) au8MacAddress, 6); - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_MAC_ADDRESS, - (uint8*) &strTmp, sizeof(tstrM2mSetMacAddress), NULL, 0,0); -} - -sint8 m2m_wifi_set_static_ip(tstrM2MIPConfig * pstrStaticIPConf) -{ - pstrStaticIPConf->u32DNS = NM_BSP_B_L_32(pstrStaticIPConf->u32DNS); - pstrStaticIPConf->u32Gateway = NM_BSP_B_L_32(pstrStaticIPConf->u32Gateway); - pstrStaticIPConf->u32StaticIP = NM_BSP_B_L_32( - pstrStaticIPConf->u32StaticIP); - pstrStaticIPConf->u32SubnetMask = NM_BSP_B_L_32( - pstrStaticIPConf->u32SubnetMask); - return hif_send(M2M_REQ_GROUP_IP, M2M_IP_REQ_STATIC_IP_CONF, - (uint8*) pstrStaticIPConf, sizeof(tstrM2MIPConfig), NULL, 0,0); -} - -sint8 m2m_wifi_request_dhcp_client(void) -{ - /*legacy API should be removed */ - return 0; -} -sint8 m2m_wifi_request_dhcp_server(uint8* addr) -{ -#ifdef ARDUINO - (void)addr; // Silence "unused" warning -#endif - /*legacy API should be removed */ - return 0; -} -/*! -@fn NMI_API sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt * pstrM2mLsnInt); -@brief Set the Wi-Fi listen interval for power save operation. It is represented in units - of AP Beacon periods. -@param [in] pstrM2mLsnInt - Structure holding the listen interval configurations. -@return The function SHALL return 0 for success and a negative value otherwise. -@sa tstrM2mLsnInt , m2m_wifi_set_sleep_mode -@pre m2m_wifi_set_sleep_mode shall be called first -@warning The Function called once after initialization. -*/ -sint8 m2m_wifi_enable_dhcp(uint8 u8DhcpEn ) -{ - - uint8 u8Req; - u8Req = u8DhcpEn ? M2M_IP_REQ_ENABLE_DHCP : M2M_IP_REQ_DISABLE_DHCP; - return hif_send(M2M_REQ_GROUP_IP, u8Req, NULL, 0, NULL, 0, 0); - - -} - -sint8 m2m_wifi_set_lsn_int(tstrM2mLsnInt* pstrM2mLsnInt) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_LSN_INT, (uint8*)pstrM2mLsnInt, sizeof(tstrM2mLsnInt), NULL, 0, 0); -} - -sint8 m2m_wifi_set_cust_InfoElement(uint8* pau8M2mCustInfoElement) -{ - - sint8 ret = M2M_ERR_FAIL; - if(pau8M2mCustInfoElement != NULL) - { - if((pau8M2mCustInfoElement[0] + 1) < M2M_CUST_IE_LEN_MAX) - { - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CUST_INFO_ELEMENT|M2M_REQ_DATA_PKT, (uint8*)pau8M2mCustInfoElement, pau8M2mCustInfoElement[0]+1, NULL, 0, 0); - } - } - return ret; -} - -sint8 m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption) -{ - sint8 s8Ret = M2M_ERR_FAIL; - if(m2m_validate_scan_options (ptstrM2MScanOption) == M2M_SUCCESS) - { - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_SCAN_OPTION, (uint8*)ptstrM2MScanOption, sizeof(tstrM2MScanOption),NULL, 0,0); - } - return s8Ret; -} -sint8 m2m_wifi_set_scan_region(uint16 ScanRegion) -{ - sint8 s8Ret = M2M_ERR_FAIL; - tstrM2MScanRegion strScanRegion; - strScanRegion.u16ScanRegion = ScanRegion; - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_SCAN_REGION, (uint8*)&strScanRegion, sizeof(tstrM2MScanRegion),NULL, 0,0); - return s8Ret; -} -sint8 m2m_wifi_request_scan(uint8 ch) -{ - sint8 s8Ret = M2M_SUCCESS; - - if(!gu8scanInProgress) - { - if(((ch >= M2M_WIFI_CH_1) && (ch <= M2M_WIFI_CH_14)) || (ch == M2M_WIFI_CH_ALL)) - { - tstrM2MScan strtmp; - strtmp.u8ChNum = ch; - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SCAN, (uint8*)&strtmp, sizeof(tstrM2MScan),NULL, 0,0); - if(s8Ret == M2M_SUCCESS) - { - gu8scanInProgress = 1; - } - } - else - { - s8Ret = M2M_ERR_INVALID_ARG; - } - } - else - { - s8Ret = M2M_ERR_SCAN_IN_PROGRESS; - } - return s8Ret; -} - -sint8 m2m_wifi_request_scan_passive(uint8 ch, uint16 scan_time) -{ - sint8 s8Ret = M2M_SUCCESS; - - if(!gu8scanInProgress) - { - if(((ch >= M2M_WIFI_CH_1) && (ch <= M2M_WIFI_CH_14)) || (ch == M2M_WIFI_CH_ALL)) - { - tstrM2MScan strtmp; - strtmp.u8ChNum = ch; - - strtmp.u16PassiveScanTime = scan_time; - - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_PASSIVE_SCAN, (uint8*)&strtmp, sizeof(tstrM2MScan),NULL, 0,0); - if(s8Ret == M2M_SUCCESS) - { - gu8scanInProgress = 1; - } - } - else - { - s8Ret = M2M_ERR_INVALID_ARG; - } - } - else - { - s8Ret = M2M_ERR_SCAN_IN_PROGRESS; - } - return s8Ret; -} - -sint8 m2m_wifi_request_scan_ssid_list(uint8 ch,uint8 * u8Ssidlist) -{ - sint8 s8Ret = M2M_ERR_INVALID_ARG; - - if(!gu8scanInProgress) - { - if((((ch >= M2M_WIFI_CH_1) && (ch <= M2M_WIFI_CH_14)) || (ch == M2M_WIFI_CH_ALL))&&(u8Ssidlist != NULL)) - { - tstrM2MScan strtmp; - uint16 u16Lsize = 0; - uint8 u8Apnum = u8Ssidlist[u16Lsize]; - if(u8Apnum <= MAX_HIDDEN_SITES) - { - u16Lsize++; - while(u8Apnum) - { - if(u8Ssidlist[u16Lsize] >= M2M_MAX_SSID_LEN){ - goto EXIT; - }else { - u16Lsize += u8Ssidlist[u16Lsize] + 1; - u8Apnum--; - } - } - strtmp.u8ChNum = ch; - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SCAN_SSID_LIST|M2M_REQ_DATA_PKT, (uint8*)&strtmp, sizeof(tstrM2MScan),u8Ssidlist, u16Lsize,sizeof(tstrM2MScan)); - if(s8Ret == M2M_SUCCESS) - { - gu8scanInProgress = 1; - } - } - } - } - else - { - s8Ret = M2M_ERR_SCAN_IN_PROGRESS; - } -EXIT: - return s8Ret; -} -sint8 m2m_wifi_wps(uint8 u8TriggerType,const char *pcPinNumber) -{ - tstrM2MWPSConnect strtmp; - - /* Stop Scan if it is ongoing. - */ - gu8scanInProgress = 0; - strtmp.u8TriggerType = u8TriggerType; - /*If WPS is using PIN METHOD*/ - if (u8TriggerType == WPS_PIN_TRIGGER) - m2m_memcpy ((uint8*)strtmp.acPinNumber,(uint8*) pcPinNumber,8); - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_WPS, (uint8*)&strtmp,sizeof(tstrM2MWPSConnect), NULL, 0,0); -} -sint8 m2m_wifi_wps_disable(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_WPS, NULL,0, NULL, 0, 0); - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_req_client_ctrl(uint8 cmd); -@brief Send a command to the PS Client (An WINC1500 board running the ps_firmware), - if the PS client send any commands it will be received in wifi_cb M2M_WIFI_RESP_CLIENT_INFO -@param [in] cmd - Control command sent from PS Server to PS Client (command values defined by the application) -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. -@sa m2m_wifi_req_server_init, M2M_WIFI_RESP_CLIENT_INFO -@pre m2m_wifi_req_server_init should be called first -@warning -*/ -sint8 m2m_wifi_req_client_ctrl(uint8 u8Cmd) -{ - - sint8 ret = M2M_SUCCESS; -#ifdef _PS_SERVER_ - tstrM2Mservercmd strCmd; - strCmd.u8cmd = u8Cmd; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CLIENT_CTRL, (uint8*)&strCmd, sizeof(tstrM2Mservercmd), NULL, 0, 0); -#else -#ifdef ARDUINO - (void)u8Cmd; // Silence "unused" warning -#endif - M2M_ERR("_PS_SERVER_ is not defined\n"); -#endif - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_req_server_init(uint8 ch); -@brief Initialize the PS Server, The WINC1500 support Non secure communication with another WINC1500, - (SERVER/CLIENT) through one byte command (probe request and probe response) without any connection setup -@param [in] ch - Server listening channel -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise -@sa m2m_wifi_req_client_ctrl -@warning The server mode can't be used with any other modes (STA/P2P/AP) -*/ -sint8 m2m_wifi_req_server_init(uint8 ch) -{ - sint8 ret = M2M_SUCCESS; -#ifdef _PS_SERVER_ - tstrM2mServerInit strServer; - strServer.u8Channel = ch; - ret = hif_send(M2M_REQ_GROUP_WIFI,M2M_WIFI_REQ_SERVER_INIT, (uint8*)&strServer, sizeof(tstrM2mServerInit), NULL, 0, 0); -#else -#ifdef ARDUINO - (void)ch; // Silence "unused" warning -#endif - M2M_ERR("_PS_SERVER_ is not defined\n"); -#endif - return ret; -} -sint8 m2m_wifi_p2p(uint8 u8Channel) -{ - sint8 ret = M2M_SUCCESS; - if((u8Channel == M2M_WIFI_CH_1) || (u8Channel == M2M_WIFI_CH_6) || (u8Channel == M2M_WIFI_CH_11)) - { - tstrM2MP2PConnect strtmp; - strtmp.u8ListenChannel = u8Channel; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_P2P, (uint8*)&strtmp, sizeof(tstrM2MP2PConnect), NULL, 0,0); - } - else - { - M2M_ERR("Listen channel should only be M2M_WIFI_CH_1/6/11 \n"); - ret = M2M_ERR_FAIL; - } - return ret; -} -sint8 m2m_wifi_p2p_disconnect(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_P2P, NULL, 0, NULL, 0, 0); - return ret; -} -sint8 m2m_wifi_enable_ap(CONST tstrM2MAPConfig* pstrM2MAPConfig) -{ - sint8 ret = M2M_ERR_FAIL; - if(M2M_SUCCESS == m2m_validate_ap_parameters(pstrM2MAPConfig)) - { -#ifdef ARDUINO - extern uint32 nmdrv_firm_ver; - uint16 txSize = sizeof(tstrM2MAPConfig); - - if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 5, 0)) { - // for backwards compat with firmwware 19.4.x and older - // (listen channel is 0 based, there is no au8Key field) - ((tstrM2MAPConfig*)pstrM2MAPConfig)->u8ListenChannel--; - txSize -= sizeof(pstrM2MAPConfig->au8Key) + 1; - } - - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_AP, (uint8 *)pstrM2MAPConfig, txSize, NULL, 0, 0); -#else - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_AP, (uint8 *)pstrM2MAPConfig, sizeof(tstrM2MAPConfig), NULL, 0, 0); -#endif - } - return ret; -} - -sint8 m2m_wifi_set_gains(tstrM2mWifiGainsParams* pstrM2mGain) -{ - sint8 ret = M2M_ERR_FAIL; - if(pstrM2mGain != NULL) - { - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_GAINS, (uint8 *)pstrM2mGain, sizeof(tstrM2mWifiGainsParams), NULL, 0, 0); - } - return ret; -} -sint8 m2m_wifi_disable_ap(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_AP, NULL, 0, NULL, 0, 0); - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_req_curr_rssi(void); -@brief Request the current RSSI for the current connected AP, - the response received in wifi_cb M2M_WIFI_RESP_CURRENT_RSSI -@sa M2M_WIFI_RESP_CURRENT_RSSI -@return The function shall return M2M_SUCCESS for success and a negative value otherwise. -*/ -sint8 m2m_wifi_req_curr_rssi(void) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_CURRENT_RSSI, NULL, 0, NULL,0, 0); - return ret; -} -sint8 m2m_wifi_send_ethernet_pkt(uint8* pu8Packet,uint16 u16PacketSize) -{ - sint8 s8Ret = -1; - if((pu8Packet != NULL)&&(u16PacketSize>0)) - { - tstrM2MWifiTxPacketInfo strTxPkt; - - strTxPkt.u16PacketSize = u16PacketSize; - strTxPkt.u16HeaderLength = M2M_ETHERNET_HDR_LEN; - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SEND_ETHERNET_PACKET | M2M_REQ_DATA_PKT, - (uint8*)&strTxPkt, sizeof(tstrM2MWifiTxPacketInfo), pu8Packet, u16PacketSize, M2M_ETHERNET_HDR_OFFSET - M2M_HIF_HDR_OFFSET); - } - return s8Ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); -@brief Request the MAC address stored on the OTP (one time programmable) memory of the device. - (the function is Blocking until response received) -@param [out] pu8MacAddr - Output MAC address buffer of 6 bytes size. Valid only if *pu8Valid=1. -@param [out] pu8IsValid - A output boolean value to indicate the validity of pu8MacAddr in OTP. - Output zero if the OTP memory is not programmed, non-zero otherwise. -@return The function shall return M2M_SUCCESS for success and a negative value otherwise. -@sa m2m_wifi_get_mac_address -@pre m2m_wifi_init required to call any WIFI/socket function -*/ -sint8 m2m_wifi_get_otp_mac_address(uint8 *pu8MacAddr, uint8* pu8IsValid) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_chip_wake(); - if(ret == M2M_SUCCESS) - { - ret = nmi_get_otp_mac_address(pu8MacAddr, pu8IsValid); - if(ret == M2M_SUCCESS) - { - ret = hif_chip_sleep(); - } - } - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr) -@brief Request the current MAC address of the device (the working mac address). - (the function is Blocking until response received) -@param [out] pu8MacAddr - Output MAC address buffer of 6 bytes size. -@return The function shall return M2M_SUCCESS for success and a negative value otherwise. -@sa m2m_wifi_get_otp_mac_address -@pre m2m_wifi_init required to call any WIFI/socket function -*/ -sint8 m2m_wifi_get_mac_address(uint8 *pu8MacAddr) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_chip_wake(); - if(ret == M2M_SUCCESS) - { - ret = nmi_get_mac_address(pu8MacAddr); - if(ret == M2M_SUCCESS) - { - ret = hif_chip_sleep(); - } - } - - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_req_scan_result(uint8 index); -@brief Reads the AP information from the Scan Result list with the given index, - the response received in wifi_cb M2M_WIFI_RESP_SCAN_RESULT, - the response pointer should be casted with tstrM2mWifiscanResult structure -@param [in] index - Index for the requested result, the index range start from 0 till number of AP's found -@sa tstrM2mWifiscanResult,m2m_wifi_get_num_ap_found,m2m_wifi_request_scan -@return The function shall return M2M_SUCCESE for success and a negative value otherwise -@pre m2m_wifi_request_scan need to be called first, then m2m_wifi_get_num_ap_found - to get the number of AP's found -@warning Function used only in STA mode only. the scan result updated only if scan request called, - else it will be cashed in firmware for the host scan request result, - which mean if large delay occur between the scan request and the scan result request, - the result will not be up-to-date -*/ - -sint8 m2m_wifi_req_scan_result(uint8 index) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mReqScanResult strReqScanRlt; - strReqScanRlt.u8Index = index; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SCAN_RESULT, (uint8*) &strReqScanRlt, sizeof(tstrM2mReqScanResult), NULL, 0, 0); - return ret; -} -/*! -@fn NMI_API uint8 m2m_wifi_get_num_ap_found(void); -@brief Reads the number of AP's found in the last Scan Request, - The function read the number of AP's from global variable which updated in the - wifi_cb in M2M_WIFI_RESP_SCAN_DONE. -@sa m2m_wifi_request_scan -@return Return the number of AP's found in the last Scan Request. -@pre m2m_wifi_request_scan need to be called first -@warning That function need to be called in the wifi_cb in M2M_WIFI_RESP_SCAN_DONE, - calling that function in any other place will return undefined/undated numbers. - Function used only in STA mode only. -*/ -uint8 m2m_wifi_get_num_ap_found(void) -{ - return gu8ChNum; -} -/*! -@fn NMI_API uint8 m2m_wifi_get_sleep_mode(void); -@brief Get the current Power save mode. -@return The current operating power saving mode. -@sa tenuPowerSaveModes , m2m_wifi_set_sleep_mode -*/ -uint8 m2m_wifi_get_sleep_mode(void) -{ - return hif_get_sleep_mode(); -} -/*! -@fn NMI_API sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn); -@brief Set the power saving mode for the WINC1500. -@param [in] PsTyp - Desired power saving mode. Supported types are defined in tenuPowerSaveModes. -@param [in] BcastEn - Broadcast reception enable flag. - If it is 1, the WINC1500 must be awake each DTIM Beacon for receiving Broadcast traffic. - If it is 0, the WINC1500 will not wakeup at the DTIM Beacon, but its wakeup depends only - on the the configured Listen Interval. -@return The function SHALL return 0 for success and a negative value otherwise. -@sa tenuPowerSaveModes -@warning The function called once after initialization. -*/ -sint8 m2m_wifi_set_sleep_mode(uint8 PsTyp, uint8 BcastEn) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mPsType strPs; - strPs.u8PsType = PsTyp; - strPs.u8BcastEn = BcastEn; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SLEEP, (uint8*) &strPs,sizeof(tstrM2mPsType), NULL, 0, 0); - M2M_INFO("POWER SAVE %d\n",PsTyp); - hif_set_sleep_mode(PsTyp); - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_request_sleep(void) -@brief Request from WINC1500 device to Sleep for specific time in the M2M_PS_MANUAL Power save mode (only). -@param [in] u32SlpReqTime - Request Sleep in ms -@return The function SHALL return M2M_SUCCESS for success and a negative value otherwise. -@sa tenuPowerSaveModes , m2m_wifi_set_sleep_mode -@warning the Function should be called in M2M_PS_MANUAL power save only -*/ -sint8 m2m_wifi_request_sleep(uint32 u32SlpReqTime) -{ - sint8 ret = M2M_SUCCESS; - uint8 psType; - psType = hif_get_sleep_mode(); - if(psType == M2M_PS_MANUAL) - { - tstrM2mSlpReqTime strPs; - strPs.u32SleepTime = u32SlpReqTime; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DOZE, (uint8*) &strPs,sizeof(tstrM2mSlpReqTime), NULL, 0, 0); - } - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength); -@brief Set the WINC1500 device name which is used as P2P device name. -@param [in] pu8DeviceName - Buffer holding the device name. -@param [in] u8DeviceNameLength - Length of the device name. -@return The function SHALL return M2M_SUCCESS for success and a negative value otherwise. -@warning The Function called once after initialization. -*/ -sint8 m2m_wifi_set_device_name(uint8 *pu8DeviceName, uint8 u8DeviceNameLength) -{ - tstrM2MDeviceNameConfig strDeviceName; - if(u8DeviceNameLength >= M2M_DEVICE_NAME_MAX) - { - u8DeviceNameLength = M2M_DEVICE_NAME_MAX; - } - //pu8DeviceName[u8DeviceNameLength] = '\0'; - u8DeviceNameLength ++; - m2m_memcpy(strDeviceName.au8DeviceName, pu8DeviceName, u8DeviceNameLength); - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_DEVICE_NAME, - (uint8*)&strDeviceName, sizeof(tstrM2MDeviceNameConfig), NULL, 0,0); -} -sint8 m2m_wifi_get_firmware_version(tstrM2mRev *pstrRev) -{ - sint8 ret = M2M_SUCCESS; - ret = hif_chip_wake(); - if(ret == M2M_SUCCESS) - { - ret = nm_get_firmware_full_info(pstrRev); - hif_chip_sleep(); - } - return ret; -} -#ifdef CONF_MGMT -sint8 m2m_wifi_enable_monitoring_mode(tstrM2MWifiMonitorModeCtrl *pstrMtrCtrl, uint8 *pu8PayloadBuffer, - uint16 u16BufferSize, uint16 u16DataOffset) -{ - sint8 s8Ret = -1; - if((pstrMtrCtrl->u8ChannelID >= M2M_WIFI_CH_1) && (pstrMtrCtrl->u8ChannelID <= M2M_WIFI_CH_14)) - { - gstrMgmtCtrl.pu8Buf = pu8PayloadBuffer; - gstrMgmtCtrl.u16Sz = u16BufferSize; - gstrMgmtCtrl.u16Offset = u16DataOffset; - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_ENABLE_MONITORING, - (uint8*)pstrMtrCtrl, sizeof(tstrM2MWifiMonitorModeCtrl), NULL, 0,0); - } - return s8Ret; -} - -sint8 m2m_wifi_disable_monitoring_mode(void) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_DISABLE_MONITORING, NULL, 0, NULL, 0,0); -} - -sint8 m2m_wifi_send_wlan_pkt(uint8 *pu8WlanPacket, uint16 u16WlanHeaderLength, uint16 u16WlanPktSize) -{ - sint8 s8Ret = -1; - if(pu8WlanPacket != NULL) - { - tstrM2MWifiTxPacketInfo strTxPkt; - - strTxPkt.u16PacketSize = u16WlanPktSize; - strTxPkt.u16HeaderLength = u16WlanHeaderLength; - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SEND_WIFI_PACKET | M2M_REQ_DATA_PKT, - (uint8*)&strTxPkt, sizeof(tstrM2MWifiTxPacketInfo), pu8WlanPacket, u16WlanPktSize, sizeof(tstrM2MWifiTxPacketInfo)); - } - return s8Ret; -} -#endif - -sint8 m2m_wifi_start_provision_mode(tstrM2MAPConfig *pstrAPConfig, char *pcHttpServerDomainName, uint8 bEnableHttpRedirect) -{ - sint8 s8Ret = M2M_ERR_FAIL; - - if((pstrAPConfig != NULL)) - { - tstrM2MProvisionModeConfig strProvConfig; - if(M2M_SUCCESS == m2m_validate_ap_parameters(pstrAPConfig)) - { - m2m_memcpy((uint8*)&strProvConfig.strApConfig, (uint8*)pstrAPConfig, sizeof(tstrM2MAPConfig)); - if((m2m_strlen((uint8 *)pcHttpServerDomainName) <= 0) || (NULL == pcHttpServerDomainName)) - { - M2M_ERR("INVALID DOMAIN NAME\n"); - goto ERR1; - } - m2m_memcpy((uint8*)strProvConfig.acHttpServerDomainName, (uint8*)pcHttpServerDomainName, 64); - strProvConfig.u8EnableRedirect = bEnableHttpRedirect; - - /* Stop Scan if it is ongoing. - */ - gu8scanInProgress = 0; -#ifdef ARDUINO - extern uint32 nmdrv_firm_ver; - uint16 txSize = sizeof(tstrM2MProvisionModeConfig); - - if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 5, 0)) { - // for backwards compat with firmwware 19.4.x and older - // (listen channel is 0 based, there is no au8Key field) - strProvConfig.strApConfig.u8ListenChannel--; - txSize -= sizeof(strProvConfig.strApConfig.au8Key) + 1; - m2m_memcpy((uint8*)&strProvConfig.strApConfig.au8Key[3], (uint8*)pcHttpServerDomainName, 64); - uint8* pu8EnableRedirect = (uint8*)strProvConfig.strApConfig.au8Key; - pu8EnableRedirect[3 + 64] = bEnableHttpRedirect; - } - - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_START_PROVISION_MODE | M2M_REQ_DATA_PKT, - (uint8*)&strProvConfig, txSize, NULL, 0, 0); -#else - s8Ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_START_PROVISION_MODE | M2M_REQ_DATA_PKT, - (uint8*)&strProvConfig, sizeof(tstrM2MProvisionModeConfig), NULL, 0, 0); -#endif - } - else - { - /*goto ERR1;*/ - } - } -ERR1: - return s8Ret; -} - -sint8 m2m_wifi_stop_provision_mode(void) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_STOP_PROVISION_MODE, NULL, 0, NULL, 0, 0); -} - -sint8 m2m_wifi_get_connection_info(void) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_GET_CONN_INFO, NULL, 0, NULL, 0, 0); -} - -sint8 m2m_wifi_set_sytem_time(uint32 u32UTCSeconds) -{ - /* - The firmware accepts timestamps relative to 1900 like NTP Timestamp. - */ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_SYS_TIME, (uint8*)&u32UTCSeconds, sizeof(tstrSystemTime), NULL, 0, 0); -} -/*! - * @fn NMI_API sint8 m2m_wifi_get_sytem_time(void); - * @see m2m_wifi_enable_sntp - tstrSystemTime - * @note get the system time from the sntp client - * using the API \ref m2m_wifi_get_sytem_time. - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -sint8 m2m_wifi_get_sytem_time(void) -{ - return hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_GET_SYS_TIME, NULL,0, NULL, 0, 0); -} - -sint8 m2m_wifi_enable_sntp(uint8 bEnable) -{ - uint8 u8Req; - - u8Req = bEnable ? M2M_WIFI_REQ_ENABLE_SNTP_CLIENT : M2M_WIFI_REQ_DISABLE_SNTP_CLIENT; - return hif_send(M2M_REQ_GROUP_WIFI, u8Req, NULL, 0, NULL, 0, 0); -} -/*! -@fn NMI_API sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode); -@brief Change the power profile mode -@param [in] u8PwrMode - Change the WINC power profile to different mode - PWR_LOW1/PWR_LOW2/PWR_HIGH/PWR_AUTO (tenuM2mPwrMode) -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. -@sa tenuM2mPwrMode -@pre m2m_wifi_init -@warning must be called after the initializations and before any connection request and can't be changed in run time, -*/ -sint8 m2m_wifi_set_power_profile(uint8 u8PwrMode) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mPwrMode strM2mPwrMode; - strM2mPwrMode.u8PwrMode = u8PwrMode; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_POWER_PROFILE, (uint8*)&strM2mPwrMode,sizeof(tstrM2mPwrMode), NULL, 0, 0); - return ret; -} -/*! -@fn NMI_API sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel); -@brief set the TX power tenuM2mTxPwrLevel -@param [in] u8TxPwrLevel - change the TX power tenuM2mTxPwrLevel -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. -@sa tenuM2mTxPwrLevel -@pre m2m_wifi_init -@warning -*/ -sint8 m2m_wifi_set_tx_power(uint8 u8TxPwrLevel) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mTxPwrLevel strM2mTxPwrLevel; - strM2mTxPwrLevel.u8TxPwrLevel = u8TxPwrLevel; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_TX_POWER, (uint8*)&strM2mTxPwrLevel,sizeof(tstrM2mTxPwrLevel), NULL, 0, 0); - return ret; -} - -/*! -@fn NMI_API sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable); -@brief Enable or Disable logs in run time (Disable Firmware logs will - enhance the firmware start-up time and performance) -@param [in] u8Enable - Set 1 to enable the logs 0 for disable -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. -@sa __DISABLE_FIRMWARE_LOGS__ (build option to disable logs from initializations) -@pre m2m_wifi_init -@warning -*/ -sint8 m2m_wifi_enable_firmware_logs(uint8 u8Enable) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mEnableLogs strM2mEnableLogs; - strM2mEnableLogs.u8Enable = u8Enable; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_ENABLE_LOGS, (uint8*)&strM2mEnableLogs,sizeof(tstrM2mEnableLogs), NULL, 0, 0); - return ret; -} - -/*! -@fn NMI_API sint8 m2m_wifi_set_battery_voltage(uint16 u16BattVoltx100); -@brief Enable or Disable logs in run time (Disable Firmware logs will - enhance the firmware start-up time and performance) -@param [in] u16BattVoltx100 - battery voltage multiplied by 100 -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. -@sa __DISABLE_FIRMWARE_LOGS__ (build option to disable logs from initializations) -@pre m2m_wifi_init -@warning -*/ -sint8 m2m_wifi_set_battery_voltage(uint16 u16BattVoltx100) -{ - sint8 ret = M2M_SUCCESS; - tstrM2mBatteryVoltage strM2mBattVol = {0}; - strM2mBattVol.u16BattVolt = u16BattVoltx100; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_BATTERY_VOLTAGE, (uint8*)&strM2mBattVol,sizeof(tstrM2mBatteryVoltage), NULL, 0, 0); - return ret; -} -/*! -@fn sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PrngBuff,uint16 u16PrngSize) -@brief Get random bytes using the PRNG bytes. -@param [in] u16PrngSize - Size of the required random bytes to be generated. -@param [in] pu8PrngBuff - Pointer to user allocated buffer. -@return The function SHALL return M2M_SUCCESE for success and a negative value otherwise. -*/ -sint8 m2m_wifi_prng_get_random_bytes(uint8 * pu8PrngBuff,uint16 u16PrngSize) -{ - sint8 ret = M2M_ERR_FAIL; - tstrPrng strRng = {0}; - if((u16PrngSize < (M2M_BUFFER_MAX_SIZE - sizeof(tstrPrng)))&&(pu8PrngBuff != NULL)) - { - strRng.u16PrngSize = u16PrngSize; - strRng.pu8RngBuff = pu8PrngBuff; - ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_GET_PRNG|M2M_REQ_DATA_PKT,(uint8 *)&strRng, sizeof(tstrPrng),NULL,0, 0); - } - else - { - M2M_ERR("PRNG Buffer exceeded maximum size %d or NULL Buffer\n",u16PrngSize); - } - return ret; -} -#ifdef ETH_MODE -/*! -@fn \ - NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8* pu8MulticastMacAddress, uint8 u8AddRemove) - -@brief - Add MAC filter to receive Multicast packets. - -@param [in] pu8MulticastMacAddress - Pointer to the MAC address. -@param [in] u8AddRemove - Flag to Add/Remove MAC address. -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ - -NMI_API sint8 m2m_wifi_enable_mac_mcast(uint8* pu8MulticastMacAddress, uint8 u8AddRemove) -{ - sint8 s8ret = M2M_ERR_FAIL; - tstrM2MMulticastMac strMulticastMac; - - if(pu8MulticastMacAddress != NULL ) - { - strMulticastMac.u8AddRemove = u8AddRemove; - m2m_memcpy(strMulticastMac.au8macaddress,pu8MulticastMacAddress,M2M_MAC_ADDRES_LEN); - M2M_DBG("mac multicast: %x:%x:%x:%x:%x:%x\r\n",strMulticastMac.au8macaddress[0],strMulticastMac.au8macaddress[1],strMulticastMac.au8macaddress[2],strMulticastMac.au8macaddress[3],strMulticastMac.au8macaddress[4],strMulticastMac.au8macaddress[5]); - s8ret = hif_send(M2M_REQ_GROUP_WIFI, M2M_WIFI_REQ_SET_MAC_MCAST, (uint8 *)&strMulticastMac,sizeof(tstrM2MMulticastMac),NULL,0,0); - } - - return s8ret; - -} - -/*! -@fn \ - NMI_API sint8 m2m_wifi_set_receive_buffer(void* pvBuffer,uint16 u16BufferLen); - -@brief - set the ethernet receive buffer, should be called in the receive call back. - -@param [in] pvBuffer - Pointer to the ethernet receive buffer. -@param [in] u16BufferLen - Length of the buffer. - -@return - The function SHALL return 0 for success and a negative value otherwise. -*/ -NMI_API sint8 m2m_wifi_set_receive_buffer(void* pvBuffer,uint16 u16BufferLen) -{ - sint8 s8ret = M2M_SUCCESS; - if(pvBuffer != NULL) - { - gau8ethRcvBuf = pvBuffer; - gu16ethRcvBufSize= u16BufferLen; - } - else - { - s8ret = M2M_ERR_FAIL; - M2M_ERR("Buffer NULL pointer\r\n"); - } - return s8ret; -} -#endif /* ETH_MODE */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmasic.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmasic.c deleted file mode 100644 index 91c0e5a..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmasic.c +++ /dev/null @@ -1,688 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 ASIC specific internal APIs. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "common/include/nm_common.h" -#include "driver/source/nmbus.h" -#include "bsp/include/nm_bsp.h" -#include "driver/source/nmasic.h" -#include "driver/include/m2m_types.h" - -#define NMI_GLB_RESET_0 (NMI_PERIPH_REG_BASE + 0x400) -#define NMI_INTR_REG_BASE (NMI_PERIPH_REG_BASE + 0xa00) -#define NMI_PIN_MUX_0 (NMI_PERIPH_REG_BASE + 0x408) -#define NMI_INTR_ENABLE (NMI_INTR_REG_BASE) -#define GET_UINT32(X,Y) (X[0+Y] + ((uint32)X[1+Y]<<8) + ((uint32)X[2+Y]<<16) +((uint32)X[3+Y]<<24)) - -/*SPI and I2C only*/ -#define CORT_HOST_COMM (0x10) -#define HOST_CORT_COMM (0x0b) -#define WAKE_CLK_REG (0x1) -#define CLOCKS_EN_REG (0xf) - - - -#ifdef ARDUINO -#define TIMEOUT (2000) -#else -#define TIMEOUT (0xfffffffful) -#endif -#define WAKUP_TRAILS_TIMEOUT (4) - -sint8 chip_apply_conf(uint32 u32Conf) -{ - sint8 ret = M2M_SUCCESS; - uint32 val32 = u32Conf; - -#if (defined __ENABLE_PMU__) || (defined CONF_WINC_INT_PMU) - val32 |= rHAVE_USE_PMU_BIT; -#endif -#ifdef __ENABLE_SLEEP_CLK_SRC_RTC__ - val32 |= rHAVE_SLEEP_CLK_SRC_RTC_BIT; -#elif defined __ENABLE_SLEEP_CLK_SRC_XO__ - val32 |= rHAVE_SLEEP_CLK_SRC_XO_BIT; -#endif -#ifdef __ENABLE_EXT_PA_INV_TX_RX__ - val32 |= rHAVE_EXT_PA_INV_TX_RX; -#endif -#ifdef __ENABLE_LEGACY_RF_SETTINGS__ - val32 |= rHAVE_LEGACY_RF_SETTINGS; -#endif -#ifdef __DISABLE_FIRMWARE_LOGS__ - val32 |= rHAVE_LOGS_DISABLED_BIT; -#endif - - val32 |= rHAVE_RESERVED1_BIT; - do { - nm_write_reg(rNMI_GP_REG_1, val32); - if(val32 != 0) { - uint32 reg = 0; - ret = nm_read_reg_with_ret(rNMI_GP_REG_1, ®); - if(ret == M2M_SUCCESS) { - if(reg == val32) - break; - } - } else { - break; - } - } while(1); - - return M2M_SUCCESS; -} -void chip_idle(void) -{ - uint32 reg = 0; - nm_read_reg_with_ret(WAKE_CLK_REG, ®); - if(reg & NBIT1) - { - reg &=~ NBIT1; - nm_write_reg(WAKE_CLK_REG, reg); - } -} - -sint8 enable_interrupts(void) -{ - uint32 reg = 0; - sint8 ret = M2M_SUCCESS; - /** - interrupt pin mux select - **/ - ret = nm_read_reg_with_ret(NMI_PIN_MUX_0, ®); - if (M2M_SUCCESS != ret) goto ERR1; - - reg |= ((uint32) 1 << 8); - ret = nm_write_reg(NMI_PIN_MUX_0, reg); - if (M2M_SUCCESS != ret) goto ERR1; - - /** - interrupt enable - **/ - ret = nm_read_reg_with_ret(NMI_INTR_ENABLE, ®); - if (M2M_SUCCESS != ret) goto ERR1; - - reg |= ((uint32) 1 << 16); - ret = nm_write_reg(NMI_INTR_ENABLE, reg); - if (M2M_SUCCESS != ret) goto ERR1; -ERR1: - return ret; -} - -sint8 cpu_start(void) { - uint32 reg = 0; - sint8 ret; - - /** - reset regs - */ - ret = nm_write_reg(BOOTROM_REG,0); - ret += nm_write_reg(NMI_STATE_REG,0); - ret += nm_write_reg(NMI_REV_REG,0); - /** - Go... - **/ - ret += nm_read_reg_with_ret(0x1118, ®); - reg |= (1 << 0); - ret += nm_write_reg(0x1118, reg); - ret += nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); - if ((reg & (1ul << 10)) == (1ul << 10)) { - reg &= ~(1ul << 10); - ret += nm_write_reg(NMI_GLB_RESET_0, reg); - } - reg |= (1ul << 10); - ret += nm_write_reg(NMI_GLB_RESET_0, reg); - nm_bsp_sleep(1); - return ret; -} - -uint32 nmi_get_chipid(void) -{ - static uint32 chipid = 0; - - if (chipid == 0) { - uint32 rfrevid; - - if((nm_read_reg_with_ret(0x1000, &chipid)) != M2M_SUCCESS) { - chipid = 0; - return 0; - } - //if((ret = nm_read_reg_with_ret(0x11fc, &revid)) != M2M_SUCCESS) { - // return 0; - //} - if((nm_read_reg_with_ret(0x13f4, &rfrevid)) != M2M_SUCCESS) { - chipid = 0; - return 0; - } - - if (chipid == 0x1002a0) { - if (rfrevid == 0x1) { /* 1002A0 */ - } else /* if (rfrevid == 0x2) */ { /* 1002A1 */ - chipid = 0x1002a1; - } - } else if(chipid == 0x1002b0) { - if(rfrevid == 3) { /* 1002B0 */ - } else if(rfrevid == 4) { /* 1002B1 */ - chipid = 0x1002b1; - } else /* if(rfrevid == 5) */ { /* 1002B2 */ - chipid = 0x1002b2; - } - }else if(chipid == 0x1000F0) { - if((nm_read_reg_with_ret(0x3B0000, &chipid)) != M2M_SUCCESS) { - chipid = 0; - return 0; - } - }else { - - } -//#define PROBE_FLASH -#ifdef PROBE_FLASH - if(chipid) { - UWORD32 flashid; - - flashid = probe_spi_flash(); - if(flashid == 0x1230ef) { - chipid &= ~(0x0f0000); - chipid |= 0x050000; - } - if(flashid == 0xc21320c2) { - chipid &= ~(0x0f0000); - chipid |= 0x050000; - } - } -#else - /*M2M is by default have SPI flash*/ - chipid &= ~(0x0f0000); - chipid |= 0x050000; -#endif /* PROBE_FLASH */ - } - return chipid; -} - -uint32 nmi_get_rfrevid(void) -{ - uint32 rfrevid; - if((nm_read_reg_with_ret(0x13f4, &rfrevid)) != M2M_SUCCESS) { - rfrevid = 0; - return 0; - } - return rfrevid; -} - -void restore_pmu_settings_after_global_reset(void) -{ - /* - * Must restore PMU register value after - * global reset if PMU toggle is done at - * least once since the last hard reset. - */ - if(REV(nmi_get_chipid()) >= REV_2B0) { - nm_write_reg(0x1e48, 0xb78469ce); - } -} - -void nmi_update_pll(void) -{ - uint32 pll; - - pll = nm_read_reg(0x1428); - pll &= ~0x1ul; - nm_write_reg(0x1428, pll); - pll |= 0x1ul; - nm_write_reg(0x1428, pll); - -} -void nmi_set_sys_clk_src_to_xo(void) -{ - uint32 val32; - - /* Switch system clock source to XO. This will take effect after nmi_update_pll(). */ - val32 = nm_read_reg(0x141c); - val32 |= (1 << 2); - nm_write_reg(0x141c, val32); - - /* Do PLL update */ - nmi_update_pll(); -} -sint8 chip_sleep(void) -{ - uint32 reg; - sint8 ret = M2M_SUCCESS; - - while(1) - { - ret = nm_read_reg_with_ret(CORT_HOST_COMM,®); - if(ret != M2M_SUCCESS) goto ERR1; - if((reg & NBIT0) == 0) break; - } - - /* Clear bit 1 */ - ret = nm_read_reg_with_ret(WAKE_CLK_REG, ®); - if(ret != M2M_SUCCESS)goto ERR1; - if(reg & NBIT1) - { - reg &=~NBIT1; - ret = nm_write_reg(WAKE_CLK_REG, reg); - if(ret != M2M_SUCCESS)goto ERR1; - } - - ret = nm_read_reg_with_ret(HOST_CORT_COMM, ®); - if(ret != M2M_SUCCESS)goto ERR1; - if(reg & NBIT0) - { - reg &= ~NBIT0; - ret = nm_write_reg(HOST_CORT_COMM, reg); - if(ret != M2M_SUCCESS)goto ERR1; - } - -ERR1: - return ret; -} -sint8 chip_wake(void) -{ - sint8 ret = M2M_SUCCESS; - uint32 reg = 0, clk_status_reg = 0,trials = 0; - - ret = nm_read_reg_with_ret(HOST_CORT_COMM, ®); - if(ret != M2M_SUCCESS)goto _WAKE_EXIT; - - if(!(reg & NBIT0)) - { - /*USE bit 0 to indicate host wakeup*/ - ret = nm_write_reg(HOST_CORT_COMM, reg|NBIT0); - if(ret != M2M_SUCCESS)goto _WAKE_EXIT; - } - - ret = nm_read_reg_with_ret(WAKE_CLK_REG, ®); - if(ret != M2M_SUCCESS)goto _WAKE_EXIT; - /* Set bit 1 */ - if(!(reg & NBIT1)) - { - ret = nm_write_reg(WAKE_CLK_REG, reg | NBIT1); - if(ret != M2M_SUCCESS) goto _WAKE_EXIT; - } - - do - { - ret = nm_read_reg_with_ret(CLOCKS_EN_REG, &clk_status_reg); - if(ret != M2M_SUCCESS) { - M2M_ERR("Bus error (5).%d %lx\n",ret,clk_status_reg); - goto _WAKE_EXIT; - } - if(clk_status_reg & NBIT2) { - break; - } - nm_bsp_sleep(2); - trials++; - if(trials > WAKUP_TRAILS_TIMEOUT) - { - M2M_ERR("Failed to wakup the chip\n"); - ret = M2M_ERR_TIME_OUT; - goto _WAKE_EXIT; - } - }while(1); - - /*workaround sometimes spi fail to read clock regs after reading/writing clockless registers*/ - nm_bus_reset(); - -_WAKE_EXIT: - return ret; -} -sint8 cpu_halt(void) -{ - sint8 ret; - uint32 reg = 0; - ret = nm_read_reg_with_ret(0x1118, ®); - reg |= (1 << 0); - ret += nm_write_reg(0x1118, reg); - ret += nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); - if ((reg & (1ul << 10)) == (1ul << 10)) { - reg &= ~(1ul << 10); - ret += nm_write_reg(NMI_GLB_RESET_0, reg); - ret += nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); - } - return ret; -} -sint8 chip_reset_and_cpu_halt(void) -{ - sint8 ret = M2M_SUCCESS; - - /*Wakeup needed only for I2C interface*/ - ret = chip_wake(); - if(ret != M2M_SUCCESS) goto ERR1; - /*Reset and CPU halt need for no wait board only*/ - ret = chip_reset(); - if(ret != M2M_SUCCESS) goto ERR1; - ret = cpu_halt(); - if(ret != M2M_SUCCESS) goto ERR1; -ERR1: - return ret; -} -sint8 chip_reset(void) -{ - sint8 ret = M2M_SUCCESS; - ret = nm_write_reg(NMI_GLB_RESET_0, 0); - nm_bsp_sleep(50); - return ret; -} - -sint8 wait_for_bootrom(uint8 arg) -{ - sint8 ret = M2M_SUCCESS; - uint32 reg = 0, cnt = 0; - uint32 u32GpReg1 = 0; - uint32 u32DriverVerInfo = M2M_MAKE_VERSION_INFO(M2M_RELEASE_VERSION_MAJOR_NO,\ - M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO,\ - M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO,\ - M2M_RELEASE_VERSION_PATCH_NO); - - - reg = 0; - while(1) { - reg = nm_read_reg(0x1014); /* wait for efuse loading done */ - if (reg & 0x80000000) { - break; - } - nm_bsp_sleep(1); /* TODO: Why bus error if this delay is not here. */ - } - reg = nm_read_reg(M2M_WAIT_FOR_HOST_REG); - reg &= 0x1; - - /* check if waiting for the host will be skipped or not */ - if(reg == 0) - { - reg = 0; - while(reg != M2M_FINISH_BOOT_ROM) - { - nm_bsp_sleep(1); - reg = nm_read_reg(BOOTROM_REG); - - if(++cnt > TIMEOUT) - { - M2M_DBG("failed to load firmware from flash.\n"); - ret = M2M_ERR_INIT; - goto ERR2; - } - } - } - - if(M2M_WIFI_MODE_ATE_HIGH == arg) { - nm_write_reg(NMI_REV_REG, M2M_ATE_FW_START_VALUE); - nm_write_reg(NMI_STATE_REG, NBIT20); - }else if(M2M_WIFI_MODE_ATE_LOW == arg) { - nm_write_reg(NMI_REV_REG, M2M_ATE_FW_START_VALUE); - nm_write_reg(NMI_STATE_REG, 0); - }else if(M2M_WIFI_MODE_ETHERNET == arg){ - u32GpReg1 = rHAVE_ETHERNET_MODE_BIT; - nm_write_reg(NMI_STATE_REG, u32DriverVerInfo); - } else { - /*bypass this step*/ - nm_write_reg(NMI_STATE_REG, u32DriverVerInfo); - } - - if(REV(nmi_get_chipid()) >= REV_3A0){ - chip_apply_conf(u32GpReg1 | rHAVE_USE_PMU_BIT); - } else { - chip_apply_conf(u32GpReg1); - } - M2M_INFO("DriverVerInfo: 0x%08lx\n",u32DriverVerInfo); - - nm_write_reg(BOOTROM_REG,M2M_START_FIRMWARE); - -#ifdef __ROM_TEST__ - rom_test(); -#endif /* __ROM_TEST__ */ - -ERR2: - return ret; -} - -sint8 wait_for_firmware_start(uint8 arg) -{ - sint8 ret = M2M_SUCCESS; - uint32 reg = 0, cnt = 0; - uint32 u32Timeout = TIMEOUT; - volatile uint32 regAddress = NMI_STATE_REG; - volatile uint32 checkValue = M2M_FINISH_INIT_STATE; - - if((M2M_WIFI_MODE_ATE_HIGH == arg)||(M2M_WIFI_MODE_ATE_LOW == arg)) { - regAddress = NMI_REV_REG; - checkValue = M2M_ATE_FW_IS_UP_VALUE; - } else { - /*bypass this step*/ - } - - - while (checkValue != reg) - { - nm_bsp_sleep(2); /* TODO: Why bus error if this delay is not here. */ - M2M_DBG("%x %x %x\n",(unsigned int)nm_read_reg(0x108c),(unsigned int)nm_read_reg(0x108c),(unsigned int)nm_read_reg(0x14A0)); - reg = nm_read_reg(regAddress); - if(++cnt >= u32Timeout) - { - M2M_DBG("Time out for wait firmware Run\n"); - ret = M2M_ERR_INIT; - goto ERR; - } - } - if(M2M_FINISH_INIT_STATE == checkValue) - { - nm_write_reg(NMI_STATE_REG, 0); - } -ERR: - return ret; -} - -sint8 chip_deinit(void) -{ - uint32 reg = 0; - sint8 ret; - - /** - stop the firmware, need a re-download - **/ - ret = nm_read_reg_with_ret(NMI_GLB_RESET_0, ®); - if (ret != M2M_SUCCESS) { - M2M_ERR("failed to de-initialize\n"); - goto ERR1; - } - reg &= ~(1 << 10); - ret = nm_write_reg(NMI_GLB_RESET_0, reg); - if (ret != M2M_SUCCESS) { - M2M_ERR("failed to de-initialize\n"); - goto ERR1; - } - -ERR1: - return ret; -} - -#ifdef CONF_PERIPH - -sint8 set_gpio_dir(uint8 gpio, uint8 dir) -{ - uint32 val32; - sint8 ret; - - ret = nm_read_reg_with_ret(0x20108, &val32); - if(ret != M2M_SUCCESS) goto _EXIT; - - if(dir) { - val32 |= (1ul << gpio); - } else { - val32 &= ~(1ul << gpio); - } - - ret = nm_write_reg(0x20108, val32); - -_EXIT: - return ret; -} -sint8 set_gpio_val(uint8 gpio, uint8 val) -{ - uint32 val32; - sint8 ret; - - ret = nm_read_reg_with_ret(0x20100, &val32); - if(ret != M2M_SUCCESS) goto _EXIT; - - if(val) { - val32 |= (1ul << gpio); - } else { - val32 &= ~(1ul << gpio); - } - - ret = nm_write_reg(0x20100, val32); - -_EXIT: - return ret; -} - -sint8 get_gpio_val(uint8 gpio, uint8* val) -{ - uint32 val32; - sint8 ret; - - ret = nm_read_reg_with_ret(0x20104, &val32); - if(ret != M2M_SUCCESS) goto _EXIT; - - *val = (uint8)((val32 >> gpio) & 0x01); - -_EXIT: - return ret; -} - -sint8 pullup_ctrl(uint32 pinmask, uint8 enable) -{ - sint8 s8Ret; - uint32 val32; - s8Ret = nm_read_reg_with_ret(0x142c, &val32); - if(s8Ret != M2M_SUCCESS) { - M2M_ERR("[pullup_ctrl]: failed to read\n"); - goto _EXIT; - } - if(enable) { - val32 &= ~pinmask; - } else { - val32 |= pinmask; - } - s8Ret = nm_write_reg(0x142c, val32); - if(s8Ret != M2M_SUCCESS) { - M2M_ERR("[pullup_ctrl]: failed to write\n"); - goto _EXIT; - } -_EXIT: - return s8Ret; -} -#endif /* CONF_PERIPH */ - -sint8 nmi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid) -{ - sint8 ret; - uint32 u32RegValue; - uint8 mac[6]; - tstrGpRegs strgp = {0}; - - ret = nm_read_reg_with_ret(rNMI_GP_REG_2, &u32RegValue); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; -#ifdef ARDUINO - if (u32RegValue) { - ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; - u32RegValue = strgp.u32Mac_efuse_mib; - } else { - // firmware version 19.3.0 - ret = nm_read_reg_with_ret(rNMI_GP_REG_0, &u32RegValue); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; - } -#else - ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; - u32RegValue = strgp.u32Mac_efuse_mib; -#endif - if(!EFUSED_MAC(u32RegValue)) { - M2M_DBG("Default MAC\n"); - m2m_memset(pu8MacAddr, 0, 6); - goto _EXIT_ERR; - } - - M2M_DBG("OTP MAC\n"); - u32RegValue >>=16; - ret = nm_read_block(u32RegValue|0x30000, mac, 6); - m2m_memcpy(pu8MacAddr,mac,6); - if(pu8IsValid) *pu8IsValid = 1; - return ret; - -_EXIT_ERR: - if(pu8IsValid) *pu8IsValid = 0; - return ret; -} - -sint8 nmi_get_mac_address(uint8 *pu8MacAddr) -{ - sint8 ret; - uint32 u32RegValue; - uint8 mac[6]; - tstrGpRegs strgp = {0}; - - ret = nm_read_reg_with_ret(rNMI_GP_REG_2, &u32RegValue); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; -#ifdef ARDUINO - if (u32RegValue) { - ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; - u32RegValue = strgp.u32Mac_efuse_mib; - } else { - // firmware version 19.3.0 - ret = nm_read_reg_with_ret(rNMI_GP_REG_0, &u32RegValue); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; - } -#else - ret = nm_read_block(u32RegValue|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); - if(ret != M2M_SUCCESS) goto _EXIT_ERR; - u32RegValue = strgp.u32Mac_efuse_mib; -#endif - u32RegValue &=0x0000ffff; - ret = nm_read_block(u32RegValue|0x30000, mac, 6); - m2m_memcpy(pu8MacAddr, mac, 6); - - return ret; - -_EXIT_ERR: - return ret; -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmasic.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmasic.h deleted file mode 100644 index 84a395b..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmasic.h +++ /dev/null @@ -1,215 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 ASIC specific internal APIs. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -#ifndef _NMASIC_H_ -#define _NMASIC_H_ - -#include "common/include/nm_common.h" - -#define NMI_PERIPH_REG_BASE 0x1000 -#define NMI_CHIPID (NMI_PERIPH_REG_BASE) -#define rNMI_GP_REG_0 (0x149c) -#define rNMI_GP_REG_1 (0x14A0) -#define rNMI_GP_REG_2 (0xc0008) -#define rNMI_GLB_RESET (0x1400) -#define rNMI_BOOT_RESET_MUX (0x1118) -#define NMI_STATE_REG (0x108c) -#define BOOTROM_REG (0xc000c) -#define NMI_REV_REG (0x207ac) /*Also, Used to load ATE firmware from SPI Flash and to ensure that it is running too*/ -#define NMI_REV_REG_ATE (0x1048) /*Revision info register in case of ATE FW*/ -#define M2M_WAIT_FOR_HOST_REG (0x207bc) -#define M2M_FINISH_INIT_STATE 0x02532636UL -#define M2M_FINISH_BOOT_ROM 0x10add09eUL -#define M2M_START_FIRMWARE 0xef522f61UL -#define M2M_START_PS_FIRMWARE 0x94992610UL - -#define M2M_ATE_FW_START_VALUE (0x3C1CD57D) /*Also, Change this value in boot_firmware if it will be changed here*/ -#define M2M_ATE_FW_IS_UP_VALUE (0xD75DC1C3) /*Also, Change this value in ATE (Burst) firmware if it will be changed here*/ - -#define REV_2B0 (0x2B0) -#define REV_B0 (0x2B0) -#define REV_3A0 (0x3A0) -#define GET_CHIPID() nmi_get_chipid() -#define ISNMC1000(id) ((((id) & 0xfffff000) == 0x100000) ? 1 : 0) -#define ISNMC1500(id) ((((id) & 0xfffff000) == 0x150000) ? 1 : 0) -#define ISNMC3000(id) ((((id) & 0xfff00000) == 0x300000) ? 1 : 0) -#define REV(id) (((id) & 0x00000fff )) -#define EFUSED_MAC(value) (value & 0xffff0000) - -#define rHAVE_SDIO_IRQ_GPIO_BIT (NBIT0) -#define rHAVE_USE_PMU_BIT (NBIT1) -#define rHAVE_SLEEP_CLK_SRC_RTC_BIT (NBIT2) -#define rHAVE_SLEEP_CLK_SRC_XO_BIT (NBIT3) -#define rHAVE_EXT_PA_INV_TX_RX (NBIT4) -#define rHAVE_LEGACY_RF_SETTINGS (NBIT5) -#define rHAVE_LOGS_DISABLED_BIT (NBIT6) -#define rHAVE_ETHERNET_MODE_BIT (NBIT7) -#define rHAVE_RESERVED1_BIT (NBIT8) - -typedef struct{ - uint32 u32Mac_efuse_mib; - uint32 u32Firmware_Ota_rev; -}tstrGpRegs; - -#ifdef __cplusplus - extern "C" { -#endif - -/* -* @fn cpu_halt -* @brief -*/ -sint8 cpu_halt(void); -/* -* @fn chip_sleep -* @brief -*/ -sint8 chip_sleep(void); -/* -* @fn chip_wake -* @brief -*/ -sint8 chip_wake(void); -/* -* @fn chip_idle -* @brief -*/ -void chip_idle(void); -/* -* @fn enable_interrupts -* @brief -*/ -sint8 enable_interrupts(void); -/* -* @fn cpu_start -* @brief -*/ -sint8 cpu_start(void); -/* -* @fn nmi_get_chipid -* @brief -*/ -uint32 nmi_get_chipid(void); -/* -* @fn nmi_get_rfrevid -* @brief -*/ -uint32 nmi_get_rfrevid(void); -/* -* @fn restore_pmu_settings_after_global_reset -* @brief -*/ -void restore_pmu_settings_after_global_reset(void); -/* -* @fn nmi_update_pll -* @brief -*/ -void nmi_update_pll(void); -/* -* @fn nmi_set_sys_clk_src_to_xo -* @brief -*/ -void nmi_set_sys_clk_src_to_xo(void); -/* -* @fn chip_reset -* @brief -*/ -sint8 chip_reset(void); -/* -* @fn wait_for_bootrom -* @brief -*/ -sint8 wait_for_bootrom(uint8); -/* -* @fn wait_for_firmware_start -* @brief -*/ -sint8 wait_for_firmware_start(uint8); -/* -* @fn chip_deinit -* @brief -*/ -sint8 chip_deinit(void); -/* -* @fn chip_reset_and_cpu_halt -* @brief -*/ -sint8 chip_reset_and_cpu_halt(void); -/* -* @fn set_gpio_dir -* @brief -*/ -sint8 set_gpio_dir(uint8 gpio, uint8 dir); -/* -* @fn set_gpio_val -* @brief -*/ -sint8 set_gpio_val(uint8 gpio, uint8 val); -/* -* @fn get_gpio_val -* @brief -*/ -sint8 get_gpio_val(uint8 gpio, uint8* val); -/* -* @fn pullup_ctrl -* @brief -*/ -sint8 pullup_ctrl(uint32 pinmask, uint8 enable); -/* -* @fn nmi_get_otp_mac_address -* @brief -*/ -sint8 nmi_get_otp_mac_address(uint8 *pu8MacAddr, uint8 * pu8IsValid); -/* -* @fn nmi_get_mac_address -* @brief -*/ -sint8 nmi_get_mac_address(uint8 *pu8MacAddr); -/* -* @fn chip_apply_conf -* @brief -*/ -sint8 chip_apply_conf(uint32 u32conf); - -#ifdef __cplusplus - } -#endif - -#endif /*_NMASIC_H_*/ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmbus.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmbus.c deleted file mode 100644 index d001d72..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmbus.c +++ /dev/null @@ -1,301 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 bus APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -#ifndef CORTUS_APP - -#include "nmbus.h" -#include "nmi2c.h" -#include "nmspi.h" -#include "nmuart.h" - -#define MAX_TRX_CFG_SZ 8 - -/** -* @fn nm_bus_iface_init -* @brief Initialize bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_bus_iface_init(void *pvInitVal) -{ - sint8 ret = M2M_SUCCESS; - ret = nm_bus_init(pvInitVal); - return ret; -} - -/** -* @fn nm_bus_iface_deinit -* @brief Deinitialize bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Samer Sarhan -* @date 07 April 2014 -* @version 1.0 -*/ -sint8 nm_bus_iface_deinit(void) -{ - sint8 ret = M2M_SUCCESS; - ret = nm_bus_deinit(); - - return ret; -} - -/** -* @fn nm_bus_reset -* @brief reset bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @version 1.0 -*/ -sint8 nm_bus_reset(void) -{ - sint8 ret = M2M_SUCCESS; -#ifdef CONF_WINC_USE_UART -#elif defined (CONF_WINC_USE_SPI) - return nm_spi_reset(); -#elif defined (CONF_WINC_USE_I2C) -#else -#error "Plesae define bus usage" -#endif - - return ret; -} - -/** -* @fn nm_bus_iface_reconfigure -* @brief reconfigure bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Viswanathan Murugesan -* @date 22 Oct 2014 -* @version 1.0 -*/ -sint8 nm_bus_iface_reconfigure(void *ptr) -{ -#ifdef ARDUINO - (void)ptr; // Silence "unused" warning -#endif - sint8 ret = M2M_SUCCESS; -#ifdef CONF_WINC_USE_UART - ret = nm_uart_reconfigure(ptr); -#endif - return ret; -} -/* -* @fn nm_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -uint32 nm_read_reg(uint32 u32Addr) -{ -#ifdef CONF_WINC_USE_UART - return nm_uart_read_reg(u32Addr); -#elif defined (CONF_WINC_USE_SPI) - return nm_spi_read_reg(u32Addr); -#elif defined (CONF_WINC_USE_I2C) - return nm_i2c_read_reg(u32Addr); -#else -#error "Plesae define bus usage" -#endif - -} - -/* -* @fn nm_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) -{ -#ifdef CONF_WINC_USE_UART - return nm_uart_read_reg_with_ret(u32Addr,pu32RetVal); -#elif defined (CONF_WINC_USE_SPI) - return nm_spi_read_reg_with_ret(u32Addr,pu32RetVal); -#elif defined (CONF_WINC_USE_I2C) - return nm_i2c_read_reg_with_ret(u32Addr,pu32RetVal); -#else -#error "Plesae define bus usage" -#endif -} - -/* -* @fn nm_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_write_reg(uint32 u32Addr, uint32 u32Val) -{ -#ifdef CONF_WINC_USE_UART - return nm_uart_write_reg(u32Addr,u32Val); -#elif defined (CONF_WINC_USE_SPI) - return nm_spi_write_reg(u32Addr,u32Val); -#elif defined (CONF_WINC_USE_I2C) - return nm_i2c_write_reg(u32Addr,u32Val); -#else -#error "Plesae define bus usage" -#endif -} - -static sint8 p_nm_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) -{ -#ifdef CONF_WINC_USE_UART - return nm_uart_read_block(u32Addr,puBuf,u16Sz); -#elif defined (CONF_WINC_USE_SPI) - return nm_spi_read_block(u32Addr,puBuf,u16Sz); -#elif defined (CONF_WINC_USE_I2C) - return nm_i2c_read_block(u32Addr,puBuf,u16Sz); -#else -#error "Plesae define bus usage" -#endif - -} -/* -* @fn nm_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u32Sz -* Number of bytes to read. The buffer size must be >= u32Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_read_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz) -{ - uint16 u16MaxTrxSz = egstrNmBusCapabilities.u16MaxTrxSz - MAX_TRX_CFG_SZ; - uint32 off = 0; - sint8 s8Ret = M2M_SUCCESS; - - for(;;) - { - if(u32Sz <= u16MaxTrxSz) - { - s8Ret += p_nm_read_block(u32Addr, &puBuf[off], (uint16)u32Sz); - break; - } - else - { - s8Ret += p_nm_read_block(u32Addr, &puBuf[off], u16MaxTrxSz); - if(M2M_SUCCESS != s8Ret) break; - u32Sz -= u16MaxTrxSz; - off += u16MaxTrxSz; - u32Addr += u16MaxTrxSz; - } - } - - return s8Ret; -} - -static sint8 p_nm_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) -{ -#ifdef CONF_WINC_USE_UART - return nm_uart_write_block(u32Addr,puBuf,u16Sz); -#elif defined (CONF_WINC_USE_SPI) - return nm_spi_write_block(u32Addr,puBuf,u16Sz); -#elif defined (CONF_WINC_USE_I2C) - return nm_i2c_write_block(u32Addr,puBuf,u16Sz); -#else -#error "Plesae define bus usage" -#endif - -} -/** -* @fn nm_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u32Sz -* Number of bytes to write. The buffer size must be >= u32Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_write_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz) -{ - uint16 u16MaxTrxSz = egstrNmBusCapabilities.u16MaxTrxSz - MAX_TRX_CFG_SZ; - uint32 off = 0; - sint8 s8Ret = M2M_SUCCESS; - - for(;;) - { - if(u32Sz <= u16MaxTrxSz) - { - s8Ret += p_nm_write_block(u32Addr, &puBuf[off], (uint16)u32Sz); - break; - } - else - { - s8Ret += p_nm_write_block(u32Addr, &puBuf[off], u16MaxTrxSz); - if(M2M_SUCCESS != s8Ret) break; - u32Sz -= u16MaxTrxSz; - off += u16MaxTrxSz; - u32Addr += u16MaxTrxSz; - } - } - - return s8Ret; -} - -#endif - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmbus.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmbus.h deleted file mode 100644 index 2ea7838..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmbus.h +++ /dev/null @@ -1,147 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 bus APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NMBUS_H_ -#define _NMBUS_H_ - -#include "common/include/nm_common.h" -#include "bus_wrapper/include/nm_bus_wrapper.h" - - - -#ifdef __cplusplus -extern "C"{ -#endif -/** -* @fn nm_bus_iface_init -* @brief Initialize bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_bus_iface_init(void *); - - -/** -* @fn nm_bus_iface_deinit -* @brief Deinitialize bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_bus_iface_deinit(void); - -/** -* @fn nm_bus_reset -* @brief reset bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @version 1.0 -*/ -sint8 nm_bus_reset(void); - -/** -* @fn nm_bus_iface_reconfigure -* @brief reconfigure bus interface -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_bus_iface_reconfigure(void *ptr); - -/** -* @fn nm_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -*/ -uint32 nm_read_reg(uint32 u32Addr); - -/** -* @fn nm_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); - -/** -* @fn nm_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_write_reg(uint32 u32Addr, uint32 u32Val); - -/** -* @fn nm_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u32Sz -* Number of bytes to read. The buffer size must be >= u32Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_read_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz); - -/** -* @fn nm_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u32Sz -* Number of bytes to write. The buffer size must be >= u32Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_write_block(uint32 u32Addr, uint8 *puBuf, uint32 u32Sz); - - - - -#ifdef __cplusplus -} -#endif - -#endif /* _NMBUS_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmdrv.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmdrv.c deleted file mode 100644 index b3f2a8a..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmdrv.c +++ /dev/null @@ -1,402 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 M2M driver APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "common/include/nm_common.h" -#include "driver/source/nmbus.h" -#include "bsp/include/nm_bsp.h" -#include "driver/source/nmdrv.h" -#include "driver/source/nmasic.h" -#include "driver/include/m2m_types.h" -#include "spi_flash/include/spi_flash.h" - -#ifdef CONF_WINC_USE_SPI -#include "driver/source/nmspi.h" -#endif - -#ifdef ARDUINO - uint32 nmdrv_firm_ver = 0; -#endif - -/** -* @fn nm_get_firmware_info(tstrM2mRev* M2mRev) -* @brief Get Firmware version info -* @param [out] M2mRev -* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters -* @version 1.0 -*/ -sint8 nm_get_firmware_info(tstrM2mRev* M2mRev) -{ - uint16 curr_drv_ver, min_req_drv_ver,curr_firm_ver; - uint32 reg = 0; - sint8 ret = M2M_SUCCESS; - - ret = nm_read_reg_with_ret(NMI_REV_REG, ®); - //In case the Firmware running is ATE fw - if(M2M_ATE_FW_IS_UP_VALUE == reg) - { - //Read FW info again from the register specified for ATE - ret = nm_read_reg_with_ret(NMI_REV_REG_ATE, ®); - } - M2mRev->u8DriverMajor = M2M_GET_DRV_MAJOR(reg); - M2mRev->u8DriverMinor = M2M_GET_DRV_MINOR(reg); - M2mRev->u8DriverPatch = M2M_GET_DRV_PATCH(reg); - M2mRev->u8FirmwareMajor = M2M_GET_FW_MAJOR(reg); - M2mRev->u8FirmwareMinor = M2M_GET_FW_MINOR(reg); - M2mRev->u8FirmwarePatch = M2M_GET_FW_PATCH(reg); - M2mRev->u32Chipid = nmi_get_chipid(); - M2mRev->u16FirmwareSvnNum = 0; - - curr_firm_ver = M2M_MAKE_VERSION(M2mRev->u8FirmwareMajor, M2mRev->u8FirmwareMinor,M2mRev->u8FirmwarePatch); -#ifdef ARDUINO - nmdrv_firm_ver = curr_firm_ver; -#endif - curr_drv_ver = M2M_MAKE_VERSION(M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); - min_req_drv_ver = M2M_MAKE_VERSION(M2mRev->u8DriverMajor, M2mRev->u8DriverMinor,M2mRev->u8DriverPatch); - if(curr_drv_ver < min_req_drv_ver) { - /*The current driver version should be larger or equal - than the min driver that the current firmware support */ - ret = M2M_ERR_FW_VER_MISMATCH; - } - if(curr_drv_ver > curr_firm_ver) { - /*The current driver should be equal or less than the firmware version*/ - ret = M2M_ERR_FW_VER_MISMATCH; - } - return ret; -} -/** -* @fn nm_get_firmware_info(tstrM2mRev* M2mRev) -* @brief Get Firmware version info -* @param [out] M2mRev -* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters -* @version 1.0 -*/ -sint8 nm_get_firmware_full_info(tstrM2mRev* pstrRev) -{ - uint16 curr_drv_ver, min_req_drv_ver,curr_firm_ver; - uint32 reg = 0; - sint8 ret = M2M_SUCCESS; - tstrGpRegs strgp = {0}; - if (pstrRev != NULL) - { - m2m_memset((uint8*)pstrRev,0,sizeof(tstrM2mRev)); - ret = nm_read_reg_with_ret(rNMI_GP_REG_2, ®); - if(ret == M2M_SUCCESS) - { - if(reg != 0) - { - ret = nm_read_block(reg|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); - if(ret == M2M_SUCCESS) - { - reg = strgp.u32Firmware_Ota_rev; - reg &= 0x0000ffff; - if(reg != 0) - { - ret = nm_read_block(reg|0x30000,(uint8*)pstrRev,sizeof(tstrM2mRev)); - if(ret == M2M_SUCCESS) - { - curr_firm_ver = M2M_MAKE_VERSION(pstrRev->u8FirmwareMajor, pstrRev->u8FirmwareMinor,pstrRev->u8FirmwarePatch); -#ifdef ARDUINO - nmdrv_firm_ver = curr_firm_ver; -#endif - curr_drv_ver = M2M_MAKE_VERSION(M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); - min_req_drv_ver = M2M_MAKE_VERSION(pstrRev->u8DriverMajor, pstrRev->u8DriverMinor,pstrRev->u8DriverPatch); - if((curr_firm_ver == 0)||(min_req_drv_ver == 0)||(min_req_drv_ver == 0)){ - ret = M2M_ERR_FAIL; - goto EXIT; - } - if(curr_drv_ver < min_req_drv_ver) { - /*The current driver version should be larger or equal - than the min driver that the current firmware support */ - ret = M2M_ERR_FW_VER_MISMATCH; - goto EXIT; - } - if(curr_drv_ver > curr_firm_ver) { - /*The current driver should be equal or less than the firmware version*/ - ret = M2M_ERR_FW_VER_MISMATCH; - goto EXIT; - } - } - }else { - ret = M2M_ERR_FAIL; - } - } - }else{ - ret = M2M_ERR_FAIL; - } - } - } -EXIT: - return ret; -} -/** -* @fn nm_get_ota_firmware_info(tstrM2mRev* pstrRev) -* @brief Get Firmware version info -* @param [out] M2mRev -* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters - -* @version 1.0 -*/ -sint8 nm_get_ota_firmware_info(tstrM2mRev* pstrRev) -{ - uint16 curr_drv_ver, min_req_drv_ver,curr_firm_ver; - uint32 reg = 0; - sint8 ret; - tstrGpRegs strgp = {0}; - - if (pstrRev != NULL) - { - m2m_memset((uint8*)pstrRev,0,sizeof(tstrM2mRev)); - ret = nm_read_reg_with_ret(rNMI_GP_REG_2, ®); - if(ret == M2M_SUCCESS) - { - if(reg != 0) - { - ret = nm_read_block(reg|0x30000,(uint8*)&strgp,sizeof(tstrGpRegs)); - if(ret == M2M_SUCCESS) - { - reg = strgp.u32Firmware_Ota_rev; - reg >>= 16; - if(reg != 0) - { - ret = nm_read_block(reg|0x30000,(uint8*)pstrRev,sizeof(tstrM2mRev)); - if(ret == M2M_SUCCESS) - { - curr_firm_ver = M2M_MAKE_VERSION(pstrRev->u8FirmwareMajor, pstrRev->u8FirmwareMinor,pstrRev->u8FirmwarePatch); - curr_drv_ver = M2M_MAKE_VERSION(M2M_RELEASE_VERSION_MAJOR_NO, M2M_RELEASE_VERSION_MINOR_NO, M2M_RELEASE_VERSION_PATCH_NO); - min_req_drv_ver = M2M_MAKE_VERSION(pstrRev->u8DriverMajor, pstrRev->u8DriverMinor,pstrRev->u8DriverPatch); - if((curr_firm_ver == 0)||(min_req_drv_ver == 0)||(min_req_drv_ver == 0)){ - ret = M2M_ERR_FAIL; - goto EXIT; - } - if(curr_drv_ver < min_req_drv_ver) { - /*The current driver version should be larger or equal - than the min driver that the current firmware support */ - ret = M2M_ERR_FW_VER_MISMATCH; - } - if(curr_drv_ver > curr_firm_ver) { - /*The current driver should be equal or less than the firmware version*/ - ret = M2M_ERR_FW_VER_MISMATCH; - } - } - }else{ - ret = M2M_ERR_INVALID; - } - } - }else{ - ret = M2M_ERR_FAIL; - } - } - } else { - ret = M2M_ERR_INVALID_ARG; - } -EXIT: - return ret; -} - - - -/* -* @fn nm_drv_init_download_mode -* @brief Initialize NMC1000 driver -* @return M2M_SUCCESS in case of success and Negative error code in case of failure -* @param [in] arg -* Generic argument -* @author Viswanathan Murugesan -* @date 10 Oct 2014 -* @version 1.0 -*/ -sint8 nm_drv_init_download_mode() -{ - sint8 ret = M2M_SUCCESS; - - ret = nm_bus_iface_init(NULL); - if (M2M_SUCCESS != ret) { - M2M_ERR("[nmi start]: fail init bus\n"); - goto ERR1; - } - - /** - TODO:reset the chip and halt the cpu in case of no wait efuse is set (add the no wait effuse check) - */ - if(!ISNMC3000(GET_CHIPID())) - { - /*Execuate that function only for 1500A/B, no room in 3000, but it may be needed in 3400 no wait*/ - chip_reset_and_cpu_halt(); - } - -#ifdef CONF_WINC_USE_SPI - /* Must do this after global reset to set SPI data packet size. */ - nm_spi_init(); -#endif - - M2M_INFO("Chip ID %lx\n", nmi_get_chipid()); - - /*disable all interrupt in ROM (to disable uart) in 2b0 chip*/ - nm_write_reg(0x20300,0); - -ERR1: - return ret; -} - -/* -* @fn nm_drv_init -* @brief Initialize NMC1000 driver -* @return M2M_SUCCESS in case of success and Negative error code in case of failure -* @param [in] arg -* Generic argument -* @author M. Abdelmawla -* @date 15 July 2012 -* @version 1.0 -*/ -sint8 nm_drv_init(void * arg) -{ - sint8 ret = M2M_SUCCESS; - uint8 u8Mode; - - if(NULL != arg) { - u8Mode = *((uint8 *)arg); - if((u8Mode < M2M_WIFI_MODE_NORMAL)||(u8Mode >= M2M_WIFI_MODE_MAX)) { - u8Mode = M2M_WIFI_MODE_NORMAL; - } - } else { - u8Mode = M2M_WIFI_MODE_NORMAL; - } - - ret = nm_bus_iface_init(NULL); - if (M2M_SUCCESS != ret) { - M2M_ERR("[nmi start]: fail init bus\n"); - goto ERR1; - } - -#ifdef BUS_ONLY - return; -#endif - - -#ifdef NO_HW_CHIP_EN - ret = chip_wake(); - if (M2M_SUCCESS != ret) { - M2M_ERR("[nmi start]: fail chip_wakeup\n"); - goto ERR2; - } - /** - Go... - **/ - ret = chip_reset(); - if (M2M_SUCCESS != ret) { - goto ERR2; - } -#endif - M2M_INFO("Chip ID %lx\n", nmi_get_chipid()); -#ifdef CONF_WINC_USE_SPI - /* Must do this after global reset to set SPI data packet size. */ - nm_spi_init(); -#endif - ret = wait_for_bootrom(u8Mode); - if (M2M_SUCCESS != ret) { - goto ERR2; - } - - ret = wait_for_firmware_start(u8Mode); - if (M2M_SUCCESS != ret) { - goto ERR2; - } - - if((M2M_WIFI_MODE_ATE_HIGH == u8Mode)||(M2M_WIFI_MODE_ATE_LOW == u8Mode)) { - goto ERR1; - } else { - /*continue running*/ - } - - ret = enable_interrupts(); - if (M2M_SUCCESS != ret) { - M2M_ERR("failed to enable interrupts..\n"); - goto ERR2; - } - return ret; -ERR2: - nm_bus_iface_deinit(); -ERR1: - return ret; -} - -/* -* @fn nm_drv_deinit -* @brief Deinitialize NMC1000 driver -* @author M. Abdelmawla -* @date 17 July 2012 -* @version 1.0 -*/ -sint8 nm_drv_deinit(void * arg) -{ -#ifdef ARDUINO - (void)arg; // Silence "unused" warning -#endif - sint8 ret; - - ret = chip_deinit(); - if (M2M_SUCCESS != ret) { - M2M_ERR("[nmi stop]: chip_deinit fail\n"); - goto ERR1; - } - - /* Disable SPI flash to save power when the chip is off */ - ret = spi_flash_enable(0); - if (M2M_SUCCESS != ret) { - M2M_ERR("[nmi stop]: SPI flash disable fail\n"); - goto ERR1; - } - - ret = nm_bus_iface_deinit(); - if (M2M_SUCCESS != ret) { - M2M_ERR("[nmi stop]: fail init bus\n"); - goto ERR1; - } -#ifdef CONF_WINC_USE_SPI - /* Must do this after global reset to set SPI data packet size. */ - nm_spi_deinit(); -#endif - -ERR1: - return ret; -} - - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmdrv.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmdrv.h deleted file mode 100644 index 6a416b2..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmdrv.h +++ /dev/null @@ -1,138 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1500 M2M driver APIs declarations. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NMDRV_H_ -#define _NMDRV_H_ - -#include "common/include/nm_common.h" - -/** -* @struct tstrM2mRev -* @brief Structure holding firmware version parameters and build date/time -*/ -typedef struct { - uint32 u32Chipid; /* HW revision which will be basically the chip ID */ - uint8 u8FirmwareMajor; /* Version Major Number which represents the official release base */ - uint8 u8FirmwareMinor; /* Version Minor Number which represents the engineering release base */ - uint8 u8FirmwarePatch; /* Version pathc Number which represents the pathces release base */ - uint8 u8DriverMajor; /* Version Major Number which represents the official release base */ - uint8 u8DriverMinor; /* Version Minor Number which represents the engineering release base */ - uint8 u8DriverPatch; /* Version Patch Number which represents the pathces release base */ - uint8 BuildDate[sizeof(__DATE__)]; - uint8 BuildTime[sizeof(__TIME__)]; - uint8 _PAD8_; - uint16 u16FirmwareSvnNum; - uint16 _PAD16_[2]; -} tstrM2mRev; - -/** -* @struct tstrM2mBinaryHeader -* @brief Structure holding compatibility version info for firmware binaries -*/ -typedef struct { - tstrM2mRev binVerInfo; - uint32 flashOffset; - uint32 payloadSize; -} tstrM2mBinaryHeader; - -#ifdef __cplusplus - extern "C" { - #endif -/** -* @fn nm_get_firmware_info(tstrM2mRev* M2mRev) -* @brief Get Firmware version info -* @param [out] M2mRev -* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters -* @version 1.0 -*/ -sint8 nm_get_firmware_info(tstrM2mRev* M2mRev); -/** -* @fn nm_get_firmware_full_info(tstrM2mRev* pstrRev) -* @brief Get Firmware version info -* @param [out] M2mRev -* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters -* @version 1.0 -*/ -sint8 nm_get_firmware_full_info(tstrM2mRev* pstrRev); -/** -* @fn nm_get_ota_firmware_info(tstrM2mRev* pstrRev) -* @brief Get Firmware version info -* @param [out] M2mRev -* pointer holds address of structure "tstrM2mRev" that contains the firmware version parameters - -* @version 1.0 -*/ -sint8 nm_get_ota_firmware_info(tstrM2mRev* pstrRev); -/* -* @fn nm_drv_init -* @brief Initialize NMC1000 driver -* @return ZERO in case of success and Negative error code in case of failure -*/ -sint8 nm_drv_init_download_mode(void); - -/* -* @fn nm_drv_init -* @brief Initialize NMC1000 driver -* @return M2M_SUCCESS in case of success and Negative error code in case of failure -* @param [in] arg -* Generic argument TBD -* @return ZERO in case of success and Negative error code in case of failure - -*/ -sint8 nm_drv_init(void * arg); - -/** -* @fn nm_drv_deinit -* @brief Deinitialize NMC1000 driver -* @author M. Abdelmawla -* @param [in] arg -* Generic argument TBD -* @return ZERO in case of success and Negative error code in case of failure -*/ -sint8 nm_drv_deinit(void * arg); - -#ifdef __cplusplus - } - #endif - -#endif /*_NMDRV_H_*/ - - diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmi2c.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmi2c.c deleted file mode 100644 index e11d2f7..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmi2c.c +++ /dev/null @@ -1,269 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 I2C protocol bus APIs implementation. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "common/include/nm_common.h" - -#ifdef CONF_WINC_USE_I2C - -#include "nmi2c.h" -#include "bus_wrapper/include/nm_bus_wrapper.h" - - -/* -* @fn nm_i2c_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ - sint8 nm_i2c_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) -{ - uint8 b[6]; - uint8 rsz; - tstrNmI2cDefault strI2c; - sint8 s8Ret = M2M_SUCCESS; - - if(u32Addr < 0xff) { /* clockless i2c */ - b[0] = 0x09; - b[1] = (uint8)(u32Addr); - rsz = 1; - strI2c.u16Sz = 2; - } else { - b[0] = 0x80; - b[1] = (uint8)(u32Addr >> 24); - b[2] = (uint8)(u32Addr >> 16); - b[3] = (uint8)(u32Addr >> 8); - b[4] = (uint8)(u32Addr); - b[5] = 0x04; - rsz = 4; - strI2c.u16Sz = 6; - } - - strI2c.pu8Buf = b; - - if(M2M_SUCCESS == nm_bus_ioctl(NM_BUS_IOCTL_W, &strI2c)) - { - strI2c.u16Sz = rsz; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strI2c)) - { - //M2M_ERR("read error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - M2M_ERR("failed to send cfg bytes\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - - if (rsz == 1) { - *pu32RetVal = b[0]; - } else { - *pu32RetVal = b[0] | ((uint32)b[1] << 8) | ((uint32)b[2] << 16) | ((uint32)b[3] << 24); - } - return s8Ret; -} - -/* -* @fn nm_i2c_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -uint32 nm_i2c_read_reg(uint32 u32Addr) -{ - uint32 val; - nm_i2c_read_reg_with_ret(u32Addr, &val); - return val; -} - -/* -* @fn nm_i2c_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_i2c_write_reg(uint32 u32Addr, uint32 u32Val) -{ - tstrNmI2cDefault strI2c; - uint8 b[16]; - sint8 s8Ret = M2M_SUCCESS; - - if(u32Addr < 0xff) { /* clockless i2c */ - b[0] = 0x19; - b[1] = (uint8)(u32Addr); - b[2] = (uint8)(u32Val); - strI2c.u16Sz = 3; - } else { - b[0] = 0x90; - b[1] = (uint8)(u32Addr >> 24); - b[2] = (uint8)(u32Addr >> 16); - b[3] = (uint8)(u32Addr >> 8); - b[4] = (uint8)u32Addr; - b[5] = 0x04; - b[6] = (uint8)u32Val; - b[7] = (uint8)(u32Val >> 8); - b[8] = (uint8)(u32Val >> 16); - b[9] = (uint8)(u32Val >> 24); - strI2c.u16Sz = 10; - } - - strI2c.pu8Buf = b; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strI2c)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - - return s8Ret; -} - -/* -* @fn nm_i2c_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u16Sz -* Number of bytes to read. The buffer size must be >= u16Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_i2c_read_block(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz) -{ - tstrNmI2cDefault strI2c; - uint8 au8Buf[7]; - sint8 s8Ret = M2M_SUCCESS; - - au8Buf[0] = 0x02; - au8Buf[1] = (uint8)(u32Addr >> 24); - au8Buf[2] = (uint8)(u32Addr >> 16); - au8Buf[3] = (uint8)(u32Addr >> 8); - au8Buf[4] = (uint8)(u32Addr >> 0); - au8Buf[5] = (uint8)(u16Sz >> 8); - au8Buf[6] = (uint8)(u16Sz); - - strI2c.pu8Buf = au8Buf; - strI2c.u16Sz = sizeof(au8Buf); - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strI2c)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - else - { - strI2c.pu8Buf = pu8Buf; - strI2c.u16Sz = u16Sz; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strI2c)) - { - M2M_ERR("read error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - - return s8Ret; -} - -/* -* @fn nm_i2c_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u16Sz -* Number of bytes to write. The buffer size must be >= u16Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_i2c_write_block(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz) -{ - uint8 au8Buf[7]; - tstrNmI2cSpecial strI2c; - sint8 s8Ret = M2M_SUCCESS; - - au8Buf[0] = 0x12; - au8Buf[1] = (uint8)(u32Addr >> 24); - au8Buf[2] = (uint8)(u32Addr >> 16); - au8Buf[3] = (uint8)(u32Addr >> 8); - au8Buf[4] = (uint8)(u32Addr); - au8Buf[5] = (uint8)(u16Sz >> 8); - au8Buf[6] = (uint8)(u16Sz); - - strI2c.pu8Buf1 = au8Buf; - strI2c.pu8Buf2 = pu8Buf; - strI2c.u16Sz1 = sizeof(au8Buf); - strI2c.u16Sz2 = u16Sz; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W_SPECIAL, &strI2c)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - - return s8Ret; -} - -#endif -/* EOF */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmi2c.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmi2c.h deleted file mode 100644 index fea85e6..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmi2c.h +++ /dev/null @@ -1,104 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 I2C protocol bus APIs implementation. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NMI2C_H_ -#define _NMI2C_H_ - -#include "common/include/nm_common.h" - -/** -* @fn nm_i2c_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -*/ -uint32 nm_i2c_read_reg(uint32 u32Addr); - -/** -* @fn nm_i2c_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_i2c_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); - -/** -* @fn nm_i2c_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_i2c_write_reg(uint32 u32Addr, uint32 u32Val); - -/** -* @fn nm_i2c_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u16Sz -* Number of bytes to read. The buffer size must be >= u16Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_i2c_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); - -/** -* @fn nm_i2c_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u16Sz -* Number of bytes to write. The buffer size must be >= u16Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_i2c_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); - -#endif /* _NMI2C_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmspi.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmspi.c deleted file mode 100644 index 9483ab7..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmspi.c +++ /dev/null @@ -1,1401 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 SPI protocol bus APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -#include "common/include/nm_common.h" - -#ifdef CONF_WINC_USE_SPI - -#define USE_OLD_SPI_SW - -#include "bus_wrapper/include/nm_bus_wrapper.h" -#include "nmspi.h" - -#define NMI_PERIPH_REG_BASE 0x1000 -#define NMI_INTR_REG_BASE (NMI_PERIPH_REG_BASE+0xa00) -#define NMI_CHIPID (NMI_PERIPH_REG_BASE) -#define NMI_PIN_MUX_0 (NMI_PERIPH_REG_BASE + 0x408) -#define NMI_INTR_ENABLE (NMI_INTR_REG_BASE) - -#define NMI_SPI_REG_BASE 0xe800 -#define NMI_SPI_CTL (NMI_SPI_REG_BASE) -#define NMI_SPI_MASTER_DMA_ADDR (NMI_SPI_REG_BASE+0x4) -#define NMI_SPI_MASTER_DMA_COUNT (NMI_SPI_REG_BASE+0x8) -#define NMI_SPI_SLAVE_DMA_ADDR (NMI_SPI_REG_BASE+0xc) -#define NMI_SPI_SLAVE_DMA_COUNT (NMI_SPI_REG_BASE+0x10) -#define NMI_SPI_TX_MODE (NMI_SPI_REG_BASE+0x20) -#define NMI_SPI_PROTOCOL_CONFIG (NMI_SPI_REG_BASE+0x24) -#define NMI_SPI_INTR_CTL (NMI_SPI_REG_BASE+0x2c) -#define NMI_SPI_MISC_CTRL (NMI_SPI_REG_BASE+0x48) - -#define NMI_SPI_PROTOCOL_OFFSET (NMI_SPI_PROTOCOL_CONFIG-NMI_SPI_REG_BASE) - -#define SPI_BASE NMI_SPI_REG_BASE - -#define CMD_DMA_WRITE 0xc1 -#define CMD_DMA_READ 0xc2 -#define CMD_INTERNAL_WRITE 0xc3 -#define CMD_INTERNAL_READ 0xc4 -#define CMD_TERMINATE 0xc5 -#define CMD_REPEAT 0xc6 -#define CMD_DMA_EXT_WRITE 0xc7 -#define CMD_DMA_EXT_READ 0xc8 -#define CMD_SINGLE_WRITE 0xc9 -#define CMD_SINGLE_READ 0xca -#define CMD_RESET 0xcf - -#define N_OK 1 -#define N_FAIL 0 -#define N_RESET -1 -#define N_RETRY -2 - -#define SPI_RESP_RETRY_COUNT (10) -#define SPI_RETRY_COUNT (10) -#define DATA_PKT_SZ_256 256 -#define DATA_PKT_SZ_512 512 -#define DATA_PKT_SZ_1K 1024 -#define DATA_PKT_SZ_4K (4 * 1024) -#define DATA_PKT_SZ_8K (8 * 1024) -#define DATA_PKT_SZ DATA_PKT_SZ_8K - -static uint8 gu8Crc_off = 0; - -static sint8 nmi_spi_read(uint8* b, uint16 sz) -{ - tstrNmSpiRw spi; - spi.pu8InBuf = NULL; - spi.pu8OutBuf = b; - spi.u16Sz = sz; - return nm_bus_ioctl(NM_BUS_IOCTL_RW, &spi); -} - -static sint8 nmi_spi_write(uint8* b, uint16 sz) -{ - tstrNmSpiRw spi; - spi.pu8InBuf = b; - spi.pu8OutBuf = NULL; - spi.u16Sz = sz; - return nm_bus_ioctl(NM_BUS_IOCTL_RW, &spi); -} -#ifndef USE_OLD_SPI_SW -static sint8 nmi_spi_rw(uint8 *bin,uint8* bout,uint16 sz) -{ - tstrNmSpiRw spi; - spi.pu8InBuf = bin; - spi.pu8OutBuf = bout; - spi.u16Sz = sz; - return nm_bus_ioctl(NM_BUS_IOCTL_RW, &spi); -} -#endif -/******************************************** - - Crc7 - -********************************************/ -#if (defined ARDUINO_ARCH_AVR) -#include -static PROGMEM const uint8 crc7_syndrome_table[256] = { -#else -static const uint8 crc7_syndrome_table[256] = { -#endif - 0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f, - 0x48, 0x41, 0x5a, 0x53, 0x6c, 0x65, 0x7e, 0x77, - 0x19, 0x10, 0x0b, 0x02, 0x3d, 0x34, 0x2f, 0x26, - 0x51, 0x58, 0x43, 0x4a, 0x75, 0x7c, 0x67, 0x6e, - 0x32, 0x3b, 0x20, 0x29, 0x16, 0x1f, 0x04, 0x0d, - 0x7a, 0x73, 0x68, 0x61, 0x5e, 0x57, 0x4c, 0x45, - 0x2b, 0x22, 0x39, 0x30, 0x0f, 0x06, 0x1d, 0x14, - 0x63, 0x6a, 0x71, 0x78, 0x47, 0x4e, 0x55, 0x5c, - 0x64, 0x6d, 0x76, 0x7f, 0x40, 0x49, 0x52, 0x5b, - 0x2c, 0x25, 0x3e, 0x37, 0x08, 0x01, 0x1a, 0x13, - 0x7d, 0x74, 0x6f, 0x66, 0x59, 0x50, 0x4b, 0x42, - 0x35, 0x3c, 0x27, 0x2e, 0x11, 0x18, 0x03, 0x0a, - 0x56, 0x5f, 0x44, 0x4d, 0x72, 0x7b, 0x60, 0x69, - 0x1e, 0x17, 0x0c, 0x05, 0x3a, 0x33, 0x28, 0x21, - 0x4f, 0x46, 0x5d, 0x54, 0x6b, 0x62, 0x79, 0x70, - 0x07, 0x0e, 0x15, 0x1c, 0x23, 0x2a, 0x31, 0x38, - 0x41, 0x48, 0x53, 0x5a, 0x65, 0x6c, 0x77, 0x7e, - 0x09, 0x00, 0x1b, 0x12, 0x2d, 0x24, 0x3f, 0x36, - 0x58, 0x51, 0x4a, 0x43, 0x7c, 0x75, 0x6e, 0x67, - 0x10, 0x19, 0x02, 0x0b, 0x34, 0x3d, 0x26, 0x2f, - 0x73, 0x7a, 0x61, 0x68, 0x57, 0x5e, 0x45, 0x4c, - 0x3b, 0x32, 0x29, 0x20, 0x1f, 0x16, 0x0d, 0x04, - 0x6a, 0x63, 0x78, 0x71, 0x4e, 0x47, 0x5c, 0x55, - 0x22, 0x2b, 0x30, 0x39, 0x06, 0x0f, 0x14, 0x1d, - 0x25, 0x2c, 0x37, 0x3e, 0x01, 0x08, 0x13, 0x1a, - 0x6d, 0x64, 0x7f, 0x76, 0x49, 0x40, 0x5b, 0x52, - 0x3c, 0x35, 0x2e, 0x27, 0x18, 0x11, 0x0a, 0x03, - 0x74, 0x7d, 0x66, 0x6f, 0x50, 0x59, 0x42, 0x4b, - 0x17, 0x1e, 0x05, 0x0c, 0x33, 0x3a, 0x21, 0x28, - 0x5f, 0x56, 0x4d, 0x44, 0x7b, 0x72, 0x69, 0x60, - 0x0e, 0x07, 0x1c, 0x15, 0x2a, 0x23, 0x38, 0x31, - 0x46, 0x4f, 0x54, 0x5d, 0x62, 0x6b, 0x70, 0x79 -}; - - -static uint8 crc7_byte(uint8 crc, uint8 data) -{ -#if (defined ARDUINO_ARCH_AVR) - return pgm_read_byte_near(crc7_syndrome_table + ((crc << 1) ^ data)); -#else - return crc7_syndrome_table[(crc << 1) ^ data]; -#endif -} - -static uint8 crc7(uint8 crc, const uint8 *buffer, uint32 len) -{ - while (len--) - crc = crc7_byte(crc, *buffer++); - return crc; -} - -/******************************************** - - Spi protocol Function - -********************************************/ - -#define CMD_DMA_WRITE 0xc1 -#define CMD_DMA_READ 0xc2 -#define CMD_INTERNAL_WRITE 0xc3 -#define CMD_INTERNAL_READ 0xc4 -#define CMD_TERMINATE 0xc5 -#define CMD_REPEAT 0xc6 -#define CMD_DMA_EXT_WRITE 0xc7 -#define CMD_DMA_EXT_READ 0xc8 -#define CMD_SINGLE_WRITE 0xc9 -#define CMD_SINGLE_READ 0xca -#define CMD_RESET 0xcf - -#define DATA_PKT_SZ_256 256 -#define DATA_PKT_SZ_512 512 -#define DATA_PKT_SZ_1K 1024 -#define DATA_PKT_SZ_4K (4 * 1024) -#define DATA_PKT_SZ_8K (8 * 1024) -#define DATA_PKT_SZ DATA_PKT_SZ_8K - -static sint8 spi_cmd(uint8 cmd, uint32 adr, uint32 u32data, uint32 sz,uint8 clockless) -{ - uint8 bc[9]; - uint8 len = 5; - sint8 result = N_OK; - - bc[0] = cmd; - switch (cmd) { - case CMD_SINGLE_READ: /* single word (4 bytes) read */ - bc[1] = (uint8)(adr >> 16); - bc[2] = (uint8)(adr >> 8); - bc[3] = (uint8)adr; - len = 5; - break; - case CMD_INTERNAL_READ: /* internal register read */ - bc[1] = (uint8)(adr >> 8); - if(clockless) bc[1] |= (1 << 7); - bc[2] = (uint8)adr; - bc[3] = 0x00; - len = 5; - break; - case CMD_TERMINATE: /* termination */ - bc[1] = 0x00; - bc[2] = 0x00; - bc[3] = 0x00; - len = 5; - break; - case CMD_REPEAT: /* repeat */ - bc[1] = 0x00; - bc[2] = 0x00; - bc[3] = 0x00; - len = 5; - break; - case CMD_RESET: /* reset */ - bc[1] = 0xff; - bc[2] = 0xff; - bc[3] = 0xff; - len = 5; - break; - case CMD_DMA_WRITE: /* dma write */ - case CMD_DMA_READ: /* dma read */ - bc[1] = (uint8)(adr >> 16); - bc[2] = (uint8)(adr >> 8); - bc[3] = (uint8)adr; - bc[4] = (uint8)(sz >> 8); - bc[5] = (uint8)(sz); - len = 7; - break; - case CMD_DMA_EXT_WRITE: /* dma extended write */ - case CMD_DMA_EXT_READ: /* dma extended read */ - bc[1] = (uint8)(adr >> 16); - bc[2] = (uint8)(adr >> 8); - bc[3] = (uint8)adr; - bc[4] = (uint8)(sz >> 16); - bc[5] = (uint8)(sz >> 8); - bc[6] = (uint8)(sz); - len = 8; - break; - case CMD_INTERNAL_WRITE: /* internal register write */ - bc[1] = (uint8)(adr >> 8); - if(clockless) bc[1] |= (1 << 7); - bc[2] = (uint8)(adr); - bc[3] = (uint8)(u32data >> 24); - bc[4] = (uint8)(u32data >> 16); - bc[5] = (uint8)(u32data >> 8); - bc[6] = (uint8)(u32data); - len = 8; - break; - case CMD_SINGLE_WRITE: /* single word write */ - bc[1] = (uint8)(adr >> 16); - bc[2] = (uint8)(adr >> 8); - bc[3] = (uint8)(adr); - bc[4] = (uint8)(u32data >> 24); - bc[5] = (uint8)(u32data >> 16); - bc[6] = (uint8)(u32data >> 8); - bc[7] = (uint8)(u32data); - len = 9; - break; - default: - result = N_FAIL; - break; - } - - if (result) { - if (!gu8Crc_off) - bc[len-1] = (crc7(0x7f, (const uint8 *)&bc[0], len-1)) << 1; - else - len-=1; - - if (M2M_SUCCESS != nmi_spi_write(bc, len)) { - M2M_ERR("[nmi spi]: Failed cmd write, bus error...\n"); - result = N_FAIL; - } - } - - return result; -} - -static sint8 spi_data_rsp(uint8 cmd) -{ -#ifdef ARDUINO - (void)cmd; // Silence "unused" warning -#endif - uint8 len; - uint8 rsp[3]; - sint8 result = N_OK; - - if (!gu8Crc_off) - len = 2; - else - len = 3; - - if (M2M_SUCCESS != nmi_spi_read(&rsp[0], len)) { - M2M_ERR("[nmi spi]: Failed bus error...\n"); - result = N_FAIL; - goto _fail_; - } - - if((rsp[len-1] != 0)||(rsp[len-2] != 0xC3)) - { - M2M_ERR("[nmi spi]: Failed data response read, %x %x %x\n",rsp[0],rsp[1],rsp[2]); - result = N_FAIL; - goto _fail_; - } -_fail_: - - return result; -} - -static sint8 spi_cmd_rsp(uint8 cmd) -{ - uint8 rsp; - sint8 result = N_OK; - sint8 s8RetryCnt; - - /** - Command/Control response - **/ - if ((cmd == CMD_RESET) || - (cmd == CMD_TERMINATE) || - (cmd == CMD_REPEAT)) { - if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { - result = N_FAIL; - goto _fail_; - } - } - - /* wait for response */ - s8RetryCnt = SPI_RESP_RETRY_COUNT; - do - { - if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { - M2M_ERR("[nmi spi]: Failed cmd response read, bus error...\n"); - result = N_FAIL; - goto _fail_; - } - } while((rsp != cmd) && (s8RetryCnt-- >0)); - - /** - State response - **/ - /* wait for response */ - s8RetryCnt = SPI_RESP_RETRY_COUNT; - do - { - if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { - M2M_ERR("[nmi spi]: Failed cmd response read, bus error...\n"); - result = N_FAIL; - goto _fail_; - } - } while((rsp != 0x00) && (s8RetryCnt-- >0)); - -_fail_: - - return result; -} -#ifndef USE_OLD_SPI_SW -static int spi_cmd_complete(uint8_t cmd, uint32_t adr, uint8_t *b, uint32_t sz, uint8_t clockless) -{ - uint8_t wb[32], rb[32]; - uint8_t wix, rix; - uint32_t len2; - uint8_t rsp; - int len = 0; - int result = N_OK; - - wb[0] = cmd; - switch (cmd) { - case CMD_SINGLE_READ: /* single word (4 bytes) read */ - wb[1] = (uint8_t)(adr >> 16); - wb[2] = (uint8_t)(adr >> 8); - wb[3] = (uint8_t)adr; - len = 5; - break; - case CMD_INTERNAL_READ: /* internal register read */ - wb[1] = (uint8_t)(adr >> 8); - if(clockless == 1) wb[1] |= (1 << 7); - wb[2] = (uint8_t)adr; - wb[3] = 0x00; - len = 5; - break; - case CMD_TERMINATE: /* termination */ - wb[1] = 0x00; - wb[2] = 0x00; - wb[3] = 0x00; - len = 5; - break; - case CMD_REPEAT: /* repeat */ - wb[1] = 0x00; - wb[2] = 0x00; - wb[3] = 0x00; - len = 5; - break; - case CMD_RESET: /* reset */ - wb[1] = 0xff; - wb[2] = 0xff; - wb[3] = 0xff; - len = 5; - break; - case CMD_DMA_WRITE: /* dma write */ - case CMD_DMA_READ: /* dma read */ - wb[1] = (uint8_t)(adr >> 16); - wb[2] = (uint8_t)(adr >> 8); - wb[3] = (uint8_t)adr; - wb[4] = (uint8_t)(sz >> 8); - wb[5] = (uint8_t)(sz); - len = 7; - break; - case CMD_DMA_EXT_WRITE: /* dma extended write */ - case CMD_DMA_EXT_READ: /* dma extended read */ - wb[1] = (uint8_t)(adr >> 16); - wb[2] = (uint8_t)(adr >> 8); - wb[3] = (uint8_t)adr; - wb[4] = (uint8_t)(sz >> 16); - wb[5] = (uint8_t)(sz >> 8); - wb[6] = (uint8_t)(sz); - len = 8; - break; - case CMD_INTERNAL_WRITE: /* internal register write */ - wb[1] = (uint8_t)(adr >> 8); - if(clockless == 1) wb[1] |= (1 << 7); - wb[2] = (uint8_t)(adr); - wb[3] = b[3]; - wb[4] = b[2]; - wb[5] = b[1]; - wb[6] = b[0]; - len = 8; - break; - case CMD_SINGLE_WRITE: /* single word write */ - wb[1] = (uint8_t)(adr >> 16); - wb[2] = (uint8_t)(adr >> 8); - wb[3] = (uint8_t)(adr); - wb[4] = b[3]; - wb[5] = b[2]; - wb[6] = b[1]; - wb[7] = b[0]; - len = 9; - break; - default: - result = N_FAIL; - break; - } - - if (result != N_OK) { - return result; - } - - if (!gu8Crc_off) { - wb[len-1] = (crc7(0x7f, (const uint8_t *)&wb[0], len-1)) << 1; - } else { - len -=1; - } - -#define NUM_SKIP_BYTES (1) -#define NUM_RSP_BYTES (2) -#define NUM_DATA_HDR_BYTES (1) -#define NUM_DATA_BYTES (4) -#define NUM_CRC_BYTES (2) -#define NUM_DUMMY_BYTES (3) - - if ((cmd == CMD_RESET) || - (cmd == CMD_TERMINATE) || - (cmd == CMD_REPEAT)) { - len2 = len + (NUM_SKIP_BYTES + NUM_RSP_BYTES + NUM_DUMMY_BYTES); - } else if ((cmd == CMD_INTERNAL_READ) || (cmd == CMD_SINGLE_READ)) { - if (!gu8Crc_off) { - len2 = len + (NUM_RSP_BYTES + NUM_DATA_HDR_BYTES + NUM_DATA_BYTES - + NUM_CRC_BYTES + NUM_DUMMY_BYTES); - } else { - len2 = len + (NUM_RSP_BYTES + NUM_DATA_HDR_BYTES + NUM_DATA_BYTES - + NUM_DUMMY_BYTES); - } - } else { - len2 = len + (NUM_RSP_BYTES + NUM_DUMMY_BYTES); - } -#undef NUM_DUMMY_BYTES - - if(len2 > (sizeof(wb)/sizeof(wb[0]))) { - M2M_ERR("[nmi spi]: spi buffer size too small (%d) (%d)\n", - len2, (sizeof(wb)/sizeof(wb[0]))); - result = N_FAIL; - return result; - } - /* zero spi write buffers. */ - for(wix = len; wix< len2; wix++) { - wb[wix] = 0; - } - rix = len; - - if (nmi_spi_rw(wb, rb, len2) != M2M_SUCCESS) { - M2M_ERR("[nmi spi]: Failed cmd write, bus error...\n"); - result = N_FAIL; - return result; - } - -#if 0 - { - int jj; - printk("--- cnd = %x, len=%d, len2=%d\n", cmd, len, len2); - for(jj=0; jj= len2) break; - if(((jj+1)%16) != 0) { - if((jj%16) == 0) { - printk("wb[%02x]: %02x ", jj, wb[jj]); - } else { - printk("%02x ", wb[jj]); - } - } else { - printk("%02x\n", wb[jj]); - } - } - printk("\n"); - - for(jj=0; jj= len2) break; - if(((jj+1)%16) != 0) { - if((jj%16) == 0) { - printk("rb[%02x]: %02x ", jj, rb[jj]); - } else { - printk("%02x ", rb[jj]); - } - } else { - printk("%02x\n", rb[jj]); - } - } - printk("\n"); - } -#endif - - /** - Command/Control response - **/ - if ((cmd == CMD_RESET) || - (cmd == CMD_TERMINATE) || - (cmd == CMD_REPEAT)) { - rix++; /* skip 1 byte */ - } - - rsp = rb[rix++]; - - - if (rsp != cmd) { - M2M_ERR("[nmi spi]: Failed cmd response, cmd (%02x), resp (%02x)\n", cmd, rsp); - result = N_FAIL; - return result; - } - - /** - State response - **/ - rsp = rb[rix++]; - if (rsp != 0x00) { - M2M_ERR("[nmi spi]: Failed cmd state response state (%02x)\n", rsp); - result = N_FAIL; - return result; - } - - if ((cmd == CMD_INTERNAL_READ) || (cmd == CMD_SINGLE_READ) - || (cmd == CMD_DMA_READ) || (cmd == CMD_DMA_EXT_READ)) { - int retry; - //uint16_t crc1, crc2; - uint8_t crc[2]; - /** - Data Respnose header - **/ - retry = SPI_RESP_RETRY_COUNT; - do { - /* ensure there is room in buffer later to read data and crc */ - if(rix < len2) { - rsp = rb[rix++]; - } else { - retry = 0; - break; - } - if (((rsp >> 4) & 0xf) == 0xf) - break; - } while (retry--); - - if (retry <= 0) { - M2M_ERR("[nmi spi]: Error, data read response (%02x)\n", rsp); - result = N_RESET; - return result; - } - - if ((cmd == CMD_INTERNAL_READ) || (cmd == CMD_SINGLE_READ)) { - /** - Read bytes - **/ - if((rix+3) < len2) { - b[0] = rb[rix++]; - b[1] = rb[rix++]; - b[2] = rb[rix++]; - b[3] = rb[rix++]; - } else { - M2M_ERR("[nmi spi]: buffer overrun when reading data.\n"); - result = N_FAIL; - return result; - } - - if (!gu8Crc_off) { - /** - Read Crc - **/ - if((rix+1) < len2) { - crc[0] = rb[rix++]; - crc[1] = rb[rix++]; - } else { - M2M_ERR("[nmi spi]: buffer overrun when reading crc.\n"); - result = N_FAIL; - return result; - } - } - } else if((cmd == CMD_DMA_READ) || (cmd == CMD_DMA_EXT_READ)) { - int ix; - - /* some data may be read in response to dummy bytes. */ - for(ix=0; (rix < len2) && (ix < sz);) { - b[ix++] = rb[rix++]; - } -#if 0 - if(ix) M2M_INFO("ttt %d %d\n", sz, ix); -#endif - sz -= ix; - - if(sz > 0) { - int nbytes; - - if (sz <= (DATA_PKT_SZ-ix)) { - nbytes = sz; - } else { - nbytes = DATA_PKT_SZ-ix; - } - - /** - Read bytes - **/ - if (nmi_spi_read(&b[ix], nbytes) != M2M_SUCCESS) { - M2M_ERR("[nmi spi]: Failed data block read, bus error...\n"); - result = N_FAIL; - goto _error_; - } - - /** - Read Crc - **/ - if (!gu8Crc_off) { - if (nmi_spi_read(crc, 2) != M2M_SUCCESS) { - M2M_ERR("[nmi spi]: Failed data block crc read, bus error...\n"); - result = N_FAIL; - goto _error_; - } - } - - - ix += nbytes; - sz -= nbytes; - } - - /* if any data in left unread, then read the rest using normal DMA code.*/ - while(sz > 0) { - int nbytes; - - if (sz <= DATA_PKT_SZ) { - nbytes = sz; - } else { - nbytes = DATA_PKT_SZ; - } - - /** - read data response only on the next DMA cycles not - the first DMA since data response header is already - handled above for the first DMA. - **/ - /** - Data Respnose header - **/ - retry = SPI_RESP_RETRY_COUNT; - do { - if (nmi_spi_read(&rsp, 1) != M2M_SUCCESS) { - M2M_ERR("[nmi spi]: Failed data response read, bus error...\n"); - result = N_FAIL; - break; - } - if (((rsp >> 4) & 0xf) == 0xf) - break; - } while (retry--); - - if (result == N_FAIL) - break; - - - /** - Read bytes - **/ - if (nmi_spi_read(&b[ix], nbytes) != M2M_SUCCESS) { - M2M_ERR("[nmi spi]: Failed data block read, bus error...\n"); - result = N_FAIL; - break; - } - - /** - Read Crc - **/ - if (!gu8Crc_off) { - if (nmi_spi_read(crc, 2) != M2M_SUCCESS) { - M2M_ERR("[nmi spi]: Failed data block crc read, bus error...\n"); - result = N_FAIL; - break; - } - } - - ix += nbytes; - sz -= nbytes; - } - } - } -_error_: - return result; -} -#endif -static sint8 spi_data_read(uint8 *b, uint16 sz,uint8 clockless) -{ - sint16 retry, ix, nbytes; - sint8 result = N_OK; - uint8 crc[2]; - uint8 rsp; - - /** - Data - **/ - ix = 0; - do { - if (sz <= DATA_PKT_SZ) - nbytes = sz; - else - nbytes = DATA_PKT_SZ; - - /** - Data Respnose header - **/ - retry = SPI_RESP_RETRY_COUNT; - do { - if (M2M_SUCCESS != nmi_spi_read(&rsp, 1)) { - M2M_ERR("[nmi spi]: Failed data response read, bus error...\n"); - result = N_FAIL; - break; - } - if (((rsp >> 4) & 0xf) == 0xf) - break; - } while (retry--); - - if (result == N_FAIL) - break; - - if (retry <= 0) { - M2M_ERR("[nmi spi]: Failed data response read...(%02x)\n", rsp); - result = N_FAIL; - break; - } - - /** - Read bytes - **/ - if (M2M_SUCCESS != nmi_spi_read(&b[ix], nbytes)) { - M2M_ERR("[nmi spi]: Failed data block read, bus error...\n"); - result = N_FAIL; - break; - } - if(!clockless) - { - /** - Read Crc - **/ - if (!gu8Crc_off) { - if (M2M_SUCCESS != nmi_spi_read(crc, 2)) { - M2M_ERR("[nmi spi]: Failed data block crc read, bus error...\n"); - result = N_FAIL; - break; - } - } - } - ix += nbytes; - sz -= nbytes; - - } while (sz); - - return result; -} - -static sint8 spi_data_write(uint8 *b, uint16 sz) -{ - sint16 ix; - uint16 nbytes; - sint8 result = 1; - uint8 cmd, order, crc[2] = {0}; - //uint8 rsp; - - /** - Data - **/ - ix = 0; - do { - if (sz <= DATA_PKT_SZ) - nbytes = sz; - else - nbytes = DATA_PKT_SZ; - - /** - Write command - **/ - cmd = 0xf0; - if (ix == 0) { - if (sz <= DATA_PKT_SZ) - order = 0x3; - else - order = 0x1; - } else { - if (sz <= DATA_PKT_SZ) - order = 0x3; - else - order = 0x2; - } - cmd |= order; - if (M2M_SUCCESS != nmi_spi_write(&cmd, 1)) { - M2M_ERR("[nmi spi]: Failed data block cmd write, bus error...\n"); - result = N_FAIL; - break; - } - - /** - Write data - **/ - if (M2M_SUCCESS != nmi_spi_write(&b[ix], nbytes)) { - M2M_ERR("[nmi spi]: Failed data block write, bus error...\n"); - result = N_FAIL; - break; - } - - /** - Write Crc - **/ - if (!gu8Crc_off) { - if (M2M_SUCCESS != nmi_spi_write(crc, 2)) { - M2M_ERR("[nmi spi]: Failed data block crc write, bus error...\n"); - result = N_FAIL; - break; - } - } - - ix += nbytes; - sz -= nbytes; - } while (sz); - - - return result; -} - -/******************************************** - - Spi Internal Read/Write Function - -********************************************/ - -/******************************************** - - Spi interfaces - -********************************************/ - -static sint8 spi_write_reg(uint32 addr, uint32 u32data) -{ - uint8 retry = SPI_RETRY_COUNT; - sint8 result = N_OK; - uint8 cmd = CMD_SINGLE_WRITE; - uint8 clockless = 0; - -_RETRY_: - if (addr <= 0x30) - { - /** - NMC1000 clockless registers. - **/ - cmd = CMD_INTERNAL_WRITE; - clockless = 1; - } - else - { - cmd = CMD_SINGLE_WRITE; - clockless = 0; - } - -#if defined USE_OLD_SPI_SW - result = spi_cmd(cmd, addr, u32data, 4, clockless); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd, write reg (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - - result = spi_cmd_rsp(cmd); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd response, write reg (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - -#else - - result = spi_cmd_complete(cmd, addr, (uint8*)&u32data, 4, clockless); - if (result != N_OK) { - M2M_ERR( "[nmi spi]: Failed cmd, write reg (%08x)...\n", addr); - goto _FAIL_; - } - -#endif -_FAIL_: - if(result != N_OK) - { - nm_bsp_sleep(1); - spi_cmd(CMD_RESET, 0, 0, 0, 0); - spi_cmd_rsp(CMD_RESET); - M2M_ERR("Reset and retry %d %lx %lx\n",retry,addr,u32data); - nm_bsp_sleep(1); - retry--; - if(retry) goto _RETRY_; - } - - return result; -} - -static sint8 nm_spi_write(uint32 addr, uint8 *buf, uint16 size) -{ - sint8 result; - uint8 retry = SPI_RETRY_COUNT; - uint8 cmd = CMD_DMA_EXT_WRITE; - - -_RETRY_: - /** - Command - **/ -#if defined USE_OLD_SPI_SW - //Workaround hardware problem with single byte transfers over SPI bus - if (size == 1) - size = 2; - - result = spi_cmd(cmd, addr, 0, size,0); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd, write block (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - - result = spi_cmd_rsp(cmd); - if (result != N_OK) { - M2M_ERR("[nmi spi ]: Failed cmd response, write block (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } -#else - result = spi_cmd_complete(cmd, addr, NULL, size, 0); - if (result != N_OK) { - M2M_ERR( "[nmi spi]: Failed cmd, write block (%08x)...\n", addr); - goto _FAIL_; - } -#endif - - /** - Data - **/ - result = spi_data_write(buf, size); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed block data write...\n"); - goto _FAIL_; - } - /** - Data RESP - **/ - result = spi_data_rsp(cmd); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed block data write...\n"); - goto _FAIL_; - } - -_FAIL_: - if(result != N_OK) - { - nm_bsp_sleep(1); - spi_cmd(CMD_RESET, 0, 0, 0, 0); - spi_cmd_rsp(CMD_RESET); - M2M_ERR("Reset and retry %d %lx %d\n",retry,addr,size); - nm_bsp_sleep(1); - retry--; - if(retry) goto _RETRY_; - } - - - return result; -} - -static sint8 spi_read_reg(uint32 addr, uint32 *u32data) -{ - uint8 retry = SPI_RETRY_COUNT; - sint8 result = N_OK; - uint8 cmd = CMD_SINGLE_READ; - uint8 tmp[4]; - uint8 clockless = 0; - -_RETRY_: - - if (addr <= 0xff) - { - /** - NMC1000 clockless registers. - **/ - cmd = CMD_INTERNAL_READ; - clockless = 1; - } - else - { - cmd = CMD_SINGLE_READ; - clockless = 0; - } - -#if defined USE_OLD_SPI_SW - result = spi_cmd(cmd, addr, 0, 4, clockless); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd, read reg (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - - result = spi_cmd_rsp(cmd); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd response, read reg (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - - /* to avoid endianess issues */ - result = spi_data_read(&tmp[0], 4, clockless); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed data read...\n"); - goto _FAIL_; - } -#else - result = spi_cmd_complete(cmd, addr, (uint8*)&tmp[0], 4, clockless); - if (result != N_OK) { - M2M_ERR( "[nmi spi]: Failed cmd, read reg (%08x)...\n", addr); - goto _FAIL_; - } - -#endif - - *u32data = tmp[0] | - ((uint32)tmp[1] << 8) | - ((uint32)tmp[2] << 16) | - ((uint32)tmp[3] << 24); - -_FAIL_: - if(result != N_OK) - { - - nm_bsp_sleep(1); - spi_cmd(CMD_RESET, 0, 0, 0, 0); - spi_cmd_rsp(CMD_RESET); - M2M_ERR("Reset and retry %d %lx\n",retry,addr); - nm_bsp_sleep(1); - retry--; - if(retry) goto _RETRY_; - } - - return result; -} - -static sint8 nm_spi_read(uint32 addr, uint8 *buf, uint16 size) -{ - uint8 cmd = CMD_DMA_EXT_READ; - sint8 result; - uint8 retry = SPI_RETRY_COUNT; -#if defined USE_OLD_SPI_SW - uint8 tmp[2]; - uint8 single_byte_workaround = 0; -#endif - -_RETRY_: - - /** - Command - **/ -#if defined USE_OLD_SPI_SW - if (size == 1) - { - //Workaround hardware problem with single byte transfers over SPI bus - size = 2; - single_byte_workaround = 1; - } - result = spi_cmd(cmd, addr, 0, size,0); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd, read block (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - - result = spi_cmd_rsp(cmd); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd response, read block (%08x)...\n", (unsigned int)addr); - goto _FAIL_; - } - - /** - Data - **/ - if (single_byte_workaround) - { - result = spi_data_read(tmp, size,0); - buf[0] = tmp[0]; - } - else - result = spi_data_read(buf, size,0); - - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed block data read...\n"); - goto _FAIL_; - } -#else - result = spi_cmd_complete(cmd, addr, buf, size, 0); - if (result != N_OK) { - M2M_ERR("[nmi spi]: Failed cmd, read block (%08x)...\n", addr); - goto _FAIL_; - } -#endif - -_FAIL_: - if(result != N_OK) - { - nm_bsp_sleep(1); - spi_cmd(CMD_RESET, 0, 0, 0, 0); - spi_cmd_rsp(CMD_RESET); - M2M_ERR("Reset and retry %d %lx %d\n",retry,addr,size); - nm_bsp_sleep(1); - retry--; - if(retry) goto _RETRY_; - } - - return result; -} - -/******************************************** - - Bus interfaces - -********************************************/ - -static void spi_init_pkt_sz(void) -{ - uint32 val32; - - /* Make sure SPI max. packet size fits the defined DATA_PKT_SZ. */ - val32 = nm_spi_read_reg(SPI_BASE+0x24); - val32 &= ~(0x7 << 4); - switch(DATA_PKT_SZ) - { - case 256: val32 |= (0 << 4); break; - case 512: val32 |= (1 << 4); break; - case 1024: val32 |= (2 << 4); break; - case 2048: val32 |= (3 << 4); break; - case 4096: val32 |= (4 << 4); break; - case 8192: val32 |= (5 << 4); break; - - } - nm_spi_write_reg(SPI_BASE+0x24, val32); -} - -sint8 nm_spi_reset(void) -{ - spi_cmd(CMD_RESET, 0, 0, 0, 0); - spi_cmd_rsp(CMD_RESET); - return M2M_SUCCESS; -} - -/* -* @fn nm_spi_init -* @brief Initialize the SPI -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_spi_init(void) -{ - uint32 chipid; - uint32 reg = 0; - - - /** - configure protocol - **/ - gu8Crc_off = 0; - - // TODO: We can remove the CRC trials if there is a definite way to reset - // the SPI to it's initial value. - if (!spi_read_reg(NMI_SPI_PROTOCOL_CONFIG, ®)) { - /* Read failed. Try with CRC off. This might happen when module - is removed but chip isn't reset*/ - gu8Crc_off = 1; - M2M_ERR("[nmi spi]: Failed internal read protocol with CRC on, retyring with CRC off...\n"); - if (!spi_read_reg(NMI_SPI_PROTOCOL_CONFIG, ®)){ - // Reaad failed with both CRC on and off, something went bad - M2M_ERR( "[nmi spi]: Failed internal read protocol...\n"); - return 0; - } - } - if(gu8Crc_off == 0) - { - reg &= ~0xc; /* disable crc checking */ - reg &= ~0x70; - reg |= (0x5 << 4); - if (!spi_write_reg(NMI_SPI_PROTOCOL_CONFIG, reg)) { - M2M_ERR( "[nmi spi]: Failed internal write protocol reg...\n"); - return 0; - } - gu8Crc_off = 1; - } - - /** - make sure can read back chip id correctly - **/ - if (!spi_read_reg(0x1000, &chipid)) { - M2M_ERR("[nmi spi]: Fail cmd read chip id...\n"); - return M2M_ERR_BUS_FAIL; - } - - M2M_DBG("[nmi spi]: chipid (%08x)\n", (unsigned int)chipid); - spi_init_pkt_sz(); - - - return M2M_SUCCESS; -} - -/* -* @fn nm_spi_init -* @brief DeInitialize the SPI -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Samer Sarhan -* @date 27 Feb 2015 -* @version 1.0 -*/ -sint8 nm_spi_deinit(void) -{ - gu8Crc_off = 0; - return M2M_SUCCESS; -} - -/* -* @fn nm_spi_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -uint32 nm_spi_read_reg(uint32 u32Addr) -{ - uint32 u32Val; - - spi_read_reg(u32Addr, &u32Val); - - return u32Val; -} - -/* -* @fn nm_spi_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_spi_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) -{ - sint8 s8Ret; - - s8Ret = spi_read_reg(u32Addr,pu32RetVal); - - if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; - else s8Ret = M2M_ERR_BUS_FAIL; - - return s8Ret; -} - -/* -* @fn nm_spi_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_spi_write_reg(uint32 u32Addr, uint32 u32Val) -{ - sint8 s8Ret; - - s8Ret = spi_write_reg(u32Addr, u32Val); - - if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; - else s8Ret = M2M_ERR_BUS_FAIL; - - return s8Ret; -} - -/* -* @fn nm_spi_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u16Sz -* Number of bytes to read. The buffer size must be >= u16Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_spi_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) -{ - sint8 s8Ret; - - s8Ret = nm_spi_read(u32Addr, puBuf, u16Sz); - - if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; - else s8Ret = M2M_ERR_BUS_FAIL; - - return s8Ret; -} - -/* -* @fn nm_spi_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u16Sz -* Number of bytes to write. The buffer size must be >= u16Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author M. Abdelmawla -* @date 11 July 2012 -* @version 1.0 -*/ -sint8 nm_spi_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) -{ - sint8 s8Ret; - - s8Ret = nm_spi_write(u32Addr, puBuf, u16Sz); - - if(N_OK == s8Ret) s8Ret = M2M_SUCCESS; - else s8Ret = M2M_ERR_BUS_FAIL; - - return s8Ret; -} - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmspi.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmspi.h deleted file mode 100644 index a1bd4a9..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmspi.h +++ /dev/null @@ -1,132 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 SPI protocol bus APIs implementation. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NMSPI_H_ -#define _NMSPI_H_ - -#include "common/include/nm_common.h" - -#ifdef __cplusplus - extern "C" { -#endif - -/** -* @fn nm_spi_init -* @brief Initialize the SPI -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_init(void); -/** -* @fn nm_spi_reset -* @brief reset the SPI -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_reset(void); - -/** -* @fn nm_spi_deinit -* @brief DeInitialize the SPI -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_deinit(void); - -/** -* @fn nm_spi_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -*/ -uint32 nm_spi_read_reg(uint32 u32Addr); - -/** -* @fn nm_spi_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); - -/** -* @fn nm_spi_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_write_reg(uint32 u32Addr, uint32 u32Val); - -/** -* @fn nm_spi_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u16Sz -* Number of bytes to read. The buffer size must be >= u16Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); - -/** -* @fn nm_spi_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u16Sz -* Number of bytes to write. The buffer size must be >= u16Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_spi_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); - -#ifdef __cplusplus - } -#endif - -#endif /* _NMSPI_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmuart.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmuart.c deleted file mode 100644 index 63541cf..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmuart.c +++ /dev/null @@ -1,536 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 UART protocol bus APIs implementation. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include "common/include/nm_common.h" - -#ifdef CONF_WINC_USE_UART - -#include "driver/source/nmuart.h" -#include "bus_wrapper/include/nm_bus_wrapper.h" - -#define HDR_SZ 12 - -static uint8 get_cs(uint8* b, uint8 sz){ - int i; - uint8 cs = 0; - for(i = 0; i < sz; i++) - cs ^= b[i]; - return cs; -} - -/* -* @fn nm_uart_sync_cmd -* @brief Check COM Port -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Dina El Sissy -* @date 13 AUG 2012 -* @version 1.0 -*/ -sint8 nm_uart_sync_cmd(void) -{ - tstrNmUartDefault strUart; - sint8 s8Ret = -1; - uint8 b [HDR_SZ+1]; - uint8 rsz; - uint8 onchip = 0; - - /*read reg*/ - b[0] = 0x12; - - rsz = 1; - strUart.pu8Buf = b; - strUart.u16Sz = 1; - - if(M2M_SUCCESS == nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - strUart.u16Sz = rsz; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - M2M_ERR("failed to send cfg bytes\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - if (b[0] == 0x5a) - { - s8Ret = 0; - onchip = 1; - M2M_INFO("Built-in WINC1500 UART Found\n"); - } - else if(b[0] == 0x5b) - { - s8Ret = 0; - onchip = 0; - M2M_INFO("WINC1500 Serial Bridge Found\n"); - } - /*TODO: this should be the way we read the register since the cortus is little endian*/ - /**pu32RetVal = b[0] | ((uint32)b[1] << 8) | ((uint32)b[2] << 16) | ((uint32)b[3] << 24);*/ - if(s8Ret == M2M_SUCCESS) - s8Ret = (sint8)onchip; - return s8Ret; -} - sint8 nm_uart_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal) -{ - tstrNmUartDefault strUart; - sint8 s8Ret = M2M_SUCCESS; - uint8 b [HDR_SZ+1]; - uint8 rsz; - - /*read reg*/ - b[0] = 0xa5; - b[1] = 0; - b[2] = 0; - b[3] = 0; - b[4] = 0; - b[5] = (uint8)(u32Addr & 0x000000ff); - b[6] = (uint8)((u32Addr & 0x0000ff00)>>8); - b[7] = (uint8)((u32Addr & 0x00ff0000)>>16); - b[8] = (uint8)((u32Addr & 0xff000000)>>24); - b[9] = 0; - b[10] = 0; - b[11] = 0; - b[12] = 0; - - b[2] = get_cs(&b[1],HDR_SZ); - - rsz = 4; - strUart.pu8Buf = b; - strUart.u16Sz = sizeof(b); - - if(M2M_SUCCESS == nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - if(!nm_bus_get_chip_type()) - { - strUart.u16Sz = 1; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - if(b[0] == 0xAC) - { - M2M_DBG("Successfully sent the command\n"); - strUart.u16Sz = rsz; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - strUart.u16Sz = rsz; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - } - } - else - { - M2M_ERR("failed to send cfg bytes\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - /*TODO: this should be the way we read the register since the cortus is little endian*/ - /**pu32RetVal = b[0] | ((uint32)b[1] << 8) | ((uint32)b[2] << 16) | ((uint32)b[3] << 24);*/ - - *pu32RetVal = ((uint32)b[0] << 24) | ((uint32)b[1] << 16) | ((uint32)b[2] << 8) | b[3]; - - return s8Ret; -} - -/* -* @fn nm_uart_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -* @author Dina El Sissy -* @date 13 AUG 2012 -* @version 1.0 -*/ -uint32 nm_uart_read_reg(uint32 u32Addr) -{ - uint32 val; - nm_uart_read_reg_with_ret(u32Addr , &val); - return val; -} - -/* -* @fn nm_uart_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Dina El Sissy -* @date 13 AUG 2012 -* @version 1.0 -*/ -sint8 nm_uart_write_reg(uint32 u32Addr, uint32 u32Val) -{ - tstrNmUartDefault strUart; - sint8 s8Ret = M2M_SUCCESS; - uint8 b[HDR_SZ+1]; - - /*write reg*/ - b[0] = 0xa5; - b[1] = 1; - b[2] = 0; - b[3] = 0; - b[4] = 0; - b[5] = (uint8)(u32Addr & 0x000000ff); - b[6] = (uint8)((u32Addr & 0x0000ff00)>>8); - b[7] = (uint8)((u32Addr & 0x00ff0000)>>16); - b[8] = (uint8)((u32Addr & 0xff000000)>>24); - b[9] = (uint8)(u32Val & 0x000000ff); - b[10] = (uint8)((u32Val & 0x0000ff00)>>8); - b[11] = (uint8)((u32Val & 0x00ff0000)>>16); - b[12] = (uint8)((u32Val & 0xff000000)>>24); - - b[2] = get_cs(&b[1],HDR_SZ); - - get_cs(&b[1],HDR_SZ); - - strUart.pu8Buf = b; - strUart.u16Sz = sizeof(b); - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - else - { - if(!nm_bus_get_chip_type()) - { - //check for the ack from the SAMD21 for the packet reception. - strUart.u16Sz = 1; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - if(b[0] == 0xAC) - { - M2M_DBG("Successfully sent the reg write command\n"); - } - else - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - } - - return s8Ret; -} - - -/** -* @fn nm_uart_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u16Sz -* Number of bytes to read. The buffer size must be >= u16Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Dina El Sissy -* @date 13 AUG 2012 -* @version 1.0 -*/ -sint8 nm_uart_read_block(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz) -{ - tstrNmUartDefault strUart; - sint8 s8Ret = M2M_SUCCESS; - uint8 au8Buf[HDR_SZ+1]; - - au8Buf[0] = 0xa5; - au8Buf[1] = 2; - au8Buf[2] = 0; - au8Buf[3] = (uint8)(u16Sz & 0x00ff); - au8Buf[4] = (uint8)((u16Sz & 0xff00)>>8); - au8Buf[5] = (uint8)(u32Addr & 0x000000ff); - au8Buf[6] = (uint8)((u32Addr & 0x0000ff00)>>8); - au8Buf[7] = (uint8)((u32Addr & 0x00ff0000)>>16); - au8Buf[8] = (uint8)((u32Addr & 0xff000000)>>24); - au8Buf[9] = 0; - au8Buf[10] = 0; - au8Buf[11] = 0; - au8Buf[12] = 0; - - au8Buf[2] = get_cs(&au8Buf[1],HDR_SZ); - - strUart.pu8Buf = au8Buf; - strUart.u16Sz = sizeof(au8Buf); - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - else - { - if(!nm_bus_get_chip_type()) - { - //check for the ack from the SAMD21 for the packet reception. - strUart.u16Sz = 1; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - if(au8Buf[0] == 0xAC) - { - M2M_DBG("Successfully sent the block read command\n"); - strUart.pu8Buf = pu8Buf; - strUart.u16Sz = u16Sz; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - M2M_ERR("read error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - M2M_ERR("write error (Error sending the block read command)\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - strUart.pu8Buf = pu8Buf; - strUart.u16Sz = u16Sz; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - M2M_ERR("read error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - } - - return s8Ret; -} - -/** -* @fn nm_uart_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u16Sz -* Number of bytes to write. The buffer size must be >= u16Sz -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Dina El Sissy -* @date 13 AUG 2012 -* @version 1.0 -*/ -sint8 nm_uart_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz) -{ - tstrNmUartDefault strUart; - sint8 s8Ret = M2M_SUCCESS; - static uint8 au8Buf[HDR_SZ+1]; - - au8Buf[0] = 0xa5; - au8Buf[1] = 3; - au8Buf[2] = 0; - au8Buf[3] = (uint8)(u16Sz & 0x00ff); - au8Buf[4] = (uint8)((u16Sz & 0xff00)>>8); - au8Buf[5] = (uint8)(u32Addr & 0x000000ff); - au8Buf[6] = (uint8)((u32Addr & 0x0000ff00)>>8); - au8Buf[7] = (uint8)((u32Addr & 0x00ff0000)>>16); - au8Buf[8] = (uint8)((u32Addr & 0xff000000)>>24); - au8Buf[9] = 0; - au8Buf[10] = 0; - au8Buf[11] = 0; - au8Buf[12] = 0; - - au8Buf[2] = get_cs(&au8Buf[1],HDR_SZ); - - strUart.pu8Buf = au8Buf; - strUart.u16Sz = sizeof(au8Buf); - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - else - { - if(!nm_bus_get_chip_type()) - { - //check for the ack from the SAMD21 for the packet reception. - strUart.u16Sz = 1; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - if(au8Buf[0] == 0xAC) - { - M2M_DBG("Successfully sent the block Write command\n"); - strUart.pu8Buf = puBuf; - strUart.u16Sz = u16Sz; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - else - { - //check for the ack from the SAMD21 for the payload reception. - strUart.pu8Buf = au8Buf; - strUart.u16Sz = 1; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - if(au8Buf[0] == 0xAC) - { - M2M_DBG("Successfully sent the data payload\n"); - } - else - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - } - else - { - M2M_ERR("write error (Error sending the block write command)\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - else - { - strUart.pu8Buf = puBuf; - strUart.u16Sz = u16Sz; - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - } - return s8Ret; -} - -/** -* @fn nm_uart_reconfigure -* @brief Reconfigures the UART interface -* @param [in] ptr -* Pointer to a DWORD containing baudrate at this moment. -* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure -* @author Viswanathan Murugesan -* @date 22 OCT 2014 -* @version 1.0 -*/ -sint8 nm_uart_reconfigure(void *ptr) -{ - tstrNmUartDefault strUart; - sint8 s8Ret = M2M_SUCCESS; - uint8 b[HDR_SZ+1]; - - /*write reg*/ - b[0] = 0xa5; - b[1] = 5; - b[2] = 0; - b[3] = 0; - b[4] = 0; - b[5] = 0; - b[6] = 0; - b[7] = 0; - b[8] = 0; - b[9] = (uint8)((*(unsigned long *)ptr) & 0x000000ff); - b[10] = (uint8)(((*(unsigned long *)ptr) & 0x0000ff00)>>8); - b[11] = (uint8)(((*(unsigned long *)ptr) & 0x00ff0000)>>16); - b[12] = (uint8)(((*(unsigned long *)ptr) & 0xff000000)>>24); - - b[2] = get_cs(&b[1],HDR_SZ); - - get_cs(&b[1],HDR_SZ); - - strUart.pu8Buf = b; - strUart.u16Sz = sizeof(b); - - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_W, &strUart)) - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - else - { - if(!nm_bus_get_chip_type()) - { - //check for the ack from the SAMD21 for the packet reception. - strUart.u16Sz = 1; - if(M2M_SUCCESS != nm_bus_ioctl(NM_BUS_IOCTL_R, &strUart)) - { - s8Ret = M2M_ERR_BUS_FAIL; - } - if(b[0] == 0xAC) - { - M2M_DBG("Successfully sent the UART reconfigure command\n"); - } - else - { - M2M_ERR("write error\n"); - s8Ret = M2M_ERR_BUS_FAIL; - } - } - } - - return s8Ret; -} -#endif -/* EOF */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmuart.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmuart.h deleted file mode 100644 index 8f07d39..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/driver/source/nmuart.h +++ /dev/null @@ -1,118 +0,0 @@ -/** - * - * \file - * - * \brief This module contains NMC1000 UART protocol bus APIs implementation. - * - * Copyright (c) 2016 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef _NMUART_H_ -#define _NMUART_H_ - -#include "common/include/nm_common.h" - -/* -* @fn nm_uart_sync_cmd -* @brief Check COM Port -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_uart_sync_cmd(void); -/** -* @fn nm_uart_read_reg -* @brief Read register -* @param [in] u32Addr -* Register address -* @return Register value -*/ -uint32 nm_uart_read_reg(uint32 u32Addr); - -/** -* @fn nm_uart_read_reg_with_ret -* @brief Read register with error code return -* @param [in] u32Addr -* Register address -* @param [out] pu32RetVal -* Pointer to u32 variable used to return the read value -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_uart_read_reg_with_ret(uint32 u32Addr, uint32* pu32RetVal); - -/** -* @fn nm_uart_write_reg -* @brief write register -* @param [in] u32Addr -* Register address -* @param [in] u32Val -* Value to be written to the register -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_uart_write_reg(uint32 u32Addr, uint32 u32Val); - -/** -* @fn nm_uart_read_block -* @brief Read block of data -* @param [in] u32Addr -* Start address -* @param [out] puBuf -* Pointer to a buffer used to return the read data -* @param [in] u16Sz -* Number of bytes to read. The buffer size must be >= u16Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_uart_read_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); - -/** -* @fn nm_uart_write_block -* @brief Write block of data -* @param [in] u32Addr -* Start address -* @param [in] puBuf -* Pointer to the buffer holding the data to be written -* @param [in] u16Sz -* Number of bytes to write. The buffer size must be >= u16Sz -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_uart_write_block(uint32 u32Addr, uint8 *puBuf, uint16 u16Sz); - -/** -* @fn nm_uart_reconfigure -* @brief Reconfigures the UART interface -* @param [in] ptr -* Pointer to a DWORD containing baudrate at this moment. -* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure -*/ -sint8 nm_uart_reconfigure(void *ptr); -#endif /* _NMI2C_H_ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h deleted file mode 100644 index 933ad67..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/m2m_socket_host_if.h +++ /dev/null @@ -1,461 +0,0 @@ -/** - * - * \file - * - * \brief BSD compatible socket interface internal types. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -#ifndef __M2M_SOCKET_HOST_IF_H__ -#define __M2M_SOCKET_HOST_IF_H__ - - -#ifdef __cplusplus -extern "C" { -#endif - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#ifndef _BOOT_ -#ifndef _FIRMWARE_ -#include "socket/include/socket.h" -#else -#include "m2m_types.h" -#endif -#endif - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -/* - * HOSTNAME_MAX_SIZE is defined here and also in host_drv/socket/include/socket.h - * The two definitions must match. -*/ -#ifdef _FIRMWARE_ -#define HOSTNAME_MAX_SIZE (64) -#endif - -#define SSL_MAX_OPT_LEN HOSTNAME_MAX_SIZE - - - -#define SOCKET_CMD_INVALID 0x00 -/*!< - Invlaid Socket command value. -*/ - - -#define SOCKET_CMD_BIND 0x41 -/*!< - Socket Binding command value. -*/ - - -#define SOCKET_CMD_LISTEN 0x42 -/*!< - Socket Listening command value. -*/ - - -#define SOCKET_CMD_ACCEPT 0x43 -/*!< - Socket Accepting command value. -*/ - - -#define SOCKET_CMD_CONNECT 0x44 -/*!< - Socket Connecting command value. -*/ - - -#define SOCKET_CMD_SEND 0x45 -/*!< - Socket send command value. -*/ - - -#define SOCKET_CMD_RECV 0x46 -/*!< - Socket Recieve command value. -*/ - - -#define SOCKET_CMD_SENDTO 0x47 -/*!< - Socket sendTo command value. -*/ - - -#define SOCKET_CMD_RECVFROM 0x48 -/*!< - Socket RecieveFrom command value. -*/ - - -#define SOCKET_CMD_CLOSE 0x49 -/*!< - Socket Close command value. -*/ - - -#define SOCKET_CMD_DNS_RESOLVE 0x4A -/*!< - Socket DNS Resolve command value. -*/ - - -#define SOCKET_CMD_SSL_CONNECT 0x4B -/*!< - SSL-Socket Connect command value. -*/ - - -#define SOCKET_CMD_SSL_SEND 0x4C -/*!< - SSL-Socket Send command value. -*/ - - -#define SOCKET_CMD_SSL_RECV 0x4D -/*!< - SSL-Socket Recieve command value. -*/ - - -#define SOCKET_CMD_SSL_CLOSE 0x4E -/*!< - SSL-Socket Close command value. -*/ - - -#define SOCKET_CMD_SET_SOCKET_OPTION 0x4F -/*!< - Set Socket Option command value. -*/ - - -#define SOCKET_CMD_SSL_CREATE 0x50 -/*!< -*/ - - -#define SOCKET_CMD_SSL_SET_SOCK_OPT 0x51 -/*!< -*/ - - -#define SOCKET_CMD_PING 0x52 -/*!< -*/ - - -#define SOCKET_CMD_SSL_SET_CS_LIST 0x53 -/*!< - Recommend instead using @ref M2M_SSL_REQ_SET_CS_LIST and - associated response @ref M2M_SSL_RESP_SET_CS_LIST -*/ - - -#define SOCKET_CMD_SSL_BIND 0x54 -/*!< -*/ - - -#define SOCKET_CMD_SSL_EXP_CHECK 0x55 -/*!< -*/ - - - -#define PING_ERR_SUCCESS 0 -#define PING_ERR_DEST_UNREACH 1 -#define PING_ERR_TIMEOUT 2 - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -/*! -* @brief -*/ -typedef struct{ - uint16 u16Family; - uint16 u16Port; - uint32 u32IPAddr; -}tstrSockAddr; - - -typedef sint8 SOCKET; -typedef tstrSockAddr tstrUIPSockAddr; - - - -/*! -@struct \ - tstrDnsReply - -@brief - DNS Reply, contains hostName and HostIP. -*/ -typedef struct{ - char acHostName[HOSTNAME_MAX_SIZE]; - uint32 u32HostIP; -}tstrDnsReply; - - -/*! -@brief -*/ -typedef struct{ - tstrSockAddr strAddr; - SOCKET sock; - uint8 u8Void; - uint16 u16SessionID; -}tstrBindCmd; - - -/*! -@brief -*/ -typedef struct{ - SOCKET sock; - sint8 s8Status; - uint16 u16SessionID; -}tstrBindReply; - - -/*! -* @brief -*/ -typedef struct{ - SOCKET sock; - uint8 u8BackLog; - uint16 u16SessionID; -}tstrListenCmd; - - -/*! -@struct \ - tstrSocketRecvMsg - -@brief Socket recv status. - - It is passed to the APPSocketEventHandler with SOCKET_MSG_RECV or SOCKET_MSG_RECVFROM message type - in a response to a user call to the recv or recvfrom. - If the received data from the remote peer is larger than the USER Buffer size (given at recv call), the data is - delivered to the user in a number of consecutive chunks according to the USER Buffer size. -*/ -typedef struct{ - SOCKET sock; - sint8 s8Status; - uint16 u16SessionID; -}tstrListenReply; - - -/*! -* @brief -*/ -typedef struct{ - tstrSockAddr strAddr; - SOCKET sListenSock; - SOCKET sConnectedSock; - uint16 u16AppDataOffset; - /*!< - In further packet send requests the host interface should put the user application - data at this offset in the allocated shared data packet. - */ -}tstrAcceptReply; - - -/*! -* @brief -*/ -typedef struct{ - tstrSockAddr strAddr; - SOCKET sock; - uint8 u8SslFlags; - uint16 u16SessionID; -}tstrConnectCmd; - - -/*! -@struct \ - tstrConnectReply - -@brief - Connect Reply, contains sock number and error value -*/ -typedef struct{ - SOCKET sock; - sint8 s8Error; - uint16 u16AppDataOffset; - /*!< - In further packet send requests the host interface should put the user application - data at this offset in the allocated shared data packet. - */ -}tstrConnectReply; - - -/*! -@brief -*/ -typedef struct{ - SOCKET sock; - uint8 u8Void; - uint16 u16DataSize; - tstrSockAddr strAddr; - uint16 u16SessionID; - uint16 u16Void; -}tstrSendCmd; - - -/*! -@struct \ - tstrSendReply - -@brief - Send Reply, contains socket number and number of sent bytes. -*/ -typedef struct{ - SOCKET sock; - uint8 u8Void; - sint16 s16SentBytes; - uint16 u16SessionID; - uint16 u16Void; -}tstrSendReply; - - -/*! -* @brief -*/ -typedef struct{ - uint32 u32Timeoutmsec; - SOCKET sock; - uint8 u8Void; - uint16 u16SessionID; -}tstrRecvCmd; - - -/*! -@struct -@brief -*/ -typedef struct{ - tstrSockAddr strRemoteAddr; - sint16 s16RecvStatus; - uint16 u16DataOffset; - SOCKET sock; - uint8 u8Void; - uint16 u16SessionID; -}tstrRecvReply; - - -/*! -* @brief -*/ -typedef struct{ - uint32 u32OptionValue; - SOCKET sock; - uint8 u8Option; - uint16 u16SessionID; -}tstrSetSocketOptCmd; - - -typedef struct{ - SOCKET sslSock; - uint8 __PAD24__[3]; -}tstrSSLSocketCreateCmd; - - -/*! -* @brief -*/ -typedef struct{ - SOCKET sock; - uint8 u8Option; - uint16 u16SessionID; - uint32 u32OptLen; - uint8 au8OptVal[SSL_MAX_OPT_LEN]; -}tstrSSLSetSockOptCmd; - - -/*! -*/ -typedef struct{ - uint32 u32DestIPAddr; - uint32 u32CmdPrivate; - uint16 u16PingCount; - uint8 u8TTL; - uint8 __PAD8__; -}tstrPingCmd; - - -typedef struct{ - uint32 u32IPAddr; - uint32 u32CmdPrivate; - uint32 u32RTT; - uint16 u16Success; - uint16 u16Fail; - uint8 u8ErrorCode; - uint8 __PAD24__[3]; -}tstrPingReply; - - -/*! -@struct\ - tstrSslCertExpSettings - -@brief SSL Certificate Expiry Validation Settings - -@sa tenuSslCertExpSettings -*/ -typedef struct{ - uint32 u32CertExpValidationOpt; - /*!< - See @tenuSslCertExpSettings for possible values. - */ -}tstrSslCertExpSettings; - - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __M2M_SOCKET_HOST_IF_H__ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/socket.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/socket.h deleted file mode 100644 index 837959a..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/socket.h +++ /dev/null @@ -1,2065 +0,0 @@ -/** - * - * \file - * - * \brief WINC BSD compatible Socket Interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef __SOCKET_H__ -#define __SOCKET_H__ - -#ifdef __cplusplus -extern "C" { -#endif - -/** \defgroup SocketHeader Socket - * BSD compatible socket interface beftween the host layer and the network - * protocol stacks in the firmware. - * These functions are used by the host application to send or receive - * packets and to do other socket operations. - */ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "common/include/nm_common.h" -#include "driver/include/m2m_types.h" - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/** - * @defgroup SocketDefines Defines - * @ingroup SocketHeader - */ - -/** @defgroup IPDefines TCP/IP Defines - * @ingroup SocketDefines - * The following list of macros are used to define constants used throughout the socket layer. - * @{ - */ - -/* - * HOSTNAME_MAX_SIZE is defined here and also in host_drv/socket/include/m2m_socket_host_if.h - * The two definitions must match. -*/ -#define HOSTNAME_MAX_SIZE 64 -/*!< - Maximum allowed size for a host domain name passed to the function gethostbyname @ref gethostbyname. - command value. Used with the setsockopt function. - -*/ - -#define SOCKET_BUFFER_MAX_LENGTH 1400 -/*!< - Maximum allowed size for a socket data buffer. Used with @ref send socket - function to ensure that the buffer sent is within the allowed range. -*/ - -#define AF_INET 2 -/*!< - The AF_INET is the address family used for IPv4. An IPv4 transport address is specified with the @ref sockaddr_in structure. - (It is the only supported type for the current implementation.) -*/ - - -#define SOCK_STREAM 1 -/*!< - One of the IPv4 supported socket types for reliable connection-oriented stream connection. - Passed to the @ref socket function for the socket creation operation. -*/ - -#define SOCK_DGRAM 2 -/*!< - One of the IPv4 supported socket types for unreliable connectionless datagram connection. - Passed to the @ref socket function for the socket creation operation. -*/ - - -#define SOCKET_FLAGS_SSL 0x01 -/*!< - This flag shall be passed to the socket API for SSL session. -*/ - -#define TCP_SOCK_MAX (7) -/*!< - Maximum number of simultaneous TCP sockets. -*/ - -#define UDP_SOCK_MAX 4 -/*!< - Maximum number of simultaneous UDP sockets. -*/ - -#define MAX_SOCKET (TCP_SOCK_MAX + UDP_SOCK_MAX) -/*!< - Maximum number of Sockets. -*/ - -#define SOL_SOCKET 1 -/*!< - Socket option. - Used with the @ref setsockopt function -*/ - -#define SOL_SSL_SOCKET 2 -/*!< - SSL Socket option level. - Used with the @ref setsockopt function -*/ - -#define SO_SET_UDP_SEND_CALLBACK 0x00 -/*!< - Socket option used by the application to enable/disable - the use of UDP send callbacks. - Used with the @ref setsockopt function. -*/ - -#define IP_ADD_MEMBERSHIP 0x01 -/*!< - Set Socket Option Add Membership command value (to join a multicast group). - Used with the @ref setsockopt function. -*/ - - -#define IP_DROP_MEMBERSHIP 0x02 -/*!< - Set Socket Option Drop Membership command value (to leave a multicast group). - Used with the @ref setsockopt function. -*/ - //@} - - - -/** - * @defgroup TLSDefines TLS Defines - * @ingroup SocketDefines - */ - - - -/** @defgroup SSLSocketOptions TLS Socket Options - * @ingroup TLSDefines - * The following list of macros are used to define SSL Socket options. - * @{ - * @sa setsockopt - */ - -#define SO_SSL_BYPASS_X509_VERIF 0x01 -/*!< - Allow an opened SSL socket to bypass the X509 certificate - verification process. - It is highly required NOT to use this socket option in production - software applications. It is supported for debugging and testing - purposes. - The option value should be casted to int type and it is handled - as a boolean flag. -*/ - - -#define SO_SSL_SNI 0x02 -/*!< - Set the Server Name Indicator (SNI) for an SSL socket. The - SNI is a NULL terminated string containing the server name - associated with the connection. It must not exceed the size - of HOSTNAME_MAX_SIZE. -*/ - - -#define SO_SSL_ENABLE_SESSION_CACHING 0x03 -/*!< - This option allow the TLS to cache the session information for fast - TLS session establishment in future connections using the - TLS Protocol session resume features. -*/ - - -#define SO_SSL_ENABLE_SNI_VALIDATION 0x04 -/*!< - Enable SNI validation against the server's certificate subject - common name. If there is no SNI provided (via the SO_SSL_SNI - option), setting this option does nothing. -*/ - - -//@} - - - -/** @defgroup LegacySSLCipherSuite Legacy names for TLS Cipher Suite IDs - * @ingroup TLSDefines - * The following list of macros MUST NOT be used. Instead use the new names under SSLCipherSuiteID - * @sa sslSetActiveCipherSuites - * @{ - */ - -#define SSL_ENABLE_RSA_SHA_SUITES 0x01 -/*!< - Enable RSA Hmac_SHA based Cipher suites. For example, - TLS_RSA_WITH_AES_128_CBC_SHA -*/ - - -#define SSL_ENABLE_RSA_SHA256_SUITES 0x02 -/*!< - Enable RSA Hmac_SHA256 based Cipher suites. For example, - TLS_RSA_WITH_AES_128_CBC_SHA256 -*/ - - -#define SSL_ENABLE_DHE_SHA_SUITES 0x04 -/*!< - Enable DHE Hmac_SHA based Cipher suites. For example, - TLS_DHE_RSA_WITH_AES_128_CBC_SHA -*/ - - -#define SSL_ENABLE_DHE_SHA256_SUITES 0x08 -/*!< - Enable DHE Hmac_SHA256 based Cipher suites. For example, - TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 -*/ - - -#define SSL_ENABLE_RSA_GCM_SUITES 0x10 -/*!< - Enable RSA AEAD based Cipher suites. For example, - TLS_RSA_WITH_AES_128_GCM_SHA256 -*/ - - -#define SSL_ENABLE_DHE_GCM_SUITES 0x20 -/*!< - Enable DHE AEAD based Cipher suites. For example, - TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 -*/ - - -#define SSL_ENABLE_ALL_SUITES 0x0000003F -/*!< - Enable all possible supported cipher suites. -*/ - -//@} - - - -/** @defgroup SSLCipherSuiteID TLS Cipher Suite IDs - * @ingroup TLSDefines - * The following list of macros defined the list of supported TLS Cipher suites. - * Each MACRO defines a single Cipher suite. - * @sa m2m_ssl_set_active_ciphersuites - * @{ - */ - -#define SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA NBIT0 -#define SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 NBIT1 -#define SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA NBIT2 -#define SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 NBIT3 -#define SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 NBIT4 -#define SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 NBIT5 -#define SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA NBIT6 -#define SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 NBIT7 -#define SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA NBIT8 -#define SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 NBIT9 -#define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA NBIT10 -#define SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA NBIT11 -#define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 NBIT12 -#define SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 NBIT13 -#define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 NBIT14 -#define SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 NBIT15 - - - -#define SSL_ECC_ONLY_CIPHERS \ -(\ - SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 \ -) -/*!< - All ciphers that use ECC crypto only. This execuldes ciphers that use RSA. They use ECDSA instead. - These ciphers are turned off by default at startup. - The application may enable them if it has an ECC math engine (like ATECC508). -*/ -#define SSL_ECC_ALL_CIPHERS \ -(\ - SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA | \ - SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 | \ - SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 \ -) -/*!< - All supported ECC Ciphers including those ciphers that depend on RSA and ECC. - These ciphers are turned off by default at startup. - The application may enable them if it has an ECC math engine (like ATECC508). -*/ - -#define SSL_NON_ECC_CIPHERS_AES_128 \ -(\ - SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA | \ - SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA | \ - SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 | \ - SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 \ -) -/*!< - All supported AES-128 Ciphers (ECC ciphers are not counted). This is the default active group after startup. -*/ - - -#define SSL_ECC_CIPHERS_AES_256 \ -(\ - SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA \ -) -/*!< - ECC AES-256 supported ciphers. -*/ - - -#define SSL_NON_ECC_CIPHERS_AES_256 \ -(\ - SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA | \ - SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 | \ - SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA | \ - SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 \ -) -/*!< - AES-256 Ciphers. - This group is disabled by default at startup because the WINC1500 HW Accelerator - supports only AES-128. If the application needs to force AES-256 cipher support, - it could enable them (or any of them) explicitly by calling sslSetActiveCipherSuites. -*/ - - -#define SSL_CIPHER_ALL \ -(\ - SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA | \ - SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA | \ - SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 | \ - SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 | \ - SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA | \ - SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 | \ - SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA | \ - SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 | \ - SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA | \ - SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 | \ - SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \ - SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 | \ - SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA \ -) -/*!< - Turn On All TLS Ciphers. -*/ - - - //@} - - - - -/************** -Socket Errors -**************/ -/**@defgroup SocketErrorCode Error Codes - * @ingroup SocketHeader - * The following list of macros are used to define the possible error codes returned as a result of a call to a socket function. - * Errors are listed in numerical order with the error macro name. - * @{ - */ -#define SOCK_ERR_NO_ERROR 0 -/*!< - Successful socket operation -*/ - - -#define SOCK_ERR_INVALID_ADDRESS -1 -/*!< - Socket address is invalid. The socket operation cannot be completed successfully without specifying a specific address - For example: bind is called without specifying a port number -*/ - - -#define SOCK_ERR_ADDR_ALREADY_IN_USE -2 -/*!< - Socket operation cannot bind on the given address. With socket operations, only one IP address per socket is permitted. - Any attempt for a new socket to bind with an IP address already bound to another open socket, - will return the following error code. States that bind operation failed. -*/ - - -#define SOCK_ERR_MAX_TCP_SOCK -3 -/*!< - Exceeded the maximum number of TCP sockets. A maximum number of TCP sockets opened simultaneously is defined through TCP_SOCK_MAX. - It is not permitted to exceed that number at socket creation. Identifies that @ref socket operation failed. -*/ - - -#define SOCK_ERR_MAX_UDP_SOCK -4 -/*!< - Exceeded the maximum number of UDP sockets. A maximum number of UDP sockets opened simultaneously is defined through UDP_SOCK_MAX. - It is not permitted to exceed that number at socket creation. Identifies that @ref socket operation failed -*/ - - -#define SOCK_ERR_INVALID_ARG -6 -/*!< - An invalid argument is passed to a function. -*/ - - -#define SOCK_ERR_MAX_LISTEN_SOCK -7 -/*!< - Exceeded the maximum number of TCP passive listening sockets. - Identifies Identifies that @ref listen operation failed. -*/ - - -#define SOCK_ERR_INVALID -9 -/*!< - The requested socket operation is not valid in the - current socket state. - For example: @ref accept is called on a TCP socket before @ref bind or @ref listen. -*/ - - -#define SOCK_ERR_ADDR_IS_REQUIRED -11 -/*!< - Destination address is required. Failure to provide the socket address required for the socket operation to be completed. - It is generated as an error to the @ref sendto function when the address required to send the data to is not known. -*/ - - -#define SOCK_ERR_CONN_ABORTED -12 -/*!< - The socket is closed by the peer. The local socket is - closed also. -*/ - - -#define SOCK_ERR_TIMEOUT -13 -/*!< - The socket pending operation has Timedout. -*/ - - -#define SOCK_ERR_BUFFER_FULL -14 -/*!< - No buffer space available to be used for the requested socket operation. -*/ - -#ifdef _NM_BSP_BIG_END - -#define _htonl(m) (m) -#define _htons(A) (A) - -#else - -#define _htonl(m) \ - (uint32)(((uint32)(m << 24)) | ((uint32)((m & 0x0000FF00) << 8)) | ((uint32)((m & 0x00FF0000) >> 8)) | ((uint32)(m >> 24))) -/*!< - Convert a 4-byte integer from the host representation to the Network byte order representation. -*/ - - -#define _htons(A) (uint16)((((uint16) (A)) << 8) | (((uint16) (A)) >> 8)) -/*!< - Convert a 2-byte integer (short) from the host representation to the Network byte order representation. -*/ - - -#endif - - -#define _ntohl _htonl -/*!< - Convert a 4-byte integer from the Network byte order representation to the host representation . -*/ - - -#define _ntohs _htons -/*!< - Convert a 2-byte integer from the Network byte order representation to the host representation . -*/ - //@} - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/** @defgroup SocketEnums DataTypes - * @ingroup SocketHeader - * Specific Enumeration-typedefs used for socket operations - * @{ */ - -/*! -@typedef \ - SOCKET - -@brief - Definition for socket handler data type. - Socket ID,used with all socket operations to uniquely identify the socket handler. - Such an ID is uniquely assigned at socket creation when calling @ref socket operation. -*/ -typedef sint8 SOCKET; - - - -/*! -@struct \ - in_addr - -@brief - IPv4 address representation. - - This structure is used as a placeholder for IPV4 address in other structures. -@see - sockaddr_in -*/ -typedef struct{ - uint32 s_addr; - /*!< - Network Byte Order representation of the IPv4 address. For example, - the address "192.168.0.10" is represented as 0x0A00A8C0. - */ -}in_addr; - - -/*! -@struct \ - sockaddr - -@brief - Generic socket address structure. - -@see - sockaddr_in -*/ -struct sockaddr{ - uint16 sa_family; - /*!< -Socket address family. - */ - uint8 sa_data[14]; - /*!< - Maximum size of all the different socket address structures. - */ -}; - - -/*! -@struct \ - sockaddr_in - -@brief - Socket address structure for IPV4 addresses. Used to specify socket address information to which to connect to. - Can be cast to @ref sockaddr structure. -*/ -struct sockaddr_in{ - uint16 sin_family; - /*!< - Specifies the address family(AF). - Members of AF_INET address family are IPv4 addresses. - Hence,the only supported value for this is AF_INET. - */ - uint16 sin_port; - /*!< - Port number of the socket. - Network sockets are identified by a pair of IP addresses and port number. - It must be set in the Network Byte Order format , @ref _htons (e.g. _htons(80)). - Can NOT have zero value. - */ - in_addr sin_addr; - /*!< - IP Address of the socket. - The IP address is of type @ref in_addr structure. - Can be set to "0" to accept any IP address for server operation. non zero otherwise. - */ - uint8 sin_zero[8]; - /*!< - Padding to make structure the same size as @ref sockaddr. - */ -}; - //@} -/**@defgroup AsyncCalback Asynchronous Events - * @ingroup SocketEnums - * Specific Enumeration used for asynchronous operations - * @{ */ -/*! -@enum \ - tenuSocketCallbackMsgType - -@brief - Asynchronous APIs, make use of callback functions, in-order to return back the results once the corresponding socket operation is completed. - Hence resuming the normal execution of the application code while the socket operation returns the results. - Callback functions expect event messages to be passed in, in-order to identify the operation they're returning the results for. - The following enum identifies the type of events that are received in the callback function. - - Application Use: - In order for application developers to handle the pending events from the network controller through the callback functions. - A function call must be made to the function @ref m2m_wifi_handle_events at least once for each socket operation. - -@see - bind - listen - accept - connect - send - recv - -*/ -typedef enum{ - SOCKET_MSG_BIND = 1, - /*!< - Bind socket event. - */ - SOCKET_MSG_LISTEN, - /*!< - Listen socket event. - */ - SOCKET_MSG_DNS_RESOLVE, - /*!< - DNS Resolution event. - */ - SOCKET_MSG_ACCEPT, - /*!< - Accept socket event. - */ - SOCKET_MSG_CONNECT, - /*!< - Connect socket event. - */ - SOCKET_MSG_RECV, - /*!< - Receive socket event. - */ - SOCKET_MSG_SEND, - /*!< - Send socket event. - */ - SOCKET_MSG_SENDTO, - /*!< - sendto socket event. - */ - SOCKET_MSG_RECVFROM - /*!< - Recvfrom socket event. - */ -}tenuSocketCallbackMsgType; - - -/*! -@struct \ - tstrSocketBindMsg - -@brief Socket bind status. - - An asynchronous call to the @ref bind socket operation, returns information through this structure in response. - This structure together with the event @ref SOCKET_MSG_BIND are passed in paramters to the callback function. -@see - bind - -*/ -typedef struct{ - sint8 status; - /*!< - The result of the bind operation. - Holding a value of ZERO for a successful bind or otherwise a negative - error code corresponding to the type of error. - */ -}tstrSocketBindMsg; - - -/*! -@struct \ - tstrSocketListenMsg - -@brief Socket listen status. - - Socket listen information is returned through this structure in response to the asynchronous call to the @ref listen function. - This structure together with the event @ref SOCKET_MSG_LISTEN are passed-in parameters to the callback function. -@see - listen -*/ -typedef struct{ - sint8 status; - /*!< - Holding a value of ZERO for a successful listen or otherwise a negative - error code corresponding to the type of error. - */ -}tstrSocketListenMsg; - - - -/*! -@struct \ - tstrSocketAcceptMsg - -@brief Socket accept status. - - Socket accept information is returned through this structure in response to the asynchronous call to the @ref accept function. - This structure together with the event @ref SOCKET_MSG_ACCEPT are passed-in parameters to the callback function. -*/ -typedef struct{ - SOCKET sock; - /*!< - On a successful @ref accept operation, the return information is the socket ID for the accepted connection with the remote peer. - Otherwise a negative error code is returned to indicate failure of the accept operation. - */ - struct sockaddr_in strAddr; - /*!< - Socket address structure for the remote peer. - */ -}tstrSocketAcceptMsg; - - -/*! -@struct \ - tstrSocketConnectMsg - -@brief Socket connect status. - - Socket connect information is returned through this structure in response to the asynchronous call to the @ref connect socket function. - This structure together with the event @ref SOCKET_MSG_CONNECT are passed-in parameters to the callback function. -*/ -typedef struct{ - SOCKET sock; - /*!< - Socket ID referring to the socket passed to the connect function call. - */ - sint8 s8Error; - /*!< - Connect error code. - Holding a value of ZERO for a successful connect or otherwise a negative - error code corresponding to the type of error. - */ -}tstrSocketConnectMsg; - - -/*! -@struct \ - tstrSocketRecvMsg - -@brief Socket recv status. - - Socket receive information is returned through this structure in response to the asynchronous call to the recv or recvfrom socket functions. - This structure together with the events @ref SOCKET_MSG_RECV or @ref SOCKET_MSG_RECVFROM are passed-in parameters to the callback function. -@remark - In case the received data from the remote peer is larger than the USER buffer size defined during the asynchronous call to the @ref recv function, the data is - delivered to the user in a number of consecutive chunks according to the USER Buffer size. - a negative or zero buffer size indicates an error with the following code: - @ref SOCK_ERR_NO_ERROR : Socket connection closed - @ref SOCK_ERR_CONN_ABORTED : Socket connection aborted - @SOCK_ERR_TIMEOUT : Socket receive timed out -*/ -typedef struct{ - uint8 *pu8Buffer; - /*!< - Pointer to the USER buffer (passed to @ref recv and @ref recvfrom function) containing the received data chunk. - */ - sint16 s16BufferSize; - /*!< - The received data chunk size. - Holds a negative value if there is a receive error or ZERO on success upon reception of close socket message. - */ - uint16 u16RemainingSize; - /*!< - The number of bytes remaining in the current @ref recv operation. - */ - struct sockaddr_in strRemoteAddr; - /*!< - Socket address structure for the remote peer. It is valid for @ref SOCKET_MSG_RECVFROM event. - */ -}tstrSocketRecvMsg; - - -/*! -@typedef \ - tpfAppSocketCb - -@brief - The main socket application callback function. Applications register their main socket application callback through this function by calling @ref registerSocketCallback. - In response to events received, the following callback function is called to handle the corresponding asynchronous function called. Example: @ref bind, @ref connect,...etc. - -@param [in] sock - Socket ID for the callback. - - The socket callback function is called whenever a new event is recived in response - to socket operations. - -@param [in] u8Msg - Socket event type. Possible values are: - - @ref SOCKET_MSG_BIND - - @ref SOCKET_MSG_LISTEN - - @ref SOCKET_MSG_ACCEPT - - @ref SOCKET_MSG_CONNECT - - @ref SOCKET_MSG_RECV - - @ref SOCKET_MSG_SEND - - @ref SOCKET_MSG_SENDTO - - @ref SOCKET_MSG_RECVFROM - -@param [in] pvMsg - Pointer to message structure. Existing types are: - - tstrSocketBindMsg - - tstrSocketListenMsg - - tstrSocketAcceptMsg - - tstrSocketConnectMsg - - tstrSocketRecvMsg - -@see - tenuSocketCallbackMsgType - tstrSocketRecvMsg - tstrSocketConnectMsg - tstrSocketAcceptMsg - tstrSocketListenMsg - tstrSocketBindMsg -*/ -typedef void (*tpfAppSocketCb) (SOCKET sock, uint8 u8Msg, void * pvMsg); - - -/*! -@typedef \ - tpfAppResolveCb - -@brief - DNS resolution callback function. - Applications requiring DNS resolution should register their callback through this function by calling @ref registerSocketCallback. - The following callback is triggered in response to asynchronous call to the @ref gethostbyname function (DNS Resolution callback). - -@param [in] pu8DomainName - Domain name of the host. - -@param [in] u32ServerIP - Server IPv4 address encoded in NW byte order format. If it is Zero, then the DNS resolution failed. -*/ -typedef void (*tpfAppResolveCb) (uint8* pu8DomainName, uint32 u32ServerIP); - -/*! -@typedef \ - tpfPingCb - -@brief PING Callback - - The function delivers the ping statistics for the sent ping triggered by calling - m2m_ping_req. - -@param [in] u32IPAddr - Destination IP. - -@param [in] u32RTT - Round Trip Time. - -@param [in] u8ErrorCode - Ping error code. It may be one of: - - PING_ERR_SUCCESS - - PING_ERR_DEST_UNREACH - - PING_ERR_TIMEOUT -*/ -typedef void (*tpfPingCb)(uint32 u32IPAddr, uint32 u32RTT, uint8 u8ErrorCode); - - /**@}*/ -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -/** \defgroup SocketAPI Function - * @ingroup SocketHeader - */ - -/** @defgroup SocketInitalizationFn socketInit - * @ingroup SocketAPI - * The function performs the necessary initializations for the socket library through the following steps: - - A check made by the global variable gbSocketInit, ensuring that initialization for sockets is performed only once, - in-order to prevent reseting the socket instances already created in the global socket array (gastrSockets). - - Zero initializations to the global socket array (gastrSockets), which holds the list of TCP sockets. - - Registers the socket (Host Interface)hif callback function through the call to the hif_register_cb function. - This facilitates handling all of the socket related functions received through interrupts from the firmware. - - */ - /**@{*/ -/*! -@fn \ - NMI_API void socketInit(void); - -@param [in] void - -@return void - -@remarks - This initialization function must be invoked before any socket operation is performed. - No error codes from this initialization function since the socket array is statically allocated based in the maximum number of - sockets @ref MAX_SOCKET based on the systems capability. -\section Example -This example demonstrates the use of the socketinit for socket initialization for an mqtt chat application. - \code - tstrWifiInitParam param; - int8_t ret; - char topic[strlen(MAIN_CHAT_TOPIC) + MAIN_CHAT_USER_NAME_SIZE + 1]; - - //Initialize the board. - system_init(); - - //Initialize the UART console. - configure_console(); - - // Initialize the BSP. - nm_bsp_init(); - - ---------- - - // Initialize socket interface. - socketInit(); - registerSocketCallback(socket_event_handler, socket_resolve_handler); - - // Connect to router. - m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), - MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); - -\endcode -*/ -NMI_API void socketInit(void); - - -/*! -@fn \ - NMI_API void socketDeinit(void); - -@brief Socket Layer De-initialization - - The function performs the necessary cleanup for the socket library static data - It must be invoked as the last any socket operation is performed on any active sockets. -*/ -NMI_API void socketDeinit(void); - - -/** @} */ -/** @defgroup SocketCallbackFn registerSocketCallback - * @ingroup SocketAPI - Register two callback functions one for asynchronous socket events and the other one for DNS callback registering function. - The registered callback functions are used to retrieve information in response to the asynchronous socket functions called. - */ - /**@{*/ - - -/*! -@fn \ - NMI_API void registerSocketCallback(tpfAppSocketCb socket_cb, tpfAppResolveCb resolve_cb); - -@param [in] tpfAppSocketCb - Assignment of callback function to the global callback @ref tpfAppSocketCb gpfAppSocketCb. Delivers - socket messages to the host application. In response to the asynchronous function calls, such as @ref bind - @ref listen @ref accept @ref connect - -@param [in] tpfAppResolveCb - Assignment of callback function to the global callback @ref tpfAppResolveCb gpfAppResolveCb. - Used for DNS resolving functionalities. The DNS resolving technique is determined by the application - registering the callback. - NULL is assigned when, DNS resolution is not required. - -@return void -@remarks - If any of the socket functionalities is not to be used, NULL is passed in as a parameter. - It must be invoked after socketinit and before other socket layer operations. - -\section Example - This example demonstrates the use of the registerSocketCallback to register a socket callback function with DNS resolution CB set to null - for a simple UDP server example. - \code - tstrWifiInitParam param; - int8_t ret; - struct sockaddr_in addr; - - // Initialize the board - system_init(); - - //Initialize the UART console. - configure_console(); - - // Initialize the BSP. - nm_bsp_init(); - - // Initialize socket address structure. - addr.sin_family = AF_INET; - addr.sin_port = _htons(MAIN_WIFI_M2M_SERVER_PORT); - addr.sin_addr.s_addr = _htonl(MAIN_WIFI_M2M_SERVER_IP); - - // Initialize Wi-Fi parameters structure. - memset((uint8_t *)¶m, 0, sizeof(tstrWifiInitParam)); - - // Initialize Wi-Fi driver with data and status callbacks. - param.pfAppWifiCb = wifi_cb; - ret = m2m_wifi_init(¶m); - if (M2M_SUCCESS != ret) { - printf("main: m2m_wifi_init call error!(%d)\r\n", ret); - while (1) { - } - } - - // Initialize socket module - socketInit(); - registerSocketCallback(socket_cb, NULL); - - // Connect to router. - m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); - \endcode -*/ -NMI_API void registerSocketCallback(tpfAppSocketCb socket_cb, tpfAppResolveCb resolve_cb); - - -/** @} */ - -/** @defgroup SocketFn socket - * @ingroup SocketAPI - * Synchronous socket allocation function based on the specified socket type. Created sockets are non-blocking and their possible types are either TCP or a UDP sockets. - * The maximum allowed number of TCP sockets is @ref TCP_SOCK_MAX sockets while the maximum number of UDP sockets that can be created simultaneously is @ref UDP_SOCK_MAX sockets. - * -*/ - /**@{*/ -/*! -@fn \ - NMI_API SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags); - - -@param [in] u16Domain - Socket family. The only allowed value is AF_INET (IPv4.0) for TCP/UDP sockets. - -@param [in] u8Type - Socket type. Allowed values are: - - [SOCK_STREAM](@ref SOCK_STREAM) - - [SOCK_DGRAM](@ref SOCK_DGRAM) - -@param [in] u8Flags - Used to specify the socket creation flags. It shall be set to zero for normal TCP/UDP sockets. - It could be @ref SOCKET_FLAGS_SSL if the socket is used for SSL session. The use of the flag - @ref SOCKET_FLAGS_SSL has no meaning in case of UDP sockets. - -@pre - The @ref socketInit function must be called once at the beginning of the application to initialize the socket handler. - before any call to the socket function can be made. - -@see - connect - bind - listen - accept - recv - recvfrom - send - sendto - close - setsockopt - getsockopt - -@return - On successful socket creation, a non-blocking socket type is created and a socket ID is returned - In case of failure the function returns a negative value, identifying one of the socket error codes defined. - For example: @ref SOCK_ERR_INVALID for invalid argument or - @ref SOCK_ERR_MAX_TCP_SOCK if the number of TCP allocated sockets exceeds the number of available sockets. - -@remarks - The socket function must be called a priori to any other related socket functions "e.g. send, recv, close ..etc" -\section Example - This example demonstrates the use of the socket function to allocate the socket, returning the socket handler to be used for other -socket operations. Socket creation is dependent on the socket type. -\subsection sub1 UDP example -@code - SOCKET UdpServerSocket = -1; - - UdpServerSocket = socket(AF_INET, SOCK_DGRAM, 0); - -@endcode -\subsection sub2 TCP example -@code - static SOCKET tcp_client_socket = -1; - - tcp_client_socket = socket(AF_INET, SOCK_STREAM, 0)); -@endcode -\subsection sub3 SSL example -@code -static SOCKET ssl_socket = -1; - -ssl_socket = socket(AF_INET, SOCK_STREAM, SOCK_FLAGS_SSL)); -@endcode -*/ -NMI_API SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags); - - -/** @} */ -/** @defgroup BindFn bind - * @ingroup SocketAPI -* Asynchronous bind function associates the provided address and local port to the socket. -* The function can be used with both TCP and UDP sockets it's mandatory to call the @ref bind function before starting any UDP or TCP server operation. -* Upon socket bind completion, the application will receive a @ref SOCKET_MSG_BIND message in the socket callback. -*/ - /**@{*/ -/*! -\fn \ - NMI_API sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); - - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] pstrAddr - Pointer to socket address structure "sockaddr_in" - [sockaddr_in](@ref sockaddr_in) - - -@param [in] u8AddrLen - Size of the given socket address structure in bytes. - -@pre - The socket function must be called to allocate a socket before passing the socket ID to the bind function. - -@see - socket - connect - listen - accept - recv - recvfrom - send - sendto - -@return - The function returns ZERO for successful operations and a negative value otherwise. - The possible error values are: - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - Indicating that the operation was successful. - - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) - Indicating passing invalid arguments such as negative socket ID or NULL socket address structure. - - - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID) - Indicate socket bind failure. -\section Example - This example demonstrates the call of the bind socket operation after a successful socket operation. -@code - struct sockaddr_in addr; - SOCKET udpServerSocket =-1; - int ret = -1; - - if(udpServerSocket == -1) - { - udpServerSocket = socket(AF_INET, SOCK_DGRAM, 0); - if(udpServerSocket >= 0) - { - addr.sin_family = AF_INET; - addr.sin_port = _htons(1234); - addr.sin_addr.s_addr = 0; - ret = bind(udpServerSocket,(struct sockaddr*)&addr,sizeof(addr)); - - if(ret != 0) - { - printf("Bind Failed. Error code = %d\n",ret); - close(udpServerSocket); - } - } - else - { - printf("UDP Server Socket Creation Failed\n"); - return; - } - } -@endcode -*/ -NMI_API sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); - - -/** @} */ - -/** @defgroup ListenFn listen - * @ingroup SocketAPI - * After successful socket binding to an IP address and port on the system, start listening on a passive socket for incoming connections. - The socket must be bound on a local port or the listen operation fails. - Upon the call to the asynchronous listen function, response is received through the event [SOCKET_MSG_BIND](@ref SOCKET_MSG_BIND) - in the socket callback. - A successful listen means the TCP server operation is active. If a connection is accepted, then the application socket callback function is - notified with the new connected socket through the event @ref SOCKET_MSG_ACCEPT. Hence there is no need to call the @ref accept function - after calling @ref listen. - - After a connection is accepted, the user is then required to call the @ref recv to receive any packets transmitted by the remote host or to receive notification of socket connection - termination. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 listen(SOCKET sock, uint8 backlog); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] backlog - Not used by the current implementation. - -@pre - The bind function must be called to assign the port number and IP address to the socket before the listen operation. - -@see - bind - accept - recv - recvfrom - send - sendto - -@return - The function returns ZERO for successful operations and a negative value otherwise. - The possible error values are: - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - Indicating that the operation was successful. - - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) - Indicating passing invalid arguments such as negative socket ID. - - - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID) - Indicate socket listen failure. -\section Example -This example demonstrates the call of the listen socket operation after a successful socket operation. -@code - static void TCP_Socketcallback(SOCKET sock, uint8 u8Msg, void * pvMsg) - { - int ret =-1; - - switch(u8Msg) - { - case SOCKET_MSG_BIND: - { - tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg; - if(pstrBind != NULL) - { - if(pstrBind->status == 0) - { - ret = listen(sock, 0); - - if(ret <0) - printf("Listen failure! Error = %d\n",ret); - } - else - { - M2M_ERR("bind Failure!\n"); - close(sock); - } - } - } - break; - - case SOCKET_MSG_LISTEN: - { - - tstrSocketListenMsg *pstrListen = (tstrSocketListenMsg*)pvMsg; - if(pstrListen != NULL) - { - if(pstrListen->status == 0) - { - ret = accept(sock,NULL,0); - } - else - { - M2M_ERR("listen Failure!\n"); - close(sock); - } - } - } - break; - - case SOCKET_MSG_ACCEPT: - { - tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg*)pvMsg; - - if(pstrAccept->sock >= 0) - { - TcpNotificationSocket = pstrAccept->sock; - recv(pstrAccept->sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT); - } - else - { - M2M_ERR("accept failure\n"); - } - } - break; - - default: - break; - } - } - -@endcode -*/ -NMI_API sint8 listen(SOCKET sock, uint8 backlog); -/** @} */ -/** @defgroup AcceptFn accept - * @ingroup SocketAPI - * The function has no current implementation. An empty deceleration is used to prevent errors when legacy application code is used. - * For recent application use, the accept function can be safer as it has no effect and could be safely removed from any application using it. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. -@param [in] addr - Not used in the current implementation. - -@param [in] addrlen - Not used in the current implementation. - -@return - The function returns ZERO for successful operations and a negative value otherwise. - The possible error values are: - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - Indicating that the operation was successful. - - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) - Indicating passing invalid arguments such as negative socket ID. -*/ -NMI_API sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen); -/** @} */ -/** @defgroup ConnectFn connect - * @ingroup SocketAPI - * Establishes a TCP connection with a remote server. - The asynchronous connect function must be called after receiving a valid socket ID from the @ref socket function. - The application socket callback function is notified of a successful new socket connection through the event @ref SOCKET_MSG_CONNECT. - A successful connect means the TCP session is active. The application is then required to make a call to the @ref recv - to receive any packets transmitted by the remote server, unless the application is interrupted by a notification of socket connection - termination. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] pstrAddr - Address of the remote server. -@param [in] pstrAddr - Pointer to socket address structure "sockaddr_in" - [sockaddr_in](@ref sockaddr_in) - -@param [in] u8AddrLen - Size of the given socket address structure in bytes. - Not currently used, implemented for BSD compatibility only. -@pre - The socket function must be called to allocate a TCP socket before passing the socket ID to the bind function. - If the socket is not bound, you do NOT have to call bind before the "connect" function. - -@see - socket - recv - send - close - -@return - The function returns ZERO for successful operations and a negative value otherwise. - The possible error values are: - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - Indicating that the operation was successful. - - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) - Indicating passing invalid arguments such as negative socket ID or NULL socket address structure. - - - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID) - Indicate socket connect failure. -\section Example - The example demonstrates a TCP application, showing how the asynchronous call to the connect function is made through the main function and how the - callback function handles the @ref SOCKET_MSG_CONNECT event. -\subsection sub1 Main Function -@code - struct sockaddr_in Serv_Addr; - SOCKET TcpClientSocket =-1; - int ret = -1 - - TcpClientSocket = socket(AF_INET,SOCK_STREAM,0); - Serv_Addr.sin_family = AF_INET; - Serv_Addr.sin_port = _htons(1234); - Serv_Addr.sin_addr.s_addr = inet_addr(SERVER); - printf("Connected to server via socket %u\n",TcpClientSocket); - - do - { - ret = connect(TcpClientSocket,(sockaddr_in*)&Serv_Addr,sizeof(Serv_Addr)); - if(ret != 0) - { - printf("Connection Error\n"); - } - else - { - printf("Connection successful.\n"); - break; - } - }while(1) -@endcode -\subsection sub2 Socket Callback -@code - if(u8Msg == SOCKET_MSG_CONNECT) - { - tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg*)pvMsg; - if(pstrConnect->s8Error == 0) - { - uint8 acBuffer[GROWL_MSG_SIZE]; - uint16 u16MsgSize; - - printf("Connect success!\n"); - - u16MsgSize = FormatMsg(u8ClientID, acBuffer); - send(sock, acBuffer, u16MsgSize, 0); - recv(pstrNotification->Socket, (void*)au8Msg,GROWL_DESCRIPTION_MAX_LENGTH, GROWL_RX_TIMEOUT); - u8Retry = GROWL_CONNECT_RETRY; - } - else - { - M2M_DBG("Connection Failed, Error: %d\n",pstrConnect->s8Error"); - close(pstrNotification->Socket); - } - } -@endcode -*/ -#ifdef ARDUINO -NMI_API sint8 connectSocket(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); -#else -NMI_API sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen); -#endif -/** @} */ -/** @defgroup ReceiveFn recv - * @ingroup SocketAPI - * An asynchronous receive function, used to retrieve data from a TCP stream. - Before calling the recv function, a successful socket connection status must have been received through any of the two socket events - [SOCKET_MSG_CONNECT] or [SOCKET_MSG_ACCEPT], from the socket callback. Hence, indicating that the socket is already connected to a remote - host. - The application receives the required data in response to this asynchronous call through the reception of the event @ref SOCKET_MSG_RECV in the - socket callback. - - Receiving the SOCKET_MSG_RECV message in the callback with zero or negative buffer length indicates the following: - - SOCK_ERR_NO_ERROR : Socket connection closed - - SOCK_ERR_CONN_ABORTED : Socket connection aborted - - SOCK_ERR_TIMEOUT : Socket receive timed out - The application code is expected to close the socket through the call to the @ref close function upon the appearance of the above mentioned errors. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - - -@param [in] pvRecvBuf - Pointer to a buffer that will hold the received data. The buffer is used - in the recv callback to deliver the received data to the caller. The buffer must - be resident in memory (heap or global buffer). - -@param [in] u16BufLen - The buffer size in bytes. - -@param [in] u32Timeoutmsec - Timeout for the recv function in milli-seconds. If the value is set to ZERO, the timeout - will be set to infinite (the recv function waits forever). If the timeout period is - elapsed with no data received, the socket will get a timeout error. -@pre - - The socket function must be called to allocate a TCP socket before passing the socket ID to the recv function. - - The socket in a connected state is expected to receive data through the socket interface. - -@see - socket - connect - bind - listen - recvfrom - close - - -@return - The function returns ZERO for successful operations and a negative value otherwise. - The possible error values are: - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - Indicating that the operation was successful. - - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) - Indicating passing invalid arguments such as negative socket ID or NULL Recieve buffer. - - - [SOCK_ERR_BUFFER_FULL](@ref SOCK_ERR_BUFFER_FULL) - Indicate socket receive failure. -\section Example - The example demonstrates a code snippet for the calling of the recv function in the socket callback upon notification of the accept or connect events, and the parsing of the - received data when the SOCKET_MSG_RECV event is received. -@code - - switch(u8Msg) - { - - case SOCKET_MSG_ACCEPT: - { - tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg*)pvMsg; - - if(pstrAccept->sock >= 0) - { - recv(pstrAccept->sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT); - } - else - { - M2M_ERR("accept\n"); - } - } - break; - - - case SOCKET_MSG_RECV: - { - tstrSocketRecvMsg *pstrRx = (tstrSocketRecvMsg*)pvMsg; - - if(pstrRx->s16BufferSize > 0) - { - - recv(sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT); - } - else - { - printf("Socet recv Error: %d\n",pstrRx->s16BufferSize); - close(sock); - } - } - break; - - default: - break; - } -} -@endcode -*/ -NMI_API sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec); -/** @} */ -/** @defgroup ReceiveFromSocketFn recvfrom - * @ingroup SocketAPI - * Receives data from a UDP Socket. -* -* The asynchronous recvfrom function is used to retrieve data from a UDP socket. The socket must already be bound to -* a local port before a call to the recvfrom function is made (i.e message @ref SOCKET_MSG_BIND is received -* with successful status in the socket callback). -* -* Upon calling the recvfrom function with a successful return code, the application is expected to receive a notification -* in the socket callback whenever a message is received through the @ref SOCKET_MSG_RECVFROM event. -* -* Receiving the SOCKET_MSG_RECVFROM message in the callback with zero, indicates that the socket is closed. -* Whereby a negative buffer length indicates one of the socket error codes such as socket timeout error @SOCK_ERR_TIMEOUT: -* -* The recvfrom callback can also be used to show the IP address of the remote host that sent the frame by -* using the "strRemoteAddr" element in the @ref tstrSocketRecvMsg structure. (refer to the code example) - */ - /**@{*/ -/*! -@fn \ - NMI_API sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32TimeoutSeconds); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] pvRecvBuf - Pointer to a buffer that will hold the received data. The buffer shall be used - in the recv callback to deliver the received data to the caller. The buffer must - be resident in memory (heap or global buffer). - -@param [in] u16BufLen - The buffer size in bytes. - -@param [in] u32TimeoutSeconds - Timeout for the recv function in milli-seconds. If the value is set to ZERO, the timeout - will be set to infinite (the recv function waits forever). - -@pre - - The socket function must be called to allocate a UDP socket before passing the socket ID to the recvfrom function. - - The socket corresponding to the socket ID must be successfully bound to a local port through the call to a @ref bind function. - -@see - socket - bind - close - -@return - The function returns ZERO for successful operations and a negative value otherwise. - The possible error values are: - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - Indicating that the operation was successful. - - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) - Indicating passing invalid arguments such as negative socket ID or NULL Receive buffer. - - - [SOCK_ERR_BUFFER_FULL](@ref SOCK_ERR_BUFFER_FULL) - Indicate socket receive failure. -\section Example - The example demonstrates a code snippet for the calling of the recvfrom function in the socket callback upon notification of a successful bind event, and the parsing of the - received data when the SOCKET_MSG_RECVFROM event is received. -@code - switch(u8Msg) - { - - case SOCKET_MSG_BIND: - { - tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg; - - if(pstrBind != NULL) - { - if(pstrBind->status == 0) - { - recvfrom(sock, gau8SocketTestBuffer, TEST_BUFFER_SIZE, 0); - } - else - { - M2M_ERR("bind\n"); - } - } - } - break; - - - case SOCKET_MSG_RECVFROM: - { - tstrSocketRecvMsg *pstrRx = (tstrSocketRecvMsg*)pvMsg; - - if(pstrRx->s16BufferSize > 0) - { - //get the remote host address and port number - uint16 u16port = pstrRx->strRemoteAddr.sin_port; - uint32 strRemoteHostAddr = pstrRx->strRemoteAddr.sin_addr.s_addr; - - printf("Recieved frame with size = %d.\tHost address=%x, Port number = %d\n\n",pstrRx->s16BufferSize,strRemoteHostAddr, u16port); - - ret = recvfrom(sock,gau8SocketTestBuffer,sizeof(gau8SocketTestBuffer),TEST_RECV_TIMEOUT); - } - else - { - printf("Socet recv Error: %d\n",pstrRx->s16BufferSize); - ret = close(sock); - } - } - break; - - default: - break; - } -} -@endcode -*/ -NMI_API sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec); -/** @} */ -/** @defgroup SendFn send - * @ingroup SocketAPI -* Asynchronous sending function, used to send data on a TCP/UDP socket. - -* Called by the application code when there is outgoing data available required to be sent on a specific socket handler. -* The only difference between this function and the similar @ref sendto function, is the type of socket the data is sent on and the parameters passed in. -* @ref send function is most commonly called for sockets in a connected state. -* After the data is sent, the socket callback function registered using registerSocketCallback(), is expected to receive an event of type -* @ref SOCKET_MSG_SEND holding information containing the number of data bytes sent. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 u16Flags); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] pvSendBuffer - Pointer to a buffer holding data to be transmitted. - -@param [in] u16SendLength - The buffer size in bytes. - -@param [in] u16Flags - Not used in the current implementation. - -@pre - Sockets must be initialized using socketInit. \n - - For TCP Socket:\n - Must use a successfully connected Socket (so that the intended recipient address is known ahead of sending the data). - Hence this function is expected to be called after a successful socket connect operation(in client case or accept in the - the server case).\n - - For UDP Socket:\n - UDP sockets most commonly use @ref sendto function, where the destination address is defined. However, in-order to send outgoing data - using the @ref send function, at least one successful call must be made to the @ref sendto function a priori the consecutive calls to the @ref send function, - to ensure that the destination address is saved in the firmware. - -@see - socketInit - recv - sendto - socket - connect - accept - sendto - -@warning - u16SendLength must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. \n - Use a valid socket identifier through the a prior call to the @ref socket function. - Must use a valid buffer pointer. - Successful completion of a call to send() does not guarantee delivery of the message, - A negative return value indicates only locally-detected errors - - -@return - The function shall return @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise. -*/ -NMI_API sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 u16Flags); -/** @} */ -/** @defgroup SendToSocketFn sendto - * @ingroup SocketAPI -* Asynchronous sending function, used to send data on a UDP socket. -* Called by the application code when there is data required to be sent on a UDP socket handler. -* The application code is expected to receive data from a successful bounded socket node. -* The only difference between this function and the similar @ref send function, is the type of socket the data is received on. This function works -* only with UDP sockets. -* After the data is sent, the socket callback function registered using registerSocketCallback(), is expected to receive an event of type -* @ref SOCKET_MSG_SENDTO. -*/ - /**@{*/ -/*! -@fn \ - NMI_API sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] pvSendBuffer - Pointer to a buffer holding data to be transmitted. - A NULL value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@param [in] u16SendLength - The buffer size in bytes. It must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. - -@param [in] flags - Not used in the current implementation - -@param [in] pstrDestAddr - The destination address. - -@param [in] u8AddrLen - Destination address length in bytes. - Not used in the current implementation, only included for BSD compatibility. -@pre - Sockets must be initialized using socketInit. - -@see - socketInit - recvfrom - sendto - socket - connect - accept - send - -@warning - u16SendLength must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. \n - Use a valid socket (returned from socket ). - A valid buffer pointer must be used (not NULL). \n - Successful completion of a call to sendto() does not guarantee delivery of the message, - A negative return value indicates only locally-detected errors - -@return - The function returns @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise. -*/ -NMI_API sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen); -/** @} */ -/** @defgroup CloseSocketFn close - * @ingroup SocketAPI - * Synchronous close function, releases all the socket assigned resources. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 close(SOCKET sock); - -@param [in] sock - Socket ID, must hold a non negative value. - A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in. - -@pre - Sockets must be initialized through the call of the socketInit function. - @ref close is called only for valid socket identifiers created through the @ref socket function. - -@warning - If @ref close is called while there are still pending messages (sent or received ) they will be discarded. - -@see - socketInit - socket - -@return - The function returned @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise. -*/ -NMI_API sint8 close(SOCKET sock); - - -/** @} */ -/** @defgroup InetAddressFn nmi_inet_addr -* @ingroup SocketAPI -* Synchronous function which returns a BSD socket compliant Internet Protocol (IPv4) socket address. -* This IPv4 address in the input string parameter could either be specified as a host name, or as a numeric string representation like n.n.n.n known as the IPv4 dotted-decimal format -* (i.e. "192.168.10.1"). -* This function is used whenever an ip address needs to be set in the proper format -* (i.e. for the @ref tstrM2MIPConfig structure). -*/ - /**@{*/ -/*! -@fn \ - NMI_API uint32 nmi_inet_addr(char *pcIpAddr); - -@param [in] pcIpAddr - A null terminated string containing the IP address in IPv4 dotted-decimal address. - -@return - Unsigned 32-bit integer representing the IP address in Network byte order - (eg. "192.168.10.1" will be expressed as 0x010AA8C0). - -*/ -NMI_API uint32 nmi_inet_addr(char *pcIpAddr); - - -/** @} */ -/** @defgroup gethostbynameFn gethostbyname - * @ingroup SocketAPI -* Asynchronous DNS resolving function. This function use DNS to resolve a domain name into the corresponding IP address. -* A call to this function will cause a DNS request to be sent and the response will be delivered to the DNS callback function registered using registerSocketCallback() - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 gethostbyname(uint8 * pcHostName); - -@param [in] pcHostName - NULL terminated string containing the domain name for the remote host. - Its size must not exceed [HOSTNAME_MAX_SIZE](@ref HOSTNAME_MAX_SIZE). - -@see - registerSocketCallback - -@warning - Successful completion of a call to gethostbyname() does not guarantee success of the DNS request, - a negative return value indicates only locally-detected errors - -@return - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) - - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG) -*/ -NMI_API sint8 gethostbyname(uint8 * pcHostName); - - -/** @} */ -/** @defgroup sslEnableCertExpirationCheckFn sslEnableCertExpirationCheck - * @ingroup SocketAPI -* Configure the behavior of the SSL Library for Certificate Expiry Validation. - */ - /**@{*/ -/*! -@fn \ -NMI_API sint8 sslEnableCertExpirationCheck(tenuSslCertExpSettings enuValidationSetting); - -@param [in] enuValidationSetting - See @ref tenuSslCertExpSettings for details. - -@return - - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR) for successful operation and negative error code otherwise. - -@sa tenuSslCertExpSettings -*/ -NMI_API sint8 sslEnableCertExpirationCheck(tenuSslCertExpSettings enuValidationSetting); - - -/** @} */ - -/** @defgroup SetSocketOptionFn setsockopt - * @ingroup SocketAPI -*The setsockopt() function shall set the option specified by the option_name -* argument, at the protocol level specified by the level argument, to the value -* pointed to by the option_value argument for the socket specified by the socket argument. -* -*

Possible protocol level values supported are @ref SOL_SOCKET and @ref SOL_SSL_SOCKET. -* Possible options when the protocol level is @ref SOL_SOCKET :

-* -* -* -* -* -* -* -* -* -* -* -* -* -*
@ref SO_SET_UDP_SEND_CALLBACKEnable/Disable callback messages for sendto(). -* Since UDP is unreliable by default the user maybe interested (or not) in -* receiving a message of @ref SOCKET_MSG_SENDTO for each call of sendto(). -* Enabled if option value equals @ref TRUE, disabled otherwise.
@ref IP_ADD_MEMBERSHIPValid for UDP sockets. This option is used to receive frames sent to -* a multicast group. option_value shall be a pointer to Unsigned 32-bit -* integer containing the multicast IPv4 address.
@ref IP_DROP_MEMBERSHIPValid for UDP sockets. This option is used to stop receiving frames -* sent to a multicast group. option_value shall be a pointer to Unsigned -* 32-bit integer containing the multicast IPv4 address.
-*

Possible options when the protcol leve  is @ref SOL_SSL_SOCKET

-* -* -* -* -* -* -* -* -* -* -* -* -* -*
-* @ref SO_SSL_BYPASS_X509_VERIFAllow an opened SSL socket to bypass the X509 -* certificate verification process. It is highly recommended NOT to use -* this socket option in production software applications. The option is -* supported for debugging and testing purposes. The option value should be -* casted to int type and it is handled as a boolean flag.
@ref SO_SSL_SNISet the Server Name Indicator (SNI) for an SSL socket. The SNI is a -* null terminated string containing the server name associated with the -* connection. It must not exceed the size of @ref HOSTNAME_MAX_SIZE.
@ref SO_SSL_ENABLE_SESSION_CACHINGThis option allow the TLS to cache the session information for fast -* TLS session establishment in future connections using the TLS Protocol -* session resume features.
- */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 setsockopt(SOCKET socket, uint8 u8Level, uint8 option_name, - const void *option_value, uint16 u16OptionLen); - -@param [in] sock - Socket handler. - -@param [in] level - protocol level. See description above. - -@param [in] option_name - option to be set. See description above. - -@param [in] option_value - pointer to user provided value. - -@param [in] option_len - length of the option value in bytes. -@return - The function shall return \ref SOCK_ERR_NO_ERROR for successful operation - and a negative value (indicating the error) otherwise. -@sa SOL_SOCKET, SOL_SSL_SOCKET, IP_ADD_MEMBERSHIP, IP_DROP_MEMBERSHIP -*/ -NMI_API sint8 setsockopt(SOCKET socket, uint8 u8Level, uint8 option_name, - const void *option_value, uint16 u16OptionLen); - - -/** @} */ -/** @defgroup GetSocketOptionsFn getsockopt - * @ingroup SocketAPI - * Get socket options retrieves -* This Function isn't implemented yet but this is the form that will be released later. - */ - /**@{*/ -/*! -@fn \ - sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8 * pu8OptLen); - -@brief - -@param [in] sock - Socket Identifie. -@param [in] u8Level - The protocol level of the option. -@param [in] u8OptName - The u8OptName argument specifies a single option to get. -@param [out] pvOptValue - The pvOptValue argument contains pointer to a buffer containing the option value. -@param [out] pu8OptLen - Option value buffer length. -@return - The function shall return ZERO for successful operation and a negative value otherwise. -*/ -NMI_API sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8* pu8OptLen); -/** @} */ - -/**@}*/ -/** @defgroup PingFn m2m_ping_req - * @ingroup SocketAPI - * The function sends ping request to the given IP Address. - */ - /**@{*/ -/*! -@fn \ - NMI_API sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb); - -@param [in] u32DstIP - Target Destination IP Address for the ping request. It must be represented in Network byte order. - The function nmi_inet_addr could be used to translate the dotted decimal notation IP - to its Network bytes order integer represntative. - -@param [in] u8TTL - IP TTL value for the ping request. If set to ZERO, the dfault value SHALL be used. - -@param [in] fpPingCb - Callback will be called to deliver the ping statistics. - -@see nmi_inet_addr -@return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. -*/ -NMI_API sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb); -/**@}*/ - - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __SOCKET_H__ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/socket_buffer.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/socket_buffer.h deleted file mode 100644 index d93a7c8..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/include/socket_buffer.h +++ /dev/null @@ -1,94 +0,0 @@ -/** - * - * \file - * - * \brief BSD compatible socket interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifndef __SOCKET_BUFFER_H__ -#define __SOCKET_BUFFER_H__ - -#include "socket/include/socket.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define SOCKET_BUFFER_UDP_HEADER_SIZE (8) - -#if defined LIMITED_RAM_DEVICE -#define SOCKET_BUFFER_MTU (16u) -#define SOCKET_BUFFER_UDP_SIZE (SOCKET_BUFFER_UDP_HEADER_SIZE + 64u) -#define SOCKET_BUFFER_TCP_SIZE (64u) -#else -#ifdef ARDUINO -#define SOCKET_BUFFER_MTU (1446u) -#else -#define SOCKET_BUFFER_MTU (1400u) -#endif -#define SOCKET_BUFFER_UDP_SIZE (SOCKET_BUFFER_UDP_HEADER_SIZE + SOCKET_BUFFER_MTU) -#define SOCKET_BUFFER_TCP_SIZE (SOCKET_BUFFER_MTU) -#endif - -#define SOCKET_BUFFER_FLAG_CONNECTED (0x1 << 0) -#define SOCKET_BUFFER_FLAG_FULL (0x1 << 1) -#define SOCKET_BUFFER_FLAG_BIND (0x1 << 2) -#define SOCKET_BUFFER_FLAG_SPAWN (0x1 << 3) -#define SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS (16) -#define SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK (((uint32)0xFF) << SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS) -#define SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS (24) -#define SOCKET_BUFFER_FLAG_PARENT_SOCKET_MSK (((uint32)0xFF) << SOCKET_BUFFER_FLAG_PARENT_SOCKET_POS) - -/* Parent stored as parent+1, as socket 1 ID is 0. */ - -typedef struct{ - uint8 *buffer; - uint32 *flag; - uint32 *head; - uint32 *tail; -}tstrSocketBuffer; - -void socketBufferInit(void); -void socketBufferRegister(SOCKET socket, uint32 *flag, uint32 *head, uint32 *tail, uint8 *buffer); -void socketBufferUnregister(SOCKET socket); -void socketBufferCb(SOCKET sock, uint8 u8Msg, void *pvMsg); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __SOCKET_BUFFER_H__ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket.c deleted file mode 100644 index 877cc1a..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket.c +++ /dev/null @@ -1,1445 +0,0 @@ -/** - * - * \file - * - * \brief BSD compatible socket interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ -#include - -#include "bsp/include/nm_bsp.h" -#include "socket/include/socket.h" -#include "driver/source/m2m_hif.h" -#include "socket/source/socket_internal.h" -#include "driver/include/m2m_types.h" - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -MACROS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -#define TLS_RECORD_HEADER_LENGTH (5) -#define ETHERNET_HEADER_OFFSET (34) -#define ETHERNET_HEADER_LENGTH (14) -#define TCP_IP_HEADER_LENGTH (40) -#define UDP_IP_HEADER_LENGTH (28) - -#define IP_PACKET_OFFSET (ETHERNET_HEADER_LENGTH + ETHERNET_HEADER_OFFSET - M2M_HIF_HDR_OFFSET) - -#define TCP_TX_PACKET_OFFSET (IP_PACKET_OFFSET + TCP_IP_HEADER_LENGTH) -#define UDP_TX_PACKET_OFFSET (IP_PACKET_OFFSET + UDP_IP_HEADER_LENGTH) -#define SSL_TX_PACKET_OFFSET (TCP_TX_PACKET_OFFSET + TLS_RECORD_HEADER_LENGTH) - -#define SOCKET_REQUEST(reqID, reqArgs, reqSize, reqPayload, reqPayloadSize, reqPayloadOffset) \ - hif_send(M2M_REQ_GROUP_IP, reqID, reqArgs, reqSize, reqPayload, reqPayloadSize, reqPayloadOffset) - - -#define SSL_FLAGS_ACTIVE NBIT0 -#define SSL_FLAGS_BYPASS_X509 NBIT1 -#define SSL_FLAGS_2_RESERVD NBIT2 -#define SSL_FLAGS_3_RESERVD NBIT3 -#define SSL_FLAGS_CACHE_SESSION NBIT4 -#define SSL_FLAGS_NO_TX_COPY NBIT5 -#define SSL_FLAGS_CHECK_SNI NBIT6 - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -PRIVATE DATA TYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - - -/*! -* @brief -*/ -typedef struct{ - SOCKET sock; - uint8 u8Dummy; - uint16 u16SessionID; -}tstrCloseCmd; - - -/*! -* @brief -*/ -typedef struct{ - uint8 *pu8UserBuffer; - uint16 u16UserBufferSize; - uint16 u16SessionID; - uint16 u16DataOffset; - uint8 bIsUsed; - uint8 u8SSLFlags; - uint8 bIsRecvPending; -}tstrSocket; - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -GLOBALS -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -volatile sint8 gsockerrno; -volatile tstrSocket gastrSockets[MAX_SOCKET]; -volatile uint8 gu8OpCode; -volatile uint16 gu16BufferSize; -volatile uint16 gu16SessionID = 0; - -volatile tpfAppSocketCb gpfAppSocketCb; -volatile tpfAppResolveCb gpfAppResolveCb; -volatile uint8 gbSocketInit = 0; -volatile tpfPingCb gfpPingCb; - -/********************************************************************* -Function - Socket_ReadSocketData - -Description - Callback function used by the NMC1500 driver to deliver messages - for socket layer. - -Return - None. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 17 July 2012 -*********************************************************************/ -#ifdef ARDUINO -extern uint8 hif_small_xfer; -static uint32 u32Address; -static SOCKET sock_xfer; -static uint8 type_xfer; -static tstrSocketRecvMsg msg_xfer; -#endif -NMI_API void Socket_ReadSocketData(SOCKET sock, tstrSocketRecvMsg *pstrRecv,uint8 u8SocketMsg, - uint32 u32StartAddress,uint16 u16ReadCount) -{ - if((u16ReadCount > 0) && (gastrSockets[sock].pu8UserBuffer != NULL) && (gastrSockets[sock].u16UserBufferSize > 0) && (gastrSockets[sock].bIsUsed == 1)) - { -#ifdef ARDUINO - u32Address = u32StartAddress; -#else - uint32 u32Address = u32StartAddress; -#endif - uint16 u16Read; - sint16 s16Diff; - uint8 u8SetRxDone; -#ifdef ARDUINO - m2m_memcpy((uint8 *)&msg_xfer, (uint8 *)pstrRecv, sizeof(tstrSocketRecvMsg)); - msg_xfer.u16RemainingSize = u16ReadCount; -#else - pstrRecv->u16RemainingSize = u16ReadCount; -#endif - do - { - u8SetRxDone = 1; - u16Read = u16ReadCount; - s16Diff = u16Read - gastrSockets[sock].u16UserBufferSize; - if(s16Diff > 0) - { - u8SetRxDone = 0; - u16Read = gastrSockets[sock].u16UserBufferSize; -#ifdef ARDUINO - hif_small_xfer = 1; - sock_xfer = sock; - type_xfer = u8SocketMsg; -#endif - } - - if(hif_receive(u32Address, gastrSockets[sock].pu8UserBuffer, u16Read, u8SetRxDone) == M2M_SUCCESS) - { -#ifdef ARDUINO - msg_xfer.pu8Buffer = gastrSockets[sock].pu8UserBuffer; - msg_xfer.s16BufferSize = u16Read; - msg_xfer.u16RemainingSize -= u16Read; - - if (gpfAppSocketCb) - gpfAppSocketCb(sock,u8SocketMsg, &msg_xfer); - - u32Address += u16Read; -#else - pstrRecv->pu8Buffer = gastrSockets[sock].pu8UserBuffer; - pstrRecv->s16BufferSize = u16Read; - pstrRecv->u16RemainingSize -= u16Read; - - if (gpfAppSocketCb) - gpfAppSocketCb(sock,u8SocketMsg, pstrRecv); - - u16ReadCount -= u16Read; - u32Address += u16Read; - - if((!gastrSockets[sock].bIsUsed) && (u16ReadCount)) - { - M2M_DBG("Application Closed Socket While Rx Is not Complete\n"); - if(hif_receive(0, NULL, 0, 1) == M2M_SUCCESS) - M2M_DBG("hif_receive Success\n"); - else - M2M_DBG("hif_receive Fail\n"); - break; - } -#endif - } - else - { - M2M_INFO("(ERRR)Current <%d>\n", u16ReadCount); - break; - } -#ifdef ARDUINO - }while(0); -#else - }while(u16ReadCount != 0); -#endif - } -} -#ifdef ARDUINO -NMI_API void Socket_ReadSocketData_Small(void) -{ - if((msg_xfer.u16RemainingSize > 0) && (gastrSockets[sock_xfer].pu8UserBuffer != NULL) && (gastrSockets[sock_xfer].u16UserBufferSize > 0) && (gastrSockets[sock_xfer].bIsUsed == 1)) - { - uint16 u16Read; - sint16 s16Diff; - uint8 u8SetRxDone; - - //do - //{ - u8SetRxDone = 1; - u16Read = msg_xfer.u16RemainingSize; - s16Diff = u16Read - gastrSockets[sock_xfer].u16UserBufferSize; - if(s16Diff > 0) - { - /*Has to be subsequent transfer*/ - hif_small_xfer = 2; - u8SetRxDone = 0; - u16Read = gastrSockets[sock_xfer].u16UserBufferSize; - } - else - { - /*Last xfer, needed for UDP*/ - hif_small_xfer = 3; - } - if(hif_receive(u32Address, gastrSockets[sock_xfer].pu8UserBuffer, u16Read, u8SetRxDone) == M2M_SUCCESS) - { - msg_xfer.pu8Buffer = gastrSockets[sock_xfer].pu8UserBuffer; - msg_xfer.s16BufferSize = u16Read; - msg_xfer.u16RemainingSize -= u16Read; - - if (gpfAppSocketCb) - gpfAppSocketCb(sock_xfer,type_xfer, &msg_xfer); - - u32Address += u16Read; - } - else - { - M2M_INFO("(ERRR)Current <%d>\n", u16Read); - //break; - } - - if (hif_small_xfer == 3) - { - hif_small_xfer = 0; - hif_chip_sleep(); - } - - //}while(u16ReadCount != 0); - } -} -#endif -/********************************************************************* -Function - m2m_ip_cb - -Description - Callback function used by the NMC1000 driver to deliver messages - for socket layer. - -Return - None. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 17 July 2012 -*********************************************************************/ -static void m2m_ip_cb(uint8 u8OpCode, uint16 u16BufferSize,uint32 u32Address) -{ - if((u8OpCode == SOCKET_CMD_BIND) || (u8OpCode == SOCKET_CMD_SSL_BIND)) - { - tstrBindReply strBindReply; - tstrSocketBindMsg strBind; - - if(hif_receive(u32Address, (uint8*)&strBindReply, sizeof(tstrBindReply), 0) == M2M_SUCCESS) - { - strBind.status = strBindReply.s8Status; - if(gpfAppSocketCb) - gpfAppSocketCb(strBindReply.sock,SOCKET_MSG_BIND,&strBind); - } - } - else if(u8OpCode == SOCKET_CMD_LISTEN) - { - tstrListenReply strListenReply; - tstrSocketListenMsg strListen; - if(hif_receive(u32Address, (uint8*)&strListenReply, sizeof(tstrListenReply), 0) == M2M_SUCCESS) - { - strListen.status = strListenReply.s8Status; - if(gpfAppSocketCb) - gpfAppSocketCb(strListenReply.sock,SOCKET_MSG_LISTEN, &strListen); - } - } - else if(u8OpCode == SOCKET_CMD_ACCEPT) - { - tstrAcceptReply strAcceptReply; - tstrSocketAcceptMsg strAccept; - if(hif_receive(u32Address, (uint8*)&strAcceptReply, sizeof(tstrAcceptReply), 0) == M2M_SUCCESS) - { - if(strAcceptReply.sConnectedSock >= 0) - { - gastrSockets[strAcceptReply.sConnectedSock].u8SSLFlags = gastrSockets[strAcceptReply.sListenSock].u8SSLFlags; - gastrSockets[strAcceptReply.sConnectedSock].bIsUsed = 1; - gastrSockets[strAcceptReply.sConnectedSock].u16DataOffset = strAcceptReply.u16AppDataOffset - M2M_HIF_HDR_OFFSET; - - /* The session ID is used to distinguish different socket connections - by comparing the assigned session ID to the one reported by the firmware*/ - ++gu16SessionID; - if(gu16SessionID == 0) - ++gu16SessionID; - - gastrSockets[strAcceptReply.sConnectedSock].u16SessionID = gu16SessionID; - M2M_DBG("Socket %d session ID = %d\r\n",strAcceptReply.sConnectedSock , gu16SessionID ); - } - strAccept.sock = strAcceptReply.sConnectedSock; - strAccept.strAddr.sin_family = AF_INET; - strAccept.strAddr.sin_port = strAcceptReply.strAddr.u16Port; - strAccept.strAddr.sin_addr.s_addr = strAcceptReply.strAddr.u32IPAddr; - if(gpfAppSocketCb) - gpfAppSocketCb(strAcceptReply.sListenSock, SOCKET_MSG_ACCEPT, &strAccept); - } - } - else if((u8OpCode == SOCKET_CMD_CONNECT) || (u8OpCode == SOCKET_CMD_SSL_CONNECT)) - { - tstrConnectReply strConnectReply; - tstrSocketConnectMsg strConnMsg; - if(hif_receive(u32Address, (uint8*)&strConnectReply, sizeof(tstrConnectReply), 0) == M2M_SUCCESS) - { - strConnMsg.sock = strConnectReply.sock; - strConnMsg.s8Error = strConnectReply.s8Error; - if(strConnectReply.s8Error == SOCK_ERR_NO_ERROR) - { - gastrSockets[strConnectReply.sock].u16DataOffset = strConnectReply.u16AppDataOffset - M2M_HIF_HDR_OFFSET; - } - if(gpfAppSocketCb) - gpfAppSocketCb(strConnectReply.sock,SOCKET_MSG_CONNECT, &strConnMsg); - } - } - else if(u8OpCode == SOCKET_CMD_DNS_RESOLVE) - { - tstrDnsReply strDnsReply; - if(hif_receive(u32Address, (uint8*)&strDnsReply, sizeof(tstrDnsReply), 0) == M2M_SUCCESS) - { - if(gpfAppResolveCb) - gpfAppResolveCb((uint8*)strDnsReply.acHostName, strDnsReply.u32HostIP); - } - } - else if((u8OpCode == SOCKET_CMD_RECV) || (u8OpCode == SOCKET_CMD_RECVFROM) || (u8OpCode == SOCKET_CMD_SSL_RECV)) - { - SOCKET sock; - sint16 s16RecvStatus; - tstrRecvReply strRecvReply; - uint16 u16ReadSize; - tstrSocketRecvMsg strRecvMsg; - uint8 u8CallbackMsgID = SOCKET_MSG_RECV; - uint16 u16DataOffset; - - if(u8OpCode == SOCKET_CMD_RECVFROM) - u8CallbackMsgID = SOCKET_MSG_RECVFROM; - - /* Read RECV REPLY data structure. - */ - u16ReadSize = sizeof(tstrRecvReply); - if(hif_receive(u32Address, (uint8*)&strRecvReply, u16ReadSize, 0) == M2M_SUCCESS) - { - uint16 u16SessionID = 0; - - sock = strRecvReply.sock; - u16SessionID = strRecvReply.u16SessionID; - M2M_DBG("recv callback session ID = %d\r\n",u16SessionID); - - /* Reset the Socket RX Pending Flag. - */ - gastrSockets[sock].bIsRecvPending = 0; - - s16RecvStatus = NM_BSP_B_L_16(strRecvReply.s16RecvStatus); - u16DataOffset = NM_BSP_B_L_16(strRecvReply.u16DataOffset); - strRecvMsg.strRemoteAddr.sin_port = strRecvReply.strRemoteAddr.u16Port; - strRecvMsg.strRemoteAddr.sin_addr.s_addr = strRecvReply.strRemoteAddr.u32IPAddr; - - if(u16SessionID == gastrSockets[sock].u16SessionID) - { -#ifdef ARDUINO - if((s16RecvStatus > 0) && (s16RecvStatus < (sint32)u16BufferSize)) -#else - if((s16RecvStatus > 0) && (s16RecvStatus < u16BufferSize)) -#endif - { - /* Skip incoming bytes until reaching the Start of Application Data. - */ - u32Address += u16DataOffset; - - /* Read the Application data and deliver it to the application callback in - the given application buffer. If the buffer is smaller than the received data, - the data is passed to the application in chunks according to its buffer size. - */ - u16ReadSize = (uint16)s16RecvStatus; - Socket_ReadSocketData(sock, &strRecvMsg, u8CallbackMsgID, u32Address, u16ReadSize); - } - else - { - strRecvMsg.s16BufferSize = s16RecvStatus; - strRecvMsg.pu8Buffer = NULL; - if(gpfAppSocketCb) - gpfAppSocketCb(sock,u8CallbackMsgID, &strRecvMsg); - } - } - else - { - M2M_DBG("Discard recv callback %d %d \r\n",u16SessionID , gastrSockets[sock].u16SessionID); - if(u16ReadSize < u16BufferSize) - { - if(hif_receive(0, NULL, 0, 1) == M2M_SUCCESS) - M2M_DBG("hif_receive Success\n"); - else -#ifdef ARDUINO - { -#endif - M2M_DBG("hif_receive Fail\n"); -#ifdef ARDUINO - } -#endif - } - } - } - } - else if((u8OpCode == SOCKET_CMD_SEND) || (u8OpCode == SOCKET_CMD_SENDTO) || (u8OpCode == SOCKET_CMD_SSL_SEND)) - { - SOCKET sock; - sint16 s16Rcvd; - tstrSendReply strReply; - uint8 u8CallbackMsgID = SOCKET_MSG_SEND; - - if(u8OpCode == SOCKET_CMD_SENDTO) - u8CallbackMsgID = SOCKET_MSG_SENDTO; - - if(hif_receive(u32Address, (uint8*)&strReply, sizeof(tstrSendReply), 0) == M2M_SUCCESS) - { - uint16 u16SessionID = 0; - - sock = strReply.sock; - u16SessionID = strReply.u16SessionID; - M2M_DBG("send callback session ID = %d\r\n",u16SessionID); - - s16Rcvd = NM_BSP_B_L_16(strReply.s16SentBytes); - - if(u16SessionID == gastrSockets[sock].u16SessionID) - { - if(gpfAppSocketCb) - gpfAppSocketCb(sock,u8CallbackMsgID, &s16Rcvd); - } - else - { - M2M_DBG("Discard send callback %d %d \r\n",u16SessionID , gastrSockets[sock].u16SessionID); - } - } - } - else if(u8OpCode == SOCKET_CMD_PING) - { - tstrPingReply strPingReply; - if(hif_receive(u32Address, (uint8*)&strPingReply, sizeof(tstrPingReply), 1) == M2M_SUCCESS) - { - gfpPingCb = (void (*)(uint32 , uint32 , uint8))(uintptr_t)strPingReply.u32CmdPrivate; - if(gfpPingCb != NULL) - { - gfpPingCb(strPingReply.u32IPAddr, strPingReply.u32RTT, strPingReply.u8ErrorCode); - } - } - } -} -/********************************************************************* -Function - socketInit - -Description - -Return - None. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -void socketInit(void) -{ - if(gbSocketInit == 0) - { - m2m_memset((uint8*)gastrSockets, 0, MAX_SOCKET * sizeof(tstrSocket)); - hif_register_cb(M2M_REQ_GROUP_IP,m2m_ip_cb); - gbSocketInit = 1; - gu16SessionID = 0; - } -} -/********************************************************************* -Function - socketDeinit - -Description - -Return - None. - -Author - Samer Sarhan - -Version - 1.0 - -Date - 27 Feb 2015 -*********************************************************************/ -void socketDeinit(void) -{ - m2m_memset((uint8*)gastrSockets, 0, MAX_SOCKET * sizeof(tstrSocket)); - hif_register_cb(M2M_REQ_GROUP_IP, NULL); - gpfAppSocketCb = NULL; - gpfAppResolveCb = NULL; - gbSocketInit = 0; -} -/********************************************************************* -Function - registerSocketCallback - -Description - -Return - None. - -Author - Ahmed Ezzat - -Versio - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -void registerSocketCallback(tpfAppSocketCb pfAppSocketCb, tpfAppResolveCb pfAppResolveCb) -{ - gpfAppSocketCb = pfAppSocketCb; - gpfAppResolveCb = pfAppResolveCb; -} - -/********************************************************************* -Function - socket - -Description - Creates a socket. - -Return - - Negative value for error. - - ZERO or positive value as a socket ID if successful. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags) -{ - SOCKET sock = -1; - uint8 u8SockID; - uint8 u8Count; - volatile tstrSocket *pstrSock; - static volatile uint8 u8NextTcpSock = 0; - static volatile uint8 u8NextUdpSock = 0; - - /* The only supported family is the AF_INET for UDP and TCP transport layer protocols. */ - if(u16Domain == AF_INET) - { - if(u8Type == SOCK_STREAM) - { - for(u8Count = 0; u8Count < TCP_SOCK_MAX; u8Count ++) - { - u8SockID = u8NextTcpSock; - pstrSock = &gastrSockets[u8NextTcpSock]; - u8NextTcpSock = (u8NextTcpSock + 1) % TCP_SOCK_MAX; - if(!pstrSock->bIsUsed) - { - sock = (SOCKET)u8SockID; - break; - } - } - } - else if(u8Type == SOCK_DGRAM) - { - volatile tstrSocket *pastrUDPSockets = &gastrSockets[TCP_SOCK_MAX]; - for(u8Count = 0; u8Count < UDP_SOCK_MAX; u8Count ++) - { - u8SockID = u8NextUdpSock; - pstrSock = &pastrUDPSockets[u8NextUdpSock]; - u8NextUdpSock = (u8NextUdpSock + 1) % UDP_SOCK_MAX; - if(!pstrSock->bIsUsed) - { - sock = (SOCKET)(u8SockID + TCP_SOCK_MAX); - break; - } - } - } - - if(sock >= 0) - { - m2m_memset((uint8*)pstrSock, 0, sizeof(tstrSocket)); - pstrSock->bIsUsed = 1; - - /* The session ID is used to distinguish different socket connections - by comparing the assigned session ID to the one reported by the firmware*/ - ++gu16SessionID; - if(gu16SessionID == 0) - ++gu16SessionID; - - pstrSock->u16SessionID = gu16SessionID; - M2M_INFO("Socket %d session ID = %d\r\n",sock, gu16SessionID ); - - if(u8Flags & SOCKET_FLAGS_SSL) - { - tstrSSLSocketCreateCmd strSSLCreate; - strSSLCreate.sslSock = sock; - pstrSock->u8SSLFlags = SSL_FLAGS_ACTIVE | SSL_FLAGS_NO_TX_COPY; - SOCKET_REQUEST(SOCKET_CMD_SSL_CREATE, (uint8*)&strSSLCreate, sizeof(tstrSSLSocketCreateCmd), 0, 0, 0); - } - } - } - return sock; -} -/********************************************************************* -Function - bind - -Description - Request to bind a socket on a local address. - -Return - - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 5 June 2012 -*********************************************************************/ -sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen) -{ - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - if((pstrAddr != NULL) && (sock >= 0) && (gastrSockets[sock].bIsUsed == 1) && (u8AddrLen != 0)) - { - tstrBindCmd strBind; - uint8 u8CMD = SOCKET_CMD_BIND; - if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) - { - u8CMD = SOCKET_CMD_SSL_BIND; - } - - /* Build the bind request. */ - strBind.sock = sock; - m2m_memcpy((uint8 *)&strBind.strAddr, (uint8 *)pstrAddr, sizeof(tstrSockAddr)); - strBind.u16SessionID = gastrSockets[sock].u16SessionID; - - /* Send the request. */ - s8Ret = SOCKET_REQUEST(u8CMD, (uint8*)&strBind,sizeof(tstrBindCmd) , NULL , 0, 0); - if(s8Ret != SOCK_ERR_NO_ERROR) - { - s8Ret = SOCK_ERR_INVALID; - } - } - return s8Ret; -} -/********************************************************************* -Function - listen - -Description - - -Return - - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 5 June 2012 -*********************************************************************/ -sint8 listen(SOCKET sock, uint8 backlog) -{ - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - - if(sock >= 0 && (gastrSockets[sock].bIsUsed == 1)) - { - tstrListenCmd strListen; - - strListen.sock = sock; - strListen.u8BackLog = backlog; - strListen.u16SessionID = gastrSockets[sock].u16SessionID; - - s8Ret = SOCKET_REQUEST(SOCKET_CMD_LISTEN, (uint8*)&strListen, sizeof(tstrListenCmd), NULL, 0, 0); - if(s8Ret != SOCK_ERR_NO_ERROR) - { - s8Ret = SOCK_ERR_INVALID; - } - } - return s8Ret; -} -/********************************************************************* -Function - accept - -Description - -Return - - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 5 June 2012 -*********************************************************************/ -sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)addr; - (void)addrlen; -#endif - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - - if(sock >= 0 && (gastrSockets[sock].bIsUsed == 1) ) - { - s8Ret = SOCK_ERR_NO_ERROR; - } - return s8Ret; -} -/********************************************************************* -Function - connect - -Description - Connect to a remote TCP Server. - -Return - - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 5 June 2012 -*********************************************************************/ -#ifdef ARDUINO -sint8 connectSocket(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen) -#else -sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen) -#endif -{ - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - if((sock >= 0) && (pstrAddr != NULL) && (gastrSockets[sock].bIsUsed == 1) && (u8AddrLen != 0)) - { - tstrConnectCmd strConnect; - uint8 u8Cmd = SOCKET_CMD_CONNECT; - if((gastrSockets[sock].u8SSLFlags) & SSL_FLAGS_ACTIVE) - { - u8Cmd = SOCKET_CMD_SSL_CONNECT; - strConnect.u8SslFlags = gastrSockets[sock].u8SSLFlags; - } - strConnect.sock = sock; - m2m_memcpy((uint8 *)&strConnect.strAddr, (uint8 *)pstrAddr, sizeof(tstrSockAddr)); - - strConnect.u16SessionID = gastrSockets[sock].u16SessionID; - s8Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strConnect,sizeof(tstrConnectCmd), NULL, 0, 0); - if(s8Ret != SOCK_ERR_NO_ERROR) - { - s8Ret = SOCK_ERR_INVALID; - } - } - return s8Ret; -} -/********************************************************************* -Function - send - -Description - -Return - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 5 June 2012 -*********************************************************************/ -sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags) -{ -#ifdef ARDUINO - (void)flags; // Silence "unused" warning -#endif - sint16 s16Ret = SOCK_ERR_INVALID_ARG; - - if((sock >= 0) && (pvSendBuffer != NULL) && (u16SendLength <= SOCKET_BUFFER_MAX_LENGTH) && (gastrSockets[sock].bIsUsed == 1)) - { - uint16 u16DataOffset; - tstrSendCmd strSend; - uint8 u8Cmd; - - u8Cmd = SOCKET_CMD_SEND; - u16DataOffset = TCP_TX_PACKET_OFFSET; - - strSend.sock = sock; - strSend.u16DataSize = NM_BSP_B_L_16(u16SendLength); - strSend.u16SessionID = gastrSockets[sock].u16SessionID; - - if(sock >= TCP_SOCK_MAX) - { - u16DataOffset = UDP_TX_PACKET_OFFSET; - } - if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) - { - u8Cmd = SOCKET_CMD_SSL_SEND; - u16DataOffset = gastrSockets[sock].u16DataOffset; -#ifdef ARDUINO - extern uint32 nmdrv_firm_ver; - - if (nmdrv_firm_ver < M2M_MAKE_VERSION(19, 4, 0)) { - // firmware 19.3.0 and older only works with this specific offset - u16DataOffset = SSL_TX_PACKET_OFFSET; - } -#endif - } - - s16Ret = SOCKET_REQUEST(u8Cmd|M2M_REQ_DATA_PKT, (uint8*)&strSend, sizeof(tstrSendCmd), pvSendBuffer, u16SendLength, u16DataOffset); - if(s16Ret != SOCK_ERR_NO_ERROR) - { - s16Ret = SOCK_ERR_BUFFER_FULL; - } - } - return s16Ret; -} -/********************************************************************* -Function - sendto - -Description - -Return - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)flags; - (void)u8AddrLen; -#endif - sint16 s16Ret = SOCK_ERR_INVALID_ARG; - - if((sock >= 0) && (pvSendBuffer != NULL) && (u16SendLength <= SOCKET_BUFFER_MAX_LENGTH) && (gastrSockets[sock].bIsUsed == 1)) - { - if(gastrSockets[sock].bIsUsed) - { - tstrSendCmd strSendTo; - - m2m_memset((uint8*)&strSendTo, 0, sizeof(tstrSendCmd)); - - strSendTo.sock = sock; - strSendTo.u16DataSize = NM_BSP_B_L_16(u16SendLength); - strSendTo.u16SessionID = gastrSockets[sock].u16SessionID; - - if(pstrDestAddr != NULL) - { - struct sockaddr_in *pstrAddr; - pstrAddr = (void*)pstrDestAddr; - - strSendTo.strAddr.u16Family = pstrAddr->sin_family; - strSendTo.strAddr.u16Port = pstrAddr->sin_port; - strSendTo.strAddr.u32IPAddr = pstrAddr->sin_addr.s_addr; - } - s16Ret = SOCKET_REQUEST(SOCKET_CMD_SENDTO|M2M_REQ_DATA_PKT, (uint8*)&strSendTo, sizeof(tstrSendCmd), - pvSendBuffer, u16SendLength, UDP_TX_PACKET_OFFSET); - - if(s16Ret != SOCK_ERR_NO_ERROR) - { - s16Ret = SOCK_ERR_BUFFER_FULL; - } - } - } - return s16Ret; -} -/********************************************************************* -Function - recv - -Description - -Return - - -Author - Ahmed Ezzat - -Version - 1.0 - 2.0 9 April 2013 --> Add timeout for recv operation. - -Date - 5 June 2012 -*********************************************************************/ -sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec) -{ - sint16 s16Ret = SOCK_ERR_INVALID_ARG; - - if((sock >= 0) && (pvRecvBuf != NULL) && (u16BufLen != 0) && (gastrSockets[sock].bIsUsed == 1)) - { - s16Ret = SOCK_ERR_NO_ERROR; - gastrSockets[sock].pu8UserBuffer = (uint8*)pvRecvBuf; - gastrSockets[sock].u16UserBufferSize = u16BufLen; - - if(!gastrSockets[sock].bIsRecvPending) - { - tstrRecvCmd strRecv; - uint8 u8Cmd = SOCKET_CMD_RECV; - - gastrSockets[sock].bIsRecvPending = 1; - if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) - { - u8Cmd = SOCKET_CMD_SSL_RECV; - } - - /* Check the timeout value. */ - if(u32Timeoutmsec == 0) - strRecv.u32Timeoutmsec = 0xFFFFFFFF; - else - strRecv.u32Timeoutmsec = NM_BSP_B_L_32(u32Timeoutmsec); - strRecv.sock = sock; - strRecv.u16SessionID = gastrSockets[sock].u16SessionID; - - s16Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strRecv, sizeof(tstrRecvCmd), NULL , 0, 0); - if(s16Ret != SOCK_ERR_NO_ERROR) - { - s16Ret = SOCK_ERR_BUFFER_FULL; - } - } - } - return s16Ret; -} -/********************************************************************* -Function - close - -Description - -Return - None. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -sint8 close(SOCKET sock) -{ - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - M2M_INFO("Sock to delete <%d>\n", sock); - if(sock >= 0 && (gastrSockets[sock].bIsUsed == 1)) - { - uint8 u8Cmd = SOCKET_CMD_CLOSE; - tstrCloseCmd strclose; - strclose.sock = sock; - strclose.u16SessionID = gastrSockets[sock].u16SessionID; - - gastrSockets[sock].bIsUsed = 0; - gastrSockets[sock].u16SessionID =0; - - if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) - { - u8Cmd = SOCKET_CMD_SSL_CLOSE; - } - s8Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strclose, sizeof(tstrCloseCmd), NULL,0, 0); - if(s8Ret != SOCK_ERR_NO_ERROR) - { - s8Ret = SOCK_ERR_INVALID; - } - m2m_memset((uint8*)&gastrSockets[sock], 0, sizeof(tstrSocket)); - } - return s8Ret; -} -/********************************************************************* -Function - recvfrom - -Description - -Return - - -Author - Ahmed Ezzat - -Version - 1.0 - 2.0 9 April 2013 --> Add timeout for recv operation. - -Date - 5 June 2012 -*********************************************************************/ -sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec) -{ - sint16 s16Ret = SOCK_ERR_NO_ERROR; - if((sock >= 0) && (pvRecvBuf != NULL) && (u16BufLen != 0) && (gastrSockets[sock].bIsUsed == 1)) - { - if(gastrSockets[sock].bIsUsed) - { - s16Ret = SOCK_ERR_NO_ERROR; - gastrSockets[sock].pu8UserBuffer = (uint8*)pvRecvBuf; - gastrSockets[sock].u16UserBufferSize = u16BufLen; - - if(!gastrSockets[sock].bIsRecvPending) - { - tstrRecvCmd strRecv; - - gastrSockets[sock].bIsRecvPending = 1; - - /* Check the timeout value. */ - if(u32Timeoutmsec == 0) - strRecv.u32Timeoutmsec = 0xFFFFFFFF; - else - strRecv.u32Timeoutmsec = NM_BSP_B_L_32(u32Timeoutmsec); - strRecv.sock = sock; - strRecv.u16SessionID = gastrSockets[sock].u16SessionID; - - s16Ret = SOCKET_REQUEST(SOCKET_CMD_RECVFROM, (uint8*)&strRecv, sizeof(tstrRecvCmd), NULL , 0, 0); - if(s16Ret != SOCK_ERR_NO_ERROR) - { - s16Ret = SOCK_ERR_BUFFER_FULL; - } - } - } - } - else - { - s16Ret = SOCK_ERR_INVALID_ARG; - } - return s16Ret; -} -/********************************************************************* -Function - nmi_inet_addr - -Description - -Return - Unsigned 32-bit integer representing the IP address in Network - byte order. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -uint32 nmi_inet_addr(char *pcIpAddr) -{ - uint8 tmp; - uint32 u32IP = 0; - uint8 au8IP[4]; - uint8 c; - uint8 i, j; - - tmp = 0; - - for(i = 0; i < 4; ++i) - { - j = 0; - do - { - c = *pcIpAddr; - ++j; - if(j > 4) - { - return 0; - } - if(c == '.' || c == 0) - { - au8IP[i] = tmp; - tmp = 0; - } - else if(c >= '0' && c <= '9') - { - tmp = (tmp * 10) + (c - '0'); - } - else - { - return 0; - } - ++pcIpAddr; - } while(c != '.' && c != 0); - } - m2m_memcpy((uint8*)&u32IP, au8IP, 4); - return u32IP; -} -/********************************************************************* -Function - gethostbyname - -Description - -Return - None. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2012 -*********************************************************************/ -sint8 gethostbyname(uint8 * pcHostName) -{ - sint8 s8Err = SOCK_ERR_INVALID_ARG; - uint8 u8HostNameSize = (uint8)m2m_strlen(pcHostName); - if(u8HostNameSize <= HOSTNAME_MAX_SIZE) - { - s8Err = SOCKET_REQUEST(SOCKET_CMD_DNS_RESOLVE, (uint8*)pcHostName, u8HostNameSize + 1, NULL,0, 0); - } - return s8Err; -} -/********************************************************************* -Function - setsockopt - -Description - -Return - None. - -Author - Abdelrahman Diab - -Version - 1.0 - -Date - 9 September 2014 -*********************************************************************/ -static sint8 sslSetSockOpt(SOCKET sock, uint8 u8Opt, const void *pvOptVal, uint16 u16OptLen) -{ - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - if(sock < TCP_SOCK_MAX) - { - if(gastrSockets[sock].u8SSLFlags & SSL_FLAGS_ACTIVE) - { - if(u8Opt == SO_SSL_BYPASS_X509_VERIF) - { - int optVal = *((int*)pvOptVal); - if(optVal) - { - gastrSockets[sock].u8SSLFlags |= SSL_FLAGS_BYPASS_X509; - } - else - { - gastrSockets[sock].u8SSLFlags &= ~SSL_FLAGS_BYPASS_X509; - } - s8Ret = SOCK_ERR_NO_ERROR; - } - else if(u8Opt == SO_SSL_ENABLE_SESSION_CACHING) - { - int optVal = *((int*)pvOptVal); - if(optVal) - { - gastrSockets[sock].u8SSLFlags |= SSL_FLAGS_CACHE_SESSION; - } - else - { - gastrSockets[sock].u8SSLFlags &= ~SSL_FLAGS_CACHE_SESSION; - } - s8Ret = SOCK_ERR_NO_ERROR; - } - else if(u8Opt == SO_SSL_ENABLE_SNI_VALIDATION) - { - int optVal = *((int*)pvOptVal); - if(optVal) - { - gastrSockets[sock].u8SSLFlags |= SSL_FLAGS_CHECK_SNI; - } - else - { - gastrSockets[sock].u8SSLFlags &= ~SSL_FLAGS_CHECK_SNI; - } - s8Ret = SOCK_ERR_NO_ERROR; - } - else if(u8Opt == SO_SSL_SNI) - { - if(u16OptLen < HOSTNAME_MAX_SIZE) - { - uint8 *pu8SNI = (uint8*)pvOptVal; - tstrSSLSetSockOptCmd strCmd; - - strCmd.sock = sock; - strCmd.u16SessionID = gastrSockets[sock].u16SessionID; - strCmd.u8Option = u8Opt; - strCmd.u32OptLen = u16OptLen; - m2m_memcpy(strCmd.au8OptVal, pu8SNI, HOSTNAME_MAX_SIZE); - - if(SOCKET_REQUEST(SOCKET_CMD_SSL_SET_SOCK_OPT, (uint8*)&strCmd, sizeof(tstrSSLSetSockOptCmd), - 0, 0, 0) == M2M_ERR_MEM_ALLOC) - { - s8Ret = SOCKET_REQUEST(SOCKET_CMD_SSL_SET_SOCK_OPT | M2M_REQ_DATA_PKT, - (uint8*)&strCmd, sizeof(tstrSSLSetSockOptCmd), 0, 0, 0); - } - s8Ret = SOCK_ERR_NO_ERROR; - } - else - { - M2M_ERR("SNI Exceeds Max Length\n"); - } - } - else - { - M2M_ERR("Unknown SSL Socket Option %d\n",u8Opt); - } - } - else - { - M2M_ERR("Not SSL Socket\n"); - } - } - return s8Ret; -} -/********************************************************************* -Function - setsockopt - -Description - -Return - None. - -Author - Abdelrahman Diab - -Version - 1.0 - -Date - 9 September 2014 -*********************************************************************/ -sint8 setsockopt(SOCKET sock, uint8 u8Level, uint8 option_name, - const void *option_value, uint16 u16OptionLen) -{ - sint8 s8Ret = SOCK_ERR_INVALID_ARG; - if((sock >= 0) && (option_value != NULL) && (gastrSockets[sock].bIsUsed == 1)) - { - if(u8Level == SOL_SSL_SOCKET) - { - s8Ret = sslSetSockOpt(sock, option_name, option_value, u16OptionLen); - } - else - { - uint8 u8Cmd = SOCKET_CMD_SET_SOCKET_OPTION; - tstrSetSocketOptCmd strSetSockOpt; - strSetSockOpt.u8Option=option_name; - strSetSockOpt.sock = sock; - strSetSockOpt.u32OptionValue = *(uint32*)option_value; - strSetSockOpt.u16SessionID = gastrSockets[sock].u16SessionID; - - s8Ret = SOCKET_REQUEST(u8Cmd, (uint8*)&strSetSockOpt, sizeof(tstrSetSocketOptCmd), NULL,0, 0); - if(s8Ret != SOCK_ERR_NO_ERROR) - { - s8Ret = SOCK_ERR_INVALID; - } - } - } - return s8Ret; -} -/********************************************************************* -Function - getsockopt - -Description - -Return - None. - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 24 August 2014 -*********************************************************************/ -sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8* pu8OptLen) -{ -#ifdef ARDUINO - // Silence "unused" warning - (void)sock; - (void)u8Level; - (void)u8OptName; - (void)pvOptValue; - (void)pu8OptLen; -#endif - /* TBD */ - return M2M_SUCCESS; -} -/********************************************************************* -Function - m2m_ping_req - -Description - Send Ping request. - -Return - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - 4 June 2015 -*********************************************************************/ -sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb) -{ - sint8 s8Ret = M2M_ERR_INVALID_ARG; - - if((u32DstIP != 0) && (fpPingCb != NULL)) - { - tstrPingCmd strPingCmd; - - strPingCmd.u16PingCount = 1; - strPingCmd.u32DestIPAddr = u32DstIP; -#ifdef ARDUINO - strPingCmd.u32CmdPrivate = (uint32)(uintptr_t)(fpPingCb); -#else - strPingCmd.u32CmdPrivate = (uint32)(fpPingCb); -#endif - strPingCmd.u8TTL = u8TTL; - - s8Ret = SOCKET_REQUEST(SOCKET_CMD_PING, (uint8*)&strPingCmd, sizeof(tstrPingCmd), NULL, 0, 0); - } - return s8Ret; -} -/********************************************************************* -Function - sslEnableCertExpirationCheck - -Description - Enable/Disable TLS Certificate Expiration Check. - -Return - -Author - Ahmed Ezzat - -Version - 1.0 - -Date - -*********************************************************************/ -sint8 sslEnableCertExpirationCheck(tenuSslCertExpSettings enuValidationSetting) -{ - tstrSslCertExpSettings strSettings; - strSettings.u32CertExpValidationOpt = (uint32)enuValidationSetting; - return SOCKET_REQUEST(SOCKET_CMD_SSL_EXP_CHECK, (uint8*)&strSettings, sizeof(tstrSslCertExpSettings), NULL, 0, 0); -} \ No newline at end of file diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket_buffer.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket_buffer.c deleted file mode 100644 index d100558..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket_buffer.c +++ /dev/null @@ -1,232 +0,0 @@ -/** - * - * \file - * - * \brief BSD compatible socket interface. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#include -#include "socket/include/socket.h" -#include "driver/source/m2m_hif.h" -#include "socket/source/socket_internal.h" -#include "socket/include/socket_buffer.h" -#include "driver/include/m2m_periph.h" - -tstrSocketBuffer gastrSocketBuffer[MAX_SOCKET]; - -extern uint8 hif_small_xfer; - -void socketBufferInit(void) -{ - memset(gastrSocketBuffer, 0, sizeof(gastrSocketBuffer)); -} - -void socketBufferRegister(SOCKET socket, uint32 *flag, uint32 *head, uint32 *tail, uint8 *buffer) -{ - gastrSocketBuffer[socket].flag = flag; - gastrSocketBuffer[socket].head = head; - gastrSocketBuffer[socket].tail = tail; - gastrSocketBuffer[socket].buffer = buffer; -} - -void socketBufferUnregister(SOCKET socket) -{ - gastrSocketBuffer[socket].flag = 0; - gastrSocketBuffer[socket].head = 0; - gastrSocketBuffer[socket].tail = 0; - gastrSocketBuffer[socket].buffer = 0; -} - -void socketBufferCb(SOCKET sock, uint8 u8Msg, void *pvMsg) -{ - switch (u8Msg) { - /* Socket connected. */ - case SOCKET_MSG_CONNECT: - { - tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg *)pvMsg; - if (pstrConnect && pstrConnect->s8Error >= 0) { - recv(sock, gastrSocketBuffer[sock].buffer, SOCKET_BUFFER_MTU, 0); - *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_CONNECTED; - } else { - close(sock); - } - } - break; - - /* TCP Data receive. */ - case SOCKET_MSG_RECV: - { - // Network led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); - - tstrSocketRecvMsg *pstrRecv = (tstrSocketRecvMsg *)pvMsg; - if (pstrRecv && pstrRecv->s16BufferSize > 0) { - /* Protect against overflow. */ - if (*(gastrSocketBuffer[sock].head) + pstrRecv->s16BufferSize > SOCKET_BUFFER_TCP_SIZE) { - *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_FULL; - break; - } - - /* Add data size. */ - *(gastrSocketBuffer[sock].head) += pstrRecv->s16BufferSize; - - /* Buffer full, stop reception. */ - if (SOCKET_BUFFER_TCP_SIZE - *(gastrSocketBuffer[sock].head) < SOCKET_BUFFER_MTU) { - if (pstrRecv->u16RemainingSize != 0) { - *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_FULL; - } - } - else { - recv(sock, gastrSocketBuffer[sock].buffer + *(gastrSocketBuffer[sock].head), - SOCKET_BUFFER_MTU, 0); - } - } - /* Test EOF (Socket closed) condition for TCP socket. */ - else { - *(gastrSocketBuffer[sock].flag) &= ~SOCKET_BUFFER_FLAG_CONNECTED; - close(sock); - } - - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - } - break; - - /* UDP Data receive. */ - case SOCKET_MSG_RECVFROM: - { - // Network led ON (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); - - tstrSocketRecvMsg *pstrRecv = (tstrSocketRecvMsg *)pvMsg; - if (pstrRecv && pstrRecv->s16BufferSize > 0) { - - if (hif_small_xfer < 2) { - uint32 h = *(gastrSocketBuffer[sock].head); - uint8 *buf = gastrSocketBuffer[sock].buffer; - uint16 sz = pstrRecv->s16BufferSize + pstrRecv->u16RemainingSize; - - /* Store packet size. */ - buf[h++] = sz >> 8; - buf[h++] = sz; - - /* Store remote host port. */ - buf[h++] = pstrRecv->strRemoteAddr.sin_port; - buf[h++] = pstrRecv->strRemoteAddr.sin_port >> 8; - - /* Store remote host IP. */ - buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr >> 24; - buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr >> 16; - buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr >> 8; - buf[h++] = pstrRecv->strRemoteAddr.sin_addr.s_addr; - - /* Data received. */ - *(gastrSocketBuffer[sock].head) = h + pstrRecv->s16BufferSize; - } - else { - /* Data received. */ - *(gastrSocketBuffer[sock].head) += pstrRecv->s16BufferSize; - } - - /* Buffer full, stop reception. */ - if (SOCKET_BUFFER_UDP_SIZE - *(gastrSocketBuffer[sock].head) < SOCKET_BUFFER_MTU + SOCKET_BUFFER_UDP_HEADER_SIZE) { - if (pstrRecv->u16RemainingSize != 0) { - *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_FULL; - } - } - else { - if (hif_small_xfer && hif_small_xfer != 3) { - recvfrom(sock, gastrSocketBuffer[sock].buffer + *(gastrSocketBuffer[sock].head), - SOCKET_BUFFER_MTU, 0); - } - else { - recvfrom(sock, gastrSocketBuffer[sock].buffer + *(gastrSocketBuffer[sock].head) + SOCKET_BUFFER_UDP_HEADER_SIZE, - SOCKET_BUFFER_MTU, 0); - } - } - } - - // Network led OFF (rev A then rev B). - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); - m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); - } - break; - - /* Socket bind. */ - case SOCKET_MSG_BIND: - { - tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg *)pvMsg; - if (pstrBind && pstrBind->status == 0) { - *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_BIND; - /* TCP socket needs to enter Listen state. */ - if (sock < TCP_SOCK_MAX) { - listen(sock, 0); - } - /* UDP socket only needs to supply the receive buffer. */ - /* +8 is used to store size, port and IP of incoming data. */ - else { - recvfrom(sock, gastrSocketBuffer[sock].buffer + SOCKET_BUFFER_UDP_HEADER_SIZE, - SOCKET_BUFFER_MTU, 0); - } - } - } - break; - - /* Connect accept. */ - case SOCKET_MSG_ACCEPT: - { - tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg *)pvMsg; - if (pstrAccept && pstrAccept->sock >= 0) { - if (*(gastrSocketBuffer[sock].flag) & SOCKET_BUFFER_FLAG_SPAWN) { - /* One spawn connection already waiting, discard current one. */ - close(pstrAccept->sock); - } - else { - /* Use flag to store spawn TCP descriptor. */ - *(gastrSocketBuffer[sock].flag) &= ~SOCKET_BUFFER_FLAG_SPAWN_SOCKET_MSK; - *(gastrSocketBuffer[sock].flag) |= (((uint32)pstrAccept->sock) << SOCKET_BUFFER_FLAG_SPAWN_SOCKET_POS); - *(gastrSocketBuffer[sock].flag) |= SOCKET_BUFFER_FLAG_SPAWN; - } - } - } - break; - - } -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket_internal.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket_internal.h deleted file mode 100644 index 1904c23..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/socket/source/socket_internal.h +++ /dev/null @@ -1,71 +0,0 @@ -/** - * - * \file - * - * \brief BSD compatible socket interface internal types. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ -#ifndef __SOCKET_INTERNAL_H__ -#define __SOCKET_INTERNAL_H__ - - -#ifdef __cplusplus -extern "C" { -#endif - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -INCLUDES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -#include "socket/include/socket.h" -#include "socket/include/m2m_socket_host_if.h" - - -/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* -FUNCTION PROTOTYPES -*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ - -NMI_API void Socket_ReadSocketData(SOCKET sock, tstrSocketRecvMsg *pstrRecv,uint8 u8SocketMsg, - uint32 u32StartAddress,uint16 u16ReadCount); -#ifdef ARDUINO -NMI_API void Socket_ReadSocketData_Small(void); -#endif - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __SOCKET_H__ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/include/spi_flash.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/include/spi_flash.h deleted file mode 100644 index a85aa72..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/include/spi_flash.h +++ /dev/null @@ -1,233 +0,0 @@ -/** - * - * \file - * - * \brief WINC1500 SPI Flash. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/** \defgroup SPIFLASH Spi Flash - * @file spi_flash.h - * @brief This file describe SPI flash APIs, how to use it and limitations with each one. - * @section Example - * This example illustrates a complete guide of how to use these APIs. - * @code{.c} - #include "spi_flash.h" - - #define DATA_TO_REPLACE "THIS IS A NEW SECTOR IN FLASH" - - int main() - { - uint8 au8FlashContent[FLASH_SECTOR_SZ] = {0}; - uint32 u32FlashTotalSize = 0; - uint32 u32FlashOffset = 0; - - ret = m2m_wifi_download_mode(); - if(M2M_SUCCESS != ret) - { - printf("Unable to enter download mode\r\n"); - } - else - { - u32FlashTotalSize = spi_flash_get_size(); - } - - while((u32FlashTotalSize > u32FlashOffset) && (M2M_SUCCESS == ret)) - { - ret = spi_flash_read(au8FlashContent, u32FlashOffset, FLASH_SECTOR_SZ); - if(M2M_SUCCESS != ret) - { - printf("Unable to read SPI sector\r\n"); - break; - } - memcpy(au8FlashContent, DATA_TO_REPLACE, strlen(DATA_TO_REPLACE)); - - ret = spi_flash_erase(u32FlashOffset, FLASH_SECTOR_SZ); - if(M2M_SUCCESS != ret) - { - printf("Unable to erase SPI sector\r\n"); - break; - } - - ret = spi_flash_write(au8FlashContent, u32FlashOffset, FLASH_SECTOR_SZ); - if(M2M_SUCCESS != ret) - { - printf("Unable to write SPI sector\r\n"); - break; - } - u32FlashOffset += FLASH_SECTOR_SZ; - } - - if(M2M_SUCCESS == ret) - { - printf("Successful operations\r\n"); - } - else - { - printf("Failed operations\r\n"); - } - - while(1); - return M2M_SUCCESS; - } - * @endcode - */ - -#ifndef __SPI_FLASH_H__ -#define __SPI_FLASH_H__ -#include "common/include/nm_common.h" -#include "bus_wrapper/include/nm_bus_wrapper.h" -#include "driver/source/nmbus.h" -#include "driver/source/nmasic.h" - -#ifdef ARDUINO -#ifdef __cplusplus -extern "C" { -#endif -#endif - -/** - * @fn spi_flash_enable - * @brief Enable spi flash operations - * @version 1.0 - */ -sint8 spi_flash_enable(uint8 enable); -/** \defgroup SPIFLASHAPI Function - * @ingroup SPIFLASH - */ - - /** @defgroup SPiFlashGetFn spi_flash_get_size - * @ingroup SPIFLASHAPI - */ - /**@{*/ -/*! - * @fn uint32 spi_flash_get_size(void); - * @brief Returns with \ref uint32 value which is total flash size\n - * @note Returned value in Mb (Mega Bit). - * @return SPI flash size in case of success and a ZERO value in case of failure. - */ -uint32 spi_flash_get_size(void); - /**@}*/ - - /** @defgroup SPiFlashRead spi_flash_read - * @ingroup SPIFLASHAPI - */ - /**@{*/ -/*! - * @fn sint8 spi_flash_read(uint8 *, uint32, uint32); - * @brief Read a specified portion of data from SPI Flash.\n - * @param [out] pu8Buf - * Pointer to data buffer which will fill in with data in case of successful operation. - * @param [in] u32Addr - * Address (Offset) to read from at the SPI flash. - * @param [in] u32Sz - * Total size of data to be read in bytes - * @warning - * - Address (offset) plus size of data must not exceed flash size.\n - * - No firmware is required for reading from SPI flash.\n - * - In case of there is a running firmware, it is required to pause your firmware first - * before any trial to access SPI flash to avoid any racing between host and running firmware on bus using - * @ref m2m_wifi_download_mode - * @note - * - It is blocking function\n - * @sa m2m_wifi_download_mode, spi_flash_get_size - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - */ -sint8 spi_flash_read(uint8 *pu8Buf, uint32 u32Addr, uint32 u32Sz); - /**@}*/ - - /** @defgroup SPiFlashWrite spi_flash_write - * @ingroup SPIFLASHAPI - */ - /**@{*/ -/*! - * @fn sint8 spi_flash_write(uint8 *, uint32, uint32); - * @brief Write a specified portion of data to SPI Flash.\n - * @param [in] pu8Buf - * Pointer to data buffer which contains the required to be written. - * @param [in] u32Offset - * Address (Offset) to write at the SPI flash. - * @param [in] u32Sz - * Total number of size of data bytes - * @note - * - It is blocking function\n - * - It is user's responsibility to verify that data has been written successfully - * by reading data again and compare it with the original. - * @warning - * - Address (offset) plus size of data must not exceed flash size.\n - * - No firmware is required for writing to SPI flash.\n - * - In case of there is a running firmware, it is required to pause your firmware first - * before any trial to access SPI flash to avoid any racing between host and running firmware on bus using - * @ref m2m_wifi_download_mode. - * - Before writing to any section, it is required to erase it first. - * @sa m2m_wifi_download_mode, spi_flash_get_size, spi_flash_erase - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - - */ -sint8 spi_flash_write(uint8* pu8Buf, uint32 u32Offset, uint32 u32Sz); - /**@}*/ - - /** @defgroup SPiFlashErase spi_flash_erase - * @ingroup SPIFLASHAPI - */ - /**@{*/ -/*! - * @fn sint8 spi_flash_erase(uint32, uint32); - * @brief Erase a specified portion of SPI Flash.\n - * @param [in] u32Offset - * Address (Offset) to erase from the SPI flash. - * @param [in] u32Sz - * Size of SPI flash required to be erased. - * @note It is blocking function \n -* @warning -* - Address (offset) plus size of data must not exceed flash size.\n -* - No firmware is required for writing to SPI flash.\n - * - In case of there is a running firmware, it is required to pause your firmware first - * before any trial to access SPI flash to avoid any racing between host and running firmware on bus using - * @ref m2m_wifi_download_mode - * - It is blocking function\n - * @sa m2m_wifi_download_mode, spi_flash_get_size - * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise. - - */ -sint8 spi_flash_erase(uint32 u32Offset, uint32 u32Sz); - /**@}*/ -#ifdef ARDUINO -#ifdef __cplusplus -} -#endif -#endif -#endif //__SPI_FLASH_H__ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h deleted file mode 100644 index 3b0da53..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/include/spi_flash_map.h +++ /dev/null @@ -1,245 +0,0 @@ -/** - * - * \file - * - * \brief WINC1500 SPI Flash. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -/** -* @file spi_flash_map.h -* @brief This module contains spi flash CONTENT -* @author M.S.M -* @date 17 SEPT 2013 -* @version 1.0 -*/ -#ifndef __SPI_FLASH_MAP_H__ -#define __SPI_FLASH_MAP_H__ - -#define FLASH_MAP_VER_0 (0) -#define FLASH_MAP_VER_1 (1) -#define FLASH_MAP_VER_2 (2) -#define FLASH_MAP_VER_3 (3) - -#define FLASH_MAP_VERSION FLASH_MAP_VER_3 - -//#define DOWNLOAD_ROLLBACK -//#define OTA_GEN -#define _PROGRAM_POWER_SAVE_ - -/* =======*=======*=======*=======*======= - * General Sizes for Flash Memory - * =======*=======*=======*=======*======= - */ - -#define FLASH_START_ADDR (0UL) -/*! location :xxxK - * "S:xxxK" -means-> Size is :xxxK - */ - -/* - * Boot Firmware: which used to select which firmware to run - * - */ -#define M2M_BOOT_FIRMWARE_STARTING_ADDR (FLASH_START_ADDR) -#define M2M_BOOT_FIRMWARE_FLASH_SZ (FLASH_SECTOR_SZ) - -/* - * Control Section: which used by Boot firmware - * - */ -#define M2M_CONTROL_FLASH_OFFSET (M2M_BOOT_FIRMWARE_STARTING_ADDR + M2M_BOOT_FIRMWARE_FLASH_SZ) -#define M2M_CONTROL_FLASH_BKP_OFFSET (M2M_CONTROL_FLASH_OFFSET + FLASH_SECTOR_SZ) -#define M2M_CONTROL_FLASH_SEC_SZ (FLASH_SECTOR_SZ) -#define M2M_CONTROL_FLASH_TOTAL_SZ (FLASH_SECTOR_SZ * 2) - -/* - * LUT for PLL and TX Gain settings: - * - */ -#define M2M_PLL_FLASH_OFFSET (M2M_CONTROL_FLASH_OFFSET + M2M_CONTROL_FLASH_TOTAL_SZ) -#define M2M_PLL_FLASH_SZ (1024 * 1) -#define M2M_GAIN_FLASH_OFFSET (M2M_PLL_FLASH_OFFSET + M2M_PLL_FLASH_SZ) -#define M2M_GAIN_FLASH_SZ (M2M_CONFIG_SECT_TOTAL_SZ - M2M_PLL_FLASH_SZ) -#define M2M_CONFIG_SECT_TOTAL_SZ (FLASH_SECTOR_SZ) - -/* - * Certificate: - * - */ -#define M2M_TLS_ROOTCER_FLASH_OFFSET (M2M_PLL_FLASH_OFFSET + M2M_CONFIG_SECT_TOTAL_SZ) -#define M2M_TLS_ROOTCER_FLASH_SIZE (FLASH_SECTOR_SZ * 1) - -/* - * TLS Server Key Files - * - */ -#define M2M_TLS_SERVER_FLASH_OFFSET (M2M_TLS_ROOTCER_FLASH_OFFSET + M2M_TLS_ROOTCER_FLASH_SIZE) -#define M2M_TLS_SERVER_FLASH_SIZE (FLASH_SECTOR_SZ * 2) - -/* - * HTTP Files - * - */ -#define M2M_HTTP_MEM_FLASH_OFFSET (M2M_TLS_SERVER_FLASH_OFFSET + M2M_TLS_SERVER_FLASH_SIZE) -#define M2M_HTTP_MEM_FLASH_SZ (FLASH_SECTOR_SZ * 2) - -/* - * Saved Connection Parameters: - * - */ -#define M2M_CACHED_CONNS_FLASH_OFFSET (M2M_HTTP_MEM_FLASH_OFFSET + M2M_HTTP_MEM_FLASH_SZ) -#define M2M_CACHED_CONNS_FLASH_SZ (FLASH_SECTOR_SZ * 1) - -/* - * - * Common section size - */ - -#define M2M_COMMON_DATA_SEC \ - (\ - M2M_BOOT_FIRMWARE_FLASH_SZ + \ - M2M_CONTROL_FLASH_TOTAL_SZ + \ - M2M_CONFIG_SECT_TOTAL_SZ + \ - M2M_TLS_ROOTCER_FLASH_SIZE + \ - M2M_TLS_SERVER_FLASH_SIZE + \ - M2M_HTTP_MEM_FLASH_SZ + \ - M2M_CACHED_CONNS_FLASH_SZ \ - ) - -/* - * - * OTA image1 Offset - */ - -#define M2M_OTA_IMAGE1_OFFSET (M2M_CACHED_CONNS_FLASH_OFFSET + M2M_CACHED_CONNS_FLASH_SZ) -/* - * Firmware Offset - * - */ -#if (defined _FIRMWARE_)||(defined OTA_GEN) -#define M2M_FIRMWARE_FLASH_OFFSET (0UL) -#else -#if (defined DOWNLOAD_ROLLBACK) -#define M2M_FIRMWARE_FLASH_OFFSET (M2M_OTA_IMAGE2_OFFSET) -#else -#define M2M_FIRMWARE_FLASH_OFFSET (M2M_OTA_IMAGE1_OFFSET) -#endif -#endif -/* - * - * Firmware - */ -#define M2M_FIRMWARE_FLASH_SZ (236 * 1024UL) -/** - * - * OTA image Size - */ -#define OTA_IMAGE_SIZE (M2M_FIRMWARE_FLASH_SZ) -/** - * - * Flash Total size - */ -#define FLASH_IMAGE1_CONTENT_SZ (M2M_COMMON_DATA_SEC + OTA_IMAGE_SIZE) - -/** - * - * OTA image 2 offset - */ -#define M2M_OTA_IMAGE2_OFFSET (FLASH_IMAGE1_CONTENT_SZ) - -/* - * App(Cortus App 4M): App. which runs over firmware - * - */ -#define M2M_APP_4M_MEM_FLASH_SZ (FLASH_SECTOR_SZ * 16) -#define M2M_APP_4M_MEM_FLASH_OFFSET (FLASH_4M_TOTAL_SZ - M2M_APP_4M_MEM_FLASH_SZ) -#define M2M_APP_8M_MEM_FLASH_OFFSET (M2M_OTA_IMAGE2_OFFSET + OTA_IMAGE_SIZE) -#define M2M_APP_8M_MEM_FLASH_SZ (FLASH_SECTOR_SZ * 32) -#define M2M_APP_OTA_MEM_FLASH_OFFSET (M2M_APP_8M_MEM_FLASH_OFFSET + M2M_APP_8M_MEM_FLASH_SZ) - -/* Check if total size of content - * don't exceed total size of memory allowed - **/ -#if (M2M_COMMON_DATA_SEC + (OTA_IMAGE_SIZE *2)> FLASH_4M_TOTAL_SZ) -#error "Excced 4M Flash Size" -#endif /* (FLASH_CONTENT_SZ > FLASH_TOTAL_SZ) */ - - -#endif /* __SPI_FLASH_MAP_H__ */ diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/source/spi_flash.c b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/source/spi_flash.c deleted file mode 100644 index 12eff59..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/libraries/WiFi101/src/spi_flash/source/spi_flash.c +++ /dev/null @@ -1,770 +0,0 @@ -/** - * - * \file - * - * \brief WINC1500 SPI Flash. - * - * Copyright (c) 2016-2017 Atmel Corporation. All rights reserved. - * - * \asf_license_start - * - * \page License - * - * 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. The name of Atmel may not be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE - * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. - * - * \asf_license_stop - * - */ - -#ifdef PROFILING -#include "windows.h" -#endif -#include "spi_flash/include/spi_flash.h" -#define DUMMY_REGISTER (0x1084) - -#ifdef ARDUINO -#define u32(x) ((uint32)x) -#endif - -#define TIMEOUT (-1) /*MS*/ - -//#define DISABLE_UNSED_FLASH_FUNCTIONS - -#define FLASH_BLOCK_SIZE (32UL * 1024) -/*!> 16); - cmd[2] = (uint8)(u32FlashAdr >> 8); - cmd[3] = (uint8)(u32FlashAdr); - cmd[4] = 0xA5; - - ret += nm_write_reg(SPI_FLASH_DATA_CNT, u32Sz); -#ifdef ARDUINO - ret += nm_write_reg(SPI_FLASH_BUF1, u32(cmd[0])|u32(cmd[1]<<8)|u32(cmd[2]<<16)|u32(cmd[3]<<24)); -#else - ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]|(cmd[1]<<8)|(cmd[2]<<16)|(cmd[3]<<24)); -#endif - ret += nm_write_reg(SPI_FLASH_BUF2, cmd[4]); - ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x1f); - ret += nm_write_reg(SPI_FLASH_DMA_ADDR, u32MemAdr); - ret += nm_write_reg(SPI_FLASH_CMD_CNT, 5 | (1<<7)); - do - { - ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); - if(M2M_SUCCESS != ret) break; - } - while(val != 1); - - return ret; -} - -/** -* @fn spi_flash_sector_erase -* @brief Erase sector (4KB) -* @param[IN] u32FlashAdr -* Any memory address within the sector -* @return Status of execution -* @note Compatible with MX25L6465E and should be working with other types -* @author M. Abdelmawla -* @version 1.0 -*/ -static sint8 spi_flash_sector_erase(uint32 u32FlashAdr) -{ - uint8 cmd[4]; - uint32 val = 0; - sint8 ret = M2M_SUCCESS; - - cmd[0] = 0x20; - cmd[1] = (uint8)(u32FlashAdr >> 16); - cmd[2] = (uint8)(u32FlashAdr >> 8); - cmd[3] = (uint8)(u32FlashAdr); - - ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); -#ifdef ARDUINO - ret += nm_write_reg(SPI_FLASH_BUF1, u32(cmd[0])|u32(cmd[1]<<8)|u32(cmd[2]<<16)|u32(cmd[3]<<24)); -#else - ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]|(cmd[1]<<8)|(cmd[2]<<16)|(cmd[3]<<24)); -#endif - ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x0f); - ret += nm_write_reg(SPI_FLASH_DMA_ADDR, 0); - ret += nm_write_reg(SPI_FLASH_CMD_CNT, 4 | (1<<7)); - do - { - ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); - if(M2M_SUCCESS != ret) break; - } - while(val != 1); - - return ret; -} - -/** -* @fn spi_flash_write_enable -* @brief Send write enable command to SPI flash -* @return Status of execution -* @note Compatible with MX25L6465E and should be working with other types -* @author M. Abdelmawla -* @version 1.0 -*/ -static sint8 spi_flash_write_enable(void) -{ - uint8 cmd[1]; - uint32 val = 0; - sint8 ret = M2M_SUCCESS; - - cmd[0] = 0x06; - - ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); - ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]); - ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x01); - ret += nm_write_reg(SPI_FLASH_DMA_ADDR, 0); - ret += nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1<<7)); - do - { - ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); - if(M2M_SUCCESS != ret) break; - } - while(val != 1); - - return ret; -} - -/** -* @fn spi_flash_write_disable -* @brief Send write disable command to SPI flash -* @note Compatible with MX25L6465E and should be working with other types -* @author M. Abdelmawla -* @version 1.0 -*/ -static sint8 spi_flash_write_disable(void) -{ - uint8 cmd[1]; - uint32 val = 0; - sint8 ret = M2M_SUCCESS; - cmd[0] = 0x04; - - ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); - ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]); - ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x01); - ret += nm_write_reg(SPI_FLASH_DMA_ADDR, 0); - ret += nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1<<7)); - do - { - ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); - if(M2M_SUCCESS != ret) break; - } - while(val != 1); - - return ret; -} - -/** -* @fn spi_flash_page_program -* @brief Write data (less than page size) from cortus memory to SPI flash -* @param[IN] u32MemAdr -* Cortus data address. It must be set to its AHB access address -* @param[IN] u32FlashAdr -* Address to write to at the SPI flash -* @param[IN] u32Sz -* Data size -* @note Compatible with MX25L6465E and should be working with other types -* @author M. Abdelmawla -* @version 1.0 -*/ -static sint8 spi_flash_page_program(uint32 u32MemAdr, uint32 u32FlashAdr, uint32 u32Sz) -{ - uint8 cmd[4]; - uint32 val = 0; - sint8 ret = M2M_SUCCESS; - - cmd[0] = 0x02; - cmd[1] = (uint8)(u32FlashAdr >> 16); - cmd[2] = (uint8)(u32FlashAdr >> 8); - cmd[3] = (uint8)(u32FlashAdr); - - ret += nm_write_reg(SPI_FLASH_DATA_CNT, 0); -#ifdef ARDUINO - ret += nm_write_reg(SPI_FLASH_BUF1, u32(cmd[0])|u32(cmd[1]<<8)|u32(cmd[2]<<16)|u32(cmd[3]<<24)); -#else - ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]|(cmd[1]<<8)|(cmd[2]<<16)|(cmd[3]<<24)); -#endif - ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x0f); - ret += nm_write_reg(SPI_FLASH_DMA_ADDR, u32MemAdr); - ret += nm_write_reg(SPI_FLASH_CMD_CNT, 4 | (1<<7) | ((u32Sz & 0xfffff) << 8)); - do - { - ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)&val); - if(M2M_SUCCESS != ret) break; - } - while(val != 1); - - return ret; -} - -/** -* @fn spi_flash_read_internal -* @brief Read from data from SPI flash -* @param[OUT] pu8Buf -* Pointer to data buffer -* @param[IN] u32Addr -* Address to read from at the SPI flash -* @param[IN] u32Sz -* Data size -* @note Data size must be < 64KB (limitation imposed by the bus wrapper) -* @author M. Abdelmawla -* @version 1.0 -*/ -static sint8 spi_flash_read_internal(uint8 *pu8Buf, uint32 u32Addr, uint32 u32Sz) -{ - sint8 ret = M2M_SUCCESS; - /* read size must be < 64KB */ - ret = spi_flash_load_to_cortus_mem(HOST_SHARE_MEM_BASE, u32Addr, u32Sz); - if(M2M_SUCCESS != ret) goto ERR; - ret = nm_read_block(HOST_SHARE_MEM_BASE, pu8Buf, u32Sz); -ERR: - return ret; -} - -/** -* @fn spi_flash_pp -* @brief Program data of size less than a page (256 bytes) at the SPI flash -* @param[IN] u32Offset -* Address to write to at the SPI flash -* @param[IN] pu8Buf -* Pointer to data buffer -* @param[IN] u32Sz -* Data size -* @return Status of execution -* @author M. Abdelmawla -* @version 1.0 -*/ -static sint8 spi_flash_pp(uint32 u32Offset, uint8 *pu8Buf, uint16 u16Sz) -{ - sint8 ret = M2M_SUCCESS; - uint8 tmp; - spi_flash_write_enable(); - /* use shared packet memory as temp mem */ - ret += nm_write_block(HOST_SHARE_MEM_BASE, pu8Buf, u16Sz); - ret += spi_flash_page_program(HOST_SHARE_MEM_BASE, u32Offset, u16Sz); - ret += spi_flash_read_status_reg(&tmp); - do - { - if(ret != M2M_SUCCESS) goto ERR; - ret += spi_flash_read_status_reg(&tmp); - }while(tmp & 0x01); - ret += spi_flash_write_disable(); -ERR: - return ret; -} - -/** -* @fn spi_flash_rdid -* @brief Read SPI Flash ID -* @return SPI FLash ID -* @author M.S.M -* @version 1.0 -*/ -static uint32 spi_flash_rdid(void) -{ - unsigned char cmd[1]; - uint32 reg = 0; - uint32 cnt = 0; - sint8 ret = M2M_SUCCESS; - - cmd[0] = 0x9f; - - ret += nm_write_reg(SPI_FLASH_DATA_CNT, 4); - ret += nm_write_reg(SPI_FLASH_BUF1, cmd[0]); - ret += nm_write_reg(SPI_FLASH_BUF_DIR, 0x1); - ret += nm_write_reg(SPI_FLASH_DMA_ADDR, DUMMY_REGISTER); - ret += nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1<<7)); - do - { - ret += nm_read_reg_with_ret(SPI_FLASH_TR_DONE, (uint32 *)®); - if(M2M_SUCCESS != ret) break; - if(++cnt > 500) - { - ret = M2M_ERR_INIT; - break; - } - } - while(reg != 1); - reg = (M2M_SUCCESS == ret)?(nm_read_reg(DUMMY_REGISTER)):(0); - M2M_PRINT("Flash ID %x \n",(unsigned int)reg); - return reg; -} - -/** -* @fn spi_flash_unlock -* @brief Unlock SPI Flash -* @author M.S.M -* @version 1.0 -*/ -#if 0 -static void spi_flash_unlock(void) -{ - uint8 tmp; - tmp = spi_flash_read_security_reg(); - spi_flash_clear_security_flags(); - if(tmp & 0x80) - { - spi_flash_write_enable(); - spi_flash_gang_unblock(); - } -} -#endif -static void spi_flash_enter_low_power_mode(void) { - volatile unsigned long tmp; - unsigned char* cmd = (unsigned char*) &tmp; - - cmd[0] = 0xb9; - - nm_write_reg(SPI_FLASH_DATA_CNT, 0); - nm_write_reg(SPI_FLASH_BUF1, cmd[0]); - nm_write_reg(SPI_FLASH_BUF_DIR, 0x1); - nm_write_reg(SPI_FLASH_DMA_ADDR, 0); - nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1 << 7)); - while(nm_read_reg(SPI_FLASH_TR_DONE) != 1); -} - - -static void spi_flash_leave_low_power_mode(void) { - volatile unsigned long tmp; - unsigned char* cmd = (unsigned char*) &tmp; - - cmd[0] = 0xab; - - nm_write_reg(SPI_FLASH_DATA_CNT, 0); - nm_write_reg(SPI_FLASH_BUF1, cmd[0]); - nm_write_reg(SPI_FLASH_BUF_DIR, 0x1); - nm_write_reg(SPI_FLASH_DMA_ADDR, 0); - nm_write_reg(SPI_FLASH_CMD_CNT, 1 | (1 << 7)); - while(nm_read_reg(SPI_FLASH_TR_DONE) != 1); -} -/*********************************************/ -/* GLOBAL FUNCTIONS */ -/*********************************************/ -/** - * @fn spi_flash_enable - * @brief Enable spi flash operations - * @author M. Abdelmawla - * @version 1.0 - */ -sint8 spi_flash_enable(uint8 enable) -{ - sint8 s8Ret = M2M_SUCCESS; - if(REV(nmi_get_chipid()) >= REV_3A0) { - uint32 u32Val; - - /* Enable pinmux to SPI flash. */ - s8Ret = nm_read_reg_with_ret(0x1410, &u32Val); - if(s8Ret != M2M_SUCCESS) { - goto ERR1; - } - /* GPIO15/16/17/18 */ - u32Val &= ~((0x7777ul) << 12); - u32Val |= ((0x1111ul) << 12); - nm_write_reg(0x1410, u32Val); - if(enable) { - spi_flash_leave_low_power_mode(); - } else { - spi_flash_enter_low_power_mode(); - } - /* Disable pinmux to SPI flash to minimize leakage. */ - u32Val &= ~((0x7777ul) << 12); - u32Val |= ((0x0010ul) << 12); - nm_write_reg(0x1410, u32Val); - } -ERR1: - return s8Ret; -} -/** -* @fn spi_flash_read -* @brief Read from data from SPI flash -* @param[OUT] pu8Buf -* Pointer to data buffer -* @param[IN] u32offset -* Address to read from at the SPI flash -* @param[IN] u32Sz -* Data size -* @return Status of execution -* @note Data size is limited by the SPI flash size only -* @author M. Abdelmawla -* @version 1.0 -*/ -sint8 spi_flash_read(uint8 *pu8Buf, uint32 u32offset, uint32 u32Sz) -{ - sint8 ret = M2M_SUCCESS; - if(u32Sz > FLASH_BLOCK_SIZE) - { - do - { - ret = spi_flash_read_internal(pu8Buf, u32offset, FLASH_BLOCK_SIZE); - if(M2M_SUCCESS != ret) goto ERR; - u32Sz -= FLASH_BLOCK_SIZE; - u32offset += FLASH_BLOCK_SIZE; - pu8Buf += FLASH_BLOCK_SIZE; - } while(u32Sz > FLASH_BLOCK_SIZE); - } - - ret = spi_flash_read_internal(pu8Buf, u32offset, u32Sz); - -ERR: - return ret; -} - -/** -* @fn spi_flash_write -* @brief Proram SPI flash -* @param[IN] pu8Buf -* Pointer to data buffer -* @param[IN] u32Offset -* Address to write to at the SPI flash -* @param[IN] u32Sz -* Data size -* @return Status of execution -* @author M. Abdelmawla -* @version 1.0 -*/ -sint8 spi_flash_write(uint8* pu8Buf, uint32 u32Offset, uint32 u32Sz) -{ -#ifdef PROFILING - uint32 t1 = 0; - uint32 percent =0; - uint32 tpercent =0; -#endif - sint8 ret = M2M_SUCCESS; - uint32 u32wsz; - uint32 u32off; - uint32 u32Blksz; - u32Blksz = FLASH_PAGE_SZ; - u32off = u32Offset % u32Blksz; -#ifdef PROFILING - tpercent = (u32Sz/u32Blksz)+((u32Sz%u32Blksz)>0); - t1 = GetTickCount(); - M2M_PRINT(">Start programming...\r\n"); -#endif - if(u32Sz<=0) - { - M2M_ERR("Data size = %d",(int)u32Sz); - ret = M2M_ERR_FAIL; - goto ERR; - } - - if (u32off)/*first part of data in the address page*/ - { - u32wsz = u32Blksz - u32off; - if(spi_flash_pp(u32Offset, pu8Buf, (uint16)BSP_MIN(u32Sz, u32wsz))!=M2M_SUCCESS) - { - ret = M2M_ERR_FAIL; - goto ERR; - } - if (u32Sz < u32wsz) goto EXIT; - pu8Buf += u32wsz; - u32Offset += u32wsz; - u32Sz -= u32wsz; - } - while (u32Sz > 0) - { - u32wsz = BSP_MIN(u32Sz, u32Blksz); - - /*write complete page or the remaining data*/ - if(spi_flash_pp(u32Offset, pu8Buf, (uint16)u32wsz)!=M2M_SUCCESS) - { - ret = M2M_ERR_FAIL; - goto ERR; - } - pu8Buf += u32wsz; - u32Offset += u32wsz; - u32Sz -= u32wsz; -#ifdef PROFILING - percent++; - printf("\r>Complete Percentage = %d%%.\r",((percent*100)/tpercent)); -#endif - } -EXIT: -#ifdef PROFILING - M2M_PRINT("\rDone\t\t\t\t\t\t"); - M2M_PRINT("\n#Programming time = %f sec\n\r",(GetTickCount() - t1)/1000.0); -#endif -ERR: - return ret; -} - -/** -* @fn spi_flash_erase -* @brief Erase from data from SPI flash -* @param[IN] u32Offset -* Address to write to at the SPI flash -* @param[IN] u32Sz -* Data size -* @return Status of execution -* @note Data size is limited by the SPI flash size only -* @author M. Abdelmawla -* @version 1.0 -*/ -sint8 spi_flash_erase(uint32 u32Offset, uint32 u32Sz) -{ - uint32 i = 0; - sint8 ret = M2M_SUCCESS; - uint8 tmp = 0; -#ifdef PROFILING - uint32 t; - t = GetTickCount(); -#endif - M2M_PRINT("\r\n>Start erasing...\r\n"); - for(i = u32Offset; i < (u32Sz +u32Offset); i += (16*FLASH_PAGE_SZ)) - { - ret += spi_flash_write_enable(); - ret += spi_flash_read_status_reg(&tmp); - ret += spi_flash_sector_erase(i + 10); - ret += spi_flash_read_status_reg(&tmp); - do - { - if(ret != M2M_SUCCESS) goto ERR; - ret += spi_flash_read_status_reg(&tmp); - }while(tmp & 0x01); - - } - M2M_PRINT("Done\r\n"); -#ifdef PROFILING - M2M_PRINT("#Erase time = %f sec\n", (GetTickCount()-t)/1000.0); -#endif -ERR: - return ret; -} - -/** -* @fn spi_flash_get_size -* @brief Get size of SPI Flash -* @return Size of Flash -* @author M.S.M -* @version 1.0 -*/ -uint32 spi_flash_get_size(void) -{ - uint32 u32FlashId = 0, u32FlashPwr = 0; - static uint32 gu32InernalFlashSize= 0; - - if(!gu32InernalFlashSize) - { - u32FlashId = spi_flash_rdid();//spi_flash_probe(); - if(u32FlashId != 0xffffffff) - { - /*flash size is the third byte from the FLASH RDID*/ - u32FlashPwr = ((u32FlashId>>16)&0xff) - 0x11; /*2MBIT is the min*/ - /*That number power 2 to get the flash size*/ - gu32InernalFlashSize = 1< -#include -#include "config.h" -#include -#include "watchdog.h" -#include "rtc.h" -#include "transmit.h" - -#ifdef HEATSEEK_FEATHER_WIFI_WICED -char const* get_encryption_str(int32_t enc_type); -#endif - -CONFIG_union CONFIG; -static DHT dht(DHT_DATA, DHT22); - -void write_config() { - File config_file; - - if (config_file = SD.open("config.bin", FILE_WRITE | O_TRUNC)) { - config_file.write(CONFIG.raw, sizeof(CONFIG)); - config_file.close(); - } else { - Serial.println("unable to update config"); - while(true); // watchdog will reboot - } -} - -bool read_config() { - File config_file; - bool success = false; - - if (config_file = SD.open("config.bin", FILE_READ)) { - int read_size = config_file.read(CONFIG.raw, sizeof(CONFIG)); - - if (sizeof(CONFIG) == read_size) { - Serial.print("Version from file: "); - Serial.print(CONFIG.data.version); - Serial.print("; expected version: "); - Serial.println(CONFIG_VERSION); - if (CONFIG.data.version == CONFIG_VERSION) { - Serial.println("config loaded"); - success = true; - } else { - Serial.println("incorrect config version"); - } - } else { - Serial.print("config incorrect size - expected: "); - Serial.print(sizeof(CONFIG)); - Serial.print(", got: "); - Serial.println(read_size); - } - - config_file.close(); - } else { - Serial.println("unable to read config"); - } - - return success; -} - -void set_default_config() { - CONFIG.data.version = CONFIG_VERSION; - CONFIG.data.reading_interval_s = 5 * 60; - CONFIG.data.cell_configured = 0; - CONFIG.data.wifi_configured = 0; - CONFIG.data.temperature_offset_f = 0.0; - - strcpy(CONFIG.data.hub_id, "featherhub"); - - strcpy(CONFIG.data.endpoint_domain, "relay.heatseek.org"); - strcpy(CONFIG.data.endpoint_path, "/temperatures"); - CONFIG.data.endpoint_configured = 1; -} - -int read_input_until_newline(char *message, char *buffer) { - int i = 0; - bool reached_newline = false; - - while (true) { - Serial.println(message); - - while (Serial.available()) { - char c = Serial.read(); - if (c == '\n') { -// Serial.println("done setting"); - reached_newline = true; - break; - } else { - buffer[i++] = c; - } - } - if (reached_newline) break; - - watchdog_feed(); - delay(2000); - } - - return i; -} - -void print_menu() { - Serial.println("-------------------------------------"); - Serial.println("[?] Print this menu"); - Serial.println("[t] Set RTC"); - Serial.println("[r] Set reading interval"); - Serial.println("[q] Clear reading transmission queue"); - Serial.println("[v] Calibrate temperature sensor"); - #ifdef TRANSMITTER_WIFI - Serial.println("[w] Setup wifi"); - Serial.println("[a] List nearby access points"); - #endif - Serial.println("[i] Setup Cell ID"); - Serial.println("[e] Setup API Endpoint"); - Serial.println("[p] Print config"); - Serial.println("[d] Reset config"); - Serial.println("[s] Exit config"); -} - -void print_config_info() { - Serial.println("-------------------------------------"); - Serial.println("Current config:"); - - #ifdef TRANSMITTER_WIFI - if (CONFIG.data.wifi_configured) { - Serial.print("wifi ssid: "); - Serial.print(CONFIG.data.wifi_ssid); - Serial.print(", wifi pass: "); - Serial.print(CONFIG.data.wifi_pass); - } else { - Serial.print("Wifi not configured"); - } - - Serial.println(); - #endif - - if (CONFIG.data.cell_configured) { - Serial.print("hub id: "); - Serial.print(CONFIG.data.hub_id); - Serial.print(", cell id: "); - Serial.print(CONFIG.data.cell_id); - } else { - Serial.print("cell id not configured"); - } - Serial.println(); - - if (CONFIG.data.endpoint_configured) { - Serial.print("endpoint: "); - Serial.print(CONFIG.data.endpoint_domain); - Serial.print(CONFIG.data.endpoint_path); - } else { - Serial.print("endpoint not configured"); - } - Serial.println(); - - Serial.print("reading_interval (seconds): "); - Serial.println(CONFIG.data.reading_interval_s); -} - -void enter_configuration() { - print_menu(); - - while(true) { - char command = Serial.read(); - while(Serial.available()) { Serial.read(); } - - switch (command) { - case '?': { - print_menu(); - break; - } - case 't': { - rtc_set(); - print_menu(); - break; - } - case 'q': { - clear_queued_transmissions(); - print_menu(); - break; - } - case 'r': { - char buffer[200]; - int length; - - length = read_input_until_newline("Enter Reading interval in seconds", buffer); - buffer[length] = '\0'; - CONFIG.data.reading_interval_s = strtol(buffer, NULL, 0); - - write_config(); - - update_last_reading_time(0); // take initial reading after configuration - clear_queued_transmissions(); // clear transmission queue - - Serial.println("Reading interval Configured"); - print_config_info(); - print_menu(); - break; - } -#ifdef TRANSMITTER_WIFI - case 'w': { - char buffer[200]; - int length; - - length = read_input_until_newline("Enter WiFi SSID", buffer); - buffer[length] = '\0'; - strcpy(CONFIG.data.wifi_ssid, buffer); - - length = read_input_until_newline("Enter WiFi password", buffer); - buffer[length] = '\0'; - strcpy(CONFIG.data.wifi_pass, buffer); - - CONFIG.data.wifi_configured = 1; - write_config(); - force_wifi_reconnect(); - - Serial.println("Wifi Configured"); - print_config_info(); - print_menu(); - break; - } -#endif -#ifdef HEATSEEK_FEATHER_WIFI_WICED - case 'a': { - wl_ap_info_t ap_list[20]; - int networkCount = 0; - networkCount = Feather.scanNetworks(ap_list, 20); - - Serial.println("========="); - Serial.print("Found "); Serial.print(networkCount); Serial.println(" Networks"); - - for (int i = 0; i < networkCount; i++) { - Serial.println("========="); - wl_ap_info_t ap = ap_list[i]; - Serial.print("SSID: "); Serial.println(ap.ssid); - Serial.print("RSSI: "); Serial.println(ap.rssi); - Serial.print("max data rate: "); Serial.println(ap.max_data_rate); - Serial.print("network type: "); Serial.println(ap.network_type); - Serial.print("security: "); Serial.print(ap.security); Serial.print(" - "); Serial.println(get_encryption_str(ap.security)); - Serial.print("channel: "); Serial.println(ap.channel); - Serial.print("band_2_4ghz: "); Serial.println(ap.band_2_4ghz); - } - - break; - } -#endif -#ifdef HEATSEEK_FEATHER_WIFI_M0 - case 'a': { - int networkCount = -1; - WiFi.setPins(8, 7, 4, 2); - networkCount = WiFi.scanNetworks(); - - Serial.println("========="); - Serial.print("Found "); Serial.print(networkCount); Serial.println(" Networks"); - - for (int i = 0; i < networkCount; i++) { - Serial.println("========="); - Serial.print("SSID: "); Serial.println(WiFi.SSID(i)); - Serial.print("RSSI: "); Serial.println(WiFi.RSSI(i)); - Serial.print("security: "); - switch (WiFi.encryptionType(i)) { - case ENC_TYPE_WEP: - Serial.println("WEP"); - case ENC_TYPE_TKIP: - Serial.println("WPA"); - case ENC_TYPE_CCMP: - Serial.println("WPA2"); - case ENC_TYPE_NONE: - Serial.println("None"); - case ENC_TYPE_AUTO: - Serial.println("Auto"); - } - } - print_menu(); - break; - } -#endif - case 'i': { - char buffer[200]; - int length; - -// hub is now always set to 'featherhub' -// length = read_input_until_newline("Enter HUB ID", buffer); -// buffer[length] = '\0'; -// strcpy(CONFIG.data.hub_id, buffer); - - length = read_input_until_newline("Enter CELL ID", buffer); - buffer[length] = '\0'; - strcpy(CONFIG.data.cell_id, buffer); - - CONFIG.data.cell_configured = 1; - write_config(); - - Serial.println("Cell ID Configured"); - print_config_info(); - print_menu(); - break; - } - case 'e': { - char buffer[200]; - int length; - - length = read_input_until_newline("Enter domain of API endpoint (Example: 'heatseek.org')", buffer); - buffer[length] = '\0'; - strcpy(CONFIG.data.endpoint_domain, buffer); - - length = read_input_until_newline("Enter path of API endpoint (Example: '/readings/create')", buffer); - buffer[length] = '\0'; - strcpy(CONFIG.data.endpoint_path, buffer); - - CONFIG.data.endpoint_configured = 1; - write_config(); - - Serial.println("API Endpoint configured"); - print_config_info(); - print_menu(); - break; - } - case 'd': { - Serial.println("reseting config"); - set_default_config(); - write_config(); - - print_config_info(); - print_menu(); - break; - } - case 'p': { - Serial.println("print config info"); - print_config_info(); - break; - } - case 's': { - Serial.println("exiting config"); - return; - } - case 'v': { - char buffer[200]; - int length; - float current_temp; - int readings_taken = 0; - float temperature_f; - float average_temperature_f = 0.0; - - length = read_input_until_newline("Enter current temperature, in fahrenheit, with one decimal place. For example: '41.0'. PLEASE ENSURE THAT SENSOR IS ON FOR APPROX. 5 MINUTES BEFORE CALIBRATING!", buffer); - buffer[length] = '\0'; - current_temp = strtof(buffer, NULL); - - while (readings_taken < 5) { - watchdog_feed(); - Serial.println("Calibrating, please wait..."); - temperature_f = dht.readTemperature(true); - - if (!isnan(temperature_f)) { - if (average_temperature_f == 0.0) { - average_temperature_f = temperature_f; - } else { - average_temperature_f = (average_temperature_f + temperature_f) / 2; - } - } else { - Serial.println("Failed to read temperature sensor; reboot device and try again."); - while(true); - } - - watchdog_feed(); - readings_taken++; - delay(2000); - } - - watchdog_feed(); - - float temperature_offset = current_temp - average_temperature_f; - CONFIG.data.temperature_offset_f = temperature_offset; - write_config(); - - Serial.print("Temperature offset set to: "); - Serial.println(temperature_offset); - - print_config_info(); - print_menu(); - break; - } - } - - watchdog_feed(); - delay(50); - } -} - -uint32_t get_last_reading_time() { - File reading_time_file; - uint8_t data[4]; - - if (reading_time_file = SD.open("time.bin", FILE_READ)) { - reading_time_file.read(data, sizeof(data)); - reading_time_file.close(); - } else { - Serial.println("unable to read last reading time"); - return 0; - } - - return data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); -} - -void update_last_reading_time(uint32_t timestamp) { - uint8_t data[4]; - - data[0] = (timestamp & 0x000000ff); - data[1] = (timestamp & 0x0000ff00) >> 8; - data[2] = (timestamp & 0x00ff0000) >> 16; - data[3] = (timestamp & 0xff000000) >> 24; - - File reading_time_file; - - if (reading_time_file = SD.open("time.bin", FILE_WRITE | O_TRUNC)) { - reading_time_file.write(data, sizeof(data)); - reading_time_file.close(); - } else { - Serial.println("unable to update last reading time"); - while(true); // watchdog will reboot - } - - Serial.println("updated last reading time"); -} - -#ifdef HEATSEEK_FEATHER_WIFI_WICED -char const* get_encryption_str(int32_t enc_type) -{ - // read the encryption type and print out the name: - switch (enc_type) - { - case ENC_TYPE_AUTO: return "ENC_TYPE_AUTO"; - case ENC_TYPE_OPEN: return "ENC_TYPE_OPEN"; - case ENC_TYPE_WEP: return "ENC_TYPE_WEP"; - case ENC_TYPE_WEP_SHARED: return "ENC_TYPE_WEP_SHARED"; - case ENC_TYPE_WPA_TKIP: return "ENC_TYPE_WPA_TKIP"; - case ENC_TYPE_WPA_AES: return "ENC_TYPE_WPA_AES"; - case ENC_TYPE_WPA_MIXED: return "ENC_TYPE_WPA_MIXED"; - case ENC_TYPE_WPA2_AES: return "ENC_TYPE_WPA2_AES"; - case ENC_TYPE_WPA2_TKIP: return "ENC_TYPE_WPA2_TKIP"; - case ENC_TYPE_WPA2_MIXED: return "ENC_TYPE_WPA2_MIXED"; - case ENC_TYPE_WPA_TKIP_ENT: return "ENC_TYPE_WPA_TKIP_ENT"; - case ENC_TYPE_WPA_AES_ENT: return "ENC_TYPE_WPA_AES_ENT"; - case ENC_TYPE_WPA_MIXED_ENT: return "ENC_TYPE_WPA_MIXED_ENT"; - case ENC_TYPE_WPA2_TKIP_ENT: return "ENC_TYPE_WPA2_TKIP_ENT"; - case ENC_TYPE_WPA2_AES_ENT: return "ENC_TYPE_WPA2_AES_ENT"; - case ENC_TYPE_WPA2_MIXED_ENT: return "ENC_TYPE_WPA2_MIXED_ENT"; - case ENC_TYPE_WPS_OPEN: return "ENC_TYPE_WPS_OPEN"; - case ENC_TYPE_WPS_SECURE: return "ENC_TYPE_WPS_SECURE"; - case ENC_TYPE_IBSS_OPEN: return "ENC_TYPE_IBSS_OPEN"; - default: return "UNKNOWN"; - } -} -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/config.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/config.h deleted file mode 100644 index 1a10ad2..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/config.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef CONFIG_H -#define CONFIG_H - -#define CONFIG_VERSION 6 - -typedef struct { - uint16_t version; - int32_t reading_interval_s; - - float temperature_offset_f; - - uint8_t cell_configured; - char hub_id[50]; - char cell_id[50]; - - uint8_t wifi_configured; - char wifi_ssid[50]; - char wifi_pass[200]; - - uint8_t endpoint_configured; - char endpoint_domain[100]; - char endpoint_path[100]; -} CONFIG_struct; - -typedef union { - CONFIG_struct data; - uint8_t raw[sizeof(CONFIG_struct)]; -} CONFIG_union; - -extern CONFIG_union CONFIG; - -void write_config(); -bool read_config(); -void set_default_config(); -void enter_configuration(); -uint32_t get_last_reading_time(); -void update_last_reading_time(uint32_t timestamp); - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.cpp deleted file mode 100644 index bc4d8eb..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.cpp +++ /dev/null @@ -1,178 +0,0 @@ -/******************************************************/ -// THIS IS A GENERATED FILE - DO NOT EDIT // -/******************************************************/ - -#include "application.h" -#line 1 "/Users/shrutiverma/feather_sensor/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.ino" -#include -#include -#include -#include -#include "user_config.h" -#include "transmit.h" -#include "config.h" -#include "watchdog.h" -#include "rtc.h" - -void setup(); -void loop(); -void read_temperatures(float *temperature_f, float *humidity, float *heat_index); -void log_to_sd(float temperature_f, float humidity, float heat_index, uint32_t current_time); -void initialize_sd(); -#line 11 "/Users/shrutiverma/feather_sensor/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.ino" -static DHT dht(DHT_DATA, DHT22); -uint32_t startup_millis = 0; - -void setup() { - watchdog_init(); - - Serial.begin(9600); - delay(2000); - - Serial.print("initializing heatseek data logger: "); - #ifdef TRANSMITTER_WIFI - Serial.println("WIFI"); - #else - Serial.println("cellular"); - #endif - - initialize_sd(); - rtc_initialize(); - - dht.begin(); - - if (!read_config()) set_default_config(); - - watchdog_feed(); - - startup_millis = millis(); -} - -void loop() { - float temperature_f; - float humidity; - float heat_index; - - int32_t current_time = rtc.now().unixtime(); - int32_t last_reading_time = get_last_reading_time(); - int32_t time_since_last_reading = current_time - last_reading_time; - - char command = Serial.read(); - if (command == 'C') { - enter_configuration(); - } - - Serial.print("Time since last reading: "); - Serial.print(time_since_last_reading); - Serial.print(", reading_interval: "); - Serial.print(CONFIG.data.reading_interval_s); - Serial.print(". Code version: "); - Serial.print(CODE_VERSION); - Serial.println(". Press 'C' to enter config."); - - if (millis() - startup_millis < 15000) { - Serial.println("Allowing 15 seconds to enter config mode [C] before taking first reading."); - watchdog_feed(); - delay(2000); - return; - } - - if (CONFIG.data.reading_interval_s - time_since_last_reading > SEND_SAVED_READINGS_THRESHOLD) { - Serial.println("Checking for queued temperature readings"); - watchdog_feed(); - transmit_queued_temps(); - delay(2000); - watchdog_feed(); - return; - } else if (time_since_last_reading < CONFIG.data.reading_interval_s) { - delay(2000); - watchdog_feed(); - return; - } - - watchdog_feed(); - - read_temperatures(&temperature_f, &humidity, &heat_index); - log_to_sd(temperature_f, humidity, heat_index, current_time); - - watchdog_feed(); - - update_last_reading_time(current_time); - watchdog_feed(); - - transmit(temperature_f, humidity, heat_index, current_time); - - watchdog_feed(); - - delay(2000); -} - -void read_temperatures(float *temperature_f, float *humidity, float *heat_index) { - while (true) { - bool success = true; - - *temperature_f = dht.readTemperature(true); - *humidity = dht.readHumidity(); - - if (!isnan(*temperature_f) && !isnan(*humidity)) { - Serial.print("Temperature (actual reading): "); - Serial.print(*temperature_f); - Serial.println(" *F"); - - *temperature_f = *temperature_f + CONFIG.data.temperature_offset_f; - Serial.print("Temperature (after calibration): "); - Serial.print(*temperature_f); - Serial.println(" *F"); - - Serial.print("Humidity: "); - Serial.print(*humidity); - Serial.println("%"); - - *heat_index = dht.computeHeatIndex(*temperature_f, *humidity); - - Serial.print("Heat index: "); - Serial.println(*heat_index); - - return; - - } else { - Serial.println("Error reading temperatures!"); - } - - delay(2000); - - // if we continue to fail to read a temperature, the watchdog will - // eventually cause a reboot - } -} - -void log_to_sd(float temperature_f, float humidity, float heat_index, uint32_t current_time) { - Serial.println("writing to SD card..."); - - File data_file; - - if (data_file = SD.open("data.csv", FILE_WRITE)) { - data_file.print(current_time); data_file.print(","); - data_file.print(temperature_f); data_file.print(","); - data_file.print(humidity); data_file.print(","); - data_file.print(heat_index); data_file.println(); - Serial.println("wrote to SD"); - data_file.close(); - } else { - Serial.println("unable to open data.csv"); - while(true); // watchdog will reboot - } -} - -void initialize_sd() { - // Stop LORA module from interfering with SPI - #ifdef TRANSMITTER_GSM - pinMode(LORA_CS, OUTPUT); - digitalWrite(LORA_CS, HIGH); - #endif - - while (!SD.begin(SD_CS)) { - Serial.println("failed to initialize SD card"); - delay(1000); // watchdog will reboot - } -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.ino b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.ino deleted file mode 100644 index 4f28524..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/feather_sensor_transmit_lte.ino +++ /dev/null @@ -1,166 +0,0 @@ -#include -#include -#include -#include -#include "user_config.h" -#include "transmit.h" -#include "config.h" -#include "watchdog.h" -#include "rtc.h" - -static DHT dht(DHT_DATA, DHT22); -uint32_t startup_millis = 0; - -void setup() { - watchdog_init(); - - Serial.begin(9600); - delay(2000); - - Serial.print("initializing heatseek data logger: "); - #ifdef TRANSMITTER_WIFI - Serial.println("WIFI"); - #else - Serial.println("cellular"); - #endif - - initialize_sd(); - rtc_initialize(); - - dht.begin(); - - if (!read_config()) set_default_config(); - - watchdog_feed(); - - startup_millis = millis(); -} - -void loop() { - float temperature_f; - float humidity; - float heat_index; - - int32_t current_time = rtc.now().unixtime(); - int32_t last_reading_time = get_last_reading_time(); - int32_t time_since_last_reading = current_time - last_reading_time; - - char command = Serial.read(); - if (command == 'C') { - enter_configuration(); - } - - Serial.print("Time since last reading: "); - Serial.print(time_since_last_reading); - Serial.print(", reading_interval: "); - Serial.print(CONFIG.data.reading_interval_s); - Serial.print(". Code version: "); - Serial.print(CODE_VERSION); - Serial.println(". Press 'C' to enter config."); - - if (millis() - startup_millis < 15000) { - Serial.println("Allowing 15 seconds to enter config mode [C] before taking first reading."); - watchdog_feed(); - delay(2000); - return; - } - - if (CONFIG.data.reading_interval_s - time_since_last_reading > SEND_SAVED_READINGS_THRESHOLD) { - Serial.println("Checking for queued temperature readings"); - watchdog_feed(); - transmit_queued_temps(); - delay(2000); - watchdog_feed(); - return; - } else if (time_since_last_reading < CONFIG.data.reading_interval_s) { - delay(2000); - watchdog_feed(); - return; - } - - watchdog_feed(); - - read_temperatures(&temperature_f, &humidity, &heat_index); - log_to_sd(temperature_f, humidity, heat_index, current_time); - - watchdog_feed(); - - update_last_reading_time(current_time); - watchdog_feed(); - - transmit(temperature_f, humidity, heat_index, current_time); - - watchdog_feed(); - - delay(2000); -} - -void read_temperatures(float *temperature_f, float *humidity, float *heat_index) { - while (true) { - bool success = true; - - *temperature_f = dht.readTemperature(true); - *humidity = dht.readHumidity(); - - if (!isnan(*temperature_f) && !isnan(*humidity)) { - Serial.print("Temperature (actual reading): "); - Serial.print(*temperature_f); - Serial.println(" *F"); - - *temperature_f = *temperature_f + CONFIG.data.temperature_offset_f; - Serial.print("Temperature (after calibration): "); - Serial.print(*temperature_f); - Serial.println(" *F"); - - Serial.print("Humidity: "); - Serial.print(*humidity); - Serial.println("%"); - - *heat_index = dht.computeHeatIndex(*temperature_f, *humidity); - - Serial.print("Heat index: "); - Serial.println(*heat_index); - - return; - - } else { - Serial.println("Error reading temperatures!"); - } - - delay(2000); - - // if we continue to fail to read a temperature, the watchdog will - // eventually cause a reboot - } -} - -void log_to_sd(float temperature_f, float humidity, float heat_index, uint32_t current_time) { - Serial.println("writing to SD card..."); - - File data_file; - - if (data_file = SD.open("data.csv", FILE_WRITE)) { - data_file.print(current_time); data_file.print(","); - data_file.print(temperature_f); data_file.print(","); - data_file.print(humidity); data_file.print(","); - data_file.print(heat_index); data_file.println(); - Serial.println("wrote to SD"); - data_file.close(); - } else { - Serial.println("unable to open data.csv"); - while(true); // watchdog will reboot - } -} - -void initialize_sd() { - // Stop LORA module from interfering with SPI - #ifdef TRANSMITTER_GSM - pinMode(LORA_CS, OUTPUT); - digitalWrite(LORA_CS, HIGH); - #endif - - while (!SD.begin(SD_CS)) { - Serial.println("failed to initialize SD card"); - delay(1000); // watchdog will reboot - } -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/rtc.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/rtc.cpp deleted file mode 100644 index 108127e..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/rtc.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include "rtc.h" -#include "watchdog.h" -#include "config.h" - -RTC_PCF8523 rtc; - -void rtc_initialize() { - if (!rtc.begin()) { - Serial.println("Couldn't find RTC"); - while (true); // watchdog will reboot - } - - if (!rtc.initialized()) { - Serial.print("RTC is NOT running! "); - Serial.println(rtc.now().unixtime()); - // TODO - this could make a web request to set and continually update the RTC - rtc_set(); - } -} - -void rtc_set() { - char timestamp[50]; - int i = 0; - bool timestamp_input = false; - uint32_t value = 0; - - while (true) { - Serial.println("Setting RTC, enter the current unix timestamp"); - - while (Serial.available()) { - char c = Serial.read(); - timestamp[i++] = c; - if (c == '\n') { timestamp_input = true; } - } - - if (timestamp_input) { - value = strtoul(timestamp, NULL, 0); - - // sanity check - if (value < 1810148331 && value > 1494614996) { - Serial.println("done setting"); - break; - } else { - Serial.println("The value you entered looks wrong - please try again"); - timestamp_input = false; - i = 0; - } - } - watchdog_feed(); - delay(2000); - } - - Serial.print("setting timestamp to: "); - Serial.println(value); - - rtc.adjust(DateTime(value)); - update_last_reading_time(0); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/rtc.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/rtc.h deleted file mode 100644 index 21befff..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/rtc.h +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef RTC_H -#define RTC_H - -#include - -extern RTC_PCF8523 rtc; - -void rtc_initialize(); -void rtc_set(); - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/transmit.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/transmit.cpp deleted file mode 100644 index 99ef317..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/transmit.cpp +++ /dev/null @@ -1,513 +0,0 @@ -#include "transmit.h" -#include "config.h" -#include "watchdog.h" -#include - -#ifdef HEATSEEK_BORON_LTE - TCPClient tcpClient; - bool lteConnected = false; -#endif - -#ifdef HEATSEEK_FEATHER_WIFI_WICED - AdafruitHTTP http; - bool wifiConnected = false; - volatile bool response_received = false; - volatile bool transmit_success = false; -#endif - -#ifdef HEATSEEK_FEATHER_WIFI_M0 - WiFiClient wifiClient; - bool wifiConnected = false; -#endif - -#ifdef TRANSMITTER_GSM - #include - - HardwareSerial *fonaSerial = &Serial1; - - Adafruit_FONA fona = Adafruit_FONA(FONA_RST); - bool gsmConnected = false; -#endif - -#ifdef TRANSMITTER_GSM - bool fona_post(float temperature_f, float humidity, float heat_index, uint32_t current_time) { - fona.HTTP_POST_end(); - - uint16_t statuscode; - int16_t length; - - char url[200]; - strcpy(url, CONFIG.data.endpoint_domain); - strcat(url, CONFIG.data.endpoint_path); - - char data[200]; - - char temperature_buffer[10]; - char humidity_buffer[10]; - char heat_index_buffer[10]; - - dtostrf(temperature_f, 4, 3, temperature_buffer); - dtostrf(humidity, 4, 3, humidity_buffer); - dtostrf(heat_index, 4, 3, heat_index_buffer); - - sprintf(data, "temp=%s&humidity=%s&heat_index=%s&hub=%s&cell=%s&time=%d&sp=%d&cell_version=%s", temperature_buffer, humidity_buffer, heat_index_buffer, CONFIG.data.hub_id, CONFIG.data.cell_id, current_time, CONFIG.data.reading_interval_s, CODE_VERSION); - - Serial.print("posting to: "); Serial.println(url); - Serial.print("with data: "); Serial.println(data); - - if (!fona.HTTP_POST_start(url, F("application/x-www-form-urlencoded"), (uint8_t *) data, strlen(data), &statuscode, (uint16_t *)&length)) { - return false; - } - - Serial.println("reading status"); - - if (statuscode != 200) { - Serial.print("status not 200: "); - Serial.println(statuscode); - return false; - } - - fona.HTTP_POST_end(); - return true; - } - - void connect_to_fona() { - Serial.println('starting fona serial'); - fonaSerial->begin(4800); - - Serial.println('starting fona serial 2'); - if (!fona.begin(*fonaSerial)) { - Serial.println("Couldn't find FONA"); - while(true); // watchdog will reboot - } - - watchdog_feed(); - delay(2000); - - Serial.println('enabling FONA GPRS'); - - uint32_t start = millis(); - - while (!fona.enableGPRS(true)) { - delay(1000); - watchdog_feed(); - - if (millis() - start > 60000) { - Serial.println("failed to start FONA GPRS after 60 sec"); - while (true); - } - } - - Serial.println("Enabled FONA GRPS"); - - gsmConnected = true; - } - - bool _transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time) { - if (!CONFIG.data.cell_configured || !CONFIG.data.endpoint_configured) { - Serial.println("cannot send data - not configured"); - return false; - } - - if (!gsmConnected) connect_to_fona(); - watchdog_feed(); - - int transmit_attempts = 1; - - while (!fona_post(temperature_f, humidity, heat_index, current_time)) { - Serial.print("failed to POST, trying again... attempt #"); - Serial.println(transmit_attempts); - - if (transmit_attempts < 4) { - transmit_attempts++; - watchdog_feed(); - delay(500); - } else { - while (true); - } - } - - return true; - } -#endif - -#ifdef HEATSEEK_FEATHER_WIFI_WICED - void force_wifi_reconnect(void) { - wifiConnected = false; - } - - void receive_callback(void) { - http.respParseHeader(); - int status_received = http.respStatus(); - - Serial.printf("transmitted - received status: (%d) \n", status_received); - - http.stop(); - response_received = true; - transmit_success = (status_received == 200); - } - - void connect_to_wifi() { - Serial.print("Please wait while connecting to:"); - Serial.print(CONFIG.data.wifi_ssid); - Serial.println("... "); - - if (Feather.connect(CONFIG.data.wifi_ssid, CONFIG.data.wifi_pass)) { - Serial.println("Connected!"); - wifiConnected = true; - } else { - Serial.printf("Failed! %s (%d) \n", Feather.errstr()); - } - Serial.println(); - - if (!Feather.connected()) { return; } - - // Connected: Print network info - Feather.printNetwork(); - - // Tell the HTTP client to auto print error codes and halt on errors - http.err_actions(true, true); - - // Set HTTP client verbose - http.verbose(true); - - // Set the callback handlers - http.setReceivedCallback(receive_callback); - } - - bool _transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time) { - if (!CONFIG.data.cell_configured || !CONFIG.data.wifi_configured || !CONFIG.data.endpoint_configured) { - Serial.println("cannot send data - not configured"); - return false; - } - - while (!wifiConnected) { connect_to_wifi(); } - - http.connect(CONFIG.data.endpoint_domain, PORT); // Will halt if an error occurs - - http.addHeader("User-Agent", USER_AGENT_HEADER); - http.addHeader("Connection", "close"); - http.addHeader("Content-Type", "application/x-www-form-urlencoded"); - - char time_buffer[30]; - char temperature_buffer[30]; - char humidity_buffer[30]; - char heat_index_buffer[30]; - char reading_interval_buffer[30]; - - sprintf(time_buffer, "%d", current_time); - sprintf(reading_interval_buffer, "%d", CONFIG.data.reading_interval_s); - sprintf(temperature_buffer, "%.3f", temperature_f); - sprintf(humidity_buffer, "%.3f", humidity); - sprintf(heat_index_buffer, "%.3f", heat_index); - - const char* post_data[][2] = - { - {"hub", CONFIG.data.hub_id}, - {"cell", CONFIG.data.cell_id}, - {"time", time_buffer}, - {"temp", temperature_buffer}, - {"humidity", humidity_buffer}, - {"sp", reading_interval_buffer}, - {"heat_index", heat_index_buffer}, - {"cell_version", CODE_VERSION}, - }; - int param_count = 8; - - response_received = false; - transmit_success = false; - - http.post(CONFIG.data.endpoint_domain, CONFIG.data.endpoint_path, post_data, param_count); // Will halt if an error occurs - - while (!response_received || !transmit_success); // Hang if transmit doesn't complete or fails - - return true; - } -#endif - -#ifdef HEATSEEK_FEATHER_WIFI_M0 - void force_wifi_reconnect(void) { - if (wifiConnected) { - wifiConnected = false; - WiFi.end(); - } - } - - void connect_to_wifi() { - WiFi.setPins(8, 7, 4, 2); - - Serial.print("Please wait while connecting to:"); - Serial.print(CONFIG.data.wifi_ssid); - Serial.println("... "); - - int status = WL_IDLE_STATUS; - - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(CONFIG.data.wifi_ssid, CONFIG.data.wifi_pass); - - while (status != WL_CONNECTED) { - delay(1000); - Serial.println("Establishing connection..."); - } - - wifiConnected = true; - Serial.println("Connected to WiFi"); - - Serial.print("SSID: "); - Serial.println(WiFi.SSID()); - - // print the received signal strength: - long rssi = WiFi.RSSI(); - Serial.print("signal strength (RSSI):"); - Serial.print(rssi); - Serial.println(" dBm"); - - watchdog_feed(); - } - - bool _transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time) { - if (!CONFIG.data.cell_configured || !CONFIG.data.wifi_configured || !CONFIG.data.endpoint_configured) { - Serial.println("cannot send data - not configured"); - return false; - } - - if (!wifiConnected) { connect_to_wifi(); } - - HttpClient client = HttpClient(wifiClient, CONFIG.data.endpoint_domain, 80); - - String contentType = "application/x-www-form-urlencoded"; - String data = "temp=" + String(temperature_f, 3) + "&humidity=" + String(humidity, 3) + "&heat_index=" + String(heat_index, 3) + "&hub=" + CONFIG.data.hub_id + "&cell=" + CONFIG.data.cell_id + "&time=" + current_time + "&sp=" + CONFIG.data.reading_interval_s + "&cell_version=" + CODE_VERSION; - - Serial.print("Posting data: "); - Serial.println(data); - - client.post(CONFIG.data.endpoint_path, contentType, data); - - int statusCode = client.responseStatusCode(); - String response = client.responseBody(); - - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - - return statusCode == 200; - } -#endif - -#ifdef HEATSEEK_BORON_LTE - // Function to reconnect to LTE? - void force_lte_reconnect(void); - - // Function to connect to Particle Cloud - void connect_to_lte(){ - // Configure the connection here. - Serial.println("Establishing connection..."); - // Connect to LTE network here. - Serial.println("Connected to LTE"); - watchdog_feed(); - } - - // Function to transmit - bool _transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time){ - // If cell / API endpoint not configured, indicate error - if (!CONFIG.data.cell_configured || !CONFIG.data.endpoint_configured) { - Serial.println("cannot send data - not configured"); - return false; - } - - // If not connected, connect - if(!lteConnected){ - connect_to_lte(); - } - - // Set up TCPClient - // Do some error checking - tcpClient.connect(CONFIG.data.endpoint_domain, 80); - String contentType = "application/x-www-form-urlencoded"; - String data = "temp=" + String(temperature_f, 3) + "&humidity=" + String(humidity, 3) + "&heat_index=" + String(heat_index, 3) + "&hub=" + CONFIG.data.hub_id + "&cell=" + CONFIG.data.cell_id + "&time=" + current_time + "&sp=" + CONFIG.data.reading_interval_s + "&cell_version=" + CODE_VERSION; - Serial.print("Posting data: "); - Serial.println(data); - tcpClient.println(data); - int statusCode = tcpClient.status(); - int numCharacters = tcpClient.available(); - String response = ""; - for (int i = 0; i < numCharacters; i++) - { - response += tcpClient.read(); - } - Serial.print("Status code: "); - Serial.println(statusCode); - Serial.print("Response: "); - Serial.println(response); - return statusCode == 200; - // Load data - // Post data via TCPClient - // Done. -} -#endif - -typedef struct { - float temperature_f; - float humidity; - float heat_index; -} temp_data_struct; - -typedef union { - temp_data_struct data; - uint8_t raw[sizeof(temp_data_struct)]; -} temp_data; - -// Create a file on the SD card representing a temperature reading -// The file name is the unix timestamp, however, due to FAT naming conventions, -// we have to place a period in it. e.g. 1500985299 -> 1500985.299 -// The content of the file is the binary reading data struct. -void queue_transmission(char *filename, temp_data temp, uint32_t current_time) { - char file_path[50]; - char timestamp[50]; - char timestamp_first_half[50]; - char timestamp_last_half[50]; - - // FAT only allows 8 character names, so we make the last 3 digits of the - // timestamp the file "extension" - sprintf(timestamp, "%d", current_time); - strncpy(timestamp_first_half, timestamp, 7); - timestamp_first_half[7] = '\0'; - strncpy(timestamp_last_half, timestamp+7, 3); - timestamp_last_half[3] = '\0'; - - sprintf(filename, "%s.%s", timestamp_first_half, timestamp_last_half); - sprintf(file_path, "pending/%s", filename); - - File temperature_file; - SD.mkdir("pending"); - if (temperature_file = SD.open(file_path, FILE_WRITE | O_TRUNC)) { - temperature_file.write(temp.raw, sizeof(temp)); - temperature_file.close(); - } else { - Serial.println("unable to write temperature"); - while(true); // watchdog will reboot - } -} - -// Take a filename for a reading, read the temperature data and -// transmit it. Then delete the file when the transfer is successful. -void transmit_queued_temp(char *filename) { - watchdog_feed(); - - File temperature_file; - temp_data temperature; - char read_time_buffer[100]; - char file_path[100]; - sprintf(file_path, "pending/%s", filename); - - Serial.print("transfering: "); - Serial.println(filename); - - strncpy(read_time_buffer, filename, 7); - strncpy(read_time_buffer+7, filename+8, 3); - read_time_buffer[10] = '\0'; - - uint32_t read_time = strtoul(read_time_buffer, NULL, 0); - - if (temperature_file = SD.open(file_path, FILE_READ)) { - int read_size = temperature_file.read(temperature.raw, sizeof(temperature)); - - if (sizeof(temperature) == read_size) { - bool transmit_success = _transmit(temperature.data.temperature_f, temperature.data.humidity, temperature.data.heat_index, read_time); - - temperature_file.close(); - delay(100); - - if (transmit_success) { - Serial.println("transferred."); - - if (SD.remove(file_path)) { - Serial.println("removed."); - } else { - Serial.println("failed to remove file"); - } - } else { - Serial.println("failed to transfer"); - } - } else { - Serial.print("file incorrect size - expected: "); - Serial.print(sizeof(temperature)); - Serial.print(", got: "); - Serial.println(read_size); - } - } else { - Serial.print("failed to open: "); - Serial.println(filename); - } - - watchdog_feed(); -} - -void transmit_queued_temps() { - char filename[100]; - File pending_dir = SD.open("pending"); - int temps_transfered_count = 0; - - while (temps_transfered_count < TRANSMITS_PER_LOOP) { - File entry = pending_dir.openNextFile(); - if (!entry) { break; } // No more files - - strcpy(filename, entry.name()); - entry.close(); - - transmit_queued_temp(filename); - temps_transfered_count += 1; - } - - pending_dir.close(); -} - -void clear_queued_transmissions() { - File pending_dir = SD.open("pending"); - - Serial.println("==== Removing queued temperature files"); - while (true) { - watchdog_feed(); - - File entry = pending_dir.openNextFile(); - if (!entry) { break; } // No more files - - char filename[100]; - strcpy(filename, entry.name()); - entry.close(); - - char file_path[100]; - sprintf(file_path, "pending/%s", filename); - - if (SD.remove(file_path)) { - Serial.println("removed queued temperature file."); - } else { - Serial.println("failed to remove queued temperature file."); - } - } - - Serial.println("===="); - - pending_dir.close(); -} - -void transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time) { - watchdog_feed(); - - temp_data temp; - temp.data.temperature_f = temperature_f; - temp.data.humidity = humidity; - temp.data.heat_index = heat_index; - - char filename[100]; - queue_transmission(filename, temp, current_time); - watchdog_feed(); - delay(1000); - - Serial.print("created file: "); - Serial.println(filename); - - transmit_queued_temp(filename); - transmit_queued_temps(); -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/transmit.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/transmit.h deleted file mode 100644 index a817d47..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/transmit.h +++ /dev/null @@ -1,58 +0,0 @@ -#ifndef TRANSMIT_H -#define TRANSMIT_H - -#define CODE_VERSION "F-1.2.0" - -#include "user_config.h" - -#ifdef HEATSEEK_FEATHER_CELL_M0 - #define TRANSMITTER_GSM -#else - #define TRANSMITTER_WIFI -#endif - -#ifdef HEATSEEK_FEATHER_WIFI_WICED - #include - #include - #include - - #define DHT_DATA PC2 - #define SD_CS PB4 - - #define TRANSMITS_PER_LOOP 20 -#endif - -#ifdef HEATSEEK_FEATHER_WIFI_M0 - #include - #include - - #define DHT_DATA A2 - #define SD_CS 10 - - #define TRANSMITS_PER_LOOP 20 -#endif - -#ifdef TRANSMITTER_GSM - #include "Adafruit_FONA.h" - #include - - #define DHT_DATA A2 - #define SD_CS 10 - #define FONA_RST A4 - #define LORA_CS 8 - - #define TRANSMITS_PER_LOOP 5 -#endif - -#define SEND_SAVED_READINGS_THRESHOLD (10 * 60) -#define USER_AGENT_HEADER "curl/7.45.0" -#define PORT 80 - -void transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time); -void transmit_queued_temps(); -void clear_queued_transmissions(); -#ifdef TRANSMITTER_WIFI -void force_wifi_reconnect(); -#endif - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/user_config.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/user_config.h deleted file mode 100644 index 6011268..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/user_config.h +++ /dev/null @@ -1,4 +0,0 @@ -//#define HEATSEEK_FEATHER_CELL_M0 -//#define HEATSEEK_FEATHER_WIFI_M0 -#define HEATSEEK_BORON_LTE -//#define HEATSEEK_FEATHER_WIFI_WICED diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/watchdog.cpp b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/watchdog.cpp deleted file mode 100644 index 090b286..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/watchdog.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "watchdog.h" - -#if defined(HEATSEEK_FEATHER_WIFI_M0) || defined(TRANSMITTER_GSM) - #include -#endif - -void watchdog_init() { - #ifdef HEATSEEK_FEATHER_WIFI_WICED - iwdg_init(IWDG_PRE_256, 3500); // 30 second watchdog, 40kHz processor - #endif - - #if defined(HEATSEEK_FEATHER_WIFI_M0) || defined(TRANSMITTER_GSM) - Watchdog.enable(16000); // 16 seconds (this is the max supported) - #endif -} - -void watchdog_feed() { - #ifdef HEATSEEK_FEATHER_WIFI_WICED - iwdg_feed(); - #endif - - #if defined(HEATSEEK_FEATHER_WIFI_M0) || defined(TRANSMITTER_GSM) - Watchdog.reset(); - #endif -} diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/watchdog.h b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/watchdog.h deleted file mode 100644 index 7acb4e3..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/src/watchdog.h +++ /dev/null @@ -1,9 +0,0 @@ -#ifndef WATCHDOG_H -#define WATCHDOG_H - -#include "transmit.h" - -void watchdog_init(); -void watchdog_feed(); - -#endif diff --git a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/target/1.1.0/boron/module_user_memory.ld b/feather_sensor_transmit_lte/feather_sensor_transmit_lte/target/1.1.0/boron/module_user_memory.ld deleted file mode 100644 index a348d59..0000000 --- a/feather_sensor_transmit_lte/feather_sensor_transmit_lte/target/1.1.0/boron/module_user_memory.ld +++ /dev/null @@ -1,4 +0,0 @@ -user_module_app_flash_origin = 0xD4000; -user_module_app_flash_length = 128K; - -user_module_sram_length = 96K; diff --git a/transmit.cpp b/transmit.cpp index 3fdd5f5..5990b49 100644 --- a/transmit.cpp +++ b/transmit.cpp @@ -3,11 +3,6 @@ #include "watchdog.h" #include -#ifdef HEATSEEK_BORON_LTE - TCPClient tcpClient; - Bool lteConnected = false; -#endif - #ifdef HEATSEEK_FEATHER_WIFI_WICED AdafruitHTTP http; bool wifiConnected = false; @@ -295,42 +290,6 @@ } #endif -#ifdef HEATSEEK_BORON_LTE - // Function to reconnect to LTE? - void force_lte_reconnect(void); - - // Function to connect to Particle Cloud - void connect_to_lte(){ - // Configure the connection here. - Serial.println(“Establishing connection...”); - // Connect to LTE network here. - Serial.println(“Connected to LTE”); - watchdog_feed(); - } - - // Function to transmit - bool _transmit(float temperature_f, float humidity, float heat_index, uint32_t current_time){ - // If cell / API endpoint not configured, indicate error - if (!CONFIG.data.cell_configured || !CONFIG.data.endpoint_configured) { - Serial.println("cannot send data - not configured"); - return false; - } - - // If not connected, connect - if(!lteConnected){ - connect_to_lte(); - } - - // Set up TCPClient - // Do some error checking - client.connect(CONFIG.data.endpoint_domain, 80); - // Load contenttype - // Load data - // Post data via TCPClient - // Done. -} -#endif - typedef struct { float temperature_f; float humidity; diff --git a/user_config.h b/user_config.h index 6011268..57fbb6a 100644 --- a/user_config.h +++ b/user_config.h @@ -1,4 +1,3 @@ //#define HEATSEEK_FEATHER_CELL_M0 -//#define HEATSEEK_FEATHER_WIFI_M0 -#define HEATSEEK_BORON_LTE +#define HEATSEEK_FEATHER_WIFI_M0 //#define HEATSEEK_FEATHER_WIFI_WICED